add usb disk option to baremetal environment

this will be used to help debug the HS issues
This commit is contained in:
bunnie 2025-09-07 15:11:46 +08:00
parent 1e00e7a496
commit f6c92a0a72
15 changed files with 2495 additions and 7 deletions

View file

@ -15,6 +15,14 @@ riscv = { version = "0.14.0", features = ["critical-section-single-hart"] }
linked_list_allocator = { version = "0.10.5", optional = true }
xous-bio-bdma = { path = "../libs/xous-bio-bdma", optional = true, default-features = false }
critical-section = "1.2.0"
ux-api = { path = "../libs/ux-api", optional = true, default-features = false }
simple-fatfs = { git = "https://github.com/betrusted-io/simple-fatfs.git", branch = "baosec", optional = true, default-features = false }
sha2 = { version = "0.10.8", optional = true, default-features = false }
digest = { version = "0.10.7", optional = true }
ed25519-dalek = { version = "=2.1.0", optional = true, default-features = false, features = [
"rand_core",
"digest",
] }
[features]
artybio = [
@ -45,6 +53,8 @@ nto-bio = [
]
# selects features for EVB target (defaults to baosec)
nto-evb = []
nto-gfx = ["ux-api/loader-baosec"]
nto-usb = ["nto-gfx", "simple-fatfs", "sha2", "digest", "ed25519-dalek"]
verilator-only = []
default = ["artyvexii", "nto-bio"]
default = ["nto-usb"]

Binary file not shown.

View file

@ -74,6 +74,10 @@ pub unsafe extern "C" fn rust_entry() -> ! {
let mut repl = crate::repl::Repl::new();
#[cfg(feature = "nto-bio")]
repl.init_cmd("bio"); // do a power-on BIO test
#[cfg(feature = "nto-usb")]
crate::platform::usb::glue::do_update(); // initially this supplants the repl loop
loop {
// Handle keyboard events.
critical_section::with(|cs| {

View file

@ -3,6 +3,10 @@ pub use cramium::*;
#[cfg(feature = "nto-bio")]
pub mod bio;
pub mod debug;
#[cfg(feature = "nto-gfx")]
pub mod gfx;
pub mod irq;
#[cfg(feature = "nto-usb")]
pub mod usb;
pub const UART_BAUD: u32 = 1_000_000;

View file

@ -13,11 +13,13 @@ use crate::platform::{
#[global_allocator]
static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN - 0x8_0000;
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM + 0x8_0000;
// bottom 256k (0x4_0000) reserved for jtag-booting targets code space
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN - 0x4_0000;
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM + 0x4_0000;
#[allow(dead_code)]
pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM;
// 0x5000 is the space for statics
pub const HEAP_START: usize = RAM_BASE + 0x5000;
pub const HEAP_LEN: usize = 1024 * 256;
@ -33,7 +35,7 @@ pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1;
pub fn early_init() {
// Define the .data region - bootstrap baremetal using these hard-coded parameters.
const DATA_ORIGIN: usize = 0x61080000;
const DATA_ORIGIN: usize = 0x61040000;
const DATA_SIZE_BYTES: usize = 0x5000;
const DATA_INIT: [(usize, u32); 1] = [(0x0, 0x1)];

View file

@ -0,0 +1,143 @@
use cramium_hal::sh1107::Mono;
use ux_api::minigfx::*;
// The discipline for all the APIs in this module are that they act on a FrameBuffer which is
// passed to the function. This allows us to bind the drawing computation on the caller-side of
// of a shared frame buffer.
// this font is from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/
const FONT_IMAGE: &'static [u8] = include_bytes!("../../font6x12_1bpp.raw");
pub const CHAR_HEIGHT: isize = 12;
pub const CHAR_WIDTH: isize = 6;
const FONT_IMAGE_WIDTH: isize = 96;
const LEFT_MARGIN: isize = 10;
fn char_offset(c: char) -> isize {
let fallback = ' ' as isize - ' ' as isize;
if c < ' ' {
return fallback;
}
if c <= '~' {
return c as isize - ' ' as isize;
}
fallback
}
pub fn msg<'a>(fb: &mut dyn FrameBuffer, text: &'a str, ll_pos: Point, fg: ColorNative, bg: ColorNative) {
let mut ll_pos = ll_pos.clone();
// this routine is adapted from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/
let char_per_row = FONT_IMAGE_WIDTH / CHAR_WIDTH;
let mut idx = 0;
let mut x_update = 0;
for current_char in text.chars() {
let mut char_walk_x = 0;
let mut char_walk_y = 0;
loop {
// Char _code_ offset from first char, most often a space
// E.g. first char = ' ' (32), target char = '!' (33), offset = 33 - 32 = 1
let char_offset = char_offset(current_char);
let row = char_offset / char_per_row;
// Top left corner of character, in pixels
let char_x = (char_offset - (row * char_per_row)) * CHAR_WIDTH;
let char_y = row * CHAR_HEIGHT;
// Bit index
// = X pixel offset for char
// + Character row offset (row 0 = 0, row 1 = (192 * 8) = 1536)
// + X offset for the pixel block that comprises this char
// + Y offset for pixel block
let bitmap_bit_index =
char_x + (FONT_IMAGE_WIDTH * char_y) + char_walk_x + (char_walk_y * FONT_IMAGE_WIDTH);
let bitmap_byte = bitmap_bit_index / 8;
let bitmap_bit = 7 - (bitmap_bit_index % 8);
let color = if FONT_IMAGE[bitmap_byte as usize] & (1 << bitmap_bit) != 0 { fg } else { bg };
let x = ll_pos.x + CHAR_WIDTH * idx + char_walk_x;
let y = ll_pos.y + char_walk_y;
// draw color at x, y
if (current_char as u8 != 0xd) && (current_char as u8 != 0xa) {
// don't draw CRLF specials
fb.put_pixel(Point::new(x, y), color);
}
char_walk_x += 1;
if char_walk_x >= CHAR_WIDTH {
char_walk_x = 0;
char_walk_y += 1;
// Done with this char, move on to the next one
if char_walk_y >= CHAR_HEIGHT {
if current_char as u8 == 0xd {
// '\n'
ll_pos.y += CHAR_HEIGHT;
} else if current_char as u8 == 0xa {
// '\r'
ll_pos.x = LEFT_MARGIN;
x_update = 0;
} else {
idx += 1;
x_update += CHAR_WIDTH;
}
break;
}
}
}
}
ll_pos.x += x_update;
}
#[allow(dead_code)]
pub fn line(fb: &mut dyn FrameBuffer, l: Line, clip: Option<Rectangle>, xor: bool) {
let color: ColorNative;
if l.style.stroke_color.is_some() {
color = l.style.stroke_color.unwrap().into();
} else {
return;
}
let mut x0 = l.start.x;
let mut y0 = l.start.y;
let x1 = l.end.x;
let y1 = l.end.y;
let dx = (x1 - x0).abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -((y1 - y0).abs());
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy; // error value e_xy
loop {
if x0 >= 0 && y0 >= 0 && x0 < (fb.dimensions().x as _) && y0 < (fb.dimensions().y as _) {
if clip.is_none() || (clip.unwrap().intersects_point(Point::new(x0, y0))) {
if !xor {
fb.put_pixel(Point::new(x0 as _, y0 as _), color);
} else {
if let Some(existing) = fb.get_pixel(Point::new(x0 as _, y0 as _)) {
if existing == Mono::Black.into() {
fb.put_pixel(Point::new(x0 as _, y0 as _), Mono::White.into());
} else {
fb.put_pixel(Point::new(x0 as _, y0 as _), Mono::Black.into());
}
}
}
}
}
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
if e2 >= dy {
err += dy;
x0 += sx;
}
if e2 <= dx {
err += dx;
y0 += sy;
}
}
}

View file

@ -1,6 +1,10 @@
#[cfg(feature = "nto-usb")]
use cramium_hal::usb::utra::*;
use riscv::register::{mcause, mie, mstatus};
use vexriscv::register::vexriscv::{mim, mip};
#[cfg(feature = "nto-usb")]
use crate::usb::USB;
use crate::*;
pub fn irq_setup() {
@ -43,7 +47,7 @@ pub unsafe extern "C" fn _start_trap() -> ! {
#[rustfmt::skip]
core::arch::asm!(
"csrw mscratch, sp",
"li sp, 0x61083000", // crate::platform::SCRATCH_PAGE - has to be hard-coded
"li sp, 0x61043000", // crate::platform::SCRATCH_PAGE - has to be hard-coded
"sw x1, 0*4(sp)",
// Skip SP for now
"sw x3, 2*4(sp)",
@ -89,7 +93,7 @@ pub unsafe extern "C" fn _start_trap() -> ! {
"csrr t0, mscratch",
"sw t0, 1*4(sp)",
// Restore a default stack pointer
"li sp, 0x61085000", // heap base, grows down
"li sp, 0x61045000", // heap base, grows down
// Note that registers $a0-$a7 still contain the arguments
"j _start_trap_rust",
@ -202,6 +206,55 @@ pub extern "C" fn trap_handler(
crate::println!("keypress interrupt {:x}", pending);
irqarray2.wo(utra::irqarray2::EV_PENDING, pending);
}
#[cfg(feature = "nto-usb")]
if (irqs_pending & (1 << utralib::utra::irqarray1::IRQARRAY1_IRQ)) != 0 {
// handle USB interrupt
unsafe {
if let Some(ref mut usb_ref) = USB {
let usb = &mut *core::ptr::addr_of_mut!(*usb_ref);
// immediately clear the interrupt and re-enable it so we can catch an interrupt
// that is generated while we are handling the interrupt.
let pending = usb.irq_csr.r(utralib::utra::irqarray1::EV_PENDING);
// clear pending
usb.irq_csr.wo(utralib::utra::irqarray1::EV_PENDING, pending);
// re-enable interrupts
usb.irq_csr.wfo(utralib::utra::irqarray1::EV_ENABLE_USBC_DUPE, 1);
let status = usb.csr.r(USBSTS);
// usb.print_status(status);
if (status & usb.csr.ms(USBSTS_SYSTEM_ERR, 1)) != 0 {
crate::println!("System error");
usb.csr.wfo(USBSTS_SYSTEM_ERR, 1);
crate::println!("USBCMD: {:x}", usb.csr.r(USBCMD));
} else {
if (status & usb.csr.ms(USBSTS_EINT, 1)) != 0 {
// from udc_handle_interrupt
let mut ret = cramium_hal::usb::driver::CrgEvent::None;
let status = usb.csr.r(USBSTS);
// self.print_status(status);
let _result = if (status & usb.csr.ms(USBSTS_SYSTEM_ERR, 1)) != 0 {
crate::println!("System error");
usb.csr.wfo(USBSTS_SYSTEM_ERR, 1);
crate::println!("USBCMD: {:x}", usb.csr.r(USBCMD));
cramium_hal::usb::driver::CrgEvent::Error
} else {
if (status & usb.csr.ms(USBSTS_EINT, 1)) != 0 {
usb.csr.wfo(USBSTS_EINT, 1);
// divert to the loader-based event ring handler
ret = usb.process_event_ring(); // there is only one event ring
}
ret
};
// crate::println!("Result: {:?}", _result);
}
if usb.csr.rf(IMAN_IE) != 0 {
usb.csr.wo(IMAN, usb.csr.ms(IMAN_IE, 1) | usb.csr.ms(IMAN_IP, 1));
}
}
}
}
}
}
// re-enable interrupts

View file

@ -1,7 +1,8 @@
/* bottom 256k reserved for copying code into RAM for JTAG-booting targets */
MEMORY
{
FLASH : ORIGIN = 0x60000000, LENGTH = 256k
RAM : ORIGIN = 0x61080000, LENGTH = 1536k
RAM : ORIGIN = 0x61040000, LENGTH = 1792k
}
REGION_ALIAS("REGION_TEXT", FLASH);

View file

@ -0,0 +1,479 @@
use core::convert::TryFrom;
use core::sync::atomic::{AtomicPtr, Ordering};
use cramium_hal::usb::compat::AtomicCsr;
use cramium_hal::usb::driver::CorigineUsb;
use cramium_hal::usb::driver::*;
use cramium_hal::usb::utra::*;
use super::*;
pub(crate) static mut USB: Option<CorigineUsb> = None;
/// Safety issue: the loader itself doesn't have a loader. So, any .data required by
/// the loader program can't be set up in advance for the loader.
///
/// The root problem: generally, a `static mut` in the loader will cause some .data
/// to be allocated. The USB handler needs to be a `static mut` because
/// the interrupt handler needs to be able to find it at a globally known location, and
/// the data has to persist beyond the scope of a single interrupt.
///
/// The assumption: we don't have to include the data section in the loader's ROM image
/// because 1) the data going into the `static mut` interrupt handler is assumed uninitialized
/// (due to the wrapper being an Option<Usb> set to None); and 2) the RAM is fully zeroized by a
/// small assembly routine that executes before the loader runs.
///
/// (1) means that in practice, the contents of the .data section is "almost 0".
/// (2) means we can just whack a pointer at where the
/// data section should go and the assumptions are met for the loader.
///
/// The inconsistency: inspecting the generated binary indicates that the `None` representation
/// for USB is not `0`; it instead has the representation of `2`. This means that if we try to
/// access `USB` prior to initialization, we will get UB.
///
/// Safe usage: init_usb() must be called before any attempt to access USB, including interrupts.
/// Furthermore, we have to manually guarantee that there are no concurrency/race conditions accessing
/// the USB structure (we are in no_std so we don't have a Mutex). Finally, we have to ensure that
/// USB is initialized with no assumptions about what is in memory prior to any access to it.
///
/// Even then, we might have some risk of UB if the compiler decides it really wants to rely
/// on some pre-initialized structure of the `USB` static mut `None`. In practice, we haven't
/// seen this, but we run a risk of this breaking in future versions of Rust because the compiler
/// is allowed to assume that `USB` has the correct value to represent a `None` on boot.
pub unsafe fn init_usb() {
let mut usb = unsafe {
cramium_hal::usb::driver::CorigineUsb::new(
cramium_hal::board::CRG_UDC_MEMBASE,
AtomicCsr::new(cramium_hal::usb::utra::CORIGINE_USB_BASE as *mut u32),
AtomicCsr::new(utralib::utra::irqarray1::HW_IRQARRAY1_BASE as *mut u32),
)
};
usb.assign_handler(handle_event);
// initialize the "disk" area
let disk = mass_storage::conjure_disk();
disk.fill(0);
// setup MBR
disk[..MBR_TEMPLATE.len()].copy_from_slice(&MBR_TEMPLATE);
/*
//set block size
disk[0xb..0xd].copy_from_slice(&SECTOR_SIZE.to_le_bytes());
//set storage size
disk[0x20..0x24].copy_from_slice(&(RAMDISK_LEN as u32 / SECTOR_SIZE as u32).to_le_bytes());
*/
// populate an initial "windows-friendly" FAT layout, generated by plugging the empty disk
// into windows and letting it...do its thing, then snapshotting the data.
disk[TABLE_OFFSET_FAT1..TABLE_OFFSET_FAT1 + FAT_TABLE.len()].copy_from_slice(&FAT_TABLE);
disk[TABLE_OFFSET_FAT2..TABLE_OFFSET_FAT2 + FAT_TABLE.len()].copy_from_slice(&FAT_TABLE);
disk[ROOT_DIR_OFFSET..ROOT_DIR_OFFSET + ROOT_DIR.len()].copy_from_slice(&ROOT_DIR);
disk[FAT_DATA1_OFFSET..FAT_DATA1_OFFSET + FAT_DATA1.len()].copy_from_slice(&FAT_DATA1);
disk[FAT_DATA2_OFFSET..FAT_DATA2_OFFSET + FAT_DATA2.len()].copy_from_slice(&FAT_DATA2);
disk[FAT_DATA3_OFFSET..FAT_DATA3_OFFSET + FAT_DATA3.len()].copy_from_slice(&FAT_DATA3);
// install the interrupt handler
// setup the stack & controller
irq_setup();
enable_irq(utralib::utra::irqarray1::IRQARRAY1_IRQ);
// for testing
enable_irq(utralib::utra::irqarray19::IRQARRAY19_IRQ);
let mut irqarray19 = utralib::CSR::new(utralib::utra::irqarray19::HW_IRQARRAY19_BASE as *mut u32);
irqarray19.wo(utralib::utra::irqarray19::EV_ENABLE, 0x80);
unsafe {
USB = Some(usb);
}
}
#[allow(dead_code)]
pub unsafe fn test_usb() {
if let Some(ref mut usb_ref) = USB {
let usb = &mut *core::ptr::addr_of_mut!(*usb_ref);
usb.reset();
let mut poweron = 0;
loop {
usb.udc_handle_interrupt();
if usb.pp() {
poweron += 1; // .pp() is a sham. MPW has no way to tell if power is applied. This needs to be fixed for NTO.
}
delay(100);
if poweron >= 4 {
break;
}
}
usb.reset();
usb.init();
usb.start();
usb.update_current_speed();
// IRQ enable must happen without dependency on the hardware lock
usb.irq_csr.wo(utralib::utra::irqarray1::EV_PENDING, 0xffff_ffff); // blanket clear
usb.irq_csr.wfo(utralib::utra::irqarray1::EV_ENABLE_USBC_DUPE, 1);
crate::println!("hw started...");
/*
let mut vbus_on = false;
let mut vbus_on_count = 0;
let mut in_u0 = false;
loop {
if vbus_on == false && vbus_on_count == 4 {
crate::println!("vbus on");
usb.init();
usb.start();
vbus_on = true;
in_u0 = false;
} else if usb.pp() == true && vbus_on == false {
vbus_on_count += 1;
delay(100);
} else if usb.pp() == false && vbus_on == true {
crate::println!("20230802 vbus off during while");
usb.stop();
usb.reset();
vbus_on_count = 0;
vbus_on = false;
in_u0 = false;
} else if in_u0 == true && vbus_on == true {
crate::println!("USB stack started");
break;
// crate::println!("Would be uvc_bulk_thread()");
// uvc_bulk_thread();
} else if usb.ccs() == true && vbus_on == true {
crate::println!("enter U0");
in_u0 = true;
}
}
*/
let mut i = 0;
loop {
// wait for interrupt handler to do something
crate::println!("{}", i);
i += 1;
delay(10_000);
// for testing interrupt handler
let mut irqarray19 = utralib::CSR::new(utralib::utra::irqarray19::HW_IRQARRAY19_BASE as *mut u32);
irqarray19.wfo(utralib::utra::irqarray19::EV_SOFT_TRIGGER, 0x80);
}
} else {
crate::println!("USB core not allocated, skipping USB test");
}
}
fn delay(quantum: usize) {
use utralib::{CSR, utra};
// abuse the d11ctime timer to create some time-out like thing
let mut d11c = CSR::new(utra::d11ctime::HW_D11CTIME_BASE as *mut u32);
d11c.wfo(utra::d11ctime::CONTROL_COUNT, 333_333); // 1.0ms per interval
let mut polarity = d11c.rf(utra::d11ctime::HEARTBEAT_BEAT);
for _ in 0..quantum {
while polarity == d11c.rf(utra::d11ctime::HEARTBEAT_BEAT) {}
polarity = d11c.rf(utra::d11ctime::HEARTBEAT_BEAT);
}
// we have to split this because we don't know where we caught the previous interval
if quantum == 1 {
while polarity == d11c.rf(utra::d11ctime::HEARTBEAT_BEAT) {}
}
}
fn get_status_request(this: &mut CorigineUsb, request_type: u8, index: u16) {
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
CRG_UDC_EP0_REQBUFSIZE,
)
};
let mut status_val: u32 = 0;
let recipient = request_type & 0x1f;
let ep_num = index & 0x7f;
let ep_dir = if index & 0x80 != 0 { USB_SEND } else { USB_RECV };
match recipient {
USB_RECIP_DEVICE => {
status_val |= 0x1;
ep0_buf[0] = status_val as u8;
this.ep0_send(ep0_buf.as_ptr() as usize, 2, 0);
}
USB_RECIP_INTERFACE => {
ep0_buf[0] = 0;
ep0_buf[1] = 0;
this.ep0_send(ep0_buf.as_ptr() as usize, 2, 0);
}
USB_RECIP_ENDPOINT => {
if this.is_halted(ep_num as u8, ep_dir) {
ep0_buf[0] = 1;
this.ep0_send(ep0_buf.as_ptr() as usize, 2, 0);
} else {
ep0_buf[0] = 0;
this.ep0_send(ep0_buf.as_ptr() as usize, 2, 0);
}
}
_ => {
this.ep_halt(0, USB_RECV);
}
}
}
fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
// crate::println!("handle_event: {:x?}", event_trb);
let pei = event_trb.get_endpoint_id();
let ep_num = pei >> 1;
let udc_ep = &mut this.udc_ep[pei as usize];
let mut ret = CrgEvent::None;
match event_trb.get_trb_type() {
TrbType::EventPortStatusChange => {
let portsc_val = this.csr.r(PORTSC);
this.csr.wo(PORTSC, portsc_val);
// this.print_status(portsc_val);
let portsc = PortSc(portsc_val);
// crate::println!("{:?}", portsc);
if portsc.prc() && !portsc.pr() {
crate::println!("update_current_speed() - reset done");
this.update_current_speed();
}
if portsc.csc() && portsc.ppc() && portsc.pp() && portsc.ccs() {
crate::println!("update_current_speed() - cable connect");
this.update_current_speed();
}
this.csr.rmwf(EVENTCONFIG_SETUP_ENABLE, 1);
}
TrbType::EventTransfer => {
let comp_code =
CompletionCode::try_from(event_trb.dw2.compl_code()).expect("Invalid completion code");
// update the dequeue pointer
// crate::println!("event_transfer {:x?}", event_trb);
let deq_pt =
unsafe { (event_trb.dw0 as *mut TransferTrbS).add(1).as_mut().expect("Couldn't deref ptr") };
if deq_pt.get_trb_type() == TrbType::Link {
udc_ep.deq_pt = AtomicPtr::new(udc_ep.first_trb.load(Ordering::SeqCst));
} else {
udc_ep.deq_pt = AtomicPtr::new(deq_pt as *mut TransferTrbS);
}
// crate::println!("EventTransfer: comp_code {:?}, PEI {}", comp_code, pei);
let dir = (pei & 1) != 0;
if pei == 0 {
if comp_code == CompletionCode::Success {
// ep0_xfer_complete
if dir == USB_SEND {
ret = CrgEvent::Data(0, 1, 0); // FIXME: this ordering contradicts the `dir` bit, but seems necessary to trigger the next packet send
} else {
ret = CrgEvent::Data(1, 0, 0); // FIXME: this ordering contradicts the `dir` bit, but seems necessary to trigger the next packet send
}
} else {
crate::println!("EP0 unhandled comp_code: {:?}", comp_code);
ret = CrgEvent::None;
}
} else if pei >= 2 {
if comp_code == CompletionCode::Success || comp_code == CompletionCode::ShortPacket {
// crate::println!("EP{} xfer event, dir {}", ep_num, if dir { "OUT" } else { "IN" });
// xfer_complete
if let Some(f) = this.udc_ep[pei as usize].completion_handler {
// so unsafe. so unsafe. We're counting on the hardware to hand us a raw pointer
// that isn't corrupted.
let p_trb = unsafe { &*(event_trb.dw0 as *const TransferTrbS) };
f(this, p_trb.dplo as usize, p_trb.dw2.0, 0);
}
} else if comp_code == CompletionCode::MissedServiceError {
crate::println!("MissedServiceError");
} else {
crate::println!("EventTransfer {:?} event not handled", comp_code);
}
}
}
TrbType::SetupPkt => {
let mut setup_storage = [0u8; 8];
setup_storage.copy_from_slice(&event_trb.get_raw_setup());
this.setup = Some(setup_storage);
this.setup_tag = event_trb.get_setup_tag();
let mut setup_pkt = CtrlRequest::default();
setup_pkt.as_mut().copy_from_slice(&setup_storage);
let w_value = setup_pkt.w_value;
let w_index = setup_pkt.w_index;
let w_length = setup_pkt.w_length;
/*
crate::println!(
" b_request={:x}, b_request_type={:x}, w_value={:04x}, w_index=0x{:x}, w_length={}",
setup_pkt.b_request,
setup_pkt.b_request_type,
w_value,
w_index,
w_length
);
*/
if (setup_pkt.b_request_type & USB_TYPE_MASK) == USB_TYPE_STANDARD {
match setup_pkt.b_request {
USB_REQ_GET_STATUS => {
crate::println!("USB_REQ_GET_STATUS");
get_status_request(this, setup_pkt.b_request_type, w_index);
}
USB_REQ_SET_ADDRESS => {
crate::println!("USB_REQ_SET_ADDRESS: {}, tag: {}", w_value, this.setup_tag);
this.set_addr(w_value as u8, CRG_INT_TARGET);
// crate::println!(" ******* set address done {}", w_value & 0xff);
}
USB_REQ_SET_SEL => {
crate::println!("USB_REQ_SET_SEL");
this.ep0_receive(this.ep0_buf.load(Ordering::SeqCst) as usize, w_length as usize, 0);
delay(100);
/* do set sel */
crate::println!("SEL_VALUE NOT HANDLED");
/*
crg_udc->sel_value.u1_sel_value = *ep0_buf;
crg_udc->sel_value.u1_pel_value = *(ep0_buf+1);
crg_udc->sel_value.u2_sel_value = *(uint16_t*)(ep0_buf+2);
crg_udc->sel_value.u2_pel_value = *(uint16_t*)(ep0_buf+4);
*/
}
USB_REQ_SET_ISOCH_DELAY => {
crate::println!("USB_REQ_SET_ISOCH_DELAY");
/* do set isoch delay */
this.ep0_send(0, 0, 0);
}
USB_REQ_CLEAR_FEATURE => {
crate::println!("USB_REQ_CLEAR_FEATURE");
crate::println!("*** UNSUPPORTED ***");
/* do clear feature */
// clear_feature_request(setup_pkt.b_request_type, w_index, w_value);
}
USB_REQ_SET_FEATURE => {
crate::println!("USB_REQ_SET_FEATURE\r\n");
crate::println!("*** UNSUPPORTED ***");
/* do set feature */
/*
if crg_udc_get_device_state() == USB_STATE_CONFIGURED {
set_feature_request(setup_pkt.b_request_type, w_index, w_value);
} else {
crg_udc_ep_halt(0, USB_RECV);
}
*/
}
USB_REQ_SET_CONFIGURATION => {
crate::println!("USB_REQ_SET_CONFIGURATION");
let mut pass = false;
if w_value == 0 {
this.set_device_state(UsbDeviceState::Address);
} else if w_value == 1 {
this.set_device_state(UsbDeviceState::Configured);
} else {
this.ep_halt(0, USB_RECV);
pass = true;
}
if !pass {
this.assign_completion_handler(usb_ep1_bulk_in_complete, 1, USB_SEND);
this.assign_completion_handler(usb_ep1_bulk_out_complete, 1, USB_RECV);
enable_mass_storage_eps(this, 1);
this.bulk_xfer(1, USB_RECV, this.cbw_ptr(), 31, 0, 0);
this.ms_state = UmsState::CommandPhase;
this.ep0_send(0, 0, 0);
}
}
USB_REQ_GET_DESCRIPTOR => {
crate::println!("USB_REQ_GET_DESCRIPTOR");
get_descriptor_request(this, w_value, w_index as usize, w_length as usize);
}
USB_REQ_GET_CONFIGURATION => {
crate::println!("USB_REQ_GET_CONFIGURATION");
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
CRG_UDC_EP0_REQBUFSIZE,
)
};
if this.get_device_state() != UsbDeviceState::Configured {
ep0_buf[0] = 0;
} else {
ep0_buf[0] = 1
}
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
}
USB_REQ_SET_INTERFACE => {
crate::println!("USB_REQ_SET_INTERFACE");
this.cur_interface_num = (w_value & 0xF) as u8;
crate::println!("USB_REQ_SET_INTERFACE altsetting {}", this.cur_interface_num);
this.ep0_send(0, 0, 0);
}
USB_REQ_GET_INTERFACE => {
crate::println!("USB_REQ_GET_INTERFACE");
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
CRG_UDC_EP0_REQBUFSIZE,
)
};
ep0_buf[0] = this.cur_interface_num;
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
}
_ => {
crate::println!(
"USB_REQ default b_request=0x{:x}, b_request_type=0x{:x}",
setup_pkt.b_request,
setup_pkt.b_request_type
);
this.ep_halt(0, USB_RECV);
}
}
} else if (setup_pkt.b_request_type & USB_TYPE_MASK) == USB_TYPE_CLASS {
match setup_pkt.b_request {
0xff => {
crate::println!("Mass Storage Reset\r\n");
if (0 == w_value)
&& (InterfaceDescriptor::default_mass_storage().b_interface_number
== w_index as u8)
&& (0 == w_length)
{
this.ep_unhalt(1, USB_SEND);
this.ep_unhalt(1, USB_RECV);
enable_mass_storage_eps(this, ep_num);
this.ms_state = UmsState::CommandPhase;
this.bulk_xfer(1, USB_RECV, this.cbw_ptr(), 31, 0, 0);
//crg_udc_ep0_status(false,0);
this.ep0_send(0, 0, 0);
} else {
this.ep_halt(0, USB_RECV);
}
}
0xfe => {
crate::println!("Get Max LUN");
if w_index != 0 || w_value != 0 || w_length != 1 {
this.ep_halt(0, USB_RECV);
} else {
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
CRG_UDC_EP0_REQBUFSIZE,
)
};
ep0_buf[0] = 0;
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
}
}
_ => {
crate::println!("Unhandled!");
}
}
} else {
this.ep_halt(0, USB_RECV);
}
ret = CrgEvent::Data(0, 0, 1);
}
TrbType::DataStage => {
panic!("data stage needs handling");
}
_ => {
crate::println!("Unexpected trb_type {:?}", event_trb.get_trb_type());
}
}
ret
}

