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 state: Mutex<InnerState>,
96
97 /// True if the driver is being shutdown.
98 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.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 pub(self) fn process(&self, clock: &Clock) {
250 let now = self.time_source().now(clock);
251
252 self.process_at_time(now);
253 }
254
255 pub(self) fn process_at_time(&self, mut now: u64) {
256 let mut waker_list = WakeList::new();
257
258 let mut lock = self.inner.lock();
259
260 if now < lock.wheel.elapsed() {
261 // Time went backwards! This normally shouldn't happen as the Rust language
262 // guarantees that an Instant is monotonic, but can happen when running
263 // Linux in a VM on a Windows host due to std incorrectly trusting the
264 // hardware clock to be monotonic.
265 //
266 // See <https://github.com/tokio-rs/tokio/issues/3619> for more information.
267 now = lock.wheel.elapsed();
268 }
269
270 while let Some(entry) = lock.wheel.poll(now) {
271 debug_assert!(unsafe { entry.is_pending() });
272
273 // SAFETY: We hold the driver lock, and just removed the entry from any linked lists.
274 if let Some(waker) = unsafe { entry.fire(Ok(())) } {
275 waker_list.push(waker);
276
277 if !waker_list.can_push() {
278 // Wake a batch of wakers. To avoid deadlock, we must do this with the lock temporarily dropped.
279 drop(lock);
280
281 waker_list.wake_all();
282
283 lock = self.inner.lock();
284 }
285 }
286 }
287
288 lock.next_wake = lock
289 .wheel
290 .poll_at()
291 .map(|t| NonZeroU64::new(t).unwrap_or_else(|| NonZeroU64::new(1).unwrap()));
292
293 drop(lock);
294
295 waker_list.wake_all();
296 }
297
298 /// Removes a registered timer from the driver.
299 ///
300 /// The timer will be moved to the cancelled state. Wakers will _not_ be
301 /// invoked. If the timer is already completed, this function is a no-op.
302 ///
303 /// This function always acquires the driver lock, even if the entry does
304 /// not appear to be registered.
305 ///
306 /// SAFETY: The timer must not be registered with some other driver, and
307 /// `add_entry` must not be called concurrently.
308 pub(self) unsafe fn clear_entry(&self, entry: NonNull<TimerShared>) {
309 unsafe {
310 let mut lock = self.inner.lock();
311
312 if entry.as_ref().might_be_registered() {
313 lock.wheel.remove(entry);
314 }
315
316 entry.as_ref().handle().fire(Ok(()));
317 }
318 }
319
320 /// Removes and re-adds an entry to the driver.
321 ///
322 /// SAFETY: The timer must be either unregistered, or registered with this
323 /// driver. No other threads are allowed to concurrently manipulate the
324 /// timer at all (the current thread should hold an exclusive reference to
325 /// the `TimerEntry`)
326 pub(self) unsafe fn reregister(
327 &self,
328 unpark: &IoHandle,
329 new_tick: u64,
330 entry: NonNull<TimerShared>,
331 ) {
332 let waker = unsafe {
333 let mut lock = self.inner.lock();
334
335 // We may have raced with a firing/deregistration, so check before
336 // deregistering.
337 if unsafe { entry.as_ref().might_be_registered() } {
338 lock.wheel.remove(entry);
339 }
340
341 // Now that we have exclusive control of this entry, mint a handle to reinsert it.
342 let entry = entry.as_ref().handle();
343
344 if self.is_shutdown() {
345 unsafe { entry.fire(Err(crate::time::error::Error::shutdown())) }
346 } else {
347 entry.set_expiration(new_tick);
348
349 // Note: We don't have to worry about racing with some other resetting
350 // thread, because add_entry and reregister require exclusive control of
351 // the timer entry.
352 match unsafe { lock.wheel.insert(entry) } {
353 Ok(when) => {
354 if lock
355 .next_wake
356 .map(|next_wake| when < next_wake.get())
357 .unwrap_or(true)
358 {
359 unpark.unpark();
360 }
361
362 None
363 }
364 Err((entry, crate::time::error::InsertError::Elapsed)) => unsafe {
365 entry.fire(Ok(()))
366 },
367 }
368 }
369
370 // Must release lock before invoking waker to avoid the risk of deadlock.
371 };
372
373 // The timer was fired synchronously as a result of the reregistration.
374 // Wake the waker; this is needed because we might reset _after_ a poll,
375 // and otherwise the task won't be awoken to poll again.
376 if let Some(waker) = waker {
377 waker.wake();
378 }
379 }
380
381 cfg_test_util! {
382 fn did_wake(&self) -> bool {
383 self.inner.did_wake.swap(false, Ordering::SeqCst)
384 }
385 }
386}
387
388// ===== impl Inner =====
389
390impl Inner {
391 /// Locks the driver's inner structure
392 pub(super) fn lock(&self) -> crate::loom::sync::MutexGuard<'_, InnerState> {
393 self.state.lock()
394 }
395
396 // Check whether the driver has been shutdown
397 pub(super) fn is_shutdown(&self) -> bool {
398 self.is_shutdown.load(Ordering::SeqCst)
399 }
400}
401
402impl fmt::Debug for Inner {
403 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
404 fmt.debug_struct("Inner").finish()
405 }
406}
407
408#[cfg(test)]
409mod tests;