usb-device-xous: implement primitive for apps-based block devices

This commit is contained in:
Gianguido Sorà 2023-01-24 17:30:35 +01:00
parent 70d5490bbb
commit 7eef972065
10 changed files with 341 additions and 10 deletions

View file

@ -5,7 +5,7 @@
"rust-analyzer.server.extraEnv": {
"XOUS_SVD_FILE": "../precursors/soc.svd"
},
"rust-analyzer.cargo.features": ["precursor"],
"rust-analyzer.cargo.features": ["precursor", "mass-storage"],
"rust-analyzer.files.excludeDirs": ["./loader/**"],
"files.exclude": {
"**/.git": true,

1
Cargo.lock generated
View file

@ -1695,6 +1695,7 @@ dependencies = [
"num-derive",
"num-traits",
"tts-frontend",
"usb-device-xous",
"xous 0.9.31 (registry+https://github.com/rust-lang/crates.io-index)",
"xous-api-log",
"xous-api-names",

View file

@ -15,6 +15,8 @@ gam = {path = "../../services/gam" }
graphics-server = {path = "../../services/graphics-server" }
locales = {path = "../../locales"}
tts-frontend = {path="../../services/tts"}
usb-device-xous = {path="../../services/usb-device-xous"}
[features]
tts = []

View file

@ -20,6 +20,12 @@ pub(crate) enum HelloOp {
/// Redraw the screen
Redraw = 0,
FocusChange,
Read,
Write,
MaxLba,
/// Quit the application
Quit,
}
@ -46,7 +52,7 @@ impl Hello {
gotinput_id: None,
audioframe_id: None,
rawkeys_id: None,
focuschange_id: None,
focuschange_id: Some(HelloOp::FocusChange.to_u32().unwrap()),
})
.expect("Could not register GAM UX")
.unwrap();
@ -130,19 +136,88 @@ fn main() -> ! {
let mut hello = Hello::new(&xns, sid);
let conn = xous::connect(sid).unwrap();
const CAPACITY: usize = 256 * 1024; // must be a multiple of one page (4096)
let mut backing = xous::syscall::map_memory(
None,
None,
CAPACITY,
xous::MemoryFlags::R | xous::MemoryFlags::W,
).unwrap();
{
let backing_slice: &mut [u32] = backing.as_slice_mut();
for (index, d) in backing_slice.iter_mut().enumerate() {
*d = index as u32;
}
}
let mut usb_setup = false;
loop {
let msg = xous::receive_message(sid).unwrap();
let mut msg = xous::receive_message(sid).unwrap();
log::debug!("Got message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(HelloOp::Redraw) => {
log::debug!("Got redraw");
log::info!("Got redraw");
hello.redraw();
}
Some(HelloOp::Quit) => {
log::info!("Quitting application");
break;
}
Some(HelloOp::FocusChange) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, {
if usb_setup {
continue;
}
let new_state = gam::FocusState::convert_focus_change(new_state_code);
match new_state {
gam::FocusState::Background => {
}
gam::FocusState::Foreground => {
let usb = usb_device_xous::UsbHid::new();
usb.set_block_device(
HelloOp::Read.to_usize().unwrap(),
HelloOp::Write.to_usize().unwrap(),
HelloOp::MaxLba.to_usize().unwrap(),
);
usb.set_block_device_sid(sid.clone());
usb.switch_to_core(usb_device_xous::UsbDeviceType::MassStorage).unwrap();
usb_setup = true;
}
}
}),
Some(HelloOp::Read) => {
let body = msg.body.memory_message_mut().expect("incorrect message type received");
let lba = body.offset.map(|v| v.get()).unwrap_or_default();
let data = body.buf.as_slice_mut::<u8>();
let block_bytes: usize = 512;
let backing_slice: &[u8] = backing.as_slice();
let rawdata = &backing_slice[lba as usize * block_bytes..(lba as usize + 1) * block_bytes];
data[..block_bytes].copy_from_slice(
rawdata
);
},
Some(HelloOp::Write) => {
let body = msg.body.memory_message_mut().expect("incorrect message type received");
let lba = body.offset.map(|v| v.get()).unwrap_or_default();
let data = body.buf.as_slice_mut::<u8>();
let block_bytes: usize = 512;
let backing_slice: &mut [u8] = backing.as_slice_mut();
backing_slice[lba as usize * block_bytes..(lba as usize + 1) * block_bytes].copy_from_slice(&data[..block_bytes]);
},
Some(HelloOp::MaxLba) => {
xous::return_scalar(msg.sender, (CAPACITY / 512) - 1).unwrap();
},
_ => {
log::error!("Got unknown message");
}

View file

@ -31,6 +31,9 @@ pub(crate) enum Opcode {
/// Query if the HID driver was able to start
IsSocCompatible,
SetBlockDevice,
SetBlockDeviceSID,
/// Handle the USB interrupt
UsbIrqHandler,
/// Suspend/resume callback

View file

@ -0,0 +1,201 @@
use core::num::NonZeroUsize;
use core::{cell::RefCell, convert::TryInto};
use num_traits::*;
use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack};
use std::sync::Arc;
use std::sync::Mutex;
use usbd_scsi::BlockDevice;
use xous::MemoryRange;
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum BlockDeviceOp {
// Read signals the application on the other side to read some data into
// the shared MemoryRange and return.
Read,
// Write signals the application on the other side to write some data in to the
// shared MemoryRange and return.
Write,
// MaxLBA signals the application on the other side to return the max amount of
// LBA and return.
MaxLBA,
}
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum BlockDeviceMgmtOp {
SetOps,
SetSID,
}
#[repr(C, align(4096))]
pub struct RawData {
raw: [u8; 4096],
}
#[derive(Debug)]
struct RwOp {
read_id: usize,
write_id: usize,
max_lba_id: usize,
}
pub struct AppsBlockDevice {
app_cid: Arc<Mutex<Option<xous::CID>>>,
rw_ids: Arc<Mutex<RwOp>>,
mgmt_cid: xous::CID,
}
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 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 mut 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();
}),
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
}
}
impl BlockDevice for AppsBlockDevice {
const BLOCK_BYTES: usize = 512;
fn read_block(&self, lba: u32, block: &mut [u8]) -> Result<(), usbd_scsi::BlockDeviceError> {
let cid = match *self.app_cid.lock().unwrap() {
Some(cid) => cid,
None => return Err(usbd_scsi::BlockDeviceError::HardwareError),
};
let rw_ids = self.rw_ids.lock().unwrap();
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::send_message(
cid,
xous::Message::new_lend_mut(
rw_ids.read_id,
buf,
xous::MemoryAddress::new(lba as usize),
None,
),
).unwrap();
block.copy_from_slice(&request.raw[..Self::BLOCK_BYTES as usize]);
Ok(())
}
fn write_block(&mut self, lba: u32, block: &[u8]) -> Result<(), usbd_scsi::BlockDeviceError> {
let cid = match *self.app_cid.lock().unwrap() {
Some(cid) => cid,
None => return Err(usbd_scsi::BlockDeviceError::HardwareError),
};
let rw_ids = self.rw_ids.lock().unwrap();
let mut request = RawData { raw: [0u8; 4096] };
(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::send_message(
cid,
xous::Message::new_lend_mut(
rw_ids.write_id,
buf,
xous::MemoryAddress::new(lba as usize),
None,
),
).unwrap();
Ok(())
}
fn max_lba(&self) -> u32 {
// take refcell contents
let cid = match *self.app_cid.lock().unwrap() {
Some(cid) => cid,
None => panic!("trying to set lba without cid being set!"),
};
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")
{
xous::Result::Scalar1(max_lba) => {
max_lba.try_into().unwrap()
}
_ => panic!("received response to max_lba that isn't a Scalar1!"),
}
}
}

View file

@ -24,16 +24,18 @@ impl usbd_scsi::BlockDevice for BlockDevice {
const BLOCK_BYTES: usize = 512;
fn read_block(&self, lba: u32, block: &mut [u8]) -> Result<(), usbd_scsi::BlockDeviceError> {
let block_bytes = Self::BLOCK_BYTES;
let backing_slice: &[u8] = self.backing.as_slice();
block.copy_from_slice(
&backing_slice[lba as usize * Self::BLOCK_BYTES..(lba as usize + 1) * Self::BLOCK_BYTES]
&backing_slice[lba as usize * block_bytes..(lba as usize + 1) * block_bytes]
);
Ok(())
}
fn write_block(&mut self, lba: u32, block: &[u8]) -> Result<(), usbd_scsi::BlockDeviceError> {
let block_bytes = Self::BLOCK_BYTES;
let backing_slice: &mut [u8] = self.backing.as_slice_mut();
backing_slice[lba as usize * Self::BLOCK_BYTES..(lba as usize + 1) * Self::BLOCK_BYTES].copy_from_slice(block);
backing_slice[lba as usize * block_bytes..(lba as usize + 1) * block_bytes].copy_from_slice(block);
Ok(())
}

View file

@ -24,6 +24,32 @@ impl UsbHid {
conn
}
}
pub fn set_block_device(&self, read_id: usize, write_id: usize, max_lba_id: usize) {
send_message(self.conn,
Message::new_blocking_scalar(
Opcode::SetBlockDevice.to_usize().unwrap(),
read_id,
write_id,
max_lba_id,
0,
)
).unwrap();
}
pub fn set_block_device_sid(&self, app_sid: xous::SID) {
let sid = app_sid.to_u32();
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();
}
/// 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(

View file

@ -22,6 +22,8 @@ use packed_struct::PackedStructSlice;
use spinal_udc::*;
#[cfg(all(any(feature="precursor", feature="renode"),feature="mass-storage"))]
mod block_device;
#[cfg(all(any(feature="precursor", feature="renode"),feature="mass-storage"))]
mod apps_block_device;
#[cfg(not(target_os = "xous"))]
mod hosted;

View file

@ -214,18 +214,20 @@ pub(crate) fn main_hw() -> ! {
// Mass storage
#[cfg(feature="mass-storage")]
let ums_alloc = UsbBusAllocator::new(ums_dev);
#[cfg(feature="mass-storage")]
let bd = block_device::BlockDevice::new();
let mut ums_alloc = UsbBusAllocator::new(ums_dev);
#[cfg(feature="mass-storage")]
let mut abd = apps_block_device::AppsBlockDevice::new();
let abdcid = abd.conn();
let mut ums = usbd_scsi::Scsi::new(
&ums_alloc,
64,
bd,
abd,
"Kosagi".as_bytes(),
"Kosagi Precursor".as_bytes(),
"1".as_bytes()
);
#[cfg(feature="mass-storage")]
let mut ums_device = UsbDeviceBuilder::new(&ums_alloc, UsbVidPid(0x1209, 0x3613))
.manufacturer("Kosagi")
@ -270,6 +272,23 @@ pub(crate) fn main_hw() -> ! {
let opcode: Option<Opcode> = FromPrimitive::from_usize(msg.body.id());
log::debug!("{:?}", opcode);
match opcode {
Some(Opcode::SetBlockDevice) => msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, {
xous::send_message(
abdcid,
xous::Message::new_blocking_scalar(
apps_block_device::BlockDeviceMgmtOp::SetOps.to_usize().unwrap(), read_id, write_id, max_lba_id, 0,
)
).unwrap();
xous::return_scalar(msg.sender, 0).unwrap();
}),
Some(Opcode::SetBlockDeviceSID) => msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, {
xous::send_message(abdcid,
xous::Message::new_blocking_scalar(
apps_block_device::BlockDeviceMgmtOp::SetSID.to_usize().unwrap(), sid1, sid2, sid3, sid4
)
).unwrap();
xous::return_scalar(msg.sender, 0).unwrap();
}),
Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, {
usbmgmt.xous_suspend();
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");