axtask/
api.rs

1//! Task APIs for multi-task configuration.
2
3use alloc::{string::String, sync::Arc};
4
5use kernel_guard::NoPreemptIrqSave;
6
7pub(crate) use crate::run_queue::{current_run_queue, select_run_queue};
8
9#[doc(cfg(feature = "multitask"))]
10pub use crate::task::{CurrentTask, TaskId, TaskInner};
11#[doc(cfg(feature = "multitask"))]
12pub use crate::task_ext::{TaskExtMut, TaskExtRef};
13#[doc(cfg(feature = "multitask"))]
14pub use crate::wait_queue::WaitQueue;
15
16/// The reference type of a task.
17pub type AxTaskRef = Arc<AxTask>;
18
19/// The wrapper type for [`cpumask::CpuMask`] with SMP configuration.
20pub type AxCpuMask = cpumask::CpuMask<{ axconfig::SMP }>;
21
22cfg_if::cfg_if! {
23    if #[cfg(feature = "sched_rr")] {
24        const MAX_TIME_SLICE: usize = 5;
25        pub(crate) type AxTask = scheduler::RRTask<TaskInner, MAX_TIME_SLICE>;
26        pub(crate) type Scheduler = scheduler::RRScheduler<TaskInner, MAX_TIME_SLICE>;
27    } else if #[cfg(feature = "sched_cfs")] {
28        pub(crate) type AxTask = scheduler::CFSTask<TaskInner>;
29        pub(crate) type Scheduler = scheduler::CFScheduler<TaskInner>;
30    } else {
31        // If no scheduler features are set, use FIFO as the default.
32        pub(crate) type AxTask = scheduler::FifoTask<TaskInner>;
33        pub(crate) type Scheduler = scheduler::FifoScheduler<TaskInner>;
34    }
35}
36
37#[cfg(feature = "preempt")]
38struct KernelGuardIfImpl;
39
40#[cfg(feature = "preempt")]
41#[crate_interface::impl_interface]
42impl kernel_guard::KernelGuardIf for KernelGuardIfImpl {
43    fn disable_preempt() {
44        if let Some(curr) = current_may_uninit() {
45            curr.disable_preempt();
46        }
47    }
48
49    fn enable_preempt() {
50        if let Some(curr) = current_may_uninit() {
51            curr.enable_preempt(true);
52        }
53    }
54}
55
56/// Gets the current task, or returns [`None`] if the current task is not
57/// initialized.
58pub fn current_may_uninit() -> Option<CurrentTask> {
59    CurrentTask::try_get()
60}
61
62/// Gets the current task.
63///
64/// # Panics
65///
66/// Panics if the current task is not initialized.
67pub fn current() -> CurrentTask {
68    CurrentTask::get()
69}
70
71/// Initializes the task scheduler (for the primary CPU).
72pub fn init_scheduler() {
73    info!("Initialize scheduling...");
74
75    crate::run_queue::init();
76    #[cfg(feature = "irq")]
77    crate::timers::init();
78
79    info!("  use {} scheduler.", Scheduler::scheduler_name());
80}
81
82/// Initializes the task scheduler for secondary CPUs.
83pub fn init_scheduler_secondary() {
84    crate::run_queue::init_secondary();
85    #[cfg(feature = "irq")]
86    crate::timers::init();
87}
88
89/// Handles periodic timer ticks for the task manager.
90///
91/// For example, advance scheduler states, checks timed events, etc.
92#[cfg(feature = "irq")]
93#[doc(cfg(feature = "irq"))]
94pub fn on_timer_tick() {
95    use kernel_guard::NoOp;
96    crate::timers::check_events();
97    // Since irq and preemption are both disabled here,
98    // we can get current run queue with the default `kernel_guard::NoOp`.
99    current_run_queue::<NoOp>().scheduler_timer_tick();
100}
101
102/// Adds the given task to the run queue, returns the task reference.
103pub fn spawn_task(task: TaskInner) -> AxTaskRef {
104    let task_ref = task.into_arc();
105    select_run_queue::<NoPreemptIrqSave>(&task_ref).add_task(task_ref.clone());
106    task_ref
107}
108
109/// Spawns a new task with the given parameters.
110///
111/// Returns the task reference.
112pub fn spawn_raw<F>(f: F, name: String, stack_size: usize) -> AxTaskRef
113where
114    F: FnOnce() + Send + 'static,
115{
116    spawn_task(TaskInner::new(f, name, stack_size))
117}
118
119/// Spawns a new task with the default parameters.
120///
121/// The default task name is an empty string. The default task stack size is
122/// [`axconfig::TASK_STACK_SIZE`].
123///
124/// Returns the task reference.
125pub fn spawn<F>(f: F) -> AxTaskRef
126where
127    F: FnOnce() + Send + 'static,
128{
129    spawn_raw(f, "".into(), axconfig::TASK_STACK_SIZE)
130}
131
132/// Set the priority for current task.
133///
134/// The range of the priority is dependent on the underlying scheduler. For
135/// example, in the [CFS] scheduler, the priority is the nice value, ranging from
136/// -20 to 19.
137///
138/// Returns `true` if the priority is set successfully.
139///
140/// [CFS]: https://en.wikipedia.org/wiki/Completely_Fair_Scheduler
141pub fn set_priority(prio: isize) -> bool {
142    current_run_queue::<NoPreemptIrqSave>().set_current_priority(prio)
143}
144
145/// Set the affinity for the current task.
146/// [`AxCpuMask`] is used to specify the CPU affinity.
147/// Returns `true` if the affinity is set successfully.
148///
149/// TODO: support set the affinity for other tasks.
150pub fn set_current_affinity(cpumask: AxCpuMask) -> bool {
151    if cpumask.is_empty() {
152        false
153    } else {
154        let curr = current().clone();
155
156        curr.set_cpumask(cpumask);
157        // After setting the affinity, we need to check if current cpu matches
158        // the affinity. If not, we need to migrate the task to the correct CPU.
159        #[cfg(feature = "smp")]
160        if !cpumask.get(axhal::cpu::this_cpu_id()) {
161            const MIGRATION_TASK_STACK_SIZE: usize = 4096;
162            // Spawn a new migration task for migrating.
163            let migration_task = TaskInner::new(
164                move || crate::run_queue::migrate_entry(curr),
165                "migration-task".into(),
166                MIGRATION_TASK_STACK_SIZE,
167            )
168            .into_arc();
169
170            // Migrate the current task to the correct CPU using the migration task.
171            current_run_queue::<NoPreemptIrqSave>().migrate_current(migration_task);
172
173            assert!(cpumask.get(axhal::cpu::this_cpu_id()), "Migration failed");
174        }
175        true
176    }
177}
178
179/// Current task gives up the CPU time voluntarily, and switches to another
180/// ready task.
181pub fn yield_now() {
182    current_run_queue::<NoPreemptIrqSave>().yield_current()
183}
184
185/// Current task is going to sleep for the given duration.
186///
187/// If the feature `irq` is not enabled, it uses busy-wait instead.
188pub fn sleep(dur: core::time::Duration) {
189    sleep_until(axhal::time::wall_time() + dur);
190}
191
192/// Current task is going to sleep, it will be woken up at the given deadline.
193///
194/// If the feature `irq` is not enabled, it uses busy-wait instead.
195pub fn sleep_until(deadline: axhal::time::TimeValue) {
196    #[cfg(feature = "irq")]
197    current_run_queue::<NoPreemptIrqSave>().sleep_until(deadline);
198    #[cfg(not(feature = "irq"))]
199    axhal::time::busy_wait_until(deadline);
200}
201
202/// Exits the current task.
203pub fn exit(exit_code: i32) -> ! {
204    current_run_queue::<NoPreemptIrqSave>().exit_current(exit_code)
205}
206
207/// The idle task routine.
208///
209/// It runs an infinite loop that keeps calling [`yield_now()`].
210pub fn run_idle() -> ! {
211    loop {
212        yield_now();
213        debug!("idle task: waiting for IRQs...");
214        #[cfg(feature = "irq")]
215        axhal::arch::wait_for_irqs();
216    }
217}