diff --git a/kernel/src/arch/hosted/process.rs b/kernel/src/arch/hosted/process.rs index d2ba45a15..5f458c4c7 100644 --- a/kernel/src/arch/hosted/process.rs +++ b/kernel/src/arch/hosted/process.rs @@ -272,6 +272,10 @@ impl Process { }) } + pub fn thread_exists(&self, _tid: TID) -> bool { + false + } + pub fn set_thread_result(&mut self, tid: TID, result: xous_kernel::Result) { assert!(tid > 0); PROCESS_TABLE.with(|pt| { diff --git a/kernel/src/arch/riscv/process.rs b/kernel/src/arch/riscv/process.rs index cba6d5cfa..40de6608f 100644 --- a/kernel/src/arch/riscv/process.rs +++ b/kernel/src/arch/riscv/process.rs @@ -35,13 +35,16 @@ pub const EXIT_THREAD: usize = 0xff80_3000; // Therefore, the first Logical Thread ID is 1, which maps // to Hardware Thread ID 2, which is Thread Context Index 1. // -// +----------------+---------------+------------------+ -// | Logical Thread | Context Index | Hardware Thread | -// +================+===============+==================+ -// | ISR Context | 0 | 1 | -// | 1 | 1 | 2 | -// | 2 | 2 | 3 | +// +-----------------+-----------------+-----------------+ +// | Thread ID | Context Index | Hardware Thread | +// +=================+=================+=================+ +// | ISR Context | 0 | 1 | +// | 1 | 1 | 2 | +// | 2 | 2 | 3 | +// ProcessImpl occupies a multiple of pages mapped to virtual address `0xff80_1000`. +// Each thread is 128 bytes (32 4-byte registers). The first "thread" does not exist, +// and instead is any bookkeeping information related to the process. #[derive(Debug, Copy, Clone)] #[repr(C)] struct ProcessImpl { @@ -182,6 +185,10 @@ impl Process { process.hardware_thread - 1 } + pub fn thread_exists(&self, tid: TID) -> bool { + self.thread(tid).sepc != 0 + } + /// Set the current thread number. pub fn set_thread(&mut self, thread: TID) -> Result<(), xous_kernel::Error> { let mut process = unsafe { &mut *PROCESS }; @@ -205,15 +212,15 @@ impl Process { &mut process.threads[thread] } - // pub fn thread(&self, thread: TID) -> &Thread { - // let process = unsafe { &mut *PROCESS }; - // assert!( - // thread <= process.threads.len(), - // "attempt to retrieve an invalid thread {}", - // thread - // ); - // &process.threads[thread] - // } + pub fn thread(&self, thread: TID) -> &Thread { + let process = unsafe { &mut *PROCESS }; + assert!( + thread <= process.threads.len(), + "attempt to retrieve an invalid thread {}", + thread + ); + &process.threads[thread] + } pub fn find_free_thread(&self) -> Option { let process = unsafe { &mut *PROCESS }; @@ -470,6 +477,22 @@ impl Process { process_table.table[pid_idx] = false; Ok(()) } + + pub fn find_thread(&self, op: F) -> Option<(TID, &mut Thread)> + where + F: Fn(TID, &Thread) -> bool, + { + let process = unsafe { &mut *PROCESS }; + for (idx, thread) in process.threads.iter_mut().enumerate() { + if thread.sepc == 0 { + continue; + } + if op(idx, thread) { + return Some((idx, thread)); + } + } + None + } } impl Thread { @@ -477,6 +500,15 @@ impl Thread { pub fn stack_pointer(&self) -> usize { self.registers[1] } + + pub fn a0(&self) -> usize { + self.registers[9] + } + + pub fn a1(&self) -> usize { + self.registers[10] + } + } pub fn set_current_pid(pid: PID) { @@ -499,31 +531,3 @@ pub fn current_pid() -> PID { pub fn current_tid() -> TID { unsafe { ((*PROCESS).hardware_thread) - 1 } } - -// pub struct ProcessHandle<'a> { -// process: &'a mut Process, -// } - -// /// Wraps the MemoryManager in a safe mutex. Because of this, accesses -// /// to the Memory Manager should only be made during interrupt contexts. -// impl<'a> ProcessHandle<'a> { -// /// Get the singleton Process. -// pub fn get() -> ProcessHandle<'a> { -// ProcessHandle { -// process: unsafe { &mut *PROCESS }, -// } -// } -// } - -// use core::ops::{Deref, DerefMut}; -// impl Deref for ProcessHandle<'_> { -// type Target = Process; -// fn deref(&self) -> &Process { -// &*self.process -// } -// } -// impl DerefMut for ProcessHandle<'_> { -// fn deref_mut(&mut self) -> &mut Process { -// &mut *self.process -// } -// } diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 703ce5f7f..4ede57fe6 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -1415,28 +1415,35 @@ impl SystemServices { /// /// * **ThreadNotAvailable**: The thread does not exist in this process #[cfg(baremetal)] - pub fn destroy_thread(&mut self, pid: PID, thread: TID) -> Result { + pub fn destroy_thread(&mut self, pid: PID, tid: TID) -> Result { let current_pid = self.current_pid(); assert_eq!(pid, current_pid); - let mut process = self.get_process_mut(pid)?; - process.activate()?; + let mut waiting_threads = match self.get_process_mut(pid)?.state { + ProcessState::Running(x) => x, + state => panic!("Process was in an invalid state: {:?}", state), + }; // Destroy the thread at a hardware level let mut arch_process = crate::arch::process::Process::current(); - let return_value = arch_process.destroy_thread(thread).unwrap(); + let return_value = arch_process.destroy_thread(tid).unwrap(); // If there's another thread waiting on the return value of this thread, // wake it up and set its return value. + if let Some((waiting_tid, _thread)) = arch_process.find_thread(|waiting_tid, thr| { + (waiting_threads & (1 << waiting_tid)) == 0 // Thread is waiting (i.e. not ready to run) + && thr.a0() == (xous_kernel::SysCallNumber::JoinThread as usize) // Thread called `JoinThread` + && thr.a1() == (tid as usize) // It is waiting on our thread + }) { + // Wake up the thread + self.set_thread_result(pid, waiting_tid, xous_kernel::Result::Scalar1(return_value))?; + waiting_threads |= 1 << waiting_tid; + } // Mark this process as `Ready`. // We can do this because the current thread has just exited. Note that if there // are no threads available, this is an error. - - process.state = match process.state { - ProcessState::Running(x) if x != 0 => ProcessState::Ready(x), - _ => panic!("Process was in an invalid state: {:?}", process.state), - }; + self.get_process_mut(pid)?.state = ProcessState::Ready(waiting_threads); // Switch to the next available TID. This moves the process back to a `Running` state. self.switch_to_thread(pid, None)?; @@ -1444,6 +1451,36 @@ impl SystemServices { Ok(return_value) } + /// Park this thread if the target thread is currently running. Otherwise, + /// return the value of the given thread. + pub fn join_thread( + &mut self, + pid: PID, + tid: TID, + join_tid: TID, + ) -> Result { + let current_pid = self.current_pid(); + assert_eq!(pid, current_pid); + + // We cannot wait on ourselves. + if tid == join_tid { + Err(xous_kernel::Error::ThreadNotAvailable)? + } + + // If the target thread exists, put this thread to sleep. + let arch_process = crate::arch::process::Process::current(); + if arch_process.thread_exists(join_tid) { + // The target thread exists -- put this thread to sleep + let ppid = self.get_process(pid).unwrap().ppid; + self.activate_process_thread(tid, ppid, 0, false) + .map(|_| Ok(xous_kernel::Result::ResumeProcess)) + .unwrap_or(Err(xous_kernel::Error::ProcessNotFound)) + } else { + // The thread does not exist -- continue execution + Err(xous_kernel::Error::ThreadNotAvailable) + } + } + /// Allocate a new server ID for this process and return the address. If the /// server table is full, or if there is not enough memory to map the server queue, /// return an error. diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 137cf8635..a8eb9a23a 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -850,6 +850,12 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR SysCall::DestroyServer(sid) => SystemServices::with_mut(|ss| { ss.destroy_server(pid, sid).and(Ok(xous_kernel::Result::Ok)) }), + SysCall::JoinThread(other_tid) => { + SystemServices::with_mut(|ss| ss.join_thread(pid, tid, other_tid)).map(|ret| { + unsafe { SWITCHTO_CALLER = None }; + ret + }) + } _ => Err(xous_kernel::Error::UnhandledSyscall), } }