xref: /linux-6.15/rust/kernel/task.rs (revision ebf2b8a7)
1313c4281SWedson Almeida Filho // SPDX-License-Identifier: GPL-2.0
2313c4281SWedson Almeida Filho 
3313c4281SWedson Almeida Filho //! Tasks (threads and processes).
4313c4281SWedson Almeida Filho //!
5bc2e7d5cSMiguel Ojeda //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
6313c4281SWedson Almeida Filho 
7313c4281SWedson Almeida Filho use crate::{bindings, types::Opaque};
8f090f0d0SAlice Ryhl use core::{
9f090f0d0SAlice Ryhl     ffi::{c_int, c_long, c_uint},
10f090f0d0SAlice Ryhl     marker::PhantomData,
11f090f0d0SAlice Ryhl     ops::Deref,
12f090f0d0SAlice Ryhl     ptr,
13f090f0d0SAlice Ryhl };
14e7b9b1ffSAlice Ryhl 
15e7b9b1ffSAlice Ryhl /// A sentinel value used for infinite timeouts.
16e7b9b1ffSAlice Ryhl pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
178da7a2b7SWedson Almeida Filho 
18f090f0d0SAlice Ryhl /// Bitmask for tasks that are sleeping in an interruptible state.
19f090f0d0SAlice Ryhl pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
20f090f0d0SAlice Ryhl /// Bitmask for tasks that are sleeping in an uninterruptible state.
21f090f0d0SAlice Ryhl pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
22f090f0d0SAlice Ryhl /// Convenience constant for waking up tasks regardless of whether they are in interruptible or
23f090f0d0SAlice Ryhl /// uninterruptible sleep.
24f090f0d0SAlice Ryhl pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
25f090f0d0SAlice Ryhl 
268da7a2b7SWedson Almeida Filho /// Returns the currently running task.
278da7a2b7SWedson Almeida Filho #[macro_export]
288da7a2b7SWedson Almeida Filho macro_rules! current {
298da7a2b7SWedson Almeida Filho     () => {
308da7a2b7SWedson Almeida Filho         // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the
318da7a2b7SWedson Almeida Filho         // caller.
328da7a2b7SWedson Almeida Filho         unsafe { &*$crate::task::Task::current() }
338da7a2b7SWedson Almeida Filho     };
348da7a2b7SWedson Almeida Filho }
35313c4281SWedson Almeida Filho 
36313c4281SWedson Almeida Filho /// Wraps the kernel's `struct task_struct`.
37313c4281SWedson Almeida Filho ///
38313c4281SWedson Almeida Filho /// # Invariants
39313c4281SWedson Almeida Filho ///
40313c4281SWedson Almeida Filho /// All instances are valid tasks created by the C portion of the kernel.
41313c4281SWedson Almeida Filho ///
42*ebf2b8a7SValentin Obst /// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
43313c4281SWedson Almeida Filho /// that the allocation remains valid at least until the matching call to `put_task_struct`.
448da7a2b7SWedson Almeida Filho ///
458da7a2b7SWedson Almeida Filho /// # Examples
468da7a2b7SWedson Almeida Filho ///
478da7a2b7SWedson Almeida Filho /// The following is an example of getting the PID of the current thread with zero additional cost
488da7a2b7SWedson Almeida Filho /// when compared to the C version:
498da7a2b7SWedson Almeida Filho ///
508da7a2b7SWedson Almeida Filho /// ```
518da7a2b7SWedson Almeida Filho /// let pid = current!().pid();
528da7a2b7SWedson Almeida Filho /// ```
538da7a2b7SWedson Almeida Filho ///
548da7a2b7SWedson Almeida Filho /// Getting the PID of the current process, also zero additional cost:
558da7a2b7SWedson Almeida Filho ///
568da7a2b7SWedson Almeida Filho /// ```
578da7a2b7SWedson Almeida Filho /// let pid = current!().group_leader().pid();
588da7a2b7SWedson Almeida Filho /// ```
598da7a2b7SWedson Almeida Filho ///
608da7a2b7SWedson Almeida Filho /// Getting the current task and storing it in some struct. The reference count is automatically
618da7a2b7SWedson Almeida Filho /// incremented when creating `State` and decremented when it is dropped:
628da7a2b7SWedson Almeida Filho ///
638da7a2b7SWedson Almeida Filho /// ```
648da7a2b7SWedson Almeida Filho /// use kernel::{task::Task, types::ARef};
658da7a2b7SWedson Almeida Filho ///
668da7a2b7SWedson Almeida Filho /// struct State {
678da7a2b7SWedson Almeida Filho ///     creator: ARef<Task>,
688da7a2b7SWedson Almeida Filho ///     index: u32,
698da7a2b7SWedson Almeida Filho /// }
708da7a2b7SWedson Almeida Filho ///
718da7a2b7SWedson Almeida Filho /// impl State {
728da7a2b7SWedson Almeida Filho ///     fn new() -> Self {
738da7a2b7SWedson Almeida Filho ///         Self {
748da7a2b7SWedson Almeida Filho ///             creator: current!().into(),
758da7a2b7SWedson Almeida Filho ///             index: 0,
768da7a2b7SWedson Almeida Filho ///         }
778da7a2b7SWedson Almeida Filho ///     }
788da7a2b7SWedson Almeida Filho /// }
798da7a2b7SWedson Almeida Filho /// ```
80313c4281SWedson Almeida Filho #[repr(transparent)]
81313c4281SWedson Almeida Filho pub struct Task(pub(crate) Opaque<bindings::task_struct>);
82313c4281SWedson Almeida Filho 
83d09a6102SAlice Ryhl // SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
84d09a6102SAlice Ryhl // `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
85d09a6102SAlice Ryhl // which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
86d09a6102SAlice Ryhl // runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
87d09a6102SAlice Ryhl unsafe impl Send for Task {}
88d09a6102SAlice Ryhl 
89d09a6102SAlice Ryhl // SAFETY: It's OK to access `Task` through shared references from other threads because we're
90d09a6102SAlice Ryhl // either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
91313c4281SWedson Almeida Filho // synchronised by C code (e.g., `signal_pending`).
92313c4281SWedson Almeida Filho unsafe impl Sync for Task {}
93313c4281SWedson Almeida Filho 
94313c4281SWedson Almeida Filho /// The type of process identifiers (PIDs).
95313c4281SWedson Almeida Filho type Pid = bindings::pid_t;
96313c4281SWedson Almeida Filho 
97313c4281SWedson Almeida Filho impl Task {
988da7a2b7SWedson Almeida Filho     /// Returns a task reference for the currently executing task/thread.
998da7a2b7SWedson Almeida Filho     ///
1008da7a2b7SWedson Almeida Filho     /// The recommended way to get the current task/thread is to use the
101c61bcc27SMiguel Ojeda     /// [`current`] macro because it is safe.
1028da7a2b7SWedson Almeida Filho     ///
1038da7a2b7SWedson Almeida Filho     /// # Safety
1048da7a2b7SWedson Almeida Filho     ///
1058da7a2b7SWedson Almeida Filho     /// Callers must ensure that the returned object doesn't outlive the current task/thread.
1068da7a2b7SWedson Almeida Filho     pub unsafe fn current() -> impl Deref<Target = Task> {
1078da7a2b7SWedson Almeida Filho         struct TaskRef<'a> {
1088da7a2b7SWedson Almeida Filho             task: &'a Task,
1098da7a2b7SWedson Almeida Filho             _not_send: PhantomData<*mut ()>,
1108da7a2b7SWedson Almeida Filho         }
1118da7a2b7SWedson Almeida Filho 
1128da7a2b7SWedson Almeida Filho         impl Deref for TaskRef<'_> {
1138da7a2b7SWedson Almeida Filho             type Target = Task;
1148da7a2b7SWedson Almeida Filho 
1158da7a2b7SWedson Almeida Filho             fn deref(&self) -> &Self::Target {
1168da7a2b7SWedson Almeida Filho                 self.task
1178da7a2b7SWedson Almeida Filho             }
1188da7a2b7SWedson Almeida Filho         }
1198da7a2b7SWedson Almeida Filho 
1208da7a2b7SWedson Almeida Filho         // SAFETY: Just an FFI call with no additional safety requirements.
1218da7a2b7SWedson Almeida Filho         let ptr = unsafe { bindings::get_current() };
1228da7a2b7SWedson Almeida Filho 
1238da7a2b7SWedson Almeida Filho         TaskRef {
1248da7a2b7SWedson Almeida Filho             // SAFETY: If the current thread is still running, the current task is valid. Given
1258da7a2b7SWedson Almeida Filho             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
1268da7a2b7SWedson Almeida Filho             // (where it could potentially outlive the caller).
1278da7a2b7SWedson Almeida Filho             task: unsafe { &*ptr.cast() },
1288da7a2b7SWedson Almeida Filho             _not_send: PhantomData,
1298da7a2b7SWedson Almeida Filho         }
1308da7a2b7SWedson Almeida Filho     }
1318da7a2b7SWedson Almeida Filho 
132313c4281SWedson Almeida Filho     /// Returns the group leader of the given task.
133313c4281SWedson Almeida Filho     pub fn group_leader(&self) -> &Task {
134313c4281SWedson Almeida Filho         // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
135313c4281SWedson Almeida Filho         // have a valid group_leader.
136313c4281SWedson Almeida Filho         let ptr = unsafe { *ptr::addr_of!((*self.0.get()).group_leader) };
137313c4281SWedson Almeida Filho 
138313c4281SWedson Almeida Filho         // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
139313c4281SWedson Almeida Filho         // and given that a task has a reference to its group leader, we know it must be valid for
140313c4281SWedson Almeida Filho         // the lifetime of the returned task reference.
141313c4281SWedson Almeida Filho         unsafe { &*ptr.cast() }
142313c4281SWedson Almeida Filho     }
143313c4281SWedson Almeida Filho 
144313c4281SWedson Almeida Filho     /// Returns the PID of the given task.
145313c4281SWedson Almeida Filho     pub fn pid(&self) -> Pid {
146313c4281SWedson Almeida Filho         // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
147313c4281SWedson Almeida Filho         // have a valid pid.
148313c4281SWedson Almeida Filho         unsafe { *ptr::addr_of!((*self.0.get()).pid) }
149313c4281SWedson Almeida Filho     }
150313c4281SWedson Almeida Filho 
151313c4281SWedson Almeida Filho     /// Determines whether the given task has pending signals.
152313c4281SWedson Almeida Filho     pub fn signal_pending(&self) -> bool {
153313c4281SWedson Almeida Filho         // SAFETY: By the type invariant, we know that `self.0` is valid.
154313c4281SWedson Almeida Filho         unsafe { bindings::signal_pending(self.0.get()) != 0 }
155313c4281SWedson Almeida Filho     }
156313c4281SWedson Almeida Filho 
157313c4281SWedson Almeida Filho     /// Wakes up the task.
158313c4281SWedson Almeida Filho     pub fn wake_up(&self) {
159313c4281SWedson Almeida Filho         // SAFETY: By the type invariant, we know that `self.0.get()` is non-null and valid.
160313c4281SWedson Almeida Filho         // And `wake_up_process` is safe to be called for any valid task, even if the task is
161313c4281SWedson Almeida Filho         // running.
162313c4281SWedson Almeida Filho         unsafe { bindings::wake_up_process(self.0.get()) };
163313c4281SWedson Almeida Filho     }
164313c4281SWedson Almeida Filho }
165313c4281SWedson Almeida Filho 
166*ebf2b8a7SValentin Obst // SAFETY: The type invariants guarantee that `Task` is always refcounted.
167313c4281SWedson Almeida Filho unsafe impl crate::types::AlwaysRefCounted for Task {
168313c4281SWedson Almeida Filho     fn inc_ref(&self) {
169313c4281SWedson Almeida Filho         // SAFETY: The existence of a shared reference means that the refcount is nonzero.
170313c4281SWedson Almeida Filho         unsafe { bindings::get_task_struct(self.0.get()) };
171313c4281SWedson Almeida Filho     }
172313c4281SWedson Almeida Filho 
173313c4281SWedson Almeida Filho     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
174313c4281SWedson Almeida Filho         // SAFETY: The safety requirements guarantee that the refcount is nonzero.
175313c4281SWedson Almeida Filho         unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
176313c4281SWedson Almeida Filho     }
177313c4281SWedson Almeida Filho }
178