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, 2009 The DragonFly Project.
8 * Copyright (c) 2008, 2009 Jordan Gordeev.
9 * Copyright (c) 2011-2017 Matthew Dillon
10 * All rights reserved.
12 * This code is derived from software contributed to Berkeley by
13 * the Systems Programming Group of the University of Utah Computer
14 * Science Department and William Jolitz of UUNET Technologies Inc.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. All advertising materials mentioning features or use of this software
25 * must display the following acknowledgement:
26 * This product includes software developed by the University of
27 * California, Berkeley and its contributors.
28 * 4. Neither the name of the University nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * Manage physical address maps for x86-64 systems.
48 * - The 'M'odified bit is only applicable to terminal PTEs.
50 * - The 'U'ser access bit can be set for higher-level PTEs as
51 * long as it isn't set for terminal PTEs for pages we don't
52 * want user access to.
58 #include "opt_msgbuf.h"
60 #include <sys/param.h>
61 #include <sys/kernel.h>
63 #include <sys/msgbuf.h>
64 #include <sys/vmmeter.h>
66 #include <sys/systm.h>
69 #include <vm/vm_param.h>
70 #include <sys/sysctl.h>
72 #include <vm/vm_kern.h>
73 #include <vm/vm_page.h>
74 #include <vm/vm_map.h>
75 #include <vm/vm_object.h>
76 #include <vm/vm_extern.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_pager.h>
79 #include <vm/vm_zone.h>
82 #include <sys/thread2.h>
83 #include <sys/spinlock2.h>
84 #include <vm/vm_page2.h>
86 #include <machine/cputypes.h>
87 #include <machine/cpu.h>
88 #include <machine/md_var.h>
89 #include <machine/specialreg.h>
90 #include <machine/smp.h>
91 #include <machine_base/apic/apicreg.h>
92 #include <machine/globaldata.h>
93 #include <machine/pmap.h>
94 #include <machine/pmap_inval.h>
95 #include <machine/inttypes.h>
99 #define PMAP_KEEP_PDIRS
100 #ifndef PMAP_SHPGPERPROC
101 #define PMAP_SHPGPERPROC 2000
104 #if defined(DIAGNOSTIC)
105 #define PMAP_DIAGNOSTIC
111 * pmap debugging will report who owns a pv lock when blocking.
115 #define PMAP_DEBUG_DECL ,const char *func, int lineno
116 #define PMAP_DEBUG_ARGS , __func__, __LINE__
117 #define PMAP_DEBUG_COPY , func, lineno
119 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp \
121 #define pv_lock(pv) _pv_lock(pv \
123 #define pv_hold_try(pv) _pv_hold_try(pv \
125 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp \
128 #define pv_free(pv, pvp) _pv_free(pv, pvp PMAP_DEBUG_ARGS)
132 #define PMAP_DEBUG_DECL
133 #define PMAP_DEBUG_ARGS
134 #define PMAP_DEBUG_COPY
136 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp)
137 #define pv_lock(pv) _pv_lock(pv)
138 #define pv_hold_try(pv) _pv_hold_try(pv)
139 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp)
140 #define pv_free(pv, pvp) _pv_free(pv, pvp)
145 * Get PDEs and PTEs for user/kernel address space
147 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
149 #define pmap_pde_v(pmap, pte) ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
150 #define pmap_pte_w(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
151 #define pmap_pte_m(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
152 #define pmap_pte_u(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
153 #define pmap_pte_v(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
156 * Given a map and a machine independent protection code,
157 * convert to a vax protection code.
159 #define pte_prot(m, p) \
160 (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
161 static uint64_t protection_codes[PROTECTION_CODES_SIZE];
163 struct pmap kernel_pmap;
164 struct pmap iso_pmap;
166 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
168 vm_paddr_t avail_start; /* PA of first available physical page */
169 vm_paddr_t avail_end; /* PA of last available physical page */
170 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
171 vm_offset_t virtual2_end;
172 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
173 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
174 vm_offset_t KvaStart; /* VA start of KVA space */
175 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
176 vm_offset_t KvaSize; /* max size of kernel virtual address space */
177 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
178 //static int pgeflag; /* PG_G or-in */
182 static vm_paddr_t dmaplimit;
183 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
185 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
186 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
188 static uint64_t KPTbase;
189 static uint64_t KPTphys;
190 static uint64_t KPDphys; /* phys addr of kernel level 2 */
191 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
192 uint64_t KPDPphys; /* phys addr of kernel level 3 */
193 uint64_t KPML4phys; /* phys addr of kernel level 4 */
195 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
196 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
199 * Data for the pv entry allocation mechanism
201 static vm_zone_t pvzone;
202 static struct vm_zone pvzone_store;
203 static vm_pindex_t pv_entry_max=0, pv_entry_high_water=0;
204 static int pmap_pagedaemon_waken = 0;
205 static struct pv_entry *pvinit;
208 * All those kernel PT submaps that BSD is so fond of
210 pt_entry_t *CMAP1 = NULL, *ptmmap;
211 caddr_t CADDR1 = NULL, ptvmmap = NULL;
212 static pt_entry_t *msgbufmap;
213 struct msgbuf *msgbufp=NULL;
216 * PMAP default PG_* bits. Needed to be able to add
217 * EPT/NPT pagetable pmap_bits for the VMM module
219 uint64_t pmap_bits_default[] = {
220 REGULAR_PMAP, /* TYPE_IDX 0 */
221 X86_PG_V, /* PG_V_IDX 1 */
222 X86_PG_RW, /* PG_RW_IDX 2 */
223 X86_PG_U, /* PG_U_IDX 3 */
224 X86_PG_A, /* PG_A_IDX 4 */
225 X86_PG_M, /* PG_M_IDX 5 */
226 X86_PG_PS, /* PG_PS_IDX3 6 */
227 X86_PG_G, /* PG_G_IDX 7 */
228 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
229 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
230 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
231 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
232 X86_PG_NX, /* PG_NX_IDX 12 */
237 static pt_entry_t *pt_crashdumpmap;
238 static caddr_t crashdumpmap;
240 static int pmap_debug = 0;
241 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
242 &pmap_debug, 0, "Debug pmap's");
244 static int pmap_enter_debug = 0;
245 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
246 &pmap_enter_debug, 0, "Debug pmap_enter's");
248 static int pmap_yield_count = 64;
249 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
250 &pmap_yield_count, 0, "Yield during init_pt/release");
251 static int pmap_mmu_optimize = 0;
252 SYSCTL_INT(_machdep, OID_AUTO, pmap_mmu_optimize, CTLFLAG_RW,
253 &pmap_mmu_optimize, 0, "Share page table pages when possible");
254 int pmap_fast_kernel_cpusync = 0;
255 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
256 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
257 int pmap_dynamic_delete = 0;
258 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
259 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
260 int pmap_lock_delay = 100;
261 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
262 &pmap_lock_delay, 0, "Spin loops");
263 static int meltdown_mitigation = -1;
264 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
265 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
266 &meltdown_mitigation, 0, "Userland pmap isolation");
268 static int pmap_nx_enable = 0;
269 /* needs manual TUNABLE in early probe, see below */
271 /* Standard user access funtions */
272 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
274 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
275 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
276 extern int std_fubyte (const uint8_t *base);
277 extern int std_subyte (uint8_t *base, uint8_t byte);
278 extern int32_t std_fuword32 (const uint32_t *base);
279 extern int64_t std_fuword64 (const uint64_t *base);
280 extern int std_suword64 (uint64_t *base, uint64_t word);
281 extern int std_suword32 (uint32_t *base, int word);
282 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
283 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
284 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
285 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
287 static void pv_hold(pv_entry_t pv);
288 static int _pv_hold_try(pv_entry_t pv
290 static void pv_drop(pv_entry_t pv);
291 static void _pv_lock(pv_entry_t pv
293 static void pv_unlock(pv_entry_t pv);
294 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
296 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
298 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
299 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
300 vm_pindex_t **pmarkp, int *errorp);
301 static void pv_put(pv_entry_t pv);
302 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
303 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
305 static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
306 pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
307 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
308 pmap_inval_bulk_t *bulk, int destroy);
309 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
310 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
311 pmap_inval_bulk_t *bulk);
313 struct pmap_scan_info;
314 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
315 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
316 pv_entry_t pt_pv, int sharept,
317 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
318 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
319 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
320 pv_entry_t pt_pv, int sharept,
321 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
323 static void x86_64_protection_init (void);
324 static void create_pagetables(vm_paddr_t *firstaddr);
325 static void pmap_remove_all (vm_page_t m);
326 static boolean_t pmap_testbit (vm_page_t m, int bit);
328 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
329 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
331 static void pmap_pinit_defaults(struct pmap *pmap);
332 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
333 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
336 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
338 if (pv1->pv_pindex < pv2->pv_pindex)
340 if (pv1->pv_pindex > pv2->pv_pindex)
345 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
346 pv_entry_compare, vm_pindex_t, pv_pindex);
350 pmap_page_stats_adding(vm_page_t m)
352 globaldata_t gd = mycpu;
354 if (TAILQ_EMPTY(&m->md.pv_list)) {
355 ++gd->gd_vmtotal.t_arm;
356 } else if (TAILQ_FIRST(&m->md.pv_list) ==
357 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
358 ++gd->gd_vmtotal.t_armshr;
359 ++gd->gd_vmtotal.t_avmshr;
361 ++gd->gd_vmtotal.t_avmshr;
367 pmap_page_stats_deleting(vm_page_t m)
369 globaldata_t gd = mycpu;
371 if (TAILQ_EMPTY(&m->md.pv_list)) {
372 --gd->gd_vmtotal.t_arm;
373 } else if (TAILQ_FIRST(&m->md.pv_list) ==
374 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
375 --gd->gd_vmtotal.t_armshr;
376 --gd->gd_vmtotal.t_avmshr;
378 --gd->gd_vmtotal.t_avmshr;
383 * This is an ineligent crowbar to prevent heavily threaded programs
384 * from creating long live-locks in the pmap code when pmap_mmu_optimize
385 * is enabled. Without it a pmap-local page table page can wind up being
386 * constantly created and destroyed (without injury, but also without
387 * progress) as the optimization tries to switch to the object's shared page
391 pmap_softwait(pmap_t pmap)
393 while (pmap->pm_softhold) {
394 tsleep_interlock(&pmap->pm_softhold, 0);
395 if (pmap->pm_softhold)
396 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
401 pmap_softhold(pmap_t pmap)
403 while (atomic_swap_int(&pmap->pm_softhold, 1) == 1) {
404 tsleep_interlock(&pmap->pm_softhold, 0);
405 if (atomic_swap_int(&pmap->pm_softhold, 1) == 1)
406 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
411 pmap_softdone(pmap_t pmap)
413 atomic_swap_int(&pmap->pm_softhold, 0);
414 wakeup(&pmap->pm_softhold);
418 * Move the kernel virtual free pointer to the next
419 * 2MB. This is used to help improve performance
420 * by using a large (2MB) page for much of the kernel
421 * (.text, .data, .bss)
425 pmap_kmem_choose(vm_offset_t addr)
427 vm_offset_t newaddr = addr;
429 newaddr = roundup2(addr, NBPDR);
434 * Returns the pindex of a page table entry (representing a terminal page).
435 * There are NUPTE_TOTAL page table entries possible (a huge number)
437 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
438 * We want to properly translate negative KVAs.
442 pmap_pte_pindex(vm_offset_t va)
444 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
448 * Returns the pindex of a page table.
452 pmap_pt_pindex(vm_offset_t va)
454 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
458 * Returns the pindex of a page directory.
462 pmap_pd_pindex(vm_offset_t va)
464 return (NUPTE_TOTAL + NUPT_TOTAL +
465 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
470 pmap_pdp_pindex(vm_offset_t va)
472 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
473 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
478 pmap_pml4_pindex(void)
480 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
484 * Return various clipped indexes for a given VA
486 * Returns the index of a pt in a page directory, representing a page
491 pmap_pt_index(vm_offset_t va)
493 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
497 * Returns the index of a pd in a page directory page, representing a page
502 pmap_pd_index(vm_offset_t va)
504 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
508 * Returns the index of a pdp in the pml4 table, representing a page
513 pmap_pdp_index(vm_offset_t va)
515 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
519 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
520 * the PT layer. This will speed up core pmap operations considerably.
521 * We also cache the PTE layer to (hopefully) improve relative lookup
524 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
525 * must be in a known associated state (typically by being locked when
526 * the pmap spinlock isn't held). We allow the race for that case.
528 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
529 * cpu_ccfence() to prevent compiler optimizations from reloading the
534 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
536 if (pindex < pmap_pt_pindex(0)) {
537 pmap->pm_pvhint_pte = pv;
538 } else if (pindex < pmap_pd_pindex(0)) {
539 pmap->pm_pvhint_pt = pv;
544 * Locate the requested pt_entry
548 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
553 if (pindex < pmap_pt_pindex(0))
554 pv = pmap->pm_pvhint_pte;
555 else if (pindex < pmap_pd_pindex(0))
556 pv = pmap->pm_pvhint_pt;
560 if (pv == NULL || pv->pv_pmap != pmap) {
561 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
563 pv_cache(pmap, pv, pindex);
564 } else if (pv->pv_pindex != pindex) {
565 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
568 pv_cache(pmap, pv, pindex);
571 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
579 * Super fast pmap_pte routine best used when scanning the pv lists.
580 * This eliminates many course-grained invltlb calls. Note that many of
581 * the pv list scans are across different pmaps and it is very wasteful
582 * to do an entire invltlb when checking a single mapping.
584 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
588 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
590 return pmap_pte(pmap, va);
594 * The placemarker hash must be broken up into four zones so lock
595 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
597 * Placemarkers are used to 'lock' page table indices that do not have
598 * a pv_entry. This allows the pmap to support managed and unmanaged
599 * pages and shared page tables.
601 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
605 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
609 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
611 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
613 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
614 hi = PM_PLACE_BASE << 1;
615 else /* zone 3 - PDP (and PML4E) */
616 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
617 hi += pindex & (PM_PLACE_BASE - 1);
619 return (&pmap->pm_placemarks[hi]);
624 * Generic procedure to index a pte from a pt, pd, or pdp.
626 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
627 * a page table page index but is instead of PV lookup index.
631 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
635 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
636 return(&pte[pindex]);
640 * Return pointer to PDP slot in the PML4
644 pmap_pdp(pmap_t pmap, vm_offset_t va)
646 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
650 * Return pointer to PD slot in the PDP given a pointer to the PDP
654 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
658 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
659 return (&pd[pmap_pd_index(va)]);
663 * Return pointer to PD slot in the PDP.
667 pmap_pd(pmap_t pmap, vm_offset_t va)
671 pdp = pmap_pdp(pmap, va);
672 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
674 return (pmap_pdp_to_pd(*pdp, va));
678 * Return pointer to PT slot in the PD given a pointer to the PD
682 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
686 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
687 return (&pt[pmap_pt_index(va)]);
691 * Return pointer to PT slot in the PD
693 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
694 * so we cannot lookup the PD via the PDP. Instead we
695 * must look it up via the pmap.
699 pmap_pt(pmap_t pmap, vm_offset_t va)
703 vm_pindex_t pd_pindex;
706 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
707 pd_pindex = pmap_pd_pindex(va);
708 spin_lock_shared(&pmap->pm_spin);
709 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
710 if (pv == NULL || pv->pv_m == NULL) {
711 spin_unlock_shared(&pmap->pm_spin);
714 phys = VM_PAGE_TO_PHYS(pv->pv_m);
715 spin_unlock_shared(&pmap->pm_spin);
716 return (pmap_pd_to_pt(phys, va));
718 pd = pmap_pd(pmap, va);
719 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
721 return (pmap_pd_to_pt(*pd, va));
726 * Return pointer to PTE slot in the PT given a pointer to the PT
730 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
734 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
735 return (&pte[pmap_pte_index(va)]);
739 * Return pointer to PTE slot in the PT
743 pmap_pte(pmap_t pmap, vm_offset_t va)
747 pt = pmap_pt(pmap, va);
748 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
750 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
751 return ((pt_entry_t *)pt);
752 return (pmap_pt_to_pte(*pt, va));
756 * Return address of PT slot in PD (KVM only)
758 * Cannot be used for user page tables because it might interfere with
759 * the shared page-table-page optimization (pmap_mmu_optimize).
763 vtopt(vm_offset_t va)
765 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
766 NPML4EPGSHIFT)) - 1);
768 return (PDmap + ((va >> PDRSHIFT) & mask));
772 * KVM - return address of PTE slot in PT
776 vtopte(vm_offset_t va)
778 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
779 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
781 return (PTmap + ((va >> PAGE_SHIFT) & mask));
785 * Returns the physical address translation from va for a user address.
786 * (vm_paddr_t)-1 is returned on failure.
789 uservtophys(vm_offset_t va)
791 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
792 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
797 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
799 if (va < VM_MAX_USER_ADDRESS) {
800 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
801 if (pte & pmap->pmap_bits[PG_V_IDX])
802 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
808 allocpages(vm_paddr_t *firstaddr, long n)
813 bzero((void *)ret, n * PAGE_SIZE);
814 *firstaddr += n * PAGE_SIZE;
820 create_pagetables(vm_paddr_t *firstaddr)
822 long i; /* must be 64 bits */
829 * We are running (mostly) V=P at this point
831 * Calculate how many 1GB PD entries in our PDP pages are needed
832 * for the DMAP. This is only allocated if the system does not
833 * support 1GB pages. Otherwise ndmpdp is simply a count of
834 * the number of 1G terminal entries in our PDP pages are needed.
836 * NOTE: Maxmem is in pages
838 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
839 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
841 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
844 * Starting at KERNBASE - map all 2G worth of page table pages.
845 * KERNBASE is offset -2G from the end of kvm. This will accomodate
846 * all KVM allocations above KERNBASE, including the SYSMAPs below.
848 * We do this by allocating 2*512 PT pages. Each PT page can map
849 * 2MB, for 2GB total.
851 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
854 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
855 * Calculate how many page table pages we need to preallocate
856 * for early vm_map allocations.
858 * A few extra won't hurt, they will get used up in the running
864 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
865 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
866 nkpt_phys += 128; /* a few extra */
869 * The highest value nkpd_phys can be set to is
870 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
872 * Doing so would cause all PD pages to be pre-populated for
873 * a maximal KVM space (approximately 16*512 pages, or 32MB.
874 * We can save memory by not doing this.
876 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
881 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
882 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
884 * Only allocate enough PD pages
885 * NOTE: We allocate all kernel PD pages up-front, typically
886 * ~511G of KVM, requiring 511 PD pages.
888 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
889 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
890 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
891 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
892 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
895 * Alloc PD pages for the area starting at KERNBASE.
897 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
902 DMPDPphys = allocpages(firstaddr, NDMPML4E);
903 if ((amd_feature & AMDID_PAGE1GB) == 0)
904 DMPDphys = allocpages(firstaddr, ndmpdp);
905 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
908 * Fill in the underlying page table pages for the area around
909 * KERNBASE. This remaps low physical memory to KERNBASE.
911 * Read-only from zero to physfree
912 * XXX not fully used, underneath 2M pages
914 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
915 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
916 ((pt_entry_t *)KPTbase)[i] |=
917 pmap_bits_default[PG_RW_IDX] |
918 pmap_bits_default[PG_V_IDX] |
919 pmap_bits_default[PG_G_IDX];
923 * Now map the initial kernel page tables. One block of page
924 * tables is placed at the beginning of kernel virtual memory,
925 * and another block is placed at KERNBASE to map the kernel binary,
926 * data, bss, and initial pre-allocations.
928 for (i = 0; i < nkpt_base; i++) {
929 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
930 ((pd_entry_t *)KPDbase)[i] |=
931 pmap_bits_default[PG_RW_IDX] |
932 pmap_bits_default[PG_V_IDX];
934 for (i = 0; i < nkpt_phys; i++) {
935 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
936 ((pd_entry_t *)KPDphys)[i] |=
937 pmap_bits_default[PG_RW_IDX] |
938 pmap_bits_default[PG_V_IDX];
942 * Map from zero to end of allocations using 2M pages as an
943 * optimization. This will bypass some of the KPTBase pages
944 * above in the KERNBASE area.
946 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
947 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
948 ((pd_entry_t *)KPDbase)[i] |=
949 pmap_bits_default[PG_RW_IDX] |
950 pmap_bits_default[PG_V_IDX] |
951 pmap_bits_default[PG_PS_IDX] |
952 pmap_bits_default[PG_G_IDX];
956 * Load PD addresses into the PDP pages for primary KVA space to
957 * cover existing page tables. PD's for KERNBASE are handled in
960 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
962 for (i = 0; i < nkpd_phys; i++) {
963 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
964 KPDphys + (i << PAGE_SHIFT);
965 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
966 pmap_bits_default[PG_RW_IDX] |
967 pmap_bits_default[PG_V_IDX] |
968 pmap_bits_default[PG_A_IDX];
972 * Load PDs for KERNBASE to the end
974 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
975 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
976 ((pdp_entry_t *)KPDPphys)[i + j] =
977 KPDbase + (j << PAGE_SHIFT);
978 ((pdp_entry_t *)KPDPphys)[i + j] |=
979 pmap_bits_default[PG_RW_IDX] |
980 pmap_bits_default[PG_V_IDX] |
981 pmap_bits_default[PG_A_IDX];
985 * Now set up the direct map space using either 2MB or 1GB pages
986 * Preset PG_M and PG_A because demotion expects it.
988 * When filling in entries in the PD pages make sure any excess
989 * entries are set to zero as we allocated enough PD pages
991 if ((amd_feature & AMDID_PAGE1GB) == 0) {
995 for (i = 0; i < NPDEPG * ndmpdp; i++) {
996 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
997 ((pd_entry_t *)DMPDphys)[i] |=
998 pmap_bits_default[PG_RW_IDX] |
999 pmap_bits_default[PG_V_IDX] |
1000 pmap_bits_default[PG_PS_IDX] |
1001 pmap_bits_default[PG_G_IDX] |
1002 pmap_bits_default[PG_M_IDX] |
1003 pmap_bits_default[PG_A_IDX];
1007 * And the direct map space's PDP
1009 for (i = 0; i < ndmpdp; i++) {
1010 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1012 ((pdp_entry_t *)DMPDPphys)[i] |=
1013 pmap_bits_default[PG_RW_IDX] |
1014 pmap_bits_default[PG_V_IDX];
1020 for (i = 0; i < ndmpdp; i++) {
1021 ((pdp_entry_t *)DMPDPphys)[i] =
1022 (vm_paddr_t)i << PDPSHIFT;
1023 ((pdp_entry_t *)DMPDPphys)[i] |=
1024 pmap_bits_default[PG_RW_IDX] |
1025 pmap_bits_default[PG_V_IDX] |
1026 pmap_bits_default[PG_PS_IDX] |
1027 pmap_bits_default[PG_G_IDX] |
1028 pmap_bits_default[PG_M_IDX] |
1029 pmap_bits_default[PG_A_IDX];
1033 /* And recursively map PML4 to itself in order to get PTmap */
1034 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1035 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1036 pmap_bits_default[PG_RW_IDX] |
1037 pmap_bits_default[PG_V_IDX] |
1038 pmap_bits_default[PG_A_IDX];
1041 * Connect the Direct Map slots up to the PML4
1043 for (j = 0; j < NDMPML4E; ++j) {
1044 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1045 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1046 pmap_bits_default[PG_RW_IDX] |
1047 pmap_bits_default[PG_V_IDX] |
1048 pmap_bits_default[PG_A_IDX];
1052 * Connect the KVA slot up to the PML4
1054 for (j = 0; j < NKPML4E; ++j) {
1055 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1056 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1057 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1058 pmap_bits_default[PG_RW_IDX] |
1059 pmap_bits_default[PG_V_IDX] |
1060 pmap_bits_default[PG_A_IDX];
1067 * Bootstrap the system enough to run with virtual memory.
1069 * On x86_64 this is called after mapping has already been enabled
1070 * and just syncs the pmap module with what has already been done.
1071 * [We can't call it easily with mapping off since the kernel is not
1072 * mapped with PA == VA, hence we would have to relocate every address
1073 * from the linked base (virtual) address "KERNBASE" to the actual
1074 * (physical) address starting relative to 0]
1077 pmap_bootstrap(vm_paddr_t *firstaddr)
1083 KvaStart = VM_MIN_KERNEL_ADDRESS;
1084 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1085 KvaSize = KvaEnd - KvaStart;
1087 avail_start = *firstaddr;
1090 * Create an initial set of page tables to run the kernel in.
1092 create_pagetables(firstaddr);
1094 virtual2_start = KvaStart;
1095 virtual2_end = PTOV_OFFSET;
1097 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1098 virtual_start = pmap_kmem_choose(virtual_start);
1100 virtual_end = VM_MAX_KERNEL_ADDRESS;
1102 /* XXX do %cr0 as well */
1103 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1104 load_cr3(KPML4phys);
1107 * Initialize protection array.
1109 x86_64_protection_init();
1112 * The kernel's pmap is statically allocated so we don't have to use
1113 * pmap_create, which is unlikely to work correctly at this part of
1114 * the boot sequence (XXX and which no longer exists).
1116 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1117 kernel_pmap.pm_count = 1;
1118 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1119 RB_INIT(&kernel_pmap.pm_pvroot);
1120 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1121 for (i = 0; i < PM_PLACEMARKS; ++i)
1122 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1125 * Reserve some special page table entries/VA space for temporary
1128 #define SYSMAP(c, p, v, n) \
1129 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1135 * CMAP1/CMAP2 are used for zeroing and copying pages.
1137 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1142 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1145 * ptvmmap is used for reading arbitrary physical pages via
1148 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1151 * msgbufp is used to map the system message buffer.
1152 * XXX msgbufmap is not used.
1154 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1155 atop(round_page(MSGBUF_SIZE)))
1158 virtual_start = pmap_kmem_choose(virtual_start);
1163 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1164 * cases rather then invl1pg. Actually, I don't even know why it
1165 * works under UP because self-referential page table mappings
1171 /* Initialize the PAT MSR */
1173 pmap_pinit_defaults(&kernel_pmap);
1175 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1176 &pmap_fast_kernel_cpusync);
1181 * Setup the PAT MSR.
1190 * Default values mapping PATi,PCD,PWT bits at system reset.
1191 * The default values effectively ignore the PATi bit by
1192 * repeating the encodings for 0-3 in 4-7, and map the PCD
1193 * and PWT bit combinations to the expected PAT types.
1195 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1196 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1197 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1198 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1199 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1200 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1201 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1202 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1203 pat_pte_index[PAT_WRITE_BACK] = 0;
1204 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1205 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1206 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1207 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1208 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1210 if (cpu_feature & CPUID_PAT) {
1212 * If we support the PAT then set-up entries for
1213 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1216 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1217 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1218 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1219 PAT_VALUE(6, PAT_WRITE_COMBINING);
1220 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1221 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1224 * Then enable the PAT
1229 load_cr4(cr4 & ~CR4_PGE);
1231 /* Disable caches (CD = 1, NW = 0). */
1233 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1235 /* Flushes caches and TLBs. */
1239 /* Update PAT and index table. */
1240 wrmsr(MSR_PAT, pat_msr);
1242 /* Flush caches and TLBs again. */
1246 /* Restore caches and PGE. */
1254 * Set 4mb pdir for mp startup
1259 if (cpu_feature & CPUID_PSE) {
1260 load_cr4(rcr4() | CR4_PSE);
1261 if (mycpu->gd_cpuid == 0) /* only on BSP */
1267 * Early initialization of the pmap module.
1269 * Called by vm_init, to initialize any structures that the pmap
1270 * system needs to map virtual memory. pmap_init has been enhanced to
1271 * support in a fairly consistant way, discontiguous physical memory.
1276 vm_pindex_t initial_pvs;
1280 * Allocate memory for random pmap data structures. Includes the
1283 for (i = 0; i < vm_page_array_size; i++) {
1286 m = &vm_page_array[i];
1287 TAILQ_INIT(&m->md.pv_list);
1291 * init the pv free list
1293 initial_pvs = vm_page_array_size;
1294 if (initial_pvs < MINPV)
1295 initial_pvs = MINPV;
1296 pvzone = &pvzone_store;
1297 pvinit = (void *)kmem_alloc(&kernel_map,
1298 initial_pvs * sizeof (struct pv_entry),
1300 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1301 pvinit, initial_pvs);
1304 * Now it is safe to enable pv_table recording.
1306 pmap_initialized = TRUE;
1310 * Initialize the address space (zone) for the pv_entries. Set a
1311 * high water mark so that the system can recover from excessive
1312 * numbers of pv entries.
1314 * Also create the kernel page table template for isolated user
1317 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1318 static void pmap_init2_iso_pmap(void);
1320 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1326 vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
1327 vm_pindex_t entry_max;
1329 TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1330 pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1331 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1332 pv_entry_high_water = 9 * (pv_entry_max / 10);
1335 * Subtract out pages already installed in the zone (hack)
1337 entry_max = pv_entry_max - vm_page_array_size;
1341 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1344 * Enable dynamic deletion of empty higher-level page table pages
1345 * by default only if system memory is < 8GB (use 7GB for slop).
1346 * This can save a little memory, but imposes significant
1347 * performance overhead for things like bulk builds, and for programs
1348 * which do a lot of memory mapping and memory unmapping.
1350 if (pmap_dynamic_delete < 0) {
1351 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1352 pmap_dynamic_delete = 1;
1354 pmap_dynamic_delete = 0;
1358 * Automatic detection of Intel meltdown bug requiring user/kernel
1361 * Currently there are so many Intel cpu's impacted that its better
1362 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1363 * so the default is off for AMD.
1365 if (meltdown_mitigation < 0) {
1366 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1367 meltdown_mitigation = 1;
1369 meltdown_mitigation = 0;
1371 if (meltdown_mitigation) {
1372 kprintf("machdep.meltdown_mitigation enabled to "
1373 "protect against (mostly Intel) meltdown bug\n");
1374 kprintf("system call performance will be impacted\n");
1377 pmap_init2_iso_pmap();
1381 * Create the isolation pmap template. Once created, the template
1382 * is static and its PML4e entries are used to populate the
1383 * kernel portion of any isolated user pmaps.
1385 * Our isolation pmap must contain:
1386 * (1) trampoline area for all cpus
1387 * (2) common_tss area for all cpus (its part of the trampoline area now)
1388 * (3) IDT for all cpus
1389 * (4) GDT for all cpus
1392 pmap_init2_iso_pmap(void)
1397 kprintf("Initialize isolation pmap\n");
1400 * Try to use our normal API calls to make this easier. We have
1401 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1404 pmap_pinit(&iso_pmap);
1405 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1408 * Install areas needed by the cpu and trampoline.
1410 for (n = 0; n < ncpus; ++n) {
1411 struct privatespace *ps;
1413 ps = CPU_prvspace[n];
1414 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1415 sizeof(ps->trampoline));
1416 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1417 sizeof(ps->dblstack));
1418 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1419 sizeof(ps->dbgstack));
1420 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1421 sizeof(ps->common_tss));
1422 pmap_init_iso_range(r_idt_arr[n].rd_base,
1423 r_idt_arr[n].rd_limit + 1);
1425 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1426 pmap_init_iso_range((vm_offset_t)(int *)btext,
1427 (vm_offset_t)(int *)etext -
1428 (vm_offset_t)(int *)btext);
1431 kprintf("Dump iso_pmap:\n");
1432 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1433 kprintf("\nDump kernel_pmap:\n");
1434 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1439 * This adds a kernel virtual address range to the isolation pmap.
1442 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1451 kprintf("isolate %016jx-%016jx (%zd)\n",
1452 base, base + bytes, bytes);
1454 va = base & ~(vm_offset_t)PAGE_MASK;
1455 while (va < base + bytes) {
1456 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1457 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1458 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1459 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1461 * Use 2MB pages if possible
1464 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1465 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1470 * Otherwise use 4KB pages
1472 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1473 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1474 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1475 kernel_pmap.pmap_bits[PG_V_IDX] |
1476 kernel_pmap.pmap_bits[PG_A_IDX] |
1477 kernel_pmap.pmap_bits[PG_M_IDX];
1488 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1492 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1499 case 0: /* PML4e page, 512G entries */
1500 incr = (1LL << 48) / 512;
1502 case 1: /* PDP page, 1G entries */
1503 incr = (1LL << 39) / 512;
1505 case 2: /* PD page, 2MB entries */
1506 incr = (1LL << 30) / 512;
1508 case 3: /* PT page, 4KB entries */
1509 incr = (1LL << 21) / 512;
1517 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1518 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1519 for (i = 0; i < 512; ++i) {
1520 if (level == 0 && i == 128)
1521 base += 0xFFFF000000000000LLU;
1523 kprintf("%*.*s ", level * 4, level * 4, "");
1524 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1525 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1527 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1528 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1530 } else if (level == 3) {
1531 kprintf("va=%016jx %3d term %016jx\n",
1534 kprintf("va=%016jx %3d deep %016jx\n",
1536 dump_pmap(pmap, ptp[i], level + 1, base);
1546 * Typically used to initialize a fictitious page by vm/device_pager.c
1549 pmap_page_init(struct vm_page *m)
1552 TAILQ_INIT(&m->md.pv_list);
1555 /***************************************************
1556 * Low level helper routines.....
1557 ***************************************************/
1560 * this routine defines the region(s) of memory that should
1561 * not be tested for the modified bit.
1565 pmap_track_modified(vm_pindex_t pindex)
1567 vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
1568 if ((va < clean_sva) || (va >= clean_eva))
1575 * Extract the physical page address associated with the map/VA pair.
1576 * The page must be wired for this to work reliably.
1579 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1586 if (va >= VM_MAX_USER_ADDRESS) {
1588 * Kernel page directories might be direct-mapped and
1589 * there is typically no PV tracking of pte's
1593 pt = pmap_pt(pmap, va);
1594 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1595 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1596 rtval = *pt & PG_PS_FRAME;
1597 rtval |= va & PDRMASK;
1599 ptep = pmap_pt_to_pte(*pt, va);
1600 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1601 rtval = *ptep & PG_FRAME;
1602 rtval |= va & PAGE_MASK;
1610 * User pages currently do not direct-map the page directory
1611 * and some pages might not used managed PVs. But all PT's
1614 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1616 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1617 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1618 rtval = *ptep & PG_FRAME;
1619 rtval |= va & PAGE_MASK;
1622 *handlep = pt_pv; /* locked until done */
1625 } else if (handlep) {
1633 pmap_extract_done(void *handle)
1636 pv_put((pv_entry_t)handle);
1640 * Similar to extract but checks protections, SMP-friendly short-cut for
1641 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1642 * fall-through to the real fault code. Does not work with HVM page
1645 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1647 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1648 * page is busied (and not held).
1650 * If busyp is not NULL and this function sets *busyp to zero, the returned
1651 * page is held (and not busied).
1653 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1654 * returned page will be dirtied. If the pte is not already writable NULL
1655 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1656 * any COW will already have happened and that page can be written by the
1659 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1663 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1666 va < VM_MAX_USER_ADDRESS &&
1667 (pmap->pm_flags & PMAP_HVM) == 0) {
1675 req = pmap->pmap_bits[PG_V_IDX] |
1676 pmap->pmap_bits[PG_U_IDX];
1677 if (prot & VM_PROT_WRITE)
1678 req |= pmap->pmap_bits[PG_RW_IDX];
1680 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1683 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1684 if ((*ptep & req) != req) {
1688 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1689 if (pte_pv && error == 0) {
1691 if (prot & VM_PROT_WRITE) {
1692 /* interlocked by presence of pv_entry */
1696 if (prot & VM_PROT_WRITE) {
1697 if (vm_page_busy_try(m, TRUE))
1708 } else if (pte_pv) {
1712 /* error, since we didn't request a placemarker */
1723 * Extract the physical page address associated kernel virtual address.
1726 pmap_kextract(vm_offset_t va)
1728 pd_entry_t pt; /* pt entry in pd */
1731 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1732 pa = DMAP_TO_PHYS(va);
1735 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1736 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1739 * Beware of a concurrent promotion that changes the
1740 * PDE at this point! For example, vtopte() must not
1741 * be used to access the PTE because it would use the
1742 * new PDE. It is, however, safe to use the old PDE
1743 * because the page table page is preserved by the
1746 pa = *pmap_pt_to_pte(pt, va);
1747 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1753 /***************************************************
1754 * Low level mapping routines.....
1755 ***************************************************/
1758 * Routine: pmap_kenter
1760 * Add a wired page to the KVA
1761 * NOTE! note that in order for the mapping to take effect -- you
1762 * should do an invltlb after doing the pmap_kenter().
1765 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1771 kernel_pmap.pmap_bits[PG_RW_IDX] |
1772 kernel_pmap.pmap_bits[PG_V_IDX];
1776 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1780 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1787 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1788 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1789 * (caller can conditionalize calling smp_invltlb()).
1792 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1798 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1799 kernel_pmap.pmap_bits[PG_V_IDX];
1808 atomic_swap_long(ptep, npte);
1809 cpu_invlpg((void *)va);
1815 * Enter addresses into the kernel pmap but don't bother
1816 * doing any tlb invalidations. Caller will do a rollup
1817 * invalidation via pmap_rollup_inval().
1820 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1827 kernel_pmap.pmap_bits[PG_RW_IDX] |
1828 kernel_pmap.pmap_bits[PG_V_IDX];
1837 atomic_swap_long(ptep, npte);
1838 cpu_invlpg((void *)va);
1844 * remove a page from the kernel pagetables
1847 pmap_kremove(vm_offset_t va)
1852 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1856 pmap_kremove_quick(vm_offset_t va)
1861 (void)pte_load_clear(ptep);
1862 cpu_invlpg((void *)va);
1866 * Remove addresses from the kernel pmap but don't bother
1867 * doing any tlb invalidations. Caller will do a rollup
1868 * invalidation via pmap_rollup_inval().
1871 pmap_kremove_noinval(vm_offset_t va)
1876 (void)pte_load_clear(ptep);
1880 * XXX these need to be recoded. They are not used in any critical path.
1883 pmap_kmodify_rw(vm_offset_t va)
1885 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1886 cpu_invlpg((void *)va);
1891 pmap_kmodify_nc(vm_offset_t va)
1893 atomic_set_long(vtopte(va), PG_N);
1894 cpu_invlpg((void *)va);
1899 * Used to map a range of physical addresses into kernel virtual
1900 * address space during the low level boot, typically to map the
1901 * dump bitmap, message buffer, and vm_page_array.
1903 * These mappings are typically made at some pointer after the end of the
1906 * We could return PHYS_TO_DMAP(start) here and not allocate any
1907 * via (*virtp), but then kmem from userland and kernel dumps won't
1908 * have access to the related pointers.
1911 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1914 vm_offset_t va_start;
1916 /*return PHYS_TO_DMAP(start);*/
1921 while (start < end) {
1922 pmap_kenter_quick(va, start);
1930 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1933 * Remove the specified set of pages from the data and instruction caches.
1935 * In contrast to pmap_invalidate_cache_range(), this function does not
1936 * rely on the CPU's self-snoop feature, because it is intended for use
1937 * when moving pages into a different cache domain.
1940 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1942 vm_offset_t daddr, eva;
1945 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1946 (cpu_feature & CPUID_CLFSH) == 0)
1950 for (i = 0; i < count; i++) {
1951 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1952 eva = daddr + PAGE_SIZE;
1953 for (; daddr < eva; daddr += cpu_clflush_line_size)
1961 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1963 KASSERT((sva & PAGE_MASK) == 0,
1964 ("pmap_invalidate_cache_range: sva not page-aligned"));
1965 KASSERT((eva & PAGE_MASK) == 0,
1966 ("pmap_invalidate_cache_range: eva not page-aligned"));
1968 if (cpu_feature & CPUID_SS) {
1969 ; /* If "Self Snoop" is supported, do nothing. */
1971 /* Globally invalidate caches */
1972 cpu_wbinvd_on_all_cpus();
1977 * Invalidate the specified range of virtual memory on all cpus associated
1981 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1983 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
1987 * Add a list of wired pages to the kva. This routine is used for temporary
1988 * kernel mappings such as those found in buffer cache buffer. Page
1989 * modifications and accesses are not tracked or recorded.
1991 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
1992 * semantics as previous mappings may have been zerod without any
1995 * The page *must* be wired.
1997 static __inline void
1998 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2003 end_va = beg_va + count * PAGE_SIZE;
2005 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2010 pte = VM_PAGE_TO_PHYS(*m) |
2011 kernel_pmap.pmap_bits[PG_RW_IDX] |
2012 kernel_pmap.pmap_bits[PG_V_IDX] |
2013 kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2015 atomic_swap_long(ptep, pte);
2019 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2023 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2025 _pmap_qenter(beg_va, m, count, 1);
2029 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2031 _pmap_qenter(beg_va, m, count, 0);
2035 * This routine jerks page mappings from the kernel -- it is meant only
2036 * for temporary mappings such as those found in buffer cache buffers.
2037 * No recording modified or access status occurs.
2039 * MPSAFE, INTERRUPT SAFE (cluster callback)
2042 pmap_qremove(vm_offset_t beg_va, int count)
2047 end_va = beg_va + count * PAGE_SIZE;
2049 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2053 (void)pte_load_clear(pte);
2054 cpu_invlpg((void *)va);
2056 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2060 * This routine removes temporary kernel mappings, only invalidating them
2061 * on the current cpu. It should only be used under carefully controlled
2065 pmap_qremove_quick(vm_offset_t beg_va, int count)
2070 end_va = beg_va + count * PAGE_SIZE;
2072 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2076 (void)pte_load_clear(pte);
2077 cpu_invlpg((void *)va);
2082 * This routine removes temporary kernel mappings *without* invalidating
2083 * the TLB. It can only be used on permanent kva reservations such as those
2084 * found in buffer cache buffers, under carefully controlled circumstances.
2086 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2087 * (pmap_qenter() does unconditional invalidation).
2090 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2095 end_va = beg_va + count * PAGE_SIZE;
2097 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2101 (void)pte_load_clear(pte);
2106 * Create a new thread and optionally associate it with a (new) process.
2107 * NOTE! the new thread's cpu may not equal the current cpu.
2110 pmap_init_thread(thread_t td)
2112 /* enforce pcb placement & alignment */
2113 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2114 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2115 td->td_savefpu = &td->td_pcb->pcb_save;
2116 td->td_sp = (char *)td->td_pcb; /* no -16 */
2120 * This routine directly affects the fork perf for a process.
2123 pmap_init_proc(struct proc *p)
2128 pmap_pinit_defaults(struct pmap *pmap)
2130 bcopy(pmap_bits_default, pmap->pmap_bits,
2131 sizeof(pmap_bits_default));
2132 bcopy(protection_codes, pmap->protection_codes,
2133 sizeof(protection_codes));
2134 bcopy(pat_pte_index, pmap->pmap_cache_bits,
2135 sizeof(pat_pte_index));
2136 pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2137 pmap->copyinstr = std_copyinstr;
2138 pmap->copyin = std_copyin;
2139 pmap->copyout = std_copyout;
2140 pmap->fubyte = std_fubyte;
2141 pmap->subyte = std_subyte;
2142 pmap->fuword32 = std_fuword32;
2143 pmap->fuword64 = std_fuword64;
2144 pmap->suword32 = std_suword32;
2145 pmap->suword64 = std_suword64;
2146 pmap->swapu32 = std_swapu32;
2147 pmap->swapu64 = std_swapu64;
2148 pmap->fuwordadd32 = std_fuwordadd32;
2149 pmap->fuwordadd64 = std_fuwordadd64;
2152 * Initialize pmap0/vmspace0.
2154 * On architectures where the kernel pmap is not integrated into the user
2155 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2156 * kernel_pmap should be used to directly access the kernel_pmap.
2159 pmap_pinit0(struct pmap *pmap)
2163 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2165 CPUMASK_ASSZERO(pmap->pm_active);
2166 pmap->pm_pvhint_pt = NULL;
2167 pmap->pm_pvhint_pte = NULL;
2168 RB_INIT(&pmap->pm_pvroot);
2169 spin_init(&pmap->pm_spin, "pmapinit0");
2170 for (i = 0; i < PM_PLACEMARKS; ++i)
2171 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2172 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2173 pmap_pinit_defaults(pmap);
2177 * Initialize a preallocated and zeroed pmap structure,
2178 * such as one in a vmspace structure.
2181 pmap_pinit_simple(struct pmap *pmap)
2186 * Misc initialization
2189 CPUMASK_ASSZERO(pmap->pm_active);
2190 pmap->pm_pvhint_pt = NULL;
2191 pmap->pm_pvhint_pte = NULL;
2192 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2194 pmap_pinit_defaults(pmap);
2197 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2200 if (pmap->pm_pmlpv == NULL) {
2201 RB_INIT(&pmap->pm_pvroot);
2202 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2203 spin_init(&pmap->pm_spin, "pmapinitsimple");
2204 for (i = 0; i < PM_PLACEMARKS; ++i)
2205 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2210 pmap_pinit(struct pmap *pmap)
2215 if (pmap->pm_pmlpv) {
2216 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2221 pmap_pinit_simple(pmap);
2222 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2225 * No need to allocate page table space yet but we do need a valid
2226 * page directory table.
2228 if (pmap->pm_pml4 == NULL) {
2230 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2233 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2237 * Allocate the PML4e table, which wires it even though it isn't
2238 * being entered into some higher level page table (it being the
2239 * highest level). If one is already cached we don't have to do
2242 if ((pv = pmap->pm_pmlpv) == NULL) {
2243 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2244 pmap->pm_pmlpv = pv;
2245 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2246 VM_PAGE_TO_PHYS(pv->pv_m));
2250 * Install DMAP and KMAP.
2252 for (j = 0; j < NDMPML4E; ++j) {
2253 pmap->pm_pml4[DMPML4I + j] =
2254 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2255 pmap->pmap_bits[PG_RW_IDX] |
2256 pmap->pmap_bits[PG_V_IDX] |
2257 pmap->pmap_bits[PG_A_IDX];
2259 for (j = 0; j < NKPML4E; ++j) {
2260 pmap->pm_pml4[KPML4I + j] =
2261 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2262 pmap->pmap_bits[PG_RW_IDX] |
2263 pmap->pmap_bits[PG_V_IDX] |
2264 pmap->pmap_bits[PG_A_IDX];
2268 * install self-referential address mapping entry
2270 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2271 pmap->pmap_bits[PG_V_IDX] |
2272 pmap->pmap_bits[PG_RW_IDX] |
2273 pmap->pmap_bits[PG_A_IDX];
2275 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2276 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2278 KKASSERT(pmap->pm_pml4[255] == 0);
2281 * When implementing an isolated userland pmap, a second PML4e table
2282 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2283 * note that we do not operate on this table using our API functions
2284 * so handling of the + 1 case is mostly just to prevent implosions.
2286 * We install an isolated version of the kernel PDPs into this
2287 * second PML4e table. The pmap code will mirror all user PDPs
2288 * between the primary and secondary PML4e table.
2290 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2291 pmap != &iso_pmap) {
2292 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2293 pmap->pm_pmlpv_iso = pv;
2294 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2295 VM_PAGE_TO_PHYS(pv->pv_m));
2299 * Install an isolated version of the kernel pmap for
2300 * user consumption, using PDPs constructed in iso_pmap.
2302 for (j = 0; j < NKPML4E; ++j) {
2303 pmap->pm_pml4_iso[KPML4I + j] =
2304 iso_pmap.pm_pml4[KPML4I + j];
2307 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2308 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2313 * Clean up a pmap structure so it can be physically freed. This routine
2314 * is called by the vmspace dtor function. A great deal of pmap data is
2315 * left passively mapped to improve vmspace management so we have a bit
2316 * of cleanup work to do here.
2319 pmap_puninit(pmap_t pmap)
2324 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2325 if ((pv = pmap->pm_pmlpv) != NULL) {
2326 if (pv_hold_try(pv) == 0)
2328 KKASSERT(pv == pmap->pm_pmlpv);
2329 p = pmap_remove_pv_page(pv);
2331 pv = NULL; /* safety */
2332 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2333 vm_page_busy_wait(p, FALSE, "pgpun");
2334 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2335 vm_page_unwire(p, 0);
2336 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2338 pmap->pm_pmlpv = NULL;
2340 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2341 if (pv_hold_try(pv) == 0)
2343 KKASSERT(pv == pmap->pm_pmlpv_iso);
2344 p = pmap_remove_pv_page(pv);
2346 pv = NULL; /* safety */
2347 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2348 vm_page_busy_wait(p, FALSE, "pgpun");
2349 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2350 vm_page_unwire(p, 0);
2351 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2353 pmap->pm_pmlpv_iso = NULL;
2355 if (pmap->pm_pml4) {
2356 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2357 kmem_free(&kernel_map,
2358 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2359 pmap->pm_pml4 = NULL;
2360 pmap->pm_pml4_iso = NULL;
2362 KKASSERT(pmap->pm_stats.resident_count == 0);
2363 KKASSERT(pmap->pm_stats.wired_count == 0);
2367 * This function is now unused (used to add the pmap to the pmap_list)
2370 pmap_pinit2(struct pmap *pmap)
2375 * This routine is called when various levels in the page table need to
2376 * be populated. This routine cannot fail.
2378 * This function returns two locked pv_entry's, one representing the
2379 * requested pv and one representing the requested pv's parent pv. If
2380 * an intermediate page table does not exist it will be created, mapped,
2381 * wired, and the parent page table will be given an additional hold
2382 * count representing the presence of the child pv_entry.
2386 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2389 pt_entry_t *ptep_iso;
2393 vm_pindex_t pt_pindex;
2399 * If the pv already exists and we aren't being asked for the
2400 * parent page table page we can just return it. A locked+held pv
2401 * is returned. The pv will also have a second hold related to the
2402 * pmap association that we don't have to worry about.
2405 pv = pv_alloc(pmap, ptepindex, &isnew);
2406 if (isnew == 0 && pvpp == NULL)
2410 * Special case terminal PVs. These are not page table pages so
2411 * no vm_page is allocated (the caller supplied the vm_page). If
2412 * pvpp is non-NULL we are being asked to also removed the pt_pv
2415 * Note that pt_pv's are only returned for user VAs. We assert that
2416 * a pt_pv is not being requested for kernel VAs. The kernel
2417 * pre-wires all higher-level page tables so don't overload managed
2418 * higher-level page tables on top of it!
2420 * However, its convenient for us to allow the case when creating
2421 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2424 if (ptepindex < pmap_pt_pindex(0)) {
2425 if (ptepindex >= NUPTE_USER && pmap != &iso_pmap) {
2426 /* kernel manages this manually for KVM */
2427 KKASSERT(pvpp == NULL);
2429 KKASSERT(pvpp != NULL);
2430 pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
2431 pvp = pmap_allocpte(pmap, pt_pindex, NULL);
2433 vm_page_wire_quick(pvp->pv_m);
2440 * The kernel never uses managed PT/PD/PDP pages.
2442 KKASSERT(pmap != &kernel_pmap);
2445 * Non-terminal PVs allocate a VM page to represent the page table,
2446 * so we have to resolve pvp and calculate ptepindex for the pvp
2447 * and then for the page table entry index in the pvp for
2450 if (ptepindex < pmap_pd_pindex(0)) {
2452 * pv is PT, pvp is PD
2454 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2455 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2456 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2461 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2462 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2464 } else if (ptepindex < pmap_pdp_pindex(0)) {
2466 * pv is PD, pvp is PDP
2468 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2471 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2472 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2474 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2475 KKASSERT(pvpp == NULL);
2478 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2484 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2485 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2486 } else if (ptepindex < pmap_pml4_pindex()) {
2488 * pv is PDP, pvp is the root pml4 table
2490 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2495 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2496 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2499 * pv represents the top-level PML4, there is no parent.
2508 * (isnew) is TRUE, pv is not terminal.
2510 * (1) Add a wire count to the parent page table (pvp).
2511 * (2) Allocate a VM page for the page table.
2512 * (3) Enter the VM page into the parent page table.
2514 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2517 vm_page_wire_quick(pvp->pv_m);
2520 m = vm_page_alloc(NULL, pv->pv_pindex,
2521 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2522 VM_ALLOC_INTERRUPT);
2527 vm_page_wire(m); /* wire for mapping in parent */
2528 vm_page_unmanage(m); /* m must be spinunlocked */
2529 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2530 m->valid = VM_PAGE_BITS_ALL;
2532 vm_page_spin_lock(m);
2533 pmap_page_stats_adding(m);
2534 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2536 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2537 vm_page_spin_unlock(m);
2540 * (isnew) is TRUE, pv is not terminal.
2542 * Wire the page into pvp. Bump the resident_count for the pmap.
2543 * There is no pvp for the top level, address the pm_pml4[] array
2546 * If the caller wants the parent we return it, otherwise
2547 * we just put it away.
2549 * No interlock is needed for pte 0 -> non-zero.
2551 * In the situation where *ptep is valid we might have an unmanaged
2552 * page table page shared from another page table which we need to
2553 * unshare before installing our private page table page.
2556 v = VM_PAGE_TO_PHYS(m) |
2557 (pmap->pmap_bits[PG_RW_IDX] |
2558 pmap->pmap_bits[PG_V_IDX] |
2559 pmap->pmap_bits[PG_A_IDX]);
2560 if (ptepindex < NUPTE_USER)
2561 v |= pmap->pmap_bits[PG_U_IDX];
2562 if (ptepindex < pmap_pt_pindex(0))
2563 v |= pmap->pmap_bits[PG_M_IDX];
2565 ptep = pv_pte_lookup(pvp, ptepindex);
2566 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2567 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2570 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2574 panic("pmap_allocpte: unexpected pte %p/%d",
2575 pvp, (int)ptepindex);
2577 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2580 pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2583 if (vm_page_unwire_quick(
2584 PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2585 panic("pmap_allocpte: shared pgtable "
2586 "pg bad wirecount");
2591 pte = atomic_swap_long(ptep, v);
2593 atomic_swap_long(ptep_iso, v);
2595 kprintf("install pgtbl mixup 0x%016jx "
2596 "old/new 0x%016jx/0x%016jx\n",
2597 (intmax_t)ptepindex, pte, v);
2604 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2608 KKASSERT(pvp->pv_m != NULL);
2609 ptep = pv_pte_lookup(pvp, ptepindex);
2610 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2611 (pmap->pmap_bits[PG_RW_IDX] |
2612 pmap->pmap_bits[PG_V_IDX] |
2613 pmap->pmap_bits[PG_A_IDX]);
2614 if (ptepindex < NUPTE_USER)
2615 v |= pmap->pmap_bits[PG_U_IDX];
2616 if (ptepindex < pmap_pt_pindex(0))
2617 v |= pmap->pmap_bits[PG_M_IDX];
2619 kprintf("mismatched upper level pt %016jx/%016jx\n",
2631 * This version of pmap_allocpte() checks for possible segment optimizations
2632 * that would allow page-table sharing. It can be called for terminal
2633 * page or page table page ptepindex's.
2635 * The function is called with page table page ptepindex's for fictitious
2636 * and unmanaged terminal pages. That is, we don't want to allocate a
2637 * terminal pv, we just want the pt_pv. pvpp is usually passed as NULL
2640 * This function can return a pv and *pvpp associated with the passed in pmap
2641 * OR a pv and *pvpp associated with the shared pmap. In the latter case
2642 * an unmanaged page table page will be entered into the pass in pmap.
2646 pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
2647 vm_map_entry_t entry, vm_offset_t va)
2652 vm_pindex_t *pt_placemark;
2654 pv_entry_t pte_pv; /* in original or shared pmap */
2655 pv_entry_t pt_pv; /* in original or shared pmap */
2656 pv_entry_t proc_pd_pv; /* in original pmap */
2657 pv_entry_t proc_pt_pv; /* in original pmap */
2658 pv_entry_t xpv; /* PT in shared pmap */
2659 pd_entry_t *pt; /* PT entry in PD of original pmap */
2660 pd_entry_t opte; /* contents of *pt */
2661 pd_entry_t npte; /* contents of *pt */
2666 * Basic tests, require a non-NULL vm_map_entry, require proper
2667 * alignment and type for the vm_map_entry, require that the
2668 * underlying object already be allocated.
2670 * We allow almost any type of object to use this optimization.
2671 * The object itself does NOT have to be sized to a multiple of the
2672 * segment size, but the memory mapping does.
2674 * XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
2675 * won't work as expected.
2677 if (entry == NULL ||
2678 pmap_mmu_optimize == 0 || /* not enabled */
2679 (pmap->pm_flags & PMAP_HVM) || /* special pmap */
2680 ptepindex >= pmap_pd_pindex(0) || /* not terminal or pt */
2681 entry->inheritance != VM_INHERIT_SHARE || /* not shared */
2682 entry->maptype != VM_MAPTYPE_NORMAL || /* weird map type */
2683 entry->object.vm_object == NULL || /* needs VM object */
2684 entry->object.vm_object->type == OBJT_DEVICE || /* ick */
2685 entry->object.vm_object->type == OBJT_MGTDEVICE || /* ick */
2686 (entry->offset & SEG_MASK) || /* must be aligned */
2687 (entry->start & SEG_MASK)) {
2688 return(pmap_allocpte(pmap, ptepindex, pvpp));
2692 * Make sure the full segment can be represented.
2694 b = va & ~(vm_offset_t)SEG_MASK;
2695 if (b < entry->start || b + SEG_SIZE > entry->end)
2696 return(pmap_allocpte(pmap, ptepindex, pvpp));
2699 * If the full segment can be represented dive the VM object's
2700 * shared pmap, allocating as required.
2702 object = entry->object.vm_object;
2704 if (entry->protection & VM_PROT_WRITE)
2705 obpmapp = &object->md.pmap_rw;
2707 obpmapp = &object->md.pmap_ro;
2710 if (pmap_enter_debug > 0) {
2712 kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
2714 va, entry->protection, object,
2716 kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
2717 entry, entry->start, entry->end);
2722 * We allocate what appears to be a normal pmap but because portions
2723 * of this pmap are shared with other unrelated pmaps we have to
2724 * set pm_active to point to all cpus.
2726 * XXX Currently using pmap_spin to interlock the update, can't use
2727 * vm_object_hold/drop because the token might already be held
2728 * shared OR exclusive and we don't know.
2730 while ((obpmap = *obpmapp) == NULL) {
2731 obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
2732 pmap_pinit_simple(obpmap);
2733 pmap_pinit2(obpmap);
2734 spin_lock(&pmap_spin);
2735 if (*obpmapp != NULL) {
2739 spin_unlock(&pmap_spin);
2740 pmap_release(obpmap);
2741 pmap_puninit(obpmap);
2742 kfree(obpmap, M_OBJPMAP);
2743 obpmap = *obpmapp; /* safety */
2745 obpmap->pm_active = smp_active_mask;
2746 obpmap->pm_flags |= PMAP_SEGSHARED;
2748 spin_unlock(&pmap_spin);
2753 * Layering is: PTE, PT, PD, PDP, PML4. We have to return the
2754 * pte/pt using the shared pmap from the object but also adjust
2755 * the process pmap's page table page as a side effect.
2759 * Resolve the terminal PTE and PT in the shared pmap. This is what
2760 * we will return. This is true if ptepindex represents a terminal
2761 * page, otherwise pte_pv is actually the PT and pt_pv is actually
2765 pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
2768 if (ptepindex >= pmap_pt_pindex(0))
2774 * Resolve the PD in the process pmap so we can properly share the
2775 * page table page. Lock order is bottom-up (leaf first)!
2777 * NOTE: proc_pt_pv can be NULL.
2779 proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b), &pt_placemark);
2780 proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
2782 if (pmap_enter_debug > 0) {
2784 kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
2786 (proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
2793 * xpv is the page table page pv from the shared object
2794 * (for convenience), from above.
2796 * Calculate the pte value for the PT to load into the process PD.
2797 * If we have to change it we must properly dispose of the previous
2800 pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2801 npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
2802 (pmap->pmap_bits[PG_U_IDX] |
2803 pmap->pmap_bits[PG_RW_IDX] |
2804 pmap->pmap_bits[PG_V_IDX] |
2805 pmap->pmap_bits[PG_A_IDX] |
2806 pmap->pmap_bits[PG_M_IDX]);
2809 * Dispose of previous page table page if it was local to the
2810 * process pmap. If the old pt is not empty we cannot dispose of it
2811 * until we clean it out. This case should not arise very often so
2812 * it is not optimized.
2814 * Leave pt_pv and pte_pv (in our object pmap) locked and intact
2818 pmap_inval_bulk_t bulk;
2820 if (proc_pt_pv->pv_m->wire_count != 1) {
2822 * The page table has a bunch of stuff in it
2823 * which we have to scrap.
2825 if (softhold == 0) {
2827 pmap_softhold(pmap);
2832 va & ~(vm_offset_t)SEG_MASK,
2833 (va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
2836 * The page table is empty and can be destroyed.
2837 * However, doing so leaves the pt slot unlocked,
2838 * so we have to loop-up to handle any races until
2839 * we get a NULL proc_pt_pv and a proper pt_placemark.
2841 pmap_inval_bulk_init(&bulk, proc_pt_pv->pv_pmap);
2842 pmap_release_pv(proc_pt_pv, proc_pd_pv, &bulk);
2843 pmap_inval_bulk_flush(&bulk);
2850 * Handle remaining cases. We are holding pt_placemark to lock
2851 * the page table page in the primary pmap while we manipulate
2855 atomic_swap_long(pt, npte);
2856 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2857 vm_page_wire_quick(proc_pd_pv->pv_m); /* proc pd for sh pt */
2858 atomic_add_long(&pmap->pm_stats.resident_count, 1);
2859 } else if (*pt != npte) {
2860 opte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, pt, npte);
2863 opte = pte_load_clear(pt);
2864 KKASSERT(opte && opte != npte);
2868 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2871 * Clean up opte, bump the wire_count for the process
2872 * PD page representing the new entry if it was
2875 * If the entry was not previously empty and we have
2876 * a PT in the proc pmap then opte must match that
2877 * pt. The proc pt must be retired (this is done
2878 * later on in this procedure).
2880 * NOTE: replacing valid pte, wire_count on proc_pd_pv
2883 KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
2884 m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
2885 if (vm_page_unwire_quick(m)) {
2886 panic("pmap_allocpte_seg: "
2887 "bad wire count %p",
2893 pmap_softdone(pmap);
2896 * Remove our earmark on the page table page.
2898 pv_placemarker_wakeup(pmap, pt_placemark);
2901 * The existing process page table was replaced and must be destroyed
2914 * Release any resources held by the given physical map.
2916 * Called when a pmap initialized by pmap_pinit is being released. Should
2917 * only be called if the map contains no valid mappings.
2919 struct pmap_release_info {
2925 static int pmap_release_callback(pv_entry_t pv, void *data);
2928 pmap_release(struct pmap *pmap)
2930 struct pmap_release_info info;
2932 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2933 ("pmap still active! %016jx",
2934 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2937 * There is no longer a pmap_list, if there were we would remove the
2938 * pmap from it here.
2942 * Pull pv's off the RB tree in order from low to high and release
2950 spin_lock(&pmap->pm_spin);
2951 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2952 pmap_release_callback, &info);
2953 spin_unlock(&pmap->pm_spin);
2957 } while (info.retry);
2961 * One resident page (the pml4 page) should remain. Two if
2962 * the pmap has implemented an isolated userland PML4E table.
2963 * No wired pages should remain.
2965 int expected_res = 0;
2967 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2969 if (pmap->pm_pmlpv_iso)
2973 if (pmap->pm_stats.resident_count != expected_res ||
2974 pmap->pm_stats.wired_count != 0) {
2975 kprintf("fatal pmap problem - pmap %p flags %08x "
2976 "rescnt=%jd wirecnt=%jd\n",
2979 pmap->pm_stats.resident_count,
2980 pmap->pm_stats.wired_count);
2981 tsleep(pmap, 0, "DEAD", 0);
2984 KKASSERT(pmap->pm_stats.resident_count == expected_res);
2985 KKASSERT(pmap->pm_stats.wired_count == 0);
2990 * Called from low to high. We must cache the proper parent pv so we
2991 * can adjust its wired count.
2994 pmap_release_callback(pv_entry_t pv, void *data)
2996 struct pmap_release_info *info = data;
2997 pmap_t pmap = info->pmap;
3002 * Acquire a held and locked pv, check for release race
3004 pindex = pv->pv_pindex;
3005 if (info->pvp == pv) {
3006 spin_unlock(&pmap->pm_spin);
3008 } else if (pv_hold_try(pv)) {
3009 spin_unlock(&pmap->pm_spin);
3011 spin_unlock(&pmap->pm_spin);
3015 spin_lock(&pmap->pm_spin);
3019 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
3021 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3023 * I am PTE, parent is PT
3025 pindex = pv->pv_pindex >> NPTEPGSHIFT;
3026 pindex += NUPTE_TOTAL;
3027 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
3029 * I am PT, parent is PD
3031 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
3032 pindex += NUPTE_TOTAL + NUPT_TOTAL;
3033 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
3035 * I am PD, parent is PDP
3037 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
3039 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
3040 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
3042 * I am PDP, parent is PML4. We always calculate the
3043 * normal PML4 here, not the isolated PML4.
3045 pindex = pmap_pml4_pindex();
3057 if (info->pvp && info->pvp->pv_pindex != pindex) {
3061 if (info->pvp == NULL)
3062 info->pvp = pv_get(pmap, pindex, NULL);
3069 r = pmap_release_pv(pv, info->pvp, NULL);
3070 spin_lock(&pmap->pm_spin);
3076 * Called with held (i.e. also locked) pv. This function will dispose of
3077 * the lock along with the pv.
3079 * If the caller already holds the locked parent page table for pv it
3080 * must pass it as pvp, allowing us to avoid a deadlock, else it can
3081 * pass NULL for pvp.
3084 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
3089 * The pmap is currently not spinlocked, pv is held+locked.
3090 * Remove the pv's page from its parent's page table. The
3091 * parent's page table page's wire_count will be decremented.
3093 * This will clean out the pte at any level of the page table.
3094 * If smp != 0 all cpus are affected.
3096 * Do not tear-down recursively, its faster to just let the
3097 * release run its course.
3099 pmap_remove_pv_pte(pv, pvp, bulk, 0);
3102 * Terminal pvs are unhooked from their vm_pages. Because
3103 * terminal pages aren't page table pages they aren't wired
3104 * by us, so we have to be sure not to unwire them either.
3106 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3107 pmap_remove_pv_page(pv);
3112 * We leave the top-level page table page cached, wired, and
3113 * mapped in the pmap until the dtor function (pmap_puninit())
3116 * Since we are leaving the top-level pv intact we need
3117 * to break out of what would otherwise be an infinite loop.
3119 * This covers both the normal and the isolated PML4 page.
3121 if (pv->pv_pindex >= pmap_pml4_pindex()) {
3127 * For page table pages (other than the top-level page),
3128 * remove and free the vm_page. The representitive mapping
3129 * removed above by pmap_remove_pv_pte() did not undo the
3130 * last wire_count so we have to do that as well.
3132 p = pmap_remove_pv_page(pv);
3133 vm_page_busy_wait(p, FALSE, "pmaprl");
3134 if (p->wire_count != 1) {
3135 kprintf("p->wire_count was %016lx %d\n",
3136 pv->pv_pindex, p->wire_count);
3138 KKASSERT(p->wire_count == 1);
3139 KKASSERT(p->flags & PG_UNMANAGED);
3141 vm_page_unwire(p, 0);
3142 KKASSERT(p->wire_count == 0);
3152 * This function will remove the pte associated with a pv from its parent.
3153 * Terminal pv's are supported. All cpus specified by (bulk) are properly
3156 * The wire count will be dropped on the parent page table. The wire
3157 * count on the page being removed (pv->pv_m) from the parent page table
3158 * is NOT touched. Note that terminal pages will not have any additional
3159 * wire counts while page table pages will have at least one representing
3160 * the mapping, plus others representing sub-mappings.
3162 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3163 * pages and user page table and terminal pages.
3165 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3166 * be freshly allocated and not imply that the pte is managed. In this
3167 * case pv->pv_m should be NULL.
3169 * The pv must be locked. The pvp, if supplied, must be locked. All
3170 * supplied pv's will remain locked on return.
3172 * XXX must lock parent pv's if they exist to remove pte XXX
3176 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3179 vm_pindex_t ptepindex = pv->pv_pindex;
3180 pmap_t pmap = pv->pv_pmap;
3186 if (ptepindex >= pmap_pml4_pindex()) {
3188 * We are the top level PML4E table, there is no parent.
3190 * This is either the normal or isolated PML4E table.
3191 * Only the normal is used in regular operation, the isolated
3192 * is only passed in when breaking down the whole pmap.
3194 p = pmap->pm_pmlpv->pv_m;
3195 KKASSERT(pv->pv_m == p); /* debugging */
3196 } else if (ptepindex >= pmap_pdp_pindex(0)) {
3198 * Remove a PDP page from the PML4E. This can only occur
3199 * with user page tables. We do not have to lock the
3200 * pml4 PV so just ignore pvp.
3202 vm_pindex_t pml4_pindex;
3203 vm_pindex_t pdp_index;
3205 pml4_entry_t *pdp_iso;
3207 pdp_index = ptepindex - pmap_pdp_pindex(0);
3209 pml4_pindex = pmap_pml4_pindex();
3210 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3215 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3216 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3217 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3218 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3221 * Also remove the PDP from the isolated PML4E if the
3224 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3225 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3226 ((1ul << NPML4EPGSHIFT) - 1)];
3227 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3229 KKASSERT(pv->pv_m == p); /* debugging */
3230 } else if (ptepindex >= pmap_pd_pindex(0)) {
3232 * Remove a PD page from the PDP
3234 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3235 * of a simple pmap because it stops at
3238 vm_pindex_t pdp_pindex;
3239 vm_pindex_t pd_index;
3242 pd_index = ptepindex - pmap_pd_pindex(0);
3245 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3246 (pd_index >> NPML4EPGSHIFT);
3247 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3252 pd = pv_pte_lookup(pvp, pd_index &
3253 ((1ul << NPDPEPGSHIFT) - 1));
3254 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3255 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3256 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3258 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3259 p = pv->pv_m; /* degenerate test later */
3261 KKASSERT(pv->pv_m == p); /* debugging */
3262 } else if (ptepindex >= pmap_pt_pindex(0)) {
3264 * Remove a PT page from the PD
3266 vm_pindex_t pd_pindex;
3267 vm_pindex_t pt_index;
3270 pt_index = ptepindex - pmap_pt_pindex(0);
3273 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3274 (pt_index >> NPDPEPGSHIFT);
3275 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3280 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3282 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3283 ("*pt unexpectedly invalid %016jx "
3284 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3285 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3286 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3288 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3289 kprintf("*pt unexpectedly invalid %016jx "
3290 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3292 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3293 tsleep(pt, 0, "DEAD", 0);
3296 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3299 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3300 KKASSERT(pv->pv_m == p); /* debugging */
3303 * Remove a PTE from the PT page. The PV might exist even if
3304 * the PTE is not managed, in whichcase pv->pv_m should be
3307 * NOTE: Userland pmaps manage the parent PT/PD/PDP page
3308 * table pages but the kernel_pmap does not.
3310 * NOTE: pv's must be locked bottom-up to avoid deadlocking.
3311 * pv is a pte_pv so we can safely lock pt_pv.
3313 * NOTE: FICTITIOUS pages may have multiple physical mappings
3314 * so PHYS_TO_VM_PAGE() will not necessarily work for
3317 vm_pindex_t pt_pindex;
3322 pt_pindex = ptepindex >> NPTEPGSHIFT;
3323 va = (vm_offset_t)ptepindex << PAGE_SHIFT;
3325 if (ptepindex >= NUPTE_USER) {
3326 ptep = vtopte(ptepindex << PAGE_SHIFT);
3327 KKASSERT(pvp == NULL);
3328 /* pvp remains NULL */
3331 pt_pindex = NUPTE_TOTAL +
3332 (ptepindex >> NPDPEPGSHIFT);
3333 pvp = pv_get(pv->pv_pmap, pt_pindex, NULL);
3337 ptep = pv_pte_lookup(pvp, ptepindex &
3338 ((1ul << NPDPEPGSHIFT) - 1));
3340 pte = pmap_inval_bulk(bulk, va, ptep, 0);
3341 if (bulk == NULL) /* XXX */
3342 cpu_invlpg((void *)va); /* XXX */
3345 * Now update the vm_page_t
3347 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3348 (pte & pmap->pmap_bits[PG_V_IDX])) {
3350 * Valid managed page, adjust (p).
3352 if (pte & pmap->pmap_bits[PG_DEVICE_IDX]) {
3355 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3356 KKASSERT(pv->pv_m == p);
3358 if (pte & pmap->pmap_bits[PG_M_IDX]) {
3359 if (pmap_track_modified(ptepindex))
3362 if (pte & pmap->pmap_bits[PG_A_IDX]) {
3363 vm_page_flag_set(p, PG_REFERENCED);
3367 * Unmanaged page, do not try to adjust the vm_page_t.
3368 * pv could be freshly allocated for a pmap_enter(),
3369 * replacing an unmanaged page with a managed one.
3371 * pv->pv_m might reflect the new page and not the
3374 * We could extract p from the physical address and
3375 * adjust it but we explicitly do not for unmanaged
3380 if (pte & pmap->pmap_bits[PG_W_IDX])
3381 atomic_add_long(&pmap->pm_stats.wired_count, -1);
3382 if (pte & pmap->pmap_bits[PG_G_IDX])
3383 cpu_invlpg((void *)va);
3387 * If requested, scrap the underlying pv->pv_m and the underlying
3388 * pv. If this is a page-table-page we must also free the page.
3390 * pvp must be returned locked.
3394 * page table page (PT, PD, PDP, PML4), caller was responsible
3395 * for testing wired_count.
3397 KKASSERT(pv->pv_m->wire_count == 1);
3398 p = pmap_remove_pv_page(pv);
3402 vm_page_busy_wait(p, FALSE, "pgpun");
3403 vm_page_unwire(p, 0);
3404 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3406 } else if (destroy == 2) {
3408 * Normal page, remove from pmap and leave the underlying
3411 pmap_remove_pv_page(pv);
3413 pv = NULL; /* safety */
3417 * If we acquired pvp ourselves then we are responsible for
3418 * recursively deleting it.
3420 if (pvp && gotpvp) {
3422 * Recursively destroy higher-level page tables.
3424 * This is optional. If we do not, they will still
3425 * be destroyed when the process exits.
3427 * NOTE: Do not destroy pv_entry's with extra hold refs,
3428 * a caller may have unlocked it and intends to
3429 * continue to use it.
3431 if (pmap_dynamic_delete &&
3433 pvp->pv_m->wire_count == 1 &&
3434 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3435 pvp->pv_pindex < pmap_pml4_pindex()) {
3436 if (pmap_dynamic_delete == 2)
3437 kprintf("A %jd %08x\n", pvp->pv_pindex, pvp->pv_hold);
3438 if (pmap != &kernel_pmap) {
3439 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3440 pvp = NULL; /* safety */
3442 kprintf("Attempt to remove kernel_pmap pindex "
3443 "%jd\n", pvp->pv_pindex);
3453 * Remove the vm_page association to a pv. The pv must be locked.
3457 pmap_remove_pv_page(pv_entry_t pv)
3462 vm_page_spin_lock(m);
3463 KKASSERT(m && m == pv->pv_m);
3465 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3466 pmap_page_stats_deleting(m);
3467 if (TAILQ_EMPTY(&m->md.pv_list))
3468 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3469 vm_page_spin_unlock(m);
3475 * Grow the number of kernel page table entries, if needed.
3477 * This routine is always called to validate any address space
3478 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3479 * space below KERNBASE.
3481 * kernel_map must be locked exclusively by the caller.
3484 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3487 vm_offset_t ptppaddr;
3489 pd_entry_t *pt, newpt;
3490 pdp_entry_t *pd, newpd;
3491 int update_kernel_vm_end;
3494 * bootstrap kernel_vm_end on first real VM use
3496 if (kernel_vm_end == 0) {
3497 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3500 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3503 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3505 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3506 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3507 if (kernel_vm_end - 1 >= kernel_map.max_offset) {
3508 kernel_vm_end = kernel_map.max_offset;
3515 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3516 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3517 * do not want to force-fill 128G worth of page tables.
3519 if (kstart < KERNBASE) {
3520 if (kstart > kernel_vm_end)
3521 kstart = kernel_vm_end;
3522 KKASSERT(kend <= KERNBASE);
3523 update_kernel_vm_end = 1;
3525 update_kernel_vm_end = 0;
3528 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3529 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3531 if (kend - 1 >= kernel_map.max_offset)
3532 kend = kernel_map.max_offset;
3534 while (kstart < kend) {
3535 pt = pmap_pt(&kernel_pmap, kstart);
3538 * We need a new PD entry
3540 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3543 VM_ALLOC_INTERRUPT);
3545 panic("pmap_growkernel: no memory to grow "
3548 paddr = VM_PAGE_TO_PHYS(nkpg);
3549 pmap_zero_page(paddr);
3550 pd = pmap_pd(&kernel_pmap, kstart);
3552 newpd = (pdp_entry_t)
3554 kernel_pmap.pmap_bits[PG_V_IDX] |
3555 kernel_pmap.pmap_bits[PG_RW_IDX] |
3556 kernel_pmap.pmap_bits[PG_A_IDX]);
3557 atomic_swap_long(pd, newpd);
3560 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3564 continue; /* try again */
3567 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3568 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3569 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3570 if (kstart - 1 >= kernel_map.max_offset) {
3571 kstart = kernel_map.max_offset;
3580 * This index is bogus, but out of the way
3582 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3585 VM_ALLOC_INTERRUPT);
3587 panic("pmap_growkernel: no memory to grow kernel");
3590 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3591 pmap_zero_page(ptppaddr);
3592 newpt = (pd_entry_t)(ptppaddr |
3593 kernel_pmap.pmap_bits[PG_V_IDX] |
3594 kernel_pmap.pmap_bits[PG_RW_IDX] |
3595 kernel_pmap.pmap_bits[PG_A_IDX]);
3596 atomic_swap_long(pt, newpt);
3598 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3599 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3601 if (kstart - 1 >= kernel_map.max_offset) {
3602 kstart = kernel_map.max_offset;
3608 * Only update kernel_vm_end for areas below KERNBASE.
3610 if (update_kernel_vm_end && kernel_vm_end < kstart)
3611 kernel_vm_end = kstart;
3615 * Add a reference to the specified pmap.
3618 pmap_reference(pmap_t pmap)
3621 atomic_add_int(&pmap->pm_count, 1);
3624 /***************************************************
3625 * page management routines.
3626 ***************************************************/
3629 * Hold a pv without locking it
3632 pv_hold(pv_entry_t pv)
3634 atomic_add_int(&pv->pv_hold, 1);
3638 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3639 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3642 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3643 * pv list via its page) must be held by the caller in order to stabilize
3647 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3652 * Critical path shortcut expects pv to already have one ref
3653 * (for the pv->pv_pmap).
3655 count = pv->pv_hold;
3658 if ((count & PV_HOLD_LOCKED) == 0) {
3659 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3660 (count + 1) | PV_HOLD_LOCKED)) {
3663 pv->pv_line = lineno;
3668 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3676 * Drop a previously held pv_entry which could not be locked, allowing its
3679 * Must not be called with a spinlock held as we might zfree() the pv if it
3680 * is no longer associated with a pmap and this was the last hold count.
3683 pv_drop(pv_entry_t pv)
3688 count = pv->pv_hold;
3690 KKASSERT((count & PV_HOLD_MASK) > 0);
3691 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3692 (PV_HOLD_LOCKED | 1));
3693 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3694 if ((count & PV_HOLD_MASK) == 1) {
3696 if (pmap_enter_debug > 0) {
3698 kprintf("pv_drop: free pv %p\n", pv);
3701 KKASSERT(count == 1);
3702 KKASSERT(pv->pv_pmap == NULL);
3712 * Find or allocate the requested PV entry, returning a locked, held pv.
3714 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3715 * for the caller and one representing the pmap and vm_page association.
3717 * If (*isnew) is zero, the returned pv will have only one hold count.
3719 * Since both associations can only be adjusted while the pv is locked,
3720 * together they represent just one additional hold.
3724 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3726 struct mdglobaldata *md = mdcpu;
3734 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3737 pnew = md->gd_newpv; /* might race NULL */
3738 md->gd_newpv = NULL;
3743 pnew = zalloc(pvzone);
3745 spin_lock_shared(&pmap->pm_spin);
3750 pv = pv_entry_lookup(pmap, pindex);
3755 * Requires exclusive pmap spinlock
3757 if (pmap_excl == 0) {
3759 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3760 spin_unlock_shared(&pmap->pm_spin);
3761 spin_lock(&pmap->pm_spin);
3767 * We need to block if someone is holding our
3768 * placemarker. As long as we determine the
3769 * placemarker has not been aquired we do not
3770 * need to get it as acquision also requires
3771 * the pmap spin lock.
3773 * However, we can race the wakeup.
3775 pmark = pmap_placemarker_hash(pmap, pindex);
3777 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3778 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3779 tsleep_interlock(pmark, 0);
3780 if (((*pmark ^ pindex) &
3781 ~PM_PLACEMARK_WAKEUP) == 0) {
3782 spin_unlock(&pmap->pm_spin);
3783 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3784 spin_lock(&pmap->pm_spin);
3790 * Setup the new entry
3792 pnew->pv_pmap = pmap;
3793 pnew->pv_pindex = pindex;
3794 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3796 pnew->pv_func = func;
3797 pnew->pv_line = lineno;
3798 if (pnew->pv_line_lastfree > 0) {
3799 pnew->pv_line_lastfree =
3800 -pnew->pv_line_lastfree;
3803 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3804 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3805 spin_unlock(&pmap->pm_spin);
3808 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3813 * We already have an entry, cleanup the staged pnew if
3814 * we can get the lock, otherwise block and retry.
3816 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3818 spin_unlock(&pmap->pm_spin);
3820 spin_unlock_shared(&pmap->pm_spin);
3822 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3824 zfree(pvzone, pnew);
3827 if (md->gd_newpv == NULL)
3828 md->gd_newpv = pnew;
3830 zfree(pvzone, pnew);
3833 KKASSERT(pv->pv_pmap == pmap &&
3834 pv->pv_pindex == pindex);
3839 spin_unlock(&pmap->pm_spin);
3840 _pv_lock(pv PMAP_DEBUG_COPY);
3842 spin_lock(&pmap->pm_spin);
3844 spin_unlock_shared(&pmap->pm_spin);
3845 _pv_lock(pv PMAP_DEBUG_COPY);
3847 spin_lock_shared(&pmap->pm_spin);
3854 * Find the requested PV entry, returning a locked+held pv or NULL
3858 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3863 spin_lock_shared(&pmap->pm_spin);
3868 pv = pv_entry_lookup(pmap, pindex);
3871 * Block if there is ANY placemarker. If we are to
3872 * return it, we must also aquire the spot, so we
3873 * have to block even if the placemarker is held on
3874 * a different address.
3876 * OPTIMIZATION: If pmarkp is passed as NULL the
3877 * caller is just probing (or looking for a real
3878 * pv_entry), and in this case we only need to check
3879 * to see if the placemarker matches pindex.
3884 * Requires exclusive pmap spinlock
3886 if (pmap_excl == 0) {
3888 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3889 spin_unlock_shared(&pmap->pm_spin);
3890 spin_lock(&pmap->pm_spin);
3895 pmark = pmap_placemarker_hash(pmap, pindex);
3897 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3898 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3899 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3900 tsleep_interlock(pmark, 0);
3901 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3902 ((*pmark ^ pindex) &
3903 ~PM_PLACEMARK_WAKEUP) == 0) {
3904 spin_unlock(&pmap->pm_spin);
3905 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3906 spin_lock(&pmap->pm_spin);
3911 if (atomic_swap_long(pmark, pindex) !=
3913 panic("_pv_get: pmark race");
3917 spin_unlock(&pmap->pm_spin);
3920 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3922 spin_unlock(&pmap->pm_spin);
3924 spin_unlock_shared(&pmap->pm_spin);
3925 KKASSERT(pv->pv_pmap == pmap &&
3926 pv->pv_pindex == pindex);
3930 spin_unlock(&pmap->pm_spin);
3931 _pv_lock(pv PMAP_DEBUG_COPY);
3933 spin_lock(&pmap->pm_spin);
3935 spin_unlock_shared(&pmap->pm_spin);
3936 _pv_lock(pv PMAP_DEBUG_COPY);
3938 spin_lock_shared(&pmap->pm_spin);
3944 * Lookup, hold, and attempt to lock (pmap,pindex).
3946 * If the entry does not exist NULL is returned and *errorp is set to 0
3948 * If the entry exists and could be successfully locked it is returned and
3949 * errorp is set to 0.
3951 * If the entry exists but could NOT be successfully locked it is returned
3952 * held and *errorp is set to 1.
3954 * If the entry is placemarked by someone else NULL is returned and *errorp
3959 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3963 spin_lock_shared(&pmap->pm_spin);
3965 pv = pv_entry_lookup(pmap, pindex);
3969 pmark = pmap_placemarker_hash(pmap, pindex);
3971 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3973 } else if (pmarkp &&
3974 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3978 * Can't set a placemark with a NULL pmarkp, or if
3979 * pmarkp is non-NULL but we failed to set our
3986 spin_unlock_shared(&pmap->pm_spin);
3992 * XXX This has problems if the lock is shared, why?
3994 if (pv_hold_try(pv)) {
3995 spin_unlock_shared(&pmap->pm_spin);
3997 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3998 return(pv); /* lock succeeded */
4000 spin_unlock_shared(&pmap->pm_spin);
4003 return (pv); /* lock failed */
4007 * Lock a held pv, keeping the hold count
4011 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
4016 count = pv->pv_hold;
4018 if ((count & PV_HOLD_LOCKED) == 0) {
4019 if (atomic_cmpset_int(&pv->pv_hold, count,
4020 count | PV_HOLD_LOCKED)) {
4023 pv->pv_line = lineno;
4029 tsleep_interlock(pv, 0);
4030 if (atomic_cmpset_int(&pv->pv_hold, count,
4031 count | PV_HOLD_WAITING)) {
4033 if (pmap_enter_debug > 0) {
4035 kprintf("pv waiting on %s:%d\n",
4036 pv->pv_func, pv->pv_line);
4039 tsleep(pv, PINTERLOCKED, "pvwait", hz);
4046 * Unlock a held and locked pv, keeping the hold count.
4050 pv_unlock(pv_entry_t pv)
4055 count = pv->pv_hold;
4057 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
4058 (PV_HOLD_LOCKED | 1));
4059 if (atomic_cmpset_int(&pv->pv_hold, count,
4061 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
4062 if (count & PV_HOLD_WAITING)
4070 * Unlock and drop a pv. If the pv is no longer associated with a pmap
4071 * and the hold count drops to zero we will free it.
4073 * Caller should not hold any spin locks. We are protected from hold races
4074 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
4075 * lock held. A pv cannot be located otherwise.
4079 pv_put(pv_entry_t pv)
4082 if (pmap_enter_debug > 0) {
4084 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
4089 * Normal put-aways must have a pv_m associated with the pv,
4090 * but allow the case where the pv has been destructed due
4091 * to pmap_dynamic_delete.
4093 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
4096 * Fast - shortcut most common condition
4098 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
4109 * Remove the pmap association from a pv, require that pv_m already be removed,
4110 * then unlock and drop the pv. Any pte operations must have already been
4111 * completed. This call may result in a last-drop which will physically free
4114 * Removing the pmap association entails an additional drop.
4116 * pv must be exclusively locked on call and will be disposed of on return.
4120 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
4125 pv->pv_func_lastfree = func;
4126 pv->pv_line_lastfree = lineno;
4128 KKASSERT(pv->pv_m == NULL);
4129 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
4130 (PV_HOLD_LOCKED|1));
4131 if ((pmap = pv->pv_pmap) != NULL) {
4132 spin_lock(&pmap->pm_spin);
4133 KKASSERT(pv->pv_pmap == pmap);
4134 if (pmap->pm_pvhint_pt == pv)
4135 pmap->pm_pvhint_pt = NULL;
4136 if (pmap->pm_pvhint_pte == pv)
4137 pmap->pm_pvhint_pte = NULL;
4138 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
4139 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4142 spin_unlock(&pmap->pm_spin);
4145 * Try to shortcut three atomic ops, otherwise fall through
4146 * and do it normally. Drop two refs and the lock all in
4150 vm_page_unwire_quick(pvp->pv_m);
4151 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
4153 if (pmap_enter_debug > 0) {
4155 kprintf("pv_free: free pv %p\n", pv);
4161 pv_drop(pv); /* ref for pv_pmap */
4168 * This routine is very drastic, but can save the system
4176 static int warningdone=0;
4178 if (pmap_pagedaemon_waken == 0)
4180 pmap_pagedaemon_waken = 0;
4181 if (warningdone < 5) {
4182 kprintf("pmap_collect: collecting pv entries -- "
4183 "suggest increasing PMAP_SHPGPERPROC\n");
4187 for (i = 0; i < vm_page_array_size; i++) {
4188 m = &vm_page_array[i];
4189 if (m->wire_count || m->hold_count)
4191 if (vm_page_busy_try(m, TRUE) == 0) {
4192 if (m->wire_count == 0 && m->hold_count == 0) {
4201 * Scan the pmap for active page table entries and issue a callback.
4202 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4203 * its parent page table.
4205 * pte_pv will be NULL if the page or page table is unmanaged.
4206 * pt_pv will point to the page table page containing the pte for the page.
4208 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4209 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4210 * process pmap's PD and page to the callback function. This can be
4211 * confusing because the pt_pv is really a pd_pv, and the target page
4212 * table page is simply aliased by the pmap and not owned by it.
4214 * It is assumed that the start and end are properly rounded to the page size.
4216 * It is assumed that PD pages and above are managed and thus in the RB tree,
4217 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4219 struct pmap_scan_info {
4223 vm_pindex_t sva_pd_pindex;
4224 vm_pindex_t eva_pd_pindex;
4225 void (*func)(pmap_t, struct pmap_scan_info *,
4226 pv_entry_t, vm_pindex_t *, pv_entry_t,
4228 pt_entry_t *, void *);
4230 pmap_inval_bulk_t bulk_core;
4231 pmap_inval_bulk_t *bulk;
4236 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4237 static int pmap_scan_callback(pv_entry_t pv, void *data);
4240 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4242 struct pmap *pmap = info->pmap;
4243 pv_entry_t pd_pv; /* A page directory PV */
4244 pv_entry_t pt_pv; /* A page table PV */
4245 pv_entry_t pte_pv; /* A page table entry PV */
4246 vm_pindex_t *pte_placemark;
4247 vm_pindex_t *pt_placemark;
4250 struct pv_entry dummy_pv;
4255 if (info->sva == info->eva)
4258 info->bulk = &info->bulk_core;
4259 pmap_inval_bulk_init(&info->bulk_core, pmap);
4265 * Hold the token for stability; if the pmap is empty we have nothing
4269 if (pmap->pm_stats.resident_count == 0) {
4277 * Special handling for scanning one page, which is a very common
4278 * operation (it is?).
4280 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4282 if (info->sva + PAGE_SIZE == info->eva) {
4283 if (info->sva >= VM_MAX_USER_ADDRESS) {
4285 * Kernel mappings do not track wire counts on
4286 * page table pages and only maintain pd_pv and
4287 * pte_pv levels so pmap_scan() works.
4290 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4292 ptep = vtopte(info->sva);
4295 * User pages which are unmanaged will not have a
4296 * pte_pv. User page table pages which are unmanaged
4297 * (shared from elsewhere) will also not have a pt_pv.
4298 * The func() callback will pass both pte_pv and pt_pv
4299 * as NULL in that case.
4301 * We hold pte_placemark across the operation for
4304 * WARNING! We must hold pt_placemark across the
4305 * *ptep test to prevent misintepreting
4306 * a non-zero *ptep as a shared page
4307 * table page. Hold it across the function
4308 * callback as well for SMP safety.
4310 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4312 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4314 if (pt_pv == NULL) {
4315 KKASSERT(pte_pv == NULL);
4316 pd_pv = pv_get(pmap,
4317 pmap_pd_pindex(info->sva),
4320 ptep = pv_pte_lookup(pd_pv,
4321 pmap_pt_index(info->sva));
4323 info->func(pmap, info,
4329 pv_placemarker_wakeup(pmap,
4334 pv_placemarker_wakeup(pmap,
4337 pv_placemarker_wakeup(pmap, pte_placemark);
4340 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4344 * NOTE: *ptep can't be ripped out from under us if we hold
4345 * pte_pv (or pte_placemark) locked, but bits can
4351 KKASSERT(pte_pv == NULL);
4352 pv_placemarker_wakeup(pmap, pte_placemark);
4353 } else if (pte_pv) {
4354 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4355 pmap->pmap_bits[PG_V_IDX])) ==
4356 (pmap->pmap_bits[PG_MANAGED_IDX] |
4357 pmap->pmap_bits[PG_V_IDX]),
4358 ("badA *ptep %016lx/%016lx sva %016lx pte_pv %p",
4359 *ptep, oldpte, info->sva, pte_pv));
4360 info->func(pmap, info, pte_pv, NULL, pt_pv, 0,
4361 info->sva, ptep, info->arg);
4363 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4364 pmap->pmap_bits[PG_V_IDX])) ==
4365 pmap->pmap_bits[PG_V_IDX],
4366 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4367 *ptep, oldpte, info->sva));
4368 info->func(pmap, info, NULL, pte_placemark, pt_pv, 0,
4369 info->sva, ptep, info->arg);
4374 pmap_inval_bulk_flush(info->bulk);
4379 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4382 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4383 * bounds, resulting in a pd_pindex of 0. To solve the
4384 * problem we use an inclusive range.
4386 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4387 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4389 if (info->sva >= VM_MAX_USER_ADDRESS) {
4391 * The kernel does not currently maintain any pv_entry's for
4392 * higher-level page tables.
4394 bzero(&dummy_pv, sizeof(dummy_pv));
4395 dummy_pv.pv_pindex = info->sva_pd_pindex;
4396 spin_lock(&pmap->pm_spin);
4397 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4398 pmap_scan_callback(&dummy_pv, info);
4399 ++dummy_pv.pv_pindex;
4400 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4403 spin_unlock(&pmap->pm_spin);
4406 * User page tables maintain local PML4, PDP, and PD
4407 * pv_entry's at the very least. PT pv's might be
4408 * unmanaged and thus not exist. PTE pv's might be
4409 * unmanaged and thus not exist.
4411 spin_lock(&pmap->pm_spin);
4412 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4413 pmap_scan_callback, info);
4414 spin_unlock(&pmap->pm_spin);
4416 pmap_inval_bulk_flush(info->bulk);
4420 * WARNING! pmap->pm_spin held
4422 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4423 * bounds, resulting in a pd_pindex of 0. To solve the
4424 * problem we use an inclusive range.
4427 pmap_scan_cmp(pv_entry_t pv, void *data)
4429 struct pmap_scan_info *info = data;
4430 if (pv->pv_pindex < info->sva_pd_pindex)
4432 if (pv->pv_pindex > info->eva_pd_pindex)
4438 * pmap_scan() by PDs
4440 * WARNING! pmap->pm_spin held
4443 pmap_scan_callback(pv_entry_t pv, void *data)
4445 struct pmap_scan_info *info = data;
4446 struct pmap *pmap = info->pmap;
4447 pv_entry_t pd_pv; /* A page directory PV */
4448 pv_entry_t pt_pv; /* A page table PV */
4449 vm_pindex_t *pt_placemark;
4454 vm_offset_t va_next;
4455 vm_pindex_t pd_pindex;
4465 * Pull the PD pindex from the pv before releasing the spinlock.
4467 * WARNING: pv is faked for kernel pmap scans.
4469 pd_pindex = pv->pv_pindex;
4470 spin_unlock(&pmap->pm_spin);
4471 pv = NULL; /* invalid after spinlock unlocked */
4474 * Calculate the page range within the PD. SIMPLE pmaps are
4475 * direct-mapped for the entire 2^64 address space. Normal pmaps
4476 * reflect the user and kernel address space which requires
4477 * cannonicalization w/regards to converting pd_pindex's back
4480 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4481 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4482 (sva & PML4_SIGNMASK)) {
4483 sva |= PML4_SIGNMASK;
4485 eva = sva + NBPDP; /* can overflow */
4486 if (sva < info->sva)
4488 if (eva < info->sva || eva > info->eva)
4492 * NOTE: kernel mappings do not track page table pages, only
4495 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4496 * However, for the scan to be efficient we try to
4497 * cache items top-down.
4502 for (; sva < eva; sva = va_next) {
4505 if (sva >= VM_MAX_USER_ADDRESS) {
4514 * PD cache, scan shortcut if it doesn't exist.
4516 if (pd_pv == NULL) {
4517 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4518 } else if (pd_pv->pv_pmap != pmap ||
4519 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4521 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4523 if (pd_pv == NULL) {
4524 va_next = (sva + NBPDP) & ~PDPMASK;
4533 * NOTE: The cached pt_pv can be removed from the pmap when
4534 * pmap_dynamic_delete is enabled.
4536 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4537 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4541 if (pt_pv == NULL) {
4542 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4543 &pt_placemark, &error);
4545 pv_put(pd_pv); /* lock order */
4552 pv_placemarker_wait(pmap, pt_placemark);
4557 /* may have to re-check later if pt_pv is NULL here */
4561 * If pt_pv is NULL we either have an shared page table
4562 * page and must issue a callback specific to that case,
4563 * or there is no page table page.
4565 * Either way we can skip the page table page.
4567 * WARNING! pt_pv can also be NULL due to a pv creation
4568 * race where we find it to be NULL and then
4569 * later see a pte_pv. But its possible the pt_pv
4570 * got created inbetween the two operations, so
4573 if (pt_pv == NULL) {
4575 * Possible unmanaged (shared from another pmap)
4578 * WARNING! We must hold pt_placemark across the
4579 * *ptep test to prevent misintepreting
4580 * a non-zero *ptep as a shared page
4581 * table page. Hold it across the function
4582 * callback as well for SMP safety.
4584 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4585 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4586 info->func(pmap, info, NULL, pt_placemark,
4588 sva, ptep, info->arg);
4590 pv_placemarker_wakeup(pmap, pt_placemark);
4594 * Done, move to next page table page.
4596 va_next = (sva + NBPDR) & ~PDRMASK;
4603 * From this point in the loop testing pt_pv for non-NULL
4604 * means we are in UVM, else if it is NULL we are in KVM.
4606 * Limit our scan to either the end of the va represented
4607 * by the current page table page, or to the end of the
4608 * range being removed.
4611 va_next = (sva + NBPDR) & ~PDRMASK;
4618 * Scan the page table for pages. Some pages may not be
4619 * managed (might not have a pv_entry).
4621 * There is no page table management for kernel pages so
4622 * pt_pv will be NULL in that case, but otherwise pt_pv
4623 * is non-NULL, locked, and referenced.
4627 * At this point a non-NULL pt_pv means a UVA, and a NULL
4628 * pt_pv means a KVA.
4631 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4635 while (sva < va_next) {
4637 vm_pindex_t *pte_placemark;
4640 * Yield every 64 pages, stop if requested.
4642 if ((++info->count & 63) == 0)
4648 * We can shortcut our scan if *ptep == 0. This is
4649 * an unlocked check.
4659 * Acquire the related pte_pv, if any. If *ptep == 0
4660 * the related pte_pv should not exist, but if *ptep
4661 * is not zero the pte_pv may or may not exist (e.g.
4662 * will not exist for an unmanaged page).
4664 * However a multitude of races are possible here
4665 * so if we cannot lock definite state we clean out
4666 * our cache and break the inner while() loop to
4667 * force a loop up to the top of the for().
4669 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4670 * validity instead of looping up?
4672 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4673 &pte_placemark, &error);
4676 pv_put(pd_pv); /* lock order */
4680 pv_put(pt_pv); /* lock order */
4683 if (pte_pv) { /* block */
4688 pv_placemarker_wait(pmap,
4691 va_next = sva; /* retry */
4696 * Reload *ptep after successfully locking the
4697 * pindex. If *ptep == 0 we had better NOT have a
4704 kprintf("Unexpected non-NULL pte_pv "
4706 "*ptep = %016lx/%016lx\n",
4707 pte_pv, pt_pv, *ptep, oldpte);
4708 panic("Unexpected non-NULL pte_pv");
4710 pv_placemarker_wakeup(pmap, pte_placemark);
4718 * We can't hold pd_pv across the callback (because
4719 * we don't pass it to the callback and the callback
4723 vm_page_wire_quick(pd_pv->pv_m);
4728 * Ready for the callback. The locked pte_pv (if any)
4729 * is consumed by the callback. pte_pv will exist if
4730 * the page is managed, and will not exist if it
4733 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4738 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4739 ("badC *ptep %016lx/%016lx sva %016lx "
4741 *ptep, oldpte, sva, pte_pv));
4743 * We must unlock pd_pv across the callback
4744 * to avoid deadlocks on any recursive
4745 * disposal. Re-check that it still exists
4748 * Call target disposes of pte_pv and may
4749 * destroy but will not dispose of pt_pv.
4751 info->func(pmap, info, pte_pv, NULL,
4753 sva, ptep, info->arg);
4758 * We must unlock pd_pv across the callback
4759 * to avoid deadlocks on any recursive
4760 * disposal. Re-check that it still exists
4763 * Call target disposes of pte_pv or
4764 * pte_placemark and may destroy but will
4765 * not dispose of pt_pv.
4767 KASSERT(pte_pv == NULL &&
4768 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4769 ("badD *ptep %016lx/%016lx sva %016lx "
4770 "pte_pv %p pte_pv->pv_m %p ",
4772 pte_pv, (pte_pv ? pte_pv->pv_m : NULL)));
4776 info->func(pmap, info,
4779 sva, ptep, info->arg);
4781 info->func(pmap, info,
4782 NULL, pte_placemark,
4784 sva, ptep, info->arg);
4789 vm_page_unwire_quick(pd_pv->pv_m);
4790 if (pd_pv->pv_pmap == NULL) {
4791 va_next = sva; /* retry */
4797 * NOTE: The cached pt_pv can be removed from the
4798 * pmap when pmap_dynamic_delete is enabled,
4799 * which will cause ptep to become stale.
4801 * This also means that no pages remain under
4802 * the PT, so we can just break out of the inner
4803 * loop and let the outer loop clean everything
4806 if (pt_pv && pt_pv->pv_pmap != pmap)
4821 if ((++info->count & 7) == 0)
4825 * Relock before returning.
4827 spin_lock(&pmap->pm_spin);
4832 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4834 struct pmap_scan_info info;
4839 info.func = pmap_remove_callback;
4841 pmap_scan(&info, 1);
4844 if (eva - sva < 1024*1024) {
4846 cpu_invlpg((void *)sva);
4854 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4856 struct pmap_scan_info info;
4861 info.func = pmap_remove_callback;
4863 pmap_scan(&info, 0);
4867 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4868 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
4869 pv_entry_t pt_pv, int sharept,
4870 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4878 * This will also drop pt_pv's wire_count. Note that
4879 * terminal pages are not wired based on mmu presence.
4881 * NOTE: If this is the kernel_pmap, pt_pv can be NULL.
4883 KKASSERT(pte_pv->pv_m != NULL);
4884 pmap_remove_pv_pte(pte_pv, pt_pv, info->bulk, 2);
4885 pte_pv = NULL; /* safety */
4888 * Recursively destroy higher-level page tables.
4890 * This is optional. If we do not, they will still
4891 * be destroyed when the process exits.
4893 * NOTE: Do not destroy pv_entry's with extra hold refs,
4894 * a caller may have unlocked it and intends to
4895 * continue to use it.
4897 if (pmap_dynamic_delete &&
4900 pt_pv->pv_m->wire_count == 1 &&
4901 (pt_pv->pv_hold & PV_HOLD_MASK) == 2 &&
4902 pt_pv->pv_pindex < pmap_pml4_pindex()) {
4903 if (pmap_dynamic_delete == 2)
4904 kprintf("B %jd %08x\n", pt_pv->pv_pindex, pt_pv->pv_hold);
4905 pv_hold(pt_pv); /* extra hold */
4906 pmap_remove_pv_pte(pt_pv, NULL, info->bulk, 1);
4907 pv_lock(pt_pv); /* prior extra hold + relock */
4909 } else if (sharept == 0) {
4911 * Unmanaged pte (pte_placemark is non-NULL)
4913 * pt_pv's wire_count is still bumped by unmanaged pages
4914 * so we must decrement it manually.
4916 * We have to unwire the target page table page.
4918 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4919 if (pte & pmap->pmap_bits[PG_W_IDX])
4920 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4921 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4922 if (vm_page_unwire_quick(pt_pv->pv_m))
4923 panic("pmap_remove: insufficient wirecount");
4924 pv_placemarker_wakeup(pmap, pte_placemark);
4927 * Unmanaged page table (pt, pd, or pdp. Not pte) for
4928 * a shared page table.
4930 * pt_pv is actually the pd_pv for our pmap (not the shared
4933 * We have to unwire the target page table page and we
4934 * have to unwire our page directory page.
4936 * It is unclear how we can invalidate a segment so we
4937 * invalidate -1 which invlidates the tlb.
4939 pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
4940 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4941 KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
4942 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
4943 panic("pmap_remove: shared pgtable1 bad wirecount");
4944 if (vm_page_unwire_quick(pt_pv->pv_m))
4945 panic("pmap_remove: shared pgtable2 bad wirecount");
4946 pv_placemarker_wakeup(pmap, pte_placemark);
4951 * Removes this physical page from all physical maps in which it resides.
4952 * Reflects back modify bits to the pager.
4954 * This routine may not be called from an interrupt.
4958 pmap_remove_all(vm_page_t m)
4961 pmap_inval_bulk_t bulk;
4963 if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
4966 vm_page_spin_lock(m);
4967 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4968 KKASSERT(pv->pv_m == m);
4969 if (pv_hold_try(pv)) {
4970 vm_page_spin_unlock(m);
4972 vm_page_spin_unlock(m);
4975 vm_page_spin_lock(m);
4978 KKASSERT(pv->pv_pmap && pv->pv_m == m);
4981 * Holding no spinlocks, pv is locked. Once we scrap
4982 * pv we can no longer use it as a list iterator (but
4983 * we are doing a TAILQ_FIRST() so we are ok).
4985 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
4986 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
4987 pv = NULL; /* safety */
4988 pmap_inval_bulk_flush(&bulk);
4989 vm_page_spin_lock(m);
4991 KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
4992 vm_page_spin_unlock(m);
4996 * Removes the page from a particular pmap
4999 pmap_remove_specific(pmap_t pmap, vm_page_t m)
5002 pmap_inval_bulk_t bulk;
5004 if (!pmap_initialized)
5008 vm_page_spin_lock(m);
5009 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5010 if (pv->pv_pmap != pmap)
5012 KKASSERT(pv->pv_m == m);
5013 if (pv_hold_try(pv)) {
5014 vm_page_spin_unlock(m);
5016 vm_page_spin_unlock(m);
5021 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
5024 * Holding no spinlocks, pv is locked. Once gone it can't
5025 * be used as an iterator. In fact, because we couldn't
5026 * necessarily lock it atomically it may have moved within
5027 * the list and ALSO cannot be used as an iterator.
5029 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5030 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5031 pv = NULL; /* safety */
5032 pmap_inval_bulk_flush(&bulk);
5035 vm_page_spin_unlock(m);
5039 * Set the physical protection on the specified range of this map
5040 * as requested. This function is typically only used for debug watchpoints
5043 * This function may not be called from an interrupt if the map is
5044 * not the kernel_pmap.
5046 * NOTE! For shared page table pages we just unmap the page.
5049 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
5051 struct pmap_scan_info info;
5052 /* JG review for NX */
5056 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
5057 pmap_remove(pmap, sva, eva);
5060 if (prot & VM_PROT_WRITE)
5065 info.func = pmap_protect_callback;
5067 pmap_scan(&info, 1);
5072 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
5073 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
5074 pv_entry_t pt_pv, int sharept,
5075 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
5086 KKASSERT(pte_pv->pv_m != NULL);
5088 if (pbits & pmap->pmap_bits[PG_A_IDX]) {
5089 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5090 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5091 KKASSERT(m == pte_pv->pv_m);
5092 vm_page_flag_set(m, PG_REFERENCED);
5094 cbits &= ~pmap->pmap_bits[PG_A_IDX];
5096 if (pbits & pmap->pmap_bits[PG_M_IDX]) {
5097 if (pmap_track_modified(pte_pv->pv_pindex)) {
5098 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5100 m = PHYS_TO_VM_PAGE(pbits &
5105 cbits &= ~pmap->pmap_bits[PG_M_IDX];
5108 } else if (sharept) {
5110 * Unmanaged page table, pt_pv is actually the pd_pv
5111 * for our pmap (not the object's shared pmap).
5113 * When asked to protect something in a shared page table
5114 * page we just unmap the page table page. We have to
5115 * invalidate the tlb in this situation.
5117 * XXX Warning, shared page tables will not be used for
5118 * OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
5119 * so PHYS_TO_VM_PAGE() should be safe here.
5121 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
5122 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
5123 panic("pmap_protect: pgtable1 pg bad wirecount");
5124 if (vm_page_unwire_quick(pt_pv->pv_m))
5125 panic("pmap_protect: pgtable2 pg bad wirecount");
5128 /* else unmanaged page, adjust bits, no wire changes */
5131 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
5133 if (pmap_enter_debug > 0) {
5135 kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
5136 "pt_pv=%p cbits=%08lx\n",
5142 if (pbits != cbits) {
5145 xva = (sharept) ? (vm_offset_t)-1 : va;
5146 if (!pmap_inval_smp_cmpset(pmap, xva,
5147 ptep, pbits, cbits)) {
5155 pv_placemarker_wakeup(pmap, pte_placemark);
5159 * Insert the vm_page (m) at the virtual address (va), replacing any prior
5160 * mapping at that address. Set protection and wiring as requested.
5162 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5163 * possible. If it is we enter the page into the appropriate shared pmap
5164 * hanging off the related VM object instead of the passed pmap, then we
5165 * share the page table page from the VM object's pmap into the current pmap.
5167 * NOTE: This routine MUST insert the page into the pmap now, it cannot
5170 * NOTE: If (m) is PG_UNMANAGED it may also be a temporary fake vm_page_t.
5174 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5175 boolean_t wired, vm_map_entry_t entry)
5177 pv_entry_t pt_pv; /* page table */
5178 pv_entry_t pte_pv; /* page table entry */
5179 vm_pindex_t *pte_placemark;
5182 pt_entry_t origpte, newpte;
5187 va = trunc_page(va);
5188 #ifdef PMAP_DIAGNOSTIC
5190 panic("pmap_enter: toobig");
5191 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5192 panic("pmap_enter: invalid to pmap_enter page table "
5193 "pages (va: 0x%lx)", va);
5195 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
5196 kprintf("Warning: pmap_enter called on UVA with "
5199 db_print_backtrace();
5202 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
5203 kprintf("Warning: pmap_enter called on KVA without"
5206 db_print_backtrace();
5211 * Get locked PV entries for our new page table entry (pte_pv or
5212 * pte_placemark) and for its parent page table (pt_pv). We need
5213 * the parent so we can resolve the location of the ptep.
5215 * Only hardware MMU actions can modify the ptep out from
5218 * if (m) is fictitious or unmanaged we do not create a managing
5219 * pte_pv for it. Any pre-existing page's management state must
5220 * match (avoiding code complexity).
5222 * If the pmap is still being initialized we assume existing
5225 * Kernel mapppings do not track page table pages (i.e. pt_pv).
5227 * WARNING! If replacing a managed mapping with an unmanaged mapping
5228 * pte_pv will wind up being non-NULL and must be handled
5231 if (pmap_initialized == FALSE) {
5234 pte_placemark = NULL;
5237 } else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
5238 pmap_softwait(pmap);
5239 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5240 KKASSERT(pte_pv == NULL);
5241 if (va >= VM_MAX_USER_ADDRESS) {
5245 pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
5247 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5251 KASSERT(origpte == 0 ||
5252 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0,
5253 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5255 pmap_softwait(pmap);
5256 if (va >= VM_MAX_USER_ADDRESS) {
5258 * Kernel map, pv_entry-tracked.
5261 pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
5267 pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
5269 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5271 pte_placemark = NULL; /* safety */
5274 KASSERT(origpte == 0 ||
5275 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]),
5276 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5279 pa = VM_PAGE_TO_PHYS(m);
5280 opa = origpte & PG_FRAME;
5283 * Calculate the new PTE. Note that pte_pv alone does not mean
5284 * the new pte_pv is managed, it could exist because the old pte
5285 * was managed even if the new one is not.
5287 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5288 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5290 newpte |= pmap->pmap_bits[PG_W_IDX];
5291 if (va < VM_MAX_USER_ADDRESS)
5292 newpte |= pmap->pmap_bits[PG_U_IDX];
5293 if (pte_pv && (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) == 0)
5294 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5295 // if (pmap == &kernel_pmap)
5296 // newpte |= pgeflag;
5297 newpte |= pmap->pmap_cache_bits[m->pat_mode];
5298 if (m->flags & PG_FICTITIOUS)
5299 newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
5302 * It is possible for multiple faults to occur in threaded
5303 * environments, the existing pte might be correct.
5305 if (((origpte ^ newpte) &
5306 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5307 pmap->pmap_bits[PG_A_IDX])) == 0) {
5312 * Ok, either the address changed or the protection or wiring
5315 * Clear the current entry, interlocking the removal. For managed
5316 * pte's this will also flush the modified state to the vm_page.
5317 * Atomic ops are mandatory in order to ensure that PG_M events are
5318 * not lost during any transition.
5320 * WARNING: The caller has busied the new page but not the original
5321 * vm_page which we are trying to replace. Because we hold
5322 * the pte_pv lock, but have not busied the page, PG bits
5323 * can be cleared out from under us.
5326 if (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
5328 * Old page was managed. Expect pte_pv to exist.
5329 * (it might also exist if the old page was unmanaged).
5331 * NOTE: pt_pv won't exist for a kernel page
5332 * (managed or otherwise).
5334 * NOTE: We may be reusing the pte_pv so we do not
5335 * destroy it in pmap_remove_pv_pte().
5337 KKASSERT(pte_pv && pte_pv->pv_m);
5338 if (prot & VM_PROT_NOSYNC) {
5339 pmap_remove_pv_pte(pte_pv, pt_pv, NULL, 0);
5341 pmap_inval_bulk_t bulk;
5343 pmap_inval_bulk_init(&bulk, pmap);
5344 pmap_remove_pv_pte(pte_pv, pt_pv, &bulk, 0);
5345 pmap_inval_bulk_flush(&bulk);
5347 pmap_remove_pv_page(pte_pv);
5348 /* will either set pte_pv->pv_m or pv_free() later */
5351 * Old page was not managed. If we have a pte_pv
5352 * it better not have a pv_m assigned to it. If the
5353 * new page is managed the pte_pv will be destroyed
5354 * near the end (we need its interlock).
5356 * NOTE: We leave the wire count on the PT page
5357 * intact for the followup enter, but adjust
5358 * the wired-pages count on the pmap.
5360 KKASSERT(pte_pv == NULL);
5361 if (prot & VM_PROT_NOSYNC) {
5363 * NOSYNC (no mmu sync) requested.
5365 (void)pte_load_clear(ptep);
5366 cpu_invlpg((void *)va);
5371 pmap_inval_smp(pmap, va, 1, ptep, 0);
5375 * We must adjust pm_stats manually for unmanaged
5379 atomic_add_long(&pmap->pm_stats.
5380 resident_count, -1);
5382 if (origpte & pmap->pmap_bits[PG_W_IDX]) {
5383 atomic_add_long(&pmap->pm_stats.
5387 KKASSERT(*ptep == 0);
5391 if (pmap_enter_debug > 0) {
5393 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5394 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5396 origpte, newpte, ptep,
5397 pte_pv, pt_pv, opa, prot);
5401 if ((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5403 * Entering an unmanaged page. We must wire the pt_pv unless
5404 * we retained the wiring from an unmanaged page we had
5405 * removed (if we retained it via pte_pv that will go away
5408 if (pt_pv && (opa == 0 ||
5409 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]))) {
5410 vm_page_wire_quick(pt_pv->pv_m);
5413 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5416 * Unmanaged pages need manual resident_count tracking.
5419 atomic_add_long(&pt_pv->pv_pmap->pm_stats.
5422 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5423 vm_page_flag_set(m, PG_WRITEABLE);
5426 * Entering a managed page. Our pte_pv takes care of the
5427 * PT wiring, so if we had removed an unmanaged page before
5430 * We have to take care of the pmap wired count ourselves.
5432 * Enter on the PV list if part of our managed memory.
5434 KKASSERT(pte_pv && (pte_pv->pv_m == NULL || pte_pv->pv_m == m));
5435 vm_page_spin_lock(m);
5437 pmap_page_stats_adding(m);
5438 TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
5439 vm_page_flag_set(m, PG_MAPPED);
5440 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5441 vm_page_flag_set(m, PG_WRITEABLE);
5442 vm_page_spin_unlock(m);
5445 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5446 vm_page_unwire_quick(pt_pv->pv_m);
5450 * Adjust pmap wired pages count for new entry.
5453 atomic_add_long(&pte_pv->pv_pmap->pm_stats.
5459 * Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
5461 * User VMAs do not because those will be zero->non-zero, so no
5462 * stale entries to worry about at this point.
5464 * For KVM there appear to still be issues. Theoretically we
5465 * should be able to scrap the interlocks entirely but we
5468 if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL) {
5469 pmap_inval_smp(pmap, va, 1, ptep, newpte);
5471 origpte = atomic_swap_long(ptep, newpte);
5472 if (origpte & pmap->pmap_bits[PG_M_IDX]) {
5473 kprintf("pmap [M] race @ %016jx\n", va);
5474 atomic_set_long(ptep, pmap->pmap_bits[PG_M_IDX]);
5477 cpu_invlpg((void *)va);
5484 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5485 (m->flags & PG_MAPPED));
5488 * Cleanup the pv entry, allowing other accessors. If the new page
5489 * is not managed but we have a pte_pv (which was locking our
5490 * operation), we can free it now. pte_pv->pv_m should be NULL.
5492 if (pte_pv && (newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5493 pv_free(pte_pv, pt_pv);
5494 } else if (pte_pv) {
5496 } else if (pte_placemark) {
5497 pv_placemarker_wakeup(pmap, pte_placemark);
5504 * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
5505 * This code also assumes that the pmap has no pre-existing entry for this
5508 * This code currently may only be used on user pmaps, not kernel_pmap.
5511 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
5513 pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
5517 * Make a temporary mapping for a physical address. This is only intended
5518 * to be used for panic dumps.
5520 * The caller is responsible for calling smp_invltlb().
5523 pmap_kenter_temporary(vm_paddr_t pa, long i)
5525 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5526 return ((void *)crashdumpmap);
5529 #define MAX_INIT_PT (96)
5532 * This routine preloads the ptes for a given object into the specified pmap.
5533 * This eliminates the blast of soft faults on process startup and
5534 * immediately after an mmap.
5536 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5539 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
5540 vm_object_t object, vm_pindex_t pindex,
5541 vm_size_t size, int limit)
5543 struct rb_vm_page_scan_info info;
5548 * We can't preinit if read access isn't set or there is no pmap
5551 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5555 * We can't preinit if the pmap is not the current pmap
5557 lp = curthread->td_lwp;
5558 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5562 * Misc additional checks
5564 psize = x86_64_btop(size);
5566 if ((object->type != OBJT_VNODE) ||
5567 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5568 (object->resident_page_count > MAX_INIT_PT))) {
5572 if (pindex + psize > object->size) {
5573 if (object->size < pindex)
5575 psize = object->size - pindex;
5582 * If everything is segment-aligned do not pre-init here. Instead
5583 * allow the normal vm_fault path to pass a segment hint to
5584 * pmap_enter() which will then use an object-referenced shared
5587 if ((addr & SEG_MASK) == 0 &&
5588 (ctob(psize) & SEG_MASK) == 0 &&
5589 (ctob(pindex) & SEG_MASK) == 0) {
5594 * Use a red-black scan to traverse the requested range and load
5595 * any valid pages found into the pmap.
5597 * We cannot safely scan the object's memq without holding the
5600 info.start_pindex = pindex;
5601 info.end_pindex = pindex + psize - 1;
5606 info.object = object;
5609 * By using the NOLK scan, the callback function must be sure
5610 * to return -1 if the VM page falls out of the object.
5612 vm_object_hold_shared(object);
5613 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5614 pmap_object_init_pt_callback, &info);
5615 vm_object_drop(object);
5620 pmap_object_init_pt_callback(vm_page_t p, void *data)
5622 struct rb_vm_page_scan_info *info = data;
5623 vm_pindex_t rel_index;
5627 * don't allow an madvise to blow away our really
5628 * free pages allocating pv entries.
5630 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5631 vmstats.v_free_count < vmstats.v_free_reserved) {
5636 * Ignore list markers and ignore pages we cannot instantly
5637 * busy (while holding the object token).
5639 if (p->flags & PG_MARKER)
5644 if (vm_page_busy_try(p, TRUE))
5647 if (vm_page_sbusy_try(p))
5650 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5651 (p->flags & PG_FICTITIOUS) == 0) {
5652 if ((p->queue - p->pc) == PQ_CACHE) {
5653 if (hard_busy == 0) {
5654 vm_page_sbusy_drop(p);
5658 vm_page_deactivate(p);
5660 rel_index = p->pindex - info->start_pindex;
5661 pmap_enter_quick(info->pmap,
5662 info->addr + x86_64_ptob(rel_index), p);
5667 vm_page_sbusy_drop(p);
5670 * We are using an unlocked scan (that is, the scan expects its
5671 * current element to remain in the tree on return). So we have
5672 * to check here and abort the scan if it isn't.
5674 if (p->object != info->object)
5681 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5684 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5687 * XXX This is safe only because page table pages are not freed.
5690 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5694 /*spin_lock(&pmap->pm_spin);*/
5695 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5696 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5697 /*spin_unlock(&pmap->pm_spin);*/
5701 /*spin_unlock(&pmap->pm_spin);*/
5706 * Change the wiring attribute for a pmap/va pair. The mapping must already
5707 * exist in the pmap. The mapping may or may not be managed. The wiring in
5708 * the page is not changed, the page is returned so the caller can adjust
5709 * its wiring (the page is not locked in any way).
5711 * Wiring is not a hardware characteristic so there is no need to invalidate
5712 * TLB. However, in an SMP environment we must use a locked bus cycle to
5713 * update the pte (if we are not using the pmap_inval_*() API that is)...
5714 * it's ok to do this for simple wiring changes.
5717 pmap_unwire(pmap_t pmap, vm_offset_t va)
5728 * Assume elements in the kernel pmap are stable
5730 if (pmap == &kernel_pmap) {
5731 if (pmap_pt(pmap, va) == 0)
5733 ptep = pmap_pte_quick(pmap, va);
5734 if (pmap_pte_v(pmap, ptep)) {
5735 if (pmap_pte_w(pmap, ptep))
5736 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5737 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5738 pa = *ptep & PG_FRAME;
5739 m = PHYS_TO_VM_PAGE(pa);
5745 * We can only [un]wire pmap-local pages (we cannot wire
5748 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5752 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5753 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5758 if (pmap_pte_w(pmap, ptep)) {
5759 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5762 /* XXX else return NULL so caller doesn't unwire m ? */
5764 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5766 pa = *ptep & PG_FRAME;
5767 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5774 * Copy the range specified by src_addr/len from the source map to
5775 * the range dst_addr/len in the destination map.
5777 * This routine is only advisory and need not do anything.
5780 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5781 vm_size_t len, vm_offset_t src_addr)
5788 * Zero the specified physical page.
5790 * This function may be called from an interrupt and no locking is
5794 pmap_zero_page(vm_paddr_t phys)
5796 vm_offset_t va = PHYS_TO_DMAP(phys);
5798 pagezero((void *)va);
5804 * Zero part of a physical page by mapping it into memory and clearing
5805 * its contents with bzero.
5807 * off and size may not cover an area beyond a single hardware page.
5810 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5812 vm_offset_t virt = PHYS_TO_DMAP(phys);
5814 bzero((char *)virt + off, size);
5820 * Copy the physical page from the source PA to the target PA.
5821 * This function may be called from an interrupt. No locking
5825 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5827 vm_offset_t src_virt, dst_virt;
5829 src_virt = PHYS_TO_DMAP(src);
5830 dst_virt = PHYS_TO_DMAP(dst);
5831 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5835 * pmap_copy_page_frag:
5837 * Copy the physical page from the source PA to the target PA.
5838 * This function may be called from an interrupt. No locking
5842 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5844 vm_offset_t src_virt, dst_virt;
5846 src_virt = PHYS_TO_DMAP(src);
5847 dst_virt = PHYS_TO_DMAP(dst);
5849 bcopy((char *)src_virt + (src & PAGE_MASK),
5850 (char *)dst_virt + (dst & PAGE_MASK),
5855 * Returns true if the pmap's pv is one of the first 16 pvs linked to from
5856 * this page. This count may be changed upwards or downwards in the future;
5857 * it is only necessary that true be returned for a small subset of pmaps
5858 * for proper page aging.
5861 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5866 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5869 vm_page_spin_lock(m);
5870 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5871 if (pv->pv_pmap == pmap) {
5872 vm_page_spin_unlock(m);
5879 vm_page_spin_unlock(m);
5884 * Remove all pages from specified address space this aids process exit
5885 * speeds. Also, this code may be special cased for the current process
5889 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5891 pmap_remove_noinval(pmap, sva, eva);
5896 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5897 * routines are inline, and a lot of things compile-time evaluate.
5902 pmap_testbit(vm_page_t m, int bit)
5908 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5911 if (TAILQ_FIRST(&m->md.pv_list) == NULL)
5913 vm_page_spin_lock(m);
5914 if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
5915 vm_page_spin_unlock(m);
5919 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5920 #if defined(PMAP_DIAGNOSTIC)
5921 if (pv->pv_pmap == NULL) {
5922 kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
5930 * If the bit being tested is the modified bit, then
5931 * mark clean_map and ptes as never
5934 * WARNING! Because we do not lock the pv, *pte can be in a
5935 * state of flux. Despite this the value of *pte
5936 * will still be related to the vm_page in some way
5937 * because the pv cannot be destroyed as long as we
5938 * hold the vm_page spin lock.
5940 if (bit == PG_A_IDX || bit == PG_M_IDX) {
5941 //& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
5942 if (!pmap_track_modified(pv->pv_pindex))
5946 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
5947 if (*pte & pmap->pmap_bits[bit]) {
5948 vm_page_spin_unlock(m);
5952 vm_page_spin_unlock(m);
5957 * This routine is used to modify bits in ptes. Only one bit should be
5958 * specified. PG_RW requires special handling.
5960 * Caller must NOT hold any spin locks
5964 pmap_clearbit(vm_page_t m, int bit_index)
5971 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
5972 if (bit_index == PG_RW_IDX)
5973 vm_page_flag_clear(m, PG_WRITEABLE);
5980 * Loop over all current mappings setting/clearing as appropos If
5981 * setting RO do we need to clear the VAC?
5983 * NOTE: When clearing PG_M we could also (not implemented) drop
5984 * through to the PG_RW code and clear PG_RW too, forcing
5985 * a fault on write to redetect PG_M for virtual kernels, but
5986 * it isn't necessary since virtual kernels invalidate the
5987 * pte when they clear the VPTE_M bit in their virtual page
5990 * NOTE: Does not re-dirty the page when clearing only PG_M.
5992 * NOTE: Because we do not lock the pv, *pte can be in a state of
5993 * flux. Despite this the value of *pte is still somewhat
5994 * related while we hold the vm_page spin lock.
5996 * *pte can be zero due to this race. Since we are clearing
5997 * bits we basically do no harm when this race occurs.
5999 if (bit_index != PG_RW_IDX) {
6000 vm_page_spin_lock(m);
6001 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6002 #if defined(PMAP_DIAGNOSTIC)
6003 if (pv->pv_pmap == NULL) {
6004 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6010 pte = pmap_pte_quick(pv->pv_pmap,
6011 pv->pv_pindex << PAGE_SHIFT);
6013 if (pbits & pmap->pmap_bits[bit_index])
6014 atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
6016 vm_page_spin_unlock(m);
6021 * Clear PG_RW. Also clears PG_M and marks the page dirty if PG_M
6025 vm_page_spin_lock(m);
6026 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6028 * don't write protect pager mappings
6030 if (!pmap_track_modified(pv->pv_pindex))
6033 #if defined(PMAP_DIAGNOSTIC)
6034 if (pv->pv_pmap == NULL) {
6035 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6043 * Skip pages which do not have PG_RW set.
6045 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6046 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
6050 * We must lock the PV to be able to safely test the pte.
6052 if (pv_hold_try(pv)) {
6053 vm_page_spin_unlock(m);
6055 vm_page_spin_unlock(m);
6056 pv_lock(pv); /* held, now do a blocking lock */
6062 * Reload pte after acquiring pv.
6064 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6066 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0) {
6072 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
6078 nbits = pbits & ~(pmap->pmap_bits[PG_RW_IDX] |
6079 pmap->pmap_bits[PG_M_IDX]);
6080 if (pmap_inval_smp_cmpset(pmap,
6081 ((vm_offset_t)pv->pv_pindex << PAGE_SHIFT),
6082 pte, pbits, nbits)) {
6089 * If PG_M was found to be set while we were clearing PG_RW
6090 * we also clear PG_M (done above) and mark the page dirty.
6091 * Callers expect this behavior.
6093 * we lost pv so it cannot be used as an iterator. In fact,
6094 * because we couldn't necessarily lock it atomically it may
6095 * have moved within the list and ALSO cannot be used as an
6098 vm_page_spin_lock(m);
6099 if (pbits & pmap->pmap_bits[PG_M_IDX])
6101 vm_page_spin_unlock(m);
6105 if (bit_index == PG_RW_IDX)
6106 vm_page_flag_clear(m, PG_WRITEABLE);
6107 vm_page_spin_unlock(m);
6111 * Lower the permission for all mappings to a given page.
6113 * Page must be busied by caller. Because page is busied by caller this
6114 * should not be able to race a pmap_enter().
6117 pmap_page_protect(vm_page_t m, vm_prot_t prot)
6119 /* JG NX support? */
6120 if ((prot & VM_PROT_WRITE) == 0) {
6121 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
6123 * NOTE: pmap_clearbit(.. PG_RW) also clears
6124 * the PG_WRITEABLE flag in (m).
6126 pmap_clearbit(m, PG_RW_IDX);
6134 pmap_phys_address(vm_pindex_t ppn)
6136 return (x86_64_ptob(ppn));
6140 * Return a count of reference bits for a page, clearing those bits.
6141 * It is not necessary for every reference bit to be cleared, but it
6142 * is necessary that 0 only be returned when there are truly no
6143 * reference bits set.
6145 * XXX: The exact number of bits to check and clear is a matter that
6146 * should be tested and standardized at some point in the future for
6147 * optimal aging of shared pages.
6149 * This routine may not block.
6152 pmap_ts_referenced(vm_page_t m)
6159 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
6162 vm_page_spin_lock(m);
6163 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6164 if (!pmap_track_modified(pv->pv_pindex))
6167 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6168 if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
6169 atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
6175 vm_page_spin_unlock(m);
6182 * Return whether or not the specified physical page was modified
6183 * in any physical maps.
6186 pmap_is_modified(vm_page_t m)
6190 res = pmap_testbit(m, PG_M_IDX);
6195 * Clear the modify bits on the specified physical page.
6198 pmap_clear_modify(vm_page_t m)
6200 pmap_clearbit(m, PG_M_IDX);
6204 * pmap_clear_reference:
6206 * Clear the reference bit on the specified physical page.
6209 pmap_clear_reference(vm_page_t m)
6211 pmap_clearbit(m, PG_A_IDX);
6215 * Miscellaneous support routines follow
6220 x86_64_protection_init(void)
6226 * NX supported? (boot time loader.conf override only)
6228 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
6229 if (pmap_nx_enable == 0 || (amd_feature & AMDID_NX) == 0)
6230 pmap_bits_default[PG_NX_IDX] = 0;
6233 * 0 is basically read-only access, but also set the NX (no-execute)
6234 * bit when VM_PROT_EXECUTE is not specified.
6236 kp = protection_codes;
6237 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
6239 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
6241 * This case handled elsewhere
6245 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
6249 *kp++ = pmap_bits_default[PG_NX_IDX];
6251 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6252 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6254 * Execute requires read access
6258 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6259 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6261 * Write without execute is RW|NX
6263 *kp++ = pmap_bits_default[PG_RW_IDX] |
6264 pmap_bits_default[PG_NX_IDX];
6266 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6267 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6269 * Write with execute is RW
6271 *kp++ = pmap_bits_default[PG_RW_IDX];
6278 * Map a set of physical memory pages into the kernel virtual
6279 * address space. Return a pointer to where it is mapped. This
6280 * routine is intended to be used for mapping device memory,
6283 * NOTE: We can't use pgeflag unless we invalidate the pages one at
6286 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6287 * work whether the cpu supports PAT or not. The remaining PAT
6288 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6292 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6294 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6298 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6300 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6304 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6306 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6310 * Map a set of physical memory pages into the kernel virtual
6311 * address space. Return a pointer to where it is mapped. This
6312 * routine is intended to be used for mapping device memory,
6316 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6318 vm_offset_t va, tmpva, offset;
6322 offset = pa & PAGE_MASK;
6323 size = roundup(offset + size, PAGE_SIZE);
6325 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6327 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6329 pa = pa & ~PAGE_MASK;
6330 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6331 pte = vtopte(tmpva);
6333 kernel_pmap.pmap_bits[PG_RW_IDX] |
6334 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
6335 kernel_pmap.pmap_cache_bits[mode];
6336 tmpsize -= PAGE_SIZE;
6340 pmap_invalidate_range(&kernel_pmap, va, va + size);
6341 pmap_invalidate_cache_range(va, va + size);
6343 return ((void *)(va + offset));
6347 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6349 vm_offset_t base, offset;
6351 base = va & ~PAGE_MASK;
6352 offset = va & PAGE_MASK;
6353 size = roundup(offset + size, PAGE_SIZE);
6354 pmap_qremove(va, size >> PAGE_SHIFT);
6355 kmem_free(&kernel_map, base, size);
6359 * Sets the memory attribute for the specified page.
6362 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6368 * If "m" is a normal page, update its direct mapping. This update
6369 * can be relied upon to perform any cache operations that are
6370 * required for data coherence.
6372 if ((m->flags & PG_FICTITIOUS) == 0)
6373 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6377 * Change the PAT attribute on an existing kernel memory map. Caller
6378 * must ensure that the virtual memory in question is not accessed
6379 * during the adjustment.
6382 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6389 panic("pmap_change_attr: va is NULL");
6390 base = trunc_page(va);
6394 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
6395 kernel_pmap.pmap_cache_bits[mode];
6400 changed = 1; /* XXX: not optimal */
6403 * Flush CPU caches if required to make sure any data isn't cached that
6404 * shouldn't be, etc.
6407 pmap_invalidate_range(&kernel_pmap, base, va);
6408 pmap_invalidate_cache_range(base, va);
6413 * perform the pmap work for mincore
6416 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6418 pt_entry_t *ptep, pte;
6422 ptep = pmap_pte(pmap, addr);
6424 if (ptep && (pte = *ptep) != 0) {
6427 val = MINCORE_INCORE;
6428 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
6431 pa = pte & PG_FRAME;
6433 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
6436 m = PHYS_TO_VM_PAGE(pa);
6441 if (pte & pmap->pmap_bits[PG_M_IDX])
6442 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6444 * Modified by someone
6446 else if (m && (m->dirty || pmap_is_modified(m)))
6447 val |= MINCORE_MODIFIED_OTHER;
6451 if (pte & pmap->pmap_bits[PG_A_IDX])
6452 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6455 * Referenced by someone
6457 else if (m && ((m->flags & PG_REFERENCED) ||
6458 pmap_ts_referenced(m))) {
6459 val |= MINCORE_REFERENCED_OTHER;
6460 vm_page_flag_set(m, PG_REFERENCED);
6469 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
6470 * vmspace will be ref'd and the old one will be deref'd.
6472 * The vmspace for all lwps associated with the process will be adjusted
6473 * and cr3 will be reloaded if any lwp is the current lwp.
6475 * The process must hold the vmspace->vm_map.token for oldvm and newvm
6478 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6480 struct vmspace *oldvm;
6483 oldvm = p->p_vmspace;
6484 if (oldvm != newvm) {
6487 p->p_vmspace = newvm;
6488 KKASSERT(p->p_nthreads == 1);
6489 lp = RB_ROOT(&p->p_lwp_tree);
6490 pmap_setlwpvm(lp, newvm);
6497 * Set the vmspace for a LWP. The vmspace is almost universally set the
6498 * same as the process vmspace, but virtual kernels need to swap out contexts
6499 * on a per-lwp basis.
6501 * Caller does not necessarily hold any vmspace tokens. Caller must control
6502 * the lwp (typically be in the context of the lwp). We use a critical
6503 * section to protect against statclock and hardclock (statistics collection).
6506 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6508 struct vmspace *oldvm;
6512 oldvm = lp->lwp_vmspace;
6514 if (oldvm != newvm) {
6517 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6518 lp->lwp_vmspace = newvm;
6519 if (td->td_lwp == lp) {
6520 pmap = vmspace_pmap(newvm);
6521 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6522 if (pmap->pm_active_lock & CPULOCK_EXCL)
6523 pmap_interlock_wait(newvm);
6524 #if defined(SWTCH_OPTIM_STATS)
6527 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6528 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6529 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6530 td->td_pcb->pcb_cr3_iso =
6531 vtophys(pmap->pm_pml4_iso);
6532 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6534 td->td_pcb->pcb_cr3_iso = 0;
6535 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6537 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6538 td->td_pcb->pcb_cr3 = KPML4phys;
6539 td->td_pcb->pcb_cr3_iso = 0;
6540 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6542 panic("pmap_setlwpvm: unknown pmap type\n");
6546 * The MMU separation fields needs to be updated.
6547 * (it can't access the pcb directly from the
6548 * restricted user pmap).
6551 struct trampframe *tramp;
6553 tramp = &pscpu->trampoline;
6554 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6555 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6556 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6557 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6558 /* tr_pcb_rsp doesn't change */
6562 * In kernel-land we always use the normal PML4E
6563 * so the kernel is fully mapped and can also access
6566 load_cr3(td->td_pcb->pcb_cr3);
6567 pmap = vmspace_pmap(oldvm);
6568 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6576 * Called when switching to a locked pmap, used to interlock against pmaps
6577 * undergoing modifications to prevent us from activating the MMU for the
6578 * target pmap until all such modifications have completed. We have to do
6579 * this because the thread making the modifications has already set up its
6580 * SMP synchronization mask.
6582 * This function cannot sleep!
6587 pmap_interlock_wait(struct vmspace *vm)
6589 struct pmap *pmap = &vm->vm_pmap;
6591 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6593 KKASSERT(curthread->td_critcount >= 2);
6594 DEBUG_PUSH_INFO("pmap_interlock_wait");
6595 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6597 lwkt_process_ipiq();
6605 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6608 if ((obj == NULL) || (size < NBPDR) ||
6609 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6613 addr = roundup2(addr, NBPDR);
6618 * Used by kmalloc/kfree, page already exists at va
6621 pmap_kvtom(vm_offset_t va)
6623 pt_entry_t *ptep = vtopte(va);
6625 KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
6626 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6630 * Initialize machine-specific shared page directory support. This
6631 * is executed when a VM object is created.
6634 pmap_object_init(vm_object_t object)
6636 object->md.pmap_rw = NULL;
6637 object->md.pmap_ro = NULL;
6641 * Clean up machine-specific shared page directory support. This
6642 * is executed when a VM object is destroyed.
6645 pmap_object_free(vm_object_t object)
6649 if ((pmap = object->md.pmap_rw) != NULL) {
6650 object->md.pmap_rw = NULL;
6651 pmap_remove_noinval(pmap,
6652 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6653 CPUMASK_ASSZERO(pmap->pm_active);
6656 kfree(pmap, M_OBJPMAP);
6658 if ((pmap = object->md.pmap_ro) != NULL) {
6659 object->md.pmap_ro = NULL;
6660 pmap_remove_noinval(pmap,
6661 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6662 CPUMASK_ASSZERO(pmap->pm_active);
6665 kfree(pmap, M_OBJPMAP);
6670 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6671 * VM page and issue a pginfo->callback.
6673 * We are expected to dispose of any non-NULL pte_pv.
6677 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6678 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
6679 pv_entry_t pt_pv, int sharept,
6680 vm_offset_t va, pt_entry_t *ptep, void *arg)
6682 struct pmap_pgscan_info *pginfo = arg;
6687 * Try to busy the page while we hold the pte_pv locked.
6689 KKASSERT(pte_pv->pv_m);
6690 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6691 if (vm_page_busy_try(m, TRUE) == 0) {
6692 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6694 * The callback is issued with the pte_pv
6695 * unlocked and put away, and the pt_pv
6700 vm_page_wire_quick(pt_pv->pv_m);
6703 if (pginfo->callback(pginfo, va, m) < 0)
6707 vm_page_unwire_quick(pt_pv->pv_m);
6714 ++pginfo->busycount;
6719 * Shared page table or unmanaged page (sharept or !sharept)
6721 pv_placemarker_wakeup(pmap, pte_placemark);
6726 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6728 struct pmap_scan_info info;
6730 pginfo->offset = pginfo->beg_addr;
6731 info.pmap = pginfo->pmap;
6732 info.sva = pginfo->beg_addr;
6733 info.eva = pginfo->end_addr;
6734 info.func = pmap_pgscan_callback;
6736 pmap_scan(&info, 0);
6738 pginfo->offset = pginfo->end_addr;
6742 * Wait for a placemarker that we do not own to clear. The placemarker
6743 * in question is not necessarily set to the pindex we want, we may have
6744 * to wait on the element because we want to reserve it ourselves.
6746 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6747 * PM_NOPLACEMARK, so it does not interfere with placemarks
6748 * which have already been woken up.
6752 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6754 if (*pmark != PM_NOPLACEMARK) {
6755 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
6756 tsleep_interlock(pmark, 0);
6757 if (*pmark != PM_NOPLACEMARK)
6758 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6763 * Wakeup a placemarker that we own. Replace the entry with
6764 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6768 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6772 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6773 KKASSERT(pindex != PM_NOPLACEMARK);
6774 if (pindex & PM_PLACEMARK_WAKEUP)