View file

@ -0,0 +1,432 @@
use core::convert::TryInto;
use core::fmt::Write;
use cramium_api::PeriphId;
use cramium_hal::board::SPIM_FLASH_IFRAM_ADDR;
use cramium_hal::ifram::IframRange;
use cramium_hal::iox::Iox;
use cramium_hal::sh1107::*;
use cramium_hal::udma;
use cramium_hal::udma::*;
use cramium_hal::usb::driver::UsbDeviceState;
use ed25519_dalek::{Digest, Signature, VerifyingKey};
use sha2::Sha512;
use simple_fatfs::PathBuf;
use utralib::generated::*;
use ux_api::minigfx::*;
use crate::platform::gfx;
use crate::usb;
use crate::usb::SliceCursor;
use crate::usb::sha512_digest::Sha512Prehash;
const TEXT_MIDLINE: isize = 51;
// Empirically measured PORTSC when the port is unplugged. This might be a brittle way
// to detect if the device is unplugged.
const DISCONNECT_STATE: u32 = 0x40b;
// loader is not updateable here because we're XIP. But we can update these other images:
const SWAP_NAME: &'static str = "SWAP.IMG";
const KERNEL_NAME: &'static str = "XOUS.BIN";
#[allow(dead_code)]
const SWAP_BASE_ADDR: usize = 0;
// location of kernel, as offset from the base of ReRAM. This needs to match up with what is in link.x.
// exclusive of the signature block offset. Vendored in from the cramium platform definition.
pub const KERNEL_BASE_ADDR: usize = 0x6_0000;
const SIGBLOCK_SIZE: usize = 0x1000;
const DEV_PUBKEY: [u8; 32] = [
0x1c, 0x9b, 0xea, 0xe3, 0x2a, 0xea, 0xc8, 0x75, 0x07, 0xc1, 0x80, 0x94, 0x38, 0x7e, 0xff, 0x1c, 0x74,
0x61, 0x42, 0x82, 0xaf, 0xfd, 0x81, 0x52, 0xd8, 0x71, 0x35, 0x2e, 0xdf, 0x3f, 0x58, 0xbb,
];
#[repr(C)]
struct SignatureInFlash {
pub version: u32,
pub signed_len: u32,
pub signature: [u8; 64],
}
#[derive(Debug)]
#[repr(C)]
pub struct SwapSourceHeader {
pub version: u32,
pub partial_nonce: [u8; 8],
pub mac_offset: u32,
pub aad_len: u32,
// aad is limited to 64 bytes!
pub aad: [u8; 64],
}
pub fn do_update() {
crate::println!(
"RAM disk starts at {:x} and is {}kiB in length",
usb::RAMDISK_ADDRESS,
usb::RAMDISK_LEN / 1024
);
let perclk = 100_000_000;
let mut iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
let mut udma_global = udma::GlobalConfig::new();
let mut sh1107 = cramium_hal::sh1107::Oled128x128::new(
cramium_hal::sh1107::MainThreadToken::new(),
perclk,
&mut iox,
&mut udma_global,
);
gfx::msg(
&mut sh1107,
"Connect to USB",
Point::new(16, TEXT_MIDLINE),
Mono::White.into(),
Mono::Black.into(),
);
sh1107.draw();
// safety: this is safe because we're calling this before any access to `USB` static mut
// state, and we also understand that the .data section doesn't exist in the loader and
// we've taken countermeasures to initialize everything "from code", i.e. not relying
// on static compile-time assignments for the static mut state.
unsafe { crate::platform::cramium::usb::init_usb() };
// Below is all unsafe because USB is global mutable state
unsafe {
if let Some(ref mut usb_ref) = crate::platform::cramium::usb::USB {
crate::println!("inside update");
let usb = &mut *core::ptr::addr_of_mut!(*usb_ref);
usb.reset();
let mut poweron = 0;
loop {
usb.udc_handle_interrupt();
if usb.pp() {
poweron += 1; // .pp() is a sham. MPW has no way to tell if power is applied. This needs to be fixed for NTO.
}
crate::platform::delay(100);
if poweron >= 4 {
break;
}
}
usb.reset();
usb.init();
usb.start();
usb.update_current_speed();
// IRQ enable must happen without dependency on the hardware lock
usb.irq_csr.wo(utralib::utra::irqarray1::EV_PENDING, 0xffff_ffff); // blanket clear
usb.irq_csr.wfo(utralib::utra::irqarray1::EV_ENABLE_USBC_DUPE, 1);
let mut last_usb_state = usb.get_device_state();
let mut portsc = usb.portsc_val();
crate::println!("USB state: {:?}, {:x}", last_usb_state, portsc);
loop {
let new_usb_state = usb.get_device_state();
let new_portsc = usb.portsc_val();
// alternately, break out of the loop when USB is disconnected
if new_portsc != portsc {
crate::println!("PP: {:x}", portsc);
portsc = new_portsc;
if portsc == DISCONNECT_STATE && new_usb_state == UsbDeviceState::Configured {
break;
}
}
if new_usb_state != last_usb_state {
crate::println!("USB state: {:?}", new_usb_state);
if new_usb_state == UsbDeviceState::Configured {
sh1107.clear();
gfx::msg(
&mut sh1107,
"Copy files to device",
Point::new(6, TEXT_MIDLINE),
Mono::White.into(),
Mono::Black.into(),
);
gfx::msg(
&mut sh1107,
"Press DOWN",
Point::new(22, TEXT_MIDLINE + 18),
Mono::Black.into(),
Mono::White.into(),
);
gfx::msg(
&mut sh1107,
"when finished!",
Point::new(19, TEXT_MIDLINE + 32),
Mono::Black.into(),
Mono::White.into(),
);
sh1107.draw();
last_usb_state = new_usb_state;
}
}
}
let disk = usb::conjure_disk();
let mut cursor = SliceCursor::new(disk);
// We can either pass by value of by (mutable) reference
let mut fs = simple_fatfs::FileSystem::from_storage(&mut cursor).unwrap();
match fs.read_dir(PathBuf::from("/")) {
Ok(dir) => {
for entry in dir {
crate::println!("{:?}", entry);
if let Some(file_name) = entry.path().file_name() {
if file_name.to_ascii_uppercase() == KERNEL_NAME {
let f = fs.get_file(entry.path().clone()).expect("file error");
let sector_offset = f.sector_offset();
crate::println!("sector offset: {}", sector_offset);
let disk_access = usb::conjure_disk();
crate::println!(
"{:x?}",
&disk_access
[sector_offset as usize * 512..sector_offset as usize * 512 + 32]
);
let pubkey =
VerifyingKey::from_bytes(&DEV_PUBKEY).expect("public key was not valid");
crate::println!("pubkey as reconstituted: {:x?}", pubkey);
let k_start = sector_offset as usize * 512;
let sig_region =
&disk_access[k_start..k_start + core::mem::size_of::<SignatureInFlash>()];
let sig_rec: &SignatureInFlash =
(sig_region.as_ptr() as *const SignatureInFlash).as_ref().unwrap(); // this pointer better not be null, we just created it!
let sig = Signature::from_bytes(&sig_rec.signature);
let kern_len = sig_rec.signed_len as usize;
crate::println!("recorded kernel len: {} bytes", kern_len);
crate::println!("verifying with signature {:x?}", sig_rec.signature);
crate::println!("verifying with pubkey {:x?}", pubkey.to_bytes());
let mut h: Sha512 = Sha512::new();
let image = &disk_access[k_start + SIGBLOCK_SIZE
..k_start + SIGBLOCK_SIZE + sig_rec.signed_len as usize];
crate::println!("image bytes: {:x?}", &image[..16]);
h.update(&image);
let hash = h.finalize();
let mut ph = Sha512Prehash::new();
ph.set_prehash(hash.as_slice().try_into().unwrap());
let v_result = pubkey.verify_prehashed(ph, None, &sig);
if let Err(e) = v_result {
crate::println!("error verifying signature: {:?}", e);
gfx::msg(
&mut sh1107,
"Kernel invalid!",
Point::new(10, TEXT_MIDLINE),
Mono::White.into(),
Mono::Black.into(),
);
sh1107.draw();
sh1107.clear();
return;
}
crate::println!("Kernel image is good!");
let mut rram = cramium_hal::rram::Reram::new();
// concatenate this with e.g. .min(0x2000) to shorten the run, if needed
let test_len = sig_rec.signed_len as usize;
let check_slice = core::slice::from_raw_parts(
(KERNEL_BASE_ADDR + utralib::HW_RERAM_MEM) as *const u8,
0x3000,
);
crate::println!(
"data before: {:x?} .. {:x?}",
&check_slice[..32],
&check_slice[0x1000..0x1000 + 32]
);
progress_bar(&mut sh1107, 0);
// choose a constant that balances screen updates versus performance
const BLOCKLEN_BYTES: usize = 4096 * 16;
let total_len = SIGBLOCK_SIZE + test_len;
for (i, byte_chunk) in disk_access
[k_start..k_start + SIGBLOCK_SIZE + test_len as usize]
.chunks(BLOCKLEN_BYTES)
.enumerate()
{
rram.write_slice(KERNEL_BASE_ADDR + i * BLOCKLEN_BYTES, &byte_chunk);
crate::println!("{:x}: {:x?}", i * BLOCKLEN_BYTES, &byte_chunk[..4]);
progress_bar(&mut sh1107, i * BLOCKLEN_BYTES * 100 / total_len);
}
progress_bar(&mut sh1107, 100);
cramium_hal::cache_flush();
crate::println!(
"data after: {:x?} .. {:x?}",
&check_slice[..32],
&check_slice[0x1000..0x1000 + 32]
);
} else if file_name.to_ascii_uppercase() == SWAP_NAME {
// This has a totally different method, as it's writing to SPI FLASH
crate::println!("Found swap image");
let f = fs.get_file(entry.path().clone()).expect("file error");
let flen = f.file_size();
let swap_offset = f.sector_offset() as usize * 512;
crate::println!("swap offset: {:x}", swap_offset);
let swap_image =
&usb::conjure_disk()[swap_offset..swap_offset + flen as usize];
let ssh: &SwapSourceHeader =
(swap_image.as_ptr() as *const SwapSourceHeader).as_ref().unwrap();
// minimal image validation - just check that the version number and magic
// number is correct.
if ssh.version == 0x01_01_0000
&& u32::from_be_bytes(swap_image[0x14..0x18].try_into().unwrap())
== 0x73776170
{
crate::println!(
"Burning swap image starting at 0x{:x} of len {} bytes",
swap_offset,
flen
);
progress_bar(&mut sh1107, 0);
let udma_global = GlobalConfig::new();
// setup the I/O pins
let iox = Iox::new(utralib::generated::HW_IOX_BASE as *mut u32);
let channel = cramium_hal::board::setup_memory_pins(&iox);
udma_global.clock_on(PeriphId::from(channel));
// safety: this is safe because clocks have been set up
let mut flash_spim = Spim::new_with_ifram(
channel,
// has to be half the clock frequency reaching the block, but
// run it as fast
// as we can run perclk
perclk / 4,
perclk / 2,
SpimClkPol::LeadingEdgeRise,
SpimClkPha::CaptureOnLeading,
SpimCs::Cs0,
0,
0,
None,
256 + 16, /* just enough space to send commands + programming
* page */
4096,
Some(6),
None,
IframRange::from_raw_parts(
SPIM_FLASH_IFRAM_ADDR,
SPIM_FLASH_IFRAM_ADDR,
4096 * 2,
),
);
flash_spim.mem_qpi_mode(true);
// NOTE: this programming routine only works for write destinations
// that start aligned to an erase page. In this case, `page_no``
// starts at 0 and increments monatomically, so, this condition is
// satisfied.
for (page_no, chunk) in swap_image.chunks(FLASH_PAGE_LEN).enumerate() {
// copy chunk to a full-page sized buffer: the last chunk may not
// be exactly a page in length, so this pads it out!
let mut buf = [0u8; 256];
buf[..chunk.len()].copy_from_slice(chunk);
// Erase the page if we're touching it the first time
if ((page_no * FLASH_PAGE_LEN) % 0x1000) == 0 {
flash_spim.flash_erase_sector((page_no * FLASH_PAGE_LEN) as u32);
}
flash_spim
.mem_flash_write_page((page_no * FLASH_PAGE_LEN) as u32, &buf);
if page_no % 32 == 0 {
progress_bar(
&mut sh1107,
page_no * FLASH_PAGE_LEN * 100 / flen as usize,
);
crate::println!(
"{:x}: write {:x?}",
page_no * FLASH_PAGE_LEN,
&buf[..16]
);
let mut rbk = [0u8; 16];
flash_spim.mem_read(
(page_no * FLASH_PAGE_LEN) as u32,
&mut rbk,
false,
);
crate::println!("rbk: {:x?}", &rbk);
}
}
progress_bar(&mut sh1107, 100);
} else {
crate::println!(
"Invalid swap image: ver {:x} magic: {:x}",
ssh.version,
u32::from_be_bytes(swap_image[0x14..0x18].try_into().unwrap())
);
gfx::msg(
&mut sh1107,
"Swap invalid!",
Point::new(6, TEXT_MIDLINE),
Mono::White.into(),
Mono::Black.into(),
);
sh1107.draw();
sh1107.clear();
return;
}
}
}
}
}
Err(e) => {
crate::println!("Couldn't list dir: {:?}", e);
}
}
// unmap IRQs
usb.stop();
} else {
crate::println!("USB core not allocated, can't do update!");
}
}
}
pub struct UsizeToString {
buf: [u8; 16], // Enough space for a u32 decimal string
pos: usize,
}
impl UsizeToString {
pub const fn new() -> Self { Self { buf: [0; 16], pos: 0 } }
pub fn as_str(&self) -> &str { core::str::from_utf8(&self.buf[..self.pos]).unwrap_or("") }
}
impl Write for UsizeToString {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
let bytes = s.as_bytes();
if self.pos + bytes.len() > self.buf.len() {
return Err(core::fmt::Error);
}
self.buf[self.pos..self.pos + bytes.len()].copy_from_slice(bytes);
self.pos += bytes.len();
Ok(())
}
}
fn progress_bar(sh1107: &mut Oled128x128<'_>, percentage: usize) {
gfx::msg(sh1107, "Writing, do not", Point::new(8, TEXT_MIDLINE), Mono::White.into(), Mono::Black.into());
gfx::msg(
sh1107,
"reset or turn off!",
Point::new(4, TEXT_MIDLINE + 14),
Mono::White.into(),
Mono::Black.into(),
);
let mut usizestr = UsizeToString::new();
write!(usizestr, "{}%", percentage).ok();
gfx::msg(
sh1107,
usizestr.as_str(),
Point::new(55, TEXT_MIDLINE + 38),
Mono::Black.into(),
Mono::White.into(),
);
sh1107.draw();
sh1107.clear();
}

