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