tokio/runtime/time/
mod.rs

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))]
6
7//! Time driver.
8
9mod entry;
10pub(crate) use entry::TimerEntry;
11use entry::{EntryList, TimerHandle, TimerShared, MAX_SAFE_MILLIS_DURATION};
12
13mod handle;
14pub(crate) use self::handle::Handle;
15
16mod source;
17pub(crate) use source::TimeSource;
18
19mod wheel;
20
21use crate::loom::sync::atomic::{AtomicBool, Ordering};
22use crate::loom::sync::Mutex;
23use crate::runtime::driver::{self, IoHandle, IoStack};
24use crate::time::error::Error;
25use crate::time::{Clock, Duration};
26use crate::util::WakeList;
27
28use std::fmt;
29use std::{num::NonZeroU64, ptr::NonNull};
30
31/// Time implementation that drives [`Sleep`][sleep], [`Interval`][interval], and [`Timeout`][timeout].
32///
33/// A `Driver` instance tracks the state necessary for managing time and
34/// notifying the [`Sleep`][sleep] instances once their deadlines are reached.
35///
36/// It is expected that a single instance manages many individual [`Sleep`][sleep]
37/// instances. The `Driver` implementation is thread-safe and, as such, is able
38/// to handle callers from across threads.
39///
40/// After creating the `Driver` instance, the caller must repeatedly call `park`
41/// or `park_timeout`. The time driver will perform no work unless `park` or
42/// `park_timeout` is called repeatedly.
43///
44/// The driver has a resolution of one millisecond. Any unit of time that falls
45/// between milliseconds are rounded up to the next millisecond.
46///
47/// When an instance is dropped, any outstanding [`Sleep`][sleep] instance that has not
48/// elapsed will be notified with an error. At this point, calling `poll` on the
49/// [`Sleep`][sleep] instance will result in panic.
50///
51/// # Implementation
52///
53/// The time driver is based on the [paper by Varghese and Lauck][paper].
54///
55/// A hashed timing wheel is a vector of slots, where each slot handles a time
56/// slice. As time progresses, the timer walks over the slot for the current
57/// instant, and processes each entry for that slot. When the timer reaches the
58/// end of the wheel, it starts again at the beginning.
59///
60/// The implementation maintains six wheels arranged in a set of levels. As the
61/// levels go up, the slots of the associated wheel represent larger intervals
62/// of time. At each level, the wheel has 64 slots. Each slot covers a range of
63/// time equal to the wheel at the lower level. At level zero, each slot
64/// represents one millisecond of time.
65///
66/// The wheels are:
67///
68/// * Level 0: 64 x 1 millisecond slots.
69/// * Level 1: 64 x 64 millisecond slots.
70/// * Level 2: 64 x ~4 second slots.
71/// * Level 3: 64 x ~4 minute slots.
72/// * Level 4: 64 x ~4 hour slots.
73/// * Level 5: 64 x ~12 day slots.
74///
75/// When the timer processes entries at level zero, it will notify all the
76/// `Sleep` instances as their deadlines have been reached. For all higher
77/// levels, all entries will be redistributed across the wheel at the next level
78/// down. Eventually, as time progresses, entries with [`Sleep`][sleep] instances will
79/// either be canceled (dropped) or their associated entries will reach level
80/// zero and be notified.
81///
82/// [paper]: http://www.cs.columbia.edu/~nahum/w6998/papers/ton97-timing-wheels.pdf
83/// [sleep]: crate::time::Sleep
84/// [timeout]: crate::time::Timeout
85/// [interval]: crate::time::Interval
86#[derive(Debug)]
87pub(crate) struct Driver {
88    /// Parker to delegate to.
89    park: IoStack,
90}
91
92/// Timer state shared between `Driver`, `Handle`, and `Registration`.
93struct Inner {
94    // The state is split like this so `Handle` can access `is_shutdown` without locking the mutex
95    pub(super) state: Mutex<InnerState>,
96
97    /// True if the driver is being shutdown.
98    pub(super) is_shutdown: AtomicBool,
99
100    // When `true`, a call to `park_timeout` should immediately return and time
101    // should not advance. One reason for this to be `true` is if the task
102    // passed to `Runtime::block_on` called `task::yield_now()`.
103    //
104    // While it may look racy, it only has any effect when the clock is paused
105    // and pausing the clock is restricted to a single-threaded runtime.
106    #[cfg(feature = "test-util")]
107    did_wake: AtomicBool,
108}
109
110/// Time state shared which must be protected by a `Mutex`
111struct InnerState {
112    /// The earliest time at which we promise to wake up without unparking.
113    next_wake: Option<NonZeroU64>,
114
115    /// Timer wheel.
116    wheel: wheel::Wheel,
117}
118
119// ===== impl Driver =====
120
121impl Driver {
122    /// Creates a new `Driver` instance that uses `park` to block the current
123    /// thread and `time_source` to get the current time and convert to ticks.
124    ///
125    /// Specifying the source of time is useful when testing.
126    pub(crate) fn new(park: IoStack, clock: &Clock) -> (Driver, Handle) {
127        let time_source = TimeSource::new(clock);
128
129        let handle = Handle {
130            time_source,
131            inner: Inner {
132                state: Mutex::new(InnerState {
133                    next_wake: None,
134                    wheel: wheel::Wheel::new(),
135                }),
136                is_shutdown: AtomicBool::new(false),
137
138                #[cfg(feature = "test-util")]
139                did_wake: AtomicBool::new(false),
140            },
141        };
142
143        let driver = Driver { park };
144
145        (driver, handle)
146    }
147
148    pub(crate) fn park(&mut self, handle: &driver::Handle) {
149        self.park_internal(handle, None);
150    }
151
152    pub(crate) fn park_timeout(&mut self, handle: &driver::Handle, duration: Duration) {
153        self.park_internal(handle, Some(duration));
154    }
155
156    pub(crate) fn shutdown(&mut self, rt_handle: &driver::Handle) {
157        let handle = rt_handle.time();
158
159        if handle.is_shutdown() {
160            return;
161        }
162
163        handle.inner.is_shutdown.store(true, Ordering::SeqCst);
164
165        // Advance time forward to the end of time.
166
167        handle.process_at_time(u64::MAX);
168
169        self.park.shutdown(rt_handle);
170    }
171
172    fn park_internal(&mut self, rt_handle: &driver::Handle, limit: Option<Duration>) {
173        let handle = rt_handle.time();
174        let mut lock = handle.inner.state.lock();
175
176        assert!(!handle.is_shutdown());
177
178        let next_wake = lock.wheel.next_expiration_time();
179        lock.next_wake =
180            next_wake.map(|t| NonZeroU64::new(t).unwrap_or_else(|| NonZeroU64::new(1).unwrap()));
181
182        drop(lock);
183
184        match next_wake {
185            Some(when) => {
186                let now = handle.time_source.now(rt_handle.clock());
187                // Note that we effectively round up to 1ms here - this avoids
188                // very short-duration microsecond-resolution sleeps that the OS
189                // might treat as zero-length.
190                let mut duration = handle
191                    .time_source
192                    .tick_to_duration(when.saturating_sub(now));
193
194                if duration > Duration::from_millis(0) {
195                    if let Some(limit) = limit {
196                        duration = std::cmp::min(limit, duration);
197                    }
198
199                    self.park_thread_timeout(rt_handle, duration);
200                } else {
201                    self.park.park_timeout(rt_handle, Duration::from_secs(0));
202                }
203            }
204            None => {
205                if let Some(duration) = limit {
206                    self.park_thread_timeout(rt_handle, duration);
207                } else {
208                    self.park.park(rt_handle);
209                }
210            }
211        }
212
213        // Process pending timers after waking up
214        handle.process(rt_handle.clock());
215    }
216
217    cfg_test_util! {
218        fn park_thread_timeout(&mut self, rt_handle: &driver::Handle, duration: Duration) {
219            let handle = rt_handle.time();
220            let clock = rt_handle.clock();
221
222            if clock.can_auto_advance() {
223                self.park.park_timeout(rt_handle, Duration::from_secs(0));
224
225                // If the time driver was woken, then the park completed
226                // before the "duration" elapsed (usually caused by a
227                // yield in `Runtime::block_on`). In this case, we don't
228                // advance the clock.
229                if !handle.did_wake() {
230                    // Simulate advancing time
231                    if let Err(msg) = clock.advance(duration) {
232                        panic!("{}", msg);
233                    }
234                }
235            } else {
236                self.park.park_timeout(rt_handle, duration);
237            }
238        }
239    }
240
241    cfg_not_test_util! {
242        fn park_thread_timeout(&mut self, rt_handle: &driver::Handle, duration: Duration) {
243            self.park.park_timeout(rt_handle, duration);
244        }
245    }
246}
247
248impl Handle {
249    /// Runs timer related logic, and returns the next wakeup time
250    pub(self) fn process(&self, clock: &Clock) {
251        let now = self.time_source().now(clock);
252
253        self.process_at_time(now);
254    }
255
256    pub(self) fn process_at_time(&self, mut now: u64) {
257        let mut waker_list = WakeList::new();
258
259        let mut lock = self.inner.lock();
260
261        if now < lock.wheel.elapsed() {
262            // Time went backwards! This normally shouldn't happen as the Rust language
263            // guarantees that an Instant is monotonic, but can happen when running
264            // Linux in a VM on a Windows host due to std incorrectly trusting the
265            // hardware clock to be monotonic.
266            //
267            // See <https://github.com/tokio-rs/tokio/issues/3619> for more information.
268            now = lock.wheel.elapsed();
269        }
270
271        while let Some(entry) = lock.wheel.poll(now) {
272            debug_assert!(unsafe { entry.is_pending() });
273
274            // SAFETY: We hold the driver lock, and just removed the entry from any linked lists.
275            if let Some(waker) = unsafe { entry.fire(Ok(())) } {
276                waker_list.push(waker);
277
278                if !waker_list.can_push() {
279                    // Wake a batch of wakers. To avoid deadlock, we must do this with the lock temporarily dropped.
280                    drop(lock);
281
282                    waker_list.wake_all();
283
284                    lock = self.inner.lock();
285                }
286            }
287        }
288
289        lock.next_wake = lock
290            .wheel
291            .poll_at()
292            .map(|t| NonZeroU64::new(t).unwrap_or_else(|| NonZeroU64::new(1).unwrap()));
293
294        drop(lock);
295
296        waker_list.wake_all();
297    }
298
299    /// Removes a registered timer from the driver.
300    ///
301    /// The timer will be moved to the cancelled state. Wakers will _not_ be
302    /// invoked. If the timer is already completed, this function is a no-op.
303    ///
304    /// This function always acquires the driver lock, even if the entry does
305    /// not appear to be registered.
306    ///
307    /// SAFETY: The timer must not be registered with some other driver, and
308    /// `add_entry` must not be called concurrently.
309    pub(self) unsafe fn clear_entry(&self, entry: NonNull<TimerShared>) {
310        unsafe {
311            let mut lock = self.inner.lock();
312
313            if entry.as_ref().might_be_registered() {
314                lock.wheel.remove(entry);
315            }
316
317            entry.as_ref().handle().fire(Ok(()));
318        }
319    }
320
321    /// Removes and re-adds an entry to the driver.
322    ///
323    /// SAFETY: The timer must be either unregistered, or registered with this
324    /// driver. No other threads are allowed to concurrently manipulate the
325    /// timer at all (the current thread should hold an exclusive reference to
326    /// the `TimerEntry`)
327    pub(self) unsafe fn reregister(
328        &self,
329        unpark: &IoHandle,
330        new_tick: u64,
331        entry: NonNull<TimerShared>,
332    ) {
333        let waker = unsafe {
334            let mut lock = self.inner.lock();
335
336            // We may have raced with a firing/deregistration, so check before
337            // deregistering.
338            if unsafe { entry.as_ref().might_be_registered() } {
339                lock.wheel.remove(entry);
340            }
341
342            // Now that we have exclusive control of this entry, mint a handle to reinsert it.
343            let entry = entry.as_ref().handle();
344
345            if self.is_shutdown() {
346                unsafe { entry.fire(Err(crate::time::error::Error::shutdown())) }
347            } else {
348                entry.set_expiration(new_tick);
349
350                // Note: We don't have to worry about racing with some other resetting
351                // thread, because add_entry and reregister require exclusive control of
352                // the timer entry.
353                match unsafe { lock.wheel.insert(entry) } {
354                    Ok(when) => {
355                        if lock
356                            .next_wake
357                            .map(|next_wake| when < next_wake.get())
358                            .unwrap_or(true)
359                        {
360                            unpark.unpark();
361                        }
362
363                        None
364                    }
365                    Err((entry, crate::time::error::InsertError::Elapsed)) => unsafe {
366                        entry.fire(Ok(()))
367                    },
368                }
369            }
370
371            // Must release lock before invoking waker to avoid the risk of deadlock.
372        };
373
374        // The timer was fired synchronously as a result of the reregistration.
375        // Wake the waker; this is needed because we might reset _after_ a poll,
376        // and otherwise the task won't be awoken to poll again.
377        if let Some(waker) = waker {
378            waker.wake();
379        }
380    }
381
382    cfg_test_util! {
383        fn did_wake(&self) -> bool {
384            self.inner.did_wake.swap(false, Ordering::SeqCst)
385        }
386    }
387}
388
389// ===== impl Inner =====
390
391impl Inner {
392    /// Locks the driver's inner structure
393    pub(super) fn lock(&self) -> crate::loom::sync::MutexGuard<'_, InnerState> {
394        self.state.lock()
395    }
396
397    // Check whether the driver has been shutdown
398    pub(super) fn is_shutdown(&self) -> bool {
399        self.is_shutdown.load(Ordering::SeqCst)
400    }
401}
402
403impl fmt::Debug for Inner {
404    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
405        fmt.debug_struct("Inner").finish()
406    }
407}
408
409#[cfg(test)]
410mod tests;