Skip to main content

hermit/scheduler/task/
mod.rs

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/// Returns the most significant bit.
30///
31/// # Examples
32///
33/// ```
34/// assert_eq!(msb(0), None);
35/// assert_eq!(msb(1), 0);
36/// assert_eq!(msb(u64::MAX), 63);
37/// ```
38#[inline]
39fn msb(n: u64) -> Option<u32> {
40	NonZeroU64::new(n).map(|n| u64::BITS - 1 - n.leading_zeros())
41}
42
43/// The status of the task - used for scheduling
44#[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/// Unique identifier for a task (i.e. `pid`).
55#[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/// Priority of a task
75#[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
101/// Maximum number of priorities
102pub 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/// A priority queue of task handles, e.g. the waiters of a futex, semaphore or mutex.
157///
158/// Usually only a few tasks wait on the same object, so the handles are stored
159/// inline. Waiting therefore does not allocate, which matters because futexes
160/// are created and dropped on every contended `futex_wait`.
161#[derive(Default)]
162pub(crate) struct TaskHandlePriorityQueue {
163	tasks: SmallVec<[TaskHandle; 4]>,
164}
165
166impl TaskHandlePriorityQueue {
167	/// Creates an empty priority queue for tasks
168	pub const fn new() -> Self {
169		Self {
170			tasks: SmallVec::new_const(),
171		}
172	}
173
174	/// Checks if the queue is empty.
175	pub fn is_empty(&self) -> bool {
176		self.tasks.is_empty()
177	}
178
179	/// Checks if the given task is in the queue. Returns `true` if the task
180	/// was found.
181	pub fn contains(&self, task: TaskHandle) -> bool {
182		self.tasks.iter().any(|queued| queued.id == task.id)
183	}
184
185	/// Add a task handle by its priority to the queue
186	pub fn push(&mut self, task: TaskHandle) {
187		self.tasks.push(task);
188	}
189
190	/// Pop the task handle with the highest priority from the queue.
191	/// Tasks with the same priority are popped in FIFO order.
192	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	/// Remove a specific task handle from the priority queue. Returns `true` if
203	/// the handle was in the queue.
204	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
211/// Realize a priority queue for tasks
212pub(crate) struct PriorityTaskQueue {
213	queues: [LinkedList<Rc<RefCell<Task>>>; NO_PRIORITIES],
214	prio_bitmap: u64,
215}
216
217impl PriorityTaskQueue {
218	/// Creates an empty priority queue for tasks
219	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	/// Add a task by its priority to the queue
228	pub fn push(&mut self, task: Rc<RefCell<Task>>) {
229		let i = task.borrow().prio.into() as usize;
230		//assert!(i < NO_PRIORITIES, "Priority {} is too high", i);
231
232		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	/// Remove the task at index from the queue and return that task,
247	/// or None if the index is out of range or the list is empty.
248	fn remove_from_queue(
249		&mut self,
250		task_index: usize,
251		queue_index: usize,
252	) -> Option<Rc<RefCell<Task>>> {
253		//assert!(prio < NO_PRIORITIES, "Priority {} is too high", prio);
254
255		let queue = &mut self.queues[queue_index];
256		if queue.len() < task_index {
257			return None;
258		}
259
260		// Calling remove is unstable: https://github.com/rust-lang/rust/issues/69210
261		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	/// Returns true if the queue is empty.
271	pub fn is_empty(&self) -> bool {
272		self.prio_bitmap == 0
273	}
274
275	/// Returns reference to prio_bitmap
276	#[allow(dead_code)]
277	#[inline]
278	pub fn get_priority_bitmap(&self) -> &u64 {
279		&self.prio_bitmap
280	}
281
282	/// Pop the task with the highest priority from the queue
283	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	/// Pop the next task, which has a higher or the same priority as `prio`
290	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	/// Returns the highest priority of all available task
301	#[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	/// Change priority of specific task
311	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/// A task control block, which identifies either a process or a thread
326#[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	/// The ID of this context
333	pub id: TaskId,
334	/// Status of a task, e.g. if the task is ready or blocked
335	pub status: TaskStatus,
336	/// Task priority,
337	pub prio: Priority,
338	/// Last stack pointer before a context switch to another task
339	pub last_stack_pointer: VirtAddr,
340	/// Last stack pointer on the user stack before jumping to kernel space
341	pub user_stack_pointer: VirtAddr,
342	/// Last FPU state before a context switch to another task using the FPU
343	pub last_fpu_state: FPUState,
344	/// ID of the core this task is running on
345	pub core_id: CoreId,
346	/// Stack of the task
347	pub stacks: TaskStacks,
348	/// Mapping between file descriptor and the referenced IO interface
349	pub object_map: Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>>,
350	/// Task Thread-Local-Storage (TLS)
351	#[cfg(not(feature = "common-os"))]
352	pub tls: Option<Tls>,
353	// Physical address of the 1st level page table
354	#[cfg(all(target_arch = "x86_64", feature = "common-os"))]
355	pub root_page_table: usize,
356}
357
358pub(crate) trait TaskFrame {
359	/// Create the initial stack frame for a new task
360	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		/// All cores use the same mapping between file descriptor and the referenced object
395		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				// This function is called once per core and thus only once on core 0.
409				// Thus, this is the only place where we set OBJECT_MAP.
410				.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
440/*impl Drop for Task {
441	fn drop(&mut self) {
442		debug!("Drop task {}", self.id);
443	}
444}*/
445
446struct 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
457/// The blocked tasks of a core.
458///
459/// Tasks with a wakeup time come first, ordered by their wakeup time, followed
460/// by the tasks that wait indefinitely.
461///
462/// This is a `Vec` rather than a `LinkedList`: every blocking operation (e.g. a
463/// contended futex) adds a task and every wakeup removes it again, and a list
464/// node would be allocated and freed on each of them. The vector keeps its
465/// capacity, so blocking does not allocate once the queue has grown.
466pub(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	/// Blocks the given task for `wakeup_time` ticks, or indefinitely if None is given.
499	pub fn add(&mut self, task: Rc<RefCell<Task>>, wakeup_time: Option<u64>) {
500		{
501			// Set the task status to Blocked.
502			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		// Shall the task automatically be woken up after a certain time?
517		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	/// Manually wake up a blocked task.
533	///
534	/// Returns `None` if the task is not blocked.
535	pub fn custom_wakeup(&mut self, task: TaskHandle) -> Option<Rc<RefCell<Task>>> {
536		// Find the task in the list of blocked tasks.
537		let index = self
538			.list
539			.iter()
540			.position(|node| node.task.borrow().id == task.get_id())?;
541
542		// Remove it from the list of blocked tasks.
543		let task_ref = self.list.remove(index).task;
544
545		// If this was the first task, adjust the One-Shot Timer to fire at the
546		// next task's wakeup time (if any).
547		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		// Wake it up.
554		Self::mark_ready(&task_ref);
555
556		Some(task_ref)
557	}
558
559	/// Wakes up all tasks whose wakeup time has elapsed.
560	///
561	/// Should be called by the One-Shot Timer interrupt handler when the wakeup time for
562	/// at least one task has elapsed.
563	pub fn handle_waiting_tasks(&mut self, ready_queue: &mut PriorityTaskQueue) {
564		// Get the current time.
565		let time = processor::get_timer_ticks();
566
567		// Get the wakeup time of this task and check if we have reached the first task
568		// that hasn't elapsed yet or waits indefinitely.
569		// This iterator has to be consumed to actually remove the elements.
570		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}