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

syscall_defs/
syscall_defs.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
15//! # pw_kernel User Space API
16//!
17//! ## Core Concepts
18//!
19//! ### Objects
20//! Objects are the basic building block of functionality exposed to user space.
21//! They are polymorphic and may be one of a limited set of types:
22//!
23//! - [Channel](#channel)
24//! - [Wait Group](#wait-group)
25//! - TODO: <https://pwbug.dev/496975012> - add other objects.
26//!
27//! ### Handles
28//! All system calls reference objects through a u32 handle which indexes into
29//! a process-local handle table.
30//!
31//! ### Signals and Waiting
32//! Every kernel object has a set of signals that can be pending and waited
33//! upon.  The exact meaning and semantics of each signal vary between kernel
34//! objects.  The signal types are:
35//! - `Signals::READABLE`: Object is readable.
36//! - `Signals::WRITABLE`: Object is writable.
37//! - `Signals::ERROR`: Object is in an error state.
38//! - `Signals::USER`: User defined signal.  Useful for out of band signaling
39//!   between peers on a [Channel](#channel).
40//!
41//! Any kernel object can be waited for signals to assert using the
42//! [`object_wait()`] syscall.  Multiple objects can be waited on simultaneously
43//! using a [Wait Group](#wait-group) object.
44//!
45//! #### Open Questions
46//! - What are the multi-threaded semantics of waiting.
47//!
48//! ### Object and Handle Creation
49//! Initially only statically defined and allocated objects and handles are
50//! supported.  The creation of these will be driven through build time
51//! configuration and the necessary code will be generated to allocate kernel
52//! data structures as well as expose handle definitions to user space
53//! processes.
54//!
55//! ## Object Types
56//!
57//! ### Channel
58//! A channel is a unidirectional connection between two asymmetric peers: an
59//! initiator and a handler.  A channel allows the initiator peer to send a
60//! buffer of data to the handler peer and wait for it's response.  A channel
61//! can have a maximum of one transaction pending at a time and is designed to
62//! not require intermediate kernel buffers.
63//!
64//! Both a synchronous and asynchronous API is offered to the initiator
65//! while the handler side API is strictly non-blocking.  All data copies
66//! between peers happen during the system call.
67//!
68//! The flow of a transaction is as follows:
69//! - The initiator starts the transaction by providing send and receive
70//!   buffers to one of the two transact system calls ([`channel_transact()`] or
71//!   [`channel_async_transact()`]). This has the additional side effect of
72//!   clearing `Signals::READABLE` and `Signals::WRITABLE` on the initiator.
73//! - The handler's `Signals::READABLE` will become asserted.
74//! - The handler can now read the message in multiple calls to
75//!   [`channel_read()`] causing the kernel to copy the data from the
76//!   initiator's send buffer to the buffer provided to [`channel_read()`].
77//! - The handler completes the transaction by calling [`channel_respond()`]
78//!   and providing a response.  The kernel will immediately copy the response
79//!   from the handler's buffer to the initiator's receive buffer.
80//!   There is no built in mechanism for the handler to signal an error
81//!   to the initiator.  This is left to the higher level protocol used to
82//!   communicate over the channel.  This will clear `Signals::READABLE` and
83//!   `Signals::WRITABLE` on the handler and raise `Signals::READABLE` on
84//!   the initiator.
85//!
86//! The handler's only ways of communicating with the initiator are by
87//! - responding to an initiated transaction
88//! - raising `Signals::USER` on the initiator by calling
89//!   [`object_set_peer_user_signal()`]
90//!
91//! #### Initiator Signals
92//! - `Signals::WRITABLE` indicates there is no pending transaction and one
93//!   can be started. Cleared on transaction initiation.
94//! - `Signals::READABLE` indicates the handler has responded to the
95//!   pending transaction.  Cleared on transaction initiation.
96//! - `Signals::ERROR` indicates pending transaction has an error.  Cleared
97//!   when the initiator is waited on.
98//! - `Signals::USER` indicates the handler calls [`object_set_peer_user_signal()`].
99//!   Cleared when the handler calls [`object_set_peer_user_signal()`] with `set=false`,
100//!   or automatically by the kernel if the initiator handler terminates. Preserved on
101//!   initiator process termination.
102//!
103//! #### Handler Signals
104//! - `Signals::READABLE` indicates there is a pending transaction.  Cleared when
105//!   the handler calls [`channel_respond()`].
106//! - `Signals::WRITABLE` indicates there is a pending transaction.  Cleared when
107//!   the handler calls [`channel_respond()`].
108//! - `Signals::ERROR` indicates a pending transaction error.  No error states
109//!   are defined at the moment.  In the future an error may be raised when
110//!   the remote peer closes.
111//! - `Signals::USER` indicates the initiator calls [`object_set_peer_user_signal()`].
112//!   Cleared when the initiator calls [`object_set_peer_user_signal()`] with `set=false`,
113//!   or automatically by the kernel if the initiator process terminates. Preserved on
114//!   handler process termination.
115//!
116//! ### Wait Group
117//! Wait groups provide a mechanism for waiting on multiple handles at once.
118//! Handles can be added to and removed from a wait group with [`wait_group_add()`]
119//! and [`wait_group_remove()`].  In addition to a set of signals to wait on,
120//! an arbitrary `user_data` is provided to [`wait_group_add()`].  This value
121//! is returned by [`object_wait()`], unmodified by the kernel, when the wait group is
122//! waited on.
123//!
124//! #### Open questions:
125//! - How is the wait group's member list allocated in there kernel.  To support
126//!   a fully statically allocated kernel one of two approaches are being
127//!   considered:
128//!   - an object (or possibly handle) may only be in a single wait group at
129//!     one time.  This allows a wait group to maintain an intrusive list of
130//!     objects with the list element storage being stored in the object.
131//!   - wait queues are statically sized at compile time and adding more objects
132//!     than there is space for will return an error.
133//!
134//! ### Interrupt
135//! Interrupt objects provide a mechanism for handling hardware interrupts.
136//! A single Interrupt object can be configured to handle multiple interrupt
137//! sources (IRQs), up to a maximum of 16 per object.
138
139//! Each interrupt source handled by an Interrupt object is mapped to a unique
140//! signal bit within the higher 16 bits of `Signals`. These signals
141//! range from `Signals::INTERRUPT_A` (bit 16) to `Signals::INTERRUPT_O` (bit 30).
142//!
143//! When a interrupt occurs for a source handled by an Interrupt object, the kernel
144//! masks the interrupt and then signals the corresponding `INTERRUPT_` bit on the
145//! object. Userspace threads can wait on the Interrupt object using the
146//! [`object_wait()`] syscall.
147//!
148//! Upon waking from `object_wait()`, the returned `Signals` mask indicates which
149//! interrupt(s) have triggered. After the userspace handler has serviced the
150//! interrupt(s), it must call the [`interrupt_ack()`] syscall to allow the
151//! interrupt(s) to be triggered again. This syscall must be provided with a
152//! `Signals` mask containing the bits for the interrupts that have been
153//! handled.
154//!
155//! [`interrupt_ack()`] accomplishes two things:
156//! 1. It clears the specified signal bits on the Interrupt object, allowing it to
157//!    receive new signals for those interrupts.
158//! 2. It signals to the underlying hardware interrupt controller (e.g., PLIC or
159//!    NVIC) that the associated IRQ(s) have been acknowledged, re-enabling them
160//!    at the hardware level.
161//!
162//! ### Futex
163//! In design
164//!
165//! ## System Calls
166//! The C ABI system calls listed here are not intended to be called directly
167//! by user space code and instead be accessed through language idiomatic
168//! wrapper libraries.
169//!
170//! ### Generic Syscalls
171//! - [`object_wait()`]
172//! - [`object_set_peer_user_signal()`]
173//!
174//! ### Channel Initiator Syscalls
175//! - [`channel_transact()`]
176//! - [`channel_async_transact()`]
177//! - [`channel_async_transact_complete()`]
178//! - [`channel_async_cancel()`]
179//!
180//! ### Channel Handler Syscalls
181//! - [`channel_read()`]
182//! - [`channel_respond()`]
183//!
184//! ### Wait Group Syscalls
185//! - [`wait_group_add()`]
186//! - [`wait_group_remove()`]
187
188#![no_std]
189
190use bitflags::bitflags;
191use pw_status::{Error, Result};
192
193pub struct SysCallReturnValue {
194    // The return value representing the two return registers.
195    pub value: [usize; 2],
196}
197
198// Errors are encoded as negative values in the first return value of syscalls.
199// This requires that:
200// 1) Error variants values are no greater than isize::MAX (satisfied by inspection)
201// 2) Error fits in a single usize. (satisfied by the assertion below)
202const _: () = assert!(core::mem::size_of::<Error>() <= core::mem::size_of::<usize>());
203
204impl From<SysCallReturnValue> for Result<()> {
205    fn from(ret_value: SysCallReturnValue) -> Result<()> {
206        let val = ret_value.value[0].cast_signed();
207        if val < 0 {
208            // TODO debug assert if error number is out of range
209            let val = (-val).cast_unsigned();
210            // TODO(421404517): Avoid the lossy cast
211            #[allow(clippy::cast_possible_truncation)]
212            Err(unsafe { core::mem::transmute::<u32, Error>(val as u32) })
213        } else {
214            Ok(())
215        }
216    }
217}
218
219impl From<SysCallReturnValue> for Result<u32> {
220    fn from(ret_value: SysCallReturnValue) -> Result<u32> {
221        let val = ret_value.value[0].cast_signed();
222        if val < 0 {
223            // TODO debug assert if error number is out of range
224            let val = (-val).cast_unsigned();
225            // TODO(421404517): Avoid the lossy cast
226            #[allow(clippy::cast_possible_truncation)]
227            Err(unsafe { core::mem::transmute::<u32, Error>(val as u32) })
228        } else {
229            // TODO(421404517): Avoid the lossy cast
230            #[allow(clippy::cast_possible_truncation)]
231            Ok(ret_value.value[0] as u32)
232        }
233    }
234}
235
236impl From<i64> for SysCallReturnValue {
237    fn from(value: i64) -> Self {
238        let unsigned_value = value.cast_unsigned();
239        Self {
240            #[expect(clippy::cast_possible_truncation)]
241            value: [
242                unsigned_value as u32 as usize,
243                (unsigned_value >> 32) as u32 as usize,
244            ],
245        }
246    }
247}
248
249impl From<u64> for SysCallReturnValue {
250    fn from(value: u64) -> Self {
251        Self {
252            #[expect(clippy::cast_possible_truncation)]
253            value: [value as u32 as usize, (value >> 32) as u32 as usize],
254        }
255    }
256}
257
258impl From<SysCallReturnValue> for u64 {
259    fn from(ret_value: SysCallReturnValue) -> u64 {
260        #[allow(clippy::cast_possible_truncation)]
261        let low = ret_value.value[0] as u32;
262        #[allow(clippy::cast_possible_truncation)]
263        let high = ret_value.value[1] as u32;
264        (u64::from(high) << 32) | u64::from(low)
265    }
266}
267
268impl From<Result<u64>> for SysCallReturnValue {
269    fn from(value: Result<u64>) -> Self {
270        match value {
271            Ok(val) => {
272                #[expect(clippy::cast_possible_truncation)]
273                let low = val as u32 as usize;
274                let high = (val >> 32) as u32 as usize;
275                Self { value: [low, high] }
276            }
277            Err(error) => Self::from(-(error as i64)),
278        }
279    }
280}
281
282impl From<Result<()>> for SysCallReturnValue {
283    fn from(value: Result<()>) -> Self {
284        match value {
285            Ok(()) => Self { value: [0, 0] },
286            Err(error) => Self::from(-(error as i64)),
287        }
288    }
289}
290
291impl From<SysCallReturnValue> for Result<WaitReturn> {
292    fn from(ret: SysCallReturnValue) -> Result<WaitReturn> {
293        // TODO(421404517): Avoid the lossy cast
294        #[allow(clippy::cast_possible_truncation)]
295        let val = ret.value[1] as u32;
296        let signals = Signals::from_bits_truncate(val);
297        // Encode that there was an error in the reserved high bit of
298        // the signal mask, and store the error in the data field.
299        if signals.contains(Signals::RESERVED) {
300            // TODO(421404517): Avoid the lossy cast
301            #[allow(clippy::cast_possible_truncation)]
302            Err(unsafe { core::mem::transmute::<u32, Error>(ret.value[0] as u32) })
303        } else {
304            Ok(WaitReturn {
305                user_data: ret.value[0],
306                pending_signals: signals,
307            })
308        }
309    }
310}
311
312impl From<Result<WaitReturn>> for SysCallReturnValue {
313    fn from(value: Result<WaitReturn>) -> Self {
314        match value {
315            Ok(val) => Self {
316                value: [val.user_data, val.pending_signals.bits() as usize],
317            },
318            Err(error) => Self {
319                // Error value is saved in the data field and the reserved bit
320                // is used to indicate an error in the signal mask.
321                value: [error as usize, Signals::RESERVED.bits() as usize],
322            },
323        }
324    }
325}
326
327impl From<Result<ExitStatus>> for SysCallReturnValue {
328    fn from(value: Result<ExitStatus>) -> Self {
329        match value {
330            Ok(status) => Self {
331                // SAFETY: ExitStatus is repr(C, usize) and fits exactly in [usize; 2]
332                // with no padding, as verified by the static assert.
333                value: unsafe { core::mem::transmute::<ExitStatus, [usize; 2]>(status) },
334            },
335            Err(error) => Self::from(-(error as i64)),
336        }
337    }
338}
339
340#[derive(Copy, Clone, PartialEq, Eq)]
341#[repr(u16)]
342pub enum SysCallId {
343    // IDs are not ABI stable yet and are subject to change.
344    SysCallLowerBound = 0x0000,
345    ChannelAsyncCancel = 0x0001,
346    ChannelAsyncTransact = 0x0002,
347    ChannelAsyncTransactComplete = 0x0003,
348    ChannelRead = 0x0004,
349    ChannelRespond = 0x0005,
350    ChannelTransact = 0x0006,
351    InterruptAck = 0x0007,
352    ObjectWait = 0x0008,
353    ProcessExit = 0x0009,
354    ProcessStart = 0x000a,
355    RaisePeerUserSignal = 0x000b,
356    TaskJoin = 0x000c,
357    TaskTerminate = 0x000d,
358    ThreadExit = 0x000e,
359    ThreadStart = 0x000f,
360    WaitGroupAdd = 0x0010,
361    WaitGroupRemove = 0x0011,
362    // Upper bound for standard system calls.
363    SysCallUpperBound = 0x0012,
364
365    // System calls prefixed with 0xF000 are reserved development/debugging use.
366    DebugSysCallLowerBound = 0xf000,
367    DebugPutc = 0xf001,
368    DebugShutdown = 0xf002,
369    DebugLog = 0xf003,
370    DebugNop = 0xf004,
371    DebugTriggerInterrupt = 0xf005,
372    DebugClockNow = 0xf006,
373    // Upper bound for debug system calls.
374    DebugSysCallUpperBound = 0xf007,
375}
376
377impl TryFrom<u16> for SysCallId {
378    type Error = Error;
379
380    fn try_from(value: u16) -> Result<Self> {
381        if (value > SysCallId::SysCallLowerBound as u16
382            && value < SysCallId::SysCallUpperBound as u16)
383            || (value > SysCallId::DebugSysCallLowerBound as u16
384                && value < SysCallId::DebugSysCallUpperBound as u16)
385        {
386            // SAFETY: The value is guaranteed to be a valid SysCallId variant
387            // because it falls within the valid ranges of defined variants.
388            Ok(unsafe { core::mem::transmute::<u16, SysCallId>(value) })
389        } else {
390            Err(Error::InvalidArgument)
391        }
392    }
393}
394
395/// A set of object signals
396#[derive(Copy, Clone, PartialEq)]
397#[repr(C)]
398pub struct Signals(u32);
399
400bitflags! {
401    impl Signals: u32 {
402        /// Object is readable.
403        const READABLE = 1 << 0;
404
405        /// Object is writeable.
406        const WRITEABLE = 1 << 1;
407
408        /// Object is in an error state.
409        const ERROR = 1 << 2;
410
411        /// Thread or Process has terminated and can be joined.
412        const JOINABLE = 1 << 3;
413
414        /// Object has a protocol specific user signal pending.
415        const USER = 1 << 15;
416
417        /// Bits 16-30 are used to denote which interrupt on the
418        /// interrupt object was signaled.  They are intentionally
419        /// named by letter not number so as not to confuse the
420        /// position within an object mask to the IRQ number.
421        const INTERRUPT_A = 1 << 16;
422        const INTERRUPT_B = 1 << 17;
423        const INTERRUPT_C = 1 << 18;
424        const INTERRUPT_D = 1 << 19;
425        const INTERRUPT_E = 1 << 20;
426        const INTERRUPT_F = 1 << 21;
427        const INTERRUPT_G = 1 << 22;
428        const INTERRUPT_H = 1 << 23;
429        const INTERRUPT_I = 1 << 24;
430        const INTERRUPT_J = 1 << 25;
431        const INTERRUPT_K = 1 << 26;
432        const INTERRUPT_L = 1 << 27;
433        const INTERRUPT_M = 1 << 28;
434        const INTERRUPT_N = 1 << 29;
435        const INTERRUPT_O = 1 << 30;
436
437        /// Reserved for internal kernel use.
438        const RESERVED = 1 << 31;
439    }
440}
441
442impl Signals {
443    #[must_use]
444    pub const fn no_active() -> Self {
445        Self(0)
446    }
447}
448
449/// Return value from the [`object_wait()`] syscall.
450#[derive(Copy, Clone, PartialEq)]
451#[repr(C)]
452pub struct WaitReturn {
453    /// `user_data` of the wait group member.
454    pub user_data: usize,
455
456    /// Signals pending on the object.
457    pub pending_signals: Signals,
458}
459
460pub use exit_status::ExitStatus;
461
462impl SysCallReturnValue {
463    /// Converts a `SysCallReturnValue` to a `Result<ExitStatus>`.
464    ///
465    /// # Safety
466    /// The caller must guarantee that if the `SysCallReturnValue` does not represent
467    /// a system error (i.e., `value[0]` interpreted as signed is positive), then
468    /// `value` contains a valid bit pattern for `ExitStatus` (the tag in
469    /// `value[0]` corresponds to a valid variant of `ExitStatus`).  If the value
470    /// does represent a system error, the caller guarantees that it is a valid
471    /// value of `Error`
472    ///
473    /// These preconditions are satisfied the return values of the `thread_terminate()`
474    /// and `process_terminate()` system calls.
475    pub unsafe fn to_exit_status(self) -> Result<ExitStatus> {
476        let val = self.value[0].cast_signed();
477        if val < 0 {
478            let val = (-val).cast_unsigned();
479            // SAFETY: Caller guarantees a valid `Error` value.
480            #[allow(clippy::cast_possible_truncation)]
481            Err(unsafe { core::mem::transmute::<u32, Error>(val as u32) })
482        } else {
483            // SAFETY: The caller guarantees that if it is not an error, the value
484            // corresponds to a valid variant of `ExitStatus`.
485            Ok(unsafe { core::mem::transmute::<[usize; 2], ExitStatus>(self.value) })
486        }
487    }
488}
489
490unsafe extern "C" {
491    /// Perform a synchronous channel transaction
492    ///
493    /// Performs a transaction from the initiator side of a channel and blocks
494    /// until the handler side has completed the transaction.  `send_data` and
495    /// `recv_data` may overlap or be the same buffer.
496    ///
497    /// While non-block and infinite blocking semantics are not explicitly
498    /// supported, they can be effectively achieved with:
499    /// - Non-blocking: `deadline` == 0
500    /// - Infinite blocking: `deadline` == `u64::MAX`
501    ///
502    /// This call will cause `Signals::READABLE` to be cleared on the initiator
503    /// channel object at the beginning of execution.  However by the time it
504    /// returns without error, `Signals::READABLE` will be set again.
505    ///
506    /// The maximum size of buffers that may be passed is `isize::MAX`.
507    ///
508    /// # Returns
509    /// - `>=0`: Number of bytes received from the handler side.
510    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid initiator
511    ///   channel object.
512    /// - [`Error::ResourceExhausted`]: The channel already has a pending transaction.
513    /// - [`Error::PermissionDenied`]: `send_data` or `recv_data` do not reference
514    ///   valid memory regions in this processes' address space.
515    /// - [`Error::DeadlineExceeded`]: The handler side did not respond before
516    ///   `deadline` was exceeded.
517    pub fn channel_transact(
518        object_handle: u32,
519        send_data: *mut u8,
520        send_len: usize,
521        recv_data: *mut u8,
522        recv_len: usize,
523        deadline: u64,
524    ) -> isize;
525
526    /// Perform an asynchronous channel transaction
527    ///
528    /// Initiates a transaction from the initiator side of a channel.
529    /// send_data` must remain valid and readable and `recv_data` must remain
530    /// valid and writeable for the duration of the transaction (completed or
531    /// canceled.)  `send_data` and `recv_data` may overlap or be the same
532    /// buffer.
533    ///
534    /// This call will cause `Signals::READABLE` to be cleared on the initiator
535    /// channel object.  It will be signaled by the handler side when it
536    /// responds.
537    ///
538    /// # Returns
539    /// - `0`: Transaction was successfully initiated.
540    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid initiator
541    ///   channel object.
542    /// - [`Error::ResourceExhausted`]: The channel already has a pending transaction.
543    /// - [`Error::PermissionDenied`]: `send_data` or `recv_data` do not reference
544    ///   valid memory regions in this processes' address space.
545    pub fn channel_async_transact(
546        object_handle: u32,
547        send_data: *const u8,
548        send_len: usize,
549        recv_data: *mut u8,
550        recv_len: usize,
551    ) -> isize;
552
553    /// Completes an asynchronous channel transaction
554    ///
555    /// # Returns
556    /// - `>=0`: Number of bytes received from the handler side.
557    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid initiator
558    ///   channel object.
559    /// - [`Error::Unavailable`]: No transaction was pending on the channel.
560    pub fn channel_async_transact_complete(object_handle: u32) -> isize;
561
562    /// Cancels a pending transaction on a channel
563    ///
564    /// # Returns
565    /// - `0`: Pending transaction was successfully canceled.
566    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid initiator
567    ///   channel object.
568    /// - [`Error::Unavailable`]: No transaction was pending on the channel.
569    pub fn channel_async_cancel(object_handle: u32) -> isize;
570
571    /// Perform a non-blocking read from a pending transaction.
572    ///
573    /// Attempts to read up to `buf_len` bytes from the `send_buffer` of the
574    /// pending transaction starting from `offset`.  The kernel will copy the
575    /// data from the initiators `send_buffer` into `buffer` before returning.
576    ///
577    /// The maximum size of buffer that may be passed is `isize::MAX`.
578    ///
579    /// # Returns
580    /// - `>=0`: Number of bytes read from the send_buffer.
581    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid handler
582    ///   channel object.
583    /// - [`Error::OutOfRange`]: A read was requested outside the bound of the
584    ///   initiator's `send_buffer`.
585    /// - [`Error::Unavailable`]: No transaction was pending on the channel.
586    ///   This can happen in the middle of handling a transaction if the initiator
587    ///   cancels the transaction.
588    /// - [`Error::PermissionDenied`]: `buffer` does not reference a valid memory
589    ///   region in this processes' address space.
590    /// - TODO: What error should be returned if the initiator's `send_buffer`
591    ///   is invalid.  Is that also permission denied?
592    pub fn channel_read(
593        object_handle: u32,
594        offset: usize,
595        buffer: *mut u8,
596        buffer_len: usize,
597    ) -> isize;
598
599    /// Respond to and complete a pending transaction
600    ///
601    /// Causes the kernel to copy `buffer` into the initiator's `recv_buffer`
602    /// and set `Signals::READABLE` on the initiator channel object.
603    ///
604    /// The maximum size of buffer that may be passed is `isize::MAX`.
605    ///
606    /// # Returns
607    /// - `0`: On success.
608    /// - [`Error::OutOfRange`]: The initiator's `recv_buffer` is not large enough
609    ///   to fit the provided `buffer`.
610    /// - [`Error::Unavailable`]: No transaction was pending on the channel.
611    ///   This can happen in the middle of handling a transaction if the initiator
612    ///   cancels the transaction.
613    /// - [`Error::PermissionDenied`]: `buffer` does not reference a valid memory
614    ///   region in this processes' address space.
615    pub fn channel_respond(object_handle: u32, buffer: *mut u8, buffer_len: usize) -> isize;
616
617    /// Set or clear `Signals::USER` on the paired peer.
618    ///
619    /// Modeled after a level-triggered hardware interrupt: the signaler owns
620    /// the signal and controls it in both directions. `set != 0` raises USER
621    /// on the peer; `set == 0` lowers USER on the peer. The receiver does
622    /// not clear the signal — only the sender does.
623    ///
624    /// If the signaler process terminates or is reset, the kernel automatically
625    /// lowers `Signals::USER` on the peer object to prevent signal leaks.
626    /// Symmetrically, if the receiver process terminates and restarts, its own
627    /// `Signals::USER` is preserved as long as the signaler remains alive and
628    /// has not lowered it.
629    ///
630    /// # Returns
631    /// - `0`: On success.
632    /// - [`Error::Unimplemented`]: `object_handle` does not support peer signaling.
633    /// - [`Error::FailedPrecondition`]: No active peer (e.g., handler not yet wired).
634    pub fn object_set_peer_user_signal(object_handle: u32, set: u32) -> isize;
635
636    /// Acknowledges the signaled interrupts allowing them to be signaled again.
637    ///
638    /// This must be called by the interrupt handler after processing the
639    /// interrupts received via an interrupt object. It signals to the
640    /// underlying interrupt controller that the interrupt handling is complete
641    /// and can be signaled again.
642    ///
643    /// # Returns
644    /// - `0`: On success.
645    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid Interrupt
646    ///   object, or the `signal_mask` is invalid.
647    pub fn interrupt_ack(object_handle: u32, signal_mask: Signals) -> isize;
648
649    //
650    // waiting
651    //
652    // Need to define multi threaded semantics
653
654    /// Wait on a single object
655    ///
656    /// Waits for one of the signals in `signal_mask` to be pending on `object_handle`.
657    ///
658    /// # Returns
659    /// - `WaitReturn.status >= 0`: Returns object specific metadata
660    /// - [`Error::InvalidArgument`]: `object_handle` is not a valid object or the object is a
661    ///   wait group and there are no members in the wait group.
662    /// - [`Error::DeadlineExceeded`]: The handler side did not respond before
663    ///   `deadline` was exceeded.
664    pub fn object_wait(object_handle: u32, signal_mask: Signals, deadline: u64) -> WaitReturn;
665
666    /// Adds an object to a wait group
667    ///
668    /// Add `object` to `wait_group`.  `wait_group` will signal when one of the
669    /// signals in `signal_mask` is raised on `object`.  `user_data` is passed,
670    /// untouched by the kernel to the return value of `object_wait()`.
671    ///
672    /// The order in which the object is added does not affect the order in
673    /// which objects in the `wait_group` are signaled.
674    ///
675    /// # Returns
676    /// `0`: Success
677    /// - [`Error::InvalidArgument`]: `wait_group` is not a valid wait group or
678    ///   `object` is not a valid object.
679    /// - [`Error::ResourceExhausted`]: `object` is already in a wait group.
680    pub fn wait_group_add(
681        wait_group: u32,
682        object: u32,
683        signal_mask: Signals,
684        user_data: usize,
685    ) -> isize;
686
687    /// Removes an object from a wait group
688    ///
689    /// # Returns
690    /// `0`: Success
691    /// - [`Error::InvalidArgument`]: `wait_group` is not a valid wait group or
692    ///   `object` is not a valid object.
693    /// - [`Error::NotFound`]: `object` is not in `wait_group`.
694    pub fn wait_group_remove(wait_group: u32, object: u32) -> isize;
695}
696
697pub trait SysCallInterface {
698    fn object_wait(handle: u32, signal_mask: u32, deadline: u64) -> Result<WaitReturn>;
699
700    fn wait_group_add(
701        wait_group: u32,
702        object: u32,
703        signal_mask: Signals,
704        user_data: usize,
705    ) -> Result<()>;
706
707    fn wait_group_remove(wait_group: u32, object: u32) -> Result<()>;
708
709    #[expect(clippy::missing_safety_doc)]
710    unsafe fn channel_transact(
711        handle: u32,
712        send_data: *const u8,
713        send_len: usize,
714        recv_data: *mut u8,
715        recv_len: usize,
716        deadline: u64,
717    ) -> Result<u32>;
718
719    #[expect(clippy::missing_safety_doc)]
720    unsafe fn channel_async_transact(
721        handle: u32,
722        send_data: *const u8,
723        send_len: usize,
724        recv_data: *mut u8,
725        recv_len: usize,
726    ) -> Result<()>;
727
728    fn channel_async_transact_complete(handle: u32) -> Result<u32>;
729
730    fn channel_async_cancel(handle: u32) -> Result<()>;
731
732    #[expect(clippy::missing_safety_doc)]
733    unsafe fn channel_read(
734        object_handle: u32,
735        offset: usize,
736        buffer: *mut u8,
737        buffer_len: usize,
738    ) -> Result<u32>;
739
740    #[expect(clippy::missing_safety_doc)]
741    unsafe fn channel_respond(
742        object_handle: u32,
743        buffer: *const u8,
744        buffer_len: usize,
745    ) -> Result<()>;
746
747    fn interrupt_ack(object_handle: u32, signal_mask: Signals) -> Result<()>;
748
749    fn thread_start(object_handle: u32, initial_pc: usize, initial_sp: usize) -> Result<()>;
750    fn task_terminate(object_handle: u32) -> Result<()>;
751    fn task_join(object_handle: u32) -> Result<ExitStatus>;
752    fn thread_exit(exit_code: u32) -> !;
753
754    fn process_start(object_handle: u32) -> Result<()>;
755    fn process_exit(exit_code: u32) -> !;
756
757    /// Set or clear `Signals::USER` on the paired peer (level-triggered model).
758    ///
759    /// If the signaler process terminates or is reset, the kernel automatically
760    /// lowers `Signals::USER` on the peer object to prevent signal leaks.
761    /// Symmetrically, if the receiver process terminates and restarts, its own
762    /// `Signals::USER` is preserved as long as the signaler remains alive and
763    /// has not lowered it.
764    fn object_set_peer_user_signal(object_handle: u32, set: bool) -> Result<()>;
765
766    fn debug_putc(a: u32) -> Result<u32>;
767    // TODO: Consider adding an feature flagged PowerManager object and move
768    // this shutdown call to it.
769    fn debug_shutdown(a: u32) -> Result<()>;
770
771    #[expect(clippy::missing_safety_doc)]
772    unsafe fn debug_log(buffer: *const u8, buffer_len: usize) -> Result<()>;
773
774    fn debug_nop() -> Result<()>;
775
776    fn debug_trigger_interrupt(irq: u32) -> Result<()>;
777
778    fn debug_clock_now() -> u64;
779}
780
781#[cfg(test)]
782mod tests {
783    use unittest::test;
784
785    use super::*;
786
787    #[test]
788    fn test_syscall_id_try_from_valid() -> unittest::Result<()> {
789        for i in (SysCallId::SysCallLowerBound as u16 + 1)..(SysCallId::SysCallUpperBound as u16) {
790            // SAFETY: The loop range guarantees `i` is a valid standard SysCallId.
791            let expected = unsafe { core::mem::transmute::<u16, SysCallId>(i) };
792            unittest::assert_eq!(SysCallId::try_from(i), Ok(expected));
793        }
794        Ok(())
795    }
796
797    #[test]
798    fn test_syscall_id_try_from_valid_debug() -> unittest::Result<()> {
799        for i in (SysCallId::DebugSysCallLowerBound as u16 + 1)
800            ..(SysCallId::DebugSysCallUpperBound as u16)
801        {
802            // SAFETY: The loop range guarantees `i` is a valid debug SysCallId.
803            let expected = unsafe { core::mem::transmute::<u16, SysCallId>(i) };
804            unittest::assert_eq!(SysCallId::try_from(i), Ok(expected));
805        }
806        Ok(())
807    }
808
809    #[test]
810    fn test_syscall_id_try_from_invalid() -> unittest::Result<()> {
811        unittest::assert_eq!(
812            SysCallId::try_from(SysCallId::SysCallLowerBound as u16),
813            Err(Error::InvalidArgument)
814        );
815        unittest::assert_eq!(
816            SysCallId::try_from(SysCallId::SysCallUpperBound as u16),
817            Err(Error::InvalidArgument)
818        );
819        unittest::assert_eq!(
820            SysCallId::try_from(SysCallId::DebugSysCallLowerBound as u16),
821            Err(Error::InvalidArgument)
822        );
823        unittest::assert_eq!(
824            SysCallId::try_from(SysCallId::DebugSysCallUpperBound as u16),
825            Err(Error::InvalidArgument)
826        );
827        unittest::assert_eq!(
828            SysCallId::try_from(SysCallId::DebugSysCallUpperBound as u16 + 1),
829            Err(Error::InvalidArgument)
830        );
831        Ok(())
832    }
833}