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::plat::MAX_CPU_NUM }>;
21
22cfg_if::cfg_if! {
23    if #[cfg(feature = "sched-rr")] {
24        const MAX_TIME_SLICE: usize = 5;
25        pub(crate) type AxTask = axsched::RRTask<TaskInner, MAX_TIME_SLICE>;
26        pub(crate) type Scheduler = axsched::RRScheduler<TaskInner, MAX_TIME_SLICE>;
27    } else if #[cfg(feature = "sched-cfs")] {
28        pub(crate) type AxTask = axsched::CFSTask<TaskInner>;
29        pub(crate) type Scheduler = axsched::CFScheduler<TaskInner>;
30    } else {
31        // If no scheduler features are set, use FIFO as the default.
32        pub(crate) type AxTask = axsched::FifoTask<TaskInner>;
33        pub(crate) type Scheduler = axsched::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    // Initialize the cpu count information.
76    init_cpu_mask_full();
77
78    // Initialize the run queue.
79    crate::run_queue::init();
80    #[cfg(feature = "irq")]
81    crate::timers::init();
82
83    info!("  use {} scheduler.", Scheduler::scheduler_name());
84}
85
86/// The full CPU mask of the system.
87static CPU_MASK_FULL: lazyinit::LazyInit<AxCpuMask> = lazyinit::LazyInit::new();
88
89/// Gets the cpu count information and initializes related data structures.
90fn init_cpu_mask_full() {
91    let cpu_num = axhal::cpu_num();
92    let mut cpumask = AxCpuMask::new();
93    for cpu_id in 0..cpu_num {
94        cpumask.set(cpu_id, true);
95    }
96
97    CPU_MASK_FULL.call_once(|| cpumask);
98}
99
100pub(crate) fn cpu_mask_full() -> AxCpuMask {
101    *CPU_MASK_FULL.get().expect("CPU mask not initialized")
102}
103
104/// Initializes the task scheduler for secondary CPUs.
105pub fn init_scheduler_secondary() {
106    crate::run_queue::init_secondary();
107    #[cfg(feature = "irq")]
108    crate::timers::init();
109}
110
111/// Handles periodic timer ticks for the task manager.
112///
113/// For example, advance scheduler states, checks timed events, etc.
114#[cfg(feature = "irq")]
115#[doc(cfg(feature = "irq"))]
116pub fn on_timer_tick() {
117    use kernel_guard::NoOp;
118    crate::timers::check_events();
119    // Since irq and preemption are both disabled here,
120    // we can get current run queue with the default `kernel_guard::NoOp`.
121    current_run_queue::<NoOp>().scheduler_timer_tick();
122}
123
124/// Adds the given task to the run queue, returns the task reference.
125pub fn spawn_task(task: TaskInner) -> AxTaskRef {
126    let task_ref = task.into_arc();
127    select_run_queue::<NoPreemptIrqSave>(&task_ref).add_task(task_ref.clone());
128    task_ref
129}
130
131/// Spawns a new task with the given parameters.
132///
133/// Returns the task reference.
134pub fn spawn_raw<F>(f: F, name: String, stack_size: usize) -> AxTaskRef
135where
136    F: FnOnce() + Send + 'static,
137{
138    spawn_task(TaskInner::new(f, name, stack_size))
139}
140
141/// Spawns a new task with the default parameters.
142///
143/// The default task name is an empty string. The default task stack size is
144/// [`axconfig::TASK_STACK_SIZE`].
145///
146/// Returns the task reference.
147pub fn spawn<F>(f: F) -> AxTaskRef
148where
149    F: FnOnce() + Send + 'static,
150{
151    spawn_raw(f, "".into(), axconfig::TASK_STACK_SIZE)
152}
153
154/// Set the priority for current task.
155///
156/// The range of the priority is dependent on the underlying scheduler. For
157/// example, in the [CFS] scheduler, the priority is the nice value, ranging from
158/// -20 to 19.
159///
160/// Returns `true` if the priority is set successfully.
161///
162/// [CFS]: https://en.wikipedia.org/wiki/Completely_Fair_Scheduler
163pub fn set_priority(prio: isize) -> bool {
164    current_run_queue::<NoPreemptIrqSave>().set_current_priority(prio)
165}
166
167/// Set the affinity for the current task.
168/// [`AxCpuMask`] is used to specify the CPU affinity.
169/// Returns `true` if the affinity is set successfully.
170///
171/// TODO: support set the affinity for other tasks.
172pub fn set_current_affinity(cpumask: AxCpuMask) -> bool {
173    if cpumask.is_empty() {
174        false
175    } else {
176        let curr = current().clone();
177
178        curr.set_cpumask(cpumask);
179        // After setting the affinity, we need to check if current cpu matches
180        // the affinity. If not, we need to migrate the task to the correct CPU.
181        #[cfg(feature = "smp")]
182        if !cpumask.get(axhal::percpu::this_cpu_id()) {
183            const MIGRATION_TASK_STACK_SIZE: usize = 4096;
184            // Spawn a new migration task for migrating.
185            let migration_task = TaskInner::new(
186                move || crate::run_queue::migrate_entry(curr),
187                "migration-task".into(),
188                MIGRATION_TASK_STACK_SIZE,
189            )
190            .into_arc();
191
192            // Migrate the current task to the correct CPU using the migration task.
193            current_run_queue::<NoPreemptIrqSave>().migrate_current(migration_task);
194
195            assert!(
196                cpumask.get(axhal::percpu::this_cpu_id()),
197                "Migration failed"
198            );
199        }
200        true
201    }
202}
203
204/// Current task gives up the CPU time voluntarily, and switches to another
205/// ready task.
206pub fn yield_now() {
207    current_run_queue::<NoPreemptIrqSave>().yield_current()
208}
209
210/// Current task is going to sleep for the given duration.
211///
212/// If the feature `irq` is not enabled, it uses busy-wait instead.
213pub fn sleep(dur: core::time::Duration) {
214    sleep_until(axhal::time::wall_time() + dur);
215}
216
217/// Current task is going to sleep, it will be woken up at the given deadline.
218///
219/// If the feature `irq` is not enabled, it uses busy-wait instead.
220pub fn sleep_until(deadline: axhal::time::TimeValue) {
221    #[cfg(feature = "irq")]
222    current_run_queue::<NoPreemptIrqSave>().sleep_until(deadline);
223    #[cfg(not(feature = "irq"))]
224    axhal::time::busy_wait_until(deadline);
225}
226
227/// Exits the current task.
228pub fn exit(exit_code: i32) -> ! {
229    current_run_queue::<NoPreemptIrqSave>().exit_current(exit_code)
230}
231
232/// The idle task routine.
233///
234/// It runs an infinite loop that keeps calling [`yield_now()`].
235pub fn run_idle() -> ! {
236    loop {
237        yield_now();
238        debug!("idle task: waiting for IRQs...");
239        #[cfg(feature = "irq")]
240        axhal::asm::wait_for_irqs();
241    }
242}