-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkernel.cc
More file actions
1553 lines (1298 loc) · 44.9 KB
/
kernel.cc
File metadata and controls
1553 lines (1298 loc) · 44.9 KB
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "kernel.hh"
#include "k-apic.hh"
#include "k-chkfs.hh"
#include "k-chkfsiter.hh"
#include "k-devices.hh"
#include "k-gfx.hh"
#include "k-vfs.hh"
#include "k-vmiter.hh"
// kernel.cc
//
// This is the kernel.
volatile unsigned long ticks; // # timer interrupts so far on CPU 0
timing_wheel sleep_wheel; // timer wheel to wake on ticks
int kdisplay; // type of display
wait_queue waitpid_wq; // waitqueue for sys_waitpid
static void kdisplay_ontick();
static void process_setup(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) {
assert(read_rbp() % 16 == 0); // check stack alignment
#ifdef GFX
log_printf("Graphics enabled! No console output will be visible.\n");
#endif
init_hardware();
console_clear();
kdisplay = KDISPLAY_MEMVIEWER;
// Set up process descriptors
for (pid_t i = 0; i < NPROC; i++) {
ptable[i] = nullptr;
}
auto irqs = ptable_lock.lock();
const char* proc_name;
#ifdef CHICKADEE_FIRST_PROCESS
// make run-proc_name
proc_name = CHICKADEE_FIRST_PROCESS;
#else
// manual entry
proc_name = "testzombie";
#endif
// old tests that want to run on pid 1
if (!strcmp(proc_name, "allocexit")
|| !strcmp(proc_name, "allocator")) {
process_setup(1, proc_name);
}
// newer programs that expect an init process
else {
process_setup(1, "init");
process_setup(2, proc_name);
}
ptable_lock.unlock(irqs);
// Switch to the first process
cpus[0].schedule(nullptr);
}
// process_setup(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.
void process_setup(pid_t pid, const char* name) {
assert(!ptable[pid]);
assert(!true_ptable[pid]);
proc* p = ptable[pid] = true_ptable[pid] = kalloc_proc();
x86_64_pagetable* npt = kalloc_pagetable();
assert(p && npt);
// initial fdtable setup
p->fdtable_ = knew<fdtable>();
assert(p->fdtable_);
// fds 0, 1, and 2 all hooked up to keyboard/console
file* f = p->fdtable_->fds_[0] = p->fdtable_->fds_[1] =
p->fdtable_->fds_[2] = knew<file>();
assert(f);
f->type_ = file::stream;
f->readable_ = true;
f->writeable_ = true;
f->vnode_ = knew<vnode_kbc>();
assert(f->vnode_);
f->refs_ = 3;
p->init_user(pid, npt);
int r = p->load(name);
assert(r >= 0 && "probably a bad process name");
p->regs_->reg_rsp = MEMSIZE_VIRTUAL;
x86_64_page* stkpg = kallocpage();
assert(stkpg);
r = vmiter(p, MEMSIZE_VIRTUAL - PAGESIZE).map(ka2pa(stkpg));
p->regs_->reg_rsp -= 8; // align stack by 16 bytes
assert(r >= 0);
r = vmiter(p, ktext2pa(console)).map(ktext2pa(console), PTE_P|PTE_W|PTE_U);
assert(r >= 0);
// manage process hierarchy
p->children_.reset();
p->ppid_ = 1;
if (p->pid_ != 1) {
true_ptable[1]->children_.push_back(p);
}
int cpu = p->cpu_ = pid % ncpu;
cpus[cpu].runq_lock_.lock_noirq();
debug_printf("process_setup enqueueing pid %d\n", p->pid_);
cpus[cpu].enqueue(p);
cpus[cpu].runq_lock_.unlock_noirq();
}
unsigned active_threads(proc* p, bool lock = true) {
irqstate irqs;
if (lock) {
irqs = ptable_lock.lock();
}
unsigned r = 0;
for (auto i = 0; i < NPROC; ++i) {
if (ptable[i] && ptable[i]->true_pid_ == p->true_pid_ &&
(ptable[i]->state_ == proc::runnable ||
ptable[i]->state_ == proc::blocked)) {
++r;
}
}
if (lock) {
ptable_lock.unlock(irqs);
}
return r;
}
void display_proc(proc* p) {
if (p) {
debug_printf("ptable[%d] = true_pid_ %d, exiting_ %d, state %s\n",
p->pid_, p->true_pid_, p->exiting_, state_string(p));
}
}
void process_exit(proc* p, int status = 0) {
p->exit_status_ = status;
debug_printf("[%d] process_exit\n", current()->pid_);
auto irqs = ptable_lock.lock();
if (active_threads(p, false) > 1) {
// mark all threads as exiting
debug_printf("[%d] process_exit killing threads...\n", current()->pid_);
for (auto i = 0; i < NPROC; ++i) {
if (ptable[i]
&& ptable[i]->true_pid_ == p->true_pid_
&& ptable[i]->state_ != proc::broken
&& ptable[i]->pid_ != p->pid_){
debug_printf("[%d] process_exit killing %d\n",
p->pid_, ptable[i]->pid_);
ptable[i]->exiting_ = true;
}
if (ptable[i]) {
display_proc(ptable[i]);
}
}
// block until all threads exit
waiter(current()).block_until(waitpid_wq, [&] () {
for (auto i = 0; i < NPROC; ++i) {
display_proc(ptable[i]);
if (ptable[i]
&& ptable[i]->true_pid_ == p->true_pid_
&& ptable[i]->pid_ != p->pid_
&& ptable[i]->state_ != proc::broken){
if (!ptable[i]->exiting_) {
ptable[i]->exiting_ = true;
}
if (ptable[i]->state_ == proc::blocked) {
ptable[i]->wake();
waitpid_wq.wake_all();
}
return false;
}
}
return true;
}, ptable_lock, irqs);
debug_printf("[%d] process_exit finished waiting for threads, "
"exiting\n", p->pid_);
}
ptable_lock.unlock(irqs);
// free file descriptors
for (unsigned i = 0; i < NFDS; i++) {
if (p->fdtable_->fds_[i]) {
p->fdtable_->fds_[i]->deref();
}
}
// interrupt parent
irqs = ptable_lock.lock();
// debug_printf("[%d] process_exit interrupting parent %d\n",
// p->pid_, p->ppid_);
auto daddy = ptable[p->ppid_];
if (daddy && daddy->state_ == proc::blocked) {
daddy->interrupted_ = true;
daddy->wake();
}
// re-parent children
while (!p->children_.empty()) {
proc* child = p->children_.pop_front();
child->ppid_ = 1;
ptable[1]->children_.push_back(child);
}
// debug_printf("[%d] process_exit waking waitpid_wq\n", p->pid_);
ptable_lock.unlock(irqs);
waitpid_wq.wake_all();
p->state_ = proc::broken;
}
// nuke_pagetable(pt)
// Wipes all memory associated with pagetable pt. MUST be called on an L4 pt
void nuke_pagetable(x86_64_pagetable* pt) {
// free virtual memory
for (vmiter vmit(pt); vmit.va() < MEMSIZE_VIRTUAL; vmit.next()) {
if (vmit.user() && vmit.writable() && vmit.pa() != ktext2pa(console)) {
kfree(reinterpret_cast<void*>(pa2ka(vmit.pa())));
assert(vmiter(pt, vmit.va()).map(0x0) >= 0);
}
}
// free L3-L1 pagetables
for (ptiter ptit(pt, 0); ptit.low(); ptit.next()) {
kfree(reinterpret_cast<void*>(pa2ka(ptit.ptp_pa())));
}
// free L4 pagetable
kdelete(pt);
}
// omae wa mou shindeiru
int process_reap(pid_t pid) {
auto irqs = ptable_lock.lock();
proc* p = ptable[pid];
// erase proc from parent's children
true_ptable[p->ppid_]->children_.erase(p);
unsigned nthr = 0;
for (pid_t i = 0; i < NPROC; ++i) {
if (ptable[i]
&& ptable[i]->true_pid_ == p->true_pid_
&& (ptable[i]->state_ == proc::runnable
|| ptable[i]->state_ == proc::blocked
|| ptable[i]->state_ == proc::broken)) {
++nthr;
}
}
if (nthr == 1) {
// wipe everything else
kdelete(p->fdtable_);
nuke_pagetable(p->pagetable_);
}
int exit_status = p->exit_status_;
kfree(p);
ptable[pid] = true_ptable[pid] = nullptr;
ptable_lock.unlock(irqs);
debug_printf("[%d] reaped pid %d, %d active threads\n",
current()->pid_, pid, nthr);
waitpid_wq.wake_all();
return exit_status;
}
// process_fork(ogproc, ogregs)
// Fork the process ogproc into the first available pid.
static pid_t process_fork(proc* ogproc, regstate* ogregs) {
// 1. Allocate a new PID.
pid_t fpid = -1;
auto irqs = ptable_lock.lock();
for (pid_t i = 1; i < NPROC; i++) {
if (!ptable[i] || ptable[i]->state_ == proc::blank) {
fpid = i;
break;
}
}
// No free process slot found
if (fpid < 1) {
debug_printf("[%d] sys_fork error no free pid\n");
ptable_lock.unlock(irqs);
return E_MFILE;
}
debug_printf("[%d] forking into pid %d\n", ogproc->pid_, fpid);
// allocate proc, store in ptable
proc* fproc = ptable[fpid] = true_ptable[fpid] = kalloc_proc();
if (!fproc) {
ptable_lock.unlock(irqs);
return E_NOMEM;
}
fproc->state_ = proc::broken;
ptable_lock.unlock(irqs);
// allocate pagetable
x86_64_pagetable* fpt = fproc->pagetable_ = kalloc_pagetable();
if (!fpt) {
irqs = ptable_lock.lock();
ptable[fpid] = true_ptable[fpid] = nullptr;
kdelete(fproc);
ptable_lock.unlock(irqs);
return E_NOMEM;
}
// initialize proc data
fproc->init_user(fpid, fpt); // note: sets registers wrong
// allocate fdtable
fproc->fdtable_ = knew<fdtable>();
if (!fproc->fdtable_) {
irqs = ptable_lock.lock();
kdelete(fpt);
kdelete(fproc);
ptable[fpid] = nullptr;
ptable_lock.unlock(irqs);
return E_NOMEM;
}
// clone ogproc's fdtable
auto fdt_irqs = ogproc->fdtable_->lock_.lock();
for (unsigned i = 0; i < NFDS && ogproc->fdtable_->fds_[i]; i++) {
auto f = fproc->fdtable_->fds_[i] = ogproc->fdtable_->fds_[i];
f->lock_.lock_noirq();
f->refs_++;
f->vnode_->lock_.lock_noirq();
f->lock_.unlock_noirq();
f->vnode_->refs_++;
f->vnode_->lock_.unlock_noirq();
}
ogproc->fdtable_->lock_.unlock(fdt_irqs);
// set up process hierarchy
fproc->ppid_ = ogproc->pid_;
ogproc->children_.push_back(fproc);
// 3. Copy the parent process’s user-accessible memory and map the copies
// into the new process’s page table.
for (vmiter source(ogproc); source.low(); source.next()) {
if (source.user() && source.writable()
&& source.pa() != ktext2pa(console)) {
void* npage_ka = kallocpage();
if (npage_ka == nullptr) {
process_reap(fpid);
return E_NOMEM;
}
uintptr_t npage_pa = ka2pa(npage_ka);
memcpy(npage_ka, reinterpret_cast<void*>(pa2ka(source.pa())),
PAGESIZE);
if (vmiter(fpt, source.va()).map(npage_pa, source.perm()) < 0) {
kfree(npage_ka);
process_reap(fpid);
return E_NOMEM;
}
}
else if (source.user()) {
if (vmiter(fpt, source.va()).map(source.pa(), source.perm()) < 0) {
process_reap(fpid);
return E_NOMEM;
}
}
}
// 4. Initialize the new process’s registers to a copy of the old process’s
// registers.
*fproc->regs_ = *ogregs;
fproc->regs_->reg_rax = 0;
// 6. Enqueue the new process on some CPU’s run queue.
int cpu = fproc->cpu_ = fpid % ncpu;
cpus[cpu].runq_lock_.lock_noirq();
debug_printf("[%d] process_fork enqueueing pid %d\n",
ogproc->pid_, fproc->pid_);
cpus[cpu].enqueue(fproc);
cpus[cpu].runq_lock_.unlock_noirq();
// 7. Arrange for the new PID to be returned to the parent process and 0 to
// be returned to the child process.
return fpid;
}
int canary_value = rand();
// check_corruption(p)
// Check for data corruption in current cpustate and proc structs by looking
// at the canary values. If the stack got too big and overwrote data, we will
// know because the saved canary values will have changed.
void check_corruption(proc* p) {
cpustate* c = &cpus[p->pid_ % ncpu];
assert(p->canary_ == canary_value);
assert(c->canary_ == canary_value);
}
// seppuku()
// Die an honorable death
int seppuku() {
int big[1000];
for (int i = 0; i < 1000; i++) {
big[i] = i;
}
return big[934];
}
// validate_memory(addr, sz, perms)
// Returns true if [addr, addr + sz) all has permissions = perms and is in
// valid address space.
bool validate_memory(uintptr_t addr, size_t sz = 0, int perms = 0) {
return !(!addr
|| addr + sz > VA_LOWEND
|| addr > VA_HIGHMAX - sz
|| (sz > 0 ? !vmiter(current(), addr).check_range(sz, perms)
: false));
}
template <typename T>
bool validate_memory(T* addr, size_t sz = 0, int perms = 0) {
return validate_memory(reinterpret_cast<uintptr_t>(addr), sz, perms);
}
// validate_fd(fd)
// Returns 0 if it's valid, or the error number if not
// MUST BE CALLED WITH fdtable_.lock HELD
int validate_fd(int fd, fdtable* fdt) {
if (fd < 0 || fd >= NFDS || fdt->fds_[fd] == nullptr) {
return E_BADF;
}
else {
return 0;
}
}
// check_string_termination(str, max_len)
// Checks if a string terminates within max_len characters. Returns <0 if not
// or the length of the string if it does.
int check_string_termination(const char* str, int max_len) {
if (!str)
return E_FAULT;
for (int i = 0; i < max_len; i++) {
if (!validate_memory(&str[i], 1, PTE_P | PTE_U))
return E_FAULT;
else if (str[i] == '\0')
return i;
}
return E_INVAL;
}
int get_proc_slot(proc** ptab) {
for (int i = 1; i < NPROC; ++i) {
if (!ptab[i] || ptab[i]->state_ == proc::blank) {
return i;
}
}
return -1;
}
// 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.
if (pid_ > 0)
debug_printf("[%d] exception %d\n", pid_, regs->reg_intno);
assert(read_rbp() % 16 == 0); // check stack alignment
// Show the current cursor location.
console_show_cursor(cursorpos);
// Actually handle the exception.
switch (regs->reg_intno) {
case INT_IRQ + IRQ_TIMER: {
cpustate* cpu = this_cpu();
if (cpu->index_ == 0) {
++ticks;
if (!sleep_wheel.wqs_[ticks % WHEEL_SPOKES].q_.empty()) {
sleep_wheel.wqs_[ticks % WHEEL_SPOKES].wake_all();
}
kdisplay_ontick();
}
lapicstate::get().ack();
this->regs_ = regs;
this->yield_noreturn();
break; /* will not be reached */
}
case INT_PAGEFAULT: {
uintptr_t addr = rcr2();
// need more stack space?
if (addr <= regs->reg_rsp && addr > regs->reg_rsp - 64) {
debug_printf("PAGEFAULT:\n"
"\taddr:%p\n"
"\t%%rip:%p\n"
"\t%%rsp:%p\n"
"\t%%rsp-64:%p\n",
addr, regs->reg_rip, regs->reg_rsp, regs->reg_rsp - 64);
auto npg = reinterpret_cast<uintptr_t>(kallocpage());
if (!npg || vmiter(this, ROUNDDOWN(addr, PAGESIZE)).map(
ka2pa(npg), PTE_P | PTE_U | PTE_W) < 0){
panic("No memory to grow process %d stack (rip=%p)!\n",
pid_, regs->reg_rip);
}
debug_printf("[%d] pagefault mapped extra page in process stack\n",
pid_);
break;
}
// Analyze faulting address and access type.
const char* operation = regs->reg_err & PFERR_WRITE
? "write" : "read";
const char* problem = regs->reg_err & PFERR_PRESENT
? "protection problem" : "missing page";
if (!(regs->reg_err & PFERR_USER)) {
panic("Kernel page fault for %p (%s %s, rip=%p)!\n",
addr, operation, problem, regs->reg_rip);
}
console_printf("\n");
error_printf(CPOS(24, 0), 0x0C00,
"Process %d page fault for %p (%s %s, rip=%p)!\n",
pid_, addr, operation, problem, regs->reg_rip);
this->state_ = proc::broken;
this->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 {
// doom debugging
log_printf("FATAL ERROR %%rip = %p\n", regs->reg_rip);
panic("Unexpected exception %d!\n", regs->reg_intno);
}
break; /* will not be reached */
}
// Return to the current process.
// If exception arrived in user mode, the process must be runnable.
assert((regs->reg_cs & 3) == 0 || this->state_ == proc::runnable);
}
// 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) {
assert(read_rbp() % 16 == 0); // check stack alignment
uintptr_t r = -1;
switch (regs->reg_rax) {
case SYSCALL_KDISPLAY:
if (kdisplay != (int) regs->reg_rdi) {
console_clear();
}
kdisplay = regs->reg_rdi;
return 0;
case SYSCALL_PANIC:
panic(NULL);
break; // will not be reached
case SYSCALL_GETPID:
r = true_pid_;
break;
case SYSCALL_YIELD:
this->yield();
r = 0;
break;
case SYSCALL_PAGE_ALLOC: {
uintptr_t addr = regs->reg_rdi;
if (addr >= VA_LOWEND || addr & 0xFFF) {
r = E_INVAL;
break;
}
x86_64_page* pg = kallocpage();
if (!pg || vmiter(this, addr).map(ka2pa(pg)) < 0) {
r = E_NOMEM;
break;
}
r = 0;
break;
}
case SYSCALL_PAUSE: {
sti();
for (uintptr_t delay = 0; delay < 1000000; ++delay) {
pause();
}
cli();
r = 0;
break;
}
case SYSCALL_FORK: {
r = process_fork(this, regs);
break;
}
case SYSCALL_EXIT: {
int status = regs->reg_rdi;
process_exit(this, status);
this->yield_noreturn();
}
case SYSCALL_MAP_CONSOLE: {
uintptr_t addr = regs->reg_rdi;
if (addr > VA_LOWMAX || addr & 0xFFF) {
break;
}
if (vmiter(this, addr).map(ktext2pa(console), PTE_P|PTE_W|PTE_U) < 0) {
break;
}
r = 0;
break;
}
case SYSCALL_MAP_SCREEN: {
uintptr_t addr = regs->reg_rdi;
int vm_r;
size_t off;
for (off = 0; off < SCREEN_MEMSIZE; off += PAGESIZE) {
vm_r = vmiter(this, addr + off).map(SCREEN_MEMBASE + off,
PTE_P|PTE_W|PTE_U);
assert(vm_r >= 0);
}
debug_printf("[%d] sys_map_screen -> %p to ~%p\n",
pid_, addr, addr + off);
r = 0;
break;
}
case SYSCALL_MSLEEP: {
interrupted_ = false;
unsigned long end = ticks + (regs->reg_rdi + 9) / 10;
// debug_printf("[%d] sys_msleep(%d)\n", pid_, regs->reg_rdi);
waiter w(this);
auto wq = &sleep_wheel.wqs_[end % WHEEL_SPOKES];
while (true) {
w.prepare(wq);
// debug_printf("[%d] sys_msleep woken\n", pid_);
if ((long) (end - ticks) <= 0 || interrupted_)
break;
// debug_printf("[%d] sys_msleep blocking\n", pid_);
w.block();
}
w.clear();
debug_printf("[-] resumes: %d\n", resumes);
debug_printf("[%d] sys_msleep%sinterrupted\n", pid_,
interrupted_ ? " " : " not ");
r = interrupted_ ? E_INTR : 0;
break;
}
case SYSCALL_GETPPID:
r = ppid_;
break;
case SYSCALL_WAITPID: {
pid_t child_pid = regs->reg_rdi;
assert(child_pid < NPROC && child_pid >= 0);
int options = regs->reg_rsi;
auto irqs = ptable_lock.lock();
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid on child pid %d; options %s W_NOHANG"
"\n", pid_, child_pid, options == W_NOHANG ? "=" : "!=");
}
pid_t parent_of_child = 0;
if (ptable[child_pid]) {
parent_of_child = ptable[child_pid]->ppid_;
}
ptable_lock.unlock(irqs);
pid_t to_reap = 0;
int exit_status = 0;
if ((child_pid != 0 && pid_ != parent_of_child)
|| (child_pid == 0 && children_.empty())) {
r = E_CHILD;
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid returning E_CHILD r=%d\n",
pid_, r);
}
break;
}
else {
waiter w(this);
while (true) {
irqs = ptable_lock.lock();
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid preparing\n", pid_);
}
w.prepare(&waitpid_wq);
// wait for any child
if (child_pid == 0) {
for (auto p = children_.front(); p; p = children_.next(p)) {
if (p->state_ == proc::broken) {
to_reap = p->true_pid_;
ptable_lock.unlock(irqs);
auto s = process_reap(p->pid_);
irqs = ptable_lock.lock();
if (s != 0) {
exit_status = s;
}
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid reaped tid %d, "
"exit_status %d\n", pid_, p->pid_, s);
}
break;
}
}
}
// wait for a child (child_pid)
else {
for (pid_t i = 0; i < NPROC; ++i) {
if (ptable[i]
&& ptable[i]->true_pid_ == child_pid
&& ptable[i]->state_ == proc::broken) {
to_reap = ptable[i]->true_pid_;
ptable_lock.unlock(irqs);
auto s = process_reap(i);
irqs = ptable_lock.lock();
if (s != 0) {
exit_status = s;
}
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid reaped tid %d, "
"exit_status %d\n", pid_, i, s);
}
}
}
}
bool no_threads_left = true;
for (pid_t i = 0; i < NPROC; ++i) {
if (ptable[i] && ptable[i]->true_pid_ == child_pid) {
no_threads_left = false;
}
}
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid to_reap=%d, %sthreads left"
"\n", pid_, to_reap, no_threads_left ? "no " : "");
}
ptable_lock.unlock(irqs);
if ((to_reap && no_threads_left) || options == W_NOHANG)
break;
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid blocking\n", pid_);
}
w.block();
}
w.clear();
}
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid pid to_reap=%d\n", pid_, to_reap);
}
if (!to_reap && options == W_NOHANG && r != (uintptr_t) E_CHILD) {
r = E_AGAIN;
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid returning E_AGAIN r=%d\n", pid_,
r);
}
}
else {
if (true_pid_ > 1) {
debug_printf("[%d] sys_waitpid exit_status=%d\n",
pid_, exit_status);
}
asm("movl %0, %%ecx;": : "r" (exit_status) : "ecx");
r = to_reap;
}
break;
}
// case SYSCALL_COMMIT_SEPPUKU: {
// r = seppuku();
// break;
// }
// DEBUG ONLY - could probably be used to crash the kernel
case SYSCALL_LOG_PRINTF: {
const char* format = reinterpret_cast<const char*>(regs->reg_rdi);
va_list* args = reinterpret_cast<va_list*>(regs->reg_rsi);
log_vprintf(format, *args);
r = 0;
break;
}
case SYSCALL_GETTICKS: {
r = ticks;
break;
}
case SYSCALL_READ:
case SYSCALL_WRITE: {
int fd = regs->reg_rdi;
uintptr_t addr = regs->reg_rsi;
size_t sz = regs->reg_rdx;
auto irqs = fdtable_->lock_.lock();
// debug_printf("[%d] sys_%s on fd %d", pid_,
// regs->reg_rax == SYSCALL_READ ? "read" : "write", fd);
if (fd < 0 || fd >= NFDS || fdtable_->fds_[fd] == nullptr) {
fdtable_->lock_.unlock(irqs);
r = E_BADF;
// debug_printf("; returning E_BADF\n");
break;
}
file* f = fdtable_->fds_[fd];
// debug_printf("; mode r? %s; w? %s\n",
// f->readable_ ? "yes" : "no", f->writeable_ ? "yes" : "no");
if ((regs->reg_rax == SYSCALL_READ && !f->readable_)
|| (regs->reg_rax == SYSCALL_WRITE && !f->writeable_)) {
fdtable_->lock_.unlock(irqs);
r = E_BADF;
// debug_printf("\t...returning E_BADF=%d\n", r);
break;
}
// If size is 0 do nothing
if (sz == 0) {
fdtable_->lock_.unlock(irqs);
r = 0;
break;
}
// Check for valid memory ranges and permissions
auto perms = PTE_P | PTE_U;
if (regs->reg_rax == SYSCALL_READ) {
perms |= PTE_W;
}
if (addr + sz > VA_LOWEND ||
addr > VA_HIGHMAX - sz ||
!vmiter(pagetable_, addr).check_range(sz, perms))
{
fdtable_->lock_.unlock(irqs);
r = E_FAULT;
break;
}
f->lock_.lock_noirq();
fdtable_->lock_.unlock_noirq();
f->refs_++;
f->lock_.unlock(irqs);
vnode* v = f->vnode_;
if (regs->reg_rax == SYSCALL_READ) {
r = v->read(addr, sz, f->off_);
}
else {
r = v->write(addr, sz, f->off_);
}
f->deref();
// debug_printf("[%d] sys_%s %d bytes\n", pid_,
// regs->reg_rax == SYSCALL_READ ? "read read" : "write wrote", r);
break;
}
case SYSCALL_DUP2: {
int oldfd = regs->reg_rdi;
int newfd = regs->reg_rsi;
debug_printf("[%d] sys_dup2(%d, %d)\n", pid_, oldfd, newfd);
auto irqs = fdtable_->lock_.lock();
if (oldfd < 0 || newfd < 0 || oldfd >= NFDS || newfd >= NFDS
|| fdtable_->fds_[oldfd] == nullptr) {
fdtable_->lock_.unlock(irqs);
debug_printf("returning E_BADF\n");
r = E_BADF;
break;
}
if (fdtable_->fds_[newfd])
fdtable_->fds_[newfd]->deref();
fdtable_->fds_[newfd] = fdtable_->fds_[oldfd];
fdtable_->fds_[oldfd]->refs_++;
fdtable_->lock_.unlock(irqs);
r = 0;
break;
}
case SYSCALL_CLOSE: {
int fd = regs->reg_rdi;
debug_printf("[%d] sys_close(%d)\n", pid_, fd);
auto irqs = fdtable_->lock_.lock();
if (fd < 0 || fd >= NFDS || fdtable_->fds_[fd] == nullptr) {
fdtable_->lock_.unlock(irqs);
debug_printf("returning E_BADF\n");
r = E_BADF;
break;
}
fdtable_->fds_[fd]->deref();
fdtable_->fds_[fd] = nullptr;
fdtable_->lock_.unlock(irqs);
debug_printf("[%d] sys_close completed\n", pid_);
r = 0;
break;
}
case SYSCALL_OPEN: {
const char* path = reinterpret_cast<const char*>(regs->reg_rdi);
int flags = regs->reg_rsi;
bool created = false;
auto path_sz = check_string_termination(path, memfile::namesize);
if (path_sz < 0) {
r = path_sz;
break;
}
debug_printf("[%d] sys_open('%s')\n", pid_, path);