From 3a8167b6ad3b9a90ebc149e7ddf8f46866544207 Mon Sep 17 00:00:00 2001 From: Julien CLEMENT Date: Sat, 31 Dec 2022 12:05:20 +0100 Subject: [PATCH] Basic thread run routine Signed-off-by: Julien CLEMENT --- src/fs/mod.rs | 11 +-- src/lib.rs | 17 ++++- src/proc/mod.rs | 2 +- src/proc/scheduler/mod.rs | 38 +++++++++-- src/proc/thread/mod.rs | 136 +++++++++++++++++++------------------- src/utils/mutex.rs | 4 ++ 6 files changed, 127 insertions(+), 81 deletions(-) diff --git a/src/fs/mod.rs b/src/fs/mod.rs index 31d1708..685397c 100644 --- a/src/fs/mod.rs +++ b/src/fs/mod.rs @@ -65,11 +65,14 @@ impl FileSystem for VirtualFS { loop { if let Some(fs) = map.find_exact(&path_split) { // TODO, remove path prefix of the mount point - return fs.borrow_mut().open(mnt_relative_path.as_str(), flags).await; - } - else { + return fs + .borrow_mut() + .open(mnt_relative_path.as_str(), flags) + .await; + } else { let component = path_split.remove(path_split.len() - 1); - mnt_relative_path = String::from("/") + component.as_str() + mnt_relative_path.as_str(); + mnt_relative_path = + String::from("/") + component.as_str() + mnt_relative_path.as_str(); } } } else { diff --git a/src/lib.rs b/src/lib.rs index a132844..c66bd00 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,9 @@ use drivers::vga::{self, Color, ColorCode}; use multiboot2::BootInformation; use task::{executor::Executor, keyboard, Task}; +use alloc::sync::Arc; +use core::cell::RefCell; + #[alloc_error_handler] fn alloc_error_handler(layout: alloc::alloc::Layout) -> ! { panic!("Allocation error: {:?}", layout) @@ -48,7 +51,6 @@ pub fn init(boot_info: &BootInformation) { memory::gdt::init_gdt(); interrupts::init_idt(); vga::change_color(ColorCode::new(Color::LightGreen, Color::Black)); - println!("Init kernel main thread: {:?}", proc::thread::KERNEL_THREAD.try_lock().unwrap().id); } #[no_mangle] @@ -86,6 +88,15 @@ async fn get_file() { fd.borrow_mut().close().await; - let mut thread = proc::thread::Thread::new(); - thread.start(proc::thread::exit as u64).await; + let thread = Arc::new(RefCell::new(proc::thread::Thread::new( + proc::thread::exit as u64, + ))); + proc::scheduler::SCHEDULER + .lock() + .await + .register(thread.clone()); + + unsafe { + (&mut*thread.as_ptr()).run(); + } } diff --git a/src/proc/mod.rs b/src/proc/mod.rs index 5e8e105..a9211ac 100644 --- a/src/proc/mod.rs +++ b/src/proc/mod.rs @@ -1,2 +1,2 @@ +pub mod scheduler; pub mod thread; -pub mod scheduler; \ No newline at end of file diff --git a/src/proc/scheduler/mod.rs b/src/proc/scheduler/mod.rs index 4d11abe..46b69af 100644 --- a/src/proc/scheduler/mod.rs +++ b/src/proc/scheduler/mod.rs @@ -1,22 +1,40 @@ +use crate::utils::mutex::AsyncMutex; + use super::thread::{Thread, ThreadId}; use alloc::{collections::BTreeMap, sync::Arc}; +use core::cell::RefCell; use crossbeam_queue::ArrayQueue; +use lazy_static::lazy_static; + +lazy_static! { + pub static ref SCHEDULER: AsyncMutex = AsyncMutex::new(Scheduler::new()); +} + +pub type Threadt = Arc>; pub struct Scheduler { - threads: BTreeMap>, + pub threads: BTreeMap, thread_queue: Arc>, } impl Scheduler { pub fn new() -> Self { - Scheduler { + let mut res = Scheduler { threads: BTreeMap::new(), thread_queue: Arc::new(ArrayQueue::new(100)), - } + }; + let k_thread: Thread = Thread { + id: ThreadId(0), + entry_point: 0, + started: true, + rsp: 0, + }; + res.register(Arc::new(RefCell::new(k_thread))); + res } - pub fn schedule(&mut self) -> Option> { + pub fn schedule(&mut self) -> Option { if let Ok(thread_id) = self.thread_queue.pop() { self.thread_queue.push(thread_id); let thread = match self.threads.get_mut(&thread_id) { @@ -28,4 +46,14 @@ impl Scheduler { None } } -} \ No newline at end of file + + pub fn register(&mut self, thread: Threadt) { + let thread_id = thread.borrow().id; + if self.threads.insert(thread_id, thread).is_some() { + panic!("Duplicate thread ID") + } + self.thread_queue + .push(thread_id) + .expect("Thread queue full"); + } +} diff --git a/src/proc/thread/mod.rs b/src/proc/thread/mod.rs index bab0282..77d3c1e 100644 --- a/src/proc/thread/mod.rs +++ b/src/proc/thread/mod.rs @@ -1,6 +1,8 @@ use crate::println; use crate::utils::mutex::AsyncMutex; +use super::scheduler::SCHEDULER; + use core::arch::asm; use core::sync::atomic::{AtomicU64, Ordering}; @@ -11,25 +13,10 @@ const STACK_SIZE: usize = 4096 * 20; lazy_static! { pub static ref RUNNING_THREAD: AsyncMutex = AsyncMutex::new(ThreadId(0)); - pub static ref KERNEL_THREAD: AsyncMutex = { - let k_rsp: u64; - unsafe { - asm!( - "push rsp", // Recover current rsp - "pop {out}", - out = out(reg) k_rsp, // Save current rsp - ); - } - let thread: Thread = Thread { - id: ThreadId(0), - rsp: k_rsp, - }; - AsyncMutex::new(thread) - }; } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct ThreadId(u64); +pub struct ThreadId(pub u64); impl ThreadId { fn new() -> Self { @@ -39,83 +26,96 @@ impl ThreadId { } pub fn exit() { - println!("Exiting"); - KERNEL_THREAD.try_lock().unwrap().run(); + println!("Exiting thread"); + let mut scheduler = SCHEDULER.try_lock().unwrap(); + let mut thread = scheduler + .threads + .get_mut(&ThreadId(0)) + .unwrap() + .borrow_mut(); + SCHEDULER.force_unlock(); + thread.run(); } pub struct Thread { pub id: ThreadId, - rsp: u64 + pub entry_point: u64, + pub started: bool, + pub rsp: u64, } impl Thread { - pub fn new() -> Self { + pub fn new(entry_point: u64) -> Self { unsafe { Thread { id: ThreadId::new(), + entry_point: entry_point, + started: false, rsp: alloc(Layout::new::<[u8; STACK_SIZE]>()) as u64 + STACK_SIZE as u64 - 0x80, } } } - pub async fn start(&mut self, rip: u64) { + pub fn run(&mut self) { + println!("Running thread {:?}", self.id); unsafe { - *RUNNING_THREAD.lock().await = self.id; + let mut current_thread_guard = RUNNING_THREAD.try_lock().unwrap(); + let current_rsp: u64; asm!( - "push rax", // Save current thread regs - "push rbx", - "push rcx", - "push rdx", - "push rbp", - "push rsi", - "push rdi", - "push rsp", // Recover current rsp "pop {out}", - out = out(reg) KERNEL_THREAD.lock().await.rsp, // Save current rsp + "sub {out}, 56", // Offset to saved registers + out = out(reg) current_rsp, // Save thread rsp ); - asm!( - "push {rsp}", - "pop rsp", - "jmp {rip}", - rsp = in(reg) self.rsp, - rip = in(reg) rip, - ); - } - } + let mut scheduler = SCHEDULER.try_lock().unwrap(); + let current_thread = scheduler.threads.get_mut(&*current_thread_guard).unwrap(); + current_thread.borrow_mut().rsp = current_rsp; + + *current_thread_guard = self.id; // change running thread + } // The scheduler and running thread guards is dropped here - pub async fn run(&mut self) { unsafe { - asm!( - "push rax", // Save current thread regs - "push rbx", - "push rcx", - "push rdx", - "push rbp", - "push rsi", - "push rdi", + if self.started { + asm!( + "push rax", // Save current thread regs + "push rbx", + "push rcx", + "push rdx", + "push rbp", + "push rsi", + "push rdi", - "push rsp", // Recover current rsp - "pop {out}", - out = out(reg) KERNEL_THREAD.lock().await.rsp, // Save current rsp - ); + "push {rsp}", // Set stack pointer to the new thread + "pop rsp", - *RUNNING_THREAD.lock().await = self.id; // change running thread + "pop rdi", // Restore new thread regs + "pop rsi", + "pop rbp", + "pop rdx", + "pop rcx", + "pop rbx", + "pop rax", + rsp = in(reg) self.rsp, + ); + } else { + self.started = true; + asm!( + "push rax", // Save current thread regs + "push rbx", + "push rcx", + "push rdx", + "push rbp", + "push rsi", + "push rdi", - asm!( - "push {rsp}", // Set stack pointer to the new thread - "pop rsp", - - "pop rdi", // Restore new thread regs - "pop rsi", - "pop rbp", - "pop rdx", - "pop rcx", - "pop rbx", - "pop rax", - rsp = in(reg) self.rsp, - ); + "push {rsp}", + "pop rsp", + "jmp {rip}", + rsp = in(reg) self.rsp, + rip = in(reg) self.entry_point, + ); + } } } -} \ No newline at end of file +} diff --git a/src/utils/mutex.rs b/src/utils/mutex.rs index 1181c43..70ffb13 100644 --- a/src/utils/mutex.rs +++ b/src/utils/mutex.rs @@ -80,6 +80,10 @@ impl AsyncMutex { } } + pub fn force_unlock(&self) { + self.lock.drop(); + } + pub async fn lock(&self) -> AsyncMutexGuard<'_, T> { self.lock.clone().await; AsyncMutexGuard { mutex: self }