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};
7use crate::vfs::{FdTable, FsContext, FsNodeHandle, SharedFdTable};
8use fuchsia_rcu::{RcuArc, RcuOptionArc, RcuOptionBox};
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: RcuOptionArc<MemoryManager>,
35
36    /// The file system for this task.
37    pub fs: RcuArc<FsContext>,
38
39    /// The namespace for abstract AF_UNIX sockets for this task.
40    pub abstract_socket_namespace: Arc<AbstractUnixSocketNamespace>,
41
42    /// The namespace for AF_VSOCK for this task.
43    pub abstract_vsock_namespace: Arc<AbstractVsockSocketNamespace>,
44
45    /// The pid directory, so it doesn't have to be generated and thrown away on every access.
46    /// See https://fxbug.dev/291962828 for details.
47    pub proc_pid_directory_cache: RcuOptionBox<FsNodeHandle>,
48}
49
50impl TaskRunningState {
51    #[track_caller]
52    pub fn files(&self) -> Result<Arc<FdTable>, Errno> {
53        self.files.lock().as_ref().map(|files| files.table.clone()).ok_or_else(|| errno!(ESRCH))
54    }
55
56    pub fn fork_files(&self) -> Option<SharedFdTable> {
57        self.files.lock().as_ref().map(|files| SharedFdTable::new(files.fork()))
58    }
59
60    pub fn share_files(&self) -> Option<SharedFdTable> {
61        self.files.lock().as_ref().map(|files| files.clone())
62    }
63
64    pub fn unshare_files(&self) {
65        if let Some(ref mut files) = *self.files.lock() {
66            files.unshare();
67        }
68    }
69
70    pub fn mm(&self) -> Result<Arc<MemoryManager>, Errno> {
71        self.mm.to_option_arc().ok_or_else(|| errno!(EINVAL))
72    }
73
74    pub fn fs(&self) -> Arc<FsContext> {
75        self.fs.to_arc()
76    }
77}
78
79/// A synchronized container for a Zircon thread and its cached KOID.
80#[derive(Debug, Clone)]
81pub struct ZirconThread {
82    /// The underlying Zircon thread.
83    ///
84    /// # Thread Safety
85    ///
86    /// Blocking operations are unsafe while holding RCU read locks. However, references to this
87    /// thread must be held across blocking operations (e.g., futex waits). The [`ZirconThread`]
88    /// container as a whole is guarded by RCU because it is a member of the RCU-guarded
89    /// [`TaskRunningState`]. This field is reference counted so it can be accessed outside of RCU
90    /// locks through a strong reference.
91    ///
92    /// Holding a reference to the thread does not guarantee that the task to which it belongs will
93    /// continue running. The task may exit at any time. The thread will continue to exist in memory
94    /// until all references are dropped. When the task exits and execution stops, reference holders
95    /// will observe the thread transition to [`zx::ThreadState::Dead`] normally.
96    pub thread: Arc<zx::Thread>,
97    pub koid: zx::Koid,
98}
99
100impl ZirconThread {
101    pub fn new(thread: Arc<zx::Thread>) -> Self {
102        let koid = thread.koid().expect("Failed to get thread koid");
103        Self { thread, koid }
104    }
105}
106
107impl Deref for ZirconThread {
108    type Target = Arc<zx::Thread>;
109    fn deref(&self) -> &Self::Target {
110        &self.thread
111    }
112}