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
// -*- coding: utf-8 -*-
//
// Copyright 2023-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
#[macro_export]
macro_rules! define_timeslice_sched {
(
name: $name:ident,
num_objs: $num_objs:literal,
tasks: {
$(
{
name: $taskname:ident,
period: $timebase:literal ms,
cpu: $core:literal,
stack: $stack_kib:literal kiB
}
),*
}
) => {
paste::paste! {
pub mod $name {
use std::{
sync::{
atomic::{
AtomicBool,
AtomicU32,
Ordering::{
Relaxed,
SeqCst,
},
fence,
},
Arc,
Condvar,
Mutex,
LazyLock,
},
thread,
time::Duration,
};
use $crate::meas::RuntimeMeas;
/// Time slice scheduler tasks.
pub trait Ops {
$(
/// Run the user code for this time base.
fn $taskname(&self) {
}
)*
}
/// Time slice scheduler handler trait object.
pub type OpsObject = Arc<dyn Ops + Send + Sync + 'static>;
/// Time slice scheduler.
#[doc(hidden)]
pub struct TimeSliceSched {
initialized: AtomicBool,
baseperiod: AtomicU32,
count: AtomicU32,
count_mod: AtomicU32,
$(
[<trigflag_ $taskname>]: Arc<(Mutex<bool>, Condvar)>,
)*
rt: RuntimeMeas,
}
/// Time slice scheduler instance.
#[doc(hidden)]
static TIMESLICESCHED: LazyLock<TimeSliceSched> = LazyLock::new(|| {
TimeSliceSched {
initialized: AtomicBool::new(false),
baseperiod: AtomicU32::new(0),
count: AtomicU32::new(0),
count_mod: AtomicU32::new(0),
$(
[<trigflag_ $taskname>]: Arc::new((Mutex::new(false),
Condvar::new())),
)*
rt: RuntimeMeas::new(),
}
});
/// Time slice scheduler instance.
#[doc(hidden)]
static TIMESLICESCHED_OS: LazyLock<Mutex<Option<$crate::hal::Timer<'static>>>>
= LazyLock::new(|| Mutex::new(None));
/// Time slice scheduler initialization.
#[inline]
pub fn init(objs: [OpsObject; $num_objs]) {
TimeSliceSched::init(objs);
}
/// Print the task and CPU runtime load.
pub fn rt_print() {
TIMESLICESCHED.rt.print_cpus();
$(
TIMESLICESCHED.rt.print_task(
std::stringify!($taskname),
$timebase,
$core
);
)*
}
#[inline]
pub fn rt_is_enabled() -> bool {
TIMESLICESCHED.rt.is_enabled()
}
#[inline]
pub fn rt_enable(enable: bool) {
TIMESLICESCHED.rt.enable(enable);
}
impl TimeSliceSched {
/// Initialize the time slice scheduler, once.
fn init(objs: [OpsObject; $num_objs]) {
assert!(!TIMESLICESCHED.initialized.swap(true, Relaxed));
let objs = Arc::new(objs);
// Calculate base period and counter modulo.
let mut min_timebase = u32::MAX;
let mut max_timebase = u32::MIN;
$(
min_timebase = min_timebase.min($timebase);
max_timebase = max_timebase.max($timebase);
)*
let baseperiod = min_timebase;
let count_mod = max_timebase / baseperiod;
// Spawn all handler threads.
$(
// Clone shared variable refs.
let [<thread_trigflag_ $taskname>] = Arc::clone(&TIMESLICESCHED.[<trigflag_ $taskname>]);
let [<thread_objs_ $taskname>] = Arc::clone(&objs);
let core: usize = $core;
let stack: usize = ($stack_kib) * 1024;
$crate::hal::task_spawn(
std::concat!(std::stringify!($name), "_cpu", $core, "\0"),
core,
stack,
move || {
assert_eq!($crate::hal::current_core(), core);
let (flag_mutex, trig_condvar) = &*[<thread_trigflag_ $taskname>];
loop {
// Wait for the thread flag to be set.
{
let mut flag = flag_mutex.lock().unwrap();
while !*flag {
flag = trig_condvar.wait(flag).unwrap();
}
*flag = false;
}
let begin = TIMESLICESCHED.rt.meas_begin();
// Execute all handlers for this task.
for obj in &*[<thread_objs_ $taskname>] {
obj.$taskname();
}
TIMESLICESCHED.rt.meas_end(std::stringify!($taskname), $core, begin);
}
}
);
)*
TIMESLICESCHED.baseperiod.store(baseperiod, Relaxed);
TIMESLICESCHED.count.store(0, Relaxed);
TIMESLICESCHED.count_mod.store(count_mod, Relaxed);
fence(SeqCst);
*TIMESLICESCHED_OS.lock().unwrap() = Some($crate::hal::Timer::new(
|| TIMESLICESCHED.base_tick_handler(),
Duration::from_millis(baseperiod as u64)
));
}
/// Base timer tick handler.
fn base_tick_handler(&self) {
let baseperiod = self.baseperiod.load(Relaxed);
let count = self.count.load(Relaxed);
$(
if count % ($timebase / baseperiod) == 0 {
let ([<flag_ $taskname>], [<trig_ $taskname>]) = &*self.[<trigflag_ $taskname>];
*[<flag_ $taskname>].lock().unwrap() = true;
[<trig_ $taskname>].notify_one();
}
)*
let count_mod = self.count_mod.load(Relaxed);
let count = (count + 1) % count_mod;
self.count.store(count, Relaxed);
}
}
}
}
}
}
// vim: ts=4 sw=4 expandtab