From ff09a784fb383635e0c73e11fa3f741a4c97b014 Mon Sep 17 00:00:00 2001 From: eupn Date: Mon, 27 Mar 2023 19:50:13 +0400 Subject: [PATCH] xous-log: split platform-dependent code --- services/xous-log/Cargo.toml | 7 + services/xous-log/src/main.rs | 250 +----------------- .../src/platform/hosted/implementation.rs | 96 +++++++ services/xous-log/src/platform/hosted/mod.rs | 1 + services/xous-log/src/platform/mod.rs | 13 + .../xous-log/src/platform/precursor/debug.rs | 112 ++++++++ .../src/platform/precursor/implementation.rs | 134 ++++++++++ .../xous-log/src/platform/precursor/mod.rs | 5 + 8 files changed, 374 insertions(+), 244 deletions(-) create mode 100644 services/xous-log/src/platform/hosted/implementation.rs create mode 100644 services/xous-log/src/platform/hosted/mod.rs create mode 100644 services/xous-log/src/platform/mod.rs create mode 100644 services/xous-log/src/platform/precursor/debug.rs create mode 100644 services/xous-log/src/platform/precursor/implementation.rs create mode 100644 services/xous-log/src/platform/precursor/mod.rs diff --git a/services/xous-log/Cargo.toml b/services/xous-log/Cargo.toml index 5c2116ab4..8bfbd576f 100644 --- a/services/xous-log/Cargo.toml +++ b/services/xous-log/Cargo.toml @@ -19,10 +19,17 @@ num-traits = {version = "0.2.14", default-features = false} utralib = {version = "0.1.15", optional = true, default-features = false } +[target.'cfg(target_arch = "arm")'.dependencies] +atsama5d27 = { git = "https://github.com/Foundation-Devices/atsama5d27.git", branch = "master", features = ["lcd-console"]} +xous = { version = "0.9.33", features = ["v2p"] } # v2p feature is used when lcd-console feature is turned on + [features] precursor = ["utralib/precursor"] hosted = ["utralib/hosted"] renode = ["utralib/renode"] +atsama5d27 = ["utralib/atsama5d27"] + +lcd-console = [] debugprint = [] # adding this allocates the UART for debugging the logger logging = [] # adding this allocates the hardware UART for console interactions #default = [] diff --git a/services/xous-log/src/main.rs b/services/xous-log/src/main.rs index 12df6e56a..0d9c73f25 100644 --- a/services/xous-log/src/main.rs +++ b/services/xous-log/src/main.rs @@ -5,250 +5,12 @@ use xous_api_log::api; #[cfg(any(feature="precursor", feature="renode"))] #[macro_use] -mod debug; +mod platform; use core::fmt::Write; use num_traits::FromPrimitive; -#[cfg(any(not(target_os = "xous"), - not(any(feature="precursor", feature="renode", not(target_os = "xous"))) // makes this the default implementation -))] -mod implementation { - use core::fmt::{Error, Write}; - use std::sync::mpsc::{channel, Receiver, Sender}; - - enum ControlMessage { - Text(String), - Byte(u8), - Exit, - } - - pub struct Output { - tx: Sender, - rx: Receiver, - stdout: std::io::Stdout, - } - - pub fn init() -> Output { - let (tx, rx) = channel(); - - Output { - tx, - rx, - stdout: std::io::stdout(), - } - } - - impl Output { - pub fn run(&mut self) { - use std::io::Write; - loop { - match self.rx.recv_timeout(std::time::Duration::from_millis(50)) { - Ok(msg) => match msg { - ControlMessage::Exit => break, - ControlMessage::Text(s) => print!("{}", s), - ControlMessage::Byte(s) => { - let mut handle = self.stdout.lock(); - handle.write_all(&[s]).unwrap(); - } - }, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} - Err(e) => panic!("Error: {}", e), - } - } - } - - pub fn get_writer(&self) -> OutputWriter { - OutputWriter { - tx: self.tx.clone(), - } - } - } - - impl Drop for Output { - fn drop(&mut self) { - self.tx.send(ControlMessage::Exit).unwrap(); - } - } - - impl Write for Output { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - // It would be nice if this worked with &str - self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); - Ok(()) - } - } - - pub struct OutputWriter { - tx: Sender, - } - - impl OutputWriter { - pub fn putc(&self, c: u8) { - self.tx.send(ControlMessage::Byte(c)).unwrap(); - } - - /// Write a buffer to the output and return the number of - /// bytes written. This is mostly compatible with `std::io::Write`, - /// except it is infallible. - pub fn write(&mut self, buf: &[u8]) -> usize { - for c in buf { - self.putc(*c); - } - buf.len() - } - - pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { - Ok(self.write(buf)) - } - } - - impl Write for OutputWriter { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - // It would be nice if this worked with &str - self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); - Ok(()) - } - } -} - -#[cfg(any(feature="precursor", feature="renode"))] -mod implementation { - use core::fmt::{Error, Write}; - use utralib::generated::*; - - pub struct Output {} - - pub fn init() -> Output { - if cfg!(feature = "logging") { - let uart = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::console::HW_CONSOLE_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map serial port"); - unsafe { crate::debug::DEFAULT_UART_ADDR = uart.as_mut_ptr() as _ }; - println!("Mapped UART @ {:08x}", uart.as_ptr() as usize); - let mut uart_csr = CSR::new(uart.as_mut_ptr() as *mut u32); - - println!("Process: map success!"); - - let inject_mem = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::keyinject::HW_KEYINJECT_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map keyinjection CSR range"); - println!("Note: character injection via console UART is enabled."); - - println!("Allocating IRQ..."); - xous::syscall::claim_interrupt( - utra::console::CONSOLE_IRQ, - handle_console_irq, - inject_mem.as_mut_ptr() as *mut usize, - ) - .expect("couldn't claim interrupt"); - println!("Claimed IRQ {}", utra::console::CONSOLE_IRQ); - uart_csr.rmwf(utra::uart::EV_ENABLE_RX, 1); - } - Output {} - } - - impl Output { - pub fn get_writer(&self) -> OutputWriter { - OutputWriter {} - } - - pub fn run(&mut self) { - loop { - xous::wait_event(); - } - } - } - - fn handle_console_irq(_irq_no: usize, arg: *mut usize) { - if cfg!(feature = "logging") { - let mut inject_csr = CSR::new(arg as *mut u32); - let mut uart_csr = CSR::new(unsafe { crate::debug::DEFAULT_UART_ADDR as *mut u32 }); - // println!("rxe {}", uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY)); - while uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY) == 0 { - // I really rather think this is more readable, than the "Rusty" version below. - inject_csr.wfo( - utra::keyinject::UART_CHAR_CHAR, - uart_csr.rf(utra::uart::RXTX_RXTX), - ); - uart_csr.wfo(utra::uart::EV_PENDING_RX, 1); - - // I guess this is how you would do it if you were "really doing Rust" - // (except this is checking pending not fifo status for loop termination) - // (which was really hard to figure out just looking at this loop) - /* - let maybe_c = match uart_csr.rf(utra::uart::EV_PENDING_RX) { - 0 => None, - ack => { - let c = Some(uart_csr.rf(utra::uart::RXTX_RXTX) as u8); - uart_csr.wfo(utra::uart::EV_PENDING_RX, ack); - c - } - }; - if let Some(c) = maybe_c { - inject_csr.wfo(utra::keyinject::UART_CHAR_CHAR, (c & 0xff) as u32); - } else { - break; - }*/ - } - // println!("rxe {}", uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY)); - // println!("pnd {}", uart_csr.rf(utra::uart::EV_PENDING_RX)); - } - } - - pub struct OutputWriter {} - - impl OutputWriter { - pub fn putc(&self, c: u8) { - if cfg!(feature = "logging") { - let mut uart_csr = CSR::new(unsafe { crate::debug::DEFAULT_UART_ADDR as *mut u32 }); - - // Wait until TXFULL is `0` - while uart_csr.r(utra::uart::TXFULL) != 0 {} - uart_csr.wo(utra::uart::RXTX, c as u32); - - // there's a race condition in the handler, if a new character comes in while handling the interrupt, - // the pending bit never clears. If the console seems to freeze, uncomment this line. - // This kind of works around that, at the expense of maybe losing some Rx characters. - // uart_csr.wfo(utra::uart::EV_PENDING_RX, 1); - } - } - - /// Write a buffer to the output and return the number of - /// bytes written. This is mostly compatible with `std::io::Write`, - /// except it is infallible. - pub fn write(&mut self, buf: &[u8]) -> usize { - for c in buf { - self.putc(*c); - } - buf.len() - } - - pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { - Ok(self.write(buf)) - } - } - - impl Write for OutputWriter { - fn write_str(&mut self, s: &str) -> Result<(), Error> { - for c in s.bytes() { - self.putc(c); - if c == '\n' as u8 { - self.putc('\r' as u8); - } - } - Ok(()) - } - } -} +use platform::implementation; fn handle_scalar( output: &mut implementation::OutputWriter, @@ -397,9 +159,9 @@ fn handle_opcode( fn reader_thread(arg: usize) { let output = unsafe { &mut *(arg as *mut implementation::OutputWriter) }; - writeln!(output, "LOG: Xous Logging Server starting up...").unwrap(); - let server_addr = xous::create_server_with_address(b"xous-log-server ").unwrap(); - writeln!(output, "LOG: Server listening on address {:?}", server_addr).unwrap(); + writeln!(output, "LOG: Xous Logging Server starting up...").ok(); + let server_addr = xous::create_server_with_address(b"xous-log-server ").expect("create server"); + writeln!(output, "LOG: Server listening on address {:?}", server_addr).ok(); println!("LOG: my PID is {}", xous::process::id()); let mut counter: usize = 0; @@ -457,7 +219,7 @@ fn main() -> ! { reader_thread, &mut writer as *mut implementation::OutputWriter as usize, ) - .unwrap(); + .expect("create reader thread"); println!("LOG: Running the output"); output.run(); panic!("LOG: Exited"); diff --git a/services/xous-log/src/platform/hosted/implementation.rs b/services/xous-log/src/platform/hosted/implementation.rs new file mode 100644 index 000000000..8e8f507b6 --- /dev/null +++ b/services/xous-log/src/platform/hosted/implementation.rs @@ -0,0 +1,96 @@ +use core::fmt::{Error, Write}; +use std::sync::mpsc::{channel, Receiver, Sender}; + +enum ControlMessage { + Text(String), + Byte(u8), + Exit, +} + +pub struct Output { + tx: Sender, + rx: Receiver, + stdout: std::io::Stdout, +} + +pub fn init() -> Output { + let (tx, rx) = channel(); + + Output { + tx, + rx, + stdout: std::io::stdout(), + } +} + +impl Output { + pub fn run(&mut self) { + use std::io::Write; + loop { + match self.rx.recv_timeout(std::time::Duration::from_millis(50)) { + Ok(msg) => match msg { + ControlMessage::Exit => break, + ControlMessage::Text(s) => print!("{}", s), + ControlMessage::Byte(s) => { + let mut handle = self.stdout.lock(); + handle.write_all(&[s]).unwrap(); + } + }, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(e) => panic!("Error: {}", e), + } + } + } + + pub fn get_writer(&self) -> OutputWriter { + OutputWriter { + tx: self.tx.clone(), + } + } +} + +impl Drop for Output { + fn drop(&mut self) { + self.tx.send(ControlMessage::Exit).unwrap(); + } +} + +impl Write for Output { + fn write_str(&mut self, s: &str) -> Result<(), Error> { + // It would be nice if this worked with &str + self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); + Ok(()) + } +} + +pub struct OutputWriter { + tx: Sender, +} + +impl OutputWriter { + pub fn putc(&self, c: u8) { + self.tx.send(ControlMessage::Byte(c)).unwrap(); + } + + /// Write a buffer to the output and return the number of + /// bytes written. This is mostly compatible with `std::io::Write`, + /// except it is infallible. + pub fn write(&mut self, buf: &[u8]) -> usize { + for c in buf { + self.putc(*c); + } + buf.len() + } + + pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { + Ok(self.write(buf)) + } +} + +impl Write for OutputWriter { + fn write_str(&mut self, s: &str) -> Result<(), Error> { + // It would be nice if this worked with &str + self.tx.send(ControlMessage::Text(s.to_owned())).unwrap(); + Ok(()) + } +} diff --git a/services/xous-log/src/platform/hosted/mod.rs b/services/xous-log/src/platform/hosted/mod.rs new file mode 100644 index 000000000..f5652a4a2 --- /dev/null +++ b/services/xous-log/src/platform/hosted/mod.rs @@ -0,0 +1 @@ +pub mod implementation; diff --git a/services/xous-log/src/platform/mod.rs b/services/xous-log/src/platform/mod.rs new file mode 100644 index 000000000..b3ee8de7b --- /dev/null +++ b/services/xous-log/src/platform/mod.rs @@ -0,0 +1,13 @@ +#[cfg(any(feature="precursor", feature="renode"))] +#[macro_use] +pub mod precursor; + +#[cfg(any(feature="precursor", feature="renode"))] +pub use precursor::debug; + +#[cfg(not(target_os = "xous"))] +#[macro_use] +pub mod hosted; + +#[cfg(not(target_os = "xous"))] +pub use hosted::implementation; diff --git a/services/xous-log/src/platform/precursor/debug.rs b/services/xous-log/src/platform/precursor/debug.rs new file mode 100644 index 000000000..b13407951 --- /dev/null +++ b/services/xous-log/src/platform/precursor/debug.rs @@ -0,0 +1,112 @@ +use core::fmt::{Error, Write}; + +use utralib::generated::*; + +#[macro_export] +macro_rules! print +{ + ($($args:tt)+) => ({ + use core::fmt::Write; + let _ = write!(crate::debug::Uart {}, $($args)+); + }); +} +#[macro_export] +macro_rules! println +{ + () => ({ + print!("\r\n") + }); + ($fmt:expr) => ({ + print!(concat!($fmt, "\r\n")) + }); + ($fmt:expr, $($args:tt)+) => ({ + print!(concat!($fmt, "\r\n"), $($args)+) + }); +} + +#[allow(dead_code)] +fn handle_irq(irq_no: usize, arg: *mut usize) { + print!("Handling IRQ {} (arg: {:08x}): ", irq_no, arg as usize); + + while let Some(c) = { crate::debug::Uart {} }.getc() { + print!("{}", c as char); + } + println!(); +} + +pub struct Uart {} + +// this is a hack to bypass an explicit initialization/allocation step for the debug structure +pub static mut DEFAULT_UART_ADDR: *mut usize = 0x0000_0000 as *mut usize; + +pub const DEFAULT: Uart = Uart {}; + +impl Uart { + fn map_uart(&self) { + /* + Note: the memory address and interrupt specified here needs to map to a unique hardware + UART resource. Modify in this function as necessary. + */ + let uart = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::console::HW_CONSOLE_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map debug uart"); + unsafe { + DEFAULT_UART_ADDR = uart.as_mut_ptr() as _; + } + println!("Mapped UART @ {:08x}", uart.as_ptr() as usize); + // core::mem::forget(uart); + + println!("Allocating IRQ..."); + /* xous::claim_interrupt( + utra::console::CONSOLE_IRQ, + handle_irq, + core::ptr::null_mut::(), + ) + .expect("unable to allocate IRQ"); */ + self.enable_rx(); + } + + pub fn putc(&self, c: u8) { + if unsafe { DEFAULT_UART_ADDR } as usize == 0 { + self.map_uart(); + } + let mut uart_csr = CSR::new(unsafe { DEFAULT_UART_ADDR as *mut u32 }); + + // Wait until TXFULL is `0` + while uart_csr.r(utra::uart::TXFULL) != 0 {} + uart_csr.wo(utra::uart::RXTX, c as u32); + } + + pub fn enable_rx(&self) { + let mut uart_csr = CSR::new(unsafe { DEFAULT_UART_ADDR as *mut u32 }); + uart_csr.rmwf(utra::uart::EV_ENABLE_RX, 1); + } + #[allow(dead_code)] + pub fn getc(&self) -> Option { + if unsafe { DEFAULT_UART_ADDR } as usize == 0 { + self.map_uart(); + } + let mut uart_csr = CSR::new(unsafe { DEFAULT_UART_ADDR as *mut u32 }); + match uart_csr.rf(utra::uart::EV_PENDING_RX) { + 0 => None, + ack => { + let c = Some(uart_csr.rf(utra::uart::RXTX_RXTX) as u8); + uart_csr.wfo(utra::uart::EV_PENDING_RX, ack); + c + } + } + } +} + +impl Write for Uart { + fn write_str(&mut self, s: &str) -> Result<(), Error> { + for c in s.bytes() { + self.putc(c); + } + Ok(()) + } +} diff --git a/services/xous-log/src/platform/precursor/implementation.rs b/services/xous-log/src/platform/precursor/implementation.rs new file mode 100644 index 000000000..840b07f79 --- /dev/null +++ b/services/xous-log/src/platform/precursor/implementation.rs @@ -0,0 +1,134 @@ +use core::fmt::{Error, Write}; +use utralib::generated::*; + +pub struct Output {} + +pub fn init() -> Output { + if cfg!(feature = "logging") { + let uart = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::console::HW_CONSOLE_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map serial port"); + unsafe { crate::debug::DEFAULT_UART_ADDR = uart.as_mut_ptr() as _ }; + println!("Mapped UART @ {:08x}", uart.as_ptr() as usize); + let mut uart_csr = CSR::new(uart.as_mut_ptr() as *mut u32); + + println!("Process: map success!"); + + let inject_mem = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::keyinject::HW_KEYINJECT_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map keyinjection CSR range"); + println!("Note: character injection via console UART is enabled."); + + println!("Allocating IRQ..."); + xous::syscall::claim_interrupt( + utra::console::CONSOLE_IRQ, + handle_console_irq, + inject_mem.as_mut_ptr() as *mut usize, + ) + .expect("couldn't claim interrupt"); + println!("Claimed IRQ {}", utra::console::CONSOLE_IRQ); + uart_csr.rmwf(utra::uart::EV_ENABLE_RX, 1); + } + Output {} +} + +impl Output { + pub fn get_writer(&self) -> OutputWriter { + OutputWriter {} + } + + pub fn run(&mut self) { + loop { + xous::wait_event(); + } + } +} + +fn handle_console_irq(_irq_no: usize, arg: *mut usize) { + if cfg!(feature = "logging") { + let mut inject_csr = CSR::new(arg as *mut u32); + let mut uart_csr = CSR::new(unsafe { crate::debug::DEFAULT_UART_ADDR as *mut u32 }); + // println!("rxe {}", uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY)); + while uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY) == 0 { + // I really rather think this is more readable, than the "Rusty" version below. + inject_csr.wfo( + utra::keyinject::UART_CHAR_CHAR, + uart_csr.rf(utra::uart::RXTX_RXTX), + ); + uart_csr.wfo(utra::uart::EV_PENDING_RX, 1); + + // I guess this is how you would do it if you were "really doing Rust" + // (except this is checking pending not fifo status for loop termination) + // (which was really hard to figure out just looking at this loop) + /* + let maybe_c = match uart_csr.rf(utra::uart::EV_PENDING_RX) { + 0 => None, + ack => { + let c = Some(uart_csr.rf(utra::uart::RXTX_RXTX) as u8); + uart_csr.wfo(utra::uart::EV_PENDING_RX, ack); + c + } + }; + if let Some(c) = maybe_c { + inject_csr.wfo(utra::keyinject::UART_CHAR_CHAR, (c & 0xff) as u32); + } else { + break; + }*/ + } + // println!("rxe {}", uart_csr.rf(utra::uart::RXEMPTY_RXEMPTY)); + // println!("pnd {}", uart_csr.rf(utra::uart::EV_PENDING_RX)); + } +} + +pub struct OutputWriter {} + +impl OutputWriter { + pub fn putc(&self, c: u8) { + if cfg!(feature = "logging") { + let mut uart_csr = CSR::new(unsafe { crate::debug::DEFAULT_UART_ADDR as *mut u32 }); + + // Wait until TXFULL is `0` + while uart_csr.r(utra::uart::TXFULL) != 0 {} + uart_csr.wo(utra::uart::RXTX, c as u32); + + // there's a race condition in the handler, if a new character comes in while handling the interrupt, + // the pending bit never clears. If the console seems to freeze, uncomment this line. + // This kind of works around that, at the expense of maybe losing some Rx characters. + // uart_csr.wfo(utra::uart::EV_PENDING_RX, 1); + } + } + + /// Write a buffer to the output and return the number of + /// bytes written. This is mostly compatible with `std::io::Write`, + /// except it is infallible. + pub fn write(&mut self, buf: &[u8]) -> usize { + for c in buf { + self.putc(*c); + } + buf.len() + } + + pub fn write_all(&mut self, buf: &[u8]) -> core::result::Result { + Ok(self.write(buf)) + } +} + +impl Write for OutputWriter { + fn write_str(&mut self, s: &str) -> Result<(), Error> { + for c in s.bytes() { + self.putc(c); + if c == '\n' as u8 { + self.putc('\r' as u8); + } + } + Ok(()) + } +} diff --git a/services/xous-log/src/platform/precursor/mod.rs b/services/xous-log/src/platform/precursor/mod.rs new file mode 100644 index 000000000..6e585ca5e --- /dev/null +++ b/services/xous-log/src/platform/precursor/mod.rs @@ -0,0 +1,5 @@ +#[cfg(feature = "debugprint")] +#[macro_use] +pub mod debug; + +pub mod implementation;