Skip to main content

kernel/
task.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! Tasks (threads and processes).
4//!
5//! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
6
7use crate::ffi::{c_int, c_long, c_uint};
8use crate::types::Opaque;
9use core::{marker::PhantomData, ops::Deref, ptr};
10
11/// A sentinel value used for infinite timeouts.
12pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
13
14/// Bitmask for tasks that are sleeping in an interruptible state.
15pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
16/// Bitmask for tasks that are sleeping in an uninterruptible state.
17pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
18/// Convenience constant for waking up tasks regardless of whether they are in interruptible or
19/// uninterruptible sleep.
20pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
21
22/// Returns the currently running task.
23#[macro_export]
24macro_rules! current {
25    () => {
26        // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the
27        // caller.
28        unsafe { &*$crate::task::Task::current() }
29    };
30}
31
32/// Wraps the kernel's `struct task_struct`.
33///
34/// # Invariants
35///
36/// All instances are valid tasks created by the C portion of the kernel.
37///
38/// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
39/// that the allocation remains valid at least until the matching call to `put_task_struct`.
40///
41/// # Examples
42///
43/// The following is an example of getting the PID of the current thread with zero additional cost
44/// when compared to the C version:
45///
46/// ```
47/// let pid = current!().pid();
48/// ```
49///
50/// Getting the PID of the current process, also zero additional cost:
51///
52/// ```
53/// let pid = current!().group_leader().pid();
54/// ```
55///
56/// Getting the current task and storing it in some struct. The reference count is automatically
57/// incremented when creating `State` and decremented when it is dropped:
58///
59/// ```
60/// use kernel::{task::Task, types::ARef};
61///
62/// struct State {
63///     creator: ARef<Task>,
64///     index: u32,
65/// }
66///
67/// impl State {
68///     fn new() -> Self {
69///         Self {
70///             creator: current!().into(),
71///             index: 0,
72///         }
73///     }
74/// }
75/// ```
76#[repr(transparent)]
77pub struct Task(pub(crate) Opaque<bindings::task_struct>);
78
79// SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
80// `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
81// which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
82// runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
83unsafe impl Send for Task {}
84
85// SAFETY: It's OK to access `Task` through shared references from other threads because we're
86// either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
87// synchronised by C code (e.g., `signal_pending`).
88unsafe impl Sync for Task {}
89
90/// The type of process identifiers (PIDs).
91type Pid = bindings::pid_t;
92
93impl Task {
94    /// Returns a task reference for the currently executing task/thread.
95    ///
96    /// The recommended way to get the current task/thread is to use the
97    /// [`current`] macro because it is safe.
98    ///
99    /// # Safety
100    ///
101    /// Callers must ensure that the returned object doesn't outlive the current task/thread.
102    pub unsafe fn current() -> impl Deref<Target = Task> {
103        struct TaskRef<'a> {
104            task: &'a Task,
105            _not_send: PhantomData<*mut ()>,
106        }
107
108        impl Deref for TaskRef<'_> {
109            type Target = Task;
110
111            fn deref(&self) -> &Self::Target {
112                self.task
113            }
114        }
115
116        // SAFETY: Just an FFI call with no additional safety requirements.
117        let ptr = unsafe { bindings::get_current() };
118
119        TaskRef {
120            // SAFETY: If the current thread is still running, the current task is valid. Given
121            // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
122            // (where it could potentially outlive the caller).
123            task: unsafe { &*ptr.cast() },
124            _not_send: PhantomData,
125        }
126    }
127
128    /// Returns the group leader of the given task.
129    pub fn group_leader(&self) -> &Task {
130        // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
131        // have a valid `group_leader`.
132        let ptr = unsafe { *ptr::addr_of!((*self.0.get()).group_leader) };
133
134        // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
135        // and given that a task has a reference to its group leader, we know it must be valid for
136        // the lifetime of the returned task reference.
137        unsafe { &*ptr.cast() }
138    }
139
140    /// Returns the PID of the given task.
141    pub fn pid(&self) -> Pid {
142        // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
143        // have a valid pid.
144        unsafe { *ptr::addr_of!((*self.0.get()).pid) }
145    }
146
147    /// Determines whether the given task has pending signals.
148    pub fn signal_pending(&self) -> bool {
149        // SAFETY: By the type invariant, we know that `self.0` is valid.
150        unsafe { bindings::signal_pending(self.0.get()) != 0 }
151    }
152
153    /// Wakes up the task.
154    pub fn wake_up(&self) {
155        // SAFETY: By the type invariant, we know that `self.0.get()` is non-null and valid.
156        // And `wake_up_process` is safe to be called for any valid task, even if the task is
157        // running.
158        unsafe { bindings::wake_up_process(self.0.get()) };
159    }
160}
161
162// SAFETY: The type invariants guarantee that `Task` is always refcounted.
163unsafe impl crate::types::AlwaysRefCounted for Task {
164    fn inc_ref(&self) {
165        // SAFETY: The existence of a shared reference means that the refcount is nonzero.
166        unsafe { bindings::get_task_struct(self.0.get()) };
167    }
168
169    unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
170        // SAFETY: The safety requirements guarantee that the refcount is nonzero.
171        unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
172    }
173}