mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-19 09:00:54 +00:00
refactor baremetal
- remove signed bootloader code - replace with serial console over USB file transfer needs to be reworked to not use signatures in baremetal, but rather just a simple hash to verify integrity. repl needs to be reworked with an "in-place" code upload command so that large images (> available RAM) can be burned
This commit is contained in:
parent
c61a521c7d
commit
602b60b669
16 changed files with 820 additions and 836 deletions
|
|
@ -53,17 +53,16 @@ nto-bio = [
|
||||||
]
|
]
|
||||||
# selects features for EVB target (defaults to baosec)
|
# selects features for EVB target (defaults to baosec)
|
||||||
nto-evb = []
|
nto-evb = []
|
||||||
nto-gfx = ["ux-api/loader-baosec"]
|
|
||||||
nto-usb = [
|
nto-usb = [
|
||||||
"nto-gfx",
|
|
||||||
"simple-fatfs",
|
"simple-fatfs",
|
||||||
"sha2",
|
"sha2",
|
||||||
"digest",
|
"digest",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"cramium-hal/debug-print-usb",
|
"cramium-hal/debug-print-usb",
|
||||||
"cramium-hal/verbose-debug",
|
# "cramium-hal/verbose-debug",
|
||||||
]
|
]
|
||||||
nto-buttons = []
|
nto-buttons = []
|
||||||
|
verbose-debug = []
|
||||||
|
|
||||||
verilator-only = []
|
verilator-only = []
|
||||||
default = ["nto-buttons"]
|
default = ["nto-usb"]
|
||||||
|
|
|
||||||
Binary file not shown.
|
|
@ -17,9 +17,16 @@ use utralib::*;
|
||||||
#[cfg(feature = "artybio")]
|
#[cfg(feature = "artybio")]
|
||||||
use xous_bio_bdma::*;
|
use xous_bio_bdma::*;
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
use crate::delay;
|
use crate::delay;
|
||||||
|
|
||||||
static UART_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
|
static UART_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
|
||||||
|
#[cfg(feature = "nto-usb")]
|
||||||
|
static USB_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
|
||||||
|
#[cfg(feature = "nto-usb")]
|
||||||
|
static USB_TX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
|
||||||
|
#[cfg(feature = "nto-usb")]
|
||||||
|
static USB_CONNECTED: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
|
||||||
|
|
||||||
pub fn uart_irq_handler() {
|
pub fn uart_irq_handler() {
|
||||||
use crate::debug::SerialRead;
|
use crate::debug::SerialRead;
|
||||||
|
|
@ -65,6 +72,7 @@ pub unsafe extern "C" fn rust_entry() -> ! {
|
||||||
// The green LEDs flash whenever the FPGA is configured with the Arty BIO design.
|
// The green LEDs flash whenever the FPGA is configured with the Arty BIO design.
|
||||||
// The RGB LEDs flash when the CPU is running this code.
|
// The RGB LEDs flash when the CPU is running this code.
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
|
#[allow(unused_mut)]
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
#[cfg(any(feature = "artyvexii", feature = "artybio"))]
|
#[cfg(any(feature = "artyvexii", feature = "artybio"))]
|
||||||
let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32);
|
let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32);
|
||||||
|
|
@ -76,8 +84,62 @@ pub unsafe extern "C" fn rust_entry() -> ! {
|
||||||
repl.init_cmd("bio"); // do a power-on BIO test
|
repl.init_cmd("bio"); // do a power-on BIO test
|
||||||
|
|
||||||
#[cfg(feature = "nto-usb")]
|
#[cfg(feature = "nto-usb")]
|
||||||
crate::platform::usb::glue::do_update(); // initially this supplants the repl loop
|
// do the main loop through the USB interface
|
||||||
|
{
|
||||||
|
use crate::platform::usb::glue;
|
||||||
|
let (mut last_usb_state, mut portsc) = glue::setup();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
use cramium_hal::usb::driver::UsbDeviceState;
|
||||||
|
|
||||||
|
let (new_usb_state, new_portsc) = glue::usb_status();
|
||||||
|
// break out of the loop when USB is disconnected, after it has been configured
|
||||||
|
// this might not make sense for baremetal that has no battery. but keep it for now.
|
||||||
|
if new_portsc != portsc {
|
||||||
|
portsc = new_portsc;
|
||||||
|
if glue::is_disconnected(portsc) && new_usb_state == UsbDeviceState::Configured {
|
||||||
|
USB_CONNECTED.store(false, core::sync::atomic::Ordering::SeqCst);
|
||||||
|
last_usb_state = UsbDeviceState::NotAttached;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if last_usb_state == UsbDeviceState::Configured {
|
||||||
|
// put repl in here
|
||||||
|
critical_section::with(|cs| {
|
||||||
|
let mut queue = USB_RX.borrow(cs).borrow_mut();
|
||||||
|
while let Some(byte) = queue.pop_front() {
|
||||||
|
repl.rx_char(byte);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Process any command line requests
|
||||||
|
match repl.process() {
|
||||||
|
Err(e) => {
|
||||||
|
if let Some(m) = e.message {
|
||||||
|
crate::println!("{}", m);
|
||||||
|
repl.abort_cmd();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
};
|
||||||
|
glue::flush_tx();
|
||||||
|
} else {
|
||||||
|
// TODO: retry connection to host by pulling SE0. Need to add the SE0 switch, tho!
|
||||||
|
}
|
||||||
|
|
||||||
|
// provide feedback when connection is established
|
||||||
|
if new_usb_state != last_usb_state {
|
||||||
|
if new_usb_state == UsbDeviceState::Configured {
|
||||||
|
crate::println!("USB is connected!");
|
||||||
|
last_usb_state = new_usb_state;
|
||||||
|
USB_CONNECTED.store(true, core::sync::atomic::Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "nto-usb"))]
|
||||||
|
// do the main loop through the serial port
|
||||||
loop {
|
loop {
|
||||||
// Handle keyboard events.
|
// Handle keyboard events.
|
||||||
critical_section::with(|cs| {
|
critical_section::with(|cs| {
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,6 @@ pub use cramium::*;
|
||||||
#[cfg(feature = "nto-bio")]
|
#[cfg(feature = "nto-bio")]
|
||||||
pub mod bio;
|
pub mod bio;
|
||||||
pub mod debug;
|
pub mod debug;
|
||||||
#[cfg(feature = "nto-gfx")]
|
|
||||||
pub mod gfx;
|
|
||||||
pub mod irq;
|
pub mod irq;
|
||||||
#[cfg(feature = "nto-usb")]
|
#[cfg(feature = "nto-usb")]
|
||||||
pub mod usb;
|
pub mod usb;
|
||||||
|
|
|
||||||
|
|
@ -13,14 +13,13 @@ use crate::platform::{
|
||||||
#[global_allocator]
|
#[global_allocator]
|
||||||
static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
|
static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty();
|
||||||
|
|
||||||
// bottom 256k (0x4_0000) reserved for jtag-booting targets code space
|
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN;
|
||||||
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN - 0x4_0000;
|
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM;
|
||||||
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM + 0x4_0000;
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM;
|
pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM;
|
||||||
|
|
||||||
// 0x5000 is the space for statics
|
const DATA_SIZE_BYTES: usize = 0x6000;
|
||||||
pub const HEAP_START: usize = RAM_BASE + 0x5000;
|
pub const HEAP_START: usize = RAM_BASE + DATA_SIZE_BYTES;
|
||||||
pub const HEAP_LEN: usize = 1024 * 256;
|
pub const HEAP_LEN: usize = 1024 * 256;
|
||||||
|
|
||||||
// scratch page for exceptions located at top of RAM
|
// scratch page for exceptions located at top of RAM
|
||||||
|
|
@ -35,9 +34,9 @@ pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1;
|
||||||
|
|
||||||
pub fn early_init() {
|
pub fn early_init() {
|
||||||
// Define the .data region - bootstrap baremetal using these hard-coded parameters.
|
// Define the .data region - bootstrap baremetal using these hard-coded parameters.
|
||||||
const DATA_ORIGIN: usize = 0x61040000;
|
// Define the .data region - bootstrap baremetal using these hard-coded parameters.
|
||||||
const DATA_SIZE_BYTES: usize = 0x5000;
|
const DATA_ORIGIN: usize = 0x61000000;
|
||||||
const DATA_INIT: [(usize, u32); 1] = [(0x0, 0x1)];
|
const DATA_INIT: [(usize, u32); 4] = [(0x0, 0x2), (0x53c, 0x1), (0x541, 0x1), (0x546, 0x1)];
|
||||||
|
|
||||||
// Clear .data, .bss, .stack, .heap regions & setup .data values
|
// Clear .data, .bss, .stack, .heap regions & setup .data values
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
@ -53,6 +52,7 @@ pub fn early_init() {
|
||||||
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
|
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
|
||||||
#[cfg(not(feature = "nto-evb"))]
|
#[cfg(not(feature = "nto-evb"))]
|
||||||
{
|
{
|
||||||
|
// sets up the FET control for DCDC2 (only useful on boards that support it)
|
||||||
iox.set_gpio_pin_value(IoxPort::PA, 5, IoxValue::High);
|
iox.set_gpio_pin_value(IoxPort::PA, 5, IoxValue::High);
|
||||||
iox.setup_pin(
|
iox.setup_pin(
|
||||||
IoxPort::PA,
|
IoxPort::PA,
|
||||||
|
|
|
||||||
|
|
@ -28,19 +28,38 @@ impl Uart {
|
||||||
while uart.r(utra::duart::SFR_SR) != 0 {}
|
while uart.r(utra::duart::SFR_SR) != 0 {}
|
||||||
uart.wo(utra::duart::SFR_TXD, c as u32);
|
uart.wo(utra::duart::SFR_TXD, c as u32);
|
||||||
} else {
|
} else {
|
||||||
let buf: [u8; 1] = [c];
|
if crate::USB_CONNECTED.load(SeqCst) {
|
||||||
let uart_buf_addr = crate::platform::UART_IFRAM_ADDR;
|
critical_section::with(|cs| {
|
||||||
#[cfg(feature = "nto-evb")]
|
let mut queue = crate::USB_TX.borrow(cs).borrow_mut();
|
||||||
let mut udma_uart = unsafe {
|
// arbitrary limit to avoid runaway memory allocation in the case that
|
||||||
// safety: this is safe to call, because we set up clock and events prior to calling new.
|
// the host side doesn't have a terminal up and running
|
||||||
udma::Uart::get_handle(utra::udma_uart_1::HW_UDMA_UART_1_BASE, uart_buf_addr, uart_buf_addr)
|
if queue.len() < 4096 {
|
||||||
};
|
queue.push_back(c);
|
||||||
#[cfg(not(feature = "nto-evb"))]
|
}
|
||||||
let mut udma_uart = unsafe {
|
});
|
||||||
// safety: this is safe to call, because we set up clock and events prior to calling new.
|
} else {
|
||||||
udma::Uart::get_handle(utra::udma_uart_2::HW_UDMA_UART_2_BASE, uart_buf_addr, uart_buf_addr)
|
let buf: [u8; 1] = [c];
|
||||||
};
|
let uart_buf_addr = crate::platform::UART_IFRAM_ADDR;
|
||||||
udma_uart.write(&buf);
|
#[cfg(feature = "nto-evb")]
|
||||||
|
let mut udma_uart = unsafe {
|
||||||
|
// safety: this is safe to call, because we set up clock and events prior to calling new.
|
||||||
|
udma::Uart::get_handle(
|
||||||
|
utra::udma_uart_1::HW_UDMA_UART_1_BASE,
|
||||||
|
uart_buf_addr,
|
||||||
|
uart_buf_addr,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
#[cfg(not(feature = "nto-evb"))]
|
||||||
|
let mut udma_uart = unsafe {
|
||||||
|
// safety: this is safe to call, because we set up clock and events prior to calling new.
|
||||||
|
udma::Uart::get_handle(
|
||||||
|
utra::udma_uart_2::HW_UDMA_UART_2_BASE,
|
||||||
|
uart_buf_addr,
|
||||||
|
uart_buf_addr,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
udma_uart.write(&buf);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,143 +0,0 @@
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -47,7 +47,7 @@ pub unsafe extern "C" fn _start_trap() -> ! {
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
core::arch::asm!(
|
core::arch::asm!(
|
||||||
"csrw mscratch, sp",
|
"csrw mscratch, sp",
|
||||||
"li sp, 0x61043000", // crate::platform::SCRATCH_PAGE - has to be hard-coded
|
"li sp, {scratch_page}", // crate::platform::SCRATCH_PAGE - has to be hard-coded
|
||||||
"sw x1, 0*4(sp)",
|
"sw x1, 0*4(sp)",
|
||||||
// Skip SP for now
|
// Skip SP for now
|
||||||
"sw x3, 2*4(sp)",
|
"sw x3, 2*4(sp)",
|
||||||
|
|
@ -93,14 +93,13 @@ pub unsafe extern "C" fn _start_trap() -> ! {
|
||||||
"csrr t0, mscratch",
|
"csrr t0, mscratch",
|
||||||
"sw t0, 1*4(sp)",
|
"sw t0, 1*4(sp)",
|
||||||
// Restore a default stack pointer
|
// Restore a default stack pointer
|
||||||
"li sp, 0x61045000", // heap base, grows down
|
"li sp, {heap_base}", // heap base, grows down
|
||||||
|
|
||||||
// Note that registers $a0-$a7 still contain the arguments
|
// Note that registers $a0-$a7 still contain the arguments
|
||||||
"j _start_trap_rust",
|
"j _start_trap_rust",
|
||||||
// Note to self: trying to assign the scratch and default pages using in(reg) syntax
|
|
||||||
// clobbers the `a0` register and places the initialization outside of the handler loop
|
scratch_page = const SCRATCH_PAGE,
|
||||||
// and there seems to be no way to refer directly to a symbol? the `sym` directive wants
|
heap_base = const HEAP_START
|
||||||
// to refer to an address, not a constant.
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
_start_trap_aligned();
|
_start_trap_aligned();
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
MEMORY
|
MEMORY
|
||||||
{
|
{
|
||||||
FLASH : ORIGIN = 0x60000000, LENGTH = 256k
|
FLASH : ORIGIN = 0x60000000, LENGTH = 256k
|
||||||
RAM : ORIGIN = 0x61040000, LENGTH = 1792k
|
RAM : ORIGIN = 0x61000000, LENGTH = 2048k
|
||||||
}
|
}
|
||||||
|
|
||||||
REGION_ALIAS("REGION_TEXT", FLASH);
|
REGION_ALIAS("REGION_TEXT", FLASH);
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,7 @@ pub unsafe fn init_usb() {
|
||||||
usb.assign_handler(handle_event);
|
usb.assign_handler(handle_event);
|
||||||
|
|
||||||
// initialize the "disk" area
|
// initialize the "disk" area
|
||||||
let disk = mass_storage::conjure_disk();
|
let disk = handlers::conjure_disk();
|
||||||
disk.fill(0);
|
disk.fill(0);
|
||||||
// setup MBR
|
// setup MBR
|
||||||
disk[..MBR_TEMPLATE.len()].copy_from_slice(&MBR_TEMPLATE);
|
disk[..MBR_TEMPLATE.len()].copy_from_slice(&MBR_TEMPLATE);
|
||||||
|
|
@ -240,6 +240,15 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
|
||||||
let comp_code =
|
let comp_code =
|
||||||
CompletionCode::try_from(event_trb.dw2.compl_code()).expect("Invalid completion code");
|
CompletionCode::try_from(event_trb.dw2.compl_code()).expect("Invalid completion code");
|
||||||
|
|
||||||
|
#[cfg(feature = "verbose-debug")]
|
||||||
|
crate::println!(
|
||||||
|
"e_trb {:x} {:x} {:x} {:x}",
|
||||||
|
event_trb.dw0,
|
||||||
|
event_trb.dw1,
|
||||||
|
event_trb.dw2.0,
|
||||||
|
event_trb.dw3.0
|
||||||
|
);
|
||||||
|
let residual_length = event_trb.dw2.trb_tran_len() as u16;
|
||||||
// update the dequeue pointer
|
// update the dequeue pointer
|
||||||
// crate::println!("event_transfer {:x?}", event_trb);
|
// crate::println!("event_transfer {:x?}", event_trb);
|
||||||
let deq_pt =
|
let deq_pt =
|
||||||
|
|
@ -272,7 +281,15 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
|
||||||
// so unsafe. so unsafe. We're counting on the hardware to hand us a raw pointer
|
// so unsafe. so unsafe. We're counting on the hardware to hand us a raw pointer
|
||||||
// that isn't corrupted.
|
// that isn't corrupted.
|
||||||
let p_trb = unsafe { &*(event_trb.dw0 as *const TransferTrbS) };
|
let p_trb = unsafe { &*(event_trb.dw0 as *const TransferTrbS) };
|
||||||
f(this, p_trb.dplo as usize, p_trb.dw2.0, 0);
|
#[cfg(feature = "verbose-debug")]
|
||||||
|
crate::println!(
|
||||||
|
"p_trb {:x} {:x} {:x} {:x}",
|
||||||
|
p_trb.dphi,
|
||||||
|
p_trb.dplo,
|
||||||
|
p_trb.dw2.0,
|
||||||
|
p_trb.dw3.0
|
||||||
|
);
|
||||||
|
f(this, p_trb.dplo as usize, p_trb.dw2.0, 0, residual_length);
|
||||||
}
|
}
|
||||||
} else if comp_code == CompletionCode::MissedServiceError {
|
} else if comp_code == CompletionCode::MissedServiceError {
|
||||||
crate::println!("MissedServiceError");
|
crate::println!("MissedServiceError");
|
||||||
|
|
@ -353,8 +370,6 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
USB_REQ_SET_CONFIGURATION => {
|
USB_REQ_SET_CONFIGURATION => {
|
||||||
crate::println!("USB_REQ_SET_CONFIGURATION");
|
|
||||||
|
|
||||||
let mut pass = false;
|
let mut pass = false;
|
||||||
if w_value == 0 {
|
if w_value == 0 {
|
||||||
this.set_device_state(UsbDeviceState::Address);
|
this.set_device_state(UsbDeviceState::Address);
|
||||||
|
|
@ -366,13 +381,23 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
|
||||||
}
|
}
|
||||||
|
|
||||||
if !pass {
|
if !pass {
|
||||||
|
// MSD as before
|
||||||
this.assign_completion_handler(usb_ep1_bulk_in_complete, 1, USB_SEND);
|
this.assign_completion_handler(usb_ep1_bulk_in_complete, 1, USB_SEND);
|
||||||
this.assign_completion_handler(usb_ep1_bulk_out_complete, 1, USB_RECV);
|
this.assign_completion_handler(usb_ep1_bulk_out_complete, 1, USB_RECV);
|
||||||
|
// USB-CDC-ACM
|
||||||
|
this.assign_completion_handler(usb_ep3_bulk_in_complete, 3, USB_SEND);
|
||||||
|
this.assign_completion_handler(usb_ep3_bulk_out_complete, 3, USB_RECV);
|
||||||
|
this.assign_completion_handler(usb_ep2_int_in_complete, 2, USB_SEND);
|
||||||
|
enable_composite_eps(this);
|
||||||
|
|
||||||
enable_mass_storage_eps(this, 1);
|
// Kick MSD CBW receive as before
|
||||||
|
|
||||||
this.bulk_xfer(1, USB_RECV, this.cbw_ptr(), 31, 0, 0);
|
this.bulk_xfer(1, USB_RECV, this.cbw_ptr(), 31, 0, 0);
|
||||||
this.ms_state = UmsState::CommandPhase;
|
this.ms_state = UmsState::CommandPhase;
|
||||||
|
|
||||||
|
// Kick off CDC-ACM
|
||||||
|
let acm_buf_rx = this.cdc_acm_rx_slice();
|
||||||
|
this.bulk_xfer(3, USB_RECV, acm_buf_rx.as_ptr() as usize, acm_buf_rx.len(), 0, 0);
|
||||||
|
|
||||||
this.ep0_send(0, 0, 0);
|
this.ep0_send(0, 0, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -456,8 +481,45 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
|
||||||
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
|
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
0x20 => {
|
||||||
|
// SET_LINE_CODING (host -> device, 7 bytes)
|
||||||
|
crate::println!("CDC SET_LINE_CODING");
|
||||||
|
let length = w_length as usize;
|
||||||
|
if length == 7 {
|
||||||
|
// queue EP0 OUT to receive the line coding structure
|
||||||
|
this.ep0_receive(this.ep0_buf.load(Ordering::SeqCst) as usize, length, 0);
|
||||||
|
// when complete, just ignore or store it
|
||||||
|
} else {
|
||||||
|
this.ep_halt(0, USB_RECV);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
0x21 => {
|
||||||
|
// GET_LINE_CODING (device -> host, 7 bytes)
|
||||||
|
crate::println!("CDC GET_LINE_CODING");
|
||||||
|
let ep0_buf = unsafe {
|
||||||
|
core::slice::from_raw_parts_mut(
|
||||||
|
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
|
||||||
|
CRG_UDC_EP0_REQBUFSIZE,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
// Fill with a dummy 115200 8N1 config
|
||||||
|
ep0_buf[0..4].copy_from_slice(&115200u32.to_le_bytes()); // dwDTERate
|
||||||
|
ep0_buf[4] = 0; // 1 stop bit
|
||||||
|
ep0_buf[5] = 0; // no parity
|
||||||
|
ep0_buf[6] = 8; // 8 data bits
|
||||||
|
this.ep0_send(ep0_buf.as_ptr() as usize, 7, 0);
|
||||||
|
}
|
||||||
|
0x22 => {
|
||||||
|
// SET_CONTROL_LINE_STATE (host -> device, 0 length)
|
||||||
|
crate::println!("CDC SET_CONTROL_LINE_STATE, DTR/RTS = {:x}", w_value);
|
||||||
|
// wValue bit0 = DTR, bit1 = RTS
|
||||||
|
// You can ignore since no real UART
|
||||||
|
|
||||||
|
this.ep0_send(0, 0, 0);
|
||||||
|
}
|
||||||
_ => {
|
_ => {
|
||||||
crate::println!("Unhandled!");
|
crate::println!("Unhandled class request bRequest=0x{:x}", setup_pkt.b_request);
|
||||||
|
this.ep_halt(0, USB_RECV);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -1,88 +1,20 @@
|
||||||
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 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;
|
||||||
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
|
// Empirically measured PORTSC when the port is unplugged. This might be a brittle way
|
||||||
// to detect if the device is unplugged.
|
// to detect if the device is unplugged.
|
||||||
const DISCONNECT_STATE: u32 = 0x40b;
|
const DISCONNECT_STATE: u32 = 0x40b; // 01_0_0000_0_1_01_1
|
||||||
|
const DISCONNECT_STATE_HS: u32 = 0xc6b; // 11_0_0011_0_1_01_1
|
||||||
|
|
||||||
// loader is not updateable here because we're XIP. But we can update these other images:
|
pub fn is_disconnected(state: u32) -> bool { state == DISCONNECT_STATE_HS || state == DISCONNECT_STATE }
|
||||||
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;
|
pub fn setup() -> (UsbDeviceState, u32) {
|
||||||
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!(
|
crate::println!(
|
||||||
"RAM disk starts at {:x} and is {}kiB in length",
|
"RAM disk starts at {:x} and is {}kiB in length",
|
||||||
usb::RAMDISK_ADDRESS,
|
usb::RAMDISK_ADDRESS,
|
||||||
usb::RAMDISK_LEN / 1024
|
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
|
// 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
|
// state, and we also understand that the .data section doesn't exist in the loader and
|
||||||
|
|
@ -115,318 +47,34 @@ pub fn do_update() {
|
||||||
usb.irq_csr.wo(utralib::utra::irqarray1::EV_PENDING, 0xffff_ffff); // blanket clear
|
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);
|
usb.irq_csr.wfo(utralib::utra::irqarray1::EV_ENABLE_USBC_DUPE, 1);
|
||||||
|
|
||||||
let mut last_usb_state = usb.get_device_state();
|
let last_usb_state = usb.get_device_state();
|
||||||
let mut portsc = usb.portsc_val();
|
let portsc = usb.portsc_val();
|
||||||
crate::println!("USB state: {:?}, {:x}", last_usb_state, portsc);
|
crate::println!("USB state: {:?}, {:x}", last_usb_state, portsc);
|
||||||
loop {
|
(last_usb_state, portsc)
|
||||||
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 {
|
|
||||||
portsc = new_portsc;
|
|
||||||
crate::println!("PP: {:x}", 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 {
|
} else {
|
||||||
crate::println!("USB core not allocated, can't do update!");
|
panic!("USB core not allocated, can't proceed!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct UsizeToString {
|
pub fn usb_status() -> (UsbDeviceState, u32) {
|
||||||
buf: [u8; 16], // Enough space for a u32 decimal string
|
unsafe {
|
||||||
pos: usize,
|
if let Some(ref mut usb_ref) = crate::platform::cramium::usb::USB {
|
||||||
}
|
let usb = &mut *core::ptr::addr_of_mut!(*usb_ref);
|
||||||
|
(usb.get_device_state(), usb.portsc_val())
|
||||||
impl UsizeToString {
|
} else {
|
||||||
pub const fn new() -> Self { Self { buf: [0; 16], pos: 0 } }
|
panic!("USB core not allocated, can't proceed!");
|
||||||
|
|
||||||
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) {
|
pub fn flush_tx() {
|
||||||
gfx::msg(sh1107, "Writing, do not", Point::new(8, TEXT_MIDLINE), Mono::White.into(), Mono::Black.into());
|
unsafe {
|
||||||
gfx::msg(
|
if let Some(ref mut usb_ref) = crate::platform::cramium::usb::USB {
|
||||||
sh1107,
|
let usb = &mut *core::ptr::addr_of_mut!(*usb_ref);
|
||||||
"reset or turn off!",
|
crate::usb::handlers::flush_tx(usb);
|
||||||
Point::new(4, TEXT_MIDLINE + 14),
|
} else {
|
||||||
Mono::White.into(),
|
panic!("USB core not allocated, can't proceed!");
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ use super::*;
|
||||||
|
|
||||||
// Locate the "disk"
|
// Locate the "disk"
|
||||||
pub(crate) const RAMDISK_ADDRESS: usize = crate::platform::HEAP_START + crate::platform::HEAP_LEN;
|
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 STACK_SIZE: usize = 128 * 1024; // 128k for stack is enough? maybe? if the ramdisk overflows, it smashes stack - dangerous!
|
||||||
pub(crate) const RAMDISK_LEN: usize =
|
pub(crate) const RAMDISK_LEN: usize =
|
||||||
crate::platform::RAM_SIZE - (RAMDISK_ADDRESS - crate::platform::RAM_BASE) - STACK_SIZE;
|
crate::platform::RAM_SIZE - (RAMDISK_ADDRESS - crate::platform::RAM_BASE) - STACK_SIZE;
|
||||||
pub(crate) const SECTOR_SIZE: u16 = 512;
|
pub(crate) const SECTOR_SIZE: u16 = 512;
|
||||||
|
|
@ -117,14 +117,27 @@ pub(crate) const EP1_OUT_BUF_LEN: usize = 1024;
|
||||||
pub(crate) const MASS_STORAGE_EPADDR_IN: u8 = 0x81;
|
pub(crate) const MASS_STORAGE_EPADDR_IN: u8 = 0x81;
|
||||||
pub(crate) const MASS_STORAGE_EPADDR_OUT: u8 = 0x01;
|
pub(crate) const MASS_STORAGE_EPADDR_OUT: u8 = 0x01;
|
||||||
|
|
||||||
const FS_MAX_PKT_SIZE: usize = 64;
|
pub const FS_MAX_PKT_SIZE: usize = 64;
|
||||||
const HS_MAX_PKT_SIZE: usize = 512;
|
pub const HS_MAX_PKT_SIZE: usize = 512;
|
||||||
|
|
||||||
pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) {
|
pub(crate) fn enable_mass_storage_eps(this: &mut CorigineUsb, ep_num: u8) {
|
||||||
this.ep_enable(ep_num, USB_RECV, HS_MAX_PKT_SIZE as _, EpType::BulkOutbound);
|
this.ep_enable(ep_num, USB_RECV, HS_MAX_PKT_SIZE as _, EpType::BulkOutbound);
|
||||||
this.ep_enable(ep_num, USB_SEND, HS_MAX_PKT_SIZE as _, EpType::BulkInbound);
|
this.ep_enable(ep_num, USB_SEND, HS_MAX_PKT_SIZE as _, EpType::BulkInbound);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Call from USB_REQ_SET_CONFIGURATION after setting device state to Configured
|
||||||
|
pub(crate) fn enable_composite_eps(this: &mut CorigineUsb) {
|
||||||
|
// MSD endpoints
|
||||||
|
enable_mass_storage_eps(this, 1);
|
||||||
|
|
||||||
|
// CDC notification IN (interrupt)
|
||||||
|
this.ep_enable(2, USB_SEND, HS_INT_MPS as _, EpType::IntrInbound);
|
||||||
|
|
||||||
|
// CDC data bulk OUT and IN
|
||||||
|
this.ep_enable(3, USB_RECV, HS_BULK_MPS as _, EpType::BulkOutbound);
|
||||||
|
this.ep_enable(3, USB_SEND, HS_BULK_MPS as _, EpType::BulkInbound);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) {
|
pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize, length: usize) {
|
||||||
let ep0_buf = unsafe {
|
let ep0_buf = unsafe {
|
||||||
core::slice::from_raw_parts_mut(
|
core::slice::from_raw_parts_mut(
|
||||||
|
|
@ -135,72 +148,34 @@ pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize,
|
||||||
|
|
||||||
match (value >> 8) as u8 {
|
match (value >> 8) as u8 {
|
||||||
USB_DT_DEVICE => {
|
USB_DT_DEVICE => {
|
||||||
crate::println!("USB_DT_DEVICE");
|
let mut dd = DeviceDescriptor::default_composite();
|
||||||
let mut device_descriptor = DeviceDescriptor::default_mass_storage();
|
dd.b_max_packet_size0 = 64;
|
||||||
device_descriptor.b_max_packet_size0 = 64;
|
|
||||||
// device_descriptor.b_cd_usb = 0x0210;
|
|
||||||
|
|
||||||
let len = length.min(core::mem::size_of::<DeviceDescriptor>());
|
let len = length.min(core::mem::size_of::<DeviceDescriptor>());
|
||||||
ep0_buf[..len].copy_from_slice(&device_descriptor.as_ref()[..len]);
|
ep0_buf[..len].copy_from_slice(&dd.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);
|
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, len, 0);
|
||||||
}
|
}
|
||||||
USB_DT_DEVICE_QUALIFIER => {
|
USB_DT_DEVICE_QUALIFIER => {
|
||||||
crate::println!("USB_DT_DEVICE_QUALIFIER");
|
let mut q = QualifierDescriptor::default_mass_storage();
|
||||||
|
// For composite the fields still apply. Keep class 0.
|
||||||
let qualifier_descriptor = QualifierDescriptor::default_mass_storage();
|
q.b_num_configurations = 1;
|
||||||
let len = length.min(core::mem::size_of::<QualifierDescriptor>());
|
let len = length.min(core::mem::size_of::<QualifierDescriptor>());
|
||||||
ep0_buf[..len].copy_from_slice(&qualifier_descriptor.as_ref()[..len]);
|
ep0_buf[..len].copy_from_slice(&q.as_ref()[..len]);
|
||||||
|
|
||||||
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, len, 0);
|
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, len, 0);
|
||||||
}
|
}
|
||||||
USB_DT_CONFIG => {
|
USB_DT_CONFIG => {
|
||||||
crate::println!("USB_DT_CONFIG");
|
let wrote = write_config_hs(ep0_buf);
|
||||||
let total_length = size_of::<ConfigDescriptor>()
|
let buffsize = wrote.min(length);
|
||||||
+ 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, HS_MAX_PKT_SIZE as _);
|
|
||||||
let ep_out =
|
|
||||||
EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_OUT, HS_MAX_PKT_SIZE as _);
|
|
||||||
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);
|
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
|
||||||
}
|
}
|
||||||
USB_DT_OTHER_SPEED_CONFIG => {
|
USB_DT_OTHER_SPEED_CONFIG => {
|
||||||
crate::println!("USB_DT_OTHER_SPEED_CONFIG\r\n");
|
let wrote = write_config_fs(ep0_buf);
|
||||||
let total_length = size_of::<ConfigDescriptor>()
|
let buffsize = wrote.min(length);
|
||||||
+ 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, FS_MAX_PKT_SIZE as _);
|
|
||||||
let ep_out =
|
|
||||||
EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_OUT, FS_MAX_PKT_SIZE as _);
|
|
||||||
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);
|
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
|
||||||
}
|
}
|
||||||
USB_DT_STRING => {
|
USB_DT_STRING => {
|
||||||
let id = (value & 0xFF) as u8;
|
let id = (value & 0xFF) as u8;
|
||||||
crate::println!("USB_DT_STRING {}", id);
|
|
||||||
let len = if id == 0 {
|
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]);
|
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
|
4
|
||||||
} else {
|
} else {
|
||||||
let s = match id {
|
let s = match id {
|
||||||
|
|
@ -208,41 +183,44 @@ pub fn get_descriptor_request(this: &mut CorigineUsb, value: u16, _index: usize,
|
||||||
2 => PRODUCT,
|
2 => PRODUCT,
|
||||||
_ => SERIAL,
|
_ => SERIAL,
|
||||||
};
|
};
|
||||||
// strings are utf16-le encoded words. Manually pack them.
|
let slen = 2 + s.len() * 2;
|
||||||
let len = 2 + s.len() * 2; // 2 bytes for header + string data
|
ep0_buf[0] = slen as u8;
|
||||||
ep0_buf[0] = len as u8;
|
|
||||||
ep0_buf[1] = USB_DT_STRING;
|
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()) {
|
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());
|
dst.copy_from_slice(&(src as u16).to_le_bytes());
|
||||||
}
|
}
|
||||||
len
|
slen
|
||||||
};
|
};
|
||||||
let buffsize = length.min(len);
|
let buffsize = length.min(len);
|
||||||
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
|
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
|
||||||
}
|
}
|
||||||
USB_DT_BOS => {
|
USB_DT_BOS => {
|
||||||
crate::println!("USB_DT_BOS");
|
let total_length =
|
||||||
let total_length = size_of::<BosDescriptor>() + size_of::<ExtCapDescriptor>();
|
core::mem::size_of::<BosDescriptor>() + core::mem::size_of::<ExtCapDescriptor>();
|
||||||
let bos = BosDescriptor::default_mass_storage(total_length as u16, 1);
|
let bos = BosDescriptor::default_mass_storage(total_length as u16, 1);
|
||||||
let ext = ExtCapDescriptor::default_mass_storage((0xfa << 8) | (0x3 << 3));
|
let ext = ExtCapDescriptor::default_mass_storage((0xfa << 8) | (0x3 << 3));
|
||||||
let response: [&[u8]; 2] = [bos.as_ref(), ext.as_ref()];
|
let response: [&[u8]; 2] = [bos.as_ref(), ext.as_ref()];
|
||||||
let flattened = response.iter().flat_map(|slice| slice.iter().copied());
|
let mut idx = 0;
|
||||||
for (dst, src) in ep0_buf.iter_mut().zip(flattened) {
|
for part in response {
|
||||||
*dst = src
|
ep0_buf[idx..idx + part.len()].copy_from_slice(part);
|
||||||
|
idx += part.len();
|
||||||
}
|
}
|
||||||
let buffsize = total_length.min(length);
|
let buffsize = total_length.min(length);
|
||||||
this.ep0_send(this.ep0_buf.load(Ordering::SeqCst) as usize, buffsize, 0);
|
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);
|
this.ep_halt(0, USB_RECV);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn usb_ep1_bulk_out_complete(this: &mut CorigineUsb, buf_addr: usize, info: u32, _error: u8) {
|
pub fn usb_ep1_bulk_out_complete(
|
||||||
|
this: &mut CorigineUsb,
|
||||||
|
buf_addr: usize,
|
||||||
|
info: u32,
|
||||||
|
_error: u8,
|
||||||
|
_residual: u16,
|
||||||
|
) {
|
||||||
let length = info & 0xFFFF;
|
let length = info & 0xFFFF;
|
||||||
let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, info as usize & 0xFFFF) };
|
let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, info as usize & 0xFFFF) };
|
||||||
let mut cbw = Cbw::default();
|
let mut cbw = Cbw::default();
|
||||||
|
|
@ -293,7 +271,13 @@ pub fn usb_ep1_bulk_out_complete(this: &mut CorigineUsb, buf_addr: usize, info:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn usb_ep1_bulk_in_complete(this: &mut CorigineUsb, _buf_addr: usize, info: u32, _error: u8) {
|
pub fn usb_ep1_bulk_in_complete(
|
||||||
|
this: &mut CorigineUsb,
|
||||||
|
_buf_addr: usize,
|
||||||
|
info: u32,
|
||||||
|
_error: u8,
|
||||||
|
_residual: u16,
|
||||||
|
) {
|
||||||
// crate::println!("bulk IN handler");
|
// crate::println!("bulk IN handler");
|
||||||
let length = info & 0xFFFF;
|
let length = info & 0xFFFF;
|
||||||
if UmsState::DataPhase == this.ms_state {
|
if UmsState::DataPhase == this.ms_state {
|
||||||
|
|
@ -314,6 +298,98 @@ pub fn usb_ep1_bulk_in_complete(this: &mut CorigineUsb, _buf_addr: usize, info:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== CDC Bulk OUT (EP3 OUT) =====
|
||||||
|
pub fn usb_ep3_bulk_out_complete(
|
||||||
|
this: &mut CorigineUsb,
|
||||||
|
buf_addr: usize,
|
||||||
|
_info: u32,
|
||||||
|
_error: u8,
|
||||||
|
residual: u16,
|
||||||
|
) {
|
||||||
|
// crate::println!("EP3 OUT: {:x} {:x}", info, _error);
|
||||||
|
|
||||||
|
let actual = CRG_UDC_APP_BUF_LEN - residual as usize;
|
||||||
|
|
||||||
|
if actual == 0 {
|
||||||
|
return; // zero-length packet, ignore
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slice of received data
|
||||||
|
let buf = unsafe { core::slice::from_raw_parts(buf_addr as *const u8, actual as usize) };
|
||||||
|
|
||||||
|
// For now: just print, or push into a ring buffer for your "virtual terminal"
|
||||||
|
// crate::println!("CDC OUT received {} bytes: {:?}", actual, &buf);
|
||||||
|
|
||||||
|
critical_section::with(|cs| {
|
||||||
|
let mut queue = crate::USB_RX.borrow(cs).borrow_mut();
|
||||||
|
for &d in buf {
|
||||||
|
queue.push_back(d);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Re-arm OUT transfer so host can send more
|
||||||
|
let acm_buf = this.cdc_acm_rx_slice();
|
||||||
|
this.bulk_xfer(3, USB_RECV, acm_buf.as_ptr() as usize, acm_buf.len(), 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn flush_tx(this: &mut CorigineUsb) {
|
||||||
|
let mut written = 0;
|
||||||
|
|
||||||
|
let tx_buf = this.cdc_acm_tx_slice();
|
||||||
|
critical_section::with(|cs| {
|
||||||
|
let mut queue = crate::USB_TX.borrow(cs).borrow_mut();
|
||||||
|
let to_copy = queue.len().min(CRG_UDC_APP_BUF_LEN);
|
||||||
|
|
||||||
|
let (a, b) = queue.as_slices();
|
||||||
|
if to_copy <= a.len() {
|
||||||
|
tx_buf[..to_copy].copy_from_slice(&a[..to_copy]);
|
||||||
|
queue.drain(..to_copy);
|
||||||
|
written = to_copy;
|
||||||
|
} else {
|
||||||
|
let first = a.len();
|
||||||
|
let second = to_copy - first;
|
||||||
|
tx_buf[..first].copy_from_slice(a);
|
||||||
|
tx_buf[first..to_copy].copy_from_slice(&b[..second]);
|
||||||
|
queue.drain(..to_copy);
|
||||||
|
written = to_copy;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if written > 0 {
|
||||||
|
this.bulk_xfer(3, USB_SEND, tx_buf.as_ptr() as usize, written, 0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== CDC Bulk IN (EP3 IN) =====
|
||||||
|
pub fn usb_ep3_bulk_in_complete(
|
||||||
|
this: &mut CorigineUsb,
|
||||||
|
_buf_addr: usize,
|
||||||
|
_info: u32,
|
||||||
|
_error: u8,
|
||||||
|
_residual: u16,
|
||||||
|
) {
|
||||||
|
// crate::println!("EP3 IN");
|
||||||
|
// let length = CRG_UDC_APP_BUF_LEN - residual as usize;
|
||||||
|
// crate::println!("CDC IN transfer complete, {} bytes sent", length);
|
||||||
|
flush_tx(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== CDC Notification IN (EP2 IN) =====
|
||||||
|
pub fn usb_ep2_int_in_complete(
|
||||||
|
_this: &mut CorigineUsb,
|
||||||
|
_buf_addr: usize,
|
||||||
|
_info: u32,
|
||||||
|
_error: u8,
|
||||||
|
_residual: u16,
|
||||||
|
) {
|
||||||
|
// crate::println!("EP2 INT");
|
||||||
|
// let length = CRG_UDC_APP_BUF_LEN - residual as usize;
|
||||||
|
// crate::println!("CDC notification sent, {} bytes", length);
|
||||||
|
|
||||||
|
// Typically sends SERIAL_STATE bitmap (carrier detect etc).
|
||||||
|
// Ignoring - this is a virtual terminal
|
||||||
|
}
|
||||||
|
|
||||||
fn process_mass_storage_command(this: &mut CorigineUsb, cbw: Cbw) {
|
fn process_mass_storage_command(this: &mut CorigineUsb, cbw: Cbw) {
|
||||||
match cbw.cdb[0] {
|
match cbw.cdb[0] {
|
||||||
0x00 => { /* Request the device to report if it is ready */
|
0x00 => { /* Request the device to report if it is ready */
|
||||||
|
|
@ -1,12 +1,9 @@
|
||||||
mod driver;
|
mod driver;
|
||||||
pub mod glue;
|
pub mod glue;
|
||||||
mod mass_storage;
|
mod handlers;
|
||||||
mod sha512_digest;
|
|
||||||
mod slice_cursor;
|
|
||||||
|
|
||||||
pub use driver::*;
|
pub use driver::*;
|
||||||
pub use mass_storage::*;
|
pub use handlers::*;
|
||||||
pub use slice_cursor::*;
|
|
||||||
|
|
||||||
use crate::irq::*;
|
use crate::irq::*;
|
||||||
|
|
||||||
|
|
@ -87,6 +84,43 @@ const USB_DT_SSP_ISOC_ENDPOINT_COMP: u8 = 0x31;
|
||||||
|
|
||||||
const USB_CAP_TYPE_EXT: u8 = 0x2;
|
const USB_CAP_TYPE_EXT: u8 = 0x2;
|
||||||
|
|
||||||
|
// ===== Constants for CDC/IAD and endpoints =====
|
||||||
|
const USB_DT_CS_INTERFACE: u8 = 0x24;
|
||||||
|
#[allow(dead_code)]
|
||||||
|
const USB_DT_CS_ENDPOINT: u8 = 0x25;
|
||||||
|
|
||||||
|
// CDC functional descriptor subtypes
|
||||||
|
const CDC_FD_HEADER: u8 = 0x00;
|
||||||
|
const CDC_FD_CALL_MANAGEMENT: u8 = 0x01;
|
||||||
|
const CDC_FD_ACM: u8 = 0x02;
|
||||||
|
const CDC_FD_UNION: u8 = 0x06;
|
||||||
|
|
||||||
|
// CDC class codes
|
||||||
|
const CDC_COMM_CLASS: u8 = 0x02;
|
||||||
|
const CDC_COMM_SUBCLASS_ACM: u8 = 0x02;
|
||||||
|
const CDC_COMM_PROTOCOL_AT: u8 = 0x01; // common ACM
|
||||||
|
|
||||||
|
const CDC_DATA_CLASS: u8 = 0x0A;
|
||||||
|
|
||||||
|
// Endpoint addresses. Keep MSD on EP1 as you already use.
|
||||||
|
// CDC notification: EP2 IN
|
||||||
|
// CDC data: EP3 OUT, EP3 IN
|
||||||
|
const CDC_NOTIF_EP_IN: u8 = 0x82;
|
||||||
|
const CDC_DATA_EP_OUT: u8 = 0x03;
|
||||||
|
const CDC_DATA_EP_IN: u8 = 0x83;
|
||||||
|
|
||||||
|
// Packet sizes
|
||||||
|
const HS_BULK_MPS: u16 = 512;
|
||||||
|
const FS_BULK_MPS: u16 = 64;
|
||||||
|
const HS_INT_MPS: u16 = 16; // common value for CDC notif
|
||||||
|
const FS_INT_MPS: u16 = 8;
|
||||||
|
|
||||||
|
// Interrupt intervals
|
||||||
|
// HS interval is in microframes. 9 gives 2^9 = 512 uframes ≈ 64 ms.
|
||||||
|
const HS_INT_INTERVAL: u8 = 9;
|
||||||
|
// FS interval in frames. 10 ≈ 10 ms
|
||||||
|
const FS_INT_INTERVAL: u8 = 10;
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
#[repr(C, packed)]
|
#[repr(C, packed)]
|
||||||
struct DeviceDescriptor {
|
struct DeviceDescriptor {
|
||||||
|
|
@ -113,6 +147,7 @@ const PRODUCT: &'static str = "SecuriBao";
|
||||||
const SERIAL: &'static str = "TODO";
|
const SERIAL: &'static str = "TODO";
|
||||||
|
|
||||||
impl DeviceDescriptor {
|
impl DeviceDescriptor {
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn default_mass_storage() -> Self {
|
pub fn default_mass_storage() -> Self {
|
||||||
Self {
|
Self {
|
||||||
b_length: core::mem::size_of::<Self>() as u8,
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
|
@ -131,7 +166,27 @@ impl DeviceDescriptor {
|
||||||
b_num_configurations: 1,
|
b_num_configurations: 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn default_composite() -> 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, // composite via per-interface classing
|
||||||
|
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,
|
||||||
|
i_product: 0x02,
|
||||||
|
i_serial_number: 0x03,
|
||||||
|
b_num_configurations: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRef<[u8]> for DeviceDescriptor {
|
impl AsRef<[u8]> for DeviceDescriptor {
|
||||||
fn as_ref(&self) -> &[u8] {
|
fn as_ref(&self) -> &[u8] {
|
||||||
unsafe {
|
unsafe {
|
||||||
|
|
@ -196,6 +251,7 @@ struct ConfigDescriptor {
|
||||||
pub b_max_power: u8,
|
pub b_max_power: u8,
|
||||||
}
|
}
|
||||||
impl ConfigDescriptor {
|
impl ConfigDescriptor {
|
||||||
|
#[allow(dead_code)]
|
||||||
pub fn default_mass_storage(total_length: u16) -> Self {
|
pub fn default_mass_storage(total_length: u16) -> Self {
|
||||||
ConfigDescriptor {
|
ConfigDescriptor {
|
||||||
b_length: core::mem::size_of::<Self>() as u8,
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
|
@ -247,6 +303,40 @@ impl InterfaceDescriptor {
|
||||||
i_interface: 0x0,
|
i_interface: 0x0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn mass_storage(if_num: u8) -> Self {
|
||||||
|
let mut d = InterfaceDescriptor::default_mass_storage();
|
||||||
|
d.b_interface_number = if_num;
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cdc_comm(if_num: u8) -> Self {
|
||||||
|
Self {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_INTERFACE,
|
||||||
|
b_interface_number: if_num,
|
||||||
|
b_alternate_setting: 0,
|
||||||
|
b_num_endpoints: 1, // interrupt IN only
|
||||||
|
b_interface_class: CDC_COMM_CLASS,
|
||||||
|
b_interface_sub_class: CDC_COMM_SUBCLASS_ACM,
|
||||||
|
b_interface_protocol: CDC_COMM_PROTOCOL_AT,
|
||||||
|
i_interface: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cdc_data(if_num: u8) -> Self {
|
||||||
|
Self {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_INTERFACE,
|
||||||
|
b_interface_number: if_num,
|
||||||
|
b_alternate_setting: 0,
|
||||||
|
b_num_endpoints: 2, // bulk IN + bulk OUT
|
||||||
|
b_interface_class: CDC_DATA_CLASS,
|
||||||
|
b_interface_sub_class: 0,
|
||||||
|
b_interface_protocol: 0,
|
||||||
|
i_interface: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
impl AsRef<[u8]> for InterfaceDescriptor {
|
impl AsRef<[u8]> for InterfaceDescriptor {
|
||||||
fn as_ref(&self) -> &[u8] {
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
|
@ -279,6 +369,72 @@ impl EndpointDescriptor {
|
||||||
b_interval: 0x0,
|
b_interval: 0x0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn cdc_notif_ep_hs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_NOTIF_EP_IN,
|
||||||
|
b_m_attributes: 0x03, // Interrupt
|
||||||
|
w_max_packet_size: HS_INT_MPS,
|
||||||
|
b_interval: HS_INT_INTERVAL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cdc_notif_ep_fs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_NOTIF_EP_IN,
|
||||||
|
b_m_attributes: 0x03,
|
||||||
|
w_max_packet_size: FS_INT_MPS,
|
||||||
|
b_interval: FS_INT_INTERVAL,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cdc_data_in_hs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_DATA_EP_IN,
|
||||||
|
b_m_attributes: 0x02, // Bulk
|
||||||
|
w_max_packet_size: HS_BULK_MPS,
|
||||||
|
b_interval: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cdc_data_out_hs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_DATA_EP_OUT,
|
||||||
|
b_m_attributes: 0x02,
|
||||||
|
w_max_packet_size: HS_BULK_MPS,
|
||||||
|
b_interval: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cdc_data_in_fs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_DATA_EP_IN,
|
||||||
|
b_m_attributes: 0x02,
|
||||||
|
w_max_packet_size: FS_BULK_MPS,
|
||||||
|
b_interval: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cdc_data_out_fs() -> Self {
|
||||||
|
EndpointDescriptor {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_ENDPOINT,
|
||||||
|
b_endpoint_address: CDC_DATA_EP_OUT,
|
||||||
|
b_m_attributes: 0x02,
|
||||||
|
w_max_packet_size: FS_BULK_MPS,
|
||||||
|
b_interval: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRef<[u8]> for EndpointDescriptor {
|
impl AsRef<[u8]> for EndpointDescriptor {
|
||||||
|
|
@ -423,7 +579,7 @@ impl Csw {
|
||||||
fn derive() -> Csw {
|
fn derive() -> Csw {
|
||||||
let mut csw = Csw::default();
|
let mut csw = Csw::default();
|
||||||
csw.as_mut().copy_from_slice(unsafe {
|
csw.as_mut().copy_from_slice(unsafe {
|
||||||
core::slice::from_raw_parts(mass_storage::CSW_ADDR as *mut u8, size_of::<Csw>())
|
core::slice::from_raw_parts(handlers::CSW_ADDR as *mut u8, size_of::<Csw>())
|
||||||
});
|
});
|
||||||
csw
|
csw
|
||||||
}
|
}
|
||||||
|
|
@ -484,3 +640,309 @@ impl AsRef<[u8]> for InquiryResponse {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== IAD descriptor to group the CDC function =====
|
||||||
|
#[repr(C, packed)]
|
||||||
|
struct IadDescriptor {
|
||||||
|
b_length: u8, // 8
|
||||||
|
b_descriptor_type: u8, // 0x0B
|
||||||
|
b_first_interface: u8, // first interface of the function
|
||||||
|
b_interface_count: u8, // number of interfaces in the function
|
||||||
|
b_function_class: u8, // 0x02 (CDC)
|
||||||
|
b_function_subclass: u8, // 0x02 (ACM)
|
||||||
|
b_function_protocol: u8, // 0x01 (AT)
|
||||||
|
i_function: u8, // string index, 0 if none
|
||||||
|
}
|
||||||
|
impl IadDescriptor {
|
||||||
|
fn cdc(first_if: u8) -> Self {
|
||||||
|
Self {
|
||||||
|
b_length: core::mem::size_of::<Self>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_INTERFACE_ASSOCIATION,
|
||||||
|
b_first_interface: first_if,
|
||||||
|
b_interface_count: 2,
|
||||||
|
b_function_class: CDC_COMM_CLASS,
|
||||||
|
b_function_subclass: CDC_COMM_SUBCLASS_ACM,
|
||||||
|
b_function_protocol: CDC_COMM_PROTOCOL_AT,
|
||||||
|
i_function: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for IadDescriptor {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const IadDescriptor as *const u8,
|
||||||
|
core::mem::size_of::<IadDescriptor>(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== CDC functional descriptors =====
|
||||||
|
#[repr(C, packed)]
|
||||||
|
struct CdcHeaderFuncDesc {
|
||||||
|
b_function_length: u8, // 5
|
||||||
|
b_descriptor_type: u8, // CS_INTERFACE
|
||||||
|
b_descriptor_subtype: u8, // Header
|
||||||
|
bcd_cdc: u16, // 0x0110 or 0x011A; 1.10 is common
|
||||||
|
}
|
||||||
|
impl CdcHeaderFuncDesc {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
b_function_length: 5,
|
||||||
|
b_descriptor_type: USB_DT_CS_INTERFACE,
|
||||||
|
b_descriptor_subtype: CDC_FD_HEADER,
|
||||||
|
bcd_cdc: 0x0110,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for CdcHeaderFuncDesc {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const CdcHeaderFuncDesc as *const u8,
|
||||||
|
core::mem::size_of::<CdcHeaderFuncDesc>(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C, packed)]
|
||||||
|
struct CdcCallMgmtFuncDesc {
|
||||||
|
b_function_length: u8, // 5
|
||||||
|
b_descriptor_type: u8, // CS_INTERFACE
|
||||||
|
b_descriptor_subtype: u8, // Call Management
|
||||||
|
bm_capabilities: u8, // 0x00 device does not handle call mgmt
|
||||||
|
b_data_interface: u8, // interface number of data interface
|
||||||
|
}
|
||||||
|
impl CdcCallMgmtFuncDesc {
|
||||||
|
fn new(data_if: u8) -> Self {
|
||||||
|
Self {
|
||||||
|
b_function_length: 5,
|
||||||
|
b_descriptor_type: USB_DT_CS_INTERFACE,
|
||||||
|
b_descriptor_subtype: CDC_FD_CALL_MANAGEMENT,
|
||||||
|
bm_capabilities: 0x00,
|
||||||
|
b_data_interface: data_if,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for CdcCallMgmtFuncDesc {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const CdcCallMgmtFuncDesc as *const u8,
|
||||||
|
core::mem::size_of::<CdcCallMgmtFuncDesc>(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C, packed)]
|
||||||
|
struct CdcAcmFuncDesc {
|
||||||
|
b_function_length: u8, // 4
|
||||||
|
b_descriptor_type: u8, // CS_INTERFACE
|
||||||
|
b_descriptor_subtype: u8, // ACM
|
||||||
|
bm_capabilities: u8, // 0x02 supports Set_Line_Coding, etc.
|
||||||
|
}
|
||||||
|
impl CdcAcmFuncDesc {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
b_function_length: 4,
|
||||||
|
b_descriptor_type: USB_DT_CS_INTERFACE,
|
||||||
|
b_descriptor_subtype: CDC_FD_ACM,
|
||||||
|
bm_capabilities: 0x02,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for CdcAcmFuncDesc {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const CdcAcmFuncDesc as *const u8,
|
||||||
|
core::mem::size_of::<CdcAcmFuncDesc>(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C, packed)]
|
||||||
|
struct CdcUnionFuncDesc {
|
||||||
|
b_function_length: u8, // 5
|
||||||
|
b_descriptor_type: u8, // CS_INTERFACE
|
||||||
|
b_descriptor_subtype: u8, // Union
|
||||||
|
b_master_interface: u8, // comm interface number
|
||||||
|
b_slave_interface0: u8, // data interface number
|
||||||
|
}
|
||||||
|
impl CdcUnionFuncDesc {
|
||||||
|
fn new(master_if: u8, slave_if: u8) -> Self {
|
||||||
|
Self {
|
||||||
|
b_function_length: 5,
|
||||||
|
b_descriptor_type: USB_DT_CS_INTERFACE,
|
||||||
|
b_descriptor_subtype: CDC_FD_UNION,
|
||||||
|
b_master_interface: master_if,
|
||||||
|
b_slave_interface0: slave_if,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for CdcUnionFuncDesc {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
unsafe {
|
||||||
|
core::slice::from_raw_parts(
|
||||||
|
self as *const CdcUnionFuncDesc as *const u8,
|
||||||
|
core::mem::size_of::<CdcUnionFuncDesc>(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Composite Config descriptors (HS and FS) =====
|
||||||
|
// Layout:
|
||||||
|
// Config
|
||||||
|
// IAD (CDC group)
|
||||||
|
// IF0 CDC Comm
|
||||||
|
// CDC Header, CallMgmt, ACM, Union
|
||||||
|
// EP interrupt IN
|
||||||
|
// IF1 CDC Data
|
||||||
|
// EP bulk OUT, EP bulk IN
|
||||||
|
// IF2 MSD
|
||||||
|
// EP bulk IN, EP bulk OUT
|
||||||
|
|
||||||
|
fn config_total_len_hs() -> usize {
|
||||||
|
core::mem::size_of::<ConfigDescriptor>()
|
||||||
|
+ core::mem::size_of::<IadDescriptor>()
|
||||||
|
+ core::mem::size_of::<InterfaceDescriptor>() // CDC Comm
|
||||||
|
+ core::mem::size_of::<CdcHeaderFuncDesc>()
|
||||||
|
+ core::mem::size_of::<CdcCallMgmtFuncDesc>()
|
||||||
|
+ core::mem::size_of::<CdcAcmFuncDesc>()
|
||||||
|
+ core::mem::size_of::<CdcUnionFuncDesc>()
|
||||||
|
+ core::mem::size_of::<EndpointDescriptor>() // CDC notif
|
||||||
|
+ core::mem::size_of::<InterfaceDescriptor>() // CDC Data
|
||||||
|
+ core::mem::size_of::<EndpointDescriptor>() * 2 // CDC data bulk
|
||||||
|
+ core::mem::size_of::<InterfaceDescriptor>() // MSD
|
||||||
|
+ core::mem::size_of::<EndpointDescriptor>() * 2 // MSD bulk
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config_total_len_fs() -> usize {
|
||||||
|
// Same structure as HS
|
||||||
|
config_total_len_hs()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writes HS config into ep0_buf and returns the byte count to send
|
||||||
|
fn write_config_hs(ep0_buf: &mut [u8]) -> usize {
|
||||||
|
let if_cdc_comm: u8 = 0;
|
||||||
|
let if_cdc_data: u8 = 1;
|
||||||
|
let if_msd: u8 = 2;
|
||||||
|
|
||||||
|
let total_len = config_total_len_hs() as u16;
|
||||||
|
|
||||||
|
let config = ConfigDescriptor {
|
||||||
|
b_length: core::mem::size_of::<ConfigDescriptor>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_CONFIG,
|
||||||
|
w_total_length: total_len,
|
||||||
|
b_num_interfaces: 3,
|
||||||
|
b_configuration_value: 1,
|
||||||
|
i_configuration: 0,
|
||||||
|
bm_attributes: 0xC0, // self powered, no remote wakeup
|
||||||
|
b_max_power: 250,
|
||||||
|
};
|
||||||
|
|
||||||
|
let iad = IadDescriptor::cdc(if_cdc_comm);
|
||||||
|
let if_comm = InterfaceDescriptor::cdc_comm(if_cdc_comm);
|
||||||
|
let fd_hdr = CdcHeaderFuncDesc::new();
|
||||||
|
let fd_call = CdcCallMgmtFuncDesc::new(if_cdc_data);
|
||||||
|
let fd_acm = CdcAcmFuncDesc::new();
|
||||||
|
let fd_union = CdcUnionFuncDesc::new(if_cdc_comm, if_cdc_data);
|
||||||
|
let ep_notif = EndpointDescriptor::cdc_notif_ep_hs();
|
||||||
|
|
||||||
|
let if_data = InterfaceDescriptor::cdc_data(if_cdc_data);
|
||||||
|
let ep_data_out = EndpointDescriptor::cdc_data_out_hs();
|
||||||
|
let ep_data_in = EndpointDescriptor::cdc_data_in_hs();
|
||||||
|
|
||||||
|
let if_msd_desc = InterfaceDescriptor::mass_storage(if_msd);
|
||||||
|
let ep_msd_in = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_IN, HS_MAX_PKT_SIZE as _);
|
||||||
|
let ep_msd_out = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_OUT, HS_MAX_PKT_SIZE as _);
|
||||||
|
|
||||||
|
let parts: [&[u8]; 14] = [
|
||||||
|
config.as_ref(),
|
||||||
|
iad.as_ref(),
|
||||||
|
if_comm.as_ref(),
|
||||||
|
fd_hdr.as_ref(),
|
||||||
|
fd_call.as_ref(),
|
||||||
|
fd_acm.as_ref(),
|
||||||
|
fd_union.as_ref(),
|
||||||
|
ep_notif.as_ref(),
|
||||||
|
if_data.as_ref(),
|
||||||
|
ep_data_out.as_ref(),
|
||||||
|
ep_data_in.as_ref(),
|
||||||
|
if_msd_desc.as_ref(),
|
||||||
|
ep_msd_in.as_ref(),
|
||||||
|
ep_msd_out.as_ref(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut idx = 0;
|
||||||
|
for p in parts.iter() {
|
||||||
|
ep0_buf[idx..idx + p.len()].copy_from_slice(p);
|
||||||
|
idx += p.len();
|
||||||
|
}
|
||||||
|
idx
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writes FS other-speed config into ep0_buf and returns the byte count
|
||||||
|
fn write_config_fs(ep0_buf: &mut [u8]) -> usize {
|
||||||
|
let if_cdc_comm: u8 = 0;
|
||||||
|
let if_cdc_data: u8 = 1;
|
||||||
|
let if_msd: u8 = 2;
|
||||||
|
|
||||||
|
let total_len = config_total_len_fs() as u16;
|
||||||
|
|
||||||
|
let config = ConfigDescriptor {
|
||||||
|
b_length: core::mem::size_of::<ConfigDescriptor>() as u8,
|
||||||
|
b_descriptor_type: USB_DT_CONFIG,
|
||||||
|
w_total_length: total_len,
|
||||||
|
b_num_interfaces: 3,
|
||||||
|
b_configuration_value: 1,
|
||||||
|
i_configuration: 0,
|
||||||
|
bm_attributes: 0xC0,
|
||||||
|
b_max_power: 250,
|
||||||
|
};
|
||||||
|
|
||||||
|
let iad = IadDescriptor::cdc(if_cdc_comm);
|
||||||
|
let if_comm = InterfaceDescriptor::cdc_comm(if_cdc_comm);
|
||||||
|
let fd_hdr = CdcHeaderFuncDesc::new();
|
||||||
|
let fd_call = CdcCallMgmtFuncDesc::new(if_cdc_data);
|
||||||
|
let fd_acm = CdcAcmFuncDesc::new();
|
||||||
|
let fd_union = CdcUnionFuncDesc::new(if_cdc_comm, if_cdc_data);
|
||||||
|
let ep_notif = EndpointDescriptor::cdc_notif_ep_fs();
|
||||||
|
|
||||||
|
let if_data = InterfaceDescriptor::cdc_data(if_cdc_data);
|
||||||
|
let ep_data_out = EndpointDescriptor::cdc_data_out_fs();
|
||||||
|
let ep_data_in = EndpointDescriptor::cdc_data_in_fs();
|
||||||
|
|
||||||
|
let if_msd_desc = InterfaceDescriptor::mass_storage(if_msd);
|
||||||
|
let ep_msd_in = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_IN, FS_MAX_PKT_SIZE as _);
|
||||||
|
let ep_msd_out = EndpointDescriptor::default_mass_storage(MASS_STORAGE_EPADDR_OUT, FS_MAX_PKT_SIZE as _);
|
||||||
|
|
||||||
|
let parts: [&[u8]; 14] = [
|
||||||
|
config.as_ref(),
|
||||||
|
iad.as_ref(),
|
||||||
|
if_comm.as_ref(),
|
||||||
|
fd_hdr.as_ref(),
|
||||||
|
fd_call.as_ref(),
|
||||||
|
fd_acm.as_ref(),
|
||||||
|
fd_union.as_ref(),
|
||||||
|
ep_notif.as_ref(),
|
||||||
|
if_data.as_ref(),
|
||||||
|
ep_data_out.as_ref(),
|
||||||
|
ep_data_in.as_ref(),
|
||||||
|
if_msd_desc.as_ref(),
|
||||||
|
ep_msd_in.as_ref(),
|
||||||
|
ep_msd_out.as_ref(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut idx = 0;
|
||||||
|
for p in parts.iter() {
|
||||||
|
ep0_buf[idx..idx + p.len()].copy_from_slice(p);
|
||||||
|
idx += p.len();
|
||||||
|
}
|
||||||
|
idx
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
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])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,117 +0,0 @@
|
||||||
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(()) }
|
|
||||||
}
|
|
||||||
|
|
@ -589,7 +589,11 @@ impl Repl {
|
||||||
if let Ok(mut pmic) = cramium_hal::axp2101::Axp2101::new(&mut i2c) {
|
if let Ok(mut pmic) = cramium_hal::axp2101::Axp2101::new(&mut i2c) {
|
||||||
pmic.update(&mut i2c).ok();
|
pmic.update(&mut i2c).ok();
|
||||||
if let Some((voltage, _dvm)) = pmic.get_dcdc(cramium_hal::axp2101::WhichDcDc::Dcdc2) {
|
if let Some((voltage, _dvm)) = pmic.get_dcdc(cramium_hal::axp2101::WhichDcDc::Dcdc2) {
|
||||||
crate::println!("DCDC2 is on and {:.2}v", voltage);
|
crate::println!(
|
||||||
|
"DCDC2 is on and {}.{}v",
|
||||||
|
voltage as i32,
|
||||||
|
(voltage * 100.0) as i32 % 100
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
crate::println!("DCDC is off, turning it on!");
|
crate::println!("DCDC is off, turning it on!");
|
||||||
match pmic.set_dcdc(
|
match pmic.set_dcdc(
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue