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-2019 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) \
149 ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
150 #define pmap_pte_w(pmap, pte) \
151 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
152 #define pmap_pte_m(pmap, pte) \
153 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
154 #define pmap_pte_u(pmap, pte) \
155 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
156 #define pmap_pte_v(pmap, pte) \
157 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
160 * Given a map and a machine independent protection code,
161 * convert to a vax protection code.
163 #define pte_prot(m, p) \
164 (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
165 static uint64_t protection_codes[PROTECTION_CODES_SIZE];
167 #define PMAP_PAGE_BACKING_SCAN(m, match_pmap, ipmap, iptep, ipte, iva) \
169 vm_object_t iobj = m->object; \
170 vm_map_backing_t iba, next_ba; \
171 struct pmap *ipmap; \
175 vm_pindex_t ipindex_start; \
176 vm_pindex_t ipindex_end; \
178 lockmgr(&iobj->backing_lk, LK_SHARED); \
179 next_ba = TAILQ_FIRST(&iobj->backing_list); \
180 while ((iba = next_ba) != NULL) { \
181 next_ba = TAILQ_NEXT(iba, entry); \
183 if (match_pmap && ipmap != match_pmap) \
185 ipindex_start = iba->offset >> PAGE_SHIFT; \
186 ipindex_end = ipindex_start + \
187 ((iba->end - iba->start) >> PAGE_SHIFT); \
188 if (m->pindex < ipindex_start || \
189 m->pindex >= ipindex_end) { \
193 ((m->pindex - ipindex_start) << PAGE_SHIFT); \
194 iptep = pmap_pte(ipmap, iva); \
198 if (m->phys_addr != (ipte & PG_FRAME)) \
201 #define PMAP_PAGE_BACKING_RETRY \
207 #define PMAP_PAGE_BACKING_DONE \
209 lockmgr(&iobj->backing_lk, LK_RELEASE); \
212 struct pmap kernel_pmap;
213 struct pmap iso_pmap;
215 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
217 vm_paddr_t avail_start; /* PA of first available physical page */
218 vm_paddr_t avail_end; /* PA of last available physical page */
219 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
220 vm_offset_t virtual2_end;
221 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
222 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
223 vm_offset_t KvaStart; /* VA start of KVA space */
224 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
225 vm_offset_t KvaSize; /* max size of kernel virtual address space */
226 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
227 //static int pgeflag; /* PG_G or-in */
231 static vm_paddr_t dmaplimit;
232 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
234 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
235 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
237 static uint64_t KPTbase;
238 static uint64_t KPTphys;
239 static uint64_t KPDphys; /* phys addr of kernel level 2 */
240 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
241 uint64_t KPDPphys; /* phys addr of kernel level 3 */
242 uint64_t KPML4phys; /* phys addr of kernel level 4 */
244 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
245 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
248 * Data for the pv entry allocation mechanism
250 static vm_zone_t pvzone;
251 static struct vm_zone pvzone_store;
252 static vm_pindex_t pv_entry_max=0, pv_entry_high_water=0;
253 static int pmap_pagedaemon_waken = 0;
254 static struct pv_entry *pvinit;
257 * All those kernel PT submaps that BSD is so fond of
259 pt_entry_t *CMAP1 = NULL, *ptmmap;
260 caddr_t CADDR1 = NULL, ptvmmap = NULL;
261 static pt_entry_t *msgbufmap;
262 struct msgbuf *msgbufp=NULL;
265 * PMAP default PG_* bits. Needed to be able to add
266 * EPT/NPT pagetable pmap_bits for the VMM module
268 uint64_t pmap_bits_default[] = {
269 REGULAR_PMAP, /* TYPE_IDX 0 */
270 X86_PG_V, /* PG_V_IDX 1 */
271 X86_PG_RW, /* PG_RW_IDX 2 */
272 X86_PG_U, /* PG_U_IDX 3 */
273 X86_PG_A, /* PG_A_IDX 4 */
274 X86_PG_M, /* PG_M_IDX 5 */
275 X86_PG_PS, /* PG_PS_IDX3 6 */
276 X86_PG_G, /* PG_G_IDX 7 */
277 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
278 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
279 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
280 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
281 X86_PG_NX, /* PG_NX_IDX 12 */
286 static pt_entry_t *pt_crashdumpmap;
287 static caddr_t crashdumpmap;
289 static int pmap_debug = 0;
290 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
291 &pmap_debug, 0, "Debug pmap's");
293 static int pmap_enter_debug = 0;
294 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
295 &pmap_enter_debug, 0, "Debug pmap_enter's");
297 static int pmap_yield_count = 64;
298 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
299 &pmap_yield_count, 0, "Yield during init_pt/release");
300 int pmap_fast_kernel_cpusync = 0;
301 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
302 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
303 int pmap_dynamic_delete = 0;
304 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
305 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
306 int pmap_lock_delay = 100;
307 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
308 &pmap_lock_delay, 0, "Spin loops");
309 static int meltdown_mitigation = -1;
310 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
311 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
312 &meltdown_mitigation, 0, "Userland pmap isolation");
314 static int pmap_nx_enable = -1; /* -1 = auto */
315 /* needs manual TUNABLE in early probe, see below */
316 SYSCTL_INT(_machdep, OID_AUTO, pmap_nx_enable, CTLFLAG_RD,
318 "no-execute support (0=disabled, 1=w/READ, 2=w/READ & WRITE)");
320 static int pmap_pv_debug = 50;
321 SYSCTL_INT(_machdep, OID_AUTO, pmap_pv_debug, CTLFLAG_RW,
322 &pmap_pv_debug, 0, "");
324 /* Standard user access funtions */
325 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
327 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
328 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
329 extern int std_fubyte (const uint8_t *base);
330 extern int std_subyte (uint8_t *base, uint8_t byte);
331 extern int32_t std_fuword32 (const uint32_t *base);
332 extern int64_t std_fuword64 (const uint64_t *base);
333 extern int std_suword64 (uint64_t *base, uint64_t word);
334 extern int std_suword32 (uint32_t *base, int word);
335 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
336 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
337 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
338 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
341 static void pv_hold(pv_entry_t pv);
343 static int _pv_hold_try(pv_entry_t pv
345 static void pv_drop(pv_entry_t pv);
346 static void _pv_lock(pv_entry_t pv
348 static void pv_unlock(pv_entry_t pv);
349 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
351 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
353 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
354 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
355 vm_pindex_t **pmarkp, int *errorp);
356 static void pv_put(pv_entry_t pv);
357 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
358 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
360 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
361 pmap_inval_bulk_t *bulk, int destroy);
362 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
363 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
364 pmap_inval_bulk_t *bulk);
366 struct pmap_scan_info;
367 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
368 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
369 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
370 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
371 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
372 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
374 static void x86_64_protection_init (void);
375 static void create_pagetables(vm_paddr_t *firstaddr);
376 static void pmap_remove_all (vm_page_t m);
377 static boolean_t pmap_testbit (vm_page_t m, int bit);
379 static pt_entry_t *pmap_pte_quick (pmap_t pmap, vm_offset_t va);
380 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
382 static void pmap_pinit_defaults(struct pmap *pmap);
383 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
384 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
387 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
389 if (pv1->pv_pindex < pv2->pv_pindex)
391 if (pv1->pv_pindex > pv2->pv_pindex)
396 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
397 pv_entry_compare, vm_pindex_t, pv_pindex);
401 pmap_page_stats_adding(vm_page_t m)
403 globaldata_t gd = mycpu;
405 if (m->md.pmap_count == 0) {
406 ++gd->gd_vmtotal.t_arm;
407 } else if (m->md.pmap_count == 1) {
408 ++gd->gd_vmtotal.t_armshr;
409 ++gd->gd_vmtotal.t_avmshr;
411 ++gd->gd_vmtotal.t_avmshr;
417 pmap_page_stats_deleting(vm_page_t m)
419 globaldata_t gd = mycpu;
421 if (m->md.pmap_count == 0) {
422 --gd->gd_vmtotal.t_arm;
423 } else if (m->md.pmap_count == 1) {
424 --gd->gd_vmtotal.t_armshr;
425 --gd->gd_vmtotal.t_avmshr;
427 --gd->gd_vmtotal.t_avmshr;
432 * Move the kernel virtual free pointer to the next
433 * 2MB. This is used to help improve performance
434 * by using a large (2MB) page for much of the kernel
435 * (.text, .data, .bss)
439 pmap_kmem_choose(vm_offset_t addr)
441 vm_offset_t newaddr = addr;
443 newaddr = roundup2(addr, NBPDR);
448 * Returns the pindex of a page table entry (representing a terminal page).
449 * There are NUPTE_TOTAL page table entries possible (a huge number)
451 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
452 * We want to properly translate negative KVAs.
456 pmap_pte_pindex(vm_offset_t va)
458 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
462 * Returns the pindex of a page table.
466 pmap_pt_pindex(vm_offset_t va)
468 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
472 * Returns the pindex of a page directory.
476 pmap_pd_pindex(vm_offset_t va)
478 return (NUPTE_TOTAL + NUPT_TOTAL +
479 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
484 pmap_pdp_pindex(vm_offset_t va)
486 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
487 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
492 pmap_pml4_pindex(void)
494 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
498 * Return various clipped indexes for a given VA
500 * Returns the index of a pt in a page directory, representing a page
505 pmap_pt_index(vm_offset_t va)
507 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
511 * Returns the index of a pd in a page directory page, representing a page
516 pmap_pd_index(vm_offset_t va)
518 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
522 * Returns the index of a pdp in the pml4 table, representing a page
527 pmap_pdp_index(vm_offset_t va)
529 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
533 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
534 * the PT layer. This will speed up core pmap operations considerably.
535 * We also cache the PTE layer to (hopefully) improve relative lookup
538 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
539 * must be in a known associated state (typically by being locked when
540 * the pmap spinlock isn't held). We allow the race for that case.
542 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
543 * cpu_ccfence() to prevent compiler optimizations from reloading the
548 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
550 if (pindex < pmap_pt_pindex(0)) {
552 } else if (pindex < pmap_pd_pindex(0)) {
553 pmap->pm_pvhint_pt = pv;
558 * Locate the requested pt_entry
562 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
566 if (pindex < pmap_pt_pindex(0))
569 if (pindex < pmap_pd_pindex(0))
570 pv = pmap->pm_pvhint_pt;
574 if (pv == NULL || pv->pv_pmap != pmap) {
575 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
577 pv_cache(pmap, pv, pindex);
578 } else if (pv->pv_pindex != pindex) {
579 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
582 pv_cache(pmap, pv, pindex);
585 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
593 * Super fast pmap_pte routine best used when scanning the pv lists.
594 * This eliminates many course-grained invltlb calls. Note that many of
595 * the pv list scans are across different pmaps and it is very wasteful
596 * to do an entire invltlb when checking a single mapping.
598 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
602 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
604 return pmap_pte(pmap, va);
608 * The placemarker hash must be broken up into four zones so lock
609 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
611 * Placemarkers are used to 'lock' page table indices that do not have
612 * a pv_entry. This allows the pmap to support managed and unmanaged
613 * pages and shared page tables.
615 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
619 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
623 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
625 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
627 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
628 hi = PM_PLACE_BASE << 1;
629 else /* zone 3 - PDP (and PML4E) */
630 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
631 hi += pindex & (PM_PLACE_BASE - 1);
633 return (&pmap->pm_placemarks[hi]);
638 * Generic procedure to index a pte from a pt, pd, or pdp.
640 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
641 * a page table page index but is instead of PV lookup index.
645 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
649 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
650 return(&pte[pindex]);
654 * Return pointer to PDP slot in the PML4
658 pmap_pdp(pmap_t pmap, vm_offset_t va)
660 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
664 * Return pointer to PD slot in the PDP given a pointer to the PDP
668 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
672 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
673 return (&pd[pmap_pd_index(va)]);
677 * Return pointer to PD slot in the PDP.
681 pmap_pd(pmap_t pmap, vm_offset_t va)
685 pdp = pmap_pdp(pmap, va);
686 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
688 return (pmap_pdp_to_pd(*pdp, va));
692 * Return pointer to PT slot in the PD given a pointer to the PD
696 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
700 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
701 return (&pt[pmap_pt_index(va)]);
705 * Return pointer to PT slot in the PD
707 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
708 * so we cannot lookup the PD via the PDP. Instead we
709 * must look it up via the pmap.
713 pmap_pt(pmap_t pmap, vm_offset_t va)
717 vm_pindex_t pd_pindex;
720 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
721 pd_pindex = pmap_pd_pindex(va);
722 spin_lock_shared(&pmap->pm_spin);
723 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
724 if (pv == NULL || pv->pv_m == NULL) {
725 spin_unlock_shared(&pmap->pm_spin);
728 phys = VM_PAGE_TO_PHYS(pv->pv_m);
729 spin_unlock_shared(&pmap->pm_spin);
730 return (pmap_pd_to_pt(phys, va));
732 pd = pmap_pd(pmap, va);
733 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
735 return (pmap_pd_to_pt(*pd, va));
740 * Return pointer to PTE slot in the PT given a pointer to the PT
744 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
748 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
749 return (&pte[pmap_pte_index(va)]);
753 * Return pointer to PTE slot in the PT
757 pmap_pte(pmap_t pmap, vm_offset_t va)
761 pt = pmap_pt(pmap, va);
762 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
764 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
765 return ((pt_entry_t *)pt);
766 return (pmap_pt_to_pte(*pt, va));
770 * Return address of PT slot in PD (KVM only)
772 * Cannot be used for user page tables because it might interfere with
773 * the shared page-table-page optimization (pmap_mmu_optimize).
777 vtopt(vm_offset_t va)
779 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
780 NPML4EPGSHIFT)) - 1);
782 return (PDmap + ((va >> PDRSHIFT) & mask));
786 * KVM - return address of PTE slot in PT
790 vtopte(vm_offset_t va)
792 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
793 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
795 return (PTmap + ((va >> PAGE_SHIFT) & mask));
799 * Returns the physical address translation from va for a user address.
800 * (vm_paddr_t)-1 is returned on failure.
803 uservtophys(vm_offset_t va)
805 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
806 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
811 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
813 if (va < VM_MAX_USER_ADDRESS) {
814 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
815 if (pte & pmap->pmap_bits[PG_V_IDX])
816 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
822 allocpages(vm_paddr_t *firstaddr, long n)
827 bzero((void *)ret, n * PAGE_SIZE);
828 *firstaddr += n * PAGE_SIZE;
834 create_pagetables(vm_paddr_t *firstaddr)
836 long i; /* must be 64 bits */
843 * We are running (mostly) V=P at this point
845 * Calculate how many 1GB PD entries in our PDP pages are needed
846 * for the DMAP. This is only allocated if the system does not
847 * support 1GB pages. Otherwise ndmpdp is simply a count of
848 * the number of 1G terminal entries in our PDP pages are needed.
850 * NOTE: Maxmem is in pages
852 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
853 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
855 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
858 * Starting at KERNBASE - map all 2G worth of page table pages.
859 * KERNBASE is offset -2G from the end of kvm. This will accomodate
860 * all KVM allocations above KERNBASE, including the SYSMAPs below.
862 * We do this by allocating 2*512 PT pages. Each PT page can map
863 * 2MB, for 2GB total.
865 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
868 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
869 * Calculate how many page table pages we need to preallocate
870 * for early vm_map allocations.
872 * A few extra won't hurt, they will get used up in the running
878 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
879 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
880 nkpt_phys += 128; /* a few extra */
883 * The highest value nkpd_phys can be set to is
884 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
886 * Doing so would cause all PD pages to be pre-populated for
887 * a maximal KVM space (approximately 16*512 pages, or 32MB.
888 * We can save memory by not doing this.
890 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
895 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
896 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
898 * Only allocate enough PD pages
899 * NOTE: We allocate all kernel PD pages up-front, typically
900 * ~511G of KVM, requiring 511 PD pages.
902 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
903 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
904 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
905 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
906 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
909 * Alloc PD pages for the area starting at KERNBASE.
911 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
916 DMPDPphys = allocpages(firstaddr, NDMPML4E);
917 if ((amd_feature & AMDID_PAGE1GB) == 0)
918 DMPDphys = allocpages(firstaddr, ndmpdp);
919 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
922 * Fill in the underlying page table pages for the area around
923 * KERNBASE. This remaps low physical memory to KERNBASE.
925 * Read-only from zero to physfree
926 * XXX not fully used, underneath 2M pages
928 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
929 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
930 ((pt_entry_t *)KPTbase)[i] |=
931 pmap_bits_default[PG_RW_IDX] |
932 pmap_bits_default[PG_V_IDX] |
933 pmap_bits_default[PG_G_IDX];
937 * Now map the initial kernel page tables. One block of page
938 * tables is placed at the beginning of kernel virtual memory,
939 * and another block is placed at KERNBASE to map the kernel binary,
940 * data, bss, and initial pre-allocations.
942 for (i = 0; i < nkpt_base; i++) {
943 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
944 ((pd_entry_t *)KPDbase)[i] |=
945 pmap_bits_default[PG_RW_IDX] |
946 pmap_bits_default[PG_V_IDX];
948 for (i = 0; i < nkpt_phys; i++) {
949 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
950 ((pd_entry_t *)KPDphys)[i] |=
951 pmap_bits_default[PG_RW_IDX] |
952 pmap_bits_default[PG_V_IDX];
956 * Map from zero to end of allocations using 2M pages as an
957 * optimization. This will bypass some of the KPTBase pages
958 * above in the KERNBASE area.
960 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
961 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
962 ((pd_entry_t *)KPDbase)[i] |=
963 pmap_bits_default[PG_RW_IDX] |
964 pmap_bits_default[PG_V_IDX] |
965 pmap_bits_default[PG_PS_IDX] |
966 pmap_bits_default[PG_G_IDX];
970 * Load PD addresses into the PDP pages for primary KVA space to
971 * cover existing page tables. PD's for KERNBASE are handled in
974 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
976 for (i = 0; i < nkpd_phys; i++) {
977 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
978 KPDphys + (i << PAGE_SHIFT);
979 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
980 pmap_bits_default[PG_RW_IDX] |
981 pmap_bits_default[PG_V_IDX] |
982 pmap_bits_default[PG_A_IDX];
986 * Load PDs for KERNBASE to the end
988 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
989 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
990 ((pdp_entry_t *)KPDPphys)[i + j] =
991 KPDbase + (j << PAGE_SHIFT);
992 ((pdp_entry_t *)KPDPphys)[i + j] |=
993 pmap_bits_default[PG_RW_IDX] |
994 pmap_bits_default[PG_V_IDX] |
995 pmap_bits_default[PG_A_IDX];
999 * Now set up the direct map space using either 2MB or 1GB pages
1000 * Preset PG_M and PG_A because demotion expects it.
1002 * When filling in entries in the PD pages make sure any excess
1003 * entries are set to zero as we allocated enough PD pages
1005 if ((amd_feature & AMDID_PAGE1GB) == 0) {
1009 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1010 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1011 ((pd_entry_t *)DMPDphys)[i] |=
1012 pmap_bits_default[PG_RW_IDX] |
1013 pmap_bits_default[PG_V_IDX] |
1014 pmap_bits_default[PG_PS_IDX] |
1015 pmap_bits_default[PG_G_IDX] |
1016 pmap_bits_default[PG_M_IDX] |
1017 pmap_bits_default[PG_A_IDX];
1021 * And the direct map space's PDP
1023 for (i = 0; i < ndmpdp; i++) {
1024 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1026 ((pdp_entry_t *)DMPDPphys)[i] |=
1027 pmap_bits_default[PG_RW_IDX] |
1028 pmap_bits_default[PG_V_IDX];
1034 for (i = 0; i < ndmpdp; i++) {
1035 ((pdp_entry_t *)DMPDPphys)[i] =
1036 (vm_paddr_t)i << PDPSHIFT;
1037 ((pdp_entry_t *)DMPDPphys)[i] |=
1038 pmap_bits_default[PG_RW_IDX] |
1039 pmap_bits_default[PG_V_IDX] |
1040 pmap_bits_default[PG_PS_IDX] |
1041 pmap_bits_default[PG_G_IDX] |
1042 pmap_bits_default[PG_M_IDX] |
1043 pmap_bits_default[PG_A_IDX];
1047 /* And recursively map PML4 to itself in order to get PTmap */
1048 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1049 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1050 pmap_bits_default[PG_RW_IDX] |
1051 pmap_bits_default[PG_V_IDX] |
1052 pmap_bits_default[PG_A_IDX];
1055 * Connect the Direct Map slots up to the PML4
1057 for (j = 0; j < NDMPML4E; ++j) {
1058 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1059 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1060 pmap_bits_default[PG_RW_IDX] |
1061 pmap_bits_default[PG_V_IDX] |
1062 pmap_bits_default[PG_A_IDX];
1066 * Connect the KVA slot up to the PML4
1068 for (j = 0; j < NKPML4E; ++j) {
1069 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1070 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1071 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1072 pmap_bits_default[PG_RW_IDX] |
1073 pmap_bits_default[PG_V_IDX] |
1074 pmap_bits_default[PG_A_IDX];
1081 * Bootstrap the system enough to run with virtual memory.
1083 * On x86_64 this is called after mapping has already been enabled
1084 * and just syncs the pmap module with what has already been done.
1085 * [We can't call it easily with mapping off since the kernel is not
1086 * mapped with PA == VA, hence we would have to relocate every address
1087 * from the linked base (virtual) address "KERNBASE" to the actual
1088 * (physical) address starting relative to 0]
1091 pmap_bootstrap(vm_paddr_t *firstaddr)
1097 KvaStart = VM_MIN_KERNEL_ADDRESS;
1098 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1099 KvaSize = KvaEnd - KvaStart;
1101 avail_start = *firstaddr;
1104 * Create an initial set of page tables to run the kernel in.
1106 create_pagetables(firstaddr);
1108 virtual2_start = KvaStart;
1109 virtual2_end = PTOV_OFFSET;
1111 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1112 virtual_start = pmap_kmem_choose(virtual_start);
1114 virtual_end = VM_MAX_KERNEL_ADDRESS;
1116 /* XXX do %cr0 as well */
1117 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1118 load_cr3(KPML4phys);
1121 * Initialize protection array.
1123 x86_64_protection_init();
1126 * The kernel's pmap is statically allocated so we don't have to use
1127 * pmap_create, which is unlikely to work correctly at this part of
1128 * the boot sequence (XXX and which no longer exists).
1130 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1131 kernel_pmap.pm_count = 1;
1132 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1133 RB_INIT(&kernel_pmap.pm_pvroot);
1134 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1135 for (i = 0; i < PM_PLACEMARKS; ++i)
1136 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1139 * Reserve some special page table entries/VA space for temporary
1142 #define SYSMAP(c, p, v, n) \
1143 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1149 * CMAP1/CMAP2 are used for zeroing and copying pages.
1151 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1156 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1159 * ptvmmap is used for reading arbitrary physical pages via
1162 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1165 * msgbufp is used to map the system message buffer.
1166 * XXX msgbufmap is not used.
1168 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1169 atop(round_page(MSGBUF_SIZE)))
1172 virtual_start = pmap_kmem_choose(virtual_start);
1177 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1178 * cases rather then invl1pg. Actually, I don't even know why it
1179 * works under UP because self-referential page table mappings
1185 /* Initialize the PAT MSR */
1187 pmap_pinit_defaults(&kernel_pmap);
1189 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1190 &pmap_fast_kernel_cpusync);
1195 * Setup the PAT MSR.
1204 * Default values mapping PATi,PCD,PWT bits at system reset.
1205 * The default values effectively ignore the PATi bit by
1206 * repeating the encodings for 0-3 in 4-7, and map the PCD
1207 * and PWT bit combinations to the expected PAT types.
1209 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1210 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1211 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1212 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1213 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1214 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1215 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1216 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1217 pat_pte_index[PAT_WRITE_BACK] = 0;
1218 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1219 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1220 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1221 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1222 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1224 if (cpu_feature & CPUID_PAT) {
1226 * If we support the PAT then set-up entries for
1227 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1230 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1231 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1232 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1233 PAT_VALUE(6, PAT_WRITE_COMBINING);
1234 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1235 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1238 * Then enable the PAT
1243 load_cr4(cr4 & ~CR4_PGE);
1245 /* Disable caches (CD = 1, NW = 0). */
1247 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1249 /* Flushes caches and TLBs. */
1253 /* Update PAT and index table. */
1254 wrmsr(MSR_PAT, pat_msr);
1256 /* Flush caches and TLBs again. */
1260 /* Restore caches and PGE. */
1268 * Set 4mb pdir for mp startup
1273 if (cpu_feature & CPUID_PSE) {
1274 load_cr4(rcr4() | CR4_PSE);
1275 if (mycpu->gd_cpuid == 0) /* only on BSP */
1280 * Check for SMAP support and enable if available. Must be done
1281 * after cr3 is loaded, and on all cores.
1283 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1284 load_cr4(rcr4() | CR4_SMAP);
1286 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1287 load_cr4(rcr4() | CR4_SMEP);
1292 * Early initialization of the pmap module.
1294 * Called by vm_init, to initialize any structures that the pmap
1295 * system needs to map virtual memory. pmap_init has been enhanced to
1296 * support in a fairly consistant way, discontiguous physical memory.
1301 vm_pindex_t initial_pvs;
1305 * Allocate memory for random pmap data structures. Includes the
1308 for (i = 0; i < vm_page_array_size; i++) {
1311 m = &vm_page_array[i];
1312 m->md.pmap_count = 0;
1313 m->md.writeable_count = 0;
1317 * init the pv free list
1319 initial_pvs = vm_page_array_size;
1320 if (initial_pvs < MINPV)
1321 initial_pvs = MINPV;
1322 pvzone = &pvzone_store;
1323 pvinit = (void *)kmem_alloc(&kernel_map,
1324 initial_pvs * sizeof (struct pv_entry),
1326 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1327 pvinit, initial_pvs);
1330 * Now it is safe to enable pv_table recording.
1332 pmap_initialized = TRUE;
1336 * Initialize the address space (zone) for the pv_entries. Set a
1337 * high water mark so that the system can recover from excessive
1338 * numbers of pv entries.
1340 * Also create the kernel page table template for isolated user
1343 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1344 static void pmap_init2_iso_pmap(void);
1346 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1352 vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
1353 vm_pindex_t entry_max;
1355 TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1356 pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1357 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1358 pv_entry_high_water = 9 * (pv_entry_max / 10);
1361 * Subtract out pages already installed in the zone (hack)
1363 entry_max = pv_entry_max - vm_page_array_size;
1367 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1370 * Enable dynamic deletion of empty higher-level page table pages
1371 * by default only if system memory is < 8GB (use 7GB for slop).
1372 * This can save a little memory, but imposes significant
1373 * performance overhead for things like bulk builds, and for programs
1374 * which do a lot of memory mapping and memory unmapping.
1377 if (pmap_dynamic_delete < 0) {
1378 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1379 pmap_dynamic_delete = 1;
1381 pmap_dynamic_delete = 0;
1385 * Disable so vm_map_backing iterations do not race
1387 pmap_dynamic_delete = 0;
1390 * Automatic detection of Intel meltdown bug requiring user/kernel
1393 * Currently there are so many Intel cpu's impacted that its better
1394 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1395 * so the default is off for AMD.
1397 if (meltdown_mitigation < 0) {
1398 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1399 meltdown_mitigation = 1;
1401 meltdown_mitigation = 0;
1403 if (meltdown_mitigation) {
1404 kprintf("machdep.meltdown_mitigation enabled to "
1405 "protect against (mostly Intel) meltdown bug\n");
1406 kprintf("system call performance will be impacted\n");
1409 pmap_init2_iso_pmap();
1413 * Create the isolation pmap template. Once created, the template
1414 * is static and its PML4e entries are used to populate the
1415 * kernel portion of any isolated user pmaps.
1417 * Our isolation pmap must contain:
1418 * (1) trampoline area for all cpus
1419 * (2) common_tss area for all cpus (its part of the trampoline area now)
1420 * (3) IDT for all cpus
1421 * (4) GDT for all cpus
1424 pmap_init2_iso_pmap(void)
1429 kprintf("Initialize isolation pmap\n");
1432 * Try to use our normal API calls to make this easier. We have
1433 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1436 pmap_pinit(&iso_pmap);
1437 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1440 * Install areas needed by the cpu and trampoline.
1442 for (n = 0; n < ncpus; ++n) {
1443 struct privatespace *ps;
1445 ps = CPU_prvspace[n];
1446 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1447 sizeof(ps->trampoline));
1448 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1449 sizeof(ps->dblstack));
1450 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1451 sizeof(ps->dbgstack));
1452 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1453 sizeof(ps->common_tss));
1454 pmap_init_iso_range(r_idt_arr[n].rd_base,
1455 r_idt_arr[n].rd_limit + 1);
1457 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1458 pmap_init_iso_range((vm_offset_t)(int *)btext,
1459 (vm_offset_t)(int *)etext -
1460 (vm_offset_t)(int *)btext);
1463 kprintf("Dump iso_pmap:\n");
1464 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1465 kprintf("\nDump kernel_pmap:\n");
1466 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1471 * This adds a kernel virtual address range to the isolation pmap.
1474 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1483 kprintf("isolate %016jx-%016jx (%zd)\n",
1484 base, base + bytes, bytes);
1486 va = base & ~(vm_offset_t)PAGE_MASK;
1487 while (va < base + bytes) {
1488 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1489 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1490 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1491 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1493 * Use 2MB pages if possible
1496 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1497 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1502 * Otherwise use 4KB pages
1504 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1505 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1506 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1507 kernel_pmap.pmap_bits[PG_V_IDX] |
1508 kernel_pmap.pmap_bits[PG_A_IDX] |
1509 kernel_pmap.pmap_bits[PG_M_IDX];
1520 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1524 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1531 case 0: /* PML4e page, 512G entries */
1532 incr = (1LL << 48) / 512;
1534 case 1: /* PDP page, 1G entries */
1535 incr = (1LL << 39) / 512;
1537 case 2: /* PD page, 2MB entries */
1538 incr = (1LL << 30) / 512;
1540 case 3: /* PT page, 4KB entries */
1541 incr = (1LL << 21) / 512;
1549 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1550 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1551 for (i = 0; i < 512; ++i) {
1552 if (level == 0 && i == 128)
1553 base += 0xFFFF000000000000LLU;
1555 kprintf("%*.*s ", level * 4, level * 4, "");
1556 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1557 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1559 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1560 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1562 } else if (level == 3) {
1563 kprintf("va=%016jx %3d term %016jx\n",
1566 kprintf("va=%016jx %3d deep %016jx\n",
1568 dump_pmap(pmap, ptp[i], level + 1, base);
1578 * Typically used to initialize a fictitious page by vm/device_pager.c
1581 pmap_page_init(struct vm_page *m)
1584 m->md.pmap_count = 0;
1585 m->md.writeable_count = 0;
1588 /***************************************************
1589 * Low level helper routines.....
1590 ***************************************************/
1593 * Extract the physical page address associated with the map/VA pair.
1594 * The page must be wired for this to work reliably.
1597 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1604 if (va >= VM_MAX_USER_ADDRESS) {
1606 * Kernel page directories might be direct-mapped and
1607 * there is typically no PV tracking of pte's
1611 pt = pmap_pt(pmap, va);
1612 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1613 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1614 rtval = *pt & PG_PS_FRAME;
1615 rtval |= va & PDRMASK;
1617 ptep = pmap_pt_to_pte(*pt, va);
1618 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1619 rtval = *ptep & PG_FRAME;
1620 rtval |= va & PAGE_MASK;
1628 * User pages currently do not direct-map the page directory
1629 * and some pages might not used managed PVs. But all PT's
1632 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1634 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1635 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1636 rtval = *ptep & PG_FRAME;
1637 rtval |= va & PAGE_MASK;
1640 *handlep = pt_pv; /* locked until done */
1643 } else if (handlep) {
1651 pmap_extract_done(void *handle)
1654 pv_put((pv_entry_t)handle);
1658 * Similar to extract but checks protections, SMP-friendly short-cut for
1659 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1660 * fall-through to the real fault code. Does not work with HVM page
1663 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1665 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1666 * page is busied (and not held).
1668 * If busyp is not NULL and this function sets *busyp to zero, the returned
1669 * page is held (and not busied).
1671 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1672 * returned page will be dirtied. If the pte is not already writable NULL
1673 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1674 * any COW will already have happened and that page can be written by the
1677 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1681 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1684 va < VM_MAX_USER_ADDRESS &&
1685 (pmap->pm_flags & PMAP_HVM) == 0) {
1693 req = pmap->pmap_bits[PG_V_IDX] |
1694 pmap->pmap_bits[PG_U_IDX];
1695 if (prot & VM_PROT_WRITE)
1696 req |= pmap->pmap_bits[PG_RW_IDX];
1698 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1701 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1702 if ((*ptep & req) != req) {
1706 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1707 if (pte_pv && error == 0) {
1709 if (prot & VM_PROT_WRITE) {
1710 /* interlocked by presence of pv_entry */
1714 if (prot & VM_PROT_WRITE) {
1715 if (vm_page_busy_try(m, TRUE))
1726 } else if (pte_pv) {
1730 /* error, since we didn't request a placemarker */
1741 * Extract the physical page address associated kernel virtual address.
1744 pmap_kextract(vm_offset_t va)
1746 pd_entry_t pt; /* pt entry in pd */
1749 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1750 pa = DMAP_TO_PHYS(va);
1753 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1754 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1757 * Beware of a concurrent promotion that changes the
1758 * PDE at this point! For example, vtopte() must not
1759 * be used to access the PTE because it would use the
1760 * new PDE. It is, however, safe to use the old PDE
1761 * because the page table page is preserved by the
1764 pa = *pmap_pt_to_pte(pt, va);
1765 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1771 /***************************************************
1772 * Low level mapping routines.....
1773 ***************************************************/
1776 * Routine: pmap_kenter
1778 * Add a wired page to the KVA
1779 * NOTE! note that in order for the mapping to take effect -- you
1780 * should do an invltlb after doing the pmap_kenter().
1783 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1789 kernel_pmap.pmap_bits[PG_RW_IDX] |
1790 kernel_pmap.pmap_bits[PG_V_IDX];
1794 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1798 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1805 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1806 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1807 * (caller can conditionalize calling smp_invltlb()).
1810 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1816 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1817 kernel_pmap.pmap_bits[PG_V_IDX];
1826 atomic_swap_long(ptep, npte);
1827 cpu_invlpg((void *)va);
1833 * Enter addresses into the kernel pmap but don't bother
1834 * doing any tlb invalidations. Caller will do a rollup
1835 * invalidation via pmap_rollup_inval().
1838 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1845 kernel_pmap.pmap_bits[PG_RW_IDX] |
1846 kernel_pmap.pmap_bits[PG_V_IDX];
1855 atomic_swap_long(ptep, npte);
1856 cpu_invlpg((void *)va);
1862 * remove a page from the kernel pagetables
1865 pmap_kremove(vm_offset_t va)
1870 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1874 pmap_kremove_quick(vm_offset_t va)
1879 (void)pte_load_clear(ptep);
1880 cpu_invlpg((void *)va);
1884 * Remove addresses from the kernel pmap but don't bother
1885 * doing any tlb invalidations. Caller will do a rollup
1886 * invalidation via pmap_rollup_inval().
1889 pmap_kremove_noinval(vm_offset_t va)
1894 (void)pte_load_clear(ptep);
1898 * XXX these need to be recoded. They are not used in any critical path.
1901 pmap_kmodify_rw(vm_offset_t va)
1903 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1904 cpu_invlpg((void *)va);
1909 pmap_kmodify_nc(vm_offset_t va)
1911 atomic_set_long(vtopte(va), PG_N);
1912 cpu_invlpg((void *)va);
1917 * Used to map a range of physical addresses into kernel virtual
1918 * address space during the low level boot, typically to map the
1919 * dump bitmap, message buffer, and vm_page_array.
1921 * These mappings are typically made at some pointer after the end of the
1924 * We could return PHYS_TO_DMAP(start) here and not allocate any
1925 * via (*virtp), but then kmem from userland and kernel dumps won't
1926 * have access to the related pointers.
1929 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1932 vm_offset_t va_start;
1934 /*return PHYS_TO_DMAP(start);*/
1939 while (start < end) {
1940 pmap_kenter_quick(va, start);
1948 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1951 * Remove the specified set of pages from the data and instruction caches.
1953 * In contrast to pmap_invalidate_cache_range(), this function does not
1954 * rely on the CPU's self-snoop feature, because it is intended for use
1955 * when moving pages into a different cache domain.
1958 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1960 vm_offset_t daddr, eva;
1963 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1964 (cpu_feature & CPUID_CLFSH) == 0)
1968 for (i = 0; i < count; i++) {
1969 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1970 eva = daddr + PAGE_SIZE;
1971 for (; daddr < eva; daddr += cpu_clflush_line_size)
1979 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1981 KASSERT((sva & PAGE_MASK) == 0,
1982 ("pmap_invalidate_cache_range: sva not page-aligned"));
1983 KASSERT((eva & PAGE_MASK) == 0,
1984 ("pmap_invalidate_cache_range: eva not page-aligned"));
1986 if (cpu_feature & CPUID_SS) {
1987 ; /* If "Self Snoop" is supported, do nothing. */
1989 /* Globally invalidate caches */
1990 cpu_wbinvd_on_all_cpus();
1995 * Invalidate the specified range of virtual memory on all cpus associated
1999 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2001 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2005 * Add a list of wired pages to the kva. This routine is used for temporary
2006 * kernel mappings such as those found in buffer cache buffer. Page
2007 * modifications and accesses are not tracked or recorded.
2009 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2010 * semantics as previous mappings may have been zerod without any
2013 * The page *must* be wired.
2015 static __inline void
2016 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2021 end_va = beg_va + count * PAGE_SIZE;
2023 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2028 pte = VM_PAGE_TO_PHYS(*m) |
2029 kernel_pmap.pmap_bits[PG_RW_IDX] |
2030 kernel_pmap.pmap_bits[PG_V_IDX] |
2031 kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2033 atomic_swap_long(ptep, pte);
2037 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2041 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2043 _pmap_qenter(beg_va, m, count, 1);
2047 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2049 _pmap_qenter(beg_va, m, count, 0);
2053 * This routine jerks page mappings from the kernel -- it is meant only
2054 * for temporary mappings such as those found in buffer cache buffers.
2055 * No recording modified or access status occurs.
2057 * MPSAFE, INTERRUPT SAFE (cluster callback)
2060 pmap_qremove(vm_offset_t beg_va, int count)
2065 end_va = beg_va + count * PAGE_SIZE;
2067 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2071 (void)pte_load_clear(pte);
2072 cpu_invlpg((void *)va);
2074 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2078 * This routine removes temporary kernel mappings, only invalidating them
2079 * on the current cpu. It should only be used under carefully controlled
2083 pmap_qremove_quick(vm_offset_t beg_va, int count)
2088 end_va = beg_va + count * PAGE_SIZE;
2090 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2094 (void)pte_load_clear(pte);
2095 cpu_invlpg((void *)va);
2100 * This routine removes temporary kernel mappings *without* invalidating
2101 * the TLB. It can only be used on permanent kva reservations such as those
2102 * found in buffer cache buffers, under carefully controlled circumstances.
2104 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2105 * (pmap_qenter() does unconditional invalidation).
2108 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2113 end_va = beg_va + count * PAGE_SIZE;
2115 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2119 (void)pte_load_clear(pte);
2124 * Create a new thread and optionally associate it with a (new) process.
2125 * NOTE! the new thread's cpu may not equal the current cpu.
2128 pmap_init_thread(thread_t td)
2130 /* enforce pcb placement & alignment */
2131 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2132 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2133 td->td_savefpu = &td->td_pcb->pcb_save;
2134 td->td_sp = (char *)td->td_pcb; /* no -16 */
2138 * This routine directly affects the fork perf for a process.
2141 pmap_init_proc(struct proc *p)
2146 pmap_pinit_defaults(struct pmap *pmap)
2148 bcopy(pmap_bits_default, pmap->pmap_bits,
2149 sizeof(pmap_bits_default));
2150 bcopy(protection_codes, pmap->protection_codes,
2151 sizeof(protection_codes));
2152 bcopy(pat_pte_index, pmap->pmap_cache_bits,
2153 sizeof(pat_pte_index));
2154 pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2155 pmap->copyinstr = std_copyinstr;
2156 pmap->copyin = std_copyin;
2157 pmap->copyout = std_copyout;
2158 pmap->fubyte = std_fubyte;
2159 pmap->subyte = std_subyte;
2160 pmap->fuword32 = std_fuword32;
2161 pmap->fuword64 = std_fuword64;
2162 pmap->suword32 = std_suword32;
2163 pmap->suword64 = std_suword64;
2164 pmap->swapu32 = std_swapu32;
2165 pmap->swapu64 = std_swapu64;
2166 pmap->fuwordadd32 = std_fuwordadd32;
2167 pmap->fuwordadd64 = std_fuwordadd64;
2170 * Initialize pmap0/vmspace0.
2172 * On architectures where the kernel pmap is not integrated into the user
2173 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2174 * kernel_pmap should be used to directly access the kernel_pmap.
2177 pmap_pinit0(struct pmap *pmap)
2181 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2183 CPUMASK_ASSZERO(pmap->pm_active);
2184 pmap->pm_pvhint_pt = NULL;
2185 pmap->pm_pvhint_unused = NULL;
2186 RB_INIT(&pmap->pm_pvroot);
2187 spin_init(&pmap->pm_spin, "pmapinit0");
2188 for (i = 0; i < PM_PLACEMARKS; ++i)
2189 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2190 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2191 pmap_pinit_defaults(pmap);
2195 * Initialize a preallocated and zeroed pmap structure,
2196 * such as one in a vmspace structure.
2199 pmap_pinit_simple(struct pmap *pmap)
2204 * Misc initialization
2207 CPUMASK_ASSZERO(pmap->pm_active);
2208 pmap->pm_pvhint_pt = NULL;
2209 pmap->pm_pvhint_unused = NULL;
2210 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2212 pmap_pinit_defaults(pmap);
2215 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2218 if (pmap->pm_pmlpv == NULL) {
2219 RB_INIT(&pmap->pm_pvroot);
2220 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2221 spin_init(&pmap->pm_spin, "pmapinitsimple");
2222 for (i = 0; i < PM_PLACEMARKS; ++i)
2223 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2228 pmap_pinit(struct pmap *pmap)
2233 if (pmap->pm_pmlpv) {
2234 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2239 pmap_pinit_simple(pmap);
2240 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2243 * No need to allocate page table space yet but we do need a valid
2244 * page directory table.
2246 if (pmap->pm_pml4 == NULL) {
2248 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2251 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2255 * Allocate the PML4e table, which wires it even though it isn't
2256 * being entered into some higher level page table (it being the
2257 * highest level). If one is already cached we don't have to do
2260 if ((pv = pmap->pm_pmlpv) == NULL) {
2261 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2262 pmap->pm_pmlpv = pv;
2263 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2264 VM_PAGE_TO_PHYS(pv->pv_m));
2268 * Install DMAP and KMAP.
2270 for (j = 0; j < NDMPML4E; ++j) {
2271 pmap->pm_pml4[DMPML4I + j] =
2272 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2273 pmap->pmap_bits[PG_RW_IDX] |
2274 pmap->pmap_bits[PG_V_IDX] |
2275 pmap->pmap_bits[PG_A_IDX];
2277 for (j = 0; j < NKPML4E; ++j) {
2278 pmap->pm_pml4[KPML4I + j] =
2279 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2280 pmap->pmap_bits[PG_RW_IDX] |
2281 pmap->pmap_bits[PG_V_IDX] |
2282 pmap->pmap_bits[PG_A_IDX];
2286 * install self-referential address mapping entry
2288 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2289 pmap->pmap_bits[PG_V_IDX] |
2290 pmap->pmap_bits[PG_RW_IDX] |
2291 pmap->pmap_bits[PG_A_IDX];
2293 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2294 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2296 KKASSERT(pmap->pm_pml4[255] == 0);
2299 * When implementing an isolated userland pmap, a second PML4e table
2300 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2301 * note that we do not operate on this table using our API functions
2302 * so handling of the + 1 case is mostly just to prevent implosions.
2304 * We install an isolated version of the kernel PDPs into this
2305 * second PML4e table. The pmap code will mirror all user PDPs
2306 * between the primary and secondary PML4e table.
2308 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2309 pmap != &iso_pmap) {
2310 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2311 pmap->pm_pmlpv_iso = pv;
2312 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2313 VM_PAGE_TO_PHYS(pv->pv_m));
2317 * Install an isolated version of the kernel pmap for
2318 * user consumption, using PDPs constructed in iso_pmap.
2320 for (j = 0; j < NKPML4E; ++j) {
2321 pmap->pm_pml4_iso[KPML4I + j] =
2322 iso_pmap.pm_pml4[KPML4I + j];
2325 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2326 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2331 * Clean up a pmap structure so it can be physically freed. This routine
2332 * is called by the vmspace dtor function. A great deal of pmap data is
2333 * left passively mapped to improve vmspace management so we have a bit
2334 * of cleanup work to do here.
2337 pmap_puninit(pmap_t pmap)
2342 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2343 if ((pv = pmap->pm_pmlpv) != NULL) {
2344 if (pv_hold_try(pv) == 0)
2346 KKASSERT(pv == pmap->pm_pmlpv);
2347 p = pmap_remove_pv_page(pv);
2349 pv = NULL; /* safety */
2350 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2351 vm_page_busy_wait(p, FALSE, "pgpun");
2352 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2353 vm_page_unwire(p, 0);
2354 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2356 pmap->pm_pmlpv = NULL;
2358 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2359 if (pv_hold_try(pv) == 0)
2361 KKASSERT(pv == pmap->pm_pmlpv_iso);
2362 p = pmap_remove_pv_page(pv);
2364 pv = NULL; /* safety */
2365 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2366 vm_page_busy_wait(p, FALSE, "pgpun");
2367 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2368 vm_page_unwire(p, 0);
2369 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2371 pmap->pm_pmlpv_iso = NULL;
2373 if (pmap->pm_pml4) {
2374 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2375 kmem_free(&kernel_map,
2376 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2377 pmap->pm_pml4 = NULL;
2378 pmap->pm_pml4_iso = NULL;
2380 KKASSERT(pmap->pm_stats.resident_count == 0);
2381 KKASSERT(pmap->pm_stats.wired_count == 0);
2385 * This function is now unused (used to add the pmap to the pmap_list)
2388 pmap_pinit2(struct pmap *pmap)
2393 * This routine is called when various levels in the page table need to
2394 * be populated. This routine cannot fail.
2396 * This function returns two locked pv_entry's, one representing the
2397 * requested pv and one representing the requested pv's parent pv. If
2398 * an intermediate page table does not exist it will be created, mapped,
2399 * wired, and the parent page table will be given an additional hold
2400 * count representing the presence of the child pv_entry.
2404 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2407 pt_entry_t *ptep_iso;
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 * DragonFly doesn't use PV's to represent terminal PTEs any more.
2429 KKASSERT(ptepindex >= pmap_pt_pindex(0));
2431 if (ptepindex < pmap_pt_pindex(0)) {
2432 if (ptepindex >= NUPTE_USER && pmap != &iso_pmap) {
2433 /* kernel manages this manually for KVM */
2434 KKASSERT(pvpp == NULL);
2436 KKASSERT(pvpp != NULL);
2437 pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
2438 pvp = pmap_allocpte(pmap, pt_pindex, NULL);
2440 vm_page_wire_quick(pvp->pv_m);
2448 * Note that pt_pv's are only returned for user VAs. We assert that
2449 * a pt_pv is not being requested for kernel VAs. The kernel
2450 * pre-wires all higher-level page tables so don't overload managed
2451 * higher-level page tables on top of it!
2453 * However, its convenient for us to allow the case when creating
2454 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2459 * The kernel never uses managed PT/PD/PDP pages.
2461 KKASSERT(pmap != &kernel_pmap);
2464 * Non-terminal PVs allocate a VM page to represent the page table,
2465 * so we have to resolve pvp and calculate ptepindex for the pvp
2466 * and then for the page table entry index in the pvp for
2469 if (ptepindex < pmap_pd_pindex(0)) {
2471 * pv is PT, pvp is PD
2473 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2474 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2475 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2480 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2481 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2483 } else if (ptepindex < pmap_pdp_pindex(0)) {
2485 * pv is PD, pvp is PDP
2487 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2490 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2491 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2493 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2494 KKASSERT(pvpp == NULL);
2497 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2503 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2504 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2505 } else if (ptepindex < pmap_pml4_pindex()) {
2507 * pv is PDP, pvp is the root pml4 table
2509 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2514 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2515 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2518 * pv represents the top-level PML4, there is no parent.
2527 * (isnew) is TRUE, pv is not terminal.
2529 * (1) Add a wire count to the parent page table (pvp).
2530 * (2) Allocate a VM page for the page table.
2531 * (3) Enter the VM page into the parent page table.
2533 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2536 vm_page_wire_quick(pvp->pv_m);
2539 m = vm_page_alloc(NULL, pv->pv_pindex,
2540 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2541 VM_ALLOC_INTERRUPT);
2546 vm_page_wire(m); /* wire for mapping in parent */
2547 vm_page_unmanage(m); /* m must be spinunlocked */
2548 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2549 m->valid = VM_PAGE_BITS_ALL;
2551 vm_page_spin_lock(m);
2552 /* pmap_page_stats_adding(m); */
2555 * PGTABLE pv's only exist in the context of the pmap RB tree
2556 * (pmap->pm_pvroot).
2558 pv->pv_flags |= PV_FLAG_PGTABLE;
2560 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2561 vm_page_spin_unlock(m);
2564 * (isnew) is TRUE, pv is not terminal.
2566 * Wire the page into pvp. Bump the resident_count for the pmap.
2567 * There is no pvp for the top level, address the pm_pml4[] array
2570 * If the caller wants the parent we return it, otherwise
2571 * we just put it away.
2573 * No interlock is needed for pte 0 -> non-zero.
2575 * In the situation where *ptep is valid we might have an unmanaged
2576 * page table page shared from another page table which we need to
2577 * unshare before installing our private page table page.
2580 v = VM_PAGE_TO_PHYS(m) |
2581 (pmap->pmap_bits[PG_RW_IDX] |
2582 pmap->pmap_bits[PG_V_IDX] |
2583 pmap->pmap_bits[PG_A_IDX]);
2584 if (ptepindex < NUPTE_USER)
2585 v |= pmap->pmap_bits[PG_U_IDX];
2586 if (ptepindex < pmap_pt_pindex(0))
2587 v |= pmap->pmap_bits[PG_M_IDX];
2589 ptep = pv_pte_lookup(pvp, ptepindex);
2590 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2591 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2594 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2597 /* REMOVED replaces shared page table page */
2601 panic("pmap_allocpte: unexpected pte %p/%d",
2602 pvp, (int)ptepindex);
2604 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2607 pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2610 if (vm_page_unwire_quick(
2611 PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2612 panic("pmap_allocpte: shared pgtable "
2613 "pg bad wirecount");
2619 pte = atomic_swap_long(ptep, v);
2621 atomic_swap_long(ptep_iso, v);
2623 kprintf("install pgtbl mixup 0x%016jx "
2624 "old/new 0x%016jx/0x%016jx\n",
2625 (intmax_t)ptepindex, pte, v);
2632 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2636 KKASSERT(pvp->pv_m != NULL);
2637 ptep = pv_pte_lookup(pvp, ptepindex);
2638 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2639 (pmap->pmap_bits[PG_RW_IDX] |
2640 pmap->pmap_bits[PG_V_IDX] |
2641 pmap->pmap_bits[PG_A_IDX]);
2642 if (ptepindex < NUPTE_USER)
2643 v |= pmap->pmap_bits[PG_U_IDX];
2644 if (ptepindex < pmap_pt_pindex(0))
2645 v |= pmap->pmap_bits[PG_M_IDX];
2647 kprintf("mismatched upper level pt %016jx/%016jx\n",
2659 * Release any resources held by the given physical map.
2661 * Called when a pmap initialized by pmap_pinit is being released. Should
2662 * only be called if the map contains no valid mappings.
2664 struct pmap_release_info {
2670 static int pmap_release_callback(pv_entry_t pv, void *data);
2673 pmap_release(struct pmap *pmap)
2675 struct pmap_release_info info;
2677 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2678 ("pmap still active! %016jx",
2679 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2682 * There is no longer a pmap_list, if there were we would remove the
2683 * pmap from it here.
2687 * Pull pv's off the RB tree in order from low to high and release
2695 spin_lock(&pmap->pm_spin);
2696 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2697 pmap_release_callback, &info);
2698 spin_unlock(&pmap->pm_spin);
2702 } while (info.retry);
2706 * One resident page (the pml4 page) should remain. Two if
2707 * the pmap has implemented an isolated userland PML4E table.
2708 * No wired pages should remain.
2710 int expected_res = 0;
2712 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2714 if (pmap->pm_pmlpv_iso)
2718 if (pmap->pm_stats.resident_count != expected_res ||
2719 pmap->pm_stats.wired_count != 0) {
2720 kprintf("fatal pmap problem - pmap %p flags %08x "
2721 "rescnt=%jd wirecnt=%jd\n",
2724 pmap->pm_stats.resident_count,
2725 pmap->pm_stats.wired_count);
2726 tsleep(pmap, 0, "DEAD", 0);
2729 KKASSERT(pmap->pm_stats.resident_count == expected_res);
2730 KKASSERT(pmap->pm_stats.wired_count == 0);
2735 * Called from low to high. We must cache the proper parent pv so we
2736 * can adjust its wired count.
2739 pmap_release_callback(pv_entry_t pv, void *data)
2741 struct pmap_release_info *info = data;
2742 pmap_t pmap = info->pmap;
2747 * Acquire a held and locked pv, check for release race
2749 pindex = pv->pv_pindex;
2750 if (info->pvp == pv) {
2751 spin_unlock(&pmap->pm_spin);
2753 } else if (pv_hold_try(pv)) {
2754 spin_unlock(&pmap->pm_spin);
2756 spin_unlock(&pmap->pm_spin);
2760 spin_lock(&pmap->pm_spin);
2764 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
2766 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2768 * I am PTE, parent is PT
2770 pindex = pv->pv_pindex >> NPTEPGSHIFT;
2771 pindex += NUPTE_TOTAL;
2772 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
2774 * I am PT, parent is PD
2776 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
2777 pindex += NUPTE_TOTAL + NUPT_TOTAL;
2778 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
2780 * I am PD, parent is PDP
2782 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
2784 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2785 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
2787 * I am PDP, parent is PML4. We always calculate the
2788 * normal PML4 here, not the isolated PML4.
2790 pindex = pmap_pml4_pindex();
2802 if (info->pvp && info->pvp->pv_pindex != pindex) {
2806 if (info->pvp == NULL)
2807 info->pvp = pv_get(pmap, pindex, NULL);
2814 r = pmap_release_pv(pv, info->pvp, NULL);
2815 spin_lock(&pmap->pm_spin);
2821 * Called with held (i.e. also locked) pv. This function will dispose of
2822 * the lock along with the pv.
2824 * If the caller already holds the locked parent page table for pv it
2825 * must pass it as pvp, allowing us to avoid a deadlock, else it can
2826 * pass NULL for pvp.
2829 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
2834 * The pmap is currently not spinlocked, pv is held+locked.
2835 * Remove the pv's page from its parent's page table. The
2836 * parent's page table page's wire_count will be decremented.
2838 * This will clean out the pte at any level of the page table.
2839 * If smp != 0 all cpus are affected.
2841 * Do not tear-down recursively, its faster to just let the
2842 * release run its course.
2844 pmap_remove_pv_pte(pv, pvp, bulk, 0);
2847 * Terminal pvs are unhooked from their vm_pages. Because
2848 * terminal pages aren't page table pages they aren't wired
2849 * by us, so we have to be sure not to unwire them either.
2851 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2852 pmap_remove_pv_page(pv);
2857 * We leave the top-level page table page cached, wired, and
2858 * mapped in the pmap until the dtor function (pmap_puninit())
2861 * Since we are leaving the top-level pv intact we need
2862 * to break out of what would otherwise be an infinite loop.
2864 * This covers both the normal and the isolated PML4 page.
2866 if (pv->pv_pindex >= pmap_pml4_pindex()) {
2872 * For page table pages (other than the top-level page),
2873 * remove and free the vm_page. The representitive mapping
2874 * removed above by pmap_remove_pv_pte() did not undo the
2875 * last wire_count so we have to do that as well.
2877 p = pmap_remove_pv_page(pv);
2878 vm_page_busy_wait(p, FALSE, "pmaprl");
2879 if (p->wire_count != 1) {
2882 if (pv->pv_pindex >= pmap_pdp_pindex(0))
2884 else if (pv->pv_pindex >= pmap_pd_pindex(0))
2886 else if (pv->pv_pindex >= pmap_pt_pindex(0))
2891 kprintf("p(%s) p->wire_count was %016lx %d\n",
2892 tstr, pv->pv_pindex, p->wire_count);
2894 KKASSERT(p->wire_count == 1);
2895 KKASSERT(p->flags & PG_UNMANAGED);
2897 vm_page_unwire(p, 0);
2898 KKASSERT(p->wire_count == 0);
2908 * This function will remove the pte associated with a pv from its parent.
2909 * Terminal pv's are supported. All cpus specified by (bulk) are properly
2912 * The wire count will be dropped on the parent page table. The wire
2913 * count on the page being removed (pv->pv_m) from the parent page table
2914 * is NOT touched. Note that terminal pages will not have any additional
2915 * wire counts while page table pages will have at least one representing
2916 * the mapping, plus others representing sub-mappings.
2918 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
2919 * pages and user page table and terminal pages.
2921 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
2922 * be freshly allocated and not imply that the pte is managed. In this
2923 * case pv->pv_m should be NULL.
2925 * The pv must be locked. The pvp, if supplied, must be locked. All
2926 * supplied pv's will remain locked on return.
2928 * XXX must lock parent pv's if they exist to remove pte XXX
2932 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
2935 vm_pindex_t ptepindex = pv->pv_pindex;
2936 pmap_t pmap = pv->pv_pmap;
2942 if (ptepindex >= pmap_pml4_pindex()) {
2944 * We are the top level PML4E table, there is no parent.
2946 * This is either the normal or isolated PML4E table.
2947 * Only the normal is used in regular operation, the isolated
2948 * is only passed in when breaking down the whole pmap.
2950 p = pmap->pm_pmlpv->pv_m;
2951 KKASSERT(pv->pv_m == p); /* debugging */
2952 } else if (ptepindex >= pmap_pdp_pindex(0)) {
2954 * Remove a PDP page from the PML4E. This can only occur
2955 * with user page tables. We do not have to lock the
2956 * pml4 PV so just ignore pvp.
2958 vm_pindex_t pml4_pindex;
2959 vm_pindex_t pdp_index;
2961 pml4_entry_t *pdp_iso;
2963 pdp_index = ptepindex - pmap_pdp_pindex(0);
2965 pml4_pindex = pmap_pml4_pindex();
2966 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
2971 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
2972 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
2973 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2974 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
2977 * Also remove the PDP from the isolated PML4E if the
2980 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
2981 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
2982 ((1ul << NPML4EPGSHIFT) - 1)];
2983 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
2985 KKASSERT(pv->pv_m == p); /* debugging */
2986 } else if (ptepindex >= pmap_pd_pindex(0)) {
2988 * Remove a PD page from the PDP
2990 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
2991 * of a simple pmap because it stops at
2994 vm_pindex_t pdp_pindex;
2995 vm_pindex_t pd_index;
2998 pd_index = ptepindex - pmap_pd_pindex(0);
3001 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3002 (pd_index >> NPML4EPGSHIFT);
3003 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3008 pd = pv_pte_lookup(pvp, pd_index &
3009 ((1ul << NPDPEPGSHIFT) - 1));
3010 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3011 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3012 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3014 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3015 p = pv->pv_m; /* degenerate test later */
3017 KKASSERT(pv->pv_m == p); /* debugging */
3018 } else if (ptepindex >= pmap_pt_pindex(0)) {
3020 * Remove a PT page from the PD
3022 vm_pindex_t pd_pindex;
3023 vm_pindex_t pt_index;
3026 pt_index = ptepindex - pmap_pt_pindex(0);
3029 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3030 (pt_index >> NPDPEPGSHIFT);
3031 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3036 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3038 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3039 ("*pt unexpectedly invalid %016jx "
3040 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3041 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3042 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3044 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3045 kprintf("*pt unexpectedly invalid %016jx "
3046 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3048 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3049 tsleep(pt, 0, "DEAD", 0);
3052 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3055 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3056 KKASSERT(pv->pv_m == p); /* debugging */
3062 * If requested, scrap the underlying pv->pv_m and the underlying
3063 * pv. If this is a page-table-page we must also free the page.
3065 * pvp must be returned locked.
3069 * page table page (PT, PD, PDP, PML4), caller was responsible
3070 * for testing wired_count.
3072 KKASSERT(pv->pv_m->wire_count == 1);
3073 p = pmap_remove_pv_page(pv);
3077 vm_page_busy_wait(p, FALSE, "pgpun");
3078 vm_page_unwire(p, 0);
3079 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3081 } else if (destroy == 2) {
3083 * Normal page, remove from pmap and leave the underlying
3086 pmap_remove_pv_page(pv);
3088 pv = NULL; /* safety */
3092 * If we acquired pvp ourselves then we are responsible for
3093 * recursively deleting it.
3095 if (pvp && gotpvp) {
3097 * Recursively destroy higher-level page tables.
3099 * This is optional. If we do not, they will still
3100 * be destroyed when the process exits.
3102 * NOTE: Do not destroy pv_entry's with extra hold refs,
3103 * a caller may have unlocked it and intends to
3104 * continue to use it.
3106 if (pmap_dynamic_delete &&
3108 pvp->pv_m->wire_count == 1 &&
3109 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3110 pvp->pv_pindex < pmap_pml4_pindex()) {
3111 if (pmap != &kernel_pmap) {
3112 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3113 pvp = NULL; /* safety */
3115 kprintf("Attempt to remove kernel_pmap pindex "
3116 "%jd\n", pvp->pv_pindex);
3126 * Remove the vm_page association to a pv. The pv must be locked.
3130 pmap_remove_pv_page(pv_entry_t pv)
3135 vm_page_spin_lock(m);
3136 KKASSERT(m && m == pv->pv_m);
3138 if (pv->pv_flags & PV_FLAG_PGTABLE) {
3139 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3140 KKASSERT(m->md.pmap_count == 0);
3143 * Used only for page table pages, so safe to clear on
3144 * the 1->0 transition.
3146 if (atomic_fetchadd_long(&m->md.pmap_count, -1) == 1)
3147 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3149 /* pmap_page_stats_deleting(m); */
3150 vm_page_spin_unlock(m);
3156 * Grow the number of kernel page table entries, if needed.
3158 * This routine is always called to validate any address space
3159 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3160 * space below KERNBASE.
3162 * kernel_map must be locked exclusively by the caller.
3165 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3168 vm_offset_t ptppaddr;
3170 pd_entry_t *pt, newpt;
3171 pdp_entry_t *pd, newpd;
3172 int update_kernel_vm_end;
3175 * bootstrap kernel_vm_end on first real VM use
3177 if (kernel_vm_end == 0) {
3178 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3181 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3184 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3186 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3187 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3188 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
3189 kernel_vm_end = vm_map_max(&kernel_map);
3196 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3197 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3198 * do not want to force-fill 128G worth of page tables.
3200 if (kstart < KERNBASE) {
3201 if (kstart > kernel_vm_end)
3202 kstart = kernel_vm_end;
3203 KKASSERT(kend <= KERNBASE);
3204 update_kernel_vm_end = 1;
3206 update_kernel_vm_end = 0;
3209 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3210 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3212 if (kend - 1 >= vm_map_max(&kernel_map))
3213 kend = vm_map_max(&kernel_map);
3215 while (kstart < kend) {
3216 pt = pmap_pt(&kernel_pmap, kstart);
3219 * We need a new PD entry
3221 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3224 VM_ALLOC_INTERRUPT);
3226 panic("pmap_growkernel: no memory to grow "
3229 paddr = VM_PAGE_TO_PHYS(nkpg);
3230 pmap_zero_page(paddr);
3231 pd = pmap_pd(&kernel_pmap, kstart);
3233 newpd = (pdp_entry_t)
3235 kernel_pmap.pmap_bits[PG_V_IDX] |
3236 kernel_pmap.pmap_bits[PG_RW_IDX] |
3237 kernel_pmap.pmap_bits[PG_A_IDX]);
3238 atomic_swap_long(pd, newpd);
3241 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3245 continue; /* try again */
3248 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3249 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3250 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3251 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3252 kstart = vm_map_max(&kernel_map);
3261 * This index is bogus, but out of the way
3263 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3266 VM_ALLOC_INTERRUPT);
3268 panic("pmap_growkernel: no memory to grow kernel");
3271 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3272 pmap_zero_page(ptppaddr);
3273 newpt = (pd_entry_t)(ptppaddr |
3274 kernel_pmap.pmap_bits[PG_V_IDX] |
3275 kernel_pmap.pmap_bits[PG_RW_IDX] |
3276 kernel_pmap.pmap_bits[PG_A_IDX]);
3277 atomic_swap_long(pt, newpt);
3279 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3280 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3282 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3283 kstart = vm_map_max(&kernel_map);
3289 * Only update kernel_vm_end for areas below KERNBASE.
3291 if (update_kernel_vm_end && kernel_vm_end < kstart)
3292 kernel_vm_end = kstart;
3296 * Add a reference to the specified pmap.
3299 pmap_reference(pmap_t pmap)
3302 atomic_add_int(&pmap->pm_count, 1);
3306 pmap_maybethreaded(pmap_t pmap)
3308 atomic_set_int(&pmap->pm_flags, PMAP_MULTI);
3312 * Called while page is hard-busied to clear the PG_MAPPED and PG_WRITEABLE
3316 pmap_mapped_sync(vm_page_t m)
3318 if (m->md.pmap_count == 0)
3319 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3323 /***************************************************
3324 * page management routines.
3325 ***************************************************/
3328 * Hold a pv without locking it
3332 pv_hold(pv_entry_t pv)
3334 atomic_add_int(&pv->pv_hold, 1);
3339 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3340 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3343 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3344 * pv list via its page) must be held by the caller in order to stabilize
3348 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3353 * Critical path shortcut expects pv to already have one ref
3354 * (for the pv->pv_pmap).
3356 count = pv->pv_hold;
3359 if ((count & PV_HOLD_LOCKED) == 0) {
3360 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3361 (count + 1) | PV_HOLD_LOCKED)) {
3364 pv->pv_line = lineno;
3369 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3377 * Drop a previously held pv_entry which could not be locked, allowing its
3380 * Must not be called with a spinlock held as we might zfree() the pv if it
3381 * is no longer associated with a pmap and this was the last hold count.
3384 pv_drop(pv_entry_t pv)
3389 count = pv->pv_hold;
3391 KKASSERT((count & PV_HOLD_MASK) > 0);
3392 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3393 (PV_HOLD_LOCKED | 1));
3394 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3395 if ((count & PV_HOLD_MASK) == 1) {
3397 if (pmap_enter_debug > 0) {
3399 kprintf("pv_drop: free pv %p\n", pv);
3402 KKASSERT(count == 1);
3403 KKASSERT(pv->pv_pmap == NULL);
3413 * Find or allocate the requested PV entry, returning a locked, held pv.
3415 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3416 * for the caller and one representing the pmap and vm_page association.
3418 * If (*isnew) is zero, the returned pv will have only one hold count.
3420 * Since both associations can only be adjusted while the pv is locked,
3421 * together they represent just one additional hold.
3425 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3427 struct mdglobaldata *md = mdcpu;
3435 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3438 pnew = md->gd_newpv; /* might race NULL */
3439 md->gd_newpv = NULL;
3444 pnew = zalloc(pvzone);
3446 spin_lock_shared(&pmap->pm_spin);
3451 pv = pv_entry_lookup(pmap, pindex);
3456 * Requires exclusive pmap spinlock
3458 if (pmap_excl == 0) {
3460 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3461 spin_unlock_shared(&pmap->pm_spin);
3462 spin_lock(&pmap->pm_spin);
3468 * We need to block if someone is holding our
3469 * placemarker. As long as we determine the
3470 * placemarker has not been aquired we do not
3471 * need to get it as acquision also requires
3472 * the pmap spin lock.
3474 * However, we can race the wakeup.
3476 pmark = pmap_placemarker_hash(pmap, pindex);
3478 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3479 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3480 tsleep_interlock(pmark, 0);
3481 if (((*pmark ^ pindex) &
3482 ~PM_PLACEMARK_WAKEUP) == 0) {
3483 spin_unlock(&pmap->pm_spin);
3484 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3485 spin_lock(&pmap->pm_spin);
3491 * Setup the new entry
3493 pnew->pv_pmap = pmap;
3494 pnew->pv_pindex = pindex;
3495 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3498 pnew->pv_func = func;
3499 pnew->pv_line = lineno;
3500 if (pnew->pv_line_lastfree > 0) {
3501 pnew->pv_line_lastfree =
3502 -pnew->pv_line_lastfree;
3505 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3506 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3507 spin_unlock(&pmap->pm_spin);
3510 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3515 * We already have an entry, cleanup the staged pnew if
3516 * we can get the lock, otherwise block and retry.
3518 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3520 spin_unlock(&pmap->pm_spin);
3522 spin_unlock_shared(&pmap->pm_spin);
3524 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3526 zfree(pvzone, pnew);
3529 if (md->gd_newpv == NULL)
3530 md->gd_newpv = pnew;
3532 zfree(pvzone, pnew);
3535 KKASSERT(pv->pv_pmap == pmap &&
3536 pv->pv_pindex == pindex);
3541 spin_unlock(&pmap->pm_spin);
3542 _pv_lock(pv PMAP_DEBUG_COPY);
3544 spin_lock(&pmap->pm_spin);
3546 spin_unlock_shared(&pmap->pm_spin);
3547 _pv_lock(pv PMAP_DEBUG_COPY);
3549 spin_lock_shared(&pmap->pm_spin);
3556 * Find the requested PV entry, returning a locked+held pv or NULL
3560 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3565 spin_lock_shared(&pmap->pm_spin);
3570 pv = pv_entry_lookup(pmap, pindex);
3573 * Block if there is ANY placemarker. If we are to
3574 * return it, we must also aquire the spot, so we
3575 * have to block even if the placemarker is held on
3576 * a different address.
3578 * OPTIMIZATION: If pmarkp is passed as NULL the
3579 * caller is just probing (or looking for a real
3580 * pv_entry), and in this case we only need to check
3581 * to see if the placemarker matches pindex.
3586 * Requires exclusive pmap spinlock
3588 if (pmap_excl == 0) {
3590 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3591 spin_unlock_shared(&pmap->pm_spin);
3592 spin_lock(&pmap->pm_spin);
3597 pmark = pmap_placemarker_hash(pmap, pindex);
3599 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3600 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3601 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3602 tsleep_interlock(pmark, 0);
3603 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3604 ((*pmark ^ pindex) &
3605 ~PM_PLACEMARK_WAKEUP) == 0) {
3606 spin_unlock(&pmap->pm_spin);
3607 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3608 spin_lock(&pmap->pm_spin);
3613 if (atomic_swap_long(pmark, pindex) !=
3615 panic("_pv_get: pmark race");
3619 spin_unlock(&pmap->pm_spin);
3622 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3624 spin_unlock(&pmap->pm_spin);
3626 spin_unlock_shared(&pmap->pm_spin);
3627 KKASSERT(pv->pv_pmap == pmap &&
3628 pv->pv_pindex == pindex);
3632 spin_unlock(&pmap->pm_spin);
3633 _pv_lock(pv PMAP_DEBUG_COPY);
3635 spin_lock(&pmap->pm_spin);
3637 spin_unlock_shared(&pmap->pm_spin);
3638 _pv_lock(pv PMAP_DEBUG_COPY);
3640 spin_lock_shared(&pmap->pm_spin);
3646 * Lookup, hold, and attempt to lock (pmap,pindex).
3648 * If the entry does not exist NULL is returned and *errorp is set to 0
3650 * If the entry exists and could be successfully locked it is returned and
3651 * errorp is set to 0.
3653 * If the entry exists but could NOT be successfully locked it is returned
3654 * held and *errorp is set to 1.
3656 * If the entry is placemarked by someone else NULL is returned and *errorp
3661 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3665 spin_lock_shared(&pmap->pm_spin);
3667 pv = pv_entry_lookup(pmap, pindex);
3671 pmark = pmap_placemarker_hash(pmap, pindex);
3673 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3675 } else if (pmarkp &&
3676 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3680 * Can't set a placemark with a NULL pmarkp, or if
3681 * pmarkp is non-NULL but we failed to set our
3688 spin_unlock_shared(&pmap->pm_spin);
3694 * XXX This has problems if the lock is shared, why?
3696 if (pv_hold_try(pv)) {
3697 spin_unlock_shared(&pmap->pm_spin);
3699 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3700 return(pv); /* lock succeeded */
3702 spin_unlock_shared(&pmap->pm_spin);
3705 return (pv); /* lock failed */
3709 * Lock a held pv, keeping the hold count
3713 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
3718 count = pv->pv_hold;
3720 if ((count & PV_HOLD_LOCKED) == 0) {
3721 if (atomic_cmpset_int(&pv->pv_hold, count,
3722 count | PV_HOLD_LOCKED)) {
3725 pv->pv_line = lineno;
3731 tsleep_interlock(pv, 0);
3732 if (atomic_cmpset_int(&pv->pv_hold, count,
3733 count | PV_HOLD_WAITING)) {
3735 if (pmap_enter_debug > 0) {
3737 kprintf("pv waiting on %s:%d\n",
3738 pv->pv_func, pv->pv_line);
3741 tsleep(pv, PINTERLOCKED, "pvwait", hz);
3748 * Unlock a held and locked pv, keeping the hold count.
3752 pv_unlock(pv_entry_t pv)
3757 count = pv->pv_hold;
3759 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
3760 (PV_HOLD_LOCKED | 1));
3761 if (atomic_cmpset_int(&pv->pv_hold, count,
3763 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
3764 if (count & PV_HOLD_WAITING)
3772 * Unlock and drop a pv. If the pv is no longer associated with a pmap
3773 * and the hold count drops to zero we will free it.
3775 * Caller should not hold any spin locks. We are protected from hold races
3776 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
3777 * lock held. A pv cannot be located otherwise.
3781 pv_put(pv_entry_t pv)
3784 if (pmap_enter_debug > 0) {
3786 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
3791 * Normal put-aways must have a pv_m associated with the pv,
3792 * but allow the case where the pv has been destructed due
3793 * to pmap_dynamic_delete.
3795 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
3798 * Fast - shortcut most common condition
3800 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
3811 * Remove the pmap association from a pv, require that pv_m already be removed,
3812 * then unlock and drop the pv. Any pte operations must have already been
3813 * completed. This call may result in a last-drop which will physically free
3816 * Removing the pmap association entails an additional drop.
3818 * pv must be exclusively locked on call and will be disposed of on return.
3822 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
3827 pv->pv_func_lastfree = func;
3828 pv->pv_line_lastfree = lineno;
3830 KKASSERT(pv->pv_m == NULL);
3831 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
3832 (PV_HOLD_LOCKED|1));
3833 if ((pmap = pv->pv_pmap) != NULL) {
3834 spin_lock(&pmap->pm_spin);
3835 KKASSERT(pv->pv_pmap == pmap);
3836 if (pmap->pm_pvhint_pt == pv)
3837 pmap->pm_pvhint_pt = NULL;
3838 if (pmap->pm_pvhint_unused == pv)
3839 pmap->pm_pvhint_unused = NULL;
3840 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
3841 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3844 spin_unlock(&pmap->pm_spin);
3847 * Try to shortcut three atomic ops, otherwise fall through
3848 * and do it normally. Drop two refs and the lock all in
3852 if (vm_page_unwire_quick(pvp->pv_m))
3853 panic("_pv_free: bad wirecount on pvp");
3855 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
3857 if (pmap_enter_debug > 0) {
3859 kprintf("pv_free: free pv %p\n", pv);
3865 pv_drop(pv); /* ref for pv_pmap */
3872 * This routine is very drastic, but can save the system
3880 static int warningdone=0;
3882 if (pmap_pagedaemon_waken == 0)
3884 pmap_pagedaemon_waken = 0;
3885 if (warningdone < 5) {
3886 kprintf("pmap_collect: collecting pv entries -- "
3887 "suggest increasing PMAP_SHPGPERPROC\n");
3891 for (i = 0; i < vm_page_array_size; i++) {
3892 m = &vm_page_array[i];
3893 if (m->wire_count || m->hold_count)
3895 if (vm_page_busy_try(m, TRUE) == 0) {
3896 if (m->wire_count == 0 && m->hold_count == 0) {
3905 * Scan the pmap for active page table entries and issue a callback.
3906 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
3907 * its parent page table.
3909 * pte_pv will be NULL if the page or page table is unmanaged.
3910 * pt_pv will point to the page table page containing the pte for the page.
3912 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
3913 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
3914 * process pmap's PD and page to the callback function. This can be
3915 * confusing because the pt_pv is really a pd_pv, and the target page
3916 * table page is simply aliased by the pmap and not owned by it.
3918 * It is assumed that the start and end are properly rounded to the page size.
3920 * It is assumed that PD pages and above are managed and thus in the RB tree,
3921 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
3923 struct pmap_scan_info {
3927 vm_pindex_t sva_pd_pindex;
3928 vm_pindex_t eva_pd_pindex;
3929 void (*func)(pmap_t, struct pmap_scan_info *,
3930 vm_pindex_t *, pv_entry_t, vm_offset_t,
3931 pt_entry_t *, void *);
3933 pmap_inval_bulk_t bulk_core;
3934 pmap_inval_bulk_t *bulk;
3939 static int pmap_scan_cmp(pv_entry_t pv, void *data);
3940 static int pmap_scan_callback(pv_entry_t pv, void *data);
3943 pmap_scan(struct pmap_scan_info *info, int smp_inval)
3945 struct pmap *pmap = info->pmap;
3946 pv_entry_t pt_pv; /* A page table PV */
3947 pv_entry_t pte_pv; /* A page table entry PV */
3948 vm_pindex_t *pte_placemark;
3949 vm_pindex_t *pt_placemark;
3952 struct pv_entry dummy_pv;
3957 if (info->sva == info->eva)
3960 info->bulk = &info->bulk_core;
3961 pmap_inval_bulk_init(&info->bulk_core, pmap);
3967 * Hold the token for stability; if the pmap is empty we have nothing
3971 if (pmap->pm_stats.resident_count == 0) {
3979 * Special handling for scanning one page, which is a very common
3980 * operation (it is?).
3982 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
3984 if (info->sva + PAGE_SIZE == info->eva) {
3985 if (info->sva >= VM_MAX_USER_ADDRESS) {
3987 * Kernel mappings do not track wire counts on
3988 * page table pages and only maintain pd_pv and
3989 * pte_pv levels so pmap_scan() works.
3992 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
3994 KKASSERT(pte_pv == NULL);
3995 ptep = vtopte(info->sva);
3998 * We hold pte_placemark across the operation for
4001 * WARNING! We must hold pt_placemark across the
4002 * *ptep test to prevent misintepreting
4003 * a non-zero *ptep as a shared page
4004 * table page. Hold it across the function
4005 * callback as well for SMP safety.
4007 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4009 KKASSERT(pte_pv == NULL);
4010 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4012 if (pt_pv == NULL) {
4015 pd_pv = pv_get(pmap,
4016 pmap_pd_pindex(info->sva),
4019 ptep = pv_pte_lookup(pd_pv,
4020 pmap_pt_index(info->sva));
4022 info->func(pmap, info,
4023 pt_placemark, pd_pv,
4027 pv_placemarker_wakeup(pmap,
4032 pv_placemarker_wakeup(pmap,
4036 pv_placemarker_wakeup(pmap, pt_placemark);
4038 pv_placemarker_wakeup(pmap, pte_placemark);
4041 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4045 * NOTE: *ptep can't be ripped out from under us if we hold
4046 * pte_pv (or pte_placemark) locked, but bits can
4052 KKASSERT(pte_pv == NULL);
4053 pv_placemarker_wakeup(pmap, pte_placemark);
4055 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]) ==
4056 pmap->pmap_bits[PG_V_IDX],
4057 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4058 *ptep, oldpte, info->sva));
4059 info->func(pmap, info, pte_placemark, pt_pv,
4060 info->sva, ptep, info->arg);
4065 pmap_inval_bulk_flush(info->bulk);
4070 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4073 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4074 * bounds, resulting in a pd_pindex of 0. To solve the
4075 * problem we use an inclusive range.
4077 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4078 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4080 if (info->sva >= VM_MAX_USER_ADDRESS) {
4082 * The kernel does not currently maintain any pv_entry's for
4083 * higher-level page tables.
4085 bzero(&dummy_pv, sizeof(dummy_pv));
4086 dummy_pv.pv_pindex = info->sva_pd_pindex;
4087 spin_lock(&pmap->pm_spin);
4088 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4089 pmap_scan_callback(&dummy_pv, info);
4090 ++dummy_pv.pv_pindex;
4091 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4094 spin_unlock(&pmap->pm_spin);
4097 * User page tables maintain local PML4, PDP, PD, and PT
4098 * pv_entry's. pv_entry's are not used for PTEs.
4100 spin_lock(&pmap->pm_spin);
4101 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4102 pmap_scan_callback, info);
4103 spin_unlock(&pmap->pm_spin);
4105 pmap_inval_bulk_flush(info->bulk);
4109 * WARNING! pmap->pm_spin held
4111 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4112 * bounds, resulting in a pd_pindex of 0. To solve the
4113 * problem we use an inclusive range.
4116 pmap_scan_cmp(pv_entry_t pv, void *data)
4118 struct pmap_scan_info *info = data;
4119 if (pv->pv_pindex < info->sva_pd_pindex)
4121 if (pv->pv_pindex > info->eva_pd_pindex)
4127 * pmap_scan() by PDs
4129 * WARNING! pmap->pm_spin held
4132 pmap_scan_callback(pv_entry_t pv, void *data)
4134 struct pmap_scan_info *info = data;
4135 struct pmap *pmap = info->pmap;
4136 pv_entry_t pd_pv; /* A page directory PV */
4137 pv_entry_t pt_pv; /* A page table PV */
4138 vm_pindex_t *pt_placemark;
4143 vm_offset_t va_next;
4144 vm_pindex_t pd_pindex;
4154 * Pull the PD pindex from the pv before releasing the spinlock.
4156 * WARNING: pv is faked for kernel pmap scans.
4158 pd_pindex = pv->pv_pindex;
4159 spin_unlock(&pmap->pm_spin);
4160 pv = NULL; /* invalid after spinlock unlocked */
4163 * Calculate the page range within the PD. SIMPLE pmaps are
4164 * direct-mapped for the entire 2^64 address space. Normal pmaps
4165 * reflect the user and kernel address space which requires
4166 * cannonicalization w/regards to converting pd_pindex's back
4169 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4170 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4171 (sva & PML4_SIGNMASK)) {
4172 sva |= PML4_SIGNMASK;
4174 eva = sva + NBPDP; /* can overflow */
4175 if (sva < info->sva)
4177 if (eva < info->sva || eva > info->eva)
4181 * NOTE: kernel mappings do not track page table pages, only
4184 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4185 * However, for the scan to be efficient we try to
4186 * cache items top-down.
4191 for (; sva < eva; sva = va_next) {
4194 if (sva >= VM_MAX_USER_ADDRESS) {
4203 * PD cache, scan shortcut if it doesn't exist.
4205 if (pd_pv == NULL) {
4206 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4207 } else if (pd_pv->pv_pmap != pmap ||
4208 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4210 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4212 if (pd_pv == NULL) {
4213 va_next = (sva + NBPDP) & ~PDPMASK;
4222 * NOTE: The cached pt_pv can be removed from the pmap when
4223 * pmap_dynamic_delete is enabled.
4225 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4226 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4230 if (pt_pv == NULL) {
4231 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4232 &pt_placemark, &error);
4234 pv_put(pd_pv); /* lock order */
4241 pv_placemarker_wait(pmap, pt_placemark);
4246 /* may have to re-check later if pt_pv is NULL here */
4250 * If pt_pv is NULL we either have a shared page table
4251 * page (NOT IMPLEMENTED XXX) and must issue a callback
4252 * specific to that case, or there is no page table page.
4254 * Either way we can skip the page table page.
4256 * WARNING! pt_pv can also be NULL due to a pv creation
4257 * race where we find it to be NULL and then
4258 * later see a pte_pv. But its possible the pt_pv
4259 * got created inbetween the two operations, so
4262 * XXX This should no longer be the case because
4263 * we have pt_placemark.
4265 if (pt_pv == NULL) {
4269 * Possible unmanaged (shared from another pmap)
4272 * WARNING! We must hold pt_placemark across the
4273 * *ptep test to prevent misintepreting
4274 * a non-zero *ptep as a shared page
4275 * table page. Hold it across the function
4276 * callback as well for SMP safety.
4279 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4280 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4281 info->func(pmap, info, pt_placemark, pd_pv,
4282 sva, ptep, info->arg);
4284 pv_placemarker_wakeup(pmap, pt_placemark);
4287 pv_placemarker_wakeup(pmap, pt_placemark);
4291 * Done, move to next page table page.
4293 va_next = (sva + NBPDR) & ~PDRMASK;
4300 * From this point in the loop testing pt_pv for non-NULL
4301 * means we are in UVM, else if it is NULL we are in KVM.
4303 * Limit our scan to either the end of the va represented
4304 * by the current page table page, or to the end of the
4305 * range being removed.
4308 va_next = (sva + NBPDR) & ~PDRMASK;
4315 * Scan the page table for pages. Some pages may not be
4316 * managed (might not have a pv_entry).
4318 * There is no page table management for kernel pages so
4319 * pt_pv will be NULL in that case, but otherwise pt_pv
4320 * is non-NULL, locked, and referenced.
4324 * At this point a non-NULL pt_pv means a UVA, and a NULL
4325 * pt_pv means a KVA.
4328 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4332 while (sva < va_next) {
4333 vm_pindex_t *pte_placemark;
4337 * Yield every 64 pages, stop if requested.
4339 if ((++info->count & 63) == 0)
4345 * We can shortcut our scan if *ptep == 0. This is
4346 * an unlocked check.
4356 * Acquire the pte_placemark. pte_pv's won't exist
4359 * A multitude of races are possible here so if we
4360 * cannot lock definite state we clean out our cache
4361 * and break the inner while() loop to force a loop
4362 * up to the top of the for().
4364 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4365 * validity instead of looping up?
4367 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4368 &pte_placemark, &error);
4369 KKASSERT(pte_pv == NULL);
4372 pv_put(pd_pv); /* lock order */
4376 pv_put(pt_pv); /* lock order */
4379 pv_placemarker_wait(pmap, pte_placemark);
4380 va_next = sva; /* retry */
4385 * Reload *ptep after successfully locking the
4391 pv_placemarker_wakeup(pmap, pte_placemark);
4398 * We can't hold pd_pv across the callback (because
4399 * we don't pass it to the callback and the callback
4403 vm_page_wire_quick(pd_pv->pv_m);
4408 * Ready for the callback. The locked placemarker
4409 * is consumed by the callback.
4411 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4415 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4416 ("badC *ptep %016lx/%016lx sva %016lx",
4417 *ptep, oldpte, sva));
4419 * We must unlock pd_pv across the callback
4420 * to avoid deadlocks on any recursive
4421 * disposal. Re-check that it still exists
4424 * Call target disposes of pte_placemark
4425 * and may destroy but will not dispose
4428 info->func(pmap, info, pte_placemark, pt_pv,
4429 sva, ptep, info->arg);
4434 * We must unlock pd_pv across the callback
4435 * to avoid deadlocks on any recursive
4436 * disposal. Re-check that it still exists
4439 * Call target disposes of pte_placemark
4440 * and may destroy but will not dispose
4443 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4444 ("badD *ptep %016lx/%016lx sva %016lx ",
4445 *ptep, oldpte, sva));
4446 info->func(pmap, info, pte_placemark, pt_pv,
4447 sva, ptep, info->arg);
4451 if (vm_page_unwire_quick(pd_pv->pv_m)) {
4452 panic("pmap_scan_callback: "
4453 "bad wirecount on pd_pv");
4455 if (pd_pv->pv_pmap == NULL) {
4456 va_next = sva; /* retry */
4462 * NOTE: The cached pt_pv can be removed from the
4463 * pmap when pmap_dynamic_delete is enabled,
4464 * which will cause ptep to become stale.
4466 * This also means that no pages remain under
4467 * the PT, so we can just break out of the inner
4468 * loop and let the outer loop clean everything
4471 if (pt_pv && pt_pv->pv_pmap != pmap)
4485 if ((++info->count & 7) == 0)
4489 * Relock before returning.
4491 spin_lock(&pmap->pm_spin);
4496 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4498 struct pmap_scan_info info;
4503 info.func = pmap_remove_callback;
4505 pmap_scan(&info, 1);
4508 if (eva - sva < 1024*1024) {
4510 cpu_invlpg((void *)sva);
4518 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4520 struct pmap_scan_info info;
4525 info.func = pmap_remove_callback;
4527 pmap_scan(&info, 0);
4531 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4532 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
4533 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4538 * Managed or unmanaged pte (pte_placemark is non-NULL)
4540 * pt_pv's wire_count is still bumped by unmanaged pages
4541 * so we must decrement it manually.
4543 * We have to unwire the target page table page.
4545 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4546 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4549 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4550 KKASSERT(pte & pmap->pmap_bits[PG_V_IDX]);
4551 if (pte & pmap->pmap_bits[PG_M_IDX])
4553 if (pte & pmap->pmap_bits[PG_A_IDX])
4554 vm_page_flag_set(p, PG_REFERENCED);
4557 * NOTE: p is not hard-busied so it is not safe to
4558 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4559 * transition against them being set in
4562 if (pte & pmap->pmap_bits[PG_RW_IDX])
4563 atomic_add_long(&p->md.writeable_count, -1);
4564 atomic_add_long(&p->md.pmap_count, -1);
4566 if (pte & pmap->pmap_bits[PG_V_IDX]) {
4567 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4568 if (pt_pv && vm_page_unwire_quick(pt_pv->pv_m))
4569 panic("pmap_remove: insufficient wirecount");
4571 if (pte & pmap->pmap_bits[PG_W_IDX])
4572 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4573 if (pte & pmap->pmap_bits[PG_G_IDX])
4574 cpu_invlpg((void *)va);
4575 pv_placemarker_wakeup(pmap, pte_placemark);
4579 * Removes this physical page from all physical maps in which it resides.
4580 * Reflects back modify bits to the pager.
4582 * This routine may not be called from an interrupt.
4584 * The page must be busied by its caller, preventing new ptes from being
4585 * installed. This allows us to assert that pmap_count is zero and safely
4586 * clear the MAPPED and WRITEABLE bits upon completion.
4590 pmap_remove_all(vm_page_t m)
4594 if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
4596 if (m->md.pmap_count == 0)
4599 retry = ticks + hz * 60;
4601 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
4602 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4603 PMAP_PAGE_BACKING_RETRY;
4604 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4605 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4607 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4608 vm_page_flag_set(m, PG_REFERENCED);
4611 * NOTE: m is not hard-busied so it is not safe to
4612 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4613 * transition against them being set in
4616 if (ipte & ipmap->pmap_bits[PG_RW_IDX])
4617 atomic_add_long(&m->md.writeable_count, -1);
4618 atomic_add_long(&m->md.pmap_count, -1);
4622 * Cleanup various tracking counters. pt_pv can't go away
4623 * due to our wired ref.
4625 if (ipmap != &kernel_pmap) {
4628 spin_lock_shared(&ipmap->pm_spin);
4629 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4630 spin_unlock_shared(&ipmap->pm_spin);
4633 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4634 panic("pmap_remove_all: bad "
4635 "wire_count on pt_pv");
4638 &ipmap->pm_stats.resident_count, -1);
4641 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4642 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4643 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4644 cpu_invlpg((void *)iva);
4645 } PMAP_PAGE_BACKING_DONE;
4648 * pmap_count should be zero but it is possible to race a pmap_enter()
4649 * replacement (see 'oldm'). Once it is zero it cannot become
4650 * non-zero because the page is hard-busied.
4652 if (m->md.pmap_count || m->md.writeable_count) {
4653 tsleep(&m->md.pmap_count, 0, "pgunm", 1);
4654 if (retry - ticks > 0)
4656 panic("pmap_remove_all: cannot return pmap_count "
4658 m->md.pmap_count, m->md.writeable_count);
4660 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
4664 * Removes the page from a particular pmap.
4666 * The page must be busied by the caller.
4669 pmap_remove_specific(pmap_t pmap_match, vm_page_t m)
4671 if (!pmap_initialized)
4673 if (m->md.pmap_count == 0)
4675 PMAP_PAGE_BACKING_SCAN(m, pmap_match, ipmap, iptep, ipte, iva) {
4676 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4677 PMAP_PAGE_BACKING_RETRY;
4678 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4679 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4681 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4682 vm_page_flag_set(m, PG_REFERENCED);
4685 * NOTE: m is not hard-busied so it is not safe to
4686 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4687 * transition against them being set in
4690 if (ipte & ipmap->pmap_bits[PG_RW_IDX])
4691 atomic_add_long(&m->md.writeable_count, -1);
4692 atomic_add_long(&m->md.pmap_count, -1);
4696 * Cleanup various tracking counters. pt_pv can't go away
4697 * due to our wired ref.
4699 if (ipmap != &kernel_pmap) {
4702 spin_lock_shared(&ipmap->pm_spin);
4703 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4704 spin_unlock_shared(&ipmap->pm_spin);
4708 &ipmap->pm_stats.resident_count, -1);
4709 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4710 panic("pmap_remove_specific: bad "
4711 "wire_count on pt_pv");
4715 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4716 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4717 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4718 cpu_invlpg((void *)iva);
4719 } PMAP_PAGE_BACKING_DONE;
4723 * Set the physical protection on the specified range of this map
4724 * as requested. This function is typically only used for debug watchpoints
4727 * This function may not be called from an interrupt if the map is
4728 * not the kernel_pmap.
4730 * NOTE! For shared page table pages we just unmap the page.
4733 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4735 struct pmap_scan_info info;
4736 /* JG review for NX */
4740 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
4741 pmap_remove(pmap, sva, eva);
4744 if (prot & VM_PROT_WRITE)
4749 info.func = pmap_protect_callback;
4751 pmap_scan(&info, 1);
4756 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
4757 vm_pindex_t *pte_placemark,
4758 pv_entry_t pt_pv, vm_offset_t va,
4759 pt_entry_t *ptep, void *arg __unused)
4769 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4770 cbits &= ~pmap->pmap_bits[PG_A_IDX];
4771 cbits &= ~pmap->pmap_bits[PG_M_IDX];
4773 /* else unmanaged page, adjust bits, no wire changes */
4776 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
4778 if (pmap_enter_debug > 0) {
4780 kprintf("pmap_protect va=%lx ptep=%p "
4781 "pt_pv=%p cbits=%08lx\n",
4782 va, ptep, pt_pv, cbits
4786 if (pbits != cbits) {
4787 if (!pmap_inval_smp_cmpset(pmap, va,
4788 ptep, pbits, cbits)) {
4792 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4793 KKASSERT((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
4794 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4795 if (pbits & pmap->pmap_bits[PG_A_IDX])
4796 vm_page_flag_set(m, PG_REFERENCED);
4797 if (pbits & pmap->pmap_bits[PG_M_IDX])
4799 if (pbits & pmap->pmap_bits[PG_RW_IDX])
4800 atomic_add_long(&m->md.writeable_count, -1);
4804 pv_placemarker_wakeup(pmap, pte_placemark);
4808 * Insert the vm_page (m) at the virtual address (va), replacing any prior
4809 * mapping at that address. Set protection and wiring as requested.
4811 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
4812 * possible. If it is we enter the page into the appropriate shared pmap
4813 * hanging off the related VM object instead of the passed pmap, then we
4814 * share the page table page from the VM object's pmap into the current pmap.
4816 * NOTE: This routine MUST insert the page into the pmap now, it cannot
4819 * NOTE: If (m) is PG_UNMANAGED it may also be a temporary fake vm_page_t.
4823 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4824 boolean_t wired, vm_map_entry_t entry)
4826 pv_entry_t pt_pv; /* page table */
4827 pv_entry_t pte_pv; /* page table entry */
4828 vm_pindex_t *pte_placemark;
4838 va = trunc_page(va);
4839 #ifdef PMAP_DIAGNOSTIC
4841 panic("pmap_enter: toobig");
4842 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
4843 panic("pmap_enter: invalid to pmap_enter page table "
4844 "pages (va: 0x%lx)", va);
4846 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
4847 kprintf("Warning: pmap_enter called on UVA with "
4850 db_print_backtrace();
4853 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
4854 kprintf("Warning: pmap_enter called on KVA without"
4857 db_print_backtrace();
4862 * Get the locked page table page (pt_pv) for our new page table
4863 * entry, allocating it if necessary.
4865 * There is no pte_pv for a terminal pte so the terminal pte will
4866 * be locked via pte_placemark.
4868 * Only MMU actions by the CPU itself can modify the ptep out from
4871 * If the pmap is still being initialized we assume existing
4874 * NOTE: Kernel mapppings do not track page table pages
4875 * (i.e. there is no pt_pv pt_pv structure).
4877 * NOTE: origpte here is 'tentative', used only to check for
4878 * the degenerate case where the entry already exists and
4881 if (pmap_initialized == FALSE) {
4884 pte_placemark = NULL;
4888 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
4889 KKASSERT(pte_pv == NULL);
4890 if (va >= VM_MAX_USER_ADDRESS) {
4894 pt_pv = pmap_allocpte(pmap, pmap_pt_pindex(va), NULL);
4895 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
4901 pa = VM_PAGE_TO_PHYS(m);
4904 * Calculate the new PTE.
4906 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
4907 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
4909 newpte |= pmap->pmap_bits[PG_W_IDX];
4910 if (va < VM_MAX_USER_ADDRESS)
4911 newpte |= pmap->pmap_bits[PG_U_IDX];
4912 if ((m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) == 0)
4913 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
4914 // if (pmap == &kernel_pmap)
4915 // newpte |= pgeflag;
4916 newpte |= pmap->pmap_cache_bits[m->pat_mode];
4917 if (m->flags & PG_FICTITIOUS)
4918 newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
4921 * It is possible for multiple faults to occur in threaded
4922 * environments, the existing pte might be correct.
4924 if (((origpte ^ newpte) &
4925 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
4926 pmap->pmap_bits[PG_A_IDX])) == 0) {
4931 * Adjust page flags. The page is soft-busied or hard-busied, we
4932 * should be able to safely set PG_* flag bits even with the (shared)
4935 * As a bit of a safety, bump pmap_count and set the PG_* bits
4936 * before mapping the page. If another part of the system does
4937 * not properly hard-busy the page (against our soft-busy) in
4938 * order to remove mappings it might not see the pte that we are
4939 * about to add and thus will not be able to drop pmap_count to 0.
4941 * NOTE! PG_MAPPED and PG_WRITEABLE can only be cleared when
4942 * the page is hard-busied AND pmap_count is 0. This
4943 * interlocks our setting of the flags here.
4945 /*vm_page_spin_lock(m);*/
4946 if ((m->flags & PG_UNMANAGED) == 0) {
4947 atomic_add_long(&m->md.pmap_count, 1);
4948 if (newpte & pmap->pmap_bits[PG_RW_IDX])
4949 atomic_add_long(&m->md.writeable_count, 1);
4951 if (newpte & pmap->pmap_bits[PG_RW_IDX]) {
4952 if ((m->flags & (PG_MAPPED | PG_WRITEABLE)) == 0)
4953 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
4955 if ((m->flags & PG_MAPPED) == 0)
4956 vm_page_flag_set(m, PG_MAPPED);
4958 /*vm_page_spin_unlock(m);*/
4959 /*pmap_page_stats_adding(m);*/
4962 * A race can develop when replacing an existing mapping. The new
4963 * page has been busied and the pte is placemark-locked, but the
4964 * old page is could be ripped out from under us at any time by
4967 * The race is handled by having the backing scans check pmap_count
4968 * writeable_count when doing operations that should ensure one
4971 opa = origpte & PG_FRAME;
4972 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
4973 oldm = PHYS_TO_VM_PAGE(opa);
4974 KKASSERT(opa == oldm->phys_addr);
4975 KKASSERT(entry != NULL);
4981 * Swap the new and old PTEs and perform any necessary SMP
4984 if ((prot & VM_PROT_NOSYNC) || (opa == 0 && pt_pv != NULL)) {
4986 * Explicitly permitted to avoid pmap cpu mask synchronization
4987 * or the prior content of a non-kernel-related pmap was
4990 origpte = atomic_swap_long(ptep, newpte);
4992 cpu_invlpg((void *)va);
4995 * Not permitted to avoid pmap cpu mask synchronization
4996 * or there prior content being replaced or this is a kernel
4999 * Due to other kernel optimizations, we cannot assume a
5000 * 0->non_zero transition of *ptep can be done with a swap.
5002 origpte = pmap_inval_smp(pmap, va, 1, ptep, newpte);
5004 opa = origpte & PG_FRAME;
5007 if (pmap_enter_debug > 0) {
5009 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5010 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5012 origpte, newpte, ptep,
5013 pte_pv, pt_pv, opa, prot);
5018 * Account for the changes in the pt_pv and pmap.
5020 * Retain the same wiring count due to replacing an existing page,
5021 * or bump the wiring count for a new page.
5023 if (pt_pv && opa == 0) {
5024 vm_page_wire_quick(pt_pv->pv_m);
5025 atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
5027 if (wired && (origpte & pmap->pmap_bits[PG_W_IDX]) == 0)
5028 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5031 * Account for the removal of the old page. pmap and pt_pv stats
5032 * have already been fully adjusted for both.
5034 * WARNING! oldm is not soft or hard-busied. The pte at worst can
5035 * only be removed out from under us since we hold the
5036 * placemarker. So if it is still there, it must not have
5039 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5040 KKASSERT(oldm == PHYS_TO_VM_PAGE(opa));
5041 /* XXX PG_DEVICE_IDX pages */
5042 if (origpte & pmap->pmap_bits[PG_M_IDX])
5043 vm_page_dirty(oldm);
5044 if (origpte & pmap->pmap_bits[PG_A_IDX])
5045 vm_page_flag_set(oldm, PG_REFERENCED);
5048 * NOTE: oldm is not hard-busied so it is not safe to
5049 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
5050 * transition against them being set in
5053 if (origpte & pmap->pmap_bits[PG_RW_IDX])
5054 atomic_add_long(&oldm->md.writeable_count, -1);
5055 atomic_add_long(&oldm->md.pmap_count, -1);
5059 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5060 (m->flags & PG_MAPPED));
5063 * Cleanup the pv entry, allowing other accessors. If the new page
5064 * is not managed but we have a pte_pv (which was locking our
5065 * operation), we can free it now. pte_pv->pv_m should be NULL.
5068 if (pte_pv && (newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5069 pv_free(pte_pv, pt_pv);
5070 } else if (pte_pv) {
5075 pv_placemarker_wakeup(pmap, pte_placemark);
5081 * Make a temporary mapping for a physical address. This is only intended
5082 * to be used for panic dumps.
5084 * The caller is responsible for calling smp_invltlb().
5087 pmap_kenter_temporary(vm_paddr_t pa, long i)
5089 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5090 return ((void *)crashdumpmap);
5094 #define MAX_INIT_PT (96)
5097 * This routine preloads the ptes for a given object into the specified pmap.
5098 * This eliminates the blast of soft faults on process startup and
5099 * immediately after an mmap.
5101 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5105 pmap_object_init_pt(pmap_t pmap, vm_map_entry_t entry,
5106 vm_offset_t addr, vm_size_t size, int limit)
5109 vm_prot_t prot = entry->protection;
5110 vm_object_t object = entry->ba.object;
5111 vm_pindex_t pindex = atop(entry->ba.offset + (addr - entry->ba.start));
5112 struct rb_vm_page_scan_info info;
5117 * We can't preinit if read access isn't set or there is no pmap
5120 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5124 * We can't preinit if the pmap is not the current pmap
5126 lp = curthread->td_lwp;
5127 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5131 * Misc additional checks
5133 psize = x86_64_btop(size);
5135 if ((object->type != OBJT_VNODE) ||
5136 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5137 (object->resident_page_count > MAX_INIT_PT))) {
5141 if (pindex + psize > object->size) {
5142 if (object->size < pindex)
5144 psize = object->size - pindex;
5151 * If everything is segment-aligned do not pre-init here. Instead
5152 * allow the normal vm_fault path to pass a segment hint to
5153 * pmap_enter() which will then use an object-referenced shared
5156 if ((addr & SEG_MASK) == 0 &&
5157 (ctob(psize) & SEG_MASK) == 0 &&
5158 (ctob(pindex) & SEG_MASK) == 0) {
5163 * Use a red-black scan to traverse the requested range and load
5164 * any valid pages found into the pmap.
5166 * We cannot safely scan the object's memq without holding the
5169 info.start_pindex = pindex;
5170 info.end_pindex = pindex + psize - 1;
5175 info.object = object;
5179 * By using the NOLK scan, the callback function must be sure
5180 * to return -1 if the VM page falls out of the object.
5182 vm_object_hold_shared(object);
5183 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5184 pmap_object_init_pt_callback, &info);
5185 vm_object_drop(object);
5193 pmap_object_init_pt_callback(vm_page_t p, void *data)
5195 struct rb_vm_page_scan_info *info = data;
5196 vm_pindex_t rel_index;
5200 * don't allow an madvise to blow away our really
5201 * free pages allocating pv entries.
5203 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5204 vmstats.v_free_count < vmstats.v_free_reserved) {
5209 * Ignore list markers and ignore pages we cannot instantly
5210 * busy (while holding the object token).
5212 if (p->flags & PG_MARKER)
5217 if (vm_page_busy_try(p, TRUE))
5220 if (vm_page_sbusy_try(p))
5223 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5224 (p->flags & PG_FICTITIOUS) == 0) {
5225 if ((p->queue - p->pc) == PQ_CACHE) {
5226 if (hard_busy == 0) {
5227 vm_page_sbusy_drop(p);
5231 vm_page_deactivate(p);
5233 rel_index = p->pindex - info->start_pindex;
5234 pmap_enter(info->pmap, info->addr + x86_64_ptob(rel_index), p,
5235 VM_PROT_READ, FALSE, info->entry);
5240 vm_page_sbusy_drop(p);
5243 * We are using an unlocked scan (that is, the scan expects its
5244 * current element to remain in the tree on return). So we have
5245 * to check here and abort the scan if it isn't.
5247 if (p->object != info->object)
5256 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5259 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5262 * The address must reside within a vm_map mapped range to ensure that the
5263 * page table doesn't get ripped out from under us.
5265 * XXX This is safe only because page table pages are not freed.
5268 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5272 /*spin_lock(&pmap->pm_spin);*/
5273 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5274 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5275 /*spin_unlock(&pmap->pm_spin);*/
5279 /*spin_unlock(&pmap->pm_spin);*/
5284 * Change the wiring attribute for a pmap/va pair. The mapping must already
5285 * exist in the pmap. The mapping may or may not be managed. The wiring in
5286 * the page is not changed, the page is returned so the caller can adjust
5287 * its wiring (the page is not locked in any way).
5289 * Wiring is not a hardware characteristic so there is no need to invalidate
5290 * TLB. However, in an SMP environment we must use a locked bus cycle to
5291 * update the pte (if we are not using the pmap_inval_*() API that is)...
5292 * it's ok to do this for simple wiring changes.
5295 pmap_unwire(pmap_t pmap, vm_offset_t va)
5306 * Assume elements in the kernel pmap are stable
5308 if (pmap == &kernel_pmap) {
5309 if (pmap_pt(pmap, va) == 0)
5311 ptep = pmap_pte_quick(pmap, va);
5312 if (pmap_pte_v(pmap, ptep)) {
5313 if (pmap_pte_w(pmap, ptep))
5314 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5315 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5316 pa = *ptep & PG_FRAME;
5317 m = PHYS_TO_VM_PAGE(pa);
5323 * We can only [un]wire pmap-local pages (we cannot wire
5326 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5330 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5331 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5336 if (pmap_pte_w(pmap, ptep)) {
5337 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5340 /* XXX else return NULL so caller doesn't unwire m ? */
5342 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5344 pa = *ptep & PG_FRAME;
5345 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5352 * Copy the range specified by src_addr/len from the source map to
5353 * the range dst_addr/len in the destination map.
5355 * This routine is only advisory and need not do anything.
5358 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5359 vm_size_t len, vm_offset_t src_addr)
5366 * Zero the specified physical page.
5368 * This function may be called from an interrupt and no locking is
5372 pmap_zero_page(vm_paddr_t phys)
5374 vm_offset_t va = PHYS_TO_DMAP(phys);
5376 pagezero((void *)va);
5382 * Zero part of a physical page by mapping it into memory and clearing
5383 * its contents with bzero.
5385 * off and size may not cover an area beyond a single hardware page.
5388 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5390 vm_offset_t virt = PHYS_TO_DMAP(phys);
5392 bzero((char *)virt + off, size);
5398 * Copy the physical page from the source PA to the target PA.
5399 * This function may be called from an interrupt. No locking
5403 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5405 vm_offset_t src_virt, dst_virt;
5407 src_virt = PHYS_TO_DMAP(src);
5408 dst_virt = PHYS_TO_DMAP(dst);
5409 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5413 * pmap_copy_page_frag:
5415 * Copy the physical page from the source PA to the target PA.
5416 * This function may be called from an interrupt. No locking
5420 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5422 vm_offset_t src_virt, dst_virt;
5424 src_virt = PHYS_TO_DMAP(src);
5425 dst_virt = PHYS_TO_DMAP(dst);
5427 bcopy((char *)src_virt + (src & PAGE_MASK),
5428 (char *)dst_virt + (dst & PAGE_MASK),
5433 * Remove all pages from specified address space this aids process exit
5434 * speeds. Also, this code may be special cased for the current process
5438 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5440 pmap_remove_noinval(pmap, sva, eva);
5445 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5446 * routines are inline, and a lot of things compile-time evaluate.
5450 pmap_testbit(vm_page_t m, int bit)
5454 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5457 * Nothing to do if all the mappings are already read-only.
5458 * The page's [M]odify bits have already been synchronized
5459 * to the vm_page_t and cleaned out.
5461 if (bit == PG_M_IDX && m->md.writeable_count == 0)
5465 * Iterate the mapping
5467 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5468 if (ipte & ipmap->pmap_bits[bit]) {
5472 } PMAP_PAGE_BACKING_DONE;
5477 * This routine is used to modify bits in ptes. Only one bit should be
5478 * specified. PG_RW requires special handling.
5480 * Caller must NOT hold any spin locks
5481 * Caller must hold (m) hard-busied
5483 * NOTE: When clearing PG_M we could also (not implemented) drop
5484 * through to the PG_RW code and clear PG_RW too, forcing
5485 * a fault on write to redetect PG_M for virtual kernels, but
5486 * it isn't necessary since virtual kernels invalidate the
5487 * pte when they clear the VPTE_M bit in their virtual page
5490 * NOTE: Does not re-dirty the page when clearing only PG_M.
5492 * NOTE: Because we do not lock the pv, *pte can be in a state of
5493 * flux. Despite this the value of *pte is still somewhat
5494 * related while we hold the vm_page spin lock.
5496 * *pte can be zero due to this race. Since we are clearing
5497 * bits we basically do no harm when this race occurs.
5501 pmap_clearbit(vm_page_t m, int bit_index)
5507 * XXX It might make sense to allow PG_FICTITIOUS + PG_DEVICE
5508 * pages through to the backing scan, but atm devices do
5509 * not care about PG_WRITEABLE;
5511 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
5512 if (bit_index == PG_RW_IDX)
5513 vm_page_flag_clear(m, PG_WRITEABLE);
5518 * Being asked to clear other random bits, we don't track them
5519 * so we have to iterate.
5521 if (bit_index != PG_RW_IDX) {
5522 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5523 if (ipte & ipmap->pmap_bits[bit_index]) {
5524 atomic_clear_long(iptep,
5525 ipmap->pmap_bits[bit_index]);
5527 } PMAP_PAGE_BACKING_DONE;
5532 * Being asked to clear the RW bit.
5534 * Nothing to do if all the mappings are already read-only
5536 if (m->md.writeable_count == 0)
5540 * Iterate the mappings and check.
5542 retry = ticks + hz * 60;
5545 * Clear PG_RW. This also clears PG_M and marks the page dirty if
5548 * Since the caller holds the page hard-busied we can safely clear
5549 * PG_WRITEABLE, and callers expect us to for the PG_RW_IDX path.
5551 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5552 if ((ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5554 if ((ipte & ipmap->pmap_bits[PG_RW_IDX]) == 0)
5556 npte = ipte & ~(ipmap->pmap_bits[PG_RW_IDX] |
5557 ipmap->pmap_bits[PG_M_IDX]);
5558 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, npte))
5559 PMAP_PAGE_BACKING_RETRY;
5560 if (ipte & ipmap->pmap_bits[PG_M_IDX])
5564 * NOTE: m is not hard-busied so it is not safe to
5565 * clear PG_WRITEABLE on the 1->0 transition
5566 * against it being set in pmap_enter().
5568 atomic_add_long(&m->md.writeable_count, -1);
5569 } PMAP_PAGE_BACKING_DONE;
5572 * writeable_count should be zero but it is possible to race
5573 * a pmap_enter() replacement (see 'oldm'). Once it is zero
5574 * it cannot become non-zero because the page is hard-busied.
5576 if (m->md.writeable_count != 0) {
5577 tsleep(&m->md.writeable_count, 0, "pgwab", 1);
5578 if (retry - ticks > 0)
5580 panic("pmap_remove_all: cannot return writeable_count "
5582 m->md.writeable_count);
5584 vm_page_flag_clear(m, PG_WRITEABLE);
5588 * Lower the permission for all mappings to a given page.
5590 * Page must be hard-busied by caller. Because the page is busied by the
5591 * caller, this should not be able to race a pmap_enter().
5594 pmap_page_protect(vm_page_t m, vm_prot_t prot)
5596 /* JG NX support? */
5597 if ((prot & VM_PROT_WRITE) == 0) {
5598 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
5600 * NOTE: pmap_clearbit(.. PG_RW) also clears
5601 * the PG_WRITEABLE flag in (m).
5603 pmap_clearbit(m, PG_RW_IDX);
5611 pmap_phys_address(vm_pindex_t ppn)
5613 return (x86_64_ptob(ppn));
5617 * Return a count of reference bits for a page, clearing those bits.
5618 * It is not necessary for every reference bit to be cleared, but it
5619 * is necessary that 0 only be returned when there are truly no
5620 * reference bits set.
5622 * XXX: The exact number of bits to check and clear is a matter that
5623 * should be tested and standardized at some point in the future for
5624 * optimal aging of shared pages.
5626 * This routine may not block.
5629 pmap_ts_referenced(vm_page_t m)
5634 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5636 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5637 if (ipte & ipmap->pmap_bits[PG_A_IDX]) {
5638 npte = ipte & ~ipmap->pmap_bits[PG_A_IDX];
5639 if (!atomic_cmpset_long(iptep, ipte, npte))
5640 PMAP_PAGE_BACKING_RETRY;
5645 } PMAP_PAGE_BACKING_DONE;
5652 * Return whether or not the specified physical page was modified
5653 * in any physical maps.
5656 pmap_is_modified(vm_page_t m)
5660 res = pmap_testbit(m, PG_M_IDX);
5665 * Clear the modify bit on the vm_page.
5667 * The page must be hard-busied.
5670 pmap_clear_modify(vm_page_t m)
5672 pmap_clearbit(m, PG_M_IDX);
5676 * pmap_clear_reference:
5678 * Clear the reference bit on the specified physical page.
5681 pmap_clear_reference(vm_page_t m)
5683 pmap_clearbit(m, PG_A_IDX);
5687 * Miscellaneous support routines follow
5692 x86_64_protection_init(void)
5698 * NX supported? (boot time loader.conf override only)
5700 * -1 Automatic (sets mode 1)
5702 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
5703 * 2 NX implemented for all cases
5705 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
5706 if ((amd_feature & AMDID_NX) == 0) {
5707 pmap_bits_default[PG_NX_IDX] = 0;
5709 } else if (pmap_nx_enable < 0) {
5710 pmap_nx_enable = 1; /* default to mode 1 (READ) */
5714 * 0 is basically read-only access, but also set the NX (no-execute)
5715 * bit when VM_PROT_EXECUTE is not specified.
5717 kp = protection_codes;
5718 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
5720 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
5722 * This case handled elsewhere
5726 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
5728 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
5730 if (pmap_nx_enable >= 1)
5731 *kp = pmap_bits_default[PG_NX_IDX];
5733 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
5734 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
5736 * Execute requires read access
5740 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
5741 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
5743 * Write without execute is RW|NX
5744 * (pmap_nx_enable mode >= 2)
5746 *kp = pmap_bits_default[PG_RW_IDX];
5747 if (pmap_nx_enable >= 2)
5748 *kp |= pmap_bits_default[PG_NX_IDX];
5750 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
5751 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
5753 * Write with execute is RW
5755 *kp = pmap_bits_default[PG_RW_IDX];
5763 * Map a set of physical memory pages into the kernel virtual
5764 * address space. Return a pointer to where it is mapped. This
5765 * routine is intended to be used for mapping device memory,
5768 * NOTE: We can't use pgeflag unless we invalidate the pages one at
5771 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
5772 * work whether the cpu supports PAT or not. The remaining PAT
5773 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
5777 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
5779 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5783 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
5785 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
5789 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5791 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5795 * Map a set of physical memory pages into the kernel virtual
5796 * address space. Return a pointer to where it is mapped. This
5797 * routine is intended to be used for mapping device memory,
5801 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
5803 vm_offset_t va, tmpva, offset;
5807 offset = pa & PAGE_MASK;
5808 size = roundup(offset + size, PAGE_SIZE);
5810 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
5812 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
5814 pa = pa & ~PAGE_MASK;
5815 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
5816 pte = vtopte(tmpva);
5818 kernel_pmap.pmap_bits[PG_RW_IDX] |
5819 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
5820 kernel_pmap.pmap_cache_bits[mode];
5821 tmpsize -= PAGE_SIZE;
5825 pmap_invalidate_range(&kernel_pmap, va, va + size);
5826 pmap_invalidate_cache_range(va, va + size);
5828 return ((void *)(va + offset));
5832 pmap_unmapdev(vm_offset_t va, vm_size_t size)
5834 vm_offset_t base, offset;
5836 base = va & ~PAGE_MASK;
5837 offset = va & PAGE_MASK;
5838 size = roundup(offset + size, PAGE_SIZE);
5839 pmap_qremove(va, size >> PAGE_SHIFT);
5840 kmem_free(&kernel_map, base, size);
5844 * Sets the memory attribute for the specified page.
5847 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5853 * If "m" is a normal page, update its direct mapping. This update
5854 * can be relied upon to perform any cache operations that are
5855 * required for data coherence.
5857 if ((m->flags & PG_FICTITIOUS) == 0)
5858 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
5862 * Change the PAT attribute on an existing kernel memory map. Caller
5863 * must ensure that the virtual memory in question is not accessed
5864 * during the adjustment.
5867 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
5874 panic("pmap_change_attr: va is NULL");
5875 base = trunc_page(va);
5879 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
5880 kernel_pmap.pmap_cache_bits[mode];
5885 changed = 1; /* XXX: not optimal */
5888 * Flush CPU caches if required to make sure any data isn't cached that
5889 * shouldn't be, etc.
5892 pmap_invalidate_range(&kernel_pmap, base, va);
5893 pmap_invalidate_cache_range(base, va);
5898 * perform the pmap work for mincore
5901 pmap_mincore(pmap_t pmap, vm_offset_t addr)
5903 pt_entry_t *ptep, pte;
5907 ptep = pmap_pte(pmap, addr);
5909 if (ptep && (pte = *ptep) != 0) {
5912 val = MINCORE_INCORE;
5913 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5916 pa = pte & PG_FRAME;
5918 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
5921 m = PHYS_TO_VM_PAGE(pa);
5926 if (pte & pmap->pmap_bits[PG_M_IDX])
5927 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
5929 * Modified by someone
5931 else if (m && (m->dirty || pmap_is_modified(m)))
5932 val |= MINCORE_MODIFIED_OTHER;
5936 if (pte & pmap->pmap_bits[PG_A_IDX])
5937 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
5940 * Referenced by someone
5942 else if (m && ((m->flags & PG_REFERENCED) ||
5943 pmap_ts_referenced(m))) {
5944 val |= MINCORE_REFERENCED_OTHER;
5945 vm_page_flag_set(m, PG_REFERENCED);
5954 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
5955 * vmspace will be ref'd and the old one will be deref'd.
5957 * The vmspace for all lwps associated with the process will be adjusted
5958 * and cr3 will be reloaded if any lwp is the current lwp.
5960 * The process must hold the vmspace->vm_map.token for oldvm and newvm
5963 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
5965 struct vmspace *oldvm;
5968 oldvm = p->p_vmspace;
5969 if (oldvm != newvm) {
5972 p->p_vmspace = newvm;
5973 KKASSERT(p->p_nthreads == 1);
5974 lp = RB_ROOT(&p->p_lwp_tree);
5975 pmap_setlwpvm(lp, newvm);
5982 * Set the vmspace for a LWP. The vmspace is almost universally set the
5983 * same as the process vmspace, but virtual kernels need to swap out contexts
5984 * on a per-lwp basis.
5986 * Caller does not necessarily hold any vmspace tokens. Caller must control
5987 * the lwp (typically be in the context of the lwp). We use a critical
5988 * section to protect against statclock and hardclock (statistics collection).
5991 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
5993 struct vmspace *oldvm;
5997 oldvm = lp->lwp_vmspace;
5999 if (oldvm != newvm) {
6002 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6003 lp->lwp_vmspace = newvm;
6004 if (td->td_lwp == lp) {
6005 pmap = vmspace_pmap(newvm);
6006 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6007 if (pmap->pm_active_lock & CPULOCK_EXCL)
6008 pmap_interlock_wait(newvm);
6009 #if defined(SWTCH_OPTIM_STATS)
6012 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6013 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6014 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6015 td->td_pcb->pcb_cr3_iso =
6016 vtophys(pmap->pm_pml4_iso);
6017 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6019 td->td_pcb->pcb_cr3_iso = 0;
6020 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6022 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6023 td->td_pcb->pcb_cr3 = KPML4phys;
6024 td->td_pcb->pcb_cr3_iso = 0;
6025 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6027 panic("pmap_setlwpvm: unknown pmap type\n");
6031 * The MMU separation fields needs to be updated.
6032 * (it can't access the pcb directly from the
6033 * restricted user pmap).
6036 struct trampframe *tramp;
6038 tramp = &pscpu->trampoline;
6039 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6040 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6041 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6042 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6043 /* tr_pcb_rsp doesn't change */
6047 * In kernel-land we always use the normal PML4E
6048 * so the kernel is fully mapped and can also access
6051 load_cr3(td->td_pcb->pcb_cr3);
6052 pmap = vmspace_pmap(oldvm);
6053 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6061 * Called when switching to a locked pmap, used to interlock against pmaps
6062 * undergoing modifications to prevent us from activating the MMU for the
6063 * target pmap until all such modifications have completed. We have to do
6064 * this because the thread making the modifications has already set up its
6065 * SMP synchronization mask.
6067 * This function cannot sleep!
6072 pmap_interlock_wait(struct vmspace *vm)
6074 struct pmap *pmap = &vm->vm_pmap;
6076 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6078 KKASSERT(curthread->td_critcount >= 2);
6079 DEBUG_PUSH_INFO("pmap_interlock_wait");
6080 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6082 lwkt_process_ipiq();
6090 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6093 if ((obj == NULL) || (size < NBPDR) ||
6094 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6098 addr = roundup2(addr, NBPDR);
6103 * Used by kmalloc/kfree, page already exists at va
6106 pmap_kvtom(vm_offset_t va)
6108 pt_entry_t *ptep = vtopte(va);
6110 KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
6111 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6115 * Initialize machine-specific shared page directory support. This
6116 * is executed when a VM object is created.
6119 pmap_object_init(vm_object_t object)
6124 * Clean up machine-specific shared page directory support. This
6125 * is executed when a VM object is destroyed.
6128 pmap_object_free(vm_object_t object)
6133 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6134 * VM page and issue a pginfo->callback.
6138 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6139 vm_pindex_t *pte_placemark,
6140 pv_entry_t pt_pv, vm_offset_t va,
6141 pt_entry_t *ptep, void *arg)
6143 struct pmap_pgscan_info *pginfo = arg;
6150 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
6152 * Try to busy the page while we hold the pte_placemark locked.
6154 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6155 if (vm_page_busy_try(m, TRUE) == 0) {
6156 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6158 * The callback is issued with the pt_pv
6161 pv_placemarker_wakeup(pmap, pte_placemark);
6163 vm_page_wire_quick(pt_pv->pv_m);
6166 if (pginfo->callback(pginfo, va, m) < 0)
6170 if (vm_page_unwire_quick(pt_pv->pv_m)) {
6171 panic("pmap_pgscan: bad wire_"
6177 pv_placemarker_wakeup(pmap, pte_placemark);
6180 ++pginfo->busycount;
6181 pv_placemarker_wakeup(pmap, pte_placemark);
6185 * Shared page table or unmanaged page (sharept or !sharept)
6187 pv_placemarker_wakeup(pmap, pte_placemark);
6192 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6194 struct pmap_scan_info info;
6196 pginfo->offset = pginfo->beg_addr;
6197 info.pmap = pginfo->pmap;
6198 info.sva = pginfo->beg_addr;
6199 info.eva = pginfo->end_addr;
6200 info.func = pmap_pgscan_callback;
6202 pmap_scan(&info, 0);
6204 pginfo->offset = pginfo->end_addr;
6208 * Wait for a placemarker that we do not own to clear. The placemarker
6209 * in question is not necessarily set to the pindex we want, we may have
6210 * to wait on the element because we want to reserve it ourselves.
6212 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6213 * PM_NOPLACEMARK, so it does not interfere with placemarks
6214 * which have already been woken up.
6218 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6220 if (*pmark != PM_NOPLACEMARK) {
6221 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
6222 tsleep_interlock(pmark, 0);
6223 if (*pmark != PM_NOPLACEMARK)
6224 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6229 * Wakeup a placemarker that we own. Replace the entry with
6230 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6234 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6238 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6239 KKASSERT(pindex != PM_NOPLACEMARK);
6240 if (pindex & PM_PLACEMARK_WAKEUP)