diff options
Diffstat (limited to 'samd21-host/src')
-rwxr-xr-x | samd21-host/src/lib.rs | 645 | ||||
-rw-r--r-- | samd21-host/src/pipe.rs | 809 | ||||
-rw-r--r-- | samd21-host/src/pipe/addr.rs | 98 | ||||
-rw-r--r-- | samd21-host/src/pipe/ctrl_pipe.rs | 177 | ||||
-rw-r--r-- | samd21-host/src/pipe/ext_reg.rs | 156 | ||||
-rw-r--r-- | samd21-host/src/pipe/pck_size.rs | 368 | ||||
-rw-r--r-- | samd21-host/src/pipe/status_bk.rs | 170 | ||||
-rw-r--r-- | samd21-host/src/pipe/status_pipe.rs | 407 |
8 files changed, 2830 insertions, 0 deletions
diff --git a/samd21-host/src/lib.rs b/samd21-host/src/lib.rs new file mode 100755 index 0000000..98ebcff --- /dev/null +++ b/samd21-host/src/lib.rs @@ -0,0 +1,645 @@ +#![no_std] +mod pipe; + +use pipe::{PipeErr, PipeTable}; + +use usb_host::{ + DescriptorType, DeviceDescriptor, Direction, Driver, DriverError, Endpoint, RequestCode, + RequestDirection, RequestKind, RequestRecipient, RequestType, TransferError, TransferType, + USBHost, WValue, +}; + +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::{debug, error, trace, warn}; +use rb::{Reader, RingBuffer, Writer}; + +#[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>; + +const NAK_LIMIT: usize = 15; + +// Must be at least 100ms. cf §9.1.2 of USB 2.0. +const SETTLE_DELAY: usize = 205; // Delay in sec/1024 + +// Ring buffer for sharing events from interrupt context. +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; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum DetachedState { + Initialize, + WaitForDevice, + Illegal, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum AttachedState { + WaitForSettle(usize), + WaitResetComplete, + WaitSOF(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum SteadyState { + Configuring, + Running, + Error, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum TaskState { + Detached(DetachedState), + Attached(AttachedState), + Steady(SteadyState), +} + +use core::mem::{self, MaybeUninit}; +use core::ptr; + +const MAX_DEVICES: usize = 4; +struct DeviceTable { + tbl: [Option<Device>; MAX_DEVICES], +} +impl DeviceTable { + fn new() -> Self { + let tbl = { + let mut devs: [MaybeUninit<Option<Device>>; MAX_DEVICES] = + unsafe { MaybeUninit::uninit().assume_init() }; + for d in &mut devs[..] { + unsafe { ptr::write(d.as_mut_ptr(), None) } + } + unsafe { mem::transmute(devs) } + }; + + Self { tbl: tbl } + } + + /// Allocate a device with the next available address. + // TODO: get rid of the millis argument somehow, but the device + // does need a way of tracking time for Settle reasons. + fn next(&mut self) -> Option<&mut Device> { + for i in 1..self.tbl.len() { + if self.tbl[i].is_none() { + let d = Device { addr: i as u8 }; + self.tbl[i] = Some(d); + return self.tbl[i].as_mut(); + } + } + None + } + + /// Remove the device at address `addr`. + fn remove(&mut self, addr: u8) -> Option<Device> { + let v = core::mem::replace(&mut self.tbl[addr as usize], None); + v + } +} + +struct Device { + addr: u8, +} + +pub struct SAMDHost<'a, F> { + usb: USB, + + events: EventReader, + task_state: TaskState, + + // Need chunk of RAM for USB pipes, which gets used with DESCADD + // register. + pipe_table: PipeTable, + + devices: DeviceTable, + + // 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: &'a F, +} + +impl<'a, F> SAMDHost<'a, F> +where + F: Fn() -> usize, +{ + 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: &'a 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), + + pipe_table: PipeTable::new(), + + devices: DeviceTable::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)); + } + + 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); + + let usbp = &rc.usb as *const _ as usize; + (rc, move || handler(usbp, &mut eventw)) + } + + pub fn reset_periph(&mut self) { + debug!("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()); + debug!("...done"); + } + + pub fn task(&mut self, drivers: &mut [&mut dyn Driver]) { + static mut LAST_EVENT: Event = Event::Error; + unsafe { + if LAST_EVENT != LATEST_EVENT { + trace!("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 { + TaskState::Attached(AttachedState::WaitForSettle( + (self.millis)() + SETTLE_DELAY, + )) + } 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 { + trace!( + "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() { + // trace!("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.fsm(drivers); + + unsafe { + LAST_EVENT = LATEST_EVENT; + } + } + fn fsm(&mut self, drivers: &mut [&mut dyn Driver]) { + // 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, drivers), + }; + } + + 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(until) => { + if (self.millis)() >= until { + 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() { + trace!("reset was sent"); + self.usb.host().intflag.write(|w| w.rst().set_bit()); + + // 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.task_state = + TaskState::Attached(AttachedState::WaitSOF((self.millis)() + 20)); + } + } + + AttachedState::WaitSOF(until) => { + if self.usb.host().intflag.read().hsof().bit_is_set() { + self.usb.host().intflag.write(|w| w.hsof().set_bit()); + if (self.millis)() >= until { + self.task_state = TaskState::Steady(SteadyState::Configuring); + } + } + } + } + } + + fn steady_fsm(&mut self, s: SteadyState, drivers: &mut [&mut dyn Driver]) { + match s { + SteadyState::Configuring => { + self.task_state = match self.configure_dev(drivers) { + Ok(_) => TaskState::Steady(SteadyState::Running), + Err(e) => { + warn!("Enumeration error: {:?}", e); + TaskState::Steady(SteadyState::Error) + } + } + } + + SteadyState::Running => { + for d in &mut drivers[..] { + if let Err(e) = d.tick((self.millis)(), self) { + warn!("running driver {:?}: {:?}", d, e); + if let DriverError::Permanent(a, _) = e { + self.devices.remove(a); + } + } + } + } + + SteadyState::Error => {} + } + } + + fn configure_dev(&mut self, drivers: &mut [&mut dyn Driver]) -> Result<(), TransferError> { + let none: Option<&mut [u8]> = None; + let mut a0ep0 = Addr0EP0 { + in_toggle: true, + out_toggle: true, + }; + let mut dev_desc: DeviceDescriptor = + unsafe { MaybeUninit::<DeviceDescriptor>::uninit().assume_init() }; + self.control_transfer( + &mut a0ep0, + RequestType::from(( + RequestDirection::DeviceToHost, + RequestKind::Standard, + RequestRecipient::Device, + )), + RequestCode::GetDescriptor, + WValue::from((0, DescriptorType::Device as u8)), + 0, + Some(unsafe { to_slice_mut(&mut dev_desc) }), + )?; + + trace!(" -- dev_desc: {:?}", dev_desc); + + // TODO: new error for being out of devices. + let addr = self + .devices + .next() + .ok_or(TransferError::Permanent("out of devices"))? + .addr; + debug!("Setting address to {}.", addr); + self.control_transfer( + &mut a0ep0, + RequestType::from(( + RequestDirection::HostToDevice, + RequestKind::Standard, + RequestRecipient::Device, + )), + RequestCode::SetAddress, + WValue::from((addr, 0)), + 0, + none, + )?; + + // Now that the device is addressed, see if any drivers want + // it. + for d in &mut drivers[..] { + if d.want_device(&dev_desc) { + let res = d.add_device(dev_desc, addr); + match res { + Ok(_) => return Ok(()), + Err(_) => return Err(TransferError::Permanent("out of addresses")), + } + } + } + Ok(()) + } +} + +struct Addr0EP0 { + in_toggle: bool, + out_toggle: bool, +} +impl Endpoint for Addr0EP0 { + fn address(&self) -> u8 { + 0 + } + + fn endpoint_num(&self) -> u8 { + 0 + } + + fn transfer_type(&self) -> TransferType { + TransferType::Control + } + + fn direction(&self) -> Direction { + Direction::In + } + + fn max_packet_size(&self) -> u16 { + 8 + } + + fn in_toggle(&self) -> bool { + self.in_toggle + } + + fn set_in_toggle(&mut self, toggle: bool) { + self.in_toggle = toggle; + } + + fn out_toggle(&self) -> bool { + self.out_toggle + } + + fn set_out_toggle(&mut self, toggle: bool) { + self.out_toggle = toggle; + } +} + +pub fn handler(usbp: usize, events: &mut EventWriter) { + let usb: &mut USB = unsafe { core::mem::transmute(usbp) }; + let flags = usb.host().intflag.read(); + + trace!("USB - {:x}", flags.bits()); + + let mut unshift_event = |e: Event| { + unsafe { LATEST_EVENT = e }; + if let Err(_) = events.unshift(e) { + error!("Couldn't write USB event to queue."); + } + }; + + if flags.hsof().bit_is_set() { + trace!(" +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. + trace!(" +rst"); + usb.host().intflag.write(|w| w.rst().set_bit()); + unshift_event(Event::Detached); + } + + if flags.uprsm().bit_is_set() { + trace!(" +uprsm"); + usb.host().intflag.write(|w| w.uprsm().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dnrsm().bit_is_set() { + trace!(" +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. + trace!(" +wakeup"); + usb.host().intflag.write(|w| w.wakeup().set_bit()); + unshift_event(Event::Attached); + } + + if flags.ramacer().bit_is_set() { + trace!(" +ramacer"); + usb.host().intflag.write(|w| w.ramacer().set_bit()); + unshift_event(Event::Detached); + } + + if flags.dconn().bit_is_set() { + trace!(" +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() { + trace!(" +ddisc"); + usb.host().intflag.write(|w| w.ddisc().set_bit()); + usb.host().intenclr.write(|w| w.ddisc().set_bit()); + 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); + } +} + +impl From<PipeErr> for TransferError { + fn from(v: PipeErr) -> Self { + match v { + PipeErr::TransferFail => Self::Retry("transfer failed"), + PipeErr::Flow => Self::Retry("data flow"), + PipeErr::DataToggle => Self::Retry("toggle sequence"), + PipeErr::ShortPacket => Self::Permanent("short packet"), + PipeErr::InvalidPipe => Self::Permanent("invalid pipe"), + PipeErr::InvalidToken => Self::Permanent("invalid token"), + PipeErr::Stall => Self::Permanent("stall"), + PipeErr::PipeErr => Self::Permanent("pipe error"), + PipeErr::HWTimeout => Self::Permanent("hardware timeout"), + PipeErr::SWTimeout => Self::Permanent("software timeout"), + PipeErr::Other(s) => Self::Permanent(s), + } + } +} + +impl<F> USBHost for SAMDHost<'_, F> +where + F: Fn() -> usize, +{ + fn control_transfer( + &mut self, + ep: &mut dyn Endpoint, + bm_request_type: RequestType, + b_request: RequestCode, + w_value: WValue, + w_index: u16, + buf: Option<&mut [u8]>, + ) -> Result<usize, TransferError> { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.control_transfer( + ep, + bm_request_type, + b_request, + w_value, + w_index, + buf, + self.millis, + )?; + Ok(len) + } + + fn in_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &mut [u8], + ) -> Result<usize, TransferError> { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.in_transfer(ep, buf, NAK_LIMIT, self.millis)?; + Ok(len) + } + + fn out_transfer(&mut self, ep: &mut dyn Endpoint, buf: &[u8]) -> Result<usize, TransferError> { + let mut pipe = self.pipe_table.pipe_for(self.usb.host_mut(), ep); + let len = pipe.out_transfer(ep, buf, NAK_LIMIT, self.millis)?; + Ok(len) + } +} + +unsafe fn to_slice_mut<T>(v: &mut T) -> &mut [u8] { + let ptr = v as *mut T as *mut u8; + let len = mem::size_of::<T>(); + core::slice::from_raw_parts_mut(ptr, len) +} diff --git a/samd21-host/src/pipe.rs b/samd21-host/src/pipe.rs new file mode 100644 index 0000000..0da0e7f --- /dev/null +++ b/samd21-host/src/pipe.rs @@ -0,0 +1,809 @@ +#[allow(unused)] +pub mod addr; +#[allow(unused)] +pub mod ctrl_pipe; +#[allow(unused)] +pub mod ext_reg; +#[allow(unused)] +pub mod pck_size; +#[allow(unused)] +pub mod status_bk; +#[allow(unused)] +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 usb_host::{ + Endpoint, RequestCode, RequestDirection, RequestType, SetupPacket, TransferType, WValue, +}; + +use atsamd_hal::target_device::usb::{ + self, + host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET}, +}; +use core::convert::TryInto; +use log::trace; + +// Maximum time to wait for a control request with data to finish. cf +// §9.2.6.1 of USB 2.0. +const USB_TIMEOUT: usize = 5 * 1024; // 5 Seconds + +// samd21 only supports 8 pipes. +const MAX_PIPES: usize = 8; + +// How many times to retry a transaction that has transient errors. +const NAK_LIMIT: usize = 15; + +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum PipeErr { + ShortPacket, + InvalidPipe, + InvalidToken, + Stall, + TransferFail, + PipeErr, + Flow, + HWTimeout, + DataToggle, + SWTimeout, + Other(&'static str), +} +impl From<&'static str> for PipeErr { + fn from(v: &'static str) -> Self { + Self::Other(v) + } +} + +pub(crate) struct PipeTable { + tbl: [PipeDesc; MAX_PIPES], +} + +impl PipeTable { + pub(crate) fn new() -> Self { + let tbl = { + let mut tbl: [core::mem::MaybeUninit<PipeDesc>; MAX_PIPES] = + unsafe { core::mem::MaybeUninit::uninit().assume_init() }; + + for e in &mut tbl[..] { + unsafe { core::ptr::write(e.as_mut_ptr(), PipeDesc::new()) } + } + + unsafe { core::mem::transmute(tbl) } + }; + Self { tbl: tbl } + } + + pub(crate) fn pipe_for<'a, 'b>( + &'a mut self, + host: &'b mut usb::HOST, + endpoint: &dyn Endpoint, + ) -> 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 endpoint.endpoint_num() == 0 { 0 } else { 1 }; + + let pregs = PipeRegs::from(host, i); + let pdesc = &mut self.tbl[i]; + + pregs.cfg.write(|w| { + let ptype = PType::from(endpoint.transfer_type()) as u8; + unsafe { w.ptype().bits(ptype) } + }); + trace!( + "setting paddr of pipe {} to {}:{}", + i, + endpoint.address(), + endpoint.endpoint_num() + ); + pdesc.bank0.ctrl_pipe.write(|w| { + w.pdaddr().set_addr(endpoint.address()); + w.pepnum().set_epnum(endpoint.endpoint_num()) + }); + 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 control_transfer( + &mut self, + ep: &mut dyn Endpoint, + bm_request_type: RequestType, + b_request: RequestCode, + w_value: WValue, + w_index: u16, + buf: Option<&mut [u8]>, + millis: &dyn Fn() -> usize, + ) -> Result<usize, PipeErr> { + /* + * Setup stage. + */ + let buflen = buf.as_ref().map_or(0, |b| b.len() as u16); + let mut setup_packet = SetupPacket { + bm_request_type: bm_request_type, + b_request: b_request, + w_value: w_value, + w_index: w_index, + w_length: buflen, + }; + self.send( + ep, + PToken::Setup, + &DataBuf::from(&mut setup_packet), + NAK_LIMIT, + millis, + )?; + + /* + * Data stage. + */ + let mut transfer_len = 0; + if let Some(b) = buf { + // TODO: data stage, has up to 5,000ms (in 500ms + // per-packet chunks) to complete. cf §9.2.6.4 of USB 2.0. + match bm_request_type.direction()? { + RequestDirection::DeviceToHost => { + transfer_len = self.in_transfer(ep, b, NAK_LIMIT, millis)?; + } + + RequestDirection::HostToDevice => { + transfer_len = self.out_transfer(ep, b, NAK_LIMIT, millis)?; + } + } + } + + /* + * Status stage. + */ + // TODO: status stage has up to 50ms to complete. cf §9.2.6.4 + // of USB 2.0. + self.desc.bank0.pcksize.write(|w| { + unsafe { w.byte_count().bits(0) }; + unsafe { w.multi_packet_size().bits(0) } + }); + + let token = match bm_request_type.direction()? { + RequestDirection::DeviceToHost => PToken::Out, + RequestDirection::HostToDevice => PToken::In, + }; + + trace!("dispatching status stage"); + self.dispatch_retries(ep, token, NAK_LIMIT, millis)?; + + Ok(transfer_len) + } + + fn send( + &mut self, + ep: &mut dyn Endpoint, + token: PToken, + buf: &DataBuf, + nak_limit: usize, + millis: &dyn Fn() -> usize, + ) -> Result<(), PipeErr> { + trace!("p{}: sending {:?}", self.num, buf); + + 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| { + unsafe { w.byte_count().bits(buf.len as u16) }; + unsafe { w.multi_packet_size().bits(0) } + }); + + self.dispatch_retries(ep, token, nak_limit, millis) + } + + pub(crate) fn in_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &mut [u8], + nak_limit: usize, + millis: &dyn Fn() -> usize, + ) -> Result<usize, PipeErr> { + // TODO: pull this from pipe descriptor for this addr/ep. + let packet_size = 8; + + trace!("p{}: Should IN for {}b.", self.num, buf.len()); + self.desc.bank0.pcksize.write(|w| { + unsafe { w.byte_count().bits(buf.len() as u16) }; + unsafe { w.multi_packet_size().bits(0) } + }); + + // Read until we get a short packet (indicating that there's + // nothing left for us in this transaction) or the buffer is + // full. + // + // TODO: It is sometimes valid to get a short packet when + // variable length data is desired by the driver. cf §5.3.2 of + // USB 2.0. + let mut bytes_received = 0; + while bytes_received < buf.len() { + // Move the buffer pointer forward as we get data. + self.desc.bank0.addr.write(|w| unsafe { + w.addr() + .bits(buf.as_mut_ptr() as u32 + bytes_received as u32) + }); + self.regs.statusclr.write(|w| w.bk0rdy().set_bit()); + trace!("--- !!! regs-pre-dispatch !!! ---"); + self.log_regs(); + + self.dispatch_retries(ep, PToken::In, nak_limit, millis)?; + let recvd = self.desc.bank0.pcksize.read().byte_count().bits() as usize; + bytes_received += recvd; + trace!("!! read {} of {}", bytes_received, buf.len()); + if recvd < packet_size { + break; + } + + // Don't allow writing past the buffer. + assert!(bytes_received <= buf.len()); + } + + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + if bytes_received < buf.len() { + self.log_regs(); + // TODO: honestly, this is probably a panic condition, + // since whatever's in DataBuf.ptr is totally + // invalid. Alternately, this function should be declared + // `unsafe`. OR! Make the function take a mutable slice of + // u8, and leave it up to the caller to figure out how to + // deal with short packets. + Err(PipeErr::ShortPacket) + } else { + Ok(bytes_received) + } + } + + pub(crate) fn out_transfer( + &mut self, + ep: &mut dyn Endpoint, + buf: &[u8], + nak_limit: usize, + millis: &dyn Fn() -> usize, + ) -> Result<usize, PipeErr> { + trace!("p{}: Should OUT for {}b.", self.num, buf.len()); + self.desc.bank0.pcksize.write(|w| { + unsafe { w.byte_count().bits(buf.len() as u16) }; + unsafe { w.multi_packet_size().bits(0) } + }); + + let mut bytes_sent = 0; + while bytes_sent < buf.len() { + self.desc + .bank0 + .addr + .write(|w| unsafe { w.addr().bits(buf.as_ptr() as u32 + bytes_sent as u32) }); + self.dispatch_retries(ep, PToken::Out, nak_limit, millis)?; + + let sent = self.desc.bank0.pcksize.read().byte_count().bits() as usize; + bytes_sent += sent; + trace!("!! wrote {} of {}", bytes_sent, buf.len()); + } + + Ok(bytes_sent) + } + + fn dtgl(&mut self, ep: &mut dyn Endpoint, token: PToken) { + // TODO: this makes no sense to me, and docs are unclear. If + // the status bit is set, set it again? if it's clear then + // clear it? This is what I get for having to work from + // Arduino sources. + trace!( + "~~~ tok: {:?}, dtgl: {}, i: {}, o: {}", + token, + self.regs.status.read().dtgl().bit(), + ep.in_toggle(), + ep.out_toggle(), + ); + + let toggle = match token { + PToken::In => { + let t = !ep.in_toggle(); + ep.set_in_toggle(t); + t + } + + PToken::Out => { + let t = !ep.out_toggle(); + ep.set_out_toggle(t); + t + } + + _ => !self.regs.status.read().dtgl().bit_is_set(), + }; + + if toggle { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + + fn dtgl_set(&mut self) { + self.regs.statusset.write(|w| w.dtgl().set_bit()); + } + + fn dtgl_clear(&mut self) { + self.regs.statusclr.write(|w| unsafe { + // FIXME: need to patch the SVD for + // PSTATUSCLR.DTGL at bit0. No? This is in the SVD, but + // not the rust output. + w.bits(1) + }); + } + + // This is the only function that calls `millis`. If we can make + // this just take the current timestamp, we can make this + // non-blocking. + fn dispatch_retries( + &mut self, + ep: &mut dyn Endpoint, + token: PToken, + retries: usize, + millis: &dyn Fn() -> usize, + ) -> Result<(), PipeErr> { + self.dispatch_packet(ep, token); + + let until = millis() + USB_TIMEOUT; + let mut last_err = PipeErr::SWTimeout; + let mut naks = 0; + while millis() < until { + let res = self.dispatch_result(token); + match res { + Ok(true) => { + if token == PToken::In { + ep.set_in_toggle(self.regs.status.read().dtgl().bit_is_set()); + } else if token == PToken::Out { + ep.set_out_toggle(self.regs.status.read().dtgl().bit_is_set()); + } + return Ok(()); + } + Ok(false) => continue, + + Err(e) => { + last_err = e; + match last_err { + PipeErr::DataToggle => self.dtgl(ep, token), + + // Flow error on interrupt pipes means we got + // a NAK, which in this context means there's + // no data. cf §32.8.7.5 of SAM D21 data + // sheet. + PipeErr::Flow if ep.transfer_type() == TransferType::Interrupt => break, + + PipeErr::Stall => break, + _ => { + naks += 1; + if naks > retries { + break; + } else { + self.dispatch_packet(ep, token); + } + } + } + } + } + } + + Err(last_err) + } + + fn dispatch_packet(&mut self, ep: &mut dyn Endpoint, token: PToken) { + self.regs + .cfg + .modify(|_, w| unsafe { w.ptoken().bits(token as u8) }); + self.regs.intflag.modify(|_, w| w.trfail().set_bit()); + self.regs.intflag.modify(|_, w| w.perr().set_bit()); + + match token { + PToken::Setup => { + self.regs.intflag.write(|w| w.txstp().set_bit()); + self.regs.statusset.write(|w| w.bk0rdy().set_bit()); + + // Toggles should be 1 for host and function's + // sequence at end of setup transaction. cf §8.6.1 of + // USB 2.0. + self.dtgl_clear(); + ep.set_in_toggle(true); + ep.set_out_toggle(true); + } + PToken::In => { + self.regs.statusclr.write(|w| w.bk0rdy().set_bit()); + if ep.in_toggle() { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + PToken::Out => { + self.regs.intflag.write(|w| w.trcpt0().set_bit()); + self.regs.statusset.write(|w| w.bk0rdy().set_bit()); + if ep.out_toggle() { + self.dtgl_set(); + } else { + self.dtgl_clear(); + } + } + _ => {} + } + + trace!("initial regs"); + self.log_regs(); + + self.regs.statusclr.write(|w| w.pfreeze().set_bit()); + } + + fn dispatch_result(&mut self, token: PToken) -> Result<bool, PipeErr> { + if self.is_transfer_complete(token)? { + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + Ok(true) + } else if self.regs.intflag.read().trfail().bit_is_set() { + self.regs.intflag.write(|w| w.trfail().set_bit()); + trace!("trfail"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::TransferFail) + } else if self.desc.bank0.status_bk.read().errorflow().bit_is_set() { + trace!("errorflow"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::Flow) + } else if self.desc.bank0.status_pipe.read().touter().bit_is_set() { + trace!("touter"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::HWTimeout) + } else if self.desc.bank0.status_pipe.read().dtgler().bit_is_set() { + trace!("dtgler"); + self.regs.statusset.write(|w| w.pfreeze().set_bit()); + self.log_regs(); + Err(PipeErr::DataToggle) + } else { + // Nothing wrong, but not done yet. + Ok(false) + } + } + + fn is_transfer_complete(&mut self, token: PToken) -> Result<bool, PipeErr> { + match token { + PToken::Setup => { + if self.regs.intflag.read().txstp().bit_is_set() { + self.regs.intflag.write(|w| w.txstp().set_bit()); + Ok(true) + } else { + Ok(false) + } + } + PToken::In => { + if self.regs.intflag.read().trcpt0().bit_is_set() { + self.regs.intflag.write(|w| w.trcpt0().set_bit()); + Ok(true) + } else { + Ok(false) + } + } + PToken::Out => { + if self.regs.intflag.read().trcpt0().bit_is_set() { + self.regs.intflag.write(|w| w.trcpt0().set_bit()); + Ok(true) + } else { + Ok(false) + } + } + _ => Err(PipeErr::InvalidToken), + } + } + + 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(); + trace!( + "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(); + trace!( + "p{}: adr: {:x}, pks: {:x}, ext: {:x}, sbk: {:x}, hcp: {:x}, spi: {:x}", + self.num, + adr, + pks, + ext, + sbk, + hcp, + spi + ); + } +} + +// TODO: merge into SVD for pipe cfg register. +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum PToken { + Setup = 0x0, + In = 0x1, + Out = 0x2, + _Reserved = 0x3, +} + +// TODO: merge into SVD for pipe cfg register. +#[allow(unused)] +#[derive(Copy, Clone, Debug, PartialEq)] +pub(crate) enum PType { + Disabled = 0x0, + Control = 0x1, + ISO = 0x2, + Bulk = 0x3, + Interrupt = 0x4, + Extended = 0x5, + _Reserved0 = 0x06, + _Reserved1 = 0x07, +} +impl From<TransferType> for PType { + fn from(v: TransferType) -> Self { + match v { + TransferType::Control => Self::Control, + TransferType::Isochronous => Self::ISO, + TransferType::Bulk => Self::Bulk, + TransferType::Interrupt => Self::Interrupt, + } + } +} + +struct DataBuf<'a> { + ptr: *mut u8, + 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 mut T> for DataBuf<'a> { + fn from(v: &'a mut T) -> Self { + Self { + ptr: v as *mut T as *mut 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 +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(), + } + } +} + +#[repr(C, packed)] +// 16 bytes per bank. +pub(crate) struct BankDesc { + pub addr: Addr, + pub pcksize: PckSize, + pub extreg: ExtReg, + pub status_bk: StatusBk, + _reserved0: u8, + pub ctrl_pipe: CtrlPipe, + pub status_pipe: StatusPipe, + _reserved1: u8, +} + +impl BankDesc { + fn new() -> Self { + Self { + addr: Addr::from(0), + pcksize: PckSize::from(0), + extreg: ExtReg::from(0), + status_bk: StatusBk::from(0), + _reserved0: 0, + ctrl_pipe: CtrlPipe::from(0), + status_pipe: StatusPipe::from(0), + _reserved1: 0, + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn bank_desc_sizes() { + assert_eq!(core::mem::size_of::<Addr>(), 4, "Addr register size."); + assert_eq!(core::mem::size_of::<PckSize>(), 4, "PckSize register size."); + assert_eq!(core::mem::size_of::<ExtReg>(), 2, "ExtReg register size."); + assert_eq!( + core::mem::size_of::<StatusBk>(), + 1, + "StatusBk register size." + ); + assert_eq!( + core::mem::size_of::<CtrlPipe>(), + 2, + "CtrlPipe register size." + ); + assert_eq!( + core::mem::size_of::<StatusPipe>(), + 1, + "StatusPipe register size." + ); + + // addr at 0x00 for 4 + // pcksize at 0x04 for 4 + // extreg at 0x08 for 2 + // status_bk at 0x0a for 2 + // ctrl_pipe at 0x0c for 2 + // status_pipe at 0x0e for 1 + assert_eq!( + core::mem::size_of::<BankDesc>(), + 16, + "Bank descriptor size." + ); + } + + #[test] + fn bank_desc_offsets() { + let bd = BankDesc::new(); + let base = &bd as *const _ as usize; + + assert_offset("Addr", &bd.addr, base, 0x00); + assert_offset("PckSize", &bd.pcksize, base, 0x04); + assert_offset("ExtReg", &bd.extreg, base, 0x08); + assert_offset("StatusBk", &bd.status_bk, base, 0x0a); + assert_offset("CtrlPipe", &bd.ctrl_pipe, base, 0x0c); + assert_offset("StatusPipe", &bd.status_pipe, base, 0x0e); + } + + #[test] + fn pipe_desc_size() { + assert_eq!(core::mem::size_of::<PipeDesc>(), 32); + } + + #[test] + fn pipe_desc_offsets() { + let pd = PipeDesc::new(); + let base = &pd as *const _ as usize; + + assert_offset("Bank0", &pd.bank0, base, 0x00); + assert_offset("Bank1", &pd.bank1, base, 0x10); + } + + fn assert_offset<T>(name: &str, field: &T, base: usize, offset: usize) { + let ptr = field as *const _ as usize; + assert_eq!(ptr - base, offset, "{} register offset.", name); + } +} diff --git a/samd21-host/src/pipe/addr.rs b/samd21-host/src/pipe/addr.rs new file mode 100644 index 0000000..b3548cf --- /dev/null +++ b/samd21-host/src/pipe/addr.rs @@ -0,0 +1,98 @@ +/// § 32.8.7.2 +/// Address of the Data Buffer. +/// +/// Offset: 0x00 & 0x10 +/// Reset: 0xxxxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +pub struct Addr(u32); + +pub struct R { + bits: u32, +} + +pub 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); + self.0 = w.bits; + } + + pub fn modify<F>(&mut self, f: F) + where + for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, + { + let r = R { bits: self.0 }; + let mut w = W { bits: self.0 }; + f(&r, &mut w); + 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 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 struct AddrW<'a> { + w: &'a mut W, +} +impl<'a> AddrW<'a> { + pub unsafe fn bits(self, v: u32) -> &'a mut W { + // Address must be 32-bit aligned. cf §32.8.7.2 of SAMD21 data + // sheet. + assert!((v & 0x3) == 0); + self.w.bits = v; + self.w + } + + // TODO: "safe" method take a pointer instead of raw u32 +} diff --git a/samd21-host/src/pipe/ctrl_pipe.rs b/samd21-host/src/pipe/ctrl_pipe.rs new file mode 100644 index 0000000..9301d51 --- /dev/null +++ b/samd21-host/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, packed)] +pub struct CtrlPipe(u16); + +pub struct R { + bits: u16, +} + +pub 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 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 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 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 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 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 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/samd21-host/src/pipe/ext_reg.rs b/samd21-host/src/pipe/ext_reg.rs new file mode 100644 index 0000000..9778f1b --- /dev/null +++ b/samd21-host/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, packed)] +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/samd21-host/src/pipe/pck_size.rs b/samd21-host/src/pipe/pck_size.rs new file mode 100644 index 0000000..acc499f --- /dev/null +++ b/samd21-host/src/pipe/pck_size.rs @@ -0,0 +1,368 @@ +/// § 32.8.7.3 +/// Packet Size. +/// +/// Offset: 0x04 & 0x14 +/// Reset: 0xxxxxxxxx +/// Property: NA +#[derive(Clone, Copy, Debug)] +#[repr(C, packed)] +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) + } + + // Documentation is wrong on this field. Actually 14 bits from + // offset 0. + pub fn byte_count(&self) -> ByteCountR { + let bits = { + const POS: u8 = 0; + const MASK: u32 = 0x3fff; + ((self.bits >> POS) & MASK) as u16 + }; + + 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(u16); +impl ByteCountR { + pub fn bits(&self) -> u16 { + 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 { + assert!(v < 16_384); + + 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> { + // Documentation is wrong on this field. Actually 14 bits from + // offset 0. + pub unsafe fn bits(self, v: u16) -> &'a mut W { + assert!(v < 16_384); + + const POS: u8 = 0; + const MASK: u16 = 0x3fff; + self.w.bits &= !((MASK as u32) << POS); + self.w.bits |= ((v & MASK) as u32) << POS; + self.w + } +} diff --git a/samd21-host/src/pipe/status_bk.rs b/samd21-host/src/pipe/status_bk.rs new file mode 100644 index 0000000..489fc62 --- /dev/null +++ b/samd21-host/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, packed)] +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/samd21-host/src/pipe/status_pipe.rs b/samd21-host/src/pipe/status_pipe.rs new file mode 100644 index 0000000..be135c5 --- /dev/null +++ b/samd21-host/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, packed)] +pub(crate) struct StatusPipe(u8); + +pub(crate) struct R { + bits: u8, +} +pub(crate) struct W { + bits: u8, +} + +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<u8> for StatusPipe { + fn from(v: u8) -> Self { + Self(v) + } +} + +impl R { + /// Value in raw bits. + pub fn bits(&self) -> u8 { + self.bits + } + + pub fn ercnt(&self) -> ErCntR { + let bits = { + const POS: u8 = 5; + const MASK: u8 = 0x7; + ((self.bits >> POS) & MASK) as u8 + }; + + ErCntR(bits) + } + + pub fn crc16er(&self) -> CRC16ErR { + let bits = { + const POS: u8 = 4; + const MASK: u8 = 1; + ((self.bits >> POS) & MASK) == 1 + }; + + CRC16ErR(bits) + } + + pub fn touter(&self) -> TOutErrR { + let bits = { + const POS: u8 = 3; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + TOutErrR(bits) + } + + pub fn pider(&self) -> PIDErR { + let bits = { + const POS: u8 = 2; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + PIDErR(bits) + } + + pub fn dapider(&self) -> DaPIDErR { + let bits = { + const POS: u8 = 1; + const MASK: u8 = 1; + + ((self.bits >> POS) & MASK) == 1 + }; + + DaPIDErR(bits) + } + + pub fn dtgler(&self) -> DTglErR { + let bits = { + const POS: u8 = 0; + const MASK: u8 = 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: u8) -> &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 u8) << POS); + self.w.bits |= ((v & MASK) as u8) << 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 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) + } +} + +/// 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 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) + } +} + +/// 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 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) + } +} + +/// 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 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) + } +} + +/// 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 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) + } +} |