View file

@ -0,0 +1,670 @@
use core::sync::atomic::Ordering;
use cramium_hal::usb::driver::CorigineUsb;
use cramium_hal::usb::driver::*;
use super::*;
// Locate the "disk"
pub(crate) const RAMDISK_ADDRESS: usize = crate::platform::HEAP_START + crate::platform::HEAP_LEN;
pub(crate) const STACK_SIZE: usize = 4096 * 16; // 64k for stack is enough? maybe? if the ramdisk overflows, it smashes stack - dangerous!
pub(crate) const RAMDISK_LEN: usize =
crate::platform::RAM_SIZE - (RAMDISK_ADDRESS - crate::platform::RAM_BASE) - STACK_SIZE;
pub(crate) const SECTOR_SIZE: u16 = 512;
// MBR template
// 0x0b~0x0C 2 bytes means block size, default 0x200 bytes
// 0x20~0x23 4 bytes means block number, default 0x400 block
#[rustfmt::skip] // keep this in 16-byte width
pub(crate) const MBR_TEMPLATE: [u8; SECTOR_SIZE as usize] = [
0xEB, 0x3C, 0x90, 0x4D, 0x53, 0x44, 0x4F, 0x53, 0x35, 0x2E, 0x30, 0x00, 0x02, 0x20, 0x06, 0x00,
0x02, 0x00, 0x02, 0x00, 0x0C, 0xF8, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x29, 0xBB, 0xBF, 0xB7, 0xB0, 0x4E, 0x4F, 0x20, 0x4E, 0x41,
0x4D, 0x45, 0x20, 0x20, 0x20, 0x20, 0x46, 0x41, 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x33, 0xC9,
0x8E, 0xD1, 0xBC, 0xF0, 0x7B, 0x8E, 0xD9, 0xB8, 0x00, 0x20, 0x8E, 0xC0, 0xFC, 0xBD, 0x00, 0x7C,
0x38, 0x4E, 0x24, 0x7D, 0x24, 0x8B, 0xC1, 0x99, 0xE8, 0x3C, 0x01, 0x72, 0x1C, 0x83, 0xEB, 0x3A,
0x66, 0xA1, 0x1C, 0x7C, 0x26, 0x66, 0x3B, 0x07, 0x26, 0x8A, 0x57, 0xFC, 0x75, 0x06, 0x80, 0xCA,
0x02, 0x88, 0x56, 0x02, 0x80, 0xC3, 0x10, 0x73, 0xEB, 0x33, 0xC9, 0x8A, 0x46, 0x10, 0x98, 0xF7,
0x66, 0x16, 0x03, 0x46, 0x1C, 0x13, 0x56, 0x1E, 0x03, 0x46, 0x0E, 0x13, 0xD1, 0x8B, 0x76, 0x11,
0x60, 0x89, 0x46, 0xFC, 0x89, 0x56, 0xFE, 0xB8, 0x20, 0x00, 0xF7, 0xE6, 0x8B, 0x5E, 0x0B, 0x03,
0xC3, 0x48, 0xF7, 0xF3, 0x01, 0x46, 0xFC, 0x11, 0x4E, 0xFE, 0x61, 0xBF, 0x00, 0x00, 0xE8, 0xE6,
0x00, 0x72, 0x39, 0x26, 0x38, 0x2D, 0x74, 0x17, 0x60, 0xB1, 0x0B, 0xBE, 0xA1, 0x7D, 0xF3, 0xA6,
0x61, 0x74, 0x32, 0x4E, 0x74, 0x09, 0x83, 0xC7, 0x20, 0x3B, 0xFB, 0x72, 0xE6, 0xEB, 0xDC, 0xA0,
0xFB, 0x7D, 0xB4, 0x7D, 0x8B, 0xF0, 0xAC, 0x98, 0x40, 0x74, 0x0C, 0x48, 0x74, 0x13, 0xB4, 0x0E,
0xBB, 0x07, 0x00, 0xCD, 0x10, 0xEB, 0xEF, 0xA0, 0xFD, 0x7D, 0xEB, 0xE6, 0xA0, 0xFC, 0x7D, 0xEB,
0xE1, 0xCD, 0x16, 0xCD, 0x19, 0x26, 0x8B, 0x55, 0x1A, 0x52, 0xB0, 0x01, 0xBB, 0x00, 0x00, 0xE8,
0x3B, 0x00, 0x72, 0xE8, 0x5B, 0x8A, 0x56, 0x24, 0xBE, 0x0B, 0x7C, 0x8B, 0xFC, 0xC7, 0x46, 0xF0,
0x3D, 0x7D, 0xC7, 0x46, 0xF4, 0x29, 0x7D, 0x8C, 0xD9, 0x89, 0x4E, 0xF2, 0x89, 0x4E, 0xF6, 0xC6,
0x06, 0x96, 0x7D, 0xCB, 0xEA, 0x03, 0x00, 0x00, 0x20, 0x0F, 0xB6, 0xC8, 0x66, 0x8B, 0x46, 0xF8,
0x66, 0x03, 0x46, 0x1C, 0x66, 0x8B, 0xD0, 0x66, 0xC1, 0xEA, 0x10, 0xEB, 0x5E, 0x0F, 0xB6, 0xC8,
0x4A, 0x4A, 0x8A, 0x46, 0x0D, 0x32, 0xE4, 0xF7, 0xE2, 0x03, 0x46, 0xFC, 0x13, 0x56, 0xFE, 0xEB,
0x4A, 0x52, 0x50, 0x06, 0x53, 0x6A, 0x01, 0x6A, 0x10, 0x91, 0x8B, 0x46, 0x18, 0x96, 0x92, 0x33,
0xD2, 0xF7, 0xF6, 0x91, 0xF7, 0xF6, 0x42, 0x87, 0xCA, 0xF7, 0x76, 0x1A, 0x8A, 0xF2, 0x8A, 0xE8,
0xC0, 0xCC, 0x02, 0x0A, 0xCC, 0xB8, 0x01, 0x02, 0x80, 0x7E, 0x02, 0x0E, 0x75, 0x04, 0xB4, 0x42,
0x8B, 0xF4, 0x8A, 0x56, 0x24, 0xCD, 0x13, 0x61, 0x61, 0x72, 0x0B, 0x40, 0x75, 0x01, 0x42, 0x03,
0x5E, 0x0B, 0x49, 0x75, 0x06, 0xF8, 0xC3, 0x41, 0xBB, 0x00, 0x00, 0x60, 0x66, 0x6A, 0x00, 0xEB,
0xB0, 0x42, 0x4F, 0x4F, 0x54, 0x4D, 0x47, 0x52, 0x20, 0x20, 0x20, 0x20, 0x0D, 0x0A, 0x52, 0x65,
0x6D, 0x6F, 0x76, 0x65, 0x20, 0x64, 0x69, 0x73, 0x6B, 0x73, 0x20, 0x6F, 0x72, 0x20, 0x6F, 0x74,
0x68, 0x65, 0x72, 0x20, 0x6D, 0x65, 0x64, 0x69, 0x61, 0x2E, 0xFF, 0x0D, 0x0A, 0x44, 0x69, 0x73,
0x6B, 0x20, 0x65, 0x72, 0x72, 0x6F, 0x72, 0xFF, 0x0D, 0x0A, 0x50, 0x72, 0x65, 0x73, 0x73, 0x20,
0x61, 0x6E, 0x79, 0x20, 0x6B, 0x65, 0x79, 0x20, 0x74, 0x6F, 0x20, 0x72, 0x65, 0x73, 0x74, 0x61,
0x72, 0x74, 0x0D, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAC, 0xCB, 0xD8, 0x55, 0xAA,
];
pub(crate) const FAT_TABLE: [u8; 0x08] = [0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F];
pub(crate) const TABLE_OFFSET_FAT1: usize = 0xC00;
pub(crate) const TABLE_OFFSET_FAT2: usize = 0xE00;
#[rustfmt::skip] // keep this in 16-byte width
pub (crate) const ROOT_DIR: [u8; 0x80] = [
0x42, 0x41, 0x4F, 0x53, 0x45, 0x43, 0x20, 0x20, 0x20, 0x20, 0x20, 0x08, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xCD, 0x78, 0x74, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42, 0x20, 0x00, 0x49, 0x00, 0x6E, 0x00, 0x66, 0x00, 0x6F, 0x00, 0x0F, 0x00, 0x72, 0x72, 0x00,
0x6D, 0x00, 0x61, 0x00, 0x74, 0x00, 0x69, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x6E, 0x00, 0x00, 0x00,
0x01, 0x53, 0x00, 0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x0F, 0x00, 0x72, 0x6D, 0x00,
0x20, 0x00, 0x56, 0x00, 0x6F, 0x00, 0x6C, 0x00, 0x75, 0x00, 0x00, 0x00, 0x6D, 0x00, 0x65, 0x00,
0x53, 0x59, 0x53, 0x54, 0x45, 0x4D, 0x7E, 0x31, 0x20, 0x20, 0x20, 0x16, 0x00, 0x36, 0xCF, 0x78,
0x74, 0x59, 0x74, 0x59, 0x00, 0x00, 0xD0, 0x78, 0x74, 0x59, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub(crate) const ROOT_DIR_OFFSET: usize = 0x1000;
#[rustfmt::skip] // keep this in 16-byte width
pub (crate) const FAT_DATA1: [u8; 0x100] = [
0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x10, 0x00, 0x36, 0xCF, 0x78,
0x74, 0x59, 0x74, 0x59, 0x00, 0x00, 0xD0, 0x78, 0x74, 0x59, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2E, 0x2E, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x10, 0x00, 0x36, 0xCF, 0x78,
0x74, 0x59, 0x74, 0x59, 0x00, 0x00, 0xD0, 0x78, 0x74, 0x59, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x42, 0x47, 0x00, 0x75, 0x00, 0x69, 0x00, 0x64, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0x01, 0x49, 0x00, 0x6E, 0x00, 0x64, 0x00, 0x65, 0x00, 0x78, 0x00, 0x0F, 0x00, 0xFF, 0x65, 0x00,
0x72, 0x00, 0x56, 0x00, 0x6F, 0x00, 0x6C, 0x00, 0x75, 0x00, 0x00, 0x00, 0x6D, 0x00, 0x65, 0x00,
0x49, 0x4E, 0x44, 0x45, 0x58, 0x45, 0x7E, 0x31, 0x20, 0x20, 0x20, 0x20, 0x00, 0x4E, 0xCF, 0x78,
0x74, 0x59, 0x74, 0x59, 0x00, 0x00, 0xD0, 0x78, 0x74, 0x59, 0x03, 0x00, 0x4C, 0x00, 0x00, 0x00,
0x42, 0x74, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x00, 0xCE, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0x01, 0x57, 0x00, 0x50, 0x00, 0x53, 0x00, 0x65, 0x00, 0x74, 0x00, 0x0F, 0x00, 0xCE, 0x74, 0x00,
0x69, 0x00, 0x6E, 0x00, 0x67, 0x00, 0x73, 0x00, 0x2E, 0x00, 0x00, 0x00, 0x64, 0x00, 0x61, 0x00,
0x57, 0x50, 0x53, 0x45, 0x54, 0x54, 0x7E, 0x31, 0x44, 0x41, 0x54, 0x20, 0x00, 0xB5, 0xD8, 0x78,
0x74, 0x59, 0x74, 0x59, 0x00, 0x00, 0xD9, 0x78, 0x74, 0x59, 0x04, 0x00, 0x0C, 0x00, 0x00, 0x00,
];
pub(crate) const FAT_DATA1_OFFSET: usize = 0x5000;
#[rustfmt::skip] // keep this in 16-byte width
pub(crate) const FAT_DATA2: [u8; 0x50] = [
0x7B, 0x00, 0x34, 0x00, 0x33, 0x00, 0x39, 0x00, 0x44, 0x00, 0x41, 0x00, 0x31, 0x00, 0x32, 0x00,
0x44, 0x00, 0x2D, 0x00, 0x37, 0x00, 0x33, 0x00, 0x42, 0x00, 0x39, 0x00, 0x2D, 0x00, 0x34, 0x00,
0x43, 0x00, 0x41, 0x00, 0x34, 0x00, 0x2D, 0x00, 0x38, 0x00, 0x38, 0x00, 0x46, 0x00, 0x39, 0x00,
0x2D, 0x00, 0x44, 0x00, 0x41, 0x00, 0x32, 0x00, 0x43, 0x00, 0x46, 0x00, 0x33, 0x00, 0x31, 0x00,
0x38, 0x00, 0x45, 0x00, 0x32, 0x00, 0x37, 0x00, 0x35, 0x00, 0x7D, 0x00, 0x00, 0x00, 0x00, 0x00,
];
pub(crate) const FAT_DATA2_OFFSET: usize = 0x9000;
#[rustfmt::skip] // keep this in 16-byte width
pub(crate) const FAT_DATA3: [u8; 0x10] = [
0x0C, 0x00, 0x00, 0x00, 0x28, 0x34, 0x07, 0x9C, 0x7C, 0xBD, 0x65, 0xF9, 0x00, 0x00, 0x00, 0x00,
];
pub(crate) const FAT_DATA3_OFFSET: usize = 0xD000;
pub(crate) const CSW_ADDR: usize = CRG_UDC_MEMBASE + CRG_UDC_APP_BUFOFFSET + CRG_UDC_APP_BUF_LEN;
pub(crate) const CBW_ADDR: usize = CRG_UDC_MEMBASE + CRG_UDC_APP_BUFOFFSET;
pub(crate) const EP1_IN_BUF: usize = CRG_UDC_MEMBASE + CRG_UDC_APP_BUFOFFSET + 1024;
pub(crate) const EP1_IN_BUF_LEN: usize = 1024;
#[allow(dead_code)]
pub(crate) const EP1_OUT_BUF: usize = CRG_UDC_MEMBASE + CRG_UDC_APP_BUFOFFSET + 2048;
#[allow(dead_code)]
pub(crate) const EP1_OUT_BUF_LEN: usize = 1024;
pub(crate) const MASS_STORAGE_EPADDR_IN: u8 = 0x81;
pub(crate) const MASS_STORAGE_EPADDR_OUT: u8 = 0x01;
pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) {
this.ep_enable(ep_num, USB_RECV, 64, EpType::BulkOutbound);
this.ep_enable(ep_num, USB_SEND, 64, EpType::BulkInbound);
}
pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) {
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
CRG_UDC_EP0_REQBUFSIZE,
)
};
match (value >> 8) as u8 {
USB_DT_DEVICE => {
crate::println!("USB_DT_DEVICE");
let mut device_descriptor = DeviceDescriptor::default_mass_storage();
device_descriptor.b_max_packet_size0 = 64;
device_descriptor.b_cd_usb = 0x0210;
let len = length.min(core::mem::size_of::<DeviceDescriptor>());
ep0_buf[..len].copy_from_slice(&device_descriptor.as_ref()[..len]);
// crate::println!("ptr: {:x}, len: {}", this.ep0_buf.load(Ordering::SeqCst) as usize, len);
// crate::println!("dd: {:x?}", device_descriptor.as_ref());
// crate::println!("buf: {:x?}", &ep0_buf[..len]);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, len, 0);
}
USB_DT_DEVICE_QUALIFIER => {
crate::println!("USB_DT_DEVICE_QUALIFIER");
let qualifier_descriptor = QualifierDescriptor::default_mass_storage();
let len = length.min(core::mem::size_of::<QualifierDescriptor>());
ep0_buf[..len].copy_from_slice(&qualifier_descriptor.as_ref()[..len]);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, len, 0);
}
USB_DT_OTHER_SPEED_CONFIG => {
crate::println!("USB_DT_OTHER_SPEED_CONFIG\r\n");
crate::println!("*** UNHANDLED ***");
}
USB_DT_CONFIG => {
crate::println!("USB_DT_CONFIG");
let total_length = size_of::<ConfigDescriptor>()
+ size_of::<InterfaceDescriptor>()
+ size_of::<EndpointDescriptor>() * 2;
let config = ConfigDescriptor::default_mass_storage(total_length as u16);
let interface = InterfaceDescriptor::default_mass_storage();
let ep_in = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_IN, 64);
let ep_out = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_OUT, 64);
let response: [&[u8]; 4] = [config.as_ref(), interface.as_ref(), ep_in.as_ref(), ep_out.as_ref()];
let flattened = response.iter().flat_map(|slice| slice.iter().copied());
for (dst, src) in ep0_buf.iter_mut().zip(flattened) {
*dst = src
}
let buffsize = total_length.min(length);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
}
USB_DT_STRING => {
let id = (value & 0xFF) as u8;
crate::println!("USB_DT_STRING {}", id);
let len = if id == 0 {
// index 0 is the language type. This is the hard-coded response for "English".
ep0_buf[..4].copy_from_slice(&[4, USB_DT_STRING, 9, 4]);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, 4, 0);
4
} else {
let s = match id {
1 => MANUFACTURER,
2 => PRODUCT,
_ => SERIAL,
};
// strings are utf16-le encoded words. Manually pack them.
let len = 2 + s.len() * 2; // 2 bytes for header + string data
ep0_buf[0] = len as u8;
ep0_buf[1] = USB_DT_STRING;
// this code fails if the string isn't simple ASCII. Yes, we could
// embed idk unicode emoji if I coded this better, but I ask you, WHY‽
for (dst, &src) in ep0_buf[2..].chunks_exact_mut(2).zip(s.as_bytes()) {
dst.copy_from_slice(&(src as u16).to_le_bytes());
}
len
};
let buffsize = length.min(len);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
}
USB_DT_BOS => {
crate::println!("USB_DT_BOS");
let total_length = size_of::<BosDescriptor>() + size_of::<ExtCapDescriptor>();
let bos = BosDescriptor::default_mass_storage(total_length as u16, 1);
let ext = ExtCapDescriptor::default_mass_storage((0xfa << 8) | (0x3 << 3));
let response: [&[u8]; 2] = [bos.as_ref(), ext.as_ref()];
let flattened = response.iter().flat_map(|slice| slice.iter().copied());
for (dst, src) in ep0_buf.iter_mut().zip(flattened) {
*dst = src
}
let buffsize = total_length.min(length);
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
}
_ => {
crate::println!("UNHANDLED SETUP: 0x{:x}", value >> 8);
this.ep_halt(0, USB_RECV);
}
}
}
pub fn usb_ep1_bulk_out_complete(this: &mut CorigineUsb, buf_addr: usize, info: u32, _error: u8) {
let length = info & 0xFFFF;
let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, info as usize & 0xFFFF) };
let mut cbw = Cbw::default();
cbw.as_mut().copy_from_slice(&buf[..size_of::<Cbw>()]);
let mut csw = Csw::derive();
if UmsState::CommandPhase == this.ms_state && (length == 31) {
// CBW
if cbw.signature == BULK_CBW_SIG {
csw.signature = BULK_CSW_SIG;
csw.tag = cbw.tag;
csw.update_hw();
process_mass_storage_command(this, cbw);
// invalid_cbw = 0;
} else {
crate::println!("Invalid CBW, HALT");
this.ep_halt(1, USB_SEND);
this.ep_halt(1, USB_RECV);
// invalid_cbw = 1;
}
} else if UmsState::CommandPhase == this.ms_state && (length != 31) {
crate::println!("invalid command");
this.ep_halt(1, USB_SEND);
this.ep_halt(1, USB_RECV);
// invalid_cbw = 1;
} else if UmsState::DataPhase == this.ms_state {
crate::println!("data");
//DATA
if let Some((write_offset, len)) = this.callback_wr.take() {
let app_buf = conjure_app_buf();
let disk = conjure_disk();
// update the received data to the disk
disk[write_offset..write_offset + len].copy_from_slice(&app_buf[..len]);
if let Some((offset, remaining_len)) = this.remaining_wr.take() {
this.setup_big_write(app_buf_addr(), app_buf_len(), offset, remaining_len);
this.ms_state = UmsState::DataPhase;
csw.update_hw();
} else {
csw.residue = 0;
csw.status = 0;
csw.send(this);
}
} else {
crate::println!("Data completion reached without destination for data copy! data dropped.");
}
} else {
crate::println!("uhhh wtf");
}
}
pub fn usb_ep1_bulk_in_complete(this: &mut CorigineUsb, _buf_addr: usize, info: u32, _error: u8) {
// crate::println!("bulk IN handler");
let length = info & 0xFFFF;
if UmsState::DataPhase == this.ms_state {
//DATA
if let Some((offset, len)) = this.remaining_rd.take() {
let app_buf = conjure_app_buf();
let disk = conjure_disk();
this.setup_big_read(app_buf, disk, offset, len);
this.ms_state = UmsState::DataPhase;
} else {
this.bulk_xfer(1, USB_SEND, CSW_ADDR, 13, 0, 0);
this.ms_state = UmsState::StatusPhase;
}
} else if UmsState::StatusPhase == this.ms_state && length == 13 {
//CSW
this.bulk_xfer(1, USB_RECV, CBW_ADDR, 31, 0, 0);
this.ms_state = UmsState::CommandPhase;
}
}
fn process_mass_storage_command(this: &mut CorigineUsb, cbw: Cbw) {
match cbw.cdb[0] {
0x00 => { /* Request the device to report if it is ready */
process_test_unit_ready(this, cbw);
}
0x03 => { /* Transfer status sense data to the host */
process_request_sense(this, cbw);
}
0x12 => { /* Inquity command. Get device information */
process_inquiry_command(this, cbw);
}
0x1E => { /* Prevent or allow the removal of media from a removable
** media device
*/
process_prevent_allow_medium_removal(this, cbw);
}
0x25 => { /* Report current media capacity */
process_report_capacity(this, cbw);
}
0x9e => {
process_read_capacity_16(this, cbw);
}
0x28 => { /* Read (10) Transfer binary data from media to the host */
process_read_command(this, cbw);
}
0x2A => { /* Write (10) Transfer binary data from the host to the
** media
*/
process_write_command(this, cbw);
}
0xAA => { /* Write (12) Transfer binary data from the host to the
** media
*/
process_write12_command(this, cbw);
}
0x01 | /* Position a head of the drive to zero track */
0x04 | /* Format unformatted media */
0x1A |
0x1B | /* Request a request a removable-media device to load or
** unload its media
*/
0x1D | /* Perform a hard reset and execute diagnostics */
0x23 | /* Read Format Capacities. Report current media capacity and
** formattable capacities supported by media
*/
0x2B | /* Seek the device to a specified address */
0x2E | /* Transfer binary data from the host to the media and
** verify data
*/
0x2F | /* Verify data on the media */
0x55 | /* Allow the host to set parameters in a peripheral */
0x5A | /* Report parameters to the host */
0xA8 /* Read (12) Transfer binary data from the media to the host */ => {
process_unsupported_command(this, cbw);
}
_ => {
process_unsupported_command(this, cbw);
}
}
}
fn process_test_unit_ready(this: &mut CorigineUsb, _cbw: Cbw) {
let mut csw = Csw::derive();
csw.residue = 0;
csw.status = 0;
csw.send(this);
}
fn process_request_sense(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
if cbw.data_transfer_length == 0 {
csw.residue = 0;
csw.status = 0;
csw.send(this);
// crate::println!("UMS_STATE_STATUS_PHASE\r\n");
} else if cbw.flags & 0x80 != 0 {
if cbw.data_transfer_length < 18 {
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..18].fill(0);
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, cbw.data_transfer_length as usize, 0, 0);
this.ms_state = UmsState::DataPhase;
csw.residue = 0;
csw.status = 0;
} else if cbw.data_transfer_length >= 18 {
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..18].fill(0);
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 18, 0, 0);
this.ms_state = UmsState::DataPhase;
csw.residue = cbw.data_transfer_length - 18;
csw.status = 0;
}
}
csw.update_hw();
}
fn process_inquiry_command(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
let inquiry_data = InquiryResponse {
peripheral_device_type: 0,
rmb: 0,
version: 0,
response_data_format: 1,
additional_length: 31,
reserved1: 0,
reserved2: 0,
reserved3: 0,
vendor_identification: *b"Bao Semi",
product_identification: *b"USB update vdisk",
product_revision_level: *b"demo",
};
if cbw.data_transfer_length == 0 {
csw.residue = 0;
csw.status = 0;
csw.send(this);
} else if cbw.flags & 0x80 != 0 {
if cbw.data_transfer_length < 36 {
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..36].fill(0);
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, cbw.data_transfer_length as usize, 0, 0);
this.ms_state = UmsState::DataPhase;
csw.residue = 0;
csw.status = 0;
} else if cbw.data_transfer_length as usize >= size_of::<InquiryResponse>() {
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..size_of::<InquiryResponse>()].copy_from_slice(inquiry_data.as_ref());
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, size_of::<InquiryResponse>(), 0, 0);
this.ms_state = UmsState::DataPhase;
csw.residue = cbw.data_transfer_length - size_of::<InquiryResponse>() as u32;
csw.status = 0;
}
}
csw.update_hw();
}
fn process_prevent_allow_medium_removal(this: &mut CorigineUsb, _cbw: Cbw) {
let mut csw = Csw::derive();
csw.residue = 0;
csw.status = 0;
csw.send(this);
}
fn process_report_capacity(this: &mut CorigineUsb, cbw: Cbw) {
crate::println!("REPORT CAPACITY");
let mut csw = Csw::derive();
let rc_lba = RAMDISK_LEN / SECTOR_SIZE as usize - 1;
let rc_bl: u32 = SECTOR_SIZE as u32;
let mut capacity = [0u8; 8];
capacity[..4].copy_from_slice(&rc_lba.to_be_bytes());
capacity[4..].copy_from_slice(&rc_bl.to_be_bytes());
if cbw.flags & 0x80 != 0 {
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..8].fill(0);
ep1_in[..8].copy_from_slice(&capacity);
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 8, 0, 0);
this.ms_state = UmsState::DataPhase;
} else {
csw.send(this);
}
csw.residue = 0;
csw.status = 0;
csw.update_hw();
}
fn process_read_capacity_16(this: &mut CorigineUsb, _cbw: Cbw) {
let rc_lba = (RAMDISK_LEN / SECTOR_SIZE as usize - 1) as u64;
let rc_bl: u32 = SECTOR_SIZE as u32;
let mut response = [0u8; 32];
response[..8].copy_from_slice(&rc_lba.to_be_bytes());
response[8..12].copy_from_slice(&rc_bl.to_be_bytes());
let ep1_in = unsafe { core::slice::from_raw_parts_mut(EP1_IN_BUF as *mut u8, EP1_IN_BUF_LEN) };
ep1_in[..32].copy_from_slice(&response);
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 32, 0, 0);
this.ms_state = UmsState::DataPhase;
}
fn process_unsupported_command(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
csw.residue = 0;
csw.status = 0;
if cbw.flags & 0x80 != 0 {
this.bulk_xfer(1, USB_SEND, EP1_IN_BUF, 0, 0, 0);
this.ms_state = UmsState::DataPhase;
} else {
csw.send(this);
}
csw.update_hw();
}
fn process_read_command(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
let mut lba;
let mut length;
lba = (cbw.cdb[4] as u32) << 8;
lba |= cbw.cdb[5] as u32;
length = (cbw.cdb[7] as u32) << 8;
length |= cbw.cdb[8] as u32;
length *= SECTOR_SIZE as u32;
if cbw.flags & 0x80 == 0 {
csw.residue = cbw.data_transfer_length;
csw.status = 2;
this.setup_big_write(
app_buf_addr(),
app_buf_len(),
lba as usize * SECTOR_SIZE as usize,
length as usize,
);
this.ms_state = UmsState::DataPhase;
return;
}
crate::println!(
"DISK READ address = 0x{:x}, length = 0x{:x}",
RAMDISK_ADDRESS + lba as usize * SECTOR_SIZE as usize,
length
);
if cbw.data_transfer_length == 0 {
csw.residue = 0;
csw.status = 2;
csw.send(this);
} else {
csw.residue = 0;
csw.status = 0;
if cbw.data_transfer_length < length {
length = cbw.data_transfer_length;
csw.residue = cbw.data_transfer_length;
csw.status = 1;
} else if cbw.data_transfer_length > length {
csw.residue = cbw.data_transfer_length - length;
csw.status = 1;
}
let app_buf = conjure_app_buf();
let disk = conjure_disk();
this.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize);
this.ms_state = UmsState::DataPhase;
}
}
fn process_write_command(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
let mut lba: u32;
let mut length: u32;
lba = (cbw.cdb[4] as u32) << 8;
lba |= cbw.cdb[5] as u32;
length = (cbw.cdb[7] as u32) << 8;
length |= cbw.cdb[8] as u32;
length *= SECTOR_SIZE as u32;
if cbw.flags & 0x80 != 0 {
csw.residue = cbw.data_transfer_length;
csw.status = 2;
let app_buf = conjure_app_buf();
let disk = conjure_disk();
this.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize);
this.ms_state = UmsState::DataPhase;
csw.update_hw();
return;
}
crate::println!(
"Write address = 0x{:x}, length = 0x{:x}",
RAMDISK_ADDRESS + lba as usize * SECTOR_SIZE as usize,
length
);
if cbw.data_transfer_length == 0 {
csw.residue = 0;
csw.status = 2;
csw.send(this);
} else {
csw.residue = 0;
csw.status = 0;
if cbw.data_transfer_length > length {
csw.residue = cbw.data_transfer_length - length;
length = cbw.data_transfer_length;
csw.status = 1;
} else if cbw.data_transfer_length < length {
csw.residue = cbw.data_transfer_length;
csw.status = 1;
length = cbw.data_transfer_length;
}
this.setup_big_write(
app_buf_addr(),
app_buf_len(),
lba as usize * SECTOR_SIZE as usize,
length as usize,
);
this.ms_state = UmsState::DataPhase;
}
csw.update_hw();
}
fn process_write12_command(this: &mut CorigineUsb, cbw: Cbw) {
let mut csw = Csw::derive();
let mut lba;
let mut length;
lba = (cbw.cdb[2] as u32) << 24;
lba |= (cbw.cdb[3] as u32) << 16;
lba |= (cbw.cdb[4] as u32) << 8;
lba |= (cbw.cdb[5] as u32) << 0;
length = (cbw.cdb[6] as u32) << 24;
length |= (cbw.cdb[7] as u32) << 16;
length |= (cbw.cdb[8] as u32) << 8;
length |= (cbw.cdb[9] as u32) << 0;
length *= SECTOR_SIZE as u32;
crate::println!("write12 of {} bytes", length);
if cbw.flags & 0x80 != 0 {
csw.residue = cbw.data_transfer_length;
csw.status = 2;
// note: zero-length transfer but we still update the buffer because that's what the reference driver
// does
let app_buf = conjure_app_buf();
let disk = conjure_disk();
this.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize);
this.ms_state = UmsState::DataPhase;
csw.update_hw();
return;
}
if cbw.data_transfer_length == 0 {
csw.residue = 0;
csw.status = 2;
csw.send(this);
return;
} else {
csw.residue = 0;
csw.status = 0;
if cbw.data_transfer_length > length {
csw.residue = cbw.data_transfer_length - length;
length = cbw.data_transfer_length;
} else if cbw.data_transfer_length < length {
csw.residue = cbw.data_transfer_length;
csw.status = 2;
length = cbw.data_transfer_length;
}
this.setup_big_write(
app_buf_addr(),
app_buf_len(),
lba as usize * SECTOR_SIZE as usize,
length as usize,
);
this.ms_state = UmsState::DataPhase;
}
csw.update_hw();
}
// the 1024 is reserved for the CSW/CBW records
pub(crate) fn app_buf_addr() -> usize { CRG_UDC_MEMBASE + CRG_UDC_APP_BUFOFFSET + 1024 }
// the length subtracts the reserved 1024, and adds one page as a hack for testing - TODO: fix that
pub(crate) fn app_buf_len() -> usize { CRG_UDC_APP_BUFSIZE - 1024 + 4096 }
pub(crate) fn conjure_app_buf() -> &'static mut [u8] {
unsafe { core::slice::from_raw_parts_mut(app_buf_addr() as *mut u8, app_buf_len()) } // added +1 page in CRG_UDC_MEMBASE
}
pub(crate) fn conjure_disk() -> &'static mut [u8] {
unsafe { core::slice::from_raw_parts_mut(RAMDISK_ADDRESS as *mut u8, RAMDISK_LEN) }
}

