task.rs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! Tasks (threads and processes).
  3. //!
  4. //! C header: [`include/linux/sched.h`](srctree/include/linux/sched.h).
  5. use crate::ffi::{c_int, c_long, c_uint};
  6. use crate::types::Opaque;
  7. use core::{marker::PhantomData, ops::Deref, ptr};
  8. /// A sentinel value used for infinite timeouts.
  9. pub const MAX_SCHEDULE_TIMEOUT: c_long = c_long::MAX;
  10. /// Bitmask for tasks that are sleeping in an interruptible state.
  11. pub const TASK_INTERRUPTIBLE: c_int = bindings::TASK_INTERRUPTIBLE as c_int;
  12. /// Bitmask for tasks that are sleeping in an uninterruptible state.
  13. pub const TASK_UNINTERRUPTIBLE: c_int = bindings::TASK_UNINTERRUPTIBLE as c_int;
  14. /// Convenience constant for waking up tasks regardless of whether they are in interruptible or
  15. /// uninterruptible sleep.
  16. pub const TASK_NORMAL: c_uint = bindings::TASK_NORMAL as c_uint;
  17. /// Returns the currently running task.
  18. #[macro_export]
  19. macro_rules! current {
  20. () => {
  21. // SAFETY: Deref + addr-of below create a temporary `TaskRef` that cannot outlive the
  22. // caller.
  23. unsafe { &*$crate::task::Task::current() }
  24. };
  25. }
  26. /// Wraps the kernel's `struct task_struct`.
  27. ///
  28. /// # Invariants
  29. ///
  30. /// All instances are valid tasks created by the C portion of the kernel.
  31. ///
  32. /// Instances of this type are always refcounted, that is, a call to `get_task_struct` ensures
  33. /// that the allocation remains valid at least until the matching call to `put_task_struct`.
  34. ///
  35. /// # Examples
  36. ///
  37. /// The following is an example of getting the PID of the current thread with zero additional cost
  38. /// when compared to the C version:
  39. ///
  40. /// ```
  41. /// let pid = current!().pid();
  42. /// ```
  43. ///
  44. /// Getting the PID of the current process, also zero additional cost:
  45. ///
  46. /// ```
  47. /// let pid = current!().group_leader().pid();
  48. /// ```
  49. ///
  50. /// Getting the current task and storing it in some struct. The reference count is automatically
  51. /// incremented when creating `State` and decremented when it is dropped:
  52. ///
  53. /// ```
  54. /// use kernel::{task::Task, types::ARef};
  55. ///
  56. /// struct State {
  57. /// creator: ARef<Task>,
  58. /// index: u32,
  59. /// }
  60. ///
  61. /// impl State {
  62. /// fn new() -> Self {
  63. /// Self {
  64. /// creator: current!().into(),
  65. /// index: 0,
  66. /// }
  67. /// }
  68. /// }
  69. /// ```
  70. #[repr(transparent)]
  71. pub struct Task(pub(crate) Opaque<bindings::task_struct>);
  72. // SAFETY: By design, the only way to access a `Task` is via the `current` function or via an
  73. // `ARef<Task>` obtained through the `AlwaysRefCounted` impl. This means that the only situation in
  74. // which a `Task` can be accessed mutably is when the refcount drops to zero and the destructor
  75. // runs. It is safe for that to happen on any thread, so it is ok for this type to be `Send`.
  76. unsafe impl Send for Task {}
  77. // SAFETY: It's OK to access `Task` through shared references from other threads because we're
  78. // either accessing properties that don't change (e.g., `pid`, `group_leader`) or that are properly
  79. // synchronised by C code (e.g., `signal_pending`).
  80. unsafe impl Sync for Task {}
  81. /// The type of process identifiers (PIDs).
  82. type Pid = bindings::pid_t;
  83. impl Task {
  84. /// Returns a task reference for the currently executing task/thread.
  85. ///
  86. /// The recommended way to get the current task/thread is to use the
  87. /// [`current`] macro because it is safe.
  88. ///
  89. /// # Safety
  90. ///
  91. /// Callers must ensure that the returned object doesn't outlive the current task/thread.
  92. pub unsafe fn current() -> impl Deref<Target = Task> {
  93. struct TaskRef<'a> {
  94. task: &'a Task,
  95. _not_send: PhantomData<*mut ()>,
  96. }
  97. impl Deref for TaskRef<'_> {
  98. type Target = Task;
  99. fn deref(&self) -> &Self::Target {
  100. self.task
  101. }
  102. }
  103. // SAFETY: Just an FFI call with no additional safety requirements.
  104. let ptr = unsafe { bindings::get_current() };
  105. TaskRef {
  106. // SAFETY: If the current thread is still running, the current task is valid. Given
  107. // that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
  108. // (where it could potentially outlive the caller).
  109. task: unsafe { &*ptr.cast() },
  110. _not_send: PhantomData,
  111. }
  112. }
  113. /// Returns the group leader of the given task.
  114. pub fn group_leader(&self) -> &Task {
  115. // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
  116. // have a valid `group_leader`.
  117. let ptr = unsafe { *ptr::addr_of!((*self.0.get()).group_leader) };
  118. // SAFETY: The lifetime of the returned task reference is tied to the lifetime of `self`,
  119. // and given that a task has a reference to its group leader, we know it must be valid for
  120. // the lifetime of the returned task reference.
  121. unsafe { &*ptr.cast() }
  122. }
  123. /// Returns the PID of the given task.
  124. pub fn pid(&self) -> Pid {
  125. // SAFETY: By the type invariant, we know that `self.0` is a valid task. Valid tasks always
  126. // have a valid pid.
  127. unsafe { *ptr::addr_of!((*self.0.get()).pid) }
  128. }
  129. /// Determines whether the given task has pending signals.
  130. pub fn signal_pending(&self) -> bool {
  131. // SAFETY: By the type invariant, we know that `self.0` is valid.
  132. unsafe { bindings::signal_pending(self.0.get()) != 0 }
  133. }
  134. /// Wakes up the task.
  135. pub fn wake_up(&self) {
  136. // SAFETY: By the type invariant, we know that `self.0.get()` is non-null and valid.
  137. // And `wake_up_process` is safe to be called for any valid task, even if the task is
  138. // running.
  139. unsafe { bindings::wake_up_process(self.0.get()) };
  140. }
  141. }
  142. // SAFETY: The type invariants guarantee that `Task` is always refcounted.
  143. unsafe impl crate::types::AlwaysRefCounted for Task {
  144. fn inc_ref(&self) {
  145. // SAFETY: The existence of a shared reference means that the refcount is nonzero.
  146. unsafe { bindings::get_task_struct(self.0.get()) };
  147. }
  148. unsafe fn dec_ref(obj: ptr::NonNull<Self>) {
  149. // SAFETY: The safety requirements guarantee that the refcount is nonzero.
  150. unsafe { bindings::put_task_struct(obj.cast().as_ptr()) }
  151. }
  152. }