kernel: add initial cut of exception handling

Though it is not yet wired up, the exception handler groundwork is laid
here.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2021-08-05 16:18:10 +08:00
parent 757a5c0f5e
commit 759ddfedd6
3 changed files with 181 additions and 61 deletions

View file

@ -2,8 +2,9 @@
// SPDX-License-Identifier: Apache-2.0
use crate::arch::current_pid;
use crate::arch::exception::RiscvException;
use crate::arch::mem::MemoryMapping;
use crate::arch::process::Process as ArchProcess;
use crate::arch::process::{Process as ArchProcess, RETURN_FROM_EXCEPTION_HANDLER};
use crate::arch::process::{Thread, EXIT_THREAD, RETURN_FROM_ISR};
use crate::services::SystemServices;
use riscv::register::{scause, sepc, sstatus, stval, vexriscv::sim, vexriscv::sip};
@ -48,6 +49,63 @@ pub unsafe fn take_isr_return_pair() -> Option<(PID, TID)> {
PREVIOUS_PAIR.take()
}
/// Convert a RISC-V `Exception` into a Xous exception argument list.
fn generate_exception_args(ex: &RiscvException) -> Option<[usize; 3]> {
match *ex {
RiscvException::InstructionAddressMisaligned(epc, addr) => Some([
xous_kernel::ExceptionType::InstructionAddressMisaligned as usize,
epc,
addr,
]),
RiscvException::InstructionAccessFault(epc, addr) => Some([
xous_kernel::ExceptionType::InstructionAccessFault as usize,
epc,
addr,
]),
RiscvException::IllegalInstruction(epc, instruction) => Some([
xous_kernel::ExceptionType::IllegalInstruction as usize,
epc,
instruction,
]),
RiscvException::LoadAddressMisaligned(epc, addr) => Some([
xous_kernel::ExceptionType::LoadAddressMisaligned as usize,
epc,
addr,
]),
RiscvException::LoadAccessFault(epc, addr) => Some([
xous_kernel::ExceptionType::LoadAccessFault as usize,
epc,
addr,
]),
RiscvException::StoreAddressMisaligned(epc, addr) => Some([
xous_kernel::ExceptionType::StoreAddressMisaligned as usize,
epc,
addr,
]),
RiscvException::StoreAccessFault(epc, addr) => Some([
xous_kernel::ExceptionType::StoreAccessFault as usize,
epc,
addr,
]),
RiscvException::InstructionPageFault(epc, addr) => Some([
xous_kernel::ExceptionType::InstructionPageFault as usize,
epc,
addr,
]),
RiscvException::LoadPageFault(epc, addr) => Some([
xous_kernel::ExceptionType::LoadPageFault as usize,
epc,
addr,
]),
RiscvException::StorePageFault(epc, addr) => Some([
xous_kernel::ExceptionType::StorePageFault as usize,
epc,
addr,
]),
_ => None,
}
}
/// Trap entry point rust (_start_trap_rust)
///
/// scause is read to determine the cause of the trap. The top bit indicates if
@ -115,12 +173,12 @@ pub extern "C" fn trap_handler(
});
}
use crate::arch::exception::RiscvException;
let ex = RiscvException::from_regs(sc.bits(), sepc::read(), stval::read());
// println!("ex: {:?}", ex);
if sc.is_exception() {
// If the CPU tries to store, look for a "reserved page" and provide
// it with one if necessary.
// See if it's a known exception, such as writing to a demand-paged area
// or returning from a handler or thread. If so, handle the exception
// and return right away.
match ex {
RiscvException::StorePageFault(pc, addr) | RiscvException::LoadPageFault(pc, addr) => {
#[cfg(all(feature = "debug-print", feature = "print-panics"))]
@ -140,45 +198,24 @@ pub extern "C" fn trap_handler(
});
})
.expect("Couldn't allocate page");
// If there is an exception of some sort, see if there is an exception handler
// available. If so, invoke it.
if let Some((pc, sp)) = SystemServices::with_mut(|ss| ss.handle_exception()) {
ArchProcess::with_current_mut(|process| {
crate::arch::syscall::invoke(
process.thread_mut(crate::arch::process::EXCEPTION_TID),
current_pid().get() == 1,
pc,
sp,
RETURN_FROM_EXCEPTION_HANDLER,
args,
);
crate::arch::syscall::resume(
current_pid().get() == 1,
process.thread(crate::arch::process::EXCEPTION_TID),
)
});
}
#[cfg(all(not(feature = "debug-print"), feature = "print-panics"))]
print!(
"KERNEL({}): RISC-V fault: {} @ {:08x}, addr {:08x} - ",
pid, ex, pc, addr
);
println!("Page was not allocated");
}
RiscvException::InstructionPageFault(RETURN_FROM_EXCEPTION_HANDLER, _offset) => {
// The instruction handler finished. Retry the existing instruction.
let tid = ArchProcess::with_current(|process| process.current_tid());
// This address indicates a thread has exited. Destroy the thread.
// This activates another thread within this process.
if SystemServices::with_mut(|ss| ss.destroy_thread(pid, tid)).unwrap() {
crate::syscall::reset_switchto_caller();
}
// This address indicates the exception handler
SystemServices::with_mut(|ss| {
ss.finish_exception_handler_and_resume(pid, tid)
.expect("unable to finish exception handler")
});
// Resume the new thread within the same process.
ArchProcess::with_current_mut(|p| {
// Adjust the program counter by the amount returned by the exception handler
let pc_adjust = a0 as isize;
p.current_thread_mut().sepc += 4;
crate::arch::syscall::resume(current_pid().get() == 1, p.current_thread())
});
}
@ -227,6 +264,43 @@ pub extern "C" fn trap_handler(
_ => (),
}
// This exception is not due to something we're aware of. In this case,
// determine if there is an exception handler in this particular program
// and call that handler if so.
if let Some(handler) = SystemServices::with_mut(|ss| ss.begin_exception_handler(pid)) {
// If this is the sort of exception that may be able to be handled by
// the userspace program, generate a list of arguments to pass to
// the handler.
if let Some(args) = generate_exception_args(&ex) {
// Invoke the handler in userspace and exit this exception handler.
ArchProcess::with_current_mut(|process| {
crate::arch::syscall::invoke(
process.thread_mut(crate::arch::process::EXCEPTION_TID),
current_pid().get() == 1,
handler.pc,
handler.sp,
RETURN_FROM_EXCEPTION_HANDLER,
&args,
);
crate::arch::syscall::resume(
current_pid().get() == 1,
process.thread(crate::arch::process::EXCEPTION_TID),
)
});
}
}
// #[cfg(all(not(feature = "debug-print"), feature = "print-panics"))]
// print!(
// "KERNEL({}): RISC-V fault: {} @ {:08x}, addr {:08x} - ",
// pid, ex, pc, addr
// );
// The exception was not handled. We should terminate the program here.
// For now, let's halt the whole system instead so that it becomes
// immediately obvious that we screwed up. On harware this will trigger
// a watchdog reset.
println!("SYSTEM HALT: CPU Exception on PID {}: {}", pid, ex);
ArchProcess::with_current(|process| {
println!("Current thread {}:", process.current_tid());

View file

@ -43,8 +43,16 @@ fn handle_panic(_arg: &PanicInfo) -> ! {
#[no_mangle]
/// This function is called from baremetal startup code to initialize various kernel structures
/// based on arguments passed by the bootloader. It is unused when running under an operating system.
pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offset: *mut u32) {
unsafe { args::KernelArguments::init(arg_offset) };
///
/// # Safety
///
/// This is safe to call only to initialize the kernel.
pub unsafe extern "C" fn init(
arg_offset: *const u32,
init_offset: *const u32,
rpt_offset: *mut u32,
) {
args::KernelArguments::init(arg_offset);
let args = args::KernelArguments::get();
// Everything needs memory, so the first thing we should do is initialize the memory manager.
crate::mem::MemoryManager::with_mut(|mm| {
@ -63,8 +71,12 @@ pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offs
#[cfg(any(feature = "debug-print", feature = "print-panics"))]
{
use utralib::generated::*;
xous_kernel::claim_interrupt(utra::uart::UART_IRQ, debug::irq, 0 as *mut usize)
.expect("Couldn't claim debug interrupt");
xous_kernel::claim_interrupt(
utra::uart::UART_IRQ,
debug::irq,
core::ptr::null_mut::<usize>(),
)
.expect("Couldn't claim debug interrupt");
// Map the serial port so println!() works as expected.
mem::MemoryManager::with_mut(|memory_manager| {
memory_manager

View file

@ -20,6 +20,15 @@ const MAX_SERVER_COUNT: usize = 128;
pub use crate::arch::process::{INITIAL_TID, MAX_PROCESS_COUNT};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ExceptionHandler {
/// Address (in program space) where the exception handler is
pub pc: usize,
/// Stack pointer when the exception is run
pub sp: usize,
}
// fn log_process_update(f: &str, l: u32, process: &Process, old_state: ProcessState) {
// if process.pid.get() == 3 {
// println!("[{}:{}] Updated PID {:?} state: {:?} -> {:?}", f, l, process.pid, old_state, process.state);
@ -118,7 +127,7 @@ pub struct Process {
previous_thread: TID,
/// When an exception is hit, the kernel will switch to this Thread.
exception_handler: Option<(usize /* handler */, usize /* Stack */)>,
exception_handler: Option<ExceptionHandler>,
}
impl Default for Process {
@ -887,6 +896,7 @@ impl SystemServices {
) -> Result<TID, xous_kernel::Error> {
let previous_pid = self.current_pid();
#[cfg(feature = "debug-print")]
if new_tid != 0 {
klog!("Activating process {} thread {}", new_pid, new_tid);
} else {
@ -896,8 +906,8 @@ impl SystemServices {
// Save state if the PID has changed. This will activate the new memory
// space.
let new = self.get_process_mut(new_pid)?;
if new_pid != previous_pid {
let new = self.get_process_mut(new_pid)?;
// println!("New state: {:?}", new.state);
// Ensure the new process can be run.
@ -945,7 +955,7 @@ impl SystemServices {
}
ProcessState::Sleeping | ProcessState::Debug(_) => {
// println!("PID {} was sleeping or being debugged", new_pid);
Err(xous_kernel::Error::ProcessNotFound)?;
return Err(xous_kernel::Error::ProcessNotFound);
}
}
@ -1164,9 +1174,9 @@ impl SystemServices {
dest_mapping.activate()?;
let dest_virt = mm
.find_virtual_address(dest_virt as *mut u8, len, xous_kernel::MemoryType::Messages)
.or_else(|e| {
.map_err(|e| {
src_mapping.activate().expect("couldn't undo mapping");
Err(e)
e
})? as *mut usize;
src_mapping
.activate()
@ -1277,10 +1287,10 @@ impl SystemServices {
dest_mapping.activate()?;
let dest_virt = mm
.find_virtual_address(dest_virt as *mut u8, len, xous_kernel::MemoryType::Messages)
.or_else(|e| {
.map_err(|e| {
src_mapping.activate().unwrap();
// klog!("Couldn't find a virtual address");
Err(e)
e
})? as *mut usize;
src_mapping.activate().unwrap();
@ -1363,19 +1373,19 @@ impl SystemServices {
// );
if len == 0 {
// klog!("No len");
Err(xous_kernel::Error::BadAddress)?;
return Err(xous_kernel::Error::BadAddress);
}
if len & 0xfff != 0 {
// klog!("len not aligned");
Err(xous_kernel::Error::BadAddress)?;
return Err(xous_kernel::Error::BadAddress);
}
if src_virt as usize & 0xfff != 0 {
// klog!("Src virt not aligned");
Err(xous_kernel::Error::BadAddress)?;
return Err(xous_kernel::Error::BadAddress);
}
if dest_virt as usize & 0xfff != 0 {
// klog!("dest virt not aligned");
Err(xous_kernel::Error::BadAddress)?;
return Err(xous_kernel::Error::BadAddress);
}
// If memory is getting returned to the kernel, then it is memory that was
@ -1420,7 +1430,7 @@ impl SystemServices {
0
});
}
error.map_or_else(|| Ok(dest_virt), |e| Err(e))
error.map_or_else(|| Ok(dest_virt), Err)
})
.map(|val| val as *mut usize)
}
@ -1563,7 +1573,7 @@ impl SystemServices {
// We cannot wait on ourselves.
if tid == join_tid {
Err(xous_kernel::Error::ThreadNotAvailable)?
return Err(xous_kernel::Error::ThreadNotAvailable)
}
// If the target thread exists, put this thread to sleep.
@ -1776,7 +1786,7 @@ impl SystemServices {
}
}
}
let slot_idx = slot_idx.ok_or_else(|| Error::OutOfMemory)?;
let slot_idx = slot_idx.ok_or(Error::OutOfMemory)?;
// Look through all servers for one whose SID matches.
for (server_idx, server) in self.servers.iter().enumerate() {
@ -1872,11 +1882,7 @@ impl SystemServices {
/// within the current process.
pub fn sidx_from_cid(&self, cid: CID) -> Option<usize> {
// println!("KERNEL({}): Attempting to get SIDX from CID {}", crate::arch::process::current_pid(), cid);
if cid == 0 {
// println!("KERNEL({}): CID is invalid -- returning", crate::arch::process::current_pid());
return None;
} else if cid == 1 {
// println!("KERNEL({}): Server has terminated -- returning", crate::arch::process::current_pid());
if cid == 0 || cid == 1 {
return None;
}
@ -2125,9 +2131,37 @@ impl SystemServices {
Ok(())
}
///
pub fn handle_exception(&mut self) -> Option<ExceptionHandler> {
None
/// Causes the provided process to go into an exception state. This will fail
/// if any of the following are true:
/// 1. The process does not exist
/// 2. The process has no exception handler
/// 3. The process is not "Running" or "Ready"
pub fn begin_exception_handler(&mut self, pid: PID) -> Option<ExceptionHandler> {
let process = self.get_process_mut(pid).ok()?;
let handler = process.exception_handler?;
process.state = match process.state {
ProcessState::Running(x) => ProcessState::Exception(x | 1 << process.current_thread),
ProcessState::Ready(x) => ProcessState::Exception(x),
_ => return None,
};
Some(handler)
}
/// Move the current process from an `Exception` state back into a `Running` state
/// with the current thread being marked as the given tid.
pub fn finish_exception_handler_and_resume(
&mut self,
pid: PID,
tid: TID,
) -> Result<(), xous_kernel::Result> {
let process = self.get_process_mut(pid)?;
if let ProcessState::Exception(threads) = process.state {
process.state = ProcessState::Running(threads & !(1 << tid));
process.current_thread = tid;
} else {
return Err(xous_kernel::Error::ThreadNotAvailable.into())
}
Ok(())
}
/// Returns the process name, if any, of a given PID