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/scheduler/process.rs

kernel/scheduler/
process.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 core::mem::ManuallyDrop;
16use core::ops::Range;
17use core::ptr::NonNull;
18use core::sync::atomic::Ordering;
19
20use exit_status::ExitStatus;
21#[cfg(not(feature = "user_space"))]
22use foreign_box::ForeignBox;
23#[cfg(feature = "user_space")]
24use foreign_box::{ForeignBox, ForeignRc};
25use list::*;
26use memory_config::{MemoryConfig as _, MemoryRegionType};
27use pw_atomic::{AtomicAdd, AtomicSub, AtomicZero};
28use pw_log::info;
29use pw_status::Result;
30use pw_time_core::Instant;
31
32use crate::Kernel;
33#[cfg(feature = "user_space")]
34use crate::object::{KernelObject, ObjectTable};
35use crate::scheduler::SchedulerState;
36use crate::scheduler::thread::{Thread, ThreadHandle, ThreadState};
37use crate::sync::event::{Event, EventConfig, EventSignaler};
38use crate::sync::spinlock::SpinLockGuard;
39
40/// Runtime state of a Process.
41#[derive(Copy, Clone, PartialEq)]
42pub enum ProcessState {
43    /// Process is registered with the scheduled because it is either new or has been joined.
44    Inactive,
45
46    /// Process is registered with the scheduler and participates in execution.
47    Active,
48
49    /// Process termination has been requested; threads are being terminated.
50    Terminating,
51
52    /// Process has no active threads and is terminated, waiting to be joined.
53    Terminated,
54}
55
56pub(super) fn process_state_to_string(s: ProcessState) -> &'static str {
57    match s {
58        ProcessState::Inactive => "Inactive",
59        ProcessState::Active => "Active",
60        ProcessState::Terminating => "Terminating",
61        ProcessState::Terminated => "Terminated",
62    }
63}
64
65pub struct Process<K: Kernel> {
66    // List of the processes in the system
67    pub link: Link,
68
69    // TODO - konkers: allow this to be tokenized.
70    pub name: &'static str,
71
72    pub(crate) memory_config: <K::ThreadState as ThreadState>::MemoryConfig,
73
74    #[cfg(feature = "user_space")]
75    object_table: ForeignBox<dyn ObjectTable<K>>,
76
77    #[cfg(feature = "user_space")]
78    pub object: Option<foreign_box::ForeignRc<K::AtomicUsize, crate::object::ProcessObject<K>>>,
79
80    pub(super) thread_list: UnsafeList<Thread<K>, ProcessThreadListAdapter<K>>,
81
82    pub(super) ref_count: K::AtomicUsize,
83    pub(super) state: ProcessState,
84    pub(super) join_event: Option<EventSignaler<K>>,
85    pub(super) exit_status: Option<ExitStatus>,
86}
87
88// Safety: Process internal state is protected by the scheduler lock or atomic operations.
89unsafe impl<K: Kernel> Send for Process<K> {}
90unsafe impl<K: Kernel> Sync for Process<K> {}
91
92list::define_adapter!(pub ProcessListAdapter<K: Kernel> => Process<K>::link);
93list::define_adapter!(pub ProcessThreadListAdapter<K: Kernel> => Thread<K>::process_link);
94
95impl<K: Kernel> Process<K> {
96    /// Creates a new, empty, unregistered process.
97    #[must_use]
98    pub const fn new(
99        name: &'static str,
100        memory_config: <K::ThreadState as ThreadState>::MemoryConfig,
101        #[cfg(feature = "user_space")] object_table: ForeignBox<dyn ObjectTable<K>>,
102    ) -> Self {
103        Self {
104            link: Link::new(),
105            name,
106            memory_config,
107            #[cfg(feature = "user_space")]
108            object_table,
109            #[cfg(feature = "user_space")]
110            object: None,
111            thread_list: UnsafeList::new(),
112            ref_count: K::AtomicUsize::ZERO,
113            state: ProcessState::Inactive,
114            join_event: None,
115            exit_status: None,
116        }
117    }
118
119    /// Manually increment the processes refcount
120    ///
121    /// SAFETY: This should only be done by the scheduler to maintain a
122    /// virtual, reference on the kernel process during initialization.
123    pub(super) unsafe fn manually_increment_ref_count(&mut self) {
124        self.ref_count.fetch_add(1, Ordering::Acquire);
125    }
126
127    #[cfg(feature = "user_space")]
128    pub fn get_object(
129        &self,
130        kernel: K,
131        handle: u32,
132    ) -> Option<ForeignRc<K::AtomicUsize, dyn KernelObject<K>>> {
133        self.object_table.get_object(kernel, handle)
134    }
135
136    #[cfg(feature = "user_space")]
137    pub fn reset_objects(&self, kernel: K) -> Result<()> {
138        self.object_table.reset_all(kernel)
139    }
140
141    /// # Safety
142    /// Caller must ensure exclusive access to the process and `thread` and all
143    /// threads in the process' thread list.  This can be accomplished by holding
144    /// the scheduler lock.
145    pub unsafe fn add_to_thread_list(&mut self, thread: &mut Thread<K>) {
146        // SAFETY: Caller guarantees exclusive access to the process and `thread`
147        // and all threads in the process' thread list.
148        unsafe {
149            let thread = NonNull::from(thread);
150            pw_assert::assert!(!self.thread_list.is_element_linked(thread));
151            self.thread_list.push_front_unchecked(thread);
152        }
153    }
154
155    pub fn range_has_access(&self, access_type: MemoryRegionType, range: Range<usize>) -> bool {
156        self.memory_config
157            .range_has_access(access_type, range.start, range.end)
158    }
159
160    /// A simple ID for debugging purposes, currently the pointer to the thread
161    /// structure itself.
162    ///
163    /// # Safety
164    ///
165    /// The returned value should not be relied upon as being a valid pointer.
166    /// Even in the current implementation, `id` does not expose the pointer's
167    /// provenance.
168    #[must_use]
169    pub fn id(&self) -> usize {
170        // Note: any changes to this also need to be reflected in
171        // `const_id_from_process_address`.
172        core::ptr::from_ref(self).addr()
173    }
174
175    /// Computes the ID of a process from its address.
176    ///
177    /// # Safety
178    ///
179    /// This exists to allow process annotations to be generated at compile time
180    /// for static processes that are initialized at runtime. This should not be
181    /// called in any other circumstance.
182    #[must_use]
183    pub const unsafe fn const_id_from_process_address(addr: *const ()) -> *const () {
184        addr
185    }
186
187    pub fn dump(&self, kernel: K) {
188        info!(
189            "Process '{}' ({:#010x}) state: {}",
190            self.name as &str,
191            self.id() as usize,
192            process_state_to_string(self.state) as &str
193        );
194        #[cfg(feature = "user_space")]
195        {
196            self.object_table.dump(kernel);
197        }
198        #[cfg(not(feature = "user_space"))]
199        {
200            // Suppress unused warning when user_space not enabled.
201            let _ = kernel;
202        }
203        unsafe {
204            let _ = self
205                .thread_list
206                .for_each(|thread| -> core::result::Result<(), ()> {
207                    thread.dump();
208                    Ok(())
209                });
210        }
211    }
212}
213
214pub struct ProcessHandle<K: Kernel> {
215    pub(crate) process: NonNull<Process<K>>,
216    kernel: K,
217}
218
219// Safety: ProcessHandle is a handle to a reference counted process.  All operations
220// on the process are protected by the scheduler lock or atomic operations.
221unsafe impl<K: Kernel> Send for ProcessHandle<K> {}
222unsafe impl<K: Kernel> Sync for ProcessHandle<K> {}
223
224impl<K: Kernel> ProcessHandle<K> {
225    // `ProcessHandle`s should only be created when adding a process to the
226    // scheduler.
227    pub(super) fn new(process: NonNull<Process<K>>, kernel: K) -> Self {
228        unsafe {
229            process.as_ref().ref_count.fetch_add(1, Ordering::Acquire);
230        }
231        Self { process, kernel }
232    }
233
234    /// Request termination of the process.
235    ///
236    /// Sets the process state to Terminating and requests termination for all
237    /// threads in the process.
238    ///
239    /// This is an ASYNCHRONOUS operation.
240    pub fn terminate(&self, kernel: K, status: ExitStatus) {
241        kernel
242            .get_scheduler()
243            .lock(kernel)
244            .process_terminate(kernel, self, status);
245    }
246
247    /// Returns the current state of the process.
248    #[must_use]
249    pub fn get_state_locked(
250        &self,
251        _sched: &SpinLockGuard<'_, K, SchedulerState<K>>,
252    ) -> ProcessState {
253        // SAFETY: `self.process` is guaranteed to be valid because it is reference
254        // counted.  The state is guaranteed to be coherent because the sched lock
255        // is taken.
256        unsafe { self.process.as_ref().state }
257    }
258
259    pub fn join(self, kernel: K) -> Result<(ForeignBox<Process<K>>, ExitStatus)> {
260        match self.join_until(kernel, Instant::<K::Clock>::MAX) {
261            crate::scheduler::ProcessJoinResult::Joined(process, status) => {
262                #[cfg(feature = "user_space")]
263                process.reset_objects(kernel)?;
264                Ok((process, status))
265            }
266            crate::scheduler::ProcessJoinResult::Err { error, .. } => Err(error),
267        }
268    }
269
270    /// Attempts to join the referenced process.
271    ///
272    /// If `ProcessTryJoinResult::Joined` is returned, the caller is responsible
273    /// for resetting the process's objects using `process.reset_objects(kernel)`.
274    pub fn try_join(self, kernel: K) -> crate::scheduler::ProcessTryJoinResult<K> {
275        let (_, res) = kernel
276            .get_scheduler()
277            .lock(kernel)
278            .process_try_join(kernel, self, None);
279        res
280    }
281
282    /// Join the referenced process with a deadline
283    ///
284    /// Waits until the all other references to the process are dropped and the
285    /// process terminates.
286    pub fn join_until(
287        mut self,
288        kernel: K,
289        deadline: Instant<K::Clock>,
290    ) -> crate::scheduler::ProcessJoinResult<K> {
291        let join_event = Event::new(kernel, EventConfig::ManualReset);
292        loop {
293            let (_, res) = kernel.get_scheduler().lock(kernel).process_try_join(
294                kernel,
295                self,
296                Some(join_event.get_signaler()),
297            );
298            match res {
299                crate::scheduler::ProcessTryJoinResult::Err {
300                    error: e,
301                    process: process_handle,
302                } => {
303                    return crate::scheduler::ProcessJoinResult::Err {
304                        error: e,
305                        process: process_handle,
306                    };
307                }
308                crate::scheduler::ProcessTryJoinResult::Joined(process_box, status) => {
309                    return crate::scheduler::ProcessJoinResult::Joined(process_box, status);
310                }
311                crate::scheduler::ProcessTryJoinResult::Wait(process_handle) => {
312                    self = process_handle
313                }
314            };
315
316            if let Err(e) = join_event.wait_until(deadline) {
317                kernel
318                    .get_scheduler()
319                    .lock(kernel)
320                    .process_cancel_try_join(&mut self);
321
322                return crate::scheduler::ProcessJoinResult::Err {
323                    error: e,
324                    process: self,
325                };
326            }
327        }
328    }
329
330    /// Drop the `ProcessHandle` while the scheduler lock is held.
331    ///
332    /// This is an internal version for use by the scheduler while it is holding
333    /// the scheduler lock.
334    pub(super) fn drop_locked(
335        mut self,
336        kernel: K,
337        mut sched: SpinLockGuard<'_, K, SchedulerState<K>>,
338    ) -> SpinLockGuard<'_, K, SchedulerState<K>> {
339        unsafe {
340            let prev_value = self
341                .process
342                .as_ref()
343                .ref_count
344                .fetch_sub(1, Ordering::Release);
345
346            // If this ref was one of two outstanding references to the process,
347            // the other reference may be attempting to join.  Let the scheduler
348            // notify the join request if it is outstanding.
349            if prev_value == 2 {
350                sched = sched.process_signal_join(kernel, &mut self);
351            }
352        }
353
354        // Ensure that the trait version of drop is not run.
355        let _ = ManuallyDrop::new(self);
356        sched
357    }
358
359    pub fn add_thread(&mut self, kernel: K, thread_handle: &mut ThreadHandle<K>) -> Result<()> {
360        kernel
361            .get_scheduler()
362            .lock(kernel)
363            .process_add_thread(self, thread_handle)
364    }
365
366    pub fn range_has_access_locked(
367        &self,
368        _sched: &SpinLockGuard<'_, K, SchedulerState<K>>,
369        region_type: MemoryRegionType,
370        range: Range<usize>,
371    ) -> bool {
372        // SAFETY: `self.process` is valid because `ProcessHandle` guarantees the
373        // lifetime of the pointed-to `Process`.
374        unsafe { self.process.as_ref().range_has_access(region_type, range) }
375    }
376}
377
378impl<K: Kernel> Clone for ProcessHandle<K> {
379    fn clone(&self) -> Self {
380        unsafe {
381            self.process
382                .as_ref()
383                .ref_count
384                .fetch_add(1, Ordering::Acquire);
385        }
386
387        Self {
388            process: self.process,
389            kernel: self.kernel,
390        }
391    }
392}
393
394impl<K: Kernel> Drop for ProcessHandle<K> {
395    fn drop(&mut self) {
396        unsafe {
397            let prev_value = self
398                .process
399                .as_ref()
400                .ref_count
401                .fetch_sub(1, Ordering::Release);
402
403            // If this ref was one of two outstanding references to the process,
404            // the other reference may be attempting to join.  Let the scheduler
405            // notify the join request if it is outstanding.
406            if prev_value == 2 {
407                let _ = self
408                    .kernel
409                    .get_scheduler()
410                    .lock(self.kernel)
411                    .process_signal_join(self.kernel, self);
412            }
413        }
414    }
415}
416
417/// Add debug annotations for a static process
418///
419/// This macro is called by `init_non_priv_process` and should not be called
420/// directly.
421#[macro_export]
422macro_rules! annotate_process_from_address {
423    ($name:expr, $arch:ty, $process_address:expr) => {{
424        #[repr(C, packed(1))]
425        struct ProcessAnnotation {
426            name: &'static str,
427            id: *const (),
428        }
429        unsafe impl Sync for ProcessAnnotation {};
430
431        #[unsafe(link_section = ".pw_kernel.annotations.process")]
432        #[used]
433        static _PROCESS_ANNOTATION: ProcessAnnotation = ProcessAnnotation {
434            name: $name,
435            id: unsafe {
436                $crate::Process::<$arch>::const_id_from_process_address(
437                    $process_address as *const (),
438                )
439            },
440        };
441    }};
442}
443
444/// Declare static storage for a non-privileged process.
445///
446/// Creates a static in named `storage_ident` in the calling scope which holds
447/// the storage for a static process.
448#[cfg(feature = "user_space")]
449#[macro_export]
450macro_rules! declare_non_priv_process_storage {
451    ($storage_ident:ident) => {
452        static $storage_ident: $crate::__private::foreign_box::StaticStorage<
453            $crate::scheduler::Process<arch::Arch>,
454        > = $crate::__private::foreign_box::StaticStorage::new();
455    };
456}
457
458/// Get the constant process ID of a non-privileged process.
459#[cfg(feature = "user_space")]
460#[macro_export]
461macro_rules! non_priv_process_id {
462    ($storage:expr) => {{
463        use $crate::scheduler::Process;
464        unsafe {
465            Process::<arch::Arch>::const_id_from_process_address(unsafe { $storage.address() })
466        }
467    }};
468}
469
470/// Declares a new [`Process`] in a previously declared static process storage.
471///
472/// # Safety
473///
474/// Each invocation of `declare_non_priv_process!` must be executed at most once at
475/// run time.
476#[cfg(feature = "user_space")]
477#[macro_export]
478macro_rules! declare_non_priv_process {
479    ($storage:expr, $name:literal, $memory_config:expr, $object_table:expr $(,)?) => {{
480        use $crate::__private::foreign_box::StaticStorage;
481        use $crate::Kernel;
482        use $crate::object::ObjectTable;
483        use $crate::scheduler::Process;
484
485        /// SAFETY: This must be executed at most once at run time.  See
486        /// StaticStorage::init() for more details.
487        #[allow(clippy::mut_from_ref)]
488        unsafe fn __declare_non_priv_process(
489            storage: &'static StaticStorage<Process<arch::Arch>>,
490            object_table: ForeignBox<dyn ObjectTable<arch::Arch>>,
491        ) -> ForeignBox<Process<arch::Arch>> {
492            use pw_log::info;
493            use $crate::__private::foreign_box::ForeignBox;
494            info!(
495                "Allocating non-privileged process '{}'",
496                $name as &'static str
497            );
498
499            // SAFETY: The caller promises that this function will be executed
500            // at most once.
501            let proc = unsafe { storage.init(Process::new($name, $memory_config, object_table)) };
502            ForeignBox::from(proc)
503        }
504
505        $crate::annotate_process_from_address!($name, arch::Arch, unsafe { $storage.address() });
506        __declare_non_priv_process(&$storage, $object_table)
507    }};
508}