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