add cramium-hal library

This commit is contained in:
bunnie 2024-01-18 18:00:49 +08:00
parent 8703764b8e
commit 28d959f938
5 changed files with 829 additions and 0 deletions

View file

@ -103,6 +103,7 @@ members = [
"libs/tls",
"libs/xous-pio",
"libs/xous-pl230",
"libs/cramium-hal",
]
resolver = "2"

View file

@ -0,0 +1,11 @@
[package]
name = "cramium-hal"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
utralib = { version = "0.1.24", default-features = false, features = [
"cramium-soc",
] }

383
libs/cramium-hal/src/iox.rs Normal file
View file

@ -0,0 +1,383 @@
use utralib::generated::utra::iox;
use utralib::generated::*;
macro_rules! set_pin_in_bank {
($self:expr, $register:expr, $port:expr, $pin:expr, $val:expr) => {{
assert!($pin < 16, "pin must be in range of 0-15");
// safety: it is safe to create this raw pointer and cast it because the
// code below does not add to the raw pointer outside of its approved range,
// thanks to the constraints placed by the enum type of IoxPort.
unsafe {
let oe_ptr = $self.csr.base();
oe_ptr.add($register.offset() + $port as usize).write_volatile(
(oe_ptr.add($register.offset() + $port as usize).read_volatile() & !(1u32 << ($pin as u32)))
| (($val as u32) << ($pin as u32)),
)
}
}};
}
#[derive(Copy, Clone)]
#[repr(u32)]
pub enum IoxPort {
PA = 0,
PB = 1,
PC = 2,
PD = 3,
PE = 4,
PF = 5,
}
#[repr(u32)]
pub enum IoxFunction {
Gpio = 0b00,
AF1 = 0b01,
AF2 = 0b10,
AF3 = 0b11,
}
#[repr(u32)]
pub enum IoxDriveStrength {
Drive2mA = 0b00,
Drive4mA = 0b01,
Drive8mA = 0b10,
Drive12mA = 0b11,
}
#[repr(u32)]
pub enum IoxDir {
Input = 0,
Output = 1,
}
#[repr(u32)]
pub enum IoxEnable {
Disable = 0,
Enable = 1,
}
#[derive(Copy, Clone)]
#[repr(u32)]
pub enum IoxValue {
Low = 0,
High = 1,
}
/// The From trait for IoxValue takes any non-zero value and interprets it as "high".
impl From<u32> for IoxValue {
fn from(value: u32) -> Self { if value == 0 { IoxValue::Low } else { IoxValue::High } }
}
pub struct Iox {
csr: CSR<u32>,
}
impl Iox {
pub fn new(base_address: *mut u32) -> Self { Iox { csr: CSR::new(base_address) } }
pub fn set_gpio_dir(&mut self, port: IoxPort, pin: u8, direction: IoxDir) {
set_pin_in_bank!(self, iox::SFR_GPIOOE_CRGOE0, port, pin, direction)
}
pub fn set_gpio_pullup(&mut self, port: IoxPort, pin: u8, enable: IoxEnable) {
set_pin_in_bank!(self, iox::SFR_GPIOPU_CRGPU0, port, pin, enable)
}
pub fn set_gpio_pin(&mut self, port: IoxPort, pin: u8, value: IoxValue) {
set_pin_in_bank!(self, iox::SFR_GPIOOUT_CRGO0, port, pin, value)
}
pub fn set_gpio_schmitt_trigger(&mut self, port: IoxPort, pin: u8, enable: IoxEnable) {
set_pin_in_bank!(self, iox::SFR_CFG_SCHM_CR_CFG_SCHMSEL0, port, pin, enable)
}
pub fn set_slow_slew_rate(&mut self, port: IoxPort, pin: u8, enable: IoxEnable) {
set_pin_in_bank!(self, iox::SFR_CFG_SLEW_CR_CFG_SLEWSLOW0, port, pin, enable)
}
pub fn get_gpio_pin(&self, port: IoxPort, pin: u8) -> IoxValue {
assert!(pin < 16, "pin must be in range of 0-15");
// safety: it is safe to create this raw pointer and cast it because the
// code below does not add to the raw pointer outside of its approved range,
// thanks to the constraints placed by the enum type of IoxPort.
unsafe {
let oe_ptr = self.csr.base();
IoxValue::from(
oe_ptr.add(iox::SFR_GPIOIN_SRGI0.offset() + port as usize).read_volatile()
& !(1u32 << (pin as u32)),
)
}
}
pub fn get_gpio_bank(&self, port: IoxPort) -> u16 {
// safety: it is safe to create this raw pointer and cast it because the
// code below does not add to the raw pointer outside of its approved range,
// thanks to the constraints placed by the enum type of IoxPort.
unsafe {
let oe_ptr = self.csr.base();
oe_ptr.add(iox::SFR_GPIOIN_SRGI0.offset() + port as usize).read_volatile() as u16
}
}
pub fn set_alternate_function(&mut self, port: IoxPort, pin: u8, function: IoxFunction) {
assert!(pin < 16, "pin must be in range of 0-15");
match port {
IoxPort::PA => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL0,
self.csr.r(iox::SFR_AFSEL_CRAFSEL0) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL1,
self.csr.r(iox::SFR_AFSEL_CRAFSEL1) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
IoxPort::PB => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL2,
self.csr.r(iox::SFR_AFSEL_CRAFSEL2) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL3,
self.csr.r(iox::SFR_AFSEL_CRAFSEL3) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
IoxPort::PC => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL4,
self.csr.r(iox::SFR_AFSEL_CRAFSEL4) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL5,
self.csr.r(iox::SFR_AFSEL_CRAFSEL5) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
IoxPort::PD => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL6,
self.csr.r(iox::SFR_AFSEL_CRAFSEL6) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL7,
self.csr.r(iox::SFR_AFSEL_CRAFSEL7) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
IoxPort::PE => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL8,
self.csr.r(iox::SFR_AFSEL_CRAFSEL8) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL9,
self.csr.r(iox::SFR_AFSEL_CRAFSEL9) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
IoxPort::PF => {
if pin < 8 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL10,
self.csr.r(iox::SFR_AFSEL_CRAFSEL10) & !(0b11 << (pin * 2))
| (function as u32) << (pin * 2),
)
} else if pin >= 8 && pin < 16 {
self.csr.wo(
iox::SFR_AFSEL_CRAFSEL11,
self.csr.r(iox::SFR_AFSEL_CRAFSEL11) & !(0b11 << ((pin - 8) * 2))
| (function as u32) << ((pin - 8) * 2),
)
}
}
}
}
/// 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(&mut self, enable_bitmask: u32) -> [Option<(IoxPort, u8)>; 32] {
let mut mapping: [Option<(IoxPort, u8)>; 32] = [None; 32];
for i in 0..32 {
let enable = ((enable_bitmask >> i) & 1) != 0;
if enable {
let map: Option<(IoxPort, u8)> = match i {
// Port B: reversed
0 => Some((IoxPort::PB, 15)),
1 => Some((IoxPort::PB, 14)),
2 => Some((IoxPort::PB, 13)),
3 => Some((IoxPort::PB, 12)),
4 => Some((IoxPort::PB, 11)),
5 => Some((IoxPort::PB, 10)),
6 => Some((IoxPort::PB, 9)),
7 => Some((IoxPort::PB, 8)),
8 => Some((IoxPort::PB, 7)),
9 => Some((IoxPort::PB, 6)),
10 => Some((IoxPort::PB, 5)),
11 => Some((IoxPort::PB, 4)),
12 => Some((IoxPort::PB, 3)),
13 => Some((IoxPort::PB, 2)),
14 => Some((IoxPort::PB, 1)),
15 => Some((IoxPort::PB, 0)),
// Port C
16 => Some((IoxPort::PC, 0)),
17 => Some((IoxPort::PC, 1)),
18 => Some((IoxPort::PC, 2)),
19 => Some((IoxPort::PC, 3)),
20 => Some((IoxPort::PC, 4)),
21 => Some((IoxPort::PC, 5)),
// Skip 22
23 => Some((IoxPort::PC, 7)),
24 => Some((IoxPort::PC, 8)),
25 => Some((IoxPort::PC, 9)),
26 => Some((IoxPort::PC, 10)),
// Skip 27
28 => Some((IoxPort::PC, 12)),
29 => Some((IoxPort::PC, 13)),
_ => None,
};
if let Some((port, pin)) = map {
// AF1 must be selected
self.set_alternate_function(port, pin, IoxFunction::AF1);
// then the PIO register must have its bit flipped to 1
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) | (1 << i));
mapping[i] = Some((port, pin));
}
} else {
mapping[i] = None;
// ensure that the PIO register bit is not set
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) & !(1 << i));
}
}
mapping
}
/// 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(&mut self, port: IoxPort, pin: u8) -> Option<u8> {
match port {
IoxPort::PA => None,
IoxPort::PB => {
if pin >= 16 {
None
} else {
self.set_alternate_function(port, pin, IoxFunction::AF1);
let pio_bit = 15 - pin;
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) | (1 << pio_bit as u32));
Some(pio_bit)
}
}
IoxPort::PC => {
if (pin != 6 && pin != 11 && pin != 14 && pin != 15) && pin < 16 {
self.set_alternate_function(port, pin, IoxFunction::AF1);
let pio_bit = pin + 16;
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) | (1 << pio_bit as u32));
Some(pio_bit)
} else {
None
}
}
_ => None,
}
}
/// 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(&mut self, port: IoxPort, pin: u8) -> Option<u8> {
match port {
IoxPort::PA => None,
IoxPort::PB => {
if pin >= 16 {
None
} else {
let pio_bit = 15 - pin;
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) & !(1 << pio_bit as u32));
Some(pio_bit)
}
}
IoxPort::PC => {
if (pin != 6 && pin != 11 && pin != 14 && pin != 15) && pin < 16 {
let pio_bit = pin + 16;
self.csr.wo(iox::SFR_PIOSEL, self.csr.r(iox::SFR_PIOSEL) & !(1 << pio_bit as u32));
Some(pio_bit)
} else {
None
}
}
_ => None,
}
}
pub fn set_drive_strength(&mut self, port: IoxPort, pin: u8, strength: IoxDriveStrength) {
assert!(pin < 16, "pin must be in range of 0-15");
match port {
IoxPort::PA => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL0,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL0) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
IoxPort::PB => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL1,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL1) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
IoxPort::PC => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL2,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL2) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
IoxPort::PD => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL3,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL3) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
IoxPort::PE => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL4,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL4) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
IoxPort::PF => self.csr.wo(
iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL5,
self.csr.r(iox::SFR_CFG_DRVSEL_CR_CFG_DRVSEL5) & !(0b11 << (pin * 2))
| (strength as u32) << (pin * 2),
),
}
}
}