View file

@ -0,0 +1,486 @@
mod driver;
pub mod glue;
mod mass_storage;
mod sha512_digest;
mod slice_cursor;
pub use driver::*;
pub use mass_storage::*;
pub use slice_cursor::*;
use crate::irq::*;
// Note that the trap handler is just placed one page below this, and it
// needs to be manually updated in the assembly because we can't refer to
// consts in that snippet of assembly. That handler also needs a default
// stack area, which is right below that spare page.
const SCRATCH_PAGE: usize = RAMDISK_ADDRESS - 4096;
#[allow(dead_code)] // this reminds us there are two places this has to be changed in assembly-land
const EXCEPTION_STACK: usize = SCRATCH_PAGE;
const USB_TYPE_MASK: u8 = 0x03 << 5;
const USB_TYPE_STANDARD: u8 = 0x00 << 5;
const USB_TYPE_CLASS: u8 = 0x01 << 5;
#[allow(dead_code)]
const USB_TYPE_VENDOR: u8 = 0x02 << 5;
#[allow(dead_code)]
const USB_TYPE_RESERVED: u8 = 0x03 << 5;
/*
* USB recipients, the third of three bRequestType fields
*/
#[allow(dead_code)]
const USB_RECIP_MASK: u8 = 0x1f;
const USB_RECIP_DEVICE: u8 = 0x00;
const USB_RECIP_INTERFACE: u8 = 0x01;
const USB_RECIP_ENDPOINT: u8 = 0x02;
#[allow(dead_code)]
const USB_RECIP_OTHER: u8 = 0x03;
const USB_REQ_GET_STATUS: u8 = 0x00;
const USB_REQ_CLEAR_FEATURE: u8 = 0x01;
const USB_REQ_SET_FEATURE: u8 = 0x03;
const USB_REQ_SET_ADDRESS: u8 = 0x05;
const USB_REQ_GET_DESCRIPTOR: u8 = 0x06;
#[allow(dead_code)]
const USB_REQ_SET_DESCRIPTOR: u8 = 0x07;
const USB_REQ_GET_CONFIGURATION: u8 = 0x08;
const USB_REQ_SET_CONFIGURATION: u8 = 0x09;
const USB_REQ_GET_INTERFACE: u8 = 0x0A;
const USB_REQ_SET_INTERFACE: u8 = 0x0B;
#[allow(dead_code)]
const USB_REQ_SYNCH_FRAME: u8 = 0x0C;
const USB_REQ_SET_SEL: u8 = 0x30;
const USB_REQ_SET_ISOCH_DELAY: u8 = 0x31;
const USB_DT_DEVICE: u8 = 0x01;
const USB_DT_CONFIG: u8 = 0x02;
const USB_DT_STRING: u8 = 0x03;
#[allow(dead_code)]
const USB_DT_INTERFACE: u8 = 0x04;
const USB_DT_ENDPOINT: u8 = 0x05;
const USB_DT_DEVICE_QUALIFIER: u8 = 0x06;
const USB_DT_OTHER_SPEED_CONFIG: u8 = 0x07;
#[allow(dead_code)]
const USB_DT_INTERFACE_POWER: u8 = 0x08;
/* these are from a minor usb 2.0 revision (ECN) */
#[allow(dead_code)]
const USB_DT_OTG: u8 = 0x09;
#[allow(dead_code)]
const USB_DT_DEVICE_CAPABILITY: u8 = 0x10;
#[allow(dead_code)]
const USB_DT_DEBUG: u8 = 0x0a;
#[allow(dead_code)]
const USB_DT_INTERFACE_ASSOCIATION: u8 = 0x0b;
#[allow(dead_code)]
const USB_DT_BOS: u8 = 0x0f;
/* From the T10 UAS specification */
#[allow(dead_code)]
const USB_DT_PIPE_USAGE: u8 = 0x24;
/* From the USB 3.0 spec */
#[allow(dead_code)]
const USB_DT_SS_ENDPOINT_COMP: u8 = 0x30;
/* From the USB 3.1 spec */
#[allow(dead_code)]
const USB_DT_SSP_ISOC_ENDPOINT_COMP: u8 = 0x31;
const USB_CAP_TYPE_EXT: u8 = 0x2;
#[allow(dead_code)]
#[repr(C, packed)]
struct DeviceDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub b_cd_usb: u16,
pub b_device_class: u8,
pub b_device_sub_class: u8,
pub b_device_protocol: u8,
pub b_max_packet_size0: u8,
pub id_vendor: u16,
pub id_product: u16,
pub b_cd_device: u16,
pub i_manufacturer: u8,
pub i_product: u8,
pub i_serial_number: u8,
pub b_num_configurations: u8,
}
const VENDOR_ID: u16 = 0x1209;
const PRODUCT_ID: u16 = 0x3613; // this needs to change! this is the Precursor product ID.
const MANUFACTURER: &'static str = "Bao Semi";
const PRODUCT: &'static str = "SecuriBao";
// no seriously, do this
const SERIAL: &'static str = "TODO";
impl DeviceDescriptor {
pub fn default_mass_storage() -> Self {
Self {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_DEVICE,
b_cd_usb: 0x0200,
b_device_class: 0,
b_device_sub_class: 0,
b_device_protocol: 0,
b_max_packet_size0: 0x40,
id_vendor: VENDOR_ID,
id_product: PRODUCT_ID,
b_cd_device: 0x0101,
i_manufacturer: 0x01, // string index for manufacturer
i_product: 0x02, // string index for product
i_serial_number: 0x03, // string index for serial number
b_num_configurations: 1,
}
}
}
impl AsRef<[u8]> for DeviceDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const DeviceDescriptor as *const u8,
core::mem::size_of::<DeviceDescriptor>(),
) as &[u8]
}
}
}
/* USB_DT_DEVICE_QUALIFIER: Device Qualifier descriptor */
#[allow(dead_code)]
#[repr(C, packed)]
struct QualifierDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub b_cd_usb: u16,
pub b_device_class: u8,
pub b_device_sub_class: u8,
pub b_device_protocol: u8,
pub b_max_packet_size0: u8,
pub b_num_configurations: u8,
pub b_reserved: u8,
}
impl QualifierDescriptor {
pub fn default_mass_storage() -> Self {
Self {
b_length: 0xA,
b_descriptor_type: 0x6,
b_cd_usb: 0x200,
b_device_class: 0x0,
b_device_sub_class: 0x0,
b_device_protocol: 0x0,
b_max_packet_size0: 0x40,
b_num_configurations: 0x1,
b_reserved: 0x0,
}
}
}
impl AsRef<[u8]> for QualifierDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const QualifierDescriptor as *const u8,
core::mem::size_of::<QualifierDescriptor>(),
) as &[u8]
}
}
}
#[allow(dead_code)]
#[repr(C, packed)]
struct ConfigDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub w_total_length: u16,
pub b_num_interfaces: u8,
pub b_configuration_value: u8,
pub i_configuration: u8,
pub bm_attributes: u8,
pub b_max_power: u8,
}
impl ConfigDescriptor {
pub fn default_mass_storage(total_length: u16) -> Self {
ConfigDescriptor {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_CONFIG,
w_total_length: total_length,
b_num_interfaces: 1,
b_configuration_value: 1,
i_configuration: 0x0,
bm_attributes: 0xC0,
b_max_power: 250,
}
}
}
impl AsRef<[u8]> for ConfigDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const ConfigDescriptor as *const u8,
core::mem::size_of::<ConfigDescriptor>(),
) as &[u8]
}
}
}
#[allow(dead_code)]
#[repr(C, packed)]
struct InterfaceDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub b_interface_number: u8,
pub b_alternate_setting: u8,
pub b_num_endpoints: u8,
pub b_interface_class: u8,
pub b_interface_sub_class: u8,
pub b_interface_protocol: u8,
pub i_interface: u8,
}
impl InterfaceDescriptor {
pub fn default_mass_storage() -> Self {
InterfaceDescriptor {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_INTERFACE,
b_interface_number: 0,
b_alternate_setting: 0,
b_num_endpoints: 2,
b_interface_class: 0x08, // mass storage class
b_interface_sub_class: 0x06,
b_interface_protocol: 0x50,
i_interface: 0x0,
}
}
}
impl AsRef<[u8]> for InterfaceDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const InterfaceDescriptor as *const u8,
core::mem::size_of::<InterfaceDescriptor>(),
) as &[u8]
}
}
}
#[allow(dead_code)]
#[repr(C, packed)]
struct EndpointDescriptor {
b_length: u8,
b_descriptor_type: u8,
b_endpoint_address: u8,
b_m_attributes: u8,
w_max_packet_size: u16,
b_interval: u8,
}
impl EndpointDescriptor {
pub fn default_mass_storage(addr: u8, max_packet_size: u16) -> Self {
EndpointDescriptor {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_ENDPOINT,
b_endpoint_address: addr,
b_m_attributes: 0x02,
w_max_packet_size: max_packet_size,
b_interval: 0x0,
}
}
}
impl AsRef<[u8]> for EndpointDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const EndpointDescriptor as *const u8,
core::mem::size_of::<EndpointDescriptor>(),
) as &[u8]
}
}
}
#[repr(C, packed)]
#[derive(Default)]
struct CtrlRequest {
b_request_type: u8,
b_request: u8,
w_value: u16,
w_index: u16,
w_length: u16,
}
impl AsMut<[u8]> for CtrlRequest {
fn as_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(
self as *const CtrlRequest as *mut u8,
core::mem::size_of::<CtrlRequest>(),
) as &mut [u8]
}
}
}
#[allow(dead_code)]
#[repr(C, packed)]
struct BosDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub w_total_length: u16,
pub b_num_device_caps: u8,
}
impl BosDescriptor {
pub fn default_mass_storage(total_length: u16, num_caps: u8) -> Self {
BosDescriptor {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_BOS,
w_total_length: total_length,
b_num_device_caps: num_caps,
}
}
}
impl AsRef<[u8]> for BosDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const BosDescriptor as *const u8,
core::mem::size_of::<BosDescriptor>(),
) as &[u8]
}
}
}
#[allow(dead_code)]
#[repr(C, packed)]
struct ExtCapDescriptor {
pub b_length: u8,
pub b_descriptor_type: u8,
pub b_dev_capability_type: u8,
pub b_mattributes: u32,
}
impl ExtCapDescriptor {
pub fn default_mass_storage(attributes: u32) -> Self {
ExtCapDescriptor {
b_length: core::mem::size_of::<Self>() as u8,
b_descriptor_type: USB_DT_DEVICE_CAPABILITY,
b_dev_capability_type: USB_CAP_TYPE_EXT,
b_mattributes: attributes,
}
}
}
impl AsRef<[u8]> for ExtCapDescriptor {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const ExtCapDescriptor as *const u8,
core::mem::size_of::<ExtCapDescriptor>(),
) as &[u8]
}
}
}
#[allow(dead_code)]
pub(crate) const USB_LPM_SUPPORT: u8 = 1 << 1; /* supports LPM */
#[allow(dead_code)]
pub(crate) const USB_BESL_SUPPORT: u8 = 1 << 2; /* supports BESL */
#[allow(dead_code)]
pub(crate) const USB_BESL_BASELINE_VALID: u8 = 1 << 3; /* Baseline BESL valid*/
#[allow(dead_code)]
pub(crate) const USB_BESL_DEEP_VALID: u8 = 1 << 4; /* Deep BESL valid */
#[repr(C, packed)]
#[derive(Default, Debug)]
struct Cbw {
signature: u32, // Contains 'USBC'
tag: u32, // Unique per command id
data_transfer_length: u32, // Size of the data
flags: u8, // Direction in bit 7
lun: u8, // LUN (normally 0)
length: u8, // Of the CDB, <= MAX_COMMAND_SIZE
cdb: [u8; 16], // Command Data Block
}
impl AsMut<[u8]> for Cbw {
fn as_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut Cbw as *mut u8, core::mem::size_of::<Cbw>())
as &mut [u8]
}
}
}
impl AsRef<[u8]> for Cbw {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(self as *const Cbw as *const u8, core::mem::size_of::<Cbw>())
as &[u8]
}
}
}
const BULK_CBW_SIG: u32 = 0x43425355; /* Spells out USBC */
#[repr(C, packed)]
#[derive(Default)]
struct Csw {
pub signature: u32, // Should = 'USBS'
pub tag: u32, // Same as original command
pub residue: u32, // Amount not transferred
pub status: u8, // See below
}
impl Csw {
fn derive() -> Csw {
let mut csw = Csw::default();
csw.as_mut().copy_from_slice(unsafe {
core::slice::from_raw_parts(mass_storage::CSW_ADDR as *mut u8, size_of::<Csw>())
});
csw
}
fn update_hw(&self) {
let csw_buf = unsafe { core::slice::from_raw_parts_mut(CSW_ADDR as *mut u8, size_of::<Csw>()) };
csw_buf.copy_from_slice(self.as_ref());
}
fn send(&self, usb: &mut cramium_hal::usb::driver::CorigineUsb) {
let csw_buf = unsafe { core::slice::from_raw_parts_mut(CSW_ADDR as *mut u8, size_of::<Csw>()) };
csw_buf.copy_from_slice(self.as_ref());
usb.bulk_xfer(1, cramium_hal::usb::driver::USB_SEND, CSW_ADDR, size_of::<Csw>(), 0, 0);
usb.ms_state = cramium_hal::usb::driver::UmsState::StatusPhase;
}
}
const BULK_CSW_SIG: u32 = 0x53425355; /* Spells out 'USBS' */
impl AsRef<[u8]> for Csw {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(self as *const Csw as *const u8, core::mem::size_of::<Csw>())
as &[u8]
}
}
}
impl AsMut<[u8]> for Csw {
fn as_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(self as *mut Csw as *mut u8, core::mem::size_of::<Csw>())
as &mut [u8]
}
}
}
#[repr(C, packed)]
struct InquiryResponse {
pub peripheral_device_type: u8, // Byte 0: Peripheral Device Type (PDT)
pub rmb: u8, // Byte 1: Removable Media Bit (RMB) and Device Type Modifier
pub version: u8, // Byte 2: ISO/ECMA/ANSI Version
pub response_data_format: u8, // Byte 3: Response Data Format (RDF) and capabilities
pub additional_length: u8, // Byte 4: Additional Length (number of bytes after byte 7)
pub reserved1: u8, // Byte 5: Reserved
pub reserved2: u8, // Byte 6: Reserved
pub reserved3: u8, // Byte 7: Reserved
pub vendor_identification: [u8; 8], // Byte 8-15: Vendor Identification (ASCII)
pub product_identification: [u8; 16], // Byte 16-31: Product Identification (ASCII)
pub product_revision_level: [u8; 4], // Byte 32-35: Product Revision Level (ASCII)
}
impl AsRef<[u8]> for InquiryResponse {
fn as_ref(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
self as *const InquiryResponse as *const u8,
core::mem::size_of::<InquiryResponse>(),
) as &[u8]
}
}
}

