From 425e48ed45b8df10648f05973441e3cabb764ac0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 14 Jan 2024 22:52:52 +0800 Subject: [PATCH] format service/usb-device-xous avoided formatting of any keymapping lookup tables... --- services/usb-device-xous/src/api.rs | 17 +- .../usb-device-xous/src/apps_block_device.rs | 127 ++- services/usb-device-xous/src/hosted.rs | 44 +- services/usb-device-xous/src/hw.rs | 628 +++++++++------ services/usb-device-xous/src/lib.rs | 353 ++++----- services/usb-device-xous/src/main.rs | 41 +- services/usb-device-xous/src/main_hosted.rs | 118 +-- services/usb-device-xous/src/main_hw.rs | 738 ++++++++++-------- services/usb-device-xous/src/mappings.rs | 4 +- services/usb-device-xous/src/spinal_udc.rs | 191 ++--- 10 files changed, 1230 insertions(+), 1031 deletions(-) diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index 2e674b96f..14e0f7470 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -1,5 +1,6 @@ // Note: the log server relies on this name not changing in order to hook the serial port for logging output. -// changing this name shouldn't lead to a crash, but it will lead to the USB driver being undiscoverable by the log crate. +// changing this name shouldn't lead to a crash, but it will lead to the USB driver being undiscoverable by +// the log crate. pub(crate) const SERVER_NAME_USB_DEVICE: &'static str = "_Xous USB device driver_"; #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] @@ -52,11 +53,11 @@ pub(crate) enum Opcode { /// TRNG send poll SerialTrngPoll = 518, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] SetBlockDevice = 1024, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] SetBlockDeviceSID = 1025, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] ResetBlockDevice = 1026, /// Handle the USB interrupt @@ -73,7 +74,7 @@ pub(crate) enum Opcode { // The log crate depends on this API not changing. #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct UsbString { - pub s: xous_ipc::String::<4000>, + pub s: xous_ipc::String<4000>, pub sent: Option, } @@ -104,7 +105,7 @@ pub enum UsbDeviceType { Debug = 0, FidoKbd = 1, Fido = 2, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] MassStorage = 3, Serial = 4, } @@ -117,7 +118,7 @@ impl TryFrom for UsbDeviceType { 0 => Ok(UsbDeviceType::Debug), 1 => Ok(UsbDeviceType::FidoKbd), 2 => Ok(UsbDeviceType::Fido), - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] 3 => Ok(UsbDeviceType::MassStorage), 4 => Ok(UsbDeviceType::Serial), _ => Err("Invalid UsbDeviceType specifier"), @@ -129,7 +130,7 @@ pub const SERIAL_ASCII_BUFLEN: usize = 512; pub const SERIAL_BINARY_BUFLEN: usize = 128; #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct UsbSerialAscii { - pub s: xous_ipc::String::, + pub s: xous_ipc::String, pub delimiter: Option, } diff --git a/services/usb-device-xous/src/apps_block_device.rs b/services/usb-device-xous/src/apps_block_device.rs index 4cd27296f..1ac3df827 100644 --- a/services/usb-device-xous/src/apps_block_device.rs +++ b/services/usb-device-xous/src/apps_block_device.rs @@ -1,7 +1,8 @@ use core::convert::TryInto; -use num_traits::*; use std::sync::Arc; use std::sync::Mutex; + +use num_traits::*; use usbd_scsi::BlockDevice; use xous::msg_blocking_scalar_unpack; @@ -33,73 +34,58 @@ pub struct AppsBlockDevice { impl AppsBlockDevice { pub fn new() -> AppsBlockDevice { let app_cid = Arc::new(Mutex::new(None)); - let rw_ids = Arc::new(Mutex::new(RwOp { - read_id: 0, - write_id: 0, - max_lba_id: 0, - })); + let rw_ids = Arc::new(Mutex::new(RwOp { read_id: 0, write_id: 0, max_lba_id: 0 })); let app_cid_clone = app_cid.clone(); let rw_ids_clone = rw_ids.clone(); let mgmt_sid = xous::create_server().unwrap(); - std::thread::spawn(move || loop { - let msg = xous::receive_message(mgmt_sid).unwrap(); - let opcode: Option = FromPrimitive::from_usize(msg.body.id()); - match opcode { - Some(BlockDeviceMgmtOp::SetOps) => { - msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { + std::thread::spawn(move || { + loop { + let msg = xous::receive_message(mgmt_sid).unwrap(); + let opcode: Option = FromPrimitive::from_usize(msg.body.id()); + match opcode { + Some(BlockDeviceMgmtOp::SetOps) => { + msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { + let mut ids = rw_ids_clone.lock().unwrap(); + + *ids = RwOp { read_id, write_id, max_lba_id }; + + log::info!("setting new app block device handler: {:?}", ids); + xous::return_scalar(msg.sender, 0).unwrap(); + }) + } + Some(BlockDeviceMgmtOp::SetSID) => { + msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, { + let app_sid = + xous::SID::from_u32(sid1 as u32, sid2 as u32, sid3 as u32, sid4 as u32); + let app_cid = xous::connect(app_sid).unwrap(); + let mut ac = app_cid_clone.lock().unwrap(); + + *ac = Some(app_cid as u32); + log::info!("setting new app block device handler SID: {:?}", app_sid); + xous::return_scalar(msg.sender, 0).unwrap(); + }) + } + Some(BlockDeviceMgmtOp::Reset) => msg_blocking_scalar_unpack!(msg, 0, 0, 0, 0, { + let mut ac = app_cid_clone.lock().unwrap(); let mut ids = rw_ids_clone.lock().unwrap(); - *ids = RwOp { - read_id, - write_id, - max_lba_id, - }; + *ac = None; + *ids = RwOp { read_id: 0, write_id: 0, max_lba_id: 0 }; - log::info!("setting new app block device handler: {:?}", ids); xous::return_scalar(msg.sender, 0).unwrap(); - }) + }), + None => unimplemented!("missing opcode for appsblockdevice mgmt interface"), } - Some(BlockDeviceMgmtOp::SetSID) => { - msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, { - let app_sid = - xous::SID::from_u32(sid1 as u32, sid2 as u32, sid3 as u32, sid4 as u32); - let app_cid = xous::connect(app_sid).unwrap(); - let mut ac = app_cid_clone.lock().unwrap(); - - *ac = Some(app_cid as u32); - log::info!("setting new app block device handler SID: {:?}", app_sid); - xous::return_scalar(msg.sender, 0).unwrap(); - }) - } - Some(BlockDeviceMgmtOp::Reset) => msg_blocking_scalar_unpack!(msg, 0, 0, 0, 0, { - let mut ac = app_cid_clone.lock().unwrap(); - let mut ids = rw_ids_clone.lock().unwrap(); - - *ac = None; - *ids = RwOp { - read_id: 0, - write_id: 0, - max_lba_id: 0, - }; - - xous::return_scalar(msg.sender, 0).unwrap(); - }), - None => unimplemented!("missing opcode for appsblockdevice mgmt interface"), } }); - AppsBlockDevice { - app_cid, - rw_ids, - mgmt_cid: xous::connect(mgmt_sid).unwrap(), - } - } - pub fn conn(&self) -> xous::CID { - self.mgmt_cid + AppsBlockDevice { app_cid, rw_ids, mgmt_cid: xous::connect(mgmt_sid).unwrap() } } + + pub fn conn(&self) -> xous::CID { self.mgmt_cid } } impl BlockDevice for AppsBlockDevice { @@ -116,21 +102,13 @@ impl BlockDevice for AppsBlockDevice { let mut request = RawData { raw: [0u8; 4096] }; let buf = unsafe { - xous::MemoryRange::new( - &mut request as *mut RawData as usize, - core::mem::size_of::(), - ) - .unwrap() + xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::()) + .unwrap() }; xous::send_message( cid, - xous::Message::new_lend_mut( - rw_ids.read_id, - buf, - xous::MemoryAddress::new(lba as usize), - None, - ), + xous::Message::new_lend_mut(rw_ids.read_id, buf, xous::MemoryAddress::new(lba as usize), None), ) .unwrap(); @@ -151,21 +129,13 @@ impl BlockDevice for AppsBlockDevice { (request.raw[..Self::BLOCK_BYTES as usize]).copy_from_slice(block); let buf = unsafe { - xous::MemoryRange::new( - &mut request as *mut RawData as usize, - core::mem::size_of::(), - ) - .unwrap() + xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::()) + .unwrap() }; xous::send_message( cid, - xous::Message::new_lend_mut( - rw_ids.write_id, - buf, - xous::MemoryAddress::new(lba as usize), - None, - ), + xous::Message::new_lend_mut(rw_ids.write_id, buf, xous::MemoryAddress::new(lba as usize), None), ) .unwrap(); @@ -181,11 +151,8 @@ impl BlockDevice for AppsBlockDevice { let rw_ids = self.rw_ids.lock().unwrap(); - match xous::send_message( - cid, - xous::Message::new_blocking_scalar(rw_ids.max_lba_id, 0, 0, 0, 0), - ) - .expect("cannot send message to block device app") + match xous::send_message(cid, xous::Message::new_blocking_scalar(rw_ids.max_lba_id, 0, 0, 0, 0)) + .expect("cannot send message to block device app") { xous::Result::Scalar1(max_lba) => max_lba.try_into().unwrap(), _ => panic!("received response to max_lba that isn't a Scalar1!"), diff --git a/services/usb-device-xous/src/hosted.rs b/services/usb-device-xous/src/hosted.rs index a813f8c50..a065362e7 100644 --- a/services/usb-device-xous/src/hosted.rs +++ b/services/usb-device-xous/src/hosted.rs @@ -4,44 +4,46 @@ pub struct SpinalUdcDescriptor {} pub struct UdcEpStatus {} -pub struct SpinalUsbMgmt { -} +pub struct SpinalUsbMgmt {} impl SpinalUsbMgmt { pub fn print_regs(&self) {} + pub fn connect_device_core(&mut self, _state: bool) {} - pub fn is_device_connected(&self) -> bool {false} + + pub fn is_device_connected(&self) -> bool { false } + pub fn disable_debug(&mut self, _disable: bool) {} - pub fn get_disable_debug(&self) -> bool {false} + + pub fn get_disable_debug(&self) -> bool { false } + pub fn xous_suspend(&mut self) {} + pub fn xous_resume1(&mut self) {} + pub fn xous_resume2(&mut self) {} + pub fn descriptor_from_status(&self, _ep_status: &UdcEpStatus) -> SpinalUdcDescriptor { SpinalUdcDescriptor {} } - pub fn status_from_index(&self, _index: usize) -> UdcEpStatus { - UdcEpStatus {} - } -} -pub struct SpinalUsbDevice { + + pub fn status_from_index(&self, _index: usize) -> UdcEpStatus { UdcEpStatus {} } } +pub struct SpinalUsbDevice {} impl SpinalUsbDevice { - pub fn new(_sid: xous::SID, _view: std::sync::Arc::) -> SpinalUsbDevice { + pub fn new(_sid: xous::SID, _view: std::sync::Arc) -> SpinalUsbDevice { SpinalUsbDevice {} } - pub fn get_iface(&self) -> SpinalUsbMgmt { - SpinalUsbMgmt {} - } + + pub fn get_iface(&self) -> SpinalUsbMgmt { SpinalUsbMgmt {} } + pub fn print_ep_stats(&self) {} - pub fn print_regs(&self) { - } + pub fn print_regs(&self) {} + /// simple but easy to understand allocator for buffers inside the descriptor memory space - pub fn alloc_region(&mut self, _requested: usize) -> Option { - None - } + pub fn alloc_region(&mut self, _requested: usize) -> Option { None } + /// returns `true` if the region was available to be deallocated - pub fn dealloc_region(&mut self, _offset: usize) -> bool { - false - } + pub fn dealloc_region(&mut self, _offset: usize) -> bool { false } } diff --git a/services/usb-device-xous/src/hw.rs b/services/usb-device-xous/src/hw.rs index f76fa761f..b4a5786de 100644 --- a/services/usb-device-xous/src/hw.rs +++ b/services/usb-device-xous/src/hw.rs @@ -1,13 +1,18 @@ -use usb_device::bus::PollResult; -use utralib::generated::*; -use crate::*; -use core::{sync::atomic::{AtomicPtr, Ordering, AtomicUsize, AtomicU16, AtomicBool}, mem::size_of}; -use std::sync::{Arc, Mutex}; -use usb_device::{class_prelude::*, Result, UsbDirection}; +use core::{ + mem::size_of, + sync::atomic::{AtomicBool, AtomicPtr, AtomicU16, AtomicUsize, Ordering}, +}; use std::collections::BTreeMap; use std::convert::TryInto; +use std::sync::{Arc, Mutex}; + +use usb_device::bus::PollResult; +use usb_device::{class_prelude::*, Result, UsbDirection}; +use utralib::generated::*; use xous::MemoryRange; +use crate::*; + const WRITE_TIMEOUT_MS: u64 = 20; /// This can be done exactly once, even if there are multiple views. Track if it's been done yet. static INTERRUPT_INIT_DONE: AtomicBool = AtomicBool::new(false); @@ -20,15 +25,19 @@ fn handle_usb(_irq_no: usize, arg: *mut usize) { usb.csr.wo(utra::usbdev::EV_PENDING, pending); - xous::try_send_message(usb.conn, - xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0)).ok(); + xous::try_send_message( + usb.conn, + xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); } pub struct SpinalUsbMgmt { csr: AtomicCsr, usb: AtomicPtr, eps: AtomicPtr, - // can't use the srmem macro because the memory region window is not exactly the size of the memory to be stored. + // can't use the srmem macro because the memory region window is not exactly the size of the memory to be + // stored. sr_descs: [u32; crate::END_OFFSET as usize / size_of::()], sr_debug: bool, sr_core: bool, @@ -44,13 +53,19 @@ impl SpinalUsbMgmt { log::info!("ep{}_status: {:x?}", i, ep_status); if ep_status.head_offset() != 0 { let desc = self.descriptor_from_status(&ep_status); - log::info!("offset: {}, in_progress: {}, length: {}", desc.offset(), desc.in_progress(), desc.length()); + log::info!( + "offset: {}, in_progress: {}, length: {}", + desc.offset(), + desc.in_progress(), + desc.length() + ); } if i == 0 { - let setup_data_base = unsafe{self.usb.load(Ordering::SeqCst).add(0x40) as *mut u32}; - log::info!("setup area: {:x?}{:x?}", - unsafe{setup_data_base.add(0).read_volatile()}.to_le_bytes(), - unsafe{setup_data_base.add(1).read_volatile()}.to_le_bytes() + let setup_data_base = unsafe { self.usb.load(Ordering::SeqCst).add(0x40) as *mut u32 }; + log::info!( + "setup area: {:x?}{:x?}", + unsafe { setup_data_base.add(0).read_volatile() }.to_le_bytes(), + unsafe { setup_data_base.add(1).read_volatile() }.to_le_bytes() ); } } @@ -63,10 +78,12 @@ impl SpinalUsbMgmt { log::debug!("ramsize: {}", self.regs.ramsize()); assert!(4096 == self.regs.ramsize(), "hardware ramsize parameter does not match our expectations"); } + /// Force and hold the reset pin according to the state selected pub fn ll_reset(&mut self, state: bool) { - self.csr.rmwf(utra::usbdev::USBSELECT_FORCE_RESET, if state {1} else {0}); + self.csr.rmwf(utra::usbdev::USBSELECT_FORCE_RESET, if state { 1 } else { 0 }); } + /// does not encode resets, leaves timing to the caller pub fn ll_connect_device_core(&mut self, state: bool) { if state { @@ -77,6 +94,7 @@ impl SpinalUsbMgmt { self.csr.rmwf(utra::usbdev::USBSELECT_SELECT_DEVICE, 0); } } + pub fn connect_device_core(&mut self, state: bool) { self.sr_core = state; log::trace!("previous state: {}", self.csr.rf(utra::usbdev::USBSELECT_SELECT_DEVICE)); @@ -93,13 +111,11 @@ impl SpinalUsbMgmt { self.tt.sleep_ms(1000).unwrap(); self.csr.rmwf(utra::usbdev::USBSELECT_FORCE_RESET, 0); } + pub fn is_device_connected(&self) -> bool { - if self.csr.rf(utra::usbdev::USBSELECT_SELECT_DEVICE) == 1 { - true - } else { - false - } + if self.csr.rf(utra::usbdev::USBSELECT_SELECT_DEVICE) == 1 { true } else { false } } + pub fn disable_debug(&mut self, disable: bool) { if disable { self.csr.wfo(utra::usbdev::USBDISABLE_USBDISABLE, 1); @@ -107,13 +123,11 @@ impl SpinalUsbMgmt { self.csr.wfo(utra::usbdev::USBDISABLE_USBDISABLE, 0); } } + pub fn get_disable_debug(&self) -> bool { - if self.csr.rf(utra::usbdev::USBDISABLE_USBDISABLE) == 0 { - false - } else { - true - } + if self.csr.rf(utra::usbdev::USBDISABLE_USBDISABLE) == 0 { false } else { true } } + pub fn xous_suspend(&mut self) { // log::set_max_level(log::LevelFilter::Debug); // self.print_regs(); @@ -128,9 +142,10 @@ impl SpinalUsbMgmt { // "reset"/disconnected state anyways let ptr = self.usb.load(Ordering::SeqCst) as *const u32; for (index, d) in self.sr_descs.iter_mut().enumerate() { - *d = unsafe{ptr.add(index).read_volatile()}; + *d = unsafe { ptr.add(index).read_volatile() }; } } + pub fn xous_resume1(&mut self) { self.regs.clear_all_interrupts(); let p = self.csr.r(utra::usbdev::EV_PENDING); // this has to be expanded out because AtomicPtr is potentially mutable on read @@ -143,29 +158,28 @@ impl SpinalUsbMgmt { let ptr = self.usb.load(Ordering::SeqCst) as *mut u32; for (index, &s) in self.sr_descs.iter().enumerate() { - unsafe{ptr.add(index).write_volatile(s)}; + unsafe { ptr.add(index).write_volatile(s) }; } self.regs.clear_all_interrupts(); // self.print_regs(); // log::set_max_level(log::LevelFilter::Info); } + pub fn xous_resume2(&mut self) { self.disable_debug(self.sr_debug); self.connect_device_core(self.sr_core); } + #[allow(dead_code)] pub fn descriptor_from_status(&self, ep_status: &UdcEpStatus) -> SpinalUdcDescriptor { - SpinalUdcDescriptor::new( - unsafe{ self.usb.load(Ordering::SeqCst).add( - ep_status.head_offset() as usize * 16 - ) as *mut u32} - ) + SpinalUdcDescriptor::new(unsafe { + self.usb.load(Ordering::SeqCst).add(ep_status.head_offset() as usize * 16) as *mut u32 + }) } + #[allow(dead_code)] pub fn status_from_index(&self, index: usize) -> UdcEpStatus { - unsafe { - self.eps.load(Ordering::SeqCst).add(index).read_volatile() - } + unsafe { self.eps.load(Ordering::SeqCst).add(index).read_volatile() } } } @@ -180,21 +194,19 @@ struct EpProps { } struct AllocView { - // tracks which endpoints have been allocated. ep0 is special. parameter is the maximum size buffer available. - // parameter is (address, len, chain_len); chain_len is the maximum number of `len`-length packets that could be chained + // tracks which endpoints have been allocated. ep0 is special. parameter is the maximum size buffer + // available. parameter is (address, len, chain_len); chain_len is the maximum number of `len`-length + // packets that could be chained ep_allocs: [Option; 16], - // record a copy of the ep0 IN setup descriptor address - could extract from ep_allocs[0], but it's here for legacy reasons + // record a copy of the ep0 IN setup descriptor address - could extract from ep_allocs[0], but it's here + // for legacy reasons ep0in_head: u32, // structure to track space allocations within the memory space - allocs: Arc::>>, // key is offset, value is len + allocs: Arc>>, // key is offset, value is len } impl Default for AllocView { fn default() -> Self { - AllocView { - ep_allocs: [None; 16], - ep0in_head: 0, - allocs: Arc::new(Mutex::new(BTreeMap::new())), - } + AllocView { ep_allocs: [None; 16], ep0in_head: 0, allocs: Arc::new(Mutex::new(BTreeMap::new())) } } } @@ -205,17 +217,21 @@ pub struct SpinalUsbDevice { csr: AtomicCsr, regs: SpinalUdcRegs, // 1:1 mapping of endpoint structures to offsets in the memory space for the actual ep storage - // data must be committed to this in a single write, and not composed dynamically using this as scratch space + // data must be committed to this in a single write, and not composed dynamically using this as scratch + // space eps: AtomicPtr, // different views into allocation, depending on the configuration view: AllocView, tt: ticktimer_server::Ticktimer, address: AtomicUsize, - // bit vector to track if a read is allowed. This prevents a race condition between polled reads and interrupted reads. + // bit vector to track if a read is allowed. This prevents a race condition between polled reads and + // interrupted reads. read_allowed: AtomicU16, - // last descriptor in write (IN packet; device->host) chain. Used to check if a transaction is in progress. - last_wr_desc: Arc::; 16]>>, - // last descriptor in read (OUT packet; host->device) chain. Used to check if a transaction is in progress. + // last descriptor in write (IN packet; device->host) chain. Used to check if a transaction is in + // progress. + last_wr_desc: Arc; 16]>>, + // last descriptor in read (OUT packet; host->device) chain. Used to check if a transaction is in + // progress. } impl SpinalUsbDevice { pub fn new(sid: xous::SID, usb: MemoryRange, csr: MemoryRange) -> SpinalUsbDevice { @@ -227,17 +243,21 @@ impl SpinalUsbDevice { // Safety: the offset of the register bank is defined as 0xFF00 from the base of the // usb memory area. Mapping SpinalUdcRegs here is safe assuming the structure has // been correctly defined. - regs: SpinalUdcRegs::new(unsafe{usb.as_mut_ptr().add(0xFF00) as *mut u32}), + regs: SpinalUdcRegs::new(unsafe { usb.as_mut_ptr().add(0xFF00) as *mut u32 }), eps: AtomicPtr::new(unsafe { - (usb.as_mut_ptr().add(0x00) as *mut UdcEpStatus).as_mut().unwrap() + (usb.as_mut_ptr().add(0x00) as *mut UdcEpStatus).as_mut().unwrap() }), view: AllocView::default(), tt: ticktimer_server::Ticktimer::new().unwrap(), address: AtomicUsize::new(0), read_allowed: AtomicU16::new(0), - last_wr_desc: Arc::new(Mutex::new([None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,])), + last_wr_desc: Arc::new(Mutex::new([ + None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, + None, + ])), } } + pub fn init(&self) { if !INTERRUPT_INIT_DONE.fetch_or(true, Ordering::SeqCst) { xous::claim_interrupt( @@ -254,6 +274,7 @@ impl SpinalUsbDevice { cfg.set_pullup_on(true); // required for proper operation self.regs.set_config(cfg); } + pub fn get_iface(&self) -> SpinalUsbMgmt { SpinalUsbMgmt { csr: AtomicCsr::new(self.csr_addr as *mut u32), @@ -268,17 +289,20 @@ impl SpinalUsbDevice { tt: ticktimer_server::Ticktimer::new().unwrap(), } } + fn print_poll_result(&self, poll_result: &PollResult) { let info = match poll_result { PollResult::None => "PollResult::None".to_string(), PollResult::Reset => "PollResult::Reset".to_string(), PollResult::Resume => "PollResult::Resume".to_string(), PollResult::Suspend => "PollResult::Suspend".to_string(), - PollResult::Data {ep_out, ep_in_complete, ep_setup} => - format!("PollResult::Data out:{:x} in:{:x} setup:{:x}", ep_out, ep_in_complete, ep_setup), + PollResult::Data { ep_out, ep_in_complete, ep_setup } => { + format!("PollResult::Data out:{:x} in:{:x} setup:{:x}", ep_out, ep_in_complete, ep_setup) + } }; log::debug!("<<<< {}", info); } + #[allow(dead_code)] pub fn print_ep_stats(&self) { for i in 0..16 { @@ -287,41 +311,50 @@ impl SpinalUsbDevice { log::info!("ep{}_status: {:x?}", i, ep_status); if ep_status.head_offset() != 0 { let desc = self.descriptor_from_status(&ep_status); - log::info!("offset: {}, in_progress: {}, length: {}", desc.offset(), desc.in_progress(), desc.length()); + log::info!( + "offset: {}, in_progress: {}, length: {}", + desc.offset(), + desc.in_progress(), + desc.length() + ); } if i == 0 { - let setup_data_base = unsafe{self.usb.as_ptr().add(0x40) as *mut u32}; - log::info!("setup area: {:x?}{:x?}", - unsafe{setup_data_base.add(0).read_volatile()}.to_le_bytes(), - unsafe{setup_data_base.add(1).read_volatile()}.to_le_bytes() + let setup_data_base = unsafe { self.usb.as_ptr().add(0x40) as *mut u32 }; + log::info!( + "setup area: {:x?}{:x?}", + unsafe { setup_data_base.add(0).read_volatile() }.to_le_bytes(), + unsafe { setup_data_base.add(1).read_volatile() }.to_le_bytes() ); } } } } - #[cfg(feature="mjolnir")] + + #[cfg(feature = "mjolnir")] pub fn ll_debug(&self) { let mut regblock = String::new(); - let regs = unsafe{self.usb.as_mut_ptr().add(0xFF00) as *const u32}; + let regs = unsafe { self.usb.as_mut_ptr().add(0xFF00) as *const u32 }; regblock.push_str("\r\nRegs:\r\n"); for i in 0..16 { - regblock.push_str( - &format!("{:08x}, {:08x},\r\n", - unsafe{regs.add(i*2).read_volatile()}, - unsafe{regs.add(i*2 +1).read_volatile()})); + regblock.push_str(&format!( + "{:08x}, {:08x},\r\n", + unsafe { regs.add(i * 2).read_volatile() }, + unsafe { regs.add(i * 2 + 1).read_volatile() } + )); } log::info!("{}", regblock); let mut eps = String::from("\r\nEps/descs:"); - let d = unsafe{self.usb.as_mut_ptr().add(0) as *const u32}; + let d = unsafe { self.usb.as_mut_ptr().add(0) as *const u32 }; for i in 0..72 { if i % 4 == 0 { eps.push_str("\r\n"); } - eps.push_str(&format!("{:08x}, ", unsafe{d.add(i).read_volatile()})); + eps.push_str(&format!("{:08x}, ", unsafe { d.add(i).read_volatile() })); } eps.push_str("\r\n"); log::info!("{}", eps); } + /// simple but easy to understand allocator for buffers inside the descriptor memory space /// See notes inside src/main.rs `alloc_inner` for the functional description. Returns /// the full byte-addressed offset of the region, so it must be shifted to the right by @@ -330,51 +363,65 @@ impl SpinalUsbDevice { pub fn alloc_region(&mut self, requested: u32) -> Option { alloc_inner(&mut self.view.allocs.lock().unwrap(), requested) } + #[allow(dead_code)] /// returns `true` if the region was available to be deallocated pub fn dealloc_region(&mut self, offset: u32) -> bool { dealloc_inner(&mut self.view.allocs.lock().unwrap(), offset) } + pub(crate) fn descriptor_from_status(&self, ep_status: &UdcEpStatus) -> SpinalUdcDescriptor { - SpinalUdcDescriptor::new( - unsafe{ self.usb.as_mut_ptr().add( - ep_status.head_offset() as usize * 16 - ) as *mut u32} - ) + SpinalUdcDescriptor::new(unsafe { + self.usb.as_mut_ptr().add(ep_status.head_offset() as usize * 16) as *mut u32 + }) } + /// overhead of a spinal descriptor in bytes pub(crate) fn descriptor_overhead_bytes(&self) -> usize { 12 } + /// create a descriptor from the head address + chain offset - pub(crate) fn descriptor_from_head_and_chain(&self, head_offset: usize, chain_offset: usize, packet_len: usize) -> SpinalUdcDescriptor { - SpinalUdcDescriptor::new( - unsafe{ self.usb.as_mut_ptr().add( + pub(crate) fn descriptor_from_head_and_chain( + &self, + head_offset: usize, + chain_offset: usize, + packet_len: usize, + ) -> SpinalUdcDescriptor { + SpinalUdcDescriptor::new(unsafe { + self.usb.as_mut_ptr().add( head_offset * 16 // in the case that packet_len is exactly a multiple of 16 plus 4 bytes, it will waste 16 bytes: a 20-byte packet could fit in 32 bytes, but we ask for 48 instead // if changed, this also needs to be updated in alloc_ep() - + (((packet_len + self.descriptor_overhead_bytes()) / 16) + 1) * 16 * chain_offset - ) as *mut u32} - ) + + (((packet_len + self.descriptor_overhead_bytes()) / 16) + 1) * 16 * chain_offset, + ) as *mut u32 + }) } + /// compute the *next* address offset for the *current* chain and packet length. Field is pre-shifted so /// this is directly passed to `set_next_desc_and_len()` - pub(crate) fn next_from_head_and_chain(&self, head_offset: usize, chain_offset: usize, packet_len: usize) -> usize { + pub(crate) fn next_from_head_and_chain( + &self, + head_offset: usize, + chain_offset: usize, + packet_len: usize, + ) -> usize { head_offset * 16 // in the case that packet_len is exactly a multiple of 16 plus 4 bytes, it will waste 16 bytes: a 20-byte packet could fit in 32 bytes, but we ask for 48 instead // if changed, this also needs to be updated in alloc_ep() - + ((((packet_len + self.descriptor_overhead_bytes()) / 16) + 1) * 16 * (chain_offset + 1)) >> 4 + + ((((packet_len + self.descriptor_overhead_bytes()) / 16) + 1) * 16 * (chain_offset + 1)) + >> 4 } - /// A dedicated, fixed descriptor that represents EP0 acting as the 0-length OUT to accept the acknowledgement - /// of IN data write complete. The location of this is at the very top of descriptor space. + + /// A dedicated, fixed descriptor that represents EP0 acting as the 0-length OUT to accept the + /// acknowledgement of IN data write complete. The location of this is at the very top of descriptor + /// space. pub(crate) fn descriptor_ep0_out(&self) -> SpinalUdcDescriptor { - SpinalUdcDescriptor::new( - unsafe{ self.usb.as_mut_ptr().add( - self.ep0_out_offset() * 16 - ) as *mut u32} - ) + SpinalUdcDescriptor::new(unsafe { self.usb.as_mut_ptr().add(self.ep0_out_offset() * 16) as *mut u32 }) } + /// This descriptor is in a fixed location, 0x50. Divide by 16 because all descriptors are 16-byte aligned /// and the bottom 0's are dropped in the register format. pub(crate) fn ep0_out_offset(&self) -> usize { 0x50 / 16 } + /// Reset the EP0 OUT descriptor to its default settings. This is necessary because after the /// descriptor is "used up" it has to be reset. pub(crate) fn ep0_out_reset(&self) { @@ -383,16 +430,15 @@ impl SpinalUsbDevice { ep0_out_desc.set_next_desc_and_len(0, 0); ep0_out_desc.set_desc_flags(UsbDirection::Out, true, true, true); } + pub(crate) fn status_read_volatile(&self, index: usize) -> UdcEpStatus { - unsafe { - self.eps.load(Ordering::SeqCst).add(index).read_volatile() - } + unsafe { self.eps.load(Ordering::SeqCst).add(index).read_volatile() } } + pub(crate) fn status_write_volatile(&self, index: usize, ep_status: UdcEpStatus) { - unsafe { - self.eps.load(Ordering::SeqCst).add(index).write_volatile(ep_status) - } + unsafe { self.eps.load(Ordering::SeqCst).add(index).write_volatile(ep_status) } } + pub(crate) fn udc_hard_halt(&self, index: usize) { self.regs.set_halt(UdcHalt(index as u32 | 0x10)); let mut iters = 0; @@ -404,19 +450,15 @@ impl SpinalUsbDevice { } } } - pub(crate) fn udc_hard_unhalt(&self, index: usize) { - self.regs.set_halt(UdcHalt(index as u32)); - } + + pub(crate) fn udc_hard_unhalt(&self, index: usize) { self.regs.set_halt(UdcHalt(index as u32)); } + pub(crate) fn get_setup(&self) -> [u8; 8] { let mut setup = [0u8; 8]; - let setup_data_base = unsafe{self.usb.as_ptr().add(0x40) as *const u32}; - let setup_data = unsafe{core::slice::from_raw_parts(setup_data_base, 2)}; - setup[..4].copy_from_slice( - &setup_data[0].to_le_bytes() - ); - setup[4..8].copy_from_slice( - &setup_data[1].to_le_bytes() - ); + let setup_data_base = unsafe { self.usb.as_ptr().add(0x40) as *const u32 }; + let setup_data = unsafe { core::slice::from_raw_parts(setup_data_base, 2) }; + setup[..4].copy_from_slice(&setup_data[0].to_le_bytes()); + setup[4..8].copy_from_slice(&setup_data[1].to_le_bytes()); setup } } @@ -430,19 +472,19 @@ impl UsbBus for SpinalUsbDevice { /// # Arguments /// /// * `ep_dir` - The endpoint direction. - /// * `ep_addr` - A static endpoint address to allocate. If Some, the implementation should - /// attempt to return an endpoint with the specified address. If None, the implementation - /// should return the next available one. + /// * `ep_addr` - A static endpoint address to allocate. If Some, the implementation should attempt to + /// return an endpoint with the specified address. If None, the implementation should return the next + /// available one. /// * `max_packet_size` - Maximum packet size in bytes. /// * `interval` - Polling interval parameter for interrupt endpoints. /// /// # Errors /// - /// * [`EndpointOverflow`](crate::UsbError::EndpointOverflow) - Available total number of - /// endpoints, endpoints of the specified type, or endpoint packet memory has been exhausted. - /// This is generally caused when a user tries to add too many classes to a composite device. - /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - A specific `ep_addr` was specified - /// but the endpoint in question has already been allocated. + /// * [`EndpointOverflow`](crate::UsbError::EndpointOverflow) - Available total number of endpoints, + /// endpoints of the specified type, or endpoint packet memory has been exhausted. This is generally + /// caused when a user tries to add too many classes to a composite device. + /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - A specific `ep_addr` was specified but the + /// endpoint in question has already been allocated. fn alloc_ep( &mut self, ep_dir: UsbDirection, @@ -455,22 +497,24 @@ impl UsbBus for SpinalUsbDevice { // note that ep_addr is a packed representation of index and direction, // so you must use `.index()` to get just the index part log::debug!("alloc ep spec: {:?} of type {:?} dir {:?}", ep_addr, ep_type, ep_dir); - if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::Out)) { // flag the control in as a special case + if ep_addr == Some(EndpointAddress::from_parts(0, UsbDirection::Out)) { + // flag the control in as a special case log::debug!("ep0 allocation fixed to 8 bytes, returning OK"); // setup the default ep0 out descriptor but leave it unlinked self.ep0_out_reset(); - return Ok(EndpointAddress::from_parts(0, UsbDirection::Out)) + return Ok(EndpointAddress::from_parts(0, UsbDirection::Out)); } for index in ep_addr.map(|a| a.index()..a.index() + 1).unwrap_or(1..NUM_ENDPOINTS) { if self.view.ep_allocs[index].is_none() { let base_packet_size = max_packet_size; let max_packet_size = match ep_type { - EndpointType::Bulk => + EndpointType::Bulk => { (CHAINED_BUF_LEN as u16 / base_packet_size) // in the case that packet_len is exactly a multiple of 16 plus 4 bytes, it will waste 16 bytes: a 20-byte packet could fit in 32 bytes, but we ask for 48 instead // if changed, this also needs to be updated in descriptor_from_status_and_chain() - * (((base_packet_size + self.descriptor_overhead_bytes() as u16) / 16) + 1) * 16, - _ => max_packet_size + * (((base_packet_size + self.descriptor_overhead_bytes() as u16) / 16) + 1) * 16 + } + _ => max_packet_size, }; // only if there is memory that can accommodate the max_packet_size if let Some(offset) = self.alloc_region(max_packet_size as _) { @@ -480,7 +524,8 @@ impl UsbBus for SpinalUsbDevice { EndpointType::Isochronous => ep_status.set_isochronous(true), _ => ep_status.set_isochronous(false), } - log::debug!("alloc ep{}@{:x?}{} max_packet_size {}", + log::debug!( + "alloc ep{}@{:x?}{} max_packet_size {}", index, offset, match ep_dir { @@ -512,7 +557,8 @@ impl UsbBus for SpinalUsbDevice { let w = u32::from_le_bytes(src.try_into().unwrap()); descriptor.write_data(index, w); } - if init_vec.len() % 4 != 0 { // handle the odd remainder case + if init_vec.len() % 4 != 0 { + // handle the odd remainder case let mut remainder = [0u8; 4]; for (index, &src) in init_vec.chunks_exact(4).remainder().iter().enumerate() { remainder[index] = src; @@ -520,7 +566,8 @@ impl UsbBus for SpinalUsbDevice { descriptor.write_data(init_vec.len() / 4, u32::from_le_bytes(remainder)); } - if index != 0 { // disable transmission on the In descriptor as there's nothing to send + if index != 0 { + // disable transmission on the In descriptor as there's nothing to send if ep_dir == UsbDirection::In { ep_status.set_head_offset(0); } @@ -533,24 +580,28 @@ impl UsbBus for SpinalUsbDevice { // now commit the ep config self.status_write_volatile(index, ep_status); - self.view.ep_allocs[index] = Some( - EpProps { - head_offset: offset as usize / 16, - packet_len: base_packet_size as usize, - max_chain: match ep_type { - EndpointType::Bulk => CHAINED_BUF_LEN / base_packet_size as usize, - _ => 1, - }, - ep_type, - ep_addr: EndpointAddress::from(index as u8), - ep_dir, - } - ); + self.view.ep_allocs[index] = Some(EpProps { + head_offset: offset as usize / 16, + packet_len: base_packet_size as usize, + max_chain: match ep_type { + EndpointType::Bulk => CHAINED_BUF_LEN / base_packet_size as usize, + _ => 1, + }, + ep_type, + ep_addr: EndpointAddress::from(index as u8), + ep_dir, + }); core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); - log::info!("alloc ep{} type {:?} dir {:?}, @{:x}({})", - index, ep_type, ep_dir, offset, max_packet_size); - return Ok(EndpointAddress::from_parts(index as usize, ep_dir)) + log::info!( + "alloc ep{} type {:?} dir {:?}, @{:x}({})", + index, + ep_type, + ep_dir, + offset, + max_packet_size + ); + return Ok(EndpointAddress::from_parts(index as usize, ep_dir)); } else { return Err(UsbError::EndpointMemoryOverflow); } @@ -593,7 +644,10 @@ impl UsbBus for SpinalUsbDevice { log::trace!("ep0 reset"); self.ep0_out_reset(); } else { - assert!(index as u8 == ep_props.ep_addr.into(), "EP record stored in incorrect location in ep_allocs array!"); + assert!( + index as u8 == ep_props.ep_addr.into(), + "EP record stored in incorrect location in ep_allocs array!" + ); let mut ep_status = UdcEpStatus(0); // rebuild from scratch, not from self.status_read_volatile(index); match ep_props.ep_type { EndpointType::Isochronous => ep_status.set_isochronous(true), @@ -622,7 +676,8 @@ impl UsbBus for SpinalUsbDevice { let w = u32::from_le_bytes(src.try_into().unwrap()); descriptor.write_data(index, w); } - if init_vec.len() % 4 != 0 { // handle the odd remainder case + if init_vec.len() % 4 != 0 { + // handle the odd remainder case let mut remainder = [0u8; 4]; for (index, &src) in init_vec.chunks_exact(4).remainder().iter().enumerate() { remainder[index] = src; @@ -630,7 +685,8 @@ impl UsbBus for SpinalUsbDevice { descriptor.write_data(init_vec.len() / 4, u32::from_le_bytes(remainder)); } - if index != 0 { // disable transmission on the In descriptor as there's nothing to send + if index != 0 { + // disable transmission on the In descriptor as there's nothing to send if ep_props.ep_dir == UsbDirection::In { ep_status.set_head_offset(0); } @@ -656,7 +712,7 @@ impl UsbBus for SpinalUsbDevice { } } } - #[cfg(feature="mjolnir")] + #[cfg(feature = "mjolnir")] self.ll_debug(); // this is the "memory dump" of the USB descriptor area. // clear other registers // self.regs.set_address(0); // i think this is automatic in the USB core... @@ -679,14 +735,13 @@ impl UsbBus for SpinalUsbDevice { /// /// # Errors /// - /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a - /// valid endpoint that was previously allocated with [`UsbBus::alloc_ep`]. - /// * [`WouldBlock`](crate::UsbError::WouldBlock) - A previously written packet is still pending - /// to be sent. + /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a valid + /// endpoint that was previously allocated with [`UsbBus::alloc_ep`]. + /// * [`WouldBlock`](crate::UsbError::WouldBlock) - A previously written packet is still pending to be + /// sent. /// * [`BufferOverflow`](crate::UsbError::BufferOverflow) - The packet is too long to fit in the - /// transmission buffer. This is generally an error in the class implementation, because the - /// class shouldn't provide more data than the `max_packet_size` it specified when allocating - /// the endpoint. + /// transmission buffer. This is generally an error in the class implementation, because the class + /// shouldn't provide more data than the `max_packet_size` it specified when allocating the endpoint. /// /// Implementations may also return other errors if applicable. fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> Result { @@ -694,24 +749,30 @@ impl UsbBus for SpinalUsbDevice { if buf.len() > ep_props.max_chain * ep_props.packet_len { Err(UsbError::BufferOverflow) } else if buf.len() <= ep_props.packet_len { - // TODO: merge this with the path below, mostly to reduce code space. This was kept "intact" so enumeration - // would work while we figured out the details of chaining on bulk transfers. - #[cfg(feature="mjolnir")] // mjolnir is so powerful, one must halt the USB core entirely for it to be wielded - if ep_addr.index() == 1 { self.udc_hard_halt(ep_addr.index()); } + // TODO: merge this with the path below, mostly to reduce code space. This was kept "intact" + // so enumeration would work while we figured out the details of chaining on + // bulk transfers. + #[cfg(feature = "mjolnir")] + // mjolnir is so powerful, one must halt the USB core entirely for it to be wielded + if ep_addr.index() == 1 { + self.udc_hard_halt(ep_addr.index()); + } let mut ep_status = self.status_read_volatile(ep_addr.index()); if ep_addr.index() != 0 { let start = self.tt.elapsed_ms(); let mut now = start; - while (ep_status.head_offset() != 0) - && (now - start < WRITE_TIMEOUT_MS) { + while (ep_status.head_offset() != 0) && (now - start < WRITE_TIMEOUT_MS) { xous::yield_slice(); ep_status = self.status_read_volatile(ep_addr.index()); now = self.tt.elapsed_ms(); } if now - start >= WRITE_TIMEOUT_MS { - log::debug!("write wait timed out: head offset {:x?} {:x?}", ep_status.head_offset() * 16, - self.last_wr_desc.lock().unwrap()[ep_addr.index()].as_ref().unwrap()); + log::debug!( + "write wait timed out: head offset {:x?} {:x?}", + ep_status.head_offset() * 16, + self.last_wr_desc.lock().unwrap()[ep_addr.index()].as_ref().unwrap() + ); } } @@ -719,17 +780,16 @@ impl UsbBus for SpinalUsbDevice { ep_status.set_head_offset(ep_props.head_offset as u32); let descriptor = self.descriptor_from_status(&ep_status); if ep_addr.index() != 0 { - descriptor.set_desc_flags(UsbDirection::In, - false, false, false); + descriptor.set_desc_flags(UsbDirection::In, false, false, false); } else { - descriptor.set_desc_flags(UsbDirection::In, - true, true, false); + descriptor.set_desc_flags(UsbDirection::In, true, true, false); } for (index, src) in buf.chunks_exact(4).enumerate() { let w = u32::from_le_bytes(src.try_into().unwrap()); descriptor.write_data(index, w); } - if buf.len() % 4 != 0 { // handle the odd remainder case + if buf.len() % 4 != 0 { + // handle the odd remainder case let mut remainder = [0u8; 4]; for (index, &src) in buf.chunks_exact(4).remainder().iter().enumerate() { remainder[index] = src; @@ -740,8 +800,7 @@ impl UsbBus for SpinalUsbDevice { ep_status.set_max_packet_size(ep_props.packet_len as _); descriptor.set_next_desc_and_len(0, buf.len()); if ep_addr.index() != 0 { - descriptor.set_desc_flags(UsbDirection::In, - false, true, false); + descriptor.set_desc_flags(UsbDirection::In, false, true, false); } descriptor.set_offset(0); // reset the write pointer to 0, also sets in_progress self.last_wr_desc.lock().unwrap()[ep_addr.index()] = Some(descriptor); @@ -751,24 +810,28 @@ impl UsbBus for SpinalUsbDevice { // this is required to commit the ep_status record once all the setup is done self.status_write_volatile(ep_addr.index(), ep_status); - #[cfg(feature="mjolnir")] - { // mjolnir is so powerful, one must halt the USB core entirely for it to be wielded + #[cfg(feature = "mjolnir")] + { + // mjolnir is so powerful, one must halt the USB core entirely for it to be wielded if ep_addr.index() == 1 { self.ll_debug(); } - if ep_addr.index() == 1 { self.udc_hard_unhalt(ep_addr.index()); } + if ep_addr.index() == 1 { + self.udc_hard_unhalt(ep_addr.index()); + } } core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); - // I think the debug statements actually mess up the timing of the core (as it causes contention for the same - // memory resources used by the core itself), so they are commented out. - //let epcheck = self.status_read_volatile(ep_addr.index()); - //let epcheckdesc = self.descriptor_from_status(&epcheck); - //if ep_addr.index() != 0 { + // I think the debug statements actually mess up the timing of the core (as it causes + // contention for the same memory resources used by the core itself), so they + // are commented out. let epcheck = + // self.status_read_volatile(ep_addr.index()); let epcheckdesc = + // self.descriptor_from_status(&epcheck); if ep_addr.index() != 0 { // log::info!("WR status{}: {:?}", ep_addr.index(), epcheck); // log::info!("WR desc{}: {:?}", ep_addr.index(), epcheckdesc); - // log::info!("WR POSTstatus{}: {:?}", ep_addr.index(), self.status_read_volatile(ep_addr.index())); + // log::info!("WR POSTstatus{}: {:?}", ep_addr.index(), + // self.status_read_volatile(ep_addr.index())); //} Ok(buf.len()) } else { @@ -782,19 +845,26 @@ impl UsbBus for SpinalUsbDevice { now = self.tt.elapsed_ms(); } if now - start >= WRITE_TIMEOUT_MS { - log::debug!("ll write wait timed out: head offset {:x?} {:x?}", ep_status.head_offset() * 16, - self.last_wr_desc.lock().unwrap()[ep_addr.index()].as_ref().unwrap()); + log::debug!( + "ll write wait timed out: head offset {:x?} {:x?}", + ep_status.head_offset() * 16, + self.last_wr_desc.lock().unwrap()[ep_addr.index()].as_ref().unwrap() + ); } for (chain_offset, sub_buf) in buf.chunks(ep_props.packet_len).enumerate() { - let descriptor = self.descriptor_from_head_and_chain(ep_props.head_offset, chain_offset, ep_props.packet_len); - descriptor.set_desc_flags(UsbDirection::In, - false, true, false); + let descriptor = self.descriptor_from_head_and_chain( + ep_props.head_offset, + chain_offset, + ep_props.packet_len, + ); + descriptor.set_desc_flags(UsbDirection::In, false, true, false); for (index, src) in sub_buf.chunks_exact(4).enumerate() { let w = u32::from_le_bytes(src.try_into().unwrap()); descriptor.write_data(index, w); } - if sub_buf.len() % 4 != 0 { // handle the odd remainder case + if sub_buf.len() % 4 != 0 { + // handle the odd remainder case let mut remainder = [0u8; 4]; for (index, &src) in sub_buf.chunks_exact(4).remainder().iter().enumerate() { remainder[index] = src; @@ -803,11 +873,16 @@ impl UsbBus for SpinalUsbDevice { } if chain_offset == (ep_props.max_chain - 1) || sub_buf.len() != ep_props.packet_len { - // on the very last packet (either by chain exhaustion, or buffer source exhaustion), set completion_on_full interrupt + // on the very last packet (either by chain exhaustion, or buffer source exhaustion), + // set completion_on_full interrupt descriptor.set_next_desc_and_len(0, sub_buf.len()); } else { // if not the last packet, setup the linked list pointer - let next_addr = self.next_from_head_and_chain(ep_props.head_offset, chain_offset, ep_props.packet_len); + let next_addr = self.next_from_head_and_chain( + ep_props.head_offset, + chain_offset, + ep_props.packet_len, + ); descriptor.set_next_desc_and_len(next_addr, sub_buf.len()); } descriptor.set_offset(0); // reset the write pointer to 0, also sets in_progress @@ -837,15 +912,14 @@ impl UsbBus for SpinalUsbDevice { /// /// # Errors /// - /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a - /// valid endpoint that was previously allocated with [`UsbBus::alloc_ep`]. - /// * [`WouldBlock`](crate::UsbError::WouldBlock) - There is no packet to be read. Note that - /// this is different from a received zero-length packet, which is valid in USB. A zero-length - /// packet will return `Ok(0)`. - /// * [`BufferOverflow`](crate::UsbError::BufferOverflow) - The received packet is too long to - /// fit in `buf`. This is generally an error in the class implementation, because the class - /// should use a buffer that is large enough for the `max_packet_size` it specified when - /// allocating the endpoint. + /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a valid + /// endpoint that was previously allocated with [`UsbBus::alloc_ep`]. + /// * [`WouldBlock`](crate::UsbError::WouldBlock) - There is no packet to be read. Note that this is + /// different from a received zero-length packet, which is valid in USB. A zero-length packet will + /// return `Ok(0)`. + /// * [`BufferOverflow`](crate::UsbError::BufferOverflow) - The received packet is too long to fit in + /// `buf`. This is generally an error in the class implementation, because the class should use a buffer + /// that is large enough for the `max_packet_size` it specified when allocating the endpoint. /// /// Implementations may also return other errors if applicable. fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> Result { @@ -855,12 +929,12 @@ impl UsbBus for SpinalUsbDevice { if buf.len() == 0 { log::info!("STATUS dummy read"); // it's a STATUS read, just ack and move on - return Ok(0) + return Ok(0); } // hard coded to 8 bytes in hardware if buf.len() < 8 { log::info!("ep0 read would overflow, aborting"); - return Err(UsbError::BufferOverflow) + return Err(UsbError::BufferOverflow); } // setup data is in a special, fixed location buf[..8].copy_from_slice(&self.get_setup()); @@ -877,41 +951,48 @@ impl UsbBus for SpinalUsbDevice { Ok(8) } else { // 🚨 mysterious delay alert 🚨 - // Without this delay, enumeration is not reliable. The specific failure is that the IN response from EP0 - // to a SETUP packet is sometimes not issued. The exact nature of the timing problem is hard to - // nail down, but the delay is necessary to be inserted after the driver calls `write()` to send the - // response to an IN configuration transaction, and something later on which seems to stop/reset - // the IN transaction before it can happen. + // Without this delay, enumeration is not reliable. The specific failure is that the IN + // response from EP0 to a SETUP packet is sometimes not issued. The exact + // nature of the timing problem is hard to nail down, but the delay is + // necessary to be inserted after the driver calls `write()` to send the + // response to an IN configuration transaction, and something later on which seems to + // stop/reset the IN transaction before it can happen. // - // Putting this delay after every `write()` fixes the problem, but interestingly, putting the delay - // at this specific spot in the `read()` path also fixes the problem. The specific code path that leads - // up to this delay being encountered in a way that fixes the problem is through the device class handler. - // Significantly, there is nothing in this *read* that seems to fix the problem. If you omit the class handler - // entirely (so that the delay does not happen), things still break. It just so happens that the call to - // the class handler is narrowly scoped enough so that this path represents a bottleneck between the + // Putting this delay after every `write()` fixes the problem, but interestingly, putting the + // delay at this specific spot in the `read()` path also fixes the problem. + // The specific code path that leads up to this delay being encountered in a + // way that fixes the problem is through the device class handler. + // Significantly, there is nothing in this *read* that seems to fix the problem. If you omit + // the class handler entirely (so that the delay does not happen), things + // still break. It just so happens that the call to the class handler is + // narrowly scoped enough so that this path represents a bottleneck between the // `write()` and the offending thing that aborts the IN transaction. // - // Obviously, I was not able to find the thing that is aborting the IN transaction. This is in part - // because any logging that gets inserted in the interrupt handler will always fix the problem (as - // it essentially inserts the delay in every path). Anyways, the notes are here, and maybe someday we'll - // get to the bottom of it. But for now it seems to work well enough and the performance is "fine" for + // Obviously, I was not able to find the thing that is aborting the IN transaction. This is in + // part because any logging that gets inserted in the interrupt handler will + // always fix the problem (as it essentially inserts the delay in every path). + // Anyways, the notes are here, and maybe someday we'll get to the bottom of + // it. But for now it seems to work well enough and the performance is "fine" for // a USB HID style interface. // - // I thought this was fixed by removing spurious interrupts, but instead, it seems to come back "sometimes", - // as opposed to "always" being a problem. So the delay is re-instated. + // I thought this was fixed by removing spurious interrupts, but instead, it seems to come + // back "sometimes", as opposed to "always" being a problem. So the delay is + // re-instated. // - // Update Jan 2023: I think this delay is necessary because we have an interaction of two bugs: - // 1. Some interrupts are going missing, because the ISR doesn't run fast enough to clear - // the interrupt before the next packet comes in. - // 2. This (or something else maybe) causes a race condition between when interrupts fire for reads, - // and when the read call actually happens, such that the read call does not line up with the intended - // interrupt. + // Update Jan 2023: I think this delay is necessary because we have an interaction of two + // bugs: + // 1. Some interrupts are going missing, because the ISR doesn't run fast enough to clear the + // interrupt before the next packet comes in. + // 2. This (or something else maybe) causes a race condition between when interrupts fire for + // reads, and when the read call actually happens, such that the read call does not line up + // with the intended interrupt. self.tt.sleep_ms(1).ok(); if (self.read_allowed.load(Ordering::Relaxed) & (1 << ep_addr.index() as u16)) == 0 { - // we do get spurious reads on EP0 transactions, so this code prevents these from proceeding - // this is because the EP0 interrupt will fire off a poll event that also causes a read of all the endpoints. - // the interrupt hasn't triggered, don't allow the read + // we do get spurious reads on EP0 transactions, so this code prevents these from + // proceeding this is because the EP0 interrupt will fire off a poll + // event that also causes a read of all the endpoints. the interrupt + // hasn't triggered, don't allow the read let ep_status = self.status_read_volatile(ep_addr.index()); if ep_status.head_offset() != 0 { return Err(UsbError::WouldBlock); @@ -927,32 +1008,39 @@ impl UsbBus for SpinalUsbDevice { ep_status.set_head_offset(ep_props.head_offset as u32); let descriptor = self.descriptor_from_status(&ep_status); if descriptor.in_progress() || descriptor.offset() == 0 { - // "early polls" happen because the main loop can be sloppy and request a read report at any time, - // not just when there's an interrupt. + // "early polls" happen because the main loop can be sloppy and request a read report at + // any time, not just when there's an interrupt. // return before side-effecting any structures log::warn!("WouldBlock {:?}", ep_addr); return Err(UsbError::WouldBlock); } self.udc_hard_halt(ep_addr.index()); - let mut len = if ep_props.max_chain > 1 { - 0 - } else { - descriptor.offset() - }; - if ep_props.max_chain > 1 { // chained descriptors + let mut len = if ep_props.max_chain > 1 { 0 } else { descriptor.offset() }; + if ep_props.max_chain > 1 { + // chained descriptors for (chain_offset, sub_buf) in buf.chunks_mut(ep_props.packet_len).enumerate() { - let descriptor = self.descriptor_from_head_and_chain(ep_props.head_offset, chain_offset, ep_props.packet_len); + let descriptor = self.descriptor_from_head_and_chain( + ep_props.head_offset, + chain_offset, + ep_props.packet_len, + ); if descriptor.offset() != 0 { log::debug!("appending {:x?}", descriptor); let available_len = sub_buf.len().min(descriptor.offset()); - for (desc_offset, word_chunk) in sub_buf[..available_len].chunks_mut(size_of::()).enumerate() { + for (desc_offset, word_chunk) in + sub_buf[..available_len].chunks_mut(size_of::()).enumerate() + { word_chunk.copy_from_slice( - &descriptor.read_data(desc_offset) - .to_le_bytes()[..word_chunk.len()]) // the upper limit index ensures that if sub_buf is an odd number of bytes, we don't panic + &descriptor.read_data(desc_offset).to_le_bytes()[..word_chunk.len()], + ) // the upper limit index ensures that if sub_buf is an odd number of bytes, we don't panic } if sub_buf.len() < descriptor.offset() { - log::warn!("insufficient space in buffer to store incoming data (want: {} have: {}). truncating!", descriptor.offset(), sub_buf.len()); + log::warn!( + "insufficient space in buffer to store incoming data (want: {} have: {}). truncating!", + descriptor.offset(), + sub_buf.len() + ); } len += available_len; } else { @@ -965,9 +1053,12 @@ impl UsbBus for SpinalUsbDevice { len = buf.len(); } for (chain_offset, sub_buf) in buf.chunks_mut(ep_props.packet_len).enumerate() { - let descriptor = self.descriptor_from_head_and_chain(ep_props.head_offset, chain_offset, ep_props.packet_len); - descriptor.set_desc_flags(UsbDirection::Out, - true, true, false); + let descriptor = self.descriptor_from_head_and_chain( + ep_props.head_offset, + chain_offset, + ep_props.packet_len, + ); + descriptor.set_desc_flags(UsbDirection::Out, true, true, false); for (index, _slice) in sub_buf.chunks(size_of::()).enumerate() { descriptor.write_data(index, 0); // zeroize the descriptor area so we don't leak data between packets } @@ -976,7 +1067,11 @@ impl UsbBus for SpinalUsbDevice { descriptor.set_next_desc_and_len(0, sub_buf.len()); } else { // if not the last link, setup the next linked list pointer - let next_addr = self.next_from_head_and_chain(ep_props.head_offset, chain_offset, ep_props.packet_len); + let next_addr = self.next_from_head_and_chain( + ep_props.head_offset, + chain_offset, + ep_props.packet_len, + ); descriptor.set_next_desc_and_len(next_addr, sub_buf.len()); } descriptor.set_offset_only(0); // reset the write pointer to 0, also sets in_progress @@ -985,7 +1080,8 @@ impl UsbBus for SpinalUsbDevice { ep_status.set_max_packet_size(ep_props.packet_len as _); // this is reset to 0 after every transaction by the hardware, so we must reset it ep_status.set_head_offset(ep_props.head_offset as u32); - } else { // single descriptor + } else { + // single descriptor if buf.len() < len { log::error!("read ep{} overflows: {} < {}", ep_addr.index(), buf.len(), len); len = buf.len(); @@ -995,11 +1091,13 @@ impl UsbBus for SpinalUsbDevice { dst.copy_from_slice(&word); } if len % 4 != 0 { - // this will "overread" the descriptor area, but it's OK because descriptors must be aligned to 16-byte boundaries - // so even if the length is odd, the space allocated will always include dummy padding which will keep us + // this will "overread" the descriptor area, but it's OK because descriptors must be + // aligned to 16-byte boundaries so even if the length is odd, + // the space allocated will always include dummy padding which will keep us // from reading into neighboring data. let word = descriptor.read_data(len / 4).to_le_bytes(); - // write only into the portion of the buffer that's allocated, don't write the extra 0's + // write only into the portion of the buffer that's allocated, don't write the extra + // 0's for i in 0..len % 4 { buf[(len / 4) + i] = word[i] } @@ -1007,33 +1105,44 @@ impl UsbBus for SpinalUsbDevice { // setup for the next transaction ep_status.set_max_packet_size(ep_props.packet_len as _); descriptor.set_next_desc_and_len(0, buf.len()); - descriptor.set_desc_flags(UsbDirection::Out, - true, true, false); + descriptor.set_desc_flags(UsbDirection::Out, true, true, false); descriptor.set_offset_only(0); // reset the read pointer to 0, also sets in_progress } // sanity check on interrupts: it should be cleared by this point! let interrupts = self.regs.interrupts(); if interrupts.0 != 0 { - if interrupts.0 != 1 { // ep0 interrupt can sometimes be leftover from ep0setup handling + if interrupts.0 != 1 { + // ep0 interrupt can sometimes be leftover from ep0setup handling log::debug!("Pending interrupts, clearing: {:?}", interrupts); } self.regs.clear_all_interrupts(); } - // this auto-toggles ep_status.set_data_phase(!ep_status.data_phase()); // toggle the data phase + // this auto-toggles ep_status.set_data_phase(!ep_status.data_phase()); // toggle the data + // phase self.status_write_volatile(ep_addr.index(), ep_status); core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); // just reading the registers after setting them seems to upset the USB device block //log::debug!("read buf: {:x?}", &buf[..len]); - //log::info!("ep{} read: {:x?} (len {} into buf of {})", ep_addr.index(), &buf[..len], len, buf.len()); + //log::info!("ep{} read: {:x?} (len {} into buf of {})", ep_addr.index(), &buf[..len], len, + // buf.len()); let epcheck = self.status_read_volatile(ep_addr.index()); let descheck = self.descriptor_from_status(&epcheck); log::debug!("RD status{} [{:x}]: {:?}", ep_addr.index(), epcheck.0, epcheck); - log::debug!("RD desc{} [{:x},{:x},{:x}]: {:?}", ep_addr.index(), descheck.read(0), descheck.read(1), descheck.read(2), descheck); - #[cfg(feature="mjolnir")] - if ep_addr.index() == 2 { // mjolnir should be use selectively on EPs that require debugging, lest the weilder be overwhelmed by its spew. + log::debug!( + "RD desc{} [{:x},{:x},{:x}]: {:?}", + ep_addr.index(), + descheck.read(0), + descheck.read(1), + descheck.read(2), + descheck + ); + #[cfg(feature = "mjolnir")] + if ep_addr.index() == 2 { + // mjolnir should be use selectively on EPs that require debugging, lest the weilder be + // overwhelmed by its spew. self.ll_debug(); } self.udc_hard_unhalt(ep_addr.index()); @@ -1044,6 +1153,7 @@ impl UsbBus for SpinalUsbDevice { Err(UsbError::InvalidEndpoint) } } + /// Reconfigures EP0 to be an OUT descriptor. Used to reconfigure EP0 for the STATUS ack. fn set_ep0_out(&self) { self.ep0_out_reset(); @@ -1051,6 +1161,7 @@ impl UsbBus for SpinalUsbDevice { ep0_status.set_head_offset(self.ep0_out_offset() as u32); self.status_write_volatile(0, ep0_status); } + /// Sets or clears the STALL condition for an endpoint. If the endpoint is an OUT endpoint, it /// should be prepared to receive data again. fn set_stalled(&self, ep_addr: EndpointAddress, stalled: bool) { @@ -1067,12 +1178,12 @@ impl UsbBus for SpinalUsbDevice { match (stalled, ep_addr.direction()) { (true, UsbDirection::In) => { ep_status.set_force_stall(true); - }, + } (true, UsbDirection::Out) => ep_status.set_force_stall(true), (false, UsbDirection::In) => { ep_status.set_force_stall(false); ep_status.set_force_nack(true); - }, + } (false, UsbDirection::Out) => ep_status.set_force_stall(false), }; // single volatile commit of the results @@ -1111,8 +1222,7 @@ impl UsbBus for SpinalUsbDevice { let interrupts = self.regs.interrupts(); let mut ints_to_clear = UdcInterrupts(0); log::debug!(">>>> frame {}: {:x?}", self.regs.frame_id(), interrupts); - let poll_result = - if interrupts.reset() { + let poll_result = if interrupts.reset() { ints_to_clear.set_reset(true); log::trace!("aft reset: {:x?}", interrupts.0); PollResult::Reset @@ -1152,12 +1262,18 @@ impl UsbBus for SpinalUsbDevice { } ints_to_clear.set_endpoint(1 << bit); - if false { // full low-level readback + if false { + // full low-level readback if bit != 0 { log::debug!("status{}: {:?}", bit, self.status_read_volatile(bit)); - log::debug!("desc{}: {:?}", bit, self.descriptor_from_status(&self.status_read_volatile(bit))); + log::debug!( + "desc{}: {:?}", + bit, + self.descriptor_from_status(&self.status_read_volatile(bit)) + ); } - } else { // as processed + } else { + // as processed if bit != 0 { log::debug!("PL status{}: {:?}", bit, ep_status); log::debug!("PL desc{}: {:?}", bit, descriptor); @@ -1191,8 +1307,11 @@ impl UsbBus for SpinalUsbDevice { } else { log::debug!("more interrupts to handle: {:x?}", self.regs.interrupts()); // re-enter the interrupt handler to handle the next interrupt - xous::try_send_message(self.conn, - xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0)).ok(); + xous::try_send_message( + self.conn, + xous::Message::new_scalar(Opcode::UsbIrqHandler.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); } // self.print_ep_stats(); @@ -1227,4 +1346,3 @@ impl UsbBus for SpinalUsbDevice { Ok(()) } } - diff --git a/services/usb-device-xous/src/lib.rs b/services/usb-device-xous/src/lib.rs index b9e57f9eb..f84a49ed9 100644 --- a/services/usb-device-xous/src/lib.rs +++ b/services/usb-device-xous/src/lib.rs @@ -2,15 +2,15 @@ pub mod api; pub use api::*; -use trng::api::TrngTestMode; -use xous::{CID, send_message, Message}; use num_traits::*; -pub use usb_device::device::UsbDeviceState; -pub use xous_usb_hid::device::keyboard::KeyboardLedsReport; -pub use xous_usb_hid::page::Keyboard as UsbKeyCode; use packed_struct::PackedStruct; +use trng::api::TrngTestMode; +pub use usb_device::device::UsbDeviceState; +use xous::{send_message, Message, CID}; use xous_ipc::Buffer; pub use xous_usb_hid::device::fido::RawFidoReport; +pub use xous_usb_hid::device::keyboard::KeyboardLedsReport; +pub use xous_usb_hid::page::Keyboard as UsbKeyCode; #[derive(Debug)] pub struct UsbHid { @@ -20,144 +20,130 @@ impl UsbHid { pub fn new() -> Self { let xns = xous_names::XousNames::new().expect("couldn't connect to XousNames"); REFCOUNT.fetch_add(1, Ordering::Relaxed); - let conn = xns.request_connection_blocking(api::SERVER_NAME_USB_DEVICE).expect("Can't connect to USB device server"); - UsbHid { - conn - } + let conn = xns + .request_connection_blocking(api::SERVER_NAME_USB_DEVICE) + .expect("Can't connect to USB device server"); + UsbHid { conn } } - #[cfg(feature="mass-storage")] + + #[cfg(feature = "mass-storage")] pub fn set_block_device(&self, read_id: usize, write_id: usize, max_lba_id: usize) { - send_message(self.conn, + send_message( + self.conn, Message::new_blocking_scalar( Opcode::SetBlockDevice.to_usize().unwrap(), read_id, write_id, max_lba_id, 0, - ) - ).unwrap(); + ), + ) + .unwrap(); } - #[cfg(feature="mass-storage")] + + #[cfg(feature = "mass-storage")] pub fn set_block_device_sid(&self, app_sid: xous::SID) { let sid = app_sid.to_u32(); - send_message(self.conn, + send_message( + self.conn, Message::new_blocking_scalar( Opcode::SetBlockDeviceSID.to_usize().unwrap(), sid.0 as usize, sid.1 as usize, sid.2 as usize, sid.3 as usize, - ) - ).unwrap(); + ), + ) + .unwrap(); } - #[cfg(feature="mass-storage")] + + #[cfg(feature = "mass-storage")] pub fn reset_block_device(&self) { - send_message(self.conn, - Message::new_blocking_scalar( - Opcode::ResetBlockDevice.to_usize().unwrap(), - 0, - 0, - 0, - 0, - ) - ).unwrap(); + send_message( + self.conn, + Message::new_blocking_scalar(Opcode::ResetBlockDevice.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); } /// used to query if the HID core was able to start. Mainly to handle edge cases between updates. pub fn is_soc_compatible(&self) -> bool { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::IsSocCompatible.to_usize().unwrap(), - 0, 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::IsSocCompatible.to_usize().unwrap(), 0, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match code { - 0 => false, - _ => true - } - } + Ok(xous::Result::Scalar1(code)) => match code { + 0 => false, + _ => true, + }, _ => panic!("Internal error: illegal return type"), } } + /// this will always trigger a reset, even if it's the same core we're switching to pub fn switch_to_core(&self, core: UsbDeviceType) -> Result<(), xous::Error> { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::SwitchCores.to_usize().unwrap(), - core as usize, - 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::SwitchCores.to_usize().unwrap(), core as usize, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match code { - 0 => Ok(()), - _ => Err(xous::Error::InternalError) - } - } + Ok(xous::Result::Scalar1(code)) => match code { + 0 => Ok(()), + _ => Err(xous::Error::InternalError), + }, _ => panic!("Internal error: illegal return type"), } } + /// this will not trigger a reset if we're already on the requested core pub fn ensure_core(&self, core: UsbDeviceType) -> Result<(), xous::Error> { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::EnsureCore.to_usize().unwrap(), - core as usize, - 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::EnsureCore.to_usize().unwrap(), core as usize, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match code { - 0 => Ok(()), - _ => Err(xous::Error::InternalError) - } - } + Ok(xous::Result::Scalar1(code)) => match code { + 0 => Ok(()), + _ => Err(xous::Error::InternalError), + }, _ => panic!("Internal error: illegal return type"), } } + pub fn get_current_core(&self) -> Result { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::WhichCore.to_usize().unwrap(), - 0, 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::WhichCore.to_usize().unwrap(), 0, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match code { - 0 => Ok(UsbDeviceType::Debug), - 1 => Ok(UsbDeviceType::FidoKbd), - 2 => Ok(UsbDeviceType::Fido), - #[cfg(feature="mass-storage")] - 3 => Ok(UsbDeviceType::MassStorage), - 4 => Ok(UsbDeviceType::Serial), - _ => Err(xous::Error::InternalError) - } - } + Ok(xous::Result::Scalar1(code)) => match code { + 0 => Ok(UsbDeviceType::Debug), + 1 => Ok(UsbDeviceType::FidoKbd), + 2 => Ok(UsbDeviceType::Fido), + #[cfg(feature = "mass-storage")] + 3 => Ok(UsbDeviceType::MassStorage), + 4 => Ok(UsbDeviceType::Serial), + _ => Err(xous::Error::InternalError), + }, _ => panic!("Internal error: illegal return type"), } } + pub fn restrict_debug_access(&self, restrict: bool) -> Result<(), xous::Error> { send_message( self.conn, Message::new_scalar( Opcode::RestrictDebugAccess.to_usize().unwrap(), - if restrict {1} else {0}, - 0, 0, 0 - ) - ).map(|_| ()) + if restrict { 1 } else { 0 }, + 0, + 0, + 0, + ), + ) + .map(|_| ()) } + pub fn is_debug_restricted(&self) -> Result { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::IsRestricted.to_usize().unwrap(), - 0, 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::IsRestricted.to_usize().unwrap(), 0, 0, 0, 0), ) { Ok(xous::Result::Scalar1(code)) => { if code == 1 { @@ -169,53 +155,43 @@ impl UsbHid { _ => Err(xous::Error::InternalError), } } + // if do_lock is Some(), set the debug USB lock status to locked if true, unlocked if false // returns a tuple of (bool, bool) -> (is_locked, force_update) // needs_update is so that the polling function knows to redraw the UX after a resume-from-suspend pub fn debug_usb(&self, do_lock: Option) -> Result<(bool, bool), xous::Error> { // arg1 indicates if an update to the state is requested // arg2 is the new state update - let (arg1, arg2) = if let Some(lock) = do_lock { - if lock { - (1, 1) - } else { - (1, 0) - } - } else { - (0, 0) - }; - let response = send_message(self.conn, - Message::new_blocking_scalar(Opcode::DebugUsbOp.to_usize().unwrap(), arg1, arg2, 0, 0))?; + let (arg1, arg2) = if let Some(lock) = do_lock { if lock { (1, 1) } else { (1, 0) } } else { (0, 0) }; + let response = send_message( + self.conn, + Message::new_blocking_scalar(Opcode::DebugUsbOp.to_usize().unwrap(), arg1, arg2, 0, 0), + )?; if let xous::Result::Scalar2(is_locked, force_update) = response { - let il = if is_locked != 0 {true} else {false}; - let fu = if force_update != 0 {true} else {false}; - Ok( - (il, fu) - ) + let il = if is_locked != 0 { true } else { false }; + let fu = if force_update != 0 { true } else { false }; + Ok((il, fu)) } else { Err(xous::Error::InternalError) } } + pub fn status(&self) -> UsbDeviceState { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::LinkStatus.to_usize().unwrap(), - 0, 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::LinkStatus.to_usize().unwrap(), 0, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match code { - 0 => UsbDeviceState::Default, - 1 => UsbDeviceState::Addressed, - 2 => UsbDeviceState::Configured, - 3 => UsbDeviceState::Suspend, - _ => panic!("Internal error: illegal status code") - } - } + Ok(xous::Result::Scalar1(code)) => match code { + 0 => UsbDeviceState::Default, + 1 => UsbDeviceState::Addressed, + 2 => UsbDeviceState::Configured, + 3 => UsbDeviceState::Suspend, + _ => panic!("Internal error: illegal status code"), + }, _ => panic!("Internal error: illegal return type"), } } + /// Sends up to three keyboard codes at once as defined by USB HID usage tables; /// see See [Universal Serial Bus (USB) HID Usage Tables Version 1.12](): /// If the vector is empty, you get an all-key-up situation @@ -227,11 +203,11 @@ impl UsbHid { self.conn, Message::new_blocking_scalar( Opcode::SendKeyCode.to_usize().unwrap(), - if code.len() >= 1 {code[0] as usize} else {0}, - if code.len() >= 2 {code[1] as usize} else {0}, - if code.len() >= 3 {code[2] as usize} else {0}, - if auto_keyup { 1 } else { 0 } - ) + if code.len() >= 1 { code[0] as usize } else { 0 }, + if code.len() >= 2 { code[1] as usize } else { 0 }, + if code.len() >= 3 { code[2] as usize } else { 0 }, + if auto_keyup { 1 } else { 0 }, + ), ) { Ok(xous::Result::Scalar1(code)) => { match code { @@ -243,13 +219,11 @@ impl UsbHid { _ => Err(xous::Error::UseBeforeInit), } } + /// This will attempt to send a string using an API based on the currently connected device /// If it's a Keyboard, it will "type" it; if it's a UART, it will just blast it out the Tx. pub fn send_str(&self, s: &str) -> Result { - let serializer = UsbString { - s: xous_ipc::String::<4000>::from_str(s), - sent: None - }; + let serializer = UsbString { s: xous_ipc::String::<4000>::from_str(s), sent: None }; let mut buf = Buffer::into_buf(serializer).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::SendString.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; let returned = buf.to_original::().or(Err(xous::Error::InternalError))?; @@ -259,85 +233,68 @@ impl UsbHid { None => Err(xous::Error::UseBeforeInit), } } + /// Sets the autotype delay. Defaults to 30ms on boot, must be reset every time on reboot. pub fn set_autotype_delay_ms(&self, rate: usize) { send_message( self.conn, - Message::new_scalar(Opcode::SetAutotypeRate.to_usize().unwrap(), rate, 0, 0, 0) - ).unwrap(); // just unwrap it. If the send fails, we want to see the panic at this spot! + Message::new_scalar(Opcode::SetAutotypeRate.to_usize().unwrap(), rate, 0, 0, 0), + ) + .unwrap(); // just unwrap it. If the send fails, we want to see the panic at this spot! } + pub fn get_led_state(&self) -> Result { match send_message( self.conn, - Message::new_blocking_scalar( - Opcode::GetLedState.to_usize().unwrap(), - 0, 0, 0, 0 - ) + Message::new_blocking_scalar(Opcode::GetLedState.to_usize().unwrap(), 0, 0, 0, 0), ) { - Ok(xous::Result::Scalar1(code)) => { - match KeyboardLedsReport::unpack(&[code as u8]) { - Ok(r) => Ok(r), - Err(_) => Err(xous::Error::InternalError), - } - } + Ok(xous::Result::Scalar1(code)) => match KeyboardLedsReport::unpack(&[code as u8]) { + Ok(r) => Ok(r), + Err(_) => Err(xous::Error::InternalError), + }, _ => panic!("Internal error: illegal return type"), } } + pub fn u2f_wait_incoming(&self) -> Result { - let req = U2fMsgIpc { - data: [0; 64], - code: U2fCode::RxWait, - timeout_ms: None, - }; + let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: None }; let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; - buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; let ack = buf.to_original::().unwrap(); match ack.code { U2fCode::RxAck => { let mut u2fmsg = RawFidoReport::default(); u2fmsg.packet.copy_from_slice(&ack.data); Ok(u2fmsg) - }, - U2fCode::Hangup => { - Err(xous::Error::ProcessTerminated) - }, - U2fCode::RxTimeout => { - Err(xous::Error::Timeout) - }, - _ => Err(xous::Error::InternalError) + } + U2fCode::Hangup => Err(xous::Error::ProcessTerminated), + U2fCode::RxTimeout => Err(xous::Error::Timeout), + _ => Err(xous::Error::InternalError), } } + /// Note: this variant is not tested. pub fn u2f_wait_incoming_timeout(&self, timeout_ms: u64) -> Result { - let req = U2fMsgIpc { - data: [0; 64], - code: U2fCode::RxWait, - timeout_ms: Some(timeout_ms), - }; + let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: Some(timeout_ms) }; let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; - buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, Opcode::U2fRxDeferred.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; let ack = buf.to_original::().unwrap(); match ack.code { U2fCode::RxAck => { let mut u2fmsg = RawFidoReport::default(); u2fmsg.packet.copy_from_slice(&ack.data); Ok(u2fmsg) - }, - U2fCode::Hangup => { - Err(xous::Error::ProcessTerminated) - }, - U2fCode::RxTimeout => { - Err(xous::Error::Timeout) - }, - _ => Err(xous::Error::InternalError) + } + U2fCode::Hangup => Err(xous::Error::ProcessTerminated), + U2fCode::RxTimeout => Err(xous::Error::Timeout), + _ => Err(xous::Error::InternalError), } } + pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> { - let mut req = U2fMsgIpc { - data: [0; 64], - code: U2fCode::Tx, - timeout_ms: None, - }; + let mut req = U2fMsgIpc { data: [0; 64], code: U2fCode::Tx, timeout_ms: None }; req.data.copy_from_slice(&msg.packet); let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; buf.lend_mut(self.conn, Opcode::U2fTx.to_u32().unwrap()).or(Err(xous::Error::InternalError))?; @@ -348,68 +305,70 @@ impl UsbHid { _ => Err(xous::Error::InternalError), } } + /// Blocks until an ASCII string terminated by `delimiter` is received on serial; if `None`, it /// will return as soon as a character (or series of characters) have been received (thus the return /// `String` will be piecemeal) pub fn serial_wait_ascii(&self, delimiter: Option) -> String { - let req = UsbSerialAscii { - s: xous_ipc::String::new(), - delimiter - }; + let req = UsbSerialAscii { s: xous_ipc::String::new(), delimiter }; let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); - buf.lend_mut(self.conn, Opcode::SerialHookAscii.to_u32().unwrap()).or(Err(xous::Error::InternalError)).expect("Internal error"); + buf.lend_mut(self.conn, Opcode::SerialHookAscii.to_u32().unwrap()) + .or(Err(xous::Error::InternalError)) + .expect("Internal error"); let resp = buf.to_original::().unwrap(); resp.s.to_str().to_string() } + /// Blocks until enough binary data has been received to fill the buffer /// Another thread can be used to call serial_flush() if we don't want to /// block forever and we're receiving small amounts of binary data. - pub fn serial_wait_binary(&self) -> Vec:: { - let req = UsbSerialBinary { - d: [0u8; SERIAL_BINARY_BUFLEN], - len: 0, - }; + pub fn serial_wait_binary(&self) -> Vec { + let req = UsbSerialBinary { d: [0u8; SERIAL_BINARY_BUFLEN], len: 0 }; let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); - buf.lend_mut(self.conn, Opcode::SerialHookBinary.to_u32().unwrap()).or(Err(xous::Error::InternalError)).expect("Internal error"); + buf.lend_mut(self.conn, Opcode::SerialHookBinary.to_u32().unwrap()) + .or(Err(xous::Error::InternalError)) + .expect("Internal error"); let resp = buf.to_original::().unwrap(); resp.d[..resp.len].to_vec() } + /// Non-blocking call that issues a serial flush command to the USB stack pub fn serial_flush(&self) -> Result<(), xous::Error> { - send_message( - self.conn, - Message::new_scalar( - Opcode::SerialFlush.to_usize().unwrap(), - 0, 0, 0, 0 - ) - ).map(|_| ()) + send_message(self.conn, Message::new_scalar(Opcode::SerialFlush.to_usize().unwrap(), 0, 0, 0, 0)) + .map(|_| ()) } + /// Inject serial input over USB to the debug console. Dangerous! /// This will also override/discard any existing hooked listeners. pub fn serial_console_input_injection(&self) { send_message( self.conn, - Message::new_scalar( - Opcode::SerialHookConsole.to_usize().unwrap(), 0, 0, 0, 0 - ) - ).unwrap(); + Message::new_scalar(Opcode::SerialHookConsole.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); } + pub fn serial_clear_input_hooks(&self) { send_message( self.conn, - Message::new_scalar( - Opcode::SerialClearHooks.to_usize().unwrap(), 0, 0, 0, 0 - ) - ).unwrap(); + Message::new_scalar(Opcode::SerialClearHooks.to_usize().unwrap(), 0, 0, 0, 0), + ) + .unwrap(); } + /// Tries to set the serial port in TRNG mode. Will silently fail if already in console mode. pub fn serial_set_trng_mode(&self, mode: TrngTestMode) { send_message( self.conn, Message::new_scalar( - Opcode::SerialHookTrngSender.to_usize().unwrap(), mode.to_usize().unwrap(), 0, 0, 0 - ) - ).unwrap(); + Opcode::SerialHookTrngSender.to_usize().unwrap(), + mode.to_usize().unwrap(), + 0, + 0, + 0, + ), + ) + .unwrap(); } } @@ -418,7 +377,9 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0); impl Drop for UsbHid { fn drop(&mut self) { if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { - unsafe{xous::disconnect(self.conn).unwrap();} + unsafe { + xous::disconnect(self.conn).unwrap(); + } } } -} \ No newline at end of file +} diff --git a/services/usb-device-xous/src/main.rs b/services/usb-device-xous/src/main.rs index df5d845d2..913510df5 100644 --- a/services/usb-device-xous/src/main.rs +++ b/services/usb-device-xous/src/main.rs @@ -1,47 +1,48 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] -#[cfg(any(feature="precursor", feature="renode"))] -mod main_hw; #[cfg(not(target_os = "xous"))] mod main_hosted; +#[cfg(any(feature = "precursor", feature = "renode"))] +mod main_hw; mod api; +#[rustfmt::skip] // don't format lookup tables mod mappings; use api::*; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] mod hw; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] use hw::*; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] mod spinal_udc; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] use packed_struct::PackedStructSlice; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] use spinal_udc::*; -#[cfg(all(any(feature="precursor", feature="renode"),feature="mass-storage"))] +#[cfg(all(any(feature = "precursor", feature = "renode"), feature = "mass-storage"))] mod apps_block_device; #[cfg(not(target_os = "xous"))] mod hosted; +use std::collections::BTreeMap; + #[cfg(not(target_os = "xous"))] use hosted::*; - -use std::collections::BTreeMap; -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] use num_traits::*; fn main() -> ! { - #[cfg(any(feature="precursor", feature="renode"))] + #[cfg(any(feature = "precursor", feature = "renode"))] main_hw::main_hw(); #[cfg(not(target_os = "xous"))] main_hosted::main_hosted(); } -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] pub(crate) const START_OFFSET: u32 = 0x0048 + 8 + 16; // align spinal free space to 16-byte boundary + 16 bytes for EP0 read -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] pub(crate) const END_OFFSET: u32 = 0x1000; // derived from RAMSIZE parameter: this could be a dynamically read out constant, but, in practice, it's part of the hardware /// USB endpoint allocator. The SpinalHDL USB controller appears as a block of /// unstructured memory to the host. You can specify pointers into the memory with @@ -53,7 +54,7 @@ pub(crate) const END_OFFSET: u32 = 0x1000; // derived from RAMSIZE parameter: th /// /// Returns a full memory address as the pointer. Must be shifted left by 4 to get the /// aligned representation used by the SpinalHDL block. -#[cfg(any(feature="precursor", feature="renode"))] +#[cfg(any(feature = "precursor", feature = "renode"))] pub(crate) fn alloc_inner(allocs: &mut BTreeMap, requested: u32) -> Option { if requested == 0 { return None; @@ -91,9 +92,9 @@ mod tests { use super::*; #[test] fn test_alloc() { - use rand_chacha::ChaCha8Rng; - use rand_chacha::rand_core::SeedableRng; use rand_chacha::rand_core::RngCore; + use rand_chacha::rand_core::SeedableRng; + use rand_chacha::ChaCha8Rng; let mut rng = ChaCha8Rng::seed_from_u64(0); let mut allocs = BTreeMap::::new(); @@ -111,7 +112,7 @@ mod tests { // consistency check and print out for (&offset, &len) in allocs.iter() { assert!(offset >= last_alloc, "new offset is inside last allocation!"); - println!("{}-{}", offset, offset+len); + println!("{}-{}", offset, offset + len); last_alloc = offset + len; } @@ -133,7 +134,7 @@ mod tests { // consistency check and print out for (&offset, &len) in allocs.iter() { assert!(offset >= last_alloc, "new offset is inside last allocation!"); - println!("{}-{}({})", offset, offset+len, len); + println!("{}-{}({})", offset, offset + len, len); last_alloc = offset + len; } @@ -163,7 +164,7 @@ mod tests { for (&offset, &len) in allocs.iter() { assert!(offset >= last_alloc, "new offset is inside last allocation!"); assert!(offset & 0xF == 0, "misaligned allocation detected"); - println!("{}-{}({})", offset, offset+len, len); + println!("{}-{}({})", offset, offset + len, len); last_alloc = offset + len; } } diff --git a/services/usb-device-xous/src/main_hosted.rs b/services/usb-device-xous/src/main_hosted.rs index 96f230a2f..17e6f4194 100644 --- a/services/usb-device-xous/src/main_hosted.rs +++ b/services/usb-device-xous/src/main_hosted.rs @@ -1,15 +1,15 @@ -use crate::*; - -use num_traits::*; -use xous_usb_hid::device::fido::RawFidoReport; -use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack}; -use xous_semver::SemVer; use core::num::NonZeroU8; use core::sync::atomic::AtomicUsize; +use std::collections::VecDeque; use std::sync::Arc; +use num_traits::*; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack}; use xous_ipc::Buffer; -use std::collections::VecDeque; +use xous_semver::SemVer; +use xous_usb_hid::device::fido::RawFidoReport; + +use crate::*; pub(crate) fn main_hosted() -> ! { log_server::init_wait().unwrap(); @@ -22,10 +22,11 @@ pub(crate) fn main_hosted() -> ! { let llio = llio::Llio::new(&xns); let tt = ticktimer_server::Ticktimer::new().unwrap(); - let minimum_ver = SemVer {maj: 0, min: 9, rev: 8, extra: 20, commit: None}; + let minimum_ver = SemVer { maj: 0, min: 9, rev: 8, extra: 20, commit: None }; let soc_ver = llio.soc_gitrev().unwrap(); if soc_ver < minimum_ver { - if soc_ver.min != 0 { // don't show during hosted mode, which reports 0.0.0+0 + if soc_ver.min != 0 { + // don't show during hosted mode, which reports 0.0.0+0 tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal let modals = modals::Modals::new(&xns).unwrap(); modals.show_notification( @@ -39,9 +40,11 @@ pub(crate) fn main_hosted() -> ! { loop { let msg = xous::receive_message(usbdev_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { - Some(Opcode::DebugUsbOp) => msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, { - xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status"); - }), + Some(Opcode::DebugUsbOp) => { + msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, { + xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status"); + }) + } Some(Opcode::U2fRxDeferred) => { // block any rx requests forever fido_listener = Some(msg); @@ -61,7 +64,8 @@ pub(crate) fn main_hosted() -> ! { arg2: _, arg3: _, arg4: _, - }) = msg.body { + }) = msg.body + { log::warn!("Returning bogus result"); xous::return_scalar(msg.sender, 0).unwrap(); } @@ -77,16 +81,13 @@ pub(crate) fn main_hosted() -> ! { // register a suspend/resume listener let cid = xous::connect(usbdev_sid).expect("couldn't create suspend callback connection"); - let mut susres = susres::Susres::new( - None, - &xns, - api::Opcode::SuspendResume as u32, - cid - ).expect("couldn't create suspend/resume object"); + let mut susres = susres::Susres::new(None, &xns, api::Opcode::SuspendResume as u32, cid) + .expect("couldn't create suspend/resume object"); let mut fido_listener: Option = None; // under the theory that PIDs are unforgeable. TODO: check that PIDs are unforgeable. - // also if someone commandeers a process, all bets are off within that process (this is a general statement) + // also if someone commandeers a process, all bets are off within that process (this is a general + // statement) let mut fido_listener_pid: Option = None; let mut fido_rx_queue = VecDeque::<[u8; 64]>::new(); @@ -97,18 +98,18 @@ pub(crate) fn main_hosted() -> ! { let opcode: Option = FromPrimitive::from_usize(msg.body.id()); log::debug!("{:?}", opcode); match opcode { - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] Some(Opcode::SetBlockDevice) => { log::info!("ignoring SetBlockDevice in hosted mode"); - }, - #[cfg(feature="mass-storage")] + } + #[cfg(feature = "mass-storage")] Some(Opcode::SetBlockDeviceSID) => { log::info!("ignoring SetBlockDeviceSID in hosted mode"); - }, - #[cfg(feature="mass-storage")] + } + #[cfg(feature = "mass-storage")] Some(Opcode::ResetBlockDevice) => { log::info!("ignoring ResetBlockDevice in hosted mode"); - }, + } Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { usbmgmt.xous_suspend(); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); @@ -126,14 +127,23 @@ pub(crate) fn main_hosted() -> ! { fido_listener_pid = msg.sender.pid(); } if fido_listener.is_some() { - log::error!("Double-listener request detected. There should only ever by one registered listener at a time."); - log::error!("This will cause an upstream server to misbehave, but not panicing so the problem can be debugged."); - // the receiver will get a response with the `code` field still in the `RxWait` state to indicate the problem + log::error!( + "Double-listener request detected. There should only ever by one registered listener at a time." + ); + log::error!( + "This will cause an upstream server to misbehave, but not panicing so the problem can be debugged." + ); + // the receiver will get a response with the `code` field still in the `RxWait` state to + // indicate the problem } if fido_listener_pid == msg.sender.pid() { // preferentially pull from the rx queue if it has elements if let Some(data) = fido_rx_queue.pop_front() { - log::debug!("no deferral: ret queued data: {:?} queue len: {}", &data[..8], fido_rx_queue.len() + 1); + log::debug!( + "no deferral: ret queued data: {:?} queue len: {}", + &data[..8], + fido_rx_queue.len() + 1 + ); let mut response = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; @@ -147,8 +157,12 @@ pub(crate) fn main_hosted() -> ! { fido_listener = Some(msg); } } else { - log::warn!("U2F interface capability is locked on first use; additional servers are ignored: {:?}", msg.sender); - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + log::warn!( + "U2F interface capability is locked on first use; additional servers are ignored: {:?}", + msg.sender + ); + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut u2f_ipc = buffer.to_original::().unwrap(); u2f_ipc.code = U2fCode::Denied; buffer.replace(u2f_ipc).unwrap(); @@ -169,7 +183,8 @@ pub(crate) fn main_hosted() -> ! { if fido_listener_pid.is_none() { fido_listener_pid = msg.sender.pid(); } - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut u2f_ipc = buffer.to_original::().unwrap(); if fido_listener_pid == msg.sender.pid() { let mut u2f_msg = RawFidoReport::default(); @@ -182,9 +197,7 @@ pub(crate) fn main_hosted() -> ! { } buffer.replace(u2f_ipc).unwrap(); } - Some(Opcode::UsbIrqHandler) => { - - }, + Some(Opcode::UsbIrqHandler) => {} Some(Opcode::SwitchCores) => msg_blocking_scalar_unpack!(msg, core, _, _, _, { if core == 1 { log::info!("Connecting USB device core; disconnecting debug USB core"); @@ -240,23 +253,17 @@ pub(crate) fn main_hosted() -> ! { usbmgmt.disable_debug(false); } } - // at this point, *read back* the new state -- don't assume it "took". The readback is always based on - // a real hardware value and not the requested value. for now, always false. - let is_locked = if usbmgmt.get_disable_debug() { - 1 - } else { - 0 - }; + // at this point, *read back* the new state -- don't assume it "took". The readback is always + // based on a real hardware value and not the requested value. for now, always + // false. + let is_locked = if usbmgmt.get_disable_debug() { 1 } else { 0 }; - // this is a performance optimization. we could always redraw the status, but, instead we only redraw when - // the status has changed. However, there is an edge case: on a resume from suspend, the status needs a redraw, - // even if nothing has changed. Thus, we have this separate boolean we send back to force an update in the + // this is a performance optimization. we could always redraw the status, but, instead we only + // redraw when the status has changed. However, there is an edge case: on a + // resume from suspend, the status needs a redraw, even if nothing has + // changed. Thus, we have this separate boolean we send back to force an update in the // case that we have just come out of a suspend. - let force_update = if lockstatus_force_update { - 1 - } else { - 0 - }; + let force_update = if lockstatus_force_update { 1 } else { 0 }; xous::return_scalar2(msg.sender, is_locked, force_update).expect("couldn't return status"); lockstatus_force_update = false; }), @@ -267,7 +274,8 @@ pub(crate) fn main_hosted() -> ! { xous::return_scalar(msg.sender, 1).unwrap(); } Some(Opcode::SendString) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let usb_send = buffer.to_original::().unwrap(); // suppress mut warning on hosted mode buffer.replace(usb_send).unwrap(); } @@ -277,8 +285,8 @@ pub(crate) fn main_hosted() -> ! { Some(Opcode::Quit) => { log::warn!("Quit received, goodbye world!"); break; - }, - _ => log::warn!("Opcode not supported: {:?}", msg), + } + _ => log::warn!("Opcode not supported: {:?}", msg), } } // clean up our program @@ -287,4 +295,4 @@ pub(crate) fn main_hosted() -> ! { xous::destroy_server(usbdev_sid).unwrap(); log::trace!("quitting"); xous::terminate_process(0) -} \ No newline at end of file +} diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index 275942a81..f0a4396f4 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -1,33 +1,31 @@ -use crate::*; +use core::num::NonZeroU8; +use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::collections::VecDeque; +use std::convert::TryInto; +use std::sync::Arc; +#[cfg(not(feature = "minimal"))] +use keyboard::KeyMap; use num_traits::*; +use usb_device::class_prelude::*; +use usb_device::prelude::*; use usb_device_xous::KeyboardLedsReport; use usb_device_xous::UsbDeviceType; -use xous_usb_hid::device::fido::RawFidoReport; -use xous_usb_hid::device::fido::RawFidoConfig; -use xous_usb_hid::device::fido::RawFido; -use xous_usb_hid::device::DeviceClass; -use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack}; -#[cfg(not(feature="minimal"))] -use xous_semver::SemVer; -use core::num::NonZeroU8; -use core::sync::atomic::{AtomicU32, AtomicBool, Ordering}; -use std::sync::Arc; +use usbd_serial::SerialPort; use utralib::generated::*; - -use usb_device::prelude::*; -use usb_device::class_prelude::*; -use xous_usb_hid::page::Keyboard; +use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack}; +use xous_ipc::Buffer; +#[cfg(not(feature = "minimal"))] +use xous_semver::SemVer; +use xous_usb_hid::device::fido::RawFido; +use xous_usb_hid::device::fido::RawFidoConfig; +use xous_usb_hid::device::fido::RawFidoReport; use xous_usb_hid::device::keyboard::{NKROBootKeyboard, NKROBootKeyboardConfig}; +use xous_usb_hid::device::DeviceClass; +use xous_usb_hid::page::Keyboard; use xous_usb_hid::prelude::*; -use std::convert::TryInto; -#[cfg(not(feature="minimal"))] -use keyboard::KeyMap; -use xous_ipc::Buffer; -use std::collections::VecDeque; - -use usbd_serial::SerialPort; +use crate::*; /// Time allowed for switchover between device core types. It's longer because some hosts /// get really confused when you have the same VID/PID show up with a different set of endpoints. @@ -37,7 +35,7 @@ const EXTENDED_CORE_RESET_MS: usize = 4000; enum Views { FidoWithKbd = 0, FidoOnly = 1, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] MassStorage = 2, Serial = 3, } @@ -80,22 +78,23 @@ pub(crate) fn main_hw() -> ! { let xns = xous_names::XousNames::new().unwrap(); let usbdev_sid = xns.register_name(api::SERVER_NAME_USB_DEVICE, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", usbdev_sid); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let llio = llio::Llio::new(&xns); let tt = ticktimer_server::Ticktimer::new().unwrap(); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let native_kbd = keyboard::Keyboard::new(&xns).unwrap(); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let native_map = native_kbd.get_keymap().unwrap(); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let serial_number = format!("{:x}", llio.soc_dna().unwrap()); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] { - let minimum_ver = SemVer {maj: 0, min: 9, rev: 8, extra: 20, commit: None}; + let minimum_ver = SemVer { maj: 0, min: 9, rev: 8, extra: 20, commit: None }; let soc_ver = llio.soc_gitrev().unwrap(); if soc_ver < minimum_ver { - if soc_ver.min != 0 { // don't show during hosted mode, which reports 0.0.0+0 + if soc_ver.min != 0 { + // don't show during hosted mode, which reports 0.0.0+0 tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal let modals = modals::Modals::new(&xns).unwrap(); modals.show_notification( @@ -109,9 +108,11 @@ pub(crate) fn main_hw() -> ! { loop { let msg = xous::receive_message(usbdev_sid).unwrap(); match FromPrimitive::from_usize(msg.body.id()) { - Some(Opcode::DebugUsbOp) => msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, { - xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status"); - }), + Some(Opcode::DebugUsbOp) => { + msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, { + xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status"); + }) + } Some(Opcode::U2fRxDeferred) => { // block any rx requests forever fido_listener = Some(msg); @@ -131,7 +132,8 @@ pub(crate) fn main_hw() -> ! { arg2: _, arg3: _, arg4: _, - }) = msg.body { + }) = msg.body + { log::warn!("Returning bogus result"); xous::return_scalar(msg.sender, 0).unwrap(); } @@ -141,9 +143,9 @@ pub(crate) fn main_hw() -> ! { log::info!("consuming listener: {:?}", fido_listener); } } - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] let serial_number = "minimalbuild"; - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] { use utralib::generated::*; let gpio_base = xous::syscall::map_memory( @@ -175,11 +177,11 @@ pub(crate) fn main_hw() -> ! { .expect("couldn't map USB CSR range"); // Notes: - // - Most drivers would `Box()` the hardware management structure to make sure the compiler doesn't - // move its location. However, we can't do this here because we are trying to maintain compatibility - // with another crate that implements the USB stack which can't handle Box'd structures. - // - It is safe to call `.init()` repeatedly because within `init()` we have an atomic bool that - // tracks if the interrupt handler has been hooked, and ignores further requests to hook it. + // - Most drivers would `Box()` the hardware management structure to make sure the compiler doesn't move + // its location. However, we can't do this here because we are trying to maintain compatibility with + // another crate that implements the USB stack which can't handle Box'd structures. + // - It is safe to call `.init()` repeatedly because within `init()` we have an atomic bool that tracks + // if the interrupt handler has been hooked, and ignores further requests to hook it. let usb_fidokbd_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); usb_fidokbd_dev.init(); let mut usbmgmt = usb_fidokbd_dev.get_iface(); @@ -188,36 +190,28 @@ pub(crate) fn main_hw() -> ! { let usb_fido_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); usb_fido_dev.init(); // do the same thing for mass storage - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let ums_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] ums_dev.init(); let serial_dev = SpinalUsbDevice::new(usbdev_sid, usb.clone(), csr.clone()); serial_dev.init(); // track which view is visible on the device core - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let mut view = Views::FidoWithKbd; // register a suspend/resume listener let cid = xous::connect(usbdev_sid).expect("couldn't create suspend callback connection"); - let mut susres = susres::Susres::new( - None, - &xns, - api::Opcode::SuspendResume as u32, - cid - ).expect("couldn't create suspend/resume object"); + let mut susres = susres::Susres::new(None, &xns, api::Opcode::SuspendResume as u32, cid) + .expect("couldn't create suspend/resume object"); // FIDO + keyboard let usb_alloc = UsbBusAllocator::new(usb_fidokbd_dev); let mut composite = UsbHidClassBuilder::new() - .add_device( - NKROBootKeyboardConfig::default(), - ) - .add_device( - RawFidoConfig::default() - ) + .add_device(NKROBootKeyboardConfig::default()) + .add_device(RawFidoConfig::default()) .build(&usb_alloc); let mut usb_dev = UsbDeviceBuilder::new(&usb_alloc, UsbVidPid(0x1209, 0x3613)) @@ -228,36 +222,32 @@ pub(crate) fn main_hw() -> ! { // FIDO only let fido_alloc = UsbBusAllocator::new(usb_fido_dev); - let mut fido_class = UsbHidClassBuilder::new() - .add_device( - RawFidoConfig::default() - ) - .build(&fido_alloc); + let mut fido_class = UsbHidClassBuilder::new().add_device(RawFidoConfig::default()).build(&fido_alloc); let mut fido_dev = UsbDeviceBuilder::new(&fido_alloc, UsbVidPid(0x1209, 0x3613)) - .manufacturer("Kosagi") - .product("Precursor") - .serial_number(&serial_number) - .build(); + .manufacturer("Kosagi") + .product("Precursor") + .serial_number(&serial_number) + .build(); // Mass storage - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let ums_alloc = UsbBusAllocator::new(ums_dev); - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let abd = apps_block_device::AppsBlockDevice::new(); - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let abdcid = abd.conn(); - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let mut ums = usbd_scsi::Scsi::new( &ums_alloc, 64, abd, "Kosagi".as_bytes(), "Kosagi Precursor".as_bytes(), - "1".as_bytes() + "1".as_bytes(), ); - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] let mut ums_device = UsbDeviceBuilder::new(&ums_alloc, UsbVidPid(0x1209, 0x3613)) .manufacturer("Kosagi") .product("Precursor") @@ -272,12 +262,12 @@ pub(crate) fn main_hw() -> ! { // this will create a default port with 128 bytes of backing store let mut serial_port = SerialPort::new(&serial_alloc); let mut serial_device = UsbDeviceBuilder::new(&serial_alloc, UsbVidPid(0x1209, 0x3613)) - .manufacturer("Kosagi") - .product("Precursor") - .serial_number(&serial_number) - .self_powered(false) - .max_power(500) - .build(); + .manufacturer("Kosagi") + .product("Precursor") + .serial_number(&serial_number) + .self_powered(false) + .max_power(500) + .build(); let mut serial_listener: Option = None; let mut serial_listen_mode: SerialListenMode = SerialListenMode::NoListener; let mut serial_buf = Vec::::new(); @@ -285,7 +275,7 @@ pub(crate) fn main_hw() -> ! { let trng = trng::Trng::new(&xns).unwrap(); let mut serial_trng_buf = Vec::::new(); let serial_trng_interval = Arc::new(AtomicU32::new(0)); - let mut serial_trng_cid: Option:: = None; + let mut serial_trng_cid: Option = None; const TRNG_PKT_SIZE: usize = 64; // size of a TRNG packet being sent. This is inferred from the spec. const TRNG_INITIAL_DELAY_MS: u32 = 200; // the very first poll takes longer, because we have to fill the TRNG back-end const TRNG_REFILL_DELAY_MS: u32 = 1; // we re-poll very fast once we see the host taking data @@ -295,7 +285,8 @@ pub(crate) fn main_hw() -> ! { let mut led_state: KeyboardLedsReport = KeyboardLedsReport::default(); let mut fido_listener: Option = None; // under the theory that PIDs cannot be forged. TODO: check that PIDs cannot be forged. - // also if someone commandeers a process, all bets are off within that process (this is a general statement) + // also if someone commandeers a process, all bets are off within that process (this is a general + // statement) let mut fido_listener_pid: Option = None; let mut fido_rx_queue = VecDeque::<[u8; 64]>::new(); @@ -303,18 +294,19 @@ pub(crate) fn main_hw() -> ! { let mut was_suspend = true; let mut autotype_delay_ms = 30; - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] std::thread::spawn(move || { - // this keeps the watchdog alive in minimal mode; if there's no event, eventually the watchdog times out + // this keeps the watchdog alive in minimal mode; if there's no event, eventually the watchdog times + // out let tt = ticktimer_server::Ticktimer::new().unwrap(); loop { tt.sleep_ms(1500).ok(); } }); // switch the core automatically on boot - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] let mut view = Views::MassStorage; - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] { usbmgmt.ll_reset(true); tt.sleep_ms(1000).ok(); @@ -325,9 +317,10 @@ pub(crate) fn main_hw() -> ! { // manage FIDO Rx timeouts -- not tested yet let to_server = xous::create_server().unwrap(); let to_conn = xous::connect(to_server).unwrap(); - // we don't have AtomicU64 on this platform, so we suffer from a rollover condition in timeouts once every 46 days - // this manifests as a timeout that happens to be scheduled on the rollover being rounded to a max limit timeout of - // 5 seconds, and/or an immediate timeout happening during the 5 seconds before the 46-day limit + // we don't have AtomicU64 on this platform, so we suffer from a rollover condition in timeouts once every + // 46 days this manifests as a timeout that happens to be scheduled on the rollover being rounded to a + // max limit timeout of 5 seconds, and/or an immediate timeout happening during the 5 seconds before + // the 46-day limit let target_time_lsb = Arc::new(AtomicU32::new(0)); let to_run = Arc::new(AtomicBool::new(false)); const MAX_TIMEOUT_LIMIT_MS: u32 = 5000; @@ -343,35 +336,46 @@ pub(crate) fn main_hw() -> ! { let mut return_type = 0; let mut next_wake = tt.elapsed_ms(); loop { - xous::reply_and_receive_next_legacy(to_server, &mut msg_opt, &mut return_type) - .unwrap(); + xous::reply_and_receive_next_legacy(to_server, &mut msg_opt, &mut return_type).unwrap(); let msg = msg_opt.as_mut().unwrap(); // loop only consumes CPU time when a timeout is active. Once it has timed out, // it will wait for a new pump call. let now = tt.elapsed_ms(); - match num_traits::FromPrimitive::from_usize(msg.body.id()) - .unwrap_or(TimeoutOp::InvalidCall) - { + match num_traits::FromPrimitive::from_usize(msg.body.id()).unwrap_or(TimeoutOp::InvalidCall) { TimeoutOp::Pump => { if to_run.load(Ordering::SeqCst) { let tt_lsb = target_time_lsb.load(Ordering::SeqCst); - if tt_lsb >= (now as u32) || - (now as u32) - tt_lsb > MAX_TIMEOUT_LIMIT_MS // limits rollover case + if tt_lsb >= (now as u32) || (now as u32) - tt_lsb > MAX_TIMEOUT_LIMIT_MS + // limits rollover case { - xous::try_send_message(cid, - xous::Message::new_scalar(Opcode::U2fRxTimeout.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + cid, + xous::Message::new_scalar( + Opcode::U2fRxTimeout.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); // no need to set to_run to `false` because a Pump message isn't initiated; // the loop de-facto stops from a lack of new Pump messages } else { if next_wake <= now { next_wake = now + POLL_INTERVAL_MS; tt.sleep_ms(POLL_INTERVAL_MS as usize).ok(); - xous::try_send_message(to_conn, - xous::Message::new_scalar(TimeoutOp::Pump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + to_conn, + xous::Message::new_scalar( + TimeoutOp::Pump.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); } else { // don't issue more wakeups if we already have a wakeup scheduled } @@ -386,7 +390,10 @@ pub(crate) fn main_hw() -> ! { } } TimeoutOp::InvalidCall => { - log::error!("Unknown opcode received in FIDO Rx timeout handler: {:?}", msg.body.id()); + log::error!( + "Unknown opcode received in FIDO Rx timeout handler: {:?}", + msg.body.id() + ); } } } @@ -399,32 +406,51 @@ pub(crate) fn main_hw() -> ! { let opcode: Option = FromPrimitive::from_usize(msg.body.id()); log::debug!("{:?}", opcode); match opcode { - #[cfg(feature="mass-storage")] - Some(Opcode::SetBlockDevice) => msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { + #[cfg(feature = "mass-storage")] + Some(Opcode::SetBlockDevice) => { + msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { + xous::send_message( + abdcid, + xous::Message::new_blocking_scalar( + apps_block_device::BlockDeviceMgmtOp::SetOps.to_usize().unwrap(), + read_id, + write_id, + max_lba_id, + 0, + ), + ) + .unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + }) + } + #[cfg(feature = "mass-storage")] + Some(Opcode::SetBlockDeviceSID) => msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, { xous::send_message( abdcid, xous::Message::new_blocking_scalar( - apps_block_device::BlockDeviceMgmtOp::SetOps.to_usize().unwrap(), read_id, write_id, max_lba_id, 0, - ) - ).unwrap(); + apps_block_device::BlockDeviceMgmtOp::SetSID.to_usize().unwrap(), + sid1, + sid2, + sid3, + sid4, + ), + ) + .unwrap(); xous::return_scalar(msg.sender, 0).unwrap(); }), - #[cfg(feature="mass-storage")] - Some(Opcode::SetBlockDeviceSID) => msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, { - xous::send_message(abdcid, - xous::Message::new_blocking_scalar( - apps_block_device::BlockDeviceMgmtOp::SetSID.to_usize().unwrap(), sid1, sid2, sid3, sid4 - ) - ).unwrap(); - xous::return_scalar(msg.sender, 0).unwrap(); - }), - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] Some(Opcode::ResetBlockDevice) => msg_blocking_scalar_unpack!(msg, 0, 0, 0, 0, { - xous::send_message(abdcid, + xous::send_message( + abdcid, xous::Message::new_blocking_scalar( - apps_block_device::BlockDeviceMgmtOp::Reset.to_usize().unwrap(), 0, 0, 0, 0, - ) - ).unwrap(); + apps_block_device::BlockDeviceMgmtOp::Reset.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .unwrap(); xous::return_scalar(msg.sender, 0).unwrap(); }), Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { @@ -436,29 +462,27 @@ pub(crate) fn main_hw() -> ! { Views::FidoWithKbd => { match usb_dev.force_reset() { Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () + _ => (), }; } Views::FidoOnly => { match fido_dev.force_reset() { Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () + _ => (), }; } - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] Views::MassStorage => { // TODO: test this match ums_device.force_reset() { Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () + _ => (), }; } - Views::Serial => { - match serial_device.force_reset() { - Err(e) => log::warn!("USB reset on resume failed: {:?}", e), - _ => () - } - } + Views::Serial => match serial_device.force_reset() { + Err(e) => log::warn!("USB reset on resume failed: {:?}", e), + _ => (), + }, } // resume2 brings us to our last application state usbmgmt.xous_resume2(); @@ -472,14 +496,23 @@ pub(crate) fn main_hw() -> ! { fido_listener_pid = msg.sender.pid(); } if fido_listener.is_some() { - log::error!("Double-listener request detected. There should only ever by one registered listener at a time."); - log::error!("This will cause an upstream server to misbehave, but not panicing so the problem can be debugged."); - // the receiver will get a response with the `code` field still in the `RxWait` state to indicate the problem + log::error!( + "Double-listener request detected. There should only ever by one registered listener at a time." + ); + log::error!( + "This will cause an upstream server to misbehave, but not panicing so the problem can be debugged." + ); + // the receiver will get a response with the `code` field still in the `RxWait` state to + // indicate the problem } if fido_listener_pid == msg.sender.pid() { // preferentially pull from the rx queue if it has elements if let Some(data) = fido_rx_queue.pop_front() { - log::debug!("no deferral: ret queued data: {:?} queue len: {}", &data[..8], fido_rx_queue.len() + 1); + log::debug!( + "no deferral: ret queued data: {:?} queue len: {}", + &data[..8], + fido_rx_queue.len() + 1 + ); let mut response = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; @@ -490,26 +523,40 @@ pub(crate) fn main_hw() -> ! { response.replace(buf).unwrap(); } else { log::trace!("registering deferred listener"); - { // not tested + { + // not tested let spec = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; if let Some(to) = spec.to_original::().unwrap().timeout_ms { let target = tt.elapsed_ms() + to; target_time_lsb.store(target as u32, Ordering::SeqCst); // this will keep updating the target time later and later - // run must always be set *after* target time is updated, because there is always a chance - // we timed out and checked target time between these two steps + // run must always be set *after* target time is updated, because there is + // always a chance we timed out and checked + // target time between these two steps to_run.store(true, Ordering::SeqCst); - xous::try_send_message(to_conn, - xous::Message::new_scalar(TimeoutOp::Pump.to_usize().unwrap(), 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + to_conn, + xous::Message::new_scalar( + TimeoutOp::Pump.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); } }; fido_listener = Some(msg); } } else { - log::warn!("U2F interface capability is locked on first use; additional servers are ignored: {:?}", msg.sender); - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + log::warn!( + "U2F interface capability is locked on first use; additional servers are ignored: {:?}", + msg.sender + ); + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut u2f_ipc = buffer.to_original::().unwrap(); u2f_ipc.code = U2fCode::Denied; buffer.replace(u2f_ipc).unwrap(); @@ -531,7 +578,8 @@ pub(crate) fn main_hw() -> ! { if fido_listener_pid.is_none() { fido_listener_pid = msg.sender.pid(); } - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut u2f_ipc = buffer.to_original::().unwrap(); if fido_listener_pid == msg.sender.pid() { let mut u2f_msg = RawFidoReport::default(); @@ -540,7 +588,7 @@ pub(crate) fn main_hw() -> ! { let u2f = match view { Views::FidoWithKbd => composite.device::, _>(), Views::FidoOnly => fido_class.device::, _>(), - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] Views::MassStorage => panic!("did not expect u2f tx when in mass storage mode!"), Views::Serial => panic!("did not expect u2f tx while in serial mode!"), }; @@ -574,52 +622,44 @@ pub(crate) fn main_hw() -> ! { } else { None } - }, - #[cfg(feature="mass-storage")] + } + #[cfg(feature = "mass-storage")] Views::MassStorage => { if ums_device.poll(&mut [&mut ums]) { log::debug!("ums device had something to do!") } None - }, + } Views::Serial => { if serial_device.poll(&mut [&mut serial_port]) { let mut data = [0u8; SERIAL_BUF_LEN]; match serial_listen_mode { - SerialListenMode::NoListener => { - match serial_port.read(&mut data) { - Ok(len) => { - match std::str::from_utf8(&data[..len]) { - Ok(s) => log::debug!("No listener ascii: {}", s), - Err(_) => { - log::debug!("No listener binary: {:x?}", &data[..len]); - } + SerialListenMode::NoListener => match serial_port.read(&mut data) { + Ok(len) => match std::str::from_utf8(&data[..len]) { + Ok(s) => log::debug!("No listener ascii: {}", s), + Err(_) => { + log::debug!("No listener binary: {:x?}", &data[..len]); + } + }, + Err(e) => { + log::debug!("No listener: {:?}", e); + } + }, + SerialListenMode::ConsoleListener => match serial_port.read(&mut data) { + Ok(len) => match std::str::from_utf8(&data[..len]) { + Ok(s) => { + for c in s.chars() { + native_kbd.inject_key(c); } } - Err(e) => { - log::debug!("No listener: {:?}", e); + Err(_) => { + log::info!("Non UTF-8 received on console: {:x?}", &data[..len]); } + }, + Err(e) => { + log::info!("Serial read error: {:?}", e); } - } - SerialListenMode::ConsoleListener => { - match serial_port.read(&mut data) { - Ok(len) => { - match std::str::from_utf8(&data[..len]) { - Ok(s) => { - for c in s.chars() { - native_kbd.inject_key(c); - } - }, - Err(_) => { - log::info!("Non UTF-8 received on console: {:x?}", &data[..len]); - } - } - } - Err(e) => { - log::info!("Serial read error: {:?}", e); - } - } - } + }, SerialListenMode::AsciiListener(maybe_delimiter) => { let readlen = serial_port.read(&mut data).unwrap_or(0); if readlen == 0 { @@ -627,10 +667,17 @@ pub(crate) fn main_hw() -> ! { } if let Some(delimiter) = maybe_delimiter { if !delimiter.is_ascii() { - log::warn!("Chosen ASCII delimiter {} is not ASCII. Serial receive will not function properly.", delimiter); + log::warn!( + "Chosen ASCII delimiter {} is not ASCII. Serial receive will not function properly.", + delimiter + ); } - if !serial_rx_trigger { // once true, sticks as true - serial_rx_trigger = data[..readlen].iter().find(|&&c| c == (delimiter as u8)).is_some(); + if !serial_rx_trigger { + // once true, sticks as true + serial_rx_trigger = data[..readlen] + .iter() + .find(|&&c| c == (delimiter as u8)) + .is_some(); } } else { serial_rx_trigger = true; @@ -643,11 +690,18 @@ pub(crate) fn main_hw() -> ! { if serial_rx_trigger && serial_listener.is_some() { let mut rx_msg = serial_listener.take().unwrap(); let mut response = unsafe { - Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + Buffer::from_memory_message_mut( + rx_msg.body.memory_message_mut().unwrap(), + ) }; let mut buf = response.to_original::().unwrap(); use std::fmt::Write; // is this really the best way to do it? probably not. - write!(buf.s, "{}", std::string::String::from_utf8_lossy(&serial_buf)).ok(); + write!( + buf.s, + "{}", + std::string::String::from_utf8_lossy(&serial_buf) + ) + .ok(); response.replace(buf).unwrap(); // the rx_msg will drop and respond to the listener @@ -667,10 +721,15 @@ pub(crate) fn main_hw() -> ! { match serial_listener.take() { Some(mut rx_msg) => { let mut response = unsafe { - Buffer::from_memory_message_mut(rx_msg.body.memory_message_mut().unwrap()) + Buffer::from_memory_message_mut( + rx_msg.body.memory_message_mut().unwrap(), + ) }; - let mut buf = response.to_original::().unwrap(); - buf.d.copy_from_slice(serial_buf.drain(..SERIAL_BINARY_BUFLEN).as_slice()); + let mut buf = + response.to_original::().unwrap(); + buf.d.copy_from_slice( + serial_buf.drain(..SERIAL_BINARY_BUFLEN).as_slice(), + ); buf.len = SERIAL_BINARY_BUFLEN; response.replace(buf).unwrap(); // the rx_msg will drop and respond to the listener @@ -684,7 +743,7 @@ pub(crate) fn main_hw() -> ! { } } None - }, + } }; if let Some(u2f) = maybe_u2f { match u2f.read_report() { @@ -692,7 +751,9 @@ pub(crate) fn main_hw() -> ! { if let Some(mut listener) = fido_listener.take() { to_run.store(false, Ordering::SeqCst); // stop the timeout process from running let mut response = unsafe { - Buffer::from_memory_message_mut(listener.body.memory_message_mut().unwrap()) + Buffer::from_memory_message_mut( + listener.body.memory_message_mut().unwrap(), + ) }; let mut buf = response.to_original::().unwrap(); assert_eq!(buf.code, U2fCode::RxWait, "Expected U2fcode::RxWait in wrapper"); @@ -704,7 +765,7 @@ pub(crate) fn main_hw() -> ! { log::debug!("Got U2F packet, but no server to respond...queuing."); fido_rx_queue.push_back(u2f_report.packet); } - }, + } Err(e) => log::trace!("U2F ERR: {:?}", e), } } @@ -712,14 +773,15 @@ pub(crate) fn main_hw() -> ! { let is_suspend = match view { Views::FidoWithKbd => usb_dev.state() == UsbDeviceState::Suspend, Views::FidoOnly => fido_dev.state() == UsbDeviceState::Suspend, - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] Views::MassStorage => ums_device.state() == UsbDeviceState::Suspend, Views::Serial => serial_device.state() == UsbDeviceState::Suspend, }; if is_suspend { log::info!("suspend detected"); if was_suspend == false { - // FIDO listener needs to know when USB was unplugged, so that it can reset state per FIDO2 spec + // FIDO listener needs to know when USB was unplugged, so that it can reset state per + // FIDO2 spec if let Some(mut listener) = fido_listener.take() { to_run.store(false, Ordering::SeqCst); let mut response = unsafe { @@ -735,25 +797,34 @@ pub(crate) fn main_hw() -> ! { } else { was_suspend = false; } - }, + } // always triggers a reset when called Some(Opcode::SwitchCores) => msg_blocking_scalar_unpack!(msg, core, _, _, _, { // ensure unhook the logger if it's connected to serial let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); // it is never harmful to double-unhook this - xous::send_message(log_conn, - xous::Message::new_blocking_scalar(log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), 0, 0, 0, 0) - ).ok(); + xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); // reset any serial listeners that may have been set serial_listen_mode = SerialListenMode::NoListener; serial_listener.take(); // shut down the TRNG sender if it's set if let Some(trng_cid) = serial_trng_cid.take() { serial_trng_interval.store(0, Ordering::SeqCst); - xous::send_message(trng_cid, - xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::send_message( + trng_cid, + xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); trng.set_test_mode(trng::api::TrngTestMode::None); } @@ -776,7 +847,7 @@ pub(crate) fn main_hw() -> ! { usbmgmt.ll_reset(false); } } - let keyboard = composite.device::, _>(); + let keyboard = composite.device::, _>(); keyboard.write_report([Keyboard::NoEventIndicated]).ok(); // queues an "all key-up" for the interface keyboard.tick().ok(); } @@ -794,7 +865,7 @@ pub(crate) fn main_hw() -> ! { } } } - #[cfg(feature="mass-storage")] + #[cfg(feature = "mass-storage")] UsbDeviceType::MassStorage => { log::info!("Connecting device mass storage; disconnecting debug USB core"); match view { @@ -831,21 +902,31 @@ pub(crate) fn main_hw() -> ! { let devtype: UsbDeviceType = core.try_into().unwrap(); // if we are switching away from serial, unhook any possible listeners, and the logger if view == Views::Serial && devtype != UsbDeviceType::Serial { - let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); + let log_conn = + xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); // it is never harmful to double-unhook this - xous::send_message(log_conn, - xous::Message::new_blocking_scalar(log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), 0, 0, 0, 0) - ).ok(); + xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); // reset any serial listeners that may have been set serial_listen_mode = SerialListenMode::NoListener; serial_listener.take(); // shut down the TRNG sender if it's set if let Some(trng_cid) = serial_trng_cid.take() { serial_trng_interval.store(0, Ordering::SeqCst); - xous::send_message(trng_cid, - xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::send_message( + trng_cid, + xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); trng.set_test_mode(trng::api::TrngTestMode::None); } } @@ -874,7 +955,7 @@ pub(crate) fn main_hw() -> ! { // type matches, do nothing } } - let keyboard = composite.device::, _>(); + let keyboard = composite.device::, _>(); keyboard.write_report([Keyboard::NoEventIndicated]).ok(); // queues an "all key-up" for the interface keyboard.tick().ok(); } @@ -895,8 +976,8 @@ pub(crate) fn main_hw() -> ! { // type matches, do nothing } } - }, - #[cfg(feature="mass-storage")] + } + #[cfg(feature = "mass-storage")] UsbDeviceType::MassStorage => { log::info!("Ensuring mass storage device"); if !usbmgmt.is_device_connected() { @@ -937,11 +1018,19 @@ pub(crate) fn main_hw() -> ! { Some(Opcode::WhichCore) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { if usbmgmt.is_device_connected() { match view { - Views::FidoWithKbd => xous::return_scalar(msg.sender, UsbDeviceType::FidoKbd as usize).unwrap(), - Views::FidoOnly => xous::return_scalar(msg.sender, UsbDeviceType::Fido as usize).unwrap(), - #[cfg(feature="mass-storage")] - Views::MassStorage => xous::return_scalar(msg.sender, UsbDeviceType::MassStorage as usize).unwrap(), - Views::Serial => xous::return_scalar(msg.sender, UsbDeviceType::Serial as usize).unwrap(), + Views::FidoWithKbd => { + xous::return_scalar(msg.sender, UsbDeviceType::FidoKbd as usize).unwrap() + } + Views::FidoOnly => { + xous::return_scalar(msg.sender, UsbDeviceType::Fido as usize).unwrap() + } + #[cfg(feature = "mass-storage")] + Views::MassStorage => { + xous::return_scalar(msg.sender, UsbDeviceType::MassStorage as usize).unwrap() + } + Views::Serial => { + xous::return_scalar(msg.sender, UsbDeviceType::Serial as usize).unwrap() + } } } else { xous::return_scalar(msg.sender, UsbDeviceType::Debug as usize).unwrap(); @@ -971,23 +1060,17 @@ pub(crate) fn main_hw() -> ! { usbmgmt.disable_debug(false); } } - // at this point, *read back* the new state -- don't assume it "took". The readback is always based on - // a real hardware value and not the requested value. for now, always false. - let is_locked = if usbmgmt.get_disable_debug() { - 1 - } else { - 0 - }; + // at this point, *read back* the new state -- don't assume it "took". The readback is always + // based on a real hardware value and not the requested value. for now, always + // false. + let is_locked = if usbmgmt.get_disable_debug() { 1 } else { 0 }; - // this is a performance optimization. we could always redraw the status, but, instead we only redraw when - // the status has changed. However, there is an edge case: on a resume from suspend, the status needs a redraw, - // even if nothing has changed. Thus, we have this separate boolean we send back to force an update in the + // this is a performance optimization. we could always redraw the status, but, instead we only + // redraw when the status has changed. However, there is an edge case: on a + // resume from suspend, the status needs a redraw, even if nothing has + // changed. Thus, we have this separate boolean we send back to force an update in the // case that we have just come out of a suspend. - let force_update = if lockstatus_force_update { - 1 - } else { - 0 - }; + let force_update = if lockstatus_force_update { 1 } else { 0 }; xous::return_scalar2(msg.sender, is_locked, force_update).expect("couldn't return status"); lockstatus_force_update = false; }), @@ -995,8 +1078,10 @@ pub(crate) fn main_hw() -> ! { match view { Views::FidoWithKbd => xous::return_scalar(msg.sender, usb_dev.state() as usize).unwrap(), Views::FidoOnly => xous::return_scalar(msg.sender, fido_dev.state() as usize).unwrap(), - #[cfg(feature="mass-storage")] - Views::MassStorage => xous::return_scalar(msg.sender, ums_device.state() as usize).unwrap(), + #[cfg(feature = "mass-storage")] + Views::MassStorage => { + xous::return_scalar(msg.sender, ums_device.state() as usize).unwrap() + } Views::Serial => xous::return_scalar(msg.sender, serial_device.state() as usize).unwrap(), } }), @@ -1006,31 +1091,31 @@ pub(crate) fn main_hw() -> ! { if usb_dev.state() == UsbDeviceState::Configured { let mut codes = Vec::::new(); if code0 != 0 { - codes.push( - match native_map { - KeyMap::Dvorak => mappings::char_to_hid_code_dvorak(code0 as u8 as char)[0], - _ => mappings::char_to_hid_code_us101(code0 as u8 as char)[0], + codes.push(match native_map { + KeyMap::Dvorak => { + mappings::char_to_hid_code_dvorak(code0 as u8 as char)[0] } - ); + _ => mappings::char_to_hid_code_us101(code0 as u8 as char)[0], + }); } if code1 != 0 { - codes.push( - match native_map { - KeyMap::Dvorak => mappings::char_to_hid_code_dvorak(code1 as u8 as char)[0], - _ => mappings::char_to_hid_code_us101(code1 as u8 as char)[0], + codes.push(match native_map { + KeyMap::Dvorak => { + mappings::char_to_hid_code_dvorak(code1 as u8 as char)[0] } - ); + _ => mappings::char_to_hid_code_us101(code1 as u8 as char)[0], + }); } if code2 != 0 { - codes.push( - match native_map { - KeyMap::Dvorak => mappings::char_to_hid_code_dvorak(code2 as u8 as char)[0], - _ => mappings::char_to_hid_code_us101(code2 as u8 as char)[0], + codes.push(match native_map { + KeyMap::Dvorak => { + mappings::char_to_hid_code_dvorak(code2 as u8 as char)[0] } - ); + _ => mappings::char_to_hid_code_us101(code2 as u8 as char)[0], + }); } - let auto_up = if autoup == 1 {true} else {false}; - let keyboard = composite.device::, _>(); + let auto_up = if autoup == 1 { true } else { false }; + let keyboard = composite.device::, _>(); keyboard.write_report(codes).ok(); keyboard.tick().ok(); tt.sleep_ms(autotype_delay_ms).ok(); @@ -1055,9 +1140,11 @@ pub(crate) fn main_hw() -> ! { // the whole subsystem stuck in some awful recursive error handling hell. match view { Views::Serial => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let buffer = + unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let usb_send = buffer.to_original::().unwrap(); - // this is implemented as a "blocking write": the routine will block until the data has all been written. + // this is implemented as a "blocking write": the routine will block until the data + // has all been written. let send_data = usb_send.s.as_bytes(); let to_send = usb_send.s.len(); let mut sent = 0; @@ -1071,7 +1158,7 @@ pub(crate) fn main_hw() -> ! { } } match serial_port.flush() { - Ok(_) => {}, + Ok(_) => {} Err(_) => { // just drop characters } @@ -1084,21 +1171,20 @@ pub(crate) fn main_hw() -> ! { Some(Opcode::SetAutotypeRate) => msg_scalar_unpack!(msg, rate, _, _, _, { // limit rate to 0.5s delay. Even then, this will probably cause repeated characters because // it also adjusts keydown delays - let checked_rate = if rate > 500 { - 500 - } else { rate }; + let checked_rate = if rate > 500 { 500 } else { rate }; // there is no limit on the minimum rate. good luck if you set it to 0! autotype_delay_ms = checked_rate; }), Some(Opcode::SendString) => { - let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let mut buffer = + unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut usb_send = buffer.to_original::().unwrap(); - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] let mut sent = 0; - #[cfg(feature="minimal")] + #[cfg(feature = "minimal")] let sent = 0; match view { - #[cfg(not(feature="minimal"))] + #[cfg(not(feature = "minimal"))] Views::FidoWithKbd => { for ch in usb_send.s.as_str().unwrap().chars() { // ASSUME: user's keyboard type matches the preference on their Precursor device. @@ -1117,7 +1203,8 @@ pub(crate) fn main_hw() -> ! { } } Views::Serial => { - // this is implemented as a "blocking write": the routine will block until the data has all been written. + // this is implemented as a "blocking write": the routine will block until the data + // has all been written. let send_data = usb_send.s.as_bytes(); let to_send = usb_send.s.len(); // log::debug!("serial RTS: {:?}", serial_port.rts()); @@ -1133,7 +1220,7 @@ pub(crate) fn main_hw() -> ! { } } match serial_port.flush() { - Ok(_) => {}, + Ok(_) => {} Err(_) => { log::warn!("Serial port reported WouldBlock on flush"); tt.sleep_ms(100).ok(); @@ -1153,23 +1240,28 @@ pub(crate) fn main_hw() -> ! { }), Some(Opcode::SerialHookAscii) => { let maybe_delimiter = { - let buffer = unsafe { - Buffer::from_memory_message(msg.body.memory_message().unwrap()) - }; + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let data = buffer.to_original::().unwrap(); data.delimiter }; serial_listen_mode = SerialListenMode::AsciiListener(maybe_delimiter); serial_listener = Some(msg); - }, + } Some(Opcode::SerialHookBinary) => { serial_listen_mode = SerialListenMode::BinaryListener; serial_listener = Some(msg); - }, + } Some(Opcode::SerialHookConsole) => msg_scalar_unpack!(msg, _, _, _, _, { let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); - match xous::send_message(log_conn, - xous::Message::new_blocking_scalar(log_server::api::Opcode::TryHookUsbMirror.to_usize().unwrap(), 0, 0, 0, 0) + match xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::TryHookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), ) { Ok(xous::Result::Scalar1(result)) => { if result == 1 { @@ -1188,19 +1280,28 @@ pub(crate) fn main_hw() -> ! { Some(Opcode::SerialClearHooks) => { let log_conn = xous::connect(xous::SID::from_bytes(b"xous-log-server ").unwrap()).unwrap(); // it is never harmful to double-unhook this - xous::send_message(log_conn, - xous::Message::new_blocking_scalar(log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), 0, 0, 0, 0) - ).ok(); + xous::send_message( + log_conn, + xous::Message::new_blocking_scalar( + log_server::api::Opcode::UnhookUsbMirror.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); serial_listen_mode = SerialListenMode::NoListener; serial_listener.take(); // shut down the TRNG sender if it's set if let Some(trng_cid) = serial_trng_cid.take() { serial_trng_interval.store(0, Ordering::SeqCst); - xous::send_message(trng_cid, - xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::send_message( + trng_cid, + xous::Message::new_blocking_scalar(TrngOp::Quit.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); trng.set_test_mode(trng::api::TrngTestMode::None); } } @@ -1254,17 +1355,23 @@ pub(crate) fn main_hw() -> ! { } match serial_listen_mode { SerialListenMode::ConsoleListener => { - log::error!("Serial is already hooked as a console. Refusing to turn on TRNG source mode"); + log::error!( + "Serial is already hooked as a console. Refusing to turn on TRNG source mode" + ); continue; } - SerialListenMode::NoListener => {}, + SerialListenMode::NoListener => {} _ => { - log::warn!("Serial already has a listener {:?} attached, hooking TRNG at your risk!", serial_listen_mode); + log::warn!( + "Serial already has a listener {:?} attached, hooking TRNG at your risk!", + serial_listen_mode + ); } } - let trng_mode: trng::api::TrngTestMode = num_traits::FromPrimitive::from_usize(trng_mode_code) - .unwrap_or(trng::api::TrngTestMode::None); + let trng_mode: trng::api::TrngTestMode = + num_traits::FromPrimitive::from_usize(trng_mode_code) + .unwrap_or(trng::api::TrngTestMode::None); if trng_mode == trng::api::TrngTestMode::None { // ignore the call in case of a bad parameter continue; @@ -1297,10 +1404,10 @@ pub(crate) fn main_hw() -> ! { let mut debug_count = 0; loop { xous::reply_and_receive_next_legacy(trng_sid, &mut msg_opt, &mut return_type) - .unwrap(); + .unwrap(); let msg = msg_opt.as_mut().unwrap(); match num_traits::FromPrimitive::from_usize(msg.body.id()) - .unwrap_or(TrngOp::InvalidCall) + .unwrap_or(TrngOp::InvalidCall) { TrngOp::Pump => { let next_interval = serial_trng_interval.load(Ordering::SeqCst); @@ -1309,17 +1416,32 @@ pub(crate) fn main_hw() -> ! { debug_count += 1; } if next_interval > 0 { - xous::try_send_message(main_conn, - xous::Message::new_scalar(Opcode::SerialTrngPoll.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + main_conn, + xous::Message::new_scalar( + Opcode::SerialTrngPoll.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); tt.sleep_ms(next_interval as _).ok(); - xous::try_send_message(trng_cid, - xous::Message::new_scalar(TrngOp::Pump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); - // reset debug_count so when the next trigger comes we can see the output - if next_interval > 100 { + xous::try_send_message( + trng_cid, + xous::Message::new_scalar( + TrngOp::Pump.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .ok(); + // reset debug_count so when the next trigger comes we can see the + // output + if next_interval > 100 { debug_count = 0; } } else { @@ -1331,15 +1453,20 @@ pub(crate) fn main_hw() -> ! { scalar.id = 0; scalar.arg1 = 1; log::info!("Quit called to Trng helper thread"); - // I think there might be a bug in the kernel where quitting/disconnecting + // I think there might be a bug in the kernel where + // quitting/disconnecting // a reply_and_receive_next_legacy() loop is broken? // This results in an inexplicable kernel hang... - // for now we can work around this by keeping the thread around once the server is started. + // for now we can work around this by keeping the thread around + // once the server is started. // break; } } TrngOp::InvalidCall => { - log::error!("Unknown opcode received in TRNG source handler: {:?}", msg.body.id()); + log::error!( + "Unknown opcode received in TRNG source handler: {:?}", + msg.body.id() + ); } } } @@ -1354,10 +1481,11 @@ pub(crate) fn main_hw() -> ! { } // kick off the polling thread if let Some(trng_cid) = serial_trng_cid.as_ref() { - xous::try_send_message(*trng_cid, - xous::Message::new_scalar(TrngOp::Pump.to_usize().unwrap(), - 0, 0, 0, 0) - ).ok(); + xous::try_send_message( + *trng_cid, + xous::Message::new_scalar(TrngOp::Pump.to_usize().unwrap(), 0, 0, 0, 0), + ) + .ok(); } }), Some(Opcode::SerialTrngPoll) => { @@ -1378,8 +1506,8 @@ pub(crate) fn main_hw() -> ! { } } } - // at this point, we should have data we can copy to the buffer. Pull it from the end of the buffer - // so the Vec can efficiently de-allocate data. + // at this point, we should have data we can copy to the buffer. Pull it from the end of + // the buffer so the Vec can efficiently de-allocate data. match serial_port.flush() { Ok(_) => { let available = serial_trng_buf.len(); @@ -1412,7 +1540,7 @@ pub(crate) fn main_hw() -> ! { Some(Opcode::Quit) => { log::warn!("Quit received, goodbye world!"); break; - }, + } None => { log::error!("couldn't convert opcode: {:?}", msg); } @@ -1424,4 +1552,4 @@ pub(crate) fn main_hw() -> ! { xous::destroy_server(usbdev_sid).unwrap(); log::trace!("quitting"); xous::terminate_process(0) -} \ No newline at end of file +} diff --git a/services/usb-device-xous/src/mappings.rs b/services/usb-device-xous/src/mappings.rs index 1b1a1d076..a7cf62cf8 100644 --- a/services/usb-device-xous/src/mappings.rs +++ b/services/usb-device-xous/src/mappings.rs @@ -2,6 +2,7 @@ pub use xous_usb_hid::page::Keyboard as UsbKeyCode; #[cfg(any(feature="precursor", feature="renode"))] +#[rustfmt::skip] pub fn char_to_hid_code_us101(key: char) -> Vec { let mut code = vec![]; match key { @@ -120,6 +121,7 @@ pub fn char_to_hid_code_us101(key: char) -> Vec { /// auto-generated using tools/kbd_layout.py + `usb kbdtest` on device for dvorak layout on US101 #[cfg(any(feature="precursor", feature="renode"))] +#[rustfmt::skip] pub fn char_to_hid_code_dvorak(key: char) -> Vec { let mut code = vec![]; match key { @@ -224,4 +226,4 @@ pub fn char_to_hid_code_dvorak(key: char) -> Vec { _ => log::warn!("Ignoring unhandled character: {}", key), }; code -} \ No newline at end of file +} diff --git a/services/usb-device-xous/src/spinal_udc.rs b/services/usb-device-xous/src/spinal_udc.rs index 12aee0105..7d124ee97 100644 --- a/services/usb-device-xous/src/spinal_udc.rs +++ b/services/usb-device-xous/src/spinal_udc.rs @@ -1,12 +1,12 @@ +use core::mem::size_of; +use core::sync::atomic::{AtomicPtr, Ordering}; +use std::fmt; + /// Abstractions for the Spinal UDC controller. /// See https://spinalhdl.github.io/SpinalDoc-RTD/dev/SpinalHDL/Libraries/Com/usb_device.html /// for documentation. - use bitfield::bitfield; use usb_device::UsbDirection; -use std::fmt; -use core::sync::atomic::{AtomicPtr, Ordering}; -use core::mem::size_of; pub(crate) const NUM_ENDPOINTS: usize = 16; @@ -44,11 +44,7 @@ impl fmt::Debug for UdcInterrupts { if self.resume() { f.write_str("resume ")?; } - if self.disconnect() { - f.write_str("disconnect ") - } else { - Ok(()) - } + if self.disconnect() { f.write_str("disconnect ") } else { Ok(()) } } } } @@ -87,73 +83,74 @@ const CONFIG_OFFSET: usize = 0x10; const RAMSIZE_OFFSET: usize = 0x20; #[allow(dead_code)] impl SpinalUdcRegs { - pub fn new(ptr: *mut u32) -> SpinalUdcRegs { - SpinalUdcRegs { - regs: AtomicPtr::new(ptr) - } - } + pub fn new(ptr: *mut u32) -> SpinalUdcRegs { SpinalUdcRegs { regs: AtomicPtr::new(ptr) } } + pub fn clone(&self) -> SpinalUdcRegs { - SpinalUdcRegs { - regs: AtomicPtr::new(self.regs.load(Ordering::SeqCst)) - } + SpinalUdcRegs { regs: AtomicPtr::new(self.regs.load(Ordering::SeqCst)) } } + /// current USB frame ID pub fn frame_id(&self) -> u32 { - unsafe { - self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::()).read_volatile() - } + unsafe { self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::()).read_volatile() } } + /// currently active address for tokens. cleared by USB reset pub fn address(&self) -> u32 { - unsafe { - self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::()).read_volatile() - } + unsafe { self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::()).read_volatile() } } + pub fn set_address(&self, addr: u32) { unsafe { self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::()).write_volatile(addr); } } + /// interrupt flags pub fn interrupts(&self) -> UdcInterrupts { unsafe { UdcInterrupts(self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::()).read_volatile()) } } + pub fn clear_some_interrupts(&self, ints: UdcInterrupts) { unsafe { self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::()).write_volatile(ints.0); } } + pub fn clear_all_interrupts(&self) { unsafe { self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::()).write_volatile(0xffff_ffff); } } + /// halt - use this to pause an endpoint to give the CPU a mutex on r/w access to its registers pub fn halt(&self) -> UdcHalt { unsafe { UdcHalt(self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::()).read_volatile()) } } + pub fn set_halt(&self, halt: UdcHalt) { - unsafe { - self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::()).write_volatile(halt.0) - } + unsafe { self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::()).write_volatile(halt.0) } } + /// config pub fn config(&self) -> UdcConfig { unsafe { UdcConfig(self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::()).read_volatile()) } } + pub fn set_config(&self, cfg: UdcConfig) { unsafe { self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::()).write_volatile(cfg.0) } } - /// the ram starting at 0 has a size of 1 << ramsize. Only the lower 4 bits are valid, but the field takes up a u32 - /// the returned value is the properly computed bytes as read out by the hardware field (no further maths needed) + + /// the ram starting at 0 has a size of 1 << ramsize. Only the lower 4 bits are valid, but the field takes + /// up a u32 the returned value is the properly computed bytes as read out by the hardware field (no + /// further maths needed) pub fn ramsize(&self) -> u32 { 1 << (unsafe { self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::()).read_volatile() @@ -162,11 +159,7 @@ impl SpinalUdcRegs { } impl fmt::Debug for SpinalUdcRegs { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "UDC: frame{}, adr{}, ints: {:?}", - self.frame_id(), - self.address(), - self.interrupts(), - ) + write!(f, "UDC: frame{}, adr{}, ints: {:?}", self.frame_id(), self.address(), self.interrupts(),) } } @@ -184,14 +177,16 @@ bitfield! { } impl fmt::Debug for UdcEpStatus { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Ep{}@0x{:x}^{}: {}{}{}{}", - if self.enable() {"ENA"} else {"DIS"}, + write!( + f, + "Ep{}@0x{:x}^{}: {}{}{}{}", + if self.enable() { "ENA" } else { "DIS" }, self.head_offset() * 16, self.max_packet_size(), - if self.force_stall() {"STALL "} else {""}, - if self.force_nack() {"NACK "} else {""}, - if self.data_phase() {"DATA1 "} else {"DATA0 "}, - if self.isochronous() {"ISO "} else {""}, + if self.force_stall() { "STALL " } else { "" }, + if self.force_nack() { "NACK " } else { "" }, + if self.data_phase() { "DATA1 " } else { "DATA0 " }, + if self.isochronous() { "ISO " } else { "" }, ) } } @@ -226,72 +221,82 @@ bitfield! { // forces dataphase to DATA1 when the descriptor is complete pub data1_on_completion, set_data1_on_completion: 19; } -/// This structure maps onto a variable length region anywhere inside the UDC region. It is always aligned to a 16-byte offset +/// This structure maps onto a variable length region anywhere inside the UDC region. It is always aligned to +/// a 16-byte offset pub struct SpinalUdcDescriptor { - base: AtomicPtr::, + base: AtomicPtr, } #[allow(dead_code)] impl SpinalUdcDescriptor { - pub fn new(base: *mut u32) -> SpinalUdcDescriptor { - SpinalUdcDescriptor { base: AtomicPtr::new(base) } - } + pub fn new(base: *mut u32) -> SpinalUdcDescriptor { SpinalUdcDescriptor { base: AtomicPtr::new(base) } } + pub(crate) fn read(&self, offset: usize) -> u32 { - // we don't do asserts on reads because for debugging sometimes we reveal invalid descriptors and that's OK - unsafe{self.base.load(Ordering::SeqCst).add(offset).read_volatile()} + // we don't do asserts on reads because for debugging sometimes we reveal invalid descriptors and + // that's OK + unsafe { self.base.load(Ordering::SeqCst).add(offset).read_volatile() } } + fn write(&self, offset: usize, data: u32) { // -16 for the dedicated ep0-out space - assert!((self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16, "descriptor is illegal (too low)! 0x{:x}", self.base.load(Ordering::SeqCst) as u32); - assert!((self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET, "descriptor is illegal (too high)! 0x{:x}", self.base.load(Ordering::SeqCst) as u32); - unsafe{self.base.load(Ordering::SeqCst).add(offset).write_volatile(data)} - } - pub fn offset(&self) -> usize { - UdcDesc0(self.read(0)).offset() as usize - } - pub fn in_progress(&self) -> bool { - UdcDesc0(self.read(0)).code() == 0xF - } - pub fn next_descriptor_addr(&self) -> usize { - UdcDesc1(self.read(1)).next_descriptor_addr() as usize - } - pub fn length(&self) -> usize { - UdcDesc1(self.read(1)).length() as usize + assert!( + (self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16, + "descriptor is illegal (too low)! 0x{:x}", + self.base.load(Ordering::SeqCst) as u32 + ); + assert!( + (self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET, + "descriptor is illegal (too high)! 0x{:x}", + self.base.load(Ordering::SeqCst) as u32 + ); + unsafe { self.base.load(Ordering::SeqCst).add(offset).write_volatile(data) } } + + pub fn offset(&self) -> usize { UdcDesc0(self.read(0)).offset() as usize } + + pub fn in_progress(&self) -> bool { UdcDesc0(self.read(0)).code() == 0xF } + + pub fn next_descriptor_addr(&self) -> usize { UdcDesc1(self.read(1)).next_descriptor_addr() as usize } + + pub fn length(&self) -> usize { UdcDesc1(self.read(1)).length() as usize } + pub fn direction(&self) -> UsbDirection { - if UdcDesc2(self.read(2)).direction() { - UsbDirection::In - } else { - UsbDirection::Out - } - } - pub fn int_on_done(&self) -> bool { - UdcDesc2(self.read(2)).int_on_done() - } - pub fn completion_on_full(&self) -> bool { - UdcDesc2(self.read(2)).completion_on_full() - } - pub fn data1_on_completion(&self) -> bool { - UdcDesc2(self.read(2)).data1_on_completion() + if UdcDesc2(self.read(2)).direction() { UsbDirection::In } else { UsbDirection::Out } } + + pub fn int_on_done(&self) -> bool { UdcDesc2(self.read(2)).int_on_done() } + + pub fn completion_on_full(&self) -> bool { UdcDesc2(self.read(2)).completion_on_full() } + + pub fn data1_on_completion(&self) -> bool { UdcDesc2(self.read(2)).data1_on_completion() } + pub fn set_offset(&self, offset: usize) { let mut d0 = UdcDesc0(0); d0.set_offset(offset as _); d0.set_code(0xF); // automatically set in_progress self.write(0, d0.0); } + pub fn set_offset_only(&self, offset: usize) { let mut d0 = UdcDesc0(0); d0.set_offset(offset as _); d0.set_code(0x0); // clears in_progress self.write(0, d0.0); } + pub fn set_next_desc_and_len(&self, next_addr: usize, length: usize) { let mut d1 = UdcDesc1(0); d1.set_length(length as _); d1.set_next_descriptor_addr(next_addr as _); self.write(1, d1.0); } - pub fn set_desc_flags(&self, direction: UsbDirection, int_on_done: bool, completion_on_full: bool, data1_on_completion: bool) { + + pub fn set_desc_flags( + &self, + direction: UsbDirection, + int_on_done: bool, + completion_on_full: bool, + data1_on_completion: bool, + ) { let mut d2 = UdcDesc2(0); match direction { UsbDirection::In => d2.set_direction(true), @@ -302,24 +307,30 @@ impl SpinalUdcDescriptor { d2.set_data1_on_completion(data1_on_completion); self.write(2, d2.0); } + pub fn write_data(&self, offset_word: usize, data: u32) { // -16 for the dedicated ep0-out space - assert!((self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16, "descriptor is illegal (too low)!"); - assert!((self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET, "descriptor is illegal (too high)!"); - unsafe { - self.base.load(Ordering::SeqCst).add(3 + offset_word).write_volatile(data) - } + assert!( + (self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16, + "descriptor is illegal (too low)!" + ); + assert!( + (self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET, + "descriptor is illegal (too high)!" + ); + unsafe { self.base.load(Ordering::SeqCst).add(3 + offset_word).write_volatile(data) } } + pub fn read_data(&self, offset_word: usize) -> u32 { - unsafe { - self.base.load(Ordering::SeqCst).add(3 + offset_word).read_volatile() - } + unsafe { self.base.load(Ordering::SeqCst).add(3 + offset_word).read_volatile() } } } impl fmt::Debug for SpinalUdcDescriptor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Desc({}){}: {} of {} -> 0x{:x} ({}{}{}) [{:x?},{:x?},..] @ {:x?}", - if self.in_progress() {"<>"} else {"--"}, + write!( + f, + "Desc({}){}: {} of {} -> 0x{:x} ({}{}{}) [{:x?},{:x?},..] @ {:x?}", + if self.in_progress() { "<>" } else { "--" }, match self.direction() { UsbDirection::In => "IN", UsbDirection::Out => "OUT", @@ -327,12 +338,12 @@ impl fmt::Debug for SpinalUdcDescriptor { self.offset(), self.length(), self.next_descriptor_addr() * 16, - if self.int_on_done() {"I"} else {"."}, - if self.completion_on_full() {"C"} else {"."}, - if self.data1_on_completion() {"1"} else {"0"}, + if self.int_on_done() { "I" } else { "." }, + if self.completion_on_full() { "C" } else { "." }, + if self.data1_on_completion() { "1" } else { "0" }, self.read_data(0).to_le_bytes(), self.read_data(1).to_le_bytes(), self.base, ) } -} \ No newline at end of file +}