-
Notifications
You must be signed in to change notification settings - Fork 0
/
kernel.cc
1774 lines (1453 loc) · 47.3 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
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-ahci.hh"
#include "k-apic.hh"
#include "k-chkfs.hh"
#include "k-chkfsiter.hh"
#include "k-devices.hh"
#include "k-vmiter.hh"
#include "k-vfs.hh"
#include "obj/k-firstprocess.h"
#include "k-futex.hh"
// kernel.cc
//
// This is the kernel.
// # timer interrupts so far on CPU 0
std::atomic<unsigned long> ticks;
spinlock timer_lock;
timingwheel timer_queue;
futex_store global_futex_store;
shm_store global_shm_store;
int total_resume_count = 0;
static void tick();
static void boot_process_start(pid_t tgid, pid_t pid, pid_t ppid, const char* program_name);
void init_process_start(pid_t tgid, pid_t pid, pid_t ppid);
void issue_prefetch_process_start(pid_t pid, pid_t ppid);
void handle_prefetch_result_process_start(pid_t pid, pid_t ppid);
// 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;
}
for (pid_t i = 0; i < NTHREADGROUP; i++) {
tgtable[i] = nullptr;
}
for (int i = 0; i < N_GLOBAL_OPEN_FILES; i++) {
open_file_table[i] = nullptr;
}
// start initial kernel process
init_process_start(1, 1, 1);
// kernel process to handle prefetching
// issue_prefetch_process_start(3, 1);
// start first user process
boot_process_start(2, 2, 1, CHICKADEE_FIRST_PROCESS);
// start running processes
cpus[0].schedule(nullptr);
}
void init_process_fn() {
proc* p = ptable[1];
int stat;
while(true) {
int result = p->waitpid(0, &stat, 0);
if (result < 0) {
if (result == E_CHILD) {
process_halt();
}
p->yield();
}
}
}
void issue_prefetch_process_fn() {
auto& bc = bufcache::get();
while(true) {
spinlock_guard guard(bc.prefetch_queue_lock_);
waiter().block_until(bc.prefetch_wait_queue_, [&] () {
bool has_new = false;
for (int i = 0; i < 32; i++) {
if (bc.prefetch_queue_[(i + bc.prefetch_queue_head_) % 32].bn_ >= 0) {
has_new = true;
break;
}
}
return has_new;
}, guard);
int block_to_get = -1;
for (int i = 0; i < 32; i++) {
int id = i + bc.prefetch_queue_head_;
if (bc.prefetch_queue_[id % 32].bn_ >= 0) {
block_to_get = bc.prefetch_queue_[id % 32].bn_;
bc.prefetch_queue_[id % 32].bn_ = -1;
bc.prefetch_queue_head_ = (bc.prefetch_queue_head_ + 1) % 32;
break;
}
}
if (block_to_get >= 0) {
guard.unlock();
bcentry* b = bc.get_disk_entry_for_prefetch(block_to_get);
log_printf("prefetched %d\n", block_to_get);
b->put();
guard.lock();
}
}
}
void init_process_start(pid_t tgid, pid_t pid, pid_t ppid) {
threadgroup* tg = knew<threadgroup>();
tg->init(tgid, ppid, early_pagetable);
kb_c_vnode* keyboard_console_vnode = knew<kb_c_vnode>();
assert(keyboard_console_vnode);
file* kbc_file = knew<file>(keyboard_console_vnode, VFS_FILE_READ | VFS_FILE_WRITE);
assert(kbc_file);
{
spinlock_guard guard(open_file_table_lock);
assert(!open_file_table[0]);
open_file_table[0] = kbc_file;
kbc_file->id_ = 0;
}
tg->fd_table_[0] = kbc_file;
tg->fd_table_[1] = kbc_file;
tg->fd_table_[2] = kbc_file;
proc* p = knew<proc>();
p->init_kernel(pid, tg, &init_process_fn);
{
spinlock_guard guard(ptable_lock);
assert(!ptable[pid]);
ptable[pid] = p;
}
{
spinlock_guard guard(tgtable_lock);
assert(!tgtable[tgid]);
tgtable[tgid] = tg;
}
tg->add_proc_to_thread_list(p);
cpus[pid % ncpu].enqueue(p);
}
void issue_prefetch_process_start(pid_t tgid, pid_t pid, pid_t ppid) {
threadgroup* tg = knew<threadgroup>();
tg->init(tgid, ppid, early_pagetable);
proc* p = knew<proc>();
tg->add_proc_to_thread_list(p);
p->init_kernel(pid, tg, &issue_prefetch_process_fn);
{
spinlock_guard guard(ptable_lock);
assert(!ptable[pid]);
ptable[pid] = p;
}
{
spinlock_guard guard(tgtable_lock);
assert(!tgtable[tgid]);
tgtable[tgid] = tg;
}
cpus[pid % ncpu].enqueue(p);
}
// 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 tgid, pid_t pid, pid_t ppid, 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 threadgroup
threadgroup* tg = knew<threadgroup>();
tg->init(tgid, ppid, ld.pagetable_);
// not locking because init process MUST exist
assert(tgtable[1]);
tg->copy_fd_table_from_threadgroup(tgtable[1]);
// allocate process, initialize memory
proc* p = knew<proc>();
p->init_user(pid, tg);
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;
vmiter(p, 0xB8000).map(0xB8000, PTE_PWU);
// 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;
}
{
spinlock_guard guard(tgtable_lock);
assert(!tgtable[tgid]);
tgtable[tgid] = tg;
}
tg->add_proc_to_thread_list(p);
{
spinlock_guard guard(process_hierarchy_lock);
tgtable[1]->children_list_.push_back(tg);
}
// 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::run_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_GETPID:
return tgid_;
case SYSCALL_GETPPID: {
spinlock_guard guard(process_hierarchy_lock);
log_printf("SYSCALL_GETPPID for process %d => %d\n", id_, tg_->ppid_);
return tg_->ppid_;
}
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_EXIT: {
syscall_exit(regs);
// should never reach
assert(false);
}
case SYSCALL_TEXIT:
syscall_texit(regs);
// should never reach
assert(false);
case SYSCALL_CLONE:
return syscall_clone(regs);
case SYSCALL_FORK:
// return 0;
return syscall_fork(regs);
case SYSCALL_OPEN:
return syscall_open(regs);
case SYSCALL_READ:
return syscall_read(regs);
case SYSCALL_WRITE:
return syscall_write(regs);
case SYSCALL_LSEEK:
return syscall_lseek(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);
}
case SYSCALL_MKDIR:
return syscall_mkdir(regs);
case SYSCALL_RMDIR:
return syscall_rmdir(regs);
case SYSCALL_MAP_CONSOLE: {
uintptr_t addr = reinterpret_cast<uintptr_t>(regs->reg_rdi);
if (addr > VA_LOWMAX || (addr % PAGESIZE) != 0) {
return E_INVAL;
}
if (vmiter(this, addr).try_map(addr, PTE_PWU) < 0) {
return E_INVAL;
}
return 0;
}
case SYSCALL_GETTID:
return id_;
case SYSCALL_MSLEEP:
return syscall_msleep(regs);
case SYSCALL_WAITPID:
return syscall_waitpid(regs);
case SYSCALL_FUTEX:
return syscall_futex(regs);
case SYSCALL_SHMGET:
return syscall_shmget(regs);
case SYSCALL_SHMAT:
return syscall_shmat(regs);
case SYSCALL_SHMDT:
return syscall_shmdt(regs);
case SYSCALL_DUP2:
return syscall_dup2(regs);
case SYSCALL_CLOSE:
return syscall_close(regs);
case SYSCALL_PIPE:
return syscall_pipe(regs);
case SYSCALL_EXECV:
return syscall_execv(regs);
case SYSCALL_NASTYALLOC:
return syscall_nastyalloc(1000);
case SYSCALL_TESTKALLOC: {
uintptr_t heap_top = regs->reg_rdi;
uintptr_t stack_bottom = regs->reg_rsi;
uintptr_t mode = regs->reg_rdx;
return syscall_testkalloc(heap_top, stack_bottom, (int) mode);
}
case SYSCALL_TESTFREE: {
uintptr_t heap_top = regs->reg_rdi;
uintptr_t stack_bottom = regs->reg_rsi;
return syscall_testfree(heap_top, stack_bottom);
}
default:
// no such system call
log_printf("%d: no such system call %u\n", id_, regs->reg_rax);
return E_NOSYS;
}
}
uintptr_t proc::syscall(regstate* regs) {
uintptr_t retval = run_syscall(regs);
assert(stack_canary_ == STACK_CANARY_VALUE);
return retval;
}
int proc::syscall_nastyalloc(int n) {
int test[1000];
for (int i = 0; i < 800; i++) {
test[i] = i;
}
return test[4];
}
int proc::syscall_testkalloc(uintptr_t heap_top, uintptr_t stack_bottom, int mode) {
void* pg = kalloc(PAGESIZE);
if (pg == nullptr || vmiter(this, heap_top).try_map(ka2pa(pg), PTE_PWU) < 0) {
return 0;
}
return 1;
}
int proc::syscall_testfree(uintptr_t heap_top, uintptr_t stack_bottom) {
for (vmiter it(pagetable_, 0); it.low(); it.next()) {
if (it.user() && it.va() >= heap_top && it.va() < stack_bottom) {
// CHANGE WHEN VARIABLE SIZE IS SUPPORTED
it.kfree_page();
}
}
return 0;
}
int proc::syscall_msleep(regstate* regs) {
uint64_t end_time = (uint64_t) ticks.load() + (regs->reg_rdi + 9) / 10;
spinlock_guard guard(timer_lock);
tg_->interrupt_sleep_ = false;
waiter().block_until(*timer_queue.get_wq_for_time(end_time), [&] () {
if (tg_->interrupt_sleep_) {
log_printf("ABOUT TO INTERRUPT!\n");
}
return long(end_time - ticks.load()) <= 0 || tg_->interrupt_sleep_.load();
}, guard);
if (tg_->interrupt_sleep_) {
return E_INTR;
}
return 0;
}
int proc::syscall_clone(regstate* regs) {
uintptr_t stack_top = regs->reg_rdi;
spinlock_guard guard(tg_->thread_list_lock_);
proc* cloned_thread = nullptr;
irqstate irqs;
pid_t pid = -1;
vmiter it(this, stack_top);
if (!it.perm(PTE_P | PTE_U | PTE_W)) {
return E_FAULT;
}
cloned_thread = knew<proc>();
if (!cloned_thread) {
return E_NOMEM;
}
tg_->thread_list_.push_back(cloned_thread);
irqs = ptable_lock.lock();
for (int i = 1; i < NPROC; i++) {
if (ptable[i] == nullptr) {
pid = i;
break;
}
}
if (pid >= 0) {
ptable[pid] = cloned_thread;
}
ptable_lock.unlock(irqs);
if (pid < 0) {
cloned_thread->thread_links_.erase();
kfree(cloned_thread);
return E_AGAIN;
}
cloned_thread->init_user(pid, tg_);
cloned_thread->regs_->reg_rip = regs->reg_rip;
cloned_thread->regs_->reg_rsp = stack_top;
log_printf("sys_clone pid[%d] tgid[%d] cloned to pid[%d] tgid[%d] with stack_page %p\n", id_, tgid_, cloned_thread->id_, cloned_thread->tgid_, stack_top);
cloned_thread->regs_->reg_rax = 0;
cpus[pid % ncpu].enqueue(cloned_thread);
return pid;
}
void proc::texit(int status) {
log_printf("syscall_texit[%d] for pid[%d] tgid[%d]\n", status, id_, tgid_);
bool has_next_thread = false;
bool has_prev_thread = false;
bool is_last_thread = false;
{
spinlock_guard ptable_guard(ptable_lock);
spinlock_guard thread_list_guard(tg_->thread_list_lock_);
has_next_thread = tg_->thread_list_.next(this) != nullptr;
has_prev_thread = tg_->thread_list_.prev(this) != nullptr;
is_last_thread = !has_next_thread && !has_prev_thread;
thread_links_.erase();
// cpustate::schedule will free proc with pstate_ = ps_blank
pstate_ = ps_blank;
ptable[id_] = nullptr;
}
if (is_last_thread) {
log_printf("is_last_thread for pid[%d] tgid[%d]\n", id_, tgid_);
tg_->exit_cleanup(status);
}
yield_noreturn();
}
void proc::syscall_texit(regstate* regs) {
int status = regs->reg_rdi;
texit(status);
}
int proc::waitpid(pid_t tgid, int* stat, int options) {
return tg_->waitpid(tgid, stat, options);
}
int proc::syscall_waitpid(regstate* regs) {
pid_t pid = regs->reg_rdi;
int* stat = (int*) regs->reg_rsi;
int options = (int) regs->reg_rdx;
return waitpid(pid, stat, options);
}
int proc::syscall_futex(regstate* regs) {
uintptr_t addr = regs->reg_rdi;
int futex_op = regs->reg_rsi;
int val = regs->reg_rdx;
// TODO validate parameters, make sure user can acess
if (futex_op != FUTEX_WAIT && futex_op != FUTEX_WAKE) {
return E_FAULT;
}
vmiter it(this, addr);
if (!it.range_perm(4096, PTE_P | PTE_U | PTE_W)) {
return E_FAULT;
}
if (futex_op == FUTEX_WAIT) {
global_futex_store.wait(addr, val);
return 0;
} else if (futex_op == FUTEX_WAKE) {
global_futex_store.wake_n(addr, val);
return 1;
}
return 0;
}
int proc::syscall_shmget(regstate* regs) {
void* shared_page = kalloc(4096);
int global_shmid = -1;
int shmid = -1;
shm* shared_mem = knew<shm>();
shared_mem->kptr_ = shared_page;
{
spinlock_guard guard(shared_mem->ref_count_lock_);
shared_mem->ref_count_ = 1;
}
{
spinlock_guard guard(global_shm_store.list_lock_);
for (int i = 0; i < N_GLOBAL_SHM; i++) {
if (global_shm_store.list_[i] == nullptr) {
global_shmid = i;
break;
}
}
if (global_shmid >= 0) {
global_shm_store.list_[global_shmid] = shared_mem;
shared_mem->id_ = global_shmid;
log_printf("shmget:: %d || %d\n", shared_mem->kptr_, shared_mem->id_);
}
}
if (global_shmid < 0) {
// HANDLE FAILURE
assert(false);
}
log_printf("shared memory page created at %p\n", shared_page);
shmid = assign_to_open_shmid(shared_mem);
if (shmid < 0) {
assert(false);
}
return shmid;
}
uintptr_t proc::syscall_shmat(regstate* regs) {
int shmid = regs->reg_rdi;
uintptr_t shmaddr = regs->reg_rsi;
if (shmid < 0 || shmid >= N_PER_PROC_SHMS) {
return E_FAULT;
}
shm_mapping* shared_mem = nullptr;
{
spinlock_guard guard(tg_->shm_mapping_table_lock_);
shared_mem = &tg_->shm_mapping_table_[shmid];
}
if (!shared_mem) {
assert(false);
}
if (vmiter(this, shmaddr).try_map(ka2pa(shared_mem->shm_->kptr_), PTE_PWU) < 0) {
assert(false);
}
shared_mem->va_ = shmaddr;
return shmaddr;
}
int proc::syscall_shmdt(regstate* regs) {
// TODO: unimplemented yet.
return 0;
}
int proc::close_fd(int fd, spinlock_guard& guard) {
file* open_file = tg_->fd_table_[fd];
if (!open_file) {
return E_BADF;
}
tg_->fd_table_[fd] = nullptr;
{
spinlock_guard ref_count_guard(open_file->ref_count_lock_);
open_file->ref_count_--;
assert(open_file->ref_count_ >= 0);
if (open_file->ref_count_ == 0) {
// no one should be using vnode at this point
{
spinlock_guard open_file_table_guard(open_file_table_lock);
open_file_table[open_file->id_] = nullptr;
}
open_file->vfs_close();
kfree(open_file);
}
}
return 0;
}
bool proc::is_valid_string(char* str, size_t max_char) {
for (size_t i = 0; i < max_char; i++) {
if (str[i] == '\0') {
return true;
}
}
return false;
}
bool proc::is_valid_pathname(uintptr_t pathname) {
if (!pathname) {
return false;
}
vmiter it(this, pathname);
if (!it.user()) {
return false;
}
char* name = reinterpret_cast<char*>(pathname);
// max name size currently allowed is 64;
if (name[0] == '\0') {
return false;
}
for (int i = 1; i < 64; i++) {
vmiter it2(this, reinterpret_cast<uintptr_t>(&name[i]));
if (!it2.user()) {
return false;
}
if (name[i] == '\0') {
return true;
}
}
return false;
}
int proc::get_available_open_file_table_id(spinlock_guard& guard) {
for (int i = 0; i < N_GLOBAL_OPEN_FILES; i++) {
if (open_file_table[i] == nullptr) {
return i;
}
}
return -1;
}
int proc::add_to_open_file_table(file* f) {
spinlock_guard guard(open_file_table_lock);
return add_to_open_file_table(f, guard);
}
int proc::add_to_open_file_table(file* f, spinlock_guard& guard) {
int id = get_available_open_file_table_id(guard);
if (id < 0) {
return -1;
}
open_file_table[id] = f;
f->id_ = id;
return id;
}
int proc::syscall_open(regstate* regs) {
int errno;
uintptr_t pathname_ptr = regs->reg_rdi;
uint64_t flag = regs->reg_rsi;
if (!is_valid_pathname(pathname_ptr)) {
return E_FAULT;
}
char* pathname = reinterpret_cast<char*>(pathname_ptr);
// create file
if ((flag & OF_CREATE) && (flag & OF_WRITE)) {
log_printf("creating file %s \n", pathname);
path_elements path(pathname);
chkfs::inode* dirino = chkfsstate::get().lookup_containing_directory_inode(pathname);
if (!dirino) {
return E_NOENT;
}
dirino->lock_write();
chkfs::inode* created_ino = chkfsstate::get().create_file_in_directory(dirino, path.last());
dirino->unlock_write();
dirino->put();
created_ino->put();
}
chkfsstate::inode* ino = nullptr;
ino = chkfsstate::get().lookup_file_inode(pathname);
if (!ino) {
return E_NOENT;
}
vnode* v;
file* f;
int open_file_id = -1;
int fd = -1;
uint64_t is_read = (flag & OF_READ) ? VFS_FILE_READ : 0;
uint64_t is_write = (flag & OF_WRITE) ? VFS_FILE_WRITE : 0;
// TODO: cleanup on failure
v = knew<inode_vnode>(ino);
if (!v) {
errno = E_NOMEM;
goto open_fail_return;
}
f = knew<file>(v, is_read | is_write);
if (!f) {
errno = E_NOMEM;
goto open_fail_free_vnode;
}
open_file_id = add_to_open_file_table(f);
if (open_file_id < 0) {
errno = E_NFILE;
goto open_fail_free_file;
}
fd = assign_to_open_fd(f);
if (fd < 0) {
errno = E_NFILE;
goto open_fail_free_open_file_table_slot;
}
if ((flag & OF_TRUNC) && (flag & OF_WRITE)) {
((inode_vnode*) v)->truncate();
}
return fd;
// open_fail_free_fd_table_slot: {
// spinlock_guard guard(tg_->fd_table_lock_);
// tg_->fd_table_[fd] = nullptr;
// }
open_fail_free_open_file_table_slot: {
spinlock_guard guard(open_file_table_lock);
open_file_table[open_file_id] = nullptr;
}
open_fail_free_file: {
kfree(f);
}
open_fail_free_vnode: {
kfree(v);
}
open_fail_return : {
ino->put();
assert(ino);
}
return errno;
}
int proc::syscall_close(regstate* regs) {
int fd = regs->reg_rdi;
assert(fd >= 0 && fd < N_FILE_DESCRIPTORS);
spinlock_guard guard(tg_->fd_table_lock_);
return close_fd(fd, guard);
}
bool proc::is_valid_fd(int fd) {
return fd >= 0 && fd < N_FILE_DESCRIPTORS;
}
int proc::syscall_dup2(regstate* regs) {
int oldfd = regs->reg_rdi;
int newfd = regs->reg_rsi;
if (!is_valid_fd(oldfd) || !is_valid_fd(oldfd)) {
return E_BADF;
}
spinlock_guard guard(tg_->fd_table_lock_);
file* file_to_dup = tg_->fd_table_[oldfd];
file* open_file = tg_->fd_table_[newfd];
if (!file_to_dup) {
return E_BADF;
}
if (open_file) {
close_fd(newfd, guard);
}
{
spinlock_guard ref_count_guard(file_to_dup->ref_count_lock_);
file_to_dup->ref_count_++;
tg_->fd_table_[newfd] = file_to_dup;
}
return newfd;
}
int proc::assign_to_open_shmid(shm* s) {
spinlock_guard guard(tg_->shm_mapping_table_lock_);
return assign_to_open_shmid(s, guard);
}
int proc::assign_to_open_shmid(shm* s, spinlock_guard& guard) {
int open_shmid = get_open_fd(guard);
if (open_shmid < 0) {
return -1;
}
tg_->shm_mapping_table_[open_shmid].shm_ = s;
return open_shmid;
}
int proc::get_open_shmid(spinlock_guard& guard) {
for (int i = 0; i < N_PER_PROC_SHMS; i++) {
if (tg_->shm_mapping_table_[i].shm_ == nullptr) {
return i;
}
}
return -1;
}
int proc::get_open_fd(spinlock_guard& guard) {
for (int i = 0; i < N_FILE_DESCRIPTORS; i++) {
if (tg_->fd_table_[i] == nullptr) {
return i;
}
}
return -1;
}
int proc::assign_to_open_fd(file* f) {
spinlock_guard guard(tg_->fd_table_lock_);
return assign_to_open_fd(f, guard);
}
int proc::assign_to_open_fd(file* f, spinlock_guard& guard) {
int open_fd = get_open_fd(guard);
if (open_fd < 0) {
return -1;
}
tg_->fd_table_[open_fd] = f;
return open_fd;
}
int proc::syscall_mkdir(regstate* regs) {
uintptr_t pathname_ptr = regs->reg_rdi;
// uint64_t flag = regs->reg_rsi;
if (!is_valid_pathname(pathname_ptr)) {
return E_FAULT;
}
const char* pathname = reinterpret_cast<const char*>(pathname_ptr);
log_printf("mkrdir %s\n", pathname);