Add support for USB classes handling control requests.

This commit is contained in:
alexmoon
2022-03-25 16:46:14 -04:00
committed by Dario Nieuwenhuis
parent 5c0db627fe
commit bdc6e0481c
8 changed files with 703 additions and 291 deletions

View File

@ -1,16 +1,19 @@
#![no_std]
#![feature(generic_associated_types)]
#![feature(type_alias_impl_trait)]
// This mod MUST go first, so that the others see its macros.
pub(crate) mod fmt;
mod builder;
mod control;
pub mod class;
pub mod control;
pub mod descriptor;
pub mod driver;
pub mod types;
mod util;
use self::class::{RequestStatus, UsbClass};
use self::control::*;
use self::descriptor::*;
use self::driver::*;
@ -48,10 +51,9 @@ pub const CONFIGURATION_VALUE: u8 = 1;
/// The default value for bAlternateSetting for all interfaces.
pub const DEFAULT_ALTERNATE_SETTING: u8 = 0;
pub struct UsbDevice<'d, D: Driver<'d>> {
pub struct UsbDevice<'d, D: Driver<'d>, C: UsbClass<'d, D>> {
bus: D::Bus,
control_in: D::EndpointIn,
control_out: D::EndpointOut,
control: D::ControlPipe,
config: Config<'d>,
device_descriptor: &'d [u8],
@ -62,32 +64,21 @@ pub struct UsbDevice<'d, D: Driver<'d>> {
remote_wakeup_enabled: bool,
self_powered: bool,
pending_address: u8,
classes: C,
}
impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
impl<'d, D: Driver<'d>, C: UsbClass<'d, D>> UsbDevice<'d, D, C> {
pub(crate) fn build(
mut driver: D,
config: Config<'d>,
device_descriptor: &'d [u8],
config_descriptor: &'d [u8],
bos_descriptor: &'d [u8],
classes: C,
) -> Self {
let control_out = driver
.alloc_endpoint_out(
Some(0x00.into()),
EndpointType::Control,
config.max_packet_size_0 as u16,
0,
)
.expect("failed to alloc control endpoint");
let control_in = driver
.alloc_endpoint_in(
Some(0x80.into()),
EndpointType::Control,
config.max_packet_size_0 as u16,
0,
)
let control = driver
.alloc_control_pipe(config.max_packet_size_0 as u16)
.expect("failed to alloc control endpoint");
// Enable the USB bus.
@ -97,8 +88,7 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
Self {
bus: driver,
config,
control_in,
control_out,
control,
device_descriptor,
config_descriptor,
bos_descriptor,
@ -106,14 +96,13 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
remote_wakeup_enabled: false,
self_powered: false,
pending_address: 0,
classes,
}
}
pub async fn run(&mut self) {
let mut buf = [0; 8];
loop {
let control_fut = self.control_out.read(&mut buf);
let control_fut = self.control.setup();
let bus_fut = self.bus.poll();
match select(bus_fut, control_fut).await {
Either::Left(evt) => match evt {
@ -124,11 +113,7 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
self.remote_wakeup_enabled = false;
self.pending_address = 0;
// TODO
//self.control.reset();
//for cls in classes {
// cls.reset();
//}
self.classes.reset();
}
Event::Resume => {}
Event::Suspend => {
@ -136,16 +121,9 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
self.device_state = UsbDeviceState::Suspend;
}
},
Either::Right(n) => {
let n = n.unwrap();
assert_eq!(n, 8);
let req = Request::parse(&buf).unwrap();
Either::Right(req) => {
info!("control request: {:x}", req);
// Now that we have properly parsed the setup packet, ensure the end-point is no longer in
// a stalled state.
self.control_out.set_stalled(false);
match req.direction {
UsbDirection::In => self.handle_control_in(req).await,
UsbDirection::Out => self.handle_control_out(req).await,
@ -155,36 +133,6 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
}
}
async fn write_chunked(&mut self, data: &[u8]) -> Result<(), driver::WriteError> {
for c in data.chunks(8) {
self.control_in.write(c).await?;
}
if data.len() % 8 == 0 {
self.control_in.write(&[]).await?;
}
Ok(())
}
async fn control_out_accept(&mut self, req: Request) {
info!("control out accept");
// status phase
// todo: cleanup
self.control_out.read(&mut []).await.unwrap();
}
async fn control_in_accept(&mut self, req: Request, data: &[u8]) {
info!("control accept {:x}", data);
let len = data.len().min(req.length as _);
if let Err(e) = self.write_chunked(&data[..len]).await {
info!("write_chunked failed: {:?}", e);
}
// status phase
// todo: cleanup
self.control_out.read(&mut []).await.unwrap();
}
async fn control_in_accept_writer(
&mut self,
req: Request,
@ -193,17 +141,26 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
let mut buf = [0; 256];
let mut w = DescriptorWriter::new(&mut buf);
f(&mut w);
let pos = w.position();
self.control_in_accept(req, &buf[..pos]).await;
}
fn control_reject(&mut self, req: Request) {
info!("control reject");
self.control_out.set_stalled(true);
let pos = w.position().min(usize::from(req.length));
self.control.accept_in(&buf[..pos]).await;
}
async fn handle_control_out(&mut self, req: Request) {
// TODO actually read the data if there's an OUT data phase.
{
let mut buf = [0; 128];
let data = if req.length > 0 {
let size = self.control.data_out(&mut buf).await.unwrap();
&buf[0..size]
} else {
&[]
};
match self.classes.control_out(req, data).await {
RequestStatus::Accepted => return self.control.accept(),
RequestStatus::Rejected => return self.control.reject(),
RequestStatus::Unhandled => (),
}
}
const CONFIGURATION_NONE_U16: u16 = CONFIGURATION_NONE as u16;
const CONFIGURATION_VALUE_U16: u16 = CONFIGURATION_VALUE as u16;
@ -217,12 +174,12 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
Request::FEATURE_DEVICE_REMOTE_WAKEUP,
) => {
self.remote_wakeup_enabled = false;
self.control_out_accept(req).await;
self.control.accept();
}
(Recipient::Endpoint, Request::CLEAR_FEATURE, Request::FEATURE_ENDPOINT_HALT) => {
//self.bus.set_stalled(((req.index as u8) & 0x8f).into(), false);
self.control_out_accept(req).await;
self.control.accept();
}
(
@ -231,51 +188,61 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
Request::FEATURE_DEVICE_REMOTE_WAKEUP,
) => {
self.remote_wakeup_enabled = true;
self.control_out_accept(req).await;
self.control.accept();
}
(Recipient::Endpoint, Request::SET_FEATURE, Request::FEATURE_ENDPOINT_HALT) => {
self.bus
.set_stalled(((req.index as u8) & 0x8f).into(), true);
self.control_out_accept(req).await;
self.control.accept();
}
(Recipient::Device, Request::SET_ADDRESS, 1..=127) => {
self.pending_address = req.value as u8;
// on NRF the hardware auto-handles SET_ADDRESS.
self.control_out_accept(req).await;
self.control.accept();
}
(Recipient::Device, Request::SET_CONFIGURATION, CONFIGURATION_VALUE_U16) => {
self.device_state = UsbDeviceState::Configured;
self.control_out_accept(req).await;
self.control.accept();
}
(Recipient::Device, Request::SET_CONFIGURATION, CONFIGURATION_NONE_U16) => {
match self.device_state {
UsbDeviceState::Default => {
self.control_out_accept(req).await;
self.control.accept();
}
_ => {
self.device_state = UsbDeviceState::Addressed;
self.control_out_accept(req).await;
self.control.accept();
}
}
}
(Recipient::Interface, Request::SET_INTERFACE, DEFAULT_ALTERNATE_SETTING_U16) => {
// TODO: do something when alternate settings are implemented
self.control_out_accept(req).await;
self.control.accept();
}
_ => self.control_reject(req),
_ => self.control.reject(),
},
_ => self.control_reject(req),
_ => self.control.reject(),
}
}
async fn handle_control_in(&mut self, req: Request) {
match self
.classes
.control_in(req, class::ControlIn::new(&mut self.control))
.await
.status()
{
RequestStatus::Accepted | RequestStatus::Rejected => return,
RequestStatus::Unhandled => (),
}
match req.request_type {
RequestType::Standard => match (req.recipient, req.request) {
(Recipient::Device, Request::GET_STATUS) => {
@ -286,12 +253,12 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
if self.remote_wakeup_enabled {
status |= 0x0002;
}
self.control_in_accept(req, &status.to_le_bytes()).await;
self.control.accept_in(&status.to_le_bytes()).await;
}
(Recipient::Interface, Request::GET_STATUS) => {
let status: u16 = 0x0000;
self.control_in_accept(req, &status.to_le_bytes()).await;
self.control.accept_in(&status.to_le_bytes()).await;
}
(Recipient::Endpoint, Request::GET_STATUS) => {
@ -300,7 +267,7 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
if self.bus.is_stalled(ep_addr) {
status |= 0x0001;
}
self.control_in_accept(req, &status.to_le_bytes()).await;
self.control.accept_in(&status.to_le_bytes()).await;
}
(Recipient::Device, Request::GET_DESCRIPTOR) => {
@ -312,17 +279,17 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
UsbDeviceState::Configured => CONFIGURATION_VALUE,
_ => CONFIGURATION_NONE,
};
self.control_in_accept(req, &status.to_le_bytes()).await;
self.control.accept_in(&status.to_le_bytes()).await;
}
(Recipient::Interface, Request::GET_INTERFACE) => {
// TODO: change when alternate settings are implemented
let status = DEFAULT_ALTERNATE_SETTING;
self.control_in_accept(req, &status.to_le_bytes()).await;
self.control.accept_in(&status.to_le_bytes()).await;
}
_ => self.control_reject(req),
_ => self.control.reject(),
},
_ => self.control_reject(req),
_ => self.control.reject(),
}
}
@ -331,11 +298,9 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
let config = self.config.clone();
match dtype {
descriptor_type::BOS => self.control_in_accept(req, self.bos_descriptor).await,
descriptor_type::DEVICE => self.control_in_accept(req, self.device_descriptor).await,
descriptor_type::CONFIGURATION => {
self.control_in_accept(req, self.config_descriptor).await
}
descriptor_type::BOS => self.control.accept_in(self.bos_descriptor).await,
descriptor_type::DEVICE => self.control.accept_in(self.device_descriptor).await,
descriptor_type::CONFIGURATION => self.control.accept_in(self.config_descriptor).await,
descriptor_type::STRING => {
if index == 0 {
self.control_in_accept_writer(req, |w| {
@ -363,11 +328,11 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
self.control_in_accept_writer(req, |w| w.string(s).unwrap())
.await;
} else {
self.control_reject(req)
self.control.reject()
}
}
}
_ => self.control_reject(req),
_ => self.control.reject(),
}
}
}