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