From cfe9f4d5c4514d89ba7782c54babc263c1b4bc10 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 15 Jun 2025 23:22:47 +0800 Subject: [PATCH] significant ergonomic improvements to baremetal - IRQ handling added - alloc crate is now available - critical_section support enabled Baseline uart RX handler added. --- baremetal/Cargo.toml | 4 +- baremetal/src/asm.rs | 7 +- baremetal/src/main.rs | 69 ++++---- baremetal/src/platform/artybio.rs | 1 + baremetal/src/platform/artybio/artybio.rs | 93 +++++++++- baremetal/src/platform/artybio/debug.rs | 35 ++++ baremetal/src/platform/artybio/irq.rs | 206 ++++++++++++++++++++++ baremetal/src/platform/artybio/link.x | 4 +- 8 files changed, 381 insertions(+), 38 deletions(-) create mode 100644 baremetal/src/platform/artybio/irq.rs diff --git a/baremetal/Cargo.toml b/baremetal/Cargo.toml index 47d1ebf09..ed67977aa 100644 --- a/baremetal/Cargo.toml +++ b/baremetal/Cargo.toml @@ -10,9 +10,11 @@ xous = "0.9.66" utralib = { version = "0.1.25", optional = true, default-features = false } cramium-hal = { path = "../libs/cramium-hal", optional = true, default-features = false } cramium-api = { path = "../libs/cramium-api", optional = true, default-features = false } -riscv = { version = "0.5.6", package = "xous-riscv" } +vexriscv = { version = "0.5.6", package = "xous-riscv" } +riscv = { version = "0.14.0", features = ["critical-section-single-hart"] } linked_list_allocator = { version = "0.10.5", optional = true } xous-bio-bdma = { path = "../libs/xous-bio-bdma", optional = true, default-features = false } +critical-section = "1.2.0" [features] artybio = [ diff --git a/baremetal/src/asm.rs b/baremetal/src/asm.rs index ab8c1d427..48a38cd55 100644 --- a/baremetal/src/asm.rs +++ b/baremetal/src/asm.rs @@ -35,7 +35,12 @@ pub extern "C" fn abort() -> ! { unsafe { #[rustfmt::skip] asm!( - "300:", // abort + "li t0, 0xf0000000", + "li t1, 0x00f", + "li t2, 0xf00", + "300:", // abort + "sw t1, 0(t0)", + "sw t2, 0(t0)", "j 300b", options(noreturn) ); diff --git a/baremetal/src/main.rs b/baremetal/src/main.rs index 501c96fbe..7f12bc38e 100644 --- a/baremetal/src/main.rs +++ b/baremetal/src/main.rs @@ -1,14 +1,39 @@ #![cfg_attr(not(test), no_main)] #![cfg_attr(not(test), no_std)] +extern crate alloc; // contains runtime setup mod asm; mod platform; +use alloc::collections::VecDeque; +use core::cell::RefCell; + +use critical_section::Mutex; use platform::*; use utralib::*; use xous_bio_bdma::*; +use crate::delay; + +static UART_RX: Mutex>> = Mutex::new(RefCell::new(VecDeque::new())); + +pub fn uart_irq_handler() { + use crate::debug::SerialRead; + let mut uart = crate::debug::Uart {}; + + loop { + match uart.getc() { + Some(c) => { + critical_section::with(|cs| { + UART_RX.borrow(cs).borrow_mut().push_back(c); + }); + } + _ => break, + } + } +} + /// Entrypoint /// /// # Safety @@ -16,17 +41,11 @@ use xous_bio_bdma::*; /// This function is safe to call exactly once. #[export_name = "rust_entry"] pub unsafe extern "C" fn rust_entry() -> ! { - // Initialize the timer, which is needed by the delay() function. - let mut timer = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); - const SYSTEM_CLOCK_FREQUENCY: u32 = 40_000_000; - const SYSTEM_TICK_INTERVAL_MS: u32 = 1; - let ms = SYSTEM_TICK_INTERVAL_MS; - timer.wfo(utra::timer0::EN_EN, 0b0); // disable the timer - // load its values - timer.wfo(utra::timer0::LOAD_LOAD, 0); - timer.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); - // enable the timer - timer.wfo(utra::timer0::EN_EN, 0b1); + // turn on a green LED to indicate boot + let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32); + rgb.wfo(utra::rgb::OUT_OUT, 0x002); + + crate::platform::early_init(); // select a BIO test to run fifo_basic(); @@ -37,6 +56,7 @@ pub unsafe extern "C" fn rust_entry() -> ! { // The RGB LEDs flash when the CPU is running this code. let mut count = 0; let mut rgb = CSR::new(utra::rgb::HW_RGB_BASE as *mut u32); + // 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. loop { @@ -50,27 +70,14 @@ pub unsafe extern "C" fn rust_entry() -> ! { rgb.wfo(utra::rgb::OUT_OUT, count); delay(500); count += 1; - } -} -// Install a panic handler when not running tests. -#[cfg(all(not(test)))] -mod panic_handler { - use core::panic::PanicInfo; - #[panic_handler] - fn handle_panic(_arg: &PanicInfo) -> ! { - crate::println!("{}", _arg); - loop {} - } -} - -/// Delay function that delays a given number of milliseconds. -pub fn delay(ms: usize) { - let mut timer = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); - timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); - for _ in 0..ms { - while timer.rf(utra::timer0::EV_PENDING_ZERO) == 0 {} - timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); + // Handle keyboard events. + critical_section::with(|cs| { + let mut queue = UART_RX.borrow(cs).borrow_mut(); + while let Some(byte) = queue.pop_front() { + crate::println!("got {}", unsafe { char::from_u32_unchecked(byte as u32) }) + } + }); } } diff --git a/baremetal/src/platform/artybio.rs b/baremetal/src/platform/artybio.rs index 3e82c5514..ea4d88fae 100644 --- a/baremetal/src/platform/artybio.rs +++ b/baremetal/src/platform/artybio.rs @@ -1,3 +1,4 @@ pub mod artybio; pub use artybio::*; pub mod debug; +pub mod irq; diff --git a/baremetal/src/platform/artybio/artybio.rs b/baremetal/src/platform/artybio/artybio.rs index 3809721ca..071781a82 100644 --- a/baremetal/src/platform/artybio/artybio.rs +++ b/baremetal/src/platform/artybio/artybio.rs @@ -1,8 +1,95 @@ +use utralib::*; + #[global_allocator] static ALLOCATOR: linked_list_allocator::LockedHeap = linked_list_allocator::LockedHeap::empty(); -pub const RAM_SIZE: usize = utralib::generated::HW_MAIN_RAM_MEM_LEN; +// RAM size has 2 pages taken off the top to make space for exception handlers +pub const RAM_SIZE: usize = utralib::generated::HW_MAIN_RAM_MEM_LEN - 8192; pub const RAM_BASE: usize = utralib::generated::HW_MAIN_RAM_MEM; -#[cfg(all(feature = "cramium-soc", not(feature = "verilator-only")))] -pub fn early_init() {} +// 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 = RAM_BASE + RAM_SIZE; + +// Arbitrarily placing heap at 16k into RAM, with a 32k length +// Total memory is 400k in size +// RAM starts at 256k, giving 144k RAM total +// Bottom 4k is for static data (.bss section) +// next 64k is heap; rest is stack. +pub const ROM_LEN: usize = 1024 * 256; +pub const BSS_LEN: usize = 4 * 1024; +pub const HEAP_START: usize = RAM_BASE + ROM_LEN + BSS_LEN; +pub const HEAP_LEN: usize = 1024 * 64; + +pub const SYSTEM_CLOCK_FREQUENCY: u32 = 40_000_000; +pub const SYSTEM_TICK_INTERVAL_MS: u32 = 1; + +pub fn early_init() { + cache_flush(); + // setup interrupts & enable IRQ handler for characters + crate::irq::irq_setup(); + crate::debug::Uart::enable_rx(true); + crate::irq::enable_irq(utra::uart::UART_IRQ); + + // Initialize the timer, which is needed by the delay() function. + let mut timer = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); + // not using interrupts, this will be polled by delay() + timer.wfo(utra::timer0::EV_ENABLE_ZERO, 0); + timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); + + let ms = SYSTEM_TICK_INTERVAL_MS; + timer.wfo(utra::timer0::EN_EN, 0b0); // disable the timer + // load its values + timer.wfo(utra::timer0::LOAD_LOAD, 0); + timer.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); + // enable the timer + timer.wfo(utra::timer0::EN_EN, 0b1); + + setup_alloc(); +} + +pub fn setup_alloc() { + // Initialize the allocator with heap memory range + crate::println!("Setting up heap @ {:x}-{:x}", HEAP_START, HEAP_START + HEAP_LEN); + crate::println!("Stack @ {:x}-{:x}", HEAP_START + HEAP_LEN, RAM_BASE + RAM_SIZE); + unsafe { + ALLOCATOR.lock().init(HEAP_START as *mut u8, HEAP_LEN); + } +} + +// Install a panic handler when not running tests. +#[cfg(all(not(test)))] +mod panic_handler { + use core::panic::PanicInfo; + #[panic_handler] + fn handle_panic(_arg: &PanicInfo) -> ! { + crate::println!("{}", _arg); + loop {} + } +} + +/// Delay function that delays a given number of milliseconds. +pub fn delay(ms: usize) { + let mut timer = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); + timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); + for _ in 0..ms { + while timer.rf(utra::timer0::EV_PENDING_ZERO) == 0 {} + timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); + } +} + +#[inline(always)] +fn cache_flush() { + unsafe { + #[rustfmt::skip] + core::arch::asm!( + "fence.i", + ".word 0x500F", + "nop", + "nop", + "nop", + "nop", + "nop", + ); + } +} diff --git a/baremetal/src/platform/artybio/debug.rs b/baremetal/src/platform/artybio/debug.rs index 3465ee9e9..449ee7c23 100644 --- a/baremetal/src/platform/artybio/debug.rs +++ b/baremetal/src/platform/artybio/debug.rs @@ -1,4 +1,12 @@ use utralib::generated::*; + +/// A trait for serial like drivers which allows reading from a source. +#[allow(dead_code)] +pub trait SerialRead { + /// Read a single byte. + fn getc(&mut self) -> Option; +} + pub struct Uart { // pub base: *mut u32, } @@ -11,6 +19,16 @@ impl Uart { while uart.r(utra::uart::TXFULL) != 0 {} uart.wo(utra::uart::RXTX, c as u32) } + + pub fn enable_rx(enable: bool) { + let base = utra::uart::HW_UART_BASE as *mut u32; + let mut uart = CSR::new(base); + if enable { + uart.rmwf(utra::uart::EV_ENABLE_RX, 1); + } else { + uart.rmwf(utra::uart::EV_ENABLE_RX, 0); + } + } } use core::fmt::{Error, Write}; @@ -23,6 +41,23 @@ impl Write for Uart { } } +impl SerialRead for Uart { + fn getc(&mut self) -> Option { + let base = utra::uart::HW_UART_BASE as *mut u32; + let mut uart = CSR::new(base); + // If EV_PENDING_RX is 1, return the pending character. + // Otherwise, return None. + match uart.rf(utra::uart::RXEMPTY_RXEMPTY) { + 1 => None, + _ => { + let ret = Some(uart.r(utra::uart::RXTX) as u8); + uart.wfo(utra::uart::EV_PENDING_RX, 1); + ret + } + } + } +} + #[macro_use] pub mod debug_print_hardware { #[macro_export] diff --git a/baremetal/src/platform/artybio/irq.rs b/baremetal/src/platform/artybio/irq.rs new file mode 100644 index 000000000..3b19b3de7 --- /dev/null +++ b/baremetal/src/platform/artybio/irq.rs @@ -0,0 +1,206 @@ +use riscv::register::{mcause, mie, mstatus}; +use vexriscv::register::vexriscv::{mim, mip}; + +use crate::*; + +pub fn irq_setup() { + unsafe { + #[rustfmt::skip] + core::arch::asm!( + // Set trap handler, which will be called + // on interrupts and cpu faults + "la t0, _start_trap", // this first one forces the nop sled symbol to be generated + "la t0, _start_trap_aligned", // this is the actual target + "csrw mtvec, t0", + ); + } + + mim::write(0x0); // first make sure everything is disabled, so we aren't OR'ing in garbage + unsafe { + mstatus::set_mie(); + } + // must enable external interrupts on the CPU for any of the above to matter + unsafe { mie::set_mext() }; +} + +pub fn enable_irq(irq_no: usize) { + // Note that the vexriscv "IRQ Mask" register is inverse-logic -- + // that is, setting a bit in the "mask" register unmasks (i.e. enables) it. + mim::write(mim::read() | (1 << irq_no)); + // must enable external interrupts on the CPU for any of the above to matter + unsafe { mie::set_mext() }; +} + +#[export_name = "_start_trap"] +// #[repr(align(4))] // can't do this yet. +#[inline(never)] +pub unsafe extern "C" fn _start_trap() -> ! { + loop { + // install a NOP sled before _start_trap() until https://github.com/rust-lang/rust/issues/82232 is stable + core::arch::asm!("nop", "nop", "nop", "nop"); + #[export_name = "_start_trap_aligned"] + pub unsafe extern "C" fn _start_trap_aligned() { + #[rustfmt::skip] + core::arch::asm!( + "csrw mscratch, sp", + "li sp, 0x40062000", // crate::platform::SCRATCH_PAGE - has to be hard-coded + "sw x1, 0*4(sp)", + // Skip SP for now + "sw x3, 2*4(sp)", + "sw x4, 3*4(sp)", + "sw x5, 4*4(sp)", + "sw x6, 5*4(sp)", + "sw x7, 6*4(sp)", + "sw x8, 7*4(sp)", + "sw x9, 8*4(sp)", + "sw x10, 9*4(sp)", + "sw x11, 10*4(sp)", + "sw x12, 11*4(sp)", + "sw x13, 12*4(sp)", + "sw x14, 13*4(sp)", + "sw x15, 14*4(sp)", + "sw x16, 15*4(sp)", + "sw x17, 16*4(sp)", + "sw x18, 17*4(sp)", + "sw x19, 18*4(sp)", + "sw x20, 19*4(sp)", + "sw x21, 20*4(sp)", + "sw x22, 21*4(sp)", + "sw x23, 22*4(sp)", + "sw x24, 23*4(sp)", + "sw x25, 24*4(sp)", + "sw x26, 25*4(sp)", + "sw x27, 26*4(sp)", + "sw x28, 27*4(sp)", + "sw x29, 28*4(sp)", + "sw x30, 29*4(sp)", + "sw x31, 30*4(sp)", + + // 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, 0x40064000", // last page of RAM, grows down + + // Note that registers $a0-$a7 still contain the arguments + "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 + // and there seems to be no way to refer directly to a symbol? the `sym` directive wants + // to refer to an address, not a constant. + ); + } + _start_trap_aligned(); + core::arch::asm!("nop", "nop", "nop", "nop"); + } +} + +#[export_name = "_resume_context"] +#[inline(never)] +pub unsafe extern "C" fn _resume_context(registers: u32) -> ! { + #[rustfmt::skip] + core::arch::asm!( + "move sp, {registers}", + + "lw x1, 0*4(sp)", + // Skip SP for now + "lw x3, 2*4(sp)", + "lw x4, 3*4(sp)", + "lw x5, 4*4(sp)", + "lw x6, 5*4(sp)", + "lw x7, 6*4(sp)", + "lw x8, 7*4(sp)", + "lw x9, 8*4(sp)", + "lw x10, 9*4(sp)", + "lw x11, 10*4(sp)", + "lw x12, 11*4(sp)", + "lw x13, 12*4(sp)", + "lw x14, 13*4(sp)", + "lw x15, 14*4(sp)", + "lw x16, 15*4(sp)", + "lw x17, 16*4(sp)", + "lw x18, 17*4(sp)", + "lw x19, 18*4(sp)", + "lw x20, 19*4(sp)", + "lw x21, 20*4(sp)", + "lw x22, 21*4(sp)", + "lw x23, 22*4(sp)", + "lw x24, 23*4(sp)", + "lw x25, 24*4(sp)", + "lw x26, 25*4(sp)", + "lw x27, 26*4(sp)", + "lw x28, 27*4(sp)", + "lw x29, 28*4(sp)", + "lw x30, 29*4(sp)", + "lw x31, 30*4(sp)", + + // Restore SP + "lw x2, 1*4(sp)", + "mret", + registers = in(reg) registers, + ); + loop {} +} + +/// Just handles specific traps for testing CPU interactions. Doesn't do anything useful with the traps. +#[export_name = "_start_trap_rust"] +pub extern "C" fn trap_handler( + _a0: usize, + _a1: usize, + _a2: usize, + _a3: usize, + _a4: usize, + _a5: usize, + _a6: usize, + _a7: usize, +) -> ! { + let cause: mcause::Mcause = mcause::read(); + crate::println!("cause {:x}", cause.bits()); + // 2 is illegal instruction + if cause.bits() == 2 { + // skip past the illegal instruction, in case that's what we want to do... + unsafe { + #[rustfmt::skip] + core::arch::asm!( + "csrr t0, mepc", + "addi t0, t0, 4", + "csrw mepc, t0", + ); + } + // ...but also panic. + panic!("Illegal Instruction"); + } else if cause.bits() == 4 { + let epc = riscv::register::mepc::read(); + panic!("Load address misaligned @ {:x}", epc); + } else if cause.bits() == 6 { + let epc = riscv::register::mepc::read(); + panic!("Store address misaligned @ {:x}", epc); + } else if cause.bits() == 0x8000_000b { + // external machine interrupt + // external interrupt. find out which ones triggered it, and clear the source. + let irqs_pending = mip::read(); + if (irqs_pending & (1 << utra::timer0::TIMER0_IRQ)) != 0 { + let ms = SYSTEM_TICK_INTERVAL_MS; + let mut timer0 = CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); + timer0.wfo(utra::timer0::EV_PENDING_ZERO, 1); + timer0.wfo(utra::timer0::RELOAD_RELOAD, (SYSTEM_CLOCK_FREQUENCY / 1_000) * ms); + } else if (irqs_pending & (1 << utra::uart::UART_IRQ)) != 0 { + crate::uart_irq_handler(); + } + } + + // re-enable interrupts + unsafe { mie::set_mext() }; + + // crate::println!("restoring from {:x}", crate::platform::SCRATCH_PAGE); + unsafe { _resume_context(crate::platform::SCRATCH_PAGE as u32) }; +} diff --git a/baremetal/src/platform/artybio/link.x b/baremetal/src/platform/artybio/link.x index 0ddbda0cd..b1a3dbb64 100644 --- a/baremetal/src/platform/artybio/link.x +++ b/baremetal/src/platform/artybio/link.x @@ -1,7 +1,7 @@ MEMORY { - FLASH : ORIGIN = 0x40000000, LENGTH = 4M - RAM : ORIGIN = 0x40400000, LENGTH = 4M + FLASH : ORIGIN = 0x40000000, LENGTH = 256k + RAM : ORIGIN = 0x40040000, LENGTH = 90k } REGION_ALIAS("REGION_TEXT", FLASH);