-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.c
More file actions
1245 lines (1053 loc) · 35.4 KB
/
Copy pathkernel.c
File metadata and controls
1245 lines (1053 loc) · 35.4 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
/*elf == bad*/ // <- !!!
#include "assets/font.h"
//#include <stdarg.h>
#include "fs.h"
#include "io.h"
#include "mem.h"
// ELF spec
typedef uint16_t Elf32_Half; // Unsigned half int
typedef uint32_t Elf32_Off; // Unsigned offset
typedef uint32_t Elf32_Addr; // Unsigned address
typedef uint32_t Elf32_Word; // Unsigned int
typedef int32_t Elf32_Sword; // Signed int
struct {
uint8_t col;
uint8_t row;
uint8_t blinking;
} term;
struct __attribute__((aligned(0x10))) {
uint8_t initialized;
uint32_t *fb;
uint32_t pitch;
uint32_t width;
uint32_t height;
uint8_t depth;
uint8_t type;
} framebuffer;
struct {
uint8_t initialized;
uint32_t lower;
uint32_t upper;
} memory;
struct {
uint64_t base_addr;
uint64_t length;
uint32_t type;
uint32_t check;
} mem_map[8];
uint32_t mem_map_entries;
uint32_t load_base_addr;
uint64_t tags[50] = {0};
uint64_t howManyTags = 0;
uint8_t stdin[100] = {0};
uint8_t stdinptr = 0;
typedef struct {
uint16_t isr_low;
uint16_t kernel_cs;
uint8_t reserved;
uint8_t attributes;
uint16_t isr_high;
} __attribute__((packed)) idtEntryT;
typedef struct {
unsigned int limit_low : 16;
unsigned int base_low : 24;
unsigned int accessed : 1;
unsigned int read_write : 1;
unsigned int conforming_expand_down : 1;
unsigned int code : 1;
unsigned int code_data_segment : 1;
unsigned int DPL : 2;
unsigned int present : 1;
unsigned int limit_high : 4;
unsigned int available : 1;
unsigned int long_mode : 1;
unsigned int big : 1;
unsigned int gran : 1;
unsigned int base_high : 8;
} __attribute__((packed)) gdtEntryT;
typedef struct {
uint32_t prev_tss; // previous tss, if we do hardware which we dont
uint32_t esp0; // stack pointer to load when changing to kernel mode
uint32_t ss0; // stack segment to load when changing to kernel mode
// literally everything else does not matter
uint32_t esp1; // esp and ss 1 and 2 would be used when switching to rings 1 or 2.
uint32_t ss1;
uint32_t esp2;
uint32_t ss2;
uint32_t cr3;
uint32_t eip;
uint32_t eflags;
uint32_t eax;
uint32_t ecx;
uint32_t edx;
uint32_t ebx;
uint32_t esp;
uint32_t ebp;
uint32_t esi;
uint32_t edi;
uint32_t es;
uint32_t cs;
uint32_t ss;
uint32_t ds;
uint32_t fs;
uint32_t gs;
uint32_t ldt;
uint16_t trap;
uint16_t iomap_base;
} __attribute__((packed)) tssEntryT;
tssEntryT kerneltss;
__attribute__((aligned(0x10)))
idtEntryT idt[256];
gdtEntryT gdt[6];
struct {
uint16_t limit; // Limit of the GDT
uint32_t base; // Base address of the GDT
} __attribute__((packed)) gdtr;
struct {
uint16_t limit; // Limit of the IDT
uint32_t base; // Base address of the GDT
} __attribute__((packed)) idtr;
// i suspect this kills floats
typedef struct {
// pusha data
uint32_t edi, esi, ebp, esp;
uint32_t ebx, edx, ecx, eax;
// irq data
uint32_t eip, cs, eflags, irqesp, ss;
} __attribute__((packed)) contextT;
typedef struct {
uint32_t pid;
uint32_t* pd;
uint8_t* stack;
uint8_t* kernelStack;
enum {
READY,
CREATED,
WAITING,
TERMINATED
} status;
contextT context;
} processT;
processT** pcbt;
uint32_t procindex;
uint32_t processcount;
uint32_t maxprocesscount = 10; // debug, should be more to avoid krealloc calls
uint32_t incpid = 1;
typedef struct {
uint8_t e_ident[16];
Elf32_Half e_type;
Elf32_Half e_machine;
Elf32_Word e_version;
Elf32_Addr e_entry;
Elf32_Off e_phoff;
Elf32_Off e_shoff;
Elf32_Word e_flags;
Elf32_Half e_ehsize;
Elf32_Half e_phentsize;
Elf32_Half e_phnum;
Elf32_Half e_shentsize;
Elf32_Half e_shnum;
Elf32_Half e_shstrndx;
} __attribute__((packed)) Elf32_Ehdr;
typedef struct {
Elf32_Word p_type;
Elf32_Word p_offset;
Elf32_Word p_vaddr;
Elf32_Word p_paddr;
Elf32_Word p_filesz;
Elf32_Word p_memsz;
Elf32_Word p_flags;
Elf32_Word p_align;
} __attribute__((packed)) Elf32_Phdr;
void tick();
// X and Y are the top left coordinates, glyphs are 16x24.
void printGlyph(uint8_t gid, uintptr_t xpos, uintptr_t ypos, uint32_t color, uint8_t clear) {
uint16_t* glyph = font[gid];
for (uint8_t i = 0; i < 24; i++) {
uint16_t row = *glyph;
for (int x = 0; x < 16; x++) {
if (row & 1) {
framebuffer.fb[(i+ypos)*framebuffer.width + (16-x) + xpos] = color;
} else if (clear) {
framebuffer.fb[(i+ypos)*framebuffer.width + (16-x) + xpos] = 0;
}
row >>= 1;
}
glyph++;
}
return;
}
uint32_t divuint64_t(uint64_t N, uint64_t D) {
uint32_t Q = 0;
uint32_t R = 0;
for (int i = 63; i >= 0; --i) {
Q = Q << 1;
R = R << 1;
R |= (N >> 63) & 1;
N = N << 1;
if (D <= R) {
R = R - D;
Q = Q | 1;
}
}
return Q;
}
uint32_t moduint64_t(uint64_t N, uint64_t D) {
uint32_t Q = 0;
uint32_t R = 0;
for (int i = 63; i >= 0; --i) {
Q = Q << 1;
R = R << 1;
R |= (N >> 63) & 1;
N = N << 1;
if (D <= R) {
R = R - D;
Q = Q | 1;
}
}
return R;
}
void clear() {
term.row = term.col = 0;
term.blinking = 1;
for (int i = 0; i < framebuffer.width*framebuffer.height; i++) {
framebuffer.fb[i] = 0;
}
}
// worst code you'll ever see no cap
uintptr_t printNumber(const uint64_t num, uintptr_t x, uintptr_t y, uint32_t color, uint8_t clear) {
uint64_t val = num;
if (val == 0) {
printGlyph('0', x, y, color, clear);
return x;
}
int g = 0;
uint64_t val2 = num;
while (val2 > 0) {
val2 = divuint64_t(val2, 10);
g++;
}
g--;
uintptr_t ret = x;
while (val > 0) {
int xpos = g * 16;
printGlyph(moduint64_t(val, 10) + '0', xpos+x, y, color, clear);
val = divuint64_t(val, 10);
g--;
ret+=16;
}
return ret;
}
uintptr_t printHex(const uint64_t num, uintptr_t x, uintptr_t y, uint32_t color, uint8_t clear) {
uint8_t hexvals[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
uint64_t val = num;
if (val == 0) {
printGlyph('0', x, y, color, clear);
return x;
}
int g = 0;
uint64_t val2 = num;
while (val2 > 0) {
val2 = divuint64_t(val2, 16);
g++;
}
g--;
uintptr_t ret = x;
while (val > 0) {
int xpos = g * 16;
printGlyph(hexvals[moduint64_t(val, 16)], xpos+x, y, color, clear);
val = divuint64_t(val, 16);
g--;
ret+=16;
}
return ret;
}
void ttyPrint(const uint8_t *str) {
if (!framebuffer.initialized || framebuffer.type != 1) return;
if (term.row >= 25) {
clear();
}
while (*str) {
if (*str == '\n') {
term.col = 0;
term.row ++;
str++;
continue;
}
printGlyph(*str, term.col*16, term.row*24, 0xFFFFFFFF, 1);
term.col++;
str++;
if (term.col >= 50) {
term.col = 0;
term.row ++;
}
}
}
void ttyPutChar(const uint8_t chr) {
if (term.row >= 25) {
clear();
}
if (chr == '\n') {
term.col = 0;
term.row ++;
return;
}
printGlyph(chr, term.col*16, term.row*24, 0xFFFFFFFF, 1);
term.col++;
if (term.col >= 50) {
term.col = 0;
term.row ++;
}
}
void ttyPrintNumber(uint32_t num) {
if (term.row >= 25) {
clear();
}
if (num == 0) {
printGlyph('0', term.col * 16, term.row * 24, 0xFFFFFFFF, 1);
term.col++;
} else {
term.col = printNumber(num, term.col * 16, term.row * 24, 0xFFFFFFFF, 1)/16;
}
if (term.col >= 50) {
term.col = 0;
term.row ++;
}
}
void ttyPrintHex(uint32_t num) {
if (!framebuffer.initialized || framebuffer.type != 1) return;
if (term.row >= 25) {
clear();
}
printGlyph('0', term.col * 16, term.row * 24, 0xFFFFFFFF, 1);
term.col++;
printGlyph('x', term.col * 16, term.row * 24, 0xFFFFFFFF, 1);
term.col++;
if (num == 0) {
printGlyph('0', term.col * 16, term.row * 24, 0xFFFFFFFF, 1);
term.col++;
} else {
term.col = printHex(num, term.col * 16, term.row * 24, 0xFFFFFFFF, 1)/16;
}
term.col++;
if (term.col >= 50) {
term.col = 0;
term.row ++;
}
}
void printHeap() {
int i = 0;
for (int y = 0; y < 512; y++) {
for (int x = 0; x < 512; x++) {
framebuffer.fb[(y+100)*framebuffer.width + x + 80] = getBit(heapmap, i) ? 0xFFFFFF : 0x000000;
i += 1;
}
i += 2048 * 1;
}
}
void printBitmap(uint32_t* bitmap, uint32_t offset) {
int x;
for (int y = 0; y < (16*32); y++) {
framebuffer.fb[(y+100)*framebuffer.width -1 + 250] = 0xFF4444;
x = 0;
for (int i = 0; i < 16; i++) {
uint32_t val = bitmap[((y*16)+i)+offset];
for (int j = 0; j < 32; j++) {
if (val & 1) {
if (((((y*16)+i+offset)*32)+j) < memory.upper/4 && ((((y*16)+i+offset)*32)+j) > memory.lower/4) {
framebuffer.fb[(y+100)*framebuffer.width + (32-j)+(x*32) + 250] = 0xFFFFFF;
} else {
framebuffer.fb[(y+100)*framebuffer.width + (32-j)+(x*32) + 250] = 0xFFFFFF;
}
} else {
if (((((y*16)+i+offset)*32)+j) < memory.upper/4 && ((((y*16)+i+offset)*32)+j) > memory.lower/4) {
framebuffer.fb[(y+100)*framebuffer.width + (32-j)+(x*32) + 250] = 0x000000;
} else {
framebuffer.fb[(y+100)*framebuffer.width + (32-j)+(x*32) + 250] = 0x000000;
}
}
val >>= 1;
}
x++;
}
framebuffer.fb[(y+100)*framebuffer.width + (16*32)+2 + 250] = 0xFF4444;
}
}
int64_t abs64(int64_t n) {
if (n < 0) return -n;
return n;
}
// Bresenham line alg
void plotLineLow(int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t color) {
int32_t dx = x1 - x0;
int32_t dy = y1 - y0;
int8_t dir = 1;
if (dy < 0) {
dir = -1; dy = -dy;
}
int32_t D = (dy<<1) - dx;
int32_t y = y0;
for (int32_t i = x0; i < x1; i++) {
framebuffer.fb[y*framebuffer.width + i] = color;
if (D > 0) {
y+=dir;
D -= dx<<1;
}
D += dy<<1;
}
}
void plotLineHigh(int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t color) {
int32_t dx = x1 - x0;
int32_t dy = y1 - y0;
int8_t dir = 1;
if (dx < 0) {
dir = -1; dx = -dx;
}
int32_t D = (dx<<1) - dy;
int32_t x = x0;
for (int32_t i = y0; i < y1; i++) {
framebuffer.fb[i*framebuffer.width + x] = color;
if (D > 0) {
x+=dir;
D -= dy<<1;
}
D += dx<<1;
}
}
void plotLine(int32_t x0, int32_t y0, int32_t x1, int32_t y1, uint32_t color) {
if (abs64(y1 - y0) < abs64(x1 - x0)) {
if (x0 > x1) {
plotLineLow(x1, y1, x0, y0, color);
} else{
plotLineLow(x0, y0, x1, y1, color);
}
} else {
if (y0 > y1){
plotLineHigh(x1, y1, x0, y0, color);
}
else {
plotLineHigh(x0, y0, x1, y1, color);
}
}
}
void readMultiboot(uint8_t *multibootData) {
// gun.org said so
//he totally meant gun.org and totally not gnu.org
framebuffer.initialized = memory.initialized = 0;
uint32_t size = *(uint32_t*)multibootData;
uint8_t *tag_ptr = multibootData + 8;
while (tag_ptr < multibootData + size) {
uint32_t type = *(uint32_t*)(tag_ptr);
uint32_t size = *(uint32_t*)(tag_ptr + 4);
tags[howManyTags] = type;
howManyTags++;
if (type == 0 && size == 8) {
break;
}
switch (type) {
case 8: {
framebuffer.initialized = 1;
framebuffer.fb = (uint32_t*)(uintptr_t)*(uint64_t*)(tag_ptr + 8);
framebuffer.pitch = *(uint32_t*)(tag_ptr + 16);
framebuffer.width = *(uint32_t*)(tag_ptr + 20);
framebuffer.height = *(uint32_t*)(tag_ptr + 24);
framebuffer.depth = *(uint8_t*)(tag_ptr + 28);
framebuffer.type = *(uint8_t*)(tag_ptr + 29);
break;
}
case 4: {
memory.initialized = 1;
memory.lower = *(uint32_t*)(tag_ptr + 8);
memory.upper = *(uint32_t*)(tag_ptr + 12);
break;
}
case 6: {
uint32_t entry_size = *(uint32_t*)(tag_ptr + 8);
// tag_ptr + 12 is entry version, which is 4 bytes long
mem_map_entries = (size-8)/(entry_size);
for (int i = 0; i < mem_map_entries; i++) {
mem_map[i].base_addr = *(uint64_t*)(tag_ptr + 16 + i*entry_size);
mem_map[i].length = *(uint64_t*)(tag_ptr + 24 + i*entry_size);
mem_map[i].type = *(uint32_t*)(tag_ptr + 32 + i*entry_size);
}
break;
}
case 21: {
load_base_addr = *(uint32_t*)(tag_ptr + 8);
break;
}
}
tag_ptr += (size + 7) & ~7;
}
}
void sleep(int millis) {
for (volatile int i = 0; i < millis * 100000; i++) {
__asm__ volatile ("nop");
}
}
void setIdtEntry(uint8_t index, void* isr, uint8_t flags) {
idtEntryT *entry = &idt[index];
entry->isr_low = (uint32_t)isr & 0xFFFF;
entry->isr_high = (uint32_t)isr >> 16;
entry->attributes = flags;
entry->reserved = 0;
entry->kernel_cs = 0x08; // kernel cs (gdt entry 1)
}
void setGdtEntry(uint8_t index, uint32_t limit, uint32_t base, uint8_t dpl, uint8_t type, uint8_t executable, uint8_t rw, uint8_t granularity, uint8_t size) {
gdtEntryT *entry = &gdt[index];
entry->limit_low = (uint16_t)limit;
entry->base_low = base & 0xFFFFFF;
entry->base_high = (uint8_t)(base>>24);
entry->limit_high = (limit >> 16) & 0xF;
entry->present = 1;
entry->accessed = 1;
entry->conforming_expand_down = 0;
entry->DPL = dpl;
entry->read_write = rw;
entry->code = executable;
entry->code_data_segment = type;
entry->available = 1;
entry->gran = granularity;
entry->big = size;
entry->long_mode = 0;
}
extern void* isr_stub_table[];
void setupTSS() {
uint32_t base = (uint32_t) &kerneltss;
uint32_t limit = sizeof kerneltss;
setGdtEntry(5, limit, base, 0, 0, 1, 0, 0, 0); // tss: present, system, 32 bit, ring 0, byte granularity
memset(&kerneltss, 0, sizeof kerneltss);
kerneltss.ss0 = 0x10; // kernel data segment
__asm__ volatile("ltr %%ax" : : "a"(5 << 3)); // TSS selector is GDT index 5
}
void setupGDT() {
setGdtEntry(0, 0, 0, 0, 0, 0, 0, 0, 0); // null segment
setGdtEntry(1, 0xFFFFF, 0x0, 0, 1, 1, 1, 1, 1); // kernel cs: present, executable, ring 0, page granularity
setGdtEntry(2, 0xFFFFF, 0x0, 0, 1, 0, 1, 1, 1); // kernel ds present, non-executable, ring 0, page granularity
setGdtEntry(3, 0xFFFFF, 0x0, 3, 1, 1, 1, 1, 1); // user cs: present, executable, ring 3, page granularity
setGdtEntry(4, 0xFFFFF, 0x0, 3, 1, 0, 1, 1, 1); // user ds: present, non-executable, ring 3, page granularity
// note: this is a flat memory model, so all segments take up the whole memory.
// this is because segmentation is fucking old and now we use paging.
gdtr.limit = sizeof(gdt) - 1;
gdtr.base = (uint32_t)&gdt;
__asm__ volatile("lgdt %0" : : "m"(gdtr)); // setting the gdt
// making sure that the new segments are loaded
__asm__ volatile(
"ljmp $0x08, $1f\n"
"1:\n"
"mov $0x10, %%ax\n"
"mov %%ax, %%ds\n"
"mov %%ax, %%es\n"
"mov %%ax, %%fs\n"
"mov %%ax, %%gs\n"
"mov %%ax, %%ss\n"
: : : "eax"
);
}
void setupPIC() {
// ICW1: init PICs
outb(0x20, 0x11);
outb(0xA0, 0x11);
io_wait();
// ICW2: remap irqs
outb(0x21, 0x20); // 32 offset (32-39)
outb(0xA1, 0x28); // 32+8 offset (40-47)
io_wait();
// ICW3: PIC wiring (IRQ2 connects master to slave)
outb(0x21, 0x04); // tell master theres a slave at irq2
outb(0xA1, 0x02); // tell slave it is a slave?
io_wait();
// ICW4: enable 8086 mode
outb(0x21, 0x01);
outb(0xA1, 0x01);
io_wait();
outb(0x21, 0xF8); // enable slave (bit2), kb (bit1), timer (bit0)
outb(0xA1, 0xFF); // disable all interrupts
}
void setupPIT() {
// pit command: setting mode 0x34 -> 00 11 010 0 (channel 00, 11 lobyte/hibyte, mode 010 = 2: rate generator, 16 bit binary)
/*
Modes:
0 0 0 = Mode 0 (interrupt on terminal count)
0 0 1 = Mode 1 (hardware re-triggerable one-shot)
0 1 0 = Mode 2 (rate generator)
0 1 1 = Mode 3 (square wave generator)
1 0 0 = Mode 4 (software triggered strobe)
1 0 1 = Mode 5 (hardware triggered strobe)
1 1 0 = Mode 2 (rate generator, same as 010b)
1 1 1 = Mode 3 (square wave generator, same as 011b)
*/
outb(0x43, 0x34);
io_wait();
// setting reload value, in two takes cause of lobite/hibyte
// note: the reload value is the number of cycles it does before sending the interrupt
// how the timer works is it increments a number until it reaches the reload and then resets it
// also note: the timer is 1.193.182 Hz
uint16_t reload = -1; // remember its 16 bits, this is the slowest it can go (0 is 65536). i can do software division later this is just debugging
outb(0x40, reload & 0xFF); // lo byte
io_wait();
outb(0x40, reload >> 8); // hi byte
}
void setupIDT() {
for (int i = 0; i < 64; i++) {
setIdtEntry(i, isr_stub_table[i], 0x8E); // present, ring 0, type 0xE (interrupt)
}
for (int i = 64; i < 256; i++) {
setIdtEntry(i,0,0); // non present, just to be sure
}
setIdtEntry(128, isr_stub_table[64], 0xEE); // present, ring 3, type 0xF (trap)
idtr.limit = sizeof idt - 1;
idtr.base = (uint32_t)&idt;
__asm__ volatile("lidt %0" : : "m"(idtr));
__asm__ volatile("andl $-16, %esp"); // align stack ig
__asm__ volatile ("sti"); // enable interrupts.
}
void setupMMU() {
//set all entries to not present
for(int i = 0; i < 1024; i++)
{
kernelpd[i] = 0b0;
}
// mapping the first 4mb of kernel
setupPageTable(kernelpt, 0, 1024, 0b011);
setupPageTable(kernelpt2, 1024, 1024, 0b011);
setupPageTable(kernelpt3, 1024*2, 1024, 0b011); // just use the heap atp dawg
// mapping framebuffer (max of 1MP)
setupPageTable(fbpt, (uint32_t)framebuffer.fb/0x1000, 1024, 0b011);
// mapping heap
setupPageTable(heappt, 1024*3, 1024, 0b011);
// stick it all inside 🤤 (with tags 011 which now means its present)
// remember all pages 0-767 are userspace
mapPageTable(kernelpd, kernelpt, 768, 0b011);
mapPageTable(kernelpd, kernelpt2, 769, 0b011);
mapPageTable(kernelpd, kernelpt3, 770, 0b011);
mapPageTable(kernelpd, heappt, 1022, 0b011);
mapPageTable(kernelpd, fbpt, 1023, 0b011);
framebuffer.fb = (1024*1023*0x1000); // set framebuffer position to new one
heap = (1024*769*0x1000);
loadPD(kernelpd);
}
int time = 0;
int kernelTime = 1;
mountT *disk;
fileT* currentDir;
uint8_t strcmp(uint8_t* s1, uint8_t* s2) {
if (*s1 == 0 && *s2 != 0) return 0; // if both are empty they are the same
while (*s1) {
if (*s1 != *s2 && ((*s1+0x20) != *s2) && ((*s1-0x20) != *s2)) return 0; // case insensitive!
s1++; s2++;
}
return 1;
}
int shownBitmap = 0;
void exception_handler(uint32_t interrupt, contextT context) {
if (interrupt == 33) {
// kb
uint8_t scancode = inb(0x60);
if (scancode < 0x80) { // Key pressed (not released) (we gon ignore shift for now)
// esc is b, bacPSace is c, tab is d, ctrl is e,, alt is i
// numlock scrolllock home uparr pgup grey- leftarr keypad5 rightarr grey+ end downarr pgdn ins del
//uint8_t x = " B1234567890-=\b\tqwertyuiop[]\nEasdfghjkl;'`\15\\zxcvbnm,./\15 I \151234567890MNOPQRSTUVWXYZ."[scancode];
//uint8_t x = " B1234567890-=\b\tQWERTYUIOP[]\nEASDFGHJKL;'`\15\\ZXCVBNM,./\15 I \151234567890MNOPQRSTUVWXYZ."[scancode];
uint8_t x = " B1234567890-=\b\tqwertyuiop[]\nEasdfghjkl;'`\15\\zxcvbnm,./\15 I \151234567890MNOPQRSTUVWXYZ."[scancode];
ttyPutChar(x);
stdin[stdinptr] = x;
stdinptr++;
} else {
scancode -= 0x80;
// handle shift ig
}
outb(0x20, 0x20); // EOI
} else if (interrupt == 32) {
__asm__ ("cli");
kernelTime = 1;
outb(0x20, 0x20); // EOI
// save context
if ((context.cs & 3) != 0) {
// we arent kernel
pcbt[procindex]->context = context;
}
tick();
} else if (interrupt == 14) {
uint32_t cr2; // contains the virtual address that triggered a page fault, allegedly
asm volatile("mov %%cr2, %0" : "=r"(cr2));
ttyPrint("Page fault at ");
ttyPrintHex(cr2);
if (kernelTime) {
ttyPrint(" @ kernel. Context\n");
} else {
ttyPrint(" @ PID ");
ttyPrintHex(pcbt[procindex]->pid);
ttyPrint(". Context\n");
}
dumpContext(context, 0);
asm("hlt");
} else if (interrupt == 13) {
ttyPrint("General Protection Fault!");
asm("hlt");
} else {
outb(0xA0, 0x20); // EOI to slave
outb(0x20, 0x20); // EOI
ttyPrint("IRQ ");
ttyPrintHex(interrupt);
ttyPrint("\n");
asm ("hlt");
}
}
int syscall_handler(contextT context) {
kernelTime=1;
pcbt[procindex]->context = context; // doesnt hurt!
uint32_t code = context.eax;
uint32_t arg1 = context.ebx;
uint32_t arg2 = context.ecx;
uint32_t arg3 = context.edx;
/*
ttyPrint("SYSCALL ");
ttyPrintHex(code);
ttyPrint(" ARG1 ");
ttyPrintHex(arg1);
ttyPrint(" ARG2 ");
ttyPrintHex(arg2);
ttyPrint(" ARG3 ");
ttyPrintHex(arg3);
ttyPrint("\n");*/
// SYSTEM. CALLS.
switch (code) {
case 1:
// Kill process. (now a zombie)
pcbt[procindex]->status = TERMINATED;
ttyPrint("Process exited with code ");
ttyPrintNumber(arg1);
ttyPutChar('\n');
return 0;
case 2:
// Fork process.
processT* child = kalloc(sizeof(processT));
processT* parent = pcbt[procindex];
pcbt[processcount++] = child;
// Process metadata
child->pid = incpid++;;
child->pd = kalloc_aligned(4096, 0x1000);
child->status = CREATED;
// Copy context from parent
memcpy(&child->context, &parent->context, sizeof(contextT));
// Copy lower PD half from parent
for(int i = 0; i < 768; i++) {
uint32_t* pt = kalloc_aligned(4096, 0x1000); // allocates a pt in the heap
child->pd[i] = ((uint32_t)pt - 0xC0000000) | (parent->pd[i] & 0xFFF);
for (int j = 0; j < 1024; j++) {
pt[j] = ((uint32_t*)((parent->pd[i] & 0xFFFFF000) + 0xC0000000))[j];
}
}
// Copy higher PD half from kernel
for(int i = 768; i < 1024; i++) child->pd[i] = kernelpd[i];
// Instantiating the stacks
mmap(0xbffff000, 0x1000, child->pd, 0b111); // process stack
mmap(0xbfffe000, 0x1000, child->pd, 0b011); // kernel stack
// Calculate physical (actually, higher-half-identity-mapped) address of CHILD'S stack
uint32_t ptiCS = 0xbffff000 >> 12; // the index of the page
uint16_t pdiCS = ptiCS >> 10; // the index of the pde in the pd
uint32_t ptiOffsetCS = ptiCS % 1024; // the index of the page in the pde
uint32_t physCS = ((((uint32_t*)((child->pd[pdiCS] & 0xFFFFF000) + 0xC0000000))[ptiOffsetCS] & 0xFFFFF000));
// Map child stack in parent's PD
uint32_t ptiPS = 0xbfffd000 >> 12; // the index of the page
uint16_t pdiPS = ptiPS >> 10; // the index of the pde in the pd
uint32_t ptiOffsetPS = ptiPS % 1024; // the index of the page in the pde
((uint32_t*)((parent->pd[pdiPS] & 0xFFFFF000) + 0xC0000000))[ptiOffsetPS] = physCS | 0b011;
uint32_t ptiPSS = 0xbffff000 >> 12; // the index of the page
uint16_t pdiPSS = ptiPSS >> 10; // the index of the pde in the pd
uint32_t ptiOffsetPSS = ptiPSS % 1024; // the index of the page in the pde
// Copy parent's stack data to the child
memcpy(0xbfffd000, 0xbffff000, 0x1000);
// Unmap child stack in parent's PD
((uint32_t*)((parent->pd[pdiPS] & 0xFFFFF000) + 0xC0000000))[ptiOffsetPS] = 0x010;
// Loading the stacks in the child metadata.
child->kernelStack = 0xbffff000;
child->context.eflags = 0x200;
child->context.eax = 0x0;
child->status = READY;
return child->pid;
case 3:
// Read, in this case tty only
return 0;
case 4:
// Write, in this case tty only
for (uint32_t i = 0; i < arg3; i++) {
ttyPutChar(*((uint8_t*)arg2+i));
}
return 0;
default:
ttyPrint("Unknown system call: ");
ttyPrintNumber(code);
ttyPutChar('\n');
return 0;
}
return 0;
}
void dumpContext(contextT context, int canDump) {
/*In the order of contextT*/
/*
uint32_t edi, esi, ebp, esp;
uint32_t ebx, edx, ecx, eax;
// irq data
uint32_t eip, cs, eflags, irqesp, ss;
*/
ttyPrintHex(context.edi);
ttyPutChar(' ');
ttyPrintHex(context.esi);
ttyPutChar(' ');
ttyPrintHex(context.ebp);
ttyPutChar(' ');
ttyPrintHex(context.esp);
ttyPutChar('\n');
ttyPrintHex(context.ebx);
ttyPutChar(' ');
ttyPrintHex(context.edx);
ttyPutChar(' ');
ttyPrintHex(context.ecx);
ttyPutChar(' ');
ttyPrintHex(context.eax);
ttyPutChar('\n');
ttyPrintHex(context.eip);
ttyPutChar(' ');
ttyPrintHex(context.cs);
ttyPutChar(' ');
ttyPrintHex(context.eflags);
ttyPutChar(' ');
ttyPrintHex(context.irqesp);
ttyPutChar(' ');
ttyPrintHex(context.ss);
ttyPutChar('\n');
if (canDump) {
ttyPrint("EIP VAL: ");
ttyPrintHex(*(uint32_t*)context.eip);
ttyPrint(" ESP VAL: ");
ttyPrintHex(*(uint32_t*)(context.irqesp-4));
ttyPutChar('\n');
}
}
processT* procstore;
__attribute__((noreturn)) void runProcess(processT* proc) {
procstore = proc;
//ttyPrint("LOAD:\n");
//dumpContext(proc->context, 1);
kerneltss.esp0 = procstore->kernelStack;
__asm__ volatile (
"mov %%ecx, %%cr3\n"
: : "c" (((uint32_t)procstore->pd)-0xC0000000)
);
kernelTime=0;
__asm__ volatile (
"mov $((4 * 8) | 3), %%ax\n" // ring 3 data segment (0x20), 4th gdt entry
"mov %%ax, %%ds\n"
"mov %%ax, %%es\n"
"mov %%ax, %%fs\n"
"mov %%ax, %%gs\n" // SS is handled by iret
// Setting up stack frame for IRET: ip, cs, flags, sp, ss
"push $((4 * 8) | 3)\n" // SS (again, ring 3 data segment)
"push 44(%[ctx])\n" // SP
"pushf\n" // EFLAGS
"pop %%eax\n"
"or $0x200, %%eax\n" // pushf fucks eflags, reenable interrupts
"push %%eax\n"
"push $((3 * 8) | 3)\n" // CS (ring 3 code segment, 3rd gdt entry)
"push 32(%[ctx])\n" // IP
"mov 0(%[ctx]), %%edi\n"
"mov 4(%[ctx]), %%esi\n"
"mov 8(%[ctx]), %%ebp\n"
"mov 20(%[ctx]), %%edx\n"
"mov 24(%[ctx]), %%ecx\n"
"mov 28(%[ctx]), %%eax\n"
"mov 16(%[ctx]), %%ebx\n"
"iret"
:
: [ctx] "r" (&procstore->context)
: "eax","ecx","edx","esi","edi","memory"
);
__builtin_unreachable();
}