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>
13 #include <klibc/string.h>
18 get_ptattr(struct mm_region* vmr)
20 u32_t vmr_attr = vmr->attr;
21 u32_t ptattr = PG_PRESENT | PG_ALLOW_USER;
23 if ((vmr_attr & PROT_WRITE)) {
27 return ptattr & 0xfff;
30 #define COW_MASK (REGION_RSHARED | REGION_READ | REGION_WRITE)
33 __print_panic_msg(const char* msg, const isr_param* param);
36 intr_routine_page_fault(const isr_param* param)
38 uint32_t errcode = param->execp->err_code;
39 ptr_t ptr = cpu_ldeaddr();
45 if (!vmm_lookup(ptr, &mapping)) {
49 // XXX do kernel trigger pfault?
51 vm_regions_t* vmr = (vm_regions_t*)&__current->mm.regions;
52 struct mm_region* hit_region = region_get(vmr, ptr);
59 volatile x86_pte_t* pte = &PTE_MOUNTED(VMS_SELF, ptr >> 12);
60 if (PG_IS_PRESENT(*pte)) {
61 if (((errcode ^ mapping.flags) & PG_ALLOW_USER)) {
63 DEBUG("invalid user access. (%p->%p, attr:0x%x)",
69 if ((hit_region->attr & COW_MASK) == COW_MASK) {
70 // normal page fault, do COW
71 cpu_flush_page((ptr_t)pte);
73 ptr_t pa = (ptr_t)vmm_dup_page(__current->pid, PG_ENTRY_ADDR(*pte));
75 pmm_free_page(__current->pid, *pte & ~0xFFF);
76 *pte = (*pte & 0xFFF & ~PG_DIRTY) | pa | PG_WRITE;
80 // impossible cases or accessing privileged page
84 // an anonymous page and not present
85 // -> a new page need to be alloc
86 if ((hit_region->attr & REGION_ANON)) {
87 if (!PG_IS_PRESENT(*pte)) {
88 cpu_flush_page((ptr_t)pte);
90 ptr_t pa = pmm_alloc_page(__current->pid, 0);
95 *pte = *pte | pa | get_ptattr(hit_region);
96 memset((void*)PG_ALIGN(ptr), 0, PG_SIZE);
99 // permission denied on anon page (e.g., write on readonly page)
103 // if mfile is set (Non-anonymous), then it is a mem map
104 if (hit_region->mfile && !PG_IS_PRESENT(*pte)) {
105 struct v_file* file = hit_region->mfile;
109 u32_t mseg_off = (ptr - hit_region->start);
110 u32_t mfile_off = mseg_off + hit_region->foff;
111 ptr_t pa = pmm_alloc_page(__current->pid, 0);
117 cpu_flush_page((ptr_t)pte);
118 *pte = (*pte & 0xFFF) | pa | get_ptattr(hit_region);
120 memset((void*)ptr, 0, PG_SIZE);
123 if (mseg_off < hit_region->flen) {
124 errno = file->ops->read_page(file->inode, (void*)ptr, mfile_off);
128 ERROR("fail to populate page (%d)", errno);
137 // page not present, might be a chance to introduce swap file?
138 __print_panic_msg("WIP page fault route", param);
143 ERROR("out of memory");
146 ERROR("(pid: %d) Segmentation fault on %p (%p:%p,e=0x%x)",
151 param->execp->err_code);
153 sigset_add(__current->sigctx.sig_pending, _SIGSEGV);
155 trace_printstack_isr(param);