Skip to main content

os/process/
mod.rs

1//! Process Management Module
2//!
3//! Chapter 6 - Process Management Experiment
4
5pub mod pid;
6pub use pid::ProcessId;
7
8pub mod pcb;
9pub use pcb::{ProcessControlBlock, ProcessState};
10
11pub mod context;
12pub use context::{
13    ProcessContext, PROCESS_CONTEXT_SATP_OFFSET, PROCESS_CONTEXT_SEPC_OFFSET,
14    PROCESS_CONTEXT_SSTATUS_OFFSET,
15};
16
17pub mod scheduler;
18pub mod state; // PTA ex5: Rust enum+match exercise
19pub use scheduler::RoundRobinScheduler;
20
21pub mod elf;
22pub mod switch;
23pub mod user;
24pub mod user_elf;
25
26use crate::println;
27use alloc::boxed::Box;
28use core::sync::atomic::{AtomicBool, Ordering};
29use lazy_static::lazy_static;
30use spin::Mutex;
31
32// ── Global scheduler ──────────────────────────────────────────────
33
34lazy_static! {
35    pub static ref SCHEDULER: Mutex<RoundRobinScheduler> = Mutex::new(RoundRobinScheduler::new(5));
36}
37
38static mut SCHEDULER_STARTED: bool = false;
39
40// ── Global frame allocator (single-cpu, interrupt-safe) ─
41
42use crate::memory::{PhysAddr, SimpleFrameAllocator};
43
44static mut FRAME_ALLOCATOR: Option<SimpleFrameAllocator> = None;
45static FRAME_ALLOCATOR_BUSY: AtomicBool = AtomicBool::new(false);
46
47lazy_static! {
48    static ref KERNEL_PAGE_TABLE_PADDR: Mutex<Option<usize>> = Mutex::new(None);
49}
50
51pub fn init_frame_allocator_from(kernel_end: usize) {
52    let memory_end = 0x8000_0000usize + 128 * 1024 * 1024;
53    let allocator = SimpleFrameAllocator::new(kernel_end, memory_end);
54    unsafe {
55        FRAME_ALLOCATOR = Some(allocator);
56    }
57}
58
59pub fn set_kernel_page_table_paddr(paddr: PhysAddr) {
60    *KERNEL_PAGE_TABLE_PADDR.lock() = Some(paddr.as_usize());
61}
62
63pub fn kernel_page_table_paddr() -> Option<PhysAddr> {
64    let paddr = *KERNEL_PAGE_TABLE_PADDR.lock();
65    paddr.map(PhysAddr::new)
66}
67
68#[allow(static_mut_refs)]
69pub fn with_frame_allocator<F, R>(f: F) -> R
70where
71    F: FnOnce(&mut SimpleFrameAllocator) -> R,
72{
73    if FRAME_ALLOCATOR_BUSY.swap(true, Ordering::Acquire) {
74        panic!("frame allocator reentered — interrupt-in-allocator detected");
75    }
76    let result = unsafe { f(FRAME_ALLOCATOR.as_mut().expect("frame allocator not set")) };
77    FRAME_ALLOCATOR_BUSY.store(false, Ordering::Release);
78    result
79}
80
81// ── Task trap ─────────────────────────────────────────────────────
82
83extern "C" fn task_trap() -> ! {
84    crate::serial_println!("[TASK] Kernel task returned unexpectedly — halting");
85    crate::hlt_loop();
86}
87
88// ── sstatus helpers ───────────────────────────────────────────────
89
90fn kernel_sstatus_init() -> usize {
91    let raw: usize;
92    unsafe {
93        core::arch::asm!("csrr {}, sstatus", out(reg) raw);
94    }
95    (raw | (1 << 8) | (1 << 5)) & !(1 << 1) // SPP=1 SPIE=1 SIE=0
96}
97
98// ── Create kernel-level task ──────────────────────────────────────
99
100/// Create a kernel task PCB backed by the supplied stack.
101///
102/// # Safety
103///
104/// `stack` must be a valid, uniquely owned 4 KiB task stack that remains
105/// alive and unmoved for as long as the returned PCB can be scheduled.
106pub unsafe fn create_kernel_task(
107    pid: ProcessId,
108    name: &'static str,
109    entry: extern "C" fn() -> !,
110    stack: *mut [u8; 4096],
111) -> Box<ProcessControlBlock> {
112    let mut pcb = ProcessControlBlock::new(pid, name, None);
113    let ctx = pcb.context_mut();
114
115    let stack_ptr = unsafe { (*stack).as_mut_ptr() };
116    ctx.set_ra(task_trap as *const () as usize);
117    ctx.set_sp(stack_ptr as usize + 4096);
118    ctx.set_sepc(entry as usize);
119    ctx.set_sstatus(kernel_sstatus_init());
120    ctx.set_satp(riscv::register::satp::read().bits());
121
122    Box::new(pcb)
123}
124
125// ── Bootstrap the first task ──────────────────────────────────────
126
127/// # Safety
128///
129/// Caller must ensure `ctx` points to a valid, properly initialised
130/// `ProcessContext` that matches the task the scheduler has selected
131/// as current.  This function disables interrupts and jumps into
132/// assembly (`__start_first_task`) which never returns.
133pub unsafe fn start_first_task(ctx: *const ProcessContext) {
134    SCHEDULER_STARTED = true;
135    riscv::register::sstatus::clear_sie();
136
137    // Set sscratch to the dedicated trap stack so traps find a clean stack.
138    unsafe {
139        core::arch::asm!("csrw sscratch, {}", in(reg) crate::interrupts::trap_stack_top());
140    }
141
142    switch::__start_first_task(ctx);
143}
144
145// ── Scheduling — called from timer interrupt ──────────────────────
146
147/// Called on every timer tick with the current trap frame.
148/// If the scheduler picks a different task, the trap frame is
149/// updated in-place so that `trap_return` resumes the new task.
150pub fn scheduler_tick(tf: &mut crate::interrupts::TrapFrame) {
151    let mut sched = SCHEDULER.lock();
152
153    // Save interrupted task's state from trap frame to its PCB
154    if let Some(pcb) = sched.current_mut() {
155        tf.save_to(pcb.context_mut());
156    }
157
158    // Run scheduler tick (may switch current task)
159    sched.tick();
160
161    // Load the (possibly new) current task's state into the trap frame
162    if let Some(pcb) = sched.current() {
163        tf.load_from(pcb.context());
164    }
165}
166
167pub fn debug_scheduler_state() {
168    let sched = SCHEDULER.lock();
169    let stats = sched.stats();
170    println!(
171        "  [SCHED] current={:?}, ready={}, blocked={}, zombies={}, total={}, is_idle={}",
172        sched.current().map(|p| (p.name(), p.pid().as_usize())),
173        stats.ready,
174        stats.blocked,
175        stats.zombies,
176        stats.total,
177        sched.is_idle(),
178    );
179}
180
181// ── Fork: deep-copy address space → new PCB → add to scheduler ──
182
183/// Fork the current user process by deep-copying the parent's user pages.
184/// Returns child PID (to parent) or 0 (to child).
185pub fn fork_current(tf: &crate::interrupts::TrapFrame) -> isize {
186    let (parent_pid, parent_satp) = {
187        let sched = SCHEDULER.lock();
188        let current = match sched.current() {
189            Some(p) => p,
190            None => return -1isize,
191        };
192        (current.pid(), current.context().satp)
193    };
194
195    let child_satp = match with_frame_allocator(|allocator| {
196        crate::memory::address_space::deep_copy_user_address_space(parent_satp, allocator)
197    }) {
198        Ok(satp) => satp,
199        Err(reason) => {
200            crate::serial_println!("[FORK] address-space copy failed: {}", reason);
201            return -1isize;
202        }
203    };
204
205    // Build child PCB
206    let child_pid = ProcessId::new();
207    let mut child_pcb = ProcessControlBlock::new(child_pid, "child", Some(parent_pid));
208
209    {
210        let child_ctx = child_pcb.context_mut();
211        // Copy parent registers from trap frame (x1-x31)
212        child_ctx.x.copy_from_slice(&tf.x[1..]);
213        child_ctx.x[9] = 0; // a0 = 0 for child
214        child_ctx.sepc = tf.sepc.wrapping_add(4);
215        // Return with SIE disabled in the saved status, but keep SPIE set so
216        // sret re-enables timer preemption when the child reaches user mode.
217        child_ctx.sstatus = (tf.sstatus | (1 << 5)) & !(1 << 1);
218        child_ctx.satp = child_satp;
219    }
220
221    // Add child to parent's children list before queueing it.
222    let mut sched = SCHEDULER.lock();
223    if let Some(parent) = sched.current_mut() {
224        if parent.pid() != parent_pid {
225            return -1isize;
226        }
227        parent.add_child(child_pid);
228    } else {
229        return -1isize;
230    }
231
232    if sched.add_process(Box::new(child_pcb)).is_err() {
233        if let Some(parent) = sched.current_mut() {
234            parent.remove_child(child_pid);
235        }
236        return -1isize;
237    }
238
239    crate::serial_println!(
240        "[FORK] parent={} child={} satp={:#x}",
241        parent_pid.as_usize(),
242        child_pid.as_usize(),
243        child_satp
244    );
245
246    child_pid.as_usize() as isize
247}
248
249// ── Exec: replace process image with new ELF ─────────────────────
250
251/// Replace the current process image with a new ELF loaded from `path`.
252/// FD table is preserved; address space and context are rebuilt.
253///
254/// Current ownership contract: the scheduler/PCB stores the installed `satp`
255/// in `ProcessContext`, but it does not yet own an `AddressSpace` object or
256/// reclaim old user frames on exec/exit. `exec_current` therefore installs a
257/// fresh page-table root and documents the remaining lifecycle gap instead of
258/// pretending to provide full POSIX-style address-space replacement.
259pub fn exec_current(path: &str) -> isize {
260    use crate::fs::vfs::open_file;
261
262    // Read ELF bytes from VFS
263    let file = match open_file(path) {
264        Ok(f) => f,
265        Err(_) => return -1isize,
266    };
267
268    let mut elf_data = alloc::vec![0u8; 65536];
269    let n = match file.lock().read(&mut elf_data) {
270        Ok(n) => n,
271        Err(_) => return -1isize,
272    };
273    elf_data.truncate(n);
274
275    let elf = match elf::Elf::parse(&elf_data) {
276        Ok(e) => e,
277        Err(_) => return -1isize,
278    };
279
280    with_frame_allocator(|allocator| {
281        // Use the boot-created kernel root, not the current user SATP saved by
282        // the trap path. Copying from the old user root would preserve stale
283        // user mappings across exec and can collide with the new ELF mappings.
284        let kernel_paddr = match kernel_page_table_paddr() {
285            Some(paddr) => paddr,
286            None => return -1isize,
287        };
288
289        let new_addr_space =
290            match user::create_user_address_space(&elf, &elf_data, allocator, kernel_paddr) {
291                Ok(a) => a,
292                Err(_) => return -1isize,
293            };
294
295        let new_satp = {
296            let ppn = new_addr_space.page_table_paddr().as_usize() >> 12;
297            (8usize << 60) | ppn
298        };
299        // The live process context owns only the SATP value today.  Page-table
300        // frames are allocator-backed and remain valid, while AddressSpace
301        // metadata is not retained by PCB yet; add a PCB-owned memory object
302        // before implementing frame reclamation or demand paging.
303
304        let user_stack_top = 0x7FFF_F000usize;
305
306        let mut sched = SCHEDULER.lock();
307        if let Some(pcb) = sched.current_mut() {
308            let ctx = pcb.context_mut();
309            ctx.x = [0; 31];
310            ctx.set_ra(0);
311            ctx.set_sp(user_stack_top);
312            ctx.set_sepc(elf.entry);
313            // SPP=0 (User), SPIE=1, SUM=1
314            let raw: usize;
315            unsafe {
316                core::arch::asm!("csrr {}, sstatus", out(reg) raw);
317            }
318            ctx.set_sstatus((raw | (1 << 5) | (1 << 18)) & !((1 << 8) | (1 << 1)));
319            ctx.set_satp(new_satp);
320        }
321
322        crate::serial_println!(
323            "[EXEC] Loaded ELF '{}' entry={:#x} satp={:#x}",
324            path,
325            elf.entry,
326            new_satp
327        );
328        0
329    })
330}
331
332/// Replace the current image and, on success, copy the new process context into
333/// the live trap frame that `trap_return` will restore.
334///
335/// `exec_current()` updates the PCB-owned `ProcessContext`.  That is sufficient
336/// for future scheduler switches, but the current syscall returns through the
337/// already-saved [`TrapFrame`].  A successful exec therefore must *not* advance
338/// the old `sepc`; it must install the new context into the live frame so sret
339/// enters the new ELF image with its new SATP.
340pub fn exec_current_into_trap_frame(tf: &mut crate::interrupts::TrapFrame, path: &str) -> isize {
341    let ret = exec_current(path);
342    if ret != 0 {
343        return ret;
344    }
345
346    let sched = SCHEDULER.lock();
347    if let Some(pcb) = sched.current() {
348        tf.load_from(pcb.context());
349        0
350    } else {
351        -1
352    }
353}
354
355// ── Exit: mark as Zombie and switch to next task ────────────────
356
357/// Exit the current process. Does NOT return — jumps to `trap_return`.
358pub fn exit_current_and_switch(tf: &mut crate::interrupts::TrapFrame, exit_code: i32) -> ! {
359    let switched = {
360        let mut sched = SCHEDULER.lock();
361        let parent_pid = if let Some(pcb) = sched.current_mut() {
362            pcb.set_exit_code(exit_code);
363            crate::serial_println!(
364                "[EXIT] PID={} exit_code={} parent={:?}",
365                pcb.pid().as_usize(),
366                exit_code,
367                pcb.parent_pid()
368            );
369            pcb.parent_pid()
370        } else {
371            None
372        };
373        // Unblock parent if it's waiting (state == Blocked)
374        if let Some(ppid) = parent_pid {
375            sched.unblock_process(ppid);
376        }
377        sched.schedule();
378        if let Some(pcb) = sched.current() {
379            tf.load_from(pcb.context());
380            true
381        } else {
382            false
383        }
384    };
385    if !switched {
386        crate::serial_println!("[EXIT] no runnable process remains; halting");
387        crate::hlt_loop();
388    }
389    // trap_return reads the TrapFrame from sp, but this function's
390    // prologue has moved sp ~0x200 bytes below the frame.  Restore sp
391    // from the tf pointer so the assembly loads the correct registers.
392    let tf_addr = tf as *const _ as usize;
393    unsafe {
394        core::arch::asm!(
395            "mv sp, {tf}",
396            "j trap_return",
397            tf = in(reg) tf_addr,
398            options(noreturn)
399        );
400    }
401}
402
403// ── PTA injection point ─────────────────────────────────────────
404// STUDENT_CODE_HERE
405
406// ── Wait: collect zombie child ──────────────────────────────────
407
408/// Wait for any child to exit. If a zombie exists, returns its PID.
409/// If children exist but none are zombies, blocks the current process
410/// and jumps directly to trap_return (does NOT return).
411/// If no ready task can run while the parent is blocked, returns EBUSY
412/// instead of parking the parent without a runnable handoff.
413/// Returns -1 if no children exist.
414pub fn wait_current(tf: &mut crate::interrupts::TrapFrame, exit_code_ptr: usize) -> isize {
415    let mut sched = SCHEDULER.lock();
416
417    let parent_pid = match sched.current() {
418        Some(p) => p.pid(),
419        None => return -1,
420    };
421
422    // Check for zombie children
423    if let Some((child_pid, code)) = sched.find_zombie_child(parent_pid) {
424        let child_pid_value = child_pid.as_usize();
425        drop(sched);
426
427        if exit_code_ptr != 0
428            && crate::syscall::user_ptr::raw_write_value(exit_code_ptr, code).is_err()
429        {
430            return -1;
431        }
432
433        let mut sched = SCHEDULER.lock();
434        sched.remove_zombie(child_pid);
435        drop(sched);
436
437        crate::serial_println!(
438            "[WAIT] Reaped zombie PID={} exit_code={}",
439            child_pid_value,
440            code
441        );
442        return child_pid_value as isize;
443    }
444
445    // Check if there are living children to wait for
446    if sched.has_living_children(parent_pid) {
447        if sched.ready_count() == 0 {
448            crate::serial_println!(
449                "[WAIT] PID={} has living children but no runnable handoff task",
450                parent_pid.as_usize()
451            );
452            return crate::errno::EBUSY;
453        }
454
455        // Advance sepc past the ecall before saving context, so the
456        // parent resumes at the next instruction when it is woken up.
457        tf.sepc = tf.sepc.wrapping_add(4);
458        // Block current and manually pick next Runnable process
459        if let Some(pcb) = sched.current_mut() {
460            tf.save_to(pcb.context_mut());
461            pcb.set_state(ProcessState::Blocked)
462                .expect("running process can block on wait");
463        }
464        // Manually pick next Ready task from ready queue
465        let next = sched.pick_next_ready();
466        if let Some(pcb) = next {
467            tf.load_from(pcb.context());
468        }
469        drop(sched);
470        let tf_addr = tf as *const _ as usize;
471        unsafe {
472            core::arch::asm!(
473                "mv sp, {tf}",
474                "j trap_return",
475                tf = in(reg) tf_addr,
476                options(noreturn)
477            );
478        }
479    }
480
481    -1isize
482}