Repository navigation
Expand file tree
/
Copy pathpreempt.rs
More file actions
389 lines (311 loc) · 12.8 KB
/
Copy pathpreempt.rs
File metadata and controls
389 lines (311 loc) · 12.8 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
use crate::{
scheduler::{
move_preemption_pending, peek_preemption_pending, remove_preemption_pending, SchedulerType,
},
task::{get_current_task, get_task, set_current_task, Task},
};
use alloc::{collections::VecDeque, sync::Arc};
use array_macro::array;
use awkernel_lib::{
context::context_switch,
cpu::NUM_MAX_CPU,
interrupt::{self, InterruptGuard},
sync::mutex::{MCSNode, Mutex},
unwind::catch_unwind,
};
use core::sync::atomic::{AtomicUsize, Ordering};
use thread::PtrWorkerThreadContext;
pub mod thread;
/// Threads to be moved to THREADS::pooled.
static THREAD_POOL: [Mutex<VecDeque<PtrWorkerThreadContext>>; NUM_MAX_CPU] =
array![_ => Mutex::new(VecDeque::new()); NUM_MAX_CPU];
/// Tasks to be rescheduled.
static PREEMPTED_TASKS: [Mutex<VecDeque<Arc<Task>>>; NUM_MAX_CPU] =
array![_ => Mutex::new(VecDeque::new()); NUM_MAX_CPU];
/// Tasks to be executed next.
static NEXT_TASK: [Mutex<VecDeque<Arc<Task>>>; NUM_MAX_CPU] =
array![_ => Mutex::new(VecDeque::new()); NUM_MAX_CPU];
static NUM_PREEMPTION: AtomicUsize = AtomicUsize::new(0);
/// The current thread yields to `next_ctx`, and the current thread will be pooled.
pub unsafe fn yield_and_pool(next_ctx: PtrWorkerThreadContext) {
let mut current_ctx = thread::take_current_context();
push_to_thread_pool(current_ctx.clone());
let current_cpu_ctx = current_ctx.get_cpu_context_mut();
let next_cpu_ctx = next_ctx.get_cpu_context();
unsafe { context_switch(current_cpu_ctx, next_cpu_ctx) };
// [resume] This (previously pooled) worker thread was switched to. Close
// the exchange sample here; set_current_context() and re_schedule() below
// are accounted to Kernel.
#[cfg(feature = "perf")]
super::perf::start_kernel();
thread::set_current_context(current_ctx);
re_schedule();
}
/// The thread of `current_task` yields to `next_thread`.
/// The current thread will be preempted, and waked soon.
fn yield_preempted_and_wake_task(current_task: Arc<Task>, next_thread: PtrWorkerThreadContext) {
let cpu_id = awkernel_lib::cpu::cpu_id();
let mut current_ctx = thread::take_current_context();
{
let mut node = MCSNode::new();
let mut info = current_task.info.lock(&mut node);
info.set_preempt_context(current_ctx.clone());
info.state = super::State::Preempted;
info.num_preempt += 1;
}
{
let mut node = MCSNode::new();
let mut tasks = PREEMPTED_TASKS[cpu_id].lock(&mut node);
tasks.push_front(current_task);
}
NUM_PREEMPTION.fetch_add(1, Ordering::Relaxed);
let current_cpu_ctx = current_ctx.get_cpu_context_mut();
let next_cpu_ctx = next_thread.get_cpu_context();
unsafe {
// Save the current context.
context_switch(current_cpu_ctx, next_cpu_ctx);
// [resume] This task was switched to (possibly on a different CPU).
// Close the exchange sample (ContextSwitch or ContextSwitchMain) here;
// set_current_context() and re_schedule() below are switch aftermath,
// accounted to Kernel, not to this task.
#[cfg(feature = "perf")]
super::perf::start_kernel();
thread::set_current_context(current_ctx);
}
re_schedule();
// The switch aftermath is done; from here on this task runs its own code.
#[cfg(feature = "perf")]
super::perf::start_task();
}
fn re_schedule() {
let cpu_id = awkernel_lib::cpu::cpu_id();
{
let mut node = MCSNode::new();
let mut tasks = PREEMPTED_TASKS[cpu_id].lock(&mut node);
while let Some(task) = tasks.pop_front() {
task.scheduler.wake_task(task);
}
}
{
let mut node = MCSNode::new();
let mut pool = THREAD_POOL[cpu_id].lock(&mut node);
while let Some(thread) = pool.pop_front() {
thread::make_thread_pooled(thread);
}
}
}
/// Initialization for worker threads executed first.
pub fn init() {
let ctx = PtrWorkerThreadContext::new();
thread::set_current_context(ctx);
}
fn push_to_thread_pool(ctx: PtrWorkerThreadContext) {
let cpu_id = awkernel_lib::cpu::cpu_id();
let mut node = MCSNode::new();
let mut pool = THREAD_POOL[cpu_id].lock(&mut node);
pool.push_back(ctx);
}
unsafe fn do_preemption() {
let cpu_id = awkernel_lib::cpu::cpu_id();
let Some(mut next) = peek_preemption_pending(cpu_id) else {
return;
};
// If there is a running task on this CPU core, preemption will be performed.
// Otherwise, this function just returns.
let Some(current_task_id) = get_current_task(cpu_id) else {
remove_preemption_pending(cpu_id, next.id);
next.scheduler.wake_task(next);
return;
};
{
let current_task = get_task(current_task_id).unwrap();
// The running task may have changed since the IPI was requested. Only
// a strictly higher-priority pending task preempts it; on equal
// priority the pending task is re-queued instead (FIFO within a
// priority level).
//
// The one exception is the PrioritizedRR time quantum. Every wake
// path requires a strictly higher priority (`Task::preempts`), so a
// pending task of equal priority can only come from
// `PrioritizedRRScheduler::invoke_preemption_tick`, which pushes the
// next runnable task when the quantum of the running task has
// expired and that task does not have a lower priority than the
// running one. Let it through when the running task
// is PrioritizedRR so that the quantum rotates equal-priority tasks.
// `PriorityInfo` includes the scheduler priority, and the tick never
// pushes a panicked task, so equal priority implies that `next` is a
// PrioritizedRR task too.
let quantum_rotation = !current_task.preempts(&next)
&& matches!(
current_task.scheduler_name(),
SchedulerType::PrioritizedRR(_)
);
if !next.preempts(¤t_task) && !quantum_rotation {
remove_preemption_pending(cpu_id, next.id);
next.scheduler.wake_task(next);
return;
}
}
// If a new preemption-pending task with the highest priority is pushed from peek_preemption_pending() to here, the subsequent re-wake may cause a infinite loop.
// Therefore, we move the preemption-pending tasks to a temporary queue and re-wake from there.
let mut moved_preemption_pending = move_preemption_pending(cpu_id).unwrap();
next = moved_preemption_pending.pop().unwrap(); // Use latest highest priority task.
// Mark `next` as running before it becomes visible as the running task,
// as `Scheduler::get_next()` does. `next` resumes either on its own
// thread or on a new thread via `NEXT_TASK`, and neither path passes
// through `Scheduler::get_next()`.
//
// Also start the time quantum of `next` here: `run_main` updates the
// time only after a new thread has started, and a stale time would let
// `invoke_preemption_tick` rotate `next` out before it runs.
{
let mut node = MCSNode::new();
let mut task_info = next.info.lock(&mut node);
if !matches!(
task_info.state,
super::State::Terminated | super::State::Panicked
) {
if task_info.state == super::State::Preempted {
task_info.need_preemption = false;
}
task_info.state = super::State::Running;
}
task_info.update_last_executed();
}
set_current_task(cpu_id, next.id);
// Re-wake the remaining all preemption-pending tasks with lower priorities than `next`.
// This is necessary to handle cases where the number of IPI sends differs from the number of executions of this function.
while let Some(p) = moved_preemption_pending.pop() {
p.scheduler.wake_task(p);
}
// If there is a task to be invoked next, execute the task.
let current_task = {
let mut node = MCSNode::new();
let tasks = super::TASKS.lock(&mut node);
let current_task = tasks.id_to_task.get(¤t_task_id).unwrap();
current_task.clone()
};
#[cfg(feature = "dvfs")]
let freq;
if let Some(next_thread) = {
let mut node = MCSNode::new();
let mut task_info = next.info.lock(&mut node);
#[cfg(feature = "dvfs")]
{
freq = task_info.get_freq();
}
task_info.take_preempt_context()
} {
#[cfg(feature = "dvfs")]
super::apply_task_freq(cpu_id, freq);
// If the next task is a preempted task, yield to it.
yield_preempted_and_wake_task(current_task, next_thread);
} else {
// Otherwise, get a thread from the thread pool or create a new thread.
let next_thread = if let Some(t) = thread::take_pooled_thread() {
// If there is a thread in the thread pool, use it,
t
} else if let Ok(mut t) = thread::create_thread(thread_entry, 0) {
// or create a new thread.
// Set an argument.
unsafe { t.set_argument(t.get_cpu_context() as *const _ as usize) };
t
} else {
// failed to create thread.
log::warn!("failed to create a worker thread.");
// `next` does not run. `current_task` keeps running on this CPU,
// so revert the state of `next` and the running task ID.
// `next` had no preemption context, so it was `Runnable`.
{
let mut node = MCSNode::new();
let mut task_info = next.info.lock(&mut node);
if task_info.state == super::State::Running {
task_info.state = super::State::Runnable;
}
}
set_current_task(cpu_id, current_task_id);
next.scheduler.wake_task(next);
return;
};
{
let cpu_id = awkernel_lib::cpu::cpu_id();
// Insert the next task to the queue.
let mut node = MCSNode::new();
let mut next_task = NEXT_TASK[cpu_id].lock(&mut node);
next_task.push_back(next);
}
yield_preempted_and_wake_task(current_task, next_thread);
}
}
extern "C" fn thread_entry(arg: usize) -> ! {
// Use only the primary heap memory region.
#[cfg(feature = "perf")]
super::perf::start_kernel();
#[cfg(not(feature = "std"))]
unsafe {
awkernel_lib::heap::TALLOC.use_primary()
};
let ctx = unsafe { PtrWorkerThreadContext::with_context(arg) };
thread::set_current_context(ctx);
// Disable interrupt.
interrupt::disable();
// Re-schedule the preempted task.
re_schedule();
// Run the main function.
super::run_main();
awkernel_lib::delay::wait_forever();
}
/// Preempt to the next executable task.
///
/// # Safety
///
/// Do not call this function during mutex locking.
pub unsafe fn preemption() {
// [start] context_switch
// NOTE(nokosaaan): Placed here rather than at the call site: calling into
// the perf module from there would create a circular dependency between
// crates. Placing it in architecture-specific interrupt-handling code was
// also considered, but that would skip this accounting on architectures
// other than the one handled there. This location runs for every
// architecture and is reached immediately after the call site, so it is
// judged appropriate for now; this may need to change if the surrounding
// structure changes in the future.
#[cfg(feature = "perf")]
super::perf::start_context_switch();
let _int_guard = InterruptGuard::new();
let _heap_guard = {
let heap_guard = awkernel_lib::heap::TALLOC.save();
awkernel_lib::heap::TALLOC.use_primary();
heap_guard
};
super::PREEMPTION_REQUEST[awkernel_lib::cpu::cpu_id()].store(false, Ordering::Release);
if let Err(e) = catch_unwind(|| do_preemption()) {
awkernel_lib::heap::TALLOC.use_primary_then_backup();
log::error!("caught panic!: {e:?}");
}
}
/// Voluntary preempt to the next executable task.
///
/// # Safety
///
/// Do not call this function during mutex locking.
pub unsafe fn voluntary_preemption() {
let cpu_id = awkernel_lib::cpu::cpu_id();
// If there is no task running on this CPU core, just return.
if super::RUNNING[cpu_id].load(Ordering::Relaxed) == 0 {
return;
}
// If preemption is not requested, just return.
if !super::PREEMPTION_REQUEST[cpu_id].load(Ordering::Acquire) {
return;
}
preemption();
}
pub fn get_next_task() -> Option<Arc<Task>> {
let mut node = MCSNode::new();
let mut next_task = NEXT_TASK[awkernel_lib::cpu::cpu_id()].lock(&mut node);
next_task.pop_front()
}
pub fn get_num_preemption() -> usize {
NUM_PREEMPTION.load(Ordering::Relaxed)
}