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