2 * Copyright (c) 1991 Regents of the University of California.
3 * Copyright (c) 1994 John S. Dyson
4 * Copyright (c) 1994 David Greenman
5 * Copyright (c) 2003 Peter Wemm
6 * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
7 * Copyright (c) 2008-2019 The DragonFly Project.
8 * Copyright (c) 2008, 2009 Jordan Gordeev.
11 * This code is derived from software contributed to Berkeley by
12 * the Systems Programming Group of the University of Utah Computer
13 * Science Department and William Jolitz of UUNET Technologies Inc.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 * must display the following acknowledgement:
25 * This product includes software developed by the University of
26 * California, Berkeley and its contributors.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
44 * $FreeBSD: src/sys/i386/i386/pmap.c,v 1.250.2.18 2002/03/06 22:48:53 silby Exp $
48 * Manages physical address maps.
51 #include "opt_msgbuf.h"
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/kernel.h>
57 #include <sys/msgbuf.h>
58 #include <sys/vmmeter.h>
60 #include <sys/vmspace.h>
63 #include <vm/vm_param.h>
64 #include <sys/sysctl.h>
66 #include <vm/vm_kern.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_map.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_pageout.h>
72 #include <vm/vm_pager.h>
73 #include <vm/vm_zone.h>
75 #include <sys/thread2.h>
76 #include <sys/spinlock2.h>
77 #include <vm/vm_page2.h>
79 #include <machine/cputypes.h>
80 #include <machine/md_var.h>
81 #include <machine/specialreg.h>
82 #include <machine/smp.h>
83 #include <machine/globaldata.h>
84 #include <machine/pcb.h>
85 #include <machine/pmap.h>
86 #include <machine/pmap_inval.h>
95 #define PMAP_KEEP_PDIRS
96 #ifndef PMAP_SHPGPERPROC
97 #define PMAP_SHPGPERPROC 1000
100 #if defined(DIAGNOSTIC)
101 #define PMAP_DIAGNOSTIC
106 #if !defined(PMAP_DIAGNOSTIC)
107 #define PMAP_INLINE __inline
113 * Get PDEs and PTEs for user/kernel address space
115 static pd_entry_t *pmap_pde(pmap_t pmap, vm_offset_t va);
116 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
118 #define pmap_pde_v(pte) ((*(pd_entry_t *)pte & VPTE_V) != 0)
119 #define pmap_pte_w(pte) ((*(pt_entry_t *)pte & VPTE_WIRED) != 0)
120 #define pmap_pte_m(pte) ((*(pt_entry_t *)pte & VPTE_M) != 0)
121 #define pmap_pte_u(pte) ((*(pt_entry_t *)pte & VPTE_A) != 0)
122 #define pmap_pte_v(pte) ((*(pt_entry_t *)pte & VPTE_V) != 0)
125 * Given a map and a machine independent protection code,
126 * convert to a vax protection code.
128 #define pte_prot(m, p) \
129 (protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
130 static uint64_t protection_codes[8];
132 struct pmap kernel_pmap;
134 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
136 static struct vm_object kptobj;
139 static uint64_t KPDphys; /* phys addr of kernel level 2 */
140 uint64_t KPDPphys; /* phys addr of kernel level 3 */
141 uint64_t KPML4phys; /* phys addr of kernel level 4 */
143 extern int vmm_enabled;
144 extern void *vkernel_stack;
147 * Data for the pv entry allocation mechanism
149 static vm_zone_t pvzone;
150 static struct vm_zone pvzone_store;
151 static vm_pindex_t pv_entry_count = 0;
152 static vm_pindex_t pv_entry_max = 0;
153 static vm_pindex_t pv_entry_high_water = 0;
154 static int pmap_pagedaemon_waken = 0;
155 static struct pv_entry *pvinit;
158 * All those kernel PT submaps that BSD is so fond of
160 pt_entry_t *CMAP1 = NULL, *ptmmap;
161 caddr_t CADDR1 = NULL;
162 static pt_entry_t *msgbufmap;
166 static PMAP_INLINE void free_pv_entry (pv_entry_t pv);
167 static pv_entry_t get_pv_entry (void);
168 static void x86_64_protection_init (void);
169 static __inline void pmap_clearbit (vm_page_t m, int bit);
171 static void pmap_remove_all (vm_page_t m);
172 static int pmap_remove_pte (struct pmap *pmap, pt_entry_t *ptq,
173 pt_entry_t oldpte, vm_offset_t sva);
174 static void pmap_remove_page (struct pmap *pmap, vm_offset_t va);
175 static int pmap_remove_entry (struct pmap *pmap, vm_page_t m,
177 static boolean_t pmap_testbit (vm_page_t m, int bit);
178 static void pmap_insert_entry (pmap_t pmap, vm_offset_t va,
179 vm_page_t mpte, vm_page_t m, pv_entry_t);
181 static vm_page_t pmap_allocpte (pmap_t pmap, vm_offset_t va);
183 static int pmap_release_free_page (pmap_t pmap, vm_page_t p);
184 static vm_page_t _pmap_allocpte (pmap_t pmap, vm_pindex_t ptepindex);
185 static vm_page_t pmap_page_lookup (vm_object_t object, vm_pindex_t pindex);
186 static int pmap_unuse_pt (pmap_t, vm_offset_t, vm_page_t);
189 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
191 if (pv1->pv_va < pv2->pv_va)
193 if (pv1->pv_va > pv2->pv_va)
198 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
199 pv_entry_compare, vm_offset_t, pv_va);
201 static __inline vm_pindex_t
202 pmap_pt_pindex(vm_offset_t va)
204 return va >> PDRSHIFT;
207 static __inline vm_pindex_t
208 pmap_pte_index(vm_offset_t va)
210 return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
213 static __inline vm_pindex_t
214 pmap_pde_index(vm_offset_t va)
216 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
219 static __inline vm_pindex_t
220 pmap_pdpe_index(vm_offset_t va)
222 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
225 static __inline vm_pindex_t
226 pmap_pml4e_index(vm_offset_t va)
228 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
231 /* Return a pointer to the PML4 slot that corresponds to a VA */
232 static __inline pml4_entry_t *
233 pmap_pml4e(pmap_t pmap, vm_offset_t va)
235 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
238 /* Return a pointer to the PDP slot that corresponds to a VA */
239 static __inline pdp_entry_t *
240 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
244 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & VPTE_FRAME);
245 return (&pdpe[pmap_pdpe_index(va)]);
248 /* Return a pointer to the PDP slot that corresponds to a VA */
249 static __inline pdp_entry_t *
250 pmap_pdpe(pmap_t pmap, vm_offset_t va)
254 pml4e = pmap_pml4e(pmap, va);
255 if ((*pml4e & VPTE_V) == 0)
257 return (pmap_pml4e_to_pdpe(pml4e, va));
260 /* Return a pointer to the PD slot that corresponds to a VA */
261 static __inline pd_entry_t *
262 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
266 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & VPTE_FRAME);
267 return (&pde[pmap_pde_index(va)]);
270 /* Return a pointer to the PD slot that corresponds to a VA */
271 static __inline pd_entry_t *
272 pmap_pde(pmap_t pmap, vm_offset_t va)
276 pdpe = pmap_pdpe(pmap, va);
277 if (pdpe == NULL || (*pdpe & VPTE_V) == 0)
279 return (pmap_pdpe_to_pde(pdpe, va));
282 /* Return a pointer to the PT slot that corresponds to a VA */
283 static __inline pt_entry_t *
284 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
288 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & VPTE_FRAME);
289 return (&pte[pmap_pte_index(va)]);
293 * Hold pt_m for page table scans to prevent it from getting reused out
294 * from under us across blocking conditions in the body of the loop.
298 pmap_hold_pt_page(pd_entry_t *pde, vm_offset_t va)
303 pte = (pt_entry_t)*pde;
305 pt_m = PHYS_TO_VM_PAGE(pte & VPTE_FRAME);
311 /* Return a pointer to the PT slot that corresponds to a VA */
312 static __inline pt_entry_t *
313 pmap_pte(pmap_t pmap, vm_offset_t va)
317 pde = pmap_pde(pmap, va);
318 if (pde == NULL || (*pde & VPTE_V) == 0)
320 if ((*pde & VPTE_PS) != 0) /* compat with x86 pmap_pte() */
321 return ((pt_entry_t *)pde);
322 return (pmap_pde_to_pte(pde, va));
325 static PMAP_INLINE pt_entry_t *
326 vtopte(vm_offset_t va)
329 x = pmap_pte(&kernel_pmap, va);
334 static __inline pd_entry_t *
335 vtopde(vm_offset_t va)
338 x = pmap_pde(&kernel_pmap, va);
344 * Returns the physical address translation from va for a user address.
345 * (vm_paddr_t)-1 is returned on failure.
348 uservtophys(vm_offset_t va)
350 struct vmspace *vm = curproc->p_vmspace;
356 /* XXX No idea how to handle this case in a simple way, just abort */
357 if (PAGE_SIZE - (va & PAGE_MASK) < sizeof(u_int))
358 return ((vm_paddr_t)-1);
360 m = vm_fault_page(&vm->vm_map, trunc_page(va),
361 VM_PROT_READ|VM_PROT_WRITE,
365 return ((vm_paddr_t)-1);
367 pa = VM_PAGE_TO_PHYS(m) | (va & PAGE_MASK);
377 allocpages(vm_paddr_t *firstaddr, int n)
382 /*bzero((void *)ret, n * PAGE_SIZE); not mapped yet */
383 *firstaddr += n * PAGE_SIZE;
388 create_dmap_vmm(vm_paddr_t *firstaddr)
391 int pml4_stack_index;
398 uint64_t KPDP_DMAP_phys = allocpages(firstaddr, NDMPML4E);
399 uint64_t KPDP_VSTACK_phys = allocpages(firstaddr, 1);
400 uint64_t KPD_VSTACK_phys = allocpages(firstaddr, 1);
402 pml4_entry_t *KPML4virt = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
403 pdp_entry_t *KPDP_DMAP_virt = (pdp_entry_t *)PHYS_TO_DMAP(KPDP_DMAP_phys);
404 pdp_entry_t *KPDP_VSTACK_virt = (pdp_entry_t *)PHYS_TO_DMAP(KPDP_VSTACK_phys);
405 pd_entry_t *KPD_VSTACK_virt = (pd_entry_t *)PHYS_TO_DMAP(KPD_VSTACK_phys);
407 bzero(KPDP_DMAP_virt, NDMPML4E * PAGE_SIZE);
408 bzero(KPDP_VSTACK_virt, 1 * PAGE_SIZE);
409 bzero(KPD_VSTACK_virt, 1 * PAGE_SIZE);
411 do_cpuid(0x80000001, regs);
412 amd_feature = regs[3];
414 /* Build the mappings for the first 512GB */
415 if (amd_feature & AMDID_PAGE1GB) {
416 /* In pages of 1 GB, if supported */
417 for (i = 0; i < NPDPEPG; i++) {
418 KPDP_DMAP_virt[i] = ((uint64_t)i << PDPSHIFT);
419 KPDP_DMAP_virt[i] |= VPTE_RW | VPTE_V | VPTE_PS | VPTE_U;
422 /* In page of 2MB, otherwise */
423 for (i = 0; i < NPDPEPG; i++) {
424 uint64_t KPD_DMAP_phys;
425 pd_entry_t *KPD_DMAP_virt;
427 KPD_DMAP_phys = allocpages(firstaddr, 1);
429 (pd_entry_t *)PHYS_TO_DMAP(KPD_DMAP_phys);
431 bzero(KPD_DMAP_virt, PAGE_SIZE);
433 KPDP_DMAP_virt[i] = KPD_DMAP_phys;
434 KPDP_DMAP_virt[i] |= VPTE_RW | VPTE_V | VPTE_U;
436 /* For each PD, we have to allocate NPTEPG PT */
437 for (j = 0; j < NPTEPG; j++) {
438 KPD_DMAP_virt[j] = (i << PDPSHIFT) |
440 KPD_DMAP_virt[j] |= VPTE_RW | VPTE_V |
446 /* DMAP for the first 512G */
447 KPML4virt[0] = KPDP_DMAP_phys;
448 KPML4virt[0] |= VPTE_RW | VPTE_V | VPTE_U;
450 /* create a 2 MB map of the new stack */
451 pml4_stack_index = (uint64_t)&stack_addr >> PML4SHIFT;
452 KPML4virt[pml4_stack_index] = KPDP_VSTACK_phys;
453 KPML4virt[pml4_stack_index] |= VPTE_RW | VPTE_V | VPTE_U;
455 pdp_stack_index = ((uint64_t)&stack_addr & PML4MASK) >> PDPSHIFT;
456 KPDP_VSTACK_virt[pdp_stack_index] = KPD_VSTACK_phys;
457 KPDP_VSTACK_virt[pdp_stack_index] |= VPTE_RW | VPTE_V | VPTE_U;
459 pd_stack_index = ((uint64_t)&stack_addr & PDPMASK) >> PDRSHIFT;
460 KPD_VSTACK_virt[pd_stack_index] = (uint64_t) vkernel_stack;
461 KPD_VSTACK_virt[pd_stack_index] |= VPTE_RW | VPTE_V | VPTE_U | VPTE_PS;
465 create_pagetables(vm_paddr_t *firstaddr, int64_t ptov_offset)
468 pml4_entry_t *KPML4virt;
469 pdp_entry_t *KPDPvirt;
472 int kpml4i = pmap_pml4e_index(ptov_offset);
473 int kpdpi = pmap_pdpe_index(ptov_offset);
474 int kpdi = pmap_pde_index(ptov_offset);
477 * Calculate NKPT - number of kernel page tables. We have to
478 * accomodoate prealloction of the vm_page_array, dump bitmap,
479 * MSGBUF_SIZE, and other stuff. Be generous.
481 * Maxmem is in pages.
483 nkpt = (Maxmem * (sizeof(struct vm_page) * 2) + MSGBUF_SIZE) / NBPDR;
487 KPML4phys = allocpages(firstaddr, 1);
488 KPDPphys = allocpages(firstaddr, NKPML4E);
489 KPDphys = allocpages(firstaddr, NKPDPE);
490 KPTphys = allocpages(firstaddr, nkpt);
492 KPML4virt = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
493 KPDPvirt = (pdp_entry_t *)PHYS_TO_DMAP(KPDPphys);
494 KPDvirt = (pd_entry_t *)PHYS_TO_DMAP(KPDphys);
495 KPTvirt = (pt_entry_t *)PHYS_TO_DMAP(KPTphys);
497 bzero(KPML4virt, 1 * PAGE_SIZE);
498 bzero(KPDPvirt, NKPML4E * PAGE_SIZE);
499 bzero(KPDvirt, NKPDPE * PAGE_SIZE);
500 bzero(KPTvirt, nkpt * PAGE_SIZE);
502 /* Now map the page tables at their location within PTmap */
503 for (i = 0; i < nkpt; i++) {
504 KPDvirt[i + kpdi] = KPTphys + (i << PAGE_SHIFT);
505 KPDvirt[i + kpdi] |= VPTE_RW | VPTE_V | VPTE_U;
508 /* And connect up the PD to the PDP */
509 for (i = 0; i < NKPDPE; i++) {
510 KPDPvirt[i + kpdpi] = KPDphys + (i << PAGE_SHIFT);
511 KPDPvirt[i + kpdpi] |= VPTE_RW | VPTE_V | VPTE_U;
514 /* And recursively map PML4 to itself in order to get PTmap */
515 KPML4virt[PML4PML4I] = KPML4phys;
516 KPML4virt[PML4PML4I] |= VPTE_RW | VPTE_V | VPTE_U;
518 /* Connect the KVA slot up to the PML4 */
519 KPML4virt[kpml4i] = KPDPphys;
520 KPML4virt[kpml4i] |= VPTE_RW | VPTE_V | VPTE_U;
524 * Typically used to initialize a fictitious page by vm/device_pager.c
527 pmap_page_init(struct vm_page *m)
530 TAILQ_INIT(&m->md.pv_list);
534 * Bootstrap the system enough to run with virtual memory.
536 * On x86_64 this is called after mapping has already been enabled
537 * and just syncs the pmap module with what has already been done.
538 * [We can't call it easily with mapping off since the kernel is not
539 * mapped with PA == VA, hence we would have to relocate every address
540 * from the linked base (virtual) address "KERNBASE" to the actual
541 * (physical) address starting relative to 0]
544 pmap_bootstrap(vm_paddr_t *firstaddr, int64_t ptov_offset)
550 * Create an initial set of page tables to run the kernel in.
552 create_pagetables(firstaddr, ptov_offset);
554 /* Create the DMAP for the VMM */
556 create_dmap_vmm(firstaddr);
559 virtual_start = KvaStart;
560 virtual_end = KvaEnd;
563 * Initialize protection array.
565 x86_64_protection_init();
568 * The kernel's pmap is statically allocated so we don't have to use
569 * pmap_create, which is unlikely to work correctly at this part of
570 * the boot sequence (XXX and which no longer exists).
572 * The kernel_pmap's pm_pteobj is used only for locking and not
575 kernel_pmap.pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
576 kernel_pmap.pm_count = 1;
577 /* don't allow deactivation */
578 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
579 kernel_pmap.pm_pteobj = NULL; /* see pmap_init */
580 RB_INIT(&kernel_pmap.pm_pvroot);
581 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
584 * Reserve some special page table entries/VA space for temporary
587 #define SYSMAP(c, p, v, n) \
588 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
591 pte = pmap_pte(&kernel_pmap, va);
593 * CMAP1/CMAP2 are used for zeroing and copying pages.
595 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
601 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
605 * ptvmmap is used for reading arbitrary physical pages via
608 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
611 * msgbufp is used to map the system message buffer.
612 * XXX msgbufmap is not used.
614 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
615 atop(round_page(MSGBUF_SIZE)))
620 /* Not ready to do an invltlb yet for VMM*/
627 * Initialize the pmap module.
628 * Called by vm_init, to initialize any structures that the pmap
629 * system needs to map virtual memory.
630 * pmap_init has been enhanced to support in a fairly consistant
631 * way, discontiguous physical memory.
637 vm_pindex_t initial_pvs;
640 * object for kernel page table pages
642 /* JG I think the number can be arbitrary */
643 vm_object_init(&kptobj, 5);
644 kernel_pmap.pm_pteobj = &kptobj;
647 * Allocate memory for random pmap data structures. Includes the
650 for (i = 0; i < vm_page_array_size; i++) {
653 m = &vm_page_array[i];
654 TAILQ_INIT(&m->md.pv_list);
655 m->md.pv_list_count = 0;
659 * init the pv free list
661 initial_pvs = vm_page_array_size;
662 if (initial_pvs < MINPV)
664 pvzone = &pvzone_store;
665 pvinit = (struct pv_entry *)
666 kmem_alloc(&kernel_map,
667 initial_pvs * sizeof (struct pv_entry),
669 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry), pvinit,
673 * Now it is safe to enable pv_table recording.
675 pmap_initialized = TRUE;
679 * Initialize the address space (zone) for the pv_entries. Set a
680 * high water mark so that the system can recover from excessive
681 * numbers of pv entries.
686 vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
688 TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
689 pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
690 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
691 pv_entry_high_water = 9 * (pv_entry_max / 10);
692 zinitna(pvzone, NULL, 0, pv_entry_max, ZONE_INTERRUPT);
696 /***************************************************
697 * Low level helper routines.....
698 ***************************************************/
701 * The modification bit is not tracked for any pages in this range. XXX
702 * such pages in this maps should always use pmap_k*() functions and not
705 * XXX User and kernel address spaces are independant for virtual kernels,
706 * this function only applies to the kernel pmap.
709 pmap_track_modified(pmap_t pmap, vm_offset_t va)
711 KKASSERT(pmap != &kernel_pmap ||
712 va < clean_sva || va >= clean_eva);
716 * Extract the physical page address associated with the map/VA pair.
721 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
725 pd_entry_t pde, *pdep;
727 vm_object_hold(pmap->pm_pteobj);
729 pdep = pmap_pde(pmap, va);
733 if ((pde & VPTE_PS) != 0) {
735 rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
737 pte = pmap_pde_to_pte(pdep, va);
738 rtval = (*pte & VPTE_FRAME) | (va & PAGE_MASK);
743 *handlep = NULL; /* XXX */
744 vm_object_drop(pmap->pm_pteobj);
750 pmap_extract_done(void *handle)
756 vm_object_drop(pmap->pm_pteobj);
761 * Similar to extract but checks protections, SMP-friendly short-cut for
762 * vm_fault_page[_quick]().
764 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NEITHER IT NOR ITS TARGET
765 * DATA IS SUITABLE FOR WRITING. Writing can interfere with
766 * pageouts flushes, msync, etc. The hold_count is not enough
767 * to avoid races against pageouts and other flush code doesn't
768 * care about hold_count.
771 pmap_fault_page_quick(pmap_t pmap __unused, vm_offset_t vaddr __unused,
772 vm_prot_t prot __unused, int *busyp __unused)
778 * Routine: pmap_kextract
780 * Extract the physical page address associated
781 * kernel virtual address.
784 pmap_kextract(vm_offset_t va)
789 KKASSERT(va >= KvaStart && va < KvaEnd);
792 * The DMAP region is not included in [KvaStart, KvaEnd)
795 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
796 pa = DMAP_TO_PHYS(va);
802 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
805 * Beware of a concurrent promotion that changes the
806 * PDE at this point! For example, vtopte() must not
807 * be used to access the PTE because it would use the
808 * new PDE. It is, however, safe to use the old PDE
809 * because the page table page is preserved by the
812 pa = *pmap_pde_to_pte(&pde, va);
813 pa = (pa & VPTE_FRAME) | (va & PAGE_MASK);
821 /***************************************************
822 * Low level mapping routines.....
823 ***************************************************/
826 * Enter a mapping into kernel_pmap. Mappings created in this fashion
827 * are not managed. Mappings must be immediately accessible on all cpus.
829 * Call pmap_inval_pte() to invalidate the virtual pte and clean out the
830 * real pmap and handle related races before storing the new vpte. The
831 * new semantics for kenter require use to do an UNCONDITIONAL invalidation,
832 * because the entry may have previously been cleared without an invalidation.
835 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
840 KKASSERT(va >= KvaStart && va < KvaEnd);
841 npte = pa | VPTE_RW | VPTE_V | VPTE_U;
845 pmap_inval_pte(ptep, &kernel_pmap, va);
848 pmap_inval_pte(ptep, &kernel_pmap, va);
850 atomic_swap_long(ptep, npte);
854 * Enter an unmanaged KVA mapping for the private use of the current
857 * It is illegal for the mapping to be accessed by other cpus without
858 * proper invalidation.
861 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
867 KKASSERT(va >= KvaStart && va < KvaEnd);
869 npte = (vpte_t)pa | VPTE_RW | VPTE_V | VPTE_U;
873 pmap_inval_pte_quick(ptep, &kernel_pmap, va);
879 pmap_inval_pte(pte, &kernel_pmap, va);
881 atomic_swap_long(ptep, npte);
887 * Invalidation will occur later, ok to be lazy here.
890 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
896 KKASSERT(va >= KvaStart && va < KvaEnd);
898 npte = (vpte_t)pa | VPTE_RW | VPTE_V | VPTE_U;
906 atomic_swap_long(ptep, npte);
912 * Remove an unmanaged mapping created with pmap_kenter*().
915 pmap_kremove(vm_offset_t va)
919 KKASSERT(va >= KvaStart && va < KvaEnd);
922 atomic_swap_long(ptep, 0);
923 pmap_inval_pte(ptep, &kernel_pmap, va);
927 * Remove an unmanaged mapping created with pmap_kenter*() but synchronize
928 * only with this cpu.
930 * Unfortunately because we optimize new entries by testing VPTE_V later
931 * on, we actually still have to synchronize with all the cpus. XXX maybe
932 * store a junk value and test against 0 in the other places instead?
935 pmap_kremove_quick(vm_offset_t va)
939 KKASSERT(va >= KvaStart && va < KvaEnd);
942 atomic_swap_long(ptep, 0);
943 pmap_inval_pte(ptep, &kernel_pmap, va); /* NOT _quick */
947 * Invalidation will occur later, ok to be lazy here.
950 pmap_kremove_noinval(vm_offset_t va)
954 KKASSERT(va >= KvaStart && va < KvaEnd);
957 atomic_swap_long(ptep, 0);
961 * Used to map a range of physical addresses into kernel
962 * virtual address space.
964 * For now, VM is already on, we only need to map the
968 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
970 return PHYS_TO_DMAP(start);
974 * Map a set of unmanaged VM pages into KVM.
977 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
982 end_va = beg_va + count * PAGE_SIZE;
983 KKASSERT(beg_va >= KvaStart && end_va <= KvaEnd);
985 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
989 atomic_swap_long(ptep, VM_PAGE_TO_PHYS(*m) |
990 VPTE_RW | VPTE_V | VPTE_U);
994 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
995 /* pmap_inval_pte(pte, &kernel_pmap, va); */
999 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
1001 _pmap_qenter(beg_va, m, count, 1);
1005 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
1007 _pmap_qenter(beg_va, m, count, 0);
1011 * Undo the effects of pmap_qenter*().
1014 pmap_qremove(vm_offset_t beg_va, int count)
1019 end_va = beg_va + count * PAGE_SIZE;
1020 KKASSERT(beg_va >= KvaStart && end_va < KvaEnd);
1022 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1026 atomic_swap_long(ptep, 0);
1028 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
1032 * Unlike the real pmap code, we can't avoid calling the real-kernel.
1035 pmap_qremove_quick(vm_offset_t va, int count)
1037 pmap_qremove(va, count);
1041 pmap_qremove_noinval(vm_offset_t va, int count)
1043 pmap_qremove(va, count);
1047 * This routine works like vm_page_lookup() but also blocks as long as the
1048 * page is busy. This routine does not busy the page it returns.
1050 * Unless the caller is managing objects whos pages are in a known state,
1051 * the call should be made with a critical section held so the page's object
1052 * association remains valid on return.
1055 pmap_page_lookup(vm_object_t object, vm_pindex_t pindex)
1059 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1060 m = vm_page_lookup_busy_wait(object, pindex, TRUE, "pplookp");
1066 * Create a new thread and optionally associate it with a (new) process.
1067 * NOTE! the new thread's cpu may not equal the current cpu.
1070 pmap_init_thread(thread_t td)
1072 /* enforce pcb placement */
1073 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
1074 td->td_savefpu = &td->td_pcb->pcb_save;
1075 td->td_sp = (char *)td->td_pcb - 16; /* JG is -16 needed on x86_64? */
1079 * This routine directly affects the fork perf for a process.
1082 pmap_init_proc(struct proc *p)
1087 * Unwire a page table which has been removed from the pmap. We own the
1088 * wire_count, so the page cannot go away. The page representing the page
1089 * table is passed in unbusied and must be busied if we cannot trivially
1092 * XXX NOTE! This code is not usually run because we do not currently
1093 * implement dynamic page table page removal. The page in
1094 * its parent assumes at least 1 wire count, so no call to this
1095 * function ever sees a wire count less than 2.
1098 pmap_unwire_pgtable(pmap_t pmap, vm_offset_t va, vm_page_t m)
1101 * Try to unwire optimally. If non-zero is returned the wire_count
1102 * is 1 and we must busy the page to unwire it.
1104 if (vm_page_unwire_quick(m) == 0)
1107 vm_page_busy_wait(m, TRUE, "pmuwpt");
1108 KASSERT(m->queue == PQ_NONE,
1109 ("_pmap_unwire_pgtable: %p->queue != PQ_NONE", m));
1111 if (m->wire_count == 1) {
1113 * Unmap the page table page.
1115 /* pmap_inval_add(info, pmap, -1); */
1117 if (m->pindex >= (NUPT_TOTAL + NUPD_TOTAL)) {
1120 pml4 = pmap_pml4e(pmap, va);
1122 } else if (m->pindex >= NUPT_TOTAL) {
1125 pdp = pmap_pdpe(pmap, va);
1130 pd = pmap_pde(pmap, va);
1134 KKASSERT(pmap->pm_stats.resident_count > 0);
1135 atomic_add_long(&pmap->pm_stats.resident_count, -1);
1137 if (pmap->pm_ptphint == m)
1138 pmap->pm_ptphint = NULL;
1140 if (m->pindex < NUPT_TOTAL) {
1141 /* We just released a PT, unhold the matching PD */
1144 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) &
1146 pmap_unwire_pgtable(pmap, va, pdpg);
1148 if (m->pindex >= NUPT_TOTAL &&
1149 m->pindex < (NUPT_TOTAL + NUPD_TOTAL)) {
1150 /* We just released a PD, unhold the matching PDP */
1153 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) &
1155 pmap_unwire_pgtable(pmap, va, pdppg);
1159 * This was our last wire, the page had better be unwired
1160 * after we decrement wire_count.
1162 * FUTURE NOTE: shared page directory page could result in
1163 * multiple wire counts.
1165 vm_page_unwire(m, 0);
1166 KKASSERT(m->wire_count == 0);
1167 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1172 /* XXX SMP race to 1 if not holding vmobj */
1173 vm_page_unwire(m, 0);
1180 * After removing a page table entry, this routine is used to
1181 * conditionally free the page, and manage the hold/wire counts.
1183 * If not NULL the caller owns a wire_count on mpte, so it can't disappear.
1184 * If NULL the caller owns a wire_count on what would be the mpte, we must
1188 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
1190 vm_pindex_t ptepindex;
1192 ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1196 * page table pages in the kernel_pmap are not managed.
1198 if (pmap == &kernel_pmap)
1200 ptepindex = pmap_pt_pindex(va);
1201 if (pmap->pm_ptphint &&
1202 (pmap->pm_ptphint->pindex == ptepindex)) {
1203 mpte = pmap->pm_ptphint;
1205 mpte = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1206 pmap->pm_ptphint = mpte;
1207 vm_page_wakeup(mpte);
1210 return pmap_unwire_pgtable(pmap, va, mpte);
1214 * Initialize pmap0/vmspace0 . Since process 0 never enters user mode we
1215 * just dummy it up so it works well enough for fork().
1217 * In DragonFly, process pmaps may only be used to manipulate user address
1218 * space, never kernel address space.
1221 pmap_pinit0(struct pmap *pmap)
1227 * Initialize a preallocated and zeroed pmap structure,
1228 * such as one in a vmspace structure.
1231 pmap_pinit(struct pmap *pmap)
1236 * No need to allocate page table space yet but we do need a valid
1237 * page directory table.
1239 if (pmap->pm_pml4 == NULL) {
1240 pmap->pm_pml4 = (pml4_entry_t *)
1241 kmem_alloc_pageable(&kernel_map, PAGE_SIZE,
1246 * Allocate an object for the ptes
1248 if (pmap->pm_pteobj == NULL)
1249 pmap->pm_pteobj = vm_object_allocate(OBJT_DEFAULT, NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL + 1);
1252 * Allocate the page directory page, unless we already have
1253 * one cached. If we used the cached page the wire_count will
1254 * already be set appropriately.
1256 if ((ptdpg = pmap->pm_pdirm) == NULL) {
1257 ptdpg = vm_page_grab(pmap->pm_pteobj,
1258 NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL,
1259 VM_ALLOC_NORMAL | VM_ALLOC_RETRY |
1261 pmap->pm_pdirm = ptdpg;
1262 vm_page_flag_clear(ptdpg, PG_MAPPED | PG_WRITEABLE);
1263 vm_page_wire(ptdpg);
1264 vm_page_wakeup(ptdpg);
1265 pmap_kenter((vm_offset_t)pmap->pm_pml4, VM_PAGE_TO_PHYS(ptdpg));
1268 CPUMASK_ASSZERO(pmap->pm_active);
1269 pmap->pm_ptphint = NULL;
1270 RB_INIT(&pmap->pm_pvroot);
1271 spin_init(&pmap->pm_spin, "pmapinit");
1272 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1273 pmap->pm_stats.resident_count = 1;
1274 pmap->pm_stats.wired_count = 1;
1278 * Clean up a pmap structure so it can be physically freed. This routine
1279 * is called by the vmspace dtor function. A great deal of pmap data is
1280 * left passively mapped to improve vmspace management so we have a bit
1281 * of cleanup work to do here.
1286 pmap_puninit(pmap_t pmap)
1290 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
1291 if ((p = pmap->pm_pdirm) != NULL) {
1292 KKASSERT(pmap->pm_pml4 != NULL);
1293 pmap_kremove((vm_offset_t)pmap->pm_pml4);
1294 vm_page_busy_wait(p, TRUE, "pgpun");
1295 vm_page_unwire(p, 0);
1296 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
1298 pmap->pm_pdirm = NULL;
1299 atomic_add_long(&pmap->pm_stats.wired_count, -1);
1300 KKASSERT(pmap->pm_stats.wired_count == 0);
1302 if (pmap->pm_pml4) {
1303 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
1304 pmap->pm_pml4 = NULL;
1306 if (pmap->pm_pteobj) {
1307 vm_object_deallocate(pmap->pm_pteobj);
1308 pmap->pm_pteobj = NULL;
1313 * This function is now unused (used to add the pmap to the pmap_list)
1316 pmap_pinit2(struct pmap *pmap)
1321 * Attempt to release and free a vm_page in a pmap. Returns 1 on success,
1322 * 0 on failure (if the procedure had to sleep).
1324 * When asked to remove the page directory page itself, we actually just
1325 * leave it cached so we do not have to incur the SMP inval overhead of
1326 * removing the kernel mapping. pmap_puninit() will take care of it.
1329 pmap_release_free_page(struct pmap *pmap, vm_page_t p)
1332 * This code optimizes the case of freeing non-busy
1333 * page-table pages. Those pages are zero now, and
1334 * might as well be placed directly into the zero queue.
1336 if (vm_page_busy_try(p, TRUE)) {
1337 vm_page_sleep_busy(p, TRUE, "pmaprl");
1342 * Remove the page table page from the processes address space.
1344 if (p->pindex == NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL) {
1346 * We are the pml4 table itself.
1348 /* XXX anything to do here? */
1349 } else if (p->pindex >= (NUPT_TOTAL + NUPD_TOTAL)) {
1351 * We are a PDP page.
1352 * We look for the PML4 entry that points to us.
1358 m4 = vm_page_lookup(pmap->pm_pteobj,
1359 NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
1360 KKASSERT(m4 != NULL);
1361 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m4));
1362 idx = (p->pindex - (NUPT_TOTAL + NUPD_TOTAL)) % NPML4EPG;
1363 KKASSERT(pml4[idx] != 0);
1365 kprintf("pmap_release: Unmapped PML4\n");
1367 vm_page_unwire_quick(m4);
1368 } else if (p->pindex >= NUPT_TOTAL) {
1371 * We look for the PDP entry that points to us.
1377 m3 = vm_page_lookup(pmap->pm_pteobj,
1378 NUPT_TOTAL + NUPD_TOTAL +
1379 (p->pindex - NUPT_TOTAL) / NPDPEPG);
1380 KKASSERT(m3 != NULL);
1381 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m3));
1382 idx = (p->pindex - NUPT_TOTAL) % NPDPEPG;
1383 KKASSERT(pdp[idx] != 0);
1385 kprintf("pmap_release: Unmapped PDP %d\n", idx);
1387 vm_page_unwire_quick(m3);
1389 /* We are a PT page.
1390 * We look for the PD entry that points to us.
1396 m2 = vm_page_lookup(pmap->pm_pteobj,
1397 NUPT_TOTAL + p->pindex / NPDEPG);
1398 KKASSERT(m2 != NULL);
1399 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m2));
1400 idx = p->pindex % NPDEPG;
1402 kprintf("pmap_release: Unmapped PD %d\n", idx);
1404 vm_page_unwire_quick(m2);
1406 KKASSERT(pmap->pm_stats.resident_count > 0);
1407 atomic_add_long(&pmap->pm_stats.resident_count, -1);
1409 if (p->wire_count > 1) {
1410 panic("pmap_release: freeing held pt page "
1411 "pmap=%p pg=%p dmap=%p pi=%ld {%ld,%ld,%ld}",
1412 pmap, p, (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(p)),
1413 p->pindex, NUPT_TOTAL, NUPD_TOTAL, NUPDP_TOTAL);
1416 if (pmap->pm_ptphint == p)
1417 pmap->pm_ptphint = NULL;
1420 * We leave the top-level page table page cached, wired, and mapped in
1421 * the pmap until the dtor function (pmap_puninit()) gets called.
1422 * However, still clean it up.
1424 if (p->pindex == NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL) {
1425 bzero(pmap->pm_pml4, PAGE_SIZE);
1428 vm_page_unwire(p, 0);
1429 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
1431 atomic_add_long(&pmap->pm_stats.wired_count, -1);
1437 * Locate the requested PT, PD, or PDP page table page.
1439 * Returns a busied page, caller must vm_page_wakeup() when done.
1442 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex)
1451 * Find or fabricate a new pagetable page. A non-zero wire_count
1452 * indicates that the page has already been mapped into its parent.
1454 m = vm_page_grab(pmap->pm_pteobj, ptepindex,
1455 VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
1456 if (m->wire_count != 0)
1460 * Map the page table page into its parent, giving it 1 wire count.
1464 atomic_add_long(&pmap->pm_stats.resident_count, 1);
1465 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
1467 data = VM_PAGE_TO_PHYS(m) |
1468 VPTE_RW | VPTE_V | VPTE_U | VPTE_A | VPTE_M | VPTE_WIRED;
1469 atomic_add_long(&pmap->pm_stats.wired_count, 1);
1471 if (ptepindex >= (NUPT_TOTAL + NUPD_TOTAL)) {
1473 * Map PDP into the PML4
1475 pindex = ptepindex - (NUPT_TOTAL + NUPD_TOTAL);
1476 pindex &= (NUPDP_TOTAL - 1);
1477 ptep = (pt_entry_t *)pmap->pm_pml4;
1479 } else if (ptepindex >= NUPT_TOTAL) {
1481 * Map PD into its PDP
1483 pindex = (ptepindex - NUPT_TOTAL) >> NPDPEPGSHIFT;
1484 pindex += NUPT_TOTAL + NUPD_TOTAL;
1485 pm = _pmap_allocpte(pmap, pindex);
1486 pindex = (ptepindex - NUPT_TOTAL) & (NPDPEPG - 1);
1487 ptep = (void *)PHYS_TO_DMAP(pm->phys_addr);
1490 * Map PT into its PD
1492 pindex = ptepindex >> NPDPEPGSHIFT;
1493 pindex += NUPT_TOTAL;
1494 pm = _pmap_allocpte(pmap, pindex);
1495 pindex = ptepindex & (NPTEPG - 1);
1496 ptep = (void *)PHYS_TO_DMAP(pm->phys_addr);
1500 * Install the pte in (pm). (m) prevents races.
1503 data = atomic_swap_long(ptep, data);
1505 vm_page_wire_quick(pm);
1508 pmap->pm_ptphint = pm;
1514 * Determine the page table page required to access the VA in the pmap
1515 * and allocate it if necessary. Return a held vm_page_t for the page.
1517 * Only used with user pmaps.
1520 pmap_allocpte(pmap_t pmap, vm_offset_t va)
1522 vm_pindex_t ptepindex;
1525 ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1528 * Calculate pagetable page index, and return the PT page to
1531 ptepindex = pmap_pt_pindex(va);
1532 m = _pmap_allocpte(pmap, ptepindex);
1537 /***************************************************
1538 * Pmap allocation/deallocation routines.
1539 ***************************************************/
1542 * Release any resources held by the given physical map.
1543 * Called when a pmap initialized by pmap_pinit is being released.
1544 * Should only be called if the map contains no valid mappings.
1546 static int pmap_release_callback(struct vm_page *p, void *data);
1549 pmap_release(struct pmap *pmap)
1551 vm_object_t object = pmap->pm_pteobj;
1552 struct rb_vm_page_scan_info info;
1554 KKASSERT(pmap != &kernel_pmap);
1556 #if defined(DIAGNOSTIC)
1557 if (object->ref_count != 1)
1558 panic("pmap_release: pteobj reference count != 1");
1562 info.object = object;
1564 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
1565 ("pmap %p still active! %016jx",
1567 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
1569 vm_object_hold(object);
1573 info.limit = object->generation;
1575 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
1576 pmap_release_callback, &info);
1577 if (info.error == 0 && info.mpte) {
1578 if (pmap_release_free_page(pmap, info.mpte))
1581 } while (info.error);
1583 pmap->pm_ptphint = NULL;
1585 KASSERT((pmap->pm_stats.wired_count == (pmap->pm_pdirm != NULL)),
1586 ("pmap_release: dangling count %p %ld",
1587 pmap, pmap->pm_stats.wired_count));
1589 vm_object_drop(object);
1593 pmap_release_callback(struct vm_page *p, void *data)
1595 struct rb_vm_page_scan_info *info = data;
1597 if (p->pindex == NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL) {
1601 if (pmap_release_free_page(info->pmap, p)) {
1605 if (info->object->generation != info->limit) {
1613 * Grow the number of kernel page table entries, if needed.
1615 * kernel_map must be locked exclusively by the caller.
1618 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
1622 vm_offset_t ptppaddr;
1624 pd_entry_t *pde, newpdir;
1629 vm_object_hold(&kptobj);
1630 if (kernel_vm_end == 0) {
1631 kernel_vm_end = KvaStart;
1633 while ((*pmap_pde(&kernel_pmap, kernel_vm_end) & VPTE_V) != 0) {
1635 rounddown2(kernel_vm_end + PAGE_SIZE * NPTEPG,
1636 PAGE_SIZE * NPTEPG);
1638 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
1639 kernel_vm_end = vm_map_max(&kernel_map);
1644 addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1645 if (addr - 1 >= vm_map_max(&kernel_map))
1646 addr = vm_map_max(&kernel_map);
1647 while (kernel_vm_end < addr) {
1648 pde = pmap_pde(&kernel_pmap, kernel_vm_end);
1650 /* We need a new PDP entry */
1651 nkpg = vm_page_alloc(&kptobj, nkpt,
1654 VM_ALLOC_INTERRUPT);
1656 panic("pmap_growkernel: no memory to "
1659 paddr = VM_PAGE_TO_PHYS(nkpg);
1660 pmap_zero_page(paddr);
1661 newpdp = (pdp_entry_t)(paddr |
1662 VPTE_V | VPTE_RW | VPTE_U |
1663 VPTE_A | VPTE_M | VPTE_WIRED);
1664 *pmap_pdpe(&kernel_pmap, kernel_vm_end) = newpdp;
1665 atomic_add_long(&kernel_pmap.pm_stats.wired_count, 1);
1667 continue; /* try again */
1669 if ((*pde & VPTE_V) != 0) {
1671 rounddown2(kernel_vm_end + PAGE_SIZE * NPTEPG,
1672 PAGE_SIZE * NPTEPG);
1673 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
1674 kernel_vm_end = vm_map_max(&kernel_map);
1681 * This index is bogus, but out of the way
1683 nkpg = vm_page_alloc(&kptobj, nkpt,
1686 VM_ALLOC_INTERRUPT);
1688 panic("pmap_growkernel: no memory to grow kernel");
1691 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1692 pmap_zero_page(ptppaddr);
1693 newpdir = (pd_entry_t)(ptppaddr |
1694 VPTE_V | VPTE_RW | VPTE_U |
1695 VPTE_A | VPTE_M | VPTE_WIRED);
1696 *pmap_pde(&kernel_pmap, kernel_vm_end) = newpdir;
1697 atomic_add_long(&kernel_pmap.pm_stats.wired_count, 1);
1701 rounddown2(kernel_vm_end + PAGE_SIZE * NPTEPG,
1702 PAGE_SIZE * NPTEPG);
1703 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
1704 kernel_vm_end = vm_map_max(&kernel_map);
1708 vm_object_drop(&kptobj);
1712 * Add a reference to the specified pmap.
1717 pmap_reference(pmap_t pmap)
1720 atomic_add_int(&pmap->pm_count, 1);
1723 /************************************************************************
1724 * VMSPACE MANAGEMENT *
1725 ************************************************************************
1727 * The VMSPACE management we do in our virtual kernel must be reflected
1728 * in the real kernel. This is accomplished by making vmspace system
1729 * calls to the real kernel.
1732 cpu_vmspace_alloc(struct vmspace *vm)
1739 * If VMM enable, don't do nothing, we
1740 * are able to use real page tables
1745 #define USER_SIZE (VM_MAX_USER_ADDRESS - VM_MIN_USER_ADDRESS)
1747 if (vmspace_create(&vm->vm_pmap, 0, NULL) < 0)
1748 panic("vmspace_create() failed");
1750 rp = vmspace_mmap(&vm->vm_pmap, VM_MIN_USER_ADDRESS, USER_SIZE,
1751 PROT_READ|PROT_WRITE|PROT_EXEC,
1752 MAP_FILE|MAP_SHARED|MAP_VPAGETABLE|MAP_FIXED,
1754 if (rp == MAP_FAILED)
1755 panic("vmspace_mmap: failed");
1756 vmspace_mcontrol(&vm->vm_pmap, VM_MIN_USER_ADDRESS, USER_SIZE,
1758 vpte = VM_PAGE_TO_PHYS(vmspace_pmap(vm)->pm_pdirm) |
1759 VPTE_RW | VPTE_V | VPTE_U;
1760 r = vmspace_mcontrol(&vm->vm_pmap, VM_MIN_USER_ADDRESS, USER_SIZE,
1763 panic("vmspace_mcontrol: failed");
1767 cpu_vmspace_free(struct vmspace *vm)
1770 * If VMM enable, don't do nothing, we
1771 * are able to use real page tables
1776 if (vmspace_destroy(&vm->vm_pmap) < 0)
1777 panic("vmspace_destroy() failed");
1780 /***************************************************
1781 * page management routines.
1782 ***************************************************/
1785 * free the pv_entry back to the free list. This function may be
1786 * called from an interrupt.
1788 static __inline void
1789 free_pv_entry(pv_entry_t pv)
1791 atomic_add_long(&pv_entry_count, -1);
1796 * get a new pv_entry, allocating a block from the system
1797 * when needed. This function may be called from an interrupt.
1802 atomic_add_long(&pv_entry_count, 1);
1803 if (pv_entry_high_water &&
1804 (pv_entry_count > pv_entry_high_water) &&
1805 atomic_swap_int(&pmap_pagedaemon_waken, 1) == 0) {
1806 wakeup(&vm_pages_needed);
1808 return zalloc(pvzone);
1812 * This routine is very drastic, but can save the system
1822 static int warningdone=0;
1824 if (pmap_pagedaemon_waken == 0)
1826 pmap_pagedaemon_waken = 0;
1828 if (warningdone < 5) {
1829 kprintf("pmap_collect: collecting pv entries -- "
1830 "suggest increasing PMAP_SHPGPERPROC\n");
1834 for (i = 0; i < vm_page_array_size; i++) {
1835 m = &vm_page_array[i];
1836 if (m->wire_count || m->hold_count)
1838 if (vm_page_busy_try(m, TRUE) == 0) {
1839 if (m->wire_count == 0 && m->hold_count == 0) {
1849 * If it is the first entry on the list, it is actually
1850 * in the header and we must copy the following entry up
1851 * to the header. Otherwise we must search the list for
1852 * the entry. In either case we free the now unused entry.
1854 * pmap->pm_pteobj must be held and (m) must be spin-locked by the caller.
1857 pmap_remove_entry(struct pmap *pmap, vm_page_t m, vm_offset_t va)
1862 vm_page_spin_lock(m);
1863 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, va);
1866 * Note that pv_ptem is NULL if the page table page itself is not
1867 * managed, even if the page being removed IS managed.
1871 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1872 if (TAILQ_EMPTY(&m->md.pv_list))
1873 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1874 m->md.pv_list_count--;
1875 KKASSERT(m->md.pv_list_count >= 0);
1876 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
1877 atomic_add_int(&pmap->pm_generation, 1);
1878 vm_page_spin_unlock(m);
1879 rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem);
1882 vm_page_spin_unlock(m);
1883 kprintf("pmap_remove_entry: could not find "
1884 "pmap=%p m=%p va=%016jx\n",
1891 * Create a pv entry for page at pa for (pmap, va). If the page table page
1892 * holding the VA is managed, mpte will be non-NULL.
1894 * pmap->pm_pteobj must be held and (m) must be spin-locked by the caller.
1897 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m,
1904 m->md.pv_list_count++;
1905 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1906 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pv);
1907 vm_page_flag_set(m, PG_MAPPED);
1908 KKASSERT(pv == NULL);
1912 * pmap_remove_pte: do the things to unmap a page in a process
1914 * Caller holds pmap->pm_pteobj and holds the associated page table
1915 * page busy to prevent races.
1918 pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, pt_entry_t oldpte,
1925 oldpte = pmap_inval_loadandclear(ptq, pmap, va);
1927 if (oldpte & VPTE_WIRED)
1928 atomic_add_long(&pmap->pm_stats.wired_count, -1);
1929 KKASSERT(pmap->pm_stats.wired_count >= 0);
1933 * Machines that don't support invlpg, also don't support
1934 * PG_G. XXX PG_G is disabled for SMP so don't worry about
1938 cpu_invlpg((void *)va);
1940 KKASSERT(pmap->pm_stats.resident_count > 0);
1941 atomic_add_long(&pmap->pm_stats.resident_count, -1);
1942 if (oldpte & VPTE_MANAGED) {
1943 m = PHYS_TO_VM_PAGE(oldpte);
1946 * NOTE: pmap_remove_entry() will spin-lock the page
1948 if (oldpte & VPTE_M) {
1949 #if defined(PMAP_DIAGNOSTIC)
1950 if (pmap_nw_modified(oldpte)) {
1951 kprintf("pmap_remove: modified page not "
1952 "writable: va: 0x%lx, pte: 0x%lx\n",
1956 pmap_track_modified(pmap, va);
1959 if (oldpte & VPTE_A)
1960 vm_page_flag_set(m, PG_REFERENCED);
1961 error = pmap_remove_entry(pmap, m, va);
1963 error = pmap_unuse_pt(pmap, va, NULL);
1971 * Remove a single page from a process address space.
1973 * This function may not be called from an interrupt if the pmap is
1976 * Caller holds pmap->pm_pteobj
1979 pmap_remove_page(struct pmap *pmap, vm_offset_t va)
1983 pte = pmap_pte(pmap, va);
1986 if ((*pte & VPTE_V) == 0)
1988 pmap_remove_pte(pmap, pte, 0, va);
1992 * Remove the given range of addresses from the specified map.
1994 * It is assumed that the start and end are properly rounded to
1997 * This function may not be called from an interrupt if the pmap is
2003 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
2005 vm_offset_t va_next;
2006 pml4_entry_t *pml4e;
2008 pd_entry_t ptpaddr, *pde;
2015 vm_object_hold(pmap->pm_pteobj);
2016 KKASSERT(pmap->pm_stats.resident_count >= 0);
2017 if (pmap->pm_stats.resident_count == 0) {
2018 vm_object_drop(pmap->pm_pteobj);
2023 * special handling of removing one page. a very
2024 * common operation and easy to short circuit some
2027 if (sva + PAGE_SIZE == eva) {
2028 pde = pmap_pde(pmap, sva);
2029 if (pde && (*pde & VPTE_PS) == 0) {
2030 pmap_remove_page(pmap, sva);
2031 vm_object_drop(pmap->pm_pteobj);
2036 for (; sva < eva; sva = va_next) {
2037 pml4e = pmap_pml4e(pmap, sva);
2038 if ((*pml4e & VPTE_V) == 0) {
2039 va_next = (sva + NBPML4) & ~PML4MASK;
2045 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2046 if ((*pdpe & VPTE_V) == 0) {
2047 va_next = (sva + NBPDP) & ~PDPMASK;
2054 * Calculate index for next page table.
2056 va_next = (sva + NBPDR) & ~PDRMASK;
2060 pde = pmap_pdpe_to_pde(pdpe, sva);
2064 * Weed out invalid mappings.
2070 * Check for large page.
2072 if ((ptpaddr & VPTE_PS) != 0) {
2073 /* JG FreeBSD has more complex treatment here */
2074 KKASSERT(*pde != 0);
2075 pmap_inval_pde(pde, pmap, sva);
2076 atomic_add_long(&pmap->pm_stats.resident_count,
2077 -NBPDR / PAGE_SIZE);
2082 * Limit our scan to either the end of the va represented
2083 * by the current page table page, or to the end of the
2084 * range being removed.
2090 * NOTE: pmap_remove_pte() can block.
2092 pt_m = pmap_hold_pt_page(pde, sva);
2093 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2096 if (pmap_remove_pte(pmap, pte, 0, sva))
2100 vm_page_unhold(pt_m);
2102 vm_object_drop(pmap->pm_pteobj);
2106 * Removes this physical page from all physical maps in which it resides.
2107 * Reflects back modify bits to the pager.
2109 * This routine may not be called from an interrupt.
2114 pmap_remove_all(vm_page_t m)
2116 pt_entry_t *pte, tpte;
2121 #if defined(PMAP_DIAGNOSTIC)
2123 * XXX this makes pmap_page_protect(NONE) illegal for non-managed
2126 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
2127 panic("pmap_page_protect: illegal for unmanaged page, va: 0x%08llx", (long long)VM_PAGE_TO_PHYS(m));
2132 vm_page_spin_lock(m);
2133 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2135 pmobj = pmap->pm_pteobj;
2138 * Handle reversed lock ordering
2140 if (vm_object_hold_try(pmobj) == 0) {
2141 refcount_acquire(&pmobj->hold_count);
2142 vm_page_spin_unlock(m);
2143 vm_object_lock(pmobj);
2144 vm_page_spin_lock(m);
2145 if (pv != TAILQ_FIRST(&m->md.pv_list) ||
2146 pmap != pv->pv_pmap ||
2147 pmobj != pmap->pm_pteobj) {
2148 vm_page_spin_unlock(m);
2149 vm_object_drop(pmobj);
2154 KKASSERT(pmap->pm_stats.resident_count > 0);
2155 atomic_add_long(&pmap->pm_stats.resident_count, -1);
2157 pte = pmap_pte(pmap, pv->pv_va);
2158 KKASSERT(pte != NULL);
2160 tpte = pmap_inval_loadandclear(pte, pmap, pv->pv_va);
2161 if (tpte & VPTE_WIRED)
2162 atomic_add_long(&pmap->pm_stats.wired_count, -1);
2163 KKASSERT(pmap->pm_stats.wired_count >= 0);
2166 vm_page_flag_set(m, PG_REFERENCED);
2169 * Update the vm_page_t clean and reference bits.
2171 if (tpte & VPTE_M) {
2172 #if defined(PMAP_DIAGNOSTIC)
2173 if (pmap_nw_modified(tpte)) {
2175 "pmap_remove_all: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2179 pmap_track_modified(pmap, pv->pv_va);
2182 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2183 if (TAILQ_EMPTY(&m->md.pv_list))
2184 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2185 m->md.pv_list_count--;
2186 KKASSERT(m->md.pv_list_count >= 0);
2187 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
2188 atomic_add_int(&pmap->pm_generation, 1);
2189 vm_page_spin_unlock(m);
2190 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem);
2193 vm_object_drop(pmobj);
2194 vm_page_spin_lock(m);
2196 KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
2197 vm_page_spin_unlock(m);
2201 * Removes the page from a particular pmap
2204 pmap_remove_specific(pmap_t pmap, vm_page_t m)
2206 pt_entry_t *pte, tpte;
2209 vm_object_hold(pmap->pm_pteobj);
2211 vm_page_spin_lock(m);
2212 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2213 if (pv->pv_pmap != pmap)
2216 KKASSERT(pmap->pm_stats.resident_count > 0);
2217 atomic_add_long(&pmap->pm_stats.resident_count, -1);
2219 pte = pmap_pte(pmap, pv->pv_va);
2220 KKASSERT(pte != NULL);
2222 tpte = pmap_inval_loadandclear(pte, pmap, pv->pv_va);
2223 if (tpte & VPTE_WIRED)
2224 atomic_add_long(&pmap->pm_stats.wired_count, -1);
2225 KKASSERT(pmap->pm_stats.wired_count >= 0);
2228 vm_page_flag_set(m, PG_REFERENCED);
2231 * Update the vm_page_t clean and reference bits.
2233 if (tpte & VPTE_M) {
2234 pmap_track_modified(pmap, pv->pv_va);
2237 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2238 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
2239 atomic_add_int(&pmap->pm_generation, 1);
2240 m->md.pv_list_count--;
2241 KKASSERT(m->md.pv_list_count >= 0);
2242 if (TAILQ_EMPTY(&m->md.pv_list))
2243 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2244 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem);
2245 vm_page_spin_unlock(m);
2249 vm_page_spin_unlock(m);
2250 vm_object_drop(pmap->pm_pteobj);
2254 * Set the physical protection on the specified range of this map
2257 * This function may not be called from an interrupt if the map is
2258 * not the kernel_pmap.
2263 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2265 vm_offset_t va_next;
2266 pml4_entry_t *pml4e;
2268 pd_entry_t ptpaddr, *pde;
2275 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
2276 pmap_remove(pmap, sva, eva);
2280 if (prot & VM_PROT_WRITE)
2283 vm_object_hold(pmap->pm_pteobj);
2285 for (; sva < eva; sva = va_next) {
2286 pml4e = pmap_pml4e(pmap, sva);
2287 if ((*pml4e & VPTE_V) == 0) {
2288 va_next = (sva + NBPML4) & ~PML4MASK;
2294 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2295 if ((*pdpe & VPTE_V) == 0) {
2296 va_next = (sva + NBPDP) & ~PDPMASK;
2302 va_next = (sva + NBPDR) & ~PDRMASK;
2306 pde = pmap_pdpe_to_pde(pdpe, sva);
2311 * Check for large page.
2313 if ((ptpaddr & VPTE_PS) != 0) {
2315 pmap_clean_pde(pde, pmap, sva);
2316 atomic_add_long(&pmap->pm_stats.resident_count,
2317 -NBPDR / PAGE_SIZE);
2323 * Weed out invalid mappings. Note: we assume that the page
2324 * directory table is always allocated, and in kernel virtual.
2332 pt_m = pmap_hold_pt_page(pde, sva);
2333 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2336 * Clean managed pages and also check the accessed
2337 * bit. Just remove write perms for unmanaged
2338 * pages. Be careful of races, turning off write
2339 * access will force a fault rather then setting
2340 * the modified bit at an unexpected time.
2342 pmap_track_modified(pmap, sva);
2343 pmap_clean_pte(pte, pmap, sva, NULL);
2345 vm_page_unhold(pt_m);
2347 vm_object_drop(pmap->pm_pteobj);
2351 * Enter a managed page into a pmap. If the page is not wired related pmap
2352 * data can be destroyed at any time for later demand-operation.
2354 * Insert the vm_page (m) at virtual address (v) in (pmap), with the
2355 * specified protection, and wire the mapping if requested.
2357 * NOTE: This routine may not lazy-evaluate or lose information. The
2358 * page must actually be inserted into the given map NOW.
2360 * NOTE: When entering a page at a KVA address, the pmap must be the
2366 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2367 boolean_t wired, vm_map_entry_t entry __unused)
2372 pt_entry_t origpte, newpte;
2379 va = trunc_page(va);
2381 vm_object_hold(pmap->pm_pteobj);
2384 * Get the page table page. The kernel_pmap's page table pages
2385 * are preallocated and have no associated vm_page_t.
2387 * If not NULL, mpte will be busied and we must vm_page_wakeup()
2388 * to cleanup. There will already be at least one wire count from
2389 * it being mapped into its parent.
2391 if (pmap == &kernel_pmap) {
2395 mpte = pmap_allocpte(pmap, va);
2396 pte = (void *)PHYS_TO_DMAP(mpte->phys_addr);
2397 pte += pmap_pte_index(va);
2401 * Deal with races against the kernel's real MMU by cleaning the
2402 * page, even if we are re-entering the same page.
2404 pa = VM_PAGE_TO_PHYS(m);
2405 origpte = pmap_inval_loadandclear(pte, pmap, va);
2406 /*origpte = pmap_clean_pte(pte, pmap, va, NULL);*/
2407 opa = origpte & VPTE_FRAME;
2409 if (origpte & VPTE_PS)
2410 panic("pmap_enter: attempted pmap_enter on 2MB page");
2412 if ((origpte & (VPTE_MANAGED|VPTE_M)) == (VPTE_MANAGED|VPTE_M)) {
2415 pmap_track_modified(pmap, va);
2416 om = PHYS_TO_VM_PAGE(opa);
2421 * Mapping has not changed, must be protection or wiring change.
2423 if (origpte && (opa == pa)) {
2425 * Wiring change, just update stats. We don't worry about
2426 * wiring PT pages as they remain resident as long as there
2427 * are valid mappings in them. Hence, if a user page is wired,
2428 * the PT page will be also.
2430 if (wired && ((origpte & VPTE_WIRED) == 0))
2431 atomic_add_long(&pmap->pm_stats.wired_count, 1);
2432 else if (!wired && (origpte & VPTE_WIRED))
2433 atomic_add_long(&pmap->pm_stats.wired_count, -1);
2435 if (origpte & VPTE_MANAGED) {
2437 KKASSERT(m->flags & PG_MAPPED);
2438 KKASSERT((m->flags & PG_FICTITIOUS) == 0);
2440 KKASSERT((m->flags & PG_FICTITIOUS));
2442 vm_page_spin_lock(m);
2447 * Bump the wire_count for the page table page.
2450 vm_page_wire_quick(mpte);
2453 * Mapping has changed, invalidate old range and fall through to
2454 * handle validating new mapping. Don't inherit anything from
2459 err = pmap_remove_pte(pmap, NULL, origpte, va);
2462 panic("pmap_enter: pte vanished, va: 0x%lx", va);
2466 * Enter on the PV list if part of our managed memory. Note that we
2467 * raise IPL while manipulating pv_table since pmap_enter can be
2468 * called at interrupt time.
2470 if (pmap_initialized) {
2471 if ((m->flags & PG_FICTITIOUS) == 0) {
2473 * WARNING! We are using m's spin-lock as a
2474 * man's pte lock to interlock against
2475 * pmap_page_protect() operations.
2477 * This is a bad hack (obviously).
2479 pv = get_pv_entry();
2480 vm_page_spin_lock(m);
2481 pmap_insert_entry(pmap, va, mpte, m, pv);
2483 /* vm_page_spin_unlock(m); */
2485 vm_page_spin_lock(m);
2488 vm_page_spin_lock(m);
2492 * Increment counters
2494 atomic_add_long(&pmap->pm_stats.resident_count, 1);
2496 atomic_add_long(&pmap->pm_stats.wired_count, 1);
2500 * Now validate mapping with desired protection/wiring.
2502 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) | VPTE_V | VPTE_U);
2506 newpte |= VPTE_WIRED;
2507 // if (pmap != &kernel_pmap)
2509 if (newpte & VPTE_RW)
2510 vm_page_flag_set(m, PG_WRITEABLE);
2511 KKASSERT((newpte & VPTE_MANAGED) == 0 || (m->flags & PG_MAPPED));
2513 origpte = atomic_swap_long(pte, newpte);
2514 if (origpte & VPTE_M) {
2515 kprintf("pmap [M] race @ %016jx\n", va);
2516 atomic_set_long(pte, VPTE_M);
2518 vm_page_spin_unlock(m);
2521 vm_page_wakeup(mpte);
2522 vm_object_drop(pmap->pm_pteobj);
2526 * Make a temporary mapping for a physical address. This is only intended
2527 * to be used for panic dumps.
2529 * The caller is responsible for calling smp_invltlb().
2532 pmap_kenter_temporary(vm_paddr_t pa, long i)
2534 pmap_kenter_quick(crashdumpmap + (i * PAGE_SIZE), pa);
2535 return ((void *)crashdumpmap);
2538 #define MAX_INIT_PT (96)
2541 * This routine preloads the ptes for a given object into the specified pmap.
2542 * This eliminates the blast of soft faults on process startup and
2543 * immediately after an mmap.
2547 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
2550 pmap_object_init_pt(pmap_t pmap, vm_map_entry_t entry,
2551 vm_offset_t addr, vm_size_t size, int limit)
2553 vm_prot_t prot = entry->protection;
2554 vm_object_t object = entry->ba.object;
2555 vm_pindex_t pindex = atop(entry->ba.offset + (addr - entry->ba.start));
2556 struct rb_vm_page_scan_info info;
2561 * We can't preinit if read access isn't set or there is no pmap
2564 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
2568 * We can't preinit if the pmap is not the current pmap
2570 lp = curthread->td_lwp;
2571 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
2575 * Misc additional checks
2577 psize = x86_64_btop(size);
2579 if ((object->type != OBJT_VNODE) ||
2580 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
2581 (object->resident_page_count > MAX_INIT_PT))) {
2585 if (psize + pindex > object->size) {
2586 if (object->size < pindex)
2588 psize = object->size - pindex;
2595 * Use a red-black scan to traverse the requested range and load
2596 * any valid pages found into the pmap.
2598 * We cannot safely scan the object's memq unless we are in a
2599 * critical section since interrupts can remove pages from objects.
2601 info.start_pindex = pindex;
2602 info.end_pindex = pindex + psize - 1;
2609 vm_object_hold_shared(object);
2610 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2611 pmap_object_init_pt_callback, &info);
2612 vm_object_drop(object);
2617 pmap_object_init_pt_callback(vm_page_t p, void *data)
2619 struct rb_vm_page_scan_info *info = data;
2620 vm_pindex_t rel_index;
2622 * don't allow an madvise to blow away our really
2623 * free pages allocating pv entries.
2625 if ((info->limit & MAP_PREFAULT_MADVISE) &&
2626 vmstats.v_free_count < vmstats.v_free_reserved) {
2631 * Ignore list markers and ignore pages we cannot instantly
2632 * busy (while holding the object token).
2634 if (p->flags & PG_MARKER)
2636 if (vm_page_busy_try(p, TRUE))
2638 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
2639 (p->flags & PG_FICTITIOUS) == 0) {
2640 if ((p->queue - p->pc) == PQ_CACHE)
2641 vm_page_deactivate(p);
2642 rel_index = p->pindex - info->start_pindex;
2643 pmap_enter(info->pmap, info->addr + x86_64_ptob(rel_index), p,
2644 VM_PROT_READ, FALSE, info->entry);
2651 * Return TRUE if the pmap is in shape to trivially
2652 * pre-fault the specified address.
2654 * Returns FALSE if it would be non-trivial or if a
2655 * pte is already loaded into the slot.
2660 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
2666 vm_object_hold(pmap->pm_pteobj);
2667 pde = pmap_pde(pmap, addr);
2668 if (pde == NULL || *pde == 0) {
2671 pte = pmap_pde_to_pte(pde, addr);
2672 ret = (*pte) ? 0 : 1;
2674 vm_object_drop(pmap->pm_pteobj);
2680 * Change the wiring attribute for a map/virtual-address pair.
2682 * The mapping must already exist in the pmap.
2683 * No other requirements.
2686 pmap_unwire(pmap_t pmap, vm_offset_t va)
2695 vm_object_hold(pmap->pm_pteobj);
2696 pte = pmap_pte(pmap, va);
2698 if (pte == NULL || (*pte & VPTE_V) == 0) {
2699 vm_object_drop(pmap->pm_pteobj);
2704 * Wiring is not a hardware characteristic so there is no need to
2705 * invalidate TLB. However, in an SMP environment we must use
2706 * a locked bus cycle to update the pte (if we are not using
2707 * the pmap_inval_*() API that is)... it's ok to do this for simple
2710 if (pmap_pte_w(pte))
2711 atomic_add_long(&pmap->pm_stats.wired_count, -1);
2712 /* XXX else return NULL so caller doesn't unwire m ? */
2713 atomic_clear_long(pte, VPTE_WIRED);
2715 pa = *pte & VPTE_FRAME;
2716 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
2718 vm_object_drop(pmap->pm_pteobj);
2724 * Copy the range specified by src_addr/len
2725 * from the source map to the range dst_addr/len
2726 * in the destination map.
2728 * This routine is only advisory and need not do anything.
2731 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
2732 vm_size_t len, vm_offset_t src_addr)
2735 * XXX BUGGY. Amoung other things srcmpte is assumed to remain
2736 * valid through blocking calls, and that's just not going to
2747 * Zero the specified physical page.
2749 * This function may be called from an interrupt and no locking is
2753 pmap_zero_page(vm_paddr_t phys)
2755 vm_offset_t va = PHYS_TO_DMAP(phys);
2757 bzero((void *)va, PAGE_SIZE);
2763 * Zero part of a physical page by mapping it into memory and clearing
2764 * its contents with bzero.
2766 * off and size may not cover an area beyond a single hardware page.
2769 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
2771 vm_offset_t virt = PHYS_TO_DMAP(phys);
2773 bzero((char *)virt + off, size);
2779 * Copy the physical page from the source PA to the target PA.
2780 * This function may be called from an interrupt. No locking
2784 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
2786 vm_offset_t src_virt, dst_virt;
2788 src_virt = PHYS_TO_DMAP(src);
2789 dst_virt = PHYS_TO_DMAP(dst);
2790 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
2794 * pmap_copy_page_frag:
2796 * Copy the physical page from the source PA to the target PA.
2797 * This function may be called from an interrupt. No locking
2801 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
2803 vm_offset_t src_virt, dst_virt;
2805 src_virt = PHYS_TO_DMAP(src);
2806 dst_virt = PHYS_TO_DMAP(dst);
2807 bcopy((char *)src_virt + (src & PAGE_MASK),
2808 (char *)dst_virt + (dst & PAGE_MASK),
2813 * Remove all pages from specified address space this aids process
2814 * exit speeds. Also, this code is special cased for current
2815 * process only, but can have the more generic (and slightly slower)
2816 * mode enabled. This is much faster than pmap_remove in the case
2817 * of running down an entire address space.
2819 * No other requirements.
2822 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2824 pmap_remove(pmap, sva, eva);
2826 pt_entry_t *pte, tpte;
2829 int save_generation;
2831 if (pmap->pm_pteobj)
2832 vm_object_hold(pmap->pm_pteobj);
2834 pmap_invalidate_range(pmap, sva, eva);
2836 for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
2837 if (pv->pv_va >= eva || pv->pv_va < sva) {
2838 npv = TAILQ_NEXT(pv, pv_plist);
2842 KKASSERT(pmap == pv->pv_pmap);
2844 pte = pmap_pte(pmap, pv->pv_va);
2847 * We cannot remove wired pages from a process' mapping
2850 if (*pte & VPTE_WIRED) {
2851 npv = TAILQ_NEXT(pv, pv_plist);
2854 tpte = pmap_inval_loadandclear(pte, pmap, pv->pv_va);
2856 m = PHYS_TO_VM_PAGE(tpte & VPTE_FRAME);
2857 vm_page_spin_lock(m);
2859 KASSERT(m < &vm_page_array[vm_page_array_size],
2860 ("pmap_remove_pages: bad tpte %lx", tpte));
2862 KKASSERT(pmap->pm_stats.resident_count > 0);
2863 atomic_add_long(&pmap->pm_stats.resident_count, -1);
2866 * Update the vm_page_t clean and reference bits.
2868 if (tpte & VPTE_M) {
2872 npv = TAILQ_NEXT(pv, pv_plist);
2873 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2874 atomic_add_int(&pmap->pm_generation, 1);
2875 save_generation = pmap->pm_generation;
2876 m->md.pv_list_count--;
2877 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2878 if (TAILQ_EMPTY(&m->md.pv_list))
2879 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2880 vm_page_spin_unlock(m);
2882 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem);
2886 * Restart the scan if we blocked during the unuse or free
2887 * calls and other removals were made.
2889 if (save_generation != pmap->pm_generation) {
2890 kprintf("Warning: pmap_remove_pages race-A avoided\n");
2891 npv = TAILQ_FIRST(&pmap->pm_pvlist);
2894 if (pmap->pm_pteobj)
2895 vm_object_drop(pmap->pm_pteobj);
2896 pmap_remove(pmap, sva, eva);
2901 * pmap_testbit tests bits in active mappings of a VM page.
2904 pmap_testbit(vm_page_t m, int bit)
2909 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2912 if (TAILQ_FIRST(&m->md.pv_list) == NULL)
2915 vm_page_spin_lock(m);
2916 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2918 * if the bit being tested is the modified bit, then
2919 * mark clean_map and ptes as never
2922 if (bit & (VPTE_A|VPTE_M))
2923 pmap_track_modified(pv->pv_pmap, pv->pv_va);
2925 #if defined(PMAP_DIAGNOSTIC)
2926 if (pv->pv_pmap == NULL) {
2927 kprintf("Null pmap (tb) at va: 0x%lx\n", pv->pv_va);
2931 pte = pmap_pte(pv->pv_pmap, pv->pv_va);
2933 vm_page_spin_unlock(m);
2937 vm_page_spin_unlock(m);
2942 * This routine is used to clear bits in ptes. Certain bits require special
2943 * handling, in particular (on virtual kernels) the VPTE_M (modify) bit.
2945 * This routine is only called with certain VPTE_* bit combinations.
2947 static __inline void
2948 pmap_clearbit(vm_page_t m, int bit)
2956 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
2958 vm_page_flag_clear(m, PG_WRITEABLE);
2963 * Loop over all current mappings setting/clearing as appropos If
2964 * setting RO do we need to clear the VAC?
2967 vm_page_spin_lock(m);
2968 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2970 * Need the pmap object lock(?)
2973 pmobj = pmap->pm_pteobj;
2975 if (vm_object_hold_try(pmobj) == 0) {
2976 refcount_acquire(&pmobj->hold_count);
2977 vm_page_spin_unlock(m);
2978 vm_object_lock(pmobj);
2979 vm_object_drop(pmobj);
2984 * don't write protect pager mappings
2986 if (bit == VPTE_RW) {
2987 pmap_track_modified(pv->pv_pmap, pv->pv_va);
2990 #if defined(PMAP_DIAGNOSTIC)
2991 if (pv->pv_pmap == NULL) {
2992 kprintf("Null pmap (cb) at va: 0x%lx\n", pv->pv_va);
2993 vm_object_drop(pmobj);
2999 * Careful here. We can use a locked bus instruction to
3000 * clear VPTE_A or VPTE_M safely but we need to synchronize
3001 * with the target cpus when we mess with VPTE_RW.
3003 * On virtual kernels we must force a new fault-on-write
3004 * in the real kernel if we clear the Modify bit ourselves,
3005 * otherwise the real kernel will not get a new fault and
3006 * will never set our Modify bit again.
3008 pte = pmap_pte(pv->pv_pmap, pv->pv_va);
3010 if (bit == VPTE_RW) {
3012 * We must also clear VPTE_M when clearing
3013 * VPTE_RW and synchronize its state to
3016 pmap_track_modified(pv->pv_pmap, pv->pv_va);
3017 pbits = pmap_clean_pte(pte, pv->pv_pmap,
3019 } else if (bit == VPTE_M) {
3021 * We must invalidate the real-kernel pte
3022 * when clearing VPTE_M bit to force the
3023 * real-kernel to take a new fault to re-set
3026 atomic_clear_long(pte, VPTE_M);
3027 if (*pte & VPTE_RW) {
3028 pmap_invalidate_range(pv->pv_pmap,
3030 pv->pv_va + PAGE_SIZE);
3032 } else if ((bit & (VPTE_RW|VPTE_M)) ==
3035 * We've been asked to clear W & M, I guess
3036 * the caller doesn't want us to update
3037 * the dirty status of the VM page.
3039 pmap_track_modified(pv->pv_pmap, pv->pv_va);
3040 pmap_clean_pte(pte, pv->pv_pmap, pv->pv_va, m);
3041 panic("shouldn't be called");
3044 * We've been asked to clear bits that do
3045 * not interact with hardware.
3047 atomic_clear_long(pte, bit);
3050 vm_object_drop(pmobj);
3053 vm_page_flag_clear(m, PG_WRITEABLE);
3054 vm_page_spin_unlock(m);
3058 * Lower the permission for all mappings to a given page.
3060 * No other requirements.
3063 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3065 if ((prot & VM_PROT_WRITE) == 0) {
3066 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3067 pmap_clearbit(m, VPTE_RW);
3075 pmap_phys_address(vm_pindex_t ppn)
3077 return (x86_64_ptob(ppn));
3081 * Return a count of reference bits for a page, clearing those bits.
3082 * It is not necessary for every reference bit to be cleared, but it
3083 * is necessary that 0 only be returned when there are truly no
3084 * reference bits set.
3086 * XXX: The exact number of bits to check and clear is a matter that
3087 * should be tested and standardized at some point in the future for
3088 * optimal aging of shared pages.
3090 * No other requirements.
3093 pmap_ts_referenced(vm_page_t m)
3095 pv_entry_t pv, pvf, pvn;
3099 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3102 vm_page_spin_lock(m);
3103 if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3106 pvn = TAILQ_NEXT(pv, pv_list);
3107 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3108 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3110 pmap_track_modified(pv->pv_pmap, pv->pv_va);
3111 pte = pmap_pte(pv->pv_pmap, pv->pv_va);
3113 if (pte && (*pte & VPTE_A)) {
3114 atomic_clear_long(pte, VPTE_A);
3120 } while ((pv = pvn) != NULL && pv != pvf);
3122 vm_page_spin_unlock(m);
3128 * Return whether or not the specified physical page was modified
3129 * in any physical maps.
3131 * No other requirements.
3134 pmap_is_modified(vm_page_t m)
3138 res = pmap_testbit(m, VPTE_M);
3144 * Clear the modify bits on the specified physical page. For the vkernel
3145 * we really need to clean the page, which clears VPTE_RW and VPTE_M, in
3146 * order to ensure that we take a fault on the next write to the page.
3147 * Otherwise the page may become dirty without us knowing it.
3149 * No other requirements.
3152 pmap_clear_modify(vm_page_t m)
3154 pmap_clearbit(m, VPTE_RW);
3158 * Clear the reference bit on the specified physical page.
3160 * No other requirements.
3163 pmap_clear_reference(vm_page_t m)
3165 pmap_clearbit(m, VPTE_A);
3169 * Miscellaneous support routines follow
3172 x86_64_protection_init(void)
3177 kp = protection_codes;
3178 for (prot = 0; prot < 8; prot++) {
3179 if (prot & VM_PROT_READ)
3181 if (prot & VM_PROT_WRITE)
3182 *kp |= VPTE_RW; /* R+W */
3183 if (prot && (prot & VM_PROT_EXECUTE) == 0)
3184 *kp |= VPTE_NX; /* NX - !executable */
3190 * Sets the memory attribute for the specified page.
3193 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
3195 /* This is a vkernel, do nothing */
3199 * Change the PAT attribute on an existing kernel memory map. Caller
3200 * must ensure that the virtual memory in question is not accessed
3201 * during the adjustment.
3204 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
3206 /* This is a vkernel, do nothing */
3210 * Perform the pmap work for mincore
3212 * No other requirements.
3215 pmap_mincore(pmap_t pmap, vm_offset_t addr)
3217 pt_entry_t *ptep, pte;
3221 vm_object_hold(pmap->pm_pteobj);
3222 ptep = pmap_pte(pmap, addr);
3224 if (ptep && (pte = *ptep) != 0) {
3227 val = MINCORE_INCORE;
3228 if ((pte & VPTE_MANAGED) == 0)
3231 pa = pte & VPTE_FRAME;
3233 m = PHYS_TO_VM_PAGE(pa);
3239 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3241 * Modified by someone
3243 else if (m->dirty || pmap_is_modified(m))
3244 val |= MINCORE_MODIFIED_OTHER;
3249 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3252 * Referenced by someone
3254 else if ((m->flags & PG_REFERENCED) || pmap_ts_referenced(m)) {
3255 val |= MINCORE_REFERENCED_OTHER;
3256 vm_page_flag_set(m, PG_REFERENCED);
3260 vm_object_drop(pmap->pm_pteobj);
3266 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
3267 * vmspace will be ref'd and the old one will be deref'd.
3269 * Caller must hold vmspace->vm_map.token for oldvm and newvm
3272 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
3274 struct vmspace *oldvm;
3277 oldvm = p->p_vmspace;
3278 if (oldvm != newvm) {
3281 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
3282 p->p_vmspace = newvm;
3283 KKASSERT(p->p_nthreads == 1);
3284 lp = RB_ROOT(&p->p_lwp_tree);
3285 pmap_setlwpvm(lp, newvm);
3292 * Set the vmspace for a LWP. The vmspace is almost universally set the
3293 * same as the process vmspace, but virtual kernels need to swap out contexts
3294 * on a per-lwp basis.
3297 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
3299 struct vmspace *oldvm;
3302 oldvm = lp->lwp_vmspace;
3303 if (oldvm != newvm) {
3305 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
3306 lp->lwp_vmspace = newvm;
3307 if (curthread->td_lwp == lp) {
3308 pmap = vmspace_pmap(newvm);
3309 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
3310 if (pmap->pm_active_lock & CPULOCK_EXCL)
3311 pmap_interlock_wait(newvm);
3312 #if defined(SWTCH_OPTIM_STATS)
3315 pmap = vmspace_pmap(oldvm);
3316 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
3324 * The swtch code tried to switch in a heavy weight process whos pmap
3325 * is locked by another cpu. We have to wait for the lock to clear before
3326 * the pmap can be used.
3329 pmap_interlock_wait (struct vmspace *vm)
3331 pmap_t pmap = vmspace_pmap(vm);
3333 if (pmap->pm_active_lock & CPULOCK_EXCL) {
3335 while (pmap->pm_active_lock & CPULOCK_EXCL) {
3344 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3347 if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3351 addr = roundup2(addr, NBPDR);
3356 * Used by kmalloc/kfree, page already exists at va
3359 pmap_kvtom(vm_offset_t va)
3363 KKASSERT(va >= KvaStart && va < KvaEnd);
3365 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
3369 pmap_object_init(vm_object_t object)
3375 pmap_object_free(vm_object_t object)
3381 pmap_pgscan(struct pmap_pgscan_info *pginfo)
3383 pmap_t pmap = pginfo->pmap;
3384 vm_offset_t sva = pginfo->beg_addr;
3385 vm_offset_t eva = pginfo->end_addr;
3386 vm_offset_t va_next;
3387 pml4_entry_t *pml4e;
3389 pd_entry_t ptpaddr, *pde;
3394 vm_object_hold(pmap->pm_pteobj);
3396 for (; sva < eva; sva = va_next) {
3400 pml4e = pmap_pml4e(pmap, sva);
3401 if ((*pml4e & VPTE_V) == 0) {
3402 va_next = (sva + NBPML4) & ~PML4MASK;
3408 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3409 if ((*pdpe & VPTE_V) == 0) {
3410 va_next = (sva + NBPDP) & ~PDPMASK;
3416 va_next = (sva + NBPDR) & ~PDRMASK;
3420 pde = pmap_pdpe_to_pde(pdpe, sva);
3425 * Check for large page (ignore).
3427 if ((ptpaddr & VPTE_PS) != 0) {
3429 pmap_clean_pde(pde, pmap, sva);
3430 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
3437 * Weed out invalid mappings. Note: we assume that the page
3438 * directory table is always allocated, and in kernel virtual.
3446 pt_m = pmap_hold_pt_page(pde, sva);
3447 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3453 if ((*pte & VPTE_MANAGED) == 0)
3456 m = PHYS_TO_VM_PAGE(*pte & VPTE_FRAME);
3457 if (vm_page_busy_try(m, TRUE) == 0) {
3458 if (pginfo->callback(pginfo, sva, m) < 0)
3462 vm_page_unhold(pt_m);
3464 vm_object_drop(pmap->pm_pteobj);
3468 pmap_maybethreaded(pmap_t pmap)
3474 * Called while page is hard-busied to clear the PG_MAPPED and PG_WRITEABLE
3477 * vkernel code is using the old pmap style so the flags should already
3481 pmap_mapped_sync(vm_page_t m)