From b43eb56346cd737b61d8a76bf2aff78baa38cef5 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 8 Oct 2021 20:01:13 +0800 Subject: [PATCH] add some skeleton for a `net` crate; testing COM interrupts --- Cargo.lock | 40 ++++++++++++++++++- Cargo.toml | 2 + imports/com_rs-ref/Cargo.toml | 2 +- services/com/src/api.rs | 43 ++++++++++++++++++++ services/com/src/lib.rs | 64 +++++++++++++++++++++++++++++- services/com/src/main.rs | 25 ++++++++++++ services/llio/src/main.rs | 3 +- services/net/Cargo.toml | 30 ++++++++++++++ services/net/src/api.rs | 11 ++++++ services/net/src/lib.rs | 33 ++++++++++++++++ services/net/src/main.rs | 74 +++++++++++++++++++++++++++++++++++ services/pddb/src/api.rs | 69 ++++++++++++++++++++++++++++++++ services/pddb/src/lib.rs | 2 + services/pddb/src/main.rs | 73 +--------------------------------- xtask/src/main.rs | 1 + 15 files changed, 397 insertions(+), 75 deletions(-) create mode 100644 services/net/Cargo.toml create mode 100644 services/net/src/api.rs create mode 100644 services/net/src/lib.rs create mode 100644 services/net/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index b2c46064e..c59356cdb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -461,7 +461,7 @@ dependencies = [ [[package]] name = "com_rs" version = "0.1.0" -source = "git+https://github.com/betrusted-io/com_rs.git?rev=5338f9959572d57f1014d04aa129804da5b4d339#5338f9959572d57f1014d04aa129804da5b4d339" +source = "git+https://github.com/betrusted-io/com_rs.git?rev=0f0998465d756e14d42d96ee348f99c1ba2bedc3#0f0998465d756e14d42d96ee348f99c1ba2bedc3" [[package]] name = "com_rs-ref" @@ -1170,6 +1170,12 @@ dependencies = [ "xous-ipc", ] +[[package]] +name = "managed" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75de51135344a4f8ed3cfe2720dc27736f7711989703a0b43aadf3753c55577" + [[package]] name = "maybe-uninit" version = "2.0.0" @@ -1229,6 +1235,25 @@ dependencies = [ "autocfg", ] +[[package]] +name = "net" +version = "0.1.0" +dependencies = [ + "com", + "llio", + "log", + "log-server", + "num-derive", + "num-traits", + "rkyv 0.7.18", + "smoltcp", + "susres", + "ticktimer-server", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "nix" version = "0.20.0" @@ -2021,6 +2046,19 @@ version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" +[[package]] +name = "smoltcp" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e4a069bef843d170df47e7c0a8bf8d037f217d9f5b325865acc3e466ffe40d3" +dependencies = [ + "bitflags", + "byteorder", + "libc", + "log", + "managed", +] + [[package]] name = "socket2" version = "0.3.19" diff --git a/Cargo.toml b/Cargo.toml index 48e616bb0..2b31ebe36 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ default-members = [ "services/oqc-test", "services/test-stub2", "services/pddb", + "services/net", ] members = [ "xous-ipc", @@ -84,6 +85,7 @@ members = [ "services/oqc-test", "services/test-stub2", "services/pddb", + "services/net", ] resolver = "2" diff --git a/imports/com_rs-ref/Cargo.toml b/imports/com_rs-ref/Cargo.toml index 80c2df69c..cac30ed38 100644 --- a/imports/com_rs-ref/Cargo.toml +++ b/imports/com_rs-ref/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" description = "com_rs import package" [dependencies] -com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "5338f9959572d57f1014d04aa129804da5b4d339" } +com_rs = { git = "https://github.com/betrusted-io/com_rs.git", rev = "0f0998465d756e14d42d96ee348f99c1ba2bedc3" } #com_rs = { path = "../../../betrusted-ec/sw/com_rs" } diff --git a/services/com/src/api.rs b/services/com/src/api.rs index 1b41995d6..b9a9f6c31 100644 --- a/services/com/src/api.rs +++ b/services/com/src/api.rs @@ -172,6 +172,18 @@ pub(crate) enum Opcode { /// wlan: get wlan radio status (power state? connected? AP info?) WlanStatus, + + /// sets the EC-side com interrupt mask + IntSetMask, + + /// gets the EC-side com interrupt mask + IntGetMask, + + /// acknowledges interrupts with the given mask + IntAck, + + /// gets more details on the latest interrupt + IntFetchVector, } /// These enums indicate what kind of callback type we're sending. @@ -182,3 +194,34 @@ pub(crate) enum Callback { /// Server is quitting, drop connections Drop, } + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum ComIntSources { + WlanRxReady, + WlanIpConfigUpdate, + WlanSsidScanDone, + BatteryCritical, + Invalid, +} +impl From for ComIntSources { + fn from(n: u16) -> ComIntSources { + match n { + com_rs_ref::INT_WLAN_RX_READY => ComIntSources::WlanRxReady, + com_rs_ref::INT_WLAN_IPCONF_UPDATE => ComIntSources::WlanIpConfigUpdate, + com_rs_ref::INT_WLAN_SSID_UPDATE => ComIntSources::WlanSsidScanDone, + com_rs_ref::INT_BATTERY_CRITICAL => ComIntSources::BatteryCritical, + _ => ComIntSources::Invalid, + } + } +} +impl From for u16 { + fn from(cis: ComIntSources) -> u16 { + match cis { + ComIntSources::BatteryCritical => com_rs_ref::INT_BATTERY_CRITICAL, + ComIntSources::WlanIpConfigUpdate => com_rs_ref::INT_WLAN_IPCONF_UPDATE, + ComIntSources::WlanSsidScanDone => com_rs_ref::INT_WLAN_SSID_UPDATE, + ComIntSources::WlanRxReady => com_rs_ref::INT_WLAN_RX_READY, + ComIntSources::Invalid => 0, + } + } +} diff --git a/services/com/src/lib.rs b/services/com/src/lib.rs index 4a22f7d83..ee118e050 100644 --- a/services/com/src/lib.rs +++ b/services/com/src/lib.rs @@ -5,7 +5,7 @@ pub mod api; pub use api::BattStats; -use api::{Callback, Opcode}; +use api::{Callback, ComIntSources, Opcode}; use xous::{send_message, Error, CID, Message, msg_scalar_unpack}; use xous_ipc::{String, Buffer}; use num_traits::{ToPrimitive, FromPrimitive}; @@ -429,6 +429,68 @@ impl Com { Ok(response) } + pub fn ints_enable(&self, int_list: &[ComIntSources]) { + let mut mask_val: u16 = 0; + for &item in int_list.iter() { + let item_as_u16: u16 = item.into(); + mask_val |= item_as_u16; + } + let _ = send_message( + self.conn, + Message::new_blocking_scalar(Opcode::IntSetMask.to_usize().unwrap(), mask_val as usize, 0, 0, 0) + ).expect("couldn't send IntSetMask message"); + } + pub fn ints_get_enabled(&self, int_list: &mut Vec::) { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::IntGetMask.to_usize().unwrap(), 0, 0, 0, 0)) + .expect("Couldn't get IntGetMask"); + if let xous::Result::Scalar1(raw_mask) = response { + let mut mask_bit: u16 = 1; + for _ in 0..16 { + let int_src = ComIntSources::from(mask_bit & raw_mask as u16); + if int_src != ComIntSources::Invalid { + int_list.push(int_src); + } + mask_bit <<= 1; + } + } else { + panic!("failed to send IntGetmask message"); + } + } + pub fn ints_ack(&self, int_list: &[ComIntSources]) { + let mut ack_val: u16 = 0; + for &item in int_list.iter() { + let item_as_u16: u16 = item.into(); + ack_val |= item_as_u16; + } + let _ = send_message( + self.conn, + Message::new_blocking_scalar(Opcode::IntAck.to_usize().unwrap(), ack_val as usize, 0, 0, 0) + ).expect("couldn't send IntSetMask message"); + } + pub fn ints_get_active(&self, int_list: &mut Vec::) -> Option { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::IntFetchVector.to_usize().unwrap(), 0, 0, 0, 0)) + .expect("couldn't get IntFetchVector"); + let mut rxlen: Option = None; + if let xous::Result::Scalar2(ints, maybe_rxlen) = response { + let mut mask_bit: u16 = 1; + for _ in 0..16 { + let int_src = ComIntSources::from(mask_bit & ints as u16); + if int_src != ComIntSources::Invalid { + int_list.push(int_src); + if int_src == ComIntSources::WlanRxReady { + rxlen = Some(maybe_rxlen as u16) + } + } + mask_bit <<= 1; + } + } else { + panic!("failed to send IntGetmask message"); + } + rxlen + } + } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/com/src/main.rs b/services/com/src/main.rs index 4c1f1299e..916684d97 100644 --- a/services/com/src/main.rs +++ b/services/com/src/main.rs @@ -723,6 +723,31 @@ fn xmain() -> ! { _ => info!("status decode failed"), }; } + Some(Opcode::IntSetMask) => msg_blocking_scalar_unpack!(msg, mask_val, _, _, _, { + com.txrx(ComState::LINK_SET_INTMASK.verb); + com.txrx(mask_val as u16); + xous::return_scalar(msg.sender, 1) + .expect("couldn't ack IntSetMask"); + }), + Some(Opcode::IntAck) => msg_blocking_scalar_unpack!(msg, ack_val, _, _, _, { + com.txrx(ComState::LINK_ACK_INTERRUPT.verb); + com.txrx(ack_val as u16); + xous::return_scalar(msg.sender, 1) + .expect("couldn't ack IntAck"); + }), + Some(Opcode::IntGetMask) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + com.txrx(ComState::LINK_GET_INTMASK.verb); + let mask = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + xous::return_scalar(msg.sender, mask as usize) + .expect("couldn't return mask value"); + }), + Some(Opcode::IntFetchVector) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + com.txrx(ComState::LINK_GET_INTERRUPT.verb); + let vector = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + let rxlen = com.wait_txrx(ComState::LINK_READ.verb, Some(STD_TIMEOUT)); + xous::return_scalar2(msg.sender, vector as _, rxlen as _) + .expect("couldn't return IntFetchVector"); + }), None => {error!("unknown opcode"); break}, } diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 4381afd50..a0b0d8ca2 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -696,7 +696,8 @@ fn xmain() -> ! { // - spinor (for turning off wfi during writes) // - rootkeys (for reboots) // - oqc-test (for testing the vibe motor) - let num_conns = 9; + // - net (for COM interrupt dispatch) + let num_conns = 10; let llio_sid = xns.register_name(api::SERVER_NAME_LLIO, Some(num_conns)).expect("can't register server"); log::trace!("registered with NS -- {:?}", llio_sid); diff --git a/services/net/Cargo.toml b/services/net/Cargo.toml new file mode 100644 index 000000000..1f8ad6650 --- /dev/null +++ b/services/net/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "net" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Network middleware" + +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +susres = {path = "../susres"} +rkyv = "0.7.18" +llio = {path = "../llio"} +com = {path = "../com"} + +[dependencies.smoltcp] +version = "0.7.5" +#features = ["proto-ipv4"] + + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] diff --git a/services/net/src/api.rs b/services/net/src/api.rs new file mode 100644 index 000000000..cbef775c0 --- /dev/null +++ b/services/net/src/api.rs @@ -0,0 +1,11 @@ +pub(crate) const SERVER_NAME_NET: &str = "_Middleware Network Server_"; + +#[allow(dead_code)] +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + /// com llio interrupt callback + ComInterrupt, + + /// Suspend/resume callback + SuspendResume, +} diff --git a/services/net/src/lib.rs b/services/net/src/lib.rs new file mode 100644 index 000000000..a3fdb9e4e --- /dev/null +++ b/services/net/src/lib.rs @@ -0,0 +1,33 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +use xous::{CID, send_message}; +use num_traits::ToPrimitive; + +pub struct Net { + conn: CID, +} +impl Net { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + let conn = xns.request_connection_blocking(api::SERVER_NAME_NET).expect("Can't connect to Net server"); + Ok(Net { + conn + }) + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Net { + fn drop(&mut self) { + // the connection to the server side must be reference counted, so that multiple instances of this object within + // a single process do not end up de-allocating the CID on other threads before they go out of scope. + // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". + if REFCOUNT.load(Ordering::Relaxed) == 0 { + unsafe{xous::disconnect(self.conn).unwrap();} + } + // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), + // de-allocate those items here. They don't need a reference count because they are object-specific + } +} \ No newline at end of file diff --git a/services/net/src/main.rs b/services/net/src/main.rs new file mode 100644 index 000000000..3ddf5260d --- /dev/null +++ b/services/net/src/main.rs @@ -0,0 +1,74 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; +use api::*; +use com::api::ComIntSources; +use num_traits::*; + +/* +use smoltcp::iface::{InterfaceBuilder, NeighborCache}; +use smoltcp::phy::{Loopback, Medium}; +use smoltcp::socket::{SocketSet, TcpSocket, TcpSocketBuffer}; +use smoltcp::time::{Duration, Instant}; +use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr}; +*/ + +#[xous::xous_main] +fn xmain() -> ! { + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + log::info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + let net_sid = xns.register_name(api::SERVER_NAME_NET, None).expect("can't register server"); + log::trace!("registered with NS -- {:?}", net_sid); + + // hook the COM interrupt listener + let llio = llio::Llio::new(&xns).unwrap(); + let net_cid = xous::connect(net_sid).unwrap(); + llio.hook_com_event_callback(Opcode::ComInterrupt.to_u32().unwrap(), net_cid).unwrap(); + // setup the interrupt masks + let com = com::Com::new(&xns).unwrap(); + let mut com_int_list: Vec:: = vec![]; + com.ints_get_active(&mut com_int_list); + log::info!("COM initial interrupts: {:?}", com_int_list); + com_int_list.clear(); + com_int_list.push(ComIntSources::WlanIpConfigUpdate); + com_int_list.push(ComIntSources::WlanRxReady); + com_int_list.push(ComIntSources::BatteryCritical); + com.ints_enable(&com_int_list); + com.ints_get_active(&mut com_int_list); + log::info!("COM interrupts after enabling: {:?}", com_int_list); + + log::trace!("ready to accept requests"); + // register a suspend/resume listener + let sr_cid = xous::connect(net_sid).expect("couldn't create suspend callback connection"); + let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + + loop { + let msg = xous::receive_message(net_sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(Opcode::ComInterrupt) => { + com_int_list.clear(); + let maybe_rxlen = com.ints_get_active(&mut com_int_list); + log::info!("COM got interrupts: {:?}", com_int_list); + com.ints_ack(&com_int_list); + } + Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { + // handle an suspend/resume state stuff here. right now, it's a NOP + susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); + }), + None => { + log::error!("couldn't convert opcode"); + break + } + } + } + // clean up our program + log::trace!("main loop exit, destroying servers"); + xns.unregister_server(net_sid).unwrap(); + xous::destroy_server(net_sid).unwrap(); + log::trace!("quitting"); + xous::terminate_process(0) +} diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index c98cb943b..5a2f1d2dc 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -7,3 +7,72 @@ pub(crate) enum Opcode { /// Suspend/resume callback SuspendResume, } + +// this is an intenal structure for managing the overall PDDB +pub(crate) struct PddbManager { + +} +impl PddbManager { + // return a list of open bases + fn list_basis(); +} + +// this is an internal struct for managing a basis +pub(crate) struct PddbBasis { + +} +impl PddbBasis { + // opening and closing basis will side-effect PddbDicts and PddbKeys + fn open(); // will result in a password box being triggered to open a basis + fn close(); +} + +// this structure can be shared on the user side? +pub struct PddbDict { + contents: Hashmap, +} +impl PddbDict { + // opens a dictionary only if it exists + pub fn open(dict_name: &str) -> Option; + // creates a dictionary only if it does not already exist + pub fn create(dict_name: &str) -> Option; + + // returns a key only if it exists + pub fn get(&mut self, key_name: &str, key_changed_cb: CB) -> Result; + // updates an existing key's value. mainly used by write(). + pub fn update(&mut self, key: PddbKey) -> Result>; + // creates a key or overwrites it + pub fn insert(&mut self, key: PddbKey) -> Option; // may return the displaced key + // deletes a key within the dictionary + pub fn remove(&mut self, key: PddbKey) -> Result<()>; + // deletes the entire dictionary + pub fn delete(&mut self); +} + +/// PddbKey is somewhat isomorphic to a File in Rust, in that it provides slices of [u8] that +/// can be `read()`, `write()` and `seek()`. +/// this is definitely a user-facing structure +pub struct PddbKey +where CB: FnMut(), { + // dictionary to search for the key within + dict: PddbDict, + // a copy of my name + name: String, + // called when the key changes (basis or is modified otherwise) + key_changed_cb: CB, + // mapped memory for the plaintext contexts, typically not all resident + mem: MemoryRange, +} + +impl PddbKey<'a, CB> { + // reads are transparent and "just happen" + pub fn read(&mut self, buf: &mut [u8]) -> Result; + // writes will call update() on the dictionary + pub fn write(&mut self, buf: &[u8]) -> Result; + // provided for compatibility with Rust API + pub fn seek(&mut self, pos: SeekFrom) -> Result; +} + +pub struct PddbBasis { + +} \ No newline at end of file diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 5cfd9c66a..befcdf6ff 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -15,6 +15,8 @@ impl Pddb { conn }) } + + } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index f9a7cead9..1c6ce4979 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -5,85 +5,16 @@ mod api; use num_traits::*; -#[cfg(any(target_os = "none", target_os = "xous"))] -mod implementation { - use utralib::generated::*; - // use crate::api::*; - use log::info; - use susres::{RegManager, RegOrField, SuspendResume}; - - pub struct Pddb { - csr: utralib::CSR, - fifo: xous::MemoryRange, - susres_manager: RegManager::<{utra::audio::AUDIO_NUMREGS}>, - } - - impl Pddb { - pub fn new() -> Pddb { - let csr = xous::syscall::map_memory( - xous::MemoryAddress::new(utra::audio::HW_AUDIO_BASE), - None, - 4096, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map Audio CSR range"); - let fifo = xous::syscall::map_memory( - xous::MemoryAddress::new(utralib::HW_AUDIO_MEM), - None, - utralib::HW_AUDIO_MEM_LEN, - xous::MemoryFlags::R | xous::MemoryFlags::W, - ) - .expect("couldn't map Audio CSR range"); - - let mut pddb = Pddb { - csr: CSR::new(csr.as_mut_ptr() as *mut u32), - susres_manager: RegManager::new(csr.as_mut_ptr() as *mut u32), - fifo, - }; - - pddb - } - - pub fn suspend(&mut self) { - self.susres_manager.suspend(); - } - pub fn resume(&mut self) { - self.susres_manager.resume(); - } - } -} - -// a stub to try to avoid breaking hosted mode for as long as possible. -#[cfg(not(any(target_os = "none", target_os = "xous")))] -mod implementation { - use log::info; - - pub struct Pddb { - } - - impl Pddb { - pub fn new() -> Pddb { - Pddb { - } - } - pub fn suspend(&self) { - } - pub fn resume(&self) { - } - } -} - - #[xous::xous_main] fn xmain() -> ! { use crate::implementation::Pddb; log_server::init_wait().unwrap(); log::set_max_level(log::LevelFilter::Info); - info!("my PID is {}", xous::process::id()); + log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); - let pddb_sid = xns.register_name(api::SERVER_NAME_PDDB).expect("can't register server"); + let pddb_sid = xns.register_name(api::SERVER_NAME_PDDB, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", pddb_sid); let mut pddb = Pddb::new(); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 062243c55..a2d712a0f 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -56,6 +56,7 @@ fn main() -> Result<(), Box> { "root-keys", "jtag", "oqc-test", + "net", ]; let benchmark_pkgs = [ "benchmark",