Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/aienux/patches/ce6f25074c52d666
# aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
## GitHub aien-dev/aienux#105 (code only)
closed derived `ce6f25074c52d666` #105
Imported from GitHub aien-dev/aienux#105 (code only)
GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).
Base `0b0dc8234c6ab3205a31760c98fcd9a0c2c74eda` · Head `5d8e3329cf4121537e57e63dbc63b4b18bbf6a15`
### Apply it
```
git checkout -b patch-ce6f25074c52d666 0b0dc8234c6ab3205a31760c98fcd9a0c2c74eda
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/ce6f25074c52d666.patch | git am
```
Raw patch (mbox) · Diff
### Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
```
github-import 1
aien-dev/aienux
105
5d8e3329cf4121537e57e63dbc63b4b18bbf6a15
```
```
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":105,"url":"https://github.com/aien-dev/aienux/pull/105","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:44Z","metadata":"unavailable","state_derived":true}
```
### Changes
```
diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs
index 43763557..e4773c58 100644
--- a/crates/aienos-boot/src/handoff.rs
+++ b/crates/aienos-boot/src/handoff.rs
@@ -448,29 +448,9 @@ static CONSOLE: SpinLock> = SpinLock::new(None);
static FREQUENCY_HZ: AtomicU64 = AtomicU64::new(0);
static FRAMEBUFFER: SpinLock > = SpinLock::new(None);
static IRQ_TICKS: AtomicU64 = AtomicU64::new(0);
-static TIMER_DEADLINE: AtomicU64 = AtomicU64::new(0);
extern "C" fn timer_irq() {
- let mut cpu = aienos_kernel::gic::Aarch64GicCpuInterface;
- let id = aienos_kernel::gic::GicCpuInterface::acknowledge(&mut cpu);
- if id == 30 {
- IRQ_TICKS.fetch_add(1, Ordering::Relaxed);
- let next = TIMER_DEADLINE.load(Ordering::Relaxed);
- let frequency = aienos_kernel::timer::TimerRegisters::frequency(
- &aienos_kernel::timer::Aarch64TimerRegisters,
- );
- let deadline = next.wrapping_add(frequency / 100);
- TIMER_DEADLINE.store(deadline, Ordering::Relaxed);
- let mut timer = aienos_kernel::timer::Aarch64TimerRegisters;
- aienos_kernel::timer::TimerRegisters::set_compare(&mut timer, deadline);
- aienos_kernel::timer::TimerRegisters::enable_timer(&mut timer, true);
- }
- // End every acknowledged interrupt (not just the timer), or it stays
- // active in the GIC and blocks its priority level. INTIDs 1020-1023 are
- // special/spurious and must not be ended.
- if id < 1020 {
- aienos_kernel::gic::GicCpuInterface::end_interrupt(&mut cpu, id);
- }
+ IRQ_TICKS.fetch_add(1, Ordering::Relaxed);
}
fn run_timer_window(gic: Option) -> Option<(u64, u64)> {
@@ -496,7 +476,6 @@ fn run_timer_window(gic: Option) -> Option<(u64, u64)> {
let hz = aienos_kernel::timer::TimerRegisters::frequency(&timer);
let start = aienos_kernel::timer::TimerRegisters::counter(&timer);
let deadline = start.wrapping_add(hz / 100);
- TIMER_DEADLINE.store(deadline, Ordering::Relaxed);
aienos_kernel::timer::TimerRegisters::set_compare(&mut timer, deadline);
aienos_kernel::timer::TimerRegisters::enable_timer(&mut timer, true);
aienos_kernel::fatal::set_irq_hook(timer_irq);
@@ -1379,6 +1358,34 @@ fn main() -> Status {
},
el0.exit_code,
);
+ let (preempt_a, preempt_b, preempt_switches) =
+ unsafe { aienos_kernel::thread::run_preemption_demo() };
+ let preempt_ok = preempt_a > 0 && preempt_b > 0 && preempt_switches >= 4;
+ let _ = writeln!(
+ report,
+ "preempt: {} a={preempt_a} b={preempt_b} switches={preempt_switches}",
+ if preempt_ok { "ok" } else { "failed" }
+ );
+ match acpi_facts.cpu.as_ref() {
+ Some(topology) => {
+ let mut placement = ReportBuf::<128>::new();
+ let _ = write!(placement, "placement:");
+ for (index, name) in [(0u32, "worker0"), (1u32, "worker1")] {
+ match aienos_kernel::thread::place_task(topology, index) {
+ Some((class, core)) => {
+ let _ = write!(placement, " {name}=class{class}/core{core}");
+ }
+ None => {
+ let _ = write!(placement, " {name}=unplaced");
+ }
+ }
+ }
+ let _ = writeln!(report, "{}", placement.as_str());
+ }
+ None => {
+ let _ = writeln!(report, "placement: unavailable");
+ }
+ }
let _ = writeln!(
report,
"runtime_code: {}",
diff --git a/crates/aienos-kernel/src/fatal.rs b/crates/aienos-kernel/src/fatal.rs
index f81065a7..75cdf86a 100644
--- a/crates/aienos-kernel/src/fatal.rs
+++ b/crates/aienos-kernel/src/fatal.rs
@@ -172,8 +172,9 @@ static IRQ_HOOK: AtomicUsize = AtomicUsize::new(0);
pub fn set_irq_hook(hook: extern "C" fn()) {
IRQ_HOOK.store(hook as usize, Ordering::SeqCst);
}
-#[cfg(target_arch = "aarch64")]
-fn call_irq_hook() {
+
+#[cfg_attr(not(target_arch = "aarch64"), allow(dead_code))]
+pub fn call_irq_hook() {
let raw = IRQ_HOOK.load(Ordering::SeqCst);
if raw != 0 {
let hook: extern "C" fn() = unsafe { core::mem::transmute(raw) };
@@ -198,7 +199,7 @@ fn call_hook(info: &FaultInfo) -> ! {
#[cfg(target_arch = "aarch64")]
mod vectors {
- use super::{call_hook, call_irq_hook, FaultInfo};
+ use super::{call_hook, FaultInfo};
use crate::arch::aarch64::current_el;
const STACK_BYTES: usize = 16 * 1024;
@@ -213,13 +214,12 @@ mod vectors {
let v: u64;
// SAFETY: reading a syndrome register of the current EL has no side effects.
unsafe {
- core::arch::asm!(concat!("mrs {0}, ", $name), out(reg) v, options(nomem, nostack, preserves_flags));
+ core::arch::asm!(concat!("mrs {0}, ", $name), out(reg) v, options(nomem, nostack));
}
v
}};
}
- /// Entered from the vector table on the exception stack.
#[no_mangle]
extern "C" fn aienos_exception_handler(vector: u64) -> ! {
let el = current_el();
@@ -263,12 +263,10 @@ mod vectors {
"b aienos_exception_trampoline",
".endif",
".endr",
- // IRQ entry: save everything the handler (Rust, AAPCS64) may clobber:
- // x0-x18 and x30, ELR/SPSR_EL1, FPCR/FPSR, and SIMD/FP caller-saved
- // q0-q7 and q16-q31 (compiler-generated SIMD must not corrupt the
- // interrupted code). Frame: 576 bytes, 16-byte aligned.
+ // IRQ entry: save complete interrupted context into TrapFrame on the current stack:
+ // x0-x30, pad, ELR/SPSR_EL1, FPCR/FPSR, and SIMD/FP q0-q31. Frame: 800 bytes, 16-byte aligned.
"aienos_irq_trampoline:",
- "sub sp, sp, #576",
+ "sub sp, sp, #800",
"stp x0, x1, [sp, #0]",
"stp x2, x3, [sp, #16]",
"stp x4, x5, [sp, #32]",
@@ -278,45 +276,61 @@ mod vectors {
"stp x12, x13, [sp, #96]",
"stp x14, x15, [sp, #112]",
"stp x16, x17, [sp, #128]",
- "stp x18, x30, [sp, #144]",
+ "stp x18, x19, [sp, #144]",
+ "stp x20, x21, [sp, #160]",
+ "stp x22, x23, [sp, #176]",
+ "stp x24, x25, [sp, #192]",
+ "stp x26, x27, [sp, #208]",
+ "stp x28, x29, [sp, #224]",
+ "str x30, [sp, #240]",
+ "str xzr, [sp, #248]",
"mrs x0, elr_el1",
"mrs x1, spsr_el1",
- "stp x0, x1, [sp, #160]",
+ "stp x0, x1, [sp, #256]",
"mrs x0, fpcr",
"mrs x1, fpsr",
- "stp x0, x1, [sp, #176]",
- "stp q0, q1, [sp, #192]",
- "stp q2, q3, [sp, #224]",
- "stp q4, q5, [sp, #256]",
- "stp q6, q7, [sp, #288]",
- "stp q16, q17, [sp, #320]",
- "stp q18, q19, [sp, #352]",
- "stp q20, q21, [sp, #384]",
- "stp q22, q23, [sp, #416]",
- "stp q24, q25, [sp, #448]",
- "stp q26, q27, [sp, #480]",
- "stp q28, q29, [sp, #512]",
- "stp q30, q31, [sp, #544]",
- "bl {irq_handler}",
- "ldp q0, q1, [sp, #192]",
- "ldp q2, q3, [sp, #224]",
- "ldp q4, q5, [sp, #256]",
- "ldp q6, q7, [sp, #288]",
- "ldp q16, q17, [sp, #320]",
- "ldp q18, q19, [sp, #352]",
- "ldp q20, q21, [sp, #384]",
- "ldp q22, q23, [sp, #416]",
- "ldp q24, q25, [sp, #448]",
- "ldp q26, q27, [sp, #480]",
- "ldp q28, q29, [sp, #512]",
- "ldp q30, q31, [sp, #544]",
- "ldp x0, x1, [sp, #176]",
+ "stp x0, x1, [sp, #272]",
+ "stp q0, q1, [sp, #288]",
+ "stp q2, q3, [sp, #320]",
+ "stp q4, q5, [sp, #352]",
+ "stp q6, q7, [sp, #384]",
+ "stp q8, q9, [sp, #416]",
+ "stp q10, q11, [sp, #448]",
+ "stp q12, q13, [sp, #480]",
+ "stp q14, q15, [sp, #512]",
+ "stp q16, q17, [sp, #544]",
+ "stp q18, q19, [sp, #576]",
+ "stp q20, q21, [sp, #608]",
+ "stp q22, q23, [sp, #640]",
+ "stp q24, q25, [sp, #672]",
+ "stp q26, q27, [sp, #704]",
+ "stp q28, q29, [sp, #736]",
+ "stp q30, q31, [sp, #768]",
+ "mov x0, sp",
+ "bl {irq_dispatcher}",
+ "mov sp, x0",
+ "ldp q0, q1, [sp, #288]",
+ "ldp q2, q3, [sp, #320]",
+ "ldp q4, q5, [sp, #352]",
+ "ldp q6, q7, [sp, #384]",
+ "ldp q8, q9, [sp, #416]",
+ "ldp q10, q11, [sp, #448]",
+ "ldp q12, q13, [sp, #480]",
+ "ldp q14, q15, [sp, #512]",
+ "ldp q16, q17, [sp, #544]",
+ "ldp q18, q19, [sp, #576]",
+ "ldp q20, q21, [sp, #608]",
+ "ldp q22, q23, [sp, #640]",
+ "ldp q24, q25, [sp, #672]",
+ "ldp q26, q27, [sp, #704]",
+ "ldp q28, q29, [sp, #736]",
+ "ldp q30, q31, [sp, #768]",
+ "ldp x0, x1, [sp, #272]",
"msr fpcr, x0",
"msr fpsr, x1",
- "ldp x0, x1, [sp, #160]",
+ "ldp x0, x1, [sp, #256]",
"msr elr_el1, x0",
"msr spsr_el1, x1",
- "ldp x0, x1, [sp, #0]",
"ldp x2, x3, [sp, #16]",
"ldp x4, x5, [sp, #32]",
"ldp x6, x7, [sp, #48]",
@@ -325,8 +339,15 @@ mod vectors {
"ldp x12, x13, [sp, #96]",
"ldp x14, x15, [sp, #112]",
"ldp x16, x17, [sp, #128]",
- "ldp x18, x30, [sp, #144]",
- "add sp, sp, #576",
+ "ldp x18, x19, [sp, #144]",
+ "ldp x20, x21, [sp, #160]",
+ "ldp x22, x23, [sp, #176]",
+ "ldp x24, x25, [sp, #192]",
+ "ldp x26, x27, [sp, #208]",
+ "ldp x28, x29, [sp, #224]",
+ "ldr x30, [sp, #240]",
+ "ldp x0, x1, [sp, #0]",
+ "add sp, sp, #800",
"eret",
"aienos_exception_trampoline:",
"adrp x1, {stack}",
@@ -339,7 +360,7 @@ mod vectors {
stack = sym EXCEPTION_STACK,
stack_bytes_hi = const STACK_BYTES >> 12,
handler = sym aienos_exception_handler,
- irq_handler = sym call_irq_hook,
+ irq_dispatcher = sym crate::thread::aienos_irq_dispatcher,
);
extern "C" {
diff --git a/crates/aienos-kernel/src/thread.rs b/crates/aienos-kernel/src/thread.rs
index 28efd845..137fafa0 100644
--- a/crates/aienos-kernel/src/thread.rs
+++ b/crates/aienos-kernel/src/thread.rs
@@ -1,7 +1,28 @@
#![allow(static_mut_refs)]
-//! Cooperative EL1 threads with caller-owned stacks.
+//! Cooperative and preemptive EL1 threads with caller-owned stacks.
#![allow(clippy::items_after_test_module)]
+use crate::acpi::CpuTopology;
use crate::scheduler::{Scheduler, TaskPriority};
+use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+
+/// Deterministic placement for a task index, derived from the MADT efficiency
+/// classes: the lowest class fills first, in core order within the class, and
+/// placement wraps across the placed cores once capacity is exhausted.
+/// Pure function so the policy is host-testable without hardware.
+pub fn place_task(topology: &CpuTopology, task_index: u32) -> Option<(u8, u32)> {
+ let capacity: u32 = topology.classes().iter().map(|(_, count)| *count).sum();
+ if capacity == 0 {
+ return None;
+ }
+ let mut index = task_index % capacity;
+ for &(class, count) in topology.classes() {
+ if index < count {
+ return Some((class, index));
+ }
+ index -= count;
+ }
+ None
+}
#[repr(C)]
#[derive(Clone, Copy, Default)]
@@ -11,6 +32,18 @@ pub struct Context {
pub d8_d15: [u64; 8],
}
+#[repr(C, align(16))]
+#[derive(Clone, Copy, Default)]
+pub struct TrapFrame {
+ pub x: [u64; 31],
+ pub _pad: u64,
+ pub elr_el1: u64,
+ pub spsr_el1: u64,
+ pub fpcr: u64,
+ pub fpsr: u64,
+ pub q: [u128; 32],
+}
+
// Context switch and thread entry live in global assembly so no compiler
// prologue/epilogue sits between saving and restoring a context, and the
// argument registers are fixed (x0 = from, x1 = to).
@@ -88,6 +121,40 @@ pub fn prepare(stack: &mut [u8], entry: extern "C" fn(usize), arg: usize) -> Opt
Some(ctx)
}
+/// Prepare a new TrapFrame at the 16-byte aligned top of a caller-provided stack.
+/// The thread starts in `entry(arg)` at EL1h with interrupts unmasked.
+pub fn prepare_trap_frame(
+ stack: &mut [u8],
+ entry: extern "C" fn(usize),
+ arg: usize,
+) -> Option<*mut TrapFrame> {
+ let base = stack.as_mut_ptr() as usize;
+ let end = base.checked_add(stack.len())? & !15usize;
+ let frame_size = core::mem::size_of::();
+ let sp = end.checked_sub(frame_size)?;
+ if sp < base {
+ return None;
+ }
+ let frame_ptr = sp as *mut TrapFrame;
+ unsafe {
+ core::ptr::write(
+ frame_ptr,
+ TrapFrame {
+ x: [0; 31],
+ _pad: 0,
+ elr_el1: entry as *const () as usize as u64,
+ spsr_el1: 0x0000_0005,
+ fpcr: 0,
+ fpsr: 0,
+ q: [0; 32],
+ },
+ );
+ (*frame_ptr).x[0] = arg as u64;
+ (*frame_ptr).x[30] = thread_exit_address();
+ }
+ Some(frame_ptr)
+}
+
fn thread_start_address() -> u64 {
#[cfg(target_arch = "aarch64")]
{
@@ -99,6 +166,17 @@ fn thread_start_address() -> u64 {
}
}
+fn thread_exit_address() -> u64 {
+ #[cfg(target_arch = "aarch64")]
+ {
+ aienos_thread_exit as *const () as usize as u64
+ }
+ #[cfg(not(target_arch = "aarch64"))]
+ {
+ 0
+ }
+}
+
#[no_mangle]
extern "C" fn aienos_thread_exit() -> ! {
unsafe { park() }
@@ -119,6 +197,90 @@ static mut MAIN: Context = Context {
sp: 0,
d8_d15: [0; 8],
};
+
+static PREEMPT_DEMO_ACTIVE: AtomicBool = AtomicBool::new(false);
+static PREEMPT_DEMO_DONE: AtomicBool = AtomicBool::new(false);
+static PREEMPT_COUNTER_A: AtomicU64 = AtomicU64::new(0);
+static PREEMPT_COUNTER_B: AtomicU64 = AtomicU64::new(0);
+static mut PREEMPT_SWITCH_COUNT: u64 = 0;
+static mut PREEMPT_WORKER_FRAMES: [*mut TrapFrame; 2] = [core::ptr::null_mut(); 2];
+static mut PREEMPT_MAIN_FRAME: *mut TrapFrame = core::ptr::null_mut();
+static mut PREEMPT_CURRENT_WORKER: usize = 0;
+
+/// Top-level IRQ dispatcher invoked by `aienos_irq_trampoline`.
+/// Acknowledges GIC interrupt, rearms generic timer, clears EOI, manages thread state,
+/// and returns the next thread TrapFrame pointer.
+///
+/// # Safety
+/// Must only be called by the IRQ trampoline on the active interrupt stack
+/// with `frame` pointing to a valid 800-byte TrapFrame.
+#[no_mangle]
+pub unsafe extern "C" fn aienos_irq_dispatcher(frame: *mut TrapFrame) -> *mut TrapFrame {
+ #[cfg(target_arch = "aarch64")]
+ {
+ irq_dispatcher_inner(frame)
+ }
+ #[cfg(not(target_arch = "aarch64"))]
+ {
+ frame
+ }
+}
+
+#[cfg(target_arch = "aarch64")]
+unsafe fn irq_dispatcher_inner(frame: *mut TrapFrame) -> *mut TrapFrame {
+ let mut cpu = crate::gic::Aarch64GicCpuInterface;
+ let id = crate::gic::GicCpuInterface::acknowledge(&mut cpu);
+
+ if id == 30 {
+ let mut timer = crate::timer::Aarch64TimerRegisters;
+ let hz = crate::timer::TimerRegisters::frequency(&timer);
+ let now = crate::timer::TimerRegisters::counter(&timer);
+ let interval = if hz > 0 { hz / 100 } else { 625_000 };
+ let deadline = now.wrapping_add(interval);
+ crate::timer::TimerRegisters::set_compare(&mut timer, deadline);
+ crate::timer::TimerRegisters::enable_timer(&mut timer, true);
+ crate::fatal::call_irq_hook();
+ }
+
+ if id < 1020 {
+ crate::gic::GicCpuInterface::end_interrupt(&mut cpu, id);
+ }
+
+ if id != 30 {
+ return frame;
+ }
+
+ if !PREEMPT_DEMO_ACTIVE.load(Ordering::SeqCst) {
+ return frame;
+ }
+
+ if PREEMPT_MAIN_FRAME.is_null() {
+ PREEMPT_MAIN_FRAME = frame;
+ PREEMPT_CURRENT_WORKER = 0;
+ return PREEMPT_WORKER_FRAMES[0];
+ }
+
+ let current = PREEMPT_CURRENT_WORKER;
+ PREEMPT_WORKER_FRAMES[current] = frame;
+
+ let a = PREEMPT_COUNTER_A.load(Ordering::Relaxed);
+ let b = PREEMPT_COUNTER_B.load(Ordering::Relaxed);
+ let sw = PREEMPT_SWITCH_COUNT;
+
+ if sw >= 4 && a > 0 && b > 0 {
+ PREEMPT_DEMO_ACTIVE.store(false, Ordering::SeqCst);
+ PREEMPT_DEMO_DONE.store(true, Ordering::SeqCst);
+ let target = PREEMPT_MAIN_FRAME;
+ PREEMPT_MAIN_FRAME = core::ptr::null_mut();
+ return target;
+ }
+
+ let next = 1 - current;
+ PREEMPT_CURRENT_WORKER = next;
+ PREEMPT_SWITCH_COUNT += 1;
+ PREEMPT_WORKER_FRAMES[next]
+}
+
/// Register a thread on a caller-provided stack. Returns its scheduler ID.
///
/// # Safety
@@ -130,6 +292,7 @@ pub unsafe fn spawn(stack: &mut [u8], entry: extern "C" fn(usize), arg: usize) -
RUNNABLE[slot] = true;
Some(slot as u32)
}
+
/// Yield to the least-served runnable thread, returning to the boot context when idle.
///
/// # Safety
@@ -158,6 +321,7 @@ pub unsafe fn yield_now() {
switch(&raw mut CONTEXTS[from], &raw const CONTEXTS[target]);
}
}
+
/// Mark the current thread finished and transfer control to another runnable thread.
///
/// # Safety
@@ -171,10 +335,140 @@ pub unsafe fn park() -> ! {
}
}
+/// Run two non-yielding spinning worker threads that each increment an atomic
+/// counter across multiple timer IRQ preemption switches.
+///
+/// Returns (counter_a, counter_b, switches).
+///
+/// # Safety
+/// Call once during single-core boot with GIC and generic timer available.
+pub unsafe fn run_preemption_demo() -> (u64, u64, u64) {
+ #[cfg(target_arch = "aarch64")]
+ {
+ run_preemption_demo_inner()
+ }
+ #[cfg(not(target_arch = "aarch64"))]
+ {
+ PREEMPT_COUNTER_A.store(0, Ordering::SeqCst);
+ PREEMPT_COUNTER_B.store(0, Ordering::SeqCst);
+ for i in 0..4 {
+ if i % 2 == 0 {
+ PREEMPT_COUNTER_A.fetch_add(50, Ordering::Relaxed);
+ } else {
+ PREEMPT_COUNTER_B.fetch_add(50, Ordering::Relaxed);
+ }
+ }
+ (
+ PREEMPT_COUNTER_A.load(Ordering::Relaxed),
+ PREEMPT_COUNTER_B.load(Ordering::Relaxed),
+ 4,
+ )
+ }
+}
+
+#[cfg(target_arch = "aarch64")]
+unsafe fn run_preemption_demo_inner() -> (u64, u64, u64) {
+ static mut DEMO_STACK_A: [u8; 16384] = [0; 16384];
+ static mut DEMO_STACK_B: [u8; 16384] = [0; 16384];
+
+ PREEMPT_COUNTER_A.store(0, Ordering::SeqCst);
+ PREEMPT_COUNTER_B.store(0, Ordering::SeqCst);
+ PREEMPT_SWITCH_COUNT = 0;
+ PREEMPT_MAIN_FRAME = core::ptr::null_mut();
+ PREEMPT_CURRENT_WORKER = 0;
+ PREEMPT_DEMO_DONE.store(false, Ordering::SeqCst);
+
+ extern "C" fn worker_a(_arg: usize) {
+ loop {
+ PREEMPT_COUNTER_A.fetch_add(1, Ordering::Relaxed);
+ core::hint::spin_loop();
+ }
+ }
+
+ extern "C" fn worker_b(_arg: usize) {
+ loop {
+ PREEMPT_COUNTER_B.fetch_add(1, Ordering::Relaxed);
+ core::hint::spin_loop();
+ }
+ }
+
+ let frame_a = prepare_trap_frame(&mut DEMO_STACK_A, worker_a, 0)
+ .expect("failed to prepare trap frame for worker A");
+ let frame_b = prepare_trap_frame(&mut DEMO_STACK_B, worker_b, 1)
+ .expect("failed to prepare trap frame for worker B");
+
+ PREEMPT_WORKER_FRAMES[0] = frame_a;
+ PREEMPT_WORKER_FRAMES[1] = frame_b;
+
+ PREEMPT_DEMO_ACTIVE.store(true, Ordering::SeqCst);
+
+ let mut cpu = crate::gic::Aarch64GicCpuInterface;
+ crate::gic::GicCpuInterface::set_priority_mask(&mut cpu, 0xff);
+ crate::gic::GicCpuInterface::enable_group1(&mut cpu);
+
+ let mut timer = crate::timer::Aarch64TimerRegisters;
+ let hz = crate::timer::TimerRegisters::frequency(&timer);
+ let start = crate::timer::TimerRegisters::counter(&timer);
+ let interval = if hz > 0 { hz / 100 } else { 625_000 };
+ crate::timer::TimerRegisters::set_compare(&mut timer, start.wrapping_add(interval));
+ crate::timer::TimerRegisters::enable_timer(&mut timer, true);
+
+ // Unmask IRQs at EL1h (clear DAIF.I)
+ core::arch::asm!("msr daifclr, #2", "isb", options(nostack));
+
+ // Spin waiting for preemption switches between worker_a and worker_b to finish
+ while !PREEMPT_DEMO_DONE.load(Ordering::SeqCst) {
+ core::hint::spin_loop();
+ }
+
+ // Mask IRQs at EL1h (set DAIF.I)
+ core::arch::asm!("msr daifset, #2", "isb", options(nostack));
+
+ // Disable timer
+ crate::timer::TimerRegisters::enable_timer(&mut timer, false);
+
+ let a = PREEMPT_COUNTER_A.load(Ordering::Relaxed);
+ let b = PREEMPT_COUNTER_B.load(Ordering::Relaxed);
+ let sw = PREEMPT_SWITCH_COUNT;
+
+ (a, b, sw)
+}
+
#[cfg(test)]
mod tests {
use super::*;
extern "C" fn entry(_: usize) {}
+ #[test]
+ fn placement_fills_lowest_class_first_then_wraps() {
+ let topology = crate::acpi::CpuTopology {
+ classes: [
+ (0, 2),
+ (1, 2),
+ (0, 0),
+ (0, 0),
+ (0, 0),
+ (0, 0),
+ (0, 0),
+ (0, 0),
+ ],
+ distinct_classes: 2,
+ cores: 4,
+ ..Default::default()
+ };
+ assert_eq!(place_task(&topology, 0), Some((0, 0)));
+ assert_eq!(place_task(&topology, 1), Some((0, 1)));
+ assert_eq!(place_task(&topology, 2), Some((1, 0)));
+ assert_eq!(place_task(&topology, 3), Some((1, 1)));
+ assert_eq!(place_task(&topology, 4), Some((0, 0)), "wraps");
+ assert_eq!(place_task(&topology, 7), Some((1, 1)), "wraps");
+ }
+
+ #[test]
+ fn placement_of_empty_topology_is_unplaced() {
+ let topology = crate::acpi::CpuTopology::default();
+ assert_eq!(place_task(&topology, 0), None);
+ }
+
#[test]
fn stack_setup_aligns_sp_and_records_trampoline_arguments() {
let mut stack = [0u8; 257];
@@ -189,6 +483,31 @@ mod tests {
assert_eq!(core::mem::offset_of!(Context, d8_d15), 104);
assert_eq!(core::mem::size_of::(), 168);
}
+ #[test]
+ fn trap_frame_layout_matches_800_bytes_and_16_byte_alignment() {
+ assert_eq!(core::mem::size_of::(), 800);
+ assert_eq!(core::mem::align_of::(), 16);
+ assert_eq!(core::mem::offset_of!(TrapFrame, x), 0);
+ assert_eq!(core::mem::offset_of!(TrapFrame, _pad), 248);
+ assert_eq!(core::mem::offset_of!(TrapFrame, elr_el1), 256);
+ assert_eq!(core::mem::offset_of!(TrapFrame, spsr_el1), 264);
+ assert_eq!(core::mem::offset_of!(TrapFrame, fpcr), 272);
+ assert_eq!(core::mem::offset_of!(TrapFrame, fpsr), 280);
+ assert_eq!(core::mem::offset_of!(TrapFrame, q), 288);
+ }
+ #[test]
+ fn trap_frame_setup_aligns_and_initializes_registers() {
+ let mut stack = [0u8; 2048];
+ let frame_ptr = prepare_trap_frame(&mut stack, entry, 99).unwrap();
+ assert_eq!((frame_ptr as usize) % 16, 0);
+ let frame = unsafe { *frame_ptr };
+ assert_eq!(frame.x[0], 99);
+ assert_eq!(frame.elr_el1, entry as *const () as usize as u64);
+ assert_eq!(frame.spsr_el1, 0x05);
+ assert_eq!(frame._pad, 0);
+ assert_eq!(frame.fpcr, 0);
+ assert_eq!(frame.fpsr, 0);
+ }
}
/// Run two bounded threads that each record a tag and yield five times.
diff --git a/evidence/m3_topology_scheduler_2026-09-24.md b/evidence/m3_topology_scheduler_2026-09-24.md
new file mode 100644
index 00000000..5af10a42
--- /dev/null
+++ b/evidence/m3_topology_scheduler_2026-09-24.md
@@ -0,0 +1,58 @@
+# Evidence: timer-driven preemption and deterministic MADT placement in QEMU
+
+Branch: feat/m3-topology-scheduler
+Base: 0b0dc82 (main after PR #104)
+Commit under test: the branch tip including
+feat(scheduler): timer-driven preemption with MADT-aware placement
+
+## Exact successful invocation
+
+ AIENOS_QEMU_VERBOSE=1 AIENOS_QEMU_TIMEOUT=90 bash scripts/qemu_boot_test.sh
+
+Exit 0, QEMU_BOOT: PASS.
+
+## Environment
+
+- Host: spark-b87b
+- QEMU 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18), virt machine, gic-version=3, -smp 4
+- Image: aienos-handoff.efi, aarch64-unknown-uefi, --features handoff
+
+## Serial proof (raw lines)
+
+ kernel_el: EL1h
+ mmu: enabled
+ threads: ok interleave=ABABABABAB
+ el0: ok write=granted forged=denied fault=contained exit=0
+ preempt: ok a=5716769 b=3798659 switches=4
+ placement: worker0=class0/core0 worker1=class0/core1
+ kernel: alive
+
+## What the results demonstrate
+
+- preempt: the timer IRQ (GIC INTID 30) preempts the EL1 boot context and
+ round-robins two runnable workers through the 800-byte TrapFrame dispatcher;
+ both counters advanced (a, b > 0) across 4 switches before the demo quiesced.
+- placement: the two workers were placed deterministically from the MADT
+ efficiency classes. QEMU exposes 4 homogeneous cores (class 0), so
+ place_task() yields class0/core0 then class0/core1. The heterogeneous path
+ (class 0 and class 1 cores) is covered by the host test
+ placement_fills_lowest_class_first_then_wraps.
+- context state: the preemption frame is the same full 800-byte TrapFrame
+ (x0-x30, ELR/SPSR, FPCR/FPSR, q0-q31) guarded by
+ trap_frame_layout_matches_800_bytes_and_16_byte_alignment, so SIMD/FP state
+ survives switches.
+
+## IRQ model
+
+The EL1 IRQ trampoline now saves the complete TrapFrame and calls
+thread::aienos_irq_dispatcher, which acknowledges the interrupt, re-arms the
+timer, ends the interrupt in the GIC, and returns the next frame to restore.
+handoff's timer_irq is a pure counter. Vector slot 8 (EL0 containment, PR #104)
+and slot 5 (IRQ) routing are unchanged.
+
+## Boundary
+
+Emulator only. QEMU exposes one efficiency class, so cross-class migration is
+host-tested, not observed on hardware. No SMP bring-up of secondary cores is
+exercised; placement is the deterministic policy the scheduler will apply when
+secondary cores are started.
diff --git a/scripts/qemu_boot_test.sh b/scripts/qemu_boot_test.sh
index 68ca5e8a..f31e0b5a 100755
--- a/scripts/qemu_boot_test.sh
+++ b/scripts/qemu_boot_test.sh
@@ -61,6 +61,8 @@ check "left firmware and entered the kernel" "kernel: alive"
check "kernel entered EL1h" "kernel_el: EL1h"
check "cooperative threads interleaved" "threads: ok"
check "EL0 capability and fault isolation" "el0: ok write=granted forged=denied fault=contained exit=0"
+check "timer-driven preemption across runnable tasks" "preempt: ok"
+check "deterministic MADT placement of preempt workers" "placement: worker0=class0/core0 worker1=class0/core1"
check "EL1 page tables and caches enabled" "mmu: enabled"
check "GICv3 enabled" "gic: v3"
if grep -qE 'timer_irq: ([0-9]+) ticks' "${work}/serial.txt"; then
```