-
Notifications
You must be signed in to change notification settings - Fork 57
/
kernel.cc
435 lines (350 loc) · 11.6 KB
/
kernel.cc
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
#include "kernel.hh"
#include "k-ahci.hh"
#include "k-apic.hh"
#include "k-chkfs.hh"
#include "k-chkfsiter.hh"
#include "k-devices.hh"
#include "k-vmiter.hh"
#include "obj/k-firstprocess.h"
// kernel.cc
//
// This is the kernel.
// # timer interrupts so far on CPU 0
std::atomic<unsigned long> ticks;
static void tick();
static void boot_process_start(pid_t pid, const char* program_name);
// kernel_start(command)
// Initialize the hardware and processes and start running. The `command`
// string is an optional string passed from the boot loader.
void kernel_start(const char* command) {
init_hardware();
consoletype = CONSOLE_NORMAL;
console_clear();
// set up process descriptors
for (pid_t i = 0; i < NPROC; i++) {
ptable[i] = nullptr;
}
// start first process
boot_process_start(1, CHICKADEE_FIRST_PROCESS);
// start running processes
cpus[0].schedule(nullptr);
}
// boot_process_start(pid, name)
// Load application program `name` as process number `pid`.
// This loads the application's code and data into memory, sets its
// %rip and %rsp, gives it a stack page, and marks it as runnable.
// Only called at initial boot time.
void boot_process_start(pid_t pid, const char* name) {
// look up process image in initfs
memfile_loader ld(memfile::initfs_lookup(name), kalloc_pagetable());
assert(ld.memfile_ && ld.pagetable_);
int r = proc::load(ld);
assert(r >= 0);
// allocate process, initialize memory
proc* p = knew<proc>();
p->init_user(pid, ld.pagetable_);
p->regs_->reg_rip = ld.entry_rip_;
void* stkpg = kalloc(PAGESIZE);
assert(stkpg);
vmiter(p, MEMSIZE_VIRTUAL - PAGESIZE).map(stkpg, PTE_PWU);
p->regs_->reg_rsp = MEMSIZE_VIRTUAL;
// add to process table (requires lock in case another CPU is already
// running processes)
{
spinlock_guard guard(ptable_lock);
assert(!ptable[pid]);
ptable[pid] = p;
}
// add to run queue
cpus[pid % ncpu].enqueue(p);
}
// proc::exception(reg)
// Exception handler (for interrupts, traps, and faults).
//
// The register values from exception time are stored in `reg`.
// The processor responds to an exception by saving application state on
// the current CPU stack, then jumping to kernel assembly code (in
// k-exception.S). That code transfers the state to the current kernel
// task's stack, then calls proc::exception().
void proc::exception(regstate* regs) {
// It can be useful to log events using `log_printf`.
// Events logged this way are stored in the host's `log.txt` file.
//log_printf("proc %d: exception %d @%p\n", id_, regs->reg_intno, regs->reg_rip);
// Record most recent user-mode %rip.
if ((regs->reg_cs & 3) != 0) {
recent_user_rip_ = regs->reg_rip;
}
// Show the current cursor location.
consolestate::get().cursor();
// Actually handle the exception.
switch (regs->reg_intno) {
case INT_IRQ + IRQ_TIMER: {
cpustate* cpu = this_cpu();
if (cpu->cpuindex_ == 0) {
tick();
}
lapicstate::get().ack();
regs_ = regs;
yield_noreturn();
break; /* will not be reached */
}
case INT_PF: { // pagefault exception
// Analyze faulting address and access type.
uintptr_t addr = rdcr2();
const char* operation = regs->reg_errcode & PFERR_WRITE
? "write" : "read";
const char* problem = regs->reg_errcode & PFERR_PRESENT
? "protection problem" : "missing page";
if ((regs->reg_cs & 3) == 0) {
panic_at(*regs, "Kernel page fault for %p (%s %s)!\n",
addr, operation, problem);
}
error_printf(CPOS(24, 0), 0x0C00,
"Process %d page fault for %p (%s %s, rip=%p)!\n",
id_, addr, operation, problem, regs->reg_rip);
pstate_ = proc::ps_faulted;
yield();
break;
}
case INT_IRQ + IRQ_KEYBOARD:
keyboardstate::get().handle_interrupt();
break;
default:
if (sata_disk && regs->reg_intno == INT_IRQ + sata_disk->irq_) {
sata_disk->handle_interrupt();
} else {
panic_at(*regs, "Unexpected exception %d!\n", regs->reg_intno);
}
break; /* will not be reached */
}
// return to interrupted context
}
// proc::syscall(regs)
// System call handler.
//
// The register values from system call time are stored in `regs`.
// The return value from `proc::syscall()` is returned to the user
// process in `%rax`.
uintptr_t proc::syscall(regstate* regs) {
//log_printf("proc %d: syscall %ld @%p\n", id_, regs->reg_rax, regs->reg_rip);
// Record most recent user-mode %rip.
recent_user_rip_ = regs->reg_rip;
switch (regs->reg_rax) {
case SYSCALL_CONSOLETYPE:
if (consoletype != (int) regs->reg_rdi) {
console_clear();
}
consoletype = regs->reg_rdi;
return 0;
case SYSCALL_PANIC:
panic_at(*regs, "process %d called sys_panic()", id_);
break; // will not be reached
case SYSCALL_KTEST:
if (regs->reg_rdi == 1) {
return ktest_wait_queues();
}
return -1;
case SYSCALL_GETPID:
return id_;
case SYSCALL_YIELD:
yield();
return 0;
case SYSCALL_PAGE_ALLOC: {
uintptr_t addr = regs->reg_rdi;
if (addr >= VA_LOWEND || addr & 0xFFF) {
return -1;
}
void* pg = kalloc(PAGESIZE);
if (!pg || vmiter(this, addr).try_map(ka2pa(pg), PTE_PWU) < 0) {
return -1;
}
return 0;
}
case SYSCALL_PAUSE: {
sti();
for (uintptr_t delay = 0; delay < 1000000; ++delay) {
pause();
}
return 0;
}
case SYSCALL_FORK:
return syscall_fork(regs);
case SYSCALL_READ:
return syscall_read(regs);
case SYSCALL_WRITE:
return syscall_write(regs);
case SYSCALL_READDISKFILE:
return syscall_readdiskfile(regs);
case SYSCALL_SYNC: {
int drop = regs->reg_rdi;
// `drop > 1` asserts that no data blocks are referenced (except
// possibly superblock and FBB blocks). This can only be ensured on
// tests that run as the first process.
if (drop > 1 && strncmp(CHICKADEE_FIRST_PROCESS, "test", 4) != 0) {
drop = 1;
}
return bufcache::get().sync(drop);
}
default:
// no such system call
log_printf("%d: no such system call %u\n", id_, regs->reg_rax);
return E_NOSYS;
}
}
// proc::syscall_fork(regs)
// Handle fork system call.
int proc::syscall_fork(regstate* regs) {
(void) regs;
return E_NOSYS;
}
// proc::syscall_read(regs), proc::syscall_write(regs),
// proc::syscall_readdiskfile(regs)
// Handle read and write system calls.
uintptr_t proc::syscall_read(regstate* regs) {
// This is a slow system call, so allow interrupts by default
sti();
uintptr_t addr = regs->reg_rsi;
size_t sz = regs->reg_rdx;
// Your code here!
// * Read from open file `fd` (reg_rdi), rather than `keyboardstate`.
// * Validate the read buffer.
auto& kbd = keyboardstate::get();
auto irqs = kbd.lock_.lock();
// mark that we are now reading from the keyboard
// (so `q` should not power off)
if (kbd.state_ == kbd.boot) {
kbd.state_ = kbd.input;
}
// yield until a line is available
// (special case: do not block if the user wants to read 0 bytes)
while (sz != 0 && kbd.eol_ == 0) {
kbd.lock_.unlock(irqs);
yield();
irqs = kbd.lock_.lock();
}
// read that line or lines
size_t n = 0;
while (kbd.eol_ != 0 && n < sz) {
if (kbd.buf_[kbd.pos_] == 0x04) {
// Ctrl-D means EOF
if (n == 0) {
kbd.consume(1);
}
break;
} else {
*reinterpret_cast<char*>(addr) = kbd.buf_[kbd.pos_];
++addr;
++n;
kbd.consume(1);
}
}
kbd.lock_.unlock(irqs);
return n;
}
uintptr_t proc::syscall_write(regstate* regs) {
// This is a slow system call, so allow interrupts by default
sti();
uintptr_t addr = regs->reg_rsi;
size_t sz = regs->reg_rdx;
// Your code here!
// * Write to open file `fd` (reg_rdi), rather than `consolestate`.
// * Validate the write buffer.
auto& csl = consolestate::get();
spinlock_guard guard(csl.lock_);
size_t n = 0;
while (n < sz) {
int ch = *reinterpret_cast<const char*>(addr);
++addr;
++n;
console_printf(0x0F00, "%c", ch);
}
return n;
}
uintptr_t proc::syscall_readdiskfile(regstate* regs) {
// This is a slow system call, so allow interrupts by default
sti();
const char* filename = reinterpret_cast<const char*>(regs->reg_rdi);
unsigned char* buf = reinterpret_cast<unsigned char*>(regs->reg_rsi);
size_t sz = regs->reg_rdx;
off_t off = regs->reg_r10;
if (!sata_disk) {
return E_IO;
}
// read root directory to find file inode number
auto ino = chkfsstate::get().lookup_inode(filename);
if (!ino) {
return E_NOENT;
}
// read file inode
ino->lock_read();
chkfs_fileiter it(ino);
size_t nread = 0;
while (nread < sz) {
// copy data from current block
if (bcentry* e = it.find(off).get_disk_entry()) {
unsigned b = it.block_relative_offset();
size_t ncopy = min(
size_t(ino->size - it.offset()), // bytes left in file
chkfs::blocksize - b, // bytes left in block
sz - nread // bytes left in request
);
memcpy(buf + nread, e->buf_ + b, ncopy);
e->put();
nread += ncopy;
off += ncopy;
if (ncopy == 0) {
break;
}
} else {
break;
}
}
ino->unlock_read();
ino->put();
return nread;
}
// memshow()
// Draw a picture of memory (physical and virtual) on the CGA console.
// Switches to a new process's virtual memory map every 0.25 sec.
// Uses `console_memviewer()`, a function defined in `k-memviewer.cc`.
static void memshow() {
static unsigned long last_redisplay = 0;
static unsigned long last_switch = 0;
static int showing = 1;
// redisplay every 0.04 sec
if (last_redisplay != 0 && ticks - last_redisplay < HZ / 25) {
return;
}
last_redisplay = ticks;
// switch to a new process every 0.5 sec
if (ticks - last_switch >= HZ / 2) {
showing = (showing + 1) % NPROC;
last_switch = ticks;
}
spinlock_guard guard(ptable_lock);
int search = 0;
while ((!ptable[showing]
|| !ptable[showing]->pagetable_
|| ptable[showing]->pagetable_ == early_pagetable)
&& search < NPROC) {
showing = (showing + 1) % NPROC;
++search;
}
console_memviewer(ptable[showing]);
if (!ptable[showing]) {
console_printf(CPOS(10, 26), 0x0F00, " VIRTUAL ADDRESS SPACE\n"
" [All processes have exited]\n"
"\n\n\n\n\n\n\n\n\n\n\n");
}
}
// tick()
// Called once every tick (0.01 sec, 1/HZ) by CPU 0. Updates the `ticks`
// counter and performs other periodic maintenance tasks.
void tick() {
// Update current time
++ticks;
// Update display
if (consoletype == CONSOLE_MEMVIEWER) {
memshow();
}
}