1 #include <lunaix/mm/mm.h>
2 #include <lunaix/mm/pmm.h>
3 #include <lunaix/mm/region.h>
4 #include <lunaix/mm/vmm.h>
5 #include <lunaix/sched.h>
6 #include <lunaix/signal.h>
7 #include <lunaix/status.h>
8 #include <lunaix/syslog.h>
9 #include <lunaix/trace.h>
11 #include <sys/interrupts.h>
12 #include <sys/mm/mm_defs.h>
14 #include <klibc/string.h>
20 #define COW_MASK (REGION_RSHARED | REGION_READ | REGION_WRITE)
23 __print_panic_msg(const char* msg, const isr_param* param);
26 intr_routine_page_fault(const isr_param* param)
28 if (param->depth > 10) {
29 // Too many nested fault! we must messed up something
30 // XXX should we failed silently?
34 uint32_t errcode = param->execp->err_code;
35 ptr_t ptr = cpu_ldeaddr();
41 if (!vmm_lookup(ptr, &mapping)) {
45 // XXX do kernel trigger pfault?
47 volatile x86_pte_t* pte = &PTE_MOUNTED(VMS_SELF, ptr >> 12);
49 if (guardian_page(*pte)) {
50 ERROR("memory region over-running");
54 vm_regions_t* vmr = vmregions(__current);
55 struct mm_region* hit_region = region_get(vmr, ptr);
62 if (PG_IS_PRESENT(*pte)) {
63 if (((errcode ^ mapping.flags) & PG_ALLOW_USER)) {
65 DEBUG("invalid user access. (%p->%p, attr:0x%x)",
71 if ((hit_region->attr & COW_MASK) == COW_MASK) {
72 // normal page fault, do COW
73 cpu_flush_page((ptr_t)pte);
75 ptr_t pa = (ptr_t)vmm_dup_page(PG_ENTRY_ADDR(*pte));
77 pmm_free_page(*pte & ~0xFFF);
78 *pte = (*pte & 0xFFF & ~PG_DIRTY) | pa | PG_WRITE;
82 // impossible cases or accessing privileged page
86 // an anonymous page and not present
87 // -> a new page need to be alloc
88 if ((hit_region->attr & REGION_ANON)) {
89 if (!PG_IS_PRESENT(*pte)) {
90 cpu_flush_page((ptr_t)pte);
92 ptr_t pa = pmm_alloc_page(0);
97 *pte = pa | region_ptattr(hit_region);
98 memset((void*)PG_ALIGN(ptr), 0, PG_SIZE);
101 // permission denied on anon page (e.g., write on readonly page)
105 // if mfile is set (Non-anonymous), then it is a mem map
106 if (hit_region->mfile && !PG_IS_PRESENT(*pte)) {
107 struct v_file* file = hit_region->mfile;
111 u32_t mseg_off = (ptr - hit_region->start);
112 u32_t mfile_off = mseg_off + hit_region->foff;
113 ptr_t pa = pmm_alloc_page(0);
119 cpu_flush_page((ptr_t)pte);
120 *pte = pa | region_ptattr(hit_region);
122 memset((void*)ptr, 0, PG_SIZE);
124 int errno = file->ops->read_page(file->inode, (void*)ptr, mfile_off);
127 ERROR("fail to populate page (%d)", errno);
136 // page not present, might be a chance to introduce swap file?
137 __print_panic_msg("WIP page fault route", param);
142 ERROR("out of memory");
145 ERROR("(pid: %d) Segmentation fault on %p (%p:%p,e=0x%x)",
150 param->execp->err_code);
152 trace_printstack_isr(param);
154 if (kernel_context(param)) {
155 ERROR("[page fault on kernel]");
156 // halt kernel if segv comes from kernel space
160 thread_setsignal(current_thread, _SIGSEGV);