kernel: first multiple threads working

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2020-08-10 21:17:48 +08:00
parent a467d6fcc7
commit 1d23bc5aae
8 changed files with 84 additions and 63 deletions

View file

@ -185,6 +185,7 @@ mod implementation {
println!("Allocating IRQ...");
xous::syscall::claim_interrupt(4, handle_irq, core::ptr::null_mut::<usize>())
.expect("couldn't claim interrupt");
println!("Claimed IRQ 4");
Output {
addr: uart.as_mut_ptr() as usize,
}
@ -318,7 +319,8 @@ fn main() {
let mut output = implementation::init();
let writer = output.get_writer();
// xous::arch::ensure_connection().unwrap();
println!("Creating the reader thread");
xous::create_thread_simple(reader_thread, writer).unwrap();
println!("Running the output");
output.run();
}

View file

@ -176,8 +176,9 @@ impl Process {
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_process(pid: PID, setup: ThreadInit) -> Result<(), xous::Error> {
let mut tmp = Process { pid };
tmp.setup_thread(INITIAL_TID, setup)
}
pub fn setup_thread(&mut self, thread: TID, _setup: ThreadInit) -> Result<(), xous::Error> {

View file

@ -107,10 +107,7 @@ pub extern "C" fn trap_handler(
if response == xous::Result::ResumeProcess {
crate::arch::syscall::resume(current_pid().get() == 1, thread);
} else {
println!(
"Returning to address {:08x}",
ArchProcess::with_current_mut(|p| p.current_thread().sepc)
);
println!("Returning to address {:08x}", thread.sepc);
unsafe { _xous_syscall_return_result(&response, thread) };
}
});

View file

@ -141,7 +141,7 @@ impl MemoryMapping {
// let l0_pt_addr = ((l1_entry >> 10) << 12) as *const u32;
let l0_pt = unsafe { &mut (*((PAGE_TABLE_OFFSET + i * 4096) as *mut LeafPageTable)) };
for (j, l0_entry) in l0_pt.entries.iter().enumerate() {
if *l0_entry & 1 == 0 {
if *l0_entry & 0x7 == 0 {
continue;
}
let _page_addr = j as u32 * (1 << 12);
@ -169,6 +169,7 @@ impl MemoryMapping {
let l1_pt = unsafe { &mut (*(PAGE_TABLE_ROOT_OFFSET as *mut RootPageTable)) };
let l0pt_virt = PAGE_TABLE_OFFSET + vpn1 * PAGE_SIZE;
// println!("Reserving memory address {:08x} with flags {:?}", addr, flags);
// Allocate a new level 1 pagetable entry if one doesn't exist.
if l1_pt.entries[vpn1] & MMUFlags::VALID.bits() == 0 {
let pid = crate::arch::current_pid();

View file

@ -49,13 +49,13 @@ struct ProcessTable {
total: usize,
/// The actual table contents
table: [Option<ProcessImpl>; MAX_PROCESS_COUNT],
table: [bool; MAX_PROCESS_COUNT],
}
static mut PROCESS_TABLE: ProcessTable = ProcessTable {
current: unsafe { PID::new_unchecked(1) },
total: 0,
table: [None; MAX_PROCESS_COUNT],
table: [false; MAX_PROCESS_COUNT],
};
#[repr(C)]
@ -166,7 +166,7 @@ impl Process {
"attempt to switch to an invalid thread {}",
thread
);
process.current_thread = thread;
process.current_thread = thread + 1;
Ok(())
}
@ -193,8 +193,8 @@ impl Process {
pub fn find_free_thread(&self) -> Option<TID> {
let process = unsafe { &mut *PROCESS };
for (index, thread) in process.threads.iter().enumerate() {
if index != 0 && thread.sepc == 0 {
return Some(index as TID + 1);
if index != IRQ_TID && thread.sepc == 0 {
return Some(index as TID);
}
}
None
@ -210,10 +210,11 @@ impl Process {
/// Initialize this process thread with the given entrypoint and stack
/// addresses.
pub fn setup_process(&mut self, thread_init: ThreadInit) {
let tid = INITIAL_TID;
assert!(tid != IRQ_TID, "tried to init using the irq thread");
pub fn setup_process(pid: PID, thread_init: ThreadInit) {
let mut process = unsafe { &mut *PROCESS };
let tid = INITIAL_TID;
assert!(tid != IRQ_TID, "tried to init using the irq thread");
assert!(
mem::size_of::<ProcessImpl>() == PAGE_SIZE,
"Process size is {}, not PAGE_SIZE ({}) (Thread size: {}, array: {}, Inner: {})",
@ -233,18 +234,31 @@ impl Process {
tid,
INITIAL_TID
);
// 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
// 1 due to how the interrupt handler functions.
process.current_thread = tid;
unsafe {
let pid_idx = (pid.get() as usize) - 1;
assert!(
!PROCESS_TABLE.table[pid_idx],
"process {} is already allocated",
pid
);
PROCESS_TABLE.table[pid_idx] = true;
}
// 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;
// Reset the thread state, since it's possibly uninitialized memory
for thread in process.threads.iter_mut() {
*thread = Default::default();
}
let pid = self.pid.get();
let mut thread = self.current_thread_mut();
let pid = pid.get();
let process = unsafe { &mut *PROCESS };
let mut thread = &mut process.threads[tid];
thread.registers = Default::default();
thread.sepc = unsafe { core::mem::transmute::<_, usize>(thread_init.call) };
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();
@ -262,7 +276,6 @@ impl Process {
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(
@ -280,6 +293,7 @@ impl Process {
// Create the new context and set it to run in the new address space.
let pid = self.pid.get();
let thread = self.thread_mut(new_tid);
println!("Setting up thread {}, pid {}", new_tid, pid);
crate::arch::syscall::invoke(
thread,
pid == 1,
@ -357,15 +371,14 @@ 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;
match pt.table.get_mut(pid_idx) {
None | Some(None) => {
panic!("PID {} does not exist", pid);
}
Some(_) => {}
match pt.table.get(pid_idx) {
None | Some(false) => panic!("PID {} does not exist", pid),
_ => (),
}
pt.current = pid;
}

View file

@ -304,6 +304,7 @@ impl SystemServices {
unsafe {
process.mapping.from_raw(init.satp);
process.ppid = PID::new_unchecked(1);
process.pid = PID::new(pid as _).unwrap();
};
if pid == 1 {
process.state = ProcessState::Running(0);
@ -320,7 +321,7 @@ impl SystemServices {
// 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
// to make sure other fields such as "thread number" are all valid.
ArchProcess::with_current_mut(|process| process.setup_process(ThreadInit::default()));
ArchProcess::setup_process(PID::new(1).unwrap(), ThreadInit::default());
}
/// Add a new entry to the process table. This results in a new address space
@ -828,13 +829,7 @@ impl SystemServices {
new.state = match new.state {
ProcessState::Setup(thread_init) => {
println!("Setting up new process...");
ArchProcess::current().setup_process(thread_init);
// let mut process = ProcessHandle::get();
// println!(
// "Initializing new process with stack size of {} bytes",
// stack_size
// );
// // process.init(entrypoint, stack, INITIAL_TID);
ArchProcess::setup_process(new_pid, thread_init);
ProcessState::Running(0)
}
@ -845,6 +840,7 @@ impl SystemServices {
}
ProcessState::Sleeping => ProcessState::Running(0),
};
new.activate()?;
// Mark the previous process as ready to run, since we just switched
// away
@ -1217,7 +1213,10 @@ impl SystemServices {
/// * **ThreadNotAvailable**: The process has used all of its context
/// slots.
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)?;
println!("Process PID for {}: {}", pid, process.pid);
process.activate()?;
let mut arch_process = crate::arch::process::Process::current();
let new_tid = arch_process
@ -1226,7 +1225,7 @@ impl SystemServices {
arch_process.setup_thread(new_tid, thread_init)?;
// println!("KERNEL({}): Created new context {}", pid, new_context_nr);
println!("KERNEL({}): Created new thread {}", pid, new_tid);
// Queue the thread to run
process.state = match process.state {

View file

@ -343,7 +343,7 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult {
}
// println!(
// "Mapping {:08x} -> {:08x} ({} bytes, flags: {:?})",
// phys as u32, virt as u32, size, req_flags
// phys_ptr as u32, virt_ptr as u32, size, req_flags
// );
let range = mm.map_range(
phys_ptr,
@ -501,7 +501,6 @@ pub fn handle_inner(pid: PID, tid: TID, call: SysCall) -> SysCallResult {
.unwrap_or(Err(xous::Error::ProcessNotFound))
}),
SysCall::CreateThread(thread_init) => SystemServices::with_mut(|ss| {
#[allow(clippy::unit_arg)]
ss.create_thread(pid, thread_init).map(|new_tid| {
if !cfg!(baremetal) {
ss.switch_to_thread(pid, Some(new_tid))

View file

@ -11,7 +11,7 @@ pub struct ProcessArgs {
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThreadInit {
pub call: fn(data: *const usize) -> usize,
pub call: fn(data: usize) -> usize,
pub stack: MemoryRange,
pub arg: Option<MemoryAddress>,
pub name: [u8; 12],
@ -19,7 +19,7 @@ pub struct ThreadInit {
impl ThreadInit {
pub fn new(
call: fn(data: *const usize) -> usize,
call: fn(data: usize) -> usize,
stack: MemoryRange,
arg: Option<MemoryAddress>,
name: [u8; 12],
@ -36,7 +36,7 @@ impl ThreadInit {
impl Default for ThreadInit {
fn default() -> Self {
ThreadInit {
call: unsafe { core::mem::transmute::<usize, fn(data: *const usize) -> usize>(4) },
call: unsafe { core::mem::transmute::<usize, fn(data: usize) -> usize>(4) },
stack: MemoryRange::new(4, 4).unwrap(),
arg: None,
name: [0; 12],
@ -65,11 +65,11 @@ pub fn thread_to_args(call: usize, init: &ThreadInit) -> [usize; 8] {
call as usize,
init.call as usize,
init.stack.as_ptr() as _,
init.stack.len(),
init.arg.map(|x| x.get()).unwrap_or_default(),
0,
0,
0,
0,
]
}
@ -77,24 +77,23 @@ pub fn thread_to_args(call: usize, init: &ThreadInit) -> [usize; 8] {
/// that were passed via registers and converts them into a `ThreadInit`
/// struct with enough information to start the new thread.
pub fn args_to_thread(
_a1: usize,
_a2: usize,
_a3: usize,
_a4: usize,
a1: usize,
a2: usize,
a3: usize,
a4: usize,
_a5: usize,
_a6: usize,
_a7: usize,
) -> core::result::Result<ThreadInit, crate::Error> {
todo!()
// let call = unsafe { core::mem::transmute::<usize, fn(usize) -> usize;
// let stack = MemoryAddress::new(a2).ok_or(Error::InvalidSyscall)?;
// let arg = MemoryAddress::new(a2);
// Ok(ThreadInit {
// call,
// stack,
// arg,
// name: [8u8; 16],
// })
let call = unsafe { core::mem::transmute(a1) };
let stack = MemoryRange::new(a2, a3).map_err(|_| crate::Error::InvalidSyscall)?;
let arg = MemoryAddress::new(a4);
Ok(ThreadInit {
call,
stack,
arg,
name: [0; 12],
})
}
pub fn create_thread_pre<F, T>(_f: &F) -> core::result::Result<ThreadInit, crate::Error>
@ -168,14 +167,22 @@ pub fn args_to_process(
}
pub fn create_thread_simple_pre<T, U>(
_f: &fn(T) -> U,
_arg: &T,
f: &fn(T) -> U,
arg: &T,
) -> core::result::Result<ThreadInit, crate::Error>
where
T: Send + 'static,
U: Send + 'static,
{
todo!()
let stack = crate::map_memory(
None,
None,
131_072,
crate::MemoryFlags::R | crate::MemoryFlags::W | crate::MemoryFlags::RESERVE,
)?;
let start = unsafe { core::mem::transmute(*f) };
let arg = unsafe { core::mem::transmute(arg) };
Ok(ThreadInit::new(start, stack, Some(arg), [0; 12]))
}
pub fn create_thread_simple_post<T, U>(
@ -187,7 +194,7 @@ where
T: Send + 'static,
U: Send + 'static,
{
todo!()
Ok(WaitHandle(core::marker::PhantomData))
}
/// If no connection exists, create a new connection to the server. This means
@ -205,5 +212,7 @@ pub fn create_process_post(
}
pub fn wait_process(_joiner: ProcessHandle) -> crate::SysCallResult {
todo!()
loop {
crate::wait_event();
}
}