Repository navigation
Expand file tree
/
Copy pathtask.rs
More file actions
1789 lines (1533 loc) · 59.2 KB
/
Copy pathtask.rs
File metadata and controls
1789 lines (1533 loc) · 59.2 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Task structure and functions.
//!
//! - `Task` represents a task. This is handled as `Arc<Task>`.
//! - `Task::wake()` and `Task::wake_by_ref()` call `Task::scheduler::wake_task()` to wake the task up.
//! - `Task::info`, which type is `TaskInfo`, contains information of the task.
//! - `TaskInfo` represents information of task.
//! - `Tasks` is a set of tasks.
#[cfg(not(feature = "no_preempt"))]
mod preempt;
use crate::scheduler::{self, get_scheduler, pop_preemption_pending, Scheduler, SchedulerType};
use alloc::{
borrow::Cow,
collections::{btree_map, BTreeMap},
sync::Arc,
};
use array_macro::array;
use awkernel_lib::{
cpu::{all_workers, masked_workers, num_cpu, CpuSet, NUM_MAX_CPU},
priority_queue::HIGHEST_PRIORITY,
sync::mutex::{MCSNode, Mutex},
unwind::catch_unwind,
};
#[cfg(target_pointer_width = "64")]
use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
#[cfg(target_pointer_width = "32")]
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use core::task::{Context, Poll};
use futures::{
future::{BoxFuture, Fuse, FusedFuture},
task::{waker_ref, ArcWake},
Future, FutureExt,
};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(not(feature = "no_preempt"))]
pub use preempt::{preemption, thread::deallocate_thread_pool, voluntary_preemption};
#[cfg(not(feature = "no_preempt"))]
use preempt::thread::PtrWorkerThreadContext;
/// Return type of futures taken by `awkernel_async_lib::task::spawn`.
pub type TaskResult = Result<(), Cow<'static, str>>;
static TASKS: Mutex<Tasks> = Mutex::new(Tasks::new()); // Set of tasks.
static RUNNING: [AtomicU32; NUM_MAX_CPU] = array![_ => AtomicU32::new(0); NUM_MAX_CPU]; // IDs of running tasks.
pub(crate) static MAX_TASK_PRIORITY: u64 = (1 << 56) - 1; // Maximum task priority.
/// Total number of tasks in the queues of the non-clustered schedulers.
/// Each of these schedulers increments it when it pushes a task to its queue
/// and decrements it when it pops one, so it counts every path that calls
/// `wake_task`, including the re-wakes that bypass `ArcWake::wake`.
pub(crate) static NUM_TASK_IN_QUEUE: AtomicU32 = AtomicU32::new(0);
/// Total number of tasks in the clustered schedulers' queues.
/// Which CPUs those tasks are runnable on is tracked exactly by the run
/// queues themselves; see `scheduler::clustered_queued_cpu_mask`.
pub(crate) static NUM_CLUSTERED_TASKS_IN_QUEUE: AtomicU32 = AtomicU32::new(0);
static PREEMPTION_REQUEST: [AtomicBool; NUM_MAX_CPU] =
array![_ => AtomicBool::new(false); NUM_MAX_CPU];
/// Per-CPU record of the idle-time frequency request. See `is_idle_min_freq_requested()`.
#[cfg(feature = "dvfs")]
static IDLE_MIN_FREQ_REQUESTED: [AtomicBool; NUM_MAX_CPU] =
array![_ => AtomicBool::new(false); NUM_MAX_CPU];
/// Task has ID, future, information, and a reference to a scheduler.
pub struct Task {
pub id: u32,
pub name: Cow<'static, str>,
future: Mutex<Fuse<BoxFuture<'static, TaskResult>>>,
pub info: Mutex<TaskInfo>,
scheduler: &'static dyn Scheduler,
pub priority: PriorityInfo,
pub cpu_set: Option<CpuSet>, // The set of cores on which the task may run in clustered scheduling. None if not assigned.
}
impl Task {
#[inline(always)]
pub fn scheduler_name(&self) -> SchedulerType {
self.scheduler.scheduler_name()
}
/// True if `self` must preempt `other`, i.e. `self` has a strictly higher
/// priority (scheduler priority, then task priority; see `PriorityInfo`).
///
/// Equal priorities never preempt. Within a priority level the schedulers
/// are FIFO (PrioritizedFIFO, EDF on equal deadlines) or
/// rotate by their own time quantum (PrioritizedRR), so a task woken while
/// an equal-priority task is running waits in the run queue instead of
/// displacing it.
///
/// The one exception is the PrioritizedRR time quantum:
/// `PrioritizedRRScheduler::invoke_preemption_tick` pushes the next
/// runnable task to the preemption-pending heap if its priority is at
/// least that of the running task, and `preempt::do_preemption` lets such
/// an equal-priority pending task preempt a running PrioritizedRR task so
/// that the quantum rotates tasks of the same priority.
///
/// This is deliberately not `self > other`: [`Ord`] for `Task` breaks
/// priority ties by task ID to give the preemption-pending heaps a total
/// order, and that tie-break must not decide whether a running task is
/// preempted.
#[inline(always)]
pub(crate) fn preempts(&self, other: &Self) -> bool {
self.priority > other.priority
}
}
impl PartialEq for Task {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Task {}
impl PartialOrd for Task {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Task {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
// Higher (larger) priority is greater.
match self.priority.cmp(&other.priority) {
core::cmp::Ordering::Equal => self.id.cmp(&other.id),
ord => ord,
}
}
}
unsafe impl Sync for Task {}
unsafe impl Send for Task {}
impl ArcWake for Task {
fn wake_by_ref(arc_self: &Arc<Self>) {
let cloned = arc_self.clone();
cloned.wake();
}
fn wake(self: Arc<Self>) {
let panicked;
{
use State::*;
let mut node = MCSNode::new();
let mut info = self.info.lock(&mut node);
match info.state {
Running | Runnable | Preempted => {
info.need_sched = true;
return;
}
Terminated | Panicked => {
return;
}
Initialized | Waiting => {
info.state = Runnable;
}
}
panicked = info.panicked;
}
if panicked {
scheduler::panicked::SCHEDULER.wake_task(self);
} else {
self.scheduler.wake_task(self);
}
}
}
/// Information of task.
pub struct TaskInfo {
pub(crate) state: State,
pub(crate) scheduler_type: SchedulerType,
pub(crate) num_preempt: u64,
last_executed_time: awkernel_lib::time::Instant,
absolute_deadline: Option<u64>,
need_sched: bool,
pub(crate) need_preemption: bool,
panicked: bool,
pub(crate) dag_info: Option<DagInfo>,
#[cfg(feature = "dvfs")]
freq: Option<u64>,
#[cfg(not(feature = "no_preempt"))]
thread: Option<PtrWorkerThreadContext>,
}
impl TaskInfo {
#[cfg(not(feature = "no_preempt"))]
#[inline(always)]
pub(crate) fn take_preempt_context(&mut self) -> Option<PtrWorkerThreadContext> {
self.thread.take()
}
#[cfg(not(feature = "no_preempt"))]
#[inline(always)]
pub(crate) fn set_preempt_context(&mut self, ctx: PtrWorkerThreadContext) {
assert!(self.thread.is_none());
self.thread = Some(ctx)
}
#[inline(always)]
pub fn get_state(&self) -> State {
self.state
}
#[inline(always)]
pub fn get_scheduler_type(&self) -> SchedulerType {
if self.panicked {
SchedulerType::Panicked
} else {
self.scheduler_type
}
}
#[inline(always)]
pub fn update_last_executed(&mut self) {
self.last_executed_time = awkernel_lib::time::Instant::now();
}
#[inline(always)]
pub fn get_last_executed(&self) -> awkernel_lib::time::Instant {
self.last_executed_time
}
#[inline(always)]
pub fn update_absolute_deadline(&mut self, deadline: u64) {
self.absolute_deadline = Some(deadline);
}
#[inline(always)]
pub fn get_absolute_deadline(&self) -> Option<u64> {
self.absolute_deadline
}
#[inline(always)]
pub fn get_num_preemption(&self) -> u64 {
self.num_preempt
}
#[inline(always)]
pub fn panicked(&self) -> bool {
self.panicked
}
#[inline(always)]
#[cfg(feature = "dvfs")]
pub fn update_freq(&mut self, freq: u64) {
self.freq = Some(freq);
}
#[inline(always)]
#[cfg(feature = "dvfs")]
pub fn get_freq(&self) -> Option<u64> {
self.freq
}
}
/// State of task.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Initialized,
Running,
Runnable,
Waiting,
Preempted,
Terminated,
Panicked,
}
/// Tasks.
#[derive(Default)]
struct Tasks {
candidate_id: u32, // Next candidate of task ID.
id_to_task: BTreeMap<u32, Arc<Task>>,
}
#[derive(Clone)]
pub struct DagInfo {
pub dag_id: u32,
pub node_id: u32,
}
impl Tasks {
const fn new() -> Self {
Self {
candidate_id: 1,
id_to_task: BTreeMap::new(),
}
}
fn spawn(
&mut self,
name: Cow<'static, str>,
future: Fuse<BoxFuture<'static, TaskResult>>,
scheduler: &'static dyn Scheduler,
mut scheduler_type: SchedulerType,
dag_info: Option<DagInfo>,
#[cfg(feature = "dvfs")] freq: Option<u64>,
) -> u32 {
let mut id = self.candidate_id;
loop {
if id == 0 {
id += 1;
}
// Find an unused task ID.
if let btree_map::Entry::Vacant(e) = self.id_to_task.entry(id) {
// Validate and normalise the CPU set before creating TaskInfo so that
// info.scheduler_type and task.cpu_set stay in sync.
let cpu_set = if let Some(set) = scheduler_type.cpu_set() {
// CPU 0 is the primary core and cannot run clustered tasks.
let masked = masked_workers(set, num_cpu());
let normalized = if masked.is_empty() {
// `cpu::sanity_check()` guarantees num_cpu() >= 2 at boot,
// so `all_workers(num_cpu())` below is always non-empty.
log::warn!(
"The CPU set must contain at least one core between 1 and {}. Falling back to all worker cores. Given set: {:?}",
num_cpu() - 1,
set
);
all_workers(num_cpu())
} else {
masked
};
scheduler_type = match scheduler_type {
SchedulerType::EDF(deadline, _) => SchedulerType::EDF(deadline, normalized),
SchedulerType::LLFT(deadline, _) => {
SchedulerType::LLFT(deadline, normalized)
}
other => other,
};
Some(normalized)
} else {
None
};
let info = Mutex::new(TaskInfo {
scheduler_type,
state: State::Initialized,
num_preempt: 0,
last_executed_time: awkernel_lib::time::Instant::now(),
absolute_deadline: None,
need_sched: false,
need_preemption: false,
panicked: false,
dag_info,
#[cfg(feature = "dvfs")]
freq,
#[cfg(not(feature = "no_preempt"))]
thread: None,
});
// Set the task priority.
// If the scheduler implements dynamic priority scheduling, the task priority will be updated later.
let task_priority = match scheduler_type {
SchedulerType::PrioritizedFIFO(priority)
| SchedulerType::PrioritizedRR(priority) => priority as u64,
_ => MAX_TASK_PRIORITY,
};
let task = Task {
name,
future: Mutex::new(future),
scheduler,
id,
info,
priority: PriorityInfo::new(scheduler.priority(), task_priority),
cpu_set,
};
e.insert(Arc::new(task));
self.candidate_id = id;
return id;
} else {
// The candidate task ID is already used.
// Check next candidate.
id += 1;
}
}
}
#[inline(always)]
fn wake(&self, id: u32) {
if let Some(task) = self.id_to_task.get(&id) {
task.clone().wake();
}
}
#[inline(always)]
fn remove(&mut self, id: u32) {
self.id_to_task.remove(&id);
}
}
/// Spawn a detached task.
/// If you want to spawn tasks in non async functions,
/// use this function.
/// This function takes only futures that return `TaskResult`.
///
/// Use `awkernel_async_lib::spawn` in async functions instead of this.
/// `awkernel_async_lib::spawn` can take any future and joinable.
///
/// # Example
///
/// ```
/// use awkernel_async_lib::{scheduler::SchedulerType, task};
/// let task_id = task::spawn("example task".into(), async { Ok(()) }, SchedulerType::PrioritizedFIFO(0));
/// ```
pub fn spawn(
name: Cow<'static, str>,
future: impl Future<Output = TaskResult> + 'static + Send,
sched_type: SchedulerType,
) -> u32 {
inner_spawn(
name,
future,
sched_type,
None,
#[cfg(feature = "dvfs")]
None,
)
}
/// Spawn a detached task with DAG information.
/// This function is similar to `spawn` but automatically sets DAG information
/// for the task, which is useful for DAG-based schedulers like EDF.
///
/// # Example
///
/// ```ignore
/// use awkernel_async_lib::{scheduler::SchedulerType, task, dag::{create_dag, add_node_with_topic_edges_public, set_relative_deadline_public}};
/// use awkernel_lib::cpu::CpuSet;
/// use core::time::Duration;
/// let dag = create_dag();
/// let sink_node_idx = add_node_with_topic_edges_public(&dag, &[], &[]);
/// let deadline = Duration::from_millis(100);
/// set_relative_deadline_public(&dag, sink_node_idx, deadline);
/// let task_id = task::spawn_with_dag_info(
/// "dag task".into(),
/// async { Ok(()) },
/// SchedulerType::EDF(0, CpuSet::all()),
/// DagInfo { dag_id: 1, node_id: 0 }
/// );
/// ```
pub fn spawn_with_dag_info(
name: Cow<'static, str>,
future: impl Future<Output = TaskResult> + 'static + Send,
sched_type: SchedulerType,
dag_info: DagInfo,
) -> u32 {
inner_spawn(
name,
future,
sched_type,
Some(dag_info),
#[cfg(feature = "dvfs")]
None,
)
}
#[cfg(feature = "dvfs")]
pub fn spawn_with_freq(
name: Cow<'static, str>,
future: impl Future<Output = TaskResult> + 'static + Send,
sched_type: SchedulerType,
freq: u64,
) -> u32 {
inner_spawn(name, future, sched_type, None, Some(freq))
}
pub fn inner_spawn(
name: Cow<'static, str>,
future: impl Future<Output = TaskResult> + 'static + Send,
sched_type: SchedulerType,
dag_info: Option<DagInfo>,
#[cfg(feature = "dvfs")] freq: Option<u64>,
) -> u32 {
if let SchedulerType::PrioritizedFIFO(p) | SchedulerType::PrioritizedRR(p) = sched_type {
if p > HIGHEST_PRIORITY {
log::warn!(
"Task priority should be between 0 and {HIGHEST_PRIORITY}. It is addressed as {HIGHEST_PRIORITY}."
);
}
}
let future = future.boxed();
let scheduler = get_scheduler(&sched_type);
let mut node = MCSNode::new();
let mut tasks = TASKS.lock(&mut node);
let id = tasks.spawn(
name,
future.fuse(),
scheduler,
sched_type,
dag_info,
#[cfg(feature = "dvfs")]
freq,
);
let task = tasks.id_to_task.get(&id).cloned();
drop(tasks);
if let Some(task) = task {
task.wake();
}
id
}
/// Get the task ID currently running.
///
/// # Example
///
/// ```
/// if let Some(task_id) = awkernel_async_lib::task::get_current_task(1) { }
/// ```
#[inline(always)]
pub fn get_current_task(cpu_id: usize) -> Option<u32> {
let id = RUNNING[cpu_id].load(Ordering::Relaxed);
if id == 0 {
None
} else {
Some(id)
}
}
#[inline(always)]
pub fn set_current_task(cpu_id: usize, task_id: u32) {
RUNNING[cpu_id].store(task_id, Ordering::Relaxed);
}
#[inline(always)]
fn get_next_task() -> Option<Arc<Task>> {
#[cfg(not(feature = "no_preempt"))]
{
if let Some(next) = preempt::get_next_task() {
// `do_preemption` has already marked this task as running.
set_current_task(awkernel_lib::cpu::cpu_id(), next.id);
return Some(next);
}
}
scheduler::get_next_task()
}
#[cfg(feature = "perf")]
pub mod perf {
//! Per-CPU time accounting by a state machine.
//!
//! Measurement definitions (agreed 2026-07-18):
//! - `ContextSwitch` / `ContextSwitchMain` measure **only the exchange
//! itself** (from just before `context_switch()` on the yielding side to
//! the first hook after it returns on the resumed side). `ContextSwitch`
//! is the preemption route (`yield_preempted_and_wake_task`);
//! `ContextSwitchMain` is the queued-resume route (`yield_and_pool`).
//! The two are symmetric and directly comparable.
//! - Preemption *decision* work (`do_preemption` bookkeeping) is covered
//! by `Interrupt` on the IPI route (`start_interrupt` already brackets
//! the handler) and leaks into `Task` on the voluntary-checkpoint route
//! (known, small). Dispatch bookkeeping in `run_main` stays in `Kernel`.
//! - Switch aftermath on the resumed side (`set_current_context`,
//! `re_schedule`) is accounted to `Kernel`; `Task` starts only when the
//! resumed task returns to its own code, keeping per-task execution
//! times (measured WCET inputs) clean.
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use awkernel_lib::cpu::NUM_MAX_CPU;
use core::ptr::{read_volatile, write_volatile};
use core::sync::atomic::AtomicU32;
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(u8)]
pub enum PerfState {
Boot = 0,
Kernel,
Task,
ContextSwitch,
ContextSwitchMain,
Interrupt,
Idle,
}
impl From<u8> for PerfState {
fn from(value: u8) -> Self {
match value {
0 => Self::Boot,
1 => Self::Kernel,
2 => Self::Task,
3 => Self::ContextSwitch,
4 => Self::ContextSwitchMain,
5 => Self::Interrupt,
6 => Self::Idle,
_ => panic!("From<u8> for PerfState::from: invalid value"),
}
}
}
static mut PERF_STATES: [u8; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut START_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut KERNEL_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut TASK_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut INTERRUPT_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_MAIN_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut IDLE_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut PERF_TIME: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut KERNEL_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut TASK_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut INTERRUPT_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_MAIN_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut IDLE_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut PERF_WCET: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut KERNEL_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut TASK_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut INTERRUPT_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut CONTEXT_SWITCH_MAIN_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut IDLE_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
static mut PERF_COUNT: [u64; NUM_MAX_CPU] = [0; NUM_MAX_CPU];
use alloc::{collections::BTreeMap, vec::Vec};
use awkernel_lib::sync::{mcs::MCSNode, mutex::Mutex};
// NOTE: When logging evaluation results, this value can be adjusted based on awkernel's execution time.
// This value matches the one actually used in the awkernel evaluation branch, and it is a ring buffer.
const MAX_LOGS: usize = 2048;
type DagTimestampMap = BTreeMap<u32, u64>;
type DagTimestampTable = [DagTimestampMap; MAX_LOGS];
static SEND_OUTER_TIMESTAMP: Mutex<Option<Box<DagTimestampTable>>> = Mutex::new(None);
static RECV_OUTER_TIMESTAMP: Mutex<Option<Box<DagTimestampTable>>> = Mutex::new(None);
static ABSOLUTE_DEADLINE: Mutex<Option<Box<DagTimestampTable>>> = Mutex::new(None);
static RELATIVE_DEADLINE: Mutex<Option<Box<DagTimestampTable>>> = Mutex::new(None);
pub static PERIOD_INDEX: Mutex<BTreeMap<u32, AtomicU32>> = Mutex::new(BTreeMap::new());
pub fn get_period_index(dag_id: u32) -> u32 {
let mut node = MCSNode::new();
let period_count = PERIOD_INDEX.lock(&mut node);
period_count
.get(&dag_id)
.map(|count| count.load(core::sync::atomic::Ordering::Relaxed))
.unwrap_or(0)
}
pub fn increment_period_index(dag_id: u32) -> u32 {
let mut node = MCSNode::new();
let mut period_count = PERIOD_INDEX.lock(&mut node);
let count = period_count
.entry(dag_id)
.or_insert_with(|| AtomicU32::new(0));
count.fetch_add(1, core::sync::atomic::Ordering::Relaxed) + 1
}
// This value represents the type of pubsub (publish only, subscribe only, or both publish and subscribe)
// and is a fixed value.
const MAX_PUBSUB: usize = 3;
// This value indicates the maximum number of nodes in the DAG
// and can be adjusted based on the structure of the DAG used for evaluation.
const MAX_NODES: usize = 5;
#[derive(Clone)]
struct PubSubTable {
timestamps: [[[u64; MAX_NODES]; MAX_PUBSUB]; MAX_LOGS],
used_indices: Vec<usize>,
}
impl Default for PubSubTable {
fn default() -> Self {
Self {
timestamps: [[[0; MAX_NODES]; MAX_PUBSUB]; MAX_LOGS],
used_indices: Vec::new(),
}
}
}
impl PubSubTable {
#[inline(always)]
fn flat_index(index: usize, pub_id: usize, node_id: usize) -> usize {
(index * MAX_PUBSUB * MAX_NODES) + (pub_id * MAX_NODES) + node_id
}
#[inline(always)]
fn decode_flat_index(flat_index: usize) -> (usize, usize, usize) {
let per_log = MAX_PUBSUB * MAX_NODES;
let index = flat_index / per_log;
let rem = flat_index % per_log;
let pub_id = rem / MAX_NODES;
let node_id = rem % MAX_NODES;
(index, pub_id, node_id)
}
#[inline(always)]
fn mark_used(&mut self, index: usize, pub_id: usize, node_id: usize) {
self.used_indices
.push(Self::flat_index(index, pub_id, node_id));
}
}
static PUBLISH: Mutex<Option<Box<PubSubTable>>> = Mutex::new(None);
static SUBSCRIBE: Mutex<Option<Box<PubSubTable>>> = Mutex::new(None);
#[inline(always)]
fn to_ring_buffer_index(period_index: usize) -> usize {
period_index % MAX_LOGS
}
pub fn update_cycle_start_timestamp(period_index: usize, new_timestamp: u64, dag_id: u32) {
let log_index = to_ring_buffer_index(period_index);
let mut node = MCSNode::new();
let mut recorder_opt = SEND_OUTER_TIMESTAMP.lock(&mut node);
let recorder =
recorder_opt.get_or_insert_with(|| Box::new(core::array::from_fn(|_| BTreeMap::new())));
recorder[log_index].entry(dag_id).or_insert(new_timestamp);
}
pub fn update_cycle_end_timestamp(period_index: usize, new_timestamp: u64, dag_id: u32) {
let log_index = to_ring_buffer_index(period_index);
let mut node = MCSNode::new();
let mut recorder_opt = RECV_OUTER_TIMESTAMP.lock(&mut node);
let recorder =
recorder_opt.get_or_insert_with(|| Box::new(core::array::from_fn(|_| BTreeMap::new())));
recorder[log_index].insert(dag_id, new_timestamp);
}
pub fn update_absolute_deadline_timestamp(period_index: usize, deadline: u64, dag_id: u32) {
let log_index = to_ring_buffer_index(period_index);
let mut node = MCSNode::new();
let mut recorder_opt = ABSOLUTE_DEADLINE.lock(&mut node);
let recorder =
recorder_opt.get_or_insert_with(|| Box::new(core::array::from_fn(|_| BTreeMap::new())));
recorder[log_index].entry(dag_id).or_insert(deadline);
}
pub fn update_relative_deadline_timestamp(period_index: usize, deadline: u64, dag_id: u32) {
let log_index = to_ring_buffer_index(period_index);
let mut node = MCSNode::new();
let mut recorder_opt = RELATIVE_DEADLINE.lock(&mut node);
let recorder =
recorder_opt.get_or_insert_with(|| Box::new(core::array::from_fn(|_| BTreeMap::new())));
recorder[log_index].entry(dag_id).or_insert(deadline);
}
pub fn record_publish_timestamp(
period_index: usize,
new_timestamp: u64,
pub_id: u32,
node_id: u32,
) {
let log_index = to_ring_buffer_index(period_index);
if (pub_id as usize) >= MAX_PUBSUB {
log::warn!(
"Publish ID out of bounds: {} (max {})",
pub_id as usize,
MAX_PUBSUB
);
return;
}
let node_id_usize = node_id as usize;
if node_id_usize >= MAX_NODES {
log::warn!(
"Publish node ID out of bounds: {} (max {})",
node_id_usize,
MAX_NODES
);
return;
}
let mut node = MCSNode::new();
let mut recorder_opt = PUBLISH.lock(&mut node);
let recorder = recorder_opt.get_or_insert_with(|| Box::new(PubSubTable::default()));
let pub_id = pub_id as usize;
if recorder.timestamps[log_index][pub_id][node_id_usize] == 0 {
recorder.timestamps[log_index][pub_id][node_id_usize] = new_timestamp;
recorder.mark_used(log_index, pub_id, node_id_usize);
}
}
pub fn record_subscribe_timestamp(
period_index: usize,
new_timestamp: u64,
sub_id: u32,
node_id: u32,
) {
let log_index = to_ring_buffer_index(period_index);
if (sub_id as usize) >= MAX_PUBSUB {
log::warn!(
"Subscribe ID out of bounds: {} (max {})",
sub_id as usize,
MAX_PUBSUB
);
return;
}
let node_id_usize = node_id as usize;
if node_id_usize >= MAX_NODES {
log::warn!(
"Subscribe node ID out of bounds: {} (max {})",
node_id_usize,
MAX_NODES
);
return;
}
let mut node = MCSNode::new();
let mut recorder_opt = SUBSCRIBE.lock(&mut node);
let recorder = recorder_opt.get_or_insert_with(|| Box::new(PubSubTable::default()));
let sub_id = sub_id as usize;
if recorder.timestamps[log_index][sub_id][node_id_usize] == 0 {
recorder.timestamps[log_index][sub_id][node_id_usize] = new_timestamp;
recorder.mark_used(log_index, sub_id, node_id_usize);
}
}
// For precision of the cycle
pub fn print_timestamp_table() {
let mut node1 = MCSNode::new();
let mut node2 = MCSNode::new();
let mut node3 = MCSNode::new();
let mut node4 = MCSNode::new();
const MAX_ROWS_TO_PRINT: usize = 256;
let send_outer_opt = SEND_OUTER_TIMESTAMP.lock(&mut node1);
let recv_outer_opt = RECV_OUTER_TIMESTAMP.lock(&mut node2);
let absolute_deadline_opt = ABSOLUTE_DEADLINE.lock(&mut node3);
let relative_deadline_opt = RELATIVE_DEADLINE.lock(&mut node4);
let mut rows = Vec::new();
let mut truncated = false;
'collect_rows: for i in 0..MAX_LOGS {
let mut dag_ids = Vec::new();
if let Some(arr) = &*send_outer_opt {
dag_ids.extend(arr[i].keys().copied());
}
if let Some(arr) = &*recv_outer_opt {
dag_ids.extend(arr[i].keys().copied());
}
if let Some(arr) = &*absolute_deadline_opt {
dag_ids.extend(arr[i].keys().copied());
}
if let Some(arr) = &*relative_deadline_opt {
dag_ids.extend(arr[i].keys().copied());
}
dag_ids.sort_unstable();
dag_ids.dedup();
for dag_id in dag_ids {
let pre_send_outer = match &*send_outer_opt {
Some(arr) => arr[i].get(&dag_id).copied().unwrap_or(0),
None => 0,
};
let fin_recv_outer = match &*recv_outer_opt {
Some(arr) => arr[i].get(&dag_id).copied().unwrap_or(0),
None => 0,
};
let absolute_deadline = match &*absolute_deadline_opt {
Some(arr) => arr[i].get(&dag_id).copied().unwrap_or(0),
None => 0,
};
let relative_deadline = match &*relative_deadline_opt {
Some(arr) => arr[i].get(&dag_id).copied().unwrap_or(0),
None => 0,
};
if pre_send_outer != 0
|| fin_recv_outer != 0
|| absolute_deadline != 0
|| relative_deadline != 0
{
if rows.len() >= MAX_ROWS_TO_PRINT {
truncated = true;
break 'collect_rows;
}
rows.push((
i,
dag_id,
pre_send_outer,
fin_recv_outer,
absolute_deadline,
relative_deadline,
));
}
}
}
drop(relative_deadline_opt);
drop(absolute_deadline_opt);
drop(recv_outer_opt);
drop(send_outer_opt);
log::info!("--- Timestamp Summary (in nanoseconds) ---");
log::info!(
"{: ^5} | {: ^5} | {: ^14} | {: ^14} | {: ^14} | {: ^14} | {: ^14}",
"Index",
"DAG-ID",
"Send-Outer",
"Recv-Outer",
"Latency",
"Absolute Deadline",
"Relative Deadline"
);
log::info!("-----|--------|----------------|----------------|----------------|--------------------|--------------------");
for (i, dag_id, pre_send_outer, fin_recv_outer, absolute_deadline, relative_deadline) in
rows
{
let format_ts = |ts: u64| -> String {
if ts == 0 {
"-".to_string()
} else {
ts.to_string()
}
};
let latency_str = if pre_send_outer != 0 && fin_recv_outer != 0 {
fin_recv_outer.saturating_sub(pre_send_outer).to_string()
} else {
"-".to_string()
};
log::info!(
"{: >5} | {: >5} | {: >14} | {: >14} | {: >14} | {: >20} | {: >20}",
i,
format_ts(dag_id as u64),
format_ts(pre_send_outer),
format_ts(fin_recv_outer),
latency_str,
format_ts(absolute_deadline),
format_ts(relative_deadline),
);
}
if truncated {
log::warn!(
"Timestamp Summary truncated to {} rows; call print_timestamp_table() again to continue inspection",
MAX_ROWS_TO_PRINT
);
}
log::info!("----------------------------------------------------------");
}
// For pubsub communication latency
pub fn print_pubsub_table() {
let mut node1 = MCSNode::new();
let mut node2 = MCSNode::new();
let publish_opt = PUBLISH.lock(&mut node1);
let subscribe_opt = SUBSCRIBE.lock(&mut node2);
let mut indices = Vec::new();
if let Some(publish) = publish_opt.as_ref() {
indices.extend_from_slice(&publish.used_indices);
}
if let Some(subscribe) = subscribe_opt.as_ref() {
indices.extend_from_slice(&subscribe.used_indices);
}
indices.sort_unstable();
indices.dedup();
log::info!("--- Pub/Sub Timestamp Summary (in nanoseconds) ---");
log::info!(