From 10e65db7487700f78e4b0ed7a7e32817a6085365 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 14 Mar 2021 18:28:44 +0800 Subject: [PATCH 01/10] loader: limit the kernel to 4 kB Signed-off-by: Sean Cross --- loader/src/main.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/loader/src/main.rs b/loader/src/main.rs index 6781e3c9e..8d8e3e058 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -21,6 +21,7 @@ const USER_AREA_END: usize = 0xff00_0000; // and therefore are limited to 4 MB. const EXCEPTION_STACK_TOP: usize = 0xffff_0000; const KERNEL_LOAD_OFFSET: usize = 0xffd0_0000; +const KERNEL_STACK_PAGE_COUNT: usize = 1; const KERNEL_ARGUMENT_OFFSET: usize = 0xffc0_0000; const FLG_VALID: usize = 0x1; @@ -421,7 +422,7 @@ impl ProgramDescription { allocator.change_owner(pid as XousPid, pt_addr as usize); // Allocate stack pages. - for i in 0..STACK_PAGE_COUNT { + for i in 0..if is_kernel { KERNEL_STACK_PAGE_COUNT} else { STACK_PAGE_COUNT } { let sp_page = allocator.alloc() as usize; allocator.map_page( satp, From 55a09990f095792611ed5f0079485023f30ce7b7 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Sun, 14 Mar 2021 18:29:04 +0800 Subject: [PATCH 02/10] hosted: pre-allocate buffers for performace boost Buffers have a known size. We can avoid reallocations by preallocating buffers to this known size. Signed-off-by: Sean Cross --- kernel/src/arch/hosted.rs | 9 +++++++-- xous-rs/src/arch/hosted.rs | 7 ++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/kernel/src/arch/hosted.rs b/kernel/src/arch/hosted.rs index e5ace70ca..59a0a2ef7 100644 --- a/kernel/src/arch/hosted.rs +++ b/kernel/src/arch/hosted.rs @@ -64,7 +64,7 @@ pub fn set_send_addr(send_addr: Sender) { #[cfg(not(test))] fn generate_pid_key() -> [u8; 16] { - use ::rand::{thread_rng, Rng}; + use rand::{thread_rng, Rng}; let mut process_key = [0u8; 16]; let mut rng = thread_rng(); for b in process_key.iter_mut() { @@ -576,7 +576,12 @@ pub fn idle() -> bool { crate::arch::process::set_current_pid(pid); let mut process = Process::current(); - let mut response_vec = Vec::new(); + let mut capacity = 9 * core::mem::size_of::(); + if let Some(mem) = response.memory() { + capacity += mem.len(); + } + let mut response_vec = Vec::with_capacity(capacity); + response_vec.extend_from_slice(&thread_id.to_le_bytes()); for word in response.to_args().iter_mut() { response_vec.extend_from_slice(&word.to_le_bytes()); diff --git a/xous-rs/src/arch/hosted.rs b/xous-rs/src/arch/hosted.rs index cf16139dc..aa172951c 100644 --- a/xous-rs/src/arch/hosted.rs +++ b/xous-rs/src/arch/hosted.rs @@ -665,7 +665,12 @@ fn _xous_syscall_to( // ); // Send the packet to the server - let mut pkt = vec![]; + let mut capacity = 9 * core::mem::size_of::(); + if let Some(mem) = call.memory() { + capacity += mem.len(); + } + + let mut pkt = Vec::with_capacity(capacity); THREAD_ID.with(|tid| pkt.extend_from_slice(&tid.borrow().to_le_bytes())); for word in &[nr, a1, a2, a3, a4, a5, a6, a7] { pkt.extend_from_slice(&word.to_le_bytes()); From 80c41f1dfce2f4dfd10a06f5b12f9410662b0d85 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Mon, 15 Mar 2021 11:21:29 +0800 Subject: [PATCH 03/10] kernel: fix build in hosted mode for rand The `rand` module exists now, which conflicts with the `rand` crate. Signed-off-by: Sean Cross --- kernel/src/arch/hosted.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/src/arch/hosted.rs b/kernel/src/arch/hosted.rs index 59a0a2ef7..e6af71273 100644 --- a/kernel/src/arch/hosted.rs +++ b/kernel/src/arch/hosted.rs @@ -64,7 +64,7 @@ pub fn set_send_addr(send_addr: Sender) { #[cfg(not(test))] fn generate_pid_key() -> [u8; 16] { - use rand::{thread_rng, Rng}; + use ::rand::{thread_rng, Rng}; let mut process_key = [0u8; 16]; let mut rng = thread_rng(); for b in process_key.iter_mut() { From eff3e7d7bf9d136cfc3a308a87c6cbd6a3b421a6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 15:52:13 +0800 Subject: [PATCH 04/10] incremental i2c changes --- Cargo.lock | 74 ++++++++-------------------------- services/llio/Cargo.toml | 6 +-- services/llio/src/api.rs | 17 ++++---- services/llio/src/lib.rs | 26 ++++++------ services/xous-names/src/api.rs | 3 ++ 5 files changed, 43 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 002edb4f4..dc822fa6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -70,7 +70,7 @@ dependencies = [ "graphics-server", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -83,7 +83,7 @@ version = "0.1.0" dependencies = [ "log", "log-server", - "rkyv 0.3.1", + "rkyv", "utralib", "xous", "xous-names", @@ -124,7 +124,7 @@ version = "0.5.0" source = "git+https://github.com/betrusted-io/blitstr.git?rev=d4516b0a6fa3ae6d29e5e323513158c4cd6b8b16#d4516b0a6fa3ae6d29e5e323513158c4cd6b8b16" dependencies = [ "log", - "rkyv 0.3.1", + "rkyv", ] [[package]] @@ -241,7 +241,7 @@ dependencies = [ "heapless", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "typenum", "utralib", @@ -276,7 +276,7 @@ version = "0.1.0" dependencies = [ "graphics-server", "log", - "rkyv 0.3.1", + "rkyv", "xous", "xous-names", ] @@ -415,7 +415,7 @@ dependencies = [ "keyboard", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "trng", "utralib", @@ -479,7 +479,7 @@ dependencies = [ "log", "log-server", "minifb", - "rkyv 0.3.1", + "rkyv", "utralib", "xous", "xous-names", @@ -559,7 +559,7 @@ dependencies = [ "keyboard", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -572,7 +572,7 @@ version = "0.1.0" dependencies = [ "graphics-server", "log", - "rkyv 0.3.1", + "rkyv", "xous", "xous-names", ] @@ -585,7 +585,7 @@ dependencies = [ "ime-plugin-api", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -613,7 +613,7 @@ dependencies = [ "heapless", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -655,7 +655,7 @@ dependencies = [ "heapless", "log", "log-server", - "rkyv 0.4.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -836,26 +836,6 @@ dependencies = [ "unicode-xid 0.2.1", ] -[[package]] -name = "ptr_meta" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aad980f4bb4053abd4733b1680024a8c71ffde345f6e584c6af9eb6f0067a198" -dependencies = [ - "ptr_meta_derive", -] - -[[package]] -name = "ptr_meta_derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bcd6232fa7d7fcd15703da5c07c9f10d203ee4fdf6ecf6d7ac5056db78089a3" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] - [[package]] name = "quick-error" version = "1.2.3" @@ -1036,18 +1016,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ba0dea2b9efaa468bc76d09a06741839d84c70a746edb1793d9653828532666" dependencies = [ "memoffset", - "rkyv_derive 0.3.1", -] - -[[package]] -name = "rkyv" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45a6fdbe501948402e00ede914b4dc21d340105b2eff740ed47e3d45ac846f5c" -dependencies = [ - "memoffset", - "ptr_meta", - "rkyv_derive 0.4.0", + "rkyv_derive", ] [[package]] @@ -1061,17 +1030,6 @@ dependencies = [ "syn 1.0.60", ] -[[package]] -name = "rkyv_derive" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a169f6bc5a81033e86ed39d0f4150e2608160b73d2b93c6e8e6a3efa873f14" -dependencies = [ - "proc-macro2 1.0.24", - "quote 1.0.8", - "syn 1.0.60", -] - [[package]] name = "rustc-hash" version = "1.1.0" @@ -1156,7 +1114,7 @@ dependencies = [ "llio", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", @@ -1593,7 +1551,7 @@ dependencies = [ "hex", "lazy_static", "log", - "rkyv 0.3.1", + "rkyv", "rustc-std-workspace-core", "xous-macros", ] @@ -1617,7 +1575,7 @@ dependencies = [ "heapless", "log", "log-server", - "rkyv 0.3.1", + "rkyv", "ticktimer-server", "utralib", "xous", diff --git a/services/llio/Cargo.toml b/services/llio/Cargo.toml index ccb520313..37aed0c2a 100644 --- a/services/llio/Cargo.toml +++ b/services/llio/Cargo.toml @@ -12,11 +12,7 @@ log-server = { path = "../log-server" } ticktimer-server = { path = "../ticktimer-server" } xous-names = { path = "../xous-names" } log = "0.4" - -[dependencies.rkyv] -version = "0.4.1" -default-features = false -features = ["const_generics"] +rkyv = { version = "0.3.1", default_features = false } [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} diff --git a/services/llio/src/api.rs b/services/llio/src/api.rs index c40abf68d..eec1505ee 100644 --- a/services/llio/src/api.rs +++ b/services/llio/src/api.rs @@ -2,7 +2,7 @@ use xous::{Message, ScalarMessage}; use xous::String; /////////////////////// UART TYPE -#[derive(Debug, rkyv::Archive)] +#[derive(Debug, rkyv::Archive, rkyv::Unarchive)] pub enum UartType { Kernel, Log, @@ -44,7 +44,7 @@ impl Into for UartType { /////////////////////// I2C // a small book-keeping struct used to report back to I2C requestors as to the status of a transaction -#[derive(Debug, Copy, Clone, rkyv::Archive)] +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)] pub enum I2cStatus { /// used only as the default, should always be set to one of the below before sending Uninitialized, @@ -65,13 +65,13 @@ pub enum I2cStatus { /// everything is OK, write finished. data fields have no meaning ResponseWriteOk, } -#[derive(Debug, Copy, Clone, rkyv::Archive)] +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)] pub struct I2cTransaction { bus_addr: u8, // write address and read address are encoded in the packet field below - txbuf: Option<[u8; 258]>, // up to 258 bytes total packet length; note cost is "same" b/c these are sent via 4kiB page remaps + txbuf: Option<[u8; 31]>, // limited by trait types available in Rkyv txlen: u32, - rxbuf: Option<[u8; 258]>, + rxbuf: Option<[u8; 31]>, rxlen: u32, timeout_ms: u32, // response field to the calling server @@ -81,10 +81,11 @@ impl I2cTransaction { pub fn new() -> Self { I2cTransaction{ bus_addr: 0, txbuf: None, txlen: 0, rxbuf: None, rxlen: 0, timeout_ms: 100, status: I2cStatus::Uninitialized } } + pub fn status(&self) -> I2cStatus { self.status } } ////////////////////////////////// VIBE -#[derive(Debug, rkyv::Archive)] +#[derive(Debug, rkyv::Archive, rkyv::Unarchive)] pub enum VibePattern { Short, Long, @@ -110,7 +111,7 @@ impl Into for VibePattern { } //////////////////////////////// CLOCK GATING (placeholder) -#[derive(Debug, rkyv::Archive)] +#[derive(Debug, rkyv::Archive, rkyv::Unarchive)] pub enum ClockMode { Low, AllOn, @@ -133,7 +134,7 @@ impl Into for ClockMode { } //////////////////////////////////// OPCODES -#[derive(Debug, rkyv::Archive)] +#[derive(Debug, rkyv::Archive, rkyv::Unarchive)] pub enum Opcode { /// not tested - reboot RebootRequest, diff --git a/services/llio/src/lib.rs b/services/llio/src/lib.rs index 7bcfda5e7..584f8e10a 100644 --- a/services/llio/src/lib.rs +++ b/services/llio/src/lib.rs @@ -10,11 +10,11 @@ use xous::{send_message, CID}; // used by the LLIO to send a response to other servers pub fn send_i2c_response(cid: CID, transaction: I2cTransaction) -> Result<(), xous::Error> { let op = api::Opcode::I2cResponse(transaction); - let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); - let pos = { - use rkyv::ser::Serializer; - writer.serialize_value(&op).expect("LLIO_API: couldn't archive I2cResponse"); - }; + use rkyv::Write; + let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096)); + let pos = writer + .archive(&op) + .expect("couldn't archive request"); let buf = writer.into_inner(); buf.lend(cid, pos as u32).expect("LLIO_API: I2cResponse operation failure"); @@ -23,20 +23,22 @@ pub fn send_i2c_response(cid: CID, transaction: I2cTransaction) -> Result<(), xo // used by other servers to request an I2C transaction pub fn send_i2c_request(cid: CID, transaction: I2cTransaction) -> Result { let op = api::Opcode::I2cTxRx(transaction); - let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); - let pos = { - use rkyv::ser::Serializer; - writer.serialize_value(&op).expect("LLIO_API: couldn't archive I2cTxRx"); - }; - let buf = writer.into_inner(); + use rkyv::Write; + let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096)); + let pos = writer + .archive(&op) + .expect("couldn't archive request"); + let mut buf = writer.into_inner(); buf.lend_mut(cid, pos as u32).expect("LLIO_API: I2cTxRx operation failure"); let returned = unsafe { rkyv::archived_value::(buf.as_ref(), pos)}; if let rkyv::Archived::::I2cTxRx(result) = returned { + use rkyv::Unarchive; let i2c_txrx: I2cTransaction = result.unarchive(); - Ok(i2c_txrx.status) + Ok(i2c_txrx.status()) } else { + use rkyv::Unarchive; let i2c_txrx = returned.unarchive(); log::info!("send_i2c_request saw an unhandled return type of {:?}", i2c_txrx); Err(xous::Error::InternalError) diff --git a/services/xous-names/src/api.rs b/services/xous-names/src/api.rs index fa2a3225b..c8481324b 100644 --- a/services/xous-names/src/api.rs +++ b/services/xous-names/src/api.rs @@ -84,6 +84,9 @@ impl Authenticate { } } +// note to self: keep around the implementation for the key-able version of the String +// structure, but we can lose the rkyv-able version for the external API + // --------------------- Taken from rkyv docs https://docs.rs/rkyv/0.3.0/rkyv/trait.Archive.html // #[derive(Debug, Copy, Clone)] pub struct XousServerName { From 8b8cad067cf387f7e0ea0c162403c93e03cfec7a Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 15:52:30 +0800 Subject: [PATCH 05/10] add the i2c file proper --- services/llio/src/i2c.rs | 204 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) create mode 100644 services/llio/src/i2c.rs diff --git a/services/llio/src/i2c.rs b/services/llio/src/i2c.rs new file mode 100644 index 000000000..9ed5e9c9e --- /dev/null +++ b/services/llio/src/i2c.rs @@ -0,0 +1,204 @@ +use heapless::Vec; +use heapless::consts::*; + +use crate::api::*; +use utralib::*; + +enum I2cState { + Idle, + Write, + Read, +} +struct I2cStateMachine { + transaction: I2cTransaction, + state: I2cState, + index: u32, // index of the current buffer in the state machine + timestamp: u64, // timestamp of the last transaction + ticktimer: xous::CID, // a connection to the ticktimer so we can measure timeouts + i2c_csr: utralib::CSR, + listeners: Vec, +} +impl I2cStateMachine { + pub fn new(ticktimer: xous::CID, i2c_csr: utralib::CSR) -> Self { + I2cStateMachine { + transaction: I2cTransaction::new(), + state: I2cState::Idle, + timestamp: ticktimer_server::elapsed_ms(ticktimer).unwrap(), + ticktimer, + i2c_csr, + index: 0, + listeners: Vec::new(), + } + } + pub fn initiate(&mut self, transaction: I2cTransaction ) -> I2cStatus { + // sanity-check the bounds limits, currently imposed by trait implementations available in rkyv + if transaction.txlen > 31 || transaction.rxlen > 31 { + return I2cStatus::ResponseFormatError + } + + let now = ticktimer_server::elapsed_ms(ticktimer).unwrap(); + if self.state != I2cState::Idle && ((now - self.timestamp) < self.transaction.timeout_ms) { + // we're in a transaction that hadn't timed out, can't accept a new one + I2cStatus::ResponseBusy + } else { + if self.state != I2cState::Idle { + // we're in a transaction, but previous transaction had timed out... + self.report_timeout(); + // reset our state parameter + self.state = I2cState::Idle; + self.index = 0; + // now we're ready to move on and try a new transaction. We hope! Maybe the block should be reset?? TBD. Need to understand the nature of the timeouts better, if and when they do happen. + } + self.timestamp = now; + self.transaction = transaction.clone(); + + if self.transaction.status == I2cStatus::RequestIncoming { + self.transaction.status = I2cStatus::ResponseInProgress; + // now do the BusAddr stuff, so that the we can get the irq response + if let Some(txbuf) = self.transaction.txbuf { + self.state = I2cState::Write; + self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 0) as u32); + self.index = 0; + self.i2c_csr.wo(utra::i2c::COMMAND, + self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) + ); + I2cStatus::ResponseInProgress + } else if let Some(rxbuf) = self.transaction.rxbuf { + self.state = I2cState::Read; + self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 1) as u32); + self.index = 0; + self.i2c_csr.wo(utra::i2c::COMMAND, + self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) + ); + I2cStatus::ResponseInProgress + } else { + // no buffers specified, erase everything and go to idle + self.state = I2cState::Idle; + self.transaction = I2cTransaction::new(); + I2cStatus::ResponseFormatError + } + } + } + } + fn report_nack(&mut self) { + // report the NACK situation to all the listeners + let mut nack = I2cTransaction::new(); + nack.status = I2cStatus::ResponseNack; + for listener in self.listeners { + send_i2c_response(listener, nack).expect("LLIO|I2C: couldn't send NACK to listeners"); + } + } + fn report_timeout(&mut self) { + let mut timeout = I2cTransaction::new(); + timeout.status = I2cStatus::ResponseTimeout; + for listener in self.listeners { + send_i2c_response(listener, timeout).expect("LLIO|I2c: couldn't send timeout error to liseners"); + } + } + fn report_write_done(&mut self) { + // report the end of a write-only transaction to all the listeners + let mut ack = I2cTransaction::new(); + ack.status = I2cStatus::ResponseWriteOk; + for listener in self.listeners { + send_i2c_response(listener, ack).expect("LLIO|I2C: couldn't send write ACK to listeners"); + } + } + fn report_read_done(&mut self) { + // report the result of a read transaction to all the listeners + self.transaction.status = I2cStatus::ResponseReadOk; + for listener in self.listeners { + send_i2c_response(listener, self.transaction).expect("LLIO|I2C: couldn't send read response to listeners"); + } + } + pub fn register_listener(&mut self, listener: xous::CID) -> Result<(), xous::CID> { + self.listeners.push(listener) + } + pub fn handler(&mut self) { + // check if the transaction had actually timed out + let now = ticktimer_server::elapsed_ms(ticktimer).unwrap(); + if now - self.timestamp > self.transaction.timeout_ms { + // previous transaction had timed out... + self.report_timeout(); + // reset our state parameter + self.state = I2cState::Idle; + self.index = 0; + self.timestamp = now; + return; + } + self.timestamp = now; + + match self.state { + I2cState::Write => { + if let Some(txbuf) = self.transaction.txbuf { + // check ack bit + if self.i2c_csr.rf(utra::i2c::STATUS_RXACK) != 1 { + self.state = I2cState::Idle; + self.transaction = I2cTransaction::new(); + self.report_nack(); + } + // send next byte if there is one + if self.index < self.transaction.txlen { + self.i2c_csr.wfo(utra::i2c::TXR_TXR, txbuf[self.index as usize] as u32); + if self.index == (self.transaction.txlen - 1) && self.transaction.rxbuf.is_none() { + // send a stop bit if this is the very last in the series + self.i2c_csr.wo(utra::i2c::COMMAND, + self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1) + ); + } else { + self.i2c_csr.wfo(utra::i2c::COMMAND_WR, 1); + } + self.index += 1; + } else { + if let Some(rxbuf) = self.transaction.rxbuf { + self.state = I2cState::Read; + self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 1) as u32); + self.index = 0; + self.i2c_csr.wo(utra::i2c::COMMAND, + self.i2c_csr.ms(utra::i2c::COMMAND_WR, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) + ); + } else { + self.report_write_done(); + self.state = I2cState::Idle; + } + } + } else { + // we should never get here, because txbuf was checked as Some() by the setup routine + log::error!("LLIO|I2C: illegal write state"); + } + }, + I2cState::Read => { + if let Some(rxbuf) = self.transaction.rxbuf { + if self.index > 0 { + // we are re-entering from a previous call, store the read value from the previous call + rxbuf[index - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8; + } + if self.index < self.transaction.rxlen { + if self.index == (self.transaction.rxlen - 1) { + self.i2c_csr.wo(utra::i2c::COMMAND, + self.i2c_csr.ms(utra::i2c::COMMAND_RD, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_STO, 1) | + self.i2c_csr.ms(utra::i2c::COMMAND_ACK, 1) + ); + } else { + self.i2c_csr.wfo(utra::i2c::COMMAND_RD, 1); + } + self.index += 1; + } else { + self.report_read_done(); + self.state = I2cState::Idle; + } + } else { + // we should never get here, because rxbuf was checked as Some() by the setup routine + log::error!("LLIO|I2C: illegal read state"); + } + }, + I2cState::Idle => { + log::error!("LLIO|I2C: received interrupt event when no transaciton pending!"); + } + } + } +} From d74b3189e64e8df37bc32f0e063297fad3712af2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 16:37:38 +0800 Subject: [PATCH 06/10] it builds, at least. --- services/llio/src/api.rs | 17 ++++++------ services/llio/src/i2c.rs | 41 +++++++++++++++++------------ services/llio/src/lib.rs | 2 +- services/llio/src/main.rs | 55 ++++++++++++++++++--------------------- 4 files changed, 58 insertions(+), 57 deletions(-) diff --git a/services/llio/src/api.rs b/services/llio/src/api.rs index eec1505ee..2f5c4b35c 100644 --- a/services/llio/src/api.rs +++ b/services/llio/src/api.rs @@ -44,7 +44,7 @@ impl Into for UartType { /////////////////////// I2C // a small book-keeping struct used to report back to I2C requestors as to the status of a transaction -#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)] +#[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive, Eq, PartialEq)] pub enum I2cStatus { /// used only as the default, should always be set to one of the below before sending Uninitialized, @@ -67,21 +67,20 @@ pub enum I2cStatus { } #[derive(Debug, Copy, Clone, rkyv::Archive, rkyv::Unarchive)] pub struct I2cTransaction { - bus_addr: u8, + pub bus_addr: u8, // write address and read address are encoded in the packet field below - txbuf: Option<[u8; 31]>, // limited by trait types available in Rkyv - txlen: u32, - rxbuf: Option<[u8; 31]>, - rxlen: u32, - timeout_ms: u32, + pub txbuf: Option<[u8; 31]>, // limited by trait types available in Rkyv + pub txlen: u32, + pub rxbuf: Option<[u8; 31]>, + pub rxlen: u32, + pub timeout_ms: u32, // response field to the calling server - status: I2cStatus, + pub status: I2cStatus, } impl I2cTransaction { pub fn new() -> Self { I2cTransaction{ bus_addr: 0, txbuf: None, txlen: 0, rxbuf: None, rxlen: 0, timeout_ms: 100, status: I2cStatus::Uninitialized } } - pub fn status(&self) -> I2cStatus { self.status } } ////////////////////////////////// VIBE diff --git a/services/llio/src/i2c.rs b/services/llio/src/i2c.rs index 9ed5e9c9e..dc82189bc 100644 --- a/services/llio/src/i2c.rs +++ b/services/llio/src/i2c.rs @@ -1,15 +1,17 @@ use heapless::Vec; use heapless::consts::*; -use crate::api::*; +use llio::api::*; +use llio::send_i2c_response; use utralib::*; +#[derive(Eq, PartialEq)] enum I2cState { Idle, Write, Read, } -struct I2cStateMachine { +pub struct I2cStateMachine { transaction: I2cTransaction, state: I2cState, index: u32, // index of the current buffer in the state machine @@ -19,13 +21,13 @@ struct I2cStateMachine { listeners: Vec, } impl I2cStateMachine { - pub fn new(ticktimer: xous::CID, i2c_csr: utralib::CSR) -> Self { + pub fn new(ticktimer: xous::CID, i2c_base: *mut u32) -> Self { I2cStateMachine { transaction: I2cTransaction::new(), state: I2cState::Idle, timestamp: ticktimer_server::elapsed_ms(ticktimer).unwrap(), ticktimer, - i2c_csr, + i2c_csr: CSR::new(i2c_base), index: 0, listeners: Vec::new(), } @@ -36,8 +38,8 @@ impl I2cStateMachine { return I2cStatus::ResponseFormatError } - let now = ticktimer_server::elapsed_ms(ticktimer).unwrap(); - if self.state != I2cState::Idle && ((now - self.timestamp) < self.transaction.timeout_ms) { + let now = ticktimer_server::elapsed_ms(self.ticktimer).unwrap(); + if self.state != I2cState::Idle && ((now - self.timestamp) < self.transaction.timeout_ms as u64) { // we're in a transaction that hadn't timed out, can't accept a new one I2cStatus::ResponseBusy } else { @@ -55,7 +57,8 @@ impl I2cStateMachine { if self.transaction.status == I2cStatus::RequestIncoming { self.transaction.status = I2cStatus::ResponseInProgress; // now do the BusAddr stuff, so that the we can get the irq response - if let Some(txbuf) = self.transaction.txbuf { + if let Some(_txbuf) = self.transaction.txbuf { + // initiate bus address with write bit set self.state = I2cState::Write; self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 0) as u32); self.index = 0; @@ -64,7 +67,8 @@ impl I2cStateMachine { self.i2c_csr.ms(utra::i2c::COMMAND_STA, 1) ); I2cStatus::ResponseInProgress - } else if let Some(rxbuf) = self.transaction.rxbuf { + } else if let Some(_rxbuf) = self.transaction.rxbuf { + // initiate bus address with read bit set self.state = I2cState::Read; self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 1) as u32); self.index = 0; @@ -79,6 +83,8 @@ impl I2cStateMachine { self.transaction = I2cTransaction::new(); I2cStatus::ResponseFormatError } + } else { + I2cStatus::ResponseFormatError // the status field was not formatted correctly to accept the transaction } } } @@ -86,14 +92,14 @@ impl I2cStateMachine { // report the NACK situation to all the listeners let mut nack = I2cTransaction::new(); nack.status = I2cStatus::ResponseNack; - for listener in self.listeners { + for &listener in self.listeners.iter() { send_i2c_response(listener, nack).expect("LLIO|I2C: couldn't send NACK to listeners"); } } fn report_timeout(&mut self) { let mut timeout = I2cTransaction::new(); timeout.status = I2cStatus::ResponseTimeout; - for listener in self.listeners { + for &listener in self.listeners.iter() { send_i2c_response(listener, timeout).expect("LLIO|I2c: couldn't send timeout error to liseners"); } } @@ -101,14 +107,14 @@ impl I2cStateMachine { // report the end of a write-only transaction to all the listeners let mut ack = I2cTransaction::new(); ack.status = I2cStatus::ResponseWriteOk; - for listener in self.listeners { + for &listener in self.listeners.iter() { send_i2c_response(listener, ack).expect("LLIO|I2C: couldn't send write ACK to listeners"); } } fn report_read_done(&mut self) { // report the result of a read transaction to all the listeners self.transaction.status = I2cStatus::ResponseReadOk; - for listener in self.listeners { + for &listener in self.listeners.iter() { send_i2c_response(listener, self.transaction).expect("LLIO|I2C: couldn't send read response to listeners"); } } @@ -117,8 +123,8 @@ impl I2cStateMachine { } pub fn handler(&mut self) { // check if the transaction had actually timed out - let now = ticktimer_server::elapsed_ms(ticktimer).unwrap(); - if now - self.timestamp > self.transaction.timeout_ms { + let now = ticktimer_server::elapsed_ms(self.ticktimer).unwrap(); + if now - self.timestamp > self.transaction.timeout_ms as u64 { // previous transaction had timed out... self.report_timeout(); // reset our state parameter @@ -152,7 +158,8 @@ impl I2cStateMachine { } self.index += 1; } else { - if let Some(rxbuf) = self.transaction.rxbuf { + if let Some(_rxbuf) = self.transaction.rxbuf { + // initiate bus address with read bit set self.state = I2cState::Read; self.i2c_csr.wfo(utra::i2c::TXR_TXR, (self.transaction.bus_addr << 1 | 1) as u32); self.index = 0; @@ -171,10 +178,10 @@ impl I2cStateMachine { } }, I2cState::Read => { - if let Some(rxbuf) = self.transaction.rxbuf { + if let Some(mut rxbuf) = self.transaction.rxbuf { if self.index > 0 { // we are re-entering from a previous call, store the read value from the previous call - rxbuf[index - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8; + rxbuf[self.index as usize - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8; } if self.index < self.transaction.rxlen { if self.index == (self.transaction.rxlen - 1) { diff --git a/services/llio/src/lib.rs b/services/llio/src/lib.rs index 584f8e10a..4a168d0d1 100644 --- a/services/llio/src/lib.rs +++ b/services/llio/src/lib.rs @@ -36,7 +36,7 @@ pub fn send_i2c_request(cid: CID, transaction: I2cTransaction) -> Result::I2cTxRx(result) = returned { use rkyv::Unarchive; let i2c_txrx: I2cTransaction = result.unarchive(); - Ok(i2c_txrx.status()) + Ok(i2c_txrx.status) } else { use rkyv::Unarchive; let i2c_txrx = returned.unarchive(); diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 83a2c3146..2f94f1c12 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -2,22 +2,23 @@ #![cfg_attr(target_os = "none", no_main)] mod api; -use api::*; +use llio::api::*; mod i2c; use i2c::*; use core::convert::TryFrom; +use core::pin::Pin; +use rkyv::archived_value; +use rkyv::Unarchive; use log::{error, info}; #[cfg(target_os = "none")] mod implementation { - use crate::api::*; + use llio::api::*; use log::{error, info}; use utralib::generated::*; - const STD_TIMEOUT: u32 = 100; - pub struct Llio { reboot_csr: utralib::CSR, crg_csr: utralib::CSR, @@ -25,7 +26,7 @@ mod implementation { info_csr: utralib::CSR, identifier_csr: utralib::CSR, i2c_csr: utralib::CSR, - handler_conn: xous::CID, + handler_conn: Option, event_csr: utralib::CSR, power_csr: utralib::CSR, seed_csr: utralib::CSR, @@ -49,8 +50,8 @@ mod implementation { // ASSUME: we are only ever handling txrx done interrupts. If implementing ARB interrupts, this needs to be refactored to read the source and dispatch accordingly. fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) { let xl = unsafe { &mut *(arg as *mut Llio) }; - if let Some(conn) = xl.i2c_conn { - xous::try_send_message(xl.handler_conn, Opcode::IrqI2cTxrxDone.into()).map(|_| ()).unwrap(); + if let Some(conn) = xl.handler_conn { + xous::try_send_message(conn, Opcode::IrqI2cTxrxDone.into()).map(|_| ()).unwrap(); } else { log::error!("LLIO|handle_i2c_irq: TXRX done interrupt, but no connection for notification!"); } @@ -59,7 +60,9 @@ mod implementation { } impl Llio { - pub fn new(local_conn: xous::CID) -> Llio { + pub fn get_i2c_base(&self) -> *mut u32 { self.i2c_csr.base } + + pub fn new(handler_conn: xous::CID) -> Llio { let reboot_csr = xous::syscall::map_memory( xous::MemoryAddress::new(utra::reboot::HW_REBOOT_BASE), None, @@ -102,7 +105,6 @@ mod implementation { xous::MemoryFlags::R | xous::MemoryFlags::W, ) .expect("couldn't map I2C CSR range"); - let i2c_sid = xous::create_server_id().expect("LLIO: couldn't get random server ID for I2C"); let event_csr = xous::syscall::map_memory( xous::MemoryAddress::new(utra::btevents::HW_BTEVENTS_BASE), None, @@ -142,7 +144,7 @@ mod implementation { info_csr: CSR::new(info_csr.as_mut_ptr() as *mut u32), identifier_csr: CSR::new(identifier_csr.as_mut_ptr() as *mut u32), i2c_csr: CSR::new(i2c_csr.as_mut_ptr() as *mut u32), - handler_conn, // connection for messages from IRQ handler + handler_conn: Some(handler_conn), // connection for messages from IRQ handler event_csr: CSR::new(event_csr.as_mut_ptr() as *mut u32), power_csr: CSR::new(power_csr.as_mut_ptr() as *mut u32), seed_csr: CSR::new(seed_csr.as_mut_ptr() as *mut u32), @@ -176,8 +178,12 @@ mod implementation { ) .expect("couldn't claim I2C irq"); - // initialize i2c - i2c_init(&mut xl, utralib::LITEX_CONFIG_CLOCK_FREQUENCY); + // initialize i2c clocks + // set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199 + let clkcode = (utralib::LITEX_CONFIG_CLOCK_FREQUENCY as u32) / (5 * 100_000) - 1; + xl.i2c_csr.wfo(utra::i2c::PRESCALE_PRESCALE, clkcode & 0xFFFF); + // enable the block + xl.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 1); // clear any interrupts pending, just in case something went pear-shaped during initialization xl.i2c_csr.wo(utra::i2c::EV_PENDING, xl.i2c_csr.r(utra::i2c::EV_PENDING)); // now enable interrupts @@ -348,16 +354,6 @@ mod implementation { pub fn xadc_gpio2(&self) -> u16 { self.xadc_csr.rf(utra::trng::XADC_GPIO2_XADC_GPIO2) as u16 } - - - fn i2c_init(&mut self, clock_hz: u32) { - // set the prescale assuming 100MHz cpu operation: 100MHz / ( 5 * 100kHz ) - 1 = 199 - let clkcode: u32 = clock_hz / (5 * 100_000) - 1; - self.i2c_csr.wfo(utra::i2c::PRESCALE_PRESCALE, clkcode & 0xFFFF); - - // enable the block - self.i2c_csr.rmwf(utra::i2c::CONTROL_EN, 1); - } } } @@ -435,8 +431,6 @@ mod implementation { fn xmain() -> ! { let debug1 = false; use crate::implementation::Llio; - //use heapless::Vec; - //use heapless::consts::*; log_server::init_wait().unwrap(); info!("LLIO: my PID is {}", xous::process::id()); @@ -452,7 +446,7 @@ fn xmain() -> ! { let ticktimer_server_id = xous::SID::from_bytes(b"ticktimer-server").unwrap(); let ticktimer_conn = xous::connect(ticktimer_server_id).unwrap(); // create an i2c state machine handler - let mut i2c_machine = I2cStateMachine::new(ticktimer_conn, llio.i2c_csr); + let mut i2c_machine = I2cStateMachine::new(ticktimer_conn, llio.get_i2c_base()); if debug1{info!("LLIO: starting main loop");} let mut reboot_requested: bool = false; @@ -590,7 +584,7 @@ fn xmain() -> ! { }, Opcode::IrqI2cTxrxDone => { // I2C state machine handler irq received - ic2_machine.handler(); + i2c_machine.handler(); }, _ => error!("LLIO: no handler for opcode"), } @@ -602,7 +596,7 @@ fn xmain() -> ! { }; match &*value { rkyv::Archived::::I2cTxRx(rkyv_i2c) => { - let i2c_txrx: I2cTransaction = rkyv_i2c.unarchive(); + let mut i2c_txrx: I2cTransaction = rkyv_i2c.unarchive(); let status = i2c_machine.initiate(i2c_txrx); @@ -610,19 +604,20 @@ fn xmain() -> ! { // pack our data back into the buffer to return use rkyv::Write; let mut writer = rkyv::ArchiveBuffer::new(buf); - writer.archive(&api::Opcode::I2cTxRx(i2c_txrx)).expect("LLIO: couldn't re-archive return value to I2cTxRx"); + writer.archive(&Opcode::I2cTxRx(i2c_txrx)).expect("LLIO: couldn't re-archive return value to I2cTxRx"); }, _ => panic!("LLIO: invalid MutableBorrow memory message") }; } else if let xous::Message::Borrow(m) = &envelope.body { - let buf = unsafe { buffer::XousBuffer::from_memory_message(m) }; + let buf = unsafe { xous::XousBuffer::from_memory_message(m) }; let bytes = Pin::new(buf.as_ref()); let value = unsafe { archived_value::(&bytes, m.id as usize) }; match &*value { rkyv::Archived::::I2cSubscribe(registration) => { - let cid = xous_names::request_connection_blocking(registration.as_str()).expect("KBD: can't connect to requested listener for reporting events"); + let reg: xous::String::<64> = registration.unarchive(); + let cid = xous_names::request_connection_blocking(reg.to_str()).expect("KBD: can't connect to requested listener for reporting events"); i2c_machine.register_listener(cid).expect("LLIO: probably ran out of slots for I2C event reporting"); }, _ => panic!("LLIO: invalid Borrow memory message"), From 2fb6ae5ee75879435c31deff1cd4864b14febd15 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 17:03:10 +0800 Subject: [PATCH 07/10] debugging i2c --- emulation/renode.svd | 38 ++++++++++++++++++++++++++++---------- kernel/Cargo.toml | 4 ++-- svd2utra/examples/soc.svd | 38 ++++++++++++++++++++++++++++---------- 3 files changed, 58 insertions(+), 22 deletions(-) diff --git a/emulation/renode.svd b/emulation/renode.svd index 40cf6f1a9..4781c6264 100644 --- a/emulation/renode.svd +++ b/emulation/renode.svd @@ -1362,7 +1362,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x00 + 0x01 32 @@ -1957,8 +1957,7 @@ upon the completion of one byte of data transfer.]]> EV_STATUS - + 0x0018 0x00 32 @@ -1970,12 +1969,18 @@ Writes to this register have no effect.]]> 0 + + txrx_done + 1 + [1:1] + 1 + + EV_PENDING - + 0x001c 0x00 32 @@ -1985,14 +1990,20 @@ register. To clear the Event, set the corresponding bit in this register.]]>0 [0:0] 0 - + + + + txrx_done + 1 + [1:1] + 1 + EV_ENABLE - + 0x0020 0x00 32 @@ -2004,6 +2015,13 @@ register to disable individual events.]]> 0 + + txrx_done + 1 + [1:1] + 1 + + @@ -3038,7 +3056,7 @@ again until the interrupt is serviced.]]> SEED1 0x0000 - 0x48f7dee1 + 0x508efbe6 32 @@ -3053,7 +3071,7 @@ again until the interrupt is serviced.]]> SEED0 0x0004 - 0xc2db130 + 0x1f1cd099 32 diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 4ffce8b58..48c4a326b 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -21,8 +21,8 @@ riscv = "0.5.6" debug-print = [] print-panics = [] report-memory = ["stats_alloc"] -#default = ["print-panics", "debug-print"] -default = ["print-panics"] +default = ["print-panics", "debug-print"] +#default = ["print-panics"] [target.'cfg(any(windows, unix))'.dependencies] lazy_static = "1.4" diff --git a/svd2utra/examples/soc.svd b/svd2utra/examples/soc.svd index 40cf6f1a9..4781c6264 100644 --- a/svd2utra/examples/soc.svd +++ b/svd2utra/examples/soc.svd @@ -1362,7 +1362,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x00 + 0x01 32 @@ -1957,8 +1957,7 @@ upon the completion of one byte of data transfer.]]> EV_STATUS - + 0x0018 0x00 32 @@ -1970,12 +1969,18 @@ Writes to this register have no effect.]]> 0 + + txrx_done + 1 + [1:1] + 1 + + EV_PENDING - + 0x001c 0x00 32 @@ -1985,14 +1990,20 @@ register. To clear the Event, set the corresponding bit in this register.]]>0 [0:0] 0 - + + + + txrx_done + 1 + [1:1] + 1 + EV_ENABLE - + 0x0020 0x00 32 @@ -2004,6 +2015,13 @@ register to disable individual events.]]> 0 + + txrx_done + 1 + [1:1] + 1 + + @@ -3038,7 +3056,7 @@ again until the interrupt is serviced.]]> SEED1 0x0000 - 0x48f7dee1 + 0x508efbe6 32 @@ -3053,7 +3071,7 @@ again until the interrupt is serviced.]]> SEED0 0x0004 - 0xc2db130 + 0x1f1cd099 32 From eda33b5de7d178dac636e981dc8170db5fee9c2b Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 18:03:12 +0800 Subject: [PATCH 08/10] factor out the shellchat callback, which mysterious breaks things --- kernel/Cargo.toml | 4 +- services/shellchat/src/cmds.rs | 86 +++++++++++----------------------- services/shellchat/src/main.rs | 28 ++--------- 3 files changed, 33 insertions(+), 85 deletions(-) diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index 48c4a326b..4ffce8b58 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -21,8 +21,8 @@ riscv = "0.5.6" debug-print = [] print-panics = [] report-memory = ["stats_alloc"] -default = ["print-panics", "debug-print"] -#default = ["print-panics"] +#default = ["print-panics", "debug-print"] +default = ["print-panics"] [target.'cfg(any(windows, unix))'.dependencies] lazy_static = "1.4" diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 0f54633cc..b21da8449 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -1,15 +1,10 @@ -use xous::{String, MessageEnvelope}; +use xous::String; use core::fmt::Write; /////////////////////////// Common items to all commands pub trait ShellCmdApi<'a> { // user implemented: // called to process the command with the remainder of the string attached fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error>; - // called to process incoming messages that may have been origniated by the most recently issued command - fn callback(&mut self, msg: &MessageEnvelope, _env: &mut CommonEnv) -> Result>, xous::Error> { - log::info!("SHCH: received unhandled message {:?}", msg); - Ok(None) - } // created with cmd_api! macro // checks if the command matches the current verb in question @@ -33,7 +28,6 @@ macro_rules! cmd_api { }; } - /////////////////////////// Command shell integration #[derive(Debug)] pub struct CommonEnv { @@ -61,17 +55,14 @@ mod echo; use echo::*; mod test; use test::*; mod sleep; use sleep::*; mod sensors; use sensors::*; -mod callback; use callback::*; #[derive(Debug)] pub struct CmdEnv { common_env: CommonEnv, - lastverb: String::<256>, ///// 2. declare storage for your command here. test_cmd: Test, sleep_cmd: Sleep, sensors_cmd: Sensors, - callback_cmd: CallBack, } impl CmdEnv { pub fn new(gam: xous::CID) -> CmdEnv { @@ -83,16 +74,14 @@ impl CmdEnv { ticktimer: xous::connect(ticktimer_server_id).unwrap(), gam, }, - lastverb: String::<256>::new(), ///// 3. initialize your storage, by calling new() test_cmd: Test::new(), sleep_cmd: Sleep::new(), sensors_cmd: Sensors::new(), - callback_cmd: CallBack::new(), } } - pub fn dispatch(&mut self, maybe_cmdline: Option<&mut String::<1024>>, maybe_callback: Option<&MessageEnvelope>) -> Result>, xous::Error> { + pub fn dispatch(&mut self, cmdline: &mut String::<1024>) -> Result>, xous::Error> { let mut ret = String::<1024>::new(); let mut echo_cmd = Echo {}; // this command has no persistent storage, so we can "create" it every time we call dispatch (but it's a zero-cost absraction so this doesn't actually create any instructions) @@ -102,59 +91,38 @@ impl CmdEnv { &mut self.test_cmd, &mut self.sleep_cmd, &mut self.sensors_cmd, - &mut self.callback_cmd, ]; - if let Some(cmdline) = maybe_cmdline { - let maybe_verb = tokenize(cmdline); + let maybe_verb = tokenize(cmdline); - let mut cmd_ret: Result>, xous::Error> = Ok(None); - if let Some(verb_string) = maybe_verb { - let verb = verb_string.to_str(); + let mut cmd_ret: Result>, xous::Error> = Ok(None); + if let Some(verb_string) = maybe_verb { + let verb = verb_string.to_str(); - // search through the list of commands linearly until one matches, - // then run it. - let mut match_found = false; - for cmd in commands.iter_mut() { - if cmd.matches(verb) { - match_found = true; - cmd_ret = cmd.process(*cmdline, &mut self.common_env); - self.lastverb.clear(); - write!(self.lastverb, "{}", verb).expect("SHCH: couldn't record last verb"); - }; - } - - // if none match, create a list of available commands - if !match_found { - let mut first = true; - write!(ret, "Commands: ").unwrap(); - for cmd in commands.iter() { - if !first { - ret.append(", ")?; - } - ret.append(cmd.verb())?; - first = false; - } - Ok(Some(ret)) - } else { - cmd_ret - } - } else { - Ok(None) + // search through the list of commands linearly until one matches, + // then run it. + let mut match_found = false; + for cmd in commands.iter_mut() { + if cmd.matches(verb) { + match_found = true; + cmd_ret = cmd.process(*cmdline, &mut self.common_env); + }; } - } else if let Some(callback) = maybe_callback { - let mut cmd_ret: Result>, xous::Error> = Ok(None); - if self.lastverb.len() > 0 { - let verb = self.lastverb.to_str(); - for cmd in commands.iter_mut() { - if cmd.matches(verb) { - cmd_ret = cmd.callback(callback, &mut self.common_env); - break; - }; + + // if none match, create a list of available commands + if !match_found { + let mut first = true; + write!(ret, "Commands: ").unwrap(); + for cmd in commands.iter() { + if !first { + ret.append(", ")?; + } + ret.append(cmd.verb())?; + first = false; } - cmd_ret + Ok(Some(ret)) } else { - Ok(None) + cmd_ret } } else { Ok(None) diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index f799698ec..d49315962 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -1,7 +1,7 @@ #![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_main)] -use log::info; +use log::{error, info}; use core::fmt::Write; use core::convert::TryFrom; @@ -16,8 +16,6 @@ use graphics_server::{Gid, Point, Rectangle, TextBounds, TextView, DrawStyle, Gl use heapless::spsc::Queue; use heapless::consts::U16; -use xous::MessageEnvelope; - mod cmds; use cmds::*; @@ -34,8 +32,7 @@ struct Repl { // optional structures that indicate new input to the Repl loop per iteration // an input string input: Option>, - // messages from other servers - msg: Option, + // examples of future inputs: returned values via other services // record our input history history: Queue, @@ -60,7 +57,6 @@ impl Repl{ let screensize = gam::get_canvas_bounds(gam_conn, content).expect("SHCH: couldn't get dimensions of content canvas"); Repl { input: None, - msg: None, history: Queue::new(), content, gam: gam_conn, @@ -84,10 +80,6 @@ impl Repl{ Ok(()) } - fn msg(&mut self, message: MessageEnvelope) { - self.msg = Some(message); - } - fn circular_push(&mut self, item: History) { if self.history.len() == self.history.capacity() { self.history.dequeue().expect("SHCH: couldn't dequeue historye"); @@ -116,17 +108,7 @@ impl Repl{ // take the input and pass it on to the various command parsers, and attach result if let Some(mut local) = self.input { - if let Some(res) = self.env.dispatch(Some(&mut local), None).expect("SHCH: command dispatch failed") { - let mut response = xous::String::<1024>::new(); - write!(response, "{}", res).expect("SHCH: can't copy result to history"); - let output_history = History { - text: response, - is_input: false - }; - self.circular_push(output_history); - } - } else if let Some(msg) = &self.msg { - if let Some(res) = self.env.dispatch(None, Some(msg)).expect("SCHC: callback failed") { + if let Some(res) = self.env.dispatch(&mut local).expect("SHCH: command dispatch failed") { let mut response = xous::String::<1024>::new(); write!(response, "{}", res).expect("SHCH: can't copy result to history"); let output_history = History { @@ -139,7 +121,6 @@ impl Repl{ // clear all the inputs to the loop, so we don't process them twice self.input = None; - self.msg = None; // redraw UI now that we've responded self.redraw().expect("SHCH: can't redraw"); @@ -252,8 +233,7 @@ fn xmain() -> ! { } } } else { - repl.msg(envelope); - update_repl = true; + error!("SHCH: couldn't convert message"); } if update_repl { From edb099d3f23c76921ac62b99ef270503b649efad Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 19:28:01 +0800 Subject: [PATCH 09/10] fix hosted mode with dummy i2c emulation calls --- services/llio/src/i2c.rs | 22 ++++++++++++++++++++++ services/llio/src/main.rs | 5 +++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/services/llio/src/i2c.rs b/services/llio/src/i2c.rs index dc82189bc..cc7f5b332 100644 --- a/services/llio/src/i2c.rs +++ b/services/llio/src/i2c.rs @@ -3,6 +3,8 @@ use heapless::consts::*; use llio::api::*; use llio::send_i2c_response; + +#[cfg(target_os = "none")] use utralib::*; #[derive(Eq, PartialEq)] @@ -11,6 +13,25 @@ enum I2cState { Write, Read, } + +#[cfg(not(target_os = "none"))] +pub struct I2cStateMachine { +} +#[cfg(not(target_os = "none"))] +impl I2cStateMachine { + pub fn new(_ticktimer: xous::CID, _i2c_base: *mut u32) -> Self { + I2cStateMachine {} + } + pub fn initiate(&mut self, _transaction: I2cTransaction ) -> I2cStatus { + I2cStatus::ResponseInProgress + } + pub fn register_listener(&mut self, _listener: xous::CID) -> Result<(), xous::CID> { + Ok(()) + } + pub fn handler(&mut self) { + } +} +#[cfg(target_os = "none")] pub struct I2cStateMachine { transaction: I2cTransaction, state: I2cState, @@ -20,6 +41,7 @@ pub struct I2cStateMachine { i2c_csr: utralib::CSR, listeners: Vec, } +#[cfg(target_os = "none")] impl I2cStateMachine { pub fn new(ticktimer: xous::CID, i2c_base: *mut u32) -> Self { I2cStateMachine { diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 2f94f1c12..a86e8ff16 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -360,17 +360,18 @@ mod implementation { // a stub to try to avoid breaking hosted mode for as long as possible. #[cfg(not(target_os = "none"))] mod implementation { - use crate::api::*; + use llio::api::*; use log::{error, info}; pub struct Llio { } impl Llio { - pub fn new() -> Llio { + pub fn new(_handler_conn: xous::CID) -> Llio { Llio { } } + pub fn get_i2c_base(&self) -> *mut u32 { 0 as *mut u32 } pub fn reboot(&self, _reboot_soc: bool) {} pub fn set_reboot_vector(&self, _vector: u32) {} From 89aa1b4c06bfbba20231e52360753d6182256697 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 16 Mar 2021 19:28:53 +0800 Subject: [PATCH 10/10] svd changes due to recompilation of SoC --- emulation/renode.svd | 12 ++++++------ svd2utra/examples/soc.svd | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/emulation/renode.svd b/emulation/renode.svd index 4781c6264..3ae9e4c40 100644 --- a/emulation/renode.svd +++ b/emulation/renode.svd @@ -1328,10 +1328,10 @@ register to disable individual events.]]> GIT_GITREV 0x0014 - 0xd77dca2f + 0x2a2abe5e 32 @@ -1348,7 +1348,7 @@ the exact git version used to build this firmware.]]> is ``1``, then the repository this was built from has one additional commit beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> 0x0018 - 0x0d + 0x0e 32 @@ -1362,7 +1362,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x01 + 0x00 32 @@ -3056,7 +3056,7 @@ again until the interrupt is serviced.]]> SEED1 0x0000 - 0x508efbe6 + 0x1a7a2a66 32 @@ -3071,7 +3071,7 @@ again until the interrupt is serviced.]]> SEED0 0x0004 - 0x1f1cd099 + 0x4b326b1e 32 diff --git a/svd2utra/examples/soc.svd b/svd2utra/examples/soc.svd index 4781c6264..3ae9e4c40 100644 --- a/svd2utra/examples/soc.svd +++ b/svd2utra/examples/soc.svd @@ -1328,10 +1328,10 @@ register to disable individual events.]]> GIT_GITREV 0x0014 - 0xd77dca2f + 0x2a2abe5e 32 @@ -1348,7 +1348,7 @@ the exact git version used to build this firmware.]]> is ``1``, then the repository this was built from has one additional commit beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> 0x0018 - 0x0d + 0x0e 32 @@ -1362,7 +1362,7 @@ beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> GIT_DIRTY 0x001c - 0x01 + 0x00 32 @@ -3056,7 +3056,7 @@ again until the interrupt is serviced.]]> SEED1 0x0000 - 0x508efbe6 + 0x1a7a2a66 32 @@ -3071,7 +3071,7 @@ again until the interrupt is serviced.]]> SEED0 0x0004 - 0x1f1cd099 + 0x4b326b1e 32