add some skeleton for a net crate; testing COM interrupts

This commit is contained in:
bunnie 2021-10-08 20:01:13 +08:00
parent 73c131cbcc
commit b43eb56346
15 changed files with 397 additions and 75 deletions

40
Cargo.lock generated
View file

@ -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"

View file

@ -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"

View file

@ -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" }

View file

@ -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<u16> 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<ComIntSources> 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,
}
}
}

View file

@ -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::<ComIntSources>) {
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::<ComIntSources>) -> Option<u16> {
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<u16> = 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};

View file

@ -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},
}

View file

@ -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);

30
services/net/Cargo.toml Normal file
View file

@ -0,0 +1,30 @@
[package]
name = "net"
version = "0.1.0"
authors = ["bunnie <bunnie@kosagi.com>"]
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 = []

11
services/net/src/api.rs Normal file
View file

@ -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,
}

33
services/net/src/lib.rs Normal file
View file

@ -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<Self, xous::Error> {
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
}
}

74
services/net/src/main.rs Normal file
View file

@ -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::<ComIntSources> = 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)
}

View file

@ -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<PddbDict>;
// creates a dictionary only if it does not already exist
pub fn create(dict_name: &str) -> Option<PddbDict>;
// returns a key only if it exists
pub fn get(&mut self, key_name: &str, key_changed_cb: CB) -> Result<PddbKey>;
// updates an existing key's value. mainly used by write().
pub fn update(&mut self, key: PddbKey) -> Result<Option<PddbKey>>;
// creates a key or overwrites it
pub fn insert(&mut self, key: PddbKey) -> Option<PddbKey>; // 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<CB>
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<usize>;
// writes will call update() on the dictionary
pub fn write(&mut self, buf: &[u8]) -> Result<usize>;
// provided for compatibility with Rust API
pub fn seek(&mut self, pos: SeekFrom) -> Result<u64>;
}
pub struct PddbBasis {
}

View file

@ -15,6 +15,8 @@ impl Pddb {
conn
})
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -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<u32>,
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();

View file

@ -56,6 +56,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
"root-keys",
"jtag",
"oqc-test",
"net",
];
let benchmark_pkgs = [
"benchmark",