From 81351bed32b54ca562b3bb115ffe0ef2f68cea0c Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 5 Jan 2023 11:53:59 +0800 Subject: [PATCH 1/2] xous: syscall: support `call.memory()` for ReplyAndReceiveNext Much of the hosted machinery requires the ability to access memory on syscalls. This feature was overlooked in the previous implementation of ReplyAndReceiveNext, which caused it to not properly return memory. Implement the ability to call `.memory()` on ReplyAndReceiveNext messages. Note that this requires the use of a sentinal value in the previously-unused `valid` field. Signed-off-by: Sean Cross --- xous-rs/src/syscall.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/xous-rs/src/syscall.rs b/xous-rs/src/syscall.rs index 01e0f9ec9..7decd8b82 100644 --- a/xous-rs/src/syscall.rs +++ b/xous-rs/src/syscall.rs @@ -514,7 +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 */ + usize, /* how many args are valid (BlockingScalar) or usize::MAX (MemoryMessge) */ ), /// This syscall does not exist. It captures all possible @@ -1188,6 +1188,7 @@ impl SysCall { ) } SysCall::ReturnMemory(_, _, _, _) => true, + SysCall::ReplyAndReceiveNext(_, _, _, _, _, _, usize::MAX) => true, _ => false, } } @@ -1224,7 +1225,10 @@ impl SysCall { /// Returns `true` if the associated syscall is returning memory pub fn is_return_memory(&self) -> bool { - matches!(self, SysCall::ReturnMemory(_, _, _, _)) + matches!( + self, + SysCall::ReturnMemory(..) | SysCall::ReplyAndReceiveNext(_, _, _, _, _, _, usize::MAX) + ) } /// If the syscall has memory attached to it, return the memory @@ -1237,26 +1241,33 @@ impl SysCall { _ => None, }, SysCall::ReturnMemory(_, range, _, _) => Some(*range), + SysCall::ReplyAndReceiveNext(_, _, a1, a2, _, _, usize::MAX) => unsafe { + MemoryRange::new(*a1, *a2).ok() + }, _ => None, } } - /// If the syscall has memory attached to it, return the memory, mutably + /// If the syscall has memory attached to it, replace the memory. /// /// # Safety /// - /// This function is only safe to call to fixup the pointer. It should - /// not be used for any other purpose. - pub unsafe fn memory_mut(&mut self) -> Option<&mut MemoryRange> { + /// This function is only safe to call to fixup the pointer, particularly + /// when running in hosted mode. It should not be used for any other purpose. + pub unsafe fn replace_memory(&mut self, new: MemoryRange) { match self { SysCall::TrySendMessage(_, msg) | SysCall::SendMessage(_, msg) => match msg { Message::Move(memory_message) | Message::Borrow(memory_message) - | Message::MutableBorrow(memory_message) => Some(&mut memory_message.buf), - _ => None, + | Message::MutableBorrow(memory_message) => memory_message.buf = new, + _ => (), }, - SysCall::ReturnMemory(_, range, _, _) => Some(range), - _ => None, + SysCall::ReturnMemory(_, range, _, _) => *range = new, + SysCall::ReplyAndReceiveNext(_, _, a1, a2, _, _, usize::MAX) => { + *a1 = new.addr.get(); + *a2 = new.size.get(); + } + _ => (), } } @@ -1958,7 +1969,7 @@ pub fn reply_and_receive_next_legacy( msg: &mut Option, return_type: &mut usize, ) -> core::result::Result<(), crate::Error> { - let rt = *return_type; + let mut rt = *return_type; *return_type = 0; if let Some(envelope) = msg.take() { // If the message inside is nonblocking, then there's nothing to return. @@ -1969,6 +1980,8 @@ pub fn reply_and_receive_next_legacy( } let args = if let Some(mem) = envelope.body.memory_message() { + // Allow hosted mode to detect this is a memory message by giving a sentinal value here + rt = usize::MAX; mem.to_usize() } else if let Some(scalar) = envelope.body.scalar_message() { scalar.to_usize() From 3593d715c1fa11201d286740c9b146526fdd620a Mon Sep 17 00:00:00 2001 From: Sean Cross Date: Thu, 5 Jan 2023 11:56:15 +0800 Subject: [PATCH 2/2] kernel: fix memorymessages with ReplyAndReceiveNext Fix a segfault that occurred when using ReplyAndReceiveNext on hosted mode. This now properly passes memory messages back to the client. Signed-off-by: Sean Cross --- kernel/src/arch/hosted/mod.rs | 136 +++++----------------------------- kernel/src/syscall.rs | 7 +- 2 files changed, 22 insertions(+), 121 deletions(-) diff --git a/kernel/src/arch/hosted/mod.rs b/kernel/src/arch/hosted/mod.rs index 3a52a71ee..82ebe4e19 100644 --- a/kernel/src/arch/hosted/mod.rs +++ b/kernel/src/arch/hosted/mod.rs @@ -67,12 +67,15 @@ static LOCAL_RNG_STATE: AtomicU64 = AtomicU64::new(2); #[cfg(not(test))] fn generate_pid_key() -> [u8; 16] { - use rand_chacha::ChaCha8Rng; - use rand_chacha::rand_core::SeedableRng; use rand_chacha::rand_core::RngCore; + use rand_chacha::rand_core::SeedableRng; + use rand_chacha::ChaCha8Rng; let mut process_key = [0u8; 16]; - let mut rng = ChaCha8Rng::seed_from_u64(LOCAL_RNG_STATE.load(Ordering::SeqCst) + xous_kernel::TESTING_RNG_SEED.load(core::sync::atomic::Ordering::SeqCst)); + let mut rng = ChaCha8Rng::seed_from_u64( + LOCAL_RNG_STATE.load(Ordering::SeqCst) + + xous_kernel::TESTING_RNG_SEED.load(core::sync::atomic::Ordering::SeqCst), + ); for b in process_key.iter_mut() { *b = rng.next_u32() as u8; } @@ -150,7 +153,7 @@ fn handle_connection( } }; - if let Some(mem) = unsafe { call.memory_mut() } { + if let Some(mem) = call.memory() { let mut data = vec![0u8; mem.len()]; if conn.read_exact(&mut data).is_err() { return; @@ -164,12 +167,14 @@ fn handle_connection( sliced_data.len(), mem.len() ); - *mem = unsafe { - xous_kernel::MemoryRange::new( - Box::into_raw(sliced_data) as *mut u8 as usize, - mem.len(), + unsafe { + call.replace_memory( + xous_kernel::MemoryRange::new( + Box::into_raw(sliced_data) as *mut u8 as usize, + mem.len(), + ) + .unwrap(), ) - .unwrap() }; } @@ -198,118 +203,10 @@ fn handle_connection( // WARNING: This functionality is unimplemented right now return; } - std::thread::park_timeout(std::time::Duration::from_secs(1)); + std::thread::park_timeout(std::time::Duration::from_millis(100)); }) .unwrap(); - // for msg in receiver { - // match msg { - // ServerMessage::Exit => { - // #[cfg(not(test))] - // eprintln!("KERNEL({}): Received ServerMessage::Exit", pid); - // break; - // } - // ServerMessage::ServerPacket(pkt) => { - // let thread_id = pkt[0]; - // let call = xous_kernel::SysCall::from_args( - // pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], pkt[8], - // ); - // match call { - // Err(e) => { - // eprintln!("KERNEL({}): Received invalid syscall: {:?}", pid, e); - // eprintln!( - // "Raw packet: {:08x} {} {} {} {} {} {} {}", - // pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7] - // ); - // } - // Ok(call) => chn - // .send(ThreadMessage::SysCall(pid, thread_id, call)) - // .expect("couldn't make syscall"), - // } - // } - // ServerMessage::ServerPacketWithData(pkt, data) => { - // let thread_id = pkt[0]; - // let call = xous_kernel::SysCall::from_args( - // pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], pkt[8], - // ); - // match call { - // Err(e) => { - // eprintln!("KERNEL({}): Received invalid syscall: {:?}", pid, e); - // eprintln!( - // "Raw packet: {:08x} {} {} {} {} {} {} {}", - // pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7] - // ); - // } - // Ok(mut call) => { - // // eprintln!( - // // "Received packet: {:08x} {} {} {} {} {} {} {}: {:?}", - // // pkt[0], pkt[1], pkt[2], pkt[3], pkt[4], pkt[5], pkt[6], pkt[7], call - // // ); - // match call { - // SysCall::SendMessage(ref _cid, ref mut envelope) - // | SysCall::TrySendMessage(ref _cid, ref mut envelope) => { - // match envelope { - // xous_kernel::Message::MutableBorrow(msg) - // | xous_kernel::Message::Borrow(msg) - // | xous_kernel::Message::Move(msg) => { - // // Update the address pointer. This will get turned back into a - // // usable pointer by casting it back into a &[T] on the other - // // side. This is just a pointer to the start of data - // // as well as the index into the data it points at. The lengths - // // should still be equal once we reconstitute the data in the - // // other process. - // // ::debug_here::debug_here!(); - // let sliced_data = data.into_boxed_slice(); - // assert_eq!( - // sliced_data.len(), - // msg.buf.len(), - // "deconstructed data {} != message buf length {}", - // sliced_data.len(), - // msg.buf.len() - // ); - // msg.buf = unsafe { - // xous_kernel::MemoryRange::new( - // Box::into_raw(sliced_data) as *mut u8 as usize, - // msg.buf.len(), - // ) - // .unwrap() - // }; - // } - // xous_kernel::Message::Scalar(_) - // | xous_kernel::Message::BlockingScalar(_) => (), - // } - // } - // SysCall::ReturnMemory( - // ref _sender, - // ref mut buf, - // ref _offset, - // ref _valid, - // ) => { - // let sliced_data = data.into_boxed_slice(); - // assert_eq!( - // sliced_data.len(), - // buf.len(), - // "deconstructed data {} != message buf length {}", - // sliced_data.len(), - // buf.len() - // ); - // *buf = unsafe { - // xous_kernel::MemoryRange::new( - // Box::into_raw(sliced_data) as *mut u8 as usize, - // buf.len(), - // ) - // .unwrap() - // }; - // } - // _ => panic!("unsupported message type"), - // } - // chn.send(ThreadMessage::SysCall(pid, thread_id, call)) - // .expect("couldn't make syscall"); - // } - // } - // } - // } - // } conn_thread.join().unwrap(); #[cfg(not(test))] eprintln!( @@ -487,7 +384,8 @@ pub fn idle() -> bool { }; let process_1 = SystemServices::with_mut(|ss| ss.create_process(pid1_init)).unwrap(); assert_eq!(process_1.pid().get(), 1); - let _tid1 = SystemServices::with_mut(|ss| ss.create_thread(process_1.pid(), ThreadInit {})).unwrap(); + let _tid1 = + SystemServices::with_mut(|ss| ss.create_thread(process_1.pid(), ThreadInit {})).unwrap(); let listen_addr = env::var("XOUS_LISTEN_ADDR") .map(|s| { diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index e944b17ad..cfc7e5a66 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -681,7 +681,7 @@ fn reply_and_receive_next( #[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 + let src_virt = arg1 as _; // Return the memory to the calling process ss.return_memory(src_virt, pid, tid, client_addr.get() as _, len.get())?; @@ -689,7 +689,10 @@ fn reply_and_receive_next( MessageResponse { pid, tid, - result: xous_kernel::Result::MemoryReturned(MemorySize::new(arg3), MemorySize::new(arg4)), + result: xous_kernel::Result::MemoryReturned( + MemorySize::new(arg3), + MemorySize::new(arg4), + ), } } WaitingMessage::MovedMemory => {