kernel: add preemptive multitasking

This is still a work in progress, but we now can have multiple processes
running at once.

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2020-04-06 15:52:07 +08:00
parent aec047b944
commit d4db20e516
6 changed files with 138 additions and 118 deletions

View file

@ -79,27 +79,33 @@ fn main() {
xous::syscall::create_server(xous::make_name!("📜")).expect("couldn't create server");
println!("Server listening on address {:?}", server_addr);
let mut counter = 0;
loop {
// println!("Waiting for an event...");
let mut envelope = xous::syscall::receive_message(server_addr).expect("couldn't get address");
// println!("Got message envelope: {:?}", envelope);
match &mut envelope.message {
xous::Message::Scalar(msg) => {
println!("Scalar message from {}: {:?}", envelope.sender, msg)
}
xous::Message::Move(msg) => {
let log_entry = LogString::from_message(msg);
println!("Moved log message from {}: {}", envelope.sender, log_entry);
}
xous::Message::ImmutableBorrow(msg) => {
let log_entry = LogString::from_message(msg);
println!("Immutably borrowed log message from {}: {}", envelope.sender, log_entry);
}
xous::Message::MutableBorrow(msg) => {
let mut log_entry = LogString::from_message(msg);
println!("Immutably borrowed log message from {}: {}", envelope.sender, log_entry);
writeln!(log_entry, " << HELLO FROM THE SERVER").unwrap();
}
if counter & 0xfff == 0 {
println!("Counter tick: {}", counter);
}
counter += 1;
// // println!("Waiting for an event...");
// let mut envelope = xous::syscall::receive_message(server_addr).expect("couldn't get address");
// // println!("Got message envelope: {:?}", envelope);
// match &mut envelope.message {
// xous::Message::Scalar(msg) => {
// println!("Scalar message from {}: {:?}", envelope.sender, msg)
// }
// xous::Message::Move(msg) => {
// let log_entry = LogString::from_message(msg);
// println!("Moved log message from {}: {}", envelope.sender, log_entry);
// }
// xous::Message::ImmutableBorrow(msg) => {
// let log_entry = LogString::from_message(msg);
// println!("Immutably borrowed log message from {}: {}", envelope.sender, log_entry);
// }
// xous::Message::MutableBorrow(msg) => {
// let mut log_entry = LogString::from_message(msg);
// println!("Immutably borrowed log message from {}: {}", envelope.sender, log_entry);
// writeln!(log_entry, " << HELLO FROM THE SERVER").unwrap();
// }
// }
}
}

View file

@ -126,36 +126,39 @@ fn main() {
let mut counter = 0;
let mut ls = logstr::LogStr::new();
loop {
println!("Sending a scalar message with id {}...", counter + 4096);
xous::syscall::send_message(
connection,
xous::Message::Scalar(xous::ScalarMessage {
id: counter + 4096,
arg1: counter,
arg2: counter * 2,
arg3: !counter,
arg4: counter + 1,
}),
)
.expect("couldn't send scalar message");
counter += 1;
if counter & 2 == 0 {
xous::syscall::yield_slice();
// println!("Sending a scalar message with id {}...", counter + 4096);
// xous::syscall::send_message(
// connection,
// xous::Message::Scalar(xous::ScalarMessage {
// id: counter + 4096,
// arg1: counter,
// arg2: counter * 2,
// arg3: !counter,
// arg4: counter + 1,
// }),
// )
// .expect("couldn't send scalar message");
if counter & 0xfff == 0 {
println!("Loop {}", counter);
}
counter += 1;
// if counter & 2 == 0 {
// xous::syscall::yield_slice();
// }
ls.clear();
write!(ls, "Hello, Server! This memory is borrowed from another process. Loop number: {}", counter).expect("couldn't send hello message");
// ls.clear();
// write!(ls, "Hello, Server! This memory is borrowed from another process. Loop number: {}", counter).expect("couldn't send hello message");
println!("Sending a mutable borrow message");
let response = xous::syscall::send_message(
connection,
xous::Message::MutableBorrow(
ls.as_memory_message(0)
.expect("couldn't form memory message"),
),
)
.expect("couldn't send memory message");
unsafe { ls.set_len(response.0)};
println!("Message came back with args ({}, {}) as: {}", response.0, response.1, ls);
// println!("Sending a mutable borrow message");
// let response = xous::syscall::send_message(
// connection,
// xous::Message::MutableBorrow(
// ls.as_memory_message(0)
// .expect("couldn't form memory message"),
// ),
// )
// .expect("couldn't send memory message");
// unsafe { ls.set_len(response.0)};
// println!("Message came back with args ({}, {}) as: {}", response.0, response.1, ls);
}
}

View file

@ -5,6 +5,8 @@ fn timer_tick(_irq_no: usize, _arg: *mut usize) {
println!(">>> Timer tick");
let ptr = TIMER_BASE as *mut usize;
xous::rsyscall(xous::SysCall::ReturnToParentI(0, 0)).expect("couldn't return to parent");
// acknowledge the timer
unsafe { ptr.add(6).write_volatile(1) };
println!("<<< Returning from timer_tick()");
@ -27,7 +29,7 @@ pub fn init() {
))
.expect("timer: couldn't claim interrupt");
let ms = 1000; // tick every 1000 ms
let ms = 10; // tick every 10 ms
en(false);
load(SYSTEM_CLOCK_FREQUENCY / 1_000 * ms);
reload(SYSTEM_CLOCK_FREQUENCY / 1_000 * ms);
@ -56,8 +58,7 @@ pub fn en(en: bool) {
let ptr = TIMER_BASE as *mut usize;
if en {
unsafe { ptr.add(2).write_volatile(1) };
}
else {
} else {
unsafe { ptr.add(2).write_volatile(0) };
}
}

View file

@ -4,7 +4,7 @@ use crate::arch::process::ProcessHandle;
use crate::mem::{MemoryManagerHandle, PAGE_SIZE};
use crate::services::{ProcessContext, SystemServicesHandle, RETURN_FROM_ISR};
use riscv::register::{scause, sepc, sie, sstatus, stval, vexriscv::sim, vexriscv::sip};
use xous::{SysCall, PID};
use xous::{SysCall, PID, CtxID};
extern "Rust" {
fn _xous_syscall_return_result(result: &xous::Result, context: &ProcessContext) -> !;
@ -34,40 +34,21 @@ pub fn disable_irq(irq_no: usize) {
sim::write(sim::read() & !(1 << irq_no));
}
static mut PREVIOUS_PAIR: Option<(PID, usize)> = None;
static mut PREVIOUS_PAIR: Option<(PID, CtxID)> = None;
// fn map_page_and_return(pc: usize, addr: usize, pid: PID, flags: MemoryFlags) {
// assert!(
// pid > 1,
// "kernel store page fault (pc: {:08x} target: {:08x})",
// pc,
// addr
// );
pub unsafe fn set_isr_return_pair(pid: PID, ctx: CtxID) {
PREVIOUS_PAIR = Some((pid, ctx));
}
// {
// let mut mm = MemoryManagerHandle::get();
// let new_page = mm.alloc_page(pid).expect("Couldn't allocate new page");
// println!(
// "Allocating new physical page {:08x} @ {:08x}",
// new_page,
// (addr & !4095)
// );
// mm.map_range(
// new_page as *mut usize,
// (addr & !4095) as *mut usize,
// 4096,
// flags,
// )
// .expect("Couldn't map new stack");
// }
// crate::arch::syscall::resume(current_pid() == 1, ProcessContext::current());
// }
pub unsafe fn take_isr_return_pair() -> Option<(PID, CtxID)> {
PREVIOUS_PAIR.take()
}
/// Trap entry point rust (_start_trap_rust)
///
/// scause is read to determine the cause of the trap. The top bit indicates
/// if it's an interrupt or an exception. The result is converted to an element
/// of the Interrupt or Exception enum and passed to handle_interrupt or
/// scause is read to determine the cause of the trap. The top bit indicates if
/// it's an interrupt or an exception. The result is converted to an element of
/// the Interrupt or Exception enum and passed to handle_interrupt or
/// handle_exception.
#[export_name = "_start_trap_rust"]
pub extern "C" fn trap_handler(
@ -82,8 +63,8 @@ pub extern "C" fn trap_handler(
) -> ! {
let sc = scause::read();
// If we were previously in Supervisor mode and we've just tried to write
// to invalid memory, then we likely blew out the stack.
// If we were previously in Supervisor mode and we've just tried to write to
// invalid memory, then we likely blew out the stack.
if cfg!(target_arch = "riscv32")
&& sstatus::read().spp() == sstatus::SPP::Supervisor
&& sc.bits() == 0xf
@ -116,7 +97,7 @@ pub extern "C" fn trap_handler(
if response == xous::Result::ResumeProcess {
crate::arch::syscall::resume(current_pid() == 1, ctx);
} else {
println!("Returning to address {:08x}", ctx.sepc);
// println!("Returning to address {:08x}", ctx.sepc);
unsafe { _xous_syscall_return_result(&response, ctx) };
}
}
@ -202,6 +183,7 @@ pub extern "C" fn trap_handler(
_ => (),
}
println!("SYSTEM HALT: CPU Exception on PID {}: {}", pid, ex);
MemoryMapping::current().print_map();
loop {}
} else {
let irqs_pending = sip::read();

View file

@ -1036,7 +1036,7 @@ impl SystemServices {
.server_from_sidx(sidx)
.expect("couldn't re-discover server index");
let result = server.queue_message(pid, context, message, original_address);
server.print_queue();
// server.print_queue();
result
};
let current_process = self
@ -1070,7 +1070,7 @@ impl SystemServices {
.server_from_sidx(sidx)
.expect("couldn't re-discover server index");
let result = server.queue_address(pid, context, message, client_address);
server.print_queue();
// server.print_queue();
result
};
let current_process = self

View file

@ -7,6 +7,9 @@ use crate::services::SystemServicesHandle;
use core::mem;
use xous::*;
/// This is the context that called SwitchTo
static mut SWITCHTO_CALLER: Option<(PID, CtxID)> = None;
pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error> {
let pid = arch::current_pid();
@ -44,12 +47,12 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
.as_mut_ptr()
.write_bytes(0, range.size.get() / mem::size_of::<usize>())
};
println!("Done zeroing out");
// println!("Done zeroing out");
}
for offset in
(range.addr.get()..(range.addr.get() + range.size.get())).step_by(PAGE_SIZE)
{
println!("Handing page to user");
// println!("Handing page to user");
crate::arch::mem::hand_page_to_user(offset as *mut usize)
.expect("couldn't hand page to user");
}
@ -115,9 +118,17 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
}
Ok(xous::Result::Ok)
}
SysCall::SwitchTo(pid, context) => {
SysCall::SwitchTo(new_pid, new_context) => {
let mut ss = SystemServicesHandle::get();
ss.activate_process_context(pid, context, true, false)
let context_nr = ss.current_context_nr();
unsafe {
assert!(
SWITCHTO_CALLER.is_none(),
"SWITCHTO_CALLER was not None, indicating SwitchTo was called twice"
);
SWITCHTO_CALLER = Some((pid, context_nr));
}
ss.activate_process_context(new_pid, new_context, true, false)
.map(|_ctx| {
// println!("switchto ({}, {})", pid, _ctx);
xous::Result::ResumeProcess
@ -127,13 +138,27 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
interrupt_claim(no, pid as definitions::PID, callback, arg).map(|_| xous::Result::Ok)
}
SysCall::Yield => {
let (parent_pid, parent_ctx) = unsafe { SWITCHTO_CALLER.take().expect("yielded when no parent context was present") };
let mut ss = SystemServicesHandle::get();
let ppid = ss.get_process(pid).expect("can't get current process").ppid;
assert_ne!(ppid, 0, "no parent process id");
ss.activate_process_context(ppid, 0, true, true)
// let ppid = ss.get_process(pid).expect("can't get current process").ppid;
// assert_ne!(ppid, 0, "no parent process id");
ss.activate_process_context(parent_pid, parent_ctx, true, true)
.map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound))
}
SysCall::ReturnToParentI(_pid, _cpuid) => {
let mut ss = SystemServicesHandle::get();
unsafe {
let (current_pid, current_ctx) = crate::arch::irq::take_isr_return_pair().expect("couldn't get the isr return pair");
// ss.ready_context(current_pid, current_ctx).unwrap();
let (parent_pid, parent_ctx) =
SWITCHTO_CALLER
.take()
.expect("ReturnToParentI called with no existing parent present");
crate::arch::irq::set_isr_return_pair(parent_pid, parent_ctx);
};
Ok(xous::Result::ResumeProcess)
}
SysCall::ReceiveMessage(sid) => {
let mut ss = SystemServicesHandle::get();
let context_nr = ss.current_context_nr();
@ -142,7 +167,7 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
let server = ss
.server_from_sidx(sidx)
.ok_or(xous::Error::ServerNotFound)?;
server.print_queue();
// server.print_queue();
// Ensure the server is for this PID
if server.pid != pid {
@ -151,7 +176,7 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
// If there is a pending message, return it immediately.
if let Some(msg) = server.take_next_message(sidx) {
println!("PID {} had a message ready -- returning it", pid);
// println!("PID {} had a message ready -- returning it", pid);
return Ok(xous::Result::Message(msg));
}
@ -159,11 +184,12 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
// process and mark ourselves as awaiting an event. When a message
// arrives, our return value will already be set to the
// MessageEnvelope of the incoming message.
println!(
"PID {} did not have any waiting messages -- parking context",
pid
);
// println!(
// "PID {} did not have any waiting messages -- parking context",
// pid
// );
server.park_context(context_nr);
unsafe { SWITCHTO_CALLER = None };
let ppid = ss.get_process(pid).expect("Can't get current process").ppid;
assert_ne!(ppid, 0, "no parent process id");
@ -175,6 +201,7 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
let mut ss = SystemServicesHandle::get();
let process = ss.get_process(pid).expect("Can't get current process");
let ppid = process.ppid;
unsafe { SWITCHTO_CALLER = None };
assert_ne!(ppid, 0, "no parent process id");
ss.activate_process_context(ppid, 0, false, true)
.map(|_| Ok(xous::Result::ResumeProcess))
@ -221,15 +248,15 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
return Err(xous::Error::ProcessNotFound);
}
};
println!(
"Returning {} bytes from {:08x} in PID {} to {:08x} in PID {} in context {}",
len,
server_addr.get(),
pid,
client_addr.get(),
client_pid,
client_ctx
);
// println!(
// "Returning {} bytes from {:08x} in PID {} to {:08x} in PID {} in context {}",
// len,
// server_addr.get(),
// pid,
// client_addr.get(),
// client_pid,
// client_ctx
// );
// Return the memory to the calling process
ss.return_memory(
@ -240,7 +267,7 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
)?;
// Unblock the client context to allow it to continue.
println!("Unblocking PID {} CTX {}", client_pid, client_ctx);
// println!("Unblocking PID {} CTX {}", client_pid, client_ctx);
ss.ready_context(client_pid, client_ctx)?;
ss.set_context_result(
client_pid,
@ -335,10 +362,10 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
.expect("server couldn't be located")
.take_available_context()
{
println!(
"There are contexts available to handle this message. Marking PID {} as Ready",
server_pid
);
// println!(
// "There are contexts available to handle this message. Marking PID {} as Ready",
// server_pid
// );
let sender = ss
.remember_server_message(sidx, pid, context_nr, &message, client_address)
.or_else(|e| {
@ -357,17 +384,17 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
})?;
if blocking {
println!("Activating Server context and switching away from Client");
// println!("Activating Server context and switching away from Client");
ss.activate_process_context(server_pid, ctx_number, !blocking, blocking)
.map(|_| Ok(xous::Result::Message(envelope)))
.unwrap_or(Err(xous::Error::ProcessNotFound))
} else {
println!("Setting the return value of the Server and returning to Client");
// println!("Setting the return value of the Server and returning to Client");
ss.set_context_result(server_pid, ctx_number, xous::Result::Message(envelope))
.map(|_| xous::Result::MessageResult(0, 0))
}
} else {
println!("No contexts available to handle this. Queueing message.");
// println!("No contexts available to handle this. Queueing message.");
// There is no server context we can use, so add the message to
// the queue.
let context_nr = ss.current_context_nr();
@ -379,14 +406,15 @@ pub fn handle(call: SysCall) -> core::result::Result<xous::Result, xous::Error>
// Park this context if it's blocking. This is roughly
// equivalent to a "Yield".
if blocking {
println!("Returning to parent");
// println!("Returning to parent");
let process = ss.get_process(pid).expect("Can't get current process");
let ppid = process.ppid;
unsafe { SWITCHTO_CALLER = None };
ss.activate_process_context(ppid, 0, !blocking, blocking)
.map(|_| Ok(xous::Result::ResumeProcess))
.unwrap_or(Err(xous::Error::ProcessNotFound))
} else {
println!("Returning to Client with Ok result");
// println!("Returning to Client with Ok result");
Ok(xous::Result::Ok)
}
}