clean up Sendable references and warnings

This commit is contained in:
bunnie 2021-02-17 23:29:20 +08:00
parent 14f661f565
commit 0af72ffb6d
13 changed files with 113 additions and 156 deletions

View file

@ -21,8 +21,8 @@ riscv = "0.5.6"
debug-print = []
print-panics = []
report-memory = ["stats_alloc"]
default = ["print-panics", "debug-print"]
# default = ["print-panics"]
# default = ["print-panics", "debug-print"]
default = ["print-panics"]
[target.'cfg(any(windows, unix))'.dependencies]
lazy_static = "1.4"

View file

@ -474,7 +474,7 @@ pub fn lend_page_inner(
dest_addr: *mut u8,
mutable: bool,
) -> Result<usize, xous_kernel::Error> {
klog!("***lend - src: {:08x} dest: {:08x}***", src_addr as u32, dest_addr as u32);
//klog!("***lend - src: {:08x} dest: {:08x}***", src_addr as u32, dest_addr as u32);
let entry = pagetable_entry(src_addr as usize)?;
let phys = (*entry >> 10) << 12;
@ -531,7 +531,7 @@ pub fn return_page_inner(
dest_space: &MemoryMapping,
dest_addr: *mut u8,
) -> Result<usize, xous_kernel::Error> {
klog!("***return - src: {:08x} dest: {:08x}***", src_addr as u32, dest_addr as u32);
//klog!("***return - src: {:08x} dest: {:08x}***", src_addr as u32, dest_addr as u32);
let src_entry = pagetable_entry(src_addr as usize)?;
let phys = (*src_entry >> 10) << 12;

View file

@ -6,10 +6,6 @@ use xous::{Message, ScalarMessage};
use com_rs_ref as com_rs;
use com_rs::*;
// subtype constants for registering service listeners from the COM
// pub const SUBTYPE_REGISTER_BATTSTATS_LISTENER: u16 = 0;
pub const REGISTER_BATTSTATS_LISTENER: u32 = 0x0022_0000;
#[derive(Debug, Default, Copy, Clone, rkyv::Archive)]
pub struct BattStats {
/// instantaneous voltage in mV
@ -146,24 +142,6 @@ impl core::convert::TryFrom<& Message> for Opcode {
Err("unrecognized opcode")
}
},
/*
Message::Borrow(m) => {
if m.id as u16 == ComState::WFX_PDS_LINE_SET.verb {
let s = unsafe {
core::slice::from_raw_parts(
m.buf.as_ptr(),
m.valid.map(|x| x.get()).unwrap_or_else(|| m.buf.len()),
)
};
Ok(Opcode::Wf200PdsLine(core::str::from_utf8(s).unwrap()))
} else if m.id as u32 == REGISTER_BATTSTATS_LISTENER {
Ok(Opcode::RegisterBattStatsListener({
unsafe { *( (m.buf.as_mut_ptr()) as *mut xous_names::api::XousServerName) }
}))
} else {
Err("COM: unknown borrow ID")
}
}*/
_ => Err("unhandled message type"),
}
}

View file

