tokio/runtime/time/wheel/mod.rs
1use crate::runtime::time::{TimerHandle, TimerShared};
2use crate::time::error::InsertError;
3use crate::util::linked_list::LinkedList;
4
5mod level;
6pub(crate) use self::level::Expiration;
7use self::level::Level;
8
9use std::ptr::NonNull;
10
11use super::entry::STATE_DEREGISTERED;
12
13/// Timing wheel implementation.
14///
15/// This type provides the hashed timing wheel implementation that backs
16/// [`Driver`].
17///
18/// See [`Driver`] documentation for some implementation notes.
19///
20/// [`Driver`]: crate::runtime::time::Driver
21#[derive(Debug)]
22pub(crate) struct Wheel {
23 /// The number of milliseconds elapsed since the wheel started.
24 elapsed: u64,
25
26 /// Timer wheel.
27 ///
28 /// Levels:
29 ///
30 /// * 1 ms slots / 64 ms range
31 /// * 64 ms slots / ~ 4 sec range
32 /// * ~ 4 sec slots / ~ 4 min range
33 /// * ~ 4 min slots / ~ 4 hr range
34 /// * ~ 4 hr slots / ~ 12 day range
35 /// * ~ 12 day slots / ~ 2 yr range
36 levels: Box<[Level; NUM_LEVELS]>,
37
38 /// Entries queued for firing
39 pending: LinkedList<TimerShared>,
40}
41
42/// Number of levels. Each level has 64 slots. By using 6 levels with 64 slots
43/// each, the timer is able to track time up to 2 years into the future with a
44/// precision of 1 millisecond.
45const NUM_LEVELS: usize = 6;
46
47/// The maximum duration of a `Sleep`.
48pub(super) const MAX_DURATION: u64 = (1 << (6 * NUM_LEVELS)) - 1;
49
50impl Wheel {
51 /// Creates a new timing wheel.
52 pub(crate) fn new() -> Wheel {
53 let levels = (0..NUM_LEVELS).map(Level::new).collect::<Box<_>>();
54 Wheel {
55 elapsed: 0,
56 levels: levels.try_into().unwrap(),
57 pending: LinkedList::new(),
58 }
59 }
60
61 /// Returns the number of milliseconds that have elapsed since the timing
62 /// wheel's creation.
63 pub(crate) fn elapsed(&self) -> u64 {
64 self.elapsed
65 }
66
67 /// Inserts an entry into the timing wheel.
68 ///
69 /// # Arguments
70 ///
71 /// * `item`: The item to insert into the wheel.
72 ///
73 /// # Return
74 ///
75 /// Returns `Ok` when the item is successfully inserted, `Err` otherwise.
76 ///
77 /// `Err(Elapsed)` indicates that `when` represents an instant that has
78 /// already passed. In this case, the caller should fire the timeout
79 /// immediately.
80 ///
81 /// `Err(Invalid)` indicates an invalid `when` argument as been supplied.
82 ///
83 /// # Safety
84 ///
85 /// This function registers item into an intrusive linked list. The caller
86 /// must ensure that `item` is pinned and will not be dropped without first
87 /// being deregistered.
88 pub(crate) unsafe fn insert(
89 &mut self,
90 item: TimerHandle,
91 ) -> Result<u64, (TimerHandle, InsertError)> {
92 let when = unsafe { item.sync_when() };
93
94 if when <= self.elapsed {
95 return Err((item, InsertError::Elapsed));
96 }
97
98 // Get the level at which the entry should be stored
99 let level = self.level_for(when);
100
101 unsafe {
102 self.levels[level].add_entry(item);
103 }
104
105 debug_assert!({
106 self.levels[level]
107 .next_expiration(self.elapsed)
108 .map(|e| e.deadline >= self.elapsed)
109 .unwrap_or(true)
110 });
111
112 Ok(when)
113 }
114
115 /// Removes `item` from the timing wheel.
116 pub(crate) unsafe fn remove(&mut self, item: NonNull<TimerShared>) {
117 unsafe {
118 let when = item.as_ref().registered_when();
119 if when == STATE_DEREGISTERED {
120 self.pending.remove(item);
121 } else {
122 debug_assert!(
123 self.elapsed <= when,
124 "elapsed={}; when={}",
125 self.elapsed,
126 when
127 );
128
129 let level = self.level_for(when);
130 self.levels[level].remove_entry(item);
131 }
132 }
133 }
134
135 /// Instant at which to poll.
136 pub(crate) fn poll_at(&self) -> Option<u64> {
137 self.next_expiration().map(|expiration| expiration.deadline)
138 }
139
140 /// Advances the timer up to the instant represented by `now`.
141 pub(crate) fn poll(&mut self, now: u64) -> Option<TimerHandle> {
142 loop {
143 if let Some(handle) = self.pending.pop_back() {
144 return Some(handle);
145 }
146
147 match self.next_expiration() {
148 Some(ref expiration) if expiration.deadline <= now => {
149 self.process_expiration(expiration, now);
150
151 // During shutdown (`now == u64::MAX`), slots are drained
152 // directly without cascading entries across levels. Keep
153 // `self.elapsed` unchanged until all slots are empty so
154 // `level_for` remains valid if the lock is temporarily
155 // dropped to wake a batch of wakers.
156 if now != u64::MAX {
157 self.set_elapsed(expiration.deadline);
158 }
159 }
160 _ => {
161 // in this case the poll did not indicate an expiration
162 // _and_ we were not able to find a next expiration in
163 // the current list of timers. advance to the poll's
164 // current time and do nothing else.
165 self.set_elapsed(now);
166 break;
167 }
168 }
169 }
170
171 self.pending.pop_back()
172 }
173
174 /// Returns the instant at which the next timeout expires.
175 fn next_expiration(&self) -> Option<Expiration> {
176 if !self.pending.is_empty() {
177 // Expire immediately as we have things pending firing
178 return Some(Expiration {
179 level: 0,
180 slot: 0,
181 deadline: self.elapsed,
182 });
183 }
184
185 // Check all levels
186 for (level_num, level) in self.levels.iter().enumerate() {
187 if let Some(expiration) = level.next_expiration(self.elapsed) {
188 // There cannot be any expirations at a higher level that happen
189 // before this one.
190 debug_assert!(self.no_expirations_before(level_num + 1, expiration.deadline));
191
192 return Some(expiration);
193 }
194 }
195
196 None
197 }
198
199 /// Returns the tick at which this timer wheel next needs to perform some
200 /// processing, or None if there are no timers registered.
201 pub(super) fn next_expiration_time(&self) -> Option<u64> {
202 self.next_expiration().map(|ex| ex.deadline)
203 }
204
205 /// Used for debug assertions
206 fn no_expirations_before(&self, start_level: usize, before: u64) -> bool {
207 let mut res = true;
208
209 for level in &self.levels[start_level..] {
210 if let Some(e2) = level.next_expiration(self.elapsed) {
211 if e2.deadline < before {
212 res = false;
213 }
214 }
215 }
216
217 res
218 }
219
220 /// iteratively find entries that are between the wheel's current
221 /// time and the expiration time. for each in that population either
222 /// queue it for notification (in the case of the last level) or tier
223 /// it down to the next level (in all other cases).
224 pub(crate) fn process_expiration(&mut self, expiration: &Expiration, now: u64) {
225 // Note that we need to take _all_ of the entries off the list before
226 // processing any of them. This is important because it's possible that
227 // those entries might need to be reinserted into the same slot.
228 //
229 // This happens only on the highest level, when an entry is inserted
230 // more than MAX_DURATION into the future. When this happens, we wrap
231 // around, and process some entries a multiple of MAX_DURATION before
232 // they actually need to be dropped down a level. We then reinsert them
233 // back into the same position; we must make sure we don't then process
234 // those entries again or we'll end up in an infinite loop.
235 let mut entries = self.take_entries(expiration);
236 let deadline = if now == u64::MAX {
237 now
238 } else {
239 expiration.deadline
240 };
241
242 while let Some(item) = entries.pop_back() {
243 if expiration.level == 0 && now != u64::MAX {
244 debug_assert_eq!(unsafe { item.registered_when() }, expiration.deadline);
245 }
246
247 // Try to expire the entry; this is cheap (doesn't synchronize) if
248 // the timer is not expired, and updates registered_when.
249 match unsafe { item.mark_pending(deadline) } {
250 Ok(()) => {
251 // Item was expired
252 self.pending.push_front(item);
253 }
254 Err(expiration_tick) => {
255 let level = level_for(expiration.deadline, expiration_tick);
256 unsafe {
257 self.levels[level].add_entry(item);
258 }
259 }
260 }
261 }
262 }
263
264 fn set_elapsed(&mut self, when: u64) {
265 assert!(
266 self.elapsed <= when,
267 "elapsed={:?}; when={:?}",
268 self.elapsed,
269 when
270 );
271
272 if when > self.elapsed {
273 self.elapsed = when;
274 }
275 }
276
277 /// Obtains the list of entries that need processing for the given expiration.
278 fn take_entries(&mut self, expiration: &Expiration) -> LinkedList<TimerShared> {
279 self.levels[expiration.level].take_slot(expiration.slot)
280 }
281
282 fn level_for(&self, when: u64) -> usize {
283 level_for(self.elapsed, when)
284 }
285}
286
287fn level_for(elapsed: u64, when: u64) -> usize {
288 const SLOT_MASK: u64 = (1 << 6) - 1;
289
290 // Mask in the trailing bits ignored by the level calculation in order to cap
291 // the possible leading zeros
292 let mut masked = elapsed ^ when | SLOT_MASK;
293
294 if masked >= MAX_DURATION {
295 // Fudge the timer into the top level
296 masked = MAX_DURATION - 1;
297 }
298
299 let leading_zeros = masked.leading_zeros() as usize;
300 let significant = 63 - leading_zeros;
301
302 significant / NUM_LEVELS
303}
304
305#[cfg(all(test, not(loom)))]
306mod test {
307 use super::*;
308
309 #[test]
310 fn test_level_for() {
311 for pos in 0..64 {
312 assert_eq!(0, level_for(0, pos), "level_for({pos}) -- binary = {pos:b}");
313 }
314
315 for level in 1..5 {
316 for pos in level..64 {
317 let a = pos * 64_usize.pow(level as u32);
318 assert_eq!(
319 level,
320 level_for(0, a as u64),
321 "level_for({a}) -- binary = {a:b}"
322 );
323
324 if pos > level {
325 let a = a - 1;
326 assert_eq!(
327 level,
328 level_for(0, a as u64),
329 "level_for({a}) -- binary = {a:b}"
330 );
331 }
332
333 if pos < 64 {
334 let a = a + 1;
335 assert_eq!(
336 level,
337 level_for(0, a as u64),
338 "level_for({a}) -- binary = {a:b}"
339 );
340 }
341 }
342 }
343 }
344}