-
Notifications
You must be signed in to change notification settings - Fork 82
/
process.rs
620 lines (535 loc) · 21 KB
/
process.rs
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
// SPDX-FileCopyrightText: 2020 Sean Cross <sean@xobs.io>
// SPDX-License-Identifier: Apache-2.0
use core::mem;
static mut PROCESS: *mut ProcessImpl = 0xff80_1000 as *mut ProcessImpl;
pub const MAX_THREAD: TID = 31;
pub const EXCEPTION_TID: TID = 1;
pub const INITIAL_TID: TID = 2;
pub const IRQ_TID: TID = 0;
use xous_kernel::{ProcessInit, ProcessStartup, ThreadInit, PID, TID};
use crate::arch::mem::PAGE_SIZE;
use crate::services::ProcessInner;
// use crate::args::KernelArguments;
pub const DEFAULT_STACK_SIZE: usize = 128 * 1024;
pub const MAX_PROCESS_COUNT: usize = 64;
// pub use crate::arch::mem::DEFAULT_STACK_TOP;
/// This is the address a program will jump to in order to return from an ISR.
pub const RETURN_FROM_ISR: usize = 0xff80_2000;
/// This is the address a thread will return to when it exits.
pub const EXIT_THREAD: usize = 0xff80_3000;
/// This is the address a thread will return to when it finishes handling an exception.
pub const RETURN_FROM_EXCEPTION_HANDLER: usize = 0xff80_4000;
/// This is the address the swapper returns from
pub const RETURN_FROM_SWAPPER: usize = 0xff80_8000;
/// Support processing interrupts, which normally are TID 0. Since
/// the TID is a NonZeroU8, we must pick a value here that can be
/// used throughout the rest of the kernel.
const IRQ_TID_SENTINAL: TID = 255;
// Thread IDs have three possible meaning:
// Logical Thread ID: What the user sees
// Thread Context Index: An index into the thread slice
// Hardware Thread ID: The index that the ISR uses
//
// The Hardware Thread ID is always equal to the Thread Context
// Index, minus one. For example, the default thread ID is
// Hardware Thread ID 1 is Thread Context Index 0.
// The Logical Thread ID is equal to the Hardware Thread ID
// plus one again. This is because the ISR context is Thread
// Context Index 0.
// Therefore, the first Logical Thread ID is 1, which maps
// to Hardware Thread ID 2, which is Thread Context Index 1.
//
// +-----------------+-----------------+-----------------+
// | Thread ID | Context Index | Hardware Thread |
// +=================+=================+=================+
// | ISR Context | 0 | 1 |
// | 1 | 1 | 2 |
// | 2 | 2 | 3 |
// ProcessImpl occupies a multiple of pages mapped to virtual address `0xff80_1000`.
// Each thread is 128 bytes (32 4-byte registers). The first "thread" does not exist,
// and instead is any bookkeeping information related to the process.
#[derive(Debug, Copy, Clone)]
#[repr(C)]
struct ProcessImpl {
/// Used by the interrupt handler to calculate offsets
scratch: usize,
/// The currently-active thread for this process. This must
/// be the 2nd item, because the ISR directly writes this value.
hardware_thread: usize,
/// Global parameters used by the operating system
pub inner: ProcessInner,
/// The last thread ID that was allocated
last_tid_allocated: u8,
/// Pad everything to 128 bytes, so the Thread slice starts at
/// offset 128.
_padding: [u32; 13],
/// This enables the kernel to keep track of threads in the
/// target process, and know which threads are ready to
/// receive messages.
threads: [Thread; MAX_THREAD],
}
/// Compile-time assertion that the procesor-specific Process implementation
/// is a multiple of the page size.
fn _assert_processimpl_is_page_sized() {
unsafe {
mem::transmute::<ProcessImpl, [u8; crate::mem::PAGE_SIZE]>(ProcessImpl {
scratch: 0,
hardware_thread: 0,
inner: Default::default(),
last_tid_allocated: 0,
_padding: [0; 13],
threads: [Default::default(); MAX_THREAD],
});
}
}
/// Singleton process table. Each process in the system gets allocated from this table.
struct ProcessTable {
/// The process upon which the current syscall is operating
current: PID,
/// The actual table contents. `true` if a process is allocated,
/// `false` if it is free.
table: [bool; MAX_PROCESS_COUNT],
}
static mut PROCESS_TABLE: ProcessTable =
ProcessTable { current: unsafe { PID::new_unchecked(1) }, table: [false; MAX_PROCESS_COUNT] };
#[repr(C)]
#[cfg(baremetal)]
#[derive(Debug, Copy, Clone)]
/// The stage1 bootloader sets up some initial processes. These are reported
/// to us as (satp, entrypoint, sp) tuples, which can be turned into a structure.
/// The first element is always the kernel.
pub struct InitialProcess {
/// The RISC-V SATP value, which includes the offset of the root page
/// table plus the process ID.
pub satp: usize,
/// Where execution begins
pub entrypoint: usize,
/// Address of the top of the stack
pub sp: usize,
/// Address of the environment block
pub env: usize,
}
impl InitialProcess {
pub fn pid(&self) -> PID {
let pid = (self.satp >> 22) & ((1 << 9) - 1);
unsafe { PID::new_unchecked(pid as u8) }
}
}
#[repr(C)]
#[derive(Debug)]
pub struct Process {
pid: PID,
}
fn fixup_irq(tid: TID) -> TID { if tid == IRQ_TID_SENTINAL { 0 } else { tid } }
#[repr(C)]
#[derive(Copy, Clone, Debug, Default)]
/// Everything required to keep track of a single thread of execution.
pub struct Thread {
/// Storage for all RISC-V registers, minus $zero
pub registers: [usize; 31],
/// The return address. Note that if this thread was created because of an
/// `ecall` instruction, you will need to add `4` to this before returning,
/// to prevent that instruction from getting executed again. If this is 0,
/// then this thread is not valid.
pub sepc: usize,
}
impl Process {
pub fn current() -> Process {
let pid = unsafe { PROCESS_TABLE.current };
let hardware_pid = (riscv::register::satp::read().bits() >> 22) & ((1 << 9) - 1);
assert_eq!((pid.get() as usize), hardware_pid);
Process { pid }
}
/// Mark this process as running on the current core
pub fn activate(&mut self) -> Result<(), xous_kernel::Error> { Ok(()) }
/// Calls the provided function with the current inner process state.
pub fn with_inner<F, R>(f: F) -> R
where
F: FnOnce(&ProcessInner) -> R,
{
let process = unsafe { &*PROCESS };
f(&process.inner)
}
/// Calls the provided function with the current inner process state.
pub fn with_current<F, R>(f: F) -> R
where
F: FnOnce(&Process) -> R,
{
let process = Self::current();
f(&process)
}
/// Calls the provided function with the current inner process state.
pub fn with_current_mut<F, R>(f: F) -> R
where
F: FnOnce(&mut Process) -> R,
{
let mut process = Self::current();
f(&mut process)
}
pub fn with_inner_mut<F, R>(f: F) -> R
where
F: FnOnce(&mut ProcessInner) -> R,
{
let process = unsafe { &mut *PROCESS };
f(&mut process.inner)
}
pub fn current_thread_mut(&mut self) -> &mut Thread {
let process = unsafe { &mut *PROCESS };
assert!(process.hardware_thread != 0, "thread number was 0");
&mut process.threads[process.hardware_thread - 1]
}
pub fn current_thread(&self) -> &Thread {
let process = unsafe { &mut *PROCESS };
&mut process.threads[process.hardware_thread - 1]
// self.thread(process.hardware_thread - 1)
}
pub fn current_tid(&self) -> TID {
let process = unsafe { &*PROCESS };
process.hardware_thread - 1
}
pub fn thread_exists(&self, tid: TID) -> bool {
let tid = fixup_irq(tid);
self.thread(tid).sepc != 0
}
/// Set the current thread number.
pub fn set_tid(&mut self, tid: TID) -> Result<(), xous_kernel::Error> {
let process = unsafe { &mut *PROCESS };
let tid = fixup_irq(tid);
klog!("Switching to thread {}", tid);
assert!(tid <= process.threads.len(), "attempt to switch to an invalid thread {}", tid);
process.hardware_thread = tid + 1;
Ok(())
}
pub fn thread_mut(&mut self, tid: TID) -> &mut Thread {
let process = unsafe { &mut *PROCESS };
let tid = fixup_irq(tid);
assert!(tid <= process.threads.len(), "attempt to retrieve an invalid thread {}", tid);
&mut process.threads[tid]
}
pub fn thread(&self, tid: TID) -> &Thread {
let process = unsafe { &mut *PROCESS };
let tid = fixup_irq(tid);
assert!(tid <= process.threads.len(), "attempt to retrieve an invalid thread {}", tid);
&process.threads[tid]
}
#[cfg(feature = "gdb-stub")]
pub fn for_each_thread_mut<F>(&self, mut op: F)
where
F: FnMut(TID, &Thread),
{
let process = unsafe { &mut *PROCESS };
for (idx, thread) in process.threads.iter_mut().enumerate() {
// Ignore threads that have no PC, and ignore the ISR thread
if thread.sepc == 0 {
continue;
}
if idx == IRQ_TID {
op(IRQ_TID_SENTINAL, thread);
} else {
op(idx, thread);
}
}
}
pub fn find_free_thread(&self) -> Option<TID> {
let process = unsafe { &mut *PROCESS };
let start_tid = process.last_tid_allocated as usize;
let a = &process.threads[start_tid..process.threads.len()];
let b = &process.threads[0..start_tid];
for (index, thread) in a.iter().chain(b.iter()).enumerate() {
let mut tid = index + start_tid;
if tid >= process.threads.len() {
tid -= process.threads.len()
}
if tid != IRQ_TID && tid != EXCEPTION_TID && thread.sepc == 0 {
process.last_tid_allocated = tid as _;
return Some(tid as TID);
}
}
None
}
pub fn set_thread_result(&mut self, thread_nr: TID, result: xous_kernel::Result) {
let vals = result.to_args();
let thread = self.thread_mut(thread_nr);
for (src, dest) in vals.iter().zip(thread.registers[9..].iter_mut()) {
*dest = *src;
}
}
pub fn retry_instruction(&mut self, tid: TID) -> Result<(), xous_kernel::Error> {
let process = unsafe { &mut *PROCESS };
let thread = &mut process.threads[tid];
if thread.sepc >= 4 {
thread.sepc -= 4;
}
Ok(())
}
/// Initialize this process thread with the given entrypoint and stack
/// addresses.
pub fn setup_process(pid: PID, thread_init: ThreadInit) -> Result<(), xous_kernel::Error> {
let process = unsafe { &mut *PROCESS };
let tid = INITIAL_TID;
assert_eq!(pid, crate::arch::current_pid(), "hardware pid does not match setup pid");
assert!(tid != IRQ_TID, "tried to init using the irq thread");
assert!(
mem::size_of::<ProcessImpl>() == PAGE_SIZE,
"Process size is {}, not PAGE_SIZE ({}) (Thread size: {}, array: {}, Inner: {})",
mem::size_of::<ProcessImpl>(),
PAGE_SIZE,
mem::size_of::<Thread>(),
mem::size_of::<[Thread; MAX_THREAD + 1]>(),
mem::size_of::<ProcessInner>(),
);
assert!(tid - 1 < process.threads.len(), "tried to init a thread that's out of range");
assert!(
tid == INITIAL_TID,
"tried to init using a thread {} that wasn't {}. This probably isn't what you want.",
tid,
INITIAL_TID
);
klog!("Setting up new process {}", pid.get());
unsafe {
let pid_idx = (pid.get() as usize) - 1;
assert!(!PROCESS_TABLE.table[pid_idx], "process {} is already allocated", pid);
PROCESS_TABLE.table[pid_idx] = true;
}
// By convention, thread 0 is the trap thread. Therefore, thread 1 is
// the first default thread. There is an offset of 1 due to how the
// interrupt handler functions.
process.hardware_thread = tid + 1;
// Reset the thread state, since it's possibly uninitialized memory
for thread in process.threads.iter_mut() {
*thread = Default::default();
}
let thread = &mut process.threads[tid];
thread.sepc = thread_init.call as usize;
thread.registers[1] = thread_init.stack.as_ptr() as usize + thread_init.stack.len();
thread.registers[9] = thread_init.arg1;
thread.registers[10] = thread_init.arg2;
thread.registers[11] = thread_init.arg3;
thread.registers[12] = thread_init.arg4;
klog!("thread_init: {:x?} thread: {:x?}", thread_init, thread);
#[cfg(any(feature = "debug-print", feature = "print-panics"))]
{
let pid = pid.get();
if pid != 1 {
klog!(
"initializing PID {} thread {} with entrypoint {:08x}, stack @ {:08x}, arg {:08x}",
pid,
tid,
thread.sepc,
thread.registers[1],
thread.registers[9],
);
}
}
process.inner = Default::default();
process.inner.pid = pid;
// Mark the stack as "unallocated-but-free"
let init_sp = (thread_init.stack.as_ptr() as usize) & !0xfff;
if init_sp != 0 {
let stack_size = thread_init.stack.len();
crate::mem::MemoryManager::with_mut(|memory_manager| {
memory_manager
.reserve_range(
init_sp as *mut u8,
stack_size,
xous_kernel::MemoryFlags::R | xous_kernel::MemoryFlags::W,
)
.expect("couldn't reserve stack")
});
}
Ok(())
}
pub fn setup_thread(&mut self, new_tid: TID, setup: ThreadInit) -> Result<(), xous_kernel::Error> {
let entrypoint = setup.call as usize;
// Create the new context and set it to run in the new address space.
let pid = self.pid.get();
let thread = self.thread_mut(new_tid);
let sp = setup.stack.as_ptr() as usize + setup.stack.len();
if sp <= 16 {
return Err(xous_kernel::Error::BadAddress);
}
// Zero out the thread registers, including special ones like `$tp`.
// This should already have been done by the destructor, but do it
// again anyway.
for val in &mut thread.registers {
*val = 0;
}
thread.sepc = 0;
crate::arch::syscall::invoke(
thread,
pid == 1,
entrypoint,
(sp - 16) & !0xf,
EXIT_THREAD,
&[setup.arg1, setup.arg2, setup.arg3, setup.arg4],
);
Ok(())
}
/// Destroy a given thread and return its return value.
///
/// # Returns
/// The return value of the function
///
/// # Errors
/// xous::ThreadNotAvailable - the thread did not exist
pub fn destroy_thread(&mut self, tid: TID) -> Result<usize, xous_kernel::Error> {
let thread = self.thread_mut(tid);
// Ensure this thread is valid
if thread.sepc == 0 || tid == IRQ_TID {
return Err(xous_kernel::Error::ThreadNotAvailable);
}
// thread.registers[0] == x1
// thread.registers[1] == x2
// ...
// thread.registers[4] == x5 == t0
// ...
// thread.registers[9] == x10 == a0
// thread.registers[10] == x11 == a1
let return_value = thread.registers[9];
for val in &mut thread.registers {
*val = 0;
}
thread.sepc = 0;
Ok(return_value)
}
pub fn print_all_threads(&self) {
let process = unsafe { &mut *PROCESS };
for (tid_idx, &thread) in process.threads.iter().enumerate() {
let tid = tid_idx;
if thread.registers[1] != 0 {
Self::print_thread(tid, &thread);
}
}
}
pub fn print_current_thread(&self) {
let thread = self.current_thread();
let tid = self.current_tid();
Self::print_thread(tid, thread);
}
pub fn print_thread(_tid: TID, _thread: &Thread) {
println!("Thread {}:", _tid);
print!("{}", _thread);
}
/// Create a brand-new process. The memory space must already be set up.
pub fn create(
pid: PID,
init_data: ProcessInit,
services: &mut crate::SystemServices,
) -> Result<ProcessStartup, xous_kernel::Error> {
let current_pid = current_pid();
services.get_process(pid)?.mapping.activate()?;
let server_id = services.create_server_id()?;
let server_id_array = server_id.to_array();
// klog!("previous process init was {:x?}", init_data);
let initial_thread = ThreadInit::new(
init_data.start.get(),
init_data.stack,
server_id_array[0] as _,
server_id_array[1] as _,
server_id_array[2] as _,
server_id_array[3] as _,
);
Self::setup_process(pid, initial_thread).unwrap();
services.create_server_with_address(pid, server_id, false)?;
// klog!("activating parent process {}", current_pid.get());
services.get_process(current_pid)?.mapping.activate()?;
// klog!("connecting to server in parent process");
let cid = services.connect_process_to_server(current_pid, server_id)?;
services.send_memory(
init_data.text.as_ptr() as *mut usize,
pid,
init_data.text_destination.get() as *mut usize,
init_data.text.len(),
)?;
Ok(ProcessStartup::new(pid, cid))
}
pub fn destroy(pid: PID) -> Result<(), xous_kernel::Error> {
let process_table = unsafe { &mut *core::ptr::addr_of_mut!(PROCESS_TABLE) };
let pid_idx = pid.get() as usize - 1;
if pid_idx >= process_table.table.len() {
panic!("attempted to destroy PID that exceeds table index: {}", pid);
}
process_table.table[pid_idx] = false;
Ok(())
}
pub fn find_thread<F>(&self, op: F) -> Option<(TID, &mut Thread)>
where
F: Fn(TID, &Thread) -> bool,
{
let process = unsafe { &mut *PROCESS };
for (idx, thread) in process.threads.iter_mut().enumerate() {
if thread.sepc == 0 {
continue;
}
if op(idx, thread) {
return Some((idx, thread));
}
}
None
}
/// This is used by debugging routines to sanity check state, which are typically #[cfg]'d out
/// but with complicated overlapping rules that constantly change. Hence, the #[allow(dead_code)].
#[allow(dead_code)]
pub fn pid(&self) -> PID { self.pid }
}
impl Thread {
/// The current stack pointer for this thread
pub fn stack_pointer(&self) -> usize { self.registers[1] }
pub fn a0(&self) -> usize { self.registers[9] }
pub fn a1(&self) -> usize { self.registers[10] }
}
impl core::fmt::Display for Thread {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "PC:{:08x} SP:{:08x} RA:{:08x}", self.sepc, self.registers[1], self.registers[0])?;
writeln!(f, "GP:{:08x} TP:{:08x}", self.registers[2], self.registers[3])?;
writeln!(
f,
"T0:{:08x} T1:{:08x} T2:{:08x}",
self.registers[4], self.registers[5], self.registers[6]
)?;
writeln!(
f,
"T3:{:08x} T4:{:08x} T5:{:08x} T6:{:08x}",
self.registers[27], self.registers[28], self.registers[29], self.registers[30]
)?;
writeln!(
f,
"S0:{:08x} S1:{:08x} S2:{:08x} S3:{:08x}",
self.registers[7], self.registers[8], self.registers[17], self.registers[18]
)?;
writeln!(
f,
"S4:{:08x} S5:{:08x} S6:{:08x} S7:{:08x}",
self.registers[19], self.registers[20], self.registers[21], self.registers[22]
)?;
writeln!(
f,
"S8:{:08x} S9:{:08x} S10:{:08x} S11:{:08x}",
self.registers[23], self.registers[24], self.registers[25], self.registers[26]
)?;
writeln!(
f,
"A0:{:08x} A1:{:08x} A2:{:08x} A3:{:08x}",
self.registers[9], self.registers[10], self.registers[11], self.registers[12]
)?;
writeln!(
f,
"A4:{:08x} A5:{:08x} A6:{:08x} A7:{:08x}",
self.registers[13], self.registers[14], self.registers[15], self.registers[16]
)?;
Ok(())
}
}
pub fn set_current_pid(pid: PID) {
let pid_idx = (pid.get() - 1) as usize;
unsafe {
let pt = &mut *core::ptr::addr_of_mut!(PROCESS_TABLE);
match pt.table.get(pid_idx) {
None | Some(false) => panic!("PID {} does not exist", pid),
_ => (),
}
pt.current = pid;
}
}
pub fn current_pid() -> PID { unsafe { PROCESS_TABLE.current } }
pub fn current_tid() -> TID { unsafe { ((*PROCESS).hardware_thread) - 1 } }