diff --git a/xv7-kernel/src/arch/x86_64/context.rs b/xv7-kernel/src/arch/x86_64/context.rs index 5e5b5e3..aabfe12 100644 --- a/xv7-kernel/src/arch/x86_64/context.rs +++ b/xv7-kernel/src/arch/x86_64/context.rs @@ -1,11 +1,17 @@ +use core::mem::{offset_of, size_of}; + +use super::trapframe::{TrapFrame, trap_return}; use crate::paging::VirtAddr; -#[derive(Debug)] +/// Pure kernel-mode coroutine context (callee-saved registers + `%rsp`). +/// +/// Address space (`CR3`), privilege entry stack (`PerCpu` / `TSS.rsp0`), and +/// interrupt masking (`IF == 0` across context switches) are managed orthogonally +/// by the scheduler and `TrapFrame`. +#[derive(Debug, Default)] #[repr(C)] pub struct Context { - pub cr3: usize, pub rsp: usize, - pub rflags: usize, pub r15: usize, pub r14: usize, pub r13: usize, @@ -14,77 +20,82 @@ pub struct Context { pub rbx: usize, } +#[must_use = "call `.to(target)` to complete the context switch"] +pub struct SwitchFrom(*mut Context); + +impl SwitchFrom { + /// Saves the current CPU callee-saved registers + `%rsp` into `from` and + /// restores execution from `to`. + #[inline(always)] + pub unsafe fn to(self, to: *const Context) { + unsafe { + Context::switch_raw(self.0, to); + } + } +} + impl Context { - pub const fn new() -> Context { - Context { - cr3: 0, - rflags: 0, - rbx: 0, - r12: 0, - r13: 0, - r14: 0, + pub const fn new() -> Self { + Self { + rsp: 0, r15: 0, + r14: 0, + r13: 0, + r12: 0, rbp: 0, - rsp: 0, + rbx: 0, } } - pub const fn user(stack_pointer: VirtAddr) -> Context { - Context { - cr3: 0, - rflags: 0x282, - rbx: 0, - r12: 0, - r13: 0, - r14: 0, - r15: 0, - rbp: 0, - rsp: stack_pointer.as_u64() as usize, + /// Initializes a kernel context at `kstack_top` that reserves a `TrapFrame` + /// at the top of the stack and returns directly into `trap_return` when first scheduled. + pub fn init_user(kstack_top: VirtAddr) -> Self { + let tf_addr = kstack_top - size_of::() as u64; + let ret_slot = tf_addr - size_of::() as u64; + unsafe { + tf_addr.as_mut_ptr::().write(TrapFrame::default()); + ret_slot + .as_mut_ptr::() + .write(trap_return as *const () as usize); + } + Self { + rsp: ret_slot.as_u64() as usize, + ..Self::new() } } + /// Begins a context switch saving the current execution state into `from`. + #[inline(always)] + pub fn switch_from(from: *mut Context) -> SwitchFrom { + SwitchFrom(from) + } + #[unsafe(naked)] - pub unsafe extern "C" fn switch_to(&mut self, _next: &Context) { + unsafe extern "C" fn switch_raw(from: *mut Context, to: *const Context) { core::arch::naked_asm!( - " - mov rcx, cr3 - mov [rdi], rcx - mov rax, [rsi] - cmp rax, rcx - - je switch_to.same_cr3 - mov cr3, rax - - switch_to.same_cr3: - pushfq - pop QWORD PTR [rdi + 0x10] - - push QWORD PTR [rsi + 0x10] - popfq - - mov [rdi + 0x18], r15 - mov r15, [rsi + 0x18] - - mov [rdi + 0x20], r14 - mov r14, [rsi + 0x20] - - mov [rdi + 0x28], r13 - mov r13, [rsi + 0x28] - - mov [rdi + 0x30], r12 - mov r12, [rsi + 0x30] - - mov [rdi + 0x38], rbp - mov rbp, [rsi + 0x38] - - mov [rdi + 0x40], rbx - mov rbx, [rsi + 0x40] - - mov [rdi + 0x08], rsp - mov rsp, [rsi + 0x08] + "mov [rdi + {r15}], r15", + "mov [rdi + {r14}], r14", + "mov [rdi + {r13}], r13", + "mov [rdi + {r12}], r12", + "mov [rdi + {rbp}], rbp", + "mov [rdi + {rbx}], rbx", + "mov [rdi + {rsp}], rsp", - ret - ", + "mov r15, [rsi + {r15}]", + "mov r14, [rsi + {r14}]", + "mov r13, [rsi + {r13}]", + "mov r12, [rsi + {r12}]", + "mov rbp, [rsi + {rbp}]", + "mov rbx, [rsi + {rbx}]", + "mov rsp, [rsi + {rsp}]", + "ret", + rsp = const offset_of!(Context, rsp), + r15 = const offset_of!(Context, r15), + r14 = const offset_of!(Context, r14), + r13 = const offset_of!(Context, r13), + r12 = const offset_of!(Context, r12), + rbp = const offset_of!(Context, rbp), + rbx = const offset_of!(Context, rbx), ); } } diff --git a/xv7-kernel/src/arch/x86_64/gdt.rs b/xv7-kernel/src/arch/x86_64/gdt.rs index fcb4fee..ed3eebd 100644 --- a/xv7-kernel/src/arch/x86_64/gdt.rs +++ b/xv7-kernel/src/arch/x86_64/gdt.rs @@ -10,7 +10,7 @@ use x86_64::structures::tss::TaskStateSegment; pub const DOUBLE_FAULT_IST_INDEX: u16 = 0; pub const PAGE_FAULT_IST_INDEX: u16 = 1; -pub static TSS: SyncUnsafeCell = SyncUnsafeCell::new(TaskStateSegment::new()); +static TSS: SyncUnsafeCell = SyncUnsafeCell::new(TaskStateSegment::new()); lazy_static! { pub static ref GDT: (GlobalDescriptorTable, Selectors) = { @@ -48,9 +48,8 @@ lazy_static! { Descriptor::UserSegment(flags.bits()) }; - // The order is required. + // Order required by `STAR` MSR (`sysret`). let kernel_code_selector = gdt.append(kernel_code); - let kernel_data_selector = gdt.append(kernel_data); let mut user_data_selector = gdt.append(user_data); @@ -61,14 +60,6 @@ lazy_static! { let tss = unsafe { let tss = &mut *TSS.get(); - tss.privilege_stack_table[0] = { - const STACK_SIZE: usize = 4096; - static STACK: SyncUnsafeCell<[u8; STACK_SIZE]> = - SyncUnsafeCell::new([0; STACK_SIZE]); - - let stack_start = VirtAddr::from_ptr(STACK.get()); - stack_start + STACK_SIZE as u64 - }; tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = { const STACK_SIZE: usize = 4096; static STACK: SyncUnsafeCell<[u8; STACK_SIZE]> = @@ -123,3 +114,10 @@ pub fn init() { load_tss(GDT.1.tss_selector); } } + +/// Updates `TSS.privilege_stack_table[0]` (`RSP0`) for hardware Ring 3 -> Ring 0 transitions. +pub fn set_tss_rsp0(kstack_top: VirtAddr) { + unsafe { + (*TSS.get()).privilege_stack_table[0] = kstack_top; + } +} diff --git a/xv7-kernel/src/arch/x86_64/interrupt/timer.rs b/xv7-kernel/src/arch/x86_64/interrupt/timer.rs index a785b77..420751a 100644 --- a/xv7-kernel/src/arch/x86_64/interrupt/timer.rs +++ b/xv7-kernel/src/arch/x86_64/interrupt/timer.rs @@ -1,15 +1,6 @@ -use crate::cpu::my_cpu; - use super::controller::LOCAL_APIC; use x86_64::structures::idt::InterruptStackFrame; pub extern "x86-interrupt" fn handler(_stack_frame: InterruptStackFrame) { LOCAL_APIC.lock().end_of_interrupt(); - - let cpu = my_cpu(); - if cpu.current_process.is_some() { - //unsafe { - // cpu.switch_to_kernel(); - //} - } } diff --git a/xv7-kernel/src/arch/x86_64/macros.rs b/xv7-kernel/src/arch/x86_64/macros.rs deleted file mode 100644 index b65ac1d..0000000 --- a/xv7-kernel/src/arch/x86_64/macros.rs +++ /dev/null @@ -1,42 +0,0 @@ -#[allow(dead_code)] -#[repr(packed)] -pub struct ScratchRegisters { - pub rcx: usize, - pub rdx: usize, - pub rsi: usize, - pub rdi: usize, - pub r8: usize, - pub r9: usize, - pub r10: usize, - pub r11: usize, - pub rax: usize, -} - -#[allow(dead_code)] -#[repr(packed)] -pub struct PreservedRegisters { - pub r15: usize, - pub r14: usize, - pub r13: usize, - pub r12: usize, - pub rbp: usize, - pub rbx: usize, -} - -#[allow(dead_code)] -#[repr(packed)] -pub struct IretRegisters { - pub rip: usize, - pub cs: usize, - pub rflags: usize, - pub rsp: usize, - pub ss: usize, -} - -#[allow(dead_code)] -#[repr(packed)] -pub struct SyscallStackFrame { - pub scratch: ScratchRegisters, - pub preserved: PreservedRegisters, - pub iret: IretRegisters, -} diff --git a/xv7-kernel/src/arch/x86_64/mod.rs b/xv7-kernel/src/arch/x86_64/mod.rs index 0318134..3075b1d 100644 --- a/xv7-kernel/src/arch/x86_64/mod.rs +++ b/xv7-kernel/src/arch/x86_64/mod.rs @@ -1,6 +1,3 @@ -#[macro_use] -mod macros; - pub mod allocator; pub mod config; mod console; @@ -10,8 +7,21 @@ pub mod device; pub mod gdt; pub mod interrupt; pub mod paging; +pub mod percpu; mod start; pub mod syscall; +pub mod trapframe; + +pub use interrupt::{disable as disable_interrupts, without_interrupts}; +pub use percpu::set_kernel_stack; + +/// Atomically enables interrupts, halts until the next hardware interrupt, +/// and disables interrupts again upon wakeup. +#[inline] +pub fn wait_for_interrupt() { + interrupt::enable_and_hlt(); + interrupt::disable(); +} #[inline(always)] pub fn idle() -> ! { diff --git a/xv7-kernel/src/arch/x86_64/paging.rs b/xv7-kernel/src/arch/x86_64/paging.rs index 93e5503..d79b1cb 100644 --- a/xv7-kernel/src/arch/x86_64/paging.rs +++ b/xv7-kernel/src/arch/x86_64/paging.rs @@ -1,12 +1,39 @@ -use crate::{config::*, memory::FrameAllocator}; +use alloc::vec::Vec; +use core::sync::atomic::{AtomicU64, Ordering}; + use boot::{BootArgs, MemoryType}; +use spin::{Mutex, Once}; use x86_64::registers::control::Cr3; -use x86_64::structures::paging::{PageTable, PageTableFlags, PhysFrame}; +use x86_64::structures::paging::{ + Mapper, OffsetPageTable, Page, PageSize, PageTable, PageTableFlags, PhysFrame, Size4KiB, + Translate, +}; pub use x86_64::{PhysAddr, VirtAddr}; +use zeroize::Zeroize; + +use crate::{ + config::*, + memory::{FRAME_ALLOCATOR, FrameAllocator}, +}; + +/// Kernel PML4 physical frame recorded during early boot. +static KERNEL_CR3: Once = Once::new(); + +/// Virtual address region for per-process kernel stacks (within PML4[416], +/// sharing the same Level-3 PDPT initialized by `init_heap` at `KERNEL_HEAP_BASE`). +const KSTACK_REGION_BASE: u64 = KERNEL_HEAP_BASE as u64 + 0x1000_0000; +const KSTACK_GUARD_SIZE: u64 = Size4KiB::SIZE; +pub const KSTACK_SIZE: u64 = 4 * Size4KiB::SIZE; +const KSTACK_SLOT_STRIDE: u64 = KSTACK_GUARD_SIZE + KSTACK_SIZE; + +static NEXT_KSTACK_SLOT: AtomicU64 = AtomicU64::new(0); +static FREE_KSTACK_TOPS: Mutex> = Mutex::new(Vec::new()); pub fn disable_identity_mapping() { - let page_table = unsafe { active_page_table() }; + let (kernel_frame, _) = Cr3::read(); + KERNEL_CR3.call_once(|| kernel_frame); + let page_table = unsafe { active_page_table() }; for i in 0..256 { page_table[i].set_unused(); } @@ -14,8 +41,18 @@ pub fn disable_identity_mapping() { x86_64::instructions::tlb::flush_all(); } +pub fn activate_kernel_page_table() { + let target = *KERNEL_CR3.get().expect("KERNEL_CR3 not initialized"); + let (current, flags) = Cr3::read(); + if current != target { + unsafe { + Cr3::write(target, flags); + } + } +} + pub fn init_frame_allocator(args: &BootArgs) { - let mut allocator = crate::memory::FRAME_ALLOCATOR.lock(); + let mut allocator = FRAME_ALLOCATOR.lock(); for descriptor in args.memory_map.clone().iter { if descriptor.ty == MemoryType::CONVENTIONAL { allocator.install_memory_region( @@ -26,14 +63,70 @@ pub fn init_frame_allocator(args: &BootArgs) { } } +unsafe fn page_table_from_frame(frame: PhysFrame) -> &'static mut PageTable { + let virt = PAGE_OFFSET_BASE + frame.start_address().as_u64(); + unsafe { &mut *(virt as *mut PageTable) } +} + pub unsafe fn active_page_table() -> &'static mut PageTable { let (level_4_table_frame, _) = Cr3::read(); + unsafe { page_table_from_frame(level_4_table_frame) } +} + +/// A 16 KiB kernel stack preceded by an unmapped 4 KiB guard page. +/// Recycled automatically on `Drop`. +pub struct KernelStack { + top: VirtAddr, +} + +impl KernelStack { + pub fn alloc() -> Self { + if let Some(top) = FREE_KSTACK_TOPS.lock().pop() { + return Self { top }; + } - let phys = level_4_table_frame.start_address(); - let virt = PAGE_OFFSET_BASE + phys.as_u64(); - let page_table_ptr: *mut PageTable = virt as *mut _; + let slot = NEXT_KSTACK_SLOT.fetch_add(1, Ordering::Relaxed); + let slot_base = KSTACK_REGION_BASE + slot * KSTACK_SLOT_STRIDE; + let stack_bottom = slot_base + KSTACK_GUARD_SIZE; + let stack_top = stack_bottom + KSTACK_SIZE; + + let kernel_frame = *KERNEL_CR3.get().expect("KERNEL_CR3 not initialized"); + let page_table = unsafe { page_table_from_frame(kernel_frame) }; + let mut mapper = + unsafe { OffsetPageTable::new(page_table, VirtAddr::new(PAGE_OFFSET_BASE)) }; + let mut frame_allocator = FRAME_ALLOCATOR.lock(); + + let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE | PageTableFlags::NO_EXECUTE; + let mut addr = stack_bottom; + while addr < stack_top { + let page = Page::::containing_address(VirtAddr::new(addr)); + let frame = frame_allocator + .allocate_frame() + .expect("Failed to allocate kernel stack frame"); + unsafe { + mapper + .map_to(page, frame, flags, &mut *frame_allocator) + .expect("Failed to map kernel stack page") + .flush(); + } + addr += Size4KiB::SIZE; + } + + Self { + top: VirtAddr::new(stack_top), + } + } - unsafe { &mut *page_table_ptr } + #[inline] + pub fn top(&self) -> VirtAddr { + self.top + } +} + +impl Drop for KernelStack { + fn drop(&mut self) { + FREE_KSTACK_TOPS.lock().push(self.top); + } } pub struct AddressSpace { @@ -42,19 +135,16 @@ pub struct AddressSpace { impl AddressSpace { pub fn new() -> AddressSpace { - let table_frame = crate::memory::FRAME_ALLOCATOR - .lock() - .allocate_frame() - .unwrap(); - let table = unsafe { - &mut *{ (PAGE_OFFSET_BASE + table_frame.start_address().as_u64()) as *mut PageTable } - }; - let current_table = unsafe { active_page_table() }; + let table_frame = FRAME_ALLOCATOR.lock().allocate_frame().unwrap(); + let table = unsafe { page_table_from_frame(table_frame) }; + let kernel_frame = *KERNEL_CR3.get().expect("KERNEL_CR3 not initialized"); + let kernel_table = unsafe { page_table_from_frame(kernel_frame) }; + for i in 0..256 { table[i].set_unused(); } for i in 256..512 { - table[i] = current_table[i].clone(); + table[i] = kernel_table[i].clone(); } table[511].set_frame( table_frame, @@ -63,11 +153,103 @@ impl AddressSpace { AddressSpace { cr3: table_frame } } + pub fn activate(&self) { + let (current, flags) = Cr3::read(); + if current != self.cr3 { + unsafe { + Cr3::write(self.cr3, flags); + } + } + } + pub unsafe fn page_table(&mut self) -> &'static mut PageTable { - let phys = self.cr3.start_address(); - let virt = PAGE_OFFSET_BASE + phys.as_u64(); - let page_table_ptr: *mut PageTable = virt as *mut _; + unsafe { page_table_from_frame(self.cr3) } + } + + fn mapper(&mut self) -> OffsetPageTable<'static> { + let page_table = unsafe { self.page_table() }; + unsafe { OffsetPageTable::new(page_table, VirtAddr::new(PAGE_OFFSET_BASE)) } + } + + /// Allocates zeroed physical frames and maps them to `[vaddr, vaddr + len)` in this user address space. + pub fn map_user_range( + &mut self, + vaddr: VirtAddr, + len: usize, + _writable: bool, + executable: bool, + ) { + if len == 0 { + return; + } + let start_addr = Page::::containing_address(vaddr) + .start_address() + .as_u64(); + let end_addr = Page::::containing_address(vaddr + (len as u64 - 1)) + .start_address() + .as_u64(); + + let mut flags = + PageTableFlags::PRESENT | PageTableFlags::USER_ACCESSIBLE | PageTableFlags::WRITABLE; + if !executable { + flags |= PageTableFlags::NO_EXECUTE; + } + + let mut mapper = self.mapper(); + let mut frame_allocator = FRAME_ALLOCATOR.lock(); + + let mut addr = start_addr; + loop { + let page = Page::::containing_address(VirtAddr::new(addr)); + if mapper.translate_page(page).is_err() { + let frame = frame_allocator + .allocate_frame() + .expect("Failed to allocate user frame"); + let kva = (PAGE_OFFSET_BASE + frame.start_address().as_u64()) as *mut u8; + let slice = + unsafe { core::slice::from_raw_parts_mut(kva, Size4KiB::SIZE as usize) }; + slice.zeroize(); + + unsafe { + let flusher = mapper + .map_to(page, frame, flags, &mut *frame_allocator) + .expect("Failed to map user page"); + if Cr3::read().0 == self.cr3 { + flusher.flush(); + } else { + flusher.ignore(); + } + } + } + if addr == end_addr { + break; + } + addr += Size4KiB::SIZE; + } + } + + /// Copies `src` bytes into user virtual address `dst_vaddr` in this `AddressSpace` + /// via the kernel direct physical mapping (safe even when `self` is not the active `cr3`). + pub fn copy_to_user(&mut self, dst_vaddr: VirtAddr, src: &[u8]) { + let mapper = self.mapper(); + let mut offset = 0usize; + while offset < src.len() { + let cur_vaddr = dst_vaddr + offset as u64; + let phys = mapper + .translate_addr(cur_vaddr) + .expect("copy_to_user: unmapped user address"); + let page_offset = (cur_vaddr.as_u64() & 0xFFF) as usize; + let chunk = (Size4KiB::SIZE as usize - page_offset).min(src.len() - offset); + let dst_ptr = (PAGE_OFFSET_BASE + phys.as_u64()) as *mut u8; + unsafe { + core::ptr::copy_nonoverlapping(src.as_ptr().add(offset), dst_ptr, chunk); + } + offset += chunk; + } + } - unsafe { &mut *page_table_ptr } + /// Writes a `u64` value to user virtual address `dst_vaddr` in this `AddressSpace`. + pub fn write_user_u64(&mut self, dst_vaddr: VirtAddr, value: u64) { + self.copy_to_user(dst_vaddr, &value.to_ne_bytes()); } } diff --git a/xv7-kernel/src/arch/x86_64/percpu.rs b/xv7-kernel/src/arch/x86_64/percpu.rs new file mode 100644 index 0000000..fefb8b2 --- /dev/null +++ b/xv7-kernel/src/arch/x86_64/percpu.rs @@ -0,0 +1,50 @@ +use core::cell::SyncUnsafeCell; + +use x86_64::VirtAddr; +use x86_64::registers::model_specific::KernelGsBase; + +use super::gdt; + +/// Per-CPU state accessed via `%gs` on `syscall` entry (after `swapgs`). +#[repr(C)] +pub struct PerCpu { + /// Top of the currently running process's kernel stack. + pub kernel_rsp: u64, + /// Scratch slot used by `syscall_entry` to stash user `%rsp` while switching stacks. + pub user_rsp_scratch: u64, + /// User Ring 3 code segment selector (with RPL=3). + pub user_cs: u64, + /// User Ring 3 data/stack segment selector (with RPL=3). + pub user_ss: u64, +} + +impl PerCpu { + const fn new() -> Self { + Self { + kernel_rsp: 0, + user_rsp_scratch: 0, + user_cs: 0, + user_ss: 0, + } + } +} + +/// TODO: Make this an array indexed by APIC ID when SMP is enabled. +static PER_CPU: SyncUnsafeCell = SyncUnsafeCell::new(PerCpu::new()); + +pub fn init() { + let per_cpu = unsafe { &mut *PER_CPU.get() }; + per_cpu.user_cs = u64::from(gdt::GDT.1.user_code_selector.0); + per_cpu.user_ss = u64::from(gdt::GDT.1.user_data_selector.0); + + KernelGsBase::write(VirtAddr::from_ptr(PER_CPU.get())); +} + +/// Registers `kstack_top` as the Ring 3 -> Ring 0 entry stack for both +/// `syscall` (`PerCpu.kernel_rsp`) and hardware interrupts/exceptions (`TSS.rsp0`). +pub fn set_kernel_stack(kstack_top: VirtAddr) { + unsafe { + (*PER_CPU.get()).kernel_rsp = kstack_top.as_u64(); + } + gdt::set_tss_rsp0(kstack_top); +} diff --git a/xv7-kernel/src/arch/x86_64/start.rs b/xv7-kernel/src/arch/x86_64/start.rs index 973451d..218b5cc 100644 --- a/xv7-kernel/src/arch/x86_64/start.rs +++ b/xv7-kernel/src/arch/x86_64/start.rs @@ -26,23 +26,19 @@ extern "sysv64" fn _start(args: &BootArgs) -> ! { // After this point, we can allocate memory crate::allocator::init_heap(); - dbg!(args); - memory::print_memory_map(&args.memory_map); cpuid::init(); gdt::init(); + percpu::init(); + interrupt::init(); interrupt::controller::init(); syscall::init(); - interrupt::enable(); - - // crate::video::fun_things(); - crate::kmain(); } diff --git a/xv7-kernel/src/arch/x86_64/syscall.rs b/xv7-kernel/src/arch/x86_64/syscall.rs index 0d8cf55..09455bd 100644 --- a/xv7-kernel/src/arch/x86_64/syscall.rs +++ b/xv7-kernel/src/arch/x86_64/syscall.rs @@ -1,30 +1,35 @@ -use super::gdt; -use super::macros::SyscallStackFrame; +use core::mem::offset_of; + use x86_64::VirtAddr; -use x86_64::registers::model_specific::{Efer, EferFlags, KernelGsBase, LStar, SFMask, Star}; +use x86_64::registers::model_specific::{Efer, EferFlags, LStar, SFMask, Star}; use x86_64::registers::rflags::RFlags; +use super::gdt; +use super::percpu::PerCpu; +use super::trapframe::{TrapFrame, trap_return}; + #[unsafe(naked)] pub unsafe extern "C" fn syscall_entry() { core::arch::naked_asm!( - "swapgs", // Load kernel TSS pointer - "mov gs:[0x1c], rsp", // Save userspace %rsp - "mov rsp, gs:[0x4]", // Load TSS %rsp - "push 0x1b", // Push userspace data segment - "push gs:[0x1c]", // Push userspace %rsp - "mov QWORD PTR gs:[0x1c], 0", // Clear userspace %rsp - "push r11", // Push rflags - "push 0x23", // Push userspace code segment - "push rcx", // Push userspace return pointer - "swapgs", // Restore %gs - // push preserved + "swapgs", + "mov QWORD PTR gs:[{u_rsp}], rsp", + "mov rsp, QWORD PTR gs:[{k_rsp}]", + // Build hardware `iretq` portion of `TrapFrame` + "push QWORD PTR gs:[{u_ss}]", + "push QWORD PTR gs:[{u_rsp}]", + "mov QWORD PTR gs:[{u_rsp}], 0", + "push r11", + "push QWORD PTR gs:[{u_cs}]", + "push rcx", + "swapgs", + // Save callee-saved registers "push rbx", "push rbp", "push r12", "push r13", "push r14", "push r15", - // push scratch + // Save scratch / syscall argument registers "push rax", "push r11", "push r10", @@ -34,47 +39,31 @@ pub unsafe extern "C" fn syscall_entry() { "push rsi", "push rdx", "push rcx", - // call syscall_inner + // Invoke `syscall_inner(&mut TrapFrame)` (`rsp` is 16-byte aligned) "mov rdi, rsp", - "call {}", - // pop scratch - "pop rcx", - "pop rdx", - "pop rsi", - "pop rdi", - "pop r8", - "pop r9", - "pop r10", - "pop r11", - "pop rax", - // pop preserved - "pop r15", - "pop r14", - "pop r13", - "pop r12", - "pop rbp", - "pop rbx", - // interrupt return - "iretq", - sym syscall_inner, + "call {syscall_inner}", + "jmp {trap_return}", + k_rsp = const offset_of!(PerCpu, kernel_rsp), + u_rsp = const offset_of!(PerCpu, user_rsp_scratch), + u_cs = const offset_of!(PerCpu, user_cs), + u_ss = const offset_of!(PerCpu, user_ss), + syscall_inner = sym syscall_inner, + trap_return = sym trap_return, ); } -extern "C" fn syscall_inner(stack: *mut SyscallStackFrame) { - let stack = unsafe { &mut *stack }; - let scratch = &stack.scratch; - stack.scratch.rax = crate::syscall::syscall( - scratch.rax, - scratch.rdi, - scratch.rsi, - scratch.rdx, - scratch.r10, - scratch.r8, - ); +extern "C" fn syscall_inner(tf: &mut TrapFrame) { + tf.rax = crate::syscall::syscall( + tf.rax as usize, + tf.rdi as usize, + tf.rsi as usize, + tf.rdx as usize, + tf.r10 as usize, + tf.r8 as usize, + ) as u64; } pub fn init() { - // Setup syscall/sysret cs/ss Star::write( gdt::GDT.1.user_code_selector, gdt::GDT.1.user_data_selector, @@ -83,10 +72,8 @@ pub fn init() { ) .unwrap(); - // Setup syscall target rip LStar::write(VirtAddr::from_ptr(syscall_entry as *const u8)); - // Setup flags to clear let mask = RFlags::TRAP_FLAG | RFlags::DIRECTION_FLAG | RFlags::INTERRUPT_FLAG @@ -97,18 +84,7 @@ pub fn init() { SFMask::write(mask); - KernelGsBase::write(VirtAddr::from_ptr(gdt::TSS.get())); - - // Enable syscall extensions unsafe { Efer::update(|efer| efer.insert(EferFlags::SYSTEM_CALL_EXTENSIONS)); } - - dbg!(unsafe { &*gdt::TSS.get() }); - - dbg!(Efer::read()); - dbg!(Star::read()); - dbg!(LStar::read()); - dbg!(SFMask::read()); - dbg!(KernelGsBase::read()); } diff --git a/xv7-kernel/src/arch/x86_64/trapframe.rs b/xv7-kernel/src/arch/x86_64/trapframe.rs new file mode 100644 index 0000000..b7fd1fd --- /dev/null +++ b/xv7-kernel/src/arch/x86_64/trapframe.rs @@ -0,0 +1,94 @@ +use core::mem::{offset_of, size_of}; + +use x86_64::VirtAddr; +use x86_64::registers::rflags::RFlags; + +use super::gdt::GDT; + +const USER_RFLAGS: u64 = RFlags::INTERRUPT_FLAG.bits() | 0x2; + +/// Complete user-mode register state saved at the top of a process's kernel stack. +/// +/// Shared uniformly across initial Ring 3 entry, `syscall` entry/exit, and future +/// `fork` / `exec` / interrupt trap handling. +#[derive(Debug, Clone, Copy, Default)] +#[repr(C)] +pub struct TrapFrame { + // Scratch / syscall argument registers + pub rcx: u64, + pub rdx: u64, + pub rsi: u64, + pub rdi: u64, + pub r8: u64, + pub r9: u64, + pub r10: u64, + pub r11: u64, + pub rax: u64, + + // Callee-saved registers + pub r15: u64, + pub r14: u64, + pub r13: u64, + pub r12: u64, + pub rbp: u64, + pub rbx: u64, + + // Hardware `iretq` frame + pub rip: u64, + pub cs: u64, + pub rflags: u64, + pub rsp: u64, + pub ss: u64, +} + +const _: () = { + assert!(offset_of!(TrapFrame, rcx) == 0x00); + assert!(offset_of!(TrapFrame, rax) == 0x40); + assert!(offset_of!(TrapFrame, r15) == 0x48); + assert!(offset_of!(TrapFrame, rbx) == 0x70); + assert!(offset_of!(TrapFrame, rip) == 0x78); + assert!(offset_of!(TrapFrame, ss) == 0x98); + assert!(size_of::() == 0xA0); +}; + +impl TrapFrame { + /// Resets the frame to cleanly enter Ring 3 at `(entry, user_sp)` with all + /// general-purpose registers zeroed and interrupts enabled in user mode. + pub fn init_user(&mut self, entry: VirtAddr, user_sp: VirtAddr) { + *self = Self { + rip: entry.as_u64(), + cs: u64::from(GDT.1.user_code_selector.0), + rflags: USER_RFLAGS, + rsp: user_sp.as_u64(), + ss: u64::from(GDT.1.user_data_selector.0), + ..Self::default() + }; + } +} + +/// Unified Ring 0 -> Ring 3 exit trampoline. +/// +/// Expects `%rsp` to point to a `TrapFrame` at `kstack_top - size_of::()` +/// with interrupts disabled (`IF = 0`). Pops all general-purpose registers and +/// executes `iretq` into user space. +#[unsafe(naked)] +pub unsafe extern "C" fn trap_return() -> ! { + core::arch::naked_asm!( + "pop rcx", + "pop rdx", + "pop rsi", + "pop rdi", + "pop r8", + "pop r9", + "pop r10", + "pop r11", + "pop rax", + "pop r15", + "pop r14", + "pop r13", + "pop r12", + "pop rbp", + "pop rbx", + "iretq", + ); +} diff --git a/xv7-kernel/src/cpu.rs b/xv7-kernel/src/cpu.rs index 60ba9a3..5c936f8 100644 --- a/xv7-kernel/src/cpu.rs +++ b/xv7-kernel/src/cpu.rs @@ -1,48 +1,87 @@ +use alloc::boxed::Box; use core::cell::SyncUnsafeCell; +use core::mem::size_of; -use crate::arch::gdt; +use crate::arch; use crate::context::Context; -use crate::process::Process; +use crate::paging; +use crate::process::{Process, ProcessState}; -#[repr(C)] pub struct Cpu { - pub kernel_context: Context, - pub current_process: Option, + scheduler_context: SyncUnsafeCell, + current_process: SyncUnsafeCell>>, } +const _: () = { + assert!(size_of::>>() == size_of::()); +}; + impl Cpu { - pub const fn new() -> Cpu { - Cpu { - kernel_context: Context::new(), - current_process: None, + pub const fn new() -> Self { + Self { + scheduler_context: SyncUnsafeCell::new(Context::new()), + current_process: SyncUnsafeCell::new(None), } } +} - pub unsafe fn switch_to_process(&mut self) { - let proc = &self.current_process.as_ref().unwrap(); - unsafe { - let tss = &mut *gdt::TSS.get(); - tss.privilege_stack_table[1] = tss.privilege_stack_table[0]; - tss.privilege_stack_table[0] = proc.kstack + 4096u64; - self.kernel_context.switch_to(&proc.context); - } - } +/// TODO: Index by CPU ID when SMP is enabled. +static CPUS: [Cpu; 1] = [const { Cpu::new() }; 1]; - pub unsafe fn switch_to_kernel(&mut self) { - match self.current_process.as_mut() { - Some(p) => unsafe { - let tss = &mut *gdt::TSS.get(); - tss.privilege_stack_table[0] = tss.privilege_stack_table[1]; - p.context.switch_to(&self.kernel_context) - }, - None => panic!("No process running"), - } +#[inline] +fn current_cpu() -> &'static Cpu { + &CPUS[0] +} + +/// Executes `f` with a scoped mutable reference to the currently running `Process`. +/// Do not call context-switching functions (`scheduler::yield_now` / `exit_current`) inside `f`. +pub fn with_current_process(f: impl FnOnce(&mut Process) -> R) -> R { + let slot = unsafe { &mut *current_cpu().current_process.get() }; + let proc = slot + .as_deref_mut() + .expect("No process running on current CPU"); + f(proc) +} + +/// Resumes `proc` on the current CPU (activating its address space and kernel entry stack) +/// until it suspends via `suspend_current`, then restores the kernel page table and returns `proc`. +pub(crate) fn resume(mut proc: Box) -> Box { + let cpu = current_cpu(); + proc.state = ProcessState::Running; + proc.vm.activate(); + arch::set_kernel_stack(proc.kstack.top()); + + let proc_ctx = { + let slot = unsafe { &mut *cpu.current_process.get() }; + let installed = slot.insert(proc); + &raw const installed.context + }; + + unsafe { + Context::switch_from(cpu.scheduler_context.get()).to(proc_ctx); } + + paging::activate_kernel_page_table(); + + let slot = unsafe { &mut *cpu.current_process.get() }; + slot.take() + .expect("Current process missing after returning to scheduler") } -/// TODO: Support more cpus -static CPUS: SyncUnsafeCell<[Cpu; 1]> = SyncUnsafeCell::new([Cpu::new(); 1]); +/// Marks the currently running process with `next_state` and suspends it back to the scheduler. +pub(crate) fn suspend_current(next_state: ProcessState) { + let cpu = current_cpu(); + + let proc_ctx = { + let slot = unsafe { &mut *cpu.current_process.get() }; + let proc = slot + .as_deref_mut() + .expect("No running process on current CPU to suspend"); + proc.state = next_state; + &raw mut proc.context + }; -pub fn my_cpu() -> &'static mut Cpu { - unsafe { &mut (*CPUS.get())[0] } + unsafe { + Context::switch_from(proc_ctx).to(cpu.scheduler_context.get()); + } } diff --git a/xv7-kernel/src/fs/file.rs b/xv7-kernel/src/fs/file.rs index ce80775..40277d6 100644 --- a/xv7-kernel/src/fs/file.rs +++ b/xv7-kernel/src/fs/file.rs @@ -4,6 +4,7 @@ use alloc::sync::Arc; use super::vfs::Metadata; +#[derive(Clone)] pub struct File { inode: Arc, offset: usize, @@ -21,6 +22,26 @@ impl File { } } + pub fn inode(&self) -> Arc { + self.inode.clone() + } + + pub fn offset(&self) -> usize { + self.offset + } + + pub fn is_readable(&self) -> bool { + self.readable + } + + pub fn is_writable(&self) -> bool { + self.writable + } + + pub fn advance_offset(&mut self, delta: usize) { + self.offset += delta; + } + pub fn read(&mut self, buf: &mut [u8]) -> Result { assert!(self.readable); let len = self.inode.read_at(self.offset, buf)?; diff --git a/xv7-kernel/src/main.rs b/xv7-kernel/src/main.rs index 8acd1ff..8684186 100644 --- a/xv7-kernel/src/main.rs +++ b/xv7-kernel/src/main.rs @@ -28,8 +28,10 @@ mod video; pub use crate::arch::context; pub use crate::arch::paging; +pub use crate::arch::trapframe; pub fn kmain() -> ! { println!("We are alive!"); - scheduler::scheduler(); + scheduler::enqueue(process::Process::initcode()); + scheduler::run(); } diff --git a/xv7-kernel/src/process.rs b/xv7-kernel/src/process.rs index 4d4df07..305be79 100644 --- a/xv7-kernel/src/process.rs +++ b/xv7-kernel/src/process.rs @@ -1,22 +1,31 @@ -use crate::context::Context; -use crate::cpu::my_cpu; -use crate::fs::file::File; -use crate::paging::{AddressSpace, VirtAddr}; -use crate::{ - config::*, - memory::{FRAME_ALLOCATOR, FrameAllocator}, -}; +use alloc::boxed::Box; use alloc::vec::Vec; +use core::mem::size_of; use core::sync::atomic::{AtomicUsize, Ordering}; -use x86_64::registers::rflags::RFlags; -use x86_64::registers::segmentation::SegmentSelector; -use x86_64::structures::idt::InterruptStackFrameValue; +use goblin::elf; +use goblin::elf::reloc::R_X86_64_RELATIVE; + +use crate::config::*; +use crate::context::Context; +use crate::fs::file::File; +use crate::paging::{AddressSpace, KernelStack, VirtAddr}; +use crate::trapframe::TrapFrame; + +const USER_STACK_SIZE: usize = 4096; + +mod images { + #[cfg(debug_assertions)] + pub const INIT: &[u8] = include_bytes!("../../target/x86_64-unknown-none/debug/init"); + #[cfg(not(debug_assertions))] + pub const INIT: &[u8] = include_bytes!("../../target/x86_64-unknown-none/release/init"); +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ProcessState { - Spawn, Runnable, Running, - Zombie, + Zombie(isize), } static NEXT_PID: AtomicUsize = AtomicUsize::new(0); @@ -26,108 +35,76 @@ pub struct Process { pub state: ProcessState, pub vm: AddressSpace, pub context: Context, - pub kstack: VirtAddr, + pub kstack: KernelStack, pub fds: Vec, } impl Process { - pub fn new() -> Process { - let kstack = { - let frame = FRAME_ALLOCATOR.lock().allocate_frame().unwrap(); - VirtAddr::new(frame.start_address().as_u64() + PAGE_OFFSET_BASE) - }; - - let stack_pointer = - kstack + 4096u64 - core::mem::size_of::() as u64 - 8u64; - - let mut context = Context::user(stack_pointer); - + pub fn new() -> Box { + let kstack = KernelStack::alloc(); let vm = AddressSpace::new(); + let context = Context::init_user(kstack.top()); - context.cr3 = vm.cr3.start_address().as_u64() as usize; - - unsafe { - stack_pointer - .as_mut_ptr::() - .write(interrupt_return as *const u8 as u64); - }; - - Process { + Box::new(Self { pid: NEXT_PID.fetch_add(1, Ordering::Relaxed), - context, + state: ProcessState::Runnable, vm, - state: ProcessState::Spawn, + context, kstack, fds: Vec::new(), - } + }) } - pub fn initcode() -> Process { - let mut p = Process::new(); - p.set_context_switch_return_address(VirtAddr::new(initcode as *const u8 as u64)); - p + pub fn initcode() -> Box { + let mut proc = Self::new(); + proc.exec("/init"); + proc } - pub fn intr_stack_frame(&mut self) -> &mut InterruptStackFrameValue { - unsafe { - &mut *((self.kstack.as_u64() + 4096 - - core::mem::size_of::() as u64) - as *mut InterruptStackFrameValue) - } + /// Returns a mutable reference to the user `TrapFrame` stored at the top of `self.kstack`. + #[inline] + pub fn trap_frame_mut(&mut self) -> &mut TrapFrame { + let tf_addr = self.kstack.top() - size_of::() as u64; + unsafe { &mut *tf_addr.as_mut_ptr::() } } - fn set_context_switch_return_address(&mut self, addr: VirtAddr) { - let stack_pointer = - self.kstack + 4096u64 - core::mem::size_of::() as u64 - 8u64; - unsafe { - stack_pointer.as_mut_ptr::().write(addr.as_u64()); + pub fn exec(&mut self, path: &str) { + let image = match path { + "/init" => images::INIT, + _ => panic!("We have no filesystem yet; executables are hardcoded"), }; - } - pub fn set_userspace_return_address( - &mut self, - instruction_pointer: VirtAddr, - stack_pointer: VirtAddr, - ) { - self.intr_stack_frame().instruction_pointer = instruction_pointer; - self.intr_stack_frame().stack_pointer = stack_pointer; - // FIXME: magic number - self.intr_stack_frame().code_segment = SegmentSelector(0x23); - self.intr_stack_frame().stack_segment = SegmentSelector(0x1b); - self.intr_stack_frame().cpu_flags = RFlags::from_bits_retain(0x282); - } -} - -impl Clone for Process { - fn clone(&self) -> Self { - Process::new() - } -} + let image_elf = elf::Elf::parse(image).expect("Failed to parse ELF file"); + + for ph in image_elf.program_headers { + if ph.p_type == elf::program_header::PT_LOAD { + let vaddr = VirtAddr::new(ph.p_vaddr); + self.vm.map_user_range( + vaddr, + ph.p_memsz as usize, + ph.is_write(), + ph.is_executable(), + ); + self.vm.copy_to_user(vaddr, &image[ph.file_range()]); + } + } -#[unsafe(naked)] -unsafe extern "C" fn interrupt_return() { - core::arch::naked_asm!("iretq") -} + self.vm + .map_user_range(VirtAddr::new(USER_STACK), USER_STACK_SIZE, true, false); + + for reloc in image_elf.dynrelas.iter() { + match reloc.r_type { + R_X86_64_RELATIVE => { + let dst = VirtAddr::new(reloc.r_offset); + let val = reloc.r_addend.unwrap() as u64; + self.vm.write_user_u64(dst, val); + } + _ => unimplemented!("Unhandled reloc type!"), + } + } -#[unsafe(naked)] -unsafe extern "C" fn initcode() { - extern "C" fn initcode_exec() { - crate::syscall::process::exec("/init"); + let entry = VirtAddr::new(image_elf.entry); + let user_sp = VirtAddr::new(USER_STACK + USER_STACK_SIZE as u64 - 16); + self.trap_frame_mut().init_user(entry, user_sp); } - core::arch::naked_asm!( - "call {}", - "iretq", - sym initcode_exec, - ) -} - -#[allow(dead_code)] -#[unsafe(naked)] -unsafe extern "C" fn fork_return() { - core::arch::naked_asm!("retq"); -} - -pub fn my_proc() -> &'static mut Process { - let cpu = my_cpu(); - cpu.current_process.as_mut().unwrap() } diff --git a/xv7-kernel/src/scheduler.rs b/xv7-kernel/src/scheduler.rs index e40af65..d6dd37b 100644 --- a/xv7-kernel/src/scheduler.rs +++ b/xv7-kernel/src/scheduler.rs @@ -1,16 +1,59 @@ -use crate::cpu::my_cpu; -use crate::process::Process; +use alloc::boxed::Box; +use alloc::collections::VecDeque; -pub fn scheduler() -> ! { - let cpu = my_cpu(); - let p = Process::initcode(); +use spin::Mutex; - cpu.current_process = Some(p); +use crate::arch; +use crate::cpu; +use crate::process::{Process, ProcessState}; + +static RUN_QUEUE: Mutex>> = Mutex::new(VecDeque::new()); + +/// Enqueues a runnable process at the tail of the global run queue. +pub fn enqueue(mut proc: Box) { + proc.state = ProcessState::Runnable; + arch::without_interrupts(|| { + RUN_QUEUE.lock().push_back(proc); + }); +} + +/// Main per-CPU round-robin scheduler loop. +/// +/// Runs with interrupts masked (`IF == 0`) except when idling via `wait_for_interrupt`. +pub fn run() -> ! { + arch::disable_interrupts(); loop { - println!("[scheduler] pick next process to run"); - unsafe { - cpu.switch_to_process(); + let Some(proc) = RUN_QUEUE.lock().pop_front() else { + arch::wait_for_interrupt(); + continue; + }; + + let proc = cpu::resume(proc); + + match proc.state { + ProcessState::Runnable => RUN_QUEUE.lock().push_back(proc), + ProcessState::Zombie(code) => { + if proc.pid == 0 { + panic!("init (pid 0) exited with code {}", code); + } + } + ProcessState::Running => unreachable!("Process returned to scheduler while Running"), } } } + +/// Cooperatively yields the CPU from the current process back to the scheduler. +pub fn yield_now() { + arch::without_interrupts(|| { + cpu::suspend_current(ProcessState::Runnable); + }); +} + +/// Terminates the current process with `code` and switches back to the scheduler. +pub fn exit_current(code: isize) -> ! { + arch::without_interrupts(|| { + cpu::suspend_current(ProcessState::Zombie(code)); + }); + unreachable!("Zombie process resumed after exit") +} diff --git a/xv7-kernel/src/syscall/fs.rs b/xv7-kernel/src/syscall/fs.rs index d8c3888..576f6a5 100644 --- a/xv7-kernel/src/syscall/fs.rs +++ b/xv7-kernel/src/syscall/fs.rs @@ -1,10 +1,13 @@ -use crate::fs::FILE_SYSTEM; -use crate::fs::file::File; -use crate::{fs::dev::Console, process::my_proc}; use alloc::string::String; use alloc::sync::Arc; + use abi::error::*; +use crate::cpu::with_current_process; +use crate::fs::FILE_SYSTEM; +use crate::fs::dev::Console; +use crate::fs::file::File; + pub fn mknod(path: &str, dev: usize) -> Result { if dev == 1 { FILE_SYSTEM @@ -17,32 +20,57 @@ pub fn mknod(path: &str, dev: usize) -> Result { } pub fn open(path: &str) -> Result { - let proc = my_proc(); match FILE_SYSTEM.lock().get(path) { - None => dbg!(Err(Error::new(ENOENT))), + None => Err(Error::new(ENOENT)), Some(inode) => { let inode = inode.clone(); let file = File::new(inode, true, true); - proc.fds.push(file); - dbg!(Ok(proc.fds.len() - 1)) + with_current_process(|proc| { + proc.fds.push(file); + Ok(proc.fds.len() - 1) + }) } } } pub fn write(fd: usize, buf: &[u8]) -> Result { - let proc = my_proc(); + let (inode, offset, writable) = with_current_process(|proc| { + proc.fds + .get(fd) + .map(|f| (f.inode(), f.offset(), f.is_writable())) + }) + .ok_or_else(|| Error::new(ENOENT))?; - match proc.fds.get_mut(fd) { - Some(f) => f.write(buf).map_err(|_| Error::new(EFAULT)), - None => Err(Error::new(ENOENT)), + if !writable { + return Err(Error::new(EBADF)); } + + let len = inode.write_at(offset, buf).map_err(|_| Error::new(EFAULT))?; + with_current_process(|proc| { + if let Some(f) = proc.fds.get_mut(fd) { + f.advance_offset(len); + } + }); + Ok(len) } pub fn read(fd: usize, buf: &mut [u8]) -> Result { - let proc = my_proc(); + let (inode, offset, readable) = with_current_process(|proc| { + proc.fds + .get(fd) + .map(|f| (f.inode(), f.offset(), f.is_readable())) + }) + .ok_or_else(|| Error::new(ENOENT))?; - match proc.fds.get_mut(fd) { - Some(f) => f.read(buf).map_err(|_| Error::new(EFAULT)), - None => Err(Error::new(ENOENT)), + if !readable { + return Err(Error::new(EBADF)); } + + let len = inode.read_at(offset, buf).map_err(|_| Error::new(EFAULT))?; + with_current_process(|proc| { + if let Some(f) = proc.fds.get_mut(fd) { + f.advance_offset(len); + } + }); + Ok(len) } diff --git a/xv7-kernel/src/syscall/process.rs b/xv7-kernel/src/syscall/process.rs index 03ad781..0544da4 100644 --- a/xv7-kernel/src/syscall/process.rs +++ b/xv7-kernel/src/syscall/process.rs @@ -1,141 +1,21 @@ -use crate::process; -use crate::{ - config::*, - memory::{FRAME_ALLOCATOR, FrameAllocator}, -}; -use crate::{cpu::my_cpu, paging::VirtAddr}; -use goblin::elf; -use goblin::elf::reloc::*; -use x86_64::structures::paging::{Mapper, Page}; -use x86_64::structures::paging::{OffsetPageTable, PageTableFlags}; -use zeroize::Zeroize; - use abi::error::*; -pub fn exit(code: isize) -> Result { - let proc = process::my_proc(); - if proc.pid == 0 { - panic!("pid 0 exited with code {}", code); - } - Ok(0) -} - -pub fn exec(path: &str) { - let proc = process::my_proc(); - - let image = match path { - "/init" => images::INIT, - _ => panic!("We have no filesystem yet; executables are hardcoded"), - }; - - let image_elf = elf::Elf::parse(image).expect("Failed to parse ELF file"); - - let mut frame_allocator = FRAME_ALLOCATOR.lock(); - // FIXME: we should free the previous vm and set up a new vm - let page_table = unsafe { proc.vm.page_table() }; - let mut mapper = unsafe { OffsetPageTable::new(page_table, VirtAddr::new(PAGE_OFFSET_BASE)) }; - - for ph in image_elf.program_headers { - if ph.p_type == elf::program_header::PT_LOAD { - let page_range = { - let start_addr = VirtAddr::new(ph.p_vaddr); - let end_addr = start_addr + ph.p_memsz - 1u64; - let start_page = Page::containing_address(start_addr); - let end_page = Page::containing_address(end_addr); - Page::range_inclusive(start_page, end_page) - }; - - let mut flags = PageTableFlags::PRESENT - | PageTableFlags::USER_ACCESSIBLE - | PageTableFlags::WRITABLE; - //if ph.is_write() { - //} - if !ph.is_executable() { - flags |= PageTableFlags::NO_EXECUTE; - } - - for page in page_range { - let frame = frame_allocator.allocate_frame().unwrap(); - unsafe { - mapper - .map_to(page, frame, flags, &mut *frame_allocator) - .unwrap() - .flush(); - } - } +use crate::cpu::with_current_process; +use crate::scheduler; - let dst = unsafe { - core::slice::from_raw_parts_mut((ph.p_vaddr) as *mut u8, ph.vm_range().len()) - }; - - dst.zeroize(); - - dst[0..ph.file_range().len()].copy_from_slice(&image[ph.file_range()]); - } - } - - // allocate and map user stack. - { - let page = Page::containing_address(VirtAddr::new(USER_STACK)); - let frame = frame_allocator.allocate_frame().unwrap(); - let flags = PageTableFlags::PRESENT - | PageTableFlags::USER_ACCESSIBLE - | PageTableFlags::WRITABLE - | PageTableFlags::NO_EXECUTE; - - unsafe { - mapper - .map_to(page, frame, flags, &mut *frame_allocator) - .unwrap() - .flush(); - } - } - - // Relocate executable - for reloc in image_elf.dynrelas.iter() { - match reloc.r_type { - R_X86_64_RELATIVE => { - let addr = (reloc.r_offset) as *mut u64; - unsafe { - *addr = reloc.r_addend.unwrap() as u64; - } - } - _ => unimplemented!("Unhandled reloc type!"), - } - } - - // FIXME: magic number - proc.set_userspace_return_address( - VirtAddr::new(image_elf.entry), - VirtAddr::new(USER_STACK + 4096 - 16), - ); +pub fn exit(code: isize) -> Result { + scheduler::exit_current(code); } pub fn fork() -> Result { - let _proc = process::my_proc(); - - Ok(0) + Err(Error::new(ENOSYS)) } pub fn getpid() -> Result { - Ok(process::my_proc().pid) -} - -mod images { - #[cfg(debug_assertions)] - pub const INIT: &'static [u8] = - include_bytes!("../../../target/x86_64-unknown-none/debug/init"); - #[cfg(not(debug_assertions))] - pub const INIT: &'static [u8] = - include_bytes!("../../../target/x86_64-unknown-none/release/init"); + with_current_process(|proc| Ok(proc.pid)) } pub(crate) fn r#yield() -> Result { - let cpu = my_cpu(); - if cpu.current_process.is_some() { - unsafe { - cpu.switch_to_kernel(); - } - } + scheduler::yield_now(); Ok(0) }