cleanup baremetal flow to work with the boot1 assumptions

This commit is contained in:
bunnie 2025-10-01 00:42:25 +08:00
parent 4e2fc04d5d
commit 4726056b29
10 changed files with 228 additions and 499 deletions

View file

@ -16,7 +16,6 @@ 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 = { package = "ed25519-dalek-bao1x", path = "../bao1x-boot/ed25519-dalek-bao1x", default-features = false, features = [
@ -61,10 +60,6 @@ bao1x-bio = [
# selects features for EVB target (defaults to baosec)
bao1x-evb = []
bao1x-usb = [
"simple-fatfs",
"sha2",
"digest",
"ed25519-dalek",
# "bao1x-hal/debug-print-usb",
# "bao1x-hal/verbose-debug",
]

View file

@ -41,56 +41,6 @@ pub extern "C" fn _start() {
// subtract four from sp to make room for a DMA "gutter"
"addi sp, sp, -4",
// twiddle duart
"li t0, 0x40042000",
// setup etuc
"sw x0, 0x4(t0)", // CR is 0
"li t1, 34", // tuned based on ringosc & oscope. not guaranteed to be precise
"sw t1, 0xc(t0)",
"li t1, 0x1",
"sw t1, 0x4(t0)", // CR is 1
// print 32 instances of 'Z' (0x5A) (provided to measure baud)
"li t2, 32",
"li t1, 0x5A",
"10:",
"sw t1, 0x0(t0)",
"11:",
"lw t3, 0x8(t0)", // check SR
"bne x0, t3, 11b", // wait for 0
"addi t2, t2, -1",
"bne x0, t2, 10b",
/*
// test if ifram is cleared
"li t0, 0x50000000",
"li t1, 0x50040000",
"60:",
"lw t2, 0(t0)",
// if not 0, jump to clearing routine
"bne x0, t2, 30f",
"addi t0, t0, 4",
// loop if we haven't checked all of ifram
"bltu t0, t1, 60b",
// if we got here, all of ifram was 0, continue with boot
"j 50f",
// clear ifram
"30:",
"sw x0, 0(t0)",
"addi t0, t0, 4",
"bltu t0, t1, 30b",
*/
/*
// clear main ram
"li t0, 0x61000000",
"li t1, 0x61200000",
"20:",
"sw x0, 0(t0)",
"addi t0, t0, 4",
"bltu t0, t1, 20b",
".word 0x500f",
*/
"50:",
// Install a machine mode trap handler
"la t0, abort",

View file

@ -9,7 +9,11 @@ mod platform;
mod repl;
use alloc::collections::VecDeque;
use core::cell::RefCell;
#[cfg(feature = "bao1x-usb")]
use core::sync::atomic::Ordering;
#[cfg(feature = "bao1x-usb")]
use bao1x_hal::{iox::Iox, usb::driver::UsbDeviceState};
use critical_section::Mutex;
use platform::*;
#[allow(unused_imports)]
@ -19,6 +23,8 @@ use xous_bio_bdma::*;
#[allow(unused_imports)]
use crate::delay;
#[cfg(feature = "bao1x-usb")]
use crate::usb::glue;
static UART_RX: Mutex<RefCell<VecDeque<u8>>> = Mutex::new(RefCell::new(VecDeque::new()));
#[allow(dead_code)]
@ -78,66 +84,86 @@ pub unsafe extern "C" fn rust_entry() -> ! {
// provide some feedback on the run state of the BIO by peeking at the program counter
// value, and provide feedback on the CPU operation by flashing the RGB LEDs.
let mut repl = crate::repl::Repl::new();
#[cfg(feature = "bao1x-bio")]
repl.init_cmd("bio"); // do a power-on BIO test
#[cfg(feature = "bao1x-usb")]
// do the main loop through the USB interface
{
use crate::platform::usb::glue;
let (mut last_usb_state, mut portsc) = glue::setup();
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
#[cfg(feature = "bao1x-usb")]
let (mut last_usb_state, mut portsc) = crate::platform::usb::glue::hotplug_usb(&iox);
loop {
use bao1x_hal::usb::driver::UsbDeviceState;
crate::println!(
"usb connected {:?}, tx ready {:?}",
USB_CONNECTED.load(Ordering::SeqCst),
crate::platform::usb::TX_IDLE.load(Ordering::SeqCst)
);
#[cfg(feature = "bao1x-usb")]
// do the main loop through either USB interface or serial port
loop {
let (new_usb_state, new_portsc) = glue::usb_status();
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;
}
// provide feedback when connection is established
if new_usb_state != last_usb_state {
crate::println_d!("new state {:?}", new_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);
}
}
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);
// repl handling; USB is entirely interrupt driven, so there is no loop to handle it
if USB_CONNECTED.load(Ordering::SeqCst) {
// fetch characters from the Rx buffer
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 {
// Handle keyboard events.
critical_section::with(|cs| {
let mut queue = UART_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();
}
}
_ => (),
};
}
// return control to hard-wired serial port when USB is disconnected
if new_portsc != portsc {
portsc = new_portsc;
if glue::is_disconnected(portsc) && new_usb_state == UsbDeviceState::Configured {
crate::println_d!("USB disconnected!");
USB_CONNECTED.store(false, core::sync::atomic::Ordering::SeqCst);
}
}
}
#[cfg(not(feature = "bao1x-usb"))]
// do the main loop through the serial port
// do the main loop through only the serial port
loop {
// Handle keyboard events.
critical_section::with(|cs| {

View file

@ -3,7 +3,6 @@ use bao1x_hal::iox::Iox;
use bao1x_hal::udma;
use utralib::CSR;
use utralib::utra;
use utralib::utra::sysctrl;
use crate::platform::{
debug::setup_rx,
@ -15,151 +14,36 @@ static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::Loc
pub const RAM_SIZE: usize = utralib::generated::HW_SRAM_MEM_LEN;
pub const RAM_BASE: usize = utralib::generated::HW_SRAM_MEM;
pub const FLASH_BASE: usize = utralib::generated::HW_RERAM_MEM;
pub const SIGBLOCK_LEN: usize = 768; // this is adjusted inside builder.rs, in the sign-image invocation
const DATA_SIZE_BYTES: usize = 0x6000;
pub const HEAP_START: usize = RAM_BASE + DATA_SIZE_BYTES;
pub const HEAP_LEN: usize = 1024 * 256;
// scratch page for exceptions located at top of RAM
// NOTE: there is an additional page above this for exception stack
pub const SCRATCH_PAGE: usize = HEAP_START - 8192;
// scratch page for exceptions
// - scratch data is stored in positive offsets from here
// - exception stack is stored in negative offsets from here, hence the +4096
// total occupied area is [HEAP_START + HEAP_LEN..HEAP_START + HEAP_LEN + 8192]
pub const SCRATCH_PAGE: usize = HEAP_START + HEAP_LEN + 4096;
pub const UART_IFRAM_ADDR: usize = bao1x_hal::board::UART_DMA_TX_BUF_PHYS;
// the 800_000_000 setting is tested to work at least on one sample
pub const SYSTEM_CLOCK_FREQUENCY: u32 = 800_000_000;
pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1;
pub fn early_init() {
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
#[cfg(not(feature = "bao1x-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.setup_pin(
IoxPort::PA,
5,
Some(IoxDir::Output),
Some(IoxFunction::Gpio),
None,
Some(IoxEnable::Enable),
None,
Some(IoxDriveStrength::Drive2mA),
);
}
let uart = crate::debug::Uart {};
uart.putc('*' as u32 as u8);
// ASSUME baosec target.
// ASSUME boot1:
// - sets up all the keep-ons & basic pins
let daric_cgu = sysctrl::HW_SYSCTRL_BASE as *mut u32;
unsafe {
// this block is mandatory in all cases to get clocks set into some consistent, expected mode
{
// conservative dividers
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_0.offset()).write_volatile(0x7f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_1.offset()).write_volatile(0x7f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_2.offset()).write_volatile(0x3f7f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_3.offset()).write_volatile(0x1f3f);
daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4.offset()).write_volatile(0x0f1f);
// ungate all clocks
daric_cgu.add(utra::sysctrl::SFR_ACLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_HCLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_ICLKGR.offset()).write_volatile(0xFF);
daric_cgu.add(utra::sysctrl::SFR_PCLKGR.offset()).write_volatile(0xFF);
// commit clocks
daric_cgu.add(utra::sysctrl::SFR_CGUSET.offset()).write_volatile(0x32);
}
// enable DUART
let duart = utra::duart::HW_DUART_BASE as *mut u32;
duart.add(utra::duart::SFR_CR.offset()).write_volatile(0);
// based on ringosc trimming as measured by oscope. this will get precise after we set the PLL.
duart.add(utra::duart::SFR_ETUC.offset()).write_volatile(34);
duart.add(utra::duart::SFR_CR.offset()).write_volatile(1);
}
// sram0 requires 1 wait state for writes
let mut sramtrm = CSR::new(utra::coresub_sramtrm::HW_CORESUB_SRAMTRM_BASE as *mut u32);
sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM0, 0x8);
sramtrm.wo(utra::coresub_sramtrm::SFR_SRAM1, 0x8);
#[cfg(feature = "v0p9")]
{
/*
logic [15:0] trm_ram32kx72 ; assign trm_ram32kx72 = trmdat[0 ]; localparam t_trm IV_trm_ram32kx72 = IV_sram_sp_uhde_inst_sram0;
logic [15:0] trm_ram8kx72 ; assign trm_ram8kx72 = trmdat[1 ]; localparam t_trm IV_trm_ram8kx72 = IV_sram_sp_hde_inst_sram1;
logic [15:0] trm_rf1kx72 ; assign trm_rf1kx72 = trmdat[2 ]; localparam t_trm IV_trm_rf1kx72 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf256x27 ; assign trm_rf256x27 = trmdat[3 ]; localparam t_trm IV_trm_rf256x27 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf512x39 ; assign trm_rf512x39 = trmdat[4 ]; localparam t_trm IV_trm_rf512x39 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_rf128x31 ; assign trm_rf128x31 = trmdat[5 ]; localparam t_trm IV_trm_rf128x31 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_dtcm8kx36 ; assign trm_dtcm8kx36 = trmdat[6 ]; localparam t_trm IV_trm_dtcm8kx36 = IV_sram_sp_hde_inst_tcm;
logic [15:0] trm_itcm32kx18 ; assign trm_itcm32kx18 = trmdat[7 ]; localparam t_trm IV_trm_itcm32kx18 = IV_sram_sp_hde_inst_tcm;
logic [15:0] trm_ifram32kx36 ; assign trm_ifram32kx36 = trmdat[8 ]; localparam t_trm IV_trm_ifram32kx36 = IV_sram_sp_uhde_inst;
logic [15:0] trm_sce_sceram_10k ; assign trm_sce_sceram_10k = trmdat[9 ]; localparam t_trm IV_trm_sce_sceram_10k = IV_sram_sp_hde_inst;
logic [15:0] trm_sce_hashram_3k ; assign trm_sce_hashram_3k = trmdat[10]; localparam t_trm IV_trm_sce_hashram_3k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_aesram_1k ; assign trm_sce_aesram_1k = trmdat[11]; localparam t_trm IV_trm_sce_aesram_1k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_pkeram_4k ; assign trm_sce_pkeram_4k = trmdat[12]; localparam t_trm IV_trm_sce_pkeram_4k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_aluram_3k ; assign trm_sce_aluram_3k = trmdat[13]; localparam t_trm IV_trm_sce_aluram_3k = IV_rf_sp_hde_inst;
logic [15:0] trm_sce_mimmdpram ; assign trm_sce_mimmdpram = trmdat[14]; localparam t_trm IV_trm_sce_mimmdpram = IV_rf_2p_hdc_inst;
logic [15:0] trm_rdram1kx32 ; assign trm_rdram1kx32 = trmdat[15]; localparam t_trm IV_trm_rdram1kx32 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram512x64 ; assign trm_rdram512x64 = trmdat[16]; localparam t_trm IV_trm_rdram512x64 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram128x22 ; assign trm_rdram128x22 = trmdat[17]; localparam t_trm IV_trm_rdram128x22 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_rdram32x16 ; assign trm_rdram32x16 = trmdat[18]; localparam t_trm IV_trm_rdram32x16 = IV_rf_2p_hdc_inst_vex;
logic [15:0] trm_bioram1kx32 ; assign trm_bioram1kx32 = trmdat[19]; localparam t_trm IV_trm_bioram1kx32 = IV_rf_sp_hde_inst_cache;
logic [15:0] trm_tx_fifo128x32 ; assign trm_tx_fifo128x32 = trmdat[20]; localparam t_trm IV_trm_tx_fifo128x32 = IV_rf_2p_hdc_inst;
logic [15:0] trm_rx_fifo128x32 ; assign trm_rx_fifo128x32 = trmdat[21]; localparam t_trm IV_trm_rx_fifo128x32 = IV_rf_2p_hdc_inst;
logic [15:0] trm_fifo32x19 ; assign trm_fifo32x19 = trmdat[22]; localparam t_trm IV_trm_fifo32x19 = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_share ; assign trm_udcmem_share = trmdat[23]; localparam t_trm IV_trm_udcmem_share = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_odb ; assign trm_udcmem_odb = trmdat[24]; localparam t_trm IV_trm_udcmem_odb = IV_rf_2p_hdc_inst;
logic [15:0] trm_udcmem_256x64 ; assign trm_udcmem_256x64 = trmdat[25]; localparam t_trm IV_trm_udcmem_256x64 = IV_rf_2p_hdc_inst;
logic [15:0] trm_acram2kx64 ; assign trm_acram2kx64 = trmdat[26]; localparam t_trm IV_trm_acram2kx64 = IV_sram_sp_uhde_inst_sram0;
logic [15:0] trm_aoram1kx36 ; assign trm_aoram1kx36 = trmdat[27]; localparam t_trm IV_trm_aoram1kx36 = IV_sram_sp_hde_inst;
*/
crate::println!("setting 0.9v sramtrm");
let mut sramtrm = CSR::new(utra::coresub_sramtrm::HW_CORESUB_SRAMTRM_BASE as *mut u32);
sramtrm.wo(utra::coresub_sramtrm::SFR_CACHE, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_ITCM, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_DTCM, 0x3);
sramtrm.wo(utra::coresub_sramtrm::SFR_VEXRAM, 0x1);
let mut rbist = CSR::new(utra::rbist_wrp::HW_RBIST_WRP_BASE as *mut u32);
// bio 0.9v settings
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (19 << 16) | 0b011_000_01_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// vex 0.9v settings
for i in 0..4 {
rbist.wo(utra::rbist_wrp::SFRCR_TRM, ((15 + i) << 16) | 0b001_010_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
// sram 0.9v settings
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (0 << 16) | 0b011_000_01_0_1_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (1 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
crate::println!("setting other 0.9v trims");
// tcm 0.9v
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (6 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (7 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// ifram 0.9v
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (8 << 16) | 0b010_000_00_0_1_000_1_01);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
// sce 0.9V
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (9 << 16) | 0b011_000_00_0_0_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
for i in 0..4 {
rbist.wo(utra::rbist_wrp::SFRCR_TRM, ((10 + i) << 16) | 0b011_000_01_0_1_000_0_00);
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
rbist.wo(utra::rbist_wrp::SFRCR_TRM, (14 << 16) | 0b001_010_00_0_0_000_0_00);
// Ensure SRAM timings are set for 900mV operation before setting fast clock frequency. We will
// be running at full tilt on baosec.
let trim_table = bao1x_hal::sram_trim::get_sram_trim_for_voltage(900);
let mut rbist = CSR::new(utra::rbist_wrp::HW_RBIST_WRP_BASE as *mut u32);
for item in trim_table {
rbist.wo(utra::rbist_wrp::SFRCR_TRM, item.raw_value());
rbist.wo(utra::rbist_wrp::SFRAR_TRM, 0x5a);
}
@ -181,11 +65,13 @@ pub fn early_init() {
data_ptr.add(i).write_volatile(0);
}
for &(offset, data) in &statics_in_rom.poke_table[..statics_in_rom.valid_pokes as usize] {
data_ptr.add(offset as usize).write_volatile(data);
data_ptr
.add(u16::from_le_bytes(offset) as usize / size_of::<u32>())
.write_volatile(u32::from_le_bytes(data));
}
}
// set the clock
// set the clock - should toggle us up to 800MHz FCLK mode.
let perclk = unsafe { init_clock_asic(SYSTEM_CLOCK_FREQUENCY) };
crate::println!("scratch page: {:x}, heap start: {:x}", SCRATCH_PAGE, HEAP_START);
@ -200,10 +86,10 @@ pub fn early_init() {
irq_setup();
enable_irq(utra::irqarray5::IRQARRAY5_IRQ);
udma_uart.write("console up\r\n".as_bytes());
udma_uart.write("baremetal console up\r\n".as_bytes());
crate::debug::USE_CONSOLE.store(true, core::sync::atomic::Ordering::SeqCst);
crate::println!("This debug print should be on the UDMA UART");
// Baosec specific:
// Setup I/Os so things that should be powered off are actually off
bao1x_hal::board::setup_display_pins(&iox);
bao1x_hal::board::setup_memory_pins(&iox);
@ -212,82 +98,6 @@ pub fn early_init() {
bao1x_hal::board::setup_kb_pins(&iox);
bao1x_hal::board::setup_oled_power_pin(&iox);
bao1x_hal::board::setup_trng_power_pin(&iox);
#[cfg(not(feature = "bao1x-evb"))]
{
crate::println!("Engage DCDC2");
let i2c_channel = bao1x_hal::board::setup_i2c_pins(&iox);
use bao1x_hal::udma::GlobalConfig;
let udma_global = GlobalConfig::new();
udma_global.clock(PeriphId::from(i2c_channel), true);
let i2c_ifram = unsafe {
bao1x_hal::ifram::IframRange::from_raw_parts(
bao1x_hal::board::I2C_IFRAM_ADDR,
bao1x_hal::board::I2C_IFRAM_ADDR,
4096,
)
};
let mut i2c = unsafe {
bao1x_hal::udma::I2c::new_with_ifram(i2c_channel, 400_000, perclk, i2c_ifram, &udma_global)
};
if let Ok(mut pmic) = bao1x_hal::axp2101::Axp2101::new(&mut i2c) {
match pmic.set_dcdc(&mut i2c, Some((0.88, true)), bao1x_hal::axp2101::WhichDcDc::Dcdc2) {
Ok(_) => crate::println!("turned on DCDC2"),
Err(_) => crate::println!("couldn't turn off DCDC2"),
}
pmic.set_pwm_mode(&mut i2c, bao1x_hal::axp2101::WhichDcDc::Dcdc2, true).ok();
}
// this does nothing on boards without the FET rework
crate::println!("Engage DCDC2 FET");
iox.set_gpio_pin_value(IoxPort::PA, 5, IoxValue::Low);
}
// code to setup PWM, for testing the PWM pin
if false {
let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32);
iox.setup_pin(IoxPort::PF, 9, Some(IoxDir::Input), Some(IoxFunction::Gpio), None, None, None, None);
iox.setup_pin(
IoxPort::PA,
0,
Some(IoxDir::Output),
Some(IoxFunction::Gpio),
None,
None,
Some(IoxEnable::Disable),
Some(IoxDriveStrength::Drive8mA),
);
iox.setup_pin(
IoxPort::PA,
0,
Some(IoxDir::Output),
Some(IoxFunction::AF3),
None,
None,
Some(IoxEnable::Disable),
Some(IoxDriveStrength::Drive8mA),
);
let mut timer = CSR::new(utra::pwm::HW_PWM_BASE as *mut u32);
timer.wo(utra::pwm::REG_CH_EN, 1);
timer.rmwf(utra::pwm::REG_TIM0_CFG_R_TIMER0_SAW, 1);
timer.rmwf(utra::pwm::REG_TIM0_CH0_TH_R_TIMER0_CH0_TH, 0);
timer.rmwf(utra::pwm::REG_TIM0_CH0_TH_R_TIMER0_CH0_MODE, 3);
let pwm = utra::pwm::HW_PWM_BASE as *mut u32;
// unsafe { pwm.add(2).write_volatile(1 << 16) };
unsafe { pwm.add(2).write_volatile(0) };
timer.rmwf(utra::pwm::REG_TIM0_CMD_R_TIMER0_START, 1);
crate::println!("PWM running on PA0?");
for i in 0..12 {
crate::println!("0x{:2x}: 0x{:08x}", i, unsafe { pwm.add(i).read_volatile() })
}
crate::println!("0x{:2x}: 0x{:08x}", 65, unsafe { pwm.add(65).read_volatile() });
/*
for i in 80..84 {
crate::println!("0x{:2x}: 0x{:08x}", i, unsafe { pwm.add(i).read_volatile() })
}
*/
crate::println!("");
}
}
pub fn setup_timer() {

View file

@ -62,35 +62,6 @@ impl Uart {
}
}
}
fn put_digit(&mut self, d: u8) {
let nyb = d & 0xF;
let c = if nyb < 10 { nyb + 0x30 } else { nyb + 0x61 - 10 };
assert!(c >= 0x30, "conversion failed!");
self.putc(c);
}
pub fn put_hex(&mut self, c: u8) {
self.put_digit(c >> 4);
self.put_digit(c & 0xF);
}
pub fn newline(&mut self) {
self.putc(0xa);
self.putc(0xd);
}
pub fn print_hex_word(&mut self, word: u32) {
for &byte in word.to_be_bytes().iter() {
self.put_hex(byte);
}
}
pub fn tiny_write_str(&mut self, s: &str) {
for c in s.bytes() {
self.putc(c);
}
}
}
use core::fmt::{Error, Write};
@ -231,3 +202,56 @@ pub fn setup_rx(perclk: u32) -> bao1x_hal::udma::Uart {
udma_uart
}
// ==== DUART-only debug print ==== -> this is used for USB feedback to avoid Tx loops on USB
/// Placeholder for debug
pub struct Duart {}
impl Duart {
/// Print a character
pub fn putc(&self, c: u8) {
let base = utra::duart::HW_DUART_BASE as *mut u32;
let mut uart = CSR::new(base);
if uart.rf(utra::duart::SFR_CR_SFR_CR) == 0 {
uart.wfo(utra::duart::SFR_CR_SFR_CR, 1);
}
while uart.r(utra::duart::SFR_SR) != 0 {}
uart.wo(utra::duart::SFR_TXD, c as u32);
}
}
impl Write for Duart {
fn write_str(&mut self, s: &str) -> Result<(), Error> {
for c in s.bytes() {
self.putc(c);
}
Ok(())
}
}
#[macro_use]
/// Hardware debug print module
pub mod debug_print_duart {
#[macro_export]
macro_rules! print_d
{
($($args:tt)+) => ({
use core::fmt::Write;
let _ = write!(crate::debug::Duart {}, $($args)+);
});
}
}
#[macro_export]
macro_rules! println_d
{
() => ({
$crate::print_d!("\r\n")
});
($fmt:expr) => ({
$crate::print_d!(concat!($fmt, "\r\n"))
});
($fmt:expr, $($args:tt)+) => ({
$crate::print_d!(concat!($fmt, "\r\n"), $($args)+)
});
}

View file

@ -47,7 +47,7 @@ pub unsafe extern "C" fn _start_trap() -> ! {
#[rustfmt::skip]
core::arch::asm!(
"csrw mscratch, sp",
"li sp, {scratch_page}", // crate::platform::SCRATCH_PAGE - has to be hard-coded
"li sp, {scratch_page}", // scratch_page, grows up
"sw x1, 0*4(sp)",
// Skip SP for now
"sw x3, 2*4(sp)",
@ -83,23 +83,17 @@ pub unsafe extern "C" fn _start_trap() -> ! {
// Save MEPC
"csrr t0, mepc",
"sw t0, 31*4(sp)",
// Save x1, which was used to calculate the offset. Prior to
// calculating, it was stashed at 0x61006000.
//"li t0, 0x61006000",
//"lw t1, 0*4(t0)",
//"sw t1, 0*4(sp)",
// Finally, save SP
"csrr t0, mscratch",
"sw t0, 1*4(sp)",
// Restore a default stack pointer
"li sp, {heap_base}", // heap base, grows down
"li sp, {scratch_page}", // scratch_page, grows down
// Note that registers $a0-$a7 still contain the arguments
"j _start_trap_rust",
scratch_page = const SCRATCH_PAGE,
heap_base = const HEAP_START
scratch_page = const SCRATCH_PAGE
);
}
_start_trap_aligned();

View file

@ -10,36 +10,6 @@ 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 {
bao1x_hal::usb::driver::CorigineUsb::new(
@ -70,8 +40,6 @@ pub unsafe fn init_usb() {
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);
@ -107,43 +75,11 @@ pub unsafe fn test_usb() {
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;
}
}
*/
crate::println_d!("hw started...");
let mut i = 0;
loop {
// wait for interrupt handler to do something
crate::println!("{}", i);
crate::println_d!("{}", i);
i += 1;
delay(10_000);
// for testing interrupt handler
@ -151,7 +87,7 @@ pub unsafe fn test_usb() {
irqarray19.wfo(utralib::utra::irqarray19::EV_SOFT_TRIGGER, 0x80);
}
} else {
crate::println!("USB core not allocated, skipping USB test");
crate::println_d!("USB core not allocated, skipping USB test");
}
}
@ -211,7 +147,7 @@ fn get_status_request(this: &mut CorigineUsb, request_type: u8, index: u16) {
}
fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
// crate::println!("handle_event: {:x?}", event_trb);
// crate::println_d!("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];
@ -223,14 +159,14 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
// this.print_status(portsc_val);
let portsc = PortSc(portsc_val);
// crate::println!("{:?}", portsc);
// crate::println_d!("{:?}", portsc);
if portsc.prc() && !portsc.pr() {
crate::println!("update_current_speed() - reset done");
crate::println_d!("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");
crate::println_d!("update_current_speed() - cable connect");
this.update_current_speed();
}
@ -241,7 +177,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
CompletionCode::try_from(event_trb.dw2.compl_code()).expect("Invalid completion code");
#[cfg(feature = "verbose-debug")]
crate::println!(
crate::println_d!(
"e_trb {:x} {:x} {:x} {:x}",
event_trb.dw0,
event_trb.dw1,
@ -250,7 +186,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
);
let residual_length = event_trb.dw2.trb_tran_len() as u16;
// update the dequeue pointer
// crate::println!("event_transfer {:x?}", event_trb);
// crate::println_d!("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 {
@ -258,7 +194,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
} else {
udc_ep.deq_pt = AtomicPtr::new(deq_pt as *mut TransferTrbS);
}
// crate::println!("EventTransfer: comp_code {:?}, PEI {}", comp_code, pei);
// crate::println_d!("EventTransfer: comp_code {:?}, PEI {}", comp_code, pei);
let dir = (pei & 1) != 0;
if pei == 0 {
@ -270,19 +206,19 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
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);
crate::println_d!("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" });
// crate::println_d!("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) };
#[cfg(feature = "verbose-debug")]
crate::println!(
crate::println_d!(
"p_trb {:x} {:x} {:x} {:x}",
p_trb.dphi,
p_trb.dplo,
@ -292,9 +228,9 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
f(this, p_trb.dplo as usize, p_trb.dw2.0, 0, residual_length);
}
} else if comp_code == CompletionCode::MissedServiceError {
crate::println!("MissedServiceError");
crate::println_d!("MissedServiceError");
} else {
crate::println!("EventTransfer {:?} event not handled", comp_code);
crate::println_d!("EventTransfer {:?} event not handled", comp_code);
}
}
}
@ -312,7 +248,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
let w_length = setup_pkt.w_length;
/*
crate::println!(
crate::println_d!(
" 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,
@ -325,20 +261,20 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
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");
crate::println_d!("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);
crate::println_d!("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);
// crate::println_d!(" ******* set address done {}", w_value & 0xff);
}
USB_REQ_SET_SEL => {
crate::println!("USB_REQ_SET_SEL");
crate::println_d!("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");
crate::println_d!("SEL_VALUE NOT HANDLED");
/*
crg_udc->sel_value.u1_sel_value = *ep0_buf;
crg_udc->sel_value.u1_pel_value = *(ep0_buf+1);
@ -347,19 +283,19 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
*/
}
USB_REQ_SET_ISOCH_DELAY => {
crate::println!("USB_REQ_SET_ISOCH_DELAY");
crate::println_d!("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 ***");
crate::println_d!("USB_REQ_CLEAR_FEATURE");
crate::println_d!("*** 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 ***");
crate::println_d!("USB_REQ_SET_FEATURE\r\n");
crate::println_d!("*** UNSUPPORTED ***");
/* do set feature */
/*
if crg_udc_get_device_state() == USB_STATE_CONFIGURED {
@ -402,11 +338,11 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
}
}
USB_REQ_GET_DESCRIPTOR => {
crate::println!("USB_REQ_GET_DESCRIPTOR");
crate::println_d!("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");
crate::println_d!("USB_REQ_GET_CONFIGURATION");
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
@ -421,13 +357,13 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
}
USB_REQ_SET_INTERFACE => {
crate::println!("USB_REQ_SET_INTERFACE");
crate::println_d!("USB_REQ_SET_INTERFACE");
this.cur_interface_num = (w_value & 0xF) as u8;
crate::println!("USB_REQ_SET_INTERFACE altsetting {}", this.cur_interface_num);
crate::println_d!("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");
crate::println_d!("USB_REQ_GET_INTERFACE");
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
@ -438,7 +374,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
this.ep0_send(ep0_buf.as_ptr() as usize, 1, 0);
}
_ => {
crate::println!(
crate::println_d!(
"USB_REQ default b_request=0x{:x}, b_request_type=0x{:x}",
setup_pkt.b_request,
setup_pkt.b_request_type
@ -449,7 +385,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
} 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");
crate::println_d!("Mass Storage Reset\r\n");
if (0 == w_value)
&& (InterfaceDescriptor::default_mass_storage().b_interface_number
== w_index as u8)
@ -467,7 +403,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
}
}
0xfe => {
crate::println!("Get Max LUN");
crate::println_d!("Get Max LUN");
if w_index != 0 || w_value != 0 || w_length != 1 {
this.ep_halt(0, USB_RECV);
} else {
@ -483,7 +419,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
}
0x20 => {
// SET_LINE_CODING (host -> device, 7 bytes)
crate::println!("CDC SET_LINE_CODING");
crate::println_d!("CDC SET_LINE_CODING");
let length = w_length as usize;
if length == 7 {
// queue EP0 OUT to receive the line coding structure
@ -495,7 +431,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
}
0x21 => {
// GET_LINE_CODING (device -> host, 7 bytes)
crate::println!("CDC GET_LINE_CODING");
crate::println_d!("CDC GET_LINE_CODING");
let ep0_buf = unsafe {
core::slice::from_raw_parts_mut(
this.ep0_buf.load(Ordering::SeqCst) as *mut u8,
@ -511,14 +447,14 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
}
0x22 => {
// SET_CONTROL_LINE_STATE (host -> device, 0 length)
crate::println!("CDC SET_CONTROL_LINE_STATE, DTR/RTS = {:x}", w_value);
crate::println_d!("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 class request bRequest=0x{:x}", setup_pkt.b_request);
crate::println_d!("Unhandled class request bRequest=0x{:x}", setup_pkt.b_request);
this.ep_halt(0, USB_RECV);
}
}
@ -532,7 +468,7 @@ fn handle_event(this: &mut CorigineUsb, event_trb: &mut EventTrbS) -> CrgEvent {
panic!("data stage needs handling");
}
_ => {
crate::println!("Unexpected trb_type {:?}", event_trb.get_trb_type());
crate::println_d!("Unexpected trb_type {:?}", event_trb.get_trb_type());
}
}
ret

View file

@ -1,6 +1,7 @@
use bao1x_api::{IoGpio, IoSetup};
use bao1x_hal::usb::driver::UsbDeviceState;
use crate::usb;
use crate::{glue, usb};
// Empirically measured PORTSC when the port is unplugged. This might be a brittle way
// to detect if the device is unplugged.
@ -10,7 +11,7 @@ const DISCONNECT_STATE_HS: u32 = 0xc6b; // 11_0_0011_0_1_01_1
pub fn is_disconnected(state: u32) -> bool { state == DISCONNECT_STATE_HS || state == DISCONNECT_STATE }
pub fn setup() -> (UsbDeviceState, u32) {
crate::println!(
crate::println_d!(
"RAM disk starts at {:x} and is {}kiB in length",
usb::RAMDISK_ADDRESS,
usb::RAMDISK_LEN / 1024
@ -25,21 +26,8 @@ pub fn setup() -> (UsbDeviceState, u32) {
// Below is all unsafe because USB is global mutable state
unsafe {
if let Some(ref mut usb_ref) = crate::platform::bao1x::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 bao1x.
}
crate::platform::delay(100);
if poweron >= 4 {
break;
}
}
usb.reset();
usb.init();
usb.start();
usb.update_current_speed();
@ -49,7 +37,7 @@ pub fn setup() -> (UsbDeviceState, u32) {
let last_usb_state = usb.get_device_state();
let portsc = usb.portsc_val();
crate::println!("USB state: {:?}, {:x}", last_usb_state, portsc);
crate::println_d!("USB state: {:?}, {:x}", last_usb_state, portsc);
(last_usb_state, portsc)
} else {
panic!("USB core not allocated, can't proceed!");
@ -78,3 +66,17 @@ pub fn flush_tx() {
}
}
}
pub fn hotplug_usb<T: IoSetup + IoGpio>(iox: &T) -> (UsbDeviceState, u32) {
let (se0_port, se0_pin) = bao1x_hal::board::setup_usb_pins(iox);
iox.set_gpio_pin_value(se0_port, se0_pin, bao1x_api::IoxValue::Low); // put the USB port into SE0
crate::delay(500);
// setup the USB port
let (last_usb_state, portsc) = glue::setup();
crate::delay(500);
// release SE0
iox.set_gpio_pin_value(se0_port, se0_pin, bao1x_api::IoxValue::High);
// USB should have a solid shot of connecting now.
crate::println!("USB device ready");
(last_usb_state, portsc)
}

View file

@ -238,18 +238,18 @@ pub fn usb_ep1_bulk_out_complete(
process_mass_storage_command(this, cbw);
// invalid_cbw = 0;
} else {
crate::println!("Invalid CBW, HALT");
crate::println_d!("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");
crate::println_d!("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");
crate::println_d!("data");
//DATA
if let Some((write_offset, len)) = this.callback_wr.take() {
let app_buf = conjure_app_buf();
@ -266,10 +266,10 @@ pub fn usb_ep1_bulk_out_complete(
csw.send(this);
}
} else {
crate::println!("Data completion reached without destination for data copy! data dropped.");
crate::println_d!("Data completion reached without destination for data copy! data dropped.");
}
} else {
crate::println!("uhhh wtf");
crate::println_d!("uhhh wtf");
}
}
@ -280,14 +280,14 @@ pub fn usb_ep1_bulk_in_complete(
_error: u8,
_residual: u16,
) {
// crate::println!("bulk IN handler");
// crate::println_d!("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.setup_big_read(app_buf, disk, offset, len, None);
this.ms_state = UmsState::DataPhase;
} else {
this.bulk_xfer(1, USB_SEND, CSW_ADDR, 13, 0, 0);
@ -308,7 +308,7 @@ pub fn usb_ep3_bulk_out_complete(
_error: u8,
residual: u16,
) {
// crate::println!("EP3 OUT: {:x} {:x}", info, _error);
// crate::println_d!("EP3 OUT: {:x} {:x}", info, _error);
let actual = CRG_UDC_APP_BUF_LEN - residual as usize;
@ -320,7 +320,7 @@ pub fn usb_ep3_bulk_out_complete(
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);
// crate::println_d!("CDC OUT received {} bytes: {:?}", actual, &buf);
critical_section::with(|cs| {
let mut queue = crate::USB_RX.borrow(cs).borrow_mut();
@ -386,9 +386,9 @@ pub fn usb_ep3_bulk_in_complete(
_error: u8,
_residual: u16,
) {
// crate::println!("EP3 IN");
// crate::println_d!("EP3 IN");
// let length = CRG_UDC_APP_BUF_LEN - residual as usize;
// crate::println!("CDC IN transfer complete, {} bytes sent", length);
// crate::println_d!("CDC IN transfer complete, {} bytes sent", length);
// signal that more stuff can be put into the pipe
TX_IDLE.store(true, Ordering::SeqCst);
@ -405,9 +405,9 @@ pub fn usb_ep2_int_in_complete(
_error: u8,
_residual: u16,
) {
// crate::println!("EP2 INT");
// crate::println_d!("EP2 INT");
// let length = CRG_UDC_APP_BUF_LEN - residual as usize;
// crate::println!("CDC notification sent, {} bytes", length);
// crate::println_d!("CDC notification sent, {} bytes", length);
// Typically sends SERIAL_STATE bitmap (carrier detect etc).
// Ignoring - this is a virtual terminal
@ -489,7 +489,7 @@ fn process_request_sense(this: &mut CorigineUsb, cbw: Cbw) {
csw.residue = 0;
csw.status = 0;
csw.send(this);
// crate::println!("UMS_STATE_STATUS_PHASE\r\n");
// crate::println_d!("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) };
@ -559,7 +559,7 @@ fn process_prevent_allow_medium_removal(this: &mut CorigineUsb, _cbw: Cbw) {
}
fn process_report_capacity(this: &mut CorigineUsb, cbw: Cbw) {
crate::println!("REPORT CAPACITY");
crate::println_d!("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;
@ -633,7 +633,7 @@ fn process_read_command(this: &mut CorigineUsb, cbw: Cbw) {
this.ms_state = UmsState::DataPhase;
return;
}
crate::println!(
crate::println_d!(
"DISK READ address = 0x{:x}, length = 0x{:x}",
RAMDISK_ADDRESS + lba as usize * SECTOR_SIZE as usize,
length
@ -656,7 +656,7 @@ fn process_read_command(this: &mut CorigineUsb, cbw: Cbw) {
}
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.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize, None);
this.ms_state = UmsState::DataPhase;
}
}
@ -679,13 +679,13 @@ fn process_write_command(this: &mut CorigineUsb, cbw: Cbw) {
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.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize, None);
this.ms_state = UmsState::DataPhase;
csw.update_hw();
return;
}
crate::println!(
crate::println_d!(
"Write address = 0x{:x}, length = 0x{:x}",
RAMDISK_ADDRESS + lba as usize * SECTOR_SIZE as usize,
length
@ -734,7 +734,7 @@ fn process_write12_command(this: &mut CorigineUsb, cbw: Cbw) {
length |= (cbw.cdb[9] as u32) << 0;
length *= SECTOR_SIZE as u32;
crate::println!("write12 of {} bytes", length);
crate::println_d!("write12 of {} bytes", length);
if cbw.flags & 0x80 != 0 {
csw.residue = cbw.data_transfer_length;
@ -743,7 +743,7 @@ fn process_write12_command(this: &mut CorigineUsb, cbw: Cbw) {
// 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.setup_big_read(app_buf, disk, lba as usize * SECTOR_SIZE as usize, length as usize, None);
this.ms_state = UmsState::DataPhase;
csw.update_hw();
return;

View file

@ -7,14 +7,6 @@ pub use handlers::*;
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;