Skip to main content

tokio/sync/mpsc/
block.rs

1use crate::loom::cell::UnsafeCell;
2use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize};
3
4use std::alloc::Layout;
5use std::mem::MaybeUninit;
6use std::ops;
7use std::ptr::{self, NonNull};
8use std::sync::atomic::Ordering::{self, AcqRel, Acquire, Release};
9
10/// A block in a linked list.
11///
12/// Each block in the list can hold up to `BLOCK_CAP` messages.
13pub(crate) struct Block<T> {
14    /// The header fields.
15    header: BlockHeader<T>,
16
17    /// Array containing values pushed into the block. Values are stored in a
18    /// continuous array in order to improve cache line behavior when reading.
19    /// The values must be manually dropped.
20    values: Values<T>,
21}
22
23/// Extra fields for a `Block<T>`.
24struct BlockHeader<T> {
25    /// The start index of this block.
26    ///
27    /// Slots in this block have indices in `start_index .. start_index + BLOCK_CAP`.
28    start_index: usize,
29
30    /// The next block in the linked list.
31    next: AtomicPtr<Block<T>>,
32
33    /// Bitfield tracking slots that are ready to have their values consumed.
34    ready_slots: AtomicUsize,
35
36    /// The observed `tail_position` value *after* the block has been passed by
37    /// `block_tail`.
38    observed_tail_position: UnsafeCell<usize>,
39}
40
41pub(crate) enum Read<T> {
42    Value(T),
43    Closed,
44}
45
46#[repr(transparent)]
47struct Values<T>([UnsafeCell<MaybeUninit<T>>; BLOCK_CAP]);
48
49use super::BLOCK_CAP;
50
51/// Masks an index to get the block identifier.
52const BLOCK_MASK: usize = !(BLOCK_CAP - 1);
53
54/// Masks an index to get the value offset in a block.
55const SLOT_MASK: usize = BLOCK_CAP - 1;
56
57/// Flag tracking that a block has gone through the sender's release routine.
58///
59/// When this is set, the receiver may consider freeing the block.
60const RELEASED: usize = 1 << BLOCK_CAP;
61
62/// Flag tracking all senders dropped.
63///
64/// When this flag is set, the send half of the channel has closed.
65const TX_CLOSED: usize = RELEASED << 1;
66
67/// Mask covering all bits used to track slot readiness.
68const READY_MASK: usize = RELEASED - 1;
69
70/// Returns the index of the first slot in the block referenced by `slot_index`.
71#[inline(always)]
72pub(crate) fn start_index(slot_index: usize) -> usize {
73    BLOCK_MASK & slot_index
74}
75
76/// Returns the offset into the block referenced by `slot_index`.
77#[inline(always)]
78pub(crate) fn offset(slot_index: usize) -> usize {
79    SLOT_MASK & slot_index
80}
81
82generate_addr_of_methods! {
83    impl<T> Block<T> {
84        unsafe fn addr_of_header(self: NonNull<Self>) -> NonNull<BlockHeader<T>> {
85            &self.header
86        }
87
88        unsafe fn addr_of_values(self: NonNull<Self>) -> NonNull<Values<T>> {
89            &self.values
90        }
91    }
92}
93
94impl<T> Block<T> {
95    pub(crate) fn new(start_index: usize) -> Box<Block<T>> {
96        unsafe {
97            // Allocate the block on the heap.
98            // SAFETY: The size of the Block<T> is non-zero, since it is at least the size of the header.
99            let block = std::alloc::alloc(Layout::new::<Block<T>>()) as *mut Block<T>;
100            let block = match NonNull::new(block) {
101                Some(block) => block,
102                None => std::alloc::handle_alloc_error(Layout::new::<Block<T>>()),
103            };
104
105            // Write the header to the block.
106            Block::addr_of_header(block).as_ptr().write(BlockHeader {
107                // The absolute index in the channel of the first slot in the block.
108                start_index,
109
110                // Pointer to the next block in the linked list.
111                next: AtomicPtr::new(ptr::null_mut()),
112
113                ready_slots: AtomicUsize::new(0),
114
115                observed_tail_position: UnsafeCell::new(0),
116            });
117
118            // Initialize the values array.
119            Values::initialize(Block::addr_of_values(block));
120
121            // Convert the pointer to a `Box`.
122            // Safety: The raw pointer was allocated using the global allocator, and with
123            // the layout for a `Block<T>`, so it's valid to convert it to box.
124            Box::from_raw(block.as_ptr())
125        }
126    }
127
128    /// Returns `true` if the block matches the given index.
129    pub(crate) fn is_at_index(&self, index: usize) -> bool {
130        debug_assert!(offset(index) == 0);
131        self.header.start_index == index
132    }
133
134    /// Returns the number of blocks between `self` and the block at the
135    /// specified index.
136    ///
137    /// `start_index` must represent a block *after* `self`.
138    pub(crate) fn distance(&self, other_index: usize) -> usize {
139        debug_assert!(offset(other_index) == 0);
140        other_index.wrapping_sub(self.header.start_index) / BLOCK_CAP
141    }
142
143    /// Reads the value at the given offset.
144    ///
145    /// Returns `None` if the slot is empty.
146    ///
147    /// # Safety
148    ///
149    /// To maintain safety, the caller must ensure:
150    ///
151    /// * No concurrent access to the slot.
152    pub(crate) unsafe fn read(&self, slot_index: usize) -> Option<Read<T>> {
153        let offset = offset(slot_index);
154
155        let ready_bits = self.header.ready_slots.load(Acquire);
156
157        if !is_ready(ready_bits, offset) {
158            if is_tx_closed(ready_bits) {
159                return Some(Read::Closed);
160            }
161
162            return None;
163        }
164
165        // Get the value
166        //
167        // Safety:
168        //
169        // 1. The caller guarantees that there is no concurrent access to the slot.
170        // 2. The `UnsafeCell` always give us a valid pointer to the value.
171        let value = self.values[offset].with(|ptr| unsafe { ptr::read(ptr) });
172
173        // Safety: the ready bit is set, so the value has been initialized.
174        Some(Read::Value(unsafe { value.assume_init() }))
175    }
176
177    /// Returns true if *this* block has a value in the given slot.
178    ///
179    /// Always returns false when given an index from a different block.
180    pub(crate) fn has_value(&self, slot_index: usize) -> bool {
181        if start_index(slot_index) != self.header.start_index {
182            return false;
183        }
184
185        let offset = offset(slot_index);
186        let ready_bits = self.header.ready_slots.load(Acquire);
187        is_ready(ready_bits, offset)
188    }
189
190    /// Writes a value to the block at the given offset.
191    ///
192    /// # Safety
193    ///
194    /// To maintain safety, the caller must ensure:
195    ///
196    /// * The slot is empty.
197    /// * No concurrent access to the slot.
198    pub(crate) unsafe fn write(&self, slot_index: usize, value: T) {
199        // Get the offset into the block
200        let slot_offset = offset(slot_index);
201
202        self.values[slot_offset].with_mut(|ptr| {
203            // Safety: the caller guarantees that there is no concurrent access to the slot
204            unsafe {
205                ptr::write(ptr, MaybeUninit::new(value));
206            }
207        });
208
209        // Release the value. After this point, the slot ref may no longer
210        // be used. It is possible for the receiver to free the memory at
211        // any point.
212        self.set_ready(slot_offset);
213    }
214
215    /// Signal to the receiver that the sender half of the list is closed.
216    pub(crate) unsafe fn tx_close(&self) {
217        self.header.ready_slots.fetch_or(TX_CLOSED, Release);
218    }
219
220    /// Resets the block to a blank state. This enables reusing blocks in the
221    /// channel.
222    ///
223    /// # Safety
224    ///
225    /// To maintain safety, the caller must ensure:
226    ///
227    /// * All slots are empty.
228    /// * The caller holds a unique pointer to the block.
229    pub(crate) unsafe fn reclaim(&mut self) {
230        self.header.start_index = 0;
231        self.header.next = AtomicPtr::new(ptr::null_mut());
232        self.header.ready_slots = AtomicUsize::new(0);
233    }
234
235    /// Releases the block to the rx half for freeing.
236    ///
237    /// This function is called by the tx half once it can be guaranteed that no
238    /// more senders will attempt to access the block.
239    ///
240    /// # Safety
241    ///
242    /// To maintain safety, the caller must ensure:
243    ///
244    /// * The block will no longer be accessed by any sender.
245    pub(crate) unsafe fn tx_release(&self, tail_position: usize) {
246        // Track the observed tail_position. Any sender targeting a greater
247        // tail_position is guaranteed to not access this block.
248        self.header
249            .observed_tail_position
250            // Safety:
251            //
252            // 1. The caller guarantees unique access to the block.
253            // 2. The `UnsafeCell` always gives us a valid pointer.
254            .with_mut(|ptr| unsafe { *ptr = tail_position });
255
256        // Set the released bit, signalling to the receiver that it is safe to
257        // free the block's memory as soon as all slots **prior** to
258        // `observed_tail_position` have been filled.
259        self.header.ready_slots.fetch_or(RELEASED, Release);
260    }
261
262    /// Mark a slot as ready
263    fn set_ready(&self, slot: usize) {
264        let mask = 1 << slot;
265        self.header.ready_slots.fetch_or(mask, Release);
266    }
267
268    /// Returns `true` when all slots have their `ready` bits set.
269    ///
270    /// This indicates that the block is in its final state and will no longer
271    /// be mutated.
272    pub(crate) fn is_final(&self) -> bool {
273        self.header.ready_slots.load(Acquire) & READY_MASK == READY_MASK
274    }
275
276    /// Returns the `observed_tail_position` value, if set
277    pub(crate) fn observed_tail_position(&self) -> Option<usize> {
278        if 0 == RELEASED & self.header.ready_slots.load(Acquire) {
279            None
280        } else {
281            Some(
282                self.header
283                    .observed_tail_position
284                    .with(|ptr| unsafe { *ptr }),
285            )
286        }
287    }
288
289    /// Loads the next block
290    pub(crate) fn load_next(&self, ordering: Ordering) -> Option<NonNull<Block<T>>> {
291        let ret = NonNull::new(self.header.next.load(ordering));
292
293        debug_assert!(unsafe {
294            ret.map_or(true, |block| {
295                block.as_ref().header.start_index == self.header.start_index.wrapping_add(BLOCK_CAP)
296            })
297        });
298
299        ret
300    }
301
302    /// Pushes `block` as the next block in the link.
303    ///
304    /// Returns Ok if successful, otherwise, a pointer to the next block in
305    /// the list is returned.
306    ///
307    /// This requires that the next pointer is null.
308    ///
309    /// # Ordering
310    ///
311    /// This performs a compare-and-swap on `next` using `AcqRel` ordering.
312    ///
313    /// # Safety
314    ///
315    /// To maintain safety, the caller must ensure:
316    ///
317    /// * `block` is not freed until it has been removed from the list.
318    pub(crate) unsafe fn try_push(
319        &self,
320        block: &mut NonNull<Block<T>>,
321        success: Ordering,
322        failure: Ordering,
323    ) -> Result<(), NonNull<Block<T>>> {
324        // Safety: caller guarantees that `block` is valid.
325        unsafe { block.as_mut() }.header.start_index =
326            self.header.start_index.wrapping_add(BLOCK_CAP);
327
328        let next_ptr = self
329            .header
330            .next
331            .compare_exchange(ptr::null_mut(), block.as_ptr(), success, failure)
332            .unwrap_or_else(|x| x);
333
334        match NonNull::new(next_ptr) {
335            Some(next_ptr) => Err(next_ptr),
336            None => Ok(()),
337        }
338    }
339
340    /// Grows the `Block` linked list by allocating and appending a new block.
341    ///
342    /// The next block in the linked list is returned. This may or may not be
343    /// the one allocated by the function call.
344    ///
345    /// # Implementation
346    ///
347    /// It is assumed that `self.next` is null. A new block is allocated with
348    /// `start_index` set to be the next block. A compare-and-swap is performed
349    /// with `AcqRel` memory ordering. If the compare-and-swap is successful, the
350    /// newly allocated block is released to other threads walking the block
351    /// linked list. If the compare-and-swap fails, the current thread acquires
352    /// the next block in the linked list, allowing the current thread to access
353    /// the slots.
354    pub(crate) fn grow(&self) -> NonNull<Block<T>> {
355        // Create the new block. It is assumed that the block will become the
356        // next one after `&self`. If this turns out to not be the case,
357        // `start_index` is updated accordingly.
358        let new_block = Block::new(self.header.start_index.wrapping_add(BLOCK_CAP));
359
360        let mut new_block = unsafe { NonNull::new_unchecked(Box::into_raw(new_block)) };
361
362        // Attempt to store the block. The first compare-and-swap attempt is
363        // "unrolled" due to minor differences in logic
364        //
365        // `AcqRel` is used as the ordering **only** when attempting the
366        // compare-and-swap on self.next.
367        //
368        // If the compare-and-swap fails, then the actual value of the cell is
369        // returned from this function and accessed by the caller. Given this,
370        // the memory must be acquired.
371        //
372        // `Release` ensures that the newly allocated block is available to
373        // other threads acquiring the next pointer.
374        let next = NonNull::new(
375            self.header
376                .next
377                .compare_exchange(ptr::null_mut(), new_block.as_ptr(), AcqRel, Acquire)
378                .unwrap_or_else(|x| x),
379        );
380
381        let next = match next {
382            Some(next) => next,
383            None => {
384                // The compare-and-swap succeeded and the newly allocated block
385                // is successfully pushed.
386                return new_block;
387            }
388        };
389
390        // There already is a next block in the linked list. The newly allocated
391        // block could be dropped and the discovered next block returned;
392        // however, that would be wasteful. Instead, the linked list is walked
393        // by repeatedly attempting to compare-and-swap the pointer into the
394        // `next` register until the compare-and-swap succeed.
395        //
396        // Care is taken to update new_block's start_index field as appropriate.
397
398        let mut curr = next;
399
400        // TODO: Should this iteration be capped?
401        loop {
402            let actual = unsafe { curr.as_ref().try_push(&mut new_block, AcqRel, Acquire) };
403
404            curr = match actual {
405                Ok(()) => {
406                    return next;
407                }
408                Err(curr) => curr,
409            };
410
411            crate::loom::thread::yield_now();
412        }
413    }
414}
415
416/// Returns `true` if the specified slot has a value ready to be consumed.
417fn is_ready(bits: usize, slot: usize) -> bool {
418    let mask = 1 << slot;
419    mask == mask & bits
420}
421
422/// Returns `true` if the closed flag has been set.
423fn is_tx_closed(bits: usize) -> bool {
424    TX_CLOSED == bits & TX_CLOSED
425}
426
427impl<T> Values<T> {
428    /// Initialize a `Values` struct from a pointer.
429    ///
430    /// # Safety
431    ///
432    /// The raw pointer must be valid for writing a `Values<T>`.
433    unsafe fn initialize(_value: NonNull<Values<T>>) {
434        // When fuzzing, `UnsafeCell` needs to be initialized.
435        if_loom! {
436            let p = _value.as_ptr() as *mut UnsafeCell<MaybeUninit<T>>;
437            for i in 0..BLOCK_CAP {
438                unsafe {
439                    p.add(i).write(UnsafeCell::new(MaybeUninit::uninit()));
440                }
441            }
442        }
443    }
444}
445
446impl<T> ops::Index<usize> for Values<T> {
447    type Output = UnsafeCell<MaybeUninit<T>>;
448
449    fn index(&self, index: usize) -> &Self::Output {
450        self.0.index(index)
451    }
452}
453
454#[cfg(all(test, not(loom)))]
455#[test]
456fn assert_no_stack_overflow() {
457    // https://github.com/tokio-rs/tokio/issues/5293
458
459    struct Foo {
460        _a: [u8; 2_000_000],
461    }
462
463    assert_eq!(
464        Layout::new::<MaybeUninit<Block<Foo>>>(),
465        Layout::new::<Block<Foo>>()
466    );
467
468    let _block = Block::<Foo>::new(0);
469}