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
use crate::priority_queue::{PriorityQueue64 as PriorityQueue, PriorityQueueTrait};
use crate::task::{Task, TaskAdapter};
use alloc::sync::Arc;
use core::future::Future;
use core::{
alloc::AllocError,
sync::atomic::{AtomicUsize, Ordering},
};
use intrusive_collections::LinkedList;
use spin::Mutex;
pub(crate) static DEFAULT_EXECUTOR: Executor = {
static DEFAULT_LOCAL_EXECUTORS: [LocalExecutor; 1] = [LocalExecutor::new(&DEFAULT_EXECUTOR, 0)];
Executor {
local_executors: &DEFAULT_LOCAL_EXECUTORS,
real_time_queue: Mutex::new(PriorityQueue::NEW),
ntasks: AtomicUsize::new(0),
}
};
pub const MAX_PRIORITY: usize = PriorityQueue::MAX_PRIORITY;
pub const MAX_QUANTUM: usize = usize::MAX - MAX_PRIORITY;
const DEFAULT_QUANTUM: usize = 1;
pub struct Executor {
pub local_executors: &'static [LocalExecutor],
pub(crate) ntasks: AtomicUsize,
pub(crate) real_time_queue: Mutex<PriorityQueue>,
}
pub struct LocalExecutor {
inner: Mutex<ExecutorInner>,
ctx: &'static Executor,
id: usize,
}
impl LocalExecutor {
pub const fn new(ctx: &'static Executor, id: usize) -> Self {
Self {
inner: Mutex::new(ExecutorInner::new()),
ctx,
id,
}
}
pub fn spawn(
&self,
future: impl Future<Output = ()> + 'static + Send,
) -> Result<(), AllocError> {
self.spawn_time_sharing(DEFAULT_QUANTUM, future)
}
pub fn spawn_time_sharing(
&self,
quantum: usize,
future: impl Future<Output = ()> + 'static + Send,
) -> Result<(), AllocError> {
self.spawn1(ExecuteWeight::from_quantum(quantum), future)
}
pub fn spawn_real_time(
&self,
priority: usize,
future: impl Future<Output = ()> + 'static + Send,
) -> Result<(), AllocError> {
self.spawn1(ExecuteWeight::from_priority(priority), future)
}
fn spawn1(
&self,
weight: ExecuteWeight,
future: impl Future<Output = ()> + 'static + Send,
) -> Result<(), AllocError> {
let task = Task::new(self.ctx, self.id, weight, future)?;
self.reschedule(task, true);
Ok(())
}
pub fn run(&self) {
while self.ctx.ntasks.load(Ordering::SeqCst) != 0 {
if let Some((_priority, task)) = self.ctx.real_time_queue.lock().pop() {
let _ = task.poll();
} else {
let mut inner = self.inner.lock();
if let Some(task) = inner.this_queue().pop_front() {
drop(inner);
let _ = task.poll();
} else {
let round = inner.round;
drop(inner);
self.steal_tasks(round);
inner = self.inner.lock();
if inner.this_queue().is_empty() && !inner.next_queue().is_empty() {
inner.round += 1;
}
}
}
}
}
fn steal_tasks(&self, max_round: usize) {
const BATCH_SIZE: usize = 10;
const NO_TASK: Option<Arc<Task>> = None;
let mut tasks = [NO_TASK; BATCH_SIZE];
let mut task_num = 0;
for (i, executor) in self.ctx.local_executors.iter().enumerate() {
if i == self.id {
continue;
}
let mut other = executor.inner.lock();
if task_num < BATCH_SIZE && other.round <= max_round {
if let Some(task) = other.this_queue().pop_front() {
task.switch_executor(self.id, other.round, max_round);
tasks[task_num] = Some(task);
task_num += 1;
}
}
if task_num < BATCH_SIZE && other.round < max_round {
if let Some(task) = other.next_queue().pop_front() {
task.switch_executor(self.id, other.round, max_round);
tasks[task_num] = Some(task);
task_num += 1;
}
}
if task_num == BATCH_SIZE {
break;
}
}
let mut inner = self.inner.lock();
for i in 0..task_num {
inner.this_queue().push_back(tasks[i].take().unwrap());
}
}
pub(crate) fn try_preempt(&self, task: Arc<Task>) -> Result<(), ()> {
let weight = task.get_weight();
match weight {
ExecuteWeight::TimeSharing(_quantum) => {
if !self.ctx.real_time_queue.lock().is_empty() {
let mut inner = self.inner.lock();
if task.tick().is_some() {
inner.this_queue().push_front(task);
} else {
task.reload_quantum();
inner.next_queue().push_back(task);
}
Ok(())
} else if task.tick().is_none() {
Ok(())
} else {
Err(())
}
}
ExecuteWeight::RealTime(priority) => {
let mut ret = Err(());
let mut rt_queue = self.ctx.real_time_queue.lock();
if let Some((other_priority, other_task)) = rt_queue.pop() {
if priority <= other_priority {
rt_queue.push(priority, task);
ret = Ok(())
}
rt_queue.push(other_priority, other_task);
}
ret
}
}
}
pub(crate) fn reschedule(&self, task: Arc<Task>, first_time: bool) {
let weight = task.get_weight();
match weight {
ExecuteWeight::TimeSharing(_quantum) => {
let mut inner = self.inner.lock();
task.reload_quantum();
if first_time {
inner.this_queue().push_front(task);
} else {
inner.next_queue().push_back(task);
}
}
ExecuteWeight::RealTime(priority) => {
let mut rt_queue = self.ctx.real_time_queue.lock();
rt_queue.push(priority, task);
}
}
}
}
unsafe impl Sync for LocalExecutor {}
type TaskQueue = LinkedList<TaskAdapter>;
struct ExecutorInner {
queue: [TaskQueue; 2],
round: usize,
}
impl ExecutorInner {
const fn new() -> Self {
const QUEUE: TaskQueue = LinkedList::new(TaskAdapter::NEW);
Self {
queue: [QUEUE; 2],
round: 0,
}
}
pub fn this_queue(&mut self) -> &mut TaskQueue {
&mut self.queue[self.round & 1]
}
pub fn next_queue(&mut self) -> &mut TaskQueue {
&mut self.queue[(self.round + 1) & 1]
}
}
#[derive(Clone, Copy)]
pub(crate) enum ExecuteWeight {
TimeSharing(usize),
RealTime(usize),
}
impl ExecuteWeight {
pub fn from_quantum(quantum: usize) -> Self {
let weight = quantum.min(MAX_QUANTUM - 1);
ExecuteWeight::TimeSharing(weight)
}
pub fn from_priority(priority: usize) -> Self {
let priority = priority.min(MAX_PRIORITY);
ExecuteWeight::RealTime(priority)
}
pub fn from_raw_weight(raw_weight: usize) -> Self {
if raw_weight < MAX_QUANTUM {
Self::TimeSharing(raw_weight)
} else {
Self::RealTime(raw_weight - MAX_QUANTUM)
}
}
pub fn into_raw_weight(self) -> usize {
match self {
ExecuteWeight::TimeSharing(quantum) => quantum,
ExecuteWeight::RealTime(priority) => priority + MAX_QUANTUM,
}
}
}