View file

@ -0,0 +1,85 @@
use core::fmt;
use digest::{
FixedOutput, HashMarker, InvalidOutputSize, Output, Update,
block_buffer::Eager,
core_api::{
AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, OutputSizeUser, TruncSide, UpdateCore,
VariableOutputCore,
},
typenum::{U64, U128},
};
/// Wrap a pre-hash value in a Digest trait
#[derive(Clone)]
pub struct Sha512Prehash {
/// track the length of the message processed so far
hash: Option<[u8; 64]>,
}
impl Sha512Prehash {
// use this function instead of default for more control over configuration of the hardware engine
pub fn new() -> Self { Sha512Prehash { hash: None } }
#[allow(dead_code)] // not used in hosted mode
pub fn set_prehash(&mut self, hash: [u8; 64]) { self.hash = Some(hash); }
}
impl Default for Sha512Prehash {
fn default() -> Self { Sha512Prehash::new() }
}
impl HashMarker for Sha512Prehash {}
impl BlockSizeUser for Sha512Prehash {
type BlockSize = U128;
}
impl BufferKindUser for Sha512Prehash {
type BufferKind = Eager;
}
impl OutputSizeUser for Sha512Prehash {
type OutputSize = U64;
}
impl AlgorithmName for Sha512Prehash {
#[inline]
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Sha512") }
}
impl fmt::Debug for Sha512Prehash {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Sha512Prehash { ... }") }
}
impl UpdateCore for Sha512Prehash {
fn update_blocks(&mut self, _blocks: &[Block<Self>]) {
panic!("Prehash implementation can't take block updates");
}
}
impl VariableOutputCore for Sha512Prehash {
const TRUNC_SIDE: TruncSide = TruncSide::Left;
fn new(_output_size: usize) -> Result<Self, InvalidOutputSize> { Ok(Self { hash: None }) }
fn finalize_variable_core(&mut self, _buffer: &mut Buffer<Self>, out: &mut Output<Self>) {
for (dest, &src) in out.chunks_exact_mut(1).zip(self.hash.unwrap().iter()) {
dest.copy_from_slice(&[src])
}
}
}
impl Update for Sha512Prehash {
/// Update state using the provided data.
fn update(&mut self, _data: &[u8]) {
panic!("Prehash implementation can't take block updates");
}
}
impl FixedOutput for Sha512Prehash {
/// Consume value and write result into provided array.
fn finalize_into(self, out: &mut Output<Self>) {
for (dest, &src) in out.chunks_exact_mut(1).zip(self.hash.unwrap().iter()) {
dest.copy_from_slice(&[src])
}
}
}

