Skip to main content

hermit/scheduler/
mod.rs

1#![allow(clippy::type_complexity)]
2
3use alloc::boxed::Box;
4use alloc::collections::{BTreeMap, VecDeque};
5use alloc::rc::Rc;
6use alloc::sync::Arc;
7#[cfg(feature = "smp")]
8use alloc::vec::Vec;
9use core::cell::RefCell;
10use core::ptr;
11use core::sync::atomic::{AtomicI32, AtomicU32, Ordering};
12
13use ahash::RandomState;
14use crossbeam_utils::Backoff;
15use hashbrown::{HashMap, hash_map};
16use hermit_sync::*;
17#[cfg(target_arch = "riscv64")]
18use riscv::register::sstatus;
19use timer_interrupts::TimerList;
20
21use crate::arch::kernel;
22use crate::arch::kernel::core_local::*;
23#[cfg(feature = "preemptive")]
24use crate::arch::kernel::processor;
25use crate::arch::kernel::scheduler::TaskStacks;
26#[cfg(target_arch = "riscv64")]
27use crate::arch::kernel::switch::switch_to_task;
28#[cfg(target_arch = "x86_64")]
29use crate::arch::kernel::switch::{switch_to_fpu_owner, switch_to_task};
30use crate::arch::kernel::{get_processor_count, interrupts};
31use crate::errno::Errno;
32use crate::fd::{Fd, RawFd};
33use crate::io;
34use crate::scheduler::task::*;
35
36#[cfg(all(
37	any(target_arch = "x86_64", target_arch = "riscv64"),
38	feature = "smp",
39	not(feature = "idle-poll")
40))]
41pub mod sleep_state;
42pub mod task;
43pub mod timer_interrupts;
44
45static NO_TASKS: AtomicU32 = AtomicU32::new(0);
46/// Length of a preemptive scheduling time slice, in microseconds (10 ms). With
47/// rhyve's external-interrupt exiting this also bounds the guest VM-exit rate
48/// during contention (one exit per slice).
49#[cfg(feature = "preemptive")]
50const PREEMPTION_SLICE_US: u64 = 10_000;
51/// Map between Core ID and per-core scheduler
52#[cfg(feature = "smp")]
53static SCHEDULER_INPUTS: InterruptSpinMutex<Vec<&InterruptTicketMutex<SchedulerInput>>> =
54	InterruptSpinMutex::new(Vec::new());
55/// Map between Task ID and Queue of waiting tasks
56static WAITING_TASKS: InterruptTicketMutex<BTreeMap<TaskId, VecDeque<TaskHandle>>> =
57	InterruptTicketMutex::new(BTreeMap::new());
58/// Map between Task ID and TaskHandle
59static TASKS: InterruptTicketMutex<BTreeMap<TaskId, TaskHandle>> =
60	InterruptTicketMutex::new(BTreeMap::new());
61
62/// Unique identifier for a core.
63pub type CoreId = u32;
64
65#[cfg(feature = "smp")]
66pub(crate) struct SchedulerInput {
67	/// Queue of new tasks
68	new_tasks: VecDeque<NewTask>,
69	/// Queue of task, which are wakeup by another core
70	wakeup_tasks: VecDeque<TaskHandle>,
71}
72
73#[cfg(feature = "smp")]
74impl SchedulerInput {
75	pub fn new() -> Self {
76		Self {
77			new_tasks: VecDeque::new(),
78			wakeup_tasks: VecDeque::new(),
79		}
80	}
81}
82
83#[cfg_attr(any(target_arch = "x86_64", target_arch = "aarch64"), repr(align(128)))]
84#[cfg_attr(
85	not(any(target_arch = "x86_64", target_arch = "aarch64")),
86	repr(align(64))
87)]
88pub(crate) struct PerCoreScheduler {
89	/// Core ID of this per-core scheduler
90	#[cfg(feature = "smp")]
91	core_id: CoreId,
92	/// Task which is currently running
93	current_task: Rc<RefCell<Task>>,
94	/// Idle Task
95	idle_task: Rc<RefCell<Task>>,
96	/// Task that currently owns the FPU
97	#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
98	fpu_owner: Rc<RefCell<Task>>,
99	/// Queue of tasks, which are ready
100	ready_queue: PriorityTaskQueue,
101	/// Queue of tasks, which are finished and can be released
102	finished_tasks: VecDeque<Rc<RefCell<Task>>>,
103	/// Queue of blocked tasks, sorted by wakeup time.
104	blocked_tasks: BlockedTaskQueue,
105	/// Queue of timer interrupts.
106	pub timers: TimerList,
107}
108
109pub(crate) trait PerCoreSchedulerExt {
110	/// Triggers the scheduler to reschedule the tasks.
111	/// Interrupt flag will be cleared during the reschedule
112	fn reschedule(self);
113
114	/// Terminate the current task on the current core.
115	fn exit(self, exit_code: i32) -> !;
116}
117
118impl PerCoreSchedulerExt for &mut PerCoreScheduler {
119	#[cfg(target_arch = "x86_64")]
120	fn reschedule(self) {
121		without_interrupts(|| {
122			let Some(last_stack_pointer) = self.scheduler() else {
123				return;
124			};
125
126			let (new_stack_pointer, is_idle) = {
127				let borrowed = self.current_task.borrow();
128				(
129					borrowed.last_stack_pointer,
130					borrowed.status == TaskStatus::Idle,
131				)
132			};
133
134			if is_idle || Rc::ptr_eq(&self.current_task, &self.fpu_owner) {
135				unsafe {
136					switch_to_fpu_owner(last_stack_pointer, new_stack_pointer.as_u64() as usize);
137				}
138			} else {
139				unsafe {
140					switch_to_task(last_stack_pointer, new_stack_pointer.as_u64() as usize);
141				}
142			}
143		});
144	}
145
146	/// Trigger an interrupt to reschedule the system
147	#[cfg(target_arch = "aarch64")]
148	fn reschedule(self) {
149		use aarch64_cpu::asm::barrier::{NSH, SY, dsb, isb};
150		use arm_gic::IntId;
151		use arm_gic::gicv3::{GicCpuInterface, SgiTarget, SgiTargetGroup};
152
153		use crate::arch::kernel::interrupts::SGI_RESCHED;
154
155		dsb(NSH);
156		isb(SY);
157
158		let reschedid = IntId::sgi(SGI_RESCHED.into());
159		#[cfg(feature = "smp")]
160		let core_id = self.core_id;
161		#[cfg(not(feature = "smp"))]
162		let core_id = 0;
163
164		GicCpuInterface::send_sgi(
165			reschedid,
166			SgiTarget::List {
167				affinity3: 0,
168				affinity2: 0,
169				affinity1: 0,
170				target_list: 1 << core_id,
171			},
172			SgiTargetGroup::CurrentGroup1,
173		)
174		.unwrap();
175
176		interrupts::enable();
177	}
178
179	#[cfg(target_arch = "riscv64")]
180	fn reschedule(self) {
181		without_interrupts(|| self.scheduler());
182	}
183
184	fn exit(self, exit_code: i32) -> ! {
185		without_interrupts(|| {
186			// Get the current task.
187			let mut current_task_borrowed = self.current_task.borrow_mut();
188			assert_ne!(
189				current_task_borrowed.status,
190				TaskStatus::Idle,
191				"Trying to terminate the idle task"
192			);
193
194			// Finish the task and reschedule.
195			debug!(
196				"Finishing task {} with exit code {}",
197				current_task_borrowed.id, exit_code
198			);
199			current_task_borrowed.status = TaskStatus::Finished;
200			let remaining_tasks = NO_TASKS.fetch_sub(1, Ordering::SeqCst) - 1;
201
202			let current_id = current_task_borrowed.id;
203			drop(current_task_borrowed);
204
205			// wakeup tasks, which are waiting for task with the identifier id
206			if let Some(mut queue) = WAITING_TASKS.lock().remove(&current_id) {
207				while let Some(task) = queue.pop_front() {
208					self.custom_wakeup(task);
209				}
210			}
211
212			TASKS.lock().remove(&current_id);
213
214			assert!(
215				remaining_tasks != 0,
216				"Last task exited with exit code {exit_code}"
217			);
218		});
219
220		self.reschedule();
221		unreachable!()
222	}
223}
224
225struct NewTask {
226	tid: TaskId,
227	func: unsafe extern "C" fn(usize),
228	arg: usize,
229	prio: Priority,
230	core_id: CoreId,
231	stacks: TaskStacks,
232	object_map: Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>>,
233}
234
235impl From<NewTask> for Task {
236	fn from(value: NewTask) -> Self {
237		let NewTask {
238			tid,
239			func,
240			arg,
241			prio,
242			core_id,
243			stacks,
244			object_map,
245		} = value;
246		let mut task = Self::new(tid, core_id, TaskStatus::Ready, prio, stacks, object_map);
247		task.create_stack_frame(func, arg);
248		task
249	}
250}
251
252impl PerCoreScheduler {
253	/// Spawn a new task.
254	pub unsafe fn spawn(
255		func: unsafe extern "C" fn(usize),
256		arg: usize,
257		prio: Priority,
258		core_id: CoreId,
259		stack_size: usize,
260	) -> TaskId {
261		// Create the new task.
262		let tid = get_tid();
263		let stacks = TaskStacks::new(stack_size);
264		let new_task = NewTask {
265			tid,
266			func,
267			arg,
268			prio,
269			core_id,
270			stacks,
271			object_map: core_scheduler().get_current_task_object_map(),
272		};
273
274		// Add it to the task lists.
275		let wakeup = {
276			#[cfg(feature = "smp")]
277			let mut input_locked = get_scheduler_input(core_id).lock();
278			WAITING_TASKS.lock().insert(tid, VecDeque::with_capacity(1));
279			TASKS.lock().insert(
280				tid,
281				TaskHandle::new(
282					tid,
283					prio,
284					#[cfg(feature = "smp")]
285					core_id,
286				),
287			);
288			NO_TASKS.fetch_add(1, Ordering::SeqCst);
289
290			#[cfg(feature = "smp")]
291			if core_id == core_scheduler().core_id {
292				let task = Rc::new(RefCell::new(Task::from(new_task)));
293				core_scheduler().ready_queue.push(task);
294				false
295			} else {
296				input_locked.new_tasks.push_back(new_task);
297				true
298			}
299			#[cfg(not(feature = "smp"))]
300			if core_id == 0 {
301				let task = Rc::new(RefCell::new(Task::from(new_task)));
302				core_scheduler().ready_queue.push(task);
303				false
304			} else {
305				panic!("Invalid core_id {core_id}!")
306			}
307		};
308
309		debug!("Creating task {tid} with priority {prio} on core {core_id}");
310
311		if wakeup {
312			kernel::wakeup_core(core_id);
313		}
314
315		tid
316	}
317
318	#[cfg(feature = "newlib")]
319	fn clone_impl(&self, func: extern "C" fn(usize), arg: usize) -> TaskId {
320		static NEXT_CORE_ID: AtomicU32 = AtomicU32::new(1);
321
322		// Get the Core ID of the next CPU.
323		let core_id: CoreId = {
324			// Increase the CPU number by 1.
325			let id = NEXT_CORE_ID.fetch_add(1, Ordering::SeqCst);
326
327			// Check for overflow.
328			if id == get_processor_count() {
329				NEXT_CORE_ID.store(0, Ordering::SeqCst);
330				0
331			} else {
332				id
333			}
334		};
335
336		// Get the current task.
337		let current_task_borrowed = self.current_task.borrow();
338
339		// Clone the current task.
340		let tid = get_tid();
341		let clone_task = NewTask {
342			tid,
343			func,
344			arg,
345			prio: current_task_borrowed.prio,
346			core_id,
347			stacks: TaskStacks::new(current_task_borrowed.stacks.get_user_stack_size()),
348			object_map: current_task_borrowed.object_map.clone(),
349		};
350
351		// Add it to the task lists.
352		let wakeup = {
353			#[cfg(feature = "smp")]
354			let mut input_locked = get_scheduler_input(core_id).lock();
355			WAITING_TASKS.lock().insert(tid, VecDeque::with_capacity(1));
356			TASKS.lock().insert(
357				tid,
358				TaskHandle::new(
359					tid,
360					current_task_borrowed.prio,
361					#[cfg(feature = "smp")]
362					core_id,
363				),
364			);
365			NO_TASKS.fetch_add(1, Ordering::SeqCst);
366			#[cfg(feature = "smp")]
367			if core_id == core_scheduler().core_id {
368				let clone_task = Rc::new(RefCell::new(Task::from(clone_task)));
369				core_scheduler().ready_queue.push(clone_task);
370				false
371			} else {
372				input_locked.new_tasks.push_back(clone_task);
373				true
374			}
375			#[cfg(not(feature = "smp"))]
376			if core_id == 0 {
377				let clone_task = Rc::new(RefCell::new(Task::from(clone_task)));
378				core_scheduler().ready_queue.push(clone_task);
379				false
380			} else {
381				panic!("Invalid core_id {core_id}!");
382			}
383		};
384
385		// Wake up the CPU
386		if wakeup {
387			kernel::wakeup_core(core_id);
388		}
389
390		tid
391	}
392
393	#[cfg(feature = "newlib")]
394	pub fn clone(&self, func: extern "C" fn(usize), arg: usize) -> TaskId {
395		without_interrupts(|| self.clone_impl(func, arg))
396	}
397
398	/// Returns `true` if a reschedule is required
399	#[inline]
400	#[cfg(all(any(target_arch = "x86_64", target_arch = "riscv64"), feature = "smp"))]
401	pub fn is_scheduling(&self) -> bool {
402		self.current_task.borrow().prio < self.ready_queue.get_highest_priority()
403	}
404
405	#[inline]
406	pub fn handle_waiting_tasks(&mut self) {
407		without_interrupts(|| {
408			crate::executor::run();
409			self.blocked_tasks
410				.handle_waiting_tasks(&mut self.ready_queue);
411		});
412	}
413
414	#[cfg(not(feature = "smp"))]
415	pub fn custom_wakeup(&mut self, task: TaskHandle) {
416		without_interrupts(|| {
417			let Some(task) = self.blocked_tasks.custom_wakeup(task) else {
418				return;
419			};
420			self.ready_queue.push(task);
421			// The woken task is now ready. Arm the preemption timer so the running
422			// task — which may be CPU-bound and never yield — is preempted soon and
423			// the newcomer gets to run.
424			#[cfg(feature = "preemptive")]
425			{
426				let deadline = processor::get_timer_ticks() + PREEMPTION_SLICE_US;
427				timer_interrupts::create_timer_abs(timer_interrupts::Source::Preemption, deadline);
428			}
429		});
430	}
431
432	#[cfg(feature = "smp")]
433	pub fn custom_wakeup(&mut self, task: TaskHandle) {
434		if task.get_core_id() == self.core_id {
435			without_interrupts(|| {
436				let Some(task) = self.blocked_tasks.custom_wakeup(task) else {
437					return;
438				};
439				self.ready_queue.push(task);
440				// The woken task is now ready on this core. Arm the preemption timer
441				// so the running (possibly non-yielding) task is preempted soon.
442				#[cfg(feature = "preemptive")]
443				{
444					let deadline = processor::get_timer_ticks() + PREEMPTION_SLICE_US;
445					timer_interrupts::create_timer_abs(
446						timer_interrupts::Source::Preemption,
447						deadline,
448					);
449				}
450			});
451		} else {
452			get_scheduler_input(task.get_core_id())
453				.lock()
454				.wakeup_tasks
455				.push_back(task);
456			// Wake up the CPU
457			kernel::wakeup_core(task.get_core_id());
458		}
459	}
460
461	#[inline]
462	pub fn block_current_task(&mut self, wakeup_time: Option<u64>) {
463		without_interrupts(|| {
464			self.blocked_tasks
465				.add(self.current_task.clone(), wakeup_time);
466		});
467	}
468
469	#[inline]
470	pub fn get_current_task_handle(&self) -> TaskHandle {
471		without_interrupts(|| {
472			let current_task_borrowed = self.current_task.borrow();
473
474			TaskHandle::new(
475				current_task_borrowed.id,
476				current_task_borrowed.prio,
477				#[cfg(feature = "smp")]
478				current_task_borrowed.core_id,
479			)
480		})
481	}
482
483	#[inline]
484	pub fn get_current_task_id(&self) -> TaskId {
485		without_interrupts(|| self.current_task.borrow().id)
486	}
487
488	#[inline]
489	pub fn get_current_task_object_map(
490		&self,
491	) -> Arc<RwSpinLock<HashMap<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>>> {
492		without_interrupts(|| self.current_task.borrow().object_map.clone())
493	}
494
495	/// Map a file descriptor to their IO interface and returns
496	/// the shared reference
497	#[inline]
498	pub fn get_object(&self, fd: RawFd) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
499		without_interrupts(|| {
500			let current_task = self.current_task.borrow();
501			let object_map = current_task.object_map.read();
502			object_map.get(&fd).cloned().ok_or(Errno::Badf)
503		})
504	}
505
506	/// Creates a new map between file descriptor and their IO interface and
507	/// clone the standard descriptors.
508	#[cfg(feature = "common-os")]
509	#[cfg_attr(not(target_arch = "x86_64"), expect(dead_code))]
510	pub fn recreate_objmap(&self) -> io::Result<()> {
511		let mut map = HashMap::<RawFd, Arc<async_lock::RwLock<Fd>>, RandomState>::with_hasher(
512			RandomState::with_seeds(0, 0, 0, 0),
513		);
514
515		without_interrupts(|| {
516			let mut current_task = self.current_task.borrow_mut();
517			let object_map = current_task.object_map.read();
518
519			// clone standard file descriptors
520			for i in 0..3 {
521				if let Some(obj) = object_map.get(&i) {
522					map.insert(i, obj.clone());
523				}
524			}
525
526			drop(object_map);
527			current_task.object_map = Arc::new(RwSpinLock::new(map));
528		});
529
530		Ok(())
531	}
532
533	/// Insert a new IO interface and returns a file descriptor as
534	/// identifier to this object
535	pub fn insert_object(&self, obj: Arc<async_lock::RwLock<Fd>>) -> io::Result<RawFd> {
536		without_interrupts(|| {
537			let current_task = self.current_task.borrow();
538			let mut object_map = current_task.object_map.write();
539
540			let new_fd = || -> io::Result<RawFd> {
541				let mut fd: RawFd = 0;
542				loop {
543					if !object_map.contains_key(&fd) {
544						break Ok(fd);
545					} else if fd == RawFd::MAX {
546						break Err(Errno::Overflow);
547					}
548
549					fd = fd.saturating_add(1);
550				}
551			};
552
553			let fd = new_fd()?;
554			object_map.insert(fd, obj.clone());
555			Ok(fd)
556		})
557	}
558
559	/// Duplicate a IO interface and returns a new file descriptor as
560	/// identifier to the new copy
561	pub fn dup_object(&self, fd: RawFd) -> io::Result<RawFd> {
562		without_interrupts(|| {
563			let current_task = self.current_task.borrow();
564			let mut object_map = current_task.object_map.write();
565
566			let obj = (*(object_map.get(&fd).ok_or(Errno::Inval)?)).clone();
567
568			let new_fd = || -> io::Result<RawFd> {
569				let mut fd: RawFd = 0;
570				loop {
571					if !object_map.contains_key(&fd) {
572						break Ok(fd);
573					} else if fd == RawFd::MAX {
574						break Err(Errno::Overflow);
575					}
576
577					fd = fd.saturating_add(1);
578				}
579			};
580
581			let fd = new_fd()?;
582			match object_map.entry(fd) {
583				hash_map::Entry::Occupied(_occupied_entry) => Err(Errno::Mfile),
584				hash_map::Entry::Vacant(vacant_entry) => {
585					vacant_entry.insert(obj);
586					Ok(fd)
587				}
588			}
589		})
590	}
591
592	pub fn dup_object2(&self, fd1: RawFd, fd2: RawFd) -> io::Result<RawFd> {
593		// Closing the replaced object may block, so drop it only after
594		// releasing the object map and the current task.
595		let replaced = without_interrupts(|| -> io::Result<_> {
596			let current_task = self.current_task.borrow();
597			let mut object_map = current_task.object_map.write();
598
599			let obj = object_map.get(&fd1).cloned().ok_or(Errno::Badf)?;
600
601			Ok(object_map.insert(fd2, obj))
602		})?;
603
604		if replaced.is_some() {
605			debug!("dup2({fd1}, {fd2}): replaced previously open fd {fd2}");
606		}
607		Ok(fd2)
608	}
609
610	/// Remove a IO interface, which is named by the file descriptor
611	pub fn remove_object(&self, fd: RawFd) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
612		without_interrupts(|| {
613			let current_task = self.current_task.borrow();
614			let mut object_map = current_task.object_map.write();
615
616			object_map.remove(&fd).ok_or(Errno::Badf)
617		})
618	}
619
620	#[inline]
621	pub fn get_current_task_prio(&self) -> Priority {
622		without_interrupts(|| self.current_task.borrow().prio)
623	}
624
625	/// Returns reference to prio_bitmap
626	#[allow(dead_code)]
627	#[inline]
628	pub fn get_priority_bitmap(&self) -> &u64 {
629		self.ready_queue.get_priority_bitmap()
630	}
631
632	#[cfg(target_arch = "x86_64")]
633	pub fn set_current_kernel_stack(&self) {
634		let current_task_borrowed = self.current_task.borrow();
635		let tss = unsafe { &mut *CoreLocal::get().tss.get() };
636
637		let rsp = current_task_borrowed.stacks.get_kernel_stack()
638			+ current_task_borrowed.stacks.get_kernel_stack_size() as u64
639			- TaskStacks::MARKER_SIZE as u64;
640		tss.privilege_stack_table[0] = rsp.into();
641		CoreLocal::get().kernel_stack.set(rsp.as_mut_ptr());
642		let ist_start = current_task_borrowed.stacks.get_interrupt_stack()
643			+ current_task_borrowed.stacks.get_interrupt_stack_size() as u64
644			- TaskStacks::MARKER_SIZE as u64;
645		tss.interrupt_stack_table[0] = ist_start.into();
646	}
647
648	pub fn set_current_task_priority(&mut self, prio: Priority) {
649		without_interrupts(|| {
650			trace!("Change priority of the current task");
651			self.current_task.borrow_mut().prio = prio;
652		});
653	}
654
655	pub fn set_priority(&mut self, id: TaskId, prio: Priority) -> Result<(), ()> {
656		trace!("Change priority of task {id} to priority {prio}");
657
658		without_interrupts(|| {
659			let task = get_task_handle(id).ok_or(())?;
660			#[cfg(feature = "smp")]
661			let other_core = task.get_core_id() != self.core_id;
662			#[cfg(not(feature = "smp"))]
663			let other_core = false;
664
665			if other_core {
666				warn!("Have to change the priority on another core");
667			} else if self.current_task.borrow().id == task.get_id() {
668				self.current_task.borrow_mut().prio = prio;
669			} else {
670				self.ready_queue
671					.set_priority(task, prio)
672					.expect("Do not find valid task in ready queue");
673			}
674
675			Ok(())
676		})
677	}
678
679	#[cfg(target_arch = "riscv64")]
680	pub fn set_current_kernel_stack(&self) {
681		let current_task_borrowed = self.current_task.borrow();
682
683		let stack = (current_task_borrowed.stacks.get_kernel_stack()
684			+ current_task_borrowed.stacks.get_kernel_stack_size() as u64
685			- TaskStacks::MARKER_SIZE as u64)
686			.as_u64();
687		CoreLocal::get().kernel_stack.set(stack);
688	}
689
690	/// Save the FPU context for the current FPU owner and restore it for the current task,
691	/// which wants to use the FPU now.
692	#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
693	pub fn fpu_switch(&mut self) {
694		if !Rc::ptr_eq(&self.current_task, &self.fpu_owner) {
695			debug!(
696				"Switching FPU owner from task {} to {}",
697				self.fpu_owner.borrow().id,
698				self.current_task.borrow().id
699			);
700
701			self.fpu_owner.borrow_mut().last_fpu_state.save();
702			self.current_task.borrow().last_fpu_state.restore();
703			self.fpu_owner = self.current_task.clone();
704		}
705	}
706
707	/// Check if a finished task could be deleted.
708	fn cleanup_tasks(&mut self) {
709		// Pop the first finished task and remove it from the TASKS list, which implicitly deallocates all associated memory.
710		while let Some(finished_task) = self.finished_tasks.pop_front() {
711			debug!("Cleaning up task {}", finished_task.borrow().id);
712		}
713	}
714
715	#[cfg(feature = "smp")]
716	pub fn check_input(&mut self) {
717		let mut input_locked = CoreLocal::get().scheduler_input.lock();
718
719		while let Some(task) = input_locked.wakeup_tasks.pop_front() {
720			if let Some(task) = self.blocked_tasks.custom_wakeup(task) {
721				self.ready_queue.push(task);
722			}
723		}
724
725		while let Some(new_task) = input_locked.new_tasks.pop_front() {
726			let task = Rc::new(RefCell::new(Task::from(new_task)));
727			self.ready_queue.push(task.clone());
728		}
729	}
730
731	/// Only the idle task should call this function.
732	/// Set the idle task to halt state if not another
733	/// available.
734	pub fn run() -> ! {
735		let backoff = Backoff::new();
736
737		loop {
738			let core_scheduler = core_scheduler();
739			interrupts::disable();
740
741			// run async tasks
742			let async_pending = crate::executor::run();
743
744			// do housekeeping
745			#[cfg(feature = "smp")]
746			core_scheduler.check_input();
747			core_scheduler.cleanup_tasks();
748
749			if core_scheduler.ready_queue.is_empty() {
750				// Do not halt while async tasks are still runnable, e.g. the network
751				// task that re-queued itself because another core holds the NIC lock
752				// (#2729). Otherwise it would only run again on the next interrupt.
753				if backoff.is_completed() && !async_pending {
754					interrupts::enable_and_wait();
755					backoff.reset();
756				} else {
757					interrupts::enable();
758					backoff.snooze();
759				}
760			} else {
761				interrupts::enable();
762				core_scheduler.reschedule();
763				backoff.reset();
764			}
765		}
766	}
767
768	#[inline]
769	#[cfg(target_arch = "aarch64")]
770	pub fn get_last_stack_pointer(&self) -> memory_addresses::VirtAddr {
771		self.current_task.borrow().last_stack_pointer
772	}
773
774	/// Triggers the scheduler to reschedule the tasks.
775	/// Interrupt flag must be cleared before calling this function.
776	pub fn scheduler(&mut self) -> Option<*mut usize> {
777		// run background tasks
778		crate::executor::run();
779
780		// Someone wants to give up the CPU
781		// => we have time to cleanup the system
782		self.cleanup_tasks();
783
784		// Get information about the current task.
785		let (id, last_stack_pointer, prio, status) = {
786			let mut borrowed = self.current_task.borrow_mut();
787			(
788				borrowed.id,
789				ptr::from_mut(&mut borrowed.last_stack_pointer).cast::<usize>(),
790				borrowed.prio,
791				borrowed.status,
792			)
793		};
794
795		let mut new_task = None;
796
797		if status == TaskStatus::Running {
798			// A task is currently running.
799			// Check if a task with a equal or higher priority is available.
800			if let Some(task) = self.ready_queue.pop_with_prio(prio) {
801				new_task = Some(task);
802			}
803		} else {
804			if status == TaskStatus::Finished {
805				// Mark the finished task as invalid and add it to the finished tasks for a later cleanup.
806				self.current_task.borrow_mut().status = TaskStatus::Invalid;
807				self.finished_tasks.push_back(self.current_task.clone());
808			}
809
810			// No task is currently running.
811			// Check if there is any available task and get the one with the highest priority.
812			if let Some(task) = self.ready_queue.pop() {
813				// This available task becomes the new task.
814				debug!("Task is available.");
815				new_task = Some(task);
816			} else if status != TaskStatus::Idle {
817				// The Idle task becomes the new task.
818				debug!("Only Idle Task is available.");
819				new_task = Some(self.idle_task.clone());
820			}
821		}
822
823		let task = new_task?;
824		// There is a new task we want to switch to.
825
826		// Handle the current task.
827		if status == TaskStatus::Running {
828			// Mark the running task as ready again and add it back to the queue.
829			self.current_task.borrow_mut().status = TaskStatus::Ready;
830			self.ready_queue.push(self.current_task.clone());
831		}
832
833		// Handle the new task and get information about it.
834		let (new_id, new_stack_pointer) = {
835			let mut borrowed = task.borrow_mut();
836			if borrowed.status != TaskStatus::Idle {
837				// Mark the new task as running.
838				borrowed.status = TaskStatus::Running;
839			}
840
841			(borrowed.id, borrowed.last_stack_pointer)
842		};
843
844		if id == new_id {
845			return None;
846		}
847
848		// Preemptive round-robin: arm a one-shot time-slice timer for the task we
849		// are about to run, but only while other tasks are ready — with no
850		// contention the system stays tickless. When the slice expires, the timer
851		// interrupt's `reschedule()` switches to the next ready task.
852		#[cfg(feature = "preemptive")]
853		if !self.ready_queue.is_empty() {
854			let deadline = processor::get_timer_ticks() + PREEMPTION_SLICE_US;
855			timer_interrupts::create_timer_abs(timer_interrupts::Source::Preemption, deadline);
856		}
857
858		// Tell the scheduler about the new task.
859		debug!(
860			"Switching task from {} to {} (stack {:#X} => {:p})",
861			id,
862			new_id,
863			unsafe { *last_stack_pointer },
864			new_stack_pointer
865		);
866		#[cfg(not(target_arch = "riscv64"))]
867		{
868			self.current_task = task;
869		}
870
871		// Finally return the context of the new task.
872		#[cfg(not(target_arch = "riscv64"))]
873		return Some(last_stack_pointer);
874
875		#[cfg(target_arch = "riscv64")]
876		{
877			if sstatus::read().fs() == sstatus::FS::Dirty {
878				self.current_task.borrow_mut().last_fpu_state.save();
879			}
880			task.borrow().last_fpu_state.restore();
881			self.current_task = task;
882			unsafe {
883				switch_to_task(last_stack_pointer, new_stack_pointer.as_usize());
884			}
885			None
886		}
887	}
888}
889
890fn get_tid() -> TaskId {
891	static TID_COUNTER: AtomicI32 = AtomicI32::new(0);
892	let guard = TASKS.lock();
893
894	loop {
895		let id = TaskId::from(TID_COUNTER.fetch_add(1, Ordering::SeqCst));
896		if !guard.contains_key(&id) {
897			return id;
898		}
899	}
900}
901
902#[inline]
903pub(crate) fn abort() -> ! {
904	cfg_select! {
905		feature = "common-os" => {
906			error!("Aborting tread execution");
907			core_scheduler().exit(-1)
908		}
909		_ => {
910			error!("Aborting kernel execution");
911			shutdown(-1);
912		}
913	}
914}
915
916/// Add a per-core scheduler for the current core.
917pub(crate) fn add_current_core() {
918	// Create an idle task for this core.
919	let core_id = core_id();
920	let tid = get_tid();
921	let idle_task = Rc::new(RefCell::new(Task::new_idle(tid, core_id)));
922
923	// Add the ID -> Task mapping.
924	WAITING_TASKS.lock().insert(tid, VecDeque::with_capacity(1));
925	TASKS.lock().insert(
926		tid,
927		TaskHandle::new(
928			tid,
929			IDLE_PRIO,
930			#[cfg(feature = "smp")]
931			core_id,
932		),
933	);
934	// Initialize a scheduler for this core.
935	debug!("Initializing scheduler for core {core_id} with idle task {tid}");
936	let boxed_scheduler = Box::new(PerCoreScheduler {
937		#[cfg(feature = "smp")]
938		core_id,
939		current_task: idle_task.clone(),
940		#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
941		fpu_owner: idle_task.clone(),
942		idle_task,
943		ready_queue: PriorityTaskQueue::new(),
944		finished_tasks: VecDeque::new(),
945		blocked_tasks: BlockedTaskQueue::new(),
946		timers: TimerList::new(),
947	});
948
949	let scheduler = Box::into_raw(boxed_scheduler);
950	set_core_scheduler(scheduler);
951	#[cfg(feature = "smp")]
952	{
953		SCHEDULER_INPUTS.lock().insert(
954			core_id.try_into().unwrap(),
955			&CoreLocal::get().scheduler_input,
956		);
957		#[cfg(all(
958			any(target_arch = "x86_64", target_arch = "riscv64"),
959			not(feature = "idle-poll")
960		))]
961		sleep_state::install_for_core(core_id);
962	}
963}
964
965#[inline]
966#[cfg(feature = "smp")]
967fn get_scheduler_input(core_id: CoreId) -> &'static InterruptTicketMutex<SchedulerInput> {
968	SCHEDULER_INPUTS.lock()[usize::try_from(core_id).unwrap()]
969}
970
971pub unsafe fn spawn(
972	func: unsafe extern "C" fn(usize),
973	arg: usize,
974	prio: Priority,
975	stack_size: usize,
976	selector: isize,
977) -> TaskId {
978	static CORE_COUNTER: AtomicU32 = AtomicU32::new(1);
979
980	let core_id = if selector < 0 {
981		// use Round Robin to schedule the cores
982		CORE_COUNTER.fetch_add(1, Ordering::SeqCst) % get_processor_count()
983	} else {
984		selector as u32
985	};
986
987	unsafe { PerCoreScheduler::spawn(func, arg, prio, core_id, stack_size) }
988}
989
990#[allow(clippy::result_unit_err)]
991pub fn join(id: TaskId) -> Result<(), ()> {
992	let core_scheduler = core_scheduler();
993
994	debug!(
995		"Task {} is waiting for task {}",
996		core_scheduler.get_current_task_id(),
997		id
998	);
999
1000	loop {
1001		let mut waiting_tasks_guard = WAITING_TASKS.lock();
1002
1003		let Some(queue) = waiting_tasks_guard.get_mut(&id) else {
1004			return Ok(());
1005		};
1006
1007		queue.push_back(core_scheduler.get_current_task_handle());
1008		core_scheduler.block_current_task(None);
1009
1010		// Switch to the next task.
1011		drop(waiting_tasks_guard);
1012		core_scheduler.reschedule();
1013	}
1014}
1015
1016pub fn shutdown(arg: i32) -> ! {
1017	crate::syscalls::shutdown(arg)
1018}
1019
1020fn get_task_handle(id: TaskId) -> Option<TaskHandle> {
1021	TASKS.lock().get(&id).copied()
1022}
1023
1024#[cfg(all(target_arch = "x86_64", feature = "common-os"))]
1025pub(crate) static BOOT_ROOT_PAGE_TABLE: OnceCell<usize> = OnceCell::new();
1026
1027#[cfg(all(target_arch = "x86_64", feature = "common-os"))]
1028pub(crate) fn get_root_page_table() -> usize {
1029	let current_task_borrowed = core_scheduler().current_task.borrow_mut();
1030	current_task_borrowed.root_page_table
1031}