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_main)]
use xous_api_names::*;
use xous_api_names::api::*;
use num_traits::FromPrimitive;
use xous::{msg_blocking_scalar_unpack, MessageEnvelope};
use xous_ipc::{Buffer, String};
use std::collections::HashMap;
use log::{error, info};
use std::collections::HashMap;
use num_traits::FromPrimitive;
use xous::{msg_blocking_scalar_unpack, MessageEnvelope};
use xous_api_names::api::*;
use xous_api_names::*;
use xous_ipc::{Buffer, String};
#[derive(PartialEq)]
#[repr(C)]
@ -35,10 +33,7 @@ enum ConnectError {
#[repr(C)]
enum ConnectSuccess {
/// The server connection was successfully made
Connected(
xous::CID, /* Connection ID */
Option<[u32; 4]>, /* Disconnection token */
),
Connected(xous::CID /* Connection ID */, Option<[u32; 4]> /* Disconnection token */),
/// There is no server with that name -- block this message
Wait,
@ -46,7 +41,7 @@ enum ConnectSuccess {
// 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 {
use utralib::generated::*;
@ -63,16 +58,16 @@ mod implementation {
)
.expect("couldn't map D11cTimeout CSR range");
D11cTimeout {
d11t_csr: CSR::new(csr.as_mut_ptr() as *mut u32),
}
D11cTimeout { d11t_csr: CSR::new(csr.as_mut_ptr() as *mut u32) }
}
pub fn deterministic_busy_wait(&self) {
let phase = self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT);
while phase == self.d11t_csr.rf(utra::d11ctime::HEARTBEAT_BEAT) {
xous::yield_slice();
}
}
pub fn hosted_delay(&self) {
// 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
@ -88,15 +83,13 @@ mod implementation {
mod implementation {
pub struct D11cTimeout {}
impl D11cTimeout {
pub fn new() -> Self {
D11cTimeout {}
}
pub fn new() -> Self { D11cTimeout {} }
pub fn deterministic_busy_wait(&self) {
// 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>,
}
impl CheckedHashMap {
pub fn new() -> Self {
CheckedHashMap {
map: HashMap::new(),
}
}
pub fn new() -> Self { CheckedHashMap { map: HashMap::new() } }
pub fn insert(
&mut self,
name: XousServerName,
@ -158,10 +148,11 @@ impl CheckedHashMap {
);
Ok(())
}
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
// however, for security reasons, you have to let us know your sid (which is a secret) in order to delete
// your entry; whereas the human-readable name is not at all a secret
// however, for security reasons, you have to let us know your sid (which is a secret) in order to
// delete your entry; whereas the human-readable name is not at all a secret
let mut removed_name: Option<XousServerName> = None;
for (name, mapping) in self.map.iter_mut() {
if mapping.sid == sid {
@ -176,9 +167,7 @@ impl CheckedHashMap {
removed_name
}
pub fn contains_key(&self, name: &XousServerName) -> bool {
self.map.contains_key(name)
}
pub fn contains_key(&self, name: &XousServerName) -> bool { self.map.contains_key(name) }
pub fn connect(&mut self, name: &XousServerName) -> (Option<xous::SID>, Option<[u32; 4]>) {
if let Some(entry) = self.map.get_mut(name) {
@ -225,12 +214,7 @@ impl CheckedHashMap {
for (name, entry) in self.map.iter() {
if let Some(max) = entry.max_conns {
if max != entry.current_conns {
log::info!(
"server {} has {} conns but expects {}",
name,
entry.current_conns,
max
);
log::info!("server {} has {} conns but expects {}", name, entry.current_conns, max);
trusted_done = false;
}
}
@ -262,15 +246,14 @@ impl CheckedHashMap {
if let Some(old_token) = entry.token {
if token == old_token {
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;
// generate the token -- we should never re-use these!
(*entry).token = Some(
xous::create_server_id()
.expect("couldn't create token")
.to_array(),
);
(*entry).token =
Some(xous::create_server_id().expect("couldn't create token").to_array());
return true;
}
}
@ -280,10 +263,7 @@ impl CheckedHashMap {
}
fn name_from_msg(env: &MessageEnvelope) -> Result<XousServerName, ConnectError> {
let msg = env
.body
.memory_message()
.ok_or(ConnectError::InvalidMessageType)?;
let msg = env.body.memory_message().ok_or(ConnectError::InvalidMessageType)?;
let valid_bytes = msg.valid.map(|v| v.get()).unwrap_or_else(|| msg.buf.len());
if valid_bytes > msg.buf.len() {
log::error!("valid bytes exceeded entire buffer length");
@ -306,16 +286,16 @@ fn blocking_connect(
) -> Result<ConnectSuccess, ConnectError> {
let name = name_from_msg(env)?;
let sender_pid = env.sender.pid().expect("kernel provided us a PID of None");
log::trace!(
"BlockingConnect request for '{}' for process {:?}",
name,
sender_pid
);
log::trace!("BlockingConnect request for '{}' for process {:?}", name, sender_pid);
// If the server already exists, attempt to make the connection. The connection can
// only succeed if the server is in the name_table.
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);
if let Ok(xous::Result::ConnectionID(connection_id)) = result {
log::trace!(
@ -327,10 +307,7 @@ fn blocking_connect(
);
return Ok(ConnectSuccess::Connected(connection_id, token));
} else {
log::error!(
"error when making connection, perhaps the server crashed? {:?}",
result
);
log::error!("error when making connection, perhaps the server crashed? {:?}", result);
// 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
@ -346,9 +323,7 @@ fn blocking_connect(
fn respond_connect_error(mut msg: MessageEnvelope, result: ConnectError) {
let mem = msg.body.memory_message_mut().unwrap();
let s = unsafe {
core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4)
};
let s = unsafe { core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4) };
s[0] = 1;
s[1] = result as u32;
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]>) {
let mem = msg.body.memory_message_mut().unwrap();
let s = unsafe {
core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4)
};
let s = unsafe { core::slice::from_raw_parts_mut(mem.buf.as_mut_ptr() as *mut u32, mem.buf.len() / 4) };
s[0] = 0;
s[1] = cid as u32;
s[2] = disc.map(|d| d[0]).unwrap_or_default();
@ -376,8 +349,8 @@ fn main() -> ! {
log::set_max_level(log::LevelFilter::Info);
info!("my PID is {}", xous::process::id());
let name_server = xous::create_server_with_address(b"xous-name-server")
.expect("Couldn't create xousnames-server");
let name_server =
xous::create_server_with_address(b"xous-name-server").expect("Couldn't create xousnames-server");
let d11ctimeout = D11cTimeout::new();
@ -399,10 +372,7 @@ fn main() -> ! {
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let registration = buffer.to_original::<Registration, _>().unwrap();
let name = XousServerName::from_str(
registration
.name
.as_str()
.expect("couldn't convert server name to string"),
registration.name.as_str().expect("couldn't convert server name to string"),
);
let response: api::Return;
@ -410,8 +380,7 @@ fn main() -> ! {
log::trace!("registration request for '{}'", name);
if !name_table.contains_key(&name) {
let new_sid =
xous::create_server_id().expect("create server failed, maybe OOM?");
let new_sid = xous::create_server_id().expect("create server failed, maybe OOM?");
name_table
.insert(name, new_sid, registration.conn_limit)
.expect("register name failure, maybe out of HashMap capacity?");
@ -424,9 +393,7 @@ fn main() -> ! {
info!("deterministic timeout done");
response = api::Return::Failure
}
buffer
.replace(response)
.expect("Register can't serialize return value");
buffer.replace(response).expect("Register can't serialize return value");
// Drop the message, which causes it to get sent back to the sender.
// The sender will then create the server immediately, allowing us
@ -448,7 +415,9 @@ fn main() -> ! {
respond_connect_success(msg, cid, disc)
}
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) {
Err(e) => respond_connect_error(msg, e),
Ok(ConnectSuccess::Connected(cid, disc)) => {
respond_connect_success(msg, cid, disc)
}
Ok(ConnectSuccess::Connected(cid, disc)) => respond_connect_success(msg, cid, disc),
Ok(ConnectSuccess::Wait) => {
if msg.body.id() == api::Opcode::TryConnect as usize {
respond_connect_error(msg, ConnectError::ServerNotFound);
@ -497,19 +464,13 @@ fn main() -> ! {
let mut buffer = unsafe { Buffer::from_memory_message_mut(mem) };
let name_string = buffer.to_original::<String<64>, _>().unwrap();
let name = XousServerName::from_str(
name_string
.as_str()
.expect("couldn't convert server name to string"),
name_string.as_str().expect("couldn't convert server name to string"),
);
log::trace!("Lookup request for '{}'", name);
let response: api::Return;
if let (Some(server_sid), token) = name_table.connect(&name) {
let sender_pid = msg
.sender
.pid()
.expect("can't extract sender PID on Lookup");
match xous::connect_for_process(sender_pid, server_sid)
.expect("can't broker connection")
let sender_pid = msg.sender.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) => {
log::trace!("lookup success, returning connection {}", connection_id);
@ -529,13 +490,12 @@ fn main() -> ! {
for (_name, conn) in name_table.map.iter() {
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 auth_request = AuthenticateRequest {
name: String::<64>::from_str(
name_string
.as_str()
.expect("couldn't convert server name to string"),
name_string.as_str().expect("couldn't convert server name to string"),
),
pubkey_id: [0; 20], // placeholder
challenge: [c1, c2, c3, c4],
@ -543,9 +503,7 @@ fn main() -> ! {
d11ctimeout.hosted_delay();
response = api::Return::AuthenticateRequest(auth_request) // this code just exists to exercise the return path
}
buffer
.replace(response)
.expect("Lookup can't serialize return value");
buffer.replace(response).expect("Lookup can't serialize return value");
}
Some(api::Opcode::AuthenticatedLookup) => {
let mem = msg.body.memory_message_mut().unwrap();