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