diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 43274c6f..96e928a6 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -32,13 +32,13 @@ jobs: target: thumbv7em-none-eabihf override: true profile: minimal - - name: Check imxrt1060-hal with features '${{ matrix.features }}' + - name: Check imxrt-hal with features '${{ matrix.features }}' uses: actions-rs/cargo@v1 with: command: check args: > --features=${{ matrix.features }} - --manifest-path=imxrt1060-hal/Cargo.toml + --manifest-path=imxrt-hal/Cargo.toml --target=thumbv7em-none-eabihf --verbose diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ffc3e793..3996ce7c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Thanks for helping us build embedded Rust support for NXP's i.MX RT processors! Please open an issue if -- you find a bug in any chip HAL +- you find a bug in the HAL, RAL, or IOMUXC crates - you have an idea for a feature - something isn't clear in our documentation @@ -20,22 +20,45 @@ You'll need ```bash rustup target add thumbv7em-none-eabihf ``` -### Chip-specific HAL(s) -We support one HAL crate per i.MX RT processor family. A "processor family" is described by an NXP datasheet and reference manual. For example, the `imxrt1060-hal` supports the [i.MX RT1060 Crossover Processors](https://www.nxp.com/docs/en/nxp/data-sheets/IMXRT1060CEC.pdf), which includes the following processors: +### RAL -- i.MX RT 1061 -- i.MX RT 1062 +The `imxrt-ral` crate is auto-generated from the checked-in SVD files, available in `imxrt-ral/svd`. It's checked into git, and you should always have whatever represents the latest auto-generated RAL. Generally, you should **not** manually change RAL source files; rather, you should describe changes in `imxrtral.py`, the Python script that auto-generates the RAL. -When developing the HAL(s) a quick way to check everything compiles, in the project root +To generate the RAL, +- Install Python 3. You'll need at least Python 3.6. +- Install the Python dependencies needed to generate the RAL: `pip3 install --user svdtools`. Alternatively, use the rules in the RAL's `Makefile` to create a virtual environment with the necessary dependencies: `make venv update-venv && source venv/bin/activate`. +- Run `make` in the `imxrt-ral` directory: `make -C imxrt-ral`. The auto-generation script might generate warnings; that's OK. + +If everything went well, you should find that the `imxrt-ral/src` directory is populated with Rust files. If you made changes in `imxrtral.py`, you should see those changes reflected in the Rust files. The RAL can build by itself: `cd imxrt-ral && cargo check --features imxrt1062 --target thumbv7em-none-eabihf`. + +If you add a SVD patch, or if you change something in `imxrtral.py`, you'll need to re-generate the RAL to realize the change. + +### HAL + +Make sure you've generated the RAL (see above). When developing the HAL, specify a feature flag from the command line. To check the HAL for `imxrt1062` processors, `cd imxrt-hal`, then + +``` +cargo check --features imxrt1062 --target thumbv7em-none-eabihf ``` -cargo check --target thumbv7em-none-eabihf + +### IOMUXC + +The `imxrt-iomuxc` crate family does not require any feature flags, and it will build for your host. Consider using `--package` flags to build and test the crate family in one command: + ``` +cargo build --package=imxrt-iomuxc --package=imxrt-iomuxc-build +cargo test -p imxrt-iomuxc -p imxrt-iomuxc-build +``` + +### SVD Patches + +To modify the RAL, you'll need to describe your change as an SVD patch. If you'd like to add patches to the i.MX RT SVD files, learn about [svdtools](https://github.com/stm32-rs/svdtools). Use some of the existing SVD patches as a guide. ### Testing -Our CI system ensures that the RAL and HAL(s) build for all processor variants. But, we can't automatically test against hardware! To test your changes on hardware, you'll need to test the RAL and the HAL(s) using another project, like a Rust BSP crate. Some BSP crates that use the `imxrt1060-hal` include +Our CI system ensures that the RAL and HAL builds for all processor variants. But, we can't automatically test against hardware! To test your changes on hardware, you'll need to test the RAL and the HAL using another project, like a Rust BSP crate. Some BSP crates that use the `imxrt-hal` include - [the `imxrt1060evk-bsp` crate](https://github.com/imxrt-rs/imxrt1060evk-bsp) - [the `teensy4-bsp` crate](https://github.com/mciantyre/teensy4-rs) @@ -53,4 +76,4 @@ Follow the instructions in those projects to prepare an environment for testing ## Release Steps -To create a release of the RAL and HAL crates, see [RELEASE.md](docs/RELEASE.md). +To create a release of the RAL and HAL crates, see [RELEASE.md](docs/RELEASE.md). \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 3007f6b2..da9f9551 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,4 @@ [workspace] members = [ - "imxrt1060-hal", + "imxrt-hal", ] diff --git a/imxrt1060-hal/.gitignore b/imxrt-hal/.gitignore similarity index 100% rename from imxrt1060-hal/.gitignore rename to imxrt-hal/.gitignore diff --git a/imxrt1060-hal/CHANGELOG.md b/imxrt-hal/CHANGELOG.md similarity index 100% rename from imxrt1060-hal/CHANGELOG.md rename to imxrt-hal/CHANGELOG.md diff --git a/imxrt-hal/Cargo.toml b/imxrt-hal/Cargo.toml new file mode 100644 index 00000000..2f3b3342 --- /dev/null +++ b/imxrt-hal/Cargo.toml @@ -0,0 +1,54 @@ +[package] +name = "imxrt-hal" +authors = ["Tom Burdick ", "Ian McIntyre "] +description = "Hardware abstraction layer for all NXP i.MX RT microcontrollers" +repository = "https://github.com/imxrt-rs/imxrt-rs" +readme = "README.md" +keywords = ["imxrt", "nxp", "embedded", "no_std"] +categories = ["embedded", "no-std"] +license = "MIT/Apache-2.0" +edition = "2018" +version = "0.4.5" + +[dependencies] +as-slice = "0.1.3" +cortex-m = { version = "0.6" } +imxrt-ral = "0.4.0" +bitflags = "1.2.1" +embedded-hal = "0.2.3" +nb = "0.1.2" +void = { version = "1.0.2", default-features = false } +log = "0.4.8" +rand_core = { version = "0.5", default-features = false, optional = true } + +[dependencies.imxrt-iomuxc] +version = "0.1.2" +git = "https://github.com/dstric-aqueduct/imxrt-iomuxc.git" +branch = "v0.1.2/can" + +[dev-dependencies.cortex-m-rt] +version = "0.6" +features = ["device"] + +[lib] +bench = false + +[features] +default = ["embedded-hal/unproven"] # Allows us to access the new digital pin traits + +# Device specific feature flags +# these need fixes and conditional sections in CCM +#imxrt1011 = ["imxrt-ral/imxrt1011"] +#imxrt1015 = ["imxrt-ral/imxrt1015"] +#imxrt1021 = ["imxrt-ral/imxrt1021"] +#imxrt1051 = ["imxrt-ral/imxrt1051"] +#imxrt1052 = ["imxrt-ral/imxrt1052"] +imxrt1061 = ["imxrt-ral/imxrt1061", "imxrt-iomuxc/imxrt106x"] +imxrt1062 = ["imxrt-ral/imxrt1062", "imxrt-iomuxc/imxrt106x"] +imxrt1064 = ["imxrt-ral/imxrt1064", "imxrt-iomuxc/imxrt106x"] +rtic = ["imxrt-ral/rtic"] +rt = ["imxrt-ral/rt"] +nosync = ["imxrt-ral/nosync"] + +[package.metadata.docs.rs] +features = ["imxrt1062"] diff --git a/imxrt1060-hal/Makefile b/imxrt-hal/Makefile similarity index 100% rename from imxrt1060-hal/Makefile rename to imxrt-hal/Makefile diff --git a/imxrt-hal/README.md b/imxrt-hal/README.md new file mode 100644 index 00000000..802a47b8 --- /dev/null +++ b/imxrt-hal/README.md @@ -0,0 +1,22 @@ +# imxrt-hal + +This project provides a Rust HAL (hardware abstraction layer) for all NXP i.MX RT +microcontrollers based on the imxrt-ral crate. + +A feature flag needs to be set for any of the supported i.MX RT SoC. + +## What is it? + +imxrt-hal is an experiment into a lightweight hardware abstraction layer. It +provides access to some of the peripherals of the i.MX RT series processors +from NXP using embedded-hal and other community driven hardware APIs. + +The main aims are fast compilation, compactness, and simplicity. + +Please consider trying it out and contributing or leaving feedback! + +## Goals + +* Simple to use and hard to use incorrectly +* All peripherals and busses supported +* Support the entire i.MX RT Series with a single crate to maximize code reuse diff --git a/imxrt1060-hal/src/adc.rs b/imxrt-hal/src/adc.rs similarity index 100% rename from imxrt1060-hal/src/adc.rs rename to imxrt-hal/src/adc.rs diff --git a/imxrt-hal/src/can/embedded_hal.rs b/imxrt-hal/src/can/embedded_hal.rs new file mode 100644 index 00000000..c90db430 --- /dev/null +++ b/imxrt-hal/src/can/embedded_hal.rs @@ -0,0 +1,104 @@ +//! `embedded_hal` trait impls. + +use super::{Data, ExtendedId, Frame, Id, OverrunError, StandardId, CAN}; + +use crate::iomuxc::consts::Unsigned; +use embedded_hal::can; + +impl can::Can for CAN +where + M: Unsigned, +{ + type Frame = Frame; + + type Error = OverrunError; + + fn transmit(&mut self, frame: &Self::Frame) -> nb::Result, Self::Error> { + match self.transmit(frame) { + Ok(_status) => Ok(Some(frame.clone())), + Err(nb::Error::WouldBlock) => Err(nb::Error::WouldBlock), + Err(nb::Error::Other(e)) => match e {}, + } + } + + fn receive(&mut self) -> nb::Result { + let data: [u8; 8] = [255, 255, 255, 255, 255, 255, 255, 255]; + let id = StandardId::new(0).unwrap(); + + Ok(Frame::new_data(id, Data::new(&data).unwrap())) + } +} + +impl can::Error for OverrunError { + fn kind(&self) -> can::ErrorKind { + can::ErrorKind::Overrun + } +} + +impl can::Frame for Frame { + fn new(id: impl Into, data: &[u8]) -> Option { + let id = match id.into() { + can::Id::Standard(id) => unsafe { + Id::Standard(StandardId::new_unchecked(id.as_raw())) + }, + can::Id::Extended(id) => unsafe { + Id::Extended(ExtendedId::new_unchecked(id.as_raw())) + }, + }; + + let data = Data::new(data)?; + Some(Frame::new_data(id, data)) + } + + fn new_remote(id: impl Into, dlc: usize) -> Option { + let id = match id.into() { + can::Id::Standard(id) => unsafe { + Id::Standard(StandardId::new_unchecked(id.as_raw())) + }, + can::Id::Extended(id) => unsafe { + Id::Extended(ExtendedId::new_unchecked(id.as_raw())) + }, + }; + + if dlc <= 8 { + Some(Frame::new_remote(id, dlc as u8)) + } else { + None + } + } + + #[inline] + fn is_extended(&self) -> bool { + self.is_extended() + } + + #[inline] + fn is_remote_frame(&self) -> bool { + self.is_remote_frame() + } + + #[inline] + fn id(&self) -> can::Id { + match self.id() { + Id::Standard(id) => unsafe { + can::Id::Standard(can::StandardId::new_unchecked(id.as_raw())) + }, + Id::Extended(id) => unsafe { + can::Id::Extended(can::ExtendedId::new_unchecked(id.as_raw())) + }, + } + } + + #[inline] + fn dlc(&self) -> usize { + self.dlc().into() + } + + fn data(&self) -> &[u8] { + if let Some(data) = self.data() { + data + } else { + &[] + } + } +} diff --git a/imxrt-hal/src/can/filter.rs b/imxrt-hal/src/can/filter.rs new file mode 100644 index 00000000..947c3b26 --- /dev/null +++ b/imxrt-hal/src/can/filter.rs @@ -0,0 +1,27 @@ +//! Filter bank API. + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] +pub enum FlexCanIde { + #[default] + None = 0, + Ext = 1, + Rtr = 2, + Std = 3, + Inactive +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] +pub enum FlexCanFlten { + AcceptAll = 0, + #[default] + RejectAll = 1, +} + +#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] +pub struct FlexCanFilter { + pub filter_id: u8, + pub id: u32, + pub ide: FlexCanIde, + pub remote: FlexCanIde +} + diff --git a/imxrt-hal/src/can/frame.rs b/imxrt-hal/src/can/frame.rs new file mode 100644 index 00000000..1c3ebbc3 --- /dev/null +++ b/imxrt-hal/src/can/frame.rs @@ -0,0 +1,451 @@ +#[cfg(test)] +mod tests; + +use core::convert::TryFrom; +use core::ops::{Deref, DerefMut}; + +use super::id::{ExtendedId, Id, StandardId}; + +/// A CAN data or remote frame. +#[derive(Clone, Debug, Eq)] +pub struct Frame { + pub(crate) code: CodeReg, + pub(crate) id: IdReg, + pub(crate) data: Data, +} + +impl Frame { + /// Creates a new data frame. + pub fn new_data(id: impl Into, data: impl Into) -> Self { + let (code, id) = match id.into() { + Id::Standard(id) => (CodeReg::new_standard(), IdReg::new_standard(id)), + Id::Extended(id) => (CodeReg::new_extended(), IdReg::new_extended(id)), + }; + + Self { + code, + id, + data: data.into(), + } + } + + /// Creates a new data frame. + #[inline(always)] + pub fn new_from_raw(code: u32, id: u32, data: impl Into) -> Self { + Self { + code: CodeReg::new(code), + id: IdReg::new(id), + data: data.into(), + } + } + + /// Creates a new remote frame with configurable data length code (DLC). + /// + /// # Panics + /// + /// This function will panic if `dlc` is not inside the valid range `0..=8`. + pub fn new_remote(id: impl Into, dlc: u8) -> Self { + assert!(dlc <= 8); + + let mut frame = Self::new_data(id, []); + // Just extend the data length, even with no data present. The API does not hand out this + // `Data` object. + frame.data.len = dlc; + frame.code = frame.code.with_rtr(true); + frame + } + + /// Returns true if this frame is an extended frame. + #[inline(always)] + pub fn is_extended(&self) -> bool { + self.code.is_extended() + } + + /// Returns true if this frame is a standard frame. + #[inline(always)] + pub fn is_standard(&self) -> bool { + self.code.is_standard() + } + + /// Returns true if this frame is a remote frame. + #[inline(always)] + pub fn is_remote_frame(&self) -> bool { + self.code.rtr() + } + + /// Returns true if this frame is a data frame. + #[inline(always)] + pub fn is_data_frame(&self) -> bool { + !self.is_remote_frame() + } + + /// Returns the frame identifier. + #[inline(always)] + pub fn id(&self) -> Id { + if self.is_extended() { + self.id.to_extended() + } else { + self.id.to_standard() + } + } + + /// Returns the data length code (DLC) which is in the range 0..8. + /// + /// For data frames the DLC value always matches the length of the data. + /// Remote frames do not carry any data, yet the DLC can be greater than 0. + #[inline(always)] + pub fn dlc(&self) -> u8 { + self.data.len() as u8 + } + + #[inline(always)] + pub fn to_tx_once_code(&self) -> u32 { + ((self.dlc() as u32) << CodeReg::DLC_SHIFT) | FlexCanMailboxCSCode::TxOnce.to_code_reg() + } + + /// Returns the frame data (0..8 bytes in length) if this is a data frame. + /// + /// If this is a remote frame, returns `None`. + pub fn data(&self) -> Option<&Data> { + if self.is_data_frame() { + Some(&self.data) + } else { + None + } + } +} + +impl PartialEq for Frame { + fn eq(&self, other: &Self) -> bool { + match (self.data(), other.data()) { + (None, None) => self.id.eq(&other.id), + (Some(a), Some(b)) => self.id.eq(&other.id) && a.eq(b), + (None, Some(_)) | (Some(_), None) => false, + } + } +} + +#[derive(Debug, PartialEq)] +#[repr(u8)] +pub enum FlexCanMailboxCSCode { + RxInactive = 0b0000, + RxEmpty = 0b0100, + RxFull = 0b0010, + RxOverrun = 0b0110, + RxAnswer = 0b1010, + RxBusy = 0b0001, + + TxInactive = 0b1000, + TxAbort = 0b1001, + TxOnce = 0b1100, + TxAnswer = 0b1110, + + Unknown, +} + +impl ::core::convert::TryFrom for FlexCanMailboxCSCode { + type Error = (); + + #[inline(always)] + fn try_from(value: u8) -> Result { + match value { + v if v == FlexCanMailboxCSCode::RxInactive as u8 => { + Ok(FlexCanMailboxCSCode::RxInactive) + } + v if v == FlexCanMailboxCSCode::RxEmpty as u8 => Ok(FlexCanMailboxCSCode::RxEmpty), + v if v == FlexCanMailboxCSCode::RxFull as u8 => Ok(FlexCanMailboxCSCode::RxFull), + v if v == FlexCanMailboxCSCode::RxOverrun as u8 => Ok(FlexCanMailboxCSCode::RxOverrun), + v if v == FlexCanMailboxCSCode::RxAnswer as u8 => Ok(FlexCanMailboxCSCode::RxAnswer), + v if v == FlexCanMailboxCSCode::RxBusy as u8 => Ok(FlexCanMailboxCSCode::RxBusy), + v if v == FlexCanMailboxCSCode::TxInactive as u8 => { + Ok(FlexCanMailboxCSCode::TxInactive) + } + v if v == FlexCanMailboxCSCode::TxAbort as u8 => Ok(FlexCanMailboxCSCode::TxAbort), + v if v == FlexCanMailboxCSCode::TxOnce as u8 => Ok(FlexCanMailboxCSCode::TxOnce), + v if v == FlexCanMailboxCSCode::TxAnswer as u8 => Ok(FlexCanMailboxCSCode::TxAnswer), + _ => Ok(FlexCanMailboxCSCode::Unknown), + } + } +} + +impl FlexCanMailboxCSCode { + #[inline(always)] + pub fn to_code_reg(&self) -> u32 { + (*self as u32) << CodeReg::CODE_SHIFT + } + + #[inline(always)] + pub fn from_code_reg(reg: u32) -> Result { + Self::try_from(((reg & CodeReg::CODE_MASK) >> CodeReg::CODE_SHIFT) as u8) + } + + #[inline(always)] + pub fn is_tx_mailbox(&self) -> bool { + (*self as u8) >> 3 != 0 + } +} + +/// Code Register of a FlexCAN mailbox. +/// +/// Contains info relating to the frame's remote status (RTR), whether +/// the frams is standard os extended (IDE), the length of the data +/// content (DLC), and the timestamp. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CodeReg(u32); + +impl CodeReg { + pub(crate) const CODE_SHIFT: u32 = 24; + pub(crate) const CODE_MASK: u32 = 0b1111_u32 << Self::CODE_SHIFT; + + #[allow(dead_code)] + const SRR_SHIFT: u32 = 22; + #[allow(dead_code)] + const SRR_MASK: u32 = 0b1_u32 << Self::SRR_SHIFT; + + const IDE_SHIFT: u32 = 21; + const IDE_MASK: u32 = 0b1_u32 << Self::IDE_SHIFT; + + const RTR_SHIFT: u32 = 20; + const RTR_MASK: u32 = 0b1_u32 << Self::RTR_SHIFT; + + const DLC_SHIFT: u32 = 16; + const DLC_MASK: u32 = 0b111_u32 << Self::DLC_SHIFT; + + const TIMESTAMP_SHIFT: u32 = 0; + const TIMESTAMP_MASK: u32 = 0xFFFF_u32 << Self::TIMESTAMP_SHIFT; + + /// Creates a new code reg. + pub fn new(code: u32) -> Self { + Self(code) + } + + /// Creates a new code reg for a standard identifier. + pub fn new_standard() -> Self { + Self::new(0x00) + } + + /// Creates a new code reg for an extended identifier. + pub fn new_extended() -> Self { + Self::new(Self::IDE_MASK) + } + + /// Returns the register value. + #[inline(always)] + pub fn to_code_reg(&self) -> u32 { + self.0 + } + + /// Set the 4 bit code content for a CodeReg + #[inline(always)] + pub fn set_code(&mut self, code: FlexCanMailboxCSCode) -> Self { + Self::new(self.0 & ((code as u32) << Self::CODE_SHIFT)) + } + + /// Get the 4 bit code content for a CodeReg. + /// + /// # Panics + /// + /// This function will panic if a matching [`FlexCanMailboxCSCode`] is not found. + #[inline(always)] + pub fn code(&self) -> FlexCanMailboxCSCode { + FlexCanMailboxCSCode::try_from(((self.0 & Self::CODE_MASK) >> Self::CODE_SHIFT) as u8) + .unwrap() + } + + pub fn timestamp(&self) -> u16 { + ((self.0 & Self::TIMESTAMP_MASK) >> Self::TIMESTAMP_SHIFT) as u16 + } + + pub fn dlc(&self) -> u8 { + ((self.0 & Self::DLC_MASK) >> Self::DLC_SHIFT) as u8 + } + + /// Returns `true` if the code reg is an extended identifier. + #[inline(always)] + fn is_extended(self) -> bool { + self.0 & Self::IDE_MASK != 0 + } + + /// Returns `true` if the code reg is a standard identifier. + #[inline(always)] + fn is_standard(self) -> bool { + !self.is_extended() + } + + /// Sets the remote transmission (RTR) flag. This marks the identifier as + /// being part of a remote frame. + #[must_use = "returns a new IdReg without modifying `self`"] + pub fn with_rtr(self, rtr: bool) -> Self { + if rtr { + Self::new(self.0 | Self::RTR_MASK) + } else { + Self::new(self.0 & !Self::RTR_MASK) + } + } + + /// Returns `true` if the identifer is part of a remote frame (RTR bit set). + #[inline(always)] + pub fn rtr(self) -> bool { + self.0 & Self::RTR_MASK != 0 + } +} + +/// Identifier of a CAN message. +/// +/// Can be either a standard identifier (11bit, Range: 0..0x3FF) or a +/// extendended identifier (29bit , Range: 0..0x1FFFFFFF). +/// +/// The `Ord` trait can be used to determine the frame’s priority this ID +/// belongs to. +/// Lower identifier values have a higher priority. Additionally standard frames +/// have a higher priority than extended frames and data frames have a higher +/// priority than remote frames. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct IdReg(u32); + +impl IdReg { + const STANDARD_SHIFT: u32 = 18; + const EXTENDED_SHIFT: u32 = 0; + + /// Creates a new standard identifier (11bit, Range: 0..0x7FF) + /// + /// Panics for IDs outside the allowed range. + #[inline(always)] + pub fn new(id: u32) -> Self { + Self(id) + } + + /// Returns the register value. + #[inline(always)] + pub fn to_id_reg(&self) -> u32 { + self.0 + } + + /// Creates a new standard identifier (11bit, Range: 0..0x7FF) + /// + /// Panics for IDs outside the allowed range. + #[inline(always)] + pub fn new_standard(id: StandardId) -> Self { + let id = u32::from(id.as_raw()) << Self::STANDARD_SHIFT; + Self::new(id) + } + + /// Creates a new extendended identifier (29bit , Range: 0..0x1FFFFFFF). + /// + /// Panics for IDs outside the allowed range. + #[inline(always)] + pub fn new_extended(id: ExtendedId) -> Self { + let id = u32::from(id.as_raw()) << Self::EXTENDED_SHIFT; + Self::new(id) + } + + #[inline(always)] + pub fn to_standard(&self) -> Id { + Id::Extended(unsafe { ExtendedId::new_unchecked(self.0 >> Self::STANDARD_SHIFT) }) + } + + #[inline(always)] + pub fn to_extended(&self) -> Id { + Id::Standard(unsafe { StandardId::new_unchecked((self.0 >> Self::EXTENDED_SHIFT) as u16) }) + } +} + +/// Payload of a CAN data frame. +/// +/// Contains 0 to 8 Bytes of data. +/// +/// `Data` implements `From<[u8; N]>` for all `N` up to 8, which provides a convenient lossless +/// conversion from fixed-length arrays. +#[derive(Debug, Copy, Clone)] +pub struct Data { + pub(crate) len: u8, + pub(crate) bytes: [u8; 8], +} + +impl Data { + /// Creates a data payload from a raw byte slice. + /// + /// Returns `None` if `data` contains more than 8 Bytes (which is the maximum). + /// + /// `Data` can also be constructed from fixed-length arrays up to length 8 via `From`/`Into`. + pub fn new(data: &[u8]) -> Option { + if data.len() > 8 { + return None; + } + + let mut bytes = [0; 8]; + bytes[..data.len()].copy_from_slice(data); + + Some(Self { + len: data.len() as u8, + bytes, + }) + } + + /// Creates an empty data payload containing 0 bytes. + #[inline(always)] + pub const fn empty() -> Self { + Self { + len: 0, + bytes: [0; 8], + } + } +} + +impl Deref for Data { + type Target = [u8]; + + #[inline(always)] + fn deref(&self) -> &[u8] { + &self.bytes[..usize::from(self.len)] + } +} + +impl DerefMut for Data { + #[inline(always)] + fn deref_mut(&mut self) -> &mut [u8] { + &mut self.bytes[..usize::from(self.len)] + } +} + +impl AsRef<[u8]> for Data { + #[inline(always)] + fn as_ref(&self) -> &[u8] { + self.deref() + } +} + +impl AsMut<[u8]> for Data { + #[inline(always)] + fn as_mut(&mut self) -> &mut [u8] { + self.deref_mut() + } +} + +impl PartialEq for Data { + fn eq(&self, other: &Self) -> bool { + self.as_ref() == other.as_ref() + } +} + +impl Eq for Data {} + +macro_rules! data_from_array { + ( $($len:literal),+ ) => { + $( + impl From<[u8; $len]> for Data { + #[inline(always)] + fn from(arr: [u8; $len]) -> Self { + let mut bytes = [0; 8]; + bytes[..$len].copy_from_slice(&arr); + Self { + len: $len, + bytes, + } + } + } + )+ + }; +} + +data_from_array!(0, 1, 2, 3, 4, 5, 6, 7, 8); diff --git a/imxrt-hal/src/can/frame/tests.rs b/imxrt-hal/src/can/frame/tests.rs new file mode 100644 index 00000000..e8b43d1f --- /dev/null +++ b/imxrt-hal/src/can/frame/tests.rs @@ -0,0 +1,78 @@ +use crate::can::{ + frame::Frame, + id::{ExtendedId, StandardId}, +}; + +#[test] +fn data_greater_remote() { + let id = StandardId::new(0).unwrap(); + + let data_frame = Frame::new_data(id, []); + let remote_frame = Frame::new_remote(id, 0); + assert!(data_frame.is_data_frame()); + assert!(remote_frame.is_remote_frame()); +} + +#[test] +fn lower_ids_win_arbitration() { + let zero = Frame::new_data(StandardId::new(0).unwrap(), []); + let one = Frame::new_data(StandardId::new(1).unwrap(), []); + assert!(zero.is_standard()); + assert!(!zero.is_extended()); + assert!(one.is_standard()); + assert!(!one.is_extended()); + + // Standard IDs have priority over Extended IDs if the Base ID matches. + let ext_one = Frame::new_data( + ExtendedId::new(0b00000000001_000000000000000000).unwrap(), + [], + ); + assert!(!ext_one.is_standard()); + assert!(ext_one.is_extended()); + + // Ext. ID with Base ID 0 has priority over Standard ID 1. + let ext_zero = Frame::new_data( + ExtendedId::new(0b00000000000_100000000000000000).unwrap(), + [], + ); + assert!(!ext_zero.is_standard()); + assert!(ext_zero.is_extended()); +} + +#[test] +fn highest_standard_higher_prio_than_highest_ext() { + let std = Frame::new_data(StandardId::MAX, []); + let ext = Frame::new_data(ExtendedId::MAX, []); + + assert!(std.is_standard()); + assert!(!std.is_extended()); + assert!(!ext.is_standard()); + assert!(ext.is_extended()); +} + +#[test] +fn data_neq_remote() { + let id = StandardId::new(0).unwrap(); + + let data_frame = Frame::new_data(id, []); + let remote_frame = Frame::new_remote(id, 0); + + assert_ne!(data_frame, remote_frame); +} + +#[test] +fn remote_eq_remote_ignores_data() { + let mut remote1 = Frame::new_remote(StandardId::MAX, 7); + let mut remote2 = Frame::new_remote(StandardId::MAX, 7); + + remote1.data.bytes = [0xAA; 8]; + remote2.data.bytes = [0x55; 8]; + + assert_eq!(remote1, remote2); +} + +#[test] +fn max_len() { + Frame::new_data(StandardId::MAX, [0; 8]); + Frame::new_remote(StandardId::MAX, 8); +} diff --git a/imxrt-hal/src/can/id.rs b/imxrt-hal/src/can/id.rs new file mode 100644 index 00000000..3a4c3f5d --- /dev/null +++ b/imxrt-hal/src/can/id.rs @@ -0,0 +1,126 @@ +/// Standard 11-bit CAN Identifier (`0..=0x7FF`). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct StandardId(u16); + +impl StandardId { + /// CAN ID `0`, the highest priority. + pub const ZERO: Self = Self(0); + + /// CAN ID `0x7FF`, the lowest priority. + pub const MAX: Self = Self(0x7FF); + + /// Tries to create a `StandardId` from a raw 16-bit integer. + /// + /// This will return `None` if `raw` is out of range of an 11-bit integer (`> 0x7FF`). + #[inline] + pub const fn new(raw: u16) -> Option { + if raw <= 0x7FF { + Some(Self(raw)) + } else { + None + } + } + + /// Creates a new `StandardId` without checking if it is inside the valid range. + /// + /// # Safety + /// + /// The caller must ensure that `raw` is in the valid range, otherwise the behavior is + /// undefined. + #[inline] + pub const unsafe fn new_unchecked(raw: u16) -> Self { + Self(raw) + } + + /// Returns this CAN Identifier as a raw 16-bit integer. + #[inline] + pub fn as_raw(&self) -> u16 { + self.0 + } +} + +/// Extended 29-bit CAN Identifier (`0..=1FFF_FFFF`). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub struct ExtendedId(u32); + +impl ExtendedId { + /// CAN ID `0`, the highest priority. + pub const ZERO: Self = Self(0); + + /// CAN ID `0x1FFFFFFF`, the lowest priority. + pub const MAX: Self = Self(0x1FFF_FFFF); + + /// Tries to create a `ExtendedId` from a raw 32-bit integer. + /// + /// This will return `None` if `raw` is out of range of an 29-bit integer (`> 0x1FFF_FFFF`). + #[inline] + pub const fn new(raw: u32) -> Option { + if raw <= 0x1FFF_FFFF { + Some(Self(raw)) + } else { + None + } + } + + /// Creates a new `ExtendedId` without checking if it is inside the valid range. + /// + /// # Safety + /// + /// The caller must ensure that `raw` is in the valid range, otherwise the behavior is + /// undefined. + #[inline] + pub const unsafe fn new_unchecked(raw: u32) -> Self { + Self(raw) + } + + /// Returns this CAN Identifier as a raw 32-bit integer. + #[inline] + pub fn as_raw(&self) -> u32 { + self.0 + } + + /// Returns the Base ID part of this extended identifier. + pub fn standard_id(&self) -> StandardId { + // ID-28 to ID-18 + StandardId((self.0 >> 18) as u16) + } +} + +/// A CAN Identifier (standard or extended). +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum Id { + /// Standard 11-bit Identifier (`0..=0x7FF`). + Standard(StandardId), + + /// Extended 29-bit Identifier (`0..=0x1FFF_FFFF`). + Extended(ExtendedId), +} + +impl Default for Id { + fn default() -> Self { + Id::Standard(StandardId::new(0).unwrap()) + } +} + +impl From for Id { + #[inline] + fn from(id: StandardId) -> Self { + Id::Standard(id) + } +} + +impl From for Id { + #[inline] + fn from(id: ExtendedId) -> Self { + Id::Extended(id) + } +} + +impl Id { + pub fn as_raw(&self) -> u32 { + match self { + Self::Standard(id) => id.as_raw() as u32, + Self::Extended(id) => id.as_raw(), + } + } +} diff --git a/imxrt-hal/src/can/mod.rs b/imxrt-hal/src/can/mod.rs new file mode 100644 index 00000000..e5bdcb88 --- /dev/null +++ b/imxrt-hal/src/can/mod.rs @@ -0,0 +1,997 @@ +mod embedded_hal; +pub mod filter; +mod frame; +mod id; + +pub use frame::{CodeReg, Data, FlexCanMailboxCSCode, Frame, IdReg}; +pub use id::{ExtendedId, Id, StandardId}; +use ral::{modify_reg, read_reg, write_reg}; + +use crate::ccm; +use crate::iomuxc::consts::{Unsigned, U1, U2}; +use crate::iomuxc::can; +use crate::ral; + +use core::convert::Infallible; +use core::marker::PhantomData; + +/// Error that indicates that an incoming message has been lost due to buffer overrun. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OverrunError { + _priv: (), +} + +/// Unclocked Can modules +/// +/// The `Unclocked` struct represents the unconfigured Can peripherals. +/// Once clocked, you'll have the ability to build Can peripherals from the +/// compatible processor pins. +pub struct Unclocked { + pub(crate) can1: ral::can::Instance, + pub(crate) can2: ral::can::Instance, +} + +impl Unclocked { + /// Enable clocks to all Can modules, returning a builder for the two Can modules. + pub fn clock( + self, + handle: &mut ccm::Handle, + clock_select: ccm::can::ClockSelect, + divider: ccm::can::PrescalarSelect, + ) -> (Builder, Builder) { + let (ccm, _) = handle.raw(); + // First, disable clocks + ral::modify_reg!( + ral::ccm, + ccm, + CCGR1, + CG0: 0, + CG1: 0, + CG2: 0, + CG3: 0 + ); + + let clk_sel = match clock_select { + ccm::can::ClockSelect::OSC => ral::ccm::CSCMR2::CAN_CLK_SEL::RW::CAN_CLK_SEL_1, + }; + + // Select clock, and commit prescalar + ral::modify_reg!( + ral::ccm, + ccm, + CSCMR2, + CAN_CLK_PODF: ral::ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_1, + CAN_CLK_SEL: clk_sel + ); + + // Enable clocks + ral::modify_reg!( + ral::ccm, + ccm, + CCGR1, + CG0: 0b11, + CG1: 0b11, + CG2: 0b11, + CG3: 0b11 + ); + + let source_clock = ccm::Frequency::from(clock_select) / ccm::Divider::from(divider); + ( + Builder::new(source_clock, self.can1), + Builder::new(source_clock, self.can2), + ) + } +} + +/// A Can builder that can build a Can peripheral +pub struct Builder { + _module: PhantomData, + reg: ral::can::Instance, + source_clock: ccm::Frequency, +} + +impl Builder +where + M: Unsigned, +{ + fn new(source_clock: ccm::Frequency, reg: ral::can::Instance) -> Self { + Builder { + _module: PhantomData, + reg, + source_clock, + } + } + + /// Builds a Can peripheral. The return + /// is a configured FlexCan peripheral running at 24MHz. + pub fn build(self, mut tx: TX, mut rx: RX) -> CAN + where + TX: can::Pin, + RX: can::Pin, + { + crate::iomuxc::can::prepare(&mut tx); + crate::iomuxc::can::prepare(&mut rx); + + CAN::new(self.source_clock, self.reg) + } +} + +/// A Can master +/// +pub struct CAN { + reg: ral::can::Instance, + _module: PhantomData, + source_clock: ccm::Frequency, + _mailbox_reader_index: u8, +} + +#[derive(Debug)] +pub struct MailboxData { + pub frame: Frame, + pub mailbox_number: u8, +} + +impl CAN +where + M: Unsigned, +{ + pub const NUMBER_FIFO_RX_MAILBOXES: u32 = 6; + + fn new(source_clock: ccm::Frequency, reg: ral::can::Instance) -> Self { + let mut can = CAN { + reg, + _module: PhantomData, + source_clock, + _mailbox_reader_index: 0, + }; + can.begin(); + can + } + + pub fn instance(&mut self) -> &mut ral::can::Instance { + &mut self.reg + } + + pub fn print_registers(&self) { + log::info!("MCR: {:X}", ral::read_reg!(ral::can, self.reg, MCR)); + log::info!("CTRL1: {:X}", ral::read_reg!(ral::can, self.reg, CTRL1)); + log::info!("CTRL2: {:X}", ral::read_reg!(ral::can, self.reg, CTRL2)); + log::info!( + "RXMGMASK: {:X}", + ral::read_reg!(ral::can, self.reg, RXMGMASK) + ); + log::info!( + "RXFGMASK: {:X}", + ral::read_reg!(ral::can, self.reg, RXFGMASK) + ); + + let max_fifo_filters = (read_reg!(ral::can, self.reg, CTRL2, RFFN) + 1) * 8; + + for mailbox_number in 0..max_fifo_filters { + let mailbox_idflt_tab_addr = + self.mailbox_number_to_idflt_tab_address(mailbox_number as u8); + let idflt_tab = + unsafe { core::ptr::read_volatile((mailbox_idflt_tab_addr) as *mut u32) }; + log::info!( + "IDFLT_TAB[{}, {:X}]: {:X}", + mailbox_number, + mailbox_idflt_tab_addr, + idflt_tab + ); + } + } + + fn while_frozen R, R>(&mut self, mut act: F) -> R { + let frz_flag_negate = ral::read_reg!(ral::can, self.reg, MCR, FRZACK == FRZACK_0); + self.enter_freeze_mode(); + let res = act(self); + if frz_flag_negate { + self.exit_freeze_mode(); + } + res + } + + pub fn begin(&mut self) { + self.set_ccm_ccg(); + + ral::modify_reg!(ral::can, self.reg, MCR, MDIS: MDIS_0); + + self.enter_freeze_mode(); + + ral::modify_reg!(ral::can, self.reg, CTRL1, LOM: LOM_1); + ral::modify_reg!(ral::can, self.reg, MCR, FRZ: FRZ_1); + while ral::read_reg!(ral::can, self.reg, MCR, LPMACK == LPMACK_1) {} + + self.soft_reset(); + + while ral::read_reg!(ral::can, self.reg, MCR, FRZACK != FRZACK_1) {} + + ral::modify_reg!( + ral::can, + self.reg, + MCR, + SRXDIS: SRXDIS_1, + IRMQ: IRMQ_1, + AEN: AEN_1, + LPRIOEN: LPRIOEN_1, + SLFWAK: SLFWAK_1, + WAKSRC: WAKSRC_1, + WRNEN: WRNEN_1, + WAKMSK: WAKMSK_1 + ); + + ral::modify_reg!(ral::can, self.reg, MCR, |reg| reg & !0x8800); + + ral::modify_reg!( + ral::can, + self.reg, + CTRL2, + RRS: RRS_1, + EACEN: EACEN_1, + MRP: MRP_1 + ); + + self.disable_fifo(); + self.exit_freeze_mode(); + } + + pub fn instance_number(&self) -> usize { + M::USIZE + } + + pub fn is_can1(&self) -> bool { + M::USIZE == 1 + } + + pub fn is_can2(&self) -> bool { + M::USIZE == 2 + } + + pub fn base_address(&self) -> u32 { + let addr: *const ral::can::RegisterBlock = &*self.reg; + addr as u32 + } + + pub fn free(self) -> ral::can::Instance { + self.reg + } + + fn soft_reset(&mut self) { + ral::modify_reg!(ral::can, self.reg, MCR, SOFTRST: SOFTRST_1); + while ral::read_reg!(ral::can, self.reg, MCR, SOFTRST == SOFTRST_1) {} + } + + fn enter_freeze_mode(&mut self) { + ral::modify_reg!(ral::can, self.reg, MCR, FRZ: FRZ_1); + ral::modify_reg!(ral::can, self.reg, MCR, HALT: HALT_1); + while ral::read_reg!(ral::can, self.reg, MCR, FRZACK != FRZACK_1) {} + } + + fn exit_freeze_mode(&mut self) { + ral::modify_reg!(ral::can, self.reg, MCR, HALT: HALT_0); + while ral::read_reg!(ral::can, self.reg, MCR, FRZACK != FRZACK_0) {} + } + + pub fn set_mrp(&mut self, mrp: bool) { + ral::modify_reg!(ral::can, self.reg, CTRL2, MRP: mrp as u32) + } + + pub fn set_rrs(&mut self, rrs: bool) { + ral::modify_reg!(ral::can, self.reg, CTRL2, RRS: rrs as u32) + } + + fn set_ccm_ccg(&mut self) { + match self.instance_number() { + 1 => { + unsafe { modify_reg!(ral::ccm, CCM, CCGR0, |reg| reg | 0x3C000) }; + } + 2 => { + unsafe { modify_reg!(ral::ccm, CCM, CCGR0, |reg| reg | 0x3C0000) }; + } + u => { + log::error!("Invalid Can instance (set_ccm_ccg): {:?}", u); + } + } + } + + pub fn get_clock(&self) -> u32 { + self.source_clock.0 + } + + fn result_to_bit_table(&self, result: u8) -> Option<[u32; 3]> { + match result { + 0 => Some([0, 0, 1]), + 1 => Some([1, 0, 1]), + 2 => Some([1, 1, 1]), + 3 => Some([2, 1, 1]), + 4 => Some([2, 2, 1]), + 5 => Some([2, 3, 1]), + 6 => Some([2, 3, 2]), + 7 => Some([2, 4, 2]), + 8 => Some([2, 5, 2]), + 9 => Some([2, 5, 3]), + 10 => Some([2, 6, 3]), + 11 => Some([2, 7, 3]), + 12 => Some([2, 7, 4]), + 13 => Some([3, 7, 4]), + 14 => Some([3, 7, 5]), + 15 => Some([4, 7, 5]), + 16 => Some([4, 7, 6]), + 17 => Some([5, 7, 6]), + 18 => Some([6, 7, 6]), + 19 => Some([6, 7, 7]), + 20 => Some([7, 7, 7]), + _ => None, + } + } + + pub fn set_baud_rate(&mut self, baud: u32) { + let clock_freq = 24_000_000; + + let mut divisor = 0; + let mut best_divisor: u32 = 0; + let mut result: u32 = clock_freq / baud / (divisor + 1); + let mut error: i16 = (baud - (clock_freq / (result * (divisor + 1)))) as i16; + let mut best_error = error; + + self.while_frozen(|this| { + while result > 5 { + divisor += 1; + result = clock_freq / baud / (divisor + 1); + if result <= 25 { + error = (baud - (clock_freq / (result * (divisor + 1)))) as i16; + if error < 0 { + error = -1 * error; + } + if error < best_error { + best_error = error; + best_divisor = divisor; + } + if (error == best_error) && (result > 11) && (result < 19) { + best_error = error; + best_divisor = divisor; + } + } + } + + divisor = best_divisor; + result = clock_freq / baud / (divisor + 1); + + if !(result < 5) || (result > 25) || (best_error > 300) { + result -= 5; + + match this.result_to_bit_table(result as u8) { + Some(t) => { + modify_reg!( + ral::can, + this.reg, + CTRL1, + PROPSEG: t[0], + RJW: 1, + PSEG1: t[1], + PSEG2: t[2], + ERRMSK: ERRMSK_1, + LOM: LOM_0, + PRESDIV: divisor) + } + _ => {} + } + } + }); + } + + pub fn set_max_mailbox(&mut self, last: u8) { + let last = last.clamp(1, 64) - 1; + self.while_frozen(|this| { + let fifo_cleared = this.fifo_enabled(); + this.disable_fifo(); + this.write_iflag(this.read_iflag()); + ral::modify_reg!(ral::can, this.reg, MCR, MAXMB: last as u32); + if fifo_cleared { + this.set_fifo(true); + } + }); + } + + fn get_max_mailbox(&self) -> u8 { + ral::read_reg!(ral::can, self.reg, MCR, MAXMB) as u8 + } + + fn write_iflag(&mut self, value: u64) { + write_reg!(ral::can, self.reg, IFLAG1, value as u32); + write_reg!(ral::can, self.reg, IFLAG2, (value >> 32) as u32); + } + + fn write_iflag_bit(&mut self, mailbox_number: u8) { + if mailbox_number < 32 { + modify_reg!(ral::can, self.reg, IFLAG1, |reg| reg + | 1_u32 << mailbox_number) + } else { + modify_reg!(ral::can, self.reg, IFLAG2, |reg| reg + | 1_u32 << (mailbox_number - 32)) + } + } + + fn write_imask_bit(&mut self, mailbox_number: u8, value: bool) { + if mailbox_number < 32 { + modify_reg!(ral::can, self.reg, IMASK1, |reg| reg + | (value as u32) << mailbox_number) + } else { + modify_reg!(ral::can, self.reg, IMASK2, |reg| reg + | (value as u32) << (mailbox_number - 32)) + } + } + + fn read_iflag(&self) -> u64 { + (ral::read_reg!(ral::can, self.reg, IFLAG2) as u64) << 32 + | ral::read_reg!(ral::can, self.reg, IFLAG1) as u64 + } + + fn read_imask(&self) -> u64 { + (ral::read_reg!(ral::can, self.reg, IMASK2) as u64) << 32 + | ral::read_reg!(ral::can, self.reg, IMASK1) as u64 + } + + fn write_imask(&mut self, value: u64) { + write_reg!(ral::can, self.reg, IMASK1, value as u32); + write_reg!(ral::can, self.reg, IMASK2, (value >> 32) as u32); + } + + pub fn set_fifo(&mut self, enabled: bool) { + self.while_frozen(|this| { + modify_reg!(ral::can, this.reg, MCR, RFEN: RFEN_0); + this.write_imask(0); + + for i in 0..this.get_max_mailbox() { + this.write_mailbox(i, Some(0), Some(0), Some([0x00; 8])); + this.write_mailbox_rximr(i, Some(0x00)); + } + + write_reg!(ral::can, this.reg, RXMGMASK, 0); + write_reg!(ral::can, this.reg, RXFGMASK, 0); + + this.write_iflag(this.read_iflag()); + + let max_mailbox = this.get_max_mailbox(); + if enabled { + modify_reg!(ral::can, this.reg, MCR, RFEN: RFEN_1); + while ral::read_reg!(ral::can, this.reg, MCR, RFEN != RFEN_1) {} + for i in this.mailbox_offset()..max_mailbox { + this.write_mailbox( + i, + Some(FlexCanMailboxCSCode::TxInactive.to_code_reg()), + None, + None, + ); + this.enable_mailbox_interrupt(i, true); + } + } else { + for i in 0..max_mailbox { + if i < max_mailbox / 2 { + let code = FlexCanMailboxCSCode::RxEmpty.to_code_reg() | 0x00400000 | { + if i < max_mailbox / 4 { + 0 + } else { + 0x00200000 + } + }; + this.write_mailbox(i, Some(code), None, None); + let eacen = read_reg!(ral::can, this.reg, CTRL2, EACEN == EACEN_1); + let rximr = 0_32 | { + if eacen { + 1_u32 << 30 + } else { + 0 + } + }; + this.write_mailbox_rximr(i, Some(rximr)); + } else { + // set inactive + this.write_mailbox( + i, + Some(FlexCanMailboxCSCode::TxInactive.to_code_reg()), + Some(0), + Some([0x00; 8]), + ); + this.enable_mailbox_interrupt(i, true); + } + } + } + }) + } + + pub fn enable_fifo(&mut self) { + self.set_fifo(true); + } + + pub fn disable_fifo(&mut self) { + self.set_fifo(false); + } + + pub fn set_fifo_reject_all(&mut self) { + self.set_fifo_filter_mask(filter::FlexCanFlten::RejectAll) + } + + pub fn set_fifo_accept_all(&mut self) { + self.set_fifo_filter_mask(filter::FlexCanFlten::AcceptAll) + } + + fn set_fifo_filter_mask(&mut self, flten: filter::FlexCanFlten) { + if !self.fifo_enabled() { + return; + } + let max_fifo_filters = (read_reg!(ral::can, self.reg, CTRL2, RFFN) + 1) * 8; + self.while_frozen(|this| match flten { + filter::FlexCanFlten::AcceptAll => { + let offset = this.mailbox_offset(); + for i in 0..max_fifo_filters { + this.write_mailbox_idflt_tab(i as u8, Some(0x00)); + if i < offset.clamp(0, 32) as u32 { + this.write_mailbox_rximr(i as u8, Some(0x00)); + } + } + write_reg!(ral::can, this.reg, RXFGMASK, 0x00); + } + filter::FlexCanFlten::RejectAll => match read_reg!(ral::can, this.reg, MCR, IDAM) { + ral::can::MCR::IDAM::RW::IDAM_0 => { + let offset = this.mailbox_offset(); + for i in 0..max_fifo_filters { + this.write_mailbox_idflt_tab(i as u8, Some(0xFFFFFFFF)); + if i < offset.clamp(0, 32) as u32 { + this.write_mailbox_rximr(i as u8, Some(0x3FFFFFFF)); + } + } + write_reg!(ral::can, this.reg, RXFGMASK, 0x3FFFFFFF); + } + ral::can::MCR::IDAM::RW::IDAM_1 => { + let offset = this.mailbox_offset(); + for i in 0..max_fifo_filters { + this.write_mailbox_idflt_tab(i as u8, Some(0xFFFFFFFF)); + if i < offset.clamp(0, 32) as u32 { + this.write_mailbox_rximr(i as u8, Some(0x7FFF7FFF)); + } + } + write_reg!(ral::can, this.reg, RXFGMASK, 0x7FFF7FFF); + } + ral::can::MCR::IDAM::RW::IDAM_2 => { + // not implemented + } + ral::can::MCR::IDAM::RW::IDAM_3 => { + // not implemented + } + _ => {} + }, + }) + } + + pub fn set_fifo_filter( + &mut self, + filter_id: u8, + id: u32, + ide: filter::FlexCanIde, + remote: filter::FlexCanIde, + ) { + if !self.fifo_enabled() { + return; + } + let max_fifo_filters = (read_reg!(ral::can, self.reg, CTRL2, RFFN) + 1) * 8; + if filter_id as u32 >= max_fifo_filters { + return; + } + self.while_frozen(|this| match read_reg!(ral::can, this.reg, MCR, IDAM) { + ral::can::MCR::IDAM::RW::IDAM_0 => { + let mask: u32 = if ide != filter::FlexCanIde::Ext { + ((((id) ^ (id)) ^ 0x7FF) << 19) | 0xC0000001 + } else { + ((((id) ^ (id)) ^ 0x1FFFFFFF) << 1) | 0xC0000001 + }; + let mut filter: u32 = (if ide == filter::FlexCanIde::Ext { 1 } else { 0 } << 30); + filter |= if remote == filter::FlexCanIde::Rtr { + 1 + } else { + 0 + } << 31; + filter |= if ide == filter::FlexCanIde::Ext { + (id & 0x1FFFFFFF) << 1 + } else { + ((id & 0x000007FF) << 18) << 1 + }; + this.write_mailbox_idflt_tab(filter_id, Some(filter)); + let offset = this.mailbox_offset(); + if filter_id < offset.clamp(0, 32) as u8 { + this.write_mailbox_rximr(filter_id, Some(mask)); + } + write_reg!(ral::can, this.reg, RXFGMASK, 0x3FFFFFFF); + } + ral::can::MCR::IDAM::RW::IDAM_1 => { + let mut mask: u32 = if ide != filter::FlexCanIde::Ext { + (((id) ^ (id)) ^ 0x7FF) << 19 + } else { + (((id) ^ (id)) ^ 0x1FFFFFFF) << 16 + } | if remote == filter::FlexCanIde::Rtr { + 1 << 31 + } else { + 0 + }; + mask |= if ide != filter::FlexCanIde::Ext { + (((id) ^ (id)) ^ 0x7FF) << 3 + } else { + (((id) ^ (id)) ^ 0x1FFFFFFF) << 0 + } | if remote == filter::FlexCanIde::Rtr { + 1 << 15 + } else { + 0 + } & 0xFFFF; + mask |= (1 << 30) | (1 << 14); + let filter: u32 = (if ide == filter::FlexCanIde::Ext { 1 } else { 0 } << 30) + | (if ide == filter::FlexCanIde::Ext { 1 } else { 0 } << 14) + | (if remote == filter::FlexCanIde::Rtr { + 1 + } else { + 0 + } << 31) + | (if remote == filter::FlexCanIde::Rtr { + 1 + } else { + 0 + } << 15) + | (if ide == filter::FlexCanIde::Ext { + (id >> (29 - 14)) << 16 + } else { + (id & 0x7FF) << 19 + }) + | (if ide == filter::FlexCanIde::Ext { + (id >> (29 - 14)) << 0 + } else { + (id & 0x7FF) << 3 + }); + this.write_mailbox_idflt_tab(filter_id, Some(filter)); + let offset = this.mailbox_offset(); + if filter_id < offset.clamp(0, 32) as u8 { + this.write_mailbox_rximr(filter_id, Some(mask)); + } + write_reg!(ral::can, this.reg, RXFGMASK, 0x7FFF7FFF); + } + ral::can::MCR::IDAM::RW::IDAM_2 => { + // not implemented + } + ral::can::MCR::IDAM::RW::IDAM_3 => { + // not implemented + } + _ => {} + }) + } + + pub fn set_fifo_filter_2(&mut self, filter: filter::FlexCanFilter) { + self.set_fifo_filter(filter.filter_id, filter.id, filter.ide, filter.remote) + } + + pub fn set_fifo_interrupt(&mut self, enabled: bool) { + /* FIFO must be enabled first */ + if !self.fifo_enabled() { + return; + }; + /* FIFO interrupts already enabled */ + const FLEXCAN_IMASK1_BUF5M: u32 = 0x00000020; + if (ral::read_reg!(ral::can, self.reg, IMASK1, BUFLM) & FLEXCAN_IMASK1_BUF5M) != 0 { + return; + }; + /* disable FIFO interrupt flags */ + modify_reg!(ral::can, self.reg, IMASK1, |reg| reg & !0xFF); + /* enable FIFO interrupt */ + if enabled { + const FLEXCAN_IMASK1_BUF5M: u32 = 0x00000020; + modify_reg!(ral::can, self.reg, IMASK1, BUFLM: FLEXCAN_IMASK1_BUF5M); + } + } + + fn fifo_enabled(&self) -> bool { + ral::read_reg!(ral::can, self.reg, MCR, RFEN == RFEN_1) + } + + fn mailbox_offset(&self) -> u8 { + if self.fifo_enabled() { + let max_mailbox = self.get_max_mailbox() as u32; + let num_rx_fifo_filters = (read_reg!(ral::can, self.reg, CTRL2, RFFN) + 1) * 2; + let remaining_mailboxes = max_mailbox - 6_u32 - num_rx_fifo_filters; + /* return offset MB position after FIFO area */ + if max_mailbox < max_mailbox - remaining_mailboxes { + max_mailbox as u8 + } else { + (max_mailbox - remaining_mailboxes) as u8 + } + } else { + /* return offset 0 since FIFO is disabled */ + 0 + } + } + + #[allow(dead_code)] + fn read_fifo(&self) -> Option<()> { + // if FIFO enabled and interrupt not enabled + if !self.fifo_enabled() { + return None; + }; + // FIFO interrupt enabled, polling blocked + if (ral::read_reg!(ral::can, self.reg, IMASK1) & (0x00000020 as u32)) != 0 { + return None; + } + // message available + if (ral::read_reg!(ral::can, self.reg, IFLAG1) & (0x00000020 as u32)) != 0 { + return None; + } + Some(()) + } + + #[inline(always)] + fn mailbox_number_to_address(&self, mailbox_number: u8) -> u32 { + self.base_address() + 0x80_u32 + (mailbox_number as u32 * 0x10_u32) + } + + #[inline(always)] + fn mailbox_number_to_rximr_address(&self, mailbox_number: u8) -> u32 { + self.base_address() + 0x880_u32 + (mailbox_number as u32 * 0x4_u32) + } + + #[inline(always)] + fn mailbox_number_to_idflt_tab_address(&self, mailbox_number: u8) -> u32 { + self.base_address() + 0xE0_u32 + (mailbox_number as u32 * 0x4_u32) + } + + #[inline(always)] + fn read_mailbox_code(&mut self, mailbox_number: u8) -> u32 { + let mailbox_addr = self.mailbox_number_to_address(mailbox_number); + unsafe { core::ptr::read_volatile(mailbox_addr as *const u32) } + } + + #[inline(always)] + fn read_mailbox(&mut self, mailbox_number: u8) -> Option { + if (self.read_imask() & (1_u64 << mailbox_number)) != 0 { + return None; + } + + let code = self.read_mailbox_code(mailbox_number); + let c = match FlexCanMailboxCSCode::from_code_reg(code) { + Ok(c) => Some(c), + Err(_e) => None, + }; + + let mailbox_addr = self.mailbox_number_to_address(mailbox_number); + + match c { + // return None from a transmit mailbox + Some(c) if c.is_tx_mailbox() => None, + // full or overrun + Some(c) + if (c == FlexCanMailboxCSCode::RxFull) | (c == FlexCanMailboxCSCode::RxOverrun) => + { + let id = + unsafe { core::ptr::read_volatile((mailbox_addr + 0x4_u32) as *const u32) }; + let data0 = + unsafe { core::ptr::read_volatile((mailbox_addr + 0x8_u32) as *const u32) }; + let data1 = + unsafe { core::ptr::read_volatile((mailbox_addr + 0xC_u32) as *const u32) }; + + let mut data: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0]; + for i in 0..4 { + data[3 - i] = (data0 >> (8 * i)) as u8; + } + for i in 0..4 { + data[7 - i] = (data1 >> (8 * i)) as u8; + } + + self.write_mailbox( + mailbox_number, + Some(FlexCanMailboxCSCode::RxEmpty.to_code_reg()), + None, + None, + ); + read_reg!(ral::can, self.reg, TIMER); + self.write_iflag_bit(mailbox_number); + + let frame = Frame::new_from_raw(code, id, data); + + Some(MailboxData { + frame, + mailbox_number, + }) + } + _ => None, + } + } + + /// Write the registers of a mailbox. + #[inline(always)] + fn write_mailbox( + &self, + mailbox_number: u8, + code: Option, + id: Option, + data: Option<[u8; 8]>, + ) { + let mailbox_addr = self.mailbox_number_to_address(mailbox_number); + if let Some(code) = code { + unsafe { core::ptr::write_volatile((mailbox_addr + 0_u32) as *mut u32, code) }; + } + if let Some(id) = id { + unsafe { core::ptr::write_volatile((mailbox_addr + 0x4_u32) as *mut u32, id) }; + } + if let Some(data) = data { + let word0 = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + let word1 = u32::from_be_bytes([data[4], data[5], data[6], data[7]]); + unsafe { core::ptr::write_volatile((mailbox_addr + 0x8_u32) as *mut u32, word0) }; + unsafe { core::ptr::write_volatile((mailbox_addr + 0xC_u32) as *mut u32, word1) }; + } + } + + /// Write data to an available TX Mailbox. + /// + /// This will accept both standard and extended data and remote frames with any ID. + /// + /// In order to transmit a Can frame, the CPU must prepare a Message Buffer for + /// transmission by executing the procedure found here. + /// + /// 1. Check if the respective interruption bit is set and clear it. + /// + /// 2. If the MB is active (transmission pending), write the ABORT code (0b1001) to the + /// CODE field of the Control and Status word to request an abortion of the + /// transmission. Wait for the corresponding IFLAG to be asserted by polling the IFLAG + /// register or by the interrupt request if enabled by the respective IMASK. Then read + /// back the CODE field to check if the transmission was aborted or transmitted (see + /// Transmission Abort Mechanism). If backwards compatibility is desired (MCR[AEN] + /// bit negated), just write the INACTIVE code (0b1000) to the CODE field to inactivate + /// the MB but then the pending frame may be transmitted without notification (see + /// Message Buffer Inactivation). + /// + /// 3. Write the ID word. + /// + /// 4. Write the data bytes. + /// + /// 5. Write the DLC, Control and Code fields of the Control and Status word to activate + /// the MB. + /// + /// Once the MB is activated, it will participate into the arbitration process and eventually be + /// transmitted according to its priority. + #[inline(always)] + fn write_tx_mailbox(&mut self, mailbox_number: u8, frame: &Frame) { + // Check if the respective interruption bit is set and clear it. + self.write_iflag_bit(mailbox_number); + self.write_mailbox( + mailbox_number, + Some(FlexCanMailboxCSCode::TxInactive.to_code_reg()), + None, + None, + ); + self.write_mailbox( + mailbox_number, + None, + Some(frame.id.to_id_reg()), + Some(frame.data.bytes), + ); + self.write_mailbox(mailbox_number, Some(frame.to_tx_once_code()), None, None); + } + + fn write_mailbox_rximr(&self, mailbox_number: u8, rximr: Option) { + let mailbox_rximr_addr = self.mailbox_number_to_rximr_address(mailbox_number); + if let Some(rximr) = rximr { + unsafe { core::ptr::write_volatile((mailbox_rximr_addr) as *mut u32, rximr) }; + } + } + + fn write_mailbox_idflt_tab(&self, mailbox_number: u8, idflt_tab: Option) { + let mailbox_idflt_tab_addr = self.mailbox_number_to_idflt_tab_address(mailbox_number); + if let Some(idflt_tab) = idflt_tab { + unsafe { core::ptr::write_volatile((mailbox_idflt_tab_addr) as *mut u32, idflt_tab) }; + } + } + + fn enable_mailbox_interrupt(&mut self, mailbox_number: u8, enabled: bool) { + /* mailbox not available */ + if mailbox_number < self.mailbox_offset() { + return; + } + if enabled { + /* enable mailbox interrupt */ + self.write_imask_bit(mailbox_number, true); + return; + } else { + match self.read_mailbox(mailbox_number) { + Some(d) => { + if (d.frame.code.to_code_reg() & 0x0F000000) >> 3 != 0 { + /* transmit interrupt keeper */ + self.write_imask_bit(mailbox_number, true); + return; + } + } + _ => {} + } + } + /* disable mailbox interrupt */ + self.write_imask_bit(mailbox_number, false); + return; + } + + pub fn read_mailboxes(&mut self) -> Option<()> { + let mut iflag: u64; + let mut cycle_limit: u8 = 3; + let offset = self.mailbox_offset(); + let max_mailbox = self.get_max_mailbox(); + while self._mailbox_reader_index <= max_mailbox { + iflag = self.read_iflag(); + if iflag != 0 && (self._mailbox_reader_index >= (64 - iflag.leading_zeros() as u8)) { + /* break from MSB's if unset, add 1 to prevent undefined behaviour in clz for 0 check */ + self._mailbox_reader_index = self.mailbox_offset(); + cycle_limit -= 1; + if cycle_limit == 0 { + return None; + } + } + if self.fifo_enabled() { + /* FIFO is enabled, get only remaining RX (if any) */ + if self._mailbox_reader_index < offset { + /* go back to position end of fifo+filter region */ + self._mailbox_reader_index = offset; + } + } + if self._mailbox_reader_index >= max_mailbox { + self._mailbox_reader_index = self.mailbox_offset(); + cycle_limit -= 1; + if cycle_limit == 0 { + return None; + } + } + if (self.read_imask() & (1_u64 << self._mailbox_reader_index)) != 0 { + self._mailbox_reader_index += 1; + continue; /* don't read interrupt enabled mailboxes */ + } + match self.read_mailbox(self._mailbox_reader_index) { + Some(mailbox_data) => { + log::info!("RX Data: {:?}", &mailbox_data,); + } + _ => {} + } + self._mailbox_reader_index += 1; + } + None + } + + #[inline(always)] + pub fn handle_interrupt(&mut self) -> Option { + let imask = self.read_imask(); + let iflag = self.read_iflag(); + + /* if DMA is disabled, ONLY THEN can you handle FIFO in ISR */ + if self.fifo_enabled() & (imask & 0x00000020 != 0) & (iflag & 0x00000020 != 0) { + if let Some(mailbox_data) = self.read_mailbox(0) { + self.write_iflag_bit(5); + if iflag & 0x00000040 != 0 { + self.write_iflag_bit(6); + } + if iflag & 0x00000080 != 0 { + self.write_iflag_bit(7); + } + return Some(mailbox_data); + } + } + + None + } + + #[inline(always)] + pub fn transmit(&mut self, frame: &Frame) -> nb::Result<(), Infallible> { + for i in self.mailbox_offset()..self.get_max_mailbox() { + if let Ok(FlexCanMailboxCSCode::TxInactive) = + FlexCanMailboxCSCode::from_code_reg(self.read_mailbox_code(i)) + { + self.write_tx_mailbox(i, frame); + return Ok(()); + } + } + Ok(()) + } +} + +/// Interface to the Can transmitter part. +pub struct Tx { + _can: PhantomData, +} diff --git a/imxrt1060-hal/src/ccm.rs b/imxrt-hal/src/ccm.rs similarity index 81% rename from imxrt1060-hal/src/ccm.rs rename to imxrt-hal/src/ccm.rs index 00af7f78..593b3d89 100644 --- a/imxrt1060-hal/src/ccm.rs +++ b/imxrt-hal/src/ccm.rs @@ -57,6 +57,10 @@ impl PLL1 { PLL1(()) } + #[cfg(any(feature = "imxrt1011", feature = "imxrt1015"))] + pub const ARM_HZ: u32 = 500_000_000; + + #[cfg(any(feature = "imxrt1064", feature = "imxrt1062", feature = "imxrt1061"))] pub const ARM_HZ: u32 = 600_000_000; /// Set the clock speed for the ARM core. This represents the base processor frequency. @@ -921,6 +925,30 @@ pub mod spi { LPSPI_PODF_6 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_6, /// 0b0111: divide by 8 LPSPI_PODF_7 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_7, + /// 0b1000: divide by 9 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_8 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_8, + /// 0b1001: divide by 10 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_9 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_9, + /// 0b1010: divide by 11 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_10 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_10, + /// 0b1011: divide by 12 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_11 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_11, + /// 0b1100: divide by 13 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_12 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_12, + /// 0b1101: divide by 14 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_13 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_13, + /// 0b1110: divide by 15 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_14 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_14, + /// 0b1111: divide by 16 + #[cfg(features = "imxrt1011")] + LPSPI_PODF_15 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_15, } impl From for Frequency { @@ -937,3 +965,162 @@ pub mod spi { } } } + +/// Timing configurations for FlexCAN peripherals +pub mod can { + use super::{ral::ccm, Divider, Frequency, OSCILLATOR_FREQUENCY}; + + #[derive(Clone, Copy)] + #[non_exhaustive] // Not all variants added + pub enum ClockSelect { + OSC, + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + #[allow(non_camel_case_types)] // Easier mapping if the names are consistent + #[repr(u32)] + pub enum PrescalarSelect { + /// 0b000000: Divide by 1 + DIVIDE_1 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_1, + /// 0b000001: Divide by 2 + DIVIDE_2 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_2, + /// 0b000010: Divide by 3 + DIVIDE_3 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_3, + /// 0b000011: Divide by 4 + DIVIDE_4 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_4, + /// 0b000100: Divide by 5 + DIVIDE_5 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_5, + /// 0b000101: Divide by 6 + DIVIDE_6 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_6, + /// 0b000110: Divide by 7 + DIVIDE_7 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_7, + /// 0b000111: Divide by 8 + DIVIDE_8 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_8, + /// 0b001000: Divide by 9 + DIVIDE_9 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_9, + /// 0b001001: Divide by 10 + DIVIDE_10 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_10, + /// 0b001010: Divide by 11 + DIVIDE_11 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_11, + /// 0b001011: Divide by 12 + DIVIDE_12 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_12, + /// 0b001100: Divide by 13 + DIVIDE_13 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_13, + /// 0b001101: Divide by 14 + DIVIDE_14 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_14, + /// 0b001110: Divide by 15 + DIVIDE_15 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_15, + /// 0b001111: Divide by 16 + DIVIDE_16 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_16, + /// 0b010000: Divide by 17 + DIVIDE_17 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_17, + /// 0b010001: Divide by 18 + DIVIDE_18 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_18, + /// 0b010010: Divide by 19 + DIVIDE_19 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_19, + /// 0b010011: Divide by 20 + DIVIDE_20 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_20, + /// 0b010100: Divide by 21 + DIVIDE_21 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_21, + /// 0b010101: Divide by 22 + DIVIDE_22 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_22, + /// 0b010110: Divide by 23 + DIVIDE_23 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_23, + /// 0b010111: Divide by 24 + DIVIDE_24 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_24, + /// 0b011000: Divide by 25 + DIVIDE_25 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_25, + /// 0b011001: Divide by 26 + DIVIDE_26 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_26, + /// 0b011010: Divide by 27 + DIVIDE_27 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_27, + /// 0b011011: Divide by 28 + DIVIDE_28 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_28, + /// 0b011100: Divide by 29 + DIVIDE_29 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_29, + /// 0b011101: Divide by 30 + DIVIDE_30 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_30, + /// 0b011110: Divide by 31 + DIVIDE_31 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_31, + /// 0b011111: Divide by 32 + DIVIDE_32 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_32, + /// 0b100000: Divide by 33 + DIVIDE_33 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_33, + /// 0b100001: Divide by 34 + DIVIDE_34 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_34, + /// 0b100010: Divide by 35 + DIVIDE_35 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_35, + /// 0b100011: Divide by 36 + DIVIDE_36 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_36, + /// 0b100100: Divide by 37 + DIVIDE_37 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_37, + /// 0b100101: Divide by 38 + DIVIDE_38 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_38, + /// 0b100110: Divide by 39 + DIVIDE_39 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_39, + /// 0b100111: Divide by 40 + DIVIDE_40 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_40, + /// 0b101000: Divide by 41 + DIVIDE_41 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_41, + /// 0b101001: Divide by 42 + DIVIDE_42 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_42, + /// 0b101010: Divide by 43 + DIVIDE_43 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_43, + /// 0b101011: Divide by 44 + DIVIDE_44 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_44, + /// 0b101100: Divide by 45 + DIVIDE_45 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_45, + /// 0b101101: Divide by 46 + DIVIDE_46 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_46, + /// 0b101110: Divide by 47 + DIVIDE_47 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_47, + /// 0b101111: Divide by 48 + DIVIDE_48 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_48, + /// 0b110000: Divide by 49 + DIVIDE_49 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_49, + /// 0b110001: Divide by 50 + DIVIDE_50 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_50, + /// 0b110010: Divide by 51 + DIVIDE_51 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_51, + /// 0b110011: Divide by 52 + DIVIDE_52 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_52, + /// 0b110100: Divide by 53 + DIVIDE_53 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_53, + /// 0b110101: Divide by 54 + DIVIDE_54 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_54, + /// 0b110110: Divide by 55 + DIVIDE_55 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_55, + /// 0b110111: Divide by 56 + DIVIDE_56 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_56, + /// 0b111000: Divide by 57 + DIVIDE_57 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_57, + /// 0b111001: Divide by 58 + DIVIDE_58 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_58, + /// 0b111010: Divide by 59 + DIVIDE_59 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_59, + /// 0b111011: Divide by 60 + DIVIDE_60 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_60, + /// 0b111100: Divide by 61 + DIVIDE_61 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_61, + /// 0b111101: Divide by 62 + DIVIDE_62 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_62, + /// 0b111110: Divide by 63 + DIVIDE_63 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_63, + /// 0b111111: Divide by 64 + DIVIDE_64 = ccm::CSCMR2::CAN_CLK_PODF::RW::DIVIDE_64, + } + + impl From for Frequency { + fn from(clock_select: ClockSelect) -> Self { + match clock_select { + ClockSelect::OSC => OSCILLATOR_FREQUENCY, + } + } + } + + impl From for Divider { + fn from(prescalar_select: PrescalarSelect) -> Self { + Divider((prescalar_select as u32) + 1) + } + } +} \ No newline at end of file diff --git a/imxrt1060-hal/src/ccm/arm_clock.rs b/imxrt-hal/src/ccm/arm_clock.rs similarity index 100% rename from imxrt1060-hal/src/ccm/arm_clock.rs rename to imxrt-hal/src/ccm/arm_clock.rs diff --git a/imxrt-hal/src/dma.rs b/imxrt-hal/src/dma.rs new file mode 100644 index 00000000..25c63321 --- /dev/null +++ b/imxrt-hal/src/dma.rs @@ -0,0 +1,600 @@ +//! Direct Memory Access (DMA) +//! +//! We support +//! +//! - DMA from memory to a peripheral. Transfers may be uni- or bi-directional. +//! See the [`Peripheral`](struct.Peripheral.html) for details. +//! - DMA memory copy, or memory-to-memory transfers. See [`Memcpy`](struct.Memcpy.html) +//! for details. +//! +//! DMA types support either [`Linear`](struct.Linear.html) or [`Circular`](struct.Circular.html) +//! memory buffers. Either may be used as a DMA transfer source or destination. Both are backed +//! by statically-allocated [`Buffer`s](struct.Buffer.html). A user will create a memory buffer, +//! then pass ownership to a DMA type that defines a transfer. When the transfer completes, the +//! DMA type will release ownership back to the user. +//! +//! # Terms +//! +//! - *Source* is a location in memory that provides data. A source may be a buffer +//! of data, or a peripheral register. +//! - *Destination* is a location in memory that will receive data. +//! A destination may be a buffer of data, or a peripheral register. +//! - *Transfer* is an overloaded term, meaning either a DMA transfer, or the movement +//! of data out of software, through a peripheral, to an external device. +//! - *DMA Transfer* is an operation achieved by the DMA controller to move data from a +//! source to a destination. +//! - *Receive* means that we're moving data into software, through a peripheral, from an +//! external device. +//! +//! # Example: Full-Duplex SPI Peripheral +//! +//! In this example, we prepare a SPI peripheral (SPI4) with two DMA +//! channels. One channel will send data; the other will receive data. +//! The example assumes that the user has registered a DMA interrupt +//! handler, since we're enabling an interrupt when the receive completes. +//! +//! ```no_run +//! use imxrt_hal::dma::{Circular, Buffer, Linear, Peripheral, bidirectional_u16}; +//! +//! // Circular buffers have alignment requirements +//! #[repr(align(512))] +//! struct Align(Buffer<[u16; 256]>); +//! +//! // Two buffers that can support maximum receive and transfer sizes of 256 elements +//! static RX_BUFFER: Buffer<[u16; 256]> = Buffer::new([0; 256]); +//! static TX_BUFFER: Align = Align(Buffer::new([0; 256])); +//! +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); +//! +//! // +//! // SPI setup... +//! // +//! +//! let (_, _, _, spi4_builder) = peripherals.spi.clock( +//! &mut peripherals.ccm.handle, +//! imxrt_hal::ccm::spi::ClockSelect::Pll2, +//! imxrt_hal::ccm::spi::PrescalarSelect::LPSPI_PODF_5, +//! ); +//! +//! let mut spi4 = spi4_builder.build( +//! peripherals.iomuxc.b0.p02, +//! peripherals.iomuxc.b0.p01, +//! peripherals.iomuxc.b0.p03, +//! ); +//! +//! spi4.enable_chip_select_0(peripherals.iomuxc.b0.p00); +//! +//! // Set the SPI clock speed, if desired... +//! +//! // +//! // DMA setup +//! // +//! +//! let mut dma_channels = peripherals.dma.clock(&mut peripherals.ccm.handle); +//! +//! // i.MX RT DMA interrupt handlers manage pairs of DMA channels. There's one +//! // interrupt for DMA channel 9 and channel 25. By selecting these two +//! // DMA channels, we can register one interrupt to handle both DMA channel +//! // completion. +//! let tx_channel = dma_channels[9].take().unwrap(); +//! let mut rx_channel = dma_channels[25].take().unwrap(); +//! +//! // We only want to interrupt when the receive completes. When +//! // the receive completes, we know that we're also done transferring +//! // data. +//! rx_channel.set_interrupt_on_completion(true); +//! +//! // The peripheral will transfer and receive u16 elements. +//! // It takes ownership of the SPI object, and the two DMA channels. +//! let mut peripheral = bidirectional_u16( +//! spi4, +//! tx_channel, +//! rx_channel, +//! ); +//! +//! // Create DMA memory adapters over the statically-allocated DMA memory. +//! // These adapters will 'own' the statically-allocated memory. See the +//! // Linear and Circular docs for more information. +//! let mut tx_buffer = Circular::new(&TX_BUFFER.0).unwrap(); +//! let mut rx_buffer = Linear::new(&RX_BUFFER).unwrap(); +//! +//! // Send 6 elements, and expect to receive 6 elements +//! for v in 1..=6 { +//! tx_buffer.push(v); +//! } +//! rx_buffer.set_transfer_len(6); +//! +//! // Start the DMA transfers +//! peripheral.start_receive(rx_buffer).unwrap(); +//! peripheral.start_transfer(tx_buffer).unwrap(); +//! +//! // At this point, the DMA controller is transferring data from +//! // the SPI peripheral, and receiving data from the SPI peripheral. +//! // Received data appears in RX_BUFFER. The DMA controller will trigger +//! // an interrupt for DMA channel 25 when it has transferred 6 u16s. +//! // +//! // Your ISR should clear the interrupt and complete the transfers, +//! // as depicted below: +//! +//! while peripheral.is_receive_interrupt() { +//! peripheral.receive_clear_interrupt(); +//! } +//! +//! let mut rx_buffer = None; +//! if peripheral.is_receive_complete() { +//! // Recover the receive buffer +//! rx_buffer = peripheral.receive_complete(); +//! } +//! +//! let mut tx_buffer = None; +//! if peripheral.is_transfer_complete() { +//! // Recover the transfer buffer +//! tx_buffer = peripheral.transfer_complete(); +//! } +//! ``` +//! +//! # Example: memcpy +//! +//! See the [`Memcpy`](struct.Memcpy.html#example) documentation for an example of DMA-powered memcpy. +//! +//! # Notes on Data Cache +//! +//! If your i.MX RT system is using a data cache (DCache), you're responsible for issuing memory barriers, +//! and flushing any cached buffers, for the DMA controller. More generally, you're responsible for placing +//! your DMA buffers into memory regions that the DMA controller can use. +//! +//! ## TODO +//! +//! - Channel arbitration modes +//! - Channel grouping +//! - Channel priority, and channel priority swapping +//! - Channel chaining + +#![allow(non_snake_case)] // Compatibility with RAL + +mod buffer; +mod element; +mod memcpy; +pub(crate) mod peripheral; +mod register; + +pub use buffer::{Buffer, Circular, CircularError, Drain, Linear, ReadHalf, WriteHalf}; +pub use element::Element; +pub use memcpy::Memcpy; +pub use peripheral::{helpers::*, Peripheral}; + +use crate::{ccm, ral}; +use core::{ + fmt::{self, Debug, Display}, + mem, +}; +pub use register::tcd::BandwidthControl; +use register::{DMARegisters, MultiplexerRegisters, Static, DMA, MULTIPLEXER}; + +/// A DMA channel +/// +/// DMA channels provide one-way transfers of data. They accept a source of data, +/// and a destination of data. They copy data from the source to the destination. +/// When the transfer is complete, a DMA channel signals completion by changing a +/// value in a register, or triggering an interrupt. +/// +/// DMA channels have very little public interface. They're best used when paired with a +/// [`Peripheral`](struct.Peripheral.html) or a [`Memcpy`](struct.Memcpy.html). +pub struct Channel { + /// Our channel number, expected to be between 0 to 31 + index: usize, + /// Reference to the DMA registers + registers: Static, + /// Reference to the DMA multiplexer + multiplexer: Static, +} + +impl Channel { + /// Set the channel's bandwidth control + /// + /// The bandwidth control will be used in any [`Memcpy`](struct.Memcpy.html) or + /// [`Peripheral`](struct.Peripheral.html) DMA transfers. + /// + /// - `None` disables bandwidth control (default setting) + /// - `Some(bwc)` sets the bandwidth control to `bwc` + pub fn set_bandwidth_control(&mut self, bandwidth: Option) { + let raw = BandwidthControl::raw(bandwidth); + let tcd = self.tcd(); + ral::modify_reg!(register::tcd, tcd, CSR, BWC: raw); + } + + /// Returns the DMA channel number + /// + /// Channels are unique and numbered within the half-open range `[0, 32)`. + pub fn channel(&self) -> usize { + self.index + } + + /// Allocates a DMA channel, and sets the initial state for + /// the channel. + fn new(index: usize) -> Self { + let channel = Channel { + index, + registers: DMA, + multiplexer: MULTIPLEXER, + }; + channel.registers.TCD[channel.index].reset(); + channel + } + + /// Returns a handle to this channel's transfer control descriptor + fn tcd(&self) -> ®ister::TransferControlDescriptor { + &self.registers.TCD[self.index] + } + + /// Prepare the source of a transfer; see [`Transfer`](struct.Transfer.html) for details. + /// + /// # Safety + /// + /// Address pointer must be valid for lifetime of the transfer. + unsafe fn set_source_transfer>, E: Element>(&mut self, transfer: T) { + let tcd = self.tcd(); + let transfer = transfer.into(); + ral::write_reg!(register::tcd, tcd, SADDR, transfer.address as u32); + ral::write_reg!(register::tcd, tcd, SOFF, transfer.offset); + ral::modify_reg!(register::tcd, tcd, ATTR, SSIZE: E::DATA_TRANSFER_ID, SMOD: transfer.modulo); + ral::write_reg!(register::tcd, tcd, SLAST, transfer.last_address_adjustment); + } + + /// Prepare the destination for a transfer; see [`Transfer`](struct.Transfer.html) for details. + /// + /// # Safety + /// + /// Address pointer must be valid for lifetime of the transfer. + unsafe fn set_destination_transfer>, E: Element>(&mut self, transfer: T) { + let tcd = self.tcd(); + let transfer = transfer.into(); + ral::write_reg!(register::tcd, tcd, DADDR, transfer.address as u32); + ral::write_reg!(register::tcd, tcd, DOFF, transfer.offset); + ral::modify_reg!(register::tcd, tcd, ATTR, DSIZE: E::DATA_TRANSFER_ID, DMOD: transfer.modulo); + ral::write_reg!( + register::tcd, + tcd, + DLAST_SGA, + transfer.last_address_adjustment + ); + } + + /// Set the number of *bytes* to transfer per minor loop + /// + /// Describes how many bytes we should transfer for each DMA service request. + fn set_minor_loop_bytes(&mut self, nbytes: u32) { + let tcd = self.tcd(); + ral::write_reg!(register::tcd, tcd, NBYTES, nbytes); + } + + /// Se the number of elements to move in each minor loop + /// + /// Describes how many elements we should transfer for each DMA service request. + fn set_minor_loop_elements(&mut self, len: usize) { + self.set_minor_loop_bytes((mem::size_of::() * len) as u32); + } + + /// Tells the DMA channel how many transfer iterations to perform + /// + /// A 'transfer iteration' is a read from a source, and a write to a destination, with + /// read and write sizes described by a minor loop. Each iteration requires a DMA + /// service request, either from hardware or from software. + fn set_transfer_iterations(&mut self, iterations: u16) { + let tcd = self.tcd(); + ral::write_reg!(register::tcd, tcd, CITER, iterations); + ral::write_reg!(register::tcd, tcd, BITER, iterations); + } + + /// Enable or disabling triggering from hardware + /// + /// If source is `Some(value)`, we trigger from hardware identified by the source identifier. + /// If `source` is `None`, we disable hardware triggering. + fn set_trigger_from_hardware(&mut self, source: Option) { + let chcfg = &self.multiplexer.chcfg[self.index]; + chcfg.write(0); + if let Some(source) = source { + chcfg.write(MultiplexerRegisters::ENBL | source); + } + } + + /// Set this DMA channel as always on + /// + /// Use `set_always_on()` so that the DMA multiplexer drives the transfer with no + /// throttling. Specifically, an "always-on" transfer will not need explicit re-activiation + /// between major loops. + /// + /// Use an always-on channel for memory-to-memory transfers, so that you don't need explicit + /// software re-activation to maintain the transfer. On the other hand, most peripheral transfers + /// should not use an always-on channel, since the peripheral should control the data flow through + /// explicit activation. + fn set_always_on(&mut self) { + let chcfg = &self.multiplexer.chcfg[self.index]; + chcfg.write(0); + chcfg.write(MultiplexerRegisters::ENBL | MultiplexerRegisters::A_ON); + } + + /// Returns `true` if the DMA channel is receiving a service signal from hardware + fn is_hardware_signaling(&self) -> bool { + self.registers.HRS.read() & (1 << self.index) != 0 + } + + /// Enable or disable the DMA's multiplexer request + /// + /// In this DMA implementation, all peripheral transfers and memcpy requests + /// go through the DMA multiplexer. So, this needs to be set for the multiplexer + /// to service the channel. + fn set_enable(&mut self, enable: bool) { + if enable { + self.registers.SERQ.write(self.index as u8); + } else { + self.registers.CERQ.write(self.index as u8); + } + } + + /// Returns `true` if this DMA channel generated an interrupt + fn is_interrupt(&self) -> bool { + self.registers.INT.read() & (1 << self.index) != 0 + } + + /// Clear the interrupt flag from this DMA channel + fn clear_interrupt(&mut self) { + self.registers.CINT.write(self.index as u8); + } + + /// Enable or disable 'disable on completion' + /// + /// 'Disable on completion' lets the DMA channel automatically clear the request signal + /// when it completes a transfer. + fn set_disable_on_completion(&mut self, dreq: bool) { + let tcd = self.tcd(); + ral::modify_reg!(register::tcd, tcd, CSR, DREQ: dreq as u16); + } + + /// Enable or disable interrupt generation when the transfer completes + /// + /// You're responsible for registering your interrupt handler. + pub fn set_interrupt_on_completion(&mut self, intr: bool) { + let tcd = self.tcd(); + ral::modify_reg!(register::tcd, tcd, CSR, INTMAJOR: intr as u16); + } + + /// Returns `true` if this channel's completion will generate an interrupt + pub fn is_interrupt_on_completion(&self) -> bool { + let tcd = self.tcd(); + ral::read_reg!(register::tcd, tcd, CSR, INTMAJOR == 1) + } + + /// Enable or disable interrupt generation when the transfer is half complete + /// + /// You're responsible for registering your interrupt handler. + pub fn set_interrupt_on_half(&mut self, intr: bool) { + let tcd = self.tcd(); + ral::modify_reg!(register::tcd, tcd, CSR, INTHALF: intr as u16); + } + + /// Returns `true` if this channel will generate an interrupt halfway through transfer + pub fn is_interrupt_on_half(&self) -> bool { + let tcd = self.tcd(); + ral::read_reg!(register::tcd, tcd, CSR, INTHALF == 1) + } + + /// Indicates if the DMA transfer has completed + fn is_complete(&self) -> bool { + let tcd = self.tcd(); + ral::read_reg!(register::tcd, tcd, CSR, DONE == 1) + } + + /// Clears completion indication + fn clear_complete(&mut self) { + self.registers.CDNE.write(self.index as u8); + } + + /// Indicates if the DMA channel is in an error state + fn is_error(&self) -> bool { + self.registers.ERR.read() & (1 << self.index) != 0 + } + + /// Clears the error flag + fn clear_error(&mut self) { + self.registers.CERR.write(self.index as u8); + } + + /// Indicates if this DMA channel is actively transferring data + fn is_active(&self) -> bool { + let tcd = self.tcd(); + ral::read_reg!(register::tcd, tcd, CSR, ACTIVE == 1) + } + + /// Indicates if this DMA channel is enabled + fn is_enabled(&self) -> bool { + self.registers.ERQ.read() & (1 << self.index) != 0 + } + + /// Returns the value from the **global** error status register + /// + /// It may reflect the last channel that produced an error, and that + /// may not be related to this channel. + fn error_status(&self) -> u32 { + self.registers.ES.read() + } + + /// Start a DMA transfer + /// + /// `start()` should be used to request service from the DMA controller. It's + /// necessary for in-memory DMA transfers. Do not use it for hardware-initiated + /// DMA transfers. DMA transfers that involve hardware will rely on the hardware + /// to request DMA service. + /// + /// Flag is automatically cleared by hardware after it's asserted. + fn start(&mut self) { + self.registers.SSRT.write(self.index as u8); + } +} + +/// An error when preparing a transfer +#[derive(Debug)] +#[non_exhaustive] +pub enum Error

