ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
//! Chapter 6 Grader: Process Management
//!
//! Tests: ProcessId, ProcessState, ProcessContext, PCB,
//! scheduler operations, fork/exec/wait/exit.

#![allow(clippy::vec_init_then_push)]

use super::*;
use crate::process::{ProcessContext, ProcessControlBlock, ProcessId, ProcessState};
use crate::syscall::SyscallId;

pub struct Chapter6Grader {
    results: Vec<TaskResult>,
}

impl Chapter6Grader {
    pub fn new() -> Self {
        Self {
            results: Vec::new(),
        }
    }

    fn add(&mut self, task_id: usize, name: &'static str, points: u32, details: Vec<GradeDetail>) {
        self.results.push(TaskResult {
            task_id,
            name,
            points,
            details,
        });
    }
}

impl Default for Chapter6Grader {
    fn default() -> Self {
        Self::new()
    }
}

impl Grade for Chapter6Grader {
    fn chapter_number(&self) -> u32 {
        6
    }
    fn chapter_name(&self) -> &'static str {
        "Process Management"
    }
    fn total_tasks(&self) -> usize {
        10
    }
    fn total_points(&self) -> u32 {
        80
    }

    fn check_all(&mut self) {
        self.results.clear();
        self.check_pid_allocator();
        self.check_process_state();
        self.check_process_context();
        self.check_pcb_basics();
        self.check_pcb_children();
        self.check_scheduler_create();
        self.check_scheduler_add();
        self.check_fork_exists();
        self.check_exec_wait_exit_exist();
        self.check_integration();
    }

    fn results(&self) -> &[TaskResult] {
        &self.results
    }
}

impl Chapter6Grader {
    // Task 1: PID allocator
    fn check_pid_allocator(&mut self) {
        let p1 = ProcessId::new();
        let p2 = ProcessId::new();
        let p3 = ProcessId::new();

        let mut details = Vec::new();
        details.push(check_condition(
            p1 != p2 && p2 != p3 && p1 != p3,
            "PID allocator returns unique IDs",
            "PIDs should be unique",
        ));
        // PIDs start from a counter — newer PIDs should be larger
        details.push(pass(alloc::format!(
            "Allocated PIDs: {}, {}, {}",
            p1,
            p2,
            p3
        )));

        self.add(1, "PID allocator uniqueness", 6, details);
    }

    // Task 2: ProcessState transitions
    fn check_process_state(&mut self) {
        let mut details = Vec::new();

        details.push(check_condition(
            ProcessState::Ready.can_schedule(),
            "Ready state can be scheduled",
            "Ready.can_schedule() should be true",
        ));
        details.push(check_condition(
            !ProcessState::Running.can_schedule(),
            "Running state cannot be scheduled",
            "Running.can_schedule() should be false",
        ));
        details.push(check_condition(
            !ProcessState::Zombie.can_schedule(),
            "Zombie state cannot be scheduled",
            "Zombie.can_schedule() should be false",
        ));

        // Valid transitions
        details.push(check_condition(
            ProcessState::Ready.can_transition_to(ProcessState::Running),
            "Ready → Running transition valid",
            "Ready → Running should be valid",
        ));
        details.push(check_condition(
            ProcessState::Running.can_transition_to(ProcessState::Zombie),
            "Running → Zombie transition valid",
            "Running → Zombie should be valid",
        ));
        details.push(check_condition(
            ProcessState::Blocked.can_transition_to(ProcessState::Ready),
            "Blocked → Ready transition valid",
            "Blocked → Ready should be valid",
        ));

        self.add(2, "ProcessState transitions", 8, details);
    }

    // Task 3: ProcessContext
    fn check_process_context(&mut self) {
        let mut ctx = ProcessContext::new();
        ctx.set_ra(0x80200000);
        ctx.set_sp(0x80300000);

        let mut details = Vec::new();
        details.push(check_condition(
            ctx.ra() == 0x80200000,
            "RA stored and retrieved correctly",
            "RA mismatch",
        ));
        details.push(check_condition(
            ctx.sp() == 0x80300000,
            "SP stored and retrieved correctly",
            "SP mismatch",
        ));
        details.push(pass("ProcessContext fields accessible"));

        self.add(3, "ProcessContext read/write", 6, details);
    }

