tokio/runtime/task/
core.rs

1//! Core task module.
2//!
3//! # Safety
4//!
5//! The functions in this module are private to the `task` module. All of them
6//! should be considered `unsafe` to use, but are not marked as such since it
7//! would be too noisy.
8//!
9//! Make sure to consult the relevant safety section of each function before
10//! use.
11
12// It doesn't make sense to enforce `unsafe_op_in_unsafe_fn` for this module because
13//
14// * This module is doing the low-level task management that requires tons of unsafe
15//   operations.
16// * Excessive `unsafe {}` blocks hurt readability significantly.
17// TODO: replace with `#[expect(unsafe_op_in_unsafe_fn)]` after bumpping
18// the MSRV to 1.81.0.
19#![allow(unsafe_op_in_unsafe_fn)]
20
21use crate::future::Future;
22use crate::loom::cell::UnsafeCell;
23use crate::runtime::context;
24use crate::runtime::task::raw::{self, Vtable};
25use crate::runtime::task::state::State;
26use crate::runtime::task::{Id, Schedule, TaskHarnessScheduleHooks};
27use crate::util::linked_list;
28
29use std::num::NonZeroU64;
30#[cfg(tokio_unstable)]
31use std::panic::Location;
32use std::pin::Pin;
33use std::ptr::NonNull;
34use std::task::{Context, Poll, Waker};
35
36/// The task cell. Contains the components of the task.
37///
38/// It is critical for `Header` to be the first field as the task structure will
39/// be referenced by both *mut Cell and *mut Header.
40///
41/// Any changes to the layout of this struct _must_ also be reflected in the
42/// `const` fns in raw.rs.
43///
44// # This struct should be cache padded to avoid false sharing. The cache padding rules are copied
45// from crossbeam-utils/src/cache_padded.rs
46//
47// Starting from Intel's Sandy Bridge, spatial prefetcher is now pulling pairs of 64-byte cache
48// lines at a time, so we have to align to 128 bytes rather than 64.
49//
50// Sources:
51// - https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf
52// - https://github.com/facebook/folly/blob/1b5288e6eea6df074758f877c849b6e73bbb9fbb/folly/lang/Align.h#L107
53//
54// ARM's big.LITTLE architecture has asymmetric cores and "big" cores have 128-byte cache line size.
55//
56// Sources:
57// - https://www.mono-project.com/news/2016/09/12/arm64-icache/
58//
59// powerpc64 has 128-byte cache line size.
60//
61// Sources:
62// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_ppc64x.go#L9
63#[cfg_attr(
64    any(
65        target_arch = "x86_64",
66        target_arch = "aarch64",
67        target_arch = "powerpc64",
68    ),
69    repr(align(128))
70)]
71// arm, mips, mips64, sparc, and hexagon have 32-byte cache line size.
72//
73// Sources:
74// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_arm.go#L7
75// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips.go#L7
76// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mipsle.go#L7
77// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_mips64x.go#L9
78// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L17
79// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/hexagon/include/asm/cache.h#L12
80#[cfg_attr(
81    any(
82        target_arch = "arm",
83        target_arch = "mips",
84        target_arch = "mips64",
85        target_arch = "sparc",
86        target_arch = "hexagon",
87    ),
88    repr(align(32))
89)]
90// m68k has 16-byte cache line size.
91//
92// Sources:
93// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/m68k/include/asm/cache.h#L9
94#[cfg_attr(target_arch = "m68k", repr(align(16)))]
95// s390x has 256-byte cache line size.
96//
97// Sources:
98// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_s390x.go#L7
99// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/s390/include/asm/cache.h#L13
100#[cfg_attr(target_arch = "s390x", repr(align(256)))]
101// x86, riscv, wasm, and sparc64 have 64-byte cache line size.
102//
103// Sources:
104// - https://github.com/golang/go/blob/dda2991c2ea0c5914714469c4defc2562a907230/src/internal/cpu/cpu_x86.go#L9
105// - https://github.com/golang/go/blob/3dd58676054223962cd915bb0934d1f9f489d4d2/src/internal/cpu/cpu_wasm.go#L7
106// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/sparc/include/asm/cache.h#L19
107// - https://github.com/torvalds/linux/blob/3516bd729358a2a9b090c1905bd2a3fa926e24c6/arch/riscv/include/asm/cache.h#L10
108//
109// All others are assumed to have 64-byte cache line size.
110#[cfg_attr(
111    not(any(
112        target_arch = "x86_64",
113        target_arch = "aarch64",
114        target_arch = "powerpc64",
115        target_arch = "arm",
116        target_arch = "mips",
117        target_arch = "mips64",
118        target_arch = "sparc",
119        target_arch = "hexagon",
120        target_arch = "m68k",
121        target_arch = "s390x",
122    )),
123    repr(align(64))
124)]
125#[repr(C)]
126pub(super) struct Cell<T: Future, S> {
127    /// Hot task state data
128    pub(super) header: Header,
129
130    /// Either the future or output, depending on the execution stage.
131    pub(super) core: Core<T, S>,
132
133    /// Cold data
134    pub(super) trailer: Trailer,
135}
136
137pub(super) struct CoreStage<T: Future> {
138    stage: UnsafeCell<Stage<T>>,
139}
140
141/// The core of the task.
142///
143/// Holds the future or output, depending on the stage of execution.
144///
145/// Any changes to the layout of this struct _must_ also be reflected in the
146/// `const` fns in raw.rs.
147#[repr(C)]
148pub(super) struct Core<T: Future, S> {
149    /// Scheduler used to drive this future.
150    pub(super) scheduler: S,
151
152    /// The task's ID, used for populating `JoinError`s.
153    pub(super) task_id: Id,
154
155    /// The source code location where the task was spawned.
156    ///
157    /// This is used for populating the `TaskMeta` passed to the task runtime
158    /// hooks.
159    #[cfg(tokio_unstable)]
160    pub(super) spawned_at: &'static Location<'static>,
161
162    /// Either the future or the output.
163    pub(super) stage: CoreStage<T>,
164}
165
166/// Crate public as this is also needed by the pool.
167#[repr(C)]
168pub(crate) struct Header {
169    /// Task state.
170    pub(super) state: State,
171
172    /// Pointer to next task, used with the injection queue.
173    pub(super) queue_next: UnsafeCell<Option<NonNull<Header>>>,
174
175    /// Table of function pointers for executing actions on the task.
176    pub(super) vtable: &'static Vtable,
177
178    /// This integer contains the id of the `OwnedTasks` or `LocalOwnedTasks`
179    /// that this task is stored in. If the task is not in any list, should be
180    /// the id of the list that it was previously in, or `None` if it has never
181    /// been in any list.
182    ///
183    /// Once a task has been bound to a list, it can never be bound to another
184    /// list, even if removed from the first list.
185    ///
186    /// The id is not unset when removed from a list because we want to be able
187    /// to read the id without synchronization, even if it is concurrently being
188    /// removed from the list.
189    pub(super) owner_id: UnsafeCell<Option<NonZeroU64>>,
190
191    /// The tracing ID for this instrumented task.
192    #[cfg(all(tokio_unstable, feature = "tracing"))]
193    pub(super) tracing_id: Option<tracing::Id>,
194}
195
196unsafe impl Send for Header {}
197unsafe impl Sync for Header {}
198
199/// Cold data is stored after the future. Data is considered cold if it is only
200/// used during creation or shutdown of the task.
201pub(super) struct Trailer {
202    /// Pointers for the linked list in the `OwnedTasks` that owns this task.
203    pub(super) owned: linked_list::Pointers<Header>,
204    /// Consumer task waiting on completion of this task.
205    pub(super) waker: UnsafeCell<Option<Waker>>,
206    /// Optional hooks needed in the harness.
207    pub(super) hooks: TaskHarnessScheduleHooks,
208}
209
210generate_addr_of_methods! {
211    impl<> Trailer {
212        pub(super) unsafe fn addr_of_owned(self: NonNull<Self>) -> NonNull<linked_list::Pointers<Header>> {
213            &self.owned
214        }
215    }
216}
217
218/// Either the future or the output.
219#[repr(C)] // https://github.com/rust-lang/miri/issues/3780
220pub(super) enum Stage<T: Future> {
221    Running(T),
222    Finished(super::Result<T::Output>),
223    Consumed,
224}
225
226impl<T: Future, S: Schedule> Cell<T, S> {
227    /// Allocates a new task cell, containing the header, trailer, and core
228    /// structures.
229    pub(super) fn new(
230        future: T,
231        scheduler: S,
232        state: State,
233        task_id: Id,
234        #[cfg(tokio_unstable)] spawned_at: &'static Location<'static>,
235    ) -> Box<Cell<T, S>> {
236        // Separated into a non-generic function to reduce LLVM codegen
237        fn new_header(
238            state: State,
239            vtable: &'static Vtable,
240            #[cfg(all(tokio_unstable, feature = "tracing"))] tracing_id: Option<tracing::Id>,
241        ) -> Header {
242            Header {
243                state,
244                queue_next: UnsafeCell::new(None),
245                vtable,
246                owner_id: UnsafeCell::new(None),
247                #[cfg(all(tokio_unstable, feature = "tracing"))]
248                tracing_id,
249            }
250        }
251
252        #[cfg(all(tokio_unstable, feature = "tracing"))]
253        let tracing_id = future.id();
254        let vtable = raw::vtable::<T, S>();
255        let result = Box::new(Cell {
256            trailer: Trailer::new(scheduler.hooks()),
257            header: new_header(
258                state,
259                vtable,
260                #[cfg(all(tokio_unstable, feature = "tracing"))]
261                tracing_id,
262            ),
263            core: Core {
264                scheduler,
265                stage: CoreStage {
266                    stage: UnsafeCell::new(Stage::Running(future)),
267                },
268                task_id,
269                #[cfg(tokio_unstable)]
270                spawned_at,
271            },
272        });
273
274        #[cfg(debug_assertions)]
275        {
276            // Using a separate function for this code avoids instantiating it separately for every `T`.
277            unsafe fn check<S>(
278                header: &Header,
279                trailer: &Trailer,
280                scheduler: &S,
281                task_id: &Id,
282                #[cfg(tokio_unstable)] spawn_location: &&'static Location<'static>,
283            ) {
284                let trailer_addr = trailer as *const Trailer as usize;
285                let trailer_ptr = unsafe { Header::get_trailer(NonNull::from(header)) };
286                assert_eq!(trailer_addr, trailer_ptr.as_ptr() as usize);
287
288                let scheduler_addr = scheduler as *const S as usize;
289                let scheduler_ptr = unsafe { Header::get_scheduler::<S>(NonNull::from(header)) };
290                assert_eq!(scheduler_addr, scheduler_ptr.as_ptr() as usize);
291
292                let id_addr = task_id as *const Id as usize;
293                let id_ptr = unsafe { Header::get_id_ptr(NonNull::from(header)) };
294                assert_eq!(id_addr, id_ptr.as_ptr() as usize);
295
296                #[cfg(tokio_unstable)]
297                {
298                    let spawn_location_addr =
299                        spawn_location as *const &'static Location<'static> as usize;
300                    let spawn_location_ptr =
301                        unsafe { Header::get_spawn_location_ptr(NonNull::from(header)) };
302                    assert_eq!(spawn_location_addr, spawn_location_ptr.as_ptr() as usize);
303                }
304            }
305            unsafe {
306                check(
307                    &result.header,
308                    &result.trailer,
309                    &result.core.scheduler,
310                    &result.core.task_id,
311                    #[cfg(tokio_unstable)]
312                    &result.core.spawned_at,
313                );
314            }
315        }
316
317        result
318    }
319}
320
321impl<T: Future> CoreStage<T> {
322    pub(super) fn with_mut<R>(&self, f: impl FnOnce(*mut Stage<T>) -> R) -> R {
323        self.stage.with_mut(f)
324    }
325}
326
327/// Set and clear the task id in the context when the future is executed or
328/// dropped, or when the output produced by the future is dropped.
329pub(crate) struct TaskIdGuard {
330    parent_task_id: Option<Id>,
331}
332
333impl TaskIdGuard {
334    fn enter(id: Id) -> Self {
335        TaskIdGuard {
336            parent_task_id: context::set_current_task_id(Some(id)),
337        }
338    }
339}
340
341impl Drop for TaskIdGuard {
342    fn drop(&mut self) {
343        context::set_current_task_id(self.parent_task_id);
344    }
345}
346
347impl<T: Future, S: Schedule> Core<T, S> {
348    /// Polls the future.
349    ///
350    /// # Safety
351    ///
352    /// The caller must ensure it is safe to mutate the `state` field. This
353    /// requires ensuring mutual exclusion between any concurrent thread that
354    /// might modify the future or output field.
355    ///
356    /// The mutual exclusion is implemented by `Harness` and the `Lifecycle`
357    /// component of the task state.
358    ///
359    /// `self` must also be pinned. This is handled by storing the task on the
360    /// heap.
361    pub(super) fn poll(&self, mut cx: Context<'_>) -> Poll<T::Output> {
362        let res = {
363            self.stage.stage.with_mut(|ptr| {
364                // Safety: The caller ensures mutual exclusion to the field.
365                let future = match unsafe { &mut *ptr } {
366                    Stage::Running(future) => future,
367                    _ => unreachable!("unexpected stage"),
368                };
369
370                // Safety: The caller ensures the future is pinned.
371                let future = unsafe { Pin::new_unchecked(future) };
372
373                let _guard = TaskIdGuard::enter(self.task_id);
374                future.poll(&mut cx)
375            })
376        };
377
378        if res.is_ready() {
379            self.drop_future_or_output();
380        }
381
382        res
383    }
384
385    /// Drops the future.
386    ///
387    /// # Safety
388    ///
389    /// The caller must ensure it is safe to mutate the `stage` field.
390    pub(super) fn drop_future_or_output(&self) {
391        // Safety: the caller ensures mutual exclusion to the field.
392        unsafe {
393            self.set_stage(Stage::Consumed);
394        }
395    }
396
397    /// Stores the task output.
398    ///
399    /// # Safety
400    ///
401    /// The caller must ensure it is safe to mutate the `stage` field.
402    pub(super) fn store_output(&self, output: super::Result<T::Output>) {
403        // Safety: the caller ensures mutual exclusion to the field.
404        unsafe {
405            self.set_stage(Stage::Finished(output));
406        }
407    }
408
409    /// Takes the task output.
410    ///
411    /// # Safety
412    ///
413    /// The caller must ensure it is safe to mutate the `stage` field.
414    pub(super) fn take_output(&self) -> super::Result<T::Output> {
415        use std::mem;
416
417        self.stage.stage.with_mut(|ptr| {
418            // Safety:: the caller ensures mutual exclusion to the field.
419            match mem::replace(unsafe { &mut *ptr }, Stage::Consumed) {
420                Stage::Finished(output) => output,
421                _ => panic!("JoinHandle polled after completion"),
422            }
423        })
424    }
425
426    unsafe fn set_stage(&self, stage: Stage<T>) {
427        let _guard = TaskIdGuard::enter(self.task_id);
428        self.stage.stage.with_mut(|ptr| *ptr = stage);
429    }
430}
431
432impl Header {
433    pub(super) unsafe fn set_next(&self, next: Option<NonNull<Header>>) {
434        self.queue_next.with_mut(|ptr| *ptr = next);
435    }
436
437    // safety: The caller must guarantee exclusive access to this field, and
438    // must ensure that the id is either `None` or the id of the OwnedTasks
439    // containing this task.
440    pub(super) unsafe fn set_owner_id(&self, owner: NonZeroU64) {
441        self.owner_id.with_mut(|ptr| *ptr = Some(owner));
442    }
443
444    pub(super) fn get_owner_id(&self) -> Option<NonZeroU64> {
445        // safety: If there are concurrent writes, then that write has violated
446        // the safety requirements on `set_owner_id`.
447        unsafe { self.owner_id.with(|ptr| *ptr) }
448    }
449
450    /// Gets a pointer to the `Trailer` of the task containing this `Header`.
451    ///
452    /// # Safety
453    ///
454    /// The provided raw pointer must point at the header of a task.
455    pub(super) unsafe fn get_trailer(me: NonNull<Header>) -> NonNull<Trailer> {
456        let offset = me.as_ref().vtable.trailer_offset;
457        let trailer = me.as_ptr().cast::<u8>().add(offset).cast::<Trailer>();
458        NonNull::new_unchecked(trailer)
459    }
460
461    /// Gets a pointer to the scheduler of the task containing this `Header`.
462    ///
463    /// # Safety
464    ///
465    /// The provided raw pointer must point at the header of a task.
466    ///
467    /// The generic type S must be set to the correct scheduler type for this
468    /// task.
469    pub(super) unsafe fn get_scheduler<S>(me: NonNull<Header>) -> NonNull<S> {
470        let offset = me.as_ref().vtable.scheduler_offset;
471        let scheduler = me.as_ptr().cast::<u8>().add(offset).cast::<S>();
472        NonNull::new_unchecked(scheduler)
473    }
474
475    /// Gets a pointer to the id of the task containing this `Header`.
476    ///
477    /// # Safety
478    ///
479    /// The provided raw pointer must point at the header of a task.
480    pub(super) unsafe fn get_id_ptr(me: NonNull<Header>) -> NonNull<Id> {
481        let offset = me.as_ref().vtable.id_offset;
482        let id = me.as_ptr().cast::<u8>().add(offset).cast::<Id>();
483        NonNull::new_unchecked(id)
484    }
485
486    /// Gets the id of the task containing this `Header`.
487    ///
488    /// # Safety
489    ///
490    /// The provided raw pointer must point at the header of a task.
491    pub(super) unsafe fn get_id(me: NonNull<Header>) -> Id {
492        let ptr = Header::get_id_ptr(me).as_ptr();
493        *ptr
494    }
495
496    /// Gets a pointer to the source code location where the task containing
497    /// this `Header` was spawned.
498    ///
499    /// # Safety
500    ///
501    /// The provided raw pointer must point at the header of a task.
502    #[cfg(tokio_unstable)]
503    pub(super) unsafe fn get_spawn_location_ptr(
504        me: NonNull<Header>,
505    ) -> NonNull<&'static Location<'static>> {
506        let offset = me.as_ref().vtable.spawn_location_offset;
507        let spawned_at = me
508            .as_ptr()
509            .cast::<u8>()
510            .add(offset)
511            .cast::<&'static Location<'static>>();
512        NonNull::new_unchecked(spawned_at)
513    }
514
515    /// Gets the source code location where the task containing
516    /// this `Header` was spawned
517    ///
518    /// # Safety
519    ///
520    /// The provided raw pointer must point at the header of a task.
521    #[cfg(tokio_unstable)]
522    pub(super) unsafe fn get_spawn_location(me: NonNull<Header>) -> &'static Location<'static> {
523        let ptr = Header::get_spawn_location_ptr(me).as_ptr();
524        *ptr
525    }
526
527    /// Gets the tracing id of the task containing this `Header`.
528    ///
529    /// # Safety
530    ///
531    /// The provided raw pointer must point at the header of a task.
532    #[cfg(all(tokio_unstable, feature = "tracing"))]
533    pub(super) unsafe fn get_tracing_id(me: &NonNull<Header>) -> Option<&tracing::Id> {
534        me.as_ref().tracing_id.as_ref()
535    }
536}
537
538impl Trailer {
539    fn new(hooks: TaskHarnessScheduleHooks) -> Self {
540        Trailer {
541            waker: UnsafeCell::new(None),
542            owned: linked_list::Pointers::new(),
543            hooks,
544        }
545    }
546
547    pub(super) unsafe fn set_waker(&self, waker: Option<Waker>) {
548        self.waker.with_mut(|ptr| {
549            *ptr = waker;
550        });
551    }
552
553    pub(super) unsafe fn will_wake(&self, waker: &Waker) -> bool {
554        self.waker
555            .with(|ptr| (*ptr).as_ref().unwrap().will_wake(waker))
556    }
557
558    pub(super) fn wake_join(&self) {
559        self.waker.with(|ptr| match unsafe { &*ptr } {
560            Some(waker) => waker.wake_by_ref(),
561            None => panic!("waker missing"),
562        });
563    }
564}
565
566#[test]
567#[cfg(not(loom))]
568fn header_lte_cache_line() {
569    assert!(std::mem::size_of::<Header>() <= 8 * std::mem::size_of::<*const ()>());
570}