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