ostd/task/scheduler/mod.rs
1// SPDX-License-Identifier: MPL-2.0
2//! Task scheduling.
3//!
4//! # Scheduler Injection
5//!
6//! The task scheduler of an OS is a complex beast,
7//! and the most suitable scheduling algorithm often depends on the target usage scenario.
8//! To avoid code bloat and offer flexibility,
9//! OSTD does not include a gigantic, one-size-fits-all task scheduler.
10//! Instead, it allows the client to implement a custom scheduler (in safe Rust, of course)
11//! and register it with OSTD.
12//! This feature is known as **scheduler injection**.
13//!
14//! The client kernel performs scheduler injection via the [`inject_scheduler`] API.
15//! This API should be called as early as possible during kernel initialization,
16//! before any [`Task`]-related APIs are used.
17//! This requirement is reasonable since `Task`s depend on the scheduler.
18//!
19//! # Scheduler Abstraction
20//!
21//! The `inject_scheduler` API accepts an object implementing the [`Scheduler`] trait,
22//! which abstracts over any SMP-aware task scheduler.
23//! Whenever an OSTD client spawns a new task (via [`crate::task::TaskOptions`])
24//! or wakes a sleeping task (e.g., via [`crate::sync::Waker`]),
25//! OSTD internally forwards the corresponding `Arc<Task>`
26//! to the scheduler by invoking the [`Scheduler::enqueue`] method.
27//! This allows the injected scheduler to manage all runnable tasks.
28//!
29//! Each enqueued task is dispatched to one of the per-CPU local runqueues,
30//! which manage all runnable tasks on a specific CPU.
31//! A local runqueue is abstracted by the [`LocalRunQueue`] trait.
32//! OSTD accesses the local runqueue of the current CPU
33//! via [`Scheduler::local_rq_with`] or [`Scheduler::mut_local_rq_with`],
34//! which return immutable and mutable references to `dyn LocalRunQueue`, respectively.
35//!
36//! The [`LocalRunQueue`] trait enables OSTD to inspect and manipulate local runqueues.
37//! For instance, OSTD invokes the [`LocalRunQueue::pick_next`] method
38//! to let the scheduler select the next task to run.
39//! OSTD then performs a context switch to that task,
40//! which becomes the _current_ running task, accessible via [`LocalRunQueue::current`].
41//! When the current task is about to sleep (e.g., via [`crate::sync::Waiter`]),
42//! OSTD removes it from the local runqueue using [`LocalRunQueue::dequeue_current`].
43//!
44//! The interfaces of `Scheduler` and `LocalRunQueue` are simple
45//! yet (perhaps surprisingly) powerful enough to support
46//! even complex and advanced task scheduler implementations.
47//! Scheduler implementations are free to employ any load-balancing strategy
48//! to dispatch enqueued tasks across local runqueues,
49//! and each local runqueue is free to choose any prioritization strategy
50//! for selecting the next task to run.
51//! Based on OSTD's scheduling abstractions,
52//! the Asterinas kernel has successfully supported multiple Linux scheduling classes,
53//! including both real-time and normal policies.
54//!
55//! # Safety Impact
56//!
57//! While OSTD delegates scheduling decisions to the injected task scheduler,
58//! it verifies these decisions to avoid undefined behavior.
59//! In particular, it enforces the following safety invariant:
60//!
61//! > A task must not be scheduled to run on more than one CPU at a time.
62//!
63//! Violating this invariant—e.g., running the same task on two CPUs concurrently—
64//! can have catastrophic consequences,
65//! as the task's stack and internal state may be corrupted by concurrent modifications.
66// mod fifo_scheduler;
67pub mod info;
68#[cfg(feature = "irc11")]
69mod thread_view;
70use spin::Once;
71
72// use super::{preempt::cpu_local, processor, Task};
73use super::Task;
74// use crate::{
75// cpu::{CpuId, CpuSet, PinCurrentCpu},
76// task::disable_preempt,
77// timer,
78// };
79use crate::{cpu::CpuId, prelude::*};
80
81#[cfg(feature = "irc11")]
82pub use self::thread_view::SchedulerIrc11State;
83
84/// Injects a custom implementation of task scheduler into OSTD.
85///
86/// This function can only be called once and must be called during the initialization phase of kernel,
87/// before any [`Task`]-related APIs are invoked.
88pub fn inject_scheduler(scheduler: &'static dyn Scheduler<Task>) {
89 /* SCHEDULER.call_once(|| scheduler);
90
91 timer::register_callback(|| {
92 SCHEDULER.get().unwrap().mut_local_rq_with(&mut |local_rq| {
93 let should_pick_next = local_rq.update_current(UpdateFlags::Tick);
94 if should_pick_next {
95 cpu_local::set_need_preempt();
96 }
97 })
98 }); */
99}
100
101static SCHEDULER: Once<&'static dyn Scheduler<Task>> = Once::new();
102
103/// A SMP-aware task scheduler.
104pub trait Scheduler<T = Task>: Sync + Send {
105 /// Enqueues a runnable task.
106 ///
107 /// The scheduler implementer can perform load-balancing or some time accounting work here.
108 ///
109 /// The newly-enqueued task may have a higher priority than the currently running one on a CPU
110 /// and thus should preempt the latter.
111 /// In this case, this method returns the ID of that CPU.
112 fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<CpuId>;
113
114 /// Gets an immutable access to the local runqueue of the current CPU.
115 fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>));
116
117 /// Gets a mutable access to the local runqueue of the current CPU.
118 fn mut_local_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>));
119}
120
121/// A per-CPU, local runqueue.
122///
123/// This abstraction allows OSTD to inspect and manipulate local runqueues.
124///
125/// Conceptually, a local runqueue maintains:
126/// 1. A priority queue of runnable tasks.
127/// The definition of "priority" is left to the concrete implementation.
128/// 2. The current running task.
129///
130/// # Interactions with OSTD
131///
132/// ## Overview
133///
134/// It is crucial for implementers of `LocalRunQueue`
135/// to understand how OSTD interacts with local runqueues.
136///
137/// A local runqueue is consulted by OSTD in response to one of four scheduling events:
138/// - **Yielding**, triggered by [`Task::yield_now`], where the current task voluntarily gives up CPU time.
139/// - **Sleeping**, triggered by [`crate::sync::Waiter::wait`]
140/// or any synchronization primitive built upon it (e.g., [`crate::sync::WaitQueue`], [`crate::sync::Mutex`]),
141/// which blocks the current task until a wake-up event occurs.
142/// - **Ticking**, triggered periodically by the system timer
143/// (see [`crate::arch::timer::TIMER_FREQ`]),
144/// which provides an opportunity to do time accounting and consider preemption.
145/// - **Exiting**, triggered when the execution logic of a task has come to an end,
146/// which informs the scheduler that the task is exiting and will never be enqueued again.
147///
148/// The general workflow for OSTD to handle a scheduling event is as follows:
149/// 1. Acquire exclusive access to the local runqueue using [`Scheduler::mut_local_rq_with`].
150/// 2. Call [`LocalRunQueue::update_current`] to update the current task's state,
151/// returning a boolean value that indicates
152/// whether the current task should and can be replaced with another runnable task.
153/// 3. If the task is about to sleep or exit, call [`LocalRunQueue::dequeue_current`]
154/// to remove it from the runqueue.
155/// 4. If the return value of `update_current` in Step 2 is true,
156/// then select the next task to run with [`LocalRunQueue::pick_next`].
157///
158/// ## When to Pick the Next Task?
159///
160/// As shown above,
161/// OSTD guarantees that `pick_next` is only called
162/// when the current task should and can be replaced.
163/// This avoids unnecessary invocations and improves efficiency.
164///
165/// But under what conditions should the current task be replaced?
166/// Two criteria must be met:
167/// 1. There exists at least one other runnable task in the runqueue.
168/// 2. That task should preempt the current one, if present.
169///
170/// Some implications of these rules:
171/// - If the runqueue is empty, `update_current` must return `false`—there's nothing to run.
172/// - If the runqueue is non-empty but the current task is absent,
173/// `update_current` should return `true`—anything is better than nothing.
174/// - If the runqueue is non-empty and the flag is `UpdateFlags::WAIT`,
175/// `update_current` should also return `true`,
176/// because the current task is about to block.
177/// - In other cases, the return value depends on the scheduler's prioritization policy.
178/// For instance, a real-time task may only be preempted by a higher-priority task
179/// or if it explicitly yields.
180/// A normal task under Linux's CFS may be preempted by a task with smaller vruntime,
181/// but never by the idle task.
182///
183/// When OSTD is unsure about whether the current task should or can be replaced,
184/// it will invoke [`LocalRunQueue::try_pick_next`], the fallible version of `pick_next`.
185///
186/// ## Internal Working
187///
188/// To guide scheduler implementers,
189/// we provide a simplified view of how OSTD interacts with local runqueues _internally_
190/// in order to handle the four scheduling events.
191///
192/// ### Yielding
193///
194/// ```
195/// # use ostd::prelude::*;
196/// # use ostd::task::{*, scheduler::*};
197/// #
198/// # fn switch_to(next: Arc<Task>) {}
199/// #
200/// /// Yields the current task.
201/// fn yield(scheduler: &'static dyn Scheduler) {
202/// let next_task_opt: Option<Arc<Task>> = scheduler.mut_local_rq_with(|local_rq| {
203/// let should_pick_next = local_rq.update_current(UpdateFlags::Yield);
204/// should_pick_next.then(|| local_rq.pick_next().clone())
205/// });
206/// let Some(next_task) = next_task_opt {
207/// switch_to(next_task);
208/// }
209/// }
210/// ```
211///
212/// ### Sleeping
213///
214/// ```
215/// # use ostd::prelude::*;
216/// # use ostd::task::{*, scheduler::*};
217/// #
218/// # fn switch_to(next: Arc<Task>) {}
219/// #
220/// /// Puts the current task to sleep.
221/// ///
222/// /// The function takes a closure to check if the task is woken.
223/// /// This function is used internally to guard against race conditions,
224/// /// where the task is woken just before it goes to sleep.
225/// fn sleep<F: Fn() -> bool>(scheduler: &'static dyn Scheduler, is_woken: F) {
226/// let mut next_task_opt: Option<Arc<Task>> = None;
227/// let mut is_first_try = true;
228/// while scheduler.mut_local_rq_with(|local_rq| {
229/// if is_first_try {
230/// if is_woken() {
231/// return false; // exit loop
232/// }
233/// is_first_try = false;
234///
235/// let should_pick_next = local_rq.update_current(UpdateFlags::Wait);
236/// let _current = local_rq.dequeue_current();
237/// if !should_pick_next {
238/// return true; // continue loop
239/// }
240/// next_task_opt = Some(local_rq.pick_next().clone());
241/// false // exit loop
242/// } else {
243/// next_task_opt = local_rq.try_pick_next().cloned();
244/// next_task_opt.is_none()
245/// }
246/// }) {}
247/// let Some(next_task) = next_task_opt {
248/// switch_to(next_task);
249/// }
250/// }
251/// ```
252///
253/// ### Ticking
254///
255/// ```
256/// # use ostd::prelude::*;
257/// # use ostd::task::{*, scheduler::*};
258/// #
259/// # fn switch_to(next: Arc<Task>) {}
260/// # mod cpu_local {
261/// # fn set_need_preempt();
262/// # fn should_preempt() -> bool;
263/// # }
264/// #
265/// /// A callback to be invoked periodically by the timer interrupt.
266/// fn on_tick(scheduler: &'static dyn Scheduler) {
267/// scheduler.mut_local_rq_with(|local_rq| {
268/// let should_pick_next = local_rq.update_current(UpdateFlags::Tick);
269/// if should_pick_next {
270/// cpu_local::set_need_preempt();
271/// }
272/// });
273/// }
274///
275/// /// A preemption point, called at an earliest convenient timing
276/// /// when OSTD can safely preempt the current running task.
277/// fn might_preempt(scheduler: &'static dyn Scheduler) {
278/// if !cpu_local::should_preempt() {
279/// return;
280/// }
281/// let next_task_opt: Option<Arc<Task>> = scheduler
282/// .mut_local_rq_with(|local_rq| local_rq.try_pick_next().cloned())
283/// let Some(next_task) = next_task_opt {
284/// switch_to(next_task);
285/// }
286/// }
287/// ```
288///
289/// ### Exiting
290///
291/// ```
292/// # use ostd::prelude::*;
293/// # use ostd::task::{*, scheduler::*};
294/// #
295/// # fn switch_to(next: Arc<Task>) {}
296/// #
297/// /// Exits the current task.
298/// fn exit(scheduler: &'static dyn Scheduler) {
299/// let mut next_task_opt: Option<Arc<Task>> = None;
300/// let mut is_first_try = true;
301/// while scheduler.mut_local_rq_with(|local_rq| {
302/// if is_first_try {
303/// is_first_try = false;
304/// let should_pick_next = local_rq.update_current(UpdateFlags::Exit);
305/// let _current = local_rq.dequeue_current();
306/// if !should_pick_next {
307/// return true; // continue loop
308/// }
309/// next_task_opt = Some(local_rq.pick_next().clone());
310/// false // exit loop
311/// } else {
312/// next_task_opt = local_rq.try_pick_next().cloned();
313/// next_task_opt.is_none()
314/// }
315/// }) {}
316/// let next_task = next_task_opt.unwrap();
317/// switch_to(next_task);
318/// }
319/// ```
320pub trait LocalRunQueue<T = Task> {
321 /// Gets the current runnable task.
322 fn current(&self) -> Option<&Arc<T>>;
323
324 /// Updates the current runnable task's scheduling statistics and
325 /// potentially its position in the runqueue.
326 ///
327 /// The return value of this method indicates whether an invocation of `pick_next` should be followed
328 /// to find another task to replace the current one.
329 #[must_use]
330 fn update_current(&mut self, flags: UpdateFlags) -> bool;
331
332 /// Picks the next runnable task.
333 ///
334 /// This method instructs the local runqueue to pick the next runnable task and replace the current one.
335 /// A reference to the new "current" task will be returned by this method.
336 /// If the "old" current task presents, then it is still runnable and thus remains in the runqueue.
337 ///
338 /// # Panics
339 ///
340 /// As explained in the type-level Rust doc,
341 /// this method will only be invoked by OSTD after a call to `update_current` returns true.
342 /// In case that this contract is broken by the caller,
343 /// the implementer is free to exhibit any undesirable or incorrect behaviors, include panicking.
344 fn pick_next(&mut self) -> &Arc<T> {
345 self.try_pick_next().unwrap()
346 }
347
348 /// Tries to pick the next runnable task.
349 ///
350 /// This method instructs the local runqueue to pick the next runnable task on a best-effort basis.
351 /// If such a task can be picked, then this task supersedes the current task and
352 /// the new the method returns a reference to the new "current" task.
353 /// If the "old" current task presents, then it is still runnable and thus remains in the runqueue.
354 fn try_pick_next(&mut self) -> Option<&Arc<T>>;
355
356 /// Removes the current runnable task from runqueue.
357 ///
358 /// This method returns the current runnable task.
359 /// If there is no current runnable task, this method returns `None`.
360 fn dequeue_current(&mut self) -> Option<Arc<T>>;
361}
362
363/// Possible triggers of an `enqueue` action.
364#[derive(PartialEq, Copy, Clone)]
365pub enum EnqueueFlags {
366 /// Spawn a new task.
367 Spawn,
368 /// Wake a sleeping task.
369 Wake,
370}
371
372/// Possible triggers of an `update_current` action.
373#[derive(PartialEq, Copy, Clone)]
374pub enum UpdateFlags {
375 /// Timer interrupt.
376 Tick,
377 /// Task waiting.
378 Wait,
379 /// Task yielding.
380 Yield,
381 /// Task exiting.
382 Exit,
383}
384
385/// Preempts the current task.
386#[track_caller]
387pub(crate) fn might_preempt() {
388 /*
389 if !cpu_local::should_preempt() {
390 return;
391 }
392 reschedule(|local_rq| {
393 let next_task_opt = local_rq.try_pick_next();
394 if let Some(next_task) = next_task_opt {
395 ReschedAction::SwitchTo(next_task.clone())
396 } else {
397 ReschedAction::DoNothing
398 }
399 })
400 */
401}
402
403/// Blocks the current task unless `has_unparked()` returns `true`.
404///
405/// Note that this method may return due to spurious wake events. It's the caller's responsibility
406/// to detect them (if necessary).
407#[track_caller]
408pub(crate) fn park_current<F>(has_unparked: F)
409where
410 F: Fn() -> bool,
411{
412 let mut current = None;
413 let mut is_first_try = true;
414
415 reschedule(|local_rq: &mut dyn LocalRunQueue| {
416 let next_task_opt = if is_first_try {
417 if has_unparked() {
418 return ReschedAction::DoNothing;
419 }
420 is_first_try = false;
421
422 // Note the race conditions: the current task may be woken after the above `has_unparked`
423 // check, but before the below `dequeue_current` action, we need to make sure that the
424 // wakeup event isn't lost.
425 //
426 // Currently, for the FIFO and CFS scheduler, `Scheduler::enqueue` will try to lock `local_rq`
427 // when the above race condition occurs, so it will wait until we finish calling the
428 // `dequeue_current` method and nothing bad will happen. This may need to be revisited
429 // after more complex schedulers are introduced.
430
431 let should_pick_next = local_rq.update_current(UpdateFlags::Wait);
432 current = local_rq.dequeue_current();
433 should_pick_next.then(|| local_rq.pick_next())
434 } else {
435 local_rq.try_pick_next()
436 };
437
438 if let Some(next_task) = next_task_opt {
439 if Arc::ptr_eq(current.as_ref().unwrap(), next_task) {
440 // The current task has been woken and picked as the next runnable task.
441 return ReschedAction::DoNothing;
442 }
443 return ReschedAction::SwitchTo(next_task.clone());
444 }
445
446 ReschedAction::Retry
447 });
448}
449
450/// Unblocks a target task.
451pub(crate) fn unpark_target(runnable: Arc<Task>) {
452 let preempt_cpu = SCHEDULER
453 .get()
454 .unwrap()
455 .enqueue(runnable, EnqueueFlags::Wake);
456 if let Some(preempt_cpu_id) = preempt_cpu {
457 // set_need_preempt(preempt_cpu_id);
458 }
459}
460
461/// Enqueues a newly built task.
462///
463/// Note that the new task is not guaranteed to run at once.
464/*
465#[track_caller]
466pub(super) fn run_new_task(runnable: Arc<Task>) {
467 // FIXME: remove this check for `SCHEDULER`.
468 // Currently OSTD cannot know whether its user has injected a scheduler.
469 if !SCHEDULER.is_completed() {
470 fifo_scheduler::init();
471 }
472
473 let preempt_cpu = SCHEDULER
474 .get()
475 .unwrap()
476 .enqueue(runnable, EnqueueFlags::Spawn);
477 if let Some(preempt_cpu_id) = preempt_cpu {
478 set_need_preempt(preempt_cpu_id);
479 }
480
481 might_preempt();
482}
483*/
484
485/*
486fn set_need_preempt(cpu_id: CpuId) {
487 let preempt_guard = disable_preempt();
488
489 if preempt_guard.current_cpu() == cpu_id {
490 cpu_local::set_need_preempt();
491 } else {
492 crate::smp::inter_processor_call(&CpuSet::from(cpu_id), || {
493 cpu_local::set_need_preempt();
494 });
495 }
496}
497*/
498
499/// Dequeues the current task from its runqueue.
500///
501/// This should only be called if the current is to exit.
502/*
503#[track_caller]
504pub(super) fn exit_current() -> ! {
505 let mut is_first_try = true;
506
507 reschedule(|local_rq: &mut dyn LocalRunQueue| {
508 let next_task_opt = if is_first_try {
509 is_first_try = false;
510 let should_pick_next = local_rq.update_current(UpdateFlags::Exit);
511 let _current = local_rq.dequeue_current();
512 should_pick_next.then(|| local_rq.pick_next())
513 } else {
514 local_rq.try_pick_next()
515 };
516
517 if let Some(next_task) = next_task_opt {
518 ReschedAction::SwitchTo(next_task.clone())
519 } else {
520 ReschedAction::Retry
521 }
522 });
523
524 unreachable!()
525}
526*/
527
528/// Yields execution.
529/*
530#[track_caller]
531pub(super) fn yield_now() {
532 reschedule(|local_rq| {
533 let should_pick_next = local_rq.update_current(UpdateFlags::Yield);
534 let next_task_opt = should_pick_next.then(|| local_rq.pick_next());
535 if let Some(next_task) = next_task_opt {
536 ReschedAction::SwitchTo(next_task.clone())
537 } else {
538 ReschedAction::DoNothing
539 }
540 })
541}
542*/
543
544/// Do rescheduling by acting on the scheduling decision (`ReschedAction`) made by a
545/// user-given closure.
546///
547/// The closure makes the scheduling decision by taking the local runqueue has its input.
548#[track_caller]
549fn reschedule<F>(mut f: F)
550where
551 F: FnMut(&mut dyn LocalRunQueue) -> ReschedAction,
552{
553 // Even if the decision below is `DoNothing`, we should clear this flag. Meanwhile, to avoid
554 // race conditions, we should do this before making the decision.
555 // cpu_local::clear_need_preempt();
556
557 let next_task = loop {
558 let mut action = ReschedAction::DoNothing;
559 SCHEDULER.get().unwrap().mut_local_rq_with(&mut |rq| {
560 action = f(rq);
561 });
562
563 match action {
564 ReschedAction::DoNothing => {
565 return;
566 }
567 ReschedAction::Retry => {
568 continue;
569 }
570 ReschedAction::SwitchTo(next_task) => {
571 break next_task;
572 }
573 };
574 };
575
576 // `switch_to_task` will spin if it finds that the next task is still running on some CPU core,
577 // which guarantees soundness regardless of the scheduler implementation.
578 //
579 // FIXME: The scheduler decision and context switching are not atomic, which can lead to some
580 // strange behavior even if the scheduler is implemented correctly. See "Problem 2" at
581 // <https://github.com/asterinas/asterinas/issues/1633> for details.
582 // processor::switch_to_task(next_task);
583}
584
585/// Possible actions of a rescheduling.
586enum ReschedAction {
587 /// Keep running current task and do nothing.
588 DoNothing,
589 /// Loop until finding a task to swap out the current.
590 Retry,
591 /// Switch to target task.
592 SwitchTo(Arc<Task>),
593}