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