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.
// 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<u32>,
}
@ -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<usize> 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::<SERIAL_ASCII_BUFLEN>,
pub s: xous_ipc::String<SERIAL_ASCII_BUFLEN>,
pub delimiter: Option<char>,
}

View file

@ -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<BlockDeviceMgmtOp> = 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<BlockDeviceMgmtOp> = 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::<RawData>(),
)
.unwrap()
xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::<RawData>())
.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::<RawData>(),
)
.unwrap()
xous::MemoryRange::new(&mut request as *mut RawData as usize, core::mem::size_of::<RawData>())
.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!"),

View file

@ -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::<std::sync::atomic::AtomicUsize>) -> SpinalUsbDevice {
pub fn new(_sid: xous::SID, _view: std::sync::Arc<std::sync::atomic::AtomicUsize>) -> 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<u32> {
None
}
pub fn alloc_region(&mut self, _requested: usize) -> Option<u32> { 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 }
}

File diff suppressed because it is too large Load diff

View file

@ -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<UsbDeviceType, xous::Error> {
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<bool, xous::Error> {
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<bool>) -> 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](<https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf>):
/// 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<usize, xous::Error> {
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::<UsbString, _>().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<KeyboardLedsReport, xous::Error> {
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<RawFidoReport, xous::Error> {
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::<U2fMsgIpc, _>().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<RawFidoReport, xous::Error> {
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::<U2fMsgIpc, _>().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<char>) -> 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::<UsbSerialAscii, _>().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::<u8> {
let req = UsbSerialBinary {
d: [0u8; SERIAL_BINARY_BUFLEN],
len: 0,
};
pub fn serial_wait_binary(&self) -> Vec<u8> {
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::<UsbSerialBinary, _>().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();
}
}
}
}
}

View file

@ -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<u32, u32>, requested: u32) -> Option<u32> {
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::<u32, u32>::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;
}
}

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::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<xous::MessageEnvelope> = 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<NonZeroU8> = None;
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());
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::<U2fMsgIpc, _>().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::<U2fMsgIpc, _>().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::<api::UsbString, _>().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)
}
}

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;
#[cfg(any(feature="precursor", feature="renode"))]
#[rustfmt::skip]
pub fn char_to_hid_code_us101(key: char) -> Vec<UsbKeyCode> {
let mut code = vec![];
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
#[cfg(any(feature="precursor", feature="renode"))]
#[rustfmt::skip]
pub fn char_to_hid_code_dvorak(key: char) -> Vec<UsbKeyCode> {
let mut code = vec![];
match key {
@ -224,4 +226,4 @@ pub fn char_to_hid_code_dvorak(key: char) -> Vec<UsbKeyCode> {
_ => log::warn!("Ignoring unhandled character: {}", key),
};
code
}
}

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.
/// 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::<u32>()).read_volatile()
}
unsafe { self.regs.load(Ordering::SeqCst).add(FRAME_OFFSET / size_of::<u32>()).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::<u32>()).read_volatile()
}
unsafe { self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).read_volatile() }
}
pub fn set_address(&self, addr: u32) {
unsafe {
self.regs.load(Ordering::SeqCst).add(ADDRESS_OFFSET / size_of::<u32>()).write_volatile(addr);
}
}
/// interrupt flags
pub fn interrupts(&self) -> UdcInterrupts {
unsafe {
UdcInterrupts(self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn clear_some_interrupts(&self, ints: UdcInterrupts) {
unsafe {
self.regs.load(Ordering::SeqCst).add(INT_OFFSET / size_of::<u32>()).write_volatile(ints.0);
}
}
pub fn clear_all_interrupts(&self) {
unsafe {
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
pub fn halt(&self) -> UdcHalt {
unsafe {
UdcHalt(self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn set_halt(&self, halt: UdcHalt) {
unsafe {
self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).write_volatile(halt.0)
}
unsafe { self.regs.load(Ordering::SeqCst).add(HALT_OFFSET / size_of::<u32>()).write_volatile(halt.0) }
}
/// config
pub fn config(&self) -> UdcConfig {
unsafe {
UdcConfig(self.regs.load(Ordering::SeqCst).add(CONFIG_OFFSET / size_of::<u32>()).read_volatile())
}
}
pub fn set_config(&self, cfg: UdcConfig) {
unsafe {
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 {
1 << (unsafe {
self.regs.load(Ordering::SeqCst).add(RAMSIZE_OFFSET / size_of::<u32>()).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::<u32>,
base: AtomicPtr<u32>,
}
#[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,
)
}
}
}