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
use super::id::RecycleAllocator;
use super::manager::insert_into_pid2process;
use super::TaskControlBlock;
use super::{add_task, SignalFlags};
use super::{pid_alloc, PidHandle};
use crate::fs::{File, Stdin, Stdout};
use crate::mm::{translated_refmut, MemorySet, KERNEL_SPACE};
use crate::sync::{Condvar, Mutex, Semaphore, UPIntrFreeCell, UPIntrRefMut};
use crate::trap::{trap_handler, TrapContext};
use alloc::string::String;
use alloc::sync::{Arc, Weak};
use alloc::vec;
use alloc::vec::Vec;
pub struct ProcessControlBlock {
pub pid: PidHandle,
inner: UPIntrFreeCell<ProcessControlBlockInner>,
}
pub struct ProcessControlBlockInner {
pub is_zombie: bool,
pub memory_set: MemorySet,
pub parent: Option<Weak<ProcessControlBlock>>,
pub children: Vec<Arc<ProcessControlBlock>>,
pub exit_code: i32,
pub fd_table: Vec<Option<Arc<dyn File + Send + Sync>>>,
pub signals: SignalFlags,
pub tasks: Vec<Option<Arc<TaskControlBlock>>>,
pub task_res_allocator: RecycleAllocator,
pub mutex_list: Vec<Option<Arc<dyn Mutex>>>,
pub semaphore_list: Vec<Option<Arc<Semaphore>>>,
pub condvar_list: Vec<Option<Arc<Condvar>>>,
}
impl ProcessControlBlockInner {
#[allow(unused)]
pub fn get_user_token(&self) -> usize {
self.memory_set.token()
}
pub fn alloc_fd(&mut self) -> usize {
if let Some(fd) = (0..self.fd_table.len()).find(|fd| self.fd_table[*fd].is_none()) {
fd
} else {
self.fd_table.push(None);
self.fd_table.len() - 1
}
}
pub fn alloc_tid(&mut self) -> usize {
self.task_res_allocator.alloc()
}
pub fn dealloc_tid(&mut self, tid: usize) {
self.task_res_allocator.dealloc(tid)
}
pub fn thread_count(&self) -> usize {
self.tasks.len()
}
pub fn get_task(&self, tid: usize) -> Arc<TaskControlBlock> {
self.tasks[tid].as_ref().unwrap().clone()
}
}
impl ProcessControlBlock {
pub fn inner_exclusive_access(&self) -> UPIntrRefMut<'_, ProcessControlBlockInner> {
self.inner.exclusive_access()
}
pub fn new(elf_data: &[u8]) -> Arc<Self> {
kprintln!("[KERN] task::process::PCB::new() begin");
kprintln!("[KERN] task::process::PCB::new(): build MemorySet, set trampoline, user_stack_base, entry_point...");
let (memory_set, ustack_base, entry_point) = MemorySet::from_elf(elf_data);
kprintln!("[KERN] task::process::PCB::new(): allocate a pid");
let pid_handle = pid_alloc();
kprintln!("[KERN] task::process::PCB::new(): new ProcessControlBlockInner");
let process = Arc::new(Self {
pid: pid_handle,
inner: unsafe {
UPIntrFreeCell::new(ProcessControlBlockInner {
is_zombie: false,
memory_set,
parent: None,
children: Vec::new(),
exit_code: 0,
fd_table: vec![
Some(Arc::new(Stdin)),
Some(Arc::new(Stdout)),
Some(Arc::new(Stdout)),
],
signals: SignalFlags::empty(),
tasks: Vec::new(),
task_res_allocator: RecycleAllocator::new(),
mutex_list: Vec::new(),
semaphore_list: Vec::new(),
condvar_list: Vec::new(),
})
},
});
kprintln!("[KERN] task::process::PCB::new(): create a main thread... start");
kprintln!("[KERN] task::process::PCB::new(): create a main thread: new TCB(alloc kstack, utack & trap_cx...) ");
let task = Arc::new(TaskControlBlock::new(
Arc::clone(&process),
ustack_base,
true,
));
kprintln!("[KERN] task::process::PCB::new(): create a main thread: set trap_cx(entry_point, ustack_top, k_satp, k_sp, trap_handler) ");
let task_inner = task.inner_exclusive_access();
let trap_cx = task_inner.get_trap_cx();
let ustack_top = task_inner.res.as_ref().unwrap().ustack_top();
let kstack_top = task.kstack.get_top();
drop(task_inner);
*trap_cx = TrapContext::app_init_context(
entry_point,
ustack_top,
KERNEL_SPACE.exclusive_access().token(),
kstack_top,
trap_handler as usize,
);
kprintln!("[KERN] task::process::PCB::new(): create a main thread... done");
kprintln!("[KERN] task::process::PCB::new(): add main thread to the process");
let mut process_inner = process.inner_exclusive_access();
process_inner.tasks.push(Some(Arc::clone(&task)));
drop(process_inner);
kprintln!("[KERN] task::process::PCB::new(): insert <pid, PCB> in PID2PCB BTreeMap");
insert_into_pid2process(process.getpid(), Arc::clone(&process));
kprintln!("[KERN] task::process::PCB::new(): add_task(task): add main thread to scheduler");
add_task(task);
kprintln!("[KERN] task::process::PCB::new() end");
process
}
pub fn exec(self: &Arc<Self>, elf_data: &[u8], args: Vec<String>) {
kprintln!("[KERN] task::process::PCB::exec() begin");
assert_eq!(self.inner_exclusive_access().thread_count(), 1);
kprintln!("[KERN] task::process::PCB::exec(): build MemorySet, trampoline, user_stack_base, entry_point...");
let (memory_set, ustack_base, entry_point) = MemorySet::from_elf(elf_data);
let new_token = memory_set.token();
kprintln!("[KERN] task::process::PCB::exec(): substitute memory_set, ustack_base");
self.inner_exclusive_access().memory_set = memory_set;
let task = self.inner_exclusive_access().get_task(0);
let mut task_inner = task.inner_exclusive_access();
task_inner.res.as_mut().unwrap().ustack_base = ustack_base;
kprintln!("[KERN] task::process::PCB::exec(): alloc user resource for this thread");
task_inner.res.as_mut().unwrap().alloc_user_res();
kprintln!("[KERN] task::process::PCB::exec(): set trap_cx_ppn for this thread");
task_inner.trap_cx_ppn = task_inner.res.as_mut().unwrap().trap_cx_ppn();
kprintln!("[KERN] task::process::PCB::exec(): push arguments on user stack for this thread");
let mut user_sp = task_inner.res.as_mut().unwrap().ustack_top();
user_sp -= (args.len() + 1) * core::mem::size_of::<usize>();
let argv_base = user_sp;
let mut argv: Vec<_> = (0..=args.len())
.map(|arg| {
translated_refmut(
new_token,
(argv_base + arg * core::mem::size_of::<usize>()) as *mut usize,
)
})
.collect();
*argv[args.len()] = 0;
for i in 0..args.len() {
user_sp -= args[i].len() + 1;
*argv[i] = user_sp;
let mut p = user_sp;
for c in args[i].as_bytes() {
*translated_refmut(new_token, p as *mut u8) = *c;
p += 1;
}
*translated_refmut(new_token, p as *mut u8) = 0;
}
user_sp -= user_sp % core::mem::size_of::<usize>();
kprintln!("[KERN] task::process::PCB::exec(): set trap_cx(entry_point, ustack_top, k_satp, k_sp, trap_handler, argc=x[10], argv=x[11])");
let mut trap_cx = TrapContext::app_init_context(
entry_point,
user_sp,
KERNEL_SPACE.exclusive_access().token(),
task.kstack.get_top(),
trap_handler as usize,
);
trap_cx.x[10] = args.len();
trap_cx.x[11] = argv_base;
*task_inner.get_trap_cx() = trap_cx;
kprintln!("[KERN] task::process::PCB::exec() end");
}
pub fn fork(self: &Arc<Self>) -> Arc<Self> {
kprintln!("[KERN] task::process::PCB::fork() begin");
let mut parent = self.inner_exclusive_access();
assert_eq!(parent.thread_count(), 1);
kprintln!("[KERN] task::process::PCB::fork(): clone parent's memory_set for child");
let memory_set = MemorySet::from_existed_user(&parent.memory_set);
kprintln!("[KERN] task::process::PCB::fork(): alloc a new pid for child");
let pid = pid_alloc();
kprintln!("[KERN] task::process::PCB::fork(): copy fd table for child");
let mut new_fd_table: Vec<Option<Arc<dyn File + Send + Sync>>> = Vec::new();
for fd in parent.fd_table.iter() {
if let Some(file) = fd {
new_fd_table.push(Some(file.clone()));
} else {
new_fd_table.push(None);
}
}
kprintln!("[KERN] task::process::PCB::fork(): new child PCB with new pid, memory_set, fd_table, ...");
let child = Arc::new(Self {
pid,
inner: unsafe {
UPIntrFreeCell::new(ProcessControlBlockInner {
is_zombie: false,
memory_set,
parent: Some(Arc::downgrade(self)),
children: Vec::new(),
exit_code: 0,
fd_table: new_fd_table,
signals: SignalFlags::empty(),
tasks: Vec::new(),
task_res_allocator: RecycleAllocator::new(),
mutex_list: Vec::new(),
semaphore_list: Vec::new(),
condvar_list: Vec::new(),
})
},
});
kprintln!("[KERN] task::process::PCB::fork(): add child link in parent' children Vec");
parent.children.push(Arc::clone(&child));
kprintln!("[KERN] task::process::PCB::fork(): TaskControlBlock::new(): create main thread of child process");
let task = Arc::new(TaskControlBlock::new(
Arc::clone(&child),
parent
.get_task(0)
.inner_exclusive_access()
.res
.as_ref()
.unwrap()
.ustack_base(),
false,
));
kprintln!("[KERN] task::process::PCB::fork(): attach child TCB to child PCB");
let mut child_inner = child.inner_exclusive_access();
child_inner.tasks.push(Some(Arc::clone(&task)));
drop(child_inner);
kprintln!("[KERN] task::process::PCB::fork(): modify child's kstack_top in trap_cx of child");
let task_inner = task.inner_exclusive_access();
let trap_cx = task_inner.get_trap_cx();
trap_cx.kernel_sp = task.kstack.get_top();
drop(task_inner);
kprintln!("[KERN] task::process::PCB::fork(): insert <child pid, child PCB> in PID2PCB BTreeMap");
insert_into_pid2process(child.getpid(), Arc::clone(&child));
kprintln!("[KERN] task::process::PCB::fork(): add_task(child task): add child thread to scheduler");
add_task(task);
kprintln!("[KERN] task::process::PCB::fork() end");
child
}
pub fn getpid(&self) -> usize {
self.pid.0
}
}