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
pub mod channel;
pub mod scheduler;
use abyss::{interrupt::InterruptGuard, x86_64::intrinsics::cpuid};
use alloc::{boxed::Box, string::String, sync::Arc};
use core::{
arch::asm,
sync::atomic::{AtomicI32, AtomicU64, Ordering},
};
pub const STACK_SIZE: usize = 0x100000;
pub const THREAD_MAGIC: usize = 0xdeadbeefcafebabe;
#[repr(C, align(0x100000))]
#[doc(hidden)]
pub(crate) struct ThreadStack {
pub(crate) thread: *mut Thread,
pub(crate) magic: usize,
pub(crate) _pad:
[u8; STACK_SIZE - core::mem::size_of::<*mut Thread>() - core::mem::size_of::<usize>()],
pub(crate) _usable_marker: [u8; 0],
_pin: core::marker::PhantomPinned,
}
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum ThreadState {
Runnable,
Running,
Exited(i32),
Idle,
Parked,
}
#[repr(C)]
pub struct Thread {
pub(crate) sp: usize,
pub(crate) stack: Box<ThreadStack>,
pub name: String,
pub state: ThreadState,
pub(crate) running_cpu: Arc<AtomicI32>,
pub(crate) exit_status: Arc<AtomicU64>,
}
impl Thread {
#[doc(hidden)]
pub fn new<I>(name: I) -> Box<Self>
where
alloc::string::String: core::convert::From<I>,
{
let mut stack: Box<ThreadStack> = unsafe { Box::new_uninit().assume_init() };
stack.magic = THREAD_MAGIC;
Box::new(Self {
sp: 0,
stack,
name: String::from(name),
state: ThreadState::Runnable,
exit_status: Arc::new(AtomicU64::new(0)),
running_cpu: Arc::new(AtomicI32::new(-1)),
})
}
pub fn exit(&mut self, exit_code: i32) -> ! {
self.exit_status
.store(0x8000_0000_0000_0000 | (exit_code as u64), Ordering::SeqCst);
self.state = ThreadState::Exited(exit_code);
scheduler::scheduler().reschedule();
unreachable!()
}
pub fn park_current_and(f: impl FnOnce(ParkHandle)) {
let _ = abyss::interrupt::InterruptGuard::new();
with_current(|th| {
f(unsafe { scheduler::scheduler().park_thread(th).unwrap() });
});
scheduler::scheduler().reschedule();
}
pub(crate) unsafe fn do_run(&mut self) {
let _p = abyss::interrupt::InterruptGuard::new();
let next_sp = self.sp;
let current_sp = with_current(|th| {
while self.running_cpu.load(Ordering::SeqCst) != -1 {
core::hint::spin_loop()
}
&mut th.sp as *mut usize
});
assert_eq!(
abyss::interrupt::InterruptState::current(),
abyss::interrupt::InterruptState::Off
);
context_switch_trampoline(current_sp, next_sp)
}
pub(crate) fn run(self: Box<Self>) {
unsafe { Box::into_raw(self).as_mut().unwrap().do_run() }
}
pub fn pin() -> ThreadPinGuard {
ThreadPinGuard::new()
}
}
pub type ThreadPinGuard = InterruptGuard;
pub struct JoinHandle
where
Self: 'static,
{
exit_status: Arc<AtomicU64>,
running_cpu: Arc<AtomicI32>,
}
impl JoinHandle {
pub fn new_for(th: &Thread) -> Self {
Self {
exit_status: th.exit_status.clone(),
running_cpu: th.running_cpu.clone(),
}
}
pub fn join(self) -> i32 {
loop {
let v = self.exit_status.load(Ordering::SeqCst);
if v >= 0x8000_0000_0000_0000 {
return v as i32;
}
}
}
pub fn try_get_running_cpu(&self) -> Option<usize> {
match self.running_cpu.load(Ordering::SeqCst) {
v if v < 0 => None,
v => Some(v as usize),
}
}
}
unsafe impl Send for JoinHandle {}
unsafe impl Sync for JoinHandle {}
pub struct ParkHandle {
pub(crate) th: Box<Thread>,
}
impl ParkHandle {
pub(crate) fn new_for(th: Box<Thread>) -> Self {
Self { th }
}
pub fn unpark(mut self) {
while self.th.running_cpu.load(Ordering::SeqCst) != -1 {
core::hint::spin_loop()
}
self.th.state = ThreadState::Runnable;
scheduler::scheduler().push_to_queue(self.th);
}
}
unsafe impl Send for ParkHandle {}
unsafe impl Sync for ParkHandle {}
#[naked]
unsafe extern "C" fn context_switch_trampoline(_current_sp: *mut usize, _next_sp: usize) {
asm!("push rbp",
"push rbx",
"push r12",
"push r13",
"push r14",
"push r15",
"mov r8, rsp",
"mov [rdi], r8",
"mov rsp, rsi",
"pop r15",
"pop r14",
"pop r13",
"pop r12",
"pop rbx",
"pop rbp",
"jmp {}",
sym finish_context_switch,
options(noreturn));
}
unsafe extern "C" fn finish_context_switch(prev: &'static mut Thread) {
assert_eq!(
abyss::interrupt::InterruptState::current(),
abyss::interrupt::InterruptState::Off
);
match prev.state {
ThreadState::Exited(_e) => {
let _ = Box::from_raw(prev);
}
ThreadState::Idle => (),
ThreadState::Running => {
prev.state = ThreadState::Runnable;
let th = Box::from_raw(prev);
scheduler::scheduler().push_to_queue(th);
}
ThreadState::Parked => (),
ThreadState::Runnable => unreachable!("{:?} {:?}", prev as *const _, prev.name),
}
with_current(|th| {
if th.state != ThreadState::Idle {
th.state = ThreadState::Running
}
abyss::x86_64::segmentation::SegmentTable::update_tss(
th.stack.as_mut() as *mut _ as usize + STACK_SIZE,
);
th.running_cpu.store(cpuid() as i32, Ordering::SeqCst);
});
prev.running_cpu.store(-1, Ordering::SeqCst);
}
pub fn with_current<R>(f: impl FnOnce(&mut Thread) -> R) -> R {
unsafe {
let mut sp: usize;
asm!("mov {}, rsp", out(reg) sp);
let current_stack = ((sp & !(STACK_SIZE - 1)) as *mut ThreadStack)
.as_mut()
.unwrap();
if current_stack.magic != THREAD_MAGIC {
panic!(
"Stack overflow detected! You might allocate big local variable. Stack: {:?}",
current_stack as *const _
)
} else {
f(current_stack.thread.as_mut().unwrap())
}
}
}
pub struct ThreadBuilder {
th: Box<Thread>,
}
#[repr(C)]
struct ContextSwitchFrame<F: FnOnce() + Send> {
_r15: usize,
_r14: usize,
_r13: usize,
_r12: usize,
_bx: usize,
_bp: usize,
ret_addr: usize,
thread_fn: *mut F,
end_of_stack: usize,
}
impl ThreadBuilder {
pub fn new<I>(name: I) -> Self
where
alloc::string::String: core::convert::From<I>,
{
Self {
th: Thread::new(name),
}
}
fn to_thread<F: FnOnce() + Send + 'static>(self, thread_fn: F) -> Box<Thread> {
#[naked]
unsafe extern "C" fn start<F: FnOnce() + Send>() -> ! {
asm!(
"pop rdi",
"sti",
"jmp {}",
sym thread_start::<F>,
options(noreturn),
);
}
fn thread_start<F: FnOnce() + Send>(thread_fn: *mut F) {
let o = unsafe { *Box::from_raw(thread_fn) };
o();
with_current(|current| current.exit(0));
scheduler::scheduler().reschedule();
unreachable!()
}
let Self { mut th } = self;
let stack = th.stack.as_mut();
let frame = unsafe {
((&mut stack._usable_marker as *mut _ as usize
- core::mem::size_of::<ContextSwitchFrame<F>>())
as *mut ContextSwitchFrame<F>)
.as_mut()
.unwrap()
};
frame.end_of_stack = 0;
frame.thread_fn = Box::into_raw(Box::new(thread_fn));
frame.ret_addr = start::<F> as usize;
th.sp = frame as *mut _ as usize;
th.stack.thread = th.as_mut() as *mut _;
th
}
pub fn spawn_as_parked<F: FnOnce() + Send + 'static>(self, thread_fn: F) -> ParkHandle {
let th = self.to_thread(thread_fn);
ParkHandle::new_for(th)
}
pub fn spawn<F: FnOnce() + Send + 'static>(self, thread_fn: F) -> JoinHandle {
let th = self.to_thread(thread_fn);
let handle = JoinHandle::new_for(&th);
scheduler::scheduler().push_to_queue(th);
handle
}
}