diff --git a/.vscode/settings.json b/.vscode/settings.json index fd85d77fb..44c9a5b82 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -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, diff --git a/Cargo.lock b/Cargo.lock index d6528fdca..ee3ef76ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4042,6 +4042,22 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "transientdisk" +version = "0.1.0" +dependencies = [ + "gam", + "graphics-server", + "log", + "num-derive", + "num-traits", + "usb-device-xous", + "xous 0.9.31 (registry+https://github.com/rust-lang/crates.io-index)", + "xous-api-log", + "xous-api-names", + "xous-ipc 0.9.31 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "trng" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a49ff184f..784b87c0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,7 @@ members = [ "apps/repl", "apps/vault", "apps/vault/tools/vaultbackup-rs", + "apps/transientdisk", "services/libstd-test", "services/ffi-test", "services/tts", diff --git a/apps/manifest.json b/apps/manifest.json index 9e2c4234f..fe58e2d00 100644 --- a/apps/manifest.json +++ b/apps/manifest.json @@ -59,5 +59,13 @@ } }, "submenu": 1 + }, + "transientdisk": { + "context_name": "Transient USB disk", + "menu_name": { + "appmenu.transientdisk": { + "en": "Transient USB disk" + } + } } } diff --git a/apps/transientdisk/Cargo.toml b/apps/transientdisk/Cargo.toml new file mode 100644 index 000000000..c7198b553 --- /dev/null +++ b/apps/transientdisk/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "transientdisk" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +log = "0.4.14" +num-derive = {version = "0.3.3", default-features = false} +num-traits = {version = "0.2.14", default-features = false} +xous = "0.9.31" +xous-ipc = "0.9.31" +log-server = { package = "xous-api-log", version = "0.1.26" } +xous-names = { package = "xous-api-names", version = "0.9.28" } +gam = {path = "../../services/gam" } +graphics-server = {path = "../../services/graphics-server" } +usb-device-xous = {path="../../services/usb-device-xous"} diff --git a/apps/transientdisk/src/main.rs b/apps/transientdisk/src/main.rs new file mode 100644 index 000000000..0f72628a9 --- /dev/null +++ b/apps/transientdisk/src/main.rs @@ -0,0 +1,287 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +use core::fmt::Write; +use graphics_server::api::GlyphStyle; +use graphics_server::{DrawStyle, Gid, PixelColor, Point, Rectangle, TextBounds, TextView}; +use num_traits::*; + +pub(crate) const SERVER_NAME_TRANSIENTDISK: &str = "_Transient Disk_"; + +/// Top level application events. +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub(crate) enum TradOp { + /// Redraw the screen + Redraw = 0, + + FocusChange, + + Read, + Write, + MaxLba, + + /// Quit the application + Quit, +} + +// Framework code to draw a string of text on the screen. +// Taken from hello app. +struct UI { + content: Gid, + gam: gam::Gam, + _gam_token: [u32; 4], + screensize: Point, + #[cfg(feature = "tts")] + tts: TtsFrontend, +} + +impl UI { + fn new(xns: &xous_names::XousNames, sid: xous::SID) -> Self { + let gam = gam::Gam::new(&xns).expect("Can't connect to GAM"); + let gam_token = gam + .register_ux(gam::UxRegistration { + app_name: xous_ipc::String::<128>::from_str(gam::APP_NAME_TRANSIENTDISK), + ux_type: gam::UxType::Chat, + predictor: None, + listener: sid.to_array(), + redraw_id: TradOp::Redraw.to_u32().unwrap(), + gotinput_id: None, + audioframe_id: None, + rawkeys_id: None, + focuschange_id: Some(TradOp::FocusChange.to_u32().unwrap()), + }) + .expect("Could not register GAM UX") + .unwrap(); + + let content = gam + .request_content_canvas(gam_token) + .expect("Could not get content canvas"); + let screensize = gam + .get_canvas_bounds(content) + .expect("Could not get canvas dimensions"); + Self { + gam, + _gam_token: gam_token, + content, + screensize, + } + } + + /// Clear the entire screen. + fn clear_area(&self) { + self.gam + .draw_rectangle( + self.content, + Rectangle::new_with_style( + Point::new(0, 0), + self.screensize, + DrawStyle { + fill_color: Some(PixelColor::Light), + stroke_color: None, + stroke_width: 0, + }, + ), + ) + .expect("can't clear content area"); + } + + /// Redraw the text view onto the screen. + fn redraw(&mut self) { + self.clear_area(); + + let mut text_view = TextView::new( + self.content, + TextBounds::GrowableFromBr( + Point::new( + self.screensize.x - 45, + self.screensize.y - (self.screensize.y / 2), + ), + (self.screensize.x / 5 * 4) as u16, + ), + ); + + text_view.border_width = 1; + text_view.draw_border = true; + text_view.clear_area = true; + text_view.rounded_border = Some(3); + text_view.style = GlyphStyle::ExtraLarge; + write!(text_view.text, "1.44mb flash drive now available.") + .expect("Could not write to text view"); + + self.gam + .post_textview(&mut text_view) + .expect("Could not render text view"); + self.gam.redraw().expect("Could not redraw screen"); + } +} + +struct FlashDrive { + capacity: usize, + block_size: usize, + memory: xous::MemoryRange, +} + +#[derive(Debug)] +enum FlashDriveError { + CapacityNotPageAligned, +} + +impl FlashDrive { + fn new(capacity: usize, block_size: usize) -> Result { + if (capacity % 1024) != 0 { + return Err(FlashDriveError::CapacityNotPageAligned); + } + + let mut backing = xous::syscall::map_memory( + None, + None, + capacity, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .unwrap(); + + // initialize backing slice with bogus data + let backing_slice: &mut [u32] = backing.as_slice_mut(); + for (index, d) in backing_slice.iter_mut().enumerate() { + *d = index as u32; + } + + Ok(Self { + capacity, + block_size, + memory: backing, + }) + } + + fn read(&mut self, lba: usize, data: &mut [u8]) { + let backing_slice: &[u8] = self.memory.as_slice(); + + let rawdata = &backing_slice[lba * self.block_size..(lba + 1) * self.block_size]; + + data[..self.block_size].copy_from_slice(rawdata); + } + + fn write(&mut self, lba: usize, data: &mut [u8]) { + let backing_slice: &mut [u8] = self.memory.as_slice_mut(); + backing_slice[lba * self.block_size..(lba + 1) * self.block_size] + .copy_from_slice(&data[..self.block_size]); + } + + fn max_lba(&self) -> u32 { + (self.capacity as u32 / 512) - 1 + } +} + +fn main() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("Hello world PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + + // Register the server with xous + let sid = xns + .register_name(SERVER_NAME_TRANSIENTDISK, None) + .expect("can't register server"); + + let mut ui = UI::new(&xns, sid); + + let mut fd = FlashDrive::new(1445888, 512).expect("cannot create flash drive instance"); + + #[cfg(all( + any(feature = "precursor", feature = "renode"), + feature = "mass-storage" + ))] + let usb = usb_device_xous::UsbHid::new(); + + #[cfg(all( + any(feature = "precursor", feature = "renode"), + feature = "mass-storage" + ))] + let core_before_ms = usb.get_current_core().unwrap(); + + let mut usb_setup = false; + + loop { + let mut msg = xous::receive_message(sid).unwrap(); + log::debug!("Got message: {:?}", msg); + + match FromPrimitive::from_usize(msg.body.id()) { + Some(TradOp::Redraw) => { + log::info!("Got redraw"); + ui.redraw(); + } + Some(TradOp::Quit) => { + log::info!("Quitting application"); + break; + } + Some(TradOp::FocusChange) => xous::msg_scalar_unpack!(msg, new_state_code, _, _, _, { + let new_state = gam::FocusState::convert_focus_change(new_state_code); + match new_state { + gam::FocusState::Background => { + #[cfg(all( + any(feature = "precursor", feature = "renode"), + feature = "mass-storage" + ))] + { + usb.reset_block_device(); + usb.switch_to_core(core_before_ms).unwrap(); + } + } + gam::FocusState::Foreground => { + if usb_setup { + continue; + } + + #[cfg(all( + any(feature = "precursor", feature = "renode"), + feature = "mass-storage" + ))] + { + usb.set_block_device( + TradOp::Read.to_usize().unwrap(), + TradOp::Write.to_usize().unwrap(), + TradOp::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(TradOp::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::(); + + fd.read(lba, data); + } + Some(TradOp::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::(); + + fd.write(lba, data); + } + Some(TradOp::MaxLba) => { + xous::return_scalar(msg.sender, fd.max_lba() as usize).unwrap(); + } + _ => { + log::error!("Got unknown message"); + } + } + } + + log::info!("Quitting"); + xous::terminate_process(0) +} diff --git a/services/usb-device-xous/src/api.rs b/services/usb-device-xous/src/api.rs index f864badc6..0f09ee1e3 100644 --- a/services/usb-device-xous/src/api.rs +++ b/services/usb-device-xous/src/api.rs @@ -33,6 +33,10 @@ pub(crate) enum Opcode { /// Query if the HID driver was able to start IsSocCompatible, + SetBlockDevice, + SetBlockDeviceSID, + ResetBlockDevice, + /// Handle the USB interrupt UsbIrqHandler, /// Suspend/resume callback diff --git a/services/usb-device-xous/src/apps_block_device.rs b/services/usb-device-xous/src/apps_block_device.rs new file mode 100644 index 000000000..4cd27296f --- /dev/null +++ b/services/usb-device-xous/src/apps_block_device.rs @@ -0,0 +1,194 @@ +use core::convert::TryInto; +use num_traits::*; +use std::sync::Arc; +use std::sync::Mutex; +use usbd_scsi::BlockDevice; +use xous::msg_blocking_scalar_unpack; + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)] +pub enum BlockDeviceMgmtOp { + SetOps, + SetSID, + Reset, +} + +#[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>>, + rw_ids: Arc>, + 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 msg = xous::receive_message(mgmt_sid).unwrap(); + let opcode: Option = FromPrimitive::from_usize(msg.body.id()); + match opcode { + Some(BlockDeviceMgmtOp::SetOps) => { + msg_blocking_scalar_unpack!(msg, read_id, write_id, max_lba_id, _, { + let mut ids = rw_ids_clone.lock().unwrap(); + + *ids = RwOp { + read_id, + write_id, + max_lba_id, + }; + + log::info!("setting new app block device handler: {:?}", ids); + xous::return_scalar(msg.sender, 0).unwrap(); + }) + } + Some(BlockDeviceMgmtOp::SetSID) => { + msg_blocking_scalar_unpack!(msg, sid1, sid2, sid3, sid4, { + let app_sid = + xous::SID::from_u32(sid1 as u32, sid2 as u32, sid3 as u32, sid4 as u32); + let app_cid = xous::connect(app_sid).unwrap(); + let mut ac = app_cid_clone.lock().unwrap(); + + *ac = Some(app_cid as u32); + log::info!("setting new app block device handler SID: {:?}", app_sid); + xous::return_scalar(msg.sender, 0).unwrap(); + }) + } + Some(BlockDeviceMgmtOp::Reset) => msg_blocking_scalar_unpack!(msg, 0, 0, 0, 0, { + let mut ac = app_cid_clone.lock().unwrap(); + let mut ids = rw_ids_clone.lock().unwrap(); + + *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 + } +} + +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::(), + ) + .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::(), + ) + .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!"), + } + } +} diff --git a/services/usb-device-xous/src/block_device.rs b/services/usb-device-xous/src/block_device.rs deleted file mode 100644 index e71359fc7..000000000 --- a/services/usb-device-xous/src/block_device.rs +++ /dev/null @@ -1,43 +0,0 @@ -use xous::MemoryRange; - -const CAPACITY: usize = 256 * 1024; // must be a multiple of one page (4096) -pub struct BlockDevice{ - backing: MemoryRange, -} -impl BlockDevice { - pub fn new() -> Self { - 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; - } - BlockDevice { backing } - } -} - -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 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] - ); - Ok(()) - } - - fn write_block(&mut self, lba: u32, block: &[u8]) -> Result<(), usbd_scsi::BlockDeviceError> { - 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); - Ok(()) - } - - fn max_lba(&self) -> u32 { - (CAPACITY / Self::BLOCK_BYTES) as u32 - 1 - } -} \ No newline at end of file diff --git a/services/usb-device-xous/src/lib.rs b/services/usb-device-xous/src/lib.rs index 4fcb722bf..4724c167a 100644 --- a/services/usb-device-xous/src/lib.rs +++ b/services/usb-device-xous/src/lib.rs @@ -24,6 +24,44 @@ 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(); + } + + pub fn reset_block_device(&self) { + 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( diff --git a/services/usb-device-xous/src/main.rs b/services/usb-device-xous/src/main.rs index f15d0c23f..df5d845d2 100644 --- a/services/usb-device-xous/src/main.rs +++ b/services/usb-device-xous/src/main.rs @@ -21,7 +21,7 @@ use packed_struct::PackedStructSlice; #[cfg(any(feature="precursor", feature="renode"))] use spinal_udc::*; #[cfg(all(any(feature="precursor", feature="renode"),feature="mass-storage"))] -mod block_device; +mod apps_block_device; #[cfg(not(target_os = "xous"))] mod hosted; diff --git a/services/usb-device-xous/src/main_hosted.rs b/services/usb-device-xous/src/main_hosted.rs index 955ea58f2..0d55100ba 100644 --- a/services/usb-device-xous/src/main_hosted.rs +++ b/services/usb-device-xous/src/main_hosted.rs @@ -97,6 +97,15 @@ pub(crate) fn main_hosted() -> ! { let opcode: Option = FromPrimitive::from_usize(msg.body.id()); log::debug!("{:?}", opcode); match opcode { + Some(Opcode::SetBlockDevice) => { + log::info!("ignoring SetBlockDevice in hosted mode"); + }, + Some(Opcode::SetBlockDeviceSID) => { + log::info!("ignoring SetBlockDeviceSID in hosted mode"); + }, + 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"); diff --git a/services/usb-device-xous/src/main_hw.rs b/services/usb-device-xous/src/main_hw.rs index 81b7d76e6..78800e06c 100644 --- a/services/usb-device-xous/src/main_hw.rs +++ b/services/usb-device-xous/src/main_hw.rs @@ -225,16 +225,18 @@ pub(crate) fn main_hw() -> ! { #[cfg(feature="mass-storage")] let ums_alloc = UsbBusAllocator::new(ums_dev); #[cfg(feature="mass-storage")] - let bd = block_device::BlockDevice::new(); - #[cfg(feature="mass-storage")] + let 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") @@ -350,6 +352,31 @@ pub(crate) fn main_hw() -> ! { let opcode: Option = 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::ResetBlockDevice) => msg_blocking_scalar_unpack!(msg, 0, 0, 0, 0, { + xous::send_message(abdcid, + xous::Message::new_blocking_scalar( + apps_block_device::BlockDeviceMgmtOp::Reset.to_usize().unwrap(), 0, 0, 0, 0, + ) + ).unwrap(); + xous::return_scalar(msg.sender, 0).unwrap(); + }), Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { usbmgmt.xous_suspend(); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");