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.rs

kernel/
object.rs

1// Copyright 2025 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::any::Any;
16use core::cell::{Cell, UnsafeCell};
17use core::ptr::NonNull;
18
19use foreign_box::{ForeignBox, ForeignRc};
20use list::{self, Link, RandomAccessForeignList};
21use pw_status::{Error, Result};
22use pw_time_core::Instant;
23pub use syscall_defs::{ExitStatus, Signals, WaitReturn};
24
25use crate::Kernel;
26use crate::scheduler::{SchedulerState, WakeList};
27use crate::sync::event::{Event, EventConfig, EventSignaler};
28use crate::sync::spinlock::{SpinLock, SpinLockGuard};
29
30mod base;
31mod buffer;
32mod channel;
33mod interrupt;
34mod process;
35mod thread;
36
37pub use base::{ObjectBase, WaitGroupObject};
38pub use buffer::SyscallBuffer;
39pub use channel::{Channel, ChannelHandlerObject, ChannelInitiatorObject};
40pub use interrupt::InterruptObject;
41pub use process::{MainThread, ProcessObject};
42pub use thread::ThreadObject;
43
44/// Trait that all kernel objects implement.
45///
46/// The methods on this trait map directly to the kernel's system calls.
47pub trait KernelObject<K: Kernel>: Any + Send + Sync {
48    fn base(&self) -> Option<&ObjectBase<K>> {
49        None
50    }
51
52    /// Dump the object's state for debugging.
53    fn dump(&self, kernel: K) {
54        if let Some(base) = self.base() {
55            base.dump(kernel);
56        }
57    }
58    /// Wait on a set of signals to be active.
59    ///
60    /// Blocks until any of the signals in `signal_mask` are active on the object
61    /// or `deadline` has expired.
62    #[allow(unused_variables)]
63    fn object_wait(
64        &self,
65        kernel: K,
66        signal_mask: Signals,
67        deadline: Instant<K::Clock>,
68    ) -> Result<WaitReturn> {
69        Err(Error::Unimplemented)
70    }
71
72    /// Add an `object` to a `WaitGroupObject`.
73    ///
74    /// `object_wait()` on the `WaitGroup` will return if any of the signals
75    /// in `signal_mask` are active on the object, return the value of `user_data`.
76    ///
77    /// # Safety
78    /// Caller must ensure that `self` is a reference storage that is contained
79    /// inside a [`foreign_box::ForeignRcState<A, T>`].
80    #[allow(unused_variables)]
81    unsafe fn wait_group_add(
82        &self,
83        kernel: K,
84        object: &dyn KernelObject<K>,
85        signal_mask: Signals,
86        user_data: usize,
87    ) -> Result<()> {
88        Err(Error::Unimplemented)
89    }
90
91    /// Remove an `object` to a `WaitGroupObject`.
92    #[allow(unused_variables)]
93    fn wait_group_remove(&self, kernel: K, object: &dyn KernelObject<K>) -> Result<()> {
94        Err(Error::Unimplemented)
95    }
96
97    #[allow(unused_variables)]
98    fn channel_transact(
99        &self,
100        kernel: K,
101        send_buffer: SyscallBuffer,
102        recv_buffer: SyscallBuffer,
103        deadline: Instant<K::Clock>,
104    ) -> Result<usize> {
105        Err(Error::Unimplemented)
106    }
107
108    #[allow(unused_variables)]
109    fn channel_async_transact(
110        &self,
111        kernel: K,
112        send_buffer: SyscallBuffer,
113        recv_buffer: SyscallBuffer,
114    ) -> Result<()> {
115        Err(Error::Unimplemented)
116    }
117
118    #[allow(unused_variables)]
119    fn channel_async_transact_complete(&self, kernel: K) -> Result<usize> {
120        Err(Error::Unimplemented)
121    }
122
123    #[allow(unused_variables)]
124    fn channel_async_cancel(&self, kernel: K) -> Result<()> {
125        Err(Error::Unimplemented)
126    }
127
128    #[allow(unused_variables)]
129    fn channel_read(&self, kernel: K, offset: usize, read_buffer: SyscallBuffer) -> Result<usize> {
130        Err(Error::Unimplemented)
131    }
132
133    #[allow(unused_variables)]
134    fn channel_respond(&self, kernel: K, response_buffer: SyscallBuffer) -> Result<()> {
135        Err(Error::Unimplemented)
136    }
137
138    #[allow(unused_variables)]
139    fn interrupt_ack(&self, kernel: K, signal_mask: Signals) -> Result<()> {
140        Err(Error::Unimplemented)
141    }
142
143    #[allow(unused_variables)]
144    fn thread_start(&self, kernel: K, initial_pc: usize, initial_sp: usize) -> Result<()> {
145        Err(Error::Unimplemented)
146    }
147
148    #[allow(unused_variables)]
149    fn task_terminate(&self, kernel: K) -> Result<()> {
150        Err(Error::Unimplemented)
151    }
152
153    #[allow(unused_variables)]
154    fn task_join(&self, kernel: K) -> Result<ExitStatus> {
155        Err(Error::Unimplemented)
156    }
157
158    #[allow(unused_variables)]
159    fn process_start(&self, kernel: K) -> Result<()> {
160        Err(Error::Unimplemented)
161    }
162
163    /// Set (`set=true`) or clear (`set=false`) `Signals::USER` on the paired peer.
164    #[allow(unused_variables)]
165    fn object_set_peer_user_signal(&self, kernel: K, set: bool) -> Result<()> {
166        Err(Error::Unimplemented)
167    }
168
169    /// Reset the object's signals to its initial signals.
170    fn reset(&self, _kernel: K) -> Result<()> {
171        Ok(())
172    }
173}
174
175trait WaiterState<K: Kernel> {
176    fn waiters(
177        &mut self,
178    ) -> &mut RandomAccessForeignList<ObjectWaiter<K>, ObjectWaiterListAdapter<K>>;
179}
180
181fn wait_on_object<'a, K: Kernel, S: WaiterState<K>>(
182    kernel: K,
183    object_lock: &'a SpinLock<K, S>,
184    mut object_state: SpinLockGuard<'a, K, S>,
185    signal_mask: Signals,
186    deadline: Instant<K::Clock>,
187) -> Result<WaitReturn> {
188    let event = Event::new(kernel, EventConfig::ManualReset);
189    let waiter = ObjectWaiter {
190        link: Link::new(),
191        signaler: Cell::new(Some(event.get_signaler())),
192        signal_mask,
193        wait_result: WaitResult::new(),
194    };
195
196    // Safety: `waiter_box`'s membership in `self.waiters` is managed by
197    // and never outlives this function's lifetime.
198    let waiter_box = unsafe { ForeignBox::new(NonNull::from_ref(&waiter)) };
199
200    let key = object_state.waiters().push_back(waiter_box);
201
202    // Drop state lock while waiting.
203    drop(object_state);
204    let wait_result = event.wait_until(deadline);
205    let mut state = object_lock.lock(kernel);
206
207    // Before processing the wait result, we remove the waiter from the queue.
208    let waiter_box = state.waiters().remove_element(key);
209
210    let result = match wait_result {
211        Err(e) => Err(e),
212        // Safety: Since `waiter_box` has been removed from the object's
213        // `waiters` list, there is no way for another thread to have a
214        // reference to the waiter.
215        _ => unsafe { waiter_box.wait_result.get() },
216    };
217
218    // `waiter_box` is no longer referenced and is safe to consume.
219    waiter_box.consume();
220
221    result
222}
223
224// For all objects except wait groups, `wake_signals`` and `return_signals`` should be
225// the same.  For a wait group, the wake_signal is READABLE, and the return signal
226// is the signal of the woken element.
227pub(crate) fn signal_all_matching_waiters_with_return_signals_locked<'a, K: Kernel>(
228    kernel: K,
229    mut sched: SpinLockGuard<'a, K, SchedulerState<K>>,
230    waiters: &mut RandomAccessForeignList<ObjectWaiter<K>, ObjectWaiterListAdapter<K>>,
231    wake_signals: Signals,
232    return_signals: Signals,
233    user_data: usize,
234) -> SpinLockGuard<'a, K, SchedulerState<K>> {
235    // Dequeue matching waiters into a WakeList and wake them after the loop.
236    let mut wake_list = WakeList::new();
237
238    for waiter in waiters.iter() {
239        if waiter.signal_mask.intersects(wake_signals) {
240            // It is important to pass the signaler by value instead of cloning
241            // it in order to support stack allocated waiters.  The signaler
242            // needs to be dropped before the thread is woken and the underlying
243            // event is dropped.
244            if let Some(signaler) = waiter.signaler.take() {
245                // SAFETY: While a waiter is in an object's `waiters` list, that
246                // object has exclusive access to the waiter.  The below
247                // operation is done with the object's spinlock held.
248                unsafe {
249                    waiter.wait_result.set(Ok(WaitReturn {
250                        user_data,
251                        pending_signals: return_signals,
252                    }))
253                };
254                sched = signaler.signal_and_dequeue_locked(sched, &mut wake_list);
255            }
256        }
257    }
258
259    wake_list.wake_and_reschedule(kernel, sched)
260}
261
262pub(crate) fn signal_all_matching_waiters_locked<'a, K: Kernel>(
263    kernel: K,
264    sched: SpinLockGuard<'a, K, SchedulerState<K>>,
265    waiters: &mut RandomAccessForeignList<ObjectWaiter<K>, ObjectWaiterListAdapter<K>>,
266    active_signals: Signals,
267    user_data: usize,
268) -> SpinLockGuard<'a, K, SchedulerState<K>> {
269    signal_all_matching_waiters_with_return_signals_locked(
270        kernel,
271        sched,
272        waiters,
273        active_signals,
274        active_signals,
275        user_data,
276    )
277}
278
279list::define_adapter!(pub ObjectWaiterListAdapter<K: Kernel> => ObjectWaiter<K>::link);
280
281struct WaitResult {
282    result: UnsafeCell<Result<WaitReturn>>,
283}
284
285impl WaitResult {
286    pub const fn new() -> Self {
287        Self {
288            result: UnsafeCell::new(Err(Error::Unknown)),
289        }
290    }
291
292    /// Safety: Users of [`WaitResult::get()`] and [`WaitResult::set()`] must
293    /// ensure that their calls into them are not done concurrently.
294    unsafe fn get(&self) -> Result<WaitReturn> {
295        unsafe { *self.result.get() }
296    }
297
298    /// Safety: Users of [`WaitResult::get()`] and [`WaitResult::set()`] must
299    /// ensure that their calls into them are not done concurrently.
300    unsafe fn set(&self, result: Result<WaitReturn>) {
301        unsafe { (*self.result.get()) = result }
302    }
303}
304
305pub struct ObjectWaiter<K: Kernel> {
306    link: Link,
307    // Interior mutability is used so that the signaler can be taken when it is
308    // signaled/woken by the object.
309    signaler: Cell<Option<EventSignaler<K>>>,
310    signal_mask: Signals,
311    wait_result: WaitResult,
312}
313
314/// Translates handles to dynamic references to kernel objects.
315///
316/// `ObjectTable` is a trait to allow for both static and dynamic tables to be
317/// used in the same time.
318pub trait ObjectTable<K: Kernel>: Send + Sync {
319    fn get_object(
320        &self,
321        kernel: K,
322        handle: u32,
323    ) -> Option<ForeignRc<K::AtomicUsize, dyn KernelObject<K>>>;
324
325    /// Dump the object table's state for debugging.
326    fn dump(&self, kernel: K);
327
328    fn reset_all(&self, kernel: K) -> Result<()>;
329}
330/// An object table with no entries.
331///
332/// This may be replaced with a static object tables with no entries.
333pub struct NullObjectTable {}
334
335impl NullObjectTable {
336    #[must_use]
337    pub const fn new() -> Self {
338        Self {}
339    }
340}
341
342impl<K: Kernel> ObjectTable<K> for NullObjectTable {
343    fn get_object(
344        &self,
345        _kernel: K,
346        _handle: u32,
347    ) -> Option<ForeignRc<K::AtomicUsize, dyn KernelObject<K>>> {
348        None
349    }
350
351    fn dump(&self, _kernel: K) {
352        pw_log::info!("      No objects in table.");
353    }
354
355    fn reset_all(&self, _kernel: K) -> Result<()> {
356        Ok(())
357    }
358}
359
360impl<const N: usize, K: Kernel> ObjectTable<K>
361    for [ForeignRc<<K>::AtomicUsize, dyn KernelObject<K>>; N]
362{
363    fn get_object(
364        &self,
365        _kernel: K,
366        handle: u32,
367    ) -> Option<ForeignRc<<K>::AtomicUsize, dyn KernelObject<K>>> {
368        self.get(handle as usize).cloned()
369    }
370
371    fn dump(&self, kernel: K) {
372        for (i, obj) in self.iter().enumerate() {
373            pw_log::info!("      Object {}:", i as usize);
374            obj.dump(kernel);
375        }
376    }
377
378    fn reset_all(&self, kernel: K) -> Result<()> {
379        for obj in self.iter() {
380            obj.reset(kernel)?;
381        }
382        Ok(())
383    }
384}
385
386/// A masked signal update applied by [`ObjectBase::signal`].
387///
388/// All bits in `mask` are updated to match `values`; bits outside `mask`
389/// are preserved.
390#[derive(Copy, Clone)]
391pub struct SignalUpdate {
392    mask: Signals,
393    values: Signals,
394}
395
396impl SignalUpdate {
397    #[must_use]
398    #[inline(always)]
399    pub const fn raise(raise: Signals) -> Self {
400        Self {
401            mask: raise,
402            values: raise,
403        }
404    }
405
406    #[must_use]
407    #[inline(always)]
408    pub const fn clear(clear: Signals) -> Self {
409        Self {
410            mask: clear,
411            values: Signals::no_active(),
412        }
413    }
414
415    #[must_use]
416    #[inline(always)]
417    pub const fn set_if(signal: Signals, cond: bool) -> Self {
418        Self {
419            mask: signal,
420            values: if cond { signal } else { Signals::no_active() },
421        }
422    }
423
424    #[must_use]
425    #[inline(always)]
426    pub const fn and_raise(self, raise: Signals) -> Self {
427        Self {
428            mask: self.mask.union(raise),
429            values: self.values.union(raise),
430        }
431    }
432
433    #[must_use]
434    #[inline(always)]
435    pub const fn and_clear(self, clear: Signals) -> Self {
436        Self {
437            mask: self.mask.union(clear),
438            values: self.values.difference(clear),
439        }
440    }
441
442    #[must_use]
443    #[inline(always)]
444    pub const fn apply(self, signals: Signals) -> Signals {
445        signals.difference(self.mask).union(self.values)
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use unittest::test;
452
453    use super::*;
454
455    #[test]
456    fn signal_update_raise() -> unittest::Result<()> {
457        let initial = Signals::READABLE;
458        let updated = SignalUpdate::raise(Signals::WRITEABLE).apply(initial);
459        unittest::assert_eq!(updated, Signals::READABLE | Signals::WRITEABLE);
460        Ok(())
461    }
462
463    #[test]
464    fn signal_update_clear() -> unittest::Result<()> {
465        let initial = Signals::READABLE | Signals::WRITEABLE;
466        let updated = SignalUpdate::clear(Signals::READABLE).apply(initial);
467        unittest::assert_eq!(updated, Signals::WRITEABLE);
468        Ok(())
469    }
470
471    #[test]
472    fn signal_update_set_if() -> unittest::Result<()> {
473        let initial = Signals::READABLE;
474        unittest::assert_eq!(
475            SignalUpdate::set_if(Signals::USER, true).apply(initial),
476            Signals::READABLE | Signals::USER
477        );
478        unittest::assert_eq!(
479            SignalUpdate::set_if(Signals::READABLE, false).apply(initial),
480            Signals::no_active()
481        );
482        Ok(())
483    }
484
485    #[test]
486    fn signal_update_chained_and_raise_and_clear() -> unittest::Result<()> {
487        let initial = Signals::READABLE | Signals::USER;
488        let updated = SignalUpdate::clear(Signals::READABLE)
489            .and_raise(Signals::WRITEABLE)
490            .and_clear(Signals::USER)
491            .apply(initial);
492        unittest::assert_eq!(updated, Signals::WRITEABLE);
493        Ok(())
494    }
495}