1 // Currently, rust warns when an unsafe fn contains an unsafe {} block. However,
2 // in the future, this will change to the reverse. For now, suppress this
3 // warning and generally stick with being explicit about unsafety.
4 #![allow(unused_unsafe)]
5 #![cfg_attr(not(feature = "rt"), allow(dead_code))]
10 pub(self) use self::entry
::{EntryList, TimerEntry, TimerHandle, TimerShared}
;
13 pub(crate) use self::handle
::Handle
;
19 use crate::loom
::sync
::atomic
::{AtomicBool, Ordering}
;
20 use crate::loom
::sync
::{Arc, Mutex}
;
21 use crate::park
::{Park, Unpark}
;
22 use crate::time
::error
::Error
;
23 use crate::time
::{Clock, Duration, Instant}
;
25 use std
::convert
::TryInto
;
27 use std
::{num::NonZeroU64, ptr::NonNull, task::Waker}
;
29 /// Time implementation that drives [`Sleep`][sleep], [`Interval`][interval], and [`Timeout`][timeout].
31 /// A `Driver` instance tracks the state necessary for managing time and
32 /// notifying the [`Sleep`][sleep] instances once their deadlines are reached.
34 /// It is expected that a single instance manages many individual [`Sleep`][sleep]
35 /// instances. The `Driver` implementation is thread-safe and, as such, is able
36 /// to handle callers from across threads.
38 /// After creating the `Driver` instance, the caller must repeatedly call `park`
39 /// or `park_timeout`. The time driver will perform no work unless `park` or
40 /// `park_timeout` is called repeatedly.
42 /// The driver has a resolution of one millisecond. Any unit of time that falls
43 /// between milliseconds are rounded up to the next millisecond.
45 /// When an instance is dropped, any outstanding [`Sleep`][sleep] instance that has not
46 /// elapsed will be notified with an error. At this point, calling `poll` on the
47 /// [`Sleep`][sleep] instance will result in panic.
51 /// The time driver is based on the [paper by Varghese and Lauck][paper].
53 /// A hashed timing wheel is a vector of slots, where each slot handles a time
54 /// slice. As time progresses, the timer walks over the slot for the current
55 /// instant, and processes each entry for that slot. When the timer reaches the
56 /// end of the wheel, it starts again at the beginning.
58 /// The implementation maintains six wheels arranged in a set of levels. As the
59 /// levels go up, the slots of the associated wheel represent larger intervals
60 /// of time. At each level, the wheel has 64 slots. Each slot covers a range of
61 /// time equal to the wheel at the lower level. At level zero, each slot
62 /// represents one millisecond of time.
66 /// * Level 0: 64 x 1 millisecond slots.
67 /// * Level 1: 64 x 64 millisecond slots.
68 /// * Level 2: 64 x ~4 second slots.
69 /// * Level 3: 64 x ~4 minute slots.
70 /// * Level 4: 64 x ~4 hour slots.
71 /// * Level 5: 64 x ~12 day slots.
73 /// When the timer processes entries at level zero, it will notify all the
74 /// `Sleep` instances as their deadlines have been reached. For all higher
75 /// levels, all entries will be redistributed across the wheel at the next level
76 /// down. Eventually, as time progresses, entries with [`Sleep`][sleep] instances will
77 /// either be canceled (dropped) or their associated entries will reach level
78 /// zero and be notified.
80 /// [paper]: http://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-wheels.pdf
81 /// [sleep]: crate::time::Sleep
82 /// [timeout]: crate::time::Timeout
83 /// [interval]: crate::time::Interval
85 pub(crate) struct Driver
<P
: Park
+ '
static> {
86 /// Timing backend in use
87 time_source
: ClockTime
,
92 /// Parker to delegate to
95 // When `true`, a call to `park_timeout` should immediately return and time
96 // should not advance. One reason for this to be `true` is if the task
97 // passed to `Runtime::block_on` called `task::yield_now()`.
99 // While it may look racy, it only has any effect when the clock is paused
100 // and pausing the clock is restricted to a single-threaded runtime.
101 #[cfg(feature = "test-util")]
102 did_wake
: Arc
<AtomicBool
>,
105 /// A structure which handles conversion from Instants to u64 timestamps.
106 #[derive(Debug, Clone)]
107 pub(self) struct ClockTime
{
108 clock
: super::clock
::Clock
,
113 pub(self) fn new(clock
: Clock
) -> Self {
115 start_time
: clock
.now(),
120 pub(self) fn deadline_to_tick(&self, t
: Instant
) -> u64 {
121 // Round up to the end of a ms
122 self.instant_to_tick(t
+ Duration
::from_nanos(999_999))
125 pub(self) fn instant_to_tick(&self, t
: Instant
) -> u64 {
127 let dur
: Duration
= t
128 .checked_duration_since(self.start_time
)
129 .unwrap_or_else(|| Duration
::from_secs(0));
130 let ms
= dur
.as_millis();
132 ms
.try_into().expect("Duration too far into the future")
135 pub(self) fn tick_to_duration(&self, t
: u64) -> Duration
{
136 Duration
::from_millis(t
)
139 pub(self) fn now(&self) -> u64 {
140 self.instant_to_tick(self.clock
.now())
144 /// Timer state shared between `Driver`, `Handle`, and `Registration`.
146 // The state is split like this so `Handle` can access `is_shutdown` without locking the mutex
147 pub(super) state
: Mutex
<InnerState
>,
149 /// True if the driver is being shutdown
150 pub(super) is_shutdown
: AtomicBool
,
153 /// Time state shared which must be protected by a `Mutex`
155 /// Timing backend in use
156 time_source
: ClockTime
,
158 /// The last published timer `elapsed` value.
161 /// The earliest time at which we promise to wake up without unparking
162 next_wake
: Option
<NonZeroU64
>,
167 /// Unparker that can be used to wake the time driver
168 unpark
: Box
<dyn Unpark
>,
171 // ===== impl Driver =====
177 /// Creates a new `Driver` instance that uses `park` to block the current
178 /// thread and `time_source` to get the current time and convert to ticks.
180 /// Specifying the source of time is useful when testing.
181 pub(crate) fn new(park
: P
, clock
: Clock
) -> Driver
<P
> {
182 let time_source
= ClockTime
::new(clock
);
184 let inner
= Inner
::new(time_source
.clone(), Box
::new(park
.unpark()));
188 handle
: Handle
::new(Arc
::new(inner
)),
190 #[cfg(feature = "test-util")]
191 did_wake
: Arc
::new(AtomicBool
::new(false)),
195 /// Returns a handle to the timer.
197 /// The `Handle` is how `Sleep` instances are created. The `Sleep` instances
198 /// can either be created directly or the `Handle` instance can be passed to
199 /// `with_default`, setting the timer as the default timer for the execution
201 pub(crate) fn handle(&self) -> Handle
{
205 fn park_internal(&mut self, limit
: Option
<Duration
>) -> Result
<(), P
::Error
> {
206 let mut lock
= self.handle
.get().state
.lock();
208 assert
!(!self.handle
.is_shutdown());
210 let next_wake
= lock
.wheel
.next_expiration_time();
212 next_wake
.map(|t
| NonZeroU64
::new(t
).unwrap_or_else(|| NonZeroU64
::new(1).unwrap()));
218 let now
= self.time_source
.now();
219 // Note that we effectively round up to 1ms here - this avoids
220 // very short-duration microsecond-resolution sleeps that the OS
221 // might treat as zero-length.
222 let mut duration
= self.time_source
.tick_to_duration(when
.saturating_sub(now
));
224 if duration
> Duration
::from_millis(0) {
225 if let Some(limit
) = limit
{
226 duration
= std
::cmp
::min(limit
, duration
);
229 self.park_timeout(duration
)?
;
231 self.park
.park_timeout(Duration
::from_secs(0))?
;
235 if let Some(duration
) = limit
{
236 self.park_timeout(duration
)?
;
243 // Process pending timers after waking up
244 self.handle
.process();
250 fn park_timeout(&mut self, duration
: Duration
) -> Result
<(), P
::Error
> {
251 let clock
= &self.time_source
.clock
;
253 if clock
.is_paused() {
254 self.park
.park_timeout(Duration
::from_secs(0))?
;
256 // If the time driver was woken, then the park completed
257 // before the "duration" elapsed (usually caused by a
258 // yield in `Runtime::block_on`). In this case, we don't
259 // advance the clock.
260 if !self.did_wake() {
261 // Simulate advancing time
262 clock
.advance(duration
);
265 self.park
.park_timeout(duration
)?
;
271 fn did_wake(&self) -> bool
{
272 self.did_wake
.swap(false, Ordering
::SeqCst
)
277 fn park_timeout(&mut self, duration
: Duration
) -> Result
<(), P
::Error
> {
278 self.park
.park_timeout(duration
)
284 /// Runs timer related logic, and returns the next wakeup time
285 pub(self) fn process(&self) {
286 let now
= self.time_source().now();
288 self.process_at_time(now
)
291 pub(self) fn process_at_time(&self, now
: u64) {
292 let mut waker_list
: [Option
<Waker
>; 32] = Default
::default();
293 let mut waker_idx
= 0;
295 let mut lock
= self.get().lock();
297 assert
!(now
>= lock
.elapsed
);
299 while let Some(entry
) = lock
.wheel
.poll(now
) {
300 debug_assert
!(unsafe { entry.is_pending() }
);
302 // SAFETY: We hold the driver lock, and just removed the entry from any linked lists.
303 if let Some(waker
) = unsafe { entry.fire(Ok(())) }
{
304 waker_list
[waker_idx
] = Some(waker
);
308 if waker_idx
== waker_list
.len() {
309 // Wake a batch of wakers. To avoid deadlock, we must do this with the lock temporarily dropped.
312 for waker
in waker_list
.iter_mut() {
313 waker
.take().unwrap().wake();
318 lock
= self.get().lock();
323 // Update the elapsed cache
324 lock
.elapsed
= lock
.wheel
.elapsed();
325 lock
.next_wake
= lock
328 .map(|t
| NonZeroU64
::new(t
).unwrap_or_else(|| NonZeroU64
::new(1).unwrap()));
332 for waker
in waker_list
[0..waker_idx
].iter_mut() {
333 waker
.take().unwrap().wake();
337 /// Removes a registered timer from the driver.
339 /// The timer will be moved to the cancelled state. Wakers will _not_ be
340 /// invoked. If the timer is already completed, this function is a no-op.
342 /// This function always acquires the driver lock, even if the entry does
343 /// not appear to be registered.
345 /// SAFETY: The timer must not be registered with some other driver, and
346 /// `add_entry` must not be called concurrently.
347 pub(self) unsafe fn clear_entry(&self, entry
: NonNull
<TimerShared
>) {
349 let mut lock
= self.get().lock();
351 if entry
.as_ref().might_be_registered() {
352 lock
.wheel
.remove(entry
);
355 entry
.as_ref().handle().fire(Ok(()));
359 /// Removes and re-adds an entry to the driver.
361 /// SAFETY: The timer must be either unregistered, or registered with this
362 /// driver. No other threads are allowed to concurrently manipulate the
363 /// timer at all (the current thread should hold an exclusive reference to
364 /// the `TimerEntry`)
365 pub(self) unsafe fn reregister(&self, new_tick
: u64, entry
: NonNull
<TimerShared
>) {
367 let mut lock
= self.get().lock();
369 // We may have raced with a firing/deregistration, so check before
371 if unsafe { entry.as_ref().might_be_registered() }
{
372 lock
.wheel
.remove(entry
);
375 // Now that we have exclusive control of this entry, mint a handle to reinsert it.
376 let entry
= entry
.as_ref().handle();
378 if self.is_shutdown() {
379 unsafe { entry.fire(Err(crate::time::error::Error::shutdown())) }
381 entry
.set_expiration(new_tick
);
383 // Note: We don't have to worry about racing with some other resetting
384 // thread, because add_entry and reregister require exclusive control of
386 match unsafe { lock.wheel.insert(entry) }
{
390 .map(|next_wake
| when
< next_wake
.get())
393 lock
.unpark
.unpark();
398 Err((entry
, super::error
::InsertError
::Elapsed
)) => unsafe {
404 // Must release lock before invoking waker to avoid the risk of deadlock.
407 // The timer was fired synchronously as a result of the reregistration.
408 // Wake the waker; this is needed because we might reset _after_ a poll,
409 // and otherwise the task won't be awoken to poll again.
410 if let Some(waker
) = waker
{
416 impl<P
> Park
for Driver
<P
>
420 type Unpark
= TimerUnpark
<P
>;
421 type Error
= P
::Error
;
423 fn unpark(&self) -> Self::Unpark
{
424 TimerUnpark
::new(self)
427 fn park(&mut self) -> Result
<(), Self::Error
> {
428 self.park_internal(None
)
431 fn park_timeout(&mut self, duration
: Duration
) -> Result
<(), Self::Error
> {
432 self.park_internal(Some(duration
))
435 fn shutdown(&mut self) {
436 if self.handle
.is_shutdown() {
440 self.handle
.get().is_shutdown
.store(true, Ordering
::SeqCst
);
442 // Advance time forward to the end of time.
444 self.handle
.process_at_time(u64::MAX
);
446 self.park
.shutdown();
450 impl<P
> Drop
for Driver
<P
>
459 pub(crate) struct TimerUnpark
<P
: Park
+ '
static> {
462 #[cfg(feature = "test-util")]
463 did_wake
: Arc
<AtomicBool
>,
466 impl<P
: Park
+ '
static> TimerUnpark
<P
> {
467 fn new(driver
: &Driver
<P
>) -> TimerUnpark
<P
> {
469 inner
: driver
.park
.unpark(),
471 #[cfg(feature = "test-util")]
472 did_wake
: driver
.did_wake
.clone(),
477 impl<P
: Park
+ '
static> Unpark
for TimerUnpark
<P
> {
479 #[cfg(feature = "test-util")]
480 self.did_wake
.store(true, Ordering
::SeqCst
);
486 // ===== impl Inner =====
489 pub(self) fn new(time_source
: ClockTime
, unpark
: Box
<dyn Unpark
>) -> Self {
491 state
: Mutex
::new(InnerState
{
496 wheel
: wheel
::Wheel
::new(),
498 is_shutdown
: AtomicBool
::new(false),
502 /// Locks the driver's inner structure
503 pub(super) fn lock(&self) -> crate::loom
::sync
::MutexGuard
<'_
, InnerState
> {
507 // Check whether the driver has been shutdown
508 pub(super) fn is_shutdown(&self) -> bool
{
509 self.is_shutdown
.load(Ordering
::SeqCst
)
513 impl fmt
::Debug
for Inner
{
514 fn fmt(&self, fmt
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
515 fmt
.debug_struct("Inner").finish()