LumaOS  v0.1.116
An experimental x86-64 OS
Loading...
Searching...
No Matches
main.c
Go to the documentation of this file.
1
9
10#include <stddef.h>
11#include <stdbool.h>
12
13#include <drivers/serial.h>
14#include <drivers/console.h>
15#include <drivers/keyboard.h>
16
17#include <arch/x86_64/idt.h>
18#include <arch/x86_64/gdt.h>
19#include <arch/x86_64/irq.h>
20#include <arch/x86_64/pic.h>
21#include <arch/x86_64/pit.h>
22
23#include <lib/kstring.h>
24#include <lib/parser.h>
25
26#include <limine/limine.h>
27
28#include <kernel/tests.h>
29#include <kernel/panic.h>
30#include <kernel/assert.h>
31#include <kernel/hexdump.h>
32#include <kernel/kprintf.h>
33#include <kernel/vars.h>
34#include <kernel/log.h>
35
36#include <mm/pmm.h>
37
38#include "arch/x86_64/paging.h"
39#include "mm/vmm.h"
40
41// Prototypes
42static void hcf(void);
43static void draw_pixel(struct limine_framebuffer *fb, uint64_t x, uint64_t y, uint8_t red, uint8_t green, uint8_t blue);
44static void limine_request_verification(void);
45static bool output_init(void);
46static void interrupt_system_init(void);
47static void memory_init(void);
48static void gdt_idt_init(void);
49static void kernel_self_tests(void);
50
51extern int font_type;
52
53static bool out_of_memory_test_1 = false;
54static bool out_of_memory_test_2 = false;
55static bool double_free_test = false;
56
57extern struct console main_console; // The main console info
58
59// LIMINE
60__attribute__((used, section(".limine_requests")))
61static volatile uint64_t limine_base_revision[] = LIMINE_BASE_REVISION(6);
62
63__attribute__((used, section(".limine_requests_start")))
64static volatile uint64_t limine_requests_start_marker[] = LIMINE_REQUESTS_START_MARKER;
65
66// REQUEST START
67
68__attribute__((used, section(".limine_requests")))
69static volatile struct limine_bootloader_info_request bootloader_info_request = {
70 .id = LIMINE_BOOTLOADER_INFO_REQUEST_ID,
71 .revision = 0
72
73 // RESPONSE FIELDS
74 // name, version (0-terminated strings)
75};
76
77__attribute__((used, section(".limine_requests")))
78static volatile struct limine_firmware_type_request firmware_type_request = {
79 .id = LIMINE_FIRMWARE_TYPE_REQUEST_ID,
80 .revision = 0
81
82 // RESPONSE FIELDS
83 // firmware_type: LIMINE_FIRMWARE_TYPE_X86BIOS (0), LIMINE_FIRMWARE_TYPE_EFI32 (1), LIMINE_FIRMWARE_TYPE_EFI64 (2)
84};
85
86__attribute__((used, section(".limine_requests")))
87static volatile struct limine_hhdm_request hhdm_request = {
88 .id = LIMINE_HHDM_REQUEST_ID,
89 .revision = 0
90
91 // RESPONSE FIELDS
92 // offset
93};
94
95__attribute__((used, section(".limine_requests")))
96static volatile struct limine_memmap_request memmap_request = {
97 .id = LIMINE_MEMMAP_REQUEST_ID,
98 .revision = 0
99
100 // RESPONSE FIELDS
101 // entry_count, and entries: an array of pointers to structs with base, length, type
102};
103
104__attribute__((used, section(".limine_requests")))
105static volatile struct limine_executable_address_request executable_address_request = {
106 .id = LIMINE_EXECUTABLE_ADDRESS_REQUEST_ID,
107 .revision = 0
108
109 // RESPONSE FIELDS
110 // physical_base, virtual_base
111};
112
113__attribute__((used, section(".limine_requests")))
114static volatile struct limine_framebuffer_request framebuffer_request = {
115 .id = LIMINE_FRAMEBUFFER_REQUEST_ID,
116 .revision = 0
117
118 // RESPONSE FIELDS
119 // framebuffer_count, and framebuffers: an array of pointers to structs with address, width,
120 // height, pitch, bpp, memory_model, and the color mask sizes and shifts
121};
122
123__attribute__((used, section(".limine_requests")))
124static volatile struct limine_executable_cmdline_request cmdline_request = {
125 .id = LIMINE_EXECUTABLE_CMDLINE_REQUEST_ID,
126 .revision = 0
127};
128
129// REQUEST END
130
131__attribute__((used, section(".limine_requests_end")))
132static volatile uint64_t limine_requests_end_marker[] = LIMINE_REQUESTS_END_MARKER;
133
137void kmain(void) {
138
139 // check if the base revision is supported
140 if (!LIMINE_BASE_REVISION_SUPPORTED(limine_base_revision)) {
141 hcf();
142 }
143
144 output_init(); // Initialize output systems
145
146 // Tests
147 limine_request_verification(); // Output all limine requests for manual verification
148 kernel_self_tests(); // Run kernel self tests
149
150 // Inits
151 gdt_idt_init(); // Initialize GDT and IDT
152 memory_init(); // Initialize memory systems
153 interrupt_system_init(); // Initialize interrupt system
154
155 // Initialization successful
156 LOG_INFO("LumaOS Initialization Complete!\nPress any key to continue...");
157 kbd_getchar();
158
159 hcf(); // Halt
160}
161
165static void hcf(void) {
166 if (main_console.cursor_row == main_console.rows - 1 && main_console.cursor_row != 0) {
167 scroll_up();
168 main_console.cursor_row--;
169 }
170
171 uint8_t current_row = main_console.cursor_row;
172 uint8_t current_col = main_console.cursor_col;
173
174 // Set cursor position
175 main_console.cursor_row = main_console.rows - 1;
176 main_console.cursor_col = 0;
177
178 uint64_t previous_second = 0;
179
180 previous_second = pit_ticks / pit_frequency;
181 // Print uptime
182 uint64_t flags = irq_save(); // Save IRQ
183 kprintf("Uptime %lds\r", previous_second); // Print
184 irq_restore(flags); // Restore IRQ
185
186
187 for (;;) {
188 asm ("hlt"); // Halt the cpu
189
190
191 int raw;
192 while ((raw = kbd_buf_pop()) >= 0) {
193 main_console.cursor_row = current_row;
194 main_console.cursor_col = current_col;
195
196 // Print character
197 struct key_event ev;
198 bool decode = kbd_decode((uint8_t)raw, &ev);
199 if (decode && ev.pressed && ev.ascii && ctrl_down) {
200 if ((ev.ascii >= 'a' && ev.ascii <= 'z'))
201 kprintf("ctrl+%c (%u)", ev.ascii, ev.ascii - 'a' + 1);
202 else if ((ev.ascii >= 'A' && ev.ascii <= 'Z'))
203 kprintf("ctrl+%c (%d)", ev.ascii, ev.ascii - 'A' + 1);
204
205 } else if (decode && ev.pressed && ev.ascii){
207 serial_putc(ev.ascii);
208 if (ev.ascii == '\b') { // If its a backspace, erase the previous character as well
209 console_putc(' ');
210 console_putc('\b');
211
212 }
213 }
214
215 // If the cursor is on the last row...
216 if (main_console.cursor_row == main_console.rows - 1) {
217 scroll_up();
218
219 // Set the cursor to the second last row
220 main_console.cursor_row -= 1;
221
222 // Erase the second last row
223 for (int i = 0; i < main_console.cols - 1; i++) {
224 console_putc(' ');
225 }
226
227 // Go back to the start of the row
228 main_console.cursor_col = 0;
229
230 // Make sure the uptime is still there correctly
231 current_row = main_console.cursor_row;
232 current_col = main_console.cursor_col;
233
234 main_console.cursor_row = main_console.rows - 1;
235 main_console.cursor_col = 0;
236
237 previous_second = pit_ticks / pit_frequency;
238
239 // Print uptime
240 uint64_t flags = irq_save(); // Save IRQ
241 kprintf("Uptime %lds\r", previous_second); // Print
242 irq_restore(flags); // Restore IRQ
243 } else {
244 // Reset the cursor for the uptime counter
245 current_row = main_console.cursor_row;
246 current_col = main_console.cursor_col;
247
248 main_console.cursor_row = main_console.rows - 1;
249 main_console.cursor_col = 0;
250 }
251
252
253 }
254
255 if (pit_ticks / pit_frequency != previous_second)
256 {
257 previous_second = pit_ticks / pit_frequency;
258 // Print uptime
259 uint64_t flags = irq_save(); // Save IRQ
260 kprintf("Uptime %lds\r", previous_second); // Print
261 irq_restore(flags); // Restore IRQ
262 }
263 }
264}
265
275static void draw_pixel(struct limine_framebuffer *fb, uint64_t x, uint64_t y, uint8_t red, uint8_t green, uint8_t blue) {
276 if (x >= fb->width || y >= fb->height) { // Return if its outside the bounds of the screen
277 return;
278 }
279
280 uint32_t *pixel_addr = (uint32_t *)( // Get the address of the pixel
281 (uint8_t *)fb->address + (y * fb->pitch) + (x * 4)
282 );
283
284 uint32_t pixel = // Store the pixel as one int
285 ((uint32_t)red << fb->red_mask_shift) |
286 ((uint32_t)green << fb->green_mask_shift) |
287 ((uint32_t)blue << fb->blue_mask_shift);
288
289 *pixel_addr = pixel; // Set the value at the pixel address to the pixel int
290}
291
296{
297 LOG_INFO("Limine Request Section.................");
298
299 uint64_t width = main_console.fb->width;
300 uint64_t height = main_console.fb->height;
301 uint64_t pitch = main_console.fb->pitch;
302 uint64_t bpp = main_console.fb->bpp;
303
304 if (get_debug_on()) kprintf("\n\n");
305 LOG_DEBUG("Framebuffer width: %d\n", width);
306 LOG_DEBUG("Framebuffer height: %d\n", height);
307 LOG_DEBUG("Framebuffer pitch: %d\n", pitch);
308 LOG_DEBUG("Framebuffer bytes per pixel: %d\n\n", bpp);
309
310
311 if (firmware_type_request.response != NULL) {
312 uint64_t type = firmware_type_request.response->firmware_type;
313 char *type_text;
314
315 if (type == LIMINE_FIRMWARE_TYPE_X86BIOS) {
316 type_text = "x86 BIOS";
317 } else if (type == LIMINE_FIRMWARE_TYPE_EFI64) {
318 type_text = "64-bit UEFI";
319 } else if (type == LIMINE_FIRMWARE_TYPE_EFI32) {
320 type_text = "32-bit UEFI";
321 } else {
322 type_text = "Unknown";
323 }
324
325 LOG_DEBUG("Firmware Type: %s\n\n", type_text);
326 }
327
328 if (hhdm_request.response != NULL) {
329 uint64_t offset = hhdm_request.response->offset;
330
331 set_hddm_offset(offset);
332
333 LOG_DEBUG("HHDM Offset: %16lx\n\n", offset);
334 } else
335 {
336 LOG_ERROR("HHDM REQUEST is NULL\n");
337 hcf();
338 }
339
340 if (executable_address_request.response != NULL) {
341 uint64_t virt = executable_address_request.response->virtual_base;
342 uint64_t phys = executable_address_request.response->physical_base;
343
344 LOG_DEBUG("Executable Virtual Address Base: %16lx\n", virt);
345 LOG_DEBUG("Executable Physical Address Base: %16lx\n\n", phys);
346 }
347
348 if (memmap_request.response != NULL) {
349 uint64_t entry_count = memmap_request.response->entry_count;
350
351 LOG_DEBUG("MEMMAP:\n");
352
353 for (unsigned int i = 0; i < entry_count; i++) {
354 uint64_t base = (*memmap_request.response->entries[i]).base;
355 uint64_t length = (*memmap_request.response->entries[i]).length;
356 uint64_t type = (*memmap_request.response->entries[i]).type;
357
358 LOG_DEBUG("Memmap entry %d:\n", i);
359 LOG_DEBUG(" Base: %lx\n", base);
360 LOG_DEBUG(" Length: %ld\n", length);
361
362 char *type_str;
363
364 switch (type) {
365 case LIMINE_MEMMAP_USABLE:
366 type_str = "Usable";
367 break;
368 case LIMINE_MEMMAP_RESERVED:
369 type_str = "Reserved";
370 break;
371 case LIMINE_MEMMAP_ACPI_RECLAIMABLE:
372 type_str = "ACPI Reclaimable";
373 break;
374 case LIMINE_MEMMAP_ACPI_NVS:
375 type_str = "ACPI NVS";
376 break;
377 case LIMINE_MEMMAP_BAD_MEMORY:
378 type_str = "Bad Memory";
379 break;
380 case LIMINE_MEMMAP_BOOTLOADER_RECLAIMABLE:
381 type_str = "Bootloader Reclaimable";
382 break;
383 case LIMINE_MEMMAP_EXECUTABLE_AND_MODULES:
384 type_str = "Executable & Modules";
385 break;
386 case LIMINE_MEMMAP_FRAMEBUFFER:
387 type_str = "Framebuffer";
388 break;
389 case LIMINE_MEMMAP_RESERVED_MAPPED:
390 type_str = "Reserved (Mapped)";
391 break;
392 default:
393 type_str = "Unknown";
394 break;
395 }
396
397 LOG_DEBUG(" Type: %s\n", type_str);
398 }
399
400 if (get_debug_on()) kprintf("\n");
401
402 } else
403 {
404 LOG_ERROR("MEMMAP REQUEST is NULL\n");
405 hcf();
406 }
407
408 kprintf("\033[94mCOMPLETE\n");
409}
410
415static bool output_init(void)
416{
417 int serial_init_return = serial_init(); // Initialize the serial
418
419 bool serial_success = serial_init_return == 0;
420
421 // Get and assign the framebuffer
422 if (framebuffer_request.response != NULL) {
423 struct limine_framebuffer *fb = framebuffer_request.response->framebuffers[0];
424
425 if (fb == NULL) {
426 kprintf("\n");
427 if (get_debug_on()) LOG_ERROR("Framebuffer is NULL!\n");
428 hcf();
429 }
430
431 main_console.fb = fb; // Assign reference to framebuffer in the main console
432 } else {
433 kprintf("\n");
434 if (get_debug_on()) LOG_ERROR("Framebuffer is NULL!\n");
435 hcf();
436 }
437
438 // Check Font header magic number to see what font type it is
439 if (*_binary_font_psf_start == 0x36 &&
440 *(_binary_font_psf_start + 1) == 0x04) {
441 font_type = FONT_PSF1;
442
443 } else if (*_binary_font_psf_start == 0x72 &&
444 *(_binary_font_psf_start + 1) == 0xB5 &&
445 *(_binary_font_psf_start + 2) == 0x4A &&
446 *(_binary_font_psf_start + 3) == 0x86) {
447 font_type = FONT_PSF2;
448 } else {
449 kprintf("\n");
450 LOG_ERROR("Font magic number does not match PSF1 or PSF2!\n");
451 hcf(); // If the fonts magic number doesnt match psf1 or psf2, halt
452 }
453
454 // Get flags and apply them
455 if (cmdline_request.response != NULL) {
456 const char *cmdline = cmdline_request.response->cmdline; // Get the flags from the limine request
457
458 // Set Logging Level
459 char log_level[6] = {0};
460
461 if (parse_string("log_level", cmdline, log_level, sizeof(log_level)))
462 {
463 if (strcmp(log_level, "error") == 0 || strcmp(log_level, "0") == 0)
464 LOGGING_LEVEL = LOG_LEVEL_ERROR;
465
466 else if (strcmp(log_level, "warn") == 0 || strcmp(log_level, "1") == 0)
467 LOGGING_LEVEL = LOG_LEVEL_WARN;
468
469 else if (strcmp(log_level, "info") == 0 || strcmp(log_level, "2") == 0)
470 LOGGING_LEVEL = LOG_LEVEL_INFO;
471
472 else if (strcmp(log_level, "debug") == 0 || strcmp(log_level, "3") == 0)
473 {
474 LOGGING_LEVEL = LOG_LEVEL_DEBUG;
475 set_debug_on(true);
476 }
477 }
478
479 // Enable Debugging
480 set_debug_on(parse_bool("debug", cmdline)); // If the debug flag is set or equal to true, toggle debug logs on
481
482 // Special Tests
483 double_free_test = parse_bool("mem.double_free_test", cmdline);
484 out_of_memory_test_1 = parse_bool("mem.oom_test_1", cmdline);
485 out_of_memory_test_2 = parse_bool("mem.oom_test_2", cmdline);
486
487 }
488
489 LOG_INFO("Limine Request Section.................");
490
491 console_init(); // Initialize console
492 console_clear(); // Clear console
493
494 LOG_INFO("Initializing Serial Output.............");
495
496 if (serial_success) // Check if the serial initialization succeded
497 kprintf("\033[92mPASS\n");
498 else
499 kprintf("\033[91mFAILED\n");
500
501 LOG_INFO("Initializing Console...................\033[92mPASS\n");
502
503 if (bootloader_info_request.response != NULL) {
504 char *name = bootloader_info_request.response->name;
505 char *version = bootloader_info_request.response->version;
506
507 LOG_INFO("BOOTLOADER INFO:\n");
508 LOG_INFO("Name: %s\n", name);
509 LOG_INFO("Version: %s\n", version);
510 }
511
512 return serial_success && get_console_status();
513}
514
518static void interrupt_system_init(void)
519{
520 LOG_INFO("Initializing IRQ and PIC Handlers......");
521 if (get_debug_on()) kprintf("\n");
522
523 // Disable APIC
524 uint64_t apic_base = rdmsr(0x1B);
525
526 if (apic_base & (1ULL << 10)) {
527 apic_base &= ~(1ULL << 10);
528 wrmsr(0x1B, apic_base);
529 }
530
531 apic_base &= ~(1ULL << 11);
532 wrmsr(0x1B, apic_base);
533
534 // Remap the PIC vectors
535 pic_remap(0x20, 0x28); // Initialize PIC
536
537 // Initialize devices
538 pit_init(100); // Initialize timer
540
541 // Enable interrupts
542 asm volatile ("sti"); // Re-enable interrupts
543
544 kprintf("\033[92mPASS\n");
545}
546
550static void memory_init(void)
551{
552 LOG_INFO("Initializing Physical Memory Manager...");
553
554 // Initializing Physical Memory Manager
555 pmm_init(memmap_request.response);
556
557 vmm_init();
558 vmm_add_region(0xFFFFC00000000000, 0xFFFFC00000000000 + 0x10000, PTE_WRITABLE); // Add a region for the kernel
559
560 kprintf("\033[92mPASS\n");
561
562 // Run PMM tests
563 if (get_debug_on())
564 {
565 LOG_DEBUG("PMM Tests\n");
566
567 if (out_of_memory_test_1)
568 {
569 LOG_DEBUG("Out of Memory Test...\n");
570 for (;;)
571 {
572 uint64_t addr = pmm_alloc_frame();
573 uint64_t free_frames = get_pmm_state().free_frames;
574
575 LOG_DEBUG("addr: %016lx free frames: %lu\r", addr, free_frames);
576
577 if (addr == 0)
578 {
579 kprintf("\nOut of memory!\n");
580 if (get_pmm_state().free_frames == 0)
581 {
582 kprintf("\n");
583 LOG_DEBUG("Out of memory test successful! Reboot with flag \"mem.oom_test_1\" set to false to continue boot regularly.\n");
584 } else
585 {
586 kprintf("\n");
587 LOG_ERROR("Out of memory test failed! Free frames != 0. Reboot with flag \"mem.oom_test_1\" set to false to continue boot regularly.\n");
588 }
589 for (;;) asm volatile("hlt");
590 }
591
592 }
593 }
594
595 // Count Restore:
596 LOG_DEBUG("Test 1 & 2: Count Restore & Uniqueness & Alignment\n");
597
598 uint64_t free_frames_before = get_pmm_state().free_frames, free_frames_after;
599
600 // Allocate Frames
601 uint64_t frames[1000];
602 for (int i = 0; i < 1000; i++)
603 {
604 frames[i] = pmm_alloc_frame();
605 }
606
607 // Verify frames are aligned, above 1MiB, and unique
608 for (int i = 0; i < 1000; i++)
609 {
610 // Verify Alignment
611 if (frames[i] % FRAME_SIZE != 0)
612 {
613 LOG_ERROR("Frame %d is not aligned!\n", i);
614 LOG_ERROR("Frame Alignment Test Failed!\n");
615 for (;;) asm volatile("hlt");
616
617 }
618
619 // Verify its above 1MiB
620 if (frames[i] < 0x100000)
621 {
622 LOG_ERROR("Frame %d is not above 1MiB!\n", i);
623 LOG_ERROR("Frame Location Test Failed!\n");
624 for (;;) asm volatile("hlt");
625
626 }
627
628 // Verify Its unique
629 for (int j = 0; j < 1000; j++)
630 {
631 if (j == i) continue;
632 ASSERT(frames[i] != frames[j]);
633 if (frames[i] == frames[j])
634 {
635 LOG_ERROR("Frame %d is not unique! (matches frame %d)\n", i, j);
636 LOG_ERROR("Frame Uniqueness Test Failed!\n");
637 for (;;) asm volatile("hlt");
638
639 }
640 }
641 }
642
643 LOG_DEBUG("All frames are aligned, above 1MiB, and unique\n");
644
645 // Free Frames
646 for (int i = 0; i < 1000; i++)
647 {
648 pmm_free_frame(frames[i]);
649 }
650
651 free_frames_after = get_pmm_state().free_frames;
652
653 ASSERT(free_frames_before == free_frames_after);
654 LOG_DEBUG("Free Frames Before: %ld\n"
655 " Free Frames After: %ld\n", free_frames_before, free_frames_after);
656
657
658 LOG_DEBUG("Test 3: Memory Usage\n");
659 uint64_t phys_address = pmm_alloc_frame();
660 uint64_t virt_address = phys_address + get_hddm_offset();
661
662 LOG_DEBUG("Writing 0xABCDEF0123456789 to the physical address 0x%lx\n", phys_address);
663
664 *(uint64_t*)virt_address = 0xABCDEF0123456789;
665
666 ASSERT(*(uint64_t*)virt_address == 0xABCDEF0123456789);
667
668 LOG_DEBUG("Reading back the value from the physical address 0x%lx\n", phys_address);
669 LOG_DEBUG("Value read: 0x%lx\n", *(uint64_t*)virt_address);
670
671 LOG_DEBUG("Zeroing Frame...\n");
672
673 memset((void*)virt_address, 0, FRAME_SIZE);
674
675 pmm_free_frame(phys_address);
676
677 if (double_free_test)
678 {
679 LOG_DEBUG("Double Freeing Frame Test...\n");
680 LOG_DEBUG("Test is SUCCESSFUL IF THE KERNEL PANICS\n");
681 LOG_DEBUG("After test, reboot with flag \"mem.double_free_test\" set to false to continue boot regularly.\n");
682 pmm_free_frame(phys_address);
683 LOG_ERROR("Double free test failed!\n");
684 for (;;) asm volatile("hlt");
685
686 }
687
688 if (out_of_memory_test_2)
689 {
690 LOG_DEBUG("Out of Memory Test...\n");
691 for (;;)
692 {
693 uint64_t addr = pmm_alloc_frame();
694 uint64_t free_frames = get_pmm_state().free_frames;
695
696 LOG_DEBUG("addr: %016lx free frames: %lu\r", addr, free_frames);
697
698 if (addr == 0)
699 {
700 kprintf("\nOut of memory!\n");
701 if (get_pmm_state().free_frames == 0)
702 {
703 kprintf("\n");
704 LOG_DEBUG("Out of memory test successful! Reboot with flag \"mem.oom_test_2\" set to false to continue boot regularly.\n");
705 } else
706 {
707 kprintf("\n");
708 LOG_ERROR("Out of memory test failed! Free frames != 0. Reboot with flag \"mem.oom_test_2\" set to false to continue boot regularly.\n");
709 }
710 for (;;) asm volatile("hlt");
711
712 }
713
714 }
715 }
716
717 kprintf("\n\n");
718 }
719
720 // Run page translator tests
721 if (get_debug_on())
722 {
723 LOG_DEBUG("Page Translator Tests\n");
724
725 uint64_t test1 = translate((uint64_t)kprintf);
726 uint64_t test2 = translate(0x500000 + get_hddm_offset());
727
728 uint64_t test_addr = pmm_alloc_frame();
729 uint64_t test3 = translate(0x400000);
730 uint64_t test4 = translate(0x400000 | (1ULL << 48));
731
732 LOG_DEBUG("kprintf: Virtual ADDR=%16lx Physical ADDR=%16lx\n", (uint64_t)kprintf, test1);
733 LOG_DEBUG("Test 2: Virtual ADDR=%16lx Physical ADDR=%16lx\n", 0x500000 + get_hddm_offset(), test2);
734 LOG_DEBUG("Test 3: Virtual ADDR=%16lx Physical ADDR=%16lx\n", 0x400000, test3);
735 LOG_DEBUG("Test 4: Virtual ADDR=%16lx Physical ADDR=%16lx\n", 0x400000 | (1ULL << 48), test4);
736 }
737
738 // Run VMM Tests
739 if (get_debug_on())
740 {
741
742
743 kprintf("\n\n");
744 LOG_DEBUG("RUNNING VIRTUAL MEMORY MANAGER TESTS\n");
745
746 // Show original frame_count
747 LOG_DEBUG("Original free_frame count: %lu\n", get_pmm_state().free_frames);
748
749 // Translate the VMM_TEST_BASE
750 translate(VMM_TEST_BASE);
751
752 // Allocate a frame
753 uint64_t frame_addr = pmm_alloc_frame();
754 LOG_DEBUG("Allocated new frame\n");
755
756 // Show new frame_count
757 LOG_DEBUG("New free_frame count: %lu\n", get_pmm_state().free_frames);
758
759 // Map the frame
760 uint64_t virt = vmm_map(get_kernel_pml4_phys(), VMM_TEST_BASE, frame_addr, PTE_WRITABLE);
761
762 if (virt == UINT64_MAX)
763 {
764 LOG_ERROR("Failed to map frame at VMM_TEST_BASE\n");
765 goto post_vmm_test_1;
766 }
767
768 LOG_DEBUG("Mapped frame at VMM_TEST_BASE\n");
769
770 translate(virt);
771
772 // Write and read to the frame
773 *(uint64_t*)virt = 0x123456789ABCDEF0;
774 LOG_DEBUG("Wrote 0x123456789ABCDEF0 to VMM_TEST_BASE\n");
775 LOG_DEBUG("Read back: 0x%lx\n", *(uint64_t*)virt);
776
777 // Translate the new mapping as well
778 translate(VMM_TEST_BASE);
779
780 // Unmap the frame
781 LOG_DEBUG("Unmapping Frame at VMM_TEST_BASE\n");
782 vmm_unmap(get_kernel_pml4_phys(), VMM_TEST_BASE);
783
784 // Translate the unmapped frame
785 translate(VMM_TEST_BASE);
786
787 post_vmm_test_1:
788
789 // Free frame
790 LOG_DEBUG("Freeing Frame\n");
791 pmm_free_frame(frame_addr);
792
793 // Show restored free_frame count
794 LOG_DEBUG("Restored free_frame count: %lu\n", get_pmm_state().free_frames);
795
796 LOG_DEBUG("Testing mapping inside HHDM (should fail)\n");
797
798 LOG_DEBUG("Allocating frame\n");
799 // Check mapping inside hhdm (should fail)
800
801 uint64_t addr = pmm_alloc_frame();
802
803 LOG_DEBUG("Address allocated: 0x%lx\n", addr);
804 LOG_DEBUG("Mapping frame\n");
805 kprintf("\n");
806 uint64_t map = vmm_map(get_kernel_pml4_phys(), addr + get_hddm_offset(), addr, 0);
807
808 if (map == UINT64_MAX)
809 LOG_DEBUG("Success! VMM Mapper did not map inside HHDM\n");
810 else
811 LOG_DEBUG("Failure! VMM Mapper did mapped inside HHDM\n");
812
813 pmm_free_frame(addr);
814
815
816 kprintf("\n");
817
818 LOG_DEBUG("DEMAND PAGING TESTS\n");
819
820 LOG_DEBUG("Frame count: %lu\n", get_pmm_state().free_frames);
821
822 uint64_t *page0 = (uint64_t*)0xFFFFC00000000000;
823 uint64_t *page3 = (uint64_t*)0xFFFFC00000003000;
824 uint64_t *page7 = (uint64_t*)0xFFFFC00000007000;
825
826 LOG_DEBUG("Writing to page 0, 3, and 7\n");
827 *page0 = 0x123456789ABCDEF0;
828 *page3 = 0x123456789ABCDEF1;
829 *page7 = 0x123456789ABCDEF2;
830
831 LOG_DEBUG("Read back from page 0: 0x%lx\n", *page0);
832 LOG_DEBUG("Read back from page 3: 0x%lx\n", *page3);
833 LOG_DEBUG("Read back from page 7: 0x%lx\n", *page7);
834
835
836 LOG_DEBUG("Frame count: %lu\n", get_pmm_state().free_frames);
837
838 LOG_DEBUG("VMM Tests completed!\n");
839
840 kprintf("\n\n");
841 }
842}
843
847static void gdt_idt_init(void)
848{
849 LOG_INFO("Initializing GDT & IST.................");
850
851 init_gdt();
852 init_idt();
853
854 if (get_debug_on()) {
855 struct gdtr current;
856 asm volatile ("sgdt %0" : "=m"(current));
857
858 uint16_t cs = 0, ss = 0, ds = 0;
859 asm volatile ("movw %%cs, %0\n\t"
860 "movw %%ss, %1\n\t"
861 "movw %%ds, %2" :
862 "=r"(cs), "=r"(ss), "=r"(ds) : : "memory");
863
864 LOG_DEBUG("GDT BASE: %lp GDT LIMIT: %u\n", current.base, current.limit);
865 LOG_DEBUG("CS: 0x%x SS: 0x%x DS: 0x%x\n\n", cs, ss, ds);
866
867 LOG_DEBUG("GDT HEXDUMP:\n");
868
869 hexdump((void*)current.base, 56);
870 }
871
872 kprintf("\033[92mPASS\n");
873}
874
878static void kernel_self_tests(void)
879{
880 LOG_INFO("Kernel Self Tests......................");
881
882 uint64_t memcpy_test_ints[3] = {12345,67890,13579};
883 uint32_t memcpy_test_ints_32[6] = {11111,22222,33333,44444,55555,66666};
884
885 uint64_t memmove_test_ints[3] = {12345,67890,13579};
886 uint32_t memmove_test_ints_32[6] = {11111,22222,33333,44444,55555,66666};
887
888 bool memcpy_tests = test_memcpy(memcpy_test_ints[0], memcpy_test_ints[1]) &&
889 test_memcpy(memcpy_test_ints[1], memcpy_test_ints[0]) &&
890 test_memcpy(memcpy_test_ints_32[0], memcpy_test_ints_32[1]);
891
892 bool memmove_tests = test_memmove(memmove_test_ints[0], memmove_test_ints[1]) &&
893 test_memmove(memmove_test_ints[1], memmove_test_ints[0]) &&
894 test_memmove(memmove_test_ints_32[0], memmove_test_ints_32[1]);
895
896 bool memset_tests = test_memset(12399027537, 12345) &&
897 test_memset(000, 02020);
898
899
900 bool memcmp_tests = test_memcmp(1234567890, 2345678901, 1) &&
901 test_memcmp(1234567890, 1234567890, 0) &&
902 test_memcmp(2345678901, 1234567890, -1);
903
904 bool strlen_tests = test_strlen("Hello World", 11) && test_strlen("Hi\n", 3) &&
905 test_strlen("strlen\0 is a function", 6) && test_strlen("123%d456", 8);
906
907 bool gdt_tests = test_access_byte() && test_flag_byte();
908
909 if (!(memcpy_tests && memmove_tests && memset_tests && memcmp_tests && strlen_tests && gdt_tests))
910 {
911 // If any tests fail
912 kprintf("\033[91mFAIL\n");
913
914 if (memcpy_tests) kprintf(" MEMCPY Test Failed\n");
915 if (memmove_tests) kprintf(" MEMMOVE Test Failed\n");
916 if (memset_tests) kprintf(" MEMSET Test Failed\n");
917 if (memcmp_tests) kprintf(" MEMCMP Test Failed\n");
918 if (strlen_tests) kprintf(" STRLEN Test Failed\n");
919 if (gdt_tests) kprintf(" GDT Test Failed\n");
920
921 } else
922 {
923 kprintf("\033[92mPASS\n");
924 }
925
926 if (get_debug_on()) {
927 kprintf("KPRINTF TESTS: VALUE (EXPECTED VALUE)\n");
929
930 // Visual test for ANSI codes
931 kprintf("\nColor Test:\n\n");
932 kprintf("FG: \033[30m#\033[31m#\033[32m#\033[33m#\033[34m#\033[35m#\033[36m#\033[37m#\033[0m\n");
933 kprintf("FG BRIGHT: \033[90m#\033[91m#\033[92m#\033[93m#\033[94m#\033[95m#\033[96m#\033[97m#\033[0m\n");
934 kprintf("BG: \033[40m#\033[41m#\033[42m#\033[43m#\033[44m#\033[45m#\033[46m#\033[47m#\033[0m\n");
935 kprintf("BG BRIGHT: \033[100m#\033[101m#\033[102m#\033[103m#\033[104m#\033[105m#\033[106m#\033[107m#\033[0m\n");
936
937 kprintf("\nEffect Test:\n\n");
938 kprintf("Dim: \033[2m###\033[0m\n");
939 kprintf("Reverse: \033[7m###\033[0m\n");
940 kprintf("Hide: \033[8m###\033[0m\n");
941
942 LOG_ERROR("Test\n");
943 LOG_WARN("Test\n");
944 LOG_INFO("Test\n");
945 LOG_DEBUG("Test\n");
946
947 kprintf("\n");
948
949 }
950}
Runtime assertion.
void console_putc(char c)
Arranges the cursor and prints characters.
Definition console.c:178
void scroll_up(void)
Scrolls the whole console up.
Definition console.c:28
bool get_console_status(void)
Returns the status of the console (initialized or uninitialized).
Definition console.c:23
void console_clear(void)
Clears the console (fills with bg color).
Definition console.c:235
void console_init(void)
Initializes the console struct and fills all the properties.
Definition console.c:68
struct console main_console
The main console info.
Definition console.c:20
Console utilities and configuration.
void init_gdt(void)
Initializes the gdt and loads it.
Definition gdt.c:29
Initializes and holds the GDT for the kernel.
Hexdump utility for displaying memory contents in hexadecimal.
void hexdump(const void *data, size_t size)
Prints each byte as a hex number from a buffer of bytes.
Definition hexdump.c:21
void init_idt(void)
Initializes the IDT and loads it.
Definition idt.c:172
Initializes and holds the IDT for the kernel.
IRQ Handler and utilities.
static uint64_t irq_save(void)
Saves the IRQ and disables interrupts (used when using a variable that is modified by an interrupt).
Definition irq.h:34
static void irq_restore(uint64_t flags)
Restores the IRQ and re-enables interrupts (used when using a variable that is modified by an interru...
Definition irq.h:44
int kbd_buf_pop(void)
Pops byte from the keyboard key buffer.
Definition keyboard.c:61
bool kbd_decode(uint8_t raw, struct key_event *ev)
Convert a keyboard byte into the correct char.
Definition keyboard.c:78
void keyboard_init(void)
Initialize the keyboard driver and register the handler with the IRQ handler.
Definition keyboard.c:128
int kbd_getchar(void)
Waits for a key to be pressed and returns the character.
Definition keyboard.c:68
Handler and utilities for the keyboard.
Tools for printing to the console and serial output.
void kprintf(const char *fmt,...) __attribute__((format(printf
Wrapper for a standard print.
Utilities for memory and string operations.
int strcmp(const char *s1, const char *s2)
Compares 2 strings.
Definition kstring.c:66
void * memset(void *dest, int c, size_t n)
Fills n bytes of the destination with c.
Definition kstring.c:44
Logging utilities for the kernel.
bool get_debug_on(void)
Gets the current value of LOG_ENABLE_DEBUG.
Definition log.c:70
log_level
The logging levels for the log utility.
Definition log.h:16
void set_debug_on(bool is_on)
Sets the debug mode.
Definition log.c:66
static void limine_request_verification(void)
Output the limine request responses.
Definition main.c:295
static void memory_init(void)
Initialize the memory systems (Physical Memory Manager, Virtual Memory Manager, etc) and test them.
Definition main.c:550
static void interrupt_system_init(void)
Initialize the interrupt system.
Definition main.c:518
static void gdt_idt_init(void)
Initialize and test the GDT & IST.
Definition main.c:847
static void kernel_self_tests(void)
Run some kernel self tests.
Definition main.c:878
static bool output_init(void)
Initialize the output systems (serial and framebuffer console) and parse any flags.
Definition main.c:415
static void draw_pixel(struct limine_framebuffer *fb, uint64_t x, uint64_t y, uint8_t red, uint8_t green, uint8_t blue)
Draws a pixel to the screen.
Definition main.c:275
static void hcf(void)
Halts the CPU, outputs the uptime, and outputs the user input to the console.
Definition main.c:165
uint64_t translate(uint64_t virtual_address)
Converts/Translates a virtual address to its corresponding physical address.
Definition paging.c:15
Handles memory paging and translation.
Handler for kernel panics.
Parses flags and values from strings.
bool parse_bool(const char *flag, const char *str)
Checks if a flag is present in a string and if its set to true or false.
Definition parser.c:83
void pic_remap(uint8_t master_offset, uint8_t slave_offset)
Initializes the PIC using ICWs and mask all lines.
Definition pic.c:19
Handles the legacy PIC for IRQ interrupts.
void pit_init(uint16_t frequency)
Initialize the PIT timer.
Definition pit.c:29
Handles timer interrupts from the PIT (Programmable Interrupt Timer).
Physical memory manager.
uint64_t pmm_alloc_frame(void)
Allocate a frame from the physical memory manager.
Definition pmm.c:112
void pmm_free_frame(uint64_t physical_addr)
Frees a frame from the physical memory manager.
Definition pmm.c:227
void pmm_init(const struct limine_memmap_response *memmap_response)
Initialize the physical memory manager.
Definition pmm.c:23
struct pmm_state get_pmm_state(void)
Get the current pmm state.
Definition pmm.c:19
int serial_init(void)
Initializes the serial port & output.
Definition serial.c:21
void serial_putc(char c)
Prints a character to serial port.
Definition serial.c:63
Serial utilities and configuration.
Console structure, holds all the information about the console.
Definition console.h:41
A decoded key event.
Definition keyboard.h:24
char ascii
0 if the key has no printable character
Definition keyboard.h:32
bool pressed
true = key down, false = key up
Definition keyboard.h:30
uint64_t free_frames
how many frames are currently free
Definition pmm.h:25
Tools for testing different parts of the kernel.
bool test_flag_byte(void)
Tests the flag byte utility for the gdt.
Definition tests.c:81
bool test_memset(uint64_t dest, int value)
Tests the memset utility.
Definition tests.c:38
bool test_memcpy(uint64_t dest, uint64_t b)
Tests the memcpy utility.
Definition tests.c:18
bool test_strlen(const char *str, uint8_t expected_value)
Tests the strlen utility.
Definition tests.c:67
bool test_memcmp(uint64_t dest, uint64_t b, int expected_value)
Tests the memcmp utility.
Definition tests.c:57
void test_kprintf_values(void)
Prints test data and the expected values for visual verification of kprintf.
Definition tests.c:90
bool test_access_byte(void)
Tests the access byte utility for the gdt.
Definition tests.c:74
bool test_memmove(uint64_t dest, uint64_t b)
Tests the memmove utility.
Definition tests.c:28
Kernel wide variables.
uint64_t get_hddm_offset(void)
Gets the offset for the HDDM.
Definition vars.c:18
void set_hddm_offset(uint64_t value)
Sets the offset for the HDDM.
Definition vars.c:14
Virtual memory manager.
void vmm_init(void)
Initialize the virtual memory manager and the kernel address space.
Definition vmm.c:24
uint64_t vmm_unmap(uint64_t pml4_phys, uint64_t virtual_address)
Unmaps a virtual address in the given address space.
Definition vmm.c:116
void vmm_add_region(uint64_t start, uint64_t end, uint64_t flags)
Add a region to the kernel address space.
Definition vmm.c:33
uint64_t get_kernel_pml4_phys(void)
Returns the physical address of the top-level table.
Definition vmm.c:19
uint64_t vmm_map(uint64_t pml4_phys, uint64_t virtual_address, uint64_t physical_address, uint64_t flags)
Maps a virtual address to a physical address in the given address space.
Definition vmm.c:47