some touch-up/cleanup; add a timeout on a blocking read

This commit is contained in:
bunnie 2023-01-12 01:45:51 +08:00
parent 1ec6bd7df4
commit bebf323798
15 changed files with 124 additions and 232 deletions

5
Cargo.lock generated
View file

@ -4326,13 +4326,14 @@ name = "usbd_bulk_only_transport"
version = "0.1.0"
dependencies = [
"embedded-hal",
"itm_logger",
"log",
"nb 0.1.3",
"packing 0.2.0",
"typenum",
"usb-device",
"usbd_mass_storage 0.1.0",
"xous 0.9.29 (registry+https://github.com/rust-lang/crates.io-index)",
"xous-api-ticktimer",
]
[[package]]
@ -4355,7 +4356,6 @@ name = "usbd_mass_storage"
version = "0.1.0"
dependencies = [
"embedded-hal",
"itm_logger",
"log",
"nb 0.1.3",
"packing 0.2.0",
@ -4399,7 +4399,6 @@ name = "usbd_scsi"
version = "0.1.1"
dependencies = [
"embedded-hal",
"itm_logger",
"log",
"nb 0.1.3",
"packing 0.2.0",

View file

@ -7,14 +7,14 @@ use self::proc_macro::TokenStream;
use quote::{ quote, format_ident };
use syn::{
spanned::Spanned,
Ident,
Ident,
Error,
parse_macro_input,
parse_macro_input,
Data,
DeriveInput,
Fields,
Attribute,
Path,
DeriveInput,
Fields,
Attribute,
Path,
Meta,
Lit,
NestedMeta,
@ -59,7 +59,7 @@ const PKD_ATTR: &str = "pkd";
///
/// Optional flags for `packed` attribute when used at the struct level:
///
/// | Name | Description |
/// | Name | Description |
/// |---------------|-------------|
/// | little_endian | (default) sets the struct default endianness to little endian |
/// | big_endian | sets the struct default endianness to big endian |
@ -80,7 +80,7 @@ const PKD_ATTR: &str = "pkd";
/// | space | (partially tested) The space before the field in bits. Allows shifting a field along by a number of bits | 0 |
///
/// Mandatory values for `pkd` attribute:
///
///
/// | Index | Description |
/// |-------|-------------|
/// | 0 | start_byte |
@ -114,7 +114,7 @@ pub fn packed_derive(input: TokenStream) -> TokenStream {
enum Attr {
Flag { name: Ident, span: Span },
Value { name: Ident, value: Lit, span: Span },
Lit { value: Lit, span: Span },
Lit { _value: Lit, span: Span },
}
impl Attr {
@ -143,12 +143,12 @@ fn flatten_attrs(attrs: &Vec<Attribute>) -> Result<Vec<Attr>, Error> {
if l.path.is_ident(PACKED_ATTR) {
for n in l.nested.iter() {
ret.push(match n {
NestedMeta::Meta(Meta::Path(p)) =>
NestedMeta::Meta(Meta::Path(p)) =>
Attr::Flag { name: get_single_segment(p)?, span: p.span() },
NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit, .. })) =>
NestedMeta::Meta(Meta::NameValue(MetaNameValue { path, lit, .. })) =>
Attr::Value { name: get_single_segment(path)?, value: lit.clone(), span: path.span() },
NestedMeta::Lit(l) =>
Attr::Lit { value: l.clone(), span: a.span() },
NestedMeta::Lit(l) =>
Attr::Lit { _value: l.clone(), span: a.span() },
y => panic!("y: {:?}", y),
});
}
@ -334,7 +334,7 @@ usize_field!(EndBit, "EndBit", "EndBit");
fn get_attr<'a, I, Ta: 'a, Tb, F>(iter: I, _span: Span, scope: Scope, default: Tb, filter_map: F) -> Result<Tb, Error>
where
where
I: Iterator<Item = &'a Ta>,
Tb: Clone + Name + Debug,
F: FnMut(&Ta) -> Option<(Result<Tb, Error>, Span)>,
@ -362,7 +362,7 @@ where
_ => {
#[cfg(feature = "diagnostic-notes")]
{
Diagnostic::spanned(results.iter().map(|x| x.1.unwrap()).collect::<Vec<proc_macro::Span>>(),
Diagnostic::spanned(results.iter().map(|x| x.1.unwrap()).collect::<Vec<proc_macro::Span>>(),
Level::Error, format!("{}.{} specified multiple times", scope, name)).emit();
}
@ -371,8 +371,8 @@ where
}
}
fn get_value<'a, A, B>(attrs: A, span: Span, scope: Scope, name_: &str) -> Result<B, Error>
where
fn get_value<'a, A, B>(attrs: A, span: Span, scope: Scope, name_: &str) -> Result<B, Error>
where
A: Iterator<Item = &'a Attr>,
B: TryFrom<Attr> + Debug + Clone + Default + Name
{
@ -384,7 +384,7 @@ where
})
}
fn get_endianness<'a, A>(attrs: A, span: Span, scope: Scope, default: Endian) -> Result<Endian, Error>
fn get_endianness<'a, A>(attrs: A, span: Span, scope: Scope, default: Endian) -> Result<Endian, Error>
where
A: Iterator<Item = &'a Attr>
{
@ -395,7 +395,7 @@ where
})
}
fn get_bit_order<'a, A>(attrs: A, span: Span, scope: Scope) -> Result<BitOrder, Error>
fn get_bit_order<'a, A>(attrs: A, span: Span, scope: Scope) -> Result<BitOrder, Error>
where
A: Iterator<Item = &'a Attr>
{
@ -486,7 +486,7 @@ impl ExplicitField {
let endian = self.endian();
let ty = &self.out_type;
let name = &self.name;
(quote! {{
const W: usize = <#ty as packing::PackedSize>::BYTES;
let field_bytes = <#ty as packing::PackedBytes<[u8; W]>>::to_bytes::<#endian>(&self.#name)?;
@ -519,7 +519,7 @@ impl ExplicitField {
}
(
quote! { bytes[#sbyte..=#ebyte].copy_from_slice(&self.#name); },
quote! { bytes[#sbyte..=#ebyte].copy_from_slice(&self.#name); },
quote! { #name: {
let mut t = [0; #width_bytes];
t.copy_from_slice(&bytes[#sbyte..=#ebyte]);
@ -539,7 +539,7 @@ impl Debug for Field {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, r"Field {{
name: {},
out_bits: {:?},
out_bits: {:?},
width: {:?},
space: {:?},
start_byte: {:?},
@ -547,7 +547,7 @@ impl Debug for Field {
start_bit: {:?},
end_bit: {:?},
}}
",
",
self.name, self.out_bits, self.width.value(), self.space.value(), self.start_byte.value(),
self.end_byte.value(), self.start_bit.value(), self.end_bit.value())
}
@ -568,14 +568,14 @@ fn error_or_diagnostic<M: core::fmt::Display>(span: Span, msg: M) -> Result<(),
}
fn derive_struct(
struct_span: Span,
struct_span: Span,
struct_ident: Ident,
bit_order: BitOrder,
struct_endian: Endian,
fields: Fields,
) -> Result<TokenStream, Error>
) -> Result<TokenStream, Error>
{
let named_fields = if let Fields::Named(f) = fields {
let named_fields = if let Fields::Named(f) = fields {
f
} else {
// TODO: shouldn't be hard to support the other kinds
@ -602,23 +602,23 @@ fn derive_struct(
start_byte: get_value(attrs.iter(), f.ident.span(), Scope::Field, ATTR_START_BYTE)?,
end_byte: get_value(attrs.iter(), f.ident.span(), Scope::Field, ATTR_END_BYTE)?,
start_bit: get_value(attrs.iter(), f.ident.span(), Scope::Field, ATTR_START_BIT)?,
end_bit: get_value(attrs.iter(), f.ident.span(), Scope::Field, ATTR_END_BIT)?,
endian: get_endianness(attrs.iter(), f.ident.span(), Scope::Field, struct_endian)?,
end_bit: get_value(attrs.iter(), f.ident.span(), Scope::Field, ATTR_END_BIT)?,
endian: get_endianness(attrs.iter(), f.ident.span(), Scope::Field, struct_endian)?,
};
if let Some(eb) = field.end_bit.value() {
if eb > 7 {
Err(Error::new(field.end_bit.0.unwrap().1,
"end_bit must be between 0 and 7 (inclusive)"))?;
Err(Error::new(field.end_bit.0.unwrap().1,
"end_bit must be between 0 and 7 (inclusive)"))?;
} else {
field.end_bit.0 = field.end_bit.0.map(|b| bit_order.map_bits(b));
}
}
if let Some(sb) = field.start_bit.value() {
if sb > 7 {
Err(Error::new(field.start_bit.0.unwrap().1,
"start_bit must be between 0 and 7 (inclusive)"))?;
Err(Error::new(field.start_bit.0.unwrap().1,
"start_bit must be between 0 and 7 (inclusive)"))?;
} else {
field.start_bit.0 = field.start_bit.0.map(|b| bit_order.map_bits(b));
}
@ -658,7 +658,7 @@ fn derive_struct(
},
}
pack_to_comment += "\n|-|-|-|-|-|-|-|-|-|\n";
let mut explicit_fields = Vec::new();
let mut bit = 0;
@ -704,7 +704,7 @@ fn derive_struct(
if w != end - bit {
error_or_diagnostic(f.name.span(),
format!("Field specifies width of {} but calculated width is {}. Check width, start/end byte/bit attributes",
w, end - bit))?;
w, end - bit))?;
}
} else {
end += w;
@ -718,23 +718,23 @@ fn derive_struct(
//end += width;
#[cfg(feature = "diagnostic-notes")]
Diagnostic::spanned(f.name.span().unwrap(), Level::Note,
format!("Field {} inferred length: {}",
f.name, width)).emit();
Diagnostic::spanned(f.name.span().unwrap(), Level::Note,
format!("Field {} inferred length: {}",
f.name, width)).emit();
panic!("!end_set: {:?}", f);
}
if end - bit > width {
error_or_diagnostic(f.name.span(),
format!("Field width is {} bits which is more than will fit in {:?} ({} bits)",
end - bit, f.out_type, width))?;
format!("Field width is {} bits which is more than will fit in {:?} ({} bits)",
end - bit, f.out_type, width))?;
}
}
#[cfg(feature = "diagnostic-notes")]
Diagnostic::spanned(f.name.span().unwrap(), Level::Note,
format!("{}: {} -> {} ({}.{} .. {}.{})", f.name, bit, end,
format!("{}: {} -> {} ({}.{} .. {}.{})", f.name, bit, end,
f.start_byte.value().unwrap(),
f.start_bit.value().unwrap(),
f.end_byte.value().unwrap(),
@ -817,7 +817,7 @@ fn derive_struct(
let result = quote!{
impl packing::Packed for #struct_ident {
type Error = packing::Error;
#[doc = #pack_to_comment]
fn pack(&self, bytes: &mut [u8]) -> Result<(), Self::Error> {
if bytes.len() < #min_len {
@ -866,12 +866,12 @@ fn derive_struct(
}
fn derive_enum(
struct_span: Span,
struct_span: Span,
struct_ident: Ident,
_bit_order: BitOrder,
_struct_endian: Endian,
variants: Vec<Variant>,
) -> Result<TokenStream, Error>
) -> Result<TokenStream, Error>
{
let mut max_discriminant = 0;
@ -914,7 +914,7 @@ fn derive_enum(
}
let width = min_width as usize;
let mut results = Vec::new();
results.push(quote!{
@ -938,7 +938,7 @@ fn derive_enum(
}
});
results.push(quote!{
results.push(quote!{
impl packing::PackedBytes<[u8; #width]> for #struct_ident {
type Error = packing::Error;
fn to_bytes<En: packing::Endian>(&self) -> Result<[u8; #width], Self::Error> {
@ -955,7 +955,7 @@ fn derive_enum(
}
}
}
});
Ok(quote! {
@ -978,4 +978,4 @@ fn inner(input: DeriveInput) -> Result<TokenStream, Error> {
Data::Enum(e) => derive_enum(struct_span, struct_ident, bit_order, struct_endian, e.variants.into_iter().collect()),
other => Err(Error::new(struct_span, format!("Packed derive only supported on structs ({:?})", other)))?,
}
}
}

View file

@ -17,17 +17,10 @@ usb-device = "0.2.4"
embedded-hal = "0.2.3"
nb = "0.1.2"
typenum = "1.11.2"
itm_logger = { version = "0.1.0", default-features = false }
usbd_mass_storage = { version = "0.1.0", path = "../usbd_mass_storage" }
packing = { version = "0.2.0", path = "../packing/packing" }
log = "0.4.17"
xous = "0.9.29"
ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.23" }
[features]
trace-bot-headers = []
trace-bot-states = []
trace-bot-bytes = []
trace-bot-zlp = []
trace-bot-buffer = []
trace-usb-control = [ "usbd_mass_storage/trace-usb-control" ]
trace-all = [ "trace-bot-headers", "trace-bot-states", "trace-bot-bytes", "trace-bot-zlp", "trace-bot-buffer",
"trace-usb-control" ]

View file

@ -54,15 +54,15 @@ impl From<PackingError> for Error {
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
enum State {
/// Waiting for a command block wrapper to arrive. Throws away data until
/// Waiting for a command block wrapper to arrive. Throws away data until
/// CBW signature is found. Moves to SendingDataToHost or ReceivingDataFromHost
/// depending on CBW direction flag
WaitingForCommand,
/// Command initiated a transfer to the host (IN in USB parlance). Sends the
/// number of bytes the command asked for unless instructed to terminate early.
/// Command initiated a transfer to the host (IN in USB parlance). Sends the
/// number of bytes the command asked for unless instructed to terminate early.
/// Moves to NeedToSendStatus or NeedZlp
SendingDataToHost,
/// Command initiated a transfer from the host (OUT in USB parlance). Reads the
/// Command initiated a transfer from the host (OUT in USB parlance). Reads the
/// number of bytes the command asked to send. Moves to NeedToSendStatus or NeedZlp
ReceivingDataFromHost,
/// Need to send a zero length packet because the transfer was shorter than
@ -84,7 +84,7 @@ pub enum TransferState {
/// need the caller to process the data before we can do more work. `done` indicates
/// data_residue has reached 0 and there won't be any more data read
ReceivingDataFromHost { bytes_available: usize, full: bool, done: bool },
/// We are sending data to the host, `bytes_remaining` indicates how many bytes are
/// We are sending data to the host, `bytes_remaining` indicates how many bytes are
/// still in the buffer. `empty` indicates the buffer is empty and we can't do any
/// more work before the caller gives us more data
SendingDataToHost { bytes_remaining: usize, empty: bool },
@ -95,7 +95,7 @@ pub enum TransferState {
/// So far only tested with the SCSI transparent command set - see [Scsi](struct.Scsi.html)
///
/// [Glossary](index.html#glossary)
///
///
/// ## Functionality overview
/// 1. Reading CBWs
/// 1. Initiating a data transfer with the length and direction from the CBW
@ -116,7 +116,7 @@ pub enum TransferState {
///
pub struct BulkOnlyTransport<'a, B: UsbBus> {
inner: MscClass<'a, B>,
/// This is the response this class will give to the Get Max LUN request
/// must be between 0 and 15, which is checked in the new function
max_lun: u8,
@ -127,7 +127,7 @@ pub struct BulkOnlyTransport<'a, B: UsbBus> {
/// The most recent CBW. Not valid if in WaitingForCommand state
command_block_wrapper: CommandBlockWrapper,
/// The previous command's CSW.
/// The previous command's CSW.
command_status_wrapper: CommandStatusWrapper,
/// The buffer, used for both reading and writing
@ -146,6 +146,9 @@ pub struct BulkOnlyTransport<'a, B: UsbBus> {
/// Indicates we are going to end the current data transaction after draining the current
/// buffer regardless of data_residue
data_done: bool,
/// access handle for the ticktimer, so we can measure time/delays
tt: ticktimer_server::Ticktimer,
}
impl<B: UsbBus> BulkOnlyTransport<'_, B> {
@ -173,6 +176,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
data_i: 0,
last_packet_full: false,
data_done: false,
tt: ticktimer_server::Ticktimer::new().unwrap(),
}
}
pub fn debug(&self) {
@ -233,7 +237,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
.map_err(|_| Error::DataError);
if cbw.is_err() {
let err = cbw.err().unwrap();
warn!("CBW unpack error: {:?}", err);
log::warn!("CBW unpack error: {:?}", err);
self.buffer_i = 0;
return Err(err);
}
@ -252,7 +256,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
}
// Updates the command status wrapper in readiness to execute the provided command.
// Copies the tag across, sets data_residue to the requested bytes and sets the
// Copies the tag across, sets data_residue to the requested bytes and sets the
// status to OK.
fn prepare_for_command(&mut self, cbw: &CommandBlockWrapper) {
self.command_status_wrapper.tag = cbw.tag;
@ -307,7 +311,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
State::SendingDataToHost |
State::ReceivingDataFromHost => Some(self.command_status_wrapper.data_residue),
_ => None,
}
}
}
pub fn transfer_state(&self) -> TransferState {
@ -338,7 +342,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
if len > self.buffer.len() {
panic!("BulkOnlyTransport::take_buffer_space called with len > buffer.len() ({} > {}) which can never be successful",
len, self.buffer.len());
}
}
if len <= self.buffer.len() - self.buffer_i {
trace_bot_buffer!("BUFFER> successfully allocated {} bytes", len);
@ -357,37 +361,12 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
/// Returns a slice containing data from the buffer if there is `len` bytes available
/// panics if len requested is > the max size of the buffer
/// `take_available` modifies behaviour to return whatever is available, even if that is [u8; 0]
/// Waits until a time-out for data to become available;
/// returns WouldBlock if there isn't enough data available
pub fn take_buffered_data(&mut self, len: usize, take_available: bool) -> Result<&[u8], Error> {
/*
if len > self.buffer.len() {
panic!("BulkOnlyTransport::take_buffered_data called with len > buffer.len() ({} > {}) which can never be successful",
len, self.buffer.len());
}
log::info!("take_buffered_data() len: {}", len);
let available = self.buffer_i - self.data_i;
if !take_available && len > available {
trace_bot_buffer!("BUFFER> contains insufficient data for take; requested: {}, available: {}", len, self.buffer_i - self.data_i);
Err(WouldBlock)?
}
let s = self.data_i;
let len = len.min(available);
let e = s + len;
self.data_i += len;
if self.data_i == self.buffer_i {
self.data_i = 0;
self.buffer_i = 0;
}
trace_bot_buffer!("BUFFER> took {}, available after: {}", len, self.buffer_i - self.data_i);
log::info!("take_buffered_data() s: {} e: {}", s, e);
Ok(&self.buffer[s..e])
*/
pub fn take_buffered_data(&mut self, len: usize) -> Result<&[u8], Error> {
log::debug!("take_buffered_data() len: {}", len);
const TIMEOUT_MS: u64 = 2000;
let start = self.tt.elapsed_ms();
loop {
match self.inner.read_packet(&mut self.buffer[..len]) {
Ok(l) => {
@ -397,6 +376,10 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
match e {
UsbError::WouldBlock => {
log::debug!("bulk read not ready yet");
if self.tt.elapsed_ms() - start > TIMEOUT_MS {
log::error!("bulk read timed out");
return Err(Error::UsbError(WouldBlock))
}
continue;
},
_ => return Err(Error::UsbError(e)),
@ -455,9 +438,9 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
0
};
trace_bot_bytes!("BYTES> Sent {} bytes. Data residue {} -> {}. Buff bytes: {}",
bytes,
residue,
trace_bot_bytes!("BYTES> Sent {} bytes. Data residue {} -> {}. Buff bytes: {}",
bytes,
residue,
self.command_status_wrapper.data_residue,
self.buffer_i - self.data_i,
);
@ -472,7 +455,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
trace_bot_zlp!("ZLP> sending failed: {:?}", e);
Err(e)?
},
}
}
self.change_state(State::NeedToSendStatus);
@ -495,14 +478,14 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
// We only send a zero length packet if the last write was a full packet AND we are sending
// less total bytes than the command header asked for
let needs_zlp = self.last_packet_full &&
let needs_zlp = self.last_packet_full &&
self.state == State::SendingDataToHost &&
self.command_status_wrapper.data_residue > 0;
// send_zlp or flush are called here because we may not get an interrupt in a timley manner
// if we don't send immediately and
if needs_zlp {
if needs_zlp {
trace_bot_zlp!("ZLP> required");
self.change_state(State::NeedZlp);
self.send_zlp()?;
@ -566,7 +549,7 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
fn receiving_data_from_host(&mut self) -> Result<(), Error> {
// print!("r\r\n");
if self.command_status_wrapper.data_residue > 0 &&
self.buffer.len() - self.buffer_i >= self.max_packet_usize()
self.buffer.len() - self.buffer_i >= self.max_packet_usize()
{
// print!("x\r\n");
let bytes = self.inner.read_packet(&mut self.buffer[self.buffer_i..])?;
@ -577,17 +560,16 @@ impl<B: UsbBus> BulkOnlyTransport<'_, B> {
if self.command_status_wrapper.data_residue >= bytes {
self.command_status_wrapper.data_residue -= bytes;
} else {
warn!("Read more bytes that CBW offered");
log::warn!("Read more bytes that CBW offered");
self.command_status_wrapper.data_residue = 0;
}
trace_bot_bytes!("BYTES> Read {} bytes. Data residue {} -> {}. Buff bytes: {}",
bytes,
residue,
trace_bot_bytes!("BYTES> Read {} bytes. Data residue {} -> {}. Buff bytes: {}",
bytes,
residue,
self.command_status_wrapper.data_residue,
self.buffer_i - self.data_i,
);
}
self.check_end_data_transfer()?;
@ -612,7 +594,7 @@ impl<B: UsbBus> UsbClass<B> for BulkOnlyTransport<'_, B> {
self.inner.get_configuration_descriptors(writer)
}
fn reset(&mut self) {
fn reset(&mut self) {
trace_usb_control!("USB_CONTROL> reset");
self.buffer_i = 0;
self.data_i = 0;
@ -623,7 +605,7 @@ impl<B: UsbBus> UsbClass<B> for BulkOnlyTransport<'_, B> {
fn control_in(&mut self, xfer: ControlIn<B>) {
let req = xfer.request();
// Check it's the right interface first
if !self.inner.correct_interface_number(req.index) {
// Inner might still want to deal with it
@ -660,7 +642,7 @@ impl<B: UsbBus> UsbClass<B> for BulkOnlyTransport<'_, B> {
};
if let Some(Err(e)) = handled_res {
error!("Error from ControlIn.accept: {:?}", e);
log::error!("Error from ControlIn.accept: {:?}", e);
}
}
@ -668,7 +650,7 @@ impl<B: UsbBus> UsbClass<B> for BulkOnlyTransport<'_, B> {
self.inner.control_out(xfer)
}
fn poll(&mut self) {
fn poll(&mut self) {
panic!("BulkOnlyTransport::poll should never be called. Consumers (SCSI for example) should use BulkOnlyTransport::read and BulkOnlyTransport::write");
}
}

View file

@ -22,13 +22,13 @@ pub struct CommandBlockWrapper {
pub signature: u32,
/// Tag sent by the host. Must be echoed back to host in tag
/// field of the command status wrapper sent after the command
/// has been executed/rejected. Host uses it to positively
/// has been executed/rejected. Host uses it to positively
/// associate a CSW with the corresponding CBW
#[packed(start_bit=7, end_bit=0, start_byte=4, end_byte=7)]
pub tag: u32,
/// Number of bytes of data that the host expects to receive on
/// the IN or OUT endpoint (as indicated by the direction field)
/// during the execution of this command. If this field is zero,
/// the IN or OUT endpoint (as indicated by the direction field)
/// during the execution of this command. If this field is zero,
/// must respond directly with CSW
#[packed(start_bit=7, end_bit=0, start_byte=8, end_byte=11)]
pub data_transfer_length: u32,
@ -41,7 +41,7 @@ pub struct CommandBlockWrapper {
/// The device Logical Unit Number (LUN) to which the command is
/// for. For devices that don't support multiple LUNs the host will
/// set this field to zero.
/// Devices that don't support multiple LUNS must not ignore this
/// Devices that don't support multiple LUNS must not ignore this
/// field and apply all commands to LUN 0, [see General Problems with Commands](http://janaxelson.com/device_errors.htm)
#[packed(start_bit=7, end_bit=0, start_byte=13, end_byte=13)]
pub lun: u8,
@ -73,7 +73,7 @@ impl CommandBlockWrapper {
buf[0] == SIGNATURE_0 &&
buf[1] == SIGNATURE_1 &&
buf[2] == SIGNATURE_2 &&
buf[3] == SIGNATURE_3
buf[3] == SIGNATURE_3
}
fn find_signature(buf: &[u8]) -> Option<usize> {
@ -83,7 +83,7 @@ impl CommandBlockWrapper {
for i in 0..buf.len().saturating_sub(4) {
if Self::check_signature(&buf[i..(i+4)]) {
return Some(i);
}
}
}
None
}

View file

@ -6,7 +6,7 @@ const SIGNATURE: u32 = 0x53425355;
/// A wrapper that identifies a command sent from the host to the
/// device on the OUT endpoint. Describes the data transfer IN or OUT
/// that should happen immediatly after this wrapper is received.
/// that should happen immediately after this wrapper is received.
/// Little Endian
#[derive(Clone, Copy, Eq, PartialEq, Debug, Packed)]
#[packed(little_endian, lsb0)]
@ -16,7 +16,7 @@ pub struct CommandStatusWrapper {
#[packed(start_bit=7, end_bit=0, start_byte=0, end_byte=3)]
pub signature: u32,
/// Tag that matches this CSW back to the CBW that initiated it.
/// Must be copied from CBW tag field. Host uses it to positively
/// Must be copied from CBW tag field. Host uses it to positively
/// associate a CSW with the corresponding CBW
#[packed(start_bit=7, end_bit=0, start_byte=4, end_byte=7)]
pub tag: u32,
@ -31,7 +31,7 @@ pub struct CommandStatusWrapper {
/// The status of the command
/// 0x00 = Command succeeded
/// 0x01 = Command failed
/// 0x02 = Phase error. Causes the host to perform a reset recovery on the
/// 0x02 = Phase error. Causes the host to perform a reset recovery on the
/// device. This indicates the device state machine has got messed up
/// or similar unrecoverable condition. Processing further CBWs without
/// a reset gives indeterminate results.

View file

@ -10,30 +10,10 @@ pub use bulk_only_transport::{
};
mod logging {
pub use itm_logger::*;
#[cfg(feature = "trace-bot-headers")]
pub use itm_logger::trace as trace_bot_headers;
#[cfg(feature = "trace-bot-states")]
pub use itm_logger::trace as trace_bot_states;
#[cfg(feature = "trace-bot-bytes")]
pub use itm_logger::trace as trace_bot_bytes;
#[cfg(feature = "trace-bot-zlp")]
pub use itm_logger::trace as trace_bot_zlp;
#[cfg(feature = "trace-bot-buffer")]
pub use itm_logger::trace as trace_bot_buffer;
#[cfg(feature = "trace-usb-control")]
pub use itm_logger::trace as trace_usb_control;
pub use log::debug as trace_bot_headers;
pub use log::debug as trace_bot_states;
pub use log::debug as trace_bot_bytes;
pub use log::debug as trace_bot_zlp;
pub use log::debug as trace_bot_buffer;
pub use log::trace as trace_bot_bytes;
pub use log::trace as trace_bot_zlp;
pub use log::trace as trace_bot_buffer;
pub use log::debug as trace_usb_control;
}

View file

@ -17,10 +17,7 @@ usb-device = "0.2.4"
embedded-hal = "0.2.3"
nb = "0.1.2"
typenum = "1.11.2"
itm_logger = { version = "0.1.0", default-features = false }
packing = { version = "0.2.0", path = "../packing/packing" }
log = "0.4.17"
[features]
trace-usb-control = []
trace-all = [ "trace-usb-control" ]

View file

@ -24,11 +24,5 @@ pub use interface_subclass::*;
pub use interface_protocol::*;
mod logging {
pub use itm_logger::*;
#[cfg(feature = "trace-usb-control")]
pub use itm_logger::trace as trace_usb_control;
#[cfg(not(feature = "trace-usb-control"))]
//pub use itm_logger::stub as trace_usb_control;
pub use log::info as trace_usb_control;
pub use log::debug as trace_usb_control;
}

View file

@ -6,6 +6,7 @@ use usb_device::{
use crate::{
InterfaceSubclass,
InterfaceProtocol,
logging::*,
};
/// This should be used as `device_class` when building `UsbDevice`
@ -15,7 +16,7 @@ pub const USB_CLASS_MSC: u8 = 0x08;
/// # USB Mass Storage Class Device
///
/// So far only tested with the Bulk Only protocol and the SCSI transparent command set - see
/// So far only tested with the Bulk Only protocol and the SCSI transparent command set - see
/// [Scsi](struct.Scsi.html) and [Bulk Only Transport](struct.BulkOnlyTransport.html)
pub struct MscClass<'a, B: UsbBus> {
pub(crate) msc_if: InterfaceNumber,
@ -28,8 +29,8 @@ pub struct MscClass<'a, B: UsbBus> {
impl<B: UsbBus> MscClass<'_, B> {
pub fn new(
alloc: &UsbBusAllocator<B>,
max_packet_size: u16,
alloc: &UsbBusAllocator<B>,
max_packet_size: u16,
subclass: InterfaceSubclass,
protocol: InterfaceProtocol,
) -> MscClass<'_, B> {
@ -63,27 +64,7 @@ impl<B: UsbBus> MscClass<'_, B> {
impl<B: UsbBus> UsbClass<B> for MscClass<'_, B> {
fn get_configuration_descriptors(&self, writer: &mut DescriptorWriter) -> Result<()> {
// writer.interface(
// self.msc_if,
// USB_CLASS_MSC,
// self.subclass.to_primitive(),
// self.protocol.to_primitive(),
// )?;
// trace_usb_control!("AYYYYYYYY: read ep addr: {:?} write ep addr: {:?}", self.read_ep.address(), self.write_ep.address());
// writer.endpoint(&self.read_ep)?;
// writer.endpoint(&self.write_ep)
// writer.iad(
// self.msc_if,
// 1,
// USB_CLASS_MSC,
// self.subclass.to_primitive(),
// self.protocol.to_primitive(),
// )?;
writer.interface(self.msc_if,
writer.interface(self.msc_if,
USB_CLASS_MSC,
self.subclass.to_primitive(),
self.protocol.to_primitive(),
@ -92,15 +73,6 @@ impl<B: UsbBus> UsbClass<B> for MscClass<'_, B> {
writer.endpoint(&self.write_ep)?;
writer.endpoint(&self.read_ep)?;
writer.endpoint(&self.write2_ep)
//writer.write(0, &[])
// writer.interface(
// self.fake_if,
// 0xff,
// 0,
// 0
// )
}
fn reset(&mut self) { }
@ -108,14 +80,14 @@ impl<B: UsbBus> UsbClass<B> for MscClass<'_, B> {
fn control_in(&mut self, xfer: ControlIn<B>) {
let req = xfer.request();
if self.correct_interface_number(req.index) {
//trace_usb_control!("USB_CONTROL> Unhandled control-IN: {:?}", req);
trace_usb_control!("USB_CONTROL> Unhandled control-IN: {:?}", req);
}
}
fn control_out(&mut self, xfer: ControlOut<B>) {
let req = xfer.request();
if self.correct_interface_number(req.index) {
//trace_usb_control!("USB_CONTRO> Unhandled control-OUT: {:?}", req);
trace_usb_control!("USB_CONTRO> Unhandled control-OUT: {:?}", req);
};
}
}

View file

@ -18,7 +18,6 @@ usb-device = "0.2.4"
embedded-hal = "0.2.3"
nb = "0.1.2"
typenum = "1.11.2"
itm_logger = { version = "0.1.0", default-features = false }
usbd_mass_storage = { version = "0.1.0", path = "../usbd_mass_storage" }
packing = { version = "0.2.0", path = "../packing/packing" }
usbd_bulk_only_transport = { version = "0.1.0", path = "../usbd_bulk_only_transport" }
@ -27,14 +26,3 @@ xous = "0.9.29"
ticktimer-server = { package = "xous-api-ticktimer", version = "0.9.23" }
[features]
trace-bot-headers = [ "usbd_bulk_only_transport/trace-bot-headers" ]
trace-bot-states = [ "usbd_bulk_only_transport/trace-bot-states" ]
trace-bot-bytes = [ "usbd_bulk_only_transport/trace-bot-bytes" ]
trace-bot-zlp = [ "usbd_bulk_only_transport/trace-bot-zlp" ]
trace-bot-buffer = [ "usbd_bulk_only_transport/trace-bot-buffer" ]
trace-usb-control = [ "usbd_bulk_only_transport/trace-usb-control" ]
trace-scsi-command = []
trace-scsi-fs = []
trace-all = [ "trace-bot-headers", "trace-bot-states", "trace-bot-bytes",
"trace-bot-zlp", "trace-bot-buffer", "trace-scsi-command",
"trace-scsi-fs", "trace-usb-control" ]

View file

@ -7,20 +7,6 @@ mod block_device;
pub use block_device::*;
mod logging {
pub use itm_logger::*;
/*
#[cfg(feature = "trace-scsi-command")]
pub use itm_logger::trace as trace_scsi_command;
#[cfg(not(feature = "trace-scsi-command"))]
pub use itm_logger::stub as trace_scsi_command;
#[cfg(feature = "trace-scsi-fs")]
pub use itm_logger::trace as trace_scsi_fs;
#[cfg(not(feature = "trace-scsi-fs"))]
pub use itm_logger::stub as trace_scsi_fs;
*/
pub use log::debug as trace_scsi_fs;
pub use log::debug as trace_scsi_command;
}

View file

@ -5,7 +5,6 @@ use packing::{
use crate::scsi::{
enums::{
VersionDescriptor,
TargetPortGroupSupport,
SpcVersion,
PeripheralQualifier,
@ -40,7 +39,7 @@ pub struct InquiryResponse {
///A hierarchical support (HISUP) bit set to zero indicates the SCSI target device does not use the hierarchical addressing model to assign LUNs to logical units. A H I S UP bit set to one indicates the SCSI target device uses the hierarchical addressing model to assign LUNs to logical units.
#[pkd(4, 4, 3, 3)]
hierarchical_support: bool,
hierarchical_support: bool,
///The RESPONSE DATA FORMAT field indicates the format of the standard INQUIRY data and shall be set as shown in table 139. A RESPONSE DATA FORMAT field set to 2h indicates that the standard INQUIRY data is in the format defined in this standard. Response data format values less than 2h are obsolete. Response data format values greater than 2h are reserved.
#[pkd(3, 0, 3, 3)]
@ -49,7 +48,7 @@ pub struct InquiryResponse {
///The ADDITIONAL LENGTH field indicates the length in bytes of the remaining standard INQUIRY data. The relationship between the ADDITIONAL LENGTH field and the CDB ALLOCATION LENGTH field is defined in 4.3.5.6.
///Set to total length in bytes minus 4
#[pkd(7, 0, 4, 4)]
additional_length: u8,
additional_length: u8,
///An SCC Supported ( SCCS ) bit set to one indicates that the SCSI target device contains an embedded storage array controller component that is addressable through this logical unit. See SCC-2 for details about storage array controller devices. An SCCS bit set to zero indicates that no embedded storage array controller component is addressable through this logical unit.
#[pkd(7, 7, 5, 5)]
@ -79,7 +78,7 @@ pub struct InquiryResponse {
enclosure_services: bool,
#[pkd(5, 5, 6, 6)]
_vendor_specific: bool,
_vendor_specific: bool,
///A Multi Port (MULTIP) bit set to one indicates that this is a multi-port (two or more ports) SCSI target device and conforms to the SCSI multi-port device requirements found in the applicable standards (e.g., SAM-4, a SCSI transport protocol standard and possibly provisions of a command standard). A M ULTI P bit set to zero indicates that this SCSI target device has a single port and does not implement the multi-port requirements.
#[pkd(4, 4, 6, 6)]
@ -116,7 +115,7 @@ pub struct InquiryResponse {
#[pkd(7, 0, 32, 35)]
product_revision_level: [u8; 4],
/*
/* // these records cause the inquiry to fail, and are thus omitted
#[pkd(7, 0, 36, 55)]
_vendor_specific3: [u8; 20],
@ -144,7 +143,7 @@ pub struct InquiryResponse {
#[pkd(7, 0, 64, 65)]
compliant_standard_4: VersionDescriptor,
#[pkd(7, 0, 66, 67)]
compliant_standard_5: VersionDescriptor,
@ -164,8 +163,8 @@ fn set_ascii_str<T: AsRef<[u8]>>(target: &mut [u8], value: T) {
target[..l].copy_from_slice(&bytes[..l]);
// Set any additional bytes to space as per SPC
for b in target[l..].iter_mut() {
*b = ASCII_SPACE
for b in target[l..].iter_mut() {
*b = ASCII_SPACE
}
}

View file

@ -237,8 +237,7 @@ impl<B: UsbBus, BD: BlockDevice> Scsi<'_, B, BD> {
};
while self.lba <= self.lba_end {
// I think this "len" computation isn't right for our purposes..
let buf = self.inner.take_buffered_data(len, true).expect("Buffer should have enough data");
let buf = self.inner.take_buffered_data(len).expect("Buffer should have enough data");
self.block_device.write_block(self.lba, buf)?;
self.lba += 1;
}
@ -402,7 +401,7 @@ impl<B: UsbBus, BD: BlockDevice> Scsi<'_, B, BD> {
),
};
info!("SENSE: {:?}, ASC: {} {}", sense_key, additional_sense_code.asc(), additional_sense_code.ascq());
log::info!("SENSE: {:?}, ASC: {} {}", sense_key, additional_sense_code.asc(), additional_sense_code.ascq());
self.request_sense_response.sense_key = sense_key;
self.request_sense_response.additional_sense_code = additional_sense_code;
}
@ -482,7 +481,7 @@ impl<B: UsbBus, BD: BlockDevice> UsbClass<B> for Scsi<'_, B, BD> {
fn poll(&mut self) {
if let Err(e) = self.update() {
error!("Error from Scsi::update: {:?}", e);
log::error!("Error from Scsi::update: {:?}", e);
}
}
}

View file

@ -649,7 +649,10 @@ pub(crate) fn main_hw() -> ! {
Some(Opcode::SendString) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut usb_send = buffer.to_original::<api::UsbString, _>().unwrap();
#[cfg(not(feature="minimal"))]
let mut sent = 0;
#[cfg(feature="minimal")]
let sent = 0;
match view {
#[cfg(not(feature="minimal"))]
Views::FidoWithKbd => {