Skip to main content

starnix_core/task/
task_running_state.rs

1// Copyright 2026 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::mm::MemoryManager;
6use crate::task::{AbstractUnixSocketNamespace, AbstractVsockSocketNamespace, CurrentTask};
7use crate::vfs::{FdTable, FsContext, FsNodeHandle, SharedFdTable};
8use fuchsia_rcu::RcuArc;
9use starnix_sync::{LockDepMutex, TaskFilesLock};
10use starnix_uapi::errno;
11use starnix_uapi::errors::Errno;
12use std::ops::Deref;
13use std::sync::{Arc, OnceLock};
14
15/// The running state of a task.
16///
17/// This structure contains the state of a task that is only relevant while the task is running. It
18/// is dropped when the task enters an exited state.
19pub struct TaskRunningState {
20    /// A handle to the underlying Zircon thread object.
21    ///
22    /// Some tasks lack an underlying Zircon thread. These tasks are used internally by the
23    /// Starnix kernel to track background work, typically on a `kthread`.
24    pub thread: OnceLock<ZirconThread>,
25
26    /// The file descriptor table for this task.
27    ///
28    /// This table can be shared by many tasks.
29    ///
30    /// This is always `Some` while the task is running. It becomes `None` upon exit.
31    pub files: LockDepMutex<Option<SharedFdTable>, TaskFilesLock>,
32
33    /// The memory manager for this task.  This is `None` only for system tasks.
34    pub mm: RcuArc<MemoryManager>,
35
36    /// The file system for this task.
37    ///
38    /// This is always `Some` while the task is running. It becomes `None` upon exit, so that the
39    /// `FsContext` (and possibly the whole mount namespace) is released on the exiting thread rather
40    /// than by whichever thread happens to drop the last reference to this `TaskRunningState`.
41    pub fs: RcuArc<FsContext>,
42
43    /// The namespace for abstract AF_UNIX sockets for this task.
44    pub abstract_socket_namespace: Arc<AbstractUnixSocketNamespace>,
45
46    /// The namespace for AF_VSOCK for this task.
47    pub abstract_vsock_namespace: Arc<AbstractVsockSocketNamespace>,
48
49    /// The pid directory, so it doesn't have to be generated and thrown away on every access.
50    /// See https://fxbug.dev/291962828 for details.
51    pub proc_pid_directory_cache: OnceLock<FsNodeHandle>,
52}
53
54impl TaskRunningState {
55    #[track_caller]
56    pub fn files(&self) -> Result<Arc<FdTable>, Errno> {
57        self.files.lock().as_ref().map(|files| files.table.clone()).ok_or_else(|| errno!(ESRCH))
58    }
59
60    pub fn fork_files(&self) -> Option<SharedFdTable> {
61        self.files.lock().as_ref().map(|files| SharedFdTable::new(files.fork()))
62    }
63
64    pub fn share_files(&self) -> Option<SharedFdTable> {
65        self.files.lock().as_ref().map(|files| files.clone())
66    }
67
68    /// Unshares the file descriptor table for this task, if shared.
69    ///
70    /// Updates the [`Arc<FdTable>`] reference in both [`SharedFdTable`] and [`CurrentTask`].
71    pub fn unshare_files(&self, current_task: &CurrentTask) {
72        if let Some(ref mut files) = *self.files.lock() {
73            files.unshare();
74            *current_task.files.borrow_mut() = Some(files.table.clone());
75        }
76    }
77
78    pub fn mm(&self) -> Result<Arc<MemoryManager>, Errno> {
79        self.mm.upgrade().ok_or_else(|| errno!(EINVAL))
80    }
81
82    /// Returns the file system context for this task.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`Err(ESRCH)`] if the task has exited and released its file system context.
87    pub fn fs(&self) -> Result<Arc<FsContext>, Errno> {
88        self.fs.upgrade().ok_or_else(|| errno!(ESRCH))
89    }
90}
91
92/// A synchronized container for a Zircon thread and its cached KOID.
93#[derive(Debug, Clone)]
94pub struct ZirconThread {
95    /// The underlying Zircon thread.
96    ///
97    /// # Thread Safety
98    ///
99    /// Blocking operations are unsafe while holding RCU read locks. However, references to this
100    /// thread must be held across blocking operations (e.g., futex waits). The [`ZirconThread`]
101    /// container as a whole is guarded by RCU because it is a member of the RCU-guarded
102    /// [`TaskRunningState`]. This field is reference counted so it can be accessed outside of RCU
103    /// locks through a strong reference.
104    ///
105    /// Holding a reference to the thread does not guarantee that the task to which it belongs will
106    /// continue running. The task may exit at any time. The thread will continue to exist in memory
107    /// until all references are dropped. When the task exits and execution stops, reference holders
108    /// will observe the thread transition to [`zx::ThreadState::Dead`] normally.
109    pub thread: Arc<zx::Thread>,
110    pub koid: zx::Koid,
111}
112
113impl ZirconThread {
114    pub fn new(thread: Arc<zx::Thread>) -> Self {
115        let koid = thread.koid().expect("Failed to get thread koid");
116        Self { thread, koid }
117    }
118}
119
120impl Deref for ZirconThread {
121    type Target = Arc<zx::Thread>;
122    fn deref(&self) -> &Self::Target {
123        &self.thread
124    }
125}