From d1d09988000d9f61a3fcbb3d574bfcbcdad08519 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 11 Jan 2026 21:22:52 +0800 Subject: [PATCH 01/13] link to pre-built tested CI artifacts --- README-baochip.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README-baochip.md b/README-baochip.md index 87ff35d63..8d97d0d0d 100644 --- a/README-baochip.md +++ b/README-baochip.md @@ -34,6 +34,9 @@ Regardless of the board, the `bao1x` chip comes from the factory programmed with #### Detailed Boot1 Update for Dabao Users +[!TIP] +You can fetch pre-built verions of the .uf2 files from the CI pipeline [here](https://ci.betrusted.io/latest-ci/baochip/bootloader/). Once Baochip hits release status, we'll drop a link for a stable release version here as well. + 1. Build alt-boot1: `cargo xtask bao1x-alt-boot1` 2. Build boot1: `cargo xtask bao1x-boot1` 3. Plug the dabao board into the host. Confirm that the mass storage device has the volume label of `BAOCHIP`. From 7b697c09188e8e2abd4c251aaae091bc41dd6096 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:08:41 +0800 Subject: [PATCH 02/13] add note to serial console that console has moved to USB this makes it clear that when USB is plugged in, the console session on the hard serial port migrates to the USB serial port. --- bao1x-boot/boot1/src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/bao1x-boot/boot1/src/main.rs b/bao1x-boot/boot1/src/main.rs index 76e937fa2..9ec98e90e 100644 --- a/bao1x-boot/boot1/src/main.rs +++ b/bao1x-boot/boot1/src/main.rs @@ -246,6 +246,7 @@ pub unsafe extern "C" fn rust_entry() -> ! { crate::println_d!("new state {:?}", new_usb_state); if new_usb_state == UsbDeviceState::Configured { crate::println!("USB is connected!"); + crate::println!("Console moved to USB serial"); last_usb_state = new_usb_state; USB_CONNECTED.store(true, core::sync::atomic::Ordering::SeqCst); if let Some(ref mut sh1107) = oled { From 86ab6b02c99ac26dadd24d8f0cfe60f7d22fe9fb Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:09:40 +0800 Subject: [PATCH 03/13] add proc info commands to dabao target --- apps-dabao/dabao-console/src/cmds/test.rs | 58 +++++++++++++++++------ 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/apps-dabao/dabao-console/src/cmds/test.rs b/apps-dabao/dabao-console/src/cmds/test.rs index 4b9b96eac..e1f5c1525 100644 --- a/apps-dabao/dabao-console/src/cmds/test.rs +++ b/apps-dabao/dabao-console/src/cmds/test.rs @@ -15,25 +15,12 @@ impl<'a> ShellCmdApi<'a> for Test { let mut ret = String::new(); #[allow(unused_variables)] - let helpstring = "Test commands. See code for options."; + let helpstring = "test [proc] [freemem] [interrupts] [panic] [timer] [env]"; let mut tokens = args.split(' '); if let Some(sub_cmd) = tokens.next() { match sub_cmd { - "mac" => { - let mut md = bio_lib::mac_demo::MacDemo::new().unwrap(); - let a = [0, -1, 32, 6, -10, 5]; - let b = 7; - let hw = md.mac_hw(&a, b); - let sw = md.mac_sw(&a, b); - log::info!("result: {}, {}", hw, sw); - if hw == sw { - writeln!(ret, "pass").unwrap(); - } else { - writeln!(ret, "fail").unwrap(); - } - } "timer" => { let start = _env.ticktimer.elapsed_ms(); log::info!("Starting test"); @@ -46,6 +33,49 @@ impl<'a> ShellCmdApi<'a> for Test { } } } + "panic" => { + log::info!("System will panic now"); + panic!("test panic"); + } + "proc" => { + // hard coded - debug feature - if the platform ABI changes its name or opcode map this + // can break, but also this routine is not meant for public + // consumption and coding it here avoids breaking dependencies to the Xous API crate. + let page_buf = xous::PageBuf::new(); + xous::rsyscall(xous::SysCall::PlatformSpecific(2, page_buf.as_ptr(), 0, 0, 0, 0, 0)) + .unwrap(); + + log::info!("Process listing:"); + for line in page_buf.as_str().lines() { + log::info!("{}", line); + } + } + "freemem" => { + // hard coded - debug feature - if the platform ABI changes its name or opcode map this + // can break, but also this routine is not meant for public + // consumption and coding it here avoids breaking dependencies to the Xous API crate. + let page_buf = xous::PageBuf::new(); + xous::rsyscall(xous::SysCall::PlatformSpecific(1, page_buf.as_ptr(), 0, 0, 0, 0, 0)) + .unwrap(); + + log::info!("RAM usage:"); + for line in page_buf.as_str().lines() { + log::info!("{}", line); + } + } + "interrupts" => { + // hard coded - debug feature - if the platform ABI changes its name or opcode map this + // can break, but also this routine is not meant for public + // consumption and coding it here avoids breaking dependencies to the Xous API crate. + let page_buf = xous::PageBuf::new(); + xous::rsyscall(xous::SysCall::PlatformSpecific(3, page_buf.as_ptr(), 0, 0, 0, 0, 0)) + .unwrap(); + + log::info!("Interrupt handlers:"); + for line in page_buf.as_str().lines() { + log::info!("{}", line); + } + } "env" => { log::info!("{:?}", std::env::vars()); } From 284e639453d30401cb02eb684301a3f2ade77a7a Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:10:17 +0800 Subject: [PATCH 04/13] adjust xtask default features - dabao now includes debug-proc by default - gdb-stub now passes to both kernel and user programs, so that uart switching can be achieved - print-panics activated in the kernel, so we can see the panic messages. They had disappeared for a while, and didn't notice. --- xtask/src/main.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bc497c76a..671fb7610 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -200,6 +200,7 @@ fn main() -> Result<(), Box> { let gdb_stub = env::args().filter(|x| x == "--gdb-stub").count() != 0; if gdb_stub { builder.add_kernel_feature("gdb-stub"); + builder.add_feature("gdb-stub"); } if env::args().filter(|x| x == "--debug-loader").count() != 0 { builder.add_loader_feature("debug-print"); @@ -755,6 +756,7 @@ fn main() -> Result<(), Box> { builder.set_swap(0, bao1x_api::offsets::baosec::SWAP_RAM_LEN as _); } builder.add_loader_feature("swap"); + builder.add_kernel_feature("print-panics"); builder.add_kernel_feature("swap"); builder.add_feature("swap"); @@ -914,6 +916,8 @@ fn main() -> Result<(), Box> { builder.add_loader_feature("debug-print"); builder.add_kernel_feature("v2p"); + builder.add_kernel_feature("print-panics"); + builder.add_kernel_feature("debug-proc"); match task.as_deref() { Some("dabao") => builder.target_bao1x_soc(), _ => panic!("should be unreachable"), From 533607b9ec96a307e721e55398566fc128c03903 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:13:39 +0800 Subject: [PATCH 05/13] gdb-stub: disable userspace console The serial port going to the userspace console is disabled to allow for gdb access to the kernel. --- services/xous-log/Cargo.toml | 2 ++ services/xous-log/src/platform/bao1x/debug.rs | 7 +++-- .../src/platform/bao1x/implementation.rs | 31 ++++++++++--------- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/services/xous-log/Cargo.toml b/services/xous-log/Cargo.toml index 52b6095e8..aecda10fa 100644 --- a/services/xous-log/Cargo.toml +++ b/services/xous-log/Cargo.toml @@ -45,6 +45,8 @@ board-baosor = ["bao1x-hal/board-baosor"] board-dabao = ["bao1x-hal/board-dabao"] hosted-baosec = [] hwsim = [] +# when activated, disables the console so the kernel GDB stub can claim it. +gdb-stub = [] precursor = ["utralib/precursor"] hosted = ["utralib/hosted"] diff --git a/services/xous-log/src/platform/bao1x/debug.rs b/services/xous-log/src/platform/bao1x/debug.rs index b9803b411..dd86c1b66 100644 --- a/services/xous-log/src/platform/bao1x/debug.rs +++ b/services/xous-log/src/platform/bao1x/debug.rs @@ -1,6 +1,6 @@ use core::fmt::{Error, Write}; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] use bao1x_hal::udma; #[macro_export] @@ -28,9 +28,10 @@ macro_rules! println pub struct Uart {} // this is a hack to bypass an explicit initialization/allocation step for the debug structure +#[cfg(not(feature = "gdb-stub"))] pub static mut DEFAULT_UART_ADDR: *mut usize = 0x0000_0000 as *mut usize; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] impl Uart { pub fn putc(&self, c: u8) { // check that we've been initialized before attempting to send any characters... @@ -70,7 +71,9 @@ impl Uart { } impl Write for Uart { + #[allow(unused_variables)] fn write_str(&mut self, s: &str) -> Result<(), Error> { + #[cfg(not(feature = "gdb-stub"))] for c in s.bytes() { self.putc(c); } diff --git a/services/xous-log/src/platform/bao1x/implementation.rs b/services/xous-log/src/platform/bao1x/implementation.rs index 04af4bb48..4b8424f42 100644 --- a/services/xous-log/src/platform/bao1x/implementation.rs +++ b/services/xous-log/src/platform/bao1x/implementation.rs @@ -1,28 +1,27 @@ use core::fmt::{Error, Write}; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] use std::pin::Pin; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] use bao1x_hal::board::UART_DMA_TX_BUF_PHYS; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] use bao1x_hal::udma; +#[cfg(not(feature = "gdb-stub"))] use utralib::generated::*; pub struct Output {} -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] pub static mut UART_DMA_TX_BUF_VIRT: *mut u8 = 0x0000_0000 as *mut u8; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] pub static mut UART_IRQ: Option>> = None; -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] pub static mut KBD_CONN: u32 = 0; pub fn init() -> Output { - // TODO: migrate this to a "proper" UART that is available on SoC hardware, but for now all we have access - // to is the DUART. - #[cfg(all(feature = "bao1x", not(feature = "hwsim")))] + #[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] let uart = xous::syscall::map_memory( xous::MemoryAddress::new(utra::udma_uart_2::HW_UDMA_UART_2_BASE), None, @@ -30,11 +29,11 @@ pub fn init() -> Output { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't map serial port"); - #[cfg(all(feature = "bao1x", not(feature = "hwsim")))] + #[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] unsafe { crate::platform::debug::DEFAULT_UART_ADDR = uart.as_mut_ptr() as _ }; - #[cfg(all(feature = "bao1x", not(feature = "hwsim")))] + #[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] { // Note: for the TX buf, we allocate a pre-reserved portion of IFRAM as our // DMA buffer. We do *not* use the IFRAM allocator in `bao1x-hal-service` because @@ -80,13 +79,14 @@ pub fn init() -> Output { unsafe { crate::platform::debug::DEFAULT_UART_ADDR = uart.as_mut_ptr() as _ }; + #[cfg(not(feature = "gdb-stub"))] println!("Mapped UART @ {:08x}", uart.as_ptr() as usize); println!("Process: map success!"); Output {} } -#[cfg(all(feature = "bao1x", not(feature = "hwsim")))] +#[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] fn uart_handler(_irq_no: usize, _arg: *mut usize) { let mut uart = unsafe { udma::Uart::get_handle( @@ -131,8 +131,9 @@ pub struct OutputWriter {} #[allow(dead_code)] impl OutputWriter { + #[allow(unused_variables)] pub fn putc(&self, c: u8) { - #[cfg(all(feature = "bao1x", not(feature = "hwsim")))] + #[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] { // safety: safe to call as long as the raw parts are initialized and we exclusively // own it; and the UART has been initialized. For this peripheral, initialization @@ -161,7 +162,7 @@ impl OutputWriter { /// bytes written. This is mostly compatible with `std::io::Write`, /// except it is infallible. pub fn write(&mut self, buf: &[u8]) -> usize { - #[cfg(all(feature = "bao1x", not(feature = "hwsim")))] + #[cfg(all(feature = "bao1x", not(feature = "hwsim"), not(feature = "gdb-stub")))] { // safety: safe to call as long as the raw parts are initialized and we exclusively // own it; and the UART has been initialized. For this peripheral, initialization @@ -185,6 +186,8 @@ impl OutputWriter { } buf.len() } + #[cfg(feature = "gdb-stub")] + buf.len() // just fake the write } pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { Ok(self.write(buf)) } From d380ea1ab6059424b56d07d5931e4843f729d6d2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:14:13 +0800 Subject: [PATCH 06/13] add gdbuart implementation for bao1x --- kernel/src/platform/bao1x/gdbuart.rs | 240 +++++++++++++++++++++++++++ 1 file changed, 240 insertions(+) create mode 100644 kernel/src/platform/bao1x/gdbuart.rs diff --git a/kernel/src/platform/bao1x/gdbuart.rs b/kernel/src/platform/bao1x/gdbuart.rs new file mode 100644 index 000000000..e5f0347f5 --- /dev/null +++ b/kernel/src/platform/bao1x/gdbuart.rs @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: 2020 Sean Cross +// SPDX-FileCopyrightText: 2022 Foundation Devices, Inc. +// SPDX-License-Identifier: Apache-2.0 + +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + +use utralib::generated::*; +use xous_kernel::{MemoryFlags, MemoryType}; + +use crate::{ + PID, + io::{SerialRead, SerialWrite}, + mem::MemoryManager, +}; + +static UART_CALLBACK_POINTER: AtomicUsize = AtomicUsize::new(0); +static UART_COUNT: AtomicUsize = AtomicUsize::new(0); +static UART_ALLOCATED: AtomicBool = AtomicBool::new(false); + +/// UART virtual address. +/// +/// See https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md +pub const GDB_UART_VADDR: usize = 0xffcc_0000; +pub const GDB_UART_IFRAM_VADDR: usize = 0xffcc_1000; +pub const GDB_UART_IRQ_VADDR: usize = 0xffcc_2000; + +pub const GDB_BAUD: u32 = 115200; + +/// UART peripheral driver. +pub struct GdbUart { + uart_csr: CSR, + uart_irq: CSR, + constructed: bool, +} + +fn gdbuart_isr(_irq_no: usize, _arg: *mut usize) { + let target = UART_CALLBACK_POINTER.load(Ordering::Relaxed); + // Return if uninitialized + if target == 0 { + return; + } + + let cb = unsafe { core::mem::transmute::<_, fn(&mut GdbUart)>(target) }; + cb(&mut GdbUart { + uart_csr: CSR::new(GDB_UART_VADDR as *mut u32), + uart_irq: CSR::new(GDB_UART_IRQ_VADDR as *mut u32), + constructed: false, + }); +} + +impl GdbUart { + pub fn new(callback: fn(&mut Self)) -> Option { + UART_CALLBACK_POINTER.store(callback as usize, Ordering::Relaxed); + if UART_COUNT.fetch_add(1, Ordering::Relaxed) != 0 { + panic!("UART has multiple consumers!"); + } + + Some(GdbUart { + uart_csr: CSR::new(GDB_UART_VADDR as *mut u32), + uart_irq: CSR::new(GDB_UART_IRQ_VADDR as *mut u32), + constructed: true, + }) + } + + pub fn enable(&mut self) { + self.allocate(); + self.uart_csr.rmwf(utra::irqarray5::EV_ENABLE_UART2_RX, 1); + let mut udma_uart = unsafe { + // safety: this is safe to call, because we set up clock and events prior to calling new. + bao1x_hal::udma::Uart::get_handle( + self.uart_csr.base() as usize, + bao1x_hal::board::UART_DMA_TX_BUF_PHYS, + GDB_UART_IFRAM_VADDR, + ) + }; + udma_uart.set_baud(GDB_BAUD, bao1x_hal::clocks::PERCLK_HZ); + udma_uart.setup_async_read(); + } + + pub fn allocate(&mut self) { + if UART_ALLOCATED.compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + + // Map the UART CSR + MemoryManager::with_mut(|memory_manager| { + memory_manager + .map_range( + utralib::utra::udma_uart_2::HW_UDMA_UART_2_BASE as *mut u8, + (GDB_UART_VADDR & !4095) as *mut u8, + 4096, + PID::new(1).unwrap(), + MemoryFlags::R | MemoryFlags::W, + MemoryType::Default, + ) + .expect("unable to map serial port"); + memory_manager + .map_range( + bao1x_hal::board::UART_DMA_TX_BUF_PHYS as *mut u8, + (GDB_UART_IFRAM_VADDR & !4095) as *mut u8, + 4096, + PID::new(1).unwrap(), + MemoryFlags::R | MemoryFlags::W, + MemoryType::Default, + ) + .expect("unable to map serial port"); + memory_manager + .map_range( + utralib::utra::irqarray5::HW_IRQARRAY5_BASE as *mut u8, + (GDB_UART_IRQ_VADDR & !4095) as *mut u8, + 4096, + PID::new(1).unwrap(), + MemoryFlags::R | MemoryFlags::W, + MemoryType::Default, + ) + .expect("unable to map serial port"); + }); + + xous_kernel::claim_interrupt(utra::irqarray5::IRQARRAY5_IRQ, gdbuart_isr, core::ptr::null_mut()) + .expect("Couldn't claim debug interrupt"); + } + + #[allow(dead_code)] + pub fn deallocate(&mut self) { + self.uart_csr.rmwf(utra::irqarray5::EV_ENABLE_UART2_RX, 0); + + // Note: This can cause an ABA error if it's multi-threaded and `.allocate()` + // is called at the same time as `.deallocate()`. + if UART_ALLOCATED.compare_exchange(true, false, Ordering::Relaxed, Ordering::Relaxed).is_err() { + return; + } + + xous_kernel::rsyscall(xous_kernel::SysCall::FreeInterrupt(utra::irqarray5::IRQARRAY5_IRQ)).unwrap(); + + MemoryManager::with_mut(|memory_manager| { + memory_manager.unmap_page((GDB_UART_VADDR & !4095) as *mut usize).unwrap(); + memory_manager.unmap_page((GDB_UART_IFRAM_VADDR & !4095) as *mut usize).unwrap(); + memory_manager.unmap_page((GDB_UART_IRQ_VADDR & !4095) as *mut usize).unwrap(); + }); + } +} + +impl Drop for GdbUart { + fn drop(&mut self) { + // Sometimes (e.g. during IRQs) we synthesize a GdbUart from nothing. + if !self.constructed { + return; + } + + if UART_COUNT.fetch_sub(1, Ordering::Relaxed) != 1 { + panic!("UART had multiple consumers!"); + } + + // Disable the IRQ until we re-enable it again when the server is reconstituted + self.uart_csr.rmwf(utra::irqarray5::EV_ENABLE_UART2_RX, 0); + } +} + +impl SerialWrite for GdbUart { + fn putc(&mut self, c: u8) { + let buf: [u8; 1] = [c]; + let mut udma_uart = unsafe { + // safety: this is safe to call, because we set up clock and events prior to calling new. + bao1x_hal::udma::Uart::get_handle( + self.uart_csr.base() as usize, + bao1x_hal::board::UART_DMA_TX_BUF_PHYS, + GDB_UART_IFRAM_VADDR, + ) + }; + udma_uart.write(&buf); + } +} + +impl SerialRead for GdbUart { + fn getc(&mut self) -> Option { + // might be a bit too big a hammer to clear everything pending, but this gets us moving + self.uart_irq.wo(utra::irqarray5::EV_PENDING, 0xFFFF_FFFF); + + let mut uart = unsafe { + bao1x_hal::udma::Uart::get_handle( + self.uart_csr.base() as usize, + bao1x_hal::board::UART_DMA_TX_BUF_PHYS, + GDB_UART_IFRAM_VADDR, + ) + }; + + let mut c: u8 = 0; + /* + println!( + "{:x} {:x} {:x} {:x} {:x}", + uart.csr() + .base() + .add(bao1x_hal::udma::Bank::Custom.into()) + .add(bao1x_hal::udma::UartReg::Status.into()) + .read_volatile(), + uart.csr() + .base() + .add(bao1x_hal::udma::Bank::Custom.into()) + .add(bao1x_hal::udma::UartReg::Setup.into()) + .read_volatile(), + uart.csr() + .base() + .add(bao1x_hal::udma::Bank::Custom.into()) + .add(bao1x_hal::udma::UartReg::Error.into()) + .read_volatile(), + uart.csr() + .base() + .add(bao1x_hal::udma::Bank::Custom.into()) + .add(bao1x_hal::udma::UartReg::Valid.into()) + .read_volatile(), + uart.csr() + .base() + .add(bao1x_hal::udma::Bank::Custom.into()) + .add(bao1x_hal::udma::UartReg::Data.into()) + .read_volatile() + ); */ + if uart.read_async(&mut c) != 0 { + print!("{}", char::from_u32_unchecked(c as u32)); + Some(c) + } else { + return None; + } + } +} + +impl gdbstub::conn::Connection for GdbUart { + type Error = &'static str; + + fn write(&mut self, byte: u8) -> Result<(), Self::Error> { + self.putc(byte); + Ok(()) + } + + fn flush(&mut self) -> Result<(), Self::Error> { Ok(()) } + + fn on_session_start(&mut self) -> Result<(), Self::Error> { + self.enable(); + Ok(()) + } +} From d39087b2e9cc0aaacc6bad7d7859279deb0dd9fc Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:15:26 +0800 Subject: [PATCH 07/13] cleanup warnings in gdb debug and cleanup debug shell for bao1x bao1x debug shell has no input, so removing the help functions will save space in the kernel --- kernel/src/debug/gdb.rs | 6 ++++++ kernel/src/debug/gdb/multi_thread_base.rs | 6 +++--- kernel/src/debug/gdb/target.rs | 4 ++-- kernel/src/debug/shell.rs | 15 +++++++++------ 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/kernel/src/debug/gdb.rs b/kernel/src/debug/gdb.rs index d050087a0..9efb1cbaa 100644 --- a/kernel/src/debug/gdb.rs +++ b/kernel/src/debug/gdb.rs @@ -5,6 +5,9 @@ use gdbstub::stub::{GdbStubBuilder, GdbStubError, MultiThreadStopReason}; use gdbstub::target::Target; use crate::io::SerialRead; +#[cfg(feature = "bao1x")] +use crate::platform::bao1x::gdbuart::GdbUart; +#[cfg(not(feature = "bao1x"))] use crate::platform::precursor::gdbuart::GdbUart; mod breakpoints; @@ -29,6 +32,9 @@ pub struct XousTarget { pub struct XousDebugState<'a> { pub target: XousTarget, + #[cfg(feature = "bao1x")] + pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::bao1x::gdbuart::GdbUart>, + #[cfg(not(feature = "bao1x"))] pub server: GdbStubStateMachine<'a, XousTarget, crate::platform::precursor::gdbuart::GdbUart>, } diff --git a/kernel/src/debug/gdb/multi_thread_base.rs b/kernel/src/debug/gdb/multi_thread_base.rs index 894983179..ec46d6de5 100644 --- a/kernel/src/debug/gdb/multi_thread_base.rs +++ b/kernel/src/debug/gdb/multi_thread_base.rs @@ -75,8 +75,8 @@ impl MultiThreadBase for XousTarget { _tid: Tid, // same address space for each core ) -> TargetResult<(), Self> { let current_addr = start_addr as usize; - if (current_addr + data.len()) >= crate::arch::mem::USER_AREA_END - || (current_addr >= crate::arch::mem::USER_AREA_END) + if (current_addr + data.len()) >= xous_kernel::arch::USER_AREA_END + || (current_addr >= xous_kernel::arch::USER_AREA_END) { for entry in data.iter_mut() { *entry = 0 @@ -143,7 +143,7 @@ impl MultiThreadBase for XousTarget { return Ok(()); }; - if (current_addr + data.len()) > crate::arch::mem::USER_AREA_END { + if (current_addr + data.len()) > xous_kernel::arch::USER_AREA_END { return Ok(()); // don't allow reads outside of the user area } diff --git a/kernel/src/debug/gdb/target.rs b/kernel/src/debug/gdb/target.rs index 530a5c0e0..1afa70568 100644 --- a/kernel/src/debug/gdb/target.rs +++ b/kernel/src/debug/gdb/target.rs @@ -11,9 +11,9 @@ impl Target for XousTarget { type Arch = gdbstub_arch::riscv::Riscv32; type Error = &'static str; - fn base_ops(&mut self) -> BaseOps { BaseOps::MultiThread(self) } + fn base_ops(&mut self) -> BaseOps<'_, Self::Arch, Self::Error> { BaseOps::MultiThread(self) } - fn support_breakpoints(&mut self) -> Option> { Some(self) } + fn support_breakpoints(&mut self) -> Option> { Some(self) } /// Opt in to having GDB handle breakpoints for us. This allows for an unlimited number /// of breakpoints without having us keep track of the breakpoints ourselves, but diff --git a/kernel/src/debug/shell.rs b/kernel/src/debug/shell.rs index bf8552792..f091fef91 100644 --- a/kernel/src/debug/shell.rs +++ b/kernel/src/debug/shell.rs @@ -7,9 +7,10 @@ use core::fmt; -use crate::io::SerialWrite; +use crate::args::KernelArguments; #[cfg(not(feature = "bao1x"))] -use crate::{args::KernelArguments, io::SerialRead}; +use crate::io::SerialRead; +use crate::io::SerialWrite; /// Instance of the shell output. pub static mut OUTPUT: Option = None; @@ -58,7 +59,6 @@ impl fmt::Write for Output { /// Initialize the kernel shell. /// /// This should be called in platform initialization code. -#[cfg(not(feature = "bao1x"))] pub fn init(serial: &'static mut dyn SerialWrite) { unsafe { OUTPUT = Some(Output::new(serial)) } @@ -69,9 +69,12 @@ pub fn init(serial: &'static mut dyn SerialWrite) { println!(" {}", arg); } - println!("=== Kernel Debug Shell Available ===="); - print_help(); - println!("====================================="); + #[cfg(not(feature = "bao1x"))] + { + println!("=== Kernel Debug Shell Available ===="); + print_help(); + println!("====================================="); + } } /// Process possible characters received through a serial interface. From 7940529d0badd0c70e2aae080e16f86cbcca88d0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:16:32 +0800 Subject: [PATCH 08/13] integrate gdb initializations into the kernel --- kernel/src/platform/bao1x/mod.rs | 4 ++++ kernel/src/platform/bao1x/uart.rs | 9 +++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/kernel/src/platform/bao1x/mod.rs b/kernel/src/platform/bao1x/mod.rs index c3917e16c..830f2cfe9 100644 --- a/kernel/src/platform/bao1x/mod.rs +++ b/kernel/src/platform/bao1x/mod.rs @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: 2022 Foundation Devices, Inc. // SPDX-FileCopyrightText: 2024 bunnie // SPDX-License-Identifier: Apache-2.0 +#[cfg(feature = "gdb-stub")] +pub mod gdbuart; #[cfg(all(feature = "bao1x", not(feature = "verilator-only")))] #[path = "rand.rs"] @@ -65,6 +67,8 @@ pub fn init() { self::rand::init(); #[cfg(any(feature = "debug-print", feature = "print-panics"))] self::uart::init(); + #[cfg(feature = "gdb-stub")] + crate::debug::gdb::init(); } #[derive(Debug, Copy, Clone, PartialEq, Eq)] diff --git a/kernel/src/platform/bao1x/uart.rs b/kernel/src/platform/bao1x/uart.rs index acebf21e6..032c27036 100644 --- a/kernel/src/platform/bao1x/uart.rs +++ b/kernel/src/platform/bao1x/uart.rs @@ -19,8 +19,6 @@ use crate::{PID, io::SerialWrite, mem::MemoryManager}; /// See https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md #[cfg(feature = "bao1x")] pub const UART_ADDR: usize = 0xffcf_0000; -#[cfg(feature = "bao1x")] -pub const IRQ0_ADDR: usize = UART_ADDR + 0x1000; /// UART instance. /// @@ -43,12 +41,11 @@ pub fn init() { ) .expect("unable to map serial port") }); - let mut uart = Uart::new(UART_ADDR, IRQ0_ADDR); + let mut uart = Uart::new(UART_ADDR); uart.init(); unsafe { UART = Some(uart); - // inaccessible because DUART is tx-only - // crate::debug::shell::init((&mut *(&raw mut UART)).as_mut().unwrap()); + crate::debug::shell::init((&mut *(&raw mut UART)).as_mut().unwrap()); } } @@ -59,7 +56,7 @@ pub struct Uart { #[cfg(feature = "bao1x")] impl Uart { - pub fn new(addr: usize, _irq_addr: usize) -> Uart { Uart { uart_csr: CSR::new(addr as *mut u32) } } + pub fn new(addr: usize) -> Uart { Uart { uart_csr: CSR::new(addr as *mut u32) } } pub fn init(&mut self) { // duart requires no special initializations From 541fecead2998ef2c37e84ebe0c7d7996b9896e6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:18:19 +0800 Subject: [PATCH 09/13] add probably flawed implementation of poke_memory this is a first take at the poke_memory primitive, which is necessary for GDB to patch in debug breakpoints. I think the memory patching is *working*, but...stuff like single stepping is still not working. This might be just me using GDB wrong, tho. Need someone who actually uses GDB/is more familiar with it to poke around a bit more. --- kernel/src/arch/riscv/mem.rs | 97 +++++++++++++++++++++++++++++++++++- 1 file changed, 96 insertions(+), 1 deletion(-) diff --git a/kernel/src/arch/riscv/mem.rs b/kernel/src/arch/riscv/mem.rs index b320ea17c..7613f90e1 100644 --- a/kernel/src/arch/riscv/mem.rs +++ b/kernel/src/arch/riscv/mem.rs @@ -549,7 +549,7 @@ pub fn peek_memory(addr: *mut T) -> Result { Ok(val) } -#[cfg(feature = "gdb-stub")] +#[cfg(all(feature = "gdb-stub", not(feature = "bao1x")))] pub fn poke_memory(addr: *mut T, val: T) -> Result<(), xous_kernel::Error> { let virt = addr as usize; let vpn1 = (virt >> 22) & ((1 << 10) - 1); @@ -608,6 +608,101 @@ pub fn poke_memory(addr: *mut T, val: T) -> Result<(), xous_kernel::Error> { Ok(()) } +#[cfg(all(feature = "gdb-stub", feature = "bao1x"))] +/// This routine looks like it *works* insofar as it really maps a RRAM page into RAM and patches it, +/// but things like single stepping still don't work. +pub fn poke_memory(addr: *mut T, val: T) -> Result<(), xous_kernel::Error> { + let virt = addr as usize; + let vpn1 = (virt >> 22) & ((1 << 10) - 1); + let vpn0 = (virt >> 12) & ((1 << 10) - 1); + let vpo = virt & ((1 << 12) - 1); + + assert!(vpn1 < 1024); + assert!(vpn0 < 1024); + assert!(vpo < 4096); + + // The root (l1) pagetable is defined to be mapped into our virtual + // address space at this address. + let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) }; + let l1_pt = &mut l1_pt.entries; + + // Subsequent pagetables are defined as being mapped starting at + // PAGE_TABLE_OFFSET + let l0pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE; + let l0_pt = &mut unsafe { &mut (*(l0pt_virt as *mut LeafPageTable)) }; + + // If the level 1 pagetable doesn't exist, then this address isn't valid. + if l1_pt[vpn1] & MMUFlags::VALID.bits() == 0 { + return Err(xous_kernel::Error::BadAddress); + } + + // Ensure the entry has been mapped. + if l0_pt.entries[vpn0] & MMUFlags::VALID.bits() == 0 { + return Err(xous_kernel::Error::BadAddress); + } + + // Ensure we're allowed to read it. + let was_writable = l0_pt.entries[vpn0] & MMUFlags::W.bits() != 0; + + if l0_pt.entries[vpn0] & MMUFlags::P.bits != 0 { + return Err(xous_kernel::Error::StorageError); // can't access because it's swapped out + } + + // check the physical location: if it's in RRAM, we're going to have to patch this into RAM + let pa = virt_to_phys(virt)?; + if pa >= utralib::HW_RERAM_MEM + bao1x_api::offsets::RRAM_STORAGE_LEN && pa < utralib::HW_SRAM_MEM { + // don't allow debug access to the keystore + return Err(xous_kernel::Error::BadAddress); + } + + // Enable supervisor access to user mode + unsafe { sstatus::set_sum() }; + + if pa >= utralib::HW_RERAM_MEM && pa < utralib::HW_RERAM_MEM + bao1x_api::offsets::RRAM_STORAGE_LEN { + // this also forces the writeable bit + let v_backing = + MemoryManager::with_mut(|mm| mm.map_zeroed_page(crate::arch::process::current_pid(), true))?; + let p_backing = virt_to_phys(v_backing as usize)?; + let v_slice = unsafe { core::slice::from_raw_parts_mut(v_backing, PAGE_SIZE / size_of::()) }; + let s_page = addr as usize & !4095; + let src_slice = + unsafe { core::slice::from_raw_parts(s_page as *mut usize, PAGE_SIZE / size_of::()) }; + v_slice.copy_from_slice(src_slice); + // println!("copied from {:x}: {:x?}", s_page, &v_slice[..16]); + + // v_slice now has a copy of src_slice. Unmap src_slice and replace with v_slice. + // currently, we just leak memory until we run out if we're doing this trick to map pages into memory. + let flags = l0_pt.entries[vpn0] & 0x3FF; + let ppn1 = (p_backing >> 22) & ((1 << 12) - 1); + let ppn0 = (p_backing >> 12) & ((1 << 10) - 1); + l0_pt.entries[vpn0] = (ppn1 << 20) | (ppn0 << 10) | flags | MMUFlags::W.bits(); + + // at this point, the page table now points to the physical memory. + // println!("flushing mmu {:x?} <- {:x?} {} {:x}", addr, val, size_of::(), flags); + bao1x_hal::cache_flush(); + unsafe { flush_mmu() }; + } else if !was_writable { + // Add the WRITE bit, which allows us to patch things like + // program code. + l0_pt.entries[vpn0] |= MMUFlags::W.bits(); + unsafe { flush_mmu() }; + } + // Perform the write + unsafe { addr.write_volatile(val) }; + bao1x_hal::cache_flush(); + + // Remove supervisor access to user mode + unsafe { sstatus::clear_sum() }; + + // Remove the WRITE bit if it wasn't previously set + if !was_writable { + l0_pt.entries[vpn0] &= !MMUFlags::W.bits(); + unsafe { flush_mmu() }; + } + + Ok(()) +} + /// Map the given page to the specified process table. If necessary, /// allocate a new page. /// From e76e5a87ffcdc26b766587b7d1e65e0126c0a789 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:19:35 +0800 Subject: [PATCH 10/13] add bao1x-api dependency to kernel in gdb-stub this is necessary to re-init the UART speed as that crate contains the default perclk speed. --- kernel/Cargo.toml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 34fe805a4..934bb7862 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -17,6 +17,7 @@ xous-kernel = { package = "xous", version = "0.9.69", features = [ utralib = { version = "0.1.26", optional = true, default-features = false } rand_chacha = { version = "0.3.1", optional = true, default-features = false } bao1x-hal = { path = "../libs/bao1x-hal", optional = true, default-features = false } +bao1x-api = { path = "../libs/bao1x-api", optional = true } loader = { path = "../loader", optional = true, features = ["swap"] } [target.'cfg(any(windows,unix))'.dev-dependencies] xous-kernel = { package = "xous", version = "0.9.69", features = [ @@ -57,12 +58,12 @@ hosted = ["utralib/hosted"] renode = ["utralib/renode"] debug-print = [] -gdb-stub = ["gdbstub", "gdbstub_arch"] +gdb-stub = ["gdbstub", "gdbstub_arch", "bao1x-api"] print-panics = [] -dump-kernel-pages = [] # include kernel pages in panic dumps +dump-kernel-pages = [] # include kernel pages in panic dumps report-memory = ["stats_alloc"] wrap-print = [] -big-heap = [] # Cause heaps to start at 12 MM instead of 512 kB +big-heap = [] # Cause heaps to start at 12 MM instead of 512 kB v2p = ["xous-kernel/v2p"] swap = ["xous-kernel/swap", "loader/swap"] memmap-flash = [] From 24105e7b22b44d5a7d26ff286b4ee2abc6155674 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:20:27 +0800 Subject: [PATCH 11/13] add the default perclk speed as a public constant instead of just hard-coding it in the clock setting routine --- libs/bao1x-hal/src/clocks.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/libs/bao1x-hal/src/clocks.rs b/libs/bao1x-hal/src/clocks.rs index 931fe4422..1020f99f9 100644 --- a/libs/bao1x-hal/src/clocks.rs +++ b/libs/bao1x-hal/src/clocks.rs @@ -12,6 +12,11 @@ use crate::i2c::I2c; #[cfg(feature = "std")] const MHZ: u32 = 1_000_000; +/// This is always the default target rate for peripheral clock, regardless of the pll setting +/// It's not always achievable - for example, when the PLL is turned off, which is why the actual +/// perclk is returned by the clock setting routines. +pub const PERCLK_HZ: u32 = 100_000_000; + #[bitfield(u32)] #[derive(PartialEq, Eq, Debug)] pub struct PmuControl { @@ -86,7 +91,7 @@ where daric_cgu.add(utra::sysctrl::SFR_CGUFD_CFGFDCR_0_4_4.offset()).write_volatile(0x7f00_010f); // pclk // peripheral clock should always target 100MHz regardless of the top frequency - let peri_params = bao1x_api::find_optimal_divider(freq_hz / 2, 100_000_000).unwrap(); + let peri_params = bao1x_api::find_optimal_divider(freq_hz / 2, PERCLK_HZ).unwrap(); let fd0 = peri_params.fd0; let fd2 = peri_params.fd2; daric_cgu.add(utra::sysctrl::SFR_CGUFDPER.offset()).write_volatile( From 29d25c13a149bad212ffadd43539413c65095a81 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:21:06 +0800 Subject: [PATCH 12/13] refactor UDMA UART to use "poll" mode to receive data The prior implementation tried to use the UDMA streaming mode to get Rx data out of the UART. The problem is that with streaming mode, it's hard to tell how much data is actually available. This is because the thing that sets up the stream sets "some number of bytes" as the fetch depth of the DMA Rx, but all you can read is "number of bytes remaining" out of the DMA interface. So when 0 bytes are remaining, you can fetch some data, but you don't know *how much* to fetch. And if someone else fetched partial data before you, you don't know how much partial data was fetched. This could be resolved with some gnarly, highly concurrent state that gets incremented on every fetch. Or, we could use poll mode. There's a reason i think it's in the block, because the Rx DMA mode is more or less not usable. Poll mode you read a config register, see if there's valid data, and if so, when you read the data register, it's pulled out of a FIFO. The FIFO is in hardware and it's 4-deep. As long as you don't need more than a depth of 4, you're rock solid. This is a lot easier than the UDMA Rx mode, so I've just gone ahead and deprecated the Rx mode. I could only ever get the Rx mode to work to receive a single character *anyways*, so despite its potential to receive thousands of bytes without CPU intervention, it was only ever used as a 1-deep buffer because of the inability to know exactly how much was in the buffer. Thus, the poll mode is actually an improvement over the DMA mode, in practice. More importantly, it means the Rx link is much more stable in GDB kernel mode, if the baud rate is cranked down to 115200 (at 1M baud, the kernel still can't respond quite fast enough to reliably drain it). --- libs/bao1x-hal/src/udma/uart.rs | 65 ++++++++++++++------------------- 1 file changed, 28 insertions(+), 37 deletions(-) diff --git a/libs/bao1x-hal/src/udma/uart.rs b/libs/bao1x-hal/src/udma/uart.rs index cdbbc5ab8..609ba7016 100644 --- a/libs/bao1x-hal/src/udma/uart.rs +++ b/libs/bao1x-hal/src/udma/uart.rs @@ -5,9 +5,13 @@ use crate::udma::*; // ----------------------------------- UART ------------------------------------ #[repr(usize)] -enum UartReg { +pub enum UartReg { Status = 0, Setup = 1, + Error = 2, + IrqEn = 3, + Valid = 4, + Data = 5, } impl Into for UartReg { fn into(self) -> usize { self as usize } @@ -92,10 +96,13 @@ impl Uart { let clk_counter: u32 = (clk_freq + baud / 2) / baud; // setup baud, bits, parity, etc. + // bit 0x10 sets poll mode - data is read out through the command interface not the streaming Rx fifo + // the command interface is more reliable in terms of determining exactly how many bytes are left to + // read. csr.base() .add(Bank::Custom.into()) .add(UartReg::Setup.into()) - .write_volatile(0x0306 | (clk_counter << 16)); + .write_volatile(0x0316 | (clk_counter << 16)); Uart { csr, ifram: IframRange::request(UART_RX_BUF_SIZE + UART_TX_BUF_SIZE, None).unwrap() } } @@ -125,12 +132,15 @@ impl Uart { } // setup baud, bits, parity, etc. // safety: this is safe to call as long as the base address points at a valid UART. + // bit 0x10 sets poll mode - data is read out through the command interface not the streaming Rx fifo + // the command interface is more reliable in terms of determining exactly how many bytes are left to + // read. unsafe { self.csr .base() .add(Bank::Custom.into()) .add(UartReg::Setup.into()) - .write_volatile(0x0306 | (clk_counter << 16)); + .write_volatile(0x0316 | (clk_counter << 16)); } } @@ -232,11 +242,11 @@ impl Uart { ); } self.wait_rx_done(); - #[cfg(feature = "std")] + #[cfg(any(feature = "std", feature = "kernel"))] chunk.copy_from_slice( &self.ifram.as_slice::()[UART_RX_BUF_START..UART_RX_BUF_START + chunk.len()], ); - #[cfg(not(feature = "std"))] + #[cfg(not(any(feature = "std", feature = "kernel")))] unsafe { chunk.copy_from_slice( &self.ifram.as_phys_slice::()[UART_RX_BUF_START..UART_RX_BUF_START + chunk.len()], @@ -251,44 +261,25 @@ impl Uart { /// /// Returns actual number of bytes read (0 or 1). pub fn read_async(&mut self, c: &mut u8) -> usize { - let bank_addr = unsafe { self.csr().base().add(Bank::Rx as usize) }; - // retrieve total bytes available - let pending = unsafe { bank_addr.add(DmaReg::Size.into()).read_volatile() } as usize; + // retrieve valid + let valid = + unsafe { self.csr().base().add(Bank::Custom.into()).add(UartReg::Valid.into()).read_volatile() } + as usize; - // recover the pending byte. Hard-coded for case of RX_BUF_DEPTH == 1 - assert!(RX_BUF_DEPTH == 1, "Need to refactor buf recovery code if RX_BUF_DEPTH > 1"); - #[cfg(feature = "std")] - { - *c = self.ifram.as_slice::()[UART_RX_BUF_START]; - } - #[cfg(not(feature = "std"))] - unsafe { - *c = self.ifram.as_phys_slice::()[UART_RX_BUF_START]; - } + if valid != 0 { + *c = unsafe { + self.csr().base().add(Bank::Custom.into()).add(UartReg::Data.into()).read_volatile() + } as u8; - // queue the next round - #[cfg(feature = "std")] - unsafe { - self.udma_enqueue( - Bank::Rx, - &self.ifram.as_phys_slice::()[UART_RX_BUF_START..UART_RX_BUF_START + RX_BUF_DEPTH], - CFG_EN | CFG_CONT, - ); + 1 + } else { + 0 } - #[cfg(not(feature = "std"))] - unsafe { - self.udma_enqueue( - Bank::Rx, - &self.ifram.as_phys_slice::()[UART_RX_BUF_START..UART_RX_BUF_START + RX_BUF_DEPTH], - CFG_EN | CFG_CONT, - ); - } - - pending } /// Call this to prime the system for async reads. This must be called at least once if any characters - /// are ever to be received. + /// are ever to be received, if the system is in FIFO mode (note that by default the system is now in POLL + /// mode) pub fn setup_async_read(&mut self) { #[cfg(feature = "std")] unsafe { From 893c71c0230bdfa16fadb67bbdab39e4b929b5a1 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 14 Jan 2026 03:25:50 +0800 Subject: [PATCH 13/13] track new dependencies for kernel --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 8de317f12..b2f9df37e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7598,6 +7598,7 @@ name = "xous-kernel" version = "0.9.38" dependencies = [ "armv7", + "bao1x-api", "bao1x-hal", "bitflags 1.3.2", "critical-section",