xref: /linux/rust/kernel/task.rs (revision 9d8a2b033db179bef9b6b5bad492f611a0fe89b7)
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     cmp::{Eq, PartialEq},
13     ffi::{c_int, c_long, c_uint},
14     ops::Deref,
15     ptr,
16 };
17 
18 /// A sentinel value used for infinite timeouts.
19 pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
20 
21 /// Bitmask for tasks that are sleeping in an interruptible state.
22 pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
23 /// Bitmask for tasks that are sleeping in an uninterruptible state.
24 pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
25 /// Convenience constant for waking up tasks regardless of whether they are in interruptible or
26 /// uninterruptible sleep.
27 pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
28 
29 /// Returns the currently running task.
30 #[macro_export]
31 macro_rules! current {
32     () => {
33         // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the
34         // caller.
35         unsafe { &*$crate::task::Task::current() }
36     };
37 }
38 
39 /// Wraps the kernel's `struct task_struct`.
40 ///
41 /// # Invariants
42 ///
43 /// All instances are valid tasks created by the C portion of the kernel.
44 ///
45 /// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
46 /// that the allocation remains valid at least until the matching call to `put_task_struct`.
47 ///
48 /// # Examples
49 ///
50 /// The following is an example of getting the PID of the current thread with zero additional cost
51 /// when compared to the C version:
52 ///
53 /// ```
54 /// let pid = current!().pid();
55 /// ```
56 ///
57 /// Getting the PID of the current process, also zero additional cost:
58 ///
59 /// ```
60 /// let pid = current!().group_leader().pid();
61 /// ```
62 ///
63 /// Getting the current task and storing it in some struct. The reference count is automatically
64 /// incremented when creating `State` and decremented when it is dropped:
65 ///
66 /// ```
67 /// use kernel::{task::Task, types::ARef};
68 ///
69 /// struct State {
70 ///     creator: ARef<Task>,
71 ///     index: u32,
72 /// }
73 ///
74 /// impl State {
75 ///     fn new() -> Self {
76 ///         Self {
77 ///             creator: current!().into(),
78 ///             index: 0,
79 ///         }
80 ///     }
81 /// }
82 /// ```
83 #[repr(transparent)]
84 pub struct Task(pub(crate) Opaque<bindings::task_struct>);
85 
86 // SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
87 // `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
88 // which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
89 // runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
90 unsafe impl Send for Task {}
91 
92 // SAFETY: It's OK to access `Task` through shared references from other threads because we're
93 // either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
94 // synchronised by C code (e.g., `signal_pending`).
95 unsafe impl Sync for Task {}
96 
97 /// The type of process identifiers (PIDs).
98 type Pid = bindings::pid_t;
99 
100 /// The type of user identifiers (UIDs).
101 #[derive(Copy, Clone)]
102 pub struct Kuid {
103     kuid: bindings::kuid_t,
104 }
105 
106 impl Task {
107     /// Returns a raw pointer to the current task.
108     ///
109     /// It is up to the user to use the pointer correctly.
110     #[inline]
111     pub fn current_raw() -> *mut bindings::task_struct {
112         // SAFETY: Getting the current pointer is always safe.
113         unsafe { bindings::get_current() }
114     }
115 
116     /// Returns a task reference for the currently executing task/thread.
117     ///
118     /// The recommended way to get the current task/thread is to use the
119     /// [`current`] macro because it is safe.
120     ///
121     /// # Safety
122     ///
123     /// Callers must ensure that the returned object doesn't outlive the current task/thread.
124     pub unsafe fn current() -> impl Deref<Target = Task> {
125         struct TaskRef<'a> {
126             task: &'a Task,
127             _not_send: NotThreadSafe,
128         }
129 
130         impl Deref for TaskRef<'_> {
131             type Target = Task;
132 
133             fn deref(&self) -> &Self::Target {
134                 self.task
135             }
136         }
137 
138         let current = Task::current_raw();
139         TaskRef {
140             // SAFETY: If the current thread is still running, the current task is valid. Given
141             // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
142             // (where it could potentially outlive the caller).
143             task: unsafe { &*current.cast() },
144             _not_send: NotThreadSafe,
145         }
146     }
147 
148     /// Returns a raw pointer to the task.
149     #[inline]
150     pub fn as_ptr(&self) -> *mut bindings::task_struct {
151         self.0.get()
152     }
153 
154     /// Returns the group leader of the given task.
155     pub fn group_leader(&self) -> &Task {
156         // SAFETY: The group leader of a task never changes after initialization, so reading this
157         // field is not a data race.
158         let ptr = unsafe { *ptr::addr_of!((*self.as_ptr()).group_leader) };
159 
160         // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
161         // and given that a task has a reference to its group leader, we know it must be valid for
162         // the lifetime of the returned task reference.
163         unsafe { &*ptr.cast() }
164     }
165 
166     /// Returns the PID of the given task.
167     pub fn pid(&self) -> Pid {
168         // SAFETY: The pid of a task never changes after initialization, so reading this field is
169         // not a data race.
170         unsafe { *ptr::addr_of!((*self.as_ptr()).pid) }
171     }
172 
173     /// Returns the UID of the given task.
174     pub fn uid(&self) -> Kuid {
175         // SAFETY: It's always safe to call `task_uid` on a valid task.
176         Kuid::from_raw(unsafe { bindings::task_uid(self.as_ptr()) })
177     }
178 
179     /// Returns the effective UID of the given task.
180     pub fn euid(&self) -> Kuid {
181         // SAFETY: It's always safe to call `task_euid` on a valid task.
182         Kuid::from_raw(unsafe { bindings::task_euid(self.as_ptr()) })
183     }
184 
185     /// Determines whether the given task has pending signals.
186     pub fn signal_pending(&self) -> bool {
187         // SAFETY: It's always safe to call `signal_pending` on a valid task.
188         unsafe { bindings::signal_pending(self.as_ptr()) != 0 }
189     }
190 
191     /// Returns the given task's pid in the current pid namespace.
192     pub fn pid_in_current_ns(&self) -> Pid {
193         // SAFETY: It's valid to pass a null pointer as the namespace (defaults to current
194         // namespace). The task pointer is also valid.
195         unsafe { bindings::task_tgid_nr_ns(self.as_ptr(), ptr::null_mut()) }
196     }
197 
198     /// Wakes up the task.
199     pub fn wake_up(&self) {
200         // SAFETY: It's always safe to call `signal_pending` on a valid task, even if the task
201         // running.
202         unsafe { bindings::wake_up_process(self.as_ptr()) };
203     }
204 }
205 
206 // SAFETY: The type invariants guarantee that `Task` is always refcounted.
207 unsafe impl crate::types::AlwaysRefCounted for Task {
208     fn inc_ref(&self) {
209         // SAFETY: The existence of a shared reference means that the refcount is nonzero.
210         unsafe { bindings::get_task_struct(self.as_ptr()) };
211     }
212 
213     unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
214         // SAFETY: The safety requirements guarantee that the refcount is nonzero.
215         unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
216     }
217 }
218 
219 impl Kuid {
220     /// Get the current euid.
221     #[inline]
222     pub fn current_euid() -> Kuid {
223         // SAFETY: Just an FFI call.
224         Self::from_raw(unsafe { bindings::current_euid() })
225     }
226 
227     /// Create a `Kuid` given the raw C type.
228     #[inline]
229     pub fn from_raw(kuid: bindings::kuid_t) -> Self {
230         Self { kuid }
231     }
232 
233     /// Turn this kuid into the raw C type.
234     #[inline]
235     pub fn into_raw(self) -> bindings::kuid_t {
236         self.kuid
237     }
238 
239     /// Converts this kernel UID into a userspace UID.
240     ///
241     /// Uses the namespace of the current task.
242     #[inline]
243     pub fn into_uid_in_current_ns(self) -> bindings::uid_t {
244         // SAFETY: Just an FFI call.
245         unsafe { bindings::from_kuid(bindings::current_user_ns(), self.kuid) }
246     }
247 }
248 
249 impl PartialEq for Kuid {
250     #[inline]
251     fn eq(&self, other: &Kuid) -> bool {
252         // SAFETY: Just an FFI call.
253         unsafe { bindings::uid_eq(self.kuid, other.kuid) }
254     }
255 }
256 
257 impl Eq for Kuid {}
258