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 mm::MmWithUser,
11 pid_namespace::PidNamespace,
12 sync::aref::ARef,
13 types::{NotThreadSafe, Opaque},
14};
15use core::{
16 cmp::{Eq, PartialEq},
17 ops::Deref,
18 ptr,
19};
20use safety_macro::safety;
21
22/// A sentinel value used for infinite timeouts.
23pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
24
25/// Bitmask for tasks that are sleeping in an interruptible state.
26pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
27/// Bitmask for tasks that are sleeping in an uninterruptible state.
28pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
29/// Bitmask for tasks that are sleeping in a freezable state.
30pub const TASK_FREEZABLE: c_int = bindings::TASK_FREEZABLE as c_int;
31/// Convenience constant for waking up tasks regardless of whether they are in interruptible or
32/// uninterruptible sleep.
33pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
34
35/// Returns the currently running task.
36#[macro_export]
37macro_rules! current {
38 () => {
39 // SAFETY: This expression creates a temporary value that is dropped at the end of the
40 // caller's scope. The following mechanisms ensure that the resulting `&CurrentTask` cannot
41 // leave current task context:
42 //
43 // * To return to userspace, the caller must leave the current scope.
44 // * Operations such as `begin_new_exec()` are necessarily unsafe and the caller of
45 // `begin_new_exec()` is responsible for safety.
46 // * Rust abstractions for things such as a `kthread_use_mm()` scope must require the
47 // closure to be `Send`, so the `NotThreadSafe` field of `CurrentTask` ensures that the
48 // `&CurrentTask` cannot cross the scope in either direction.
49 unsafe { &*$crate::task::Task::current() }
50 };
51}
52
53/// Wraps the kernel's `struct task_struct`.
54///
55/// # Invariants
56///
57/// All instances are valid tasks created by the C portion of the kernel.
58///
59/// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
60/// that the allocation remains valid at least until the matching call to `put_task_struct`.
61///
62/// # Examples
63///
64/// The following is an example of getting the PID of the current thread with zero additional cost
65/// when compared to the C version:
66///
67/// ```
68/// let pid = current!().pid();
69/// ```
70///
71/// Getting the PID of the current process, also zero additional cost:
72///
73/// ```
74/// let pid = current!().group_leader().pid();
75/// ```
76///
77/// Getting the current task and storing it in some struct. The reference count is automatically
78/// incremented when creating `State` and decremented when it is dropped:
79///
80/// ```
81/// use kernel::{task::Task, sync::aref::ARef};
82///
83/// struct State {
84/// creator: ARef<Task>,
85/// index: u32,
86/// }
87///
88/// impl State {
89/// fn new() -> Self {
90/// Self {
91/// creator: ARef::from(&**current!()),
92/// index: 0,
93/// }
94/// }
95/// }
96/// ```
97#[repr(transparent)]
98pub struct Task(pub(crate) Opaque<bindings::task_struct>);
99
100// SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
101// `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
102// which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
103// runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
104unsafe impl Send for Task {}
105
106// SAFETY: It's OK to access `Task` through shared references from other threads because we're
107// either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
108// synchronised by C code (e.g., `signal_pending`).
109unsafe impl Sync for Task {}
110
111/// Represents the [`Task`] in the `current` global.
112///
113/// This type exists to provide more efficient operations that are only valid on the current task.
114/// For example, to retrieve the pid-namespace of a task, you must use rcu protection unless it is
115/// the current task.
116///
117/// # Invariants
118///
119/// Each value of this type must only be accessed from the task context it was created within.
120///
121/// Of course, every thread is in a different task context, but for the purposes of this invariant,
122/// these operations also permanently leave the task context:
123///
124/// * Returning to userspace from system call context.
125/// * Calling `release_task()`.
126/// * Calling `begin_new_exec()` in a binary format loader.
127///
128/// Other operations temporarily create a new sub-context:
129///
130/// * Calling `kthread_use_mm()` creates a new context, and `kthread_unuse_mm()` returns to the
131/// old context.
132///
133/// This means that a `CurrentTask` obtained before a `kthread_use_mm()` call may be used again
134/// once `kthread_unuse_mm()` is called, but it must not be used between these two calls.
135/// Conversely, a `CurrentTask` obtained between a `kthread_use_mm()`/`kthread_unuse_mm()` pair
136/// must not be used after `kthread_unuse_mm()`.
137#[repr(transparent)]
138pub struct CurrentTask(Task, NotThreadSafe);
139
140// Make all `Task` methods available on `CurrentTask`.
141impl Deref for CurrentTask {
142 type Target = Task;
143 #[inline]
144 fn deref(&self) -> &Task {
145 &self.0
146 }
147}
148
149/// The type of process identifiers (PIDs).
150pub type Pid = bindings::pid_t;
151
152/// The type of user identifiers (UIDs).
153#[derive(Copy, Clone)]
154pub struct Kuid {
155 kuid: bindings::kuid_t,
156}
157
158impl Task {
159 /// Returns a raw pointer to the current task.
160 ///
161 /// It is up to the user to use the pointer correctly.
162 #[inline]
163 pub fn current_raw() -> *mut bindings::task_struct {
164 // SAFETY: Getting the current pointer is always safe.
165 unsafe { bindings::get_current() }
166 }
167
168 /// Returns a task reference for the currently executing task/thread.
169 ///
170 /// The recommended way to get the current task/thread is to use the
171 /// [`current`] macro because it is safe.
172 ///
173 /// # Safety
174 ///
175 /// Callers must ensure that the returned object is only used to access a [`CurrentTask`]
176 /// within the task context that was active when this function was called. For more details,
177 /// see the invariants section for [`CurrentTask`].
178 #[inline]
179 #[safety{ActiveContext("CurrentTask")}]
180 pub unsafe fn current() -> impl Deref<Target = CurrentTask> {
181 struct TaskRef {
182 task: *const CurrentTask,
183 }
184
185 impl Deref for TaskRef {
186 type Target = CurrentTask;
187
188 fn deref(&self) -> &Self::Target {
189 // SAFETY: The returned reference borrows from this `TaskRef`, so it cannot outlive
190 // the `TaskRef`, which the caller of `Task::current()` has promised will not
191 // outlive the task/thread for which `self.task` is the `current` pointer. Thus, it
192 // is okay to return a `CurrentTask` reference here.
193 unsafe { &*self.task }
194 }
195 }
196
197 TaskRef {
198 // CAST: The layout of `struct task_struct` and `CurrentTask` is identical.
199 task: Task::current_raw().cast(),
200 }
201 }
202
203 /// Returns a raw pointer to the task.
204 #[inline]
205 pub fn as_ptr(&self) -> *mut bindings::task_struct {
206 self.0.get()
207 }
208
209 /// Returns the group leader of the given task.
210 pub fn group_leader(&self) -> &Task {
211 // SAFETY: The group leader of a task never changes after initialization, so reading this
212 // field is not a data race.
213 let ptr = unsafe { *ptr::addr_of!((*self.as_ptr()).group_leader) };
214
215 // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
216 // and given that a task has a reference to its group leader, we know it must be valid for
217 // the lifetime of the returned task reference.
218 unsafe { &*ptr.cast() }
219 }
220
221 /// Returns the PID of the given task.
222 pub fn pid(&self) -> Pid {
223 // SAFETY: The pid of a task never changes after initialization, so reading this field is
224 // not a data race.
225 unsafe { *ptr::addr_of!((*self.as_ptr()).pid) }
226 }
227
228 /// Returns the UID of the given task.
229 #[inline]
230 pub fn uid(&self) -> Kuid {
231 // SAFETY: It's always safe to call `task_uid` on a valid task.
232 Kuid::from_raw(unsafe { bindings::task_uid(self.as_ptr()) })
233 }
234
235 /// Returns the effective UID of the given task.
236 #[inline]
237 pub fn euid(&self) -> Kuid {
238 // SAFETY: It's always safe to call `task_euid` on a valid task.
239 Kuid::from_raw(unsafe { bindings::task_euid(self.as_ptr()) })
240 }
241
242 /// Determines whether the given task has pending signals.
243 #[inline]
244 pub fn signal_pending(&self) -> bool {
245 // SAFETY: It's always safe to call `signal_pending` on a valid task.
246 unsafe { bindings::signal_pending(self.as_ptr()) != 0 }
247 }
248
249 /// Returns task's pid namespace with elevated reference count
250 #[inline]
251 pub fn get_pid_ns(&self) -> Option<ARef<PidNamespace>> {
252 // SAFETY: By the type invariant, we know that `self.0` is valid.
253 let ptr = unsafe { bindings::task_get_pid_ns(self.as_ptr()) };
254 if ptr.is_null() {
255 None
256 } else {
257 // SAFETY: `ptr` is valid by the safety requirements of this function. And we own a
258 // reference count via `task_get_pid_ns()`.
259 // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::pid_namespace`.
260 Some(unsafe { ARef::from_raw(ptr::NonNull::new_unchecked(ptr.cast::<PidNamespace>())) })
261 }
262 }
263
264 /// Returns the given task's pid in the provided pid namespace.
265 #[doc(alias = "task_tgid_nr_ns")]
266 #[inline]
267 pub fn tgid_nr_ns(&self, pidns: Option<&PidNamespace>) -> Pid {
268 let pidns = match pidns {
269 Some(pidns) => pidns.as_ptr(),
270 None => core::ptr::null_mut(),
271 };
272 // SAFETY: By the type invariant, we know that `self.0` is valid. We received a valid
273 // PidNamespace that we can use as a pointer or we received an empty PidNamespace and
274 // thus pass a null pointer. The underlying C function is safe to be used with NULL
275 // pointers.
276 unsafe { bindings::task_tgid_nr_ns(self.as_ptr(), pidns) }
277 }
278
279 /// Wakes up the task.
280 #[inline]
281 pub fn wake_up(&self) {
282 // SAFETY: It's always safe to call `wake_up_process` on a valid task, even if the task
283 // running.
284 unsafe { bindings::wake_up_process(self.as_ptr()) };
285 }
286}
287
288impl CurrentTask {
289 /// Access the address space of the current task.
290 ///
291 /// This function does not touch the refcount of the mm.
292 #[inline]
293 pub fn mm(&self) -> Option<&MmWithUser> {
294 // SAFETY: The `mm` field of `current` is not modified from other threads, so reading it is
295 // not a data race.
296 let mm = unsafe { (*self.as_ptr()).mm };
297
298 if mm.is_null() {
299 return None;
300 }
301
302 // SAFETY: If `current->mm` is non-null, then it references a valid mm with a non-zero
303 // value of `mm_users`. Furthermore, the returned `&MmWithUser` borrows from this
304 // `CurrentTask`, so it cannot escape the scope in which the current pointer was obtained.
305 //
306 // This is safe even if `kthread_use_mm()`/`kthread_unuse_mm()` are used. There are two
307 // relevant cases:
308 // * If the `&CurrentTask` was created before `kthread_use_mm()`, then it cannot be
309 // accessed during the `kthread_use_mm()`/`kthread_unuse_mm()` scope due to the
310 // `NotThreadSafe` field of `CurrentTask`.
311 // * If the `&CurrentTask` was created within a `kthread_use_mm()`/`kthread_unuse_mm()`
312 // scope, then the `&CurrentTask` cannot escape that scope, so the returned `&MmWithUser`
313 // also cannot escape that scope.
314 // In either case, it's not possible to read `current->mm` and keep using it after the
315 // scope is ended with `kthread_unuse_mm()`.
316 Some(unsafe { MmWithUser::from_raw(mm) })
317 }
318
319 /// Access the pid namespace of the current task.
320 ///
321 /// This function does not touch the refcount of the namespace or use RCU protection.
322 ///
323 /// To access the pid namespace of another task, see [`Task::get_pid_ns`].
324 #[doc(alias = "task_active_pid_ns")]
325 #[inline]
326 pub fn active_pid_ns(&self) -> Option<&PidNamespace> {
327 // SAFETY: It is safe to call `task_active_pid_ns` without RCU protection when calling it
328 // on the current task.
329 let active_ns = unsafe { bindings::task_active_pid_ns(self.as_ptr()) };
330
331 if active_ns.is_null() {
332 return None;
333 }
334
335 // The lifetime of `PidNamespace` is bound to `Task` and `struct pid`.
336 //
337 // The `PidNamespace` of a `Task` doesn't ever change once the `Task` is alive.
338 //
339 // From system call context retrieving the `PidNamespace` for the current task is always
340 // safe and requires neither RCU locking nor a reference count to be held. Retrieving the
341 // `PidNamespace` after `release_task()` for current will return `NULL` but no codepath
342 // like that is exposed to Rust.
343 //
344 // SAFETY: If `current`'s pid ns is non-null, then it references a valid pid ns.
345 // Furthermore, the returned `&PidNamespace` borrows from this `CurrentTask`, so it cannot
346 // escape the scope in which the current pointer was obtained, e.g. it cannot live past a
347 // `release_task()` call.
348 Some(unsafe { PidNamespace::from_ptr(active_ns) })
349 }
350}
351
352// SAFETY: The type invariants guarantee that `Task` is always refcounted.
353unsafe impl crate::sync::aref::AlwaysRefCounted for Task {
354 #[inline]
355 fn inc_ref(&self) {
356 // SAFETY: The existence of a shared reference means that the refcount is nonzero.
357 unsafe { bindings::get_task_struct(self.as_ptr()) };
358 }
359
360 #[inline]
361 unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
362 // SAFETY: The safety requirements guarantee that the refcount is nonzero.
363 unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
364 }
365}
366
367impl Kuid {
368 /// Get the current euid.
369 #[inline]
370 pub fn current_euid() -> Kuid {
371 // SAFETY: Just an FFI call.
372 Self::from_raw(unsafe { bindings::current_euid() })
373 }
374
375 /// Create a `Kuid` given the raw C type.
376 #[inline]
377 pub fn from_raw(kuid: bindings::kuid_t) -> Self {
378 Self { kuid }
379 }
380
381 /// Turn this kuid into the raw C type.
382 #[inline]
383 pub fn into_raw(self) -> bindings::kuid_t {
384 self.kuid
385 }
386
387 /// Converts this kernel UID into a userspace UID.
388 ///
389 /// Uses the namespace of the current task.
390 #[inline]
391 pub fn into_uid_in_current_ns(self) -> bindings::uid_t {
392 // SAFETY: Just an FFI call.
393 unsafe { bindings::from_kuid(bindings::current_user_ns(), self.kuid) }
394 }
395}
396
397impl PartialEq for Kuid {
398 #[inline]
399 fn eq(&self, other: &Kuid) -> bool {
400 // SAFETY: Just an FFI call.
401 unsafe { bindings::uid_eq(self.kuid, other.kuid) }
402 }
403}
404
405impl Eq for Kuid {}
406
407/// Annotation for functions that can sleep.
408///
409/// Equivalent to the C side [`might_sleep()`], this function serves as
410/// a debugging aid and a potential scheduling point.
411///
412/// This function can only be used in a nonatomic context.
413///
414/// [`might_sleep()`]: https://docs.kernel.org/driver-api/basics.html#c.might_sleep
415#[track_caller]
416#[inline]
417pub fn might_sleep() {
418 #[cfg(CONFIG_DEBUG_ATOMIC_SLEEP)]
419 {
420 let loc = core::panic::Location::caller();
421 let file = kernel::file_from_location(loc);
422
423 // SAFETY: `file.as_ptr()` is valid for reading and guaranteed to be nul-terminated.
424 unsafe { crate::bindings::__might_sleep(file.as_ptr().cast(), loc.line() as i32) }
425 }
426
427 // SAFETY: Always safe to call.
428 unsafe { crate::bindings::might_resched() }
429}