    // Task 4: PCB basics
    fn check_pcb_basics(&mut self) {
        let pid = ProcessId::new();
        let pcb = ProcessControlBlock::new(pid, "test_proc", None);

        let mut details = Vec::new();
        details.push(check_condition(
            pcb.name() == "test_proc",
            "PCB name stored correctly",
            "PCB name mismatch",
        ));
        details.push(check_condition(
            pcb.children().is_empty(),
            "New PCB has no children",
            "New PCB should have empty children",
        ));
        details.push(pass(alloc::format!(
            "PCB created: PID={} name='{}'",
            pid,
            pcb.name()
        )));

        self.add(4, "PCB creation and fields", 8, details);
    }

    // Task 5: PCB parent-child relationships
    fn check_pcb_children(&mut self) {
        let parent_pid = ProcessId::new();
        let child_pid = ProcessId::new();
        let mut parent = ProcessControlBlock::new(parent_pid, "parent", None);
        parent.add_child(child_pid);

        let mut details = Vec::new();
        details.push(check_condition(
            parent.children().len() == 1,
            "Child added to parent",
            "Parent should have 1 child",
        ));
        details.push(pass(alloc::format!(
            "Parent PID={} has child PID={}",
            parent_pid,
            child_pid
        )));

        self.add(5, "PCB parent-child relationship", 8, details);
    }

    // Task 6: Scheduler creation
    fn check_scheduler_create(&mut self) {
        use crate::process::RoundRobinScheduler;
        let sched = RoundRobinScheduler::new(10);

        let mut details = Vec::new();
        // New scheduler should have no current task
        details.push(pass("RoundRobinScheduler created with time_slice=10"));
        details.push(check_condition(
            sched.current().is_none(),
            "New scheduler has no current task",
            "New scheduler should start empty",
        ));

        core::mem::drop(sched);
        self.add(6, "Scheduler initialisation", 8, details);
    }

    // Task 7: Add processes to scheduler
    fn check_scheduler_add(&mut self) {
        use crate::process::RoundRobinScheduler;
        let mut sched = RoundRobinScheduler::new(10);
        let p1 = ProcessId::new();
        let p2 = ProcessId::new();
        let proc1 = alloc::boxed::Box::new(ProcessControlBlock::new(p1, "p1", None));
        let proc2 = alloc::boxed::Box::new(ProcessControlBlock::new(p2, "p2", None));

        let r1 = sched.add_process(proc1);
        let r2 = sched.add_process(proc2);

        let mut details = Vec::new();
        details.push(check_condition(
            r1.is_ok(),
            "Process 1 added",
            "Failed to add process 1",
        ));
        details.push(check_condition(
            r2.is_ok(),
            "Process 2 added",
            "Failed to add process 2",
        ));
        details.push(pass("Two processes registered in scheduler"));

        self.add(7, "Scheduler add_process", 8, details);
    }

    // Task 8: fork mechanism exists
    fn check_fork_exists(&mut self) {
        let mut details = Vec::new();
        // Verify fork syscall ID is defined
        details.push(check_condition(
            SyscallId::from(220) == SyscallId::Fork,
            "fork syscall ID 220 defined",
            "fork syscall ID missing",
        ));
        details.push(pass(
            "fork_current() entry point available in process/mod.rs",
        ));
        self.add(8, "fork system call presence", 8, details);
    }

    // Task 9: exec/wait/exit mechanisms exist
    fn check_exec_wait_exit_exist(&mut self) {
        let mut details = Vec::new();
        details.push(check_condition(
            SyscallId::from(221) == SyscallId::Exec,
            "exec syscall ID 221 defined",
            "exec syscall ID missing",
        ));
        details.push(check_condition(
            SyscallId::from(260) == SyscallId::Wait,
            "wait syscall ID 260 defined",
            "wait syscall ID missing",
        ));
        details.push(check_condition(
            SyscallId::from(93) == SyscallId::Exit,
            "exit syscall ID 93 defined",
            "exit syscall ID missing",
        ));
        details.push(pass("exec/exit/wait entry points in process/mod.rs"));
        self.add(9, "exec/wait/exit presence", 8, details);
    }

    // Task 10: Integration check
    fn check_integration(&mut self) {
        let mut details = Vec::new();
        details.push(pass("Process management module compiles without errors"));
        details.push(pass("SCHEDULER static is accessible"));
        details.push(pass(
            "All syscall IDs (fork/exec/wait/exit/getpid) registered",
        ));
        self.add(10, "Module integration", 12, details);
    }
}