Merge pull request #289 from betrusted-io/reply-and-receive-next-syscall

Reply and receive next syscall
This commit is contained in:
bunnie 2022-12-30 15:16:13 +08:00 committed by GitHub
commit e4c298db40
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 456 additions and 110 deletions

View file

@ -1,4 +1,5 @@
/// Do not modify the discriminants in this structure. They are used in `libstd` directly.
#[repr(usize)]
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub enum Opcode {
/// Get the elapsed time in milliseconds
@ -48,9 +49,12 @@ pub enum Opcode {
/// *arg1*: An integer of some sort, such as the address of the Condvar
/// *arg2*: The number of conditions to notify
NotifyCondition = 9,
/// Invalid call -- an error occurred decoding the opcode
InvalidCall = u32::MAX as usize,
}
#[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct VersionString {
pub version: xous_ipc::String::<512>,
}
pub version: xous_ipc::String<512>,
}

View file

@ -36,12 +36,12 @@ impl fmt::Write for Output {
self.character_count = 0;
} else if self.character_count > 80 {
self.character_count = 0;
self.uart.putc(b'\n');
self.uart.putc(b'\r');
self.uart.putc(b' ');
self.uart.putc(b' ');
self.uart.putc(b' ');
self.uart.putc(b' ');
self.serial.putc(b'\n');
self.serial.putc(b'\r');
self.serial.putc(b' ');
self.serial.putc(b' ');
self.serial.putc(b' ');
self.serial.putc(b' ');
} else {
self.character_count += 1;
}

View file

