Repository navigation
Expand file tree
/
Copy pathscheduler.rs
More file actions
586 lines (515 loc) · 20.3 KB
/
Copy pathscheduler.rs
File metadata and controls
586 lines (515 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! Define types and trait for the Awkernel scheduler.
//! This module contains `SleepingTasks` for sleeping.
use core::sync::atomic::Ordering;
use core::time::Duration;
use crate::{
task::{get_current_task, get_scheduler_type_by_task_id, State, Task, NUM_TASK_IN_QUEUE},
time::Instant,
};
use alloc::collections::{binary_heap::BinaryHeap, btree_map::BTreeMap};
use alloc::sync::Arc;
use awkernel_lib::{
cpu::{num_cpu, CpuSet},
priority_queue::PriorityQueue,
sync::mutex::{MCSNode, Mutex},
verified::delta_list::DeltaList,
};
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
mod clustered;
mod edf;
mod llft;
pub(super) mod panicked;
mod prioritized_fifo;
mod prioritized_rr;
static SLEEPING: Mutex<SleepingTasks> = Mutex::new(SleepingTasks::new());
/// Tasks that request preemption by IPI. The key is the IPI destination CPU ID.
static PREEMPTION_PENDING_TASKS: Mutex<BTreeMap<usize, BinaryHeap<Arc<Task>>>> =
Mutex::new(BTreeMap::new());
#[inline(always)]
pub fn peek_preemption_pending(cpu_id: usize) -> Option<Arc<Task>> {
let mut node = MCSNode::new();
let pending_tasks = PREEMPTION_PENDING_TASKS.lock(&mut node);
pending_tasks
.get(&cpu_id)
.and_then(|heap| heap.peek().cloned())
}
#[inline(always)]
pub fn remove_preemption_pending(cpu_id: usize, task_id: u32) {
let mut node = MCSNode::new();
let mut pending_tasks = PREEMPTION_PENDING_TASKS.lock(&mut node);
if let Some(heap) = pending_tasks.get_mut(&cpu_id) {
heap.retain(|task| task.id != task_id);
}
}
#[inline(always)]
pub fn push_preemption_pending(cpu_id: usize, task: Arc<Task>) {
let mut node = MCSNode::new();
let mut pending_tasks = PREEMPTION_PENDING_TASKS.lock(&mut node);
pending_tasks.entry(cpu_id).or_default().push(task);
}
#[inline(always)]
pub fn pop_preemption_pending(cpu_id: usize) -> Option<Arc<Task>> {
let mut node = MCSNode::new();
let mut pending_tasks = PREEMPTION_PENDING_TASKS.lock(&mut node);
pending_tasks.get_mut(&cpu_id).and_then(|heap| heap.pop())
}
#[inline(always)]
pub fn move_preemption_pending(cpu_id: usize) -> Option<BinaryHeap<Arc<Task>>> {
let mut node = MCSNode::new();
let mut pending_tasks = PREEMPTION_PENDING_TASKS.lock(&mut node);
pending_tasks.remove(&cpu_id)
}
/// Type of scheduler.
/// `u8` is the priority of priority based schedulers.
/// 0 is the lowest priority and 31 is the highest priority.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchedulerType {
/// Earliest Deadline First (EDF): `(relative_deadline, cpu_set)`.
///
/// `cpu_set` is the set of cores the task may run on. It is normalized at
/// spawn time: CPU 0 (the primary core) and any out-of-range bits are
/// removed. If normalization leaves the set empty — e.g. an empty set, or
/// one naming only CPU 0 or out-of-range cores — the task is **not**
/// rejected; it falls back to all worker cores (`1..num_cpu()`) with a
/// warning.
///
/// `CpuSet::all()` gives global EDF, and a one-core set gives
/// partitioned EDF.
EDF(u64, CpuSet),
/// Least Latest Finish Time (LLFT): `(relative_deadline, cpu_set)`.
///
/// DAG tasks are ordered by their estimated latest finish; standalone
/// tasks use their relative deadline in microseconds. Affinity is
/// normalized in the same way as for EDF.
LLFT(u64, CpuSet),
PrioritizedFIFO(u8),
PrioritizedRR(u8),
Panicked,
}
impl SchedulerType {
pub const fn equals(&self, other: &Self) -> bool {
matches!(
(self, other),
(SchedulerType::EDF(_, _), SchedulerType::EDF(_, _))
| (SchedulerType::LLFT(_, _), SchedulerType::LLFT(_, _))
| (
SchedulerType::PrioritizedFIFO(_),
SchedulerType::PrioritizedFIFO(_)
)
| (
SchedulerType::PrioritizedRR(_),
SchedulerType::PrioritizedRR(_)
)
| (SchedulerType::Panicked, SchedulerType::Panicked)
)
}
/// Return the CPU affinity set for a clustered scheduler.
///
/// Returns `Some(set)` where `set` is the set of CPU cores (`1..num_cpu()`) the task
/// may run on. Returns `None` for all other scheduler variants.
pub const fn cpu_set(&self) -> Option<CpuSet> {
match self {
SchedulerType::EDF(_, set) | SchedulerType::LLFT(_, set) => Some(*set),
_ => None,
}
}
/// True if this is a clustered scheduler, i.e. one whose tasks carry a
/// CPU affinity set. Update this function when adding a new clustered
/// scheduler; it is the single source of truth for the clustered prefix
/// of `PRIORITY_LIST`.
pub const fn is_clustered(&self) -> bool {
matches!(self, SchedulerType::EDF(_, _) | SchedulerType::LLFT(_, _))
}
}
/// # Priority
///
/// `priority()` returns the priority of the scheduler for preemption.
///
/// - The highest priority.
/// - EDF scheduler.
/// - The second highest priority.
/// - LLFT scheduler.
/// - The third highest priority.
/// - Prioritized FIFO scheduler.
/// - The fourth highest priority.
/// - Prioritized Round-Robin scheduler.
/// - The lowest priority.
/// - Panicked scheduler.
static PRIORITY_LIST: [SchedulerType; 5] = [
SchedulerType::EDF(0, CpuSet::empty()),
SchedulerType::LLFT(0, CpuSet::empty()),
SchedulerType::PrioritizedFIFO(0),
SchedulerType::PrioritizedRR(0),
SchedulerType::Panicked,
];
/// Return the number of clustered schedulers in `PRIORITY_LIST`.
const fn get_num_clustered_schedulers() -> usize {
let mut count = 0;
while count < PRIORITY_LIST.len() {
if PRIORITY_LIST[count].is_clustered() {
count += 1;
} else {
break;
}
}
count
}
// `get_next_task` relies on the clustered schedulers forming a strict prefix
// of `PRIORITY_LIST`. Reject any reorder at compile time.
const _: () = {
let mut i = get_num_clustered_schedulers();
while i < PRIORITY_LIST.len() {
assert!(
!PRIORITY_LIST[i].is_clustered(),
"clustered schedulers must form a strict prefix of PRIORITY_LIST"
);
i += 1;
}
};
/// When false, no scheduler requests preemption, and `wake_task` enqueues the woken task.
/// `no_preempt` compiles out the IPI handler that runs preemption-pending tasks.
/// Without this flag, a pending task waits until its target CPU goes idle and starves while every worker keeps polling.
pub(crate) const PREEMPTION_ENABLED: bool = cfg!(not(feature = "no_preempt"));
/// For exclusion execution of `wake_task` and `get_next` across all schedulers.
/// In order to resolve priority inversion in multiple priority-based schedulers,
/// the decision to preempt, dequeuing, enqueuing, and updating of RUNNING must be executed exclusively.
static GLOBAL_WAKE_GET_MUTEX: Mutex<()> = Mutex::new(());
/// # Implementing a clustered scheduler
///
/// A clustered scheduler keeps tasks that may run only on a subset of CPUs.
/// Use [`clustered::ClusteredScheduler`] to share the affinity-aware queue,
/// clustered-task accounting, and queued CPU mask implementation. Implement
/// [`clustered::ClusteredOrdering`] to identify the scheduler type and define
/// how ready tasks are ordered.
///
/// The scheduler type must still be placed in the clustered prefix of
/// `PRIORITY_LIST` and matched by [`SchedulerType::is_clustered`]. The prefix
/// requirement is checked at compile time.
pub(crate) trait Scheduler {
/// Enqueue an executable task.
/// The enqueued task will be taken by `get_next()`.
fn wake_task(&self, task: Arc<Task>);
/// Get the next executable task.
/// The dequeued task is marked as running on the calling CPU.
fn get_next(&self) -> Option<Arc<Task>>;
/// Dequeue the task at the head of the run queue, but only if `pred`
/// accepts it. A rejected task stays at the head of the run queue.
/// Unlike `get_next()`, the dequeued task is not marked as running.
///
/// The check and the dequeue must be done without releasing the lock of
/// the run queue, so that the dequeued task is the one `pred` accepted.
///
/// This is used only by `get_next_task_if()`, which runs on the primary
/// CPU (CPU 0). A scheduler whose tasks must never be taken that way
/// returns [`ConditionalNext::Empty`].
fn get_next_if(&self, pred: &dyn Fn(&Task) -> bool) -> ConditionalNext;
/// Get the scheduler name.
fn scheduler_name(&self) -> SchedulerType;
#[allow(dead_code)] // TODO: to be removed
fn priority(&self) -> u8;
/// The set of CPUs that have at least one queued task eligible to run on
/// them. Non-clustered schedulers use the default (empty) implementation;
/// clustered schedulers must override it.
fn queued_cpu_mask(&self) -> CpuSet {
CpuSet::empty()
}
}
/// Return the union of [`Scheduler::queued_cpu_mask`] over all clustered
/// schedulers: the exact set of CPUs for which a clustered task is queued.
pub(crate) fn clustered_queued_cpu_mask() -> CpuSet {
let mut mask = CpuSet::empty();
for scheduler_type in &PRIORITY_LIST[..get_num_clustered_schedulers()] {
mask = mask.union(get_scheduler(scheduler_type).queued_cpu_mask());
}
mask
}
/// Get the next executable task.
#[inline]
pub(crate) fn get_next_task() -> Option<Arc<Task>> {
let mut node = MCSNode::new();
let _guard = GLOBAL_WAKE_GET_MUTEX.lock(&mut node);
let num_clustered_tasks = crate::task::NUM_CLUSTERED_TASKS_IN_QUEUE.load(Ordering::Relaxed);
// The counter is global: it may be non-zero even when no queued clustered
// task is runnable on this CPU. That is fine because the run queues fail
// fast (`pop_for_cpu` checks the root affinity mask in O(1)).
if num_clustered_tasks > 0 {
let task = PRIORITY_LIST[..get_num_clustered_schedulers()]
.iter()
.find_map(|scheduler_type| get_scheduler(scheduler_type).get_next());
// The counter is decremented by the ClusteredTask::take() call inside
// get_next() (Drop is a no-op once take() has run).
if task.is_some() {
return task;
}
}
// Skip the clustered prefix: it was either just tried above and returned
// None (the queue state cannot change in between because both `wake_task`
// and `get_next_task` hold `GLOBAL_WAKE_GET_MUTEX`), or the counter was 0
// and its queues are empty.
PRIORITY_LIST[get_num_clustered_schedulers()..]
.iter()
.find_map(|scheduler_type| get_scheduler(scheduler_type).get_next())
}
/// The result of [`Scheduler::get_next_if`].
pub(crate) enum ConditionalNext {
/// The run queue has no executable task.
Empty,
/// The head of the run queue was rejected and is left in the queue.
Rejected,
/// The head of the run queue was accepted and dequeued.
Taken(Arc<Task>),
}
/// Dequeue the next executable task only if `pred` accepts it.
///
/// This examines the head of the run queues of the non-clustered schedulers
/// in the order of their priorities, except that panicked tasks are never
/// taken. If `pred` returns `false` for it, the run queues are left
/// untouched, so the task keeps its position in the queue, and `false` is
/// returned. The dequeued task is not marked as running.
///
/// If a task is dequeued, it is passed to `on_taken` and `true` is returned.
///
/// `pred` is called with `GLOBAL_WAKE_GET_MUTEX`, the lock of the run queue,
/// and the lock of the task information held. `on_taken` is called with only
/// `GLOBAL_WAKE_GET_MUTEX` held, so what `pred` observed under that mutex
/// still holds, and a worker that takes the mutex afterwards sees the effect
/// of `on_taken`.
///
/// This function must be called on the primary CPU, which can never dequeue
/// a clustered task, so only the non-clustered schedulers are examined.
pub(crate) fn get_next_task_if(
pred: impl Fn(&Task) -> bool,
on_taken: impl FnOnce(Arc<Task>),
) -> bool {
let mut node = MCSNode::new();
let _guard = GLOBAL_WAKE_GET_MUTEX.lock(&mut node);
for scheduler_type in &PRIORITY_LIST[get_num_clustered_schedulers()..] {
match get_scheduler(scheduler_type).get_next_if(&pred) {
ConditionalNext::Empty => (),
ConditionalNext::Rejected => return false,
ConditionalNext::Taken(task) => {
on_taken(task);
return true;
}
}
}
false
}
/// The body of [`Scheduler::get_next_if`] for the schedulers whose run queue
/// is a [`PriorityQueue`]. `task_of` returns the task of a queue entry.
///
/// Finished tasks at the head of the queue are discarded as `get_next()`
/// does. The lock of the run queue must be held by the caller.
fn take_head_if<T>(
queue: &mut PriorityQueue<T>,
task_of: impl Fn(&T) -> &Arc<Task>,
pred: &dyn Fn(&Task) -> bool,
) -> ConditionalNext {
loop {
let Some(task) = queue.peek().map(|entry| task_of(entry).clone()) else {
return ConditionalNext::Empty;
};
let mut node = MCSNode::new();
let mut task_info = task.info.lock(&mut node);
if matches!(task_info.state, State::Terminated | State::Panicked) {
drop(task_info);
queue.pop();
NUM_TASK_IN_QUEUE.fetch_sub(1, Ordering::Relaxed);
continue;
}
if !pred(&task) {
return ConditionalNext::Rejected;
}
queue.pop();
NUM_TASK_IN_QUEUE.fetch_sub(1, Ordering::Relaxed);
if task_info.state == State::Preempted {
task_info.need_preemption = false;
}
drop(task_info);
return ConditionalNext::Taken(task);
}
}
/// Get a scheduler.
///
/// Takes `&SchedulerType` so the caller does not copy the full payload (the
/// embedded `CpuSet` makes `SchedulerType` large); only the discriminant is
/// matched.
pub(crate) fn get_scheduler(sched_type: &SchedulerType) -> &'static dyn Scheduler {
match sched_type {
SchedulerType::PrioritizedFIFO(_) => &prioritized_fifo::SCHEDULER,
SchedulerType::PrioritizedRR(_) => &prioritized_rr::SCHEDULER,
SchedulerType::EDF(_, _) => &edf::SCHEDULER,
SchedulerType::LLFT(_, _) => &llft::SCHEDULER,
SchedulerType::Panicked => &panicked::SCHEDULER,
}
}
pub const fn get_priority(sched_type: &SchedulerType) -> u8 {
let mut index = 0;
while index < PRIORITY_LIST.len() {
if PRIORITY_LIST[index].equals(sched_type) {
return (PRIORITY_LIST.len() - 1 - index) as u8;
}
index += 1;
}
panic!("Scheduler type not registered in PRIORITY_LIST or equals()")
}
/// RAII wrapper representing one slot in `NUM_CLUSTERED_TASKS_IN_QUEUE`.
///
/// Constructing a `ClusteredTask` increments the counter. The counter is
/// decremented exactly once — either via [`take`] (explicit ownership
/// transfer) or via `Drop` (e.g. when a terminated task is discarded). If
/// `take` has already been called, `Drop` is a no-op.
///
/// [`take`]: ClusteredTask::take
pub(crate) struct ClusteredTask<T> {
inner: Option<T>,
}
impl<T> ClusteredTask<T> {
pub(crate) fn new(inner: T) -> Self {
crate::task::NUM_CLUSTERED_TASKS_IN_QUEUE.fetch_add(1, Ordering::Relaxed);
Self { inner: Some(inner) }
}
/// Take the inner value and decrement the counter.
///
/// Returns `None` if the value has already been taken.
/// After this call `Drop` will be a no-op.
pub(crate) fn take(&mut self) -> Option<T> {
let val = self.inner.take();
if val.is_some() {
crate::task::NUM_CLUSTERED_TASKS_IN_QUEUE.fetch_sub(1, Ordering::Relaxed);
}
val
}
}
impl<T> Drop for ClusteredTask<T> {
fn drop(&mut self) {
// Decrement only if take() has not been called yet.
if self.inner.is_some() {
crate::task::NUM_CLUSTERED_TASKS_IN_QUEUE.fetch_sub(1, Ordering::Relaxed);
}
}
}
/// Maintain sleeping tasks by a delta list.
struct SleepingTasks {
delta_list: DeltaList<Box<dyn FnOnce() + Send>>,
base_time: Instant,
}
impl SleepingTasks {
const fn new() -> Self {
Self {
delta_list: DeltaList::Nil,
base_time: Instant::zero(),
}
}
/// `dur` is a Duration.
fn sleep_task(&mut self, handler: Box<dyn FnOnce() + Send>, mut dur: Duration) {
if self.delta_list.is_empty() {
self.base_time = Instant::now();
} else {
let diff = self.base_time.elapsed();
dur += diff;
}
self.delta_list.insert(dur.as_nanos() as u64, handler);
}
/// Sleep until `next` (no relative duration).
fn sleep_until_task(&mut self, handler: Box<dyn FnOnce() + Send>, next: Instant) {
if self.delta_list.is_empty() {
self.base_time = Instant::now();
}
let dur = next - self.base_time;
self.delta_list.insert(dur.as_nanos() as u64, handler);
}
/// Wake tasks up.
fn wake_task(&mut self) {
while let Some((dur, _)) = self.delta_list.front() {
let dur = Duration::from_nanos(dur);
let elapsed = self.base_time.elapsed();
if dur <= elapsed {
// Timed out.
if let DeltaList::Cons(data) = self.delta_list.pop().unwrap() {
let (_, handler, _) = data.into_inner();
handler(); // Invoke a handler.
self.base_time += dur;
}
} else {
break;
}
}
}
/// Get the duration of between the current time and the time of the head.
fn time_to_wait(&self) -> Option<Duration> {
let (dur, _) = self.delta_list.front()?;
let elapsed = self.base_time.elapsed().as_nanos() as u64;
if elapsed >= dur {
Some(Duration::from_nanos(0))
} else {
Some(Duration::from_nanos(dur - elapsed))
}
}
}
/// After `dur` time, `sleep_handler` will be invoked.
/// `dur` is microseconds.
pub(crate) fn sleep_task(sleep_handler: Box<dyn FnOnce() + Send>, dur: Duration) {
{
let mut node = MCSNode::new();
let mut guard = SLEEPING.lock(&mut node);
guard.sleep_task(sleep_handler, dur);
}
awkernel_lib::cpu::wake_cpu(0);
}
/// After reaching `next` time, `sleep_until_handler` will be invoked.
pub(crate) fn sleep_until_task(sleep_handler: Box<dyn FnOnce() + Send>, next: Instant) {
{
let mut node = MCSNode::new();
let mut guard = SLEEPING.lock(&mut node);
guard.sleep_until_task(sleep_handler, next);
}
awkernel_lib::cpu::wake_cpu(0);
}
/// Wake executable tasks up.
/// Waked tasks will be enqueued to their scheduler's queue.
///
/// This function should be called from only Awkernel.
/// So, do not call this from userland.
///
/// # Return Value
///
/// If there are sleeping tasks, this function returns the duration to wait.
/// If there are no sleeping tasks, this function returns `None`.
pub fn wake_task() -> Option<Duration> {
// Check whether each running task exceeds the time quantum.
let mut quantum_wait: Option<Duration> = None;
if PREEMPTION_ENABLED {
for cpu_id in 1..num_cpu() {
if let Some(task_id) = get_current_task(cpu_id) {
if let Some(SchedulerType::PrioritizedRR(_)) =
get_scheduler_type_by_task_id(task_id)
{
let wait = prioritized_rr::SCHEDULER.invoke_preemption_tick(cpu_id, task_id);
quantum_wait = match (quantum_wait, wait) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
}
}
}
}
let mut node = MCSNode::new();
let mut guard = SLEEPING.lock(&mut node);
guard.wake_task();
// A queued task may be waiting for a time quantum to expire. Nothing
// else wakes the primary CPU at that time, so do not sleep beyond it.
// If no task is queued, the next enqueue wakes the primary CPU.
//
// This is checked after `guard.wake_task()`: a sleep handler enqueues
// its task on this CPU, and `wake_cpu(0)` does nothing here, so such a
// task must be counted now.
if NUM_TASK_IN_QUEUE.load(Ordering::Relaxed) == 0 {
quantum_wait = None;
}
match (guard.time_to_wait(), quantum_wait) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}