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>
97 #define PMAP_KEEP_PDIRS
99 #if defined(DIAGNOSTIC)
100 #define PMAP_DIAGNOSTIC
106 * pmap debugging will report who owns a pv lock when blocking.
110 #define PMAP_DEBUG_DECL ,const char *func, int lineno
111 #define PMAP_DEBUG_ARGS , __func__, __LINE__
112 #define PMAP_DEBUG_COPY , func, lineno
114 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp \
116 #define pv_lock(pv) _pv_lock(pv \
118 #define pv_hold_try(pv) _pv_hold_try(pv \
120 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp \
123 #define pv_free(pv, pvp) _pv_free(pv, pvp PMAP_DEBUG_ARGS)
127 #define PMAP_DEBUG_DECL
128 #define PMAP_DEBUG_ARGS
129 #define PMAP_DEBUG_COPY
131 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp)
132 #define pv_lock(pv) _pv_lock(pv)
133 #define pv_hold_try(pv) _pv_hold_try(pv)
134 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp)
135 #define pv_free(pv, pvp) _pv_free(pv, pvp)
140 * Get PDEs and PTEs for user/kernel address space
142 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
144 #define pmap_pde_v(pmap, pte) \
145 ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
146 #define pmap_pte_w(pmap, pte) \
147 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
148 #define pmap_pte_m(pmap, pte) \
149 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
150 #define pmap_pte_u(pmap, pte) \
151 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
152 #define pmap_pte_v(pmap, pte) \
153 ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
156 * Given a map and a machine independent protection code,
157 * convert to a vax protection code.
159 #define pte_prot(m, p) \
160 (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
161 static uint64_t protection_codes[PROTECTION_CODES_SIZE];
163 #define PMAP_PAGE_BACKING_SCAN(m, match_pmap, ipmap, iptep, ipte, iva) \
165 vm_object_t iobj = m->object; \
166 vm_map_backing_t iba, next_ba; \
167 struct pmap *ipmap; \
171 vm_pindex_t ipindex_start; \
172 vm_pindex_t ipindex_end; \
174 lockmgr(&iobj->backing_lk, LK_SHARED); \
175 next_ba = TAILQ_FIRST(&iobj->backing_list); \
176 while ((iba = next_ba) != NULL) { \
177 next_ba = TAILQ_NEXT(iba, entry); \
179 if (match_pmap && ipmap != match_pmap) \
181 ipindex_start = iba->offset >> PAGE_SHIFT; \
182 ipindex_end = ipindex_start + \
183 ((iba->end - iba->start) >> PAGE_SHIFT); \
184 if (m->pindex < ipindex_start || \
185 m->pindex >= ipindex_end) { \
189 ((m->pindex - ipindex_start) << PAGE_SHIFT); \
190 iptep = pmap_pte(ipmap, iva); \
194 if (m->phys_addr != (ipte & PG_FRAME)) \
197 #define PMAP_PAGE_BACKING_RETRY \
203 #define PMAP_PAGE_BACKING_DONE \
205 lockmgr(&iobj->backing_lk, LK_RELEASE); \
208 struct pmap kernel_pmap;
209 struct pmap iso_pmap;
211 vm_paddr_t avail_start; /* PA of first available physical page */
212 vm_paddr_t avail_end; /* PA of last available physical page */
213 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
214 vm_offset_t virtual2_end;
215 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
216 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
217 vm_offset_t KvaStart; /* VA start of KVA space */
218 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
219 vm_offset_t KvaSize; /* max size of kernel virtual address space */
220 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
221 //static int pgeflag; /* PG_G or-in */
225 static vm_paddr_t dmaplimit;
226 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
228 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
229 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
231 static uint64_t KPTbase;
232 static uint64_t KPTphys;
233 static uint64_t KPDphys; /* phys addr of kernel level 2 */
234 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
235 uint64_t KPDPphys; /* phys addr of kernel level 3 */
236 uint64_t KPML4phys; /* phys addr of kernel level 4 */
238 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
239 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
242 * Data for the pv entry allocation mechanism
244 __read_mostly static vm_zone_t pvzone;
245 __read_mostly static int pmap_pagedaemon_waken = 0;
246 static struct vm_zone pvzone_store;
247 static struct pv_entry *pvinit;
250 * All those kernel PT submaps that BSD is so fond of
252 pt_entry_t *CMAP1 = NULL, *ptmmap;
253 caddr_t CADDR1 = NULL, ptvmmap = NULL;
254 static pt_entry_t *msgbufmap;
255 struct msgbuf *msgbufp=NULL;
258 * PMAP default PG_* bits. Needed to be able to add
259 * EPT/NPT pagetable pmap_bits for the VMM module
261 uint64_t pmap_bits_default[] = {
262 REGULAR_PMAP, /* TYPE_IDX 0 */
263 X86_PG_V, /* PG_V_IDX 1 */
264 X86_PG_RW, /* PG_RW_IDX 2 */
265 X86_PG_U, /* PG_U_IDX 3 */
266 X86_PG_A, /* PG_A_IDX 4 */
267 X86_PG_M, /* PG_M_IDX 5 */
268 X86_PG_PS, /* PG_PS_IDX3 6 */
269 X86_PG_G, /* PG_G_IDX 7 */
270 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
271 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
272 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
273 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
274 X86_PG_NX, /* PG_NX_IDX 12 */
279 static pt_entry_t *pt_crashdumpmap;
280 static caddr_t crashdumpmap;
282 static int pmap_debug = 0;
283 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
284 &pmap_debug, 0, "Debug pmap's");
286 static int pmap_enter_debug = 0;
287 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
288 &pmap_enter_debug, 0, "Debug pmap_enter's");
290 static int pmap_yield_count = 64;
291 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
292 &pmap_yield_count, 0, "Yield during init_pt/release");
293 int pmap_fast_kernel_cpusync = 0;
294 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
295 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
296 int pmap_dynamic_delete = 0;
297 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
298 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
299 int pmap_lock_delay = 100;
300 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
301 &pmap_lock_delay, 0, "Spin loops");
302 static int meltdown_mitigation = -1;
303 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
304 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
305 &meltdown_mitigation, 0, "Userland pmap isolation");
307 static int pmap_nx_enable = -1; /* -1 = auto */
308 /* needs manual TUNABLE in early probe, see below */
309 SYSCTL_INT(_machdep, OID_AUTO, pmap_nx_enable, CTLFLAG_RD,
311 "no-execute support (0=disabled, 1=w/READ, 2=w/READ & WRITE)");
313 static int pmap_pv_debug = 50;
314 SYSCTL_INT(_machdep, OID_AUTO, pmap_pv_debug, CTLFLAG_RW,
315 &pmap_pv_debug, 0, "");
317 static long vm_pmap_pv_entries;
318 SYSCTL_LONG(_vm, OID_AUTO, pmap_pv_entries, CTLFLAG_RD,
319 &vm_pmap_pv_entries, 0, "");
321 /* Standard user access funtions */
322 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
324 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
325 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
326 extern int std_fubyte (const uint8_t *base);
327 extern int std_subyte (uint8_t *base, uint8_t byte);
328 extern int32_t std_fuword32 (const uint32_t *base);
329 extern int64_t std_fuword64 (const uint64_t *base);
330 extern int std_suword64 (uint64_t *base, uint64_t word);
331 extern int std_suword32 (uint32_t *base, int word);
332 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
333 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
334 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
335 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
338 static void pv_hold(pv_entry_t pv);
340 static int _pv_hold_try(pv_entry_t pv
342 static void pv_drop(pv_entry_t pv);
343 static void _pv_lock(pv_entry_t pv
345 static void pv_unlock(pv_entry_t pv);
346 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
348 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
350 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
351 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
352 vm_pindex_t **pmarkp, int *errorp);
353 static void pv_put(pv_entry_t pv);
354 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
355 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
357 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
358 pmap_inval_bulk_t *bulk, int destroy);
359 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
360 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
361 pmap_inval_bulk_t *bulk);
363 struct pmap_scan_info;
364 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
365 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
366 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
367 static void pmap_protect_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);
371 static void x86_64_protection_init (void);
372 static void create_pagetables(vm_paddr_t *firstaddr);
373 static void pmap_remove_all (vm_page_t m);
374 static boolean_t pmap_testbit (vm_page_t m, int bit);
376 static pt_entry_t *pmap_pte_quick (pmap_t pmap, vm_offset_t va);
377 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
379 static void pmap_pinit_defaults(struct pmap *pmap);
380 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
381 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
384 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
386 if (pv1->pv_pindex < pv2->pv_pindex)
388 if (pv1->pv_pindex > pv2->pv_pindex)
393 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
394 pv_entry_compare, vm_pindex_t, pv_pindex);
397 * Keep track of pages in the pmap. The procedure is handed
398 * the vm_page->md.pmap_count value prior to an increment or
401 * t_arm - Active real memory
402 * t_avm - Active virtual memory
403 * t_armshr - Active real memory that is also shared
404 * t_avmshr - Active virtual memory that is also shared
406 * NOTE: At the moment t_avm is effectively just the same as t_arm.
410 pmap_page_stats_adding(long prev_count)
412 globaldata_t gd = mycpu;
414 if (prev_count == 0) {
415 ++gd->gd_vmtotal.t_arm;
416 ++gd->gd_vmtotal.t_avm;
417 } else if (prev_count == 1) {
418 ++gd->gd_vmtotal.t_armshr;
419 ++gd->gd_vmtotal.t_avmshr;
421 ++gd->gd_vmtotal.t_avmshr;
427 pmap_page_stats_deleting(long prev_count)
429 globaldata_t gd = mycpu;
431 if (prev_count == 1) {
432 --gd->gd_vmtotal.t_arm;
433 --gd->gd_vmtotal.t_avm;
434 } else if (prev_count == 2) {
435 --gd->gd_vmtotal.t_armshr;
436 --gd->gd_vmtotal.t_avmshr;
438 --gd->gd_vmtotal.t_avmshr;
443 * Move the kernel virtual free pointer to the next
444 * 2MB. This is used to help improve performance
445 * by using a large (2MB) page for much of the kernel
446 * (.text, .data, .bss)
450 pmap_kmem_choose(vm_offset_t addr)
452 vm_offset_t newaddr = addr;
454 newaddr = roundup2(addr, NBPDR);
459 * Returns the pindex of a page table entry (representing a terminal page).
460 * There are NUPTE_TOTAL page table entries possible (a huge number)
462 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
463 * We want to properly translate negative KVAs.
467 pmap_pte_pindex(vm_offset_t va)
469 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
473 * Returns the pindex of a page table.
477 pmap_pt_pindex(vm_offset_t va)
479 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
483 * Returns the pindex of a page directory.
487 pmap_pd_pindex(vm_offset_t va)
489 return (NUPTE_TOTAL + NUPT_TOTAL +
490 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
495 pmap_pdp_pindex(vm_offset_t va)
497 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
498 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
503 pmap_pml4_pindex(void)
505 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
509 * Return various clipped indexes for a given VA
511 * Returns the index of a pt in a page directory, representing a page
516 pmap_pt_index(vm_offset_t va)
518 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
522 * Returns the index of a pd in a page directory page, representing a page
527 pmap_pd_index(vm_offset_t va)
529 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
533 * Returns the index of a pdp in the pml4 table, representing a page
538 pmap_pdp_index(vm_offset_t va)
540 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
544 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
545 * the PT layer. This will speed up core pmap operations considerably.
546 * We also cache the PTE layer to (hopefully) improve relative lookup
549 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
550 * must be in a known associated state (typically by being locked when
551 * the pmap spinlock isn't held). We allow the race for that case.
553 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
554 * cpu_ccfence() to prevent compiler optimizations from reloading the
559 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
561 if (pindex < pmap_pt_pindex(0)) {
563 } else if (pindex < pmap_pd_pindex(0)) {
564 pmap->pm_pvhint_pt = pv;
569 * Locate the requested pt_entry
573 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
577 if (pindex < pmap_pt_pindex(0))
580 if (pindex < pmap_pd_pindex(0))
581 pv = pmap->pm_pvhint_pt;
585 if (pv == NULL || pv->pv_pmap != pmap) {
586 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
588 pv_cache(pmap, pv, pindex);
589 } else if (pv->pv_pindex != pindex) {
590 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
593 pv_cache(pmap, pv, pindex);
596 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
604 * Super fast pmap_pte routine best used when scanning the pv lists.
605 * This eliminates many course-grained invltlb calls. Note that many of
606 * the pv list scans are across different pmaps and it is very wasteful
607 * to do an entire invltlb when checking a single mapping.
609 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
613 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
615 return pmap_pte(pmap, va);
619 * The placemarker hash must be broken up into four zones so lock
620 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
622 * Placemarkers are used to 'lock' page table indices that do not have
623 * a pv_entry. This allows the pmap to support managed and unmanaged
624 * pages and shared page tables.
626 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
630 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
634 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
636 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
638 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
639 hi = PM_PLACE_BASE << 1;
640 else /* zone 3 - PDP (and PML4E) */
641 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
642 hi += pindex & (PM_PLACE_BASE - 1);
644 return (&pmap->pm_placemarks[hi]);
649 * Generic procedure to index a pte from a pt, pd, or pdp.
651 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
652 * a page table page index but is instead of PV lookup index.
656 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
660 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
661 return(&pte[pindex]);
665 * Return pointer to PDP slot in the PML4
669 pmap_pdp(pmap_t pmap, vm_offset_t va)
671 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
675 * Return pointer to PD slot in the PDP given a pointer to the PDP
679 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
683 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
684 return (&pd[pmap_pd_index(va)]);
688 * Return pointer to PD slot in the PDP.
692 pmap_pd(pmap_t pmap, vm_offset_t va)
696 pdp = pmap_pdp(pmap, va);
697 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
699 return (pmap_pdp_to_pd(*pdp, va));
703 * Return pointer to PT slot in the PD given a pointer to the PD
707 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
711 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
712 return (&pt[pmap_pt_index(va)]);
716 * Return pointer to PT slot in the PD
718 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
719 * so we cannot lookup the PD via the PDP. Instead we
720 * must look it up via the pmap.
724 pmap_pt(pmap_t pmap, vm_offset_t va)
728 vm_pindex_t pd_pindex;
731 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
732 pd_pindex = pmap_pd_pindex(va);
733 spin_lock_shared(&pmap->pm_spin);
734 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
735 if (pv == NULL || pv->pv_m == NULL) {
736 spin_unlock_shared(&pmap->pm_spin);
739 phys = VM_PAGE_TO_PHYS(pv->pv_m);
740 spin_unlock_shared(&pmap->pm_spin);
741 return (pmap_pd_to_pt(phys, va));
743 pd = pmap_pd(pmap, va);
744 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
746 return (pmap_pd_to_pt(*pd, va));
751 * Return pointer to PTE slot in the PT given a pointer to the PT
755 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
759 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
760 return (&pte[pmap_pte_index(va)]);
764 * Return pointer to PTE slot in the PT
768 pmap_pte(pmap_t pmap, vm_offset_t va)
772 pt = pmap_pt(pmap, va);
773 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
775 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
776 return ((pt_entry_t *)pt);
777 return (pmap_pt_to_pte(*pt, va));
781 * Return address of PT slot in PD (KVM only)
783 * Cannot be used for user page tables because it might interfere with
784 * the shared page-table-page optimization (pmap_mmu_optimize).
788 vtopt(vm_offset_t va)
790 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
791 NPML4EPGSHIFT)) - 1);
793 return (PDmap + ((va >> PDRSHIFT) & mask));
797 * KVM - return address of PTE slot in PT
801 vtopte(vm_offset_t va)
803 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
804 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
806 return (PTmap + ((va >> PAGE_SHIFT) & mask));
810 * Returns the physical address translation from va for a user address.
811 * (vm_paddr_t)-1 is returned on failure.
814 uservtophys(vm_offset_t va)
816 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
817 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
822 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
824 if (va < VM_MAX_USER_ADDRESS) {
825 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
826 if (pte & pmap->pmap_bits[PG_V_IDX])
827 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
833 allocpages(vm_paddr_t *firstaddr, long n)
838 bzero((void *)ret, n * PAGE_SIZE);
839 *firstaddr += n * PAGE_SIZE;
845 create_pagetables(vm_paddr_t *firstaddr)
847 long i; /* must be 64 bits */
854 * We are running (mostly) V=P at this point
856 * Calculate how many 1GB PD entries in our PDP pages are needed
857 * for the DMAP. This is only allocated if the system does not
858 * support 1GB pages. Otherwise ndmpdp is simply a count of
859 * the number of 1G terminal entries in our PDP pages are needed.
861 * NOTE: Maxmem is in pages
863 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
864 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
866 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
869 * Starting at KERNBASE - map all 2G worth of page table pages.
870 * KERNBASE is offset -2G from the end of kvm. This will accomodate
871 * all KVM allocations above KERNBASE, including the SYSMAPs below.
873 * We do this by allocating 2*512 PT pages. Each PT page can map
874 * 2MB, for 2GB total.
876 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
879 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
880 * Calculate how many page table pages we need to preallocate
881 * for early vm_map allocations.
883 * A few extra won't hurt, they will get used up in the running
889 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
890 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
891 nkpt_phys += 128; /* a few extra */
894 * The highest value nkpd_phys can be set to is
895 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
897 * Doing so would cause all PD pages to be pre-populated for
898 * a maximal KVM space (approximately 16*512 pages, or 32MB.
899 * We can save memory by not doing this.
901 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
906 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
907 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
909 * Only allocate enough PD pages
910 * NOTE: We allocate all kernel PD pages up-front, typically
911 * ~511G of KVM, requiring 511 PD pages.
913 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
914 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
915 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
916 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
917 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
920 * Alloc PD pages for the area starting at KERNBASE.
922 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
927 DMPDPphys = allocpages(firstaddr, NDMPML4E);
928 if ((amd_feature & AMDID_PAGE1GB) == 0)
929 DMPDphys = allocpages(firstaddr, ndmpdp);
930 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
933 * Fill in the underlying page table pages for the area around
934 * KERNBASE. This remaps low physical memory to KERNBASE.
936 * Read-only from zero to physfree
937 * XXX not fully used, underneath 2M pages
939 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
940 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
941 ((pt_entry_t *)KPTbase)[i] |=
942 pmap_bits_default[PG_RW_IDX] |
943 pmap_bits_default[PG_V_IDX] |
944 pmap_bits_default[PG_G_IDX];
948 * Now map the initial kernel page tables. One block of page
949 * tables is placed at the beginning of kernel virtual memory,
950 * and another block is placed at KERNBASE to map the kernel binary,
951 * data, bss, and initial pre-allocations.
953 for (i = 0; i < nkpt_base; i++) {
954 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
955 ((pd_entry_t *)KPDbase)[i] |=
956 pmap_bits_default[PG_RW_IDX] |
957 pmap_bits_default[PG_V_IDX];
959 for (i = 0; i < nkpt_phys; i++) {
960 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
961 ((pd_entry_t *)KPDphys)[i] |=
962 pmap_bits_default[PG_RW_IDX] |
963 pmap_bits_default[PG_V_IDX];
967 * Map from zero to end of allocations using 2M pages as an
968 * optimization. This will bypass some of the KPTBase pages
969 * above in the KERNBASE area.
971 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
972 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
973 ((pd_entry_t *)KPDbase)[i] |=
974 pmap_bits_default[PG_RW_IDX] |
975 pmap_bits_default[PG_V_IDX] |
976 pmap_bits_default[PG_PS_IDX] |
977 pmap_bits_default[PG_G_IDX];
981 * Load PD addresses into the PDP pages for primary KVA space to
982 * cover existing page tables. PD's for KERNBASE are handled in
985 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
987 for (i = 0; i < nkpd_phys; i++) {
988 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
989 KPDphys + (i << PAGE_SHIFT);
990 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
991 pmap_bits_default[PG_RW_IDX] |
992 pmap_bits_default[PG_V_IDX] |
993 pmap_bits_default[PG_A_IDX];
997 * Load PDs for KERNBASE to the end
999 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
1000 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
1001 ((pdp_entry_t *)KPDPphys)[i + j] =
1002 KPDbase + (j << PAGE_SHIFT);
1003 ((pdp_entry_t *)KPDPphys)[i + j] |=
1004 pmap_bits_default[PG_RW_IDX] |
1005 pmap_bits_default[PG_V_IDX] |
1006 pmap_bits_default[PG_A_IDX];
1010 * Now set up the direct map space using either 2MB or 1GB pages
1011 * Preset PG_M and PG_A because demotion expects it.
1013 * When filling in entries in the PD pages make sure any excess
1014 * entries are set to zero as we allocated enough PD pages
1016 if ((amd_feature & AMDID_PAGE1GB) == 0) {
1020 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1021 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1022 ((pd_entry_t *)DMPDphys)[i] |=
1023 pmap_bits_default[PG_RW_IDX] |
1024 pmap_bits_default[PG_V_IDX] |
1025 pmap_bits_default[PG_PS_IDX] |
1026 pmap_bits_default[PG_G_IDX] |
1027 pmap_bits_default[PG_M_IDX] |
1028 pmap_bits_default[PG_A_IDX];
1032 * And the direct map space's PDP
1034 for (i = 0; i < ndmpdp; i++) {
1035 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1037 ((pdp_entry_t *)DMPDPphys)[i] |=
1038 pmap_bits_default[PG_RW_IDX] |
1039 pmap_bits_default[PG_V_IDX];
1045 for (i = 0; i < ndmpdp; i++) {
1046 ((pdp_entry_t *)DMPDPphys)[i] =
1047 (vm_paddr_t)i << PDPSHIFT;
1048 ((pdp_entry_t *)DMPDPphys)[i] |=
1049 pmap_bits_default[PG_RW_IDX] |
1050 pmap_bits_default[PG_V_IDX] |
1051 pmap_bits_default[PG_PS_IDX] |
1052 pmap_bits_default[PG_G_IDX] |
1053 pmap_bits_default[PG_M_IDX] |
1054 pmap_bits_default[PG_A_IDX];
1058 /* And recursively map PML4 to itself in order to get PTmap */
1059 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1060 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1061 pmap_bits_default[PG_RW_IDX] |
1062 pmap_bits_default[PG_V_IDX] |
1063 pmap_bits_default[PG_A_IDX];
1066 * Connect the Direct Map slots up to the PML4
1068 for (j = 0; j < NDMPML4E; ++j) {
1069 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1070 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1071 pmap_bits_default[PG_RW_IDX] |
1072 pmap_bits_default[PG_V_IDX] |
1073 pmap_bits_default[PG_A_IDX];
1077 * Connect the KVA slot up to the PML4
1079 for (j = 0; j < NKPML4E; ++j) {
1080 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1081 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1082 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1083 pmap_bits_default[PG_RW_IDX] |
1084 pmap_bits_default[PG_V_IDX] |
1085 pmap_bits_default[PG_A_IDX];
1092 * Bootstrap the system enough to run with virtual memory.
1094 * On x86_64 this is called after mapping has already been enabled
1095 * and just syncs the pmap module with what has already been done.
1096 * [We can't call it easily with mapping off since the kernel is not
1097 * mapped with PA == VA, hence we would have to relocate every address
1098 * from the linked base (virtual) address "KERNBASE" to the actual
1099 * (physical) address starting relative to 0]
1102 pmap_bootstrap(vm_paddr_t *firstaddr)
1108 KvaStart = VM_MIN_KERNEL_ADDRESS;
1109 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1110 KvaSize = KvaEnd - KvaStart;
1112 avail_start = *firstaddr;
1115 * Create an initial set of page tables to run the kernel in.
1117 create_pagetables(firstaddr);
1119 virtual2_start = KvaStart;
1120 virtual2_end = PTOV_OFFSET;
1122 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1123 virtual_start = pmap_kmem_choose(virtual_start);
1125 virtual_end = VM_MAX_KERNEL_ADDRESS;
1127 /* XXX do %cr0 as well */
1128 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1129 load_cr3(KPML4phys);
1132 * Initialize protection array.
1134 x86_64_protection_init();
1137 * The kernel's pmap is statically allocated so we don't have to use
1138 * pmap_create, which is unlikely to work correctly at this part of
1139 * the boot sequence (XXX and which no longer exists).
1141 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1142 kernel_pmap.pm_count = 1;
1143 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1144 RB_INIT(&kernel_pmap.pm_pvroot);
1145 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1146 for (i = 0; i < PM_PLACEMARKS; ++i)
1147 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1150 * Reserve some special page table entries/VA space for temporary
1153 #define SYSMAP(c, p, v, n) \
1154 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1160 * CMAP1/CMAP2 are used for zeroing and copying pages.
1162 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1167 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1170 * ptvmmap is used for reading arbitrary physical pages via
1173 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1176 * msgbufp is used to map the system message buffer.
1177 * XXX msgbufmap is not used.
1179 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1180 atop(round_page(MSGBUF_SIZE)))
1183 virtual_start = pmap_kmem_choose(virtual_start);
1188 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1189 * cases rather then invl1pg. Actually, I don't even know why it
1190 * works under UP because self-referential page table mappings
1196 /* Initialize the PAT MSR */
1198 pmap_pinit_defaults(&kernel_pmap);
1200 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1201 &pmap_fast_kernel_cpusync);
1206 * Setup the PAT MSR.
1215 * Default values mapping PATi,PCD,PWT bits at system reset.
1216 * The default values effectively ignore the PATi bit by
1217 * repeating the encodings for 0-3 in 4-7, and map the PCD
1218 * and PWT bit combinations to the expected PAT types.
1220 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1221 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1222 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1223 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1224 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1225 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1226 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1227 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1228 pat_pte_index[PAT_WRITE_BACK] = 0;
1229 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1230 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1231 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1232 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1233 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1235 if (cpu_feature & CPUID_PAT) {
1237 * If we support the PAT then set-up entries for
1238 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1241 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1242 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1243 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1244 PAT_VALUE(6, PAT_WRITE_COMBINING);
1245 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1246 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1249 * Then enable the PAT
1254 load_cr4(cr4 & ~CR4_PGE);
1256 /* Disable caches (CD = 1, NW = 0). */
1258 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1260 /* Flushes caches and TLBs. */
1264 /* Update PAT and index table. */
1265 wrmsr(MSR_PAT, pat_msr);
1267 /* Flush caches and TLBs again. */
1271 /* Restore caches and PGE. */
1279 * Set 4mb pdir for mp startup
1284 if (cpu_feature & CPUID_PSE) {
1285 load_cr4(rcr4() | CR4_PSE);
1286 if (mycpu->gd_cpuid == 0) /* only on BSP */
1291 * Check for SMAP support and enable if available. Must be done
1292 * after cr3 is loaded, and on all cores.
1294 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1295 load_cr4(rcr4() | CR4_SMAP);
1297 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1298 load_cr4(rcr4() | CR4_SMEP);
1303 * Early initialization of the pmap module.
1305 * Called by vm_init, to initialize any structures that the pmap
1306 * system needs to map virtual memory. pmap_init has been enhanced to
1307 * support in a fairly consistant way, discontiguous physical memory.
1312 vm_pindex_t initial_pvs;
1316 * Allocate memory for random pmap data structures. Includes the
1319 for (i = 0; i < vm_page_array_size; i++) {
1322 m = &vm_page_array[i];
1323 m->md.pmap_count = 0;
1324 m->md.writeable_count = 0;
1328 * init the pv free list
1330 initial_pvs = vm_page_array_size;
1331 if (initial_pvs < MINPV)
1332 initial_pvs = MINPV;
1333 pvzone = &pvzone_store;
1334 pvinit = (void *)kmem_alloc(&kernel_map,
1335 initial_pvs * sizeof (struct pv_entry),
1337 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1338 pvinit, initial_pvs);
1341 * Now it is safe to enable pv_table recording.
1343 pmap_initialized = TRUE;
1347 * Initialize the address space (zone) for the pv_entries. Set a
1348 * high water mark so that the system can recover from excessive
1349 * numbers of pv entries.
1351 * Also create the kernel page table template for isolated user
1354 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1355 static void pmap_init2_iso_pmap(void);
1357 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1363 vm_pindex_t entry_max;
1366 * We can significantly reduce pv_entry_max from historical
1367 * levels because pv_entry's are no longer use for PTEs at the
1368 * leafs. This prevents excessive pcpu caching on many-core
1369 * boxes (even with the further '/ 16' done in zinitna().
1371 * Remember, however, that processes can share physical pages
1372 * with each process still needing the pdp/pd/pt infrstructure
1373 * (which still use pv_entry's). And don't just assume that
1374 * every PT will be completely filled up. So don't make it
1377 entry_max = maxproc * 32 + vm_page_array_size / 16;
1378 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &entry_max);
1379 vm_pmap_pv_entries = entry_max;
1382 * Subtract out pages already installed in the zone (hack)
1384 if (entry_max <= MINPV)
1387 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1390 * Enable dynamic deletion of empty higher-level page table pages
1391 * by default only if system memory is < 8GB (use 7GB for slop).
1392 * This can save a little memory, but imposes significant
1393 * performance overhead for things like bulk builds, and for programs
1394 * which do a lot of memory mapping and memory unmapping.
1397 if (pmap_dynamic_delete < 0) {
1398 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1399 pmap_dynamic_delete = 1;
1401 pmap_dynamic_delete = 0;
1405 * Disable so vm_map_backing iterations do not race
1407 pmap_dynamic_delete = 0;
1410 * Automatic detection of Intel meltdown bug requiring user/kernel
1413 * Currently there are so many Intel cpu's impacted that its better
1414 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1415 * so the default is off for AMD.
1417 if (meltdown_mitigation < 0) {
1418 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1419 meltdown_mitigation = 1;
1421 meltdown_mitigation = 0;
1423 if (meltdown_mitigation) {
1424 kprintf("machdep.meltdown_mitigation enabled to "
1425 "protect against (mostly Intel) meltdown bug\n");
1426 kprintf("system call performance will be impacted\n");
1429 pmap_init2_iso_pmap();
1433 * Create the isolation pmap template. Once created, the template
1434 * is static and its PML4e entries are used to populate the
1435 * kernel portion of any isolated user pmaps.
1437 * Our isolation pmap must contain:
1438 * (1) trampoline area for all cpus
1439 * (2) common_tss area for all cpus (its part of the trampoline area now)
1440 * (3) IDT for all cpus
1441 * (4) GDT for all cpus
1444 pmap_init2_iso_pmap(void)
1449 kprintf("Initialize isolation pmap\n");
1452 * Try to use our normal API calls to make this easier. We have
1453 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1456 pmap_pinit(&iso_pmap);
1457 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1460 * Install areas needed by the cpu and trampoline.
1462 for (n = 0; n < ncpus; ++n) {
1463 struct privatespace *ps;
1465 ps = CPU_prvspace[n];
1466 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1467 sizeof(ps->trampoline));
1468 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1469 sizeof(ps->dblstack));
1470 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1471 sizeof(ps->dbgstack));
1472 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1473 sizeof(ps->common_tss));
1474 pmap_init_iso_range(r_idt_arr[n].rd_base,
1475 r_idt_arr[n].rd_limit + 1);
1477 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1478 pmap_init_iso_range((vm_offset_t)(int *)btext,
1479 (vm_offset_t)(int *)etext -
1480 (vm_offset_t)(int *)btext);
1483 kprintf("Dump iso_pmap:\n");
1484 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1485 kprintf("\nDump kernel_pmap:\n");
1486 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1491 * This adds a kernel virtual address range to the isolation pmap.
1494 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1503 kprintf("isolate %016jx-%016jx (%zd)\n",
1504 base, base + bytes, bytes);
1506 va = base & ~(vm_offset_t)PAGE_MASK;
1507 while (va < base + bytes) {
1508 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1509 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1510 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1511 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1513 * Use 2MB pages if possible
1516 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1517 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1522 * Otherwise use 4KB pages
1524 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1525 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1526 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1527 kernel_pmap.pmap_bits[PG_V_IDX] |
1528 kernel_pmap.pmap_bits[PG_A_IDX] |
1529 kernel_pmap.pmap_bits[PG_M_IDX];
1540 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1544 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1551 case 0: /* PML4e page, 512G entries */
1552 incr = (1LL << 48) / 512;
1554 case 1: /* PDP page, 1G entries */
1555 incr = (1LL << 39) / 512;
1557 case 2: /* PD page, 2MB entries */
1558 incr = (1LL << 30) / 512;
1560 case 3: /* PT page, 4KB entries */
1561 incr = (1LL << 21) / 512;
1569 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1570 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1571 for (i = 0; i < 512; ++i) {
1572 if (level == 0 && i == 128)
1573 base += 0xFFFF000000000000LLU;
1575 kprintf("%*.*s ", level * 4, level * 4, "");
1576 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1577 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1579 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1580 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1582 } else if (level == 3) {
1583 kprintf("va=%016jx %3d term %016jx\n",
1586 kprintf("va=%016jx %3d deep %016jx\n",
1588 dump_pmap(pmap, ptp[i], level + 1, base);
1598 * Typically used to initialize a fictitious page by vm/device_pager.c
1601 pmap_page_init(struct vm_page *m)
1604 m->md.pmap_count = 0;
1605 m->md.writeable_count = 0;
1608 /***************************************************
1609 * Low level helper routines.....
1610 ***************************************************/
1613 * Extract the physical page address associated with the map/VA pair.
1614 * The page must be wired for this to work reliably.
1617 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1624 if (va >= VM_MAX_USER_ADDRESS) {
1626 * Kernel page directories might be direct-mapped and
1627 * there is typically no PV tracking of pte's
1631 pt = pmap_pt(pmap, va);
1632 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1633 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1634 rtval = *pt & PG_PS_FRAME;
1635 rtval |= va & PDRMASK;
1637 ptep = pmap_pt_to_pte(*pt, va);
1638 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1639 rtval = *ptep & PG_FRAME;
1640 rtval |= va & PAGE_MASK;
1648 * User pages currently do not direct-map the page directory
1649 * and some pages might not used managed PVs. But all PT's
1652 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1654 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1655 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1656 rtval = *ptep & PG_FRAME;
1657 rtval |= va & PAGE_MASK;
1660 *handlep = pt_pv; /* locked until done */
1663 } else if (handlep) {
1671 pmap_extract_done(void *handle)
1674 pv_put((pv_entry_t)handle);
1678 * Similar to extract but checks protections, SMP-friendly short-cut for
1679 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1680 * fall-through to the real fault code. Does not work with HVM page
1683 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1685 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1686 * page is busied (and not held).
1688 * If busyp is not NULL and this function sets *busyp to zero, the returned
1689 * page is held (and not busied).
1691 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1692 * returned page will be dirtied. If the pte is not already writable NULL
1693 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1694 * any COW will already have happened and that page can be written by the
1697 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1701 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1704 va < VM_MAX_USER_ADDRESS &&
1705 (pmap->pm_flags & PMAP_HVM) == 0) {
1713 req = pmap->pmap_bits[PG_V_IDX] |
1714 pmap->pmap_bits[PG_U_IDX];
1715 if (prot & VM_PROT_WRITE)
1716 req |= pmap->pmap_bits[PG_RW_IDX];
1718 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1721 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1722 if ((*ptep & req) != req) {
1726 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1727 if (pte_pv && error == 0) {
1729 if (prot & VM_PROT_WRITE) {
1730 /* interlocked by presence of pv_entry */
1734 if (prot & VM_PROT_WRITE) {
1735 if (vm_page_busy_try(m, TRUE))
1746 } else if (pte_pv) {
1750 /* error, since we didn't request a placemarker */
1761 * Extract the physical page address associated kernel virtual address.
1764 pmap_kextract(vm_offset_t va)
1766 pd_entry_t pt; /* pt entry in pd */
1769 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1770 pa = DMAP_TO_PHYS(va);
1773 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1774 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1777 * Beware of a concurrent promotion that changes the
1778 * PDE at this point! For example, vtopte() must not
1779 * be used to access the PTE because it would use the
1780 * new PDE. It is, however, safe to use the old PDE
1781 * because the page table page is preserved by the
1784 pa = *pmap_pt_to_pte(pt, va);
1785 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1791 /***************************************************
1792 * Low level mapping routines.....
1793 ***************************************************/
1796 * Routine: pmap_kenter
1798 * Add a wired page to the KVA
1799 * NOTE! note that in order for the mapping to take effect -- you
1800 * should do an invltlb after doing the pmap_kenter().
1803 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1809 kernel_pmap.pmap_bits[PG_RW_IDX] |
1810 kernel_pmap.pmap_bits[PG_V_IDX];
1814 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1818 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1825 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1826 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1827 * (caller can conditionalize calling smp_invltlb()).
1830 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1836 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1837 kernel_pmap.pmap_bits[PG_V_IDX];
1846 atomic_swap_long(ptep, npte);
1847 cpu_invlpg((void *)va);
1853 * Enter addresses into the kernel pmap but don't bother
1854 * doing any tlb invalidations. Caller will do a rollup
1855 * invalidation via pmap_rollup_inval().
1858 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1865 kernel_pmap.pmap_bits[PG_RW_IDX] |
1866 kernel_pmap.pmap_bits[PG_V_IDX];
1875 atomic_swap_long(ptep, npte);
1876 cpu_invlpg((void *)va);
1882 * remove a page from the kernel pagetables
1885 pmap_kremove(vm_offset_t va)
1890 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1894 pmap_kremove_quick(vm_offset_t va)
1899 (void)pte_load_clear(ptep);
1900 cpu_invlpg((void *)va);
1904 * Remove addresses from the kernel pmap but don't bother
1905 * doing any tlb invalidations. Caller will do a rollup
1906 * invalidation via pmap_rollup_inval().
1909 pmap_kremove_noinval(vm_offset_t va)
1914 (void)pte_load_clear(ptep);
1918 * XXX these need to be recoded. They are not used in any critical path.
1921 pmap_kmodify_rw(vm_offset_t va)
1923 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1924 cpu_invlpg((void *)va);
1929 pmap_kmodify_nc(vm_offset_t va)
1931 atomic_set_long(vtopte(va), PG_N);
1932 cpu_invlpg((void *)va);
1937 * Used to map a range of physical addresses into kernel virtual
1938 * address space during the low level boot, typically to map the
1939 * dump bitmap, message buffer, and vm_page_array.
1941 * These mappings are typically made at some pointer after the end of the
1944 * We could return PHYS_TO_DMAP(start) here and not allocate any
1945 * via (*virtp), but then kmem from userland and kernel dumps won't
1946 * have access to the related pointers.
1949 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1952 vm_offset_t va_start;
1954 /*return PHYS_TO_DMAP(start);*/
1959 while (start < end) {
1960 pmap_kenter_quick(va, start);
1968 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1971 * Remove the specified set of pages from the data and instruction caches.
1973 * In contrast to pmap_invalidate_cache_range(), this function does not
1974 * rely on the CPU's self-snoop feature, because it is intended for use
1975 * when moving pages into a different cache domain.
1978 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1980 vm_offset_t daddr, eva;
1983 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1984 (cpu_feature & CPUID_CLFSH) == 0)
1988 for (i = 0; i < count; i++) {
1989 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1990 eva = daddr + PAGE_SIZE;
1991 for (; daddr < eva; daddr += cpu_clflush_line_size)
1999 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
2001 KASSERT((sva & PAGE_MASK) == 0,
2002 ("pmap_invalidate_cache_range: sva not page-aligned"));
2003 KASSERT((eva & PAGE_MASK) == 0,
2004 ("pmap_invalidate_cache_range: eva not page-aligned"));
2006 if (cpu_feature & CPUID_SS) {
2007 ; /* If "Self Snoop" is supported, do nothing. */
2009 /* Globally invalidate caches */
2010 cpu_wbinvd_on_all_cpus();
2015 * Invalidate the specified range of virtual memory on all cpus associated
2019 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2021 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2025 * Add a list of wired pages to the kva. This routine is used for temporary
2026 * kernel mappings such as those found in buffer cache buffer. Page
2027 * modifications and accesses are not tracked or recorded.
2029 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2030 * semantics as previous mappings may have been zerod without any
2033 * The page *must* be wired.
2035 static __inline void
2036 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2041 end_va = beg_va + count * PAGE_SIZE;
2043 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2048 pte = VM_PAGE_TO_PHYS(*m) |
2049 kernel_pmap.pmap_bits[PG_RW_IDX] |
2050 kernel_pmap.pmap_bits[PG_V_IDX] |
2051 kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2053 atomic_swap_long(ptep, pte);
2057 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2061 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2063 _pmap_qenter(beg_va, m, count, 1);
2067 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2069 _pmap_qenter(beg_va, m, count, 0);
2073 * This routine jerks page mappings from the kernel -- it is meant only
2074 * for temporary mappings such as those found in buffer cache buffers.
2075 * No recording modified or access status occurs.
2077 * MPSAFE, INTERRUPT SAFE (cluster callback)
2080 pmap_qremove(vm_offset_t beg_va, int count)
2085 end_va = beg_va + count * PAGE_SIZE;
2087 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2091 (void)pte_load_clear(pte);
2092 cpu_invlpg((void *)va);
2094 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2098 * This routine removes temporary kernel mappings, only invalidating them
2099 * on the current cpu. It should only be used under carefully controlled
2103 pmap_qremove_quick(vm_offset_t beg_va, int count)
2108 end_va = beg_va + count * PAGE_SIZE;
2110 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2114 (void)pte_load_clear(pte);
2115 cpu_invlpg((void *)va);
2120 * This routine removes temporary kernel mappings *without* invalidating
2121 * the TLB. It can only be used on permanent kva reservations such as those
2122 * found in buffer cache buffers, under carefully controlled circumstances.
2124 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2125 * (pmap_qenter() does unconditional invalidation).
2128 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2133 end_va = beg_va + count * PAGE_SIZE;
2135 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2139 (void)pte_load_clear(pte);
2144 * Create a new thread and optionally associate it with a (new) process.
2145 * NOTE! the new thread's cpu may not equal the current cpu.
2148 pmap_init_thread(thread_t td)
2150 /* enforce pcb placement & alignment */
2151 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2152 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2153 td->td_savefpu = &td->td_pcb->pcb_save;
2154 td->td_sp = (char *)td->td_pcb; /* no -16 */
2158 * This routine directly affects the fork perf for a process.
2161 pmap_init_proc(struct proc *p)
2166 pmap_pinit_defaults(struct pmap *pmap)
2168 bcopy(pmap_bits_default, pmap->pmap_bits,
2169 sizeof(pmap_bits_default));
2170 bcopy(protection_codes, pmap->protection_codes,
2171 sizeof(protection_codes));
2172 bcopy(pat_pte_index, pmap->pmap_cache_bits,
2173 sizeof(pat_pte_index));
2174 pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2175 pmap->copyinstr = std_copyinstr;
2176 pmap->copyin = std_copyin;
2177 pmap->copyout = std_copyout;
2178 pmap->fubyte = std_fubyte;
2179 pmap->subyte = std_subyte;
2180 pmap->fuword32 = std_fuword32;
2181 pmap->fuword64 = std_fuword64;
2182 pmap->suword32 = std_suword32;
2183 pmap->suword64 = std_suword64;
2184 pmap->swapu32 = std_swapu32;
2185 pmap->swapu64 = std_swapu64;
2186 pmap->fuwordadd32 = std_fuwordadd32;
2187 pmap->fuwordadd64 = std_fuwordadd64;
2190 * Initialize pmap0/vmspace0.
2192 * On architectures where the kernel pmap is not integrated into the user
2193 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2194 * kernel_pmap should be used to directly access the kernel_pmap.
2197 pmap_pinit0(struct pmap *pmap)
2201 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2203 CPUMASK_ASSZERO(pmap->pm_active);
2204 pmap->pm_pvhint_pt = NULL;
2205 pmap->pm_pvhint_unused = NULL;
2206 RB_INIT(&pmap->pm_pvroot);
2207 spin_init(&pmap->pm_spin, "pmapinit0");
2208 for (i = 0; i < PM_PLACEMARKS; ++i)
2209 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2210 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2211 pmap_pinit_defaults(pmap);
2215 * Initialize a preallocated and zeroed pmap structure,
2216 * such as one in a vmspace structure.
2219 pmap_pinit_simple(struct pmap *pmap)
2224 * Misc initialization
2227 CPUMASK_ASSZERO(pmap->pm_active);
2228 pmap->pm_pvhint_pt = NULL;
2229 pmap->pm_pvhint_unused = NULL;
2230 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2232 pmap_pinit_defaults(pmap);
2235 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2238 if (pmap->pm_pmlpv == NULL) {
2239 RB_INIT(&pmap->pm_pvroot);
2240 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2241 spin_init(&pmap->pm_spin, "pmapinitsimple");
2242 for (i = 0; i < PM_PLACEMARKS; ++i)
2243 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2248 pmap_pinit(struct pmap *pmap)
2253 if (pmap->pm_pmlpv) {
2254 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2259 pmap_pinit_simple(pmap);
2260 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2263 * No need to allocate page table space yet but we do need a valid
2264 * page directory table.
2266 if (pmap->pm_pml4 == NULL) {
2268 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2271 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2275 * Allocate the PML4e table, which wires it even though it isn't
2276 * being entered into some higher level page table (it being the
2277 * highest level). If one is already cached we don't have to do
2280 if ((pv = pmap->pm_pmlpv) == NULL) {
2281 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2282 pmap->pm_pmlpv = pv;
2283 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2284 VM_PAGE_TO_PHYS(pv->pv_m));
2288 * Install DMAP and KMAP.
2290 for (j = 0; j < NDMPML4E; ++j) {
2291 pmap->pm_pml4[DMPML4I + j] =
2292 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2293 pmap->pmap_bits[PG_RW_IDX] |
2294 pmap->pmap_bits[PG_V_IDX] |
2295 pmap->pmap_bits[PG_A_IDX];
2297 for (j = 0; j < NKPML4E; ++j) {
2298 pmap->pm_pml4[KPML4I + j] =
2299 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2300 pmap->pmap_bits[PG_RW_IDX] |
2301 pmap->pmap_bits[PG_V_IDX] |
2302 pmap->pmap_bits[PG_A_IDX];
2306 * install self-referential address mapping entry
2308 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2309 pmap->pmap_bits[PG_V_IDX] |
2310 pmap->pmap_bits[PG_RW_IDX] |
2311 pmap->pmap_bits[PG_A_IDX];
2313 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2314 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2316 KKASSERT(pmap->pm_pml4[255] == 0);
2319 * When implementing an isolated userland pmap, a second PML4e table
2320 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2321 * note that we do not operate on this table using our API functions
2322 * so handling of the + 1 case is mostly just to prevent implosions.
2324 * We install an isolated version of the kernel PDPs into this
2325 * second PML4e table. The pmap code will mirror all user PDPs
2326 * between the primary and secondary PML4e table.
2328 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2329 pmap != &iso_pmap) {
2330 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2331 pmap->pm_pmlpv_iso = pv;
2332 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2333 VM_PAGE_TO_PHYS(pv->pv_m));
2337 * Install an isolated version of the kernel pmap for
2338 * user consumption, using PDPs constructed in iso_pmap.
2340 for (j = 0; j < NKPML4E; ++j) {
2341 pmap->pm_pml4_iso[KPML4I + j] =
2342 iso_pmap.pm_pml4[KPML4I + j];
2345 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2346 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2351 * Clean up a pmap structure so it can be physically freed. This routine
2352 * is called by the vmspace dtor function. A great deal of pmap data is
2353 * left passively mapped to improve vmspace management so we have a bit
2354 * of cleanup work to do here.
2357 pmap_puninit(pmap_t pmap)
2362 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2363 if ((pv = pmap->pm_pmlpv) != NULL) {
2364 if (pv_hold_try(pv) == 0)
2366 KKASSERT(pv == pmap->pm_pmlpv);
2367 p = pmap_remove_pv_page(pv);
2369 pv = NULL; /* safety */
2370 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2371 vm_page_busy_wait(p, FALSE, "pgpun");
2372 KKASSERT(p->flags & PG_UNQUEUED);
2373 vm_page_unwire(p, 0);
2374 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2376 pmap->pm_pmlpv = NULL;
2378 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2379 if (pv_hold_try(pv) == 0)
2381 KKASSERT(pv == pmap->pm_pmlpv_iso);
2382 p = pmap_remove_pv_page(pv);
2384 pv = NULL; /* safety */
2385 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2386 vm_page_busy_wait(p, FALSE, "pgpun");
2387 KKASSERT(p->flags & PG_UNQUEUED);
2388 vm_page_unwire(p, 0);
2389 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2391 pmap->pm_pmlpv_iso = NULL;
2393 if (pmap->pm_pml4) {
2394 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2395 kmem_free(&kernel_map,
2396 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2397 pmap->pm_pml4 = NULL;
2398 pmap->pm_pml4_iso = NULL;
2400 KKASSERT(pmap->pm_stats.resident_count == 0);
2401 KKASSERT(pmap->pm_stats.wired_count == 0);
2405 * This function is now unused (used to add the pmap to the pmap_list)
2408 pmap_pinit2(struct pmap *pmap)
2413 * This routine is called when various levels in the page table need to
2414 * be populated. This routine cannot fail.
2416 * This function returns two locked pv_entry's, one representing the
2417 * requested pv and one representing the requested pv's parent pv. If
2418 * an intermediate page table does not exist it will be created, mapped,
2419 * wired, and the parent page table will be given an additional hold
2420 * count representing the presence of the child pv_entry.
2424 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2427 pt_entry_t *ptep_iso;
2436 * If the pv already exists and we aren't being asked for the
2437 * parent page table page we can just return it. A locked+held pv
2438 * is returned. The pv will also have a second hold related to the
2439 * pmap association that we don't have to worry about.
2442 pv = pv_alloc(pmap, ptepindex, &isnew);
2443 if (isnew == 0 && pvpp == NULL)
2447 * DragonFly doesn't use PV's to represent terminal PTEs any more.
2448 * The index range is still used for placemarkers, but not for
2449 * actual pv_entry's.
2451 KKASSERT(ptepindex >= pmap_pt_pindex(0));
2454 * Note that pt_pv's are only returned for user VAs. We assert that
2455 * a pt_pv is not being requested for kernel VAs. The kernel
2456 * pre-wires all higher-level page tables so don't overload managed
2457 * higher-level page tables on top of it!
2459 * However, its convenient for us to allow the case when creating
2460 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2465 * The kernel never uses managed PT/PD/PDP pages.
2467 KKASSERT(pmap != &kernel_pmap);
2470 * Non-terminal PVs allocate a VM page to represent the page table,
2471 * so we have to resolve pvp and calculate ptepindex for the pvp
2472 * and then for the page table entry index in the pvp for
2475 if (ptepindex < pmap_pd_pindex(0)) {
2477 * pv is PT, pvp is PD
2479 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2480 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2481 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2486 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2487 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2489 } else if (ptepindex < pmap_pdp_pindex(0)) {
2491 * pv is PD, pvp is PDP
2493 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2496 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2497 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2499 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2500 KKASSERT(pvpp == NULL);
2503 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2509 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2510 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2511 } else if (ptepindex < pmap_pml4_pindex()) {
2513 * pv is PDP, pvp is the root pml4 table
2515 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2520 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2521 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2524 * pv represents the top-level PML4, there is no parent.
2533 * (isnew) is TRUE, pv is not terminal.
2535 * (1) Add a wire count to the parent page table (pvp).
2536 * (2) Allocate a VM page for the page table.
2537 * (3) Enter the VM page into the parent page table.
2539 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2542 vm_page_wire_quick(pvp->pv_m);
2545 m = vm_page_alloc(NULL, pv->pv_pindex,
2546 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2547 VM_ALLOC_INTERRUPT);
2552 vm_page_wire(m); /* wire for mapping in parent */
2553 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2554 m->valid = VM_PAGE_BITS_ALL;
2555 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_UNQUEUED);
2556 KKASSERT(m->queue == PQ_NONE);
2561 * (isnew) is TRUE, pv is not terminal.
2563 * Wire the page into pvp. Bump the resident_count for the pmap.
2564 * There is no pvp for the top level, address the pm_pml4[] array
2567 * If the caller wants the parent we return it, otherwise
2568 * we just put it away.
2570 * No interlock is needed for pte 0 -> non-zero.
2572 * In the situation where *ptep is valid we might have an unmanaged
2573 * page table page shared from another page table which we need to
2574 * unshare before installing our private page table page.
2577 v = VM_PAGE_TO_PHYS(m) |
2578 (pmap->pmap_bits[PG_RW_IDX] |
2579 pmap->pmap_bits[PG_V_IDX] |
2580 pmap->pmap_bits[PG_A_IDX]);
2581 if (ptepindex < NUPTE_USER)
2582 v |= pmap->pmap_bits[PG_U_IDX];
2583 if (ptepindex < pmap_pt_pindex(0))
2584 v |= pmap->pmap_bits[PG_M_IDX];
2586 ptep = pv_pte_lookup(pvp, ptepindex);
2587 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2588 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2591 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2592 panic("pmap_allocpte: ptpte present without pv_entry!");
2596 pte = atomic_swap_long(ptep, v);
2598 atomic_swap_long(ptep_iso, v);
2600 kprintf("install pgtbl mixup 0x%016jx "
2601 "old/new 0x%016jx/0x%016jx\n",
2602 (intmax_t)ptepindex, pte, v);
2609 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2613 KKASSERT(pvp->pv_m != NULL);
2614 ptep = pv_pte_lookup(pvp, ptepindex);
2615 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2616 (pmap->pmap_bits[PG_RW_IDX] |
2617 pmap->pmap_bits[PG_V_IDX] |
2618 pmap->pmap_bits[PG_A_IDX]);
2619 if (ptepindex < NUPTE_USER)
2620 v |= pmap->pmap_bits[PG_U_IDX];
2621 if (ptepindex < pmap_pt_pindex(0))
2622 v |= pmap->pmap_bits[PG_M_IDX];
2624 kprintf("mismatched upper level pt %016jx/%016jx\n",
2636 * Release any resources held by the given physical map.
2638 * Called when a pmap initialized by pmap_pinit is being released. Should
2639 * only be called if the map contains no valid mappings.
2641 struct pmap_release_info {
2647 static int pmap_release_callback(pv_entry_t pv, void *data);
2650 pmap_release(struct pmap *pmap)
2652 struct pmap_release_info info;
2654 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2655 ("pmap still active! %016jx",
2656 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2659 * There is no longer a pmap_list, if there were we would remove the
2660 * pmap from it here.
2664 * Pull pv's off the RB tree in order from low to high and release
2672 spin_lock(&pmap->pm_spin);
2673 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2674 pmap_release_callback, &info);
2675 spin_unlock(&pmap->pm_spin);
2679 } while (info.retry);
2683 * One resident page (the pml4 page) should remain. Two if
2684 * the pmap has implemented an isolated userland PML4E table.
2685 * No wired pages should remain.
2687 int expected_res = 0;
2689 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2691 if (pmap->pm_pmlpv_iso)
2695 if (pmap->pm_stats.resident_count != expected_res ||
2696 pmap->pm_stats.wired_count != 0) {
2697 kprintf("fatal pmap problem - pmap %p flags %08x "
2698 "rescnt=%jd wirecnt=%jd\n",
2701 pmap->pm_stats.resident_count,
2702 pmap->pm_stats.wired_count);
2703 tsleep(pmap, 0, "DEAD", 0);
2706 KKASSERT(pmap->pm_stats.resident_count == expected_res);
2707 KKASSERT(pmap->pm_stats.wired_count == 0);
2712 * Called from low to high. We must cache the proper parent pv so we
2713 * can adjust its wired count.
2716 pmap_release_callback(pv_entry_t pv, void *data)
2718 struct pmap_release_info *info = data;
2719 pmap_t pmap = info->pmap;
2724 * Acquire a held and locked pv, check for release race
2726 pindex = pv->pv_pindex;
2727 if (info->pvp == pv) {
2728 spin_unlock(&pmap->pm_spin);
2730 } else if (pv_hold_try(pv)) {
2731 spin_unlock(&pmap->pm_spin);
2733 spin_unlock(&pmap->pm_spin);
2737 spin_lock(&pmap->pm_spin);
2741 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
2743 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2745 * I am PTE, parent is PT
2747 pindex = pv->pv_pindex >> NPTEPGSHIFT;
2748 pindex += NUPTE_TOTAL;
2749 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
2751 * I am PT, parent is PD
2753 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
2754 pindex += NUPTE_TOTAL + NUPT_TOTAL;
2755 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
2757 * I am PD, parent is PDP
2759 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
2761 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2762 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
2764 * I am PDP, parent is PML4. We always calculate the
2765 * normal PML4 here, not the isolated PML4.
2767 pindex = pmap_pml4_pindex();
2779 if (info->pvp && info->pvp->pv_pindex != pindex) {
2783 if (info->pvp == NULL)
2784 info->pvp = pv_get(pmap, pindex, NULL);
2791 r = pmap_release_pv(pv, info->pvp, NULL);
2792 spin_lock(&pmap->pm_spin);
2798 * Called with held (i.e. also locked) pv. This function will dispose of
2799 * the lock along with the pv.
2801 * If the caller already holds the locked parent page table for pv it
2802 * must pass it as pvp, allowing us to avoid a deadlock, else it can
2803 * pass NULL for pvp.
2806 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
2811 * The pmap is currently not spinlocked, pv is held+locked.
2812 * Remove the pv's page from its parent's page table. The
2813 * parent's page table page's wire_count will be decremented.
2815 * This will clean out the pte at any level of the page table.
2816 * If smp != 0 all cpus are affected.
2818 * Do not tear-down recursively, its faster to just let the
2819 * release run its course.
2821 pmap_remove_pv_pte(pv, pvp, bulk, 0);
2824 * Terminal pvs are unhooked from their vm_pages. Because
2825 * terminal pages aren't page table pages they aren't wired
2826 * by us, so we have to be sure not to unwire them either.
2828 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2829 pmap_remove_pv_page(pv);
2834 * We leave the top-level page table page cached, wired, and
2835 * mapped in the pmap until the dtor function (pmap_puninit())
2838 * Since we are leaving the top-level pv intact we need
2839 * to break out of what would otherwise be an infinite loop.
2841 * This covers both the normal and the isolated PML4 page.
2843 if (pv->pv_pindex >= pmap_pml4_pindex()) {
2849 * For page table pages (other than the top-level page),
2850 * remove and free the vm_page. The representitive mapping
2851 * removed above by pmap_remove_pv_pte() did not undo the
2852 * last wire_count so we have to do that as well.
2854 p = pmap_remove_pv_page(pv);
2855 vm_page_busy_wait(p, FALSE, "pmaprl");
2856 if (p->wire_count != 1) {
2859 if (pv->pv_pindex >= pmap_pdp_pindex(0))
2861 else if (pv->pv_pindex >= pmap_pd_pindex(0))
2863 else if (pv->pv_pindex >= pmap_pt_pindex(0))
2868 kprintf("p(%s) p->wire_count was %016lx %d\n",
2869 tstr, pv->pv_pindex, p->wire_count);
2871 KKASSERT(p->wire_count == 1);
2872 KKASSERT(p->flags & PG_UNQUEUED);
2874 vm_page_unwire(p, 0);
2875 KKASSERT(p->wire_count == 0);
2885 * This function will remove the pte associated with a pv from its parent.
2886 * Terminal pv's are supported. All cpus specified by (bulk) are properly
2889 * The wire count will be dropped on the parent page table. The wire
2890 * count on the page being removed (pv->pv_m) from the parent page table
2891 * is NOT touched. Note that terminal pages will not have any additional
2892 * wire counts while page table pages will have at least one representing
2893 * the mapping, plus others representing sub-mappings.
2895 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
2896 * pages and user page table and terminal pages.
2898 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
2899 * be freshly allocated and not imply that the pte is managed. In this
2900 * case pv->pv_m should be NULL.
2902 * The pv must be locked. The pvp, if supplied, must be locked. All
2903 * supplied pv's will remain locked on return.
2905 * XXX must lock parent pv's if they exist to remove pte XXX
2909 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
2912 vm_pindex_t ptepindex = pv->pv_pindex;
2913 pmap_t pmap = pv->pv_pmap;
2919 if (ptepindex >= pmap_pml4_pindex()) {
2921 * We are the top level PML4E table, there is no parent.
2923 * This is either the normal or isolated PML4E table.
2924 * Only the normal is used in regular operation, the isolated
2925 * is only passed in when breaking down the whole pmap.
2927 p = pmap->pm_pmlpv->pv_m;
2928 KKASSERT(pv->pv_m == p); /* debugging */
2929 } else if (ptepindex >= pmap_pdp_pindex(0)) {
2931 * Remove a PDP page from the PML4E. This can only occur
2932 * with user page tables. We do not have to lock the
2933 * pml4 PV so just ignore pvp.
2935 vm_pindex_t pml4_pindex;
2936 vm_pindex_t pdp_index;
2938 pml4_entry_t *pdp_iso;
2940 pdp_index = ptepindex - pmap_pdp_pindex(0);
2942 pml4_pindex = pmap_pml4_pindex();
2943 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
2948 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
2949 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
2950 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2951 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
2954 * Also remove the PDP from the isolated PML4E if the
2957 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
2958 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
2959 ((1ul << NPML4EPGSHIFT) - 1)];
2960 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
2962 KKASSERT(pv->pv_m == p); /* debugging */
2963 } else if (ptepindex >= pmap_pd_pindex(0)) {
2965 * Remove a PD page from the PDP
2967 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
2968 * of a simple pmap because it stops at
2971 vm_pindex_t pdp_pindex;
2972 vm_pindex_t pd_index;
2975 pd_index = ptepindex - pmap_pd_pindex(0);
2978 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
2979 (pd_index >> NPML4EPGSHIFT);
2980 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
2985 pd = pv_pte_lookup(pvp, pd_index &
2986 ((1ul << NPDPEPGSHIFT) - 1));
2987 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
2988 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2989 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
2991 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
2992 p = pv->pv_m; /* degenerate test later */
2994 KKASSERT(pv->pv_m == p); /* debugging */
2995 } else if (ptepindex >= pmap_pt_pindex(0)) {
2997 * Remove a PT page from the PD
2999 vm_pindex_t pd_pindex;
3000 vm_pindex_t pt_index;
3003 pt_index = ptepindex - pmap_pt_pindex(0);
3006 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3007 (pt_index >> NPDPEPGSHIFT);
3008 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3013 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3015 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3016 ("*pt unexpectedly invalid %016jx "
3017 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3018 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3019 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3021 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3022 kprintf("*pt unexpectedly invalid %016jx "
3023 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3025 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3026 tsleep(pt, 0, "DEAD", 0);
3029 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3032 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3033 KKASSERT(pv->pv_m == p); /* debugging */
3039 * If requested, scrap the underlying pv->pv_m and the underlying
3040 * pv. If this is a page-table-page we must also free the page.
3042 * pvp must be returned locked.
3046 * page table page (PT, PD, PDP, PML4), caller was responsible
3047 * for testing wired_count.
3049 KKASSERT(pv->pv_m->wire_count == 1);
3050 p = pmap_remove_pv_page(pv);
3054 vm_page_busy_wait(p, FALSE, "pgpun");
3055 vm_page_unwire(p, 0);
3056 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3058 } else if (destroy == 2) {
3060 * Normal page, remove from pmap and leave the underlying
3063 pmap_remove_pv_page(pv);
3065 pv = NULL; /* safety */
3069 * If we acquired pvp ourselves then we are responsible for
3070 * recursively deleting it.
3072 if (pvp && gotpvp) {
3074 * Recursively destroy higher-level page tables.
3076 * This is optional. If we do not, they will still
3077 * be destroyed when the process exits.
3079 * NOTE: Do not destroy pv_entry's with extra hold refs,
3080 * a caller may have unlocked it and intends to
3081 * continue to use it.
3083 if (pmap_dynamic_delete &&
3085 pvp->pv_m->wire_count == 1 &&
3086 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3087 pvp->pv_pindex < pmap_pml4_pindex()) {
3088 if (pmap != &kernel_pmap) {
3089 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3090 pvp = NULL; /* safety */
3092 kprintf("Attempt to remove kernel_pmap pindex "
3093 "%jd\n", pvp->pv_pindex);
3103 * Remove the vm_page association to a pv. The pv must be locked.
3107 pmap_remove_pv_page(pv_entry_t pv)
3113 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3119 * Grow the number of kernel page table entries, if needed.
3121 * This routine is always called to validate any address space
3122 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3123 * space below KERNBASE.
3125 * kernel_map must be locked exclusively by the caller.
3128 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3131 vm_offset_t ptppaddr;
3133 pd_entry_t *pt, newpt;
3134 pdp_entry_t *pd, newpd;
3135 int update_kernel_vm_end;
3138 * bootstrap kernel_vm_end on first real VM use
3140 if (kernel_vm_end == 0) {
3141 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3144 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3147 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3149 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3150 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3151 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
3152 kernel_vm_end = vm_map_max(&kernel_map);
3159 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3160 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3161 * do not want to force-fill 128G worth of page tables.
3163 if (kstart < KERNBASE) {
3164 if (kstart > kernel_vm_end)
3165 kstart = kernel_vm_end;
3166 KKASSERT(kend <= KERNBASE);
3167 update_kernel_vm_end = 1;
3169 update_kernel_vm_end = 0;
3172 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3173 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3175 if (kend - 1 >= vm_map_max(&kernel_map))
3176 kend = vm_map_max(&kernel_map);
3178 while (kstart < kend) {
3179 pt = pmap_pt(&kernel_pmap, kstart);
3182 * We need a new PD entry
3184 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3187 VM_ALLOC_INTERRUPT);
3189 panic("pmap_growkernel: no memory to grow "
3192 paddr = VM_PAGE_TO_PHYS(nkpg);
3193 pmap_zero_page(paddr);
3194 pd = pmap_pd(&kernel_pmap, kstart);
3196 newpd = (pdp_entry_t)
3198 kernel_pmap.pmap_bits[PG_V_IDX] |
3199 kernel_pmap.pmap_bits[PG_RW_IDX] |
3200 kernel_pmap.pmap_bits[PG_A_IDX]);
3201 atomic_swap_long(pd, newpd);
3204 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3208 continue; /* try again */
3211 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3212 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3213 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3214 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3215 kstart = vm_map_max(&kernel_map);
3224 * This index is bogus, but out of the way
3226 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3229 VM_ALLOC_INTERRUPT);
3231 panic("pmap_growkernel: no memory to grow kernel");
3234 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3235 pmap_zero_page(ptppaddr);
3236 newpt = (pd_entry_t)(ptppaddr |
3237 kernel_pmap.pmap_bits[PG_V_IDX] |
3238 kernel_pmap.pmap_bits[PG_RW_IDX] |
3239 kernel_pmap.pmap_bits[PG_A_IDX]);
3240 atomic_swap_long(pt, newpt);
3242 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3243 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3245 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3246 kstart = vm_map_max(&kernel_map);
3252 * Only update kernel_vm_end for areas below KERNBASE.
3254 if (update_kernel_vm_end && kernel_vm_end < kstart)
3255 kernel_vm_end = kstart;
3259 * Add a reference to the specified pmap.
3262 pmap_reference(pmap_t pmap)
3265 atomic_add_int(&pmap->pm_count, 1);
3269 pmap_maybethreaded(pmap_t pmap)
3271 atomic_set_int(&pmap->pm_flags, PMAP_MULTI);
3275 * Called while page is hard-busied to clear the PG_MAPPED and PG_WRITEABLE
3279 pmap_mapped_sync(vm_page_t m)
3281 if (m->md.pmap_count == 0)
3282 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3286 /***************************************************
3287 * page management routines.
3288 ***************************************************/
3291 * Hold a pv without locking it
3295 pv_hold(pv_entry_t pv)
3297 atomic_add_int(&pv->pv_hold, 1);
3302 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3303 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3306 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3307 * pv list via its page) must be held by the caller in order to stabilize
3311 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3316 * Critical path shortcut expects pv to already have one ref
3317 * (for the pv->pv_pmap).
3319 count = pv->pv_hold;
3322 if ((count & PV_HOLD_LOCKED) == 0) {
3323 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3324 (count + 1) | PV_HOLD_LOCKED)) {
3327 pv->pv_line = lineno;
3332 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3340 * Drop a previously held pv_entry which could not be locked, allowing its
3343 * Must not be called with a spinlock held as we might zfree() the pv if it
3344 * is no longer associated with a pmap and this was the last hold count.
3347 pv_drop(pv_entry_t pv)
3352 count = pv->pv_hold;
3354 KKASSERT((count & PV_HOLD_MASK) > 0);
3355 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3356 (PV_HOLD_LOCKED | 1));
3357 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3358 if ((count & PV_HOLD_MASK) == 1) {
3360 if (pmap_enter_debug > 0) {
3362 kprintf("pv_drop: free pv %p\n", pv);
3365 KKASSERT(count == 1);
3366 KKASSERT(pv->pv_pmap == NULL);
3376 * Find or allocate the requested PV entry, returning a locked, held pv.
3378 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3379 * for the caller and one representing the pmap and vm_page association.
3381 * If (*isnew) is zero, the returned pv will have only one hold count.
3383 * Since both associations can only be adjusted while the pv is locked,
3384 * together they represent just one additional hold.
3388 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3390 struct mdglobaldata *md = mdcpu;
3398 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3401 pnew = md->gd_newpv; /* might race NULL */
3402 md->gd_newpv = NULL;
3407 pnew = zalloc(pvzone);
3409 spin_lock_shared(&pmap->pm_spin);
3414 pv = pv_entry_lookup(pmap, pindex);
3419 * Requires exclusive pmap spinlock
3421 if (pmap_excl == 0) {
3423 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3424 spin_unlock_shared(&pmap->pm_spin);
3425 spin_lock(&pmap->pm_spin);
3431 * We need to block if someone is holding our
3432 * placemarker. As long as we determine the
3433 * placemarker has not been aquired we do not
3434 * need to get it as acquision also requires
3435 * the pmap spin lock.
3437 * However, we can race the wakeup.
3439 pmark = pmap_placemarker_hash(pmap, pindex);
3441 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3442 tsleep_interlock(pmark, 0);
3443 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3444 if (((*pmark ^ pindex) &
3445 ~PM_PLACEMARK_WAKEUP) == 0) {
3446 spin_unlock(&pmap->pm_spin);
3447 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3448 spin_lock(&pmap->pm_spin);
3454 * Setup the new entry
3456 pnew->pv_pmap = pmap;
3457 pnew->pv_pindex = pindex;
3458 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3461 pnew->pv_func = func;
3462 pnew->pv_line = lineno;
3463 if (pnew->pv_line_lastfree > 0) {
3464 pnew->pv_line_lastfree =
3465 -pnew->pv_line_lastfree;
3468 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3469 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3470 spin_unlock(&pmap->pm_spin);
3473 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3478 * We already have an entry, cleanup the staged pnew if
3479 * we can get the lock, otherwise block and retry.
3481 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3483 spin_unlock(&pmap->pm_spin);
3485 spin_unlock_shared(&pmap->pm_spin);
3487 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3489 zfree(pvzone, pnew);
3492 if (md->gd_newpv == NULL)
3493 md->gd_newpv = pnew;
3495 zfree(pvzone, pnew);
3498 KKASSERT(pv->pv_pmap == pmap &&
3499 pv->pv_pindex == pindex);
3504 spin_unlock(&pmap->pm_spin);
3505 _pv_lock(pv PMAP_DEBUG_COPY);
3507 spin_lock(&pmap->pm_spin);
3509 spin_unlock_shared(&pmap->pm_spin);
3510 _pv_lock(pv PMAP_DEBUG_COPY);
3512 spin_lock_shared(&pmap->pm_spin);
3519 * Find the requested PV entry, returning a locked+held pv or NULL
3523 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3528 spin_lock_shared(&pmap->pm_spin);
3533 pv = pv_entry_lookup(pmap, pindex);
3536 * Block if there is ANY placemarker. If we are to
3537 * return it, we must also aquire the spot, so we
3538 * have to block even if the placemarker is held on
3539 * a different address.
3541 * OPTIMIZATION: If pmarkp is passed as NULL the
3542 * caller is just probing (or looking for a real
3543 * pv_entry), and in this case we only need to check
3544 * to see if the placemarker matches pindex.
3549 * Requires exclusive pmap spinlock
3551 if (pmap_excl == 0) {
3553 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3554 spin_unlock_shared(&pmap->pm_spin);
3555 spin_lock(&pmap->pm_spin);
3560 pmark = pmap_placemarker_hash(pmap, pindex);
3562 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3563 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3564 tsleep_interlock(pmark, 0);
3565 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3566 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3567 ((*pmark ^ pindex) &
3568 ~PM_PLACEMARK_WAKEUP) == 0) {
3569 spin_unlock(&pmap->pm_spin);
3570 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3571 spin_lock(&pmap->pm_spin);
3576 if (atomic_swap_long(pmark, pindex) !=
3578 panic("_pv_get: pmark race");
3582 spin_unlock(&pmap->pm_spin);
3585 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3587 spin_unlock(&pmap->pm_spin);
3589 spin_unlock_shared(&pmap->pm_spin);
3590 KKASSERT(pv->pv_pmap == pmap &&
3591 pv->pv_pindex == pindex);
3595 spin_unlock(&pmap->pm_spin);
3596 _pv_lock(pv PMAP_DEBUG_COPY);
3598 spin_lock(&pmap->pm_spin);
3600 spin_unlock_shared(&pmap->pm_spin);
3601 _pv_lock(pv PMAP_DEBUG_COPY);
3603 spin_lock_shared(&pmap->pm_spin);
3609 * Lookup, hold, and attempt to lock (pmap,pindex).
3611 * If the entry does not exist NULL is returned and *errorp is set to 0
3613 * If the entry exists and could be successfully locked it is returned and
3614 * errorp is set to 0.
3616 * If the entry exists but could NOT be successfully locked it is returned
3617 * held and *errorp is set to 1.
3619 * If the entry is placemarked by someone else NULL is returned and *errorp
3624 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3628 spin_lock_shared(&pmap->pm_spin);
3630 pv = pv_entry_lookup(pmap, pindex);
3634 pmark = pmap_placemarker_hash(pmap, pindex);
3636 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3638 } else if (pmarkp &&
3639 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3643 * Can't set a placemark with a NULL pmarkp, or if
3644 * pmarkp is non-NULL but we failed to set our
3651 spin_unlock_shared(&pmap->pm_spin);
3657 * XXX This has problems if the lock is shared, why?
3659 if (pv_hold_try(pv)) {
3660 spin_unlock_shared(&pmap->pm_spin);
3662 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3663 return(pv); /* lock succeeded */
3665 spin_unlock_shared(&pmap->pm_spin);
3668 return (pv); /* lock failed */
3672 * Lock a held pv, keeping the hold count
3676 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
3681 count = pv->pv_hold;
3683 if ((count & PV_HOLD_LOCKED) == 0) {
3684 if (atomic_cmpset_int(&pv->pv_hold, count,
3685 count | PV_HOLD_LOCKED)) {
3688 pv->pv_line = lineno;
3694 tsleep_interlock(pv, 0);
3695 if (atomic_cmpset_int(&pv->pv_hold, count,
3696 count | PV_HOLD_WAITING)) {
3698 if (pmap_enter_debug > 0) {
3700 kprintf("pv waiting on %s:%d\n",
3701 pv->pv_func, pv->pv_line);
3704 tsleep(pv, PINTERLOCKED, "pvwait", hz);
3711 * Unlock a held and locked pv, keeping the hold count.
3715 pv_unlock(pv_entry_t pv)
3720 count = pv->pv_hold;
3722 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
3723 (PV_HOLD_LOCKED | 1));
3724 if (atomic_cmpset_int(&pv->pv_hold, count,
3726 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
3727 if (count & PV_HOLD_WAITING)
3735 * Unlock and drop a pv. If the pv is no longer associated with a pmap
3736 * and the hold count drops to zero we will free it.
3738 * Caller should not hold any spin locks. We are protected from hold races
3739 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
3740 * lock held. A pv cannot be located otherwise.
3744 pv_put(pv_entry_t pv)
3747 if (pmap_enter_debug > 0) {
3749 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
3754 * Normal put-aways must have a pv_m associated with the pv,
3755 * but allow the case where the pv has been destructed due
3756 * to pmap_dynamic_delete.
3758 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
3761 * Fast - shortcut most common condition
3763 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
3774 * Remove the pmap association from a pv, require that pv_m already be removed,
3775 * then unlock and drop the pv. Any pte operations must have already been
3776 * completed. This call may result in a last-drop which will physically free
3779 * Removing the pmap association entails an additional drop.
3781 * pv must be exclusively locked on call and will be disposed of on return.
3785 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
3790 pv->pv_func_lastfree = func;
3791 pv->pv_line_lastfree = lineno;
3793 KKASSERT(pv->pv_m == NULL);
3794 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
3795 (PV_HOLD_LOCKED|1));
3796 if ((pmap = pv->pv_pmap) != NULL) {
3797 spin_lock(&pmap->pm_spin);
3798 KKASSERT(pv->pv_pmap == pmap);
3799 if (pmap->pm_pvhint_pt == pv)
3800 pmap->pm_pvhint_pt = NULL;
3801 if (pmap->pm_pvhint_unused == pv)
3802 pmap->pm_pvhint_unused = NULL;
3803 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
3804 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3807 spin_unlock(&pmap->pm_spin);
3810 * Try to shortcut three atomic ops, otherwise fall through
3811 * and do it normally. Drop two refs and the lock all in
3815 if (vm_page_unwire_quick(pvp->pv_m))
3816 panic("_pv_free: bad wirecount on pvp");
3818 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
3820 if (pmap_enter_debug > 0) {
3822 kprintf("pv_free: free pv %p\n", pv);
3828 pv_drop(pv); /* ref for pv_pmap */
3835 * This routine is very drastic, but can save the system
3843 static int warningdone=0;
3845 if (pmap_pagedaemon_waken == 0)
3847 pmap_pagedaemon_waken = 0;
3848 if (warningdone < 5) {
3849 kprintf("pmap_collect: pv_entries exhausted -- "
3850 "suggest increasing vm.pmap_pv_entries above %ld\n",
3851 vm_pmap_pv_entries);
3855 for (i = 0; i < vm_page_array_size; i++) {
3856 m = &vm_page_array[i];
3857 if (m->wire_count || m->hold_count)
3859 if (vm_page_busy_try(m, TRUE) == 0) {
3860 if (m->wire_count == 0 && m->hold_count == 0) {
3869 * Scan the pmap for active page table entries and issue a callback.
3870 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
3871 * its parent page table.
3873 * pte_pv will be NULL if the page or page table is unmanaged.
3874 * pt_pv will point to the page table page containing the pte for the page.
3876 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
3877 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
3878 * process pmap's PD and page to the callback function. This can be
3879 * confusing because the pt_pv is really a pd_pv, and the target page
3880 * table page is simply aliased by the pmap and not owned by it.
3882 * It is assumed that the start and end are properly rounded to the page size.
3884 * It is assumed that PD pages and above are managed and thus in the RB tree,
3885 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
3887 struct pmap_scan_info {
3891 vm_pindex_t sva_pd_pindex;
3892 vm_pindex_t eva_pd_pindex;
3893 void (*func)(pmap_t, struct pmap_scan_info *,
3894 vm_pindex_t *, pv_entry_t, vm_offset_t,
3895 pt_entry_t *, void *);
3897 pmap_inval_bulk_t bulk_core;
3898 pmap_inval_bulk_t *bulk;
3903 static int pmap_scan_cmp(pv_entry_t pv, void *data);
3904 static int pmap_scan_callback(pv_entry_t pv, void *data);
3907 pmap_scan(struct pmap_scan_info *info, int smp_inval)
3909 struct pmap *pmap = info->pmap;
3910 pv_entry_t pt_pv; /* A page table PV */
3911 pv_entry_t pte_pv; /* A page table entry PV */
3912 vm_pindex_t *pte_placemark;
3913 vm_pindex_t *pt_placemark;
3916 struct pv_entry dummy_pv;
3921 if (info->sva == info->eva)
3924 info->bulk = &info->bulk_core;
3925 pmap_inval_bulk_init(&info->bulk_core, pmap);
3931 * Hold the token for stability; if the pmap is empty we have nothing
3935 if (pmap->pm_stats.resident_count == 0) {
3943 * Special handling for scanning one page, which is a very common
3944 * operation (it is?).
3946 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
3948 if (info->sva + PAGE_SIZE == info->eva) {
3949 if (info->sva >= VM_MAX_USER_ADDRESS) {
3951 * Kernel mappings do not track wire counts on
3952 * page table pages and only maintain pd_pv and
3953 * pte_pv levels so pmap_scan() works.
3956 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
3958 KKASSERT(pte_pv == NULL);
3959 ptep = vtopte(info->sva);
3962 * We hold pte_placemark across the operation for
3965 * WARNING! We must hold pt_placemark across the
3966 * *ptep test to prevent misintepreting
3967 * a non-zero *ptep as a shared page
3968 * table page. Hold it across the function
3969 * callback as well for SMP safety.
3971 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
3973 KKASSERT(pte_pv == NULL);
3974 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
3976 if (pt_pv == NULL) {
3979 pd_pv = pv_get(pmap,
3980 pmap_pd_pindex(info->sva),
3983 ptep = pv_pte_lookup(pd_pv,
3984 pmap_pt_index(info->sva));
3986 info->func(pmap, info,
3987 pt_placemark, pd_pv,
3991 pv_placemarker_wakeup(pmap,
3996 pv_placemarker_wakeup(pmap,
4000 pv_placemarker_wakeup(pmap, pt_placemark);
4002 pv_placemarker_wakeup(pmap, pte_placemark);
4005 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4009 * NOTE: *ptep can't be ripped out from under us if we hold
4010 * pte_pv (or pte_placemark) locked, but bits can
4016 KKASSERT(pte_pv == NULL);
4017 pv_placemarker_wakeup(pmap, pte_placemark);
4019 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]) ==
4020 pmap->pmap_bits[PG_V_IDX],
4021 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4022 *ptep, oldpte, info->sva));
4023 info->func(pmap, info, pte_placemark, pt_pv,
4024 info->sva, ptep, info->arg);
4029 pmap_inval_bulk_flush(info->bulk);
4034 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4037 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4038 * bounds, resulting in a pd_pindex of 0. To solve the
4039 * problem we use an inclusive range.
4041 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4042 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4044 if (info->sva >= VM_MAX_USER_ADDRESS) {
4046 * The kernel does not currently maintain any pv_entry's for
4047 * higher-level page tables.
4049 bzero(&dummy_pv, sizeof(dummy_pv));
4050 dummy_pv.pv_pindex = info->sva_pd_pindex;
4051 spin_lock(&pmap->pm_spin);
4052 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4053 pmap_scan_callback(&dummy_pv, info);
4054 ++dummy_pv.pv_pindex;
4055 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4058 spin_unlock(&pmap->pm_spin);
4061 * User page tables maintain local PML4, PDP, PD, and PT
4062 * pv_entry's. pv_entry's are not used for PTEs.
4064 spin_lock(&pmap->pm_spin);
4065 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4066 pmap_scan_callback, info);
4067 spin_unlock(&pmap->pm_spin);
4069 pmap_inval_bulk_flush(info->bulk);
4073 * WARNING! pmap->pm_spin held
4075 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4076 * bounds, resulting in a pd_pindex of 0. To solve the
4077 * problem we use an inclusive range.
4080 pmap_scan_cmp(pv_entry_t pv, void *data)
4082 struct pmap_scan_info *info = data;
4083 if (pv->pv_pindex < info->sva_pd_pindex)
4085 if (pv->pv_pindex > info->eva_pd_pindex)
4091 * pmap_scan() by PDs
4093 * WARNING! pmap->pm_spin held
4096 pmap_scan_callback(pv_entry_t pv, void *data)
4098 struct pmap_scan_info *info = data;
4099 struct pmap *pmap = info->pmap;
4100 pv_entry_t pd_pv; /* A page directory PV */
4101 pv_entry_t pt_pv; /* A page table PV */
4102 vm_pindex_t *pt_placemark;
4107 vm_offset_t va_next;
4108 vm_pindex_t pd_pindex;
4118 * Pull the PD pindex from the pv before releasing the spinlock.
4120 * WARNING: pv is faked for kernel pmap scans.
4122 pd_pindex = pv->pv_pindex;
4123 spin_unlock(&pmap->pm_spin);
4124 pv = NULL; /* invalid after spinlock unlocked */
4127 * Calculate the page range within the PD. SIMPLE pmaps are
4128 * direct-mapped for the entire 2^64 address space. Normal pmaps
4129 * reflect the user and kernel address space which requires
4130 * cannonicalization w/regards to converting pd_pindex's back
4133 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4134 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4135 (sva & PML4_SIGNMASK)) {
4136 sva |= PML4_SIGNMASK;
4138 eva = sva + NBPDP; /* can overflow */
4139 if (sva < info->sva)
4141 if (eva < info->sva || eva > info->eva)
4145 * NOTE: kernel mappings do not track page table pages, only
4148 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4149 * However, for the scan to be efficient we try to
4150 * cache items top-down.
4155 for (; sva < eva; sva = va_next) {
4158 if (sva >= VM_MAX_USER_ADDRESS) {
4167 * PD cache, scan shortcut if it doesn't exist.
4169 if (pd_pv == NULL) {
4170 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4171 } else if (pd_pv->pv_pmap != pmap ||
4172 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4174 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4176 if (pd_pv == NULL) {
4177 va_next = (sva + NBPDP) & ~PDPMASK;
4186 * NOTE: The cached pt_pv can be removed from the pmap when
4187 * pmap_dynamic_delete is enabled.
4189 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4190 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4194 if (pt_pv == NULL) {
4195 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4196 &pt_placemark, &error);
4198 pv_put(pd_pv); /* lock order */
4205 pv_placemarker_wait(pmap, pt_placemark);
4210 /* may have to re-check later if pt_pv is NULL here */
4214 * If pt_pv is NULL we either have a shared page table
4215 * page (NOT IMPLEMENTED XXX) and must issue a callback
4216 * specific to that case, or there is no page table page.
4218 * Either way we can skip the page table page.
4220 * WARNING! pt_pv can also be NULL due to a pv creation
4221 * race where we find it to be NULL and then
4222 * later see a pte_pv. But its possible the pt_pv
4223 * got created inbetween the two operations, so
4226 * XXX This should no longer be the case because
4227 * we have pt_placemark.
4229 if (pt_pv == NULL) {
4233 * Possible unmanaged (shared from another pmap)
4236 * WARNING! We must hold pt_placemark across the
4237 * *ptep test to prevent misintepreting
4238 * a non-zero *ptep as a shared page
4239 * table page. Hold it across the function
4240 * callback as well for SMP safety.
4243 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4244 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4245 info->func(pmap, info, pt_placemark, pd_pv,
4246 sva, ptep, info->arg);
4248 pv_placemarker_wakeup(pmap, pt_placemark);
4251 pv_placemarker_wakeup(pmap, pt_placemark);
4255 * Done, move to next page table page.
4257 va_next = (sva + NBPDR) & ~PDRMASK;
4264 * From this point in the loop testing pt_pv for non-NULL
4265 * means we are in UVM, else if it is NULL we are in KVM.
4267 * Limit our scan to either the end of the va represented
4268 * by the current page table page, or to the end of the
4269 * range being removed.
4272 va_next = (sva + NBPDR) & ~PDRMASK;
4279 * Scan the page table for pages. Some pages may not be
4280 * managed (might not have a pv_entry).
4282 * There is no page table management for kernel pages so
4283 * pt_pv will be NULL in that case, but otherwise pt_pv
4284 * is non-NULL, locked, and referenced.
4288 * At this point a non-NULL pt_pv means a UVA, and a NULL
4289 * pt_pv means a KVA.
4292 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4296 while (sva < va_next) {
4297 vm_pindex_t *pte_placemark;
4301 * Yield every 64 pages, stop if requested.
4303 if ((++info->count & 63) == 0)
4309 * We can shortcut our scan if *ptep == 0. This is
4310 * an unlocked check.
4320 * Acquire the pte_placemark. pte_pv's won't exist
4323 * A multitude of races are possible here so if we
4324 * cannot lock definite state we clean out our cache
4325 * and break the inner while() loop to force a loop
4326 * up to the top of the for().
4328 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4329 * validity instead of looping up?
4331 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4332 &pte_placemark, &error);
4333 KKASSERT(pte_pv == NULL);
4336 pv_put(pd_pv); /* lock order */
4340 pv_put(pt_pv); /* lock order */
4343 pv_placemarker_wait(pmap, pte_placemark);
4344 va_next = sva; /* retry */
4349 * Reload *ptep after successfully locking the
4355 pv_placemarker_wakeup(pmap, pte_placemark);
4362 * We can't hold pd_pv across the callback (because
4363 * we don't pass it to the callback and the callback
4367 vm_page_wire_quick(pd_pv->pv_m);
4372 * Ready for the callback. The locked placemarker
4373 * is consumed by the callback.
4375 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4379 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4380 ("badC *ptep %016lx/%016lx sva %016lx",
4381 *ptep, oldpte, sva));
4383 * We must unlock pd_pv across the callback
4384 * to avoid deadlocks on any recursive
4385 * disposal. Re-check that it still exists
4388 * Call target disposes of pte_placemark
4389 * and may destroy but will not dispose
4392 info->func(pmap, info, pte_placemark, pt_pv,
4393 sva, ptep, info->arg);
4398 * We must unlock pd_pv across the callback
4399 * to avoid deadlocks on any recursive
4400 * disposal. Re-check that it still exists
4403 * Call target disposes of pte_placemark
4404 * and may destroy but will not dispose
4407 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4408 ("badD *ptep %016lx/%016lx sva %016lx ",
4409 *ptep, oldpte, sva));
4410 info->func(pmap, info, pte_placemark, pt_pv,
4411 sva, ptep, info->arg);
4415 if (vm_page_unwire_quick(pd_pv->pv_m)) {
4416 panic("pmap_scan_callback: "
4417 "bad wirecount on pd_pv");
4419 if (pd_pv->pv_pmap == NULL) {
4420 va_next = sva; /* retry */
4426 * NOTE: The cached pt_pv can be removed from the
4427 * pmap when pmap_dynamic_delete is enabled,
4428 * which will cause ptep to become stale.
4430 * This also means that no pages remain under
4431 * the PT, so we can just break out of the inner
4432 * loop and let the outer loop clean everything
4435 if (pt_pv && pt_pv->pv_pmap != pmap)
4449 if ((++info->count & 7) == 0)
4453 * Relock before returning.
4455 spin_lock(&pmap->pm_spin);
4460 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4462 struct pmap_scan_info info;
4467 info.func = pmap_remove_callback;
4469 pmap_scan(&info, 1);
4472 if (eva - sva < 1024*1024) {
4474 cpu_invlpg((void *)sva);
4482 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4484 struct pmap_scan_info info;
4489 info.func = pmap_remove_callback;
4491 pmap_scan(&info, 0);
4495 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4496 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
4497 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4502 * Managed or unmanaged pte (pte_placemark is non-NULL)
4504 * pt_pv's wire_count is still bumped by unmanaged pages
4505 * so we must decrement it manually.
4507 * We have to unwire the target page table page.
4509 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4510 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4513 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4514 KKASSERT(pte & pmap->pmap_bits[PG_V_IDX]);
4515 if (pte & pmap->pmap_bits[PG_M_IDX])
4517 if (pte & pmap->pmap_bits[PG_A_IDX])
4518 vm_page_flag_set(p, PG_REFERENCED);
4521 * NOTE: p is not hard-busied so it is not safe to
4522 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4523 * transition against them being set in
4526 if (pte & pmap->pmap_bits[PG_RW_IDX])
4527 atomic_add_long(&p->md.writeable_count, -1);
4528 pmap_page_stats_deleting(
4529 atomic_fetchadd_long(&p->md.pmap_count, -1));
4531 if (pte & pmap->pmap_bits[PG_V_IDX]) {
4532 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4533 if (pt_pv && vm_page_unwire_quick(pt_pv->pv_m))
4534 panic("pmap_remove: insufficient wirecount");
4536 if (pte & pmap->pmap_bits[PG_W_IDX])
4537 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4538 if (pte & pmap->pmap_bits[PG_G_IDX])
4539 cpu_invlpg((void *)va);
4540 pv_placemarker_wakeup(pmap, pte_placemark);
4544 * Removes this physical page from all physical maps in which it resides.
4545 * Reflects back modify bits to the pager.
4547 * This routine may not be called from an interrupt.
4549 * The page must be busied by its caller, preventing new ptes from being
4550 * installed. This allows us to assert that pmap_count is zero and safely
4551 * clear the MAPPED and WRITEABLE bits upon completion.
4555 pmap_remove_all(vm_page_t m)
4559 if (!pmap_initialized)
4563 * pmap_count doesn't cover fictitious pages, but PG_MAPPED does
4564 * (albeit without certain race protections).
4567 if (m->md.pmap_count == 0)
4570 if ((m->flags & PG_MAPPED) == 0)
4573 retry = ticks + hz * 60;
4575 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
4576 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4577 PMAP_PAGE_BACKING_RETRY;
4578 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4579 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4581 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4582 vm_page_flag_set(m, PG_REFERENCED);
4585 * NOTE: m is not hard-busied so it is not safe to
4586 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4587 * transition against them being set in
4590 if (ipte & ipmap->pmap_bits[PG_RW_IDX])
4591 atomic_add_long(&m->md.writeable_count, -1);
4592 pmap_page_stats_deleting(
4593 atomic_fetchadd_long(&m->md.pmap_count, -1));
4597 * Cleanup various tracking counters. pt_pv can't go away
4598 * due to our wired ref.
4600 if (ipmap != &kernel_pmap) {
4603 spin_lock_shared(&ipmap->pm_spin);
4604 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4605 spin_unlock_shared(&ipmap->pm_spin);
4608 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4609 panic("pmap_remove_all: bad "
4610 "wire_count on pt_pv");
4613 &ipmap->pm_stats.resident_count, -1);
4616 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4617 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4618 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4619 cpu_invlpg((void *)iva);
4620 } PMAP_PAGE_BACKING_DONE;
4623 * pmap_count should be zero but it is possible to race a pmap_enter()
4624 * replacement (see 'oldm'). Once it is zero it cannot become
4625 * non-zero because the page is hard-busied.
4627 if (m->md.pmap_count || m->md.writeable_count) {
4628 tsleep(&m->md.pmap_count, 0, "pgunm", 1);
4629 if (retry - ticks > 0)
4631 panic("pmap_remove_all: cannot return pmap_count "
4633 m->md.pmap_count, m->md.writeable_count);
4635 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
4639 * Removes the page from a particular pmap.
4641 * The page must be busied by the caller.
4644 pmap_remove_specific(pmap_t pmap_match, vm_page_t m)
4646 if (!pmap_initialized)
4650 * PG_MAPPED test works for both non-fictitious and fictitious pages.
4652 if ((m->flags & PG_MAPPED) == 0)
4655 PMAP_PAGE_BACKING_SCAN(m, pmap_match, ipmap, iptep, ipte, iva) {
4656 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4657 PMAP_PAGE_BACKING_RETRY;
4658 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4659 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4661 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4662 vm_page_flag_set(m, PG_REFERENCED);
4665 * NOTE: m is not hard-busied so it is not safe to
4666 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4667 * transition against them being set in
4670 if (ipte & ipmap->pmap_bits[PG_RW_IDX])
4671 atomic_add_long(&m->md.writeable_count, -1);
4672 pmap_page_stats_deleting(
4673 atomic_fetchadd_long(&m->md.pmap_count, -1));
4677 * Cleanup various tracking counters. pt_pv can't go away
4678 * due to our wired ref.
4680 if (ipmap != &kernel_pmap) {
4683 spin_lock_shared(&ipmap->pm_spin);
4684 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4685 spin_unlock_shared(&ipmap->pm_spin);
4689 &ipmap->pm_stats.resident_count, -1);
4690 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4691 panic("pmap_remove_specific: bad "
4692 "wire_count on pt_pv");
4696 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4697 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4698 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4699 cpu_invlpg((void *)iva);
4700 } PMAP_PAGE_BACKING_DONE;
4704 * Set the physical protection on the specified range of this map
4705 * as requested. This function is typically only used for debug watchpoints
4708 * This function may not be called from an interrupt if the map is
4709 * not the kernel_pmap.
4711 * NOTE! For shared page table pages we just unmap the page.
4714 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4716 struct pmap_scan_info info;
4717 /* JG review for NX */
4721 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
4722 pmap_remove(pmap, sva, eva);
4725 if (prot & VM_PROT_WRITE)
4730 info.func = pmap_protect_callback;
4732 pmap_scan(&info, 1);
4737 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
4738 vm_pindex_t *pte_placemark,
4739 pv_entry_t pt_pv, vm_offset_t va,
4740 pt_entry_t *ptep, void *arg __unused)
4750 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4751 cbits &= ~pmap->pmap_bits[PG_A_IDX];
4752 cbits &= ~pmap->pmap_bits[PG_M_IDX];
4754 /* else unmanaged page, adjust bits, no wire changes */
4757 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
4759 if (pmap_enter_debug > 0) {
4761 kprintf("pmap_protect va=%lx ptep=%p "
4762 "pt_pv=%p cbits=%08lx\n",
4763 va, ptep, pt_pv, cbits
4767 if (pbits != cbits) {
4768 if (!pmap_inval_smp_cmpset(pmap, va,
4769 ptep, pbits, cbits)) {
4773 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4774 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4775 if (pbits & pmap->pmap_bits[PG_A_IDX])
4776 vm_page_flag_set(m, PG_REFERENCED);
4777 if (pbits & pmap->pmap_bits[PG_M_IDX])
4779 if (pbits & pmap->pmap_bits[PG_RW_IDX])
4780 atomic_add_long(&m->md.writeable_count, -1);
4784 pv_placemarker_wakeup(pmap, pte_placemark);
4788 * Insert the vm_page (m) at the virtual address (va), replacing any prior
4789 * mapping at that address. Set protection and wiring as requested.
4791 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
4792 * possible. If it is we enter the page into the appropriate shared pmap
4793 * hanging off the related VM object instead of the passed pmap, then we
4794 * share the page table page from the VM object's pmap into the current pmap.
4796 * NOTE: This routine MUST insert the page into the pmap now, it cannot
4800 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4801 boolean_t wired, vm_map_entry_t entry)
4803 pv_entry_t pt_pv; /* page table */
4804 pv_entry_t pte_pv; /* page table entry */
4805 vm_pindex_t *pte_placemark;
4815 va = trunc_page(va);
4816 #ifdef PMAP_DIAGNOSTIC
4818 panic("pmap_enter: toobig");
4819 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
4820 panic("pmap_enter: invalid to pmap_enter page table "
4821 "pages (va: 0x%lx)", va);
4823 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
4824 kprintf("Warning: pmap_enter called on UVA with "
4827 db_print_backtrace();
4830 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
4831 kprintf("Warning: pmap_enter called on KVA without"
4834 db_print_backtrace();
4839 * Get the locked page table page (pt_pv) for our new page table
4840 * entry, allocating it if necessary.
4842 * There is no pte_pv for a terminal pte so the terminal pte will
4843 * be locked via pte_placemark.
4845 * Only MMU actions by the CPU itself can modify the ptep out from
4848 * If the pmap is still being initialized we assume existing
4851 * NOTE: Kernel mapppings do not track page table pages
4852 * (i.e. there is no pt_pv pt_pv structure).
4854 * NOTE: origpte here is 'tentative', used only to check for
4855 * the degenerate case where the entry already exists and
4858 if (pmap_initialized == FALSE) {
4861 pte_placemark = NULL;
4865 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
4866 KKASSERT(pte_pv == NULL);
4867 if (va >= VM_MAX_USER_ADDRESS) {
4871 pt_pv = pmap_allocpte(pmap, pmap_pt_pindex(va), NULL);
4872 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
4878 pa = VM_PAGE_TO_PHYS(m);
4881 * Calculate the new PTE.
4883 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
4884 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
4886 newpte |= pmap->pmap_bits[PG_W_IDX];
4887 if (va < VM_MAX_USER_ADDRESS)
4888 newpte |= pmap->pmap_bits[PG_U_IDX];
4889 if ((m->flags & PG_FICTITIOUS) == 0)
4890 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
4891 // if (pmap == &kernel_pmap)
4892 // newpte |= pgeflag;
4893 newpte |= pmap->pmap_cache_bits[m->pat_mode];
4896 * It is possible for multiple faults to occur in threaded
4897 * environments, the existing pte might be correct.
4899 if (((origpte ^ newpte) &
4900 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
4901 pmap->pmap_bits[PG_A_IDX])) == 0) {
4906 * Adjust page flags. The page is soft-busied or hard-busied, we
4907 * should be able to safely set PG_* flag bits even with the (shared)
4910 * The pmap_count and writeable_count is only tracked for
4911 * non-fictitious pages. As a bit of a safety, bump pmap_count
4912 * and set the PG_* bits before mapping the page. If another part
4913 * of the system does not properly hard-busy the page (against our
4914 * soft-busy or hard-busy) in order to remove mappings it might not
4915 * see the pte that we are about to add and thus will not be able to
4916 * drop pmap_count to 0.
4918 * The PG_MAPPED and PG_WRITEABLE flags are set for any type of page.
4920 * NOTE! PG_MAPPED and PG_WRITEABLE can only be cleared when
4921 * the page is hard-busied AND pmap_count is 0. This
4922 * interlocks our setting of the flags here.
4924 /*vm_page_spin_lock(m);*/
4925 if ((m->flags & PG_FICTITIOUS) == 0) {
4926 pmap_page_stats_adding(
4927 atomic_fetchadd_long(&m->md.pmap_count, 1));
4928 if (newpte & pmap->pmap_bits[PG_RW_IDX])
4929 atomic_add_long(&m->md.writeable_count, 1);
4931 if (newpte & pmap->pmap_bits[PG_RW_IDX]) {
4932 if ((m->flags & (PG_MAPPED | PG_WRITEABLE)) == 0)
4933 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
4935 if ((m->flags & PG_MAPPED) == 0)
4936 vm_page_flag_set(m, PG_MAPPED);
4938 /*vm_page_spin_unlock(m);*/
4941 * A race can develop when replacing an existing mapping. The new
4942 * page has been busied and the pte is placemark-locked, but the
4943 * old page is could be ripped out from under us at any time by
4946 * The race is handled by having the backing scans check pmap_count
4947 * writeable_count when doing operations that should ensure one
4950 opa = origpte & PG_FRAME;
4951 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
4952 oldm = PHYS_TO_VM_PAGE(opa);
4953 KKASSERT(opa == oldm->phys_addr);
4954 KKASSERT(entry != NULL);
4960 * Swap the new and old PTEs and perform any necessary SMP
4963 if ((prot & VM_PROT_NOSYNC) || (opa == 0 && pt_pv != NULL)) {
4965 * Explicitly permitted to avoid pmap cpu mask synchronization
4966 * or the prior content of a non-kernel-related pmap was
4969 origpte = atomic_swap_long(ptep, newpte);
4971 cpu_invlpg((void *)va);
4974 * Not permitted to avoid pmap cpu mask synchronization
4975 * or there prior content being replaced or this is a kernel
4978 * Due to other kernel optimizations, we cannot assume a
4979 * 0->non_zero transition of *ptep can be done with a swap.
4981 origpte = pmap_inval_smp(pmap, va, 1, ptep, newpte);
4983 opa = origpte & PG_FRAME;
4986 if (pmap_enter_debug > 0) {
4988 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
4989 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
4991 origpte, newpte, ptep,
4992 pte_pv, pt_pv, opa, prot);
4997 * Account for the changes in the pt_pv and pmap.
4999 * Retain the same wiring count due to replacing an existing page,
5000 * or bump the wiring count for a new page.
5002 if (pt_pv && opa == 0) {
5003 vm_page_wire_quick(pt_pv->pv_m);
5004 atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
5006 if (wired && (origpte & pmap->pmap_bits[PG_W_IDX]) == 0)
5007 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5010 * Account for the removal of the old page. pmap and pt_pv stats
5011 * have already been fully adjusted for both.
5013 * WARNING! oldm is not soft or hard-busied. The pte at worst can
5014 * only be removed out from under us since we hold the
5015 * placemarker. So if it is still there, it must not have
5018 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5019 KKASSERT(oldm == PHYS_TO_VM_PAGE(opa));
5020 if (origpte & pmap->pmap_bits[PG_M_IDX])
5021 vm_page_dirty(oldm);
5022 if (origpte & pmap->pmap_bits[PG_A_IDX])
5023 vm_page_flag_set(oldm, PG_REFERENCED);
5026 * NOTE: oldm is not hard-busied so it is not safe to
5027 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
5028 * transition against them being set in
5031 if (origpte & pmap->pmap_bits[PG_RW_IDX])
5032 atomic_add_long(&oldm->md.writeable_count, -1);
5033 pmap_page_stats_deleting(
5034 atomic_fetchadd_long(&oldm->md.pmap_count, -1));
5038 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5039 (m->flags & PG_MAPPED));
5042 * Cleanup the pv entry, allowing other accessors. If the new page
5043 * is not managed but we have a pte_pv (which was locking our
5044 * operation), we can free it now. pte_pv->pv_m should be NULL.
5047 pv_placemarker_wakeup(pmap, pte_placemark);
5053 * Make a temporary mapping for a physical address. This is only intended
5054 * to be used for panic dumps.
5056 * The caller is responsible for calling smp_invltlb().
5059 pmap_kenter_temporary(vm_paddr_t pa, long i)
5061 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5062 return ((void *)crashdumpmap);
5066 #define MAX_INIT_PT (96)
5069 * This routine preloads the ptes for a given object into the specified pmap.
5070 * This eliminates the blast of soft faults on process startup and
5071 * immediately after an mmap.
5073 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5077 pmap_object_init_pt(pmap_t pmap, vm_map_entry_t entry,
5078 vm_offset_t addr, vm_size_t size, int limit)
5081 vm_prot_t prot = entry->protection;
5082 vm_object_t object = entry->ba.object;
5083 vm_pindex_t pindex = atop(entry->ba.offset + (addr - entry->ba.start));
5084 struct rb_vm_page_scan_info info;
5089 * We can't preinit if read access isn't set or there is no pmap
5092 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5096 * We can't preinit if the pmap is not the current pmap
5098 lp = curthread->td_lwp;
5099 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5103 * Misc additional checks
5105 psize = x86_64_btop(size);
5107 if ((object->type != OBJT_VNODE) ||
5108 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5109 (object->resident_page_count > MAX_INIT_PT))) {
5113 if (pindex + psize > object->size) {
5114 if (object->size < pindex)
5116 psize = object->size - pindex;
5123 * If everything is segment-aligned do not pre-init here. Instead
5124 * allow the normal vm_fault path to pass a segment hint to
5125 * pmap_enter() which will then use an object-referenced shared
5128 if ((addr & SEG_MASK) == 0 &&
5129 (ctob(psize) & SEG_MASK) == 0 &&
5130 (ctob(pindex) & SEG_MASK) == 0) {
5135 * Use a red-black scan to traverse the requested range and load
5136 * any valid pages found into the pmap.
5138 * We cannot safely scan the object's memq without holding the
5141 info.start_pindex = pindex;
5142 info.end_pindex = pindex + psize - 1;
5147 info.object = object;
5151 * By using the NOLK scan, the callback function must be sure
5152 * to return -1 if the VM page falls out of the object.
5154 vm_object_hold_shared(object);
5155 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5156 pmap_object_init_pt_callback, &info);
5157 vm_object_drop(object);
5165 pmap_object_init_pt_callback(vm_page_t p, void *data)
5167 struct rb_vm_page_scan_info *info = data;
5168 vm_pindex_t rel_index;
5172 * don't allow an madvise to blow away our really
5173 * free pages allocating pv entries.
5175 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5176 vmstats.v_free_count < vmstats.v_free_reserved) {
5181 * Ignore list markers and ignore pages we cannot instantly
5182 * busy (while holding the object token).
5184 if (p->flags & PG_MARKER)
5189 if (vm_page_busy_try(p, TRUE))
5192 if (vm_page_sbusy_try(p))
5195 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5196 (p->flags & PG_FICTITIOUS) == 0) {
5197 if ((p->queue - p->pc) == PQ_CACHE) {
5198 if (hard_busy == 0) {
5199 vm_page_sbusy_drop(p);
5203 vm_page_deactivate(p);
5205 rel_index = p->pindex - info->start_pindex;
5206 pmap_enter(info->pmap, info->addr + x86_64_ptob(rel_index), p,
5207 VM_PROT_READ, FALSE, info->entry);
5212 vm_page_sbusy_drop(p);
5215 * We are using an unlocked scan (that is, the scan expects its
5216 * current element to remain in the tree on return). So we have
5217 * to check here and abort the scan if it isn't.
5219 if (p->object != info->object)
5228 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5231 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5234 * The address must reside within a vm_map mapped range to ensure that the
5235 * page table doesn't get ripped out from under us.
5237 * XXX This is safe only because page table pages are not freed.
5240 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5244 /*spin_lock(&pmap->pm_spin);*/
5245 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5246 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5247 /*spin_unlock(&pmap->pm_spin);*/
5251 /*spin_unlock(&pmap->pm_spin);*/
5256 * Change the wiring attribute for a pmap/va pair. The mapping must already
5257 * exist in the pmap. The mapping may or may not be managed. The wiring in
5258 * the page is not changed, the page is returned so the caller can adjust
5259 * its wiring (the page is not locked in any way).
5261 * Wiring is not a hardware characteristic so there is no need to invalidate
5262 * TLB. However, in an SMP environment we must use a locked bus cycle to
5263 * update the pte (if we are not using the pmap_inval_*() API that is)...
5264 * it's ok to do this for simple wiring changes.
5267 pmap_unwire(pmap_t pmap, vm_offset_t va)
5278 * Assume elements in the kernel pmap are stable
5280 if (pmap == &kernel_pmap) {
5281 if (pmap_pt(pmap, va) == 0)
5283 ptep = pmap_pte_quick(pmap, va);
5284 if (pmap_pte_v(pmap, ptep)) {
5285 if (pmap_pte_w(pmap, ptep))
5286 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5287 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5288 pa = *ptep & PG_FRAME;
5289 m = PHYS_TO_VM_PAGE(pa);
5295 * We can only [un]wire pmap-local pages (we cannot wire
5298 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5302 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5303 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5308 if (pmap_pte_w(pmap, ptep)) {
5309 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5312 /* XXX else return NULL so caller doesn't unwire m ? */
5314 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5316 pa = *ptep & PG_FRAME;
5317 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5324 * Copy the range specified by src_addr/len from the source map to
5325 * the range dst_addr/len in the destination map.
5327 * This routine is only advisory and need not do anything.
5330 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5331 vm_size_t len, vm_offset_t src_addr)
5338 * Zero the specified physical page.
5340 * This function may be called from an interrupt and no locking is
5344 pmap_zero_page(vm_paddr_t phys)
5346 vm_offset_t va = PHYS_TO_DMAP(phys);
5348 pagezero((void *)va);
5354 * Zero part of a physical page by mapping it into memory and clearing
5355 * its contents with bzero.
5357 * off and size may not cover an area beyond a single hardware page.
5360 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5362 vm_offset_t virt = PHYS_TO_DMAP(phys);
5364 bzero((char *)virt + off, size);
5370 * Copy the physical page from the source PA to the target PA.
5371 * This function may be called from an interrupt. No locking
5375 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5377 vm_offset_t src_virt, dst_virt;
5379 src_virt = PHYS_TO_DMAP(src);
5380 dst_virt = PHYS_TO_DMAP(dst);
5381 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5385 * pmap_copy_page_frag:
5387 * Copy the physical page from the source PA to the target PA.
5388 * This function may be called from an interrupt. No locking
5392 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5394 vm_offset_t src_virt, dst_virt;
5396 src_virt = PHYS_TO_DMAP(src);
5397 dst_virt = PHYS_TO_DMAP(dst);
5399 bcopy((char *)src_virt + (src & PAGE_MASK),
5400 (char *)dst_virt + (dst & PAGE_MASK),
5405 * Remove all pages from specified address space this aids process exit
5406 * speeds. Also, this code may be special cased for the current process
5410 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5412 pmap_remove_noinval(pmap, sva, eva);
5417 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5418 * routines are inline, and a lot of things compile-time evaluate.
5422 pmap_testbit(vm_page_t m, int bit)
5426 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5429 * Nothing to do if all the mappings are already read-only.
5430 * The page's [M]odify bits have already been synchronized
5431 * to the vm_page_t and cleaned out.
5433 if (bit == PG_M_IDX && m->md.writeable_count == 0)
5437 * Iterate the mapping
5439 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5440 if (ipte & ipmap->pmap_bits[bit]) {
5444 } PMAP_PAGE_BACKING_DONE;
5449 * This routine is used to modify bits in ptes. Only one bit should be
5450 * specified. PG_RW requires special handling. This call works with
5451 * any sort of mapped page. PG_FICTITIOUS pages might not be optimal.
5453 * Caller must NOT hold any spin locks
5454 * Caller must hold (m) hard-busied
5456 * NOTE: When clearing PG_M we could also (not implemented) drop
5457 * through to the PG_RW code and clear PG_RW too, forcing
5458 * a fault on write to redetect PG_M for virtual kernels, but
5459 * it isn't necessary since virtual kernels invalidate the
5460 * pte when they clear the VPTE_M bit in their virtual page
5463 * NOTE: Does not re-dirty the page when clearing only PG_M.
5465 * NOTE: Because we do not lock the pv, *pte can be in a state of
5466 * flux. Despite this the value of *pte is still somewhat
5467 * related while we hold the vm_page spin lock.
5469 * *pte can be zero due to this race. Since we are clearing
5470 * bits we basically do no harm when this race occurs.
5474 pmap_clearbit(vm_page_t m, int bit_index)
5480 * Too early in the boot
5482 if (!pmap_initialized) {
5483 if (bit_index == PG_RW_IDX)
5484 vm_page_flag_clear(m, PG_WRITEABLE);
5489 * Being asked to clear other random bits, we don't track them
5490 * so we have to iterate.
5492 if (bit_index != PG_RW_IDX) {
5493 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5494 if (ipte & ipmap->pmap_bits[bit_index]) {
5495 atomic_clear_long(iptep,
5496 ipmap->pmap_bits[bit_index]);
5498 } PMAP_PAGE_BACKING_DONE;
5503 * Being asked to clear the RW bit.
5505 * Nothing to do if all the mappings are already read-only
5507 if (m->md.writeable_count == 0)
5511 * Iterate the mappings and check.
5513 retry = ticks + hz * 60;
5516 * Clear PG_RW. This also clears PG_M and marks the page dirty if
5519 * Since the caller holds the page hard-busied we can safely clear
5520 * PG_WRITEABLE, and callers expect us to for the PG_RW_IDX path.
5522 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5524 if ((ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5527 if ((ipte & ipmap->pmap_bits[PG_RW_IDX]) == 0)
5529 npte = ipte & ~(ipmap->pmap_bits[PG_RW_IDX] |
5530 ipmap->pmap_bits[PG_M_IDX]);
5531 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, npte))
5532 PMAP_PAGE_BACKING_RETRY;
5533 if (ipte & ipmap->pmap_bits[PG_M_IDX])
5537 * NOTE: m is not hard-busied so it is not safe to
5538 * clear PG_WRITEABLE on the 1->0 transition
5539 * against it being set in pmap_enter().
5541 * pmap_count and writeable_count are only applicable
5542 * to non-fictitious pages (PG_MANAGED_IDX from pte)
5544 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX])
5545 atomic_add_long(&m->md.writeable_count, -1);
5546 } PMAP_PAGE_BACKING_DONE;
5549 * writeable_count should be zero but it is possible to race
5550 * a pmap_enter() replacement (see 'oldm'). Once it is zero
5551 * it cannot become non-zero because the page is hard-busied.
5553 if (m->md.writeable_count != 0) {
5554 tsleep(&m->md.writeable_count, 0, "pgwab", 1);
5555 if (retry - ticks > 0)
5557 panic("pmap_remove_all: cannot return writeable_count "
5559 m->md.writeable_count);
5561 vm_page_flag_clear(m, PG_WRITEABLE);
5565 * Lower the permission for all mappings to a given page.
5567 * Page must be hard-busied by caller. Because the page is busied by the
5568 * caller, this should not be able to race a pmap_enter().
5571 pmap_page_protect(vm_page_t m, vm_prot_t prot)
5573 /* JG NX support? */
5574 if ((prot & VM_PROT_WRITE) == 0) {
5575 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
5577 * NOTE: pmap_clearbit(.. PG_RW) also clears
5578 * the PG_WRITEABLE flag in (m).
5580 pmap_clearbit(m, PG_RW_IDX);
5588 pmap_phys_address(vm_pindex_t ppn)
5590 return (x86_64_ptob(ppn));
5594 * Return a count of reference bits for a page, clearing those bits.
5595 * It is not necessary for every reference bit to be cleared, but it
5596 * is necessary that 0 only be returned when there are truly no
5597 * reference bits set.
5599 * XXX: The exact number of bits to check and clear is a matter that
5600 * should be tested and standardized at some point in the future for
5601 * optimal aging of shared pages.
5603 * This routine may not block.
5606 pmap_ts_referenced(vm_page_t m)
5611 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5613 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5614 if (ipte & ipmap->pmap_bits[PG_A_IDX]) {
5615 npte = ipte & ~ipmap->pmap_bits[PG_A_IDX];
5616 if (!atomic_cmpset_long(iptep, ipte, npte))
5617 PMAP_PAGE_BACKING_RETRY;
5622 } PMAP_PAGE_BACKING_DONE;
5629 * Return whether or not the specified physical page was modified
5630 * in any physical maps.
5633 pmap_is_modified(vm_page_t m)
5637 res = pmap_testbit(m, PG_M_IDX);
5642 * Clear the modify bit on the vm_page.
5644 * The page must be hard-busied.
5647 pmap_clear_modify(vm_page_t m)
5649 pmap_clearbit(m, PG_M_IDX);
5653 * pmap_clear_reference:
5655 * Clear the reference bit on the specified physical page.
5658 pmap_clear_reference(vm_page_t m)
5660 pmap_clearbit(m, PG_A_IDX);
5664 * Miscellaneous support routines follow
5669 x86_64_protection_init(void)
5675 * NX supported? (boot time loader.conf override only)
5677 * -1 Automatic (sets mode 1)
5679 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
5680 * 2 NX implemented for all cases
5682 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
5683 if ((amd_feature & AMDID_NX) == 0) {
5684 pmap_bits_default[PG_NX_IDX] = 0;
5686 } else if (pmap_nx_enable < 0) {
5687 pmap_nx_enable = 1; /* default to mode 1 (READ) */
5691 * 0 is basically read-only access, but also set the NX (no-execute)
5692 * bit when VM_PROT_EXECUTE is not specified.
5694 kp = protection_codes;
5695 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
5697 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
5699 * This case handled elsewhere
5703 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
5705 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
5707 if (pmap_nx_enable >= 1)
5708 *kp = pmap_bits_default[PG_NX_IDX];
5710 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
5711 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
5713 * Execute requires read access
5717 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
5718 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
5720 * Write without execute is RW|NX
5721 * (pmap_nx_enable mode >= 2)
5723 *kp = pmap_bits_default[PG_RW_IDX];
5724 if (pmap_nx_enable >= 2)
5725 *kp |= pmap_bits_default[PG_NX_IDX];
5727 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
5728 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
5730 * Write with execute is RW
5732 *kp = pmap_bits_default[PG_RW_IDX];
5740 * Map a set of physical memory pages into the kernel virtual
5741 * address space. Return a pointer to where it is mapped. This
5742 * routine is intended to be used for mapping device memory,
5745 * NOTE: We can't use pgeflag unless we invalidate the pages one at
5748 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
5749 * work whether the cpu supports PAT or not. The remaining PAT
5750 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
5754 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
5756 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5760 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
5762 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
5766 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5768 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5772 * Map a set of physical memory pages into the kernel virtual
5773 * address space. Return a pointer to where it is mapped. This
5774 * routine is intended to be used for mapping device memory,
5778 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
5780 vm_offset_t va, tmpva, offset;
5784 offset = pa & PAGE_MASK;
5785 size = roundup(offset + size, PAGE_SIZE);
5787 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
5789 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
5791 pa = pa & ~PAGE_MASK;
5792 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
5793 pte = vtopte(tmpva);
5795 kernel_pmap.pmap_bits[PG_RW_IDX] |
5796 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
5797 kernel_pmap.pmap_cache_bits[mode];
5798 tmpsize -= PAGE_SIZE;
5802 pmap_invalidate_range(&kernel_pmap, va, va + size);
5803 pmap_invalidate_cache_range(va, va + size);
5805 return ((void *)(va + offset));
5809 pmap_unmapdev(vm_offset_t va, vm_size_t size)
5811 vm_offset_t base, offset;
5813 base = va & ~PAGE_MASK;
5814 offset = va & PAGE_MASK;
5815 size = roundup(offset + size, PAGE_SIZE);
5816 pmap_qremove(va, size >> PAGE_SHIFT);
5817 kmem_free(&kernel_map, base, size);
5821 * Sets the memory attribute for the specified page.
5824 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5830 * If "m" is a normal page, update its direct mapping. This update
5831 * can be relied upon to perform any cache operations that are
5832 * required for data coherence.
5834 if ((m->flags & PG_FICTITIOUS) == 0)
5835 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
5839 * Change the PAT attribute on an existing kernel memory map. Caller
5840 * must ensure that the virtual memory in question is not accessed
5841 * during the adjustment.
5844 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
5851 panic("pmap_change_attr: va is NULL");
5852 base = trunc_page(va);
5856 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
5857 kernel_pmap.pmap_cache_bits[mode];
5862 changed = 1; /* XXX: not optimal */
5865 * Flush CPU caches if required to make sure any data isn't cached that
5866 * shouldn't be, etc.
5869 pmap_invalidate_range(&kernel_pmap, base, va);
5870 pmap_invalidate_cache_range(base, va);
5875 * perform the pmap work for mincore
5878 pmap_mincore(pmap_t pmap, vm_offset_t addr)
5880 pt_entry_t *ptep, pte;
5884 ptep = pmap_pte(pmap, addr);
5886 if (ptep && (pte = *ptep) != 0) {
5889 val = MINCORE_INCORE;
5890 pa = pte & PG_FRAME;
5891 if (pte & pmap->pmap_bits[PG_MANAGED_IDX])
5892 m = PHYS_TO_VM_PAGE(pa);
5899 if (pte & pmap->pmap_bits[PG_M_IDX])
5900 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
5903 * Modified by someone
5905 else if (m && (m->dirty || pmap_is_modified(m)))
5906 val |= MINCORE_MODIFIED_OTHER;
5909 * Referenced by us, or someone else.
5911 if (pte & pmap->pmap_bits[PG_A_IDX]) {
5912 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
5913 } else if (m && ((m->flags & PG_REFERENCED) ||
5914 pmap_ts_referenced(m))) {
5915 val |= MINCORE_REFERENCED_OTHER;
5916 vm_page_flag_set(m, PG_REFERENCED);
5923 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
5924 * vmspace will be ref'd and the old one will be deref'd.
5926 * The vmspace for all lwps associated with the process will be adjusted
5927 * and cr3 will be reloaded if any lwp is the current lwp.
5929 * The process must hold the vmspace->vm_map.token for oldvm and newvm
5932 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
5934 struct vmspace *oldvm;
5937 oldvm = p->p_vmspace;
5938 if (oldvm != newvm) {
5941 p->p_vmspace = newvm;
5942 KKASSERT(p->p_nthreads == 1);
5943 lp = RB_ROOT(&p->p_lwp_tree);
5944 pmap_setlwpvm(lp, newvm);
5951 * Set the vmspace for a LWP. The vmspace is almost universally set the
5952 * same as the process vmspace, but virtual kernels need to swap out contexts
5953 * on a per-lwp basis.
5955 * Caller does not necessarily hold any vmspace tokens. Caller must control
5956 * the lwp (typically be in the context of the lwp). We use a critical
5957 * section to protect against statclock and hardclock (statistics collection).
5960 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
5962 struct vmspace *oldvm;
5966 oldvm = lp->lwp_vmspace;
5968 if (oldvm != newvm) {
5971 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
5972 lp->lwp_vmspace = newvm;
5973 if (td->td_lwp == lp) {
5974 pmap = vmspace_pmap(newvm);
5975 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
5976 if (pmap->pm_active_lock & CPULOCK_EXCL)
5977 pmap_interlock_wait(newvm);
5978 #if defined(SWTCH_OPTIM_STATS)
5981 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
5982 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
5983 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
5984 td->td_pcb->pcb_cr3_iso =
5985 vtophys(pmap->pm_pml4_iso);
5986 td->td_pcb->pcb_flags |= PCB_ISOMMU;
5988 td->td_pcb->pcb_cr3_iso = 0;
5989 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
5991 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
5992 td->td_pcb->pcb_cr3 = KPML4phys;
5993 td->td_pcb->pcb_cr3_iso = 0;
5994 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
5996 panic("pmap_setlwpvm: unknown pmap type\n");
6000 * The MMU separation fields needs to be updated.
6001 * (it can't access the pcb directly from the
6002 * restricted user pmap).
6005 struct trampframe *tramp;
6007 tramp = &pscpu->trampoline;
6008 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6009 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6010 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6011 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6012 /* tr_pcb_rsp doesn't change */
6016 * In kernel-land we always use the normal PML4E
6017 * so the kernel is fully mapped and can also access
6020 load_cr3(td->td_pcb->pcb_cr3);
6021 pmap = vmspace_pmap(oldvm);
6022 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6030 * Called when switching to a locked pmap, used to interlock against pmaps
6031 * undergoing modifications to prevent us from activating the MMU for the
6032 * target pmap until all such modifications have completed. We have to do
6033 * this because the thread making the modifications has already set up its
6034 * SMP synchronization mask.
6036 * This function cannot sleep!
6041 pmap_interlock_wait(struct vmspace *vm)
6043 struct pmap *pmap = &vm->vm_pmap;
6045 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6047 KKASSERT(curthread->td_critcount >= 2);
6048 DEBUG_PUSH_INFO("pmap_interlock_wait");
6049 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6051 lwkt_process_ipiq();
6059 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6062 if ((obj == NULL) || (size < NBPDR) ||
6063 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6067 addr = roundup2(addr, NBPDR);
6072 * Used by kmalloc/kfree, page already exists at va
6075 pmap_kvtom(vm_offset_t va)
6077 pt_entry_t *ptep = vtopte(va);
6079 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6083 * Initialize machine-specific shared page directory support. This
6084 * is executed when a VM object is created.
6087 pmap_object_init(vm_object_t object)
6092 * Clean up machine-specific shared page directory support. This
6093 * is executed when a VM object is destroyed.
6096 pmap_object_free(vm_object_t object)
6101 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6102 * VM page and issue a pginfo->callback.
6106 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6107 vm_pindex_t *pte_placemark,
6108 pv_entry_t pt_pv, vm_offset_t va,
6109 pt_entry_t *ptep, void *arg)
6111 struct pmap_pgscan_info *pginfo = arg;
6118 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
6120 * Try to busy the page while we hold the pte_placemark locked.
6122 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6123 if (vm_page_busy_try(m, TRUE) == 0) {
6124 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6126 * The callback is issued with the pt_pv
6129 pv_placemarker_wakeup(pmap, pte_placemark);
6131 vm_page_wire_quick(pt_pv->pv_m);
6134 if (pginfo->callback(pginfo, va, m) < 0)
6138 if (vm_page_unwire_quick(pt_pv->pv_m)) {
6139 panic("pmap_pgscan: bad wire_"
6145 pv_placemarker_wakeup(pmap, pte_placemark);
6148 ++pginfo->busycount;
6149 pv_placemarker_wakeup(pmap, pte_placemark);
6153 * Shared page table or unmanaged page (sharept or !sharept)
6155 pv_placemarker_wakeup(pmap, pte_placemark);
6160 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6162 struct pmap_scan_info info;
6164 pginfo->offset = pginfo->beg_addr;
6165 info.pmap = pginfo->pmap;
6166 info.sva = pginfo->beg_addr;
6167 info.eva = pginfo->end_addr;
6168 info.func = pmap_pgscan_callback;
6170 pmap_scan(&info, 0);
6172 pginfo->offset = pginfo->end_addr;
6176 * Wait for a placemarker that we do not own to clear. The placemarker
6177 * in question is not necessarily set to the pindex we want, we may have
6178 * to wait on the element because we want to reserve it ourselves.
6180 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6181 * PM_NOPLACEMARK, so it does not interfere with placemarks
6182 * which have already been woken up.
6184 * NOTE: This routine is called without the pmap spin-lock and so can
6185 * race changes to *pmark. Due to the sensitivity of the routine
6186 * to possible MULTIPLE interactions from other cpus, and the
6187 * overloading of the WAKEUP bit on PM_NOPLACEMARK, we have to
6188 * use a cmpset loop to avoid a race that might cause the WAKEUP
6191 * Caller is expected to retry its operation upon return.
6195 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6201 while (mark != PM_NOPLACEMARK) {
6202 tsleep_interlock(pmark, 0);
6203 if (atomic_fcmpset_long(pmark, &mark,
6204 mark | PM_PLACEMARK_WAKEUP)) {
6205 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6212 * Wakeup a placemarker that we own. Replace the entry with
6213 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6217 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6221 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6222 KKASSERT(pindex != PM_NOPLACEMARK);
6223 if (pindex & PM_PLACEMARK_WAKEUP)