milo

04 — Tasks and Scheduling

Milo models execution units as Kernel::Process::Process instances scheduled across a global intrusive runqueue (Kernel::Scheduler::Runqueue / Kernel::Scheduler) and intrusive sleep queues (Kernel::Process::WaitQueue), with AArch64 context-switch and exception-exit assembly in arch/aarch64-linux-gnu/boot.s and arch/aarch64-linux-gnu/cpu.cpp.

Execution Primitives & Process Lifecycle

Process Control Block (kernel/process/Process.hpp, kernel/process/Process.cpp)

Each Process is allocated from the kernel heap (MM::kzalloc) via Process::create(uint32_t ppid) and linked into a global doubly-linked process list (g_process_list_head..g_process_list_tail), subject to a dynamic process quota (default_rlimit_nproc() in kernel/process/resource.{hpp,cpp}, computed as ram_size / (1 MiB) with a minimum of 64).

Key resources and metadata owned by a Process:

Lifecycle States (ProcessState)

Context Switching (arch/aarch64-linux-gnu/boot.s, arch/aarch64-linux-gnu/cpu.cpp, kernel/hal/cpu.hpp)

Milo separates EL1 kernel-thread/task switching (HAL::KernelContext, 112 bytes) from EL0 user trap/execution frames (HAL::CpuContext, 288 bytes):

  1. Kernel Context Switch (cpu_switch_context in boot.s, called by AArch64CpuControl::switch_kernel_context): If x0 (prev) is non-null, saves callee-saved registers x19–x28, frame pointer x29, link register x30, and sp into prev; then loads x19–x30 and sp from x1 (next) and executes ret to resume next in EL1.

  2. New Kernel Thread Bootstrap (kernel_thread_trampoline in boot.s): Configured by HAL::Test::init_kernel_thread_context (arch_test.cpp) with x19 = entry, x20 = arg, x30 = &kernel_thread_trampoline, and 16-byte aligned sp. On first switch-in, the trampoline unmasks IRQs (msr daifclr, #2), passes x0 = x20, calls blr x19, and on return calls kthread_exit_trampoline -> Kernel::Process::exit_current_process(0).

  3. New User Process Kernel Stack (AArch64CpuControl::init_user_kstack in cpu.cpp): Copies user_ctx (HAL::CpuContext) onto the top of the kernel stack (kstack_top - sizeof(HAL::CpuContext)), sets arch_kctx->x30 = &user_trap_exit and arch_kctx->sp = frame_addr. When switched in via cpu_switch_context, ret jumps to user_trap_exit (boot.s), which restores sp_el0, elr_el1, spsr_el1, tpidr_el0, and x0–x30 and executes eret into EL0.

  4. Direct / Legacy EL0 Context Helpers (enter_user_mode, enter_user_context, return_to_kernel in boot.s): Save EL1 callee-saved registers into global kernel_ctx and eret into EL0 (spsr_el1 = 0x0 for EL0t); return_to_kernel restores kernel_ctx and returns to the caller.

Scheduler Algorithm & Timers

Runqueue, Preemption & Idle Loop (kernel/process/scheduler.hpp, kernel/process/scheduler.cpp)