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