{ + /// There is already a scheduled transfer + /// + /// Cancel the transfer and try again. + ScheduledTransfer, + /// The peripheral returned an error + Peripheral(P), + /// Error setting up the DMA transfer + Setup(ErrorStatus), +} + +/// Unclocked, uninitialized DMA channels +/// +/// Use [`clock()`](struct.Unclocked.html#method.clock) to initialize and acquire all DMA channels +/// +/// ```no_run +/// let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); +/// +/// let mut dma_channels = peripherals.dma.clock(&mut peripherals.ccm.handle); +/// let channel_27 = dma_channels[27].take().unwrap(); +/// let channel_0 = dma_channels[0].take().unwrap(); +/// ``` +pub struct Unclocked([Option; 32]); +impl Unclocked { + pub(crate) fn new(dma: ral::dma0::Instance, mux: ral::dmamux::Instance) -> Self { + // Explicitly dropping instances + // + // Users should see these as "taken" by the HAL's DMA module, although they're not + // used in the implementation. + drop(dma); + drop(mux); + + Unclocked([ + 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, + ]) + } + /// Enable the clocks for the DMA peripheral + /// + /// The return is 32 channels, each being initialized as `Some(Channel)`. Users may take channels as needed. + /// The index in the array maps to the DMA channel number. + pub fn clock(mut self, ccm: &mut ccm::Handle) -> [Option; 32] { + let (ccm, _) = ccm.raw(); + ral::modify_reg!(ral::ccm, ccm, CCGR5, CG3: 0x03); + for (idx, channel) in self.0.iter_mut().enumerate() { + *channel = Some(Channel::new(idx)); + } + self.0 + } +} + +/// A wrapper around a DMA error status value +/// +/// The wrapper contains a copy of the DMA controller's +/// error status register at the point of an error. The +/// wrapper implements both `Debug` and `Display`. The +/// type may be printed to understand why there was a +/// DMA error. +#[derive(Clone, Copy)] +pub struct ErrorStatus { + /// The raw error status + es: u32, +} + +impl ErrorStatus { + const fn new(es: u32) -> Self { + ErrorStatus { es } + } +} + +impl Debug for ErrorStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "DMA_ES({:#010X})", self.es) + } +} + +impl Display for ErrorStatus { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, + "DMA_ES: VLD {vld} ECX {ecx} GPE {gpe} CPE {cpe} ERRCHN {errchn} SAE {sae} SOE {soe} DAE {dae} DOE {doe} NCE {nce} SGE {sge} SBE {sbe} DBE {dbe}", + vld = (self.es >> 31) & 0x1, + ecx = (self.es >> 16) & 0x1, + gpe = (self.es >> 15) & 0x1, + cpe = (self.es >> 14) & 0x1, + errchn = (self.es >> 8) & 0x1F, + sae = (self.es >> 7) & 0x1, + soe = (self.es >> 6) & 0x1, + dae = (self.es >> 5) & 0x1, + doe = (self.es >> 4) & 0x1, + nce = (self.es >> 3) & 0x1, + sge = (self.es >> 2) & 0x1, + sbe = (self.es >> 1) & 0x1, + dbe = self.es & 0x1 + ) + } +} + +/// Describes a DMA transfer +/// +/// `Transfer` describes a source or a destination of a DMA transfer. See the member +/// documentation for details. +#[derive(Clone, Copy, Debug)] +struct Transfer { + /// The starting address for the DMA transfer + /// + /// If this describes a source, `address` will be the first + /// address read. If this describes a destination, `address` + /// will be the first address written. + address: *const E, + + /// Offsets to perform for each read / write of a memory address. + /// + /// When defining a transfer for a peripheral source or destination, + /// `offset` should be zero. Otherwise, `offset` should represent the + /// size of the data element, `E`. + /// + /// Negative (backwards) adjustments are permitted, if you'd like to read + /// a buffer backwards or something. + offset: i16, + + /* size: u16, // Not needed; captured in E: Element type */ + /// Defines the strategy for reading / writing linear or circular buffers + /// + /// `modulo` should be zero if this definition defines a transfer from linear + /// memory or a peripheral. `modulo` will be non-zero when defining a transfer + /// from a circular buffer. The non-zero value is the number of high bits to freeze + /// when performing address offsets (see `offset`). Given that we're only supporting + /// power-of-two buffer sizes, `modulo` will be `31 - clz(cap * sizeof(E))`, where `cap` is the + /// total size of the circular buffer, `clz` is "count leading zeros," and `sizeof(E)` is + /// the size of the element, in bytes. + modulo: u16, + + /// Perform any last-address adjustments when we complete the transfer + /// + /// Once we complete moving data from a linear buffer, we should set our pointer back to the + /// initial address. For this case, `last_address_adjustment` should be a negative number that + /// describes how may *bytes* to move backwards from our current address to reach our starting + /// address. Alternatively, it could describe how to move to a completely new address, like + /// a nearby buffer that we're using for a double-buffer. Or, set it to zero, which means "keep + /// your current position." "Keep your current position" is important when working with a + /// peripheral address! + last_address_adjustment: i32, +} + +impl Transfer { + fn hardware(address: *const E) -> Self { + Transfer { + address, + // Don't move the address pointer + offset: 0, + // We're not a circular buffer + modulo: 0, + // Don't move the address pointer + last_address_adjustment: 0, + } + } +} + +// It's OK to send a channel across an execution context. +// They can't be cloned or copied, so there's no chance of +// them being (mutably) shared. +unsafe impl Send for Channel {} diff --git a/imxrt1060-hal/src/dma/buffer.rs b/imxrt-hal/src/dma/buffer.rs similarity index 92% rename from imxrt1060-hal/src/dma/buffer.rs rename to imxrt-hal/src/dma/buffer.rs index d44e1d98..01dd05eb 100644 --- a/imxrt1060-hal/src/dma/buffer.rs +++ b/imxrt-hal/src/dma/buffer.rs @@ -5,7 +5,7 @@ //! - A normal, statically-allocated array, which we call [`Linear`](struct.Linear.html) //! - A circular buffer, called [`Circular`](struct.Circular.html) -use super::{Element, Transfer}; +use super::Element; use as_slice::{AsMutSlice, AsSlice}; use core::{ @@ -21,7 +21,7 @@ use core::{ /// `Buffer`s should store arrays of `u8`, `u16`, or `u32` elements. /// /// ``` -/// use imxrt1060_hal::dma; +/// use imxrt_hal::dma; /// static UART2_DMA_RX: dma::Buffer<[u8; 256]> = dma::Buffer::new([0; 256]); /// ``` /// @@ -47,7 +47,7 @@ impl Buffer { /// May be used to allocate a `static` buffer. /// /// ``` - /// use imxrt1060_hal::dma; + /// use imxrt_hal::dma; /// static UART2_DMA_RX: dma::Buffer<[u8; 256]> = dma::Buffer::new([0; 256]); /// ``` pub const fn new(memory: B) -> Self { @@ -75,7 +75,7 @@ impl Buffer { /// the same buffer. /// /// ``` -/// use imxrt1060_hal::dma; +/// use imxrt_hal::dma; /// /// static DMA1_BUFFER: dma::Buffer<[u8; 256]> = dma::Buffer::new([0; 256]); /// @@ -150,7 +150,7 @@ where /// that there are no other mutable references to this memory. /// /// ``` - /// use imxrt1060_hal::dma; + /// use imxrt_hal::dma; /// /// let mut my_buffer: [u32; 128] = [0; 128]; /// // my_buffer is stack-allocated, so we need to ensure that the lifetime of @@ -270,7 +270,7 @@ unsafe impl Send for Linear {} /// # Example /// /// ``` -/// use imxrt1060_hal::dma; +/// use imxrt_hal::dma; /// /// // A newtype to enforce the required alignment /// #[repr(align(1024))] // 512 * 2 for size of u16 @@ -304,7 +304,7 @@ unsafe impl Send for Linear {} /// circular DMA queue: /// /// ``` -/// # use imxrt1060_hal::dma; +/// # use imxrt_hal::dma; /// #[repr(align(64))] /// struct Align(dma::Buffer<[u16; 30]>); /// static BUFFER: Align = Align(dma::Buffer::new([0; 30])); @@ -316,7 +316,7 @@ unsafe impl Send for Linear {} /// If the alignment is not a multiple of the size, we cannot create a circular DMA queue: /// /// ```no_run -/// # use imxrt1060_hal::dma; +/// # use imxrt_hal::dma; /// #[repr(align(256))] // Should be 1024 to account for u32 size /// struct Align(dma::Buffer<[u32; 256]>); /// static BUFFER: Align = Align(dma::Buffer::new([0; 256])); @@ -411,7 +411,7 @@ impl Circular { /// the memory. Caller must ensure that there are no other mutable references to this memory. /// /// ``` - /// use imxrt1060_hal::dma; + /// use imxrt_hal::dma; /// /// #[repr(align(64))] /// struct Align([u8; 64]); @@ -456,7 +456,7 @@ impl Circular { /// Clears the readable contents from the queue /// /// ``` - /// # use imxrt1060_hal::dma; + /// # use imxrt_hal::dma; /// # #[repr(align(64))] /// # struct Align(dma::Buffer<[u16; 32]>); /// # static BUFFER: Align = Align(dma::Buffer::new([0; 32])); @@ -504,7 +504,7 @@ impl Circular { /// `insert` may *not* insert all the elements into the buffer. /// /// ``` - /// use imxrt1060_hal::dma; + /// use imxrt_hal::dma; /// /// #[repr(align(64))] /// struct Align(dma::Buffer<[u16; 32]>); @@ -558,7 +558,7 @@ impl Circular { /// elements remain in the queue. /// /// ``` - /// # use imxrt1060_hal::dma; + /// # use imxrt_hal::dma; /// # #[repr(align(64))] /// # struct Align(dma::Buffer<[u16; 32]>); /// # static BUFFER: Align = Align(dma::Buffer::new([0; 32])); @@ -612,6 +612,13 @@ impl Circular { fn mark_written(&mut self, size: usize) { self.write = (self.write + size) & (self.cap - 1) } + + /// Computes the modulo value that describes the circular buffer + /// + /// See the DMA `Transfer` struct members for more information. + fn modulo(&self) -> u16 { + 31 - (self.cap * mem::size_of::()).leading_zeros() as u16 + } } // OK to send; pointer assumed to be pointing at static memory. We're @@ -692,13 +699,48 @@ impl<'a, E: Element> ReadHalf<'a, E> { } } +#[derive(Clone, Copy, Debug)] +pub struct Description { + /// Starting address for the transfer to / from the buffer + address: *const E, + /// Number of usable elements (number of `E`s) in the buffer + length: usize, + /// Modulus value for the buffer + /// + /// See the (internal) `Transfer` struct for more details + modulo: u16, +} + +impl Description { + /// Returns the number of usable elemens (number of `E`s) in the buffer + pub fn len(&self) -> usize { + self.length + } +} + +impl From> for super::Transfer { + fn from(desc: Description) -> Self { + Self { + address: desc.address, + // Increment sizeof(E) bytes for every read or write + offset: mem::size_of::() as i16, + modulo: desc.modulo, + // If this is a circular buffer, do not perform any last address changes. Otherwise, + // reset the address back to the beginning + last_address_adjustment: if desc.modulo != 0 { + 0 + } else { + ((desc.length * mem::size_of::()) as i32).wrapping_neg() + }, + } + } +} + /// A buffer that can be used as the source of a DMA transfer pub trait Source: private::Sealed { /// Returns a buffer [`Description`](struct.Description.html) that describes /// this source buffer. - fn source(&self) -> Transfer; - /// Returns the usable number of elements in the source - fn source_len(&self) -> usize; + fn source(&self) -> Description; /// Prepare the buffer to be used as a source of a DMA transfer /// /// Use this to perform any state capture or setup before a transfer starts. @@ -714,9 +756,7 @@ pub trait Source: private::Sealed { pub trait Destination: private::Sealed { /// Returns a buffer [`Description`](struct.Description.html) that describes this /// destination buffer. - fn destination(&self) -> Transfer; - /// Returns the usable number of elements in the destination - fn destination_len(&self) -> usize; + fn destination(&self) -> Description; /// Prepare the buffer to be used as the destination for a DMA transfer /// /// Use this to perform any state capture or setup before a transfer starts. @@ -741,26 +781,24 @@ mod private { // impl Source for Linear { - fn source(&self) -> Transfer { - // Safety: pointer to buffer is always valid; usable is within - // bounds of the buffer. - unsafe { Transfer::buffer_linear(self.ptr, self.usable) } - } - fn source_len(&self) -> usize { - self.usable + fn source(&self) -> Description { + Description { + address: self.ptr, + length: self.usable, + modulo: 0u16, + } } fn prepare_source(&mut self) {} fn complete_source(&mut self) {} } impl Destination for Linear { - fn destination(&self) -> Transfer { - // Safety: pointer to buffer is always valid; usable is within - // bounds of the buffer. - unsafe { Transfer::buffer_linear(self.ptr, self.usable) } - } - fn destination_len(&self) -> usize { - self.usable + fn destination(&self) -> Description { + Description { + address: self.ptr, + length: self.usable, + modulo: 0u16, + } } fn prepare_destination(&mut self) {} fn complete_destination(&mut self) {} @@ -771,15 +809,12 @@ impl Destination for Linear { // impl Source for Circular { - fn source(&self) -> Transfer { - // Safety: Circular API enforces that buffer is aligned, and - // capacity is a power of two. - // - // Unwrap OK: power of two - unsafe { Transfer::buffer_circular(self.read_ptr(), self.cap).unwrap() } - } - fn source_len(&self) -> usize { - self.len() + fn source(&self) -> Description { + Description { + address: self.read_ptr(), + length: self.len(), + modulo: self.modulo(), + } } fn prepare_source(&mut self) { self.reserved = self.len(); @@ -790,15 +825,12 @@ impl Source for Circular { } impl Destination for Circular { - fn destination(&self) -> Transfer { - // Safety: Circular API enforces that buffer is aligned, and - // capacity is a power of two. - // - // Unwrap OK: power of two - unsafe { Transfer::buffer_circular(self.write_ptr(), self.cap).unwrap() } - } - fn destination_len(&self) -> usize { - self.reserved + fn destination(&self) -> Description { + Description { + address: self.write_ptr(), + length: self.reserved, + modulo: self.modulo(), + } } fn prepare_destination(&mut self) {} fn complete_destination(&mut self) { diff --git a/imxrt-hal/src/dma/element.rs b/imxrt-hal/src/dma/element.rs new file mode 100644 index 00000000..4a35d3d7 --- /dev/null +++ b/imxrt-hal/src/dma/element.rs @@ -0,0 +1,36 @@ +//! Trait to generalize acceptable DMA transfer elements + +/// Describes a transferrable DMA element; basically, an unsigned +/// integer of any size. +pub trait Element: Copy + private::Sealed { + /// An identifier describing the data transfer size + /// + /// Part of the TCD API; see documentation on TCD[SSIZE] + /// and TCD[DSIZE] for more information. + const DATA_TRANSFER_ID: u16; +} + +impl Element for u8 { + const DATA_TRANSFER_ID: u16 = 0; +} + +impl Element for u16 { + const DATA_TRANSFER_ID: u16 = 1; +} + +impl Element for u32 { + const DATA_TRANSFER_ID: u16 = 2; +} + +impl Element for u64 { + const DATA_TRANSFER_ID: u16 = 3; +} + +mod private { + pub trait Sealed {} + + impl Sealed for u8 {} + impl Sealed for u16 {} + impl Sealed for u32 {} + impl Sealed for u64 {} +} diff --git a/imxrt1060-hal/src/dma/memcpy.rs b/imxrt-hal/src/dma/memcpy.rs similarity index 89% rename from imxrt1060-hal/src/dma/memcpy.rs rename to imxrt-hal/src/dma/memcpy.rs index e16bee69..4e60ea66 100644 --- a/imxrt1060-hal/src/dma/memcpy.rs +++ b/imxrt-hal/src/dma/memcpy.rs @@ -1,6 +1,6 @@ //! DMA-powered memory copy -use super::{buffer, Channel, Element, Error}; +use super::{buffer, Channel, Element, Error, ErrorStatus}; use core::{ marker::PhantomData, sync::atomic::{compiler_fence, Ordering}, @@ -18,12 +18,12 @@ use core::{ /// # Example /// /// ```no_run -/// use imxrt1060_hal::dma; +/// use imxrt_hal::dma; /// /// static SOURCE: dma::Buffer<[u8; 32]> = dma::Buffer::new([0; 32]); /// static DESTINATION: dma::Buffer<[u8; 64]> = dma::Buffer::new([0; 64]); /// -/// let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +/// let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); /// let mut dma_channels = peripherals.dma.clock(&mut peripherals.ccm.handle); /// let mut dma_channel = dma_channels[7].take().unwrap(); /// dma_channel.set_interrupt_on_completion(false); @@ -82,7 +82,11 @@ where /// /// The number of elements transferred is the minimum size of the two /// buffers. - pub fn transfer(&mut self, mut source: S, mut destination: D) -> Result<(), (S, D, Error)> { + pub fn transfer( + &mut self, + mut source: S, + mut destination: D, + ) -> Result<(), (S, D, Error)> { if self.buffers.is_some() || self.channel.is_enabled() { return Err((source, destination, Error::ScheduledTransfer)); } @@ -91,25 +95,23 @@ where let dst = destination.destination(); unsafe { - self.channel.set_source_transfer(&src); - self.channel.set_destination_transfer(&dst); + self.channel.set_source_transfer(src); + self.channel.set_destination_transfer(dst); } source.prepare_source(); destination.prepare_destination(); - let length = source.source_len().min(destination.destination_len()) as u16; + let length = src.len().min(dst.len()) as u16; self.channel.set_minor_loop_elements::(1); self.channel.set_transfer_iterations(length); compiler_fence(Ordering::Release); - unsafe { - self.channel.enable(); - self.channel.start(); - } + self.channel.set_enable(true); + self.channel.start(); if self.channel.is_error() { - let es = self.channel.error_status(); + let es = ErrorStatus::new(self.channel.error_status()); self.channel.clear_error(); Err((source, destination, Error::Setup(es))) } else { @@ -159,7 +161,7 @@ where destination.complete_destination(); Ok((source, destination)) } else { - self.channel.disable(); + self.channel.set_enable(false); self.channel.clear_complete(); Err((source, destination)) } diff --git a/imxrt1060-hal/src/dma/peripheral.rs b/imxrt-hal/src/dma/peripheral.rs similarity index 100% rename from imxrt1060-hal/src/dma/peripheral.rs rename to imxrt-hal/src/dma/peripheral.rs diff --git a/imxrt-hal/src/dma/register.rs b/imxrt-hal/src/dma/register.rs new file mode 100644 index 00000000..84822e69 --- /dev/null +++ b/imxrt-hal/src/dma/register.rs @@ -0,0 +1,204 @@ +//! A RAL-like module to support DMA register access +//! +//! The RAL has TONS of symbols for DMA. The script that auto-generates +//! the RAL from a SVD file doesn't represent register clusters as an array +//! of structs. The transfer control descriptions, in particularly, could +//! conveniently be represented by 32 TCD structs. Same with the multiplexer +//! registers. Same with the priority registers... +//! +//! This module lets us hit those ideals. At the same time, we can expose an +//! interface that lets us use the RAL macros, where applicable. + +use crate::ral::{RORegister, RWRegister}; +use core::ops::Index; + +/// DMA multiplexer configuration registers +#[repr(C)] +pub(super) struct MultiplexerRegisters { + /// Multiplexer configuration registers, one per channel + pub chcfg: [RWRegister; 32], +} + +pub(super) const MULTIPLEXER: Static = Static(0x400E_C000 as *const _); + +impl MultiplexerRegisters { + pub const ENBL: u32 = 1 << 31; + pub const A_ON: u32 = 1 << 29; +} + +/// DMA registers +#[repr(C)] +pub(super) struct DMARegisters { + /// Control Register + pub CR: RWRegister, + /// Error Status Register + pub ES: RORegister, + _reserved1: [u32; 1], + /// Enable Request Register + pub ERQ: RWRegister, + _reserved2: [u32; 1], + /// Enable Error Interrupt Register + pub EEI: RWRegister, + /// Clear Enable Error Interrupt Register + pub CEEI: RWRegister, + /// Set Enable Error Interrupt Register + pub SEEI: RWRegister, + /// Clear Enable Request Register + pub CERQ: RWRegister, + /// Set Enable Request Register + pub SERQ: RWRegister, + /// Clear DONE Status Bit Register + pub CDNE: RWRegister, + /// Set START Bit Register + pub SSRT: RWRegister, + /// Clear Error Register + pub CERR: RWRegister, + /// Clear Interrupt Request Register + pub CINT: RWRegister, + _reserved3: [u32; 1], + /// Interrupt Request Register + pub INT: RWRegister, + _reserved4: [u32; 1], + /// Error Register + pub ERR: RWRegister, + _reserved5: [u32; 1], + /// Hardware Request Status Register + pub HRS: RORegister, + _reserved6: [u32; 3], + /// Enable Asynchronous Request in Stop Register + pub EARS: RWRegister, + _reserved7: [u32; 46], + /// Channel Priority Registers + pub DCHPRI: ChannelPriorityRegisters, + _reserved8: [u32; 952], + /// Transfer Control Descriptors + pub TCD: [TransferControlDescriptor; 32], +} + +pub(super) const DMA: Static = Static(0x400E_8000 as *const _); + +/// Wrapper for channel priority registers +/// +/// Channel priority registers cannot be accessed with +/// normal channel indexes. This adapter makes it so that +/// we *can* access them with channel indexes by converting +/// the channel number to a reference to the priority +/// register. +#[repr(transparent)] +pub(super) struct ChannelPriorityRegisters([RWRegister; 32]); + +impl Index for ChannelPriorityRegisters { + type Output = RWRegister; + fn index(&self, channel: usize) -> &RWRegister { + // Pattern follows + // + // 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, ... + // + // for all channels < 32. NXP keeping us on our toes. + let idx = 4 * (channel / 4) + (3 - (channel % 4)); + &self.0[idx] + } +} + +/// DMA Transfer Control Descriptor (TCD) +#[repr(C, align(32))] +pub(super) struct TransferControlDescriptor { + pub SADDR: RWRegister, + // Signed numbers for offsets / 'last' members intentional. + // The hardware treats them as signed numbers. + pub SOFF: RWRegister, + pub ATTR: RWRegister, + pub NBYTES: RWRegister, + pub SLAST: RWRegister, + pub DADDR: RWRegister, + pub DOFF: RWRegister, + pub CITER: RWRegister, + pub DLAST_SGA: RWRegister, + pub CSR: RWRegister, + pub BITER: RWRegister, +} + +const _STATIC_ASSERT_TCD_32_BYTES: [u32; 1] = + [0; (32 == core::mem::size_of::()) as usize]; + +impl TransferControlDescriptor { + /// TCDs are uninitialized after reset. Set them to a known, + /// good state here. + pub(super) fn reset(&self) { + self.SADDR.write(0); + self.SOFF.write(0); + self.ATTR.write(0); + self.NBYTES.write(0); + self.SLAST.write(0); + self.DADDR.write(0); + self.DOFF.write(0); + self.CITER.write(0); + self.DLAST_SGA.write(0); + self.CSR.write(0); + self.BITER.write(0); + } +} + +// +// Re-export all TCD register fields in our own namespace. +// It lets us abuse the RAL's macros while using our own +// naming convention. We're only exporting those fields for +// registers that have multiple fields. +// +// Arbitrary selection of TCD_*0. +// + +pub(super) mod tcd { + pub mod ATTR { + pub use crate::ral::dma0::TCD_ATTR0::*; + } + pub mod CSR { + pub use crate::ral::dma0::TCD_CSR0::*; + } + + /// Throttles the amount of bus bandwidth consumed by the eDMA + /// + /// Defines the number of stalls that the DMA engine will insert + /// between most element transfers. + /// + /// Some stalls may not occur to minimize startup latency. See the + /// reference manual for more details. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[repr(u16)] + pub enum BandwidthControl { + /// DMA engine stalls for 4 cycles after each R/W. + Stall4Cycles = CSR::BWC::RW::BWC_2, + /// DMA engine stalls for 8 cycles after each R/W. + Stall8Cycles = CSR::BWC::RW::BWC_3, + } + + impl BandwidthControl { + pub(in crate::dma) fn raw(bwc: Option) -> u16 { + match bwc { + None => CSR::BWC::RW::BWC_0, + Some(bwc) => bwc as u16, + } + } + } +} + +// +// Helper types for static memory +// +// Similar to the RAL's `Instance` type, but more copy. +// + +pub(super) struct Static(*const T); +impl core::ops::Deref for Static { + type Target = T; + fn deref(&self) -> &'static Self::Target { + // Safety: pointer points to static memory (peripheral memory) + unsafe { &*self.0 } + } +} +impl Clone for Static { + fn clone(&self) -> Self { + Static(self.0) + } +} +impl Copy for Static {} diff --git a/imxrt1060-hal/src/gpio.rs b/imxrt-hal/src/gpio.rs similarity index 100% rename from imxrt1060-hal/src/gpio.rs rename to imxrt-hal/src/gpio.rs diff --git a/imxrt1060-hal/src/gpt.rs b/imxrt-hal/src/gpt.rs similarity index 98% rename from imxrt1060-hal/src/gpt.rs rename to imxrt-hal/src/gpt.rs index f4683e4b..4896120c 100644 --- a/imxrt1060-hal/src/gpt.rs +++ b/imxrt-hal/src/gpt.rs @@ -87,33 +87,33 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; +//! use imxrt_hal; //! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); //! //! let (_, ipg_hz) = peripherals.ccm.pll1.set_arm_clock( -//! imxrt1060_hal::ccm::PLL1::ARM_HZ, +//! imxrt_hal::ccm::PLL1::ARM_HZ, //! &mut peripherals.ccm.handle, //! &mut peripherals.dcdc, //! ); //! //! let mut cfg = peripherals.ccm.perclk.configure( //! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::perclk::PODF::DIVIDE_3, -//! imxrt1060_hal::ccm::perclk::CLKSEL::IPG(ipg_hz), +//! imxrt_hal::ccm::perclk::PODF::DIVIDE_3, +//! imxrt_hal::ccm::perclk::CLKSEL::IPG(ipg_hz), //! ); //! //! let mut gpt1 = peripherals.gpt1.clock(&mut cfg); //! //! gpt1.set_output_interrupt_on_compare( -//! imxrt1060_hal::gpt::OutputCompareRegister::Three, +//! imxrt_hal::gpt::OutputCompareRegister::Three, //! true, //! ); //! gpt1.set_wait_mode_enable(true); -//! gpt1.set_mode(imxrt1060_hal::gpt::Mode::FreeRunning); +//! gpt1.set_mode(imxrt_hal::gpt::Mode::FreeRunning); //! //! gpt1.set_output_compare_duration( -//! imxrt1060_hal::gpt::OutputCompareRegister::Three, +//! imxrt_hal::gpt::OutputCompareRegister::Three, //! core::time::Duration::from_micros(765), //! ); //! ``` diff --git a/imxrt1060-hal/src/i2c.rs b/imxrt-hal/src/i2c.rs similarity index 98% rename from imxrt1060-hal/src/i2c.rs rename to imxrt-hal/src/i2c.rs index b363222b..058e0dcd 100644 --- a/imxrt1060-hal/src/i2c.rs +++ b/imxrt-hal/src/i2c.rs @@ -3,16 +3,16 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; -//! use imxrt1060_hal::i2c::ClockSpeed; +//! use imxrt_hal; +//! use imxrt_hal::i2c::ClockSpeed; //! use embedded_hal::blocking::i2c::WriteRead; //! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); //! //! let (_, _, i2c3_builder, _) = peripherals.i2c.clock( //! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::i2c::ClockSelect::OSC, // 24MHz clock... -//! imxrt1060_hal::ccm::i2c::PrescalarSelect::DIVIDE_3, // Divide by 3 +//! imxrt_hal::ccm::i2c::ClockSelect::OSC, // 24MHz clock... +//! imxrt_hal::ccm::i2c::PrescalarSelect::DIVIDE_3, // Divide by 3 //! ); //! //! let mut i2c3 = i2c3_builder.build( diff --git a/imxrt1060-hal/src/lib.rs b/imxrt-hal/src/lib.rs similarity index 94% rename from imxrt1060-hal/src/lib.rs rename to imxrt-hal/src/lib.rs index 71b8ee89..7445956f 100644 --- a/imxrt1060-hal/src/lib.rs +++ b/imxrt-hal/src/lib.rs @@ -15,7 +15,7 @@ pub use imxrt_ral as ral; /// See the `imxrt_iomuxc` crate documentation for more information on this module. /// This module re-exports that crate, along with a chip-specific IOMUXC crate. pub mod iomuxc { - pub use imxrt_iomuxc::imxrt1060::*; + pub use imxrt_iomuxc::imxrt106x::*; pub use imxrt_iomuxc::*; /// Use this function to acquire the IOMUXC pads. It requires that you have an @@ -26,6 +26,7 @@ pub mod iomuxc { } pub mod adc; +pub mod can; pub mod ccm; pub mod dma; pub mod gpio; @@ -51,6 +52,7 @@ pub mod dcdc { pub struct Peripherals { pub adc: adc::Unclocked, pub iomuxc: iomuxc::Pads, + pub can: can::Unclocked, pub ccm: ccm::CCM, pub pit: pit::UnclockedPIT, pub dcdc: dcdc::DCDC, @@ -83,6 +85,10 @@ impl Peripherals { adc2: ral::adc::ADC2::steal(), }, iomuxc: iomuxc::pads(ral::iomuxc::IOMUXC::steal()), + can: can::Unclocked { + can1: ral::can::CAN1::steal(), + can2: ral::can::CAN2::steal(), + }, ccm: ccm::CCM::new(ral::ccm::CCM::steal(), ral::ccm_analog::CCM_ANALOG::steal()), pit: pit::UnclockedPIT::new(ral::pit::PIT::steal()), dcdc: dcdc::DCDC(ral::dcdc::DCDC::steal()), @@ -131,6 +137,10 @@ impl Peripherals { adc2: ral::adc::ADC2::take()?, }, iomuxc: iomuxc::pads(ral::iomuxc::IOMUXC::take()?), + can: can::Unclocked { + can1: ral::can::CAN1::take()?, + can2: ral::can::CAN2::take()?, + }, ccm: ccm::CCM::new(ral::ccm::CCM::take()?, ral::ccm_analog::CCM_ANALOG::take()?), pit: pit::UnclockedPIT::new(ral::pit::PIT::take()?), dcdc: dcdc::DCDC(ral::dcdc::DCDC::take()?), diff --git a/imxrt1060-hal/src/pit.rs b/imxrt-hal/src/pit.rs similarity index 98% rename from imxrt1060-hal/src/pit.rs rename to imxrt-hal/src/pit.rs index b8fc43bf..af317464 100644 --- a/imxrt1060-hal/src/pit.rs +++ b/imxrt-hal/src/pit.rs @@ -3,21 +3,21 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; +//! use imxrt_hal; //! use embedded_hal::timer::CountDown; //! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); //! //! let (_, ipg_hz) = peripherals.ccm.pll1.set_arm_clock( -//! imxrt1060_hal::ccm::PLL1::ARM_HZ, +//! imxrt_hal::ccm::PLL1::ARM_HZ, //! &mut peripherals.ccm.handle, //! &mut peripherals.dcdc, //! ); //! //! let mut cfg = peripherals.ccm.perclk.configure( //! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::perclk::PODF::DIVIDE_3, -//! imxrt1060_hal::ccm::perclk::CLKSEL::IPG(ipg_hz), +//! imxrt_hal::ccm::perclk::PODF::DIVIDE_3, +//! imxrt_hal::ccm::perclk::CLKSEL::IPG(ipg_hz), //! ); //! //! let (_, _, _, mut timer) = peripherals.pit.clock(&mut cfg); diff --git a/imxrt1060-hal/src/pwm.rs b/imxrt-hal/src/pwm.rs similarity index 97% rename from imxrt1060-hal/src/pwm.rs rename to imxrt-hal/src/pwm.rs index 0990e6e5..4aca0039 100644 --- a/imxrt1060-hal/src/pwm.rs +++ b/imxrt-hal/src/pwm.rs @@ -16,16 +16,16 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; -//! use imxrt1060_hal::pwm::Channel; +//! use imxrt_hal; +//! use imxrt_hal::pwm::Channel; //! use embedded_hal::Pwm; //! -//! let mut p = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut p = imxrt_hal::Peripherals::take().unwrap(); //! //! let (_, ipg_hz) = //! p.ccm //! .pll1 -//! .set_arm_clock(imxrt1060_hal::ccm::PLL1::ARM_HZ, &mut p.ccm.handle, &mut p.dcdc); +//! .set_arm_clock(imxrt_hal::ccm::PLL1::ARM_HZ, &mut p.ccm.handle, &mut p.dcdc); //! //! let mut pwm2 = p.pwm2.clock(&mut p.ccm.handle); //! @@ -35,9 +35,9 @@ //! &mut pwm2.handle, //! p.iomuxc.b0.p10, //! p.iomuxc.b0.p11, -//! imxrt1060_hal::pwm::Timing { -//! clock_select: imxrt1060_hal::ccm::pwm::ClockSelect::IPG(ipg_hz), -//! prescalar: imxrt1060_hal::ccm::pwm::Prescalar::PRSC_5, +//! imxrt_hal::pwm::Timing { +//! clock_select: imxrt_hal::ccm::pwm::ClockSelect::IPG(ipg_hz), +//! prescalar: imxrt_hal::ccm::pwm::Prescalar::PRSC_5, //! switching_period: core::time::Duration::from_micros(1000), //! }, //! ) diff --git a/imxrt1060-hal/src/spi.rs b/imxrt-hal/src/spi.rs similarity index 81% rename from imxrt1060-hal/src/spi.rs rename to imxrt-hal/src/spi.rs index f48d55af..310a90c8 100644 --- a/imxrt1060-hal/src/spi.rs +++ b/imxrt-hal/src/spi.rs @@ -16,15 +16,15 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; +//! use imxrt_hal; //! use embedded_hal::blocking::spi::Transfer; //! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); //! //! let (_, _, _, spi4_builder) = peripherals.spi.clock( //! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::spi::ClockSelect::Pll2, -//! imxrt1060_hal::ccm::spi::PrescalarSelect::LPSPI_PODF_5, +//! imxrt_hal::ccm::spi::ClockSelect::Pll2, +//! imxrt_hal::ccm::spi::PrescalarSelect::LPSPI_PODF_5, //! ); //! //! let mut spi4 = spi4_builder.build( @@ -35,7 +35,7 @@ //! //! spi4.enable_chip_select_0(peripherals.iomuxc.b0.p00); //! -//! spi4.set_clock_speed(imxrt1060_hal::spi::ClockSpeed(1_000_000)).unwrap(); +//! spi4.set_clock_speed(imxrt_hal::spi::ClockSpeed(1_000_000)).unwrap(); //! //! let mut buffer: [u8; 3] = [1, 2, 3]; //! spi4.transfer(&mut buffer).unwrap(); @@ -235,9 +235,6 @@ impl SPI where M: Unsigned, { - const DMA_DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; - const DMA_SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; - fn new(source_clock: ccm::Frequency, reg: ral::lpspi::Instance) -> Self { let mut spi = SPI { reg, @@ -354,11 +351,8 @@ where } } - /// # Safety - /// - /// Interior mutability must be atomic #[inline(always)] - unsafe fn set_frame_size(&self) { + fn set_frame_size(&mut self) { ral::modify_reg!(ral::lpspi, self.reg, TCR, FRAMESZ: ((core::mem::size_of::() * 8 - 1) as u32)); } @@ -368,9 +362,7 @@ where let sr = self.check_errors()?; self.clear_status(); - // Safety: user provided mutable reference to SPI, so they are ensuring that - // we can safely change this. - unsafe { self.set_frame_size::() }; + self.set_frame_size::(); if (sr & MBF::mask != 0) || (sr & TDF::mask == 0) { return Err(nb::Error::WouldBlock); @@ -398,44 +390,30 @@ where } /// Perform common actions for enabling a DMA source - /// - /// # Safety - /// - /// Interior mutability must be atomic #[inline(always)] - unsafe fn enable_dma_source(&self) { + fn enable_dma_source(&mut self) { self.set_frame_size::(); ral::modify_reg!(ral::lpspi, self.reg, FCR, RXWATER: 0); // No watermarks; affects DMA signaling ral::modify_reg!(ral::lpspi, self.reg, DER, RDDE: 1); } /// Perform common actions for disabling a DMA source - /// - /// # Safety - /// - /// Performs writes behind an immutable receiver. Interior mutability must be atomic. #[inline(always)] - unsafe fn disable_dma_source(&self) { + fn disable_dma_source(&mut self) { while ral::read_reg!(ral::lpspi, self.reg, DER, RDDE == 1) { ral::modify_reg!(ral::lpspi, self.reg, DER, RDDE: 0); } } - /// # Safety - /// - /// Performs writes behind an immutable receiver. Interior mutability must be atomic. #[inline(always)] - unsafe fn enable_dma_destination(&self) { + fn enable_dma_destination(&mut self) { self.set_frame_size::(); ral::modify_reg!(ral::lpspi, self.reg, FCR, TXWATER: 0); // No watermarks; affects DMA signaling ral::modify_reg!(ral::lpspi, self.reg, DER, TDDE: 1); } - /// # Safety - /// - /// Performs writes behind an immutable receiver. Interior mutability must be atomic. #[inline(always)] - unsafe fn disable_dma_destination(&self) { + fn disable_dma_destination(&mut self) { while ral::read_reg!(ral::lpspi, self.reg, DER, TDDE == 1) { ral::modify_reg!(ral::lpspi, self.reg, DER, TDDE: 0); } @@ -509,98 +487,74 @@ const DMA_RX_REQUEST_LOOKUP: [u32; 4] = [13, 77, 15, 79]; /// See table 4-3 of the iMXRT1060 Reference Manual (Rev 2) const DMA_TX_REQUEST_LOOKUP: [u32; 4] = [14, 78, 16, 80]; -unsafe impl dma::peripheral::Source for SPI +impl dma::peripheral::Source for SPI where M: Unsigned, { - fn source_signal(&self) -> u32 { - Self::DMA_SOURCE_REQUEST_SIGNAL - } + type Error = void::Void; + const SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; fn source(&self) -> *const u8 { &self.reg.RDR as *const _ as *const u8 } - fn enable_source(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.enable_dma_source::(); - }); + fn enable_source(&mut self) -> Result<(), Self::Error> { + self.enable_dma_source::(); + Ok(()) } - fn disable_source(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.disable_dma_source(); - }); + fn disable_source(&mut self) { + self.disable_dma_source(); } } -unsafe impl dma::peripheral::Destination for SPI +impl dma::peripheral::Destination for SPI where M: Unsigned, { - fn destination_signal(&self) -> u32 { - Self::DMA_DESTINATION_REQUEST_SIGNAL - } + type Error = void::Void; + const DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; fn destination(&self) -> *const u8 { &self.reg.TDR as *const _ as *const u8 } - fn enable_destination(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.enable_dma_destination::(); - }); + fn enable_destination(&mut self) -> Result<(), Self::Error> { + self.enable_dma_destination::(); + Ok(()) } - fn disable_destination(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.disable_dma_destination(); - }); + fn disable_destination(&mut self) { + self.disable_dma_destination(); } } -unsafe impl dma::peripheral::Source for SPI +impl dma::peripheral::Source for SPI where M: Unsigned, { - fn source_signal(&self) -> u32 { - Self::DMA_SOURCE_REQUEST_SIGNAL - } + type Error = void::Void; + const SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; fn source(&self) -> *const u16 { &self.reg.RDR as *const _ as *const u16 } - fn enable_source(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.enable_dma_source::(); - }); + fn enable_source(&mut self) -> Result<(), Self::Error> { + self.enable_dma_source::(); + Ok(()) } - fn disable_source(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.disable_dma_source(); - }); + fn disable_source(&mut self) { + self.disable_dma_source(); } } -unsafe impl dma::peripheral::Destination for SPI +impl dma::peripheral::Destination for SPI where M: Unsigned, { - fn destination_signal(&self) -> u32 { - Self::DMA_DESTINATION_REQUEST_SIGNAL - } + type Error = void::Void; + const DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; fn destination(&self) -> *const u16 { &self.reg.TDR as *const _ as *const u16 } - fn enable_destination(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.enable_dma_destination::(); - }); - } - fn disable_destination(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: atomic operation - self.disable_dma_destination(); - }); + fn enable_destination(&mut self) -> Result<(), Self::Error> { + self.enable_dma_destination::(); + Ok(()) + } + fn disable_destination(&mut self) { + self.disable_dma_destination(); } } diff --git a/imxrt1060-hal/src/srtc.rs b/imxrt-hal/src/srtc.rs similarity index 100% rename from imxrt1060-hal/src/srtc.rs rename to imxrt-hal/src/srtc.rs diff --git a/imxrt1060-hal/src/trng.rs b/imxrt-hal/src/trng.rs similarity index 100% rename from imxrt1060-hal/src/trng.rs rename to imxrt-hal/src/trng.rs diff --git a/imxrt1060-hal/src/uart.rs b/imxrt-hal/src/uart.rs similarity index 89% rename from imxrt1060-hal/src/uart.rs rename to imxrt-hal/src/uart.rs index eb1771b3..9de39bea 100644 --- a/imxrt1060-hal/src/uart.rs +++ b/imxrt-hal/src/uart.rs @@ -9,15 +9,15 @@ //! # Example //! //! ```no_run -//! use imxrt1060_hal; +//! use imxrt_hal; //! use embedded_hal::serial::{Read, Write}; //! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); +//! let mut peripherals = imxrt_hal::Peripherals::take().unwrap(); //! //! let uarts = peripherals.uart.clock( //! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::uart::ClockSelect::OSC, -//! imxrt1060_hal::ccm::uart::PrescalarSelect::DIVIDE_1, +//! imxrt_hal::ccm::uart::ClockSelect::OSC, +//! imxrt_hal::ccm::uart::PrescalarSelect::DIVIDE_1, //! ); //! //! let mut uart = uarts @@ -31,7 +31,7 @@ //! //! uart.set_tx_fifo(core::num::NonZeroU8::new(3)); //! uart.set_rx_fifo(true); -//! uart.set_parity(Some(imxrt1060_hal::uart::Parity::Even)); +//! uart.set_parity(Some(imxrt_hal::uart::Parity::Even)); //! uart.set_rx_inversion(true); //! uart.set_tx_inversion(false); //! @@ -302,9 +302,6 @@ impl UART where M: Unsigned, { - const DMA_SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; - const DMA_DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; - fn start( reg: ral::lpuart::Instance, effective_clock: ccm::Frequency, @@ -469,13 +466,7 @@ where Ok(()) } - /// Clear the UART status flags - /// - /// # Safety - /// - /// Performs writes behind an immutable receiver. Caller must ensure - /// that the operation is atomic. - unsafe fn clear_status(&self) { + fn clear_status(&mut self) { ral::modify_reg!( ral::lpuart, self.reg, @@ -610,11 +601,7 @@ where flags.set(ReadErrorFlags::NOISY, data & NOISY::mask != 0); let raw = (data & 0xFF) as u8; - // Safety: called with mutable receiver; caller is ensuring that this - // entire read() operation occurs atomically. - unsafe { - self.clear_status(); - } + self.clear_status(); if flags.is_empty() { Ok(raw) @@ -648,88 +635,77 @@ const DMA_TX_REQUEST_LOOKUP: [u32; 8] = [2, 66, 4, 68, 6, 70, 8, 72]; /// See table 4-3 of the iMXRT1060 Reference Manual (Rev 2) const DMA_RX_REQUEST_LOOKUP: [u32; 8] = [3, 67, 5, 69, 7, 71, 9, 73]; -unsafe impl dma::peripheral::Source for UART +impl dma::peripheral::Source for UART where M: Unsigned, { - fn source_signal(&self) -> u32 { - Self::DMA_SOURCE_REQUEST_SIGNAL - } + type Error = void::Void; + const SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; fn source(&self) -> *const u8 { &self.reg.DATA as *const _ as *const u8 } - fn enable_source(&self) { - cortex_m::interrupt::free(|_| unsafe { - // Safety: mutability is atomic - self.clear_status(); - ral::modify_reg!(ral::lpuart, self.reg, BAUD, RDMAE: 1); - }); + fn enable_source(&mut self) -> Result<(), Self::Error> { + self.clear_status(); + ral::modify_reg!(ral::lpuart, self.reg, BAUD, RDMAE: 1); + Ok(()) } - fn disable_source(&self) { - cortex_m::interrupt::free(|_| { - while ral::read_reg!(ral::lpuart, self.reg, BAUD, RDMAE == 1) { - ral::modify_reg!(ral::lpuart, self.reg, BAUD, RDMAE: 0); - } - }); + fn disable_source(&mut self) { + while ral::read_reg!(ral::lpuart, self.reg, BAUD, RDMAE == 1) { + ral::modify_reg!(ral::lpuart, self.reg, BAUD, RDMAE: 0); + } } } -unsafe impl dma::peripheral::Source for Rx +impl dma::peripheral::Source for Rx where M: Unsigned, { - fn source_signal(&self) -> u32 { - UART::::DMA_SOURCE_REQUEST_SIGNAL - } + type Error = void::Void; + const SOURCE_REQUEST_SIGNAL: u32 = DMA_RX_REQUEST_LOOKUP[M::USIZE - 1]; fn source(&self) -> *const u8 { self.0.source() } - fn enable_source(&self) { + fn enable_source(&mut self) -> Result<(), Self::Error> { self.0.enable_source() } - fn disable_source(&self) { + fn disable_source(&mut self) { self.0.disable_source() } } -unsafe impl dma::peripheral::Destination for UART +impl dma::peripheral::Destination for UART where M: Unsigned, { - fn destination_signal(&self) -> u32 { - Self::DMA_DESTINATION_REQUEST_SIGNAL - } + type Error = void::Void; + const DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; fn destination(&self) -> *const u8 { &self.reg.DATA as *const _ as *const u8 } - fn enable_destination(&self) { - cortex_m::interrupt::free(|_| { - ral::modify_reg!(ral::lpuart, self.reg, BAUD, TDMAE: 1); - }); + fn enable_destination(&mut self) -> Result<(), Self::Error> { + ral::modify_reg!(ral::lpuart, self.reg, BAUD, TDMAE: 1); + Ok(()) } - fn disable_destination(&self) { - cortex_m::interrupt::free(|_| { - while ral::read_reg!(ral::lpuart, self.reg, BAUD, TDMAE == 1) { - ral::modify_reg!(ral::lpuart, self.reg, BAUD, TDMAE: 0); - } - }); + fn disable_destination(&mut self) { + while ral::read_reg!(ral::lpuart, self.reg, BAUD, TDMAE == 1) { + ral::modify_reg!(ral::lpuart, self.reg, BAUD, TDMAE: 0); + } } } -unsafe impl dma::peripheral::Destination for Tx +impl dma::peripheral::Destination for Tx where M: Unsigned, { - fn destination_signal(&self) -> u32 { - UART::::DMA_DESTINATION_REQUEST_SIGNAL - } + type Error = void::Void; + const DESTINATION_REQUEST_SIGNAL: u32 = DMA_TX_REQUEST_LOOKUP[M::USIZE - 1]; fn destination(&self) -> *const u8 { self.0.destination() } - fn enable_destination(&self) { + fn enable_destination(&mut self) -> Result<(), Self::Error> { self.0.enable_destination() } - fn disable_destination(&self) { + fn disable_destination(&mut self) { self.0.disable_destination() } } diff --git a/imxrt1060-hal/Cargo.toml b/imxrt1060-hal/Cargo.toml deleted file mode 100644 index e26aa621..00000000 --- a/imxrt1060-hal/Cargo.toml +++ /dev/null @@ -1,58 +0,0 @@ -[package] -name = "imxrt1060-hal" -authors = ["Tom Burdick ", "Ian McIntyre "] -description = """ -Hardware abstraction layer for NXP i.MX RT 1060 microcontrollers, including - -- i.MX RT 1061 -- i.MX RT 1062 -""" -repository = "https://github.com/imxrt-rs/imxrt-rs" -readme = "README.md" -keywords = ["imxrt", "nxp", "embedded", "no_std"] -categories = ["embedded", "no-std"] -license = "MIT/Apache-2.0" -edition = "2018" -version = "0.5.0-alpha" - -[dependencies] -as-slice = "0.1.3" -cortex-m = { version = "0.6" } -bitflags = "1.2.1" -nb = "0.1.2" -void = { version = "1.0.2", default-features = false } -log = "0.4.8" -rand_core = { version = "0.5", default-features = false, optional = true } - -[dependencies.embedded-hal] -version = "0.2.4" -features = ["unproven"] # Allows us to access the new digital pin traits - -[dependencies.imxrt-dma] -version = "0.1" -rev = "a825d22" -git = "https://github.com/imxrt-rs/imxrt-dma" - -[dependencies.imxrt-ral] -version = "0.4.0" -rev = "aae64342e2cb7491707776fd9cc70b100f8d00c9" -git = "https://github.com/imxrt-rs/imxrt-ral" -features = ["imxrt1062"] - -[dependencies.imxrt-iomuxc] -version = "0.2.0" -git = "https://github.com/imxrt-rs/imxrt-iomuxc.git" -rev = "dffa37438b362ad598015db90f8b2d4b6c71b609" -features = ["imxrt1060"] - -[dev-dependencies.cortex-m-rt] -version = "0.6" -features = ["device"] - -[lib] -bench = false - -[features] -rtic = ["imxrt-ral/rtic"] -rt = ["imxrt-ral/rt"] -nosync = ["imxrt-ral/nosync"] diff --git a/imxrt1060-hal/README.md b/imxrt1060-hal/README.md deleted file mode 100644 index 7eb42111..00000000 --- a/imxrt1060-hal/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# imxrt1060-hal - -`imxrt1060-hal` is a Rust hardware abstraction layer that's specific to i.MX -RT 1060 processors. This includes some of the following processor parts: - -- i.MX RT 1061 -- i.MX RT 1062 - -It is the successor to `imxrt-hal`, version 0.4, with `feature = "imxrt1062"`. - -## Features - -The table below describes the optional features supported by `imxrt1060-hal`. - -| Feature | Description | -| -------- | ---------------------------------- | -| `"rt"` | Runtime support with `cortex-m-rt` | -| `"rtic"` | Support for RTIC | diff --git a/imxrt1060-hal/src/dma.rs b/imxrt1060-hal/src/dma.rs deleted file mode 100644 index 4ad641ff..00000000 --- a/imxrt1060-hal/src/dma.rs +++ /dev/null @@ -1,231 +0,0 @@ -//! Direct Memory Access (DMA) -//! -//! We support -//! -//! - DMA from memory to a peripheral. Transfers may be uni- or bi-directional. -//! See the [`Peripheral`](struct.Peripheral.html) for details. -//! - DMA memory copy, or memory-to-memory transfers. See [`Memcpy`](struct.Memcpy.html) -//! for details. -//! -//! DMA types support either [`Linear`](struct.Linear.html) or [`Circular`](struct.Circular.html) -//! memory buffers. Either may be used as a DMA transfer source or destination. Both are backed -//! by statically-allocated [`Buffer`s](struct.Buffer.html). A user will create a memory buffer, -//! then pass ownership to a DMA type that defines a transfer. When the transfer completes, the -//! DMA type will release ownership back to the user. -//! -//! # Terms -//! -//! - *Source* is a location in memory that provides data. A source may be a buffer -//! of data, or a peripheral register. -//! - *Destination* is a location in memory that will receive data. -//! A destination may be a buffer of data, or a peripheral register. -//! - *Transfer* is an overloaded term, meaning either a DMA transfer, or the movement -//! of data out of software, through a peripheral, to an external device. -//! - *DMA Transfer* is an operation achieved by the DMA controller to move data from a -//! source to a destination. -//! - *Receive* means that we're moving data into software, through a peripheral, from an -//! external device. -//! -//! # Example: Full-Duplex SPI Peripheral -//! -//! In this example, we prepare a SPI peripheral (SPI4) with two DMA -//! channels. One channel will send data; the other will receive data. -//! The example assumes that the user has registered a DMA interrupt -//! handler, since we're enabling an interrupt when the receive completes. -//! -//! ```no_run -//! use imxrt1060_hal::dma::{Circular, Buffer, Linear, Peripheral, bidirectional_u16}; -//! -//! // Circular buffers have alignment requirements -//! #[repr(align(512))] -//! struct Align(Buffer<[u16; 256]>); -//! -//! // Two buffers that can support maximum receive and transfer sizes of 256 elements -//! static RX_BUFFER: Buffer<[u16; 256]> = Buffer::new([0; 256]); -//! static TX_BUFFER: Align = Align(Buffer::new([0; 256])); -//! -//! let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); -//! -//! // -//! // SPI setup... -//! // -//! -//! let (_, _, _, spi4_builder) = peripherals.spi.clock( -//! &mut peripherals.ccm.handle, -//! imxrt1060_hal::ccm::spi::ClockSelect::Pll2, -//! imxrt1060_hal::ccm::spi::PrescalarSelect::LPSPI_PODF_5, -//! ); -//! -//! let mut spi4 = spi4_builder.build( -//! peripherals.iomuxc.b0.p02, -//! peripherals.iomuxc.b0.p01, -//! peripherals.iomuxc.b0.p03, -//! ); -//! -//! spi4.enable_chip_select_0(peripherals.iomuxc.b0.p00); -//! -//! // Set the SPI clock speed, if desired... -//! -//! // -//! // DMA setup -//! // -//! -//! let mut dma_channels = peripherals.dma.clock(&mut peripherals.ccm.handle); -//! -//! // i.MX RT DMA interrupt handlers manage pairs of DMA channels. There's one -//! // interrupt for DMA channel 9 and channel 25. By selecting these two -//! // DMA channels, we can register one interrupt to handle both DMA channel -//! // completion. -//! let tx_channel = dma_channels[9].take().unwrap(); -//! let mut rx_channel = dma_channels[25].take().unwrap(); -//! -//! // We only want to interrupt when the receive completes. When -//! // the receive completes, we know that we're also done transferring -//! // data. -//! rx_channel.set_interrupt_on_completion(true); -//! -//! // The peripheral will transfer and receive u16 elements. -//! // It takes ownership of the SPI object, and the two DMA channels. -//! let mut peripheral = bidirectional_u16( -//! spi4, -//! tx_channel, -//! rx_channel, -//! ); -//! -//! // Create DMA memory adapters over the statically-allocated DMA memory. -//! // These adapters will 'own' the statically-allocated memory. See the -//! // Linear and Circular docs for more information. -//! let mut tx_buffer = Circular::new(&TX_BUFFER.0).unwrap(); -//! let mut rx_buffer = Linear::new(&RX_BUFFER).unwrap(); -//! -//! // Send 6 elements, and expect to receive 6 elements -//! for v in 1..=6 { -//! tx_buffer.push(v); -//! } -//! rx_buffer.set_transfer_len(6); -//! -//! // Start the DMA transfers -//! peripheral.start_receive(rx_buffer).unwrap(); -//! peripheral.start_transfer(tx_buffer).unwrap(); -//! -//! // At this point, the DMA controller is transferring data from -//! // the SPI peripheral, and receiving data from the SPI peripheral. -//! // Received data appears in RX_BUFFER. The DMA controller will trigger -//! // an interrupt for DMA channel 25 when it has transferred 6 u16s. -//! // -//! // Your ISR should clear the interrupt and complete the transfers, -//! // as depicted below: -//! -//! while peripheral.is_receive_interrupt() { -//! peripheral.receive_clear_interrupt(); -//! } -//! -//! let mut rx_buffer = None; -//! if peripheral.is_receive_complete() { -//! // Recover the receive buffer -//! rx_buffer = peripheral.receive_complete(); -//! } -//! -//! let mut tx_buffer = None; -//! if peripheral.is_transfer_complete() { -//! // Recover the transfer buffer -//! tx_buffer = peripheral.transfer_complete(); -//! } -//! ``` -//! -//! # Example: memcpy -//! -//! See the [`Memcpy`](struct.Memcpy.html#example) documentation for an example of DMA-powered memcpy. -//! -//! # Notes on Data Cache -//! -//! If your i.MX RT system is using a data cache (DCache), you're responsible for issuing memory barriers, -//! and flushing any cached buffers, for the DMA controller. More generally, you're responsible for placing -//! your DMA buffers into memory regions that the DMA controller can use. -//! -//! ## TODO -//! -//! - Channel arbitration modes -//! - Channel grouping -//! - Channel priority, and channel priority swapping -//! - Channel chaining - -mod buffer; -mod memcpy; -pub(crate) mod peripheral; - -use imxrt_dma::Transfer; -pub use imxrt_dma::{Channel, Element, ErrorStatus}; - -pub use buffer::{Buffer, Circular, CircularError, Drain, Linear, ReadHalf, WriteHalf}; -pub use memcpy::Memcpy; -pub use peripheral::{helpers::*, Peripheral}; - -use crate::{ccm, ral}; - -/// The number of DMA channels -pub const CHANNEL_COUNT: usize = 32; - -/// An error when preparing a transfer -#[derive(Debug)] -#[non_exhaustive] -pub enum Error { - /// There is already a scheduled transfer - /// - /// Cancel the transfer and try again. - ScheduledTransfer, - /// Error setting up the DMA transfer - Setup(ErrorStatus), -} - -/// Helper symbol to support DMA channel initialization -/// -/// We always provide users with an array of 32 channels. But, only the first `CHANNEL_COUNT` -/// channels are initialized. -const DMA_CHANNEL_INIT: [Option; 32] = [ - 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, -]; - -/// Unclocked, uninitialized DMA channels -/// -/// Use [`clock()`](struct.Unclocked.html#method.clock) to initialize and acquire all DMA channels -/// -/// ```no_run -/// let mut peripherals = imxrt1060_hal::Peripherals::take().unwrap(); -/// -/// let mut dma_channels = peripherals.dma.clock(&mut peripherals.ccm.handle); -/// let channel_27 = dma_channels[27].take().unwrap(); -/// let channel_0 = dma_channels[0].take().unwrap(); -/// ``` -pub struct Unclocked([Option; CHANNEL_COUNT]); -impl Unclocked { - pub(crate) fn new(dma: ral::dma0::Instance, mux: ral::dmamux::Instance) -> Self { - // Explicitly dropping instances - // - // Users should see these as "taken" by the HAL's DMA module, although they're not - // used in the implementation. - drop(dma); - drop(mux); - - Unclocked(DMA_CHANNEL_INIT) - } - /// Enable the clocks for the DMA peripheral - /// - /// The return is an array of 32 channels. However, **only the first [`CHANNEL_COUNT`](constant.CHANNEL_COUNT.html) channels - /// are initialized to `Some(channel)`. The rest are `None`.** - /// - /// Users may take channels as needed. The index in the array maps to the DMA channel number. - pub fn clock(mut self, ccm: &mut ccm::Handle) -> [Option; 32] { - let (ccm, _) = ccm.raw(); - ral::modify_reg!(ral::ccm, ccm, CCGR5, CG3: 0x03); - for (idx, channel) in self.0.iter_mut().take(CHANNEL_COUNT).enumerate() { - // Safety: because we have the DMA instance, we assume that we own the DMA - // peripheral. That means we own all the DMA channels. - let mut chan = unsafe { Channel::new(idx) }; - chan.reset(); - *channel = Some(chan); - } - self.0 - } -}