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];
164 * Backing scan macros. Note that in the use case 'ipte' is only a tentitive
165 * value and must be validated by a pmap_inval_smp_cmpset*() or equivalent
168 * NOTE: cpu_ccfence() is required to prevent excessive optmization of
169 * of the (ipte) variable.
171 * NOTE: We don't bother locking the backing object if it isn't mapped
172 * to anything (backing_list is empty).
174 * NOTE: For now guarantee an interlock via iobj->backing_lk if the
175 * object exists and do not shortcut the lock by checking to see
176 * if the list is empty first.
178 #define PMAP_PAGE_BACKING_SCAN(m, match_pmap, ipmap, iptep, ipte, iva) \
180 vm_object_t iobj = m->object; \
181 vm_map_backing_t iba, next_ba; \
182 struct pmap *ipmap; \
186 vm_pindex_t ipindex_start; \
187 vm_pindex_t ipindex_end; \
189 lockmgr(&iobj->backing_lk, LK_SHARED); \
190 next_ba = TAILQ_FIRST(&iobj->backing_list); \
191 while ((iba = next_ba) != NULL) { \
192 next_ba = TAILQ_NEXT(iba, entry); \
194 if (match_pmap && ipmap != match_pmap) \
196 ipindex_start = iba->offset >> PAGE_SHIFT; \
197 ipindex_end = ipindex_start + \
198 ((iba->end - iba->start) >> PAGE_SHIFT); \
199 if (m->pindex < ipindex_start || \
200 m->pindex >= ipindex_end) { \
204 ((m->pindex - ipindex_start) << PAGE_SHIFT); \
205 iptep = pmap_pte(ipmap, iva); \
210 if (m->phys_addr != (ipte & PG_FRAME)) \
213 #define PMAP_PAGE_BACKING_RETRY \
219 #define PMAP_PAGE_BACKING_DONE \
221 lockmgr(&iobj->backing_lk, LK_RELEASE); \
224 struct pmap kernel_pmap;
225 struct pmap iso_pmap;
227 vm_paddr_t avail_start; /* PA of first available physical page */
228 vm_paddr_t avail_end; /* PA of last available physical page */
229 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
230 vm_offset_t virtual2_end;
231 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
232 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
233 vm_offset_t KvaStart; /* VA start of KVA space */
234 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
235 vm_offset_t KvaSize; /* max size of kernel virtual address space */
236 vm_offset_t DMapMaxAddress;
237 /* Has pmap_init completed? */
238 __read_frequently static boolean_t pmap_initialized = FALSE;
239 //static int pgeflag; /* PG_G or-in */
243 static vm_paddr_t dmaplimit;
244 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
246 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
247 static pt_entry_t pat_pde_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
249 static uint64_t KPTbase;
250 static uint64_t KPTphys;
251 static uint64_t KPDphys; /* phys addr of kernel level 2 */
252 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
253 uint64_t KPDPphys; /* phys addr of kernel level 3 */
254 uint64_t KPML4phys; /* phys addr of kernel level 4 */
256 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
257 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
260 * Data for the pv entry allocation mechanism
262 __read_mostly static vm_zone_t pvzone;
263 __read_mostly static int pmap_pagedaemon_waken = 0;
264 static struct vm_zone pvzone_store;
265 static struct pv_entry *pvinit;
268 * All those kernel PT submaps that BSD is so fond of
270 pt_entry_t *CMAP1 = NULL, *ptmmap;
271 caddr_t CADDR1 = NULL, ptvmmap = NULL;
272 static pt_entry_t *msgbufmap;
273 struct msgbuf *msgbufp=NULL;
276 * PMAP default PG_* bits. Needed to be able to add
277 * EPT/NPT pagetable pmap_bits for the VMM module
279 __read_frequently uint64_t pmap_bits_default[] = {
280 REGULAR_PMAP, /* TYPE_IDX 0 */
281 X86_PG_V, /* PG_V_IDX 1 */
282 X86_PG_RW, /* PG_RW_IDX 2 */
283 X86_PG_U, /* PG_U_IDX 3 */
284 X86_PG_A, /* PG_A_IDX 4 */
285 X86_PG_M, /* PG_M_IDX 5 */
286 X86_PG_PS, /* PG_PS_IDX3 6 */
287 X86_PG_G, /* PG_G_IDX 7 */
288 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
289 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
290 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
291 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
292 X86_PG_NX, /* PG_NX_IDX 12 */
298 static pt_entry_t *pt_crashdumpmap;
299 static caddr_t crashdumpmap;
301 static int pmap_debug = 0;
302 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
303 &pmap_debug, 0, "Debug pmap's");
305 static int pmap_enter_debug = 0;
306 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
307 &pmap_enter_debug, 0, "Debug pmap_enter's");
309 static int pmap_yield_count = 64;
310 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
311 &pmap_yield_count, 0, "Yield during init_pt/release");
312 int pmap_fast_kernel_cpusync = 0;
313 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
314 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
315 int pmap_dynamic_delete = 0;
316 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
317 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
318 int pmap_lock_delay = 100;
319 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
320 &pmap_lock_delay, 0, "Spin loops");
321 static int meltdown_mitigation = -1;
322 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
323 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
324 &meltdown_mitigation, 0, "Userland pmap isolation");
326 static int pmap_nx_enable = -1; /* -1 = auto */
327 /* needs manual TUNABLE in early probe, see below */
328 SYSCTL_INT(_machdep, OID_AUTO, pmap_nx_enable, CTLFLAG_RD,
330 "no-execute support (0=disabled, 1=w/READ, 2=w/READ & WRITE)");
332 static int pmap_pv_debug = 50;
333 SYSCTL_INT(_machdep, OID_AUTO, pmap_pv_debug, CTLFLAG_RW,
334 &pmap_pv_debug, 0, "");
336 static long vm_pmap_pv_entries;
337 SYSCTL_LONG(_vm, OID_AUTO, pmap_pv_entries, CTLFLAG_RD,
338 &vm_pmap_pv_entries, 0, "");
340 /* Standard user access funtions */
341 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
343 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
344 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
345 extern int std_fubyte (const uint8_t *base);
346 extern int std_subyte (uint8_t *base, uint8_t byte);
347 extern int32_t std_fuword32 (const uint32_t *base);
348 extern int64_t std_fuword64 (const uint64_t *base);
349 extern int std_suword64 (uint64_t *base, uint64_t word);
350 extern int std_suword32 (uint32_t *base, int word);
351 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
352 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
353 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
354 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
357 static void pv_hold(pv_entry_t pv);
359 static int _pv_hold_try(pv_entry_t pv
361 static void pv_drop(pv_entry_t pv);
362 static void _pv_lock(pv_entry_t pv
364 static void pv_unlock(pv_entry_t pv);
365 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
367 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
369 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
370 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
371 vm_pindex_t **pmarkp, int *errorp);
372 static void pv_put(pv_entry_t pv);
373 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
374 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
376 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
377 pmap_inval_bulk_t *bulk, int destroy);
378 static vm_page_t pmap_remove_pv_page(pv_entry_t pv, int clrpgbits);
379 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
380 pmap_inval_bulk_t *bulk);
382 struct pmap_scan_info;
383 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
384 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
385 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
386 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
387 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
388 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
390 static void x86_64_protection_init (void);
391 static void create_pagetables(vm_paddr_t *firstaddr);
392 static void pmap_remove_all (vm_page_t m);
393 static boolean_t pmap_testbit (vm_page_t m, int bit);
395 static pt_entry_t *pmap_pte_quick (pmap_t pmap, vm_offset_t va);
396 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
398 static void pmap_pinit_defaults(struct pmap *pmap);
399 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
400 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
403 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
405 if (pv1->pv_pindex < pv2->pv_pindex)
407 if (pv1->pv_pindex > pv2->pv_pindex)
412 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
413 pv_entry_compare, vm_pindex_t, pv_pindex);
416 * Keep track of pages in the pmap. The procedure is handed
417 * the vm_page->md.pmap_count value prior to an increment or
420 * t_arm - Active real memory
421 * t_avm - Active virtual memory
422 * t_armshr - Active real memory that is also shared
423 * t_avmshr - Active virtual memory that is also shared
425 * NOTE: At the moment t_avm is effectively just the same as t_arm.
429 pmap_page_stats_adding(long prev_count)
431 globaldata_t gd = mycpu;
433 if (prev_count == 0) {
434 ++gd->gd_vmtotal.t_arm;
435 ++gd->gd_vmtotal.t_avm;
436 } else if (prev_count == 1) {
437 ++gd->gd_vmtotal.t_armshr;
438 ++gd->gd_vmtotal.t_avmshr;
440 ++gd->gd_vmtotal.t_avmshr;
446 pmap_page_stats_deleting(long prev_count)
448 globaldata_t gd = mycpu;
450 if (prev_count == 1) {
451 --gd->gd_vmtotal.t_arm;
452 --gd->gd_vmtotal.t_avm;
453 } else if (prev_count == 2) {
454 --gd->gd_vmtotal.t_armshr;
455 --gd->gd_vmtotal.t_avmshr;
457 --gd->gd_vmtotal.t_avmshr;
462 * We have removed a managed pte. The page might not be hard or soft-busied
463 * at this point so we have to be careful.
465 * If advanced mode is enabled we can clear PG_MAPPED/WRITEABLE only if
466 * MAPPEDMULTI is not set. This must be done atomically against possible
467 * concurrent pmap_enter()s occurring at the same time. If MULTI is set
468 * then the kernel may have to call vm_page_protect() later on to clean
469 * the bits up. This is particularly important for kernel_map/kernel_object
470 * mappings due to the expense of scanning the kernel_object's vm_backing's.
472 * If advanced mode is not enabled we update our tracking counts and
473 * synchronize PG_MAPPED/WRITEABLE later on in pmap_mapped_sync().
477 pmap_removed_pte(vm_page_t m, pt_entry_t pte)
485 while ((flags & PG_MAPPEDMULTI) == 0) {
486 nflags = flags & ~(PG_MAPPED | PG_WRITEABLE);
487 if (atomic_fcmpset_int(&m->flags, &flags, nflags))
491 if (pte & pmap->pmap_bits[PG_RW_IDX])
492 atomic_add_long(&p->md.writeable_count, -1);
493 pmap_page_stats_deleting(atomic_fetchadd_long(&p->md.pmap_count, -1));
498 * Move the kernel virtual free pointer to the next
499 * 2MB. This is used to help improve performance
500 * by using a large (2MB) page for much of the kernel
501 * (.text, .data, .bss)
505 pmap_kmem_choose(vm_offset_t addr)
507 vm_offset_t newaddr = addr;
509 newaddr = roundup2(addr, NBPDR);
514 * Returns the pindex of a page table entry (representing a terminal page).
515 * There are NUPTE_TOTAL page table entries possible (a huge number)
517 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
518 * We want to properly translate negative KVAs.
522 pmap_pte_pindex(vm_offset_t va)
524 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
528 * Returns the pindex of a page table.
532 pmap_pt_pindex(vm_offset_t va)
534 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
538 * Returns the pindex of a page directory.
542 pmap_pd_pindex(vm_offset_t va)
544 return (NUPTE_TOTAL + NUPT_TOTAL +
545 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
550 pmap_pdp_pindex(vm_offset_t va)
552 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
553 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
558 pmap_pml4_pindex(void)
560 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
564 * Return various clipped indexes for a given VA
566 * Returns the index of a pt in a page directory, representing a page
571 pmap_pt_index(vm_offset_t va)
573 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
577 * Returns the index of a pd in a page directory page, representing a page
582 pmap_pd_index(vm_offset_t va)
584 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
588 * Returns the index of a pdp in the pml4 table, representing a page
593 pmap_pdp_index(vm_offset_t va)
595 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
599 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
600 * the PT layer. This will speed up core pmap operations considerably.
601 * We also cache the PTE layer to (hopefully) improve relative lookup
604 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
605 * must be in a known associated state (typically by being locked when
606 * the pmap spinlock isn't held). We allow the race for that case.
608 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
609 * cpu_ccfence() to prevent compiler optimizations from reloading the
614 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
616 if (pindex < pmap_pt_pindex(0)) {
618 } else if (pindex < pmap_pd_pindex(0)) {
619 pmap->pm_pvhint_pt = pv;
624 * Locate the requested pt_entry
628 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
632 if (pindex < pmap_pt_pindex(0))
635 if (pindex < pmap_pd_pindex(0))
636 pv = pmap->pm_pvhint_pt;
640 if (pv == NULL || pv->pv_pmap != pmap) {
641 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
643 pv_cache(pmap, pv, pindex);
644 } else if (pv->pv_pindex != pindex) {
645 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
648 pv_cache(pmap, pv, pindex);
651 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
659 * Super fast pmap_pte routine best used when scanning the pv lists.
660 * This eliminates many course-grained invltlb calls. Note that many of
661 * the pv list scans are across different pmaps and it is very wasteful
662 * to do an entire invltlb when checking a single mapping.
664 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
668 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
670 return pmap_pte(pmap, va);
674 * The placemarker hash must be broken up into four zones so lock
675 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
677 * Placemarkers are used to 'lock' page table indices that do not have
678 * a pv_entry. This allows the pmap to support managed and unmanaged
679 * pages and shared page tables.
681 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
685 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
689 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
691 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
693 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
694 hi = PM_PLACE_BASE << 1;
695 else /* zone 3 - PDP (and PML4E) */
696 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
697 hi += pindex & (PM_PLACE_BASE - 1);
699 return (&pmap->pm_placemarks[hi]);
704 * Generic procedure to index a pte from a pt, pd, or pdp.
706 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
707 * a page table page index but is instead of PV lookup index.
711 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
715 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
716 return(&pte[pindex]);
720 * Return pointer to PDP slot in the PML4
724 pmap_pdp(pmap_t pmap, vm_offset_t va)
726 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
730 * Return pointer to PD slot in the PDP given a pointer to the PDP
734 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
738 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
739 return (&pd[pmap_pd_index(va)]);
743 * Return pointer to PD slot in the PDP.
747 pmap_pd(pmap_t pmap, vm_offset_t va)
751 pdp = pmap_pdp(pmap, va);
752 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
754 return (pmap_pdp_to_pd(*pdp, va));
758 * Return pointer to PT slot in the PD given a pointer to the PD
762 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
766 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
767 return (&pt[pmap_pt_index(va)]);
771 * Return pointer to PT slot in the PD
773 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
774 * so we cannot lookup the PD via the PDP. Instead we
775 * must look it up via the pmap.
779 pmap_pt(pmap_t pmap, vm_offset_t va)
783 vm_pindex_t pd_pindex;
786 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
787 pd_pindex = pmap_pd_pindex(va);
788 spin_lock_shared(&pmap->pm_spin);
789 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
790 if (pv == NULL || pv->pv_m == NULL) {
791 spin_unlock_shared(&pmap->pm_spin);
794 phys = VM_PAGE_TO_PHYS(pv->pv_m);
795 spin_unlock_shared(&pmap->pm_spin);
796 return (pmap_pd_to_pt(phys, va));
798 pd = pmap_pd(pmap, va);
799 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
801 return (pmap_pd_to_pt(*pd, va));
806 * Return pointer to PTE slot in the PT given a pointer to the PT
810 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
814 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
815 return (&pte[pmap_pte_index(va)]);
819 * Return pointer to PTE slot in the PT
823 pmap_pte(pmap_t pmap, vm_offset_t va)
827 pt = pmap_pt(pmap, va);
828 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
830 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
831 return ((pt_entry_t *)pt);
832 return (pmap_pt_to_pte(*pt, va));
836 * Return address of PT slot in PD (KVM only)
838 * Cannot be used for user page tables because it might interfere with
839 * the shared page-table-page optimization (pmap_mmu_optimize).
843 vtopt(vm_offset_t va)
845 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
846 NPML4EPGSHIFT)) - 1);
848 return (PDmap + ((va >> PDRSHIFT) & mask));
852 * KVM - return address of PTE slot in PT
856 vtopte(vm_offset_t va)
858 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
859 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
861 return (PTmap + ((va >> PAGE_SHIFT) & mask));
865 * Returns the physical address translation from va for a user address.
866 * (vm_paddr_t)-1 is returned on failure.
869 uservtophys(vm_offset_t va)
871 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
872 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
877 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
879 if (va < VM_MAX_USER_ADDRESS) {
880 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
881 if (pte & pmap->pmap_bits[PG_V_IDX])
882 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
888 allocpages(vm_paddr_t *firstaddr, long n)
893 bzero((void *)ret, n * PAGE_SIZE);
894 *firstaddr += n * PAGE_SIZE;
900 create_pagetables(vm_paddr_t *firstaddr)
902 long i; /* must be 64 bits */
909 * We are running (mostly) V=P at this point
911 * Calculate how many 1GB PD entries in our PDP pages are needed
912 * for the DMAP. This is only allocated if the system does not
913 * support 1GB pages. Otherwise ndmpdp is simply a count of
914 * the number of 1G terminal entries in our PDP pages are needed.
916 * NOTE: Maxmem is in pages
918 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
919 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
921 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
922 DMapMaxAddress = DMAP_MIN_ADDRESS +
923 ((ndmpdp * NPDEPG) << PDRSHIFT);
926 * Starting at KERNBASE - map all 2G worth of page table pages.
927 * KERNBASE is offset -2G from the end of kvm. This will accomodate
928 * all KVM allocations above KERNBASE, including the SYSMAPs below.
930 * We do this by allocating 2*512 PT pages. Each PT page can map
931 * 2MB, for 2GB total.
933 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
936 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
937 * Calculate how many page table pages we need to preallocate
938 * for early vm_map allocations.
940 * A few extra won't hurt, they will get used up in the running
946 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
947 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
948 nkpt_phys += 128; /* a few extra */
951 * The highest value nkpd_phys can be set to is
952 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
954 * Doing so would cause all PD pages to be pre-populated for
955 * a maximal KVM space (approximately 16*512 pages, or 32MB.
956 * We can save memory by not doing this.
958 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
963 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
964 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
966 * Only allocate enough PD pages
967 * NOTE: We allocate all kernel PD pages up-front, typically
968 * ~511G of KVM, requiring 511 PD pages.
970 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
971 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
972 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
973 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
974 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
977 * Alloc PD pages for the area starting at KERNBASE.
979 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
982 * Stuff for our DMAP. Use 2MB pages even when 1GB pages
983 * are available in order to allow APU code to adjust page
984 * attributes on a fixed grain (see pmap_change_attr()).
986 DMPDPphys = allocpages(firstaddr, NDMPML4E);
988 DMPDphys = allocpages(firstaddr, ndmpdp);
990 if ((amd_feature & AMDID_PAGE1GB) == 0)
991 DMPDphys = allocpages(firstaddr, ndmpdp);
993 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
996 * Fill in the underlying page table pages for the area around
997 * KERNBASE. This remaps low physical memory to KERNBASE.
999 * Read-only from zero to physfree
1000 * XXX not fully used, underneath 2M pages
1002 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
1003 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
1004 ((pt_entry_t *)KPTbase)[i] |=
1005 pmap_bits_default[PG_RW_IDX] |
1006 pmap_bits_default[PG_V_IDX] |
1007 pmap_bits_default[PG_G_IDX];
1011 * Now map the initial kernel page tables. One block of page
1012 * tables is placed at the beginning of kernel virtual memory,
1013 * and another block is placed at KERNBASE to map the kernel binary,
1014 * data, bss, and initial pre-allocations.
1016 for (i = 0; i < nkpt_base; i++) {
1017 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
1018 ((pd_entry_t *)KPDbase)[i] |=
1019 pmap_bits_default[PG_RW_IDX] |
1020 pmap_bits_default[PG_V_IDX];
1022 for (i = 0; i < nkpt_phys; i++) {
1023 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
1024 ((pd_entry_t *)KPDphys)[i] |=
1025 pmap_bits_default[PG_RW_IDX] |
1026 pmap_bits_default[PG_V_IDX];
1030 * Map from zero to end of allocations using 2M pages as an
1031 * optimization. This will bypass some of the KPTBase pages
1032 * above in the KERNBASE area.
1034 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
1035 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
1036 ((pd_entry_t *)KPDbase)[i] |=
1037 pmap_bits_default[PG_RW_IDX] |
1038 pmap_bits_default[PG_V_IDX] |
1039 pmap_bits_default[PG_PS_IDX] |
1040 pmap_bits_default[PG_G_IDX];
1044 * Load PD addresses into the PDP pages for primary KVA space to
1045 * cover existing page tables. PD's for KERNBASE are handled in
1048 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
1050 for (i = 0; i < nkpd_phys; i++) {
1051 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
1052 KPDphys + (i << PAGE_SHIFT);
1053 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
1054 pmap_bits_default[PG_RW_IDX] |
1055 pmap_bits_default[PG_V_IDX] |
1056 pmap_bits_default[PG_A_IDX];
1060 * Load PDs for KERNBASE to the end
1062 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
1063 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
1064 ((pdp_entry_t *)KPDPphys)[i + j] =
1065 KPDbase + (j << PAGE_SHIFT);
1066 ((pdp_entry_t *)KPDPphys)[i + j] |=
1067 pmap_bits_default[PG_RW_IDX] |
1068 pmap_bits_default[PG_V_IDX] |
1069 pmap_bits_default[PG_A_IDX];
1073 * Now set up the direct map space using either 2MB or 1GB pages
1074 * Preset PG_M and PG_A because demotion expects it.
1076 * When filling in entries in the PD pages make sure any excess
1077 * entries are set to zero as we allocated enough PD pages
1079 * Stuff for our DMAP. Use 2MB pages even when 1GB pages
1080 * are available in order to allow APU code to adjust page
1081 * attributes on a fixed grain (see pmap_change_attr()).
1084 if ((amd_feature & AMDID_PAGE1GB) == 0)
1090 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1091 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1092 ((pd_entry_t *)DMPDphys)[i] |=
1093 pmap_bits_default[PG_RW_IDX] |
1094 pmap_bits_default[PG_V_IDX] |
1095 pmap_bits_default[PG_PS_IDX] |
1096 pmap_bits_default[PG_G_IDX] |
1097 pmap_bits_default[PG_M_IDX] |
1098 pmap_bits_default[PG_A_IDX];
1102 * And the direct map space's PDP
1104 for (i = 0; i < ndmpdp; i++) {
1105 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1107 ((pdp_entry_t *)DMPDPphys)[i] |=
1108 pmap_bits_default[PG_RW_IDX] |
1109 pmap_bits_default[PG_V_IDX] |
1110 pmap_bits_default[PG_A_IDX];
1118 for (i = 0; i < ndmpdp; i++) {
1119 ((pdp_entry_t *)DMPDPphys)[i] =
1120 (vm_paddr_t)i << PDPSHIFT;
1121 ((pdp_entry_t *)DMPDPphys)[i] |=
1122 pmap_bits_default[PG_RW_IDX] |
1123 pmap_bits_default[PG_V_IDX] |
1124 pmap_bits_default[PG_PS_IDX] |
1125 pmap_bits_default[PG_G_IDX] |
1126 pmap_bits_default[PG_M_IDX] |
1127 pmap_bits_default[PG_A_IDX];
1132 /* And recursively map PML4 to itself in order to get PTmap */
1133 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1134 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1135 pmap_bits_default[PG_RW_IDX] |
1136 pmap_bits_default[PG_V_IDX] |
1137 pmap_bits_default[PG_A_IDX];
1140 * Connect the Direct Map slots up to the PML4
1142 for (j = 0; j < NDMPML4E; ++j) {
1143 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1144 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1145 pmap_bits_default[PG_RW_IDX] |
1146 pmap_bits_default[PG_V_IDX] |
1147 pmap_bits_default[PG_A_IDX];
1151 * Connect the KVA slot up to the PML4
1153 for (j = 0; j < NKPML4E; ++j) {
1154 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1155 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1156 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1157 pmap_bits_default[PG_RW_IDX] |
1158 pmap_bits_default[PG_V_IDX] |
1159 pmap_bits_default[PG_A_IDX];
1166 * Bootstrap the system enough to run with virtual memory.
1168 * On x86_64 this is called after mapping has already been enabled
1169 * and just syncs the pmap module with what has already been done.
1170 * [We can't call it easily with mapping off since the kernel is not
1171 * mapped with PA == VA, hence we would have to relocate every address
1172 * from the linked base (virtual) address "KERNBASE" to the actual
1173 * (physical) address starting relative to 0]
1176 pmap_bootstrap(vm_paddr_t *firstaddr)
1182 KvaStart = VM_MIN_KERNEL_ADDRESS;
1183 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1184 KvaSize = KvaEnd - KvaStart;
1186 avail_start = *firstaddr;
1189 * Create an initial set of page tables to run the kernel in.
1191 create_pagetables(firstaddr);
1193 virtual2_start = KvaStart;
1194 virtual2_end = PTOV_OFFSET;
1196 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1197 virtual_start = pmap_kmem_choose(virtual_start);
1199 virtual_end = VM_MAX_KERNEL_ADDRESS;
1201 /* XXX do %cr0 as well */
1202 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1203 load_cr3(KPML4phys);
1206 * Initialize protection array.
1208 x86_64_protection_init();
1211 * The kernel's pmap is statically allocated so we don't have to use
1212 * pmap_create, which is unlikely to work correctly at this part of
1213 * the boot sequence (XXX and which no longer exists).
1215 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1216 kernel_pmap.pm_count = 1;
1217 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1218 RB_INIT(&kernel_pmap.pm_pvroot);
1219 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1220 for (i = 0; i < PM_PLACEMARKS; ++i)
1221 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1224 * Reserve some special page table entries/VA space for temporary
1227 #define SYSMAP(c, p, v, n) \
1228 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1234 * CMAP1/CMAP2 are used for zeroing and copying pages.
1236 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1241 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1244 * ptvmmap is used for reading arbitrary physical pages via
1247 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1250 * msgbufp is used to map the system message buffer.
1251 * XXX msgbufmap is not used.
1253 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1254 atop(round_page(MSGBUF_SIZE)))
1257 virtual_start = pmap_kmem_choose(virtual_start);
1262 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1263 * cases rather then invl1pg. Actually, I don't even know why it
1264 * works under UP because self-referential page table mappings
1270 /* Initialize the PAT MSR */
1272 pmap_pinit_defaults(&kernel_pmap);
1274 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1275 &pmap_fast_kernel_cpusync);
1280 * Setup the PAT MSR.
1290 * Default values mapping PATi,PCD,PWT bits at system reset.
1291 * The default values effectively ignore the PATi bit by
1292 * repeating the encodings for 0-3 in 4-7, and map the PCD
1293 * and PWT bit combinations to the expected PAT types.
1295 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1296 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1297 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1298 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1299 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1300 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1301 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1302 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1303 pat_pte_index[PAT_WRITE_BACK] = 0;
1304 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1305 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1306 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1307 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1308 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1310 if (cpu_feature & CPUID_PAT) {
1312 * If we support the PAT then set-up entries for
1313 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1316 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1317 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1318 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1319 PAT_VALUE(6, PAT_WRITE_COMBINING);
1320 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1321 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1324 * Then enable the PAT
1329 load_cr4(cr4 & ~CR4_PGE);
1331 /* Disable caches (CD = 1, NW = 0). */
1333 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1335 /* Flushes caches and TLBs. */
1339 /* Update PAT and index table. */
1340 wrmsr(MSR_PAT, pat_msr);
1342 /* Flush caches and TLBs again. */
1346 /* Restore caches and PGE. */
1352 for (i = 0; i < 8; ++i) {
1355 pte = pat_pte_index[i];
1356 if (pte & X86_PG_PTE_PAT) {
1357 pte &= ~X86_PG_PTE_PAT;
1358 pte |= X86_PG_PDE_PAT;
1360 pat_pde_index[i] = pte;
1365 * Set 4mb pdir for mp startup
1370 if (cpu_feature & CPUID_PSE) {
1371 load_cr4(rcr4() | CR4_PSE);
1372 if (mycpu->gd_cpuid == 0) /* only on BSP */
1377 * Check for SMAP support and enable if available. Must be done
1378 * after cr3 is loaded, and on all cores.
1380 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1381 load_cr4(rcr4() | CR4_SMAP);
1383 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1384 load_cr4(rcr4() | CR4_SMEP);
1389 * SMAP is just a processor flag, but SMEP can only be enabled
1390 * and disabled via CR4. We still use the processor flag to
1391 * disable SMAP because the page-fault/trap code checks it, in
1392 * order to allow a page-fault to actually occur.
1395 smap_smep_disable(void)
1398 * disable SMAP. This also bypasses a software failsafe check
1399 * in the trap() code.
1404 * Also needed to bypass a software failsafe check in the trap()
1405 * code and allow the userspace address fault from kernel mode
1408 * Note that This will not reload %rip because pcb_onfault_rsp will
1409 * not match. Just setting it to non-NULL is sufficient to bypass
1412 curthread->td_pcb->pcb_onfault = (void *)1;
1415 * Disable SMEP (requires modifying cr4)
1417 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1418 load_cr4(rcr4() & ~CR4_SMEP);
1422 smap_smep_enable(void)
1424 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1425 load_cr4(rcr4() | CR4_SMEP);
1426 curthread->td_pcb->pcb_onfault = NULL;
1431 * Early initialization of the pmap module.
1433 * Called by vm_init, to initialize any structures that the pmap
1434 * system needs to map virtual memory. pmap_init has been enhanced to
1435 * support in a fairly consistant way, discontiguous physical memory.
1440 vm_pindex_t initial_pvs;
1444 * Allocate memory for random pmap data structures. Includes the
1447 for (i = 0; i < vm_page_array_size; i++) {
1450 m = &vm_page_array[i];
1451 #ifdef PMAP_ADVANCED
1452 m->md.interlock_count = 0;
1454 m->md.pmap_count = 0;
1455 m->md.writeable_count = 0;
1460 * init the pv free list
1462 initial_pvs = vm_page_array_size;
1463 if (initial_pvs < MINPV)
1464 initial_pvs = MINPV;
1465 pvzone = &pvzone_store;
1466 pvinit = (void *)kmem_alloc(&kernel_map,
1467 initial_pvs * sizeof (struct pv_entry),
1469 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1470 pvinit, initial_pvs);
1473 * Now it is safe to enable pv_table recording.
1475 pmap_initialized = TRUE;
1479 * Initialize the address space (zone) for the pv_entries. Set a
1480 * high water mark so that the system can recover from excessive
1481 * numbers of pv entries.
1483 * Also create the kernel page table template for isolated user
1486 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1487 static void pmap_init2_iso_pmap(void);
1489 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1495 vm_pindex_t entry_max;
1498 * We can significantly reduce pv_entry_max from historical
1499 * levels because pv_entry's are no longer use for PTEs at the
1500 * leafs. This prevents excessive pcpu caching on many-core
1501 * boxes (even with the further '/ 16' done in zinitna().
1503 * Remember, however, that processes can share physical pages
1504 * with each process still needing the pdp/pd/pt infrstructure
1505 * (which still use pv_entry's). And don't just assume that
1506 * every PT will be completely filled up. So don't make it
1509 entry_max = maxproc * 32 + vm_page_array_size / 16;
1510 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &entry_max);
1511 vm_pmap_pv_entries = entry_max;
1514 * Subtract out pages already installed in the zone (hack)
1516 if (entry_max <= MINPV)
1519 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1522 * Enable dynamic deletion of empty higher-level page table pages
1523 * by default only if system memory is < 8GB (use 7GB for slop).
1524 * This can save a little memory, but imposes significant
1525 * performance overhead for things like bulk builds, and for programs
1526 * which do a lot of memory mapping and memory unmapping.
1529 if (pmap_dynamic_delete < 0) {
1530 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1531 pmap_dynamic_delete = 1;
1533 pmap_dynamic_delete = 0;
1537 * Disable so vm_map_backing iterations do not race
1539 pmap_dynamic_delete = 0;
1542 * Automatic detection of Intel meltdown bug requiring user/kernel
1545 * Currently there are so many Intel cpu's impacted that its better
1546 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1547 * so the default is off for AMD.
1549 if (meltdown_mitigation < 0) {
1550 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1551 meltdown_mitigation = 1;
1553 meltdown_mitigation = 0;
1555 if (meltdown_mitigation) {
1556 kprintf("machdep.meltdown_mitigation enabled to "
1557 "protect against (mostly Intel) meltdown bug\n");
1558 kprintf("system call performance will be impacted\n");
1561 pmap_init2_iso_pmap();
1565 * Create the isolation pmap template. Once created, the template
1566 * is static and its PML4e entries are used to populate the
1567 * kernel portion of any isolated user pmaps.
1569 * Our isolation pmap must contain:
1570 * (1) trampoline area for all cpus
1571 * (2) common_tss area for all cpus (its part of the trampoline area now)
1572 * (3) IDT for all cpus
1573 * (4) GDT for all cpus
1576 pmap_init2_iso_pmap(void)
1581 kprintf("Initialize isolation pmap\n");
1584 * Try to use our normal API calls to make this easier. We have
1585 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1588 pmap_pinit(&iso_pmap);
1589 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1592 * Install areas needed by the cpu and trampoline.
1594 for (n = 0; n < ncpus; ++n) {
1595 struct privatespace *ps;
1597 ps = CPU_prvspace[n];
1598 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1599 sizeof(ps->trampoline));
1600 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1601 sizeof(ps->dblstack));
1602 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1603 sizeof(ps->dbgstack));
1604 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1605 sizeof(ps->common_tss));
1606 pmap_init_iso_range(r_idt_arr[n].rd_base,
1607 r_idt_arr[n].rd_limit + 1);
1609 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1610 pmap_init_iso_range((vm_offset_t)(int *)btext,
1611 (vm_offset_t)(int *)etext -
1612 (vm_offset_t)(int *)btext);
1615 kprintf("Dump iso_pmap:\n");
1616 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1617 kprintf("\nDump kernel_pmap:\n");
1618 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1623 * This adds a kernel virtual address range to the isolation pmap.
1626 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1635 kprintf("isolate %016jx-%016jx (%zd)\n",
1636 base, base + bytes, bytes);
1638 va = base & ~(vm_offset_t)PAGE_MASK;
1639 while (va < base + bytes) {
1640 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1641 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1642 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1643 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1645 * Use 2MB pages if possible
1648 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1649 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1654 * Otherwise use 4KB pages
1656 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1657 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1658 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1659 kernel_pmap.pmap_bits[PG_V_IDX] |
1660 kernel_pmap.pmap_bits[PG_A_IDX] |
1661 kernel_pmap.pmap_bits[PG_M_IDX];
1672 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1676 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1683 case 0: /* PML4e page, 512G entries */
1684 incr = (1LL << 48) / 512;
1686 case 1: /* PDP page, 1G entries */
1687 incr = (1LL << 39) / 512;
1689 case 2: /* PD page, 2MB entries */
1690 incr = (1LL << 30) / 512;
1692 case 3: /* PT page, 4KB entries */
1693 incr = (1LL << 21) / 512;
1701 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1702 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1703 for (i = 0; i < 512; ++i) {
1704 if (level == 0 && i == 128)
1705 base += 0xFFFF000000000000LLU;
1707 kprintf("%*.*s ", level * 4, level * 4, "");
1708 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1709 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1711 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1712 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1714 } else if (level == 3) {
1715 kprintf("va=%016jx %3d term %016jx\n",
1718 kprintf("va=%016jx %3d deep %016jx\n",
1720 dump_pmap(pmap, ptp[i], level + 1, base);
1730 * Typically used to initialize a fictitious page by vm/device_pager.c
1733 pmap_page_init(struct vm_page *m)
1736 #ifdef PMAP_ADVANCED
1737 m->md.interlock_count = 0;
1739 m->md.pmap_count = 0;
1740 m->md.writeable_count = 0;
1744 /***************************************************
1745 * Low level helper routines.....
1746 ***************************************************/
1749 * Extract the physical page address associated with the map/VA pair.
1750 * The page must be wired for this to work reliably.
1753 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1760 if (va >= VM_MAX_USER_ADDRESS) {
1762 * Kernel page directories might be direct-mapped and
1763 * there is typically no PV tracking of pte's
1767 pt = pmap_pt(pmap, va);
1768 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1769 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1770 rtval = *pt & PG_PS_FRAME;
1771 rtval |= va & PDRMASK;
1773 ptep = pmap_pt_to_pte(*pt, va);
1774 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1775 rtval = *ptep & PG_FRAME;
1776 rtval |= va & PAGE_MASK;
1784 * User pages currently do not direct-map the page directory
1785 * and some pages might not used managed PVs. But all PT's
1788 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1790 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1791 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1792 rtval = *ptep & PG_FRAME;
1793 rtval |= va & PAGE_MASK;
1796 *handlep = pt_pv; /* locked until done */
1799 } else if (handlep) {
1807 pmap_extract_done(void *handle)
1810 pv_put((pv_entry_t)handle);
1814 * Similar to extract but checks protections, SMP-friendly short-cut for
1815 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1816 * fall-through to the real fault code. Does not work with HVM page
1819 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1821 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1822 * page is busied (and not held).
1824 * If busyp is not NULL and this function sets *busyp to zero, the returned
1825 * page is held (and not busied).
1827 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1828 * returned page will be dirtied. If the pte is not already writable NULL
1829 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1830 * any COW will already have happened and that page can be written by the
1833 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1837 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1840 va < VM_MAX_USER_ADDRESS &&
1841 (pmap->pm_flags & PMAP_HVM) == 0) {
1849 req = pmap->pmap_bits[PG_V_IDX] |
1850 pmap->pmap_bits[PG_U_IDX];
1851 if (prot & VM_PROT_WRITE)
1852 req |= pmap->pmap_bits[PG_RW_IDX];
1854 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1857 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1858 if ((*ptep & req) != req) {
1862 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1863 if (pte_pv && error == 0) {
1865 if (prot & VM_PROT_WRITE) {
1866 /* interlocked by presence of pv_entry */
1870 if (prot & VM_PROT_WRITE) {
1871 if (vm_page_busy_try(m, TRUE))
1882 } else if (pte_pv) {
1886 /* error, since we didn't request a placemarker */
1897 * Extract the physical page address associated kernel virtual address.
1900 pmap_kextract(vm_offset_t va)
1902 pd_entry_t pt; /* pt entry in pd */
1905 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1906 pa = DMAP_TO_PHYS(va);
1909 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1910 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1913 * Beware of a concurrent promotion that changes the
1914 * PDE at this point! For example, vtopte() must not
1915 * be used to access the PTE because it would use the
1916 * new PDE. It is, however, safe to use the old PDE
1917 * because the page table page is preserved by the
1920 pa = *pmap_pt_to_pte(pt, va);
1921 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1927 /***************************************************
1928 * Low level mapping routines.....
1929 ***************************************************/
1932 * Routine: pmap_kenter
1934 * Add a wired page to the KVA
1935 * NOTE! note that in order for the mapping to take effect -- you
1936 * should do an invltlb after doing the pmap_kenter().
1939 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1945 kernel_pmap.pmap_bits[PG_RW_IDX] |
1946 kernel_pmap.pmap_bits[PG_V_IDX];
1950 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1954 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1961 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1962 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1963 * (caller can conditionalize calling smp_invltlb()).
1966 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1972 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1973 kernel_pmap.pmap_bits[PG_V_IDX];
1982 atomic_swap_long(ptep, npte);
1983 cpu_invlpg((void *)va);
1989 * Enter addresses into the kernel pmap but don't bother
1990 * doing any tlb invalidations. Caller will do a rollup
1991 * invalidation via pmap_rollup_inval().
1994 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
2001 kernel_pmap.pmap_bits[PG_RW_IDX] |
2002 kernel_pmap.pmap_bits[PG_V_IDX];
2011 atomic_swap_long(ptep, npte);
2012 cpu_invlpg((void *)va);
2018 * remove a page from the kernel pagetables
2021 pmap_kremove(vm_offset_t va)
2026 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
2030 pmap_kremove_quick(vm_offset_t va)
2035 (void)pte_load_clear(ptep);
2036 cpu_invlpg((void *)va);
2040 * Remove addresses from the kernel pmap but don't bother
2041 * doing any tlb invalidations. Caller will do a rollup
2042 * invalidation via pmap_rollup_inval().
2045 pmap_kremove_noinval(vm_offset_t va)
2050 (void)pte_load_clear(ptep);
2054 * XXX these need to be recoded. They are not used in any critical path.
2057 pmap_kmodify_rw(vm_offset_t va)
2059 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
2060 cpu_invlpg((void *)va);
2065 pmap_kmodify_nc(vm_offset_t va)
2067 atomic_set_long(vtopte(va), PG_N);
2068 cpu_invlpg((void *)va);
2073 * Used to map a range of physical addresses into kernel virtual
2074 * address space during the low level boot, typically to map the
2075 * dump bitmap, message buffer, and vm_page_array.
2077 * These mappings are typically made at some pointer after the end of the
2080 * We could return PHYS_TO_DMAP(start) here and not allocate any
2081 * via (*virtp), but then kmem from userland and kernel dumps won't
2082 * have access to the related pointers.
2085 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
2088 vm_offset_t va_start;
2090 /*return PHYS_TO_DMAP(start);*/
2095 while (start < end) {
2096 pmap_kenter_quick(va, start);
2104 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2107 * Remove the specified set of pages from the data and instruction caches.
2109 * In contrast to pmap_invalidate_cache_range(), this function does not
2110 * rely on the CPU's self-snoop feature, because it is intended for use
2111 * when moving pages into a different cache domain.
2114 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2116 vm_offset_t daddr, eva;
2119 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2120 (cpu_feature & CPUID_CLFSH) == 0)
2124 for (i = 0; i < count; i++) {
2125 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2126 eva = daddr + PAGE_SIZE;
2127 for (; daddr < eva; daddr += cpu_clflush_line_size)
2135 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
2137 KASSERT((sva & PAGE_MASK) == 0,
2138 ("pmap_invalidate_cache_range: sva not page-aligned"));
2139 KASSERT((eva & PAGE_MASK) == 0,
2140 ("pmap_invalidate_cache_range: eva not page-aligned"));
2142 if (cpu_feature & CPUID_SS) {
2143 ; /* If "Self Snoop" is supported, do nothing. */
2145 /* Globally invalidate caches */
2146 cpu_wbinvd_on_all_cpus();
2151 * Invalidate the specified range of virtual memory on all cpus associated
2155 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2157 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2161 * Add a list of wired pages to the kva. This routine is used for temporary
2162 * kernel mappings such as those found in buffer cache buffer. Page
2163 * modifications and accesses are not tracked or recorded.
2165 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2166 * semantics as previous mappings may have been zerod without any
2169 * The page *must* be wired.
2171 static __inline void
2172 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2177 end_va = beg_va + count * PAGE_SIZE;
2179 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2184 pte = VM_PAGE_TO_PHYS(*m) |
2185 kernel_pmap.pmap_bits[PG_RW_IDX] |
2186 kernel_pmap.pmap_bits[PG_V_IDX] |
2187 kernel_pmap.pmap_cache_bits_pte[(*m)->pat_mode];
2189 atomic_swap_long(ptep, pte);
2193 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2197 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2199 _pmap_qenter(beg_va, m, count, 1);
2203 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2205 _pmap_qenter(beg_va, m, count, 0);
2209 * This routine jerks page mappings from the kernel -- it is meant only
2210 * for temporary mappings such as those found in buffer cache buffers.
2211 * No recording modified or access status occurs.
2213 * MPSAFE, INTERRUPT SAFE (cluster callback)
2216 pmap_qremove(vm_offset_t beg_va, int count)
2221 end_va = beg_va + count * PAGE_SIZE;
2223 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2227 (void)pte_load_clear(pte);
2228 cpu_invlpg((void *)va);
2230 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2234 * This routine removes temporary kernel mappings, only invalidating them
2235 * on the current cpu. It should only be used under carefully controlled
2239 pmap_qremove_quick(vm_offset_t beg_va, int count)
2244 end_va = beg_va + count * PAGE_SIZE;
2246 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2250 (void)pte_load_clear(pte);
2251 cpu_invlpg((void *)va);
2256 * This routine removes temporary kernel mappings *without* invalidating
2257 * the TLB. It can only be used on permanent kva reservations such as those
2258 * found in buffer cache buffers, under carefully controlled circumstances.
2260 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2261 * (pmap_qenter() does unconditional invalidation).
2264 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2269 end_va = beg_va + count * PAGE_SIZE;
2271 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2275 (void)pte_load_clear(pte);
2280 * Create a new thread and optionally associate it with a (new) process.
2281 * NOTE! the new thread's cpu may not equal the current cpu.
2284 pmap_init_thread(thread_t td)
2286 /* enforce pcb placement & alignment */
2287 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2288 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2289 td->td_savefpu = &td->td_pcb->pcb_save;
2290 td->td_sp = (char *)td->td_pcb; /* no -16 */
2294 * This routine directly affects the fork perf for a process.
2297 pmap_init_proc(struct proc *p)
2302 pmap_pinit_defaults(struct pmap *pmap)
2304 bcopy(pmap_bits_default, pmap->pmap_bits,
2305 sizeof(pmap_bits_default));
2306 bcopy(protection_codes, pmap->protection_codes,
2307 sizeof(protection_codes));
2308 bcopy(pat_pte_index, pmap->pmap_cache_bits_pte,
2309 sizeof(pat_pte_index));
2310 bcopy(pat_pde_index, pmap->pmap_cache_bits_pde,
2311 sizeof(pat_pte_index));
2312 pmap->pmap_cache_mask_pte = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2313 pmap->pmap_cache_mask_pde = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PDE_PAT;
2314 pmap->copyinstr = std_copyinstr;
2315 pmap->copyin = std_copyin;
2316 pmap->copyout = std_copyout;
2317 pmap->fubyte = std_fubyte;
2318 pmap->subyte = std_subyte;
2319 pmap->fuword32 = std_fuword32;
2320 pmap->fuword64 = std_fuword64;
2321 pmap->suword32 = std_suword32;
2322 pmap->suword64 = std_suword64;
2323 pmap->swapu32 = std_swapu32;
2324 pmap->swapu64 = std_swapu64;
2325 pmap->fuwordadd32 = std_fuwordadd32;
2326 pmap->fuwordadd64 = std_fuwordadd64;
2329 * Initialize pmap0/vmspace0.
2331 * On architectures where the kernel pmap is not integrated into the user
2332 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2333 * kernel_pmap should be used to directly access the kernel_pmap.
2336 pmap_pinit0(struct pmap *pmap)
2340 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2342 CPUMASK_ASSZERO(pmap->pm_active);
2343 pmap->pm_pvhint_pt = NULL;
2344 pmap->pm_pvhint_unused = NULL;
2345 RB_INIT(&pmap->pm_pvroot);
2346 spin_init(&pmap->pm_spin, "pmapinit0");
2347 for (i = 0; i < PM_PLACEMARKS; ++i)
2348 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2349 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2350 pmap_pinit_defaults(pmap);
2354 * Initialize a preallocated and zeroed pmap structure,
2355 * such as one in a vmspace structure.
2358 pmap_pinit_simple(struct pmap *pmap)
2363 * Misc initialization
2366 CPUMASK_ASSZERO(pmap->pm_active);
2367 pmap->pm_pvhint_pt = NULL;
2368 pmap->pm_pvhint_unused = NULL;
2369 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2371 pmap_pinit_defaults(pmap);
2374 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2377 if (pmap->pm_pmlpv == NULL) {
2378 RB_INIT(&pmap->pm_pvroot);
2379 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2380 spin_init(&pmap->pm_spin, "pmapinitsimple");
2381 for (i = 0; i < PM_PLACEMARKS; ++i)
2382 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2387 pmap_pinit(struct pmap *pmap)
2392 if (pmap->pm_pmlpv) {
2393 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2398 pmap_pinit_simple(pmap);
2399 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2402 * No need to allocate page table space yet but we do need a valid
2403 * page directory table.
2405 if (pmap->pm_pml4 == NULL) {
2407 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2410 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2414 * Allocate the PML4e table, which wires it even though it isn't
2415 * being entered into some higher level page table (it being the
2416 * highest level). If one is already cached we don't have to do
2419 if ((pv = pmap->pm_pmlpv) == NULL) {
2420 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2421 pmap->pm_pmlpv = pv;
2422 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2423 VM_PAGE_TO_PHYS(pv->pv_m));
2427 * Install DMAP and KMAP.
2429 for (j = 0; j < NDMPML4E; ++j) {
2430 pmap->pm_pml4[DMPML4I + j] =
2431 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2432 pmap->pmap_bits[PG_RW_IDX] |
2433 pmap->pmap_bits[PG_V_IDX] |
2434 pmap->pmap_bits[PG_A_IDX];
2436 for (j = 0; j < NKPML4E; ++j) {
2437 pmap->pm_pml4[KPML4I + j] =
2438 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2439 pmap->pmap_bits[PG_RW_IDX] |
2440 pmap->pmap_bits[PG_V_IDX] |
2441 pmap->pmap_bits[PG_A_IDX];
2445 * install self-referential address mapping entry
2447 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2448 pmap->pmap_bits[PG_V_IDX] |
2449 pmap->pmap_bits[PG_RW_IDX] |
2450 pmap->pmap_bits[PG_A_IDX];
2452 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2453 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2455 KKASSERT(pmap->pm_pml4[255] == 0);
2458 * When implementing an isolated userland pmap, a second PML4e table
2459 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2460 * note that we do not operate on this table using our API functions
2461 * so handling of the + 1 case is mostly just to prevent implosions.
2463 * We install an isolated version of the kernel PDPs into this
2464 * second PML4e table. The pmap code will mirror all user PDPs
2465 * between the primary and secondary PML4e table.
2467 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2468 pmap != &iso_pmap) {
2469 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2470 pmap->pm_pmlpv_iso = pv;
2471 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2472 VM_PAGE_TO_PHYS(pv->pv_m));
2476 * Install an isolated version of the kernel pmap for
2477 * user consumption, using PDPs constructed in iso_pmap.
2479 for (j = 0; j < NKPML4E; ++j) {
2480 pmap->pm_pml4_iso[KPML4I + j] =
2481 iso_pmap.pm_pml4[KPML4I + j];
2484 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2485 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2490 * Clean up a pmap structure so it can be physically freed. This routine
2491 * is called by the vmspace dtor function. A great deal of pmap data is
2492 * left passively mapped to improve vmspace management so we have a bit
2493 * of cleanup work to do here.
2496 pmap_puninit(pmap_t pmap)
2501 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2502 if ((pv = pmap->pm_pmlpv) != NULL) {
2503 if (pv_hold_try(pv) == 0)
2505 KKASSERT(pv == pmap->pm_pmlpv);
2506 p = pmap_remove_pv_page(pv, 1);
2508 pv = NULL; /* safety */
2509 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2510 vm_page_busy_wait(p, FALSE, "pgpun");
2511 KKASSERT(p->flags & PG_UNQUEUED);
2512 vm_page_unwire(p, 0);
2513 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2515 pmap->pm_pmlpv = NULL;
2517 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2518 if (pv_hold_try(pv) == 0)
2520 KKASSERT(pv == pmap->pm_pmlpv_iso);
2521 p = pmap_remove_pv_page(pv, 1);
2523 pv = NULL; /* safety */
2524 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2525 vm_page_busy_wait(p, FALSE, "pgpun");
2526 KKASSERT(p->flags & PG_UNQUEUED);
2527 vm_page_unwire(p, 0);
2528 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2530 pmap->pm_pmlpv_iso = NULL;
2532 if (pmap->pm_pml4) {
2533 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2534 kmem_free(&kernel_map,
2535 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2536 pmap->pm_pml4 = NULL;
2537 pmap->pm_pml4_iso = NULL;
2539 KKASSERT(pmap->pm_stats.resident_count == 0);
2540 KKASSERT(pmap->pm_stats.wired_count == 0);
2544 * This function is now unused (used to add the pmap to the pmap_list)
2547 pmap_pinit2(struct pmap *pmap)
2552 * This routine is called when various levels in the page table need to
2553 * be populated. This routine cannot fail.
2555 * This function returns two locked pv_entry's, one representing the
2556 * requested pv and one representing the requested pv's parent pv. If
2557 * an intermediate page table does not exist it will be created, mapped,
2558 * wired, and the parent page table will be given an additional hold
2559 * count representing the presence of the child pv_entry.
2563 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2566 pt_entry_t *ptep_iso;
2575 * If the pv already exists and we aren't being asked for the
2576 * parent page table page we can just return it. A locked+held pv
2577 * is returned. The pv will also have a second hold related to the
2578 * pmap association that we don't have to worry about.
2581 pv = pv_alloc(pmap, ptepindex, &isnew);
2582 if (isnew == 0 && pvpp == NULL)
2586 * DragonFly doesn't use PV's to represent terminal PTEs any more.
2587 * The index range is still used for placemarkers, but not for
2588 * actual pv_entry's.
2590 KKASSERT(ptepindex >= pmap_pt_pindex(0));
2593 * Note that pt_pv's are only returned for user VAs. We assert that
2594 * a pt_pv is not being requested for kernel VAs. The kernel
2595 * pre-wires all higher-level page tables so don't overload managed
2596 * higher-level page tables on top of it!
2598 * However, its convenient for us to allow the case when creating
2599 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2604 * The kernel never uses managed PT/PD/PDP pages.
2606 KKASSERT(pmap != &kernel_pmap);
2609 * Non-terminal PVs allocate a VM page to represent the page table,
2610 * so we have to resolve pvp and calculate ptepindex for the pvp
2611 * and then for the page table entry index in the pvp for
2614 if (ptepindex < pmap_pd_pindex(0)) {
2616 * pv is PT, pvp is PD
2618 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2619 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2620 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2625 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2626 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2628 } else if (ptepindex < pmap_pdp_pindex(0)) {
2630 * pv is PD, pvp is PDP
2632 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2635 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2636 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2638 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2639 KKASSERT(pvpp == NULL);
2642 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2648 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2649 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2650 } else if (ptepindex < pmap_pml4_pindex()) {
2652 * pv is PDP, pvp is the root pml4 table
2654 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2659 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2660 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2663 * pv represents the top-level PML4, there is no parent.
2672 * (isnew) is TRUE, pv is not terminal.
2674 * (1) Add a wire count to the parent page table (pvp).
2675 * (2) Allocate a VM page for the page table.
2676 * (3) Enter the VM page into the parent page table.
2678 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2681 vm_page_wire_quick(pvp->pv_m);
2684 m = vm_page_alloc(NULL, pv->pv_pindex,
2685 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2686 VM_ALLOC_INTERRUPT);
2691 vm_page_wire(m); /* wire for mapping in parent */
2692 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2693 m->valid = VM_PAGE_BITS_ALL;
2694 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_UNQUEUED);
2695 KKASSERT(m->queue == PQ_NONE);
2700 * (isnew) is TRUE, pv is not terminal.
2702 * Wire the page into pvp. Bump the resident_count for the pmap.
2703 * There is no pvp for the top level, address the pm_pml4[] array
2706 * If the caller wants the parent we return it, otherwise
2707 * we just put it away.
2709 * No interlock is needed for pte 0 -> non-zero.
2711 * In the situation where *ptep is valid we might have an unmanaged
2712 * page table page shared from another page table which we need to
2713 * unshare before installing our private page table page.
2716 v = VM_PAGE_TO_PHYS(m) |
2717 (pmap->pmap_bits[PG_RW_IDX] |
2718 pmap->pmap_bits[PG_V_IDX] |
2719 pmap->pmap_bits[PG_A_IDX]);
2720 if (ptepindex < NUPTE_USER)
2721 v |= pmap->pmap_bits[PG_U_IDX];
2722 if (ptepindex < pmap_pt_pindex(0))
2723 v |= pmap->pmap_bits[PG_M_IDX];
2725 ptep = pv_pte_lookup(pvp, ptepindex);
2726 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2727 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2730 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2731 panic("pmap_allocpte: ptpte present without pv_entry!");
2735 pte = atomic_swap_long(ptep, v);
2737 atomic_swap_long(ptep_iso, v);
2739 kprintf("install pgtbl mixup 0x%016jx "
2740 "old/new 0x%016jx/0x%016jx\n",
2741 (intmax_t)ptepindex, pte, v);
2748 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2752 KKASSERT(pvp->pv_m != NULL);
2753 ptep = pv_pte_lookup(pvp, ptepindex);
2754 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2755 (pmap->pmap_bits[PG_RW_IDX] |
2756 pmap->pmap_bits[PG_V_IDX] |
2757 pmap->pmap_bits[PG_A_IDX]);
2758 if (ptepindex < NUPTE_USER)
2759 v |= pmap->pmap_bits[PG_U_IDX];
2760 if (ptepindex < pmap_pt_pindex(0))
2761 v |= pmap->pmap_bits[PG_M_IDX];
2763 kprintf("mismatched upper level pt %016jx/%016jx\n",
2775 * Release any resources held by the given physical map.
2777 * Called when a pmap initialized by pmap_pinit is being released. Should
2778 * only be called if the map contains no valid mappings.
2780 struct pmap_release_info {
2786 static int pmap_release_callback(pv_entry_t pv, void *data);
2789 pmap_release(struct pmap *pmap)
2791 struct pmap_release_info info;
2793 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2794 ("pmap still active! %016jx",
2795 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2798 * There is no longer a pmap_list, if there were we would remove the
2799 * pmap from it here.
2803 * Pull pv's off the RB tree in order from low to high and release
2811 spin_lock(&pmap->pm_spin);
2812 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2813 pmap_release_callback, &info);
2814 spin_unlock(&pmap->pm_spin);
2818 } while (info.retry);
2822 * One resident page (the pml4 page) should remain. Two if
2823 * the pmap has implemented an isolated userland PML4E table.
2824 * No wired pages should remain.
2826 int expected_res = 0;
2828 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2830 if (pmap->pm_pmlpv_iso)
2834 if (pmap->pm_stats.resident_count != expected_res ||
2835 pmap->pm_stats.wired_count != 0) {
2836 kprintf("fatal pmap problem - pmap %p flags %08x "
2837 "rescnt=%jd wirecnt=%jd\n",
2840 pmap->pm_stats.resident_count,
2841 pmap->pm_stats.wired_count);
2842 tsleep(pmap, 0, "DEAD", 0);
2845 KKASSERT(pmap->pm_stats.resident_count == expected_res);
2846 KKASSERT(pmap->pm_stats.wired_count == 0);
2851 * Called from low to high. We must cache the proper parent pv so we
2852 * can adjust its wired count.
2855 pmap_release_callback(pv_entry_t pv, void *data)
2857 struct pmap_release_info *info = data;
2858 pmap_t pmap = info->pmap;
2863 * Acquire a held and locked pv, check for release race
2865 pindex = pv->pv_pindex;
2866 if (info->pvp == pv) {
2867 spin_unlock(&pmap->pm_spin);
2869 } else if (pv_hold_try(pv)) {
2870 spin_unlock(&pmap->pm_spin);
2872 spin_unlock(&pmap->pm_spin);
2876 spin_lock(&pmap->pm_spin);
2880 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
2882 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2884 * I am PTE, parent is PT
2886 pindex = pv->pv_pindex >> NPTEPGSHIFT;
2887 pindex += NUPTE_TOTAL;
2888 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
2890 * I am PT, parent is PD
2892 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
2893 pindex += NUPTE_TOTAL + NUPT_TOTAL;
2894 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
2896 * I am PD, parent is PDP
2898 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
2900 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2901 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
2903 * I am PDP, parent is PML4. We always calculate the
2904 * normal PML4 here, not the isolated PML4.
2906 pindex = pmap_pml4_pindex();
2918 if (info->pvp && info->pvp->pv_pindex != pindex) {
2922 if (info->pvp == NULL)
2923 info->pvp = pv_get(pmap, pindex, NULL);
2930 r = pmap_release_pv(pv, info->pvp, NULL);
2931 spin_lock(&pmap->pm_spin);
2937 * Called with held (i.e. also locked) pv. This function will dispose of
2938 * the lock along with the pv.
2940 * If the caller already holds the locked parent page table for pv it
2941 * must pass it as pvp, allowing us to avoid a deadlock, else it can
2942 * pass NULL for pvp.
2945 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
2950 * The pmap is currently not spinlocked, pv is held+locked.
2951 * Remove the pv's page from its parent's page table. The
2952 * parent's page table page's wire_count will be decremented.
2954 * This will clean out the pte at any level of the page table.
2955 * If smp != 0 all cpus are affected.
2957 * Do not tear-down recursively, its faster to just let the
2958 * release run its course.
2960 pmap_remove_pv_pte(pv, pvp, bulk, 0);
2963 * Terminal pvs are unhooked from their vm_pages. Because
2964 * terminal pages aren't page table pages they aren't wired
2965 * by us, so we have to be sure not to unwire them either.
2967 * XXX this code is operating on a user page rather than
2968 * a page-table page and cannot safely clear the PG_MAPPED
2969 * and PG_WRITEABLE bits. (XXX clearing these bits should
2970 * be safe in PMAP_ADVANCED mode).
2972 * XXX It is unclear if this code ever gets called because we
2973 * no longer use pv's to track terminal pages.
2975 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2976 pmap_remove_pv_page(pv, 0);
2981 * We leave the top-level page table page cached, wired, and
2982 * mapped in the pmap until the dtor function (pmap_puninit())
2985 * Since we are leaving the top-level pv intact we need
2986 * to break out of what would otherwise be an infinite loop.
2988 * This covers both the normal and the isolated PML4 page.
2990 if (pv->pv_pindex >= pmap_pml4_pindex()) {
2996 * For page table pages (other than the top-level page),
2997 * remove and free the vm_page. The representitive mapping
2998 * removed above by pmap_remove_pv_pte() did not undo the
2999 * last wire_count so we have to do that as well.
3001 p = pmap_remove_pv_page(pv, 1);
3002 vm_page_busy_wait(p, FALSE, "pmaprl");
3003 if (p->wire_count != 1) {
3006 if (pv->pv_pindex >= pmap_pdp_pindex(0))
3008 else if (pv->pv_pindex >= pmap_pd_pindex(0))
3010 else if (pv->pv_pindex >= pmap_pt_pindex(0))
3015 kprintf("p(%s) p->wire_count was %016lx %d\n",
3016 tstr, pv->pv_pindex, p->wire_count);
3018 KKASSERT(p->wire_count == 1);
3019 KKASSERT(p->flags & PG_UNQUEUED);
3021 vm_page_unwire(p, 0);
3022 KKASSERT(p->wire_count == 0);
3032 * This function will remove the pte associated with a pv from its parent.
3033 * Terminal pv's are supported. All cpus specified by (bulk) are properly
3036 * The wire count will be dropped on the parent page table. The wire
3037 * count on the page being removed (pv->pv_m) from the parent page table
3038 * is NOT touched. Note that terminal pages will not have any additional
3039 * wire counts while page table pages will have at least one representing
3040 * the mapping, plus others representing sub-mappings.
3042 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3043 * pages and user page table and terminal pages.
3045 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3046 * be freshly allocated and not imply that the pte is managed. In this
3047 * case pv->pv_m should be NULL.
3049 * The pv must be locked. The pvp, if supplied, must be locked. All
3050 * supplied pv's will remain locked on return.
3052 * XXX must lock parent pv's if they exist to remove pte XXX
3056 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3059 vm_pindex_t ptepindex = pv->pv_pindex;
3060 pmap_t pmap = pv->pv_pmap;
3066 if (ptepindex >= pmap_pml4_pindex()) {
3068 * We are the top level PML4E table, there is no parent.
3070 * This is either the normal or isolated PML4E table.
3071 * Only the normal is used in regular operation, the isolated
3072 * is only passed in when breaking down the whole pmap.
3074 p = pmap->pm_pmlpv->pv_m;
3075 KKASSERT(pv->pv_m == p); /* debugging */
3076 } else if (ptepindex >= pmap_pdp_pindex(0)) {
3078 * Remove a PDP page from the PML4E. This can only occur
3079 * with user page tables. We do not have to lock the
3080 * pml4 PV so just ignore pvp.
3082 vm_pindex_t pml4_pindex;
3083 vm_pindex_t pdp_index;
3085 pml4_entry_t *pdp_iso;
3087 pdp_index = ptepindex - pmap_pdp_pindex(0);
3089 pml4_pindex = pmap_pml4_pindex();
3090 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3095 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3096 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3097 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3098 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3101 * Also remove the PDP from the isolated PML4E if the
3104 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3105 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3106 ((1ul << NPML4EPGSHIFT) - 1)];
3107 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3109 KKASSERT(pv->pv_m == p); /* debugging */
3110 } else if (ptepindex >= pmap_pd_pindex(0)) {
3112 * Remove a PD page from the PDP
3114 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3115 * of a simple pmap because it stops at
3118 vm_pindex_t pdp_pindex;
3119 vm_pindex_t pd_index;
3122 pd_index = ptepindex - pmap_pd_pindex(0);
3125 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3126 (pd_index >> NPML4EPGSHIFT);
3127 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3132 pd = pv_pte_lookup(pvp, pd_index &
3133 ((1ul << NPDPEPGSHIFT) - 1));
3134 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3135 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3136 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3138 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3139 p = pv->pv_m; /* degenerate test later */
3141 KKASSERT(pv->pv_m == p); /* debugging */
3142 } else if (ptepindex >= pmap_pt_pindex(0)) {
3144 * Remove a PT page from the PD
3146 vm_pindex_t pd_pindex;
3147 vm_pindex_t pt_index;
3150 pt_index = ptepindex - pmap_pt_pindex(0);
3153 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3154 (pt_index >> NPDPEPGSHIFT);
3155 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3160 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3162 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3163 ("*pt unexpectedly invalid %016jx "
3164 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3165 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3166 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3168 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3169 kprintf("*pt unexpectedly invalid %016jx "
3170 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3172 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3173 tsleep(pt, 0, "DEAD", 0);
3176 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3179 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3180 KKASSERT(pv->pv_m == p); /* debugging */
3186 * If requested, scrap the underlying pv->pv_m and the underlying
3187 * pv. If this is a page-table-page we must also free the page.
3189 * pvp must be returned locked.
3193 * page table page (PT, PD, PDP, PML4), caller was responsible
3194 * for testing wired_count.
3196 KKASSERT(pv->pv_m->wire_count == 1);
3197 p = pmap_remove_pv_page(pv, 1);
3201 vm_page_busy_wait(p, FALSE, "pgpun");
3202 vm_page_unwire(p, 0);
3203 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3206 #if !defined(PMAP_ADVANCED)
3207 else if (destroy == 2) {
3209 * Normal page, remove from pmap and leave the underlying
3212 * XXX REMOVE ME, destroy can no longer be 2.
3214 pmap_remove_pv_page(pv, 0);
3216 pv = NULL; /* safety */
3221 * If we acquired pvp ourselves then we are responsible for
3222 * recursively deleting it.
3224 if (pvp && gotpvp) {
3226 * Recursively destroy higher-level page tables.
3228 * This is optional. If we do not, they will still
3229 * be destroyed when the process exits.
3231 * NOTE: Do not destroy pv_entry's with extra hold refs,
3232 * a caller may have unlocked it and intends to
3233 * continue to use it.
3235 if (pmap_dynamic_delete &&
3237 pvp->pv_m->wire_count == 1 &&
3238 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3239 pvp->pv_pindex < pmap_pml4_pindex()) {
3240 if (pmap != &kernel_pmap) {
3241 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3242 pvp = NULL; /* safety */
3244 kprintf("Attempt to remove kernel_pmap pindex "
3245 "%jd\n", pvp->pv_pindex);
3255 * Remove the vm_page association to a pv. The pv must be locked.
3259 pmap_remove_pv_page(pv_entry_t pv, int clrpgbits)
3266 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3272 * Grow the number of kernel page table entries, if needed.
3274 * This routine is always called to validate any address space
3275 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3276 * space below KERNBASE.
3278 * kernel_map must be locked exclusively by the caller.
3281 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3284 vm_offset_t ptppaddr;
3286 pd_entry_t *pt, newpt;
3287 pdp_entry_t *pd, newpd;
3288 int update_kernel_vm_end;
3291 * bootstrap kernel_vm_end on first real VM use
3293 if (kernel_vm_end == 0) {
3294 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3297 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3300 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3302 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3303 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3304 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
3305 kernel_vm_end = vm_map_max(&kernel_map);
3312 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3313 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3314 * do not want to force-fill 128G worth of page tables.
3316 if (kstart < KERNBASE) {
3317 if (kstart > kernel_vm_end)
3318 kstart = kernel_vm_end;
3319 KKASSERT(kend <= KERNBASE);
3320 update_kernel_vm_end = 1;
3322 update_kernel_vm_end = 0;
3325 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3326 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3328 if (kend - 1 >= vm_map_max(&kernel_map))
3329 kend = vm_map_max(&kernel_map);
3331 while (kstart < kend) {
3332 pt = pmap_pt(&kernel_pmap, kstart);
3335 * We need a new PD entry
3337 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3340 VM_ALLOC_INTERRUPT);
3342 panic("pmap_growkernel: no memory to grow "
3345 paddr = VM_PAGE_TO_PHYS(nkpg);
3346 pmap_zero_page(paddr);
3347 pd = pmap_pd(&kernel_pmap, kstart);
3349 newpd = (pdp_entry_t)
3351 kernel_pmap.pmap_bits[PG_V_IDX] |
3352 kernel_pmap.pmap_bits[PG_RW_IDX] |
3353 kernel_pmap.pmap_bits[PG_A_IDX]);
3354 atomic_swap_long(pd, newpd);
3357 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3361 continue; /* try again */
3364 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3365 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3366 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3367 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3368 kstart = vm_map_max(&kernel_map);
3377 * This index is bogus, but out of the way
3379 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3382 VM_ALLOC_INTERRUPT);
3384 panic("pmap_growkernel: no memory to grow kernel");
3387 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3388 pmap_zero_page(ptppaddr);
3389 newpt = (pd_entry_t)(ptppaddr |
3390 kernel_pmap.pmap_bits[PG_V_IDX] |
3391 kernel_pmap.pmap_bits[PG_RW_IDX] |
3392 kernel_pmap.pmap_bits[PG_A_IDX]);
3393 atomic_swap_long(pt, newpt);
3395 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3396 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3398 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3399 kstart = vm_map_max(&kernel_map);
3405 * Only update kernel_vm_end for areas below KERNBASE.
3407 if (update_kernel_vm_end && kernel_vm_end < kstart)
3408 kernel_vm_end = kstart;
3412 * Add a reference to the specified pmap.
3415 pmap_reference(pmap_t pmap)
3418 atomic_add_int(&pmap->pm_count, 1);
3422 pmap_maybethreaded(pmap_t pmap)
3424 atomic_set_int(&pmap->pm_flags, PMAP_MULTI);
3428 * Called while page is hard-busied to clear the PG_MAPPED and PG_WRITEABLE
3429 * flags if able. This can happen when the pmap code is unable to clear
3430 * the bits in prior actions due to not holding the page hard-busied at
3433 * When PMAP_ADVANCED is enabled the clearing of PG_MAPPED/WRITEABLE
3434 * is an optional optimization done when the pte is removed and only
3435 * if the pte has not been multiply-mapped. The caller may have to
3436 * call vm_page_protect() if the bits are still set here.
3438 * When PMAP_ADVANCED is disabled we check pmap_count to synchronize
3439 * the clearing of PG_MAPPED etc. The caller only has to call
3440 * vm_page_protect() if the page is still actually mapped.
3442 * This function is expected to be quick.
3445 pmap_mapped_sync(vm_page_t m)
3447 #if !defined(PMAP_ADVANCED)
3448 if (m->flags & (PG_MAPPED | PG_WRITEABLE)) {
3449 if (m->md.pmap_count == 0) {
3450 vm_page_flag_clear(m, PG_MAPPED | PG_MAPPEDMULTI |
3458 /***************************************************
3459 * page management routines.
3460 ***************************************************/
3463 * Hold a pv without locking it
3467 pv_hold(pv_entry_t pv)
3469 atomic_add_int(&pv->pv_hold, 1);
3474 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3475 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3478 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3479 * pv list via its page) must be held by the caller in order to stabilize
3483 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3488 * Critical path shortcut expects pv to already have one ref
3489 * (for the pv->pv_pmap).
3491 count = pv->pv_hold;
3494 if ((count & PV_HOLD_LOCKED) == 0) {
3495 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3496 (count + 1) | PV_HOLD_LOCKED)) {
3499 pv->pv_line = lineno;
3504 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3512 * Drop a previously held pv_entry which could not be locked, allowing its
3515 * Must not be called with a spinlock held as we might zfree() the pv if it
3516 * is no longer associated with a pmap and this was the last hold count.
3519 pv_drop(pv_entry_t pv)
3524 count = pv->pv_hold;
3526 KKASSERT((count & PV_HOLD_MASK) > 0);
3527 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3528 (PV_HOLD_LOCKED | 1));
3529 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3530 if ((count & PV_HOLD_MASK) == 1) {
3532 if (pmap_enter_debug > 0) {
3534 kprintf("pv_drop: free pv %p\n", pv);
3537 KKASSERT(count == 1);
3538 KKASSERT(pv->pv_pmap == NULL);
3548 * Find or allocate the requested PV entry, returning a locked, held pv.
3550 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3551 * for the caller and one representing the pmap and vm_page association.
3553 * If (*isnew) is zero, the returned pv will have only one hold count.
3555 * Since both associations can only be adjusted while the pv is locked,
3556 * together they represent just one additional hold.
3560 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3562 struct mdglobaldata *md = mdcpu;
3570 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3573 pnew = md->gd_newpv; /* might race NULL */
3574 md->gd_newpv = NULL;
3579 pnew = zalloc(pvzone);
3581 spin_lock_shared(&pmap->pm_spin);
3586 pv = pv_entry_lookup(pmap, pindex);
3591 * Requires exclusive pmap spinlock
3593 if (pmap_excl == 0) {
3595 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3596 spin_unlock_shared(&pmap->pm_spin);
3597 spin_lock(&pmap->pm_spin);
3603 * We need to block if someone is holding our
3604 * placemarker. As long as we determine the
3605 * placemarker has not been aquired we do not
3606 * need to get it as acquision also requires
3607 * the pmap spin lock.
3609 * However, we can race the wakeup.
3611 pmark = pmap_placemarker_hash(pmap, pindex);
3613 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3614 tsleep_interlock(pmark, 0);
3615 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3616 if (((*pmark ^ pindex) &
3617 ~PM_PLACEMARK_WAKEUP) == 0) {
3618 spin_unlock(&pmap->pm_spin);
3619 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3620 spin_lock(&pmap->pm_spin);
3626 * Setup the new entry
3628 pnew->pv_pmap = pmap;
3629 pnew->pv_pindex = pindex;
3630 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3633 pnew->pv_func = func;
3634 pnew->pv_line = lineno;
3635 if (pnew->pv_line_lastfree > 0) {
3636 pnew->pv_line_lastfree =
3637 -pnew->pv_line_lastfree;
3640 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3641 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3642 spin_unlock(&pmap->pm_spin);
3645 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3650 * We already have an entry, cleanup the staged pnew if
3651 * we can get the lock, otherwise block and retry.
3653 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3655 spin_unlock(&pmap->pm_spin);
3657 spin_unlock_shared(&pmap->pm_spin);
3659 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3661 zfree(pvzone, pnew);
3664 if (md->gd_newpv == NULL)
3665 md->gd_newpv = pnew;
3667 zfree(pvzone, pnew);
3670 KKASSERT(pv->pv_pmap == pmap &&
3671 pv->pv_pindex == pindex);
3676 spin_unlock(&pmap->pm_spin);
3677 _pv_lock(pv PMAP_DEBUG_COPY);
3679 spin_lock(&pmap->pm_spin);
3681 spin_unlock_shared(&pmap->pm_spin);
3682 _pv_lock(pv PMAP_DEBUG_COPY);
3684 spin_lock_shared(&pmap->pm_spin);
3691 * Find the requested PV entry, returning a locked+held pv or NULL
3695 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3700 spin_lock_shared(&pmap->pm_spin);
3705 pv = pv_entry_lookup(pmap, pindex);
3708 * Block if there is ANY placemarker. If we are to
3709 * return it, we must also aquire the spot, so we
3710 * have to block even if the placemarker is held on
3711 * a different address.
3713 * OPTIMIZATION: If pmarkp is passed as NULL the
3714 * caller is just probing (or looking for a real
3715 * pv_entry), and in this case we only need to check
3716 * to see if the placemarker matches pindex.
3721 * Requires exclusive pmap spinlock
3723 if (pmap_excl == 0) {
3725 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3726 spin_unlock_shared(&pmap->pm_spin);
3727 spin_lock(&pmap->pm_spin);
3732 pmark = pmap_placemarker_hash(pmap, pindex);
3734 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3735 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3736 tsleep_interlock(pmark, 0);
3737 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3738 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3739 ((*pmark ^ pindex) &
3740 ~PM_PLACEMARK_WAKEUP) == 0) {
3741 spin_unlock(&pmap->pm_spin);
3742 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3743 spin_lock(&pmap->pm_spin);
3748 if (atomic_swap_long(pmark, pindex) !=
3750 panic("_pv_get: pmark race");
3754 spin_unlock(&pmap->pm_spin);
3757 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3759 spin_unlock(&pmap->pm_spin);
3761 spin_unlock_shared(&pmap->pm_spin);
3762 KKASSERT(pv->pv_pmap == pmap &&
3763 pv->pv_pindex == pindex);
3767 spin_unlock(&pmap->pm_spin);
3768 _pv_lock(pv PMAP_DEBUG_COPY);
3770 spin_lock(&pmap->pm_spin);
3772 spin_unlock_shared(&pmap->pm_spin);
3773 _pv_lock(pv PMAP_DEBUG_COPY);
3775 spin_lock_shared(&pmap->pm_spin);
3781 * Lookup, hold, and attempt to lock (pmap,pindex).
3783 * If the entry does not exist NULL is returned and *errorp is set to 0
3785 * If the entry exists and could be successfully locked it is returned and
3786 * errorp is set to 0.
3788 * If the entry exists but could NOT be successfully locked it is returned
3789 * held and *errorp is set to 1.
3791 * If the entry is placemarked by someone else NULL is returned and *errorp
3796 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3800 spin_lock_shared(&pmap->pm_spin);
3802 pv = pv_entry_lookup(pmap, pindex);
3806 pmark = pmap_placemarker_hash(pmap, pindex);
3808 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3810 } else if (pmarkp &&
3811 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3815 * Can't set a placemark with a NULL pmarkp, or if
3816 * pmarkp is non-NULL but we failed to set our
3823 spin_unlock_shared(&pmap->pm_spin);
3829 * XXX This has problems if the lock is shared, why?
3831 if (pv_hold_try(pv)) {
3832 spin_unlock_shared(&pmap->pm_spin);
3834 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3835 return(pv); /* lock succeeded */
3837 spin_unlock_shared(&pmap->pm_spin);
3840 return (pv); /* lock failed */
3844 * Lock a held pv, keeping the hold count
3848 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
3853 count = pv->pv_hold;
3855 if ((count & PV_HOLD_LOCKED) == 0) {
3856 if (atomic_cmpset_int(&pv->pv_hold, count,
3857 count | PV_HOLD_LOCKED)) {
3860 pv->pv_line = lineno;
3866 tsleep_interlock(pv, 0);
3867 if (atomic_cmpset_int(&pv->pv_hold, count,
3868 count | PV_HOLD_WAITING)) {
3870 if (pmap_enter_debug > 0) {
3872 kprintf("pv waiting on %s:%d\n",
3873 pv->pv_func, pv->pv_line);
3876 tsleep(pv, PINTERLOCKED, "pvwait", hz);
3883 * Unlock a held and locked pv, keeping the hold count.
3887 pv_unlock(pv_entry_t pv)
3892 count = pv->pv_hold;
3894 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
3895 (PV_HOLD_LOCKED | 1));
3896 if (atomic_cmpset_int(&pv->pv_hold, count,
3898 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
3899 if (count & PV_HOLD_WAITING)
3907 * Unlock and drop a pv. If the pv is no longer associated with a pmap
3908 * and the hold count drops to zero we will free it.
3910 * Caller should not hold any spin locks. We are protected from hold races
3911 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
3912 * lock held. A pv cannot be located otherwise.
3916 pv_put(pv_entry_t pv)
3919 if (pmap_enter_debug > 0) {
3921 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
3926 * Normal put-aways must have a pv_m associated with the pv,
3927 * but allow the case where the pv has been destructed due
3928 * to pmap_dynamic_delete.
3930 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
3933 * Fast - shortcut most common condition
3935 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
3946 * Remove the pmap association from a pv, require that pv_m already be removed,
3947 * then unlock and drop the pv. Any pte operations must have already been
3948 * completed. This call may result in a last-drop which will physically free
3951 * Removing the pmap association entails an additional drop.
3953 * pv must be exclusively locked on call and will be disposed of on return.
3957 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
3962 pv->pv_func_lastfree = func;
3963 pv->pv_line_lastfree = lineno;
3965 KKASSERT(pv->pv_m == NULL);
3966 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
3967 (PV_HOLD_LOCKED|1));
3968 if ((pmap = pv->pv_pmap) != NULL) {
3969 spin_lock(&pmap->pm_spin);
3970 KKASSERT(pv->pv_pmap == pmap);
3971 if (pmap->pm_pvhint_pt == pv)
3972 pmap->pm_pvhint_pt = NULL;
3973 if (pmap->pm_pvhint_unused == pv)
3974 pmap->pm_pvhint_unused = NULL;
3975 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
3976 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3979 spin_unlock(&pmap->pm_spin);
3982 * Try to shortcut three atomic ops, otherwise fall through
3983 * and do it normally. Drop two refs and the lock all in
3987 if (vm_page_unwire_quick(pvp->pv_m))
3988 panic("_pv_free: bad wirecount on pvp");
3990 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
3992 if (pmap_enter_debug > 0) {
3994 kprintf("pv_free: free pv %p\n", pv);
4000 pv_drop(pv); /* ref for pv_pmap */
4007 * This routine is very drastic, but can save the system
4015 static int warningdone=0;
4017 if (pmap_pagedaemon_waken == 0)
4019 pmap_pagedaemon_waken = 0;
4020 if (warningdone < 5) {
4021 kprintf("pmap_collect: pv_entries exhausted -- "
4022 "suggest increasing vm.pmap_pv_entries above %ld\n",
4023 vm_pmap_pv_entries);
4027 for (i = 0; i < vm_page_array_size; i++) {
4028 m = &vm_page_array[i];
4029 if (m->wire_count || m->hold_count)
4031 if (vm_page_busy_try(m, TRUE) == 0) {
4032 if (m->wire_count == 0 && m->hold_count == 0) {
4041 * Scan the pmap for active page table entries and issue a callback.
4042 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4043 * its parent page table.
4045 * pte_pv will be NULL if the page or page table is unmanaged.
4046 * pt_pv will point to the page table page containing the pte for the page.
4048 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4049 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4050 * process pmap's PD and page to the callback function. This can be
4051 * confusing because the pt_pv is really a pd_pv, and the target page
4052 * table page is simply aliased by the pmap and not owned by it.
4054 * It is assumed that the start and end are properly rounded to the page size.
4056 * It is assumed that PD pages and above are managed and thus in the RB tree,
4057 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4059 struct pmap_scan_info {
4063 vm_pindex_t sva_pd_pindex;
4064 vm_pindex_t eva_pd_pindex;
4065 void (*func)(pmap_t, struct pmap_scan_info *,
4066 vm_pindex_t *, pv_entry_t, vm_offset_t,
4067 pt_entry_t *, void *);
4069 pmap_inval_bulk_t bulk_core;
4070 pmap_inval_bulk_t *bulk;
4075 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4076 static int pmap_scan_callback(pv_entry_t pv, void *data);
4079 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4081 struct pmap *pmap = info->pmap;
4082 pv_entry_t pt_pv; /* A page table PV */
4083 pv_entry_t pte_pv; /* A page table entry PV */
4084 vm_pindex_t *pte_placemark;
4085 vm_pindex_t *pt_placemark;
4088 struct pv_entry dummy_pv;
4093 if (info->sva == info->eva)
4096 info->bulk = &info->bulk_core;
4097 pmap_inval_bulk_init(&info->bulk_core, pmap);
4103 * Hold the token for stability; if the pmap is empty we have nothing
4107 if (pmap->pm_stats.resident_count == 0) {
4115 * Special handling for scanning one page, which is a very common
4116 * operation (it is?).
4118 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4120 if (info->sva + PAGE_SIZE == info->eva) {
4121 if (info->sva >= VM_MAX_USER_ADDRESS) {
4123 * Kernel mappings do not track wire counts on
4124 * page table pages and only maintain pd_pv and
4125 * pte_pv levels so pmap_scan() works.
4128 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4130 KKASSERT(pte_pv == NULL);
4131 ptep = vtopte(info->sva);
4134 * We hold pte_placemark across the operation for
4137 * WARNING! We must hold pt_placemark across the
4138 * *ptep test to prevent misintepreting
4139 * a non-zero *ptep as a shared page
4140 * table page. Hold it across the function
4141 * callback as well for SMP safety.
4143 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4145 KKASSERT(pte_pv == NULL);
4146 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4148 if (pt_pv == NULL) {
4151 pd_pv = pv_get(pmap,
4152 pmap_pd_pindex(info->sva),
4155 ptep = pv_pte_lookup(pd_pv,
4156 pmap_pt_index(info->sva));
4158 info->func(pmap, info,
4159 pt_placemark, pd_pv,
4163 pv_placemarker_wakeup(pmap,
4168 pv_placemarker_wakeup(pmap,
4172 pv_placemarker_wakeup(pmap, pt_placemark);
4174 pv_placemarker_wakeup(pmap, pte_placemark);
4177 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4181 * NOTE: *ptep can't be ripped out from under us if we hold
4182 * pte_pv (or pte_placemark) locked, but bits can
4188 KKASSERT(pte_pv == NULL);
4189 pv_placemarker_wakeup(pmap, pte_placemark);
4191 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]) ==
4192 pmap->pmap_bits[PG_V_IDX],
4193 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4194 *ptep, oldpte, info->sva));
4195 info->func(pmap, info, pte_placemark, pt_pv,
4196 info->sva, ptep, info->arg);
4201 pmap_inval_bulk_flush(info->bulk);
4206 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4209 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4210 * bounds, resulting in a pd_pindex of 0. To solve the
4211 * problem we use an inclusive range.
4213 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4214 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4216 if (info->sva >= VM_MAX_USER_ADDRESS) {
4218 * The kernel does not currently maintain any pv_entry's for
4219 * higher-level page tables.
4221 bzero(&dummy_pv, sizeof(dummy_pv));
4222 dummy_pv.pv_pindex = info->sva_pd_pindex;
4223 spin_lock(&pmap->pm_spin);
4224 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4225 pmap_scan_callback(&dummy_pv, info);
4226 ++dummy_pv.pv_pindex;
4227 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4230 spin_unlock(&pmap->pm_spin);
4233 * User page tables maintain local PML4, PDP, PD, and PT
4234 * pv_entry's. pv_entry's are not used for PTEs.
4236 spin_lock(&pmap->pm_spin);
4237 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4238 pmap_scan_callback, info);
4239 spin_unlock(&pmap->pm_spin);
4241 pmap_inval_bulk_flush(info->bulk);
4245 * WARNING! pmap->pm_spin held
4247 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4248 * bounds, resulting in a pd_pindex of 0. To solve the
4249 * problem we use an inclusive range.
4252 pmap_scan_cmp(pv_entry_t pv, void *data)
4254 struct pmap_scan_info *info = data;
4255 if (pv->pv_pindex < info->sva_pd_pindex)
4257 if (pv->pv_pindex > info->eva_pd_pindex)
4263 * pmap_scan() by PDs
4265 * WARNING! pmap->pm_spin held
4268 pmap_scan_callback(pv_entry_t pv, void *data)
4270 struct pmap_scan_info *info = data;
4271 struct pmap *pmap = info->pmap;
4272 pv_entry_t pd_pv; /* A page directory PV */
4273 pv_entry_t pt_pv; /* A page table PV */
4274 vm_pindex_t *pt_placemark;
4279 vm_offset_t va_next;
4280 vm_pindex_t pd_pindex;
4290 * Pull the PD pindex from the pv before releasing the spinlock.
4292 * WARNING: pv is faked for kernel pmap scans.
4294 pd_pindex = pv->pv_pindex;
4295 spin_unlock(&pmap->pm_spin);
4296 pv = NULL; /* invalid after spinlock unlocked */
4299 * Calculate the page range within the PD. SIMPLE pmaps are
4300 * direct-mapped for the entire 2^64 address space. Normal pmaps
4301 * reflect the user and kernel address space which requires
4302 * cannonicalization w/regards to converting pd_pindex's back
4305 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4306 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4307 (sva & PML4_SIGNMASK)) {
4308 sva |= PML4_SIGNMASK;
4310 eva = sva + NBPDP; /* can overflow */
4311 if (sva < info->sva)
4313 if (eva < info->sva || eva > info->eva)
4317 * NOTE: kernel mappings do not track page table pages, only
4320 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4321 * However, for the scan to be efficient we try to
4322 * cache items top-down.
4327 for (; sva < eva; sva = va_next) {
4330 if (sva >= VM_MAX_USER_ADDRESS) {
4339 * PD cache, scan shortcut if it doesn't exist.
4341 if (pd_pv == NULL) {
4342 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4343 } else if (pd_pv->pv_pmap != pmap ||
4344 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4346 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4348 if (pd_pv == NULL) {
4349 va_next = (sva + NBPDP) & ~PDPMASK;
4358 * NOTE: The cached pt_pv can be removed from the pmap when
4359 * pmap_dynamic_delete is enabled.
4361 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4362 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4366 if (pt_pv == NULL) {
4367 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4368 &pt_placemark, &error);
4370 pv_put(pd_pv); /* lock order */
4377 pv_placemarker_wait(pmap, pt_placemark);
4382 /* may have to re-check later if pt_pv is NULL here */
4386 * If pt_pv is NULL we either have a shared page table
4387 * page (NOT IMPLEMENTED XXX) and must issue a callback
4388 * specific to that case, or there is no page table page.
4390 * Either way we can skip the page table page.
4392 * WARNING! pt_pv can also be NULL due to a pv creation
4393 * race where we find it to be NULL and then
4394 * later see a pte_pv. But its possible the pt_pv
4395 * got created inbetween the two operations, so
4398 * XXX This should no longer be the case because
4399 * we have pt_placemark.
4401 if (pt_pv == NULL) {
4405 * Possible unmanaged (shared from another pmap)
4408 * WARNING! We must hold pt_placemark across the
4409 * *ptep test to prevent misintepreting
4410 * a non-zero *ptep as a shared page
4411 * table page. Hold it across the function
4412 * callback as well for SMP safety.
4415 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4416 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4417 info->func(pmap, info, pt_placemark, pd_pv,
4418 sva, ptep, info->arg);
4420 pv_placemarker_wakeup(pmap, pt_placemark);
4423 pv_placemarker_wakeup(pmap, pt_placemark);
4427 * Done, move to next page table page.
4429 va_next = (sva + NBPDR) & ~PDRMASK;
4436 * From this point in the loop testing pt_pv for non-NULL
4437 * means we are in UVM, else if it is NULL we are in KVM.
4439 * Limit our scan to either the end of the va represented
4440 * by the current page table page, or to the end of the
4441 * range being removed.
4444 va_next = (sva + NBPDR) & ~PDRMASK;
4451 * Scan the page table for pages. Some pages may not be
4452 * managed (might not have a pv_entry).
4454 * There is no page table management for kernel pages so
4455 * pt_pv will be NULL in that case, but otherwise pt_pv
4456 * is non-NULL, locked, and referenced.
4460 * At this point a non-NULL pt_pv means a UVA, and a NULL
4461 * pt_pv means a KVA.
4464 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4468 while (sva < va_next) {
4469 vm_pindex_t *pte_placemark;
4473 * Yield every 64 pages, stop if requested.
4475 if ((++info->count & 63) == 0)
4481 * We can shortcut our scan if *ptep == 0. This is
4482 * an unlocked check.
4492 * Acquire the pte_placemark. pte_pv's won't exist
4495 * A multitude of races are possible here so if we
4496 * cannot lock definite state we clean out our cache
4497 * and break the inner while() loop to force a loop
4498 * up to the top of the for().
4500 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4501 * validity instead of looping up?
4503 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4504 &pte_placemark, &error);
4505 KKASSERT(pte_pv == NULL);
4508 pv_put(pd_pv); /* lock order */
4512 pv_put(pt_pv); /* lock order */
4515 pv_placemarker_wait(pmap, pte_placemark);
4516 va_next = sva; /* retry */
4521 * Reload *ptep after successfully locking the
4527 pv_placemarker_wakeup(pmap, pte_placemark);
4534 * We can't hold pd_pv across the callback (because
4535 * we don't pass it to the callback and the callback
4539 vm_page_wire_quick(pd_pv->pv_m);
4544 * Ready for the callback. The locked placemarker
4545 * is consumed by the callback.
4547 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4551 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4552 ("badC *ptep %016lx/%016lx sva %016lx",
4553 *ptep, oldpte, sva));
4555 * We must unlock pd_pv across the callback
4556 * to avoid deadlocks on any recursive
4557 * disposal. Re-check that it still exists
4560 * Call target disposes of pte_placemark
4561 * and may destroy but will not dispose
4564 info->func(pmap, info, pte_placemark, pt_pv,
4565 sva, ptep, info->arg);
4570 * We must unlock pd_pv across the callback
4571 * to avoid deadlocks on any recursive
4572 * disposal. Re-check that it still exists
4575 * Call target disposes of pte_placemark
4576 * and may destroy but will not dispose
4579 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4580 ("badD *ptep %016lx/%016lx sva %016lx ",
4581 *ptep, oldpte, sva));
4582 info->func(pmap, info, pte_placemark, pt_pv,
4583 sva, ptep, info->arg);
4587 if (vm_page_unwire_quick(pd_pv->pv_m)) {
4588 panic("pmap_scan_callback: "
4589 "bad wirecount on pd_pv");
4591 if (pd_pv->pv_pmap == NULL) {
4592 va_next = sva; /* retry */
4598 * NOTE: The cached pt_pv can be removed from the
4599 * pmap when pmap_dynamic_delete is enabled,
4600 * which will cause ptep to become stale.
4602 * This also means that no pages remain under
4603 * the PT, so we can just break out of the inner
4604 * loop and let the outer loop clean everything
4607 if (pt_pv && pt_pv->pv_pmap != pmap)
4621 if ((++info->count & 7) == 0)
4625 * Relock before returning.
4627 spin_lock(&pmap->pm_spin);
4632 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4634 struct pmap_scan_info info;
4639 info.func = pmap_remove_callback;
4641 pmap_scan(&info, 1);
4644 if (eva - sva < 1024*1024) {
4646 cpu_invlpg((void *)sva);
4654 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4656 struct pmap_scan_info info;
4661 info.func = pmap_remove_callback;
4663 pmap_scan(&info, 0);
4667 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4668 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
4669 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4672 #ifdef PMAP_ADVANCED
4677 * Managed or unmanaged pte (pte_placemark is non-NULL)
4679 * pt_pv's wire_count is still bumped by unmanaged pages
4680 * so we must decrement it manually.
4682 * We have to unwire the target page table page.
4684 #ifdef PMAP_ADVANCED
4686 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4687 oldm = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4688 atomic_add_long(&oldm->md.interlock_count, 1);
4694 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4695 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4698 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4699 KKASSERT(pte & pmap->pmap_bits[PG_V_IDX]);
4700 if (pte & pmap->pmap_bits[PG_M_IDX])
4702 if (pte & pmap->pmap_bits[PG_A_IDX])
4703 vm_page_flag_set(p, PG_REFERENCED);
4706 * (p) is not hard-busied.
4708 * If PMAP_ADVANCED mode is enabled we can safely
4709 * clear PG_MAPPED and PG_WRITEABLE only if PG_MAPPEDMULTI
4710 * is not set, atomically.
4712 pmap_removed_pte(p, pte);
4714 if (pte & pmap->pmap_bits[PG_V_IDX]) {
4715 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4716 if (pt_pv && vm_page_unwire_quick(pt_pv->pv_m))
4717 panic("pmap_remove: insufficient wirecount");
4719 if (pte & pmap->pmap_bits[PG_W_IDX])
4720 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4721 if (pte & pmap->pmap_bits[PG_G_IDX])
4722 cpu_invlpg((void *)va);
4723 pv_placemarker_wakeup(pmap, pte_placemark);
4724 #ifdef PMAP_ADVANCED
4726 if ((atomic_fetchadd_long(&oldm->md.interlock_count, -1) &
4727 0x7FFFFFFFFFFFFFFFLU) == 0x4000000000000001LU) {
4728 atomic_clear_long(&oldm->md.interlock_count,
4729 0x4000000000000000LU);
4730 wakeup(&oldm->md.interlock_count);
4737 * Removes this physical page from all physical maps in which it resides.
4738 * Reflects back modify bits to the pager.
4740 * This routine may not be called from an interrupt.
4742 * The page must be busied by its caller, preventing new ptes from being
4743 * installed. This allows us to assert that pmap_count is zero and safely
4744 * clear the MAPPED and WRITEABLE bits upon completion.
4748 pmap_remove_all(vm_page_t m)
4750 #ifdef PMAP_ADVANCED
4755 if (__predict_false(!pmap_initialized))
4759 * pmap_count doesn't cover fictitious pages, but PG_MAPPED does
4760 * (albeit without certain race protections).
4763 if (m->md.pmap_count == 0)
4766 if ((m->flags & PG_MAPPED) == 0)
4769 retry = ticks + hz * 60;
4771 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
4772 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4773 PMAP_PAGE_BACKING_RETRY;
4774 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4775 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4777 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4778 vm_page_flag_set(m, PG_REFERENCED);
4781 * NOTE: m is not hard-busied so it is not safe to
4782 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4783 * transition against them being set in
4786 pmap_removed_pte(m, ipte);
4790 * Cleanup various tracking counters. pt_pv can't go away
4791 * due to our wired ref.
4793 if (ipmap != &kernel_pmap) {
4796 spin_lock_shared(&ipmap->pm_spin);
4797 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4798 spin_unlock_shared(&ipmap->pm_spin);
4801 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4802 panic("pmap_remove_all: bad "
4803 "wire_count on pt_pv");
4806 &ipmap->pm_stats.resident_count, -1);
4809 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4810 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4811 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4812 cpu_invlpg((void *)iva);
4813 } PMAP_PAGE_BACKING_DONE;
4815 #ifdef PMAP_ADVANCED
4817 * If our scan lost a pte swap race oldm->md.interlock_count might
4818 * be set from the pmap_enter() code. If so sleep a little and try
4821 icount = atomic_fetchadd_long(&m->md.interlock_count,
4822 0x8000000000000000LU) +
4823 0x8000000000000000LU;
4825 while (icount & 0x3FFFFFFFFFFFFFFFLU) {
4826 tsleep_interlock(&m->md.interlock_count, 0);
4827 if (atomic_fcmpset_long(&m->md.interlock_count, &icount,
4828 icount | 0x4000000000000000LU)) {
4829 tsleep(&m->md.interlock_count, PINTERLOCKED,
4831 icount = m->md.interlock_count;
4832 if (retry - ticks > 0)
4834 panic("pmap_remove_all: cannot return interlock_count "
4836 m, m->md.interlock_count);
4841 * pmap_count should be zero but it is possible to race a pmap_enter()
4842 * replacement (see 'oldm'). Once it is zero it cannot become
4843 * non-zero because the page is hard-busied.
4845 if (m->md.pmap_count || m->md.writeable_count) {
4846 tsleep(&m->md.pmap_count, 0, "pgunm", 1);
4847 if (retry - ticks > 0)
4849 panic("pmap_remove_all: cannot return pmap_count "
4850 "to 0 (%p, %ld, %ld)",
4851 m, m->md.pmap_count, m->md.writeable_count);
4854 vm_page_flag_clear(m, PG_MAPPED | PG_MAPPEDMULTI | PG_WRITEABLE);
4858 * Removes the page from a particular pmap.
4860 * The page must be busied by the caller.
4863 pmap_remove_specific(pmap_t pmap_match, vm_page_t m)
4865 if (__predict_false(!pmap_initialized))
4869 * PG_MAPPED test works for both non-fictitious and fictitious pages.
4871 if ((m->flags & PG_MAPPED) == 0)
4874 PMAP_PAGE_BACKING_SCAN(m, pmap_match, ipmap, iptep, ipte, iva) {
4875 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4876 PMAP_PAGE_BACKING_RETRY;
4877 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4878 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4880 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4881 vm_page_flag_set(m, PG_REFERENCED);
4884 * NOTE: m is not hard-busied so it is not safe to
4885 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4886 * transition against them being set in
4889 pmap_removed_pte(m, ipte);
4893 * Cleanup various tracking counters. pt_pv can't go away
4894 * due to our wired ref.
4896 if (ipmap != &kernel_pmap) {
4899 spin_lock_shared(&ipmap->pm_spin);
4900 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4901 spin_unlock_shared(&ipmap->pm_spin);
4905 &ipmap->pm_stats.resident_count, -1);
4906 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4907 panic("pmap_remove_specific: bad "
4908 "wire_count on pt_pv");
4912 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4913 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4914 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4915 cpu_invlpg((void *)iva);
4916 } PMAP_PAGE_BACKING_DONE;
4920 * Set the physical protection on the specified range of this map
4921 * as requested. This function is typically only used for debug watchpoints
4924 * This function may not be called from an interrupt if the map is
4925 * not the kernel_pmap.
4927 * NOTE! For shared page table pages we just unmap the page.
4930 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4932 struct pmap_scan_info info;
4933 /* JG review for NX */
4937 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
4938 pmap_remove(pmap, sva, eva);
4941 if (prot & VM_PROT_WRITE)
4946 info.func = pmap_protect_callback;
4948 pmap_scan(&info, 1);
4953 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
4954 vm_pindex_t *pte_placemark,
4955 pv_entry_t pt_pv, vm_offset_t va,
4956 pt_entry_t *ptep, void *arg __unused)
4966 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4967 cbits &= ~pmap->pmap_bits[PG_A_IDX];
4968 cbits &= ~pmap->pmap_bits[PG_M_IDX];
4970 /* else unmanaged page, adjust bits, no wire changes */
4973 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
4975 if (pmap_enter_debug > 0) {
4977 kprintf("pmap_protect va=%lx ptep=%p "
4978 "pt_pv=%p cbits=%08lx\n",
4979 va, ptep, pt_pv, cbits
4983 if (pbits != cbits) {
4984 if (!pmap_inval_smp_cmpset(pmap, va,
4985 ptep, pbits, cbits)) {
4989 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4990 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4991 if (pbits & pmap->pmap_bits[PG_A_IDX])
4992 vm_page_flag_set(m, PG_REFERENCED);
4993 if (pbits & pmap->pmap_bits[PG_M_IDX])
4995 #if !defined(PMAP_ADVANCED)
4996 if (pbits & pmap->pmap_bits[PG_RW_IDX])
4997 atomic_add_long(&m->md.writeable_count, -1);
5002 pv_placemarker_wakeup(pmap, pte_placemark);
5006 * Insert the vm_page (m) at the virtual address (va), replacing any prior
5007 * mapping at that address. Set protection and wiring as requested.
5009 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5010 * possible. If it is we enter the page into the appropriate shared pmap
5011 * hanging off the related VM object instead of the passed pmap, then we
5012 * share the page table page from the VM object's pmap into the current pmap.
5014 * NOTE: This routine MUST insert the page into the pmap now, it cannot
5018 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5019 boolean_t wired, vm_map_entry_t entry)
5021 pv_entry_t pt_pv; /* page table */
5022 pv_entry_t pte_pv; /* page table entry */
5023 vm_pindex_t *pte_placemark;
5030 #if defined(PMAP_ADVANCED)
5037 va = trunc_page(va);
5038 #ifdef PMAP_DIAGNOSTIC
5040 panic("pmap_enter: toobig");
5041 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5042 panic("pmap_enter: invalid to pmap_enter page table "
5043 "pages (va: 0x%lx)", va);
5045 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
5046 kprintf("Warning: pmap_enter called on UVA with "
5049 db_print_backtrace();
5052 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
5053 kprintf("Warning: pmap_enter called on KVA without"
5056 db_print_backtrace();
5061 * Get the locked page table page (pt_pv) for our new page table
5062 * entry, allocating it if necessary.
5064 * There is no pte_pv for a terminal pte so the terminal pte will
5065 * be locked via pte_placemark.
5067 * Only MMU actions by the CPU itself can modify the ptep out from
5070 * If the pmap is still being initialized we assume existing
5073 * NOTE: Kernel mapppings do not track page table pages
5074 * (i.e. there is no pt_pv pt_pv structure).
5076 * NOTE: origpte here is 'tentative', used only to check for
5077 * the degenerate case where the entry already exists and
5080 if (__predict_false(pmap_initialized == FALSE)) {
5083 pte_placemark = NULL;
5087 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5088 KKASSERT(pte_pv == NULL);
5089 if (va >= VM_MAX_USER_ADDRESS) {
5093 pt_pv = pmap_allocpte(pmap, pmap_pt_pindex(va), NULL);
5094 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5100 pa = VM_PAGE_TO_PHYS(m);
5103 * Calculate the new PTE.
5105 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5106 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5108 newpte |= pmap->pmap_bits[PG_W_IDX];
5109 if (va < VM_MAX_USER_ADDRESS)
5110 newpte |= pmap->pmap_bits[PG_U_IDX];
5111 if ((m->flags & PG_FICTITIOUS) == 0)
5112 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5113 // if (pmap == &kernel_pmap)
5114 // newpte |= pgeflag;
5115 newpte |= pmap->pmap_cache_bits_pte[m->pat_mode];
5118 * It is possible for multiple faults to occur in threaded
5119 * environments, the existing pte might be correct.
5121 if (((origpte ^ newpte) &
5122 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5123 pmap->pmap_bits[PG_A_IDX])) == 0) {
5128 * Adjust page flags. The page is soft-busied or hard-busied, we
5129 * should be able to safely set PG_* flag bits even with the (shared)
5132 * The pmap_count and writeable_count is only tracked for
5133 * non-fictitious pages. As a bit of a safety, bump pmap_count
5134 * and set the PG_* bits before mapping the page. If another part
5135 * of the system does not properly hard-busy the page (against our
5136 * soft-busy or hard-busy) in order to remove mappings it might not
5137 * see the pte that we are about to add and thus will not be able to
5138 * drop pmap_count to 0.
5140 * The PG_MAPPED and PG_WRITEABLE flags are set for any type of page.
5142 * NOTE! PG_MAPPED and PG_WRITEABLE can only be cleared when
5143 * the page is hard-busied AND pmap_count is 0. This
5144 * interlocks our setting of the flags here.
5146 /*vm_page_spin_lock(m);*/
5147 #if !defined(PMAP_ADVANCED)
5148 if ((m->flags & PG_FICTITIOUS) == 0) {
5149 pmap_page_stats_adding(
5150 atomic_fetchadd_long(&m->md.pmap_count, 1));
5151 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5152 atomic_add_long(&m->md.writeable_count, 1);
5157 * In advanced mode we keep track of single mappings verses
5158 * multiple mappings in order to avoid unnecessary vm_page_protect()
5159 * calls (particularly on the kernel_map).
5161 * If non-advanced mode we track the mapping count for similar effect.
5163 * Avoid modifying the vm_page as much as possible, conditionalize
5164 * updates to reduce cache line ping-ponging.
5166 #if defined(PMAP_ADVANCED)
5171 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5172 nflags |= PG_WRITEABLE;
5173 if (flags & PG_MAPPED)
5174 nflags |= PG_MAPPEDMULTI;
5175 if (flags == (flags | nflags))
5177 if (atomic_fcmpset_int(&m->flags, &flags, flags | nflags))
5181 if (newpte & pmap->pmap_bits[PG_RW_IDX]) {
5182 if ((m->flags & (PG_MAPPED | PG_WRITEABLE)) == 0)
5183 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
5185 if ((m->flags & PG_MAPPED) == 0)
5186 vm_page_flag_set(m, PG_MAPPED);
5189 /*vm_page_spin_unlock(m);*/
5192 * A race can develop when replacing an existing mapping. The new
5193 * page has been busied and the pte is placemark-locked, but the
5194 * old page could be ripped out from under us at any time by
5197 * When PMAP_ADVANCED is disabled the race is handled by having the
5198 * backing scans check pmap_count and writeable_count when doing
5199 * operations that should ensure one becomes 0.
5201 * When PMAP_ADVANCED is enabled, if we do nothing, a concurrent
5202 * backing scan may clear PG_WRITEABLE and PG_MAPPED before we can
5205 opa = origpte & PG_FRAME;
5206 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5207 oldm = PHYS_TO_VM_PAGE(opa);
5208 KKASSERT(opa == oldm->phys_addr);
5209 KKASSERT(entry != NULL);
5210 #ifdef PMAP_ADVANCED
5211 atomic_add_long(&oldm->md.interlock_count, 1);
5218 * Swap the new and old PTEs and perform any necessary SMP
5221 if ((prot & VM_PROT_NOSYNC) || (opa == 0 && pt_pv != NULL)) {
5223 * Explicitly permitted to avoid pmap cpu mask synchronization
5224 * or the prior content of a non-kernel-related pmap was
5227 origpte = atomic_swap_long(ptep, newpte);
5229 cpu_invlpg((void *)va);
5232 * Not permitted to avoid pmap cpu mask synchronization
5233 * or there prior content being replaced or this is a kernel
5236 * Due to other kernel optimizations, we cannot assume a
5237 * 0->non_zero transition of *ptep can be done with a swap.
5239 origpte = pmap_inval_smp(pmap, va, 1, ptep, newpte);
5241 opa = origpte & PG_FRAME;
5244 if (pmap_enter_debug > 0) {
5246 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5247 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5249 origpte, newpte, ptep,
5250 pte_pv, pt_pv, opa, prot);
5255 * Account for the changes in the pt_pv and pmap.
5257 * Retain the same wiring count due to replacing an existing page,
5258 * or bump the wiring count for a new page.
5260 if (pt_pv && opa == 0) {
5261 vm_page_wire_quick(pt_pv->pv_m);
5262 atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
5264 if (wired && (origpte & pmap->pmap_bits[PG_W_IDX]) == 0)
5265 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5268 * Account for the removal of the old page. pmap and pt_pv stats
5269 * have already been fully adjusted for both.
5271 * WARNING! oldm is not soft or hard-busied. The pte at worst can
5272 * only be removed out from under us since we hold the
5273 * placemarker. So if it is still there, it must not have
5276 * WARNING! When PMAP_ADVANCED is enabled, a backing scan
5277 * can clear PG_WRITEABLE and/or PG_MAPPED and rip oldm
5278 * away from us, possibly even freeing or paging it, and
5279 * not setting our dirtying below.
5281 * To deal with this, oldm->md.interlock_count is bumped
5282 * to indicate that we might (only might) have won the pte
5283 * swap race, and then released below.
5285 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5286 KKASSERT(oldm == PHYS_TO_VM_PAGE(opa));
5287 if (origpte & pmap->pmap_bits[PG_M_IDX])
5288 vm_page_dirty(oldm);
5289 if (origpte & pmap->pmap_bits[PG_A_IDX])
5290 vm_page_flag_set(oldm, PG_REFERENCED);
5293 * NOTE: oldm is not hard-busied so it is not safe to
5294 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
5295 * transition against them being set in
5298 pmap_removed_pte(oldm, origpte);
5300 #ifdef PMAP_ADVANCED
5302 if ((atomic_fetchadd_long(&oldm->md.interlock_count, -1) &
5303 0x7FFFFFFFFFFFFFFFLU) == 0x4000000000000001LU) {
5304 atomic_clear_long(&oldm->md.interlock_count,
5305 0x4000000000000000LU);
5306 wakeup(&oldm->md.interlock_count);
5312 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5313 (m->flags & PG_MAPPED));
5316 * Cleanup the pv entry, allowing other accessors. If the new page
5317 * is not managed but we have a pte_pv (which was locking our
5318 * operation), we can free it now. pte_pv->pv_m should be NULL.
5321 pv_placemarker_wakeup(pmap, pte_placemark);
5327 * Make a temporary mapping for a physical address. This is only intended
5328 * to be used for panic dumps.
5330 * The caller is responsible for calling smp_invltlb().
5333 pmap_kenter_temporary(vm_paddr_t pa, long i)
5335 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5336 return ((void *)crashdumpmap);
5340 #define MAX_INIT_PT (96)
5343 * This routine preloads the ptes for a given object into the specified pmap.
5344 * This eliminates the blast of soft faults on process startup and
5345 * immediately after an mmap.
5347 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5351 pmap_object_init_pt(pmap_t pmap, vm_map_entry_t entry,
5352 vm_offset_t addr, vm_size_t size, int limit)
5355 vm_prot_t prot = entry->protection;
5356 vm_object_t object = entry->ba.object;
5357 vm_pindex_t pindex = atop(entry->ba.offset + (addr - entry->ba.start));
5358 struct rb_vm_page_scan_info info;
5363 * We can't preinit if read access isn't set or there is no pmap
5366 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5370 * We can't preinit if the pmap is not the current pmap
5372 lp = curthread->td_lwp;
5373 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5377 * Misc additional checks
5379 psize = x86_64_btop(size);
5381 if ((object->type != OBJT_VNODE) ||
5382 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5383 (object->resident_page_count > MAX_INIT_PT))) {
5387 if (pindex + psize > object->size) {
5388 if (object->size < pindex)
5390 psize = object->size - pindex;
5397 * If everything is segment-aligned do not pre-init here. Instead
5398 * allow the normal vm_fault path to pass a segment hint to
5399 * pmap_enter() which will then use an object-referenced shared
5402 if ((addr & SEG_MASK) == 0 &&
5403 (ctob(psize) & SEG_MASK) == 0 &&
5404 (ctob(pindex) & SEG_MASK) == 0) {
5409 * Use a red-black scan to traverse the requested range and load
5410 * any valid pages found into the pmap.
5412 * We cannot safely scan the object's memq without holding the
5415 info.start_pindex = pindex;
5416 info.end_pindex = pindex + psize - 1;
5421 info.object = object;
5425 * By using the NOLK scan, the callback function must be sure
5426 * to return -1 if the VM page falls out of the object.
5428 vm_object_hold_shared(object);
5429 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5430 pmap_object_init_pt_callback, &info);
5431 vm_object_drop(object);
5439 pmap_object_init_pt_callback(vm_page_t p, void *data)
5441 struct rb_vm_page_scan_info *info = data;
5442 vm_pindex_t rel_index;
5446 * don't allow an madvise to blow away our really
5447 * free pages allocating pv entries.
5449 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5450 vmstats.v_free_count < vmstats.v_free_reserved) {
5455 * Ignore list markers and ignore pages we cannot instantly
5456 * busy (while holding the object token).
5458 if (p->flags & PG_MARKER)
5463 if (vm_page_busy_try(p, TRUE))
5466 if (vm_page_sbusy_try(p))
5469 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5470 (p->flags & PG_FICTITIOUS) == 0) {
5471 if ((p->queue - p->pc) == PQ_CACHE) {
5472 if (hard_busy == 0) {
5473 vm_page_sbusy_drop(p);
5477 vm_page_deactivate(p);
5479 rel_index = p->pindex - info->start_pindex;
5480 pmap_enter(info->pmap, info->addr + x86_64_ptob(rel_index), p,
5481 VM_PROT_READ, FALSE, info->entry);
5486 vm_page_sbusy_drop(p);
5489 * We are using an unlocked scan (that is, the scan expects its
5490 * current element to remain in the tree on return). So we have
5491 * to check here and abort the scan if it isn't.
5493 if (p->object != info->object)
5502 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5505 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5508 * The address must reside within a vm_map mapped range to ensure that the
5509 * page table doesn't get ripped out from under us.
5511 * XXX This is safe only because page table pages are not freed.
5514 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5518 /*spin_lock(&pmap->pm_spin);*/
5519 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5520 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5521 /*spin_unlock(&pmap->pm_spin);*/
5525 /*spin_unlock(&pmap->pm_spin);*/
5530 * Change the wiring attribute for a pmap/va pair. The mapping must already
5531 * exist in the pmap. The mapping may or may not be managed. The wiring in
5532 * the page is not changed, the page is returned so the caller can adjust
5533 * its wiring (the page is not locked in any way).
5535 * Wiring is not a hardware characteristic so there is no need to invalidate
5536 * TLB. However, in an SMP environment we must use a locked bus cycle to
5537 * update the pte (if we are not using the pmap_inval_*() API that is)...
5538 * it's ok to do this for simple wiring changes.
5541 pmap_unwire(pmap_t pmap, vm_offset_t va)
5552 * Assume elements in the kernel pmap are stable
5554 if (pmap == &kernel_pmap) {
5555 if (pmap_pt(pmap, va) == 0)
5557 ptep = pmap_pte_quick(pmap, va);
5558 if (pmap_pte_v(pmap, ptep)) {
5559 if (pmap_pte_w(pmap, ptep))
5560 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5561 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5562 pa = *ptep & PG_FRAME;
5563 m = PHYS_TO_VM_PAGE(pa);
5569 * We can only [un]wire pmap-local pages (we cannot wire
5572 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5576 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5577 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5582 if (pmap_pte_w(pmap, ptep)) {
5583 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5586 /* XXX else return NULL so caller doesn't unwire m ? */
5588 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5590 pa = *ptep & PG_FRAME;
5591 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5598 * Copy the range specified by src_addr/len from the source map to
5599 * the range dst_addr/len in the destination map.
5601 * This routine is only advisory and need not do anything.
5604 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5605 vm_size_t len, vm_offset_t src_addr)
5612 * Zero the specified physical page.
5614 * This function may be called from an interrupt and no locking is
5618 pmap_zero_page(vm_paddr_t phys)
5620 vm_offset_t va = PHYS_TO_DMAP(phys);
5622 pagezero((void *)va);
5628 * Zero part of a physical page by mapping it into memory and clearing
5629 * its contents with bzero.
5631 * off and size may not cover an area beyond a single hardware page.
5634 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5636 vm_offset_t virt = PHYS_TO_DMAP(phys);
5638 bzero((char *)virt + off, size);
5644 * Copy the physical page from the source PA to the target PA.
5645 * This function may be called from an interrupt. No locking
5649 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5651 vm_offset_t src_virt, dst_virt;
5653 src_virt = PHYS_TO_DMAP(src);
5654 dst_virt = PHYS_TO_DMAP(dst);
5655 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5659 * pmap_copy_page_frag:
5661 * Copy the physical page from the source PA to the target PA.
5662 * This function may be called from an interrupt. No locking
5666 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5668 vm_offset_t src_virt, dst_virt;
5670 src_virt = PHYS_TO_DMAP(src);
5671 dst_virt = PHYS_TO_DMAP(dst);
5673 bcopy((char *)src_virt + (src & PAGE_MASK),
5674 (char *)dst_virt + (dst & PAGE_MASK),
5679 * Remove all pages from specified address space this aids process exit
5680 * speeds. Also, this code may be special cased for the current process
5684 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5686 pmap_remove_noinval(pmap, sva, eva);
5691 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5692 * routines are inline, and a lot of things compile-time evaluate.
5694 * Currently only used to test the 'M'odified bit. If the page
5695 * is not PG_WRITEABLE, the 'M'odified bit cannot be set and we
5696 * return immediately. Fictitious pages do not track this bit.
5700 pmap_testbit(vm_page_t m, int bit)
5704 if (__predict_false(!pmap_initialized || (m->flags & PG_FICTITIOUS)))
5707 * Nothing to do if all the mappings are already read-only.
5708 * The page's [M]odify bits have already been synchronized
5709 * to the vm_page_t and cleaned out.
5711 #ifdef PMAP_ADVANCED
5712 if (bit == PG_M_IDX && (m->flags & PG_WRITEABLE) == 0)
5715 if (bit == PG_M_IDX && m->md.writeable_count == 0)
5720 * Iterate the mapping
5722 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5723 if (ipte & ipmap->pmap_bits[bit]) {
5727 } PMAP_PAGE_BACKING_DONE;
5732 * This routine is used to modify bits in ptes. Only one bit should be
5733 * specified. PG_RW requires special handling. This call works with
5734 * any sort of mapped page. PG_FICTITIOUS pages might not be optimal.
5736 * Caller must NOT hold any spin locks
5737 * Caller must hold (m) hard-busied
5739 * NOTE: When clearing PG_M we could also (not implemented) drop
5740 * through to the PG_RW code and clear PG_RW too, forcing
5741 * a fault on write to redetect PG_M for virtual kernels, but
5742 * it isn't necessary since virtual kernels invalidate the
5743 * pte when they clear the VPTE_M bit in their virtual page
5746 * NOTE: Does not re-dirty the page when clearing only PG_M.
5748 * NOTE: Because we do not lock the pv, *pte can be in a state of
5749 * flux. Despite this the value of *pte is still somewhat
5750 * related while we hold the vm_page spin lock.
5752 * *pte can be zero due to this race. Since we are clearing
5753 * bits we basically do no harm when this race occurs.
5757 pmap_clearbit(vm_page_t m, int bit_index)
5761 #ifdef PMAP_ADVANCED
5766 * Too early in the boot
5768 if (__predict_false(!pmap_initialized)) {
5769 if (bit_index == PG_RW_IDX)
5770 vm_page_flag_clear(m, PG_WRITEABLE);
5773 #ifdef PMAP_ADVANCED
5774 if ((m->flags & (PG_MAPPED | PG_WRITEABLE)) == 0)
5779 * Being asked to clear other random bits, we don't track them
5780 * so we have to iterate.
5782 * When PMAP_ADVANCED is enabled, pmap_clear_reference()
5783 * is called (into here) with the page hard-busied to check whether
5784 * the page is still mapped and will clear PG_MAPPED and PG_WRITEABLE
5787 if (bit_index != PG_RW_IDX) {
5789 #ifdef PMAP_ADVANCED
5795 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5797 #ifdef PMAP_ADVANCED
5801 if (ipte & ipmap->pmap_bits[bit_index]) {
5802 atomic_clear_long(iptep,
5803 ipmap->pmap_bits[bit_index]);
5805 } PMAP_PAGE_BACKING_DONE;
5807 #ifdef PMAP_ADVANCED
5809 icount = atomic_fetchadd_long(&m->md.interlock_count,
5810 0x8000000000000000LU);
5811 if ((icount & 0x3FFFFFFFFFFFFFFFLU) == 0) {
5812 vm_page_flag_clear(m, PG_MAPPED |
5823 * Being asked to clear the RW bit.
5825 * Nothing to do if all the mappings are already read-only
5827 #ifdef PMAP_ADVANCED
5828 if ((m->flags & PG_WRITEABLE) == 0)
5831 if (m->md.writeable_count == 0)
5836 * Iterate the mappings and check.
5838 retry = ticks + hz * 60;
5841 * Clear PG_RW. This also clears PG_M and marks the page dirty if
5844 * Since the caller holds the page hard-busied we can safely clear
5845 * PG_WRITEABLE, and callers expect us to for the PG_RW_IDX path.
5847 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5849 if ((ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5852 if ((ipte & ipmap->pmap_bits[PG_RW_IDX]) == 0)
5854 npte = ipte & ~(ipmap->pmap_bits[PG_RW_IDX] |
5855 ipmap->pmap_bits[PG_M_IDX]);
5856 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, npte))
5857 PMAP_PAGE_BACKING_RETRY;
5858 if (ipte & ipmap->pmap_bits[PG_M_IDX])
5862 * NOTE: m is not hard-busied so it is not safe to
5863 * clear PG_WRITEABLE on the 1->0 transition
5864 * against it being set in pmap_enter().
5866 * pmap_count and writeable_count are only applicable
5867 * to non-fictitious pages (PG_MANAGED_IDX from pte)
5869 #if !defined(PMAP_ADVANCED)
5870 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX])
5871 atomic_add_long(&m->md.writeable_count, -1);
5873 } PMAP_PAGE_BACKING_DONE;
5875 #ifdef PMAP_ADVANCED
5877 * If our scan lost a pte swap race oldm->md.interlock_count might
5878 * be set from the pmap_enter() code. If so sleep a little and try
5881 * Use an atomic op to access interlock_count to ensure ordering.
5883 icount = atomic_fetchadd_long(&m->md.interlock_count,
5884 0x8000000000000000LU) +
5885 0x8000000000000000LU;
5887 while (icount & 0x3FFFFFFFFFFFFFFFLU) {
5888 tsleep_interlock(&m->md.interlock_count, 0);
5889 if (atomic_fcmpset_long(&m->md.interlock_count, &icount,
5890 icount | 0x4000000000000000LU)) {
5891 tsleep(&m->md.interlock_count, PINTERLOCKED,
5893 icount = m->md.interlock_count;
5894 if (retry - ticks > 0)
5896 panic("pmap_clearbit: cannot return interlock_count "
5898 m, m->md.interlock_count);
5903 * writeable_count should be zero but it is possible to race
5904 * a pmap_enter() replacement (see 'oldm'). Once it is zero
5905 * it cannot become non-zero because the page is hard-busied.
5907 if (m->md.writeable_count != 0) {
5908 tsleep(&m->md.writeable_count, 0, "pgwab", 1);
5909 if (retry - ticks > 0)
5911 panic("pmap_clearbit: cannot return writeable_count "
5913 m->md.writeable_count);
5916 vm_page_flag_clear(m, PG_WRITEABLE);
5920 * Lower the permission for all mappings to a given page.
5922 * Page must be hard-busied by caller. Because the page is busied by the
5923 * caller, this should not be able to race a pmap_enter().
5926 pmap_page_protect(vm_page_t m, vm_prot_t prot)
5928 /* JG NX support? */
5929 if ((prot & VM_PROT_WRITE) == 0) {
5930 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
5932 * NOTE: pmap_clearbit(.. PG_RW) also clears
5933 * the PG_WRITEABLE flag in (m).
5935 pmap_clearbit(m, PG_RW_IDX);
5943 pmap_phys_address(vm_pindex_t ppn)
5945 return (x86_64_ptob(ppn));
5949 * Return a count of reference bits for a page, clearing those bits.
5950 * It is not necessary for every reference bit to be cleared, but it
5951 * is necessary that 0 only be returned when there are truly no
5952 * reference bits set.
5954 * XXX: The exact number of bits to check and clear is a matter that
5955 * should be tested and standardized at some point in the future for
5956 * optimal aging of shared pages.
5958 * This routine may not block.
5961 pmap_ts_referenced(vm_page_t m)
5966 if (__predict_false(!pmap_initialized || (m->flags & PG_FICTITIOUS)))
5968 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5969 if (ipte & ipmap->pmap_bits[PG_A_IDX]) {
5970 npte = ipte & ~ipmap->pmap_bits[PG_A_IDX];
5971 if (!atomic_cmpset_long(iptep, ipte, npte))
5972 PMAP_PAGE_BACKING_RETRY;
5977 } PMAP_PAGE_BACKING_DONE;
5984 * Return whether or not the specified physical page was modified
5985 * in any physical maps.
5988 pmap_is_modified(vm_page_t m)
5992 res = pmap_testbit(m, PG_M_IDX);
5997 * Clear the modify bit on the vm_page.
5999 * The page must be hard-busied.
6002 pmap_clear_modify(vm_page_t m)
6004 pmap_clearbit(m, PG_M_IDX);
6008 * pmap_clear_reference:
6010 * Clear the reference bit on the specified physical page.
6013 pmap_clear_reference(vm_page_t m)
6015 pmap_clearbit(m, PG_A_IDX);
6019 * Miscellaneous support routines follow
6024 x86_64_protection_init(void)
6030 * NX supported? (boot time loader.conf override only)
6032 * -1 Automatic (sets mode 1)
6034 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
6035 * 2 NX implemented for all cases
6037 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
6038 if ((amd_feature & AMDID_NX) == 0) {
6039 pmap_bits_default[PG_NX_IDX] = 0;
6041 } else if (pmap_nx_enable < 0) {
6042 pmap_nx_enable = 1; /* default to mode 1 (READ) */
6046 * 0 is basically read-only access, but also set the NX (no-execute)
6047 * bit when VM_PROT_EXECUTE is not specified.
6049 kp = protection_codes;
6050 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
6052 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
6054 * This case handled elsewhere
6058 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
6060 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
6062 if (pmap_nx_enable >= 1)
6063 *kp = pmap_bits_default[PG_NX_IDX];
6065 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6066 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6068 * Execute requires read access
6072 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6073 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6075 * Write without execute is RW|NX
6076 * (pmap_nx_enable mode >= 2)
6078 *kp = pmap_bits_default[PG_RW_IDX];
6079 if (pmap_nx_enable >= 2)
6080 *kp |= pmap_bits_default[PG_NX_IDX];
6082 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6083 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6085 * Write with execute is RW
6087 *kp = pmap_bits_default[PG_RW_IDX];
6095 * Map a set of physical memory pages into the kernel virtual
6096 * address space. Return a pointer to where it is mapped. This
6097 * routine is intended to be used for mapping device memory,
6100 * NOTE: We can't use pgeflag unless we invalidate the pages one at
6103 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6104 * work whether the cpu supports PAT or not. The remaining PAT
6105 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6109 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6111 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6115 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6117 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6121 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6123 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6127 * Map a set of physical memory pages into the kernel virtual
6128 * address space. Return a pointer to where it is mapped. This
6129 * routine is intended to be used for mapping device memory,
6133 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6135 vm_offset_t va, tmpva, offset;
6139 offset = pa & PAGE_MASK;
6140 size = roundup(offset + size, PAGE_SIZE);
6142 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6144 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6146 pa = pa & ~PAGE_MASK;
6147 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6148 pte = vtopte(tmpva);
6150 kernel_pmap.pmap_bits[PG_RW_IDX] |
6151 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
6152 kernel_pmap.pmap_cache_bits_pte[mode];
6153 tmpsize -= PAGE_SIZE;
6157 pmap_invalidate_range(&kernel_pmap, va, va + size);
6158 pmap_invalidate_cache_range(va, va + size);
6160 return ((void *)(va + offset));
6164 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6166 vm_offset_t base, offset;
6168 base = va & ~PAGE_MASK;
6169 offset = va & PAGE_MASK;
6170 size = roundup(offset + size, PAGE_SIZE);
6171 pmap_qremove(va, size >> PAGE_SHIFT);
6172 kmem_free(&kernel_map, base, size);
6176 * Sets the memory attribute for the specified page.
6179 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6185 * If "m" is a normal page, update its direct mapping. This update
6186 * can be relied upon to perform any cache operations that are
6187 * required for data coherence.
6189 if ((m->flags & PG_FICTITIOUS) == 0)
6190 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6194 * Change the PAT attribute on an existing kernel memory map. Caller
6195 * must ensure that the virtual memory in question is not accessed
6196 * during the adjustment.
6198 * If the va is within the DMAP we cannot use vtopte() because the DMAP
6199 * utilizes 2MB or 1GB pages. 2MB is forced atm so calculate the pd_entry
6200 * pointer based on that.
6203 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6210 panic("pmap_change_attr: va is NULL");
6211 base = trunc_page(va);
6213 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
6216 KKASSERT(va < DMapMaxAddress);
6217 pd = (pd_entry_t *)PHYS_TO_DMAP(DMPDphys);
6218 pd += (va - DMAP_MIN_ADDRESS) >> PDRSHIFT;
6220 while ((long)count > 0) {
6222 (*pd & ~(pd_entry_t)(kernel_pmap.pmap_cache_mask_pde)) |
6223 kernel_pmap.pmap_cache_bits_pde[mode];
6224 count -= NBPDR / PAGE_SIZE;
6232 (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask_pte)) |
6233 kernel_pmap.pmap_cache_bits_pte[mode];
6239 changed = 1; /* XXX: not optimal */
6242 * Flush CPU caches if required to make sure any data isn't cached that
6243 * shouldn't be, etc.
6246 pmap_invalidate_range(&kernel_pmap, base, va);
6247 pmap_invalidate_cache_range(base, va);
6252 * perform the pmap work for mincore
6255 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6257 pt_entry_t *ptep, pte;
6261 ptep = pmap_pte(pmap, addr);
6263 if (ptep && (pte = *ptep) != 0) {
6266 val = MINCORE_INCORE;
6267 pa = pte & PG_FRAME;
6268 if (pte & pmap->pmap_bits[PG_MANAGED_IDX])
6269 m = PHYS_TO_VM_PAGE(pa);
6276 if (pte & pmap->pmap_bits[PG_M_IDX])
6277 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6280 * Modified by someone
6282 else if (m && (m->dirty || pmap_is_modified(m)))
6283 val |= MINCORE_MODIFIED_OTHER;
6286 * Referenced by us, or someone else.
6288 if (pte & pmap->pmap_bits[PG_A_IDX]) {
6289 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6290 } else if (m && ((m->flags & PG_REFERENCED) ||
6291 pmap_ts_referenced(m))) {
6292 val |= MINCORE_REFERENCED_OTHER;
6293 vm_page_flag_set(m, PG_REFERENCED);
6300 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
6301 * vmspace will be ref'd and the old one will be deref'd.
6303 * The vmspace for all lwps associated with the process will be adjusted
6304 * and cr3 will be reloaded if any lwp is the current lwp.
6306 * The process must hold the vmspace->vm_map.token for oldvm and newvm
6309 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6311 struct vmspace *oldvm;
6314 oldvm = p->p_vmspace;
6315 if (oldvm != newvm) {
6318 p->p_vmspace = newvm;
6319 KKASSERT(p->p_nthreads == 1);
6320 lp = RB_ROOT(&p->p_lwp_tree);
6321 pmap_setlwpvm(lp, newvm);
6328 * Set the vmspace for a LWP. The vmspace is almost universally set the
6329 * same as the process vmspace, but virtual kernels need to swap out contexts
6330 * on a per-lwp basis.
6332 * Caller does not necessarily hold any vmspace tokens. Caller must control
6333 * the lwp (typically be in the context of the lwp). We use a critical
6334 * section to protect against statclock and hardclock (statistics collection).
6337 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6339 struct vmspace *oldvm;
6343 oldvm = lp->lwp_vmspace;
6345 if (oldvm != newvm) {
6348 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6349 lp->lwp_vmspace = newvm;
6350 if (td->td_lwp == lp) {
6351 pmap = vmspace_pmap(newvm);
6352 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6353 if (pmap->pm_active_lock & CPULOCK_EXCL)
6354 pmap_interlock_wait(newvm);
6355 #if defined(SWTCH_OPTIM_STATS)
6358 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6359 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6360 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6361 td->td_pcb->pcb_cr3_iso =
6362 vtophys(pmap->pm_pml4_iso);
6363 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6365 td->td_pcb->pcb_cr3_iso = 0;
6366 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6368 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6369 td->td_pcb->pcb_cr3 = KPML4phys;
6370 td->td_pcb->pcb_cr3_iso = 0;
6371 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6373 panic("pmap_setlwpvm: unknown pmap type\n");
6377 * The MMU separation fields needs to be updated.
6378 * (it can't access the pcb directly from the
6379 * restricted user pmap).
6382 struct trampframe *tramp;
6384 tramp = &pscpu->trampoline;
6385 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6386 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6387 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6388 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6389 /* tr_pcb_rsp doesn't change */
6393 * In kernel-land we always use the normal PML4E
6394 * so the kernel is fully mapped and can also access
6397 load_cr3(td->td_pcb->pcb_cr3);
6398 pmap = vmspace_pmap(oldvm);
6399 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6407 * Called when switching to a locked pmap, used to interlock against pmaps
6408 * undergoing modifications to prevent us from activating the MMU for the
6409 * target pmap until all such modifications have completed. We have to do
6410 * this because the thread making the modifications has already set up its
6411 * SMP synchronization mask.
6413 * This function cannot sleep!
6418 pmap_interlock_wait(struct vmspace *vm)
6420 struct pmap *pmap = &vm->vm_pmap;
6422 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6424 KKASSERT(curthread->td_critcount >= 2);
6425 DEBUG_PUSH_INFO("pmap_interlock_wait");
6426 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6428 lwkt_process_ipiq();
6436 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6439 if ((obj == NULL) || (size < NBPDR) ||
6440 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6444 addr = roundup2(addr, NBPDR);
6449 * Used by kmalloc/kfree, page already exists at va
6452 pmap_kvtom(vm_offset_t va)
6454 pt_entry_t *ptep = vtopte(va);
6456 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6460 * Initialize machine-specific shared page directory support. This
6461 * is executed when a VM object is created.
6464 pmap_object_init(vm_object_t object)
6469 * Clean up machine-specific shared page directory support. This
6470 * is executed when a VM object is destroyed.
6473 pmap_object_free(vm_object_t object)
6478 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6479 * VM page and issue a pginfo->callback.
6483 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6484 vm_pindex_t *pte_placemark,
6485 pv_entry_t pt_pv, vm_offset_t va,
6486 pt_entry_t *ptep, void *arg)
6488 struct pmap_pgscan_info *pginfo = arg;
6495 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
6497 * Try to busy the page while we hold the pte_placemark locked.
6499 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6500 if (vm_page_busy_try(m, TRUE) == 0) {
6501 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6503 * The callback is issued with the pt_pv
6506 pv_placemarker_wakeup(pmap, pte_placemark);
6508 vm_page_wire_quick(pt_pv->pv_m);
6511 if (pginfo->callback(pginfo, va, m) < 0)
6515 if (vm_page_unwire_quick(pt_pv->pv_m)) {
6516 panic("pmap_pgscan: bad wire_"
6522 pv_placemarker_wakeup(pmap, pte_placemark);
6525 ++pginfo->busycount;
6526 pv_placemarker_wakeup(pmap, pte_placemark);
6530 * Shared page table or unmanaged page (sharept or !sharept)
6532 pv_placemarker_wakeup(pmap, pte_placemark);
6537 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6539 struct pmap_scan_info info;
6541 pginfo->offset = pginfo->beg_addr;
6542 info.pmap = pginfo->pmap;
6543 info.sva = pginfo->beg_addr;
6544 info.eva = pginfo->end_addr;
6545 info.func = pmap_pgscan_callback;
6547 pmap_scan(&info, 0);
6549 pginfo->offset = pginfo->end_addr;
6553 * Wait for a placemarker that we do not own to clear. The placemarker
6554 * in question is not necessarily set to the pindex we want, we may have
6555 * to wait on the element because we want to reserve it ourselves.
6557 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6558 * PM_NOPLACEMARK, so it does not interfere with placemarks
6559 * which have already been woken up.
6561 * NOTE: This routine is called without the pmap spin-lock and so can
6562 * race changes to *pmark. Due to the sensitivity of the routine
6563 * to possible MULTIPLE interactions from other cpus, and the
6564 * overloading of the WAKEUP bit on PM_NOPLACEMARK, we have to
6565 * use a cmpset loop to avoid a race that might cause the WAKEUP
6568 * Caller is expected to retry its operation upon return.
6572 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6578 while (mark != PM_NOPLACEMARK) {
6579 tsleep_interlock(pmark, 0);
6580 if (atomic_fcmpset_long(pmark, &mark,
6581 mark | PM_PLACEMARK_WAKEUP)) {
6582 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6589 * Wakeup a placemarker that we own. Replace the entry with
6590 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6594 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6598 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6599 KKASSERT(pindex != PM_NOPLACEMARK);
6600 if (pindex & PM_PLACEMARK_WAKEUP)