kernel: baremetal: 2nd process starts to run and crashes

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2020-08-10 16:06:38 +08:00
parent 75449f1deb
commit a467d6fcc7
8 changed files with 143 additions and 68 deletions

View file

@ -17,9 +17,9 @@ i @peripherals/keyboard.cs
machine LoadPlatformDescription @betrusted.repl machine LoadPlatformDescription @betrusted.repl
machine StartGdbServer 3333 true machine StartGdbServer 3333 true
showAnalyzer uartkernel
showAnalyzer uart showAnalyzer uart
showAnalyzer uartlog showAnalyzer uartlog
showAnalyzer uartkernel
#showAnalyzer memlcd #showAnalyzer memlcd
logLevel -1 kbd logLevel -1 kbd

View file

@ -176,6 +176,10 @@ impl Process {
process.threads[thread - 1].allocated = true; process.threads[thread - 1].allocated = true;
} }
pub fn setup_process(&mut self, setup: ThreadInit) -> Result<(), xous::Error> {
self.setup_thread(INITIAL_TID, setup)
}
pub fn setup_thread(&mut self, thread: TID, _setup: ThreadInit) -> Result<(), xous::Error> { pub fn setup_thread(&mut self, thread: TID, _setup: ThreadInit) -> Result<(), xous::Error> {
// println!( // println!(
// "KERNEL({}): Setting up thread {} @ {:?}", // "KERNEL({}): Setting up thread {} @ {:?}",

View file

@ -83,7 +83,7 @@ pub extern "C" fn trap_handler(
// performing the switch in order to avoid constantly executing the same // performing the switch in order to avoid constantly executing the same
// instruction. // instruction.
let tid = ArchProcess::with_current_mut(|p| { let tid = ArchProcess::with_current_mut(|p| {
p.current_thread().sepc += 4; p.current_thread_mut().sepc += 4;
p.current_tid() p.current_tid()
}); });
let call = SysCall::from_args(a0, a1, a2, a3, a4, a5, a6, a7).unwrap_or_else(|_| { let call = SysCall::from_args(a0, a1, a2, a3, a4, a5, a6, a7).unwrap_or_else(|_| {
@ -199,6 +199,10 @@ pub extern "C" fn trap_handler(
_ => (), _ => (),
} }
println!("SYSTEM HALT: CPU Exception on PID {}: {}", pid, ex); println!("SYSTEM HALT: CPU Exception on PID {}: {}", pid, ex);
ArchProcess::with_current(|process| {
println!("Current thread {}:", process.current_tid());
process.print_thread();
});
MemoryMapping::current().print_map(); MemoryMapping::current().print_map();
loop {} loop {}
} else { } else {

View file

@ -116,7 +116,7 @@ impl MemoryMapping {
} }
pub fn print_map(&self) { pub fn print_map(&self) {
println!("Memory Maps:"); println!("Memory Maps for PID {}:", self.get_pid());
let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) }; let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) };
for (i, l1_entry) in l1_pt.entries.iter().enumerate() { for (i, l1_entry) in l1_pt.entries.iter().enumerate() {
if *l1_entry == 0 { if *l1_entry == 0 {

View file

@ -2,6 +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;
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};
@ -16,7 +17,6 @@ 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;
pub const IRQ_THREAD: usize = 0;
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
#[repr(C)] #[repr(C)]
@ -38,7 +38,6 @@ struct ProcessImpl {
/// target process, and know which threads are ready to /// target process, and know which threads are ready to
/// receive messages. /// receive messages.
threads: [Thread; MAX_THREAD], threads: [Thread; MAX_THREAD],
} }
/// Singleton process table. Each process in the system gets allocated from this table. /// Singleton process table. Each process in the system gets allocated from this table.
@ -113,24 +112,18 @@ impl Process {
where where
F: FnOnce(&ProcessInner) -> R, F: FnOnce(&ProcessInner) -> R,
{ {
todo!(); let process = unsafe { &*PROCESS };
// PROCESS_TABLE.with(|pt| { f(&process.inner)
// let process_table = pt.borrow();
// let current = &process_table.table[process_table.current.get() as usize - 1]
// .as_ref()
// .unwrap();
// f(&current.inner)
// })
} }
// /// Calls the provided function with the current inner process state. /// Calls the provided function with the current inner process state.
// pub fn with_current<F, R>(f: F) -> R pub fn with_current<F, R>(f: F) -> R
// where where
// F: FnOnce(&Process) -> R, F: FnOnce(&Process) -> R,
// { {
// let process = Self::current(); let process = Self::current();
// f(&process) f(&process)
// } }
/// Calls the provided function with the current inner process state. /// Calls the provided function with the current inner process state.
pub fn with_current_mut<F, R>(f: F) -> R pub fn with_current_mut<F, R>(f: F) -> R
@ -145,21 +138,21 @@ impl Process {
where where
F: FnOnce(&mut ProcessInner) -> R, F: FnOnce(&mut ProcessInner) -> R,
{ {
todo!(); let process = unsafe { &mut *PROCESS };
// PROCESS_TABLE.with(|pt| { f(&mut process.inner)
// let mut process_table = pt.borrow_mut();
// let current_pid_idx = process_table.current.get() as usize - 1;
// let current = &mut process_table.table[current_pid_idx].as_mut().unwrap();
// f(&mut current.inner)
// })
} }
pub fn current_thread(&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.current_thread != 0, "thread number was 0");
&mut process.threads[process.current_thread - 1] &mut process.threads[process.current_thread - 1]
} }
pub fn current_thread(&self) -> &Thread {
let process = unsafe { &mut *PROCESS };
self.thread(process.current_thread)
}
pub fn current_tid(&self) -> TID { pub fn current_tid(&self) -> TID {
let process = unsafe { &*PROCESS }; let process = unsafe { &*PROCESS };
process.current_thread process.current_thread
@ -177,7 +170,7 @@ impl Process {
Ok(()) Ok(())
} }
pub fn thread(&mut self, thread: TID) -> &mut Thread { pub fn thread_mut(&mut self, thread: TID) -> &mut 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(),
@ -187,6 +180,16 @@ impl Process {
&mut process.threads[thread - 1] &mut 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 - 1]
}
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 };
for (index, thread) in process.threads.iter().enumerate() { for (index, thread) in process.threads.iter().enumerate() {
@ -199,7 +202,7 @@ impl Process {
pub fn set_thread_result(&mut self, thread_nr: TID, result: xous::Result) { pub fn set_thread_result(&mut self, thread_nr: TID, result: xous::Result) {
let vals = unsafe { mem::transmute::<_, [usize; 8]>(result) }; let vals = unsafe { mem::transmute::<_, [usize; 8]>(result) };
let thread = self.thread(thread_nr); let thread = self.thread_mut(thread_nr);
for (idx, reg) in vals.iter().enumerate() { for (idx, reg) in vals.iter().enumerate() {
thread.registers[9 + idx] = *reg; thread.registers[9 + idx] = *reg;
} }
@ -207,7 +210,9 @@ impl Process {
/// Initialize this process thread with the given entrypoint and stack /// Initialize this process thread with the given entrypoint and stack
/// addresses. /// addresses.
pub fn init(&mut self, entrypoint: usize, stack: usize, thread: usize) { pub fn setup_process(&mut self, thread_init: ThreadInit) {
let tid = INITIAL_TID;
assert!(tid != IRQ_TID, "tried to init using the irq thread");
let mut process = unsafe { &mut *PROCESS }; let mut process = unsafe { &mut *PROCESS };
assert!( assert!(
mem::size_of::<ProcessImpl>() == PAGE_SIZE, mem::size_of::<ProcessImpl>() == PAGE_SIZE,
@ -219,49 +224,113 @@ impl Process {
mem::size_of::<ProcessInner>(), mem::size_of::<ProcessInner>(),
); );
assert!( assert!(
thread + 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!(thread != IRQ_THREAD, "tried to init using the irq thread");
assert!( assert!(
thread == INITIAL_TID, tid == INITIAL_TID,
"tried to init using a thread {} that wasn't {}. This probably isn't what you want.", "tried to init using a thread {} that wasn't {}. This probably isn't what you want.",
thread, tid,
INITIAL_TID INITIAL_TID
); );
// By convention, thread 1 is the trap thread. Therefore, thread 2 is // By convention, thread 1 is the trap thread. Therefore, thread 2 is
// the first default thread. Thread 0 is unused. There is an offset of // the first default thread. Thread 0 is unused. There is an offset of
// 1 due to how the interrupt handler functions. // 1 due to how the interrupt handler functions.
process.current_thread = thread + 1; process.current_thread = tid;
for thread in process.threads.iter_mut() { for thread in process.threads.iter_mut() {
*thread = Default::default(); *thread = Default::default();
} }
let mut thread = self.current_thread(); let pid = self.pid.get();
let mut thread = self.current_thread_mut();
thread.registers = Default::default(); thread.registers = Default::default();
thread.sepc = entrypoint; thread.sepc = unsafe { core::mem::transmute::<_, usize>(thread_init.call) };
thread.registers[1] = stack; thread.registers[1] = thread_init.stack.as_ptr() as usize + thread_init.stack.len();
thread.registers[9] = thread_init.arg.map(|x| x.get()).unwrap_or_default();
if pid != 1 {
println!(
"Initializing PID {} thread {} with entrypoint {:08x}, stack @ {:08x}, arg {:08x}",
pid, tid, thread.sepc, thread.registers[1], thread.registers[9],
);
}
process.inner = Default::default(); process.inner = Default::default();
// Mark the stack as "unallocated-but-free"
let init_sp = (thread_init.stack.as_ptr() as usize) & !0xfff;
if init_sp != 0 {
let stack_size = thread_init.stack.len();
println!("Reserving stack {:08x} - {:08x} ({})", init_sp, init_sp + stack_size, stack_size);
crate::mem::MemoryManager::with_mut(|memory_manager| {
memory_manager
.reserve_range(
init_sp as *mut u8,
stack_size + 4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't reserve stack")
});
}
} }
pub fn setup_thread(&mut self, new_tid: TID, setup: ThreadInit) -> Result<(), xous::Error> { pub fn setup_thread(&mut self, new_tid: TID, setup: ThreadInit) -> Result<(), xous::Error> {
let entrypoint = unsafe { core::mem::transmute::<_, usize>(setup.call) }; let entrypoint = unsafe { core::mem::transmute::<_, usize>(setup.call) };
// Create the new context and set it to run in the new address space. // Create the new context and set it to run in the new address space.
let pid = self.pid.get(); let pid = self.pid.get();
let thread = self.thread(new_tid); let thread = self.thread_mut(new_tid);
crate::arch::syscall::invoke( crate::arch::syscall::invoke(
thread, thread,
pid == 1, pid == 1,
entrypoint, entrypoint,
setup.stack.as_ptr() as usize, setup.stack.as_ptr() as usize + setup.stack.len(),
EXIT_THREAD, EXIT_THREAD,
&[setup.arg.map(|x| x.get() as usize).unwrap_or_default()], &[setup.arg.map(|x| x.get() as usize).unwrap_or_default()],
); );
Ok(()) Ok(())
} }
pub fn print_thread(&self) {
let thread = self.current_thread();
println!(
"PC:{:08x} SP:{:08x} RA:{:08x}",
thread.sepc, thread.registers[1], thread.registers[0]
);
println!(
"GP:{:08x} TP:{:08x}",
thread.registers[2], thread.registers[3]
);
println!(
"T0:{:08x} T1:{:08x} T2:{:08x}",
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]
);
println!(
"S0:{:08x} S1:{:08x} S2:{:08x} S3:{:08x}",
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]
);
println!(
"S8:{:08x} S9:{:08x} S10:{:08x} S11:{:08x}",
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]
);
println!(
"A4:{:08x} A5:{:08x} A6:{:08x} A7:{:08x}",
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!();
} }

View file

@ -320,9 +320,7 @@ impl SystemServices {
// Set up our handle with a bogus sp and pc. These will get updated // Set up our handle with a bogus sp and pc. These will get updated
// once a context switch _away_ from the kernel occurs, however we need // once a context switch _away_ from the kernel occurs, however we need
// to make sure other fields such as "thread number" are all valid. // to make sure other fields such as "thread number" are all valid.
ArchProcess::with_current_mut(|process| process.init(0, 0, INITIAL_TID)); ArchProcess::with_current_mut(|process| process.setup_process(ThreadInit::default()));
// ProcessHandle::get().init(0, 0, INITIAL_TID);
// self.processes[0].current_thread = INITIAL_TID as u8;
} }
/// Add a new entry to the process table. This results in a new address space /// Add a new entry to the process table. This results in a new address space
@ -492,7 +490,7 @@ impl SystemServices {
}; };
process.state = ProcessState::Running(available_threads); process.state = ProcessState::Running(available_threads);
process.previous_thread = process.current_thread; process.previous_thread = process.current_thread;
process.current_thread = arch::process::IRQ_THREAD; process.current_thread = arch::process::IRQ_TID;
process.mapping.activate()?; process.mapping.activate()?;
} }
@ -507,11 +505,11 @@ impl SystemServices {
let sp = arch_process.current_thread().stack_pointer(); let sp = arch_process.current_thread().stack_pointer();
// Activate the current context // Activate the current context
arch_process.set_thread(arch::process::IRQ_THREAD).unwrap(); arch_process.set_thread(arch::process::IRQ_TID).unwrap();
// Construct the new frame // Construct the new frame
arch::syscall::invoke( arch::syscall::invoke(
arch_process.current_thread(), arch_process.current_thread_mut(),
pid.get() == 1, pid.get() == 1,
pc as usize, pc as usize,
sp, sp,
@ -573,7 +571,7 @@ impl SystemServices {
// ensure it's the INITIAL_TID. Otherwise it's not valid. // ensure it's the INITIAL_TID. Otherwise it's not valid.
if let Some(tid) = tid { if let Some(tid) = tid {
if tid != INITIAL_TID { if tid != INITIAL_TID {
return Err(xous::Error::InvalidThread); panic!("switched to an incorrect thread");
} }
} }
@ -768,14 +766,11 @@ impl SystemServices {
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_context); // 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); // let previous_tid = self.current_thread(previous_pid);
// println!("KERNEL({}): Activating process {} context {}", previous_pid, new_pid, new_context); println!("KERNEL({}): Activating process {} thread {}", previous_pid, new_pid, new_tid);
if !cfg!(baremetal) {
panic!("Not running on bare metal");
}
// 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.
if new_pid != previous_pid { if new_pid != previous_pid {
@ -831,24 +826,16 @@ impl SystemServices {
// Set up the new process, if necessary. Remove the new context from // Set up the new process, if necessary. Remove the new context from
// the list of ready contexts. // the list of ready contexts.
new.state = match new.state { new.state = match new.state {
ProcessState::Setup(_init_context) => { ProcessState::Setup(thread_init) => {
// entrypoint, stack, stack_size) => { println!("Setting up new process...");
ArchProcess::current().setup_process(thread_init);
// let mut process = ProcessHandle::get(); // let mut process = ProcessHandle::get();
// println!( // println!(
// "Initializing new process with stack size of {} bytes", // "Initializing new process with stack size of {} bytes",
// stack_size // stack_size
// ); // );
// // process.init(entrypoint, stack, INITIAL_TID); // // process.init(entrypoint, stack, INITIAL_TID);
// // Mark the stack as "unallocated-but-free"
// let init_sp = stack & !0xfff;
// let mut memory_manager = MemoryManagerHandle::get();
// memory_manager
// .reserve_range(
// (init_sp - stack_size) as *mut usize,
// stack_size + 4096,
// MemoryFlags::R | MemoryFlags::W,
// )
// .expect("couldn't reserve stack");
ProcessState::Running(0) ProcessState::Running(0)
} }
ProcessState::Allocated => ProcessState::Running(0), ProcessState::Allocated => ProcessState::Running(0),

View file

@ -309,9 +309,9 @@ fn receive_message(pid: PID, tid: TID, sid: SID) -> SysCallResult {
} }
pub fn handle(pid: PID, tid: TID, call: SysCall) -> SysCallResult { pub fn handle(pid: PID, tid: TID, call: SysCall) -> SysCallResult {
// print!("KERNEL({}:{}): Syscall {:?}", pid, tid, call); print!("KERNEL({}:{}): Syscall {:?}", pid, tid, call);
let result = handle_inner(pid, tid, call); let result = handle_inner(pid, tid, call);
// println!(" -> {:?}", result); println!(" -> {:?}", result);
result result
} }

View file

@ -33,6 +33,17 @@ impl ThreadInit {
} }
} }
impl Default for ThreadInit {
fn default() -> Self {
ThreadInit {
call: unsafe { core::mem::transmute::<usize, fn(data: *const usize) -> usize>(4) },
stack: MemoryRange::new(4, 4).unwrap(),
arg: None,
name: [0; 12],
}
}
}
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Copy, Clone, Debug, PartialEq)]
pub struct ProcessKey([u8; 8]); pub struct ProcessKey([u8; 8]);
impl ProcessKey { impl ProcessKey {