format service/usb-device-xous

avoided formatting of any keymapping lookup tables...
This commit is contained in:
bunnie 2024-01-14 22:52:52 +08:00
parent 49c50e12c1
commit 425e48ed45
10 changed files with 1230 additions and 1031 deletions

View file

@ -1,5 +1,6 @@
// Note: the log server relies on this name not changing in order to hook the serial port for logging output. // 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_"; pub(crate) const SERVER_NAME_USB_DEVICE: &'static str = "_Xous USB device driver_";
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
@ -52,11 +53,11 @@ pub(crate) enum Opcode {
/// TRNG send poll /// TRNG send poll
SerialTrngPoll = 518, SerialTrngPoll = 518,
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
SetBlockDevice = 1024, SetBlockDevice = 1024,
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
SetBlockDeviceSID = 1025, SetBlockDeviceSID = 1025,
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
ResetBlockDevice = 1026, ResetBlockDevice = 1026,
/// Handle the USB interrupt /// Handle the USB interrupt
@ -73,7 +74,7 @@ pub(crate) enum Opcode {
// The log crate depends on this API not changing. // The log crate depends on this API not changing.
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct UsbString { pub struct UsbString {
pub s: xous_ipc::String::<4000>, pub s: xous_ipc::String<4000>,
pub sent: Option<u32>, pub sent: Option<u32>,
} }
@ -104,7 +105,7 @@ pub enum UsbDeviceType {
Debug = 0, Debug = 0,
FidoKbd = 1, FidoKbd = 1,
Fido = 2, Fido = 2,
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
MassStorage = 3, MassStorage = 3,
Serial = 4, Serial = 4,
} }
@ -117,7 +118,7 @@ impl TryFrom<usize> for UsbDeviceType {
0 => Ok(UsbDeviceType::Debug), 0 => Ok(UsbDeviceType::Debug),
1 => Ok(UsbDeviceType::FidoKbd), 1 => Ok(UsbDeviceType::FidoKbd),
2 => Ok(UsbDeviceType::Fido), 2 => Ok(UsbDeviceType::Fido),
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
3 => Ok(UsbDeviceType::MassStorage), 3 => Ok(UsbDeviceType::MassStorage),
4 => Ok(UsbDeviceType::Serial), 4 => Ok(UsbDeviceType::Serial),
_ => Err("Invalid UsbDeviceType specifier"), _ => Err("Invalid UsbDeviceType specifier"),
@ -129,7 +130,7 @@ pub const SERIAL_ASCII_BUFLEN: usize = 512;
pub const SERIAL_BINARY_BUFLEN: usize = 128; pub const SERIAL_BINARY_BUFLEN: usize = 128;
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct UsbSerialAscii { pub struct UsbSerialAscii {
pub s: xous_ipc::String::<SERIAL_ASCII_BUFLEN>, pub s: xous_ipc::String<SERIAL_ASCII_BUFLEN>,
pub delimiter: Option<char>, pub delimiter: Option<char>,
} }

View file

@ -1,7 +1,8 @@
use core::convert::TryInto; use core::convert::TryInto;
use num_traits::*;
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
use num_traits::*;
use usbd_scsi::BlockDevice; use usbd_scsi::BlockDevice;
use xous::msg_blocking_scalar_unpack; use xous::msg_blocking_scalar_unpack;
@ -33,73 +34,58 @@ pub struct AppsBlockDevice {
impl AppsBlockDevice { impl AppsBlockDevice {
pub fn new() -> AppsBlockDevice { pub fn new() -> AppsBlockDevice {
let app_cid = Arc::new(Mutex::new(None)); let app_cid = Arc::new(Mutex::new(None));
let rw_ids = Arc::new(Mutex::new(RwOp { let rw_ids = Arc::new(Mutex::new(RwOp { read_id: 0, write_id: 0, max_lba_id: 0 }));
read_id: 0,
write_id: 0,
max_lba_id: 0,
}));
let app_cid_clone = app_cid.clone(); let app_cid_clone = app_cid.clone();
let rw_ids_clone = rw_ids.clone(); let rw_ids_clone = rw_ids.clone();
let mgmt_sid = xous::create_server().unwrap(); let mgmt_sid = xous::create_server().unwrap();
std::thread::spawn(move || loop { std::thread::spawn(move || {
let msg = xous::receive_message(mgmt_sid).unwrap(); loop {
let opcode: Option<BlockDeviceMgmtOp> = FromPrimitive::from_usize(msg.body.id()); let msg = xous::receive_message(mgmt_sid).unwrap();
match opcode { let opcode: Option<BlockDeviceMgmtOp> = FromPrimitive::from_usize(msg.body.id());
Some(BlockDeviceMgmtOp::SetOps) => { match opcode {
msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { 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(); let mut ids = rw_ids_clone.lock().unwrap();
*ids = RwOp { *ac = None;
read_id, *ids = RwOp { read_id: 0, write_id: 0, max_lba_id: 0 };
write_id,
max_lba_id,
};
log::info!("setting new app block device handler: {:?}", ids);
xous::return_scalar(msg.sender, 0).unwrap(); 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 { AppsBlockDevice { app_cid, rw_ids, mgmt_cid: xous::connect(mgmt_sid).unwrap() }
app_cid,
rw_ids,
mgmt_cid: xous::connect(mgmt_sid).unwrap(),
}
}
pub fn conn(&self) -> xous::CID {
self.mgmt_cid
} }
pub fn conn(&self) -> xous::CID { self.mgmt_cid }
} }
impl BlockDevice for AppsBlockDevice { impl BlockDevice for AppsBlockDevice {
@ -116,21 +102,13 @@ impl BlockDevice for AppsBlockDevice {
let mut request = RawData { raw: [0u8; 4096] }; let mut request = RawData { raw: [0u8; 4096] };
let buf = unsafe { let buf = unsafe {
xous::MemoryRange::new( xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::<RawData>())
&mut request as *mut RawData as usize, .unwrap()
core::mem::size_of::<RawData>(),
)
.unwrap()
}; };
xous::send_message( xous::send_message(
cid, cid,
xous::Message::new_lend_mut( xous::Message::new_lend_mut(rw_ids.read_id, buf, xous::MemoryAddress::new(lba as usize), None),
rw_ids.read_id,
buf,
xous::MemoryAddress::new(lba as usize),
None,
),
) )
.unwrap(); .unwrap();
@ -151,21 +129,13 @@ impl BlockDevice for AppsBlockDevice {
(request.raw[..Self::BLOCK_BYTES as usize]).copy_from_slice(block); (request.raw[..Self::BLOCK_BYTES as usize]).copy_from_slice(block);
let buf = unsafe { let buf = unsafe {
xous::MemoryRange::new( xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::<RawData>())
&mut request as *mut RawData as usize, .unwrap()
core::mem::size_of::<RawData>(),
)
.unwrap()
}; };
xous::send_message( xous::send_message(
cid, cid,
xous::Message::new_lend_mut( xous::Message::new_lend_mut(rw_ids.write_id, buf, xous::MemoryAddress::new(lba as usize), None),
rw_ids.write_id,
buf,
xous::MemoryAddress::new(lba as usize),
None,
),
) )
.unwrap(); .unwrap();
@ -181,11 +151,8 @@ impl BlockDevice for AppsBlockDevice {
let rw_ids = self.rw_ids.lock().unwrap(); let rw_ids = self.rw_ids.lock().unwrap();
match xous::send_message( match xous::send_message(cid, xous::Message::new_blocking_scalar(rw_ids.max_lba_id, 0, 0, 0, 0))
cid, .expect("cannot send message to block device app")
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(), xous::Result::Scalar1(max_lba) => max_lba.try_into().unwrap(),
_ => panic!("received response to max_lba that isn't a Scalar1!"), _ => panic!("received response to max_lba that isn't a Scalar1!"),

View file

@ -4,44 +4,46 @@ pub struct SpinalUdcDescriptor {}
pub struct UdcEpStatus {} pub struct UdcEpStatus {}
pub struct SpinalUsbMgmt { pub struct SpinalUsbMgmt {}
}
impl SpinalUsbMgmt { impl SpinalUsbMgmt {
pub fn print_regs(&self) {} pub fn print_regs(&self) {}
pub fn connect_device_core(&mut self, _state: bool) {} 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 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_suspend(&mut self) {}
pub fn xous_resume1(&mut self) {} pub fn xous_resume1(&mut self) {}
pub fn xous_resume2(&mut self) {} pub fn xous_resume2(&mut self) {}
pub fn descriptor_from_status(&self, _ep_status: &UdcEpStatus) -> SpinalUdcDescriptor { pub fn descriptor_from_status(&self, _ep_status: &UdcEpStatus) -> SpinalUdcDescriptor {
SpinalUdcDescriptor {} SpinalUdcDescriptor {}
} }
pub fn status_from_index(&self, _index: usize) -> UdcEpStatus {
UdcEpStatus {} pub fn status_from_index(&self, _index: usize) -> UdcEpStatus { UdcEpStatus {} }
}
}
pub struct SpinalUsbDevice {
} }
pub struct SpinalUsbDevice {}
impl SpinalUsbDevice { impl SpinalUsbDevice {
pub fn new(_sid: xous::SID, _view: std::sync::Arc::<std::sync::atomic::AtomicUsize>) -> SpinalUsbDevice { pub fn new(_sid: xous::SID, _view: std::sync::Arc<std::sync::atomic::AtomicUsize>) -> SpinalUsbDevice {
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_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 /// simple but easy to understand allocator for buffers inside the descriptor memory space
pub fn alloc_region(&mut self, _requested: usize) -> Option<u32> { pub fn alloc_region(&mut self, _requested: usize) -> Option<u32> { None }
None
}
/// returns `true` if the region was available to be deallocated /// returns `true` if the region was available to be deallocated
pub fn dealloc_region(&mut self, _offset: usize) -> bool { pub fn dealloc_region(&mut self, _offset: usize) -> bool { false }
false
}
} }

File diff suppressed because it is too large Load diff

View file

@ -2,15 +2,15 @@
pub mod api; pub mod api;
pub use api::*; pub use api::*;
use trng::api::TrngTestMode;
use xous::{CID, send_message, Message};
use num_traits::*; 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 packed_struct::PackedStruct;
use trng::api::TrngTestMode;
pub use usb_device::device::UsbDeviceState;
use xous::{send_message, Message, CID};
use xous_ipc::Buffer; use xous_ipc::Buffer;
pub use xous_usb_hid::device::fido::RawFidoReport; 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)] #[derive(Debug)]
pub struct UsbHid { pub struct UsbHid {
@ -20,144 +20,130 @@ impl UsbHid {
pub fn new() -> Self { pub fn new() -> Self {
let xns = xous_names::XousNames::new().expect("couldn't connect to XousNames"); let xns = xous_names::XousNames::new().expect("couldn't connect to XousNames");
REFCOUNT.fetch_add(1, Ordering::Relaxed); 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"); let conn = xns
UsbHid { .request_connection_blocking(api::SERVER_NAME_USB_DEVICE)
conn .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) { 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( Message::new_blocking_scalar(
Opcode::SetBlockDevice.to_usize().unwrap(), Opcode::SetBlockDevice.to_usize().unwrap(),
read_id, read_id,
write_id, write_id,
max_lba_id, max_lba_id,
0, 0,
) ),
).unwrap(); )
.unwrap();
} }
#[cfg(feature="mass-storage")]
#[cfg(feature = "mass-storage")]
pub fn set_block_device_sid(&self, app_sid: xous::SID) { pub fn set_block_device_sid(&self, app_sid: xous::SID) {
let sid = app_sid.to_u32(); let sid = app_sid.to_u32();
send_message(self.conn, send_message(
self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(
Opcode::SetBlockDeviceSID.to_usize().unwrap(), Opcode::SetBlockDeviceSID.to_usize().unwrap(),
sid.0 as usize, sid.0 as usize,
sid.1 as usize, sid.1 as usize,
sid.2 as usize, sid.2 as usize,
sid.3 as usize, sid.3 as usize,
) ),
).unwrap(); )
.unwrap();
} }
#[cfg(feature="mass-storage")]
#[cfg(feature = "mass-storage")]
pub fn reset_block_device(&self) { pub fn reset_block_device(&self) {
send_message(self.conn, send_message(
Message::new_blocking_scalar( self.conn,
Opcode::ResetBlockDevice.to_usize().unwrap(), Message::new_blocking_scalar(Opcode::ResetBlockDevice.to_usize().unwrap(), 0, 0, 0, 0),
0, )
0, .unwrap();
0,
0,
)
).unwrap();
} }
/// used to query if the HID core was able to start. Mainly to handle edge cases between updates. /// 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 { pub fn is_soc_compatible(&self) -> bool {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::IsSocCompatible.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::IsSocCompatible.to_usize().unwrap(),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match code {
match code { 0 => false,
0 => false, _ => true,
_ => true },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
/// this will always trigger a reset, even if it's the same core we're switching to /// 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> { pub fn switch_to_core(&self, core: UsbDeviceType) -> Result<(), xous::Error> {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::SwitchCores.to_usize().unwrap(), core as usize, 0, 0, 0),
Opcode::SwitchCores.to_usize().unwrap(),
core as usize,
0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match code {
match code { 0 => Ok(()),
0 => Ok(()), _ => Err(xous::Error::InternalError),
_ => Err(xous::Error::InternalError) },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
/// this will not trigger a reset if we're already on the requested core /// this will not trigger a reset if we're already on the requested core
pub fn ensure_core(&self, core: UsbDeviceType) -> Result<(), xous::Error> { pub fn ensure_core(&self, core: UsbDeviceType) -> Result<(), xous::Error> {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::EnsureCore.to_usize().unwrap(), core as usize, 0, 0, 0),
Opcode::EnsureCore.to_usize().unwrap(),
core as usize,
0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match code {
match code { 0 => Ok(()),
0 => Ok(()), _ => Err(xous::Error::InternalError),
_ => Err(xous::Error::InternalError) },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
pub fn get_current_core(&self) -> Result<UsbDeviceType, xous::Error> { pub fn get_current_core(&self) -> Result<UsbDeviceType, xous::Error> {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::WhichCore.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::WhichCore.to_usize().unwrap(),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match code {
match code { 0 => Ok(UsbDeviceType::Debug),
0 => Ok(UsbDeviceType::Debug), 1 => Ok(UsbDeviceType::FidoKbd),
1 => Ok(UsbDeviceType::FidoKbd), 2 => Ok(UsbDeviceType::Fido),
2 => Ok(UsbDeviceType::Fido), #[cfg(feature = "mass-storage")]
#[cfg(feature="mass-storage")] 3 => Ok(UsbDeviceType::MassStorage),
3 => Ok(UsbDeviceType::MassStorage), 4 => Ok(UsbDeviceType::Serial),
4 => Ok(UsbDeviceType::Serial), _ => Err(xous::Error::InternalError),
_ => Err(xous::Error::InternalError) },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
pub fn restrict_debug_access(&self, restrict: bool) -> Result<(), xous::Error> { pub fn restrict_debug_access(&self, restrict: bool) -> Result<(), xous::Error> {
send_message( send_message(
self.conn, self.conn,
Message::new_scalar( Message::new_scalar(
Opcode::RestrictDebugAccess.to_usize().unwrap(), Opcode::RestrictDebugAccess.to_usize().unwrap(),
if restrict {1} else {0}, if restrict { 1 } else { 0 },
0, 0, 0 0,
) 0,
).map(|_| ()) 0,
),
)
.map(|_| ())
} }
pub fn is_debug_restricted(&self) -> Result<bool, xous::Error> { pub fn is_debug_restricted(&self) -> Result<bool, xous::Error> {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::IsRestricted.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::IsRestricted.to_usize().unwrap(),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => {
if code == 1 { if code == 1 {
@ -169,53 +155,43 @@ impl UsbHid {
_ => Err(xous::Error::InternalError), _ => Err(xous::Error::InternalError),
} }
} }
// if do_lock is Some(), set the debug USB lock status to locked if true, unlocked if false // 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) // 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 // 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<bool>) -> Result<(bool, bool), xous::Error> { pub fn debug_usb(&self, do_lock: Option<bool>) -> Result<(bool, bool), xous::Error> {
// arg1 indicates if an update to the state is requested // arg1 indicates if an update to the state is requested
// arg2 is the new state update // arg2 is the new state update
let (arg1, arg2) = if let Some(lock) = do_lock { let (arg1, arg2) = if let Some(lock) = do_lock { if lock { (1, 1) } else { (1, 0) } } else { (0, 0) };
if lock { let response = send_message(
(1, 1) self.conn,
} else { Message::new_blocking_scalar(Opcode::DebugUsbOp.to_usize().unwrap(), arg1, arg2, 0, 0),
(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 { if let xous::Result::Scalar2(is_locked, force_update) = response {
let il = if is_locked != 0 {true} else {false}; let il = if is_locked != 0 { true } else { false };
let fu = if force_update != 0 {true} else {false}; let fu = if force_update != 0 { true } else { false };
Ok( Ok((il, fu))
(il, fu)
)
} else { } else {
Err(xous::Error::InternalError) Err(xous::Error::InternalError)
} }
} }
pub fn status(&self) -> UsbDeviceState { pub fn status(&self) -> UsbDeviceState {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::LinkStatus.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::LinkStatus.to_usize().unwrap(),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match code {
match code { 0 => UsbDeviceState::Default,
0 => UsbDeviceState::Default, 1 => UsbDeviceState::Addressed,
1 => UsbDeviceState::Addressed, 2 => UsbDeviceState::Configured,
2 => UsbDeviceState::Configured, 3 => UsbDeviceState::Suspend,
3 => UsbDeviceState::Suspend, _ => panic!("Internal error: illegal status code"),
_ => panic!("Internal error: illegal status code") },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
/// Sends up to three keyboard codes at once as defined by USB HID usage tables; /// 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](<https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf>): /// see See [Universal Serial Bus (USB) HID Usage Tables Version 1.12](<https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf>):
/// If the vector is empty, you get an all-key-up situation /// If the vector is empty, you get an all-key-up situation
@ -227,11 +203,11 @@ impl UsbHid {
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(
Opcode::SendKeyCode.to_usize().unwrap(), Opcode::SendKeyCode.to_usize().unwrap(),
if code.len() >= 1 {code[0] as usize} 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() >= 2 { code[1] as usize } else { 0 },
if code.len() >= 3 {code[2] as usize} else {0}, if code.len() >= 3 { code[2] as usize } else { 0 },
if auto_keyup { 1 } else { 0 } if auto_keyup { 1 } else { 0 },
) ),
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => {
match code { match code {
@ -243,13 +219,11 @@ impl UsbHid {
_ => Err(xous::Error::UseBeforeInit), _ => Err(xous::Error::UseBeforeInit),
} }
} }
/// This will attempt to send a string using an API based on the currently connected device /// 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. /// 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<usize, xous::Error> { pub fn send_str(&self, s: &str) -> Result<usize, xous::Error> {
let serializer = UsbString { let serializer = UsbString { s: xous_ipc::String::<4000>::from_str(s), sent: None };
s: xous_ipc::String::<4000>::from_str(s),
sent: None
};
let mut buf = Buffer::into_buf(serializer).or(Err(xous::Error::InternalError))?; 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))?; buf.lend_mut(self.conn, Opcode::SendString.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let returned = buf.to_original::<UsbString, _>().or(Err(xous::Error::InternalError))?; let returned = buf.to_original::<UsbString, _>().or(Err(xous::Error::InternalError))?;
@ -259,85 +233,68 @@ impl UsbHid {
None => Err(xous::Error::UseBeforeInit), None => Err(xous::Error::UseBeforeInit),
} }
} }
/// Sets the autotype delay. Defaults to 30ms on boot, must be reset every time on reboot. /// 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) { pub fn set_autotype_delay_ms(&self, rate: usize) {
send_message( send_message(
self.conn, self.conn,
Message::new_scalar(Opcode::SetAutotypeRate.to_usize().unwrap(), rate, 0, 0, 0) 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! )
.unwrap(); // just unwrap it. If the send fails, we want to see the panic at this spot!
} }
pub fn get_led_state(&self) -> Result<KeyboardLedsReport, xous::Error> { pub fn get_led_state(&self) -> Result<KeyboardLedsReport, xous::Error> {
match send_message( match send_message(
self.conn, self.conn,
Message::new_blocking_scalar( Message::new_blocking_scalar(Opcode::GetLedState.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::GetLedState.to_usize().unwrap(),
0, 0, 0, 0
)
) { ) {
Ok(xous::Result::Scalar1(code)) => { Ok(xous::Result::Scalar1(code)) => match KeyboardLedsReport::unpack(&[code as u8]) {
match KeyboardLedsReport::unpack(&[code as u8]) { Ok(r) => Ok(r),
Ok(r) => Ok(r), Err(_) => Err(xous::Error::InternalError),
Err(_) => Err(xous::Error::InternalError), },
}
}
_ => panic!("Internal error: illegal return type"), _ => panic!("Internal error: illegal return type"),
} }
} }
pub fn u2f_wait_incoming(&self) -> Result<RawFidoReport, xous::Error> { pub fn u2f_wait_incoming(&self) -> Result<RawFidoReport, xous::Error> {
let req = U2fMsgIpc { let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: None };
data: [0; 64],
code: U2fCode::RxWait,
timeout_ms: None,
};
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; 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::<U2fMsgIpc, _>().unwrap(); let ack = buf.to_original::<U2fMsgIpc, _>().unwrap();
match ack.code { match ack.code {
U2fCode::RxAck => { U2fCode::RxAck => {
let mut u2fmsg = RawFidoReport::default(); let mut u2fmsg = RawFidoReport::default();
u2fmsg.packet.copy_from_slice(&ack.data); u2fmsg.packet.copy_from_slice(&ack.data);
Ok(u2fmsg) Ok(u2fmsg)
}, }
U2fCode::Hangup => { U2fCode::Hangup => Err(xous::Error::ProcessTerminated),
Err(xous::Error::ProcessTerminated) U2fCode::RxTimeout => Err(xous::Error::Timeout),
}, _ => Err(xous::Error::InternalError),
U2fCode::RxTimeout => {
Err(xous::Error::Timeout)
},
_ => Err(xous::Error::InternalError)
} }
} }
/// Note: this variant is not tested. /// Note: this variant is not tested.
pub fn u2f_wait_incoming_timeout(&self, timeout_ms: u64) -> Result<RawFidoReport, xous::Error> { pub fn u2f_wait_incoming_timeout(&self, timeout_ms: u64) -> Result<RawFidoReport, xous::Error> {
let req = U2fMsgIpc { let req = U2fMsgIpc { data: [0; 64], code: U2fCode::RxWait, timeout_ms: Some(timeout_ms) };
data: [0; 64],
code: U2fCode::RxWait,
timeout_ms: Some(timeout_ms),
};
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; 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::<U2fMsgIpc, _>().unwrap(); let ack = buf.to_original::<U2fMsgIpc, _>().unwrap();
match ack.code { match ack.code {
U2fCode::RxAck => { U2fCode::RxAck => {
let mut u2fmsg = RawFidoReport::default(); let mut u2fmsg = RawFidoReport::default();
u2fmsg.packet.copy_from_slice(&ack.data); u2fmsg.packet.copy_from_slice(&ack.data);
Ok(u2fmsg) Ok(u2fmsg)
}, }
U2fCode::Hangup => { U2fCode::Hangup => Err(xous::Error::ProcessTerminated),
Err(xous::Error::ProcessTerminated) U2fCode::RxTimeout => Err(xous::Error::Timeout),
}, _ => Err(xous::Error::InternalError),
U2fCode::RxTimeout => {
Err(xous::Error::Timeout)
},
_ => Err(xous::Error::InternalError)
} }
} }
pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> { pub fn u2f_send(&self, msg: RawFidoReport) -> Result<(), xous::Error> {
let mut req = U2fMsgIpc { let mut req = U2fMsgIpc { data: [0; 64], code: U2fCode::Tx, timeout_ms: None };
data: [0; 64],
code: U2fCode::Tx,
timeout_ms: None,
};
req.data.copy_from_slice(&msg.packet); req.data.copy_from_slice(&msg.packet);
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError))?; 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))?; 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), _ => Err(xous::Error::InternalError),
} }
} }
/// Blocks until an ASCII string terminated by `delimiter` is received on serial; if `None`, it /// 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 /// will return as soon as a character (or series of characters) have been received (thus the return
/// `String` will be piecemeal) /// `String` will be piecemeal)
pub fn serial_wait_ascii(&self, delimiter: Option<char>) -> String { pub fn serial_wait_ascii(&self, delimiter: Option<char>) -> String {
let req = UsbSerialAscii { let req = UsbSerialAscii { s: xous_ipc::String::new(), delimiter };
s: xous_ipc::String::new(),
delimiter
};
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); 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::<UsbSerialAscii, _>().unwrap(); let resp = buf.to_original::<UsbSerialAscii, _>().unwrap();
resp.s.to_str().to_string() resp.s.to_str().to_string()
} }
/// Blocks until enough binary data has been received to fill the buffer /// 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 /// 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. /// block forever and we're receiving small amounts of binary data.
pub fn serial_wait_binary(&self) -> Vec::<u8> { pub fn serial_wait_binary(&self) -> Vec<u8> {
let req = UsbSerialBinary { let req = UsbSerialBinary { d: [0u8; SERIAL_BINARY_BUFLEN], len: 0 };
d: [0u8; SERIAL_BINARY_BUFLEN],
len: 0,
};
let mut buf = Buffer::into_buf(req).or(Err(xous::Error::InternalError)).expect("Internal error"); 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::<UsbSerialBinary, _>().unwrap(); let resp = buf.to_original::<UsbSerialBinary, _>().unwrap();
resp.d[..resp.len].to_vec() resp.d[..resp.len].to_vec()
} }
/// Non-blocking call that issues a serial flush command to the USB stack /// Non-blocking call that issues a serial flush command to the USB stack
pub fn serial_flush(&self) -> Result<(), xous::Error> { pub fn serial_flush(&self) -> Result<(), xous::Error> {
send_message( send_message(self.conn, Message::new_scalar(Opcode::SerialFlush.to_usize().unwrap(), 0, 0, 0, 0))
self.conn, .map(|_| ())
Message::new_scalar(
Opcode::SerialFlush.to_usize().unwrap(),
0, 0, 0, 0
)
).map(|_| ())
} }
/// Inject serial input over USB to the debug console. Dangerous! /// Inject serial input over USB to the debug console. Dangerous!
/// This will also override/discard any existing hooked listeners. /// This will also override/discard any existing hooked listeners.
pub fn serial_console_input_injection(&self) { pub fn serial_console_input_injection(&self) {
send_message( send_message(
self.conn, self.conn,
Message::new_scalar( Message::new_scalar(Opcode::SerialHookConsole.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::SerialHookConsole.to_usize().unwrap(), 0, 0, 0, 0 )
) .unwrap();
).unwrap();
} }
pub fn serial_clear_input_hooks(&self) { pub fn serial_clear_input_hooks(&self) {
send_message( send_message(
self.conn, self.conn,
Message::new_scalar( Message::new_scalar(Opcode::SerialClearHooks.to_usize().unwrap(), 0, 0, 0, 0),
Opcode::SerialClearHooks.to_usize().unwrap(), 0, 0, 0, 0 )
) .unwrap();
).unwrap();
} }
/// Tries to set the serial port in TRNG mode. Will silently fail if already in console mode. /// 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) { pub fn serial_set_trng_mode(&self, mode: TrngTestMode) {
send_message( send_message(
self.conn, self.conn,
Message::new_scalar( Message::new_scalar(
Opcode::SerialHookTrngSender.to_usize().unwrap(), mode.to_usize().unwrap(), 0, 0, 0 Opcode::SerialHookTrngSender.to_usize().unwrap(),
) mode.to_usize().unwrap(),
).unwrap(); 0,
0,
0,
),
)
.unwrap();
} }
} }
@ -418,7 +377,9 @@ static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for UsbHid { impl Drop for UsbHid {
fn drop(&mut self) { fn drop(&mut self) {
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();} unsafe {
xous::disconnect(self.conn).unwrap();
}
} }
} }
} }

View file

@ -1,47 +1,48 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)] #![cfg_attr(target_os = "none", no_main)]
#[cfg(any(feature="precursor", feature="renode"))]
mod main_hw;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
mod main_hosted; mod main_hosted;
#[cfg(any(feature = "precursor", feature = "renode"))]
mod main_hw;
mod api; mod api;
#[rustfmt::skip] // don't format lookup tables
mod mappings; mod mappings;
use api::*; use api::*;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
mod hw; mod hw;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
use hw::*; use hw::*;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
mod spinal_udc; mod spinal_udc;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
use packed_struct::PackedStructSlice; use packed_struct::PackedStructSlice;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
use spinal_udc::*; 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; mod apps_block_device;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
mod hosted; mod hosted;
use std::collections::BTreeMap;
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
use hosted::*; use hosted::*;
#[cfg(any(feature = "precursor", feature = "renode"))]
use std::collections::BTreeMap;
#[cfg(any(feature="precursor", feature="renode"))]
use num_traits::*; use num_traits::*;
fn main() -> ! { fn main() -> ! {
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
main_hw::main_hw(); main_hw::main_hw();
#[cfg(not(target_os = "xous"))] #[cfg(not(target_os = "xous"))]
main_hosted::main_hosted(); 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 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 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 /// 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 /// 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 /// Returns a full memory address as the pointer. Must be shifted left by 4 to get the
/// aligned representation used by the SpinalHDL block. /// 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<u32, u32>, requested: u32) -> Option<u32> { pub(crate) fn alloc_inner(allocs: &mut BTreeMap<u32, u32>, requested: u32) -> Option<u32> {
if requested == 0 { if requested == 0 {
return None; return None;
@ -91,9 +92,9 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn test_alloc() { fn test_alloc() {
use rand_chacha::ChaCha8Rng;
use rand_chacha::rand_core::SeedableRng;
use rand_chacha::rand_core::RngCore; 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 rng = ChaCha8Rng::seed_from_u64(0);
let mut allocs = BTreeMap::<u32, u32>::new(); let mut allocs = BTreeMap::<u32, u32>::new();
@ -111,7 +112,7 @@ mod tests {
// consistency check and print out // consistency check and print out
for (&offset, &len) in allocs.iter() { for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!"); assert!(offset >= last_alloc, "new offset is inside last allocation!");
println!("{}-{}", offset, offset+len); println!("{}-{}", offset, offset + len);
last_alloc = offset + len; last_alloc = offset + len;
} }
@ -133,7 +134,7 @@ mod tests {
// consistency check and print out // consistency check and print out
for (&offset, &len) in allocs.iter() { for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!"); assert!(offset >= last_alloc, "new offset is inside last allocation!");
println!("{}-{}({})", offset, offset+len, len); println!("{}-{}({})", offset, offset + len, len);
last_alloc = offset + len; last_alloc = offset + len;
} }
@ -163,7 +164,7 @@ mod tests {
for (&offset, &len) in allocs.iter() { for (&offset, &len) in allocs.iter() {
assert!(offset >= last_alloc, "new offset is inside last allocation!"); assert!(offset >= last_alloc, "new offset is inside last allocation!");
assert!(offset & 0xF == 0, "misaligned allocation detected"); assert!(offset & 0xF == 0, "misaligned allocation detected");
println!("{}-{}({})", offset, offset+len, len); println!("{}-{}({})", offset, offset + len, len);
last_alloc = offset + len; last_alloc = offset + len;
} }
} }

View file

@ -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::num::NonZeroU8;
use core::sync::atomic::AtomicUsize; use core::sync::atomic::AtomicUsize;
use std::collections::VecDeque;
use std::sync::Arc; use std::sync::Arc;
use num_traits::*;
use xous::{msg_blocking_scalar_unpack, msg_scalar_unpack};
use xous_ipc::Buffer; 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() -> ! { pub(crate) fn main_hosted() -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
@ -22,10 +22,11 @@ pub(crate) fn main_hosted() -> ! {
let llio = llio::Llio::new(&xns); let llio = llio::Llio::new(&xns);
let tt = ticktimer_server::Ticktimer::new().unwrap(); 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(); let soc_ver = llio.soc_gitrev().unwrap();
if soc_ver < minimum_ver { 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 tt.sleep_ms(1500).ok(); // wait for some system boot to happen before popping up the modal
let modals = modals::Modals::new(&xns).unwrap(); let modals = modals::Modals::new(&xns).unwrap();
modals.show_notification( modals.show_notification(
@ -39,9 +40,11 @@ pub(crate) fn main_hosted() -> ! {
loop { loop {
let msg = xous::receive_message(usbdev_sid).unwrap(); let msg = xous::receive_message(usbdev_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::DebugUsbOp) => msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, { Some(Opcode::DebugUsbOp) => {
xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status"); msg_blocking_scalar_unpack!(msg, _update_req, _new_state, _, _, {
}), xous::return_scalar2(msg.sender, 0, 1).expect("couldn't return status");
})
}
Some(Opcode::U2fRxDeferred) => { Some(Opcode::U2fRxDeferred) => {
// block any rx requests forever // block any rx requests forever
fido_listener = Some(msg); fido_listener = Some(msg);
@ -61,7 +64,8 @@ pub(crate) fn main_hosted() -> ! {
arg2: _, arg2: _,
arg3: _, arg3: _,
arg4: _, arg4: _,
}) = msg.body { }) = msg.body
{
log::warn!("Returning bogus result"); log::warn!("Returning bogus result");
xous::return_scalar(msg.sender, 0).unwrap(); xous::return_scalar(msg.sender, 0).unwrap();
} }
@ -77,16 +81,13 @@ pub(crate) fn main_hosted() -> ! {
// register a suspend/resume listener // register a suspend/resume listener
let cid = xous::connect(usbdev_sid).expect("couldn't create suspend callback connection"); let cid = xous::connect(usbdev_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new( let mut susres = susres::Susres::new(None, &xns, api::Opcode::SuspendResume as u32, cid)
None, .expect("couldn't create suspend/resume object");
&xns,
api::Opcode::SuspendResume as u32,
cid
).expect("couldn't create suspend/resume object");
let mut fido_listener: Option<xous::MessageEnvelope> = None; let mut fido_listener: Option<xous::MessageEnvelope> = None;
// under the theory that PIDs are unforgeable. TODO: check that PIDs are unforgeable. // 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<NonZeroU8> = None; let mut fido_listener_pid: Option<NonZeroU8> = None;
let mut fido_rx_queue = VecDeque::<[u8; 64]>::new(); let mut fido_rx_queue = VecDeque::<[u8; 64]>::new();
@ -97,18 +98,18 @@ pub(crate) fn main_hosted() -> ! {
let opcode: Option<Opcode> = FromPrimitive::from_usize(msg.body.id()); let opcode: Option<Opcode> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode); log::debug!("{:?}", opcode);
match opcode { match opcode {
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
Some(Opcode::SetBlockDevice) => { Some(Opcode::SetBlockDevice) => {
log::info!("ignoring SetBlockDevice in hosted mode"); log::info!("ignoring SetBlockDevice in hosted mode");
}, }
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
Some(Opcode::SetBlockDeviceSID) => { Some(Opcode::SetBlockDeviceSID) => {
log::info!("ignoring SetBlockDeviceSID in hosted mode"); log::info!("ignoring SetBlockDeviceSID in hosted mode");
}, }
#[cfg(feature="mass-storage")] #[cfg(feature = "mass-storage")]
Some(Opcode::ResetBlockDevice) => { Some(Opcode::ResetBlockDevice) => {
log::info!("ignoring ResetBlockDevice in hosted mode"); log::info!("ignoring ResetBlockDevice in hosted mode");
}, }
Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, {
usbmgmt.xous_suspend(); usbmgmt.xous_suspend();
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); 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(); fido_listener_pid = msg.sender.pid();
} }
if fido_listener.is_some() { if fido_listener.is_some() {
log::error!("Double-listener request detected. There should only ever by one registered listener at a time."); log::error!(
log::error!("This will cause an upstream server to misbehave, but not panicing so the problem can be debugged."); "Double-listener request detected. There should only ever by one registered listener at a time."
// the receiver will get a response with the `code` field still in the `RxWait` state to indicate the problem );
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() { if fido_listener_pid == msg.sender.pid() {
// preferentially pull from the rx queue if it has elements // preferentially pull from the rx queue if it has elements
if let Some(data) = fido_rx_queue.pop_front() { 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 { let mut response = unsafe {
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap())
}; };
@ -147,8 +157,12 @@ pub(crate) fn main_hosted() -> ! {
fido_listener = Some(msg); fido_listener = Some(msg);
} }
} else { } else {
log::warn!("U2F interface capability is locked on first use; additional servers are ignored: {:?}", msg.sender); log::warn!(
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; "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::<U2fMsgIpc, _>().unwrap(); let mut u2f_ipc = buffer.to_original::<U2fMsgIpc, _>().unwrap();
u2f_ipc.code = U2fCode::Denied; u2f_ipc.code = U2fCode::Denied;
buffer.replace(u2f_ipc).unwrap(); buffer.replace(u2f_ipc).unwrap();
@ -169,7 +183,8 @@ pub(crate) fn main_hosted() -> ! {
if fido_listener_pid.is_none() { if fido_listener_pid.is_none() {
fido_listener_pid = msg.sender.pid(); 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::<U2fMsgIpc, _>().unwrap(); let mut u2f_ipc = buffer.to_original::<U2fMsgIpc, _>().unwrap();
if fido_listener_pid == msg.sender.pid() { if fido_listener_pid == msg.sender.pid() {
let mut u2f_msg = RawFidoReport::default(); let mut u2f_msg = RawFidoReport::default();
@ -182,9 +197,7 @@ pub(crate) fn main_hosted() -> ! {
} }
buffer.replace(u2f_ipc).unwrap(); buffer.replace(u2f_ipc).unwrap();
} }
Some(Opcode::UsbIrqHandler) => { Some(Opcode::UsbIrqHandler) => {}
},
Some(Opcode::SwitchCores) => msg_blocking_scalar_unpack!(msg, core, _, _, _, { Some(Opcode::SwitchCores) => msg_blocking_scalar_unpack!(msg, core, _, _, _, {
if core == 1 { if core == 1 {
log::info!("Connecting USB device core; disconnecting debug USB core"); log::info!("Connecting USB device core; disconnecting debug USB core");
@ -240,23 +253,17 @@ pub(crate) fn main_hosted() -> ! {
usbmgmt.disable_debug(false); usbmgmt.disable_debug(false);
} }
} }
// at this point, *read back* the new state -- don't assume it "took". The readback is always based on // at this point, *read back* the new state -- don't assume it "took". The readback is always
// a real hardware value and not the requested value. for now, always false. // based on a real hardware value and not the requested value. for now, always
let is_locked = if usbmgmt.get_disable_debug() { // false.
1 let is_locked = if usbmgmt.get_disable_debug() { 1 } else { 0 };
} else {
0
};
// this is a performance optimization. we could always redraw the status, but, instead we only redraw when // this is a performance optimization. we could always redraw the status, but, instead we only
// the status has changed. However, there is an edge case: on a resume from suspend, the status needs a redraw, // redraw when the status has changed. However, there is an edge case: on a
// even if nothing has changed. Thus, we have this separate boolean we send back to force an update in the // 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. // case that we have just come out of a suspend.
let force_update = if lockstatus_force_update { let force_update = if lockstatus_force_update { 1 } else { 0 };
1
} else {
0
};
xous::return_scalar2(msg.sender, is_locked, force_update).expect("couldn't return status"); xous::return_scalar2(msg.sender, is_locked, force_update).expect("couldn't return status");
lockstatus_force_update = false; lockstatus_force_update = false;
}), }),
@ -267,7 +274,8 @@ pub(crate) fn main_hosted() -> ! {
xous::return_scalar(msg.sender, 1).unwrap(); xous::return_scalar(msg.sender, 1).unwrap();
} }
Some(Opcode::SendString) => { 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::<api::UsbString, _>().unwrap(); // suppress mut warning on hosted mode let usb_send = buffer.to_original::<api::UsbString, _>().unwrap(); // suppress mut warning on hosted mode
buffer.replace(usb_send).unwrap(); buffer.replace(usb_send).unwrap();
} }
@ -277,8 +285,8 @@ pub(crate) fn main_hosted() -> ! {
Some(Opcode::Quit) => { Some(Opcode::Quit) => {
log::warn!("Quit received, goodbye world!"); log::warn!("Quit received, goodbye world!");
break; break;
}, }
_ => log::warn!("Opcode not supported: {:?}", msg), _ => log::warn!("Opcode not supported: {:?}", msg),
} }
} }
// clean up our program // clean up our program

File diff suppressed because it is too large Load diff

View file

@ -2,6 +2,7 @@
pub use xous_usb_hid::page::Keyboard as UsbKeyCode; pub use xous_usb_hid::page::Keyboard as UsbKeyCode;
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature="precursor", feature="renode"))]
#[rustfmt::skip]
pub fn char_to_hid_code_us101(key: char) -> Vec<UsbKeyCode> { pub fn char_to_hid_code_us101(key: char) -> Vec<UsbKeyCode> {
let mut code = vec![]; let mut code = vec![];
match key { match key {
@ -120,6 +121,7 @@ pub fn char_to_hid_code_us101(key: char) -> Vec<UsbKeyCode> {
/// auto-generated using tools/kbd_layout.py + `usb kbdtest` on device for dvorak layout on US101 /// auto-generated using tools/kbd_layout.py + `usb kbdtest` on device for dvorak layout on US101
#[cfg(any(feature="precursor", feature="renode"))] #[cfg(any(feature="precursor", feature="renode"))]
#[rustfmt::skip]
pub fn char_to_hid_code_dvorak(key: char) -> Vec<UsbKeyCode> { pub fn char_to_hid_code_dvorak(key: char) -> Vec<UsbKeyCode> {
let mut code = vec![]; let mut code = vec![];
match key { match key {

View file

@ -1,12 +1,12 @@
use core::mem::size_of;
use core::sync::atomic::{AtomicPtr, Ordering};
use std::fmt;
/// Abstractions for the Spinal UDC controller. /// Abstractions for the Spinal UDC controller.
/// See https://spinalhdl.github.io/SpinalDoc-RTD/dev/SpinalHDL/Libraries/Com/usb_device.html /// See https://spinalhdl.github.io/SpinalDoc-RTD/dev/SpinalHDL/Libraries/Com/usb_device.html
/// for documentation. /// for documentation.
use bitfield::bitfield; use bitfield::bitfield;
use usb_device::UsbDirection; 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; pub(crate) const NUM_ENDPOINTS: usize = 16;
@ -44,11 +44,7 @@ impl fmt::Debug for UdcInterrupts {
if self.resume() { if self.resume() {
f.write_str("resume ")?; f.write_str("resume ")?;
} }
if self.disconnect() { if self.disconnect() { f.write_str("disconnect ") } else { Ok(()) }
f.write_str("disconnect ")
} else {
Ok(())
}
} }
} }
} }
@ -87,73 +83,74 @@ const CONFIG_OFFSET: usize = 0x10;
const RAMSIZE_OFFSET: usize = 0x20; const RAMSIZE_OFFSET: usize = 0x20;
#[allow(dead_code)] #[allow(dead_code)]
impl SpinalUdcRegs { impl SpinalUdcRegs {
pub fn new(ptr: *mut u32) -> SpinalUdcRegs { pub fn new(ptr: *mut u32) -> SpinalUdcRegs { SpinalUdcRegs { regs: AtomicPtr::new(ptr) } }
SpinalUdcRegs {
regs: AtomicPtr::new(ptr)
}
}
pub fn clone(&self) -> SpinalUdcRegs { pub fn clone(&self) -> SpinalUdcRegs {
SpinalUdcRegs { SpinalUdcRegs { regs: AtomicPtr::new(self.regs.load(Ordering::SeqCst)) }
regs: AtomicPtr::new(self.regs.load(Ordering::SeqCst))
}
} }
/// current USB frame ID /// current USB frame ID
pub fn frame_id(&self) -> u32 { pub fn frame_id(&self) -> u32 {
unsafe { unsafe { self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::<u32>()).read_volatile() }
self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::<u32>()).read_volatile()
}
} }
/// currently active address for tokens. cleared by USB reset /// currently active address for tokens. cleared by USB reset
pub fn address(&self) -> u32 { pub fn address(&self) -> u32 {
unsafe { unsafe { self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).read_volatile() }
self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).read_volatile()
}
} }
pub fn set_address(&self, addr: u32) { pub fn set_address(&self, addr: u32) {
unsafe { unsafe {
self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).write_volatile(addr); self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).write_volatile(addr);
} }
} }
/// interrupt flags /// interrupt flags
pub fn interrupts(&self) -> UdcInterrupts { pub fn interrupts(&self) -> UdcInterrupts {
unsafe { unsafe {
UdcInterrupts(self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).read_volatile()) UdcInterrupts(self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).read_volatile())
} }
} }
pub fn clear_some_interrupts(&self, ints: UdcInterrupts) { pub fn clear_some_interrupts(&self, ints: UdcInterrupts) {
unsafe { unsafe {
self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(ints.0); self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(ints.0);
} }
} }
pub fn clear_all_interrupts(&self) { pub fn clear_all_interrupts(&self) {
unsafe { unsafe {
self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(0xffff_ffff); self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(0xffff_ffff);
} }
} }
/// halt - use this to pause an endpoint to give the CPU a mutex on r/w access to its registers /// 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 { pub fn halt(&self) -> UdcHalt {
unsafe { unsafe {
UdcHalt(self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).read_volatile()) UdcHalt(self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).read_volatile())
} }
} }
pub fn set_halt(&self, halt: UdcHalt) { pub fn set_halt(&self, halt: UdcHalt) {
unsafe { unsafe { self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).write_volatile(halt.0) }
self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).write_volatile(halt.0)
}
} }
/// config /// config
pub fn config(&self) -> UdcConfig { pub fn config(&self) -> UdcConfig {
unsafe { unsafe {
UdcConfig(self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).read_volatile()) UdcConfig(self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).read_volatile())
} }
} }
pub fn set_config(&self, cfg: UdcConfig) { pub fn set_config(&self, cfg: UdcConfig) {
unsafe { unsafe {
self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).write_volatile(cfg.0) self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).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 { pub fn ramsize(&self) -> u32 {
1 << (unsafe { 1 << (unsafe {
self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).read_volatile() self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).read_volatile()
@ -162,11 +159,7 @@ impl SpinalUdcRegs {
} }
impl fmt::Debug for SpinalUdcRegs { impl fmt::Debug for SpinalUdcRegs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "UDC: frame{}, adr{}, ints: {:?}", write!(f, "UDC: frame{}, adr{}, ints: {:?}", self.frame_id(), self.address(), self.interrupts(),)
self.frame_id(),
self.address(),
self.interrupts(),
)
} }
} }
@ -184,14 +177,16 @@ bitfield! {
} }
impl fmt::Debug for UdcEpStatus { impl fmt::Debug for UdcEpStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ep{}@0x{:x}^{}: {}{}{}{}", write!(
if self.enable() {"ENA"} else {"DIS"}, f,
"Ep{}@0x{:x}^{}: {}{}{}{}",
if self.enable() { "ENA" } else { "DIS" },
self.head_offset() * 16, self.head_offset() * 16,
self.max_packet_size(), self.max_packet_size(),
if self.force_stall() {"STALL "} else {""}, if self.force_stall() { "STALL " } else { "" },
if self.force_nack() {"NACK "} else {""}, if self.force_nack() { "NACK " } else { "" },
if self.data_phase() {"DATA1 "} else {"DATA0 "}, if self.data_phase() { "DATA1 " } else { "DATA0 " },
if self.isochronous() {"ISO "} else {""}, if self.isochronous() { "ISO " } else { "" },
) )
} }
} }
@ -226,72 +221,82 @@ bitfield! {
// forces dataphase to DATA1 when the descriptor is complete // forces dataphase to DATA1 when the descriptor is complete
pub data1_on_completion, set_data1_on_completion: 19; 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 { pub struct SpinalUdcDescriptor {
base: AtomicPtr::<u32>, base: AtomicPtr<u32>,
} }
#[allow(dead_code)] #[allow(dead_code)]
impl SpinalUdcDescriptor { impl SpinalUdcDescriptor {
pub fn new(base: *mut u32) -> SpinalUdcDescriptor { pub fn new(base: *mut u32) -> SpinalUdcDescriptor { SpinalUdcDescriptor { base: AtomicPtr::new(base) } }
SpinalUdcDescriptor { base: AtomicPtr::new(base) }
}
pub(crate) fn read(&self, offset: usize) -> u32 { 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 // we don't do asserts on reads because for debugging sometimes we reveal invalid descriptors and
unsafe{self.base.load(Ordering::SeqCst).add(offset).read_volatile()} // that's OK
unsafe { self.base.load(Ordering::SeqCst).add(offset).read_volatile() }
} }
fn write(&self, offset: usize, data: u32) { fn write(&self, offset: usize, data: u32) {
// -16 for the dedicated ep0-out space // -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!(
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); (self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16,
unsafe{self.base.load(Ordering::SeqCst).add(offset).write_volatile(data)} "descriptor is illegal (too low)! 0x{:x}",
} self.base.load(Ordering::SeqCst) as u32
pub fn offset(&self) -> usize { );
UdcDesc0(self.read(0)).offset() as usize assert!(
} (self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET,
pub fn in_progress(&self) -> bool { "descriptor is illegal (too high)! 0x{:x}",
UdcDesc0(self.read(0)).code() == 0xF self.base.load(Ordering::SeqCst) as u32
} );
pub fn next_descriptor_addr(&self) -> usize { unsafe { self.base.load(Ordering::SeqCst).add(offset).write_volatile(data) }
UdcDesc1(self.read(1)).next_descriptor_addr() as usize
}
pub fn length(&self) -> usize {
UdcDesc1(self.read(1)).length() as usize
} }
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 { pub fn direction(&self) -> UsbDirection {
if UdcDesc2(self.read(2)).direction() { if UdcDesc2(self.read(2)).direction() { UsbDirection::In } else { UsbDirection::Out }
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 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) { pub fn set_offset(&self, offset: usize) {
let mut d0 = UdcDesc0(0); let mut d0 = UdcDesc0(0);
d0.set_offset(offset as _); d0.set_offset(offset as _);
d0.set_code(0xF); // automatically set in_progress d0.set_code(0xF); // automatically set in_progress
self.write(0, d0.0); self.write(0, d0.0);
} }
pub fn set_offset_only(&self, offset: usize) { pub fn set_offset_only(&self, offset: usize) {
let mut d0 = UdcDesc0(0); let mut d0 = UdcDesc0(0);
d0.set_offset(offset as _); d0.set_offset(offset as _);
d0.set_code(0x0); // clears in_progress d0.set_code(0x0); // clears in_progress
self.write(0, d0.0); self.write(0, d0.0);
} }
pub fn set_next_desc_and_len(&self, next_addr: usize, length: usize) { pub fn set_next_desc_and_len(&self, next_addr: usize, length: usize) {
let mut d1 = UdcDesc1(0); let mut d1 = UdcDesc1(0);
d1.set_length(length as _); d1.set_length(length as _);
d1.set_next_descriptor_addr(next_addr as _); d1.set_next_descriptor_addr(next_addr as _);
self.write(1, d1.0); 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); let mut d2 = UdcDesc2(0);
match direction { match direction {
UsbDirection::In => d2.set_direction(true), UsbDirection::In => d2.set_direction(true),
@ -302,24 +307,30 @@ impl SpinalUdcDescriptor {
d2.set_data1_on_completion(data1_on_completion); d2.set_data1_on_completion(data1_on_completion);
self.write(2, d2.0); self.write(2, d2.0);
} }
pub fn write_data(&self, offset_word: usize, data: u32) { pub fn write_data(&self, offset_word: usize, data: u32) {
// -16 for the dedicated ep0-out space // -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!(
assert!((self.base.load(Ordering::SeqCst) as u32) & 0xFFF < crate::END_OFFSET, "descriptor is illegal (too high)!"); (self.base.load(Ordering::SeqCst) as u32) & 0xFFF >= crate::START_OFFSET - 16,
unsafe { "descriptor is illegal (too low)!"
self.base.load(Ordering::SeqCst).add(3 + offset_word).write_volatile(data) );
} 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 { pub fn read_data(&self, offset_word: usize) -> u32 {
unsafe { unsafe { self.base.load(Ordering::SeqCst).add(3 + offset_word).read_volatile() }
self.base.load(Ordering::SeqCst).add(3 + offset_word).read_volatile()
}
} }
} }
impl fmt::Debug for SpinalUdcDescriptor { impl fmt::Debug for SpinalUdcDescriptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Desc({}){}: {} of {} -> 0x{:x} ({}{}{}) [{:x?},{:x?},..] @ {:x?}", write!(
if self.in_progress() {"<>"} else {"--"}, f,
"Desc({}){}: {} of {} -> 0x{:x} ({}{}{}) [{:x?},{:x?},..] @ {:x?}",
if self.in_progress() { "<>" } else { "--" },
match self.direction() { match self.direction() {
UsbDirection::In => "IN", UsbDirection::In => "IN",
UsbDirection::Out => "OUT", UsbDirection::Out => "OUT",
@ -327,9 +338,9 @@ impl fmt::Debug for SpinalUdcDescriptor {
self.offset(), self.offset(),
self.length(), self.length(),
self.next_descriptor_addr() * 16, self.next_descriptor_addr() * 16,
if self.int_on_done() {"I"} else {"."}, if self.int_on_done() { "I" } else { "." },
if self.completion_on_full() {"C"} else {"."}, if self.completion_on_full() { "C" } else { "." },
if self.data1_on_completion() {"1"} else {"0"}, if self.data1_on_completion() { "1" } else { "0" },
self.read_data(0).to_le_bytes(), self.read_data(0).to_le_bytes(),
self.read_data(1).to_le_bytes(), self.read_data(1).to_le_bytes(),
self.base, self.base,