aboutsummaryrefslogtreecommitdiffstats
path: root/usbh/src
diff options
context:
space:
mode:
Diffstat (limited to 'usbh/src')
-rw-r--r--usbh/src/device.rs392
-rwxr-xr-xusbh/src/lib.rs474
-rw-r--r--usbh/src/pipe.rs800
-rw-r--r--usbh/src/pipe/addr.rs98
-rw-r--r--usbh/src/pipe/ctrl_pipe.rs177
-rw-r--r--usbh/src/pipe/ext_reg.rs156
-rw-r--r--usbh/src/pipe/pck_size.rs368
-rw-r--r--usbh/src/pipe/status_bk.rs170
-rw-r--r--usbh/src/pipe/status_pipe.rs407
-rw-r--r--usbh/src/usbproto.rs438
10 files changed, 0 insertions, 3480 deletions
diff --git a/usbh/src/device.rs b/usbh/src/device.rs
deleted file mode 100644
index fd5c1a1..0000000
--- a/usbh/src/device.rs
+++ /dev/null
@@ -1,392 +0,0 @@
-use super::pipe::{PipeErr, PipeTable, NO_DATA_STAGE};
-use super::usbproto::*;
-
-use core::convert::TryInto;
-use log::{debug, error, info, trace};
-
-// TODO: impl Drop for Device/Endpoint cleanup if any ends up being
-// required.
-
-// FIXME: once again, this doesn't belong here. The issue is that
-// we're using `pipe_for`, which requires it.
-use atsamd_hal::target_device::usb;
-
-const MAX_DEVICES: usize = 16;
-
-// TODO:
-// This may be wrong. It may be 15 additional input + 15 additional
-// output! cf §5.3.1.2 of USB 2.0.
-const MAX_ENDPOINTS: usize = 16;
-
-// How long to wait before talking to the device again after setting
-// its address. cf §9.2.6.3 of USB 2.0
-const SETTLE_DELAY: usize = 2;
-
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub(crate) enum Error {
- PipeErr(PipeErr),
-}
-impl From<PipeErr> for Error {
- fn from(e: PipeErr) -> Self {
- Self::PipeErr(e)
- }
-}
-
-enum FSM {
- AddressSet,
- WaitForSettle(usize),
- GetConfigDescriptor,
- SetConfig,
- GetReport(usize),
- Steady,
-}
-
-pub(crate) struct DeviceTable {
- devices: [Option<Device>; MAX_DEVICES],
-}
-// TODO: Untie device address from table index. Right now it's wasting
-// a table slot because addr 0 isn't used here. And rather than just
-// putting in an offset, which can be forgotten, it's better to let
-// something else handle address assignment.
-impl DeviceTable {
- pub(crate) fn new<F>(millis: &'static F) -> Self
- where
- F: Fn() -> usize + 'static,
- {
- let mut devices: [Option<Device>; MAX_DEVICES] = {
- let mut devs: [core::mem::MaybeUninit<Option<Device>>; MAX_DEVICES] =
- unsafe { core::mem::MaybeUninit::uninit().assume_init() };
- for d in &mut devs[..] {
- unsafe { core::ptr::write(d.as_mut_ptr(), None) }
- }
- unsafe { core::mem::transmute(devs) }
- };
- devices[0] = Some(Device::new(0, 8, millis));
- Self { devices: devices }
- }
-
- /// Return the device at address `addr`.
- pub(crate) fn device_for(&mut self, addr: u8) -> Option<&mut Device> {
- if let Some(ref mut d) = self.devices[addr as usize] {
- Some(d)
- } else {
- None
- }
- }
-
- /// 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.
- pub(crate) fn next(
- &mut self,
- max_packet_size: u8,
- millis: &'static dyn Fn() -> usize,
- ) -> Option<&mut Device> {
- for i in 1..self.devices.len() {
- if self.devices[i].is_none() {
- let a = i.try_into().unwrap();
- let d = Device::new(a, max_packet_size, millis);
- self.devices[i] = Some(d);
- return self.device_for(a);
- }
- }
- None
- }
-
- /// Remove the device at address `addr`.
- pub(crate) fn remove(&mut self, addr: u8) -> Option<Device> {
- let v = core::mem::replace(&mut self.devices[addr as usize], None);
- v
- }
-
- pub(crate) fn run(&mut self, pipe_table: &mut PipeTable, host: &mut usb::HOST) {
- for i in 1..self.devices.len() {
- // TODO: Woof, this is ugly, but I'm not sure of a better
- // way to avoid mutably borrowing self twice.
- let mut remove_addr: Option<u8> = None;
- if let Some(ref mut d) = self.devices[i] {
- if let Err(e) = d.fsm(pipe_table, host) {
- error!("Removing device {}: {:?}", d.addr, e);
- remove_addr = Some(d.addr);
- } else {
- remove_addr = None;
- }
- }
-
- if let Some(addr) = remove_addr {
- self.remove(addr);
- }
- }
- }
-}
-
-pub struct Device {
- pub addr: u8,
- pub max_packet_size: u8,
- pub endpoints: [Option<Endpoint>; MAX_ENDPOINTS],
- pub ep0: Endpoint,
-
- state: FSM,
- millis: &'static dyn Fn() -> usize,
-}
-impl Device {
- // TODO: get max packet size from device descriptor.
- pub fn new(addr: u8, max_packet_size: u8, millis: &'static dyn Fn() -> usize) -> Self {
- // Set up endpoints array with 0 as default control endpoint.
- let endpoints: [Option<Endpoint>; MAX_ENDPOINTS] = {
- let mut eps: [core::mem::MaybeUninit<Option<Endpoint>>; MAX_ENDPOINTS] =
- unsafe { core::mem::MaybeUninit::uninit().assume_init() };
- for ep in &mut eps[..] {
- unsafe { core::ptr::write(ep.as_mut_ptr(), None) }
- }
- unsafe { core::mem::transmute(eps) }
- };
-
- Self {
- addr: addr,
- max_packet_size: max_packet_size,
- endpoints: endpoints,
- ep0: Endpoint::new(
- addr,
- 0,
- TransferType::Control,
- TransferDirection::In,
- max_packet_size,
- ),
-
- state: FSM::AddressSet,
-
- // TODO: This doesn't belong here. Ideally the current
- // time is passed in to the FSM routine.
- millis: millis,
- }
- }
-}
-
-impl Device {
- pub(crate) fn fsm(
- &mut self,
- pipe_table: &mut PipeTable,
- host: &mut usb::HOST,
- ) -> Result<(), Error> {
- match self.state {
- FSM::AddressSet => self.state = FSM::WaitForSettle((self.millis)() + SETTLE_DELAY),
-
- FSM::WaitForSettle(until) => {
- if (self.millis)() >= until {
- // Dunno why we get the device descriptor a second time.
- let mut pipe = pipe_table.pipe_for(host, &self.ep0);
-
- let mut vol_descr =
- ::vcell::VolatileCell::<DeviceDescriptor>::new(Default::default());
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::get_descr(),
- RequestCode::GetDescriptor,
- WValue::from((0, DescriptorType::Device as u8)),
- 0,
- Some(&mut vol_descr),
- self.millis,
- )?;
-
- let desc = vol_descr.get();
- trace!(" -- devDesc: {:?}", desc);
-
- self.state = FSM::GetConfigDescriptor
- }
- }
-
- FSM::GetConfigDescriptor => {
- // Get config descriptor with minimal data, to see how much we need to allocate for the full descriptor.
- let mut pipe = pipe_table.pipe_for(host, &self.ep0);
-
- let mut vol_descr =
- ::vcell::VolatileCell::<ConfigurationDescriptor>::new(Default::default());
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::get_descr(),
- RequestCode::GetDescriptor,
- WValue::from((0, DescriptorType::Configuration as u8)),
- 0,
- Some(&mut vol_descr),
- self.millis,
- )?;
- let desc = vol_descr.get();
- debug!("config: {:?}", desc);
-
- // TODO: do real allocation later.
- assert!(desc.w_total_length < 64);
- let buf: [u8; 64] = [0; 64];
- let mut tmp = &buf[..desc.w_total_length as usize];
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::get_descr(),
- RequestCode::GetDescriptor,
- WValue::from((0, DescriptorType::Configuration as u8)),
- 0,
- Some(&mut tmp),
- self.millis,
- )?;
-
- self.state = FSM::SetConfig
- }
-
- FSM::SetConfig => {
- let mut pipe = pipe_table.pipe_for(host, &self.ep0);
-
- debug!("+++ setting configuration");
- let conf: u8 = 1;
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::set(),
- RequestCode::SetConfiguration,
- WValue::from((conf, 0)),
- 0,
- NO_DATA_STAGE,
- self.millis,
- )?;
- debug!(" -- configuration set");
-
- debug!("+++ setting idle");
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::from((
- RequestDirection::HostToDevice,
- RequestKind::Class,
- RequestRecipient::Interface,
- )),
- RequestCode::GetInterface, // This is also idle, but can't have two enums with the same value.
- WValue::from((0, 0)),
- 0,
- NO_DATA_STAGE,
- self.millis,
- )?;
- debug!(" -- idle set");
-
- debug!("+++ setting report");
- let mut report: u8 = 0;
- pipe.control_transfer(
- &mut self.ep0,
- RequestType::from((
- RequestDirection::HostToDevice,
- RequestKind::Class,
- RequestRecipient::Interface,
- )),
- RequestCode::SetConfiguration,
- WValue::from((0, 2)),
- 0,
- Some(&mut report),
- self.millis,
- )?;
- debug!(" -- report set");
-
- // Stub in some endpoints until we can parse the
- // configuration descriptor.
- self.endpoints[1] = Some(Endpoint::new(
- self.addr,
- 1,
- TransferType::Interrupt,
- TransferDirection::In,
- 8,
- ));
- self.endpoints[2] = Some(Endpoint::new(
- self.addr,
- 2,
- TransferType::Interrupt,
- TransferDirection::In,
- 8,
- ));
- self.state = FSM::GetReport(2)
- }
-
- FSM::GetReport(0) => self.state = FSM::Steady,
-
- FSM::GetReport(count) => {
- debug!("+++ getting report {}", count);
-
- // For now, just do an IN transfer to see if we can
- // get some keyboard reports without further setup.
-
- // EP 1 is boot proto keyboard.
- self.read_report(pipe_table, host, 1);
-
- // EP 2 is consumer control keys.
- self.read_report(pipe_table, host, 2);
-
- self.state = FSM::GetReport(count)
- }
-
- FSM::Steady => {}
- }
- Ok(())
- }
-
- fn read_report(&mut self, pipe_table: &mut PipeTable, host: &mut usb::HOST, id: u8) {
- if let Some(ref mut ep) = self.endpoints[id as usize] {
- let mut pipe = pipe_table.pipe_for(host, ep);
- let mut buf: [u8; 8] = [0; 8];
- match pipe.in_transfer(ep, &mut buf, 15, self.millis) {
- Ok(bytes_received) => info!("report {}: {} - {:?}", id, bytes_received, buf),
-
- Err(PipeErr::Flow) => return,
-
- Err(e) => trace!("error {}: {:?}", id, e),
- }
- } else {
- error!("endpoint {} doesn't exist!", id)
- }
- }
-}
-
-// TransferType (INTERRUPT)
-// Direction (IN)
-pub struct Endpoint {
- // This just points back to the address because we need to know it
- // for all endpoint operations, but we don't want to pass the
- // address struct (which contains all endpoints) around.
- pub addr: u8,
- pub num: u8,
- pub transfer_type: TransferType,
- pub direction: TransferDirection,
- pub in_toggle: bool,
- pub out_toggle: bool,
- pub max_packet_size: u8,
-}
-
-// cf §9.6.6 of USB 2.0
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum TransferDirection {
- Out,
- In,
-}
-
-// ibid
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum TransferType {
- Control = 0,
- Isochronous = 1,
- Bulk = 2,
- Interrupt = 3,
-}
-
-impl Endpoint {
- // TODO: direction is ignored on control endpoints. Try to remove
- // it from the API in those cases as well.
- pub fn new(
- addr: u8,
- num: u8,
- transfer_type: TransferType,
- direction: TransferDirection,
- max_packet_size: u8,
- ) -> Self {
- Self {
- addr: addr,
- num: num,
- transfer_type: transfer_type,
- direction: direction,
- in_toggle: false,
- out_toggle: false,
- max_packet_size: max_packet_size,
- }
- }
-}
diff --git a/usbh/src/lib.rs b/usbh/src/lib.rs
deleted file mode 100755
index 1ed414c..0000000
--- a/usbh/src/lib.rs
+++ /dev/null
@@ -1,474 +0,0 @@
-#![no_std]
-#![allow(dead_code)]
-
-mod device;
-mod pipe;
-mod usbproto;
-
-use device::{Device, DeviceTable};
-use pipe::{PipeErr, PipeTable, NO_DATA_STAGE};
-use rb::{Reader, RingBuffer, Writer};
-use usbproto::*;
-
-use atsamd_hal::{
- calibration::{usb_transn_cal, usb_transp_cal, usb_trim_cal},
- clock::{ClockGenId, ClockSource, GenericClockController},
- gpio::{self, Floating, Input, OpenDrain, Output},
- target_device::{PM, USB},
-};
-use embedded_hal::digital::v2::OutputPin;
-use log::{debug, error, trace, warn};
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum Event {
- Error,
- Detached,
- Attached,
-}
-type Events = RingBuffer<Event>;
-type EventReader = Reader<'static, Event>;
-type EventWriter = Writer<'static, Event>;
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-enum DetachedState {
- Initialize,
- WaitForDevice,
- Illegal,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-enum AttachedState {
- WaitForSettle(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),
-}
-
-// Must be at least 100ms. cf §9.1.2 of USB 2.0.
-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;
-
-pub struct USBHost<F>
-where
- F: Fn() -> usize + 'static,
-{
- 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,
- addr0: Device,
-
- // need sof 1kHz pad?
- _sof_pad: gpio::Pa23<gpio::PfG>,
- _dm_pad: gpio::Pa24<gpio::PfG>,
- _dp_pad: gpio::Pa25<gpio::PfG>,
- host_enable_pin: Option<gpio::Pa28<Output<OpenDrain>>>,
-
- // To get current milliseconds.
- millis: &'static F,
-}
-
-impl<F> USBHost<F>
-where
- F: Fn() -> usize + 'static,
-{
- pub fn new(
- usb: USB,
- sof_pin: gpio::Pa23<Input<Floating>>,
- dm_pin: gpio::Pa24<Input<Floating>>,
- dp_pin: gpio::Pa25<Input<Floating>>,
- host_enable_pin: Option<gpio::Pa28<Input<Floating>>>,
- port: &mut gpio::Port,
- clocks: &mut GenericClockController,
- pm: &mut PM,
- millis: &'static F,
- ) -> (Self, impl FnMut()) {
- let (eventr, mut eventw) = unsafe { EVENTS.split() };
-
- let mut rc = Self {
- usb: usb,
-
- events: eventr,
- task_state: TaskState::Detached(DetachedState::Initialize),
-
- pipe_table: PipeTable::new(),
-
- devices: DeviceTable::new(millis),
- addr0: Device::new(0, 8, millis),
-
- _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) {
- 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();
-
- unsafe {
- LAST_EVENT = LATEST_EVENT;
- }
- }
-
- fn poll_devices(&mut self) {}
-
- 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(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) {
- match s {
- SteadyState::Configuring => {
- self.task_state = match self.configure_dev() {
- Ok(_) => TaskState::Steady(SteadyState::Running),
- Err(e) => {
- warn!("Enumeration error: {:?}", e);
- TaskState::Steady(SteadyState::Error)
- }
- }
- }
-
- SteadyState::Running => {
- self.devices.run(&mut self.pipe_table, self.usb.host_mut());
- }
-
- SteadyState::Error => {}
- }
- }
-
- fn configure_dev(&mut self) -> Result<(), PipeErr> {
- let mut pipe = self
- .pipe_table
- .pipe_for(self.usb.host_mut(), &self.addr0.ep0);
- let mut vol_descr = ::vcell::VolatileCell::<DeviceDescriptor>::new(Default::default());
- pipe.control_transfer(
- &mut self.addr0.ep0,
- RequestType::get_descr(),
- RequestCode::GetDescriptor,
- WValue::from((0, DescriptorType::Device as u8)),
- 0,
- Some(&mut vol_descr),
- self.millis,
- )?;
-
- let desc = vol_descr.get();
- trace!(" -- devDesc: {:?}", desc);
-
- match self.devices.next(desc.b_max_packet_size, self.millis) {
- // TODO: new error for being out of devices.
- None => Err(PipeErr::Other("out of devices")),
- Some(device) => {
- debug!("Setting address to {}.", device.addr);
- pipe.control_transfer(
- &mut self.addr0.ep0,
- RequestType::set(),
- RequestCode::SetAddress,
- WValue::from((device.addr, 0)),
- 0,
- NO_DATA_STAGE,
- self.millis,
- )?;
-
- // Now that the device is addressed, `Device` can handle the
- // rest of the setup in its FSM.
- Ok(())
- }
- }
- }
-}
-
-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());
- // // Stop reset signal, in case of disconnection during reset
- // uhd_stop_reset(); // nothing on samd21
- usb.host().intflag.write(|w| w.dconn().set_bit());
- usb.host().intenset.write(|w| w.dconn().set_bit());
- usb.host().intflag.write(|w| w.ddisc().set_bit());
- unshift_event(Event::Detached);
- }
-}
diff --git a/usbh/src/pipe.rs b/usbh/src/pipe.rs
deleted file mode 100644
index 80ebe11..0000000
--- a/usbh/src/pipe.rs
+++ /dev/null
@@ -1,800 +0,0 @@
-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 super::device::{Endpoint, TransferType};
-
-use super::usbproto::*;
-
-use atsamd_hal::target_device::usb::{
- self,
- host::{BINTERVAL, PCFG, PINTFLAG, PSTATUS, PSTATUSCLR, PSTATUSSET},
-};
-use core::convert::TryInto;
-use log::{trace, warn};
-
-// 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;
-
-// For use in control requests that do not require a data stage.
-pub(crate) const NO_DATA_STAGE: Option<&mut ()> = None;
-
-#[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: &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.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.addr,
- endpoint.num
- );
- pdesc.bank0.ctrl_pipe.write(|w| {
- w.pdaddr().set_addr(endpoint.addr);
- w.pepnum().set_epnum(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<T>(
- &mut self,
- ep: &mut Endpoint,
- bm_request_type: RequestType,
- b_request: RequestCode,
- w_value: WValue,
- w_index: u16,
- buf: Option<&mut T>,
- millis: &dyn Fn() -> usize,
- ) -> Result<(), PipeErr> {
- let len = match buf {
- None => 0,
- _ => core::mem::size_of::<T>(),
- };
-
- /*
- * Setup stage.
- */
- 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: len as u16,
- };
- self.send(
- ep,
- PToken::Setup,
- &DataBuf::from(&mut setup_packet),
- NAK_LIMIT,
- millis,
- )?;
-
- /*
- * Data stage.
- */
- 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 => {
- self.in_transfer(ep, b, NAK_LIMIT, millis)?;
- }
-
- RequestDirection::HostToDevice => {
- 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(())
- }
-
- fn send(
- &mut self,
- ep: &mut 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<T>(
- &mut self,
- ep: &mut Endpoint,
- buf: &mut T,
- nak_limit: usize,
- millis: &dyn Fn() -> usize,
- ) -> Result<usize, PipeErr> {
- // TODO: pull this from pipe descriptor for this addr/ep.
- let packet_size = 8;
-
- let db: DataBuf = buf.into();
-
- trace!("p{}: Should IN for {}b.", self.num, db.len);
- self.desc.bank0.pcksize.write(|w| {
- unsafe { w.byte_count().bits(db.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 < db.len {
- // Move the buffer pointer forward as we get data.
- self.desc
- .bank0
- .addr
- .write(|w| unsafe { w.addr().bits(db.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, db.len);
- if recvd < packet_size {
- break;
- }
-
- // Don't allow writing past the buffer.
- assert!(bytes_received <= db.len);
- }
-
- self.regs.statusset.write(|w| w.pfreeze().set_bit());
- if bytes_received < db.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<T>(
- &mut self,
- ep: &mut Endpoint,
- buf: &mut T,
- nak_limit: usize,
- millis: &dyn Fn() -> usize,
- ) -> Result<usize, PipeErr> {
- let db: DataBuf = buf.into();
-
- trace!("p{}: Should OUT for {}b.", self.num, db.len);
- self.desc.bank0.pcksize.write(|w| {
- unsafe { w.byte_count().bits(db.len as u16) };
- unsafe { w.multi_packet_size().bits(0) }
- });
-
- let mut bytes_sent = 0;
- while bytes_sent < db.len {
- self.desc
- .bank0
- .addr
- .write(|w| unsafe { w.addr().bits(db.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, db.len);
- }
-
- Ok(bytes_sent)
- }
-
- pub(crate) fn dtgl(&mut self, ep: &mut 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,
- );
- if self.regs.status.read().dtgl().bit_is_set() {
- self.dtgl_set();
- } else {
- self.dtgl_clear();
- }
- if token == PToken::In {
- ep.in_toggle = self.regs.status.read().dtgl().bit_is_set()
- } else {
- ep.out_toggle = self.regs.status.read().dtgl().bit_is_set()
- }
- }
-
- pub(crate) fn dtgl_set(&mut self) {
- self.regs.statusset.write(|w| w.dtgl().set_bit());
- }
-
- pub(crate) fn dtgl_clear(&mut self) {
- self.regs.statusclr.write(|w| unsafe {
- // No function for this. 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 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.in_toggle = self.regs.status.read().dtgl().bit_is_set();
- } else if token == PToken::Out {
- ep.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 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.in_toggle = true;
- ep.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.
-#[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/usbh/src/pipe/addr.rs b/usbh/src/pipe/addr.rs
deleted file mode 100644
index aa26048..0000000
--- a/usbh/src/pipe/addr.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-/// § 32.8.7.2
-/// Address of the Data Buffer.
-///
-/// Offset: 0x00 & 0x10
-/// Reset: 0xxxxxxxxx
-/// Property: NA
-#[derive(Clone, Copy, Debug)]
-#[repr(C, packed)]
-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);
- 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(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 {
- // 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/usbh/src/pipe/ctrl_pipe.rs b/usbh/src/pipe/ctrl_pipe.rs
deleted file mode 100644
index 179b615..0000000
--- a/usbh/src/pipe/ctrl_pipe.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-/// Host Control Pipe.
-///
-/// Offset: 0x0c
-/// Reset: 0xXXXX
-/// Property: PAC Write-Protection, Write-Synchronized, Read-Synchronized
-#[derive(Clone, Copy, Debug)]
-#[repr(C, packed)]
-pub(crate) struct CtrlPipe(u16);
-
-pub(crate) struct R {
- bits: u16,
-}
-
-pub(crate) struct W {
- bits: u16,
-}
-
-impl CtrlPipe {
- pub fn read(&self) -> R {
- R { bits: self.0 }
- }
-
- pub fn write<F>(&mut self, f: F)
- where
- F: FnOnce(&mut W) -> &mut W,
- {
- let mut w = W { bits: self.0 };
- f(&mut w);
- self.0 = w.bits;
- }
-}
-
-impl From<u16> for CtrlPipe {
- fn from(v: u16) -> Self {
- Self(v)
- }
-}
-
-impl R {
- /// Value in raw bits.
- pub fn bits(&self) -> u16 {
- self.bits
- }
-
- pub fn permax(&self) -> PErMaxR {
- let bits = {
- const POS: u8 = 12;
- const MASK: u16 = 0xf;
- ((self.bits >> POS) & MASK) as u8
- };
-
- PErMaxR(bits)
- }
-
- pub fn pepnum(&self) -> PEpNumR {
- let bits = {
- const POS: u8 = 8;
- const MASK: u16 = 0xf;
- ((self.bits >> POS) & MASK) as u8
- };
-
- PEpNumR(bits)
- }
-
- pub fn pdaddr(&self) -> PDAddrR {
- let bits = {
- const POS: u8 = 0;
- const MASK: u16 = 0x3f;
- ((self.bits >> POS) & MASK) as u8
- };
-
- PDAddrR(bits)
- }
-}
-
-/// Pipe Error Max Number
-///
-/// These bits define the maximum number of error for this Pipe before
-/// freezing the pipe automatically.
-pub(crate) struct PErMaxR(u8);
-impl PErMaxR {
- pub fn max(&self) -> u8 {
- self.0
- }
-}
-
-/// Pipe EndPoint Number
-///
-/// These bits define the number of endpoint for this Pipe.
-pub(crate) struct PEpNumR(u8);
-impl PEpNumR {
- pub fn epnum(&self) -> u8 {
- self.0
- }
-}
-
-/// Pipe Device Address
-///
-/// These bits define the Device Address for this pipe.
-pub(crate) struct PDAddrR(u8);
-impl PDAddrR {
- pub fn addr(&self) -> u8 {
- self.0
- }
-}
-
-impl W {
- /// Write raw bits.
-
- pub unsafe fn bits(&mut self, v: u16) -> &mut Self {
- self.bits = v;
- self
- }
-
- pub fn permax(&mut self) -> PErMaxW {
- PErMaxW { w: self }
- }
-
- pub fn pepnum(&mut self) -> PEpNumW {
- PEpNumW { w: self }
- }
-
- pub fn pdaddr(&mut self) -> PDAddrW {
- PDAddrW { w: self }
- }
-}
-
-pub(crate) struct PErMaxW<'a> {
- w: &'a mut W,
-}
-impl<'a> PErMaxW<'a> {
- pub unsafe fn bits(self, v: u8) -> &'a mut W {
- const POS: u8 = 12;
- const MASK: u8 = 0xf;
- self.w.bits &= !((MASK as u16) << POS);
- self.w.bits |= ((v & MASK) as u16) << POS;
- self.w
- }
-
- pub fn set_max(self, v: u8) -> &'a mut W {
- unsafe { self.bits(v) }
- }
-}
-
-pub(crate) struct PEpNumW<'a> {
- w: &'a mut W,
-}
-impl<'a> PEpNumW<'a> {
- pub unsafe fn bits(self, v: u8) -> &'a mut W {
- const POS: u8 = 8;
- const MASK: u8 = 0xf;
- self.w.bits &= !((MASK as u16) << POS);
- self.w.bits |= ((v & MASK) as u16) << POS;
- self.w
- }
-
- pub fn set_epnum(self, v: u8) -> &'a mut W {
- unsafe { self.bits(v) }
- }
-}
-
-pub(crate) struct PDAddrW<'a> {
- w: &'a mut W,
-}
-impl<'a> PDAddrW<'a> {
- pub unsafe fn bits(self, v: u8) -> &'a mut W {
- const POS: u8 = 0;
- const MASK: u8 = 0x3f;
- self.w.bits &= !((MASK as u16) << POS);
- self.w.bits |= ((v & MASK) as u16) << POS;
- self.w
- }
-
- pub fn set_addr(self, v: u8) -> &'a mut W {
- unsafe { self.bits(v) }
- }
-}
diff --git a/usbh/src/pipe/ext_reg.rs b/usbh/src/pipe/ext_reg.rs
deleted file mode 100644
index 9778f1b..0000000
--- a/usbh/src/pipe/ext_reg.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-/// §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/usbh/src/pipe/pck_size.rs b/usbh/src/pipe/pck_size.rs
deleted file mode 100644
index acc499f..0000000
--- a/usbh/src/pipe/pck_size.rs
+++ /dev/null
@@ -1,368 +0,0 @@
-/// § 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/usbh/src/pipe/status_bk.rs b/usbh/src/pipe/status_bk.rs
deleted file mode 100644
index 489fc62..0000000
--- a/usbh/src/pipe/status_bk.rs
+++ /dev/null
@@ -1,170 +0,0 @@
-/// §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/usbh/src/pipe/status_pipe.rs b/usbh/src/pipe/status_pipe.rs
deleted file mode 100644
index be135c5..0000000
--- a/usbh/src/pipe/status_pipe.rs
+++ /dev/null
@@ -1,407 +0,0 @@
-/// 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)
- }
-}
diff --git a/usbh/src/usbproto.rs b/usbh/src/usbproto.rs
deleted file mode 100644
index 33bc28c..0000000
--- a/usbh/src/usbproto.rs
+++ /dev/null
@@ -1,438 +0,0 @@
-/// USB Protocol level types and functions.
-///
-/// Everything in here is defined by the USB specification, and
-/// hardware independent.
-use core::convert::TryFrom;
-use core::convert::TryInto;
-
-// TODO: Put protocol section references in for types and
-// documentation.
-
-#[derive(Copy, Clone, Debug, Default, PartialEq)]
-#[repr(C, packed)]
-pub struct DeviceDescriptor {
- pub b_length: u8,
- pub b_descriptor_type: DescriptorType,
- 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, PartialEq)]
-#[repr(C, packed)]
-pub struct ConfigurationDescriptor {
- pub b_length: u8,
- pub b_descriptor_type: DescriptorType,
- 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, PartialEq)]
-#[repr(C, packed)]
-pub struct InterfaceDescriptor {
- pub b_length: u8,
- pub b_descriptor_type: DescriptorType,
- 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, PartialEq)]
-#[repr(C, packed)]
-pub struct EndpointDescriptor {
- pub b_length: u8,
- pub b_descriptor_type: DescriptorType,
- pub b_endpoint_address: u8,
- pub bm_attributes: u8,
- pub w_max_packet_size: u16,
- pub b_interval: u8,
-}
-
-#[derive(Copy, Clone, Debug, Default, PartialEq)]
-#[repr(C, packed)]
-pub struct SetupPacket {
- pub bm_request_type: RequestType,
- pub b_request: RequestCode,
- pub w_value: WValue,
- pub w_index: u16,
- pub w_length: u16,
-}
-
-#[derive(Clone, Copy, Debug, Default, PartialEq)]
-#[repr(C)]
-pub struct RequestType(u8);
-impl RequestType {
- // Get descriptor request type.
- pub fn get_descr() -> Self {
- Self::from((
- RequestDirection::DeviceToHost,
- RequestKind::Standard,
- RequestRecipient::Device,
- ))
- }
-
- // Set request type for all but 'set feature' and 'set interface'.
- pub fn set() -> Self {
- Self::from((
- RequestDirection::HostToDevice,
- RequestKind::Standard,
- RequestRecipient::Device,
- ))
- }
-
- // Get interface request type.
- pub fn cl_get_intf() -> Self {
- Self::from((
- RequestDirection::DeviceToHost,
- RequestKind::Class,
- RequestRecipient::Interface,
- ))
- }
-
- pub fn recipient(&self) -> Result<RequestRecipient, &'static str> {
- const POS: u8 = 0;
- const MASK: u8 = 0x1f;
- (self.0 & (MASK << POS)).try_into()
- }
-
- pub fn set_recipient(&mut self, v: RequestRecipient) {
- const POS: u8 = 0;
- const MASK: u8 = 0x1f;
- self.0 &= !(MASK << POS);
- self.0 |= v as u8 & MASK;
- }
-
- pub fn kind(&self) -> Result<RequestKind, &'static str> {
- const POS: u8 = 5;
- const MASK: u8 = 0x3;
- (self.0 & (MASK << POS)).try_into()
- }
-
- pub fn set_kind(&mut self, v: RequestKind) {
- const POS: u8 = 5;
- const MASK: u8 = 0x3;
- self.0 &= !(MASK << POS);
- self.0 |= v as u8 & MASK;
- }
-
- pub fn direction(&self) -> Result<RequestDirection, &'static str> {
- const POS: u8 = 7;
- const MASK: u8 = 0x1;
- (self.0 & (MASK << POS)).try_into()
- }
-
- pub fn set_direction(&mut self, v: RequestDirection) {
- const POS: u8 = 7;
- const MASK: u8 = 0x1;
- self.0 &= !(MASK << POS);
- self.0 |= v as u8 & MASK;
- }
-}
-impl From<(RequestDirection, RequestKind, RequestRecipient)> for RequestType {
- fn from(v: (RequestDirection, RequestKind, RequestRecipient)) -> Self {
- Self(v.0 as u8 | v.1 as u8 | v.2 as u8)
- }
-}
-
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum RequestDirection {
- HostToDevice = 0x00,
- DeviceToHost = 0x80,
-}
-impl TryFrom<u8> for RequestDirection {
- type Error = &'static str;
-
- fn try_from(v: u8) -> Result<Self, Self::Error> {
- match v {
- 0x00 => Ok(Self::HostToDevice),
- 0x80 => Ok(Self::DeviceToHost),
- _ => Err("direction can only be 0x00 or 0x80"),
- }
- }
-}
-
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum RequestKind {
- Standard = 0x00,
- Class = 0x20,
- Vendor = 0x40,
-}
-impl TryFrom<u8> for RequestKind {
- type Error = &'static str;
-
- fn try_from(v: u8) -> Result<Self, Self::Error> {
- match v {
- 0x00 => Ok(Self::Standard),
- 0x20 => Ok(Self::Class),
- 0x40 => Ok(Self::Vendor),
- _ => Err("type can only be 0x00, 0x20, or 0x40"),
- }
- }
-}
-
-#[derive(Copy, Clone, Debug, PartialEq)]
-pub enum RequestRecipient {
- Device = 0x00,
- Interface = 0x01,
- Endpoint = 0x02,
- Other = 0x03,
-}
-impl TryFrom<u8> for RequestRecipient {
- type Error = &'static str;
-
- fn try_from(v: u8) -> Result<Self, Self::Error> {
- match v {
- 0x00 => Ok(Self::Device),
- 0x01 => Ok(Self::Interface),
- 0x02 => Ok(Self::Endpoint),
- 0x03 => Ok(Self::Other),
- _ => Err("recipient can only be between 0 and 3"),
- }
- }
-}
-
-#[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 RequestCode {
- GetStatus = 0,
- ClearFeature = 1,
- SetFeature = 3,
- SetAddress = 5,
- GetDescriptor = 6,
- SetDescriptor = 7,
- GetConfiguration = 8,
- SetConfiguration = 9,
- GetInterface = 10,
- SetInterface = 11,
- SynchFrame = 12,
-}
-impl TryFrom<u8> for RequestCode {
- type Error = &'static str;
-
- fn try_from(v: u8) -> Result<Self, Self::Error> {
- match v {
- 0 => Ok(Self::GetStatus),
- 1 => Ok(Self::ClearFeature),
- 3 => Ok(Self::SetFeature),
- 5 => Ok(Self::SetAddress),
- 6 => Ok(Self::GetDescriptor),
- 7 => Ok(Self::SetDescriptor),
- 8 => Ok(Self::GetConfiguration),
- 9 => Ok(Self::SetConfiguration),
- 10 => Ok(Self::GetInterface),
- 11 => Ok(Self::SetInterface),
- 12 => Ok(Self::SynchFrame),
- _ => Err("invalid request value"),
- }
- }
-}
-impl Default for RequestCode {
- fn default() -> Self {
- Self::GetStatus
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum USBFeature {
- EndpointHalt = 0,
- DeviceRemoteWakeup = 1,
- TestMode = 2,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub enum DescriptorType {
- Device = 1,
- Configuration = 2,
- String = 3,
- Interface = 4,
- Endpoint = 5,
- DeviceQualifier = 6,
- OtherSpeed = 7,
- InterfacePower = 8,
-}
-impl Default for DescriptorType {
- fn default() -> Self {
- Self::Device
- }
-}
-
-#[cfg(test)]
-mod test {
- use super::*;
-
- #[test]
- fn dev_desc_serialize() {
- let desc = DeviceDescriptor {
- b_length: 18,
- b_descriptor_type: DescriptorType::Device,
- bcd_usb: 0x0110,
- b_device_class: 0x02,
- b_device_sub_class: 0x03,
- b_device_protocol: 0x04,
- b_max_packet_size: 64,
- id_vendor: 0xdead,
- id_product: 0xbeef,
- bcd_device: 0x5432,
- i_manufacturer: 0xa0,
- i_product: 0xa1,
- i_serial_number: 0xa2,
- b_num_configurations: 1,
- };
- let want = [
- 0x12, 0x01, 0x10, 0x01, 0x02, 0x03, 0x04, 64, 0xad, 0xde, 0xef, 0xbe, 0x32, 0x54, 0xa0,
- 0xa1, 0xa2, 1,
- ];
-
- serde_test(&desc, &want);
- }
-
- #[test]
- fn config_desc_serialize() {
- let desc = ConfigurationDescriptor {
- b_length: 18,
- b_descriptor_type: DescriptorType::Configuration,
- w_total_length: 0x20,
- b_num_interfaces: 5,
- b_configuration_value: 10,
- i_configuration: 1,
- bm_attributes: 0x40,
- b_max_power: 0xfa,
- };
- let want = [0x12, 0x02, 0x20, 0x00, 0x05, 0x0a, 0x01, 0x40, 0xfa];
-
- serde_test(&desc, &want);
- }
-
- #[test]
- fn interface_desc_serialize() {
- let desc = InterfaceDescriptor {
- b_length: 18,
- b_descriptor_type: DescriptorType::Interface,
- b_interface_number: 2,
- b_alternate_setting: 0xaa,
- b_num_endpoints: 5,
- b_interface_class: 0x11,
- b_interface_sub_class: 0x22,
- b_interface_protocol: 0x33,
- i_interface: 10,
- };
- let want = [0x12, 0x04, 0x02, 0xaa, 0x05, 0x11, 0x22, 0x33, 0x0a];
-
- serde_test(&desc, &want);
- }
-
- #[test]
- fn endpoint_desc_serialize() {
- let desc = EndpointDescriptor {
- b_length: 18,
- b_descriptor_type: DescriptorType::Endpoint,
- b_endpoint_address: 1,
- bm_attributes: 0x22,
- w_max_packet_size: 0xdead,
- b_interval: 0x33,
- };
- let want = [0x12, 0x05, 0x01, 0x22, 0xad, 0xde, 0x33];
-
- serde_test(&desc, &want);
- }
-
- #[test]
- fn setup_packet_serialize() {
- let setup_packet = SetupPacket {
- bm_request_type: RequestType::get_descr(),
- b_request: RequestCode::GetDescriptor,
- w_value: WValue::from((0x00, 0x01)),
- w_index: 0xbeef,
- w_length: 18,
- };
- let want = [0x80, 0x06, 0x00, 0x01, 0xef, 0xbe, 0x012, 0x00];
-
- serde_test(&setup_packet, &want);
- }
-
- fn serde_test<T>(native: &T, raw: &[u8])
- where
- T: Default + PartialEq + core::fmt::Debug,
- {
- ser_test(native, raw);
- de_test(raw, native);
- }
-
- fn ser_test<T>(native: &T, raw: &[u8]) {
- let ptr = native as *const T as *const u8;
- let len = core::mem::size_of::<T>();
- assert_eq!(len, raw.len());
- let got_raw = unsafe { core::slice::from_raw_parts(ptr, len) };
- assert_eq!(got_raw, raw);
- }
-
- fn de_test<T>(raw: &[u8], native: &T)
- where
- T: Default + PartialEq + core::fmt::Debug,
- {
- let mut got_native: T = Default::default();
- let ptr = &mut got_native as *mut T as *mut u8;
- let len = core::mem::size_of::<T>();
- assert_eq!(raw.len(), len);
- let dbslice = unsafe { core::slice::from_raw_parts_mut(ptr, len) };
- for i in 0..len {
- dbslice[i] = raw[i];
- }
- assert_eq!(got_native, *native);
- }
-}