cleanup the API after running through an implementation

This commit is contained in:
bunnie 2025-12-26 20:17:34 +08:00
parent 8c3c23ea85
commit c239d79ead
3 changed files with 202 additions and 95 deletions

View file

@ -51,11 +51,12 @@
// 0: Hi 1 cycle, low 3 cycle
// 1: Hi 2 cycle, low 2 cycle
use core::marker::PhantomData;
use core::num::NonZeroU32;
use std::marker::PhantomData;
use bitbybit::bitfield;
use num_traits::ToPrimitive;
use xous::MemoryRange;
pub const BIO_SERVER_NAME: &'static str = "_BIO server_";
@ -63,8 +64,9 @@ pub const BIO_SERVER_NAME: &'static str = "_BIO server_";
pub enum BioOp {
InitCore,
DeInitCore,
SetCoreFreq,
UpdateBioFreq,
GetCoreFreq,
GetBioFreq,
CoreState,
GetCoreHandle,
ReleaseCoreHandle,
@ -75,18 +77,22 @@ pub enum BioOp {
GetVersion,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
// align this so it can be passed as a memory message
#[repr(align(4096))]
pub struct CoreInitRkyv {
pub core: BioCore,
pub offset: usize,
pub config: CoreConfigRkyv,
pub actual_freq: Option<u32>,
pub config: CoreConfig,
pub code: [u8; 4096],
pub result: BioError,
}
#[repr(usize)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub enum BioCore {
Core0 = 0,
Core1 = 1,
@ -95,7 +101,8 @@ pub enum BioCore {
}
#[repr(usize)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub enum CoreRunSetting {
Unchanged = 0,
Start = 1,
@ -114,23 +121,32 @@ impl From<usize> for BioCore {
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub enum BioError {
/// specified state machine is not valid
InvalidSm,
/// Uninitialized
Uninit,
/// No error
None,
/// specified core is not valid
InvalidCore,
/// program can't fit in memory, for one reason or another
Oom,
/// no more machines available
NoFreeMachines,
/// core is already in use
CoreInUse,
/// Loaded code did not match, first error at argument
CodeCheck(usize),
/// Catch-all for programming bugs that shouldn't happen
InternalError,
}
impl From<xous::Error> for BioError {
fn from(error: xous::Error) -> Self {
match error {
xous::Error::OutOfMemory => BioError::Oom,
xous::Error::ServerNotFound => BioError::InvalidSm,
xous::Error::ServerNotFound => BioError::InvalidCore,
xous::Error::ServerExists => BioError::NoFreeMachines,
// Handle unmapped cases with a panic
_ => panic!("Cannot convert Error::{:?} to BioError", error),
@ -138,7 +154,8 @@ impl From<xous::Error> for BioError {
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct BioPin {
pin_number: u8,
}
@ -150,45 +167,31 @@ impl BioPin {
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub enum ClockMode {
/// Fixed divider - (int, frac)
FixedDivider(u16, u8),
/// Target frequency - fractional allowed. Attempts to adjust to target based on
/// changing CPU clock. Fractional component means the "average" frequency is achieved
/// by occasionally skipping clocks. This means there is jitter in the edge timing.
TargetFreqFrac(u32),
/// Target frequency - integer dividers only allowed. The absolute error of the
/// frequency may be larger, but the jitter is smaller. Attempts to adjust to the
/// target based on changing CPU clock.
TargetFreqInt(u32),
/// Use external pin as quantum source
ExternalPin(BioPin),
}
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct CoreConfig {
pub div_int: u16,
pub div_frac: u8,
/// When some, configures use_extclk of the corresponding core to use the GPIO pin specified as the
/// argument
pub quantum_from_pin: Option<BioPin>,
pub clock_mode: ClockMode,
}
impl From<CoreConfig> for CoreConfigRkyv {
fn from(config: CoreConfig) -> Self {
CoreConfigRkyv {
div_int: config.div_int,
div_frac: config.div_frac,
quantum_from_pin: config.quantum_from_pin.map(|pin| pin.pin_number().into()),
}
}
}
impl From<CoreConfigRkyv> for CoreConfig {
fn from(config: CoreConfigRkyv) -> Self {
CoreConfig {
div_int: config.div_int,
div_frac: config.div_frac,
quantum_from_pin: config.quantum_from_pin.map(|pin_num| BioPin::new(pin_num)),
}
}
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct CoreConfigRkyv {
pub div_int: u16,
pub div_frac: u8,
/// When some, configures use_extclk of the corresponding core to use the GPIO pin specified as the
/// argument
pub quantum_from_pin: Option<u8>,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct IoConfig {
/// bits set to `1` here are mapped to the BIO instead of the GPIO
pub mapped: u32,
@ -208,9 +211,23 @@ pub struct IoConfig {
/// When specified all GPIO outputs are aligned to the divided clock of the specified core
pub snap_outputs: Option<BioCore>,
}
impl Default for IoConfig {
fn default() -> Self {
Self {
mapped: 0,
sync_bypass: 0,
oe_inv: 0,
o_inv: 0,
i_inv: 0,
snap_inputs: None,
snap_outputs: None,
}
}
}
#[bitfield(u8)]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct TriggerSlot {
#[bits(1..=7)]
_reserved: arbitrary_int::u7,
@ -219,7 +236,8 @@ pub struct TriggerSlot {
}
#[bitfield(u8)]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct FifoLevel {
#[bits(3..=7)]
_reserved: arbitrary_int::u5,
@ -228,7 +246,8 @@ pub struct FifoLevel {
}
/// The event register is divided into 24 code-settable event bits + 8 FIFO event bits
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct FifoEventConfig {
// for which FIFO we're configuring its event triggers
pub which: Fifo,
@ -242,38 +261,45 @@ pub struct FifoEventConfig {
pub trigger_equal_to: bool,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct FifoEventConfigRkyv {
// for which FIFO we're configuring its event triggers
pub which: Fifo,
// there are up to two trigger slots per FIFO, specify 0 or 1 here.
pub trigger_slot: bool,
// the level used for the triggers. Any number from 0-7.
pub level: u8,
// when set, the trigger condition happens compared to the level above
pub trigger_less_than: bool,
pub trigger_greater_than: bool,
pub trigger_equal_to: bool,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[repr(usize)]
pub enum Fifo {
Fifo0,
Fifo1,
Fifo2,
Fifo3,
Fifo0 = 0,
Fifo1 = 1,
Fifo2 = 2,
Fifo3 = 3,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
impl Fifo {
pub fn to_usize_checked(self) -> usize {
let discriminant = self as usize;
assert!(discriminant <= 3, "Invalid discriminant");
discriminant
}
}
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
#[repr(usize)]
pub enum Irq {
Irq0,
Irq1,
Irq2,
Irq3,
Irq0 = 0,
Irq1 = 1,
Irq2 = 2,
Irq3 = 3,
}
impl Irq {
pub fn to_usize_checked(self) -> usize {
let discriminant = self as usize;
assert!(discriminant <= 3, "Invalid discriminant");
discriminant
}
}
#[bitfield(u32)]
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct IrqMask {
#[bit(31, rw)]
fifo3_trigger1: bool,
@ -295,7 +321,8 @@ pub struct IrqMask {
software: arbitrary_int::u24,
}
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct IrqConfig {
/// Specifies which of the four BIO IRQ lines are being configured
pub which: Irq,
@ -307,14 +334,16 @@ pub struct IrqConfig {
/// Defines an accessible window by DMA from BIO cores. It's a slice starting from `base` going for `bounds`
/// bytes.
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct DmaWindow {
pub base: u32,
pub bounds: NonZeroU32,
}
/// Structure that defines all of the windows allowed by the system
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "std", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct DmaFilterWindows {
pub windows: [Option<DmaWindow>; 4],
}
@ -360,11 +389,14 @@ pub struct FifoHandle {
pub struct CoreHandle<'a> {
conn: xous::CID,
handle: usize,
bank: arbitrary_int::u2,
_phantom: PhantomData<&'a ()>,
}
impl<'a> CoreHandle<'a> {
pub fn new(conn: xous::CID, handle: usize) -> Self { Self { conn, handle, _phantom: PhantomData } }
pub fn new(conn: xous::CID, handle: usize, bank: arbitrary_int::u2) -> Self {
Self { conn, handle, bank, _phantom: PhantomData }
}
/// safety: this needs to be wrapped in a hardware-level CSR object that tracks the lifetime of
/// the underlying pointer handle.
@ -373,11 +405,14 @@ impl<'a> CoreHandle<'a> {
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
xous::unmap_memory(unsafe { MemoryRange::new(self.handle, 4096).unwrap() }).unwrap();
xous::send_message(
self.conn,
xous::Message::new_blocking_scalar(
BioOp::ReleaseCoreHandle.to_usize().unwrap(),
self.handle,
self.bank.value() as usize,
0,
0,
0,
@ -390,29 +425,44 @@ impl Drop for CoreHandle<'_> {
/// A platform-neutral API for the BIO. Intended to be usable in both baremetal and `std` environments
pub trait BioApi<'a> {
/// Initializes a core with the given `code`, loading into `offset`, with a given
/// core configuration.
/// core configuration. This does not start the core running: that needs to be
/// done with a separate `set_core_state` call.
///
/// Returns a `u32` which is the frequency in Hz of the actual quantum interval that
/// the core is running at. It's `None` if an external pin is configured as the quantum source.
fn init_core(
&self,
&mut self,
core: BioCore,
code: &[u8],
offset: usize,
config: CoreConfig,
) -> Result<(), BioError>;
) -> Result<Option<u32>, BioError>;
/// Releases the core. As a side effect, the core is stopped.
fn de_init_core(&self, core: BioCore) -> Result<(), BioError>;
fn de_init_core(&mut self, core: BioCore) -> Result<(), BioError>;
/// Sets the frequency of the cores, used to calculate dividers etc.
/// Returns the previous frequency used by the system. Setting this frequency
/// Updates the frequency of the cores, used to calculate dividers etc.
/// Returns the previous frequency used by the system. Setting this
/// allows the sleep/wake clock manager to do a best-effort rescaling of the
/// clock dividers for each core as DVFS is applied for power savings.
fn set_core_freq(&self, freq: u32) -> Result<u32, BioError>;
///
/// This API call does not actually *set* the frequency of the BIO complex -
/// that is handled by the clock manager. This merely informs the BIO driver
/// that the clocks may have changed.
fn update_bio_freq(&mut self, freq: u32) -> u32;
/// Returns the frequency, in Hz, of the incoming clock to the BIO cores.
fn get_freq(&self) -> u32;
fn get_bio_freq(&self) -> u32;
/// Returns the currently running frequency of a given BIO core. This API
/// exists because `update_bio_freq()` call will result in the dividers being
/// adjusted in an attempt to maintain the target quantum; however, there will
/// often be some error between what was requested and the actual achievable
/// frequency of the quantum interval.
fn get_core_freq(&self, core: BioCore) -> Option<u32>;
/// The index of `which` corresponds to each of the cores, 0-3.
fn set_core_state(&self, which: [CoreRunSetting; 4]) -> Result<(), BioError>;
fn set_core_state(&mut self, which: [CoreRunSetting; 4]) -> Result<(), BioError>;
/// Returns a `usize` which should be turned into a CSR as *mut u32 by the caller
/// this can then be dereferenced using UTRA abstractions to access the following
@ -428,22 +478,65 @@ pub trait BioApi<'a> {
///
/// Safety: this has to be wrapped in an object that derives a CSR that also tracks
/// the lifetime of this object, to prevent `Drop` from being called at the wrong time.
unsafe fn get_core_handle(&'a self) -> Result<CoreHandle<'a>, BioError>;
unsafe fn get_core_handle(&'a mut self) -> Result<CoreHandle<'a>, 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.
fn setup_irq_config(&self, config: IrqConfig) -> Result<(), BioError>;
fn setup_irq_config(&mut self, config: IrqConfig) -> Result<(), BioError>;
/// Allows BIO cores to DMA to/from the windows specified in `windows`. DMA filtering is
/// on by default with no windows allowed.
fn setup_dma_windows(&self, windows: DmaFilterWindows) -> Result<(), BioError>;
fn setup_dma_windows(&mut self, windows: DmaFilterWindows) -> Result<(), BioError>;
/// Sets up the BIO I/O configuration
fn setup_io_config(&self, config: IoConfig) -> Result<(), BioError>;
fn setup_io_config(&mut self, config: IoConfig) -> Result<(), BioError>;
/// Sets up a FIFO event trigger
fn setup_fifo_event_triggers(&self, config: FifoEventConfig) -> Result<(), BioError>;
fn setup_fifo_event_triggers(&mut self, config: FifoEventConfig) -> Result<(), BioError>;
/// Returns a version code for the underlying hardware.
fn get_version(&self) -> u32;
}
#[macro_export]
/// This macro takes three identifiers and assembly code:
/// - name of the function to call to retrieve the assembled code
/// - a unique identifier that serves as label name for the start of the code
/// - a unique identifier that serves as label name for the end of the code
/// - a comma separated list of strings that form the assembly itself
///
/// *** The comma separated list must *not* end in a comma. ***
///
/// The macro is unable to derive names of functions or identifiers for labels
/// due to the partially hygienic macro rules of Rust, so you have to come
/// up with a list of unique names by yourself.
macro_rules! bio_code {
($fn_name:ident, $name_start:ident, $name_end:ident, $($item:expr),*) => {
pub fn $fn_name() -> &'static [u8] {
extern "C" {
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)}
}
core::arch::global_asm!(
".align 4",
concat!(".globl ", stringify!($name_start)),
concat!(stringify!($name_start), ":"),
".word .",
$($item),*
, ".align 4",
concat!(".globl ", stringify!($name_end)),
concat!(stringify!($name_end), ":"),
".word .",
);
};
}

View file

@ -83,6 +83,7 @@ pub trait IoSetup {
strength: Option<IoxDriveStrength>,
);
fn set_bio_bit_from_port_and_pin(&self, port: IoxPort, pin: u8) -> Option<u8>;
fn set_ports_from_bio_bitmask(&self, enable_bitmask: u32);
}
/// Traits for accessing GPIOs after the port has been set up.
@ -276,6 +277,20 @@ impl IoSetup for IoxHal {
_ => panic!("Internal error setting up BIO"),
}
}
fn set_ports_from_bio_bitmask(&self, enable_bitmask: u32) {
xous::send_message(
self.conn,
xous::Message::new_blocking_scalar(
HalOpcode::ConfigureBio.to_usize().unwrap(),
enable_bitmask as usize,
0,
1,
0,
),
)
.expect("Internal error setting up BIO");
}
}
#[cfg(feature = "std")]

View file

@ -21,7 +21,6 @@ pub mod pubkeys;
use arbitrary_int::u31;
use bitbybit::bitfield;
pub use clocks::*;
#[cfg(feature = "std")]
pub mod bio;
/// UF2 Family ID. Randomly generated, no collisions with the known list, still to be merged