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