1use 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#[derive(Copy, Clone, PartialEq)]
42pub enum ProcessState {
43 Inactive,
45
46 Active,
48
49 Terminating,
51
52 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 pub link: Link,
68
69 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
88unsafe 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 #[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 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 pub unsafe fn add_to_thread_list(&mut self, thread: &mut Thread<K>) {
146 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 #[must_use]
169 pub fn id(&self) -> usize {
170 core::ptr::from_ref(self).addr()
173 }
174
175 #[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 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
219unsafe impl<K: Kernel> Send for ProcessHandle<K> {}
222unsafe impl<K: Kernel> Sync for ProcessHandle<K> {}
223
224impl<K: Kernel> ProcessHandle<K> {
225 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 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 #[must_use]
249 pub fn get_state_locked(
250 &self,
251 _sched: &SpinLockGuard<'_, K, SchedulerState<K>>,
252 ) -> ProcessState {
253 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 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 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 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 prev_value == 2 {
350 sched = sched.process_signal_join(kernel, &mut self);
351 }
352 }
353
354 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 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 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#[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#[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#[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#[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 #[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 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}