@ -589,7 +589,7 @@ impl Server {
// Sanity check the specified address was correct, and matches what we
// had cached.
if is_memory && cfg!(baremetal) {
if is_memory && cfg!(baremetal) && buf.is_some() {
let buf = buf.expect("memory message expected but no buffer passed!");
if server_addr != buf.as_ptr() as usize || len != buf.len() {
// klog!("Memory is attached but the returned buffer doesn't match (len: {} vs {}), buf addr: {:08x} vs {:08x}", len, buf.len(), server_addr, buf.as_ptr() as usize);

View file

@ -199,7 +199,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
ss.set_thread_result(
server_pid,
server_tid,
xous_kernel::Result::Message(envelope),
xous_kernel::Result::MessageEnvelope(envelope),
)
.expect("couldn't set result for server thread");
ss.activate_process_thread(thread, ppid, ptid, false)
@ -209,7 +209,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
// Switch to the server, since it's in a state to be run.
klog!("Activating Server context and switching away from Client");
ss.activate_process_thread(thread, server_pid, server_tid, false)
.map(|_| Ok(xous_kernel::Result::Message(envelope)))
.map(|_| Ok(xous_kernel::Result::MessageEnvelope(envelope)))
.unwrap_or(Err(xous_kernel::Error::ProcessNotFound))
}
} else if blocking && !cfg!(baremetal) {
@ -219,7 +219,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
ss.set_thread_result(
server_pid,
server_tid,
xous_kernel::Result::Message(envelope),
xous_kernel::Result::MessageEnvelope(envelope),
)
.map(|_| xous_kernel::Result::BlockedProcess)
} else if cfg!(baremetal) {
@ -228,7 +228,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
ss.set_thread_result(
server_pid,
server_tid,
xous_kernel::Result::Message(envelope),
xous_kernel::Result::MessageEnvelope(envelope),
)
.map(|_| xous_kernel::Result::Ok)
} else {
@ -242,7 +242,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
ss.set_thread_result(
server_pid,
server_tid,
xous_kernel::Result::Message(envelope),
xous_kernel::Result::MessageEnvelope(envelope),
)
.map(|_| xous_kernel::Result::Ok)
};
@ -616,6 +616,147 @@ fn return_scalar5(
})
}
fn reply_and_receive_next(
server_pid: PID,
server_tid: TID,
_in_irq: bool,
sender: MessageSender,
arg0: usize,
arg1: usize,
arg2: usize,
arg3: usize,
arg4: usize,
scalar_type: usize,
) -> SysCallResult {
let sender = SenderID::from(sender);
SystemServices::with_mut(|ss| {
struct MessageResponse {
pid: PID,
tid: TID,
result: xous_kernel::Result,
}
let (result, next_message) = {
let server = ss
.server_from_sidx_mut(sender.sidx)
.ok_or(xous_kernel::Error::ServerNotFound)?;
if server.pid != server_pid {
println!(
"WARNING: PIDs don't match! The server is from PID {}, but our PID is {}",
server.pid, server_pid
);
return Err(xous_kernel::Error::ServerNotFound);
}
let waiting_message = server.take_waiting_message(sender.idx, None)?;
let next_message = server.take_next_message(sender.sidx);
// If there is no message, park the server thread. We do this here because
// we cannot hold the `Server` object while we also modify process state.
if next_message.is_none() {
server.park_thread(server_tid);
}
(waiting_message, next_message)
};
// TODO: Have errors turn into calls to `ReceiveMessage`
let response = match result {
WaitingMessage::ScalarMessage(pid, tid) => {
let result = match scalar_type {
1 => xous_kernel::Result::Scalar1(arg1),
2 => xous_kernel::Result::Scalar2(arg1, arg2),
_ => xous_kernel::Result::Scalar5(arg0, arg1, arg2, arg3, arg4),
};
MessageResponse { pid, tid, result }
}
WaitingMessage::ForgetMemory(_) => {
println!(
"WARNING: Tried to wait on a scalar message that was actually forgetting memory"
);
return Err(xous_kernel::Error::ProcessNotFound);
}
WaitingMessage::BorrowedMemory(pid, tid, _server_addr, client_addr, len) => {
#[cfg(baremetal)]
let src_virt = _server_addr.get() as _;
#[cfg(not(baremetal))]
let src_virt = arg1 as _; // TODO: Check this is correct on hosted mode
// Return the memory to the calling process
ss.return_memory(src_virt, pid, tid, client_addr.get() as _, len.get())?;
MessageResponse {
pid,
tid,
result: xous_kernel::Result::MemoryReturned(MemorySize::new(arg3), MemorySize::new(arg4)),
}
}
WaitingMessage::MovedMemory => {
println!(
"WARNING: Tried to wait on a scalar message that was actually moved memory"
);
return Err(xous_kernel::Error::ProcessNotFound);
}
WaitingMessage::None => {
println!("WARNING: Tried to wait on a message that didn't exist");
return Err(xous_kernel::Error::ProcessNotFound);
}
};
// If there is a pending message, fetch it and schedule the thread to run
if let Some(msg) = next_message {
if cfg!(baremetal) {
// When the server is resumed, it will receive this as a return value.
ss.set_thread_result(
server_pid,
server_tid,
xous_kernel::Result::MessageEnvelope(msg),
)?;
ss.ready_thread(response.pid, response.tid).unwrap();
ss.set_thread_result(response.pid, response.tid, response.result)?;
ss.activate_process_thread(server_tid, response.pid, response.tid, true)
.map(|_| Ok(xous_kernel::Result::ResumeProcess))
.unwrap_or(Err(xous_kernel::Error::ProcessNotFound))
} else {
// Switch to the client and return the result
ss.ready_thread(response.pid, response.tid)?;
ss.switch_to_thread(response.pid, Some(response.tid))?;
ss.set_thread_result(response.pid, response.tid, response.result)?;
// Return the new message envelope to the server
Ok(xous_kernel::Result::MessageEnvelope(msg))
}
} else {
// For baremetal targets, switch away from this process.
if cfg!(baremetal) {
// Switch back to the client process.
ss.ready_thread(response.pid, response.tid)?;
// Set the thread result for the client
ss.set_thread_result(response.pid, response.tid, response.result)?;
// Activate the client thread and switch to it
ss.activate_process_thread(server_tid, response.pid, response.tid, false)
.map(|_| Ok(xous_kernel::Result::ResumeProcess))
.unwrap_or(Err(xous_kernel::Error::ProcessNotFound))
}
// For hosted targets, simply return `BlockedProcess` indicating we'll make
// a callback to their socket at a later time.
else {
ss.unschedule_thread(server_pid, server_tid)?;
// Switch to the client and return the result
ss.ready_thread(response.pid, response.tid)?;
ss.switch_to_thread(response.pid, Some(response.tid))?;
ss.set_thread_result(response.pid, response.tid, response.result)?;
// Indicate that the server should block its process
Ok(xous_kernel::Result::BlockedProcess)
}
}
})
}
fn receive_message(pid: PID, tid: TID, sid: SID, blocking: ExecutionType) -> SysCallResult {
SystemServices::with_mut(|ss| {
assert!(
@ -639,7 +780,7 @@ fn receive_message(pid: PID, tid: TID, sid: SID, blocking: ExecutionType) -> Sys
// If there is a pending message, return it immediately.
if let Some(msg) = server.take_next_message(sidx) {
klog!("waiting messages found -- returning {:x?}", msg);
return Ok(xous_kernel::Result::Message(msg));
return Ok(xous_kernel::Result::MessageEnvelope(msg));
}
if blocking == ExecutionType::NonBlocking {
@ -936,6 +1077,9 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR
SysCall::ReturnScalar5(sender, arg1, arg2, arg3, arg4, arg5) => {
return_scalar5(pid, tid, in_irq, sender, arg1, arg2, arg3, arg4, arg5)
}
SysCall::ReplyAndReceiveNext(sender, a0, a1, a2, a3, a4, scalar_type) => {
reply_and_receive_next(pid, tid, in_irq, sender, a0, a1, a2, a3, a4, scalar_type)
}
SysCall::TrySendMessage(cid, message) => send_message(pid, tid, cid, message),
SysCall::TerminateProcess(_ret) => SystemServices::with_mut(|ss| {
ss.unschedule_thread(pid, tid)?;

View file

@ -32,7 +32,7 @@ fn handle_panic(_arg: &core::panic::PanicInfo) -> ! {
pub extern "C" fn init(server1: u32, server2: u32, server3: u32, server4: u32) -> ! {
let server = xous::SID::from_u32(server1, server2, server3, server4);
loop {
if let Ok(xous::Result::Message(envelope)) =
if let Ok(xous::Result::MessageEnvelope(envelope)) =
xous::rsyscall(xous::SysCall::ReceiveMessage(server))
{
match envelope.id().into() {

View file

@ -3,7 +3,7 @@
#![cfg_attr(target_os = "none", no_main)]
use xous_api_ticktimer::*;
#[cfg(feature="timestamp")]
#[cfg(feature = "timestamp")]
mod version;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
@ -62,7 +62,7 @@ impl core::cmp::PartialEq for TimerRequest {
}
}
#[cfg(any(feature="precursor", feature="renode"))]
#[cfg(any(feature = "precursor", feature = "renode"))]
mod implementation {
const TICKS_PER_MS: u64 = 1;
use super::TimerRequest;
@ -284,8 +284,9 @@ mod implementation {
}
}
#[cfg(any(not(target_os = "xous"),
not(any(feature="precursor", feature="renode", not(target_os = "xous")))
#[cfg(any(
not(target_os = "xous"),
not(any(feature = "precursor", feature = "renode", not(target_os = "xous")))
))]
mod implementation {
use crate::RequestKind;
@ -524,14 +525,14 @@ fn main() -> ! {
log::set_max_level(log::LevelFilter::Info);
info!("my PID is {}", xous::process::id());
#[cfg(feature="timestamp")]
#[cfg(feature = "timestamp")]
{
log::info!("****************************************************************");
log::info!("Welcome to Xous {}", version::SEMVER);
log::info!("Built on {}", version::TIMESTAMP);
log::info!("****************************************************************");
}
#[cfg(not(feature="timestamp"))]
#[cfg(not(feature = "timestamp"))]
{
log::info!("****************************************************************");
log::info!("Welcome to Xous");
@ -598,38 +599,66 @@ fn main() -> ! {
let mut mutex_hash: HashMap<Option<xous::PID>, HashMap<usize, VecDeque<xous::MessageSender>>> =
HashMap::new();
let mut msg_opt = None;
let mut return_type = 0;
loop {
#[cfg(feature = "watchdog")]
ticktimer.reset_wdt();
//#[cfg(feature = "watchdog")] // for debugging the watchdog
//ticktimer.check_wdt();
let mut msg = xous::receive_message(ticktimer_server).unwrap();
xous::reply_and_receive_next_legacy(ticktimer_server, &mut msg_opt, &mut return_type)
.unwrap();
let msg = msg_opt.as_mut().unwrap();
log::trace!("msg: {:x?}", msg);
match num_traits::FromPrimitive::from_usize(msg.body.id()) {
Some(api::Opcode::ElapsedMs) => {
let time = ticktimer.elapsed_ms() as i64;
xous::return_scalar2(
msg.sender,
(time & 0xFFFF_FFFFi64) as usize,
((time >> 32) & 0xFFF_FFFFi64) as usize,
)
.expect("couldn't return time request");
match num_traits::FromPrimitive::from_usize(msg.body.id())
.unwrap_or(api::Opcode::InvalidCall)
{
api::Opcode::ElapsedMs => {
if let Some(scalar) = msg.body.scalar_message_mut() {
let time = ticktimer.elapsed_ms() as i64;
scalar.arg1 = (time & 0xFFFF_FFFFi64) as usize;
scalar.arg2 = ((time >> 32) & 0xFFF_FFFFi64) as usize;
scalar.id = 0;
// API calls expect a `Scalar2` value in response
return_type = 2;
}
}
Some(api::Opcode::SleepMs) => xous::msg_blocking_scalar_unpack!(msg, ms, _, _, _, {
// let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default();
recalculate_sleep(
&mut ticktimer,
&mut sleep_heap,
Some(TimerRequest {
msec: ms as i64,
sender: msg.sender,
kind: RequestKind::Sleep,
data: 0,
}),
)
}),
Some(api::Opcode::RecalculateSleep) => {
api::Opcode::SleepMs => {
if let Some(scalar) = msg.body.scalar_message_mut() {
let ms = scalar.arg1 as i64;
let sender = msg.sender;
// Forget the contents of the message, replacing it with `None`. This
// will prevent it from getting dropped, which (under normal circumstances)
// would cause it to be responded to automatically.
//
// The ideal approach here would be to have the struct -- in this case the
// TimerRequest -- keep track of the element itself. That way, it could
// return the value as part of its response routine. However, due to the
// legacy split of `BlockingScalars`, these are allowed to have an explicit
// return path, so we need to forget the original message here to prevent
// it from getting returned early.
//
// (n.b. this auto-response hasn't been enabled yet for Scalar messages,
// but this definitely would need to be done for e.g. Memory messages).
core::mem::forget(msg_opt.take());
// let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default();
recalculate_sleep(
&mut ticktimer,
&mut sleep_heap,
Some(TimerRequest {
msec: ms,
sender: sender,
kind: RequestKind::Sleep,
data: 0,
}),
);
}
}
api::Opcode::RecalculateSleep => {
// let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default();
if let Some(args) = msg.body.scalar_message() {
// If this is a Timeout message that fired, remove it from the Notification list
@ -643,7 +672,8 @@ fn main() -> ! {
// the first check confirms that the origin of the RecalculateSleep message is the Ticktimer,
// to prevent third-party servers from issuing the command and thus distorting the sleep
// calculations (since this is a public API, anything could happen).
if (msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32) == xous::process::id()
if (msg.sender.pid().map(|p| p.get()).unwrap_or_default() as u32)
== xous::process::id()
&& (request_kind == RequestKind::Timeout as usize)
&& (sender > 0)
{
@ -667,44 +697,40 @@ fn main() -> ! {
}
recalculate_sleep(&mut ticktimer, &mut sleep_heap, None);
}
Some(api::Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
api::Opcode::SuspendResume => xous::msg_scalar_unpack!(msg, token, _, _, _, {
ticktimer.suspend();
susres
.suspend_until_resume(token)
.expect("couldn't execute suspend/resume");
ticktimer.resume();
}),
Some(api::Opcode::PingWdt) => {
api::Opcode::PingWdt => {
ticktimer.reset_wdt();
}
Some(api::Opcode::GetVersion) => {
api::Opcode::GetVersion => {
let mut buf = unsafe {
xous_ipc::Buffer::from_memory_message_mut(
msg.body.memory_message_mut().unwrap(),
)
};
#[cfg(feature="timestamp")]
#[cfg(feature = "timestamp")]
buf.replace(version::get_version()).unwrap();
#[cfg(not(feature="timestamp"))]
#[cfg(not(feature = "timestamp"))]
{
let v = crate::api::VersionString {
version: xous_ipc::String::from_str("--no-timestamp requested for build")
version: xous_ipc::String::from_str("--no-timestamp requested for build"),
};
buf.replace(v).unwrap();
}
}
Some(api::Opcode::LockMutex) => {
api::Opcode::LockMutex => {
let pid = msg.sender.pid();
if !msg.body.is_blocking() {
info!("sender made LockMutex request that was not blocking");
continue;
}
if let Some(scalar) = msg.body.scalar_message() {
if let Some(scalar) = msg.body.scalar_message_mut() {
let ready = mutex_ready_hash.entry(pid).or_default();
// If this item is in the Ready list, return right away without blocking
if ready.remove(&scalar.arg1) {
xous::return_scalar(msg.sender, 0).unwrap();
scalar.id = 0;
continue;
}
@ -716,9 +742,15 @@ fn main() -> ! {
// the message will get a response.
let mutex_entry = awaiting.entry(scalar.arg1).or_default();
mutex_entry.push_back(msg.sender);
// We've saved the `msg.sender` above and will return the lock as part of the mutex
// work thread. Forget the contents of `msg_opt` without running its destructor.
core::mem::forget(msg_opt.take());
} else {
info!("sender made LockMutex request that was not blocking");
}
}
Some(api::Opcode::UnlockMutex) => {
api::Opcode::UnlockMutex => {
let pid = msg.sender.pid();
if msg.body.is_blocking() {
info!("sender made UnlockMutex request that was blocking");
@ -740,13 +772,9 @@ fn main() -> ! {
}
}
}
Some(api::Opcode::WaitForCondition) => {
api::Opcode::WaitForCondition => {
let pid = msg.sender.pid();
if !msg.body.is_blocking() {
info!("sender made WaitForCondition request that was not blocking");
continue;
}
if let Some(scalar) = msg.body.scalar_message() {
if let Some(scalar) = msg.body.scalar_message_mut() {
let condvar = scalar.arg1;
let timeout = scalar.arg2;
@ -766,8 +794,10 @@ fn main() -> ! {
{
if *excess > 0 {
*excess -= 1;
xous::return_scalar(msg.sender, 0)
.expect("couldn't respond to message");
scalar.id = 0;
// Rust libstd expects a `Scalar1` return type for this call
return_type = 1;
continue;
}
}
@ -795,14 +825,18 @@ fn main() -> ! {
.push_back(msg.sender);
// log::trace!("New waiting senders: {:?}", notify_hash.get(&pid).unwrap().get(&condvar));
continue;
// The message will be responded to as part of the notification hash
// when the condvar is unlocked. Forget the contents of the message
// in order to prevent it from being responded to early.
core::mem::forget(msg_opt.take());
} else {
info!(
"sender made WaitForCondition request that wasn't a BlockingScalar Message"
);
}
}
Some(api::Opcode::NotifyCondition) => {
api::Opcode::NotifyCondition => {
let pid = msg.sender.pid();
if msg.body.is_blocking() {
info!("sender made NotifyCondition request that was blocking");
@ -831,13 +865,7 @@ fn main() -> ! {
stop_sleep(&mut ticktimer, &mut sleep_heap);
for entry in awaiting.drain(..available_count) {
// Remove each entry in the timeout set
sleep_heap.retain(|_, v| {
if v.sender == entry {
false
} else {
true
}
});
sleep_heap.retain(|_, v| if v.sender == entry { false } else { true });
xous::return_scalar(entry, 0).expect("couldn't send response");
}
@ -865,7 +893,7 @@ fn main() -> ! {
);
}
}
None => {
api::Opcode::InvalidCall => {
error!("couldn't convert opcode");
}
}

View file

@ -233,7 +233,7 @@ fn read_next_syscall_result(
// If the client is passing us memory, read bytes from the data, then
// remap the addresses to function in our address space.
if let Result::Message(msg) = &mut response {
if let Result::MessageEnvelope(msg) = &mut response {
match &mut msg.body {
crate::Message::Move(ref mut memory_message)
| crate::Message::Borrow(ref mut memory_message)

View file

@ -757,7 +757,7 @@ fn _xous_syscall_result(ret: &mut Result, thread_id: TID, server_connection: &Se
});
// If the client is passing us memory, remap the array to our own space.
if let Result::Message(msg) = &mut response {
if let Result::MessageEnvelope(msg) = &mut response {
match &mut msg.body {
crate::Message::Move(ref mut memory_message)
| crate::Message::Borrow(ref mut memory_message)

View file

@ -421,7 +421,7 @@ pub enum Result {
NewServerID(SID, CID),
// 9
Message(MessageEnvelope),
MessageEnvelope(MessageEnvelope),
// 10
ThreadID(TID),
@ -463,6 +463,9 @@ pub enum Result {
/// 20: A scalar with five values
Scalar5(usize, usize, usize, usize, usize),
// 21: A message is returned as part of `send_message()` when the result is blocking
Message(Message),
UnknownResult(usize, usize, usize, usize, usize, usize, usize),
}
@ -488,7 +491,7 @@ impl Result {
[6, s.0 as _, s.1 as _, s.2 as _, s.3 as _, 0, 0, 0]
}
Result::ConnectionID(cid) => [7, *cid as usize, 0, 0, 0, 0, 0, 0],
Result::Message(me) => {
Result::MessageEnvelope(me) => {
let me_enc = me.to_usize();
[
9, me_enc[0], me_enc[1], me_enc[2], me_enc[3], me_enc[4], me_enc[5], me_enc[6],
@ -526,7 +529,13 @@ impl Result {
0,
],
Result::NewProcess(p) => Self::add_opcode(19, p.into()),
Result::Scalar5(a, b, c, d, e) => [15, *a, *b, *c, *d, *e, 0, 0],
Result::Scalar5(a, b, c, d, e) => [20, *a, *b, *c, *d, *e, 0, 0],
Result::Message(message) => {
let encoded = message.to_usize();
[
21, encoded[0], encoded[1], encoded[2], encoded[3], encoded[4], encoded[5], 0,
]
}
Result::UnknownResult(arg1, arg2, arg3, arg4, arg5, arg6, arg7) => {
[usize::MAX, *arg1, *arg2, *arg3, *arg4, *arg5, *arg6, *arg7]
}
@ -589,7 +598,7 @@ impl Result {
)),
_ => return Result::Error(Error::InternalError),
};
Result::Message(MessageEnvelope {
Result::MessageEnvelope(MessageEnvelope {
sender: MessageSender::from_usize(sender),
body: message,
})
@ -605,19 +614,36 @@ impl Result {
18 => Result::MemoryReturned(MemorySize::new(src[1]), MemorySize::new(src[2])),
19 => Result::NewProcess(src.into()),
20 => Result::Scalar5(src[1], src[2], src[3], src[4], src[5]),
21 => Result::Message(match src[1] {
0 => match MemoryMessage::from_usize(src[2], src[3], src[4], src[5], src[6]) {
None => return Result::Error(Error::InternalError),
Some(s) => Message::MutableBorrow(s),
},
1 => match MemoryMessage::from_usize(src[2], src[3], src[4], src[5], src[6]) {
None => return Result::Error(Error::InternalError),
Some(s) => Message::Borrow(s),
},
2 => match MemoryMessage::from_usize(src[2], src[3], src[4], src[5], src[6]) {
None => return Result::Error(Error::InternalError),
Some(s) => Message::Move(s),
},
3 => Message::Scalar(ScalarMessage::from_usize(
src[2], src[3], src[4], src[5], src[6],
)),
4 => Message::BlockingScalar(ScalarMessage::from_usize(
src[2], src[3], src[4], src[5], src[6],
)),
_ => return Result::Error(Error::InternalError),
}),
_ => Result::UnknownResult(src[0], src[1], src[2], src[3], src[4], src[5], src[6]),
}
}
/// If the Result has memory attached to it, return the memory
pub fn memory(&self) -> Option<MemoryRange> {
pub fn memory(&self) -> Option<&MemoryRange> {
match self {
Result::Message(msg) => match &msg.body {
Message::Move(memory_message)
| Message::Borrow(memory_message)
| Message::MutableBorrow(memory_message) => Some(memory_message.buf),
_ => None,
},
Result::MessageEnvelope(msg) => msg.body.memory(),
Result::Message(msg) => msg.memory(),
_ => None,
}
}

View file

@ -10,21 +10,15 @@ pub struct Envelope {
impl Envelope {
pub fn to_usize(&self) -> [usize; 7] {
let ret = match &self.body {
Message::MutableBorrow(m) => (0, m.to_usize()),
Message::Borrow(m) => (1, m.to_usize()),
Message::Move(m) => (2, m.to_usize()),
Message::Scalar(m) => (3, m.to_usize()),
Message::BlockingScalar(m) => (4, m.to_usize()),
};
let body_usize = self.body.to_usize();
[
self.sender.to_usize(),
ret.0,
ret.1[0],
ret.1[1],
ret.1[2],
ret.1[3],
ret.1[4],
body_usize[0],
body_usize[1],
body_usize[2],
body_usize[3],
body_usize[4],
body_usize[5],
]
}

View file

@ -92,7 +92,7 @@ impl MemoryMessage {
}
#[repr(C)]
#[derive(Debug, PartialEq, Clone, Copy)]
#[derive(Debug, PartialEq, Clone, Copy, Default)]
/// A simple scalar message. This is similar to a `move` message.
pub struct ScalarMessage {
pub id: MessageId,
@ -210,6 +210,10 @@ impl Message {
}
}
pub fn is_scalar(&self) -> bool {
!self.has_memory()
}
pub fn memory(&self) -> Option<&MemoryRange> {
self.memory_message().map(|msg| &msg.buf)
}
@ -235,6 +239,15 @@ impl Message {
}
}
pub fn scalar_message_mut(&mut self) -> Option<&mut ScalarMessage> {
match self {
Message::MutableBorrow(_)
| Message::Borrow(_)
| Message::Move(_)
| Message::Scalar(_) => None,
Message::BlockingScalar(scalar) => Some(scalar),
}
}
pub(crate) fn message_type(&self) -> usize {
match *self {
Message::MutableBorrow(_) => 1,
@ -260,6 +273,19 @@ impl Message {
Message::Scalar(s) | Message::BlockingScalar(s) => s.id = id,
}
}
pub fn to_usize(&self) -> [usize; 6] {
let ret = match &*self {
Message::MutableBorrow(m) => (0, m.to_usize()),
Message::Borrow(m) => (1, m.to_usize()),
Message::Move(m) => (2, m.to_usize()),
Message::Scalar(m) => (3, m.to_usize()),
Message::BlockingScalar(m) => (4, m.to_usize()),
};
[
ret.0, ret.1[0], ret.1[1], ret.1[2], ret.1[3], ret.1[4],
]
}
}
impl TryFrom<(usize, usize, usize, usize, usize, usize)> for Message {

View file

@ -158,7 +158,7 @@ pub enum SysCall {
///
/// # Returns
///
/// * **Message**: A valid message from the queue
/// * **MessageEnvelope**: A valid message from the queue
///
/// # Errors
///
@ -324,11 +324,14 @@ pub enum SysCall {
///
/// # Returns
///
/// * **Ok**: The Scalar / Send message was successfully sent, or the Borrow has finished
/// * **Ok**: The Scalar / Send message was successfully sent
/// * **Scalar1**: The Server returned a `Scalar1` value
/// * **Scalar2**: The Server returned a `Scalar2` value
/// * **Scalar5**: The Server returned a `Scalar5` value
/// * **BlockedProcess**: In Hosted mode, the target process is now blocked
/// * **Message**: For Scalar messages, this includes the args as returned
/// by the server. For MemoryMessages, this will include
/// the Opcode, Offset, and Valid fields.
///
/// # Errors
///
@ -475,6 +478,45 @@ pub enum SysCall {
/// Return five scalars to the sender
ReturnScalar5(MessageSender, usize, usize, usize, usize, usize),
/// Return a message with the given Message ID and the provided parameters,
/// and listen for another message on the server ID that sent this message.
/// This call is meant to be used in the main loop of a server in order to
/// reduce latency when that server is called frequently.
///
/// This call works on both `MemoryMessages` and `BlockingScalars`, and does
/// not distinguish between the two from the API.
///
/// ## Arguments
///
/// * **MessageSender**: This is the `sender` from the message envelope.
/// It is a unique ID that identifies this message,
/// as well as the server it came from.
///
/// The remaining arguments depend on whether the message was a `BlockingScalar`
/// message or a `MemoryMessage`. Note that this function should NOT be called
/// on non-blocking messages such as `Send` or `Scalar`.
///
/// ## Returns
///
/// * **Message**: A valid message from the queue
///
/// # Errors
///
/// * **ServerNotFound**: The given SID is not active or has terminated
/// * **ProcessNotFound**: The parent process terminated when we were getting ready
/// to block. This is an internal error.
/// * **BlockedProcess**: When running in Hosted mode, this indicates that this
/// thread is blocking.
ReplyAndReceiveNext(
MessageSender, /* ID if the sender that sent this message */
usize, /* Return code to the caller */
usize, /* arg1 (BlockingScalar) or the memory address (MemoryMesage) */
usize, /* arg2 (BlockingScalar) or the memory length (MemoryMesage) */
usize, /* arg3 (BlockingScalar) or the memory offset (MemoryMesage) */
usize, /* arg4 (BlockingScalar) or the memory valid (MemoryMesage) */
usize, /* for BlockingScalars, indicates how many args are valid */
),
/// This syscall does not exist. It captures all possible
/// arguments so detailed analysis can be performed.
Invalid(usize, usize, usize, usize, usize, usize, usize),
@ -522,6 +564,7 @@ pub enum SysCallNumber {
#[cfg(feature = "v2p")]
VirtToPhys = 39,
ReturnScalar5 = 40,
ReplyAndReceiveNext = 41,
Invalid,
}
@ -569,6 +612,7 @@ impl SysCallNumber {
#[cfg(feature = "v2p")]
39 => VirtToPhys,
40 => ReturnScalar5,
41 => ReplyAndReceiveNext,
_ => Invalid,
}
}
@ -806,6 +850,17 @@ impl SysCall {
0,
0,
],
SysCall::ReplyAndReceiveNext(sender, arg0, arg1, arg2, arg3, arg4, return_type) => [
SysCallNumber::ReplyAndReceiveNext as usize,
sender.to_usize(),
*arg0,
*arg1,
*arg2,
*arg3,
*arg4,
*return_type,
],
SysCall::CreateThread(init) => {
crate::arch::thread_to_args(SysCallNumber::CreateThread as usize, init)
}
@ -1030,6 +1085,9 @@ impl SysCall {
MemorySize::new(a4),
MemorySize::new(a5),
),
SysCallNumber::ReplyAndReceiveNext => {
SysCall::ReplyAndReceiveNext(MessageSender::from_usize(a1), a2, a3, a4, a5, a6, a7)
}
SysCallNumber::CreateThread => {
SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?)
}
@ -1516,7 +1574,7 @@ pub fn try_connect(server: SID) -> core::result::Result<CID, Error> {
///
pub fn receive_message(server: SID) -> core::result::Result<MessageEnvelope, Error> {
let result = rsyscall(SysCall::ReceiveMessage(server)).expect("Couldn't call ReceiveMessage");
if let Result::Message(envelope) = result {
if let Result::MessageEnvelope(envelope) = result {
Ok(envelope)
} else if let Result::Error(e) = result {
Err(e)
@ -1533,7 +1591,7 @@ pub fn receive_message(server: SID) -> core::result::Result<MessageEnvelope, Err
pub fn try_receive_message(server: SID) -> core::result::Result<Option<MessageEnvelope>, Error> {
let result =
rsyscall(SysCall::TryReceiveMessage(server)).expect("Couldn't call ReceiveMessage");
if let Result::Message(envelope) = result {
if let Result::MessageEnvelope(envelope) = result {
Ok(Some(envelope))
} else if result == Result::None {
Ok(None)
@ -1563,6 +1621,7 @@ pub fn try_send_message(connection: CID, message: Message) -> core::result::Resu
Ok(Result::Scalar2(a, b)) => Ok(Result::Scalar2(a, b)),
Ok(Result::Scalar5(a, b, c, d, e)) => Ok(Result::Scalar5(a, b, c, d, e)),
Ok(Result::MemoryReturned(offset, valid)) => Ok(Result::MemoryReturned(offset, valid)),
Ok(Result::MessageEnvelope(msg)) => Ok(Result::MessageEnvelope(msg)),
Err(e) => Err(e),
v => panic!("Unexpected return value: {:?}", v),
}
@ -1870,6 +1929,71 @@ pub fn join_thread(tid: TID) -> core::result::Result<usize, Error> {
}
})
}
/// Reply to the message, if one exists, and receive the next one.
/// If no message exists, delegate the call to `receive_syscall()`.
pub fn reply_and_receive_next(
server: SID,
msg: &mut Option<MessageEnvelope>,
) -> core::result::Result<(), crate::Error> {
reply_and_receive_next_legacy(server, msg, &mut 0)
}
/// Reply to the message, if one exists, and receive the next one.
/// If no message exists, delegate the call to `receive_syscall()`.
/// Allow specifying the scalar return type.
///
/// This is named `_legacy` because it is meant to work with calls that
/// expect both `Scalar1` and `Scalar2` values, in addition to `Scalar5`.
///
/// ## Arguments
///
/// * **server**: The SID of the server to receive messages from
/// * **msg**: An Option<MessageEnvelope> specifying the message to return.
/// * **return_type**: If 1 or 2, responds to a BlockingScalarMessage
/// with a Scalar1 or a Scalar2. Otherwise, will respond
/// as normal.
pub fn reply_and_receive_next_legacy(
server: SID,
msg: &mut Option<MessageEnvelope>,
return_type: &mut usize,
) -> core::result::Result<(), crate::Error> {
let rt = *return_type;
*return_type = 0;
if let Some(envelope) = msg.take() {
// If the message inside is nonblocking, then there's nothing to return.
// Delegate reception to the `receive_message()` call
if !envelope.body.is_blocking() {
*msg = Some(receive_message(server)?);
return Ok(());
}
let args = if let Some(mem) = envelope.body.memory_message() {
mem.to_usize()
} else if let Some(scalar) = envelope.body.scalar_message() {
scalar.to_usize()
} else {
panic!("unrecognized message type")
};
let sender = envelope.sender;
core::mem::forget(envelope);
let call =
SysCall::ReplyAndReceiveNext(sender, args[0], args[1], args[2], args[3], args[4], rt);
match rsyscall(call) {
Ok(crate::Result::MessageEnvelope(envelope)) => {
*msg = Some(envelope);
Ok(())
}
Ok(crate::Result::Error(e)) => Err(e),
_ => Err(crate::Error::InternalError),
}
} else {
// No waiting message -- call the existing `receive_message()` function
*msg = Some(receive_message(server)?);
Ok(())
}
}
/* https://github.com/betrusted-io/xous-core/issues/90
static EXCEPTION_HANDLER: core::sync::atomic::AtomicUsize = core::sync::atomic::AtomicUsize::new(0);
fn handle_exception(exception_type: usize, arg1: usize, arg2: usize) -> isize {