kernel: threads work now

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2020-08-10 22:05:06 +08:00
parent 1d23bc5aae
commit 31f63c3f5f
4 changed files with 89 additions and 58 deletions

View file

@ -2,7 +2,7 @@ use core::mem;
static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl; static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl;
pub const MAX_THREAD: TID = 31; pub const MAX_THREAD: TID = 31;
pub const INITIAL_TID: TID = 1; 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::arch::mem::PAGE_SIZE;
use crate::services::ProcessInner; use crate::services::ProcessInner;
use xous::{ProcessInit, ThreadInit, PID, TID}; 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. /// This is the address a thread will return to when it exits.
const EXIT_THREAD: usize = 0xff80_3000; 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)] #[derive(Debug, Copy, Clone)]
#[repr(C)] #[repr(C)]
struct ProcessImpl { struct ProcessImpl {
/// Used by the interrupt handler to calculate offsets /// Used by the interrupt handler to calculate offsets
scratch: usize, scratch: usize,
/// The currently-active thread for this process /// The currently-active thread for this process. This must
current_thread: usize, /// be the 2nd item, because the ISR directly writes this value.
hardware_thread: usize,
/// Global parameters used by the operating system /// Global parameters used by the operating system
pub inner: ProcessInner, pub inner: ProcessInner,
@ -46,7 +68,7 @@ struct ProcessTable {
current: PID, current: PID,
/// The number of processes that exist /// The number of processes that exist
total: usize, // total: usize,
/// The actual table contents /// The actual table contents
table: [bool; MAX_PROCESS_COUNT], table: [bool; MAX_PROCESS_COUNT],
@ -54,7 +76,7 @@ struct ProcessTable {
static mut PROCESS_TABLE: ProcessTable = ProcessTable { static mut PROCESS_TABLE: ProcessTable = ProcessTable {
current: unsafe { PID::new_unchecked(1) }, current: unsafe { PID::new_unchecked(1) },
total: 0, // total: 0,
table: [false; MAX_PROCESS_COUNT], table: [false; MAX_PROCESS_COUNT],
}; };
@ -144,18 +166,19 @@ impl Process {
pub fn current_thread_mut(&mut self) -> &mut Thread { pub fn current_thread_mut(&mut self) -> &mut Thread {
let process = unsafe { &mut *PROCESS }; let process = unsafe { &mut *PROCESS };
assert!(process.current_thread != 0, "thread number was 0"); assert!(process.hardware_thread != 0, "thread number was 0");
&mut process.threads[process.current_thread - 1] &mut process.threads[process.hardware_thread - 1]
} }
pub fn current_thread(&self) -> &Thread { pub fn current_thread(&self) -> &Thread {
let process = unsafe { &mut *PROCESS }; 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 { pub fn current_tid(&self) -> TID {
let process = unsafe { &*PROCESS }; let process = unsafe { &*PROCESS };
process.current_thread process.hardware_thread - 1
} }
/// Set the current thread number. /// Set the current thread number.
@ -166,7 +189,7 @@ impl Process {
"attempt to switch to an invalid thread {}", "attempt to switch to an invalid thread {}",
thread thread
); );
process.current_thread = thread + 1; process.hardware_thread = thread + 1;
Ok(()) Ok(())
} }
@ -177,18 +200,18 @@ impl Process {
"attempt to retrieve an invalid thread {}", "attempt to retrieve an invalid thread {}",
thread thread
); );
&mut process.threads[thread - 1] &mut process.threads[thread]
} }
pub fn thread(&self, thread: TID) -> &Thread { // pub fn thread(&self, thread: TID) -> &Thread {
let process = unsafe { &mut *PROCESS }; // let process = unsafe { &mut *PROCESS };
assert!( // assert!(
thread > 0 && thread <= process.threads.len(), // thread > 0 && thread <= process.threads.len(),
"attempt to retrieve an invalid thread {}", // "attempt to retrieve an invalid thread {}",
thread // thread
); // );
&process.threads[thread - 1] // &process.threads[thread]
} // }
pub fn find_free_thread(&self) -> Option<TID> { pub fn find_free_thread(&self) -> Option<TID> {
let process = unsafe { &mut *PROCESS }; let process = unsafe { &mut *PROCESS };
@ -225,7 +248,7 @@ impl Process {
mem::size_of::<ProcessInner>(), mem::size_of::<ProcessInner>(),
); );
assert!( assert!(
tid + 1 < process.threads.len(), tid - 1 < process.threads.len(),
"tried to init a thread that's out of range" "tried to init a thread that's out of range"
); );
assert!( assert!(
@ -248,7 +271,7 @@ impl Process {
// By convention, thread 0 is the trap thread. Therefore, thread 1 is // 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 // the first default thread. There is an offset of 1 due to how the
// interrupt handler functions. // interrupt handler functions.
process.current_thread = tid + 1; process.hardware_thread = tid + 1;
// Reset the thread state, since it's possibly uninitialized memory // Reset the thread state, since it's possibly uninitialized memory
for thread in process.threads.iter_mut() { for thread in process.threads.iter_mut() {
@ -306,50 +329,50 @@ impl Process {
} }
pub fn print_thread(&self) { pub fn print_thread(&self) {
let thread = self.current_thread(); let _thread = self.current_thread();
println!( println!(
"PC:{:08x} SP:{:08x} RA:{:08x}", "PC:{:08x} SP:{:08x} RA:{:08x}",
thread.sepc, thread.registers[1], thread.registers[0] _thread.sepc, _thread.registers[1], _thread.registers[0]
); );
println!( println!(
"GP:{:08x} TP:{:08x}", "GP:{:08x} TP:{:08x}",
thread.registers[2], thread.registers[3] _thread.registers[2], _thread.registers[3]
); );
println!( println!(
"T0:{:08x} T1:{:08x} T2:{:08x}", "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!( println!(
"T3:{:08x} T4:{:08x} T5:{:08x} T6:{:08x}", "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!( println!(
"S0:{:08x} S1:{:08x} S2:{:08x} S3:{:08x}", "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!( println!(
"S4:{:08x} S5:{:08x} S6:{:08x} S7:{:08x}", "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!( println!(
"S8:{:08x} S9:{:08x} S10:{:08x} S11:{:08x}", "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!( println!(
"A0:{:08x} A1:{:08x} A2:{:08x} A3:{:08x}", "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!( println!(
"A4:{:08x} A5:{:08x} A6:{:08x} A7:{:08x}", "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!(); todo!();
} }
pub fn destroy(pid: PID) -> Result<(), xous::Error> { pub fn destroy(_pid: PID) -> Result<(), xous::Error> {
todo!(); todo!();
// let mut process_table = unsafe { &mut *PROCESS }; // let mut process_table = unsafe { &mut *PROCESS };
// let pid_idx = pid.get() as usize - 1; // let pid_idx = pid.get() as usize - 1;
@ -371,7 +394,6 @@ impl Thread {
} }
pub fn set_current_pid(pid: PID) { pub fn set_current_pid(pid: PID) {
println!("ARCH: Setting current PID to {}", pid);
let pid_idx = (pid.get() - 1) as usize; let pid_idx = (pid.get() - 1) as usize;
unsafe { unsafe {
let mut pt = &mut PROCESS_TABLE; let mut pt = &mut PROCESS_TABLE;
@ -389,7 +411,7 @@ pub fn current_pid() -> PID {
} }
pub fn current_tid() -> TID { pub fn current_tid() -> TID {
unsafe { (*PROCESS).current_thread } unsafe { ((*PROCESS).hardware_thread) + 1 }
} }
// pub struct ProcessHandle<'a> { // pub struct ProcessHandle<'a> {

View file

@ -140,11 +140,11 @@ pub extern "C" fn kmain() {
match pid { match pid {
Some(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"); xous::rsyscall(xous::SysCall::SwitchTo(pid, 0)).expect("couldn't switch to pid");
} }
None => { 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 // Special case for testing: idle can return `false` to indicate exit
if !arch::idle() { if !arch::idle() {
return; return;

View file

@ -487,7 +487,9 @@ impl SystemServices {
ProcessState::Ready(x) | ProcessState::Running(x) => x, ProcessState::Ready(x) | ProcessState::Running(x) => x,
ProcessState::Sleeping => 0, ProcessState::Sleeping => 0,
ProcessState::Free => panic!("process was not allocated"), 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.state = ProcessState::Running(available_threads);
process.previous_thread = process.current_thread; process.previous_thread = process.current_thread;
@ -763,14 +765,17 @@ impl SystemServices {
/// process is in the Setup state, set it up and then resume. /// process is in the Setup state, set it up and then resume.
pub fn activate_process_thread( pub fn activate_process_thread(
&mut self, &mut self,
previous_tid: TID,
new_pid: PID, new_pid: PID,
mut new_tid: TID, mut new_tid: TID,
can_resume: bool, can_resume: bool,
) -> Result<TID, xous::Error> { ) -> Result<TID, xous::Error> {
// println!("Activating PID {}, context {}", new_pid, new_tid); // println!("Activating PID {}, context {}", new_pid, new_tid);
let previous_pid = self.current_pid(); let previous_pid = self.current_pid();
// let previous_tid = self.current_thread(previous_pid); println!(
println!("KERNEL({}): Activating process {} thread {}", previous_pid, new_pid, new_tid); "KERNEL({}): Activating process {} thread {}",
previous_pid, new_pid, new_tid
);
// Save state if the PID has changed. This will activate the new memory // Save state if the PID has changed. This will activate the new memory
// space. // space.
@ -779,7 +784,10 @@ impl SystemServices {
// Ensure the new process can be run. // Ensure the new process can be run.
match new.state { 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::Setup(_) | ProcessState::Allocated => new_tid = INITIAL_TID,
ProcessState::Running(x) | ProcessState::Ready(x) => { ProcessState::Running(x) | ProcessState::Ready(x) => {
// If no new context is specified, take the previous // If no new context is specified, take the previous
@ -810,13 +818,16 @@ impl SystemServices {
// println!(" -- picked context {}", new_context); // println!(" -- picked context {}", new_context);
} else if x & (1 << new_tid) == 0 { } else if x & (1 << new_tid) == 0 {
println!( println!(
"context is {:?}, which is not valid for new context {}", "thread is {:?}, which is not valid for new thread {}",
new.state, new_tid new.state, new_tid
); );
return Err(xous::Error::ProcessNotFound); 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 // 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 // we will either need to Sleep this process, or mark it as
// being Ready to run. // being Ready to run.
ProcessState::Running(x) if x == 0 => { ProcessState::Running(x) if x == 0 => {
// if can_resume { if can_resume {
// ProcessState::Ready(1 << previous_tid) ProcessState::Ready(1 << previous_tid)
// } else { } else {
ProcessState::Sleeping ProcessState::Sleeping
// } }
} }
// Otherwise, there are additional threads that can be run. // Otherwise, there are additional threads that can be run.
// Convert the previous process into "Ready", and include the // Convert the previous process into "Ready", and include the
@ -1213,9 +1224,7 @@ impl SystemServices {
/// * **ThreadNotAvailable**: The process has used all of its context /// * **ThreadNotAvailable**: The process has used all of its context
/// slots. /// slots.
pub fn create_thread(&mut self, pid: PID, thread_init: ThreadInit) -> Result<TID, xous::Error> { pub fn create_thread(&mut self, pid: PID, thread_init: ThreadInit) -> Result<TID, xous::Error> {
println!("Creating thread for PID {}", pid);
let mut process = self.get_process_mut(pid)?; let mut process = self.get_process_mut(pid)?;
println!("Process PID for {}: {}", pid, process.pid);
process.activate()?; process.activate()?;
let mut arch_process = crate::arch::process::Process::current(); let mut arch_process = crate::arch::process::Process::current();
@ -1225,7 +1234,7 @@ impl SystemServices {
arch_process.setup_thread(new_tid, thread_init)?; 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 // Queue the thread to run
process.state = match process.state { process.state = match process.state {

View file

@ -132,7 +132,7 @@ fn send_message(pid: PID, thread: TID, cid: CID, message: Message) -> SysCallRes
if blocking && cfg!(baremetal) { if blocking && cfg!(baremetal) {
// println!("Activating Server context and switching away from Client"); // 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))) .map(|_| Ok(xous::Result::Message(envelope)))
.unwrap_or(Err(xous::Error::ProcessNotFound)) .unwrap_or(Err(xous::Error::ProcessNotFound))
} else if blocking && !cfg!(baremetal) { } 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 process = ss.get_process(pid).expect("Can't get current process");
let ppid = process.ppid; let ppid = process.ppid;
unsafe { SWITCHTO_CALLER = None }; unsafe { SWITCHTO_CALLER = None };
ss.activate_process_thread(ppid, 0, !blocking) ss.activate_process_thread(thread, ppid, 0, !blocking)
.map(|_| Ok(xous::Result::ResumeProcess)) .map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound)) .unwrap_or(Err(xous::Error::ProcessNotFound))
} else { } else {
@ -295,7 +295,7 @@ fn receive_message(pid: PID, tid: TID, sid: SID) -> SysCallResult {
unsafe { SWITCHTO_CALLER = None }; unsafe { SWITCHTO_CALLER = None };
let ppid = ss.get_process(pid).expect("Can't get current process").ppid; let ppid = ss.get_process(pid).expect("Can't get current process").ppid;
// TODO: Advance thread // TODO: Advance thread
ss.activate_process_thread(ppid, 0, false) ss.activate_process_thread(tid, ppid, 0, false)
.map(|_| Ok(xous::Result::ResumeProcess)) .map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound)) .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)); 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| { .map(|_ctx| {
// println!("switchto ({}, {})", pid, _ctx); // println!("switchto ({}, {})", pid, _ctx);
xous::Result::ResumeProcess xous::Result::ResumeProcess
@ -473,7 +473,7 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult {
}; };
SystemServices::with_mut(|ss| { SystemServices::with_mut(|ss| {
// TODO: Advance thread // 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)) .map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound)) .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; let ppid = process.ppid;
unsafe { SWITCHTO_CALLER = None }; unsafe { SWITCHTO_CALLER = None };
// TODO: Advance thread // TODO: Advance thread
ss.activate_process_thread(ppid, 0, false) ss.activate_process_thread(tid, ppid, 0, false)
.map(|_| Ok(xous::Result::ResumeProcess)) .map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound)) .unwrap_or(Err(xous::Error::ProcessNotFound))
}), }),