From 36e6e6c30b06f10ce64ad1fcb88c4bf2535d13c2 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 6 Jul 2022 15:18:32 +0800 Subject: [PATCH 01/12] xous: syscall: add ReplyAndReceiveNext call Signed-off-by: Sean Cross --- xous-rs/src/syscall.rs | 54 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 5047abe73..93018cc41 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -475,6 +475,44 @@ 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) */ + ), + /// 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 +560,7 @@ pub enum SysCallNumber { #[cfg(feature = "v2p")] VirtToPhys = 39, ReturnScalar5 = 40, + ReplyAndReceiveNext = 41, Invalid, } @@ -569,6 +608,7 @@ impl SysCallNumber { #[cfg(feature = "v2p")] 39 => VirtToPhys, 40 => ReturnScalar5, + 41 => ReplyAndReceiveNext, _ => Invalid, } } @@ -806,6 +846,17 @@ impl SysCall { 0, 0, ], + SysCall::ReplyAndReceiveNext(sender, result, arg1, arg2, arg3, arg4) => [ + SysCallNumber::ReturnMemory as usize, + sender.to_usize(), + *result, + *arg1, + *arg2, + *arg3, + *arg4, + 0, + ], + SysCall::CreateThread(init) => { crate::arch::thread_to_args(SysCallNumber::CreateThread as usize, init) } @@ -1030,6 +1081,9 @@ impl SysCall { MemorySize::new(a4), MemorySize::new(a5), ), + SysCallNumber::ReplyAndReceiveNext => { + SysCall::ReplyAndReceiveNext(MessageSender::from_usize(a1), a2, a3, a4, a5, a6) + } SysCallNumber::CreateThread => { SysCall::CreateThread(crate::arch::args_to_thread(a1, a2, a3, a4, a5, a6, a7)?) } From be56af6303b298c68d516409d4c32fe908c719be Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 6 Jul 2022 15:35:22 +0800 Subject: [PATCH 02/12] xous: add wrapper for reply_and_receive_next This wrapper enables userspace programs to use the new ReplyAndReceiveNext syscall easily. Signed-off-by: Sean Cross --- xous-rs/src/definitions/messages/mod.rs | 4 +++ xous-rs/src/syscall.rs | 45 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/xous-rs/src/definitions/messages/mod.rs b/xous-rs/src/definitions/messages/mod.rs index 0e29634d3..53ed4897c 100644 --- a/xous-rs/src/definitions/messages/mod.rs +++ b/xous-rs/src/definitions/messages/mod.rs @@ -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) } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 93018cc41..26f819b87 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -1924,6 +1924,51 @@ pub fn join_thread(tid: TID) -> core::result::Result { } }) } + +/// 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, +) -> core::result::Result<(), crate::Error> { + 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 call = SysCall::ReplyAndReceiveNext( + envelope.sender, + args[0], + args[1], + args[2], + args[3], + args[4], + ); + match rsyscall(call) { + Ok(crate::Result::Message(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 { From 49ce85f9a809b268c87525fe1915e75c31d06d9d Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Wed, 6 Jul 2022 15:57:10 +0800 Subject: [PATCH 03/12] ticktimer-server: prepare for using ReplyAndReceiveNext Misc cleanup prior to switching which call we use. Signed-off-by: Sean Cross --- api/xous-api-ticktimer/src/api.rs | 8 +++++-- services/xous-ticktimer/src/main.rs | 37 +++++++++++++---------------- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/api/xous-api-ticktimer/src/api.rs b/api/xous-api-ticktimer/src/api.rs index 18ab624f5..034f30501 100644 --- a/api/xous-api-ticktimer/src/api.rs +++ b/api/xous-api-ticktimer/src/api.rs @@ -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>, -} \ No newline at end of file + pub version: xous_ipc::String<512>, +} diff --git a/services/xous-ticktimer/src/main.rs b/services/xous-ticktimer/src/main.rs index b85b8a824..49490cabf 100644 --- a/services/xous-ticktimer/src/main.rs +++ b/services/xous-ticktimer/src/main.rs @@ -606,8 +606,10 @@ fn main() -> ! { let mut msg = xous::receive_message(ticktimer_server).unwrap(); log::trace!("msg: {:x?}", msg); - match num_traits::FromPrimitive::from_usize(msg.body.id()) { - Some(api::Opcode::ElapsedMs) => { + match num_traits::FromPrimitive::from_usize(msg.body.id()) + .unwrap_or(api::Opcode::InvalidCall) + { + api::Opcode::ElapsedMs => { let time = ticktimer.elapsed_ms() as i64; xous::return_scalar2( msg.sender, @@ -616,7 +618,7 @@ fn main() -> ! { ) .expect("couldn't return time request"); } - Some(api::Opcode::SleepMs) => xous::msg_blocking_scalar_unpack!(msg, ms, _, _, _, { + 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, @@ -629,7 +631,7 @@ fn main() -> ! { }), ) }), - Some(api::Opcode::RecalculateSleep) => { + 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 +645,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,17 +670,17 @@ 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(), @@ -693,7 +696,7 @@ fn main() -> ! { 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"); @@ -718,7 +721,7 @@ fn main() -> ! { mutex_entry.push_back(msg.sender); } } - 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,7 +743,7 @@ 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"); @@ -802,7 +805,7 @@ fn main() -> ! { ); } } - 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 +834,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 +862,7 @@ fn main() -> ! { ); } } - None => { + api::Opcode::InvalidCall => { error!("couldn't convert opcode"); } } From d463f9563f0bf6e88aa98060e7f39b1bc122abb0 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 20:58:51 +0800 Subject: [PATCH 04/12] xous: rename Message to MessageEnvelope This reflects the fact that up until now, the `Message` struct has merely been the envelope that surrounds the message. It does not contain any actual Message contents. Signed-off-by: Sean Cross --- xous-rs/src/arch/hosted/mod.rs | 2 +- xous-rs/src/arch/test/mod.rs | 2 +- xous-rs/src/definitions.rs | 6 +++--- xous-rs/src/definitions/messages/envelope.rs | 20 +++++++------------ xous-rs/src/syscall.rs | 21 +++++++++----------- 5 files changed, 21 insertions(+), 30 deletions(-) diff --git a/xous-rs/src/arch/hosted/mod.rs b/xous-rs/src/arch/hosted/mod.rs index 5a807e719..48790449b 100644 --- a/xous-rs/src/arch/hosted/mod.rs +++ b/xous-rs/src/arch/hosted/mod.rs @@ -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) diff --git a/xous-rs/src/arch/test/mod.rs b/xous-rs/src/arch/test/mod.rs index 1ed57149d..d8c84f947 100644 --- a/xous-rs/src/arch/test/mod.rs +++ b/xous-rs/src/arch/test/mod.rs @@ -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) diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 39b5d00c8..3867cf6a1 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -421,7 +421,7 @@ pub enum Result { NewServerID(SID, CID), // 9 - Message(MessageEnvelope), + MessageEnvelope(MessageEnvelope), // 10 ThreadID(TID), @@ -488,7 +488,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], @@ -589,7 +589,7 @@ impl Result { )), _ => return Result::Error(Error::InternalError), }; - Result::Message(MessageEnvelope { + Result::MessageEnvelope(MessageEnvelope { sender: MessageSender::from_usize(sender), body: message, }) diff --git a/xous-rs/src/definitions/messages/envelope.rs b/xous-rs/src/definitions/messages/envelope.rs index 70a7cc503..61c3eb3cc 100644 --- a/xous-rs/src/definitions/messages/envelope.rs +++ b/xous-rs/src/definitions/messages/envelope.rs @@ -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], ] } diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 26f819b87..7e799be86 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -158,7 +158,7 @@ pub enum SysCall { /// /// # Returns /// - /// * **Message**: A valid message from the queue + /// * **MessageEnvelope**: A valid message from the queue /// /// # Errors /// @@ -1570,7 +1570,7 @@ pub fn try_connect(server: SID) -> core::result::Result { /// pub fn receive_message(server: SID) -> core::result::Result { 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) @@ -1587,7 +1587,7 @@ pub fn receive_message(server: SID) -> core::result::Result core::result::Result, 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) @@ -1617,6 +1617,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), } @@ -1946,16 +1947,12 @@ pub fn reply_and_receive_next( } else { panic!("unrecognized message type") }; - let call = SysCall::ReplyAndReceiveNext( - envelope.sender, - args[0], - args[1], - args[2], - args[3], - args[4], - ); + 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::Message(envelope)) => { + Ok(crate::Result::MessageEnvelope(envelope)) => { *msg = Some(envelope); Ok(()) } From 64c88f9942267aa99c323d7641cf0dd02e5977c3 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:00:05 +0800 Subject: [PATCH 05/12] xous: add Message type This type actually contains the message contents, and will be used to return data to the caller. Signed-off-by: Sean Cross --- xous-rs/src/definitions.rs | 42 ++++++++++++++++++++----- xous-rs/src/definitions/messages/mod.rs | 13 ++++++++ xous-rs/src/syscall.rs | 6 +++- 3 files changed, 52 insertions(+), 9 deletions(-) diff --git a/xous-rs/src/definitions.rs b/xous-rs/src/definitions.rs index 3867cf6a1..138bf9d83 100644 --- a/xous-rs/src/definitions.rs +++ b/xous-rs/src/definitions.rs @@ -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), } @@ -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] } @@ -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 { + 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, } } diff --git a/xous-rs/src/definitions/messages/mod.rs b/xous-rs/src/definitions/messages/mod.rs index 53ed4897c..a3d5fa7fc 100644 --- a/xous-rs/src/definitions/messages/mod.rs +++ b/xous-rs/src/definitions/messages/mod.rs @@ -264,6 +264,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 { diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 7e799be86..6082f8343 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -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 /// @@ -511,6 +514,7 @@ pub enum SysCall { 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 From d88254b1b1cefe21e15e2d897795ed24bf07554e Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:00:35 +0800 Subject: [PATCH 06/12] xous: add reply_and_receive_next_legacy call This call is used to return values while simultaneously listening for new messages. The -legacy suffix is used to disambiguate scalar values, so we know whether to send Scalar1, Scalar2, or Scalar5 messages. Signed-off-by: Sean Cross --- xous-rs/src/definitions/messages/mod.rs | 11 +++++++- xous-rs/src/syscall.rs | 34 +++++++++++++++++++++---- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/xous-rs/src/definitions/messages/mod.rs b/xous-rs/src/definitions/messages/mod.rs index a3d5fa7fc..714b7549c 100644 --- a/xous-rs/src/definitions/messages/mod.rs +++ b/xous-rs/src/definitions/messages/mod.rs @@ -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, @@ -239,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, diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 6082f8343..01e0f9ec9 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -850,15 +850,15 @@ impl SysCall { 0, 0, ], - SysCall::ReplyAndReceiveNext(sender, result, arg1, arg2, arg3, arg4) => [ - SysCallNumber::ReturnMemory as usize, + SysCall::ReplyAndReceiveNext(sender, arg0, arg1, arg2, arg3, arg4, return_type) => [ + SysCallNumber::ReplyAndReceiveNext as usize, sender.to_usize(), - *result, + *arg0, *arg1, *arg2, *arg3, *arg4, - 0, + *return_type, ], SysCall::CreateThread(init) => { @@ -1086,7 +1086,7 @@ impl SysCall { MemorySize::new(a5), ), SysCallNumber::ReplyAndReceiveNext => { - SysCall::ReplyAndReceiveNext(MessageSender::from_usize(a1), a2, a3, a4, a5, a6) + 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)?) @@ -1936,6 +1936,30 @@ pub fn reply_and_receive_next( server: SID, msg: &mut Option, ) -> 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 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, + 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 From 911ddb60fcacac62751b5bd2c64631d3487b935d Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:01:27 +0800 Subject: [PATCH 07/12] kernel: debug: fix klog on baremetal klog() refers to an outdated `.uart` struct, which has since been renamed to `.serial`. Signed-off-by: Sean Cross --- kernel/src/debug/shell.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/kernel/src/debug/shell.rs b/kernel/src/debug/shell.rs index 86408ad97..76a7e3947 100644 --- a/kernel/src/debug/shell.rs +++ b/kernel/src/debug/shell.rs @@ -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; } From 46f340324def1f8f625a444b53cb0bd12de6976b Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:02:57 +0800 Subject: [PATCH 08/12] kernel: rename `Message` -> `MessageEnvelope` This syncs with the latest changes to `xous-rs`. Signed-off-by: Sean Cross --- kernel/src/syscall.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 226d68407..61b30c9bf 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -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) }; @@ -639,7 +639,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 { From ab0c7d3b32a28bed58836317f2203d90e4eb80dc Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:03:39 +0800 Subject: [PATCH 09/12] kernel: server: check buf is some when returning mem Signed-off-by: Sean Cross --- kernel/src/server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kernel/src/server.rs b/kernel/src/server.rs index 285cb1889..f62220e10 100644 --- a/kernel/src/server.rs +++ b/kernel/src/server.rs @@ -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); From 3218bde2b46eda44b6b81d643cfe2e975669f3ca Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:04:01 +0800 Subject: [PATCH 10/12] kernel: implement reply_and_receive_next Implement `ReplyAndReceiveNext` as a syscall. This will reply to a message, pull the next message out of the queue, and then re-queue the server to run. This should make servers much more responsive. This patch has been tested on both hosted and native modes. Signed-off-by: Sean Cross --- kernel/src/syscall.rs | 144 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 61b30c9bf..e944b17ad 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -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!( @@ -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)?; From 0e75b8e4795c1905e4733c985d60e31dc6524c2f Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:05:26 +0800 Subject: [PATCH 11/12] test-spawn: rename `Message` to `MessageEnvelope` Signed-off-by: Sean Cross --- services/test-spawn/spawn/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/test-spawn/spawn/src/main.rs b/services/test-spawn/spawn/src/main.rs index 9f7703cc9..dfeac1627 100644 --- a/services/test-spawn/spawn/src/main.rs +++ b/services/test-spawn/spawn/src/main.rs @@ -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() { From e2bf710939742ebed2d680164ab194a88455cab7 Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 29 Dec 2022 21:06:51 +0800 Subject: [PATCH 12/12] services: xous-ticktimer: use reply_and_receive_next() Convert the ticktimer server to use the new reply_and_receive_next_legacy() call. This is an example of how to use this API for future projects. Signed-off-by: Sean Cross --- services/xous-ticktimer/src/main.rs | 119 ++++++++++++++++++---------- 1 file changed, 75 insertions(+), 44 deletions(-) diff --git a/services/xous-ticktimer/src/main.rs b/services/xous-ticktimer/src/main.rs index 49490cabf..db2d6a7e7 100644 --- a/services/xous-ticktimer/src/main.rs +++ b/services/xous-ticktimer/src/main.rs @@ -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,39 +599,65 @@ fn main() -> ! { let mut mutex_hash: HashMap, HashMap>> = 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()) .unwrap_or(api::Opcode::InvalidCall) { 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"); + 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; + } + } + 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::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, - }), - ) - }), api::Opcode::RecalculateSleep => { // let timeout_queue = timeout_heap.entry(msg.sender.pid()).or_default(); if let Some(args) = msg.body.scalar_message() { @@ -686,28 +713,24 @@ fn main() -> ! { 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(); } } 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; } @@ -719,6 +742,12 @@ 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"); } } api::Opcode::UnlockMutex => { @@ -745,11 +774,7 @@ fn main() -> ! { } 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; @@ -769,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; } } @@ -798,7 +825,11 @@ 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"