aboutsummaryrefslogtreecommitdiffstats
path: root/usbh
diff options
context:
space:
mode:
authorBrian Cully <bjc@kublai.com>2019-07-25 09:40:31 -0400
committerBrian Cully <bjc@kublai.com>2019-07-25 10:14:46 -0400
commit7966be1419d3eaa088ed83f95282383182585640 (patch)
tree3b7b09eb768d47e327035301f53f3bd23b7596f2 /usbh
parent5b48a5c2f5526f088187fa341f64368994c9f517 (diff)
downloadsamd21-demo-7966be1419d3eaa088ed83f95282383182585640.tar.gz
samd21-demo-7966be1419d3eaa088ed83f95282383182585640.zip
Move USB host stuff to separate crate.
Diffstat (limited to 'usbh')
-rw-r--r--usbh/Cargo.lock269
-rw-r--r--usbh/Cargo.toml15
-rwxr-xr-xusbh/src/lib.rs641
-rw-r--r--usbh/src/pipe.rs500
-rw-r--r--usbh/src/pipe/addr.rs87
-rw-r--r--usbh/src/pipe/ctrl_pipe.rs177
-rw-r--r--usbh/src/pipe/ext_reg.rs156
-rw-r--r--usbh/src/pipe/pck_size.rs360
-rw-r--r--usbh/src/pipe/status_bk.rs170
-rw-r--r--usbh/src/pipe/status_pipe.rs407
-rw-r--r--usbh/src/usbproto.rs331
11 files changed, 3113 insertions, 0 deletions
diff --git a/usbh/Cargo.lock b/usbh/Cargo.lock
new file mode 100644
index 0000000..5b973da
--- /dev/null
+++ b/usbh/Cargo.lock
@@ -0,0 +1,269 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "aligned"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "aligned"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "as-slice"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "atsamd-hal"
+version = "0.5.0"
+dependencies = [
+ "atsamd21e18a 0.4.0",
+ "bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "atsamd21e18a"
+version = "0.4.0"
+dependencies = [
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "bare-metal"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "bitfield"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "cfg-if"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "cortex-m"
+version = "0.5.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cortex-m"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
+ "bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)",
+ "volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "embedded-hal"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
+ "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "log"
+version = "0.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "nb"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "paste"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
+ "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "paste-impl"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)",
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "proc-macro-hack"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "0.4.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "quote"
+version = "0.6.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "rb"
+version = "0.1.0"
+
+[[package]]
+name = "rustc_version"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "semver"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "semver-parser"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "syn"
+version = "0.15.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)",
+ "quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)",
+ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "typenum"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "unicode-xid"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "usbh"
+version = "0.1.0"
+dependencies = [
+ "atsamd-hal 0.5.0",
+ "embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
+ "log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)",
+ "rb 0.1.0",
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "vcell"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "void"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+
+[[package]]
+name = "volatile-register"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+dependencies = [
+ "vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[metadata]
+"checksum aligned 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d39da9b88ae1a81c03c9c082b8db83f1d0e93914126041962af61034ab44c4a5"
+"checksum aligned 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d3a316c7ea8e1e9ece54862c992def5a7ac14de9f5832b69d71760680efeeefa"
+"checksum as-slice 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "293dac66b274fab06f95e7efb05ec439a6b70136081ea522d270bc351ae5bb27"
+"checksum bare-metal 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3caf393d93b2d453e80638d0674597020cef3382ada454faacd43d1a55a735a"
+"checksum bitfield 0.13.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46afbd2983a5d5a7bd740ccb198caf5b82f45c40c09c0eed36052d91cb92e719"
+"checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33"
+"checksum cortex-m 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0b159a1e8306949579de3698c841dba58058197b65c60807194e4fa1e7a554"
+"checksum cortex-m 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f3c18719fdc57db65668bfc977db9a0fa1a41d718c5d9cd4f652c9d4b0e0956a"
+"checksum embedded-hal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ee4908a155094da7723c2d60d617b820061e3b4efcc3d9e293d206a5a76c170b"
+"checksum generic-array 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c68f0274ae0e023facc3c97b2e00f076be70e254bc851d972503b328db79b2ec"
+"checksum log 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c275b6ad54070ac2d665eef9197db647b32239c9d244bfb6f041a766d00da5b3"
+"checksum nb 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b1411551beb3c11dedfb0a90a0fa256b47d28b9ec2cdff34c25a2fa59e45dbdc"
+"checksum paste 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "1f4a4a1c555c6505821f9d58b8779d0f630a6b7e4e1be24ba718610acf01fa79"
+"checksum paste-impl 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "26e796e623b8b257215f27e6c80a5478856cae305f5b59810ff9acdaa34570e6"
+"checksum proc-macro-hack 0.5.8 (registry+https://github.com/rust-lang/crates.io-index)" = "982a35d1194084ba319d65c4a68d24ca28f5fdb5b8bc20899e4eef8641ea5178"
+"checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759"
+"checksum quote 0.6.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1"
+"checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
+"checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"
+"checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
+"checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8"
+"checksum syn 0.15.42 (registry+https://github.com/rust-lang/crates.io-index)" = "eadc09306ca51a40555dd6fc2b415538e9e18bc9f870e47b1a524a79fe2dcf5e"
+"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169"
+"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"
+"checksum vcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "45c297f0afb6928cd08ab1ff9d95e99392595ea25ae1b5ecf822ff8764e57a0d"
+"checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
+"checksum volatile-register 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d67cb4616d99b940db1d6bd28844ff97108b498a6ca850e5b6191a532063286"
diff --git a/usbh/Cargo.toml b/usbh/Cargo.toml
new file mode 100644
index 0000000..327772b
--- /dev/null
+++ b/usbh/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "usbh"
+version = "0.1.0"
+authors = ["Brian Cully <bjc@kublai.com>"]
+edition = "2018"
+
+[dependencies]
+rb = { path = "../rb" }
+atsamd-hal = { path = "../../atsamd/hal" }
+embedded-hal = "~0.2"
+log = "~0.4"
+vcell = "~0.1"
+
+[features]
+default = ["atsamd-hal/samd21e18a"]
diff --git a/usbh/src/lib.rs b/usbh/src/lib.rs
new file mode 100755
index 0000000..4e6b8bf
--- /dev/null
+++ b/usbh/src/lib.rs
@@ -0,0 +1,641 @@
+#![no_std]
+
+mod pipe;
+mod usbproto;
+
+use pipe::{DataBuf, PipeErr, PipeTable, USBPipeType, USBToken};
+use rb::{Reader, RingBuffer, Writer};
+use usbproto::*;
+
+use atsamd_hal::{
+ calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal},
+ clock::{ClockGenId, ClockSource, GenericClockController},
+ gpio::{self, Floating, Input, OpenDrain, Output},
+ target_device::{PM, USB},
+};
+use embedded_hal::digital::v2::OutputPin;
+use log::{info, warn};
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Event {
+ Error,
+ Detached,
+ Attached,
+}
+type Events = RingBuffer<Event>;
+type EventReader = Reader<'static, Event>;
+type EventWriter = Writer<'static, Event>;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum DetachedState {
+ Initialize,
+ WaitForDevice,
+ Illegal,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum AttachedState {
+ WaitForSettle,
+ WaitResetComplete,
+ WaitSOF,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum SteadyState {
+ Configuring,
+ Running,
+ Error,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum TaskState {
+ Detached(DetachedState),
+ Attached(AttachedState),
+ Steady(SteadyState),
+}
+
+const MAX_DEVICES: usize = 16;
+const SETTLE_DELAY: usize = 205; // Delay in sec/1024
+const NAK_LIMIT: usize = 15;
+
+static mut EVENTS: Events = Events::new(Event::Error);
+// FIXME: this is just for testing. The enum needs to be
+// thread-safe if this is the way we're going.
+static mut LATEST_EVENT: Event = Event::Detached;
+
+#[repr(C)]
+#[derive(Debug)]
+struct EPInfo {
+ ep_addr: u32,
+ mak_pkt_size: u32,
+ ep_attribs: u8,
+}
+
+impl EPInfo {
+ fn bm_snd_toggle(&self) -> bool {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1;
+ ((self.ep_attribs >> POS) & MASK) == 1
+ }
+ fn bm_rcv_toggle(&self) -> bool {
+ const POS: u8 = 1;
+ const MASK: u8 = 0x1;
+ ((self.ep_attribs >> POS) & MASK) == 1
+ }
+ fn bm_nak_power(&self) -> u8 {
+ const POS: u8 = 2;
+ const MASK: u8 = 0x3f;
+ (self.ep_attribs >> POS) & MASK
+ }
+}
+
+#[derive(Debug)]
+struct USBDeviceAddress(u32);
+
+impl USBDeviceAddress {
+ fn bm_address(&self) -> u8 {
+ const POS: u8 = 0;
+ const MASK: u32 = 0x7;
+ ((self.0 >> POS) & MASK) as u8
+ }
+ fn bm_parent(&self) -> u8 {
+ const POS: u8 = 3;
+ const MASK: u32 = 0x7;
+ ((self.0 >> POS) & MASK) as u8
+ }
+ fn bm_hub(&self) -> bool {
+ const POS: u8 = 6;
+ const MASK: u32 = 0x1;
+ ((self.0 >> POS) & MASK) == 1
+ }
+}
+
+pub struct USBHost<F>
+where
+ F: Fn() -> usize + 'static,
+{
+ usb: USB,
+
+ events: EventReader,
+ task_state: TaskState,
+ delay: usize,
+
+ // Need chunk of RAM for USB pipes, which gets used with DESCADD
+ // register.
+ pipe_table: PipeTable,
+
+ // need sof 1kHz pad?
+ _sof_pad: gpio::Pa23<gpio::PfG>,
+ _dm_pad: gpio::Pa24<gpio::PfG>,
+ _dp_pad: gpio::Pa25<gpio::PfG>,
+ host_enable_pin: Option<gpio::Pa28<Output<OpenDrain>>>,
+
+ // To get current milliseconds.
+ millis: &'static F,
+}
+
+impl<F> USBHost<F>
+where
+ F: Fn() -> usize + 'static,
+{
+ pub fn new(
+ usb: USB,
+ sof_pin: gpio::Pa23<Input<Floating>>,
+ dm_pin: gpio::Pa24<Input<Floating>>,
+ dp_pin: gpio::Pa25<Input<Floating>>,
+ host_enable_pin: Option<gpio::Pa28<Input<Floating>>>,
+ port: &mut gpio::Port,
+ clocks: &mut GenericClockController,
+ pm: &mut PM,
+ millis: &'static F,
+ ) -> (Self, impl FnMut()) {
+ let (eventr, mut eventw) = unsafe { EVENTS.split() };
+ let mut rc = Self {
+ usb: usb,
+ events: eventr,
+ task_state: TaskState::Detached(DetachedState::Initialize),
+ delay: 0,
+ pipe_table: PipeTable::new(),
+
+ _sof_pad: sof_pin.into_function_g(port),
+ _dm_pad: dm_pin.into_function_g(port),
+ _dp_pad: dp_pin.into_function_g(port),
+ host_enable_pin: None,
+
+ millis: millis,
+ };
+
+ if let Some(he_pin) = host_enable_pin {
+ rc.host_enable_pin = Some(he_pin.into_open_drain_output(port));
+ }
+
+ info!("setting up usb clock");
+ pm.apbbmask.modify(|_, w| w.usb_().set_bit());
+
+ // Set up USB clock from 48MHz source on generic clock 6.
+ clocks.configure_gclk_divider_and_source(ClockGenId::GCLK6, 1, ClockSource::DFLL48M, false);
+ let gclk6 = clocks
+ .get_gclk(ClockGenId::GCLK6)
+ .expect("Could not get clock 6");
+ clocks.usb(&gclk6);
+
+ rc.reset_periph();
+
+ let usbp = &rc.usb as *const _ as usize;
+ (rc, move || handler(usbp, &mut eventw))
+ }
+
+ pub fn reset_periph(&mut self) {
+ info!("resetting usb");
+ // Reset the USB peripheral and wait for sync.
+ self.usb.host().ctrla.write(|w| w.swrst().set_bit());
+ while self.usb.host().syncbusy.read().swrst().bit_is_set() {}
+
+ // Specify host mode.
+ self.usb.host().ctrla.modify(|_, w| w.mode().host());
+
+ // Unsafe due to use of raw bits method.
+ unsafe {
+ self.usb.host().padcal.write(|w| {
+ w.transn().bits(usb_transn_cal());
+ w.transp().bits(usb_transp_cal());
+ w.trim().bits(usb_trim_cal())
+ });
+ }
+
+ // Use normal, which is 0 and apparently means low-and-full capable
+ self.usb.host().ctrlb.modify(|_, w| w.spdconf().normal());
+ // According to docs, 1,2,3 are reserved, but .fs returns 3
+ //self.usb.host().ctrlb.modify(|_, w| w.spdconf().fs());
+
+ self.usb.host().ctrla.modify(|_, w| w.runstdby().set_bit()); // keep usb clock running in standby.
+
+ // Set address of USB SRAM.
+ // Unsafe due to use of raw bits method.
+ unsafe {
+ self.usb
+ .host()
+ .descadd
+ .write(|w| w.bits(&self.pipe_table as *const _ as u32));
+ }
+
+ if let Some(he_pin) = &mut self.host_enable_pin {
+ he_pin.set_high().expect("turning on usb host enable pin");
+ }
+
+ self.usb.host().intenset.write(|w| {
+ w.wakeup().set_bit();
+ w.dconn().set_bit();
+ w.ddisc().set_bit()
+ });
+
+ self.usb.host().ctrla.modify(|_, w| w.enable().set_bit());
+ while self.usb.host().syncbusy.read().enable().bit_is_set() {}
+
+ // Set VBUS OK to allow host operation.
+ self.usb.host().ctrlb.modify(|_, w| w.vbusok().set_bit());
+ info!("...done");
+ }
+
+ pub fn task(&mut self) {
+ static mut LAST_EVENT: Event = Event::Error;
+ unsafe {
+ if LAST_EVENT != LATEST_EVENT {
+ info!("new event: {:?}", LATEST_EVENT);
+ }
+ }
+
+ static mut LAST_TASK_STATE: TaskState = TaskState::Detached(DetachedState::Illegal);
+ self.task_state = match unsafe { LATEST_EVENT } {
+ Event::Error => TaskState::Detached(DetachedState::Illegal),
+ Event::Detached => {
+ if let TaskState::Detached(_) = self.task_state {
+ self.task_state
+ } else {
+ TaskState::Detached(DetachedState::Initialize)
+ }
+ }
+ Event::Attached => {
+ if let TaskState::Detached(_) = self.task_state {
+ self.delay = (self.millis)() + SETTLE_DELAY;
+ TaskState::Attached(AttachedState::WaitForSettle)
+ } else {
+ self.task_state
+ }
+ }
+ };
+
+ static mut LAST_CBITS: u16 = 0;
+ static mut LAST_FLAGS: u16 = 0;
+ let cbits = self.usb.host().ctrlb.read().bits();
+ let bits = self.usb.host().intflag.read().bits();
+ unsafe {
+ if LAST_CBITS != cbits || LAST_FLAGS != bits || LAST_TASK_STATE != self.task_state {
+ info!(
+ "cb: {:x}, f: {:x} changing state {:?} -> {:?}",
+ cbits, bits, LAST_TASK_STATE, self.task_state,
+ );
+ }
+ LAST_CBITS = cbits;
+ LAST_FLAGS = bits;
+ LAST_TASK_STATE = self.task_state
+ };
+
+ if let Some(_event) = self.events.shift() {
+ // info!("Found event: {:?}", event);
+ // self.task_state = match event {
+ // Event::None => TaskState::Detached(DetachedState::Illegal),
+ // Event::Detached => {
+ // if let TaskState::Detached(_) = self.task_state {
+ // self.task_state
+ // } else {
+ // TaskState::Detached(DetachedState::Initialize)
+ // }
+ // }
+ // Event::Attached => {
+ // if let TaskState::Detached(_) = self.task_state {
+ // self.delay = self.millis() + SETTLE_DELAY;
+ // TaskState::Attached(AttachedState::WaitForSettle)
+ // } else {
+ // self.task_state
+ // }
+ // }
+ // };
+ }
+
+ self.poll_devices();
+ self.fsm();
+
+ unsafe {
+ LAST_EVENT = LATEST_EVENT;
+ }
+ }
+
+ fn poll_devices(&mut self) {
+ for _ in 0..MAX_DEVICES {}
+ }
+
+ fn fsm(&mut self) {
+ // respond to events from interrupt.
+ match self.task_state {
+ TaskState::Detached(s) => self.detached_fsm(s),
+ TaskState::Attached(s) => self.attached_fsm(s),
+ TaskState::Steady(s) => self.steady_fsm(s),
+ };
+ }
+
+ fn detached_fsm(&mut self, s: DetachedState) {
+ match s {
+ DetachedState::Initialize => {
+ self.reset_periph();
+ // TODO: Free resources.
+
+ self.task_state = TaskState::Detached(DetachedState::WaitForDevice);
+ }
+
+ // Do nothing state. Just wait for an interrupt to come in
+ // saying we have a device attached.
+ DetachedState::WaitForDevice => {}
+
+ // TODO: should probably reset everything if we end up here somehow.
+ DetachedState::Illegal => {}
+ }
+ }
+
+ fn attached_fsm(&mut self, s: AttachedState) {
+ match s {
+ AttachedState::WaitForSettle => {
+ if (self.millis)() >= self.delay {
+ self.usb.host().ctrlb.modify(|_, w| w.busreset().set_bit());
+ self.task_state = TaskState::Attached(AttachedState::WaitResetComplete);
+ }
+ }
+
+ AttachedState::WaitResetComplete => {
+ if self.usb.host().intflag.read().rst().bit_is_set() {
+ info!("reset was sent");
+ self.usb.host().intflag.write(|w| w.rst().set_bit());
+
+ // Make sure we always have a control pipe set up.
+ self.init_pipe0();
+
+ // Seems unneccesary, since SOFE will be set
+ // immediately after reset according to §32.6.3.3.
+ self.usb.host().ctrlb.modify(|_, w| w.sofe().set_bit());
+ // USB spec requires 20ms of SOF after bus reset.
+ self.delay = (self.millis)() + 20;
+ self.task_state = TaskState::Attached(AttachedState::WaitSOF);
+ }
+ }
+
+ AttachedState::WaitSOF => {
+ if self.usb.host().intflag.read().hsof().bit_is_set() {
+ self.usb.host().intflag.write(|w| w.hsof().set_bit());
+ if (self.millis)() >= self.delay {
+ self.task_state = TaskState::Steady(SteadyState::Configuring);
+ }
+ }
+ }
+ }
+ }
+
+ fn steady_fsm(&mut self, s: SteadyState) {
+ match s {
+ SteadyState::Configuring => {
+ let low_speed = 0;
+ self.task_state = match self.configure_dev(0, 0, low_speed) {
+ Ok(_) => TaskState::Steady(SteadyState::Running),
+ Err(e) => {
+ warn!("Enumeration error: {:?}", e);
+ TaskState::Steady(SteadyState::Error)
+ }
+ }
+ }
+
+ SteadyState::Running => {}
+
+ SteadyState::Error => {}
+ }
+ }
+
+ fn configure_dev(&mut self, _parent: u32, _port: u32, _low_speed: u32) -> Result<(), PipeErr> {
+ // addr: 0x20007774
+ let tmp: USBDeviceDescriptor = Default::default();
+ // addr: 0x20007788
+ let vol_descr = ::vcell::VolatileCell::new(tmp);
+ self.control_req(
+ 0,
+ 0,
+ BMRequestType::get_descr(),
+ USBRequest::GetDescriptor,
+ WValue::from((0, USBDescriptor::Device as u8)),
+ 0,
+ Some(DataBuf::from(&vol_descr)),
+ )?;
+
+ let desc = vol_descr.get();
+ info!(
+ " -- len: {}, ver: {:04x}, bMaxPacketSize: {}, bNumConfigurations: {}",
+ desc.b_length, desc.bcd_usb, desc.b_max_packet_size, desc.b_num_configurations
+ );
+ info!(" -- vid: {:x}, pid: {:x}", desc.id_vendor, desc.id_product);
+
+ // Assign address to this device and:
+ // - Stash bMaxPacketSize
+ // Then SET_ADDRESS(newAddr)
+ let new_address: u8 = 1;
+ self.control_req(
+ 0,
+ 0,
+ BMRequestType::set(),
+ USBRequest::SetAddress,
+ WValue::from((new_address, 0)),
+ 0,
+ None,
+ )?;
+ info!(" -- address set");
+ // Delay according to §9.2.6.3 of USB 2.0
+ let until = (self.millis)() + 300;
+ while (self.millis)() < until {}
+
+ info!("getting config");
+ let tmp: USBConfigurationDescriptor = Default::default();
+ //let vol_descr = ::vcell::VolatileCell::new(tmp);
+ self.control_req(
+ new_address,
+ 0,
+ BMRequestType::get_descr(),
+ USBRequest::GetConfiguration,
+ WValue::from((0, 0)),
+ 0,
+ Some(DataBuf::from(&tmp)),
+ )?;
+
+ //let desc = vol_descr.get();
+ info!("cdesc.len: {}", tmp.b_length);
+
+ // Once addressed, SET_CONFIGURATION(0)
+ info!("+++ setting configuration");
+ let conf: u8 = 0;
+ self.control_req(
+ new_address,
+ 0,
+ BMRequestType::set(),
+ USBRequest::SetConfiguration,
+ WValue::from((conf, 0)),
+ 0,
+ None,
+ )?;
+ info!(" -- configuration set");
+
+ // Now we should be able to access it normally.
+
+ Ok(())
+ }
+
+ fn control_req(
+ &mut self,
+ addr: u8,
+ ep: u8,
+ bm_request_type: BMRequestType,
+ b_request: USBRequest,
+ w_value: WValue,
+ w_index: u16,
+ buf: Option<DataBuf>,
+ ) -> Result<(), PipeErr> {
+ if let Some(ref b) = buf {
+ assert!(b.ptr as usize & 0x3 == 0);
+ assert!(b.len <= 65_535);
+ }
+
+ /*
+ * Setup stage.
+ */
+ let setup_packet = USBSetupPacket {
+ bm_request_type: bm_request_type,
+ b_request: b_request,
+ w_value: w_value,
+ w_index: w_index,
+ w_length: match buf {
+ None => 0,
+ Some(ref b) => b.len as u16,
+ },
+ };
+ let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), addr, ep);
+ pipe.send(
+ USBToken::Setup,
+ &DataBuf::from(&setup_packet),
+ NAK_LIMIT,
+ self.millis,
+ )?;
+
+ /*
+ * Data stage.
+ */
+ if let Some(b) = buf {
+ match bm_request_type.direction() {
+ USBSetupDirection::DeviceToHost => {
+ info!("buf0: {:?}", &b);
+ pipe.in_transfer(&b, NAK_LIMIT, self.millis)?;
+ info!("buf1: {:?}", &b);
+ }
+
+ USBSetupDirection::HostToDevice => {
+ info!("Should OUT for {}b", b.len);
+ }
+ }
+ }
+
+ /*
+ * Status stage.
+ */
+ pipe.desc.bank0.pcksize.write(|w| {
+ // FIXME: see note in `Pipe.send`.
+ unsafe { w.bits(0) }
+ });
+
+ // PSTATUSSET.DTGL set -- TODO: figure out if this is
+ // necessary.
+ pipe.regs.statusset.write(|w| w.dtgl().set_bit());
+
+ let token = match bm_request_type.direction() {
+ USBSetupDirection::DeviceToHost => USBToken::Out,
+ USBSetupDirection::HostToDevice => USBToken::In,
+ };
+
+ // TODO: should probably make `pipe.send` have optional
+ // `DataBuf`, rather than exposing `dispatch_retries`.
+ info!("dispatching status stage");
+ pipe.dispatch_retries(token, NAK_LIMIT, self.millis)?;
+ Ok(())
+ }
+
+ // Set up a default pipe for the control endpoint 0 on pipe 0.
+ fn init_pipe0(&mut self) {
+ let speed = self.usb.host().status.read().speed().bits();
+ let pipe = self.pipe_table.pipe_for(self.usb.host_mut(), 0, 0);
+ pipe.regs.cfg.write(|w| {
+ unsafe { w.ptype().bits(USBPipeType::Control as u8) };
+ w.bk().clear_bit()
+ });
+ pipe.desc.bank0.pcksize.write(|w| match speed {
+ 0 => w.size().bytes64(),
+ _ => w.size().bytes8(),
+ });
+ }
+}
+
+pub fn handler(usbp: usize, events: &mut EventWriter) {
+ let usb: &mut USB = unsafe { core::mem::transmute(usbp) };
+ let flags = usb.host().intflag.read();
+
+ info!("USB - {:x}", flags.bits());
+
+ let mut unshift_event = |e: Event| {
+ unsafe { LATEST_EVENT = e };
+ if let Err(_) = events.unshift(e) {
+ info!("Couldn't write USB event to queue.");
+ }
+ };
+
+ if flags.hsof().bit_is_set() {
+ info!(" +hsof");
+ usb.host().intflag.write(|w| w.hsof().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.rst().bit_is_set() {
+ // We seem to get this whenever a device attaches/detaches.
+ info!(" +rst");
+ usb.host().intflag.write(|w| w.rst().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.uprsm().bit_is_set() {
+ info!(" +uprsm");
+ usb.host().intflag.write(|w| w.uprsm().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dnrsm().bit_is_set() {
+ info!(" +dnrsm");
+ usb.host().intflag.write(|w| w.dnrsm().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.wakeup().bit_is_set() {
+ // §32.8.5.8 - since VBUSOK is set, then this happens when a
+ // device is connected.
+ info!(" +wakeup");
+ usb.host().intflag.write(|w| w.wakeup().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.ramacer().bit_is_set() {
+ info!(" +ramacer");
+ usb.host().intflag.write(|w| w.ramacer().set_bit());
+ unshift_event(Event::Detached);
+ }
+
+ if flags.dconn().bit_is_set() {
+ info!(" +dconn");
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ usb.host().intenclr.write(|w| w.dconn().set_bit());
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ usb.host().intenset.write(|w| w.ddisc().set_bit());
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ unshift_event(Event::Attached);
+ }
+
+ if flags.ddisc().bit_is_set() {
+ info!(" +ddisc");
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ usb.host().intenclr.write(|w| w.ddisc().set_bit());
+ // // Stop reset signal, in case of disconnection during reset
+ // uhd_stop_reset(); // nothing on samd21
+ usb.host().intflag.write(|w| w.dconn().set_bit());
+ usb.host().intenset.write(|w| w.dconn().set_bit());
+ usb.host().intflag.write(|w| w.ddisc().set_bit());
+ unshift_event(Event::Detached);
+ }
+}
diff --git a/usbh/src/pipe.rs b/usbh/src/pipe.rs
new file mode 100644
index 0000000..75923ba
--- /dev/null
+++ b/usbh/src/pipe.rs
@@ -0,0 +1,500 @@
+pub mod addr;
+pub mod ctrl_pipe;
+pub mod ext_reg;
+pub mod pck_size;
+pub mod status_bk;
+pub mod status_pipe;
+
+use addr::Addr;
+use ctrl_pipe::CtrlPipe;
+use ext_reg::ExtReg;
+use pck_size::PckSize;
+use status_bk::StatusBk;
+use status_pipe::StatusPipe;
+
+use core::convert::TryInto;
+use log::info;
+
+use atsamd_hal::target_device::usb::{
+ self,
+ host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET},
+};
+
+// TODO: verify this timeout against §9.2.6.1 of USB 2.0 spec.
+const USB_TIMEOUT: usize = 5 * 1024; // 5 Seconds
+
+// samd21 only supports 8 pipes.
+const MAX_PIPES: usize = 8;
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum PipeErr {
+ InvalidPipe,
+ InvalidToken,
+ Stall,
+ TransferFail,
+ Flow,
+ HWTimeout,
+ DataToggle,
+ SWTimeout,
+ Other,
+}
+pub(crate) struct PipeTable {
+ tbl: [PipeDesc; MAX_PIPES],
+}
+
+impl PipeTable {
+ pub(crate) fn new() -> Self {
+ Self {
+ tbl: [PipeDesc::new(); MAX_PIPES],
+ }
+ }
+
+ pub(crate) fn pipe_for<'a, 'b>(
+ &'a mut self,
+ host: &'b mut usb::HOST,
+ addr: u8,
+ ep: u8,
+ ) -> Pipe<'a, 'b> {
+ // Just use two pipes for now. 0 is always for control
+ // endpoints, 1 for everything else.
+ //
+ // TODO: cache in-use pipes and return them without init if
+ // possible.
+ let i = if ep == 0 { 0 } else { 1 };
+
+ let pregs = PipeRegs::from(host, i);
+ let pdesc = &mut self.tbl[i];
+
+ info!("setting paddr of pipe {} to {}:{}", i, addr, ep);
+ info!("cpipe0: {:x}", pdesc.bank0.ctrl_pipe.read().bits());
+ pdesc.bank0.ctrl_pipe.write(|w| {
+ w.pdaddr().set_addr(addr);
+ w.pepnum().set_epnum(ep)
+ });
+ info!("cpipe1: {:x}", pdesc.bank0.ctrl_pipe.read().bits());
+ Pipe {
+ num: i,
+ regs: pregs,
+ desc: pdesc,
+ }
+ }
+}
+
+// TODO: hide regs/desc fields. Needed right now for init_pipe0.
+pub(crate) struct Pipe<'a, 'b> {
+ num: usize,
+ pub(crate) regs: PipeRegs<'b>,
+ pub(crate) desc: &'a mut PipeDesc,
+}
+impl Pipe<'_, '_> {
+ pub(crate) fn send(
+ &mut self,
+ token: USBToken,
+ buf: &DataBuf,
+ nak_limit: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ // Data needs to be word aligned.
+ assert!((buf.ptr as u32) & 0x3 == 0);
+ // byte_count section of register is 14 bits.
+ assert!(buf.len < 16_384);
+
+ info!("p{}: sending {:?}", self.num, buf);
+
+ // Equiv to UHD_Pipe_Write(epAddr: 0, sizeof(setup_packet), &setup_packet)
+ self.desc
+ .bank0
+ .addr
+ .write(|w| unsafe { w.addr().bits(buf.ptr as u32) });
+ // configure packet size PCKSIZE.SIZE
+ self.desc.bank0.pcksize.write(|w| {
+ // FIXME: write raw to pcksize, because byte_count offset
+ // may be off? Doc table shows 6 bits, but text says 14,
+ // and arduino shows 14.
+ unsafe { w.bits(buf.len as u32) }
+ //unsafe { w.byte_count().bits(buf.len as u8) };
+ //unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ self.dispatch_retries(token, nak_limit, millis)
+ }
+
+ pub(crate) fn in_transfer(
+ &mut self,
+ buf: &DataBuf,
+ nak_limit: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ // Data needs to be word aligned.
+ assert!((buf.ptr as u32) & 0x3 == 0);
+ // byte_count section of register is 14 bits.
+ assert!(buf.len < 16_384);
+
+ info!("p{}: Should IN for {}b.", self.num, buf.len);
+ // TODO: should just pass pipe and pregs in, probably. TODO:
+ // merge with stuff in `send_to_pipe` that also does this.
+ self.desc
+ .bank0
+ .addr
+ .write(|w| unsafe { w.addr().bits(buf.ptr as u32) });
+ self.desc.bank0.pcksize.write(|w| {
+ // FIXME: see note in `send`.
+ unsafe { w.bits(buf.len as u32) }
+ //unsafe { w.byte_count().bits(buf.len as u8) };
+ //unsafe { w.multi_packet_size().bits(0) }
+ });
+
+ // Possibly set PSTATUS.DTGL? Not sure how this works
+ // yet. Arduino would set it here if dispatchPkt returned USB_ERROR_DATATOGGLE
+ //pregs.statusset.write(|w| w.dtgl().set_bit());
+ //pregs.statusclr.write(|w| unsafe {
+ // No function for this. FIXME: need to patch the SVD for
+ // PSTATUSCLR.DTGL at bit0
+ // w.bits(1)
+ //});
+
+ self.dispatch_retries(USBToken::In, nak_limit, millis)
+ }
+
+ pub(crate) fn dispatch_retries(
+ &mut self,
+ token: USBToken,
+ retries: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ assert!(retries > 0);
+
+ info!("initial regs");
+ self.log_regs();
+
+ let until = millis() + USB_TIMEOUT;
+ let mut last_result: Result<(), PipeErr> = Err(PipeErr::SWTimeout);
+ let mut naks = 0;
+ while naks <= retries {
+ info!("p{}: dispatch {:?} retry {}", self.num, token, naks);
+
+ self.dispatch_packet(token);
+ last_result = self.dispatch_result(token, until, millis);
+ match last_result {
+ Ok(_) => return Ok(()),
+ // FIXME: handle datatoggle
+ Err(PipeErr::DataToggle) => {
+ if self.regs.status.read().dtgl().bit_is_set() {
+ self.regs.statusset.write(|w| w.dtgl().set_bit());
+ } else {
+ self.regs.statusclr.write(|w| unsafe {
+ // No function for this. FIXME: need to patch the SVD for PSTATUSCLR.DTGL at bit0
+ w.bits(1)
+ });
+ }
+ }
+ Err(PipeErr::SWTimeout) => break,
+ Err(PipeErr::Stall) => break,
+ Err(_) => naks += 1,
+ }
+ }
+
+ last_result
+ }
+
+ fn log_regs(&self) {
+ // Pipe regs
+ let cfg = self.regs.cfg.read().bits();
+ let bin = self.regs.binterval.read().bits();
+ let sts = self.regs.status.read().bits();
+ let ifl = self.regs.intflag.read().bits();
+ info!(
+ "p{}: cfg: {:x}, bin: {:x}, sts: {:x}, ifl: {:x}",
+ self.num, cfg, bin, sts, ifl
+ );
+
+ // Pipe RAM regs
+ let adr = self.desc.bank0.addr.read().bits();
+ let pks = self.desc.bank0.pcksize.read().bits();
+ let ext = self.desc.bank0.extreg.read().bits();
+ let sbk = self.desc.bank0.status_bk.read().bits();
+ let hcp = self.desc.bank0.ctrl_pipe.read().bits();
+ let spi = self.desc.bank0.status_pipe.read().bits();
+ info!(
+ "p{}: adr: {:x}, pks: {:x}, ext: {:x}, sbk: {:x}, hcp: {:x}, spi: {:x}",
+ self.num, adr, pks, ext, sbk, hcp, spi
+ );
+ }
+
+ fn dispatch_packet(&mut self, token: USBToken) {
+ self.regs
+ .cfg
+ .modify(|_, w| unsafe { w.ptoken().bits(token as u8) });
+ match token {
+ USBToken::Setup => {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+ }
+ USBToken::In => self.regs.statusclr.write(|w| w.bk0rdy().set_bit()),
+ USBToken::Out => {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.bk0rdy().set_bit());
+ }
+ _ => {}
+ }
+ self.regs.statusclr.write(|w| w.pfreeze().set_bit());
+ }
+
+ fn dispatch_result(
+ &mut self,
+ token: USBToken,
+ until: usize,
+ millis: &dyn Fn() -> usize,
+ ) -> Result<(), PipeErr> {
+ while millis() <= until {
+ if self.is_transfer_complete(token)? {
+ return Ok(());
+ } else if self.regs.intflag.read().stall().bit_is_set() {
+ info!("stall");
+ self.log_regs();
+ self.regs.intflag.write(|w| w.stall().set_bit());
+ return Err(PipeErr::Stall);
+ } else if self.regs.intflag.read().trfail().bit_is_set() {
+ info!("trfail");
+ self.log_regs();
+ self.regs.intflag.write(|w| w.trfail().set_bit());
+ return Err(PipeErr::TransferFail);
+ } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() {
+ info!("errorflow");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_bk
+ .write(|w| w.errorflow().clear_bit());
+ return Err(PipeErr::Flow);
+ } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() {
+ info!("touter");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_pipe
+ .write(|w| w.touter().clear_bit());
+ return Err(PipeErr::HWTimeout);
+ } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() {
+ info!("dtgler");
+ self.log_regs();
+ self.desc
+ .bank0
+ .status_pipe
+ .write(|w| w.dtgler().clear_bit());
+ return Err(PipeErr::DataToggle);
+ }
+ }
+ info!("swtimeout");
+ self.log_regs();
+ Err(PipeErr::SWTimeout)
+ }
+
+ fn is_transfer_complete(&mut self, token: USBToken) -> Result<bool, PipeErr> {
+ match token {
+ USBToken::Setup => {
+ if self.regs.intflag.read().txstp().bit_is_set() {
+ self.regs.intflag.write(|w| w.txstp().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ USBToken::In => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ USBToken::Out => {
+ if self.regs.intflag.read().trcpt0().bit_is_set() {
+ self.regs.intflag.write(|w| w.trcpt0().set_bit());
+ self.regs.statusset.write(|w| w.pfreeze().set_bit());
+ Ok(true)
+ } else {
+ Ok(false)
+ }
+ }
+ _ => Err(PipeErr::InvalidToken),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum USBToken {
+ Setup = 0,
+ In = 1,
+ Out = 2,
+ Reserved = 3,
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum USBPipeType {
+ Disabled = 0x0,
+ Control = 0x1,
+ ISO = 0x2,
+ Bulk = 0x3,
+ Interrupt = 0x4,
+ Extended = 0x5,
+ _Reserved0 = 0x06,
+ _Reserved1 = 0x07,
+}
+
+pub(crate) struct DataBuf<'a> {
+ pub(crate) ptr: *const u8,
+ pub(crate) len: usize,
+ _marker: core::marker::PhantomData<&'a ()>,
+}
+impl DataBuf<'_> {}
+
+impl core::fmt::Debug for DataBuf<'_> {
+ fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ write!(f, "DataBuf {{ len: {}, ptr: [", self.len)?;
+ for i in 0..self.len {
+ write!(f, " {:x}", unsafe {
+ *self.ptr.offset(i.try_into().unwrap())
+ })?;
+ }
+ write!(f, " ] }}")
+ }
+}
+
+impl<'a, T> From<&'a T> for DataBuf<'a> {
+ fn from(v: &'a T) -> Self {
+ Self {
+ ptr: v as *const T as *const u8,
+ len: core::mem::size_of::<T>(),
+ _marker: core::marker::PhantomData,
+ }
+ }
+}
+
+pub(crate) struct PipeRegs<'a> {
+ pub(crate) cfg: &'a mut PCFG,
+ pub(crate) binterval: &'a mut BINTERVAL,
+ pub(crate) statusclr: &'a mut PSTATUSCLR,
+ pub(crate) statusset: &'a mut PSTATUSSET,
+ pub(crate) status: &'a mut PSTATUS,
+ pub(crate) intflag: &'a mut PINTFLAG,
+}
+impl<'a> PipeRegs<'a> {
+ pub(crate) fn from(host: &'a mut usb::HOST, i: usize) -> PipeRegs {
+ assert!(i < MAX_PIPES);
+ match i {
+ 0 => Self {
+ cfg: &mut host.pcfg0,
+ binterval: &mut host.binterval0,
+ statusclr: &mut host.pstatusclr0,
+ statusset: &mut host.pstatusset0,
+ status: &mut host.pstatus0,
+ intflag: &mut host.pintflag0,
+ },
+ 1 => Self {
+ cfg: &mut host.pcfg1,
+ binterval: &mut host.binterval1,
+ statusclr: &mut host.pstatusclr1,
+ statusset: &mut host.pstatusset1,
+ status: &mut host.pstatus1,
+ intflag: &mut host.pintflag1,
+ },
+ 2 => Self {
+ cfg: &mut host.pcfg2,
+ binterval: &mut host.binterval2,
+ statusclr: &mut host.pstatusclr2,
+ statusset: &mut host.pstatusset2,
+ status: &mut host.pstatus2,
+ intflag: &mut host.pintflag2,
+ },
+ 3 => Self {
+ cfg: &mut host.pcfg3,
+ binterval: &mut host.binterval3,
+ statusclr: &mut host.pstatusclr3,
+ statusset: &mut host.pstatusset3,
+ status: &mut host.pstatus3,
+ intflag: &mut host.pintflag3,
+ },
+ 4 => Self {
+ cfg: &mut host.pcfg4,
+ binterval: &mut host.binterval4,
+ statusclr: &mut host.pstatusclr4,
+ statusset: &mut host.pstatusset4,
+ status: &mut host.pstatus4,
+ intflag: &mut host.pintflag4,
+ },
+ 5 => Self {
+ cfg: &mut host.pcfg5,
+ binterval: &mut host.binterval5,
+ statusclr: &mut host.pstatusclr5,
+ statusset: &mut host.pstatusset5,
+ status: &mut host.pstatus5,
+ intflag: &mut host.pintflag5,
+ },
+ 6 => Self {
+ cfg: &mut host.pcfg6,
+ binterval: &mut host.binterval6,
+ statusclr: &mut host.pstatusclr6,
+ statusset: &mut host.pstatusset6,
+ status: &mut host.pstatus6,
+ intflag: &mut host.pintflag6,
+ },
+ 7 => Self {
+ cfg: &mut host.pcfg7,
+ binterval: &mut host.binterval7,
+ statusclr: &mut host.pstatusclr7,
+ statusset: &mut host.pstatusset7,
+ status: &mut host.pstatus7,
+ intflag: &mut host.pintflag7,
+ },
+ _ => unreachable!(),
+ }
+ }
+}
+
+// §32.8.7.1
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct PipeDesc {
+ pub bank0: BankDesc,
+ pub bank1: BankDesc,
+}
+
+// 2 banks: 32 bytes per pipe.
+impl PipeDesc {
+ pub fn new() -> Self {
+ Self {
+ bank0: BankDesc::new(),
+ bank1: BankDesc::new(),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+// 16 bytes per bank.
+pub(crate) struct BankDesc {
+ pub addr: Addr,
+ pub pcksize: PckSize,
+ pub extreg: ExtReg,
+ pub status_bk: StatusBk,
+ pub ctrl_pipe: CtrlPipe,
+ pub status_pipe: StatusPipe,
+
+ _reserved: u8,
+}
+
+impl BankDesc {
+ fn new() -> Self {
+ Self {
+ addr: Addr::from(0),
+ pcksize: PckSize::from(0),
+ extreg: ExtReg::from(0),
+ status_bk: StatusBk::from(0),
+ ctrl_pipe: CtrlPipe::from(0),
+ status_pipe: StatusPipe::from(0),
+ _reserved: 0,
+ }
+ }
+}
diff --git a/usbh/src/pipe/addr.rs b/usbh/src/pipe/addr.rs
new file mode 100644
index 0000000..8b92177
--- /dev/null
+++ b/usbh/src/pipe/addr.rs
@@ -0,0 +1,87 @@
+/// § 32.8.7.2
+/// Address of the Data Buffer.
+///
+/// Offset: 0x00 & 0x10
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct Addr(u32);
+
+pub(crate) struct R {
+ bits: u32,
+}
+
+pub(crate) struct W {
+ bits: u32,
+}
+
+impl Addr {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ // Address must be 32-bit aligned.
+ assert!((w.bits & 0x3) == 0);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u32> for Addr {
+ fn from(v: u32) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u32 {
+ self.bits
+ }
+
+ pub fn addr(&self) -> AddrR {
+ AddrR(self.bits)
+ }
+}
+
+/// Data Pointer Address Value
+///
+/// These bits define the data pointer address as an absolute double
+/// word address in RAM. The two least significant bits must be zero
+/// to ensure the descriptor is 32-bit aligned.
+pub(crate) struct AddrR(u32);
+impl AddrR {
+ pub fn bits(&self) -> u32 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u32) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn addr(&mut self) -> AddrW {
+ AddrW { w: self }
+ }
+}
+
+pub(crate) struct AddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> AddrW<'a> {
+ pub unsafe fn bits(self, v: u32) -> &'a mut W {
+ self.w.bits = v;
+ self.w
+ }
+
+ // TODO: "safe" method take a pointer instead of raw u32
+}
diff --git a/usbh/src/pipe/ctrl_pipe.rs b/usbh/src/pipe/ctrl_pipe.rs
new file mode 100644
index 0000000..63390df
--- /dev/null
+++ b/usbh/src/pipe/ctrl_pipe.rs
@@ -0,0 +1,177 @@
+/// Host Control Pipe.
+///
+/// Offset: 0x0c
+/// Reset: 0xXXXX
+/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct CtrlPipe(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+
+pub(crate) struct W {
+ bits: u16,
+}
+
+impl CtrlPipe {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u16> for CtrlPipe {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn permax(&self) -> PErMaxR {
+ let bits = {
+ const POS: u8 = 12;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PErMaxR(bits)
+ }
+
+ pub fn pepnum(&self) -> PEpNumR {
+ let bits = {
+ const POS: u8 = 8;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PEpNumR(bits)
+ }
+
+ pub fn pdaddr(&self) -> PDAddrR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 0x3f;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ PDAddrR(bits)
+ }
+}
+
+/// Pipe Error Max Number
+///
+/// These bits define the maximum number of error for this Pipe before
+/// freezing the pipe automatically.
+pub(crate) struct PErMaxR(u8);
+impl PErMaxR {
+ pub fn max(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe EndPoint Number
+///
+/// These bits define the number of endpoint for this Pipe.
+pub(crate) struct PEpNumR(u8);
+impl PEpNumR {
+ pub fn epnum(&self) -> u8 {
+ self.0
+ }
+}
+
+/// Pipe Device Address
+///
+/// These bits define the Device Address for this pipe.
+pub(crate) struct PDAddrR(u8);
+impl PDAddrR {
+ pub fn addr(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn permax(&mut self) -> PErMaxW {
+ PErMaxW { w: self }
+ }
+
+ pub fn pepnum(&mut self) -> PEpNumW {
+ PEpNumW { w: self }
+ }
+
+ pub fn pdaddr(&mut self) -> PDAddrW {
+ PDAddrW { w: self }
+ }
+}
+
+pub(crate) struct PErMaxW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PErMaxW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 12;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_max(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub(crate) struct PEpNumW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PEpNumW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 8;
+ const MASK: u8 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_epnum(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+pub(crate) struct PDAddrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PDAddrW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x3f;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_addr(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
diff --git a/usbh/src/pipe/ext_reg.rs b/usbh/src/pipe/ext_reg.rs
new file mode 100644
index 0000000..023ce9f
--- /dev/null
+++ b/usbh/src/pipe/ext_reg.rs
@@ -0,0 +1,156 @@
+/// §32.8.7.4
+/// Extended Register.
+///
+/// Offset: 0x08
+/// Reset: 0xxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct ExtReg(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+
+pub(crate) struct W {
+ bits: u16,
+}
+
+impl ExtReg {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u16> for ExtReg {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn variable(&self) -> VariableR {
+ let bits = {
+ const POS: u8 = 4;
+ const MASK: u16 = 0x7ff;
+ (self.bits >> POS) & MASK
+ };
+
+ VariableR(bits)
+ }
+
+ pub fn subpid(&self) -> SubPIDR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xf;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ SubPIDR(bits)
+ }
+}
+
+/// Variable field send with extended token
+///
+/// These bits define the VARIABLE field sent with extended token. See
+/// “Section 2.1.1 Protocol Extension Token in the reference document
+/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management
+/// Addendum.”
+///
+/// To support the USB2.0 Link Power Management addition the VARIABLE
+/// field should be set as described below.
+///
+/// | VARIABLE | Description |
+/// +----------------+-----------------------+
+/// | VARIABLE[3:0] | bLinkState[1] |
+/// | VARIABLE[7:4] | BESL (See LPM ECN)[2] |
+/// | VARIABLE[8] | bRemoteWake[1] |
+/// | VARIABLE[10:9] | Reserved |
+///
+/// [1] for a definition of LPM Token bRemoteWake and bLinkState
+/// fields, refer to "Table 2-3 in the reference document ENGINEERING
+/// CHANGE NOTICE, USB 2.0 Link Power Management Addendum"
+///
+/// [2] for a definition of LPM Token BESL field, refer to "Table 2-3
+/// in the reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link
+/// Power Management Addendum" and "Table X-X1 in Errata for ECN USB
+/// 2.0 Link Power Management.
+pub(crate) struct VariableR(u16);
+impl VariableR {
+ pub fn bits(&self) -> u16 {
+ self.0
+ }
+}
+
+/// SUBPID field with extended token
+///
+/// These bits define the SUBPID field sent with extended token. See
+/// “Section 2.1.1 Protocol Extension Token in the reference document
+/// ENGINEERING CHANGE NOTICE, USB 2.0 Link Power Management
+/// Addendum”.
+///
+/// To support the USB2.0 Link Power Management addition the SUBPID
+/// field should be set as described in “Table 2.2 SubPID Types in the
+/// reference document ENGINEERING CHANGE NOTICE, USB 2.0 Link Power
+/// Management Addendum”.
+pub(crate) struct SubPIDR(u8);
+impl SubPIDR {
+ pub fn bits(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn variable(&mut self) -> VariableW {
+ VariableW { w: self }
+ }
+ pub fn subpid(&mut self) -> SubPIDW {
+ SubPIDW { w: self }
+ }
+}
+
+pub(crate) struct VariableW<'a> {
+ w: &'a mut W,
+}
+impl<'a> VariableW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ const POS: u8 = 4;
+ const MASK: u16 = 0x7ff;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+}
+
+pub(crate) struct SubPIDW<'a> {
+ w: &'a mut W,
+}
+impl<'a> SubPIDW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xf;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+}
diff --git a/usbh/src/pipe/pck_size.rs b/usbh/src/pipe/pck_size.rs
new file mode 100644
index 0000000..5133005
--- /dev/null
+++ b/usbh/src/pipe/pck_size.rs
@@ -0,0 +1,360 @@
+/// § 32.8.7.3
+/// Packet Size.
+///
+/// Offset: 0x04 & 0x14
+/// Reset: 0xxxxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct PckSize(u32);
+
+pub(crate) struct R {
+ bits: u32,
+}
+
+pub(crate) struct W {
+ bits: u32,
+}
+
+impl PckSize {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u32> for PckSize {
+ fn from(v: u32) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u32 {
+ self.bits
+ }
+
+ pub fn auto_zlp(&self) -> AutoZLPR {
+ let bits = {
+ const POS: u8 = 31;
+ const MASK: u32 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ AutoZLPR(bits)
+ }
+
+ pub fn size(&self) -> SizeR {
+ let bits = {
+ const POS: u8 = 28;
+ const MASK: u32 = 0x7;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ SizeR::from(bits)
+ }
+
+ pub fn multi_packet_size(&self) -> MultiPacketSizeR {
+ let bits = {
+ const POS: u8 = 14;
+ const MASK: u32 = 0x3fff;
+ ((self.bits >> POS) & MASK) as u16
+ };
+
+ MultiPacketSizeR(bits)
+ }
+
+ pub fn byte_count(&self) -> ByteCountR {
+ let bits = {
+ const POS: u8 = 8;
+ const MASK: u32 = 0x3f;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ ByteCountR(bits)
+ }
+}
+
+/// Automatic Zero Length Packet
+///
+/// This bit defines the automatic Zero Length Packet mode of the
+/// pipe.
+///
+/// When enabled, the USB module will manage the ZLP handshake by
+/// hardware. This bit is for OUT pipes only. When disabled the
+/// handshake should be managed by firmware.
+pub(crate) struct AutoZLPR(bool);
+impl AutoZLPR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit()
+ }
+}
+
+/// Pipe size
+///
+/// These bits contains the size of the pipe.
+///
+/// These bits are cleared upon sending a USB reset.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum SizeR {
+ Bytes8,
+ Bytes16,
+ Bytes32,
+ Bytes64,
+ Bytes128,
+ Bytes256,
+ Bytes512,
+ Bytes1024,
+}
+
+impl SizeR {
+ pub fn bits(&self) -> u8 {
+ match *self {
+ Self::Bytes8 => 0x0,
+ Self::Bytes16 => 0x1,
+ Self::Bytes32 => 0x2,
+ Self::Bytes64 => 0x3,
+ Self::Bytes128 => 0x4,
+ Self::Bytes256 => 0x5,
+ Self::Bytes512 => 0x6,
+ Self::Bytes1024 => 0x7,
+ }
+ }
+
+ fn is_bytes8(&self) -> bool {
+ *self == Self::Bytes8
+ }
+ fn is_bytes16(&self) -> bool {
+ *self == Self::Bytes16
+ }
+ fn is_bytes32(&self) -> bool {
+ *self == Self::Bytes32
+ }
+ fn is_bytes64(&self) -> bool {
+ *self == Self::Bytes64
+ }
+ fn is_bytes128(&self) -> bool {
+ *self == Self::Bytes128
+ }
+ fn is_bytes256(&self) -> bool {
+ *self == Self::Bytes256
+ }
+ fn is_bytes512(&self) -> bool {
+ *self == Self::Bytes512
+ }
+ fn is_bytes1024(&self) -> bool {
+ *self == Self::Bytes1024
+ }
+}
+
+impl From<u8> for SizeR {
+ fn from(v: u8) -> Self {
+ match v {
+ 0x0 => Self::Bytes8,
+ 0x1 => Self::Bytes16,
+ 0x2 => Self::Bytes32,
+ 0x3 => Self::Bytes64,
+ 0x4 => Self::Bytes128,
+ 0x5 => Self::Bytes256,
+ 0x6 => Self::Bytes512,
+ 0x7 => Self::Bytes1024,
+ _ => panic!("pcksize between 0 and 7 only"),
+ }
+ }
+}
+
+/// Multi Packet IN or OUT size
+///
+/// These bits define the 14-bit value that is used for multi-packet
+/// transfers.
+///
+/// For IN pipes, MULTI_PACKET_SIZE holds the total number of bytes
+/// sent. MULTI_PACKET_SIZE should be written to zero when setting up
+/// a new transfer.
+///
+/// For OUT pipes, MULTI_PACKET_SIZE holds the total data size for the
+/// complete transfer. This value must be a multiple of the maximum
+/// packet size.
+pub(crate) struct MultiPacketSizeR(u16);
+impl MultiPacketSizeR {
+ pub fn bits(&self) -> u16 {
+ self.0
+ }
+}
+
+/// Byte Count
+///
+/// These bits define the 14-bit value that contains number of bytes
+/// sent in the last OUT or SETUP transaction for an OUT pipe, or of
+/// the number of bytes to be received in the next IN transaction for
+/// an input pipe.
+pub(crate) struct ByteCountR(u8);
+impl ByteCountR {
+ pub fn bits(&self) -> u8 {
+ self.0
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u32) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn auto_zlp(&mut self) -> AutoZLPW {
+ AutoZLPW { w: self }
+ }
+
+ pub fn size(&mut self) -> _SizeW {
+ _SizeW { w: self }
+ }
+
+ pub fn multi_packet_size(&mut self) -> MultiPacketSizeW {
+ MultiPacketSizeW { w: self }
+ }
+
+ pub fn byte_count(&mut self) -> ByteCountW {
+ ByteCountW { w: self }
+ }
+}
+
+pub(crate) struct AutoZLPW<'a> {
+ w: &'a mut W,
+}
+impl<'a> AutoZLPW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 31;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub(crate) enum SizeW {
+ Bytes8,
+ Bytes16,
+ Bytes32,
+ Bytes64,
+ Bytes128,
+ Bytes256,
+ Bytes512,
+ Bytes1024,
+}
+impl SizeW {
+ pub fn bits(&self) -> u8 {
+ match *self {
+ Self::Bytes8 => 0,
+ Self::Bytes16 => 1,
+ Self::Bytes32 => 2,
+ Self::Bytes64 => 3,
+ Self::Bytes128 => 4,
+ Self::Bytes256 => 5,
+ Self::Bytes512 => 6,
+ Self::Bytes1024 => 7,
+ }
+ }
+}
+
+/// Proxy for `SizeW`
+pub(crate) struct _SizeW<'a> {
+ w: &'a mut W,
+}
+impl<'a> _SizeW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 28;
+ const MASK: u8 = 0x7;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+
+ pub fn variant(self, v: SizeW) -> &'a mut W {
+ unsafe { self.bits(v.bits()) }
+ }
+
+ pub fn bytes8(self) -> &'a mut W {
+ self.variant(SizeW::Bytes8)
+ }
+
+ pub fn bytes16(self) -> &'a mut W {
+ self.variant(SizeW::Bytes16)
+ }
+
+ pub fn bytes32(self) -> &'a mut W {
+ self.variant(SizeW::Bytes32)
+ }
+
+ pub fn bytes64(self) -> &'a mut W {
+ self.variant(SizeW::Bytes64)
+ }
+
+ pub fn bytes128(self) -> &'a mut W {
+ self.variant(SizeW::Bytes128)
+ }
+
+ pub fn bytes256(self) -> &'a mut W {
+ self.variant(SizeW::Bytes256)
+ }
+
+ pub fn bytes512(self) -> &'a mut W {
+ self.variant(SizeW::Bytes512)
+ }
+
+ pub fn bytes1024(self) -> &'a mut W {
+ self.variant(SizeW::Bytes1024)
+ }
+}
+
+pub(crate) struct MultiPacketSizeW<'a> {
+ w: &'a mut W,
+}
+impl<'a> MultiPacketSizeW<'a> {
+ pub unsafe fn bits(self, v: u16) -> &'a mut W {
+ const POS: u8 = 14;
+ const MASK: u16 = 0x3fff;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+}
+
+pub(crate) struct ByteCountW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ByteCountW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 8;
+ const MASK: u8 = 0x3f;
+ self.w.bits &= !((MASK as u32) << POS);
+ self.w.bits |= ((v & MASK) as u32) << POS;
+ self.w
+ }
+}
diff --git a/usbh/src/pipe/status_bk.rs b/usbh/src/pipe/status_bk.rs
new file mode 100644
index 0000000..4ddb420
--- /dev/null
+++ b/usbh/src/pipe/status_bk.rs
@@ -0,0 +1,170 @@
+/// §32.8.7.5
+/// Host Status Bank.
+///
+/// Offset: 0x0a & 0x1a
+/// Reset: 0xxxxxxx
+/// Property: NA
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct StatusBk(u8);
+
+pub(crate) struct R {
+ bits: u8,
+}
+
+pub(crate) struct W {
+ bits: u8,
+}
+
+impl StatusBk {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u8> for StatusBk {
+ fn from(v: u8) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u8 {
+ self.bits
+ }
+
+ pub fn errorflow(&self) -> ErrorFlowR {
+ let bits = {
+ const POS: u8 = 1;
+ const MASK: u8 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ ErrorFlowR(bits)
+ }
+
+ pub fn crcerr(&self) -> CRCErrR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u8 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ CRCErrR(bits)
+ }
+}
+
+/// Error Flow Status
+///
+/// This bit defines the Error Flow Status.
+///
+/// This bit is set when a Error Flow has been detected during
+/// transfer from/towards this bank.
+///
+/// For IN transfer, a NAK handshake has been received. For OUT
+/// transfer, a NAK handshake has been received. For Isochronous IN
+/// transfer, an overrun condition has occurred. For Isochronous OUT
+/// transfer, an underflow condition has occurred.
+pub(crate) struct ErrorFlowR(bool);
+impl ErrorFlowR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// CRC Error
+///
+/// This bit defines the CRC Error Status.
+///
+/// This bit is set when a CRC error has been detected in an
+/// isochronous IN endpoint bank.
+pub(crate) struct CRCErrR(bool);
+impl CRCErrR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u8) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn errorflow(&mut self) -> ErrorFlowW {
+ ErrorFlowW { w: self }
+ }
+
+ pub fn crcerr(&mut self) -> CRCErrW {
+ CRCErrW { w: self }
+ }
+}
+
+pub(crate) struct ErrorFlowW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ErrorFlowW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 1;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+pub(crate) struct CRCErrW<'a> {
+ w: &'a mut W,
+}
+impl<'a> CRCErrW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u8) << POS);
+ self.w.bits |= ((v & MASK) as u8) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
diff --git a/usbh/src/pipe/status_pipe.rs b/usbh/src/pipe/status_pipe.rs
new file mode 100644
index 0000000..4f8eb41
--- /dev/null
+++ b/usbh/src/pipe/status_pipe.rs
@@ -0,0 +1,407 @@
+/// Host Status Pipe.
+///
+/// Offset: 0x0e & 0x1e
+/// Reset: 0xxxxxx
+/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized
+#[derive(Clone, Copy, Debug)]
+#[repr(C)]
+pub(crate) struct StatusPipe(u16);
+
+pub(crate) struct R {
+ bits: u16,
+}
+pub(crate) struct W {
+ bits: u16,
+}
+
+impl StatusPipe {
+ pub fn read(&self) -> R {
+ R { bits: self.0 }
+ }
+
+ pub fn write<F>(&mut self, f: F)
+ where
+ F: FnOnce(&mut W) -> &mut W,
+ {
+ let mut w = W { bits: self.0 };
+ f(&mut w);
+ self.0 = w.bits;
+ }
+}
+
+impl From<u16> for StatusPipe {
+ fn from(v: u16) -> Self {
+ Self(v)
+ }
+}
+
+impl R {
+ /// Value in raw bits.
+ pub fn bits(&self) -> u16 {
+ self.bits
+ }
+
+ pub fn ercnt(&self) -> ErCntR {
+ let bits = {
+ const POS: u8 = 5;
+ const MASK: u16 = 0x7;
+ ((self.bits >> POS) & MASK) as u8
+ };
+
+ ErCntR(bits)
+ }
+
+ pub fn crc16er(&self) -> CRC16ErR {
+ let bits = {
+ const POS: u8 = 4;
+ const MASK: u16 = 1;
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ CRC16ErR(bits)
+ }
+
+ pub fn touter(&self) -> TOutErrR {
+ let bits = {
+ const POS: u8 = 3;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ TOutErrR(bits)
+ }
+
+ pub fn pider(&self) -> PIDErR {
+ let bits = {
+ const POS: u8 = 2;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ PIDErR(bits)
+ }
+
+ pub fn dapider(&self) -> DaPIDErR {
+ let bits = {
+ const POS: u8 = 1;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ DaPIDErR(bits)
+ }
+
+ pub fn dtgler(&self) -> DTglErR {
+ let bits = {
+ const POS: u8 = 0;
+ const MASK: u16 = 1;
+
+ ((self.bits >> POS) & MASK) == 1
+ };
+
+ DTglErR(bits)
+ }
+}
+
+/// Pipe Error Counter
+///
+/// The number of errors detected on the pipe.
+pub(crate) struct ErCntR(u8);
+impl ErCntR {
+ pub fn bits(&self) -> u8 {
+ self.0
+ }
+}
+
+/// CRC16 ERROR
+///
+/// This bit defines the CRC16 Error Status.
+///
+/// This bit is set when a CRC 16 error has been detected during a IN
+/// transactions.
+pub(crate) struct CRC16ErR(bool);
+impl CRC16ErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// TIME OUT ERROR
+///
+/// This bit defines the Time Out Error Status.
+///
+/// This bit is set when a Time Out error has been detected during a
+/// USB transaction.
+pub(crate) struct TOutErrR(bool);
+impl TOutErrR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a PID error has been detected during a USB
+/// transaction.
+pub(crate) struct PIDErR(bool);
+impl PIDErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// Data PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a Data PID error has been detected during a
+/// USB transaction.
+pub(crate) struct DaPIDErR(bool);
+impl DaPIDErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+/// Data Toggle Error
+///
+/// This bit defines the Data Toggle Error Status.
+///
+/// This bit is set when a Data Toggle Error has been detected.
+pub(crate) struct DTglErR(bool);
+impl DTglErR {
+ pub fn bit(&self) -> bool {
+ self.0
+ }
+
+ pub fn bit_is_set(&self) -> bool {
+ self.bit()
+ }
+
+ pub fn bit_is_clear(&self) -> bool {
+ !self.bit_is_set()
+ }
+}
+
+impl W {
+ /// Write raw bits.
+ pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
+ self.bits = v;
+ self
+ }
+
+ pub fn ercnt(&mut self) -> ErCntW {
+ ErCntW { w: self }
+ }
+
+ pub fn crc16er(&mut self) -> CRC16ErW {
+ CRC16ErW { w: self }
+ }
+
+ pub fn touter(&mut self) -> TOutErW {
+ TOutErW { w: self }
+ }
+
+ pub fn pider(&mut self) -> PIDErW {
+ PIDErW { w: self }
+ }
+
+ pub fn dapider(&mut self) -> DaPIDErW {
+ DaPIDErW { w: self }
+ }
+
+ pub fn dtgler(&mut self) -> DTglErW {
+ DTglErW { w: self }
+ }
+}
+
+/// Pipe Error Counter
+///
+/// The number of errors detected on the pipe.
+pub(crate) struct ErCntW<'a> {
+ w: &'a mut W,
+}
+impl<'a> ErCntW<'a> {
+ pub unsafe fn bits(self, v: u8) -> &'a mut W {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x7;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_count(self, v: u8) -> &'a mut W {
+ unsafe { self.bits(v) }
+ }
+}
+
+/// CRC16 ERROR
+///
+/// This bit defines the CRC16 Error Status.
+///
+/// This bit is set when a CRC 16 error has been detected during a IN
+/// transactions.
+pub(crate) struct CRC16ErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> CRC16ErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 4;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// TIME OUT ERROR
+///
+/// This bit defines the Time Out Error Status.
+///
+/// This bit is set when a Time Out error has been detected during a
+/// USB transaction.
+pub(crate) struct TOutErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> TOutErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 3;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a PID error has been detected during a USB
+/// transaction.
+pub(crate) struct PIDErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> PIDErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 2;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// Data PID ERROR
+///
+/// This bit defines the PID Error Status.
+///
+/// This bit is set when a Data PID error has been detected during a
+/// USB transaction.
+pub(crate) struct DaPIDErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> DaPIDErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 1;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
+
+/// Data Toggle Error
+///
+/// This bit defines the Data Toggle Error Status.
+///
+/// This bit is set when a Data Toggle Error has been detected.
+pub(crate) struct DTglErW<'a> {
+ w: &'a mut W,
+}
+impl<'a> DTglErW<'a> {
+ pub fn bit(self, v: bool) -> &'a mut W {
+ const POS: u8 = 0;
+ const MASK: bool = true;
+ self.w.bits &= !((MASK as u16) << POS);
+ self.w.bits |= ((v & MASK) as u16) << POS;
+ self.w
+ }
+
+ pub fn set_bit(self) -> &'a mut W {
+ self.bit(true)
+ }
+
+ pub fn clear_bit(self) -> &'a mut W {
+ self.bit(false)
+ }
+}
diff --git a/usbh/src/usbproto.rs b/usbh/src/usbproto.rs
new file mode 100644
index 0000000..9c1dbcb
--- /dev/null
+++ b/usbh/src/usbproto.rs
@@ -0,0 +1,331 @@
+/// USB Protocol level types and functions.
+///
+/// Everything in here is defined by the USB specification, and
+/// hardware independent.
+
+// TODO: Put protocol section references in for types and
+// documentation.
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C)]
+pub struct USBDeviceDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub bcd_usb: u16,
+ pub b_device_class: u8,
+ pub b_device_sub_class: u8,
+ pub b_device_protocol: u8,
+ pub b_max_packet_size: u8,
+ pub id_vendor: u16,
+ pub id_product: u16,
+ pub bcd_device: u16,
+ pub i_manufacturer: u8,
+ pub i_product: u8,
+ pub i_serial_number: u8,
+ pub b_num_configurations: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C)]
+pub struct USBConfigurationDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub w_total_length: u16,
+ pub b_num_interfaces: u8,
+ pub b_configuration_value: u8,
+ pub i_configuration: u8,
+ pub bm_attributes: u8,
+ pub b_max_power: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C)]
+pub struct USBInterfaceDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub b_interface_number: u8,
+ pub b_alternate_setting: u8,
+ pub b_num_endpoints: u8,
+ pub b_interface_class: u8,
+ pub b_interface_sub_class: u8,
+ pub b_interface_protocol: u8,
+ pub i_interface: u8,
+}
+
+#[derive(Copy, Clone, Debug, Default)]
+#[repr(C)]
+pub struct USBEndpointDescriptor {
+ pub b_length: u8,
+ pub b_descriptor_type: u8,
+ pub b_endpoint_address: u8,
+ pub bm_attributes: u8,
+ pub w_max_packet_size: u16,
+ pub b_interval: u8,
+}
+
+#[derive(Copy, Clone, Debug)]
+#[repr(C)]
+pub struct USBSetupPacket {
+ pub bm_request_type: BMRequestType,
+ pub b_request: USBRequest,
+ pub w_value: WValue,
+ pub w_index: u16,
+ pub w_length: u16,
+}
+// TODO: shortcuts for standard device requests §9.4 of USB standard.
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupDirection {
+ HostToDevice = 0x00,
+ DeviceToHost = 0x80,
+}
+impl<T> From<T> for USBSetupDirection
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::HostToDevice,
+ 0x80 => Self::DeviceToHost,
+ _ => panic!("direction can only be 0x00 or 0x80"),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupType {
+ Standard = 0x00,
+ Class = 0x20,
+ Vendor = 0x40,
+}
+impl<T> From<T> for USBSetupType
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::Standard,
+ 0x20 => Self::Class,
+ 0x40 => Self::Vendor,
+ _ => panic!("type can only be 0x00, 0x20, or 0x40"),
+ }
+ }
+}
+
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum USBSetupRecipient {
+ Device = 0x00,
+ Interface = 0x01,
+ Endpoint = 0x02,
+ Other = 0x03,
+}
+impl<T> From<T> for USBSetupRecipient
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0x00 => Self::Device,
+ 0x01 => Self::Interface,
+ 0x02 => Self::Endpoint,
+ 0x03 => Self::Other,
+ _ => panic!("recipient can only be between 0 and 3"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct BMRequestType(u8);
+impl BMRequestType {
+ // Get descriptor request type.
+ pub fn get_descr() -> Self {
+ Self::from((
+ USBSetupDirection::DeviceToHost,
+ USBSetupType::Standard,
+ USBSetupRecipient::Device,
+ ))
+ }
+
+ // Set request type for all but 'set feature' and 'set interface'.
+ pub fn set() -> Self {
+ Self::from((
+ USBSetupDirection::HostToDevice,
+ USBSetupType::Standard,
+ USBSetupRecipient::Device,
+ ))
+ }
+
+ // Get interface request type.
+ pub fn cl_get_intf() -> Self {
+ Self::from((
+ USBSetupDirection::DeviceToHost,
+ USBSetupType::Class,
+ USBSetupRecipient::Interface,
+ ))
+ }
+
+ pub fn recipient(&self) -> USBSetupRecipient {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1f;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_recipient(&mut self, v: USBSetupRecipient) {
+ const POS: u8 = 0;
+ const MASK: u8 = 0x1f;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+
+ pub fn typ(&self) -> USBSetupType {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x3;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_typ(&mut self, v: USBSetupType) {
+ const POS: u8 = 5;
+ const MASK: u8 = 0x3;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+
+ pub fn direction(&self) -> USBSetupDirection {
+ const POS: u8 = 7;
+ const MASK: u8 = 0x1;
+ (self.0 & (MASK << POS)).into()
+ }
+
+ pub fn set_direction(&mut self, v: USBSetupDirection) {
+ const POS: u8 = 7;
+ const MASK: u8 = 0x1;
+ self.0 &= !(MASK << POS);
+ self.0 |= v as u8 & MASK;
+ }
+}
+impl From<u8> for BMRequestType {
+ fn from(v: u8) -> Self {
+ Self(v)
+ }
+}
+impl From<(USBSetupDirection, USBSetupType, USBSetupRecipient)> for BMRequestType {
+ fn from(v: (USBSetupDirection, USBSetupType, USBSetupRecipient)) -> Self {
+ Self(v.0 as u8 | v.1 as u8 | v.2 as u8)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+#[repr(C)]
+pub struct WValue(u16);
+impl WValue {
+ pub fn w_value_lo(&self) -> u8 {
+ const POS: u8 = 0;
+ const MASK: u16 = 0xff;
+ ((self.0 >> POS) & MASK) as u8
+ }
+
+ pub fn set_w_value_lo(&mut self, v: u8) {
+ const POS: u8 = 0;
+ const MASK: u8 = 0xff;
+ self.0 &= !((MASK as u16) << POS);
+ self.0 |= ((v & MASK) as u16) << POS;
+ }
+
+ pub fn w_value_hi(&self) -> u8 {
+ const POS: u8 = 8;
+ const MASK: u16 = 0xff;
+ ((self.0 >> POS) & MASK) as u8
+ }
+
+ pub fn set_w_value_hi(&mut self, v: u8) {
+ const POS: u8 = 8;
+ const MASK: u8 = 0xff;
+ self.0 &= !((MASK as u16) << POS);
+ self.0 |= ((v & MASK) as u16) << POS;
+ }
+}
+impl From<(u8, u8)> for WValue {
+ fn from(v: (u8, u8)) -> Self {
+ let mut rc = Self(0);
+ rc.set_w_value_lo(v.0);
+ rc.set_w_value_hi(v.1);
+ rc
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBRequest {
+ GetStatus = 0,
+ ClearFeature = 1,
+ SetFeature = 3,
+ SetAddress = 5,
+ GetDescriptor = 6,
+ SetDescriptor = 7,
+ GetConfiguration = 8,
+ SetConfiguration = 9,
+ GetInterface = 10,
+ SetInterface = 11,
+ SynchFrame = 12,
+}
+impl<T> From<T> for USBRequest
+where
+ T: Into<u8>,
+{
+ fn from(v: T) -> Self {
+ match v.into() {
+ 0 => Self::GetStatus,
+ 1 => Self::ClearFeature,
+ 3 => Self::SetFeature,
+ 5 => Self::SetAddress,
+ 6 => Self::GetDescriptor,
+ 7 => Self::SetDescriptor,
+ 8 => Self::GetConfiguration,
+ 9 => Self::SetConfiguration,
+ 10 => Self::GetInterface,
+ 11 => Self::SetInterface,
+ 12 => Self::SynchFrame,
+ _ => panic!("invalid request value"),
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBFeature {
+ EndpointHalt = 0,
+ DeviceRemoteWakeup = 1,
+ TestMode = 2,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBDescriptor {
+ Device = 0x01,
+ Configuration = 0x02,
+ String = 0x03,
+ Interface = 0x04,
+ Endpoint = 0x05,
+ DeviceQualifier = 0x06,
+ OtherSpeed = 0x07,
+ InterfacePower = 0x08,
+ OTG = 0x09,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum HIDDescriptor {
+ HID = 0x21,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum OTGFeature {
+ BHNPEnable = 3,
+ AHNPSupport = 4,
+ AAltHNPSupport = 5,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum USBTransferType {
+ Control = 0x00,
+ Isochronous = 0x01,
+ Bulk = 0x02,
+ Interrupt = 0x03,
+}