usb: cleanup and simplify error handling.

This commit is contained in:
Dario Nieuwenhuis 2022-03-30 02:01:09 +02:00
parent 60d3d11197
commit a435d78cf7
5 changed files with 91 additions and 131 deletions

View File

@ -403,11 +403,9 @@ unsafe fn read_dma<T: Instance>(i: usize, buf: &mut [u8]) -> Result<usize, ReadE
Ok(size) Ok(size)
} }
unsafe fn write_dma<T: Instance>(i: usize, buf: &[u8]) -> Result<(), WriteError> { unsafe fn write_dma<T: Instance>(i: usize, buf: &[u8]) {
let regs = T::regs(); let regs = T::regs();
if buf.len() > 64 { assert!(buf.len() <= 64);
return Err(WriteError::BufferOverflow);
}
let mut ram_buf: MaybeUninit<[u8; 64]> = MaybeUninit::uninit(); let mut ram_buf: MaybeUninit<[u8; 64]> = MaybeUninit::uninit();
let ptr = if !slice_in_ram(buf) { let ptr = if !slice_in_ram(buf) {
@ -441,8 +439,6 @@ unsafe fn write_dma<T: Instance>(i: usize, buf: &[u8]) -> Result<(), WriteError>
regs.tasks_startepin[i].write(|w| w.bits(1)); regs.tasks_startepin[i].write(|w| w.bits(1));
while regs.events_endepin[i].read().bits() == 0 {} while regs.events_endepin[i].read().bits() == 0 {}
dma_end(); dma_end();
Ok(())
} }
impl<'d, T: Instance> driver::EndpointOut for Endpoint<'d, T, Out> { impl<'d, T: Instance> driver::EndpointOut for Endpoint<'d, T, Out> {
@ -497,6 +493,8 @@ impl<'d, T: Instance> driver::EndpointIn for Endpoint<'d, T, In> {
READY_ENDPOINTS.fetch_and(!(1 << i), Ordering::AcqRel); READY_ENDPOINTS.fetch_and(!(1 << i), Ordering::AcqRel);
unsafe { write_dma::<T>(i, buf) } unsafe { write_dma::<T>(i, buf) }
Ok(())
} }
} }
} }
@ -535,9 +533,7 @@ impl<'d, T: Instance> ControlPipe<'d, T> {
async fn write(&mut self, buf: &[u8], last_chunk: bool) { async fn write(&mut self, buf: &[u8], last_chunk: bool) {
let regs = T::regs(); let regs = T::regs();
regs.events_ep0datadone.reset(); regs.events_ep0datadone.reset();
unsafe { unsafe { write_dma::<T>(0, buf) }
write_dma::<T>(0, buf).unwrap();
}
regs.shorts regs.shorts
.modify(|_, w| w.ep0datadone_ep0status().bit(last_chunk)); .modify(|_, w| w.ep0datadone_ep0status().bit(last_chunk));
@ -616,7 +612,7 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> {
fn data_out<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::DataOutFuture<'a> { fn data_out<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::DataOutFuture<'a> {
async move { async move {
let req = self.request.unwrap(); let req = unwrap!(self.request);
assert!(req.direction == UsbDirection::Out); assert!(req.direction == UsbDirection::Out);
assert!(req.length > 0); assert!(req.length > 0);
@ -649,7 +645,7 @@ impl<'d, T: Instance> driver::ControlPipe for ControlPipe<'d, T> {
debug!("control in accept {:x}", buf); debug!("control in accept {:x}", buf);
#[cfg(not(feature = "defmt"))] #[cfg(not(feature = "defmt"))]
debug!("control in accept {:x?}", buf); debug!("control in accept {:x?}", buf);
let req = self.request.unwrap(); let req = unwrap!(self.request);
assert!(req.direction == UsbDirection::In); assert!(req.direction == UsbDirection::In);
let req_len = usize::from(req.length); let req_len = usize::from(req.length);

View File

@ -184,78 +184,57 @@ impl<'d, D: Driver<'d>> CdcAcmClass<'d, D> {
let read_ep = builder.alloc_bulk_endpoint_out(max_packet_size); let read_ep = builder.alloc_bulk_endpoint_out(max_packet_size);
let write_ep = builder.alloc_bulk_endpoint_in(max_packet_size); let write_ep = builder.alloc_bulk_endpoint_in(max_packet_size);
builder builder.config_descriptor.iad(
.config_descriptor
.iad(
comm_if, comm_if,
2, 2,
USB_CLASS_CDC, USB_CLASS_CDC,
CDC_SUBCLASS_ACM, CDC_SUBCLASS_ACM,
CDC_PROTOCOL_NONE, CDC_PROTOCOL_NONE,
) );
.unwrap(); builder.config_descriptor.interface(
comm_if,
builder USB_CLASS_CDC,
.config_descriptor CDC_SUBCLASS_ACM,
.interface(comm_if, USB_CLASS_CDC, CDC_SUBCLASS_ACM, CDC_PROTOCOL_NONE) CDC_PROTOCOL_NONE,
.unwrap(); );
builder.config_descriptor.write(
builder
.config_descriptor
.write(
CS_INTERFACE, CS_INTERFACE,
&[ &[
CDC_TYPE_HEADER, // bDescriptorSubtype CDC_TYPE_HEADER, // bDescriptorSubtype
0x10, 0x10,
0x01, // bcdCDC (1.10) 0x01, // bcdCDC (1.10)
], ],
) );
.unwrap(); builder.config_descriptor.write(
builder
.config_descriptor
.write(
CS_INTERFACE, CS_INTERFACE,
&[ &[
CDC_TYPE_ACM, // bDescriptorSubtype CDC_TYPE_ACM, // bDescriptorSubtype
0x00, // bmCapabilities 0x00, // bmCapabilities
], ],
) );
.unwrap(); builder.config_descriptor.write(
builder
.config_descriptor
.write(
CS_INTERFACE, CS_INTERFACE,
&[ &[
CDC_TYPE_UNION, // bDescriptorSubtype CDC_TYPE_UNION, // bDescriptorSubtype
comm_if.into(), // bControlInterface comm_if.into(), // bControlInterface
data_if.into(), // bSubordinateInterface data_if.into(), // bSubordinateInterface
], ],
) );
.unwrap(); builder.config_descriptor.write(
builder
.config_descriptor
.write(
CS_INTERFACE, CS_INTERFACE,
&[ &[
CDC_TYPE_CALL_MANAGEMENT, // bDescriptorSubtype CDC_TYPE_CALL_MANAGEMENT, // bDescriptorSubtype
0x00, // bmCapabilities 0x00, // bmCapabilities
data_if.into(), // bDataInterface data_if.into(), // bDataInterface
], ],
) );
.unwrap(); builder.config_descriptor.endpoint(comm_ep.info());
builder.config_descriptor.endpoint(comm_ep.info()).unwrap();
builder builder
.config_descriptor .config_descriptor
.interface(data_if, USB_CLASS_CDC_DATA, 0x00, 0x00) .interface(data_if, USB_CLASS_CDC_DATA, 0x00, 0x00);
.unwrap(); builder.config_descriptor.endpoint(write_ep.info());
builder.config_descriptor.endpoint(read_ep.info());
builder.config_descriptor.endpoint(write_ep.info()).unwrap();
builder.config_descriptor.endpoint(read_ep.info()).unwrap();
CdcAcmClass { CdcAcmClass {
comm_ep, comm_ep,

View File

@ -168,9 +168,9 @@ impl<'d, D: Driver<'d>> UsbDeviceBuilder<'d, D> {
let mut config_descriptor = DescriptorWriter::new(config_descriptor_buf); let mut config_descriptor = DescriptorWriter::new(config_descriptor_buf);
let mut bos_descriptor = BosWriter::new(DescriptorWriter::new(bos_descriptor_buf)); let mut bos_descriptor = BosWriter::new(DescriptorWriter::new(bos_descriptor_buf));
device_descriptor.device(&config).unwrap(); device_descriptor.device(&config);
config_descriptor.configuration(&config).unwrap(); config_descriptor.configuration(&config);
bos_descriptor.bos().unwrap(); bos_descriptor.bos();
UsbDeviceBuilder { UsbDeviceBuilder {
bus, bus,

View File

@ -1,13 +1,6 @@
use super::builder::Config; use super::builder::Config;
use super::{types::*, CONFIGURATION_VALUE, DEFAULT_ALTERNATE_SETTING}; use super::{types::*, CONFIGURATION_VALUE, DEFAULT_ALTERNATE_SETTING};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
BufferFull,
InvalidState,
}
/// Standard descriptor types /// Standard descriptor types
#[allow(missing_docs)] #[allow(missing_docs)]
pub mod descriptor_type { pub mod descriptor_type {
@ -69,11 +62,11 @@ impl<'a> DescriptorWriter<'a> {
} }
/// Writes an arbitrary (usually class-specific) descriptor. /// Writes an arbitrary (usually class-specific) descriptor.
pub fn write(&mut self, descriptor_type: u8, descriptor: &[u8]) -> Result<(), Error> { pub fn write(&mut self, descriptor_type: u8, descriptor: &[u8]) {
let length = descriptor.len(); let length = descriptor.len();
if (self.position + 2 + length) > self.buf.len() || (length + 2) > 255 { if (self.position + 2 + length) > self.buf.len() || (length + 2) > 255 {
return Err(Error::BufferFull); panic!("Descriptor buffer full");
} }
self.buf[self.position] = (length + 2) as u8; self.buf[self.position] = (length + 2) as u8;
@ -84,11 +77,9 @@ impl<'a> DescriptorWriter<'a> {
self.buf[start..start + length].copy_from_slice(descriptor); self.buf[start..start + length].copy_from_slice(descriptor);
self.position = start + length; self.position = start + length;
Ok(())
} }
pub(crate) fn device(&mut self, config: &Config) -> Result<(), Error> { pub(crate) fn device(&mut self, config: &Config) {
self.write( self.write(
descriptor_type::DEVICE, descriptor_type::DEVICE,
&[ &[
@ -112,7 +103,7 @@ impl<'a> DescriptorWriter<'a> {
) )
} }
pub(crate) fn configuration(&mut self, config: &Config) -> Result<(), Error> { pub(crate) fn configuration(&mut self, config: &Config) {
self.num_interfaces_mark = Some(self.position + 4); self.num_interfaces_mark = Some(self.position + 4);
self.write_iads = config.composite_with_iads; self.write_iads = config.composite_with_iads;
@ -168,9 +159,9 @@ impl<'a> DescriptorWriter<'a> {
function_class: u8, function_class: u8,
function_sub_class: u8, function_sub_class: u8,
function_protocol: u8, function_protocol: u8,
) -> Result<(), Error> { ) {
if !self.write_iads { if !self.write_iads {
return Ok(()); return;
} }
self.write( self.write(
@ -183,9 +174,7 @@ impl<'a> DescriptorWriter<'a> {
function_protocol, function_protocol,
0, 0,
], ],
)?; );
Ok(())
} }
/// Writes a interface descriptor. /// Writes a interface descriptor.
@ -204,7 +193,7 @@ impl<'a> DescriptorWriter<'a> {
interface_class: u8, interface_class: u8,
interface_sub_class: u8, interface_sub_class: u8,
interface_protocol: u8, interface_protocol: u8,
) -> Result<(), Error> { ) {
self.interface_alt( self.interface_alt(
number, number,
DEFAULT_ALTERNATE_SETTING, DEFAULT_ALTERNATE_SETTING,
@ -237,11 +226,13 @@ impl<'a> DescriptorWriter<'a> {
interface_sub_class: u8, interface_sub_class: u8,
interface_protocol: u8, interface_protocol: u8,
interface_string: Option<StringIndex>, interface_string: Option<StringIndex>,
) -> Result<(), Error> { ) {
if alternate_setting == DEFAULT_ALTERNATE_SETTING { if alternate_setting == DEFAULT_ALTERNATE_SETTING {
match self.num_interfaces_mark { match self.num_interfaces_mark {
Some(mark) => self.buf[mark] += 1, Some(mark) => self.buf[mark] += 1,
None => return Err(Error::InvalidState), None => {
panic!("you can only call `interface/interface_alt` after `configuration`.")
}
}; };
} }
@ -260,9 +251,7 @@ impl<'a> DescriptorWriter<'a> {
interface_protocol, // bInterfaceProtocol interface_protocol, // bInterfaceProtocol
str_index, // iInterface str_index, // iInterface
], ],
)?; );
Ok(())
} }
/// Writes an endpoint descriptor. /// Writes an endpoint descriptor.
@ -271,10 +260,10 @@ impl<'a> DescriptorWriter<'a> {
/// ///
/// * `endpoint` - Endpoint previously allocated with /// * `endpoint` - Endpoint previously allocated with
/// [`UsbDeviceBuilder`](crate::bus::UsbDeviceBuilder). /// [`UsbDeviceBuilder`](crate::bus::UsbDeviceBuilder).
pub fn endpoint(&mut self, endpoint: &EndpointInfo) -> Result<(), Error> { pub fn endpoint(&mut self, endpoint: &EndpointInfo) {
match self.num_endpoints_mark { match self.num_endpoints_mark {
Some(mark) => self.buf[mark] += 1, Some(mark) => self.buf[mark] += 1,
None => return Err(Error::InvalidState), None => panic!("you can only call `endpoint` after `interface/interface_alt`."),
}; };
self.write( self.write(
@ -286,17 +275,15 @@ impl<'a> DescriptorWriter<'a> {
(endpoint.max_packet_size >> 8) as u8, // wMaxPacketSize (endpoint.max_packet_size >> 8) as u8, // wMaxPacketSize
endpoint.interval, // bInterval endpoint.interval, // bInterval
], ],
)?; );
Ok(())
} }
/// Writes a string descriptor. /// Writes a string descriptor.
pub(crate) fn string(&mut self, string: &str) -> Result<(), Error> { pub(crate) fn string(&mut self, string: &str) {
let mut pos = self.position; let mut pos = self.position;
if pos + 2 > self.buf.len() { if pos + 2 > self.buf.len() {
return Err(Error::BufferFull); panic!("Descriptor buffer full");
} }
self.buf[pos] = 0; // length placeholder self.buf[pos] = 0; // length placeholder
@ -306,7 +293,7 @@ impl<'a> DescriptorWriter<'a> {
for c in string.encode_utf16() { for c in string.encode_utf16() {
if pos >= self.buf.len() { if pos >= self.buf.len() {
return Err(Error::BufferFull); panic!("Descriptor buffer full");
} }
self.buf[pos..pos + 2].copy_from_slice(&c.to_le_bytes()); self.buf[pos..pos + 2].copy_from_slice(&c.to_le_bytes());
@ -316,8 +303,6 @@ impl<'a> DescriptorWriter<'a> {
self.buf[self.position] = (pos - self.position) as u8; self.buf[self.position] = (pos - self.position) as u8;
self.position = pos; self.position = pos;
Ok(())
} }
} }
@ -335,7 +320,7 @@ impl<'a> BosWriter<'a> {
} }
} }
pub(crate) fn bos(&mut self) -> Result<(), Error> { pub(crate) fn bos(&mut self) {
self.num_caps_mark = Some(self.writer.position + 4); self.num_caps_mark = Some(self.writer.position + 4);
self.writer.write( self.writer.write(
descriptor_type::BOS, descriptor_type::BOS,
@ -343,11 +328,9 @@ impl<'a> BosWriter<'a> {
0x00, 0x00, // wTotalLength 0x00, 0x00, // wTotalLength
0x00, // bNumDeviceCaps 0x00, // bNumDeviceCaps
], ],
)?; );
self.capability(capability_type::USB_2_0_EXTENSION, &[0; 4])?; self.capability(capability_type::USB_2_0_EXTENSION, &[0; 4]);
Ok(())
} }
/// Writes capability descriptor to a BOS /// Writes capability descriptor to a BOS
@ -356,17 +339,17 @@ impl<'a> BosWriter<'a> {
/// ///
/// * `capability_type` - Type of a capability /// * `capability_type` - Type of a capability
/// * `data` - Binary data of the descriptor /// * `data` - Binary data of the descriptor
pub fn capability(&mut self, capability_type: u8, data: &[u8]) -> Result<(), Error> { pub fn capability(&mut self, capability_type: u8, data: &[u8]) {
match self.num_caps_mark { match self.num_caps_mark {
Some(mark) => self.writer.buf[mark] += 1, Some(mark) => self.writer.buf[mark] += 1,
None => return Err(Error::InvalidState), None => panic!("called `capability` not between `bos` and `end_bos`."),
} }
let mut start = self.writer.position; let mut start = self.writer.position;
let blen = data.len(); let blen = data.len();
if (start + blen + 3) > self.writer.buf.len() || (blen + 3) > 255 { if (start + blen + 3) > self.writer.buf.len() || (blen + 3) > 255 {
return Err(Error::BufferFull); panic!("Descriptor buffer full");
} }
self.writer.buf[start] = (blen + 3) as u8; self.writer.buf[start] = (blen + 3) as u8;
@ -376,8 +359,6 @@ impl<'a> BosWriter<'a> {
start += 3; start += 3;
self.writer.buf[start..start + blen].copy_from_slice(data); self.writer.buf[start..start + blen].copy_from_slice(data);
self.writer.position = start + blen; self.writer.position = start + blen;
Ok(())
} }
pub(crate) fn end_bos(&mut self) { pub(crate) fn end_bos(&mut self) {

View File

@ -158,7 +158,13 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
// If the request has a data state, we must read it. // If the request has a data state, we must read it.
let data = if req.length > 0 { let data = if req.length > 0 {
let size = self.control.data_out(self.control_buf).await.unwrap(); let size = match self.control.data_out(self.control_buf).await {
Ok(size) => size,
Err(_) => {
warn!("usb: failed to read CONTROL OUT data stage.");
return;
}
};
&self.control_buf[0..size] &self.control_buf[0..size]
} else { } else {
&[] &[]
@ -311,7 +317,6 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
if index == 0 { if index == 0 {
self.control_in_accept_writer(req, |w| { self.control_in_accept_writer(req, |w| {
w.write(descriptor_type::STRING, &lang_id::ENGLISH_US.to_le_bytes()) w.write(descriptor_type::STRING, &lang_id::ENGLISH_US.to_le_bytes())
.unwrap();
}) })
.await .await
} else { } else {
@ -328,8 +333,7 @@ impl<'d, D: Driver<'d>> UsbDevice<'d, D> {
}; };
if let Some(s) = s { if let Some(s) = s {
self.control_in_accept_writer(req, |w| w.string(s).unwrap()) self.control_in_accept_writer(req, |w| w.string(s)).await;
.await;
} else { } else {
self.control.reject() self.control.reject()
} }