feat: added ability to identify process vm regions
[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         // Attempt to execute non-executable page
32         goto segv_term;
33     }
34
35     x86_pte_t* pte = CURPROC_PTE(ptr >> 12);
36     if (*pte & PG_PRESENT) {
37         if ((hit_region->attr & REGION_PERM_MASK) == (REGION_RSHARED | REGION_READ)) {
38             // normal page fault, do COW
39                 uintptr_t pa = (uintptr_t)vmm_dup_page(__current->pid, PG_ENTRY_ADDR(*pte));
40                 pmm_free_page(__current->pid, *pte & ~0xFFF);
41                 *pte = (*pte & 0xFFF) | pa | PG_WRITE;
42                 return;
43         }
44         else {
45             // impossible cases or accessing privileged page
46             goto segv_term;
47         }
48     } else {
49         if (!(*pte)) {
50             // Invalid location
51             goto segv_term;
52         }
53         // page not present, bring it from disk or somewhere else
54         __print_panic_msg("WIP page fault route", param);
55         while (1);
56     }
57
58 segv_term:
59     kprintf(KERROR "(pid: %d) Segmentation fault on %p\n", __current->pid, ptr);
60     terminate_proc(LXSEGFAULT);
61     // should not reach
62 }