feat: No more kernel page table switching upon interrupt.
[lunaix-os.git] / lunaix-os / kernel / asm / x86 / pfault.c
1 #include <arch/x86/interrupts.h>
2 #include <lunaix/mm/pmm.h>
3 #include <lunaix/mm/mm.h>
4 #include <lunaix/mm/region.h>
5 #include <lunaix/mm/vmm.h>
6 #include <lunaix/common.h>
7 #include <lunaix/syslog.h>
8 #include <lunaix/status.h>
9 #include <lunaix/sched.h>
10
11 static void kprintf(const char* fmt, ...) { va_list args; va_start(args, fmt); __kprintf("PFAULT", fmt, args); va_end(args); }
12
13 extern void __print_panic_msg(const char* msg, const isr_param* param);
14
15 void
16 intr_routine_page_fault (const isr_param* param) 
17 {
18     uintptr_t ptr = cpu_rcr2();
19     if (!ptr) {
20         goto segv_term;
21     }
22
23     struct mm_region* hit_region = region_get(__current, ptr);
24
25     if (!hit_region) {
26         // Into the void...
27         goto segv_term;
28     }
29
30     // if (param->eip == ptr && !(hit_region->attr & REGION_EXEC)) {
31     //     goto segv_term;
32     // }
33
34     x86_pte_t* pte = CURPROC_PTE(ptr >> 12);
35     if (*pte & PG_PRESENT) {
36         if ((hit_region->attr & REGION_PERM_MASK) == (REGION_RSHARED | REGION_READ)) {
37             // normal page fault, do COW
38                 uintptr_t pa = (uintptr_t)vmm_dup_page(__current->pid, PG_ENTRY_ADDR(*pte));
39                 pmm_free_page(__current->pid, *pte & ~0xFFF);
40                 *pte = (*pte & 0xFFF) | pa | PG_WRITE;
41                 return;
42         }
43         // impossible cases or accessing privileged page
44         goto segv_term;
45     }
46
47     if (!(*pte)) {
48         // Invalid location
49         goto segv_term;
50     }
51     uintptr_t loc = *pte & ~0xfff;
52     // a writable page, not present, pte attr is not null and no indication of cached page -> a new page need to be alloc
53     if ((hit_region->attr & REGION_WRITE) && (*pte & 0xfff) && !loc) {
54         uintptr_t pa = pmm_alloc_page(__current->pid, 0);
55         *pte = *pte | pa | PG_PRESENT;
56         return;
57     }
58     // page not present, bring it from disk or somewhere else
59     __print_panic_msg("WIP page fault route", param);
60     while (1);
61
62 segv_term:
63     kprintf(KERROR "(pid: %d) Segmentation fault on %p (%p:%p)\n", __current->pid, ptr, param->cs, param->eip);
64     terminate_proc(LXSEGFAULT);
65     // should not reach
66 }