kernel - Implement support for SMAP and SMEP security (2)
[dragonfly.git] / sys / platform / pc64 / x86_64 / pmap.c
blobcd6f803c24259112fd7b3aa8a4faa14e1ab3cc74
1 /*
2 * Copyright (c) 1991 Regents of the University of California.
3 * Copyright (c) 1994 John S. Dyson
4 * Copyright (c) 1994 David Greenman
5 * Copyright (c) 2003 Peter Wemm
6 * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
7 * Copyright (c) 2008, 2009 The DragonFly Project.
8 * Copyright (c) 2008, 2009 Jordan Gordeev.
9 * Copyright (c) 2011-2017 Matthew Dillon
10 * All rights reserved.
12 * This code is derived from software contributed to Berkeley by
13 * the Systems Programming Group of the University of Utah Computer
14 * Science Department and William Jolitz of UUNET Technologies Inc.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
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
42 * SUCH DAMAGE.
45 * Manage physical address maps for x86-64 systems.
47 * Some notes:
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.
55 #if 0 /* JG */
56 #include "opt_pmap.h"
57 #endif
58 #include "opt_msgbuf.h"
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #include <sys/proc.h>
63 #include <sys/msgbuf.h>
64 #include <sys/vmmeter.h>
65 #include <sys/mman.h>
66 #include <sys/systm.h>
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <sys/sysctl.h>
71 #include <sys/lock.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/user.h>
82 #include <sys/thread2.h>
83 #include <sys/spinlock2.h>
84 #include <vm/vm_page2.h>
86 #include <machine/cputypes.h>
87 #include <machine/cpu.h>
88 #include <machine/md_var.h>
89 #include <machine/specialreg.h>
90 #include <machine/smp.h>
91 #include <machine_base/apic/apicreg.h>
92 #include <machine/globaldata.h>
93 #include <machine/pmap.h>
94 #include <machine/pmap_inval.h>
95 #include <machine/inttypes.h>
97 #include <ddb/ddb.h>
99 #define PMAP_KEEP_PDIRS
100 #ifndef PMAP_SHPGPERPROC
101 #define PMAP_SHPGPERPROC 2000
102 #endif
104 #if defined(DIAGNOSTIC)
105 #define PMAP_DIAGNOSTIC
106 #endif
108 #define MINPV 2048
111 * pmap debugging will report who owns a pv lock when blocking.
113 #ifdef PMAP_DEBUG
115 #define PMAP_DEBUG_DECL ,const char *func, int lineno
116 #define PMAP_DEBUG_ARGS , __func__, __LINE__
117 #define PMAP_DEBUG_COPY , func, lineno
119 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp \
120 PMAP_DEBUG_ARGS)
121 #define pv_lock(pv) _pv_lock(pv \
122 PMAP_DEBUG_ARGS)
123 #define pv_hold_try(pv) _pv_hold_try(pv \
124 PMAP_DEBUG_ARGS)
125 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp \
126 PMAP_DEBUG_ARGS)
128 #define pv_free(pv, pvp) _pv_free(pv, pvp PMAP_DEBUG_ARGS)
130 #else
132 #define PMAP_DEBUG_DECL
133 #define PMAP_DEBUG_ARGS
134 #define PMAP_DEBUG_COPY
136 #define pv_get(pmap, pindex, pmarkp) _pv_get(pmap, pindex, pmarkp)
137 #define pv_lock(pv) _pv_lock(pv)
138 #define pv_hold_try(pv) _pv_hold_try(pv)
139 #define pv_alloc(pmap, pindex, isnewp) _pv_alloc(pmap, pindex, isnewp)
140 #define pv_free(pv, pvp) _pv_free(pv, pvp)
142 #endif
145 * Get PDEs and PTEs for user/kernel address space
147 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
149 #define pmap_pde_v(pmap, pte) ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
150 #define pmap_pte_w(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
151 #define pmap_pte_m(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
152 #define pmap_pte_u(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
153 #define pmap_pte_v(pmap, pte) ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
156 * Given a map and a machine independent protection code,
157 * convert to a vax protection code.
159 #define pte_prot(m, p) \
160 (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
161 static uint64_t protection_codes[PROTECTION_CODES_SIZE];
163 struct pmap kernel_pmap;
164 struct pmap iso_pmap;
166 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
168 vm_paddr_t avail_start; /* PA of first available physical page */
169 vm_paddr_t avail_end; /* PA of last available physical page */
170 vm_offset_t virtual2_start; /* cutout free area prior to kernel start */
171 vm_offset_t virtual2_end;
172 vm_offset_t virtual_start; /* VA of first avail page (after kernel bss) */
173 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
174 vm_offset_t KvaStart; /* VA start of KVA space */
175 vm_offset_t KvaEnd; /* VA end of KVA space (non-inclusive) */
176 vm_offset_t KvaSize; /* max size of kernel virtual address space */
177 static boolean_t pmap_initialized = FALSE; /* Has pmap_init completed? */
178 //static int pgeflag; /* PG_G or-in */
179 uint64_t PatMsr;
181 static int ndmpdp;
182 static vm_paddr_t dmaplimit;
183 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
185 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE]; /* PAT -> PG_ bits */
186 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/ /* PAT -> PG_ bits */
188 static uint64_t KPTbase;
189 static uint64_t KPTphys;
190 static uint64_t KPDphys; /* phys addr of kernel level 2 */
191 static uint64_t KPDbase; /* phys addr of kernel level 2 @ KERNBASE */
192 uint64_t KPDPphys; /* phys addr of kernel level 3 */
193 uint64_t KPML4phys; /* phys addr of kernel level 4 */
195 static uint64_t DMPDphys; /* phys addr of direct mapped level 2 */
196 static uint64_t DMPDPphys; /* phys addr of direct mapped level 3 */
199 * Data for the pv entry allocation mechanism
201 static vm_zone_t pvzone;
202 static struct vm_zone pvzone_store;
203 static vm_pindex_t pv_entry_max=0, pv_entry_high_water=0;
204 static int pmap_pagedaemon_waken = 0;
205 static struct pv_entry *pvinit;
208 * All those kernel PT submaps that BSD is so fond of
210 pt_entry_t *CMAP1 = NULL, *ptmmap;
211 caddr_t CADDR1 = NULL, ptvmmap = NULL;
212 static pt_entry_t *msgbufmap;
213 struct msgbuf *msgbufp=NULL;
216 * PMAP default PG_* bits. Needed to be able to add
217 * EPT/NPT pagetable pmap_bits for the VMM module
219 uint64_t pmap_bits_default[] = {
220 REGULAR_PMAP, /* TYPE_IDX 0 */
221 X86_PG_V, /* PG_V_IDX 1 */
222 X86_PG_RW, /* PG_RW_IDX 2 */
223 X86_PG_U, /* PG_U_IDX 3 */
224 X86_PG_A, /* PG_A_IDX 4 */
225 X86_PG_M, /* PG_M_IDX 5 */
226 X86_PG_PS, /* PG_PS_IDX3 6 */
227 X86_PG_G, /* PG_G_IDX 7 */
228 X86_PG_AVAIL1, /* PG_AVAIL1_IDX 8 */
229 X86_PG_AVAIL2, /* PG_AVAIL2_IDX 9 */
230 X86_PG_AVAIL3, /* PG_AVAIL3_IDX 10 */
231 X86_PG_NC_PWT | X86_PG_NC_PCD, /* PG_N_IDX 11 */
232 X86_PG_NX, /* PG_NX_IDX 12 */
235 * Crashdump maps.
237 static pt_entry_t *pt_crashdumpmap;
238 static caddr_t crashdumpmap;
240 static int pmap_debug = 0;
241 SYSCTL_INT(_machdep, OID_AUTO, pmap_debug, CTLFLAG_RW,
242 &pmap_debug, 0, "Debug pmap's");
243 #ifdef PMAP_DEBUG2
244 static int pmap_enter_debug = 0;
245 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
246 &pmap_enter_debug, 0, "Debug pmap_enter's");
247 #endif
248 static int pmap_yield_count = 64;
249 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
250 &pmap_yield_count, 0, "Yield during init_pt/release");
251 static int pmap_mmu_optimize = 0;
252 SYSCTL_INT(_machdep, OID_AUTO, pmap_mmu_optimize, CTLFLAG_RW,
253 &pmap_mmu_optimize, 0, "Share page table pages when possible");
254 int pmap_fast_kernel_cpusync = 0;
255 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
256 &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
257 int pmap_dynamic_delete = 0;
258 SYSCTL_INT(_machdep, OID_AUTO, pmap_dynamic_delete, CTLFLAG_RW,
259 &pmap_dynamic_delete, 0, "Dynamically delete PT/PD/PDPs");
260 int pmap_lock_delay = 100;
261 SYSCTL_INT(_machdep, OID_AUTO, pmap_lock_delay, CTLFLAG_RW,
262 &pmap_lock_delay, 0, "Spin loops");
263 static int meltdown_mitigation = -1;
264 TUNABLE_INT("machdep.meltdown_mitigation", &meltdown_mitigation);
265 SYSCTL_INT(_machdep, OID_AUTO, meltdown_mitigation, CTLFLAG_RW,
266 &meltdown_mitigation, 0, "Userland pmap isolation");
268 static int pmap_nx_enable = -1; /* -1 = auto */
269 /* needs manual TUNABLE in early probe, see below */
270 SYSCTL_INT(_machdep, OID_AUTO, pmap_nx_enable, CTLFLAG_RD,
271 &pmap_nx_enable, 0,
272 "no-execute support (0=disabled, 1=w/READ, 2=w/READ & WRITE)");
274 static int pmap_pv_debug = 50;
275 SYSCTL_INT(_machdep, OID_AUTO, pmap_pv_debug, CTLFLAG_RW,
276 &pmap_pv_debug, 0, "");
278 /* Standard user access funtions */
279 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
280 size_t *lencopied);
281 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
282 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
283 extern int std_fubyte (const uint8_t *base);
284 extern int std_subyte (uint8_t *base, uint8_t byte);
285 extern int32_t std_fuword32 (const uint32_t *base);
286 extern int64_t std_fuword64 (const uint64_t *base);
287 extern int std_suword64 (uint64_t *base, uint64_t word);
288 extern int std_suword32 (uint32_t *base, int word);
289 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
290 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
291 extern uint32_t std_fuwordadd32 (volatile uint32_t *base, uint32_t v);
292 extern uint64_t std_fuwordadd64 (volatile uint64_t *base, uint64_t v);
294 static void pv_hold(pv_entry_t pv);
295 static int _pv_hold_try(pv_entry_t pv
296 PMAP_DEBUG_DECL);
297 static void pv_drop(pv_entry_t pv);
298 static void _pv_lock(pv_entry_t pv
299 PMAP_DEBUG_DECL);
300 static void pv_unlock(pv_entry_t pv);
301 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
302 PMAP_DEBUG_DECL);
303 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
304 PMAP_DEBUG_DECL);
305 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
306 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
307 vm_pindex_t **pmarkp, int *errorp);
308 static void pv_put(pv_entry_t pv);
309 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
310 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
311 pv_entry_t *pvpp);
312 static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
313 pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
314 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
315 pmap_inval_bulk_t *bulk, int destroy);
316 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
317 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
318 pmap_inval_bulk_t *bulk);
320 struct pmap_scan_info;
321 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
322 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
323 pv_entry_t pt_pv, int sharept,
324 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
325 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
326 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
327 pv_entry_t pt_pv, int sharept,
328 vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
330 static void x86_64_protection_init (void);
331 static void create_pagetables(vm_paddr_t *firstaddr);
332 static void pmap_remove_all (vm_page_t m);
333 static boolean_t pmap_testbit (vm_page_t m, int bit);
335 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
336 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
338 static void pmap_pinit_defaults(struct pmap *pmap);
339 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
340 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
342 static int
343 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
345 if (pv1->pv_pindex < pv2->pv_pindex)
346 return(-1);
347 if (pv1->pv_pindex > pv2->pv_pindex)
348 return(1);
349 return(0);
352 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
353 pv_entry_compare, vm_pindex_t, pv_pindex);
355 static __inline
356 void
357 pmap_page_stats_adding(vm_page_t m)
359 globaldata_t gd = mycpu;
361 if (TAILQ_EMPTY(&m->md.pv_list)) {
362 ++gd->gd_vmtotal.t_arm;
363 } else if (TAILQ_FIRST(&m->md.pv_list) ==
364 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
365 ++gd->gd_vmtotal.t_armshr;
366 ++gd->gd_vmtotal.t_avmshr;
367 } else {
368 ++gd->gd_vmtotal.t_avmshr;
372 static __inline
373 void
374 pmap_page_stats_deleting(vm_page_t m)
376 globaldata_t gd = mycpu;
378 if (TAILQ_EMPTY(&m->md.pv_list)) {
379 --gd->gd_vmtotal.t_arm;
380 } else if (TAILQ_FIRST(&m->md.pv_list) ==
381 TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
382 --gd->gd_vmtotal.t_armshr;
383 --gd->gd_vmtotal.t_avmshr;
384 } else {
385 --gd->gd_vmtotal.t_avmshr;
390 * This is an ineligent crowbar to prevent heavily threaded programs
391 * from creating long live-locks in the pmap code when pmap_mmu_optimize
392 * is enabled. Without it a pmap-local page table page can wind up being
393 * constantly created and destroyed (without injury, but also without
394 * progress) as the optimization tries to switch to the object's shared page
395 * table page.
397 static __inline void
398 pmap_softwait(pmap_t pmap)
400 while (pmap->pm_softhold) {
401 tsleep_interlock(&pmap->pm_softhold, 0);
402 if (pmap->pm_softhold)
403 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
407 static __inline void
408 pmap_softhold(pmap_t pmap)
410 while (atomic_swap_int(&pmap->pm_softhold, 1) == 1) {
411 tsleep_interlock(&pmap->pm_softhold, 0);
412 if (atomic_swap_int(&pmap->pm_softhold, 1) == 1)
413 tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
417 static __inline void
418 pmap_softdone(pmap_t pmap)
420 atomic_swap_int(&pmap->pm_softhold, 0);
421 wakeup(&pmap->pm_softhold);
425 * Move the kernel virtual free pointer to the next
426 * 2MB. This is used to help improve performance
427 * by using a large (2MB) page for much of the kernel
428 * (.text, .data, .bss)
430 static
431 vm_offset_t
432 pmap_kmem_choose(vm_offset_t addr)
434 vm_offset_t newaddr = addr;
436 newaddr = roundup2(addr, NBPDR);
437 return newaddr;
441 * Returns the pindex of a page table entry (representing a terminal page).
442 * There are NUPTE_TOTAL page table entries possible (a huge number)
444 * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
445 * We want to properly translate negative KVAs.
447 static __inline
448 vm_pindex_t
449 pmap_pte_pindex(vm_offset_t va)
451 return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
455 * Returns the pindex of a page table.
457 static __inline
458 vm_pindex_t
459 pmap_pt_pindex(vm_offset_t va)
461 return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
465 * Returns the pindex of a page directory.
467 static __inline
468 vm_pindex_t
469 pmap_pd_pindex(vm_offset_t va)
471 return (NUPTE_TOTAL + NUPT_TOTAL +
472 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
475 static __inline
476 vm_pindex_t
477 pmap_pdp_pindex(vm_offset_t va)
479 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
480 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
483 static __inline
484 vm_pindex_t
485 pmap_pml4_pindex(void)
487 return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
491 * Return various clipped indexes for a given VA
493 * Returns the index of a pt in a page directory, representing a page
494 * table.
496 static __inline
497 vm_pindex_t
498 pmap_pt_index(vm_offset_t va)
500 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
504 * Returns the index of a pd in a page directory page, representing a page
505 * directory.
507 static __inline
508 vm_pindex_t
509 pmap_pd_index(vm_offset_t va)
511 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
515 * Returns the index of a pdp in the pml4 table, representing a page
516 * directory page.
518 static __inline
519 vm_pindex_t
520 pmap_pdp_index(vm_offset_t va)
522 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
526 * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
527 * the PT layer. This will speed up core pmap operations considerably.
528 * We also cache the PTE layer to (hopefully) improve relative lookup
529 * speeds.
531 * NOTE: The pmap spinlock does not need to be held but the passed-in pv
532 * must be in a known associated state (typically by being locked when
533 * the pmap spinlock isn't held). We allow the race for that case.
535 * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
536 * cpu_ccfence() to prevent compiler optimizations from reloading the
537 * field.
539 static __inline
540 void
541 pv_cache(pmap_t pmap, pv_entry_t pv, vm_pindex_t pindex)
543 if (pindex < pmap_pt_pindex(0)) {
544 pmap->pm_pvhint_pte = pv;
545 } else if (pindex < pmap_pd_pindex(0)) {
546 pmap->pm_pvhint_pt = pv;
551 * Locate the requested pt_entry
553 static __inline
554 pv_entry_t
555 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
557 pv_entry_t pv;
559 #if 1
560 if (pindex < pmap_pt_pindex(0))
561 pv = pmap->pm_pvhint_pte;
562 else if (pindex < pmap_pd_pindex(0))
563 pv = pmap->pm_pvhint_pt;
564 else
565 pv = NULL;
566 cpu_ccfence();
567 if (pv == NULL || pv->pv_pmap != pmap) {
568 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
569 if (pv)
570 pv_cache(pmap, pv, pindex);
571 } else if (pv->pv_pindex != pindex) {
572 pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
573 pindex, pv);
574 if (pv)
575 pv_cache(pmap, pv, pindex);
577 #else
578 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
579 #endif
580 return pv;
584 * pmap_pte_quick:
586 * Super fast pmap_pte routine best used when scanning the pv lists.
587 * This eliminates many course-grained invltlb calls. Note that many of
588 * the pv list scans are across different pmaps and it is very wasteful
589 * to do an entire invltlb when checking a single mapping.
591 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
593 static
594 pt_entry_t *
595 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
597 return pmap_pte(pmap, va);
601 * The placemarker hash must be broken up into four zones so lock
602 * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
604 * Placemarkers are used to 'lock' page table indices that do not have
605 * a pv_entry. This allows the pmap to support managed and unmanaged
606 * pages and shared page tables.
608 #define PM_PLACE_BASE (PM_PLACEMARKS >> 2)
610 static __inline
611 vm_pindex_t *
612 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
614 int hi;
616 if (pindex < pmap_pt_pindex(0)) /* zone 0 - PTE */
617 hi = 0;
618 else if (pindex < pmap_pd_pindex(0)) /* zone 1 - PT */
619 hi = PM_PLACE_BASE;
620 else if (pindex < pmap_pdp_pindex(0)) /* zone 2 - PD */
621 hi = PM_PLACE_BASE << 1;
622 else /* zone 3 - PDP (and PML4E) */
623 hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
624 hi += pindex & (PM_PLACE_BASE - 1);
626 return (&pmap->pm_placemarks[hi]);
631 * Generic procedure to index a pte from a pt, pd, or pdp.
633 * NOTE: Normally passed pindex as pmap_xx_index(). pmap_xx_pindex() is NOT
634 * a page table page index but is instead of PV lookup index.
636 static
637 void *
638 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
640 pt_entry_t *pte;
642 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
643 return(&pte[pindex]);
647 * Return pointer to PDP slot in the PML4
649 static __inline
650 pml4_entry_t *
651 pmap_pdp(pmap_t pmap, vm_offset_t va)
653 return (&pmap->pm_pml4[pmap_pdp_index(va)]);
657 * Return pointer to PD slot in the PDP given a pointer to the PDP
659 static __inline
660 pdp_entry_t *
661 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
663 pdp_entry_t *pd;
665 pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
666 return (&pd[pmap_pd_index(va)]);
670 * Return pointer to PD slot in the PDP.
672 static __inline
673 pdp_entry_t *
674 pmap_pd(pmap_t pmap, vm_offset_t va)
676 pml4_entry_t *pdp;
678 pdp = pmap_pdp(pmap, va);
679 if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
680 return NULL;
681 return (pmap_pdp_to_pd(*pdp, va));
685 * Return pointer to PT slot in the PD given a pointer to the PD
687 static __inline
688 pd_entry_t *
689 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
691 pd_entry_t *pt;
693 pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
694 return (&pt[pmap_pt_index(va)]);
698 * Return pointer to PT slot in the PD
700 * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
701 * so we cannot lookup the PD via the PDP. Instead we
702 * must look it up via the pmap.
704 static __inline
705 pd_entry_t *
706 pmap_pt(pmap_t pmap, vm_offset_t va)
708 pdp_entry_t *pd;
709 pv_entry_t pv;
710 vm_pindex_t pd_pindex;
711 vm_paddr_t phys;
713 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
714 pd_pindex = pmap_pd_pindex(va);
715 spin_lock_shared(&pmap->pm_spin);
716 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
717 if (pv == NULL || pv->pv_m == NULL) {
718 spin_unlock_shared(&pmap->pm_spin);
719 return NULL;
721 phys = VM_PAGE_TO_PHYS(pv->pv_m);
722 spin_unlock_shared(&pmap->pm_spin);
723 return (pmap_pd_to_pt(phys, va));
724 } else {
725 pd = pmap_pd(pmap, va);
726 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
727 return NULL;
728 return (pmap_pd_to_pt(*pd, va));
733 * Return pointer to PTE slot in the PT given a pointer to the PT
735 static __inline
736 pt_entry_t *
737 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
739 pt_entry_t *pte;
741 pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
742 return (&pte[pmap_pte_index(va)]);
746 * Return pointer to PTE slot in the PT
748 static __inline
749 pt_entry_t *
750 pmap_pte(pmap_t pmap, vm_offset_t va)
752 pd_entry_t *pt;
754 pt = pmap_pt(pmap, va);
755 if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
756 return NULL;
757 if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
758 return ((pt_entry_t *)pt);
759 return (pmap_pt_to_pte(*pt, va));
763 * Return address of PT slot in PD (KVM only)
765 * Cannot be used for user page tables because it might interfere with
766 * the shared page-table-page optimization (pmap_mmu_optimize).
768 static __inline
769 pd_entry_t *
770 vtopt(vm_offset_t va)
772 uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
773 NPML4EPGSHIFT)) - 1);
775 return (PDmap + ((va >> PDRSHIFT) & mask));
779 * KVM - return address of PTE slot in PT
781 static __inline
782 pt_entry_t *
783 vtopte(vm_offset_t va)
785 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
786 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
788 return (PTmap + ((va >> PAGE_SHIFT) & mask));
792 * Returns the physical address translation from va for a user address.
793 * (vm_paddr_t)-1 is returned on failure.
795 vm_paddr_t
796 uservtophys(vm_offset_t va)
798 uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
799 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
800 vm_paddr_t pa;
801 pt_entry_t pte;
802 pmap_t pmap;
804 pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
805 pa = (vm_paddr_t)-1;
806 if (va < VM_MAX_USER_ADDRESS) {
807 pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
808 if (pte & pmap->pmap_bits[PG_V_IDX])
809 pa = (pte & PG_FRAME) | (va & PAGE_MASK);
811 return pa;
814 static uint64_t
815 allocpages(vm_paddr_t *firstaddr, long n)
817 uint64_t ret;
819 ret = *firstaddr;
820 bzero((void *)ret, n * PAGE_SIZE);
821 *firstaddr += n * PAGE_SIZE;
822 return (ret);
825 static
826 void
827 create_pagetables(vm_paddr_t *firstaddr)
829 long i; /* must be 64 bits */
830 long nkpt_base;
831 long nkpt_phys;
832 long nkpd_phys;
833 int j;
836 * We are running (mostly) V=P at this point
838 * Calculate how many 1GB PD entries in our PDP pages are needed
839 * for the DMAP. This is only allocated if the system does not
840 * support 1GB pages. Otherwise ndmpdp is simply a count of
841 * the number of 1G terminal entries in our PDP pages are needed.
843 * NOTE: Maxmem is in pages
845 ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
846 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
847 ndmpdp = 4;
848 KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
851 * Starting at KERNBASE - map all 2G worth of page table pages.
852 * KERNBASE is offset -2G from the end of kvm. This will accomodate
853 * all KVM allocations above KERNBASE, including the SYSMAPs below.
855 * We do this by allocating 2*512 PT pages. Each PT page can map
856 * 2MB, for 2GB total.
858 nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
861 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
862 * Calculate how many page table pages we need to preallocate
863 * for early vm_map allocations.
865 * A few extra won't hurt, they will get used up in the running
866 * system.
868 * vm_page array
869 * initial pventry's
871 nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
872 nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
873 nkpt_phys += 128; /* a few extra */
876 * The highest value nkpd_phys can be set to is
877 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
879 * Doing so would cause all PD pages to be pre-populated for
880 * a maximal KVM space (approximately 16*512 pages, or 32MB.
881 * We can save memory by not doing this.
883 nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
886 * Allocate pages
888 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
889 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
891 * Only allocate enough PD pages
892 * NOTE: We allocate all kernel PD pages up-front, typically
893 * ~511G of KVM, requiring 511 PD pages.
895 KPTbase = allocpages(firstaddr, nkpt_base); /* KERNBASE to end */
896 KPTphys = allocpages(firstaddr, nkpt_phys); /* KVA start */
897 KPML4phys = allocpages(firstaddr, 1); /* recursive PML4 map */
898 KPDPphys = allocpages(firstaddr, NKPML4E); /* kernel PDP pages */
899 KPDphys = allocpages(firstaddr, nkpd_phys); /* kernel PD pages */
902 * Alloc PD pages for the area starting at KERNBASE.
904 KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
907 * Stuff for our DMAP
909 DMPDPphys = allocpages(firstaddr, NDMPML4E);
910 if ((amd_feature & AMDID_PAGE1GB) == 0)
911 DMPDphys = allocpages(firstaddr, ndmpdp);
912 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
915 * Fill in the underlying page table pages for the area around
916 * KERNBASE. This remaps low physical memory to KERNBASE.
918 * Read-only from zero to physfree
919 * XXX not fully used, underneath 2M pages
921 for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
922 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
923 ((pt_entry_t *)KPTbase)[i] |=
924 pmap_bits_default[PG_RW_IDX] |
925 pmap_bits_default[PG_V_IDX] |
926 pmap_bits_default[PG_G_IDX];
930 * Now map the initial kernel page tables. One block of page
931 * tables is placed at the beginning of kernel virtual memory,
932 * and another block is placed at KERNBASE to map the kernel binary,
933 * data, bss, and initial pre-allocations.
935 for (i = 0; i < nkpt_base; i++) {
936 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
937 ((pd_entry_t *)KPDbase)[i] |=
938 pmap_bits_default[PG_RW_IDX] |
939 pmap_bits_default[PG_V_IDX];
941 for (i = 0; i < nkpt_phys; i++) {
942 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
943 ((pd_entry_t *)KPDphys)[i] |=
944 pmap_bits_default[PG_RW_IDX] |
945 pmap_bits_default[PG_V_IDX];
949 * Map from zero to end of allocations using 2M pages as an
950 * optimization. This will bypass some of the KPTBase pages
951 * above in the KERNBASE area.
953 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
954 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
955 ((pd_entry_t *)KPDbase)[i] |=
956 pmap_bits_default[PG_RW_IDX] |
957 pmap_bits_default[PG_V_IDX] |
958 pmap_bits_default[PG_PS_IDX] |
959 pmap_bits_default[PG_G_IDX];
963 * Load PD addresses into the PDP pages for primary KVA space to
964 * cover existing page tables. PD's for KERNBASE are handled in
965 * the next loop.
967 * expected to pre-populate all of its PDs. See NKPDPE in vmparam.h.
969 for (i = 0; i < nkpd_phys; i++) {
970 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
971 KPDphys + (i << PAGE_SHIFT);
972 ((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
973 pmap_bits_default[PG_RW_IDX] |
974 pmap_bits_default[PG_V_IDX] |
975 pmap_bits_default[PG_A_IDX];
979 * Load PDs for KERNBASE to the end
981 i = (NKPML4E - 1) * NPDPEPG + KPDPI;
982 for (j = 0; j < NPDPEPG - KPDPI; ++j) {
983 ((pdp_entry_t *)KPDPphys)[i + j] =
984 KPDbase + (j << PAGE_SHIFT);
985 ((pdp_entry_t *)KPDPphys)[i + j] |=
986 pmap_bits_default[PG_RW_IDX] |
987 pmap_bits_default[PG_V_IDX] |
988 pmap_bits_default[PG_A_IDX];
992 * Now set up the direct map space using either 2MB or 1GB pages
993 * Preset PG_M and PG_A because demotion expects it.
995 * When filling in entries in the PD pages make sure any excess
996 * entries are set to zero as we allocated enough PD pages
998 if ((amd_feature & AMDID_PAGE1GB) == 0) {
1000 * Use 2MB pages
1002 for (i = 0; i < NPDEPG * ndmpdp; i++) {
1003 ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
1004 ((pd_entry_t *)DMPDphys)[i] |=
1005 pmap_bits_default[PG_RW_IDX] |
1006 pmap_bits_default[PG_V_IDX] |
1007 pmap_bits_default[PG_PS_IDX] |
1008 pmap_bits_default[PG_G_IDX] |
1009 pmap_bits_default[PG_M_IDX] |
1010 pmap_bits_default[PG_A_IDX];
1014 * And the direct map space's PDP
1016 for (i = 0; i < ndmpdp; i++) {
1017 ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1018 (i << PAGE_SHIFT);
1019 ((pdp_entry_t *)DMPDPphys)[i] |=
1020 pmap_bits_default[PG_RW_IDX] |
1021 pmap_bits_default[PG_V_IDX];
1023 } else {
1025 * 1GB pages
1027 for (i = 0; i < ndmpdp; i++) {
1028 ((pdp_entry_t *)DMPDPphys)[i] =
1029 (vm_paddr_t)i << PDPSHIFT;
1030 ((pdp_entry_t *)DMPDPphys)[i] |=
1031 pmap_bits_default[PG_RW_IDX] |
1032 pmap_bits_default[PG_V_IDX] |
1033 pmap_bits_default[PG_PS_IDX] |
1034 pmap_bits_default[PG_G_IDX] |
1035 pmap_bits_default[PG_M_IDX] |
1036 pmap_bits_default[PG_A_IDX];
1040 /* And recursively map PML4 to itself in order to get PTmap */
1041 ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1042 ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1043 pmap_bits_default[PG_RW_IDX] |
1044 pmap_bits_default[PG_V_IDX] |
1045 pmap_bits_default[PG_A_IDX];
1048 * Connect the Direct Map slots up to the PML4
1050 for (j = 0; j < NDMPML4E; ++j) {
1051 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1052 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1053 pmap_bits_default[PG_RW_IDX] |
1054 pmap_bits_default[PG_V_IDX] |
1055 pmap_bits_default[PG_A_IDX];
1059 * Connect the KVA slot up to the PML4
1061 for (j = 0; j < NKPML4E; ++j) {
1062 ((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1063 KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1064 ((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1065 pmap_bits_default[PG_RW_IDX] |
1066 pmap_bits_default[PG_V_IDX] |
1067 pmap_bits_default[PG_A_IDX];
1069 cpu_mfence();
1070 cpu_invltlb();
1074 * Bootstrap the system enough to run with virtual memory.
1076 * On x86_64 this is called after mapping has already been enabled
1077 * and just syncs the pmap module with what has already been done.
1078 * [We can't call it easily with mapping off since the kernel is not
1079 * mapped with PA == VA, hence we would have to relocate every address
1080 * from the linked base (virtual) address "KERNBASE" to the actual
1081 * (physical) address starting relative to 0]
1083 void
1084 pmap_bootstrap(vm_paddr_t *firstaddr)
1086 vm_offset_t va;
1087 pt_entry_t *pte;
1088 int i;
1090 KvaStart = VM_MIN_KERNEL_ADDRESS;
1091 KvaEnd = VM_MAX_KERNEL_ADDRESS;
1092 KvaSize = KvaEnd - KvaStart;
1094 avail_start = *firstaddr;
1097 * Create an initial set of page tables to run the kernel in.
1099 create_pagetables(firstaddr);
1101 virtual2_start = KvaStart;
1102 virtual2_end = PTOV_OFFSET;
1104 virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1105 virtual_start = pmap_kmem_choose(virtual_start);
1107 virtual_end = VM_MAX_KERNEL_ADDRESS;
1109 /* XXX do %cr0 as well */
1110 load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1111 load_cr3(KPML4phys);
1114 * Initialize protection array.
1116 x86_64_protection_init();
1119 * The kernel's pmap is statically allocated so we don't have to use
1120 * pmap_create, which is unlikely to work correctly at this part of
1121 * the boot sequence (XXX and which no longer exists).
1123 kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1124 kernel_pmap.pm_count = 1;
1125 CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1126 RB_INIT(&kernel_pmap.pm_pvroot);
1127 spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1128 for (i = 0; i < PM_PLACEMARKS; ++i)
1129 kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1132 * Reserve some special page table entries/VA space for temporary
1133 * mapping of pages.
1135 #define SYSMAP(c, p, v, n) \
1136 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1138 va = virtual_start;
1139 pte = vtopte(va);
1142 * CMAP1/CMAP2 are used for zeroing and copying pages.
1144 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1147 * Crashdump maps.
1149 SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1152 * ptvmmap is used for reading arbitrary physical pages via
1153 * /dev/mem.
1155 SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1158 * msgbufp is used to map the system message buffer.
1159 * XXX msgbufmap is not used.
1161 SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1162 atop(round_page(MSGBUF_SIZE)))
1164 virtual_start = va;
1165 virtual_start = pmap_kmem_choose(virtual_start);
1167 *CMAP1 = 0;
1170 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1171 * cases rather then invl1pg. Actually, I don't even know why it
1172 * works under UP because self-referential page table mappings
1174 // pgeflag = 0;
1176 cpu_invltlb();
1178 /* Initialize the PAT MSR */
1179 pmap_init_pat();
1180 pmap_pinit_defaults(&kernel_pmap);
1182 TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1183 &pmap_fast_kernel_cpusync);
1188 * Setup the PAT MSR.
1190 void
1191 pmap_init_pat(void)
1193 uint64_t pat_msr;
1194 u_long cr0, cr4;
1197 * Default values mapping PATi,PCD,PWT bits at system reset.
1198 * The default values effectively ignore the PATi bit by
1199 * repeating the encodings for 0-3 in 4-7, and map the PCD
1200 * and PWT bit combinations to the expected PAT types.
1202 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) | /* 000 */
1203 PAT_VALUE(1, PAT_WRITE_THROUGH) | /* 001 */
1204 PAT_VALUE(2, PAT_UNCACHED) | /* 010 */
1205 PAT_VALUE(3, PAT_UNCACHEABLE) | /* 011 */
1206 PAT_VALUE(4, PAT_WRITE_BACK) | /* 100 */
1207 PAT_VALUE(5, PAT_WRITE_THROUGH) | /* 101 */
1208 PAT_VALUE(6, PAT_UNCACHED) | /* 110 */
1209 PAT_VALUE(7, PAT_UNCACHEABLE); /* 111 */
1210 pat_pte_index[PAT_WRITE_BACK] = 0;
1211 pat_pte_index[PAT_WRITE_THROUGH]= 0 | X86_PG_NC_PWT;
1212 pat_pte_index[PAT_UNCACHED] = X86_PG_NC_PCD;
1213 pat_pte_index[PAT_UNCACHEABLE] = X86_PG_NC_PCD | X86_PG_NC_PWT;
1214 pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1215 pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1217 if (cpu_feature & CPUID_PAT) {
1219 * If we support the PAT then set-up entries for
1220 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1221 * 5 and 6.
1223 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1224 PAT_VALUE(5, PAT_WRITE_PROTECTED);
1225 pat_msr = (pat_msr & ~PAT_MASK(6)) |
1226 PAT_VALUE(6, PAT_WRITE_COMBINING);
1227 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1228 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1231 * Then enable the PAT
1234 /* Disable PGE. */
1235 cr4 = rcr4();
1236 load_cr4(cr4 & ~CR4_PGE);
1238 /* Disable caches (CD = 1, NW = 0). */
1239 cr0 = rcr0();
1240 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1242 /* Flushes caches and TLBs. */
1243 wbinvd();
1244 cpu_invltlb();
1246 /* Update PAT and index table. */
1247 wrmsr(MSR_PAT, pat_msr);
1249 /* Flush caches and TLBs again. */
1250 wbinvd();
1251 cpu_invltlb();
1253 /* Restore caches and PGE. */
1254 load_cr0(cr0);
1255 load_cr4(cr4);
1256 PatMsr = pat_msr;
1261 * Set 4mb pdir for mp startup
1263 void
1264 pmap_set_opt(void)
1266 if (cpu_feature & CPUID_PSE) {
1267 load_cr4(rcr4() | CR4_PSE);
1268 if (mycpu->gd_cpuid == 0) /* only on BSP */
1269 cpu_invltlb();
1273 * Check for SMAP support and enable if available. Must be done
1274 * after cr3 is loaded, and on all cores.
1276 if (cpu_stdext_feature & CPUID_STDEXT_SMAP) {
1277 load_cr4(rcr4() | CR4_SMAP);
1279 if (cpu_stdext_feature & CPUID_STDEXT_SMEP) {
1280 load_cr4(rcr4() | CR4_SMEP);
1285 * Early initialization of the pmap module.
1287 * Called by vm_init, to initialize any structures that the pmap
1288 * system needs to map virtual memory. pmap_init has been enhanced to
1289 * support in a fairly consistant way, discontiguous physical memory.
1291 void
1292 pmap_init(void)
1294 vm_pindex_t initial_pvs;
1295 vm_pindex_t i;
1298 * Allocate memory for random pmap data structures. Includes the
1299 * pv_head_table.
1301 for (i = 0; i < vm_page_array_size; i++) {
1302 vm_page_t m;
1304 m = &vm_page_array[i];
1305 TAILQ_INIT(&m->md.pv_list);
1309 * init the pv free list
1311 initial_pvs = vm_page_array_size;
1312 if (initial_pvs < MINPV)
1313 initial_pvs = MINPV;
1314 pvzone = &pvzone_store;
1315 pvinit = (void *)kmem_alloc(&kernel_map,
1316 initial_pvs * sizeof (struct pv_entry),
1317 VM_SUBSYS_PVENTRY);
1318 zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1319 pvinit, initial_pvs);
1322 * Now it is safe to enable pv_table recording.
1324 pmap_initialized = TRUE;
1328 * Initialize the address space (zone) for the pv_entries. Set a
1329 * high water mark so that the system can recover from excessive
1330 * numbers of pv entries.
1332 * Also create the kernel page table template for isolated user
1333 * pmaps.
1335 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1336 static void pmap_init2_iso_pmap(void);
1337 #if 0
1338 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1339 #endif
1341 void
1342 pmap_init2(void)
1344 vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
1345 vm_pindex_t entry_max;
1347 TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1348 pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1349 TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1350 pv_entry_high_water = 9 * (pv_entry_max / 10);
1353 * Subtract out pages already installed in the zone (hack)
1355 entry_max = pv_entry_max - vm_page_array_size;
1356 if (entry_max <= 0)
1357 entry_max = 1;
1359 zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1362 * Enable dynamic deletion of empty higher-level page table pages
1363 * by default only if system memory is < 8GB (use 7GB for slop).
1364 * This can save a little memory, but imposes significant
1365 * performance overhead for things like bulk builds, and for programs
1366 * which do a lot of memory mapping and memory unmapping.
1368 if (pmap_dynamic_delete < 0) {
1369 if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1370 pmap_dynamic_delete = 1;
1371 else
1372 pmap_dynamic_delete = 0;
1376 * Automatic detection of Intel meltdown bug requiring user/kernel
1377 * mmap isolation.
1379 * Currently there are so many Intel cpu's impacted that its better
1380 * to whitelist future Intel CPUs. Most? AMD cpus are not impacted
1381 * so the default is off for AMD.
1383 if (meltdown_mitigation < 0) {
1384 if (cpu_vendor_id == CPU_VENDOR_INTEL)
1385 meltdown_mitigation = 1;
1386 else
1387 meltdown_mitigation = 0;
1389 if (meltdown_mitigation) {
1390 kprintf("machdep.meltdown_mitigation enabled to "
1391 "protect against (mostly Intel) meltdown bug\n");
1392 kprintf("system call performance will be impacted\n");
1395 pmap_init2_iso_pmap();
1399 * Create the isolation pmap template. Once created, the template
1400 * is static and its PML4e entries are used to populate the
1401 * kernel portion of any isolated user pmaps.
1403 * Our isolation pmap must contain:
1404 * (1) trampoline area for all cpus
1405 * (2) common_tss area for all cpus (its part of the trampoline area now)
1406 * (3) IDT for all cpus
1407 * (4) GDT for all cpus
1409 static void
1410 pmap_init2_iso_pmap(void)
1412 int n;
1414 if (bootverbose)
1415 kprintf("Initialize isolation pmap\n");
1418 * Try to use our normal API calls to make this easier. We have
1419 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1420 * iso_pmap.
1422 pmap_pinit(&iso_pmap);
1423 bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1426 * Install areas needed by the cpu and trampoline.
1428 for (n = 0; n < ncpus; ++n) {
1429 struct privatespace *ps;
1431 ps = CPU_prvspace[n];
1432 pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1433 sizeof(ps->trampoline));
1434 pmap_init_iso_range((vm_offset_t)&ps->dblstack,
1435 sizeof(ps->dblstack));
1436 pmap_init_iso_range((vm_offset_t)&ps->dbgstack,
1437 sizeof(ps->dbgstack));
1438 pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1439 sizeof(ps->common_tss));
1440 pmap_init_iso_range(r_idt_arr[n].rd_base,
1441 r_idt_arr[n].rd_limit + 1);
1443 pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1444 pmap_init_iso_range((vm_offset_t)(int *)btext,
1445 (vm_offset_t)(int *)etext -
1446 (vm_offset_t)(int *)btext);
1448 #if 0
1449 kprintf("Dump iso_pmap:\n");
1450 dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1451 kprintf("\nDump kernel_pmap:\n");
1452 dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1453 #endif
1457 * This adds a kernel virtual address range to the isolation pmap.
1459 static void
1460 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1462 pv_entry_t pv;
1463 pv_entry_t pvp;
1464 pt_entry_t *ptep;
1465 pt_entry_t pte;
1466 vm_offset_t va;
1468 if (bootverbose) {
1469 kprintf("isolate %016jx-%016jx (%zd)\n",
1470 base, base + bytes, bytes);
1472 va = base & ~(vm_offset_t)PAGE_MASK;
1473 while (va < base + bytes) {
1474 if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1475 (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1476 (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1477 (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1479 * Use 2MB pages if possible
1481 pte = *ptep;
1482 pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1483 ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1484 *ptep = pte;
1485 va += NBPDR;
1486 } else {
1488 * Otherwise use 4KB pages
1490 pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1491 ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1492 *ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1493 kernel_pmap.pmap_bits[PG_V_IDX] |
1494 kernel_pmap.pmap_bits[PG_A_IDX] |
1495 kernel_pmap.pmap_bits[PG_M_IDX];
1497 va += PAGE_SIZE;
1499 pv_put(pv);
1500 pv_put(pvp);
1504 #if 0
1506 * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1508 static
1509 void
1510 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1512 pt_entry_t *ptp;
1513 vm_offset_t incr;
1514 int i;
1516 switch(level) {
1517 case 0: /* PML4e page, 512G entries */
1518 incr = (1LL << 48) / 512;
1519 break;
1520 case 1: /* PDP page, 1G entries */
1521 incr = (1LL << 39) / 512;
1522 break;
1523 case 2: /* PD page, 2MB entries */
1524 incr = (1LL << 30) / 512;
1525 break;
1526 case 3: /* PT page, 4KB entries */
1527 incr = (1LL << 21) / 512;
1528 break;
1529 default:
1530 incr = 0;
1531 break;
1534 if (level == 0)
1535 kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1536 ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1537 for (i = 0; i < 512; ++i) {
1538 if (level == 0 && i == 128)
1539 base += 0xFFFF000000000000LLU;
1540 if (ptp[i]) {
1541 kprintf("%*.*s ", level * 4, level * 4, "");
1542 if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1543 kprintf("va=%016jx %3d term %016jx (1GB)\n",
1544 base, i, ptp[i]);
1545 } else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1546 kprintf("va=%016jx %3d term %016jx (2MB)\n",
1547 base, i, ptp[i]);
1548 } else if (level == 3) {
1549 kprintf("va=%016jx %3d term %016jx\n",
1550 base, i, ptp[i]);
1551 } else {
1552 kprintf("va=%016jx %3d deep %016jx\n",
1553 base, i, ptp[i]);
1554 dump_pmap(pmap, ptp[i], level + 1, base);
1557 base += incr;
1561 #endif
1564 * Typically used to initialize a fictitious page by vm/device_pager.c
1566 void
1567 pmap_page_init(struct vm_page *m)
1569 vm_page_init(m);
1570 TAILQ_INIT(&m->md.pv_list);
1573 /***************************************************
1574 * Low level helper routines.....
1575 ***************************************************/
1578 * this routine defines the region(s) of memory that should
1579 * not be tested for the modified bit.
1581 static __inline
1583 pmap_track_modified(vm_pindex_t pindex)
1585 vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
1586 if ((va < clean_sva) || (va >= clean_eva))
1587 return 1;
1588 else
1589 return 0;
1593 * Extract the physical page address associated with the map/VA pair.
1594 * The page must be wired for this to work reliably.
1596 vm_paddr_t
1597 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1599 vm_paddr_t rtval;
1600 pv_entry_t pt_pv;
1601 pt_entry_t *ptep;
1603 rtval = 0;
1604 if (va >= VM_MAX_USER_ADDRESS) {
1606 * Kernel page directories might be direct-mapped and
1607 * there is typically no PV tracking of pte's
1609 pd_entry_t *pt;
1611 pt = pmap_pt(pmap, va);
1612 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1613 if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1614 rtval = *pt & PG_PS_FRAME;
1615 rtval |= va & PDRMASK;
1616 } else {
1617 ptep = pmap_pt_to_pte(*pt, va);
1618 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1619 rtval = *ptep & PG_FRAME;
1620 rtval |= va & PAGE_MASK;
1624 if (handlep)
1625 *handlep = NULL;
1626 } else {
1628 * User pages currently do not direct-map the page directory
1629 * and some pages might not used managed PVs. But all PT's
1630 * will have a PV.
1632 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1633 if (pt_pv) {
1634 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1635 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1636 rtval = *ptep & PG_FRAME;
1637 rtval |= va & PAGE_MASK;
1639 if (handlep)
1640 *handlep = pt_pv; /* locked until done */
1641 else
1642 pv_put (pt_pv);
1643 } else if (handlep) {
1644 *handlep = NULL;
1647 return rtval;
1650 void
1651 pmap_extract_done(void *handle)
1653 if (handle)
1654 pv_put((pv_entry_t)handle);
1658 * Similar to extract but checks protections, SMP-friendly short-cut for
1659 * vm_fault_page[_quick](). Can return NULL to cause the caller to
1660 * fall-through to the real fault code. Does not work with HVM page
1661 * tables.
1663 * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1665 * If busyp is not NULL and this function sets *busyp non-zero, the returned
1666 * page is busied (and not held).
1668 * If busyp is not NULL and this function sets *busyp to zero, the returned
1669 * page is held (and not busied).
1671 * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1672 * returned page will be dirtied. If the pte is not already writable NULL
1673 * is returned. In otherwords, if the bit is set and a vm_page_t is returned,
1674 * any COW will already have happened and that page can be written by the
1675 * caller.
1677 * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1678 * OR WRITING AS-IS.
1680 vm_page_t
1681 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1683 if (pmap &&
1684 va < VM_MAX_USER_ADDRESS &&
1685 (pmap->pm_flags & PMAP_HVM) == 0) {
1686 pv_entry_t pt_pv;
1687 pv_entry_t pte_pv;
1688 pt_entry_t *ptep;
1689 pt_entry_t req;
1690 vm_page_t m;
1691 int error;
1693 req = pmap->pmap_bits[PG_V_IDX] |
1694 pmap->pmap_bits[PG_U_IDX];
1695 if (prot & VM_PROT_WRITE)
1696 req |= pmap->pmap_bits[PG_RW_IDX];
1698 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1699 if (pt_pv == NULL)
1700 return (NULL);
1701 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1702 if ((*ptep & req) != req) {
1703 pv_put(pt_pv);
1704 return (NULL);
1706 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1707 if (pte_pv && error == 0) {
1708 m = pte_pv->pv_m;
1709 if (prot & VM_PROT_WRITE) {
1710 /* interlocked by presence of pv_entry */
1711 vm_page_dirty(m);
1713 if (busyp) {
1714 if (prot & VM_PROT_WRITE) {
1715 if (vm_page_busy_try(m, TRUE))
1716 m = NULL;
1717 *busyp = 1;
1718 } else {
1719 vm_page_hold(m);
1720 *busyp = 0;
1722 } else {
1723 vm_page_hold(m);
1725 pv_put(pte_pv);
1726 } else if (pte_pv) {
1727 pv_drop(pte_pv);
1728 m = NULL;
1729 } else {
1730 /* error, since we didn't request a placemarker */
1731 m = NULL;
1733 pv_put(pt_pv);
1734 return(m);
1735 } else {
1736 return(NULL);
1741 * Extract the physical page address associated kernel virtual address.
1743 vm_paddr_t
1744 pmap_kextract(vm_offset_t va)
1746 pd_entry_t pt; /* pt entry in pd */
1747 vm_paddr_t pa;
1749 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1750 pa = DMAP_TO_PHYS(va);
1751 } else {
1752 pt = *vtopt(va);
1753 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1754 pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1755 } else {
1757 * Beware of a concurrent promotion that changes the
1758 * PDE at this point! For example, vtopte() must not
1759 * be used to access the PTE because it would use the
1760 * new PDE. It is, however, safe to use the old PDE
1761 * because the page table page is preserved by the
1762 * promotion.
1764 pa = *pmap_pt_to_pte(pt, va);
1765 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1768 return pa;
1771 /***************************************************
1772 * Low level mapping routines.....
1773 ***************************************************/
1776 * Routine: pmap_kenter
1777 * Function:
1778 * Add a wired page to the KVA
1779 * NOTE! note that in order for the mapping to take effect -- you
1780 * should do an invltlb after doing the pmap_kenter().
1782 void
1783 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1785 pt_entry_t *ptep;
1786 pt_entry_t npte;
1788 npte = pa |
1789 kernel_pmap.pmap_bits[PG_RW_IDX] |
1790 kernel_pmap.pmap_bits[PG_V_IDX];
1791 // pgeflag;
1792 ptep = vtopte(va);
1793 #if 1
1794 pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1795 #else
1796 /* FUTURE */
1797 if (*ptep)
1798 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1799 else
1800 *ptep = npte;
1801 #endif
1805 * Similar to pmap_kenter(), except we only invalidate the mapping on the
1806 * current CPU. Returns 0 if the previous pte was 0, 1 if it wasn't
1807 * (caller can conditionalize calling smp_invltlb()).
1810 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1812 pt_entry_t *ptep;
1813 pt_entry_t npte;
1814 int res;
1816 npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1817 kernel_pmap.pmap_bits[PG_V_IDX];
1818 // npte |= pgeflag;
1819 ptep = vtopte(va);
1820 #if 1
1821 res = 1;
1822 #else
1823 /* FUTURE */
1824 res = (*ptep != 0);
1825 #endif
1826 atomic_swap_long(ptep, npte);
1827 cpu_invlpg((void *)va);
1829 return res;
1833 * Enter addresses into the kernel pmap but don't bother
1834 * doing any tlb invalidations. Caller will do a rollup
1835 * invalidation via pmap_rollup_inval().
1838 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1840 pt_entry_t *ptep;
1841 pt_entry_t npte;
1842 int res;
1844 npte = pa |
1845 kernel_pmap.pmap_bits[PG_RW_IDX] |
1846 kernel_pmap.pmap_bits[PG_V_IDX];
1847 // pgeflag;
1848 ptep = vtopte(va);
1849 #if 1
1850 res = 1;
1851 #else
1852 /* FUTURE */
1853 res = (*ptep != 0);
1854 #endif
1855 atomic_swap_long(ptep, npte);
1856 cpu_invlpg((void *)va);
1858 return res;
1862 * remove a page from the kernel pagetables
1864 void
1865 pmap_kremove(vm_offset_t va)
1867 pt_entry_t *ptep;
1869 ptep = vtopte(va);
1870 pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1873 void
1874 pmap_kremove_quick(vm_offset_t va)
1876 pt_entry_t *ptep;
1878 ptep = vtopte(va);
1879 (void)pte_load_clear(ptep);
1880 cpu_invlpg((void *)va);
1884 * Remove addresses from the kernel pmap but don't bother
1885 * doing any tlb invalidations. Caller will do a rollup
1886 * invalidation via pmap_rollup_inval().
1888 void
1889 pmap_kremove_noinval(vm_offset_t va)
1891 pt_entry_t *ptep;
1893 ptep = vtopte(va);
1894 (void)pte_load_clear(ptep);
1898 * XXX these need to be recoded. They are not used in any critical path.
1900 void
1901 pmap_kmodify_rw(vm_offset_t va)
1903 atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1904 cpu_invlpg((void *)va);
1907 /* NOT USED
1908 void
1909 pmap_kmodify_nc(vm_offset_t va)
1911 atomic_set_long(vtopte(va), PG_N);
1912 cpu_invlpg((void *)va);
1917 * Used to map a range of physical addresses into kernel virtual
1918 * address space during the low level boot, typically to map the
1919 * dump bitmap, message buffer, and vm_page_array.
1921 * These mappings are typically made at some pointer after the end of the
1922 * kernel text+data.
1924 * We could return PHYS_TO_DMAP(start) here and not allocate any
1925 * via (*virtp), but then kmem from userland and kernel dumps won't
1926 * have access to the related pointers.
1928 vm_offset_t
1929 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1931 vm_offset_t va;
1932 vm_offset_t va_start;
1934 /*return PHYS_TO_DMAP(start);*/
1936 va_start = *virtp;
1937 va = va_start;
1939 while (start < end) {
1940 pmap_kenter_quick(va, start);
1941 va += PAGE_SIZE;
1942 start += PAGE_SIZE;
1944 *virtp = va;
1945 return va_start;
1948 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1951 * Remove the specified set of pages from the data and instruction caches.
1953 * In contrast to pmap_invalidate_cache_range(), this function does not
1954 * rely on the CPU's self-snoop feature, because it is intended for use
1955 * when moving pages into a different cache domain.
1957 void
1958 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1960 vm_offset_t daddr, eva;
1961 int i;
1963 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1964 (cpu_feature & CPUID_CLFSH) == 0)
1965 wbinvd();
1966 else {
1967 cpu_mfence();
1968 for (i = 0; i < count; i++) {
1969 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1970 eva = daddr + PAGE_SIZE;
1971 for (; daddr < eva; daddr += cpu_clflush_line_size)
1972 clflush(daddr);
1974 cpu_mfence();
1978 void
1979 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1981 KASSERT((sva & PAGE_MASK) == 0,
1982 ("pmap_invalidate_cache_range: sva not page-aligned"));
1983 KASSERT((eva & PAGE_MASK) == 0,
1984 ("pmap_invalidate_cache_range: eva not page-aligned"));
1986 if (cpu_feature & CPUID_SS) {
1987 ; /* If "Self Snoop" is supported, do nothing. */
1988 } else {
1989 /* Globally invalidate caches */
1990 cpu_wbinvd_on_all_cpus();
1995 * Invalidate the specified range of virtual memory on all cpus associated
1996 * with the pmap.
1998 void
1999 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2001 pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
2005 * Add a list of wired pages to the kva. This routine is used for temporary
2006 * kernel mappings such as those found in buffer cache buffer. Page
2007 * modifications and accesses are not tracked or recorded.
2009 * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
2010 * semantics as previous mappings may have been zerod without any
2011 * invalidation.
2013 * The page *must* be wired.
2015 static __inline void
2016 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
2018 vm_offset_t end_va;
2019 vm_offset_t va;
2021 end_va = beg_va + count * PAGE_SIZE;
2023 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2024 pt_entry_t pte;
2025 pt_entry_t *ptep;
2027 ptep = vtopte(va);
2028 pte = VM_PAGE_TO_PHYS(*m) |
2029 kernel_pmap.pmap_bits[PG_RW_IDX] |
2030 kernel_pmap.pmap_bits[PG_V_IDX] |
2031 kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2032 // pgeflag;
2033 atomic_swap_long(ptep, pte);
2034 m++;
2036 if (doinval)
2037 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2040 void
2041 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2043 _pmap_qenter(beg_va, m, count, 1);
2046 void
2047 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2049 _pmap_qenter(beg_va, m, count, 0);
2053 * This routine jerks page mappings from the kernel -- it is meant only
2054 * for temporary mappings such as those found in buffer cache buffers.
2055 * No recording modified or access status occurs.
2057 * MPSAFE, INTERRUPT SAFE (cluster callback)
2059 void
2060 pmap_qremove(vm_offset_t beg_va, int count)
2062 vm_offset_t end_va;
2063 vm_offset_t va;
2065 end_va = beg_va + count * PAGE_SIZE;
2067 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2068 pt_entry_t *pte;
2070 pte = vtopte(va);
2071 (void)pte_load_clear(pte);
2072 cpu_invlpg((void *)va);
2074 pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2078 * This routine removes temporary kernel mappings, only invalidating them
2079 * on the current cpu. It should only be used under carefully controlled
2080 * conditions.
2082 void
2083 pmap_qremove_quick(vm_offset_t beg_va, int count)
2085 vm_offset_t end_va;
2086 vm_offset_t va;
2088 end_va = beg_va + count * PAGE_SIZE;
2090 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2091 pt_entry_t *pte;
2093 pte = vtopte(va);
2094 (void)pte_load_clear(pte);
2095 cpu_invlpg((void *)va);
2100 * This routine removes temporary kernel mappings *without* invalidating
2101 * the TLB. It can only be used on permanent kva reservations such as those
2102 * found in buffer cache buffers, under carefully controlled circumstances.
2104 * NOTE: Repopulating these KVAs requires unconditional invalidation.
2105 * (pmap_qenter() does unconditional invalidation).
2107 void
2108 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2110 vm_offset_t end_va;
2111 vm_offset_t va;
2113 end_va = beg_va + count * PAGE_SIZE;
2115 for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2116 pt_entry_t *pte;
2118 pte = vtopte(va);
2119 (void)pte_load_clear(pte);
2124 * Create a new thread and optionally associate it with a (new) process.
2125 * NOTE! the new thread's cpu may not equal the current cpu.
2127 void
2128 pmap_init_thread(thread_t td)
2130 /* enforce pcb placement & alignment */
2131 td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2132 td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2133 td->td_savefpu = &td->td_pcb->pcb_save;
2134 td->td_sp = (char *)td->td_pcb; /* no -16 */
2138 * This routine directly affects the fork perf for a process.
2140 void
2141 pmap_init_proc(struct proc *p)
2145 static void
2146 pmap_pinit_defaults(struct pmap *pmap)
2148 bcopy(pmap_bits_default, pmap->pmap_bits,
2149 sizeof(pmap_bits_default));
2150 bcopy(protection_codes, pmap->protection_codes,
2151 sizeof(protection_codes));
2152 bcopy(pat_pte_index, pmap->pmap_cache_bits,
2153 sizeof(pat_pte_index));
2154 pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2155 pmap->copyinstr = std_copyinstr;
2156 pmap->copyin = std_copyin;
2157 pmap->copyout = std_copyout;
2158 pmap->fubyte = std_fubyte;
2159 pmap->subyte = std_subyte;
2160 pmap->fuword32 = std_fuword32;
2161 pmap->fuword64 = std_fuword64;
2162 pmap->suword32 = std_suword32;
2163 pmap->suword64 = std_suword64;
2164 pmap->swapu32 = std_swapu32;
2165 pmap->swapu64 = std_swapu64;
2166 pmap->fuwordadd32 = std_fuwordadd32;
2167 pmap->fuwordadd64 = std_fuwordadd64;
2170 * Initialize pmap0/vmspace0.
2172 * On architectures where the kernel pmap is not integrated into the user
2173 * process pmap, this pmap represents the process pmap, not the kernel pmap.
2174 * kernel_pmap should be used to directly access the kernel_pmap.
2176 void
2177 pmap_pinit0(struct pmap *pmap)
2179 int i;
2181 pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2182 pmap->pm_count = 1;
2183 CPUMASK_ASSZERO(pmap->pm_active);
2184 pmap->pm_pvhint_pt = NULL;
2185 pmap->pm_pvhint_pte = NULL;
2186 RB_INIT(&pmap->pm_pvroot);
2187 spin_init(&pmap->pm_spin, "pmapinit0");
2188 for (i = 0; i < PM_PLACEMARKS; ++i)
2189 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2190 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2191 pmap_pinit_defaults(pmap);
2195 * Initialize a preallocated and zeroed pmap structure,
2196 * such as one in a vmspace structure.
2198 static void
2199 pmap_pinit_simple(struct pmap *pmap)
2201 int i;
2204 * Misc initialization
2206 pmap->pm_count = 1;
2207 CPUMASK_ASSZERO(pmap->pm_active);
2208 pmap->pm_pvhint_pt = NULL;
2209 pmap->pm_pvhint_pte = NULL;
2210 pmap->pm_flags = PMAP_FLAG_SIMPLE;
2212 pmap_pinit_defaults(pmap);
2215 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2216 * for this).
2218 if (pmap->pm_pmlpv == NULL) {
2219 RB_INIT(&pmap->pm_pvroot);
2220 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2221 spin_init(&pmap->pm_spin, "pmapinitsimple");
2222 for (i = 0; i < PM_PLACEMARKS; ++i)
2223 pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2227 void
2228 pmap_pinit(struct pmap *pmap)
2230 pv_entry_t pv;
2231 int j;
2233 if (pmap->pm_pmlpv) {
2234 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2235 pmap_puninit(pmap);
2239 pmap_pinit_simple(pmap);
2240 pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2243 * No need to allocate page table space yet but we do need a valid
2244 * page directory table.
2246 if (pmap->pm_pml4 == NULL) {
2247 pmap->pm_pml4 =
2248 (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2249 PAGE_SIZE * 2,
2250 VM_SUBSYS_PML4);
2251 pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2255 * Allocate the PML4e table, which wires it even though it isn't
2256 * being entered into some higher level page table (it being the
2257 * highest level). If one is already cached we don't have to do
2258 * anything.
2260 if ((pv = pmap->pm_pmlpv) == NULL) {
2261 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2262 pmap->pm_pmlpv = pv;
2263 pmap_kenter((vm_offset_t)pmap->pm_pml4,
2264 VM_PAGE_TO_PHYS(pv->pv_m));
2265 pv_put(pv);
2268 * Install DMAP and KMAP.
2270 for (j = 0; j < NDMPML4E; ++j) {
2271 pmap->pm_pml4[DMPML4I + j] =
2272 (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2273 pmap->pmap_bits[PG_RW_IDX] |
2274 pmap->pmap_bits[PG_V_IDX] |
2275 pmap->pmap_bits[PG_A_IDX];
2277 for (j = 0; j < NKPML4E; ++j) {
2278 pmap->pm_pml4[KPML4I + j] =
2279 (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2280 pmap->pmap_bits[PG_RW_IDX] |
2281 pmap->pmap_bits[PG_V_IDX] |
2282 pmap->pmap_bits[PG_A_IDX];
2286 * install self-referential address mapping entry
2288 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2289 pmap->pmap_bits[PG_V_IDX] |
2290 pmap->pmap_bits[PG_RW_IDX] |
2291 pmap->pmap_bits[PG_A_IDX];
2292 } else {
2293 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2294 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2296 KKASSERT(pmap->pm_pml4[255] == 0);
2299 * When implementing an isolated userland pmap, a second PML4e table
2300 * is needed. We use pmap_pml4_pindex() + 1 for convenience, but
2301 * note that we do not operate on this table using our API functions
2302 * so handling of the + 1 case is mostly just to prevent implosions.
2304 * We install an isolated version of the kernel PDPs into this
2305 * second PML4e table. The pmap code will mirror all user PDPs
2306 * between the primary and secondary PML4e table.
2308 if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2309 pmap != &iso_pmap) {
2310 pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2311 pmap->pm_pmlpv_iso = pv;
2312 pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2313 VM_PAGE_TO_PHYS(pv->pv_m));
2314 pv_put(pv);
2317 * Install an isolated version of the kernel pmap for
2318 * user consumption, using PDPs constructed in iso_pmap.
2320 for (j = 0; j < NKPML4E; ++j) {
2321 pmap->pm_pml4_iso[KPML4I + j] =
2322 iso_pmap.pm_pml4[KPML4I + j];
2324 } else if (pv) {
2325 KKASSERT(pv->pv_m->flags & PG_MAPPED);
2326 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2331 * Clean up a pmap structure so it can be physically freed. This routine
2332 * is called by the vmspace dtor function. A great deal of pmap data is
2333 * left passively mapped to improve vmspace management so we have a bit
2334 * of cleanup work to do here.
2336 void
2337 pmap_puninit(pmap_t pmap)
2339 pv_entry_t pv;
2340 vm_page_t p;
2342 KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2343 if ((pv = pmap->pm_pmlpv) != NULL) {
2344 if (pv_hold_try(pv) == 0)
2345 pv_lock(pv);
2346 KKASSERT(pv == pmap->pm_pmlpv);
2347 p = pmap_remove_pv_page(pv);
2348 pv_free(pv, NULL);
2349 pv = NULL; /* safety */
2350 pmap_kremove((vm_offset_t)pmap->pm_pml4);
2351 vm_page_busy_wait(p, FALSE, "pgpun");
2352 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2353 vm_page_unwire(p, 0);
2354 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2355 vm_page_free(p);
2356 pmap->pm_pmlpv = NULL;
2358 if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2359 if (pv_hold_try(pv) == 0)
2360 pv_lock(pv);
2361 KKASSERT(pv == pmap->pm_pmlpv_iso);
2362 p = pmap_remove_pv_page(pv);
2363 pv_free(pv, NULL);
2364 pv = NULL; /* safety */
2365 pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2366 vm_page_busy_wait(p, FALSE, "pgpun");
2367 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2368 vm_page_unwire(p, 0);
2369 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2370 vm_page_free(p);
2371 pmap->pm_pmlpv_iso = NULL;
2373 if (pmap->pm_pml4) {
2374 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2375 kmem_free(&kernel_map,
2376 (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2377 pmap->pm_pml4 = NULL;
2378 pmap->pm_pml4_iso = NULL;
2380 KKASSERT(pmap->pm_stats.resident_count == 0);
2381 KKASSERT(pmap->pm_stats.wired_count == 0);
2385 * This function is now unused (used to add the pmap to the pmap_list)
2387 void
2388 pmap_pinit2(struct pmap *pmap)
2393 * This routine is called when various levels in the page table need to
2394 * be populated. This routine cannot fail.
2396 * This function returns two locked pv_entry's, one representing the
2397 * requested pv and one representing the requested pv's parent pv. If
2398 * an intermediate page table does not exist it will be created, mapped,
2399 * wired, and the parent page table will be given an additional hold
2400 * count representing the presence of the child pv_entry.
2402 static
2403 pv_entry_t
2404 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2406 pt_entry_t *ptep;
2407 pt_entry_t *ptep_iso;
2408 pv_entry_t pv;
2409 pv_entry_t pvp;
2410 pt_entry_t v;
2411 vm_pindex_t pt_pindex;
2412 vm_page_t m;
2413 int isnew;
2414 int ispt;
2417 * If the pv already exists and we aren't being asked for the
2418 * parent page table page we can just return it. A locked+held pv
2419 * is returned. The pv will also have a second hold related to the
2420 * pmap association that we don't have to worry about.
2422 ispt = 0;
2423 pv = pv_alloc(pmap, ptepindex, &isnew);
2424 if (isnew == 0 && pvpp == NULL)
2425 return(pv);
2428 * Special case terminal PVs. These are not page table pages so
2429 * no vm_page is allocated (the caller supplied the vm_page). If
2430 * pvpp is non-NULL we are being asked to also removed the pt_pv
2431 * for this pv.
2433 * Note that pt_pv's are only returned for user VAs. We assert that
2434 * a pt_pv is not being requested for kernel VAs. The kernel
2435 * pre-wires all higher-level page tables so don't overload managed
2436 * higher-level page tables on top of it!
2438 * However, its convenient for us to allow the case when creating
2439 * iso_pmap. This is a bit of a hack but it simplifies iso_pmap
2440 * a lot.
2442 if (ptepindex < pmap_pt_pindex(0)) {
2443 if (ptepindex >= NUPTE_USER && pmap != &iso_pmap) {
2444 /* kernel manages this manually for KVM */
2445 KKASSERT(pvpp == NULL);
2446 } else {
2447 KKASSERT(pvpp != NULL);
2448 pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
2449 pvp = pmap_allocpte(pmap, pt_pindex, NULL);
2450 if (isnew)
2451 vm_page_wire_quick(pvp->pv_m);
2452 *pvpp = pvp;
2454 return(pv);
2458 * The kernel never uses managed PT/PD/PDP pages.
2460 KKASSERT(pmap != &kernel_pmap);
2463 * Non-terminal PVs allocate a VM page to represent the page table,
2464 * so we have to resolve pvp and calculate ptepindex for the pvp
2465 * and then for the page table entry index in the pvp for
2466 * fall-through.
2468 if (ptepindex < pmap_pd_pindex(0)) {
2470 * pv is PT, pvp is PD
2472 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2473 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2474 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2477 * PT index in PD
2479 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2480 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2481 ispt = 1;
2482 } else if (ptepindex < pmap_pdp_pindex(0)) {
2484 * pv is PD, pvp is PDP
2486 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2487 * the PD.
2489 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2490 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2492 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2493 KKASSERT(pvpp == NULL);
2494 pvp = NULL;
2495 } else {
2496 pvp = pmap_allocpte(pmap, ptepindex, NULL);
2500 * PD index in PDP
2502 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2503 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2504 } else if (ptepindex < pmap_pml4_pindex()) {
2506 * pv is PDP, pvp is the root pml4 table
2508 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2511 * PDP index in PML4
2513 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2514 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2515 } else {
2517 * pv represents the top-level PML4, there is no parent.
2519 pvp = NULL;
2522 if (isnew == 0)
2523 goto notnew;
2526 * (isnew) is TRUE, pv is not terminal.
2528 * (1) Add a wire count to the parent page table (pvp).
2529 * (2) Allocate a VM page for the page table.
2530 * (3) Enter the VM page into the parent page table.
2532 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2534 if (pvp)
2535 vm_page_wire_quick(pvp->pv_m);
2537 for (;;) {
2538 m = vm_page_alloc(NULL, pv->pv_pindex,
2539 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2540 VM_ALLOC_INTERRUPT);
2541 if (m)
2542 break;
2543 vm_wait(0);
2545 vm_page_wire(m); /* wire for mapping in parent */
2546 vm_page_unmanage(m); /* m must be spinunlocked */
2547 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2548 m->valid = VM_PAGE_BITS_ALL;
2550 vm_page_spin_lock(m);
2551 pmap_page_stats_adding(m);
2554 * PGTABLE pv's only exist in the context of the pmap RB tree
2555 * (pmap->pm_pvroot).
2557 #if 0
2558 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2559 #endif
2560 pv->pv_flags |= PV_FLAG_PGTABLE;
2561 pv->pv_m = m;
2562 vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2563 vm_page_spin_unlock(m);
2566 * (isnew) is TRUE, pv is not terminal.
2568 * Wire the page into pvp. Bump the resident_count for the pmap.
2569 * There is no pvp for the top level, address the pm_pml4[] array
2570 * directly.
2572 * If the caller wants the parent we return it, otherwise
2573 * we just put it away.
2575 * No interlock is needed for pte 0 -> non-zero.
2577 * In the situation where *ptep is valid we might have an unmanaged
2578 * page table page shared from another page table which we need to
2579 * unshare before installing our private page table page.
2581 if (pvp) {
2582 v = VM_PAGE_TO_PHYS(m) |
2583 (pmap->pmap_bits[PG_RW_IDX] |
2584 pmap->pmap_bits[PG_V_IDX] |
2585 pmap->pmap_bits[PG_A_IDX]);
2586 if (ptepindex < NUPTE_USER)
2587 v |= pmap->pmap_bits[PG_U_IDX];
2588 if (ptepindex < pmap_pt_pindex(0))
2589 v |= pmap->pmap_bits[PG_M_IDX];
2591 ptep = pv_pte_lookup(pvp, ptepindex);
2592 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2593 ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2594 else
2595 ptep_iso = NULL;
2596 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2597 pt_entry_t pte;
2599 if (ispt == 0) {
2600 panic("pmap_allocpte: unexpected pte %p/%d",
2601 pvp, (int)ptepindex);
2603 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2604 ptep, v);
2605 if (ptep_iso) {
2606 pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2607 ptep_iso, v);
2609 if (vm_page_unwire_quick(
2610 PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2611 panic("pmap_allocpte: shared pgtable "
2612 "pg bad wirecount");
2614 } else {
2615 pt_entry_t pte;
2617 pte = atomic_swap_long(ptep, v);
2618 if (ptep_iso)
2619 atomic_swap_long(ptep_iso, v);
2620 if (pte != 0) {
2621 kprintf("install pgtbl mixup 0x%016jx "
2622 "old/new 0x%016jx/0x%016jx\n",
2623 (intmax_t)ptepindex, pte, v);
2627 vm_page_wakeup(m);
2630 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2632 notnew:
2633 if (pvp) {
2634 KKASSERT(pvp->pv_m != NULL);
2635 ptep = pv_pte_lookup(pvp, ptepindex);
2636 v = VM_PAGE_TO_PHYS(pv->pv_m) |
2637 (pmap->pmap_bits[PG_RW_IDX] |
2638 pmap->pmap_bits[PG_V_IDX] |
2639 pmap->pmap_bits[PG_A_IDX]);
2640 if (ptepindex < NUPTE_USER)
2641 v |= pmap->pmap_bits[PG_U_IDX];
2642 if (ptepindex < pmap_pt_pindex(0))
2643 v |= pmap->pmap_bits[PG_M_IDX];
2644 if (*ptep != v) {
2645 kprintf("mismatched upper level pt %016jx/%016jx\n",
2646 *ptep, v);
2649 if (pvpp)
2650 *pvpp = pvp;
2651 else if (pvp)
2652 pv_put(pvp);
2653 return (pv);
2657 * This version of pmap_allocpte() checks for possible segment optimizations
2658 * that would allow page-table sharing. It can be called for terminal
2659 * page or page table page ptepindex's.
2661 * The function is called with page table page ptepindex's for fictitious
2662 * and unmanaged terminal pages. That is, we don't want to allocate a
2663 * terminal pv, we just want the pt_pv. pvpp is usually passed as NULL
2664 * for this case.
2666 * This function can return a pv and *pvpp associated with the passed in pmap
2667 * OR a pv and *pvpp associated with the shared pmap. In the latter case
2668 * an unmanaged page table page will be entered into the pass in pmap.
2670 static
2671 pv_entry_t
2672 pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
2673 vm_map_entry_t entry, vm_offset_t va)
2675 vm_object_t object;
2676 pmap_t obpmap;
2677 pmap_t *obpmapp;
2678 vm_pindex_t *pt_placemark;
2679 vm_offset_t b;
2680 pv_entry_t pte_pv; /* in original or shared pmap */
2681 pv_entry_t pt_pv; /* in original or shared pmap */
2682 pv_entry_t proc_pd_pv; /* in original pmap */
2683 pv_entry_t proc_pt_pv; /* in original pmap */
2684 pv_entry_t xpv; /* PT in shared pmap */
2685 pd_entry_t *pt; /* PT entry in PD of original pmap */
2686 pd_entry_t opte; /* contents of *pt */
2687 pd_entry_t npte; /* contents of *pt */
2688 vm_page_t m;
2689 int softhold;
2692 * Basic tests, require a non-NULL vm_map_entry, require proper
2693 * alignment and type for the vm_map_entry, require that the
2694 * underlying object already be allocated.
2696 * We allow almost any type of object to use this optimization.
2697 * The object itself does NOT have to be sized to a multiple of the
2698 * segment size, but the memory mapping does.
2700 * XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
2701 * won't work as expected.
2703 if (entry == NULL ||
2704 pmap_mmu_optimize == 0 || /* not enabled */
2705 (pmap->pm_flags & PMAP_HVM) || /* special pmap */
2706 ptepindex >= pmap_pd_pindex(0) || /* not terminal or pt */
2707 entry->inheritance != VM_INHERIT_SHARE || /* not shared */
2708 entry->maptype != VM_MAPTYPE_NORMAL || /* weird map type */
2709 entry->ba.object == NULL || /* needs VM object */
2710 entry->ba.backing_ba || /* no backing objs */
2711 entry->ba.object->type == OBJT_DEVICE || /* ick */
2712 entry->ba.object->type == OBJT_MGTDEVICE || /* ick */
2713 (entry->ba.offset & SEG_MASK) || /* must be aligned */
2714 (entry->ba.start & SEG_MASK)) {
2715 return(pmap_allocpte(pmap, ptepindex, pvpp));
2719 * Make sure the full segment can be represented.
2721 b = va & ~(vm_offset_t)SEG_MASK;
2722 if (b < entry->ba.start || b + SEG_SIZE > entry->ba.end)
2723 return(pmap_allocpte(pmap, ptepindex, pvpp));
2726 * If the full segment can be represented dive the VM object's
2727 * shared pmap, allocating as required.
2729 object = entry->ba.object;
2731 if (entry->protection & VM_PROT_WRITE)
2732 obpmapp = &object->md.pmap_rw;
2733 else
2734 obpmapp = &object->md.pmap_ro;
2736 #ifdef PMAP_DEBUG2
2737 if (pmap_enter_debug > 0) {
2738 --pmap_enter_debug;
2739 kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
2740 "obpmapp %p %p\n",
2741 va, entry->protection, object,
2742 obpmapp, *obpmapp);
2743 kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
2744 entry, entry->ba.start, entry->ba.end);
2746 #endif
2749 * We allocate what appears to be a normal pmap but because portions
2750 * of this pmap are shared with other unrelated pmaps we have to
2751 * set pm_active to point to all cpus.
2753 * XXX Currently using pmap_spin to interlock the update, can't use
2754 * vm_object_hold/drop because the token might already be held
2755 * shared OR exclusive and we don't know.
2757 while ((obpmap = *obpmapp) == NULL) {
2758 obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
2759 pmap_pinit_simple(obpmap);
2760 pmap_pinit2(obpmap);
2761 spin_lock(&pmap_spin);
2762 if (*obpmapp != NULL) {
2764 * Handle race
2766 spin_unlock(&pmap_spin);
2767 pmap_release(obpmap);
2768 pmap_puninit(obpmap);
2769 kfree(obpmap, M_OBJPMAP);
2770 obpmap = *obpmapp; /* safety */
2771 } else {
2772 obpmap->pm_active = smp_active_mask;
2773 obpmap->pm_flags |= PMAP_SEGSHARED;
2774 *obpmapp = obpmap;
2775 spin_unlock(&pmap_spin);
2780 * Layering is: PTE, PT, PD, PDP, PML4. We have to return the
2781 * pte/pt using the shared pmap from the object but also adjust
2782 * the process pmap's page table page as a side effect.
2786 * Resolve the terminal PTE and PT in the shared pmap. This is what
2787 * we will return. This is true if ptepindex represents a terminal
2788 * page, otherwise pte_pv is actually the PT and pt_pv is actually
2789 * the PD.
2791 pt_pv = NULL;
2792 pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
2793 softhold = 0;
2794 retry:
2795 if (ptepindex >= pmap_pt_pindex(0))
2796 xpv = pte_pv;
2797 else
2798 xpv = pt_pv;
2801 * Resolve the PD in the process pmap so we can properly share the
2802 * page table page. Lock order is bottom-up (leaf first)!
2804 * NOTE: proc_pt_pv can be NULL.
2806 proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b), &pt_placemark);
2807 proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
2808 #ifdef PMAP_DEBUG2
2809 if (pmap_enter_debug > 0) {
2810 --pmap_enter_debug;
2811 kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
2812 proc_pt_pv,
2813 (proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
2814 proc_pd_pv,
2815 va);
2817 #endif
2820 * xpv is the page table page pv from the shared object
2821 * (for convenience), from above.
2823 * Calculate the pte value for the PT to load into the process PD.
2824 * If we have to change it we must properly dispose of the previous
2825 * entry.
2827 pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2828 npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
2829 (pmap->pmap_bits[PG_U_IDX] |
2830 pmap->pmap_bits[PG_RW_IDX] |
2831 pmap->pmap_bits[PG_V_IDX] |
2832 pmap->pmap_bits[PG_A_IDX] |
2833 pmap->pmap_bits[PG_M_IDX]);
2836 * Dispose of previous page table page if it was local to the
2837 * process pmap. If the old pt is not empty we cannot dispose of it
2838 * until we clean it out. This case should not arise very often so
2839 * it is not optimized.
2841 * Leave pt_pv and pte_pv (in our object pmap) locked and intact
2842 * for the retry.
2844 if (proc_pt_pv) {
2845 pmap_inval_bulk_t bulk;
2847 if (proc_pt_pv->pv_m->wire_count != 1) {
2849 * The page table has a bunch of stuff in it
2850 * which we have to scrap.
2852 if (softhold == 0) {
2853 softhold = 1;
2854 pmap_softhold(pmap);
2856 pv_put(proc_pd_pv);
2857 pv_put(proc_pt_pv);
2858 pmap_remove(pmap,
2859 va & ~(vm_offset_t)SEG_MASK,
2860 (va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
2861 } else {
2863 * The page table is empty and can be destroyed.
2864 * However, doing so leaves the pt slot unlocked,
2865 * so we have to loop-up to handle any races until
2866 * we get a NULL proc_pt_pv and a proper pt_placemark.
2868 pmap_inval_bulk_init(&bulk, proc_pt_pv->pv_pmap);
2869 pmap_release_pv(proc_pt_pv, proc_pd_pv, &bulk);
2870 pmap_inval_bulk_flush(&bulk);
2871 pv_put(proc_pd_pv);
2873 goto retry;
2877 * Handle remaining cases. We are holding pt_placemark to lock
2878 * the page table page in the primary pmap while we manipulate
2879 * it.
2881 if (*pt == 0) {
2882 atomic_swap_long(pt, npte);
2883 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2884 vm_page_wire_quick(proc_pd_pv->pv_m); /* proc pd for sh pt */
2885 atomic_add_long(&pmap->pm_stats.resident_count, 1);
2886 } else if (*pt != npte) {
2887 opte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, pt, npte);
2889 #if 0
2890 opte = pte_load_clear(pt);
2891 KKASSERT(opte && opte != npte);
2893 *pt = npte;
2894 #endif
2895 vm_page_wire_quick(xpv->pv_m); /* shared pt -> proc */
2898 * Clean up opte, bump the wire_count for the process
2899 * PD page representing the new entry if it was
2900 * previously empty.
2902 * If the entry was not previously empty and we have
2903 * a PT in the proc pmap then opte must match that
2904 * pt. The proc pt must be retired (this is done
2905 * later on in this procedure).
2907 * NOTE: replacing valid pte, wire_count on proc_pd_pv
2908 * stays the same.
2910 KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
2911 m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
2912 if (vm_page_unwire_quick(m)) {
2913 panic("pmap_allocpte_seg: "
2914 "bad wire count %p",
2919 if (softhold)
2920 pmap_softdone(pmap);
2923 * Remove our earmark on the page table page.
2925 pv_placemarker_wakeup(pmap, pt_placemark);
2928 * The existing process page table was replaced and must be destroyed
2929 * here.
2931 if (proc_pd_pv)
2932 pv_put(proc_pd_pv);
2933 if (pvpp)
2934 *pvpp = pt_pv;
2935 else
2936 pv_put(pt_pv);
2937 return (pte_pv);
2941 * Release any resources held by the given physical map.
2943 * Called when a pmap initialized by pmap_pinit is being released. Should
2944 * only be called if the map contains no valid mappings.
2946 struct pmap_release_info {
2947 pmap_t pmap;
2948 int retry;
2949 pv_entry_t pvp;
2952 static int pmap_release_callback(pv_entry_t pv, void *data);
2954 void
2955 pmap_release(struct pmap *pmap)
2957 struct pmap_release_info info;
2959 KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2960 ("pmap still active! %016jx",
2961 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2964 * There is no longer a pmap_list, if there were we would remove the
2965 * pmap from it here.
2969 * Pull pv's off the RB tree in order from low to high and release
2970 * each page.
2972 info.pmap = pmap;
2973 do {
2974 info.retry = 0;
2975 info.pvp = NULL;
2977 spin_lock(&pmap->pm_spin);
2978 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2979 pmap_release_callback, &info);
2980 spin_unlock(&pmap->pm_spin);
2982 if (info.pvp)
2983 pv_put(info.pvp);
2984 } while (info.retry);
2988 * One resident page (the pml4 page) should remain. Two if
2989 * the pmap has implemented an isolated userland PML4E table.
2990 * No wired pages should remain.
2992 int expected_res = 0;
2994 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2995 ++expected_res;
2996 if (pmap->pm_pmlpv_iso)
2997 ++expected_res;
2999 #if 1
3000 if (pmap->pm_stats.resident_count != expected_res ||
3001 pmap->pm_stats.wired_count != 0) {
3002 kprintf("fatal pmap problem - pmap %p flags %08x "
3003 "rescnt=%jd wirecnt=%jd\n",
3004 pmap,
3005 pmap->pm_flags,
3006 pmap->pm_stats.resident_count,
3007 pmap->pm_stats.wired_count);
3008 tsleep(pmap, 0, "DEAD", 0);
3010 #else
3011 KKASSERT(pmap->pm_stats.resident_count == expected_res);
3012 KKASSERT(pmap->pm_stats.wired_count == 0);
3013 #endif
3017 * Called from low to high. We must cache the proper parent pv so we
3018 * can adjust its wired count.
3020 static int
3021 pmap_release_callback(pv_entry_t pv, void *data)
3023 struct pmap_release_info *info = data;
3024 pmap_t pmap = info->pmap;
3025 vm_pindex_t pindex;
3026 int r;
3029 * Acquire a held and locked pv, check for release race
3031 pindex = pv->pv_pindex;
3032 if (info->pvp == pv) {
3033 spin_unlock(&pmap->pm_spin);
3034 info->pvp = NULL;
3035 } else if (pv_hold_try(pv)) {
3036 spin_unlock(&pmap->pm_spin);
3037 } else {
3038 spin_unlock(&pmap->pm_spin);
3039 pv_lock(pv);
3040 pv_put(pv);
3041 info->retry = 1;
3042 spin_lock(&pmap->pm_spin);
3044 return -1;
3046 KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
3048 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3050 * I am PTE, parent is PT
3052 pindex = pv->pv_pindex >> NPTEPGSHIFT;
3053 pindex += NUPTE_TOTAL;
3054 } else if (pv->pv_pindex < pmap_pd_pindex(0)) {
3056 * I am PT, parent is PD
3058 pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
3059 pindex += NUPTE_TOTAL + NUPT_TOTAL;
3060 } else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
3062 * I am PD, parent is PDP
3064 pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
3065 NPDPEPGSHIFT;
3066 pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
3067 } else if (pv->pv_pindex < pmap_pml4_pindex()) {
3069 * I am PDP, parent is PML4. We always calculate the
3070 * normal PML4 here, not the isolated PML4.
3072 pindex = pmap_pml4_pindex();
3073 } else {
3075 * parent is NULL
3077 if (info->pvp) {
3078 pv_put(info->pvp);
3079 info->pvp = NULL;
3081 pindex = 0;
3083 if (pindex) {
3084 if (info->pvp && info->pvp->pv_pindex != pindex) {
3085 pv_put(info->pvp);
3086 info->pvp = NULL;
3088 if (info->pvp == NULL)
3089 info->pvp = pv_get(pmap, pindex, NULL);
3090 } else {
3091 if (info->pvp) {
3092 pv_put(info->pvp);
3093 info->pvp = NULL;
3096 r = pmap_release_pv(pv, info->pvp, NULL);
3097 spin_lock(&pmap->pm_spin);
3099 return(r);
3103 * Called with held (i.e. also locked) pv. This function will dispose of
3104 * the lock along with the pv.
3106 * If the caller already holds the locked parent page table for pv it
3107 * must pass it as pvp, allowing us to avoid a deadlock, else it can
3108 * pass NULL for pvp.
3110 static int
3111 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
3113 vm_page_t p;
3116 * The pmap is currently not spinlocked, pv is held+locked.
3117 * Remove the pv's page from its parent's page table. The
3118 * parent's page table page's wire_count will be decremented.
3120 * This will clean out the pte at any level of the page table.
3121 * If smp != 0 all cpus are affected.
3123 * Do not tear-down recursively, its faster to just let the
3124 * release run its course.
3126 pmap_remove_pv_pte(pv, pvp, bulk, 0);
3129 * Terminal pvs are unhooked from their vm_pages. Because
3130 * terminal pages aren't page table pages they aren't wired
3131 * by us, so we have to be sure not to unwire them either.
3133 if (pv->pv_pindex < pmap_pt_pindex(0)) {
3134 pmap_remove_pv_page(pv);
3135 goto skip;
3139 * We leave the top-level page table page cached, wired, and
3140 * mapped in the pmap until the dtor function (pmap_puninit())
3141 * gets called.
3143 * Since we are leaving the top-level pv intact we need
3144 * to break out of what would otherwise be an infinite loop.
3146 * This covers both the normal and the isolated PML4 page.
3148 if (pv->pv_pindex >= pmap_pml4_pindex()) {
3149 pv_put(pv);
3150 return(-1);
3154 * For page table pages (other than the top-level page),
3155 * remove and free the vm_page. The representitive mapping
3156 * removed above by pmap_remove_pv_pte() did not undo the
3157 * last wire_count so we have to do that as well.
3159 p = pmap_remove_pv_page(pv);
3160 vm_page_busy_wait(p, FALSE, "pmaprl");
3161 if (p->wire_count != 1) {
3162 kprintf("p->wire_count was %016lx %d\n",
3163 pv->pv_pindex, p->wire_count);
3165 KKASSERT(p->wire_count == 1);
3166 KKASSERT(p->flags & PG_UNMANAGED);
3168 vm_page_unwire(p, 0);
3169 KKASSERT(p->wire_count == 0);
3171 vm_page_free(p);
3172 skip:
3173 pv_free(pv, pvp);
3175 return 0;
3179 * This function will remove the pte associated with a pv from its parent.
3180 * Terminal pv's are supported. All cpus specified by (bulk) are properly
3181 * invalidated.
3183 * The wire count will be dropped on the parent page table. The wire
3184 * count on the page being removed (pv->pv_m) from the parent page table
3185 * is NOT touched. Note that terminal pages will not have any additional
3186 * wire counts while page table pages will have at least one representing
3187 * the mapping, plus others representing sub-mappings.
3189 * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3190 * pages and user page table and terminal pages.
3192 * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3193 * be freshly allocated and not imply that the pte is managed. In this
3194 * case pv->pv_m should be NULL.
3196 * The pv must be locked. The pvp, if supplied, must be locked. All
3197 * supplied pv's will remain locked on return.
3199 * XXX must lock parent pv's if they exist to remove pte XXX
3201 static
3202 void
3203 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3204 int destroy)
3206 vm_pindex_t ptepindex = pv->pv_pindex;
3207 pmap_t pmap = pv->pv_pmap;
3208 vm_page_t p;
3209 int gotpvp = 0;
3211 KKASSERT(pmap);
3213 if (ptepindex >= pmap_pml4_pindex()) {
3215 * We are the top level PML4E table, there is no parent.
3217 * This is either the normal or isolated PML4E table.
3218 * Only the normal is used in regular operation, the isolated
3219 * is only passed in when breaking down the whole pmap.
3221 p = pmap->pm_pmlpv->pv_m;
3222 KKASSERT(pv->pv_m == p); /* debugging */
3223 } else if (ptepindex >= pmap_pdp_pindex(0)) {
3225 * Remove a PDP page from the PML4E. This can only occur
3226 * with user page tables. We do not have to lock the
3227 * pml4 PV so just ignore pvp.
3229 vm_pindex_t pml4_pindex;
3230 vm_pindex_t pdp_index;
3231 pml4_entry_t *pdp;
3232 pml4_entry_t *pdp_iso;
3234 pdp_index = ptepindex - pmap_pdp_pindex(0);
3235 if (pvp == NULL) {
3236 pml4_pindex = pmap_pml4_pindex();
3237 pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3238 KKASSERT(pvp);
3239 gotpvp = 1;
3242 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3243 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3244 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3245 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3248 * Also remove the PDP from the isolated PML4E if the
3249 * process uses one.
3251 if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3252 pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3253 ((1ul << NPML4EPGSHIFT) - 1)];
3254 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3256 KKASSERT(pv->pv_m == p); /* debugging */
3257 } else if (ptepindex >= pmap_pd_pindex(0)) {
3259 * Remove a PD page from the PDP
3261 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3262 * of a simple pmap because it stops at
3263 * the PD page.
3265 vm_pindex_t pdp_pindex;
3266 vm_pindex_t pd_index;
3267 pdp_entry_t *pd;
3269 pd_index = ptepindex - pmap_pd_pindex(0);
3271 if (pvp == NULL) {
3272 pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3273 (pd_index >> NPML4EPGSHIFT);
3274 pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3275 gotpvp = 1;
3278 if (pvp) {
3279 pd = pv_pte_lookup(pvp, pd_index &
3280 ((1ul << NPDPEPGSHIFT) - 1));
3281 KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3282 p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3283 pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3284 } else {
3285 KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3286 p = pv->pv_m; /* degenerate test later */
3288 KKASSERT(pv->pv_m == p); /* debugging */
3289 } else if (ptepindex >= pmap_pt_pindex(0)) {
3291 * Remove a PT page from the PD
3293 vm_pindex_t pd_pindex;
3294 vm_pindex_t pt_index;
3295 pd_entry_t *pt;
3297 pt_index = ptepindex - pmap_pt_pindex(0);
3299 if (pvp == NULL) {
3300 pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3301 (pt_index >> NPDPEPGSHIFT);
3302 pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3303 KKASSERT(pvp);
3304 gotpvp = 1;
3307 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3308 #if 0
3309 KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3310 ("*pt unexpectedly invalid %016jx "
3311 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3312 *pt, gotpvp, ptepindex, pt_index, pv, pvp));
3313 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3314 #else
3315 if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3316 kprintf("*pt unexpectedly invalid %016jx "
3317 "gotpvp=%d ptepindex=%ld ptindex=%ld "
3318 "pv=%p pvp=%p\n",
3319 *pt, gotpvp, ptepindex, pt_index, pv, pvp);
3320 tsleep(pt, 0, "DEAD", 0);
3321 p = pv->pv_m;
3322 } else {
3323 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3325 #endif
3326 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3327 KKASSERT(pv->pv_m == p); /* debugging */
3328 } else {
3330 * Remove a PTE from the PT page. The PV might exist even if
3331 * the PTE is not managed, in whichcase pv->pv_m should be
3332 * NULL.
3334 * NOTE: Userland pmaps manage the parent PT/PD/PDP page
3335 * table pages but the kernel_pmap does not.
3337 * NOTE: pv's must be locked bottom-up to avoid deadlocking.
3338 * pv is a pte_pv so we can safely lock pt_pv.
3340 * NOTE: FICTITIOUS pages may have multiple physical mappings
3341 * so PHYS_TO_VM_PAGE() will not necessarily work for
3342 * terminal ptes.
3344 vm_pindex_t pt_pindex;
3345 pt_entry_t *ptep;
3346 pt_entry_t pte;
3347 vm_offset_t va;
3349 pt_pindex = ptepindex >> NPTEPGSHIFT;
3350 va = (vm_offset_t)ptepindex << PAGE_SHIFT;
3352 if (ptepindex >= NUPTE_USER) {
3353 ptep = vtopte(ptepindex << PAGE_SHIFT);
3354 KKASSERT(pvp == NULL);
3355 /* pvp remains NULL */
3356 } else {
3357 if (pvp == NULL) {
3358 pt_pindex = NUPTE_TOTAL +
3359 (ptepindex >> NPDPEPGSHIFT);
3360 pvp = pv_get(pv->pv_pmap, pt_pindex, NULL);
3361 KKASSERT(pvp);
3362 gotpvp = 1;
3364 ptep = pv_pte_lookup(pvp, ptepindex &
3365 ((1ul << NPDPEPGSHIFT) - 1));
3367 pte = pmap_inval_bulk(bulk, va, ptep, 0);
3368 if (bulk == NULL) /* XXX */
3369 cpu_invlpg((void *)va); /* XXX */
3372 * Now update the vm_page_t
3374 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3375 (pte & pmap->pmap_bits[PG_V_IDX])) {
3377 * Valid managed page, adjust (p).
3379 if (pte & pmap->pmap_bits[PG_DEVICE_IDX]) {
3380 p = pv->pv_m;
3381 } else {
3382 p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3383 KKASSERT(pv->pv_m == p);
3385 if (pte & pmap->pmap_bits[PG_M_IDX]) {
3386 if (pmap_track_modified(ptepindex))
3387 vm_page_dirty(p);
3389 if (pte & pmap->pmap_bits[PG_A_IDX]) {
3390 vm_page_flag_set(p, PG_REFERENCED);
3392 } else {
3394 * Unmanaged page, do not try to adjust the vm_page_t.
3395 * pv could be freshly allocated for a pmap_enter(),
3396 * replacing an unmanaged page with a managed one.
3398 * pv->pv_m might reflect the new page and not the
3399 * existing page.
3401 * We could extract p from the physical address and
3402 * adjust it but we explicitly do not for unmanaged
3403 * pages.
3405 p = NULL;
3407 if (pte & pmap->pmap_bits[PG_W_IDX])
3408 atomic_add_long(&pmap->pm_stats.wired_count, -1);
3409 if (pte & pmap->pmap_bits[PG_G_IDX])
3410 cpu_invlpg((void *)va);
3414 * If requested, scrap the underlying pv->pv_m and the underlying
3415 * pv. If this is a page-table-page we must also free the page.
3417 * pvp must be returned locked.
3419 if (destroy == 1) {
3421 * page table page (PT, PD, PDP, PML4), caller was responsible
3422 * for testing wired_count.
3424 KKASSERT(pv->pv_m->wire_count == 1);
3425 p = pmap_remove_pv_page(pv);
3426 pv_free(pv, pvp);
3427 pv = NULL;
3429 vm_page_busy_wait(p, FALSE, "pgpun");
3430 vm_page_unwire(p, 0);
3431 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3432 vm_page_free(p);
3433 } else if (destroy == 2) {
3435 * Normal page, remove from pmap and leave the underlying
3436 * page untouched.
3438 pmap_remove_pv_page(pv);
3439 pv_free(pv, pvp);
3440 pv = NULL; /* safety */
3444 * If we acquired pvp ourselves then we are responsible for
3445 * recursively deleting it.
3447 if (pvp && gotpvp) {
3449 * Recursively destroy higher-level page tables.
3451 * This is optional. If we do not, they will still
3452 * be destroyed when the process exits.
3454 * NOTE: Do not destroy pv_entry's with extra hold refs,
3455 * a caller may have unlocked it and intends to
3456 * continue to use it.
3458 if (pmap_dynamic_delete &&
3459 pvp->pv_m &&
3460 pvp->pv_m->wire_count == 1 &&
3461 (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3462 pvp->pv_pindex < pmap_pml4_pindex()) {
3463 if (pmap_dynamic_delete == 2)
3464 kprintf("A %jd %08x\n", pvp->pv_pindex, pvp->pv_hold);
3465 if (pmap != &kernel_pmap) {
3466 pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3467 pvp = NULL; /* safety */
3468 } else {
3469 kprintf("Attempt to remove kernel_pmap pindex "
3470 "%jd\n", pvp->pv_pindex);
3471 pv_put(pvp);
3473 } else {
3474 pv_put(pvp);
3480 * Remove the vm_page association to a pv. The pv must be locked.
3482 static
3483 vm_page_t
3484 pmap_remove_pv_page(pv_entry_t pv)
3486 vm_page_t m;
3488 m = pv->pv_m;
3489 vm_page_spin_lock(m);
3490 KKASSERT(m && m == pv->pv_m);
3491 pv->pv_m = NULL;
3492 if (pv->pv_flags & PV_FLAG_PGTABLE) {
3493 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3494 KKASSERT(TAILQ_EMPTY(&m->md.pv_list));
3495 } else {
3496 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3498 #if 1
3499 if (TAILQ_EMPTY(&m->md.pv_list))
3500 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3501 #else
3503 * For normal pages, an empty pv_list does not necessarily
3504 * mean that the page is no longer mapped. It might still
3505 * be mapped via an extent through its object.
3507 * However, if m->object is NULL, or the object has not
3508 * extents, then we can clear the bits.
3510 if (TAILQ_EMPTY(&m->md.pv_list) &&
3511 (m->object == NULL ||
3512 TAILQ_EMPTY(&m->object->backing_list))) {
3513 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3515 #endif
3517 pmap_page_stats_deleting(m);
3518 vm_page_spin_unlock(m);
3520 return(m);
3524 * Grow the number of kernel page table entries, if needed.
3526 * This routine is always called to validate any address space
3527 * beyond KERNBASE (for kldloads). kernel_vm_end only governs the address
3528 * space below KERNBASE.
3530 * kernel_map must be locked exclusively by the caller.
3532 void
3533 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3535 vm_paddr_t paddr;
3536 vm_offset_t ptppaddr;
3537 vm_page_t nkpg;
3538 pd_entry_t *pt, newpt;
3539 pdp_entry_t *pd, newpd;
3540 int update_kernel_vm_end;
3543 * bootstrap kernel_vm_end on first real VM use
3545 if (kernel_vm_end == 0) {
3546 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3548 for (;;) {
3549 pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3550 if (pt == NULL)
3551 break;
3552 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3553 break;
3554 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3555 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3556 if (kernel_vm_end - 1 >= vm_map_max(&kernel_map)) {
3557 kernel_vm_end = vm_map_max(&kernel_map);
3558 break;
3564 * Fill in the gaps. kernel_vm_end is only adjusted for ranges
3565 * below KERNBASE. Ranges above KERNBASE are kldloaded and we
3566 * do not want to force-fill 128G worth of page tables.
3568 if (kstart < KERNBASE) {
3569 if (kstart > kernel_vm_end)
3570 kstart = kernel_vm_end;
3571 KKASSERT(kend <= KERNBASE);
3572 update_kernel_vm_end = 1;
3573 } else {
3574 update_kernel_vm_end = 0;
3577 kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3578 kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3580 if (kend - 1 >= vm_map_max(&kernel_map))
3581 kend = vm_map_max(&kernel_map);
3583 while (kstart < kend) {
3584 pt = pmap_pt(&kernel_pmap, kstart);
3585 if (pt == NULL) {
3587 * We need a new PD entry
3589 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3590 VM_ALLOC_NORMAL |
3591 VM_ALLOC_SYSTEM |
3592 VM_ALLOC_INTERRUPT);
3593 if (nkpg == NULL) {
3594 panic("pmap_growkernel: no memory to grow "
3595 "kernel");
3597 paddr = VM_PAGE_TO_PHYS(nkpg);
3598 pmap_zero_page(paddr);
3599 pd = pmap_pd(&kernel_pmap, kstart);
3601 newpd = (pdp_entry_t)
3602 (paddr |
3603 kernel_pmap.pmap_bits[PG_V_IDX] |
3604 kernel_pmap.pmap_bits[PG_RW_IDX] |
3605 kernel_pmap.pmap_bits[PG_A_IDX]);
3606 atomic_swap_long(pd, newpd);
3608 #if 0
3609 kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3610 pd, newpd, paddr);
3611 #endif
3613 continue; /* try again */
3616 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3617 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3618 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3619 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3620 kstart = vm_map_max(&kernel_map);
3621 break;
3623 continue;
3627 * We need a new PT
3629 * This index is bogus, but out of the way
3631 nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3632 VM_ALLOC_NORMAL |
3633 VM_ALLOC_SYSTEM |
3634 VM_ALLOC_INTERRUPT);
3635 if (nkpg == NULL)
3636 panic("pmap_growkernel: no memory to grow kernel");
3638 vm_page_wire(nkpg);
3639 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3640 pmap_zero_page(ptppaddr);
3641 newpt = (pd_entry_t)(ptppaddr |
3642 kernel_pmap.pmap_bits[PG_V_IDX] |
3643 kernel_pmap.pmap_bits[PG_RW_IDX] |
3644 kernel_pmap.pmap_bits[PG_A_IDX]);
3645 atomic_swap_long(pt, newpt);
3647 kstart = (kstart + PAGE_SIZE * NPTEPG) &
3648 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3650 if (kstart - 1 >= vm_map_max(&kernel_map)) {
3651 kstart = vm_map_max(&kernel_map);
3652 break;
3657 * Only update kernel_vm_end for areas below KERNBASE.
3659 if (update_kernel_vm_end && kernel_vm_end < kstart)
3660 kernel_vm_end = kstart;
3664 * Add a reference to the specified pmap.
3666 void
3667 pmap_reference(pmap_t pmap)
3669 if (pmap != NULL)
3670 atomic_add_int(&pmap->pm_count, 1);
3673 /***************************************************
3674 * page management routines.
3675 ***************************************************/
3678 * Hold a pv without locking it
3680 static void
3681 pv_hold(pv_entry_t pv)
3683 atomic_add_int(&pv->pv_hold, 1);
3687 * Hold a pv_entry, preventing its destruction. TRUE is returned if the pv
3688 * was successfully locked, FALSE if it wasn't. The caller must dispose of
3689 * the pv properly.
3691 * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3692 * pv list via its page) must be held by the caller in order to stabilize
3693 * the pv.
3695 static int
3696 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3698 u_int count;
3701 * Critical path shortcut expects pv to already have one ref
3702 * (for the pv->pv_pmap).
3704 count = pv->pv_hold;
3705 cpu_ccfence();
3706 for (;;) {
3707 if ((count & PV_HOLD_LOCKED) == 0) {
3708 if (atomic_fcmpset_int(&pv->pv_hold, &count,
3709 (count + 1) | PV_HOLD_LOCKED)) {
3710 #ifdef PMAP_DEBUG
3711 pv->pv_func = func;
3712 pv->pv_line = lineno;
3713 #endif
3714 return TRUE;
3716 } else {
3717 if (atomic_fcmpset_int(&pv->pv_hold, &count, count + 1))
3718 return FALSE;
3720 /* retry */
3725 * Drop a previously held pv_entry which could not be locked, allowing its
3726 * destruction.
3728 * Must not be called with a spinlock held as we might zfree() the pv if it
3729 * is no longer associated with a pmap and this was the last hold count.
3731 static void
3732 pv_drop(pv_entry_t pv)
3734 u_int count;
3736 for (;;) {
3737 count = pv->pv_hold;
3738 cpu_ccfence();
3739 KKASSERT((count & PV_HOLD_MASK) > 0);
3740 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3741 (PV_HOLD_LOCKED | 1));
3742 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3743 if ((count & PV_HOLD_MASK) == 1) {
3744 #ifdef PMAP_DEBUG2
3745 if (pmap_enter_debug > 0) {
3746 --pmap_enter_debug;
3747 kprintf("pv_drop: free pv %p\n", pv);
3749 #endif
3750 KKASSERT(count == 1);
3751 KKASSERT(pv->pv_pmap == NULL);
3752 zfree(pvzone, pv);
3754 return;
3756 /* retry */
3761 * Find or allocate the requested PV entry, returning a locked, held pv.
3763 * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3764 * for the caller and one representing the pmap and vm_page association.
3766 * If (*isnew) is zero, the returned pv will have only one hold count.
3768 * Since both associations can only be adjusted while the pv is locked,
3769 * together they represent just one additional hold.
3771 static
3772 pv_entry_t
3773 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3775 struct mdglobaldata *md = mdcpu;
3776 pv_entry_t pv;
3777 pv_entry_t pnew;
3778 int pmap_excl = 0;
3780 pnew = NULL;
3781 if (md->gd_newpv) {
3782 #if 1
3783 pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3784 #else
3785 crit_enter();
3786 pnew = md->gd_newpv; /* might race NULL */
3787 md->gd_newpv = NULL;
3788 crit_exit();
3789 #endif
3791 if (pnew == NULL)
3792 pnew = zalloc(pvzone);
3794 spin_lock_shared(&pmap->pm_spin);
3795 for (;;) {
3797 * Shortcut cache
3799 pv = pv_entry_lookup(pmap, pindex);
3800 if (pv == NULL) {
3801 vm_pindex_t *pmark;
3804 * Requires exclusive pmap spinlock
3806 if (pmap_excl == 0) {
3807 pmap_excl = 1;
3808 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3809 spin_unlock_shared(&pmap->pm_spin);
3810 spin_lock(&pmap->pm_spin);
3811 continue;
3816 * We need to block if someone is holding our
3817 * placemarker. As long as we determine the
3818 * placemarker has not been aquired we do not
3819 * need to get it as acquision also requires
3820 * the pmap spin lock.
3822 * However, we can race the wakeup.
3824 pmark = pmap_placemarker_hash(pmap, pindex);
3826 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3827 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3828 tsleep_interlock(pmark, 0);
3829 if (((*pmark ^ pindex) &
3830 ~PM_PLACEMARK_WAKEUP) == 0) {
3831 spin_unlock(&pmap->pm_spin);
3832 tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3833 spin_lock(&pmap->pm_spin);
3835 continue;
3839 * Setup the new entry
3841 pnew->pv_pmap = pmap;
3842 pnew->pv_pindex = pindex;
3843 pnew->pv_hold = PV_HOLD_LOCKED | 2;
3844 pnew->pv_flags = 0;
3845 #ifdef PMAP_DEBUG
3846 pnew->pv_func = func;
3847 pnew->pv_line = lineno;
3848 if (pnew->pv_line_lastfree > 0) {
3849 pnew->pv_line_lastfree =
3850 -pnew->pv_line_lastfree;
3852 #endif
3853 pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3854 atomic_add_long(&pmap->pm_stats.resident_count, 1);
3855 spin_unlock(&pmap->pm_spin);
3856 *isnew = 1;
3858 KASSERT(pv == NULL, ("pv insert failed %p->%p", pnew, pv));
3859 return(pnew);
3863 * We already have an entry, cleanup the staged pnew if
3864 * we can get the lock, otherwise block and retry.
3866 if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3867 if (pmap_excl)
3868 spin_unlock(&pmap->pm_spin);
3869 else
3870 spin_unlock_shared(&pmap->pm_spin);
3871 #if 1
3872 pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3873 if (pnew)
3874 zfree(pvzone, pnew);
3875 #else
3876 crit_enter();
3877 if (md->gd_newpv == NULL)
3878 md->gd_newpv = pnew;
3879 else
3880 zfree(pvzone, pnew);
3881 crit_exit();
3882 #endif
3883 KKASSERT(pv->pv_pmap == pmap &&
3884 pv->pv_pindex == pindex);
3885 *isnew = 0;
3886 return(pv);
3888 if (pmap_excl) {
3889 spin_unlock(&pmap->pm_spin);
3890 _pv_lock(pv PMAP_DEBUG_COPY);
3891 pv_put(pv);
3892 spin_lock(&pmap->pm_spin);
3893 } else {
3894 spin_unlock_shared(&pmap->pm_spin);
3895 _pv_lock(pv PMAP_DEBUG_COPY);
3896 pv_put(pv);
3897 spin_lock_shared(&pmap->pm_spin);
3900 /* NOT REACHED */
3904 * Find the requested PV entry, returning a locked+held pv or NULL
3906 static
3907 pv_entry_t
3908 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3910 pv_entry_t pv;
3911 int pmap_excl = 0;
3913 spin_lock_shared(&pmap->pm_spin);
3914 for (;;) {
3916 * Shortcut cache
3918 pv = pv_entry_lookup(pmap, pindex);
3919 if (pv == NULL) {
3921 * Block if there is ANY placemarker. If we are to
3922 * return it, we must also aquire the spot, so we
3923 * have to block even if the placemarker is held on
3924 * a different address.
3926 * OPTIMIZATION: If pmarkp is passed as NULL the
3927 * caller is just probing (or looking for a real
3928 * pv_entry), and in this case we only need to check
3929 * to see if the placemarker matches pindex.
3931 vm_pindex_t *pmark;
3934 * Requires exclusive pmap spinlock
3936 if (pmap_excl == 0) {
3937 pmap_excl = 1;
3938 if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3939 spin_unlock_shared(&pmap->pm_spin);
3940 spin_lock(&pmap->pm_spin);
3941 continue;
3945 pmark = pmap_placemarker_hash(pmap, pindex);
3947 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3948 ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3949 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3950 tsleep_interlock(pmark, 0);
3951 if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3952 ((*pmark ^ pindex) &
3953 ~PM_PLACEMARK_WAKEUP) == 0) {
3954 spin_unlock(&pmap->pm_spin);
3955 tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3956 spin_lock(&pmap->pm_spin);
3958 continue;
3960 if (pmarkp) {
3961 if (atomic_swap_long(pmark, pindex) !=
3962 PM_NOPLACEMARK) {
3963 panic("_pv_get: pmark race");
3965 *pmarkp = pmark;
3967 spin_unlock(&pmap->pm_spin);
3968 return NULL;
3970 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3971 if (pmap_excl)
3972 spin_unlock(&pmap->pm_spin);
3973 else
3974 spin_unlock_shared(&pmap->pm_spin);
3975 KKASSERT(pv->pv_pmap == pmap &&
3976 pv->pv_pindex == pindex);
3977 return(pv);
3979 if (pmap_excl) {
3980 spin_unlock(&pmap->pm_spin);
3981 _pv_lock(pv PMAP_DEBUG_COPY);
3982 pv_put(pv);
3983 spin_lock(&pmap->pm_spin);
3984 } else {
3985 spin_unlock_shared(&pmap->pm_spin);
3986 _pv_lock(pv PMAP_DEBUG_COPY);
3987 pv_put(pv);
3988 spin_lock_shared(&pmap->pm_spin);
3994 * Lookup, hold, and attempt to lock (pmap,pindex).
3996 * If the entry does not exist NULL is returned and *errorp is set to 0
3998 * If the entry exists and could be successfully locked it is returned and
3999 * errorp is set to 0.
4001 * If the entry exists but could NOT be successfully locked it is returned
4002 * held and *errorp is set to 1.
4004 * If the entry is placemarked by someone else NULL is returned and *errorp
4005 * is set to 1.
4007 static
4008 pv_entry_t
4009 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
4011 pv_entry_t pv;
4013 spin_lock_shared(&pmap->pm_spin);
4015 pv = pv_entry_lookup(pmap, pindex);
4016 if (pv == NULL) {
4017 vm_pindex_t *pmark;
4019 pmark = pmap_placemarker_hash(pmap, pindex);
4021 if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
4022 *errorp = 1;
4023 } else if (pmarkp &&
4024 atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
4025 *errorp = 0;
4026 } else {
4028 * Can't set a placemark with a NULL pmarkp, or if
4029 * pmarkp is non-NULL but we failed to set our
4030 * placemark.
4032 *errorp = 1;
4034 if (pmarkp)
4035 *pmarkp = pmark;
4036 spin_unlock_shared(&pmap->pm_spin);
4038 return NULL;
4042 * XXX This has problems if the lock is shared, why?
4044 if (pv_hold_try(pv)) {
4045 spin_unlock_shared(&pmap->pm_spin);
4046 *errorp = 0;
4047 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
4048 return(pv); /* lock succeeded */
4050 spin_unlock_shared(&pmap->pm_spin);
4051 *errorp = 1;
4053 return (pv); /* lock failed */
4057 * Lock a held pv, keeping the hold count
4059 static
4060 void
4061 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
4063 u_int count;
4065 for (;;) {
4066 count = pv->pv_hold;
4067 cpu_ccfence();
4068 if ((count & PV_HOLD_LOCKED) == 0) {
4069 if (atomic_cmpset_int(&pv->pv_hold, count,
4070 count | PV_HOLD_LOCKED)) {
4071 #ifdef PMAP_DEBUG
4072 pv->pv_func = func;
4073 pv->pv_line = lineno;
4074 #endif
4075 return;
4077 continue;
4079 tsleep_interlock(pv, 0);
4080 if (atomic_cmpset_int(&pv->pv_hold, count,
4081 count | PV_HOLD_WAITING)) {
4082 #ifdef PMAP_DEBUG2
4083 if (pmap_enter_debug > 0) {
4084 --pmap_enter_debug;
4085 kprintf("pv waiting on %s:%d\n",
4086 pv->pv_func, pv->pv_line);
4088 #endif
4089 tsleep(pv, PINTERLOCKED, "pvwait", hz);
4091 /* retry */
4096 * Unlock a held and locked pv, keeping the hold count.
4098 static
4099 void
4100 pv_unlock(pv_entry_t pv)
4102 u_int count;
4104 for (;;) {
4105 count = pv->pv_hold;
4106 cpu_ccfence();
4107 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
4108 (PV_HOLD_LOCKED | 1));
4109 if (atomic_cmpset_int(&pv->pv_hold, count,
4110 count &
4111 ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
4112 if (count & PV_HOLD_WAITING)
4113 wakeup(pv);
4114 break;
4120 * Unlock and drop a pv. If the pv is no longer associated with a pmap
4121 * and the hold count drops to zero we will free it.
4123 * Caller should not hold any spin locks. We are protected from hold races
4124 * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
4125 * lock held. A pv cannot be located otherwise.
4127 static
4128 void
4129 pv_put(pv_entry_t pv)
4131 #ifdef PMAP_DEBUG2
4132 if (pmap_enter_debug > 0) {
4133 --pmap_enter_debug;
4134 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
4136 #endif
4139 * Normal put-aways must have a pv_m associated with the pv,
4140 * but allow the case where the pv has been destructed due
4141 * to pmap_dynamic_delete.
4143 KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
4146 * Fast - shortcut most common condition
4148 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
4149 return;
4152 * Slow
4154 pv_unlock(pv);
4155 pv_drop(pv);
4159 * Remove the pmap association from a pv, require that pv_m already be removed,
4160 * then unlock and drop the pv. Any pte operations must have already been
4161 * completed. This call may result in a last-drop which will physically free
4162 * the pv.
4164 * Removing the pmap association entails an additional drop.
4166 * pv must be exclusively locked on call and will be disposed of on return.
4168 static
4169 void
4170 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
4172 pmap_t pmap;
4174 #ifdef PMAP_DEBUG
4175 pv->pv_func_lastfree = func;
4176 pv->pv_line_lastfree = lineno;
4177 #endif
4178 KKASSERT(pv->pv_m == NULL);
4179 KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
4180 (PV_HOLD_LOCKED|1));
4181 if ((pmap = pv->pv_pmap) != NULL) {
4182 spin_lock(&pmap->pm_spin);
4183 KKASSERT(pv->pv_pmap == pmap);
4184 if (pmap->pm_pvhint_pt == pv)
4185 pmap->pm_pvhint_pt = NULL;
4186 if (pmap->pm_pvhint_pte == pv)
4187 pmap->pm_pvhint_pte = NULL;
4188 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
4189 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4190 pv->pv_pmap = NULL;
4191 pv->pv_pindex = 0;
4192 spin_unlock(&pmap->pm_spin);
4195 * Try to shortcut three atomic ops, otherwise fall through
4196 * and do it normally. Drop two refs and the lock all in
4197 * one go.
4199 if (pvp)
4200 vm_page_unwire_quick(pvp->pv_m);
4201 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
4202 #ifdef PMAP_DEBUG2
4203 if (pmap_enter_debug > 0) {
4204 --pmap_enter_debug;
4205 kprintf("pv_free: free pv %p\n", pv);
4207 #endif
4208 zfree(pvzone, pv);
4209 return;
4211 pv_drop(pv); /* ref for pv_pmap */
4213 pv_unlock(pv);
4214 pv_drop(pv);
4218 * This routine is very drastic, but can save the system
4219 * in a pinch.
4221 void
4222 pmap_collect(void)
4224 int i;
4225 vm_page_t m;
4226 static int warningdone=0;
4228 if (pmap_pagedaemon_waken == 0)
4229 return;
4230 pmap_pagedaemon_waken = 0;
4231 if (warningdone < 5) {
4232 kprintf("pmap_collect: collecting pv entries -- "
4233 "suggest increasing PMAP_SHPGPERPROC\n");
4234 warningdone++;
4237 for (i = 0; i < vm_page_array_size; i++) {
4238 m = &vm_page_array[i];
4239 if (m->wire_count || m->hold_count)
4240 continue;
4241 if (vm_page_busy_try(m, TRUE) == 0) {
4242 if (m->wire_count == 0 && m->hold_count == 0) {
4243 pmap_remove_all(m);
4245 vm_page_wakeup(m);
4251 * Scan the pmap for active page table entries and issue a callback.
4252 * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4253 * its parent page table.
4255 * pte_pv will be NULL if the page or page table is unmanaged.
4256 * pt_pv will point to the page table page containing the pte for the page.
4258 * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4259 * we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4260 * process pmap's PD and page to the callback function. This can be
4261 * confusing because the pt_pv is really a pd_pv, and the target page
4262 * table page is simply aliased by the pmap and not owned by it.
4264 * It is assumed that the start and end are properly rounded to the page size.
4266 * It is assumed that PD pages and above are managed and thus in the RB tree,
4267 * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4269 struct pmap_scan_info {
4270 struct pmap *pmap;
4271 vm_offset_t sva;
4272 vm_offset_t eva;
4273 vm_pindex_t sva_pd_pindex;
4274 vm_pindex_t eva_pd_pindex;
4275 void (*func)(pmap_t, struct pmap_scan_info *,
4276 pv_entry_t, vm_pindex_t *, pv_entry_t,
4277 int, vm_offset_t,
4278 pt_entry_t *, void *);
4279 void *arg;
4280 pmap_inval_bulk_t bulk_core;
4281 pmap_inval_bulk_t *bulk;
4282 int count;
4283 int stop;
4286 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4287 static int pmap_scan_callback(pv_entry_t pv, void *data);
4289 static void
4290 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4292 struct pmap *pmap = info->pmap;
4293 pv_entry_t pd_pv; /* A page directory PV */
4294 pv_entry_t pt_pv; /* A page table PV */
4295 pv_entry_t pte_pv; /* A page table entry PV */
4296 vm_pindex_t *pte_placemark;
4297 vm_pindex_t *pt_placemark;
4298 pt_entry_t *ptep;
4299 pt_entry_t oldpte;
4300 struct pv_entry dummy_pv;
4302 info->stop = 0;
4303 if (pmap == NULL)
4304 return;
4305 if (info->sva == info->eva)
4306 return;
4307 if (smp_inval) {
4308 info->bulk = &info->bulk_core;
4309 pmap_inval_bulk_init(&info->bulk_core, pmap);
4310 } else {
4311 info->bulk = NULL;
4315 * Hold the token for stability; if the pmap is empty we have nothing
4316 * to do.
4318 #if 0
4319 if (pmap->pm_stats.resident_count == 0) {
4320 return;
4322 #endif
4324 info->count = 0;
4327 * Special handling for scanning one page, which is a very common
4328 * operation (it is?).
4330 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4332 if (info->sva + PAGE_SIZE == info->eva) {
4333 if (info->sva >= VM_MAX_USER_ADDRESS) {
4335 * Kernel mappings do not track wire counts on
4336 * page table pages and only maintain pd_pv and
4337 * pte_pv levels so pmap_scan() works.
4339 pt_pv = NULL;
4340 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4341 &pte_placemark);
4342 ptep = vtopte(info->sva);
4343 } else {
4345 * User pages which are unmanaged will not have a
4346 * pte_pv. User page table pages which are unmanaged
4347 * (shared from elsewhere) will also not have a pt_pv.
4348 * The func() callback will pass both pte_pv and pt_pv
4349 * as NULL in that case.
4351 * We hold pte_placemark across the operation for
4352 * unmanaged pages.
4354 * WARNING! We must hold pt_placemark across the
4355 * *ptep test to prevent misintepreting
4356 * a non-zero *ptep as a shared page
4357 * table page. Hold it across the function
4358 * callback as well for SMP safety.
4360 pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4361 &pte_placemark);
4362 pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4363 &pt_placemark);
4364 if (pt_pv == NULL) {
4365 KKASSERT(pte_pv == NULL);
4366 pd_pv = pv_get(pmap,
4367 pmap_pd_pindex(info->sva),
4368 NULL);
4369 if (pd_pv) {
4370 ptep = pv_pte_lookup(pd_pv,
4371 pmap_pt_index(info->sva));
4372 if (*ptep) {
4373 info->func(pmap, info,
4374 NULL, pt_placemark,
4375 pd_pv, 1,
4376 info->sva, ptep,
4377 info->arg);
4378 } else {
4379 pv_placemarker_wakeup(pmap,
4380 pt_placemark);
4382 pv_put(pd_pv);
4383 } else {
4384 pv_placemarker_wakeup(pmap,
4385 pt_placemark);
4387 pv_placemarker_wakeup(pmap, pte_placemark);
4388 goto fast_skip;
4390 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4394 * NOTE: *ptep can't be ripped out from under us if we hold
4395 * pte_pv (or pte_placemark) locked, but bits can
4396 * change.
4398 oldpte = *ptep;
4399 cpu_ccfence();
4400 if (oldpte == 0) {
4401 KKASSERT(pte_pv == NULL);
4402 pv_placemarker_wakeup(pmap, pte_placemark);
4403 } else if (pte_pv) {
4404 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4405 pmap->pmap_bits[PG_V_IDX])) ==
4406 (pmap->pmap_bits[PG_MANAGED_IDX] |
4407 pmap->pmap_bits[PG_V_IDX]),
4408 ("badA *ptep %016lx/%016lx sva %016lx pte_pv %p",
4409 *ptep, oldpte, info->sva, pte_pv));
4410 info->func(pmap, info, pte_pv, NULL, pt_pv, 0,
4411 info->sva, ptep, info->arg);
4412 } else {
4413 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4414 pmap->pmap_bits[PG_V_IDX])) ==
4415 pmap->pmap_bits[PG_V_IDX],
4416 ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4417 *ptep, oldpte, info->sva));
4418 info->func(pmap, info, NULL, pte_placemark, pt_pv, 0,
4419 info->sva, ptep, info->arg);
4421 if (pt_pv)
4422 pv_put(pt_pv);
4423 fast_skip:
4424 pmap_inval_bulk_flush(info->bulk);
4425 return;
4429 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4430 * there.
4432 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4433 * bounds, resulting in a pd_pindex of 0. To solve the
4434 * problem we use an inclusive range.
4436 info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4437 info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4439 if (info->sva >= VM_MAX_USER_ADDRESS) {
4441 * The kernel does not currently maintain any pv_entry's for
4442 * higher-level page tables.
4444 bzero(&dummy_pv, sizeof(dummy_pv));
4445 dummy_pv.pv_pindex = info->sva_pd_pindex;
4446 spin_lock(&pmap->pm_spin);
4447 while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4448 pmap_scan_callback(&dummy_pv, info);
4449 ++dummy_pv.pv_pindex;
4450 if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4451 break;
4453 spin_unlock(&pmap->pm_spin);
4454 } else {
4456 * User page tables maintain local PML4, PDP, and PD
4457 * pv_entry's at the very least. PT pv's might be
4458 * unmanaged and thus not exist. PTE pv's might be
4459 * unmanaged and thus not exist.
4461 spin_lock(&pmap->pm_spin);
4462 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4463 pmap_scan_callback, info);
4464 spin_unlock(&pmap->pm_spin);
4466 pmap_inval_bulk_flush(info->bulk);
4470 * WARNING! pmap->pm_spin held
4472 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4473 * bounds, resulting in a pd_pindex of 0. To solve the
4474 * problem we use an inclusive range.
4476 static int
4477 pmap_scan_cmp(pv_entry_t pv, void *data)
4479 struct pmap_scan_info *info = data;
4480 if (pv->pv_pindex < info->sva_pd_pindex)
4481 return(-1);
4482 if (pv->pv_pindex > info->eva_pd_pindex)
4483 return(1);
4484 return(0);
4488 * pmap_scan() by PDs
4490 * WARNING! pmap->pm_spin held
4492 static int
4493 pmap_scan_callback(pv_entry_t pv, void *data)
4495 struct pmap_scan_info *info = data;
4496 struct pmap *pmap = info->pmap;
4497 pv_entry_t pd_pv; /* A page directory PV */
4498 pv_entry_t pt_pv; /* A page table PV */
4499 vm_pindex_t *pt_placemark;
4500 pt_entry_t *ptep;
4501 pt_entry_t oldpte;
4502 vm_offset_t sva;
4503 vm_offset_t eva;
4504 vm_offset_t va_next;
4505 vm_pindex_t pd_pindex;
4506 int error;
4509 * Stop if requested
4511 if (info->stop)
4512 return -1;
4515 * Pull the PD pindex from the pv before releasing the spinlock.
4517 * WARNING: pv is faked for kernel pmap scans.
4519 pd_pindex = pv->pv_pindex;
4520 spin_unlock(&pmap->pm_spin);
4521 pv = NULL; /* invalid after spinlock unlocked */
4524 * Calculate the page range within the PD. SIMPLE pmaps are
4525 * direct-mapped for the entire 2^64 address space. Normal pmaps
4526 * reflect the user and kernel address space which requires
4527 * cannonicalization w/regards to converting pd_pindex's back
4528 * into addresses.
4530 sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4531 if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4532 (sva & PML4_SIGNMASK)) {
4533 sva |= PML4_SIGNMASK;
4535 eva = sva + NBPDP; /* can overflow */
4536 if (sva < info->sva)
4537 sva = info->sva;
4538 if (eva < info->sva || eva > info->eva)
4539 eva = info->eva;
4542 * NOTE: kernel mappings do not track page table pages, only
4543 * terminal pages.
4545 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4546 * However, for the scan to be efficient we try to
4547 * cache items top-down.
4549 pd_pv = NULL;
4550 pt_pv = NULL;
4552 for (; sva < eva; sva = va_next) {
4553 if (info->stop)
4554 break;
4555 if (sva >= VM_MAX_USER_ADDRESS) {
4556 if (pt_pv) {
4557 pv_put(pt_pv);
4558 pt_pv = NULL;
4560 goto kernel_skip;
4564 * PD cache, scan shortcut if it doesn't exist.
4566 if (pd_pv == NULL) {
4567 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4568 } else if (pd_pv->pv_pmap != pmap ||
4569 pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4570 pv_put(pd_pv);
4571 pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4573 if (pd_pv == NULL) {
4574 va_next = (sva + NBPDP) & ~PDPMASK;
4575 if (va_next < sva)
4576 va_next = eva;
4577 continue;
4581 * PT cache
4583 * NOTE: The cached pt_pv can be removed from the pmap when
4584 * pmap_dynamic_delete is enabled.
4586 if (pt_pv && (pt_pv->pv_pmap != pmap ||
4587 pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4588 pv_put(pt_pv);
4589 pt_pv = NULL;
4591 if (pt_pv == NULL) {
4592 pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4593 &pt_placemark, &error);
4594 if (error) {
4595 pv_put(pd_pv); /* lock order */
4596 pd_pv = NULL;
4597 if (pt_pv) {
4598 pv_lock(pt_pv);
4599 pv_put(pt_pv);
4600 pt_pv = NULL;
4601 } else {
4602 pv_placemarker_wait(pmap, pt_placemark);
4604 va_next = sva;
4605 continue;
4607 /* may have to re-check later if pt_pv is NULL here */
4611 * If pt_pv is NULL we either have an shared page table
4612 * page and must issue a callback specific to that case,
4613 * or there is no page table page.
4615 * Either way we can skip the page table page.
4617 * WARNING! pt_pv can also be NULL due to a pv creation
4618 * race where we find it to be NULL and then
4619 * later see a pte_pv. But its possible the pt_pv
4620 * got created inbetween the two operations, so
4621 * we must check.
4623 if (pt_pv == NULL) {
4625 * Possible unmanaged (shared from another pmap)
4626 * page table page.
4628 * WARNING! We must hold pt_placemark across the
4629 * *ptep test to prevent misintepreting
4630 * a non-zero *ptep as a shared page
4631 * table page. Hold it across the function
4632 * callback as well for SMP safety.
4634 ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4635 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4636 info->func(pmap, info, NULL, pt_placemark,
4637 pd_pv, 1,
4638 sva, ptep, info->arg);
4639 } else {
4640 pv_placemarker_wakeup(pmap, pt_placemark);
4644 * Done, move to next page table page.
4646 va_next = (sva + NBPDR) & ~PDRMASK;
4647 if (va_next < sva)
4648 va_next = eva;
4649 continue;
4653 * From this point in the loop testing pt_pv for non-NULL
4654 * means we are in UVM, else if it is NULL we are in KVM.
4656 * Limit our scan to either the end of the va represented
4657 * by the current page table page, or to the end of the
4658 * range being removed.
4660 kernel_skip:
4661 va_next = (sva + NBPDR) & ~PDRMASK;
4662 if (va_next < sva)
4663 va_next = eva;
4664 if (va_next > eva)
4665 va_next = eva;
4668 * Scan the page table for pages. Some pages may not be
4669 * managed (might not have a pv_entry).
4671 * There is no page table management for kernel pages so
4672 * pt_pv will be NULL in that case, but otherwise pt_pv
4673 * is non-NULL, locked, and referenced.
4677 * At this point a non-NULL pt_pv means a UVA, and a NULL
4678 * pt_pv means a KVA.
4680 if (pt_pv)
4681 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4682 else
4683 ptep = vtopte(sva);
4685 while (sva < va_next) {
4686 pv_entry_t pte_pv;
4687 vm_pindex_t *pte_placemark;
4690 * Yield every 64 pages, stop if requested.
4692 if ((++info->count & 63) == 0)
4693 lwkt_user_yield();
4694 if (info->stop)
4695 break;
4698 * We can shortcut our scan if *ptep == 0. This is
4699 * an unlocked check.
4701 if (*ptep == 0) {
4702 sva += PAGE_SIZE;
4703 ++ptep;
4704 continue;
4706 cpu_ccfence();
4709 * Acquire the related pte_pv, if any. If *ptep == 0
4710 * the related pte_pv should not exist, but if *ptep
4711 * is not zero the pte_pv may or may not exist (e.g.
4712 * will not exist for an unmanaged page).
4714 * However a multitude of races are possible here
4715 * so if we cannot lock definite state we clean out
4716 * our cache and break the inner while() loop to
4717 * force a loop up to the top of the for().
4719 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4720 * validity instead of looping up?
4722 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4723 &pte_placemark, &error);
4724 if (error) {
4725 if (pd_pv) {
4726 pv_put(pd_pv); /* lock order */
4727 pd_pv = NULL;
4729 if (pt_pv) {
4730 pv_put(pt_pv); /* lock order */
4731 pt_pv = NULL;
4733 if (pte_pv) { /* block */
4734 pv_lock(pte_pv);
4735 pv_put(pte_pv);
4736 pte_pv = NULL;
4737 } else {
4738 pv_placemarker_wait(pmap,
4739 pte_placemark);
4741 va_next = sva; /* retry */
4742 break;
4746 * Reload *ptep after successfully locking the
4747 * pindex. If *ptep == 0 we had better NOT have a
4748 * pte_pv.
4750 cpu_ccfence();
4751 oldpte = *ptep;
4752 if (oldpte == 0) {
4753 if (pte_pv) {
4754 kprintf("Unexpected non-NULL pte_pv "
4755 "%p pt_pv %p "
4756 "*ptep = %016lx/%016lx\n",
4757 pte_pv, pt_pv, *ptep, oldpte);
4758 panic("Unexpected non-NULL pte_pv");
4759 } else {
4760 pv_placemarker_wakeup(pmap, pte_placemark);
4762 sva += PAGE_SIZE;
4763 ++ptep;
4764 continue;
4768 * We can't hold pd_pv across the callback (because
4769 * we don't pass it to the callback and the callback
4770 * might deadlock)
4772 if (pd_pv) {
4773 vm_page_wire_quick(pd_pv->pv_m);
4774 pv_unlock(pd_pv);
4778 * Ready for the callback. The locked pte_pv (if any)
4779 * is consumed by the callback. pte_pv will exist if
4780 * the page is managed, and will not exist if it
4781 * isn't.
4783 if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4785 * Managed pte
4787 KASSERT(pte_pv &&
4788 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4789 ("badC *ptep %016lx/%016lx sva %016lx "
4790 "pte_pv %p",
4791 *ptep, oldpte, sva, pte_pv));
4793 * We must unlock pd_pv across the callback
4794 * to avoid deadlocks on any recursive
4795 * disposal. Re-check that it still exists
4796 * after re-locking.
4798 * Call target disposes of pte_pv and may
4799 * destroy but will not dispose of pt_pv.
4801 info->func(pmap, info, pte_pv, NULL,
4802 pt_pv, 0,
4803 sva, ptep, info->arg);
4804 } else {
4806 * Unmanaged pte
4808 * We must unlock pd_pv across the callback
4809 * to avoid deadlocks on any recursive
4810 * disposal. Re-check that it still exists
4811 * after re-locking.
4813 * Call target disposes of pte_pv or
4814 * pte_placemark and may destroy but will
4815 * not dispose of pt_pv.
4817 KASSERT(pte_pv == NULL &&
4818 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4819 ("badD *ptep %016lx/%016lx sva %016lx "
4820 "pte_pv %p pte_pv->pv_m %p ",
4821 *ptep, oldpte, sva,
4822 pte_pv, (pte_pv ? pte_pv->pv_m : NULL)));
4823 if (pte_pv)
4824 kprintf("RaceD\n");
4825 if (pte_pv) {
4826 info->func(pmap, info,
4827 pte_pv, NULL,
4828 pt_pv, 0,
4829 sva, ptep, info->arg);
4830 } else {
4831 info->func(pmap, info,
4832 NULL, pte_placemark,
4833 pt_pv, 0,
4834 sva, ptep, info->arg);
4837 if (pd_pv) {
4838 pv_lock(pd_pv);
4839 vm_page_unwire_quick(pd_pv->pv_m);
4840 if (pd_pv->pv_pmap == NULL) {
4841 va_next = sva; /* retry */
4842 break;
4847 * NOTE: The cached pt_pv can be removed from the
4848 * pmap when pmap_dynamic_delete is enabled,
4849 * which will cause ptep to become stale.
4851 * This also means that no pages remain under
4852 * the PT, so we can just break out of the inner
4853 * loop and let the outer loop clean everything
4854 * up.
4856 if (pt_pv && pt_pv->pv_pmap != pmap)
4857 break;
4858 pte_pv = NULL;
4859 sva += PAGE_SIZE;
4860 ++ptep;
4863 if (pd_pv) {
4864 pv_put(pd_pv);
4865 pd_pv = NULL;
4867 if (pt_pv) {
4868 pv_put(pt_pv);
4869 pt_pv = NULL;
4871 if ((++info->count & 7) == 0)
4872 lwkt_user_yield();
4875 * Relock before returning.
4877 spin_lock(&pmap->pm_spin);
4878 return (0);
4881 void
4882 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4884 struct pmap_scan_info info;
4886 info.pmap = pmap;
4887 info.sva = sva;
4888 info.eva = eva;
4889 info.func = pmap_remove_callback;
4890 info.arg = NULL;
4891 pmap_scan(&info, 1);
4892 #if 0
4893 cpu_invltlb();
4894 if (eva - sva < 1024*1024) {
4895 while (sva < eva) {
4896 cpu_invlpg((void *)sva);
4897 sva += PAGE_SIZE;
4900 #endif
4903 static void
4904 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4906 struct pmap_scan_info info;
4908 info.pmap = pmap;
4909 info.sva = sva;
4910 info.eva = eva;
4911 info.func = pmap_remove_callback;
4912 info.arg = NULL;
4913 pmap_scan(&info, 0);
4916 static void
4917 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4918 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
4919 pv_entry_t pt_pv, int sharept,
4920 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4922 pt_entry_t pte;
4924 if (pte_pv) {
4926 * Managed entry
4928 * This will also drop pt_pv's wire_count. Note that
4929 * terminal pages are not wired based on mmu presence.
4931 * NOTE: If this is the kernel_pmap, pt_pv can be NULL.
4933 KKASSERT(pte_pv->pv_m != NULL);
4934 pmap_remove_pv_pte(pte_pv, pt_pv, info->bulk, 2);
4935 pte_pv = NULL; /* safety */
4938 * Recursively destroy higher-level page tables.
4940 * This is optional. If we do not, they will still
4941 * be destroyed when the process exits.
4943 * NOTE: Do not destroy pv_entry's with extra hold refs,
4944 * a caller may have unlocked it and intends to
4945 * continue to use it.
4947 if (pmap_dynamic_delete &&
4948 pt_pv &&
4949 pt_pv->pv_m &&
4950 pt_pv->pv_m->wire_count == 1 &&
4951 (pt_pv->pv_hold & PV_HOLD_MASK) == 2 &&
4952 pt_pv->pv_pindex < pmap_pml4_pindex()) {
4953 if (pmap_dynamic_delete == 2)
4954 kprintf("B %jd %08x\n", pt_pv->pv_pindex, pt_pv->pv_hold);
4955 pv_hold(pt_pv); /* extra hold */
4956 pmap_remove_pv_pte(pt_pv, NULL, info->bulk, 1);
4957 pv_lock(pt_pv); /* prior extra hold + relock */
4959 } else if (sharept == 0) {
4961 * Unmanaged pte (pte_placemark is non-NULL)
4963 * pt_pv's wire_count is still bumped by unmanaged pages
4964 * so we must decrement it manually.
4966 * We have to unwire the target page table page.
4968 pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4969 if (pte & pmap->pmap_bits[PG_W_IDX])
4970 atomic_add_long(&pmap->pm_stats.wired_count, -1);
4971 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4972 if (vm_page_unwire_quick(pt_pv->pv_m))
4973 panic("pmap_remove: insufficient wirecount");
4974 pv_placemarker_wakeup(pmap, pte_placemark);
4975 } else {
4977 * Unmanaged page table (pt, pd, or pdp. Not pte) for
4978 * a shared page table.
4980 * pt_pv is actually the pd_pv for our pmap (not the shared
4981 * object pmap).
4983 * We have to unwire the target page table page and we
4984 * have to unwire our page directory page.
4986 * It is unclear how we can invalidate a segment so we
4987 * invalidate -1 which invlidates the tlb.
4989 pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
4990 atomic_add_long(&pmap->pm_stats.resident_count, -1);
4991 KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
4992 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
4993 panic("pmap_remove: shared pgtable1 bad wirecount");
4994 if (vm_page_unwire_quick(pt_pv->pv_m))
4995 panic("pmap_remove: shared pgtable2 bad wirecount");
4996 pv_placemarker_wakeup(pmap, pte_placemark);
5001 * Removes this physical page from all physical maps in which it resides.
5002 * Reflects back modify bits to the pager.
5004 * This routine may not be called from an interrupt.
5006 static
5007 void
5008 pmap_remove_all(vm_page_t m)
5010 pv_entry_t pv;
5011 pmap_inval_bulk_t bulk;
5012 vm_object_t obj;
5014 if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
5015 return;
5017 vm_page_spin_lock(m);
5018 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
5019 if (pv->pv_m != m) {
5020 kprintf("pmap_remove_all FAILURE\n");
5021 kprintf("pv %p pv->pv_m %p m %p\n", pv, pv->pv_m, m);
5022 kprintf("pvflags %08x\n", pv->pv_flags);
5025 KKASSERT(pv->pv_m == m);
5026 if (pv_hold_try(pv)) {
5027 vm_page_spin_unlock(m);
5028 } else {
5029 vm_page_spin_unlock(m);
5030 pv_lock(pv);
5031 pv_put(pv);
5032 vm_page_spin_lock(m);
5033 continue;
5035 KKASSERT(pv->pv_pmap && pv->pv_m == m);
5038 * Holding no spinlocks, pv is locked. Once we scrap
5039 * pv we can no longer use it as a list iterator (but
5040 * we are doing a TAILQ_FIRST() so we are ok).
5042 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5043 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5044 pv = NULL; /* safety */
5045 pmap_inval_bulk_flush(&bulk);
5046 vm_page_spin_lock(m);
5048 if (m->flags & PG_MAPPED) {
5049 obj = m->object;
5050 if (obj) {
5051 vm_map_backing_t ba;
5053 spin_lock(&obj->spin);
5054 TAILQ_FOREACH(ba, &obj->backing_list, entry) {
5056 pmap_backing_match(ba, m, pmap_backing_remove);
5059 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
5060 spin_unlock(&obj->spin);
5061 } else {
5062 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
5066 KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
5067 vm_page_spin_unlock(m);
5071 * Removes the page from a particular pmap
5073 void
5074 pmap_remove_specific(pmap_t pmap, vm_page_t m)
5076 pv_entry_t pv;
5077 pmap_inval_bulk_t bulk;
5079 if (!pmap_initialized)
5080 return;
5082 again:
5083 vm_page_spin_lock(m);
5084 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5085 if (pv->pv_pmap != pmap)
5086 continue;
5087 KKASSERT(pv->pv_m == m);
5088 if (pv_hold_try(pv)) {
5089 vm_page_spin_unlock(m);
5090 } else {
5091 vm_page_spin_unlock(m);
5092 pv_lock(pv);
5093 pv_put(pv);
5094 goto again;
5096 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
5099 * Holding no spinlocks, pv is locked. Once gone it can't
5100 * be used as an iterator. In fact, because we couldn't
5101 * necessarily lock it atomically it may have moved within
5102 * the list and ALSO cannot be used as an iterator.
5104 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5105 pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5106 pv = NULL; /* safety */
5107 pmap_inval_bulk_flush(&bulk);
5108 goto again;
5110 vm_page_spin_unlock(m);
5114 * Set the physical protection on the specified range of this map
5115 * as requested. This function is typically only used for debug watchpoints
5116 * and COW pages.
5118 * This function may not be called from an interrupt if the map is
5119 * not the kernel_pmap.
5121 * NOTE! For shared page table pages we just unmap the page.
5123 void
5124 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
5126 struct pmap_scan_info info;
5127 /* JG review for NX */
5129 if (pmap == NULL)
5130 return;
5131 if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
5132 pmap_remove(pmap, sva, eva);
5133 return;
5135 if (prot & VM_PROT_WRITE)
5136 return;
5137 info.pmap = pmap;
5138 info.sva = sva;
5139 info.eva = eva;
5140 info.func = pmap_protect_callback;
5141 info.arg = &prot;
5142 pmap_scan(&info, 1);
5145 static
5146 void
5147 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
5148 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
5149 pv_entry_t pt_pv, int sharept,
5150 vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
5152 pt_entry_t pbits;
5153 pt_entry_t cbits;
5154 pt_entry_t pte;
5155 vm_page_t m;
5157 again:
5158 pbits = *ptep;
5159 cbits = pbits;
5160 if (pte_pv) {
5161 KKASSERT(pte_pv->pv_m != NULL);
5162 m = NULL;
5163 if (pbits & pmap->pmap_bits[PG_A_IDX]) {
5164 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5165 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5166 KKASSERT(m == pte_pv->pv_m);
5167 vm_page_flag_set(m, PG_REFERENCED);
5169 cbits &= ~pmap->pmap_bits[PG_A_IDX];
5171 if (pbits & pmap->pmap_bits[PG_M_IDX]) {
5172 if (pmap_track_modified(pte_pv->pv_pindex)) {
5173 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5174 if (m == NULL) {
5175 m = PHYS_TO_VM_PAGE(pbits &
5176 PG_FRAME);
5178 vm_page_dirty(m);
5180 cbits &= ~pmap->pmap_bits[PG_M_IDX];
5183 } else if (sharept) {
5185 * Unmanaged page table, pt_pv is actually the pd_pv
5186 * for our pmap (not the object's shared pmap).
5188 * When asked to protect something in a shared page table
5189 * page we just unmap the page table page. We have to
5190 * invalidate the tlb in this situation.
5192 * XXX Warning, shared page tables will not be used for
5193 * OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
5194 * so PHYS_TO_VM_PAGE() should be safe here.
5196 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
5197 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
5198 panic("pmap_protect: pgtable1 pg bad wirecount");
5199 if (vm_page_unwire_quick(pt_pv->pv_m))
5200 panic("pmap_protect: pgtable2 pg bad wirecount");
5201 ptep = NULL;
5203 /* else unmanaged page, adjust bits, no wire changes */
5205 if (ptep) {
5206 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
5207 #ifdef PMAP_DEBUG2
5208 if (pmap_enter_debug > 0) {
5209 --pmap_enter_debug;
5210 kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
5211 "pt_pv=%p cbits=%08lx\n",
5212 va, ptep, pte_pv,
5213 pt_pv, cbits
5216 #endif
5217 if (pbits != cbits) {
5218 vm_offset_t xva;
5220 xva = (sharept) ? (vm_offset_t)-1 : va;
5221 if (!pmap_inval_smp_cmpset(pmap, xva,
5222 ptep, pbits, cbits)) {
5223 goto again;
5227 if (pte_pv)
5228 pv_put(pte_pv);
5229 else
5230 pv_placemarker_wakeup(pmap, pte_placemark);
5234 * Insert the vm_page (m) at the virtual address (va), replacing any prior
5235 * mapping at that address. Set protection and wiring as requested.
5237 * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5238 * possible. If it is we enter the page into the appropriate shared pmap
5239 * hanging off the related VM object instead of the passed pmap, then we
5240 * share the page table page from the VM object's pmap into the current pmap.
5242 * NOTE: This routine MUST insert the page into the pmap now, it cannot
5243 * lazy-evaluate.
5245 * NOTE: If (m) is PG_UNMANAGED it may also be a temporary fake vm_page_t.
5246 * never record it.
5248 void
5249 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5250 boolean_t wired, vm_map_entry_t entry)
5252 pv_entry_t pt_pv; /* page table */
5253 pv_entry_t pte_pv; /* page table entry */
5254 vm_pindex_t *pte_placemark;
5255 pt_entry_t *ptep;
5256 vm_paddr_t opa;
5257 pt_entry_t origpte, newpte;
5258 vm_paddr_t pa;
5260 if (pmap == NULL)
5261 return;
5262 va = trunc_page(va);
5263 #ifdef PMAP_DIAGNOSTIC
5264 if (va >= KvaEnd)
5265 panic("pmap_enter: toobig");
5266 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5267 panic("pmap_enter: invalid to pmap_enter page table "
5268 "pages (va: 0x%lx)", va);
5269 #endif
5270 if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
5271 kprintf("Warning: pmap_enter called on UVA with "
5272 "kernel_pmap\n");
5273 #ifdef DDB
5274 db_print_backtrace();
5275 #endif
5277 if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
5278 kprintf("Warning: pmap_enter called on KVA without"
5279 "kernel_pmap\n");
5280 #ifdef DDB
5281 db_print_backtrace();
5282 #endif
5286 * Get locked PV entries for our new page table entry (pte_pv or
5287 * pte_placemark) and for its parent page table (pt_pv). We need
5288 * the parent so we can resolve the location of the ptep.
5290 * Only hardware MMU actions can modify the ptep out from
5291 * under us.
5293 * if (m) is fictitious or unmanaged we do not create a managing
5294 * pte_pv for it. Any pre-existing page's management state must
5295 * match (avoiding code complexity).
5297 * If the pmap is still being initialized we assume existing
5298 * page tables.
5300 * Kernel mapppings do not track page table pages (i.e. pt_pv).
5302 * WARNING! If replacing a managed mapping with an unmanaged mapping
5303 * pte_pv will wind up being non-NULL and must be handled
5304 * below.
5306 if (pmap_initialized == FALSE) {
5307 pte_pv = NULL;
5308 pt_pv = NULL;
5309 pte_placemark = NULL;
5310 ptep = vtopte(va);
5311 origpte = *ptep;
5312 } else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
5313 pmap_softwait(pmap);
5314 pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5315 KKASSERT(pte_pv == NULL);
5316 if (va >= VM_MAX_USER_ADDRESS) {
5317 pt_pv = NULL;
5318 ptep = vtopte(va);
5319 } else {
5320 pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
5321 NULL, entry, va);
5322 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5324 origpte = *ptep;
5325 cpu_ccfence();
5326 KASSERT(origpte == 0 ||
5327 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0,
5328 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5329 } else {
5330 pmap_softwait(pmap);
5331 if (va >= VM_MAX_USER_ADDRESS) {
5333 * Kernel map, pv_entry-tracked.
5335 pt_pv = NULL;
5336 pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
5337 ptep = vtopte(va);
5338 } else {
5340 * User map
5342 pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
5343 &pt_pv, entry, va);
5344 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5346 pte_placemark = NULL; /* safety */
5347 origpte = *ptep;
5348 cpu_ccfence();
5349 KASSERT(origpte == 0 ||
5350 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]),
5351 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5354 pa = VM_PAGE_TO_PHYS(m);
5355 opa = origpte & PG_FRAME;
5358 * Calculate the new PTE. Note that pte_pv alone does not mean
5359 * the new pte_pv is managed, it could exist because the old pte
5360 * was managed even if the new one is not.
5362 newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5363 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5364 if (wired)
5365 newpte |= pmap->pmap_bits[PG_W_IDX];
5366 if (va < VM_MAX_USER_ADDRESS)
5367 newpte |= pmap->pmap_bits[PG_U_IDX];
5368 if (pte_pv && (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) == 0)
5369 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5370 // if (pmap == &kernel_pmap)
5371 // newpte |= pgeflag;
5372 newpte |= pmap->pmap_cache_bits[m->pat_mode];
5373 if (m->flags & PG_FICTITIOUS)
5374 newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
5377 * It is possible for multiple faults to occur in threaded
5378 * environments, the existing pte might be correct.
5380 if (((origpte ^ newpte) &
5381 ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5382 pmap->pmap_bits[PG_A_IDX])) == 0) {
5383 goto done;
5387 * Ok, either the address changed or the protection or wiring
5388 * changed.
5390 * Clear the current entry, interlocking the removal. For managed
5391 * pte's this will also flush the modified state to the vm_page.
5392 * Atomic ops are mandatory in order to ensure that PG_M events are
5393 * not lost during any transition.
5395 * WARNING: The caller has busied the new page but not the original
5396 * vm_page which we are trying to replace. Because we hold
5397 * the pte_pv lock, but have not busied the page, PG bits
5398 * can be cleared out from under us.
5400 if (opa) {
5401 if (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
5403 * Old page was managed. Expect pte_pv to exist.
5404 * (it might also exist if the old page was unmanaged).
5406 * NOTE: pt_pv won't exist for a kernel page
5407 * (managed or otherwise).
5409 * NOTE: We may be reusing the pte_pv so we do not
5410 * destroy it in pmap_remove_pv_pte().
5412 KKASSERT(pte_pv && pte_pv->pv_m);
5413 if (prot & VM_PROT_NOSYNC) {
5414 pmap_remove_pv_pte(pte_pv, pt_pv, NULL, 0);
5415 } else {
5416 pmap_inval_bulk_t bulk;
5418 pmap_inval_bulk_init(&bulk, pmap);
5419 pmap_remove_pv_pte(pte_pv, pt_pv, &bulk, 0);
5420 pmap_inval_bulk_flush(&bulk);
5422 pmap_remove_pv_page(pte_pv);
5423 /* will either set pte_pv->pv_m or pv_free() later */
5424 } else {
5426 * Old page was not managed. If we have a pte_pv
5427 * it better not have a pv_m assigned to it. If the
5428 * new page is managed the pte_pv will be destroyed
5429 * near the end (we need its interlock).
5431 * NOTE: We leave the wire count on the PT page
5432 * intact for the followup enter, but adjust
5433 * the wired-pages count on the pmap.
5435 KKASSERT(pte_pv == NULL);
5436 if (prot & VM_PROT_NOSYNC) {
5438 * NOSYNC (no mmu sync) requested.
5440 (void)pte_load_clear(ptep);
5441 cpu_invlpg((void *)va);
5442 } else {
5444 * Nominal SYNC
5446 pmap_inval_smp(pmap, va, 1, ptep, 0);
5450 * We must adjust pm_stats manually for unmanaged
5451 * pages.
5453 if (pt_pv) {
5454 atomic_add_long(&pmap->pm_stats.
5455 resident_count, -1);
5457 if (origpte & pmap->pmap_bits[PG_W_IDX]) {
5458 atomic_add_long(&pmap->pm_stats.
5459 wired_count, -1);
5462 KKASSERT(*ptep == 0);
5465 #ifdef PMAP_DEBUG2
5466 if (pmap_enter_debug > 0) {
5467 --pmap_enter_debug;
5468 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5469 " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5470 va, m,
5471 origpte, newpte, ptep,
5472 pte_pv, pt_pv, opa, prot);
5474 #endif
5476 if ((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5478 * Entering an unmanaged page. We must wire the pt_pv unless
5479 * we retained the wiring from an unmanaged page we had
5480 * removed (if we retained it via pte_pv that will go away
5481 * soon).
5483 if (pt_pv && (opa == 0 ||
5484 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]))) {
5485 vm_page_wire_quick(pt_pv->pv_m);
5487 if (wired)
5488 atomic_add_long(&pmap->pm_stats.wired_count, 1);
5491 * Unmanaged pages need manual resident_count tracking.
5493 if (pt_pv) {
5494 atomic_add_long(&pt_pv->pv_pmap->pm_stats.
5495 resident_count, 1);
5497 if (newpte & pmap->pmap_bits[PG_RW_IDX])
5498 vm_page_flag_set(m, PG_WRITEABLE);
5499 } else {
5501 * Entering a managed page. Our pte_pv takes care of the
5502 * PT wiring, so if we had removed an unmanaged page before
5503 * we must adjust.
5505 * We have to take care of the pmap wired count ourselves.
5507 * Enter on the PV list if part of our managed memory.
5510 if (m->object == NULL && pmap_pv_debug > 0) {
5511 --pmap_pv_debug;
5512 kprintf("pte_m %p pv_entry %p NOOBJ\n", m, pte_pv);
5513 print_backtrace(16);
5516 KKASSERT(pte_pv && (pte_pv->pv_m == NULL || pte_pv->pv_m == m));
5517 vm_page_spin_lock(m);
5518 pte_pv->pv_m = m;
5519 pmap_page_stats_adding(m);
5520 TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
5523 * Set vm_page flags. Avoid a cache mastership change if
5524 * the bits are already set.
5526 if ((m->flags & PG_MAPPED) == 0)
5527 vm_page_flag_set(m, PG_MAPPED);
5528 if ((newpte & pmap->pmap_bits[PG_RW_IDX]) &&
5529 (m->flags & PG_WRITEABLE) == 0) {
5530 vm_page_flag_set(m, PG_WRITEABLE);
5532 vm_page_spin_unlock(m);
5534 if (pt_pv && opa &&
5535 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5536 vm_page_unwire_quick(pt_pv->pv_m);
5540 * Adjust pmap wired pages count for new entry.
5542 if (wired) {
5543 atomic_add_long(&pte_pv->pv_pmap->pm_stats.
5544 wired_count, 1);
5549 * Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
5551 * User VMAs do not because those will be zero->non-zero, so no
5552 * stale entries to worry about at this point.
5554 * For KVM there appear to still be issues. Theoretically we
5555 * should be able to scrap the interlocks entirely but we
5556 * get crashes.
5558 if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL) {
5559 pmap_inval_smp(pmap, va, 1, ptep, newpte);
5560 } else {
5561 origpte = atomic_swap_long(ptep, newpte);
5562 if (origpte & pmap->pmap_bits[PG_M_IDX]) {
5563 kprintf("pmap [M] race @ %016jx\n", va);
5564 atomic_set_long(ptep, pmap->pmap_bits[PG_M_IDX]);
5566 if (pt_pv == NULL)
5567 cpu_invlpg((void *)va);
5571 * Cleanup
5573 done:
5574 KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5575 (m->flags & PG_MAPPED));
5578 * Cleanup the pv entry, allowing other accessors. If the new page
5579 * is not managed but we have a pte_pv (which was locking our
5580 * operation), we can free it now. pte_pv->pv_m should be NULL.
5582 if (pte_pv && (newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5583 pv_free(pte_pv, pt_pv);
5584 } else if (pte_pv) {
5585 pv_put(pte_pv);
5586 } else if (pte_placemark) {
5587 pv_placemarker_wakeup(pmap, pte_placemark);
5589 if (pt_pv)
5590 pv_put(pt_pv);
5594 * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
5595 * This code also assumes that the pmap has no pre-existing entry for this
5596 * VA.
5598 * This code currently may only be used on user pmaps, not kernel_pmap.
5600 void
5601 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
5603 pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
5607 * Make a temporary mapping for a physical address. This is only intended
5608 * to be used for panic dumps.
5610 * The caller is responsible for calling smp_invltlb().
5612 void *
5613 pmap_kenter_temporary(vm_paddr_t pa, long i)
5615 pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5616 return ((void *)crashdumpmap);
5619 #define MAX_INIT_PT (96)
5622 * This routine preloads the ptes for a given object into the specified pmap.
5623 * This eliminates the blast of soft faults on process startup and
5624 * immediately after an mmap.
5626 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5628 void
5629 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
5630 vm_object_t object, vm_pindex_t pindex,
5631 vm_size_t size, int limit)
5633 struct rb_vm_page_scan_info info;
5634 struct lwp *lp;
5635 vm_size_t psize;
5638 * We can't preinit if read access isn't set or there is no pmap
5639 * or object.
5641 if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5642 return;
5645 * We can't preinit if the pmap is not the current pmap
5647 lp = curthread->td_lwp;
5648 if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5649 return;
5652 * Misc additional checks
5654 psize = x86_64_btop(size);
5656 if ((object->type != OBJT_VNODE) ||
5657 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5658 (object->resident_page_count > MAX_INIT_PT))) {
5659 return;
5662 if (pindex + psize > object->size) {
5663 if (object->size < pindex)
5664 return;
5665 psize = object->size - pindex;
5668 if (psize == 0)
5669 return;
5672 * If everything is segment-aligned do not pre-init here. Instead
5673 * allow the normal vm_fault path to pass a segment hint to
5674 * pmap_enter() which will then use an object-referenced shared
5675 * page table page.
5677 if ((addr & SEG_MASK) == 0 &&
5678 (ctob(psize) & SEG_MASK) == 0 &&
5679 (ctob(pindex) & SEG_MASK) == 0) {
5680 return;
5684 * Use a red-black scan to traverse the requested range and load
5685 * any valid pages found into the pmap.
5687 * We cannot safely scan the object's memq without holding the
5688 * object token.
5690 info.start_pindex = pindex;
5691 info.end_pindex = pindex + psize - 1;
5692 info.limit = limit;
5693 info.mpte = NULL;
5694 info.addr = addr;
5695 info.pmap = pmap;
5696 info.object = object;
5699 * By using the NOLK scan, the callback function must be sure
5700 * to return -1 if the VM page falls out of the object.
5702 vm_object_hold_shared(object);
5703 vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5704 pmap_object_init_pt_callback, &info);
5705 vm_object_drop(object);
5708 static
5710 pmap_object_init_pt_callback(vm_page_t p, void *data)
5712 struct rb_vm_page_scan_info *info = data;
5713 vm_pindex_t rel_index;
5714 int hard_busy;
5717 * don't allow an madvise to blow away our really
5718 * free pages allocating pv entries.
5720 if ((info->limit & MAP_PREFAULT_MADVISE) &&
5721 vmstats.v_free_count < vmstats.v_free_reserved) {
5722 return(-1);
5726 * Ignore list markers and ignore pages we cannot instantly
5727 * busy (while holding the object token).
5729 if (p->flags & PG_MARKER)
5730 return 0;
5731 hard_busy = 0;
5732 again:
5733 if (hard_busy) {
5734 if (vm_page_busy_try(p, TRUE))
5735 return 0;
5736 } else {
5737 if (vm_page_sbusy_try(p))
5738 return 0;
5740 if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5741 (p->flags & PG_FICTITIOUS) == 0) {
5742 if ((p->queue - p->pc) == PQ_CACHE) {
5743 if (hard_busy == 0) {
5744 vm_page_sbusy_drop(p);
5745 hard_busy = 1;
5746 goto again;
5748 vm_page_deactivate(p);
5750 rel_index = p->pindex - info->start_pindex;
5751 pmap_enter_quick(info->pmap,
5752 info->addr + x86_64_ptob(rel_index), p);
5754 if (hard_busy)
5755 vm_page_wakeup(p);
5756 else
5757 vm_page_sbusy_drop(p);
5760 * We are using an unlocked scan (that is, the scan expects its
5761 * current element to remain in the tree on return). So we have
5762 * to check here and abort the scan if it isn't.
5764 if (p->object != info->object)
5765 return -1;
5766 lwkt_yield();
5767 return(0);
5771 * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5772 * address.
5774 * Returns FALSE if it would be non-trivial or if a pte is already loaded
5775 * into the slot.
5777 * XXX This is safe only because page table pages are not freed.
5780 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5782 pt_entry_t *pte;
5784 /*spin_lock(&pmap->pm_spin);*/
5785 if ((pte = pmap_pte(pmap, addr)) != NULL) {
5786 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5787 /*spin_unlock(&pmap->pm_spin);*/
5788 return FALSE;
5791 /*spin_unlock(&pmap->pm_spin);*/
5792 return TRUE;
5796 * Change the wiring attribute for a pmap/va pair. The mapping must already
5797 * exist in the pmap. The mapping may or may not be managed. The wiring in
5798 * the page is not changed, the page is returned so the caller can adjust
5799 * its wiring (the page is not locked in any way).
5801 * Wiring is not a hardware characteristic so there is no need to invalidate
5802 * TLB. However, in an SMP environment we must use a locked bus cycle to
5803 * update the pte (if we are not using the pmap_inval_*() API that is)...
5804 * it's ok to do this for simple wiring changes.
5806 vm_page_t
5807 pmap_unwire(pmap_t pmap, vm_offset_t va)
5809 pt_entry_t *ptep;
5810 pv_entry_t pt_pv;
5811 vm_paddr_t pa;
5812 vm_page_t m;
5814 if (pmap == NULL)
5815 return NULL;
5818 * Assume elements in the kernel pmap are stable
5820 if (pmap == &kernel_pmap) {
5821 if (pmap_pt(pmap, va) == 0)
5822 return NULL;
5823 ptep = pmap_pte_quick(pmap, va);
5824 if (pmap_pte_v(pmap, ptep)) {
5825 if (pmap_pte_w(pmap, ptep))
5826 atomic_add_long(&pmap->pm_stats.wired_count,-1);
5827 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5828 pa = *ptep & PG_FRAME;
5829 m = PHYS_TO_VM_PAGE(pa);
5830 } else {
5831 m = NULL;
5833 } else {
5835 * We can only [un]wire pmap-local pages (we cannot wire
5836 * shared pages)
5838 pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5839 if (pt_pv == NULL)
5840 return NULL;
5842 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5843 if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5844 pv_put(pt_pv);
5845 return NULL;
5848 if (pmap_pte_w(pmap, ptep)) {
5849 atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5850 -1);
5852 /* XXX else return NULL so caller doesn't unwire m ? */
5854 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5856 pa = *ptep & PG_FRAME;
5857 m = PHYS_TO_VM_PAGE(pa); /* held by wired count */
5858 pv_put(pt_pv);
5860 return m;
5864 * Copy the range specified by src_addr/len from the source map to
5865 * the range dst_addr/len in the destination map.
5867 * This routine is only advisory and need not do anything.
5869 void
5870 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5871 vm_size_t len, vm_offset_t src_addr)
5876 * pmap_zero_page:
5878 * Zero the specified physical page.
5880 * This function may be called from an interrupt and no locking is
5881 * required.
5883 void
5884 pmap_zero_page(vm_paddr_t phys)
5886 vm_offset_t va = PHYS_TO_DMAP(phys);
5888 pagezero((void *)va);
5892 * pmap_zero_page:
5894 * Zero part of a physical page by mapping it into memory and clearing
5895 * its contents with bzero.
5897 * off and size may not cover an area beyond a single hardware page.
5899 void
5900 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5902 vm_offset_t virt = PHYS_TO_DMAP(phys);
5904 bzero((char *)virt + off, size);
5908 * pmap_copy_page:
5910 * Copy the physical page from the source PA to the target PA.
5911 * This function may be called from an interrupt. No locking
5912 * is required.
5914 void
5915 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5917 vm_offset_t src_virt, dst_virt;
5919 src_virt = PHYS_TO_DMAP(src);
5920 dst_virt = PHYS_TO_DMAP(dst);
5921 bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5925 * pmap_copy_page_frag:
5927 * Copy the physical page from the source PA to the target PA.
5928 * This function may be called from an interrupt. No locking
5929 * is required.
5931 void
5932 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5934 vm_offset_t src_virt, dst_virt;
5936 src_virt = PHYS_TO_DMAP(src);
5937 dst_virt = PHYS_TO_DMAP(dst);
5939 bcopy((char *)src_virt + (src & PAGE_MASK),
5940 (char *)dst_virt + (dst & PAGE_MASK),
5941 bytes);
5945 * Returns true if the pmap's pv is one of the first 16 pvs linked to from
5946 * this page. This count may be changed upwards or downwards in the future;
5947 * it is only necessary that true be returned for a small subset of pmaps
5948 * for proper page aging.
5950 boolean_t
5951 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5953 pv_entry_t pv;
5954 int loops = 0;
5956 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5957 return FALSE;
5959 vm_page_spin_lock(m);
5960 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5961 if (pv->pv_pmap == pmap) {
5962 vm_page_spin_unlock(m);
5963 return TRUE;
5965 loops++;
5966 if (loops >= 16)
5967 break;
5969 vm_page_spin_unlock(m);
5970 return (FALSE);
5974 * Remove all pages from specified address space this aids process exit
5975 * speeds. Also, this code may be special cased for the current process
5976 * only.
5978 void
5979 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5981 pmap_remove_noinval(pmap, sva, eva);
5982 cpu_invltlb();
5986 * pmap_testbit tests bits in pte's note that the testbit/clearbit
5987 * routines are inline, and a lot of things compile-time evaluate.
5990 static
5991 boolean_t
5992 pmap_testbit(vm_page_t m, int bit)
5994 pv_entry_t pv;
5995 pt_entry_t *pte;
5996 pmap_t pmap;
5998 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5999 return FALSE;
6001 if (TAILQ_FIRST(&m->md.pv_list) == NULL)
6002 return FALSE;
6003 vm_page_spin_lock(m);
6004 if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
6005 vm_page_spin_unlock(m);
6006 return FALSE;
6009 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6010 #if defined(PMAP_DIAGNOSTIC)
6011 if (pv->pv_pmap == NULL) {
6012 kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
6013 pv->pv_pindex);
6014 continue;
6016 #endif
6017 pmap = pv->pv_pmap;
6020 * If the bit being tested is the modified bit, then
6021 * mark clean_map and ptes as never
6022 * modified.
6024 * WARNING! Because we do not lock the pv, *pte can be in a
6025 * state of flux. Despite this the value of *pte
6026 * will still be related to the vm_page in some way
6027 * because the pv cannot be destroyed as long as we
6028 * hold the vm_page spin lock.
6030 if (bit == PG_A_IDX || bit == PG_M_IDX) {
6031 //& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
6032 if (!pmap_track_modified(pv->pv_pindex))
6033 continue;
6036 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6037 if (*pte & pmap->pmap_bits[bit]) {
6038 vm_page_spin_unlock(m);
6039 return TRUE;
6042 vm_page_spin_unlock(m);
6043 return (FALSE);
6047 * This routine is used to modify bits in ptes. Only one bit should be
6048 * specified. PG_RW requires special handling.
6050 * Caller must NOT hold any spin locks
6052 static __inline
6053 void
6054 pmap_clearbit(vm_page_t m, int bit_index)
6056 pv_entry_t pv;
6057 pt_entry_t *pte;
6058 pt_entry_t pbits;
6059 pmap_t pmap;
6061 if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
6062 if (bit_index == PG_RW_IDX)
6063 vm_page_flag_clear(m, PG_WRITEABLE);
6064 return;
6068 * PG_M or PG_A case
6070 * Loop over all current mappings setting/clearing as appropos If
6071 * setting RO do we need to clear the VAC?
6073 * NOTE: When clearing PG_M we could also (not implemented) drop
6074 * through to the PG_RW code and clear PG_RW too, forcing
6075 * a fault on write to redetect PG_M for virtual kernels, but
6076 * it isn't necessary since virtual kernels invalidate the
6077 * pte when they clear the VPTE_M bit in their virtual page
6078 * tables.
6080 * NOTE: Does not re-dirty the page when clearing only PG_M.
6082 * NOTE: Because we do not lock the pv, *pte can be in a state of
6083 * flux. Despite this the value of *pte is still somewhat
6084 * related while we hold the vm_page spin lock.
6086 * *pte can be zero due to this race. Since we are clearing
6087 * bits we basically do no harm when this race occurs.
6089 if (bit_index != PG_RW_IDX) {
6090 vm_page_spin_lock(m);
6091 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6092 #if defined(PMAP_DIAGNOSTIC)
6093 if (pv->pv_pmap == NULL) {
6094 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6095 pv->pv_pindex);
6096 continue;
6098 #endif
6099 pmap = pv->pv_pmap;
6100 pte = pmap_pte_quick(pv->pv_pmap,
6101 pv->pv_pindex << PAGE_SHIFT);
6102 pbits = *pte;
6103 if (pbits & pmap->pmap_bits[bit_index])
6104 atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
6106 vm_page_spin_unlock(m);
6107 return;
6111 * Clear PG_RW. Also clears PG_M and marks the page dirty if PG_M
6112 * was set.
6114 restart:
6115 vm_page_spin_lock(m);
6116 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6118 * don't write protect pager mappings
6120 if (!pmap_track_modified(pv->pv_pindex))
6121 continue;
6123 #if defined(PMAP_DIAGNOSTIC)
6124 if (pv->pv_pmap == NULL) {
6125 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6126 pv->pv_pindex);
6127 continue;
6129 #endif
6130 pmap = pv->pv_pmap;
6133 * Skip pages which do not have PG_RW set.
6135 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6136 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
6137 continue;
6140 * We must lock the PV to be able to safely test the pte.
6142 if (pv_hold_try(pv)) {
6143 vm_page_spin_unlock(m);
6144 } else {
6145 vm_page_spin_unlock(m);
6146 pv_lock(pv); /* held, now do a blocking lock */
6147 pv_put(pv);
6148 goto restart;
6152 * Reload pte after acquiring pv.
6154 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6155 #if 0
6156 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0) {
6157 pv_put(pv);
6158 goto restart;
6160 #endif
6162 KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
6163 for (;;) {
6164 pt_entry_t nbits;
6166 pbits = *pte;
6167 cpu_ccfence();
6168 nbits = pbits & ~(pmap->pmap_bits[PG_RW_IDX] |
6169 pmap->pmap_bits[PG_M_IDX]);
6170 if (pmap_inval_smp_cmpset(pmap,
6171 ((vm_offset_t)pv->pv_pindex << PAGE_SHIFT),
6172 pte, pbits, nbits)) {
6173 break;
6175 cpu_pause();
6179 * If PG_M was found to be set while we were clearing PG_RW
6180 * we also clear PG_M (done above) and mark the page dirty.
6181 * Callers expect this behavior.
6183 * we lost pv so it cannot be used as an iterator. In fact,
6184 * because we couldn't necessarily lock it atomically it may
6185 * have moved within the list and ALSO cannot be used as an
6186 * iterator.
6188 vm_page_spin_lock(m);
6189 if (pbits & pmap->pmap_bits[PG_M_IDX])
6190 vm_page_dirty(m);
6191 vm_page_spin_unlock(m);
6192 pv_put(pv);
6193 goto restart;
6195 if (bit_index == PG_RW_IDX)
6196 vm_page_flag_clear(m, PG_WRITEABLE);
6197 vm_page_spin_unlock(m);
6201 * Lower the permission for all mappings to a given page.
6203 * Page must be busied by caller. Because page is busied by caller this
6204 * should not be able to race a pmap_enter().
6206 void
6207 pmap_page_protect(vm_page_t m, vm_prot_t prot)
6209 /* JG NX support? */
6210 if ((prot & VM_PROT_WRITE) == 0) {
6211 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
6213 * NOTE: pmap_clearbit(.. PG_RW) also clears
6214 * the PG_WRITEABLE flag in (m).
6216 pmap_clearbit(m, PG_RW_IDX);
6217 } else {
6218 pmap_remove_all(m);
6223 vm_paddr_t
6224 pmap_phys_address(vm_pindex_t ppn)
6226 return (x86_64_ptob(ppn));
6230 * Return a count of reference bits for a page, clearing those bits.
6231 * It is not necessary for every reference bit to be cleared, but it
6232 * is necessary that 0 only be returned when there are truly no
6233 * reference bits set.
6235 * XXX: The exact number of bits to check and clear is a matter that
6236 * should be tested and standardized at some point in the future for
6237 * optimal aging of shared pages.
6239 * This routine may not block.
6242 pmap_ts_referenced(vm_page_t m)
6244 pv_entry_t pv;
6245 pt_entry_t *pte;
6246 pmap_t pmap;
6247 int rtval = 0;
6249 if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
6250 return (rtval);
6252 vm_page_spin_lock(m);
6253 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6254 if (!pmap_track_modified(pv->pv_pindex))
6255 continue;
6256 pmap = pv->pv_pmap;
6257 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6258 if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
6259 atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
6260 rtval++;
6261 if (rtval > 4)
6262 break;
6265 vm_page_spin_unlock(m);
6266 return (rtval);
6270 * pmap_is_modified:
6272 * Return whether or not the specified physical page was modified
6273 * in any physical maps.
6275 boolean_t
6276 pmap_is_modified(vm_page_t m)
6278 boolean_t res;
6280 res = pmap_testbit(m, PG_M_IDX);
6281 return (res);
6285 * Clear the modify bits on the specified physical page.
6287 void
6288 pmap_clear_modify(vm_page_t m)
6290 pmap_clearbit(m, PG_M_IDX);
6294 * pmap_clear_reference:
6296 * Clear the reference bit on the specified physical page.
6298 void
6299 pmap_clear_reference(vm_page_t m)
6301 pmap_clearbit(m, PG_A_IDX);
6305 * Miscellaneous support routines follow
6308 static
6309 void
6310 x86_64_protection_init(void)
6312 uint64_t *kp;
6313 int prot;
6316 * NX supported? (boot time loader.conf override only)
6318 * -1 Automatic (sets mode 1)
6319 * 0 Disabled
6320 * 1 NX implemented, differentiates PROT_READ vs PROT_READ|PROT_EXEC
6321 * 2 NX implemented for all cases
6323 TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
6324 if ((amd_feature & AMDID_NX) == 0) {
6325 pmap_bits_default[PG_NX_IDX] = 0;
6326 pmap_nx_enable = 0;
6327 } else if (pmap_nx_enable < 0) {
6328 pmap_nx_enable = 1; /* default to mode 1 (READ) */
6332 * 0 is basically read-only access, but also set the NX (no-execute)
6333 * bit when VM_PROT_EXECUTE is not specified.
6335 kp = protection_codes;
6336 for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
6337 switch (prot) {
6338 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
6340 * This case handled elsewhere
6342 *kp = 0;
6343 break;
6344 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
6346 * Read-only is 0|NX (pmap_nx_enable mode >= 1)
6348 if (pmap_nx_enable >= 1)
6349 *kp = pmap_bits_default[PG_NX_IDX];
6350 break;
6351 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6352 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6354 * Execute requires read access
6356 *kp = 0;
6357 break;
6358 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6359 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6361 * Write without execute is RW|NX
6362 * (pmap_nx_enable mode >= 2)
6364 *kp = pmap_bits_default[PG_RW_IDX];
6365 if (pmap_nx_enable >= 2)
6366 *kp |= pmap_bits_default[PG_NX_IDX];
6367 break;
6368 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6369 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6371 * Write with execute is RW
6373 *kp = pmap_bits_default[PG_RW_IDX];
6374 break;
6376 ++kp;
6381 * Map a set of physical memory pages into the kernel virtual
6382 * address space. Return a pointer to where it is mapped. This
6383 * routine is intended to be used for mapping device memory,
6384 * NOT real memory.
6386 * NOTE: We can't use pgeflag unless we invalidate the pages one at
6387 * a time.
6389 * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6390 * work whether the cpu supports PAT or not. The remaining PAT
6391 * attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6392 * supports PAT.
6394 void *
6395 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6397 return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6400 void *
6401 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6403 return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6406 void *
6407 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6409 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6413 * Map a set of physical memory pages into the kernel virtual
6414 * address space. Return a pointer to where it is mapped. This
6415 * routine is intended to be used for mapping device memory,
6416 * NOT real memory.
6418 void *
6419 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6421 vm_offset_t va, tmpva, offset;
6422 pt_entry_t *pte;
6423 vm_size_t tmpsize;
6425 offset = pa & PAGE_MASK;
6426 size = roundup(offset + size, PAGE_SIZE);
6428 va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6429 if (va == 0)
6430 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6432 pa = pa & ~PAGE_MASK;
6433 for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6434 pte = vtopte(tmpva);
6435 *pte = pa |
6436 kernel_pmap.pmap_bits[PG_RW_IDX] |
6437 kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
6438 kernel_pmap.pmap_cache_bits[mode];
6439 tmpsize -= PAGE_SIZE;
6440 tmpva += PAGE_SIZE;
6441 pa += PAGE_SIZE;
6443 pmap_invalidate_range(&kernel_pmap, va, va + size);
6444 pmap_invalidate_cache_range(va, va + size);
6446 return ((void *)(va + offset));
6449 void
6450 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6452 vm_offset_t base, offset;
6454 base = va & ~PAGE_MASK;
6455 offset = va & PAGE_MASK;
6456 size = roundup(offset + size, PAGE_SIZE);
6457 pmap_qremove(va, size >> PAGE_SHIFT);
6458 kmem_free(&kernel_map, base, size);
6462 * Sets the memory attribute for the specified page.
6464 void
6465 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6468 m->pat_mode = ma;
6471 * If "m" is a normal page, update its direct mapping. This update
6472 * can be relied upon to perform any cache operations that are
6473 * required for data coherence.
6475 if ((m->flags & PG_FICTITIOUS) == 0)
6476 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6480 * Change the PAT attribute on an existing kernel memory map. Caller
6481 * must ensure that the virtual memory in question is not accessed
6482 * during the adjustment.
6484 void
6485 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6487 pt_entry_t *pte;
6488 vm_offset_t base;
6489 int changed = 0;
6491 if (va == 0)
6492 panic("pmap_change_attr: va is NULL");
6493 base = trunc_page(va);
6495 while (count) {
6496 pte = vtopte(va);
6497 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
6498 kernel_pmap.pmap_cache_bits[mode];
6499 --count;
6500 va += PAGE_SIZE;
6503 changed = 1; /* XXX: not optimal */
6506 * Flush CPU caches if required to make sure any data isn't cached that
6507 * shouldn't be, etc.
6509 if (changed) {
6510 pmap_invalidate_range(&kernel_pmap, base, va);
6511 pmap_invalidate_cache_range(base, va);
6516 * perform the pmap work for mincore
6519 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6521 pt_entry_t *ptep, pte;
6522 vm_page_t m;
6523 int val = 0;
6525 ptep = pmap_pte(pmap, addr);
6527 if (ptep && (pte = *ptep) != 0) {
6528 vm_offset_t pa;
6530 val = MINCORE_INCORE;
6531 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
6532 goto done;
6534 pa = pte & PG_FRAME;
6536 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
6537 m = NULL;
6538 else
6539 m = PHYS_TO_VM_PAGE(pa);
6542 * Modified by us
6544 if (pte & pmap->pmap_bits[PG_M_IDX])
6545 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6547 * Modified by someone
6549 else if (m && (m->dirty || pmap_is_modified(m)))
6550 val |= MINCORE_MODIFIED_OTHER;
6552 * Referenced by us
6554 if (pte & pmap->pmap_bits[PG_A_IDX])
6555 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6558 * Referenced by someone
6560 else if (m && ((m->flags & PG_REFERENCED) ||
6561 pmap_ts_referenced(m))) {
6562 val |= MINCORE_REFERENCED_OTHER;
6563 vm_page_flag_set(m, PG_REFERENCED);
6566 done:
6568 return val;
6572 * Replace p->p_vmspace with a new one. If adjrefs is non-zero the new
6573 * vmspace will be ref'd and the old one will be deref'd.
6575 * The vmspace for all lwps associated with the process will be adjusted
6576 * and cr3 will be reloaded if any lwp is the current lwp.
6578 * The process must hold the vmspace->vm_map.token for oldvm and newvm
6580 void
6581 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6583 struct vmspace *oldvm;
6584 struct lwp *lp;
6586 oldvm = p->p_vmspace;
6587 if (oldvm != newvm) {
6588 if (adjrefs)
6589 vmspace_ref(newvm);
6590 p->p_vmspace = newvm;
6591 KKASSERT(p->p_nthreads == 1);
6592 lp = RB_ROOT(&p->p_lwp_tree);
6593 pmap_setlwpvm(lp, newvm);
6594 if (adjrefs)
6595 vmspace_rel(oldvm);
6600 * Set the vmspace for a LWP. The vmspace is almost universally set the
6601 * same as the process vmspace, but virtual kernels need to swap out contexts
6602 * on a per-lwp basis.
6604 * Caller does not necessarily hold any vmspace tokens. Caller must control
6605 * the lwp (typically be in the context of the lwp). We use a critical
6606 * section to protect against statclock and hardclock (statistics collection).
6608 void
6609 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6611 struct vmspace *oldvm;
6612 struct pmap *pmap;
6613 thread_t td;
6615 oldvm = lp->lwp_vmspace;
6617 if (oldvm != newvm) {
6618 crit_enter();
6619 td = curthread;
6620 KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6621 lp->lwp_vmspace = newvm;
6622 if (td->td_lwp == lp) {
6623 pmap = vmspace_pmap(newvm);
6624 ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6625 if (pmap->pm_active_lock & CPULOCK_EXCL)
6626 pmap_interlock_wait(newvm);
6627 #if defined(SWTCH_OPTIM_STATS)
6628 tlb_flush_count++;
6629 #endif
6630 if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6631 td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6632 if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6633 td->td_pcb->pcb_cr3_iso =
6634 vtophys(pmap->pm_pml4_iso);
6635 td->td_pcb->pcb_flags |= PCB_ISOMMU;
6636 } else {
6637 td->td_pcb->pcb_cr3_iso = 0;
6638 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6640 } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6641 td->td_pcb->pcb_cr3 = KPML4phys;
6642 td->td_pcb->pcb_cr3_iso = 0;
6643 td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6644 } else {
6645 panic("pmap_setlwpvm: unknown pmap type\n");
6649 * The MMU separation fields needs to be updated.
6650 * (it can't access the pcb directly from the
6651 * restricted user pmap).
6654 struct trampframe *tramp;
6656 tramp = &pscpu->trampoline;
6657 tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6658 tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6659 tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6660 tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6661 /* tr_pcb_rsp doesn't change */
6665 * In kernel-land we always use the normal PML4E
6666 * so the kernel is fully mapped and can also access
6667 * user memory.
6669 load_cr3(td->td_pcb->pcb_cr3);
6670 pmap = vmspace_pmap(oldvm);
6671 ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6672 mycpu->gd_cpuid);
6674 crit_exit();
6679 * Called when switching to a locked pmap, used to interlock against pmaps
6680 * undergoing modifications to prevent us from activating the MMU for the
6681 * target pmap until all such modifications have completed. We have to do
6682 * this because the thread making the modifications has already set up its
6683 * SMP synchronization mask.
6685 * This function cannot sleep!
6687 * No requirements.
6689 void
6690 pmap_interlock_wait(struct vmspace *vm)
6692 struct pmap *pmap = &vm->vm_pmap;
6694 if (pmap->pm_active_lock & CPULOCK_EXCL) {
6695 crit_enter();
6696 KKASSERT(curthread->td_critcount >= 2);
6697 DEBUG_PUSH_INFO("pmap_interlock_wait");
6698 while (pmap->pm_active_lock & CPULOCK_EXCL) {
6699 cpu_ccfence();
6700 lwkt_process_ipiq();
6702 DEBUG_POP_INFO();
6703 crit_exit();
6707 vm_offset_t
6708 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6711 if ((obj == NULL) || (size < NBPDR) ||
6712 ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6713 return addr;
6716 addr = roundup2(addr, NBPDR);
6717 return addr;
6721 * Used by kmalloc/kfree, page already exists at va
6723 vm_page_t
6724 pmap_kvtom(vm_offset_t va)
6726 pt_entry_t *ptep = vtopte(va);
6728 KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
6729 return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6733 * Initialize machine-specific shared page directory support. This
6734 * is executed when a VM object is created.
6736 void
6737 pmap_object_init(vm_object_t object)
6739 object->md.pmap_rw = NULL;
6740 object->md.pmap_ro = NULL;
6744 * Clean up machine-specific shared page directory support. This
6745 * is executed when a VM object is destroyed.
6747 void
6748 pmap_object_free(vm_object_t object)
6750 pmap_t pmap;
6752 if ((pmap = object->md.pmap_rw) != NULL) {
6753 object->md.pmap_rw = NULL;
6754 pmap_remove_noinval(pmap,
6755 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6756 CPUMASK_ASSZERO(pmap->pm_active);
6757 pmap_release(pmap);
6758 pmap_puninit(pmap);
6759 kfree(pmap, M_OBJPMAP);
6761 if ((pmap = object->md.pmap_ro) != NULL) {
6762 object->md.pmap_ro = NULL;
6763 pmap_remove_noinval(pmap,
6764 VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6765 CPUMASK_ASSZERO(pmap->pm_active);
6766 pmap_release(pmap);
6767 pmap_puninit(pmap);
6768 kfree(pmap, M_OBJPMAP);
6773 * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6774 * VM page and issue a pginfo->callback.
6776 * We are expected to dispose of any non-NULL pte_pv.
6778 static
6779 void
6780 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6781 pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
6782 pv_entry_t pt_pv, int sharept,
6783 vm_offset_t va, pt_entry_t *ptep, void *arg)
6785 struct pmap_pgscan_info *pginfo = arg;
6786 vm_page_t m;
6788 if (pte_pv) {
6790 * Try to busy the page while we hold the pte_pv locked.
6792 KKASSERT(pte_pv->pv_m);
6793 m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6794 if (vm_page_busy_try(m, TRUE) == 0) {
6795 if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6797 * The callback is issued with the pte_pv
6798 * unlocked and put away, and the pt_pv
6799 * unlocked.
6801 pv_put(pte_pv);
6802 if (pt_pv) {
6803 vm_page_wire_quick(pt_pv->pv_m);
6804 pv_unlock(pt_pv);
6806 if (pginfo->callback(pginfo, va, m) < 0)
6807 info->stop = 1;
6808 if (pt_pv) {
6809 pv_lock(pt_pv);
6810 vm_page_unwire_quick(pt_pv->pv_m);
6812 } else {
6813 vm_page_wakeup(m);
6814 pv_put(pte_pv);
6816 } else {
6817 ++pginfo->busycount;
6818 pv_put(pte_pv);
6820 } else {
6822 * Shared page table or unmanaged page (sharept or !sharept)
6824 pv_placemarker_wakeup(pmap, pte_placemark);
6828 void
6829 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6831 struct pmap_scan_info info;
6833 pginfo->offset = pginfo->beg_addr;
6834 info.pmap = pginfo->pmap;
6835 info.sva = pginfo->beg_addr;
6836 info.eva = pginfo->end_addr;
6837 info.func = pmap_pgscan_callback;
6838 info.arg = pginfo;
6839 pmap_scan(&info, 0);
6840 if (info.stop == 0)
6841 pginfo->offset = pginfo->end_addr;
6845 * Wait for a placemarker that we do not own to clear. The placemarker
6846 * in question is not necessarily set to the pindex we want, we may have
6847 * to wait on the element because we want to reserve it ourselves.
6849 * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6850 * PM_NOPLACEMARK, so it does not interfere with placemarks
6851 * which have already been woken up.
6853 static
6854 void
6855 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6857 if (*pmark != PM_NOPLACEMARK) {
6858 atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
6859 tsleep_interlock(pmark, 0);
6860 if (*pmark != PM_NOPLACEMARK)
6861 tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6866 * Wakeup a placemarker that we own. Replace the entry with
6867 * PM_NOPLACEMARK and issue a wakeup() if necessary.
6869 static
6870 void
6871 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6873 vm_pindex_t pindex;
6875 pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6876 KKASSERT(pindex != PM_NOPLACEMARK);
6877 if (pindex & PM_PLACEMARK_WAKEUP)
6878 wakeup(pmark);