xref: /dragonfly/sys/platform/pc64/x86_64/pmap.c (revision bea94db0)
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.
11  *
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.
15  *
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.
31  *
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.
43  */
44 /*
45  * Manage physical address maps for x86-64 systems.
46  *
47  * Some notes:
48  *	- The 'M'odified bit is only applicable to terminal PTEs.
49  *
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.
53  */
54 
55 #if 0 /* JG */
56 #include "opt_pmap.h"
57 #endif
58 #include "opt_msgbuf.h"
59 
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>
67 
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>
80 
81 #include <sys/user.h>
82 #include <sys/thread2.h>
83 #include <sys/spinlock2.h>
84 #include <vm/vm_page2.h>
85 
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>
96 
97 #include <ddb/ddb.h>
98 
99 #define PMAP_KEEP_PDIRS
100 #ifndef PMAP_SHPGPERPROC
101 #define PMAP_SHPGPERPROC 2000
102 #endif
103 
104 #if defined(DIAGNOSTIC)
105 #define PMAP_DIAGNOSTIC
106 #endif
107 
108 #define MINPV 2048
109 
110 /*
111  * pmap debugging will report who owns a pv lock when blocking.
112  */
113 #ifdef PMAP_DEBUG
114 
115 #define PMAP_DEBUG_DECL		,const char *func, int lineno
116 #define PMAP_DEBUG_ARGS		, __func__, __LINE__
117 #define PMAP_DEBUG_COPY		, func, lineno
118 
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)
127 
128 #define pv_free(pv, pvp)		_pv_free(pv, pvp PMAP_DEBUG_ARGS)
129 
130 #else
131 
132 #define PMAP_DEBUG_DECL
133 #define PMAP_DEBUG_ARGS
134 #define PMAP_DEBUG_COPY
135 
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)
141 
142 #endif
143 
144 /*
145  * Get PDEs and PTEs for user/kernel address space
146  */
147 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
148 
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)
154 
155 /*
156  * Given a map and a machine independent protection code,
157  * convert to a vax protection code.
158  */
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];
162 
163 struct pmap kernel_pmap;
164 struct pmap iso_pmap;
165 
166 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
167 
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;
180 
181 static int ndmpdp;
182 static vm_paddr_t dmaplimit;
183 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
184 
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 */
187 
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 */
194 
195 static uint64_t	DMPDphys;	/* phys addr of direct mapped level 2 */
196 static uint64_t	DMPDPphys;	/* phys addr of direct mapped level 3 */
197 
198 /*
199  * Data for the pv entry allocation mechanism
200  */
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;
206 
207 /*
208  * All those kernel PT submaps that BSD is so fond of
209  */
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;
214 
215 /*
216  * PMAP default PG_* bits. Needed to be able to add
217  * EPT/NPT pagetable pmap_bits for the VMM module
218  */
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 */
233 };
234 /*
235  * Crashdump maps.
236  */
237 static pt_entry_t *pt_crashdumpmap;
238 static caddr_t crashdumpmap;
239 
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");
267 
268 static int pmap_nx_enable = 0;
269 /* needs manual TUNABLE in early probe, see below */
270 
271 /* Standard user access funtions */
272 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
273     size_t *lencopied);
274 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
275 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
276 extern int std_fubyte (const uint8_t *base);
277 extern int std_subyte (uint8_t *base, uint8_t byte);
278 extern int32_t std_fuword32 (const uint32_t *base);
279 extern int64_t std_fuword64 (const uint64_t *base);
280 extern int std_suword64 (uint64_t *base, uint64_t word);
281 extern int std_suword32 (uint32_t *base, int word);
282 extern uint32_t std_swapu32 (volatile uint32_t *base, uint32_t v);
283 extern uint64_t std_swapu64 (volatile uint64_t *base, uint64_t v);
284 
285 static void pv_hold(pv_entry_t pv);
286 static int _pv_hold_try(pv_entry_t pv
287 				PMAP_DEBUG_DECL);
288 static void pv_drop(pv_entry_t pv);
289 static void _pv_lock(pv_entry_t pv
290 				PMAP_DEBUG_DECL);
291 static void pv_unlock(pv_entry_t pv);
292 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
293 				PMAP_DEBUG_DECL);
294 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp
295 				PMAP_DEBUG_DECL);
296 static void _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL);
297 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex,
298 				vm_pindex_t **pmarkp, int *errorp);
299 static void pv_put(pv_entry_t pv);
300 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
301 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
302 		      pv_entry_t *pvpp);
303 static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
304 		      pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
305 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
306 			pmap_inval_bulk_t *bulk, int destroy);
307 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
308 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
309 			pmap_inval_bulk_t *bulk);
310 
311 struct pmap_scan_info;
312 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
313 		      pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
314 		      pv_entry_t pt_pv, int sharept,
315 		      vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
316 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
317 		      pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
318 		      pv_entry_t pt_pv, int sharept,
319 		      vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
320 
321 static void x86_64_protection_init (void);
322 static void create_pagetables(vm_paddr_t *firstaddr);
323 static void pmap_remove_all (vm_page_t m);
324 static boolean_t pmap_testbit (vm_page_t m, int bit);
325 
326 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
327 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
328 
329 static void pmap_pinit_defaults(struct pmap *pmap);
330 static void pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark);
331 static void pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark);
332 
333 static int
334 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
335 {
336 	if (pv1->pv_pindex < pv2->pv_pindex)
337 		return(-1);
338 	if (pv1->pv_pindex > pv2->pv_pindex)
339 		return(1);
340 	return(0);
341 }
342 
343 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
344              pv_entry_compare, vm_pindex_t, pv_pindex);
345 
346 static __inline
347 void
348 pmap_page_stats_adding(vm_page_t m)
349 {
350 	globaldata_t gd = mycpu;
351 
352 	if (TAILQ_EMPTY(&m->md.pv_list)) {
353 		++gd->gd_vmtotal.t_arm;
354 	} else if (TAILQ_FIRST(&m->md.pv_list) ==
355 		   TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
356 		++gd->gd_vmtotal.t_armshr;
357 		++gd->gd_vmtotal.t_avmshr;
358 	} else {
359 		++gd->gd_vmtotal.t_avmshr;
360 	}
361 }
362 
363 static __inline
364 void
365 pmap_page_stats_deleting(vm_page_t m)
366 {
367 	globaldata_t gd = mycpu;
368 
369 	if (TAILQ_EMPTY(&m->md.pv_list)) {
370 		--gd->gd_vmtotal.t_arm;
371 	} else if (TAILQ_FIRST(&m->md.pv_list) ==
372 		   TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
373 		--gd->gd_vmtotal.t_armshr;
374 		--gd->gd_vmtotal.t_avmshr;
375 	} else {
376 		--gd->gd_vmtotal.t_avmshr;
377 	}
378 }
379 
380 /*
381  * This is an ineligent crowbar to prevent heavily threaded programs
382  * from creating long live-locks in the pmap code when pmap_mmu_optimize
383  * is enabled.  Without it a pmap-local page table page can wind up being
384  * constantly created and destroyed (without injury, but also without
385  * progress) as the optimization tries to switch to the object's shared page
386  * table page.
387  */
388 static __inline void
389 pmap_softwait(pmap_t pmap)
390 {
391 	while (pmap->pm_softhold) {
392 		tsleep_interlock(&pmap->pm_softhold, 0);
393 		if (pmap->pm_softhold)
394 			tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
395 	}
396 }
397 
398 static __inline void
399 pmap_softhold(pmap_t pmap)
400 {
401 	while (atomic_swap_int(&pmap->pm_softhold, 1) == 1) {
402 		tsleep_interlock(&pmap->pm_softhold, 0);
403 		if (atomic_swap_int(&pmap->pm_softhold, 1) == 1)
404 			tsleep(&pmap->pm_softhold, PINTERLOCKED, "mmopt", 0);
405 	}
406 }
407 
408 static __inline void
409 pmap_softdone(pmap_t pmap)
410 {
411 	atomic_swap_int(&pmap->pm_softhold, 0);
412 	wakeup(&pmap->pm_softhold);
413 }
414 
415 /*
416  * Move the kernel virtual free pointer to the next
417  * 2MB.  This is used to help improve performance
418  * by using a large (2MB) page for much of the kernel
419  * (.text, .data, .bss)
420  */
421 static
422 vm_offset_t
423 pmap_kmem_choose(vm_offset_t addr)
424 {
425 	vm_offset_t newaddr = addr;
426 
427 	newaddr = roundup2(addr, NBPDR);
428 	return newaddr;
429 }
430 
431 /*
432  * Returns the pindex of a page table entry (representing a terminal page).
433  * There are NUPTE_TOTAL page table entries possible (a huge number)
434  *
435  * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
436  * We want to properly translate negative KVAs.
437  */
438 static __inline
439 vm_pindex_t
440 pmap_pte_pindex(vm_offset_t va)
441 {
442 	return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
443 }
444 
445 /*
446  * Returns the pindex of a page table.
447  */
448 static __inline
449 vm_pindex_t
450 pmap_pt_pindex(vm_offset_t va)
451 {
452 	return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
453 }
454 
455 /*
456  * Returns the pindex of a page directory.
457  */
458 static __inline
459 vm_pindex_t
460 pmap_pd_pindex(vm_offset_t va)
461 {
462 	return (NUPTE_TOTAL + NUPT_TOTAL +
463 		((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
464 }
465 
466 static __inline
467 vm_pindex_t
468 pmap_pdp_pindex(vm_offset_t va)
469 {
470 	return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
471 		((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
472 }
473 
474 static __inline
475 vm_pindex_t
476 pmap_pml4_pindex(void)
477 {
478 	return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
479 }
480 
481 /*
482  * Return various clipped indexes for a given VA
483  *
484  * Returns the index of a pt in a page directory, representing a page
485  * table.
486  */
487 static __inline
488 vm_pindex_t
489 pmap_pt_index(vm_offset_t va)
490 {
491 	return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
492 }
493 
494 /*
495  * Returns the index of a pd in a page directory page, representing a page
496  * directory.
497  */
498 static __inline
499 vm_pindex_t
500 pmap_pd_index(vm_offset_t va)
501 {
502 	return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
503 }
504 
505 /*
506  * Returns the index of a pdp in the pml4 table, representing a page
507  * directory page.
508  */
509 static __inline
510 vm_pindex_t
511 pmap_pdp_index(vm_offset_t va)
512 {
513 	return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
514 }
515 
516 /*
517  * Locate the requested pt_entry
518  */
519 static __inline
520 pv_entry_t
521 pv_entry_lookup(pmap_t pmap, vm_pindex_t pindex)
522 {
523 	pv_entry_t pv;
524 
525 	if (pindex < pmap_pt_pindex(0))
526 		pv = pmap->pm_pvhint_pte;
527 	else if (pindex < pmap_pd_pindex(0))
528 		pv = pmap->pm_pvhint_pt;
529 	else
530 		pv = NULL;
531 	cpu_ccfence();
532 	if (pv == NULL || pv->pv_pmap != pmap) {
533 		pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot,
534 						pindex);
535 	} else if (pv->pv_pindex != pindex) {
536 		pv = pv_entry_rb_tree_RB_LOOKUP_REL(&pmap->pm_pvroot,
537 						    pindex, pv);
538 	}
539 	return pv;
540 }
541 
542 /*
543  * pmap_pte_quick:
544  *
545  *	Super fast pmap_pte routine best used when scanning the pv lists.
546  *	This eliminates many course-grained invltlb calls.  Note that many of
547  *	the pv list scans are across different pmaps and it is very wasteful
548  *	to do an entire invltlb when checking a single mapping.
549  */
550 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
551 
552 static
553 pt_entry_t *
554 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
555 {
556 	return pmap_pte(pmap, va);
557 }
558 
559 /*
560  * The placemarker hash must be broken up into four zones so lock
561  * ordering semantics continue to work (e.g. pte, pt, pd, then pdp).
562  *
563  * Placemarkers are used to 'lock' page table indices that do not have
564  * a pv_entry.  This allows the pmap to support managed and unmanaged
565  * pages and shared page tables.
566  */
567 #define PM_PLACE_BASE	(PM_PLACEMARKS >> 2)
568 
569 static __inline
570 vm_pindex_t *
571 pmap_placemarker_hash(pmap_t pmap, vm_pindex_t pindex)
572 {
573 	int hi;
574 
575 	if (pindex < pmap_pt_pindex(0))		/* zone 0 - PTE */
576 		hi = 0;
577 	else if (pindex < pmap_pd_pindex(0))	/* zone 1 - PT */
578 		hi = PM_PLACE_BASE;
579 	else if (pindex < pmap_pdp_pindex(0))	/* zone 2 - PD */
580 		hi = PM_PLACE_BASE << 1;
581 	else					/* zone 3 - PDP (and PML4E) */
582 		hi = PM_PLACE_BASE | (PM_PLACE_BASE << 1);
583 	hi += pindex & (PM_PLACE_BASE - 1);
584 
585 	return (&pmap->pm_placemarks[hi]);
586 }
587 
588 
589 /*
590  * Generic procedure to index a pte from a pt, pd, or pdp.
591  *
592  * NOTE: Normally passed pindex as pmap_xx_index().  pmap_xx_pindex() is NOT
593  *	 a page table page index but is instead of PV lookup index.
594  */
595 static
596 void *
597 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
598 {
599 	pt_entry_t *pte;
600 
601 	pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
602 	return(&pte[pindex]);
603 }
604 
605 /*
606  * Return pointer to PDP slot in the PML4
607  */
608 static __inline
609 pml4_entry_t *
610 pmap_pdp(pmap_t pmap, vm_offset_t va)
611 {
612 	return (&pmap->pm_pml4[pmap_pdp_index(va)]);
613 }
614 
615 /*
616  * Return pointer to PD slot in the PDP given a pointer to the PDP
617  */
618 static __inline
619 pdp_entry_t *
620 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
621 {
622 	pdp_entry_t *pd;
623 
624 	pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
625 	return (&pd[pmap_pd_index(va)]);
626 }
627 
628 /*
629  * Return pointer to PD slot in the PDP.
630  */
631 static __inline
632 pdp_entry_t *
633 pmap_pd(pmap_t pmap, vm_offset_t va)
634 {
635 	pml4_entry_t *pdp;
636 
637 	pdp = pmap_pdp(pmap, va);
638 	if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
639 		return NULL;
640 	return (pmap_pdp_to_pd(*pdp, va));
641 }
642 
643 /*
644  * Return pointer to PT slot in the PD given a pointer to the PD
645  */
646 static __inline
647 pd_entry_t *
648 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
649 {
650 	pd_entry_t *pt;
651 
652 	pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
653 	return (&pt[pmap_pt_index(va)]);
654 }
655 
656 /*
657  * Return pointer to PT slot in the PD
658  *
659  * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
660  *		     so we cannot lookup the PD via the PDP.  Instead we
661  *		     must look it up via the pmap.
662  */
663 static __inline
664 pd_entry_t *
665 pmap_pt(pmap_t pmap, vm_offset_t va)
666 {
667 	pdp_entry_t *pd;
668 	pv_entry_t pv;
669 	vm_pindex_t pd_pindex;
670 	vm_paddr_t phys;
671 
672 	if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
673 		pd_pindex = pmap_pd_pindex(va);
674 		spin_lock_shared(&pmap->pm_spin);
675 		pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
676 		if (pv == NULL || pv->pv_m == NULL) {
677 			spin_unlock_shared(&pmap->pm_spin);
678 			return NULL;
679 		}
680 		phys = VM_PAGE_TO_PHYS(pv->pv_m);
681 		spin_unlock_shared(&pmap->pm_spin);
682 		return (pmap_pd_to_pt(phys, va));
683 	} else {
684 		pd = pmap_pd(pmap, va);
685 		if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
686 			 return NULL;
687 		return (pmap_pd_to_pt(*pd, va));
688 	}
689 }
690 
691 /*
692  * Return pointer to PTE slot in the PT given a pointer to the PT
693  */
694 static __inline
695 pt_entry_t *
696 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
697 {
698 	pt_entry_t *pte;
699 
700 	pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
701 	return (&pte[pmap_pte_index(va)]);
702 }
703 
704 /*
705  * Return pointer to PTE slot in the PT
706  */
707 static __inline
708 pt_entry_t *
709 pmap_pte(pmap_t pmap, vm_offset_t va)
710 {
711 	pd_entry_t *pt;
712 
713 	pt = pmap_pt(pmap, va);
714 	if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
715 		 return NULL;
716 	if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
717 		return ((pt_entry_t *)pt);
718 	return (pmap_pt_to_pte(*pt, va));
719 }
720 
721 /*
722  * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
723  * the PT layer.  This will speed up core pmap operations considerably.
724  *
725  * NOTE: The pmap spinlock does not need to be held but the passed-in pv
726  *	 must be in a known associated state (typically by being locked when
727  *	 the pmap spinlock isn't held).  We allow the race for that case.
728  *
729  * NOTE: pm_pvhint* is only accessed (read) with the spin-lock held, using
730  *	 cpu_ccfence() to prevent compiler optimizations from reloading the
731  *	 field.
732  */
733 static __inline
734 void
735 pv_cache(pv_entry_t pv, vm_pindex_t pindex)
736 {
737 	if (pindex < pmap_pt_pindex(0)) {
738 		if (pv->pv_pmap)
739 			pv->pv_pmap->pm_pvhint_pte = pv;
740 	} else if (pindex < pmap_pd_pindex(0)) {
741 		if (pv->pv_pmap)
742 			pv->pv_pmap->pm_pvhint_pt = pv;
743 	}
744 }
745 
746 
747 /*
748  * Return address of PT slot in PD (KVM only)
749  *
750  * Cannot be used for user page tables because it might interfere with
751  * the shared page-table-page optimization (pmap_mmu_optimize).
752  */
753 static __inline
754 pd_entry_t *
755 vtopt(vm_offset_t va)
756 {
757 	uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
758 				  NPML4EPGSHIFT)) - 1);
759 
760 	return (PDmap + ((va >> PDRSHIFT) & mask));
761 }
762 
763 /*
764  * KVM - return address of PTE slot in PT
765  */
766 static __inline
767 pt_entry_t *
768 vtopte(vm_offset_t va)
769 {
770 	uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
771 				  NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
772 
773 	return (PTmap + ((va >> PAGE_SHIFT) & mask));
774 }
775 
776 /*
777  * Returns the physical address translation from va for a user address.
778  * (vm_paddr_t)-1 is returned on failure.
779  */
780 vm_paddr_t
781 uservtophys(vm_offset_t va)
782 {
783 	uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
784 				  NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
785 	vm_paddr_t pa;
786 	pt_entry_t pte;
787 	pmap_t pmap;
788 
789 	pmap = vmspace_pmap(mycpu->gd_curthread->td_lwp->lwp_vmspace);
790 	pa = (vm_paddr_t)-1;
791 	if (va < VM_MAX_USER_ADDRESS) {
792 		pte = kreadmem64(PTmap + ((va >> PAGE_SHIFT) & mask));
793 		if (pte & pmap->pmap_bits[PG_V_IDX])
794 			pa = (pte & PG_FRAME) | (va & PAGE_MASK);
795 	}
796 	return pa;
797 }
798 
799 static uint64_t
800 allocpages(vm_paddr_t *firstaddr, long n)
801 {
802 	uint64_t ret;
803 
804 	ret = *firstaddr;
805 	bzero((void *)ret, n * PAGE_SIZE);
806 	*firstaddr += n * PAGE_SIZE;
807 	return (ret);
808 }
809 
810 static
811 void
812 create_pagetables(vm_paddr_t *firstaddr)
813 {
814 	long i;		/* must be 64 bits */
815 	long nkpt_base;
816 	long nkpt_phys;
817 	long nkpd_phys;
818 	int j;
819 
820 	/*
821 	 * We are running (mostly) V=P at this point
822 	 *
823 	 * Calculate how many 1GB PD entries in our PDP pages are needed
824 	 * for the DMAP.  This is only allocated if the system does not
825 	 * support 1GB pages.  Otherwise ndmpdp is simply a count of
826 	 * the number of 1G terminal entries in our PDP pages are needed.
827 	 *
828 	 * NOTE: Maxmem is in pages
829 	 */
830 	ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
831 	if (ndmpdp < 4)		/* Minimum 4GB of dirmap */
832 		ndmpdp = 4;
833 	KKASSERT(ndmpdp <= NDMPML4E * NPML4EPG);
834 
835 	/*
836 	 * Starting at KERNBASE - map all 2G worth of page table pages.
837 	 * KERNBASE is offset -2G from the end of kvm.  This will accomodate
838 	 * all KVM allocations above KERNBASE, including the SYSMAPs below.
839 	 *
840 	 * We do this by allocating 2*512 PT pages.  Each PT page can map
841 	 * 2MB, for 2GB total.
842 	 */
843 	nkpt_base = (NPDPEPG - KPDPI) * NPTEPG;	/* typically 2 x 512 */
844 
845 	/*
846 	 * Starting at the beginning of kvm (VM_MIN_KERNEL_ADDRESS),
847 	 * Calculate how many page table pages we need to preallocate
848 	 * for early vm_map allocations.
849 	 *
850 	 * A few extra won't hurt, they will get used up in the running
851 	 * system.
852 	 *
853 	 * vm_page array
854 	 * initial pventry's
855 	 */
856 	nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
857 	nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
858 	nkpt_phys += 128;	/* a few extra */
859 
860 	/*
861 	 * The highest value nkpd_phys can be set to is
862 	 * NKPDPE - (NPDPEPG - KPDPI) (i.e. NKPDPE - 2).
863 	 *
864 	 * Doing so would cause all PD pages to be pre-populated for
865 	 * a maximal KVM space (approximately 16*512 pages, or 32MB.
866 	 * We can save memory by not doing this.
867 	 */
868 	nkpd_phys = (nkpt_phys + NPDPEPG - 1) / NPDPEPG;
869 
870 	/*
871 	 * Allocate pages
872 	 *
873 	 * Normally NKPML4E=1-16 (1-16 kernel PDP page)
874 	 * Normally NKPDPE= NKPML4E*512-1 (511 min kernel PD pages)
875 	 *
876 	 * Only allocate enough PD pages
877 	 * NOTE: We allocate all kernel PD pages up-front, typically
878 	 *	 ~511G of KVM, requiring 511 PD pages.
879 	 */
880 	KPTbase = allocpages(firstaddr, nkpt_base);	/* KERNBASE to end */
881 	KPTphys = allocpages(firstaddr, nkpt_phys);	/* KVA start */
882 	KPML4phys = allocpages(firstaddr, 1);		/* recursive PML4 map */
883 	KPDPphys = allocpages(firstaddr, NKPML4E);	/* kernel PDP pages */
884 	KPDphys = allocpages(firstaddr, nkpd_phys);	/* kernel PD pages */
885 
886 	/*
887 	 * Alloc PD pages for the area starting at KERNBASE.
888 	 */
889 	KPDbase = allocpages(firstaddr, NPDPEPG - KPDPI);
890 
891 	/*
892 	 * Stuff for our DMAP
893 	 */
894 	DMPDPphys = allocpages(firstaddr, NDMPML4E);
895 	if ((amd_feature & AMDID_PAGE1GB) == 0)
896 		DMPDphys = allocpages(firstaddr, ndmpdp);
897 	dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
898 
899 	/*
900 	 * Fill in the underlying page table pages for the area around
901 	 * KERNBASE.  This remaps low physical memory to KERNBASE.
902 	 *
903 	 * Read-only from zero to physfree
904 	 * XXX not fully used, underneath 2M pages
905 	 */
906 	for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
907 		((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
908 		((pt_entry_t *)KPTbase)[i] |=
909 		    pmap_bits_default[PG_RW_IDX] |
910 		    pmap_bits_default[PG_V_IDX] |
911 		    pmap_bits_default[PG_G_IDX];
912 	}
913 
914 	/*
915 	 * Now map the initial kernel page tables.  One block of page
916 	 * tables is placed at the beginning of kernel virtual memory,
917 	 * and another block is placed at KERNBASE to map the kernel binary,
918 	 * data, bss, and initial pre-allocations.
919 	 */
920 	for (i = 0; i < nkpt_base; i++) {
921 		((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
922 		((pd_entry_t *)KPDbase)[i] |=
923 		    pmap_bits_default[PG_RW_IDX] |
924 		    pmap_bits_default[PG_V_IDX];
925 	}
926 	for (i = 0; i < nkpt_phys; i++) {
927 		((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
928 		((pd_entry_t *)KPDphys)[i] |=
929 		    pmap_bits_default[PG_RW_IDX] |
930 		    pmap_bits_default[PG_V_IDX];
931 	}
932 
933 	/*
934 	 * Map from zero to end of allocations using 2M pages as an
935 	 * optimization.  This will bypass some of the KPTBase pages
936 	 * above in the KERNBASE area.
937 	 */
938 	for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
939 		((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
940 		((pd_entry_t *)KPDbase)[i] |=
941 		    pmap_bits_default[PG_RW_IDX] |
942 		    pmap_bits_default[PG_V_IDX] |
943 		    pmap_bits_default[PG_PS_IDX] |
944 		    pmap_bits_default[PG_G_IDX];
945 	}
946 
947 	/*
948 	 * Load PD addresses into the PDP pages for primary KVA space to
949 	 * cover existing page tables.  PD's for KERNBASE are handled in
950 	 * the next loop.
951 	 *
952 	 * expected to pre-populate all of its PDs.  See NKPDPE in vmparam.h.
953 	 */
954 	for (i = 0; i < nkpd_phys; i++) {
955 		((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] =
956 				KPDphys + (i << PAGE_SHIFT);
957 		((pdp_entry_t *)KPDPphys)[NKPML4E * NPDPEPG - NKPDPE + i] |=
958 		    pmap_bits_default[PG_RW_IDX] |
959 		    pmap_bits_default[PG_V_IDX] |
960 		    pmap_bits_default[PG_A_IDX];
961 	}
962 
963 	/*
964 	 * Load PDs for KERNBASE to the end
965 	 */
966 	i = (NKPML4E - 1) * NPDPEPG + KPDPI;
967 	for (j = 0; j < NPDPEPG - KPDPI; ++j) {
968 		((pdp_entry_t *)KPDPphys)[i + j] =
969 				KPDbase + (j << PAGE_SHIFT);
970 		((pdp_entry_t *)KPDPphys)[i + j] |=
971 		    pmap_bits_default[PG_RW_IDX] |
972 		    pmap_bits_default[PG_V_IDX] |
973 		    pmap_bits_default[PG_A_IDX];
974 	}
975 
976 	/*
977 	 * Now set up the direct map space using either 2MB or 1GB pages
978 	 * Preset PG_M and PG_A because demotion expects it.
979 	 *
980 	 * When filling in entries in the PD pages make sure any excess
981 	 * entries are set to zero as we allocated enough PD pages
982 	 */
983 	if ((amd_feature & AMDID_PAGE1GB) == 0) {
984 		/*
985 		 * Use 2MB pages
986 		 */
987 		for (i = 0; i < NPDEPG * ndmpdp; i++) {
988 			((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
989 			((pd_entry_t *)DMPDphys)[i] |=
990 			    pmap_bits_default[PG_RW_IDX] |
991 			    pmap_bits_default[PG_V_IDX] |
992 			    pmap_bits_default[PG_PS_IDX] |
993 			    pmap_bits_default[PG_G_IDX] |
994 			    pmap_bits_default[PG_M_IDX] |
995 			    pmap_bits_default[PG_A_IDX];
996 		}
997 
998 		/*
999 		 * And the direct map space's PDP
1000 		 */
1001 		for (i = 0; i < ndmpdp; i++) {
1002 			((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
1003 							(i << PAGE_SHIFT);
1004 			((pdp_entry_t *)DMPDPphys)[i] |=
1005 			    pmap_bits_default[PG_RW_IDX] |
1006 			    pmap_bits_default[PG_V_IDX];
1007 		}
1008 	} else {
1009 		/*
1010 		 * 1GB pages
1011 		 */
1012 		for (i = 0; i < ndmpdp; i++) {
1013 			((pdp_entry_t *)DMPDPphys)[i] =
1014 						(vm_paddr_t)i << PDPSHIFT;
1015 			((pdp_entry_t *)DMPDPphys)[i] |=
1016 			    pmap_bits_default[PG_RW_IDX] |
1017 			    pmap_bits_default[PG_V_IDX] |
1018 			    pmap_bits_default[PG_PS_IDX] |
1019 			    pmap_bits_default[PG_G_IDX] |
1020 			    pmap_bits_default[PG_M_IDX] |
1021 			    pmap_bits_default[PG_A_IDX];
1022 		}
1023 	}
1024 
1025 	/* And recursively map PML4 to itself in order to get PTmap */
1026 	((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
1027 	((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
1028 	    pmap_bits_default[PG_RW_IDX] |
1029 	    pmap_bits_default[PG_V_IDX] |
1030 	    pmap_bits_default[PG_A_IDX];
1031 
1032 	/*
1033 	 * Connect the Direct Map slots up to the PML4
1034 	 */
1035 	for (j = 0; j < NDMPML4E; ++j) {
1036 		((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
1037 		    (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
1038 		    pmap_bits_default[PG_RW_IDX] |
1039 		    pmap_bits_default[PG_V_IDX] |
1040 		    pmap_bits_default[PG_A_IDX];
1041 	}
1042 
1043 	/*
1044 	 * Connect the KVA slot up to the PML4
1045 	 */
1046 	for (j = 0; j < NKPML4E; ++j) {
1047 		((pdp_entry_t *)KPML4phys)[KPML4I + j] =
1048 		    KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT);
1049 		((pdp_entry_t *)KPML4phys)[KPML4I + j] |=
1050 		    pmap_bits_default[PG_RW_IDX] |
1051 		    pmap_bits_default[PG_V_IDX] |
1052 		    pmap_bits_default[PG_A_IDX];
1053 	}
1054 	cpu_mfence();
1055 	cpu_invltlb();
1056 }
1057 
1058 /*
1059  *	Bootstrap the system enough to run with virtual memory.
1060  *
1061  *	On x86_64 this is called after mapping has already been enabled
1062  *	and just syncs the pmap module with what has already been done.
1063  *	[We can't call it easily with mapping off since the kernel is not
1064  *	mapped with PA == VA, hence we would have to relocate every address
1065  *	from the linked base (virtual) address "KERNBASE" to the actual
1066  *	(physical) address starting relative to 0]
1067  */
1068 void
1069 pmap_bootstrap(vm_paddr_t *firstaddr)
1070 {
1071 	vm_offset_t va;
1072 	pt_entry_t *pte;
1073 	int i;
1074 
1075 	KvaStart = VM_MIN_KERNEL_ADDRESS;
1076 	KvaEnd = VM_MAX_KERNEL_ADDRESS;
1077 	KvaSize = KvaEnd - KvaStart;
1078 
1079 	avail_start = *firstaddr;
1080 
1081 	/*
1082 	 * Create an initial set of page tables to run the kernel in.
1083 	 */
1084 	create_pagetables(firstaddr);
1085 
1086 	virtual2_start = KvaStart;
1087 	virtual2_end = PTOV_OFFSET;
1088 
1089 	virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
1090 	virtual_start = pmap_kmem_choose(virtual_start);
1091 
1092 	virtual_end = VM_MAX_KERNEL_ADDRESS;
1093 
1094 	/* XXX do %cr0 as well */
1095 	load_cr4(rcr4() | CR4_PGE | CR4_PSE);
1096 	load_cr3(KPML4phys);
1097 
1098 	/*
1099 	 * Initialize protection array.
1100 	 */
1101 	x86_64_protection_init();
1102 
1103 	/*
1104 	 * The kernel's pmap is statically allocated so we don't have to use
1105 	 * pmap_create, which is unlikely to work correctly at this part of
1106 	 * the boot sequence (XXX and which no longer exists).
1107 	 */
1108 	kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
1109 	kernel_pmap.pm_count = 1;
1110 	CPUMASK_ASSALLONES(kernel_pmap.pm_active);
1111 	RB_INIT(&kernel_pmap.pm_pvroot);
1112 	spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
1113 	for (i = 0; i < PM_PLACEMARKS; ++i)
1114 		kernel_pmap.pm_placemarks[i] = PM_NOPLACEMARK;
1115 
1116 	/*
1117 	 * Reserve some special page table entries/VA space for temporary
1118 	 * mapping of pages.
1119 	 */
1120 #define	SYSMAP(c, p, v, n)	\
1121 	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1122 
1123 	va = virtual_start;
1124 	pte = vtopte(va);
1125 
1126 	/*
1127 	 * CMAP1/CMAP2 are used for zeroing and copying pages.
1128 	 */
1129 	SYSMAP(caddr_t, CMAP1, CADDR1, 1)
1130 
1131 	/*
1132 	 * Crashdump maps.
1133 	 */
1134 	SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
1135 
1136 	/*
1137 	 * ptvmmap is used for reading arbitrary physical pages via
1138 	 * /dev/mem.
1139 	 */
1140 	SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
1141 
1142 	/*
1143 	 * msgbufp is used to map the system message buffer.
1144 	 * XXX msgbufmap is not used.
1145 	 */
1146 	SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
1147 	       atop(round_page(MSGBUF_SIZE)))
1148 
1149 	virtual_start = va;
1150 	virtual_start = pmap_kmem_choose(virtual_start);
1151 
1152 	*CMAP1 = 0;
1153 
1154 	/*
1155 	 * PG_G is terribly broken on SMP because we IPI invltlb's in some
1156 	 * cases rather then invl1pg.  Actually, I don't even know why it
1157 	 * works under UP because self-referential page table mappings
1158 	 */
1159 //	pgeflag = 0;
1160 
1161 	cpu_invltlb();
1162 
1163 	/* Initialize the PAT MSR */
1164 	pmap_init_pat();
1165 	pmap_pinit_defaults(&kernel_pmap);
1166 
1167 	TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
1168 			  &pmap_fast_kernel_cpusync);
1169 
1170 }
1171 
1172 /*
1173  * Setup the PAT MSR.
1174  */
1175 void
1176 pmap_init_pat(void)
1177 {
1178 	uint64_t pat_msr;
1179 	u_long cr0, cr4;
1180 
1181 	/*
1182 	 * Default values mapping PATi,PCD,PWT bits at system reset.
1183 	 * The default values effectively ignore the PATi bit by
1184 	 * repeating the encodings for 0-3 in 4-7, and map the PCD
1185 	 * and PWT bit combinations to the expected PAT types.
1186 	 */
1187 	pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |	/* 000 */
1188 		  PAT_VALUE(1, PAT_WRITE_THROUGH) |	/* 001 */
1189 		  PAT_VALUE(2, PAT_UNCACHED) |		/* 010 */
1190 		  PAT_VALUE(3, PAT_UNCACHEABLE) |	/* 011 */
1191 		  PAT_VALUE(4, PAT_WRITE_BACK) |	/* 100 */
1192 		  PAT_VALUE(5, PAT_WRITE_THROUGH) |	/* 101 */
1193 		  PAT_VALUE(6, PAT_UNCACHED) |		/* 110 */
1194 		  PAT_VALUE(7, PAT_UNCACHEABLE);	/* 111 */
1195 	pat_pte_index[PAT_WRITE_BACK]	= 0;
1196 	pat_pte_index[PAT_WRITE_THROUGH]= 0         | X86_PG_NC_PWT;
1197 	pat_pte_index[PAT_UNCACHED]	= X86_PG_NC_PCD;
1198 	pat_pte_index[PAT_UNCACHEABLE]	= X86_PG_NC_PCD | X86_PG_NC_PWT;
1199 	pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1200 	pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1201 
1202 	if (cpu_feature & CPUID_PAT) {
1203 		/*
1204 		 * If we support the PAT then set-up entries for
1205 		 * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1206 		 * 5 and 6.
1207 		 */
1208 		pat_msr = (pat_msr & ~PAT_MASK(5)) |
1209 			  PAT_VALUE(5, PAT_WRITE_PROTECTED);
1210 		pat_msr = (pat_msr & ~PAT_MASK(6)) |
1211 			  PAT_VALUE(6, PAT_WRITE_COMBINING);
1212 		pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1213 		pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PCD;
1214 
1215 		/*
1216 		 * Then enable the PAT
1217 		 */
1218 
1219 		/* Disable PGE. */
1220 		cr4 = rcr4();
1221 		load_cr4(cr4 & ~CR4_PGE);
1222 
1223 		/* Disable caches (CD = 1, NW = 0). */
1224 		cr0 = rcr0();
1225 		load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1226 
1227 		/* Flushes caches and TLBs. */
1228 		wbinvd();
1229 		cpu_invltlb();
1230 
1231 		/* Update PAT and index table. */
1232 		wrmsr(MSR_PAT, pat_msr);
1233 
1234 		/* Flush caches and TLBs again. */
1235 		wbinvd();
1236 		cpu_invltlb();
1237 
1238 		/* Restore caches and PGE. */
1239 		load_cr0(cr0);
1240 		load_cr4(cr4);
1241 		PatMsr = pat_msr;
1242 	}
1243 }
1244 
1245 /*
1246  * Set 4mb pdir for mp startup
1247  */
1248 void
1249 pmap_set_opt(void)
1250 {
1251 	if (cpu_feature & CPUID_PSE) {
1252 		load_cr4(rcr4() | CR4_PSE);
1253 		if (mycpu->gd_cpuid == 0) 	/* only on BSP */
1254 			cpu_invltlb();
1255 	}
1256 }
1257 
1258 /*
1259  * Early initialization of the pmap module.
1260  *
1261  * Called by vm_init, to initialize any structures that the pmap
1262  * system needs to map virtual memory.  pmap_init has been enhanced to
1263  * support in a fairly consistant way, discontiguous physical memory.
1264  */
1265 void
1266 pmap_init(void)
1267 {
1268 	vm_pindex_t initial_pvs;
1269 	vm_pindex_t i;
1270 
1271 	/*
1272 	 * Allocate memory for random pmap data structures.  Includes the
1273 	 * pv_head_table.
1274 	 */
1275 	for (i = 0; i < vm_page_array_size; i++) {
1276 		vm_page_t m;
1277 
1278 		m = &vm_page_array[i];
1279 		TAILQ_INIT(&m->md.pv_list);
1280 	}
1281 
1282 	/*
1283 	 * init the pv free list
1284 	 */
1285 	initial_pvs = vm_page_array_size;
1286 	if (initial_pvs < MINPV)
1287 		initial_pvs = MINPV;
1288 	pvzone = &pvzone_store;
1289 	pvinit = (void *)kmem_alloc(&kernel_map,
1290 				    initial_pvs * sizeof (struct pv_entry),
1291 				    VM_SUBSYS_PVENTRY);
1292 	zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1293 		  pvinit, initial_pvs);
1294 
1295 	/*
1296 	 * Now it is safe to enable pv_table recording.
1297 	 */
1298 	pmap_initialized = TRUE;
1299 }
1300 
1301 /*
1302  * Initialize the address space (zone) for the pv_entries.  Set a
1303  * high water mark so that the system can recover from excessive
1304  * numbers of pv entries.
1305  *
1306  * Also create the kernel page table template for isolated user
1307  * pmaps.
1308  */
1309 static void pmap_init_iso_range(vm_offset_t base, size_t bytes);
1310 static void pmap_init2_iso_pmap(void);
1311 #if 0
1312 static void dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base);
1313 #endif
1314 
1315 void
1316 pmap_init2(void)
1317 {
1318 	vm_pindex_t shpgperproc = PMAP_SHPGPERPROC;
1319 	vm_pindex_t entry_max;
1320 
1321 	TUNABLE_LONG_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1322 	pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1323 	TUNABLE_LONG_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1324 	pv_entry_high_water = 9 * (pv_entry_max / 10);
1325 
1326 	/*
1327 	 * Subtract out pages already installed in the zone (hack)
1328 	 */
1329 	entry_max = pv_entry_max - vm_page_array_size;
1330 	if (entry_max <= 0)
1331 		entry_max = 1;
1332 
1333 	zinitna(pvzone, NULL, 0, entry_max, ZONE_INTERRUPT);
1334 
1335 	/*
1336 	 * Enable dynamic deletion of empty higher-level page table pages
1337 	 * by default only if system memory is < 8GB (use 7GB for slop).
1338 	 * This can save a little memory, but imposes significant
1339 	 * performance overhead for things like bulk builds, and for programs
1340 	 * which do a lot of memory mapping and memory unmapping.
1341 	 */
1342 	if (pmap_dynamic_delete < 0) {
1343 		if (vmstats.v_page_count < 7LL * 1024 * 1024 * 1024 / PAGE_SIZE)
1344 			pmap_dynamic_delete = 1;
1345 		else
1346 			pmap_dynamic_delete = 0;
1347 	}
1348 
1349 	/*
1350 	 * Automatic detection of Intel meltdown bug requiring user/kernel
1351 	 * mmap isolation.
1352 	 *
1353 	 * Currently there are so many Intel cpu's impacted that its better
1354 	 * to whitelist future Intel CPUs.  Most? AMD cpus are not impacted
1355 	 * so the default is off for AMD.
1356 	 */
1357 	if (meltdown_mitigation < 0) {
1358 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
1359 			meltdown_mitigation = 1;
1360 		else
1361 			meltdown_mitigation = 0;
1362 	}
1363 	if (meltdown_mitigation) {
1364 		kprintf("machdep.meltdown_mitigation enabled to "
1365 			"protect against (mostly Intel) meltdown bug\n");
1366 		kprintf("system call performance will be impacted\n");
1367 	}
1368 
1369 	pmap_init2_iso_pmap();
1370 }
1371 
1372 /*
1373  * Create the isolation pmap template.  Once created, the template
1374  * is static and its PML4e entries are used to populate the
1375  * kernel portion of any isolated user pmaps.
1376  *
1377  * Our isolation pmap must contain:
1378  * (1) trampoline area for all cpus
1379  * (2) common_tss area for all cpus (its part of the trampoline area now)
1380  * (3) IDT for all cpus
1381  * (4) GDT for all cpus
1382  */
1383 static void
1384 pmap_init2_iso_pmap(void)
1385 {
1386 	int n;
1387 
1388 	if (bootverbose)
1389 		kprintf("Initialize isolation pmap\n");
1390 
1391 	/*
1392 	 * Try to use our normal API calls to make this easier.  We have
1393 	 * to scrap the shadowed kernel PDPs pmap_pinit() creates for our
1394 	 * iso_pmap.
1395 	 */
1396 	pmap_pinit(&iso_pmap);
1397 	bzero(iso_pmap.pm_pml4, PAGE_SIZE);
1398 
1399 	/*
1400 	 * Install areas needed by the cpu and trampoline.
1401 	 */
1402 	for (n = 0; n < ncpus; ++n) {
1403 		struct privatespace *ps;
1404 
1405 		ps = CPU_prvspace[n];
1406 		pmap_init_iso_range((vm_offset_t)&ps->trampoline,
1407 				    sizeof(ps->trampoline));
1408 		pmap_init_iso_range((vm_offset_t)&ps->common_tss,
1409 				    sizeof(ps->common_tss));
1410 		pmap_init_iso_range(r_idt_arr[n].rd_base,
1411 				    r_idt_arr[n].rd_limit + 1);
1412 	}
1413 	pmap_init_iso_range((register_t)gdt, sizeof(gdt));
1414 	pmap_init_iso_range((vm_offset_t)(int *)btext,
1415 			    (vm_offset_t)(int *)etext -
1416 			     (vm_offset_t)(int *)btext);
1417 
1418 #if 0
1419 	kprintf("Dump iso_pmap:\n");
1420 	dump_pmap(&iso_pmap, vtophys(iso_pmap.pm_pml4), 0, 0);
1421 	kprintf("\nDump kernel_pmap:\n");
1422 	dump_pmap(&kernel_pmap, vtophys(kernel_pmap.pm_pml4), 0, 0);
1423 #endif
1424 }
1425 
1426 /*
1427  * This adds a kernel virtual address range to the isolation pmap.
1428  */
1429 static void
1430 pmap_init_iso_range(vm_offset_t base, size_t bytes)
1431 {
1432 	pv_entry_t pv;
1433 	pv_entry_t pvp;
1434 	pt_entry_t *ptep;
1435 	pt_entry_t pte;
1436 	vm_offset_t va;
1437 
1438 	if (bootverbose) {
1439 		kprintf("isolate %016jx-%016jx (%zd)\n",
1440 			base, base + bytes, bytes);
1441 	}
1442 	va = base & ~(vm_offset_t)PAGE_MASK;
1443 	while (va < base + bytes) {
1444 		if ((va & PDRMASK) == 0 && va + NBPDR <= base + bytes &&
1445 		    (ptep = pmap_pt(&kernel_pmap, va)) != NULL &&
1446 		    (*ptep & kernel_pmap.pmap_bits[PG_V_IDX]) &&
1447 		    (*ptep & kernel_pmap.pmap_bits[PG_PS_IDX])) {
1448 			/*
1449 			 * Use 2MB pages if possible
1450 			 */
1451 			pte = *ptep;
1452 			pv = pmap_allocpte(&iso_pmap, pmap_pd_pindex(va), &pvp);
1453 			ptep = pv_pte_lookup(pv, (va >> PDRSHIFT) & 511);
1454 			*ptep = pte;
1455 			va += NBPDR;
1456 		} else {
1457 			/*
1458 			 * Otherwise use 4KB pages
1459 			 */
1460 			pv = pmap_allocpte(&iso_pmap, pmap_pt_pindex(va), &pvp);
1461 			ptep = pv_pte_lookup(pv, (va >> PAGE_SHIFT) & 511);
1462 			*ptep = vtophys(va) | kernel_pmap.pmap_bits[PG_RW_IDX] |
1463 					      kernel_pmap.pmap_bits[PG_V_IDX] |
1464 					      kernel_pmap.pmap_bits[PG_A_IDX] |
1465 					      kernel_pmap.pmap_bits[PG_M_IDX];
1466 
1467 			va += PAGE_SIZE;
1468 		}
1469 		pv_put(pv);
1470 		pv_put(pvp);
1471 	}
1472 }
1473 
1474 #if 0
1475 /*
1476  * Useful debugging pmap dumper, do not remove (#if 0 when not in use)
1477  */
1478 static
1479 void
1480 dump_pmap(pmap_t pmap, pt_entry_t pte, int level, vm_offset_t base)
1481 {
1482 	pt_entry_t *ptp;
1483 	vm_offset_t incr;
1484 	int i;
1485 
1486 	switch(level) {
1487 	case 0:					/* PML4e page, 512G entries */
1488 		incr = (1LL << 48) / 512;
1489 		break;
1490 	case 1:					/* PDP page, 1G entries */
1491 		incr = (1LL << 39) / 512;
1492 		break;
1493 	case 2:					/* PD page, 2MB entries */
1494 		incr = (1LL << 30) / 512;
1495 		break;
1496 	case 3:					/* PT page, 4KB entries */
1497 		incr = (1LL << 21) / 512;
1498 		break;
1499 	default:
1500 		incr = 0;
1501 		break;
1502 	}
1503 
1504 	if (level == 0)
1505 		kprintf("cr3 %016jx @ va=%016jx\n", pte, base);
1506 	ptp = (void *)PHYS_TO_DMAP(pte & ~(pt_entry_t)PAGE_MASK);
1507 	for (i = 0; i < 512; ++i) {
1508 		if (level == 0 && i == 128)
1509 			base += 0xFFFF000000000000LLU;
1510 		if (ptp[i]) {
1511 			kprintf("%*.*s ", level * 4, level * 4, "");
1512 			if (level == 1 && (ptp[i] & 0x180) == 0x180) {
1513 				kprintf("va=%016jx %3d term %016jx (1GB)\n",
1514 					base, i, ptp[i]);
1515 			} else if (level == 2 && (ptp[i] & 0x180) == 0x180) {
1516 				kprintf("va=%016jx %3d term %016jx (2MB)\n",
1517 					base, i, ptp[i]);
1518 			} else if (level == 3) {
1519 				kprintf("va=%016jx %3d term %016jx\n",
1520 					base, i, ptp[i]);
1521 			} else {
1522 				kprintf("va=%016jx %3d deep %016jx\n",
1523 					base, i, ptp[i]);
1524 				dump_pmap(pmap, ptp[i], level + 1, base);
1525 			}
1526 		}
1527 		base += incr;
1528 	}
1529 }
1530 
1531 #endif
1532 
1533 /*
1534  * Typically used to initialize a fictitious page by vm/device_pager.c
1535  */
1536 void
1537 pmap_page_init(struct vm_page *m)
1538 {
1539 	vm_page_init(m);
1540 	TAILQ_INIT(&m->md.pv_list);
1541 }
1542 
1543 /***************************************************
1544  * Low level helper routines.....
1545  ***************************************************/
1546 
1547 /*
1548  * this routine defines the region(s) of memory that should
1549  * not be tested for the modified bit.
1550  */
1551 static __inline
1552 int
1553 pmap_track_modified(vm_pindex_t pindex)
1554 {
1555 	vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
1556 	if ((va < clean_sva) || (va >= clean_eva))
1557 		return 1;
1558 	else
1559 		return 0;
1560 }
1561 
1562 /*
1563  * Extract the physical page address associated with the map/VA pair.
1564  * The page must be wired for this to work reliably.
1565  */
1566 vm_paddr_t
1567 pmap_extract(pmap_t pmap, vm_offset_t va, void **handlep)
1568 {
1569 	vm_paddr_t rtval;
1570 	pv_entry_t pt_pv;
1571 	pt_entry_t *ptep;
1572 
1573 	rtval = 0;
1574 	if (va >= VM_MAX_USER_ADDRESS) {
1575 		/*
1576 		 * Kernel page directories might be direct-mapped and
1577 		 * there is typically no PV tracking of pte's
1578 		 */
1579 		pd_entry_t *pt;
1580 
1581 		pt = pmap_pt(pmap, va);
1582 		if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1583 			if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1584 				rtval = *pt & PG_PS_FRAME;
1585 				rtval |= va & PDRMASK;
1586 			} else {
1587 				ptep = pmap_pt_to_pte(*pt, va);
1588 				if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1589 					rtval = *ptep & PG_FRAME;
1590 					rtval |= va & PAGE_MASK;
1591 				}
1592 			}
1593 		}
1594 		if (handlep)
1595 			*handlep = NULL;
1596 	} else {
1597 		/*
1598 		 * User pages currently do not direct-map the page directory
1599 		 * and some pages might not used managed PVs.  But all PT's
1600 		 * will have a PV.
1601 		 */
1602 		pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1603 		if (pt_pv) {
1604 			ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1605 			if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1606 				rtval = *ptep & PG_FRAME;
1607 				rtval |= va & PAGE_MASK;
1608 			}
1609 			if (handlep)
1610 				*handlep = pt_pv;	/* locked until done */
1611 			else
1612 				pv_put (pt_pv);
1613 		} else if (handlep) {
1614 			*handlep = NULL;
1615 		}
1616 	}
1617 	return rtval;
1618 }
1619 
1620 void
1621 pmap_extract_done(void *handle)
1622 {
1623 	if (handle)
1624 		pv_put((pv_entry_t)handle);
1625 }
1626 
1627 /*
1628  * Similar to extract but checks protections, SMP-friendly short-cut for
1629  * vm_fault_page[_quick]().  Can return NULL to cause the caller to
1630  * fall-through to the real fault code.  Does not work with HVM page
1631  * tables.
1632  *
1633  * if busyp is NULL the returned page, if not NULL, is held (and not busied).
1634  *
1635  * If busyp is not NULL and this function sets *busyp non-zero, the returned
1636  * page is busied (and not held).
1637  *
1638  * If busyp is not NULL and this function sets *busyp to zero, the returned
1639  * page is held (and not busied).
1640  *
1641  * If VM_PROT_WRITE is set in prot, and the pte is already writable, the
1642  * returned page will be dirtied.  If the pte is not already writable NULL
1643  * is returned.  In otherwords, if the bit is set and a vm_page_t is returned,
1644  * any COW will already have happened and that page can be written by the
1645  * caller.
1646  *
1647  * WARNING! THE RETURNED PAGE IS ONLY HELD AND NOT SUITABLE FOR READING
1648  *	    OR WRITING AS-IS.
1649  */
1650 vm_page_t
1651 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot, int *busyp)
1652 {
1653 	if (pmap &&
1654 	    va < VM_MAX_USER_ADDRESS &&
1655 	    (pmap->pm_flags & PMAP_HVM) == 0) {
1656 		pv_entry_t pt_pv;
1657 		pv_entry_t pte_pv;
1658 		pt_entry_t *ptep;
1659 		pt_entry_t req;
1660 		vm_page_t m;
1661 		int error;
1662 
1663 		req = pmap->pmap_bits[PG_V_IDX] |
1664 		      pmap->pmap_bits[PG_U_IDX];
1665 		if (prot & VM_PROT_WRITE)
1666 			req |= pmap->pmap_bits[PG_RW_IDX];
1667 
1668 		pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
1669 		if (pt_pv == NULL)
1670 			return (NULL);
1671 		ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1672 		if ((*ptep & req) != req) {
1673 			pv_put(pt_pv);
1674 			return (NULL);
1675 		}
1676 		pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), NULL, &error);
1677 		if (pte_pv && error == 0) {
1678 			m = pte_pv->pv_m;
1679 			if (prot & VM_PROT_WRITE) {
1680 				/* interlocked by presence of pv_entry */
1681 				vm_page_dirty(m);
1682 			}
1683 			if (busyp) {
1684 				if (prot & VM_PROT_WRITE) {
1685 					if (vm_page_busy_try(m, TRUE))
1686 						m = NULL;
1687 					*busyp = 1;
1688 				} else {
1689 					vm_page_hold(m);
1690 					*busyp = 0;
1691 				}
1692 			} else {
1693 				vm_page_hold(m);
1694 			}
1695 			pv_put(pte_pv);
1696 		} else if (pte_pv) {
1697 			pv_drop(pte_pv);
1698 			m = NULL;
1699 		} else {
1700 			/* error, since we didn't request a placemarker */
1701 			m = NULL;
1702 		}
1703 		pv_put(pt_pv);
1704 		return(m);
1705 	} else {
1706 		return(NULL);
1707 	}
1708 }
1709 
1710 /*
1711  * Extract the physical page address associated kernel virtual address.
1712  */
1713 vm_paddr_t
1714 pmap_kextract(vm_offset_t va)
1715 {
1716 	pd_entry_t pt;		/* pt entry in pd */
1717 	vm_paddr_t pa;
1718 
1719 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1720 		pa = DMAP_TO_PHYS(va);
1721 	} else {
1722 		pt = *vtopt(va);
1723 		if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1724 			pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1725 		} else {
1726 			/*
1727 			 * Beware of a concurrent promotion that changes the
1728 			 * PDE at this point!  For example, vtopte() must not
1729 			 * be used to access the PTE because it would use the
1730 			 * new PDE.  It is, however, safe to use the old PDE
1731 			 * because the page table page is preserved by the
1732 			 * promotion.
1733 			 */
1734 			pa = *pmap_pt_to_pte(pt, va);
1735 			pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1736 		}
1737 	}
1738 	return pa;
1739 }
1740 
1741 /***************************************************
1742  * Low level mapping routines.....
1743  ***************************************************/
1744 
1745 /*
1746  * Routine: pmap_kenter
1747  * Function:
1748  *  	Add a wired page to the KVA
1749  *  	NOTE! note that in order for the mapping to take effect -- you
1750  *  	should do an invltlb after doing the pmap_kenter().
1751  */
1752 void
1753 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1754 {
1755 	pt_entry_t *ptep;
1756 	pt_entry_t npte;
1757 
1758 	npte = pa |
1759 	       kernel_pmap.pmap_bits[PG_RW_IDX] |
1760 	       kernel_pmap.pmap_bits[PG_V_IDX];
1761 //	       pgeflag;
1762 	ptep = vtopte(va);
1763 #if 1
1764 	pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1765 #else
1766 	/* FUTURE */
1767 	if (*ptep)
1768 		pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1769 	else
1770 		*ptep = npte;
1771 #endif
1772 }
1773 
1774 /*
1775  * Similar to pmap_kenter(), except we only invalidate the mapping on the
1776  * current CPU.  Returns 0 if the previous pte was 0, 1 if it wasn't
1777  * (caller can conditionalize calling smp_invltlb()).
1778  */
1779 int
1780 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1781 {
1782 	pt_entry_t *ptep;
1783 	pt_entry_t npte;
1784 	int res;
1785 
1786 	npte = pa | kernel_pmap.pmap_bits[PG_RW_IDX] |
1787 		    kernel_pmap.pmap_bits[PG_V_IDX];
1788 	// npte |= pgeflag;
1789 	ptep = vtopte(va);
1790 #if 1
1791 	res = 1;
1792 #else
1793 	/* FUTURE */
1794 	res = (*ptep != 0);
1795 #endif
1796 	atomic_swap_long(ptep, npte);
1797 	cpu_invlpg((void *)va);
1798 
1799 	return res;
1800 }
1801 
1802 /*
1803  * Enter addresses into the kernel pmap but don't bother
1804  * doing any tlb invalidations.  Caller will do a rollup
1805  * invalidation via pmap_rollup_inval().
1806  */
1807 int
1808 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1809 {
1810 	pt_entry_t *ptep;
1811 	pt_entry_t npte;
1812 	int res;
1813 
1814 	npte = pa |
1815 	    kernel_pmap.pmap_bits[PG_RW_IDX] |
1816 	    kernel_pmap.pmap_bits[PG_V_IDX];
1817 //	    pgeflag;
1818 	ptep = vtopte(va);
1819 #if 1
1820 	res = 1;
1821 #else
1822 	/* FUTURE */
1823 	res = (*ptep != 0);
1824 #endif
1825 	atomic_swap_long(ptep, npte);
1826 	cpu_invlpg((void *)va);
1827 
1828 	return res;
1829 }
1830 
1831 /*
1832  * remove a page from the kernel pagetables
1833  */
1834 void
1835 pmap_kremove(vm_offset_t va)
1836 {
1837 	pt_entry_t *ptep;
1838 
1839 	ptep = vtopte(va);
1840 	pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1841 }
1842 
1843 void
1844 pmap_kremove_quick(vm_offset_t va)
1845 {
1846 	pt_entry_t *ptep;
1847 
1848 	ptep = vtopte(va);
1849 	(void)pte_load_clear(ptep);
1850 	cpu_invlpg((void *)va);
1851 }
1852 
1853 /*
1854  * Remove addresses from the kernel pmap but don't bother
1855  * doing any tlb invalidations.  Caller will do a rollup
1856  * invalidation via pmap_rollup_inval().
1857  */
1858 void
1859 pmap_kremove_noinval(vm_offset_t va)
1860 {
1861 	pt_entry_t *ptep;
1862 
1863 	ptep = vtopte(va);
1864 	(void)pte_load_clear(ptep);
1865 }
1866 
1867 /*
1868  * XXX these need to be recoded.  They are not used in any critical path.
1869  */
1870 void
1871 pmap_kmodify_rw(vm_offset_t va)
1872 {
1873 	atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1874 	cpu_invlpg((void *)va);
1875 }
1876 
1877 /* NOT USED
1878 void
1879 pmap_kmodify_nc(vm_offset_t va)
1880 {
1881 	atomic_set_long(vtopte(va), PG_N);
1882 	cpu_invlpg((void *)va);
1883 }
1884 */
1885 
1886 /*
1887  * Used to map a range of physical addresses into kernel virtual
1888  * address space during the low level boot, typically to map the
1889  * dump bitmap, message buffer, and vm_page_array.
1890  *
1891  * These mappings are typically made at some pointer after the end of the
1892  * kernel text+data.
1893  *
1894  * We could return PHYS_TO_DMAP(start) here and not allocate any
1895  * via (*virtp), but then kmem from userland and kernel dumps won't
1896  * have access to the related pointers.
1897  */
1898 vm_offset_t
1899 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1900 {
1901 	vm_offset_t va;
1902 	vm_offset_t va_start;
1903 
1904 	/*return PHYS_TO_DMAP(start);*/
1905 
1906 	va_start = *virtp;
1907 	va = va_start;
1908 
1909 	while (start < end) {
1910 		pmap_kenter_quick(va, start);
1911 		va += PAGE_SIZE;
1912 		start += PAGE_SIZE;
1913 	}
1914 	*virtp = va;
1915 	return va_start;
1916 }
1917 
1918 #define PMAP_CLFLUSH_THRESHOLD  (2 * 1024 * 1024)
1919 
1920 /*
1921  * Remove the specified set of pages from the data and instruction caches.
1922  *
1923  * In contrast to pmap_invalidate_cache_range(), this function does not
1924  * rely on the CPU's self-snoop feature, because it is intended for use
1925  * when moving pages into a different cache domain.
1926  */
1927 void
1928 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1929 {
1930 	vm_offset_t daddr, eva;
1931 	int i;
1932 
1933 	if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1934 	    (cpu_feature & CPUID_CLFSH) == 0)
1935 		wbinvd();
1936 	else {
1937 		cpu_mfence();
1938 		for (i = 0; i < count; i++) {
1939 			daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1940 			eva = daddr + PAGE_SIZE;
1941 			for (; daddr < eva; daddr += cpu_clflush_line_size)
1942 				clflush(daddr);
1943 		}
1944 		cpu_mfence();
1945 	}
1946 }
1947 
1948 void
1949 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1950 {
1951 	KASSERT((sva & PAGE_MASK) == 0,
1952 	    ("pmap_invalidate_cache_range: sva not page-aligned"));
1953 	KASSERT((eva & PAGE_MASK) == 0,
1954 	    ("pmap_invalidate_cache_range: eva not page-aligned"));
1955 
1956 	if (cpu_feature & CPUID_SS) {
1957 		; /* If "Self Snoop" is supported, do nothing. */
1958 	} else {
1959 		/* Globally invalidate caches */
1960 		cpu_wbinvd_on_all_cpus();
1961 	}
1962 }
1963 
1964 /*
1965  * Invalidate the specified range of virtual memory on all cpus associated
1966  * with the pmap.
1967  */
1968 void
1969 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1970 {
1971 	pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
1972 }
1973 
1974 /*
1975  * Add a list of wired pages to the kva.  This routine is used for temporary
1976  * kernel mappings such as those found in buffer cache buffer.  Page
1977  * modifications and accesses are not tracked or recorded.
1978  *
1979  * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
1980  *	 semantics as previous mappings may have been zerod without any
1981  *	 invalidation.
1982  *
1983  * The page *must* be wired.
1984  */
1985 static __inline void
1986 _pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count, int doinval)
1987 {
1988 	vm_offset_t end_va;
1989 	vm_offset_t va;
1990 
1991 	end_va = beg_va + count * PAGE_SIZE;
1992 
1993 	for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1994 		pt_entry_t pte;
1995 		pt_entry_t *ptep;
1996 
1997 		ptep = vtopte(va);
1998 		pte = VM_PAGE_TO_PHYS(*m) |
1999 			kernel_pmap.pmap_bits[PG_RW_IDX] |
2000 			kernel_pmap.pmap_bits[PG_V_IDX] |
2001 			kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
2002 //		pgeflag;
2003 		atomic_swap_long(ptep, pte);
2004 		m++;
2005 	}
2006 	if (doinval)
2007 		pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2008 }
2009 
2010 void
2011 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
2012 {
2013 	_pmap_qenter(beg_va, m, count, 1);
2014 }
2015 
2016 void
2017 pmap_qenter_noinval(vm_offset_t beg_va, vm_page_t *m, int count)
2018 {
2019 	_pmap_qenter(beg_va, m, count, 0);
2020 }
2021 
2022 /*
2023  * This routine jerks page mappings from the kernel -- it is meant only
2024  * for temporary mappings such as those found in buffer cache buffers.
2025  * No recording modified or access status occurs.
2026  *
2027  * MPSAFE, INTERRUPT SAFE (cluster callback)
2028  */
2029 void
2030 pmap_qremove(vm_offset_t beg_va, int count)
2031 {
2032 	vm_offset_t end_va;
2033 	vm_offset_t va;
2034 
2035 	end_va = beg_va + count * PAGE_SIZE;
2036 
2037 	for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2038 		pt_entry_t *pte;
2039 
2040 		pte = vtopte(va);
2041 		(void)pte_load_clear(pte);
2042 		cpu_invlpg((void *)va);
2043 	}
2044 	pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
2045 }
2046 
2047 /*
2048  * This routine removes temporary kernel mappings, only invalidating them
2049  * on the current cpu.  It should only be used under carefully controlled
2050  * conditions.
2051  */
2052 void
2053 pmap_qremove_quick(vm_offset_t beg_va, int count)
2054 {
2055 	vm_offset_t end_va;
2056 	vm_offset_t va;
2057 
2058 	end_va = beg_va + count * PAGE_SIZE;
2059 
2060 	for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2061 		pt_entry_t *pte;
2062 
2063 		pte = vtopte(va);
2064 		(void)pte_load_clear(pte);
2065 		cpu_invlpg((void *)va);
2066 	}
2067 }
2068 
2069 /*
2070  * This routine removes temporary kernel mappings *without* invalidating
2071  * the TLB.  It can only be used on permanent kva reservations such as those
2072  * found in buffer cache buffers, under carefully controlled circumstances.
2073  *
2074  * NOTE: Repopulating these KVAs requires unconditional invalidation.
2075  *	 (pmap_qenter() does unconditional invalidation).
2076  */
2077 void
2078 pmap_qremove_noinval(vm_offset_t beg_va, int count)
2079 {
2080 	vm_offset_t end_va;
2081 	vm_offset_t va;
2082 
2083 	end_va = beg_va + count * PAGE_SIZE;
2084 
2085 	for (va = beg_va; va < end_va; va += PAGE_SIZE) {
2086 		pt_entry_t *pte;
2087 
2088 		pte = vtopte(va);
2089 		(void)pte_load_clear(pte);
2090 	}
2091 }
2092 
2093 /*
2094  * Create a new thread and optionally associate it with a (new) process.
2095  * NOTE! the new thread's cpu may not equal the current cpu.
2096  */
2097 void
2098 pmap_init_thread(thread_t td)
2099 {
2100 	/* enforce pcb placement & alignment */
2101 	td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
2102 	td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
2103 	td->td_savefpu = &td->td_pcb->pcb_save;
2104 	td->td_sp = (char *)td->td_pcb;	/* no -16 */
2105 }
2106 
2107 /*
2108  * This routine directly affects the fork perf for a process.
2109  */
2110 void
2111 pmap_init_proc(struct proc *p)
2112 {
2113 }
2114 
2115 static void
2116 pmap_pinit_defaults(struct pmap *pmap)
2117 {
2118 	bcopy(pmap_bits_default, pmap->pmap_bits,
2119 	      sizeof(pmap_bits_default));
2120 	bcopy(protection_codes, pmap->protection_codes,
2121 	      sizeof(protection_codes));
2122 	bcopy(pat_pte_index, pmap->pmap_cache_bits,
2123 	      sizeof(pat_pte_index));
2124 	pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
2125 	pmap->copyinstr = std_copyinstr;
2126 	pmap->copyin = std_copyin;
2127 	pmap->copyout = std_copyout;
2128 	pmap->fubyte = std_fubyte;
2129 	pmap->subyte = std_subyte;
2130 	pmap->fuword32 = std_fuword32;
2131 	pmap->fuword64 = std_fuword64;
2132 	pmap->suword32 = std_suword32;
2133 	pmap->suword64 = std_suword64;
2134 	pmap->swapu32 = std_swapu32;
2135 	pmap->swapu64 = std_swapu64;
2136 }
2137 /*
2138  * Initialize pmap0/vmspace0.
2139  *
2140  * On architectures where the kernel pmap is not integrated into the user
2141  * process pmap, this pmap represents the process pmap, not the kernel pmap.
2142  * kernel_pmap should be used to directly access the kernel_pmap.
2143  */
2144 void
2145 pmap_pinit0(struct pmap *pmap)
2146 {
2147 	int i;
2148 
2149 	pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
2150 	pmap->pm_count = 1;
2151 	CPUMASK_ASSZERO(pmap->pm_active);
2152 	pmap->pm_pvhint_pt = NULL;
2153 	pmap->pm_pvhint_pte = NULL;
2154 	RB_INIT(&pmap->pm_pvroot);
2155 	spin_init(&pmap->pm_spin, "pmapinit0");
2156 	for (i = 0; i < PM_PLACEMARKS; ++i)
2157 		pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2158 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2159 	pmap_pinit_defaults(pmap);
2160 }
2161 
2162 /*
2163  * Initialize a preallocated and zeroed pmap structure,
2164  * such as one in a vmspace structure.
2165  */
2166 static void
2167 pmap_pinit_simple(struct pmap *pmap)
2168 {
2169 	int i;
2170 
2171 	/*
2172 	 * Misc initialization
2173 	 */
2174 	pmap->pm_count = 1;
2175 	CPUMASK_ASSZERO(pmap->pm_active);
2176 	pmap->pm_pvhint_pt = NULL;
2177 	pmap->pm_pvhint_pte = NULL;
2178 	pmap->pm_flags = PMAP_FLAG_SIMPLE;
2179 
2180 	pmap_pinit_defaults(pmap);
2181 
2182 	/*
2183 	 * Don't blow up locks/tokens on re-use (XXX fix/use drop code
2184 	 * for this).
2185 	 */
2186 	if (pmap->pm_pmlpv == NULL) {
2187 		RB_INIT(&pmap->pm_pvroot);
2188 		bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2189 		spin_init(&pmap->pm_spin, "pmapinitsimple");
2190 		for (i = 0; i < PM_PLACEMARKS; ++i)
2191 			pmap->pm_placemarks[i] = PM_NOPLACEMARK;
2192 	}
2193 }
2194 
2195 void
2196 pmap_pinit(struct pmap *pmap)
2197 {
2198 	pv_entry_t pv;
2199 	int j;
2200 
2201 	if (pmap->pm_pmlpv) {
2202 		if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
2203 			pmap_puninit(pmap);
2204 		}
2205 	}
2206 
2207 	pmap_pinit_simple(pmap);
2208 	pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
2209 
2210 	/*
2211 	 * No need to allocate page table space yet but we do need a valid
2212 	 * page directory table.
2213 	 */
2214 	if (pmap->pm_pml4 == NULL) {
2215 		pmap->pm_pml4 =
2216 		    (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
2217 							PAGE_SIZE * 2,
2218 							VM_SUBSYS_PML4);
2219 		pmap->pm_pml4_iso = (void *)((char *)pmap->pm_pml4 + PAGE_SIZE);
2220 	}
2221 
2222 	/*
2223 	 * Allocate the PML4e table, which wires it even though it isn't
2224 	 * being entered into some higher level page table (it being the
2225 	 * highest level).  If one is already cached we don't have to do
2226 	 * anything.
2227 	 */
2228 	if ((pv = pmap->pm_pmlpv) == NULL) {
2229 		pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2230 		pmap->pm_pmlpv = pv;
2231 		pmap_kenter((vm_offset_t)pmap->pm_pml4,
2232 			    VM_PAGE_TO_PHYS(pv->pv_m));
2233 		pv_put(pv);
2234 
2235 		/*
2236 		 * Install DMAP and KMAP.
2237 		 */
2238 		for (j = 0; j < NDMPML4E; ++j) {
2239 			pmap->pm_pml4[DMPML4I + j] =
2240 			    (DMPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2241 			    pmap->pmap_bits[PG_RW_IDX] |
2242 			    pmap->pmap_bits[PG_V_IDX] |
2243 			    pmap->pmap_bits[PG_A_IDX];
2244 		}
2245 		for (j = 0; j < NKPML4E; ++j) {
2246 			pmap->pm_pml4[KPML4I + j] =
2247 			    (KPDPphys + ((vm_paddr_t)j << PAGE_SHIFT)) |
2248 			    pmap->pmap_bits[PG_RW_IDX] |
2249 			    pmap->pmap_bits[PG_V_IDX] |
2250 			    pmap->pmap_bits[PG_A_IDX];
2251 		}
2252 
2253 		/*
2254 		 * install self-referential address mapping entry
2255 		 */
2256 		pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
2257 		    pmap->pmap_bits[PG_V_IDX] |
2258 		    pmap->pmap_bits[PG_RW_IDX] |
2259 		    pmap->pmap_bits[PG_A_IDX];
2260 	} else {
2261 		KKASSERT(pv->pv_m->flags & PG_MAPPED);
2262 		KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2263 	}
2264 	KKASSERT(pmap->pm_pml4[255] == 0);
2265 
2266 	/*
2267 	 * When implementing an isolated userland pmap, a second PML4e table
2268 	 * is needed.  We use pmap_pml4_pindex() + 1 for convenience, but
2269 	 * note that we do not operate on this table using our API functions
2270 	 * so handling of the + 1 case is mostly just to prevent implosions.
2271 	 *
2272 	 * We install an isolated version of the kernel PDPs into this
2273 	 * second PML4e table.  The pmap code will mirror all user PDPs
2274 	 * between the primary and secondary PML4e table.
2275 	 */
2276 	if ((pv = pmap->pm_pmlpv_iso) == NULL && meltdown_mitigation &&
2277 	    pmap != &iso_pmap) {
2278 		pv = pmap_allocpte(pmap, pmap_pml4_pindex() + 1, NULL);
2279 		pmap->pm_pmlpv_iso = pv;
2280 		pmap_kenter((vm_offset_t)pmap->pm_pml4_iso,
2281 			    VM_PAGE_TO_PHYS(pv->pv_m));
2282 		pv_put(pv);
2283 
2284 		/*
2285 		 * Install an isolated version of the kernel pmap for
2286 		 * user consumption, using PDPs constructed in iso_pmap.
2287 		 */
2288 		for (j = 0; j < NKPML4E; ++j) {
2289 			pmap->pm_pml4_iso[KPML4I + j] =
2290 				iso_pmap.pm_pml4[KPML4I + j];
2291 		}
2292 	} else if (pv) {
2293 		KKASSERT(pv->pv_m->flags & PG_MAPPED);
2294 		KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
2295 	}
2296 }
2297 
2298 /*
2299  * Clean up a pmap structure so it can be physically freed.  This routine
2300  * is called by the vmspace dtor function.  A great deal of pmap data is
2301  * left passively mapped to improve vmspace management so we have a bit
2302  * of cleanup work to do here.
2303  */
2304 void
2305 pmap_puninit(pmap_t pmap)
2306 {
2307 	pv_entry_t pv;
2308 	vm_page_t p;
2309 
2310 	KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
2311 	if ((pv = pmap->pm_pmlpv) != NULL) {
2312 		if (pv_hold_try(pv) == 0)
2313 			pv_lock(pv);
2314 		KKASSERT(pv == pmap->pm_pmlpv);
2315 		p = pmap_remove_pv_page(pv);
2316 		pv_free(pv, NULL);
2317 		pv = NULL;	/* safety */
2318 		pmap_kremove((vm_offset_t)pmap->pm_pml4);
2319 		vm_page_busy_wait(p, FALSE, "pgpun");
2320 		KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2321 		vm_page_unwire(p, 0);
2322 		vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2323 		vm_page_free(p);
2324 		pmap->pm_pmlpv = NULL;
2325 	}
2326 	if ((pv = pmap->pm_pmlpv_iso) != NULL) {
2327 		if (pv_hold_try(pv) == 0)
2328 			pv_lock(pv);
2329 		KKASSERT(pv == pmap->pm_pmlpv_iso);
2330 		p = pmap_remove_pv_page(pv);
2331 		pv_free(pv, NULL);
2332 		pv = NULL;	/* safety */
2333 		pmap_kremove((vm_offset_t)pmap->pm_pml4_iso);
2334 		vm_page_busy_wait(p, FALSE, "pgpun");
2335 		KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
2336 		vm_page_unwire(p, 0);
2337 		vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
2338 		vm_page_free(p);
2339 		pmap->pm_pmlpv_iso = NULL;
2340 	}
2341 	if (pmap->pm_pml4) {
2342 		KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
2343 		kmem_free(&kernel_map,
2344 			  (vm_offset_t)pmap->pm_pml4, PAGE_SIZE * 2);
2345 		pmap->pm_pml4 = NULL;
2346 		pmap->pm_pml4_iso = NULL;
2347 	}
2348 	KKASSERT(pmap->pm_stats.resident_count == 0);
2349 	KKASSERT(pmap->pm_stats.wired_count == 0);
2350 }
2351 
2352 /*
2353  * This function is now unused (used to add the pmap to the pmap_list)
2354  */
2355 void
2356 pmap_pinit2(struct pmap *pmap)
2357 {
2358 }
2359 
2360 /*
2361  * This routine is called when various levels in the page table need to
2362  * be populated.  This routine cannot fail.
2363  *
2364  * This function returns two locked pv_entry's, one representing the
2365  * requested pv and one representing the requested pv's parent pv.  If
2366  * an intermediate page table does not exist it will be created, mapped,
2367  * wired, and the parent page table will be given an additional hold
2368  * count representing the presence of the child pv_entry.
2369  */
2370 static
2371 pv_entry_t
2372 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
2373 {
2374 	pt_entry_t *ptep;
2375 	pt_entry_t *ptep_iso;
2376 	pv_entry_t pv;
2377 	pv_entry_t pvp;
2378 	pt_entry_t v;
2379 	vm_pindex_t pt_pindex;
2380 	vm_page_t m;
2381 	int isnew;
2382 	int ispt;
2383 
2384 	/*
2385 	 * If the pv already exists and we aren't being asked for the
2386 	 * parent page table page we can just return it.  A locked+held pv
2387 	 * is returned.  The pv will also have a second hold related to the
2388 	 * pmap association that we don't have to worry about.
2389 	 */
2390 	ispt = 0;
2391 	pv = pv_alloc(pmap, ptepindex, &isnew);
2392 	if (isnew == 0 && pvpp == NULL)
2393 		return(pv);
2394 
2395 	/*
2396 	 * Special case terminal PVs.  These are not page table pages so
2397 	 * no vm_page is allocated (the caller supplied the vm_page).  If
2398 	 * pvpp is non-NULL we are being asked to also removed the pt_pv
2399 	 * for this pv.
2400 	 *
2401 	 * Note that pt_pv's are only returned for user VAs. We assert that
2402 	 * a pt_pv is not being requested for kernel VAs.  The kernel
2403 	 * pre-wires all higher-level page tables so don't overload managed
2404 	 * higher-level page tables on top of it!
2405 	 *
2406 	 * However, its convenient for us to allow the case when creating
2407 	 * iso_pmap.  This is a bit of a hack but it simplifies iso_pmap
2408 	 * a lot.
2409 	 */
2410 	if (ptepindex < pmap_pt_pindex(0)) {
2411 		if (ptepindex >= NUPTE_USER && pmap != &iso_pmap) {
2412 			/* kernel manages this manually for KVM */
2413 			KKASSERT(pvpp == NULL);
2414 		} else {
2415 			KKASSERT(pvpp != NULL);
2416 			pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
2417 			pvp = pmap_allocpte(pmap, pt_pindex, NULL);
2418 			if (isnew)
2419 				vm_page_wire_quick(pvp->pv_m);
2420 			*pvpp = pvp;
2421 		}
2422 		return(pv);
2423 	}
2424 
2425 	/*
2426 	 * The kernel never uses managed PT/PD/PDP pages.
2427 	 */
2428 	KKASSERT(pmap != &kernel_pmap);
2429 
2430 	/*
2431 	 * Non-terminal PVs allocate a VM page to represent the page table,
2432 	 * so we have to resolve pvp and calculate ptepindex for the pvp
2433 	 * and then for the page table entry index in the pvp for
2434 	 * fall-through.
2435 	 */
2436 	if (ptepindex < pmap_pd_pindex(0)) {
2437 		/*
2438 		 * pv is PT, pvp is PD
2439 		 */
2440 		ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
2441 		ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
2442 		pvp = pmap_allocpte(pmap, ptepindex, NULL);
2443 
2444 		/*
2445 		 * PT index in PD
2446 		 */
2447 		ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
2448 		ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
2449 		ispt = 1;
2450 	} else if (ptepindex < pmap_pdp_pindex(0)) {
2451 		/*
2452 		 * pv is PD, pvp is PDP
2453 		 *
2454 		 * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
2455 		 *		     the PD.
2456 		 */
2457 		ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
2458 		ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
2459 
2460 		if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
2461 			KKASSERT(pvpp == NULL);
2462 			pvp = NULL;
2463 		} else {
2464 			pvp = pmap_allocpte(pmap, ptepindex, NULL);
2465 		}
2466 
2467 		/*
2468 		 * PD index in PDP
2469 		 */
2470 		ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
2471 		ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
2472 	} else if (ptepindex < pmap_pml4_pindex()) {
2473 		/*
2474 		 * pv is PDP, pvp is the root pml4 table
2475 		 */
2476 		pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
2477 
2478 		/*
2479 		 * PDP index in PML4
2480 		 */
2481 		ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
2482 		ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
2483 	} else {
2484 		/*
2485 		 * pv represents the top-level PML4, there is no parent.
2486 		 */
2487 		pvp = NULL;
2488 	}
2489 
2490 	if (isnew == 0)
2491 		goto notnew;
2492 
2493 	/*
2494 	 * (isnew) is TRUE, pv is not terminal.
2495 	 *
2496 	 * (1) Add a wire count to the parent page table (pvp).
2497 	 * (2) Allocate a VM page for the page table.
2498 	 * (3) Enter the VM page into the parent page table.
2499 	 *
2500 	 * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2501 	 */
2502 	if (pvp)
2503 		vm_page_wire_quick(pvp->pv_m);
2504 
2505 	for (;;) {
2506 		m = vm_page_alloc(NULL, pv->pv_pindex,
2507 				  VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2508 				  VM_ALLOC_INTERRUPT);
2509 		if (m)
2510 			break;
2511 		vm_wait(0);
2512 	}
2513 	vm_page_wire(m);	/* wire for mapping in parent */
2514 	vm_page_unmanage(m);	/* m must be spinunlocked */
2515 	pmap_zero_page(VM_PAGE_TO_PHYS(m));
2516 	m->valid = VM_PAGE_BITS_ALL;
2517 
2518 	vm_page_spin_lock(m);
2519 	pmap_page_stats_adding(m);
2520 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2521 	pv->pv_m = m;
2522 	vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2523 	vm_page_spin_unlock(m);
2524 
2525 	/*
2526 	 * (isnew) is TRUE, pv is not terminal.
2527 	 *
2528 	 * Wire the page into pvp.  Bump the resident_count for the pmap.
2529 	 * There is no pvp for the top level, address the pm_pml4[] array
2530 	 * directly.
2531 	 *
2532 	 * If the caller wants the parent we return it, otherwise
2533 	 * we just put it away.
2534 	 *
2535 	 * No interlock is needed for pte 0 -> non-zero.
2536 	 *
2537 	 * In the situation where *ptep is valid we might have an unmanaged
2538 	 * page table page shared from another page table which we need to
2539 	 * unshare before installing our private page table page.
2540 	 */
2541 	if (pvp) {
2542 		v = VM_PAGE_TO_PHYS(m) |
2543 		    (pmap->pmap_bits[PG_RW_IDX] |
2544 		     pmap->pmap_bits[PG_V_IDX] |
2545 		     pmap->pmap_bits[PG_A_IDX]);
2546 		if (ptepindex < NUPTE_USER)
2547 			v |= pmap->pmap_bits[PG_U_IDX];
2548 		if (ptepindex < pmap_pt_pindex(0))
2549 			v |= pmap->pmap_bits[PG_M_IDX];
2550 
2551 		ptep = pv_pte_lookup(pvp, ptepindex);
2552 		if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso)
2553 			ptep_iso = pv_pte_lookup(pmap->pm_pmlpv_iso, ptepindex);
2554 		else
2555 			ptep_iso  = NULL;
2556 		if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2557 			pt_entry_t pte;
2558 
2559 			if (ispt == 0) {
2560 				panic("pmap_allocpte: unexpected pte %p/%d",
2561 				      pvp, (int)ptepindex);
2562 			}
2563 			pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2564 					     ptep, v);
2565 			if (ptep_iso) {
2566 				pmap_inval_smp(pmap, (vm_offset_t)-1, 1,
2567 					       ptep_iso, v);
2568 			}
2569 			if (vm_page_unwire_quick(
2570 					PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2571 				panic("pmap_allocpte: shared pgtable "
2572 				      "pg bad wirecount");
2573 			}
2574 		} else {
2575 			pt_entry_t pte;
2576 
2577 			pte = atomic_swap_long(ptep, v);
2578 			if (ptep_iso)
2579 				atomic_swap_long(ptep_iso, v);
2580 			if (pte != 0) {
2581 				kprintf("install pgtbl mixup 0x%016jx "
2582 					"old/new 0x%016jx/0x%016jx\n",
2583 					(intmax_t)ptepindex, pte, v);
2584 			}
2585 		}
2586 	}
2587 	vm_page_wakeup(m);
2588 
2589 	/*
2590 	 * (isnew) may be TRUE or FALSE, pv may or may not be terminal.
2591 	 */
2592 notnew:
2593 	if (pvp) {
2594 		KKASSERT(pvp->pv_m != NULL);
2595 		ptep = pv_pte_lookup(pvp, ptepindex);
2596 		v = VM_PAGE_TO_PHYS(pv->pv_m) |
2597 		    (pmap->pmap_bits[PG_RW_IDX] |
2598 		     pmap->pmap_bits[PG_V_IDX] |
2599 		     pmap->pmap_bits[PG_A_IDX]);
2600 		if (ptepindex < NUPTE_USER)
2601 			v |= pmap->pmap_bits[PG_U_IDX];
2602 		if (ptepindex < pmap_pt_pindex(0))
2603 			v |= pmap->pmap_bits[PG_M_IDX];
2604 		if (*ptep != v) {
2605 			kprintf("mismatched upper level pt %016jx/%016jx\n",
2606 				*ptep, v);
2607 		}
2608 	}
2609 	if (pvpp)
2610 		*pvpp = pvp;
2611 	else if (pvp)
2612 		pv_put(pvp);
2613 	return (pv);
2614 }
2615 
2616 /*
2617  * This version of pmap_allocpte() checks for possible segment optimizations
2618  * that would allow page-table sharing.  It can be called for terminal
2619  * page or page table page ptepindex's.
2620  *
2621  * The function is called with page table page ptepindex's for fictitious
2622  * and unmanaged terminal pages.  That is, we don't want to allocate a
2623  * terminal pv, we just want the pt_pv.  pvpp is usually passed as NULL
2624  * for this case.
2625  *
2626  * This function can return a pv and *pvpp associated with the passed in pmap
2627  * OR a pv and *pvpp associated with the shared pmap.  In the latter case
2628  * an unmanaged page table page will be entered into the pass in pmap.
2629  */
2630 static
2631 pv_entry_t
2632 pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
2633 		  vm_map_entry_t entry, vm_offset_t va)
2634 {
2635 	vm_object_t object;
2636 	pmap_t obpmap;
2637 	pmap_t *obpmapp;
2638 	vm_pindex_t *pt_placemark;
2639 	vm_offset_t b;
2640 	pv_entry_t pte_pv;	/* in original or shared pmap */
2641 	pv_entry_t pt_pv;	/* in original or shared pmap */
2642 	pv_entry_t proc_pd_pv;	/* in original pmap */
2643 	pv_entry_t proc_pt_pv;	/* in original pmap */
2644 	pv_entry_t xpv;		/* PT in shared pmap */
2645 	pd_entry_t *pt;		/* PT entry in PD of original pmap */
2646 	pd_entry_t opte;	/* contents of *pt */
2647 	pd_entry_t npte;	/* contents of *pt */
2648 	vm_page_t m;
2649 	int softhold;
2650 
2651 	/*
2652 	 * Basic tests, require a non-NULL vm_map_entry, require proper
2653 	 * alignment and type for the vm_map_entry, require that the
2654 	 * underlying object already be allocated.
2655 	 *
2656 	 * We allow almost any type of object to use this optimization.
2657 	 * The object itself does NOT have to be sized to a multiple of the
2658 	 * segment size, but the memory mapping does.
2659 	 *
2660 	 * XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
2661 	 *     won't work as expected.
2662 	 */
2663 	if (entry == NULL ||
2664 	    pmap_mmu_optimize == 0 ||			/* not enabled */
2665 	    (pmap->pm_flags & PMAP_HVM) ||		/* special pmap */
2666 	    ptepindex >= pmap_pd_pindex(0) ||		/* not terminal or pt */
2667 	    entry->inheritance != VM_INHERIT_SHARE ||	/* not shared */
2668 	    entry->maptype != VM_MAPTYPE_NORMAL ||	/* weird map type */
2669 	    entry->object.vm_object == NULL ||		/* needs VM object */
2670 	    entry->object.vm_object->type == OBJT_DEVICE ||	/* ick */
2671 	    entry->object.vm_object->type == OBJT_MGTDEVICE ||	/* ick */
2672 	    (entry->offset & SEG_MASK) ||		/* must be aligned */
2673 	    (entry->start & SEG_MASK)) {
2674 		return(pmap_allocpte(pmap, ptepindex, pvpp));
2675 	}
2676 
2677 	/*
2678 	 * Make sure the full segment can be represented.
2679 	 */
2680 	b = va & ~(vm_offset_t)SEG_MASK;
2681 	if (b < entry->start || b + SEG_SIZE > entry->end)
2682 		return(pmap_allocpte(pmap, ptepindex, pvpp));
2683 
2684 	/*
2685 	 * If the full segment can be represented dive the VM object's
2686 	 * shared pmap, allocating as required.
2687 	 */
2688 	object = entry->object.vm_object;
2689 
2690 	if (entry->protection & VM_PROT_WRITE)
2691 		obpmapp = &object->md.pmap_rw;
2692 	else
2693 		obpmapp = &object->md.pmap_ro;
2694 
2695 #ifdef PMAP_DEBUG2
2696 	if (pmap_enter_debug > 0) {
2697 		--pmap_enter_debug;
2698 		kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
2699 			"obpmapp %p %p\n",
2700 			va, entry->protection, object,
2701 			obpmapp, *obpmapp);
2702 		kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
2703 			entry, entry->start, entry->end);
2704 	}
2705 #endif
2706 
2707 	/*
2708 	 * We allocate what appears to be a normal pmap but because portions
2709 	 * of this pmap are shared with other unrelated pmaps we have to
2710 	 * set pm_active to point to all cpus.
2711 	 *
2712 	 * XXX Currently using pmap_spin to interlock the update, can't use
2713 	 *     vm_object_hold/drop because the token might already be held
2714 	 *     shared OR exclusive and we don't know.
2715 	 */
2716 	while ((obpmap = *obpmapp) == NULL) {
2717 		obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
2718 		pmap_pinit_simple(obpmap);
2719 		pmap_pinit2(obpmap);
2720 		spin_lock(&pmap_spin);
2721 		if (*obpmapp != NULL) {
2722 			/*
2723 			 * Handle race
2724 			 */
2725 			spin_unlock(&pmap_spin);
2726 			pmap_release(obpmap);
2727 			pmap_puninit(obpmap);
2728 			kfree(obpmap, M_OBJPMAP);
2729 			obpmap = *obpmapp; /* safety */
2730 		} else {
2731 			obpmap->pm_active = smp_active_mask;
2732 			obpmap->pm_flags |= PMAP_SEGSHARED;
2733 			*obpmapp = obpmap;
2734 			spin_unlock(&pmap_spin);
2735 		}
2736 	}
2737 
2738 	/*
2739 	 * Layering is: PTE, PT, PD, PDP, PML4.  We have to return the
2740 	 * pte/pt using the shared pmap from the object but also adjust
2741 	 * the process pmap's page table page as a side effect.
2742 	 */
2743 
2744 	/*
2745 	 * Resolve the terminal PTE and PT in the shared pmap.  This is what
2746 	 * we will return.  This is true if ptepindex represents a terminal
2747 	 * page, otherwise pte_pv is actually the PT and pt_pv is actually
2748 	 * the PD.
2749 	 */
2750 	pt_pv = NULL;
2751 	pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
2752 	softhold = 0;
2753 retry:
2754 	if (ptepindex >= pmap_pt_pindex(0))
2755 		xpv = pte_pv;
2756 	else
2757 		xpv = pt_pv;
2758 
2759 	/*
2760 	 * Resolve the PD in the process pmap so we can properly share the
2761 	 * page table page.  Lock order is bottom-up (leaf first)!
2762 	 *
2763 	 * NOTE: proc_pt_pv can be NULL.
2764 	 */
2765 	proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b), &pt_placemark);
2766 	proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
2767 #ifdef PMAP_DEBUG2
2768 	if (pmap_enter_debug > 0) {
2769 		--pmap_enter_debug;
2770 		kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
2771 			proc_pt_pv,
2772 			(proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
2773 			proc_pd_pv,
2774 			va);
2775 	}
2776 #endif
2777 
2778 	/*
2779 	 * xpv is the page table page pv from the shared object
2780 	 * (for convenience), from above.
2781 	 *
2782 	 * Calculate the pte value for the PT to load into the process PD.
2783 	 * If we have to change it we must properly dispose of the previous
2784 	 * entry.
2785 	 */
2786 	pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2787 	npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
2788 	       (pmap->pmap_bits[PG_U_IDX] |
2789 		pmap->pmap_bits[PG_RW_IDX] |
2790 		pmap->pmap_bits[PG_V_IDX] |
2791 		pmap->pmap_bits[PG_A_IDX] |
2792 		pmap->pmap_bits[PG_M_IDX]);
2793 
2794 	/*
2795 	 * Dispose of previous page table page if it was local to the
2796 	 * process pmap.  If the old pt is not empty we cannot dispose of it
2797 	 * until we clean it out.  This case should not arise very often so
2798 	 * it is not optimized.
2799 	 *
2800 	 * Leave pt_pv and pte_pv (in our object pmap) locked and intact
2801 	 * for the retry.
2802 	 */
2803 	if (proc_pt_pv) {
2804 		pmap_inval_bulk_t bulk;
2805 
2806 		if (proc_pt_pv->pv_m->wire_count != 1) {
2807 			/*
2808 			 * The page table has a bunch of stuff in it
2809 			 * which we have to scrap.
2810 			 */
2811 			if (softhold == 0) {
2812 				softhold = 1;
2813 				pmap_softhold(pmap);
2814 			}
2815 			pv_put(proc_pd_pv);
2816 			pv_put(proc_pt_pv);
2817 			pmap_remove(pmap,
2818 				    va & ~(vm_offset_t)SEG_MASK,
2819 				    (va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
2820 		} else {
2821 			/*
2822 			 * The page table is empty and can be destroyed.
2823 			 * However, doing so leaves the pt slot unlocked,
2824 			 * so we have to loop-up to handle any races until
2825 			 * we get a NULL proc_pt_pv and a proper pt_placemark.
2826 			 */
2827 			pmap_inval_bulk_init(&bulk, proc_pt_pv->pv_pmap);
2828 			pmap_release_pv(proc_pt_pv, proc_pd_pv, &bulk);
2829 			pmap_inval_bulk_flush(&bulk);
2830 			pv_put(proc_pd_pv);
2831 		}
2832 		goto retry;
2833 	}
2834 
2835 	/*
2836 	 * Handle remaining cases.  We are holding pt_placemark to lock
2837 	 * the page table page in the primary pmap while we manipulate
2838 	 * it.
2839 	 */
2840 	if (*pt == 0) {
2841 		atomic_swap_long(pt, npte);
2842 		vm_page_wire_quick(xpv->pv_m);		/* shared pt -> proc */
2843 		vm_page_wire_quick(proc_pd_pv->pv_m);	/* proc pd for sh pt */
2844 		atomic_add_long(&pmap->pm_stats.resident_count, 1);
2845 	} else if (*pt != npte) {
2846 		opte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, pt, npte);
2847 
2848 #if 0
2849 		opte = pte_load_clear(pt);
2850 		KKASSERT(opte && opte != npte);
2851 
2852 		*pt = npte;
2853 #endif
2854 		vm_page_wire_quick(xpv->pv_m);		/* shared pt -> proc */
2855 
2856 		/*
2857 		 * Clean up opte, bump the wire_count for the process
2858 		 * PD page representing the new entry if it was
2859 		 * previously empty.
2860 		 *
2861 		 * If the entry was not previously empty and we have
2862 		 * a PT in the proc pmap then opte must match that
2863 		 * pt.  The proc pt must be retired (this is done
2864 		 * later on in this procedure).
2865 		 *
2866 		 * NOTE: replacing valid pte, wire_count on proc_pd_pv
2867 		 * stays the same.
2868 		 */
2869 		KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
2870 		m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
2871 		if (vm_page_unwire_quick(m)) {
2872 			panic("pmap_allocpte_seg: "
2873 			      "bad wire count %p",
2874 			      m);
2875 		}
2876 	}
2877 
2878 	if (softhold)
2879 		pmap_softdone(pmap);
2880 
2881 	/*
2882 	 * Remove our earmark on the page table page.
2883 	 */
2884 	pv_placemarker_wakeup(pmap, pt_placemark);
2885 
2886 	/*
2887 	 * The existing process page table was replaced and must be destroyed
2888 	 * here.
2889 	 */
2890 	if (proc_pd_pv)
2891 		pv_put(proc_pd_pv);
2892 	if (pvpp)
2893 		*pvpp = pt_pv;
2894 	else
2895 		pv_put(pt_pv);
2896 	return (pte_pv);
2897 }
2898 
2899 /*
2900  * Release any resources held by the given physical map.
2901  *
2902  * Called when a pmap initialized by pmap_pinit is being released.  Should
2903  * only be called if the map contains no valid mappings.
2904  */
2905 struct pmap_release_info {
2906 	pmap_t	pmap;
2907 	int	retry;
2908 	pv_entry_t pvp;
2909 };
2910 
2911 static int pmap_release_callback(pv_entry_t pv, void *data);
2912 
2913 void
2914 pmap_release(struct pmap *pmap)
2915 {
2916 	struct pmap_release_info info;
2917 
2918 	KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2919 		("pmap still active! %016jx",
2920 		(uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2921 
2922 	/*
2923 	 * There is no longer a pmap_list, if there were we would remove the
2924 	 * pmap from it here.
2925 	 */
2926 
2927 	/*
2928 	 * Pull pv's off the RB tree in order from low to high and release
2929 	 * each page.
2930 	 */
2931 	info.pmap = pmap;
2932 	do {
2933 		info.retry = 0;
2934 		info.pvp = NULL;
2935 
2936 		spin_lock(&pmap->pm_spin);
2937 		RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2938 			pmap_release_callback, &info);
2939 		spin_unlock(&pmap->pm_spin);
2940 
2941 		if (info.pvp)
2942 			pv_put(info.pvp);
2943 	} while (info.retry);
2944 
2945 
2946 	/*
2947 	 * One resident page (the pml4 page) should remain.  Two if
2948 	 * the pmap has implemented an isolated userland PML4E table.
2949 	 * No wired pages should remain.
2950 	 */
2951 	int expected_res = 0;
2952 
2953 	if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0)
2954 		++expected_res;
2955 	if (pmap->pm_pmlpv_iso)
2956 		++expected_res;
2957 
2958 #if 1
2959 	if (pmap->pm_stats.resident_count != expected_res ||
2960 	    pmap->pm_stats.wired_count != 0) {
2961 		kprintf("fatal pmap problem - pmap %p flags %08x "
2962 			"rescnt=%jd wirecnt=%jd\n",
2963 			pmap,
2964 			pmap->pm_flags,
2965 			pmap->pm_stats.resident_count,
2966 			pmap->pm_stats.wired_count);
2967 		tsleep(pmap, 0, "DEAD", 0);
2968 	}
2969 #else
2970 	KKASSERT(pmap->pm_stats.resident_count == expected_res);
2971 	KKASSERT(pmap->pm_stats.wired_count == 0);
2972 #endif
2973 }
2974 
2975 /*
2976  * Called from low to high.  We must cache the proper parent pv so we
2977  * can adjust its wired count.
2978  */
2979 static int
2980 pmap_release_callback(pv_entry_t pv, void *data)
2981 {
2982 	struct pmap_release_info *info = data;
2983 	pmap_t pmap = info->pmap;
2984 	vm_pindex_t pindex;
2985 	int r;
2986 
2987 	/*
2988 	 * Acquire a held and locked pv, check for release race
2989 	 */
2990 	pindex = pv->pv_pindex;
2991 	if (info->pvp == pv) {
2992 		spin_unlock(&pmap->pm_spin);
2993 		info->pvp = NULL;
2994 	} else if (pv_hold_try(pv)) {
2995 		spin_unlock(&pmap->pm_spin);
2996 	} else {
2997 		spin_unlock(&pmap->pm_spin);
2998 		pv_lock(pv);
2999 		pv_put(pv);
3000 		info->retry = 1;
3001 		spin_lock(&pmap->pm_spin);
3002 
3003 		return -1;
3004 	}
3005 	KKASSERT(pv->pv_pmap == pmap && pindex == pv->pv_pindex);
3006 
3007 	if (pv->pv_pindex < pmap_pt_pindex(0)) {
3008 		/*
3009 		 * I am PTE, parent is PT
3010 		 */
3011 		pindex = pv->pv_pindex >> NPTEPGSHIFT;
3012 		pindex += NUPTE_TOTAL;
3013 	} else if (pv->pv_pindex < pmap_pd_pindex(0)) {
3014 		/*
3015 		 * I am PT, parent is PD
3016 		 */
3017 		pindex = (pv->pv_pindex - NUPTE_TOTAL) >> NPDEPGSHIFT;
3018 		pindex += NUPTE_TOTAL + NUPT_TOTAL;
3019 	} else if (pv->pv_pindex < pmap_pdp_pindex(0)) {
3020 		/*
3021 		 * I am PD, parent is PDP
3022 		 */
3023 		pindex = (pv->pv_pindex - NUPTE_TOTAL - NUPT_TOTAL) >>
3024 			 NPDPEPGSHIFT;
3025 		pindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
3026 	} else if (pv->pv_pindex < pmap_pml4_pindex()) {
3027 		/*
3028 		 * I am PDP, parent is PML4.  We always calculate the
3029 		 * normal PML4 here, not the isolated PML4.
3030 		 */
3031 		pindex = pmap_pml4_pindex();
3032 	} else {
3033 		/*
3034 		 * parent is NULL
3035 		 */
3036 		if (info->pvp) {
3037 			pv_put(info->pvp);
3038 			info->pvp = NULL;
3039 		}
3040 		pindex = 0;
3041 	}
3042 	if (pindex) {
3043 		if (info->pvp && info->pvp->pv_pindex != pindex) {
3044 			pv_put(info->pvp);
3045 			info->pvp = NULL;
3046 		}
3047 		if (info->pvp == NULL)
3048 			info->pvp = pv_get(pmap, pindex, NULL);
3049 	} else {
3050 		if (info->pvp) {
3051 			pv_put(info->pvp);
3052 			info->pvp = NULL;
3053 		}
3054 	}
3055 	r = pmap_release_pv(pv, info->pvp, NULL);
3056 	spin_lock(&pmap->pm_spin);
3057 
3058 	return(r);
3059 }
3060 
3061 /*
3062  * Called with held (i.e. also locked) pv.  This function will dispose of
3063  * the lock along with the pv.
3064  *
3065  * If the caller already holds the locked parent page table for pv it
3066  * must pass it as pvp, allowing us to avoid a deadlock, else it can
3067  * pass NULL for pvp.
3068  */
3069 static int
3070 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
3071 {
3072 	vm_page_t p;
3073 
3074 	/*
3075 	 * The pmap is currently not spinlocked, pv is held+locked.
3076 	 * Remove the pv's page from its parent's page table.  The
3077 	 * parent's page table page's wire_count will be decremented.
3078 	 *
3079 	 * This will clean out the pte at any level of the page table.
3080 	 * If smp != 0 all cpus are affected.
3081 	 *
3082 	 * Do not tear-down recursively, its faster to just let the
3083 	 * release run its course.
3084 	 */
3085 	pmap_remove_pv_pte(pv, pvp, bulk, 0);
3086 
3087 	/*
3088 	 * Terminal pvs are unhooked from their vm_pages.  Because
3089 	 * terminal pages aren't page table pages they aren't wired
3090 	 * by us, so we have to be sure not to unwire them either.
3091 	 */
3092 	if (pv->pv_pindex < pmap_pt_pindex(0)) {
3093 		pmap_remove_pv_page(pv);
3094 		goto skip;
3095 	}
3096 
3097 	/*
3098 	 * We leave the top-level page table page cached, wired, and
3099 	 * mapped in the pmap until the dtor function (pmap_puninit())
3100 	 * gets called.
3101 	 *
3102 	 * Since we are leaving the top-level pv intact we need
3103 	 * to break out of what would otherwise be an infinite loop.
3104 	 *
3105 	 * This covers both the normal and the isolated PML4 page.
3106 	 */
3107 	if (pv->pv_pindex >= pmap_pml4_pindex()) {
3108 		pv_put(pv);
3109 		return(-1);
3110 	}
3111 
3112 	/*
3113 	 * For page table pages (other than the top-level page),
3114 	 * remove and free the vm_page.  The representitive mapping
3115 	 * removed above by pmap_remove_pv_pte() did not undo the
3116 	 * last wire_count so we have to do that as well.
3117 	 */
3118 	p = pmap_remove_pv_page(pv);
3119 	vm_page_busy_wait(p, FALSE, "pmaprl");
3120 	if (p->wire_count != 1) {
3121 		kprintf("p->wire_count was %016lx %d\n",
3122 			pv->pv_pindex, p->wire_count);
3123 	}
3124 	KKASSERT(p->wire_count == 1);
3125 	KKASSERT(p->flags & PG_UNMANAGED);
3126 
3127 	vm_page_unwire(p, 0);
3128 	KKASSERT(p->wire_count == 0);
3129 
3130 	vm_page_free(p);
3131 skip:
3132 	pv_free(pv, pvp);
3133 
3134 	return 0;
3135 }
3136 
3137 /*
3138  * This function will remove the pte associated with a pv from its parent.
3139  * Terminal pv's are supported.  All cpus specified by (bulk) are properly
3140  * invalidated.
3141  *
3142  * The wire count will be dropped on the parent page table.  The wire
3143  * count on the page being removed (pv->pv_m) from the parent page table
3144  * is NOT touched.  Note that terminal pages will not have any additional
3145  * wire counts while page table pages will have at least one representing
3146  * the mapping, plus others representing sub-mappings.
3147  *
3148  * NOTE: Cannot be called on kernel page table pages, only KVM terminal
3149  *	 pages and user page table and terminal pages.
3150  *
3151  * NOTE: The pte being removed might be unmanaged, and the pv supplied might
3152  *	 be freshly allocated and not imply that the pte is managed.  In this
3153  *	 case pv->pv_m should be NULL.
3154  *
3155  * The pv must be locked.  The pvp, if supplied, must be locked.  All
3156  * supplied pv's will remain locked on return.
3157  *
3158  * XXX must lock parent pv's if they exist to remove pte XXX
3159  */
3160 static
3161 void
3162 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk,
3163 		   int destroy)
3164 {
3165 	vm_pindex_t ptepindex = pv->pv_pindex;
3166 	pmap_t pmap = pv->pv_pmap;
3167 	vm_page_t p;
3168 	int gotpvp = 0;
3169 
3170 	KKASSERT(pmap);
3171 
3172 	if (ptepindex >= pmap_pml4_pindex()) {
3173 		/*
3174 		 * We are the top level PML4E table, there is no parent.
3175 		 *
3176 		 * This is either the normal or isolated PML4E table.
3177 		 * Only the normal is used in regular operation, the isolated
3178 		 * is only passed in when breaking down the whole pmap.
3179 		 */
3180 		p = pmap->pm_pmlpv->pv_m;
3181 		KKASSERT(pv->pv_m == p);	/* debugging */
3182 	} else if (ptepindex >= pmap_pdp_pindex(0)) {
3183 		/*
3184 		 * Remove a PDP page from the PML4E.  This can only occur
3185 		 * with user page tables.  We do not have to lock the
3186 		 * pml4 PV so just ignore pvp.
3187 		 */
3188 		vm_pindex_t pml4_pindex;
3189 		vm_pindex_t pdp_index;
3190 		pml4_entry_t *pdp;
3191 		pml4_entry_t *pdp_iso;
3192 
3193 		pdp_index = ptepindex - pmap_pdp_pindex(0);
3194 		if (pvp == NULL) {
3195 			pml4_pindex = pmap_pml4_pindex();
3196 			pvp = pv_get(pv->pv_pmap, pml4_pindex, NULL);
3197 			KKASSERT(pvp);
3198 			gotpvp = 1;
3199 		}
3200 
3201 		pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
3202 		KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
3203 		p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3204 		pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
3205 
3206 		/*
3207 		 * Also remove the PDP from the isolated PML4E if the
3208 		 * process uses one.
3209 		 */
3210 		if (pvp == pmap->pm_pmlpv && pmap->pm_pmlpv_iso) {
3211 			pdp_iso = &pmap->pm_pml4_iso[pdp_index &
3212 						((1ul << NPML4EPGSHIFT) - 1)];
3213 			pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp_iso, 0);
3214 		}
3215 		KKASSERT(pv->pv_m == p);	/* debugging */
3216 	} else if (ptepindex >= pmap_pd_pindex(0)) {
3217 		/*
3218 		 * Remove a PD page from the PDP
3219 		 *
3220 		 * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
3221 		 *		     of a simple pmap because it stops at
3222 		 *		     the PD page.
3223 		 */
3224 		vm_pindex_t pdp_pindex;
3225 		vm_pindex_t pd_index;
3226 		pdp_entry_t *pd;
3227 
3228 		pd_index = ptepindex - pmap_pd_pindex(0);
3229 
3230 		if (pvp == NULL) {
3231 			pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
3232 				     (pd_index >> NPML4EPGSHIFT);
3233 			pvp = pv_get(pv->pv_pmap, pdp_pindex, NULL);
3234 			gotpvp = 1;
3235 		}
3236 
3237 		if (pvp) {
3238 			pd = pv_pte_lookup(pvp, pd_index &
3239 						((1ul << NPDPEPGSHIFT) - 1));
3240 			KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
3241 			p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3242 			pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
3243 		} else {
3244 			KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
3245 			p = pv->pv_m;		/* degenerate test later */
3246 		}
3247 		KKASSERT(pv->pv_m == p);	/* debugging */
3248 	} else if (ptepindex >= pmap_pt_pindex(0)) {
3249 		/*
3250 		 *  Remove a PT page from the PD
3251 		 */
3252 		vm_pindex_t pd_pindex;
3253 		vm_pindex_t pt_index;
3254 		pd_entry_t *pt;
3255 
3256 		pt_index = ptepindex - pmap_pt_pindex(0);
3257 
3258 		if (pvp == NULL) {
3259 			pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
3260 				    (pt_index >> NPDPEPGSHIFT);
3261 			pvp = pv_get(pv->pv_pmap, pd_pindex, NULL);
3262 			KKASSERT(pvp);
3263 			gotpvp = 1;
3264 		}
3265 
3266 		pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
3267 #if 0
3268 		KASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0,
3269 			("*pt unexpectedly invalid %016jx "
3270 			 "gotpvp=%d ptepindex=%ld ptindex=%ld pv=%p pvp=%p",
3271 			*pt, gotpvp, ptepindex, pt_index, pv, pvp));
3272 		p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3273 #else
3274 		if ((*pt & pmap->pmap_bits[PG_V_IDX]) == 0) {
3275 			kprintf("*pt unexpectedly invalid %016jx "
3276 			        "gotpvp=%d ptepindex=%ld ptindex=%ld "
3277 				"pv=%p pvp=%p\n",
3278 				*pt, gotpvp, ptepindex, pt_index, pv, pvp);
3279 			tsleep(pt, 0, "DEAD", 0);
3280 			p = pv->pv_m;
3281 		} else {
3282 			p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
3283 		}
3284 #endif
3285 		pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
3286 		KKASSERT(pv->pv_m == p);	/* debugging */
3287 	} else {
3288 		/*
3289 		 * Remove a PTE from the PT page.  The PV might exist even if
3290 		 * the PTE is not managed, in whichcase pv->pv_m should be
3291 		 * NULL.
3292 		 *
3293 		 * NOTE: Userland pmaps manage the parent PT/PD/PDP page
3294 		 *	 table pages but the kernel_pmap does not.
3295 		 *
3296 		 * NOTE: pv's must be locked bottom-up to avoid deadlocking.
3297 		 *	 pv is a pte_pv so we can safely lock pt_pv.
3298 		 *
3299 		 * NOTE: FICTITIOUS pages may have multiple physical mappings
3300 		 *	 so PHYS_TO_VM_PAGE() will not necessarily work for
3301 		 *	 terminal ptes.
3302 		 */
3303 		vm_pindex_t pt_pindex;
3304 		pt_entry_t *ptep;
3305 		pt_entry_t pte;
3306 		vm_offset_t va;
3307 
3308 		pt_pindex = ptepindex >> NPTEPGSHIFT;
3309 		va = (vm_offset_t)ptepindex << PAGE_SHIFT;
3310 
3311 		if (ptepindex >= NUPTE_USER) {
3312 			ptep = vtopte(ptepindex << PAGE_SHIFT);
3313 			KKASSERT(pvp == NULL);
3314 			/* pvp remains NULL */
3315 		} else {
3316 			if (pvp == NULL) {
3317 				pt_pindex = NUPTE_TOTAL +
3318 					    (ptepindex >> NPDPEPGSHIFT);
3319 				pvp = pv_get(pv->pv_pmap, pt_pindex, NULL);
3320 				KKASSERT(pvp);
3321 				gotpvp = 1;
3322 			}
3323 			ptep = pv_pte_lookup(pvp, ptepindex &
3324 						  ((1ul << NPDPEPGSHIFT) - 1));
3325 		}
3326 		pte = pmap_inval_bulk(bulk, va, ptep, 0);
3327 		if (bulk == NULL)		/* XXX */
3328 			cpu_invlpg((void *)va);	/* XXX */
3329 
3330 		/*
3331 		 * Now update the vm_page_t
3332 		 */
3333 		if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3334 		    (pte & pmap->pmap_bits[PG_V_IDX])) {
3335 			/*
3336 			 * Valid managed page, adjust (p).
3337 			 */
3338 			if (pte & pmap->pmap_bits[PG_DEVICE_IDX]) {
3339 				p = pv->pv_m;
3340 			} else {
3341 				p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3342 				KKASSERT(pv->pv_m == p);
3343 			}
3344 			if (pte & pmap->pmap_bits[PG_M_IDX]) {
3345 				if (pmap_track_modified(ptepindex))
3346 					vm_page_dirty(p);
3347 			}
3348 			if (pte & pmap->pmap_bits[PG_A_IDX]) {
3349 				vm_page_flag_set(p, PG_REFERENCED);
3350 			}
3351 		} else {
3352 			/*
3353 			 * Unmanaged page, do not try to adjust the vm_page_t.
3354 			 * pv could be freshly allocated for a pmap_enter(),
3355 			 * replacing an unmanaged page with a managed one.
3356 			 *
3357 			 * pv->pv_m might reflect the new page and not the
3358 			 * existing page.
3359 			 *
3360 			 * We could extract p from the physical address and
3361 			 * adjust it but we explicitly do not for unmanaged
3362 			 * pages.
3363 			 */
3364 			p = NULL;
3365 		}
3366 		if (pte & pmap->pmap_bits[PG_W_IDX])
3367 			atomic_add_long(&pmap->pm_stats.wired_count, -1);
3368 		if (pte & pmap->pmap_bits[PG_G_IDX])
3369 			cpu_invlpg((void *)va);
3370 	}
3371 
3372 	/*
3373 	 * If requested, scrap the underlying pv->pv_m and the underlying
3374 	 * pv.  If this is a page-table-page we must also free the page.
3375 	 *
3376 	 * pvp must be returned locked.
3377 	 */
3378 	if (destroy == 1) {
3379 		/*
3380 		 * page table page (PT, PD, PDP, PML4), caller was responsible
3381 		 * for testing wired_count.
3382 		 */
3383 		KKASSERT(pv->pv_m->wire_count == 1);
3384 		p = pmap_remove_pv_page(pv);
3385 		pv_free(pv, pvp);
3386 		pv = NULL;
3387 
3388 		vm_page_busy_wait(p, FALSE, "pgpun");
3389 		vm_page_unwire(p, 0);
3390 		vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
3391 		vm_page_free(p);
3392 	} else if (destroy == 2) {
3393 		/*
3394 		 * Normal page, remove from pmap and leave the underlying
3395 		 * page untouched.
3396 		 */
3397 		pmap_remove_pv_page(pv);
3398 		pv_free(pv, pvp);
3399 		pv = NULL;		/* safety */
3400 	}
3401 
3402 	/*
3403 	 * If we acquired pvp ourselves then we are responsible for
3404 	 * recursively deleting it.
3405 	 */
3406 	if (pvp && gotpvp) {
3407 		/*
3408 		 * Recursively destroy higher-level page tables.
3409 		 *
3410 		 * This is optional.  If we do not, they will still
3411 		 * be destroyed when the process exits.
3412 		 *
3413 		 * NOTE: Do not destroy pv_entry's with extra hold refs,
3414 		 *	 a caller may have unlocked it and intends to
3415 		 *	 continue to use it.
3416 		 */
3417 		if (pmap_dynamic_delete &&
3418 		    pvp->pv_m &&
3419 		    pvp->pv_m->wire_count == 1 &&
3420 		    (pvp->pv_hold & PV_HOLD_MASK) == 2 &&
3421 		    pvp->pv_pindex < pmap_pml4_pindex()) {
3422 			if (pmap_dynamic_delete == 2)
3423 				kprintf("A %jd %08x\n", pvp->pv_pindex, pvp->pv_hold);
3424 			if (pmap != &kernel_pmap) {
3425 				pmap_remove_pv_pte(pvp, NULL, bulk, 1);
3426 				pvp = NULL;	/* safety */
3427 			} else {
3428 				kprintf("Attempt to remove kernel_pmap pindex "
3429 					"%jd\n", pvp->pv_pindex);
3430 				pv_put(pvp);
3431 			}
3432 		} else {
3433 			pv_put(pvp);
3434 		}
3435 	}
3436 }
3437 
3438 /*
3439  * Remove the vm_page association to a pv.  The pv must be locked.
3440  */
3441 static
3442 vm_page_t
3443 pmap_remove_pv_page(pv_entry_t pv)
3444 {
3445 	vm_page_t m;
3446 
3447 	m = pv->pv_m;
3448 	vm_page_spin_lock(m);
3449 	KKASSERT(m && m == pv->pv_m);
3450 	pv->pv_m = NULL;
3451 	TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3452 	pmap_page_stats_deleting(m);
3453 	if (TAILQ_EMPTY(&m->md.pv_list))
3454 		vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3455 	vm_page_spin_unlock(m);
3456 
3457 	return(m);
3458 }
3459 
3460 /*
3461  * Grow the number of kernel page table entries, if needed.
3462  *
3463  * This routine is always called to validate any address space
3464  * beyond KERNBASE (for kldloads).  kernel_vm_end only governs the address
3465  * space below KERNBASE.
3466  *
3467  * kernel_map must be locked exclusively by the caller.
3468  */
3469 void
3470 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
3471 {
3472 	vm_paddr_t paddr;
3473 	vm_offset_t ptppaddr;
3474 	vm_page_t nkpg;
3475 	pd_entry_t *pt, newpt;
3476 	pdp_entry_t *pd, newpd;
3477 	int update_kernel_vm_end;
3478 
3479 	/*
3480 	 * bootstrap kernel_vm_end on first real VM use
3481 	 */
3482 	if (kernel_vm_end == 0) {
3483 		kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
3484 
3485 		for (;;) {
3486 			pt = pmap_pt(&kernel_pmap, kernel_vm_end);
3487 			if (pt == NULL)
3488 				break;
3489 			if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) == 0)
3490 				break;
3491 			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
3492 					~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3493 			if (kernel_vm_end - 1 >= kernel_map.max_offset) {
3494 				kernel_vm_end = kernel_map.max_offset;
3495 				break;
3496 			}
3497 		}
3498 	}
3499 
3500 	/*
3501 	 * Fill in the gaps.  kernel_vm_end is only adjusted for ranges
3502 	 * below KERNBASE.  Ranges above KERNBASE are kldloaded and we
3503 	 * do not want to force-fill 128G worth of page tables.
3504 	 */
3505 	if (kstart < KERNBASE) {
3506 		if (kstart > kernel_vm_end)
3507 			kstart = kernel_vm_end;
3508 		KKASSERT(kend <= KERNBASE);
3509 		update_kernel_vm_end = 1;
3510 	} else {
3511 		update_kernel_vm_end = 0;
3512 	}
3513 
3514 	kstart = rounddown2(kstart, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3515 	kend = roundup2(kend, (vm_offset_t)(PAGE_SIZE * NPTEPG));
3516 
3517 	if (kend - 1 >= kernel_map.max_offset)
3518 		kend = kernel_map.max_offset;
3519 
3520 	while (kstart < kend) {
3521 		pt = pmap_pt(&kernel_pmap, kstart);
3522 		if (pt == NULL) {
3523 			/*
3524 			 * We need a new PD entry
3525 			 */
3526 			nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3527 			                     VM_ALLOC_NORMAL |
3528 					     VM_ALLOC_SYSTEM |
3529 					     VM_ALLOC_INTERRUPT);
3530 			if (nkpg == NULL) {
3531 				panic("pmap_growkernel: no memory to grow "
3532 				      "kernel");
3533 			}
3534 			paddr = VM_PAGE_TO_PHYS(nkpg);
3535 			pmap_zero_page(paddr);
3536 			pd = pmap_pd(&kernel_pmap, kstart);
3537 
3538 			newpd = (pdp_entry_t)
3539 			    (paddr |
3540 			    kernel_pmap.pmap_bits[PG_V_IDX] |
3541 			    kernel_pmap.pmap_bits[PG_RW_IDX] |
3542 			    kernel_pmap.pmap_bits[PG_A_IDX]);
3543 			atomic_swap_long(pd, newpd);
3544 
3545 #if 0
3546 			kprintf("NEWPD pd=%p pde=%016jx phys=%016jx\n",
3547 				pd, newpd, paddr);
3548 #endif
3549 
3550 			continue; /* try again */
3551 		}
3552 
3553 		if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
3554 			kstart = (kstart + PAGE_SIZE * NPTEPG) &
3555 				 ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3556 			if (kstart - 1 >= kernel_map.max_offset) {
3557 				kstart = kernel_map.max_offset;
3558 				break;
3559 			}
3560 			continue;
3561 		}
3562 
3563 		/*
3564 		 * We need a new PT
3565 		 *
3566 		 * This index is bogus, but out of the way
3567 		 */
3568 		nkpg = vm_page_alloc(NULL, mycpu->gd_rand_incr++,
3569 				     VM_ALLOC_NORMAL |
3570 				     VM_ALLOC_SYSTEM |
3571 				     VM_ALLOC_INTERRUPT);
3572 		if (nkpg == NULL)
3573 			panic("pmap_growkernel: no memory to grow kernel");
3574 
3575 		vm_page_wire(nkpg);
3576 		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
3577 		pmap_zero_page(ptppaddr);
3578 		newpt = (pd_entry_t)(ptppaddr |
3579 				     kernel_pmap.pmap_bits[PG_V_IDX] |
3580 				     kernel_pmap.pmap_bits[PG_RW_IDX] |
3581 				     kernel_pmap.pmap_bits[PG_A_IDX]);
3582 		atomic_swap_long(pt, newpt);
3583 
3584 		kstart = (kstart + PAGE_SIZE * NPTEPG) &
3585 			  ~(vm_offset_t)(PAGE_SIZE * NPTEPG - 1);
3586 
3587 		if (kstart - 1 >= kernel_map.max_offset) {
3588 			kstart = kernel_map.max_offset;
3589 			break;
3590 		}
3591 	}
3592 
3593 	/*
3594 	 * Only update kernel_vm_end for areas below KERNBASE.
3595 	 */
3596 	if (update_kernel_vm_end && kernel_vm_end < kstart)
3597 		kernel_vm_end = kstart;
3598 }
3599 
3600 /*
3601  *	Add a reference to the specified pmap.
3602  */
3603 void
3604 pmap_reference(pmap_t pmap)
3605 {
3606 	if (pmap != NULL)
3607 		atomic_add_int(&pmap->pm_count, 1);
3608 }
3609 
3610 /***************************************************
3611  * page management routines.
3612  ***************************************************/
3613 
3614 /*
3615  * Hold a pv without locking it
3616  */
3617 static void
3618 pv_hold(pv_entry_t pv)
3619 {
3620 	atomic_add_int(&pv->pv_hold, 1);
3621 }
3622 
3623 /*
3624  * Hold a pv_entry, preventing its destruction.  TRUE is returned if the pv
3625  * was successfully locked, FALSE if it wasn't.  The caller must dispose of
3626  * the pv properly.
3627  *
3628  * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
3629  * pv list via its page) must be held by the caller in order to stabilize
3630  * the pv.
3631  */
3632 static int
3633 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
3634 {
3635 	u_int count;
3636 
3637 	/*
3638 	 * Critical path shortcut expects pv to already have one ref
3639 	 * (for the pv->pv_pmap).
3640 	 */
3641 	if (atomic_cmpset_int(&pv->pv_hold, 1, PV_HOLD_LOCKED | 2)) {
3642 #ifdef PMAP_DEBUG
3643 		pv->pv_func = func;
3644 		pv->pv_line = lineno;
3645 #endif
3646 		return TRUE;
3647 	}
3648 
3649 	for (;;) {
3650 		count = pv->pv_hold;
3651 		cpu_ccfence();
3652 		if ((count & PV_HOLD_LOCKED) == 0) {
3653 			if (atomic_cmpset_int(&pv->pv_hold, count,
3654 					      (count + 1) | PV_HOLD_LOCKED)) {
3655 #ifdef PMAP_DEBUG
3656 				pv->pv_func = func;
3657 				pv->pv_line = lineno;
3658 #endif
3659 				return TRUE;
3660 			}
3661 		} else {
3662 			if (atomic_cmpset_int(&pv->pv_hold, count, count + 1))
3663 				return FALSE;
3664 		}
3665 		/* retry */
3666 	}
3667 }
3668 
3669 /*
3670  * Drop a previously held pv_entry which could not be locked, allowing its
3671  * destruction.
3672  *
3673  * Must not be called with a spinlock held as we might zfree() the pv if it
3674  * is no longer associated with a pmap and this was the last hold count.
3675  */
3676 static void
3677 pv_drop(pv_entry_t pv)
3678 {
3679 	u_int count;
3680 
3681 	for (;;) {
3682 		count = pv->pv_hold;
3683 		cpu_ccfence();
3684 		KKASSERT((count & PV_HOLD_MASK) > 0);
3685 		KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
3686 			 (PV_HOLD_LOCKED | 1));
3687 		if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
3688 			if ((count & PV_HOLD_MASK) == 1) {
3689 #ifdef PMAP_DEBUG2
3690 				if (pmap_enter_debug > 0) {
3691 					--pmap_enter_debug;
3692 					kprintf("pv_drop: free pv %p\n", pv);
3693 				}
3694 #endif
3695 				KKASSERT(count == 1);
3696 				KKASSERT(pv->pv_pmap == NULL);
3697 				zfree(pvzone, pv);
3698 			}
3699 			return;
3700 		}
3701 		/* retry */
3702 	}
3703 }
3704 
3705 /*
3706  * Find or allocate the requested PV entry, returning a locked, held pv.
3707  *
3708  * If (*isnew) is non-zero, the returned pv will have two hold counts, one
3709  * for the caller and one representing the pmap and vm_page association.
3710  *
3711  * If (*isnew) is zero, the returned pv will have only one hold count.
3712  *
3713  * Since both associations can only be adjusted while the pv is locked,
3714  * together they represent just one additional hold.
3715  */
3716 static
3717 pv_entry_t
3718 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
3719 {
3720 	struct mdglobaldata *md = mdcpu;
3721 	pv_entry_t pv;
3722 	pv_entry_t pnew;
3723 	int pmap_excl = 0;
3724 
3725 	pnew = NULL;
3726 	if (md->gd_newpv) {
3727 #if 1
3728 		pnew = atomic_swap_ptr((void *)&md->gd_newpv, NULL);
3729 #else
3730 		crit_enter();
3731 		pnew = md->gd_newpv;	/* might race NULL */
3732 		md->gd_newpv = NULL;
3733 		crit_exit();
3734 #endif
3735 	}
3736 	if (pnew == NULL)
3737 		pnew = zalloc(pvzone);
3738 
3739 	spin_lock_shared(&pmap->pm_spin);
3740 	for (;;) {
3741 		/*
3742 		 * Shortcut cache
3743 		 */
3744 		pv = pv_entry_lookup(pmap, pindex);
3745 		if (pv == NULL) {
3746 			vm_pindex_t *pmark;
3747 
3748 			/*
3749 			 * Requires exclusive pmap spinlock
3750 			 */
3751 			if (pmap_excl == 0) {
3752 				pmap_excl = 1;
3753 				if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3754 					spin_unlock_shared(&pmap->pm_spin);
3755 					spin_lock(&pmap->pm_spin);
3756 					continue;
3757 				}
3758 			}
3759 
3760 			/*
3761 			 * We need to block if someone is holding our
3762 			 * placemarker.  As long as we determine the
3763 			 * placemarker has not been aquired we do not
3764 			 * need to get it as acquision also requires
3765 			 * the pmap spin lock.
3766 			 *
3767 			 * However, we can race the wakeup.
3768 			 */
3769 			pmark = pmap_placemarker_hash(pmap, pindex);
3770 
3771 			if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3772 				atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3773 				tsleep_interlock(pmark, 0);
3774 				if (((*pmark ^ pindex) &
3775 				     ~PM_PLACEMARK_WAKEUP) == 0) {
3776 					spin_unlock(&pmap->pm_spin);
3777 					tsleep(pmark, PINTERLOCKED, "pvplc", 0);
3778 					spin_lock(&pmap->pm_spin);
3779 				}
3780 				continue;
3781 			}
3782 
3783 			/*
3784 			 * Setup the new entry
3785 			 */
3786 			pnew->pv_pmap = pmap;
3787 			pnew->pv_pindex = pindex;
3788 			pnew->pv_hold = PV_HOLD_LOCKED | 2;
3789 #ifdef PMAP_DEBUG
3790 			pnew->pv_func = func;
3791 			pnew->pv_line = lineno;
3792 			if (pnew->pv_line_lastfree > 0) {
3793 				pnew->pv_line_lastfree =
3794 						-pnew->pv_line_lastfree;
3795 			}
3796 #endif
3797 			pv = pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
3798 			atomic_add_long(&pmap->pm_stats.resident_count, 1);
3799 			spin_unlock(&pmap->pm_spin);
3800 			*isnew = 1;
3801 
3802 			KKASSERT(pv == NULL);
3803 			return(pnew);
3804 		}
3805 
3806 		/*
3807 		 * We already have an entry, cleanup the staged pnew if
3808 		 * we can get the lock, otherwise block and retry.
3809 		 */
3810 		if (__predict_true(_pv_hold_try(pv PMAP_DEBUG_COPY))) {
3811 			if (pmap_excl)
3812 				spin_unlock(&pmap->pm_spin);
3813 			else
3814 				spin_unlock_shared(&pmap->pm_spin);
3815 #if 1
3816 			pnew = atomic_swap_ptr((void *)&md->gd_newpv, pnew);
3817 			if (pnew)
3818 				zfree(pvzone, pnew);
3819 #else
3820 			crit_enter();
3821 			if (md->gd_newpv == NULL)
3822 				md->gd_newpv = pnew;
3823 			else
3824 				zfree(pvzone, pnew);
3825 			crit_exit();
3826 #endif
3827 			KKASSERT(pv->pv_pmap == pmap &&
3828 				 pv->pv_pindex == pindex);
3829 			*isnew = 0;
3830 			return(pv);
3831 		}
3832 		if (pmap_excl) {
3833 			spin_unlock(&pmap->pm_spin);
3834 			_pv_lock(pv PMAP_DEBUG_COPY);
3835 			pv_put(pv);
3836 			spin_lock(&pmap->pm_spin);
3837 		} else {
3838 			spin_unlock_shared(&pmap->pm_spin);
3839 			_pv_lock(pv PMAP_DEBUG_COPY);
3840 			pv_put(pv);
3841 			spin_lock_shared(&pmap->pm_spin);
3842 		}
3843 	}
3844 	/* NOT REACHED */
3845 }
3846 
3847 /*
3848  * Find the requested PV entry, returning a locked+held pv or NULL
3849  */
3850 static
3851 pv_entry_t
3852 _pv_get(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp PMAP_DEBUG_DECL)
3853 {
3854 	pv_entry_t pv;
3855 	int pmap_excl = 0;
3856 
3857 	spin_lock_shared(&pmap->pm_spin);
3858 	for (;;) {
3859 		/*
3860 		 * Shortcut cache
3861 		 */
3862 		pv = pv_entry_lookup(pmap, pindex);
3863 		if (pv == NULL) {
3864 			/*
3865 			 * Block if there is ANY placemarker.  If we are to
3866 			 * return it, we must also aquire the spot, so we
3867 			 * have to block even if the placemarker is held on
3868 			 * a different address.
3869 			 *
3870 			 * OPTIMIZATION: If pmarkp is passed as NULL the
3871 			 * caller is just probing (or looking for a real
3872 			 * pv_entry), and in this case we only need to check
3873 			 * to see if the placemarker matches pindex.
3874 			 */
3875 			vm_pindex_t *pmark;
3876 
3877 			/*
3878 			 * Requires exclusive pmap spinlock
3879 			 */
3880 			if (pmap_excl == 0) {
3881 				pmap_excl = 1;
3882 				if (!spin_lock_upgrade_try(&pmap->pm_spin)) {
3883 					spin_unlock_shared(&pmap->pm_spin);
3884 					spin_lock(&pmap->pm_spin);
3885 					continue;
3886 				}
3887 			}
3888 
3889 			pmark = pmap_placemarker_hash(pmap, pindex);
3890 
3891 			if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3892 			    ((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3893 				atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
3894 				tsleep_interlock(pmark, 0);
3895 				if ((pmarkp && *pmark != PM_NOPLACEMARK) ||
3896 				    ((*pmark ^ pindex) &
3897 				     ~PM_PLACEMARK_WAKEUP) == 0) {
3898 					spin_unlock(&pmap->pm_spin);
3899 					tsleep(pmark, PINTERLOCKED, "pvpld", 0);
3900 					spin_lock(&pmap->pm_spin);
3901 				}
3902 				continue;
3903 			}
3904 			if (pmarkp) {
3905 				if (atomic_swap_long(pmark, pindex) !=
3906 				    PM_NOPLACEMARK) {
3907 					panic("_pv_get: pmark race");
3908 				}
3909 				*pmarkp = pmark;
3910 			}
3911 			spin_unlock(&pmap->pm_spin);
3912 			return NULL;
3913 		}
3914 		if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3915 			pv_cache(pv, pindex);
3916 			if (pmap_excl)
3917 				spin_unlock(&pmap->pm_spin);
3918 			else
3919 				spin_unlock_shared(&pmap->pm_spin);
3920 			KKASSERT(pv->pv_pmap == pmap &&
3921 				 pv->pv_pindex == pindex);
3922 			return(pv);
3923 		}
3924 		if (pmap_excl) {
3925 			spin_unlock(&pmap->pm_spin);
3926 			_pv_lock(pv PMAP_DEBUG_COPY);
3927 			pv_put(pv);
3928 			spin_lock(&pmap->pm_spin);
3929 		} else {
3930 			spin_unlock_shared(&pmap->pm_spin);
3931 			_pv_lock(pv PMAP_DEBUG_COPY);
3932 			pv_put(pv);
3933 			spin_lock_shared(&pmap->pm_spin);
3934 		}
3935 	}
3936 }
3937 
3938 /*
3939  * Lookup, hold, and attempt to lock (pmap,pindex).
3940  *
3941  * If the entry does not exist NULL is returned and *errorp is set to 0
3942  *
3943  * If the entry exists and could be successfully locked it is returned and
3944  * errorp is set to 0.
3945  *
3946  * If the entry exists but could NOT be successfully locked it is returned
3947  * held and *errorp is set to 1.
3948  *
3949  * If the entry is placemarked by someone else NULL is returned and *errorp
3950  * is set to 1.
3951  */
3952 static
3953 pv_entry_t
3954 pv_get_try(pmap_t pmap, vm_pindex_t pindex, vm_pindex_t **pmarkp, int *errorp)
3955 {
3956 	pv_entry_t pv;
3957 
3958 	spin_lock_shared(&pmap->pm_spin);
3959 
3960 	pv = pv_entry_lookup(pmap, pindex);
3961 	if (pv == NULL) {
3962 		vm_pindex_t *pmark;
3963 
3964 		pmark = pmap_placemarker_hash(pmap, pindex);
3965 
3966 		if (((*pmark ^ pindex) & ~PM_PLACEMARK_WAKEUP) == 0) {
3967 			*errorp = 1;
3968 		} else if (pmarkp &&
3969 			   atomic_cmpset_long(pmark, PM_NOPLACEMARK, pindex)) {
3970 			*errorp = 0;
3971 		} else {
3972 			/*
3973 			 * Can't set a placemark with a NULL pmarkp, or if
3974 			 * pmarkp is non-NULL but we failed to set our
3975 			 * placemark.
3976 			 */
3977 			*errorp = 1;
3978 		}
3979 		if (pmarkp)
3980 			*pmarkp = pmark;
3981 		spin_unlock_shared(&pmap->pm_spin);
3982 
3983 		return NULL;
3984 	}
3985 
3986 	/*
3987 	 * XXX This has problems if the lock is shared, why?
3988 	 */
3989 	if (pv_hold_try(pv)) {
3990 		pv_cache(pv, pindex);	/* overwrite ok (shared lock) */
3991 		spin_unlock_shared(&pmap->pm_spin);
3992 		*errorp = 0;
3993 		KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3994 		return(pv);	/* lock succeeded */
3995 	}
3996 	spin_unlock_shared(&pmap->pm_spin);
3997 	*errorp = 1;
3998 
3999 	return (pv);		/* lock failed */
4000 }
4001 
4002 /*
4003  * Lock a held pv, keeping the hold count
4004  */
4005 static
4006 void
4007 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
4008 {
4009 	u_int count;
4010 
4011 	for (;;) {
4012 		count = pv->pv_hold;
4013 		cpu_ccfence();
4014 		if ((count & PV_HOLD_LOCKED) == 0) {
4015 			if (atomic_cmpset_int(&pv->pv_hold, count,
4016 					      count | PV_HOLD_LOCKED)) {
4017 #ifdef PMAP_DEBUG
4018 				pv->pv_func = func;
4019 				pv->pv_line = lineno;
4020 #endif
4021 				return;
4022 			}
4023 			continue;
4024 		}
4025 		tsleep_interlock(pv, 0);
4026 		if (atomic_cmpset_int(&pv->pv_hold, count,
4027 				      count | PV_HOLD_WAITING)) {
4028 #ifdef PMAP_DEBUG2
4029 			if (pmap_enter_debug > 0) {
4030 				--pmap_enter_debug;
4031 				kprintf("pv waiting on %s:%d\n",
4032 					pv->pv_func, pv->pv_line);
4033 			}
4034 #endif
4035 			tsleep(pv, PINTERLOCKED, "pvwait", hz);
4036 		}
4037 		/* retry */
4038 	}
4039 }
4040 
4041 /*
4042  * Unlock a held and locked pv, keeping the hold count.
4043  */
4044 static
4045 void
4046 pv_unlock(pv_entry_t pv)
4047 {
4048 	u_int count;
4049 
4050 	for (;;) {
4051 		count = pv->pv_hold;
4052 		cpu_ccfence();
4053 		KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
4054 			 (PV_HOLD_LOCKED | 1));
4055 		if (atomic_cmpset_int(&pv->pv_hold, count,
4056 				      count &
4057 				      ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
4058 			if (count & PV_HOLD_WAITING)
4059 				wakeup(pv);
4060 			break;
4061 		}
4062 	}
4063 }
4064 
4065 /*
4066  * Unlock and drop a pv.  If the pv is no longer associated with a pmap
4067  * and the hold count drops to zero we will free it.
4068  *
4069  * Caller should not hold any spin locks.  We are protected from hold races
4070  * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
4071  * lock held.  A pv cannot be located otherwise.
4072  */
4073 static
4074 void
4075 pv_put(pv_entry_t pv)
4076 {
4077 #ifdef PMAP_DEBUG2
4078 	if (pmap_enter_debug > 0) {
4079 		--pmap_enter_debug;
4080 		kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
4081 	}
4082 #endif
4083 
4084 	/*
4085 	 * Normal put-aways must have a pv_m associated with the pv,
4086 	 * but allow the case where the pv has been destructed due
4087 	 * to pmap_dynamic_delete.
4088 	 */
4089 	KKASSERT(pv->pv_pmap == NULL || pv->pv_m != NULL);
4090 
4091 	/*
4092 	 * Fast - shortcut most common condition
4093 	 */
4094 	if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
4095 		return;
4096 
4097 	/*
4098 	 * Slow
4099 	 */
4100 	pv_unlock(pv);
4101 	pv_drop(pv);
4102 }
4103 
4104 /*
4105  * Remove the pmap association from a pv, require that pv_m already be removed,
4106  * then unlock and drop the pv.  Any pte operations must have already been
4107  * completed.  This call may result in a last-drop which will physically free
4108  * the pv.
4109  *
4110  * Removing the pmap association entails an additional drop.
4111  *
4112  * pv must be exclusively locked on call and will be disposed of on return.
4113  */
4114 static
4115 void
4116 _pv_free(pv_entry_t pv, pv_entry_t pvp PMAP_DEBUG_DECL)
4117 {
4118 	pmap_t pmap;
4119 
4120 #ifdef PMAP_DEBUG
4121 	pv->pv_func_lastfree = func;
4122 	pv->pv_line_lastfree = lineno;
4123 #endif
4124 	KKASSERT(pv->pv_m == NULL);
4125 	KKASSERT((pv->pv_hold & (PV_HOLD_LOCKED|PV_HOLD_MASK)) >=
4126 		  (PV_HOLD_LOCKED|1));
4127 	if ((pmap = pv->pv_pmap) != NULL) {
4128 		spin_lock(&pmap->pm_spin);
4129 		KKASSERT(pv->pv_pmap == pmap);
4130 		if (pmap->pm_pvhint_pt == pv)
4131 			pmap->pm_pvhint_pt = NULL;
4132 		if (pmap->pm_pvhint_pte == pv)
4133 			pmap->pm_pvhint_pte = NULL;
4134 		pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
4135 		atomic_add_long(&pmap->pm_stats.resident_count, -1);
4136 		pv->pv_pmap = NULL;
4137 		pv->pv_pindex = 0;
4138 		spin_unlock(&pmap->pm_spin);
4139 
4140 		/*
4141 		 * Try to shortcut three atomic ops, otherwise fall through
4142 		 * and do it normally.  Drop two refs and the lock all in
4143 		 * one go.
4144 		 */
4145 		if (pvp)
4146 			vm_page_unwire_quick(pvp->pv_m);
4147 		if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
4148 #ifdef PMAP_DEBUG2
4149 			if (pmap_enter_debug > 0) {
4150 				--pmap_enter_debug;
4151 				kprintf("pv_free: free pv %p\n", pv);
4152 			}
4153 #endif
4154 			zfree(pvzone, pv);
4155 			return;
4156 		}
4157 		pv_drop(pv);	/* ref for pv_pmap */
4158 	}
4159 	pv_unlock(pv);
4160 	pv_drop(pv);
4161 }
4162 
4163 /*
4164  * This routine is very drastic, but can save the system
4165  * in a pinch.
4166  */
4167 void
4168 pmap_collect(void)
4169 {
4170 	int i;
4171 	vm_page_t m;
4172 	static int warningdone=0;
4173 
4174 	if (pmap_pagedaemon_waken == 0)
4175 		return;
4176 	pmap_pagedaemon_waken = 0;
4177 	if (warningdone < 5) {
4178 		kprintf("pmap_collect: collecting pv entries -- "
4179 			"suggest increasing PMAP_SHPGPERPROC\n");
4180 		warningdone++;
4181 	}
4182 
4183 	for (i = 0; i < vm_page_array_size; i++) {
4184 		m = &vm_page_array[i];
4185 		if (m->wire_count || m->hold_count)
4186 			continue;
4187 		if (vm_page_busy_try(m, TRUE) == 0) {
4188 			if (m->wire_count == 0 && m->hold_count == 0) {
4189 				pmap_remove_all(m);
4190 			}
4191 			vm_page_wakeup(m);
4192 		}
4193 	}
4194 }
4195 
4196 /*
4197  * Scan the pmap for active page table entries and issue a callback.
4198  * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
4199  * its parent page table.
4200  *
4201  * pte_pv will be NULL if the page or page table is unmanaged.
4202  * pt_pv will point to the page table page containing the pte for the page.
4203  *
4204  * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
4205  *	 we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
4206  *	 process pmap's PD and page to the callback function.  This can be
4207  *	 confusing because the pt_pv is really a pd_pv, and the target page
4208  *	 table page is simply aliased by the pmap and not owned by it.
4209  *
4210  * It is assumed that the start and end are properly rounded to the page size.
4211  *
4212  * It is assumed that PD pages and above are managed and thus in the RB tree,
4213  * allowing us to use RB_SCAN from the PD pages down for ranged scans.
4214  */
4215 struct pmap_scan_info {
4216 	struct pmap *pmap;
4217 	vm_offset_t sva;
4218 	vm_offset_t eva;
4219 	vm_pindex_t sva_pd_pindex;
4220 	vm_pindex_t eva_pd_pindex;
4221 	void (*func)(pmap_t, struct pmap_scan_info *,
4222 		     pv_entry_t, vm_pindex_t *, pv_entry_t,
4223 		     int, vm_offset_t,
4224 		     pt_entry_t *, void *);
4225 	void *arg;
4226 	pmap_inval_bulk_t bulk_core;
4227 	pmap_inval_bulk_t *bulk;
4228 	int count;
4229 	int stop;
4230 };
4231 
4232 static int pmap_scan_cmp(pv_entry_t pv, void *data);
4233 static int pmap_scan_callback(pv_entry_t pv, void *data);
4234 
4235 static void
4236 pmap_scan(struct pmap_scan_info *info, int smp_inval)
4237 {
4238 	struct pmap *pmap = info->pmap;
4239 	pv_entry_t pd_pv;	/* A page directory PV */
4240 	pv_entry_t pt_pv;	/* A page table PV */
4241 	pv_entry_t pte_pv;	/* A page table entry PV */
4242 	vm_pindex_t *pte_placemark;
4243 	vm_pindex_t *pt_placemark;
4244 	pt_entry_t *ptep;
4245 	pt_entry_t oldpte;
4246 	struct pv_entry dummy_pv;
4247 
4248 	info->stop = 0;
4249 	if (pmap == NULL)
4250 		return;
4251 	if (info->sva == info->eva)
4252 		return;
4253 	if (smp_inval) {
4254 		info->bulk = &info->bulk_core;
4255 		pmap_inval_bulk_init(&info->bulk_core, pmap);
4256 	} else {
4257 		info->bulk = NULL;
4258 	}
4259 
4260 	/*
4261 	 * Hold the token for stability; if the pmap is empty we have nothing
4262 	 * to do.
4263 	 */
4264 #if 0
4265 	if (pmap->pm_stats.resident_count == 0) {
4266 		return;
4267 	}
4268 #endif
4269 
4270 	info->count = 0;
4271 
4272 	/*
4273 	 * Special handling for scanning one page, which is a very common
4274 	 * operation (it is?).
4275 	 *
4276 	 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
4277 	 */
4278 	if (info->sva + PAGE_SIZE == info->eva) {
4279 		if (info->sva >= VM_MAX_USER_ADDRESS) {
4280 			/*
4281 			 * Kernel mappings do not track wire counts on
4282 			 * page table pages and only maintain pd_pv and
4283 			 * pte_pv levels so pmap_scan() works.
4284 			 */
4285 			pt_pv = NULL;
4286 			pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4287 					&pte_placemark);
4288 			ptep = vtopte(info->sva);
4289 		} else {
4290 			/*
4291 			 * User pages which are unmanaged will not have a
4292 			 * pte_pv.  User page table pages which are unmanaged
4293 			 * (shared from elsewhere) will also not have a pt_pv.
4294 			 * The func() callback will pass both pte_pv and pt_pv
4295 			 * as NULL in that case.
4296 			 *
4297 			 * We hold pte_placemark across the operation for
4298 			 * unmanaged pages.
4299 			 *
4300 			 * WARNING!  We must hold pt_placemark across the
4301 			 *	     *ptep test to prevent misintepreting
4302 			 *	     a non-zero *ptep as a shared page
4303 			 *	     table page.  Hold it across the function
4304 			 *	     callback as well for SMP safety.
4305 			 */
4306 			pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva),
4307 					&pte_placemark);
4308 			pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva),
4309 					&pt_placemark);
4310 			if (pt_pv == NULL) {
4311 				KKASSERT(pte_pv == NULL);
4312 				pd_pv = pv_get(pmap,
4313 					       pmap_pd_pindex(info->sva),
4314 					       NULL);
4315 				if (pd_pv) {
4316 					ptep = pv_pte_lookup(pd_pv,
4317 						    pmap_pt_index(info->sva));
4318 					if (*ptep) {
4319 						info->func(pmap, info,
4320 						     NULL, pt_placemark,
4321 						     pd_pv, 1,
4322 						     info->sva, ptep,
4323 						     info->arg);
4324 					} else {
4325 						pv_placemarker_wakeup(pmap,
4326 								  pt_placemark);
4327 					}
4328 					pv_put(pd_pv);
4329 				} else {
4330 					pv_placemarker_wakeup(pmap,
4331 							      pt_placemark);
4332 				}
4333 				pv_placemarker_wakeup(pmap, pte_placemark);
4334 				goto fast_skip;
4335 			}
4336 			ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
4337 		}
4338 
4339 		/*
4340 		 * NOTE: *ptep can't be ripped out from under us if we hold
4341 		 *	 pte_pv (or pte_placemark) locked, but bits can
4342 		 *	 change.
4343 		 */
4344 		oldpte = *ptep;
4345 		cpu_ccfence();
4346 		if (oldpte == 0) {
4347 			KKASSERT(pte_pv == NULL);
4348 			pv_placemarker_wakeup(pmap, pte_placemark);
4349 		} else if (pte_pv) {
4350 			KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4351 					   pmap->pmap_bits[PG_V_IDX])) ==
4352 				(pmap->pmap_bits[PG_MANAGED_IDX] |
4353 				 pmap->pmap_bits[PG_V_IDX]),
4354 			    ("badA *ptep %016lx/%016lx sva %016lx pte_pv %p",
4355 			    *ptep, oldpte, info->sva, pte_pv));
4356 			info->func(pmap, info, pte_pv, NULL, pt_pv, 0,
4357 				   info->sva, ptep, info->arg);
4358 		} else {
4359 			KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
4360 					   pmap->pmap_bits[PG_V_IDX])) ==
4361 			    pmap->pmap_bits[PG_V_IDX],
4362 			    ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL",
4363 			    *ptep, oldpte, info->sva));
4364 			info->func(pmap, info, NULL, pte_placemark, pt_pv, 0,
4365 				   info->sva, ptep, info->arg);
4366 		}
4367 		if (pt_pv)
4368 			pv_put(pt_pv);
4369 fast_skip:
4370 		pmap_inval_bulk_flush(info->bulk);
4371 		return;
4372 	}
4373 
4374 	/*
4375 	 * Nominal scan case, RB_SCAN() for PD pages and iterate from
4376 	 * there.
4377 	 *
4378 	 * WARNING! eva can overflow our standard ((N + mask) >> bits)
4379 	 *	    bounds, resulting in a pd_pindex of 0.  To solve the
4380 	 *	    problem we use an inclusive range.
4381 	 */
4382 	info->sva_pd_pindex = pmap_pd_pindex(info->sva);
4383 	info->eva_pd_pindex = pmap_pd_pindex(info->eva - PAGE_SIZE);
4384 
4385 	if (info->sva >= VM_MAX_USER_ADDRESS) {
4386 		/*
4387 		 * The kernel does not currently maintain any pv_entry's for
4388 		 * higher-level page tables.
4389 		 */
4390 		bzero(&dummy_pv, sizeof(dummy_pv));
4391 		dummy_pv.pv_pindex = info->sva_pd_pindex;
4392 		spin_lock(&pmap->pm_spin);
4393 		while (dummy_pv.pv_pindex <= info->eva_pd_pindex) {
4394 			pmap_scan_callback(&dummy_pv, info);
4395 			++dummy_pv.pv_pindex;
4396 			if (dummy_pv.pv_pindex < info->sva_pd_pindex) /*wrap*/
4397 				break;
4398 		}
4399 		spin_unlock(&pmap->pm_spin);
4400 	} else {
4401 		/*
4402 		 * User page tables maintain local PML4, PDP, and PD
4403 		 * pv_entry's at the very least.  PT pv's might be
4404 		 * unmanaged and thus not exist.  PTE pv's might be
4405 		 * unmanaged and thus not exist.
4406 		 */
4407 		spin_lock(&pmap->pm_spin);
4408 		pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot, pmap_scan_cmp,
4409 					 pmap_scan_callback, info);
4410 		spin_unlock(&pmap->pm_spin);
4411 	}
4412 	pmap_inval_bulk_flush(info->bulk);
4413 }
4414 
4415 /*
4416  * WARNING! pmap->pm_spin held
4417  *
4418  * WARNING! eva can overflow our standard ((N + mask) >> bits)
4419  *	    bounds, resulting in a pd_pindex of 0.  To solve the
4420  *	    problem we use an inclusive range.
4421  */
4422 static int
4423 pmap_scan_cmp(pv_entry_t pv, void *data)
4424 {
4425 	struct pmap_scan_info *info = data;
4426 	if (pv->pv_pindex < info->sva_pd_pindex)
4427 		return(-1);
4428 	if (pv->pv_pindex > info->eva_pd_pindex)
4429 		return(1);
4430 	return(0);
4431 }
4432 
4433 /*
4434  * pmap_scan() by PDs
4435  *
4436  * WARNING! pmap->pm_spin held
4437  */
4438 static int
4439 pmap_scan_callback(pv_entry_t pv, void *data)
4440 {
4441 	struct pmap_scan_info *info = data;
4442 	struct pmap *pmap = info->pmap;
4443 	pv_entry_t pd_pv;	/* A page directory PV */
4444 	pv_entry_t pt_pv;	/* A page table PV */
4445 	vm_pindex_t *pt_placemark;
4446 	pt_entry_t *ptep;
4447 	pt_entry_t oldpte;
4448 	vm_offset_t sva;
4449 	vm_offset_t eva;
4450 	vm_offset_t va_next;
4451 	vm_pindex_t pd_pindex;
4452 	int error;
4453 
4454 	/*
4455 	 * Stop if requested
4456 	 */
4457 	if (info->stop)
4458 		return -1;
4459 
4460 	/*
4461 	 * Pull the PD pindex from the pv before releasing the spinlock.
4462 	 *
4463 	 * WARNING: pv is faked for kernel pmap scans.
4464 	 */
4465 	pd_pindex = pv->pv_pindex;
4466 	spin_unlock(&pmap->pm_spin);
4467 	pv = NULL;	/* invalid after spinlock unlocked */
4468 
4469 	/*
4470 	 * Calculate the page range within the PD.  SIMPLE pmaps are
4471 	 * direct-mapped for the entire 2^64 address space.  Normal pmaps
4472 	 * reflect the user and kernel address space which requires
4473 	 * cannonicalization w/regards to converting pd_pindex's back
4474 	 * into addresses.
4475 	 */
4476 	sva = (pd_pindex - pmap_pd_pindex(0)) << PDPSHIFT;
4477 	if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
4478 	    (sva & PML4_SIGNMASK)) {
4479 		sva |= PML4_SIGNMASK;
4480 	}
4481 	eva = sva + NBPDP;	/* can overflow */
4482 	if (sva < info->sva)
4483 		sva = info->sva;
4484 	if (eva < info->sva || eva > info->eva)
4485 		eva = info->eva;
4486 
4487 	/*
4488 	 * NOTE: kernel mappings do not track page table pages, only
4489 	 * 	 terminal pages.
4490 	 *
4491 	 * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
4492 	 *	 However, for the scan to be efficient we try to
4493 	 *	 cache items top-down.
4494 	 */
4495 	pd_pv = NULL;
4496 	pt_pv = NULL;
4497 
4498 	for (; sva < eva; sva = va_next) {
4499 		if (info->stop)
4500 			break;
4501 		if (sva >= VM_MAX_USER_ADDRESS) {
4502 			if (pt_pv) {
4503 				pv_put(pt_pv);
4504 				pt_pv = NULL;
4505 			}
4506 			goto kernel_skip;
4507 		}
4508 
4509 		/*
4510 		 * PD cache, scan shortcut if it doesn't exist.
4511 		 */
4512 		if (pd_pv == NULL) {
4513 			pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4514 		} else if (pd_pv->pv_pmap != pmap ||
4515 			   pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
4516 			pv_put(pd_pv);
4517 			pd_pv = pv_get(pmap, pmap_pd_pindex(sva), NULL);
4518 		}
4519 		if (pd_pv == NULL) {
4520 			va_next = (sva + NBPDP) & ~PDPMASK;
4521 			if (va_next < sva)
4522 				va_next = eva;
4523 			continue;
4524 		}
4525 
4526 		/*
4527 		 * PT cache
4528 		 *
4529 		 * NOTE: The cached pt_pv can be removed from the pmap when
4530 		 *	 pmap_dynamic_delete is enabled.
4531 		 */
4532 		if (pt_pv && (pt_pv->pv_pmap != pmap ||
4533 			      pt_pv->pv_pindex != pmap_pt_pindex(sva))) {
4534 			pv_put(pt_pv);
4535 			pt_pv = NULL;
4536 		}
4537 		if (pt_pv == NULL) {
4538 			pt_pv = pv_get_try(pmap, pmap_pt_pindex(sva),
4539 					   &pt_placemark, &error);
4540 			if (error) {
4541 				pv_put(pd_pv);	/* lock order */
4542 				pd_pv = NULL;
4543 				if (pt_pv) {
4544 					pv_lock(pt_pv);
4545 					pv_put(pt_pv);
4546 					pt_pv = NULL;
4547 				} else {
4548 					pv_placemarker_wait(pmap, pt_placemark);
4549 				}
4550 				va_next = sva;
4551 				continue;
4552 			}
4553 			/* may have to re-check later if pt_pv is NULL here */
4554 		}
4555 
4556 		/*
4557 		 * If pt_pv is NULL we either have an shared page table
4558 		 * page and must issue a callback specific to that case,
4559 		 * or there is no page table page.
4560 		 *
4561 		 * Either way we can skip the page table page.
4562 		 *
4563 		 * WARNING! pt_pv can also be NULL due to a pv creation
4564 		 *	    race where we find it to be NULL and then
4565 		 *	    later see a pte_pv.  But its possible the pt_pv
4566 		 *	    got created inbetween the two operations, so
4567 		 *	    we must check.
4568 		 */
4569 		if (pt_pv == NULL) {
4570 			/*
4571 			 * Possible unmanaged (shared from another pmap)
4572 			 * page table page.
4573 			 *
4574 			 * WARNING!  We must hold pt_placemark across the
4575 			 *	     *ptep test to prevent misintepreting
4576 			 *	     a non-zero *ptep as a shared page
4577 			 *	     table page.  Hold it across the function
4578 			 *	     callback as well for SMP safety.
4579 			 */
4580 			ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
4581 			if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
4582 				info->func(pmap, info, NULL, pt_placemark,
4583 					   pd_pv, 1,
4584 					   sva, ptep, info->arg);
4585 			} else {
4586 				pv_placemarker_wakeup(pmap, pt_placemark);
4587 			}
4588 
4589 			/*
4590 			 * Done, move to next page table page.
4591 			 */
4592 			va_next = (sva + NBPDR) & ~PDRMASK;
4593 			if (va_next < sva)
4594 				va_next = eva;
4595 			continue;
4596 		}
4597 
4598 		/*
4599 		 * From this point in the loop testing pt_pv for non-NULL
4600 		 * means we are in UVM, else if it is NULL we are in KVM.
4601 		 *
4602 		 * Limit our scan to either the end of the va represented
4603 		 * by the current page table page, or to the end of the
4604 		 * range being removed.
4605 		 */
4606 kernel_skip:
4607 		va_next = (sva + NBPDR) & ~PDRMASK;
4608 		if (va_next < sva)
4609 			va_next = eva;
4610 		if (va_next > eva)
4611 			va_next = eva;
4612 
4613 		/*
4614 		 * Scan the page table for pages.  Some pages may not be
4615 		 * managed (might not have a pv_entry).
4616 		 *
4617 		 * There is no page table management for kernel pages so
4618 		 * pt_pv will be NULL in that case, but otherwise pt_pv
4619 		 * is non-NULL, locked, and referenced.
4620 		 */
4621 
4622 		/*
4623 		 * At this point a non-NULL pt_pv means a UVA, and a NULL
4624 		 * pt_pv means a KVA.
4625 		 */
4626 		if (pt_pv)
4627 			ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
4628 		else
4629 			ptep = vtopte(sva);
4630 
4631 		while (sva < va_next) {
4632 			pv_entry_t pte_pv;
4633 			vm_pindex_t *pte_placemark;
4634 
4635 			/*
4636 			 * Yield every 64 pages, stop if requested.
4637 			 */
4638 			if ((++info->count & 63) == 0)
4639 				lwkt_user_yield();
4640 			if (info->stop)
4641 				break;
4642 
4643 			/*
4644 			 * We can shortcut our scan if *ptep == 0.  This is
4645 			 * an unlocked check.
4646 			 */
4647 			if (*ptep == 0) {
4648 				sva += PAGE_SIZE;
4649 				++ptep;
4650 				continue;
4651 			}
4652 			cpu_ccfence();
4653 
4654 			/*
4655 			 * Acquire the related pte_pv, if any.  If *ptep == 0
4656 			 * the related pte_pv should not exist, but if *ptep
4657 			 * is not zero the pte_pv may or may not exist (e.g.
4658 			 * will not exist for an unmanaged page).
4659 			 *
4660 			 * However a multitude of races are possible here
4661 			 * so if we cannot lock definite state we clean out
4662 			 * our cache and break the inner while() loop to
4663 			 * force a loop up to the top of the for().
4664 			 *
4665 			 * XXX unlock/relock pd_pv, pt_pv, and re-test their
4666 			 *     validity instead of looping up?
4667 			 */
4668 			pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
4669 					    &pte_placemark, &error);
4670 			if (error) {
4671 				pv_put(pd_pv);		/* lock order */
4672 				pd_pv = NULL;
4673 				if (pt_pv) {
4674 					pv_put(pt_pv);	/* lock order */
4675 					pt_pv = NULL;
4676 				}
4677 				if (pte_pv) {		/* block */
4678 					pv_lock(pte_pv);
4679 					pv_put(pte_pv);
4680 					pte_pv = NULL;
4681 				} else {
4682 					pv_placemarker_wait(pmap,
4683 							pte_placemark);
4684 				}
4685 				va_next = sva;		/* retry */
4686 				break;
4687 			}
4688 
4689 			/*
4690 			 * Reload *ptep after successfully locking the
4691 			 * pindex.  If *ptep == 0 we had better NOT have a
4692 			 * pte_pv.
4693 			 */
4694 			cpu_ccfence();
4695 			oldpte = *ptep;
4696 			if (oldpte == 0) {
4697 				if (pte_pv) {
4698 					kprintf("Unexpected non-NULL pte_pv "
4699 						"%p pt_pv %p "
4700 						"*ptep = %016lx/%016lx\n",
4701 						pte_pv, pt_pv, *ptep, oldpte);
4702 					panic("Unexpected non-NULL pte_pv");
4703 				} else {
4704 					pv_placemarker_wakeup(pmap, pte_placemark);
4705 				}
4706 				sva += PAGE_SIZE;
4707 				++ptep;
4708 				continue;
4709 			}
4710 
4711 			/*
4712 			 * We can't hold pd_pv across the callback (because
4713 			 * we don't pass it to the callback and the callback
4714 			 * might deadlock)
4715 			 */
4716 			if (pd_pv) {
4717 				vm_page_wire_quick(pd_pv->pv_m);
4718 				pv_unlock(pd_pv);
4719 			}
4720 
4721 			/*
4722 			 * Ready for the callback.  The locked pte_pv (if any)
4723 			 * is consumed by the callback.  pte_pv will exist if
4724 			 * the page is managed, and will not exist if it
4725 			 * isn't.
4726 			 */
4727 			if (oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
4728 				/*
4729 				 * Managed pte
4730 				 */
4731 				KASSERT(pte_pv &&
4732 					 (oldpte & pmap->pmap_bits[PG_V_IDX]),
4733 				    ("badC *ptep %016lx/%016lx sva %016lx "
4734 				    "pte_pv %p",
4735 				    *ptep, oldpte, sva, pte_pv));
4736 				/*
4737 				 * We must unlock pd_pv across the callback
4738 				 * to avoid deadlocks on any recursive
4739 				 * disposal.  Re-check that it still exists
4740 				 * after re-locking.
4741 				 *
4742 				 * Call target disposes of pte_pv and may
4743 				 * destroy but will not dispose of pt_pv.
4744 				 */
4745 				info->func(pmap, info, pte_pv, NULL,
4746 					   pt_pv, 0,
4747 					   sva, ptep, info->arg);
4748 			} else {
4749 				/*
4750 				 * Unmanaged pte
4751 				 *
4752 				 * We must unlock pd_pv across the callback
4753 				 * to avoid deadlocks on any recursive
4754 				 * disposal.  Re-check that it still exists
4755 				 * after re-locking.
4756 				 *
4757 				 * Call target disposes of pte_pv or
4758 				 * pte_placemark and may destroy but will
4759 				 * not dispose of pt_pv.
4760 				 */
4761 				KASSERT(pte_pv == NULL &&
4762 					(oldpte & pmap->pmap_bits[PG_V_IDX]),
4763 				    ("badD *ptep %016lx/%016lx sva %016lx "
4764 				    "pte_pv %p pte_pv->pv_m %p ",
4765 				     *ptep, oldpte, sva,
4766 				     pte_pv, (pte_pv ? pte_pv->pv_m : NULL)));
4767 				if (pte_pv)
4768 					kprintf("RaceD\n");
4769 				if (pte_pv) {
4770 					info->func(pmap, info,
4771 						   pte_pv, NULL,
4772 						   pt_pv, 0,
4773 						   sva, ptep, info->arg);
4774 				} else {
4775 					info->func(pmap, info,
4776 						   NULL, pte_placemark,
4777 						   pt_pv, 0,
4778 						   sva, ptep, info->arg);
4779 				}
4780 			}
4781 			if (pd_pv) {
4782 				pv_lock(pd_pv);
4783 				vm_page_unwire_quick(pd_pv->pv_m);
4784 				if (pd_pv->pv_pmap == NULL) {
4785 					va_next = sva;		/* retry */
4786 					break;
4787 				}
4788 			}
4789 
4790 			/*
4791 			 * NOTE: The cached pt_pv can be removed from the
4792 			 *	 pmap when pmap_dynamic_delete is enabled,
4793 			 *	 which will cause ptep to become stale.
4794 			 *
4795 			 *	 This also means that no pages remain under
4796 			 *	 the PT, so we can just break out of the inner
4797 			 *	 loop and let the outer loop clean everything
4798 			 *	 up.
4799 			 */
4800 			if (pt_pv && pt_pv->pv_pmap != pmap)
4801 				break;
4802 			pte_pv = NULL;
4803 			sva += PAGE_SIZE;
4804 			++ptep;
4805 		}
4806 	}
4807 	if (pd_pv) {
4808 		pv_put(pd_pv);
4809 		pd_pv = NULL;
4810 	}
4811 	if (pt_pv) {
4812 		pv_put(pt_pv);
4813 		pt_pv = NULL;
4814 	}
4815 	if ((++info->count & 7) == 0)
4816 		lwkt_user_yield();
4817 
4818 	/*
4819 	 * Relock before returning.
4820 	 */
4821 	spin_lock(&pmap->pm_spin);
4822 	return (0);
4823 }
4824 
4825 void
4826 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4827 {
4828 	struct pmap_scan_info info;
4829 
4830 	info.pmap = pmap;
4831 	info.sva = sva;
4832 	info.eva = eva;
4833 	info.func = pmap_remove_callback;
4834 	info.arg = NULL;
4835 	pmap_scan(&info, 1);
4836 #if 0
4837 	cpu_invltlb();
4838 	if (eva - sva < 1024*1024) {
4839 		while (sva < eva) {
4840 			cpu_invlpg((void *)sva);
4841 			sva += PAGE_SIZE;
4842 		}
4843 	}
4844 #endif
4845 }
4846 
4847 static void
4848 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
4849 {
4850 	struct pmap_scan_info info;
4851 
4852 	info.pmap = pmap;
4853 	info.sva = sva;
4854 	info.eva = eva;
4855 	info.func = pmap_remove_callback;
4856 	info.arg = NULL;
4857 	pmap_scan(&info, 0);
4858 }
4859 
4860 static void
4861 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
4862 		     pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
4863 		     pv_entry_t pt_pv, int sharept,
4864 		     vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
4865 {
4866 	pt_entry_t pte;
4867 
4868 	if (pte_pv) {
4869 		/*
4870 		 * Managed entry
4871 		 *
4872 		 * This will also drop pt_pv's wire_count. Note that
4873 		 * terminal pages are not wired based on mmu presence.
4874 		 *
4875 		 * NOTE: If this is the kernel_pmap, pt_pv can be NULL.
4876 		 */
4877 		KKASSERT(pte_pv->pv_m != NULL);
4878 		pmap_remove_pv_pte(pte_pv, pt_pv, info->bulk, 2);
4879 		pte_pv = NULL;	/* safety */
4880 
4881 		/*
4882 		 * Recursively destroy higher-level page tables.
4883 		 *
4884 		 * This is optional.  If we do not, they will still
4885 		 * be destroyed when the process exits.
4886 		 *
4887 		 * NOTE: Do not destroy pv_entry's with extra hold refs,
4888 		 *	 a caller may have unlocked it and intends to
4889 		 *	 continue to use it.
4890 		 */
4891 		if (pmap_dynamic_delete &&
4892 		    pt_pv &&
4893 		    pt_pv->pv_m &&
4894 		    pt_pv->pv_m->wire_count == 1 &&
4895 		    (pt_pv->pv_hold & PV_HOLD_MASK) == 2 &&
4896 		    pt_pv->pv_pindex < pmap_pml4_pindex()) {
4897 			if (pmap_dynamic_delete == 2)
4898 				kprintf("B %jd %08x\n", pt_pv->pv_pindex, pt_pv->pv_hold);
4899 			pv_hold(pt_pv);	/* extra hold */
4900 			pmap_remove_pv_pte(pt_pv, NULL, info->bulk, 1);
4901 			pv_lock(pt_pv);	/* prior extra hold + relock */
4902 		}
4903 	} else if (sharept == 0) {
4904 		/*
4905 		 * Unmanaged pte (pte_placemark is non-NULL)
4906 		 *
4907 		 * pt_pv's wire_count is still bumped by unmanaged pages
4908 		 * so we must decrement it manually.
4909 		 *
4910 		 * We have to unwire the target page table page.
4911 		 */
4912 		pte = pmap_inval_bulk(info->bulk, va, ptep, 0);
4913 		if (pte & pmap->pmap_bits[PG_W_IDX])
4914 			atomic_add_long(&pmap->pm_stats.wired_count, -1);
4915 		atomic_add_long(&pmap->pm_stats.resident_count, -1);
4916 		if (vm_page_unwire_quick(pt_pv->pv_m))
4917 			panic("pmap_remove: insufficient wirecount");
4918 		pv_placemarker_wakeup(pmap, pte_placemark);
4919 	} else {
4920 		/*
4921 		 * Unmanaged page table (pt, pd, or pdp. Not pte) for
4922 		 * a shared page table.
4923 		 *
4924 		 * pt_pv is actually the pd_pv for our pmap (not the shared
4925 		 * object pmap).
4926 		 *
4927 		 * We have to unwire the target page table page and we
4928 		 * have to unwire our page directory page.
4929 		 *
4930 		 * It is unclear how we can invalidate a segment so we
4931 		 * invalidate -1 which invlidates the tlb.
4932 		 */
4933 		pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
4934 		atomic_add_long(&pmap->pm_stats.resident_count, -1);
4935 		KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
4936 		if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
4937 			panic("pmap_remove: shared pgtable1 bad wirecount");
4938 		if (vm_page_unwire_quick(pt_pv->pv_m))
4939 			panic("pmap_remove: shared pgtable2 bad wirecount");
4940 		pv_placemarker_wakeup(pmap, pte_placemark);
4941 	}
4942 }
4943 
4944 /*
4945  * Removes this physical page from all physical maps in which it resides.
4946  * Reflects back modify bits to the pager.
4947  *
4948  * This routine may not be called from an interrupt.
4949  */
4950 static
4951 void
4952 pmap_remove_all(vm_page_t m)
4953 {
4954 	pv_entry_t pv;
4955 	pmap_inval_bulk_t bulk;
4956 
4957 	if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
4958 		return;
4959 
4960 	vm_page_spin_lock(m);
4961 	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4962 		KKASSERT(pv->pv_m == m);
4963 		if (pv_hold_try(pv)) {
4964 			vm_page_spin_unlock(m);
4965 		} else {
4966 			vm_page_spin_unlock(m);
4967 			pv_lock(pv);
4968 			pv_put(pv);
4969 			vm_page_spin_lock(m);
4970 			continue;
4971 		}
4972 		KKASSERT(pv->pv_pmap && pv->pv_m == m);
4973 
4974 		/*
4975 		 * Holding no spinlocks, pv is locked.  Once we scrap
4976 		 * pv we can no longer use it as a list iterator (but
4977 		 * we are doing a TAILQ_FIRST() so we are ok).
4978 		 */
4979 		pmap_inval_bulk_init(&bulk, pv->pv_pmap);
4980 		pmap_remove_pv_pte(pv, NULL, &bulk, 2);
4981 		pv = NULL;	/* safety */
4982 		pmap_inval_bulk_flush(&bulk);
4983 		vm_page_spin_lock(m);
4984 	}
4985 	KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
4986 	vm_page_spin_unlock(m);
4987 }
4988 
4989 /*
4990  * Removes the page from a particular pmap
4991  */
4992 void
4993 pmap_remove_specific(pmap_t pmap, vm_page_t m)
4994 {
4995 	pv_entry_t pv;
4996 	pmap_inval_bulk_t bulk;
4997 
4998 	if (!pmap_initialized)
4999 		return;
5000 
5001 again:
5002 	vm_page_spin_lock(m);
5003 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5004 		if (pv->pv_pmap != pmap)
5005 			continue;
5006 		KKASSERT(pv->pv_m == m);
5007 		if (pv_hold_try(pv)) {
5008 			vm_page_spin_unlock(m);
5009 		} else {
5010 			vm_page_spin_unlock(m);
5011 			pv_lock(pv);
5012 			pv_put(pv);
5013 			goto again;
5014 		}
5015 		KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
5016 
5017 		/*
5018 		 * Holding no spinlocks, pv is locked.  Once gone it can't
5019 		 * be used as an iterator.  In fact, because we couldn't
5020 		 * necessarily lock it atomically it may have moved within
5021 		 * the list and ALSO cannot be used as an iterator.
5022 		 */
5023 		pmap_inval_bulk_init(&bulk, pv->pv_pmap);
5024 		pmap_remove_pv_pte(pv, NULL, &bulk, 2);
5025 		pv = NULL;	/* safety */
5026 		pmap_inval_bulk_flush(&bulk);
5027 		goto again;
5028 	}
5029 	vm_page_spin_unlock(m);
5030 }
5031 
5032 /*
5033  * Set the physical protection on the specified range of this map
5034  * as requested.  This function is typically only used for debug watchpoints
5035  * and COW pages.
5036  *
5037  * This function may not be called from an interrupt if the map is
5038  * not the kernel_pmap.
5039  *
5040  * NOTE!  For shared page table pages we just unmap the page.
5041  */
5042 void
5043 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
5044 {
5045 	struct pmap_scan_info info;
5046 	/* JG review for NX */
5047 
5048 	if (pmap == NULL)
5049 		return;
5050 	if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == VM_PROT_NONE) {
5051 		pmap_remove(pmap, sva, eva);
5052 		return;
5053 	}
5054 	if (prot & VM_PROT_WRITE)
5055 		return;
5056 	info.pmap = pmap;
5057 	info.sva = sva;
5058 	info.eva = eva;
5059 	info.func = pmap_protect_callback;
5060 	info.arg = &prot;
5061 	pmap_scan(&info, 1);
5062 }
5063 
5064 static
5065 void
5066 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
5067 		      pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
5068 		      pv_entry_t pt_pv, int sharept,
5069 		      vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
5070 {
5071 	pt_entry_t pbits;
5072 	pt_entry_t cbits;
5073 	pt_entry_t pte;
5074 	vm_page_t m;
5075 
5076 again:
5077 	pbits = *ptep;
5078 	cbits = pbits;
5079 	if (pte_pv) {
5080 		KKASSERT(pte_pv->pv_m != NULL);
5081 		m = NULL;
5082 		if (pbits & pmap->pmap_bits[PG_A_IDX]) {
5083 			if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5084 				m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5085 				KKASSERT(m == pte_pv->pv_m);
5086 				vm_page_flag_set(m, PG_REFERENCED);
5087 			}
5088 			cbits &= ~pmap->pmap_bits[PG_A_IDX];
5089 		}
5090 		if (pbits & pmap->pmap_bits[PG_M_IDX]) {
5091 			if (pmap_track_modified(pte_pv->pv_pindex)) {
5092 				if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
5093 					if (m == NULL) {
5094 						m = PHYS_TO_VM_PAGE(pbits &
5095 								    PG_FRAME);
5096 					}
5097 					vm_page_dirty(m);
5098 				}
5099 				cbits &= ~pmap->pmap_bits[PG_M_IDX];
5100 			}
5101 		}
5102 	} else if (sharept) {
5103 		/*
5104 		 * Unmanaged page table, pt_pv is actually the pd_pv
5105 		 * for our pmap (not the object's shared pmap).
5106 		 *
5107 		 * When asked to protect something in a shared page table
5108 		 * page we just unmap the page table page.  We have to
5109 		 * invalidate the tlb in this situation.
5110 		 *
5111 		 * XXX Warning, shared page tables will not be used for
5112 		 * OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
5113 		 * so PHYS_TO_VM_PAGE() should be safe here.
5114 		 */
5115 		pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
5116 		if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
5117 			panic("pmap_protect: pgtable1 pg bad wirecount");
5118 		if (vm_page_unwire_quick(pt_pv->pv_m))
5119 			panic("pmap_protect: pgtable2 pg bad wirecount");
5120 		ptep = NULL;
5121 	}
5122 	/* else unmanaged page, adjust bits, no wire changes */
5123 
5124 	if (ptep) {
5125 		cbits &= ~pmap->pmap_bits[PG_RW_IDX];
5126 #ifdef PMAP_DEBUG2
5127 		if (pmap_enter_debug > 0) {
5128 			--pmap_enter_debug;
5129 			kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
5130 				"pt_pv=%p cbits=%08lx\n",
5131 				va, ptep, pte_pv,
5132 				pt_pv, cbits
5133 			);
5134 		}
5135 #endif
5136 		if (pbits != cbits) {
5137 			vm_offset_t xva;
5138 
5139 			xva = (sharept) ? (vm_offset_t)-1 : va;
5140 			if (!pmap_inval_smp_cmpset(pmap, xva,
5141 						   ptep, pbits, cbits)) {
5142 				goto again;
5143 			}
5144 		}
5145 	}
5146 	if (pte_pv)
5147 		pv_put(pte_pv);
5148 	else
5149 		pv_placemarker_wakeup(pmap, pte_placemark);
5150 }
5151 
5152 /*
5153  * Insert the vm_page (m) at the virtual address (va), replacing any prior
5154  * mapping at that address.  Set protection and wiring as requested.
5155  *
5156  * If entry is non-NULL we check to see if the SEG_SIZE optimization is
5157  * possible.  If it is we enter the page into the appropriate shared pmap
5158  * hanging off the related VM object instead of the passed pmap, then we
5159  * share the page table page from the VM object's pmap into the current pmap.
5160  *
5161  * NOTE: This routine MUST insert the page into the pmap now, it cannot
5162  *	 lazy-evaluate.
5163  *
5164  * NOTE: If (m) is PG_UNMANAGED it may also be a temporary fake vm_page_t.
5165  *	 never record it.
5166  */
5167 void
5168 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5169 	   boolean_t wired, vm_map_entry_t entry)
5170 {
5171 	pv_entry_t pt_pv;	/* page table */
5172 	pv_entry_t pte_pv;	/* page table entry */
5173 	vm_pindex_t *pte_placemark;
5174 	pt_entry_t *ptep;
5175 	vm_paddr_t opa;
5176 	pt_entry_t origpte, newpte;
5177 	vm_paddr_t pa;
5178 
5179 	if (pmap == NULL)
5180 		return;
5181 	va = trunc_page(va);
5182 #ifdef PMAP_DIAGNOSTIC
5183 	if (va >= KvaEnd)
5184 		panic("pmap_enter: toobig");
5185 	if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
5186 		panic("pmap_enter: invalid to pmap_enter page table "
5187 		      "pages (va: 0x%lx)", va);
5188 #endif
5189 	if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
5190 		kprintf("Warning: pmap_enter called on UVA with "
5191 			"kernel_pmap\n");
5192 #ifdef DDB
5193 		db_print_backtrace();
5194 #endif
5195 	}
5196 	if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
5197 		kprintf("Warning: pmap_enter called on KVA without"
5198 			"kernel_pmap\n");
5199 #ifdef DDB
5200 		db_print_backtrace();
5201 #endif
5202 	}
5203 
5204 	/*
5205 	 * Get locked PV entries for our new page table entry (pte_pv or
5206 	 * pte_placemark) and for its parent page table (pt_pv).  We need
5207 	 * the parent so we can resolve the location of the ptep.
5208 	 *
5209 	 * Only hardware MMU actions can modify the ptep out from
5210 	 * under us.
5211 	 *
5212 	 * if (m) is fictitious or unmanaged we do not create a managing
5213 	 * pte_pv for it.  Any pre-existing page's management state must
5214 	 * match (avoiding code complexity).
5215 	 *
5216 	 * If the pmap is still being initialized we assume existing
5217 	 * page tables.
5218 	 *
5219 	 * Kernel mapppings do not track page table pages (i.e. pt_pv).
5220 	 *
5221 	 * WARNING! If replacing a managed mapping with an unmanaged mapping
5222 	 *	    pte_pv will wind up being non-NULL and must be handled
5223 	 *	    below.
5224 	 */
5225 	if (pmap_initialized == FALSE) {
5226 		pte_pv = NULL;
5227 		pt_pv = NULL;
5228 		pte_placemark = NULL;
5229 		ptep = vtopte(va);
5230 		origpte = *ptep;
5231 	} else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
5232 		pmap_softwait(pmap);
5233 		pte_pv = pv_get(pmap, pmap_pte_pindex(va), &pte_placemark);
5234 		KKASSERT(pte_pv == NULL);
5235 		if (va >= VM_MAX_USER_ADDRESS) {
5236 			pt_pv = NULL;
5237 			ptep = vtopte(va);
5238 		} else {
5239 			pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
5240 						  NULL, entry, va);
5241 			ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5242 		}
5243 		origpte = *ptep;
5244 		cpu_ccfence();
5245 		KASSERT(origpte == 0 ||
5246 			 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0,
5247 			 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5248 	} else {
5249 		pmap_softwait(pmap);
5250 		if (va >= VM_MAX_USER_ADDRESS) {
5251 			/*
5252 			 * Kernel map, pv_entry-tracked.
5253 			 */
5254 			pt_pv = NULL;
5255 			pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
5256 			ptep = vtopte(va);
5257 		} else {
5258 			/*
5259 			 * User map
5260 			 */
5261 			pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
5262 						   &pt_pv, entry, va);
5263 			ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5264 		}
5265 		pte_placemark = NULL;	/* safety */
5266 		origpte = *ptep;
5267 		cpu_ccfence();
5268 		KASSERT(origpte == 0 ||
5269 			 (origpte & pmap->pmap_bits[PG_MANAGED_IDX]),
5270 			 ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
5271 	}
5272 
5273 	pa = VM_PAGE_TO_PHYS(m);
5274 	opa = origpte & PG_FRAME;
5275 
5276 	/*
5277 	 * Calculate the new PTE.  Note that pte_pv alone does not mean
5278 	 * the new pte_pv is managed, it could exist because the old pte
5279 	 * was managed even if the new one is not.
5280 	 */
5281 	newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
5282 		 pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
5283 	if (wired)
5284 		newpte |= pmap->pmap_bits[PG_W_IDX];
5285 	if (va < VM_MAX_USER_ADDRESS)
5286 		newpte |= pmap->pmap_bits[PG_U_IDX];
5287 	if (pte_pv && (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) == 0)
5288 		newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
5289 //	if (pmap == &kernel_pmap)
5290 //		newpte |= pgeflag;
5291 	newpte |= pmap->pmap_cache_bits[m->pat_mode];
5292 	if (m->flags & PG_FICTITIOUS)
5293 		newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
5294 
5295 	/*
5296 	 * It is possible for multiple faults to occur in threaded
5297 	 * environments, the existing pte might be correct.
5298 	 */
5299 	if (((origpte ^ newpte) &
5300 	    ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
5301 			  pmap->pmap_bits[PG_A_IDX])) == 0) {
5302 		goto done;
5303 	}
5304 
5305 	/*
5306 	 * Ok, either the address changed or the protection or wiring
5307 	 * changed.
5308 	 *
5309 	 * Clear the current entry, interlocking the removal.  For managed
5310 	 * pte's this will also flush the modified state to the vm_page.
5311 	 * Atomic ops are mandatory in order to ensure that PG_M events are
5312 	 * not lost during any transition.
5313 	 *
5314 	 * WARNING: The caller has busied the new page but not the original
5315 	 *	    vm_page which we are trying to replace.  Because we hold
5316 	 *	    the pte_pv lock, but have not busied the page, PG bits
5317 	 *	    can be cleared out from under us.
5318 	 */
5319 	if (opa) {
5320 		if (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) {
5321 			/*
5322 			 * Old page was managed.  Expect pte_pv to exist.
5323 			 * (it might also exist if the old page was unmanaged).
5324 			 *
5325 			 * NOTE: pt_pv won't exist for a kernel page
5326 			 *	 (managed or otherwise).
5327 			 *
5328 			 * NOTE: We may be reusing the pte_pv so we do not
5329 			 *	 destroy it in pmap_remove_pv_pte().
5330 			 */
5331 			KKASSERT(pte_pv && pte_pv->pv_m);
5332 			if (prot & VM_PROT_NOSYNC) {
5333 				pmap_remove_pv_pte(pte_pv, pt_pv, NULL, 0);
5334 			} else {
5335 				pmap_inval_bulk_t bulk;
5336 
5337 				pmap_inval_bulk_init(&bulk, pmap);
5338 				pmap_remove_pv_pte(pte_pv, pt_pv, &bulk, 0);
5339 				pmap_inval_bulk_flush(&bulk);
5340 			}
5341 			pmap_remove_pv_page(pte_pv);
5342 			/* will either set pte_pv->pv_m or pv_free() later */
5343 		} else {
5344 			/*
5345 			 * Old page was not managed.  If we have a pte_pv
5346 			 * it better not have a pv_m assigned to it.  If the
5347 			 * new page is managed the pte_pv will be destroyed
5348 			 * near the end (we need its interlock).
5349 			 *
5350 			 * NOTE: We leave the wire count on the PT page
5351 			 *	 intact for the followup enter, but adjust
5352 			 *	 the wired-pages count on the pmap.
5353 			 */
5354 			KKASSERT(pte_pv == NULL);
5355 			if (prot & VM_PROT_NOSYNC) {
5356 				/*
5357 				 * NOSYNC (no mmu sync) requested.
5358 				 */
5359 				(void)pte_load_clear(ptep);
5360 				cpu_invlpg((void *)va);
5361 			} else {
5362 				/*
5363 				 * Nominal SYNC
5364 				 */
5365 				pmap_inval_smp(pmap, va, 1, ptep, 0);
5366 			}
5367 
5368 			/*
5369 			 * We must adjust pm_stats manually for unmanaged
5370 			 * pages.
5371 			 */
5372 			if (pt_pv) {
5373 				atomic_add_long(&pmap->pm_stats.
5374 						resident_count, -1);
5375 			}
5376 			if (origpte & pmap->pmap_bits[PG_W_IDX]) {
5377 				atomic_add_long(&pmap->pm_stats.
5378 						wired_count, -1);
5379 			}
5380 		}
5381 		KKASSERT(*ptep == 0);
5382 	}
5383 
5384 #ifdef PMAP_DEBUG2
5385 	if (pmap_enter_debug > 0) {
5386 		--pmap_enter_debug;
5387 		kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
5388 			" pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
5389 			va, m,
5390 			origpte, newpte, ptep,
5391 			pte_pv, pt_pv, opa, prot);
5392 	}
5393 #endif
5394 
5395 	if ((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5396 		/*
5397 		 * Entering an unmanaged page.  We must wire the pt_pv unless
5398 		 * we retained the wiring from an unmanaged page we had
5399 		 * removed (if we retained it via pte_pv that will go away
5400 		 * soon).
5401 		 */
5402 		if (pt_pv && (opa == 0 ||
5403 			      (origpte & pmap->pmap_bits[PG_MANAGED_IDX]))) {
5404 			vm_page_wire_quick(pt_pv->pv_m);
5405 		}
5406 		if (wired)
5407 			atomic_add_long(&pmap->pm_stats.wired_count, 1);
5408 
5409 		/*
5410 		 * Unmanaged pages need manual resident_count tracking.
5411 		 */
5412 		if (pt_pv) {
5413 			atomic_add_long(&pt_pv->pv_pmap->pm_stats.
5414 					resident_count, 1);
5415 		}
5416 		if (newpte & pmap->pmap_bits[PG_RW_IDX])
5417 			vm_page_flag_set(m, PG_WRITEABLE);
5418 	} else {
5419 		/*
5420 		 * Entering a managed page.  Our pte_pv takes care of the
5421 		 * PT wiring, so if we had removed an unmanaged page before
5422 		 * we must adjust.
5423 		 *
5424 		 * We have to take care of the pmap wired count ourselves.
5425 		 *
5426 		 * Enter on the PV list if part of our managed memory.
5427 		 */
5428 		KKASSERT(pte_pv && (pte_pv->pv_m == NULL || pte_pv->pv_m == m));
5429 		vm_page_spin_lock(m);
5430 		pte_pv->pv_m = m;
5431 		pmap_page_stats_adding(m);
5432 		TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
5433 		vm_page_flag_set(m, PG_MAPPED);
5434 		if (newpte & pmap->pmap_bits[PG_RW_IDX])
5435 			vm_page_flag_set(m, PG_WRITEABLE);
5436 		vm_page_spin_unlock(m);
5437 
5438 		if (pt_pv && opa &&
5439 		    (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5440 			vm_page_unwire_quick(pt_pv->pv_m);
5441 		}
5442 
5443 		/*
5444 		 * Adjust pmap wired pages count for new entry.
5445 		 */
5446 		if (wired) {
5447 			atomic_add_long(&pte_pv->pv_pmap->pm_stats.
5448 					wired_count, 1);
5449 		}
5450 	}
5451 
5452 	/*
5453 	 * Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
5454 	 *
5455 	 * User VMAs do not because those will be zero->non-zero, so no
5456 	 * stale entries to worry about at this point.
5457 	 *
5458 	 * For KVM there appear to still be issues.  Theoretically we
5459 	 * should be able to scrap the interlocks entirely but we
5460 	 * get crashes.
5461 	 */
5462 	if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL) {
5463 		pmap_inval_smp(pmap, va, 1, ptep, newpte);
5464 	} else {
5465 		origpte = atomic_swap_long(ptep, newpte);
5466 		if (origpte & pmap->pmap_bits[PG_M_IDX]) {
5467 			kprintf("pmap [M] race @ %016jx\n", va);
5468 			atomic_set_long(ptep, pmap->pmap_bits[PG_M_IDX]);
5469 		}
5470 		if (pt_pv == NULL)
5471 			cpu_invlpg((void *)va);
5472 	}
5473 
5474 	/*
5475 	 * Cleanup
5476 	 */
5477 done:
5478 	KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
5479 		 (m->flags & PG_MAPPED));
5480 
5481 	/*
5482 	 * Cleanup the pv entry, allowing other accessors.  If the new page
5483 	 * is not managed but we have a pte_pv (which was locking our
5484 	 * operation), we can free it now.  pte_pv->pv_m should be NULL.
5485 	 */
5486 	if (pte_pv && (newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0) {
5487 		pv_free(pte_pv, pt_pv);
5488 	} else if (pte_pv) {
5489 		pv_put(pte_pv);
5490 	} else if (pte_placemark) {
5491 		pv_placemarker_wakeup(pmap, pte_placemark);
5492 	}
5493 	if (pt_pv)
5494 		pv_put(pt_pv);
5495 }
5496 
5497 /*
5498  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
5499  * This code also assumes that the pmap has no pre-existing entry for this
5500  * VA.
5501  *
5502  * This code currently may only be used on user pmaps, not kernel_pmap.
5503  */
5504 void
5505 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
5506 {
5507 	pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
5508 }
5509 
5510 /*
5511  * Make a temporary mapping for a physical address.  This is only intended
5512  * to be used for panic dumps.
5513  *
5514  * The caller is responsible for calling smp_invltlb().
5515  */
5516 void *
5517 pmap_kenter_temporary(vm_paddr_t pa, long i)
5518 {
5519 	pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
5520 	return ((void *)crashdumpmap);
5521 }
5522 
5523 #define MAX_INIT_PT (96)
5524 
5525 /*
5526  * This routine preloads the ptes for a given object into the specified pmap.
5527  * This eliminates the blast of soft faults on process startup and
5528  * immediately after an mmap.
5529  */
5530 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
5531 
5532 void
5533 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
5534 		    vm_object_t object, vm_pindex_t pindex,
5535 		    vm_size_t size, int limit)
5536 {
5537 	struct rb_vm_page_scan_info info;
5538 	struct lwp *lp;
5539 	vm_size_t psize;
5540 
5541 	/*
5542 	 * We can't preinit if read access isn't set or there is no pmap
5543 	 * or object.
5544 	 */
5545 	if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
5546 		return;
5547 
5548 	/*
5549 	 * We can't preinit if the pmap is not the current pmap
5550 	 */
5551 	lp = curthread->td_lwp;
5552 	if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
5553 		return;
5554 
5555 	/*
5556 	 * Misc additional checks
5557 	 */
5558 	psize = x86_64_btop(size);
5559 
5560 	if ((object->type != OBJT_VNODE) ||
5561 		((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
5562 			(object->resident_page_count > MAX_INIT_PT))) {
5563 		return;
5564 	}
5565 
5566 	if (pindex + psize > object->size) {
5567 		if (object->size < pindex)
5568 			return;
5569 		psize = object->size - pindex;
5570 	}
5571 
5572 	if (psize == 0)
5573 		return;
5574 
5575 	/*
5576 	 * If everything is segment-aligned do not pre-init here.  Instead
5577 	 * allow the normal vm_fault path to pass a segment hint to
5578 	 * pmap_enter() which will then use an object-referenced shared
5579 	 * page table page.
5580 	 */
5581 	if ((addr & SEG_MASK) == 0 &&
5582 	    (ctob(psize) & SEG_MASK) == 0 &&
5583 	    (ctob(pindex) & SEG_MASK) == 0) {
5584 		return;
5585 	}
5586 
5587 	/*
5588 	 * Use a red-black scan to traverse the requested range and load
5589 	 * any valid pages found into the pmap.
5590 	 *
5591 	 * We cannot safely scan the object's memq without holding the
5592 	 * object token.
5593 	 */
5594 	info.start_pindex = pindex;
5595 	info.end_pindex = pindex + psize - 1;
5596 	info.limit = limit;
5597 	info.mpte = NULL;
5598 	info.addr = addr;
5599 	info.pmap = pmap;
5600 	info.object = object;
5601 
5602 	/*
5603 	 * By using the NOLK scan, the callback function must be sure
5604 	 * to return -1 if the VM page falls out of the object.
5605 	 */
5606 	vm_object_hold_shared(object);
5607 	vm_page_rb_tree_RB_SCAN_NOLK(&object->rb_memq, rb_vm_page_scancmp,
5608 				     pmap_object_init_pt_callback, &info);
5609 	vm_object_drop(object);
5610 }
5611 
5612 static
5613 int
5614 pmap_object_init_pt_callback(vm_page_t p, void *data)
5615 {
5616 	struct rb_vm_page_scan_info *info = data;
5617 	vm_pindex_t rel_index;
5618 	int hard_busy;
5619 
5620 	/*
5621 	 * don't allow an madvise to blow away our really
5622 	 * free pages allocating pv entries.
5623 	 */
5624 	if ((info->limit & MAP_PREFAULT_MADVISE) &&
5625 		vmstats.v_free_count < vmstats.v_free_reserved) {
5626 		    return(-1);
5627 	}
5628 
5629 	/*
5630 	 * Ignore list markers and ignore pages we cannot instantly
5631 	 * busy (while holding the object token).
5632 	 */
5633 	if (p->flags & PG_MARKER)
5634 		return 0;
5635 	hard_busy = 0;
5636 again:
5637 	if (hard_busy) {
5638 		if (vm_page_busy_try(p, TRUE))
5639 			return 0;
5640 	} else {
5641 		if (vm_page_sbusy_try(p))
5642 			return 0;
5643 	}
5644 	if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
5645 	    (p->flags & PG_FICTITIOUS) == 0) {
5646 		if ((p->queue - p->pc) == PQ_CACHE) {
5647 			if (hard_busy == 0) {
5648 				vm_page_sbusy_drop(p);
5649 				hard_busy = 1;
5650 				goto again;
5651 			}
5652 			vm_page_deactivate(p);
5653 		}
5654 		rel_index = p->pindex - info->start_pindex;
5655 		pmap_enter_quick(info->pmap,
5656 				 info->addr + x86_64_ptob(rel_index), p);
5657 	}
5658 	if (hard_busy)
5659 		vm_page_wakeup(p);
5660 	else
5661 		vm_page_sbusy_drop(p);
5662 
5663 	/*
5664 	 * We are using an unlocked scan (that is, the scan expects its
5665 	 * current element to remain in the tree on return).  So we have
5666 	 * to check here and abort the scan if it isn't.
5667 	 */
5668 	if (p->object != info->object)
5669 		return -1;
5670 	lwkt_yield();
5671 	return(0);
5672 }
5673 
5674 /*
5675  * Return TRUE if the pmap is in shape to trivially pre-fault the specified
5676  * address.
5677  *
5678  * Returns FALSE if it would be non-trivial or if a pte is already loaded
5679  * into the slot.
5680  *
5681  * XXX This is safe only because page table pages are not freed.
5682  */
5683 int
5684 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
5685 {
5686 	pt_entry_t *pte;
5687 
5688 	/*spin_lock(&pmap->pm_spin);*/
5689 	if ((pte = pmap_pte(pmap, addr)) != NULL) {
5690 		if (*pte & pmap->pmap_bits[PG_V_IDX]) {
5691 			/*spin_unlock(&pmap->pm_spin);*/
5692 			return FALSE;
5693 		}
5694 	}
5695 	/*spin_unlock(&pmap->pm_spin);*/
5696 	return TRUE;
5697 }
5698 
5699 /*
5700  * Change the wiring attribute for a pmap/va pair.  The mapping must already
5701  * exist in the pmap.  The mapping may or may not be managed.  The wiring in
5702  * the page is not changed, the page is returned so the caller can adjust
5703  * its wiring (the page is not locked in any way).
5704  *
5705  * Wiring is not a hardware characteristic so there is no need to invalidate
5706  * TLB.  However, in an SMP environment we must use a locked bus cycle to
5707  * update the pte (if we are not using the pmap_inval_*() API that is)...
5708  * it's ok to do this for simple wiring changes.
5709  */
5710 vm_page_t
5711 pmap_unwire(pmap_t pmap, vm_offset_t va)
5712 {
5713 	pt_entry_t *ptep;
5714 	pv_entry_t pt_pv;
5715 	vm_paddr_t pa;
5716 	vm_page_t m;
5717 
5718 	if (pmap == NULL)
5719 		return NULL;
5720 
5721 	/*
5722 	 * Assume elements in the kernel pmap are stable
5723 	 */
5724 	if (pmap == &kernel_pmap) {
5725 		if (pmap_pt(pmap, va) == 0)
5726 			return NULL;
5727 		ptep = pmap_pte_quick(pmap, va);
5728 		if (pmap_pte_v(pmap, ptep)) {
5729 			if (pmap_pte_w(pmap, ptep))
5730 				atomic_add_long(&pmap->pm_stats.wired_count,-1);
5731 			atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5732 			pa = *ptep & PG_FRAME;
5733 			m = PHYS_TO_VM_PAGE(pa);
5734 		} else {
5735 			m = NULL;
5736 		}
5737 	} else {
5738 		/*
5739 		 * We can only [un]wire pmap-local pages (we cannot wire
5740 		 * shared pages)
5741 		 */
5742 		pt_pv = pv_get(pmap, pmap_pt_pindex(va), NULL);
5743 		if (pt_pv == NULL)
5744 			return NULL;
5745 
5746 		ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
5747 		if ((*ptep & pmap->pmap_bits[PG_V_IDX]) == 0) {
5748 			pv_put(pt_pv);
5749 			return NULL;
5750 		}
5751 
5752 		if (pmap_pte_w(pmap, ptep)) {
5753 			atomic_add_long(&pt_pv->pv_pmap->pm_stats.wired_count,
5754 					-1);
5755 		}
5756 		/* XXX else return NULL so caller doesn't unwire m ? */
5757 
5758 		atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
5759 
5760 		pa = *ptep & PG_FRAME;
5761 		m = PHYS_TO_VM_PAGE(pa);	/* held by wired count */
5762 		pv_put(pt_pv);
5763 	}
5764 	return m;
5765 }
5766 
5767 /*
5768  * Copy the range specified by src_addr/len from the source map to
5769  * the range dst_addr/len in the destination map.
5770  *
5771  * This routine is only advisory and need not do anything.
5772  */
5773 void
5774 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
5775 	  vm_size_t len, vm_offset_t src_addr)
5776 {
5777 }
5778 
5779 /*
5780  * pmap_zero_page:
5781  *
5782  *	Zero the specified physical page.
5783  *
5784  *	This function may be called from an interrupt and no locking is
5785  *	required.
5786  */
5787 void
5788 pmap_zero_page(vm_paddr_t phys)
5789 {
5790 	vm_offset_t va = PHYS_TO_DMAP(phys);
5791 
5792 	pagezero((void *)va);
5793 }
5794 
5795 /*
5796  * pmap_zero_page:
5797  *
5798  *	Zero part of a physical page by mapping it into memory and clearing
5799  *	its contents with bzero.
5800  *
5801  *	off and size may not cover an area beyond a single hardware page.
5802  */
5803 void
5804 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
5805 {
5806 	vm_offset_t virt = PHYS_TO_DMAP(phys);
5807 
5808 	bzero((char *)virt + off, size);
5809 }
5810 
5811 /*
5812  * pmap_copy_page:
5813  *
5814  *	Copy the physical page from the source PA to the target PA.
5815  *	This function may be called from an interrupt.  No locking
5816  *	is required.
5817  */
5818 void
5819 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
5820 {
5821 	vm_offset_t src_virt, dst_virt;
5822 
5823 	src_virt = PHYS_TO_DMAP(src);
5824 	dst_virt = PHYS_TO_DMAP(dst);
5825 	bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
5826 }
5827 
5828 /*
5829  * pmap_copy_page_frag:
5830  *
5831  *	Copy the physical page from the source PA to the target PA.
5832  *	This function may be called from an interrupt.  No locking
5833  *	is required.
5834  */
5835 void
5836 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
5837 {
5838 	vm_offset_t src_virt, dst_virt;
5839 
5840 	src_virt = PHYS_TO_DMAP(src);
5841 	dst_virt = PHYS_TO_DMAP(dst);
5842 
5843 	bcopy((char *)src_virt + (src & PAGE_MASK),
5844 	      (char *)dst_virt + (dst & PAGE_MASK),
5845 	      bytes);
5846 }
5847 
5848 /*
5849  * Returns true if the pmap's pv is one of the first 16 pvs linked to from
5850  * this page.  This count may be changed upwards or downwards in the future;
5851  * it is only necessary that true be returned for a small subset of pmaps
5852  * for proper page aging.
5853  */
5854 boolean_t
5855 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5856 {
5857 	pv_entry_t pv;
5858 	int loops = 0;
5859 
5860 	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5861 		return FALSE;
5862 
5863 	vm_page_spin_lock(m);
5864 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5865 		if (pv->pv_pmap == pmap) {
5866 			vm_page_spin_unlock(m);
5867 			return TRUE;
5868 		}
5869 		loops++;
5870 		if (loops >= 16)
5871 			break;
5872 	}
5873 	vm_page_spin_unlock(m);
5874 	return (FALSE);
5875 }
5876 
5877 /*
5878  * Remove all pages from specified address space this aids process exit
5879  * speeds.  Also, this code may be special cased for the current process
5880  * only.
5881  */
5882 void
5883 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5884 {
5885 	pmap_remove_noinval(pmap, sva, eva);
5886 	cpu_invltlb();
5887 }
5888 
5889 /*
5890  * pmap_testbit tests bits in pte's note that the testbit/clearbit
5891  * routines are inline, and a lot of things compile-time evaluate.
5892  */
5893 
5894 static
5895 boolean_t
5896 pmap_testbit(vm_page_t m, int bit)
5897 {
5898 	pv_entry_t pv;
5899 	pt_entry_t *pte;
5900 	pmap_t pmap;
5901 
5902 	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
5903 		return FALSE;
5904 
5905 	if (TAILQ_FIRST(&m->md.pv_list) == NULL)
5906 		return FALSE;
5907 	vm_page_spin_lock(m);
5908 	if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
5909 		vm_page_spin_unlock(m);
5910 		return FALSE;
5911 	}
5912 
5913 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5914 #if defined(PMAP_DIAGNOSTIC)
5915 		if (pv->pv_pmap == NULL) {
5916 			kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
5917 			    pv->pv_pindex);
5918 			continue;
5919 		}
5920 #endif
5921 		pmap = pv->pv_pmap;
5922 
5923 		/*
5924 		 * If the bit being tested is the modified bit, then
5925 		 * mark clean_map and ptes as never
5926 		 * modified.
5927 		 *
5928 		 * WARNING!  Because we do not lock the pv, *pte can be in a
5929 		 *	     state of flux.  Despite this the value of *pte
5930 		 *	     will still be related to the vm_page in some way
5931 		 *	     because the pv cannot be destroyed as long as we
5932 		 *	     hold the vm_page spin lock.
5933 		 */
5934 		if (bit == PG_A_IDX || bit == PG_M_IDX) {
5935 				//& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
5936 			if (!pmap_track_modified(pv->pv_pindex))
5937 				continue;
5938 		}
5939 
5940 		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
5941 		if (*pte & pmap->pmap_bits[bit]) {
5942 			vm_page_spin_unlock(m);
5943 			return TRUE;
5944 		}
5945 	}
5946 	vm_page_spin_unlock(m);
5947 	return (FALSE);
5948 }
5949 
5950 /*
5951  * This routine is used to modify bits in ptes.  Only one bit should be
5952  * specified.  PG_RW requires special handling.
5953  *
5954  * Caller must NOT hold any spin locks
5955  */
5956 static __inline
5957 void
5958 pmap_clearbit(vm_page_t m, int bit_index)
5959 {
5960 	pv_entry_t pv;
5961 	pt_entry_t *pte;
5962 	pt_entry_t pbits;
5963 	pmap_t pmap;
5964 
5965 	if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
5966 		if (bit_index == PG_RW_IDX)
5967 			vm_page_flag_clear(m, PG_WRITEABLE);
5968 		return;
5969 	}
5970 
5971 	/*
5972 	 * PG_M or PG_A case
5973 	 *
5974 	 * Loop over all current mappings setting/clearing as appropos If
5975 	 * setting RO do we need to clear the VAC?
5976 	 *
5977 	 * NOTE: When clearing PG_M we could also (not implemented) drop
5978 	 *	 through to the PG_RW code and clear PG_RW too, forcing
5979 	 *	 a fault on write to redetect PG_M for virtual kernels, but
5980 	 *	 it isn't necessary since virtual kernels invalidate the
5981 	 *	 pte when they clear the VPTE_M bit in their virtual page
5982 	 *	 tables.
5983 	 *
5984 	 * NOTE: Does not re-dirty the page when clearing only PG_M.
5985 	 *
5986 	 * NOTE: Because we do not lock the pv, *pte can be in a state of
5987 	 *	 flux.  Despite this the value of *pte is still somewhat
5988 	 *	 related while we hold the vm_page spin lock.
5989 	 *
5990 	 *	 *pte can be zero due to this race.  Since we are clearing
5991 	 *	 bits we basically do no harm when this race occurs.
5992 	 */
5993 	if (bit_index != PG_RW_IDX) {
5994 		vm_page_spin_lock(m);
5995 		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
5996 #if defined(PMAP_DIAGNOSTIC)
5997 			if (pv->pv_pmap == NULL) {
5998 				kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
5999 				    pv->pv_pindex);
6000 				continue;
6001 			}
6002 #endif
6003 			pmap = pv->pv_pmap;
6004 			pte = pmap_pte_quick(pv->pv_pmap,
6005 					     pv->pv_pindex << PAGE_SHIFT);
6006 			pbits = *pte;
6007 			if (pbits & pmap->pmap_bits[bit_index])
6008 				atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
6009 		}
6010 		vm_page_spin_unlock(m);
6011 		return;
6012 	}
6013 
6014 	/*
6015 	 * Clear PG_RW.  Also clears PG_M and marks the page dirty if PG_M
6016 	 * was set.
6017 	 */
6018 restart:
6019 	vm_page_spin_lock(m);
6020 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6021 		/*
6022 		 * don't write protect pager mappings
6023 		 */
6024 		if (!pmap_track_modified(pv->pv_pindex))
6025 			continue;
6026 
6027 #if defined(PMAP_DIAGNOSTIC)
6028 		if (pv->pv_pmap == NULL) {
6029 			kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
6030 				pv->pv_pindex);
6031 			continue;
6032 		}
6033 #endif
6034 		pmap = pv->pv_pmap;
6035 
6036 		/*
6037 		 * Skip pages which do not have PG_RW set.
6038 		 */
6039 		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6040 		if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
6041 			continue;
6042 
6043 		/*
6044 		 * We must lock the PV to be able to safely test the pte.
6045 		 */
6046 		if (pv_hold_try(pv)) {
6047 			vm_page_spin_unlock(m);
6048 		} else {
6049 			vm_page_spin_unlock(m);
6050 			pv_lock(pv);	/* held, now do a blocking lock */
6051 			pv_put(pv);
6052 			goto restart;
6053 		}
6054 
6055 		/*
6056 		 * Reload pte after acquiring pv.
6057 		 */
6058 		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6059 #if 0
6060 		if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0) {
6061 			pv_put(pv);
6062 			goto restart;
6063 		}
6064 #endif
6065 
6066 		KKASSERT(pv->pv_pmap == pmap && pv->pv_m == m);
6067 		for (;;) {
6068 			pt_entry_t nbits;
6069 
6070 			pbits = *pte;
6071 			cpu_ccfence();
6072 			nbits = pbits & ~(pmap->pmap_bits[PG_RW_IDX] |
6073 					  pmap->pmap_bits[PG_M_IDX]);
6074 			if (pmap_inval_smp_cmpset(pmap,
6075 				     ((vm_offset_t)pv->pv_pindex << PAGE_SHIFT),
6076 				     pte, pbits, nbits)) {
6077 				break;
6078 			}
6079 			cpu_pause();
6080 		}
6081 
6082 		/*
6083 		 * If PG_M was found to be set while we were clearing PG_RW
6084 		 * we also clear PG_M (done above) and mark the page dirty.
6085 		 * Callers expect this behavior.
6086 		 *
6087 		 * we lost pv so it cannot be used as an iterator.  In fact,
6088 		 * because we couldn't necessarily lock it atomically it may
6089 		 * have moved within the list and ALSO cannot be used as an
6090 		 * iterator.
6091 		 */
6092 		vm_page_spin_lock(m);
6093 		if (pbits & pmap->pmap_bits[PG_M_IDX])
6094 			vm_page_dirty(m);
6095 		vm_page_spin_unlock(m);
6096 		pv_put(pv);
6097 		goto restart;
6098 	}
6099 	if (bit_index == PG_RW_IDX)
6100 		vm_page_flag_clear(m, PG_WRITEABLE);
6101 	vm_page_spin_unlock(m);
6102 }
6103 
6104 /*
6105  * Lower the permission for all mappings to a given page.
6106  *
6107  * Page must be busied by caller.  Because page is busied by caller this
6108  * should not be able to race a pmap_enter().
6109  */
6110 void
6111 pmap_page_protect(vm_page_t m, vm_prot_t prot)
6112 {
6113 	/* JG NX support? */
6114 	if ((prot & VM_PROT_WRITE) == 0) {
6115 		if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
6116 			/*
6117 			 * NOTE: pmap_clearbit(.. PG_RW) also clears
6118 			 *	 the PG_WRITEABLE flag in (m).
6119 			 */
6120 			pmap_clearbit(m, PG_RW_IDX);
6121 		} else {
6122 			pmap_remove_all(m);
6123 		}
6124 	}
6125 }
6126 
6127 vm_paddr_t
6128 pmap_phys_address(vm_pindex_t ppn)
6129 {
6130 	return (x86_64_ptob(ppn));
6131 }
6132 
6133 /*
6134  * Return a count of reference bits for a page, clearing those bits.
6135  * It is not necessary for every reference bit to be cleared, but it
6136  * is necessary that 0 only be returned when there are truly no
6137  * reference bits set.
6138  *
6139  * XXX: The exact number of bits to check and clear is a matter that
6140  * should be tested and standardized at some point in the future for
6141  * optimal aging of shared pages.
6142  *
6143  * This routine may not block.
6144  */
6145 int
6146 pmap_ts_referenced(vm_page_t m)
6147 {
6148 	pv_entry_t pv;
6149 	pt_entry_t *pte;
6150 	pmap_t pmap;
6151 	int rtval = 0;
6152 
6153 	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
6154 		return (rtval);
6155 
6156 	vm_page_spin_lock(m);
6157 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
6158 		if (!pmap_track_modified(pv->pv_pindex))
6159 			continue;
6160 		pmap = pv->pv_pmap;
6161 		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
6162 		if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
6163 			atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
6164 			rtval++;
6165 			if (rtval > 4)
6166 				break;
6167 		}
6168 	}
6169 	vm_page_spin_unlock(m);
6170 	return (rtval);
6171 }
6172 
6173 /*
6174  *	pmap_is_modified:
6175  *
6176  *	Return whether or not the specified physical page was modified
6177  *	in any physical maps.
6178  */
6179 boolean_t
6180 pmap_is_modified(vm_page_t m)
6181 {
6182 	boolean_t res;
6183 
6184 	res = pmap_testbit(m, PG_M_IDX);
6185 	return (res);
6186 }
6187 
6188 /*
6189  *	Clear the modify bits on the specified physical page.
6190  */
6191 void
6192 pmap_clear_modify(vm_page_t m)
6193 {
6194 	pmap_clearbit(m, PG_M_IDX);
6195 }
6196 
6197 /*
6198  *	pmap_clear_reference:
6199  *
6200  *	Clear the reference bit on the specified physical page.
6201  */
6202 void
6203 pmap_clear_reference(vm_page_t m)
6204 {
6205 	pmap_clearbit(m, PG_A_IDX);
6206 }
6207 
6208 /*
6209  * Miscellaneous support routines follow
6210  */
6211 
6212 static
6213 void
6214 x86_64_protection_init(void)
6215 {
6216 	uint64_t *kp;
6217 	int prot;
6218 
6219 	/*
6220 	 * NX supported? (boot time loader.conf override only)
6221 	 */
6222 	TUNABLE_INT_FETCH("machdep.pmap_nx_enable", &pmap_nx_enable);
6223 	if (pmap_nx_enable == 0 || (amd_feature & AMDID_NX) == 0)
6224 		pmap_bits_default[PG_NX_IDX] = 0;
6225 
6226 	/*
6227 	 * 0 is basically read-only access, but also set the NX (no-execute)
6228 	 * bit when VM_PROT_EXECUTE is not specified.
6229 	 */
6230 	kp = protection_codes;
6231 	for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
6232 		switch (prot) {
6233 		case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
6234 			/*
6235 			 * This case handled elsewhere
6236 			 */
6237 			*kp++ = 0;
6238 			break;
6239 		case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
6240 			/*
6241 			 * Read-only is 0|NX
6242 			 */
6243 			*kp++ = pmap_bits_default[PG_NX_IDX];
6244 			break;
6245 		case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
6246 		case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
6247 			/*
6248 			 * Execute requires read access
6249 			 */
6250 			*kp++ = 0;
6251 			break;
6252 		case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
6253 		case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
6254 			/*
6255 			 * Write without execute is RW|NX
6256 			 */
6257 			*kp++ = pmap_bits_default[PG_RW_IDX] |
6258 				pmap_bits_default[PG_NX_IDX];
6259 			break;
6260 		case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
6261 		case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
6262 			/*
6263 			 * Write with execute is RW
6264 			 */
6265 			*kp++ = pmap_bits_default[PG_RW_IDX];
6266 			break;
6267 		}
6268 	}
6269 }
6270 
6271 /*
6272  * Map a set of physical memory pages into the kernel virtual
6273  * address space. Return a pointer to where it is mapped. This
6274  * routine is intended to be used for mapping device memory,
6275  * NOT real memory.
6276  *
6277  * NOTE: We can't use pgeflag unless we invalidate the pages one at
6278  *	 a time.
6279  *
6280  * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
6281  *	 work whether the cpu supports PAT or not.  The remaining PAT
6282  *	 attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
6283  *	 supports PAT.
6284  */
6285 void *
6286 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6287 {
6288 	return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6289 }
6290 
6291 void *
6292 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
6293 {
6294 	return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6295 }
6296 
6297 void *
6298 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6299 {
6300 	return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6301 }
6302 
6303 /*
6304  * Map a set of physical memory pages into the kernel virtual
6305  * address space. Return a pointer to where it is mapped. This
6306  * routine is intended to be used for mapping device memory,
6307  * NOT real memory.
6308  */
6309 void *
6310 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6311 {
6312 	vm_offset_t va, tmpva, offset;
6313 	pt_entry_t *pte;
6314 	vm_size_t tmpsize;
6315 
6316 	offset = pa & PAGE_MASK;
6317 	size = roundup(offset + size, PAGE_SIZE);
6318 
6319 	va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
6320 	if (va == 0)
6321 		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
6322 
6323 	pa = pa & ~PAGE_MASK;
6324 	for (tmpva = va, tmpsize = size; tmpsize > 0;) {
6325 		pte = vtopte(tmpva);
6326 		*pte = pa |
6327 		    kernel_pmap.pmap_bits[PG_RW_IDX] |
6328 		    kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
6329 		    kernel_pmap.pmap_cache_bits[mode];
6330 		tmpsize -= PAGE_SIZE;
6331 		tmpva += PAGE_SIZE;
6332 		pa += PAGE_SIZE;
6333 	}
6334 	pmap_invalidate_range(&kernel_pmap, va, va + size);
6335 	pmap_invalidate_cache_range(va, va + size);
6336 
6337 	return ((void *)(va + offset));
6338 }
6339 
6340 void
6341 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6342 {
6343 	vm_offset_t base, offset;
6344 
6345 	base = va & ~PAGE_MASK;
6346 	offset = va & PAGE_MASK;
6347 	size = roundup(offset + size, PAGE_SIZE);
6348 	pmap_qremove(va, size >> PAGE_SHIFT);
6349 	kmem_free(&kernel_map, base, size);
6350 }
6351 
6352 /*
6353  * Sets the memory attribute for the specified page.
6354  */
6355 void
6356 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6357 {
6358 
6359     m->pat_mode = ma;
6360 
6361     /*
6362      * If "m" is a normal page, update its direct mapping.  This update
6363      * can be relied upon to perform any cache operations that are
6364      * required for data coherence.
6365      */
6366     if ((m->flags & PG_FICTITIOUS) == 0)
6367         pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
6368 }
6369 
6370 /*
6371  * Change the PAT attribute on an existing kernel memory map.  Caller
6372  * must ensure that the virtual memory in question is not accessed
6373  * during the adjustment.
6374  */
6375 void
6376 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
6377 {
6378 	pt_entry_t *pte;
6379 	vm_offset_t base;
6380 	int changed = 0;
6381 
6382 	if (va == 0)
6383 		panic("pmap_change_attr: va is NULL");
6384 	base = trunc_page(va);
6385 
6386 	while (count) {
6387 		pte = vtopte(va);
6388 		*pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
6389 		       kernel_pmap.pmap_cache_bits[mode];
6390 		--count;
6391 		va += PAGE_SIZE;
6392 	}
6393 
6394 	changed = 1;	/* XXX: not optimal */
6395 
6396 	/*
6397 	 * Flush CPU caches if required to make sure any data isn't cached that
6398 	 * shouldn't be, etc.
6399 	 */
6400 	if (changed) {
6401 		pmap_invalidate_range(&kernel_pmap, base, va);
6402 		pmap_invalidate_cache_range(base, va);
6403 	}
6404 }
6405 
6406 /*
6407  * perform the pmap work for mincore
6408  */
6409 int
6410 pmap_mincore(pmap_t pmap, vm_offset_t addr)
6411 {
6412 	pt_entry_t *ptep, pte;
6413 	vm_page_t m;
6414 	int val = 0;
6415 
6416 	ptep = pmap_pte(pmap, addr);
6417 
6418 	if (ptep && (pte = *ptep) != 0) {
6419 		vm_offset_t pa;
6420 
6421 		val = MINCORE_INCORE;
6422 		if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
6423 			goto done;
6424 
6425 		pa = pte & PG_FRAME;
6426 
6427 		if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
6428 			m = NULL;
6429 		else
6430 			m = PHYS_TO_VM_PAGE(pa);
6431 
6432 		/*
6433 		 * Modified by us
6434 		 */
6435 		if (pte & pmap->pmap_bits[PG_M_IDX])
6436 			val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
6437 		/*
6438 		 * Modified by someone
6439 		 */
6440 		else if (m && (m->dirty || pmap_is_modified(m)))
6441 			val |= MINCORE_MODIFIED_OTHER;
6442 		/*
6443 		 * Referenced by us
6444 		 */
6445 		if (pte & pmap->pmap_bits[PG_A_IDX])
6446 			val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
6447 
6448 		/*
6449 		 * Referenced by someone
6450 		 */
6451 		else if (m && ((m->flags & PG_REFERENCED) ||
6452 				pmap_ts_referenced(m))) {
6453 			val |= MINCORE_REFERENCED_OTHER;
6454 			vm_page_flag_set(m, PG_REFERENCED);
6455 		}
6456 	}
6457 done:
6458 
6459 	return val;
6460 }
6461 
6462 /*
6463  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
6464  * vmspace will be ref'd and the old one will be deref'd.
6465  *
6466  * The vmspace for all lwps associated with the process will be adjusted
6467  * and cr3 will be reloaded if any lwp is the current lwp.
6468  *
6469  * The process must hold the vmspace->vm_map.token for oldvm and newvm
6470  */
6471 void
6472 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
6473 {
6474 	struct vmspace *oldvm;
6475 	struct lwp *lp;
6476 
6477 	oldvm = p->p_vmspace;
6478 	if (oldvm != newvm) {
6479 		if (adjrefs)
6480 			vmspace_ref(newvm);
6481 		p->p_vmspace = newvm;
6482 		KKASSERT(p->p_nthreads == 1);
6483 		lp = RB_ROOT(&p->p_lwp_tree);
6484 		pmap_setlwpvm(lp, newvm);
6485 		if (adjrefs)
6486 			vmspace_rel(oldvm);
6487 	}
6488 }
6489 
6490 /*
6491  * Set the vmspace for a LWP.  The vmspace is almost universally set the
6492  * same as the process vmspace, but virtual kernels need to swap out contexts
6493  * on a per-lwp basis.
6494  *
6495  * Caller does not necessarily hold any vmspace tokens.  Caller must control
6496  * the lwp (typically be in the context of the lwp).  We use a critical
6497  * section to protect against statclock and hardclock (statistics collection).
6498  */
6499 void
6500 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
6501 {
6502 	struct vmspace *oldvm;
6503 	struct pmap *pmap;
6504 	thread_t td;
6505 
6506 	oldvm = lp->lwp_vmspace;
6507 
6508 	if (oldvm != newvm) {
6509 		crit_enter();
6510 		td = curthread;
6511 		KKASSERT((newvm->vm_refcnt & VM_REF_DELETED) == 0);
6512 		lp->lwp_vmspace = newvm;
6513 		if (td->td_lwp == lp) {
6514 			pmap = vmspace_pmap(newvm);
6515 			ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
6516 			if (pmap->pm_active_lock & CPULOCK_EXCL)
6517 				pmap_interlock_wait(newvm);
6518 #if defined(SWTCH_OPTIM_STATS)
6519 			tlb_flush_count++;
6520 #endif
6521 			if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
6522 				td->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
6523 				if (meltdown_mitigation && pmap->pm_pmlpv_iso) {
6524 					td->td_pcb->pcb_cr3_iso =
6525 						vtophys(pmap->pm_pml4_iso);
6526 					td->td_pcb->pcb_flags |= PCB_ISOMMU;
6527 				} else {
6528 					td->td_pcb->pcb_cr3_iso = 0;
6529 					td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6530 				}
6531 			} else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
6532 				td->td_pcb->pcb_cr3 = KPML4phys;
6533 				td->td_pcb->pcb_cr3_iso = 0;
6534 				td->td_pcb->pcb_flags &= ~PCB_ISOMMU;
6535 			} else {
6536 				panic("pmap_setlwpvm: unknown pmap type\n");
6537 			}
6538 
6539 			/*
6540 			 * The MMU separation fields needs to be updated.
6541 			 * (it can't access the pcb directly from the
6542 			 * restricted user pmap).
6543 			 */
6544 			{
6545 				struct trampframe *tramp;
6546 
6547 				tramp = &pscpu->trampoline;
6548 				tramp->tr_pcb_cr3 = td->td_pcb->pcb_cr3;
6549 				tramp->tr_pcb_cr3_iso = td->td_pcb->pcb_cr3_iso;
6550 				tramp->tr_pcb_flags = td->td_pcb->pcb_flags;
6551 				tramp->tr_pcb_rsp = (register_t)td->td_pcb;
6552 				/* tr_pcb_rsp doesn't change */
6553 			}
6554 
6555 			/*
6556 			 * In kernel-land we always use the normal PML4E
6557 			 * so the kernel is fully mapped and can also access
6558 			 * user memory.
6559 			 */
6560 			load_cr3(td->td_pcb->pcb_cr3);
6561 			pmap = vmspace_pmap(oldvm);
6562 			ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
6563 					       mycpu->gd_cpuid);
6564 		}
6565 		crit_exit();
6566 	}
6567 }
6568 
6569 /*
6570  * Called when switching to a locked pmap, used to interlock against pmaps
6571  * undergoing modifications to prevent us from activating the MMU for the
6572  * target pmap until all such modifications have completed.  We have to do
6573  * this because the thread making the modifications has already set up its
6574  * SMP synchronization mask.
6575  *
6576  * This function cannot sleep!
6577  *
6578  * No requirements.
6579  */
6580 void
6581 pmap_interlock_wait(struct vmspace *vm)
6582 {
6583 	struct pmap *pmap = &vm->vm_pmap;
6584 
6585 	if (pmap->pm_active_lock & CPULOCK_EXCL) {
6586 		crit_enter();
6587 		KKASSERT(curthread->td_critcount >= 2);
6588 		DEBUG_PUSH_INFO("pmap_interlock_wait");
6589 		while (pmap->pm_active_lock & CPULOCK_EXCL) {
6590 			cpu_ccfence();
6591 			lwkt_process_ipiq();
6592 		}
6593 		DEBUG_POP_INFO();
6594 		crit_exit();
6595 	}
6596 }
6597 
6598 vm_offset_t
6599 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
6600 {
6601 
6602 	if ((obj == NULL) || (size < NBPDR) ||
6603 	    ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
6604 		return addr;
6605 	}
6606 
6607 	addr = roundup2(addr, NBPDR);
6608 	return addr;
6609 }
6610 
6611 /*
6612  * Used by kmalloc/kfree, page already exists at va
6613  */
6614 vm_page_t
6615 pmap_kvtom(vm_offset_t va)
6616 {
6617 	pt_entry_t *ptep = vtopte(va);
6618 
6619 	KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
6620 	return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
6621 }
6622 
6623 /*
6624  * Initialize machine-specific shared page directory support.  This
6625  * is executed when a VM object is created.
6626  */
6627 void
6628 pmap_object_init(vm_object_t object)
6629 {
6630 	object->md.pmap_rw = NULL;
6631 	object->md.pmap_ro = NULL;
6632 }
6633 
6634 /*
6635  * Clean up machine-specific shared page directory support.  This
6636  * is executed when a VM object is destroyed.
6637  */
6638 void
6639 pmap_object_free(vm_object_t object)
6640 {
6641 	pmap_t pmap;
6642 
6643 	if ((pmap = object->md.pmap_rw) != NULL) {
6644 		object->md.pmap_rw = NULL;
6645 		pmap_remove_noinval(pmap,
6646 				  VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6647 		CPUMASK_ASSZERO(pmap->pm_active);
6648 		pmap_release(pmap);
6649 		pmap_puninit(pmap);
6650 		kfree(pmap, M_OBJPMAP);
6651 	}
6652 	if ((pmap = object->md.pmap_ro) != NULL) {
6653 		object->md.pmap_ro = NULL;
6654 		pmap_remove_noinval(pmap,
6655 				  VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
6656 		CPUMASK_ASSZERO(pmap->pm_active);
6657 		pmap_release(pmap);
6658 		pmap_puninit(pmap);
6659 		kfree(pmap, M_OBJPMAP);
6660 	}
6661 }
6662 
6663 /*
6664  * pmap_pgscan_callback - Used by pmap_pgscan to acquire the related
6665  * VM page and issue a pginfo->callback.
6666  *
6667  * We are expected to dispose of any non-NULL pte_pv.
6668  */
6669 static
6670 void
6671 pmap_pgscan_callback(pmap_t pmap, struct pmap_scan_info *info,
6672 		      pv_entry_t pte_pv, vm_pindex_t *pte_placemark,
6673 		      pv_entry_t pt_pv, int sharept,
6674 		      vm_offset_t va, pt_entry_t *ptep, void *arg)
6675 {
6676 	struct pmap_pgscan_info *pginfo = arg;
6677 	vm_page_t m;
6678 
6679 	if (pte_pv) {
6680 		/*
6681 		 * Try to busy the page while we hold the pte_pv locked.
6682 		 */
6683 		KKASSERT(pte_pv->pv_m);
6684 		m = PHYS_TO_VM_PAGE(*ptep & PG_FRAME);
6685 		if (vm_page_busy_try(m, TRUE) == 0) {
6686 			if (m == PHYS_TO_VM_PAGE(*ptep & PG_FRAME)) {
6687 				/*
6688 				 * The callback is issued with the pte_pv
6689 				 * unlocked and put away, and the pt_pv
6690 				 * unlocked.
6691 				 */
6692 				pv_put(pte_pv);
6693 				if (pt_pv) {
6694 					vm_page_wire_quick(pt_pv->pv_m);
6695 					pv_unlock(pt_pv);
6696 				}
6697 				if (pginfo->callback(pginfo, va, m) < 0)
6698 					info->stop = 1;
6699 				if (pt_pv) {
6700 					pv_lock(pt_pv);
6701 					vm_page_unwire_quick(pt_pv->pv_m);
6702 				}
6703 			} else {
6704 				vm_page_wakeup(m);
6705 				pv_put(pte_pv);
6706 			}
6707 		} else {
6708 			++pginfo->busycount;
6709 			pv_put(pte_pv);
6710 		}
6711 	} else {
6712 		/*
6713 		 * Shared page table or unmanaged page (sharept or !sharept)
6714 		 */
6715 		pv_placemarker_wakeup(pmap, pte_placemark);
6716 	}
6717 }
6718 
6719 void
6720 pmap_pgscan(struct pmap_pgscan_info *pginfo)
6721 {
6722 	struct pmap_scan_info info;
6723 
6724 	pginfo->offset = pginfo->beg_addr;
6725 	info.pmap = pginfo->pmap;
6726 	info.sva = pginfo->beg_addr;
6727 	info.eva = pginfo->end_addr;
6728 	info.func = pmap_pgscan_callback;
6729 	info.arg = pginfo;
6730 	pmap_scan(&info, 0);
6731 	if (info.stop == 0)
6732 		pginfo->offset = pginfo->end_addr;
6733 }
6734 
6735 /*
6736  * Wait for a placemarker that we do not own to clear.  The placemarker
6737  * in question is not necessarily set to the pindex we want, we may have
6738  * to wait on the element because we want to reserve it ourselves.
6739  *
6740  * NOTE: PM_PLACEMARK_WAKEUP sets a bit which is already set in
6741  *	 PM_NOPLACEMARK, so it does not interfere with placemarks
6742  *	 which have already been woken up.
6743  */
6744 static
6745 void
6746 pv_placemarker_wait(pmap_t pmap, vm_pindex_t *pmark)
6747 {
6748 	if (*pmark != PM_NOPLACEMARK) {
6749 		atomic_set_long(pmark, PM_PLACEMARK_WAKEUP);
6750 		tsleep_interlock(pmark, 0);
6751 		if (*pmark != PM_NOPLACEMARK)
6752 			tsleep(pmark, PINTERLOCKED, "pvplw", 0);
6753 	}
6754 }
6755 
6756 /*
6757  * Wakeup a placemarker that we own.  Replace the entry with
6758  * PM_NOPLACEMARK and issue a wakeup() if necessary.
6759  */
6760 static
6761 void
6762 pv_placemarker_wakeup(pmap_t pmap, vm_pindex_t *pmark)
6763 {
6764 	vm_pindex_t pindex;
6765 
6766 	pindex = atomic_swap_long(pmark, PM_NOPLACEMARK);
6767 	KKASSERT(pindex != PM_NOPLACEMARK);
6768 	if (pindex & PM_PLACEMARK_WAKEUP)
6769 		wakeup(pmark);
6770 }
6771