diff options
author | Brian Cully <bjc@kublai.com> | 2019-06-24 21:14:32 -0400 |
---|---|---|
committer | Brian Cully <bjc@kublai.com> | 2019-07-23 19:55:18 -0400 |
commit | 63d4ce8154eb8f6feb67986e98ea9b5007632460 (patch) | |
tree | 187e66104eb7c848dcf73a5ee067c5f27235360a /app/src | |
download | samd21-demo-63d4ce8154eb8f6feb67986e98ea9b5007632460.tar.gz samd21-demo-63d4ce8154eb8f6feb67986e98ea9b5007632460.zip |
Initial commit.
Diffstat (limited to 'app/src')
-rw-r--r-- | app/src/dotstar.rs | 42 | ||||
-rw-r--r-- | app/src/log.rs | 95 | ||||
-rw-r--r-- | app/src/macros.rs | 31 | ||||
-rwxr-xr-x | app/src/main.rs | 202 | ||||
-rw-r--r-- | app/src/rtc.rs | 71 | ||||
-rw-r--r-- | app/src/usb.rs | 612 | ||||
-rw-r--r-- | app/src/usb/pipe.rs | 503 | ||||
-rw-r--r-- | app/src/usb/pipe/addr.rs | 87 | ||||
-rw-r--r-- | app/src/usb/pipe/ctrl_pipe.rs | 177 | ||||
-rw-r--r-- | app/src/usb/pipe/ext_reg.rs | 156 | ||||
-rw-r--r-- | app/src/usb/pipe/pck_size.rs | 360 | ||||
-rw-r--r-- | app/src/usb/pipe/status_bk.rs | 170 | ||||
-rw-r--r-- | app/src/usb/pipe/status_pipe.rs | 407 | ||||
-rw-r--r-- | app/src/usb/usbproto.rs | 331 |
14 files changed, 3244 insertions, 0 deletions
diff --git a/app/src/dotstar.rs b/app/src/dotstar.rs new file mode 100644 index 0000000..8e930d0 --- /dev/null +++ b/app/src/dotstar.rs @@ -0,0 +1,42 @@ +use trinket_m0::{ + clock::GenericClockController, + gpio::{self, Floating, Input}, + prelude::*, + sercom::{self, PadPin, SPIMaster1}, + PM, SERCOM1, +}; + +use apa102_spi::Apa102; + +pub fn new( + sercom: SERCOM1, + miso: gpio::Pa31<Input<Floating>>, + mosi: gpio::Pa0<Input<Floating>>, + sck: gpio::Pa1<Input<Floating>>, + port: &mut gpio::Port, + pm: &mut PM, + clocks: &mut GenericClockController, +) -> Apa102< + SPIMaster1< + sercom::Sercom1Pad3<gpio::Pa31<gpio::PfD>>, + sercom::Sercom1Pad0<gpio::Pa0<gpio::PfD>>, + sercom::Sercom1Pad1<gpio::Pa1<gpio::PfD>>, + >, +> { + let gclk = clocks.gclk0(); + let miso = miso.into_pad(port); + let mosi = mosi.into_pad(port); + let sck = sck.into_pad(port); + let spi = SPIMaster1::new( + &clocks + .sercom1_core(&gclk) + .expect("setting up sercom1 clock"), + 3.mhz(), + apa102_spi::MODE, + sercom, + pm, + (miso, mosi, sck), + ); + + Apa102::new(spi) +} diff --git a/app/src/log.rs b/app/src/log.rs new file mode 100644 index 0000000..6cfba8f --- /dev/null +++ b/app/src/log.rs @@ -0,0 +1,95 @@ +use rb::{Reader, RingBuffer, Writer}; + +use core::fmt::{self, Write}; +use embedded_hal::{digital::v2::OutputPin, serial}; +use trinket_m0::{ + gpio::{Pa6, Pa7, PfD}, + sercom::{Sercom0Pad2, Sercom0Pad3, UART0}, +}; + +static mut LB: RingBuffer<u8> = RingBuffer::<u8>::new(0); + +struct JoinedRingBuffer<'a> { + lbr: Reader<'a, u8>, + lbw: Writer<'a, u8>, +} + +impl<'a> JoinedRingBuffer<'a> { + const fn new(rb: &'a RingBuffer<u8>) -> Self { + let (lbr, lbw) = rb.split(); + Self { lbr: lbr, lbw: lbw } + } +} + +impl Write for JoinedRingBuffer<'_> { + fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { + for b in s.bytes() { + if let Err(_) = self.lbw.unshift(b) { + // Ignore buffer full errors for logging. + return Ok(()); + } + } + Ok(()) + } +} + +static mut LOGBUF: JoinedRingBuffer = unsafe { JoinedRingBuffer::new(&LB) }; +static mut UART0: usize = 0; + +pub struct Processor<W, L> { + uart: W, + led: L, +} + +impl<W, L> Processor<W, L> +where + W: serial::Write<u8>, + L: OutputPin, +{ + pub fn new(uart: W, led: L) -> Self { + // Unsafe because we're creating a mutable alias. + unsafe { UART0 = core::mem::transmute(&uart) }; + Self { + uart: uart, + led: led, + } + } + + pub fn task(&mut self) { + // Unsafe due to mutable static. + if unsafe { LOGBUF.lbr.is_empty() } { + return; + } + self.led.set_high().ok(); + // Unsafe due to mutable static. + while let Some(b) = unsafe { LOGBUF.lbr.shift() } { + nb::block!(self.uart.write(b)).ok(); + } + self.led.set_low().ok(); + } +} + +// Write to the UART right now, instead of putting it on a ring +// buffer. This function is a huge hack, and only useful for debugging +// either before the main loop starts or if the ring buffer is broken. +pub unsafe fn write_fmt_now(args: fmt::Arguments, nl: bool) { + if UART0 == 0 { + return; + } + let uart: &mut UART0<Sercom0Pad3<Pa7<PfD>>, Sercom0Pad2<Pa6<PfD>>, (), ()> = + core::mem::transmute(UART0); + fmt::write(uart, args).expect("writing fmt now to uart"); + if nl { + uart.write_str("\r\n").expect("writing nl now to uart"); + } +} + +pub fn write_fmt(args: fmt::Arguments, nl: bool) { + // Unsafe due to mutable static. + unsafe { + fmt::write(&mut LOGBUF, args).expect("writing fmt to log"); + if nl { + LOGBUF.write_str("\r\n").expect("writing nl to log"); + } + } +} diff --git a/app/src/macros.rs b/app/src/macros.rs new file mode 100644 index 0000000..fe262b4 --- /dev/null +++ b/app/src/macros.rs @@ -0,0 +1,31 @@ +#[macro_export] +macro_rules! logln { + ($($arg:tt)*) => { + crate::log::write_fmt(format_args!($($arg)*), true); + }; + (_) => {}; +} + +#[macro_export] +macro_rules! log { + ($($arg:tt)*) => { + crate::log::write_fmt(format_args!($($arg)*), false); + }; + (_) => {}; +} + +#[macro_export] +macro_rules! logln_now { + ($($arg:tt)*) => { + unsafe {crate::log::write_fmt_now(format_args!($($arg)*), true);} + }; + (_) => {}; +} + +#[macro_export] +macro_rules! log_now { + ($($arg:tt)*) => { + unsafe {crate::log::write_fmt_now(format_args!($($arg)*), false);} + }; + (_) => {}; +} diff --git a/app/src/main.rs b/app/src/main.rs new file mode 100755 index 0000000..1025fae --- /dev/null +++ b/app/src/main.rs @@ -0,0 +1,202 @@ +#![no_std] +#![no_main] +#![feature(const_fn)] +#![feature(const_transmute)] +#![allow(dead_code)] + +mod dotstar; +mod log; +mod macros; +mod rtc; +mod usb; + +//#[allow(unused)] +//use panic_halt; + +use clint::HandlerArray; +use cortex_m::asm::wfi; +use cortex_m_rt::{entry, exception, ExceptionFrame}; +use embedded_hal::digital::v2::OutputPin; +use smart_leds::colors; +use smart_leds_trait::SmartLedsWrite; +use trinket_m0::{ + self as hal, + clock::GenericClockController, + gpio::{OpenDrain, Output, Pa10}, + target_device::{interrupt, Interrupt}, + time::*, + CorePeripherals, Peripherals, +}; + +static HANDLERS: HandlerArray = HandlerArray::new(); + +static mut LED: usize = 0; + +#[entry] +fn main() -> ! { + let mut peripherals = Peripherals::take().expect("taking peripherals"); + let mut core = CorePeripherals::take().expect("taking core peripherals"); + + let mut clocks = GenericClockController::with_internal_32kosc( + peripherals.GCLK, + &mut peripherals.PM, + &mut peripherals.SYSCTRL, + &mut peripherals.NVMCTRL, + ); + + let mut pins = hal::Pins::new(peripherals.PORT); + + let uart = hal::uart( + &mut clocks, + 115_200.hz(), + peripherals.SERCOM0, + &mut core.NVIC, + &mut peripherals.PM, + pins.d3, + pins.d4, + &mut pins.port, + ); + + let mut red_led = pins.d13.into_open_drain_output(&mut pins.port); + red_led.set_low().expect("turning off red LED"); + unsafe { LED = core::mem::transmute(&red_led) } + + let mut processor = log::Processor::new(uart, red_led); + logln_now!("setting up dotstar"); + + let mut dotstar = dotstar::new( + peripherals.SERCOM1, + pins.swdio, + pins.dotstar_di, + pins.dotstar_ci, + &mut pins.port, + &mut peripherals.PM, + &mut clocks, + ); + + let black = [colors::BLACK]; + let blue = [colors::DARK_MAGENTA]; + + logln_now!("setting up timer"); + let mut rtc_handler = rtc::setup(peripherals.RTC, &mut clocks); + + logln_now!("setting up usb host"); + let (mut usb_host, mut usb_handler) = usb::USBHost::new( + peripherals.USB, + pins.usb_sof, + pins.usb_dm, + pins.usb_dp, + Some(pins.usb_host_enable), + &mut pins.port, + &mut clocks, + &mut peripherals.PM, + ); + + logln!("setting up handlers"); + HANDLERS.with_overrides(|hs| { + hs.register(0, &mut rtc_handler); + core.NVIC.enable(Interrupt::RTC); + + hs.register(1, &mut usb_handler); + unsafe { core.NVIC.set_priority(Interrupt::USB, 0) }; + core.NVIC.enable(Interrupt::USB); + + logln!("Boot up complete."); + + let mut last_tick = 0; + loop { + dotstar + .write(black.iter().cloned()) + .expect("turning off dotstar"); + + let tick = rtc::millis(); + if tick >= last_tick + 1_024 { + last_tick = tick; + //logln!("{}: tick", rtc::millis()); + } + + usb_host.task(); + + processor.task(); + + dotstar + .write(blue.iter().cloned()) + .expect("turning on dotstar"); + wfi(); + } + }); + unreachable!(); +} + +#[panic_handler] +fn panic_handler(pi: &core::panic::PanicInfo) -> ! { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("~~~ PANIC ~~~"); + logln_now!("{}", pi); + loop { + wfi() + } +} + +#[exception] +fn HardFault(ef: &ExceptionFrame) -> ! { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("!!! Hard Fault - ef: {:?} !!!", ef); + loop { + wfi() + } +} + +#[exception] +fn DefaultHandler(interrupt: i16) { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("*** Default Handler: {} ***", interrupt); +} + +#[exception] +fn NonMaskableInt() { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("+++ NonMaskableInt +++"); +} + +#[exception] +fn SVCall() { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("+++ SVCall +++"); +} + +#[exception] +fn PendSV() { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("+++ PendSV +++"); +} + +#[exception] +fn SysTick() { + let red_led: &mut Pa10<Output<OpenDrain>> = unsafe { core::mem::transmute(LED) }; + red_led.set_high().ok(); + + logln_now!("+++ SysTick +++"); +} + +#[interrupt] +fn RTC() { + HANDLERS.call(0); +} + +#[interrupt] +fn USB() { + HANDLERS.call(1); +} diff --git a/app/src/rtc.rs b/app/src/rtc.rs new file mode 100644 index 0000000..0d39d31 --- /dev/null +++ b/app/src/rtc.rs @@ -0,0 +1,71 @@ +use core::sync::atomic::{AtomicUsize, Ordering}; +use trinket_m0::{clock::GenericClockController, RTC}; + +struct Clock(AtomicUsize); +impl Clock { + const fn new() -> Self { + Self(AtomicUsize::new(0)) + } + + fn set(&self, millis: usize) { + self.0.store(millis, Ordering::SeqCst) + } + + // Slightly less than 1ms, due to using a 32,768Hz clock, we can't + // hit exactly 1ms, so we shoot for a bit under. + fn millis(&self) -> usize { + self.0.load(Ordering::SeqCst) + } +} + +static CLOCK: Clock = Clock::new(); + +// Set to run every ~500µs. +static COUNTER: u32 = 16; // 32 ticks requires 1024 cycles at 32,768Hz for 1 second. + +pub fn setup(mut rtc: RTC, clocks: &mut GenericClockController) -> impl FnMut() { + let rtc_clock = &clocks.gclk1(); + clocks.rtc(&rtc_clock); + + rtc.mode0().ctrl.write(|w| w.swrst().set_bit()); + while rtc.mode0().status.read().syncbusy().bit_is_set() {} + + rtc.mode0().ctrl.write(|w| { + w.mode().count32(); + + // Neither the prescaler nor matchlr values seem to work. Not + // sure why. + //w.prescaler().div1024(); + w.matchclr().set_bit() // Reset on match for periodic + }); + + rtc.mode0().comp[0].write(|w| unsafe { w.bits(COUNTER) }); + rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); + rtc.mode0().intenset.write(|w| w.cmp0().set_bit()); + + // Enable the RTC and wait for sync. + rtc.mode0().ctrl.write(|w| w.enable().set_bit()); + while rtc.mode0().status.read().syncbusy().bit_is_set() {} + + move || handler(&mut rtc) +} + +pub fn millis() -> usize { + CLOCK.millis() +} + +fn handler(rtc: &mut RTC) { + // FIXME: matchclr doesn't seem to work to reset the counter? + rtc.mode0().count.write(|w| unsafe { w.bits(0) }); + rtc.mode0().intflag.write(|w| w.cmp0().set_bit()); + + static mut TICKS: usize = 0; + static mut ADD: bool = false; + unsafe { + if ADD { + TICKS += 1; + CLOCK.set(TICKS); + } + ADD = !ADD; + } +} diff --git a/app/src/usb.rs b/app/src/usb.rs new file mode 100644 index 0000000..c15e1b5 --- /dev/null +++ b/app/src/usb.rs @@ -0,0 +1,612 @@ +mod pipe; +mod usbproto; + +use crate::{log, logln, logln_now, rtc}; +use pipe::{DataBuf, PipeErr, PipeTable, USBPipeType, USBToken}; +use rb::{Reader, RingBuffer, Writer}; +use usbproto::*; + +use embedded_hal::digital::v2::OutputPin; +use trinket_m0::{ + calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal}, + clock::{ClockGenId, ClockSource, GenericClockController}, + gpio::{self, Floating, Input, OpenDrain, Output}, + PM, USB, +}; + +#[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 { + 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>>>, +} + +impl USBHost { + 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, + ) -> (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, + }; + + if let Some(he_pin) = host_enable_pin { + rc.host_enable_pin = Some(he_pin.into_open_drain_output(port)); + } + + logln_now!("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) { + log!("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()); + logln!("...done"); + } + + pub fn task(&mut self) { + static mut LAST_EVENT: Event = Event::Error; + unsafe { + if LAST_EVENT != LATEST_EVENT { + logln!("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 = rtc::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 { + logln!( + "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() { + // logln!("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 = rtc::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 rtc::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() { + logln!("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 = rtc::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 rtc::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) => { + logln!("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(); + logln_now!( + " -- len: {}, ver: {:04x}, bMaxPacketSize: {}, bNumConfigurations: {}", + desc.b_length, + desc.bcd_usb, + desc.b_max_packet_size, + desc.b_num_configurations + ); + logln_now!(" -- 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, + )?; + logln_now!(" -- address set"); + // Delay according to §9.2.6.3 of USB 2.0 + let until = rtc::millis() + 300; + while rtc::millis() < until {} + + // Once addressed, SET_CONFIGURATION(0) + logln_now!("+++ setting configuration"); + let conf: u8 = 0; + self.control_req( + new_address, + 0, + BMRequestType::set(), + USBRequest::SetConfiguration, + WValue::from((conf, 0)), + 0, + None, + )?; + logln_now!(" -- 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)?; + + /* + * Data stage. + */ + if let Some(b) = buf { + match bm_request_type.direction() { + USBSetupDirection::DeviceToHost => { + logln_now!("buf0: {:?}", &b); + pipe.in_transfer(&b, NAK_LIMIT)?; + logln_now!("buf1: {:?}", &b); + } + + USBSetupDirection::HostToDevice => { + logln_now!("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`. + logln_now!("dispatching status stage"); + pipe.dispatch_retries(token, NAK_LIMIT)?; + 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(); + + logln!("USB - {:x}", flags.bits()); + + let mut unshift_event = |e: Event| { + unsafe { LATEST_EVENT = e }; + if let Err(_) = events.unshift(e) { + logln!("Couldn't write USB event to queue."); + } + }; + + if flags.hsof().bit_is_set() { + logln!(" +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. + logln!(" +rst"); + usb.host().intflag.write(|w| w.rst().set_bit()); + unshift_event(Event::Detached); + } + + if flags.uprsm().bit_is_set() { + logln!(" +uprsm"); + usb.host().intflag.write(|w| w.uprsm().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dnrsm().bit_is_set() { + logln!(" +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. + logln!(" +wakeup"); + usb.host().intflag.write(|w| w.wakeup().set_bit()); + unshift_event(Event::Attached); + } + + if flags.ramacer().bit_is_set() { + logln!(" +ramacer"); + usb.host().intflag.write(|w| w.ramacer().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dconn().bit_is_set() { + logln!(" +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() { + logln!(" +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/app/src/usb/pipe.rs b/app/src/usb/pipe.rs new file mode 100644 index 0000000..12ca4cb --- /dev/null +++ b/app/src/usb/pipe.rs @@ -0,0 +1,503 @@ +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 crate::logln_now; +use crate::rtc; + +use core::convert::TryInto; + +// FIXME: this stuff is needed for PipeRegs, and while tied to samd, +// it shouldn't be tied to trinket_m0. Will need to figure out a +// better layout for this. +use trinket_m0::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]; + + logln_now!("setting paddr of pipe {} to {}:{}", i, addr, ep); + logln_now!("cpipe0: {:x}", pdesc.bank0.ctrl_pipe.read().bits()); + pdesc.bank0.ctrl_pipe.write(|w| { + w.pdaddr().set_addr(addr); + w.pepnum().set_epnum(ep) + }); + logln_now!("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, + ) -> 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); + + logln_now!("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) + } + + pub(crate) fn in_transfer(&mut self, buf: &DataBuf, nak_limit: 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); + + logln_now!("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) + } + + pub(crate) fn dispatch_retries( + &mut self, + token: USBToken, + retries: usize, + ) -> Result<(), PipeErr> { + assert!(retries > 0); + + logln_now!("initial regs"); + self.log_regs(); + + let until = rtc::millis() + USB_TIMEOUT; + let mut last_result: Result<(), PipeErr> = Err(PipeErr::SWTimeout); + let mut naks = 0; + while naks <= retries { + logln_now!("p{}: dispatch {:?} retry {}", self.num, token, naks); + + self.dispatch_packet(token); + last_result = self.dispatch_result(token, until); + 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(); + logln_now!( + "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(); + logln_now!( + "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) -> Result<(), PipeErr> { + while rtc::millis() <= until { + if self.is_transfer_complete(token)? { + return Ok(()); + } else if self.regs.intflag.read().stall().bit_is_set() { + logln_now!("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() { + logln_now!("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() { + logln_now!("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() { + logln_now!("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() { + logln_now!("dtgler"); + self.log_regs(); + self.desc + .bank0 + .status_pipe + .write(|w| w.dtgler().clear_bit()); + return Err(PipeErr::DataToggle); + } + } + logln_now!("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, packed)] +// 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/app/src/usb/pipe/addr.rs b/app/src/usb/pipe/addr.rs new file mode 100644 index 0000000..8b92177 --- /dev/null +++ b/app/src/usb/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/app/src/usb/pipe/ctrl_pipe.rs b/app/src/usb/pipe/ctrl_pipe.rs new file mode 100644 index 0000000..63390df --- /dev/null +++ b/app/src/usb/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/app/src/usb/pipe/ext_reg.rs b/app/src/usb/pipe/ext_reg.rs new file mode 100644 index 0000000..023ce9f --- /dev/null +++ b/app/src/usb/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/app/src/usb/pipe/pck_size.rs b/app/src/usb/pipe/pck_size.rs new file mode 100644 index 0000000..5133005 --- /dev/null +++ b/app/src/usb/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/app/src/usb/pipe/status_bk.rs b/app/src/usb/pipe/status_bk.rs new file mode 100644 index 0000000..4ddb420 --- /dev/null +++ b/app/src/usb/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/app/src/usb/pipe/status_pipe.rs b/app/src/usb/pipe/status_pipe.rs new file mode 100644 index 0000000..4f8eb41 --- /dev/null +++ b/app/src/usb/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/app/src/usb/usbproto.rs b/app/src/usb/usbproto.rs new file mode 100644 index 0000000..9a86ed7 --- /dev/null +++ b/app/src/usb/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, packed)] +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, packed)] +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, packed)] +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, packed)] +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, packed)] +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, +} |