-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.c
More file actions
5784 lines (5345 loc) · 218 KB
/
Copy pathkernel.c
File metadata and controls
5784 lines (5345 loc) · 218 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.h"
#include "net.h"
#include "tls.h"
#include "bootdefs.h"
#include "minifs.h"
#include "ide.h"
#include "block.h"
#include "sched.h"
#include "vga_fb.h"
#include "pcspk.h"
#include "sb16.h"
#include "smp.h"
#include "rtc.h"
#include "lz4_kernel.h"
#define XXH_STATIC_LINKING_ONLY
#include "xxhash.h"
#include "stb/stb_api.h"
#include "zip.h"
/* ================================================================
* Serial console (COM1, 16550 UART) — mirrors VGA, drives input
* ================================================================ */
#define COM1 0x3F8
void serial_init(void) {
outb(COM1 + 1, 0x00); /* disable interrupts */
outb(COM1 + 3, 0x80); /* enable DLAB */
outb(COM1 + 0, 0x01); /* divisor lo -> 115200 baud */
outb(COM1 + 1, 0x00); /* divisor hi */
outb(COM1 + 3, 0x03); /* 8 bits, no parity, one stop */
outb(COM1 + 2, 0xC7); /* enable FIFO, clear, 14-byte threshold */
outb(COM1 + 4, 0x0B); /* IRQs off, RTS/DSR set */
}
static int serial_tx_ready(void) { return inb(COM1 + 5) & 0x20; }
static int serial_rx_ready(void) { return inb(COM1 + 5) & 0x01; }
void serial_putc(char c) {
while (!serial_tx_ready());
outb(COM1, (unsigned char)c);
}
void serial_puts(const char *s) { while (*s) serial_putc(*s++); }
int serial_available(void) { return serial_rx_ready(); }
int serial_getc(void) { return serial_rx_ready() ? (int)inb(COM1) : -1; }
static int console_getc(void); /* defined in the shell section */
/* ================================================================
* VGA driver
* ================================================================ */
static int vga_mode13h; /* nonzero when a graphics program owns the display */
/* Set when a graphics program activates SYS_VGA_MODE and cleared when the
* desktop is restored on return. A program (nuklear) may clear vga_mode13h
* itself before exiting; this flag is what guarantees the desktop is still
* redrawn on return, otherwise the framebuffer stays frozen on the program's
* last frame and the cursor is never re-established. */
static int graphics_program_ran;
static int vga_x, vga_y;
static char vga_color = 0x07; /* light grey on black */
/* Console scrollback: a ring of lines that scrolled off the top of the VGA
* screen. Captured lazily from vga_scroll(); viewed with PageUp/PageDown. */
static char *sb_ring;
static int sb_head, sb_count, sb_inited;
static void sb_capture_row0(void);
static void sb_init(void);
static inline unsigned vga_offset(int x, int y) { return (unsigned)(y * VGA_COLS + x) * 2; }
void vga_clear(void) {
int i;
for (i = 0; i < VGA_COLS * VGA_ROWS; i++) {
VGA_BASE[i * 2] = ' ';
VGA_BASE[i * 2 + 1] = vga_color;
}
vga_x = vga_y = 0;
vga_set_cursor(0, 0);
if (sb_ring) { sb_head = sb_count = 0; }
}
void vga_set_cursor(int x, int y) {
unsigned short pos = (unsigned short)(y * VGA_COLS + x);
unsigned char lo = pos & 0xFF;
unsigned char hi = (pos >> 8) & 0xFF;
__asm__ volatile(
"movw $0x3D4, %%dx\n\t"
"movb $0x0F, %%al\n\t"
"outb %%al, %%dx\n\t"
"movb %b0, %%al\n\t"
"outb %%al, %%dx\n\t"
"movb $0x0E, %%al\n\t"
"outb %%al, %%dx\n\t"
"movb %b1, %%al\n\t"
"outb %%al, %%dx"
:
: "r"((unsigned long)lo), "r"((unsigned long)hi)
: "ax", "dx"
);
}
void vga_scroll(void) {
int y, x;
sb_capture_row0();
for (y = 0; y < VGA_ROWS - 1; y++) {
for (x = 0; x < VGA_COLS; x++) {
unsigned src = vga_offset(x, y + 1);
unsigned dst = vga_offset(x, y);
VGA_BASE[dst] = VGA_BASE[src];
VGA_BASE[dst + 1] = VGA_BASE[src + 1];
}
}
for (x = 0; x < VGA_COLS; x++) {
unsigned off = vga_offset(x, VGA_ROWS - 1);
VGA_BASE[off] = ' ';
VGA_BASE[off + 1] = vga_color;
}
vga_y = VGA_ROWS - 1;
}
void vga_newline(void) {
vga_x = 0;
vga_y++;
if (vga_y >= VGA_ROWS) vga_scroll();
}
/* ---- Console scrollback ring ----
*
* The ring stores complete text lines that have scrolled off the top of the
* 25-row VGA screen. Each line is VGA_COLS bytes (the character cell only;
* colour is regenerated as the default attribute on re-display). The ring is
* heap-allocated on first use and is a circular buffer of SCROLLBACK_ROWS
* slots; `clear` resets the cursor (it does not free the ring, which would
* be re-allocated again the next time a line scrolls). */
#define SCROLLBACK_ROWS 4096
static void sb_init(void) {
sb_ring = (char *)kmalloc((unsigned long)SCROLLBACK_ROWS * VGA_COLS);
sb_inited = sb_ring ? 1 : -1;
sb_head = sb_count = 0;
}
/* Called from vga_scroll() immediately before row 0 is overwritten: copies
* the row that is about to leave the screen into the ring. */
static void sb_capture_row0(void) {
if (sb_inited == 0) sb_init();
if (sb_inited != 1) return;
int idx = (sb_head + sb_count) % SCROLLBACK_ROWS;
for (int x = 0; x < VGA_COLS; x++)
sb_ring[(unsigned long)idx * VGA_COLS + x] = VGA_BASE[vga_offset(x, 0)];
if (sb_count < SCROLLBACK_ROWS) sb_count++;
else sb_head = (sb_head + 1) % SCROLLBACK_ROWS;
}
/* Toggle the hardware text cursor. bit 5 of VGA index 0x0A disables the
* cursor; clearing it brings the cursor back. */
void vga_cursor_enable(int on) {
outb(0x3D4, 0x0A);
unsigned char v = inb(0x3D5);
if (on) v &= 0xDF; else v |= 0x20;
outb(0x3D5, v);
}
static void vga_raw_space(void) {
unsigned off = vga_offset(vga_x, vga_y);
VGA_BASE[off] = ' ';
VGA_BASE[off + 1] = vga_color;
vga_x++;
if (vga_x >= VGA_COLS) vga_newline();
}
/* Console output capture used by shell redirection. While a capture is
* active every character produced through vga_putc is accumulated in memory
* instead of reaching the screen, and the shell commits the result to a
* ramdisk file once the command returns. */
#define REDIR_INITIAL_CAP (16UL * 1024)
#define REDIR_MAX_BYTES (16UL * 1024 * 1024)
static char *redir_buf;
static unsigned long redir_len;
static unsigned long redir_cap;
static int redir_active;
static int redir_overflow;
static int redirect_suspend(void);
static int redirect_begin(void);
static int redirect_commit(const char *path, int append_mode);
static void redirect_resume(int was);
static int redir_grow(void) {
unsigned long want = redir_cap ? redir_cap * 2 : REDIR_INITIAL_CAP;
if (want > REDIR_MAX_BYTES) return 0;
char *grown = krealloc(redir_buf, want);
if (!grown) return 0;
redir_buf = grown;
redir_cap = want;
return 1;
}
void vga_putc(char c) {
if (redir_active) {
if (redir_len < redir_cap || redir_grow()) redir_buf[redir_len++] = c;
else redir_overflow = 1;
return;
}
serial_putc(c);
if (vga_fb_active) {
if (c == '\n') serial_putc('\r');
vga_fb_putc_term(c);
return;
}
if (vga_mode13h) {
if (c == '\n') serial_putc('\r');
return;
}
if (c == '\n') { serial_putc('\r'); vga_newline(); vga_set_cursor(vga_x, vga_y); return; }
if (c == '\r') { vga_x = 0; vga_set_cursor(vga_x, vga_y); return; }
if (c == '\t') {
int spaces = 8 - (vga_x & 7);
while (spaces--) vga_raw_space();
vga_set_cursor(vga_x, vga_y);
return;
}
if (c == '\b') {
if (vga_x > 0) {
vga_x--;
unsigned off = vga_offset(vga_x, vga_y);
VGA_BASE[off] = ' ';
VGA_BASE[off + 1] = vga_color;
vga_set_cursor(vga_x, vga_y);
}
return;
}
unsigned off = vga_offset(vga_x, vga_y);
VGA_BASE[off] = c;
VGA_BASE[off + 1] = vga_color;
vga_x++;
if (vga_x >= VGA_COLS) vga_newline();
vga_set_cursor(vga_x, vga_y);
}
void vga_puts(const char *s) {
while (*s) vga_putc(*s++);
}
/* ================================================================
* Keyboard driver — PS/2 scancode set 1 (US qwerty)
* ================================================================ */
static const unsigned char kbd_us[128] = {
0, 0x1B, '1','2','3','4','5','6','7','8','9','0','-','=','\b',
'\t','q','w','e','r','t','y','u','i','o','p','[',']','\n',
0, 'a','s','d','f','g','h','j','k','l',';','\'','`',
0, '\\','z','x','c','v','b','n','m',',','.','/', 0,
'*', 0, ' ', 0,
/* F1-F10 */ 0,0,0,0,0,0,0,0,0,0,
/* numlock, scrlk */ 0,0,
/* home, up, pgup, - */ 0,0,0,'-',
/* left, center, right */ 0,0,0,
/* +, end, down, pgdn, ins, del */ '+',0,0,0,0,0,
0,0,0,
/* F11-F12 */ 0,0,
0,0,0,0,0,0,0
};
static const unsigned char kbd_us_shift[128] = {
0, 0x1B, '!','@','#','$','%','^','&','*','(',')','_','+','\b',
'\t','Q','W','E','R','T','Y','U','I','O','P','{','}','\n',
0, 'A','S','D','F','G','H','J','K','L',':','"','~',
0, '|','Z','X','C','V','B','N','M','<','>','?', 0,
'*', 0, ' ', 0,
0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, '-',0,0,0,0,
'+', 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
static int kbd_shift;
static int kbd_ctrl;
static int kbd_alt;
/* PS/2 set 1 arrow keys arrive as E0-prefixed make codes; they are
* translated into the same three-byte CSI sequence a serial terminal
* sends (ESC [ A / ESC [ B) and buffered here. */
#define KBD_QUEUE_LEN 8
static unsigned char kbd_queue[KBD_QUEUE_LEN];
static int kbd_q_head, kbd_q_tail;
static int kbd_e0;
/* Raw keyboard mode for DOOM: when enabled, PS/2 make/break codes are
* pushed into a separate queue so the caller sees both press and release
* events. The raw queue stores bytes with bit 7 set for break codes. */
#define KBD_RAW_LEN 64
static unsigned char kbd_raw[KBD_RAW_LEN];
static int kbd_raw_head, kbd_raw_tail;
static int kbd_raw_mode; /* 1 = raw mode (DOOM), 0 = translated mode (shell) */
static void kbd_q_push(unsigned char c) {
int next = (kbd_q_tail + 1) % KBD_QUEUE_LEN;
if (next == kbd_q_head) return;
kbd_queue[kbd_q_tail] = c;
kbd_q_tail = next;
}
static void kbd_raw_push(unsigned char c) {
int next = (kbd_raw_tail + 1) % KBD_RAW_LEN;
if (next == kbd_raw_head) return;
kbd_raw[kbd_raw_tail] = c;
kbd_raw_tail = next;
}
static int kbd_q_empty(void) { return kbd_q_head == kbd_q_tail; }
static int kbd_q_pop(void) {
if (kbd_q_empty()) return -1;
unsigned char c = kbd_queue[kbd_q_head];
kbd_q_head = (kbd_q_head + 1) % KBD_QUEUE_LEN;
return (int)c;
}
int kbd_available(void) {
unsigned char s;
__asm__ volatile("inb $0x64, %0" : "=a"(s));
/* Output-buffer full AND not auxiliary: the PS/2 controller shares one
* port for keyboard and mouse, and bit 5 marks mouse data. The keyboard
* poll must not consume mouse bytes (the IRQ12 handler owns those), or a
* click would be misread as a scancode. */
return (s & 1) && !(s & 0x20);
}
int kbd_read(void) {
if (!kbd_q_empty()) return kbd_q_pop();
while (!kbd_available()) __asm__ volatile("pause");
unsigned char sc;
__asm__ volatile("inb $0x60, %0" : "=a"(sc));
/* Raw mode (DOOM): push make/break codes with E0 prefix preserved.
* Make codes are sent as-is; break codes have bit 7 set.
* E0 prefix is pushed as 0xE0 so the reader can detect extended keys. */
if (kbd_raw_mode) {
if (sc == KEY_E0) { kbd_e0 = 1; return -1; }
if (kbd_e0) {
kbd_e0 = 0;
kbd_raw_push(0xE0); kbd_raw_push(sc); /* E0 make or break */
return -1;
}
/* Normal make or break */
kbd_raw_push(sc);
return -1;
}
/* The E0 prefix must be tested before the release check: 0xE0 has the
* high bit set, so testing the release bit first swallows every
* extended-key prefix and arrows/PageUp/PageDown never translate. */
if (sc == KEY_E0) { kbd_e0 = 1; return -1; }
if (sc & 0x80) { /* key release */
sc &= 0x7F;
if (sc == KEY_LSHIFT || sc == KEY_RSHIFT) kbd_shift = 0;
if (sc == KEY_LCTRL) kbd_ctrl = 0;
if (sc == KEY_LALT) kbd_alt = 0;
kbd_e0 = 0; /* a release ends any E0 sequence */
return -1;
}
if (kbd_e0) {
kbd_e0 = 0;
/* Ctrl+arrow keys move the framebuffer terminal window */
if (kbd_ctrl && vga_fb_active) {
if (sc == KEY_UP) { vga_fb_move_terminal(0, -1); return -1; }
if (sc == KEY_DOWN) { vga_fb_move_terminal(0, 1); return -1; }
if (sc == KEY_LEFT) { vga_fb_move_terminal(-1, 0); return -1; }
if (sc == KEY_RIGHT) { vga_fb_move_terminal( 1, 0); return -1; }
}
/* Alt+arrow keys snap the window to the matching screen half. */
if (kbd_alt && vga_fb_active) {
if (sc == KEY_UP) { vga_fb_snap_window(TILING_TOP); return -1; }
if (sc == KEY_DOWN) { vga_fb_snap_window(TILING_BOTTOM); return -1; }
if (sc == KEY_LEFT) { vga_fb_snap_window(TILING_LEFT); return -1; }
if (sc == KEY_RIGHT) { vga_fb_snap_window(TILING_RIGHT); return -1; }
if (sc == KEY_HOME) { vga_fb_snap_window(TILING_TOP_LEFT); return -1; }
if (sc == KEY_END) { vga_fb_snap_window(TILING_BOTTOM_RIGHT); return -1; }
}
if (sc == KEY_UP) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_ARR_UP);
} else if (sc == KEY_DOWN) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_ARR_DOWN);
} else if (sc == KEY_RIGHT) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_ARR_RIGHT);
} else if (sc == KEY_LEFT) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_ARR_LEFT);
} else if (sc == KEY_HOME) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_HOME_SEQ);
} else if (sc == KEY_END) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI); kbd_q_push(KEY_END_SEQ);
} else if (sc == KEY_PGUP) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI);
kbd_q_push(KEY_PGUP_SEQ); kbd_q_push(KEY_TILDE);
} else if (sc == KEY_PGDN) {
kbd_q_push(KEY_ESC); kbd_q_push(KEY_CSI);
kbd_q_push(KEY_PGDN_SEQ); kbd_q_push(KEY_TILDE);
}
return -1;
}
if (sc == KEY_LSHIFT || sc == KEY_RSHIFT) { kbd_shift = 1; return -1; }
if (sc == KEY_LCTRL) { kbd_ctrl = 1; return -1; }
if (sc == KEY_LALT) { kbd_alt = 1; return -1; }
/* F11: toggle fullscreen, F5: reset terminal position */
if (vga_fb_active) {
if (sc == KEY_F11) { vga_fb_toggle_fullscreen(); return -1; }
if (sc == KEY_F5) { vga_fb_move_terminal(0, 0); return -1; }
}
/* Alt = WM modifier: resize, quadrant snap, reset, minimize and close. */
if (vga_fb_active && kbd_alt) {
char ch = kbd_us[sc];
if (sc == KEY_ENTER) { vga_fb_toggle_fullscreen(); return -1; }
if (sc == KEY_HOME) { vga_fb_snap_window(TILING_TOP_LEFT); return -1; }
if (sc == KEY_END) { vga_fb_snap_window(TILING_BOTTOM_RIGHT); return -1; }
if (ch == 'm' || ch == 'M') { vga_fb_toggle_minimize(); return -1; }
if (ch == 'x' || ch == 'X') { vga_fb_close_active(); return -1; }
if (ch == 'q' || ch == 'Q') { vga_fb_close_active(); return -1; }
if (ch == '[') { vga_fb_resize(-1, 0); return -1; }
if (ch == ']') { vga_fb_resize(1, 0); return -1; }
if (ch == '-') { vga_fb_resize(-1, -1); return -1; }
if (ch == '=') { vga_fb_resize(1, 1); return -1; }
if (ch == '0') { vga_fb_reset_default(); return -1; }
}
if (kbd_shift)
return kbd_us_shift[sc];
else
return kbd_us[sc];
}
/* Restore the translated keyboard mode the shell expects after a user
* program returns. A graphics program (DOOM) enables raw mode via
* SYS_KBD_RAW(1) but does not always disable it on exit; if left set, the
* shell's translated readline never sees PS/2 keystrokes and the desktop
* appears frozen until a serial byte unblocks it. */
void kbd_reset_for_shell(void) {
kbd_raw_mode = 0;
kbd_q_head = kbd_q_tail = 0;
kbd_raw_head = kbd_raw_tail = 0;
kbd_e0 = 0;
}
/* ================================================================
* Memory allocator — dlmalloc backend over the fixed kernel heap.
* kmalloc/free/calloc/realloc delegate to a private mspace rooted at
* [HEAP_BASE, HEAP_BASE+HEAP_SIZE) (see third_party/dlmalloc). The
* mspace is built with HAVE_MORECORE=0 and HAVE_MMAP=0, so it can
* never grow beyond the heap; an exhausted heap returns 0 exactly
* like the first-fit allocator it replaced.
* ================================================================ */
#define ALIGN_UP(x, a) (((x) + (a) - 1) & ~((a) - 1))
/* ---- Physical memory map (identity-mapped 0..1GB by the bootloader) ----
* The user-window and kernel-heap layout lives in progs/minios_abi.h (single
* source of truth) and is surfaced through kernel.h, so a layout change is a
* one-line edit in one file instead of a cross-file address hunt.
* 0x00000000 .. 0x00100000 BIOS / kernel image / page tables / stack
* 0x00400000 .. 0x0C000000 user program region (ELF load addr + brk)
* 0x0C000000 .. 0x18000000 192 MB kernel heap (HEAP_BASE/HEAP_SIZE)
*/
#define EFAULT (-14)
#define MSR_EFER 0xC0000080
#define EFER_NXE 0x00000800
#define PT_FLAGS_PS 0x080
#define PT_FLAGS_NX 0x8000000000000000ULL
#define PT_ADDR_MASK 0x000FFFFFFFFFF000ULL
#define PT_USER_ENTRY (0x003 | PT_FLAGS_USER) /* present | rw | user */
#define PT_USER_NX_ENTRY ((unsigned long)(PT_USER_ENTRY | PT_FLAGS_NX))
/* Asm-safe (no UL suffix) mirror of the user window for the syscall-entry
* return discriminator; the trampoline is a raw string literal, so the C
* preprocessor cannot paste the UL-suffixed macros into it. The values must
* track minios_abi.h; the _Static_asserts below prove they do. */
#define USER_WIN_LO 0x00400000
#define USER_WIN_HI 0x0C000000
#define STR_(x) #x
#define STR(x) STR_(x)
/* The kernel's layout constants are derived from minios_abi.h, and the
* asm-safe mirrors above are checked against them at compile time, so a
* layout edit in the ABI header can never silently leave the syscall return
* discriminator, the page-table zone sizing or a ring-3 program out of step. */
_Static_assert(USER_WIN_LO == MINIOS_USER_LOAD_BASE, "USER_WIN_LO drift");
_Static_assert(USER_WIN_HI == MINIOS_USER_LOAD_END, "USER_WIN_HI drift");
_Static_assert(USER_LOAD_BASE == MINIOS_USER_LOAD_BASE, "USER_LOAD_BASE drift");
_Static_assert(USER_LOAD_END == MINIOS_USER_LOAD_END, "USER_LOAD_END drift");
_Static_assert(USER_STACK_TOP == MINIOS_USER_STACK_TOP, "USER_STACK_TOP drift");
_Static_assert(USER_BRK_END == MINIOS_USER_BRK_END, "USER_BRK_END drift");
_Static_assert(HEAP_BASE == MINIOS_HEAP_BASE, "HEAP_BASE drift");
_Static_assert(HEAP_SIZE == MINIOS_HEAP_SIZE, "HEAP_SIZE drift");
static inline unsigned long rdmsr(unsigned msr);
static inline void wrmsr(unsigned msr, unsigned long val);
/* Build 4 KB page tables for the whole user window and enable the NX bit
* (EFER.NXE). Every user page is present, writable, user-accessible and
* non-executable; the ELF loader later clears NX on the pages a program's
* executable segments occupy, so a ring-3 program can only execute the text
* it actually contains. The page tables live in the dedicated
* PT_USER_TABLES_ADDR zone (0x10000, in the boot staging buffer below the
* kernel link base), never in the heap (the ramdisk data area is
* heap-backed and its final size is only discovered at boot, so heap-resident
* tables could be overwritten by a later reservation) and never inside the
* kernel image: the zone is BELOW 0x100000, so kernel code, data and .bss
* can never reach it in the plain build or under KASLR. That zone stays
* supervisor, so a ring-3 program cannot reach the tables that govern it.
* The per-page isolation replaces the coarse 2 MB leaves the boot path
* installs, so kernel image, heap, page tables, VGA and MMIO stay supervisor,
* and the U/S bit stops a ring-3 program from reading or writing kernel
* memory. */
static void mm_setup_protections(void) {
volatile unsigned long *pml4 = (volatile unsigned long *)PT_PML4_ADDR;
volatile unsigned long *pdpt = (volatile unsigned long *)PT_PDPT_ADDR;
volatile unsigned long *pd = (volatile unsigned long *)PT_PD_ADDR;
unsigned long lo = USER_LOAD_BASE >> PT_PD_INDEX_SHIFT;
unsigned long hi = (USER_LOAD_END - 1) >> PT_PD_INDEX_SHIFT;
unsigned long i;
/* Guard against the kernel image growing into the user window: the whole
* kernel (code + .bss) must end below USER_LOAD_BASE or the .bss would
* be mapped where user programs load and silently corrupt them. */
extern char _kernel_end[];
if ((unsigned long)_kernel_end > USER_LOAD_BASE) {
kprintf("mm: kernel image reaches 0x%lx, must stay below 0x%lx\n",
(unsigned long)_kernel_end, USER_LOAD_BASE);
return;
}
if (hi - lo + 1 > PT_USER_TABLES_BYTES / 0x1000) {
kprintf("mm: user window needs more page table space\n");
return;
}
wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NXE);
pml4[0] |= (unsigned long)PT_FLAGS_USER;
pdpt[0] |= (unsigned long)PT_FLAGS_USER;
for (i = lo; i <= hi; i++) {
unsigned long *pt = (unsigned long *)PT_USER_TABLES_ADDR +
(i - lo) * 0x1000 / sizeof(unsigned long);
unsigned long phys = i << PT_PD_INDEX_SHIFT;
unsigned long k;
for (k = 0; k < PT_PD_ENTRIES; k++)
pt[k] = (phys + k * 0x1000) | PT_USER_NX_ENTRY;
pd[i] = ((unsigned long)pt) | PT_USER_ENTRY;
}
__asm__ volatile("mov %%cr3, %%rax; mov %%rax, %%cr3" ::: "rax", "memory");
/* Map the linear framebuffer into the user window at virtual FB_ADDR, in
* the reserved tail above the DOOM back-buffer and the brk cap (so a
* memory-hungry program's heap can never grow over it). The physical base
* and stride come from the VBE probe (Mode 13h at 0xA0000 when
* unavailable). The mapping is RW with NX set: it is data, not
* executable. */
{
unsigned long fb_vaddr = (unsigned long)FB_ADDR;
unsigned long fb_pd_idx = fb_vaddr >> PT_PD_INDEX_SHIFT;
unsigned long fb_pt_off = (fb_vaddr & 0x1FFFFF) >> 12;
unsigned long *fb_pt = (unsigned long *)PT_USER_TABLES_ADDR +
(fb_pd_idx - lo) * 0x1000 /
sizeof(unsigned long);
unsigned long fb_bytes = (unsigned long)fb_pitch * (unsigned long)fb_height;
unsigned long fb_pages = (fb_bytes + 0xFFF) >> 12;
unsigned long k;
if (fb_pages == 0) fb_pages = 1;
if (fb_pages > PT_PD_ENTRIES - fb_pt_off)
fb_pages = PT_PD_ENTRIES - fb_pt_off;
for (k = 0; k < fb_pages; k++)
fb_pt[fb_pt_off + k] = (fb_phys_base + k * 0x1000) | PT_USER_NX_ENTRY;
}
/* Map a kernel-heap back-buffer into the user window at DOOM_BACKBUF_ADDR
* so a ring-3 graphics program (DOOM) can render off-screen; the kernel
* composites it onto the desktop on SYS_DOOM_FRAME. The heap is identity
* mapped, so the physical frame is the returned virtual address. */
{
unsigned long bb_vaddr = DOOM_BACKBUF_ADDR;
unsigned long bb_pd_idx = bb_vaddr >> PT_PD_INDEX_SHIFT;
unsigned long bb_pt_off = (bb_vaddr & 0x1FFFFF) >> 12;
unsigned long *bb_pt = (unsigned long *)PT_USER_TABLES_ADDR +
(bb_pd_idx - lo) * 0x1000 /
sizeof(unsigned long);
unsigned char *buf = (unsigned char *)kmalloc(DOOM_W * DOOM_H);
unsigned long phys;
unsigned long k;
if (buf == 0) return;
phys = (unsigned long)buf;
for (k = 0; k < (DOOM_W * DOOM_H + 0xFFF) >> 12; k++)
bb_pt[bb_pt_off + k] = (phys + k * 0x1000) | PT_USER_NX_ENTRY;
}
/* Map a kernel-heap back-buffer for Nuklear UI apps (the node editor) in
* the same way, at its own fixed address; the kernel composites it as a
* titled window on SYS_NK_FRAME (220). */
{
unsigned long bb_vaddr = NK_BACKBUF_ADDR;
unsigned long bb_pd_idx = bb_vaddr >> PT_PD_INDEX_SHIFT;
unsigned long bb_pt_off = (bb_vaddr & 0x1FFFFF) >> 12;
unsigned long *bb_pt = (unsigned long *)PT_USER_TABLES_ADDR +
(bb_pd_idx - lo) * 0x1000 /
sizeof(unsigned long);
unsigned char *buf = (unsigned char *)kmalloc(NK_W * NK_H);
unsigned long phys;
unsigned long k;
if (buf == 0) return;
phys = (unsigned long)buf;
for (k = 0; k < (NK_W * NK_H + 0xFFF) >> 12; k++)
bb_pt[bb_pt_off + k] = (phys + k * 0x1000) | PT_USER_NX_ENTRY;
}
}
/* Set or clear the NX bit on the single 4 KB page holding vaddr. The page
* table for vaddr is the one the user-window PD entry points at; a 2 MB
* leaf (should not appear inside the window after mm_setup_protections) is
* left untouched. */
static void mm_user_pte_update(unsigned long vaddr, int exec) {
volatile unsigned long *pd = (volatile unsigned long *)PT_PD_ADDR;
unsigned long pd_idx = vaddr >> PT_PD_INDEX_SHIFT;
unsigned long pde = pd[pd_idx];
if (!(pde & PT_FLAGS_PRESENT_RW)) return;
if (pde & PT_FLAGS_PS) return;
volatile unsigned long *pt =
(volatile unsigned long *)(pde & PT_ADDR_MASK);
unsigned long pte_idx = (vaddr >> 12) & 0x1FF;
if (exec) pt[pte_idx] &= ~(unsigned long)PT_FLAGS_NX;
else pt[pte_idx] |= (unsigned long)PT_FLAGS_NX;
}
/* Mark the pages of a loaded executable segment as executable (clear NX)
* and flush the TLB so the new permissions take effect before the program
* runs. */
static void mm_user_set_exec(unsigned long start, unsigned long end) {
unsigned long p;
start &= ~0xFFFUL;
end = ALIGN_UP(end, 0x1000);
for (p = start; p < end; p += 0x1000) mm_user_pte_update(p, 1);
__asm__ volatile("mov %%cr3, %%rax; mov %%rax, %%cr3" ::: "rax", "memory");
}
void kallocator_init(void) {
/* Build the dlmalloc mspace over the fixed kernel heap once. HAVE_MORECORE
* and HAVE_MMAP are disabled in the backend, so the space is bounded by
* HEAP_SIZE and an exhausted heap returns 0, exactly like the allocator
* this replaces. */
dlmalloc_init();
}
void *kmalloc(unsigned long size) {
if (size == 0) return 0;
return dlmalloc_malloc(size);
}
void kfree(void *ptr) {
if (!ptr) return;
dlmalloc_free(ptr);
}
void *kcalloc(unsigned long nmemb, unsigned long size) {
return dlmalloc_calloc(nmemb, size);
}
void *krealloc(void *ptr, unsigned long size) {
if (!ptr) return kmalloc(size);
if (size == 0) { kfree(ptr); return 0; }
return dlmalloc_realloc(ptr, size);
}
/* ================================================================
* String functions
* ================================================================ */
unsigned long kstrlen(const char *s) {
const char *p = s;
while (*p) p++;
return (unsigned long)(p - s);
}
char *kstrcpy(char *dst, const char *src) {
char *d = dst;
while ((*d++ = *src++));
return dst;
}
char *kstrncpy(char *dst, const char *src, unsigned long n) {
char *d = dst;
while (n-- && (*d++ = *src++));
return dst;
}
char *kstrncat(char *dst, const char *src, unsigned long n) {
char *d = dst;
while (*d) d++;
while (n-- && *src) *d++ = *src++;
*d = 0;
return dst;
}
int kstrcmp(const char *a, const char *b) {
while (*a && *a == *b) { a++; b++; }
return (unsigned char)*a - (unsigned char)*b;
}
int kstrncmp(const char *a, const char *b, unsigned long n) {
while (n-- && *a && *a == *b) { a++; b++; }
return n == (unsigned long)-1 ? 0 : (unsigned char)*a - (unsigned char)*b;
}
char *kstrchr(const char *s, int c) {
while (*s) { if (*s == (char)c) return (char *)s; s++; }
return 0;
}
char *kstrstr(const char *hay, const char *ndl) {
unsigned long nl = kstrlen(ndl);
if (nl == 0) return (char *)hay;
while (*hay) {
if (kstrncmp(hay, ndl, nl) == 0) return (char *)hay;
hay++;
}
return 0;
}
void *kmemcpy(void *dst, const void *src, unsigned long n) {
char *d = dst;
const char *s = src;
while (n--) *d++ = *s++;
return dst;
}
void *kmemset(void *dst, int c, unsigned long n) {
char *d = dst;
while (n--) *d++ = (char)c;
return dst;
}
int kmemcmp(const void *a, const void *b, unsigned long n) {
const unsigned char *pa = a, *pb = b;
while (n--) { if (*pa != *pb) return *pa - *pb; pa++; pb++; }
return 0;
}
void *kmemmove(void *dst, const void *src, unsigned long n) {
char *d = dst;
const char *s = src;
if (d < s) { while (n--) *d++ = *s++; }
else { d += n; s += n; while (n--) *--d = *--s; }
return dst;
}
/* atoi helper */
static long katol(const char *s) {
long v = 0, sign = 1;
while (*s == ' ') s++;
if (*s == '-') { sign = -1; s++; }
else if (*s == '+') s++;
while (*s >= '0' && *s <= '9') { v = v * 10 + (*s - '0'); s++; }
return v * sign;
}
/* ================================================================
* Ramdisk file system
* ================================================================ */
#define RD_MAGIC 0x4B534452
#define RD_HEADER_SIZE 8
#define RD_ENTRY_SIZE (RAMDISK_FNAME_LEN + 8)
#define RD_DATA_MIN (512UL * 1024)
#define RD_DATA_SPARE (1024UL * 1024)
#define RD_DATA_MAX (48UL * 1024 * 1024)
typedef struct {
unsigned magic;
unsigned count;
RDFile files[RAMDISK_MAX_FILES];
} RDSuper;
static RDSuper *rd;
static char *rd_data;
static unsigned rd_used;
static unsigned rd_cap;
/* Reserve a data area of `want` bytes, clamped to the configured maximum.
* An existing area is kept when it is already large enough, otherwise the
* live contents are carried over to the new one. The cap is deliberately
* conservative (48 MB out of the 192 MB heap) to leave room for MiniFS
* bitmaps, dlmalloc metadata, and transient compression buffers. Returns
* 1 on success, 0 when the allocation would leave the heap too small. */
static int ramdisk_reserve(unsigned long want) {
if (want > RD_DATA_MAX) return 0;
if (want < RD_DATA_MIN) want = RD_DATA_MIN;
if (rd_data && rd_cap >= want) return 1;
char *area = kmalloc(want);
if (!area) {
kprintf("ramdisk: cannot allocate %lu KB (heap exhausted)\n",
want / 1024);
return 0;
}
kmemset(area, 0, want);
if (rd_data && rd_used > 0) kmemcpy(area, rd_data, rd_used);
if (rd_data) kfree(rd_data);
rd_data = area;
rd_cap = (unsigned)want;
return 1;
}
/* Populate the ramdisk from a packed image. The image is validated in full
* before any entry is published, so a rejected image leaves the directory
* untouched instead of advertising files whose data was never copied. */
void ramdisk_setup_from(void *data, unsigned size) {
char *raw = (char *)data;
unsigned i;
if (!raw || size < RD_HEADER_SIZE) return;
if (*(unsigned *)raw != RD_MAGIC) return;
unsigned count = *(unsigned *)(raw + 4);
if (count > RAMDISK_MAX_FILES) return;
unsigned long table_bytes = (unsigned long)count * RD_ENTRY_SIZE;
if (table_bytes > (unsigned long)size - RD_HEADER_SIZE) return;
char *entry_start = raw + RD_HEADER_SIZE;
char *data_start = entry_start + table_bytes;
unsigned long payload = (unsigned long)size - RD_HEADER_SIZE - table_bytes;
unsigned long total = 0;
for (i = 0; i < count; i++) {
char *esrc = entry_start + (unsigned long)i * RD_ENTRY_SIZE;
unsigned fsize = *(unsigned *)(esrc + RAMDISK_FNAME_LEN);
unsigned forig = *(unsigned *)(esrc + RAMDISK_FNAME_LEN + 4);
if (forig > payload || fsize > payload - forig) return;
if (total > RD_DATA_MAX - fsize) return;
total += fsize;
}
if (!rd) ramdisk_init();
if (!rd) return;
if (!ramdisk_reserve(total + RD_DATA_SPARE)) {
kprintf("ramdisk: image needs %u bytes, capacity unavailable\n",
(unsigned)total);
return;
}
unsigned offset = 0;
for (i = 0; i < count; i++) {
char *esrc = entry_start + (unsigned long)i * RD_ENTRY_SIZE;
unsigned fsize = *(unsigned *)(esrc + RAMDISK_FNAME_LEN);
unsigned forig = *(unsigned *)(esrc + RAMDISK_FNAME_LEN + 4);
RDFile *f = &rd->files[i];
kmemcpy(f->name, esrc, RAMDISK_FNAME_LEN);
f->name[RAMDISK_FNAME_LEN - 1] = 0;
f->size = fsize;
f->offset = offset;
if (fsize) kmemcpy(rd_data + offset, data_start + forig, fsize);
offset += fsize;
}
rd->count = count;
rd_used = offset;
}
void ramdisk_init(void) {
if (!rd) {
rd = kcalloc(1, sizeof(RDSuper));
if (!rd) return;
rd_used = 0;
rd_cap = 0;
rd_data = 0;
if (!ramdisk_reserve(RD_DATA_MIN)) {
kfree(rd);
rd = 0;
return;
}
rd->magic = RD_MAGIC;
rd->count = 0;
}
}
RDFile *ramdisk_open(const char *name) {
unsigned i;
if (!rd) return 0;
for (i = 0; i < rd->count; i++) {
if (kstrcmp(rd->files[i].name, name) == 0)
return &rd->files[i];
}
return 0;
}
int ramdisk_read(RDFile *f, void *buf, unsigned offset, unsigned len) {
if (!f || !buf || !rd_data) return 0;
if (offset >= f->size) return 0;
if (offset + len > f->size) len = f->size - offset;
kmemcpy(buf, rd_data + f->offset + offset, len);
return (int)len;
}
int ramdisk_write(RDFile *f, const void *buf, unsigned offset, unsigned len) {
if (!f || !buf || !rd_data) return 0;
if (offset >= f->size) return 0;
if (offset + len > f->size) len = f->size - offset;
kmemcpy(rd_data + f->offset + offset, buf, len);
return (int)len;
}
RDFile *ramdisk_create(const char *name, unsigned size) {
if (!rd || !name || rd->count >= RAMDISK_MAX_FILES) return 0;
if (size > RD_DATA_MAX - rd_used) return 0;
if (!ramdisk_reserve((unsigned long)rd_used + size)) return 0;
RDFile *f = &rd->files[rd->count];
kstrncpy(f->name, name, RAMDISK_FNAME_LEN - 1);
f->name[RAMDISK_FNAME_LEN - 1] = 0;
f->size = size;
f->offset = rd_used;
rd_used += size;
rd->count++;
return f;
}
/* Grow or shrink an existing file by relocating the data that follows it.
* Files are stored back to back in the data area; this moves every file
* after `f` by the size delta. Returns 1 on success, 0 on overflow. */
int ramdisk_resize(RDFile *f, unsigned newsize) {
unsigned i;
if (!rd || !f || !rd_data) return 0;
if (newsize == f->size) return 1;
unsigned old_end = f->offset + f->size;
unsigned new_end = f->offset + newsize;
unsigned delta;
unsigned move_len;
if (newsize > f->size) {
delta = newsize - f->size;
if (delta > RD_DATA_MAX - rd_used) return 0;
if (!ramdisk_reserve((unsigned long)rd_used + delta)) return 0;
move_len = rd_used - old_end;
for (i = 0; i < rd->count; i++)
if (&rd->files[i] != f && rd->files[i].offset >= old_end)
rd->files[i].offset += delta;
kmemmove(rd_data + new_end, rd_data + old_end, move_len);
kmemset(rd_data + old_end, 0, delta);
f->size = newsize;
rd_used += delta;
return 1;
}
delta = f->size - newsize;
move_len = rd_used - old_end;
kmemmove(rd_data + new_end, rd_data + old_end, move_len);
kmemset(rd_data + rd_used - delta, 0, delta);
for (i = 0; i < rd->count; i++)
if (&rd->files[i] != f && rd->files[i].offset >= old_end)
rd->files[i].offset -= delta;
f->size = newsize;
rd_used -= delta;
return 1;
}
int ramdisk_list(RDFile **out, int max) {
if (!rd) return 0;
int n = (int)rd->count < max ? (int)rd->count : max;
unsigned i;
for (i = 0; i < (unsigned)n; i++) out[i] = &rd->files[i];
return n;
}
/* Remove an entry and compact the data area. Files after `f` are shifted
* left by f->size and the directory slot is dropped. Returns 1 on success,
* 0 when the pointer is not a live entry. */
int ramdisk_delete(RDFile *f) {
unsigned i;
int idx = -1;
if (!rd || !f) return 0;
for (i = 0; i < rd->count; i++) {
if (&rd->files[i] == f) { idx = (int)i; break; }
}
if (idx < 0) return 0;
unsigned old_end = f->offset + f->size;
unsigned move_len = rd_used - old_end;
kmemmove(rd_data + f->offset, rd_data + old_end, move_len);
for (i = 0; i < rd->count; i++)
if (&rd->files[i] != f && rd->files[i].offset >= old_end)
rd->files[i].offset -= f->size;
for (i = (unsigned)idx; i + 1 < rd->count; i++)
rd->files[i] = rd->files[i + 1];
rd->count--;
rd_used -= f->size;
return 1;
}