format services/xous-names

This commit is contained in:
bunnie 2024-01-14 22:57:09 +08:00
parent 931309590f
commit 9668179753

View file

@ -1,16 +1,14 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)] #![cfg_attr(target_os = "none", no_main)]
use xous_api_names::*; use std::collections::HashMap;
use xous_api_names::api::*;
use num_traits::FromPrimitive;
use xous::{msg_blocking_scalar_unpack, MessageEnvelope};
use xous_ipc::{Buffer, String};
use log::{error, info}; use log::{error, info};
use num_traits::FromPrimitive;
use std::collections::HashMap; use xous::{msg_blocking_scalar_unpack, MessageEnvelope};
use xous_api_names::api::*;
use xous_api_names::*;
use xous_ipc::{Buffer, String};
#[derive(PartialEq)] #[derive(PartialEq)]
#[repr(C)] #[repr(C)]
@ -35,10 +33,7 @@ enum ConnectError {
#[repr(C)] #[repr(C)]
enum ConnectSuccess { enum ConnectSuccess {
/// The server connection was successfully made /// The server connection was successfully made
Connected( Connected(xous::CID /* Connection ID */, Option<[u32; 4]> /* Disconnection token */),
xous::CID, /* Connection ID */
Option<[u32; 4]>, /* Disconnection token */
),
/// There is no server with that name -- block this message /// There is no server with that name -- block this message
Wait, Wait,
@ -46,7 +41,7 @@ enum ConnectSuccess {
// AuthenticationRequest // AuthenticationRequest
} }
#[cfg(any(feature="precursor", feature="renode", feature="cramium-fpga", feature="cramium-soc"))] #[cfg(any(feature = "precursor", feature = "renode", feature = "cramium-fpga", feature = "cramium-soc"))]
mod implementation { mod implementation {
use utralib::generated::*; use utralib::generated::*;
@ -63,16 +58,16 @@ mod implementation {
) )
.expect("couldn't map D11cTimeout CSR range"); .expect("couldn't map D11cTimeout CSR range");
D11cTimeout { D11cTimeout { d11t_csr: CSR::new(csr.as_mut_ptr() as *mut u32) }
d11t_csr: CSR::new(csr.as_mut_ptr() as *mut u32),
}
} }
pub fn deterministic_busy_wait(&self) { pub fn deterministic_busy_wait(&self) {
let phase = self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT); let phase = self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT);
while phase == self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT) { while phase == self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT) {
xous::yield_slice(); xous::yield_slice();
} }
} }
pub fn hosted_delay(&self) { pub fn hosted_delay(&self) {
// this is a delay used in hosted mode to prevent threads from thrashing. We don't need this on // this is a delay used in hosted mode to prevent threads from thrashing. We don't need this on
// raw hardware because we aren't multi-core, and thus a yield_slice() will always schedule // raw hardware because we aren't multi-core, and thus a yield_slice() will always schedule
@ -88,15 +83,13 @@ mod implementation {
mod implementation { mod implementation {
pub struct D11cTimeout {} pub struct D11cTimeout {}
impl D11cTimeout { impl D11cTimeout {
pub fn new() -> Self { pub fn new() -> Self { D11cTimeout {} }
D11cTimeout {}
}
pub fn deterministic_busy_wait(&self) { pub fn deterministic_busy_wait(&self) {
// don't do anything for hosted mode // don't do anything for hosted mode
} }
pub fn hosted_delay(&self) {
std::thread::sleep(std::time::Duration::from_millis(10)); pub fn hosted_delay(&self) { std::thread::sleep(std::time::Duration::from_millis(10)); }
}
} }
} }
@ -123,11 +116,8 @@ struct CheckedHashMap {
pub map: HashMap<XousServerName, Connection>, pub map: HashMap<XousServerName, Connection>,
} }
impl CheckedHashMap { impl CheckedHashMap {
pub fn new() -> Self { pub fn new() -> Self { CheckedHashMap { map: HashMap::new() } }
CheckedHashMap {
map: HashMap::new(),
}
}
pub fn insert( pub fn insert(
&mut self, &mut self,
name: XousServerName, name: XousServerName,
@ -158,10 +148,11 @@ impl CheckedHashMap {
); );
Ok(()) Ok(())
} }
pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> { pub fn remove(&mut self, sid: xous::SID) -> Option<XousServerName> {
// remove is expensive, because we have to do a full search for the sid, which is not our usual key // remove is expensive, because we have to do a full search for the sid, which is not our usual key
// however, for security reasons, you have to let us know your sid (which is a secret) in order to delete // however, for security reasons, you have to let us know your sid (which is a secret) in order to
// your entry; whereas the human-readable name is not at all a secret // delete your entry; whereas the human-readable name is not at all a secret
let mut removed_name: Option<XousServerName> = None; let mut removed_name: Option<XousServerName> = None;
for (name, mapping) in self.map.iter_mut() { for (name, mapping) in self.map.iter_mut() {
if mapping.sid == sid { if mapping.sid == sid {
@ -176,9 +167,7 @@ impl CheckedHashMap {
removed_name removed_name
} }
pub fn contains_key(&self, name: &XousServerName) -> bool { pub fn contains_key(&self, name: &XousServerName) -> bool { self.map.contains_key(name) }
self.map.contains_key(name)
}
pub fn connect(&mut self, name: &XousServerName) -> (Option<xous::SID>, Option<[u32; 4]>) { pub fn connect(&mut self, name: &XousServerName) -> (Option<xous::SID>, Option<[u32; 4]>) {
if let Some(entry) = self.map.get_mut(name) { if let Some(entry) = self.map.get_mut(name) {
@ -225,12 +214,7 @@ impl CheckedHashMap {
for (name, entry) in self.map.iter() { for (name, entry) in self.map.iter() {
if let Some(max) = entry.max_conns { if let Some(max) = entry.max_conns {
if max != entry.current_conns { if max != entry.current_conns {
log::info!( log::info!("server {} has {} conns but expects {}", name, entry.current_conns, max);
"server {} has {} conns but expects {}",
name,
entry.current_conns,
max
);
trusted_done = false; trusted_done = false;
} }
} }
@ -262,15 +246,14 @@ impl CheckedHashMap {
if let Some(old_token) = entry.token { if let Some(old_token) = entry.token {
if token == old_token { if token == old_token {
if entry.current_conns != 1 { if entry.current_conns != 1 {
log::warn!("disconnect with token used on system with more than one client; this will cause other disconnects to fail"); log::warn!(
"disconnect with token used on system with more than one client; this will cause other disconnects to fail"
);
} }
(*entry).current_conns = 0; (*entry).current_conns = 0;
// generate the token -- we should never re-use these! // generate the token -- we should never re-use these!
(*entry).token = Some( (*entry).token =
xous::create_server_id() Some(xous::create_server_id().expect("couldn't create token").to_array());
.expect("couldn't create token")
.to_array(),
);
return true; return true;
} }
} }
@ -280,10 +263,7 @@ impl CheckedHashMap {
} }
fn name_from_msg(env: &MessageEnvelope) -> Result<XousServerName, ConnectError> { fn name_from_msg(env: &MessageEnvelope) -> Result<XousServerName, ConnectError> {
let msg = env let msg = env.body.memory_message().ok_or(ConnectError::InvalidMessageType)?;
.body
.memory_message()
.ok_or(ConnectError::InvalidMessageType)?;
let valid_bytes = msg.valid.map(|v| v.get()).unwrap_or_else(|| msg.buf.len()); let valid_bytes = msg.valid.map(|v| v.get()).unwrap_or_else(|| msg.buf.len());
if valid_bytes > msg.buf.len() { if valid_bytes > msg.buf.len() {
log::error!("valid bytes exceeded entire buffer length"); log::error!("valid bytes exceeded entire buffer length");
@ -306,16 +286,16 @@ fn blocking_connect(
) -> Result<ConnectSuccess, ConnectError> { ) -> Result<ConnectSuccess, ConnectError> {
let name = name_from_msg(env)?; let name = name_from_msg(env)?;
let sender_pid = env.sender.pid().expect("kernel provided us a PID of None"); let sender_pid = env.sender.pid().expect("kernel provided us a PID of None");
log::trace!( log::trace!("BlockingConnect request for '{}' for process {:?}", name, sender_pid);
"BlockingConnect request for '{}' for process {:?}",
name,
sender_pid
);
// If the server already exists, attempt to make the connection. The connection can // If the server already exists, attempt to make the connection. The connection can
// only succeed if the server is in the name_table. // only succeed if the server is in the name_table.
if let (Some(server_sid), token) = name_table.connect(&name) { if let (Some(server_sid), token) = name_table.connect(&name) {
log::trace!("Found entry in the table (sid: {:?}, token: {:?}) -- attempting to call connect_for_process()", server_sid, token); log::trace!(
"Found entry in the table (sid: {:?}, token: {:?}) -- attempting to call connect_for_process()",
server_sid,
token
);
let result = xous::connect_for_process(sender_pid, server_sid); let result = xous::connect_for_process(sender_pid, server_sid);
if let Ok(xous::Result::ConnectionID(connection_id)) = result { if let Ok(xous::Result::ConnectionID(connection_id)) = result {
log::trace!( log::trace!(
@ -327,10 +307,7 @@ fn blocking_connect(
); );
return Ok(ConnectSuccess::Connected(connection_id, token)); return Ok(ConnectSuccess::Connected(connection_id, token));
} else { } else {
log::error!( log::error!("error when making connection, perhaps the server crashed? {:?}", result);
"error when making connection, perhaps the server crashed? {:?}",
result
);
// The server connection process failed inside the kernel for one reason or // The server connection process failed inside the kernel for one reason or
// another, so remove the entry from the `name_table` and return an error // another, so remove the entry from the `name_table` and return an error
@ -346,9 +323,7 @@ fn blocking_connect(
fn respond_connect_error(mut msg: MessageEnvelope, result: ConnectError) { fn respond_connect_error(mut msg: MessageEnvelope, result: ConnectError) {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();
let s = unsafe { let s = unsafe { core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4) };
core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4)
};
s[0] = 1; s[0] = 1;
s[1] = result as u32; s[1] = result as u32;
mem.valid = None; mem.valid = None;
@ -357,9 +332,7 @@ fn respond_connect_error(mut msg: MessageEnvelope, result: ConnectError) {
fn respond_connect_success(mut msg: MessageEnvelope, cid: xous::CID, disc: Option<[u32; 4]>) { fn respond_connect_success(mut msg: MessageEnvelope, cid: xous::CID, disc: Option<[u32; 4]>) {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();
let s = unsafe { let s = unsafe { core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4) };
core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4)
};
s[0] = 0; s[0] = 0;
s[1] = cid as u32; s[1] = cid as u32;
s[2] = disc.map(|d| d[0]).unwrap_or_default(); s[2] = disc.map(|d| d[0]).unwrap_or_default();
@ -376,8 +349,8 @@ fn main() -> ! {
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Info);
info!("my PID is {}", xous::process::id()); info!("my PID is {}", xous::process::id());
let name_server = xous::create_server_with_address(b"xous-name-server") let name_server =
.expect("Couldn't create xousnames-server"); xous::create_server_with_address(b"xous-name-server").expect("Couldn't create xousnames-server");
let d11ctimeout = D11cTimeout::new(); let d11ctimeout = D11cTimeout::new();
@ -399,10 +372,7 @@ fn main() -> ! {
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let registration = buffer.to_original::<Registration, _>().unwrap(); let registration = buffer.to_original::<Registration, _>().unwrap();
let name = XousServerName::from_str( let name = XousServerName::from_str(
registration registration.name.as_str().expect("couldn't convert server name to string"),
.name
.as_str()
.expect("couldn't convert server name to string"),
); );
let response: api::Return; let response: api::Return;
@ -410,8 +380,7 @@ fn main() -> ! {
log::trace!("registration request for '{}'", name); log::trace!("registration request for '{}'", name);
if !name_table.contains_key(&name) { if !name_table.contains_key(&name) {
let new_sid = let new_sid = xous::create_server_id().expect("create server failed, maybe OOM?");
xous::create_server_id().expect("create server failed, maybe OOM?");
name_table name_table
.insert(name, new_sid, registration.conn_limit) .insert(name, new_sid, registration.conn_limit)
.expect("register name failure, maybe out of HashMap capacity?"); .expect("register name failure, maybe out of HashMap capacity?");
@ -424,9 +393,7 @@ fn main() -> ! {
info!("deterministic timeout done"); info!("deterministic timeout done");
response = api::Return::Failure response = api::Return::Failure
} }
buffer buffer.replace(response).expect("Register can't serialize return value");
.replace(response)
.expect("Register can't serialize return value");
// Drop the message, which causes it to get sent back to the sender. // Drop the message, which causes it to get sent back to the sender.
// The sender will then create the server immediately, allowing us // The sender will then create the server immediately, allowing us
@ -448,7 +415,9 @@ fn main() -> ! {
respond_connect_success(msg, cid, disc) respond_connect_success(msg, cid, disc)
} }
Ok(ConnectSuccess::Wait) => { Ok(ConnectSuccess::Wait) => {
panic!("message connection attempt resulted in `Wait` even though it ought to exist"); panic!(
"message connection attempt resulted in `Wait` even though it ought to exist"
);
} }
} }
} }
@ -478,9 +447,7 @@ fn main() -> ! {
match blocking_connect(&mut msg, &mut name_table) { match blocking_connect(&mut msg, &mut name_table) {
Err(e) => respond_connect_error(msg, e), Err(e) => respond_connect_error(msg, e),
Ok(ConnectSuccess::Connected(cid, disc)) => { Ok(ConnectSuccess::Connected(cid, disc)) => respond_connect_success(msg, cid, disc),
respond_connect_success(msg, cid, disc)
}
Ok(ConnectSuccess::Wait) => { Ok(ConnectSuccess::Wait) => {
if msg.body.id() == api::Opcode::TryConnect as usize { if msg.body.id() == api::Opcode::TryConnect as usize {
respond_connect_error(msg, ConnectError::ServerNotFound); respond_connect_error(msg, ConnectError::ServerNotFound);
@ -497,19 +464,13 @@ fn main() -> ! {
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let name_string = buffer.to_original::<String<64>, _>().unwrap(); let name_string = buffer.to_original::<String<64>, _>().unwrap();
let name = XousServerName::from_str( let name = XousServerName::from_str(
name_string name_string.as_str().expect("couldn't convert server name to string"),
.as_str()
.expect("couldn't convert server name to string"),
); );
log::trace!("Lookup request for '{}'", name); log::trace!("Lookup request for '{}'", name);
let response: api::Return; let response: api::Return;
if let (Some(server_sid), token) = name_table.connect(&name) { if let (Some(server_sid), token) = name_table.connect(&name) {
let sender_pid = msg let sender_pid = msg.sender.pid().expect("can't extract sender PID on Lookup");
.sender match xous::connect_for_process(sender_pid, server_sid).expect("can't broker connection")
.pid()
.expect("can't extract sender PID on Lookup");
match xous::connect_for_process(sender_pid, server_sid)
.expect("can't broker connection")
{ {
xous::Result::ConnectionID(connection_id) => { xous::Result::ConnectionID(connection_id) => {
log::trace!("lookup success, returning connection {}", connection_id); log::trace!("lookup success, returning connection {}", connection_id);
@ -529,13 +490,12 @@ fn main() -> ! {
for (_name, conn) in name_table.map.iter() { for (_name, conn) in name_table.map.iter() {
log::debug!("{:?}", conn); log::debug!("{:?}", conn);
} }
// no authenticate remedy currently supported, but we'd put that code somewhere around here eventually. // no authenticate remedy currently supported, but we'd put that code somewhere around
// here eventually.
let (c1, c2, c3, c4) = xous::create_server_id().unwrap().to_u32(); let (c1, c2, c3, c4) = xous::create_server_id().unwrap().to_u32();
let auth_request = AuthenticateRequest { let auth_request = AuthenticateRequest {
name: String::<64>::from_str( name: String::<64>::from_str(
name_string name_string.as_str().expect("couldn't convert server name to string"),
.as_str()
.expect("couldn't convert server name to string"),
), ),
pubkey_id: [0; 20], // placeholder pubkey_id: [0; 20], // placeholder
challenge: [c1, c2, c3, c4], challenge: [c1, c2, c3, c4],
@ -543,9 +503,7 @@ fn main() -> ! {
d11ctimeout.hosted_delay(); d11ctimeout.hosted_delay();
response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path
} }
buffer buffer.replace(response).expect("Lookup can't serialize return value");
.replace(response)
.expect("Lookup can't serialize return value");
} }
Some(api::Opcode::AuthenticatedLookup) => { Some(api::Opcode::AuthenticatedLookup) => {
let mem = msg.body.memory_message_mut().unwrap(); let mem = msg.body.memory_message_mut().unwrap();