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/blob/main/crates/aienos-kernel/src/thread.rs # 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 branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / thread.rs` 566 lines ยท 18709 bytes Raw Blame History 1 #![allow(static_mut_refs)] 2 // SPDX-License-Identifier: Apache-2.0 3 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 //! Cooperative and preemptive EL1 threads with caller-owned stacks. 18 #![allow(clippy::items_after_test_module)] 19 use crate::acpi::CpuTopology; 20 use crate::scheduler::{Scheduler, TaskPriority}; 21 use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; 22 23 /// Deterministic placement for a task index, derived from the MADT efficiency 24 /// classes: the lowest class fills first, in core order within the class, and 25 /// placement wraps across the placed cores once capacity is exhausted. 26 /// Pure function so the policy is host-testable without hardware. 27 pub fn place_task(topology: &CpuTopology, task_index: u32) -> Option<(u8, u32)> { 28 let capacity: u32 = topology.classes().iter().map(|(_, count)| *count).sum(); 29 if capacity == 0 { 30 return None; 31 } 32 let mut index = task_index % capacity; 33 for &(class, count) in topology.classes() { 34 if index < count { 35 return Some((class, index)); 36 } 37 index -= count; 38 } 39 None 40 } 41 42 #[repr(C)] 43 #[derive(Clone, Copy, Default)] 44 pub struct Context { 45 pub x19_x30: [u64; 12], 46 pub sp: u64, 47 pub d8_d15: [u64; 8], 48 } 49 50 #[repr(C, align(16))] 51 #[derive(Clone, Copy, Default)] 52 pub struct TrapFrame { 53 pub x: [u64; 31], 54 pub _pad: u64, 55 pub elr_el1: u64, 56 pub spsr_el1: u64, 57 pub fpcr: u64, 58 pub fpsr: u64, 59 pub q: [u128; 32], 60 } 61 62 // Context switch and thread entry live in global assembly so no compiler 63 // prologue/epilogue sits between saving and restoring a context, and the 64 // argument registers are fixed (x0 = from, x1 = to). 65 #[cfg(target_arch = "aarch64")] 66 core::arch::global_asm!( 67 ".global aienos_ctx_switch", 68 "aienos_ctx_switch:", 69 "stp x19, x20, [x0, #0]", 70 "stp x21, x22, [x0, #16]", 71 "stp x23, x24, [x0, #32]", 72 "stp x25, x26, [x0, #48]", 73 "stp x27, x28, [x0, #64]", 74 "stp x29, x30, [x0, #80]", 75 "mov x9, sp", 76 "str x9, [x0, #96]", 77 "stp d8, d9, [x0, #104]", 78 "stp d10, d11, [x0, #120]", 79 "stp d12, d13, [x0, #136]", 80 "stp d14, d15, [x0, #152]", 81 "ldp d8, d9, [x1, #104]", 82 "ldp d10, d11, [x1, #120]", 83 "ldp d12, d13, [x1, #136]", 84 "ldp d14, d15, [x1, #152]", 85 "ldr x9, [x1, #96]", 86 "mov sp, x9", 87 "ldp x19, x20, [x1, #0]", 88 "ldp x21, x22, [x1, #16]", 89 "ldp x23, x24, [x1, #32]", 90 "ldp x25, x26, [x1, #48]", 91 "ldp x27, x28, [x1, #64]", 92 "ldp x29, x30, [x1, #80]", 93 "ret", 94 ".global aienos_thread_start", 95 "aienos_thread_start:", 96 "mov x0, x19", 97 "blr x20", 98 "bl aienos_thread_exit", 99 ); 100 101 #[cfg(target_arch = "aarch64")] 102 extern "C" { 103 fn aienos_ctx_switch(from: *mut Context, to: *const Context); 104 fn aienos_thread_start(); 105 } 106 107 /// Save the current callee-saved context into `from` and resume `to`. 108 /// 109 /// # Safety 110 /// `to` must hold a valid stack and resume address; both contexts must stay 111 /// valid; execution must be serialized with interrupts masked. 112 #[cfg(target_arch = "aarch64")] 113 pub unsafe fn switch(from: *mut Context, to: *const Context) { 114 aienos_ctx_switch(from, to); 115 } 116 #[cfg(not(target_arch = "aarch64"))] 117 pub unsafe fn switch(_from: *mut Context, _to: *const Context) {} 118 119 /// Prepare a new context at the aligned top of a caller-provided stack. 120 /// The thread starts in `aienos_thread_start`, which calls `entry(arg)` from 121 /// x19/x20 and parks the thread when it returns. 122 pub fn prepare(stack: &mut [u8], entry: extern "C" fn(usize), arg: usize) -> Option { 123 let base = stack.as_mut_ptr() as usize; 124 let end = base.checked_add(stack.len())? & !15usize; 125 let sp = end.checked_sub(16)?; 126 if sp < base { 127 return None; 128 } 129 let mut ctx = Context { 130 sp: sp as u64, 131 ..Context::default() 132 }; 133 ctx.x19_x30[0] = arg as u64; 134 ctx.x19_x30[1] = entry as *const () as usize as u64; 135 ctx.x19_x30[11] = thread_start_address(); 136 Some(ctx) 137 } 138 139 /// Prepare a new TrapFrame at the 16-byte aligned top of a caller-provided stack. 140 /// The thread starts in `entry(arg)` at EL1h with interrupts unmasked. 141 pub fn prepare_trap_frame( 142 stack: &mut [u8], 143 entry: extern "C" fn(usize), 144 arg: usize, 145 ) -> Option<*mut TrapFrame> { 146 let base = stack.as_mut_ptr() as usize; 147 let end = base.checked_add(stack.len())? & !15usize; 148 let frame_size = core::mem::size_of::(); 149 let sp = end.checked_sub(frame_size)?; 150 if sp < base { 151 return None; 152 } 153 let frame_ptr = sp as *mut TrapFrame; 154 unsafe { 155 core::ptr::write( 156 frame_ptr, 157 TrapFrame { 158 x: [0; 31], 159 _pad: 0, 160 elr_el1: entry as *const () as usize as u64, 161 spsr_el1: 0x0000_0005, 162 fpcr: 0, 163 fpsr: 0, 164 q: [0; 32], 165 }, 166 ); 167 (*frame_ptr).x[0] = arg as u64; 168 (*frame_ptr).x[30] = thread_exit_address(); 169 } 170 Some(frame_ptr) 171 } 172 173 fn thread_start_address() -> u64 { 174 #[cfg(target_arch = "aarch64")] 175 { 176 aienos_thread_start as *const () as usize as u64 177 } 178 #[cfg(not(target_arch = "aarch64"))] 179 { 180 0 181 } 182 } 183 184 fn thread_exit_address() -> u64 { 185 #[cfg(target_arch = "aarch64")] 186 { 187 aienos_thread_exit as *const () as usize as u64 188 } 189 #[cfg(not(target_arch = "aarch64"))] 190 { 191 0 192 } 193 } 194 195 #[no_mangle] 196 extern "C" fn aienos_thread_exit() -> ! { 197 unsafe { park() } 198 } 199 200 const MAX: usize = 4; 201 static mut CONTEXTS: [Context; MAX] = [Context { 202 x19_x30: [0; 12], 203 sp: 0, 204 d8_d15: [0; 8], 205 }; MAX]; 206 static mut RUNNABLE: [bool; MAX] = [false; MAX]; 207 /// Index of the running thread; MAX means the boot context. 208 static mut CURRENT: usize = MAX; 209 static mut SCHED: Scheduler<1, MAX> = Scheduler::new([0]); 210 static mut MAIN: Context = Context { 211 x19_x30: [0; 12], 212 sp: 0, 213 d8_d15: [0; 8], 214 }; 215 216 static PREEMPT_DEMO_ACTIVE: AtomicBool = AtomicBool::new(false); 217 static PREEMPT_DEMO_DONE: AtomicBool = AtomicBool::new(false); 218 static PREEMPT_COUNTER_A: AtomicU64 = AtomicU64::new(0); 219 static PREEMPT_COUNTER_B: AtomicU64 = AtomicU64::new(0); 220 static mut PREEMPT_SWITCH_COUNT: u64 = 0; 221 static mut PREEMPT_WORKER_FRAMES: [*mut TrapFrame; 2] = [core::ptr::null_mut(); 2]; 222 static mut PREEMPT_MAIN_FRAME: *mut TrapFrame = core::ptr::null_mut(); 223 static mut PREEMPT_CURRENT_WORKER: usize = 0; 224 225 /// Top-level IRQ dispatcher invoked by `aienos_irq_trampoline`. 226 /// Acknowledges GIC interrupt, rearms generic timer, clears EOI, manages thread state, 227 /// and returns the next thread TrapFrame pointer. 228 /// 229 /// # Safety 230 /// Must only be called by the IRQ trampoline on the active interrupt stack 231 /// with `frame` pointing to a valid 800-byte TrapFrame. 232 #[no_mangle] 233 pub unsafe extern "C" fn aienos_irq_dispatcher(frame: *mut TrapFrame) -> *mut TrapFrame { 234 #[cfg(target_arch = "aarch64")] 235 { 236 irq_dispatcher_inner(frame) 237 } 238 #[cfg(not(target_arch = "aarch64"))] 239 { 240 frame 241 } 242 } 243 244 #[cfg(target_arch = "aarch64")] 245 unsafe fn irq_dispatcher_inner(frame: *mut TrapFrame) -> *mut TrapFrame { 246 let mut cpu = crate::gic::Aarch64GicCpuInterface; 247 let id = crate::gic::GicCpuInterface::acknowledge(&mut cpu); 248 249 if id == 30 { 250 let mut timer = crate::timer::Aarch64TimerRegisters; 251 let hz = crate::timer::TimerRegisters::frequency(&timer); 252 let now = crate::timer::TimerRegisters::counter(&timer); 253 let interval = if hz > 0 { hz / 100 } else { 625_000 }; 254 let deadline = now.wrapping_add(interval); 255 crate::timer::TimerRegisters::set_compare(&mut timer, deadline); 256 crate::timer::TimerRegisters::enable_timer(&mut timer, true); 257 crate::fatal::call_irq_hook(); 258 } 259 260 if id < 1020 { 261 crate::gic::GicCpuInterface::end_interrupt(&mut cpu, id); 262 } 263 264 if id != 30 { 265 return frame; 266 } 267 268 // A loaded artifact task interrupted at EL0: enforce its time budget, 269 // possibly rewriting the frame to terminate it. 270 if crate::task_runtime::is_active() { 271 crate::task_runtime::on_timer_tick(&mut *frame); 272 return frame; 273 } 274 275 if !PREEMPT_DEMO_ACTIVE.load(Ordering::SeqCst) { 276 return frame; 277 } 278 279 if PREEMPT_MAIN_FRAME.is_null() { 280 PREEMPT_MAIN_FRAME = frame; 281 PREEMPT_CURRENT_WORKER = 0; 282 return PREEMPT_WORKER_FRAMES[0]; 283 } 284 285 let current = PREEMPT_CURRENT_WORKER; 286 PREEMPT_WORKER_FRAMES[current] = frame; 287 288 let a = PREEMPT_COUNTER_A.load(Ordering::Relaxed); 289 let b = PREEMPT_COUNTER_B.load(Ordering::Relaxed); 290 let sw = PREEMPT_SWITCH_COUNT; 291 292 if sw >= 4 && a > 0 && b > 0 { 293 PREEMPT_DEMO_ACTIVE.store(false, Ordering::SeqCst); 294 PREEMPT_DEMO_DONE.store(true, Ordering::SeqCst); 295 let target = PREEMPT_MAIN_FRAME; 296 PREEMPT_MAIN_FRAME = core::ptr::null_mut(); 297 return target; 298 } 299 300 let next = 1 - current; 301 PREEMPT_CURRENT_WORKER = next; 302 PREEMPT_SWITCH_COUNT += 1; 303 PREEMPT_WORKER_FRAMES[next] 304 } 305 306 /// Register a thread on a caller-provided stack. Returns its scheduler ID. 307 /// 308 /// # Safety 309 /// The stack must remain allocated and exclusively owned until the thread parks. 310 pub unsafe fn spawn(stack: &mut [u8], entry: extern "C" fn(usize), arg: usize) -> Option { 311 let slot = (0..MAX).find(|&i| !RUNNABLE[i] && SCHED.task(i as u32).is_none())?; 312 CONTEXTS[slot] = prepare(stack, entry, arg)?; 313 SCHED.enqueue(slot as u32, TaskPriority::Normal).ok()?; 314 RUNNABLE[slot] = true; 315 Some(slot as u32) 316 } 317 318 /// Yield to the least-served runnable thread, returning to the boot context when idle. 319 /// 320 /// # Safety 321 /// Call only after thread state is initialized, on the single scheduling core. 322 pub unsafe fn yield_now() { 323 let from = CURRENT; 324 let mut next = None; 325 for _ in 0..MAX { 326 if let Some(id) = SCHED.tick(0).ok().flatten() { 327 if RUNNABLE[id as usize] && id as usize != from { 328 next = Some(id as usize); 329 break; 330 } 331 } 332 } 333 let target = next.unwrap_or(MAX); 334 if target == from { 335 return; 336 } 337 CURRENT = target; 338 if target == MAX { 339 switch(&raw mut CONTEXTS[from], &raw const MAIN); 340 } else if from == MAX { 341 switch(&raw mut MAIN, &raw const CONTEXTS[target]); 342 } else { 343 switch(&raw mut CONTEXTS[from], &raw const CONTEXTS[target]); 344 } 345 } 346 347 /// Mark the current thread finished and transfer control to another runnable thread. 348 /// 349 /// # Safety 350 /// Call only from a scheduled thread on the single scheduling core. 351 pub unsafe fn park() -> ! { 352 RUNNABLE[CURRENT] = false; 353 // Free the scheduler slot so finished threads don't exhaust capacity. 354 let _ = SCHED.remove(CURRENT as u32); 355 loop { 356 yield_now(); 357 } 358 } 359 360 /// Run two non-yielding spinning worker threads that each increment an atomic 361 /// counter across multiple timer IRQ preemption switches. 362 /// 363 /// Returns (counter_a, counter_b, switches). 364 /// 365 /// # Safety 366 /// Call once during single-core boot with GIC and generic timer available. 367 pub unsafe fn run_preemption_demo() -> (u64, u64, u64) { 368 #[cfg(target_arch = "aarch64")] 369 { 370 run_preemption_demo_inner() 371 } 372 #[cfg(not(target_arch = "aarch64"))] 373 { 374 PREEMPT_COUNTER_A.store(0, Ordering::SeqCst); 375 PREEMPT_COUNTER_B.store(0, Ordering::SeqCst); 376 for i in 0..4 { 377 if i % 2 == 0 { 378 PREEMPT_COUNTER_A.fetch_add(50, Ordering::Relaxed); 379 } else { 380 PREEMPT_COUNTER_B.fetch_add(50, Ordering::Relaxed); 381 } 382 } 383 ( 384 PREEMPT_COUNTER_A.load(Ordering::Relaxed), 385 PREEMPT_COUNTER_B.load(Ordering::Relaxed), 386 4, 387 ) 388 } 389 } 390 391 #[cfg(target_arch = "aarch64")] 392 unsafe fn run_preemption_demo_inner() -> (u64, u64, u64) { 393 static mut DEMO_STACK_A: [u8; 16384] = [0; 16384]; 394 static mut DEMO_STACK_B: [u8; 16384] = [0; 16384]; 395 396 PREEMPT_COUNTER_A.store(0, Ordering::SeqCst); 397 PREEMPT_COUNTER_B.store(0, Ordering::SeqCst); 398 PREEMPT_SWITCH_COUNT = 0; 399 PREEMPT_MAIN_FRAME = core::ptr::null_mut(); 400 PREEMPT_CURRENT_WORKER = 0; 401 PREEMPT_DEMO_DONE.store(false, Ordering::SeqCst); 402 403 extern "C" fn worker_a(_arg: usize) { 404 loop { 405 PREEMPT_COUNTER_A.fetch_add(1, Ordering::Relaxed); 406 core::hint::spin_loop(); 407 } 408 } 409 410 extern "C" fn worker_b(_arg: usize) { 411 loop { 412 PREEMPT_COUNTER_B.fetch_add(1, Ordering::Relaxed); 413 core::hint::spin_loop(); 414 } 415 } 416 417 let frame_a = prepare_trap_frame(&mut DEMO_STACK_A, worker_a, 0) 418 .expect("failed to prepare trap frame for worker A"); 419 let frame_b = prepare_trap_frame(&mut DEMO_STACK_B, worker_b, 1) 420 .expect("failed to prepare trap frame for worker B"); 421 422 PREEMPT_WORKER_FRAMES[0] = frame_a; 423 PREEMPT_WORKER_FRAMES[1] = frame_b; 424 425 PREEMPT_DEMO_ACTIVE.store(true, Ordering::SeqCst); 426 427 let mut cpu = crate::gic::Aarch64GicCpuInterface; 428 crate::gic::GicCpuInterface::set_priority_mask(&mut cpu, 0xff); 429 crate::gic::GicCpuInterface::enable_group1(&mut cpu); 430 431 let mut timer = crate::timer::Aarch64TimerRegisters; 432 let hz = crate::timer::TimerRegisters::frequency(&timer); 433 let start = crate::timer::TimerRegisters::counter(&timer); 434 let interval = if hz > 0 { hz / 100 } else { 625_000 }; 435 crate::timer::TimerRegisters::set_compare(&mut timer, start.wrapping_add(interval)); 436 crate::timer::TimerRegisters::enable_timer(&mut timer, true); 437 438 // Unmask IRQs at EL1h (clear DAIF.I) 439 core::arch::asm!("msr daifclr, #2", "isb", options(nostack)); 440 441 // Spin waiting for preemption switches between worker_a and worker_b to finish 442 while !PREEMPT_DEMO_DONE.load(Ordering::SeqCst) { 443 core::hint::spin_loop(); 444 } 445 446 // Mask IRQs at EL1h (set DAIF.I) 447 core::arch::asm!("msr daifset, #2", "isb", options(nostack)); 448 449 // Disable timer 450 crate::timer::TimerRegisters::enable_timer(&mut timer, false); 451 452 let a = PREEMPT_COUNTER_A.load(Ordering::Relaxed); 453 let b = PREEMPT_COUNTER_B.load(Ordering::Relaxed); 454 let sw = PREEMPT_SWITCH_COUNT; 455 456 (a, b, sw) 457 } 458 459 #[cfg(test)] 460 mod tests { 461 use super::*; 462 extern "C" fn entry(_: usize) {} 463 #[test] 464 fn placement_fills_lowest_class_first_then_wraps() { 465 let topology = crate::acpi::CpuTopology { 466 classes: [ 467 (0, 2), 468 (1, 2), 469 (0, 0), 470 (0, 0), 471 (0, 0), 472 (0, 0), 473 (0, 0), 474 (0, 0), 475 ], 476 distinct_classes: 2, 477 cores: 4, 478 ..Default::default() 479 }; 480 assert_eq!(place_task(&topology, 0), Some((0, 0))); 481 assert_eq!(place_task(&topology, 1), Some((0, 1))); 482 assert_eq!(place_task(&topology, 2), Some((1, 0))); 483 assert_eq!(place_task(&topology, 3), Some((1, 1))); 484 assert_eq!(place_task(&topology, 4), Some((0, 0)), "wraps"); 485 assert_eq!(place_task(&topology, 7), Some((1, 1)), "wraps"); 486 } 487 488 #[test] 489 fn placement_of_empty_topology_is_unplaced() { 490 let topology = crate::acpi::CpuTopology::default(); 491 assert_eq!(place_task(&topology, 0), None); 492 } 493 494 #[test] 495 fn stack_setup_aligns_sp_and_records_trampoline_arguments() { 496 let mut stack = [0u8; 257]; 497 let ctx = prepare(&mut stack, entry, 42).unwrap(); 498 assert_eq!(ctx.sp % 16, 0); 499 assert_eq!(ctx.x19_x30[0], 42); 500 assert_eq!(ctx.x19_x30[1], entry as *const () as usize as u64); 501 } 502 #[test] 503 fn context_offsets_match_assembly_layout() { 504 assert_eq!(core::mem::offset_of!(Context, sp), 96); 505 assert_eq!(core::mem::offset_of!(Context, d8_d15), 104); 506 assert_eq!(core::mem::size_of::(), 168); 507 } 508 #[test] 509 fn trap_frame_layout_matches_800_bytes_and_16_byte_alignment() { 510 assert_eq!(core::mem::size_of::(), 800); 511 assert_eq!(core::mem::align_of::(), 16); 512 assert_eq!(core::mem::offset_of!(TrapFrame, x), 0); 513 assert_eq!(core::mem::offset_of!(TrapFrame, _pad), 248); 514 assert_eq!(core::mem::offset_of!(TrapFrame, elr_el1), 256); 515 assert_eq!(core::mem::offset_of!(TrapFrame, spsr_el1), 264); 516 assert_eq!(core::mem::offset_of!(TrapFrame, fpcr), 272); 517 assert_eq!(core::mem::offset_of!(TrapFrame, fpsr), 280); 518 assert_eq!(core::mem::offset_of!(TrapFrame, q), 288); 519 } 520 #[test] 521 fn trap_frame_setup_aligns_and_initializes_registers() { 522 let mut stack = [0u8; 2048]; 523 let frame_ptr = prepare_trap_frame(&mut stack, entry, 99).unwrap(); 524 assert_eq!((frame_ptr as usize) % 16, 0); 525 let frame = unsafe { *frame_ptr }; 526 assert_eq!(frame.x[0], 99); 527 assert_eq!(frame.elr_el1, entry as *const () as usize as u64); 528 assert_eq!(frame.spsr_el1, 0x05); 529 assert_eq!(frame._pad, 0); 530 assert_eq!(frame.fpcr, 0); 531 assert_eq!(frame.fpsr, 0); 532 } 533 } 534 535 /// Run two bounded threads that each record a tag and yield five times. 536 /// Returns the observed interleaving (up to 10 bytes) and its length. 537 /// 538 /// # Safety 539 /// Call once during single-core boot, at EL1 with interrupts masked, before 540 /// other threads are registered. 541 pub unsafe fn run_demo() -> ([u8; 10], usize) { 542 static mut STACK_A: [u8; 8192] = [0; 8192]; 543 static mut STACK_B: [u8; 8192] = [0; 8192]; 544 static mut TRACE: [u8; 10] = [0; 10]; 545 static mut LEN: usize = 0; 546 extern "C" fn worker(tag: usize) { 547 for _ in 0..5 { 548 unsafe { 549 if LEN < TRACE.len() { 550 TRACE[LEN] = if tag == 0 { b'A' } else { b'B' }; 551 LEN += 1; 552 } 553 yield_now(); 554 } 555 } 556 } 557 if spawn(&mut STACK_A, worker, 0).is_none() || spawn(&mut STACK_B, worker, 1).is_none() { 558 return ([0; 10], 0); 559 } 560 CURRENT = MAX; 561 // Run until both workers have parked and control returns here. 562 while RUNNABLE.iter().any(|r| *r) { 563 yield_now(); 564 } 565 (TRACE, LEN) 566 }