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::{
8 bindings,
9 ffi::{c_int, c_long, c_uint},
10 pid_namespace::PidNamespace,
11 types::{ARef, NotThreadSafe, Opaque},
12};
13use core::{
14 cmp::{Eq, PartialEq},
15 ops::Deref,
16 ptr,
17};
18
19/// A sentinel value used for infinite timeouts.
20pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
21
22/// Bitmask for tasks that are sleeping in an interruptible state.
23pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
24/// Bitmask for tasks that are sleeping in an uninterruptible state.
25pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
26/// Bitmask for tasks that are sleeping in a freezable state.
27pub const TASK_FREEZABLE: c_int = bindings::TASK_FREEZABLE as c_int;
28/// Convenience constant for waking up tasks regardless of whether they are in interruptible or
29/// uninterruptible sleep.
30pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
31
32/// Returns the currently running task.
33#[macro_export]
34macro_rules! current {
35 () => {
36 // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the
37 // caller.
38 unsafe { &*$crate::task::Task::current() }
39 };
40}
41
42/// Returns the currently running task's pid namespace.
43#[macro_export]
44macro_rules! current_pid_ns {
45 () => {
46 // SAFETY: Deref + addr-of below create a temporary `PidNamespaceRef` that cannot outlive
47 // the caller.
48 unsafe { &*$crate::task::Task::current_pid_ns() }
49 };
50}
51
52/// Wraps the kernel's `struct task_struct`.
53///
54/// # Invariants
55///
56/// All instances are valid tasks created by the C portion of the kernel.
57///
58/// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
59/// that the allocation remains valid at least until the matching call to `put_task_struct`.
60///
61/// # Examples
62///
63/// The following is an example of getting the PID of the current thread with zero additional cost
64/// when compared to the C version:
65///
66/// ```
67/// let pid = current!().pid();
68/// ```
69///
70/// Getting the PID of the current process, also zero additional cost:
71///
72/// ```
73/// let pid = current!().group_leader().pid();
74/// ```
75///
76/// Getting the current task and storing it in some struct. The reference count is automatically
77/// incremented when creating `State` and decremented when it is dropped:
78///
79/// ```
80/// use kernel::{task::Task, types::ARef};
81///
82/// struct State {
83/// creator: ARef<Task>,
84/// index: u32,
85/// }
86///
87/// impl State {
88/// fn new() -> Self {
89/// Self {
90/// creator: current!().into(),
91/// index: 0,
92/// }
93/// }
94/// }
95/// ```
96#[repr(transparent)]
97pub struct Task(pub(crate) Opaque<bindings::task_struct>);
98
99// SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
100// `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
101// which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
102// runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
103unsafe impl Send for Task {}
104
105// SAFETY: It's OK to access `Task` through shared references from other threads because we're
106// either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
107// synchronised by C code (e.g., `signal_pending`).
108unsafe impl Sync for Task {}
109
110/// The type of process identifiers (PIDs).
111pub type Pid = bindings::pid_t;
112
113/// The type of user identifiers (UIDs).
114#[derive(Copy, Clone)]
115pub struct Kuid {
116 kuid: bindings::kuid_t,
117}
118
119impl Task {
120 /// Returns a raw pointer to the current task.
121 ///
122 /// It is up to the user to use the pointer correctly.
123 #[inline]
124 pub fn current_raw() -> *mut bindings::task_struct {
125 // SAFETY: Getting the current pointer is always safe.
126 unsafe { bindings::get_current() }
127 }
128
129 /// Returns a task reference for the currently executing task/thread.
130 ///
131 /// The recommended way to get the current task/thread is to use the
132 /// [`current`] macro because it is safe.
133 ///
134 /// # Safety
135 ///
136 /// Callers must ensure that the returned object doesn't outlive the current task/thread.
137 pub unsafe fn current() -> impl Deref<Target = Task> {
138 struct TaskRef<'a> {
139 task: &'a Task,
140 _not_send: NotThreadSafe,
141 }
142
143 impl Deref for TaskRef<'_> {
144 type Target = Task;
145
146 fn deref(&self) -> &Self::Target {
147 self.task
148 }
149 }
150
151 let current = Task::current_raw();
152 TaskRef {
153 // SAFETY: If the current thread is still running, the current task is valid. Given
154 // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
155 // (where it could potentially outlive the caller).
156 task: unsafe { &*current.cast() },
157 _not_send: NotThreadSafe,
158 }
159 }
160
161 /// Returns a PidNamespace reference for the currently executing task's/thread's pid namespace.
162 ///
163 /// This function can be used to create an unbounded lifetime by e.g., storing the returned
164 /// PidNamespace in a global variable which would be a bug. So the recommended way to get the
165 /// current task's/thread's pid namespace is to use the [`current_pid_ns`] macro because it is
166 /// safe.
167 ///
168 /// # Safety
169 ///
170 /// Callers must ensure that the returned object doesn't outlive the current task/thread.
171 pub unsafe fn current_pid_ns() -> impl Deref<Target = PidNamespace> {
172 struct PidNamespaceRef<'a> {
173 task: &'a PidNamespace,
174 _not_send: NotThreadSafe,
175 }
176
177 impl Deref for PidNamespaceRef<'_> {
178 type Target = PidNamespace;
179
180 fn deref(&self) -> &Self::Target {
181 self.task
182 }
183 }
184
185 // The lifetime of `PidNamespace` is bound to `Task` and `struct pid`.
186 //
187 // The `PidNamespace` of a `Task` doesn't ever change once the `Task` is alive. A
188 // `unshare(CLONE_NEWPID)` or `setns(fd_pidns/pidfd, CLONE_NEWPID)` will not have an effect
189 // on the calling `Task`'s pid namespace. It will only effect the pid namespace of children
190 // created by the calling `Task`. This invariant guarantees that after having acquired a
191 // reference to a `Task`'s pid namespace it will remain unchanged.
192 //
193 // When a task has exited and been reaped `release_task()` will be called. This will set
194 // the `PidNamespace` of the task to `NULL`. So retrieving the `PidNamespace` of a task
195 // that is dead will return `NULL`. Note, that neither holding the RCU lock nor holding a
196 // referencing count to
197 // the `Task` will prevent `release_task()` being called.
198 //
199 // In order to retrieve the `PidNamespace` of a `Task` the `task_active_pid_ns()` function
200 // can be used. There are two cases to consider:
201 //
202 // (1) retrieving the `PidNamespace` of the `current` task
203 // (2) retrieving the `PidNamespace` of a non-`current` task
204 //
205 // From system call context retrieving the `PidNamespace` for case (1) is always safe and
206 // requires neither RCU locking nor a reference count to be held. Retrieving the
207 // `PidNamespace` after `release_task()` for current will return `NULL` but no codepath
208 // like that is exposed to Rust.
209 //
210 // Retrieving the `PidNamespace` from system call context for (2) requires RCU protection.
211 // Accessing `PidNamespace` outside of RCU protection requires a reference count that
212 // must've been acquired while holding the RCU lock. Note that accessing a non-`current`
213 // task means `NULL` can be returned as the non-`current` task could have already passed
214 // through `release_task()`.
215 //
216 // To retrieve (1) the `current_pid_ns!()` macro should be used which ensure that the
217 // returned `PidNamespace` cannot outlive the calling scope. The associated
218 // `current_pid_ns()` function should not be called directly as it could be abused to
219 // created an unbounded lifetime for `PidNamespace`. The `current_pid_ns!()` macro allows
220 // Rust to handle the common case of accessing `current`'s `PidNamespace` without RCU
221 // protection and without having to acquire a reference count.
222 //
223 // For (2) the `task_get_pid_ns()` method must be used. This will always acquire a
224 // reference on `PidNamespace` and will return an `Option` to force the caller to
225 // explicitly handle the case where `PidNamespace` is `None`, something that tends to be
226 // forgotten when doing the equivalent operation in `C`. Missing RCU primitives make it
227 // difficult to perform operations that are otherwise safe without holding a reference
228 // count as long as RCU protection is guaranteed. But it is not important currently. But we
229 // do want it in the future.
230 //
231 // Note for (2) the required RCU protection around calling `task_active_pid_ns()`
232 // synchronizes against putting the last reference of the associated `struct pid` of
233 // `task->thread_pid`. The `struct pid` stored in that field is used to retrieve the
234 // `PidNamespace` of the caller. When `release_task()` is called `task->thread_pid` will be
235 // `NULL`ed and `put_pid()` on said `struct pid` will be delayed in `free_pid()` via
236 // `call_rcu()` allowing everyone with an RCU protected access to the `struct pid` acquired
237 // from `task->thread_pid` to finish.
238 //
239 // SAFETY: The current task's pid namespace is valid as long as the current task is running.
240 let pidns = unsafe { bindings::task_active_pid_ns(Task::current_raw()) };
241 PidNamespaceRef {
242 // SAFETY: If the current thread is still running, the current task and its associated
243 // pid namespace are valid. `PidNamespaceRef` is not `Send`, so we know it cannot be
244 // transferred to another thread (where it could potentially outlive the current
245 // `Task`). The caller needs to ensure that the PidNamespaceRef doesn't outlive the
246 // current task/thread.
247 task: unsafe { PidNamespace::from_ptr(pidns) },
248 _not_send: NotThreadSafe,
249 }
250 }
251
252 /// Returns a raw pointer to the task.
253 #[inline]
254 pub fn as_ptr(&self) -> *mut bindings::task_struct {
255 self.0.get()
256 }
257
258 /// Returns the group leader of the given task.
259 pub fn group_leader(&self) -> &Task {
260 // SAFETY: The group leader of a task never changes after initialization, so reading this
261 // field is not a data race.
262 let ptr = unsafe { *ptr::addr_of!((*self.as_ptr()).group_leader) };
263
264 // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
265 // and given that a task has a reference to its group leader, we know it must be valid for
266 // the lifetime of the returned task reference.
267 unsafe { &*ptr.cast() }
268 }
269
270 /// Returns the PID of the given task.
271 pub fn pid(&self) -> Pid {
272 // SAFETY: The pid of a task never changes after initialization, so reading this field is
273 // not a data race.
274 unsafe { *ptr::addr_of!((*self.as_ptr()).pid) }
275 }
276
277 /// Returns the UID of the given task.
278 pub fn uid(&self) -> Kuid {
279 // SAFETY: It's always safe to call `task_uid` on a valid task.
280 Kuid::from_raw(unsafe { bindings::task_uid(self.as_ptr()) })
281 }
282
283 /// Returns the effective UID of the given task.
284 pub fn euid(&self) -> Kuid {
285 // SAFETY: It's always safe to call `task_euid` on a valid task.
286 Kuid::from_raw(unsafe { bindings::task_euid(self.as_ptr()) })
287 }
288
289 /// Determines whether the given task has pending signals.
290 pub fn signal_pending(&self) -> bool {
291 // SAFETY: It's always safe to call `signal_pending` on a valid task.
292 unsafe { bindings::signal_pending(self.as_ptr()) != 0 }
293 }
294
295 /// Returns task's pid namespace with elevated reference count
296 pub fn get_pid_ns(&self) -> Option<ARef<PidNamespace>> {
297 // SAFETY: By the type invariant, we know that `self.0` is valid.
298 let ptr = unsafe { bindings::task_get_pid_ns(self.as_ptr()) };
299 if ptr.is_null() {
300 None
301 } else {
302 // SAFETY: `ptr` is valid by the safety requirements of this function. And we own a
303 // reference count via `task_get_pid_ns()`.
304 // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::pid_namespace`.
305 Some(unsafe { ARef::from_raw(ptr::NonNull::new_unchecked(ptr.cast::<PidNamespace>())) })
306 }
307 }
308
309 /// Returns the given task's pid in the provided pid namespace.
310 #[doc(alias = "task_tgid_nr_ns")]
311 pub fn tgid_nr_ns(&self, pidns: Option<&PidNamespace>) -> Pid {
312 let pidns = match pidns {
313 Some(pidns) => pidns.as_ptr(),
314 None => core::ptr::null_mut(),
315 };
316 // SAFETY: By the type invariant, we know that `self.0` is valid. We received a valid
317 // PidNamespace that we can use as a pointer or we received an empty PidNamespace and
318 // thus pass a null pointer. The underlying C function is safe to be used with NULL
319 // pointers.
320 unsafe { bindings::task_tgid_nr_ns(self.as_ptr(), pidns) }
321 }
322
323 /// Wakes up the task.
324 pub fn wake_up(&self) {
325 // SAFETY: It's always safe to call `wake_up_process` on a valid task, even if the task
326 // running.
327 unsafe { bindings::wake_up_process(self.as_ptr()) };
328 }
329}
330
331// SAFETY: The type invariants guarantee that `Task` is always refcounted.
332unsafe impl crate::types::AlwaysRefCounted for Task {
333 fn inc_ref(&self) {
334 // SAFETY: The existence of a shared reference means that the refcount is nonzero.
335 unsafe { bindings::get_task_struct(self.as_ptr()) };
336 }
337
338 unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
339 // SAFETY: The safety requirements guarantee that the refcount is nonzero.
340 unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
341 }
342}
343
344impl Kuid {
345 /// Get the current euid.
346 #[inline]
347 pub fn current_euid() -> Kuid {
348 // SAFETY: Just an FFI call.
349 Self::from_raw(unsafe { bindings::current_euid() })
350 }
351
352 /// Create a `Kuid` given the raw C type.
353 #[inline]
354 pub fn from_raw(kuid: bindings::kuid_t) -> Self {
355 Self { kuid }
356 }
357
358 /// Turn this kuid into the raw C type.
359 #[inline]
360 pub fn into_raw(self) -> bindings::kuid_t {
361 self.kuid
362 }
363
364 /// Converts this kernel UID into a userspace UID.
365 ///
366 /// Uses the namespace of the current task.
367 #[inline]
368 pub fn into_uid_in_current_ns(self) -> bindings::uid_t {
369 // SAFETY: Just an FFI call.
370 unsafe { bindings::from_kuid(bindings::current_user_ns(), self.kuid) }
371 }
372}
373
374impl PartialEq for Kuid {
375 #[inline]
376 fn eq(&self, other: &Kuid) -> bool {
377 // SAFETY: Just an FFI call.
378 unsafe { bindings::uid_eq(self.kuid, other.kuid) }
379 }
380}
381
382impl Eq for Kuid {}