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, pde) \
145 ((*(pd_entry_t *)pde & 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 static struct pmap iso_pmap;
225 static struct pmap kernel_pmap_store;
226 struct pmap *kernel_pmap = &kernel_pmap_store;
228 vm_paddr_t avail_start; /* PA of first available physical page */
229 vm_paddr_t avail_end; /* PA of last available physical page */
230 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
231 vm_offset_t virtual2_end;
232 vm_offset_t virtual_start; /* VA of first avail page (after kernel BSS) */
233 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
234 vm_offset_t KvaStart; /* VA start of KVA space */
235 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
236 vm_offset_t KvaSize; /* max size of KVA space */
237 vm_offset_t DMapMaxAddress;
239 /* Has pmap_init completed? */
240 __read_frequently static boolean_t pmap_initialized = FALSE;
241 //static int pgeflag; /* PG_G or-in */
242 static uint64_t PatMsr; /* value of MSR_PAT */
245 static vm_paddr_t dmaplimit;
246 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
248 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
249 static pt_entry_t pat_pde_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
251 static uint64_t KPTbase;
252 static uint64_t KPTphys;
253 static uint64_t KPDphys; /* phys addr of kernel level 2 */
254 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
255 uint64_t KPDPphys; /* phys addr of kernel level 3 */
256 uint64_t KPML4phys; /* phys addr of kernel level 4 */
258 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
259 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
262 * Data for the pv entry allocation mechanism
264 __read_mostly static vm_zone_t pvzone;
265 __read_mostly static int pmap_pagedaemon_waken = 0;
266 static struct vm_zone pvzone_store;
267 static struct pv_entry *pvinit;
270 * All those kernel PT submaps that BSD is so fond of
272 pt_entry_t *CMAP1 = NULL;
273 caddr_t CADDR1 = NULL, ptvmmap = NULL;
274 static pt_entry_t *msgbufmap, *ptmmap;
275 struct msgbuf *msgbufp = NULL;
278 * PG_* bits for regular (x86) pmap.
280 __read_frequently static uint64_t pmap_bits_default[PG_BITS_SIZE] = {
281 [TYPE_IDX] = REGULAR_PMAP,
282 [PG_V_IDX] = X86_PG_V,
283 [PG_RW_IDX] = X86_PG_RW,
284 [PG_U_IDX] = X86_PG_U,
285 [PG_A_IDX] = X86_PG_A,
286 [PG_M_IDX] = X86_PG_M,
287 [PG_PS_IDX] = X86_PG_PS,
288 [PG_G_IDX] = X86_PG_G,
289 [PG_W_IDX] = X86_PG_AVAIL1,
290 [PG_MANAGED_IDX] = X86_PG_AVAIL2,
291 [PG_N_IDX] = X86_PG_NC_PWT | X86_PG_NC_PCD,
292 [PG_NX_IDX] = X86_PG_NX,
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 static 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 static 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 static 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 * We have removed a managed pte. The page might not be hard or soft-busied
417 * at this point so we have to be careful.
419 * If advanced mode is enabled we can clear PG_MAPPED/WRITEABLE only if
420 * MAPPEDMULTI is not set. This must be done atomically against possible
421 * concurrent pmap_enter()s occurring at the same time. If MULTI is set
422 * then the kernel may have to call vm_page_protect() later on to clean
423 * the bits up. This is particularly important for kernel_map/kernel_object
424 * mappings due to the expense of scanning the kernel_object's vm_backing's.
426 * If advanced mode is not enabled we update our tracking counts and
427 * synchronize PG_MAPPED/WRITEABLE later on in pmap_mapped_sync().
431 pmap_removed_pte(vm_page_t m, pt_entry_t pte)
438 while ((flags & PG_MAPPEDMULTI) == 0) {
439 nflags = flags & ~(PG_MAPPED | PG_WRITEABLE);
440 if (atomic_fcmpset_int(&m->flags, &flags, nflags))
446 * Move the kernel virtual free pointer to the next
447 * 2MB. This is used to help improve performance
448 * by using a large (2MB) page for much of the kernel
449 * (.text, .data, .bss)
453 pmap_kmem_choose(vm_offset_t addr)
455 vm_offset_t newaddr = addr;
457 newaddr = roundup2(addr, NBPDR);
462 * Returns the pindex of a page table entry (representing a terminal page).
463 * There are NUPTE_TOTAL page table entries possible (a huge number)
465 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
466 * We want to properly translate negative KVAs.
470 pmap_pte_pindex(vm_offset_t va)
472 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
476 * Returns the pindex of a page table.
480 pmap_pt_pindex(vm_offset_t va)
482 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
486 * Returns the pindex of a page directory.
490 pmap_pd_pindex(vm_offset_t va)
492 return (NUPTE_TOTAL + NUPT_TOTAL +
493 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
498 pmap_pdp_pindex(vm_offset_t va)
500 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
501 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
506 pmap_pml4_pindex(void)
508 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
512 * Return various *clipped* indexes for a given VA.
514 * Returns the index of a PTE in a page table (PT), representing
519 pmap_pte_index(vm_offset_t va)
521 return ((va >> PAGE_SHIFT) & ((1UL << NPTEPGSHIFT) - 1));
525 * Returns the index of a PDE in a page directory (PD) table, representing
530 pmap_pt_index(vm_offset_t va)
532 return ((va >> PDRSHIFT) & ((1UL << NPDEPGSHIFT) - 1));
536 * Returns the index of a PDPE in a page directory pointer (PDP) table,
537 * representing a page directory (PD) table.
541 pmap_pd_index(vm_offset_t va)
543 return ((va >> PDPSHIFT) & ((1UL << NPDPEPGSHIFT) - 1));
547 * Returns the index of a PML4E in the PML4 table, representing a page
548 * directory pointer (PDP) table.
552 pmap_pdp_index(vm_offset_t va)
554 return ((va >> PML4SHIFT) & ((1UL << NPML4EPGSHIFT) - 1));
558 * Of all the layers (PT, PD, PDP, PML4) the best one to cache is
559 * the PT layer. This will speed up core pmap operations considerably.
561 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
562 * must be in a known associated state (typically by being locked when
563 * the pmap spinlock isn't held). We allow the race for that case.
565 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
566 * cpu_ccfence() to prevent compiler optimizations from reloading the
571 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
573 if (pindex < pmap_pt_pindex(0)) {
575 } else if (pindex < pmap_pd_pindex(0)) {
576 pmap->pm_pvhint_pt = pv;
581 * Locate the requested pt_entry
585 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
589 if (pindex < pmap_pt_pindex(0))
592 if (pindex < pmap_pd_pindex(0))
593 pv = pmap->pm_pvhint_pt;
597 if (pv == NULL || pv->pv_pmap != pmap) {
598 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
600 pv_cache(pmap, pv, pindex);
601 } else if (pv->pv_pindex != pindex) {
602 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
605 pv_cache(pmap, pv, pindex);
608 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
616 * Super fast pmap_pte routine best used when scanning the pv lists.
617 * This eliminates many course-grained invltlb calls. Note that many of
618 * the pv list scans are across different pmaps and it is very wasteful
619 * to do an entire invltlb when checking a single mapping.
621 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
625 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
627 return pmap_pte(pmap, va);
631 * The placemarker hash must be broken up into four zones so lock
632 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
634 * Placemarkers are used to 'lock' page table indices that do not have
635 * a pv_entry. This allows the pmap to support managed and unmanaged
636 * pages and shared page tables.
638 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
642 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
646 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
648 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
650 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
651 hi = PM_PLACE_BASE << 1;
652 else /* zone 3 - PDP (and PML4E) */
653 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
654 hi += pindex & (PM_PLACE_BASE - 1);
656 return (&pmap->pm_placemarks[hi]);
661 * Generic procedure to index a pte from a pt, pd, or pdp.
663 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
664 * a page table page index but is instead of PV lookup index.
668 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
672 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
673 return(&pte[pindex]);
677 * Return pointer to PDP slot in the PML4
681 pmap_pdp(pmap_t pmap, vm_offset_t va)
683 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
687 * Return pointer to PD slot in the PDP given a pointer to the PDP
691 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
695 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
696 return (&pd[pmap_pd_index(va)]);
700 * Return pointer to PD slot in the PDP.
704 pmap_pd(pmap_t pmap, vm_offset_t va)
708 pdp = pmap_pdp(pmap, va);
709 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
711 return (pmap_pdp_to_pd(*pdp, va));
715 * Return pointer to PT slot in the PD given a pointer to the PD
719 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
723 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
724 return (&pt[pmap_pt_index(va)]);
728 * Return pointer to PT slot in the PD
730 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
731 * so we cannot lookup the PD via the PDP. Instead we
732 * must look it up via the pmap.
736 pmap_pt(pmap_t pmap, vm_offset_t va)
740 vm_pindex_t pd_pindex;
743 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
744 pd_pindex = pmap_pd_pindex(va);
745 spin_lock_shared(&pmap->pm_spin);
746 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
747 if (pv == NULL || pv->pv_m == NULL) {
748 spin_unlock_shared(&pmap->pm_spin);
751 phys = VM_PAGE_TO_PHYS(pv->pv_m);
752 spin_unlock_shared(&pmap->pm_spin);
753 return (pmap_pd_to_pt(phys, va));
755 pd = pmap_pd(pmap, va);
756 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
758 return (pmap_pd_to_pt(*pd, va));
763 * Return pointer to PTE slot in the PT given a pointer to the PT
767 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
771 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
772 return (&pte[pmap_pte_index(va)]);
776 * Return pointer to PTE slot in the PT
780 pmap_pte(pmap_t pmap, vm_offset_t va)
784 pt = pmap_pt(pmap, va);
785 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
787 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
788 return ((pt_entry_t *)pt);
789 return (pmap_pt_to_pte(*pt, va));
793 * Return address of PT slot in PD (KVM only)
795 * Cannot be used for user page tables because it might interfere with
796 * the shared page-table-page optimization (pmap_mmu_optimize).
800 vtopt(vm_offset_t va)
802 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
803 NPML4EPGSHIFT)) - 1);
805 return (PDmap + ((va >> PDRSHIFT) & mask));
809 * KVM - return address of PTE slot in PT
813 vtopte(vm_offset_t va)
815 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
816 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
818 return (PTmap + ((va >> PAGE_SHIFT) & mask));
822 * Returns the physical address translation from va for a user address.
823 * (vm_paddr_t)-1 is returned on failure.
826 uservtophys(vm_offset_t va)
828 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
829 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
834 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
836 if (va < VM_MAX_USER_ADDRESS) {
837 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
838 if (pte & pmap->pmap_bits[PG_V_IDX])
839 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
845 allocpages(vm_paddr_t *firstaddr, long n)
850 bzero((void *)ret, n * PAGE_SIZE);
851 *firstaddr += n * PAGE_SIZE;
857 create_pagetables(vm_paddr_t *firstaddr)
859 long i; /* must be 64 bits */
866 * We are running (mostly) V=P at this point
868 * Calculate how many 1GB PD entries in our PDP pages are needed
869 * for the DMAP. This is only allocated if the system does not
870 * support 1GB pages. Otherwise ndmpdp is simply a count of
871 * the number of 1G terminal entries in our PDP pages are needed.
873 * NOTE: Maxmem is in pages
875 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
876 if (ndmpdp < 4) /* Minimum 4GB of DMAP */
881 * HACK XXX fix me - Some laptops map the EFI framebuffer in
882 * very high physical addresses and the DMAP winds up being too
883 * small. The EFI framebuffer has to be mapped for the console
884 * very early and the DMAP is how it does it.
886 if (ndmpdp < 512) /* Minimum 512GB of DMAP */
890 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
891 DMapMaxAddress = DMAP_MIN_ADDRESS +
892 ((ndmpdp * NPDEPG) << PDRSHIFT);
895 * Starting at KERNBASE - map all 2G worth of page table pages.
896 * KERNBASE is offset -2G from the end of kvm. This will accomodate
897 * all KVM allocations above KERNBASE, including the SYSMAPs below.
899 * We do this by allocating 2*512 PT pages. Each PT page can map
900 * 2MB, for 2GB total.
902 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
905 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
906 * Calculate how many page table pages we need to preallocate
907 * for early vm_map allocations.
909 * A few extra won't hurt, they will get used up in the running
915 nkpt_phys = howmany(Maxmem * sizeof(struct vm_page), NBPDR);
916 nkpt_phys += howmany(Maxmem * sizeof(struct pv_entry), NBPDR);
917 nkpt_phys += 128; /* a few extra */
920 * The highest value nkpd_phys can be set to is
921 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
923 * Doing so would cause all PD pages to be pre-populated for
924 * a maximal KVM space (approximately 16*512 pages, or 32MB.
925 * We can save memory by not doing this.
927 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
932 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
933 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
935 * Only allocate enough PD pages
936 * NOTE: We allocate all kernel PD pages up-front, typically
937 * ~511G of KVM, requiring 511 PD pages.
939 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
940 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
941 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
942 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
943 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
946 * Alloc PD pages for the area starting at KERNBASE.
948 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
951 * Stuff for our DMAP. Use 2MB pages even when 1GB pages
952 * are available in order to allow APU code to adjust page
953 * attributes on a fixed grain (see pmap_change_attr()).
955 DMPDPphys = allocpages(firstaddr, NDMPML4E);
957 DMPDphys = allocpages(firstaddr, ndmpdp);
959 if ((amd_feature & AMDID_PAGE1GB) == 0)
960 DMPDphys = allocpages(firstaddr, ndmpdp);
962 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
965 * Fill in the underlying page table pages for the area around
966 * KERNBASE. This remaps low physical memory to KERNBASE.
968 * Read-only from zero to physfree
969 * XXX not fully used, underneath 2M pages
971 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
972 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
973 ((pt_entry_t *)KPTbase)[i] |=
974 pmap_bits_default[PG_RW_IDX] |
975 pmap_bits_default[PG_V_IDX] |
976 pmap_bits_default[PG_G_IDX];
980 * Now map the initial kernel page tables. One block of page
981 * tables is placed at the beginning of kernel virtual memory,
982 * and another block is placed at KERNBASE to map the kernel binary,
983 * data, bss, and initial pre-allocations.
985 for (i = 0; i < nkpt_base; i++) {
986 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
987 ((pd_entry_t *)KPDbase)[i] |=
988 pmap_bits_default[PG_RW_IDX] |
989 pmap_bits_default[PG_V_IDX];
991 for (i = 0; i < nkpt_phys; i++) {
992 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
993 ((pd_entry_t *)KPDphys)[i] |=
994 pmap_bits_default[PG_RW_IDX] |
995 pmap_bits_default[PG_V_IDX];
999 * Map from zero to end of allocations using 2M pages as an
1000 * optimization. This will bypass some of the KPTBase pages
1001 * above in the KERNBASE area.
1003 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
1004 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
1005 ((pd_entry_t *)KPDbase)[i] |=
1006 pmap_bits_default[PG_RW_IDX] |
1007 pmap_bits_default[PG_V_IDX] |
1008 pmap_bits_default[PG_PS_IDX] |
1009 pmap_bits_default[PG_G_IDX];
1013 * Load PD addresses into the PDP pages for primary KVA space to
1014 * cover existing page tables. PD's for KERNBASE are handled in
1017 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
1019 for (i = 0; i < nkpd_phys; i++) {
1020 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
1021 KPDphys + (i << PAGE_SHIFT);
1022 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
1023 pmap_bits_default[PG_RW_IDX] |
1024 pmap_bits_default[PG_V_IDX] |
1025 pmap_bits_default[PG_A_IDX];
1029 * Load PDs for KERNBASE to the end
1031 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
1032 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
1033 ((pdp_entry_t *)KPDPphys)[i + j] =
1034 KPDbase + (j << PAGE_SHIFT);
1035 ((pdp_entry_t *)KPDPphys)[i + j] |=
1036 pmap_bits_default[PG_RW_IDX] |
1037 pmap_bits_default[PG_V_IDX] |
1038 pmap_bits_default[PG_A_IDX];
1042 * Now set up the direct map space using either 2MB or 1GB pages
1043 * Preset PG_M and PG_A because demotion expects it.
1045 * When filling in entries in the PD pages make sure any excess
1046 * entries are set to zero as we allocated enough PD pages
1048 * Stuff for our DMAP. Use 2MB pages even when 1GB pages
1049 * are available in order to allow APU code to adjust page
1050 * attributes on a fixed grain (see pmap_change_attr()).
1053 if ((amd_feature & AMDID_PAGE1GB) == 0)
1059 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1060 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1061 ((pd_entry_t *)DMPDphys)[i] |=
1062 pmap_bits_default[PG_RW_IDX] |
1063 pmap_bits_default[PG_V_IDX] |
1064 pmap_bits_default[PG_PS_IDX] |
1065 pmap_bits_default[PG_G_IDX] |
1066 pmap_bits_default[PG_M_IDX] |
1067 pmap_bits_default[PG_A_IDX];
1071 * And the direct map space's PDP
1073 for (i = 0; i < ndmpdp; i++) {
1074 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1076 ((pdp_entry_t *)DMPDPphys)[i] |=
1077 pmap_bits_default[PG_RW_IDX] |
1078 pmap_bits_default[PG_V_IDX] |
1079 pmap_bits_default[PG_A_IDX];
1087 for (i = 0; i < ndmpdp; i++) {
1088 ((pdp_entry_t *)DMPDPphys)[i] =
1089 (vm_paddr_t)i << PDPSHIFT;
1090 ((pdp_entry_t *)DMPDPphys)[i] |=
1091 pmap_bits_default[PG_RW_IDX] |
1092 pmap_bits_default[PG_V_IDX] |
1093 pmap_bits_default[PG_PS_IDX] |
1094 pmap_bits_default[PG_G_IDX] |
1095 pmap_bits_default[PG_M_IDX] |
1096 pmap_bits_default[PG_A_IDX];
1101 /* And recursively map PML4 to itself in order to get PTmap */
1102 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1103 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1104 pmap_bits_default[PG_RW_IDX] |
1105 pmap_bits_default[PG_V_IDX] |
1106 pmap_bits_default[PG_A_IDX];
1109 * Connect the Direct Map slots up to the PML4
1111 for (j = 0; j < NDMPML4E; ++j) {
1112 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1113 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1114 pmap_bits_default[PG_RW_IDX] |
1115 pmap_bits_default[PG_V_IDX] |
1116 pmap_bits_default[PG_A_IDX];
1120 * Connect the KVA slot up to the PML4
1122 for (j = 0; j < NKPML4E; ++j) {
1123 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1124 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1125 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1126 pmap_bits_default[PG_RW_IDX] |
1127 pmap_bits_default[PG_V_IDX] |
1128 pmap_bits_default[PG_A_IDX];
1135 * Bootstrap the system enough to run with virtual memory.
1137 * On x86_64 this is called after mapping has already been enabled
1138 * and just syncs the pmap module with what has already been done.
1139 * [We can't call it easily with mapping off since the kernel is not
1140 * mapped with PA == VA, hence we would have to relocate every address
1141 * from the linked base (virtual) address "KERNBASE" to the actual
1142 * (physical) address starting relative to 0]
1145 pmap_bootstrap(vm_paddr_t *firstaddr)
1151 KvaStart = VM_MIN_KERNEL_ADDRESS;
1152 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1153 KvaSize = KvaEnd - KvaStart;
1155 avail_start = *firstaddr;
1158 * Create an initial set of page tables to run the kernel in.
1160 create_pagetables(firstaddr);
1162 virtual2_start = KvaStart;
1163 virtual2_end = PTOV_OFFSET;
1165 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1166 virtual_start = pmap_kmem_choose(virtual_start);
1168 virtual_end = VM_MAX_KERNEL_ADDRESS;
1170 /* XXX do %cr0 as well */
1171 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1172 load_cr3(KPML4phys);
1175 * Initialize protection array.
1177 x86_64_protection_init();
1180 * The kernel's pmap is statically allocated so we don't have to use
1181 * pmap_create, which is unlikely to work correctly at this part of
1182 * the boot sequence (XXX and which no longer exists).
1184 kernel_pmap->pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1185 kernel_pmap->pm_count = 1;
1186 CPUMASK_ASSALLONES(kernel_pmap->pm_active);
1187 RB_INIT(&kernel_pmap->pm_pvroot);
1188 spin_init(&kernel_pmap->pm_spin, "pmapbootstrap");
1189 for (i = 0; i < PM_PLACEMARKS; ++i)
1190 kernel_pmap->pm_placemarks[i] = PM_NOPLACEMARK;
1193 * Reserve some special page table entries/VA space for temporary
1196 #define SYSMAP(c, p, v, n) \
1197 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1203 * CMAP1/CMAP2 are used for zeroing and copying pages.
1205 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1210 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1213 * ptvmmap is used for reading arbitrary physical pages via
1216 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1219 * msgbufp is used to map the system message buffer.
1220 * XXX msgbufmap is not used.
1222 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1223 atop(round_page(MSGBUF_SIZE)))
1226 virtual_start = pmap_kmem_choose(virtual_start);
1231 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1232 * cases rather then invl1pg. Actually, I don't even know why it
1233 * works under UP because self-referential page table mappings
1239 /* Initialize the PAT MSR */
1241 pmap_pinit_defaults(kernel_pmap);
1243 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1244 &pmap_fast_kernel_cpusync);
1249 * Setup the PAT MSR.
1259 * Default values mapping PATi,PCD,PWT bits at system reset.
1260 * The default values effectively ignore the PATi bit by
1261 * repeating the encodings for 0-3 in 4-7, and map the PCD
1262 * and PWT bit combinations to the expected PAT types.
1264 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1265 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1266 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1267 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1268 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1269 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1270 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1271 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1272 pat_pte_index[PAT_WRITE_BACK] = 0;
1273 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1274 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1275 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1276 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1277 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1279 if (cpu_feature & CPUID_PAT) {
1281 * If we support the PAT then set-up entries for
1282 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1285 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1286 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1287 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1288 PAT_VALUE(6, PAT_WRITE_COMBINING);
1289 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1290 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1293 * Then enable the PAT
1298 load_cr4(cr4 & ~CR4_PGE);
1300 /* Disable caches (CD = 1, NW = 0). */
1302 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1304 /* Flushes caches and TLBs. */
1308 /* Update PAT and index table. */
1309 wrmsr(MSR_PAT, pat_msr);
1311 /* Flush caches and TLBs again. */
1315 /* Restore caches and PGE. */
1321 for (i = 0; i < 8; ++i) {
1324 pte = pat_pte_index[i];
1325 if (pte & X86_PG_PTE_PAT) {
1326 pte &= ~X86_PG_PTE_PAT;
1327 pte |= X86_PG_PDE_PAT;
1329 pat_pde_index[i] = pte;
1334 * Set 4mb pdir for mp startup
1339 if (cpu_feature & CPUID_PSE) {
1340 load_cr4(rcr4() | CR4_PSE);
1341 if (mycpu->gd_cpuid == 0) /* only on BSP */
1346 * Check for SMAP support and enable if available. Must be done
1347 * after cr3 is loaded, and on all cores.
1349 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1350 load_cr4(rcr4() | CR4_SMAP);
1352 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1353 load_cr4(rcr4() | CR4_SMEP);
1358 * SMAP is just a processor flag, but SMEP can only be enabled
1359 * and disabled via CR4. We still use the processor flag to
1360 * disable SMAP because the page-fault/trap code checks it, in
1361 * order to allow a page-fault to actually occur.
1364 smap_smep_disable(void)
1367 * disable SMAP. This also bypasses a software failsafe check
1368 * in the trap() code.
1373 * Also needed to bypass a software failsafe check in the trap()
1374 * code and allow the userspace address fault from kernel mode
1377 * Note that This will not reload %rip because pcb_onfault_rsp will
1378 * not match. Just setting it to non-NULL is sufficient to bypass
1381 curthread->td_pcb->pcb_onfault = (void *)1;
1384 * Disable SMEP (requires modifying cr4)
1386 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1387 load_cr4(rcr4() & ~CR4_SMEP);
1391 smap_smep_enable(void)
1393 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1394 load_cr4(rcr4() | CR4_SMEP);
1395 curthread->td_pcb->pcb_onfault = NULL;
1400 * Early initialization of the pmap module.
1402 * Called by vm_init, to initialize any structures that the pmap
1403 * system needs to map virtual memory. pmap_init has been enhanced to
1404 * support in a fairly consistant way, discontiguous physical memory.
1409 vm_pindex_t initial_pvs;
1413 * Allocate memory for random pmap data structures. Includes the
1416 for (i = 0; i < vm_page_array_size; i++) {
1419 m = &vm_page_array[i];
1420 m->md.interlock_count = 0;
1424 * init the pv free list
1426 initial_pvs = vm_page_array_size;
1427 if (initial_pvs < MINPV)
1428 initial_pvs = MINPV;
1429 pvzone = &pvzone_store;
1430 pvinit = (void *)kmem_alloc(kernel_map,
1431 initial_pvs * sizeof (struct pv_entry),
1433 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1434 pvinit, initial_pvs);
1437 * Now it is safe to enable pv_table recording.
1439 pmap_initialized = TRUE;
1443 * Initialize the address space (zone) for the pv_entries. Set a
1444 * high water mark so that the system can recover from excessive
1445 * numbers of pv entries.
1447 * Also create the kernel page table template for isolated user
1450 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1451 static void pmap_init2_iso_pmap(void);
1453 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1459 vm_pindex_t entry_max;
1462 * We can significantly reduce pv_entry_max from historical
1463 * levels because pv_entry's are no longer use for PTEs at the
1464 * leafs. This prevents excessive pcpu caching on many-core
1465 * boxes (even with the further '/ 16' done in zinitna().
1467 * Remember, however, that processes can share physical pages
1468 * with each process still needing the pdp/pd/pt infrstructure
1469 * (which still use pv_entry's). And don't just assume that
1470 * every PT will be completely filled up. So don't make it
1473 entry_max = maxproc * 32 + vm_page_array_size / 16;
1474 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &entry_max);
1475 vm_pmap_pv_entries = entry_max;
1478 * Subtract out pages already installed in the zone (hack)
1480 if (entry_max <= MINPV)
1483 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1486 * Enable dynamic deletion of empty higher-level page table pages
1487 * by default only if system memory is < 8GB (use 7GB for slop).
1488 * This can save a little memory, but imposes significant
1489 * performance overhead for things like bulk builds, and for programs
1490 * which do a lot of memory mapping and memory unmapping.
1493 if (pmap_dynamic_delete < 0) {
1494 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1495 pmap_dynamic_delete = 1;
1497 pmap_dynamic_delete = 0;
1501 * Disable so vm_map_backing iterations do not race
1503 pmap_dynamic_delete = 0;
1506 * Automatic detection of Intel meltdown bug requiring user/kernel
1509 * Currently there are so many Intel cpu's impacted that its better
1510 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1511 * so the default is off for AMD.
1513 if (meltdown_mitigation < 0) {
1514 if (cpu_vendor_id == CPU_VENDOR_INTEL) {
1515 meltdown_mitigation = 1;
1516 if (cpu_ia32_arch_caps & IA32_ARCH_CAP_RDCL_NO)
1517 meltdown_mitigation = 0;
1519 meltdown_mitigation = 0;
1522 if (meltdown_mitigation) {
1523 kprintf("machdep.meltdown_mitigation enabled to "
1524 "protect against (mostly Intel) meltdown bug\n");
1525 kprintf("system call performance will be impacted\n");
1528 pmap_init2_iso_pmap();
1532 * Create the isolation pmap template. Once created, the template
1533 * is static and its PML4e entries are used to populate the
1534 * kernel portion of any isolated user pmaps.
1536 * Our isolation pmap must contain:
1537 * (1) trampoline area for all cpus
1538 * (2) common_tss area for all cpus (its part of the trampoline area now)
1539 * (3) IDT for all cpus
1540 * (4) GDT for all cpus
1543 pmap_init2_iso_pmap(void)
1548 kprintf("Initialize isolation pmap\n");
1551 * Try to use our normal API calls to make this easier. We have
1552 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1555 pmap_pinit(&iso_pmap);
1556 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1559 * Install areas needed by the cpu and trampoline.
1561 for (n = 0; n < ncpus; ++n) {
1562 struct privatespace *ps;
1564 ps = CPU_prvspace[n];
1565 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1566 sizeof(ps->trampoline));
1567 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1568 sizeof(ps->dblstack));
1569 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1570 sizeof(ps->dbgstack));
1571 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1572 sizeof(ps->common_tss));
1573 pmap_init_iso_range(r_idt_arr[n].rd_base,
1574 r_idt_arr[n].rd_limit + 1);
1576 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1577 pmap_init_iso_range((vm_offset_t)(int *)btext,
1578 (vm_offset_t)(int *)etext -
1579 (vm_offset_t)(int *)btext);
1582 kprintf("Dump iso_pmap:\n");
1583 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1584 kprintf("\nDump kernel_pmap:\n");
1585 dump_pmap(kernel_pmap, vtophys(kernel_pmap->pm_pml4), 0, 0);
1590 * This adds a kernel virtual address range to the isolation pmap.
1593 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1602 kprintf("isolate %016jx-%016jx (%zd)\n",
1603 base, base + bytes, bytes);
1605 va = base & ~(vm_offset_t)PAGE_MASK;
1606 while (va < base + bytes) {
1607 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1608 (ptep = pmap_pt(kernel_pmap, va)) != NULL &&
1609 (*ptep & kernel_pmap->pmap_bits[PG_V_IDX]) &&
1610 (*ptep & kernel_pmap->pmap_bits[PG_PS_IDX])) {
1612 * Use 2MB pages if possible
1615 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1616 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1621 * Otherwise use 4KB pages
1623 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1624 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1625 *ptep = vtophys(va) | kernel_pmap->pmap_bits[PG_RW_IDX] |
1626 kernel_pmap->pmap_bits[PG_V_IDX] |
1627 kernel_pmap->pmap_bits[PG_A_IDX] |
1628 kernel_pmap->pmap_bits[PG_M_IDX];
1639 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1643 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1650 case 0: /* PML4e page, 512G entries */
1651 incr = (1LL << 48) / 512;
1653 case 1: /* PDP page, 1G entries */
1654 incr = (1LL << 39) / 512;
1656 case 2: /* PD page, 2MB entries */
1657 incr = (1LL << 30) / 512;
1659 case 3: /* PT page, 4KB entries */
1660 incr = (1LL << 21) / 512;
1668 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1669 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1670 for (i = 0; i < 512; ++i) {
1671 if (level == 0 && i == 128)
1672 base += 0xFFFF000000000000LLU;
1674 kprintf("%*.*s ", level * 4, level * 4, "");
1675 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1676 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1678 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1679 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1681 } else if (level == 3) {
1682 kprintf("va=%016jx %3d term %016jx\n",
1685 kprintf("va=%016jx %3d deep %016jx\n",
1687 dump_pmap(pmap, ptp[i], level + 1, base);
1697 * Typically used to initialize a fictitious page by vm/device_pager.c
1700 pmap_page_init(struct vm_page *m)
1703 m->md.interlock_count = 0;
1706 /***************************************************
1707 * Low level helper routines.....
1708 ***************************************************/
1711 * Extract the physical page address associated with the map/VA pair.
1712 * The page must be wired for this to work reliably.
1715 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1722 if (va >= VM_MAX_USER_ADDRESS) {
1724 * Kernel page directories might be direct-mapped and
1725 * there is typically no PV tracking of pte's
1729 pt = pmap_pt(pmap, va);
1730 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1731 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1732 rtval = *pt & PG_PS_FRAME;
1733 rtval |= va & PDRMASK;
1735 ptep = pmap_pt_to_pte(*pt, va);
1736 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1737 rtval = *ptep & PG_FRAME;
1738 rtval |= va & PAGE_MASK;
1746 * User pages currently do not direct-map the page directory
1747 * and some pages might not used managed PVs. But all PT's
1750 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1752 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1753 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1754 rtval = *ptep & PG_FRAME;
1755 rtval |= va & PAGE_MASK;
1758 *handlep = pt_pv; /* locked until done */
1761 } else if (handlep) {
1769 pmap_extract_done(void *handle)
1772 pv_put((pv_entry_t)handle);
1776 * Similar to extract but checks protections, SMP-friendly short-cut for
1777 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1778 * fall-through to the real fault code. Does not work with HVM page
1781 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1783 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1784 * page is busied (and not held).
1786 * If busyp is not NULL and this function sets *busyp to zero, the returned
1787 * page is held (and not busied).
1789 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1790 * returned page will be dirtied. If the pte is not already writable NULL
1791 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1792 * any COW will already have happened and that page can be written by the
1795 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1799 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1802 va < VM_MAX_USER_ADDRESS &&
1803 (pmap->pm_flags & PMAP_HVM) == 0) {
1811 req = pmap->pmap_bits[PG_V_IDX] |
1812 pmap->pmap_bits[PG_U_IDX];
1813 if (prot & VM_PROT_WRITE)
1814 req |= pmap->pmap_bits[PG_RW_IDX];
1816 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1819 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1820 if ((*ptep & req) != req) {
1824 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1825 if (pte_pv && error == 0) {
1827 if (prot & VM_PROT_WRITE) {
1828 /* interlocked by presence of pv_entry */
1832 if (prot & VM_PROT_WRITE) {
1833 if (vm_page_busy_try(m, TRUE))
1844 } else if (pte_pv) {
1848 /* error, since we didn't request a placemarker */
1859 * Extract the physical page address associated kernel virtual address.
1862 pmap_kextract(vm_offset_t va)
1864 pd_entry_t pt; /* pt entry in pd */
1867 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1868 pa = DMAP_TO_PHYS(va);
1871 if (pt & kernel_pmap->pmap_bits[PG_PS_IDX]) {
1872 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1875 * Beware of a concurrent promotion that changes the
1876 * PDE at this point! For example, vtopte() must not
1877 * be used to access the PTE because it would use the
1878 * new PDE. It is, however, safe to use the old PDE
1879 * because the page table page is preserved by the
1882 pa = *pmap_pt_to_pte(pt, va);
1883 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1889 /***************************************************
1890 * Low level mapping routines.....
1891 ***************************************************/
1894 * Add a wired page to the KVA and invalidate the mapping on all CPUs.
1897 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1903 kernel_pmap->pmap_bits[PG_RW_IDX] |
1904 kernel_pmap->pmap_bits[PG_V_IDX];
1908 pmap_inval_smp(kernel_pmap, va, 1, ptep, npte);
1912 pmap_inval_smp(kernel_pmap, va, ptep, npte);
1919 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1920 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1921 * (caller can conditionalize calling smp_invltlb()).
1924 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1930 npte = pa | kernel_pmap->pmap_bits[PG_RW_IDX] |
1931 kernel_pmap->pmap_bits[PG_V_IDX];
1940 atomic_swap_long(ptep, npte);
1941 cpu_invlpg((void *)va);
1947 * Enter addresses into the kernel pmap but don't bother
1948 * doing any tlb invalidations. Caller will do a rollup
1949 * invalidation via pmap_rollup_inval().
1952 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1959 kernel_pmap->pmap_bits[PG_RW_IDX] |
1960 kernel_pmap->pmap_bits[PG_V_IDX];
1969 atomic_swap_long(ptep, npte);
1970 cpu_invlpg((void *)va);
1976 * remove a page from the kernel pagetables
1979 pmap_kremove(vm_offset_t va)
1984 pmap_inval_smp(kernel_pmap, va, 1, ptep, 0);
1988 pmap_kremove_quick(vm_offset_t va)
1993 atomic_readandclear_long(ptep);
1994 cpu_invlpg((void *)va);
1998 * Remove addresses from the kernel pmap but don't bother
1999 * doing any tlb invalidations. Caller will do a rollup
2000 * invalidation via pmap_rollup_inval().
2003 pmap_kremove_noinval(vm_offset_t va)
2008 atomic_readandclear_long(ptep);
2012 * XXX these need to be recoded. They are not used in any critical path.
2015 pmap_kmodify_rw(vm_offset_t va)
2017 atomic_set_long(vtopte(va), kernel_pmap->pmap_bits[PG_RW_IDX]);
2018 cpu_invlpg((void *)va);
2023 pmap_kmodify_nc(vm_offset_t va)
2025 atomic_set_long(vtopte(va), PG_N);
2026 cpu_invlpg((void *)va);
2031 * Used to map a range of physical addresses into kernel virtual
2032 * address space during the low level boot, typically to map the
2033 * dump bitmap, message buffer, and vm_page_array.
2035 * These mappings are typically made at some pointer after the end of the
2038 * We could return PHYS_TO_DMAP(start) here and not allocate any
2039 * via (*virtp), but then kmem from userland and kernel dumps won't
2040 * have access to the related pointers.
2043 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
2046 vm_offset_t va_start;
2048 /*return PHYS_TO_DMAP(start);*/
2053 while (start < end) {
2054 pmap_kenter_quick(va, start);
2062 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2065 * Remove the specified set of pages from the data and instruction caches.
2067 * In contrast to pmap_invalidate_cache_range(), this function does not
2068 * rely on the CPU's self-snoop feature, because it is intended for use
2069 * when moving pages into a different cache domain.
2072 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2074 vm_offset_t daddr, eva;
2077 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2078 (cpu_feature & CPUID_CLFSH) == 0)
2082 for (i = 0; i < count; i++) {
2083 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2084 eva = daddr + PAGE_SIZE;
2085 for (; daddr < eva; daddr += cpu_clflush_line_size)
2093 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
2095 KASSERT((sva & PAGE_MASK) == 0,
2096 ("pmap_invalidate_cache_range: sva not page-aligned"));
2097 KASSERT((eva & PAGE_MASK) == 0,
2098 ("pmap_invalidate_cache_range: eva not page-aligned"));
2100 if (cpu_feature & CPUID_SS) {
2101 ; /* If "Self Snoop" is supported, do nothing. */
2103 /* Globally invalidate caches */
2104 cpu_wbinvd_on_all_cpus();
2109 * Invalidate the specified range of virtual memory on all cpus associated
2113 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2115 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2119 * Add a list of wired pages to the kva. This routine is used for temporary
2120 * kernel mappings such as those found in buffer cache buffer. Page
2121 * modifications and accesses are not tracked or recorded.
2123 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2124 * semantics as previous mappings may have been zerod without any
2127 * The page *must* be wired.
2129 static __inline void
2130 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2135 end_va = beg_va + count * PAGE_SIZE;
2137 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2142 pte = VM_PAGE_TO_PHYS(*m) |
2143 kernel_pmap->pmap_bits[PG_RW_IDX] |
2144 kernel_pmap->pmap_bits[PG_V_IDX] |
2145 kernel_pmap->pmap_cache_bits_pte[(*m)->pat_mode];
2147 atomic_swap_long(ptep, pte);
2151 pmap_invalidate_range(kernel_pmap, beg_va, end_va);
2155 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2157 _pmap_qenter(beg_va, m, count, 1);
2161 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2163 _pmap_qenter(beg_va, m, count, 0);
2167 * This routine jerks page mappings from the kernel -- it is meant only
2168 * for temporary mappings such as those found in buffer cache buffers.
2169 * No recording modified or access status occurs.
2171 * MPSAFE, INTERRUPT SAFE (cluster callback)
2174 pmap_qremove(vm_offset_t beg_va, int count)
2179 end_va = beg_va + count * PAGE_SIZE;
2181 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2185 atomic_readandclear_long(pte);
2186 cpu_invlpg((void *)va);
2188 pmap_invalidate_range(kernel_pmap, beg_va, end_va);
2192 * This routine removes temporary kernel mappings, only invalidating them
2193 * on the current cpu. It should only be used under carefully controlled
2197 pmap_qremove_quick(vm_offset_t beg_va, int count)
2202 end_va = beg_va + count * PAGE_SIZE;
2204 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2208 atomic_readandclear_long(pte);
2209 cpu_invlpg((void *)va);
2214 * This routine removes temporary kernel mappings *without* invalidating
2215 * the TLB. It can only be used on permanent kva reservations such as those
2216 * found in buffer cache buffers, under carefully controlled circumstances.
2218 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2219 * (pmap_qenter() does unconditional invalidation).
2222 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2227 end_va = beg_va + count * PAGE_SIZE;
2229 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2233 atomic_readandclear_long(pte);
2238 * Create a new thread and optionally associate it with a (new) process.
2239 * NOTE! the new thread's cpu may not equal the current cpu.
2242 pmap_init_thread(thread_t td)
2244 /* enforce pcb placement & alignment */
2245 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2246 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2247 td->td_savefpu = &td->td_pcb->pcb_save;
2248 td->td_sp = (char *)td->td_pcb; /* no -16 */
2252 * This routine directly affects the fork perf for a process.
2255 pmap_init_proc(struct proc *p)
2260 pmap_pinit_defaults(struct pmap *pmap)
2262 bcopy(pmap_bits_default, pmap->pmap_bits,
2263 sizeof(pmap_bits_default));
2264 bcopy(protection_codes, pmap->protection_codes,
2265 sizeof(protection_codes));
2266 bcopy(pat_pte_index, pmap->pmap_cache_bits_pte,
2267 sizeof(pat_pte_index));
2268 bcopy(pat_pde_index, pmap->pmap_cache_bits_pde,
2269 sizeof(pat_pte_index));
2270 pmap->pmap_cache_mask_pte = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2271 pmap->pmap_cache_mask_pde = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PDE_PAT;
2272 pmap->copyinstr = std_copyinstr;
2273 pmap->copyin = std_copyin;
2274 pmap->copyout = std_copyout;
2275 pmap->fubyte = std_fubyte;
2276 pmap->subyte = std_subyte;
2277 pmap->fuword32 = std_fuword32;
2278 pmap->fuword64 = std_fuword64;
2279 pmap->suword32 = std_suword32;
2280 pmap->suword64 = std_suword64;
2281 pmap->swapu32 = std_swapu32;
2282 pmap->swapu64 = std_swapu64;
2283 pmap->fuwordadd32 = std_fuwordadd32;
2284 pmap->fuwordadd64 = std_fuwordadd64;
2287 pmap->pm_data = NULL;
2288 pmap->pm_tlb_flush = NULL;
2291 * Initialize pmap0/vmspace0.
2293 * On architectures where the kernel pmap is not integrated into the user
2294 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2295 * kernel_pmap should be used to directly access the kernel_pmap.
2298 pmap_pinit0(struct pmap *pmap)
2302 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2304 CPUMASK_ASSZERO(pmap->pm_active);
2305 pmap->pm_pvhint_pt = NULL;
2306 pmap->pm_pvhint_unused = NULL;
2307 RB_INIT(&pmap->pm_pvroot);
2308 spin_init(&pmap->pm_spin, "pmapinit0");
2309 for (i = 0; i < PM_PLACEMARKS; ++i)
2310 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2311 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2312 pmap_pinit_defaults(pmap);
2316 * Initialize a preallocated and zeroed pmap structure,
2317 * such as one in a vmspace structure.
2320 pmap_pinit_simple(struct pmap *pmap)
2325 * Misc initialization
2328 CPUMASK_ASSZERO(pmap->pm_active);
2329 pmap->pm_pvhint_pt = NULL;
2330 pmap->pm_pvhint_unused = NULL;
2331 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2333 pmap_pinit_defaults(pmap);
2336 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2339 if (pmap->pm_pmlpv == NULL) {
2340 RB_INIT(&pmap->pm_pvroot);
2341 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2342 spin_init(&pmap->pm_spin, "pmapinitsimple");
2343 for (i = 0; i < PM_PLACEMARKS; ++i)
2344 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2349 pmap_pinit(struct pmap *pmap)
2354 if (pmap->pm_pmlpv) {
2355 /* Completely clear the cached pmap if not REGULAR_PMAP. */
2356 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2361 pmap_pinit_simple(pmap);
2362 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2365 * No need to allocate page table space yet but we do need a valid
2366 * page directory table.
2368 if (pmap->pm_pml4 == NULL) {
2370 (pml4_entry_t *)kmem_alloc_pageable(kernel_map,
2373 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2377 * Allocate the PML4e table, which wires it even though it isn't
2378 * being entered into some higher level page table (it being the
2379 * highest level). If one is already cached we don't have to do
2382 if ((pv = pmap->pm_pmlpv) == NULL) {
2383 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2384 pmap->pm_pmlpv = pv;
2385 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2386 VM_PAGE_TO_PHYS(pv->pv_m));
2390 * Install DMAP and KMAP.
2392 for (j = 0; j < NDMPML4E; ++j) {
2393 pmap->pm_pml4[DMPML4I + j] =
2394 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2395 pmap->pmap_bits[PG_RW_IDX] |
2396 pmap->pmap_bits[PG_V_IDX] |
2397 pmap->pmap_bits[PG_A_IDX];
2399 for (j = 0; j < NKPML4E; ++j) {
2400 pmap->pm_pml4[KPML4I + j] =
2401 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2402 pmap->pmap_bits[PG_RW_IDX] |
2403 pmap->pmap_bits[PG_V_IDX] |
2404 pmap->pmap_bits[PG_A_IDX];
2408 * install self-referential address mapping entry
2410 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2411 pmap->pmap_bits[PG_V_IDX] |
2412 pmap->pmap_bits[PG_RW_IDX] |
2413 pmap->pmap_bits[PG_A_IDX];
2415 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2416 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2418 KKASSERT(pmap->pm_pml4[255] == 0);
2421 * When implementing an isolated userland pmap, a second PML4e table
2422 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2423 * note that we do not operate on this table using our API functions
2424 * so handling of the + 1 case is mostly just to prevent implosions.
2426 * We install an isolated version of the kernel PDPs into this
2427 * second PML4e table. The pmap code will mirror all user PDPs
2428 * between the primary and secondary PML4e table.
2430 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2431 pmap != &iso_pmap) {
2432 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2433 pmap->pm_pmlpv_iso = pv;
2434 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2435 VM_PAGE_TO_PHYS(pv->pv_m));
2439 * Install an isolated version of the kernel pmap for
2440 * user consumption, using PDPs constructed in iso_pmap.
2442 for (j = 0; j < NKPML4E; ++j) {
2443 pmap->pm_pml4_iso[KPML4I + j] =
2444 iso_pmap.pm_pml4[KPML4I + j];
2447 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2448 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2453 * Clean up a pmap structure so it can be physically freed. This routine
2454 * is called by the vmspace dtor function. A great deal of pmap data is
2455 * left passively mapped to improve vmspace management so we have a bit
2456 * of cleanup work to do here.
2459 pmap_puninit(pmap_t pmap)
2464 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2465 if ((pv = pmap->pm_pmlpv) != NULL) {
2466 if (pv_hold_try(pv) == 0)
2468 KKASSERT(pv == pmap->pm_pmlpv);
2469 p = pmap_remove_pv_page(pv, 1);
2471 pv = NULL; /* safety */
2472 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2473 vm_page_busy_wait(p, FALSE, "pgpun");
2474 KKASSERT(p->flags & PG_UNQUEUED);
2475 vm_page_unwire(p, 0);
2476 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2478 pmap->pm_pmlpv = NULL;
2480 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2481 if (pv_hold_try(pv) == 0)
2483 KKASSERT(pv == pmap->pm_pmlpv_iso);
2484 p = pmap_remove_pv_page(pv, 1);
2486 pv = NULL; /* safety */
2487 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2488 vm_page_busy_wait(p, FALSE, "pgpun");
2489 KKASSERT(p->flags & PG_UNQUEUED);
2490 vm_page_unwire(p, 0);
2491 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2493 pmap->pm_pmlpv_iso = NULL;
2495 if (pmap->pm_pml4) {
2496 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2497 kmem_free(kernel_map,
2498 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2499 pmap->pm_pml4 = NULL;
2500 pmap->pm_pml4_iso = NULL;
2502 KKASSERT(pmap->pm_stats.resident_count == 0);
2503 KKASSERT(pmap->pm_stats.wired_count == 0);
2507 * This function is now unused (used to add the pmap to the pmap_list)
2510 pmap_pinit2(struct pmap *pmap)
2515 * Transform an initialized pmap for Intel EPT.
2518 pmap_ept_transform(pmap_t pmap, int flags)
2520 uint64_t pmap_bits_ept[PG_BITS_SIZE] = {
2521 [TYPE_IDX] = EPT_PMAP,
2522 [PG_V_IDX] = EPT_PG_READ | EPT_PG_EXECUTE,
2523 [PG_RW_IDX] = EPT_PG_WRITE,
2524 [PG_U_IDX] = 0, /* no support in EPT */
2525 [PG_A_IDX] = EPT_PG_A,
2526 [PG_M_IDX] = EPT_PG_M,
2527 [PG_PS_IDX] = EPT_PG_PS,
2528 [PG_G_IDX] = 0, /* no support in EPT */
2529 [PG_W_IDX] = EPT_PG_AVAIL1,
2530 [PG_MANAGED_IDX] = EPT_PG_AVAIL2,
2531 [PG_N_IDX] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_UC,
2532 [PG_NX_IDX] = 0, /* no support in EPT */
2534 uint64_t protection_codes_ept[PROTECTION_CODES_SIZE] = {
2535 [VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE ] = 0,
2536 [VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE ] = 0,
2537 [VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE] = 0,
2538 [VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE] = 0,
2539 [VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE ] =
2540 pmap_bits_ept[PG_RW_IDX],
2541 [VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE] =
2542 pmap_bits_ept[PG_RW_IDX],
2543 [VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE ] =
2544 pmap_bits_ept[PG_RW_IDX],
2545 [VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE] =
2546 pmap_bits_ept[PG_RW_IDX],
2548 pt_entry_t pmap_cache_bits_ept[PAT_INDEX_SIZE] = {
2549 [PAT_UNCACHEABLE] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_UC,
2550 [PAT_WRITE_COMBINING] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_WC,
2551 [PAT_WRITE_THROUGH] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_WT,
2552 [PAT_WRITE_PROTECTED] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_WP,
2553 [PAT_WRITE_BACK] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_WB,
2554 [PAT_UNCACHED] = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_UC,
2556 pt_entry_t pmap_cache_mask_ept = EPT_PG_IGNORE_PAT | EPT_MEM_TYPE_MASK;
2558 pmap->pm_flags |= (flags | PMAP_HVM);
2559 bcopy(pmap_bits_ept, pmap->pmap_bits, sizeof(pmap_bits_ept));
2560 bcopy(protection_codes_ept, pmap->protection_codes,
2561 sizeof(protection_codes_ept));
2562 bcopy(pmap_cache_bits_ept, pmap->pmap_cache_bits_pte,
2563 sizeof(pmap_cache_bits_ept));
2564 bcopy(pmap_cache_bits_ept, pmap->pmap_cache_bits_pde,
2565 sizeof(pmap_cache_bits_ept));
2566 pmap->pmap_cache_mask_pte = pmap_cache_mask_ept;
2567 pmap->pmap_cache_mask_pde = pmap_cache_mask_ept;
2570 * Zero out page directories. These are only used by the VM. Note
2571 * that the valid area is two pages if there is a pm_pmlpv_iso PTE
2572 * installed, otherwise it is only one page. The ISO page isn't used
2573 * either way but clean it out anyway if it exists.
2575 if (pmap->pm_pmlpv_iso != NULL)
2576 bzero(pmap->pm_pml4, PAGE_SIZE * 2);
2578 bzero(pmap->pm_pml4, PAGE_SIZE);
2582 * Transform an initialized pmap for AMD NPT/RVI.
2585 pmap_npt_transform(pmap_t pmap, int flags)
2587 uint64_t protection_codes_npt[PROTECTION_CODES_SIZE] = {
2588 [VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE ] = 0,
2589 [VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE ] = 0,
2590 [VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE] = 0,
2591 [VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE] = 0,
2592 [VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE ] =
2593 pmap_bits_default[PG_RW_IDX],
2594 [VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE] =
2595 pmap_bits_default[PG_RW_IDX],
2596 [VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE ] =
2597 pmap_bits_default[PG_RW_IDX],
2598 [VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE] =
2599 pmap_bits_default[PG_RW_IDX],
2602 pmap->pm_flags |= (flags | PMAP_HVM);
2603 pmap->pmap_bits[TYPE_IDX] = NPT_PMAP;
2604 /* Set PG_G and PG_NX bits to 0, similar to the EPT case above. */
2605 pmap->pmap_bits[PG_G_IDX] = 0;
2606 pmap->pmap_bits[PG_NX_IDX] = 0;
2608 bcopy(protection_codes_npt, pmap->protection_codes,
2609 sizeof(protection_codes_npt));
2611 if (pmap->pm_pmlpv_iso != NULL)
2612 bzero(pmap->pm_pml4, PAGE_SIZE * 2);
2614 bzero(pmap->pm_pml4, PAGE_SIZE);
2618 * This routine is called when various levels in the page table need to
2619 * be populated. This routine cannot fail.
2621 * This function returns two locked pv_entry's, one representing the
2622 * requested pv and one representing the requested pv's parent pv. If
2623 * an intermediate page table does not exist it will be created, mapped,
2624 * wired, and the parent page table will be given an additional hold
2625 * count representing the presence of the child pv_entry.
2629 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2632 pt_entry_t *ptep_iso;
2641 * If the pv already exists and we aren't being asked for the
2642 * parent page table page we can just return it. A locked+held pv
2643 * is returned. The pv will also have a second hold related to the
2644 * pmap association that we don't have to worry about.
2647 pv = pv_alloc(pmap, ptepindex, &isnew);
2648 if (isnew == 0 && pvpp == NULL)
2652 * DragonFly doesn't use PV's to represent terminal PTEs any more.
2653 * The index range is still used for placemarkers, but not for
2654 * actual pv_entry's.
2656 KKASSERT(ptepindex >= pmap_pt_pindex(0));
2659 * Note that pt_pv's are only returned for user VAs. We assert that
2660 * a pt_pv is not being requested for kernel VAs. The kernel
2661 * pre-wires all higher-level page tables so don't overload managed
2662 * higher-level page tables on top of it!
2664 * However, its convenient for us to allow the case when creating
2665 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2670 * The kernel never uses managed PT/PD/PDP pages.
2672 KKASSERT(pmap != kernel_pmap);
2675 * Non-terminal PVs allocate a VM page to represent the page table,
2676 * so we have to resolve pvp and calculate ptepindex for the pvp
2677 * and then for the page table entry index in the pvp for
2680 if (ptepindex < pmap_pd_pindex(0)) {
2682 * pv is PT, pvp is PD
2684 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2685 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2686 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2691 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2692 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2694 } else if (ptepindex < pmap_pdp_pindex(0)) {
2696 * pv is PD, pvp is PDP
2698 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2701 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2702 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2704 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2705 KKASSERT(pvpp == NULL);
2708 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2714 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2715 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2716 } else if (ptepindex < pmap_pml4_pindex()) {
2718 * pv is PDP, pvp is the root pml4 table
2720 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2725 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2726 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2729 * pv represents the top-level PML4, there is no parent.
2740 * (1) Add a wire count to the parent page table (pvp).
2741 * (2) Allocate a VM page for the page table.
2742 * (3) Enter the VM page into the parent page table.
2744 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2747 vm_page_wire_quick(pvp->pv_m);
2750 m = vm_page_alloc(NULL, pv->pv_pindex,
2751 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2752 VM_ALLOC_INTERRUPT);
2757 vm_page_wire(m); /* wire for mapping in parent */
2758 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2759 m->valid = VM_PAGE_BITS_ALL;
2760 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE | PG_UNQUEUED);
2761 KKASSERT(m->queue == PQ_NONE);
2768 * Wire the page into pvp. Bump the resident_count for the pmap.
2769 * There is no pvp for the top level, address the pm_pml4[] array
2772 * If the caller wants the parent we return it, otherwise
2773 * we just put it away.
2775 * No interlock is needed for pte 0 -> non-zero.
2777 * In the situation where *ptep is valid we might have an unmanaged
2778 * page table page shared from another page table which we need to
2779 * unshare before installing our private page table page.
2782 v = VM_PAGE_TO_PHYS(m) |
2783 (pmap->pmap_bits[PG_RW_IDX] |
2784 pmap->pmap_bits[PG_V_IDX] |
2785 pmap->pmap_bits[PG_A_IDX]);
2786 if (ptepindex < NUPTE_USER)
2787 v |= pmap->pmap_bits[PG_U_IDX];
2788 if (ptepindex < pmap_pt_pindex(0))
2789 v |= pmap->pmap_bits[PG_M_IDX];
2791 ptep = pv_pte_lookup(pvp, ptepindex);
2792 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2793 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2796 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2797 panic("pmap_allocpte: ptpte present without pv_entry!");
2801 pte = atomic_swap_long(ptep, v);
2803 atomic_swap_long(ptep_iso, v);
2805 kprintf("install pgtbl mixup 0x%016jx "
2806 "old/new 0x%016jx/0x%016jx\n",
2807 (intmax_t)ptepindex, pte, v);
2815 * (isnew) may be TRUE or FALSE.
2818 KKASSERT(pvp->pv_m != NULL);
2819 ptep = pv_pte_lookup(pvp, ptepindex);
2820 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2821 (pmap->pmap_bits[PG_RW_IDX] |
2822 pmap->pmap_bits[PG_V_IDX] |
2823 pmap->pmap_bits[PG_A_IDX]);
2824 if (ptepindex < NUPTE_USER)
2825 v |= pmap->pmap_bits[PG_U_IDX];
2826 if (ptepindex < pmap_pt_pindex(0))
2827 v |= pmap->pmap_bits[PG_M_IDX];
2829 kprintf("mismatched upper level pt %016jx/%016jx\n",
2841 * Release any resources held by the given physical map.
2843 * Called when a pmap initialized by pmap_pinit is being released. Should
2844 * only be called if the map contains no valid mappings.
2846 struct pmap_release_info {
2852 static int pmap_release_callback(pv_entry_t pv, void *data);
2855 pmap_release(struct pmap *pmap)
2857 struct pmap_release_info info;
2859 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2860 ("pmap still active! %016jx",
2861 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2864 * There is no longer a pmap_list, if there were we would remove the
2865 * pmap from it here.
2869 * Pull pv's off the RB tree in order from low to high and release
2877 spin_lock(&pmap->pm_spin);
2878 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2879 pmap_release_callback, &info);
2880 spin_unlock(&pmap->pm_spin);
2884 } while (info.retry);
2888 * One resident page (the pml4 page) should remain. Two if
2889 * the pmap has implemented an isolated userland PML4E table.
2890 * No wired pages should remain.
2892 int expected_res = 0;
2894 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2896 if (pmap->pm_pmlpv_iso)
2900 if (pmap->pm_stats.resident_count != expected_res ||
2901 pmap->pm_stats.wired_count != 0) {
2902 kprintf("fatal pmap problem - pmap %p flags %08x "
2903 "rescnt=%jd wirecnt=%jd\n",
2906 pmap->pm_stats.resident_count,
2907 pmap->pm_stats.wired_count);
2908 tsleep(pmap, 0, "DEAD", 0);
2911 KKASSERT(pmap->pm_stats.resident_count == expected_res);
2912 KKASSERT(pmap->pm_stats.wired_count == 0);
2917 * Called from low to high. We must cache the proper parent pv so we
2918 * can adjust its wired count.
2921 pmap_release_callback(pv_entry_t pv, void *data)
2923 struct pmap_release_info *info = data;
2924 pmap_t pmap = info->pmap;
2929 * Acquire a held and locked pv, check for release race
2931 pindex = pv->pv_pindex;
2932 if (info->pvp == pv) {
2933 spin_unlock(&pmap->pm_spin);
2935 } else if (pv_hold_try(pv)) {
2936 spin_unlock(&pmap->pm_spin);
2938 spin_unlock(&pmap->pm_spin);
2942 spin_lock(&pmap->pm_spin);
2946 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
2948 if (pv->pv_pindex < pmap_pt_pindex(0)) {
2950 * I am PTE, parent is PT
2952 pindex = pv->pv_pindex >> NPTEPGSHIFT;
2953 pindex += NUPTE_TOTAL;
2954 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
2956 * I am PT, parent is PD
2958 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
2959 pindex += NUPTE_TOTAL + NUPT_TOTAL;
2960 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
2962 * I am PD, parent is PDP
2964 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
2966 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2967 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
2969 * I am PDP, parent is PML4. We always calculate the
2970 * normal PML4 here, not the isolated PML4.
2972 pindex = pmap_pml4_pindex();
2984 if (info->pvp && info->pvp->pv_pindex != pindex) {
2988 if (info->pvp == NULL)
2989 info->pvp = pv_get(pmap, pindex, NULL);
2996 r = pmap_release_pv(pv, info->pvp, NULL);
2997 spin_lock(&pmap->pm_spin);
3003 * Called with held (i.e. also locked) pv. This function will dispose of
3004 * the lock along with the pv.
3006 * If the caller already holds the locked parent page table for pv it
3007 * must pass it as pvp, allowing us to avoid a deadlock, else it can
3008 * pass NULL for pvp.
3011 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
3016 * The pmap is currently not spinlocked, pv is held+locked.
3017 * Remove the pv's page from its parent's page table. The
3018 * parent's page table page's wire_count will be decremented.
3020 * This will clean out the pte at any level of the page table.
3021 * If smp != 0 all cpus are affected.
3023 * Do not tear-down recursively, its faster to just let the
3024 * release run its course.
3026 pmap_remove_pv_pte(pv, pvp, bulk, 0);
3029 * Terminal pvs are unhooked from their vm_pages. Because
3030 * terminal pages aren't page table pages they aren't wired
3031 * by us, so we have to be sure not to unwire them either.
3033 * XXX It is unclear if this code ever gets called because we
3034 * no longer use pv's to track terminal pages.
3036 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3037 pmap_remove_pv_page(pv, 0);
3042 * We leave the top-level page table page cached, wired, and
3043 * mapped in the pmap until the dtor function (pmap_puninit())
3046 * Since we are leaving the top-level pv intact we need
3047 * to break out of what would otherwise be an infinite loop.
3049 * This covers both the normal and the isolated PML4 page.
3051 if (pv->pv_pindex >= pmap_pml4_pindex()) {
3057 * For page table pages (other than the top-level page),
3058 * remove and free the vm_page. The representitive mapping
3059 * removed above by pmap_remove_pv_pte() did not undo the
3060 * last wire_count so we have to do that as well.
3062 p = pmap_remove_pv_page(pv, 1);
3063 vm_page_busy_wait(p, FALSE, "pmaprl");
3064 if (p->wire_count != 1) {
3067 if (pv->pv_pindex >= pmap_pdp_pindex(0))
3069 else if (pv->pv_pindex >= pmap_pd_pindex(0))
3071 else if (pv->pv_pindex >= pmap_pt_pindex(0))
3076 kprintf("p(%s) p->wire_count was %016lx %d\n",
3077 tstr, pv->pv_pindex, p->wire_count);
3079 KKASSERT(p->wire_count == 1);
3080 KKASSERT(p->flags & PG_UNQUEUED);
3082 vm_page_unwire(p, 0);
3083 KKASSERT(p->wire_count == 0);
3093 * This function will remove the pte associated with a pv from its parent.
3094 * Terminal pv's are supported. All cpus specified by (bulk) are properly
3097 * The wire count will be dropped on the parent page table. The wire
3098 * count on the page being removed (pv->pv_m) from the parent page table
3099 * is NOT touched. Note that terminal pages will not have any additional
3100 * wire counts while page table pages will have at least one representing
3101 * the mapping, plus others representing sub-mappings.
3103 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3104 * pages and user page table and terminal pages.
3106 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3107 * be freshly allocated and not imply that the pte is managed. In this
3108 * case pv->pv_m should be NULL.
3110 * The pv must be locked. The pvp, if supplied, must be locked. All
3111 * supplied pv's will remain locked on return.
3113 * XXX must lock parent pv's if they exist to remove pte XXX
3117 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3120 vm_pindex_t ptepindex = pv->pv_pindex;
3121 pmap_t pmap = pv->pv_pmap;
3127 if (ptepindex >= pmap_pml4_pindex()) {
3129 * We are the top level PML4E table, there is no parent.
3131 * This is either the normal or isolated PML4E table.
3132 * Only the normal is used in regular operation, the isolated
3133 * is only passed in when breaking down the whole pmap.
3135 p = pmap->pm_pmlpv->pv_m;
3136 KKASSERT(pv->pv_m == p); /* debugging */
3137 } else if (ptepindex >= pmap_pdp_pindex(0)) {
3139 * Remove a PDP page from the PML4E. This can only occur
3140 * with user page tables. We do not have to lock the
3141 * pml4 PV so just ignore pvp.
3143 vm_pindex_t pml4_pindex;
3144 vm_pindex_t pdp_index;
3146 pml4_entry_t *pdp_iso;
3148 pdp_index = ptepindex - pmap_pdp_pindex(0);
3150 pml4_pindex = pmap_pml4_pindex();
3151 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3156 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3157 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3158 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3159 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3162 * Also remove the PDP from the isolated PML4E if the
3165 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3166 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3167 ((1ul << NPML4EPGSHIFT) - 1)];
3168 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3170 KKASSERT(pv->pv_m == p); /* debugging */
3171 } else if (ptepindex >= pmap_pd_pindex(0)) {
3173 * Remove a PD page from the PDP
3175 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3176 * of a simple pmap because it stops at
3179 vm_pindex_t pdp_pindex;
3180 vm_pindex_t pd_index;
3183 pd_index = ptepindex - pmap_pd_pindex(0);
3186 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3187 (pd_index >> NPML4EPGSHIFT);
3188 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3193 pd = pv_pte_lookup(pvp, pd_index &
3194 ((1ul << NPDPEPGSHIFT) - 1));
3195 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3196 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3197 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3199 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3200 p = pv->pv_m; /* degenerate test later */
3202 KKASSERT(pv->pv_m == p); /* debugging */
3203 } else if (ptepindex >= pmap_pt_pindex(0)) {
3205 * Remove a PT page from the PD
3207 vm_pindex_t pd_pindex;
3208 vm_pindex_t pt_index;
3211 pt_index = ptepindex - pmap_pt_pindex(0);
3214 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3215 (pt_index >> NPDPEPGSHIFT);
3216 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3221 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3223 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3224 ("*pt unexpectedly invalid %016jx "
3225 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3226 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3227 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3229 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3230 kprintf("*pt unexpectedly invalid %016jx "
3231 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3233 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3234 tsleep(pt, 0, "DEAD", 0);
3237 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3240 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3241 KKASSERT(pv->pv_m == p); /* debugging */
3247 * If requested, scrap the underlying pv->pv_m and the underlying
3248 * pv. If this is a page-table-page we must also free the page.
3250 * pvp must be returned locked.
3254 * page table page (PT, PD, PDP, PML4), caller was responsible
3255 * for testing wired_count.
3257 KKASSERT(pv->pv_m->wire_count == 1);
3258 p = pmap_remove_pv_page(pv, 1);
3262 vm_page_busy_wait(p, FALSE, "pgpun");
3263 vm_page_unwire(p, 0);
3264 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3269 * If we acquired pvp ourselves then we are responsible for
3270 * recursively deleting it.
3272 if (pvp && gotpvp) {
3274 * Recursively destroy higher-level page tables.
3276 * This is optional. If we do not, they will still
3277 * be destroyed when the process exits.
3279 * NOTE: Do not destroy pv_entry's with extra hold refs,
3280 * a caller may have unlocked it and intends to
3281 * continue to use it.
3283 if (pmap_dynamic_delete &&
3285 pvp->pv_m->wire_count == 1 &&
3286 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3287 pvp->pv_pindex < pmap_pml4_pindex()) {
3288 if (pmap != kernel_pmap) {
3289 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3290 pvp = NULL; /* safety */
3292 kprintf("Attempt to remove kernel_pmap pindex "
3293 "%jd\n", pvp->pv_pindex);
3303 * Remove the vm_page association to a pv. The pv must be locked.
3307 pmap_remove_pv_page(pv_entry_t pv, int clrpgbits)
3314 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3320 * Grow the number of kernel page table entries, if needed.
3322 * This routine is always called to validate any address space
3323 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3324 * space below KERNBASE.
3326 * kernel_map must be locked exclusively by the caller.
3329 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3332 vm_offset_t ptppaddr;
3334 pd_entry_t *pt, newpt;
3335 pdp_entry_t *pd, newpd;
3336 int update_kernel_vm_end;
3339 * bootstrap kernel_vm_end on first real VM use
3341 if (kernel_vm_end == 0) {
3342 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3345 pt = pmap_pt(kernel_pmap, kernel_vm_end);
3348 if ((*pt & kernel_pmap->pmap_bits[PG_V_IDX]) == 0)
3350 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3351 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3352 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3353 kernel_vm_end = vm_map_max(kernel_map);
3360 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3361 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3362 * do not want to force-fill 128G worth of page tables.
3364 if (kstart < KERNBASE) {
3365 if (kstart > kernel_vm_end)
3366 kstart = kernel_vm_end;
3367 KKASSERT(kend <= KERNBASE);
3368 update_kernel_vm_end = 1;
3370 update_kernel_vm_end = 0;
3373 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3374 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3376 if (kend - 1 >= vm_map_max(kernel_map))
3377 kend = vm_map_max(kernel_map);
3379 while (kstart < kend) {
3380 pt = pmap_pt(kernel_pmap, kstart);
3383 * We need a new PD entry
3385 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3388 VM_ALLOC_INTERRUPT);
3390 panic("pmap_growkernel: no memory to grow "
3393 paddr = VM_PAGE_TO_PHYS(nkpg);
3394 pmap_zero_page(paddr);
3395 pd = pmap_pd(kernel_pmap, kstart);
3397 newpd = (pdp_entry_t)
3399 kernel_pmap->pmap_bits[PG_V_IDX] |
3400 kernel_pmap->pmap_bits[PG_RW_IDX] |
3401 kernel_pmap->pmap_bits[PG_A_IDX]);
3402 atomic_swap_long(pd, newpd);
3405 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3409 continue; /* try again */
3412 if ((*pt & kernel_pmap->pmap_bits[PG_V_IDX]) != 0) {
3413 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3414 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3415 if (kstart - 1 >= vm_map_max(kernel_map)) {
3416 kstart = vm_map_max(kernel_map);
3425 * This index is bogus, but out of the way
3427 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3430 VM_ALLOC_INTERRUPT);
3432 panic("pmap_growkernel: no memory to grow kernel");
3435 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3436 pmap_zero_page(ptppaddr);
3437 newpt = (pd_entry_t)(ptppaddr |
3438 kernel_pmap->pmap_bits[PG_V_IDX] |
3439 kernel_pmap->pmap_bits[PG_RW_IDX] |
3440 kernel_pmap->pmap_bits[PG_A_IDX]);
3441 atomic_swap_long(pt, newpt);
3443 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3444 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3446 if (kstart - 1 >= vm_map_max(kernel_map)) {
3447 kstart = vm_map_max(kernel_map);
3453 * Only update kernel_vm_end for areas below KERNBASE.
3455 if (update_kernel_vm_end && kernel_vm_end < kstart)
3456 kernel_vm_end = kstart;
3460 * Add a reference to the specified pmap.
3463 pmap_reference(pmap_t pmap)
3466 atomic_add_int(&pmap->pm_count, 1);
3470 pmap_maybethreaded(pmap_t pmap)
3472 atomic_set_int(&pmap->pm_flags, PMAP_MULTI);
3476 * Called while page is hard-busied to clear the PG_MAPPED and PG_WRITEABLE
3477 * flags if able. This can happen when the pmap code is unable to clear
3478 * the bits in prior actions due to not holding the page hard-busied at
3481 * The clearing of PG_MAPPED/WRITEABLE is an optional optimization done
3482 * when the pte is removed and only if the pte has not been multiply-mapped.
3483 * The caller may have to call vm_page_protect() if the bits are still set
3486 * This function is expected to be quick.
3489 pmap_mapped_sync(vm_page_t m)
3494 /***************************************************
3495 * page management routines.
3496 ***************************************************/
3499 * Hold a pv without locking it
3503 pv_hold(pv_entry_t pv)
3505 atomic_add_int(&pv->pv_hold, 1);
3510 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3511 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3514 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3515 * pv list via its page) must be held by the caller in order to stabilize
3519 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3524 * Critical path shortcut expects pv to already have one ref
3525 * (for the pv->pv_pmap).
3527 count = pv->pv_hold;
3530 if ((count & PV_HOLD_LOCKED) == 0) {
3531 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3532 (count + 1) | PV_HOLD_LOCKED)) {
3535 pv->pv_line = lineno;
3540 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3548 * Drop a previously held pv_entry which could not be locked, allowing its
3551 * Must not be called with a spinlock held as we might zfree() the pv if it
3552 * is no longer associated with a pmap and this was the last hold count.
3555 pv_drop(pv_entry_t pv)
3560 count = pv->pv_hold;
3562 KKASSERT((count & PV_HOLD_MASK) > 0);
3563 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3564 (PV_HOLD_LOCKED | 1));
3565 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3566 if ((count & PV_HOLD_MASK) == 1) {
3568 if (pmap_enter_debug > 0) {
3570 kprintf("pv_drop: free pv %p\n", pv);
3573 KKASSERT(count == 1);
3574 KKASSERT(pv->pv_pmap == NULL);
3584 * Find or allocate the requested PV entry, returning a locked, held pv.
3586 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3587 * for the caller and one representing the pmap and vm_page association.
3589 * If (*isnew) is zero, the returned pv will have only one hold count.
3591 * Since both associations can only be adjusted while the pv is locked,
3592 * together they represent just one additional hold.
3596 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3598 struct mdglobaldata *md = mdcpu;
3606 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3609 pnew = md->gd_newpv; /* might race NULL */
3610 md->gd_newpv = NULL;
3615 pnew = zalloc(pvzone);
3617 spin_lock_shared(&pmap->pm_spin);
3622 pv = pv_entry_lookup(pmap, pindex);
3627 * Requires exclusive pmap spinlock
3629 if (pmap_excl == 0) {
3631 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3632 spin_unlock_shared(&pmap->pm_spin);
3633 spin_lock(&pmap->pm_spin);
3639 * We need to block if someone is holding our
3640 * placemarker. As long as we determine the
3641 * placemarker has not been aquired we do not
3642 * need to get it as acquision also requires
3643 * the pmap spin lock.
3645 * However, we can race the wakeup.
3647 pmark = pmap_placemarker_hash(pmap, pindex);
3649 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3650 tsleep_interlock(pmark, 0);
3651 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3652 if (((*pmark ^ pindex) &
3653 ~PM_PLACEMARK_WAKEUP) == 0) {
3654 spin_unlock(&pmap->pm_spin);
3655 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3656 spin_lock(&pmap->pm_spin);
3662 * Setup the new entry
3664 pnew->pv_pmap = pmap;
3665 pnew->pv_pindex = pindex;
3666 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3669 pnew->pv_func = func;
3670 pnew->pv_line = lineno;
3671 if (pnew->pv_line_lastfree > 0) {
3672 pnew->pv_line_lastfree =
3673 -pnew->pv_line_lastfree;
3676 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3677 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3678 spin_unlock(&pmap->pm_spin);
3681 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3686 * We already have an entry, cleanup the staged pnew if
3687 * we can get the lock, otherwise block and retry.
3689 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3691 spin_unlock(&pmap->pm_spin);
3693 spin_unlock_shared(&pmap->pm_spin);
3695 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3697 zfree(pvzone, pnew);
3700 if (md->gd_newpv == NULL)
3701 md->gd_newpv = pnew;
3703 zfree(pvzone, pnew);
3706 KKASSERT(pv->pv_pmap == pmap &&
3707 pv->pv_pindex == pindex);
3712 spin_unlock(&pmap->pm_spin);
3713 _pv_lock(pv PMAP_DEBUG_COPY);
3715 spin_lock(&pmap->pm_spin);
3717 spin_unlock_shared(&pmap->pm_spin);
3718 _pv_lock(pv PMAP_DEBUG_COPY);
3720 spin_lock_shared(&pmap->pm_spin);
3727 * Find the requested PV entry, returning a locked+held pv or NULL
3731 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3736 spin_lock_shared(&pmap->pm_spin);
3741 pv = pv_entry_lookup(pmap, pindex);
3744 * Block if there is ANY placemarker. If we are to
3745 * return it, we must also aquire the spot, so we
3746 * have to block even if the placemarker is held on
3747 * a different address.
3749 * OPTIMIZATION: If pmarkp is passed as NULL the
3750 * caller is just probing (or looking for a real
3751 * pv_entry), and in this case we only need to check
3752 * to see if the placemarker matches pindex.
3757 * Requires exclusive pmap spinlock
3759 if (pmap_excl == 0) {
3761 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3762 spin_unlock_shared(&pmap->pm_spin);
3763 spin_lock(&pmap->pm_spin);
3768 pmark = pmap_placemarker_hash(pmap, pindex);
3770 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3771 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3772 tsleep_interlock(pmark, 0);
3773 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3774 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3775 ((*pmark ^ pindex) &
3776 ~PM_PLACEMARK_WAKEUP) == 0) {
3777 spin_unlock(&pmap->pm_spin);
3778 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3779 spin_lock(&pmap->pm_spin);
3784 if (atomic_swap_long(pmark, pindex) !=
3786 panic("_pv_get: pmark race");
3790 spin_unlock(&pmap->pm_spin);
3793 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3795 spin_unlock(&pmap->pm_spin);
3797 spin_unlock_shared(&pmap->pm_spin);
3798 KKASSERT(pv->pv_pmap == pmap &&
3799 pv->pv_pindex == pindex);
3803 spin_unlock(&pmap->pm_spin);
3804 _pv_lock(pv PMAP_DEBUG_COPY);
3806 spin_lock(&pmap->pm_spin);
3808 spin_unlock_shared(&pmap->pm_spin);
3809 _pv_lock(pv PMAP_DEBUG_COPY);
3811 spin_lock_shared(&pmap->pm_spin);
3817 * Lookup, hold, and attempt to lock (pmap,pindex).
3819 * If the entry does not exist NULL is returned and *errorp is set to 0
3821 * If the entry exists and could be successfully locked it is returned and
3822 * errorp is set to 0.
3824 * If the entry exists but could NOT be successfully locked it is returned
3825 * held and *errorp is set to 1.
3827 * If the entry is placemarked by someone else NULL is returned and *errorp
3832 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3836 spin_lock_shared(&pmap->pm_spin);
3838 pv = pv_entry_lookup(pmap, pindex);
3842 pmark = pmap_placemarker_hash(pmap, pindex);
3844 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3846 } else if (pmarkp &&
3847 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3851 * Can't set a placemark with a NULL pmarkp, or if
3852 * pmarkp is non-NULL but we failed to set our
3859 spin_unlock_shared(&pmap->pm_spin);
3865 * XXX This has problems if the lock is shared, why?
3867 if (pv_hold_try(pv)) {
3868 spin_unlock_shared(&pmap->pm_spin);
3870 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3871 return(pv); /* lock succeeded */
3873 spin_unlock_shared(&pmap->pm_spin);
3876 return (pv); /* lock failed */
3880 * Lock a held pv, keeping the hold count
3884 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
3889 count = pv->pv_hold;
3891 if ((count & PV_HOLD_LOCKED) == 0) {
3892 if (atomic_cmpset_int(&pv->pv_hold, count,
3893 count | PV_HOLD_LOCKED)) {
3896 pv->pv_line = lineno;
3902 tsleep_interlock(pv, 0);
3903 if (atomic_cmpset_int(&pv->pv_hold, count,
3904 count | PV_HOLD_WAITING)) {
3906 if (pmap_enter_debug > 0) {
3908 kprintf("pv waiting on %s:%d\n",
3909 pv->pv_func, pv->pv_line);
3912 tsleep(pv, PINTERLOCKED, "pvwait", hz);
3919 * Unlock a held and locked pv, keeping the hold count.
3923 pv_unlock(pv_entry_t pv)
3928 count = pv->pv_hold;
3930 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
3931 (PV_HOLD_LOCKED | 1));
3932 if (atomic_cmpset_int(&pv->pv_hold, count,
3934 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
3935 if (count & PV_HOLD_WAITING)
3943 * Unlock and drop a pv. If the pv is no longer associated with a pmap
3944 * and the hold count drops to zero we will free it.
3946 * Caller should not hold any spin locks. We are protected from hold races
3947 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
3948 * lock held. A pv cannot be located otherwise.
3952 pv_put(pv_entry_t pv)
3955 if (pmap_enter_debug > 0) {
3957 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
3962 * Normal put-aways must have a pv_m associated with the pv,
3963 * but allow the case where the pv has been destructed due
3964 * to pmap_dynamic_delete.
3966 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
3969 * Fast - shortcut most common condition
3971 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
3982 * Remove the pmap association from a pv, require that pv_m already be removed,
3983 * then unlock and drop the pv. Any pte operations must have already been
3984 * completed. This call may result in a last-drop which will physically free
3987 * Removing the pmap association entails an additional drop.
3989 * pv must be exclusively locked on call and will be disposed of on return.
3993 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
3998 pv->pv_func_lastfree = func;
3999 pv->pv_line_lastfree = lineno;
4001 KKASSERT(pv->pv_m == NULL);
4002 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
4003 (PV_HOLD_LOCKED|1));
4004 if ((pmap = pv->pv_pmap) != NULL) {
4005 spin_lock(&pmap->pm_spin);
4006 KKASSERT(pv->pv_pmap == pmap);
4007 if (pmap->pm_pvhint_pt == pv)
4008 pmap->pm_pvhint_pt = NULL;
4009 if (pmap->pm_pvhint_unused == pv)
4010 pmap->pm_pvhint_unused = NULL;
4011 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
4012 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4015 spin_unlock(&pmap->pm_spin);
4018 * Try to shortcut three atomic ops, otherwise fall through
4019 * and do it normally. Drop two refs and the lock all in
4023 if (vm_page_unwire_quick(pvp->pv_m))
4024 panic("_pv_free: bad wirecount on pvp");
4026 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
4028 if (pmap_enter_debug > 0) {
4030 kprintf("pv_free: free pv %p\n", pv);
4036 pv_drop(pv); /* ref for pv_pmap */
4043 * This routine is very drastic, but can save the system
4051 static int warningdone=0;
4053 if (pmap_pagedaemon_waken == 0)
4055 pmap_pagedaemon_waken = 0;
4056 if (warningdone < 5) {
4057 kprintf("pmap_collect: pv_entries exhausted -- "
4058 "suggest increasing vm.pmap_pv_entries above %ld\n",
4059 vm_pmap_pv_entries);
4063 for (i = 0; i < vm_page_array_size; i++) {
4064 m = &vm_page_array[i];
4065 if (m->wire_count || m->hold_count)
4067 if (vm_page_busy_try(m, TRUE) == 0) {
4068 if (m->wire_count == 0 && m->hold_count == 0) {
4077 * Scan the pmap for active page table entries and issue a callback.
4078 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4079 * its parent page table.
4081 * pte_pv will be NULL if the page or page table is unmanaged.
4082 * pt_pv will point to the page table page containing the pte for the page.
4084 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4085 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4086 * process pmap's PD and page to the callback function. This can be
4087 * confusing because the pt_pv is really a pd_pv, and the target page
4088 * table page is simply aliased by the pmap and not owned by it.
4090 * It is assumed that the start and end are properly rounded to the page size.
4092 * It is assumed that PD pages and above are managed and thus in the RB tree,
4093 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4095 struct pmap_scan_info {
4099 vm_pindex_t sva_pd_pindex;
4100 vm_pindex_t eva_pd_pindex;
4101 void (*func)(pmap_t, struct pmap_scan_info *,
4102 vm_pindex_t *, pv_entry_t, vm_offset_t,
4103 pt_entry_t *, void *);
4105 pmap_inval_bulk_t bulk_core;
4106 pmap_inval_bulk_t *bulk;
4111 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4112 static int pmap_scan_callback(pv_entry_t pv, void *data);
4115 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4117 struct pmap *pmap = info->pmap;
4118 pv_entry_t pt_pv; /* A page table PV */
4119 pv_entry_t pte_pv; /* A page table entry PV */
4120 vm_pindex_t *pte_placemark;
4121 vm_pindex_t *pt_placemark;
4124 struct pv_entry dummy_pv;
4129 if (info->sva == info->eva)
4132 info->bulk = &info->bulk_core;
4133 pmap_inval_bulk_init(&info->bulk_core, pmap);
4139 * Hold the token for stability; if the pmap is empty we have nothing
4143 if (pmap->pm_stats.resident_count == 0) {
4151 * Special handling for scanning one page, which is a very common
4152 * operation (it is?).
4154 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4156 if (info->sva + PAGE_SIZE == info->eva) {
4157 if (info->sva >= VM_MAX_USER_ADDRESS) {
4159 * Kernel mappings do not track wire counts on
4160 * page table pages and only maintain pd_pv and
4161 * pte_pv levels so pmap_scan() works.
4164 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4166 KKASSERT(pte_pv == NULL);
4167 ptep = vtopte(info->sva);
4170 * We hold pte_placemark across the operation for
4173 * WARNING! We must hold pt_placemark across the
4174 * *ptep test to prevent misintepreting
4175 * a non-zero *ptep as a shared page
4176 * table page. Hold it across the function
4177 * callback as well for SMP safety.
4179 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4181 KKASSERT(pte_pv == NULL);
4182 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4184 if (pt_pv == NULL) {
4187 pd_pv = pv_get(pmap,
4188 pmap_pd_pindex(info->sva),
4191 ptep = pv_pte_lookup(pd_pv,
4192 pmap_pt_index(info->sva));
4194 info->func(pmap, info,
4195 pt_placemark, pd_pv,
4199 pv_placemarker_wakeup(pmap,
4204 pv_placemarker_wakeup(pmap,
4208 pv_placemarker_wakeup(pmap, pt_placemark);
4210 pv_placemarker_wakeup(pmap, pte_placemark);
4213 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4217 * NOTE: *ptep can't be ripped out from under us if we hold
4218 * pte_pv (or pte_placemark) locked, but bits can
4224 KKASSERT(pte_pv == NULL);
4225 pv_placemarker_wakeup(pmap, pte_placemark);
4227 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]) ==
4228 pmap->pmap_bits[PG_V_IDX],
4229 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4230 *ptep, oldpte, info->sva));
4231 info->func(pmap, info, pte_placemark, pt_pv,
4232 info->sva, ptep, info->arg);
4237 pmap_inval_bulk_flush(info->bulk);
4242 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4245 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4246 * bounds, resulting in a pd_pindex of 0. To solve the
4247 * problem we use an inclusive range.
4249 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4250 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4252 if (info->sva >= VM_MAX_USER_ADDRESS) {
4254 * The kernel does not currently maintain any pv_entry's for
4255 * higher-level page tables.
4257 bzero(&dummy_pv, sizeof(dummy_pv));
4258 dummy_pv.pv_pindex = info->sva_pd_pindex;
4259 spin_lock(&pmap->pm_spin);
4260 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4261 pmap_scan_callback(&dummy_pv, info);
4262 ++dummy_pv.pv_pindex;
4263 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4266 spin_unlock(&pmap->pm_spin);
4269 * User page tables maintain local PML4, PDP, PD, and PT
4270 * pv_entry's. pv_entry's are not used for PTEs.
4272 spin_lock(&pmap->pm_spin);
4273 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4274 pmap_scan_callback, info);
4275 spin_unlock(&pmap->pm_spin);
4277 pmap_inval_bulk_flush(info->bulk);
4281 * WARNING! pmap->pm_spin held
4283 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4284 * bounds, resulting in a pd_pindex of 0. To solve the
4285 * problem we use an inclusive range.
4288 pmap_scan_cmp(pv_entry_t pv, void *data)
4290 struct pmap_scan_info *info = data;
4291 if (pv->pv_pindex < info->sva_pd_pindex)
4293 if (pv->pv_pindex > info->eva_pd_pindex)
4299 * pmap_scan() by PDs
4301 * WARNING! pmap->pm_spin held
4304 pmap_scan_callback(pv_entry_t pv, void *data)
4306 struct pmap_scan_info *info = data;
4307 struct pmap *pmap = info->pmap;
4308 pv_entry_t pd_pv; /* A page directory PV */
4309 pv_entry_t pt_pv; /* A page table PV */
4310 vm_pindex_t *pt_placemark;
4315 vm_offset_t va_next;
4316 vm_pindex_t pd_pindex;
4326 * Pull the PD pindex from the pv before releasing the spinlock.
4328 * WARNING: pv is faked for kernel pmap scans.
4330 pd_pindex = pv->pv_pindex;
4331 spin_unlock(&pmap->pm_spin);
4332 pv = NULL; /* invalid after spinlock unlocked */
4335 * Calculate the page range within the PD. SIMPLE pmaps are
4336 * direct-mapped for the entire 2^64 address space. Normal pmaps
4337 * reflect the user and kernel address space which requires
4338 * cannonicalization w/regards to converting pd_pindex's back
4341 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4342 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4343 (sva & PML4_SIGNMASK)) {
4344 sva |= PML4_SIGNMASK;
4346 eva = sva + NBPDP; /* can overflow */
4347 if (sva < info->sva)
4349 if (eva < info->sva || eva > info->eva)
4353 * NOTE: kernel mappings do not track page table pages, only
4356 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4357 * However, for the scan to be efficient we try to
4358 * cache items top-down.
4363 for (; sva < eva; sva = va_next) {
4366 if (sva >= VM_MAX_USER_ADDRESS) {
4375 * PD cache, scan shortcut if it doesn't exist.
4377 if (pd_pv == NULL) {
4378 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4379 } else if (pd_pv->pv_pmap != pmap ||
4380 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4382 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4384 if (pd_pv == NULL) {
4385 va_next = (sva + NBPDP) & ~PDPMASK;
4394 * NOTE: The cached pt_pv can be removed from the pmap when
4395 * pmap_dynamic_delete is enabled.
4397 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4398 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4402 if (pt_pv == NULL) {
4403 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4404 &pt_placemark, &error);
4406 pv_put(pd_pv); /* lock order */
4413 pv_placemarker_wait(pmap, pt_placemark);
4418 /* may have to re-check later if pt_pv is NULL here */
4422 * If pt_pv is NULL we either have a shared page table
4423 * page (NOT IMPLEMENTED XXX) and must issue a callback
4424 * specific to that case, or there is no page table page.
4426 * Either way we can skip the page table page.
4428 * WARNING! pt_pv can also be NULL due to a pv creation
4429 * race where we find it to be NULL and then
4430 * later see a pte_pv. But its possible the pt_pv
4431 * got created inbetween the two operations, so
4434 * XXX This should no longer be the case because
4435 * we have pt_placemark.
4437 if (pt_pv == NULL) {
4441 * Possible unmanaged (shared from another pmap)
4444 * WARNING! We must hold pt_placemark across the
4445 * *ptep test to prevent misintepreting
4446 * a non-zero *ptep as a shared page
4447 * table page. Hold it across the function
4448 * callback as well for SMP safety.
4451 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4452 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4453 info->func(pmap, info, pt_placemark, pd_pv,
4454 sva, ptep, info->arg);
4456 pv_placemarker_wakeup(pmap, pt_placemark);
4459 pv_placemarker_wakeup(pmap, pt_placemark);
4463 * Done, move to next page table page.
4465 va_next = (sva + NBPDR) & ~PDRMASK;
4472 * From this point in the loop testing pt_pv for non-NULL
4473 * means we are in UVM, else if it is NULL we are in KVM.
4475 * Limit our scan to either the end of the va represented
4476 * by the current page table page, or to the end of the
4477 * range being removed.
4480 va_next = (sva + NBPDR) & ~PDRMASK;
4487 * Scan the page table for pages. Some pages may not be
4488 * managed (might not have a pv_entry).
4490 * There is no page table management for kernel pages so
4491 * pt_pv will be NULL in that case, but otherwise pt_pv
4492 * is non-NULL, locked, and referenced.
4496 * At this point a non-NULL pt_pv means a UVA, and a NULL
4497 * pt_pv means a KVA.
4500 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4504 while (sva < va_next) {
4505 vm_pindex_t *pte_placemark;
4509 * Yield every 64 pages, stop if requested.
4511 if ((++info->count & 63) == 0)
4517 * We can shortcut our scan if *ptep == 0. This is
4518 * an unlocked check.
4528 * Acquire the pte_placemark. pte_pv's won't exist
4531 * A multitude of races are possible here so if we
4532 * cannot lock definite state we clean out our cache
4533 * and break the inner while() loop to force a loop
4534 * up to the top of the for().
4536 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4537 * validity instead of looping up?
4539 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4540 &pte_placemark, &error);
4541 KKASSERT(pte_pv == NULL);
4544 pv_put(pd_pv); /* lock order */
4548 pv_put(pt_pv); /* lock order */
4551 pv_placemarker_wait(pmap, pte_placemark);
4552 va_next = sva; /* retry */
4557 * Reload *ptep after successfully locking the
4563 pv_placemarker_wakeup(pmap, pte_placemark);
4570 * We can't hold pd_pv across the callback (because
4571 * we don't pass it to the callback and the callback
4575 vm_page_wire_quick(pd_pv->pv_m);
4580 * Ready for the callback. The locked placemarker
4581 * is consumed by the callback.
4583 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4587 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4588 ("badC *ptep %016lx/%016lx sva %016lx",
4589 *ptep, oldpte, sva));
4591 * We must unlock pd_pv across the callback
4592 * to avoid deadlocks on any recursive
4593 * disposal. Re-check that it still exists
4596 * Call target disposes of pte_placemark
4597 * and may destroy but will not dispose
4600 info->func(pmap, info, pte_placemark, pt_pv,
4601 sva, ptep, info->arg);
4606 * We must unlock pd_pv across the callback
4607 * to avoid deadlocks on any recursive
4608 * disposal. Re-check that it still exists
4611 * Call target disposes of pte_placemark
4612 * and may destroy but will not dispose
4615 KASSERT((oldpte & pmap->pmap_bits[PG_V_IDX]),
4616 ("badD *ptep %016lx/%016lx sva %016lx ",
4617 *ptep, oldpte, sva));
4618 info->func(pmap, info, pte_placemark, pt_pv,
4619 sva, ptep, info->arg);
4623 if (vm_page_unwire_quick(pd_pv->pv_m)) {
4624 panic("pmap_scan_callback: "
4625 "bad wirecount on pd_pv");
4627 if (pd_pv->pv_pmap == NULL) {
4628 va_next = sva; /* retry */
4634 * NOTE: The cached pt_pv can be removed from the
4635 * pmap when pmap_dynamic_delete is enabled,
4636 * which will cause ptep to become stale.
4638 * This also means that no pages remain under
4639 * the PT, so we can just break out of the inner
4640 * loop and let the outer loop clean everything
4643 if (pt_pv && pt_pv->pv_pmap != pmap)
4657 if ((++info->count & 7) == 0)
4661 * Relock before returning.
4663 spin_lock(&pmap->pm_spin);
4668 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4670 struct pmap_scan_info info;
4675 info.func = pmap_remove_callback;
4677 pmap_scan(&info, 1);
4680 if (eva - sva < 1024*1024) {
4682 cpu_invlpg((void *)sva);
4690 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4692 struct pmap_scan_info info;
4697 info.func = pmap_remove_callback;
4699 pmap_scan(&info, 0);
4703 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4704 vm_pindex_t *pte_placemark, pv_entry_t pt_pv,
4705 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4711 * Managed or unmanaged pte (pte_placemark is non-NULL)
4713 * pt_pv's wire_count is still bumped by unmanaged pages
4714 * so we must decrement it manually.
4716 * We have to unwire the target page table page.
4719 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4720 oldm = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4721 atomic_add_long(&oldm->md.interlock_count, 1);
4726 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4727 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4730 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
4731 KKASSERT(pte & pmap->pmap_bits[PG_V_IDX]);
4732 if (pte & pmap->pmap_bits[PG_M_IDX])
4734 if (pte & pmap->pmap_bits[PG_A_IDX])
4735 vm_page_flag_set(p, PG_REFERENCED);
4738 * (p) is not hard-busied.
4740 * We can safely clear PG_MAPPED and PG_WRITEABLE only
4741 * if PG_MAPPEDMULTI is not set, atomically.
4743 pmap_removed_pte(p, pte);
4745 if (pte & pmap->pmap_bits[PG_V_IDX]) {
4746 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4747 if (pt_pv && vm_page_unwire_quick(pt_pv->pv_m))
4748 panic("pmap_remove: insufficient wirecount");
4750 if (pte & pmap->pmap_bits[PG_W_IDX])
4751 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4752 if (pte & pmap->pmap_bits[PG_G_IDX])
4753 cpu_invlpg((void *)va);
4754 pv_placemarker_wakeup(pmap, pte_placemark);
4756 if ((atomic_fetchadd_long(&oldm->md.interlock_count, -1) &
4757 0x7FFFFFFFFFFFFFFFLU) == 0x4000000000000001LU) {
4758 atomic_clear_long(&oldm->md.interlock_count,
4759 0x4000000000000000LU);
4760 wakeup(&oldm->md.interlock_count);
4766 * Removes this physical page from all physical maps in which it resides.
4767 * Reflects back modify bits to the pager.
4769 * This routine may not be called from an interrupt.
4771 * The page must be busied by its caller, preventing new ptes from being
4772 * installed. This allows us to assert that pmap_count is zero and safely
4773 * clear the MAPPED and WRITEABLE bits upon completion.
4777 pmap_remove_all(vm_page_t m)
4782 if (__predict_false(!pmap_initialized))
4786 * pmap_count doesn't cover fictitious pages, but PG_MAPPED does
4787 * (albeit without certain race protections).
4790 if (m->md.pmap_count == 0)
4793 if ((m->flags & PG_MAPPED) == 0)
4796 retry = ticks + hz * 60;
4798 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
4799 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4800 PMAP_PAGE_BACKING_RETRY;
4801 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4802 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4804 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4805 vm_page_flag_set(m, PG_REFERENCED);
4808 * NOTE: m is not hard-busied so it is not safe to
4809 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4810 * transition against them being set in
4813 pmap_removed_pte(m, ipte);
4817 * Cleanup various tracking counters. pt_pv can't go away
4818 * due to our wired ref.
4820 if (ipmap != kernel_pmap) {
4823 spin_lock_shared(&ipmap->pm_spin);
4824 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4825 spin_unlock_shared(&ipmap->pm_spin);
4828 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4829 panic("pmap_remove_all: bad "
4830 "wire_count on pt_pv");
4833 &ipmap->pm_stats.resident_count, -1);
4836 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4837 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4838 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4839 cpu_invlpg((void *)iva);
4840 } PMAP_PAGE_BACKING_DONE;
4843 * If our scan lost a pte swap race oldm->md.interlock_count might
4844 * be set from the pmap_enter() code. If so sleep a little and try
4847 icount = atomic_fetchadd_long(&m->md.interlock_count,
4848 0x8000000000000000LU) +
4849 0x8000000000000000LU;
4851 while (icount & 0x3FFFFFFFFFFFFFFFLU) {
4852 tsleep_interlock(&m->md.interlock_count, 0);
4853 if (atomic_fcmpset_long(&m->md.interlock_count, &icount,
4854 icount | 0x4000000000000000LU)) {
4855 tsleep(&m->md.interlock_count, PINTERLOCKED,
4857 icount = m->md.interlock_count;
4858 if (retry - ticks > 0)
4860 panic("pmap_remove_all: cannot return interlock_count "
4862 m, m->md.interlock_count);
4865 vm_page_flag_clear(m, PG_MAPPED | PG_MAPPEDMULTI | PG_WRITEABLE);
4869 * Removes the page from a particular pmap.
4871 * The page must be busied by the caller.
4874 pmap_remove_specific(pmap_t pmap_match, vm_page_t m)
4876 if (__predict_false(!pmap_initialized))
4880 * PG_MAPPED test works for both non-fictitious and fictitious pages.
4882 if ((m->flags & PG_MAPPED) == 0)
4885 PMAP_PAGE_BACKING_SCAN(m, pmap_match, ipmap, iptep, ipte, iva) {
4886 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, 0))
4887 PMAP_PAGE_BACKING_RETRY;
4888 if (ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) {
4889 if (ipte & ipmap->pmap_bits[PG_M_IDX])
4891 if (ipte & ipmap->pmap_bits[PG_A_IDX])
4892 vm_page_flag_set(m, PG_REFERENCED);
4895 * NOTE: m is not hard-busied so it is not safe to
4896 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
4897 * transition against them being set in
4900 pmap_removed_pte(m, ipte);
4904 * Cleanup various tracking counters. pt_pv can't go away
4905 * due to our wired ref.
4907 if (ipmap != kernel_pmap) {
4910 spin_lock_shared(&ipmap->pm_spin);
4911 pt_pv = pv_entry_lookup(ipmap, pmap_pt_pindex(iva));
4912 spin_unlock_shared(&ipmap->pm_spin);
4916 &ipmap->pm_stats.resident_count, -1);
4917 if (vm_page_unwire_quick(pt_pv->pv_m)) {
4918 panic("pmap_remove_specific: bad "
4919 "wire_count on pt_pv");
4923 if (ipte & ipmap->pmap_bits[PG_W_IDX])
4924 atomic_add_long(&ipmap->pm_stats.wired_count, -1);
4925 if (ipte & ipmap->pmap_bits[PG_G_IDX])
4926 cpu_invlpg((void *)iva);
4927 } PMAP_PAGE_BACKING_DONE;
4931 * Set the physical protection on the specified range of this map
4932 * as requested. This function is typically only used for debug watchpoints
4935 * This function may not be called from an interrupt if the map is
4936 * not the kernel_pmap.
4938 * NOTE! For shared page table pages we just unmap the page.
4941 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4943 struct pmap_scan_info info;
4944 /* JG review for NX */
4948 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
4949 pmap_remove(pmap, sva, eva);
4952 if (prot & VM_PROT_WRITE)
4957 info.func = pmap_protect_callback;
4959 pmap_scan(&info, 1);
4964 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
4965 vm_pindex_t *pte_placemark,
4966 pv_entry_t pt_pv, vm_offset_t va,
4967 pt_entry_t *ptep, void *arg __unused)
4977 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
4978 cbits &= ~pmap->pmap_bits[PG_A_IDX];
4979 cbits &= ~pmap->pmap_bits[PG_M_IDX];
4981 /* else unmanaged page, adjust bits, no wire changes */
4984 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
4986 if (pmap_enter_debug > 0) {
4988 kprintf("pmap_protect va=%lx ptep=%p "
4989 "pt_pv=%p cbits=%08lx\n",
4990 va, ptep, pt_pv, cbits
4994 if (pbits != cbits) {
4995 if (!pmap_inval_smp_cmpset(pmap, va,
4996 ptep, pbits, cbits)) {
5000 if (pbits & pmap->pmap_bits[PG_MANAGED_IDX]) {
5001 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5002 if (pbits & pmap->pmap_bits[PG_A_IDX])
5003 vm_page_flag_set(m, PG_REFERENCED);
5004 if (pbits & pmap->pmap_bits[PG_M_IDX])
5008 pv_placemarker_wakeup(pmap, pte_placemark);
5012 * Insert the vm_page (m) at the virtual address (va), replacing any prior
5013 * mapping at that address. Set protection and wiring as requested.
5015 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5016 * possible. If it is we enter the page into the appropriate shared pmap
5017 * hanging off the related VM object instead of the passed pmap, then we
5018 * share the page table page from the VM object's pmap into the current pmap.
5020 * NOTE: This routine MUST insert the page into the pmap now, it cannot
5024 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5025 boolean_t wired, vm_map_entry_t entry)
5027 pv_entry_t pt_pv; /* page table */
5028 pv_entry_t pte_pv; /* page table entry */
5029 vm_pindex_t *pte_placemark;
5041 va = trunc_page(va);
5042 #ifdef PMAP_DIAGNOSTIC
5044 panic("pmap_enter: toobig");
5045 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5046 panic("pmap_enter: invalid to pmap_enter page table "
5047 "pages (va: 0x%lx)", va);
5049 if (va < UPT_MAX_ADDRESS && pmap == kernel_pmap) {
5050 kprintf("Warning: pmap_enter called on UVA with "
5053 db_print_backtrace();
5056 if (va >= UPT_MAX_ADDRESS && pmap != kernel_pmap) {
5057 kprintf("Warning: pmap_enter called on KVA without"
5060 db_print_backtrace();
5065 * Get the locked page table page (pt_pv) for our new page table
5066 * entry, allocating it if necessary.
5068 * There is no pte_pv for a terminal pte so the terminal pte will
5069 * be locked via pte_placemark.
5071 * Only MMU actions by the CPU itself can modify the ptep out from
5074 * If the pmap is still being initialized we assume existing
5077 * NOTE: Kernel mapppings do not track page table pages
5078 * (i.e. there is no pt_pv pt_pv structure).
5080 * NOTE: origpte here is 'tentative', used only to check for
5081 * the degenerate case where the entry already exists and
5084 if (__predict_false(pmap_initialized == FALSE)) {
5087 pte_placemark = NULL;
5091 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5092 KKASSERT(pte_pv == NULL);
5093 if (va >= VM_MAX_USER_ADDRESS) {
5097 pt_pv = pmap_allocpte(pmap, pmap_pt_pindex(va), NULL);
5098 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5104 pa = VM_PAGE_TO_PHYS(m);
5107 * Calculate the new PTE.
5109 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5110 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5112 newpte |= pmap->pmap_bits[PG_W_IDX];
5113 if (va < VM_MAX_USER_ADDRESS)
5114 newpte |= pmap->pmap_bits[PG_U_IDX];
5115 if ((m->flags & PG_FICTITIOUS) == 0)
5116 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5117 // if (pmap == kernel_pmap)
5118 // newpte |= pgeflag;
5119 newpte |= pmap->pmap_cache_bits_pte[m->pat_mode];
5122 * It is possible for multiple faults to occur in threaded
5123 * environments, the existing pte might be correct.
5125 if (((origpte ^ newpte) &
5126 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5127 pmap->pmap_bits[PG_A_IDX])) == 0) {
5132 * Adjust page flags. The page is soft-busied or hard-busied, we
5133 * should be able to safely set PG_* flag bits even with the (shared)
5136 * The pmap_count and writeable_count is only tracked for
5137 * non-fictitious pages. As a bit of a safety, bump pmap_count
5138 * and set the PG_* bits before mapping the page. If another part
5139 * of the system does not properly hard-busy the page (against our
5140 * soft-busy or hard-busy) in order to remove mappings it might not
5141 * see the pte that we are about to add and thus will not be able to
5142 * drop pmap_count to 0.
5144 * The PG_MAPPED and PG_WRITEABLE flags are set for any type of page.
5146 * NOTE! PG_MAPPED and PG_WRITEABLE can only be cleared when
5147 * the page is hard-busied AND pmap_count is 0. This
5148 * interlocks our setting of the flags here.
5150 /*vm_page_spin_lock(m);*/
5153 * In advanced mode we keep track of single mappings verses
5154 * multiple mappings in order to avoid unnecessary vm_page_protect()
5155 * calls (particularly on the kernel_map).
5157 * If non-advanced mode we track the mapping count for similar effect.
5159 * Avoid modifying the vm_page as much as possible, conditionalize
5160 * updates to reduce cache line ping-ponging.
5166 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5167 nflags |= PG_WRITEABLE;
5168 if (flags & PG_MAPPED)
5169 nflags |= PG_MAPPEDMULTI;
5170 if (flags == (flags | nflags))
5172 if (atomic_fcmpset_int(&m->flags, &flags, flags | nflags))
5175 /*vm_page_spin_unlock(m);*/
5178 * A race can develop when replacing an existing mapping. The new
5179 * page has been busied and the pte is placemark-locked, but the
5180 * old page could be ripped out from under us at any time by
5183 * If we do nothing, a concurrent backing scan may clear
5184 * PG_WRITEABLE and PG_MAPPED before we can act on oldm.
5186 opa = origpte & PG_FRAME;
5187 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5188 oldm = PHYS_TO_VM_PAGE(opa);
5189 KKASSERT(opa == oldm->phys_addr);
5190 KKASSERT(entry != NULL);
5191 atomic_add_long(&oldm->md.interlock_count, 1);
5197 * Swap the new and old PTEs and perform any necessary SMP
5200 if ((prot & VM_PROT_NOSYNC) || (opa == 0 && pt_pv != NULL)) {
5202 * Explicitly permitted to avoid pmap cpu mask synchronization
5203 * or the prior content of a non-kernel-related pmap was
5206 origpte = atomic_swap_long(ptep, newpte);
5208 cpu_invlpg((void *)va);
5211 * Not permitted to avoid pmap cpu mask synchronization
5212 * or there prior content being replaced or this is a kernel
5215 * Due to other kernel optimizations, we cannot assume a
5216 * 0->non_zero transition of *ptep can be done with a swap.
5218 origpte = pmap_inval_smp(pmap, va, 1, ptep, newpte);
5220 opa = origpte & PG_FRAME;
5223 if (pmap_enter_debug > 0) {
5225 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5226 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5228 origpte, newpte, ptep,
5229 pte_pv, pt_pv, opa, prot);
5234 * Account for the changes in the pt_pv and pmap.
5236 * Retain the same wiring count due to replacing an existing page,
5237 * or bump the wiring count for a new page.
5239 if (pt_pv && opa == 0) {
5240 vm_page_wire_quick(pt_pv->pv_m);
5241 atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
5243 if (wired && (origpte & pmap->pmap_bits[PG_W_IDX]) == 0)
5244 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5247 * Account for the removal of the old page. pmap and pt_pv stats
5248 * have already been fully adjusted for both.
5250 * WARNING! oldm is not soft or hard-busied. The pte at worst can
5251 * only be removed out from under us since we hold the
5252 * placemarker. So if it is still there, it must not have
5255 * WARNING! A backing scan can clear PG_WRITEABLE and/or PG_MAPPED
5256 * and rip oldm away from us, possibly even freeing or
5257 * paging it, and not setting our dirtying below.
5259 * To deal with this, oldm->md.interlock_count is bumped
5260 * to indicate that we might (only might) have won the pte
5261 * swap race, and then released below.
5263 if (opa && (origpte & pmap->pmap_bits[PG_MANAGED_IDX])) {
5264 KKASSERT(oldm == PHYS_TO_VM_PAGE(opa));
5265 if (origpte & pmap->pmap_bits[PG_M_IDX])
5266 vm_page_dirty(oldm);
5267 if (origpte & pmap->pmap_bits[PG_A_IDX])
5268 vm_page_flag_set(oldm, PG_REFERENCED);
5271 * NOTE: oldm is not hard-busied so it is not safe to
5272 * clear PG_MAPPED and PG_WRITEABLE on the 1->0
5273 * transition against them being set in
5276 pmap_removed_pte(oldm, origpte);
5279 if ((atomic_fetchadd_long(&oldm->md.interlock_count, -1) &
5280 0x7FFFFFFFFFFFFFFFLU) == 0x4000000000000001LU) {
5281 atomic_clear_long(&oldm->md.interlock_count,
5282 0x4000000000000000LU);
5283 wakeup(&oldm->md.interlock_count);
5288 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5289 (m->flags & PG_MAPPED));
5292 * Cleanup the pv entry, allowing other accessors. If the new page
5293 * is not managed but we have a pte_pv (which was locking our
5294 * operation), we can free it now. pte_pv->pv_m should be NULL.
5297 pv_placemarker_wakeup(pmap, pte_placemark);
5303 * Make a temporary mapping for a physical address. This is only intended
5304 * to be used for panic dumps.
5306 * The caller is responsible for calling smp_invltlb().
5309 pmap_kenter_temporary(vm_paddr_t pa, long i)
5311 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5312 return ((void *)crashdumpmap);
5316 #define MAX_INIT_PT (96)
5319 * This routine preloads the ptes for a given object into the specified pmap.
5320 * This eliminates the blast of soft faults on process startup and
5321 * immediately after an mmap.
5323 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5327 pmap_object_init_pt(pmap_t pmap, vm_map_entry_t entry,
5328 vm_offset_t addr, vm_size_t size, int limit)
5331 vm_prot_t prot = entry->protection;
5332 vm_object_t object = entry->ba.object;
5333 vm_pindex_t pindex = atop(entry->ba.offset + (addr - entry->ba.start));
5334 struct rb_vm_page_scan_info info;
5339 * We can't preinit if read access isn't set or there is no pmap
5342 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5346 * We can't preinit if the pmap is not the current pmap
5348 lp = curthread->td_lwp;
5349 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5353 * Misc additional checks
5355 psize = x86_64_btop(size);
5357 if ((object->type != OBJT_VNODE) ||
5358 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5359 (object->resident_page_count > MAX_INIT_PT))) {
5363 if (pindex + psize > object->size) {
5364 if (object->size < pindex)
5366 psize = object->size - pindex;
5373 * If everything is segment-aligned do not pre-init here. Instead
5374 * allow the normal vm_fault path to pass a segment hint to
5375 * pmap_enter() which will then use an object-referenced shared
5378 if ((addr & SEG_MASK) == 0 &&
5379 (ctob(psize) & SEG_MASK) == 0 &&
5380 (ctob(pindex) & SEG_MASK) == 0) {
5385 * Use a red-black scan to traverse the requested range and load
5386 * any valid pages found into the pmap.
5388 * We cannot safely scan the object's memq without holding the
5391 info.start_pindex = pindex;
5392 info.end_pindex = pindex + psize - 1;
5397 info.object = object;
5401 * By using the NOLK scan, the callback function must be sure
5402 * to return -1 if the VM page falls out of the object.
5404 vm_object_hold_shared(object);
5405 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5406 pmap_object_init_pt_callback, &info);
5407 vm_object_drop(object);
5415 pmap_object_init_pt_callback(vm_page_t p, void *data)
5417 struct rb_vm_page_scan_info *info = data;
5418 vm_pindex_t rel_index;
5422 * don't allow an madvise to blow away our really
5423 * free pages allocating pv entries.
5425 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5426 vmstats.v_free_count < vmstats.v_free_reserved) {
5431 * Ignore list markers and ignore pages we cannot instantly
5432 * busy (while holding the object token).
5434 if (p->flags & PG_MARKER)
5439 if (vm_page_busy_try(p, TRUE))
5442 if (vm_page_sbusy_try(p))
5445 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5446 (p->flags & PG_FICTITIOUS) == 0) {
5447 if ((p->queue - p->pc) == PQ_CACHE) {
5448 if (hard_busy == 0) {
5449 vm_page_sbusy_drop(p);
5453 vm_page_deactivate(p);
5455 rel_index = p->pindex - info->start_pindex;
5456 pmap_enter(info->pmap, info->addr + x86_64_ptob(rel_index), p,
5457 VM_PROT_READ, FALSE, info->entry);
5462 vm_page_sbusy_drop(p);
5465 * We are using an unlocked scan (that is, the scan expects its
5466 * current element to remain in the tree on return). So we have
5467 * to check here and abort the scan if it isn't.
5469 if (p->object != info->object)
5478 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5481 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5484 * The address must reside within a vm_map mapped range to ensure that the
5485 * page table doesn't get ripped out from under us.
5487 * XXX This is safe only because page table pages are not freed.
5490 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5494 /*spin_lock(&pmap->pm_spin);*/
5495 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5496 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5497 /*spin_unlock(&pmap->pm_spin);*/
5501 /*spin_unlock(&pmap->pm_spin);*/
5506 * Change the wiring attribute for a pmap/va pair. The mapping must already
5507 * exist in the pmap. The mapping may or may not be managed. The wiring in
5508 * the page is not changed, the page is returned so the caller can adjust
5509 * its wiring (the page is not locked in any way).
5511 * Wiring is not a hardware characteristic so there is no need to invalidate
5512 * TLB. However, in an SMP environment we must use a locked bus cycle to
5513 * update the pte (if we are not using the pmap_inval_*() API that is)...
5514 * it's ok to do this for simple wiring changes.
5517 pmap_unwire(pmap_t pmap, vm_offset_t va)
5528 * Assume elements in the kernel pmap are stable
5530 if (pmap == kernel_pmap) {
5531 if (pmap_pt(pmap, va) == 0)
5533 ptep = pmap_pte_quick(pmap, va);
5534 if (pmap_pte_v(pmap, ptep)) {
5535 if (pmap_pte_w(pmap, ptep))
5536 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5537 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5538 pa = *ptep & PG_FRAME;
5539 m = PHYS_TO_VM_PAGE(pa);
5545 * We can only [un]wire pmap-local pages (we cannot wire
5548 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5552 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5553 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5558 if (pmap_pte_w(pmap, ptep)) {
5559 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5562 /* XXX else return NULL so caller doesn't unwire m ? */
5564 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5566 pa = *ptep & PG_FRAME;
5567 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5574 * Copy the range specified by src_addr/len from the source map to
5575 * the range dst_addr/len in the destination map.
5577 * This routine is only advisory and need not do anything.
5580 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5581 vm_size_t len, vm_offset_t src_addr)
5588 * Zero the specified physical page.
5590 * This function may be called from an interrupt and no locking is
5594 pmap_zero_page(vm_paddr_t phys)
5596 vm_offset_t va = PHYS_TO_DMAP(phys);
5598 pagezero((void *)va);
5604 * Zero part of a physical page by mapping it into memory and clearing
5605 * its contents with bzero.
5607 * off and size may not cover an area beyond a single hardware page.
5610 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5612 vm_offset_t virt = PHYS_TO_DMAP(phys);
5614 bzero((char *)virt + off, size);
5620 * Copy the physical page from the source PA to the target PA.
5621 * This function may be called from an interrupt. No locking
5625 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5627 vm_offset_t src_virt, dst_virt;
5629 src_virt = PHYS_TO_DMAP(src);
5630 dst_virt = PHYS_TO_DMAP(dst);
5631 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5635 * pmap_copy_page_frag:
5637 * Copy the physical page from the source PA to the target PA.
5638 * This function may be called from an interrupt. No locking
5642 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5644 vm_offset_t src_virt, dst_virt;
5646 src_virt = PHYS_TO_DMAP(src);
5647 dst_virt = PHYS_TO_DMAP(dst);
5649 bcopy((char *)src_virt + (src & PAGE_MASK),
5650 (char *)dst_virt + (dst & PAGE_MASK),
5655 * Remove all pages from specified address space this aids process exit
5656 * speeds. Also, this code may be special cased for the current process
5660 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5662 pmap_remove_noinval(pmap, sva, eva);
5667 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5668 * routines are inline, and a lot of things compile-time evaluate.
5670 * Currently only used to test the 'M'odified bit. If the page
5671 * is not PG_WRITEABLE, the 'M'odified bit cannot be set and we
5672 * return immediately. Fictitious pages do not track this bit.
5676 pmap_testbit(vm_page_t m, int bit)
5680 if (__predict_false(!pmap_initialized || (m->flags & PG_FICTITIOUS)))
5683 * Nothing to do if all the mappings are already read-only.
5684 * The page's [M]odify bits have already been synchronized
5685 * to the vm_page_t and cleaned out.
5687 if (bit == PG_M_IDX && (m->flags & PG_WRITEABLE) == 0)
5691 * Iterate the mapping
5693 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5694 if (ipte & ipmap->pmap_bits[bit]) {
5698 } PMAP_PAGE_BACKING_DONE;
5703 * This routine is used to modify bits in ptes. Only one bit should be
5704 * specified. PG_RW requires special handling. This call works with
5705 * any sort of mapped page. PG_FICTITIOUS pages might not be optimal.
5707 * Caller must NOT hold any spin locks
5708 * Caller must hold (m) hard-busied
5710 * NOTE: When clearing PG_M we could also (not implemented) drop
5711 * through to the PG_RW code and clear PG_RW too, forcing
5712 * a fault on write to redetect PG_M for virtual kernels, but
5713 * it isn't necessary since virtual kernels invalidate the
5714 * pte when they clear the VPTE_M bit in their virtual page
5717 * NOTE: Does not re-dirty the page when clearing only PG_M.
5719 * NOTE: Because we do not lock the pv, *pte can be in a state of
5720 * flux. Despite this the value of *pte is still somewhat
5721 * related while we hold the vm_page spin lock.
5723 * *pte can be zero due to this race. Since we are clearing
5724 * bits we basically do no harm when this race occurs.
5728 pmap_clearbit(vm_page_t m, int bit_index)
5735 * Too early in the boot
5737 if (__predict_false(!pmap_initialized)) {
5738 if (bit_index == PG_RW_IDX)
5739 vm_page_flag_clear(m, PG_WRITEABLE);
5742 if ((m->flags & (PG_MAPPED | PG_WRITEABLE)) == 0)
5746 * Being asked to clear other random bits, we don't track them
5747 * so we have to iterate.
5749 * pmap_clear_reference() is called (into here) with the page
5750 * hard-busied to check whether the page is still mapped and
5751 * will clear PG_MAPPED and PG_WRITEABLE if it isn't.
5753 if (bit_index != PG_RW_IDX) {
5759 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5763 if (ipte & ipmap->pmap_bits[bit_index]) {
5764 atomic_clear_long(iptep,
5765 ipmap->pmap_bits[bit_index]);
5767 } PMAP_PAGE_BACKING_DONE;
5770 icount = atomic_fetchadd_long(&m->md.interlock_count,
5771 0x8000000000000000LU);
5772 if ((icount & 0x3FFFFFFFFFFFFFFFLU) == 0) {
5773 vm_page_flag_clear(m, PG_MAPPED |
5783 * Being asked to clear the RW bit.
5785 * Nothing to do if all the mappings are already read-only
5787 if ((m->flags & PG_WRITEABLE) == 0)
5791 * Iterate the mappings and check.
5793 retry = ticks + hz * 60;
5796 * Clear PG_RW. This also clears PG_M and marks the page dirty if
5799 * Since the caller holds the page hard-busied we can safely clear
5800 * PG_WRITEABLE, and callers expect us to for the PG_RW_IDX path.
5802 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5804 if ((ipte & ipmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5807 if ((ipte & ipmap->pmap_bits[PG_RW_IDX]) == 0)
5809 npte = ipte & ~(ipmap->pmap_bits[PG_RW_IDX] |
5810 ipmap->pmap_bits[PG_M_IDX]);
5811 if (!pmap_inval_smp_cmpset(ipmap, iva, iptep, ipte, npte))
5812 PMAP_PAGE_BACKING_RETRY;
5813 if (ipte & ipmap->pmap_bits[PG_M_IDX])
5817 * NOTE: m is not hard-busied so it is not safe to
5818 * clear PG_WRITEABLE on the 1->0 transition
5819 * against it being set in pmap_enter().
5821 * pmap_count and writeable_count are only applicable
5822 * to non-fictitious pages (PG_MANAGED_IDX from pte)
5824 } PMAP_PAGE_BACKING_DONE;
5827 * If our scan lost a pte swap race oldm->md.interlock_count might
5828 * be set from the pmap_enter() code. If so sleep a little and try
5831 * Use an atomic op to access interlock_count to ensure ordering.
5833 icount = atomic_fetchadd_long(&m->md.interlock_count,
5834 0x8000000000000000LU) +
5835 0x8000000000000000LU;
5837 while (icount & 0x3FFFFFFFFFFFFFFFLU) {
5838 tsleep_interlock(&m->md.interlock_count, 0);
5839 if (atomic_fcmpset_long(&m->md.interlock_count, &icount,
5840 icount | 0x4000000000000000LU)) {
5841 tsleep(&m->md.interlock_count, PINTERLOCKED,
5843 icount = m->md.interlock_count;
5844 if (retry - ticks > 0)
5846 panic("pmap_clearbit: cannot return interlock_count "
5848 m, m->md.interlock_count);
5851 vm_page_flag_clear(m, PG_WRITEABLE);
5855 * Lower the permission for all mappings to a given page.
5857 * Page must be hard-busied by caller. Because the page is busied by the
5858 * caller, this should not be able to race a pmap_enter().
5861 pmap_page_protect(vm_page_t m, vm_prot_t prot)
5863 /* JG NX support? */
5864 if ((prot & VM_PROT_WRITE) == 0) {
5865 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
5867 * NOTE: pmap_clearbit(.. PG_RW) also clears
5868 * the PG_WRITEABLE flag in (m).
5870 pmap_clearbit(m, PG_RW_IDX);
5878 pmap_phys_address(vm_pindex_t ppn)
5880 return (x86_64_ptob(ppn));
5884 * Return a count of reference bits for a page, clearing those bits.
5885 * It is not necessary for every reference bit to be cleared, but it
5886 * is necessary that 0 only be returned when there are truly no
5887 * reference bits set.
5889 * XXX: The exact number of bits to check and clear is a matter that
5890 * should be tested and standardized at some point in the future for
5891 * optimal aging of shared pages.
5893 * This routine may not block.
5896 pmap_ts_referenced(vm_page_t m)
5901 if (__predict_false(!pmap_initialized || (m->flags & PG_FICTITIOUS)))
5903 PMAP_PAGE_BACKING_SCAN(m, NULL, ipmap, iptep, ipte, iva) {
5904 if (ipte & ipmap->pmap_bits[PG_A_IDX]) {
5905 npte = ipte & ~ipmap->pmap_bits[PG_A_IDX];
5906 if (!atomic_cmpset_long(iptep, ipte, npte))
5907 PMAP_PAGE_BACKING_RETRY;
5912 } PMAP_PAGE_BACKING_DONE;
5919 * Return whether or not the specified physical page was modified
5920 * in any physical maps.
5923 pmap_is_modified(vm_page_t m)
5927 res = pmap_testbit(m, PG_M_IDX);
5932 * Clear the modify bit on the vm_page.
5934 * The page must be hard-busied.
5937 pmap_clear_modify(vm_page_t m)
5939 pmap_clearbit(m, PG_M_IDX);
5943 * pmap_clear_reference:
5945 * Clear the reference bit on the specified physical page.
5948 pmap_clear_reference(vm_page_t m)
5950 pmap_clearbit(m, PG_A_IDX);
5954 * Miscellaneous support routines follow
5959 x86_64_protection_init(void)
5965 * NX supported? (boot time loader.conf override only)
5967 * -1 Automatic (sets mode 1)
5969 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
5970 * 2 NX implemented for all cases
5972 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
5973 if ((amd_feature & AMDID_NX) == 0) {
5974 pmap_bits_default[PG_NX_IDX] = 0;
5976 } else if (pmap_nx_enable < 0) {
5977 pmap_nx_enable = 1; /* default to mode 1 (READ) */
5981 * 0 is basically read-only access, but also set the NX (no-execute)
5982 * bit when VM_PROT_EXECUTE is not specified.
5984 kp = protection_codes;
5985 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
5987 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
5989 * This case handled elsewhere
5993 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
5995 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
5997 if (pmap_nx_enable >= 1)
5998 *kp = pmap_bits_default[PG_NX_IDX];
6000 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6001 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6003 * Execute requires read access
6007 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6008 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6010 * Write without execute is RW|NX
6011 * (pmap_nx_enable mode >= 2)
6013 *kp = pmap_bits_default[PG_RW_IDX];
6014 if (pmap_nx_enable >= 2)
6015 *kp |= pmap_bits_default[PG_NX_IDX];
6017 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6018 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6020 * Write with execute is RW
6022 *kp = pmap_bits_default[PG_RW_IDX];
6030 * Map a set of physical memory pages into the kernel virtual
6031 * address space. Return a pointer to where it is mapped. This
6032 * routine is intended to be used for mapping device memory,
6035 * NOTE: We can't use pgeflag unless we invalidate the pages one at
6038 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6039 * work whether the cpu supports PAT or not. The remaining PAT
6040 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6044 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6046 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6050 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6052 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6056 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6058 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6062 * Map a set of physical memory pages into the kernel virtual
6063 * address space. Return a pointer to where it is mapped. This
6064 * routine is intended to be used for mapping device memory,
6068 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6070 vm_offset_t va, tmpva, offset;
6074 offset = pa & PAGE_MASK;
6075 size = roundup(offset + size, PAGE_SIZE);
6077 va = kmem_alloc_nofault(kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6079 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6081 pa = pa & ~PAGE_MASK;
6082 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6083 pte = vtopte(tmpva);
6085 kernel_pmap->pmap_bits[PG_RW_IDX] |
6086 kernel_pmap->pmap_bits[PG_V_IDX] | /* pgeflag | */
6087 kernel_pmap->pmap_cache_bits_pte[mode];
6088 tmpsize -= PAGE_SIZE;
6092 pmap_invalidate_range(kernel_pmap, va, va + size);
6093 pmap_invalidate_cache_range(va, va + size);
6095 return ((void *)(va + offset));
6099 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6101 vm_offset_t base, offset;
6103 base = va & ~PAGE_MASK;
6104 offset = va & PAGE_MASK;
6105 size = roundup(offset + size, PAGE_SIZE);
6106 pmap_qremove(va, size >> PAGE_SHIFT);
6107 kmem_free(kernel_map, base, size);
6111 * Sets the memory attribute for the specified page.
6114 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6120 * If "m" is a normal page, update its direct mapping. This update
6121 * can be relied upon to perform any cache operations that are
6122 * required for data coherence.
6124 if ((m->flags & PG_FICTITIOUS) == 0)
6125 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6129 * Change the PAT attribute on an existing kernel memory map. Caller
6130 * must ensure that the virtual memory in question is not accessed
6131 * during the adjustment.
6133 * If the va is within the DMAP we cannot use vtopte() because the DMAP
6134 * utilizes 2MB or 1GB pages. 2MB is forced atm so calculate the pd_entry
6135 * pointer based on that.
6138 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6145 panic("pmap_change_attr: va is NULL");
6146 base = trunc_page(va);
6148 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
6151 KKASSERT(va < DMapMaxAddress);
6152 pd = (pd_entry_t *)PHYS_TO_DMAP(DMPDphys);
6153 pd += (va - DMAP_MIN_ADDRESS) >> PDRSHIFT;
6155 while ((long)count > 0) {
6157 (*pd & ~(pd_entry_t)(kernel_pmap->pmap_cache_mask_pde)) |
6158 kernel_pmap->pmap_cache_bits_pde[mode];
6159 count -= NBPDR / PAGE_SIZE;
6167 (*pte & ~(pt_entry_t)(kernel_pmap->pmap_cache_mask_pte)) |
6168 kernel_pmap->pmap_cache_bits_pte[mode];
6174 changed = 1; /* XXX: not optimal */
6177 * Flush CPU caches if required to make sure any data isn't cached that
6178 * shouldn't be, etc.
6181 pmap_invalidate_range(kernel_pmap, base, va);
6182 pmap_invalidate_cache_range(base, va);
6187 * perform the pmap work for mincore
6190 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6192 pt_entry_t *ptep, pte;
6196 ptep = pmap_pte(pmap, addr);
6198 if (ptep && (pte = *ptep) != 0) {
6201 val = MINCORE_INCORE;
6202 pa = pte & PG_FRAME;
6203 if (pte & pmap->pmap_bits[PG_MANAGED_IDX])
6204 m = PHYS_TO_VM_PAGE(pa);
6211 if (pte & pmap->pmap_bits[PG_M_IDX])
6212 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6215 * Modified by someone
6217 else if (m && (m->dirty || pmap_is_modified(m)))
6218 val |= MINCORE_MODIFIED_OTHER;
6221 * Referenced by us, or someone else.
6223 if (pte & pmap->pmap_bits[PG_A_IDX]) {
6224 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6225 } else if (m && ((m->flags & PG_REFERENCED) ||
6226 pmap_ts_referenced(m))) {
6227 val |= MINCORE_REFERENCED_OTHER;
6228 vm_page_flag_set(m, PG_REFERENCED);
6235 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
6236 * vmspace will be ref'd and the old one will be deref'd.
6238 * The vmspace for all lwps associated with the process will be adjusted
6239 * and cr3 will be reloaded if any lwp is the current lwp.
6241 * The process must hold the vmspace->vm_map.token for oldvm and newvm
6244 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6246 struct vmspace *oldvm;
6249 oldvm = p->p_vmspace;
6250 if (oldvm != newvm) {
6253 p->p_vmspace = newvm;
6254 KKASSERT(p->p_nthreads == 1);
6255 lp = RB_ROOT(&p->p_lwp_tree);
6256 pmap_setlwpvm(lp, newvm);
6263 * Set the vmspace for a LWP. The vmspace is almost universally set the
6264 * same as the process vmspace, but virtual kernels need to swap out contexts
6265 * on a per-lwp basis.
6267 * Caller does not necessarily hold any vmspace tokens. Caller must control
6268 * the lwp (typically be in the context of the lwp). We use a critical
6269 * section to protect against statclock and hardclock (statistics collection).
6272 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6274 struct vmspace *oldvm;
6278 oldvm = lp->lwp_vmspace;
6280 if (oldvm != newvm) {
6283 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6284 lp->lwp_vmspace = newvm;
6285 if (td->td_lwp == lp) {
6286 pmap = vmspace_pmap(newvm);
6287 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6288 if (pmap->pm_active_lock & CPULOCK_EXCL)
6289 pmap_interlock_wait(newvm);
6290 #if defined(SWTCH_OPTIM_STATS)
6293 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6294 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6295 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6296 td->td_pcb->pcb_cr3_iso =
6297 vtophys(pmap->pm_pml4_iso);
6298 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6300 td->td_pcb->pcb_cr3_iso = 0;
6301 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6303 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6304 td->td_pcb->pcb_cr3 = KPML4phys;
6305 td->td_pcb->pcb_cr3_iso = 0;
6306 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6308 panic("pmap_setlwpvm: unknown pmap type\n");
6312 * The MMU separation fields needs to be updated.
6313 * (it can't access the pcb directly from the
6314 * restricted user pmap).
6317 struct trampframe *tramp;
6319 tramp = &pscpu->trampoline;
6320 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6321 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6322 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6323 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6324 /* tr_pcb_rsp doesn't change */
6328 * In kernel-land we always use the normal PML4E
6329 * so the kernel is fully mapped and can also access
6332 load_cr3(td->td_pcb->pcb_cr3);
6333 pmap = vmspace_pmap(oldvm);
6334 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6342 * Used to control the backing vmspace on the host for a guest VM.
6343 * The cpumask is needed by the host pager to properly invalidate the
6344 * host TLB when paging out the backing memory of a guest VM.
6346 * NOTE: The scheduler might somtimes overload multiple vCPUs on the
6347 * same physical cpu, so operating is not quite as simple as
6348 * calling add_cpu/del_cpu in the core vmrun routines.
6351 pmap_add_cpu(struct vmspace *vm, int cpuid)
6353 ATOMIC_CPUMASK_ORBIT(vm->vm_pmap.pm_active, mycpu->gd_cpuid);
6355 pmap_interlock_wait(vm);
6360 pmap_del_cpu(struct vmspace *vm, int cpuid)
6362 ATOMIC_CPUMASK_NANDBIT(vm->vm_pmap.pm_active, mycpu->gd_cpuid);
6366 pmap_del_all_cpus(struct vmspace *vm)
6368 CPUMASK_ASSZERO(vm->vm_pmap.pm_active);
6372 * Called when switching to a locked pmap, used to interlock against pmaps
6373 * undergoing modifications to prevent us from activating the MMU for the
6374 * target pmap until all such modifications have completed. We have to do
6375 * this because the thread making the modifications has already set up its
6376 * SMP synchronization mask.
6378 * This function cannot sleep!
6383 pmap_interlock_wait(struct vmspace *vm)
6385 struct pmap *pmap = &vm->vm_pmap;
6387 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6389 KKASSERT(curthread->td_critcount >= 2);
6390 DEBUG_PUSH_INFO("pmap_interlock_wait");
6391 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6393 lwkt_process_ipiq();
6401 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6404 if ((obj == NULL) || (size < NBPDR) ||
6405 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6409 addr = roundup2(addr, NBPDR);
6414 * Used by kmalloc/kfree, page already exists at va
6417 pmap_kvtom(vm_offset_t va)
6419 pt_entry_t *ptep = vtopte(va);
6421 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6425 * Initialize machine-specific shared page directory support. This
6426 * is executed when a VM object is created.
6429 pmap_object_init(vm_object_t object)
6434 * Clean up machine-specific shared page directory support. This
6435 * is executed when a VM object is destroyed.
6438 pmap_object_free(vm_object_t object)
6443 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6444 * VM page and issue a pginfo->callback.
6448 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6449 vm_pindex_t *pte_placemark,
6450 pv_entry_t pt_pv, vm_offset_t va,
6451 pt_entry_t *ptep, void *arg)
6453 struct pmap_pgscan_info *pginfo = arg;
6460 if (pte & pmap->pmap_bits[PG_MANAGED_IDX]) {
6462 * Try to busy the page while we hold the pte_placemark locked.
6464 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6465 if (vm_page_busy_try(m, TRUE) == 0) {
6466 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6468 * The callback is issued with the pt_pv
6471 pv_placemarker_wakeup(pmap, pte_placemark);
6473 vm_page_wire_quick(pt_pv->pv_m);
6476 if (pginfo->callback(pginfo, va, m) < 0)
6480 if (vm_page_unwire_quick(pt_pv->pv_m)) {
6481 panic("pmap_pgscan: bad wire_"
6487 pv_placemarker_wakeup(pmap, pte_placemark);
6490 ++pginfo->busycount;
6491 pv_placemarker_wakeup(pmap, pte_placemark);
6495 * Shared page table or unmanaged page (sharept or !sharept)
6497 pv_placemarker_wakeup(pmap, pte_placemark);
6502 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6504 struct pmap_scan_info info;
6506 pginfo->offset = pginfo->beg_addr;
6507 info.pmap = pginfo->pmap;
6508 info.sva = pginfo->beg_addr;
6509 info.eva = pginfo->end_addr;
6510 info.func = pmap_pgscan_callback;
6512 pmap_scan(&info, 0);
6514 pginfo->offset = pginfo->end_addr;
6518 * Wait for a placemarker that we do not own to clear. The placemarker
6519 * in question is not necessarily set to the pindex we want, we may have
6520 * to wait on the element because we want to reserve it ourselves.
6522 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6523 * PM_NOPLACEMARK, so it does not interfere with placemarks
6524 * which have already been woken up.
6526 * NOTE: This routine is called without the pmap spin-lock and so can
6527 * race changes to *pmark. Due to the sensitivity of the routine
6528 * to possible MULTIPLE interactions from other cpus, and the
6529 * overloading of the WAKEUP bit on PM_NOPLACEMARK, we have to
6530 * use a cmpset loop to avoid a race that might cause the WAKEUP
6533 * Caller is expected to retry its operation upon return.
6537 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6543 while (mark != PM_NOPLACEMARK) {
6544 tsleep_interlock(pmark, 0);
6545 if (atomic_fcmpset_long(pmark, &mark,
6546 mark | PM_PLACEMARK_WAKEUP)) {
6547 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6554 * Wakeup a placemarker that we own. Replace the entry with
6555 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6559 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6563 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6564 KKASSERT(pindex != PM_NOPLACEMARK);
6565 if (pindex & PM_PLACEMARK_WAKEUP)