@ -53,8 +53,16 @@ pub fn get_ec_git_rev(cid: CID) -> Result<(u32, bool), Error> {
}
pub fn send_pds_line(cid: CID, s: &xous::String<512>) -> Result<(), Error> {
s.lend(cid /*, ComState::WFX_PDS_LINE_SET.verb as _ */).map( |_| ())
// send_message(cid, api::Opcode::Wf200PdsLine(line).into()).map(|_| ())
use core::fmt::Write;
let mut clone_s: xous::String<512> = xous::String::new();
write!(clone_s, "{}", s.as_str().unwrap()).map_err(|_| xous::Error::AccessDenied)?;
let request = api::Opcode::Wf200PdsLine(clone_s);
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(512));
let pos = writer.archive(&request).expect("COM: couldn't archive PDS line request");
let xous_buffer = writer.into_inner();
xous_buffer.lend(cid, pos as u32).expect("COM: PDS line request failure");
Ok(())
}
pub fn get_rx_stats_agent(cid: CID) -> Result<(), Error> {

View file

@ -271,11 +271,35 @@ fn xmain() -> ! {
let value = unsafe {
archived_value_mut::<api::Opcode>(Pin::new(buf.as_mut()), m.id as usize)
};
let new_value = match &*value {
match &*value {
rkyv::Archived::<api::Opcode>::RegisterBattStatsListener(registration_name) => {
let cid = xous_names::request_connection_blocking(registration_name.as_str()).expect("COM: can't connect to requested listener for reporting events");
battstats_conns.push(cid).expect("COM: probably ran out of slots for battstats event reporting");
},
rkyv::Archived::<api::Opcode>::Wf200PdsLine(rkyv_l) => {
use rkyv::Unarchive;
let l: xous::String<512> = rkyv_l.unarchive();
info!("COM: Wf200PdsLine got line {}", l);
let line = l.as_bytes();
let length = line.len() as u16;
//info!("COM: 0x{:04x}", ComState::WFX_PDS_LINE_SET.verb);
com.txrx(ComState::WFX_PDS_LINE_SET.verb);
//info!("COM: 0x{:04x}", length);
com.txrx(length);
//for i in 0..(ComState::WFX_PDS_LINE_SET.w_words as usize - 1) {
for i in 0..128 {
let word: u16;
if (i * 2 + 1) == length as usize { // odd last element
word = line[i * 2] as u16;
} else if i * 2 < length as usize {
word = (line[i*2] as u16) | ((line[i*2+1] as u16) << 8);
} else {
word = 0;
}
com.txrx(word);
//info!("COM: 0x{:04x}", word);
}
}
_ => panic!("Invalid memory message response -- corruption occurred"),
};
} else if let Ok(opcode) = Opcode::try_from(&envelope.body) {
@ -327,29 +351,6 @@ fn xmain() -> ! {
)
.expect("COM: couldn't return WF200 firmware rev");
}
/*
Opcode::Wf200PdsLine(l) => {
info!("COM: Wf200PdsLine got line {}", l);
let line = l.as_bytes();
let length = line.len() as u16;
//info!("COM: 0x{:04x}", ComState::WFX_PDS_LINE_SET.verb);
com.txrx(ComState::WFX_PDS_LINE_SET.verb);
//info!("COM: 0x{:04x}", length);
com.txrx(length);
//for i in 0..(ComState::WFX_PDS_LINE_SET.w_words as usize - 1) {
for i in 0..128 {
let word: u16;
if (i * 2 + 1) == length as usize { // odd last element
word = line[i * 2] as u16;
} else if i * 2 < length as usize {
word = (line[i*2] as u16) | ((line[i*2+1] as u16) << 8);
} else {
word = 0;
}
com.txrx(word);
//info!("COM: 0x{:04x}", word);
}
}*/
Opcode::RxStatsAgent => {
if cfg!(feature = "fccagent") {
// note -- this code never worked, but wasn't needed. just hanging out as bread crumbs for future work in case this is needed.
@ -365,11 +366,7 @@ fn xmain() -> ! {
let m = xous::Message::Borrow(data.into_message(2));
xous::send_message(agent_conn, m).expect("Can't send RxStat message to FCC agent!");
}
}/*
Opcode::RegisterBattStatsListener(registration) => {
let cid = xous_names::request_connection_blocking(registration.to_str()).expect("COM: can't connect to requested listener for reporting events");
battstats_conns.push(cid).expect("COM: probably ran out of slots for battstats event reporting");
}*/
}
_ => error!("unknown opcode"),
}
} else {

View file

@ -49,12 +49,12 @@ fn xmain() -> ! {
let msg = xous::receive_message(sid).unwrap();
//info!("GFX: Message: {:?}", msg);
if let xous::Message::Borrow(m) = &msg.body {
let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
let buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe {
archived_value::<api::Opcode>(&bytes, m.id.try_into().unwrap())
};
let new_value = match &*value {
match &*value {
rkyv::Archived::<api::Opcode>::String(rkyv_s) => {
let s: xous::String<4096> = rkyv_s.unarchive();
//info!("GFX: unarchived string: {:?}", s);

View file

@ -3,11 +3,9 @@ use core::ops::Deref;
use heapless::consts::*;
use heapless::Vec;
use xous::{Message, ScalarMessage};
use rkyv::{RelPtr, Archive, Archived, Resolve, Resolver, Write};
use rkyv::{RelPtr, Archive, Resolve, Write};
use core::slice;
pub const REGISTER_BASIC_LISTENER: u32 = 0x1000_0000;
pub const REGISTER_RAW_LISTENER: u32 = 0x1000_0001;
use core::ops::DerefMut;
#[derive(Debug, Default, Copy, Clone)]
pub struct ScanCode {
@ -28,18 +26,12 @@ pub struct RowCol {
}
#[repr(packed)]
pub struct KeyRawStates {
mid: u32,
pub keydowns: Vec<RowCol, U16>,
pub keyups: Vec<RowCol, U16>,
}
impl KeyRawStates {
pub fn mid(&self) -> usize {
self.mid as usize
}
pub fn new() -> Self {
KeyRawStates {
mid: xous::names::GID_KEYBOARD_RAW_KEYSTATE_EVENT as u32,
keydowns: Vec::new(),
keyups: Vec::new(),
}
@ -73,12 +65,34 @@ impl Deref for KeyRawStates {
}
}
}
impl DerefMut for KeyRawStates {
fn deref_mut(&mut self) -> &mut[u8] {
unsafe {
slice::from_raw_parts_mut(self as *mut KeyRawStates as *mut u8, core::mem::size_of::<KeyRawStates>())
as &mut [u8]
}
}
}
// warning: this rkyv code is totally untested
pub struct ArchivedKeyRawStates {
ptr: RelPtr,
len: u32,
}
#[allow(dead_code)]
impl ArchivedKeyRawStates {
fn as_keyrawstates(&self) -> KeyRawStates {
let mut returned_krs: KeyRawStates = KeyRawStates::new();
let bytes: &[u8];
unsafe {
bytes = core::slice::from_raw_parts(self.ptr.as_ptr(), self.len as usize);
}
for (dest, src) in returned_krs.deref_mut().iter_mut().zip(bytes.iter()) {
*dest = *src;
}
returned_krs
}
}
pub struct KeyRawStatesResolver {
bytes_pos: usize,
}

View file

@ -16,8 +16,7 @@ use log::{error, info};
use core::pin::Pin;
use xous::buffer;
use rkyv::{archived_value, Unarchive};
use rkyv::Write;
use rkyv::{archived_value, Write};
/// Compute the dvorak key mapping of row/col to key tuples
fn map_dvorak(code: RowCol) -> ScanCode {
@ -819,12 +818,12 @@ fn xmain() -> ! {
Some(envelope) => {
info!("KBD: Message: {:?}", envelope);
if let xous::Message::Borrow(m) = &envelope.body {
let mut buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
let buf = unsafe { buffer::XousBuffer::from_memory_message(m) };
let bytes = Pin::new(buf.as_ref());
let value = unsafe {
archived_value::<api::Opcode>(&bytes, m.id as usize)
};
let new_value = match &*value {
match &*value {
rkyv::Archived::<api::Opcode>::RegisterListener(registration) => {
let cid = xous_names::request_connection_blocking(registration.as_str()).expect("KBD: can't connect to requested listener for reporting events");
normal_conns.push(cid).expect("KBD: probably ran out of slots for keyboard event reporting");
@ -884,17 +883,21 @@ fn xmain() -> ! {
let mut rs: KeyRawStates = KeyRawStates::new();
if let Some(ku) = &keyups {
for &k in ku.iter() {
rs.keyups.push(k).unwrap();
unsafe { // because rs is "repr packed"
rs.keyups.push(k).unwrap();
}
}
}
if let Some(kd) = &keydowns {
for &k in kd.iter() {
rs.keydowns.push(k).unwrap();
unsafe {
rs.keydowns.push(k).unwrap();
}
}
}
let mut writer = rkyv::ArchiveBuffer::new(xous::XousBuffer::new(4096));
let pos = writer.archive(&rs).expect("couldn't archive request");
let mut xous_buffer = writer.into_inner();
let xous_buffer = writer.into_inner();
xous_buffer.send(*conn, pos as u32).expect("KBD: can't send raw code");
}
}

View file

@ -324,7 +324,7 @@ fn some_main() -> ! {
)
.expect("couldn't map GPIO CSR range");
let mut gpio = CSR::new(gpio_base.as_mut_ptr() as *mut u32);
gpio.wfo(utra::gpio::UARTSEL_UARTSEL, 0); // 0 = kernel, 1 = log, 2 = app_uart
gpio.wfo(utra::gpio::UARTSEL_UARTSEL, 1); // 0 = kernel, 1 = log, 2 = app_uart
}
let mut output = implementation::init();

View file

@ -32,41 +32,38 @@ is necessary for implementing deterministic timing delays in
wait a fixed period of time on initialization while the initial set
of name registrations occur.
A new process that intends to receive messages initializes using the
following procedure:
A new process that intends to receive messages uses the `register_name` convenience
function in the `xous-names/src/lib.rs` file, with the following procedure.
1. It creates a `Registration` IPC structure by wrapping it in `xous::ipc::Sendable`,
using the `new()` initializer.
1. It calls `register_name` with a preferred ASCII name string,
limited to 64 characters. The convenience function wraps this in an `rkyv`
object and passes it as mutable-borrowed memory to the name server.
2. It copies a preferred ASCII name string, limited to 64 characters,
into the `Registration` record. It then uses the `.lend_mut()` method
on the Sendable Registration to lend the structure to `xous-name-server`.
The sending process will block until `xous-name-server` returns.
3. `xous-name-server` returns the borrowed memory to the server, with the
response field with a code that either affirms the name was
registered, or the registration is denied (because the proposed name
is already taken or otherwise invalid). In the case that the registration
2. `xous-name-server` returns the borrowed memory to the server, where the
buffer has been replaced with a response field. In the case that the registration
is affirmed, the SID field in `Registration` contains the assigned SID
of calling process.
of calling process. In the case that the name is determined to be invalid
(perhaps because it is already reserved or registered), it will return
an error code.
4. If the registration is denied, the server can attempt to
3. If the registration is denied, the server can attempt to
re-register its SID with a different ASCII name string by repeating
steps 2-3.
A process that would like to send a server a message does so using the following procedure:
A process that would like to send a server a message must first request the
name server to broker a connection to the target process. It does this by
typically calling the `request_conneciton_blocking` convenience function
with the registered name of the server.
1. It creates a `Lookup` IPC structure by wrapping it in a `xous::ipc::Sendable`,
using the `new()` initializer.
1. `request_connection_blocking` is called with the maximum 64-character
ASCII name string.
2. It populates the Lookup structure with the name of the server it is looking up.
3. It uses `.lend_mut()` method to send `xous-name-server` a “Mutable Borrow”
`MemoryMessage`.
2. The convencience function creates a `Lookup` message which is lent to
the name server.
4. `xous-name-server` can respond with one of three results:
A. affirm the connection, where one of the slots contains the connection ID;
A. affirm the connection by returning a connection ID
B. a flat denial of the connection; or
C. a slot containing a request to authenticate.
@ -80,8 +77,8 @@ the common case, and many servers follow this path, such as those
asking for access to the `ticktimer` or other public services.
B. flat denial: `xous-name-server` simply returns a message saying the
request was denied by setting `success` to `false`. This is also the case
when the request is malformed or incorrect. No information shall be leaked about the
request was denied. This is also the case when the request is malformed or incorrect.
No information shall be leaked about the
nature of the denial. Denials are also delayed to the nearest 0.1 second interval since boot
to eliminate side channels and to rate limit fuzzing requests. Some
services (such as the key server) are restricted to only a set of

View file

@ -38,56 +38,6 @@ pub(crate) enum Request {
CID(CID),
}
// impl Request {
// pub fn set_response(&mut self, val: bool) {
// *self = Request::Result(val);
// }
// }
// #[derive(rkyv::Archive)]
// pub(crate) struct Response {
// pub success: bool,
// }
// impl Response {
// pub fn fail() -> Response {
// Response { success: false }
// }
// }
// #[derive(Debug, Copy, Clone, Default, rkyv::Archive)]
// pub(crate) struct Registration {
// pub sid: [u32; 4],
// // we use fixed-length, u8-only records to pass server names. This is different from
// // your typical Rust String object; but, a key restriction on IPC calls is that the size
// // of structures must be (1) statically known and (2) contain no references. Therefore
// // the name is a pre-allocated, 64-length u8 array, and the *entire* array is the name,
// // including characters after the first "null"
// pub name: XousServerName,
// pub success: bool,
// }
// impl Registration {
// // pub fn mid(&self) -> usize { self.mid as usize }
// // pub fn get_subtype(&self) -> u16 { (self.mid & 0xFFFF) as u16 }
// // pub fn set_subtype(&mut self, subtype: u16) { self.mid = (self.mid & 0xFFFF_0000) | (subtype as u32); }
// pub fn match_subtype(id: u32, subtype: u16) -> bool {
// ((id & 0xFFFF) as u16 == subtype)
// && ((id & 0xFFFF_0000) == (ID_REGISTER_NAME & 0xFFFF_0000))
// }
// // pub fn new() -> Self {
// // Registration {
// // mid: ID_REGISTER_NAME as u32,
// // sid: Default::default(),
// // name: XousServerName::default(),
// // success: false,
// // }
// // }
// }
#[derive(Debug, Default, rkyv::Archive)]
pub(crate) struct Lookup {
pub name: XousServerName,

View file

@ -30,6 +30,8 @@ pub fn register_name(name: &str) -> Result<xous::SID, xous::Error> {
let sid = sid.into();
xous::create_server_with_sid(sid).expect("can't auto-register server");
Ok(sid)
} else if let rkyv::Archived::<api::Request>::Failure = archived {
return Err(xous::Error::InternalError);
} else {
panic!("Invalid response from the server -- corruption occurred");
}

View file

@ -19,6 +19,10 @@ impl<const N: usize> String<N> {
}
}
pub fn as_bytes(&self) -> [u8; N] {
self.bytes
}
pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> {
core::str::from_utf8(&self.bytes[0..self.len as usize])
}
@ -46,6 +50,11 @@ impl<const N: usize> String<N> {
/// Perform an immutable lend of this String to the specified server.
/// This function will block until the server returns.
/// Note that this convenience should only be used if the server only ever
/// expects to deal with one type of String, ever. Otherwise, this should be
/// implemented in the API and wrapped in an Enum to help decorate the functional
/// target of the string. An example of a server that uses this convencience function
/// is the logger.
pub fn lend(
&self,
connection: CID,
@ -60,20 +69,19 @@ impl<const N: usize> String<N> {
xous_buffer.lend(connection, pos as u32)
}
/*
/// Move this string from the client into the server.
pub fn send(
self,
connection: CID,
id: crate::MessageId,
// id: crate::MessageId,
) -> core::result::Result<Result, Error> {
let mut writer = rkyv::ArchiveBuffer::new(crate::XousBuffer::new(/*self.bytes.len()*/ 4096));
let pos = writer.archive(&self).expect("xous::String -- couldn't archive self");
let mut xous_buffer = writer.into_inner();
let xous_buffer = writer.into_inner();
xous_buffer.send(connection, pos as u32)
}
*/
/// Clear the contents of this String and set the length to 0
pub fn clear(&mut self) {
self.len = 0;