attempt to refactor xous_names

This commit is contained in:
bunnie 2021-03-29 04:35:11 +08:00
parent 88d66f4fd2
commit f35d478cf0
14 changed files with 196 additions and 229 deletions

View file

@ -57,30 +57,27 @@ fn stopwatch_thread(_arg: xous::SID) {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
let shell_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_SHELL).expect("BENCHMARK|stopwatch: can't connect to main program"); let shell_conn = xous_names::request_connection_blocking(xous::names::SERVER_NAME_SHELL).expect("BENCHMARK|stopwatch: can't connect to main program");
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
let mut start_sent = false; let mut start_sent = false;
loop { loop {
if let Ok(elapsed_time) = ticktimer.elapsed_ms() { elapsed_time = ticktimer.elapsed_ms();
if elapsed_time - last_time > 500 && !start_sent { if elapsed_time - last_time > 500 && !start_sent {
last_time = elapsed_time; last_time = elapsed_time;
xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message"); xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message");
start_sent = true; start_sent = true;
} else if elapsed_time - last_time > 10_000 && start_sent { } else if elapsed_time - last_time > 10_000 && start_sent {
last_time = elapsed_time; last_time = elapsed_time;
start_sent = false; start_sent = false;
xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message"); xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message");
}
} else {
error!("error requesting ticktimer!")
} }
if false { if false {
// send a start loop message // send a start loop message
xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message"); xous::send_message(shell_conn, Opcode::Start.into()).expect("BENCHMARK|stopwatch: couldn't send Start message");
ticktimer.sleep_ms(ticktimer_conn, 10_000).expect("couldn't sleep"); ticktimer.sleep_ms(10_000).expect("couldn't sleep");
// send a stop loop message // send a stop loop message
xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message"); xous::send_message(shell_conn, Opcode::Stop.into()).expect("BENCHMARK|stopwatch: couldn't send Stop message");
// give a moment for the result to update // give a moment for the result to update
ticktimer.sleep_ms(ticktimer_conn, 500).expect("couldn't sleep"); ticktimer.sleep_ms(500).expect("couldn't sleep");
} }
xous::yield_slice(); xous::yield_slice();
} }
@ -135,10 +132,10 @@ fn shell_main() -> ! {
if let Ok(opcode) = Opcode::try_from(&envelope.body) { if let Ok(opcode) = Opcode::try_from(&envelope.body) {
match opcode { match opcode {
Opcode::Start => { Opcode::Start => {
start_time = ticktimer.elapsed_ms().unwrap(); start_time = ticktimer.elapsed_ms();
}, },
Opcode::Stop => { Opcode::Stop => {
stop_time = ticktimer.elapsed_ms().unwrap(); stop_time = ticktimer.elapsed_ms();
update_result = true; update_result = true;
}, },
} }

View file

@ -107,15 +107,11 @@ mod implementation {
pub fn wait_txrx(&mut self, tx: u16, timeout: Option<u32>) -> u16 { pub fn wait_txrx(&mut self, tx: u16, timeout: Option<u32>) -> u16 {
if timeout.is_some() { if timeout.is_some() {
let curtime = self.ticktimer.elapsed_ms() let curtime = self.ticktimer.elapsed_ms();
.expect("couldn't connect to ticktimer");
let mut timed_out = false; let mut timed_out = false;
let to = timeout.unwrap() as u64; let to = timeout.unwrap() as u64;
while self.csr.rf(utra::com::STATUS_HOLD) == 1 && !timed_out { while self.csr.rf(utra::com::STATUS_HOLD) == 1 && !timed_out {
if (self.ticktimer.elapsed_ms() if (self.ticktimer.elapsed_ms() - curtime) > to
.expect("couldn't connect to ticktimer")
- curtime)
> to
{ {
timed_out = true; timed_out = true;
} }

View file

@ -378,7 +378,7 @@ fn do_agent(cmd: &mut String<U2048>, com_cid: xous::CID, pds_list: &mut Vec<Stri
} else if tokens[1].trim() == "commit_pds" { } else if tokens[1].trim() == "commit_pds" {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer"); let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
for pds in pds_list.iter() { for pds in pds_list.iter() {
let mut sendable_string = xous::String::<512>::new(); let mut sendable_string = xous::String::<512>::new();
write!(&mut sendable_string, "{}", pds); write!(&mut sendable_string, "{}", pds);
@ -499,7 +499,7 @@ fn xmain() -> ! {
uart.enable_rx(); uart.enable_rx();
print!("\n\r\n\r*** FCC agent ***\n\r\n\r"); print!("\n\r\n\r*** FCC agent ***\n\r\n\r");
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
let mut pds_list: Vec<String<U512>, U16> = Vec::new(); let mut pds_list: Vec<String<U512>, U16> = Vec::new();
let mut repeat = false; let mut repeat = false;
let mut phase = 0; let mut phase = 0;

View file

@ -227,7 +227,7 @@ fn xmain() -> ! {
xous::create_thread_4(status_thread, gid[0] as _, gid[1] as _, gid[2] as _, gid[3] as _).expect("GAM: couldn't create status thread"); xous::create_thread_4(status_thread, gid[0] as _, gid[1] as _, gid[2] as _, gid[3] as _).expect("GAM: couldn't create status thread");
let mut powerdown_requested = false; let mut powerdown_requested = false;
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
info!("GAM: entering main loop"); info!("GAM: entering main loop");
loop { loop {
let envelope = xous::receive_message(gam_sid).unwrap(); let envelope = xous::receive_message(gam_sid).unwrap();

View file

@ -46,7 +46,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
battstats_tv.margin = Point::new(0, 0); battstats_tv.margin = Point::new(0, 0);
let mut stats: BattStats; let mut stats: BattStats;
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
let mut stats_phase: usize = 0; let mut stats_phase: usize = 0;
let mut last_seconds: usize = ((last_time / 1000) % 60) as usize; let mut last_seconds: usize = ((last_time / 1000) % 60) as usize;

View file

@ -24,9 +24,9 @@ fn sleep_loop_4(main_conn: usize, sleep_ms: usize, ticktimer_conn: usize, pid: u
// sleep_ms, // sleep_ms,
// loop_count // loop_count
// ); // );
let start_time = ticktimer.elapsed_ms().unwrap(); let start_time = ticktimer.elapsed_ms();
ticktimer.sleep_ms(ticktimer_conn, sleep_ms).unwrap(); ticktimer.sleep_ms(ticktimer_conn, sleep_ms).unwrap();
let end_time = ticktimer.elapsed_ms().unwrap(); let end_time = ticktimer.elapsed_ms();
log::info!( log::info!(
"TEST THREAD {}:{}: target {}ms, {} loops: Sleep finished (uptime: {}, took {} ms)", "TEST THREAD {}:{}: target {}ms, {} loops: Sleep finished (uptime: {}, took {} ms)",
pid, pid,

View file

@ -229,7 +229,7 @@ mod implementation {
let mut ticktimer = XousTickTimer::new(ticktimer_client).expect("KBD: couldn't connect to ticktimer"); let mut ticktimer = XousTickTimer::new(ticktimer_client).expect("KBD: couldn't connect to ticktimer");
let timestamp = ticktimer.elapsed_ms().unwrap(); let timestamp = ticktimer.elapsed_ms();
let kbd = Keyboard { let kbd = Keyboard {
csr: CSR::new(csr.as_mut_ptr() as *mut u32), csr: CSR::new(csr.as_mut_ptr() as *mut u32),
debounce: [[0; KBD_COLS]; KBD_ROWS], debounce: [[0; KBD_COLS]; KBD_ROWS],
@ -341,7 +341,7 @@ mod implementation {
// clear the pending bit // clear the pending bit
self.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1); self.csr.wfo(utra::keyboard::EV_PENDING_KEYPRESSED, 1);
let elapsed = self.ticktimer.elapsed_ms().unwrap() - self.timestamp; let elapsed = self.ticktimer.elapsed_ms() - self.timestamp;
if elapsed <= 1 { if elapsed <= 1 {
// skip debounce processing if time elapsed is too short // skip debounce processing if time elapsed is too short
(None, None) (None, None)
@ -435,7 +435,7 @@ mod implementation {
let mut keystates: Vec<char, U4> = Vec::new(); let mut keystates: Vec<char, U4> = Vec::new();
if self.chord_active || keydowns.is_some() { if self.chord_active || keydowns.is_some() {
let now = self.ticktimer.elapsed_ms().unwrap(); let now = self.ticktimer.elapsed_ms();
if !self.chord_active && keydowns.is_some() { if !self.chord_active && keydowns.is_some() {
self.chord_active = true; self.chord_active = true;
@ -622,7 +622,7 @@ mod implementation {
// interpret keys in the context of the shift/alt modifiers // interpret keys in the context of the shift/alt modifiers
if let Some(kds) = &keydowns { if let Some(kds) = &keydowns {
self.chord_timestamp = self.ticktimer.elapsed_ms().unwrap(); self.chord_timestamp = self.ticktimer.elapsed_ms();
// if more than one is held, the key that gets picked for the repeat function is arbitrary! // if more than one is held, the key that gets picked for the repeat function is arbitrary!
for &rc in kds.iter() { for &rc in kds.iter() {
let code = match self.map { let code = match self.map {
@ -637,7 +637,7 @@ mod implementation {
} }
} }
} }
let now = self.ticktimer.elapsed_ms().unwrap(); let now = self.ticktimer.elapsed_ms();
let hold: bool; let hold: bool;
if (now - self.chord_timestamp) >= self.delay as u64 { if (now - self.chord_timestamp) >= self.delay as u64 {
if self.rate_timestamp <= self.chord_timestamp { if self.rate_timestamp <= self.chord_timestamp {

View file

@ -47,7 +47,7 @@ impl I2cStateMachine {
I2cStateMachine { I2cStateMachine {
transaction: I2cTransaction::new(), transaction: I2cTransaction::new(),
state: I2cState::Idle, state: I2cState::Idle,
timestamp: ticktimer.elapsed_ms().unwrap(), timestamp: ticktimer.elapsed_ms(),
ticktimer, ticktimer,
i2c_csr: CSR::new(i2c_base), i2c_csr: CSR::new(i2c_base),
index: 0, index: 0,
@ -60,7 +60,7 @@ impl I2cStateMachine {
return I2cStatus::ResponseFormatError return I2cStatus::ResponseFormatError
} }
let now = self.ticktimer.elapsed_ms().unwrap(); let now = self.ticktimer.elapsed_ms();
if self.state != I2cState::Idle && ((now - self.timestamp) < self.transaction.timeout_ms as u64) { 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 // we're in a transaction that hadn't timed out, can't accept a new one
I2cStatus::ResponseBusy I2cStatus::ResponseBusy
@ -145,7 +145,7 @@ impl I2cStateMachine {
} }
pub fn handler(&mut self) { pub fn handler(&mut self) {
// check if the transaction had actually timed out // check if the transaction had actually timed out
let now = self.ticktimer.elapsed_ms().unwrap(); let now = self.ticktimer.elapsed_ms();
if now - self.timestamp > self.transaction.timeout_ms as u64 { if now - self.timestamp > self.transaction.timeout_ms as u64 {
// previous transaction had timed out... // previous transaction had timed out...
self.report_timeout(); self.report_timeout();

View file

@ -15,7 +15,8 @@ static SERVER_CID: AtomicU32 = AtomicU32::new(0);
fn ensure_connection() -> xous::CID { fn ensure_connection() -> xous::CID {
let mut cid = SERVER_CID.load(Ordering::Relaxed); let mut cid = SERVER_CID.load(Ordering::Relaxed);
if cid == 0 { if cid == 0 {
cid = xous_names::request_connection_blocking(api::SERVER_NAME).unwrap(); let ns = xous_names::XousNames::new().unwrap();
cid = ns.request_connection_blocking(api::SERVER_NAME).unwrap();
SERVER_CID.store(cid, Ordering::Relaxed); SERVER_CID.store(cid, Ordering::Relaxed);
} }
cid cid

View file

@ -174,8 +174,8 @@ fn shell_main() -> ! {
// make a thread to catch responses from the COM // make a thread to catch responses from the COM
xous::create_thread_simple(event_thread, 0).unwrap(); xous::create_thread_simple(event_thread, 0).unwrap();
info!("SHELL: COM responder thread started"); info!("SHELL: COM responder thread started");
let start_time: u64 = ticktimer.elapsed_ms().unwrap(); let start_time: u64 = ticktimer.elapsed_ms();
while ticktimer.elapsed_ms().unwrap() - start_time < 1000 { while ticktimer.elapsed_ms() - start_time < 1000 {
xous::yield_slice(); xous::yield_slice();
} }
@ -217,7 +217,7 @@ fn shell_main() -> ! {
graphics_server::draw_rectangle(graphics_conn, work_clipregion) graphics_server::draw_rectangle(graphics_conn, work_clipregion)
.expect("unable to clear region"); .expect("unable to clear region");
let mut last_time: u64 = ticktimer.elapsed_ms().unwrap(); let mut last_time: u64 = ticktimer.elapsed_ms();
let mut first_time = true; let mut first_time = true;
loop { loop {
//////////////// status bar //////////////// status bar

View file

@ -16,17 +16,18 @@ impl Ticktimer {
}) })
} }
pub fn elapsed_ms(&self) -> Result<u64, Error> { /// note special case for elapsed_ms() is "infalliable". it really should never fail so get rid of the Error
pub fn elapsed_ms(&self) -> u64 {
let response = send_message(self.conn, let response = send_message(self.conn,
xous::Message::BlockingScalar(xous::ScalarMessage { xous::Message::BlockingScalar(xous::ScalarMessage {
id: api::Opcode::ElapsedMs.to_usize().unwrap(), id: api::Opcode::ElapsedMs.to_usize().unwrap(),
arg1: 0, arg2: 0, arg3: 0, arg4: 0 arg1: 0, arg2: 0, arg3: 0, arg4: 0
}) })
)?; ).expect("Ticktimer: failure to send message to Ticktimer");
if let xous::Result::Scalar2(upper, lower) = response { if let xous::Result::Scalar2(upper, lower) = response {
Ok(upper as u64 | ((lower as u64) << 32)) upper as u64 | ((lower as u64) << 32)
} else { } else {
panic!("unexpected return value: {:#?}", response); panic!("Ticktimer elapsed_ms(): unexpected return value: {:#?}", response);
} }
} }

View file

@ -3,68 +3,39 @@ use hash32::{Hash, Hasher};
pub const AUTHENTICATE_TIMEOUT: u32 = 10_000; // time in ms that a process has to respond to an authentication request pub const AUTHENTICATE_TIMEOUT: u32 = 10_000; // time in ms that a process has to respond to an authentication request
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)] #[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Request { pub(crate) enum Opcode {
/// Create a new server with the given name and return its SID. /// Create a new server with the given name and return its SID.
Register, Register,
/// Create a connection to the target server. /// Create a connection to the target server.
Lookup, Lookup,
/// Create an authenticated connection to the target server. /// Create an authenticated connection to the target server.
AuthenticatedLookup, AuthenticatedLookup,
// Return values
/// The caller must perform an AuthenticatedLookup using this challenge
AuthenticateRequest,
/// The connection failed for some reason
Failure,
/// A server was successfully created with the given SID
SID,
/// A connection was successfully made with the given CID
CID,
} }
/*
pub(crate) enum Request {
/// Create a new server with the given name and return its SID.
Register(xous_ipc::String::<64>),
/// Create a connection to the target server.
Lookup(xous_ipc::String::<64>),
/// Create an authenticated connection to the target server.
AuthenticatedLookup(AuthenticatedLookup),
// Return values
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Return {
/// The caller must perform an AuthenticatedLookup using this challenge /// The caller must perform an AuthenticatedLookup using this challenge
AuthenticateRequest(AuthenticatedRequest), AuthenticateRequest(AuthenticateRequest),
/// The connection failed for some reason /// The connection failed for some reason
Failure, Failure,
/// A server was successfully created with the given SID /// A server was successfully created with the given SID
SID([u32; 4]), SID([u32; 4]),
/// A connection was successfully made with the given CID /// A connection was successfully made with the given CID
CID(CID), CID(xous::CID),
}*/ }
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct AuthenticatedLookup { pub(crate) struct AuthenticatedLookup {
pub name: xous_ipc::String::<64>, pub name: xous_ipc::String::<64>,
pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian) pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
pub challenge: [u32; 8], pub response: [u32; 8],
} }
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) struct AuthenticatedRequest { pub(crate) struct AuthenticateRequest {
pub request: AuthenicatedLookup, // a copy of the original request. We don't trust it, but it's helpful to have for reference pub name: xous_ipc::String::<64>, // a copy of the originally requested lookup
pub nonce: [u32; 4], pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian)
pub response: [u32; 8], pub challenge: [u32; 4],
} }

View file

@ -3,90 +3,75 @@
pub mod api; pub mod api;
use core::fmt::Write; use core::fmt::Write;
use xous_ipc::{String, Buffer};
use num_traits::{FromPrimitive, ToPrimitive};
pub struct XousNames { pub struct XousNames {
conn: xous::CID, conn: xous::CID,
} }
impl XousNames { impl XousNames {
pub fn new() -> Result<Self, Error> { pub fn new() -> Result<Self, xous::Error> {
let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()).expect("Couldn't connect to XousNames"); let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()).expect("Couldn't connect to XousNames");
Ok(XousNames { Ok(XousNames {
conn, conn,
}) })
} }
pub fn register_name(&self, name: &str) -> Result<xous::SID, xous::Error> { pub fn register_name(&self, name: &str) -> Result<xous::SID, xous::Error> {
let mut registration_name = String::<64>::new();
// could also do String::from_str() but in this case we want things to fail if the string is too long.
write!(registration_name, "{}", name).expect("NS: name probably too long");
} let mut buf = Buffer::try_from(registration_name).or(Err(xous::Error::InternalError))?;
}
pub fn register_name(name: &str) -> Result<xous::SID, xous::Error> { buf.lend_mut(
// Ensure we have a connection to the nameserver. If one exists, this is a no-op. self.conn,
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap(); api::Opcode::Register.to_u32().unwrap()
let ns_conn = xous::connect(ns_id).unwrap(); )
.or(Err(xous::Error::InternalError))?;
let mut registration_name = xous_ipc::String::<64>::new(); match buf.deserialize().unwrap() {
write!(registration_name, "{}", name).expect("namserver: name probably too long"); api::Return::SID(sid_raw) => {
let request = api::Request::Register(registration_name); let sid = sid_raw.into();
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); xous::create_server_with_sid(sid).expect("NS: can't auto-register server");
let pos = { Ok(sid)
use rkyv::ser::Serializer; }
writer.serialize_value(&request).expect("nameserver: couldn't archive name") api::Return::Failure => {
}; Err(xous::Error::InternalError)
let mut xous_buffer = writer.into_inner(); }
_ => unimplemented!("NS: unimplemented return codes")
xous_buffer }
.lend_mut(ns_conn, pos as u32) }
.expect("nameserver registration failure");
/// note: if this throws an AccessDenied error, you can retry with a request_authenticate_connection() call (to be written)
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) }; pub fn request_connection(&self, name: &str) -> Result<xous::CID, xous::Error> {
let mut lookup_name = xous_ipc::String::<64>::new();
if let rkyv::Archived::<api::Request>::SID(sid) = archived { write!(lookup_name, "{}", name).expect("NS: name problably too long");
let sid = sid.into();
xous::create_server_with_sid(sid).expect("can't auto-register server"); let mut buf = Buffer::try_from(lookup_name).or(Err(xous::Error::InternalError))?;
Ok(sid)
} else if let rkyv::Archived::<api::Request>::Failure = archived { buf.lend_mut(
return Err(xous::Error::InternalError); self.conn,
} else { api::Opcode::Lookup.to_u32().unwrap()
panic!("Invalid response from the server -- corruption occurred"); )
} .or(Err(xous::Error::InternalError))?;
}
match buf.deserialize().unwrap() {
/// note: if this throws an AccessDenied error, you can retry with a request_authenticat_connection() call (to be written) api::Return::CID(cid) => Ok(cid),
pub fn request_connection(name: &str) -> Result<xous::CID, xous::Error> { api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
let ns_id = xous::SID::from_bytes(b"xous-name-server").unwrap(); _ => Err(xous::Error::ServerNotFound),
let ns_conn = xous::connect(ns_id).unwrap(); }
}
let mut lookup_name = xous_ipc::String::<64>::new();
write!(lookup_name, "{}", name).expect("nameserver: name problably too long"); /// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously
let request = api::Request::Lookup(lookup_name); pub fn request_connection_blocking(&self, name: &str) -> Result<xous::CID, xous::Error> {
loop {
let mut writer = rkyv::ser::serializers::BufferSerializer::new(xous::XousBuffer::new(4096)); match self.request_connection(name) {
let pos = { Ok(val) => return Ok(val),
use rkyv::ser::Serializer; Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied),
writer.serialize_value(&request).expect("nameserver: couldn't archive name") _ => (),
}; }
let mut xous_buffer = writer.into_inner(); xous::yield_slice();
xous_buffer
.lend_mut(ns_conn, pos as u32)
.expect("nameserver lookup failure!");
let archived = unsafe { rkyv::archived_value::<api::Request>(xous_buffer.as_ref(), pos) };
match archived {
rkyv::Archived::<api::Request>::CID(cid) => Ok(*cid),
rkyv::Archived::<api::Request>::AuthenticateRequest(_) => Err(xous::Error::AccessDenied),
_ => Err(xous::Error::ServerNotFound),
}
}
/// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously
pub fn request_connection_blocking(name: &str) -> Result<xous::CID, xous::Error> {
loop {
match request_connection(name) {
Ok(val) => return Ok(val),
Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied),
_ => (),
} }
xous::yield_slice();
} }
} }

View file

@ -5,17 +5,20 @@ extern crate hash32_derive;
mod api; mod api;
use api::*; use api::*;
use xous::buffer;
// use heapless::String; // use heapless::String;
use heapless::consts::*; use heapless::consts::*;
use heapless::FnvIndexMap; use heapless::FnvIndexMap;
use core::convert::TryInto; use core::convert::TryInto;
use num_traits::{FromPrimitive, ToPrimitive};
use xous_ipc::{String, Buffer};
use log::{error, info}; use log::{error, info};
const FAIL_TIMEOUT_MS: u64 = 100; const FAIL_TIMEOUT_MS: u64 = 100;
#[xous::xous_main] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
let debug1 = false; let debug1 = false;
@ -31,87 +34,100 @@ fn xmain() -> ! {
let mut name_table = FnvIndexMap::<_, _, U128>::new(); let mut name_table = FnvIndexMap::<_, _, U128>::new();
info!("NS: started"); info!("NS: started");
use core::pin::Pin;
use rkyv::archived_value_mut;
loop { loop {
let envelope = xous::receive_message(name_server).unwrap(); let mut msg = xous::receive_message(name_server).unwrap();
if debug1{info!("NS: received message");} if debug1{info!("NS: received message");}
if let xous::Message::MutableBorrow(m) = &envelope.body { match FromPrimitive::from_usize(msg.body.id()) {
let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) }; Some(api::Opcode::Register) => {
let value = unsafe { let mut mem = msg.body.memory_message_mut().unwrap();
archived_value_mut::<api::Request>(Pin::new(buf.as_mut()), m.id.try_into().unwrap()) let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
}; let xous_string = buffer.try_into::<xous_ipc::String::<64>, _>().unwrap();
let new_value = match &*value { let name = XousServerName::from_str(xous_string.as_str().unwrap());
rkyv::Archived::<api::Request>::Register(registration_name) => {
let name = XousServerName::from_str(registration_name.as_str()); let mut response: api::Return;
if debug1{info!("NS: registration request for '{}'", name);}
if !name_table.contains_key(&name) { if debug1{info!("NS: registration request for '{}'", name);}
let new_sid = if !name_table.contains_key(&name) {
xous::create_server_id().expect("NS: create server failed, maybe OOM?"); let new_sid =
name_table xous::create_server_id().expect("NS: create server failed, maybe OOM?");
.insert(name, new_sid) name_table
.expect("NS: register name failure, maybe out of HashMap capacity?"); .insert(name, new_sid)
if debug1{info!("NS: request successful, SID is {:?}", new_sid);} .expect("NS: register name failure, maybe out of HashMap capacity?");
rkyv::Archived::<api::Request>::SID(new_sid.into()) if debug1{info!("NS: request successful, SID is {:?}", new_sid);}
} else {
// compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels response = api::Return::SID(new_sid.into());
let target_time: u64 = ((ticktimer.elapsed_ms() } else {
.unwrap() // compute the next interval, rounded to a multiple of FAIL_TIMEOUT_MS to reduce timing side channels
/ FAIL_TIMEOUT_MS) let target_time: u64 = ((ticktimer.elapsed_ms()
+ 1) / FAIL_TIMEOUT_MS)
* FAIL_TIMEOUT_MS; + 1)
info!("NS: request failed, waiting for deterministic timeout"); * FAIL_TIMEOUT_MS;
while ticktimer.elapsed_ms().unwrap() < target_time { info!("NS: request failed, waiting for deterministic timeout");
xous::yield_slice(); while ticktimer.elapsed_ms() < target_time {
} xous::yield_slice();
info!("NS: deterministic timeout done");
rkyv::Archived::<api::Request>::Failure
} }
info!("NS: deterministic timeout done");
response = api::Return::Failure
} }
rkyv::Archived::<api::Request>::Lookup(lookup_name) => { buffer.serialize_from(response).unwrap();
let name = XousServerName::from_str(lookup_name.as_str()); }
if debug1{info!("NS: Lookup request for '{}'", name);} Some(api::Opcode::Lookup) => {
if let Some(server_sid) = name_table.get(&name) { let mut mem = msg.body.memory_message_mut().unwrap();
let sender_pid = envelope let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
.sender let name_string = buffer.try_into::<xous_ipc::String::<64>, _>().unwrap();
.pid() let name = XousServerName::from_str(name_string.as_str().unwrap());
.expect("NS: can't extract sender PID on Lookup"); if debug1{info!("NS: Lookup request for '{}'", name);}
match xous::connect_for_process(sender_pid, *server_sid) let mut response: api::Return;
.expect("NS: can't broker connection") if let Some(server_sid) = name_table.get(&name) {
{ let sender_pid = msg
xous::Result::ConnectionID(connection_id) => { .sender
if debug1{info!("NS: lookup success, returning connection {}", connection_id);} .pid()
rkyv::Archived::<api::Request>::CID(connection_id) .expect("NS: can't extract sender PID on Lookup");
} match xous::connect_for_process(sender_pid, *server_sid)
_ => { .expect("NS: can't broker connection")
info!( {
"NS: Can't find request '{}' in table, dumping table:", xous::Result::ConnectionID(connection_id) => {
name if debug1{info!("NS: lookup success, returning connection {}", connection_id);}
); response = api::Return::CID(connection_id)
for (key, val) in name_table.iter() {
info!("NS: name: '{}', sid: '{:?}'", key, val);
}
rkyv::Archived::<api::Request>::Failure
}
} }
} else { _ => {
info!( info!(
"NS: Can't find request '{}' in table, dumping table:", "NS: Can't find request '{}' in table, dumping table:",
name name
); );
for (key, val) in name_table.iter() { for (key, val) in name_table.iter() {
info!("NS: name: '{}', sid: '{:?}'", key, val); info!("NS: name: '{}', sid: '{:?}'", key, val);
}
response = api::Return::Failure
} }
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
rkyv::Archived::<api::Request>::Failure
} }
} else {
info!(
"NS: Can't find request '{}' in table, dumping table:",
name
);
for (key, val) in name_table.iter() {
info!("NS: name: '{}', sid: '{:?}'", key, val);
}
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually.
let auth_request = AuthenticateRequest {
name: name_string,
pubkey_id: [0; 20], // placeholder
challenge: xous::create_server_id().to_u32().unwrap(),
};
response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path
} }
_ => panic!("Invalid response from the server -- corruption occurred"), buffer.serialize_from(response).unwrap();
}; }
unsafe { *value.get_unchecked_mut() = new_value }; Some(api::Opcode::AuthenticatedLookup) => {
} else { let mut mem = msg.body.memory_message_mut().unwrap();
error!("NS: couldn't convert opcode"); let buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let auth_lookup = buffer.try_into::<api::AuthenticatedLookup>().unwrap();
info!("NS: AuthenticatedLookup request {:?}", auth_lookup);
error!("NS: AuthenticatedLookup not yet implemented");
unimplemented!("NS: AuthenticatedLookup not yet implemented");
}
None => error!("NS: couldn't decode message: {:?}", msg)
} }
} }
} }