1#![allow(clippy::type_complexity)]
2
3#[cfg(not(feature = "common-os"))]
4pub(crate) mod tls;
5
6use alloc::collections::LinkedList;
7use alloc::rc::Rc;
8use alloc::sync::Arc;
9use alloc::vec::Vec;
10use core::cell::RefCell;
11use core::num::NonZeroU64;
12use core::{cmp, fmt};
13
14use ahash::RandomState;
15use hashbrown::HashMap;
16use hermit_sync::{OnceCell, RwSpinLock};
17use memory_addresses::VirtAddr;
18use smallvec::SmallVec;
19
20#[cfg(not(feature = "common-os"))]
21use self::tls::Tls;
22use super::timer_interrupts::{Source, create_timer_abs};
23use crate::arch::kernel::core_local::*;
24use crate::arch::kernel::processor::{self, FPUState};
25use crate::arch::kernel::scheduler::TaskStacks;
26use crate::fd::{Fd, RawFd, stdio};
27use crate::scheduler::CoreId;
28
29#[inline]
39fn msb(n: u64) -> Option<u32> {
40 NonZeroU64::new(n).map(|n| u64::BITS - 1 - n.leading_zeros())
41}
42
43#[derive(Copy, Clone, Debug, Eq, PartialEq)]
45pub(crate) enum TaskStatus {
46 Invalid,
47 Ready,
48 Running,
49 Blocked,
50 Finished,
51 Idle,
52}
53
54#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
56pub struct TaskId(i32);
57
58impl TaskId {
59 pub const fn into(self) -> i32 {
60 self.0
61 }
62
63 pub const fn from(x: i32) -> Self {
64 TaskId(x)
65 }
66}
67
68impl fmt::Display for TaskId {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 write!(f, "{}", self.0)
71 }
72}
73
74#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
76pub struct Priority(u8);
77
78impl Priority {
79 pub const fn into(self) -> u8 {
80 self.0
81 }
82
83 pub const fn from(x: u8) -> Self {
84 Priority(x)
85 }
86}
87
88impl fmt::Display for Priority {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 write!(f, "{}", self.0)
91 }
92}
93
94#[allow(dead_code)]
95pub const HIGH_PRIO: Priority = Priority::from(3);
96pub const NORMAL_PRIO: Priority = Priority::from(2);
97#[allow(dead_code)]
98pub const LOW_PRIO: Priority = Priority::from(1);
99pub const IDLE_PRIO: Priority = Priority::from(0);
100
101pub const NO_PRIORITIES: usize = 31;
103
104#[derive(Copy, Clone, Debug)]
105pub(crate) struct TaskHandle {
106 id: TaskId,
107 priority: Priority,
108 #[cfg(feature = "smp")]
109 core_id: CoreId,
110}
111
112impl TaskHandle {
113 pub fn new(id: TaskId, priority: Priority, #[cfg(feature = "smp")] core_id: CoreId) -> Self {
114 Self {
115 id,
116 priority,
117 #[cfg(feature = "smp")]
118 core_id,
119 }
120 }
121
122 #[cfg(feature = "smp")]
123 pub fn get_core_id(&self) -> CoreId {
124 self.core_id
125 }
126
127 pub fn get_id(&self) -> TaskId {
128 self.id
129 }
130
131 pub fn get_priority(&self) -> Priority {
132 self.priority
133 }
134}
135
136impl Ord for TaskHandle {
137 fn cmp(&self, other: &Self) -> cmp::Ordering {
138 self.id.cmp(&other.id)
139 }
140}
141
142impl PartialOrd for TaskHandle {
143 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
144 Some(self.cmp(other))
145 }
146}
147
148impl PartialEq for TaskHandle {
149 fn eq(&self, other: &Self) -> bool {
150 self.id == other.id
151 }
152}
153
154impl Eq for TaskHandle {}
155
156#[derive(Default)]
162pub(crate) struct TaskHandlePriorityQueue {
163 tasks: SmallVec<[TaskHandle; 4]>,
164}
165
166impl TaskHandlePriorityQueue {
167 pub const fn new() -> Self {
169 Self {
170 tasks: SmallVec::new_const(),
171 }
172 }
173
174 pub fn is_empty(&self) -> bool {
176 self.tasks.is_empty()
177 }
178
179 pub fn contains(&self, task: TaskHandle) -> bool {
182 self.tasks.iter().any(|queued| queued.id == task.id)
183 }
184
185 pub fn push(&mut self, task: TaskHandle) {
187 self.tasks.push(task);
188 }
189
190 pub fn pop(&mut self) -> Option<TaskHandle> {
193 let (index, _) = self
194 .tasks
195 .iter()
196 .enumerate()
197 .rev()
198 .max_by_key(|(_, task)| task.priority)?;
199 Some(self.tasks.remove(index))
200 }
201
202 pub fn remove(&mut self, task: TaskHandle) -> bool {
205 let len = self.tasks.len();
206 self.tasks.retain(|queued| queued.id != task.id);
207 self.tasks.len() != len
208 }
209}
210
211pub(crate) struct PriorityTaskQueue {
213 queues: [LinkedList<Rc<RefCell<Task>>>; NO_PRIORITIES],
214 prio_bitmap: u64,
215}
216
217impl PriorityTaskQueue {
218 pub const fn new() -> PriorityTaskQueue {
220 const EMPTY_LIST: LinkedList<Rc<RefCell<Task>>> = LinkedList::new();
221 PriorityTaskQueue {
222 queues: [EMPTY_LIST; NO_PRIORITIES],
223 prio_bitmap: 0,
224 }
225 }
226
227 pub fn push(&mut self, task: Rc<RefCell<Task>>) {
229 let i = task.borrow().prio.into() as usize;
230 self.prio_bitmap |= (1 << i) as u64;
233 let queue = &mut self.queues[i];
234 queue.push_back(task);
235 }
236
237 fn pop_from_queue(&mut self, queue_index: usize) -> Option<Rc<RefCell<Task>>> {
238 let task = self.queues[queue_index].pop_front();
239 if self.queues[queue_index].is_empty() {
240 self.prio_bitmap &= !(1 << queue_index as u64);
241 }
242
243 task
244 }
245
246 fn remove_from_queue(
249 &mut self,
250 task_index: usize,
251 queue_index: usize,
252 ) -> Option<Rc<RefCell<Task>>> {
253 let queue = &mut self.queues[queue_index];
256 if queue.len() < task_index {
257 return None;
258 }
259
260 let mut split_list = queue.split_off(task_index);
262 let element = split_list.pop_front();
263 queue.append(&mut split_list);
264 if queue.is_empty() {
265 self.prio_bitmap &= !(1 << queue_index as u64);
266 }
267 element
268 }
269
270 pub fn is_empty(&self) -> bool {
272 self.prio_bitmap == 0
273 }
274
275 #[allow(dead_code)]
277 #[inline]
278 pub fn get_priority_bitmap(&self) -> &u64 {
279 &self.prio_bitmap
280 }
281
282 pub fn pop(&mut self) -> Option<Rc<RefCell<Task>>> {
284 let i = msb(self.prio_bitmap)?;
285
286 self.pop_from_queue(i as usize)
287 }
288
289 pub fn pop_with_prio(&mut self, prio: Priority) -> Option<Rc<RefCell<Task>>> {
291 let i = msb(self.prio_bitmap)?;
292
293 if i < u32::from(prio.into()) {
294 return None;
295 }
296
297 self.pop_from_queue(i as usize)
298 }
299
300 #[cfg(all(any(target_arch = "x86_64", target_arch = "riscv64"), feature = "smp"))]
302 pub fn get_highest_priority(&self) -> Priority {
303 let Some(i) = msb(self.prio_bitmap) else {
304 return IDLE_PRIO;
305 };
306
307 Priority::from(i.try_into().unwrap())
308 }
309
310 pub fn set_priority(&mut self, handle: TaskHandle, prio: Priority) -> Result<(), ()> {
312 let old_priority = handle.get_priority().into() as usize;
313 let index = self.queues[old_priority]
314 .iter()
315 .position(|current_task| current_task.borrow().id == handle.id)
316 .ok_or(())?;
317
318 let task = self.remove_from_queue(index, old_priority).ok_or(())?;
319 task.borrow_mut().prio = prio;
320 self.push(task);
321 Ok(())
322 }
323}
324
325#[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(align(128)))]
327#[cfg_attr(
328 not(any(target_arch = "x86_64", target_arch = "aarch64")),
329 repr(align(64))
330)]
331pub(crate) struct Task {
332 pub id: TaskId,
334 pub status: TaskStatus,
336 pub prio: Priority,
338 pub last_stack_pointer: VirtAddr,
340 pub user_stack_pointer: VirtAddr,
342 pub last_fpu_state: FPUState,
344 pub core_id: CoreId,
346 pub stacks: TaskStacks,
348 pub object_map: Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>>,
350 #[cfg(not(feature = "common-os"))]
352 pub tls: Option<Tls>,
353 #[cfg(all(target_arch = "x86_64", feature = "common-os"))]
355 pub root_page_table: usize,
356}
357
358pub(crate) trait TaskFrame {
359 fn create_stack_frame(&mut self, func: unsafe extern "C" fn(usize), arg: usize);
361}
362
363impl Task {
364 pub fn new(
365 tid: TaskId,
366 core_id: CoreId,
367 task_status: TaskStatus,
368 task_prio: Priority,
369 stacks: TaskStacks,
370 object_map: Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>>,
371 ) -> Task {
372 debug!("Creating new task {tid} on core {core_id}");
373
374 Task {
375 id: tid,
376 status: task_status,
377 prio: task_prio,
378 last_stack_pointer: VirtAddr::zero(),
379 user_stack_pointer: VirtAddr::zero(),
380 last_fpu_state: FPUState::new(),
381 core_id,
382 stacks,
383 object_map,
384 #[cfg(not(feature = "common-os"))]
385 tls: None,
386 #[cfg(all(target_arch = "x86_64", feature = "common-os"))]
387 root_page_table: crate::arch::mm::paging::create_new_root_page_table(),
388 }
389 }
390
391 pub fn new_idle(tid: TaskId, core_id: CoreId) -> Task {
392 debug!("Creating idle task {tid}");
393
394 static OBJECT_MAP: OnceCell<
396 Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>>,
397 > = OnceCell::new();
398
399 if core_id == 0 {
400 OBJECT_MAP
401 .set(Arc::new(RwSpinLock::new(HashMap::<
402 RawFd,
403 Arc<async_lock::RwLock<Fd>>,
404 RandomState,
405 >::with_hasher(
406 RandomState::with_seeds(0, 0, 0, 0),
407 ))))
408 .unwrap_or_else(|_| unreachable!());
411 let objmap = OBJECT_MAP.get().unwrap().clone();
412 stdio::setup(&mut objmap.write());
413 }
414
415 #[cfg(not(feature = "common-os"))]
416 let tls = if cfg!(feature = "instrument-mcount") {
417 Tls::from_env().inspect(Tls::set_thread_ptr)
418 } else {
419 None
420 };
421
422 Task {
423 id: tid,
424 status: TaskStatus::Idle,
425 prio: IDLE_PRIO,
426 last_stack_pointer: VirtAddr::zero(),
427 user_stack_pointer: VirtAddr::zero(),
428 last_fpu_state: FPUState::new(),
429 core_id,
430 stacks: TaskStacks::from_boot_stacks(),
431 object_map: OBJECT_MAP.get().unwrap().clone(),
432 #[cfg(not(feature = "common-os"))]
433 tls,
434 #[cfg(all(target_arch = "x86_64", feature = "common-os"))]
435 root_page_table: *crate::scheduler::BOOT_ROOT_PAGE_TABLE.get().unwrap(),
436 }
437 }
438}
439
440struct BlockedTask {
447 task: Rc<RefCell<Task>>,
448 wakeup_time: Option<u64>,
449}
450
451impl BlockedTask {
452 pub fn new(task: Rc<RefCell<Task>>, wakeup_time: Option<u64>) -> Self {
453 Self { task, wakeup_time }
454 }
455}
456
457pub(crate) struct BlockedTaskQueue {
467 list: Vec<BlockedTask>,
468}
469
470impl BlockedTaskQueue {
471 pub const fn new() -> Self {
472 Self { list: Vec::new() }
473 }
474
475 fn mark_ready(task: &RefCell<Task>) {
476 let mut borrowed = task.borrow_mut();
477 debug!(
478 "Waking up task {} on core {}",
479 borrowed.id, borrowed.core_id
480 );
481
482 assert!(
483 borrowed.core_id == core_id(),
484 "Try to wake up task {} on the wrong core {} != {}",
485 borrowed.id,
486 borrowed.core_id,
487 core_id()
488 );
489
490 assert!(
491 borrowed.status == TaskStatus::Blocked,
492 "Trying to wake up task {} which is not blocked",
493 borrowed.id
494 );
495 borrowed.status = TaskStatus::Ready;
496 }
497
498 pub fn add(&mut self, task: Rc<RefCell<Task>>, wakeup_time: Option<u64>) {
500 {
501 let mut borrowed = task.borrow_mut();
503 debug!("Blocking task {}", borrowed.id);
504
505 assert_eq!(
506 borrowed.status,
507 TaskStatus::Running,
508 "Trying to block task {} which is not running",
509 borrowed.id
510 );
511 borrowed.status = TaskStatus::Blocked;
512 }
513
514 let new_node = BlockedTask::new(task, wakeup_time);
515
516 if let Some(wt) = wakeup_time {
518 let index = self
519 .list
520 .iter()
521 .position(|node| node.wakeup_time.is_none_or(|node_wt| wt < node_wt))
522 .unwrap_or(self.list.len());
523 self.list.insert(index, new_node);
524
525 create_timer_abs(Source::Scheduler, wt);
526 return;
527 }
528
529 self.list.push(new_node);
530 }
531
532 pub fn custom_wakeup(&mut self, task: TaskHandle) -> Option<Rc<RefCell<Task>>> {
536 let index = self
538 .list
539 .iter()
540 .position(|node| node.task.borrow().id == task.get_id())?;
541
542 let task_ref = self.list.remove(index).task;
544
545 if index == 0
548 && let Some(wakeup) = self.list.first().and_then(|node| node.wakeup_time)
549 {
550 create_timer_abs(Source::Scheduler, wakeup);
551 }
552
553 Self::mark_ready(&task_ref);
555
556 Some(task_ref)
557 }
558
559 pub fn handle_waiting_tasks(&mut self, ready_queue: &mut PriorityTaskQueue) {
564 let time = processor::get_timer_ticks();
566
567 let newly_ready_tasks = self.list.extract_if(.., |blocked_task| {
571 blocked_task
572 .wakeup_time
573 .is_some_and(|wakeup_time| wakeup_time < time)
574 });
575
576 for task in newly_ready_tasks {
577 Self::mark_ready(&task.task);
578 ready_queue.push(task.task);
579 }
580
581 let new_task_wakeup_time = self.list.first().and_then(|task| task.wakeup_time);
582
583 if let Some(wakeup) = new_task_wakeup_time {
584 create_timer_abs(Source::Scheduler, wakeup);
585 }
586 }
587}