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
use super::{TrapFrame, Context, Register, ContextRegisters};
use crate::{page, panic, info, warn};
use crate::symbols::*;
use crate::mem;
use crate::arch;
use crate::println;
use crate::trap::usertrapret;
use alloc::boxed::Box;
use crate::process::{put_back_proc, my_proc, PROCS_POOL, my_cpu, sched, ProcInPool};
use crate::page::{Page, Table, EntryAttributes};
use crate::process::Register::a0;
use crate::jump::*;
use crate::spinlock::{Mutex, MutexGuard};
use alloc::sync::Arc;
use crate::file::{File, FsFile};
#[derive(PartialEq)]
#[derive(Debug)]
pub enum ProcessState {
UNUSED,
SLEEPING,
RUNNABLE,
RUNNING,
ZOMBIE,
}
#[repr(C)]
#[repr(align(4096))]
pub struct Process {
pub pgtable: Box<page::Table>,
pub trapframe: Box<TrapFrame>,
pub context: Box<Context>,
pub state: ProcessState,
pub kstack: usize,
pub kstack_sp: usize,
pub pid: i32,
pub channel: usize,
pub drop_on_put_back: Option<MutexGuard<'static, ()>>,
pub files: [Option<Arc<File>>; 256],
}
impl Process {
pub fn new(pid: i32) -> Self {
Self::from_exist(pid, box page::Table::new(), box TrapFrame::zero())
}
pub fn from_exist(pid: i32, pgtable: Box<Table>, trapframe: Box<TrapFrame>) -> Self {
if pid < 0 {
panic!("invalid pid");
}
let kstack = mem::ALLOC().lock().allocate(PAGE_SIZE * 1024) as usize;
let mut p = Self {
trapframe,
pgtable,
context: box Context::zero(),
state: ProcessState::UNUSED,
kstack: kstack,
kstack_sp: kstack + PAGE_SIZE * 1024,
pid,
channel: 0,
drop_on_put_back: None,
files: [None; 256],
};
p.pgtable.kernel_map(
TRAMPOLINE_START,
TRAMPOLINE_TEXT_START(),
page::EntryAttributes::RX as usize,
);
let trapframe = &*p.trapframe as *const _ as usize;
p.pgtable.kernel_map(
TRAPFRAME_START,
trapframe,
page::EntryAttributes::RW as usize,
);
p.context.regs[ContextRegisters::ra as usize] = forkret as usize;
p.context.regs[ContextRegisters::sp as usize] = p.kstack + PAGE_SIZE;
p
}
}
impl Drop for Process {
fn drop(&mut self) {
let _kstack = unsafe { Box::from_raw(self.kstack as *mut Page) };
}
}
#[no_mangle]
pub extern "C" fn forkret() -> ! {
usertrapret()
}
fn init_code() -> &'static [u8] {
#[cfg(debug_assertions)]
let x = include_bytes!("../../../target/riscv64gc-unknown-none-elf/debug/initcode");
#[cfg(not(debug_assertions))]
let x = include_bytes!("../../../target/riscv64gc-unknown-none-elf/release/initcode");
x
}
pub fn init_proc() {
let mut p = Process::new(0);
let content = init_code();
let mut page = Page::new();
page.data[0..content.len()].copy_from_slice(content);
p.pgtable.map(0, page, EntryAttributes::URX as usize);
let sp = map_stack(&mut p.pgtable, 0x80001000);
p.trapframe.epc = 0;
p.trapframe.regs[Register::sp as usize] = sp;
p.state = ProcessState::RUNNABLE;
put_back_proc(box p);
}
pub fn find_available_pid() -> Option<i32> {
let pool = PROCS_POOL.lock();
for i in 0..NMAXPROCS {
match &pool[i] {
ProcInPool::NoProc => return Some(i as i32),
_ => {}
}
}
None
}
pub fn fork() -> i32 {
let p = my_proc();
let f_pid = find_available_pid();
if f_pid.is_none() {
panic!("pid unavailable");
}
let f_pid = f_pid.unwrap();
let pgtable = p.pgtable.clone();
let trapframe = box *p.trapframe.clone();
let mut fork_p = Process::from_exist(f_pid, pgtable, trapframe);
for i in 0..fork_p.files.len() {
fork_p.files[i] = match &p.files[i] {
Some(x) => Some(x.clone()),
None => None
}
}
fork_p.trapframe.regs[a0 as usize] = 0;
fork_p.state = ProcessState::RUNNABLE;
put_back_proc(box fork_p);
f_pid
}
pub const USER_STACK_PAGE: usize = 4;
pub fn map_stack(pgtable: &mut Table, stack_begin: usize) -> usize {
for i in 0..USER_STACK_PAGE {
let stack = page::Page::new();
pgtable.map(
stack_begin + i * PAGE_SIZE,
stack,
page::EntryAttributes::URW as usize,
);
}
stack_begin + PAGE_SIZE * USER_STACK_PAGE
}
pub fn exec(path: &str) {
let p = my_proc();
info!("loading elf {}", path);
let mut content: Box<[u8; 131072]> = box [0; 131072];
{
let f = FsFile::open(path, 0);
let mut blk = [0; 1024];
let mut i = 0;
while f.read(&mut blk) == 1024 {
for j in 0..1024 {
content[i + j] = blk[j];
}
i += 1024;
if i + 1024 >= content.len() {
panic!("elf file too large!");
}
}
}
info!("parsing...");
p.pgtable.unmap_user();
let entry = crate::elf::parse_elf(
&*content,
&mut p.pgtable,
);
info!("done");
let sp = map_stack(&mut p.pgtable, 0x80001000);
p.trapframe.epc = entry as usize;
p.trapframe.regs[Register::sp as usize] = sp;
}
pub fn exit(status: i32) -> ! {
{
let p = my_proc();
if p.pid == 0 {
panic!("init exiting");
}
p.state = ProcessState::ZOMBIE;
}
arch::intr_off();
sched();
unreachable!();
}
pub static PROCS_POOL_SLEEP: Mutex<()> = Mutex::new((), "proc pool sleep");
pub fn sleep<T, U>(channel: *const T, lck: MutexGuard<U>) -> MutexGuard<U> {
let p = my_proc();
p.channel = channel as *const _ as usize;
p.state = ProcessState::SLEEPING;
{
let mut pool = PROCS_POOL.lock();
let p_in_pool = &mut pool[p.pid as usize];
match p_in_pool {
ProcInPool::Scheduled => {}
_ => panic!("invalid proc pool state")
}
*p_in_pool = ProcInPool::BeingSlept;
}
p.drop_on_put_back = Some(PROCS_POOL_SLEEP.lock());
let weak_lock = lck.into_weak();
sched();
p.channel = 0;
return weak_lock.into_guard();
}
pub fn wakeup<T>(channel: *const T) {
let channel = channel as *const _ as usize;
let mut pool = PROCS_POOL.lock();
let mut i = 0;
while i < NMAXPROCS {
match &mut pool[i] {
ProcInPool::Pooling(p) => {
if p.state == ProcessState::SLEEPING && p.channel == channel {
p.state = ProcessState::RUNNABLE;
}
i += 1;
}
ProcInPool::BeingSlept => {
let weak_lock = pool.into_weak();
PROCS_POOL_SLEEP.lock();
pool = weak_lock.into_guard();
}
_ => { i += 1; }
}
}
}