1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum SchedState {
108 New,
110 Runnable { cpu: usize },
112 Running { cpu: usize },
114 Blocked,
116 Zombie,
118 Reaped,
120}
121
122impl SchedState {
123 #[inline]
125 pub fn is_runnable_like(self) -> bool {
126 matches!(
127 self,
128 SchedState::Runnable { .. } | SchedState::Running { .. }
129 )
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139#[repr(u8)]
140pub(crate) enum LockRank {
141 Global = 1,
143 IdentityW = 2,
145 IdentityR = 3,
147 Blocked = 4,
149 Local = 5,
151 #[allow(dead_code)] TaskInternal = 6,
154}
155
156#[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 #[allow(dead_code)] cpu: Option<usize>,
171 #[allow(dead_code)] 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 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 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 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 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 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 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 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 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 #[allow(dead_code)] pub(crate) fn current_depth(&self) -> usize {
287 self.depth
288 }
289}
290
291#[cfg(debug_assertions)]
294static mut LOCKDEP: [LockdepState; crate::arch::percpu::MAX_CPUS] =
295 [const { LockdepState::new() }; crate::arch::percpu::MAX_CPUS];
296
297#[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#[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#[cfg(debug_assertions)]
322#[inline]
323pub(crate) fn lockdep_release(rank: LockRank) {
324 unsafe { LOCKDEP[current_cpu_index()].release(rank) };
325}
326
327#[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#[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#[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)] pub(crate) fn lockdep_assert_no_locks() {}
355#[cfg(not(debug_assertions))]
356#[inline]
357pub(crate) fn lockdep_assert_held(_rank: LockRank) {}
358
359static 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
383pub(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
395pub(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
405pub(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);
453static 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];
460pub(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#[inline]
475pub(crate) fn active_cpu_count() -> usize {
476 crate::arch::percpu::online_count().max(1)
477}
478
479#[inline]
481fn cpu_is_valid(cpu: usize) -> bool {
482 cpu < crate::arch::percpu::MAX_CPUS
483}
484
485#[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#[inline]
496pub(crate) fn cpu_has_scheduler(cpu: usize) -> bool {
497 cpu_is_online(cpu) && LOCAL_SCHEDULERS[cpu].lock().is_some()
498}
499
500#[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
510pub(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
543pub(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
568pub(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
650pub 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
669pub 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
709pub 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#[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#[inline]
737pub fn note_try_lock_fail() {
738 note_try_lock_fail_on_cpu(current_cpu_index());
739}
740
741fn 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#[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#[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
806pub(crate) static GLOBAL_SCHED_STATE: SpinLock<Option<GlobalSchedState>> = SpinLock::new(None);
817
818pub fn debug_scheduler_lock_addr() -> usize {
820 &GLOBAL_SCHED_STATE as *const _ as usize
821}
822
823static TICK_COUNT: AtomicU64 = AtomicU64::new(0);
825static SCHED_VERBOSE: AtomicBool = AtomicBool::new(false);
827
828#[inline]
830fn sched_trace(args: core::fmt::Arguments<'_>) {
831 if SCHED_VERBOSE.load(Ordering::Relaxed) {
832 log::debug!("[sched] {}", args);
833 }
834}
835
836pub(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
882unsafe impl Send for SwitchTarget {}
888
889pub enum WaitChildResult {
891 Reaped {
892 child: TaskId,
893 pid: Pid,
894 status: i32,
895 },
896 NoChildren,
897 StillRunning,
898}
899
900fn 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 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 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 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 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 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 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 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 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 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 fn tick_update_wait(&mut self) {
1006 use crate::process::sched::SchedClassRq;
1007 self.fair.tick_update_wait();
1008 }
1009
1010 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
1024pub(crate) struct SchedulerCpu {
1026 class_rqs: PerCpuClassRqSet,
1028 current_task: Option<Arc<Task>>,
1030 current_runtime: crate::process::sched::CurrentRuntime,
1032 idle_task: Arc<Task>,
1034 task_to_requeue: Option<Arc<Task>>,
1036 task_to_drop: Option<Arc<Task>>,
1038 need_resched: bool,
1040 class_table: crate::process::sched::SchedClassTable,
1043}
1044
1045#[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
1055pub(crate) static BLOCKED_TASKS: SpinLock<BTreeMap<TaskId, Arc<Task>>> =
1063 SpinLock::new(BTreeMap::new());
1064
1065pub(crate) static SCHED_IDENTITY: SpinRwLock<SchedIdentity> = SpinRwLock::new(SchedIdentity::new());
1077
1078pub struct SchedIdentity {
1085 pub pid_to_task: BTreeMap<Pid, TaskId>,
1087 pub tid_to_task: BTreeMap<Tid, TaskId>,
1089 pub pid_to_pgid: BTreeMap<Pid, Pid>,
1091 pub pid_to_sid: BTreeMap<Pid, Pid>,
1093 pub pgid_members: BTreeMap<Pid, alloc::vec::Vec<TaskId>>,
1095 pub sid_members: BTreeMap<Pid, alloc::vec::Vec<TaskId>>,
1097 pub parent_of: BTreeMap<TaskId, TaskId>,
1099 pub children_of: BTreeMap<TaskId, alloc::vec::Vec<TaskId>>,
1101}
1102
1103impl SchedIdentity {
1104 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
1119pub struct GlobalSchedState {
1129 pub(crate) all_tasks: BTreeMap<TaskId, Arc<Task>>,
1131 task_cpu: BTreeMap<TaskId, usize>,
1133 #[allow(dead_code)]
1135 wake_deadlines: BTreeMap<u64, alloc::vec::Vec<TaskId>>,
1136 #[allow(dead_code)]
1138 wake_deadline_of: BTreeMap<TaskId, u64>,
1139 zombies: BTreeMap<TaskId, (i32, Pid)>,
1141 class_table: crate::process::sched::SchedClassTable,
1143}
1144
1145fn 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 if saved_rsp & 7 != 0 {
1157 return Err("saved_rsp not 8-byte aligned");
1158 }
1159
1160 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 if ret_ip < 0xFFFF_8000_0000_0000 {
1170 return Err("return IP is outside the kernel address space");
1171 }
1172
1173 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#[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 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, };
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 {
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#[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
1280pub 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};