View file

@ -0,0 +1,117 @@
use core::fmt::Display;
use simple_fatfs::io::{IOBase, Read, Seek, SeekFrom, Write};
use simple_fatfs::{IOError, IOErrorKind};
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum IOErrorFatfs {
UnexpectedEof,
Interrupted,
InvalidData,
Description,
SeekUnderflow,
SeekOverflow,
SeekOutOfBounds,
}
impl Display for IOErrorFatfs {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
IOErrorFatfs::UnexpectedEof => write!(f, "Unexpected EOF"),
IOErrorFatfs::Interrupted => write!(f, "Interrupted"),
IOErrorFatfs::InvalidData => write!(f, "Invalid Data"),
IOErrorFatfs::Description => write!(f, "Unsupported string description"),
IOErrorFatfs::SeekOutOfBounds => write!(f, "Seek out of bounds"),
IOErrorFatfs::SeekOverflow => write!(f, "Seek overflow"),
IOErrorFatfs::SeekUnderflow => write!(f, "Seek underflow"),
}
}
}
impl From<&str> for IOErrorFatfs {
fn from(_value: &str) -> Self { IOErrorFatfs::Description }
}
impl IOErrorKind for IOErrorFatfs {
fn new_unexpected_eof() -> Self { Self::UnexpectedEof }
fn new_invalid_data() -> Self { Self::InvalidData }
fn new_interrupted() -> Self { Self::Interrupted }
}
impl IOError for IOErrorFatfs {
type Kind = IOErrorFatfs;
fn new<M>(kind: Self::Kind, _msg: M) -> Self
where
M: core::fmt::Display,
{
kind
}
fn kind(&self) -> Self::Kind { *self }
}
impl simple_fatfs::Error for IOErrorFatfs {}
impl IOBase for SliceCursor<'_> {
type Error = IOErrorFatfs;
}
pub struct SliceCursor<'a> {
pub slice: &'a mut [u8],
pub pos: u64,
}
impl<'a> SliceCursor<'a> {
pub fn new(slice: &'a mut [u8]) -> Self { Self { slice, pos: 0 } }
}
impl Seek for SliceCursor<'_> {
fn seek(&mut self, seek_from: simple_fatfs::io::SeekFrom) -> Result<u64, Self::Error> {
let new_pos = match seek_from {
SeekFrom::Start(offset) => offset,
SeekFrom::End(offset) => {
let result = if offset < 0 {
self.slice.len().checked_sub((-offset) as usize).ok_or(IOErrorFatfs::SeekUnderflow)?
} else {
self.slice.len().checked_add(offset as usize).ok_or(IOErrorFatfs::SeekOverflow)?
};
result as u64
}
SeekFrom::Current(offset) => {
if offset < 0 {
self.pos.checked_sub((-offset) as u64).ok_or(IOErrorFatfs::SeekUnderflow)?
} else {
self.pos.checked_add(offset as u64).ok_or(IOErrorFatfs::SeekUnderflow)?
}
}
};
if new_pos > self.slice.len() as u64 {
Err(IOErrorFatfs::SeekOutOfBounds)
} else {
self.pos = new_pos;
Ok(self.pos)
}
}
}
impl Read for SliceCursor<'_> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
let available = &self.slice[self.pos as usize..];
let to_read = buf.len().min(available.len());
buf[..to_read].copy_from_slice(&available[..to_read]);
self.pos += to_read as u64;
Ok(to_read)
}
}
impl Write for SliceCursor<'_> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
let available = &mut self.slice[self.pos as usize..];
let to_write = buf.len().min(available.len());
available[..to_write].copy_from_slice(&buf[..to_write]);
self.pos += to_write as u64;
Ok(to_write)
}
fn flush(&mut self) -> Result<(), Self::Error> { Ok(()) }
}

View file

@ -374,6 +374,7 @@ impl Repl {
return Err(Error::help("clocks <CPU freq in MHz, 100-1600>"));
}
}
/*
#[cfg(feature = "cramium-soc")]
"usb" => {
crate::println!("USB basic test...");
@ -471,6 +472,7 @@ impl Repl {
}
}
}
*/
#[cfg(feature = "nto-bio")]
"pin" => {
// We need at least a subcommand.