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>
81 #include <sys/thread2.h>
82 #include <sys/spinlock2.h>
83 #include <vm/vm_page2.h>
85 #include <machine/cputypes.h>
86 #include <machine/cpu.h>
87 #include <machine/md_var.h>
88 #include <machine/specialreg.h>
89 #include <machine/smp.h>
90 #include <machine_base/apic/apicreg.h>
91 #include <machine/globaldata.h>
92 #include <machine/pmap.h>
93 #include <machine/pmap_inval.h>
94 #include <machine/inttypes.h>
98 #define PMAP_KEEP_PDIRS
99 #ifndef PMAP_SHPGPERPROC
100 #define PMAP_SHPGPERPROC 2000
103 #if defined(DIAGNOSTIC)
104 #define PMAP_DIAGNOSTIC
110 * pmap debugging will report who owns a pv lock when blocking.
114 #define PMAP_DEBUG_DECL ,const char *func, int lineno
115 #define PMAP_DEBUG_ARGS , __func__, __LINE__
116 #define PMAP_DEBUG_COPY , func, lineno
118 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp \
120 #define pv_lock(pv) _pv_lock(pv \
122 #define pv_hold_try(pv) _pv_hold_try(pv \
124 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp \
127 #define pv_free(pv, pvp) _pv_free(pv, pvp PMAP_DEBUG_ARGS)
131 #define PMAP_DEBUG_DECL
132 #define PMAP_DEBUG_ARGS
133 #define PMAP_DEBUG_COPY
135 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp)
136 #define pv_lock(pv) _pv_lock(pv)
137 #define pv_hold_try(pv) _pv_hold_try(pv)
138 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp)
139 #define pv_free(pv, pvp) _pv_free(pv, pvp)
144 * Get PDEs and PTEs for user/kernel address space
146 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
148 #define pmap_pde_v(pmap, pte) ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
149 #define pmap_pte_w(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
150 #define pmap_pte_m(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
151 #define pmap_pte_u(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
152 #define pmap_pte_v(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
155 * Given a map and a machine independent protection code,
156 * convert to a vax protection code.
158 #define pte_prot(m, p) \
159 (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
160 static uint64_t protection_codes[PROTECTION_CODES_SIZE];
162 struct pmap kernel_pmap;
163 struct pmap iso_pmap;
165 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
167 vm_paddr_t avail_start; /* PA of first available physical page */
168 vm_paddr_t avail_end; /* PA of last available physical page */
169 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
170 vm_offset_t virtual2_end;
171 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
172 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
173 vm_offset_t KvaStart; /* VA start of KVA space */
174 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
175 vm_offset_t KvaSize; /* max size of kernel virtual address space */
176 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
177 //static int pgeflag; /* PG_G or-in */
181 static vm_paddr_t dmaplimit;
182 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
184 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
185 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
187 static uint64_t KPTbase;
188 static uint64_t KPTphys;
189 static uint64_t KPDphys; /* phys addr of kernel level 2 */
190 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
191 uint64_t KPDPphys; /* phys addr of kernel level 3 */
192 uint64_t KPML4phys; /* phys addr of kernel level 4 */
194 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
195 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
198 * Data for the pv entry allocation mechanism
200 static vm_zone_t pvzone;
201 static struct vm_zone pvzone_store;
202 static vm_pindex_t pv_entry_max=0, pv_entry_high_water=0;
203 static int pmap_pagedaemon_waken = 0;
204 static struct pv_entry *pvinit;
207 * All those kernel PT submaps that BSD is so fond of
209 pt_entry_t *CMAP1 = NULL, *ptmmap;
210 caddr_t CADDR1 = NULL, ptvmmap = NULL;
211 static pt_entry_t *msgbufmap;
212 struct msgbuf *msgbufp=NULL;
215 * PMAP default PG_* bits. Needed to be able to add
216 * EPT/NPT pagetable pmap_bits for the VMM module
218 uint64_t pmap_bits_default[] = {
219 REGULAR_PMAP, /* TYPE_IDX 0 */
220 X86_PG_V, /* PG_V_IDX 1 */
221 X86_PG_RW, /* PG_RW_IDX 2 */
222 X86_PG_U, /* PG_U_IDX 3 */
223 X86_PG_A, /* PG_A_IDX 4 */
224 X86_PG_M, /* PG_M_IDX 5 */
225 X86_PG_PS, /* PG_PS_IDX3 6 */
226 X86_PG_G, /* PG_G_IDX 7 */
227 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
228 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
229 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
230 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
231 X86_PG_NX, /* PG_NX_IDX 12 */
236 static pt_entry_t *pt_crashdumpmap;
237 static caddr_t crashdumpmap;
239 static int pmap_debug = 0;
240 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
241 &pmap_debug, 0, "Debug pmap's");
243 static int pmap_enter_debug = 0;
244 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
245 &pmap_enter_debug, 0, "Debug pmap_enter's");
247 static int pmap_yield_count = 64;
248 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
249 &pmap_yield_count, 0, "Yield during init_pt/release");
250 static int pmap_mmu_optimize = 0;
251 SYSCTL_INT(_machdep, OID_AUTO, pmap_mmu_optimize, CTLFLAG_RW,
252 &pmap_mmu_optimize, 0, "Share page table pages when possible");
253 int pmap_fast_kernel_cpusync = 0;
254 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
255 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
256 int pmap_dynamic_delete = 0;
257 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
258 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
259 int pmap_lock_delay = 100;
260 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
261 &pmap_lock_delay, 0, "Spin loops");
262 static int meltdown_mitigation = -1;
263 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
264 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
265 &meltdown_mitigation, 0, "Userland pmap isolation");
267 static int pmap_nx_enable = -1; /* -1 = auto */
268 /* needs manual TUNABLE in early probe, see below */
269 SYSCTL_INT(_machdep, OID_AUTO, pmap_nx_enable, CTLFLAG_RD,
271 "no-execute support (0=disabled, 1=w/READ, 2=w/READ & WRITE)");
273 static int pmap_pv_debug = 50;
274 SYSCTL_INT(_machdep, OID_AUTO, pmap_pv_debug, CTLFLAG_RW,
275 &pmap_pv_debug, 0, "");
277 /* Standard user access funtions */
278 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
280 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
281 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
282 extern int std_fubyte (const uint8_t *base);
283 extern int std_subyte (uint8_t *base, uint8_t byte);
284 extern int32_t std_fuword32 (const uint32_t *base);
285 extern int64_t std_fuword64 (const uint64_t *base);
286 extern int std_suword64 (uint64_t *base, uint64_t word);
287 extern int std_suword32 (uint32_t *base, int word);
288 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
289 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
290 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
291 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
293 static void pv_hold(pv_entry_t pv);
294 static int _pv_hold_try(pv_entry_t pv
296 static void pv_drop(pv_entry_t pv);
297 static void _pv_lock(pv_entry_t pv
299 static void pv_unlock(pv_entry_t pv);
300 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
302 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
304 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
305 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
306 vm_pindex_t **pmarkp, int *errorp);
307 static void pv_put(pv_entry_t pv);
308 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
309 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
311 static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
312 pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
313 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
314 pmap_inval_bulk_t *bulk, int destroy);
315 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
316 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
317 pmap_inval_bulk_t *bulk);
319 struct pmap_scan_info;
320 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
321 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
322 pv_entry_t pt_pv, int sharept,
323 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
324 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
325 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
326 pv_entry_t pt_pv, int sharept,
327 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
329 static void x86_64_protection_init (void);
330 static void create_pagetables(vm_paddr_t *firstaddr);
331 static void pmap_remove_all (vm_page_t m);
332 static boolean_t pmap_testbit (vm_page_t m, int bit);
334 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
335 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
337 static void pmap_pinit_defaults(struct pmap *pmap);
338 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
339 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
342 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
344 if (pv1->pv_pindex < pv2->pv_pindex)
346 if (pv1->pv_pindex > pv2->pv_pindex)
351 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
352 pv_entry_compare, vm_pindex_t, pv_pindex);
356 pmap_page_stats_adding(vm_page_t m)
358 globaldata_t gd = mycpu;
360 if (TAILQ_EMPTY(&m->md.pv_list)) {
361 ++gd->gd_vmtotal.t_arm;
362 } else if (TAILQ_FIRST(&m->md.pv_list) ==
363 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
364 ++gd->gd_vmtotal.t_armshr;
365 ++gd->gd_vmtotal.t_avmshr;
367 ++gd->gd_vmtotal.t_avmshr;
373 pmap_page_stats_deleting(vm_page_t m)
375 globaldata_t gd = mycpu;
377 if (TAILQ_EMPTY(&m->md.pv_list)) {
378 --gd->gd_vmtotal.t_arm;
379 } else if (TAILQ_FIRST(&m->md.pv_list) ==
380 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
381 --gd->gd_vmtotal.t_armshr;
382 --gd->gd_vmtotal.t_avmshr;
384 --gd->gd_vmtotal.t_avmshr;
389 * This is an ineligent crowbar to prevent heavily threaded programs
390 * from creating long live-locks in the pmap code when pmap_mmu_optimize
391 * is enabled. Without it a pmap-local page table page can wind up being
392 * constantly created and destroyed (without injury, but also without
393 * progress) as the optimization tries to switch to the object's shared page
397 pmap_softwait(pmap_t pmap)
399 while (pmap->pm_softhold) {
400 tsleep_interlock(&pmap->pm_softhold, 0);
401 if (pmap->pm_softhold)
402 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
407 pmap_softhold(pmap_t pmap)
409 while (atomic_swap_int(&pmap->pm_softhold, 1) == 1) {
410 tsleep_interlock(&pmap->pm_softhold, 0);
411 if (atomic_swap_int(&pmap->pm_softhold, 1) == 1)
412 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
417 pmap_softdone(pmap_t pmap)
419 atomic_swap_int(&pmap->pm_softhold, 0);
420 wakeup(&pmap->pm_softhold);
424 * Move the kernel virtual free pointer to the next
425 * 2MB. This is used to help improve performance
426 * by using a large (2MB) page for much of the kernel
427 * (.text, .data, .bss)
431 pmap_kmem_choose(vm_offset_t addr)
433 vm_offset_t newaddr = addr;
435 newaddr = roundup2(addr, NBPDR);
440 * Returns the pindex of a page table entry (representing a terminal page).
441 * There are NUPTE_TOTAL page table entries possible (a huge number)
443 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
444 * We want to properly translate negative KVAs.
448 pmap_pte_pindex(vm_offset_t va)
450 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
454 * Returns the pindex of a page table.
458 pmap_pt_pindex(vm_offset_t va)
460 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
464 * Returns the pindex of a page directory.
468 pmap_pd_pindex(vm_offset_t va)
470 return (NUPTE_TOTAL + NUPT_TOTAL +
471 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
476 pmap_pdp_pindex(vm_offset_t va)
478 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
479 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
484 pmap_pml4_pindex(void)
486 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
490 * Return various clipped indexes for a given VA
492 * Returns the index of a pt in a page directory, representing a page
497 pmap_pt_index(vm_offset_t va)
499 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
503 * Returns the index of a pd in a page directory page, representing a page
508 pmap_pd_index(vm_offset_t va)
510 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
514 * Returns the index of a pdp in the pml4 table, representing a page
519 pmap_pdp_index(vm_offset_t va)
521 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
525 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
526 * the PT layer. This will speed up core pmap operations considerably.
527 * We also cache the PTE layer to (hopefully) improve relative lookup
530 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
531 * must be in a known associated state (typically by being locked when
532 * the pmap spinlock isn't held). We allow the race for that case.
534 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
535 * cpu_ccfence() to prevent compiler optimizations from reloading the
540 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
542 if (pindex < pmap_pt_pindex(0)) {
543 pmap->pm_pvhint_pte = pv;
544 } else if (pindex < pmap_pd_pindex(0)) {
545 pmap->pm_pvhint_pt = pv;
550 * Locate the requested pt_entry
554 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
559 if (pindex < pmap_pt_pindex(0))
560 pv = pmap->pm_pvhint_pte;
561 else if (pindex < pmap_pd_pindex(0))
562 pv = pmap->pm_pvhint_pt;
566 if (pv == NULL || pv->pv_pmap != pmap) {
567 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
569 pv_cache(pmap, pv, pindex);
570 } else if (pv->pv_pindex != pindex) {
571 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
574 pv_cache(pmap, pv, pindex);
577 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
585 * Super fast pmap_pte routine best used when scanning the pv lists.
586 * This eliminates many course-grained invltlb calls. Note that many of
587 * the pv list scans are across different pmaps and it is very wasteful
588 * to do an entire invltlb when checking a single mapping.
590 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
594 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
596 return pmap_pte(pmap, va);
600 * The placemarker hash must be broken up into four zones so lock
601 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
603 * Placemarkers are used to 'lock' page table indices that do not have
604 * a pv_entry. This allows the pmap to support managed and unmanaged
605 * pages and shared page tables.
607 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
611 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
615 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
617 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
619 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
620 hi = PM_PLACE_BASE << 1;
621 else /* zone 3 - PDP (and PML4E) */
622 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
623 hi += pindex & (PM_PLACE_BASE - 1);
625 return (&pmap->pm_placemarks[hi]);
630 * Generic procedure to index a pte from a pt, pd, or pdp.
632 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
633 * a page table page index but is instead of PV lookup index.
637 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
641 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
642 return(&pte[pindex]);
646 * Return pointer to PDP slot in the PML4
650 pmap_pdp(pmap_t pmap, vm_offset_t va)
652 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
656 * Return pointer to PD slot in the PDP given a pointer to the PDP
660 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
664 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
665 return (&pd[pmap_pd_index(va)]);
669 * Return pointer to PD slot in the PDP.
673 pmap_pd(pmap_t pmap, vm_offset_t va)
677 pdp = pmap_pdp(pmap, va);
678 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
680 return (pmap_pdp_to_pd(*pdp, va));
684 * Return pointer to PT slot in the PD given a pointer to the PD
688 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
692 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
693 return (&pt[pmap_pt_index(va)]);
697 * Return pointer to PT slot in the PD
699 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
700 * so we cannot lookup the PD via the PDP. Instead we
701 * must look it up via the pmap.
705 pmap_pt(pmap_t pmap, vm_offset_t va)
709 vm_pindex_t pd_pindex;
712 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
713 pd_pindex = pmap_pd_pindex(va);
714 spin_lock_shared(&pmap->pm_spin);
715 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
716 if (pv == NULL || pv->pv_m == NULL) {
717 spin_unlock_shared(&pmap->pm_spin);
720 phys = VM_PAGE_TO_PHYS(pv->pv_m);
721 spin_unlock_shared(&pmap->pm_spin);
722 return (pmap_pd_to_pt(phys, va));
724 pd = pmap_pd(pmap, va);
725 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
727 return (pmap_pd_to_pt(*pd, va));
732 * Return pointer to PTE slot in the PT given a pointer to the PT
736 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
740 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
741 return (&pte[pmap_pte_index(va)]);
745 * Return pointer to PTE slot in the PT
749 pmap_pte(pmap_t pmap, vm_offset_t va)
753 pt = pmap_pt(pmap, va);
754 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
756 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
757 return ((pt_entry_t *)pt);
758 return (pmap_pt_to_pte(*pt, va));
762 * Return address of PT slot in PD (KVM only)
764 * Cannot be used for user page tables because it might interfere with
765 * the shared page-table-page optimization (pmap_mmu_optimize).
769 vtopt(vm_offset_t va)
771 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
772 NPML4EPGSHIFT)) - 1);
774 return (PDmap + ((va >> PDRSHIFT) & mask));
778 * KVM - return address of PTE slot in PT
782 vtopte(vm_offset_t va)
784 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
785 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
787 return (PTmap + ((va >> PAGE_SHIFT) & mask));
791 * Returns the physical address translation from va for a user address.
792 * (vm_paddr_t)-1 is returned on failure.
795 uservtophys(vm_offset_t va)
797 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
798 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
803 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
805 if (va < VM_MAX_USER_ADDRESS) {
806 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
807 if (pte & pmap->pmap_bits[PG_V_IDX])
808 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
814 allocpages(vm_paddr_t *firstaddr, long n)
819 bzero((void *)ret, n * PAGE_SIZE);
820 *firstaddr += n * PAGE_SIZE;
826 create_pagetables(vm_paddr_t *firstaddr)
828 long i; /* must be 64 bits */
835 * We are running (mostly) V=P at this point
837 * Calculate how many 1GB PD entries in our PDP pages are needed
838 * for the DMAP. This is only allocated if the system does not
839 * support 1GB pages. Otherwise ndmpdp is simply a count of
840 * the number of 1G terminal entries in our PDP pages are needed.
842 * NOTE: Maxmem is in pages
844 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
845 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
847 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
850 * Starting at KERNBASE - map all 2G worth of page table pages.
851 * KERNBASE is offset -2G from the end of kvm. This will accomodate
852 * all KVM allocations above KERNBASE, including the SYSMAPs below.
854 * We do this by allocating 2*512 PT pages. Each PT page can map
855 * 2MB, for 2GB total.
857 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
860 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
861 * Calculate how many page table pages we need to preallocate
862 * for early vm_map allocations.
864 * A few extra won't hurt, they will get used up in the running
870 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
871 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
872 nkpt_phys += 128; /* a few extra */
875 * The highest value nkpd_phys can be set to is
876 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
878 * Doing so would cause all PD pages to be pre-populated for
879 * a maximal KVM space (approximately 16*512 pages, or 32MB.
880 * We can save memory by not doing this.
882 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
887 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
888 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
890 * Only allocate enough PD pages
891 * NOTE: We allocate all kernel PD pages up-front, typically
892 * ~511G of KVM, requiring 511 PD pages.
894 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
895 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
896 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
897 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
898 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
901 * Alloc PD pages for the area starting at KERNBASE.
903 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
908 DMPDPphys = allocpages(firstaddr, NDMPML4E);
909 if ((amd_feature & AMDID_PAGE1GB) == 0)
910 DMPDphys = allocpages(firstaddr, ndmpdp);
911 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
914 * Fill in the underlying page table pages for the area around
915 * KERNBASE. This remaps low physical memory to KERNBASE.
917 * Read-only from zero to physfree
918 * XXX not fully used, underneath 2M pages
920 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
921 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
922 ((pt_entry_t *)KPTbase)[i] |=
923 pmap_bits_default[PG_RW_IDX] |
924 pmap_bits_default[PG_V_IDX] |
925 pmap_bits_default[PG_G_IDX];
929 * Now map the initial kernel page tables. One block of page
930 * tables is placed at the beginning of kernel virtual memory,
931 * and another block is placed at KERNBASE to map the kernel binary,
932 * data, bss, and initial pre-allocations.
934 for (i = 0; i < nkpt_base; i++) {
935 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
936 ((pd_entry_t *)KPDbase)[i] |=
937 pmap_bits_default[PG_RW_IDX] |
938 pmap_bits_default[PG_V_IDX];
940 for (i = 0; i < nkpt_phys; i++) {
941 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
942 ((pd_entry_t *)KPDphys)[i] |=
943 pmap_bits_default[PG_RW_IDX] |
944 pmap_bits_default[PG_V_IDX];
948 * Map from zero to end of allocations using 2M pages as an
949 * optimization. This will bypass some of the KPTBase pages
950 * above in the KERNBASE area.
952 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
953 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
954 ((pd_entry_t *)KPDbase)[i] |=
955 pmap_bits_default[PG_RW_IDX] |
956 pmap_bits_default[PG_V_IDX] |
957 pmap_bits_default[PG_PS_IDX] |
958 pmap_bits_default[PG_G_IDX];
962 * Load PD addresses into the PDP pages for primary KVA space to
963 * cover existing page tables. PD's for KERNBASE are handled in
966 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
968 for (i = 0; i < nkpd_phys; i++) {
969 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
970 KPDphys + (i << PAGE_SHIFT);
971 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
972 pmap_bits_default[PG_RW_IDX] |
973 pmap_bits_default[PG_V_IDX] |
974 pmap_bits_default[PG_A_IDX];
978 * Load PDs for KERNBASE to the end
980 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
981 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
982 ((pdp_entry_t *)KPDPphys)[i + j] =
983 KPDbase + (j << PAGE_SHIFT);
984 ((pdp_entry_t *)KPDPphys)[i + j] |=
985 pmap_bits_default[PG_RW_IDX] |
986 pmap_bits_default[PG_V_IDX] |
987 pmap_bits_default[PG_A_IDX];
991 * Now set up the direct map space using either 2MB or 1GB pages
992 * Preset PG_M and PG_A because demotion expects it.
994 * When filling in entries in the PD pages make sure any excess
995 * entries are set to zero as we allocated enough PD pages
997 if ((amd_feature & AMDID_PAGE1GB) == 0) {
1001 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1002 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1003 ((pd_entry_t *)DMPDphys)[i] |=
1004 pmap_bits_default[PG_RW_IDX] |
1005 pmap_bits_default[PG_V_IDX] |
1006 pmap_bits_default[PG_PS_IDX] |
1007 pmap_bits_default[PG_G_IDX] |
1008 pmap_bits_default[PG_M_IDX] |
1009 pmap_bits_default[PG_A_IDX];
1013 * And the direct map space's PDP
1015 for (i = 0; i < ndmpdp; i++) {
1016 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1018 ((pdp_entry_t *)DMPDPphys)[i] |=
1019 pmap_bits_default[PG_RW_IDX] |
1020 pmap_bits_default[PG_V_IDX];
1026 for (i = 0; i < ndmpdp; i++) {
1027 ((pdp_entry_t *)DMPDPphys)[i] =
1028 (vm_paddr_t)i << PDPSHIFT;
1029 ((pdp_entry_t *)DMPDPphys)[i] |=
1030 pmap_bits_default[PG_RW_IDX] |
1031 pmap_bits_default[PG_V_IDX] |
1032 pmap_bits_default[PG_PS_IDX] |
1033 pmap_bits_default[PG_G_IDX] |
1034 pmap_bits_default[PG_M_IDX] |
1035 pmap_bits_default[PG_A_IDX];
1039 /* And recursively map PML4 to itself in order to get PTmap */
1040 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1041 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1042 pmap_bits_default[PG_RW_IDX] |
1043 pmap_bits_default[PG_V_IDX] |
1044 pmap_bits_default[PG_A_IDX];
1047 * Connect the Direct Map slots up to the PML4
1049 for (j = 0; j < NDMPML4E; ++j) {
1050 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1051 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1052 pmap_bits_default[PG_RW_IDX] |
1053 pmap_bits_default[PG_V_IDX] |
1054 pmap_bits_default[PG_A_IDX];
1058 * Connect the KVA slot up to the PML4
1060 for (j = 0; j < NKPML4E; ++j) {
1061 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1062 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1063 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1064 pmap_bits_default[PG_RW_IDX] |
1065 pmap_bits_default[PG_V_IDX] |
1066 pmap_bits_default[PG_A_IDX];
1073 * Bootstrap the system enough to run with virtual memory.
1075 * On x86_64 this is called after mapping has already been enabled
1076 * and just syncs the pmap module with what has already been done.
1077 * [We can't call it easily with mapping off since the kernel is not
1078 * mapped with PA == VA, hence we would have to relocate every address
1079 * from the linked base (virtual) address "KERNBASE" to the actual
1080 * (physical) address starting relative to 0]
1083 pmap_bootstrap(vm_paddr_t *firstaddr)
1089 KvaStart = VM_MIN_KERNEL_ADDRESS;
1090 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1091 KvaSize = KvaEnd - KvaStart;
1093 avail_start = *firstaddr;
1096 * Create an initial set of page tables to run the kernel in.
1098 create_pagetables(firstaddr);
1100 virtual2_start = KvaStart;
1101 virtual2_end = PTOV_OFFSET;
1103 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1104 virtual_start = pmap_kmem_choose(virtual_start);
1106 virtual_end = VM_MAX_KERNEL_ADDRESS;
1108 /* XXX do %cr0 as well */
1109 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1110 load_cr3(KPML4phys);
1113 * Initialize protection array.
1115 x86_64_protection_init();
1118 * The kernel's pmap is statically allocated so we don't have to use
1119 * pmap_create, which is unlikely to work correctly at this part of
1120 * the boot sequence (XXX and which no longer exists).
1122 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1123 kernel_pmap.pm_count = 1;
1124 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1125 RB_INIT(&kernel_pmap.pm_pvroot);
1126 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1127 for (i = 0; i < PM_PLACEMARKS; ++i)
1128 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1131 * Reserve some special page table entries/VA space for temporary
1134 #define SYSMAP(c, p, v, n) \
1135 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1141 * CMAP1/CMAP2 are used for zeroing and copying pages.
1143 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1148 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1151 * ptvmmap is used for reading arbitrary physical pages via
1154 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1157 * msgbufp is used to map the system message buffer.
1158 * XXX msgbufmap is not used.
1160 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1161 atop(round_page(MSGBUF_SIZE)))
1164 virtual_start = pmap_kmem_choose(virtual_start);
1169 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1170 * cases rather then invl1pg. Actually, I don't even know why it
1171 * works under UP because self-referential page table mappings
1177 /* Initialize the PAT MSR */
1179 pmap_pinit_defaults(&kernel_pmap);
1181 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1182 &pmap_fast_kernel_cpusync);
1187 * Setup the PAT MSR.
1196 * Default values mapping PATi,PCD,PWT bits at system reset.
1197 * The default values effectively ignore the PATi bit by
1198 * repeating the encodings for 0-3 in 4-7, and map the PCD
1199 * and PWT bit combinations to the expected PAT types.
1201 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1202 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1203 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1204 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1205 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1206 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1207 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1208 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1209 pat_pte_index[PAT_WRITE_BACK] = 0;
1210 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1211 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1212 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1213 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1214 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1216 if (cpu_feature & CPUID_PAT) {
1218 * If we support the PAT then set-up entries for
1219 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1222 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1223 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1224 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1225 PAT_VALUE(6, PAT_WRITE_COMBINING);
1226 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1227 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1230 * Then enable the PAT
1235 load_cr4(cr4 & ~CR4_PGE);
1237 /* Disable caches (CD = 1, NW = 0). */
1239 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1241 /* Flushes caches and TLBs. */
1245 /* Update PAT and index table. */
1246 wrmsr(MSR_PAT, pat_msr);
1248 /* Flush caches and TLBs again. */
1252 /* Restore caches and PGE. */
1260 * Set 4mb pdir for mp startup
1265 if (cpu_feature & CPUID_PSE) {
1266 load_cr4(rcr4() | CR4_PSE);
1267 if (mycpu->gd_cpuid == 0) /* only on BSP */
1272 * Check for SMAP support and enable if available. Must be done
1273 * after cr3 is loaded, and on all cores.
1275 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1276 load_cr4(rcr4() | CR4_SMAP);
1278 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1279 load_cr4(rcr4() | CR4_SMEP);
1284 * Early initialization of the pmap module.
1286 * Called by vm_init, to initialize any structures that the pmap
1287 * system needs to map virtual memory. pmap_init has been enhanced to
1288 * support in a fairly consistant way, discontiguous physical memory.
1293 vm_pindex_t initial_pvs;
1297 * Allocate memory for random pmap data structures. Includes the
1300 for (i = 0; i < vm_page_array_size; i++) {
1303 m = &vm_page_array[i];
1304 TAILQ_INIT(&m->md.pv_list);
1308 * init the pv free list
1310 initial_pvs = vm_page_array_size;
1311 if (initial_pvs < MINPV)
1312 initial_pvs = MINPV;
1313 pvzone = &pvzone_store;
1314 pvinit = (void *)kmem_alloc(&kernel_map,
1315 initial_pvs * sizeof (struct pv_entry),
1317 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1318 pvinit, initial_pvs);
1321 * Now it is safe to enable pv_table recording.
1323 pmap_initialized = TRUE;
1327 * Initialize the address space (zone) for the pv_entries. Set a
1328 * high water mark so that the system can recover from excessive
1329 * numbers of pv entries.
1331 * Also create the kernel page table template for isolated user
1334 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1335 static void pmap_init2_iso_pmap(void);
1337 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1343 vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
1344 vm_pindex_t entry_max;
1346 TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1347 pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1348 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1349 pv_entry_high_water = 9 * (pv_entry_max / 10);
1352 * Subtract out pages already installed in the zone (hack)
1354 entry_max = pv_entry_max - vm_page_array_size;
1358 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1361 * Enable dynamic deletion of empty higher-level page table pages
1362 * by default only if system memory is < 8GB (use 7GB for slop).
1363 * This can save a little memory, but imposes significant
1364 * performance overhead for things like bulk builds, and for programs
1365 * which do a lot of memory mapping and memory unmapping.
1367 if (pmap_dynamic_delete < 0) {
1368 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1369 pmap_dynamic_delete = 1;
1371 pmap_dynamic_delete = 0;
1375 * Automatic detection of Intel meltdown bug requiring user/kernel
1378 * Currently there are so many Intel cpu's impacted that its better
1379 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1380 * so the default is off for AMD.
1382 if (meltdown_mitigation < 0) {
1383 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1384 meltdown_mitigation = 1;
1386 meltdown_mitigation = 0;
1388 if (meltdown_mitigation) {
1389 kprintf("machdep.meltdown_mitigation enabled to "
1390 "protect against (mostly Intel) meltdown bug\n");
1391 kprintf("system call performance will be impacted\n");
1394 pmap_init2_iso_pmap();
1398 * Create the isolation pmap template. Once created, the template
1399 * is static and its PML4e entries are used to populate the
1400 * kernel portion of any isolated user pmaps.
1402 * Our isolation pmap must contain:
1403 * (1) trampoline area for all cpus
1404 * (2) common_tss area for all cpus (its part of the trampoline area now)
1405 * (3) IDT for all cpus
1406 * (4) GDT for all cpus
1409 pmap_init2_iso_pmap(void)
1414 kprintf("Initialize isolation pmap\n");
1417 * Try to use our normal API calls to make this easier. We have
1418 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1421 pmap_pinit(&iso_pmap);
1422 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1425 * Install areas needed by the cpu and trampoline.
1427 for (n = 0; n < ncpus; ++n) {
1428 struct privatespace *ps;
1430 ps = CPU_prvspace[n];
1431 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1432 sizeof(ps->trampoline));
1433 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1434 sizeof(ps->dblstack));
1435 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1436 sizeof(ps->dbgstack));
1437 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1438 sizeof(ps->common_tss));
1439 pmap_init_iso_range(r_idt_arr[n].rd_base,
1440 r_idt_arr[n].rd_limit + 1);
1442 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1443 pmap_init_iso_range((vm_offset_t)(int *)btext,
1444 (vm_offset_t)(int *)etext -
1445 (vm_offset_t)(int *)btext);
1448 kprintf("Dump iso_pmap:\n");
1449 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1450 kprintf("\nDump kernel_pmap:\n");
1451 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1456 * This adds a kernel virtual address range to the isolation pmap.
1459 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1468 kprintf("isolate %016jx-%016jx (%zd)\n",
1469 base, base + bytes, bytes);
1471 va = base & ~(vm_offset_t)PAGE_MASK;
1472 while (va < base + bytes) {
1473 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1474 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1475 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1476 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1478 * Use 2MB pages if possible
1481 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1482 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1487 * Otherwise use 4KB pages
1489 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1490 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1491 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1492 kernel_pmap.pmap_bits[PG_V_IDX] |
1493 kernel_pmap.pmap_bits[PG_A_IDX] |
1494 kernel_pmap.pmap_bits[PG_M_IDX];
1505 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1509 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1516 case 0: /* PML4e page, 512G entries */
1517 incr = (1LL << 48) / 512;
1519 case 1: /* PDP page, 1G entries */
1520 incr = (1LL << 39) / 512;
1522 case 2: /* PD page, 2MB entries */
1523 incr = (1LL << 30) / 512;
1525 case 3: /* PT page, 4KB entries */
1526 incr = (1LL << 21) / 512;
1534 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1535 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1536 for (i = 0; i < 512; ++i) {
1537 if (level == 0 && i == 128)
1538 base += 0xFFFF000000000000LLU;
1540 kprintf("%*.*s ", level * 4, level * 4, "");
1541 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1542 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1544 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1545 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1547 } else if (level == 3) {
1548 kprintf("va=%016jx %3d term %016jx\n",
1551 kprintf("va=%016jx %3d deep %016jx\n",
1553 dump_pmap(pmap, ptp[i], level + 1, base);
1563 * Typically used to initialize a fictitious page by vm/device_pager.c
1566 pmap_page_init(struct vm_page *m)
1569 TAILQ_INIT(&m->md.pv_list);
1572 /***************************************************
1573 * Low level helper routines.....
1574 ***************************************************/
1577 * this routine defines the region(s) of memory that should
1578 * not be tested for the modified bit.
1582 pmap_track_modified(vm_pindex_t pindex)
1584 vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
1585 if ((va < clean_sva) || (va >= clean_eva))
1592 * Extract the physical page address associated with the map/VA pair.
1593 * The page must be wired for this to work reliably.
1596 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1603 if (va >= VM_MAX_USER_ADDRESS) {
1605 * Kernel page directories might be direct-mapped and
1606 * there is typically no PV tracking of pte's
1610 pt = pmap_pt(pmap, va);
1611 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1612 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1613 rtval = *pt & PG_PS_FRAME;
1614 rtval |= va & PDRMASK;
1616 ptep = pmap_pt_to_pte(*pt, va);
1617 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1618 rtval = *ptep & PG_FRAME;
1619 rtval |= va & PAGE_MASK;
1627 * User pages currently do not direct-map the page directory
1628 * and some pages might not used managed PVs. But all PT's
1631 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1633 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1634 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1635 rtval = *ptep & PG_FRAME;
1636 rtval |= va & PAGE_MASK;
1639 *handlep = pt_pv; /* locked until done */
1642 } else if (handlep) {
1650 pmap_extract_done(void *handle)
1653 pv_put((pv_entry_t)handle);
1657 * Similar to extract but checks protections, SMP-friendly short-cut for
1658 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1659 * fall-through to the real fault code. Does not work with HVM page
1662 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1664 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1665 * page is busied (and not held).
1667 * If busyp is not NULL and this function sets *busyp to zero, the returned
1668 * page is held (and not busied).
1670 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1671 * returned page will be dirtied. If the pte is not already writable NULL
1672 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1673 * any COW will already have happened and that page can be written by the
1676 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1680 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1683 va < VM_MAX_USER_ADDRESS &&
1684 (pmap->pm_flags & PMAP_HVM) == 0) {
1692 req = pmap->pmap_bits[PG_V_IDX] |
1693 pmap->pmap_bits[PG_U_IDX];
1694 if (prot & VM_PROT_WRITE)
1695 req |= pmap->pmap_bits[PG_RW_IDX];
1697 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1700 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1701 if ((*ptep & req) != req) {
1705 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1706 if (pte_pv && error == 0) {
1708 if (prot & VM_PROT_WRITE) {
1709 /* interlocked by presence of pv_entry */
1713 if (prot & VM_PROT_WRITE) {
1714 if (vm_page_busy_try(m, TRUE))
1725 } else if (pte_pv) {
1729 /* error, since we didn't request a placemarker */
1740 * Extract the physical page address associated kernel virtual address.
1743 pmap_kextract(vm_offset_t va)
1745 pd_entry_t pt; /* pt entry in pd */
1748 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1749 pa = DMAP_TO_PHYS(va);
1752 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1753 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1756 * Beware of a concurrent promotion that changes the
1757 * PDE at this point! For example, vtopte() must not
1758 * be used to access the PTE because it would use the
1759 * new PDE. It is, however, safe to use the old PDE
1760 * because the page table page is preserved by the
1763 pa = *pmap_pt_to_pte(pt, va);
1764 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1770 /***************************************************
1771 * Low level mapping routines.....
1772 ***************************************************/
1775 * Routine: pmap_kenter
1777 * Add a wired page to the KVA
1778 * NOTE! note that in order for the mapping to take effect -- you
1779 * should do an invltlb after doing the pmap_kenter().
1782 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1788 kernel_pmap.pmap_bits[PG_RW_IDX] |
1789 kernel_pmap.pmap_bits[PG_V_IDX];
1793 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1797 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1804 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1805 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1806 * (caller can conditionalize calling smp_invltlb()).
1809 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1815 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1816 kernel_pmap.pmap_bits[PG_V_IDX];
1825 atomic_swap_long(ptep, npte);
1826 cpu_invlpg((void *)va);
1832 * Enter addresses into the kernel pmap but don't bother
1833 * doing any tlb invalidations. Caller will do a rollup
1834 * invalidation via pmap_rollup_inval().
1837 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1844 kernel_pmap.pmap_bits[PG_RW_IDX] |
1845 kernel_pmap.pmap_bits[PG_V_IDX];
1854 atomic_swap_long(ptep, npte);
1855 cpu_invlpg((void *)va);
1861 * remove a page from the kernel pagetables
1864 pmap_kremove(vm_offset_t va)
1869 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1873 pmap_kremove_quick(vm_offset_t va)
1878 (void)pte_load_clear(ptep);
1879 cpu_invlpg((void *)va);
1883 * Remove addresses from the kernel pmap but don't bother
1884 * doing any tlb invalidations. Caller will do a rollup
1885 * invalidation via pmap_rollup_inval().
1888 pmap_kremove_noinval(vm_offset_t va)
1893 (void)pte_load_clear(ptep);
1897 * XXX these need to be recoded. They are not used in any critical path.
1900 pmap_kmodify_rw(vm_offset_t va)
1902 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1903 cpu_invlpg((void *)va);
1908 pmap_kmodify_nc(vm_offset_t va)
1910 atomic_set_long(vtopte(va), PG_N);
1911 cpu_invlpg((void *)va);
1916 * Used to map a range of physical addresses into kernel virtual
1917 * address space during the low level boot, typically to map the
1918 * dump bitmap, message buffer, and vm_page_array.
1920 * These mappings are typically made at some pointer after the end of the
1923 * We could return PHYS_TO_DMAP(start) here and not allocate any
1924 * via (*virtp), but then kmem from userland and kernel dumps won't
1925 * have access to the related pointers.
1928 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1931 vm_offset_t va_start;
1933 /*return PHYS_TO_DMAP(start);*/
1938 while (start < end) {
1939 pmap_kenter_quick(va, start);
1947 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1950 * Remove the specified set of pages from the data and instruction caches.
1952 * In contrast to pmap_invalidate_cache_range(), this function does not
1953 * rely on the CPU's self-snoop feature, because it is intended for use
1954 * when moving pages into a different cache domain.
1957 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1959 vm_offset_t daddr, eva;
1962 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1963 (cpu_feature & CPUID_CLFSH) == 0)
1967 for (i = 0; i < count; i++) {
1968 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1969 eva = daddr + PAGE_SIZE;
1970 for (; daddr < eva; daddr += cpu_clflush_line_size)
1978 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1980 KASSERT((sva & PAGE_MASK) == 0,
1981 ("pmap_invalidate_cache_range: sva not page-aligned"));
1982 KASSERT((eva & PAGE_MASK) == 0,
1983 ("pmap_invalidate_cache_range: eva not page-aligned"));
1985 if (cpu_feature & CPUID_SS) {
1986 ; /* If "Self Snoop" is supported, do nothing. */
1988 /* Globally invalidate caches */
1989 cpu_wbinvd_on_all_cpus();
1994 * Invalidate the specified range of virtual memory on all cpus associated
1998 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2000 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2004 * Add a list of wired pages to the kva. This routine is used for temporary
2005 * kernel mappings such as those found in buffer cache buffer. Page
2006 * modifications and accesses are not tracked or recorded.
2008 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2009 * semantics as previous mappings may have been zerod without any
2012 * The page *must* be wired.
2014 static __inline void
2015 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2020 end_va = beg_va + count * PAGE_SIZE;
2022 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2027 pte = VM_PAGE_TO_PHYS(*m) |
2028 kernel_pmap.pmap_bits[PG_RW_IDX] |
2029 kernel_pmap.pmap_bits[PG_V_IDX] |
2030 kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2032 atomic_swap_long(ptep, pte);
2036 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2040 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2042 _pmap_qenter(beg_va, m, count, 1);
2046 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2048 _pmap_qenter(beg_va, m, count, 0);
2052 * This routine jerks page mappings from the kernel -- it is meant only
2053 * for temporary mappings such as those found in buffer cache buffers.
2054 * No recording modified or access status occurs.
2056 * MPSAFE, INTERRUPT SAFE (cluster callback)
2059 pmap_qremove(vm_offset_t beg_va, int count)
2064 end_va = beg_va + count * PAGE_SIZE;
2066 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2070 (void)pte_load_clear(pte);
2071 cpu_invlpg((void *)va);
2073 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2077 * This routine removes temporary kernel mappings, only invalidating them
2078 * on the current cpu. It should only be used under carefully controlled
2082 pmap_qremove_quick(vm_offset_t beg_va, int count)
2087 end_va = beg_va + count * PAGE_SIZE;
2089 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2093 (void)pte_load_clear(pte);
2094 cpu_invlpg((void *)va);
2099 * This routine removes temporary kernel mappings *without* invalidating
2100 * the TLB. It can only be used on permanent kva reservations such as those
2101 * found in buffer cache buffers, under carefully controlled circumstances.
2103 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2104 * (pmap_qenter() does unconditional invalidation).
2107 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2112 end_va = beg_va + count * PAGE_SIZE;
2114 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2118 (void)pte_load_clear(pte);
2123 * Create a new thread and optionally associate it with a (new) process.
2124 * NOTE! the new thread's cpu may not equal the current cpu.
2127 pmap_init_thread(thread_t td)
2129 /* enforce pcb placement & alignment */
2130 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2131 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2132 td->td_savefpu = &td->td_pcb->pcb_save;
2133 td->td_sp = (char *)td->td_pcb; /* no -16 */
2137 * This routine directly affects the fork perf for a process.
2140 pmap_init_proc(struct proc *p)
2145 pmap_pinit_defaults(struct pmap *pmap)
2147 bcopy(pmap_bits_default, pmap->pmap_bits,
2148 sizeof(pmap_bits_default));
2149 bcopy(protection_codes, pmap->protection_codes,
2150 sizeof(protection_codes));
2151 bcopy(pat_pte_index, pmap->pmap_cache_bits,
2152 sizeof(pat_pte_index));
2153 pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2154 pmap->copyinstr = std_copyinstr;
2155 pmap->copyin = std_copyin;
2156 pmap->copyout = std_copyout;
2157 pmap->fubyte = std_fubyte;
2158 pmap->subyte = std_subyte;
2159 pmap->fuword32 = std_fuword32;
2160 pmap->fuword64 = std_fuword64;
2161 pmap->suword32 = std_suword32;
2162 pmap->suword64 = std_suword64;
2163 pmap->swapu32 = std_swapu32;
2164 pmap->swapu64 = std_swapu64;
2165 pmap->fuwordadd32 = std_fuwordadd32;
2166 pmap->fuwordadd64 = std_fuwordadd64;
2169 * Initialize pmap0/vmspace0.
2171 * On architectures where the kernel pmap is not integrated into the user
2172 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2173 * kernel_pmap should be used to directly access the kernel_pmap.
2176 pmap_pinit0(struct pmap *pmap)
2180 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2182 CPUMASK_ASSZERO(pmap->pm_active);
2183 pmap->pm_pvhint_pt = NULL;
2184 pmap->pm_pvhint_pte = NULL;
2185 RB_INIT(&pmap->pm_pvroot);
2186 spin_init(&pmap->pm_spin, "pmapinit0");
2187 for (i = 0; i < PM_PLACEMARKS; ++i)
2188 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2189 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2190 pmap_pinit_defaults(pmap);
2194 * Initialize a preallocated and zeroed pmap structure,
2195 * such as one in a vmspace structure.
2198 pmap_pinit_simple(struct pmap *pmap)
2203 * Misc initialization
2206 CPUMASK_ASSZERO(pmap->pm_active);
2207 pmap->pm_pvhint_pt = NULL;
2208 pmap->pm_pvhint_pte = NULL;
2209 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2211 pmap_pinit_defaults(pmap);
2214 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2217 if (pmap->pm_pmlpv == NULL) {
2218 RB_INIT(&pmap->pm_pvroot);
2219 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2220 spin_init(&pmap->pm_spin, "pmapinitsimple");
2221 for (i = 0; i < PM_PLACEMARKS; ++i)
2222 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2227 pmap_pinit(struct pmap *pmap)
2232 if (pmap->pm_pmlpv) {
2233 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2238 pmap_pinit_simple(pmap);
2239 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2242 * No need to allocate page table space yet but we do need a valid
2243 * page directory table.
2245 if (pmap->pm_pml4 == NULL) {
2247 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2250 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2254 * Allocate the PML4e table, which wires it even though it isn't
2255 * being entered into some higher level page table (it being the
2256 * highest level). If one is already cached we don't have to do
2259 if ((pv = pmap->pm_pmlpv) == NULL) {
2260 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2261 pmap->pm_pmlpv = pv;
2262 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2263 VM_PAGE_TO_PHYS(pv->pv_m));
2267 * Install DMAP and KMAP.
2269 for (j = 0; j < NDMPML4E; ++j) {
2270 pmap->pm_pml4[DMPML4I + j] =
2271 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2272 pmap->pmap_bits[PG_RW_IDX] |
2273 pmap->pmap_bits[PG_V_IDX] |
2274 pmap->pmap_bits[PG_A_IDX];
2276 for (j = 0; j < NKPML4E; ++j) {
2277 pmap->pm_pml4[KPML4I + j] =
2278 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2279 pmap->pmap_bits[PG_RW_IDX] |
2280 pmap->pmap_bits[PG_V_IDX] |
2281 pmap->pmap_bits[PG_A_IDX];
2285 * install self-referential address mapping entry
2287 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2288 pmap->pmap_bits[PG_V_IDX] |
2289 pmap->pmap_bits[PG_RW_IDX] |
2290 pmap->pmap_bits[PG_A_IDX];
2292 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2293 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2295 KKASSERT(pmap->pm_pml4[255] == 0);
2298 * When implementing an isolated userland pmap, a second PML4e table
2299 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2300 * note that we do not operate on this table using our API functions
2301 * so handling of the + 1 case is mostly just to prevent implosions.
2303 * We install an isolated version of the kernel PDPs into this
2304 * second PML4e table. The pmap code will mirror all user PDPs
2305 * between the primary and secondary PML4e table.
2307 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2308 pmap != &iso_pmap) {
2309 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2310 pmap->pm_pmlpv_iso = pv;
2311 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2312 VM_PAGE_TO_PHYS(pv->pv_m));
2316 * Install an isolated version of the kernel pmap for
2317 * user consumption, using PDPs constructed in iso_pmap.
2319 for (j = 0; j < NKPML4E; ++j) {
2320 pmap->pm_pml4_iso[KPML4I + j] =
2321 iso_pmap.pm_pml4[KPML4I + j];
2324 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2325 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2330 * Clean up a pmap structure so it can be physically freed. This routine
2331 * is called by the vmspace dtor function. A great deal of pmap data is
2332 * left passively mapped to improve vmspace management so we have a bit
2333 * of cleanup work to do here.
2336 pmap_puninit(pmap_t pmap)
2341 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2342 if ((pv = pmap->pm_pmlpv) != NULL) {
2343 if (pv_hold_try(pv) == 0)
2345 KKASSERT(pv == pmap->pm_pmlpv);
2346 p = pmap_remove_pv_page(pv);
2348 pv = NULL; /* safety */
2349 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2350 vm_page_busy_wait(p, FALSE, "pgpun");
2351 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2352 vm_page_unwire(p, 0);
2353 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2355 pmap->pm_pmlpv = NULL;
2357 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2358 if (pv_hold_try(pv) == 0)
2360 KKASSERT(pv == pmap->pm_pmlpv_iso);
2361 p = pmap_remove_pv_page(pv);
2363 pv = NULL; /* safety */
2364 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2365 vm_page_busy_wait(p, FALSE, "pgpun");
2366 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2367 vm_page_unwire(p, 0);
2368 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2370 pmap->pm_pmlpv_iso = NULL;
2372 if (pmap->pm_pml4) {
2373 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2374 kmem_free(&kernel_map,
2375 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2376 pmap->pm_pml4 = NULL;
2377 pmap->pm_pml4_iso = NULL;
2379 KKASSERT(pmap->pm_stats.resident_count == 0);
2380 KKASSERT(pmap->pm_stats.wired_count == 0);
2384 * This function is now unused (used to add the pmap to the pmap_list)
2387 pmap_pinit2(struct pmap *pmap)
2392 * This routine is called when various levels in the page table need to
2393 * be populated. This routine cannot fail.
2395 * This function returns two locked pv_entry's, one representing the
2396 * requested pv and one representing the requested pv's parent pv. If
2397 * an intermediate page table does not exist it will be created, mapped,
2398 * wired, and the parent page table will be given an additional hold
2399 * count representing the presence of the child pv_entry.
2403 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2406 pt_entry_t *ptep_iso;
2410 vm_pindex_t pt_pindex;
2416 * If the pv already exists and we aren't being asked for the
2417 * parent page table page we can just return it. A locked+held pv
2418 * is returned. The pv will also have a second hold related to the
2419 * pmap association that we don't have to worry about.
2422 pv = pv_alloc(pmap, ptepindex, &isnew);
2423 if (isnew == 0 && pvpp == NULL)
2427 * Special case terminal PVs. These are not page table pages so
2428 * no vm_page is allocated (the caller supplied the vm_page). If
2429 * pvpp is non-NULL we are being asked to also removed the pt_pv
2432 * Note that pt_pv's are only returned for user VAs. We assert that
2433 * a pt_pv is not being requested for kernel VAs. The kernel
2434 * pre-wires all higher-level page tables so don't overload managed
2435 * higher-level page tables on top of it!
2437 * However, its convenient for us to allow the case when creating
2438 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2441 if (ptepindex < pmap_pt_pindex(0)) {
2442 if (ptepindex >= NUPTE_USER && pmap != &iso_pmap) {
2443 /* kernel manages this manually for KVM */
2444 KKASSERT(pvpp == NULL);
2446 KKASSERT(pvpp != NULL);
2447 pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
2448 pvp = pmap_allocpte(pmap, pt_pindex, NULL);
2450 vm_page_wire_quick(pvp->pv_m);
2457 * The kernel never uses managed PT/PD/PDP pages.
2459 KKASSERT(pmap != &kernel_pmap);
2462 * Non-terminal PVs allocate a VM page to represent the page table,
2463 * so we have to resolve pvp and calculate ptepindex for the pvp
2464 * and then for the page table entry index in the pvp for
2467 if (ptepindex < pmap_pd_pindex(0)) {
2469 * pv is PT, pvp is PD
2471 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2472 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2473 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2478 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2479 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2481 } else if (ptepindex < pmap_pdp_pindex(0)) {
2483 * pv is PD, pvp is PDP
2485 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2488 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2489 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2491 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2492 KKASSERT(pvpp == NULL);
2495 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2501 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2502 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2503 } else if (ptepindex < pmap_pml4_pindex()) {
2505 * pv is PDP, pvp is the root pml4 table
2507 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2512 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2513 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2516 * pv represents the top-level PML4, there is no parent.
2525 * (isnew) is TRUE, pv is not terminal.
2527 * (1) Add a wire count to the parent page table (pvp).
2528 * (2) Allocate a VM page for the page table.
2529 * (3) Enter the VM page into the parent page table.
2531 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2534 vm_page_wire_quick(pvp->pv_m);
2537 m = vm_page_alloc(NULL, pv->pv_pindex,
2538 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2539 VM_ALLOC_INTERRUPT);
2544 vm_page_wire(m); /* wire for mapping in parent */
2545 vm_page_unmanage(m); /* m must be spinunlocked */
2546 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2547 m->valid = VM_PAGE_BITS_ALL;
2549 vm_page_spin_lock(m);
2550 pmap_page_stats_adding(m);
2553 * PGTABLE pv's only exist in the context of the pmap RB tree
2554 * (pmap->pm_pvroot).
2557 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2559 pv->pv_flags |= PV_FLAG_PGTABLE;
2561 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2562 vm_page_spin_unlock(m);
2565 * (isnew) is TRUE, pv is not terminal.
2567 * Wire the page into pvp. Bump the resident_count for the pmap.
2568 * There is no pvp for the top level, address the pm_pml4[] array
2571 * If the caller wants the parent we return it, otherwise
2572 * we just put it away.
2574 * No interlock is needed for pte 0 -> non-zero.
2576 * In the situation where *ptep is valid we might have an unmanaged
2577 * page table page shared from another page table which we need to
2578 * unshare before installing our private page table page.
2581 v = VM_PAGE_TO_PHYS(m) |
2582 (pmap->pmap_bits[PG_RW_IDX] |
2583 pmap->pmap_bits[PG_V_IDX] |
2584 pmap->pmap_bits[PG_A_IDX]);
2585 if (ptepindex < NUPTE_USER)
2586 v |= pmap->pmap_bits[PG_U_IDX];
2587 if (ptepindex < pmap_pt_pindex(0))
2588 v |= pmap->pmap_bits[PG_M_IDX];
2590 ptep = pv_pte_lookup(pvp, ptepindex);
2591 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2592 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2595 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2599 panic("pmap_allocpte: unexpected pte %p/%d",
2600 pvp, (int)ptepindex);
2602 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2605 pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2608 if (vm_page_unwire_quick(
2609 PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2610 panic("pmap_allocpte: shared pgtable "
2611 "pg bad wirecount");
2616 pte = atomic_swap_long(ptep, v);
2618 atomic_swap_long(ptep_iso, v);
2620 kprintf("install pgtbl mixup 0x%016jx "
2621 "old/new 0x%016jx/0x%016jx\n",
2622 (intmax_t)ptepindex, pte, v);
2629 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2633 KKASSERT(pvp->pv_m != NULL);
2634 ptep = pv_pte_lookup(pvp, ptepindex);
2635 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2636 (pmap->pmap_bits[PG_RW_IDX] |
2637 pmap->pmap_bits[PG_V_IDX] |
2638 pmap->pmap_bits[PG_A_IDX]);
2639 if (ptepindex < NUPTE_USER)
2640 v |= pmap->pmap_bits[PG_U_IDX];
2641 if (ptepindex < pmap_pt_pindex(0))
2642 v |= pmap->pmap_bits[PG_M_IDX];
2644 kprintf("mismatched upper level pt %016jx/%016jx\n",
2656 * This version of pmap_allocpte() checks for possible segment optimizations
2657 * that would allow page-table sharing. It can be called for terminal
2658 * page or page table page ptepindex's.
2660 * The function is called with page table page ptepindex's for fictitious
2661 * and unmanaged terminal pages. That is, we don't want to allocate a
2662 * terminal pv, we just want the pt_pv. pvpp is usually passed as NULL
2665 * This function can return a pv and *pvpp associated with the passed in pmap
2666 * OR a pv and *pvpp associated with the shared pmap. In the latter case
2667 * an unmanaged page table page will be entered into the pass in pmap.
2671 pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
2672 vm_map_entry_t entry, vm_offset_t va)
2677 vm_pindex_t *pt_placemark;
2679 pv_entry_t pte_pv; /* in original or shared pmap */
2680 pv_entry_t pt_pv; /* in original or shared pmap */
2681 pv_entry_t proc_pd_pv; /* in original pmap */
2682 pv_entry_t proc_pt_pv; /* in original pmap */
2683 pv_entry_t xpv; /* PT in shared pmap */
2684 pd_entry_t *pt; /* PT entry in PD of original pmap */
2685 pd_entry_t opte; /* contents of *pt */
2686 pd_entry_t npte; /* contents of *pt */
2691 * Basic tests, require a non-NULL vm_map_entry, require proper
2692 * alignment and type for the vm_map_entry, require that the
2693 * underlying object already be allocated.
2695 * We allow almost any type of object to use this optimization.
2696 * The object itself does NOT have to be sized to a multiple of the
2697 * segment size, but the memory mapping does.
2699 * XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
2700 * won't work as expected.
2702 if (entry == NULL ||
2703 pmap_mmu_optimize == 0 || /* not enabled */
2704 (pmap->pm_flags & PMAP_HVM) || /* special pmap */
2705 ptepindex >= pmap_pd_pindex(0) || /* not terminal or pt */
2706 entry->inheritance != VM_INHERIT_SHARE || /* not shared */
2707 entry->maptype != VM_MAPTYPE_NORMAL || /* weird map type */
2708 entry->ba.object == NULL || /* needs VM object */
2709 entry->ba.backing_ba || /* no backing objs */
2710 entry->ba.object->type == OBJT_DEVICE || /* ick */
2711 entry->ba.object->type == OBJT_MGTDEVICE || /* ick */
2712 (entry->ba.offset & SEG_MASK) || /* must be aligned */
2713 (entry->ba.start & SEG_MASK)) {
2714 return(pmap_allocpte(pmap, ptepindex, pvpp));
2718 * Make sure the full segment can be represented.
2720 b = va & ~(vm_offset_t)SEG_MASK;
2721 if (b < entry->ba.start || b + SEG_SIZE > entry->ba.end)
2722 return(pmap_allocpte(pmap, ptepindex, pvpp));
2725 * If the full segment can be represented dive the VM object's
2726 * shared pmap, allocating as required.
2728 object = entry->ba.object;
2730 if (entry->protection & VM_PROT_WRITE)
2731 obpmapp = &object->md.pmap_rw;
2733 obpmapp = &object->md.pmap_ro;
2736 if (pmap_enter_debug > 0) {
2738 kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
2740 va, entry->protection, object,
2742 kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
2743 entry, entry->ba.start, entry->ba.end);
2748 * We allocate what appears to be a normal pmap but because portions
2749 * of this pmap are shared with other unrelated pmaps we have to
2750 * set pm_active to point to all cpus.
2752 * XXX Currently using pmap_spin to interlock the update, can't use
2753 * vm_object_hold/drop because the token might already be held
2754 * shared OR exclusive and we don't know.
2756 while ((obpmap = *obpmapp) == NULL) {
2757 obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
2758 pmap_pinit_simple(obpmap);
2759 pmap_pinit2(obpmap);
2760 spin_lock(&pmap_spin);
2761 if (*obpmapp != NULL) {
2765 spin_unlock(&pmap_spin);
2766 pmap_release(obpmap);
2767 pmap_puninit(obpmap);
2768 kfree(obpmap, M_OBJPMAP);
2769 obpmap = *obpmapp; /* safety */
2771 obpmap->pm_active = smp_active_mask;
2772 obpmap->pm_flags |= PMAP_SEGSHARED;
2774 spin_unlock(&pmap_spin);
2779 * Layering is: PTE, PT, PD, PDP, PML4. We have to return the
2780 * pte/pt using the shared pmap from the object but also adjust
2781 * the process pmap's page table page as a side effect.
2785 * Resolve the terminal PTE and PT in the shared pmap. This is what
2786 * we will return. This is true if ptepindex represents a terminal
2787 * page, otherwise pte_pv is actually the PT and pt_pv is actually
2791 pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
2794 if (ptepindex >= pmap_pt_pindex(0))
2800 * Resolve the PD in the process pmap so we can properly share the
2801 * page table page. Lock order is bottom-up (leaf first)!
2803 * NOTE: proc_pt_pv can be NULL.
2805 proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b), &pt_placemark);
2806 proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
2808 if (pmap_enter_debug > 0) {
2810 kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
2812 (proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
2819 * xpv is the page table page pv from the shared object
2820 * (for convenience), from above.
2822 * Calculate the pte value for the PT to load into the process PD.
2823 * If we have to change it we must properly dispose of the previous
2826 pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2827 npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
2828 (pmap->pmap_bits[PG_U_IDX] |
2829 pmap->pmap_bits[PG_RW_IDX] |
2830 pmap->pmap_bits[PG_V_IDX] |
2831 pmap->pmap_bits[PG_A_IDX] |
2832 pmap->pmap_bits[PG_M_IDX]);
2835 * Dispose of previous page table page if it was local to the
2836 * process pmap. If the old pt is not empty we cannot dispose of it
2837 * until we clean it out. This case should not arise very often so
2838 * it is not optimized.
2840 * Leave pt_pv and pte_pv (in our object pmap) locked and intact
2844 pmap_inval_bulk_t bulk;
2846 if (proc_pt_pv->pv_m->wire_count != 1) {
2848 * The page table has a bunch of stuff in it
2849 * which we have to scrap.
2851 if (softhold == 0) {
2853 pmap_softhold(pmap);
2858 va & ~(vm_offset_t)SEG_MASK,
2859 (va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
2862 * The page table is empty and can be destroyed.
2863 * However, doing so leaves the pt slot unlocked,
2864 * so we have to loop-up to handle any races until
2865 * we get a NULL proc_pt_pv and a proper pt_placemark.
2867 pmap_inval_bulk_init(&bulk, proc_pt_pv->pv_pmap);
2868 pmap_release_pv(proc_pt_pv, proc_pd_pv, &bulk);
2869 pmap_inval_bulk_flush(&bulk);
2876 * Handle remaining cases. We are holding pt_placemark to lock
2877 * the page table page in the primary pmap while we manipulate
2881 atomic_swap_long(pt, npte);
2882 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2883 vm_page_wire_quick(proc_pd_pv->pv_m); /* proc pd for sh pt */
2884 atomic_add_long(&pmap->pm_stats.resident_count, 1);
2885 } else if (*pt != npte) {
2886 opte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, pt, npte);
2889 opte = pte_load_clear(pt);
2890 KKASSERT(opte && opte != npte);
2894 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2897 * Clean up opte, bump the wire_count for the process
2898 * PD page representing the new entry if it was
2901 * If the entry was not previously empty and we have
2902 * a PT in the proc pmap then opte must match that
2903 * pt. The proc pt must be retired (this is done
2904 * later on in this procedure).
2906 * NOTE: replacing valid pte, wire_count on proc_pd_pv
2909 KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
2910 m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
2911 if (vm_page_unwire_quick(m)) {
2912 panic("pmap_allocpte_seg: "
2913 "bad wire count %p",
2919 pmap_softdone(pmap);
2922 * Remove our earmark on the page table page.
2924 pv_placemarker_wakeup(pmap, pt_placemark);
2927 * The existing process page table was replaced and must be destroyed
2940 * Release any resources held by the given physical map.
2942 * Called when a pmap initialized by pmap_pinit is being released. Should
2943 * only be called if the map contains no valid mappings.
2945 struct pmap_release_info {
2951 static int pmap_release_callback(pv_entry_t pv, void *data);
2954 pmap_release(struct pmap *pmap)
2956 struct pmap_release_info info;
2958 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2959 ("pmap still active! %016jx",
2960 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2963 * There is no longer a pmap_list, if there were we would remove the
2964 * pmap from it here.
2968 * Pull pv's off the RB tree in order from low to high and release
2976 spin_lock(&pmap->pm_spin);
2977 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2978 pmap_release_callback, &info);
2979 spin_unlock(&pmap->pm_spin);
2983 } while (info.retry);
2987 * One resident page (the pml4 page) should remain. Two if
2988 * the pmap has implemented an isolated userland PML4E table.
2989 * No wired pages should remain.
2991 int expected_res = 0;
2993 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2995 if (pmap->pm_pmlpv_iso)
2999 if (pmap->pm_stats.resident_count != expected_res ||
3000 pmap->pm_stats.wired_count != 0) {
3001 kprintf("fatal pmap problem - pmap %p flags %08x "
3002 "rescnt=%jd wirecnt=%jd\n",
3005 pmap->pm_stats.resident_count,
3006 pmap->pm_stats.wired_count);
3007 tsleep(pmap, 0, "DEAD", 0);
3010 KKASSERT(pmap->pm_stats.resident_count == expected_res);
3011 KKASSERT(pmap->pm_stats.wired_count == 0);
3016 * Called from low to high. We must cache the proper parent pv so we
3017 * can adjust its wired count.
3020 pmap_release_callback(pv_entry_t pv, void *data)
3022 struct pmap_release_info *info = data;
3023 pmap_t pmap = info->pmap;
3028 * Acquire a held and locked pv, check for release race
3030 pindex = pv->pv_pindex;
3031 if (info->pvp == pv) {
3032 spin_unlock(&pmap->pm_spin);
3034 } else if (pv_hold_try(pv)) {
3035 spin_unlock(&pmap->pm_spin);
3037 spin_unlock(&pmap->pm_spin);
3041 spin_lock(&pmap->pm_spin);
3045 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
3047 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3049 * I am PTE, parent is PT
3051 pindex = pv->pv_pindex >> NPTEPGSHIFT;
3052 pindex += NUPTE_TOTAL;
3053 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
3055 * I am PT, parent is PD
3057 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
3058 pindex += NUPTE_TOTAL + NUPT_TOTAL;
3059 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
3061 * I am PD, parent is PDP
3063 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
3065 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
3066 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
3068 * I am PDP, parent is PML4. We always calculate the
3069 * normal PML4 here, not the isolated PML4.
3071 pindex = pmap_pml4_pindex();
3083 if (info->pvp && info->pvp->pv_pindex != pindex) {
3087 if (info->pvp == NULL)
3088 info->pvp = pv_get(pmap, pindex, NULL);
3095 r = pmap_release_pv(pv, info->pvp, NULL);
3096 spin_lock(&pmap->pm_spin);
3102 * Called with held (i.e. also locked) pv. This function will dispose of
3103 * the lock along with the pv.
3105 * If the caller already holds the locked parent page table for pv it
3106 * must pass it as pvp, allowing us to avoid a deadlock, else it can
3107 * pass NULL for pvp.
3110 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
3115 * The pmap is currently not spinlocked, pv is held+locked.
3116 * Remove the pv's page from its parent's page table. The
3117 * parent's page table page's wire_count will be decremented.
3119 * This will clean out the pte at any level of the page table.
3120 * If smp != 0 all cpus are affected.
3122 * Do not tear-down recursively, its faster to just let the
3123 * release run its course.
3125 pmap_remove_pv_pte(pv, pvp, bulk, 0);
3128 * Terminal pvs are unhooked from their vm_pages. Because
3129 * terminal pages aren't page table pages they aren't wired
3130 * by us, so we have to be sure not to unwire them either.
3132 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3133 pmap_remove_pv_page(pv);
3138 * We leave the top-level page table page cached, wired, and
3139 * mapped in the pmap until the dtor function (pmap_puninit())
3142 * Since we are leaving the top-level pv intact we need
3143 * to break out of what would otherwise be an infinite loop.
3145 * This covers both the normal and the isolated PML4 page.
3147 if (pv->pv_pindex >= pmap_pml4_pindex()) {
3153 * For page table pages (other than the top-level page),
3154 * remove and free the vm_page. The representitive mapping
3155 * removed above by pmap_remove_pv_pte() did not undo the
3156 * last wire_count so we have to do that as well.
3158 p = pmap_remove_pv_page(pv);
3159 vm_page_busy_wait(p, FALSE, "pmaprl");
3160 if (p->wire_count != 1) {
3161 kprintf("p->wire_count was %016lx %d\n",
3162 pv->pv_pindex, p->wire_count);
3164 KKASSERT(p->wire_count == 1);
3165 KKASSERT(p->flags & PG_UNMANAGED);
3167 vm_page_unwire(p, 0);
3168 KKASSERT(p->wire_count == 0);
3178 * This function will remove the pte associated with a pv from its parent.
3179 * Terminal pv's are supported. All cpus specified by (bulk) are properly
3182 * The wire count will be dropped on the parent page table. The wire
3183 * count on the page being removed (pv->pv_m) from the parent page table
3184 * is NOT touched. Note that terminal pages will not have any additional
3185 * wire counts while page table pages will have at least one representing
3186 * the mapping, plus others representing sub-mappings.
3188 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3189 * pages and user page table and terminal pages.
3191 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3192 * be freshly allocated and not imply that the pte is managed. In this
3193 * case pv->pv_m should be NULL.
3195 * The pv must be locked. The pvp, if supplied, must be locked. All
3196 * supplied pv's will remain locked on return.
3198 * XXX must lock parent pv's if they exist to remove pte XXX
3202 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3205 vm_pindex_t ptepindex = pv->pv_pindex;
3206 pmap_t pmap = pv->pv_pmap;
3212 if (ptepindex >= pmap_pml4_pindex()) {
3214 * We are the top level PML4E table, there is no parent.
3216 * This is either the normal or isolated PML4E table.
3217 * Only the normal is used in regular operation, the isolated
3218 * is only passed in when breaking down the whole pmap.
3220 p = pmap->pm_pmlpv->pv_m;
3221 KKASSERT(pv->pv_m == p); /* debugging */
3222 } else if (ptepindex >= pmap_pdp_pindex(0)) {
3224 * Remove a PDP page from the PML4E. This can only occur
3225 * with user page tables. We do not have to lock the
3226 * pml4 PV so just ignore pvp.
3228 vm_pindex_t pml4_pindex;
3229 vm_pindex_t pdp_index;
3231 pml4_entry_t *pdp_iso;
3233 pdp_index = ptepindex - pmap_pdp_pindex(0);
3235 pml4_pindex = pmap_pml4_pindex();
3236 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3241 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3242 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3243 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3244 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3247 * Also remove the PDP from the isolated PML4E if the
3250 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3251 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3252 ((1ul << NPML4EPGSHIFT) - 1)];
3253 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3255 KKASSERT(pv->pv_m == p); /* debugging */
3256 } else if (ptepindex >= pmap_pd_pindex(0)) {
3258 * Remove a PD page from the PDP
3260 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3261 * of a simple pmap because it stops at
3264 vm_pindex_t pdp_pindex;
3265 vm_pindex_t pd_index;
3268 pd_index = ptepindex - pmap_pd_pindex(0);
3271 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3272 (pd_index >> NPML4EPGSHIFT);
3273 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3278 pd = pv_pte_lookup(pvp, pd_index &
3279 ((1ul << NPDPEPGSHIFT) - 1));
3280 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3281 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3282 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3284 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3285 p = pv->pv_m; /* degenerate test later */
3287 KKASSERT(pv->pv_m == p); /* debugging */
3288 } else if (ptepindex >= pmap_pt_pindex(0)) {
3290 * Remove a PT page from the PD
3292 vm_pindex_t pd_pindex;
3293 vm_pindex_t pt_index;
3296 pt_index = ptepindex - pmap_pt_pindex(0);
3299 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3300 (pt_index >> NPDPEPGSHIFT);
3301 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3306 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3308 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3309 ("*pt unexpectedly invalid %016jx "
3310 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3311 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3312 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3314 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3315 kprintf("*pt unexpectedly invalid %016jx "
3316 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3318 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3319 tsleep(pt, 0, "DEAD", 0);
3322 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3325 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3326 KKASSERT(pv->pv_m == p); /* debugging */
3329 * Remove a PTE from the PT page. The PV might exist even if
3330 * the PTE is not managed, in whichcase pv->pv_m should be
3333 * NOTE: Userland pmaps manage the parent PT/PD/PDP page
3334 * table pages but the kernel_pmap does not.
3336 * NOTE: pv's must be locked bottom-up to avoid deadlocking.
3337 * pv is a pte_pv so we can safely lock pt_pv.
3339 * NOTE: FICTITIOUS pages may have multiple physical mappings
3340 * so PHYS_TO_VM_PAGE() will not necessarily work for
3343 vm_pindex_t pt_pindex;
3348 pt_pindex = ptepindex >> NPTEPGSHIFT;
3349 va = (vm_offset_t)ptepindex << PAGE_SHIFT;
3351 if (ptepindex >= NUPTE_USER) {
3352 ptep = vtopte(ptepindex << PAGE_SHIFT);
3353 KKASSERT(pvp == NULL);
3354 /* pvp remains NULL */
3357 pt_pindex = NUPTE_TOTAL +
3358 (ptepindex >> NPDPEPGSHIFT);
3359 pvp = pv_get(pv->pv_pmap, pt_pindex, NULL);
3363 ptep = pv_pte_lookup(pvp, ptepindex &
3364 ((1ul << NPDPEPGSHIFT) - 1));
3366 pte = pmap_inval_bulk(bulk, va, ptep, 0);
3367 if (bulk == NULL) /* XXX */
3368 cpu_invlpg((void *)va); /* XXX */
3371 * Now update the vm_page_t
3373 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3374 (pte & pmap->pmap_bits[PG_V_IDX])) {
3376 * Valid managed page, adjust (p).
3378 if (pte & pmap->pmap_bits[PG_DEVICE_IDX]) {
3381 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3382 KKASSERT(pv->pv_m == p);
3384 if (pte & pmap->pmap_bits[PG_M_IDX]) {
3385 if (pmap_track_modified(ptepindex))
3388 if (pte & pmap->pmap_bits[PG_A_IDX]) {
3389 vm_page_flag_set(p, PG_REFERENCED);
3393 * Unmanaged page, do not try to adjust the vm_page_t.
3394 * pv could be freshly allocated for a pmap_enter(),
3395 * replacing an unmanaged page with a managed one.
3397 * pv->pv_m might reflect the new page and not the
3400 * We could extract p from the physical address and
3401 * adjust it but we explicitly do not for unmanaged
3406 if (pte & pmap->pmap_bits[PG_W_IDX])
3407 atomic_add_long(&pmap->pm_stats.wired_count, -1);
3408 if (pte & pmap->pmap_bits[PG_G_IDX])
3409 cpu_invlpg((void *)va);
3413 * If requested, scrap the underlying pv->pv_m and the underlying
3414 * pv. If this is a page-table-page we must also free the page.
3416 * pvp must be returned locked.
3420 * page table page (PT, PD, PDP, PML4), caller was responsible
3421 * for testing wired_count.
3423 KKASSERT(pv->pv_m->wire_count == 1);
3424 p = pmap_remove_pv_page(pv);
3428 vm_page_busy_wait(p, FALSE, "pgpun");
3429 vm_page_unwire(p, 0);
3430 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3432 } else if (destroy == 2) {
3434 * Normal page, remove from pmap and leave the underlying
3437 pmap_remove_pv_page(pv);
3439 pv = NULL; /* safety */
3443 * If we acquired pvp ourselves then we are responsible for
3444 * recursively deleting it.
3446 if (pvp && gotpvp) {
3448 * Recursively destroy higher-level page tables.
3450 * This is optional. If we do not, they will still
3451 * be destroyed when the process exits.
3453 * NOTE: Do not destroy pv_entry's with extra hold refs,
3454 * a caller may have unlocked it and intends to
3455 * continue to use it.
3457 if (pmap_dynamic_delete &&
3459 pvp->pv_m->wire_count == 1 &&
3460 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3461 pvp->pv_pindex < pmap_pml4_pindex()) {
3462 if (pmap_dynamic_delete == 2)
3463 kprintf("A %jd %08x\n", pvp->pv_pindex, pvp->pv_hold);
3464 if (pmap != &kernel_pmap) {
3465 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3466 pvp = NULL; /* safety */
3468 kprintf("Attempt to remove kernel_pmap pindex "
3469 "%jd\n", pvp->pv_pindex);
3479 * Remove the vm_page association to a pv. The pv must be locked.
3483 pmap_remove_pv_page(pv_entry_t pv)
3488 vm_page_spin_lock(m);
3489 KKASSERT(m && m == pv->pv_m);
3491 if (pv->pv_flags & PV_FLAG_PGTABLE) {
3492 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3493 KKASSERT(TAILQ_EMPTY(&m->md.pv_list));
3495 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3498 if (TAILQ_EMPTY(&m->md.pv_list))
3499 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3502 * For normal pages, an empty pv_list does not necessarily
3503 * mean that the page is no longer mapped. It might still
3504 * be mapped via an extent through its object.
3506 * However, if m->object is NULL, or the object has not
3507 * extents, then we can clear the bits.
3509 if (TAILQ_EMPTY(&m->md.pv_list) &&
3510 (m->object == NULL ||
3511 TAILQ_EMPTY(&m->object->backing_list))) {
3512 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3516 pmap_page_stats_deleting(m);
3517 vm_page_spin_unlock(m);
3523 * Grow the number of kernel page table entries, if needed.
3525 * This routine is always called to validate any address space
3526 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3527 * space below KERNBASE.
3529 * kernel_map must be locked exclusively by the caller.
3532 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3535 vm_offset_t ptppaddr;
3537 pd_entry_t *pt, newpt;
3538 pdp_entry_t *pd, newpd;
3539 int update_kernel_vm_end;
3542 * bootstrap kernel_vm_end on first real VM use
3544 if (kernel_vm_end == 0) {
3545 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3548 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3551 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3553 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3554 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3555 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
3556 kernel_vm_end = vm_map_max(&kernel_map);
3563 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3564 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3565 * do not want to force-fill 128G worth of page tables.
3567 if (kstart < KERNBASE) {
3568 if (kstart > kernel_vm_end)
3569 kstart = kernel_vm_end;
3570 KKASSERT(kend <= KERNBASE);
3571 update_kernel_vm_end = 1;
3573 update_kernel_vm_end = 0;
3576 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3577 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3579 if (kend - 1 >= vm_map_max(&kernel_map))
3580 kend = vm_map_max(&kernel_map);
3582 while (kstart < kend) {
3583 pt = pmap_pt(&kernel_pmap, kstart);
3586 * We need a new PD entry
3588 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3591 VM_ALLOC_INTERRUPT);
3593 panic("pmap_growkernel: no memory to grow "
3596 paddr = VM_PAGE_TO_PHYS(nkpg);
3597 pmap_zero_page(paddr);
3598 pd = pmap_pd(&kernel_pmap, kstart);
3600 newpd = (pdp_entry_t)
3602 kernel_pmap.pmap_bits[PG_V_IDX] |
3603 kernel_pmap.pmap_bits[PG_RW_IDX] |
3604 kernel_pmap.pmap_bits[PG_A_IDX]);
3605 atomic_swap_long(pd, newpd);
3608 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3612 continue; /* try again */
3615 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3616 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3617 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3618 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3619 kstart = vm_map_max(&kernel_map);
3628 * This index is bogus, but out of the way
3630 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3633 VM_ALLOC_INTERRUPT);
3635 panic("pmap_growkernel: no memory to grow kernel");
3638 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3639 pmap_zero_page(ptppaddr);
3640 newpt = (pd_entry_t)(ptppaddr |
3641 kernel_pmap.pmap_bits[PG_V_IDX] |
3642 kernel_pmap.pmap_bits[PG_RW_IDX] |
3643 kernel_pmap.pmap_bits[PG_A_IDX]);
3644 atomic_swap_long(pt, newpt);
3646 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3647 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3649 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3650 kstart = vm_map_max(&kernel_map);
3656 * Only update kernel_vm_end for areas below KERNBASE.
3658 if (update_kernel_vm_end && kernel_vm_end < kstart)
3659 kernel_vm_end = kstart;
3663 * Add a reference to the specified pmap.
3666 pmap_reference(pmap_t pmap)
3669 atomic_add_int(&pmap->pm_count, 1);
3672 /***************************************************
3673 * page management routines.
3674 ***************************************************/
3677 * Hold a pv without locking it
3680 pv_hold(pv_entry_t pv)
3682 atomic_add_int(&pv->pv_hold, 1);
3686 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3687 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3690 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3691 * pv list via its page) must be held by the caller in order to stabilize
3695 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3700 * Critical path shortcut expects pv to already have one ref
3701 * (for the pv->pv_pmap).
3703 count = pv->pv_hold;
3706 if ((count & PV_HOLD_LOCKED) == 0) {
3707 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3708 (count + 1) | PV_HOLD_LOCKED)) {
3711 pv->pv_line = lineno;
3716 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3724 * Drop a previously held pv_entry which could not be locked, allowing its
3727 * Must not be called with a spinlock held as we might zfree() the pv if it
3728 * is no longer associated with a pmap and this was the last hold count.
3731 pv_drop(pv_entry_t pv)
3736 count = pv->pv_hold;
3738 KKASSERT((count & PV_HOLD_MASK) > 0);
3739 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3740 (PV_HOLD_LOCKED | 1));
3741 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3742 if ((count & PV_HOLD_MASK) == 1) {
3744 if (pmap_enter_debug > 0) {
3746 kprintf("pv_drop: free pv %p\n", pv);
3749 KKASSERT(count == 1);
3750 KKASSERT(pv->pv_pmap == NULL);
3760 * Find or allocate the requested PV entry, returning a locked, held pv.
3762 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3763 * for the caller and one representing the pmap and vm_page association.
3765 * If (*isnew) is zero, the returned pv will have only one hold count.
3767 * Since both associations can only be adjusted while the pv is locked,
3768 * together they represent just one additional hold.
3772 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3774 struct mdglobaldata *md = mdcpu;
3782 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3785 pnew = md->gd_newpv; /* might race NULL */
3786 md->gd_newpv = NULL;
3791 pnew = zalloc(pvzone);
3793 spin_lock_shared(&pmap->pm_spin);
3798 pv = pv_entry_lookup(pmap, pindex);
3803 * Requires exclusive pmap spinlock
3805 if (pmap_excl == 0) {
3807 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3808 spin_unlock_shared(&pmap->pm_spin);
3809 spin_lock(&pmap->pm_spin);
3815 * We need to block if someone is holding our
3816 * placemarker. As long as we determine the
3817 * placemarker has not been aquired we do not
3818 * need to get it as acquision also requires
3819 * the pmap spin lock.
3821 * However, we can race the wakeup.
3823 pmark = pmap_placemarker_hash(pmap, pindex);
3825 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3826 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3827 tsleep_interlock(pmark, 0);
3828 if (((*pmark ^ pindex) &
3829 ~PM_PLACEMARK_WAKEUP) == 0) {
3830 spin_unlock(&pmap->pm_spin);
3831 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3832 spin_lock(&pmap->pm_spin);
3838 * Setup the new entry
3840 pnew->pv_pmap = pmap;
3841 pnew->pv_pindex = pindex;
3842 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3845 pnew->pv_func = func;
3846 pnew->pv_line = lineno;
3847 if (pnew->pv_line_lastfree > 0) {
3848 pnew->pv_line_lastfree =
3849 -pnew->pv_line_lastfree;
3852 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3853 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3854 spin_unlock(&pmap->pm_spin);
3857 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3862 * We already have an entry, cleanup the staged pnew if
3863 * we can get the lock, otherwise block and retry.
3865 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3867 spin_unlock(&pmap->pm_spin);
3869 spin_unlock_shared(&pmap->pm_spin);
3871 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3873 zfree(pvzone, pnew);
3876 if (md->gd_newpv == NULL)
3877 md->gd_newpv = pnew;
3879 zfree(pvzone, pnew);
3882 KKASSERT(pv->pv_pmap == pmap &&
3883 pv->pv_pindex == pindex);
3888 spin_unlock(&pmap->pm_spin);
3889 _pv_lock(pv PMAP_DEBUG_COPY);
3891 spin_lock(&pmap->pm_spin);
3893 spin_unlock_shared(&pmap->pm_spin);
3894 _pv_lock(pv PMAP_DEBUG_COPY);
3896 spin_lock_shared(&pmap->pm_spin);
3903 * Find the requested PV entry, returning a locked+held pv or NULL
3907 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3912 spin_lock_shared(&pmap->pm_spin);
3917 pv = pv_entry_lookup(pmap, pindex);
3920 * Block if there is ANY placemarker. If we are to
3921 * return it, we must also aquire the spot, so we
3922 * have to block even if the placemarker is held on
3923 * a different address.
3925 * OPTIMIZATION: If pmarkp is passed as NULL the
3926 * caller is just probing (or looking for a real
3927 * pv_entry), and in this case we only need to check
3928 * to see if the placemarker matches pindex.
3933 * Requires exclusive pmap spinlock
3935 if (pmap_excl == 0) {
3937 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3938 spin_unlock_shared(&pmap->pm_spin);
3939 spin_lock(&pmap->pm_spin);
3944 pmark = pmap_placemarker_hash(pmap, pindex);
3946 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3947 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3948 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3949 tsleep_interlock(pmark, 0);
3950 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3951 ((*pmark ^ pindex) &
3952 ~PM_PLACEMARK_WAKEUP) == 0) {
3953 spin_unlock(&pmap->pm_spin);
3954 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3955 spin_lock(&pmap->pm_spin);
3960 if (atomic_swap_long(pmark, pindex) !=
3962 panic("_pv_get: pmark race");
3966 spin_unlock(&pmap->pm_spin);
3969 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3971 spin_unlock(&pmap->pm_spin);
3973 spin_unlock_shared(&pmap->pm_spin);
3974 KKASSERT(pv->pv_pmap == pmap &&
3975 pv->pv_pindex == pindex);
3979 spin_unlock(&pmap->pm_spin);
3980 _pv_lock(pv PMAP_DEBUG_COPY);
3982 spin_lock(&pmap->pm_spin);
3984 spin_unlock_shared(&pmap->pm_spin);
3985 _pv_lock(pv PMAP_DEBUG_COPY);
3987 spin_lock_shared(&pmap->pm_spin);
3993 * Lookup, hold, and attempt to lock (pmap,pindex).
3995 * If the entry does not exist NULL is returned and *errorp is set to 0
3997 * If the entry exists and could be successfully locked it is returned and
3998 * errorp is set to 0.
4000 * If the entry exists but could NOT be successfully locked it is returned
4001 * held and *errorp is set to 1.
4003 * If the entry is placemarked by someone else NULL is returned and *errorp
4008 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
4012 spin_lock_shared(&pmap->pm_spin);
4014 pv = pv_entry_lookup(pmap, pindex);
4018 pmark = pmap_placemarker_hash(pmap, pindex);
4020 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
4022 } else if (pmarkp &&
4023 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
4027 * Can't set a placemark with a NULL pmarkp, or if
4028 * pmarkp is non-NULL but we failed to set our
4035 spin_unlock_shared(&pmap->pm_spin);
4041 * XXX This has problems if the lock is shared, why?
4043 if (pv_hold_try(pv)) {
4044 spin_unlock_shared(&pmap->pm_spin);
4046 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
4047 return(pv); /* lock succeeded */
4049 spin_unlock_shared(&pmap->pm_spin);
4052 return (pv); /* lock failed */
4056 * Lock a held pv, keeping the hold count
4060 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
4065 count = pv->pv_hold;
4067 if ((count & PV_HOLD_LOCKED) == 0) {
4068 if (atomic_cmpset_int(&pv->pv_hold, count,
4069 count | PV_HOLD_LOCKED)) {
4072 pv->pv_line = lineno;
4078 tsleep_interlock(pv, 0);
4079 if (atomic_cmpset_int(&pv->pv_hold, count,
4080 count | PV_HOLD_WAITING)) {
4082 if (pmap_enter_debug > 0) {
4084 kprintf("pv waiting on %s:%d\n",
4085 pv->pv_func, pv->pv_line);
4088 tsleep(pv, PINTERLOCKED, "pvwait", hz);
4095 * Unlock a held and locked pv, keeping the hold count.
4099 pv_unlock(pv_entry_t pv)
4104 count = pv->pv_hold;
4106 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
4107 (PV_HOLD_LOCKED | 1));
4108 if (atomic_cmpset_int(&pv->pv_hold, count,
4110 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
4111 if (count & PV_HOLD_WAITING)
4119 * Unlock and drop a pv. If the pv is no longer associated with a pmap
4120 * and the hold count drops to zero we will free it.
4122 * Caller should not hold any spin locks. We are protected from hold races
4123 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
4124 * lock held. A pv cannot be located otherwise.
4128 pv_put(pv_entry_t pv)
4131 if (pmap_enter_debug > 0) {
4133 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
4138 * Normal put-aways must have a pv_m associated with the pv,
4139 * but allow the case where the pv has been destructed due
4140 * to pmap_dynamic_delete.
4142 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
4145 * Fast - shortcut most common condition
4147 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
4158 * Remove the pmap association from a pv, require that pv_m already be removed,
4159 * then unlock and drop the pv. Any pte operations must have already been
4160 * completed. This call may result in a last-drop which will physically free
4163 * Removing the pmap association entails an additional drop.
4165 * pv must be exclusively locked on call and will be disposed of on return.
4169 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
4174 pv->pv_func_lastfree = func;
4175 pv->pv_line_lastfree = lineno;
4177 KKASSERT(pv->pv_m == NULL);
4178 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
4179 (PV_HOLD_LOCKED|1));
4180 if ((pmap = pv->pv_pmap) != NULL) {
4181 spin_lock(&pmap->pm_spin);
4182 KKASSERT(pv->pv_pmap == pmap);
4183 if (pmap->pm_pvhint_pt == pv)
4184 pmap->pm_pvhint_pt = NULL;
4185 if (pmap->pm_pvhint_pte == pv)
4186 pmap->pm_pvhint_pte = NULL;
4187 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
4188 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4191 spin_unlock(&pmap->pm_spin);
4194 * Try to shortcut three atomic ops, otherwise fall through
4195 * and do it normally. Drop two refs and the lock all in
4199 vm_page_unwire_quick(pvp->pv_m);
4200 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
4202 if (pmap_enter_debug > 0) {
4204 kprintf("pv_free: free pv %p\n", pv);
4210 pv_drop(pv); /* ref for pv_pmap */
4217 * This routine is very drastic, but can save the system
4225 static int warningdone=0;
4227 if (pmap_pagedaemon_waken == 0)
4229 pmap_pagedaemon_waken = 0;
4230 if (warningdone < 5) {
4231 kprintf("pmap_collect: collecting pv entries -- "
4232 "suggest increasing PMAP_SHPGPERPROC\n");
4236 for (i = 0; i < vm_page_array_size; i++) {
4237 m = &vm_page_array[i];
4238 if (m->wire_count || m->hold_count)
4240 if (vm_page_busy_try(m, TRUE) == 0) {
4241 if (m->wire_count == 0 && m->hold_count == 0) {
4250 * Scan the pmap for active page table entries and issue a callback.
4251 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4252 * its parent page table.
4254 * pte_pv will be NULL if the page or page table is unmanaged.
4255 * pt_pv will point to the page table page containing the pte for the page.
4257 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4258 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4259 * process pmap's PD and page to the callback function. This can be
4260 * confusing because the pt_pv is really a pd_pv, and the target page
4261 * table page is simply aliased by the pmap and not owned by it.
4263 * It is assumed that the start and end are properly rounded to the page size.
4265 * It is assumed that PD pages and above are managed and thus in the RB tree,
4266 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4268 struct pmap_scan_info {
4272 vm_pindex_t sva_pd_pindex;
4273 vm_pindex_t eva_pd_pindex;
4274 void (*func)(pmap_t, struct pmap_scan_info *,
4275 pv_entry_t, vm_pindex_t *, pv_entry_t,
4277 pt_entry_t *, void *);
4279 pmap_inval_bulk_t bulk_core;
4280 pmap_inval_bulk_t *bulk;
4285 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4286 static int pmap_scan_callback(pv_entry_t pv, void *data);
4289 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4291 struct pmap *pmap = info->pmap;
4292 pv_entry_t pd_pv; /* A page directory PV */
4293 pv_entry_t pt_pv; /* A page table PV */
4294 pv_entry_t pte_pv; /* A page table entry PV */
4295 vm_pindex_t *pte_placemark;
4296 vm_pindex_t *pt_placemark;
4299 struct pv_entry dummy_pv;
4304 if (info->sva == info->eva)
4307 info->bulk = &info->bulk_core;
4308 pmap_inval_bulk_init(&info->bulk_core, pmap);
4314 * Hold the token for stability; if the pmap is empty we have nothing
4318 if (pmap->pm_stats.resident_count == 0) {
4326 * Special handling for scanning one page, which is a very common
4327 * operation (it is?).
4329 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4331 if (info->sva + PAGE_SIZE == info->eva) {
4332 if (info->sva >= VM_MAX_USER_ADDRESS) {
4334 * Kernel mappings do not track wire counts on
4335 * page table pages and only maintain pd_pv and
4336 * pte_pv levels so pmap_scan() works.
4339 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4341 ptep = vtopte(info->sva);
4344 * User pages which are unmanaged will not have a
4345 * pte_pv. User page table pages which are unmanaged
4346 * (shared from elsewhere) will also not have a pt_pv.
4347 * The func() callback will pass both pte_pv and pt_pv
4348 * as NULL in that case.
4350 * We hold pte_placemark across the operation for
4353 * WARNING! We must hold pt_placemark across the
4354 * *ptep test to prevent misintepreting
4355 * a non-zero *ptep as a shared page
4356 * table page. Hold it across the function
4357 * callback as well for SMP safety.
4359 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4361 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4363 if (pt_pv == NULL) {
4364 KKASSERT(pte_pv == NULL);
4365 pd_pv = pv_get(pmap,
4366 pmap_pd_pindex(info->sva),
4369 ptep = pv_pte_lookup(pd_pv,
4370 pmap_pt_index(info->sva));
4372 info->func(pmap, info,
4378 pv_placemarker_wakeup(pmap,
4383 pv_placemarker_wakeup(pmap,
4386 pv_placemarker_wakeup(pmap, pte_placemark);
4389 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4393 * NOTE: *ptep can't be ripped out from under us if we hold
4394 * pte_pv (or pte_placemark) locked, but bits can
4400 KKASSERT(pte_pv == NULL);
4401 pv_placemarker_wakeup(pmap, pte_placemark);
4402 } else if (pte_pv) {
4403 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4404 pmap->pmap_bits[PG_V_IDX])) ==
4405 (pmap->pmap_bits[PG_MANAGED_IDX] |
4406 pmap->pmap_bits[PG_V_IDX]),
4407 ("badA *ptep %016lx/%016lx sva %016lx pte_pv %p",
4408 *ptep, oldpte, info->sva, pte_pv));
4409 info->func(pmap, info, pte_pv, NULL, pt_pv, 0,
4410 info->sva, ptep, info->arg);
4412 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4413 pmap->pmap_bits[PG_V_IDX])) ==
4414 pmap->pmap_bits[PG_V_IDX],
4415 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4416 *ptep, oldpte, info->sva));
4417 info->func(pmap, info, NULL, pte_placemark, pt_pv, 0,
4418 info->sva, ptep, info->arg);
4423 pmap_inval_bulk_flush(info->bulk);
4428 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4431 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4432 * bounds, resulting in a pd_pindex of 0. To solve the
4433 * problem we use an inclusive range.
4435 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4436 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4438 if (info->sva >= VM_MAX_USER_ADDRESS) {
4440 * The kernel does not currently maintain any pv_entry's for
4441 * higher-level page tables.
4443 bzero(&dummy_pv, sizeof(dummy_pv));
4444 dummy_pv.pv_pindex = info->sva_pd_pindex;
4445 spin_lock(&pmap->pm_spin);
4446 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4447 pmap_scan_callback(&dummy_pv, info);
4448 ++dummy_pv.pv_pindex;
4449 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4452 spin_unlock(&pmap->pm_spin);
4455 * User page tables maintain local PML4, PDP, and PD
4456 * pv_entry's at the very least. PT pv's might be
4457 * unmanaged and thus not exist. PTE pv's might be
4458 * unmanaged and thus not exist.
4460 spin_lock(&pmap->pm_spin);
4461 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4462 pmap_scan_callback, info);
4463 spin_unlock(&pmap->pm_spin);
4465 pmap_inval_bulk_flush(info->bulk);
4469 * WARNING! pmap->pm_spin held
4471 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4472 * bounds, resulting in a pd_pindex of 0. To solve the
4473 * problem we use an inclusive range.
4476 pmap_scan_cmp(pv_entry_t pv, void *data)
4478 struct pmap_scan_info *info = data;
4479 if (pv->pv_pindex < info->sva_pd_pindex)
4481 if (pv->pv_pindex > info->eva_pd_pindex)
4487 * pmap_scan() by PDs
4489 * WARNING! pmap->pm_spin held
4492 pmap_scan_callback(pv_entry_t pv, void *data)
4494 struct pmap_scan_info *info = data;
4495 struct pmap *pmap = info->pmap;
4496 pv_entry_t pd_pv; /* A page directory PV */
4497 pv_entry_t pt_pv; /* A page table PV */
4498 vm_pindex_t *pt_placemark;
4503 vm_offset_t va_next;
4504 vm_pindex_t pd_pindex;
4514 * Pull the PD pindex from the pv before releasing the spinlock.
4516 * WARNING: pv is faked for kernel pmap scans.
4518 pd_pindex = pv->pv_pindex;
4519 spin_unlock(&pmap->pm_spin);
4520 pv = NULL; /* invalid after spinlock unlocked */
4523 * Calculate the page range within the PD. SIMPLE pmaps are
4524 * direct-mapped for the entire 2^64 address space. Normal pmaps
4525 * reflect the user and kernel address space which requires
4526 * cannonicalization w/regards to converting pd_pindex's back
4529 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4530 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4531 (sva & PML4_SIGNMASK)) {
4532 sva |= PML4_SIGNMASK;
4534 eva = sva + NBPDP; /* can overflow */
4535 if (sva < info->sva)
4537 if (eva < info->sva || eva > info->eva)
4541 * NOTE: kernel mappings do not track page table pages, only
4544 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4545 * However, for the scan to be efficient we try to
4546 * cache items top-down.
4551 for (; sva < eva; sva = va_next) {
4554 if (sva >= VM_MAX_USER_ADDRESS) {
4563 * PD cache, scan shortcut if it doesn't exist.
4565 if (pd_pv == NULL) {
4566 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4567 } else if (pd_pv->pv_pmap != pmap ||
4568 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4570 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4572 if (pd_pv == NULL) {
4573 va_next = (sva + NBPDP) & ~PDPMASK;
4582 * NOTE: The cached pt_pv can be removed from the pmap when
4583 * pmap_dynamic_delete is enabled.
4585 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4586 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4590 if (pt_pv == NULL) {
4591 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4592 &pt_placemark, &error);
4594 pv_put(pd_pv); /* lock order */
4601 pv_placemarker_wait(pmap, pt_placemark);
4606 /* may have to re-check later if pt_pv is NULL here */
4610 * If pt_pv is NULL we either have an shared page table
4611 * page and must issue a callback specific to that case,
4612 * or there is no page table page.
4614 * Either way we can skip the page table page.
4616 * WARNING! pt_pv can also be NULL due to a pv creation
4617 * race where we find it to be NULL and then
4618 * later see a pte_pv. But its possible the pt_pv
4619 * got created inbetween the two operations, so
4622 if (pt_pv == NULL) {
4624 * Possible unmanaged (shared from another pmap)
4627 * WARNING! We must hold pt_placemark across the
4628 * *ptep test to prevent misintepreting
4629 * a non-zero *ptep as a shared page
4630 * table page. Hold it across the function
4631 * callback as well for SMP safety.
4633 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4634 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4635 info->func(pmap, info, NULL, pt_placemark,
4637 sva, ptep, info->arg);
4639 pv_placemarker_wakeup(pmap, pt_placemark);
4643 * Done, move to next page table page.
4645 va_next = (sva + NBPDR) & ~PDRMASK;
4652 * From this point in the loop testing pt_pv for non-NULL
4653 * means we are in UVM, else if it is NULL we are in KVM.
4655 * Limit our scan to either the end of the va represented
4656 * by the current page table page, or to the end of the
4657 * range being removed.
4660 va_next = (sva + NBPDR) & ~PDRMASK;
4667 * Scan the page table for pages. Some pages may not be
4668 * managed (might not have a pv_entry).
4670 * There is no page table management for kernel pages so
4671 * pt_pv will be NULL in that case, but otherwise pt_pv
4672 * is non-NULL, locked, and referenced.
4676 * At this point a non-NULL pt_pv means a UVA, and a NULL
4677 * pt_pv means a KVA.
4680 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4684 while (sva < va_next) {
4686 vm_pindex_t *pte_placemark;
4689 * Yield every 64 pages, stop if requested.
4691 if ((++info->count & 63) == 0)
4697 * We can shortcut our scan if *ptep == 0. This is
4698 * an unlocked check.
4708 * Acquire the related pte_pv, if any. If *ptep == 0
4709 * the related pte_pv should not exist, but if *ptep
4710 * is not zero the pte_pv may or may not exist (e.g.
4711 * will not exist for an unmanaged page).
4713 * However a multitude of races are possible here
4714 * so if we cannot lock definite state we clean out
4715 * our cache and break the inner while() loop to
4716 * force a loop up to the top of the for().
4718 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4719 * validity instead of looping up?
4721 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4722 &pte_placemark, &error);
4725 pv_put(pd_pv); /* lock order */
4729 pv_put(pt_pv); /* lock order */
4732 if (pte_pv) { /* block */
4737 pv_placemarker_wait(pmap,
4740 va_next = sva; /* retry */
4745 * Reload *ptep after successfully locking the
4746 * pindex. If *ptep == 0 we had better NOT have a
4753 kprintf("Unexpected non-NULL pte_pv "
4755 "*ptep = %016lx/%016lx\n",
4756 pte_pv, pt_pv, *ptep, oldpte);
4757 panic("Unexpected non-NULL pte_pv");
4759 pv_placemarker_wakeup(pmap, pte_placemark);
4767 * We can't hold pd_pv across the callback (because
4768 * we don't pass it to the callback and the callback
4772 vm_page_wire_quick(pd_pv->pv_m);
4777 * Ready for the callback. The locked pte_pv (if any)
4778 * is consumed by the callback. pte_pv will exist if
4779 * the page is managed, and will not exist if it
4782 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4787 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4788 ("badC *ptep %016lx/%016lx sva %016lx "
4790 *ptep, oldpte, sva, pte_pv));
4792 * We must unlock pd_pv across the callback
4793 * to avoid deadlocks on any recursive
4794 * disposal. Re-check that it still exists
4797 * Call target disposes of pte_pv and may
4798 * destroy but will not dispose of pt_pv.
4800 info->func(pmap, info, pte_pv, NULL,
4802 sva, ptep, info->arg);
4807 * We must unlock pd_pv across the callback
4808 * to avoid deadlocks on any recursive
4809 * disposal. Re-check that it still exists
4812 * Call target disposes of pte_pv or
4813 * pte_placemark and may destroy but will
4814 * not dispose of pt_pv.
4816 KASSERT(pte_pv == NULL &&
4817 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4818 ("badD *ptep %016lx/%016lx sva %016lx "
4819 "pte_pv %p pte_pv->pv_m %p ",
4821 pte_pv, (pte_pv ? pte_pv->pv_m : NULL)));
4825 info->func(pmap, info,
4828 sva, ptep, info->arg);
4830 info->func(pmap, info,
4831 NULL, pte_placemark,
4833 sva, ptep, info->arg);
4838 vm_page_unwire_quick(pd_pv->pv_m);
4839 if (pd_pv->pv_pmap == NULL) {
4840 va_next = sva; /* retry */
4846 * NOTE: The cached pt_pv can be removed from the
4847 * pmap when pmap_dynamic_delete is enabled,
4848 * which will cause ptep to become stale.
4850 * This also means that no pages remain under
4851 * the PT, so we can just break out of the inner
4852 * loop and let the outer loop clean everything
4855 if (pt_pv && pt_pv->pv_pmap != pmap)
4870 if ((++info->count & 7) == 0)
4874 * Relock before returning.
4876 spin_lock(&pmap->pm_spin);
4881 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4883 struct pmap_scan_info info;
4888 info.func = pmap_remove_callback;
4890 pmap_scan(&info, 1);
4893 if (eva - sva < 1024*1024) {
4895 cpu_invlpg((void *)sva);
4903 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4905 struct pmap_scan_info info;
4910 info.func = pmap_remove_callback;
4912 pmap_scan(&info, 0);
4916 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4917 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
4918 pv_entry_t pt_pv, int sharept,
4919 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4927 * This will also drop pt_pv's wire_count. Note that
4928 * terminal pages are not wired based on mmu presence.
4930 * NOTE: If this is the kernel_pmap, pt_pv can be NULL.
4932 KKASSERT(pte_pv->pv_m != NULL);
4933 pmap_remove_pv_pte(pte_pv, pt_pv, info->bulk, 2);
4934 pte_pv = NULL; /* safety */
4937 * Recursively destroy higher-level page tables.
4939 * This is optional. If we do not, they will still
4940 * be destroyed when the process exits.
4942 * NOTE: Do not destroy pv_entry's with extra hold refs,
4943 * a caller may have unlocked it and intends to
4944 * continue to use it.
4946 if (pmap_dynamic_delete &&
4949 pt_pv->pv_m->wire_count == 1 &&
4950 (pt_pv->pv_hold & PV_HOLD_MASK) == 2 &&
4951 pt_pv->pv_pindex < pmap_pml4_pindex()) {
4952 if (pmap_dynamic_delete == 2)
4953 kprintf("B %jd %08x\n", pt_pv->pv_pindex, pt_pv->pv_hold);
4954 pv_hold(pt_pv); /* extra hold */
4955 pmap_remove_pv_pte(pt_pv, NULL, info->bulk, 1);
4956 pv_lock(pt_pv); /* prior extra hold + relock */
4958 } else if (sharept == 0) {
4960 * Unmanaged pte (pte_placemark is non-NULL)
4962 * pt_pv's wire_count is still bumped by unmanaged pages
4963 * so we must decrement it manually.
4965 * We have to unwire the target page table page.
4967 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4968 if (pte & pmap->pmap_bits[PG_W_IDX])
4969 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4970 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4971 if (vm_page_unwire_quick(pt_pv->pv_m))
4972 panic("pmap_remove: insufficient wirecount");
4973 pv_placemarker_wakeup(pmap, pte_placemark);
4976 * Unmanaged page table (pt, pd, or pdp. Not pte) for
4977 * a shared page table.
4979 * pt_pv is actually the pd_pv for our pmap (not the shared
4982 * We have to unwire the target page table page and we
4983 * have to unwire our page directory page.
4985 * It is unclear how we can invalidate a segment so we
4986 * invalidate -1 which invlidates the tlb.
4988 pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
4989 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4990 KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
4991 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
4992 panic("pmap_remove: shared pgtable1 bad wirecount");
4993 if (vm_page_unwire_quick(pt_pv->pv_m))
4994 panic("pmap_remove: shared pgtable2 bad wirecount");
4995 pv_placemarker_wakeup(pmap, pte_placemark);
5000 * Removes this physical page from all physical maps in which it resides.
5001 * Reflects back modify bits to the pager.
5003 * This routine may not be called from an interrupt.
5007 pmap_remove_all(vm_page_t m)
5010 pmap_inval_bulk_t bulk;
5013 if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
5016 vm_page_spin_lock(m);
5017 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
5018 if (pv->pv_m != m) {
5019 kprintf("pmap_remove_all FAILURE\n");
5020 kprintf("pv %p pv->pv_m %p m %p\n", pv, pv->pv_m, m);
5021 kprintf("pvflags %08x\n", pv->pv_flags);
5024 KKASSERT(pv->pv_m == m);
5025 if (pv_hold_try(pv)) {
5026 vm_page_spin_unlock(m);
5028 vm_page_spin_unlock(m);
5031 vm_page_spin_lock(m);
5034 KKASSERT(pv->pv_pmap && pv->pv_m == m);
5037 * Holding no spinlocks, pv is locked. Once we scrap
5038 * pv we can no longer use it as a list iterator (but
5039 * we are doing a TAILQ_FIRST() so we are ok).
5041 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5042 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5043 pv = NULL; /* safety */
5044 pmap_inval_bulk_flush(&bulk);
5045 vm_page_spin_lock(m);
5047 if (m->flags & PG_MAPPED) {
5050 vm_map_backing_t ba;
5052 spin_lock(&obj->spin);
5053 TAILQ_FOREACH(ba, &obj->backing_list, entry) {
5055 pmap_backing_match(ba, m, pmap_backing_remove);
5058 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
5059 spin_unlock(&obj->spin);
5061 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
5065 KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
5066 vm_page_spin_unlock(m);
5070 * Removes the page from a particular pmap
5073 pmap_remove_specific(pmap_t pmap, vm_page_t m)
5076 pmap_inval_bulk_t bulk;
5078 if (!pmap_initialized)
5082 vm_page_spin_lock(m);
5083 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5084 if (pv->pv_pmap != pmap)
5086 KKASSERT(pv->pv_m == m);
5087 if (pv_hold_try(pv)) {
5088 vm_page_spin_unlock(m);
5090 vm_page_spin_unlock(m);
5095 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
5098 * Holding no spinlocks, pv is locked. Once gone it can't
5099 * be used as an iterator. In fact, because we couldn't
5100 * necessarily lock it atomically it may have moved within
5101 * the list and ALSO cannot be used as an iterator.
5103 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5104 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5105 pv = NULL; /* safety */
5106 pmap_inval_bulk_flush(&bulk);
5109 vm_page_spin_unlock(m);
5113 * Set the physical protection on the specified range of this map
5114 * as requested. This function is typically only used for debug watchpoints
5117 * This function may not be called from an interrupt if the map is
5118 * not the kernel_pmap.
5120 * NOTE! For shared page table pages we just unmap the page.
5123 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
5125 struct pmap_scan_info info;
5126 /* JG review for NX */
5130 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
5131 pmap_remove(pmap, sva, eva);
5134 if (prot & VM_PROT_WRITE)
5139 info.func = pmap_protect_callback;
5141 pmap_scan(&info, 1);
5146 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
5147 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
5148 pv_entry_t pt_pv, int sharept,
5149 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
5160 KKASSERT(pte_pv->pv_m != NULL);
5162 if (pbits & pmap->pmap_bits[PG_A_IDX]) {
5163 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5164 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5165 KKASSERT(m == pte_pv->pv_m);
5166 vm_page_flag_set(m, PG_REFERENCED);
5168 cbits &= ~pmap->pmap_bits[PG_A_IDX];
5170 if (pbits & pmap->pmap_bits[PG_M_IDX]) {
5171 if (pmap_track_modified(pte_pv->pv_pindex)) {
5172 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5174 m = PHYS_TO_VM_PAGE(pbits &
5179 cbits &= ~pmap->pmap_bits[PG_M_IDX];
5182 } else if (sharept) {
5184 * Unmanaged page table, pt_pv is actually the pd_pv
5185 * for our pmap (not the object's shared pmap).
5187 * When asked to protect something in a shared page table
5188 * page we just unmap the page table page. We have to
5189 * invalidate the tlb in this situation.
5191 * XXX Warning, shared page tables will not be used for
5192 * OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
5193 * so PHYS_TO_VM_PAGE() should be safe here.
5195 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
5196 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
5197 panic("pmap_protect: pgtable1 pg bad wirecount");
5198 if (vm_page_unwire_quick(pt_pv->pv_m))
5199 panic("pmap_protect: pgtable2 pg bad wirecount");
5202 /* else unmanaged page, adjust bits, no wire changes */
5205 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
5207 if (pmap_enter_debug > 0) {
5209 kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
5210 "pt_pv=%p cbits=%08lx\n",
5216 if (pbits != cbits) {
5219 xva = (sharept) ? (vm_offset_t)-1 : va;
5220 if (!pmap_inval_smp_cmpset(pmap, xva,
5221 ptep, pbits, cbits)) {
5229 pv_placemarker_wakeup(pmap, pte_placemark);
5233 * Insert the vm_page (m) at the virtual address (va), replacing any prior
5234 * mapping at that address. Set protection and wiring as requested.
5236 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5237 * possible. If it is we enter the page into the appropriate shared pmap
5238 * hanging off the related VM object instead of the passed pmap, then we
5239 * share the page table page from the VM object's pmap into the current pmap.
5241 * NOTE: This routine MUST insert the page into the pmap now, it cannot
5244 * NOTE: If (m) is PG_UNMANAGED it may also be a temporary fake vm_page_t.
5248 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5249 boolean_t wired, vm_map_entry_t entry)
5251 pv_entry_t pt_pv; /* page table */
5252 pv_entry_t pte_pv; /* page table entry */
5253 vm_pindex_t *pte_placemark;
5256 pt_entry_t origpte, newpte;
5261 va = trunc_page(va);
5262 #ifdef PMAP_DIAGNOSTIC
5264 panic("pmap_enter: toobig");
5265 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5266 panic("pmap_enter: invalid to pmap_enter page table "
5267 "pages (va: 0x%lx)", va);
5269 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
5270 kprintf("Warning: pmap_enter called on UVA with "
5273 db_print_backtrace();
5276 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
5277 kprintf("Warning: pmap_enter called on KVA without"
5280 db_print_backtrace();
5285 * Get locked PV entries for our new page table entry (pte_pv or
5286 * pte_placemark) and for its parent page table (pt_pv). We need
5287 * the parent so we can resolve the location of the ptep.
5289 * Only hardware MMU actions can modify the ptep out from
5292 * if (m) is fictitious or unmanaged we do not create a managing
5293 * pte_pv for it. Any pre-existing page's management state must
5294 * match (avoiding code complexity).
5296 * If the pmap is still being initialized we assume existing
5299 * Kernel mapppings do not track page table pages (i.e. pt_pv).
5301 * WARNING! If replacing a managed mapping with an unmanaged mapping
5302 * pte_pv will wind up being non-NULL and must be handled
5305 if (pmap_initialized == FALSE) {
5308 pte_placemark = NULL;
5311 } else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
5312 pmap_softwait(pmap);
5313 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5314 KKASSERT(pte_pv == NULL);
5315 if (va >= VM_MAX_USER_ADDRESS) {
5319 pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
5321 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5325 KASSERT(origpte == 0 ||
5326 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0,
5327 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5329 pmap_softwait(pmap);
5330 if (va >= VM_MAX_USER_ADDRESS) {
5332 * Kernel map, pv_entry-tracked.
5335 pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
5341 pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
5343 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5345 pte_placemark = NULL; /* safety */
5348 KASSERT(origpte == 0 ||
5349 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]),
5350 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5353 pa = VM_PAGE_TO_PHYS(m);
5354 opa = origpte & PG_FRAME;
5357 * Calculate the new PTE. Note that pte_pv alone does not mean
5358 * the new pte_pv is managed, it could exist because the old pte
5359 * was managed even if the new one is not.
5361 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5362 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5364 newpte |= pmap->pmap_bits[PG_W_IDX];
5365 if (va < VM_MAX_USER_ADDRESS)
5366 newpte |= pmap->pmap_bits[PG_U_IDX];
5367 if (pte_pv && (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) == 0)
5368 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5369 // if (pmap == &kernel_pmap)
5370 // newpte |= pgeflag;
5371 newpte |= pmap->pmap_cache_bits[m->pat_mode];
5372 if (m->flags & PG_FICTITIOUS)
5373 newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
5376 * It is possible for multiple faults to occur in threaded
5377 * environments, the existing pte might be correct.
5379 if (((origpte ^ newpte) &
5380 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5381 pmap->pmap_bits[PG_A_IDX])) == 0) {
5386 * Ok, either the address changed or the protection or wiring
5389 * Clear the current entry, interlocking the removal. For managed
5390 * pte's this will also flush the modified state to the vm_page.
5391 * Atomic ops are mandatory in order to ensure that PG_M events are
5392 * not lost during any transition.
5394 * WARNING: The caller has busied the new page but not the original
5395 * vm_page which we are trying to replace. Because we hold
5396 * the pte_pv lock, but have not busied the page, PG bits
5397 * can be cleared out from under us.
5400 if (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
5402 * Old page was managed. Expect pte_pv to exist.
5403 * (it might also exist if the old page was unmanaged).
5405 * NOTE: pt_pv won't exist for a kernel page
5406 * (managed or otherwise).
5408 * NOTE: We may be reusing the pte_pv so we do not
5409 * destroy it in pmap_remove_pv_pte().
5411 KKASSERT(pte_pv && pte_pv->pv_m);
5412 if (prot & VM_PROT_NOSYNC) {
5413 pmap_remove_pv_pte(pte_pv, pt_pv, NULL, 0);
5415 pmap_inval_bulk_t bulk;
5417 pmap_inval_bulk_init(&bulk, pmap);
5418 pmap_remove_pv_pte(pte_pv, pt_pv, &bulk, 0);
5419 pmap_inval_bulk_flush(&bulk);
5421 pmap_remove_pv_page(pte_pv);
5422 /* will either set pte_pv->pv_m or pv_free() later */
5425 * Old page was not managed. If we have a pte_pv
5426 * it better not have a pv_m assigned to it. If the
5427 * new page is managed the pte_pv will be destroyed
5428 * near the end (we need its interlock).
5430 * NOTE: We leave the wire count on the PT page
5431 * intact for the followup enter, but adjust
5432 * the wired-pages count on the pmap.
5434 KKASSERT(pte_pv == NULL);
5435 if (prot & VM_PROT_NOSYNC) {
5437 * NOSYNC (no mmu sync) requested.
5439 (void)pte_load_clear(ptep);
5440 cpu_invlpg((void *)va);
5445 pmap_inval_smp(pmap, va, 1, ptep, 0);
5449 * We must adjust pm_stats manually for unmanaged
5453 atomic_add_long(&pmap->pm_stats.
5454 resident_count, -1);
5456 if (origpte & pmap->pmap_bits[PG_W_IDX]) {
5457 atomic_add_long(&pmap->pm_stats.
5461 KKASSERT(*ptep == 0);
5465 if (pmap_enter_debug > 0) {
5467 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5468 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5470 origpte, newpte, ptep,
5471 pte_pv, pt_pv, opa, prot);
5475 if ((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5477 * Entering an unmanaged page. We must wire the pt_pv unless
5478 * we retained the wiring from an unmanaged page we had
5479 * removed (if we retained it via pte_pv that will go away
5482 if (pt_pv && (opa == 0 ||
5483 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]))) {
5484 vm_page_wire_quick(pt_pv->pv_m);
5487 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5490 * Unmanaged pages need manual resident_count tracking.
5493 atomic_add_long(&pt_pv->pv_pmap->pm_stats.
5496 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5497 vm_page_flag_set(m, PG_WRITEABLE);
5500 * Entering a managed page. Our pte_pv takes care of the
5501 * PT wiring, so if we had removed an unmanaged page before
5504 * We have to take care of the pmap wired count ourselves.
5506 * Enter on the PV list if part of our managed memory.
5509 if (m->object == NULL && pmap_pv_debug > 0) {
5511 kprintf("pte_m %p pv_entry %p NOOBJ\n", m, pte_pv);
5512 print_backtrace(16);
5515 KKASSERT(pte_pv && (pte_pv->pv_m == NULL || pte_pv->pv_m == m));
5516 vm_page_spin_lock(m);
5518 pmap_page_stats_adding(m);
5519 TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
5522 * Set vm_page flags. Avoid a cache mastership change if
5523 * the bits are already set.
5525 if ((m->flags & PG_MAPPED) == 0)
5526 vm_page_flag_set(m, PG_MAPPED);
5527 if ((newpte & pmap->pmap_bits[PG_RW_IDX]) &&
5528 (m->flags & PG_WRITEABLE) == 0) {
5529 vm_page_flag_set(m, PG_WRITEABLE);
5531 vm_page_spin_unlock(m);
5534 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5535 vm_page_unwire_quick(pt_pv->pv_m);
5539 * Adjust pmap wired pages count for new entry.
5542 atomic_add_long(&pte_pv->pv_pmap->pm_stats.
5548 * Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
5550 * User VMAs do not because those will be zero->non-zero, so no
5551 * stale entries to worry about at this point.
5553 * For KVM there appear to still be issues. Theoretically we
5554 * should be able to scrap the interlocks entirely but we
5557 if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL) {
5558 pmap_inval_smp(pmap, va, 1, ptep, newpte);
5560 origpte = atomic_swap_long(ptep, newpte);
5561 if (origpte & pmap->pmap_bits[PG_M_IDX]) {
5562 kprintf("pmap [M] race @ %016jx\n", va);
5563 atomic_set_long(ptep, pmap->pmap_bits[PG_M_IDX]);
5566 cpu_invlpg((void *)va);
5573 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5574 (m->flags & PG_MAPPED));
5577 * Cleanup the pv entry, allowing other accessors. If the new page
5578 * is not managed but we have a pte_pv (which was locking our
5579 * operation), we can free it now. pte_pv->pv_m should be NULL.
5581 if (pte_pv && (newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5582 pv_free(pte_pv, pt_pv);
5583 } else if (pte_pv) {
5585 } else if (pte_placemark) {
5586 pv_placemarker_wakeup(pmap, pte_placemark);
5593 * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
5594 * This code also assumes that the pmap has no pre-existing entry for this
5597 * This code currently may only be used on user pmaps, not kernel_pmap.
5600 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
5602 pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
5606 * Make a temporary mapping for a physical address. This is only intended
5607 * to be used for panic dumps.
5609 * The caller is responsible for calling smp_invltlb().
5612 pmap_kenter_temporary(vm_paddr_t pa, long i)
5614 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5615 return ((void *)crashdumpmap);
5618 #define MAX_INIT_PT (96)
5621 * This routine preloads the ptes for a given object into the specified pmap.
5622 * This eliminates the blast of soft faults on process startup and
5623 * immediately after an mmap.
5625 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5628 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
5629 vm_object_t object, vm_pindex_t pindex,
5630 vm_size_t size, int limit)
5632 struct rb_vm_page_scan_info info;
5637 * We can't preinit if read access isn't set or there is no pmap
5640 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5644 * We can't preinit if the pmap is not the current pmap
5646 lp = curthread->td_lwp;
5647 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5651 * Misc additional checks
5653 psize = x86_64_btop(size);
5655 if ((object->type != OBJT_VNODE) ||
5656 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5657 (object->resident_page_count > MAX_INIT_PT))) {
5661 if (pindex + psize > object->size) {
5662 if (object->size < pindex)
5664 psize = object->size - pindex;
5671 * If everything is segment-aligned do not pre-init here. Instead
5672 * allow the normal vm_fault path to pass a segment hint to
5673 * pmap_enter() which will then use an object-referenced shared
5676 if ((addr & SEG_MASK) == 0 &&
5677 (ctob(psize) & SEG_MASK) == 0 &&
5678 (ctob(pindex) & SEG_MASK) == 0) {
5683 * Use a red-black scan to traverse the requested range and load
5684 * any valid pages found into the pmap.
5686 * We cannot safely scan the object's memq without holding the
5689 info.start_pindex = pindex;
5690 info.end_pindex = pindex + psize - 1;
5695 info.object = object;
5698 * By using the NOLK scan, the callback function must be sure
5699 * to return -1 if the VM page falls out of the object.
5701 vm_object_hold_shared(object);
5702 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5703 pmap_object_init_pt_callback, &info);
5704 vm_object_drop(object);
5709 pmap_object_init_pt_callback(vm_page_t p, void *data)
5711 struct rb_vm_page_scan_info *info = data;
5712 vm_pindex_t rel_index;
5716 * don't allow an madvise to blow away our really
5717 * free pages allocating pv entries.
5719 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5720 vmstats.v_free_count < vmstats.v_free_reserved) {
5725 * Ignore list markers and ignore pages we cannot instantly
5726 * busy (while holding the object token).
5728 if (p->flags & PG_MARKER)
5733 if (vm_page_busy_try(p, TRUE))
5736 if (vm_page_sbusy_try(p))
5739 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5740 (p->flags & PG_FICTITIOUS) == 0) {
5741 if ((p->queue - p->pc) == PQ_CACHE) {
5742 if (hard_busy == 0) {
5743 vm_page_sbusy_drop(p);
5747 vm_page_deactivate(p);
5749 rel_index = p->pindex - info->start_pindex;
5750 pmap_enter_quick(info->pmap,
5751 info->addr + x86_64_ptob(rel_index), p);
5756 vm_page_sbusy_drop(p);
5759 * We are using an unlocked scan (that is, the scan expects its
5760 * current element to remain in the tree on return). So we have
5761 * to check here and abort the scan if it isn't.
5763 if (p->object != info->object)
5770 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5773 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5776 * XXX This is safe only because page table pages are not freed.
5779 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5783 /*spin_lock(&pmap->pm_spin);*/
5784 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5785 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5786 /*spin_unlock(&pmap->pm_spin);*/
5790 /*spin_unlock(&pmap->pm_spin);*/
5795 * Change the wiring attribute for a pmap/va pair. The mapping must already
5796 * exist in the pmap. The mapping may or may not be managed. The wiring in
5797 * the page is not changed, the page is returned so the caller can adjust
5798 * its wiring (the page is not locked in any way).
5800 * Wiring is not a hardware characteristic so there is no need to invalidate
5801 * TLB. However, in an SMP environment we must use a locked bus cycle to
5802 * update the pte (if we are not using the pmap_inval_*() API that is)...
5803 * it's ok to do this for simple wiring changes.
5806 pmap_unwire(pmap_t pmap, vm_offset_t va)
5817 * Assume elements in the kernel pmap are stable
5819 if (pmap == &kernel_pmap) {
5820 if (pmap_pt(pmap, va) == 0)
5822 ptep = pmap_pte_quick(pmap, va);
5823 if (pmap_pte_v(pmap, ptep)) {
5824 if (pmap_pte_w(pmap, ptep))
5825 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5826 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5827 pa = *ptep & PG_FRAME;
5828 m = PHYS_TO_VM_PAGE(pa);
5834 * We can only [un]wire pmap-local pages (we cannot wire
5837 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5841 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5842 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5847 if (pmap_pte_w(pmap, ptep)) {
5848 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5851 /* XXX else return NULL so caller doesn't unwire m ? */
5853 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5855 pa = *ptep & PG_FRAME;
5856 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5863 * Copy the range specified by src_addr/len from the source map to
5864 * the range dst_addr/len in the destination map.
5866 * This routine is only advisory and need not do anything.
5869 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5870 vm_size_t len, vm_offset_t src_addr)
5877 * Zero the specified physical page.
5879 * This function may be called from an interrupt and no locking is
5883 pmap_zero_page(vm_paddr_t phys)
5885 vm_offset_t va = PHYS_TO_DMAP(phys);
5887 pagezero((void *)va);
5893 * Zero part of a physical page by mapping it into memory and clearing
5894 * its contents with bzero.
5896 * off and size may not cover an area beyond a single hardware page.
5899 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5901 vm_offset_t virt = PHYS_TO_DMAP(phys);
5903 bzero((char *)virt + off, size);
5909 * Copy the physical page from the source PA to the target PA.
5910 * This function may be called from an interrupt. No locking
5914 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5916 vm_offset_t src_virt, dst_virt;
5918 src_virt = PHYS_TO_DMAP(src);
5919 dst_virt = PHYS_TO_DMAP(dst);
5920 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5924 * pmap_copy_page_frag:
5926 * Copy the physical page from the source PA to the target PA.
5927 * This function may be called from an interrupt. No locking
5931 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5933 vm_offset_t src_virt, dst_virt;
5935 src_virt = PHYS_TO_DMAP(src);
5936 dst_virt = PHYS_TO_DMAP(dst);
5938 bcopy((char *)src_virt + (src & PAGE_MASK),
5939 (char *)dst_virt + (dst & PAGE_MASK),
5944 * Returns true if the pmap's pv is one of the first 16 pvs linked to from
5945 * this page. This count may be changed upwards or downwards in the future;
5946 * it is only necessary that true be returned for a small subset of pmaps
5947 * for proper page aging.
5950 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5955 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5958 vm_page_spin_lock(m);
5959 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5960 if (pv->pv_pmap == pmap) {
5961 vm_page_spin_unlock(m);
5968 vm_page_spin_unlock(m);
5973 * Remove all pages from specified address space this aids process exit
5974 * speeds. Also, this code may be special cased for the current process
5978 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5980 pmap_remove_noinval(pmap, sva, eva);
5985 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5986 * routines are inline, and a lot of things compile-time evaluate.
5991 pmap_testbit(vm_page_t m, int bit)
5997 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
6000 if (TAILQ_FIRST(&m->md.pv_list) == NULL)
6002 vm_page_spin_lock(m);
6003 if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
6004 vm_page_spin_unlock(m);
6008 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6009 #if defined(PMAP_DIAGNOSTIC)
6010 if (pv->pv_pmap == NULL) {
6011 kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
6019 * If the bit being tested is the modified bit, then
6020 * mark clean_map and ptes as never
6023 * WARNING! Because we do not lock the pv, *pte can be in a
6024 * state of flux. Despite this the value of *pte
6025 * will still be related to the vm_page in some way
6026 * because the pv cannot be destroyed as long as we
6027 * hold the vm_page spin lock.
6029 if (bit == PG_A_IDX || bit == PG_M_IDX) {
6030 //& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
6031 if (!pmap_track_modified(pv->pv_pindex))
6035 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6036 if (*pte & pmap->pmap_bits[bit]) {
6037 vm_page_spin_unlock(m);
6041 vm_page_spin_unlock(m);
6046 * This routine is used to modify bits in ptes. Only one bit should be
6047 * specified. PG_RW requires special handling.
6049 * Caller must NOT hold any spin locks
6053 pmap_clearbit(vm_page_t m, int bit_index)
6060 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
6061 if (bit_index == PG_RW_IDX)
6062 vm_page_flag_clear(m, PG_WRITEABLE);
6069 * Loop over all current mappings setting/clearing as appropos If
6070 * setting RO do we need to clear the VAC?
6072 * NOTE: When clearing PG_M we could also (not implemented) drop
6073 * through to the PG_RW code and clear PG_RW too, forcing
6074 * a fault on write to redetect PG_M for virtual kernels, but
6075 * it isn't necessary since virtual kernels invalidate the
6076 * pte when they clear the VPTE_M bit in their virtual page
6079 * NOTE: Does not re-dirty the page when clearing only PG_M.
6081 * NOTE: Because we do not lock the pv, *pte can be in a state of
6082 * flux. Despite this the value of *pte is still somewhat
6083 * related while we hold the vm_page spin lock.
6085 * *pte can be zero due to this race. Since we are clearing
6086 * bits we basically do no harm when this race occurs.
6088 if (bit_index != PG_RW_IDX) {
6089 vm_page_spin_lock(m);
6090 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6091 #if defined(PMAP_DIAGNOSTIC)
6092 if (pv->pv_pmap == NULL) {
6093 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6099 pte = pmap_pte_quick(pv->pv_pmap,
6100 pv->pv_pindex << PAGE_SHIFT);
6102 if (pbits & pmap->pmap_bits[bit_index])
6103 atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
6105 vm_page_spin_unlock(m);
6110 * Clear PG_RW. Also clears PG_M and marks the page dirty if PG_M
6114 vm_page_spin_lock(m);
6115 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6117 * don't write protect pager mappings
6119 if (!pmap_track_modified(pv->pv_pindex))
6122 #if defined(PMAP_DIAGNOSTIC)
6123 if (pv->pv_pmap == NULL) {
6124 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6132 * Skip pages which do not have PG_RW set.
6134 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6135 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
6139 * We must lock the PV to be able to safely test the pte.
6141 if (pv_hold_try(pv)) {
6142 vm_page_spin_unlock(m);
6144 vm_page_spin_unlock(m);
6145 pv_lock(pv); /* held, now do a blocking lock */
6151 * Reload pte after acquiring pv.
6153 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6155 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0) {
6161 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
6167 nbits = pbits & ~(pmap->pmap_bits[PG_RW_IDX] |
6168 pmap->pmap_bits[PG_M_IDX]);
6169 if (pmap_inval_smp_cmpset(pmap,
6170 ((vm_offset_t)pv->pv_pindex << PAGE_SHIFT),
6171 pte, pbits, nbits)) {
6178 * If PG_M was found to be set while we were clearing PG_RW
6179 * we also clear PG_M (done above) and mark the page dirty.
6180 * Callers expect this behavior.
6182 * we lost pv so it cannot be used as an iterator. In fact,
6183 * because we couldn't necessarily lock it atomically it may
6184 * have moved within the list and ALSO cannot be used as an
6187 vm_page_spin_lock(m);
6188 if (pbits & pmap->pmap_bits[PG_M_IDX])
6190 vm_page_spin_unlock(m);
6194 if (bit_index == PG_RW_IDX)
6195 vm_page_flag_clear(m, PG_WRITEABLE);
6196 vm_page_spin_unlock(m);
6200 * Lower the permission for all mappings to a given page.
6202 * Page must be busied by caller. Because page is busied by caller this
6203 * should not be able to race a pmap_enter().
6206 pmap_page_protect(vm_page_t m, vm_prot_t prot)
6208 /* JG NX support? */
6209 if ((prot & VM_PROT_WRITE) == 0) {
6210 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
6212 * NOTE: pmap_clearbit(.. PG_RW) also clears
6213 * the PG_WRITEABLE flag in (m).
6215 pmap_clearbit(m, PG_RW_IDX);
6223 pmap_phys_address(vm_pindex_t ppn)
6225 return (x86_64_ptob(ppn));
6229 * Return a count of reference bits for a page, clearing those bits.
6230 * It is not necessary for every reference bit to be cleared, but it
6231 * is necessary that 0 only be returned when there are truly no
6232 * reference bits set.
6234 * XXX: The exact number of bits to check and clear is a matter that
6235 * should be tested and standardized at some point in the future for
6236 * optimal aging of shared pages.
6238 * This routine may not block.
6241 pmap_ts_referenced(vm_page_t m)
6248 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
6251 vm_page_spin_lock(m);
6252 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6253 if (!pmap_track_modified(pv->pv_pindex))
6256 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6257 if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
6258 atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
6264 vm_page_spin_unlock(m);
6271 * Return whether or not the specified physical page was modified
6272 * in any physical maps.
6275 pmap_is_modified(vm_page_t m)
6279 res = pmap_testbit(m, PG_M_IDX);
6284 * Clear the modify bits on the specified physical page.
6287 pmap_clear_modify(vm_page_t m)
6289 pmap_clearbit(m, PG_M_IDX);
6293 * pmap_clear_reference:
6295 * Clear the reference bit on the specified physical page.
6298 pmap_clear_reference(vm_page_t m)
6300 pmap_clearbit(m, PG_A_IDX);
6304 * Miscellaneous support routines follow
6309 x86_64_protection_init(void)
6315 * NX supported? (boot time loader.conf override only)
6317 * -1 Automatic (sets mode 1)
6319 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
6320 * 2 NX implemented for all cases
6322 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
6323 if ((amd_feature & AMDID_NX) == 0) {
6324 pmap_bits_default[PG_NX_IDX] = 0;
6326 } else if (pmap_nx_enable < 0) {
6327 pmap_nx_enable = 1; /* default to mode 1 (READ) */
6331 * 0 is basically read-only access, but also set the NX (no-execute)
6332 * bit when VM_PROT_EXECUTE is not specified.
6334 kp = protection_codes;
6335 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
6337 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
6339 * This case handled elsewhere
6343 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
6345 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
6347 if (pmap_nx_enable >= 1)
6348 *kp = pmap_bits_default[PG_NX_IDX];
6350 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6351 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6353 * Execute requires read access
6357 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6358 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6360 * Write without execute is RW|NX
6361 * (pmap_nx_enable mode >= 2)
6363 *kp = pmap_bits_default[PG_RW_IDX];
6364 if (pmap_nx_enable >= 2)
6365 *kp |= pmap_bits_default[PG_NX_IDX];
6367 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6368 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6370 * Write with execute is RW
6372 *kp = pmap_bits_default[PG_RW_IDX];
6380 * Map a set of physical memory pages into the kernel virtual
6381 * address space. Return a pointer to where it is mapped. This
6382 * routine is intended to be used for mapping device memory,
6385 * NOTE: We can't use pgeflag unless we invalidate the pages one at
6388 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6389 * work whether the cpu supports PAT or not. The remaining PAT
6390 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6394 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6396 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6400 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6402 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6406 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6408 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6412 * Map a set of physical memory pages into the kernel virtual
6413 * address space. Return a pointer to where it is mapped. This
6414 * routine is intended to be used for mapping device memory,
6418 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6420 vm_offset_t va, tmpva, offset;
6424 offset = pa & PAGE_MASK;
6425 size = roundup(offset + size, PAGE_SIZE);
6427 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6429 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6431 pa = pa & ~PAGE_MASK;
6432 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6433 pte = vtopte(tmpva);
6435 kernel_pmap.pmap_bits[PG_RW_IDX] |
6436 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
6437 kernel_pmap.pmap_cache_bits[mode];
6438 tmpsize -= PAGE_SIZE;
6442 pmap_invalidate_range(&kernel_pmap, va, va + size);
6443 pmap_invalidate_cache_range(va, va + size);
6445 return ((void *)(va + offset));
6449 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6451 vm_offset_t base, offset;
6453 base = va & ~PAGE_MASK;
6454 offset = va & PAGE_MASK;
6455 size = roundup(offset + size, PAGE_SIZE);
6456 pmap_qremove(va, size >> PAGE_SHIFT);
6457 kmem_free(&kernel_map, base, size);
6461 * Sets the memory attribute for the specified page.
6464 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6470 * If "m" is a normal page, update its direct mapping. This update
6471 * can be relied upon to perform any cache operations that are
6472 * required for data coherence.
6474 if ((m->flags & PG_FICTITIOUS) == 0)
6475 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6479 * Change the PAT attribute on an existing kernel memory map. Caller
6480 * must ensure that the virtual memory in question is not accessed
6481 * during the adjustment.
6484 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6491 panic("pmap_change_attr: va is NULL");
6492 base = trunc_page(va);
6496 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
6497 kernel_pmap.pmap_cache_bits[mode];
6502 changed = 1; /* XXX: not optimal */
6505 * Flush CPU caches if required to make sure any data isn't cached that
6506 * shouldn't be, etc.
6509 pmap_invalidate_range(&kernel_pmap, base, va);
6510 pmap_invalidate_cache_range(base, va);
6515 * perform the pmap work for mincore
6518 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6520 pt_entry_t *ptep, pte;
6524 ptep = pmap_pte(pmap, addr);
6526 if (ptep && (pte = *ptep) != 0) {
6529 val = MINCORE_INCORE;
6530 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
6533 pa = pte & PG_FRAME;
6535 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
6538 m = PHYS_TO_VM_PAGE(pa);
6543 if (pte & pmap->pmap_bits[PG_M_IDX])
6544 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6546 * Modified by someone
6548 else if (m && (m->dirty || pmap_is_modified(m)))
6549 val |= MINCORE_MODIFIED_OTHER;
6553 if (pte & pmap->pmap_bits[PG_A_IDX])
6554 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6557 * Referenced by someone
6559 else if (m && ((m->flags & PG_REFERENCED) ||
6560 pmap_ts_referenced(m))) {
6561 val |= MINCORE_REFERENCED_OTHER;
6562 vm_page_flag_set(m, PG_REFERENCED);
6571 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
6572 * vmspace will be ref'd and the old one will be deref'd.
6574 * The vmspace for all lwps associated with the process will be adjusted
6575 * and cr3 will be reloaded if any lwp is the current lwp.
6577 * The process must hold the vmspace->vm_map.token for oldvm and newvm
6580 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6582 struct vmspace *oldvm;
6585 oldvm = p->p_vmspace;
6586 if (oldvm != newvm) {
6589 p->p_vmspace = newvm;
6590 KKASSERT(p->p_nthreads == 1);
6591 lp = RB_ROOT(&p->p_lwp_tree);
6592 pmap_setlwpvm(lp, newvm);
6599 * Set the vmspace for a LWP. The vmspace is almost universally set the
6600 * same as the process vmspace, but virtual kernels need to swap out contexts
6601 * on a per-lwp basis.
6603 * Caller does not necessarily hold any vmspace tokens. Caller must control
6604 * the lwp (typically be in the context of the lwp). We use a critical
6605 * section to protect against statclock and hardclock (statistics collection).
6608 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6610 struct vmspace *oldvm;
6614 oldvm = lp->lwp_vmspace;
6616 if (oldvm != newvm) {
6619 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6620 lp->lwp_vmspace = newvm;
6621 if (td->td_lwp == lp) {
6622 pmap = vmspace_pmap(newvm);
6623 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6624 if (pmap->pm_active_lock & CPULOCK_EXCL)
6625 pmap_interlock_wait(newvm);
6626 #if defined(SWTCH_OPTIM_STATS)
6629 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6630 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6631 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6632 td->td_pcb->pcb_cr3_iso =
6633 vtophys(pmap->pm_pml4_iso);
6634 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6636 td->td_pcb->pcb_cr3_iso = 0;
6637 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6639 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6640 td->td_pcb->pcb_cr3 = KPML4phys;
6641 td->td_pcb->pcb_cr3_iso = 0;
6642 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6644 panic("pmap_setlwpvm: unknown pmap type\n");
6648 * The MMU separation fields needs to be updated.
6649 * (it can't access the pcb directly from the
6650 * restricted user pmap).
6653 struct trampframe *tramp;
6655 tramp = &pscpu->trampoline;
6656 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6657 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6658 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6659 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6660 /* tr_pcb_rsp doesn't change */
6664 * In kernel-land we always use the normal PML4E
6665 * so the kernel is fully mapped and can also access
6668 load_cr3(td->td_pcb->pcb_cr3);
6669 pmap = vmspace_pmap(oldvm);
6670 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6678 * Called when switching to a locked pmap, used to interlock against pmaps
6679 * undergoing modifications to prevent us from activating the MMU for the
6680 * target pmap until all such modifications have completed. We have to do
6681 * this because the thread making the modifications has already set up its
6682 * SMP synchronization mask.
6684 * This function cannot sleep!
6689 pmap_interlock_wait(struct vmspace *vm)
6691 struct pmap *pmap = &vm->vm_pmap;
6693 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6695 KKASSERT(curthread->td_critcount >= 2);
6696 DEBUG_PUSH_INFO("pmap_interlock_wait");
6697 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6699 lwkt_process_ipiq();
6707 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6710 if ((obj == NULL) || (size < NBPDR) ||
6711 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6715 addr = roundup2(addr, NBPDR);
6720 * Used by kmalloc/kfree, page already exists at va
6723 pmap_kvtom(vm_offset_t va)
6725 pt_entry_t *ptep = vtopte(va);
6727 KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
6728 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6732 * Initialize machine-specific shared page directory support. This
6733 * is executed when a VM object is created.
6736 pmap_object_init(vm_object_t object)
6738 object->md.pmap_rw = NULL;
6739 object->md.pmap_ro = NULL;
6743 * Clean up machine-specific shared page directory support. This
6744 * is executed when a VM object is destroyed.
6747 pmap_object_free(vm_object_t object)
6751 if ((pmap = object->md.pmap_rw) != NULL) {
6752 object->md.pmap_rw = NULL;
6753 pmap_remove_noinval(pmap,
6754 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6755 CPUMASK_ASSZERO(pmap->pm_active);
6758 kfree(pmap, M_OBJPMAP);
6760 if ((pmap = object->md.pmap_ro) != NULL) {
6761 object->md.pmap_ro = NULL;
6762 pmap_remove_noinval(pmap,
6763 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6764 CPUMASK_ASSZERO(pmap->pm_active);
6767 kfree(pmap, M_OBJPMAP);
6772 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6773 * VM page and issue a pginfo->callback.
6775 * We are expected to dispose of any non-NULL pte_pv.
6779 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6780 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
6781 pv_entry_t pt_pv, int sharept,
6782 vm_offset_t va, pt_entry_t *ptep, void *arg)
6784 struct pmap_pgscan_info *pginfo = arg;
6789 * Try to busy the page while we hold the pte_pv locked.
6791 KKASSERT(pte_pv->pv_m);
6792 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6793 if (vm_page_busy_try(m, TRUE) == 0) {
6794 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6796 * The callback is issued with the pte_pv
6797 * unlocked and put away, and the pt_pv
6802 vm_page_wire_quick(pt_pv->pv_m);
6805 if (pginfo->callback(pginfo, va, m) < 0)
6809 vm_page_unwire_quick(pt_pv->pv_m);
6816 ++pginfo->busycount;
6821 * Shared page table or unmanaged page (sharept or !sharept)
6823 pv_placemarker_wakeup(pmap, pte_placemark);
6828 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6830 struct pmap_scan_info info;
6832 pginfo->offset = pginfo->beg_addr;
6833 info.pmap = pginfo->pmap;
6834 info.sva = pginfo->beg_addr;
6835 info.eva = pginfo->end_addr;
6836 info.func = pmap_pgscan_callback;
6838 pmap_scan(&info, 0);
6840 pginfo->offset = pginfo->end_addr;
6844 * Wait for a placemarker that we do not own to clear. The placemarker
6845 * in question is not necessarily set to the pindex we want, we may have
6846 * to wait on the element because we want to reserve it ourselves.
6848 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6849 * PM_NOPLACEMARK, so it does not interfere with placemarks
6850 * which have already been woken up.
6854 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6856 if (*pmark != PM_NOPLACEMARK) {
6857 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
6858 tsleep_interlock(pmark, 0);
6859 if (*pmark != PM_NOPLACEMARK)
6860 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6865 * Wakeup a placemarker that we own. Replace the entry with
6866 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6870 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6874 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6875 KKASSERT(pindex != PM_NOPLACEMARK);
6876 if (pindex & PM_PLACEMARK_WAKEUP)