xref: /freebsd/sys/i386/i386/pmap.c (revision 81b22a98)
1 /*-
2  * SPDX-License-Identifier: BSD-4-Clause
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11  * All rights reserved.
12  *
13  * This code is derived from software contributed to Berkeley by
14  * the Systems Programming Group of the University of Utah Computer
15  * Science Department and William Jolitz of UUNET Technologies Inc.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. All advertising materials mentioning features or use of this software
26  *    must display the following acknowledgement:
27  *	This product includes software developed by the University of
28  *	California, Berkeley and its contributors.
29  * 4. Neither the name of the University nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43  * SUCH DAMAGE.
44  *
45  *	from:	@(#)pmap.c	7.7 (Berkeley)	5/12/91
46  */
47 /*-
48  * Copyright (c) 2003 Networks Associates Technology, Inc.
49  * All rights reserved.
50  * Copyright (c) 2018 The FreeBSD Foundation
51  * All rights reserved.
52  *
53  * This software was developed for the FreeBSD Project by Jake Burkholder,
54  * Safeport Network Services, and Network Associates Laboratories, the
55  * Security Research Division of Network Associates, Inc. under
56  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
57  * CHATS research program.
58  *
59  * Portions of this software were developed by
60  * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
61  * the FreeBSD Foundation.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  * 1. Redistributions of source code must retain the above copyright
67  *    notice, this list of conditions and the following disclaimer.
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in the
70  *    documentation and/or other materials provided with the distribution.
71  *
72  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
73  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
76  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
77  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
78  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
79  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
80  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
81  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
82  * SUCH DAMAGE.
83  */
84 
85 #include <sys/cdefs.h>
86 __FBSDID("$FreeBSD$");
87 
88 /*
89  *	Manages physical address maps.
90  *
91  *	Since the information managed by this module is
92  *	also stored by the logical address mapping module,
93  *	this module may throw away valid virtual-to-physical
94  *	mappings at almost any time.  However, invalidations
95  *	of virtual-to-physical mappings must be done as
96  *	requested.
97  *
98  *	In order to cope with hardware architectures which
99  *	make virtual-to-physical map invalidates expensive,
100  *	this module may delay invalidate or reduced protection
101  *	operations until such time as they are actually
102  *	necessary.  This module is given full information as
103  *	to which processors are currently using which maps,
104  *	and to when physical maps must be made correct.
105  */
106 
107 #include "opt_apic.h"
108 #include "opt_cpu.h"
109 #include "opt_pmap.h"
110 #include "opt_smp.h"
111 #include "opt_vm.h"
112 
113 #include <sys/param.h>
114 #include <sys/systm.h>
115 #include <sys/kernel.h>
116 #include <sys/ktr.h>
117 #include <sys/lock.h>
118 #include <sys/malloc.h>
119 #include <sys/mman.h>
120 #include <sys/msgbuf.h>
121 #include <sys/mutex.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
124 #include <sys/sbuf.h>
125 #include <sys/sf_buf.h>
126 #include <sys/sx.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
130 #include <sys/smp.h>
131 #include <sys/vmem.h>
132 
133 #include <vm/vm.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
145 #include <vm/uma.h>
146 
147 #ifdef DEV_APIC
148 #include <sys/bus.h>
149 #include <machine/intr_machdep.h>
150 #include <x86/apicvar.h>
151 #endif
152 #include <x86/ifunc.h>
153 #include <machine/bootinfo.h>
154 #include <machine/cpu.h>
155 #include <machine/cputypes.h>
156 #include <machine/md_var.h>
157 #include <machine/pcb.h>
158 #include <machine/specialreg.h>
159 #ifdef SMP
160 #include <machine/smp.h>
161 #endif
162 #include <machine/pmap_base.h>
163 
164 #if !defined(DIAGNOSTIC)
165 #ifdef __GNUC_GNU_INLINE__
166 #define PMAP_INLINE	__attribute__((__gnu_inline__)) inline
167 #else
168 #define PMAP_INLINE	extern inline
169 #endif
170 #else
171 #define PMAP_INLINE
172 #endif
173 
174 #ifdef PV_STATS
175 #define PV_STAT(x)	do { x ; } while (0)
176 #else
177 #define PV_STAT(x)	do { } while (0)
178 #endif
179 
180 #define	pa_index(pa)	((pa) >> PDRSHIFT)
181 #define	pa_to_pvh(pa)	(&pv_table[pa_index(pa)])
182 
183 /*
184  * PTmap is recursive pagemap at top of virtual address space.
185  * Within PTmap, the page directory can be found (third indirection).
186  */
187 #define	PTmap	((pt_entry_t *)(PTDPTDI << PDRSHIFT))
188 #define	PTD	((pd_entry_t *)((PTDPTDI << PDRSHIFT) + (PTDPTDI * PAGE_SIZE)))
189 #define	PTDpde	((pd_entry_t *)((PTDPTDI << PDRSHIFT) + (PTDPTDI * PAGE_SIZE) + \
190     (PTDPTDI * PDESIZE)))
191 
192 /*
193  * Translate a virtual address to the kernel virtual address of its page table
194  * entry (PTE).  This can be used recursively.  If the address of a PTE as
195  * previously returned by this macro is itself given as the argument, then the
196  * address of the page directory entry (PDE) that maps the PTE will be
197  * returned.
198  *
199  * This macro may be used before pmap_bootstrap() is called.
200  */
201 #define	vtopte(va)	(PTmap + i386_btop(va))
202 
203 /*
204  * Get PDEs and PTEs for user/kernel address space
205  */
206 #define	pmap_pde(m, v)	(&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
207 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
208 
209 #define pmap_pde_v(pte)		((*(int *)pte & PG_V) != 0)
210 #define pmap_pte_w(pte)		((*(int *)pte & PG_W) != 0)
211 #define pmap_pte_m(pte)		((*(int *)pte & PG_M) != 0)
212 #define pmap_pte_u(pte)		((*(int *)pte & PG_A) != 0)
213 #define pmap_pte_v(pte)		((*(int *)pte & PG_V) != 0)
214 
215 #define pmap_pte_set_w(pte, v)	((v) ? atomic_set_int((u_int *)(pte), PG_W) : \
216     atomic_clear_int((u_int *)(pte), PG_W))
217 #define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
218 
219 static int pgeflag = 0;		/* PG_G or-in */
220 static int pseflag = 0;		/* PG_PS or-in */
221 
222 static int nkpt = NKPT;
223 
224 #ifdef PMAP_PAE_COMP
225 pt_entry_t pg_nx;
226 static uma_zone_t pdptzone;
227 #else
228 #define	pg_nx	0
229 #endif
230 
231 _Static_assert(VM_MAXUSER_ADDRESS == VADDR(TRPTDI, 0), "VM_MAXUSER_ADDRESS");
232 _Static_assert(VM_MAX_KERNEL_ADDRESS <= VADDR(PTDPTDI, 0),
233     "VM_MAX_KERNEL_ADDRESS");
234 _Static_assert(PMAP_MAP_LOW == VADDR(LOWPTDI, 0), "PMAP_MAP_LOW");
235 _Static_assert(KERNLOAD == (KERNPTDI << PDRSHIFT), "KERNLOAD");
236 
237 extern int pat_works;
238 extern int pg_ps_enabled;
239 
240 extern int elf32_nxstack;
241 
242 #define	PAT_INDEX_SIZE	8
243 static int pat_index[PAT_INDEX_SIZE];	/* cache mode to PAT index conversion */
244 
245 /*
246  * pmap_mapdev support pre initialization (i.e. console)
247  */
248 #define	PMAP_PREINIT_MAPPING_COUNT	8
249 static struct pmap_preinit_mapping {
250 	vm_paddr_t	pa;
251 	vm_offset_t	va;
252 	vm_size_t	sz;
253 	int		mode;
254 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
255 static int pmap_initialized;
256 
257 static struct rwlock_padalign pvh_global_lock;
258 
259 /*
260  * Data for the pv entry allocation mechanism
261  */
262 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
263 extern int pv_entry_max, pv_entry_count;
264 static int pv_entry_high_water = 0;
265 static struct md_page *pv_table;
266 extern int shpgperproc;
267 
268 static struct pv_chunk *pv_chunkbase;	/* KVA block for pv_chunks */
269 static int pv_maxchunks;		/* How many chunks we have KVA for */
270 static vm_offset_t pv_vafree;		/* freelist stored in the PTE */
271 
272 /*
273  * All those kernel PT submaps that BSD is so fond of
274  */
275 static pt_entry_t *CMAP3;
276 static pd_entry_t *KPTD;
277 static caddr_t CADDR3;
278 
279 /*
280  * Crashdump maps.
281  */
282 static caddr_t crashdumpmap;
283 
284 static pt_entry_t *PMAP1 = NULL, *PMAP2, *PMAP3;
285 static pt_entry_t *PADDR1 = NULL, *PADDR2, *PADDR3;
286 #ifdef SMP
287 static int PMAP1cpu, PMAP3cpu;
288 extern int PMAP1changedcpu;
289 #endif
290 extern int PMAP1changed;
291 extern int PMAP1unchanged;
292 static struct mtx PMAP2mutex;
293 
294 /*
295  * Internal flags for pmap_enter()'s helper functions.
296  */
297 #define	PMAP_ENTER_NORECLAIM	0x1000000	/* Don't reclaim PV entries. */
298 #define	PMAP_ENTER_NOREPLACE	0x2000000	/* Don't replace mappings. */
299 
300 static void	free_pv_chunk(struct pv_chunk *pc);
301 static void	free_pv_entry(pmap_t pmap, pv_entry_t pv);
302 static pv_entry_t get_pv_entry(pmap_t pmap, boolean_t try);
303 static void	pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
304 static bool	pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
305 		    u_int flags);
306 #if VM_NRESERVLEVEL > 0
307 static void	pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
308 #endif
309 static void	pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
310 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
311 		    vm_offset_t va);
312 static int	pmap_pvh_wired_mappings(struct md_page *pvh, int count);
313 
314 static void	pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
315 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
316 static bool	pmap_enter_4mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
317 		    vm_prot_t prot);
318 static int	pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
319 		    u_int flags, vm_page_t m);
320 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
321     vm_page_t m, vm_prot_t prot, vm_page_t mpte);
322 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted);
323 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
324 		    pd_entry_t pde);
325 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
326 static boolean_t pmap_is_modified_pvh(struct md_page *pvh);
327 static boolean_t pmap_is_referenced_pvh(struct md_page *pvh);
328 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
329 static void pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde);
330 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits);
331 #if VM_NRESERVLEVEL > 0
332 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
333 #endif
334 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
335     vm_prot_t prot);
336 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits);
337 static void pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
338     struct spglist *free);
339 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
340     struct spglist *free);
341 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
342 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, struct spglist *free);
343 static bool	pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
344 		    struct spglist *free);
345 static void pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va);
346 static void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
347 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
348     vm_page_t m);
349 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
350     pd_entry_t newpde);
351 static void pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde);
352 
353 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags);
354 
355 static vm_page_t _pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags);
356 static void _pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free);
357 static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
358 static void pmap_pte_release(pt_entry_t *pte);
359 static int pmap_unuse_pt(pmap_t, vm_offset_t, struct spglist *);
360 #ifdef PMAP_PAE_COMP
361 static void *pmap_pdpt_allocf(uma_zone_t zone, vm_size_t bytes, int domain,
362     uint8_t *flags, int wait);
363 #endif
364 static void pmap_init_trm(void);
365 static void pmap_invalidate_all_int(pmap_t pmap);
366 
367 static __inline void pagezero(void *page);
368 
369 CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
370 CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
371 
372 extern char _end[];
373 extern u_long physfree;	/* phys addr of next free page */
374 extern u_long vm86phystk;/* PA of vm86/bios stack */
375 extern u_long vm86paddr;/* address of vm86 region */
376 extern int vm86pa;	/* phys addr of vm86 region */
377 extern u_long KERNend;	/* phys addr end of kernel (just after bss) */
378 #ifdef PMAP_PAE_COMP
379 pd_entry_t *IdlePTD_pae;	/* phys addr of kernel PTD */
380 pdpt_entry_t *IdlePDPT;	/* phys addr of kernel PDPT */
381 pt_entry_t *KPTmap_pae;	/* address of kernel page tables */
382 #define	IdlePTD	IdlePTD_pae
383 #define	KPTmap	KPTmap_pae
384 #else
385 pd_entry_t *IdlePTD_nopae;
386 pt_entry_t *KPTmap_nopae;
387 #define	IdlePTD	IdlePTD_nopae
388 #define	KPTmap	KPTmap_nopae
389 #endif
390 extern u_long KPTphys;	/* phys addr of kernel page tables */
391 extern u_long tramp_idleptd;
392 
393 static u_long
394 allocpages(u_int cnt, u_long *physfree)
395 {
396 	u_long res;
397 
398 	res = *physfree;
399 	*physfree += PAGE_SIZE * cnt;
400 	bzero((void *)res, PAGE_SIZE * cnt);
401 	return (res);
402 }
403 
404 static void
405 pmap_cold_map(u_long pa, u_long va, u_long cnt)
406 {
407 	pt_entry_t *pt;
408 
409 	for (pt = (pt_entry_t *)KPTphys + atop(va); cnt > 0;
410 	    cnt--, pt++, va += PAGE_SIZE, pa += PAGE_SIZE)
411 		*pt = pa | PG_V | PG_RW | PG_A | PG_M;
412 }
413 
414 static void
415 pmap_cold_mapident(u_long pa, u_long cnt)
416 {
417 
418 	pmap_cold_map(pa, pa, cnt);
419 }
420 
421 _Static_assert(LOWPTDI * 2 * NBPDR == KERNBASE,
422     "Broken double-map of zero PTD");
423 
424 static void
425 __CONCAT(PMTYPE, remap_lower)(bool enable)
426 {
427 	int i;
428 
429 	for (i = 0; i < LOWPTDI; i++)
430 		IdlePTD[i] = enable ? IdlePTD[LOWPTDI + i] : 0;
431 	load_cr3(rcr3());		/* invalidate TLB */
432 }
433 
434 /*
435  * Called from locore.s before paging is enabled.  Sets up the first
436  * kernel page table.  Since kernel is mapped with PA == VA, this code
437  * does not require relocations.
438  */
439 void
440 __CONCAT(PMTYPE, cold)(void)
441 {
442 	pt_entry_t *pt;
443 	u_long a;
444 	u_int cr3, ncr4;
445 
446 	physfree = (u_long)&_end;
447 	if (bootinfo.bi_esymtab != 0)
448 		physfree = bootinfo.bi_esymtab;
449 	if (bootinfo.bi_kernend != 0)
450 		physfree = bootinfo.bi_kernend;
451 	physfree = roundup2(physfree, NBPDR);
452 	KERNend = physfree;
453 
454 	/* Allocate Kernel Page Tables */
455 	KPTphys = allocpages(NKPT, &physfree);
456 	KPTmap = (pt_entry_t *)KPTphys;
457 
458 	/* Allocate Page Table Directory */
459 #ifdef PMAP_PAE_COMP
460 	/* XXX only need 32 bytes (easier for now) */
461 	IdlePDPT = (pdpt_entry_t *)allocpages(1, &physfree);
462 #endif
463 	IdlePTD = (pd_entry_t *)allocpages(NPGPTD, &physfree);
464 
465 	/*
466 	 * Allocate KSTACK.  Leave a guard page between IdlePTD and
467 	 * proc0kstack, to control stack overflow for thread0 and
468 	 * prevent corruption of the page table.  We leak the guard
469 	 * physical memory due to 1:1 mappings.
470 	 */
471 	allocpages(1, &physfree);
472 	proc0kstack = allocpages(TD0_KSTACK_PAGES, &physfree);
473 
474 	/* vm86/bios stack */
475 	vm86phystk = allocpages(1, &physfree);
476 
477 	/* pgtable + ext + IOPAGES */
478 	vm86paddr = vm86pa = allocpages(3, &physfree);
479 
480 	/* Install page tables into PTD.  Page table page 1 is wasted. */
481 	for (a = 0; a < NKPT; a++)
482 		IdlePTD[a] = (KPTphys + ptoa(a)) | PG_V | PG_RW | PG_A | PG_M;
483 
484 #ifdef PMAP_PAE_COMP
485 	/* PAE install PTD pointers into PDPT */
486 	for (a = 0; a < NPGPTD; a++)
487 		IdlePDPT[a] = ((u_int)IdlePTD + ptoa(a)) | PG_V;
488 #endif
489 
490 	/*
491 	 * Install recursive mapping for kernel page tables into
492 	 * itself.
493 	 */
494 	for (a = 0; a < NPGPTD; a++)
495 		IdlePTD[PTDPTDI + a] = ((u_int)IdlePTD + ptoa(a)) | PG_V |
496 		    PG_RW;
497 
498 	/*
499 	 * Initialize page table pages mapping physical address zero
500 	 * through the (physical) end of the kernel.  Many of these
501 	 * pages must be reserved, and we reserve them all and map
502 	 * them linearly for convenience.  We do this even if we've
503 	 * enabled PSE above; we'll just switch the corresponding
504 	 * kernel PDEs before we turn on paging.
505 	 *
506 	 * This and all other page table entries allow read and write
507 	 * access for various reasons.  Kernel mappings never have any
508 	 * access restrictions.
509 	 */
510 	pmap_cold_mapident(0, atop(NBPDR) * LOWPTDI);
511 	pmap_cold_map(0, NBPDR * LOWPTDI, atop(NBPDR) * LOWPTDI);
512 	pmap_cold_mapident(KERNBASE, atop(KERNend - KERNBASE));
513 
514 	/* Map page table directory */
515 #ifdef PMAP_PAE_COMP
516 	pmap_cold_mapident((u_long)IdlePDPT, 1);
517 #endif
518 	pmap_cold_mapident((u_long)IdlePTD, NPGPTD);
519 
520 	/* Map early KPTmap.  It is really pmap_cold_mapident. */
521 	pmap_cold_map(KPTphys, (u_long)KPTmap, NKPT);
522 
523 	/* Map proc0kstack */
524 	pmap_cold_mapident(proc0kstack, TD0_KSTACK_PAGES);
525 	/* ISA hole already mapped */
526 
527 	pmap_cold_mapident(vm86phystk, 1);
528 	pmap_cold_mapident(vm86pa, 3);
529 
530 	/* Map page 0 into the vm86 page table */
531 	*(pt_entry_t *)vm86pa = 0 | PG_RW | PG_U | PG_A | PG_M | PG_V;
532 
533 	/* ...likewise for the ISA hole for vm86 */
534 	for (pt = (pt_entry_t *)vm86pa + atop(ISA_HOLE_START), a = 0;
535 	    a < atop(ISA_HOLE_LENGTH); a++, pt++)
536 		*pt = (ISA_HOLE_START + ptoa(a)) | PG_RW | PG_U | PG_A |
537 		    PG_M | PG_V;
538 
539 	/* Enable PSE, PGE, VME, and PAE if configured. */
540 	ncr4 = 0;
541 	if ((cpu_feature & CPUID_PSE) != 0) {
542 		ncr4 |= CR4_PSE;
543 		pseflag = PG_PS;
544 		/*
545 		 * Superpage mapping of the kernel text.  Existing 4k
546 		 * page table pages are wasted.
547 		 */
548 		for (a = KERNBASE; a < KERNend; a += NBPDR)
549 			IdlePTD[a >> PDRSHIFT] = a | PG_PS | PG_A | PG_M |
550 			    PG_RW | PG_V;
551 	}
552 	if ((cpu_feature & CPUID_PGE) != 0) {
553 		ncr4 |= CR4_PGE;
554 		pgeflag = PG_G;
555 	}
556 	ncr4 |= (cpu_feature & CPUID_VME) != 0 ? CR4_VME : 0;
557 #ifdef PMAP_PAE_COMP
558 	ncr4 |= CR4_PAE;
559 #endif
560 	if (ncr4 != 0)
561 		load_cr4(rcr4() | ncr4);
562 
563 	/* Now enable paging */
564 #ifdef PMAP_PAE_COMP
565 	cr3 = (u_int)IdlePDPT;
566 	if ((cpu_feature & CPUID_PAT) == 0)
567 		wbinvd();
568 #else
569 	cr3 = (u_int)IdlePTD;
570 #endif
571 	tramp_idleptd = cr3;
572 	load_cr3(cr3);
573 	load_cr0(rcr0() | CR0_PG);
574 
575 	/*
576 	 * Now running relocated at KERNBASE where the system is
577 	 * linked to run.
578 	 */
579 
580 	/*
581 	 * Remove the lowest part of the double mapping of low memory
582 	 * to get some null pointer checks.
583 	 */
584 	__CONCAT(PMTYPE, remap_lower)(false);
585 
586 	kernel_vm_end = /* 0 + */ NKPT * NBPDR;
587 #ifdef PMAP_PAE_COMP
588 	i386_pmap_VM_NFREEORDER = VM_NFREEORDER_PAE;
589 	i386_pmap_VM_LEVEL_0_ORDER = VM_LEVEL_0_ORDER_PAE;
590 	i386_pmap_PDRSHIFT = PDRSHIFT_PAE;
591 #else
592 	i386_pmap_VM_NFREEORDER = VM_NFREEORDER_NOPAE;
593 	i386_pmap_VM_LEVEL_0_ORDER = VM_LEVEL_0_ORDER_NOPAE;
594 	i386_pmap_PDRSHIFT = PDRSHIFT_NOPAE;
595 #endif
596 }
597 
598 static void
599 __CONCAT(PMTYPE, set_nx)(void)
600 {
601 
602 #ifdef PMAP_PAE_COMP
603 	if ((amd_feature & AMDID_NX) == 0)
604 		return;
605 	pg_nx = PG_NX;
606 	elf32_nxstack = 1;
607 	/* EFER.EFER_NXE is set in initializecpu(). */
608 #endif
609 }
610 
611 /*
612  *	Bootstrap the system enough to run with virtual memory.
613  *
614  *	On the i386 this is called after pmap_cold() created initial
615  *	kernel page table and enabled paging, and just syncs the pmap
616  *	module with what has already been done.
617  */
618 static void
619 __CONCAT(PMTYPE, bootstrap)(vm_paddr_t firstaddr)
620 {
621 	vm_offset_t va;
622 	pt_entry_t *pte, *unused;
623 	struct pcpu *pc;
624 	u_long res;
625 	int i;
626 
627 	res = atop(firstaddr - (vm_paddr_t)KERNLOAD);
628 
629 	/*
630 	 * Add a physical memory segment (vm_phys_seg) corresponding to the
631 	 * preallocated kernel page table pages so that vm_page structures
632 	 * representing these pages will be created.  The vm_page structures
633 	 * are required for promotion of the corresponding kernel virtual
634 	 * addresses to superpage mappings.
635 	 */
636 	vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
637 
638 	/*
639 	 * Initialize the first available kernel virtual address.
640 	 * However, using "firstaddr" may waste a few pages of the
641 	 * kernel virtual address space, because pmap_cold() may not
642 	 * have mapped every physical page that it allocated.
643 	 * Preferably, pmap_cold() would provide a first unused
644 	 * virtual address in addition to "firstaddr".
645 	 */
646 	virtual_avail = (vm_offset_t)firstaddr;
647 	virtual_end = VM_MAX_KERNEL_ADDRESS;
648 
649 	/*
650 	 * Initialize the kernel pmap (which is statically allocated).
651 	 * Count bootstrap data as being resident in case any of this data is
652 	 * later unmapped (using pmap_remove()) and freed.
653 	 */
654 	PMAP_LOCK_INIT(kernel_pmap);
655 	kernel_pmap->pm_pdir = IdlePTD;
656 #ifdef PMAP_PAE_COMP
657 	kernel_pmap->pm_pdpt = IdlePDPT;
658 #endif
659 	CPU_FILL(&kernel_pmap->pm_active);	/* don't allow deactivation */
660 	kernel_pmap->pm_stats.resident_count = res;
661 	TAILQ_INIT(&kernel_pmap->pm_pvchunk);
662 
663  	/*
664 	 * Initialize the global pv list lock.
665 	 */
666 	rw_init(&pvh_global_lock, "pmap pv global");
667 
668 	/*
669 	 * Reserve some special page table entries/VA space for temporary
670 	 * mapping of pages.
671 	 */
672 #define	SYSMAP(c, p, v, n)	\
673 	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
674 
675 	va = virtual_avail;
676 	pte = vtopte(va);
677 
678 	/*
679 	 * Initialize temporary map objects on the current CPU for use
680 	 * during early boot.
681 	 * CMAP1/CMAP2 are used for zeroing and copying pages.
682 	 * CMAP3 is used for the boot-time memory test.
683 	 */
684 	pc = get_pcpu();
685 	mtx_init(&pc->pc_cmap_lock, "SYSMAPS", NULL, MTX_DEF);
686 	SYSMAP(caddr_t, pc->pc_cmap_pte1, pc->pc_cmap_addr1, 1)
687 	SYSMAP(caddr_t, pc->pc_cmap_pte2, pc->pc_cmap_addr2, 1)
688 	SYSMAP(vm_offset_t, pte, pc->pc_qmap_addr, 1)
689 
690 	SYSMAP(caddr_t, CMAP3, CADDR3, 1);
691 
692 	/*
693 	 * Crashdump maps.
694 	 */
695 	SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
696 
697 	/*
698 	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
699 	 */
700 	SYSMAP(caddr_t, unused, ptvmmap, 1)
701 
702 	/*
703 	 * msgbufp is used to map the system message buffer.
704 	 */
705 	SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(msgbufsize)))
706 
707 	/*
708 	 * KPTmap is used by pmap_kextract().
709 	 *
710 	 * KPTmap is first initialized by pmap_cold().  However, that initial
711 	 * KPTmap can only support NKPT page table pages.  Here, a larger
712 	 * KPTmap is created that can support KVA_PAGES page table pages.
713 	 */
714 	SYSMAP(pt_entry_t *, KPTD, KPTmap, KVA_PAGES)
715 
716 	for (i = 0; i < NKPT; i++)
717 		KPTD[i] = (KPTphys + ptoa(i)) | PG_RW | PG_V;
718 
719 	/*
720 	 * PADDR1 and PADDR2 are used by pmap_pte_quick() and pmap_pte(),
721 	 * respectively.
722 	 */
723 	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1)
724 	SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1)
725 	SYSMAP(pt_entry_t *, PMAP3, PADDR3, 1)
726 
727 	mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
728 
729 	virtual_avail = va;
730 
731 	/*
732 	 * Initialize the PAT MSR if present.
733 	 * pmap_init_pat() clears and sets CR4_PGE, which, as a
734 	 * side-effect, invalidates stale PG_G TLB entries that might
735 	 * have been created in our pre-boot environment.  We assume
736 	 * that PAT support implies PGE and in reverse, PGE presence
737 	 * comes with PAT.  Both features were added for Pentium Pro.
738 	 */
739 	pmap_init_pat();
740 }
741 
742 static void
743 pmap_init_reserved_pages(void)
744 {
745 	struct pcpu *pc;
746 	vm_offset_t pages;
747 	int i;
748 
749 #ifdef PMAP_PAE_COMP
750 	if (!pae_mode)
751 		return;
752 #else
753 	if (pae_mode)
754 		return;
755 #endif
756 	CPU_FOREACH(i) {
757 		pc = pcpu_find(i);
758 		mtx_init(&pc->pc_copyout_mlock, "cpmlk", NULL, MTX_DEF |
759 		    MTX_NEW);
760 		pc->pc_copyout_maddr = kva_alloc(ptoa(2));
761 		if (pc->pc_copyout_maddr == 0)
762 			panic("unable to allocate non-sleepable copyout KVA");
763 		sx_init(&pc->pc_copyout_slock, "cpslk");
764 		pc->pc_copyout_saddr = kva_alloc(ptoa(2));
765 		if (pc->pc_copyout_saddr == 0)
766 			panic("unable to allocate sleepable copyout KVA");
767 		pc->pc_pmap_eh_va = kva_alloc(ptoa(1));
768 		if (pc->pc_pmap_eh_va == 0)
769 			panic("unable to allocate pmap_extract_and_hold KVA");
770 		pc->pc_pmap_eh_ptep = (char *)vtopte(pc->pc_pmap_eh_va);
771 
772 		/*
773 		 * Skip if the mappings have already been initialized,
774 		 * i.e. this is the BSP.
775 		 */
776 		if (pc->pc_cmap_addr1 != 0)
777 			continue;
778 
779 		mtx_init(&pc->pc_cmap_lock, "SYSMAPS", NULL, MTX_DEF);
780 		pages = kva_alloc(PAGE_SIZE * 3);
781 		if (pages == 0)
782 			panic("unable to allocate CMAP KVA");
783 		pc->pc_cmap_pte1 = vtopte(pages);
784 		pc->pc_cmap_pte2 = vtopte(pages + PAGE_SIZE);
785 		pc->pc_cmap_addr1 = (caddr_t)pages;
786 		pc->pc_cmap_addr2 = (caddr_t)(pages + PAGE_SIZE);
787 		pc->pc_qmap_addr = pages + ptoa(2);
788 	}
789 }
790 
791 SYSINIT(rpages_init, SI_SUB_CPU, SI_ORDER_ANY, pmap_init_reserved_pages, NULL);
792 
793 /*
794  * Setup the PAT MSR.
795  */
796 static void
797 __CONCAT(PMTYPE, init_pat)(void)
798 {
799 	int pat_table[PAT_INDEX_SIZE];
800 	uint64_t pat_msr;
801 	u_long cr0, cr4;
802 	int i;
803 
804 	/* Set default PAT index table. */
805 	for (i = 0; i < PAT_INDEX_SIZE; i++)
806 		pat_table[i] = -1;
807 	pat_table[PAT_WRITE_BACK] = 0;
808 	pat_table[PAT_WRITE_THROUGH] = 1;
809 	pat_table[PAT_UNCACHEABLE] = 3;
810 	pat_table[PAT_WRITE_COMBINING] = 3;
811 	pat_table[PAT_WRITE_PROTECTED] = 3;
812 	pat_table[PAT_UNCACHED] = 3;
813 
814 	/*
815 	 * Bail if this CPU doesn't implement PAT.
816 	 * We assume that PAT support implies PGE.
817 	 */
818 	if ((cpu_feature & CPUID_PAT) == 0) {
819 		for (i = 0; i < PAT_INDEX_SIZE; i++)
820 			pat_index[i] = pat_table[i];
821 		pat_works = 0;
822 		return;
823 	}
824 
825 	/*
826 	 * Due to some Intel errata, we can only safely use the lower 4
827 	 * PAT entries.
828 	 *
829 	 *   Intel Pentium III Processor Specification Update
830 	 * Errata E.27 (Upper Four PAT Entries Not Usable With Mode B
831 	 * or Mode C Paging)
832 	 *
833 	 *   Intel Pentium IV  Processor Specification Update
834 	 * Errata N46 (PAT Index MSB May Be Calculated Incorrectly)
835 	 */
836 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
837 	    !(CPUID_TO_FAMILY(cpu_id) == 6 && CPUID_TO_MODEL(cpu_id) >= 0xe))
838 		pat_works = 0;
839 
840 	/* Initialize default PAT entries. */
841 	pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
842 	    PAT_VALUE(1, PAT_WRITE_THROUGH) |
843 	    PAT_VALUE(2, PAT_UNCACHED) |
844 	    PAT_VALUE(3, PAT_UNCACHEABLE) |
845 	    PAT_VALUE(4, PAT_WRITE_BACK) |
846 	    PAT_VALUE(5, PAT_WRITE_THROUGH) |
847 	    PAT_VALUE(6, PAT_UNCACHED) |
848 	    PAT_VALUE(7, PAT_UNCACHEABLE);
849 
850 	if (pat_works) {
851 		/*
852 		 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
853 		 * Program 5 and 6 as WP and WC.
854 		 * Leave 4 and 7 as WB and UC.
855 		 */
856 		pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
857 		pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
858 		    PAT_VALUE(6, PAT_WRITE_COMBINING);
859 		pat_table[PAT_UNCACHED] = 2;
860 		pat_table[PAT_WRITE_PROTECTED] = 5;
861 		pat_table[PAT_WRITE_COMBINING] = 6;
862 	} else {
863 		/*
864 		 * Just replace PAT Index 2 with WC instead of UC-.
865 		 */
866 		pat_msr &= ~PAT_MASK(2);
867 		pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
868 		pat_table[PAT_WRITE_COMBINING] = 2;
869 	}
870 
871 	/* Disable PGE. */
872 	cr4 = rcr4();
873 	load_cr4(cr4 & ~CR4_PGE);
874 
875 	/* Disable caches (CD = 1, NW = 0). */
876 	cr0 = rcr0();
877 	load_cr0((cr0 & ~CR0_NW) | CR0_CD);
878 
879 	/* Flushes caches and TLBs. */
880 	wbinvd();
881 	invltlb();
882 
883 	/* Update PAT and index table. */
884 	wrmsr(MSR_PAT, pat_msr);
885 	for (i = 0; i < PAT_INDEX_SIZE; i++)
886 		pat_index[i] = pat_table[i];
887 
888 	/* Flush caches and TLBs again. */
889 	wbinvd();
890 	invltlb();
891 
892 	/* Restore caches and PGE. */
893 	load_cr0(cr0);
894 	load_cr4(cr4);
895 }
896 
897 #ifdef PMAP_PAE_COMP
898 static void *
899 pmap_pdpt_allocf(uma_zone_t zone, vm_size_t bytes, int domain, uint8_t *flags,
900     int wait)
901 {
902 
903 	/* Inform UMA that this allocator uses kernel_map/object. */
904 	*flags = UMA_SLAB_KERNEL;
905 	return ((void *)kmem_alloc_contig_domainset(DOMAINSET_FIXED(domain),
906 	    bytes, wait, 0x0ULL, 0xffffffffULL, 1, 0, VM_MEMATTR_DEFAULT));
907 }
908 #endif
909 
910 /*
911  * Abuse the pte nodes for unmapped kva to thread a kva freelist through.
912  * Requirements:
913  *  - Must deal with pages in order to ensure that none of the PG_* bits
914  *    are ever set, PG_V in particular.
915  *  - Assumes we can write to ptes without pte_store() atomic ops, even
916  *    on PAE systems.  This should be ok.
917  *  - Assumes nothing will ever test these addresses for 0 to indicate
918  *    no mapping instead of correctly checking PG_V.
919  *  - Assumes a vm_offset_t will fit in a pte (true for i386).
920  * Because PG_V is never set, there can be no mappings to invalidate.
921  */
922 static vm_offset_t
923 pmap_ptelist_alloc(vm_offset_t *head)
924 {
925 	pt_entry_t *pte;
926 	vm_offset_t va;
927 
928 	va = *head;
929 	if (va == 0)
930 		panic("pmap_ptelist_alloc: exhausted ptelist KVA");
931 	pte = vtopte(va);
932 	*head = *pte;
933 	if (*head & PG_V)
934 		panic("pmap_ptelist_alloc: va with PG_V set!");
935 	*pte = 0;
936 	return (va);
937 }
938 
939 static void
940 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
941 {
942 	pt_entry_t *pte;
943 
944 	if (va & PG_V)
945 		panic("pmap_ptelist_free: freeing va with PG_V set!");
946 	pte = vtopte(va);
947 	*pte = *head;		/* virtual! PG_V is 0 though */
948 	*head = va;
949 }
950 
951 static void
952 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
953 {
954 	int i;
955 	vm_offset_t va;
956 
957 	*head = 0;
958 	for (i = npages - 1; i >= 0; i--) {
959 		va = (vm_offset_t)base + i * PAGE_SIZE;
960 		pmap_ptelist_free(head, va);
961 	}
962 }
963 
964 /*
965  *	Initialize the pmap module.
966  *	Called by vm_init, to initialize any structures that the pmap
967  *	system needs to map virtual memory.
968  */
969 static void
970 __CONCAT(PMTYPE, init)(void)
971 {
972 	struct pmap_preinit_mapping *ppim;
973 	vm_page_t mpte;
974 	vm_size_t s;
975 	int i, pv_npg;
976 
977 	/*
978 	 * Initialize the vm page array entries for the kernel pmap's
979 	 * page table pages.
980 	 */
981 	PMAP_LOCK(kernel_pmap);
982 	for (i = 0; i < NKPT; i++) {
983 		mpte = PHYS_TO_VM_PAGE(KPTphys + ptoa(i));
984 		KASSERT(mpte >= vm_page_array &&
985 		    mpte < &vm_page_array[vm_page_array_size],
986 		    ("pmap_init: page table page is out of range"));
987 		mpte->pindex = i + KPTDI;
988 		mpte->phys_addr = KPTphys + ptoa(i);
989 		mpte->ref_count = 1;
990 
991 		/*
992 		 * Collect the page table pages that were replaced by a 2/4MB
993 		 * page.  They are filled with equivalent 4KB page mappings.
994 		 */
995 		if (pseflag != 0 &&
996 		    KERNBASE <= i << PDRSHIFT && i << PDRSHIFT < KERNend &&
997 		    pmap_insert_pt_page(kernel_pmap, mpte, true))
998 			panic("pmap_init: pmap_insert_pt_page failed");
999 	}
1000 	PMAP_UNLOCK(kernel_pmap);
1001 	vm_wire_add(NKPT);
1002 
1003 	/*
1004 	 * Initialize the address space (zone) for the pv entries.  Set a
1005 	 * high water mark so that the system can recover from excessive
1006 	 * numbers of pv entries.
1007 	 */
1008 	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1009 	pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
1010 	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1011 	pv_entry_max = roundup(pv_entry_max, _NPCPV);
1012 	pv_entry_high_water = 9 * (pv_entry_max / 10);
1013 
1014 	/*
1015 	 * If the kernel is running on a virtual machine, then it must assume
1016 	 * that MCA is enabled by the hypervisor.  Moreover, the kernel must
1017 	 * be prepared for the hypervisor changing the vendor and family that
1018 	 * are reported by CPUID.  Consequently, the workaround for AMD Family
1019 	 * 10h Erratum 383 is enabled if the processor's feature set does not
1020 	 * include at least one feature that is only supported by older Intel
1021 	 * or newer AMD processors.
1022 	 */
1023 	if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1024 	    (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1025 	    CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1026 	    AMDID2_FMA4)) == 0)
1027 		workaround_erratum383 = 1;
1028 
1029 	/*
1030 	 * Are large page mappings supported and enabled?
1031 	 */
1032 	TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1033 	if (pseflag == 0)
1034 		pg_ps_enabled = 0;
1035 	else if (pg_ps_enabled) {
1036 		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1037 		    ("pmap_init: can't assign to pagesizes[1]"));
1038 		pagesizes[1] = NBPDR;
1039 	}
1040 
1041 	/*
1042 	 * Calculate the size of the pv head table for superpages.
1043 	 * Handle the possibility that "vm_phys_segs[...].end" is zero.
1044 	 */
1045 	pv_npg = trunc_4mpage(vm_phys_segs[vm_phys_nsegs - 1].end -
1046 	    PAGE_SIZE) / NBPDR + 1;
1047 
1048 	/*
1049 	 * Allocate memory for the pv head table for superpages.
1050 	 */
1051 	s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1052 	s = round_page(s);
1053 	pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
1054 	for (i = 0; i < pv_npg; i++)
1055 		TAILQ_INIT(&pv_table[i].pv_list);
1056 
1057 	pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
1058 	pv_chunkbase = (struct pv_chunk *)kva_alloc(PAGE_SIZE * pv_maxchunks);
1059 	if (pv_chunkbase == NULL)
1060 		panic("pmap_init: not enough kvm for pv chunks");
1061 	pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
1062 #ifdef PMAP_PAE_COMP
1063 	pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
1064 	    NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
1065 	    UMA_ZONE_CONTIG | UMA_ZONE_VM | UMA_ZONE_NOFREE);
1066 	uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
1067 #endif
1068 
1069 	pmap_initialized = 1;
1070 	pmap_init_trm();
1071 
1072 	if (!bootverbose)
1073 		return;
1074 	for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1075 		ppim = pmap_preinit_mapping + i;
1076 		if (ppim->va == 0)
1077 			continue;
1078 		printf("PPIM %u: PA=%#jx, VA=%#x, size=%#x, mode=%#x\n", i,
1079 		    (uintmax_t)ppim->pa, ppim->va, ppim->sz, ppim->mode);
1080 	}
1081 
1082 }
1083 
1084 extern u_long pmap_pde_demotions;
1085 extern u_long pmap_pde_mappings;
1086 extern u_long pmap_pde_p_failures;
1087 extern u_long pmap_pde_promotions;
1088 
1089 /***************************************************
1090  * Low level helper routines.....
1091  ***************************************************/
1092 
1093 static boolean_t
1094 __CONCAT(PMTYPE, is_valid_memattr)(pmap_t pmap __unused, vm_memattr_t mode)
1095 {
1096 
1097 	return (mode >= 0 && mode < PAT_INDEX_SIZE &&
1098 	    pat_index[(int)mode] >= 0);
1099 }
1100 
1101 /*
1102  * Determine the appropriate bits to set in a PTE or PDE for a specified
1103  * caching mode.
1104  */
1105 static int
1106 __CONCAT(PMTYPE, cache_bits)(pmap_t pmap, int mode, boolean_t is_pde)
1107 {
1108 	int cache_bits, pat_flag, pat_idx;
1109 
1110 	if (!pmap_is_valid_memattr(pmap, mode))
1111 		panic("Unknown caching mode %d\n", mode);
1112 
1113 	/* The PAT bit is different for PTE's and PDE's. */
1114 	pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
1115 
1116 	/* Map the caching mode to a PAT index. */
1117 	pat_idx = pat_index[mode];
1118 
1119 	/* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1120 	cache_bits = 0;
1121 	if (pat_idx & 0x4)
1122 		cache_bits |= pat_flag;
1123 	if (pat_idx & 0x2)
1124 		cache_bits |= PG_NC_PCD;
1125 	if (pat_idx & 0x1)
1126 		cache_bits |= PG_NC_PWT;
1127 	return (cache_bits);
1128 }
1129 
1130 static int
1131 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
1132 {
1133 	int pat_flag, pat_idx;
1134 
1135 	if ((cpu_feature & CPUID_PAT) == 0)
1136 		return (0);
1137 
1138 	pat_idx = 0;
1139 	/* The PAT bit is different for PTE's and PDE's. */
1140 	pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
1141 
1142 	if ((pte & pat_flag) != 0)
1143 		pat_idx |= 0x4;
1144 	if ((pte & PG_NC_PCD) != 0)
1145 		pat_idx |= 0x2;
1146 	if ((pte & PG_NC_PWT) != 0)
1147 		pat_idx |= 0x1;
1148 
1149 	/* See pmap_init_pat(). */
1150 	if (pat_works) {
1151 		if (pat_idx == 4)
1152 			pat_idx = 0;
1153 		if (pat_idx == 7)
1154 			pat_idx = 3;
1155 	} else {
1156 		/* XXXKIB */
1157 	}
1158 
1159 	return (pat_idx);
1160 }
1161 
1162 static bool
1163 __CONCAT(PMTYPE, ps_enabled)(pmap_t pmap __unused)
1164 {
1165 
1166 	return (pg_ps_enabled);
1167 }
1168 
1169 /*
1170  * The caller is responsible for maintaining TLB consistency.
1171  */
1172 static void
1173 pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde)
1174 {
1175 	pd_entry_t *pde;
1176 
1177 	pde = pmap_pde(kernel_pmap, va);
1178 	pde_store(pde, newpde);
1179 }
1180 
1181 /*
1182  * After changing the page size for the specified virtual address in the page
1183  * table, flush the corresponding entries from the processor's TLB.  Only the
1184  * calling processor's TLB is affected.
1185  *
1186  * The calling thread must be pinned to a processor.
1187  */
1188 static void
1189 pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde)
1190 {
1191 
1192 	if ((newpde & PG_PS) == 0)
1193 		/* Demotion: flush a specific 2MB page mapping. */
1194 		invlpg(va);
1195 	else /* if ((newpde & PG_G) == 0) */
1196 		/*
1197 		 * Promotion: flush every 4KB page mapping from the TLB
1198 		 * because there are too many to flush individually.
1199 		 */
1200 		invltlb();
1201 }
1202 
1203 #ifdef SMP
1204 
1205 static void
1206 pmap_curcpu_cb_dummy(pmap_t pmap __unused, vm_offset_t addr1 __unused,
1207     vm_offset_t addr2 __unused)
1208 {
1209 }
1210 
1211 /*
1212  * For SMP, these functions have to use the IPI mechanism for coherence.
1213  *
1214  * N.B.: Before calling any of the following TLB invalidation functions,
1215  * the calling processor must ensure that all stores updating a non-
1216  * kernel page table are globally performed.  Otherwise, another
1217  * processor could cache an old, pre-update entry without being
1218  * invalidated.  This can happen one of two ways: (1) The pmap becomes
1219  * active on another processor after its pm_active field is checked by
1220  * one of the following functions but before a store updating the page
1221  * table is globally performed. (2) The pmap becomes active on another
1222  * processor before its pm_active field is checked but due to
1223  * speculative loads one of the following functions stills reads the
1224  * pmap as inactive on the other processor.
1225  *
1226  * The kernel page table is exempt because its pm_active field is
1227  * immutable.  The kernel page table is always active on every
1228  * processor.
1229  */
1230 static void
1231 pmap_invalidate_page_int(pmap_t pmap, vm_offset_t va)
1232 {
1233 	cpuset_t *mask, other_cpus;
1234 	u_int cpuid;
1235 
1236 	sched_pin();
1237 	if (pmap == kernel_pmap) {
1238 		invlpg(va);
1239 		mask = &all_cpus;
1240 	} else if (!CPU_CMP(&pmap->pm_active, &all_cpus)) {
1241 		mask = &all_cpus;
1242 	} else {
1243 		cpuid = PCPU_GET(cpuid);
1244 		other_cpus = all_cpus;
1245 		CPU_CLR(cpuid, &other_cpus);
1246 		CPU_AND(&other_cpus, &pmap->pm_active);
1247 		mask = &other_cpus;
1248 	}
1249 	smp_masked_invlpg(*mask, va, pmap, pmap_curcpu_cb_dummy);
1250 	sched_unpin();
1251 }
1252 
1253 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1254 #define	PMAP_INVLPG_THRESHOLD	(4 * 1024 * PAGE_SIZE)
1255 
1256 static void
1257 pmap_invalidate_range_int(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1258 {
1259 	cpuset_t *mask, other_cpus;
1260 	vm_offset_t addr;
1261 	u_int cpuid;
1262 
1263 	if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1264 		pmap_invalidate_all_int(pmap);
1265 		return;
1266 	}
1267 
1268 	sched_pin();
1269 	if (pmap == kernel_pmap) {
1270 		for (addr = sva; addr < eva; addr += PAGE_SIZE)
1271 			invlpg(addr);
1272 		mask = &all_cpus;
1273 	} else  if (!CPU_CMP(&pmap->pm_active, &all_cpus)) {
1274 		mask = &all_cpus;
1275 	} else {
1276 		cpuid = PCPU_GET(cpuid);
1277 		other_cpus = all_cpus;
1278 		CPU_CLR(cpuid, &other_cpus);
1279 		CPU_AND(&other_cpus, &pmap->pm_active);
1280 		mask = &other_cpus;
1281 	}
1282 	smp_masked_invlpg_range(*mask, sva, eva, pmap, pmap_curcpu_cb_dummy);
1283 	sched_unpin();
1284 }
1285 
1286 static void
1287 pmap_invalidate_all_int(pmap_t pmap)
1288 {
1289 	cpuset_t *mask, other_cpus;
1290 	u_int cpuid;
1291 
1292 	sched_pin();
1293 	if (pmap == kernel_pmap) {
1294 		invltlb();
1295 		mask = &all_cpus;
1296 	} else if (!CPU_CMP(&pmap->pm_active, &all_cpus)) {
1297 		mask = &all_cpus;
1298 	} else {
1299 		cpuid = PCPU_GET(cpuid);
1300 		other_cpus = all_cpus;
1301 		CPU_CLR(cpuid, &other_cpus);
1302 		CPU_AND(&other_cpus, &pmap->pm_active);
1303 		mask = &other_cpus;
1304 	}
1305 	smp_masked_invltlb(*mask, pmap, pmap_curcpu_cb_dummy);
1306 	sched_unpin();
1307 }
1308 
1309 static void
1310 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused,
1311     vm_offset_t addr1 __unused, vm_offset_t addr2 __unused)
1312 {
1313 	wbinvd();
1314 }
1315 
1316 static void
1317 __CONCAT(PMTYPE, invalidate_cache)(void)
1318 {
1319 	smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
1320 }
1321 
1322 struct pde_action {
1323 	cpuset_t invalidate;	/* processors that invalidate their TLB */
1324 	vm_offset_t va;
1325 	pd_entry_t *pde;
1326 	pd_entry_t newpde;
1327 	u_int store;		/* processor that updates the PDE */
1328 };
1329 
1330 static void
1331 pmap_update_pde_kernel(void *arg)
1332 {
1333 	struct pde_action *act = arg;
1334 	pd_entry_t *pde;
1335 
1336 	if (act->store == PCPU_GET(cpuid)) {
1337 		pde = pmap_pde(kernel_pmap, act->va);
1338 		pde_store(pde, act->newpde);
1339 	}
1340 }
1341 
1342 static void
1343 pmap_update_pde_user(void *arg)
1344 {
1345 	struct pde_action *act = arg;
1346 
1347 	if (act->store == PCPU_GET(cpuid))
1348 		pde_store(act->pde, act->newpde);
1349 }
1350 
1351 static void
1352 pmap_update_pde_teardown(void *arg)
1353 {
1354 	struct pde_action *act = arg;
1355 
1356 	if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1357 		pmap_update_pde_invalidate(act->va, act->newpde);
1358 }
1359 
1360 /*
1361  * Change the page size for the specified virtual address in a way that
1362  * prevents any possibility of the TLB ever having two entries that map the
1363  * same virtual address using different page sizes.  This is the recommended
1364  * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
1365  * machine check exception for a TLB state that is improperly diagnosed as a
1366  * hardware error.
1367  */
1368 static void
1369 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1370 {
1371 	struct pde_action act;
1372 	cpuset_t active, other_cpus;
1373 	u_int cpuid;
1374 
1375 	sched_pin();
1376 	cpuid = PCPU_GET(cpuid);
1377 	other_cpus = all_cpus;
1378 	CPU_CLR(cpuid, &other_cpus);
1379 	if (pmap == kernel_pmap)
1380 		active = all_cpus;
1381 	else
1382 		active = pmap->pm_active;
1383 	if (CPU_OVERLAP(&active, &other_cpus)) {
1384 		act.store = cpuid;
1385 		act.invalidate = active;
1386 		act.va = va;
1387 		act.pde = pde;
1388 		act.newpde = newpde;
1389 		CPU_SET(cpuid, &active);
1390 		smp_rendezvous_cpus(active,
1391 		    smp_no_rendezvous_barrier, pmap == kernel_pmap ?
1392 		    pmap_update_pde_kernel : pmap_update_pde_user,
1393 		    pmap_update_pde_teardown, &act);
1394 	} else {
1395 		if (pmap == kernel_pmap)
1396 			pmap_kenter_pde(va, newpde);
1397 		else
1398 			pde_store(pde, newpde);
1399 		if (CPU_ISSET(cpuid, &active))
1400 			pmap_update_pde_invalidate(va, newpde);
1401 	}
1402 	sched_unpin();
1403 }
1404 #else /* !SMP */
1405 /*
1406  * Normal, non-SMP, 486+ invalidation functions.
1407  * We inline these within pmap.c for speed.
1408  */
1409 static void
1410 pmap_invalidate_page_int(pmap_t pmap, vm_offset_t va)
1411 {
1412 
1413 	if (pmap == kernel_pmap)
1414 		invlpg(va);
1415 }
1416 
1417 static void
1418 pmap_invalidate_range_int(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1419 {
1420 	vm_offset_t addr;
1421 
1422 	if (pmap == kernel_pmap)
1423 		for (addr = sva; addr < eva; addr += PAGE_SIZE)
1424 			invlpg(addr);
1425 }
1426 
1427 static void
1428 pmap_invalidate_all_int(pmap_t pmap)
1429 {
1430 
1431 	if (pmap == kernel_pmap)
1432 		invltlb();
1433 }
1434 
1435 static void
1436 __CONCAT(PMTYPE, invalidate_cache)(void)
1437 {
1438 
1439 	wbinvd();
1440 }
1441 
1442 static void
1443 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1444 {
1445 
1446 	if (pmap == kernel_pmap)
1447 		pmap_kenter_pde(va, newpde);
1448 	else
1449 		pde_store(pde, newpde);
1450 	if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1451 		pmap_update_pde_invalidate(va, newpde);
1452 }
1453 #endif /* !SMP */
1454 
1455 static void
1456 __CONCAT(PMTYPE, invalidate_page)(pmap_t pmap, vm_offset_t va)
1457 {
1458 
1459 	pmap_invalidate_page_int(pmap, va);
1460 }
1461 
1462 static void
1463 __CONCAT(PMTYPE, invalidate_range)(pmap_t pmap, vm_offset_t sva,
1464     vm_offset_t eva)
1465 {
1466 
1467 	pmap_invalidate_range_int(pmap, sva, eva);
1468 }
1469 
1470 static void
1471 __CONCAT(PMTYPE, invalidate_all)(pmap_t pmap)
1472 {
1473 
1474 	pmap_invalidate_all_int(pmap);
1475 }
1476 
1477 static void
1478 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1479 {
1480 
1481 	/*
1482 	 * When the PDE has PG_PROMOTED set, the 2- or 4MB page mapping was
1483 	 * created by a promotion that did not invalidate the 512 or 1024 4KB
1484 	 * page mappings that might exist in the TLB.  Consequently, at this
1485 	 * point, the TLB may hold both 4KB and 2- or 4MB page mappings for
1486 	 * the address range [va, va + NBPDR).  Therefore, the entire range
1487 	 * must be invalidated here.  In contrast, when PG_PROMOTED is clear,
1488 	 * the TLB will not hold any 4KB page mappings for the address range
1489 	 * [va, va + NBPDR), and so a single INVLPG suffices to invalidate the
1490 	 * 2- or 4MB page mapping from the TLB.
1491 	 */
1492 	if ((pde & PG_PROMOTED) != 0)
1493 		pmap_invalidate_range_int(pmap, va, va + NBPDR - 1);
1494 	else
1495 		pmap_invalidate_page_int(pmap, va);
1496 }
1497 
1498 /*
1499  * Are we current address space or kernel?
1500  */
1501 static __inline int
1502 pmap_is_current(pmap_t pmap)
1503 {
1504 
1505 	return (pmap == kernel_pmap);
1506 }
1507 
1508 /*
1509  * If the given pmap is not the current or kernel pmap, the returned pte must
1510  * be released by passing it to pmap_pte_release().
1511  */
1512 static pt_entry_t *
1513 __CONCAT(PMTYPE, pte)(pmap_t pmap, vm_offset_t va)
1514 {
1515 	pd_entry_t newpf;
1516 	pd_entry_t *pde;
1517 
1518 	pde = pmap_pde(pmap, va);
1519 	if (*pde & PG_PS)
1520 		return (pde);
1521 	if (*pde != 0) {
1522 		/* are we current address space or kernel? */
1523 		if (pmap_is_current(pmap))
1524 			return (vtopte(va));
1525 		mtx_lock(&PMAP2mutex);
1526 		newpf = *pde & PG_FRAME;
1527 		if ((*PMAP2 & PG_FRAME) != newpf) {
1528 			*PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
1529 			pmap_invalidate_page_int(kernel_pmap,
1530 			    (vm_offset_t)PADDR2);
1531 		}
1532 		return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
1533 	}
1534 	return (NULL);
1535 }
1536 
1537 /*
1538  * Releases a pte that was obtained from pmap_pte().  Be prepared for the pte
1539  * being NULL.
1540  */
1541 static __inline void
1542 pmap_pte_release(pt_entry_t *pte)
1543 {
1544 
1545 	if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2)
1546 		mtx_unlock(&PMAP2mutex);
1547 }
1548 
1549 /*
1550  * NB:  The sequence of updating a page table followed by accesses to the
1551  * corresponding pages is subject to the situation described in the "AMD64
1552  * Architecture Programmer's Manual Volume 2: System Programming" rev. 3.23,
1553  * "7.3.1 Special Coherency Considerations".  Therefore, issuing the INVLPG
1554  * right after modifying the PTE bits is crucial.
1555  */
1556 static __inline void
1557 invlcaddr(void *caddr)
1558 {
1559 
1560 	invlpg((u_int)caddr);
1561 }
1562 
1563 /*
1564  * Super fast pmap_pte routine best used when scanning
1565  * the pv lists.  This eliminates many coarse-grained
1566  * invltlb calls.  Note that many of the pv list
1567  * scans are across different pmaps.  It is very wasteful
1568  * to do an entire invltlb for checking a single mapping.
1569  *
1570  * If the given pmap is not the current pmap, pvh_global_lock
1571  * must be held and curthread pinned to a CPU.
1572  */
1573 static pt_entry_t *
1574 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
1575 {
1576 	pd_entry_t newpf;
1577 	pd_entry_t *pde;
1578 
1579 	pde = pmap_pde(pmap, va);
1580 	if (*pde & PG_PS)
1581 		return (pde);
1582 	if (*pde != 0) {
1583 		/* are we current address space or kernel? */
1584 		if (pmap_is_current(pmap))
1585 			return (vtopte(va));
1586 		rw_assert(&pvh_global_lock, RA_WLOCKED);
1587 		KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1588 		newpf = *pde & PG_FRAME;
1589 		if ((*PMAP1 & PG_FRAME) != newpf) {
1590 			*PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
1591 #ifdef SMP
1592 			PMAP1cpu = PCPU_GET(cpuid);
1593 #endif
1594 			invlcaddr(PADDR1);
1595 			PMAP1changed++;
1596 		} else
1597 #ifdef SMP
1598 		if (PMAP1cpu != PCPU_GET(cpuid)) {
1599 			PMAP1cpu = PCPU_GET(cpuid);
1600 			invlcaddr(PADDR1);
1601 			PMAP1changedcpu++;
1602 		} else
1603 #endif
1604 			PMAP1unchanged++;
1605 		return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
1606 	}
1607 	return (0);
1608 }
1609 
1610 static pt_entry_t *
1611 pmap_pte_quick3(pmap_t pmap, vm_offset_t va)
1612 {
1613 	pd_entry_t newpf;
1614 	pd_entry_t *pde;
1615 
1616 	pde = pmap_pde(pmap, va);
1617 	if (*pde & PG_PS)
1618 		return (pde);
1619 	if (*pde != 0) {
1620 		rw_assert(&pvh_global_lock, RA_WLOCKED);
1621 		KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1622 		newpf = *pde & PG_FRAME;
1623 		if ((*PMAP3 & PG_FRAME) != newpf) {
1624 			*PMAP3 = newpf | PG_RW | PG_V | PG_A | PG_M;
1625 #ifdef SMP
1626 			PMAP3cpu = PCPU_GET(cpuid);
1627 #endif
1628 			invlcaddr(PADDR3);
1629 			PMAP1changed++;
1630 		} else
1631 #ifdef SMP
1632 		if (PMAP3cpu != PCPU_GET(cpuid)) {
1633 			PMAP3cpu = PCPU_GET(cpuid);
1634 			invlcaddr(PADDR3);
1635 			PMAP1changedcpu++;
1636 		} else
1637 #endif
1638 			PMAP1unchanged++;
1639 		return (PADDR3 + (i386_btop(va) & (NPTEPG - 1)));
1640 	}
1641 	return (0);
1642 }
1643 
1644 static pt_entry_t
1645 pmap_pte_ufast(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1646 {
1647 	pt_entry_t *eh_ptep, pte, *ptep;
1648 
1649 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1650 	pde &= PG_FRAME;
1651 	critical_enter();
1652 	eh_ptep = (pt_entry_t *)PCPU_GET(pmap_eh_ptep);
1653 	if ((*eh_ptep & PG_FRAME) != pde) {
1654 		*eh_ptep = pde | PG_RW | PG_V | PG_A | PG_M;
1655 		invlcaddr((void *)PCPU_GET(pmap_eh_va));
1656 	}
1657 	ptep = (pt_entry_t *)PCPU_GET(pmap_eh_va) + (i386_btop(va) &
1658 	    (NPTEPG - 1));
1659 	pte = *ptep;
1660 	critical_exit();
1661 	return (pte);
1662 }
1663 
1664 /*
1665  * Extract from the kernel page table the physical address that is mapped by
1666  * the given virtual address "va".
1667  *
1668  * This function may be used before pmap_bootstrap() is called.
1669  */
1670 static vm_paddr_t
1671 __CONCAT(PMTYPE, kextract)(vm_offset_t va)
1672 {
1673 	vm_paddr_t pa;
1674 
1675 	if ((pa = pte_load(&PTD[va >> PDRSHIFT])) & PG_PS) {
1676 		pa = (pa & PG_PS_FRAME) | (va & PDRMASK);
1677 	} else {
1678 		/*
1679 		 * Beware of a concurrent promotion that changes the PDE at
1680 		 * this point!  For example, vtopte() must not be used to
1681 		 * access the PTE because it would use the new PDE.  It is,
1682 		 * however, safe to use the old PDE because the page table
1683 		 * page is preserved by the promotion.
1684 		 */
1685 		pa = KPTmap[i386_btop(va)];
1686 		pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1687 	}
1688 	return (pa);
1689 }
1690 
1691 /*
1692  *	Routine:	pmap_extract
1693  *	Function:
1694  *		Extract the physical page address associated
1695  *		with the given map/virtual_address pair.
1696  */
1697 static vm_paddr_t
1698 __CONCAT(PMTYPE, extract)(pmap_t pmap, vm_offset_t va)
1699 {
1700 	vm_paddr_t rtval;
1701 	pt_entry_t pte;
1702 	pd_entry_t pde;
1703 
1704 	rtval = 0;
1705 	PMAP_LOCK(pmap);
1706 	pde = pmap->pm_pdir[va >> PDRSHIFT];
1707 	if (pde != 0) {
1708 		if ((pde & PG_PS) != 0)
1709 			rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
1710 		else {
1711 			pte = pmap_pte_ufast(pmap, va, pde);
1712 			rtval = (pte & PG_FRAME) | (va & PAGE_MASK);
1713 		}
1714 	}
1715 	PMAP_UNLOCK(pmap);
1716 	return (rtval);
1717 }
1718 
1719 /*
1720  *	Routine:	pmap_extract_and_hold
1721  *	Function:
1722  *		Atomically extract and hold the physical page
1723  *		with the given pmap and virtual address pair
1724  *		if that mapping permits the given protection.
1725  */
1726 static vm_page_t
1727 __CONCAT(PMTYPE, extract_and_hold)(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1728 {
1729 	pd_entry_t pde;
1730 	pt_entry_t pte;
1731 	vm_page_t m;
1732 
1733 	m = NULL;
1734 	PMAP_LOCK(pmap);
1735 	pde = *pmap_pde(pmap, va);
1736 	if (pde != 0) {
1737 		if (pde & PG_PS) {
1738 			if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0)
1739 				m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
1740 				    (va & PDRMASK));
1741 		} else {
1742 			pte = pmap_pte_ufast(pmap, va, pde);
1743 			if (pte != 0 &&
1744 			    ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0))
1745 				m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
1746 		}
1747 		if (m != NULL && !vm_page_wire_mapped(m))
1748 			m = NULL;
1749 	}
1750 	PMAP_UNLOCK(pmap);
1751 	return (m);
1752 }
1753 
1754 /***************************************************
1755  * Low level mapping routines.....
1756  ***************************************************/
1757 
1758 /*
1759  * Add a wired page to the kva.
1760  * Note: not SMP coherent.
1761  *
1762  * This function may be used before pmap_bootstrap() is called.
1763  */
1764 static void
1765 __CONCAT(PMTYPE, kenter)(vm_offset_t va, vm_paddr_t pa)
1766 {
1767 	pt_entry_t *pte;
1768 
1769 	pte = vtopte(va);
1770 	pte_store(pte, pa | PG_RW | PG_V);
1771 }
1772 
1773 static __inline void
1774 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
1775 {
1776 	pt_entry_t *pte;
1777 
1778 	pte = vtopte(va);
1779 	pte_store(pte, pa | PG_RW | PG_V | pmap_cache_bits(kernel_pmap,
1780 	    mode, 0));
1781 }
1782 
1783 /*
1784  * Remove a page from the kernel pagetables.
1785  * Note: not SMP coherent.
1786  *
1787  * This function may be used before pmap_bootstrap() is called.
1788  */
1789 static void
1790 __CONCAT(PMTYPE, kremove)(vm_offset_t va)
1791 {
1792 	pt_entry_t *pte;
1793 
1794 	pte = vtopte(va);
1795 	pte_clear(pte);
1796 }
1797 
1798 /*
1799  *	Used to map a range of physical addresses into kernel
1800  *	virtual address space.
1801  *
1802  *	The value passed in '*virt' is a suggested virtual address for
1803  *	the mapping. Architectures which can support a direct-mapped
1804  *	physical to virtual region can return the appropriate address
1805  *	within that region, leaving '*virt' unchanged. Other
1806  *	architectures should map the pages starting at '*virt' and
1807  *	update '*virt' with the first usable address after the mapped
1808  *	region.
1809  */
1810 static vm_offset_t
1811 __CONCAT(PMTYPE, map)(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end,
1812     int prot)
1813 {
1814 	vm_offset_t va, sva;
1815 	vm_paddr_t superpage_offset;
1816 	pd_entry_t newpde;
1817 
1818 	va = *virt;
1819 	/*
1820 	 * Does the physical address range's size and alignment permit at
1821 	 * least one superpage mapping to be created?
1822 	 */
1823 	superpage_offset = start & PDRMASK;
1824 	if ((end - start) - ((NBPDR - superpage_offset) & PDRMASK) >= NBPDR) {
1825 		/*
1826 		 * Increase the starting virtual address so that its alignment
1827 		 * does not preclude the use of superpage mappings.
1828 		 */
1829 		if ((va & PDRMASK) < superpage_offset)
1830 			va = (va & ~PDRMASK) + superpage_offset;
1831 		else if ((va & PDRMASK) > superpage_offset)
1832 			va = ((va + PDRMASK) & ~PDRMASK) + superpage_offset;
1833 	}
1834 	sva = va;
1835 	while (start < end) {
1836 		if ((start & PDRMASK) == 0 && end - start >= NBPDR &&
1837 		    pseflag != 0) {
1838 			KASSERT((va & PDRMASK) == 0,
1839 			    ("pmap_map: misaligned va %#x", va));
1840 			newpde = start | PG_PS | PG_RW | PG_V;
1841 			pmap_kenter_pde(va, newpde);
1842 			va += NBPDR;
1843 			start += NBPDR;
1844 		} else {
1845 			pmap_kenter(va, start);
1846 			va += PAGE_SIZE;
1847 			start += PAGE_SIZE;
1848 		}
1849 	}
1850 	pmap_invalidate_range_int(kernel_pmap, sva, va);
1851 	*virt = va;
1852 	return (sva);
1853 }
1854 
1855 /*
1856  * Add a list of wired pages to the kva
1857  * this routine is only used for temporary
1858  * kernel mappings that do not need to have
1859  * page modification or references recorded.
1860  * Note that old mappings are simply written
1861  * over.  The page *must* be wired.
1862  * Note: SMP coherent.  Uses a ranged shootdown IPI.
1863  */
1864 static void
1865 __CONCAT(PMTYPE, qenter)(vm_offset_t sva, vm_page_t *ma, int count)
1866 {
1867 	pt_entry_t *endpte, oldpte, pa, *pte;
1868 	vm_page_t m;
1869 
1870 	oldpte = 0;
1871 	pte = vtopte(sva);
1872 	endpte = pte + count;
1873 	while (pte < endpte) {
1874 		m = *ma++;
1875 		pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(kernel_pmap,
1876 		    m->md.pat_mode, 0);
1877 		if ((*pte & (PG_FRAME | PG_PTE_CACHE)) != pa) {
1878 			oldpte |= *pte;
1879 			pte_store(pte, pa | pg_nx | PG_RW | PG_V);
1880 		}
1881 		pte++;
1882 	}
1883 	if (__predict_false((oldpte & PG_V) != 0))
1884 		pmap_invalidate_range_int(kernel_pmap, sva, sva + count *
1885 		    PAGE_SIZE);
1886 }
1887 
1888 /*
1889  * This routine tears out page mappings from the
1890  * kernel -- it is meant only for temporary mappings.
1891  * Note: SMP coherent.  Uses a ranged shootdown IPI.
1892  */
1893 static void
1894 __CONCAT(PMTYPE, qremove)(vm_offset_t sva, int count)
1895 {
1896 	vm_offset_t va;
1897 
1898 	va = sva;
1899 	while (count-- > 0) {
1900 		pmap_kremove(va);
1901 		va += PAGE_SIZE;
1902 	}
1903 	pmap_invalidate_range_int(kernel_pmap, sva, va);
1904 }
1905 
1906 /***************************************************
1907  * Page table page management routines.....
1908  ***************************************************/
1909 /*
1910  * Schedule the specified unused page table page to be freed.  Specifically,
1911  * add the page to the specified list of pages that will be released to the
1912  * physical memory manager after the TLB has been updated.
1913  */
1914 static __inline void
1915 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
1916     boolean_t set_PG_ZERO)
1917 {
1918 
1919 	if (set_PG_ZERO)
1920 		m->flags |= PG_ZERO;
1921 	else
1922 		m->flags &= ~PG_ZERO;
1923 	SLIST_INSERT_HEAD(free, m, plinks.s.ss);
1924 }
1925 
1926 /*
1927  * Inserts the specified page table page into the specified pmap's collection
1928  * of idle page table pages.  Each of a pmap's page table pages is responsible
1929  * for mapping a distinct range of virtual addresses.  The pmap's collection is
1930  * ordered by this virtual address range.
1931  *
1932  * If "promoted" is false, then the page table page "mpte" must be zero filled.
1933  */
1934 static __inline int
1935 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
1936 {
1937 
1938 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1939 	mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
1940 	return (vm_radix_insert(&pmap->pm_root, mpte));
1941 }
1942 
1943 /*
1944  * Removes the page table page mapping the specified virtual address from the
1945  * specified pmap's collection of idle page table pages, and returns it.
1946  * Otherwise, returns NULL if there is no page table page corresponding to the
1947  * specified virtual address.
1948  */
1949 static __inline vm_page_t
1950 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
1951 {
1952 
1953 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1954 	return (vm_radix_remove(&pmap->pm_root, va >> PDRSHIFT));
1955 }
1956 
1957 /*
1958  * Decrements a page table page's reference count, which is used to record the
1959  * number of valid page table entries within the page.  If the reference count
1960  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
1961  * page table page was unmapped and FALSE otherwise.
1962  */
1963 static inline boolean_t
1964 pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1965 {
1966 
1967 	--m->ref_count;
1968 	if (m->ref_count == 0) {
1969 		_pmap_unwire_ptp(pmap, m, free);
1970 		return (TRUE);
1971 	} else
1972 		return (FALSE);
1973 }
1974 
1975 static void
1976 _pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1977 {
1978 
1979 	/*
1980 	 * unmap the page table page
1981 	 */
1982 	pmap->pm_pdir[m->pindex] = 0;
1983 	--pmap->pm_stats.resident_count;
1984 
1985 	/*
1986 	 * There is not need to invalidate the recursive mapping since
1987 	 * we never instantiate such mapping for the usermode pmaps,
1988 	 * and never remove page table pages from the kernel pmap.
1989 	 * Put page on a list so that it is released since all TLB
1990 	 * shootdown is done.
1991 	 */
1992 	MPASS(pmap != kernel_pmap);
1993 	pmap_add_delayed_free_list(m, free, TRUE);
1994 }
1995 
1996 /*
1997  * After removing a page table entry, this routine is used to
1998  * conditionally free the page, and manage the reference count.
1999  */
2000 static int
2001 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, struct spglist *free)
2002 {
2003 	pd_entry_t ptepde;
2004 	vm_page_t mpte;
2005 
2006 	if (pmap == kernel_pmap)
2007 		return (0);
2008 	ptepde = *pmap_pde(pmap, va);
2009 	mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2010 	return (pmap_unwire_ptp(pmap, mpte, free));
2011 }
2012 
2013 /*
2014  * Release a page table page reference after a failed attempt to create a
2015  * mapping.
2016  */
2017 static void
2018 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2019 {
2020 	struct spglist free;
2021 
2022 	SLIST_INIT(&free);
2023 	if (pmap_unwire_ptp(pmap, mpte, &free)) {
2024 		/*
2025 		 * Although "va" was never mapped, paging-structure caches
2026 		 * could nonetheless have entries that refer to the freed
2027 		 * page table pages.  Invalidate those entries.
2028 		 */
2029 		pmap_invalidate_page_int(pmap, va);
2030 		vm_page_free_pages_toq(&free, true);
2031 	}
2032 }
2033 
2034 /*
2035  * Initialize the pmap for the swapper process.
2036  */
2037 static void
2038 __CONCAT(PMTYPE, pinit0)(pmap_t pmap)
2039 {
2040 
2041 	PMAP_LOCK_INIT(pmap);
2042 	pmap->pm_pdir = IdlePTD;
2043 #ifdef PMAP_PAE_COMP
2044 	pmap->pm_pdpt = IdlePDPT;
2045 #endif
2046 	vm_radix_init(&pmap->pm_root);
2047 	CPU_ZERO(&pmap->pm_active);
2048 	TAILQ_INIT(&pmap->pm_pvchunk);
2049 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2050 	pmap_activate_boot(pmap);
2051 }
2052 
2053 /*
2054  * Initialize a preallocated and zeroed pmap structure,
2055  * such as one in a vmspace structure.
2056  */
2057 static int
2058 __CONCAT(PMTYPE, pinit)(pmap_t pmap)
2059 {
2060 	int i;
2061 
2062 	/*
2063 	 * No need to allocate page table space yet but we do need a valid
2064 	 * page directory table.
2065 	 */
2066 	if (pmap->pm_pdir == NULL) {
2067 		pmap->pm_pdir = (pd_entry_t *)kva_alloc(NBPTD);
2068 		if (pmap->pm_pdir == NULL)
2069 			return (0);
2070 #ifdef PMAP_PAE_COMP
2071 		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
2072 		KASSERT(((vm_offset_t)pmap->pm_pdpt &
2073 		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
2074 		    ("pmap_pinit: pdpt misaligned"));
2075 		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
2076 		    ("pmap_pinit: pdpt above 4g"));
2077 #endif
2078 		vm_radix_init(&pmap->pm_root);
2079 	}
2080 	KASSERT(vm_radix_is_empty(&pmap->pm_root),
2081 	    ("pmap_pinit: pmap has reserved page table page(s)"));
2082 
2083 	/*
2084 	 * allocate the page directory page(s)
2085 	 */
2086 	for (i = 0; i < NPGPTD; i++) {
2087 		pmap->pm_ptdpg[i] = vm_page_alloc_noobj(VM_ALLOC_WIRED |
2088 		    VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2089 #ifdef PMAP_PAE_COMP
2090 		pmap->pm_pdpt[i] = VM_PAGE_TO_PHYS(pmap->pm_ptdpg[i]) | PG_V;
2091 #endif
2092 	}
2093 
2094 	pmap_qenter((vm_offset_t)pmap->pm_pdir, pmap->pm_ptdpg, NPGPTD);
2095 #ifdef PMAP_PAE_COMP
2096 	if ((cpu_feature & CPUID_PAT) == 0) {
2097 		pmap_invalidate_cache_range(
2098 		    trunc_page((vm_offset_t)pmap->pm_pdpt),
2099 		    round_page((vm_offset_t)pmap->pm_pdpt +
2100 		    NPGPTD * sizeof(pdpt_entry_t)));
2101 	}
2102 #endif
2103 
2104 	/* Install the trampoline mapping. */
2105 	pmap->pm_pdir[TRPTDI] = PTD[TRPTDI];
2106 
2107 	CPU_ZERO(&pmap->pm_active);
2108 	TAILQ_INIT(&pmap->pm_pvchunk);
2109 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2110 
2111 	return (1);
2112 }
2113 
2114 /*
2115  * this routine is called if the page table page is not
2116  * mapped correctly.
2117  */
2118 static vm_page_t
2119 _pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags)
2120 {
2121 	vm_paddr_t ptepa;
2122 	vm_page_t m;
2123 
2124 	/*
2125 	 * Allocate a page table page.
2126 	 */
2127 	if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2128 		if ((flags & PMAP_ENTER_NOSLEEP) == 0) {
2129 			PMAP_UNLOCK(pmap);
2130 			rw_wunlock(&pvh_global_lock);
2131 			vm_wait(NULL);
2132 			rw_wlock(&pvh_global_lock);
2133 			PMAP_LOCK(pmap);
2134 		}
2135 
2136 		/*
2137 		 * Indicate the need to retry.  While waiting, the page table
2138 		 * page may have been allocated.
2139 		 */
2140 		return (NULL);
2141 	}
2142 	m->pindex = ptepindex;
2143 
2144 	/*
2145 	 * Map the pagetable page into the process address space, if
2146 	 * it isn't already there.
2147 	 */
2148 
2149 	pmap->pm_stats.resident_count++;
2150 
2151 	ptepa = VM_PAGE_TO_PHYS(m);
2152 	KASSERT((pmap->pm_pdir[ptepindex] & PG_V) == 0,
2153 	    ("%s: page directory entry %#jx is valid",
2154 	    __func__, (uintmax_t)pmap->pm_pdir[ptepindex]));
2155 	pmap->pm_pdir[ptepindex] =
2156 	    (pd_entry_t)(ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
2157 
2158 	return (m);
2159 }
2160 
2161 static vm_page_t
2162 pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags)
2163 {
2164 	u_int ptepindex;
2165 	pd_entry_t ptepa;
2166 	vm_page_t m;
2167 
2168 	/*
2169 	 * Calculate pagetable page index
2170 	 */
2171 	ptepindex = va >> PDRSHIFT;
2172 retry:
2173 	/*
2174 	 * Get the page directory entry
2175 	 */
2176 	ptepa = pmap->pm_pdir[ptepindex];
2177 
2178 	/*
2179 	 * This supports switching from a 4MB page to a
2180 	 * normal 4K page.
2181 	 */
2182 	if (ptepa & PG_PS) {
2183 		(void)pmap_demote_pde(pmap, &pmap->pm_pdir[ptepindex], va);
2184 		ptepa = pmap->pm_pdir[ptepindex];
2185 	}
2186 
2187 	/*
2188 	 * If the page table page is mapped, we just increment the
2189 	 * hold count, and activate it.
2190 	 */
2191 	if (ptepa) {
2192 		m = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
2193 		m->ref_count++;
2194 	} else {
2195 		/*
2196 		 * Here if the pte page isn't mapped, or if it has
2197 		 * been deallocated.
2198 		 */
2199 		m = _pmap_allocpte(pmap, ptepindex, flags);
2200 		if (m == NULL && (flags & PMAP_ENTER_NOSLEEP) == 0)
2201 			goto retry;
2202 	}
2203 	return (m);
2204 }
2205 
2206 /***************************************************
2207 * Pmap allocation/deallocation routines.
2208  ***************************************************/
2209 
2210 /*
2211  * Release any resources held by the given physical map.
2212  * Called when a pmap initialized by pmap_pinit is being released.
2213  * Should only be called if the map contains no valid mappings.
2214  */
2215 static void
2216 __CONCAT(PMTYPE, release)(pmap_t pmap)
2217 {
2218 	vm_page_t m;
2219 	int i;
2220 
2221 	KASSERT(pmap->pm_stats.resident_count == 0,
2222 	    ("pmap_release: pmap resident count %ld != 0",
2223 	    pmap->pm_stats.resident_count));
2224 	KASSERT(vm_radix_is_empty(&pmap->pm_root),
2225 	    ("pmap_release: pmap has reserved page table page(s)"));
2226 	KASSERT(CPU_EMPTY(&pmap->pm_active),
2227 	    ("releasing active pmap %p", pmap));
2228 
2229 	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
2230 
2231 	for (i = 0; i < NPGPTD; i++) {
2232 		m = pmap->pm_ptdpg[i];
2233 #ifdef PMAP_PAE_COMP
2234 		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
2235 		    ("pmap_release: got wrong ptd page"));
2236 #endif
2237 		vm_page_unwire_noq(m);
2238 		vm_page_free(m);
2239 	}
2240 }
2241 
2242 /*
2243  * grow the number of kernel page table entries, if needed
2244  */
2245 static void
2246 __CONCAT(PMTYPE, growkernel)(vm_offset_t addr)
2247 {
2248 	vm_paddr_t ptppaddr;
2249 	vm_page_t nkpg;
2250 	pd_entry_t newpdir;
2251 
2252 	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2253 	addr = roundup2(addr, NBPDR);
2254 	if (addr - 1 >= vm_map_max(kernel_map))
2255 		addr = vm_map_max(kernel_map);
2256 	while (kernel_vm_end < addr) {
2257 		if (pdir_pde(PTD, kernel_vm_end)) {
2258 			kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2259 			if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2260 				kernel_vm_end = vm_map_max(kernel_map);
2261 				break;
2262 			}
2263 			continue;
2264 		}
2265 
2266 		nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2267 		    VM_ALLOC_ZERO);
2268 		if (nkpg == NULL)
2269 			panic("pmap_growkernel: no memory to grow kernel");
2270 		nkpg->pindex = kernel_vm_end >> PDRSHIFT;
2271 		nkpt++;
2272 
2273 		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
2274 		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
2275 		pdir_pde(KPTD, kernel_vm_end) = newpdir;
2276 
2277 		pmap_kenter_pde(kernel_vm_end, newpdir);
2278 		kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2279 		if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2280 			kernel_vm_end = vm_map_max(kernel_map);
2281 			break;
2282 		}
2283 	}
2284 }
2285 
2286 /***************************************************
2287  * page management routines.
2288  ***************************************************/
2289 
2290 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2291 CTASSERT(_NPCM == 11);
2292 CTASSERT(_NPCPV == 336);
2293 
2294 static __inline struct pv_chunk *
2295 pv_to_chunk(pv_entry_t pv)
2296 {
2297 
2298 	return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2299 }
2300 
2301 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2302 
2303 #define	PC_FREE0_9	0xfffffffful	/* Free values for index 0 through 9 */
2304 #define	PC_FREE10	0x0000fffful	/* Free values for index 10 */
2305 
2306 static const uint32_t pc_freemask[_NPCM] = {
2307 	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2308 	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2309 	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2310 	PC_FREE0_9, PC_FREE10
2311 };
2312 
2313 #ifdef PV_STATS
2314 extern int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2315 extern long pv_entry_frees, pv_entry_allocs;
2316 extern int pv_entry_spare;
2317 #endif
2318 
2319 /*
2320  * We are in a serious low memory condition.  Resort to
2321  * drastic measures to free some pages so we can allocate
2322  * another pv entry chunk.
2323  */
2324 static vm_page_t
2325 pmap_pv_reclaim(pmap_t locked_pmap)
2326 {
2327 	struct pch newtail;
2328 	struct pv_chunk *pc;
2329 	struct md_page *pvh;
2330 	pd_entry_t *pde;
2331 	pmap_t pmap;
2332 	pt_entry_t *pte, tpte;
2333 	pv_entry_t pv;
2334 	vm_offset_t va;
2335 	vm_page_t m, m_pc;
2336 	struct spglist free;
2337 	uint32_t inuse;
2338 	int bit, field, freed;
2339 
2340 	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2341 	pmap = NULL;
2342 	m_pc = NULL;
2343 	SLIST_INIT(&free);
2344 	TAILQ_INIT(&newtail);
2345 	while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
2346 	    SLIST_EMPTY(&free))) {
2347 		TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2348 		if (pmap != pc->pc_pmap) {
2349 			if (pmap != NULL) {
2350 				pmap_invalidate_all_int(pmap);
2351 				if (pmap != locked_pmap)
2352 					PMAP_UNLOCK(pmap);
2353 			}
2354 			pmap = pc->pc_pmap;
2355 			/* Avoid deadlock and lock recursion. */
2356 			if (pmap > locked_pmap)
2357 				PMAP_LOCK(pmap);
2358 			else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
2359 				pmap = NULL;
2360 				TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2361 				continue;
2362 			}
2363 		}
2364 
2365 		/*
2366 		 * Destroy every non-wired, 4 KB page mapping in the chunk.
2367 		 */
2368 		freed = 0;
2369 		for (field = 0; field < _NPCM; field++) {
2370 			for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2371 			    inuse != 0; inuse &= ~(1UL << bit)) {
2372 				bit = bsfl(inuse);
2373 				pv = &pc->pc_pventry[field * 32 + bit];
2374 				va = pv->pv_va;
2375 				pde = pmap_pde(pmap, va);
2376 				if ((*pde & PG_PS) != 0)
2377 					continue;
2378 				pte = __CONCAT(PMTYPE, pte)(pmap, va);
2379 				tpte = *pte;
2380 				if ((tpte & PG_W) == 0)
2381 					tpte = pte_load_clear(pte);
2382 				pmap_pte_release(pte);
2383 				if ((tpte & PG_W) != 0)
2384 					continue;
2385 				KASSERT(tpte != 0,
2386 				    ("pmap_pv_reclaim: pmap %p va %x zero pte",
2387 				    pmap, va));
2388 				if ((tpte & PG_G) != 0)
2389 					pmap_invalidate_page_int(pmap, va);
2390 				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2391 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2392 					vm_page_dirty(m);
2393 				if ((tpte & PG_A) != 0)
2394 					vm_page_aflag_set(m, PGA_REFERENCED);
2395 				TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2396 				if (TAILQ_EMPTY(&m->md.pv_list) &&
2397 				    (m->flags & PG_FICTITIOUS) == 0) {
2398 					pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2399 					if (TAILQ_EMPTY(&pvh->pv_list)) {
2400 						vm_page_aflag_clear(m,
2401 						    PGA_WRITEABLE);
2402 					}
2403 				}
2404 				pc->pc_map[field] |= 1UL << bit;
2405 				pmap_unuse_pt(pmap, va, &free);
2406 				freed++;
2407 			}
2408 		}
2409 		if (freed == 0) {
2410 			TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2411 			continue;
2412 		}
2413 		/* Every freed mapping is for a 4 KB page. */
2414 		pmap->pm_stats.resident_count -= freed;
2415 		PV_STAT(pv_entry_frees += freed);
2416 		PV_STAT(pv_entry_spare += freed);
2417 		pv_entry_count -= freed;
2418 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2419 		for (field = 0; field < _NPCM; field++)
2420 			if (pc->pc_map[field] != pc_freemask[field]) {
2421 				TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2422 				    pc_list);
2423 				TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2424 
2425 				/*
2426 				 * One freed pv entry in locked_pmap is
2427 				 * sufficient.
2428 				 */
2429 				if (pmap == locked_pmap)
2430 					goto out;
2431 				break;
2432 			}
2433 		if (field == _NPCM) {
2434 			PV_STAT(pv_entry_spare -= _NPCPV);
2435 			PV_STAT(pc_chunk_count--);
2436 			PV_STAT(pc_chunk_frees++);
2437 			/* Entire chunk is free; return it. */
2438 			m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2439 			pmap_qremove((vm_offset_t)pc, 1);
2440 			pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2441 			break;
2442 		}
2443 	}
2444 out:
2445 	TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
2446 	if (pmap != NULL) {
2447 		pmap_invalidate_all_int(pmap);
2448 		if (pmap != locked_pmap)
2449 			PMAP_UNLOCK(pmap);
2450 	}
2451 	if (m_pc == NULL && pv_vafree != 0 && SLIST_EMPTY(&free)) {
2452 		m_pc = SLIST_FIRST(&free);
2453 		SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2454 		/* Recycle a freed page table page. */
2455 		m_pc->ref_count = 1;
2456 	}
2457 	vm_page_free_pages_toq(&free, true);
2458 	return (m_pc);
2459 }
2460 
2461 /*
2462  * free the pv_entry back to the free list
2463  */
2464 static void
2465 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2466 {
2467 	struct pv_chunk *pc;
2468 	int idx, field, bit;
2469 
2470 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2471 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2472 	PV_STAT(pv_entry_frees++);
2473 	PV_STAT(pv_entry_spare++);
2474 	pv_entry_count--;
2475 	pc = pv_to_chunk(pv);
2476 	idx = pv - &pc->pc_pventry[0];
2477 	field = idx / 32;
2478 	bit = idx % 32;
2479 	pc->pc_map[field] |= 1ul << bit;
2480 	for (idx = 0; idx < _NPCM; idx++)
2481 		if (pc->pc_map[idx] != pc_freemask[idx]) {
2482 			/*
2483 			 * 98% of the time, pc is already at the head of the
2484 			 * list.  If it isn't already, move it to the head.
2485 			 */
2486 			if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
2487 			    pc)) {
2488 				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2489 				TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2490 				    pc_list);
2491 			}
2492 			return;
2493 		}
2494 	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2495 	free_pv_chunk(pc);
2496 }
2497 
2498 static void
2499 free_pv_chunk(struct pv_chunk *pc)
2500 {
2501 	vm_page_t m;
2502 
2503  	TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2504 	PV_STAT(pv_entry_spare -= _NPCPV);
2505 	PV_STAT(pc_chunk_count--);
2506 	PV_STAT(pc_chunk_frees++);
2507 	/* entire chunk is free, return it */
2508 	m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2509 	pmap_qremove((vm_offset_t)pc, 1);
2510 	vm_page_unwire_noq(m);
2511 	vm_page_free(m);
2512 	pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2513 }
2514 
2515 /*
2516  * get a new pv_entry, allocating a block from the system
2517  * when needed.
2518  */
2519 static pv_entry_t
2520 get_pv_entry(pmap_t pmap, boolean_t try)
2521 {
2522 	static const struct timeval printinterval = { 60, 0 };
2523 	static struct timeval lastprint;
2524 	int bit, field;
2525 	pv_entry_t pv;
2526 	struct pv_chunk *pc;
2527 	vm_page_t m;
2528 
2529 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2530 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2531 	PV_STAT(pv_entry_allocs++);
2532 	pv_entry_count++;
2533 	if (pv_entry_count > pv_entry_high_water)
2534 		if (ratecheck(&lastprint, &printinterval))
2535 			printf("Approaching the limit on PV entries, consider "
2536 			    "increasing either the vm.pmap.shpgperproc or the "
2537 			    "vm.pmap.pv_entries tunable.\n");
2538 retry:
2539 	pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2540 	if (pc != NULL) {
2541 		for (field = 0; field < _NPCM; field++) {
2542 			if (pc->pc_map[field]) {
2543 				bit = bsfl(pc->pc_map[field]);
2544 				break;
2545 			}
2546 		}
2547 		if (field < _NPCM) {
2548 			pv = &pc->pc_pventry[field * 32 + bit];
2549 			pc->pc_map[field] &= ~(1ul << bit);
2550 			/* If this was the last item, move it to tail */
2551 			for (field = 0; field < _NPCM; field++)
2552 				if (pc->pc_map[field] != 0) {
2553 					PV_STAT(pv_entry_spare--);
2554 					return (pv);	/* not full, return */
2555 				}
2556 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2557 			TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2558 			PV_STAT(pv_entry_spare--);
2559 			return (pv);
2560 		}
2561 	}
2562 	/*
2563 	 * Access to the ptelist "pv_vafree" is synchronized by the pvh
2564 	 * global lock.  If "pv_vafree" is currently non-empty, it will
2565 	 * remain non-empty until pmap_ptelist_alloc() completes.
2566 	 */
2567 	if (pv_vafree == 0 ||
2568 	    (m = vm_page_alloc_noobj(VM_ALLOC_WIRED)) == NULL) {
2569 		if (try) {
2570 			pv_entry_count--;
2571 			PV_STAT(pc_chunk_tryfail++);
2572 			return (NULL);
2573 		}
2574 		m = pmap_pv_reclaim(pmap);
2575 		if (m == NULL)
2576 			goto retry;
2577 	}
2578 	PV_STAT(pc_chunk_count++);
2579 	PV_STAT(pc_chunk_allocs++);
2580 	pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
2581 	pmap_qenter((vm_offset_t)pc, &m, 1);
2582 	pc->pc_pmap = pmap;
2583 	pc->pc_map[0] = pc_freemask[0] & ~1ul;	/* preallocated bit 0 */
2584 	for (field = 1; field < _NPCM; field++)
2585 		pc->pc_map[field] = pc_freemask[field];
2586 	TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
2587 	pv = &pc->pc_pventry[0];
2588 	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2589 	PV_STAT(pv_entry_spare += _NPCPV - 1);
2590 	return (pv);
2591 }
2592 
2593 static __inline pv_entry_t
2594 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2595 {
2596 	pv_entry_t pv;
2597 
2598 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2599 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
2600 		if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
2601 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
2602 			break;
2603 		}
2604 	}
2605 	return (pv);
2606 }
2607 
2608 static void
2609 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2610 {
2611 	struct md_page *pvh;
2612 	pv_entry_t pv;
2613 	vm_offset_t va_last;
2614 	vm_page_t m;
2615 
2616 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2617 	KASSERT((pa & PDRMASK) == 0,
2618 	    ("pmap_pv_demote_pde: pa is not 4mpage aligned"));
2619 
2620 	/*
2621 	 * Transfer the 4mpage's pv entry for this mapping to the first
2622 	 * page's pv list.
2623 	 */
2624 	pvh = pa_to_pvh(pa);
2625 	va = trunc_4mpage(va);
2626 	pv = pmap_pvh_remove(pvh, pmap, va);
2627 	KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
2628 	m = PHYS_TO_VM_PAGE(pa);
2629 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2630 	/* Instantiate the remaining NPTEPG - 1 pv entries. */
2631 	va_last = va + NBPDR - PAGE_SIZE;
2632 	do {
2633 		m++;
2634 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2635 		    ("pmap_pv_demote_pde: page %p is not managed", m));
2636 		va += PAGE_SIZE;
2637 		pmap_insert_entry(pmap, va, m);
2638 	} while (va < va_last);
2639 }
2640 
2641 #if VM_NRESERVLEVEL > 0
2642 static void
2643 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2644 {
2645 	struct md_page *pvh;
2646 	pv_entry_t pv;
2647 	vm_offset_t va_last;
2648 	vm_page_t m;
2649 
2650 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2651 	KASSERT((pa & PDRMASK) == 0,
2652 	    ("pmap_pv_promote_pde: pa is not 4mpage aligned"));
2653 
2654 	/*
2655 	 * Transfer the first page's pv entry for this mapping to the
2656 	 * 4mpage's pv list.  Aside from avoiding the cost of a call
2657 	 * to get_pv_entry(), a transfer avoids the possibility that
2658 	 * get_pv_entry() calls pmap_collect() and that pmap_collect()
2659 	 * removes one of the mappings that is being promoted.
2660 	 */
2661 	m = PHYS_TO_VM_PAGE(pa);
2662 	va = trunc_4mpage(va);
2663 	pv = pmap_pvh_remove(&m->md, pmap, va);
2664 	KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
2665 	pvh = pa_to_pvh(pa);
2666 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2667 	/* Free the remaining NPTEPG - 1 pv entries. */
2668 	va_last = va + NBPDR - PAGE_SIZE;
2669 	do {
2670 		m++;
2671 		va += PAGE_SIZE;
2672 		pmap_pvh_free(&m->md, pmap, va);
2673 	} while (va < va_last);
2674 }
2675 #endif /* VM_NRESERVLEVEL > 0 */
2676 
2677 static void
2678 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2679 {
2680 	pv_entry_t pv;
2681 
2682 	pv = pmap_pvh_remove(pvh, pmap, va);
2683 	KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
2684 	free_pv_entry(pmap, pv);
2685 }
2686 
2687 static void
2688 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
2689 {
2690 	struct md_page *pvh;
2691 
2692 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2693 	pmap_pvh_free(&m->md, pmap, va);
2694 	if (TAILQ_EMPTY(&m->md.pv_list) && (m->flags & PG_FICTITIOUS) == 0) {
2695 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2696 		if (TAILQ_EMPTY(&pvh->pv_list))
2697 			vm_page_aflag_clear(m, PGA_WRITEABLE);
2698 	}
2699 }
2700 
2701 /*
2702  * Create a pv entry for page at pa for
2703  * (pmap, va).
2704  */
2705 static void
2706 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2707 {
2708 	pv_entry_t pv;
2709 
2710 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2711 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2712 	pv = get_pv_entry(pmap, FALSE);
2713 	pv->pv_va = va;
2714 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2715 }
2716 
2717 /*
2718  * Conditionally create a pv entry.
2719  */
2720 static boolean_t
2721 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2722 {
2723 	pv_entry_t pv;
2724 
2725 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2726 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2727 	if (pv_entry_count < pv_entry_high_water &&
2728 	    (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2729 		pv->pv_va = va;
2730 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2731 		return (TRUE);
2732 	} else
2733 		return (FALSE);
2734 }
2735 
2736 /*
2737  * Create the pv entries for each of the pages within a superpage.
2738  */
2739 static bool
2740 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags)
2741 {
2742 	struct md_page *pvh;
2743 	pv_entry_t pv;
2744 	bool noreclaim;
2745 
2746 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2747 	noreclaim = (flags & PMAP_ENTER_NORECLAIM) != 0;
2748 	if ((noreclaim && pv_entry_count >= pv_entry_high_water) ||
2749 	    (pv = get_pv_entry(pmap, noreclaim)) == NULL)
2750 		return (false);
2751 	pv->pv_va = va;
2752 	pvh = pa_to_pvh(pde & PG_PS_FRAME);
2753 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2754 	return (true);
2755 }
2756 
2757 /*
2758  * Fills a page table page with mappings to consecutive physical pages.
2759  */
2760 static void
2761 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
2762 {
2763 	pt_entry_t *pte;
2764 
2765 	for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
2766 		*pte = newpte;
2767 		newpte += PAGE_SIZE;
2768 	}
2769 }
2770 
2771 /*
2772  * Tries to demote a 2- or 4MB page mapping.  If demotion fails, the
2773  * 2- or 4MB page mapping is invalidated.
2774  */
2775 static boolean_t
2776 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2777 {
2778 	pd_entry_t newpde, oldpde;
2779 	pt_entry_t *firstpte, newpte;
2780 	vm_paddr_t mptepa;
2781 	vm_page_t mpte;
2782 	struct spglist free;
2783 	vm_offset_t sva;
2784 
2785 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2786 	oldpde = *pde;
2787 	KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
2788 	    ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
2789 	if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
2790 	    NULL) {
2791 		KASSERT((oldpde & PG_W) == 0,
2792 		    ("pmap_demote_pde: page table page for a wired mapping"
2793 		    " is missing"));
2794 
2795 		/*
2796 		 * Invalidate the 2- or 4MB page mapping and return
2797 		 * "failure" if the mapping was never accessed or the
2798 		 * allocation of the new page table page fails.
2799 		 */
2800 		if ((oldpde & PG_A) == 0 ||
2801 		    (mpte = vm_page_alloc_noobj(VM_ALLOC_WIRED)) == NULL) {
2802 			SLIST_INIT(&free);
2803 			sva = trunc_4mpage(va);
2804 			pmap_remove_pde(pmap, pde, sva, &free);
2805 			if ((oldpde & PG_G) == 0)
2806 				pmap_invalidate_pde_page(pmap, sva, oldpde);
2807 			vm_page_free_pages_toq(&free, true);
2808 			CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#x"
2809 			    " in pmap %p", va, pmap);
2810 			return (FALSE);
2811 		}
2812 		mpte->pindex = va >> PDRSHIFT;
2813 		if (pmap != kernel_pmap) {
2814 			mpte->ref_count = NPTEPG;
2815 			pmap->pm_stats.resident_count++;
2816 		}
2817 	}
2818 	mptepa = VM_PAGE_TO_PHYS(mpte);
2819 
2820 	/*
2821 	 * If the page mapping is in the kernel's address space, then the
2822 	 * KPTmap can provide access to the page table page.  Otherwise,
2823 	 * temporarily map the page table page (mpte) into the kernel's
2824 	 * address space at either PADDR1 or PADDR2.
2825 	 */
2826 	if (pmap == kernel_pmap)
2827 		firstpte = &KPTmap[i386_btop(trunc_4mpage(va))];
2828 	else if (curthread->td_pinned > 0 && rw_wowned(&pvh_global_lock)) {
2829 		if ((*PMAP1 & PG_FRAME) != mptepa) {
2830 			*PMAP1 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2831 #ifdef SMP
2832 			PMAP1cpu = PCPU_GET(cpuid);
2833 #endif
2834 			invlcaddr(PADDR1);
2835 			PMAP1changed++;
2836 		} else
2837 #ifdef SMP
2838 		if (PMAP1cpu != PCPU_GET(cpuid)) {
2839 			PMAP1cpu = PCPU_GET(cpuid);
2840 			invlcaddr(PADDR1);
2841 			PMAP1changedcpu++;
2842 		} else
2843 #endif
2844 			PMAP1unchanged++;
2845 		firstpte = PADDR1;
2846 	} else {
2847 		mtx_lock(&PMAP2mutex);
2848 		if ((*PMAP2 & PG_FRAME) != mptepa) {
2849 			*PMAP2 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2850 			pmap_invalidate_page_int(kernel_pmap,
2851 			    (vm_offset_t)PADDR2);
2852 		}
2853 		firstpte = PADDR2;
2854 	}
2855 	newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
2856 	KASSERT((oldpde & PG_A) != 0,
2857 	    ("pmap_demote_pde: oldpde is missing PG_A"));
2858 	KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
2859 	    ("pmap_demote_pde: oldpde is missing PG_M"));
2860 	newpte = oldpde & ~PG_PS;
2861 	if ((newpte & PG_PDE_PAT) != 0)
2862 		newpte ^= PG_PDE_PAT | PG_PTE_PAT;
2863 
2864 	/*
2865 	 * If the page table page is not leftover from an earlier promotion,
2866 	 * initialize it.
2867 	 */
2868 	if (mpte->valid == 0)
2869 		pmap_fill_ptp(firstpte, newpte);
2870 
2871 	KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
2872 	    ("pmap_demote_pde: firstpte and newpte map different physical"
2873 	    " addresses"));
2874 
2875 	/*
2876 	 * If the mapping has changed attributes, update the page table
2877 	 * entries.
2878 	 */
2879 	if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
2880 		pmap_fill_ptp(firstpte, newpte);
2881 
2882 	/*
2883 	 * Demote the mapping.  This pmap is locked.  The old PDE has
2884 	 * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
2885 	 * set.  Thus, there is no danger of a race with another
2886 	 * processor changing the setting of PG_A and/or PG_M between
2887 	 * the read above and the store below.
2888 	 */
2889 	if (workaround_erratum383)
2890 		pmap_update_pde(pmap, va, pde, newpde);
2891 	else if (pmap == kernel_pmap)
2892 		pmap_kenter_pde(va, newpde);
2893 	else
2894 		pde_store(pde, newpde);
2895 	if (firstpte == PADDR2)
2896 		mtx_unlock(&PMAP2mutex);
2897 
2898 	/*
2899 	 * Invalidate the recursive mapping of the page table page.
2900 	 */
2901 	pmap_invalidate_page_int(pmap, (vm_offset_t)vtopte(va));
2902 
2903 	/*
2904 	 * Demote the pv entry.  This depends on the earlier demotion
2905 	 * of the mapping.  Specifically, the (re)creation of a per-
2906 	 * page pv entry might trigger the execution of pmap_collect(),
2907 	 * which might reclaim a newly (re)created per-page pv entry
2908 	 * and destroy the associated mapping.  In order to destroy
2909 	 * the mapping, the PDE must have already changed from mapping
2910 	 * the 2mpage to referencing the page table page.
2911 	 */
2912 	if ((oldpde & PG_MANAGED) != 0)
2913 		pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME);
2914 
2915 	pmap_pde_demotions++;
2916 	CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#x"
2917 	    " in pmap %p", va, pmap);
2918 	return (TRUE);
2919 }
2920 
2921 /*
2922  * Removes a 2- or 4MB page mapping from the kernel pmap.
2923  */
2924 static void
2925 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2926 {
2927 	pd_entry_t newpde;
2928 	vm_paddr_t mptepa;
2929 	vm_page_t mpte;
2930 
2931 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2932 	mpte = pmap_remove_pt_page(pmap, va);
2933 	if (mpte == NULL)
2934 		panic("pmap_remove_kernel_pde: Missing pt page.");
2935 
2936 	mptepa = VM_PAGE_TO_PHYS(mpte);
2937 	newpde = mptepa | PG_M | PG_A | PG_RW | PG_V;
2938 
2939 	/*
2940 	 * If this page table page was unmapped by a promotion, then it
2941 	 * contains valid mappings.  Zero it to invalidate those mappings.
2942 	 */
2943 	if (mpte->valid != 0)
2944 		pagezero((void *)&KPTmap[i386_btop(trunc_4mpage(va))]);
2945 
2946 	/*
2947 	 * Remove the mapping.
2948 	 */
2949 	if (workaround_erratum383)
2950 		pmap_update_pde(pmap, va, pde, newpde);
2951 	else
2952 		pmap_kenter_pde(va, newpde);
2953 
2954 	/*
2955 	 * Invalidate the recursive mapping of the page table page.
2956 	 */
2957 	pmap_invalidate_page_int(pmap, (vm_offset_t)vtopte(va));
2958 }
2959 
2960 /*
2961  * pmap_remove_pde: do the things to unmap a superpage in a process
2962  */
2963 static void
2964 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
2965     struct spglist *free)
2966 {
2967 	struct md_page *pvh;
2968 	pd_entry_t oldpde;
2969 	vm_offset_t eva, va;
2970 	vm_page_t m, mpte;
2971 
2972 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2973 	KASSERT((sva & PDRMASK) == 0,
2974 	    ("pmap_remove_pde: sva is not 4mpage aligned"));
2975 	oldpde = pte_load_clear(pdq);
2976 	if (oldpde & PG_W)
2977 		pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
2978 
2979 	/*
2980 	 * Machines that don't support invlpg, also don't support
2981 	 * PG_G.
2982 	 */
2983 	if ((oldpde & PG_G) != 0)
2984 		pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
2985 
2986 	pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2987 	if (oldpde & PG_MANAGED) {
2988 		pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
2989 		pmap_pvh_free(pvh, pmap, sva);
2990 		eva = sva + NBPDR;
2991 		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
2992 		    va < eva; va += PAGE_SIZE, m++) {
2993 			if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
2994 				vm_page_dirty(m);
2995 			if (oldpde & PG_A)
2996 				vm_page_aflag_set(m, PGA_REFERENCED);
2997 			if (TAILQ_EMPTY(&m->md.pv_list) &&
2998 			    TAILQ_EMPTY(&pvh->pv_list))
2999 				vm_page_aflag_clear(m, PGA_WRITEABLE);
3000 		}
3001 	}
3002 	if (pmap == kernel_pmap) {
3003 		pmap_remove_kernel_pde(pmap, pdq, sva);
3004 	} else {
3005 		mpte = pmap_remove_pt_page(pmap, sva);
3006 		if (mpte != NULL) {
3007 			KASSERT(mpte->valid == VM_PAGE_BITS_ALL,
3008 			    ("pmap_remove_pde: pte page not promoted"));
3009 			pmap->pm_stats.resident_count--;
3010 			KASSERT(mpte->ref_count == NPTEPG,
3011 			    ("pmap_remove_pde: pte page ref count error"));
3012 			mpte->ref_count = 0;
3013 			pmap_add_delayed_free_list(mpte, free, FALSE);
3014 		}
3015 	}
3016 }
3017 
3018 /*
3019  * pmap_remove_pte: do the things to unmap a page in a process
3020  */
3021 static int
3022 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3023     struct spglist *free)
3024 {
3025 	pt_entry_t oldpte;
3026 	vm_page_t m;
3027 
3028 	rw_assert(&pvh_global_lock, RA_WLOCKED);
3029 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3030 	oldpte = pte_load_clear(ptq);
3031 	KASSERT(oldpte != 0,
3032 	    ("pmap_remove_pte: pmap %p va %x zero pte", pmap, va));
3033 	if (oldpte & PG_W)
3034 		pmap->pm_stats.wired_count -= 1;
3035 	/*
3036 	 * Machines that don't support invlpg, also don't support
3037 	 * PG_G.
3038 	 */
3039 	if (oldpte & PG_G)
3040 		pmap_invalidate_page_int(kernel_pmap, va);
3041 	pmap->pm_stats.resident_count -= 1;
3042 	if (oldpte & PG_MANAGED) {
3043 		m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3044 		if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3045 			vm_page_dirty(m);
3046 		if (oldpte & PG_A)
3047 			vm_page_aflag_set(m, PGA_REFERENCED);
3048 		pmap_remove_entry(pmap, m, va);
3049 	}
3050 	return (pmap_unuse_pt(pmap, va, free));
3051 }
3052 
3053 /*
3054  * Remove a single page from a process address space
3055  */
3056 static void
3057 pmap_remove_page(pmap_t pmap, vm_offset_t va, struct spglist *free)
3058 {
3059 	pt_entry_t *pte;
3060 
3061 	rw_assert(&pvh_global_lock, RA_WLOCKED);
3062 	KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
3063 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3064 	if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
3065 		return;
3066 	pmap_remove_pte(pmap, pte, va, free);
3067 	pmap_invalidate_page_int(pmap, va);
3068 }
3069 
3070 /*
3071  * Removes the specified range of addresses from the page table page.
3072  */
3073 static bool
3074 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3075     struct spglist *free)
3076 {
3077 	pt_entry_t *pte;
3078 	bool anyvalid;
3079 
3080 	rw_assert(&pvh_global_lock, RA_WLOCKED);
3081 	KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
3082 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3083 	anyvalid = false;
3084 	for (pte = pmap_pte_quick(pmap, sva); sva != eva; pte++,
3085 	    sva += PAGE_SIZE) {
3086 		if (*pte == 0)
3087 			continue;
3088 
3089 		/*
3090 		 * The TLB entry for a PG_G mapping is invalidated by
3091 		 * pmap_remove_pte().
3092 		 */
3093 		if ((*pte & PG_G) == 0)
3094 			anyvalid = true;
3095 
3096 		if (pmap_remove_pte(pmap, pte, sva, free))
3097 			break;
3098 	}
3099 	return (anyvalid);
3100 }
3101 
3102 /*
3103  *	Remove the given range of addresses from the specified map.
3104  *
3105  *	It is assumed that the start and end are properly
3106  *	rounded to the page size.
3107  */
3108 static void
3109 __CONCAT(PMTYPE, remove)(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3110 {
3111 	vm_offset_t pdnxt;
3112 	pd_entry_t ptpaddr;
3113 	struct spglist free;
3114 	int anyvalid;
3115 
3116 	/*
3117 	 * Perform an unsynchronized read.  This is, however, safe.
3118 	 */
3119 	if (pmap->pm_stats.resident_count == 0)
3120 		return;
3121 
3122 	anyvalid = 0;
3123 	SLIST_INIT(&free);
3124 
3125 	rw_wlock(&pvh_global_lock);
3126 	sched_pin();
3127 	PMAP_LOCK(pmap);
3128 
3129 	/*
3130 	 * special handling of removing one page.  a very
3131 	 * common operation and easy to short circuit some
3132 	 * code.
3133 	 */
3134 	if ((sva + PAGE_SIZE == eva) &&
3135 	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
3136 		pmap_remove_page(pmap, sva, &free);
3137 		goto out;
3138 	}
3139 
3140 	for (; sva < eva; sva = pdnxt) {
3141 		u_int pdirindex;
3142 
3143 		/*
3144 		 * Calculate index for next page table.
3145 		 */
3146 		pdnxt = (sva + NBPDR) & ~PDRMASK;
3147 		if (pdnxt < sva)
3148 			pdnxt = eva;
3149 		if (pmap->pm_stats.resident_count == 0)
3150 			break;
3151 
3152 		pdirindex = sva >> PDRSHIFT;
3153 		ptpaddr = pmap->pm_pdir[pdirindex];
3154 
3155 		/*
3156 		 * Weed out invalid mappings. Note: we assume that the page
3157 		 * directory table is always allocated, and in kernel virtual.
3158 		 */
3159 		if (ptpaddr == 0)
3160 			continue;
3161 
3162 		/*
3163 		 * Check for large page.
3164 		 */
3165 		if ((ptpaddr & PG_PS) != 0) {
3166 			/*
3167 			 * Are we removing the entire large page?  If not,
3168 			 * demote the mapping and fall through.
3169 			 */
3170 			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
3171 				/*
3172 				 * The TLB entry for a PG_G mapping is
3173 				 * invalidated by pmap_remove_pde().
3174 				 */
3175 				if ((ptpaddr & PG_G) == 0)
3176 					anyvalid = 1;
3177 				pmap_remove_pde(pmap,
3178 				    &pmap->pm_pdir[pdirindex], sva, &free);
3179 				continue;
3180 			} else if (!pmap_demote_pde(pmap,
3181 			    &pmap->pm_pdir[pdirindex], sva)) {
3182 				/* The large page mapping was destroyed. */
3183 				continue;
3184 			}
3185 		}
3186 
3187 		/*
3188 		 * Limit our scan to either the end of the va represented
3189 		 * by the current page table page, or to the end of the
3190 		 * range being removed.
3191 		 */
3192 		if (pdnxt > eva)
3193 			pdnxt = eva;
3194 
3195 		if (pmap_remove_ptes(pmap, sva, pdnxt, &free))
3196 			anyvalid = 1;
3197 	}
3198 out:
3199 	sched_unpin();
3200 	if (anyvalid)
3201 		pmap_invalidate_all_int(pmap);
3202 	rw_wunlock(&pvh_global_lock);
3203 	PMAP_UNLOCK(pmap);
3204 	vm_page_free_pages_toq(&free, true);
3205 }
3206 
3207 /*
3208  *	Routine:	pmap_remove_all
3209  *	Function:
3210  *		Removes this physical page from
3211  *		all physical maps in which it resides.
3212  *		Reflects back modify bits to the pager.
3213  *
3214  *	Notes:
3215  *		Original versions of this routine were very
3216  *		inefficient because they iteratively called
3217  *		pmap_remove (slow...)
3218  */
3219 
3220 static void
3221 __CONCAT(PMTYPE, remove_all)(vm_page_t m)
3222 {
3223 	struct md_page *pvh;
3224 	pv_entry_t pv;
3225 	pmap_t pmap;
3226 	pt_entry_t *pte, tpte;
3227 	pd_entry_t *pde;
3228 	vm_offset_t va;
3229 	struct spglist free;
3230 
3231 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3232 	    ("pmap_remove_all: page %p is not managed", m));
3233 	SLIST_INIT(&free);
3234 	rw_wlock(&pvh_global_lock);
3235 	sched_pin();
3236 	if ((m->flags & PG_FICTITIOUS) != 0)
3237 		goto small_mappings;
3238 	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3239 	while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3240 		va = pv->pv_va;
3241 		pmap = PV_PMAP(pv);
3242 		PMAP_LOCK(pmap);
3243 		pde = pmap_pde(pmap, va);
3244 		(void)pmap_demote_pde(pmap, pde, va);
3245 		PMAP_UNLOCK(pmap);
3246 	}
3247 small_mappings:
3248 	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3249 		pmap = PV_PMAP(pv);
3250 		PMAP_LOCK(pmap);
3251 		pmap->pm_stats.resident_count--;
3252 		pde = pmap_pde(pmap, pv->pv_va);
3253 		KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3254 		    " a 4mpage in page %p's pv list", m));
3255 		pte = pmap_pte_quick(pmap, pv->pv_va);
3256 		tpte = pte_load_clear(pte);
3257 		KASSERT(tpte != 0, ("pmap_remove_all: pmap %p va %x zero pte",
3258 		    pmap, pv->pv_va));
3259 		if (tpte & PG_W)
3260 			pmap->pm_stats.wired_count--;
3261 		if (tpte & PG_A)
3262 			vm_page_aflag_set(m, PGA_REFERENCED);
3263 
3264 		/*
3265 		 * Update the vm_page_t clean and reference bits.
3266 		 */
3267 		if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3268 			vm_page_dirty(m);
3269 		pmap_unuse_pt(pmap, pv->pv_va, &free);
3270 		pmap_invalidate_page_int(pmap, pv->pv_va);
3271 		TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3272 		free_pv_entry(pmap, pv);
3273 		PMAP_UNLOCK(pmap);
3274 	}
3275 	vm_page_aflag_clear(m, PGA_WRITEABLE);
3276 	sched_unpin();
3277 	rw_wunlock(&pvh_global_lock);
3278 	vm_page_free_pages_toq(&free, true);
3279 }
3280 
3281 /*
3282  * pmap_protect_pde: do the things to protect a 4mpage in a process
3283  */
3284 static boolean_t
3285 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3286 {
3287 	pd_entry_t newpde, oldpde;
3288 	vm_page_t m, mt;
3289 	boolean_t anychanged;
3290 
3291 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3292 	KASSERT((sva & PDRMASK) == 0,
3293 	    ("pmap_protect_pde: sva is not 4mpage aligned"));
3294 	anychanged = FALSE;
3295 retry:
3296 	oldpde = newpde = *pde;
3297 	if ((prot & VM_PROT_WRITE) == 0) {
3298 		if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
3299 		    (PG_MANAGED | PG_M | PG_RW)) {
3300 			m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3301 			for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
3302 				vm_page_dirty(mt);
3303 		}
3304 		newpde &= ~(PG_RW | PG_M);
3305 	}
3306 #ifdef PMAP_PAE_COMP
3307 	if ((prot & VM_PROT_EXECUTE) == 0 && !i386_read_exec)
3308 		newpde |= pg_nx;
3309 #endif
3310 	if (newpde != oldpde) {
3311 		/*
3312 		 * As an optimization to future operations on this PDE, clear
3313 		 * PG_PROMOTED.  The impending invalidation will remove any
3314 		 * lingering 4KB page mappings from the TLB.
3315 		 */
3316 		if (!pde_cmpset(pde, oldpde, newpde & ~PG_PROMOTED))
3317 			goto retry;
3318 		if ((oldpde & PG_G) != 0)
3319 			pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3320 		else
3321 			anychanged = TRUE;
3322 	}
3323 	return (anychanged);
3324 }
3325 
3326 /*
3327  *	Set the physical protection on the
3328  *	specified range of this map as requested.
3329  */
3330 static void
3331 __CONCAT(PMTYPE, protect)(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3332     vm_prot_t prot)
3333 {
3334 	vm_offset_t pdnxt;
3335 	pd_entry_t ptpaddr;
3336 	pt_entry_t *pte;
3337 	boolean_t anychanged, pv_lists_locked;
3338 
3339 	KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3340 	if (prot == VM_PROT_NONE) {
3341 		pmap_remove(pmap, sva, eva);
3342 		return;
3343 	}
3344 
3345 #ifdef PMAP_PAE_COMP
3346 	if ((prot & (VM_PROT_WRITE | VM_PROT_EXECUTE)) ==
3347 	    (VM_PROT_WRITE | VM_PROT_EXECUTE))
3348 		return;
3349 #else
3350 	if (prot & VM_PROT_WRITE)
3351 		return;
3352 #endif
3353 
3354 	if (pmap_is_current(pmap))
3355 		pv_lists_locked = FALSE;
3356 	else {
3357 		pv_lists_locked = TRUE;
3358 resume:
3359 		rw_wlock(&pvh_global_lock);
3360 		sched_pin();
3361 	}
3362 	anychanged = FALSE;
3363 
3364 	PMAP_LOCK(pmap);
3365 	for (; sva < eva; sva = pdnxt) {
3366 		pt_entry_t obits, pbits;
3367 		u_int pdirindex;
3368 
3369 		pdnxt = (sva + NBPDR) & ~PDRMASK;
3370 		if (pdnxt < sva)
3371 			pdnxt = eva;
3372 
3373 		pdirindex = sva >> PDRSHIFT;
3374 		ptpaddr = pmap->pm_pdir[pdirindex];
3375 
3376 		/*
3377 		 * Weed out invalid mappings. Note: we assume that the page
3378 		 * directory table is always allocated, and in kernel virtual.
3379 		 */
3380 		if (ptpaddr == 0)
3381 			continue;
3382 
3383 		/*
3384 		 * Check for large page.
3385 		 */
3386 		if ((ptpaddr & PG_PS) != 0) {
3387 			/*
3388 			 * Are we protecting the entire large page?  If not,
3389 			 * demote the mapping and fall through.
3390 			 */
3391 			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
3392 				/*
3393 				 * The TLB entry for a PG_G mapping is
3394 				 * invalidated by pmap_protect_pde().
3395 				 */
3396 				if (pmap_protect_pde(pmap,
3397 				    &pmap->pm_pdir[pdirindex], sva, prot))
3398 					anychanged = TRUE;
3399 				continue;
3400 			} else {
3401 				if (!pv_lists_locked) {
3402 					pv_lists_locked = TRUE;
3403 					if (!rw_try_wlock(&pvh_global_lock)) {
3404 						if (anychanged)
3405 							pmap_invalidate_all_int(
3406 							    pmap);
3407 						PMAP_UNLOCK(pmap);
3408 						goto resume;
3409 					}
3410 					sched_pin();
3411 				}
3412 				if (!pmap_demote_pde(pmap,
3413 				    &pmap->pm_pdir[pdirindex], sva)) {
3414 					/*
3415 					 * The large page mapping was
3416 					 * destroyed.
3417 					 */
3418 					continue;
3419 				}
3420 			}
3421 		}
3422 
3423 		if (pdnxt > eva)
3424 			pdnxt = eva;
3425 
3426 		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
3427 		    sva += PAGE_SIZE) {
3428 			vm_page_t m;
3429 
3430 retry:
3431 			/*
3432 			 * Regardless of whether a pte is 32 or 64 bits in
3433 			 * size, PG_RW, PG_A, and PG_M are among the least
3434 			 * significant 32 bits.
3435 			 */
3436 			obits = pbits = *pte;
3437 			if ((pbits & PG_V) == 0)
3438 				continue;
3439 
3440 			if ((prot & VM_PROT_WRITE) == 0) {
3441 				if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
3442 				    (PG_MANAGED | PG_M | PG_RW)) {
3443 					m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
3444 					vm_page_dirty(m);
3445 				}
3446 				pbits &= ~(PG_RW | PG_M);
3447 			}
3448 #ifdef PMAP_PAE_COMP
3449 			if ((prot & VM_PROT_EXECUTE) == 0 && !i386_read_exec)
3450 				pbits |= pg_nx;
3451 #endif
3452 
3453 			if (pbits != obits) {
3454 #ifdef PMAP_PAE_COMP
3455 				if (!atomic_cmpset_64(pte, obits, pbits))
3456 					goto retry;
3457 #else
3458 				if (!atomic_cmpset_int((u_int *)pte, obits,
3459 				    pbits))
3460 					goto retry;
3461 #endif
3462 				if (obits & PG_G)
3463 					pmap_invalidate_page_int(pmap, sva);
3464 				else
3465 					anychanged = TRUE;
3466 			}
3467 		}
3468 	}
3469 	if (anychanged)
3470 		pmap_invalidate_all_int(pmap);
3471 	if (pv_lists_locked) {
3472 		sched_unpin();
3473 		rw_wunlock(&pvh_global_lock);
3474 	}
3475 	PMAP_UNLOCK(pmap);
3476 }
3477 
3478 #if VM_NRESERVLEVEL > 0
3479 /*
3480  * Tries to promote the 512 or 1024, contiguous 4KB page mappings that are
3481  * within a single page table page (PTP) to a single 2- or 4MB page mapping.
3482  * For promotion to occur, two conditions must be met: (1) the 4KB page
3483  * mappings must map aligned, contiguous physical memory and (2) the 4KB page
3484  * mappings must have identical characteristics.
3485  *
3486  * Managed (PG_MANAGED) mappings within the kernel address space are not
3487  * promoted.  The reason is that kernel PDEs are replicated in each pmap but
3488  * pmap_clear_ptes() and pmap_ts_referenced() only read the PDE from the kernel
3489  * pmap.
3490  */
3491 static void
3492 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3493 {
3494 	pd_entry_t newpde;
3495 	pt_entry_t *firstpte, oldpte, pa, *pte;
3496 	vm_offset_t oldpteva;
3497 	vm_page_t mpte;
3498 
3499 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3500 
3501 	/*
3502 	 * Examine the first PTE in the specified PTP.  Abort if this PTE is
3503 	 * either invalid, unused, or does not map the first 4KB physical page
3504 	 * within a 2- or 4MB page.
3505 	 */
3506 	firstpte = pmap_pte_quick(pmap, trunc_4mpage(va));
3507 setpde:
3508 	newpde = *firstpte;
3509 	if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
3510 		pmap_pde_p_failures++;
3511 		CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3512 		    " in pmap %p", va, pmap);
3513 		return;
3514 	}
3515 	if ((*firstpte & PG_MANAGED) != 0 && pmap == kernel_pmap) {
3516 		pmap_pde_p_failures++;
3517 		CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3518 		    " in pmap %p", va, pmap);
3519 		return;
3520 	}
3521 	if ((newpde & (PG_M | PG_RW)) == PG_RW) {
3522 		/*
3523 		 * When PG_M is already clear, PG_RW can be cleared without
3524 		 * a TLB invalidation.
3525 		 */
3526 		if (!atomic_cmpset_int((u_int *)firstpte, newpde, newpde &
3527 		    ~PG_RW))
3528 			goto setpde;
3529 		newpde &= ~PG_RW;
3530 	}
3531 
3532 	/*
3533 	 * Examine each of the other PTEs in the specified PTP.  Abort if this
3534 	 * PTE maps an unexpected 4KB physical page or does not have identical
3535 	 * characteristics to the first PTE.
3536 	 */
3537 	pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
3538 	for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
3539 setpte:
3540 		oldpte = *pte;
3541 		if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
3542 			pmap_pde_p_failures++;
3543 			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3544 			    " in pmap %p", va, pmap);
3545 			return;
3546 		}
3547 		if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
3548 			/*
3549 			 * When PG_M is already clear, PG_RW can be cleared
3550 			 * without a TLB invalidation.
3551 			 */
3552 			if (!atomic_cmpset_int((u_int *)pte, oldpte,
3553 			    oldpte & ~PG_RW))
3554 				goto setpte;
3555 			oldpte &= ~PG_RW;
3556 			oldpteva = (oldpte & PG_FRAME & PDRMASK) |
3557 			    (va & ~PDRMASK);
3558 			CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#x"
3559 			    " in pmap %p", oldpteva, pmap);
3560 		}
3561 		if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
3562 			pmap_pde_p_failures++;
3563 			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3564 			    " in pmap %p", va, pmap);
3565 			return;
3566 		}
3567 		pa -= PAGE_SIZE;
3568 	}
3569 
3570 	/*
3571 	 * Save the page table page in its current state until the PDE
3572 	 * mapping the superpage is demoted by pmap_demote_pde() or
3573 	 * destroyed by pmap_remove_pde().
3574 	 */
3575 	mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
3576 	KASSERT(mpte >= vm_page_array &&
3577 	    mpte < &vm_page_array[vm_page_array_size],
3578 	    ("pmap_promote_pde: page table page is out of range"));
3579 	KASSERT(mpte->pindex == va >> PDRSHIFT,
3580 	    ("pmap_promote_pde: page table page's pindex is wrong"));
3581 	if (pmap_insert_pt_page(pmap, mpte, true)) {
3582 		pmap_pde_p_failures++;
3583 		CTR2(KTR_PMAP,
3584 		    "pmap_promote_pde: failure for va %#x in pmap %p", va,
3585 		    pmap);
3586 		return;
3587 	}
3588 
3589 	/*
3590 	 * Promote the pv entries.
3591 	 */
3592 	if ((newpde & PG_MANAGED) != 0)
3593 		pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME);
3594 
3595 	/*
3596 	 * Propagate the PAT index to its proper position.
3597 	 */
3598 	if ((newpde & PG_PTE_PAT) != 0)
3599 		newpde ^= PG_PDE_PAT | PG_PTE_PAT;
3600 
3601 	/*
3602 	 * Map the superpage.
3603 	 */
3604 	if (workaround_erratum383)
3605 		pmap_update_pde(pmap, va, pde, PG_PS | newpde);
3606 	else if (pmap == kernel_pmap)
3607 		pmap_kenter_pde(va, PG_PROMOTED | PG_PS | newpde);
3608 	else
3609 		pde_store(pde, PG_PROMOTED | PG_PS | newpde);
3610 
3611 	pmap_pde_promotions++;
3612 	CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#x"
3613 	    " in pmap %p", va, pmap);
3614 }
3615 #endif /* VM_NRESERVLEVEL > 0 */
3616 
3617 /*
3618  *	Insert the given physical page (p) at
3619  *	the specified virtual address (v) in the
3620  *	target physical map with the protection requested.
3621  *
3622  *	If specified, the page will be wired down, meaning
3623  *	that the related pte can not be reclaimed.
3624  *
3625  *	NB:  This is the only routine which MAY NOT lazy-evaluate
3626  *	or lose information.  That is, this routine must actually
3627  *	insert this page into the given map NOW.
3628  */
3629 static int
3630 __CONCAT(PMTYPE, enter)(pmap_t pmap, vm_offset_t va, vm_page_t m,
3631     vm_prot_t prot, u_int flags, int8_t psind)
3632 {
3633 	pd_entry_t *pde;
3634 	pt_entry_t *pte;
3635 	pt_entry_t newpte, origpte;
3636 	pv_entry_t pv;
3637 	vm_paddr_t opa, pa;
3638 	vm_page_t mpte, om;
3639 	int rv;
3640 
3641 	va = trunc_page(va);
3642 	KASSERT((pmap == kernel_pmap && va < VM_MAX_KERNEL_ADDRESS) ||
3643 	    (pmap != kernel_pmap && va < VM_MAXUSER_ADDRESS),
3644 	    ("pmap_enter: toobig k%d %#x", pmap == kernel_pmap, va));
3645 	KASSERT(va < PMAP_TRM_MIN_ADDRESS,
3646 	    ("pmap_enter: invalid to pmap_enter into trampoline (va: 0x%x)",
3647 	    va));
3648 	KASSERT(pmap != kernel_pmap || (m->oflags & VPO_UNMANAGED) != 0 ||
3649 	    !VA_IS_CLEANMAP(va),
3650 	    ("pmap_enter: managed mapping within the clean submap"));
3651 	if ((m->oflags & VPO_UNMANAGED) == 0)
3652 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
3653 	KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
3654 	    ("pmap_enter: flags %u has reserved bits set", flags));
3655 	pa = VM_PAGE_TO_PHYS(m);
3656 	newpte = (pt_entry_t)(pa | PG_A | PG_V);
3657 	if ((flags & VM_PROT_WRITE) != 0)
3658 		newpte |= PG_M;
3659 	if ((prot & VM_PROT_WRITE) != 0)
3660 		newpte |= PG_RW;
3661 	KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
3662 	    ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
3663 #ifdef PMAP_PAE_COMP
3664 	if ((prot & VM_PROT_EXECUTE) == 0 && !i386_read_exec)
3665 		newpte |= pg_nx;
3666 #endif
3667 	if ((flags & PMAP_ENTER_WIRED) != 0)
3668 		newpte |= PG_W;
3669 	if (pmap != kernel_pmap)
3670 		newpte |= PG_U;
3671 	newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
3672 	if ((m->oflags & VPO_UNMANAGED) == 0)
3673 		newpte |= PG_MANAGED;
3674 
3675 	rw_wlock(&pvh_global_lock);
3676 	PMAP_LOCK(pmap);
3677 	sched_pin();
3678 	if (psind == 1) {
3679 		/* Assert the required virtual and physical alignment. */
3680 		KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
3681 		KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
3682 		rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m);
3683 		goto out;
3684 	}
3685 
3686 	pde = pmap_pde(pmap, va);
3687 	if (pmap != kernel_pmap) {
3688 		/*
3689 		 * va is for UVA.
3690 		 * In the case that a page table page is not resident,
3691 		 * we are creating it here.  pmap_allocpte() handles
3692 		 * demotion.
3693 		 */
3694 		mpte = pmap_allocpte(pmap, va, flags);
3695 		if (mpte == NULL) {
3696 			KASSERT((flags & PMAP_ENTER_NOSLEEP) != 0,
3697 			    ("pmap_allocpte failed with sleep allowed"));
3698 			rv = KERN_RESOURCE_SHORTAGE;
3699 			goto out;
3700 		}
3701 	} else {
3702 		/*
3703 		 * va is for KVA, so pmap_demote_pde() will never fail
3704 		 * to install a page table page.  PG_V is also
3705 		 * asserted by pmap_demote_pde().
3706 		 */
3707 		mpte = NULL;
3708 		KASSERT(pde != NULL && (*pde & PG_V) != 0,
3709 		    ("KVA %#x invalid pde pdir %#jx", va,
3710 		    (uintmax_t)pmap->pm_pdir[PTDPTDI]));
3711 		if ((*pde & PG_PS) != 0)
3712 			pmap_demote_pde(pmap, pde, va);
3713 	}
3714 	pte = pmap_pte_quick(pmap, va);
3715 
3716 	/*
3717 	 * Page Directory table entry is not valid, which should not
3718 	 * happen.  We should have either allocated the page table
3719 	 * page or demoted the existing mapping above.
3720 	 */
3721 	if (pte == NULL) {
3722 		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x",
3723 		    (uintmax_t)pmap->pm_pdir[PTDPTDI], va);
3724 	}
3725 
3726 	origpte = *pte;
3727 	pv = NULL;
3728 
3729 	/*
3730 	 * Is the specified virtual address already mapped?
3731 	 */
3732 	if ((origpte & PG_V) != 0) {
3733 		/*
3734 		 * Wiring change, just update stats. We don't worry about
3735 		 * wiring PT pages as they remain resident as long as there
3736 		 * are valid mappings in them. Hence, if a user page is wired,
3737 		 * the PT page will be also.
3738 		 */
3739 		if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
3740 			pmap->pm_stats.wired_count++;
3741 		else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
3742 			pmap->pm_stats.wired_count--;
3743 
3744 		/*
3745 		 * Remove the extra PT page reference.
3746 		 */
3747 		if (mpte != NULL) {
3748 			mpte->ref_count--;
3749 			KASSERT(mpte->ref_count > 0,
3750 			    ("pmap_enter: missing reference to page table page,"
3751 			     " va: 0x%x", va));
3752 		}
3753 
3754 		/*
3755 		 * Has the physical page changed?
3756 		 */
3757 		opa = origpte & PG_FRAME;
3758 		if (opa == pa) {
3759 			/*
3760 			 * No, might be a protection or wiring change.
3761 			 */
3762 			if ((origpte & PG_MANAGED) != 0 &&
3763 			    (newpte & PG_RW) != 0)
3764 				vm_page_aflag_set(m, PGA_WRITEABLE);
3765 			if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
3766 				goto unchanged;
3767 			goto validate;
3768 		}
3769 
3770 		/*
3771 		 * The physical page has changed.  Temporarily invalidate
3772 		 * the mapping.  This ensures that all threads sharing the
3773 		 * pmap keep a consistent view of the mapping, which is
3774 		 * necessary for the correct handling of COW faults.  It
3775 		 * also permits reuse of the old mapping's PV entry,
3776 		 * avoiding an allocation.
3777 		 *
3778 		 * For consistency, handle unmanaged mappings the same way.
3779 		 */
3780 		origpte = pte_load_clear(pte);
3781 		KASSERT((origpte & PG_FRAME) == opa,
3782 		    ("pmap_enter: unexpected pa update for %#x", va));
3783 		if ((origpte & PG_MANAGED) != 0) {
3784 			om = PHYS_TO_VM_PAGE(opa);
3785 
3786 			/*
3787 			 * The pmap lock is sufficient to synchronize with
3788 			 * concurrent calls to pmap_page_test_mappings() and
3789 			 * pmap_ts_referenced().
3790 			 */
3791 			if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3792 				vm_page_dirty(om);
3793 			if ((origpte & PG_A) != 0) {
3794 				pmap_invalidate_page_int(pmap, va);
3795 				vm_page_aflag_set(om, PGA_REFERENCED);
3796 			}
3797 			pv = pmap_pvh_remove(&om->md, pmap, va);
3798 			KASSERT(pv != NULL,
3799 			    ("pmap_enter: no PV entry for %#x", va));
3800 			if ((newpte & PG_MANAGED) == 0)
3801 				free_pv_entry(pmap, pv);
3802 			if ((om->a.flags & PGA_WRITEABLE) != 0 &&
3803 			    TAILQ_EMPTY(&om->md.pv_list) &&
3804 			    ((om->flags & PG_FICTITIOUS) != 0 ||
3805 			    TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
3806 				vm_page_aflag_clear(om, PGA_WRITEABLE);
3807 		} else {
3808 			/*
3809 			 * Since this mapping is unmanaged, assume that PG_A
3810 			 * is set.
3811 			 */
3812 			pmap_invalidate_page_int(pmap, va);
3813 		}
3814 		origpte = 0;
3815 	} else {
3816 		/*
3817 		 * Increment the counters.
3818 		 */
3819 		if ((newpte & PG_W) != 0)
3820 			pmap->pm_stats.wired_count++;
3821 		pmap->pm_stats.resident_count++;
3822 	}
3823 
3824 	/*
3825 	 * Enter on the PV list if part of our managed memory.
3826 	 */
3827 	if ((newpte & PG_MANAGED) != 0) {
3828 		if (pv == NULL) {
3829 			pv = get_pv_entry(pmap, FALSE);
3830 			pv->pv_va = va;
3831 		}
3832 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3833 		if ((newpte & PG_RW) != 0)
3834 			vm_page_aflag_set(m, PGA_WRITEABLE);
3835 	}
3836 
3837 	/*
3838 	 * Update the PTE.
3839 	 */
3840 	if ((origpte & PG_V) != 0) {
3841 validate:
3842 		origpte = pte_load_store(pte, newpte);
3843 		KASSERT((origpte & PG_FRAME) == pa,
3844 		    ("pmap_enter: unexpected pa update for %#x", va));
3845 		if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
3846 		    (PG_M | PG_RW)) {
3847 			if ((origpte & PG_MANAGED) != 0)
3848 				vm_page_dirty(m);
3849 
3850 			/*
3851 			 * Although the PTE may still have PG_RW set, TLB
3852 			 * invalidation may nonetheless be required because
3853 			 * the PTE no longer has PG_M set.
3854 			 */
3855 		}
3856 #ifdef PMAP_PAE_COMP
3857 		else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
3858 			/*
3859 			 * This PTE change does not require TLB invalidation.
3860 			 */
3861 			goto unchanged;
3862 		}
3863 #endif
3864 		if ((origpte & PG_A) != 0)
3865 			pmap_invalidate_page_int(pmap, va);
3866 	} else
3867 		pte_store_zero(pte, newpte);
3868 
3869 unchanged:
3870 
3871 #if VM_NRESERVLEVEL > 0
3872 	/*
3873 	 * If both the page table page and the reservation are fully
3874 	 * populated, then attempt promotion.
3875 	 */
3876 	if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
3877 	    pg_ps_enabled && (m->flags & PG_FICTITIOUS) == 0 &&
3878 	    vm_reserv_level_iffullpop(m) == 0)
3879 		pmap_promote_pde(pmap, pde, va);
3880 #endif
3881 
3882 	rv = KERN_SUCCESS;
3883 out:
3884 	sched_unpin();
3885 	rw_wunlock(&pvh_global_lock);
3886 	PMAP_UNLOCK(pmap);
3887 	return (rv);
3888 }
3889 
3890 /*
3891  * Tries to create a read- and/or execute-only 2 or 4 MB page mapping.  Returns
3892  * true if successful.  Returns false if (1) a mapping already exists at the
3893  * specified virtual address or (2) a PV entry cannot be allocated without
3894  * reclaiming another PV entry.
3895  */
3896 static bool
3897 pmap_enter_4mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3898 {
3899 	pd_entry_t newpde;
3900 
3901 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3902 	newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
3903 	    PG_PS | PG_V;
3904 	if ((m->oflags & VPO_UNMANAGED) == 0)
3905 		newpde |= PG_MANAGED;
3906 #ifdef PMAP_PAE_COMP
3907 	if ((prot & VM_PROT_EXECUTE) == 0 && !i386_read_exec)
3908 		newpde |= pg_nx;
3909 #endif
3910 	if (pmap != kernel_pmap)
3911 		newpde |= PG_U;
3912 	return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
3913 	    PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL) ==
3914 	    KERN_SUCCESS);
3915 }
3916 
3917 /*
3918  * Returns true if every page table entry in the page table page that maps
3919  * the specified kernel virtual address is zero.
3920  */
3921 static bool
3922 pmap_every_pte_zero(vm_offset_t va)
3923 {
3924 	pt_entry_t *pt_end, *pte;
3925 
3926 	KASSERT((va & PDRMASK) == 0, ("va is misaligned"));
3927 	pte = vtopte(va);
3928 	for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
3929 		if (*pte != 0)
3930 			return (false);
3931 	}
3932 	return (true);
3933 }
3934 
3935 /*
3936  * Tries to create the specified 2 or 4 MB page mapping.  Returns KERN_SUCCESS
3937  * if the mapping was created, and either KERN_FAILURE or
3938  * KERN_RESOURCE_SHORTAGE otherwise.  Returns KERN_FAILURE if
3939  * PMAP_ENTER_NOREPLACE was specified and a mapping already exists at the
3940  * specified virtual address.  Returns KERN_RESOURCE_SHORTAGE if
3941  * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
3942  *
3943  * The parameter "m" is only used when creating a managed, writeable mapping.
3944  */
3945 static int
3946 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
3947     vm_page_t m)
3948 {
3949 	struct spglist free;
3950 	pd_entry_t oldpde, *pde;
3951 	vm_page_t mt;
3952 
3953 	rw_assert(&pvh_global_lock, RA_WLOCKED);
3954 	KASSERT((newpde & (PG_M | PG_RW)) != PG_RW,
3955 	    ("pmap_enter_pde: newpde is missing PG_M"));
3956 	KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
3957 	    ("pmap_enter_pde: cannot create wired user mapping"));
3958 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3959 	pde = pmap_pde(pmap, va);
3960 	oldpde = *pde;
3961 	if ((oldpde & PG_V) != 0) {
3962 		if ((flags & PMAP_ENTER_NOREPLACE) != 0 && (pmap !=
3963 		    kernel_pmap || (oldpde & PG_PS) != 0 ||
3964 		    !pmap_every_pte_zero(va))) {
3965 			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3966 			    " in pmap %p", va, pmap);
3967 			return (KERN_FAILURE);
3968 		}
3969 		/* Break the existing mapping(s). */
3970 		SLIST_INIT(&free);
3971 		if ((oldpde & PG_PS) != 0) {
3972 			/*
3973 			 * If the PDE resulted from a promotion, then a
3974 			 * reserved PT page could be freed.
3975 			 */
3976 			(void)pmap_remove_pde(pmap, pde, va, &free);
3977 			if ((oldpde & PG_G) == 0)
3978 				pmap_invalidate_pde_page(pmap, va, oldpde);
3979 		} else {
3980 			if (pmap_remove_ptes(pmap, va, va + NBPDR, &free))
3981 		               pmap_invalidate_all_int(pmap);
3982 		}
3983 		if (pmap != kernel_pmap) {
3984 			vm_page_free_pages_toq(&free, true);
3985 			KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
3986 			    pde));
3987 		} else {
3988 			KASSERT(SLIST_EMPTY(&free),
3989 			    ("pmap_enter_pde: freed kernel page table page"));
3990 
3991 			/*
3992 			 * Both pmap_remove_pde() and pmap_remove_ptes() will
3993 			 * leave the kernel page table page zero filled.
3994 			 */
3995 			mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
3996 			if (pmap_insert_pt_page(pmap, mt, false))
3997 				panic("pmap_enter_pde: trie insert failed");
3998 		}
3999 	}
4000 	if ((newpde & PG_MANAGED) != 0) {
4001 		/*
4002 		 * Abort this mapping if its PV entry could not be created.
4003 		 */
4004 		if (!pmap_pv_insert_pde(pmap, va, newpde, flags)) {
4005 			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4006 			    " in pmap %p", va, pmap);
4007 			return (KERN_RESOURCE_SHORTAGE);
4008 		}
4009 		if ((newpde & PG_RW) != 0) {
4010 			for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4011 				vm_page_aflag_set(mt, PGA_WRITEABLE);
4012 		}
4013 	}
4014 
4015 	/*
4016 	 * Increment counters.
4017 	 */
4018 	if ((newpde & PG_W) != 0)
4019 		pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4020 	pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
4021 
4022 	/*
4023 	 * Map the superpage.  (This is not a promoted mapping; there will not
4024 	 * be any lingering 4KB page mappings in the TLB.)
4025 	 */
4026 	pde_store(pde, newpde);
4027 
4028 	pmap_pde_mappings++;
4029 	CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
4030 	    va, pmap);
4031 	return (KERN_SUCCESS);
4032 }
4033 
4034 /*
4035  * Maps a sequence of resident pages belonging to the same object.
4036  * The sequence begins with the given page m_start.  This page is
4037  * mapped at the given virtual address start.  Each subsequent page is
4038  * mapped at a virtual address that is offset from start by the same
4039  * amount as the page is offset from m_start within the object.  The
4040  * last page in the sequence is the page with the largest offset from
4041  * m_start that can be mapped at a virtual address less than the given
4042  * virtual address end.  Not every virtual page between start and end
4043  * is mapped; only those for which a resident page exists with the
4044  * corresponding offset from m_start are mapped.
4045  */
4046 static void
4047 __CONCAT(PMTYPE, enter_object)(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4048     vm_page_t m_start, vm_prot_t prot)
4049 {
4050 	vm_offset_t va;
4051 	vm_page_t m, mpte;
4052 	vm_pindex_t diff, psize;
4053 
4054 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
4055 
4056 	psize = atop(end - start);
4057 	mpte = NULL;
4058 	m = m_start;
4059 	rw_wlock(&pvh_global_lock);
4060 	PMAP_LOCK(pmap);
4061 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4062 		va = start + ptoa(diff);
4063 		if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4064 		    m->psind == 1 && pg_ps_enabled &&
4065 		    pmap_enter_4mpage(pmap, va, m, prot))
4066 			m = &m[NBPDR / PAGE_SIZE - 1];
4067 		else
4068 			mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4069 			    mpte);
4070 		m = TAILQ_NEXT(m, listq);
4071 	}
4072 	rw_wunlock(&pvh_global_lock);
4073 	PMAP_UNLOCK(pmap);
4074 }
4075 
4076 /*
4077  * this code makes some *MAJOR* assumptions:
4078  * 1. Current pmap & pmap exists.
4079  * 2. Not wired.
4080  * 3. Read access.
4081  * 4. No page table pages.
4082  * but is *MUCH* faster than pmap_enter...
4083  */
4084 
4085 static void
4086 __CONCAT(PMTYPE, enter_quick)(pmap_t pmap, vm_offset_t va, vm_page_t m,
4087     vm_prot_t prot)
4088 {
4089 
4090 	rw_wlock(&pvh_global_lock);
4091 	PMAP_LOCK(pmap);
4092 	(void)pmap_enter_quick_locked(pmap, va, m, prot, NULL);
4093 	rw_wunlock(&pvh_global_lock);
4094 	PMAP_UNLOCK(pmap);
4095 }
4096 
4097 static vm_page_t
4098 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4099     vm_prot_t prot, vm_page_t mpte)
4100 {
4101 	pt_entry_t newpte, *pte;
4102 
4103 	KASSERT(pmap != kernel_pmap || !VA_IS_CLEANMAP(va) ||
4104 	    (m->oflags & VPO_UNMANAGED) != 0,
4105 	    ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4106 	rw_assert(&pvh_global_lock, RA_WLOCKED);
4107 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4108 
4109 	/*
4110 	 * In the case that a page table page is not
4111 	 * resident, we are creating it here.
4112 	 */
4113 	if (pmap != kernel_pmap) {
4114 		u_int ptepindex;
4115 		pd_entry_t ptepa;
4116 
4117 		/*
4118 		 * Calculate pagetable page index
4119 		 */
4120 		ptepindex = va >> PDRSHIFT;
4121 		if (mpte && (mpte->pindex == ptepindex)) {
4122 			mpte->ref_count++;
4123 		} else {
4124 			/*
4125 			 * Get the page directory entry
4126 			 */
4127 			ptepa = pmap->pm_pdir[ptepindex];
4128 
4129 			/*
4130 			 * If the page table page is mapped, we just increment
4131 			 * the hold count, and activate it.
4132 			 */
4133 			if (ptepa) {
4134 				if (ptepa & PG_PS)
4135 					return (NULL);
4136 				mpte = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
4137 				mpte->ref_count++;
4138 			} else {
4139 				mpte = _pmap_allocpte(pmap, ptepindex,
4140 				    PMAP_ENTER_NOSLEEP);
4141 				if (mpte == NULL)
4142 					return (mpte);
4143 			}
4144 		}
4145 	} else {
4146 		mpte = NULL;
4147 	}
4148 
4149 	sched_pin();
4150 	pte = pmap_pte_quick(pmap, va);
4151 	if (*pte) {
4152 		if (mpte != NULL)
4153 			mpte->ref_count--;
4154 		sched_unpin();
4155 		return (NULL);
4156 	}
4157 
4158 	/*
4159 	 * Enter on the PV list if part of our managed memory.
4160 	 */
4161 	if ((m->oflags & VPO_UNMANAGED) == 0 &&
4162 	    !pmap_try_insert_pv_entry(pmap, va, m)) {
4163 		if (mpte != NULL)
4164 			pmap_abort_ptp(pmap, va, mpte);
4165 		sched_unpin();
4166 		return (NULL);
4167 	}
4168 
4169 	/*
4170 	 * Increment counters
4171 	 */
4172 	pmap->pm_stats.resident_count++;
4173 
4174 	newpte = VM_PAGE_TO_PHYS(m) | PG_V |
4175 	    pmap_cache_bits(pmap, m->md.pat_mode, 0);
4176 	if ((m->oflags & VPO_UNMANAGED) == 0)
4177 		newpte |= PG_MANAGED;
4178 #ifdef PMAP_PAE_COMP
4179 	if ((prot & VM_PROT_EXECUTE) == 0 && !i386_read_exec)
4180 		newpte |= pg_nx;
4181 #endif
4182 	if (pmap != kernel_pmap)
4183 		newpte |= PG_U;
4184 	pte_store_zero(pte, newpte);
4185 	sched_unpin();
4186 	return (mpte);
4187 }
4188 
4189 /*
4190  * Make a temporary mapping for a physical address.  This is only intended
4191  * to be used for panic dumps.
4192  */
4193 static void *
4194 __CONCAT(PMTYPE, kenter_temporary)(vm_paddr_t pa, int i)
4195 {
4196 	vm_offset_t va;
4197 
4198 	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4199 	pmap_kenter(va, pa);
4200 	invlpg(va);
4201 	return ((void *)crashdumpmap);
4202 }
4203 
4204 /*
4205  * This code maps large physical mmap regions into the
4206  * processor address space.  Note that some shortcuts
4207  * are taken, but the code works.
4208  */
4209 static void
4210 __CONCAT(PMTYPE, object_init_pt)(pmap_t pmap, vm_offset_t addr,
4211     vm_object_t object, vm_pindex_t pindex, vm_size_t size)
4212 {
4213 	pd_entry_t *pde;
4214 	vm_paddr_t pa, ptepa;
4215 	vm_page_t p;
4216 	int pat_mode;
4217 
4218 	VM_OBJECT_ASSERT_WLOCKED(object);
4219 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4220 	    ("pmap_object_init_pt: non-device object"));
4221 	if (pg_ps_enabled &&
4222 	    (addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4223 		if (!vm_object_populate(object, pindex, pindex + atop(size)))
4224 			return;
4225 		p = vm_page_lookup(object, pindex);
4226 		KASSERT(p->valid == VM_PAGE_BITS_ALL,
4227 		    ("pmap_object_init_pt: invalid page %p", p));
4228 		pat_mode = p->md.pat_mode;
4229 
4230 		/*
4231 		 * Abort the mapping if the first page is not physically
4232 		 * aligned to a 2/4MB page boundary.
4233 		 */
4234 		ptepa = VM_PAGE_TO_PHYS(p);
4235 		if (ptepa & (NBPDR - 1))
4236 			return;
4237 
4238 		/*
4239 		 * Skip the first page.  Abort the mapping if the rest of
4240 		 * the pages are not physically contiguous or have differing
4241 		 * memory attributes.
4242 		 */
4243 		p = TAILQ_NEXT(p, listq);
4244 		for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4245 		    pa += PAGE_SIZE) {
4246 			KASSERT(p->valid == VM_PAGE_BITS_ALL,
4247 			    ("pmap_object_init_pt: invalid page %p", p));
4248 			if (pa != VM_PAGE_TO_PHYS(p) ||
4249 			    pat_mode != p->md.pat_mode)
4250 				return;
4251 			p = TAILQ_NEXT(p, listq);
4252 		}
4253 
4254 		/*
4255 		 * Map using 2/4MB pages.  Since "ptepa" is 2/4M aligned and
4256 		 * "size" is a multiple of 2/4M, adding the PAT setting to
4257 		 * "pa" will not affect the termination of this loop.
4258 		 */
4259 		PMAP_LOCK(pmap);
4260 		for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4261 		    pa < ptepa + size; pa += NBPDR) {
4262 			pde = pmap_pde(pmap, addr);
4263 			if (*pde == 0) {
4264 				pde_store(pde, pa | PG_PS | PG_M | PG_A |
4265 				    PG_U | PG_RW | PG_V);
4266 				pmap->pm_stats.resident_count += NBPDR /
4267 				    PAGE_SIZE;
4268 				pmap_pde_mappings++;
4269 			}
4270 			/* Else continue on if the PDE is already valid. */
4271 			addr += NBPDR;
4272 		}
4273 		PMAP_UNLOCK(pmap);
4274 	}
4275 }
4276 
4277 /*
4278  *	Clear the wired attribute from the mappings for the specified range of
4279  *	addresses in the given pmap.  Every valid mapping within that range
4280  *	must have the wired attribute set.  In contrast, invalid mappings
4281  *	cannot have the wired attribute set, so they are ignored.
4282  *
4283  *	The wired attribute of the page table entry is not a hardware feature,
4284  *	so there is no need to invalidate any TLB entries.
4285  */
4286 static void
4287 __CONCAT(PMTYPE, unwire)(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4288 {
4289 	vm_offset_t pdnxt;
4290 	pd_entry_t *pde;
4291 	pt_entry_t *pte;
4292 	boolean_t pv_lists_locked;
4293 
4294 	if (pmap_is_current(pmap))
4295 		pv_lists_locked = FALSE;
4296 	else {
4297 		pv_lists_locked = TRUE;
4298 resume:
4299 		rw_wlock(&pvh_global_lock);
4300 		sched_pin();
4301 	}
4302 	PMAP_LOCK(pmap);
4303 	for (; sva < eva; sva = pdnxt) {
4304 		pdnxt = (sva + NBPDR) & ~PDRMASK;
4305 		if (pdnxt < sva)
4306 			pdnxt = eva;
4307 		pde = pmap_pde(pmap, sva);
4308 		if ((*pde & PG_V) == 0)
4309 			continue;
4310 		if ((*pde & PG_PS) != 0) {
4311 			if ((*pde & PG_W) == 0)
4312 				panic("pmap_unwire: pde %#jx is missing PG_W",
4313 				    (uintmax_t)*pde);
4314 
4315 			/*
4316 			 * Are we unwiring the entire large page?  If not,
4317 			 * demote the mapping and fall through.
4318 			 */
4319 			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
4320 				/*
4321 				 * Regardless of whether a pde (or pte) is 32
4322 				 * or 64 bits in size, PG_W is among the least
4323 				 * significant 32 bits.
4324 				 */
4325 				atomic_clear_int((u_int *)pde, PG_W);
4326 				pmap->pm_stats.wired_count -= NBPDR /
4327 				    PAGE_SIZE;
4328 				continue;
4329 			} else {
4330 				if (!pv_lists_locked) {
4331 					pv_lists_locked = TRUE;
4332 					if (!rw_try_wlock(&pvh_global_lock)) {
4333 						PMAP_UNLOCK(pmap);
4334 						/* Repeat sva. */
4335 						goto resume;
4336 					}
4337 					sched_pin();
4338 				}
4339 				if (!pmap_demote_pde(pmap, pde, sva))
4340 					panic("pmap_unwire: demotion failed");
4341 			}
4342 		}
4343 		if (pdnxt > eva)
4344 			pdnxt = eva;
4345 		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
4346 		    sva += PAGE_SIZE) {
4347 			if ((*pte & PG_V) == 0)
4348 				continue;
4349 			if ((*pte & PG_W) == 0)
4350 				panic("pmap_unwire: pte %#jx is missing PG_W",
4351 				    (uintmax_t)*pte);
4352 
4353 			/*
4354 			 * PG_W must be cleared atomically.  Although the pmap
4355 			 * lock synchronizes access to PG_W, another processor
4356 			 * could be setting PG_M and/or PG_A concurrently.
4357 			 *
4358 			 * PG_W is among the least significant 32 bits.
4359 			 */
4360 			atomic_clear_int((u_int *)pte, PG_W);
4361 			pmap->pm_stats.wired_count--;
4362 		}
4363 	}
4364 	if (pv_lists_locked) {
4365 		sched_unpin();
4366 		rw_wunlock(&pvh_global_lock);
4367 	}
4368 	PMAP_UNLOCK(pmap);
4369 }
4370 
4371 /*
4372  *	Copy the range specified by src_addr/len
4373  *	from the source map to the range dst_addr/len
4374  *	in the destination map.
4375  *
4376  *	This routine is only advisory and need not do anything.  Since
4377  *	current pmap is always the kernel pmap when executing in
4378  *	kernel, and we do not copy from the kernel pmap to a user
4379  *	pmap, this optimization is not usable in 4/4G full split i386
4380  *	world.
4381  */
4382 
4383 static void
4384 __CONCAT(PMTYPE, copy)(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
4385     vm_size_t len, vm_offset_t src_addr)
4386 {
4387 	pt_entry_t *src_pte, *dst_pte, ptetemp;
4388 	pd_entry_t srcptepaddr;
4389 	vm_page_t dstmpte, srcmpte;
4390 	vm_offset_t addr, end_addr, pdnxt;
4391 	u_int ptepindex;
4392 
4393 	if (dst_addr != src_addr)
4394 		return;
4395 
4396 	end_addr = src_addr + len;
4397 
4398 	rw_wlock(&pvh_global_lock);
4399 	if (dst_pmap < src_pmap) {
4400 		PMAP_LOCK(dst_pmap);
4401 		PMAP_LOCK(src_pmap);
4402 	} else {
4403 		PMAP_LOCK(src_pmap);
4404 		PMAP_LOCK(dst_pmap);
4405 	}
4406 	sched_pin();
4407 	for (addr = src_addr; addr < end_addr; addr = pdnxt) {
4408 		KASSERT(addr < PMAP_TRM_MIN_ADDRESS,
4409 		    ("pmap_copy: invalid to pmap_copy the trampoline"));
4410 
4411 		pdnxt = (addr + NBPDR) & ~PDRMASK;
4412 		if (pdnxt < addr)
4413 			pdnxt = end_addr;
4414 		ptepindex = addr >> PDRSHIFT;
4415 
4416 		srcptepaddr = src_pmap->pm_pdir[ptepindex];
4417 		if (srcptepaddr == 0)
4418 			continue;
4419 
4420 		if (srcptepaddr & PG_PS) {
4421 			if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
4422 				continue;
4423 			if (dst_pmap->pm_pdir[ptepindex] == 0 &&
4424 			    ((srcptepaddr & PG_MANAGED) == 0 ||
4425 			    pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
4426 			    PMAP_ENTER_NORECLAIM))) {
4427 				dst_pmap->pm_pdir[ptepindex] = srcptepaddr &
4428 				    ~PG_W;
4429 				dst_pmap->pm_stats.resident_count +=
4430 				    NBPDR / PAGE_SIZE;
4431 				pmap_pde_mappings++;
4432 			}
4433 			continue;
4434 		}
4435 
4436 		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr & PG_FRAME);
4437 		KASSERT(srcmpte->ref_count > 0,
4438 		    ("pmap_copy: source page table page is unused"));
4439 
4440 		if (pdnxt > end_addr)
4441 			pdnxt = end_addr;
4442 
4443 		src_pte = pmap_pte_quick3(src_pmap, addr);
4444 		while (addr < pdnxt) {
4445 			ptetemp = *src_pte;
4446 			/*
4447 			 * we only virtual copy managed pages
4448 			 */
4449 			if ((ptetemp & PG_MANAGED) != 0) {
4450 				dstmpte = pmap_allocpte(dst_pmap, addr,
4451 				    PMAP_ENTER_NOSLEEP);
4452 				if (dstmpte == NULL)
4453 					goto out;
4454 				dst_pte = pmap_pte_quick(dst_pmap, addr);
4455 				if (*dst_pte == 0 &&
4456 				    pmap_try_insert_pv_entry(dst_pmap, addr,
4457 				    PHYS_TO_VM_PAGE(ptetemp & PG_FRAME))) {
4458 					/*
4459 					 * Clear the wired, modified, and
4460 					 * accessed (referenced) bits
4461 					 * during the copy.
4462 					 */
4463 					*dst_pte = ptetemp & ~(PG_W | PG_M |
4464 					    PG_A);
4465 					dst_pmap->pm_stats.resident_count++;
4466 				} else {
4467 					pmap_abort_ptp(dst_pmap, addr, dstmpte);
4468 					goto out;
4469 				}
4470 				if (dstmpte->ref_count >= srcmpte->ref_count)
4471 					break;
4472 			}
4473 			addr += PAGE_SIZE;
4474 			src_pte++;
4475 		}
4476 	}
4477 out:
4478 	sched_unpin();
4479 	rw_wunlock(&pvh_global_lock);
4480 	PMAP_UNLOCK(src_pmap);
4481 	PMAP_UNLOCK(dst_pmap);
4482 }
4483 
4484 /*
4485  * Zero 1 page of virtual memory mapped from a hardware page by the caller.
4486  */
4487 static __inline void
4488 pagezero(void *page)
4489 {
4490 #if defined(I686_CPU)
4491 	if (cpu_class == CPUCLASS_686) {
4492 		if (cpu_feature & CPUID_SSE2)
4493 			sse2_pagezero(page);
4494 		else
4495 			i686_pagezero(page);
4496 	} else
4497 #endif
4498 		bzero(page, PAGE_SIZE);
4499 }
4500 
4501 /*
4502  * Zero the specified hardware page.
4503  */
4504 static void
4505 __CONCAT(PMTYPE, zero_page)(vm_page_t m)
4506 {
4507 	pt_entry_t *cmap_pte2;
4508 	struct pcpu *pc;
4509 
4510 	sched_pin();
4511 	pc = get_pcpu();
4512 	cmap_pte2 = pc->pc_cmap_pte2;
4513 	mtx_lock(&pc->pc_cmap_lock);
4514 	if (*cmap_pte2)
4515 		panic("pmap_zero_page: CMAP2 busy");
4516 	*cmap_pte2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4517 	    pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4518 	invlcaddr(pc->pc_cmap_addr2);
4519 	pagezero(pc->pc_cmap_addr2);
4520 	*cmap_pte2 = 0;
4521 
4522 	/*
4523 	 * Unpin the thread before releasing the lock.  Otherwise the thread
4524 	 * could be rescheduled while still bound to the current CPU, only
4525 	 * to unpin itself immediately upon resuming execution.
4526 	 */
4527 	sched_unpin();
4528 	mtx_unlock(&pc->pc_cmap_lock);
4529 }
4530 
4531 /*
4532  * Zero an an area within a single hardware page.  off and size must not
4533  * cover an area beyond a single hardware page.
4534  */
4535 static void
4536 __CONCAT(PMTYPE, zero_page_area)(vm_page_t m, int off, int size)
4537 {
4538 	pt_entry_t *cmap_pte2;
4539 	struct pcpu *pc;
4540 
4541 	sched_pin();
4542 	pc = get_pcpu();
4543 	cmap_pte2 = pc->pc_cmap_pte2;
4544 	mtx_lock(&pc->pc_cmap_lock);
4545 	if (*cmap_pte2)
4546 		panic("pmap_zero_page_area: CMAP2 busy");
4547 	*cmap_pte2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4548 	    pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4549 	invlcaddr(pc->pc_cmap_addr2);
4550 	if (off == 0 && size == PAGE_SIZE)
4551 		pagezero(pc->pc_cmap_addr2);
4552 	else
4553 		bzero(pc->pc_cmap_addr2 + off, size);
4554 	*cmap_pte2 = 0;
4555 	sched_unpin();
4556 	mtx_unlock(&pc->pc_cmap_lock);
4557 }
4558 
4559 /*
4560  * Copy 1 specified hardware page to another.
4561  */
4562 static void
4563 __CONCAT(PMTYPE, copy_page)(vm_page_t src, vm_page_t dst)
4564 {
4565 	pt_entry_t *cmap_pte1, *cmap_pte2;
4566 	struct pcpu *pc;
4567 
4568 	sched_pin();
4569 	pc = get_pcpu();
4570 	cmap_pte1 = pc->pc_cmap_pte1;
4571 	cmap_pte2 = pc->pc_cmap_pte2;
4572 	mtx_lock(&pc->pc_cmap_lock);
4573 	if (*cmap_pte1)
4574 		panic("pmap_copy_page: CMAP1 busy");
4575 	if (*cmap_pte2)
4576 		panic("pmap_copy_page: CMAP2 busy");
4577 	*cmap_pte1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A |
4578 	    pmap_cache_bits(kernel_pmap, src->md.pat_mode, 0);
4579 	invlcaddr(pc->pc_cmap_addr1);
4580 	*cmap_pte2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M |
4581 	    pmap_cache_bits(kernel_pmap, dst->md.pat_mode, 0);
4582 	invlcaddr(pc->pc_cmap_addr2);
4583 	bcopy(pc->pc_cmap_addr1, pc->pc_cmap_addr2, PAGE_SIZE);
4584 	*cmap_pte1 = 0;
4585 	*cmap_pte2 = 0;
4586 	sched_unpin();
4587 	mtx_unlock(&pc->pc_cmap_lock);
4588 }
4589 
4590 static void
4591 __CONCAT(PMTYPE, copy_pages)(vm_page_t ma[], vm_offset_t a_offset,
4592     vm_page_t mb[], vm_offset_t b_offset, int xfersize)
4593 {
4594 	vm_page_t a_pg, b_pg;
4595 	char *a_cp, *b_cp;
4596 	vm_offset_t a_pg_offset, b_pg_offset;
4597 	pt_entry_t *cmap_pte1, *cmap_pte2;
4598 	struct pcpu *pc;
4599 	int cnt;
4600 
4601 	sched_pin();
4602 	pc = get_pcpu();
4603 	cmap_pte1 = pc->pc_cmap_pte1;
4604 	cmap_pte2 = pc->pc_cmap_pte2;
4605 	mtx_lock(&pc->pc_cmap_lock);
4606 	if (*cmap_pte1 != 0)
4607 		panic("pmap_copy_pages: CMAP1 busy");
4608 	if (*cmap_pte2 != 0)
4609 		panic("pmap_copy_pages: CMAP2 busy");
4610 	while (xfersize > 0) {
4611 		a_pg = ma[a_offset >> PAGE_SHIFT];
4612 		a_pg_offset = a_offset & PAGE_MASK;
4613 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
4614 		b_pg = mb[b_offset >> PAGE_SHIFT];
4615 		b_pg_offset = b_offset & PAGE_MASK;
4616 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
4617 		*cmap_pte1 = PG_V | VM_PAGE_TO_PHYS(a_pg) | PG_A |
4618 		    pmap_cache_bits(kernel_pmap, a_pg->md.pat_mode, 0);
4619 		invlcaddr(pc->pc_cmap_addr1);
4620 		*cmap_pte2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(b_pg) | PG_A |
4621 		    PG_M | pmap_cache_bits(kernel_pmap, b_pg->md.pat_mode, 0);
4622 		invlcaddr(pc->pc_cmap_addr2);
4623 		a_cp = pc->pc_cmap_addr1 + a_pg_offset;
4624 		b_cp = pc->pc_cmap_addr2 + b_pg_offset;
4625 		bcopy(a_cp, b_cp, cnt);
4626 		a_offset += cnt;
4627 		b_offset += cnt;
4628 		xfersize -= cnt;
4629 	}
4630 	*cmap_pte1 = 0;
4631 	*cmap_pte2 = 0;
4632 	sched_unpin();
4633 	mtx_unlock(&pc->pc_cmap_lock);
4634 }
4635 
4636 /*
4637  * Returns true if the pmap's pv is one of the first
4638  * 16 pvs linked to from this page.  This count may
4639  * be changed upwards or downwards in the future; it
4640  * is only necessary that true be returned for a small
4641  * subset of pmaps for proper page aging.
4642  */
4643 static boolean_t
4644 __CONCAT(PMTYPE, page_exists_quick)(pmap_t pmap, vm_page_t m)
4645 {
4646 	struct md_page *pvh;
4647 	pv_entry_t pv;
4648 	int loops = 0;
4649 	boolean_t rv;
4650 
4651 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4652 	    ("pmap_page_exists_quick: page %p is not managed", m));
4653 	rv = FALSE;
4654 	rw_wlock(&pvh_global_lock);
4655 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4656 		if (PV_PMAP(pv) == pmap) {
4657 			rv = TRUE;
4658 			break;
4659 		}
4660 		loops++;
4661 		if (loops >= 16)
4662 			break;
4663 	}
4664 	if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4665 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4666 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4667 			if (PV_PMAP(pv) == pmap) {
4668 				rv = TRUE;
4669 				break;
4670 			}
4671 			loops++;
4672 			if (loops >= 16)
4673 				break;
4674 		}
4675 	}
4676 	rw_wunlock(&pvh_global_lock);
4677 	return (rv);
4678 }
4679 
4680 /*
4681  *	pmap_page_wired_mappings:
4682  *
4683  *	Return the number of managed mappings to the given physical page
4684  *	that are wired.
4685  */
4686 static int
4687 __CONCAT(PMTYPE, page_wired_mappings)(vm_page_t m)
4688 {
4689 	int count;
4690 
4691 	count = 0;
4692 	if ((m->oflags & VPO_UNMANAGED) != 0)
4693 		return (count);
4694 	rw_wlock(&pvh_global_lock);
4695 	count = pmap_pvh_wired_mappings(&m->md, count);
4696 	if ((m->flags & PG_FICTITIOUS) == 0) {
4697 	    count = pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)),
4698 	        count);
4699 	}
4700 	rw_wunlock(&pvh_global_lock);
4701 	return (count);
4702 }
4703 
4704 /*
4705  *	pmap_pvh_wired_mappings:
4706  *
4707  *	Return the updated number "count" of managed mappings that are wired.
4708  */
4709 static int
4710 pmap_pvh_wired_mappings(struct md_page *pvh, int count)
4711 {
4712 	pmap_t pmap;
4713 	pt_entry_t *pte;
4714 	pv_entry_t pv;
4715 
4716 	rw_assert(&pvh_global_lock, RA_WLOCKED);
4717 	sched_pin();
4718 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4719 		pmap = PV_PMAP(pv);
4720 		PMAP_LOCK(pmap);
4721 		pte = pmap_pte_quick(pmap, pv->pv_va);
4722 		if ((*pte & PG_W) != 0)
4723 			count++;
4724 		PMAP_UNLOCK(pmap);
4725 	}
4726 	sched_unpin();
4727 	return (count);
4728 }
4729 
4730 /*
4731  * Returns TRUE if the given page is mapped individually or as part of
4732  * a 4mpage.  Otherwise, returns FALSE.
4733  */
4734 static boolean_t
4735 __CONCAT(PMTYPE, page_is_mapped)(vm_page_t m)
4736 {
4737 	boolean_t rv;
4738 
4739 	if ((m->oflags & VPO_UNMANAGED) != 0)
4740 		return (FALSE);
4741 	rw_wlock(&pvh_global_lock);
4742 	rv = !TAILQ_EMPTY(&m->md.pv_list) ||
4743 	    ((m->flags & PG_FICTITIOUS) == 0 &&
4744 	    !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
4745 	rw_wunlock(&pvh_global_lock);
4746 	return (rv);
4747 }
4748 
4749 /*
4750  * Remove all pages from specified address space
4751  * this aids process exit speeds.  Also, this code
4752  * is special cased for current process only, but
4753  * can have the more generic (and slightly slower)
4754  * mode enabled.  This is much faster than pmap_remove
4755  * in the case of running down an entire address space.
4756  */
4757 static void
4758 __CONCAT(PMTYPE, remove_pages)(pmap_t pmap)
4759 {
4760 	pt_entry_t *pte, tpte;
4761 	vm_page_t m, mpte, mt;
4762 	pv_entry_t pv;
4763 	struct md_page *pvh;
4764 	struct pv_chunk *pc, *npc;
4765 	struct spglist free;
4766 	int field, idx;
4767 	int32_t bit;
4768 	uint32_t inuse, bitmask;
4769 	int allfree;
4770 
4771 	if (pmap != PCPU_GET(curpmap)) {
4772 		printf("warning: pmap_remove_pages called with non-current pmap\n");
4773 		return;
4774 	}
4775 	SLIST_INIT(&free);
4776 	rw_wlock(&pvh_global_lock);
4777 	PMAP_LOCK(pmap);
4778 	sched_pin();
4779 	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
4780 		KASSERT(pc->pc_pmap == pmap, ("Wrong pmap %p %p", pmap,
4781 		    pc->pc_pmap));
4782 		allfree = 1;
4783 		for (field = 0; field < _NPCM; field++) {
4784 			inuse = ~pc->pc_map[field] & pc_freemask[field];
4785 			while (inuse != 0) {
4786 				bit = bsfl(inuse);
4787 				bitmask = 1UL << bit;
4788 				idx = field * 32 + bit;
4789 				pv = &pc->pc_pventry[idx];
4790 				inuse &= ~bitmask;
4791 
4792 				pte = pmap_pde(pmap, pv->pv_va);
4793 				tpte = *pte;
4794 				if ((tpte & PG_PS) == 0) {
4795 					pte = pmap_pte_quick(pmap, pv->pv_va);
4796 					tpte = *pte & ~PG_PTE_PAT;
4797 				}
4798 
4799 				if (tpte == 0) {
4800 					printf(
4801 					    "TPTE at %p  IS ZERO @ VA %08x\n",
4802 					    pte, pv->pv_va);
4803 					panic("bad pte");
4804 				}
4805 
4806 /*
4807  * We cannot remove wired pages from a process' mapping at this time
4808  */
4809 				if (tpte & PG_W) {
4810 					allfree = 0;
4811 					continue;
4812 				}
4813 
4814 				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
4815 				KASSERT(m->phys_addr == (tpte & PG_FRAME),
4816 				    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
4817 				    m, (uintmax_t)m->phys_addr,
4818 				    (uintmax_t)tpte));
4819 
4820 				KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
4821 				    m < &vm_page_array[vm_page_array_size],
4822 				    ("pmap_remove_pages: bad tpte %#jx",
4823 				    (uintmax_t)tpte));
4824 
4825 				pte_clear(pte);
4826 
4827 				/*
4828 				 * Update the vm_page_t clean/reference bits.
4829 				 */
4830 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4831 					if ((tpte & PG_PS) != 0) {
4832 						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4833 							vm_page_dirty(mt);
4834 					} else
4835 						vm_page_dirty(m);
4836 				}
4837 
4838 				/* Mark free */
4839 				PV_STAT(pv_entry_frees++);
4840 				PV_STAT(pv_entry_spare++);
4841 				pv_entry_count--;
4842 				pc->pc_map[field] |= bitmask;
4843 				if ((tpte & PG_PS) != 0) {
4844 					pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
4845 					pvh = pa_to_pvh(tpte & PG_PS_FRAME);
4846 					TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4847 					if (TAILQ_EMPTY(&pvh->pv_list)) {
4848 						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4849 							if (TAILQ_EMPTY(&mt->md.pv_list))
4850 								vm_page_aflag_clear(mt, PGA_WRITEABLE);
4851 					}
4852 					mpte = pmap_remove_pt_page(pmap, pv->pv_va);
4853 					if (mpte != NULL) {
4854 						KASSERT(mpte->valid == VM_PAGE_BITS_ALL,
4855 						    ("pmap_remove_pages: pte page not promoted"));
4856 						pmap->pm_stats.resident_count--;
4857 						KASSERT(mpte->ref_count == NPTEPG,
4858 						    ("pmap_remove_pages: pte page ref count error"));
4859 						mpte->ref_count = 0;
4860 						pmap_add_delayed_free_list(mpte, &free, FALSE);
4861 					}
4862 				} else {
4863 					pmap->pm_stats.resident_count--;
4864 					TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4865 					if (TAILQ_EMPTY(&m->md.pv_list) &&
4866 					    (m->flags & PG_FICTITIOUS) == 0) {
4867 						pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4868 						if (TAILQ_EMPTY(&pvh->pv_list))
4869 							vm_page_aflag_clear(m, PGA_WRITEABLE);
4870 					}
4871 					pmap_unuse_pt(pmap, pv->pv_va, &free);
4872 				}
4873 			}
4874 		}
4875 		if (allfree) {
4876 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4877 			free_pv_chunk(pc);
4878 		}
4879 	}
4880 	sched_unpin();
4881 	pmap_invalidate_all_int(pmap);
4882 	rw_wunlock(&pvh_global_lock);
4883 	PMAP_UNLOCK(pmap);
4884 	vm_page_free_pages_toq(&free, true);
4885 }
4886 
4887 /*
4888  *	pmap_is_modified:
4889  *
4890  *	Return whether or not the specified physical page was modified
4891  *	in any physical maps.
4892  */
4893 static boolean_t
4894 __CONCAT(PMTYPE, is_modified)(vm_page_t m)
4895 {
4896 	boolean_t rv;
4897 
4898 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4899 	    ("pmap_is_modified: page %p is not managed", m));
4900 
4901 	/*
4902 	 * If the page is not busied then this check is racy.
4903 	 */
4904 	if (!pmap_page_is_write_mapped(m))
4905 		return (FALSE);
4906 	rw_wlock(&pvh_global_lock);
4907 	rv = pmap_is_modified_pvh(&m->md) ||
4908 	    ((m->flags & PG_FICTITIOUS) == 0 &&
4909 	    pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4910 	rw_wunlock(&pvh_global_lock);
4911 	return (rv);
4912 }
4913 
4914 /*
4915  * Returns TRUE if any of the given mappings were used to modify
4916  * physical memory.  Otherwise, returns FALSE.  Both page and 2mpage
4917  * mappings are supported.
4918  */
4919 static boolean_t
4920 pmap_is_modified_pvh(struct md_page *pvh)
4921 {
4922 	pv_entry_t pv;
4923 	pt_entry_t *pte;
4924 	pmap_t pmap;
4925 	boolean_t rv;
4926 
4927 	rw_assert(&pvh_global_lock, RA_WLOCKED);
4928 	rv = FALSE;
4929 	sched_pin();
4930 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4931 		pmap = PV_PMAP(pv);
4932 		PMAP_LOCK(pmap);
4933 		pte = pmap_pte_quick(pmap, pv->pv_va);
4934 		rv = (*pte & (PG_M | PG_RW)) == (PG_M | PG_RW);
4935 		PMAP_UNLOCK(pmap);
4936 		if (rv)
4937 			break;
4938 	}
4939 	sched_unpin();
4940 	return (rv);
4941 }
4942 
4943 /*
4944  *	pmap_is_prefaultable:
4945  *
4946  *	Return whether or not the specified virtual address is elgible
4947  *	for prefault.
4948  */
4949 static boolean_t
4950 __CONCAT(PMTYPE, is_prefaultable)(pmap_t pmap, vm_offset_t addr)
4951 {
4952 	pd_entry_t pde;
4953 	boolean_t rv;
4954 
4955 	rv = FALSE;
4956 	PMAP_LOCK(pmap);
4957 	pde = *pmap_pde(pmap, addr);
4958 	if (pde != 0 && (pde & PG_PS) == 0)
4959 		rv = pmap_pte_ufast(pmap, addr, pde) == 0;
4960 	PMAP_UNLOCK(pmap);
4961 	return (rv);
4962 }
4963 
4964 /*
4965  *	pmap_is_referenced:
4966  *
4967  *	Return whether or not the specified physical page was referenced
4968  *	in any physical maps.
4969  */
4970 static boolean_t
4971 __CONCAT(PMTYPE, is_referenced)(vm_page_t m)
4972 {
4973 	boolean_t rv;
4974 
4975 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4976 	    ("pmap_is_referenced: page %p is not managed", m));
4977 	rw_wlock(&pvh_global_lock);
4978 	rv = pmap_is_referenced_pvh(&m->md) ||
4979 	    ((m->flags & PG_FICTITIOUS) == 0 &&
4980 	    pmap_is_referenced_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4981 	rw_wunlock(&pvh_global_lock);
4982 	return (rv);
4983 }
4984 
4985 /*
4986  * Returns TRUE if any of the given mappings were referenced and FALSE
4987  * otherwise.  Both page and 4mpage mappings are supported.
4988  */
4989 static boolean_t
4990 pmap_is_referenced_pvh(struct md_page *pvh)
4991 {
4992 	pv_entry_t pv;
4993 	pt_entry_t *pte;
4994 	pmap_t pmap;
4995 	boolean_t rv;
4996 
4997 	rw_assert(&pvh_global_lock, RA_WLOCKED);
4998 	rv = FALSE;
4999 	sched_pin();
5000 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5001 		pmap = PV_PMAP(pv);
5002 		PMAP_LOCK(pmap);
5003 		pte = pmap_pte_quick(pmap, pv->pv_va);
5004 		rv = (*pte & (PG_A | PG_V)) == (PG_A | PG_V);
5005 		PMAP_UNLOCK(pmap);
5006 		if (rv)
5007 			break;
5008 	}
5009 	sched_unpin();
5010 	return (rv);
5011 }
5012 
5013 /*
5014  * Clear the write and modified bits in each of the given page's mappings.
5015  */
5016 static void
5017 __CONCAT(PMTYPE, remove_write)(vm_page_t m)
5018 {
5019 	struct md_page *pvh;
5020 	pv_entry_t next_pv, pv;
5021 	pmap_t pmap;
5022 	pd_entry_t *pde;
5023 	pt_entry_t oldpte, *pte;
5024 	vm_offset_t va;
5025 
5026 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5027 	    ("pmap_remove_write: page %p is not managed", m));
5028 	vm_page_assert_busied(m);
5029 
5030 	if (!pmap_page_is_write_mapped(m))
5031 		return;
5032 	rw_wlock(&pvh_global_lock);
5033 	sched_pin();
5034 	if ((m->flags & PG_FICTITIOUS) != 0)
5035 		goto small_mappings;
5036 	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5037 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5038 		va = pv->pv_va;
5039 		pmap = PV_PMAP(pv);
5040 		PMAP_LOCK(pmap);
5041 		pde = pmap_pde(pmap, va);
5042 		if ((*pde & PG_RW) != 0)
5043 			(void)pmap_demote_pde(pmap, pde, va);
5044 		PMAP_UNLOCK(pmap);
5045 	}
5046 small_mappings:
5047 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5048 		pmap = PV_PMAP(pv);
5049 		PMAP_LOCK(pmap);
5050 		pde = pmap_pde(pmap, pv->pv_va);
5051 		KASSERT((*pde & PG_PS) == 0, ("pmap_clear_write: found"
5052 		    " a 4mpage in page %p's pv list", m));
5053 		pte = pmap_pte_quick(pmap, pv->pv_va);
5054 retry:
5055 		oldpte = *pte;
5056 		if ((oldpte & PG_RW) != 0) {
5057 			/*
5058 			 * Regardless of whether a pte is 32 or 64 bits
5059 			 * in size, PG_RW and PG_M are among the least
5060 			 * significant 32 bits.
5061 			 */
5062 			if (!atomic_cmpset_int((u_int *)pte, oldpte,
5063 			    oldpte & ~(PG_RW | PG_M)))
5064 				goto retry;
5065 			if ((oldpte & PG_M) != 0)
5066 				vm_page_dirty(m);
5067 			pmap_invalidate_page_int(pmap, pv->pv_va);
5068 		}
5069 		PMAP_UNLOCK(pmap);
5070 	}
5071 	vm_page_aflag_clear(m, PGA_WRITEABLE);
5072 	sched_unpin();
5073 	rw_wunlock(&pvh_global_lock);
5074 }
5075 
5076 /*
5077  *	pmap_ts_referenced:
5078  *
5079  *	Return a count of reference bits for a page, clearing those bits.
5080  *	It is not necessary for every reference bit to be cleared, but it
5081  *	is necessary that 0 only be returned when there are truly no
5082  *	reference bits set.
5083  *
5084  *	As an optimization, update the page's dirty field if a modified bit is
5085  *	found while counting reference bits.  This opportunistic update can be
5086  *	performed at low cost and can eliminate the need for some future calls
5087  *	to pmap_is_modified().  However, since this function stops after
5088  *	finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5089  *	dirty pages.  Those dirty pages will only be detected by a future call
5090  *	to pmap_is_modified().
5091  */
5092 static int
5093 __CONCAT(PMTYPE, ts_referenced)(vm_page_t m)
5094 {
5095 	struct md_page *pvh;
5096 	pv_entry_t pv, pvf;
5097 	pmap_t pmap;
5098 	pd_entry_t *pde;
5099 	pt_entry_t *pte;
5100 	vm_paddr_t pa;
5101 	int rtval = 0;
5102 
5103 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5104 	    ("pmap_ts_referenced: page %p is not managed", m));
5105 	pa = VM_PAGE_TO_PHYS(m);
5106 	pvh = pa_to_pvh(pa);
5107 	rw_wlock(&pvh_global_lock);
5108 	sched_pin();
5109 	if ((m->flags & PG_FICTITIOUS) != 0 ||
5110 	    (pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5111 		goto small_mappings;
5112 	pv = pvf;
5113 	do {
5114 		pmap = PV_PMAP(pv);
5115 		PMAP_LOCK(pmap);
5116 		pde = pmap_pde(pmap, pv->pv_va);
5117 		if ((*pde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5118 			/*
5119 			 * Although "*pde" is mapping a 2/4MB page, because
5120 			 * this function is called at a 4KB page granularity,
5121 			 * we only update the 4KB page under test.
5122 			 */
5123 			vm_page_dirty(m);
5124 		}
5125 		if ((*pde & PG_A) != 0) {
5126 			/*
5127 			 * Since this reference bit is shared by either 1024
5128 			 * or 512 4KB pages, it should not be cleared every
5129 			 * time it is tested.  Apply a simple "hash" function
5130 			 * on the physical page number, the virtual superpage
5131 			 * number, and the pmap address to select one 4KB page
5132 			 * out of the 1024 or 512 on which testing the
5133 			 * reference bit will result in clearing that bit.
5134 			 * This function is designed to avoid the selection of
5135 			 * the same 4KB page for every 2- or 4MB page mapping.
5136 			 *
5137 			 * On demotion, a mapping that hasn't been referenced
5138 			 * is simply destroyed.  To avoid the possibility of a
5139 			 * subsequent page fault on a demoted wired mapping,
5140 			 * always leave its reference bit set.  Moreover,
5141 			 * since the superpage is wired, the current state of
5142 			 * its reference bit won't affect page replacement.
5143 			 */
5144 			if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5145 			    (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5146 			    (*pde & PG_W) == 0) {
5147 				atomic_clear_int((u_int *)pde, PG_A);
5148 				pmap_invalidate_page_int(pmap, pv->pv_va);
5149 			}
5150 			rtval++;
5151 		}
5152 		PMAP_UNLOCK(pmap);
5153 		/* Rotate the PV list if it has more than one entry. */
5154 		if (TAILQ_NEXT(pv, pv_next) != NULL) {
5155 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5156 			TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5157 		}
5158 		if (rtval >= PMAP_TS_REFERENCED_MAX)
5159 			goto out;
5160 	} while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5161 small_mappings:
5162 	if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5163 		goto out;
5164 	pv = pvf;
5165 	do {
5166 		pmap = PV_PMAP(pv);
5167 		PMAP_LOCK(pmap);
5168 		pde = pmap_pde(pmap, pv->pv_va);
5169 		KASSERT((*pde & PG_PS) == 0,
5170 		    ("pmap_ts_referenced: found a 4mpage in page %p's pv list",
5171 		    m));
5172 		pte = pmap_pte_quick(pmap, pv->pv_va);
5173 		if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5174 			vm_page_dirty(m);
5175 		if ((*pte & PG_A) != 0) {
5176 			atomic_clear_int((u_int *)pte, PG_A);
5177 			pmap_invalidate_page_int(pmap, pv->pv_va);
5178 			rtval++;
5179 		}
5180 		PMAP_UNLOCK(pmap);
5181 		/* Rotate the PV list if it has more than one entry. */
5182 		if (TAILQ_NEXT(pv, pv_next) != NULL) {
5183 			TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5184 			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5185 		}
5186 	} while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && rtval <
5187 	    PMAP_TS_REFERENCED_MAX);
5188 out:
5189 	sched_unpin();
5190 	rw_wunlock(&pvh_global_lock);
5191 	return (rtval);
5192 }
5193 
5194 /*
5195  *	Apply the given advice to the specified range of addresses within the
5196  *	given pmap.  Depending on the advice, clear the referenced and/or
5197  *	modified flags in each mapping and set the mapped page's dirty field.
5198  */
5199 static void
5200 __CONCAT(PMTYPE, advise)(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
5201     int advice)
5202 {
5203 	pd_entry_t oldpde, *pde;
5204 	pt_entry_t *pte;
5205 	vm_offset_t va, pdnxt;
5206 	vm_page_t m;
5207 	bool anychanged, pv_lists_locked;
5208 
5209 	if (advice != MADV_DONTNEED && advice != MADV_FREE)
5210 		return;
5211 	if (pmap_is_current(pmap))
5212 		pv_lists_locked = false;
5213 	else {
5214 		pv_lists_locked = true;
5215 resume:
5216 		rw_wlock(&pvh_global_lock);
5217 		sched_pin();
5218 	}
5219 	anychanged = false;
5220 	PMAP_LOCK(pmap);
5221 	for (; sva < eva; sva = pdnxt) {
5222 		pdnxt = (sva + NBPDR) & ~PDRMASK;
5223 		if (pdnxt < sva)
5224 			pdnxt = eva;
5225 		pde = pmap_pde(pmap, sva);
5226 		oldpde = *pde;
5227 		if ((oldpde & PG_V) == 0)
5228 			continue;
5229 		else if ((oldpde & PG_PS) != 0) {
5230 			if ((oldpde & PG_MANAGED) == 0)
5231 				continue;
5232 			if (!pv_lists_locked) {
5233 				pv_lists_locked = true;
5234 				if (!rw_try_wlock(&pvh_global_lock)) {
5235 					if (anychanged)
5236 						pmap_invalidate_all_int(pmap);
5237 					PMAP_UNLOCK(pmap);
5238 					goto resume;
5239 				}
5240 				sched_pin();
5241 			}
5242 			if (!pmap_demote_pde(pmap, pde, sva)) {
5243 				/*
5244 				 * The large page mapping was destroyed.
5245 				 */
5246 				continue;
5247 			}
5248 
5249 			/*
5250 			 * Unless the page mappings are wired, remove the
5251 			 * mapping to a single page so that a subsequent
5252 			 * access may repromote.  Choosing the last page
5253 			 * within the address range [sva, min(pdnxt, eva))
5254 			 * generally results in more repromotions.  Since the
5255 			 * underlying page table page is fully populated, this
5256 			 * removal never frees a page table page.
5257 			 */
5258 			if ((oldpde & PG_W) == 0) {
5259 				va = eva;
5260 				if (va > pdnxt)
5261 					va = pdnxt;
5262 				va -= PAGE_SIZE;
5263 				KASSERT(va >= sva,
5264 				    ("pmap_advise: no address gap"));
5265 				pte = pmap_pte_quick(pmap, va);
5266 				KASSERT((*pte & PG_V) != 0,
5267 				    ("pmap_advise: invalid PTE"));
5268 				pmap_remove_pte(pmap, pte, va, NULL);
5269 				anychanged = true;
5270 			}
5271 		}
5272 		if (pdnxt > eva)
5273 			pdnxt = eva;
5274 		va = pdnxt;
5275 		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
5276 		    sva += PAGE_SIZE) {
5277 			if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
5278 				goto maybe_invlrng;
5279 			else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5280 				if (advice == MADV_DONTNEED) {
5281 					/*
5282 					 * Future calls to pmap_is_modified()
5283 					 * can be avoided by making the page
5284 					 * dirty now.
5285 					 */
5286 					m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
5287 					vm_page_dirty(m);
5288 				}
5289 				atomic_clear_int((u_int *)pte, PG_M | PG_A);
5290 			} else if ((*pte & PG_A) != 0)
5291 				atomic_clear_int((u_int *)pte, PG_A);
5292 			else
5293 				goto maybe_invlrng;
5294 			if ((*pte & PG_G) != 0) {
5295 				if (va == pdnxt)
5296 					va = sva;
5297 			} else
5298 				anychanged = true;
5299 			continue;
5300 maybe_invlrng:
5301 			if (va != pdnxt) {
5302 				pmap_invalidate_range_int(pmap, va, sva);
5303 				va = pdnxt;
5304 			}
5305 		}
5306 		if (va != pdnxt)
5307 			pmap_invalidate_range_int(pmap, va, sva);
5308 	}
5309 	if (anychanged)
5310 		pmap_invalidate_all_int(pmap);
5311 	if (pv_lists_locked) {
5312 		sched_unpin();
5313 		rw_wunlock(&pvh_global_lock);
5314 	}
5315 	PMAP_UNLOCK(pmap);
5316 }
5317 
5318 /*
5319  *	Clear the modify bits on the specified physical page.
5320  */
5321 static void
5322 __CONCAT(PMTYPE, clear_modify)(vm_page_t m)
5323 {
5324 	struct md_page *pvh;
5325 	pv_entry_t next_pv, pv;
5326 	pmap_t pmap;
5327 	pd_entry_t oldpde, *pde;
5328 	pt_entry_t *pte;
5329 	vm_offset_t va;
5330 
5331 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5332 	    ("pmap_clear_modify: page %p is not managed", m));
5333 	vm_page_assert_busied(m);
5334 
5335 	if (!pmap_page_is_write_mapped(m))
5336 		return;
5337 	rw_wlock(&pvh_global_lock);
5338 	sched_pin();
5339 	if ((m->flags & PG_FICTITIOUS) != 0)
5340 		goto small_mappings;
5341 	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5342 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5343 		va = pv->pv_va;
5344 		pmap = PV_PMAP(pv);
5345 		PMAP_LOCK(pmap);
5346 		pde = pmap_pde(pmap, va);
5347 		oldpde = *pde;
5348 		/* If oldpde has PG_RW set, then it also has PG_M set. */
5349 		if ((oldpde & PG_RW) != 0 &&
5350 		    pmap_demote_pde(pmap, pde, va) &&
5351 		    (oldpde & PG_W) == 0) {
5352 			/*
5353 			 * Write protect the mapping to a single page so that
5354 			 * a subsequent write access may repromote.
5355 			 */
5356 			va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
5357 			pte = pmap_pte_quick(pmap, va);
5358 			/*
5359 			 * Regardless of whether a pte is 32 or 64 bits
5360 			 * in size, PG_RW and PG_M are among the least
5361 			 * significant 32 bits.
5362 			 */
5363 			atomic_clear_int((u_int *)pte, PG_M | PG_RW);
5364 			vm_page_dirty(m);
5365 			pmap_invalidate_page_int(pmap, va);
5366 		}
5367 		PMAP_UNLOCK(pmap);
5368 	}
5369 small_mappings:
5370 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5371 		pmap = PV_PMAP(pv);
5372 		PMAP_LOCK(pmap);
5373 		pde = pmap_pde(pmap, pv->pv_va);
5374 		KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
5375 		    " a 4mpage in page %p's pv list", m));
5376 		pte = pmap_pte_quick(pmap, pv->pv_va);
5377 		if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5378 			/*
5379 			 * Regardless of whether a pte is 32 or 64 bits
5380 			 * in size, PG_M is among the least significant
5381 			 * 32 bits.
5382 			 */
5383 			atomic_clear_int((u_int *)pte, PG_M);
5384 			pmap_invalidate_page_int(pmap, pv->pv_va);
5385 		}
5386 		PMAP_UNLOCK(pmap);
5387 	}
5388 	sched_unpin();
5389 	rw_wunlock(&pvh_global_lock);
5390 }
5391 
5392 /*
5393  * Miscellaneous support routines follow
5394  */
5395 
5396 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
5397 static __inline void
5398 pmap_pte_attr(pt_entry_t *pte, int cache_bits)
5399 {
5400 	u_int opte, npte;
5401 
5402 	/*
5403 	 * The cache mode bits are all in the low 32-bits of the
5404 	 * PTE, so we can just spin on updating the low 32-bits.
5405 	 */
5406 	do {
5407 		opte = *(u_int *)pte;
5408 		npte = opte & ~PG_PTE_CACHE;
5409 		npte |= cache_bits;
5410 	} while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
5411 }
5412 
5413 /* Adjust the cache mode for a 2/4MB page mapped via a PDE. */
5414 static __inline void
5415 pmap_pde_attr(pd_entry_t *pde, int cache_bits)
5416 {
5417 	u_int opde, npde;
5418 
5419 	/*
5420 	 * The cache mode bits are all in the low 32-bits of the
5421 	 * PDE, so we can just spin on updating the low 32-bits.
5422 	 */
5423 	do {
5424 		opde = *(u_int *)pde;
5425 		npde = opde & ~PG_PDE_CACHE;
5426 		npde |= cache_bits;
5427 	} while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
5428 }
5429 
5430 /*
5431  * Map a set of physical memory pages into the kernel virtual
5432  * address space. Return a pointer to where it is mapped. This
5433  * routine is intended to be used for mapping device memory,
5434  * NOT real memory.
5435  */
5436 static void *
5437 __CONCAT(PMTYPE, mapdev_attr)(vm_paddr_t pa, vm_size_t size, int mode,
5438     int flags)
5439 {
5440 	struct pmap_preinit_mapping *ppim;
5441 	vm_offset_t va, offset;
5442 	vm_page_t m;
5443 	vm_size_t tmpsize;
5444 	int i;
5445 
5446 	offset = pa & PAGE_MASK;
5447 	size = round_page(offset + size);
5448 	pa = pa & PG_FRAME;
5449 
5450 	if (pa < PMAP_MAP_LOW && pa + size <= PMAP_MAP_LOW) {
5451 		va = pa + PMAP_MAP_LOW;
5452 		if ((flags & MAPDEV_SETATTR) == 0)
5453 			return ((void *)(va + offset));
5454 	} else if (!pmap_initialized) {
5455 		va = 0;
5456 		for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
5457 			ppim = pmap_preinit_mapping + i;
5458 			if (ppim->va == 0) {
5459 				ppim->pa = pa;
5460 				ppim->sz = size;
5461 				ppim->mode = mode;
5462 				ppim->va = virtual_avail;
5463 				virtual_avail += size;
5464 				va = ppim->va;
5465 				break;
5466 			}
5467 		}
5468 		if (va == 0)
5469 			panic("%s: too many preinit mappings", __func__);
5470 	} else {
5471 		/*
5472 		 * If we have a preinit mapping, re-use it.
5473 		 */
5474 		for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
5475 			ppim = pmap_preinit_mapping + i;
5476 			if (ppim->pa == pa && ppim->sz == size &&
5477 			    (ppim->mode == mode ||
5478 			    (flags & MAPDEV_SETATTR) == 0))
5479 				return ((void *)(ppim->va + offset));
5480 		}
5481 		va = kva_alloc(size);
5482 		if (va == 0)
5483 			panic("%s: Couldn't allocate KVA", __func__);
5484 	}
5485 	for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE) {
5486 		if ((flags & MAPDEV_SETATTR) == 0 && pmap_initialized) {
5487 			m = PHYS_TO_VM_PAGE(pa);
5488 			if (m != NULL && VM_PAGE_TO_PHYS(m) == pa) {
5489 				pmap_kenter_attr(va + tmpsize, pa + tmpsize,
5490 				    m->md.pat_mode);
5491 				continue;
5492 			}
5493 		}
5494 		pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
5495 	}
5496 	pmap_invalidate_range_int(kernel_pmap, va, va + tmpsize);
5497 	pmap_invalidate_cache_range(va, va + size);
5498 	return ((void *)(va + offset));
5499 }
5500 
5501 static void
5502 __CONCAT(PMTYPE, unmapdev)(vm_offset_t va, vm_size_t size)
5503 {
5504 	struct pmap_preinit_mapping *ppim;
5505 	vm_offset_t offset;
5506 	int i;
5507 
5508 	if (va >= PMAP_MAP_LOW && va <= KERNBASE && va + size <= KERNBASE)
5509 		return;
5510 	offset = va & PAGE_MASK;
5511 	size = round_page(offset + size);
5512 	va = trunc_page(va);
5513 	for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
5514 		ppim = pmap_preinit_mapping + i;
5515 		if (ppim->va == va && ppim->sz == size) {
5516 			if (pmap_initialized)
5517 				return;
5518 			ppim->pa = 0;
5519 			ppim->va = 0;
5520 			ppim->sz = 0;
5521 			ppim->mode = 0;
5522 			if (va + size == virtual_avail)
5523 				virtual_avail = va;
5524 			return;
5525 		}
5526 	}
5527 	if (pmap_initialized) {
5528 		pmap_qremove(va, atop(size));
5529 		kva_free(va, size);
5530 	}
5531 }
5532 
5533 /*
5534  * Sets the memory attribute for the specified page.
5535  */
5536 static void
5537 __CONCAT(PMTYPE, page_set_memattr)(vm_page_t m, vm_memattr_t ma)
5538 {
5539 
5540 	m->md.pat_mode = ma;
5541 	if ((m->flags & PG_FICTITIOUS) != 0)
5542 		return;
5543 
5544 	/*
5545 	 * If "m" is a normal page, flush it from the cache.
5546 	 * See pmap_invalidate_cache_range().
5547 	 *
5548 	 * First, try to find an existing mapping of the page by sf
5549 	 * buffer. sf_buf_invalidate_cache() modifies mapping and
5550 	 * flushes the cache.
5551 	 */
5552 	if (sf_buf_invalidate_cache(m))
5553 		return;
5554 
5555 	/*
5556 	 * If page is not mapped by sf buffer, but CPU does not
5557 	 * support self snoop, map the page transient and do
5558 	 * invalidation. In the worst case, whole cache is flushed by
5559 	 * pmap_invalidate_cache_range().
5560 	 */
5561 	if ((cpu_feature & CPUID_SS) == 0)
5562 		pmap_flush_page(m);
5563 }
5564 
5565 static void
5566 __CONCAT(PMTYPE, flush_page)(vm_page_t m)
5567 {
5568 	pt_entry_t *cmap_pte2;
5569 	struct pcpu *pc;
5570 	vm_offset_t sva, eva;
5571 	bool useclflushopt;
5572 
5573 	useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
5574 	if (useclflushopt || (cpu_feature & CPUID_CLFSH) != 0) {
5575 		sched_pin();
5576 		pc = get_pcpu();
5577 		cmap_pte2 = pc->pc_cmap_pte2;
5578 		mtx_lock(&pc->pc_cmap_lock);
5579 		if (*cmap_pte2)
5580 			panic("pmap_flush_page: CMAP2 busy");
5581 		*cmap_pte2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) |
5582 		    PG_A | PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode,
5583 		    0);
5584 		invlcaddr(pc->pc_cmap_addr2);
5585 		sva = (vm_offset_t)pc->pc_cmap_addr2;
5586 		eva = sva + PAGE_SIZE;
5587 
5588 		/*
5589 		 * Use mfence or sfence despite the ordering implied by
5590 		 * mtx_{un,}lock() because clflush on non-Intel CPUs
5591 		 * and clflushopt are not guaranteed to be ordered by
5592 		 * any other instruction.
5593 		 */
5594 		if (useclflushopt)
5595 			sfence();
5596 		else if (cpu_vendor_id != CPU_VENDOR_INTEL)
5597 			mfence();
5598 		for (; sva < eva; sva += cpu_clflush_line_size) {
5599 			if (useclflushopt)
5600 				clflushopt(sva);
5601 			else
5602 				clflush(sva);
5603 		}
5604 		if (useclflushopt)
5605 			sfence();
5606 		else if (cpu_vendor_id != CPU_VENDOR_INTEL)
5607 			mfence();
5608 		*cmap_pte2 = 0;
5609 		sched_unpin();
5610 		mtx_unlock(&pc->pc_cmap_lock);
5611 	} else
5612 		pmap_invalidate_cache();
5613 }
5614 
5615 /*
5616  * Changes the specified virtual address range's memory type to that given by
5617  * the parameter "mode".  The specified virtual address range must be
5618  * completely contained within either the kernel map.
5619  *
5620  * Returns zero if the change completed successfully, and either EINVAL or
5621  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
5622  * of the virtual address range was not mapped, and ENOMEM is returned if
5623  * there was insufficient memory available to complete the change.
5624  */
5625 static int
5626 __CONCAT(PMTYPE, change_attr)(vm_offset_t va, vm_size_t size, int mode)
5627 {
5628 	vm_offset_t base, offset, tmpva;
5629 	pd_entry_t *pde;
5630 	pt_entry_t *pte;
5631 	int cache_bits_pte, cache_bits_pde;
5632 	boolean_t changed;
5633 
5634 	base = trunc_page(va);
5635 	offset = va & PAGE_MASK;
5636 	size = round_page(offset + size);
5637 
5638 	/*
5639 	 * Only supported on kernel virtual addresses above the recursive map.
5640 	 */
5641 	if (base < VM_MIN_KERNEL_ADDRESS)
5642 		return (EINVAL);
5643 
5644 	cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
5645 	cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
5646 	changed = FALSE;
5647 
5648 	/*
5649 	 * Pages that aren't mapped aren't supported.  Also break down
5650 	 * 2/4MB pages into 4KB pages if required.
5651 	 */
5652 	PMAP_LOCK(kernel_pmap);
5653 	for (tmpva = base; tmpva < base + size; ) {
5654 		pde = pmap_pde(kernel_pmap, tmpva);
5655 		if (*pde == 0) {
5656 			PMAP_UNLOCK(kernel_pmap);
5657 			return (EINVAL);
5658 		}
5659 		if (*pde & PG_PS) {
5660 			/*
5661 			 * If the current 2/4MB page already has
5662 			 * the required memory type, then we need not
5663 			 * demote this page.  Just increment tmpva to
5664 			 * the next 2/4MB page frame.
5665 			 */
5666 			if ((*pde & PG_PDE_CACHE) == cache_bits_pde) {
5667 				tmpva = trunc_4mpage(tmpva) + NBPDR;
5668 				continue;
5669 			}
5670 
5671 			/*
5672 			 * If the current offset aligns with a 2/4MB
5673 			 * page frame and there is at least 2/4MB left
5674 			 * within the range, then we need not break
5675 			 * down this page into 4KB pages.
5676 			 */
5677 			if ((tmpva & PDRMASK) == 0 &&
5678 			    tmpva + PDRMASK < base + size) {
5679 				tmpva += NBPDR;
5680 				continue;
5681 			}
5682 			if (!pmap_demote_pde(kernel_pmap, pde, tmpva)) {
5683 				PMAP_UNLOCK(kernel_pmap);
5684 				return (ENOMEM);
5685 			}
5686 		}
5687 		pte = vtopte(tmpva);
5688 		if (*pte == 0) {
5689 			PMAP_UNLOCK(kernel_pmap);
5690 			return (EINVAL);
5691 		}
5692 		tmpva += PAGE_SIZE;
5693 	}
5694 	PMAP_UNLOCK(kernel_pmap);
5695 
5696 	/*
5697 	 * Ok, all the pages exist, so run through them updating their
5698 	 * cache mode if required.
5699 	 */
5700 	for (tmpva = base; tmpva < base + size; ) {
5701 		pde = pmap_pde(kernel_pmap, tmpva);
5702 		if (*pde & PG_PS) {
5703 			if ((*pde & PG_PDE_CACHE) != cache_bits_pde) {
5704 				pmap_pde_attr(pde, cache_bits_pde);
5705 				changed = TRUE;
5706 			}
5707 			tmpva = trunc_4mpage(tmpva) + NBPDR;
5708 		} else {
5709 			pte = vtopte(tmpva);
5710 			if ((*pte & PG_PTE_CACHE) != cache_bits_pte) {
5711 				pmap_pte_attr(pte, cache_bits_pte);
5712 				changed = TRUE;
5713 			}
5714 			tmpva += PAGE_SIZE;
5715 		}
5716 	}
5717 
5718 	/*
5719 	 * Flush CPU caches to make sure any data isn't cached that
5720 	 * shouldn't be, etc.
5721 	 */
5722 	if (changed) {
5723 		pmap_invalidate_range_int(kernel_pmap, base, tmpva);
5724 		pmap_invalidate_cache_range(base, tmpva);
5725 	}
5726 	return (0);
5727 }
5728 
5729 /*
5730  * Perform the pmap work for mincore(2).  If the page is not both referenced and
5731  * modified by this pmap, returns its physical address so that the caller can
5732  * find other mappings.
5733  */
5734 static int
5735 __CONCAT(PMTYPE, mincore)(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
5736 {
5737 	pd_entry_t pde;
5738 	pt_entry_t pte;
5739 	vm_paddr_t pa;
5740 	int val;
5741 
5742 	PMAP_LOCK(pmap);
5743 	pde = *pmap_pde(pmap, addr);
5744 	if (pde != 0) {
5745 		if ((pde & PG_PS) != 0) {
5746 			pte = pde;
5747 			/* Compute the physical address of the 4KB page. */
5748 			pa = ((pde & PG_PS_FRAME) | (addr & PDRMASK)) &
5749 			    PG_FRAME;
5750 			val = MINCORE_PSIND(1);
5751 		} else {
5752 			pte = pmap_pte_ufast(pmap, addr, pde);
5753 			pa = pte & PG_FRAME;
5754 			val = 0;
5755 		}
5756 	} else {
5757 		pte = 0;
5758 		pa = 0;
5759 		val = 0;
5760 	}
5761 	if ((pte & PG_V) != 0) {
5762 		val |= MINCORE_INCORE;
5763 		if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5764 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5765 		if ((pte & PG_A) != 0)
5766 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5767 	}
5768 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5769 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
5770 	    (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
5771 		*pap = pa;
5772 	}
5773 	PMAP_UNLOCK(pmap);
5774 	return (val);
5775 }
5776 
5777 static void
5778 __CONCAT(PMTYPE, activate)(struct thread *td)
5779 {
5780 	pmap_t	pmap, oldpmap;
5781 	u_int	cpuid;
5782 	u_int32_t  cr3;
5783 
5784 	critical_enter();
5785 	pmap = vmspace_pmap(td->td_proc->p_vmspace);
5786 	oldpmap = PCPU_GET(curpmap);
5787 	cpuid = PCPU_GET(cpuid);
5788 #if defined(SMP)
5789 	CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
5790 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
5791 #else
5792 	CPU_CLR(cpuid, &oldpmap->pm_active);
5793 	CPU_SET(cpuid, &pmap->pm_active);
5794 #endif
5795 #ifdef PMAP_PAE_COMP
5796 	cr3 = vtophys(pmap->pm_pdpt);
5797 #else
5798 	cr3 = vtophys(pmap->pm_pdir);
5799 #endif
5800 	/*
5801 	 * pmap_activate is for the current thread on the current cpu
5802 	 */
5803 	td->td_pcb->pcb_cr3 = cr3;
5804 	PCPU_SET(curpmap, pmap);
5805 	critical_exit();
5806 }
5807 
5808 static void
5809 __CONCAT(PMTYPE, activate_boot)(pmap_t pmap)
5810 {
5811 	u_int cpuid;
5812 
5813 	cpuid = PCPU_GET(cpuid);
5814 #if defined(SMP)
5815 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
5816 #else
5817 	CPU_SET(cpuid, &pmap->pm_active);
5818 #endif
5819 	PCPU_SET(curpmap, pmap);
5820 }
5821 
5822 /*
5823  *	Increase the starting virtual address of the given mapping if a
5824  *	different alignment might result in more superpage mappings.
5825  */
5826 static void
5827 __CONCAT(PMTYPE, align_superpage)(vm_object_t object, vm_ooffset_t offset,
5828     vm_offset_t *addr, vm_size_t size)
5829 {
5830 	vm_offset_t superpage_offset;
5831 
5832 	if (size < NBPDR)
5833 		return;
5834 	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5835 		offset += ptoa(object->pg_color);
5836 	superpage_offset = offset & PDRMASK;
5837 	if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
5838 	    (*addr & PDRMASK) == superpage_offset)
5839 		return;
5840 	if ((*addr & PDRMASK) < superpage_offset)
5841 		*addr = (*addr & ~PDRMASK) + superpage_offset;
5842 	else
5843 		*addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
5844 }
5845 
5846 static vm_offset_t
5847 __CONCAT(PMTYPE, quick_enter_page)(vm_page_t m)
5848 {
5849 	vm_offset_t qaddr;
5850 	pt_entry_t *pte;
5851 
5852 	critical_enter();
5853 	qaddr = PCPU_GET(qmap_addr);
5854 	pte = vtopte(qaddr);
5855 
5856 	KASSERT(*pte == 0,
5857 	    ("pmap_quick_enter_page: PTE busy %#jx", (uintmax_t)*pte));
5858 	*pte = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
5859 	    pmap_cache_bits(kernel_pmap, pmap_page_get_memattr(m), 0);
5860 	invlpg(qaddr);
5861 
5862 	return (qaddr);
5863 }
5864 
5865 static void
5866 __CONCAT(PMTYPE, quick_remove_page)(vm_offset_t addr)
5867 {
5868 	vm_offset_t qaddr;
5869 	pt_entry_t *pte;
5870 
5871 	qaddr = PCPU_GET(qmap_addr);
5872 	pte = vtopte(qaddr);
5873 
5874 	KASSERT(*pte != 0, ("pmap_quick_remove_page: PTE not in use"));
5875 	KASSERT(addr == qaddr, ("pmap_quick_remove_page: invalid address"));
5876 
5877 	*pte = 0;
5878 	critical_exit();
5879 }
5880 
5881 static vmem_t *pmap_trm_arena;
5882 static vmem_addr_t pmap_trm_arena_last = PMAP_TRM_MIN_ADDRESS;
5883 static int trm_guard = PAGE_SIZE;
5884 
5885 static int
5886 pmap_trm_import(void *unused __unused, vmem_size_t size, int flags,
5887     vmem_addr_t *addrp)
5888 {
5889 	vm_page_t m;
5890 	vmem_addr_t af, addr, prev_addr;
5891 	pt_entry_t *trm_pte;
5892 
5893 	prev_addr = atomic_load_long(&pmap_trm_arena_last);
5894 	size = round_page(size) + trm_guard;
5895 	for (;;) {
5896 		if (prev_addr + size < prev_addr || prev_addr + size < size ||
5897 		    prev_addr + size > PMAP_TRM_MAX_ADDRESS)
5898 			return (ENOMEM);
5899 		addr = prev_addr + size;
5900 		if (atomic_fcmpset_int(&pmap_trm_arena_last, &prev_addr, addr))
5901 			break;
5902 	}
5903 	prev_addr += trm_guard;
5904 	trm_pte = PTmap + atop(prev_addr);
5905 	for (af = prev_addr; af < addr; af += PAGE_SIZE) {
5906 		m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
5907 		pte_store(&trm_pte[atop(af - prev_addr)], VM_PAGE_TO_PHYS(m) |
5908 		    PG_M | PG_A | PG_RW | PG_V | pgeflag |
5909 		    pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE));
5910 	}
5911 	*addrp = prev_addr;
5912 	return (0);
5913 }
5914 
5915 void
5916 pmap_init_trm(void)
5917 {
5918 	vm_page_t pd_m;
5919 
5920 	TUNABLE_INT_FETCH("machdep.trm_guard", &trm_guard);
5921 	if ((trm_guard & PAGE_MASK) != 0)
5922 		trm_guard = 0;
5923 	pmap_trm_arena = vmem_create("i386trampoline", 0, 0, 1, 0, M_WAITOK);
5924 	vmem_set_import(pmap_trm_arena, pmap_trm_import, NULL, NULL, PAGE_SIZE);
5925 	pd_m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_WAITOK |
5926 	    VM_ALLOC_ZERO);
5927 	PTD[TRPTDI] = VM_PAGE_TO_PHYS(pd_m) | PG_M | PG_A | PG_RW | PG_V |
5928 	    pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, TRUE);
5929 }
5930 
5931 static void *
5932 __CONCAT(PMTYPE, trm_alloc)(size_t size, int flags)
5933 {
5934 	vmem_addr_t res;
5935 	int error;
5936 
5937 	MPASS((flags & ~(M_WAITOK | M_NOWAIT | M_ZERO)) == 0);
5938 	error = vmem_xalloc(pmap_trm_arena, roundup2(size, 4), sizeof(int),
5939 	    0, 0, VMEM_ADDR_MIN, VMEM_ADDR_MAX, flags | M_FIRSTFIT, &res);
5940 	if (error != 0)
5941 		return (NULL);
5942 	if ((flags & M_ZERO) != 0)
5943 		bzero((void *)res, size);
5944 	return ((void *)res);
5945 }
5946 
5947 static void
5948 __CONCAT(PMTYPE, trm_free)(void *addr, size_t size)
5949 {
5950 
5951 	vmem_free(pmap_trm_arena, (uintptr_t)addr, roundup2(size, 4));
5952 }
5953 
5954 static void
5955 __CONCAT(PMTYPE, ksetrw)(vm_offset_t va)
5956 {
5957 
5958 	*vtopte(va) |= PG_RW;
5959 }
5960 
5961 static void
5962 __CONCAT(PMTYPE, remap_lowptdi)(bool enable)
5963 {
5964 
5965 	PTD[KPTDI] = enable ? PTD[LOWPTDI] : 0;
5966 	invltlb_glob();
5967 }
5968 
5969 static vm_offset_t
5970 __CONCAT(PMTYPE, get_map_low)(void)
5971 {
5972 
5973 	return (PMAP_MAP_LOW);
5974 }
5975 
5976 static vm_offset_t
5977 __CONCAT(PMTYPE, get_vm_maxuser_address)(void)
5978 {
5979 
5980 	return (VM_MAXUSER_ADDRESS);
5981 }
5982 
5983 static vm_paddr_t
5984 __CONCAT(PMTYPE, pg_frame)(vm_paddr_t pa)
5985 {
5986 
5987 	return (pa & PG_FRAME);
5988 }
5989 
5990 static void
5991 __CONCAT(PMTYPE, sf_buf_map)(struct sf_buf *sf)
5992 {
5993 	pt_entry_t opte, *ptep;
5994 
5995 	/*
5996 	 * Update the sf_buf's virtual-to-physical mapping, flushing the
5997 	 * virtual address from the TLB.  Since the reference count for
5998 	 * the sf_buf's old mapping was zero, that mapping is not
5999 	 * currently in use.  Consequently, there is no need to exchange
6000 	 * the old and new PTEs atomically, even under PAE.
6001 	 */
6002 	ptep = vtopte(sf->kva);
6003 	opte = *ptep;
6004 	*ptep = VM_PAGE_TO_PHYS(sf->m) | PG_RW | PG_V |
6005 	    pmap_cache_bits(kernel_pmap, sf->m->md.pat_mode, 0);
6006 
6007 	/*
6008 	 * Avoid unnecessary TLB invalidations: If the sf_buf's old
6009 	 * virtual-to-physical mapping was not used, then any processor
6010 	 * that has invalidated the sf_buf's virtual address from its TLB
6011 	 * since the last used mapping need not invalidate again.
6012 	 */
6013 #ifdef SMP
6014 	if ((opte & (PG_V | PG_A)) ==  (PG_V | PG_A))
6015 		CPU_ZERO(&sf->cpumask);
6016 #else
6017 	if ((opte & (PG_V | PG_A)) ==  (PG_V | PG_A))
6018 		pmap_invalidate_page_int(kernel_pmap, sf->kva);
6019 #endif
6020 }
6021 
6022 static void
6023 __CONCAT(PMTYPE, cp_slow0_map)(vm_offset_t kaddr, int plen, vm_page_t *ma)
6024 {
6025 	pt_entry_t *pte;
6026 	int i;
6027 
6028 	for (i = 0, pte = vtopte(kaddr); i < plen; i++, pte++) {
6029 		*pte = PG_V | PG_RW | PG_A | PG_M | VM_PAGE_TO_PHYS(ma[i]) |
6030 		    pmap_cache_bits(kernel_pmap, pmap_page_get_memattr(ma[i]),
6031 		    FALSE);
6032 		invlpg(kaddr + ptoa(i));
6033 	}
6034 }
6035 
6036 static u_int
6037 __CONCAT(PMTYPE, get_kcr3)(void)
6038 {
6039 
6040 #ifdef PMAP_PAE_COMP
6041 	return ((u_int)IdlePDPT);
6042 #else
6043 	return ((u_int)IdlePTD);
6044 #endif
6045 }
6046 
6047 static u_int
6048 __CONCAT(PMTYPE, get_cr3)(pmap_t pmap)
6049 {
6050 
6051 #ifdef PMAP_PAE_COMP
6052 	return ((u_int)vtophys(pmap->pm_pdpt));
6053 #else
6054 	return ((u_int)vtophys(pmap->pm_pdir));
6055 #endif
6056 }
6057 
6058 static caddr_t
6059 __CONCAT(PMTYPE, cmap3)(vm_paddr_t pa, u_int pte_bits)
6060 {
6061 	pt_entry_t *pte;
6062 
6063 	pte = CMAP3;
6064 	*pte = pa | pte_bits;
6065 	invltlb();
6066 	return (CADDR3);
6067 }
6068 
6069 static void
6070 __CONCAT(PMTYPE, basemem_setup)(u_int basemem)
6071 {
6072 	pt_entry_t *pte;
6073 	int i;
6074 
6075 	/*
6076 	 * Map pages between basemem and ISA_HOLE_START, if any, r/w into
6077 	 * the vm86 page table so that vm86 can scribble on them using
6078 	 * the vm86 map too.  XXX: why 2 ways for this and only 1 way for
6079 	 * page 0, at least as initialized here?
6080 	 */
6081 	pte = (pt_entry_t *)vm86paddr;
6082 	for (i = basemem / 4; i < 160; i++)
6083 		pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
6084 }
6085 
6086 struct bios16_pmap_handle {
6087 	pt_entry_t	*pte;
6088 	pd_entry_t	*ptd;
6089 	pt_entry_t	orig_ptd;
6090 };
6091 
6092 static void *
6093 __CONCAT(PMTYPE, bios16_enter)(void)
6094 {
6095 	struct bios16_pmap_handle *h;
6096 
6097 	/*
6098 	 * no page table, so create one and install it.
6099 	 */
6100 	h = malloc(sizeof(struct bios16_pmap_handle), M_TEMP, M_WAITOK);
6101 	h->pte = (pt_entry_t *)malloc(PAGE_SIZE, M_TEMP, M_WAITOK);
6102 	h->ptd = IdlePTD;
6103 	*h->pte = vm86phystk | PG_RW | PG_V;
6104 	h->orig_ptd = *h->ptd;
6105 	*h->ptd = vtophys(h->pte) | PG_RW | PG_V;
6106 	pmap_invalidate_all_int(kernel_pmap);	/* XXX insurance for now */
6107 	return (h);
6108 }
6109 
6110 static void
6111 __CONCAT(PMTYPE, bios16_leave)(void *arg)
6112 {
6113 	struct bios16_pmap_handle *h;
6114 
6115 	h = arg;
6116 	*h->ptd = h->orig_ptd;		/* remove page table */
6117 	/*
6118 	 * XXX only needs to be invlpg(0) but that doesn't work on the 386
6119 	 */
6120 	pmap_invalidate_all_int(kernel_pmap);
6121 	free(h->pte, M_TEMP);		/* ... and free it */
6122 }
6123 
6124 struct pmap_kernel_map_range {
6125 	vm_offset_t sva;
6126 	pt_entry_t attrs;
6127 	int ptes;
6128 	int pdes;
6129 	int pdpes;
6130 };
6131 
6132 static void
6133 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
6134     vm_offset_t eva)
6135 {
6136 	const char *mode;
6137 	int i, pat_idx;
6138 
6139 	if (eva <= range->sva)
6140 		return;
6141 
6142 	pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
6143 	for (i = 0; i < PAT_INDEX_SIZE; i++)
6144 		if (pat_index[i] == pat_idx)
6145 			break;
6146 
6147 	switch (i) {
6148 	case PAT_WRITE_BACK:
6149 		mode = "WB";
6150 		break;
6151 	case PAT_WRITE_THROUGH:
6152 		mode = "WT";
6153 		break;
6154 	case PAT_UNCACHEABLE:
6155 		mode = "UC";
6156 		break;
6157 	case PAT_UNCACHED:
6158 		mode = "U-";
6159 		break;
6160 	case PAT_WRITE_PROTECTED:
6161 		mode = "WP";
6162 		break;
6163 	case PAT_WRITE_COMBINING:
6164 		mode = "WC";
6165 		break;
6166 	default:
6167 		printf("%s: unknown PAT mode %#x for range 0x%08x-0x%08x\n",
6168 		    __func__, pat_idx, range->sva, eva);
6169 		mode = "??";
6170 		break;
6171 	}
6172 
6173 	sbuf_printf(sb, "0x%08x-0x%08x r%c%c%c%c %s %d %d %d\n",
6174 	    range->sva, eva,
6175 	    (range->attrs & PG_RW) != 0 ? 'w' : '-',
6176 	    (range->attrs & pg_nx) != 0 ? '-' : 'x',
6177 	    (range->attrs & PG_U) != 0 ? 'u' : 's',
6178 	    (range->attrs & PG_G) != 0 ? 'g' : '-',
6179 	    mode, range->pdpes, range->pdes, range->ptes);
6180 
6181 	/* Reset to sentinel value. */
6182 	range->sva = 0xffffffff;
6183 }
6184 
6185 /*
6186  * Determine whether the attributes specified by a page table entry match those
6187  * being tracked by the current range.  This is not quite as simple as a direct
6188  * flag comparison since some PAT modes have multiple representations.
6189  */
6190 static bool
6191 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
6192 {
6193 	pt_entry_t diff, mask;
6194 
6195 	mask = pg_nx | PG_G | PG_RW | PG_U | PG_PDE_CACHE;
6196 	diff = (range->attrs ^ attrs) & mask;
6197 	if (diff == 0)
6198 		return (true);
6199 	if ((diff & ~PG_PDE_PAT) == 0 &&
6200 	    pmap_pat_index(kernel_pmap, range->attrs, true) ==
6201 	    pmap_pat_index(kernel_pmap, attrs, true))
6202 		return (true);
6203 	return (false);
6204 }
6205 
6206 static void
6207 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
6208     pt_entry_t attrs)
6209 {
6210 
6211 	memset(range, 0, sizeof(*range));
6212 	range->sva = va;
6213 	range->attrs = attrs;
6214 }
6215 
6216 /*
6217  * Given a leaf PTE, derive the mapping's attributes.  If they do not match
6218  * those of the current run, dump the address range and its attributes, and
6219  * begin a new run.
6220  */
6221 static void
6222 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
6223     vm_offset_t va, pd_entry_t pde, pt_entry_t pte)
6224 {
6225 	pt_entry_t attrs;
6226 
6227 	attrs = pde & (PG_RW | PG_U | pg_nx);
6228 
6229 	if ((pde & PG_PS) != 0) {
6230 		attrs |= pde & (PG_G | PG_PDE_CACHE);
6231 	} else if (pte != 0) {
6232 		attrs |= pte & pg_nx;
6233 		attrs &= pg_nx | (pte & (PG_RW | PG_U));
6234 		attrs |= pte & (PG_G | PG_PTE_CACHE);
6235 
6236 		/* Canonicalize by always using the PDE PAT bit. */
6237 		if ((attrs & PG_PTE_PAT) != 0)
6238 			attrs ^= PG_PDE_PAT | PG_PTE_PAT;
6239 	}
6240 
6241 	if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
6242 		sysctl_kmaps_dump(sb, range, va);
6243 		sysctl_kmaps_reinit(range, va, attrs);
6244 	}
6245 }
6246 
6247 static int
6248 __CONCAT(PMTYPE, sysctl_kmaps)(SYSCTL_HANDLER_ARGS)
6249 {
6250 	struct pmap_kernel_map_range range;
6251 	struct sbuf sbuf, *sb;
6252 	pd_entry_t pde;
6253 	pt_entry_t *pt, pte;
6254 	vm_offset_t sva;
6255 	vm_paddr_t pa;
6256 	int error;
6257 	u_int i, k;
6258 
6259 	error = sysctl_wire_old_buffer(req, 0);
6260 	if (error != 0)
6261 		return (error);
6262 	sb = &sbuf;
6263 	sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
6264 
6265 	/* Sentinel value. */
6266 	range.sva = 0xffffffff;
6267 
6268 	/*
6269 	 * Iterate over the kernel page tables without holding the
6270 	 * kernel pmap lock.  Kernel page table pages are never freed,
6271 	 * so at worst we will observe inconsistencies in the output.
6272 	 */
6273 	for (sva = 0, i = 0; i < NPTEPG * NPGPTD * NPDEPG ;) {
6274 		if (i == 0)
6275 			sbuf_printf(sb, "\nLow PDE:\n");
6276 		else if (i == LOWPTDI * NPTEPG)
6277 			sbuf_printf(sb, "Low PDE dup:\n");
6278 		else if (i == PTDPTDI * NPTEPG)
6279 			sbuf_printf(sb, "Recursive map:\n");
6280 		else if (i == KERNPTDI * NPTEPG)
6281 			sbuf_printf(sb, "Kernel base:\n");
6282 		else if (i == TRPTDI * NPTEPG)
6283 			sbuf_printf(sb, "Trampoline:\n");
6284 		pde = IdlePTD[sva >> PDRSHIFT];
6285 		if ((pde & PG_V) == 0) {
6286 			sva = rounddown2(sva, NBPDR);
6287 			sysctl_kmaps_dump(sb, &range, sva);
6288 			sva += NBPDR;
6289 			i += NPTEPG;
6290 			continue;
6291 		}
6292 		pa = pde & PG_FRAME;
6293 		if ((pde & PG_PS) != 0) {
6294 			sysctl_kmaps_check(sb, &range, sva, pde, 0);
6295 			range.pdes++;
6296 			sva += NBPDR;
6297 			i += NPTEPG;
6298 			continue;
6299 		}
6300 		for (pt = vtopte(sva), k = 0; k < NPTEPG; i++, k++, pt++,
6301 		    sva += PAGE_SIZE) {
6302 			pte = *pt;
6303 			if ((pte & PG_V) == 0) {
6304 				sysctl_kmaps_dump(sb, &range, sva);
6305 				continue;
6306 			}
6307 			sysctl_kmaps_check(sb, &range, sva, pde, pte);
6308 			range.ptes++;
6309 		}
6310 	}
6311 
6312 	error = sbuf_finish(sb);
6313 	sbuf_delete(sb);
6314 	return (error);
6315 }
6316 
6317 #define	PMM(a)					\
6318 	.pm_##a = __CONCAT(PMTYPE, a),
6319 
6320 struct pmap_methods __CONCAT(PMTYPE, methods) = {
6321 	PMM(ksetrw)
6322 	PMM(remap_lower)
6323 	PMM(remap_lowptdi)
6324 	PMM(align_superpage)
6325 	PMM(quick_enter_page)
6326 	PMM(quick_remove_page)
6327 	PMM(trm_alloc)
6328 	PMM(trm_free)
6329 	PMM(get_map_low)
6330 	PMM(get_vm_maxuser_address)
6331 	PMM(kextract)
6332 	PMM(pg_frame)
6333 	PMM(sf_buf_map)
6334 	PMM(cp_slow0_map)
6335 	PMM(get_kcr3)
6336 	PMM(get_cr3)
6337 	PMM(cmap3)
6338 	PMM(basemem_setup)
6339 	PMM(set_nx)
6340 	PMM(bios16_enter)
6341 	PMM(bios16_leave)
6342 	PMM(bootstrap)
6343 	PMM(is_valid_memattr)
6344 	PMM(cache_bits)
6345 	PMM(ps_enabled)
6346 	PMM(pinit0)
6347 	PMM(pinit)
6348 	PMM(activate)
6349 	PMM(activate_boot)
6350 	PMM(advise)
6351 	PMM(clear_modify)
6352 	PMM(change_attr)
6353 	PMM(mincore)
6354 	PMM(copy)
6355 	PMM(copy_page)
6356 	PMM(copy_pages)
6357 	PMM(zero_page)
6358 	PMM(zero_page_area)
6359 	PMM(enter)
6360 	PMM(enter_object)
6361 	PMM(enter_quick)
6362 	PMM(kenter_temporary)
6363 	PMM(object_init_pt)
6364 	PMM(unwire)
6365 	PMM(page_exists_quick)
6366 	PMM(page_wired_mappings)
6367 	PMM(page_is_mapped)
6368 	PMM(remove_pages)
6369 	PMM(is_modified)
6370 	PMM(is_prefaultable)
6371 	PMM(is_referenced)
6372 	PMM(remove_write)
6373 	PMM(ts_referenced)
6374 	PMM(mapdev_attr)
6375 	PMM(unmapdev)
6376 	PMM(page_set_memattr)
6377 	PMM(extract)
6378 	PMM(extract_and_hold)
6379 	PMM(map)
6380 	PMM(qenter)
6381 	PMM(qremove)
6382 	PMM(release)
6383 	PMM(remove)
6384 	PMM(protect)
6385 	PMM(remove_all)
6386 	PMM(init)
6387 	PMM(init_pat)
6388 	PMM(growkernel)
6389 	PMM(invalidate_page)
6390 	PMM(invalidate_range)
6391 	PMM(invalidate_all)
6392 	PMM(invalidate_cache)
6393 	PMM(flush_page)
6394 	PMM(kenter)
6395 	PMM(kremove)
6396 	PMM(sysctl_kmaps)
6397 };
6398