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/signal.h>
9 #include <lunaix/status.h>
10 #include <lunaix/syslog.h>
12 #include <klibc/string.h>
15 kprintf(const char* fmt, ...)
19 __kprintf("PFAULT", fmt, args);
23 #define COW_MASK (REGION_RSHARED | REGION_READ | REGION_WRITE)
26 __print_panic_msg(const char* msg, const isr_param* param);
29 intr_routine_page_fault(const isr_param* param)
31 ptr_t ptr = cpu_rcr2();
37 if (!vmm_lookup(ptr, &mapping)) {
41 if (!SEL_RPL(param->execp->cs)) {
42 // TODO if kernel pfault
45 vm_regions_t* vmr = (vm_regions_t*)&__current->mm.regions;
46 struct mm_region* hit_region = region_get(vmr, ptr);
53 volatile x86_pte_t* pte = &PTE_MOUNTED(VMS_SELF, ptr >> 12);
54 if (PG_IS_PRESENT(*pte)) {
55 if ((hit_region->attr & COW_MASK) == COW_MASK) {
56 // normal page fault, do COW
57 cpu_invplg((ptr_t)pte);
59 ptr_t pa = (ptr_t)vmm_dup_page(__current->pid, PG_ENTRY_ADDR(*pte));
61 pmm_free_page(__current->pid, *pte & ~0xFFF);
62 *pte = (*pte & 0xFFF & ~PG_DIRTY) | pa | PG_WRITE;
66 // impossible cases or accessing privileged page
70 // an anonymous page and not present
71 // -> a new page need to be alloc
72 if ((hit_region->attr & REGION_ANON)) {
73 if (!PG_IS_PRESENT(*pte)) {
74 cpu_invplg((ptr_t)pte);
76 ptr_t pa = pmm_alloc_page(__current->pid, 0);
81 *pte = *pte | pa | PG_PRESENT;
82 memset((void*)PG_ALIGN(ptr), 0, PG_SIZE);
85 // permission denied on anon page (e.g., write on readonly page)
89 // if mfile is set (Non-anonymous), then it is a mem map
90 if (hit_region->mfile && !PG_IS_PRESENT(*pte)) {
91 struct v_file* file = hit_region->mfile;
95 u32_t mseg_off = (ptr - hit_region->start);
96 u32_t mfile_off = mseg_off + hit_region->foff;
97 ptr_t pa = pmm_alloc_page(__current->pid, 0);
103 cpu_invplg((ptr_t)pte);
104 *pte = (*pte & 0xFFF) | pa | PG_PRESENT;
106 memset((void*)ptr, 0, PG_SIZE);
109 if (mseg_off < hit_region->flen) {
111 file->ops->read_page(file->inode, (void*)ptr, PG_SIZE, mfile_off);
115 kprintf(KERROR "fail to populate page (%d)\n", errno);
124 // page not present, might be a chance to introduce swap file?
125 __print_panic_msg("WIP page fault route", param);
130 kprintf(KERROR "out of memory\n");
132 kprintf(KERROR "(pid: %d) Segmentation fault on %p (%p:%p)\n",
137 __SIGSET(__current->sig_pending, _SIGSEGV);