mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-16 08:38:26 +00:00
add iox function to cram-hal-service
also modularize ifram into a separate file
This commit is contained in:
parent
1e93171575
commit
7da6649e30
7 changed files with 504 additions and 148 deletions
|
|
@ -12,12 +12,22 @@ utralib = { version = "0.1.24", optional = true, default-features = false, featu
|
|||
xous-api-names = "0.9.55"
|
||||
xous-api-ticktimer = "0.9.53"
|
||||
xous = "0.9.57"
|
||||
xous-ipc = "0.9.57"
|
||||
log-server = { package = "xous-api-log", version = "0.1.53" }
|
||||
log = "0.4.14"
|
||||
cramium-hal = { path = "../../libs/cramium-hal" }
|
||||
cramium-hal = { path = "../../libs/cramium-hal", features = ["derive-rkyv"] }
|
||||
xous-pl230 = { path = "../../libs/xous-pl230", features = ["cramium-soc"] }
|
||||
xous-pio = { path = "../../libs/xous-pio", features = ["cramium-soc"] }
|
||||
pio-proc = "0.2.2"
|
||||
pio = "0.2.1"
|
||||
|
||||
num-derive = { version = "0.3.3", default-features = false }
|
||||
num-traits = { version = "0.2.14", default-features = false }
|
||||
rkyv = { version = "0.4.3", default-features = false, features = [
|
||||
"const_generics",
|
||||
] }
|
||||
|
||||
[features]
|
||||
pio = []
|
||||
pio-memlcd = []
|
||||
default = []
|
||||
|
|
|
|||
|
|
@ -1,13 +1,112 @@
|
|||
use cramium_hal::iox;
|
||||
|
||||
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
|
||||
#[repr(usize)]
|
||||
pub enum Opcode {
|
||||
/// Allocate an IFRAM block
|
||||
MapIfram,
|
||||
MapIfram = 0,
|
||||
/// Deallocate an IFRAM block
|
||||
UnmapIfram,
|
||||
UnmapIfram = 1,
|
||||
|
||||
/// Manage PIO behaviors. PIO requires real-time behaviors, so
|
||||
/// the idea is that this service encodes a set of "behaviors" that
|
||||
/// are API extensions which are modular. The behaviors are set up as
|
||||
/// feature flags. Fast bulk data transfer to/from the behaviors is
|
||||
/// done using IFRAM blocks, which are managed by the above API calls;
|
||||
/// otherwise "singleton" peeks and pokes to the PIO should be handled
|
||||
/// with specific ScalarMessage calls to minimize OS overhead in
|
||||
/// context-switching to the block.
|
||||
#[cfg(feature = "pio")]
|
||||
ConfigurePioBehavior = 2,
|
||||
|
||||
/// Gutter for Invalid Calls
|
||||
InvalidCall,
|
||||
InvalidCall = 3,
|
||||
|
||||
/// Configure Iox (memory mutable lend)
|
||||
ConfigureIox = 4,
|
||||
/// Set the whole bank with a value/bitmask pair (blocking scalar)
|
||||
SetGpioBank = 5,
|
||||
/// Return the value of a GPIO bank (blocking scalar)
|
||||
GetGpioBank = 6,
|
||||
|
||||
/// Exit server
|
||||
Quit,
|
||||
Quit = 255,
|
||||
|
||||
/// Behavior opcode base
|
||||
#[cfg(feature = "pio")]
|
||||
BehaviorBase0 = 0x1000,
|
||||
#[cfg(feature = "pio")]
|
||||
BehaviorBase1 = 0x2000,
|
||||
#[cfg(feature = "pio")]
|
||||
BehaviorBase2 = 0x3000,
|
||||
#[cfg(feature = "pio")]
|
||||
BehaviorBase3 = 0x4000,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
#[cfg(feature = "pio")]
|
||||
pub enum PioBehavior {
|
||||
/// PIO pins for sclk, si, scs + IFRAM physical address
|
||||
#[cfg(feature = "pio-memlcd")]
|
||||
MemoryLcd(u8, u8, u8, usize),
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
#[cfg(feature = "pio")]
|
||||
pub enum BehaviorBase {
|
||||
Base0,
|
||||
Base1,
|
||||
Base2,
|
||||
Base3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
#[cfg(feature = "pio")]
|
||||
pub enum PioResult {
|
||||
Ok(BehaviorBase),
|
||||
NoSmAvailable,
|
||||
PinConflict,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
#[cfg(feature = "pio-memlcd")]
|
||||
#[repr(usize)]
|
||||
pub enum MemoryLcdOpcode {
|
||||
/// Blit a frame, don't block. If a callback is set, messages the callback when done.
|
||||
BlitFrameNonBlocking = 0,
|
||||
/// Blit a frame, block until blit is done
|
||||
BiltFrameBlocking = 1,
|
||||
/// Poll if blitting is in progress
|
||||
IsBusy = 2,
|
||||
/// Sets a callback address as SID + opcode for pingbacks when the blit is done.
|
||||
SetCallbackServer = 3,
|
||||
}
|
||||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
pub struct IoxConfigMessage {
|
||||
pub port: iox::IoxPort,
|
||||
pub pin: u8,
|
||||
pub direction: Option<iox::IoxDir>,
|
||||
pub function: Option<iox::IoxFunction>,
|
||||
pub schmitt_trigger: Option<iox::IoxEnable>,
|
||||
pub pullup: Option<iox::IoxEnable>,
|
||||
pub slow_slew: Option<iox::IoxEnable>,
|
||||
pub strength: Option<iox::IoxDriveStrength>,
|
||||
}
|
||||
|
||||
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
|
||||
pub enum IoxRequest {
|
||||
// possible requests
|
||||
Direction(iox::IoxDir),
|
||||
Pullup(iox::IoxEnable),
|
||||
SchmittTrigger(iox::IoxEnable),
|
||||
SlowSlew(iox::IoxEnable),
|
||||
DriveStrength(iox::IoxDriveStrength),
|
||||
SetAlternateFunction(iox::IoxFunction),
|
||||
SetPioFromPioBitmask(u32),
|
||||
SetPioFromPortAndPin(bool),
|
||||
// possible return results
|
||||
ResultPortPin(iox::IoxPort, u8),
|
||||
ResultOk,
|
||||
ResultErr,
|
||||
}
|
||||
|
|
|
|||
154
services/cram-hal-service/src/ifram_lib.rs
Normal file
154
services/cram-hal-service/src/ifram_lib.rs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
use num_traits::*;
|
||||
use xous::{send_message, MemoryAddress, MemoryRange, MemorySize, Message, Result};
|
||||
|
||||
use crate::{Opcode, SERVER_NAME_CRAM_HAL};
|
||||
|
||||
pub enum IframBank {
|
||||
Bank0,
|
||||
Bank1,
|
||||
}
|
||||
|
||||
/// `IframRange` is a range of memory that is suitable for use as a DMA target.
|
||||
pub struct IframRange {
|
||||
pub(crate) phys_addr: MemoryAddress,
|
||||
pub(crate) memory: MemoryRange,
|
||||
pub(crate) size: MemorySize,
|
||||
pub(crate) conn: xous::CID,
|
||||
}
|
||||
|
||||
impl IframRange {
|
||||
/// Request `length` bytes of memory in an optional Bank
|
||||
///
|
||||
/// Safety: the caller must ensure that the `IframRange` object lives for the
|
||||
/// entire lifetime of the *hardware* operation.
|
||||
///
|
||||
/// Example of how things can go wrong: `IframRange` is used to allocate
|
||||
/// a buffer for data that takes a long time to send via a slow UART.
|
||||
/// The DMA is initiated, and the function exits, dropping `IframRange`.
|
||||
/// At this point, the range could be re-allocated for another purpose.
|
||||
///
|
||||
/// An `IframRange` would naturally live as long as a DMA request
|
||||
/// if a sender synchronizes on the completion of the DMA request. Thus,
|
||||
/// the `unsafe` bit happens in "fire-and-forget" contexts, and the
|
||||
/// caller has to explicitly manage the lifetime of this object to
|
||||
/// match the maximum duration of the call.
|
||||
///
|
||||
/// A simple way to do this is to simply bind the structure to a long-lived
|
||||
/// scope, but the trade-off is that IFRAM is very limited in capacity
|
||||
/// and hanging on to chunks much longer than necessary can lead to memory
|
||||
/// exhaustion.
|
||||
pub unsafe fn request(length: usize, bank: Option<IframBank>) -> Option<Self> {
|
||||
REFCOUNT.fetch_add(1, Ordering::Relaxed);
|
||||
let xns = xous_api_names::XousNames::new().unwrap();
|
||||
let conn =
|
||||
xns.request_connection(SERVER_NAME_CRAM_HAL).expect("Couldn't connect to Cramium HAL server");
|
||||
let bank_code = match bank {
|
||||
Some(IframBank::Bank0) => 0,
|
||||
Some(IframBank::Bank1) => 1,
|
||||
_ => 2,
|
||||
};
|
||||
match send_message(
|
||||
conn,
|
||||
Message::new_blocking_scalar(Opcode::MapIfram.to_usize().unwrap(), length, bank_code, 0, 0),
|
||||
) {
|
||||
Ok(Result::Scalar5(maybe_size, maybe_phys_address, _, _, _)) => {
|
||||
if maybe_size != 0 && maybe_phys_address != 0 {
|
||||
let mut page_aligned_size = maybe_size / 4096;
|
||||
if maybe_size % 4096 != 0 {
|
||||
page_aligned_size += 1;
|
||||
}
|
||||
let virtual_pages = xous::map_memory(
|
||||
core::num::NonZeroUsize::new(maybe_phys_address),
|
||||
None,
|
||||
page_aligned_size,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.unwrap();
|
||||
Some(IframRange {
|
||||
phys_addr: MemoryAddress::new(maybe_phys_address).unwrap(),
|
||||
memory: virtual_pages,
|
||||
size: MemorySize::new(maybe_size).unwrap(),
|
||||
conn,
|
||||
})
|
||||
} else {
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
// "almost" safe because we checked our reference count before disconnecting
|
||||
// there is a race condition possibly if someone allocates a connection between
|
||||
// the check above, and the disconnect below.
|
||||
unsafe { xous::disconnect(conn).unwrap() }
|
||||
};
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
// "almost" safe because we checked our reference count before disconnecting
|
||||
// there is a race condition possibly if someone allocates a connection between
|
||||
// the check above, and the disconnect below.
|
||||
unsafe { xous::disconnect(conn).unwrap() }
|
||||
};
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the IframRange as a slice, useful for passing to the UDMA API calls.
|
||||
/// This is `unsafe` because the slice is actually not accessible in virtual memory mode:
|
||||
/// any attempt to reference the returned slice will result in a panic. The returned
|
||||
/// slice is *only* useful as a range-checked base/bounds for UDMA API calls.
|
||||
pub unsafe fn as_phys_slice(&self) -> &[u8] {
|
||||
core::slice::from_raw_parts(self.phys_addr.get() as *const u8, self.size.get())
|
||||
}
|
||||
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
// safe because `u8` is always representable on our system
|
||||
unsafe { self.memory.as_slice() }
|
||||
}
|
||||
|
||||
pub fn as_slice_u32(&self) -> &[u32] {
|
||||
// safe because `u32` is always representable on our system
|
||||
unsafe { self.memory.as_slice() }
|
||||
}
|
||||
|
||||
pub fn as_slice_mut(&mut self) -> &mut [u8] {
|
||||
// safe because `u8` is always representable on our system
|
||||
unsafe { self.memory.as_slice_mut() }
|
||||
}
|
||||
|
||||
pub fn as_slice_u32_mut(&mut self) -> &mut [u32] {
|
||||
// safe because `u32` is always representable on our system
|
||||
unsafe { self.memory.as_slice_mut() }
|
||||
}
|
||||
}
|
||||
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
pub(crate) static REFCOUNT: AtomicU32 = AtomicU32::new(0);
|
||||
impl Drop for IframRange {
|
||||
fn drop(&mut self) {
|
||||
match send_message(
|
||||
self.conn,
|
||||
Message::new_blocking_scalar(
|
||||
Opcode::UnmapIfram.to_usize().unwrap(),
|
||||
self.size.get(),
|
||||
self.phys_addr.get(),
|
||||
0,
|
||||
0,
|
||||
),
|
||||
) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
// This probably never happens, but also probably doesn't need to be a hard-panic
|
||||
// if it does happen because it simply degrades performance; it does not impact
|
||||
// correctness.
|
||||
log::error!("Couldn't de-allocate IframRange: {:?}, IFRAM memory is leaking!", e)
|
||||
}
|
||||
}
|
||||
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the
|
||||
// connection.
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
unsafe {
|
||||
xous::disconnect(self.conn).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
150
services/cram-hal-service/src/iox_lib.rs
Normal file
150
services/cram-hal-service/src/iox_lib.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
use cramium_hal::iox::{IoxDir, IoxDriveStrength, IoxEnable, IoxFunction, IoxPort, IoxValue};
|
||||
use num_traits::*;
|
||||
|
||||
use crate::{IoxConfigMessage, Opcode, SERVER_NAME_CRAM_HAL};
|
||||
|
||||
pub struct IoxHal {
|
||||
conn: xous::CID,
|
||||
}
|
||||
|
||||
impl IoxHal {
|
||||
pub fn new() -> Self {
|
||||
crate::REFCOUNT.fetch_add(1, Ordering::Relaxed);
|
||||
let xns = xous_api_names::XousNames::new().unwrap();
|
||||
let conn =
|
||||
xns.request_connection(SERVER_NAME_CRAM_HAL).expect("Couldn't connect to Cramium HAL server");
|
||||
IoxHal { conn }
|
||||
}
|
||||
|
||||
pub fn setup_io_pin(
|
||||
&self,
|
||||
port: IoxPort,
|
||||
pin: u8,
|
||||
direction: Option<IoxDir>,
|
||||
function: Option<IoxFunction>,
|
||||
schmitt_trigger: Option<IoxEnable>,
|
||||
pullup: Option<IoxEnable>,
|
||||
slow_slew: Option<IoxEnable>,
|
||||
strength: Option<IoxDriveStrength>,
|
||||
) {
|
||||
let msg =
|
||||
IoxConfigMessage { port, pin, direction, function, schmitt_trigger, pullup, slow_slew, strength };
|
||||
let buf = xous_ipc::Buffer::into_buf(msg).unwrap();
|
||||
buf.lend(self.conn, Opcode::ConfigureIox.to_u32().unwrap()).expect("Couldn't set up IO");
|
||||
}
|
||||
|
||||
pub fn set_gpio_pin_value(&self, port: IoxPort, pin: u8, value: IoxValue) {
|
||||
xous::send_message(
|
||||
self.conn,
|
||||
xous::Message::new_blocking_scalar(
|
||||
Opcode::SetGpioBank.to_usize().unwrap(),
|
||||
port as usize,
|
||||
// which pin, as a bitmask
|
||||
1 << pin as usize,
|
||||
// values to set
|
||||
(value as usize) << (pin as usize),
|
||||
0,
|
||||
),
|
||||
)
|
||||
.expect("Couldn't set GPIO pin value");
|
||||
}
|
||||
|
||||
pub fn set_gpio_bank_value(&self, port: IoxPort, value: u16, bitmask: u16) {
|
||||
xous::send_message(
|
||||
self.conn,
|
||||
xous::Message::new_blocking_scalar(
|
||||
Opcode::SetGpioBank.to_usize().unwrap(),
|
||||
port as usize,
|
||||
// values to set
|
||||
value as usize,
|
||||
// mask of valid bits
|
||||
bitmask as usize,
|
||||
0,
|
||||
),
|
||||
)
|
||||
.expect("Couldn't set GPIO pin value");
|
||||
}
|
||||
|
||||
pub fn get_gpio_pin_value(&self, port: IoxPort, pin: u8) -> IoxValue {
|
||||
match xous::send_message(
|
||||
self.conn,
|
||||
xous::Message::new_blocking_scalar(
|
||||
Opcode::GetGpioBank.to_usize().unwrap(),
|
||||
port as usize,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
) {
|
||||
Ok(xous::Result::Scalar5(value, _, _, _, _)) => {
|
||||
if value & (1 << pin as usize) != 0 {
|
||||
IoxValue::High
|
||||
} else {
|
||||
IoxValue::Low
|
||||
}
|
||||
}
|
||||
_ => panic!("Internal Error: Couldn't get GPIO pin value"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_gpio_bank_value(&self, port: IoxPort) -> u32 {
|
||||
match xous::send_message(
|
||||
self.conn,
|
||||
xous::Message::new_blocking_scalar(
|
||||
Opcode::GetGpioBank.to_usize().unwrap(),
|
||||
port as usize,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
) {
|
||||
Ok(xous::Result::Scalar5(value, _, _, _, _)) => value as u32,
|
||||
_ => panic!("Internal Error: Couldn't get GPIO pin value"),
|
||||
}
|
||||
}
|
||||
|
||||
/// This function takes a 32-bit bitmask, corresponding to PIO 31 through 0, where
|
||||
/// a `1` indicates to map that PIO to a GPIO.
|
||||
///
|
||||
/// This function will automatically remap the AF and PIO settings for the PIO pins
|
||||
/// specified in the bitmask, corresponding to the PIO GPIO pin number. If a `0` is
|
||||
/// present in a bit position, it will turn off the PIO mux, but not change the AF setting.
|
||||
///
|
||||
/// VERY IMPORTANT: Note that the PIO GPIO number is *not* consistent with the
|
||||
/// numbering order of the GPIO ports: in fact, it is reverse-order for PORT B and in-order with skips for
|
||||
/// PORT C. Also, bits 22, 27, 30 and 31 are not mappable for the PIO.
|
||||
///
|
||||
/// Returns: a 32-entry array which records which GPIO bank and pin number was affected
|
||||
/// by the mapping request. The index of the array corresponds to the bit position in
|
||||
/// the bitmask. You may use this to pass as arguments to further functions
|
||||
/// that do things like control slew rate or apply pull-ups.
|
||||
pub fn set_ports_from_pio_bitmask(&self, _enable_bitmask: u32) -> [Option<(IoxPort, u8)>; 32] {
|
||||
todo!("Do this when we get around to filling in the PIO drivers")
|
||||
}
|
||||
|
||||
/// Returns the PIO bit that was enabled based on the port and pin specifier given;
|
||||
/// returns `None` if the proposed mapping is invalid.
|
||||
pub fn set_pio_bit_from_port_and_pin(&self, _port: IoxPort, _pin: u8) -> Option<u8> {
|
||||
todo!("Do this when we get around to filling in the PIO drivers")
|
||||
}
|
||||
|
||||
/// Returns the PIO bit that was disabled based on the port and pin specifier given;
|
||||
/// returns `None` if the proposed mapping is invalid. Does not change the AF mapping,
|
||||
/// simply disables the bit in the PIO mux register.
|
||||
pub fn unset_pio_bit_from_port_and_pin(&self, _port: IoxPort, _pin: u8) -> Option<u8> {
|
||||
todo!("Do this when we get around to filling in the PIO drivers")
|
||||
}
|
||||
}
|
||||
|
||||
use core::sync::atomic::Ordering;
|
||||
impl Drop for IoxHal {
|
||||
fn drop(&mut self) {
|
||||
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the
|
||||
// connection.
|
||||
if crate::REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
unsafe {
|
||||
xous::disconnect(self.conn).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,148 +1,9 @@
|
|||
pub mod api;
|
||||
use core::sync::atomic::{AtomicU32, Ordering};
|
||||
pub mod ifram_lib;
|
||||
pub mod iox_lib;
|
||||
|
||||
pub use api::*;
|
||||
use num_traits::*;
|
||||
use xous::{send_message, MemoryAddress, MemoryRange, MemorySize, Message, Result};
|
||||
|
||||
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
|
||||
pub use ifram_lib::*;
|
||||
pub use iox_lib::*;
|
||||
|
||||
pub const SERVER_NAME_CRAM_HAL: &str = "_Cramium-SoC HAL_";
|
||||
|
||||
pub enum IframBank {
|
||||
Bank0,
|
||||
Bank1,
|
||||
}
|
||||
|
||||
/// `IframRange` is a range of memory that is suitable for use as a DMA target.
|
||||
pub struct IframRange {
|
||||
pub(crate) phys_addr: MemoryAddress,
|
||||
pub(crate) memory: MemoryRange,
|
||||
pub(crate) size: MemorySize,
|
||||
pub(crate) conn: xous::CID,
|
||||
}
|
||||
|
||||
impl IframRange {
|
||||
/// Request `length` bytes of memory in an optional Bank
|
||||
///
|
||||
/// Safety: the caller must ensure that the `IframRange` object lives for the
|
||||
/// entire lifetime of the *hardware* operation.
|
||||
///
|
||||
/// Example of how things can go wrong: `IframRange` is used to allocate
|
||||
/// a buffer for data that takes a long time to send via a slow UART.
|
||||
/// The DMA is initiated, and the function exits, dropping `IframRange`.
|
||||
/// At this point, the range could be re-allocated for another purpose.
|
||||
///
|
||||
/// An `IframRange` would naturally live as long as a DMA request
|
||||
/// if a sender synchronizes on the completion of the DMA request. Thus,
|
||||
/// the `unsafe` bit happens in "fire-and-forget" contexts, and the
|
||||
/// caller has to explicitly manage the lifetime of this object to
|
||||
/// match the maximum duration of the call.
|
||||
///
|
||||
/// A simple way to do this is to simply bind the structure to a long-lived
|
||||
/// scope, but the trade-off is that IFRAM is very limited in capacity
|
||||
/// and hanging on to chunks much longer than necessary can lead to memory
|
||||
/// exhaustion.
|
||||
pub unsafe fn request(length: usize, bank: Option<IframBank>) -> Option<Self> {
|
||||
REFCOUNT.fetch_add(1, Ordering::Relaxed);
|
||||
let xns = xous_api_names::XousNames::new().unwrap();
|
||||
let conn =
|
||||
xns.request_connection(SERVER_NAME_CRAM_HAL).expect("Couldn't connect to Cramium HAL server");
|
||||
let bank_code = match bank {
|
||||
Some(IframBank::Bank0) => 0,
|
||||
Some(IframBank::Bank1) => 1,
|
||||
_ => 2,
|
||||
};
|
||||
match send_message(
|
||||
conn,
|
||||
Message::new_blocking_scalar(Opcode::MapIfram.to_usize().unwrap(), length, bank_code, 0, 0),
|
||||
) {
|
||||
Ok(Result::Scalar5(maybe_size, maybe_phys_address, _, _, _)) => {
|
||||
if maybe_size != 0 && maybe_phys_address != 0 {
|
||||
let mut page_aligned_size = maybe_size / 4096;
|
||||
if maybe_size % 4096 != 0 {
|
||||
page_aligned_size += 1;
|
||||
}
|
||||
let virtual_pages = xous::map_memory(
|
||||
core::num::NonZeroUsize::new(maybe_phys_address),
|
||||
None,
|
||||
page_aligned_size,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.unwrap();
|
||||
Some(IframRange {
|
||||
phys_addr: MemoryAddress::new(maybe_phys_address).unwrap(),
|
||||
memory: virtual_pages,
|
||||
size: MemorySize::new(maybe_size).unwrap(),
|
||||
conn,
|
||||
})
|
||||
} else {
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
// "almost" safe because we checked our reference count before disconnecting
|
||||
// there is a race condition possibly if someone allocates a connection between
|
||||
// the check above, and the disconnect below.
|
||||
unsafe { xous::disconnect(conn).unwrap() }
|
||||
};
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
// "almost" safe because we checked our reference count before disconnecting
|
||||
// there is a race condition possibly if someone allocates a connection between
|
||||
// the check above, and the disconnect below.
|
||||
unsafe { xous::disconnect(conn).unwrap() }
|
||||
};
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the IframRange as a slice, useful for passing to the UDMA API calls.
|
||||
/// This is `unsafe` because the slice is actually not accessible in virtual memory mode:
|
||||
/// any attempt to reference the returned slice will result in a panic. The returned
|
||||
/// slice is *only* useful as a range-checked base/bounds for UDMA API calls.
|
||||
pub unsafe fn as_phys_slice(&self) -> &[u8] {
|
||||
core::slice::from_raw_parts(self.phys_addr.get() as *const u8, self.size.get())
|
||||
}
|
||||
|
||||
pub fn as_slice(&self) -> &[u8] {
|
||||
// safe because `u8` is always representable on our system
|
||||
unsafe { self.memory.as_slice() }
|
||||
}
|
||||
|
||||
pub fn as_slice_mut(&mut self) -> &mut [u8] {
|
||||
// safe because `u8` is always representable on our system
|
||||
unsafe { self.memory.as_slice_mut() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for IframRange {
|
||||
fn drop(&mut self) {
|
||||
match send_message(
|
||||
self.conn,
|
||||
Message::new_blocking_scalar(
|
||||
Opcode::UnmapIfram.to_usize().unwrap(),
|
||||
self.size.get(),
|
||||
self.phys_addr.get(),
|
||||
0,
|
||||
0,
|
||||
),
|
||||
) {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
// This probably never happens, but also probably doesn't need to be a hard-panic
|
||||
// if it does happen because it simply degrades performance; it does not impact
|
||||
// correctness.
|
||||
log::error!("Couldn't de-allocate IframRange: {:?}, IFRAM memory is leaking!", e)
|
||||
}
|
||||
}
|
||||
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the
|
||||
// connection.
|
||||
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
unsafe {
|
||||
xous::disconnect(self.conn).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
mod api;
|
||||
use api::*;
|
||||
#[cfg(feature = "pio")]
|
||||
mod pio;
|
||||
use cramium_hal::iox;
|
||||
use xous::sender::Sender;
|
||||
|
||||
fn try_alloc(ifram_allocs: &mut Vec<Option<Sender>>, size: usize, sender: Sender) -> Option<usize> {
|
||||
|
|
@ -68,6 +71,15 @@ fn main() {
|
|||
// `Sender` of it, so fill it with a value for `Some` that can't map to any PID.
|
||||
ifram_allocs[0][31] = Some(Sender::from_usize(usize::MAX));
|
||||
|
||||
let iox_page = xous::syscall::map_memory(
|
||||
xous::MemoryAddress::new(utralib::generated::HW_IOX_BASE),
|
||||
None,
|
||||
4096,
|
||||
xous::MemoryFlags::R | xous::MemoryFlags::W,
|
||||
)
|
||||
.expect("couldn't claim the IOX hardware page");
|
||||
let mut iox = iox::Iox::new(iox_page.as_mut_ptr() as *mut u32);
|
||||
|
||||
let mut msg_opt = None;
|
||||
log::debug!("Starting main loop");
|
||||
loop {
|
||||
|
|
@ -152,6 +164,45 @@ fn main() {
|
|||
}
|
||||
}
|
||||
}
|
||||
Opcode::ConfigureIox => {
|
||||
let buf =
|
||||
unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
|
||||
let config = buf.to_original::<IoxConfigMessage, _>().unwrap();
|
||||
if let Some(f) = config.function {
|
||||
iox.set_alternate_function(config.port, config.pin, f);
|
||||
}
|
||||
if let Some(d) = config.direction {
|
||||
iox.set_gpio_dir(config.port, config.pin, d);
|
||||
}
|
||||
if let Some(t) = config.schmitt_trigger {
|
||||
iox.set_gpio_schmitt_trigger(config.port, config.pin, t);
|
||||
}
|
||||
if let Some(p) = config.pullup {
|
||||
iox.set_gpio_pullup(config.port, config.pin, p);
|
||||
}
|
||||
if let Some(s) = config.slow_slew {
|
||||
iox.set_slow_slew_rate(config.port, config.pin, s);
|
||||
}
|
||||
if let Some(s) = config.strength {
|
||||
iox.set_drive_strength(config.port, config.pin, s);
|
||||
}
|
||||
}
|
||||
Opcode::SetGpioBank => {
|
||||
if let Some(scalar) = msg.body.scalar_message() {
|
||||
let port: cramium_hal::iox::IoxPort =
|
||||
num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap();
|
||||
let value = scalar.arg2 as u16;
|
||||
let bitmask = scalar.arg3 as u16;
|
||||
iox.set_gpio_bank(port, value, bitmask);
|
||||
}
|
||||
}
|
||||
Opcode::GetGpioBank => {
|
||||
if let Some(scalar) = msg.body.scalar_message_mut() {
|
||||
let port: cramium_hal::iox::IoxPort =
|
||||
num_traits::FromPrimitive::from_usize(scalar.arg1).unwrap();
|
||||
scalar.arg1 = iox.get_gpio_bank(port) as usize;
|
||||
}
|
||||
}
|
||||
Opcode::InvalidCall => {
|
||||
log::error!("Invalid opcode received: {:?}", msg);
|
||||
}
|
||||
|
|
|
|||
31
services/cram-hal-service/src/pio.rs
Normal file
31
services/cram-hal-service/src/pio.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
use cramium_hal::iox;
|
||||
use xous_pio::*;
|
||||
|
||||
/// This is the start of the memory LCD driver program, but aborted because we now
|
||||
/// realize the UDMA SPI block is much better suited for this task.
|
||||
fn pio_memlcd_program() {
|
||||
#[rustfmt::skip]
|
||||
let memlcd_line = pio_proc::pio_asm!(
|
||||
// The PIO engine is configured as a simple 16-bit, LSB-first shift register
|
||||
// to send data to the LCD at a rate of 2 MHz, requesting a new word via DMA
|
||||
// whenever the shift register is empty. It takes 2 PIO cycles to send one
|
||||
// bit, so the PIO engine should be configure to run at 4 MHz.
|
||||
//
|
||||
// In addition to the shift function, the PIO asserts the chip select signal
|
||||
// high for 12 cycles (3us @ 4MHz) before the first word starts shifting
|
||||
//
|
||||
// At the end of the DMA transfer, CS & clock should be dropped manually.
|
||||
".side_set 2 opt",
|
||||
|
||||
".define CS_SETUP_DELAY 12 ", // setup time for CS
|
||||
"setup_line:",
|
||||
" set y, CS_SETUP_DELAY side 0",
|
||||
"setup_cs:",
|
||||
" jmp y-- setup_cs side 1", // respect setup time
|
||||
".wrap_target",
|
||||
" out pins, 1 side 1", // assert data/clock low
|
||||
" nop side 3", // clock high
|
||||
".wrap",
|
||||
// after data transfer is done, clock and then CS should be dropped manually.
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue