Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/object/thread.rs

kernel/object/
thread.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use foreign_box::ForeignBox;
16use pw_status::{Error, Result};
17use syscall_defs::ExitStatus;
18
19use crate::Kernel;
20use crate::object::{KernelObject, ObjectBase, SignalUpdate, Signals};
21use crate::scheduler::{ProcessHandle, SchedulerState, Thread, ThreadHandle, TryJoinResult};
22use crate::sync::spinlock::{SpinLock, SpinLockGuard};
23
24enum State<K: Kernel> {
25    Stopped(ForeignBox<Thread<K>>),
26    Running(ThreadHandle<K>),
27    Empty,
28}
29
30impl<K: Kernel> State<K> {
31    fn take_thread(&mut self) -> Option<ForeignBox<Thread<K>>> {
32        match core::mem::replace(self, State::Empty) {
33            State::Stopped(thread) => Some(thread),
34            state => {
35                *self = state;
36                None
37            }
38        }
39    }
40}
41
42pub struct ThreadObject<K: Kernel> {
43    base: ObjectBase<K>,
44    state: SpinLock<K, State<K>>,
45}
46
47impl<K: Kernel> ThreadObject<K> {
48    #[must_use]
49    pub const fn new(thread: ForeignBox<Thread<K>>) -> Self {
50        Self {
51            base: ObjectBase::new(Signals::no_active()),
52            state: SpinLock::new(State::Stopped(thread)),
53        }
54    }
55
56    pub const fn new_empty() -> Self {
57        Self {
58            base: ObjectBase::new(Signals::no_active()),
59            state: SpinLock::new(State::Empty),
60        }
61    }
62
63    pub fn set_thread(&self, kernel: K, thread: ForeignBox<Thread<K>>) -> Result<()> {
64        let mut state = self.state.lock(kernel);
65        match *state {
66            State::Empty => {
67                *state = State::Stopped(thread);
68                Ok(())
69            }
70            _ => Err(Error::AlreadyExists),
71        }
72    }
73
74    pub fn start(
75        &self,
76        kernel: K,
77        process_handle: ProcessHandle<K>,
78        initial_pc: usize,
79        initial_sp: usize,
80        args: (usize, usize, usize),
81    ) -> Result<()> {
82        let mut state = self.state.lock(kernel);
83        let Some(mut thread) = state.take_thread() else {
84            return Err(Error::AlreadyExists);
85        };
86
87        // SAFETY: `ThreadObject` is a kernel object that is always managed
88        // within a `ForeignRcState` (e.g., when wrapped in `ForeignRc` or
89        // `ForeignBox` for the object table). Thus, the `&self` reference
90        // points to storage contained inside a `ForeignRcState`.
91        let self_rc = unsafe { foreign_box::ForeignRcState::create_ref_from_inner(self) };
92        thread.object = Some(self_rc.clone());
93
94        unsafe {
95            thread.initialize_non_priv_thread(
96                kernel,
97                process_handle,
98                initial_pc,
99                initial_sp,
100                args,
101            )?;
102        }
103        let thread_handle = crate::scheduler::start_thread(kernel, thread);
104        *state = State::Running(thread_handle);
105        Ok(())
106    }
107
108    pub fn terminate(&self, kernel: K) -> Result<()> {
109        let mut thread_handle = {
110            let state = self.state.lock(kernel);
111            match &*state {
112                State::Running(thread_handle) => thread_handle.clone(),
113                State::Stopped(_) => return Err(Error::FailedPrecondition),
114                State::Empty => return Err(Error::Internal),
115            }
116        };
117        // Call terminate without holding the state lock
118        thread_handle.terminate(kernel, ExitStatus::TerminatedBySyscall)
119    }
120
121    pub fn join_locked<'a>(
122        &self,
123        kernel: K,
124        sched: SpinLockGuard<'a, K, SchedulerState<K>>,
125    ) -> (SpinLockGuard<'a, K, SchedulerState<K>>, Result<ExitStatus>) {
126        let thread_handle = {
127            let mut state = self.state.lock(kernel);
128            match core::mem::replace(&mut *state, State::Empty) {
129                State::Running(t) => t,
130                old_state => {
131                    *state = old_state;
132                    return (sched, Err(Error::FailedPrecondition));
133                }
134            }
135        };
136
137        let res = thread_handle.try_join_locked(kernel, sched);
138
139        match res {
140            (sched, crate::scheduler::TryJoinResult::Joined(thread, status)) => {
141                let mut state = self.state.lock(kernel);
142                *state = State::Stopped(thread);
143                (sched, Ok(status))
144            }
145            (sched, crate::scheduler::TryJoinResult::Wait(thread_handle)) => {
146                let mut state = self.state.lock(kernel);
147                *state = State::Running(thread_handle);
148                (sched, Err(Error::Unavailable))
149            }
150            (
151                sched,
152                TryJoinResult::Err {
153                    error,
154                    thread: thread_handle,
155                },
156            ) => {
157                let mut state = self.state.lock(kernel);
158                *state = State::Running(thread_handle);
159                (sched, Err(error))
160            }
161        }
162    }
163
164    pub(crate) fn signal_locked<'a>(
165        &self,
166        kernel: K,
167        sched: SpinLockGuard<'a, K, SchedulerState<K>>,
168        update: SignalUpdate,
169    ) -> SpinLockGuard<'a, K, SchedulerState<K>> {
170        self.base.signal_locked(kernel, sched, update)
171    }
172}
173
174impl<K: Kernel> KernelObject<K> for ThreadObject<K> {
175    fn base(&self) -> Option<&ObjectBase<K>> {
176        Some(&self.base)
177    }
178
179    fn object_wait(
180        &self,
181        kernel: K,
182        signal_mask: Signals,
183        deadline: pw_time_core::Instant<K::Clock>,
184    ) -> Result<crate::object::WaitReturn> {
185        self.base.wait_until(kernel, signal_mask, deadline)
186    }
187
188    fn thread_start(&self, kernel: K, initial_pc: usize, initial_sp: usize) -> Result<()> {
189        let process = kernel.get_scheduler().lock(kernel).current_process_handle();
190        self.start(kernel, process.clone(), initial_pc, initial_sp, (0, 0, 0))
191    }
192
193    fn task_terminate(&self, kernel: K) -> Result<()> {
194        self.terminate(kernel)
195    }
196
197    fn task_join(&self, kernel: K) -> Result<ExitStatus> {
198        let sched = kernel.get_scheduler().lock(kernel);
199        let (_, res) = self.join_locked(kernel, sched);
200        res
201    }
202}