View file

@ -0,0 +1,4 @@
#![no_std]
pub mod iox;
pub mod udma;

View file

@ -0,0 +1,430 @@
use core::mem::size_of;
use utralib::generated::*;
/// UDMA has a structure that Rust hates. The concept of UDMA is to take a bunch of
/// different hardware functions, and access them with a template register pattern.
/// But with small asterisks here and there depending upon the hardware block in question.
///
/// It is essentially polymorphism at the hardware level, but with special cases meant
/// to be patched up with instance-specific peeks and pokes. It's probably possible
/// to create a type system that can safe-ify this kind of structure, but just because
/// something is possible does not mean it's a good idea to do it, nor would it be
/// maintainable and/or ergonomic to use.
///
/// Anyways. Lots of unsafe code here. UDMA: specious concept, made entirely of footguns.
// --------------------------- Global Shared State (!!🤌!!) --------------------------
#[repr(usize)]
enum GlobalReg {
ClockGate = 0,
EventIn = 1,
}
impl Into<usize> for GlobalReg {
fn into(self) -> usize { self as usize }
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum PeriphId {
Uart0 = 1 << 0,
Uart1 = 1 << 1,
Uart2 = 1 << 2,
Uart3 = 1 << 3,
Spim0 = 1 << 4,
Spim1 = 1 << 5,
Spim2 = 1 << 6,
Spim3 = 1 << 7,
I2c0 = 1 << 8,
I2c1 = 1 << 9,
I2c2 = 1 << 10,
I2c3 = 1 << 11,
Sdio = 1 << 12,
I2s = 1 << 13,
Cam = 1 << 14,
Filter = 1 << 15,
Scif = 1 << 16,
Spis0 = 1 << 17,
Spis1 = 1 << 18,
Adc = 1 << 19,
}
impl Into<u32> for PeriphId {
fn into(self) -> u32 { self as u32 }
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum PeriphEventId {
Uart0 = 0,
Uart1 = 4,
Uart2 = 8,
Uart3 = 12,
Spim0 = 16,
Spim1 = 20,
Spim2 = 24,
Spim3 = 28,
I2c0 = 32,
I2c1 = 36,
I2c2 = 40,
I2c3 = 44,
Sdio = 48,
I2s = 52,
Cam = 56,
Adc = 57, // note exception to ordering here
Filter = 60,
Scif = 64,
Spis0 = 68,
Spis1 = 72,
}
impl From<PeriphId> for PeriphEventId {
fn from(id: PeriphId) -> Self {
match id {
PeriphId::Uart0 => PeriphEventId::Uart0,
PeriphId::Uart1 => PeriphEventId::Uart1,
PeriphId::Uart2 => PeriphEventId::Uart2,
PeriphId::Uart3 => PeriphEventId::Uart3,
PeriphId::Spim0 => PeriphEventId::Spim0,
PeriphId::Spim1 => PeriphEventId::Spim1,
PeriphId::Spim2 => PeriphEventId::Spim2,
PeriphId::Spim3 => PeriphEventId::Spim3,
PeriphId::I2c0 => PeriphEventId::I2c0,
PeriphId::I2c1 => PeriphEventId::I2c1,
PeriphId::I2c2 => PeriphEventId::I2c2,
PeriphId::I2c3 => PeriphEventId::I2c3,
PeriphId::Sdio => PeriphEventId::Sdio,
PeriphId::I2s => PeriphEventId::I2s,
PeriphId::Cam => PeriphEventId::Cam,
PeriphId::Filter => PeriphEventId::Filter,
PeriphId::Scif => PeriphEventId::Scif,
PeriphId::Spis0 => PeriphEventId::Spis0,
PeriphId::Spis1 => PeriphEventId::Spis1,
PeriphId::Adc => PeriphEventId::Adc,
}
}
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventUartOffset {
Rx = 0,
Tx = 1,
RxChar = 2,
Err = 3,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventSpimOffset {
Rx = 0,
Tx = 1,
Cmd = 2,
Eot = 3,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventI2cOffset {
Rx = 0,
Tx = 1,
Cmd = 2,
Eot = 3,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventSdioOffset {
Rx = 0,
Tx = 1,
Eot = 2,
Err = 3,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventI2sOffset {
Rx = 0,
Tx = 1,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventCamOffset {
Rx = 0,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventAdcOffset {
Rx = 0,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventFilterOffset {
Eot = 0,
Active = 1,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventScifOffset {
Rx = 0,
Tx = 1,
RxChar = 2,
Err = 3,
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventSpisOffset {
Rx = 0,
Tx = 1,
Eot = 2,
}
#[derive(Copy, Clone)]
pub enum PeriphEventType {
Uart(EventUartOffset),
Spim(EventSpimOffset),
I2c(EventI2cOffset),
Sdio(EventSdioOffset),
I2s(EventI2sOffset),
Cam(EventCamOffset),
Adc(EventAdcOffset),
Filter(EventFilterOffset),
Scif(EventScifOffset),
Spis(EventSpisOffset),
}
impl Into<u32> for PeriphEventType {
fn into(self) -> u32 {
match self {
PeriphEventType::Uart(t) => t as u32,
PeriphEventType::Spim(t) => t as u32,
PeriphEventType::I2c(t) => t as u32,
PeriphEventType::Sdio(t) => t as u32,
PeriphEventType::I2s(t) => t as u32,
PeriphEventType::Cam(t) => t as u32,
PeriphEventType::Adc(t) => t as u32,
PeriphEventType::Filter(t) => t as u32,
PeriphEventType::Scif(t) => t as u32,
PeriphEventType::Spis(t) => t as u32,
}
}
}
#[repr(u32)]
#[derive(Copy, Clone)]
pub enum EventChannel {
Channel0 = 0,
Channel1 = 8,
Channel2 = 16,
Channel3 = 24,
}
pub struct GlobalConfig {
csr: CSR<u32>,
}
impl GlobalConfig {
pub fn new(base_addr: *mut u32) -> Self { GlobalConfig { csr: CSR::new(base_addr) } }
pub fn clock_on(&mut self, peripheral: PeriphId) {
// Safety: only safe when used in the context of UDMA registers.
unsafe {
self.csr.base().add(GlobalReg::ClockGate.into()).write_volatile(
self.csr.base().add(GlobalReg::ClockGate.into()).read_volatile() | peripheral as u32,
);
}
}
pub fn clock_off(&mut self, peripheral: PeriphId) {
// Safety: only safe when used in the context of UDMA registers.
unsafe {
self.csr.base().add(GlobalReg::ClockGate.into()).write_volatile(
self.csr.base().add(GlobalReg::ClockGate.into()).read_volatile() & !(peripheral as u32),
);
}
}
pub fn raw_clock_map(&self) -> u32 {
// Safety: only safe when used in the context of UDMA registers.
unsafe { self.csr.base().add(GlobalReg::ClockGate.into()).read_volatile() }
}
pub fn is_clock_set(&self, peripheral: PeriphId) -> bool {
// Safety: only safe when used in the context of UDMA registers.
unsafe {
(self.csr.base().add(GlobalReg::ClockGate.into()).read_volatile() & (peripheral as u32)) != 0
}
}
pub fn map_event(&mut self, peripheral: PeriphId, event_type: PeriphEventType, to_channel: EventChannel) {
let event_type: u32 = event_type.into();
let id: u32 = PeriphEventId::from(peripheral) as u32 + event_type;
// Safety: only safe when used in the context of UDMA registers.
unsafe {
self.csr.base().add(GlobalReg::EventIn.into()).write_volatile(
self.csr.base().add(GlobalReg::EventIn.into()).read_volatile()
& !(0xFF << (to_channel as u32))
| id << (to_channel as u32),
)
}
}
pub fn raw_event_map(&self) -> u32 {
// Safety: only safe when used in the context of UDMA registers.
unsafe { self.csr.base().add(GlobalReg::EventIn.into()).read_volatile() }
}
}
// --------------------------------- DMA channel ------------------------------------
const CFG_EN: u32 = 0b01_0000; // start a transfer
#[allow(dead_code)]
const CFG_CONT: u32 = 0b00_0001; // continuous mode
#[allow(dead_code)]
const CFG_SIZE_8: u32 = 0b00_0000; // 8-bit transfer
#[allow(dead_code)]
const CFG_SIZE_16: u32 = 0b00_0010; // 16-bit transfer
#[allow(dead_code)]
const CFG_SIZE_32: u32 = 0b00_0100; // 32-bit transfer
#[allow(dead_code)]
const CFG_CLEAR: u32 = 0b10_0000; // stop and clear all pending transfers
const CFG_SHADOW: u32 = 0b10_0000; // indicates a shadow transfer
#[repr(usize)]
pub enum Bank {
Rx = 0,
Tx = 0x10 / size_of::<u32>(),
// woo dat special case...
Custom = 0x20 / size_of::<u32>(),
}
impl Into<usize> for Bank {
fn into(self) -> usize { self as usize }
}
/// Crate-local struct that defines the offset of registers in UDMA banks, as words.
#[repr(usize)]
enum DmaReg {
Saddr = 0,
Size = 1,
Cfg = 2,
#[allow(dead_code)]
IntCfg = 3,
}
impl Into<usize> for DmaReg {
fn into(self) -> usize { self as usize }
}
/// The common UDMA channel structure shared across all UDMA peripherals
pub struct Channel {
/// This is assumed to point to the base of the peripheral's UDMA register set.
csr: CSR<u32>,
}
impl Channel {
pub fn new(udma_base_addr: *mut u32) -> Self { Channel { csr: CSR::new(udma_base_addr) } }
/// `bank` selects which UDMA bank is the target
/// `buf` is a slice that points to the memory that is the target of the UDMA. Needs to be accessible
/// by the UDMA subsystem, e.g. in IFRAM0/IFRAM1 range, and is a *physical address* even in a
/// system running on virtual memory (!!!)
/// `config` is a device-specific word that configures the DMA.
pub fn enqueue(&mut self, bank: Bank, buf: &[u8], config: u32) {
// Safety: only safe when used in the context of UDMA registers.
unsafe {
let bank_addr = self.csr.base().add(bank as usize);
let buf_addr = buf.as_ptr() as u32;
bank_addr.add(DmaReg::Saddr.into()).write_volatile(buf_addr);
bank_addr.add(DmaReg::Size.into()).write_volatile(buf.len() as u32);
bank_addr.add(DmaReg::Cfg.into()).write_volatile(config | CFG_EN)
}
}
pub fn can_enqueue(&self, bank: Bank) -> bool {
// Safety: only safe when used in the context of UDMA registers.
unsafe {
(self.csr.base().add(bank as usize).add(DmaReg::Cfg.into()).read_volatile() & CFG_SHADOW) == 0
}
}
pub fn busy(&self, bank: Bank) -> bool {
// Safety: only safe when used in the context of UDMA registers.
unsafe { (self.csr.base().add(bank as usize).add(DmaReg::Cfg.into()).read_volatile() & CFG_EN) != 0 }
}
}
// ----------------------------------- UART ------------------------------------
#[repr(usize)]
enum UartReg {
Status = 0,
Setup = 1,
}
impl Into<usize> for UartReg {
fn into(self) -> usize { self as usize }
}
/// UDMA UART wrapper. Contains all the warts on top of the Channel abstraction.
pub struct Uart {
/// This is assumed to point to the base of the peripheral's UDMA register set.
csr: CSR<u32>,
udma: Channel,
}
impl Uart {
/// Configures for N81
///
/// This function is `unsafe` because it can only be called after the
/// global shared UDMA state has been set up to un-gate clocks and set up
/// events.
///
/// It is also `unsafe` on Drop because you have to remember to unmap
/// the clock manually as well once the object is dropped...
pub unsafe fn new(base_addr: usize, baud: u32, clk_freq: u32) -> Self {
// now setup the channel
let channel = Channel::new(base_addr as *mut u32);
let csr = CSR::new(base_addr as *mut u32);
let clk_counter: u32 = (clk_freq + baud / 2) / baud;
// safe only in the context of a UART UDMA address
unsafe {
// setup baud, bits, parity, etc.
csr.base()
.add(Bank::Custom.into())
.add(UartReg::Setup.into())
.write_volatile(0x0306 | (clk_counter << 16))
}
Uart { csr, udma: channel }
}
pub fn disable(&mut self) {
// safe only in the context of a UART UDMA address
unsafe {
self.csr.base().add(Bank::Custom.into()).add(UartReg::Setup.into()).write_volatile(0x0050_0006);
}
}
pub fn tx_busy(&self) -> bool {
// safe only in the context of a UART UDMA address
unsafe {
(self.csr.base().add(Bank::Custom.into()).add(UartReg::Status.into()).read_volatile() & 1) != 0
}
}
pub fn rx_busy(&self) -> bool {
// safe only in the context of a UART UDMA address
unsafe {
(self.csr.base().add(Bank::Custom.into()).add(UartReg::Status.into()).read_volatile() & 2) != 0
}
}
pub fn wait_tx_done(&self) {
while self.udma.busy(Bank::Tx) {}
while self.tx_busy() {}
}
pub fn wait_rx_done(&self) { while self.udma.busy(Bank::Rx) {} }
pub fn write(&mut self, buf: &[u8]) {
self.udma.enqueue(Bank::Tx, buf, CFG_EN | CFG_SIZE_8);
self.wait_tx_done();
}
pub fn read(&mut self, buf: &mut [u8]) {
self.udma.enqueue(Bank::Rx, buf, CFG_EN | CFG_SIZE_8);
self.wait_rx_done();
}
}
impl Drop for Uart {
fn drop(&mut self) {
self.wait_tx_done();
self.disable();
// NOTE: this does not unmap the clock on drop, because clocks are managed by global shared state.
}
}