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