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);
150
151 self.set_elapsed(expiration.deadline);
152 }
153 _ => {
154 // in this case the poll did not indicate an expiration
155 // _and_ we were not able to find a next expiration in
156 // the current list of timers. advance to the poll's
157 // current time and do nothing else.
158 self.set_elapsed(now);
159 break;
160 }
161 }
162 }
163
164 self.pending.pop_back()
165 }
166
167 /// Returns the instant at which the next timeout expires.
168 fn next_expiration(&self) -> Option<Expiration> {
169 if !self.pending.is_empty() {
170 // Expire immediately as we have things pending firing
171 return Some(Expiration {
172 level: 0,
173 slot: 0,
174 deadline: self.elapsed,
175 });
176 }
177
178 // Check all levels
179 for (level_num, level) in self.levels.iter().enumerate() {
180 if let Some(expiration) = level.next_expiration(self.elapsed) {
181 // There cannot be any expirations at a higher level that happen
182 // before this one.
183 debug_assert!(self.no_expirations_before(level_num + 1, expiration.deadline));
184
185 return Some(expiration);
186 }
187 }
188
189 None
190 }
191
192 /// Returns the tick at which this timer wheel next needs to perform some
193 /// processing, or None if there are no timers registered.
194 pub(super) fn next_expiration_time(&self) -> Option<u64> {
195 self.next_expiration().map(|ex| ex.deadline)
196 }
197
198 /// Used for debug assertions
199 fn no_expirations_before(&self, start_level: usize, before: u64) -> bool {
200 let mut res = true;
201
202 for level in &self.levels[start_level..] {
203 if let Some(e2) = level.next_expiration(self.elapsed) {
204 if e2.deadline < before {
205 res = false;
206 }
207 }
208 }
209
210 res
211 }
212
213 /// iteratively find entries that are between the wheel's current
214 /// time and the expiration time. for each in that population either
215 /// queue it for notification (in the case of the last level) or tier
216 /// it down to the next level (in all other cases).
217 pub(crate) fn process_expiration(&mut self, expiration: &Expiration) {
218 // Note that we need to take _all_ of the entries off the list before
219 // processing any of them. This is important because it's possible that
220 // those entries might need to be reinserted into the same slot.
221 //
222 // This happens only on the highest level, when an entry is inserted
223 // more than MAX_DURATION into the future. When this happens, we wrap
224 // around, and process some entries a multiple of MAX_DURATION before
225 // they actually need to be dropped down a level. We then reinsert them
226 // back into the same position; we must make sure we don't then process
227 // those entries again or we'll end up in an infinite loop.
228 let mut entries = self.take_entries(expiration);
229
230 while let Some(item) = entries.pop_back() {
231 if expiration.level == 0 {
232 debug_assert_eq!(unsafe { item.registered_when() }, expiration.deadline);
233 }
234
235 // Try to expire the entry; this is cheap (doesn't synchronize) if
236 // the timer is not expired, and updates registered_when.
237 match unsafe { item.mark_pending(expiration.deadline) } {
238 Ok(()) => {
239 // Item was expired
240 self.pending.push_front(item);
241 }
242 Err(expiration_tick) => {
243 let level = level_for(expiration.deadline, expiration_tick);
244 unsafe {
245 self.levels[level].add_entry(item);
246 }
247 }
248 }
249 }
250 }
251
252 fn set_elapsed(&mut self, when: u64) {
253 assert!(
254 self.elapsed <= when,
255 "elapsed={:?}; when={:?}",
256 self.elapsed,
257 when
258 );
259
260 if when > self.elapsed {
261 self.elapsed = when;
262 }
263 }
264
265 /// Obtains the list of entries that need processing for the given expiration.
266 fn take_entries(&mut self, expiration: &Expiration) -> LinkedList<TimerShared> {
267 self.levels[expiration.level].take_slot(expiration.slot)
268 }
269
270 fn level_for(&self, when: u64) -> usize {
271 level_for(self.elapsed, when)
272 }
273}
274
275fn level_for(elapsed: u64, when: u64) -> usize {
276 const SLOT_MASK: u64 = (1 << 6) - 1;
277
278 // Mask in the trailing bits ignored by the level calculation in order to cap
279 // the possible leading zeros
280 let mut masked = elapsed ^ when | SLOT_MASK;
281
282 if masked >= MAX_DURATION {
283 // Fudge the timer into the top level
284 masked = MAX_DURATION - 1;
285 }
286
287 let leading_zeros = masked.leading_zeros() as usize;
288 let significant = 63 - leading_zeros;
289
290 significant / NUM_LEVELS
291}
292
293#[cfg(all(test, not(loom)))]
294mod test {
295 use super::*;
296
297 #[test]
298 fn test_level_for() {
299 for pos in 0..64 {
300 assert_eq!(0, level_for(0, pos), "level_for({pos}) -- binary = {pos:b}");
301 }
302
303 for level in 1..5 {
304 for pos in level..64 {
305 let a = pos * 64_usize.pow(level as u32);
306 assert_eq!(
307 level,
308 level_for(0, a as u64),
309 "level_for({a}) -- binary = {a:b}"
310 );
311
312 if pos > level {
313 let a = a - 1;
314 assert_eq!(
315 level,
316 level_for(0, a as u64),
317 "level_for({a}) -- binary = {a:b}"
318 );
319 }
320
321 if pos < 64 {
322 let a = a + 1;
323 assert_eq!(
324 level,
325 level_for(0, a as u64),
326 "level_for({a}) -- binary = {a:b}"
327 );
328 }
329 }
330 }
331 }
332}