diff --git a/libs/bao1x-api/src/bio.rs b/libs/bao1x-api/src/bio.rs index 35a41bf0e..061915997 100644 --- a/libs/bao1x-api/src/bio.rs +++ b/libs/bao1x-api/src/bio.rs @@ -45,7 +45,6 @@ // output frequency = fclk / (div_int + div_frac / 256) // -use core::marker::PhantomData; use core::num::NonZeroU32; use bitbybit::bitfield; @@ -69,6 +68,16 @@ pub enum BioOp { IoConfig, FifoEventTriggers, GetVersion, + + // Resource management opcodes + ClaimResources, + ReleaseResources, + ResourceAvailability, + CheckResources, + CheckResourcesBatch, + ClaimDynamicPin, + ReleaseDynamicPin, + InvalidCall, } @@ -267,7 +276,7 @@ pub struct FifoEventConfig { pub trigger_equal_to: bool, } -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] #[repr(usize)] pub enum Fifo { @@ -354,62 +363,23 @@ pub struct DmaFilterWindows { pub windows: [Option; 4], } -/* -#[bitfield(u32)] -pub struct PackedFifoLevels { - #[bits(16..=31)] - _padding: u16, - #[bits(12..=15)] - fifo3_level: arbitrary_int::u4, - #[bits(8..=11)] - fifo2_level: arbitrary_int::u4, - #[bits(4..=7)] - fifo1_level: arbitrary_int::u4, - #[bits(0..=3)] - fifo0_level: arbitrary_int::u4, -} - -#[bitfield(u32)] -pub struct PackedEvent { - #[bits(24..=31)] - _padding: u8, - #[bits(0..=23)] - event: arbitrary_int::u24, -} -/// Memory-mapped structure for a FIFO endpoint. The returned structure -/// is literally mapped on top of the virtual address of the FIFO page starting at offset 0xC. -/// You could also access these fields using the UTRA abstractions, but with the the CSR base -/// set to the FIFO alias region -#[repr(C)] -pub struct FifoHandle { - pub packed_fifo_levels: PackedFifoLevels, - pub tx_fifo: [u32; 4], - pub rx_fifo: [u32; 4], - pub _unused: [u32; 2], - pub set_event: PackedEvent, - pub clear_event: PackedEvent, - pub event_status: PackedEvent, -} -*/ - -pub struct CoreHandle<'a> { +pub struct CoreHandle { conn: xous::CID, handle: usize, fifo: arbitrary_int::u2, - _phantom: PhantomData<&'a ()>, } -impl<'a> CoreHandle<'a> { +impl CoreHandle { pub fn new(conn: xous::CID, handle: usize, fifo: arbitrary_int::u2) -> Self { - Self { conn, handle, fifo, _phantom: PhantomData } + Self { conn, handle, fifo } } /// safety: this needs to be wrapped in a hardware-level CSR object that tracks the lifetime of /// the underlying pointer handle. - pub unsafe fn handle(&self) -> (usize, PhantomData<&'a ()>) { (self.handle, self._phantom) } + pub unsafe fn handle(&self) -> usize { self.handle } } -impl Drop for CoreHandle<'_> { +impl Drop for CoreHandle { fn drop(&mut self) { // safety: handle was allocated by the OS and is thus safe to re-create as a range // the length of the range (one page) is set by the hardware implementation and never changes @@ -489,7 +459,7 @@ pub trait BioApi<'a> { /// the lifetime of this object, to prevent `Drop` from being called at the wrong time. /// /// Returns `None` if no more handles are available - unsafe fn get_core_handle(&'a self, fifo: Fifo) -> Result>, BioError>; + unsafe fn get_core_handle(&self, fifo: Fifo) -> Result, BioError>; /// This call sets up the BIO's IRQ routing. It doesn't actually claim the IRQ /// or install the handler - that's up to the caller to do with Xous API calls. @@ -528,12 +498,6 @@ macro_rules! bio_code { static $name_start: *const u8; static $name_end: *const u8; } - /* - unsafe { - report_api($name_start as u32); - report_api($name_end as u32); - } - */ // skip the first 4 bytes, as they contain the loading offset unsafe { core::slice::from_raw_parts($name_start.add(4), ($name_end as usize) - ($name_start as usize) - 4)} } diff --git a/libs/bao1x-api/src/bio_resources.rs b/libs/bao1x-api/src/bio_resources.rs new file mode 100644 index 000000000..4102d093b --- /dev/null +++ b/libs/bao1x-api/src/bio_resources.rs @@ -0,0 +1,250 @@ +use crate::bio::*; + +/// Specifies a core requirement +#[derive(Clone, Debug, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub enum CoreRequirement { + /// Any available core will do + Any, + /// A specific core is required + Specific(BioCore), +} + +/// Specification of resources an application needs +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct ResourceSpec { + /// Human-readable identifier for the claimer (for debugging/error messages) + pub claimer: String, + /// Core requirements - each element represents one core needed + pub cores: Vec, + /// Specific FIFOs required (always specific, never "any") + pub fifos: Vec, + /// Statically known pins (by pin number 0-31) + pub static_pins: Vec, + /// Number of dynamically allocated pins (best-effort tracking only) + pub dynamic_pin_count: u8, +} + +#[cfg(feature = "std")] +impl ResourceSpec { + pub fn new(claimer: impl Into) -> Self { + Self { + claimer: claimer.into(), + cores: Vec::new(), + fifos: Vec::new(), + static_pins: Vec::new(), + dynamic_pin_count: 0, + } + } + + pub fn any_core(mut self) -> Self { + self.cores.push(CoreRequirement::Any); + self + } + + pub fn any_cores(mut self, count: usize) -> Self { + for _ in 0..count { + self.cores.push(CoreRequirement::Any); + } + self + } + + pub fn specific_core(mut self, core: BioCore) -> Self { + self.cores.push(CoreRequirement::Specific(core)); + self + } + + pub fn fifo(mut self, fifo: Fifo) -> Self { + if !self.fifos.contains(&fifo) { + self.fifos.push(fifo); + } + self + } + + pub fn pin(mut self, pin: u8) -> Self { + assert!(pin < 32, "Pin must be 0-31"); + if !self.static_pins.contains(&pin) { + self.static_pins.push(pin); + } + self + } + + pub fn pins_from_mask(mut self, mask: u32) -> Self { + for i in 0..32u8 { + if mask & (1 << i) != 0 && !self.static_pins.contains(&i) { + self.static_pins.push(i); + } + } + self + } + + pub fn dynamic_pins(mut self, count: u8) -> Self { + self.dynamic_pin_count = count; + self + } +} + +/// Result of a successful resource claim +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct ResourceGrant { + /// Unique ID for this grant (used for release) + pub grant_id: u32, + /// The actual cores allocated, in the same order as requested + pub cores: Vec, + /// The FIFOs granted (mirrors request, confirms allocation) + pub fifos: Vec, + /// Static pins granted + pub static_pins: Vec, + /// Dynamic pin capacity reserved + pub dynamic_pin_count: u8, +} + +/// Current state of resource availability (for diagnostics) +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct ResourceAvailability { + /// For each core: None if available, Some(claimer_name) if claimed + pub cores: [Option; 4], + /// For each FIFO: None if available, Some(claimer_name) if claimed + pub fifos: [Option; 4], + /// For each of 32 pins: None if available, Some(claimer_name) if claimed + pub pins: [Option; 32], + /// Total dynamic pins reserved across all claimers + pub dynamic_pins_reserved: u8, +} + +#[cfg(feature = "std")] +impl Default for ResourceAvailability { + fn default() -> Self { + // Ugly but necessary since Option doesn't impl Copy + Self { + cores: [None, None, None, None], + fifos: [None, None, None, None], + pins: [ + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, None, + ], + dynamic_pins_reserved: 0, + } + } +} + +/// Detailed error for resource conflicts +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub enum ResourceError { + /// No error (used as sentinel in IPC) + None, + /// A specific core was requested but is unavailable + CoreUnavailable { core: BioCore, claimed_by: String }, + /// Not enough free cores for "Any" requests + InsufficientCores { requested: usize, available: usize }, + /// A FIFO is unavailable + FifoUnavailable { fifo: Fifo, claimed_by: String }, + /// A pin is unavailable + PinUnavailable { pin: u8, claimed_by: String }, + /// Too many dynamic pins would be reserved (exceeds 32 total) + DynamicPinOverflow { requested: u8, already_reserved: u8, static_pins_used: u8 }, + /// Grant ID not found (already released or invalid) + InvalidGrantId(u32), + /// Claimer name mismatch on dynamic pin operation + ClaimerMismatch { expected: String, provided: String }, + /// Internal error + InternalError, +} + +impl From for BioError { + fn from(e: ResourceError) -> Self { + match e { + ResourceError::None => BioError::None, + ResourceError::InternalError => BioError::InternalError, + _ => BioError::ResourceInUse, + } + } +} + +// ============================================================================ +// IPC MESSAGE WRAPPERS +// ============================================================================ + +/// IPC wrapper for claim_resources / check_resources +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct ClaimResourcesRequest { + pub spec: ResourceSpec, + /// On return: the grant (if successful) + pub grant: Option, + /// On return: the error (if failed) + pub error: ResourceError, +} + +/// IPC wrapper for check_resources_batch +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct CheckResourcesBatchRequest { + pub specs: Vec, + /// On return: the error (if any conflict found) + pub error: ResourceError, +} + +/// IPC wrapper for resource_availability query +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct ResourceAvailabilityResponse { + pub availability: ResourceAvailability, +} + +/// IPC wrapper for dynamic pin operations +#[derive(Clone, Debug)] +#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))] +pub struct DynamicPinRequest { + pub pin: u8, + pub claimer: String, + /// On return: the error (if failed) + pub error: ResourceError, +} + +/// Resource management API for BIO applications. +/// +/// This trait is only available with the `std` feature, as it requires +/// communication with the global BIO resource server. +/// +/// In no-std/baremetal environments, resource tracking is the programmer's +/// responsibility. +/// +/// The `std`/`no-std` split in the API means that the resource tracking is fundamentally +/// decoupled from the actual resource usage. +#[cfg(feature = "std")] +pub trait BioResources { + /// Claim resources according to spec. + fn claim_resources(&self, spec: &ResourceSpec) -> Result; + + /// Release previously claimed resources. + fn release_resources(&self, grant_id: u32) -> Result<(), ResourceError>; + + /// Query current resource availability. + fn resource_availability(&self) -> Result; + + /// Check if a spec could be satisfied without actually claiming. + fn check_resources(&self, spec: &ResourceSpec) -> Result<(), ResourceError>; + + /// Check if multiple specs can coexist (ignoring current state). + fn check_resources_batch(&self, specs: &[ResourceSpec]) -> Result<(), ResourceError>; + + /// Claim a specific dynamic pin at runtime. + fn claim_dynamic_pin(&self, pin: u8, claimer: &str) -> Result<(), ResourceError>; + + /// Release a specific dynamic pin. + fn release_dynamic_pin(&self, pin: u8, claimer: &str) -> Result<(), ResourceError>; + + /// Sets the run state of the cores based on the resource grant. Starts the cores if `start` is `true`, + /// otherwise stops them. + fn set_core_run_state(&self, grant: &ResourceGrant, start: bool); +} + +pub trait Resources { + fn resource_spec() -> ResourceSpec; +} diff --git a/libs/bao1x-api/src/lib.rs b/libs/bao1x-api/src/lib.rs index fd6cedd34..6b0578f2d 100644 --- a/libs/bao1x-api/src/lib.rs +++ b/libs/bao1x-api/src/lib.rs @@ -22,6 +22,8 @@ use arbitrary_int::u31; use bitbybit::bitfield; pub use clocks::*; pub mod bio; +#[cfg(feature = "std")] +pub mod bio_resources; /// UF2 Family ID. Randomly generated, no collisions with the known list, still to be merged /// into the "official" list