tokio/runtime/time/entry.rs
1//! Timer state structures.
2//!
3//! This module contains the heart of the intrusive timer implementation, and as
4//! such the structures inside are full of tricky concurrency and unsafe code.
5//!
6//! # Ground rules
7//!
8//! The heart of the timer implementation here is the [`TimerShared`] structure,
9//! shared between the [`TimerEntry`] and the driver. Generally, we permit access
10//! to [`TimerShared`] ONLY via either 1) a mutable reference to [`TimerEntry`] or
11//! 2) a held driver lock.
12//!
13//! It follows from this that any changes made while holding BOTH 1 and 2 will
14//! be reliably visible, regardless of ordering. This is because of the `acq/rel`
15//! fences on the driver lock ensuring ordering with 2, and rust mutable
16//! reference rules for 1 (a mutable reference to an object can't be passed
17//! between threads without an `acq/rel` barrier, and same-thread we have local
18//! happens-before ordering).
19//!
20//! # State field
21//!
22//! Each timer has a state field associated with it. This field contains either
23//! the current scheduled time, or a special flag value indicating its state.
24//! This state can either indicate that the timer is on the 'pending' queue (and
25//! thus will be fired with an `Ok(())` result soon) or that it has already been
26//! fired/deregistered.
27//!
28//! This single state field allows for code that is firing the timer to
29//! synchronize with any racing `reset` calls reliably.
30//!
31//! # Registered vs true timeouts
32//!
33//! To allow for the use case of a timeout that is periodically reset before
34//! expiration to be as lightweight as possible, we support optimistically
35//! lock-free timer resets, in the case where a timer is rescheduled to a later
36//! point than it was originally scheduled for.
37//!
38//! This is accomplished by lazily rescheduling timers. That is, we update the
39//! state field with the true expiration of the timer from the holder of
40//! the [`TimerEntry`]. When the driver services timers (ie, whenever it's
41//! walking lists of timers), it checks this "true when" value, and reschedules
42//! based on it.
43//!
44//! We do, however, also need to track what the expiration time was when we
45//! originally registered the timer; this is used to locate the right linked
46//! list when the timer is being cancelled.
47//! This is referred to as the `registered_when` internally.
48//!
49//! There is of course a race condition between timer reset and timer
50//! expiration. If the driver fails to observe the updated expiration time, it
51//! could trigger expiration of the timer too early. However, because
52//! [`mark_pending`][mark_pending] performs a compare-and-swap, it will identify this race and
53//! refuse to mark the timer as pending.
54//!
55//! [mark_pending]: TimerHandle::mark_pending
56
57use crate::loom::cell::UnsafeCell;
58use crate::loom::sync::atomic::AtomicU64;
59use crate::loom::sync::atomic::Ordering;
60
61use crate::runtime::scheduler;
62use crate::sync::AtomicWaker;
63use crate::time::Instant;
64use crate::util::linked_list;
65
66use pin_project_lite::pin_project;
67use std::task::{Context, Poll, Waker};
68use std::{marker::PhantomPinned, pin::Pin, ptr::NonNull};
69
70type TimerResult = Result<(), crate::time::error::Error>;
71
72pub(in crate::runtime::time) const STATE_DEREGISTERED: u64 = u64::MAX;
73const STATE_PENDING_FIRE: u64 = STATE_DEREGISTERED - 1;
74const STATE_MIN_VALUE: u64 = STATE_PENDING_FIRE;
75/// The largest safe integer to use for ticks.
76///
77/// This value should be updated if any other signal values are added above.
78pub(super) const MAX_SAFE_MILLIS_DURATION: u64 = STATE_MIN_VALUE - 1;
79
80/// This structure holds the current shared state of the timer - its scheduled
81/// time (if registered), or otherwise the result of the timer completing, as
82/// well as the registered waker.
83///
84/// Generally, the `StateCell` is only permitted to be accessed from two contexts:
85/// Either a thread holding the corresponding `&mut TimerEntry`, or a thread
86/// holding the timer driver lock. The write actions on the `StateCell` amount to
87/// passing "ownership" of the `StateCell` between these contexts; moving a timer
88/// from the `TimerEntry` to the driver requires _both_ holding the `&mut
89/// TimerEntry` and the driver lock, while moving it back (firing the timer)
90/// requires only the driver lock.
91pub(super) struct StateCell {
92 /// Holds either the scheduled expiration time for this timer, or (if the
93 /// timer has been fired and is unregistered), `u64::MAX`.
94 state: AtomicU64,
95 /// If the timer is fired (an Acquire order read on state shows
96 /// `u64::MAX`), holds the result that should be returned from
97 /// polling the timer. Otherwise, the contents are unspecified and reading
98 /// without holding the driver lock is undefined behavior.
99 result: UnsafeCell<TimerResult>,
100 /// The currently-registered waker
101 waker: AtomicWaker,
102}
103
104impl Default for StateCell {
105 fn default() -> Self {
106 Self::new()
107 }
108}
109
110impl std::fmt::Debug for StateCell {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 write!(f, "StateCell({:?})", self.read_state())
113 }
114}
115
116impl StateCell {
117 fn new() -> Self {
118 Self {
119 state: AtomicU64::new(STATE_DEREGISTERED),
120 result: UnsafeCell::new(Ok(())),
121 waker: AtomicWaker::new(),
122 }
123 }
124
125 fn is_pending(&self) -> bool {
126 self.state.load(Ordering::Relaxed) == STATE_PENDING_FIRE
127 }
128
129 /// Returns the current expiration time, or None if not currently scheduled.
130 fn when(&self) -> Option<u64> {
131 let cur_state = self.state.load(Ordering::Relaxed);
132
133 if cur_state == STATE_DEREGISTERED {
134 None
135 } else {
136 Some(cur_state)
137 }
138 }
139
140 /// If the timer is completed, returns the result of the timer. Otherwise,
141 /// returns None and registers the waker.
142 fn poll(&self, waker: &Waker) -> Poll<TimerResult> {
143 // We must register first. This ensures that either `fire` will
144 // observe the new waker, or we will observe a racing fire to have set
145 // the state, or both.
146 self.waker.register_by_ref(waker);
147
148 self.read_state()
149 }
150
151 fn read_state(&self) -> Poll<TimerResult> {
152 let cur_state = self.state.load(Ordering::Acquire);
153
154 if cur_state == STATE_DEREGISTERED {
155 // SAFETY: The driver has fired this timer; this involves writing
156 // the result, and then writing (with release ordering) the state
157 // field.
158 Poll::Ready(unsafe { self.result.with(|p| *p) })
159 } else {
160 Poll::Pending
161 }
162 }
163
164 /// Marks this timer as being moved to the pending list, if its scheduled
165 /// time is not after `not_after`.
166 ///
167 /// If the timer is scheduled for a time after `not_after`, returns an Err
168 /// containing the current scheduled time.
169 ///
170 /// SAFETY: Must hold the driver lock.
171 unsafe fn mark_pending(&self, not_after: u64) -> Result<(), u64> {
172 // Quick initial debug check to see if the timer is already fired. Since
173 // firing the timer can only happen with the driver lock held, we know
174 // we shouldn't be able to "miss" a transition to a fired state, even
175 // with relaxed ordering.
176 let mut cur_state = self.state.load(Ordering::Relaxed);
177
178 loop {
179 // improve the error message for things like
180 // https://github.com/tokio-rs/tokio/issues/3675
181 assert!(
182 cur_state < STATE_MIN_VALUE,
183 "mark_pending called when the timer entry is in an invalid state"
184 );
185
186 if cur_state > not_after {
187 break Err(cur_state);
188 }
189
190 match self.state.compare_exchange_weak(
191 cur_state,
192 STATE_PENDING_FIRE,
193 Ordering::AcqRel,
194 Ordering::Acquire,
195 ) {
196 Ok(_) => break Ok(()),
197 Err(actual_state) => cur_state = actual_state,
198 }
199 }
200 }
201
202 /// Fires the timer, setting the result to the provided result.
203 ///
204 /// Returns:
205 /// * `Some(waker)` - if fired and a waker needs to be invoked once the
206 /// driver lock is released
207 /// * `None` - if fired and a waker does not need to be invoked, or if
208 /// already fired
209 ///
210 /// SAFETY: The driver lock must be held.
211 unsafe fn fire(&self, result: TimerResult) -> Option<Waker> {
212 // Quick initial check to see if the timer is already fired. Since
213 // firing the timer can only happen with the driver lock held, we know
214 // we shouldn't be able to "miss" a transition to a fired state, even
215 // with relaxed ordering.
216 let cur_state = self.state.load(Ordering::Relaxed);
217 if cur_state == STATE_DEREGISTERED {
218 return None;
219 }
220
221 // SAFETY: We assume the driver lock is held and the timer is not
222 // fired, so only the driver is accessing this field.
223 //
224 // We perform a release-ordered store to state below, to ensure this
225 // write is visible before the state update is visible.
226 unsafe { self.result.with_mut(|p| *p = result) };
227
228 self.state.store(STATE_DEREGISTERED, Ordering::Release);
229
230 self.waker.take_waker()
231 }
232
233 /// Marks the timer as registered (poll will return None) and sets the
234 /// expiration time.
235 ///
236 /// While this function is memory-safe, it should only be called from a
237 /// context holding both `&mut TimerEntry` and the driver lock.
238 fn set_expiration(&self, timestamp: u64) {
239 debug_assert!(timestamp < STATE_MIN_VALUE);
240
241 // We can use relaxed ordering because we hold the driver lock and will
242 // fence when we release the lock.
243 self.state.store(timestamp, Ordering::Relaxed);
244 }
245
246 /// Attempts to adjust the timer to a new timestamp.
247 ///
248 /// If the timer has already been fired, is pending firing, or the new
249 /// timestamp is earlier than the old timestamp, (or occasionally
250 /// spuriously) returns Err without changing the timer's state. In this
251 /// case, the timer must be deregistered and re-registered.
252 fn extend_expiration(&self, new_timestamp: u64) -> Result<(), ()> {
253 let mut prior = self.state.load(Ordering::Relaxed);
254 loop {
255 if new_timestamp < prior || prior >= STATE_MIN_VALUE {
256 return Err(());
257 }
258
259 match self.state.compare_exchange_weak(
260 prior,
261 new_timestamp,
262 Ordering::AcqRel,
263 Ordering::Acquire,
264 ) {
265 Ok(_) => return Ok(()),
266 Err(true_prior) => prior = true_prior,
267 }
268 }
269 }
270
271 /// Returns true if the state of this timer indicates that the timer might
272 /// be registered with the driver. This check is performed with relaxed
273 /// ordering, but is conservative - if it returns false, the timer is
274 /// definitely _not_ registered.
275 pub(super) fn might_be_registered(&self) -> bool {
276 self.state.load(Ordering::Relaxed) != STATE_DEREGISTERED
277 }
278}
279
280pin_project! {
281 // A timer entry.
282 //
283 // This is the handle to a timer that is controlled by the requester of the
284 // timer. As this participates in intrusive data structures, it must be pinned
285 // before polling.
286 #[derive(Debug)]
287 pub(crate) struct TimerEntry {
288 // Arc reference to the runtime handle. We can only free the driver after
289 // deregistering everything from their respective timer wheels.
290 driver: scheduler::Handle,
291 // Shared inner structure; this is part of an intrusive linked list, and
292 // therefore other references can exist to it while mutable references to
293 // Entry exist.
294 //
295 // This is manipulated only under the inner mutex.
296 #[pin]
297 inner: TimerShared,
298 }
299
300 impl PinnedDrop for TimerEntry {
301 fn drop(this: Pin<&mut Self>) {
302 this.cancel();
303 }
304 }
305}
306
307unsafe impl Send for TimerEntry {}
308unsafe impl Sync for TimerEntry {}
309
310/// An `TimerHandle` is the (non-enforced) "unique" pointer from the driver to the
311/// timer entry. Generally, at most one `TimerHandle` exists for a timer at a time
312/// (enforced by the timer state machine).
313///
314/// SAFETY: An `TimerHandle` is essentially a raw pointer, and the usual caveats
315/// of pointer safety apply. In particular, `TimerHandle` does not itself enforce
316/// that the timer does still exist; however, normally an `TimerHandle` is created
317/// immediately before registering the timer, and is consumed when firing the
318/// timer, to help minimize mistakes. Still, because `TimerHandle` cannot enforce
319/// memory safety, all operations are unsafe.
320#[derive(Debug)]
321pub(crate) struct TimerHandle {
322 inner: NonNull<TimerShared>,
323}
324
325/// The shared state structure of a timer. This structure is shared between the
326/// frontend (`Entry`) and driver backend.
327///
328/// Note that this structure is located inside the `TimerEntry` structure.
329pub(crate) struct TimerShared {
330 /// A link within the doubly-linked list of timers on a particular level and
331 /// slot. Valid only if state is equal to Registered.
332 ///
333 /// Only accessed under the entry lock.
334 pointers: linked_list::Pointers<TimerShared>,
335
336 /// The time when the [`TimerEntry`] was registered into the Wheel,
337 /// [`STATE_DEREGISTERED`] means it is not registered.
338 ///
339 /// Generally owned by the driver, but is accessed by the entry when not
340 /// registered.
341 ///
342 /// We use relaxed ordering for both loading and storing since this value
343 /// is only accessed either when holding the driver lock or through mutable
344 /// references to [`TimerEntry`].
345 registered_when: AtomicU64,
346
347 /// Current state. This records whether the timer entry is currently under
348 /// the ownership of the driver, and if not, its current state (not
349 /// complete, fired, error, etc).
350 state: StateCell,
351
352 _p: PhantomPinned,
353}
354
355unsafe impl Send for TimerShared {}
356unsafe impl Sync for TimerShared {}
357
358impl std::fmt::Debug for TimerShared {
359 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
360 f.debug_struct("TimerShared")
361 .field(
362 "registered_when",
363 &self.registered_when.load(Ordering::Relaxed),
364 )
365 .field("state", &self.state)
366 .finish()
367 }
368}
369
370generate_addr_of_methods! {
371 impl<> TimerShared {
372 unsafe fn addr_of_pointers(self: NonNull<Self>) -> NonNull<linked_list::Pointers<TimerShared>> {
373 &self.pointers
374 }
375 }
376}
377
378impl TimerShared {
379 pub(super) fn new() -> Self {
380 Self {
381 registered_when: AtomicU64::new(0),
382 pointers: linked_list::Pointers::new(),
383 state: StateCell::default(),
384 _p: PhantomPinned,
385 }
386 }
387
388 /// Gets the cached time-of-expiration value.
389 pub(super) fn registered_when(&self) -> u64 {
390 // Cached-when is only accessed under the driver lock, so we can use relaxed
391 self.registered_when.load(Ordering::Relaxed)
392 }
393
394 /// Gets the true time-of-expiration value, and copies it into the cached
395 /// time-of-expiration value.
396 ///
397 /// SAFETY: Must be called with the driver lock held, and when this entry is
398 /// not in any timer wheel lists.
399 pub(super) unsafe fn sync_when(&self) -> u64 {
400 let true_when = self.true_when();
401
402 self.registered_when.store(true_when, Ordering::Relaxed);
403
404 true_when
405 }
406
407 /// Sets the cached time-of-expiration value.
408 ///
409 /// SAFETY: Must be called with the driver lock held, and when this entry is
410 /// not in any timer wheel lists.
411 unsafe fn set_registered_when(&self, when: u64) {
412 self.registered_when.store(when, Ordering::Relaxed);
413 }
414
415 /// Returns the true time-of-expiration value, with relaxed memory ordering.
416 pub(super) fn true_when(&self) -> u64 {
417 self.state.when().expect("Timer already fired")
418 }
419
420 /// Sets the true time-of-expiration value, even if it is less than the
421 /// current expiration or the timer is deregistered.
422 ///
423 /// SAFETY: Must only be called with the driver lock held and the entry not
424 /// in the timer wheel.
425 pub(super) unsafe fn set_expiration(&self, t: u64) {
426 self.state.set_expiration(t);
427 self.registered_when.store(t, Ordering::Relaxed);
428 }
429
430 /// Sets the true time-of-expiration only if it is after the current.
431 pub(super) fn extend_expiration(&self, t: u64) -> Result<(), ()> {
432 self.state.extend_expiration(t)
433 }
434
435 /// Returns a `TimerHandle` for this timer.
436 pub(super) fn handle(&self) -> TimerHandle {
437 TimerHandle {
438 inner: NonNull::from(self),
439 }
440 }
441
442 /// Returns true if the state of this timer indicates that the timer might
443 /// be registered with the driver. This check is performed with relaxed
444 /// ordering, but is conservative - if it returns false, the timer is
445 /// definitely _not_ registered.
446 pub(super) fn might_be_registered(&self) -> bool {
447 self.state.might_be_registered()
448 }
449}
450
451unsafe impl linked_list::Link for TimerShared {
452 type Handle = TimerHandle;
453
454 type Target = TimerShared;
455
456 fn as_raw(handle: &Self::Handle) -> NonNull<Self::Target> {
457 handle.inner
458 }
459
460 unsafe fn from_raw(ptr: NonNull<Self::Target>) -> Self::Handle {
461 TimerHandle { inner: ptr }
462 }
463
464 unsafe fn pointers(
465 target: NonNull<Self::Target>,
466 ) -> NonNull<linked_list::Pointers<Self::Target>> {
467 unsafe { TimerShared::addr_of_pointers(target) }
468 }
469}
470
471// ===== impl Entry =====
472
473impl TimerEntry {
474 pub(crate) fn new(handle: scheduler::Handle) -> Self {
475 Self {
476 driver: handle,
477 inner: TimerShared::new(),
478 }
479 }
480
481 pub(crate) fn init(self: Pin<&mut Self>, deadline: Instant) {
482 let tick = self.driver().time_source().deadline_to_tick(deadline);
483
484 unsafe {
485 self.driver()
486 .reregister(&self.driver.driver().io, tick, (&self.inner).into());
487 }
488 }
489
490 pub(crate) fn is_elapsed(&self) -> bool {
491 // Is this timer still in the timer wheel?
492 !self.inner.might_be_registered()
493 }
494
495 /// Cancels and deregisters the timer. This operation is irreversible.
496 pub(crate) fn cancel(self: Pin<&mut Self>) {
497 // We need to perform an acq/rel fence with the driver thread, and the
498 // simplest way to do so is to grab the driver lock.
499 //
500 // Why is this necessary? We're about to release this timer's memory for
501 // some other non-timer use. However, we've been doing a bunch of
502 // relaxed (or even non-atomic) writes from the driver thread, and we'll
503 // be doing more from _this thread_ (as this memory is interpreted as
504 // something else).
505 //
506 // It is critical to ensure that, from the point of view of the driver,
507 // those future non-timer writes happen-after the timer is fully fired,
508 // and from the purpose of this thread, the driver's writes all
509 // happen-before we drop the timer. This in turn requires us to perform
510 // an acquire-release barrier in _both_ directions between the driver
511 // and dropping thread.
512 //
513 // The lock acquisition in clear_entry serves this purpose. All of the
514 // driver manipulations happen with the lock held, so we can just take
515 // the lock and be sure that this drop happens-after everything the
516 // driver did so far and happens-before everything the driver does in
517 // the future. While we have the lock held, we also go ahead and
518 // deregister the entry if necessary.
519 unsafe { self.driver().clear_entry(NonNull::from(&self.inner)) };
520 }
521
522 pub(crate) fn reset(self: Pin<&mut Self>, deadline: Instant) {
523 let tick = self.driver().time_source().deadline_to_tick(deadline);
524
525 if self.inner.extend_expiration(tick).is_ok() {
526 return;
527 }
528
529 unsafe {
530 self.driver()
531 .reregister(&self.driver.driver().io, tick, (&self.inner).into());
532 }
533 }
534
535 pub(crate) fn poll_elapsed(
536 self: Pin<&mut Self>,
537 cx: &mut Context<'_>,
538 ) -> Poll<Result<(), super::Error>> {
539 assert!(
540 !self.driver().is_shutdown(),
541 "{}",
542 crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
543 );
544
545 self.inner.state.poll(cx.waker())
546 }
547
548 fn driver(&self) -> &super::Handle {
549 self.driver.driver().time()
550 }
551}
552
553impl TimerHandle {
554 pub(super) unsafe fn registered_when(&self) -> u64 {
555 unsafe { self.inner.as_ref().registered_when() }
556 }
557
558 pub(super) unsafe fn sync_when(&self) -> u64 {
559 unsafe { self.inner.as_ref().sync_when() }
560 }
561
562 pub(super) unsafe fn is_pending(&self) -> bool {
563 unsafe { self.inner.as_ref().state.is_pending() }
564 }
565
566 /// Forcibly sets the true and cached expiration times to the given tick.
567 ///
568 /// SAFETY: The caller must ensure that the handle remains valid, the driver
569 /// lock is held, and that the timer is not in any wheel linked lists.
570 pub(super) unsafe fn set_expiration(&self, tick: u64) {
571 unsafe {
572 self.inner.as_ref().set_expiration(tick);
573 }
574 }
575
576 /// Attempts to mark this entry as pending. If the expiration time is after
577 /// `not_after`, however, returns an Err with the current expiration time.
578 ///
579 /// If an `Err` is returned, the `registered_when` value will be updated to this
580 /// new expiration time.
581 ///
582 /// SAFETY: The caller must ensure that the handle remains valid, the driver
583 /// lock is held, and that the timer is not in any wheel linked lists.
584 /// After returning Ok, the entry must be added to the pending list.
585 pub(super) unsafe fn mark_pending(&self, not_after: u64) -> Result<(), u64> {
586 match unsafe { self.inner.as_ref().state.mark_pending(not_after) } {
587 Ok(()) => {
588 // mark this as being on the pending queue in registered_when
589 unsafe {
590 self.inner.as_ref().set_registered_when(STATE_DEREGISTERED);
591 }
592 Ok(())
593 }
594 Err(tick) => {
595 unsafe {
596 self.inner.as_ref().set_registered_when(tick);
597 }
598 Err(tick)
599 }
600 }
601 }
602
603 /// Attempts to transition to a terminal state. If the state is already a
604 /// terminal state, does nothing.
605 ///
606 /// Because the entry might be dropped after the state is moved to a
607 /// terminal state, this function consumes the handle to ensure we don't
608 /// access the entry afterwards.
609 ///
610 /// Returns the last-registered waker, if any.
611 ///
612 /// SAFETY: The driver lock must be held while invoking this function, and
613 /// the entry must not be in any wheel linked lists.
614 pub(super) unsafe fn fire(self, completed_state: TimerResult) -> Option<Waker> {
615 unsafe { self.inner.as_ref().state.fire(completed_state) }
616 }
617}