Skip to main content

tokio/util/
idle_notified_set.rs

1//! This module defines an `IdleNotifiedSet`, which is a collection of elements.
2//! Each element is intended to correspond to a task, and the collection will
3//! keep track of which tasks have had their waker notified, and which have not.
4//!
5//! Each entry in the set holds some user-specified value. The value's type is
6//! specified using the `T` parameter. It will usually be a `JoinHandle` or
7//! similar.
8
9use std::marker::PhantomPinned;
10use std::mem::ManuallyDrop;
11use std::ptr::NonNull;
12use std::task::{Context, Waker};
13
14use crate::loom::cell::UnsafeCell;
15use crate::loom::sync::{Arc, Mutex};
16use crate::util::linked_list::{self, Link, LinkedList};
17use crate::util::{waker_ref, Wake};
18
19/// This is the main handle to the collection.
20pub(crate) struct IdleNotifiedSet<T> {
21    lists: Arc<Lists<T>>,
22    length: usize,
23}
24
25/// A handle to an entry that is guaranteed to be stored in the idle or notified
26/// list of its `IdleNotifiedSet`. This value borrows the `IdleNotifiedSet`
27/// mutably to prevent the entry from being moved to the `Neither` list, which
28/// only the `IdleNotifiedSet` may do.
29///
30/// The main consequence of being stored in one of the lists is that the `value`
31/// field has not yet been consumed.
32///
33/// Note: This entry can be moved from the idle to the notified list while this
34/// object exists by waking its waker.
35pub(crate) struct EntryInOneOfTheLists<'a, T> {
36    entry: Arc<ListEntry<T>>,
37    set: &'a mut IdleNotifiedSet<T>,
38}
39
40type Lists<T> = Mutex<ListsInner<T>>;
41
42/// The linked lists hold strong references to the `ListEntry` items, and the
43/// `ListEntry` items also hold a strong reference back to the Lists object, but
44/// the destructor of the `IdleNotifiedSet` will clear the two lists, so once
45/// that object is destroyed, no ref-cycles will remain.
46struct ListsInner<T> {
47    notified: LinkedList<ListEntry<T>>,
48    idle: LinkedList<ListEntry<T>>,
49    /// Whenever an element in the `notified` list is woken, this waker will be
50    /// notified and consumed, if it exists.
51    waker: Option<Waker>,
52}
53
54/// Which of the two lists in the shared Lists object is this entry stored in?
55///
56/// If the value is `Idle`, then an entry's waker may move it to the notified
57/// list. Otherwise, only the `IdleNotifiedSet` may move it.
58///
59/// If the value is `Neither`, then it is still possible that the entry is in
60/// some third external list (this happens in `drain`).
61#[derive(Copy, Clone, Eq, PartialEq)]
62enum List {
63    Notified,
64    Idle,
65    Neither,
66}
67
68/// An entry in the list.
69///
70/// # Safety
71///
72/// The `my_list` field must only be accessed while holding the mutex in
73/// `parent`. It is an invariant that the value of `my_list` corresponds to
74/// which linked list in the `parent` holds this entry. Once this field takes
75/// the value `Neither`, then it may never be modified again.
76///
77/// If the value of `my_list` is `Notified` or `Idle`, then the `pointers` field
78/// must only be accessed while holding the mutex. If the value of `my_list` is
79/// `Neither`, then the `pointers` field may be accessed by the
80/// `IdleNotifiedSet` (this happens inside `drain`).
81///
82/// The `value` field is owned by the `IdleNotifiedSet` and may only be accessed
83/// by the `IdleNotifiedSet`. The operation that sets the value of `my_list` to
84/// `Neither` assumes ownership of the `value`, and it must either drop it or
85/// move it out from this entry to prevent it from getting leaked. (Since the
86/// two linked lists are emptied in the destructor of `IdleNotifiedSet`, the
87/// value should not be leaked.)
88struct ListEntry<T> {
89    /// The linked list pointers of the list this entry is in.
90    pointers: linked_list::Pointers<ListEntry<T>>,
91    /// Pointer to the shared `Lists` struct.
92    parent: Arc<Lists<T>>,
93    /// The value stored in this entry.
94    value: UnsafeCell<ManuallyDrop<T>>,
95    /// Used to remember which list this entry is in.
96    my_list: UnsafeCell<List>,
97    /// Required by the `linked_list::Pointers` field.
98    _pin: PhantomPinned,
99}
100
101generate_addr_of_methods! {
102    impl<T> ListEntry<T> {
103        unsafe fn addr_of_pointers(self: NonNull<Self>) -> NonNull<linked_list::Pointers<ListEntry<T>>> {
104            &self.pointers
105        }
106    }
107}
108
109// With mutable access to the `IdleNotifiedSet`, you can get mutable access to
110// the values.
111unsafe impl<T: Send> Send for IdleNotifiedSet<T> {}
112// With the current API we strictly speaking don't even need `T: Sync`, but we
113// require it anyway to support adding &self APIs that access the values in the
114// future.
115unsafe impl<T: Sync> Sync for IdleNotifiedSet<T> {}
116
117// These impls control when it is safe to create a Waker. Since the waker does
118// not allow access to the value in any way (including its destructor), it is
119// not necessary for `T` to be Send or Sync.
120unsafe impl<T> Send for ListEntry<T> {}
121unsafe impl<T> Sync for ListEntry<T> {}
122
123impl<T> IdleNotifiedSet<T> {
124    /// Create a new `IdleNotifiedSet`.
125    pub(crate) fn new() -> Self {
126        let lists = Mutex::new(ListsInner {
127            notified: LinkedList::new(),
128            idle: LinkedList::new(),
129            waker: None,
130        });
131
132        IdleNotifiedSet {
133            lists: Arc::new(lists),
134            length: 0,
135        }
136    }
137
138    pub(crate) fn len(&self) -> usize {
139        self.length
140    }
141
142    pub(crate) fn is_empty(&self) -> bool {
143        self.length == 0
144    }
145
146    /// Insert the given value into the `idle` list.
147    pub(crate) fn insert_idle(&mut self, value: T) -> EntryInOneOfTheLists<'_, T> {
148        self.length += 1;
149
150        let entry = Arc::new(ListEntry {
151            parent: self.lists.clone(),
152            value: UnsafeCell::new(ManuallyDrop::new(value)),
153            my_list: UnsafeCell::new(List::Idle),
154            pointers: linked_list::Pointers::new(),
155            _pin: PhantomPinned,
156        });
157
158        {
159            let mut lock = self.lists.lock();
160            lock.idle.push_front(entry.clone());
161        }
162
163        // Safety: We just put the entry in the idle list, so it is in one of the lists.
164        EntryInOneOfTheLists { entry, set: self }
165    }
166
167    /// Pop an entry from the notified list to poll it. The entry is moved to
168    /// the idle list atomically.
169    pub(crate) fn pop_notified(&mut self, waker: &Waker) -> Option<EntryInOneOfTheLists<'_, T>> {
170        // We don't decrement the length because this call moves the entry to
171        // the idle list rather than removing it.
172        if self.length == 0 {
173            // Fast path.
174            return None;
175        }
176
177        // Declare `_old_waker` before `lock` so that it is dropped after `lock`
178        // is released, including when returning early via `?`.
179        let _old_waker;
180        let mut lock = self.lists.lock();
181
182        let should_update_waker = match lock.waker.as_mut() {
183            Some(cur_waker) => !waker.will_wake(cur_waker),
184            None => true,
185        };
186        if should_update_waker {
187            _old_waker = lock.waker.replace(waker.clone());
188        }
189
190        // Pop the entry, returning None if empty.
191        let entry = lock.notified.pop_back()?;
192
193        lock.idle.push_front(entry.clone());
194
195        // Safety: We are holding the lock.
196        entry.my_list.with_mut(|ptr| unsafe {
197            *ptr = List::Idle;
198        });
199
200        drop(lock);
201
202        // Safety: We just put the entry in the idle list, so it is in one of the lists.
203        Some(EntryInOneOfTheLists { entry, set: self })
204    }
205
206    /// Tries to pop an entry from the notified list to poll it. The entry is moved to
207    /// the idle list atomically.
208    pub(crate) fn try_pop_notified(&mut self) -> Option<EntryInOneOfTheLists<'_, T>> {
209        // We don't decrement the length because this call moves the entry to
210        // the idle list rather than removing it.
211        if self.length == 0 {
212            // Fast path.
213            return None;
214        }
215
216        let mut lock = self.lists.lock();
217
218        // Pop the entry, returning None if empty.
219        let entry = lock.notified.pop_back()?;
220
221        lock.idle.push_front(entry.clone());
222
223        // Safety: We are holding the lock.
224        entry.my_list.with_mut(|ptr| unsafe {
225            *ptr = List::Idle;
226        });
227
228        drop(lock);
229
230        // Safety: We just put the entry in the idle list, so it is in one of the lists.
231        Some(EntryInOneOfTheLists { entry, set: self })
232    }
233
234    /// Call a function on every element in this list.
235    pub(crate) fn for_each<F: FnMut(&mut T)>(&mut self, mut func: F) {
236        fn get_ptrs<T>(list: &mut LinkedList<ListEntry<T>>, ptrs: &mut Vec<*mut T>) {
237            let mut node = list.last();
238
239            while let Some(entry) = node {
240                ptrs.push(entry.value.with_mut(|ptr| {
241                    let ptr: *mut ManuallyDrop<T> = ptr;
242                    let ptr: *mut T = ptr.cast();
243                    ptr
244                }));
245
246                let prev = entry.pointers.get_prev();
247                node = prev.map(|prev| unsafe { &*prev.as_ptr() });
248            }
249        }
250
251        // Atomically get a raw pointer to the value of every entry.
252        //
253        // Since this only locks the mutex once, it is not possible for a value
254        // to get moved from the idle list to the notified list during the
255        // operation, which would otherwise result in some value being listed
256        // twice.
257        let mut ptrs = Vec::with_capacity(self.len());
258        {
259            let mut lock = self.lists.lock();
260
261            get_ptrs(&mut lock.idle, &mut ptrs);
262            get_ptrs(&mut lock.notified, &mut ptrs);
263        }
264        debug_assert_eq!(ptrs.len(), ptrs.capacity());
265
266        for ptr in ptrs {
267            // Safety: When we grabbed the pointers, the entries were in one of
268            // the two lists. This means that their value was valid at the time,
269            // and it must still be valid because we are the IdleNotifiedSet,
270            // and only we can remove an entry from the two lists. (It's
271            // possible that an entry is moved from one list to the other during
272            // this loop, but that is ok.)
273            func(unsafe { &mut *ptr });
274        }
275    }
276
277    /// Remove all entries in both lists, applying some function to each element.
278    ///
279    /// The closure is called on all elements even if it panics. Having it panic
280    /// twice is a double-panic, and will abort the application.
281    pub(crate) fn drain<F: FnMut(T)>(&mut self, func: F) {
282        if self.length == 0 {
283            // Fast path.
284            return;
285        }
286        self.length = 0;
287
288        // The LinkedList is not cleared on panic, so we use a bomb to clear it.
289        //
290        // This value has the invariant that any entry in its `all_entries` list
291        // has `my_list` set to `Neither` and that the value has not yet been
292        // dropped.
293        struct AllEntries<T, F: FnMut(T)> {
294            all_entries: LinkedList<ListEntry<T>>,
295            func: F,
296        }
297
298        impl<T, F: FnMut(T)> AllEntries<T, F> {
299            fn pop_next(&mut self) -> bool {
300                if let Some(entry) = self.all_entries.pop_back() {
301                    // Safety: We just took this value from the list, so we can
302                    // destroy the value in the entry.
303                    entry
304                        .value
305                        .with_mut(|ptr| unsafe { (self.func)(ManuallyDrop::take(&mut *ptr)) });
306                    true
307                } else {
308                    false
309                }
310            }
311        }
312
313        impl<T, F: FnMut(T)> Drop for AllEntries<T, F> {
314            fn drop(&mut self) {
315                while self.pop_next() {}
316            }
317        }
318
319        let mut all_entries = AllEntries {
320            all_entries: LinkedList::new(),
321            func,
322        };
323
324        // Atomically move all entries to the new linked list in the AllEntries
325        // object.
326        {
327            let mut lock = self.lists.lock();
328            unsafe {
329                // Safety: We are holding the lock and `all_entries` is a new
330                // LinkedList.
331                move_to_new_list(&mut lock.idle, &mut all_entries.all_entries);
332                move_to_new_list(&mut lock.notified, &mut all_entries.all_entries);
333            }
334        }
335
336        // Keep destroying entries in the list until it is empty.
337        //
338        // If the closure panics, then the destructor of the `AllEntries` bomb
339        // ensures that we keep running the destructor on the remaining values.
340        // A second panic will abort the program.
341        while all_entries.pop_next() {}
342    }
343}
344
345/// # Safety
346///
347/// The mutex for the entries must be held, and the target list must be such
348/// that setting `my_list` to `Neither` is ok.
349unsafe fn move_to_new_list<T>(
350    from: &mut LinkedList<ListEntry<T>>,
351    to: &mut LinkedList<ListEntry<T>>,
352) {
353    while let Some(entry) = from.pop_back() {
354        entry.my_list.with_mut(|ptr| {
355            // Safety: pointer is accessed while holding the mutex.
356            unsafe {
357                *ptr = List::Neither;
358            }
359        });
360        to.push_front(entry);
361    }
362}
363
364impl<'a, T> EntryInOneOfTheLists<'a, T> {
365    /// Remove this entry from the list it is in, returning the value associated
366    /// with the entry.
367    ///
368    /// This consumes the value, since it is no longer guaranteed to be in a
369    /// list.
370    pub(crate) fn remove(self) -> T {
371        self.set.length -= 1;
372
373        {
374            let mut lock = self.set.lists.lock();
375
376            // Safety: We are holding the lock so there is no race, and we will
377            // remove the entry afterwards to uphold invariants.
378            let old_my_list = self.entry.my_list.with_mut(|ptr| unsafe {
379                let old_my_list = *ptr;
380                *ptr = List::Neither;
381                old_my_list
382            });
383
384            let list = match old_my_list {
385                List::Idle => &mut lock.idle,
386                List::Notified => &mut lock.notified,
387                // An entry in one of the lists is in one of the lists.
388                List::Neither => unreachable!(),
389            };
390
391            unsafe {
392                // Safety: We just checked that the entry is in this particular
393                // list.
394                list.remove(ListEntry::as_raw(&self.entry)).unwrap();
395            }
396        }
397
398        // By setting `my_list` to `Neither`, we have taken ownership of the
399        // value. We return it to the caller.
400        //
401        // Safety: We have a mutable reference to the `IdleNotifiedSet` that
402        // owns this entry, so we can use its permission to access the value.
403        self.entry
404            .value
405            .with_mut(|ptr| unsafe { ManuallyDrop::take(&mut *ptr) })
406    }
407
408    /// Access the value in this entry together with a context for its waker.
409    pub(crate) fn with_value_and_context<F, U>(&mut self, func: F) -> U
410    where
411        F: FnOnce(&mut T, &mut Context<'_>) -> U,
412        T: 'static,
413    {
414        let waker = waker_ref(&self.entry);
415
416        let mut context = Context::from_waker(&waker);
417
418        // Safety: We have a mutable reference to the `IdleNotifiedSet` that
419        // owns this entry, so we can use its permission to access the value.
420        self.entry
421            .value
422            .with_mut(|ptr| unsafe { func(&mut *ptr, &mut context) })
423    }
424}
425
426impl<T> Drop for IdleNotifiedSet<T> {
427    fn drop(&mut self) {
428        // Clear both lists.
429        self.drain(drop);
430
431        #[cfg(debug_assertions)]
432        if !std::thread::panicking() {
433            let lock = self.lists.lock();
434            assert!(lock.idle.is_empty());
435            assert!(lock.notified.is_empty());
436        }
437    }
438}
439
440impl<T: 'static> Wake for ListEntry<T> {
441    fn wake_by_ref(me: &Arc<Self>) {
442        let mut lock = me.parent.lock();
443
444        // Safety: We are holding the lock and we will update the lists to
445        // maintain invariants.
446        let old_my_list = me.my_list.with_mut(|ptr| unsafe {
447            let old_my_list = *ptr;
448            if old_my_list == List::Idle {
449                *ptr = List::Notified;
450            }
451            old_my_list
452        });
453
454        if old_my_list == List::Idle {
455            // We move ourself to the notified list.
456            let me = unsafe {
457                // Safety: We just checked that we are in this particular list.
458                lock.idle.remove(ListEntry::as_raw(me)).unwrap()
459            };
460            lock.notified.push_front(me);
461
462            if let Some(waker) = lock.waker.take() {
463                drop(lock);
464                waker.wake();
465            }
466        }
467    }
468
469    fn wake(me: Arc<Self>) {
470        Self::wake_by_ref(&me);
471    }
472}
473
474/// # Safety
475///
476/// `ListEntry` is forced to be !Unpin.
477unsafe impl<T> linked_list::Link for ListEntry<T> {
478    type Handle = Arc<ListEntry<T>>;
479    type Target = ListEntry<T>;
480
481    fn as_raw(handle: &Self::Handle) -> NonNull<ListEntry<T>> {
482        let ptr: *const ListEntry<T> = Arc::as_ptr(handle);
483        // Safety: We can't get a null pointer from `Arc::as_ptr`.
484        unsafe { NonNull::new_unchecked(ptr as *mut ListEntry<T>) }
485    }
486
487    unsafe fn from_raw(ptr: NonNull<ListEntry<T>>) -> Arc<ListEntry<T>> {
488        unsafe { Arc::from_raw(ptr.as_ptr()) }
489    }
490
491    unsafe fn pointers(
492        target: NonNull<ListEntry<T>>,
493    ) -> NonNull<linked_list::Pointers<ListEntry<T>>> {
494        unsafe { ListEntry::addr_of_pointers(target) }
495    }
496}
497
498#[cfg(all(test, not(loom)))]
499mod tests {
500    use crate::runtime::Builder;
501    use crate::task::JoinSet;
502
503    // A test that runs under miri.
504    //
505    // https://github.com/tokio-rs/tokio/pull/5693
506    #[test]
507    fn join_set_test() {
508        let rt = Builder::new_current_thread().build().unwrap();
509
510        let mut set = JoinSet::new();
511        set.spawn_on(futures::future::ready(()), rt.handle());
512
513        rt.block_on(set.join_next()).unwrap().unwrap();
514    }
515}