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", 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`. 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()); } 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 { 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 = [] 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. /// 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. 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(()) + } +} 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 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( 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 { 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)) } 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"),