diff --git a/kernel/src/arch/riscv/process.rs b/kernel/src/arch/riscv/process.rs index c06d2c4bb..4507499a4 100644 --- a/kernel/src/arch/riscv/process.rs +++ b/kernel/src/arch/riscv/process.rs @@ -2,7 +2,7 @@ use core::mem; static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl; pub const MAX_THREAD: TID = 31; pub const INITIAL_TID: TID = 1; -pub const IRQ_TID: usize = 0; +pub const IRQ_TID: TID = 0; use crate::arch::mem::PAGE_SIZE; use crate::services::ProcessInner; use xous::{ProcessInit, ThreadInit, PID, TID}; @@ -18,14 +18,36 @@ pub const RETURN_FROM_ISR: usize = 0xff80_2000; /// This is the address a thread will return to when it exits. const EXIT_THREAD: usize = 0xff80_3000; +// Thread IDs have three possible meaning: +// Logical Thread ID: What the user sees +// Thread Context Index: An index into the thread slice +// Hardware Thread ID: The index that the ISR uses +// +// The Hardware Thread ID is always equal to the Thread Context +// Index, minus one. For example, the default thread ID is +// Hardware Thread ID 1 is Thread Context Index 0. +// The Logical Thread ID is equal to the Hardware Thread ID +// plus one again. This is because the ISR context is Thread +// Context Index 0. +// 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 | + #[derive(Debug, Copy, Clone)] #[repr(C)] struct ProcessImpl { /// Used by the interrupt handler to calculate offsets scratch: usize, - /// The currently-active thread for this process - current_thread: usize, + /// The currently-active thread for this process. This must + /// be the 2nd item, because the ISR directly writes this value. + hardware_thread: usize, /// Global parameters used by the operating system pub inner: ProcessInner, @@ -46,7 +68,7 @@ struct ProcessTable { current: PID, /// The number of processes that exist - total: usize, + // total: usize, /// The actual table contents table: [bool; MAX_PROCESS_COUNT], @@ -54,7 +76,7 @@ struct ProcessTable { static mut PROCESS_TABLE: ProcessTable = ProcessTable { current: unsafe { PID::new_unchecked(1) }, - total: 0, + // total: 0, table: [false; MAX_PROCESS_COUNT], }; @@ -144,18 +166,19 @@ impl Process { pub fn current_thread_mut(&mut self) -> &mut Thread { let process = unsafe { &mut *PROCESS }; - assert!(process.current_thread != 0, "thread number was 0"); - &mut process.threads[process.current_thread - 1] + assert!(process.hardware_thread != 0, "thread number was 0"); + &mut process.threads[process.hardware_thread - 1] } pub fn current_thread(&self) -> &Thread { let process = unsafe { &mut *PROCESS }; - self.thread(process.current_thread) + &mut process.threads[process.hardware_thread - 1] + // self.thread(process.hardware_thread - 1) } pub fn current_tid(&self) -> TID { let process = unsafe { &*PROCESS }; - process.current_thread + process.hardware_thread - 1 } /// Set the current thread number. @@ -166,7 +189,7 @@ impl Process { "attempt to switch to an invalid thread {}", thread ); - process.current_thread = thread + 1; + process.hardware_thread = thread + 1; Ok(()) } @@ -177,18 +200,18 @@ impl Process { "attempt to retrieve an invalid thread {}", thread ); - &mut process.threads[thread - 1] + &mut process.threads[thread] } - pub fn thread(&self, thread: TID) -> &Thread { - let process = unsafe { &mut *PROCESS }; - assert!( - thread > 0 && thread <= process.threads.len(), - "attempt to retrieve an invalid thread {}", - thread - ); - &process.threads[thread - 1] - } + // pub fn thread(&self, thread: TID) -> &Thread { + // let process = unsafe { &mut *PROCESS }; + // assert!( + // thread > 0 && 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 }; @@ -225,7 +248,7 @@ impl Process { mem::size_of::(), ); assert!( - tid + 1 < process.threads.len(), + tid - 1 < process.threads.len(), "tried to init a thread that's out of range" ); assert!( @@ -248,7 +271,7 @@ impl Process { // By convention, thread 0 is the trap thread. Therefore, thread 1 is // the first default thread. There is an offset of 1 due to how the // interrupt handler functions. - process.current_thread = tid + 1; + process.hardware_thread = tid + 1; // Reset the thread state, since it's possibly uninitialized memory for thread in process.threads.iter_mut() { @@ -306,50 +329,50 @@ impl Process { } pub fn print_thread(&self) { - let thread = self.current_thread(); + let _thread = self.current_thread(); println!( "PC:{:08x} SP:{:08x} RA:{:08x}", - thread.sepc, thread.registers[1], thread.registers[0] + _thread.sepc, _thread.registers[1], _thread.registers[0] ); println!( "GP:{:08x} TP:{:08x}", - thread.registers[2], thread.registers[3] + _thread.registers[2], _thread.registers[3] ); println!( "T0:{:08x} T1:{:08x} T2:{:08x}", - thread.registers[4], thread.registers[5], thread.registers[6] + _thread.registers[4], _thread.registers[5], _thread.registers[6] ); println!( "T3:{:08x} T4:{:08x} T5:{:08x} T6:{:08x}", - thread.registers[27], thread.registers[28], thread.registers[29], thread.registers[30] + _thread.registers[27], _thread.registers[28], _thread.registers[29], _thread.registers[30] ); println!( "S0:{:08x} S1:{:08x} S2:{:08x} S3:{:08x}", - thread.registers[7], thread.registers[8], thread.registers[17], thread.registers[18] + _thread.registers[7], _thread.registers[8], _thread.registers[17], _thread.registers[18] ); println!( "S4:{:08x} S5:{:08x} S6:{:08x} S7:{:08x}", - thread.registers[19], thread.registers[20], thread.registers[21], thread.registers[22] + _thread.registers[19], _thread.registers[20], _thread.registers[21], _thread.registers[22] ); println!( "S8:{:08x} S9:{:08x} S10:{:08x} S11:{:08x}", - thread.registers[23], thread.registers[24], thread.registers[25], thread.registers[26] + _thread.registers[23], _thread.registers[24], _thread.registers[25], _thread.registers[26] ); println!( "A0:{:08x} A1:{:08x} A2:{:08x} A3:{:08x}", - thread.registers[9], thread.registers[10], thread.registers[11], thread.registers[12] + _thread.registers[9], _thread.registers[10], _thread.registers[11], _thread.registers[12] ); println!( "A4:{:08x} A5:{:08x} A6:{:08x} A7:{:08x}", - thread.registers[13], thread.registers[14], thread.registers[15], thread.registers[16] + _thread.registers[13], _thread.registers[14], _thread.registers[15], _thread.registers[16] ); } - pub fn create(pid: PID, init_data: ProcessInit) -> PID { + pub fn create(_pid: PID, _init_data: ProcessInit) -> PID { todo!(); } - pub fn destroy(pid: PID) -> Result<(), xous::Error> { + pub fn destroy(_pid: PID) -> Result<(), xous::Error> { todo!(); // let mut process_table = unsafe { &mut *PROCESS }; // let pid_idx = pid.get() as usize - 1; @@ -371,7 +394,6 @@ impl Thread { } pub fn set_current_pid(pid: PID) { - println!("ARCH: Setting current PID to {}", pid); let pid_idx = (pid.get() - 1) as usize; unsafe { let mut pt = &mut PROCESS_TABLE; @@ -389,7 +411,7 @@ pub fn current_pid() -> PID { } pub fn current_tid() -> TID { - unsafe { (*PROCESS).current_thread } + unsafe { ((*PROCESS).hardware_thread) + 1 } } // pub struct ProcessHandle<'a> { diff --git a/kernel/src/main.rs b/kernel/src/main.rs index f2cb174e1..a97402b99 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -140,11 +140,11 @@ pub extern "C" fn kmain() { match pid { Some(pid) => { - // println!("Attempting to switch to PID {}", pid); + println!("Attempting to switch to PID {}", pid); xous::rsyscall(xous::SysCall::SwitchTo(pid, 0)).expect("couldn't switch to pid"); } None => { - // println!("No runnable tasks found. Entering idle state..."); + println!("No runnable tasks found. Entering idle state..."); // Special case for testing: idle can return `false` to indicate exit if !arch::idle() { return; diff --git a/kernel/src/services.rs b/kernel/src/services.rs index ac5ddcbfa..494f3387f 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -487,7 +487,9 @@ impl SystemServices { ProcessState::Ready(x) | ProcessState::Running(x) => x, ProcessState::Sleeping => 0, ProcessState::Free => panic!("process was not allocated"), - ProcessState::Setup(_) | ProcessState::Allocated => panic!("process hasn't been set up yet"), + ProcessState::Setup(_) | ProcessState::Allocated => { + panic!("process hasn't been set up yet") + } }; process.state = ProcessState::Running(available_threads); process.previous_thread = process.current_thread; @@ -763,14 +765,17 @@ impl SystemServices { /// process is in the Setup state, set it up and then resume. pub fn activate_process_thread( &mut self, + previous_tid: TID, new_pid: PID, mut new_tid: TID, can_resume: bool, ) -> Result { // println!("Activating PID {}, context {}", new_pid, new_tid); let previous_pid = self.current_pid(); - // let previous_tid = self.current_thread(previous_pid); - println!("KERNEL({}): Activating process {} thread {}", previous_pid, new_pid, new_tid); + println!( + "KERNEL({}): Activating process {} thread {}", + previous_pid, new_pid, new_tid + ); // Save state if the PID has changed. This will activate the new memory // space. @@ -779,7 +784,10 @@ impl SystemServices { // Ensure the new process can be run. match new.state { - ProcessState::Free => return Err(xous::Error::ProcessNotFound), + ProcessState::Free => { + println!("PID {} was free", new_pid); + return Err(xous::Error::ProcessNotFound); + } ProcessState::Setup(_) | ProcessState::Allocated => new_tid = INITIAL_TID, ProcessState::Running(x) | ProcessState::Ready(x) => { // If no new context is specified, take the previous @@ -810,13 +818,16 @@ impl SystemServices { // println!(" -- picked context {}", new_context); } else if x & (1 << new_tid) == 0 { println!( - "context is {:?}, which is not valid for new context {}", + "thread is {:?}, which is not valid for new thread {}", new.state, new_tid ); return Err(xous::Error::ProcessNotFound); } } - ProcessState::Sleeping => return Err(xous::Error::ProcessNotFound), + ProcessState::Sleeping => { + println!("PID {} was sleeping", new_pid); + return Err(xous::Error::ProcessNotFound); + } } // Perform the actual switch to the new memory space. From this @@ -853,11 +864,11 @@ impl SystemServices { // we will either need to Sleep this process, or mark it as // being Ready to run. ProcessState::Running(x) if x == 0 => { - // if can_resume { - // ProcessState::Ready(1 << previous_tid) - // } else { - ProcessState::Sleeping - // } + if can_resume { + ProcessState::Ready(1 << previous_tid) + } else { + ProcessState::Sleeping + } } // Otherwise, there are additional threads that can be run. // Convert the previous process into "Ready", and include the @@ -1213,9 +1224,7 @@ impl SystemServices { /// * **ThreadNotAvailable**: The process has used all of its context /// slots. pub fn create_thread(&mut self, pid: PID, thread_init: ThreadInit) -> Result { - println!("Creating thread for PID {}", pid); let mut process = self.get_process_mut(pid)?; - println!("Process PID for {}: {}", pid, process.pid); process.activate()?; let mut arch_process = crate::arch::process::Process::current(); @@ -1225,7 +1234,7 @@ impl SystemServices { arch_process.setup_thread(new_tid, thread_init)?; - println!("KERNEL({}): Created new thread {}", pid, new_tid); + // println!("KERNEL({}): Created new thread {}", pid, new_tid); // Queue the thread to run process.state = match process.state { diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 1cf7a2735..ac3f360b8 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -132,7 +132,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes if blocking && cfg!(baremetal) { // println!("Activating Server context and switching away from Client"); - ss.activate_process_thread(server_pid, server_tid, !blocking) + ss.activate_process_thread(thread, server_pid, server_tid, !blocking) .map(|_| Ok(xous::Result::Message(envelope))) .unwrap_or(Err(xous::Error::ProcessNotFound)) } else if blocking && !cfg!(baremetal) { @@ -166,7 +166,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes let process = ss.get_process(pid).expect("Can't get current process"); let ppid = process.ppid; unsafe { SWITCHTO_CALLER = None }; - ss.activate_process_thread(ppid, 0, !blocking) + ss.activate_process_thread(thread, ppid, 0, !blocking) .map(|_| Ok(xous::Result::ResumeProcess)) .unwrap_or(Err(xous::Error::ProcessNotFound)) } else { @@ -295,7 +295,7 @@ fn receive_message(pid: PID, tid: TID, sid: SID) -> SysCallResult { unsafe { SWITCHTO_CALLER = None }; let ppid = ss.get_process(pid).expect("Can't get current process").ppid; // TODO: Advance thread - ss.activate_process_thread(ppid, 0, false) + ss.activate_process_thread(tid, ppid, 0, false) .map(|_| Ok(xous::Result::ResumeProcess)) .unwrap_or(Err(xous::Error::ProcessNotFound)) } @@ -450,7 +450,7 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult { ); SWITCHTO_CALLER = Some((pid, tid)); } - ss.activate_process_thread(new_pid, new_context, true) + ss.activate_process_thread(tid, new_pid, new_context, true) .map(|_ctx| { // println!("switchto ({}, {})", pid, _ctx); xous::Result::ResumeProcess @@ -473,7 +473,7 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult { }; SystemServices::with_mut(|ss| { // TODO: Advance thread - ss.activate_process_thread(parent_pid, parent_ctx, true) + ss.activate_process_thread(tid, parent_pid, parent_ctx, true) .map(|_| Ok(xous::Result::ResumeProcess)) .unwrap_or(Err(xous::Error::ProcessNotFound)) }) @@ -496,7 +496,7 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult { let ppid = process.ppid; unsafe { SWITCHTO_CALLER = None }; // TODO: Advance thread - ss.activate_process_thread(ppid, 0, false) + ss.activate_process_thread(tid, ppid, 0, false) .map(|_| Ok(xous::Result::ResumeProcess)) .unwrap_or(Err(xous::Error::ProcessNotFound)) }),