Skip to main content

strat9_kernel/process/
scheduler.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Scheduler implementation
24//!
25//! Implements a per-CPU, multi-class, SMP scheduler for Strat9-OS with support
26//! for cooperative and preemptive multitasking.
27//!
28//! ## Scheduler locking contract : mandatory total order
29//!
30//! ```text
31//!   GLOBAL_SCHED_STATE                        (rank 1)
32//!     -> SCHED_IDENTITY write                 (rank 2)
33//!       -> BLOCKED_TASKS                      (rank 3)
34//!         -> LOCAL_SCHEDULERS[cpu]            (rank 4)
35//!           -> Task/Process internal lock     (rank 5)
36//! ```
37//!
38//! `SCHED_IDENTITY` read is observational only:
39//! - do not acquire any scheduler lock while holding it;
40//! - copy the result, release it, then begin a mutating operation.
41//!
42//! ### Forbidden
43//! - Acquiring GLOBAL, IDENTITY, BLOCKED, or another LOCAL while holding LOCAL.
44//! - Holding two LOCAL locks simultaneously.
45//! - Allocating, logging, VFS access, IPI sends, or context switching while
46//!   any scheduler spinlock is held.
47//! - Any transition from Blocked directly to Running (must go through Runnable).
48//!
49//! ### Cross-CPU operations
50//! Use a two-phase protocol: detach under the source local lock, release it,
51//! then attach under the destination local lock.
52//!
53//! ### Task ownership invariant
54//! A non-idle task is in exactly one scheduling ownership state:
55//! New, Runnable(cpu), Running(cpu), Blocked, Zombie, or Reaped.
56//!
57//! ## Canonical state machine
58//!
59//! ```text
60//!   New -> Runnable(cpu)
61//!   Runnable(cpu) -> Running(cpu)     [selection / preempt]
62//!   Running(cpu) -> Runnable(cpu)     [tick / yield / preempt]
63//!   Running(cpu) -> Blocked           [block_current]
64//!   Blocked -> Runnable(cpu)          [wake_task]
65//!   Running/Runnable/Blocked -> Zombie [exit / kill]
66//!   Zombie -> Reaped                  [waitpid / reap]
67//! ```
68//!
69//! Each transition has a single owner (the function performing it) and a
70//! defined transaction: which locks are taken, which containers lose the task,
71//! which containers receive it, and when `taskcpu` becomes visible.
72//!
73//! ## Metrics
74//! All counters (FORCE_RESCHED_HINT, RESCHED_IPI_PENDING, ticks, etc.) are
75//! lock-free atomics and must never be used to drive state transitions.
76
77use super::task::{Pid, Task, TaskId, TaskPriority, TaskState, Tid};
78use crate::{
79    arch::{apic, percpu, restore_flags, save_flags_and_cli, timer},
80    sync::SpinLock,
81};
82use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
83use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
84use spin::RwLock as SpinRwLock;
85
86// ---------------------------------------------------------------------------
87// Scheduler state machine
88// ---------------------------------------------------------------------------
89
90/// Formal scheduling state of a task, encoding ownership unambiguously.
91///
92/// Each state identifies the *exclusive owner* of the task:
93///
94/// | State             | Owner                | Present in                  |
95/// |-------------------|----------------------|-----------------------------|
96/// | New               | creator / global     | alltasks only, no queue     |
97/// | Runnable { cpu }  | LOCAL_SCHEDULERS[cpu]| exactly one class queue     |
98/// | Running { cpu }   | LOCAL_SCHEDULERS[cpu]| exactly currenttask on cpu  |
99/// | Blocked           | BLOCKED_TASKS        | exactly BLOCKED_TASKS       |
100/// | Zombie            | GLOBAL_SCHED_STATE   | zombies + alltasks          |
101/// | Reaped            | nobody               | removed from all structures |
102///
103/// `alltasks` may retain a reference for all states except Reaped, but must
104/// **never** be used to determine schedulability.  The source of truth is the
105/// `SchedState` and its owning container.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum SchedState {
108    /// Task constructed but not yet visible to the scheduler.
109    New,
110    /// Enqueued on `cpu`'s local run queue, awaiting selection.
111    Runnable { cpu: usize },
112    /// Currently executing on `cpu`.
113    Running { cpu: usize },
114    /// Waiting for an event; entry must exist in `BLOCKED_TASKS`.
115    Blocked,
116    /// Exited; waiting to be reaped by parent's `waitpid`.
117    Zombie,
118    /// Fully removed from all scheduler and identity structures.
119    Reaped,
120}
121
122impl SchedState {
123    /// Returns `true` if the task is in a scheduling-eligible state.
124    #[inline]
125    pub fn is_runnable_like(self) -> bool {
126        matches!(
127            self,
128            SchedState::Runnable { .. } | SchedState::Running { .. }
129        )
130    }
131}
132
133// ---------------------------------------------------------------------------
134// Lockdep debug instrumentation
135// ---------------------------------------------------------------------------
136
137/// Lock ranks matching the total order documented in the module header.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139#[repr(u8)]
140pub(crate) enum LockRank {
141    /// GLOBAL_SCHED_STATE : rank 1.
142    Global = 1,
143    /// SCHED_IDENTITY write : rank 2.
144    IdentityW = 2,
145    /// SCHED_IDENTITY read : rank 2R (must not chain to scheduler locks).
146    IdentityR = 3,
147    /// BLOCKED_TASKS : rank 3.
148    Blocked = 4,
149    /// LOCAL_SCHEDULERS[cpu] : rank 4.
150    Local = 5,
151    /// Task/Process internal : rank 5.
152    #[allow(dead_code)] // Retained task-internal lock rank.
153    TaskInternal = 6,
154}
155
156/// Per-CPU lockdep state, active only under `cfg(debug_assertions)`.
157#[cfg(debug_assertions)]
158#[allow(dead_code)]
159pub(crate) struct LockdepState {
160    depth: usize,
161    held: [HeldLock; 6],
162}
163
164#[cfg(debug_assertions)]
165#[derive(Debug, Clone, Copy)]
166pub(crate) struct HeldLock {
167    rank: LockRank,
168    /// Optional CPU index for LOCAL locks.
169    #[allow(dead_code)] // Retained lockdep CPU metadata.
170    cpu: Option<usize>,
171    /// Caller return address (for diagnostics).
172    #[allow(dead_code)] // Retained lockdep caller metadata.
173    caller: usize,
174}
175
176#[cfg(debug_assertions)]
177impl LockdepState {
178    pub(crate) const fn new() -> Self {
179        Self {
180            depth: 0,
181            held: [HeldLock {
182                rank: LockRank::Global,
183                cpu: None,
184                caller: 0,
185            }; 6],
186        }
187    }
188
189    /// Record a lock acquisition.  Panics in debug if ordering is violated.
190    pub(crate) fn acquire(&mut self, rank: LockRank, cpu: Option<usize>, caller: usize) {
191        if self.depth > 0 {
192            let top = self.held[self.depth - 1];
193            // SCHED_IDENTITY read (rank 3) must not chain to any scheduler lock.
194            if top.rank == LockRank::IdentityR {
195                panic!(
196                    "lockdep: SCHED_IDENTITY read held at depth {}, cannot acquire {:?} \
197                     (read path must not chain to scheduler locks)",
198                    self.depth - 1,
199                    rank
200                );
201            }
202            // LOCAL must never be held while acquiring another LOCAL.
203            if rank == LockRank::Local && cpu.is_some() {
204                for i in 0..self.depth {
205                    if self.held[i].rank == LockRank::Local {
206                        panic!(
207                            "lockdep: two LOCAL locks simultaneously (held {:?} at depth {}, \
208                             acquiring LOCAL[{}] at depth {})",
209                            self.held[i],
210                            i,
211                            cpu.unwrap(),
212                            self.depth
213                        );
214                    }
215                }
216            }
217            // General rank check: new rank must be strictly greater than current top.
218            if (rank as u8) <= (top.rank as u8) {
219                panic!(
220                    "lockdep: lock order violation at depth {}: held {:?}, acquiring {:?}",
221                    self.depth - 1,
222                    top,
223                    rank
224                );
225            }
226        }
227        if self.depth < self.held.len() {
228            self.held[self.depth] = HeldLock { rank, cpu, caller };
229        }
230        self.depth += 1;
231    }
232
233    /// Record a best-effort (`try_lock`) acquisition **without** the rank
234    /// order assertion.  The lock is genuinely held once this returns, so it
235    /// is pushed/released like any other lock.  Used only for the intentional
236    /// LOCAL → GLOBAL inversion in work stealing: the acquisition cannot
237    /// block, so the inversion cannot deadlock.
238    pub(crate) fn acquire_try(&mut self, rank: LockRank, cpu: Option<usize>, caller: usize) {
239        if self.depth < self.held.len() {
240            self.held[self.depth] = HeldLock { rank, cpu, caller };
241        }
242        self.depth += 1;
243    }
244
245    /// Record a lock release.  Asserts LIFO order.
246    pub(crate) fn release(&mut self, rank: LockRank) {
247        if self.depth == 0 {
248            panic!("lockdep: release underflow for {:?}", rank);
249        }
250        self.depth -= 1;
251        let was = self.held[self.depth];
252        if was.rank != rank {
253            panic!(
254                "lockdep: releasing {:?} but top of stack is {:?} (depth {})",
255                rank, was, self.depth
256            );
257        }
258    }
259
260    /// Assert that no scheduler lock is held.
261    pub(crate) fn assert_no_scheduler_locks(&self) {
262        if self.depth > 0 {
263            panic!(
264                "lockdep: asserting no scheduler locks but depth={}, top={:?}",
265                self.depth,
266                self.held[self.depth - 1]
267            );
268        }
269    }
270
271    /// Assert that a specific rank is currently held.
272    pub(crate) fn assert_held(&self, rank: LockRank) {
273        for i in 0..self.depth {
274            if self.held[i].rank == rank {
275                return;
276            }
277        }
278        panic!(
279            "lockdep: expected {:?} to be held, but depth={}",
280            rank, self.depth
281        );
282    }
283
284    /// Return the current depth.
285    #[allow(dead_code)] // Retained lockdep depth accessor.
286    pub(crate) fn current_depth(&self) -> usize {
287        self.depth
288    }
289}
290
291/// Per-CPU lockdep state.  Each CPU tracks its own stack of held scheduler locks.
292/// SAFETY: accessed only from the owning CPU with IRQs disabled (no concurrent access).
293#[cfg(debug_assertions)]
294static mut LOCKDEP: [LockdepState; crate::arch::percpu::MAX_CPUS] =
295    [const { LockdepState::new() }; crate::arch::percpu::MAX_CPUS];
296
297/// Record a lock acquisition in the per-CPU lockdep state.
298#[cfg(debug_assertions)]
299#[inline]
300#[track_caller]
301pub(crate) fn lockdep_acquire(rank: LockRank, cpu: Option<usize>) {
302    let caller = core::panic::Location::caller();
303    let addr = caller as *const core::panic::Location<'static> as usize;
304    unsafe { LOCKDEP[current_cpu_index()].acquire(rank, cpu, addr) };
305}
306
307/// Record a best-effort (`try_lock`) acquisition without the rank-order check.
308///
309/// The lock is held on return, so it must still be released with
310/// [`lockdep_release`].  Only for try-locks where blocking is impossible.
311#[cfg(debug_assertions)]
312#[inline]
313#[track_caller]
314pub(crate) fn lockdep_acquire_try(rank: LockRank, cpu: Option<usize>) {
315    let caller = core::panic::Location::caller();
316    let addr = caller as *const core::panic::Location<'static> as usize;
317    unsafe { LOCKDEP[current_cpu_index()].acquire_try(rank, cpu, addr) };
318}
319
320/// Record a lock release in the per-CPU lockdep state.
321#[cfg(debug_assertions)]
322#[inline]
323pub(crate) fn lockdep_release(rank: LockRank) {
324    unsafe { LOCKDEP[current_cpu_index()].release(rank) };
325}
326
327/// Assert that no scheduler locks are held on this CPU.
328#[cfg(debug_assertions)]
329#[inline]
330pub(crate) fn lockdep_assert_no_locks() {
331    unsafe { LOCKDEP[current_cpu_index()].assert_no_scheduler_locks() };
332}
333
334/// Assert that a specific rank is currently held on this CPU.
335#[cfg(debug_assertions)]
336#[inline]
337pub(crate) fn lockdep_assert_held(rank: LockRank) {
338    unsafe { LOCKDEP[current_cpu_index()].assert_held(rank) };
339}
340
341// No-op stubs for release builds
342#[cfg(not(debug_assertions))]
343#[inline]
344pub(crate) fn lockdep_acquire(_rank: LockRank, _cpu: Option<usize>) {}
345#[cfg(not(debug_assertions))]
346#[inline]
347pub(crate) fn lockdep_release(_rank: LockRank) {}
348#[cfg(not(debug_assertions))]
349#[inline]
350pub(crate) fn lockdep_acquire_try(_rank: LockRank, _cpu: Option<usize>) {}
351#[cfg(not(debug_assertions))]
352#[inline]
353#[allow(dead_code)] // Retained to mirror the debug-only lockdep assertion API.
354pub(crate) fn lockdep_assert_no_locks() {}
355#[cfg(not(debug_assertions))]
356#[inline]
357pub(crate) fn lockdep_assert_held(_rank: LockRank) {}
358
359/// Per-CPU scheduler tick counters used for CPU usage estimation.
360///
361/// - `CPU_TOTAL_TICKS[cpu]`: all timer ticks observed on `cpu`.
362/// - `CPU_IDLE_TICKS[cpu]`: ticks where the idle task was running on `cpu`.
363///
364/// CPU usage over a time window:
365/// `usage = 1 - (delta_idle / delta_total)`.
366///
367/// INVARIANT: the class counters below are incremented **once per timer tick
368/// from the hardirq** (see `timer_ops::timer_tick`), never from deferred work.
369/// They used to be updated in `process_per_task_accounting()`, which runs from a
370/// coalescing bitmask: N ticks raised `PerTaskAccounting` once, so only a
371/// handful of ticks were ever attributed. `CPU_TOTAL_TICKS` kept counting all of
372/// them, `busy = total - idle` was therefore ~100% on a completely idle box,
373/// and `top`'s "CPU(avg)" was meaningless.
374static CPU_TOTAL_TICKS: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
375    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
376static CPU_IDLE_TICKS: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
377    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
378static CPU_RT_RUNTIME_TICKS: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
379    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
380static CPU_FAIR_RUNTIME_TICKS: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
381    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
382
383/// Scheduling class currently running on each CPU, cached lock-free.
384///
385/// The hardirq cannot take `LOCAL_SCHEDULERS` (try_lock drops the tick when the
386/// lock is held), so the class is published by the scheduler whenever it
387/// installs `current_task` and read here with a plain atomic load.
388pub(crate) const CPU_CLASS_UNKNOWN: u8 = 0;
389pub(crate) const CPU_CLASS_IDLE: u8 = 1;
390pub(crate) const CPU_CLASS_FAIR: u8 = 2;
391pub(crate) const CPU_CLASS_RT: u8 = 3;
392pub(crate) static CPU_CLASS: [core::sync::atomic::AtomicU8; crate::arch::percpu::MAX_CPUS] =
393    [const { core::sync::atomic::AtomicU8::new(CPU_CLASS_UNKNOWN) }; crate::arch::percpu::MAX_CPUS];
394
395/// Address of the current task's `ticks` counter on each CPU, cached lock-free.
396///
397/// Same rationale as [`CPU_CLASS`]: per-task CPU time must be accounted once per
398/// tick. It used to be incremented from the coalescing deferred-work bitmask, so
399/// a task that ran for 100 ticks without a context switch was credited 1 tick,
400/// which made `top`'s per-task column and its "biggest consumer" sort wrong.
401pub(crate) static CPU_CURRENT_TICKS: [core::sync::atomic::AtomicUsize;
402    crate::arch::percpu::MAX_CPUS] =
403    [const { core::sync::atomic::AtomicUsize::new(0) }; crate::arch::percpu::MAX_CPUS];
404
405/// Publish the task now running on `cpu_index` (class + tick counter address).
406///
407/// Must be called every time `SchedulerCpu::current_task` changes, and again
408/// after a switch completes (before the previous task can be dropped), so the
409/// timer hardirq never dereferences a stale `Arc`.
410pub(crate) fn publish_current_task(
411    cpu_index: usize,
412    task: &crate::process::task::Task,
413    class: crate::process::sched::SchedClassId,
414) {
415    if cpu_index >= crate::arch::percpu::MAX_CPUS {
416        return;
417    }
418    let value = match class {
419        crate::process::sched::SchedClassId::Idle => CPU_CLASS_IDLE,
420        crate::process::sched::SchedClassId::Fair => CPU_CLASS_FAIR,
421        crate::process::sched::SchedClassId::RealTime => CPU_CLASS_RT,
422    };
423    CPU_CLASS[cpu_index].store(value, Ordering::Relaxed);
424    let ticks = core::ptr::addr_of!(task.ticks) as usize;
425    CPU_CURRENT_TICKS[cpu_index].store(ticks, Ordering::Release);
426
427    if crate::trace::enabled(crate::trace::category::SCHED_SWITCH) {
428        crate::trace::record(
429            crate::trace::category::SCHED_SWITCH,
430            crate::trace::TraceKind::SchedSwitch,
431            value as u64,
432            crate::trace::TraceTaskCtx::from_task(task),
433            0,
434            0,
435            cpu_index as u64,
436            task.id.as_u64(),
437        );
438    }
439}
440static CPU_SWITCH_COUNT: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
441    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
442static CPU_PREEMPT_COUNT: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
443    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
444static CPU_STEAL_IN_COUNT: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
445    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
446static CPU_STEAL_OUT_COUNT: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
447    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
448static CPU_TRY_LOCK_FAIL_COUNT: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
449    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
450static RESCHED_IPI_PENDING: [AtomicBool; crate::arch::percpu::MAX_CPUS] =
451    [const { AtomicBool::new(false) }; crate::arch::percpu::MAX_CPUS];
452static IPI_SEND_TRACE_BUDGET: AtomicU64 = AtomicU64::new(64);
453/// Lock-free per-CPU hint: request a local preemption as soon as maybe_preempt
454/// can observe scheduler state. Written from IRQ paths without touching
455/// `GLOBAL_SCHED_STATE`, consumed under scheduler lock in `maybe_preempt`.
456static FORCE_RESCHED_HINT: [AtomicBool; crate::arch::percpu::MAX_CPUS] =
457    [const { AtomicBool::new(false) }; crate::arch::percpu::MAX_CPUS];
458static LAST_STEAL_TICK: [AtomicU64; crate::arch::percpu::MAX_CPUS] =
459    [const { AtomicU64::new(0) }; crate::arch::percpu::MAX_CPUS];
460/// One-shot flag per CPU: set to true after the first preemption is logged.
461/// Prevents flooding the serial port with a preempt trace on every tick.
462pub(crate) static FIRST_PREEMPT_LOGGED: [AtomicBool; crate::arch::percpu::MAX_CPUS] =
463    [const { AtomicBool::new(false) }; crate::arch::percpu::MAX_CPUS];
464
465const STEAL_IMBALANCE_MIN: usize = 2;
466const STEAL_COOLDOWN_TICKS: u64 = 2;
467
468/// Number of CPUs that are currently online.
469///
470/// **This is a COUNT, not an index bound.** CPU indices are sparse (an AP that
471/// failed to boot may own a registered index that is not online), so callers
472/// must not iterate `0..active_cpu_count()` when touching per-CPU state. Use
473/// [`cpu_is_online`] and iterate `0..crate::arch::percpu::MAX_CPUS` instead.
474#[inline]
475pub(crate) fn active_cpu_count() -> usize {
476    crate::arch::percpu::online_count().max(1)
477}
478
479/// Performs the cpu is valid operation.
480#[inline]
481fn cpu_is_valid(cpu: usize) -> bool {
482    cpu < crate::arch::percpu::MAX_CPUS
483}
484
485/// True iff `cpu` is in range and currently online.
486#[inline]
487pub(crate) fn cpu_is_online(cpu: usize) -> bool {
488    cpu < crate::arch::percpu::MAX_CPUS && crate::arch::percpu::is_online(cpu)
489}
490
491/// True iff `cpu` is online and its local scheduler has been created.
492///
493/// Acquires the per-CPU scheduler lock, so this must not be called from IRQ
494/// context; use [`scheduler_ready_try`] there.
495#[inline]
496pub(crate) fn cpu_has_scheduler(cpu: usize) -> bool {
497    cpu_is_online(cpu) && LOCAL_SCHEDULERS[cpu].lock().is_some()
498}
499
500/// Non-blocking [`cpu_has_scheduler`] for IRQ context (contention == not ready).
501#[inline]
502pub(crate) fn scheduler_ready_try(cpu: usize) -> bool {
503    cpu_is_online(cpu)
504        && LOCAL_SCHEDULERS[cpu]
505            .try_lock_no_irqsave()
506            .map(|guard| guard.is_some())
507            .unwrap_or(false)
508}
509
510/// Least-loaded online CPU that has an initialized local scheduler.
511///
512/// Returns 0 if no scheduler is visible yet (the BSP is always online and no
513/// caller may hand out a sparse dead slot); enqueue paths still tolerate
514/// `None` schedulers during earliest boot.
515pub(crate) fn least_loaded_online_cpu() -> usize {
516    let mut buf = [0usize; crate::arch::percpu::MAX_CPUS];
517    let count = crate::arch::percpu::online_cpu_indices(&mut buf);
518    let mut best = 0usize;
519    let mut best_load = usize::MAX;
520    let mut found = false;
521    for &cpu in &buf[..count] {
522        lockdep_acquire(LockRank::Local, Some(cpu));
523        let load = LOCAL_SCHEDULERS[cpu]
524            .lock()
525            .as_ref()
526            .map(|c| c.class_rqs.runnable_len());
527        lockdep_release(LockRank::Local);
528        if let Some(load) = load {
529            found = true;
530            if load < best_load {
531                best = cpu;
532                best_load = load;
533            }
534        }
535    }
536    if found {
537        best
538    } else {
539        0
540    }
541}
542
543/// Choose a CPU for a ready task.
544///
545/// Preference order matches the historical placement policy: `last` (cache
546/// warmth) when online, initialized and lightly loaded; then `home` when
547/// online and initialized; then the least-loaded online CPU. Never returns a
548/// non-online slot.
549pub(crate) fn placement_cpu(last: usize, home: usize) -> usize {
550    if cpu_is_online(last) {
551        lockdep_acquire(LockRank::Local, Some(last));
552        let light = LOCAL_SCHEDULERS[last]
553            .lock()
554            .as_ref()
555            .map(|c| c.class_rqs.runnable_len() <= 2)
556            .unwrap_or(false);
557        lockdep_release(LockRank::Local);
558        if light {
559            return last;
560        }
561    }
562    if cpu_has_scheduler(home) {
563        return home;
564    }
565    least_loaded_online_cpu()
566}
567
568/// IRQ-safe variant of [`placement_cpu`]: never blocks; contention counts as
569/// unusable and falls through to the next candidate.
570pub(crate) fn placement_cpu_try(last: usize, home: usize) -> usize {
571    if cpu_is_online(last) {
572        if let Some(guard) = LOCAL_SCHEDULERS[last].try_lock_no_irqsave() {
573            let light = guard
574                .as_ref()
575                .map(|c| c.class_rqs.runnable_len() <= 2)
576                .unwrap_or(false);
577            drop(guard);
578            if light {
579                return last;
580            }
581        }
582    }
583    if scheduler_ready_try(home) {
584        return home;
585    }
586    let mut buf = [0usize; crate::arch::percpu::MAX_CPUS];
587    let count = crate::arch::percpu::online_cpu_indices(&mut buf);
588    let mut best = 0usize;
589    let mut best_load = usize::MAX;
590    let mut found = false;
591    for &cpu in &buf[..count] {
592        if let Some(guard) = LOCAL_SCHEDULERS[cpu].try_lock_no_irqsave() {
593            let load = guard.as_ref().map(|c| c.class_rqs.runnable_len());
594            drop(guard);
595            if let Some(load) = load {
596                found = true;
597                if load < best_load {
598                    best = cpu;
599                    best_load = load;
600                }
601            }
602        }
603    }
604    if found {
605        best
606    } else {
607        0
608    }
609}
610
611#[derive(Clone, Copy)]
612pub struct CpuUsageSnapshot {
613    pub cpu_count: usize,
614    pub total_ticks: [u64; crate::arch::percpu::MAX_CPUS],
615    pub idle_ticks: [u64; crate::arch::percpu::MAX_CPUS],
616}
617
618#[derive(Clone, Copy)]
619pub struct SchedulerMetricsSnapshot {
620    pub cpu_count: usize,
621    pub rt_runtime_ticks: [u64; crate::arch::percpu::MAX_CPUS],
622    pub fair_runtime_ticks: [u64; crate::arch::percpu::MAX_CPUS],
623    pub idle_runtime_ticks: [u64; crate::arch::percpu::MAX_CPUS],
624    pub switch_count: [u64; crate::arch::percpu::MAX_CPUS],
625    pub preempt_count: [u64; crate::arch::percpu::MAX_CPUS],
626    pub steal_in_count: [u64; crate::arch::percpu::MAX_CPUS],
627    pub steal_out_count: [u64; crate::arch::percpu::MAX_CPUS],
628    pub try_lock_fail_count: [u64; crate::arch::percpu::MAX_CPUS],
629    pub deferred_work_raised: [u32; crate::arch::percpu::MAX_CPUS],
630    pub deferred_work_processed: [u32; crate::arch::percpu::MAX_CPUS],
631}
632
633#[derive(Clone, Copy)]
634pub struct SchedulerStateSnapshot {
635    pub initialized: bool,
636    pub boot_phase: u8,
637    pub cpu_count: usize,
638    pub pick_order: [crate::process::sched::SchedClassId; 3],
639    pub steal_order: [crate::process::sched::SchedClassId; 2],
640    pub blocked_tasks: usize,
641    pub current_task: [u64; crate::arch::percpu::MAX_CPUS],
642    pub rq_rt: [usize; crate::arch::percpu::MAX_CPUS],
643    pub rq_fair: [usize; crate::arch::percpu::MAX_CPUS],
644    pub rq_idle: [usize; crate::arch::percpu::MAX_CPUS],
645    pub need_resched: [bool; crate::arch::percpu::MAX_CPUS],
646    pub deferred_work_raised: [u32; crate::arch::percpu::MAX_CPUS],
647    pub deferred_work_processed: [u32; crate::arch::percpu::MAX_CPUS],
648}
649
650/// Performs the cpu usage snapshot operation.
651pub fn cpu_usage_snapshot() -> CpuUsageSnapshot {
652    let cpu_count = active_cpu_count();
653    let mut total_ticks = [0u64; crate::arch::percpu::MAX_CPUS];
654    let mut idle_ticks = [0u64; crate::arch::percpu::MAX_CPUS];
655    for i in 0..crate::arch::percpu::MAX_CPUS {
656        if !cpu_is_online(i) {
657            continue;
658        }
659        total_ticks[i] = CPU_TOTAL_TICKS[i].load(Ordering::Relaxed);
660        idle_ticks[i] = CPU_IDLE_TICKS[i].load(Ordering::Relaxed);
661    }
662    CpuUsageSnapshot {
663        cpu_count,
664        total_ticks,
665        idle_ticks,
666    }
667}
668
669/// Performs the scheduler metrics snapshot operation.
670pub fn scheduler_metrics_snapshot() -> SchedulerMetricsSnapshot {
671    let cpu_count = active_cpu_count();
672    let dw = deferred_work::metrics_snapshot();
673    let mut rt_runtime_ticks = [0u64; crate::arch::percpu::MAX_CPUS];
674    let mut fair_runtime_ticks = [0u64; crate::arch::percpu::MAX_CPUS];
675    let mut idle_runtime_ticks = [0u64; crate::arch::percpu::MAX_CPUS];
676    let mut switch_count = [0u64; crate::arch::percpu::MAX_CPUS];
677    let mut preempt_count = [0u64; crate::arch::percpu::MAX_CPUS];
678    let mut steal_in_count = [0u64; crate::arch::percpu::MAX_CPUS];
679    let mut steal_out_count = [0u64; crate::arch::percpu::MAX_CPUS];
680    let mut try_lock_fail_count = [0u64; crate::arch::percpu::MAX_CPUS];
681    for i in 0..crate::arch::percpu::MAX_CPUS {
682        if !cpu_is_online(i) {
683            continue;
684        }
685        rt_runtime_ticks[i] = CPU_RT_RUNTIME_TICKS[i].load(Ordering::Relaxed);
686        fair_runtime_ticks[i] = CPU_FAIR_RUNTIME_TICKS[i].load(Ordering::Relaxed);
687        idle_runtime_ticks[i] = CPU_IDLE_TICKS[i].load(Ordering::Relaxed);
688        switch_count[i] = CPU_SWITCH_COUNT[i].load(Ordering::Relaxed);
689        preempt_count[i] = CPU_PREEMPT_COUNT[i].load(Ordering::Relaxed);
690        steal_in_count[i] = CPU_STEAL_IN_COUNT[i].load(Ordering::Relaxed);
691        steal_out_count[i] = CPU_STEAL_OUT_COUNT[i].load(Ordering::Relaxed);
692        try_lock_fail_count[i] = CPU_TRY_LOCK_FAIL_COUNT[i].load(Ordering::Relaxed);
693    }
694    SchedulerMetricsSnapshot {
695        cpu_count,
696        rt_runtime_ticks,
697        fair_runtime_ticks,
698        idle_runtime_ticks,
699        switch_count,
700        preempt_count,
701        steal_in_count,
702        steal_out_count,
703        try_lock_fail_count,
704        deferred_work_raised: dw.raised,
705        deferred_work_processed: dw.processed,
706    }
707}
708
709/// Performs the reset scheduler metrics operation.
710pub fn reset_scheduler_metrics() {
711    for i in 0..crate::arch::percpu::MAX_CPUS {
712        if !cpu_is_online(i) {
713            continue;
714        }
715        CPU_RT_RUNTIME_TICKS[i].store(0, Ordering::Relaxed);
716        CPU_FAIR_RUNTIME_TICKS[i].store(0, Ordering::Relaxed);
717        CPU_IDLE_TICKS[i].store(0, Ordering::Relaxed);
718        CPU_SWITCH_COUNT[i].store(0, Ordering::Relaxed);
719        CPU_PREEMPT_COUNT[i].store(0, Ordering::Relaxed);
720        CPU_STEAL_IN_COUNT[i].store(0, Ordering::Relaxed);
721        CPU_STEAL_OUT_COUNT[i].store(0, Ordering::Relaxed);
722        CPU_TRY_LOCK_FAIL_COUNT[i].store(0, Ordering::Relaxed);
723    }
724    deferred_work::reset_metrics();
725}
726
727/// Performs the note try lock fail on cpu operation.
728#[inline]
729pub(crate) fn note_try_lock_fail_on_cpu(cpu: usize) {
730    if cpu_is_valid(cpu) {
731        CPU_TRY_LOCK_FAIL_COUNT[cpu].fetch_add(1, Ordering::Relaxed);
732    }
733}
734
735/// Performs the note try lock fail operation.
736#[inline]
737pub fn note_try_lock_fail() {
738    note_try_lock_fail_on_cpu(current_cpu_index());
739}
740
741// ========== Cross-CPU IPI helpers ===============================================
742
743/// Send a reschedule IPI to `cpu_index`.
744/// No-op if APIC is not initialized, or if `cpu_index` is the current CPU
745/// (the caller already handles the local-CPU case via `yield_cpu`).
746fn send_resched_ipi_to_cpu(cpu_index: usize) {
747    if !cpu_is_valid(cpu_index) {
748        return;
749    }
750    if !apic::is_initialized() {
751        return;
752    }
753    let my_cpu = current_cpu_index();
754    let should_trace = IPI_SEND_TRACE_BUDGET
755        .try_update(Ordering::AcqRel, Ordering::Relaxed, |budget| {
756            budget.checked_sub(1)
757        })
758        .is_ok();
759    if let Some(target_apic) = percpu::apic_id_by_cpu_index(cpu_index) {
760        if let Some(my_apic) = percpu::apic_id_by_cpu_index(my_cpu) {
761            if target_apic != my_apic {
762                if RESCHED_IPI_PENDING[cpu_index].swap(true, Ordering::AcqRel) {
763                    if should_trace {
764                        crate::e9_println!(
765                            "[ipi-send-skip] from_cpu={} to_cpu={} to_apic={:#x} pending=1",
766                            my_cpu,
767                            cpu_index,
768                            target_apic
769                        );
770                    }
771                    return;
772                }
773                if should_trace {
774                    crate::e9_println!(
775                        "[ipi-send] from_cpu={} from_apic={:#x} to_cpu={} to_apic={:#x}",
776                        my_cpu,
777                        my_apic,
778                        cpu_index,
779                        target_apic
780                    );
781                }
782                apic::send_resched_ipi(target_apic);
783            }
784        }
785    }
786}
787
788/// Request a local force-reschedule hint for `cpu`.
789#[inline]
790pub(crate) fn request_force_resched_hint(cpu: usize) {
791    if cpu_is_valid(cpu) {
792        FORCE_RESCHED_HINT[cpu].store(true, Ordering::Release);
793    }
794}
795
796/// Consume and clear the local force-reschedule hint for `cpu`.
797#[inline]
798pub(crate) fn take_force_resched_hint(cpu: usize) -> bool {
799    if cpu_is_valid(cpu) {
800        FORCE_RESCHED_HINT[cpu].swap(false, Ordering::AcqRel)
801    } else {
802        false
803    }
804}
805
806/// Global scheduler state : rank 1 (root) in the total lock order.
807///
808/// This is the root lock.  It may precede all other scheduler locks but must
809/// **never** be acquired from a path that already holds a LOCAL, BLOCKED, or
810/// IDENTITY lock.
811///
812/// Protects: `all_tasks`, `task_cpu`, `zombies`, `wake_deadlines`, and the
813/// global `class_table`.  Per-CPU run queues and current-task tracking live
814/// in `LOCAL_SCHEDULERS` (rank 4).  Blocked tasks are in `BLOCKED_TASKS`
815/// (rank 3).  Identity maps are in `SCHED_IDENTITY` (rank 2).
816pub(crate) static GLOBAL_SCHED_STATE: SpinLock<Option<GlobalSchedState>> = SpinLock::new(None);
817
818/// Returns the scheduler lock address for deadlock tracing.
819pub fn debug_scheduler_lock_addr() -> usize {
820    &GLOBAL_SCHED_STATE as *const _ as usize
821}
822
823/// Global tick counter (safe to increment from interrupt context)
824static TICK_COUNT: AtomicU64 = AtomicU64::new(0);
825/// Verbose scheduler trace switch.
826static SCHED_VERBOSE: AtomicBool = AtomicBool::new(false);
827
828/// Performs the sched trace operation.
829#[inline]
830fn sched_trace(args: core::fmt::Arguments<'_>) {
831    if SCHED_VERBOSE.load(Ordering::Relaxed) {
832        log::debug!("[sched] {}", args);
833    }
834}
835
836/// Information needed to perform a context switch after releasing the lock.
837///
838/// # Safety invariants
839///
840/// `SwitchTarget` contains raw pointers into `Arc<Task>` objects.  All five
841/// invariants below must hold at the moment `do_switch_context` / `switch_context`
842/// reads them.  They are established by `yield_cpu_local` under the LOCAL lock
843/// and consumed before any other CPU can observe the pointed-to memory.
844///
845/// 1. **`old_rsp_ptr`** points to `(*source.context.get()).saved_rsp`.
846///    The `source` Arc<Task> is kept alive by `cpu.current_task` or
847///    `cpu.task_to_requeue` for the duration of the switch; no migration,
848///    reap, or exit can invalidate it while the lock is held.
849///
850/// 2. **`new_rsp_ptr`** points to `(*target.context.get()).saved_rsp`.
851///    Same lifetime guarantee as above: `target` is in `cpu.current_task`.
852///
853/// 3. **`old_fpu_ptr` / `new_fpu_ptr`** point into the FPU state areas of
854///    the source / target tasks respectively.  These areas sit inside the
855///    kernel stack and are valid as long as the owning `Arc<Task>` is alive.
856///    FPU state is never modified concurrently: the switch context owns it
857///    exclusively between the save and restore.
858///
859/// 4. **`old_xcr0` / `new_xcr0`** are the XCR0 masks of source and target,
860///    read atomically from `task.xcr0_mask`.  They are only consumed by the
861///    switch assembly which toggles XCR0 around xsave/xrstor.
862///
863/// 5. **Lifetime**: `SwitchTarget` must not outlive the LOCAL lock that
864///    protected its construction.  It is consumed by `do_switch_context`
865///    immediately after the lock is released, before any allocation, IPI,
866///    or scheduler operation.
867///
868/// # Debug checks
869///
870/// Under `cfg(debug_assertions)`, `prepare_switch_target` validates that
871/// `old_rsp` / `new_rsp` fall within their respective kernel stacks before
872/// returning this struct.
873pub(super) struct SwitchTarget {
874    pub(super) old_rsp_ptr: *mut u64,
875    pub(super) new_rsp_ptr: *const u64,
876    pub(super) old_fpu_ptr: *mut u8,
877    pub(super) new_fpu_ptr: *const u8,
878    pub(super) old_xcr0: u64,
879    pub(super) new_xcr0: u64,
880}
881
882// SAFETY: SwitchTarget is only constructed under LOCAL lock on the owning CPU
883// and consumed by do_switch_context before any other CPU can observe the
884// pointed-to memory.  The Arc<Task> objects are kept alive by current_task /
885// task_to_requeue for the full duration.  No concurrent modification of the
886// pointed-to context or FPU state occurs between construction and consumption.
887unsafe impl Send for SwitchTarget {}
888
889/// Result of a non-blocking wait on child exit.
890pub enum WaitChildResult {
891    Reaped {
892        child: TaskId,
893        pid: Pid,
894        status: i32,
895    },
896    NoChildren,
897    StillRunning,
898}
899
900/// Performs the current cpu index operation.
901fn current_cpu_index() -> usize {
902    crate::arch::percpu::current_cpu_index()
903}
904
905struct PerCpuClassRqSet {
906    real_time: crate::process::sched::real_time::RealTimeClassRq,
907    fair: crate::process::sched::fair::FairClassRq,
908    idle: crate::process::sched::idle::IdleClassRq,
909}
910
911impl PerCpuClassRqSet {
912    /// Creates a new instance.
913    fn new() -> Self {
914        Self {
915            real_time: crate::process::sched::real_time::RealTimeClassRq::new(),
916            fair: crate::process::sched::fair::FairClassRq::new(),
917            idle: crate::process::sched::idle::IdleClassRq::new(),
918        }
919    }
920
921    /// Performs the enqueue operation.
922    fn enqueue(&mut self, class: crate::process::sched::SchedClassId, task: Arc<Task>) {
923        use crate::process::sched::SchedClassRq;
924        match class {
925            crate::process::sched::SchedClassId::Fair => self.fair.enqueue(task),
926            crate::process::sched::SchedClassId::RealTime => self.real_time.enqueue(task),
927            crate::process::sched::SchedClassId::Idle => self.idle.enqueue(task),
928        }
929    }
930
931    /// Performs the len by class operation.
932    fn len_by_class(&self, class: crate::process::sched::SchedClassId) -> usize {
933        use crate::process::sched::SchedClassRq;
934        match class {
935            crate::process::sched::SchedClassId::Fair => self.fair.len(),
936            crate::process::sched::SchedClassId::RealTime => self.real_time.len(),
937            crate::process::sched::SchedClassId::Idle => self.idle.len(),
938        }
939    }
940
941    /// Performs the runnable len operation.
942    fn runnable_len(&self) -> usize {
943        self.len_by_class(crate::process::sched::SchedClassId::RealTime)
944            + self.len_by_class(crate::process::sched::SchedClassId::Fair)
945    }
946
947    /// Performs the pick next by class operation.
948    fn pick_next_by_class(
949        &mut self,
950        class: crate::process::sched::SchedClassId,
951    ) -> Option<Arc<Task>> {
952        use crate::process::sched::SchedClassRq;
953        match class {
954            crate::process::sched::SchedClassId::Fair => self.fair.pick_next(),
955            crate::process::sched::SchedClassId::RealTime => self.real_time.pick_next(),
956            crate::process::sched::SchedClassId::Idle => self.idle.pick_next(),
957        }
958    }
959
960    /// Performs the pick next operation.
961    fn pick_next(&mut self, table: &crate::process::sched::SchedClassTable) -> Option<Arc<Task>> {
962        for class in table.pick_order().iter().copied() {
963            if let Some(task) = self.pick_next_by_class(class) {
964                return Some(task);
965            }
966        }
967        None
968    }
969
970    /// Updates current.
971    fn update_current(
972        &mut self,
973        rt: &crate::process::sched::CurrentRuntime,
974        task: &Task,
975        is_yield: bool,
976        table: &crate::process::sched::SchedClassTable,
977    ) -> bool {
978        use crate::process::sched::SchedClassRq;
979        let should_preempt = match table.class_for_task(task) {
980            crate::process::sched::SchedClassId::Fair => {
981                self.fair.update_current(rt, task, is_yield)
982            }
983            crate::process::sched::SchedClassId::RealTime => {
984                self.real_time.update_current(rt, task, is_yield)
985            }
986            crate::process::sched::SchedClassId::Idle => {
987                self.idle.update_current(rt, task, is_yield)
988            }
989        };
990        // Always preempt idle task if there are other tasks ready
991        let any_ready = !self.real_time.is_empty() || !self.fair.is_empty();
992        should_preempt
993            || (table.class_for_task(task) == crate::process::sched::SchedClassId::Idle
994                && any_ready)
995    }
996
997    /// Performs the remove operation.
998    fn remove(&mut self, task_id: crate::process::TaskId) -> bool {
999        use crate::process::sched::SchedClassRq;
1000        self.real_time.remove(task_id) || self.fair.remove(task_id) || self.idle.remove(task_id)
1001    }
1002
1003    /// Called once per timer tick.  Increments wait-time counters for all
1004    /// queued tasks across all classes.  Used for Fair starvation detection.
1005    fn tick_update_wait(&mut self) {
1006        use crate::process::sched::SchedClassRq;
1007        self.fair.tick_update_wait();
1008    }
1009
1010    /// Performs the steal candidate operation.
1011    fn steal_candidate(
1012        &mut self,
1013        table: &crate::process::sched::SchedClassTable,
1014    ) -> Option<Arc<Task>> {
1015        for class in table.steal_order().iter().copied() {
1016            if let Some(task) = self.pick_next_by_class(class) {
1017                return Some(task);
1018            }
1019        }
1020        None
1021    }
1022}
1023
1024/// Per-CPU scheduler state
1025pub(crate) struct SchedulerCpu {
1026    /// Multi-class priority queues
1027    class_rqs: PerCpuClassRqSet,
1028    /// Currently running task
1029    current_task: Option<Arc<Task>>,
1030    /// Current runtime accounting
1031    current_runtime: crate::process::sched::CurrentRuntime,
1032    /// Idle task to run when no other tasks are ready
1033    idle_task: Arc<Task>,
1034    /// Task that was just preempted and needs to be re-queued
1035    task_to_requeue: Option<Arc<Task>>,
1036    /// Task that is dying or blocked, to drop outside the scheduler lock
1037    task_to_drop: Option<Arc<Task>>,
1038    /// Flag indicating if the current task's time slice has expired
1039    need_resched: bool,
1040    /// Local copy of the class table for hot-path use without GLOBAL lock.
1041    /// Updated atomically when the global class table changes.
1042    class_table: crate::process::sched::SchedClassTable,
1043}
1044
1045/// Per-CPU local scheduler locks : rank 4 in the total lock order.
1046///
1047/// Acquired after `GLOBAL_SCHED_STATE`, `SCHED_IDENTITY`, and `BLOCKED_TASKS`.
1048/// **Never** hold two LOCAL locks simultaneously.
1049/// Cross-CPU operations use a two-phase protocol: detach under source LOCAL,
1050/// release, then attach under destination LOCAL.
1051#[allow(dead_code)]
1052pub(crate) static LOCAL_SCHEDULERS: [SpinLock<Option<SchedulerCpu>>;
1053    crate::arch::percpu::MAX_CPUS] = [const { SpinLock::new(None) }; crate::arch::percpu::MAX_CPUS];
1054
1055/// Blocked tasks registry : rank 3 in the total lock order.
1056///
1057/// `BLOCKED_TASKS` must be acquired **after** `GLOBAL_SCHED_STATE` and
1058/// `SCHED_IDENTITY` (write), and **before** `LOCAL_SCHEDULERS[cpu]`.
1059/// It is **never** acquired from a path that already holds a LOCAL lock.
1060///
1061/// A task appears here if and only if its `SchedState` is `Blocked`.
1062pub(crate) static BLOCKED_TASKS: SpinLock<BTreeMap<TaskId, Arc<Task>>> =
1063    SpinLock::new(BTreeMap::new());
1064
1065/// Identity maps : rank 2 (write) / 2R (read) in the total lock order.
1066///
1067/// `SCHED_IDENTITY` write is acquired after `GLOBAL_SCHED_STATE` and before
1068/// `BLOCKED_TASKS` or `LOCAL_SCHEDULERS[cpu]`.
1069///
1070/// `SCHED_IDENTITY` read is **observational only**: copy the result, release,
1071/// then begin any mutating operation.  No scheduler lock may be acquired
1072/// while holding the read guard.
1073///
1074/// Upgraded to `RwLock` so that concurrent readers (`getpid`, `getpgid`,
1075/// `get_task_by_pid`) do not serialize.
1076pub(crate) static SCHED_IDENTITY: SpinRwLock<SchedIdentity> = SpinRwLock::new(SchedIdentity::new());
1077
1078/// Identity maps for the scheduler: PID/TID routing, process groups,
1079/// session membership, and parent/child relationships.
1080///
1081/// Lives behind the `SCHED_IDENTITY` lock, separate from `GLOBAL_SCHED_STATE`
1082/// so that syscall lookups (`getpid`, `getpgid`, `setpgid`, `setsid`, etc.)
1083/// never contend with fork/exit or block/wake paths.
1084pub struct SchedIdentity {
1085    /// Map userspace PID -> internal TaskId (process leader in current model).
1086    pub pid_to_task: BTreeMap<Pid, TaskId>,
1087    /// Map userspace TID -> internal TaskId (fast thread lookup).
1088    pub tid_to_task: BTreeMap<Tid, TaskId>,
1089    /// Map PID -> process group id.
1090    pub pid_to_pgid: BTreeMap<Pid, Pid>,
1091    /// Map PID -> session id.
1092    pub pid_to_sid: BTreeMap<Pid, Pid>,
1093    /// Group membership index: pgid -> task ids.
1094    pub pgid_members: BTreeMap<Pid, alloc::vec::Vec<TaskId>>,
1095    /// Session membership index: sid -> task ids.
1096    pub sid_members: BTreeMap<Pid, alloc::vec::Vec<TaskId>>,
1097    /// Parent relationship: child -> parent
1098    pub parent_of: BTreeMap<TaskId, TaskId>,
1099    /// Children list: parent -> children
1100    pub children_of: BTreeMap<TaskId, alloc::vec::Vec<TaskId>>,
1101}
1102
1103impl SchedIdentity {
1104    /// Creates a new empty identity registry.
1105    pub const fn new() -> Self {
1106        Self {
1107            pid_to_task: BTreeMap::new(),
1108            tid_to_task: BTreeMap::new(),
1109            pid_to_pgid: BTreeMap::new(),
1110            pid_to_sid: BTreeMap::new(),
1111            pgid_members: BTreeMap::new(),
1112            sid_members: BTreeMap::new(),
1113            parent_of: BTreeMap::new(),
1114            children_of: BTreeMap::new(),
1115        }
1116    }
1117}
1118
1119/// Global task registry : cold path: fork, exit, all_tasks scan.
1120///
1121/// Lock order: acquire GLOBAL_SCHED_STATE before LOCAL when both are needed.
1122/// Per-CPU runqueues and current-task tracking live in `LOCAL_SCHEDULERS`.
1123/// Blocked tasks are tracked in `BLOCKED_TASKS` (separate lock).
1124/// Identity maps (PID/TID, pgid, sid, parent/child) are in `SCHED_IDENTITY` (separate lock).
1125/// This struct holds only data that is accessed by cold paths (fork, exit,
1126/// all_tasks scan, zombie management, wake deadlines) and is protected by the
1127/// `GLOBAL_SCHED_STATE` lock.
1128pub struct GlobalSchedState {
1129    /// All tasks in the system (for lookup by TaskId)
1130    pub(crate) all_tasks: BTreeMap<TaskId, Arc<Task>>,
1131    /// Map TaskId -> CPU index (for wake/resume routing)
1132    task_cpu: BTreeMap<TaskId, usize>,
1133    /// Deadline -> task ids map for sleeping tasks (ordered wakeups).
1134    #[allow(dead_code)]
1135    wake_deadlines: BTreeMap<u64, alloc::vec::Vec<TaskId>>,
1136    /// Task -> deadline reverse index.
1137    #[allow(dead_code)]
1138    wake_deadline_of: BTreeMap<TaskId, u64>,
1139    /// Zombie exit statuses: child -> (exit_code, pid)
1140    zombies: BTreeMap<TaskId, (i32, Pid)>,
1141    /// Scheduler class table (pick order, steal order, class metadata)
1142    class_table: crate::process::sched::SchedClassTable,
1143}
1144
1145/// Performs the validate task context operation.
1146fn validate_task_context(task: &Arc<Task>) -> Result<(), &'static str> {
1147    let saved_rsp = unsafe { (*task.context.get()).saved_rsp };
1148    let stack_base = task.kernel_stack.virt_base.as_u64();
1149    let stack_top = stack_base.saturating_add(task.kernel_stack.size as u64);
1150
1151    if saved_rsp < stack_base || saved_rsp.saturating_add(56) > stack_top {
1152        return Err("saved_rsp outside kernel stack bounds");
1153    }
1154
1155    // ABI alignment: saved_rsp must be 8-byte aligned (x86-64 ABI requirement).
1156    if saved_rsp & 7 != 0 {
1157        return Err("saved_rsp not 8-byte aligned");
1158    }
1159
1160    // Return IP is at [saved_rsp + 48] in our switch frame layout.
1161    let ret_ip = unsafe { core::ptr::read_unaligned((saved_rsp + 48) as *const u64) };
1162    if ret_ip == 0 {
1163        return Err("null return IP in switch frame");
1164    }
1165
1166    // This frame is consumed by the kernel's ret-based context switch. Even
1167    // though low addresses (including 0x2) are canonical x86-64 addresses,
1168    // they can never be valid return targets for a saved kernel context.
1169    if ret_ip < 0xFFFF_8000_0000_0000 {
1170        return Err("return IP is outside the kernel address space");
1171    }
1172
1173    // ExtendedState is embedded in the Arc-owned Task, not in kernel_stack.
1174    // The owning Arc keeps the save area alive across the context switch.
1175    // Check the alignment required by XSAVE/XRSTOR (also sufficient for FXSAVE).
1176    let fpu_ptr = task.fpu_state.get() as usize;
1177    if fpu_ptr % core::mem::align_of::<crate::process::task::ExtendedState>() != 0 {
1178        return Err("FPU state not aligned for context restore");
1179    }
1180
1181    Ok(())
1182}
1183
1184// ---------------------------------------------------------------------------
1185// Debug invariant validator
1186// ---------------------------------------------------------------------------
1187
1188/// Validate scheduler-wide invariants in debug builds.
1189///
1190/// Uses `try_lock` everywhere so it can be called from `finish_switch` without
1191/// blocking.  Silently skips if any lock is contended.
1192///
1193/// Panics with a diagnostic message on the first invariant violation.
1194#[cfg(debug_assertions)]
1195#[allow(dead_code)]
1196pub(crate) fn validate_scheduler_invariants() {
1197    let n = active_cpu_count();
1198    let mut seen_current: alloc::collections::BTreeSet<TaskId> =
1199        alloc::collections::BTreeSet::new();
1200
1201    // 1. Each CPU has at most one current_task; no task is current on two CPUs.
1202    for cpu_idx in 0..crate::arch::percpu::MAX_CPUS {
1203        if !cpu_is_online(cpu_idx) {
1204            continue;
1205        }
1206        let guard = match LOCAL_SCHEDULERS[cpu_idx].try_lock() {
1207            Some(g) => g,
1208            None => return, // Lock contended, skip validation.
1209        };
1210        if let Some(ref cpu) = *guard {
1211            if let Some(ref current) = cpu.current_task {
1212                let tid = current.id;
1213                if !Arc::ptr_eq(current, &cpu.idle_task) {
1214                    assert!(
1215                        seen_current.insert(tid),
1216                        "scheduler invariant: task {} is current on multiple CPUs (cpu={})",
1217                        tid.as_u64(),
1218                        cpu_idx
1219                    );
1220                }
1221            }
1222        }
1223    }
1224
1225    // 2. task_cpu consistency + zombie isolation.
1226    {
1227        let sched_guard = match GLOBAL_SCHED_STATE.try_lock() {
1228            Some(g) => g,
1229            None => return,
1230        };
1231        if let Some(ref sched) = *sched_guard {
1232            for (tid, &cpu_idx) in sched.task_cpu.iter() {
1233                let state = sched.all_tasks.get(tid).map(|t| t.get_state());
1234                match state {
1235                    Some(TaskState::Ready) | Some(TaskState::Running) => {
1236                        assert!(
1237                            cpu_is_online(cpu_idx),
1238                            "scheduler invariant: task_cpu[{}] = {} but that CPU is not online (online_count = {})",
1239                            tid.as_u64(),
1240                            cpu_idx,
1241                            n
1242                        );
1243                    }
1244                    _ => {}
1245                }
1246            }
1247            for (tid, _) in sched.zombies.iter() {
1248                assert!(
1249                    !seen_current.contains(tid),
1250                    "scheduler invariant: zombie task {} is current on a CPU",
1251                    tid.as_u64()
1252                );
1253            }
1254        }
1255    }
1256}
1257
1258#[cfg(not(debug_assertions))]
1259#[inline]
1260pub(crate) fn validate_scheduler_invariants() {}
1261
1262/// Check that `SCHED_IDENTITY` read is not held (observational-only contract).
1263#[cfg(debug_assertions)]
1264#[allow(dead_code)]
1265pub(crate) fn assert_no_identity_read_held() {
1266    lockdep_assert_no_locks();
1267}
1268
1269mod core_impl;
1270pub mod deferred_work;
1271pub mod perf_counters;
1272mod runtime_ops;
1273mod task_ops;
1274mod timer_ops;
1275
1276pub use runtime_ops::*;
1277pub use task_ops::*;
1278pub use timer_ops::*;
1279
1280// Re-export deferred work module for metrics and raise functions.
1281pub use deferred_work::{
1282    has_pending, metrics_snapshot as deferred_work_metrics, process_deferred_work,
1283    raise_deferred_work, raise_tick_deferred_work, reset_metrics as reset_deferred_work_metrics,
1284    DeferredWork, DeferredWorkMetrics,
1285};