xref: /freebsd/sys/amd64/amd64/pmap.c (revision 6ec4ff70885d8048be8de9b9d690dd371e3d4a3e)
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) 2003 Peter Wemm
11  * All rights reserved.
12  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
13  * All rights reserved.
14  *
15  * This code is derived from software contributed to Berkeley by
16  * the Systems Programming Group of the University of Utah Computer
17  * Science Department and William Jolitz of UUNET Technologies Inc.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  * 3. All advertising materials mentioning features or use of this software
28  *    must display the following acknowledgement:
29  *	This product includes software developed by the University of
30  *	California, Berkeley and its contributors.
31  * 4. Neither the name of the University nor the names of its contributors
32  *    may be used to endorse or promote products derived from this software
33  *    without specific prior written permission.
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45  * SUCH DAMAGE.
46  */
47 /*-
48  * Copyright (c) 2003 Networks Associates Technology, Inc.
49  * Copyright (c) 2014-2020 The FreeBSD Foundation
50  * All rights reserved.
51  *
52  * This software was developed for the FreeBSD Project by Jake Burkholder,
53  * Safeport Network Services, and Network Associates Laboratories, the
54  * Security Research Division of Network Associates, Inc. under
55  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
56  * CHATS research program.
57  *
58  * Portions of this software were developed by
59  * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
60  * the FreeBSD Foundation.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  *
71  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
72  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
75  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
81  * SUCH DAMAGE.
82  */
83 
84 #define	AMD64_NPT_AWARE
85 
86 #include <sys/cdefs.h>
87 /*
88  *	Manages physical address maps.
89  *
90  *	Since the information managed by this module is
91  *	also stored by the logical address mapping module,
92  *	this module may throw away valid virtual-to-physical
93  *	mappings at almost any time.  However, invalidations
94  *	of virtual-to-physical mappings must be done as
95  *	requested.
96  *
97  *	In order to cope with hardware architectures which
98  *	make virtual-to-physical map invalidates expensive,
99  *	this module may delay invalidate or reduced protection
100  *	operations until such time as they are actually
101  *	necessary.  This module is given full information as
102  *	to which processors are currently using which maps,
103  *	and to when physical maps must be made correct.
104  */
105 
106 #include "opt_ddb.h"
107 #include "opt_pmap.h"
108 #include "opt_vm.h"
109 
110 #include <sys/param.h>
111 #include <sys/asan.h>
112 #include <sys/bitstring.h>
113 #include <sys/bus.h>
114 #include <sys/systm.h>
115 #include <sys/counter.h>
116 #include <sys/kernel.h>
117 #include <sys/ktr.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/msan.h>
122 #include <sys/mutex.h>
123 #include <sys/proc.h>
124 #include <sys/rangeset.h>
125 #include <sys/rwlock.h>
126 #include <sys/sbuf.h>
127 #include <sys/smr.h>
128 #include <sys/sx.h>
129 #include <sys/turnstile.h>
130 #include <sys/vmem.h>
131 #include <sys/vmmeter.h>
132 #include <sys/sched.h>
133 #include <sys/sysctl.h>
134 #include <sys/smp.h>
135 #ifdef DDB
136 #include <sys/kdb.h>
137 #include <ddb/ddb.h>
138 #endif
139 
140 #include <vm/vm.h>
141 #include <vm/vm_param.h>
142 #include <vm/vm_kern.h>
143 #include <vm/vm_page.h>
144 #include <vm/vm_map.h>
145 #include <vm/vm_object.h>
146 #include <vm/vm_extern.h>
147 #include <vm/vm_pageout.h>
148 #include <vm/vm_pager.h>
149 #include <vm/vm_phys.h>
150 #include <vm/vm_radix.h>
151 #include <vm/vm_reserv.h>
152 #include <vm/vm_dumpset.h>
153 #include <vm/uma.h>
154 
155 #include <machine/asan.h>
156 #include <machine/intr_machdep.h>
157 #include <x86/apicvar.h>
158 #include <x86/ifunc.h>
159 #include <machine/cpu.h>
160 #include <machine/cputypes.h>
161 #include <machine/md_var.h>
162 #include <machine/msan.h>
163 #include <machine/pcb.h>
164 #include <machine/specialreg.h>
165 #ifdef SMP
166 #include <machine/smp.h>
167 #endif
168 #include <machine/sysarch.h>
169 #include <machine/tss.h>
170 
171 #ifdef NUMA
172 #define	PMAP_MEMDOM	MAXMEMDOM
173 #else
174 #define	PMAP_MEMDOM	1
175 #endif
176 
177 static __inline bool
pmap_type_guest(pmap_t pmap)178 pmap_type_guest(pmap_t pmap)
179 {
180 
181 	return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
182 }
183 
184 static __inline bool
pmap_emulate_ad_bits(pmap_t pmap)185 pmap_emulate_ad_bits(pmap_t pmap)
186 {
187 
188 	return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
189 }
190 
191 static __inline pt_entry_t
pmap_valid_bit(pmap_t pmap)192 pmap_valid_bit(pmap_t pmap)
193 {
194 	pt_entry_t mask;
195 
196 	switch (pmap->pm_type) {
197 	case PT_X86:
198 	case PT_RVI:
199 		mask = X86_PG_V;
200 		break;
201 	case PT_EPT:
202 		if (pmap_emulate_ad_bits(pmap))
203 			mask = EPT_PG_EMUL_V;
204 		else
205 			mask = EPT_PG_READ;
206 		break;
207 	default:
208 		panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
209 	}
210 
211 	return (mask);
212 }
213 
214 static __inline pt_entry_t
pmap_rw_bit(pmap_t pmap)215 pmap_rw_bit(pmap_t pmap)
216 {
217 	pt_entry_t mask;
218 
219 	switch (pmap->pm_type) {
220 	case PT_X86:
221 	case PT_RVI:
222 		mask = X86_PG_RW;
223 		break;
224 	case PT_EPT:
225 		if (pmap_emulate_ad_bits(pmap))
226 			mask = EPT_PG_EMUL_RW;
227 		else
228 			mask = EPT_PG_WRITE;
229 		break;
230 	default:
231 		panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
232 	}
233 
234 	return (mask);
235 }
236 
237 static pt_entry_t pg_g;
238 
239 static __inline pt_entry_t
pmap_global_bit(pmap_t pmap)240 pmap_global_bit(pmap_t pmap)
241 {
242 	pt_entry_t mask;
243 
244 	switch (pmap->pm_type) {
245 	case PT_X86:
246 		mask = pg_g;
247 		break;
248 	case PT_RVI:
249 	case PT_EPT:
250 		mask = 0;
251 		break;
252 	default:
253 		panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
254 	}
255 
256 	return (mask);
257 }
258 
259 static __inline pt_entry_t
pmap_accessed_bit(pmap_t pmap)260 pmap_accessed_bit(pmap_t pmap)
261 {
262 	pt_entry_t mask;
263 
264 	switch (pmap->pm_type) {
265 	case PT_X86:
266 	case PT_RVI:
267 		mask = X86_PG_A;
268 		break;
269 	case PT_EPT:
270 		if (pmap_emulate_ad_bits(pmap))
271 			mask = EPT_PG_READ;
272 		else
273 			mask = EPT_PG_A;
274 		break;
275 	default:
276 		panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
277 	}
278 
279 	return (mask);
280 }
281 
282 static __inline pt_entry_t
pmap_modified_bit(pmap_t pmap)283 pmap_modified_bit(pmap_t pmap)
284 {
285 	pt_entry_t mask;
286 
287 	switch (pmap->pm_type) {
288 	case PT_X86:
289 	case PT_RVI:
290 		mask = X86_PG_M;
291 		break;
292 	case PT_EPT:
293 		if (pmap_emulate_ad_bits(pmap))
294 			mask = EPT_PG_WRITE;
295 		else
296 			mask = EPT_PG_M;
297 		break;
298 	default:
299 		panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
300 	}
301 
302 	return (mask);
303 }
304 
305 static __inline pt_entry_t
pmap_pku_mask_bit(pmap_t pmap)306 pmap_pku_mask_bit(pmap_t pmap)
307 {
308 
309 	return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
310 }
311 
312 static __inline bool
safe_to_clear_referenced(pmap_t pmap,pt_entry_t pte)313 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
314 {
315 
316 	if (!pmap_emulate_ad_bits(pmap))
317 		return (true);
318 
319 	KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
320 
321 	/*
322 	 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
323 	 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
324 	 * if the EPT_PG_WRITE bit is set.
325 	 */
326 	if ((pte & EPT_PG_WRITE) != 0)
327 		return (false);
328 
329 	/*
330 	 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
331 	 */
332 	if ((pte & EPT_PG_EXECUTE) == 0 ||
333 	    ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
334 		return (true);
335 	else
336 		return (false);
337 }
338 
339 #ifdef PV_STATS
340 #define PV_STAT(x)	do { x ; } while (0)
341 #else
342 #define PV_STAT(x)	do { } while (0)
343 #endif
344 
345 #undef pa_index
346 #ifdef NUMA
347 #define	pa_index(pa)	({					\
348 	KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end,	\
349 	    ("address %lx beyond the last segment", (pa)));	\
350 	(pa) >> PDRSHIFT;					\
351 })
352 #define	pa_to_pmdp(pa)	(&pv_table[pa_index(pa)])
353 #define	pa_to_pvh(pa)	(&(pa_to_pmdp(pa)->pv_page))
354 #define	PHYS_TO_PV_LIST_LOCK(pa)	({			\
355 	struct rwlock *_lock;					\
356 	if (__predict_false((pa) > pmap_last_pa))		\
357 		_lock = &pv_dummy_large.pv_lock;		\
358 	else							\
359 		_lock = &(pa_to_pmdp(pa)->pv_lock);		\
360 	_lock;							\
361 })
362 #else
363 #define	pa_index(pa)	((pa) >> PDRSHIFT)
364 #define	pa_to_pvh(pa)	(&pv_table[pa_index(pa)])
365 
366 #define	NPV_LIST_LOCKS	MAXCPU
367 
368 #define	PHYS_TO_PV_LIST_LOCK(pa)	\
369 			(&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
370 #endif
371 
372 #define	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)	do {	\
373 	struct rwlock **_lockp = (lockp);		\
374 	struct rwlock *_new_lock;			\
375 							\
376 	_new_lock = PHYS_TO_PV_LIST_LOCK(pa);		\
377 	if (_new_lock != *_lockp) {			\
378 		if (*_lockp != NULL)			\
379 			rw_wunlock(*_lockp);		\
380 		*_lockp = _new_lock;			\
381 		rw_wlock(*_lockp);			\
382 	}						\
383 } while (0)
384 
385 #define	CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)	\
386 			CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
387 
388 #define	RELEASE_PV_LIST_LOCK(lockp)		do {	\
389 	struct rwlock **_lockp = (lockp);		\
390 							\
391 	if (*_lockp != NULL) {				\
392 		rw_wunlock(*_lockp);			\
393 		*_lockp = NULL;				\
394 	}						\
395 } while (0)
396 
397 #define	VM_PAGE_TO_PV_LIST_LOCK(m)	\
398 			PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
399 
400 /*
401  * Statically allocate kernel pmap memory.  However, memory for
402  * pm_pcids is obtained after the dynamic allocator is operational.
403  * Initialize it with a non-canonical pointer to catch early accesses
404  * regardless of the active mapping.
405  */
406 struct pmap kernel_pmap_store = {
407 	.pm_pcidp = (void *)0xdeadbeefdeadbeef,
408 };
409 
410 vm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
411 vm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
412 
413 int nkpt;
414 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
415     "Number of kernel page table pages allocated on bootup");
416 
417 static int ndmpdp;
418 vm_paddr_t dmaplimit;
419 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
420 pt_entry_t pg_nx;
421 
422 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
423     "VM/pmap parameters");
424 
425 static int __read_frequently pg_ps_enabled = 1;
426 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
427     &pg_ps_enabled, 0, "Are large page mappings enabled?");
428 
429 int __read_frequently la57 = 0;
430 SYSCTL_INT(_vm_pmap, OID_AUTO, la57, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
431     &la57, 0,
432     "5-level paging for host is enabled");
433 
434 static bool
pmap_is_la57(pmap_t pmap)435 pmap_is_la57(pmap_t pmap)
436 {
437 	if (pmap->pm_type == PT_X86)
438 		return (la57);
439 	return (false);		/* XXXKIB handle EPT */
440 }
441 
442 #define	PAT_INDEX_SIZE	8
443 static int pat_index[PAT_INDEX_SIZE];	/* cache mode to PAT index conversion */
444 
445 static u_int64_t	KPTphys;	/* phys addr of kernel level 1 */
446 static u_int64_t	KPDphys;	/* phys addr of kernel level 2 */
447 static u_int64_t	KPDPphys;	/* phys addr of kernel level 3 */
448 u_int64_t		KPML4phys;	/* phys addr of kernel level 4 */
449 u_int64_t		KPML5phys;	/* phys addr of kernel level 5,
450 					   if supported */
451 
452 #ifdef KASAN
453 static uint64_t		KASANPDPphys;
454 #endif
455 #ifdef KMSAN
456 static uint64_t		KMSANSHADPDPphys;
457 static uint64_t		KMSANORIGPDPphys;
458 
459 /*
460  * To support systems with large amounts of memory, it is necessary to extend
461  * the maximum size of the direct map.  This could eat into the space reserved
462  * for the shadow map.
463  */
464 _Static_assert(DMPML4I + NDMPML4E <= KMSANSHADPML4I, "direct map overflow");
465 #endif
466 
467 static pml4_entry_t	*kernel_pml4;
468 static u_int64_t	DMPDphys;	/* phys addr of direct mapped level 2 */
469 static u_int64_t	DMPDPphys;	/* phys addr of direct mapped level 3 */
470 static int		ndmpdpphys;	/* number of DMPDPphys pages */
471 
472 vm_paddr_t		kernphys;	/* phys addr of start of bootstrap data */
473 vm_paddr_t		KERNend;	/* and the end */
474 
475 /*
476  * pmap_mapdev support pre initialization (i.e. console)
477  */
478 #define	PMAP_PREINIT_MAPPING_COUNT	8
479 static struct pmap_preinit_mapping {
480 	vm_paddr_t	pa;
481 	vm_offset_t	va;
482 	vm_size_t	sz;
483 	int		mode;
484 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
485 static int pmap_initialized;
486 
487 /*
488  * Data for the pv entry allocation mechanism.
489  * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
490  */
491 #ifdef NUMA
492 static __inline int
pc_to_domain(struct pv_chunk * pc)493 pc_to_domain(struct pv_chunk *pc)
494 {
495 
496 	return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
497 }
498 #else
499 static __inline int
pc_to_domain(struct pv_chunk * pc __unused)500 pc_to_domain(struct pv_chunk *pc __unused)
501 {
502 
503 	return (0);
504 }
505 #endif
506 
507 struct pv_chunks_list {
508 	struct mtx pvc_lock;
509 	TAILQ_HEAD(pch, pv_chunk) pvc_list;
510 	int active_reclaims;
511 } __aligned(CACHE_LINE_SIZE);
512 
513 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
514 
515 #ifdef	NUMA
516 struct pmap_large_md_page {
517 	struct rwlock   pv_lock;
518 	struct md_page  pv_page;
519 	u_long pv_invl_gen;
520 };
521 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
522 #define pv_dummy pv_dummy_large.pv_page
523 __read_mostly static struct pmap_large_md_page *pv_table;
524 __read_mostly vm_paddr_t pmap_last_pa;
525 #else
526 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
527 static u_long pv_invl_gen[NPV_LIST_LOCKS];
528 static struct md_page *pv_table;
529 static struct md_page pv_dummy;
530 #endif
531 
532 /*
533  * All those kernel PT submaps that BSD is so fond of
534  */
535 pt_entry_t *CMAP1 = NULL;
536 caddr_t CADDR1 = 0;
537 static vm_offset_t qframe = 0;
538 static struct mtx qframe_mtx;
539 
540 static int pmap_flags = PMAP_PDE_SUPERPAGE;	/* flags for x86 pmaps */
541 
542 static vmem_t *large_vmem;
543 static u_int lm_ents;
544 #define	PMAP_ADDRESS_IN_LARGEMAP(va)	((va) >= LARGEMAP_MIN_ADDRESS && \
545 	(va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
546 
547 int pmap_pcid_enabled = 1;
548 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
549     &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
550 int invpcid_works = 0;
551 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
552     "Is the invpcid instruction available ?");
553 int invlpgb_works;
554 SYSCTL_INT(_vm_pmap, OID_AUTO, invlpgb_works, CTLFLAG_RD, &invlpgb_works, 0,
555     "Is the invlpgb instruction available?");
556 int invlpgb_maxcnt;
557 int pmap_pcid_invlpg_workaround = 0;
558 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_invlpg_workaround,
559     CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
560     &pmap_pcid_invlpg_workaround, 0,
561     "Enable small core PCID/INVLPG workaround");
562 int pmap_pcid_invlpg_workaround_uena = 1;
563 
564 int __read_frequently pti = 0;
565 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
566     &pti, 0,
567     "Page Table Isolation enabled");
568 static vm_object_t pti_obj;
569 static pml4_entry_t *pti_pml4;
570 static vm_pindex_t pti_pg_idx;
571 static bool pti_finalized;
572 
573 struct pmap_pkru_range {
574 	struct rs_el	pkru_rs_el;
575 	u_int		pkru_keyidx;
576 	int		pkru_flags;
577 };
578 
579 static uma_zone_t pmap_pkru_ranges_zone;
580 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
581     pt_entry_t *pte);
582 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
583 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
584 static void *pkru_dup_range(void *ctx, void *data);
585 static void pkru_free_range(void *ctx, void *node);
586 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
587 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
588 static void pmap_pkru_deassign_all(pmap_t pmap);
589 
590 static COUNTER_U64_DEFINE_EARLY(pcid_save_cnt);
591 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLFLAG_RD,
592     &pcid_save_cnt, "Count of saved TLB context on switch");
593 
594 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
595     LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
596 static struct mtx invl_gen_mtx;
597 /* Fake lock object to satisfy turnstiles interface. */
598 static struct lock_object invl_gen_ts = {
599 	.lo_name = "invlts",
600 };
601 static struct pmap_invl_gen pmap_invl_gen_head = {
602 	.gen = 1,
603 	.next = NULL,
604 };
605 static u_long pmap_invl_gen = 1;
606 static int pmap_invl_waiters;
607 static struct callout pmap_invl_callout;
608 static bool pmap_invl_callout_inited;
609 
610 #define	PMAP_ASSERT_NOT_IN_DI() \
611     KASSERT(pmap_not_in_di(), ("DI already started"))
612 
613 static bool
pmap_di_locked(void)614 pmap_di_locked(void)
615 {
616 	int tun;
617 
618 	if ((cpu_feature2 & CPUID2_CX16) == 0)
619 		return (true);
620 	tun = 0;
621 	TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
622 	return (tun != 0);
623 }
624 
625 static int
sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)626 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
627 {
628 	int locked;
629 
630 	locked = pmap_di_locked();
631 	return (sysctl_handle_int(oidp, &locked, 0, req));
632 }
633 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
634     CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
635     "Locked delayed invalidation");
636 
637 static bool pmap_not_in_di_l(void);
638 static bool pmap_not_in_di_u(void);
639 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
640 {
641 
642 	return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
643 }
644 
645 static bool
pmap_not_in_di_l(void)646 pmap_not_in_di_l(void)
647 {
648 	struct pmap_invl_gen *invl_gen;
649 
650 	invl_gen = &curthread->td_md.md_invl_gen;
651 	return (invl_gen->gen == 0);
652 }
653 
654 static void
pmap_thread_init_invl_gen_l(struct thread * td)655 pmap_thread_init_invl_gen_l(struct thread *td)
656 {
657 	struct pmap_invl_gen *invl_gen;
658 
659 	invl_gen = &td->td_md.md_invl_gen;
660 	invl_gen->gen = 0;
661 }
662 
663 static void
pmap_delayed_invl_wait_block(u_long * m_gen,u_long * invl_gen)664 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
665 {
666 	struct turnstile *ts;
667 
668 	ts = turnstile_trywait(&invl_gen_ts);
669 	if (*m_gen > atomic_load_long(invl_gen))
670 		turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
671 	else
672 		turnstile_cancel(ts);
673 }
674 
675 static void
pmap_delayed_invl_finish_unblock(u_long new_gen)676 pmap_delayed_invl_finish_unblock(u_long new_gen)
677 {
678 	struct turnstile *ts;
679 
680 	turnstile_chain_lock(&invl_gen_ts);
681 	ts = turnstile_lookup(&invl_gen_ts);
682 	if (new_gen != 0)
683 		pmap_invl_gen = new_gen;
684 	if (ts != NULL) {
685 		turnstile_broadcast(ts, TS_SHARED_QUEUE);
686 		turnstile_unpend(ts);
687 	}
688 	turnstile_chain_unlock(&invl_gen_ts);
689 }
690 
691 /*
692  * Start a new Delayed Invalidation (DI) block of code, executed by
693  * the current thread.  Within a DI block, the current thread may
694  * destroy both the page table and PV list entries for a mapping and
695  * then release the corresponding PV list lock before ensuring that
696  * the mapping is flushed from the TLBs of any processors with the
697  * pmap active.
698  */
699 static void
pmap_delayed_invl_start_l(void)700 pmap_delayed_invl_start_l(void)
701 {
702 	struct pmap_invl_gen *invl_gen;
703 	u_long currgen;
704 
705 	invl_gen = &curthread->td_md.md_invl_gen;
706 	PMAP_ASSERT_NOT_IN_DI();
707 	mtx_lock(&invl_gen_mtx);
708 	if (LIST_EMPTY(&pmap_invl_gen_tracker))
709 		currgen = pmap_invl_gen;
710 	else
711 		currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
712 	invl_gen->gen = currgen + 1;
713 	LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
714 	mtx_unlock(&invl_gen_mtx);
715 }
716 
717 /*
718  * Finish the DI block, previously started by the current thread.  All
719  * required TLB flushes for the pages marked by
720  * pmap_delayed_invl_page() must be finished before this function is
721  * called.
722  *
723  * This function works by bumping the global DI generation number to
724  * the generation number of the current thread's DI, unless there is a
725  * pending DI that started earlier.  In the latter case, bumping the
726  * global DI generation number would incorrectly signal that the
727  * earlier DI had finished.  Instead, this function bumps the earlier
728  * DI's generation number to match the generation number of the
729  * current thread's DI.
730  */
731 static void
pmap_delayed_invl_finish_l(void)732 pmap_delayed_invl_finish_l(void)
733 {
734 	struct pmap_invl_gen *invl_gen, *next;
735 
736 	invl_gen = &curthread->td_md.md_invl_gen;
737 	KASSERT(invl_gen->gen != 0, ("missed invl_start"));
738 	mtx_lock(&invl_gen_mtx);
739 	next = LIST_NEXT(invl_gen, link);
740 	if (next == NULL)
741 		pmap_delayed_invl_finish_unblock(invl_gen->gen);
742 	else
743 		next->gen = invl_gen->gen;
744 	LIST_REMOVE(invl_gen, link);
745 	mtx_unlock(&invl_gen_mtx);
746 	invl_gen->gen = 0;
747 }
748 
749 static bool
pmap_not_in_di_u(void)750 pmap_not_in_di_u(void)
751 {
752 	struct pmap_invl_gen *invl_gen;
753 
754 	invl_gen = &curthread->td_md.md_invl_gen;
755 	return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
756 }
757 
758 static void
pmap_thread_init_invl_gen_u(struct thread * td)759 pmap_thread_init_invl_gen_u(struct thread *td)
760 {
761 	struct pmap_invl_gen *invl_gen;
762 
763 	invl_gen = &td->td_md.md_invl_gen;
764 	invl_gen->gen = 0;
765 	invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
766 }
767 
768 static bool
pmap_di_load_invl(struct pmap_invl_gen * ptr,struct pmap_invl_gen * out)769 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
770 {
771 	uint64_t new_high, new_low, old_high, old_low;
772 	char res;
773 
774 	old_low = new_low = 0;
775 	old_high = new_high = (uintptr_t)0;
776 
777 	__asm volatile("lock;cmpxchg16b\t%1"
778 	    : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
779 	    : "b"(new_low), "c" (new_high)
780 	    : "memory", "cc");
781 	if (res == 0) {
782 		if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
783 			return (false);
784 		out->gen = old_low;
785 		out->next = (void *)old_high;
786 	} else {
787 		out->gen = new_low;
788 		out->next = (void *)new_high;
789 	}
790 	return (true);
791 }
792 
793 static bool
pmap_di_store_invl(struct pmap_invl_gen * ptr,struct pmap_invl_gen * old_val,struct pmap_invl_gen * new_val)794 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
795     struct pmap_invl_gen *new_val)
796 {
797 	uint64_t new_high, new_low, old_high, old_low;
798 	char res;
799 
800 	new_low = new_val->gen;
801 	new_high = (uintptr_t)new_val->next;
802 	old_low = old_val->gen;
803 	old_high = (uintptr_t)old_val->next;
804 
805 	__asm volatile("lock;cmpxchg16b\t%1"
806 	    : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
807 	    : "b"(new_low), "c" (new_high)
808 	    : "memory", "cc");
809 	return (res);
810 }
811 
812 static COUNTER_U64_DEFINE_EARLY(pv_page_count);
813 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_page_count, CTLFLAG_RD,
814     &pv_page_count, "Current number of allocated pv pages");
815 
816 static COUNTER_U64_DEFINE_EARLY(user_pt_page_count);
817 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, user_pt_page_count, CTLFLAG_RD,
818     &user_pt_page_count,
819     "Current number of allocated page table pages for userspace");
820 
821 static COUNTER_U64_DEFINE_EARLY(kernel_pt_page_count);
822 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, kernel_pt_page_count, CTLFLAG_RD,
823     &kernel_pt_page_count,
824     "Current number of allocated page table pages for the kernel");
825 
826 #ifdef PV_STATS
827 
828 static COUNTER_U64_DEFINE_EARLY(invl_start_restart);
829 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_start_restart,
830     CTLFLAG_RD, &invl_start_restart,
831     "Number of delayed TLB invalidation request restarts");
832 
833 static COUNTER_U64_DEFINE_EARLY(invl_finish_restart);
834 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
835     &invl_finish_restart,
836     "Number of delayed TLB invalidation completion restarts");
837 
838 static int invl_max_qlen;
839 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
840     &invl_max_qlen, 0,
841     "Maximum delayed TLB invalidation request queue length");
842 #endif
843 
844 #define di_delay	locks_delay
845 
846 static void
pmap_delayed_invl_start_u(void)847 pmap_delayed_invl_start_u(void)
848 {
849 	struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
850 	struct thread *td;
851 	struct lock_delay_arg lda;
852 	uintptr_t prevl;
853 	u_char pri;
854 #ifdef PV_STATS
855 	int i, ii;
856 #endif
857 
858 	td = curthread;
859 	invl_gen = &td->td_md.md_invl_gen;
860 	PMAP_ASSERT_NOT_IN_DI();
861 	lock_delay_arg_init(&lda, &di_delay);
862 	invl_gen->saved_pri = 0;
863 	pri = td->td_base_pri;
864 	if (pri > PVM) {
865 		thread_lock(td);
866 		pri = td->td_base_pri;
867 		if (pri > PVM) {
868 			invl_gen->saved_pri = pri;
869 			sched_prio(td, PVM);
870 		}
871 		thread_unlock(td);
872 	}
873 again:
874 	PV_STAT(i = 0);
875 	for (p = &pmap_invl_gen_head;; p = prev.next) {
876 		PV_STAT(i++);
877 		prevl = (uintptr_t)atomic_load_ptr(&p->next);
878 		if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
879 			PV_STAT(counter_u64_add(invl_start_restart, 1));
880 			lock_delay(&lda);
881 			goto again;
882 		}
883 		if (prevl == 0)
884 			break;
885 		prev.next = (void *)prevl;
886 	}
887 #ifdef PV_STATS
888 	if ((ii = invl_max_qlen) < i)
889 		atomic_cmpset_int(&invl_max_qlen, ii, i);
890 #endif
891 
892 	if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
893 		PV_STAT(counter_u64_add(invl_start_restart, 1));
894 		lock_delay(&lda);
895 		goto again;
896 	}
897 
898 	new_prev.gen = prev.gen;
899 	new_prev.next = invl_gen;
900 	invl_gen->gen = prev.gen + 1;
901 
902 	/* Formal fence between store to invl->gen and updating *p. */
903 	atomic_thread_fence_rel();
904 
905 	/*
906 	 * After inserting an invl_gen element with invalid bit set,
907 	 * this thread blocks any other thread trying to enter the
908 	 * delayed invalidation block.  Do not allow to remove us from
909 	 * the CPU, because it causes starvation for other threads.
910 	 */
911 	critical_enter();
912 
913 	/*
914 	 * ABA for *p is not possible there, since p->gen can only
915 	 * increase.  So if the *p thread finished its di, then
916 	 * started a new one and got inserted into the list at the
917 	 * same place, its gen will appear greater than the previously
918 	 * read gen.
919 	 */
920 	if (!pmap_di_store_invl(p, &prev, &new_prev)) {
921 		critical_exit();
922 		PV_STAT(counter_u64_add(invl_start_restart, 1));
923 		lock_delay(&lda);
924 		goto again;
925 	}
926 
927 	/*
928 	 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
929 	 * invl_gen->next, allowing other threads to iterate past us.
930 	 * pmap_di_store_invl() provides fence between the generation
931 	 * write and the update of next.
932 	 */
933 	invl_gen->next = NULL;
934 	critical_exit();
935 }
936 
937 static bool
pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen * invl_gen,struct pmap_invl_gen * p)938 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
939     struct pmap_invl_gen *p)
940 {
941 	struct pmap_invl_gen prev, new_prev;
942 	u_long mygen;
943 
944 	/*
945 	 * Load invl_gen->gen after setting invl_gen->next
946 	 * PMAP_INVL_GEN_NEXT_INVALID.  This prevents larger
947 	 * generations to propagate to our invl_gen->gen.  Lock prefix
948 	 * in atomic_set_ptr() worked as seq_cst fence.
949 	 */
950 	mygen = atomic_load_long(&invl_gen->gen);
951 
952 	if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
953 		return (false);
954 
955 	KASSERT(prev.gen < mygen,
956 	    ("invalid di gen sequence %lu %lu", prev.gen, mygen));
957 	new_prev.gen = mygen;
958 	new_prev.next = (void *)((uintptr_t)invl_gen->next &
959 	    ~PMAP_INVL_GEN_NEXT_INVALID);
960 
961 	/* Formal fence between load of prev and storing update to it. */
962 	atomic_thread_fence_rel();
963 
964 	return (pmap_di_store_invl(p, &prev, &new_prev));
965 }
966 
967 static void
pmap_delayed_invl_finish_u(void)968 pmap_delayed_invl_finish_u(void)
969 {
970 	struct pmap_invl_gen *invl_gen, *p;
971 	struct thread *td;
972 	struct lock_delay_arg lda;
973 	uintptr_t prevl;
974 
975 	td = curthread;
976 	invl_gen = &td->td_md.md_invl_gen;
977 	KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
978 	KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
979 	    ("missed invl_start: INVALID"));
980 	lock_delay_arg_init(&lda, &di_delay);
981 
982 again:
983 	for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
984 		prevl = (uintptr_t)atomic_load_ptr(&p->next);
985 		if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
986 			PV_STAT(counter_u64_add(invl_finish_restart, 1));
987 			lock_delay(&lda);
988 			goto again;
989 		}
990 		if ((void *)prevl == invl_gen)
991 			break;
992 	}
993 
994 	/*
995 	 * It is legitimate to not find ourself on the list if a
996 	 * thread before us finished its DI and started it again.
997 	 */
998 	if (__predict_false(p == NULL)) {
999 		PV_STAT(counter_u64_add(invl_finish_restart, 1));
1000 		lock_delay(&lda);
1001 		goto again;
1002 	}
1003 
1004 	critical_enter();
1005 	atomic_set_ptr((uintptr_t *)&invl_gen->next,
1006 	    PMAP_INVL_GEN_NEXT_INVALID);
1007 	if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
1008 		atomic_clear_ptr((uintptr_t *)&invl_gen->next,
1009 		    PMAP_INVL_GEN_NEXT_INVALID);
1010 		critical_exit();
1011 		PV_STAT(counter_u64_add(invl_finish_restart, 1));
1012 		lock_delay(&lda);
1013 		goto again;
1014 	}
1015 	critical_exit();
1016 	if (atomic_load_int(&pmap_invl_waiters) > 0)
1017 		pmap_delayed_invl_finish_unblock(0);
1018 	if (invl_gen->saved_pri != 0) {
1019 		thread_lock(td);
1020 		sched_prio(td, invl_gen->saved_pri);
1021 		thread_unlock(td);
1022 	}
1023 }
1024 
1025 #ifdef DDB
DB_SHOW_COMMAND(di_queue,pmap_di_queue)1026 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
1027 {
1028 	struct pmap_invl_gen *p, *pn;
1029 	struct thread *td;
1030 	uintptr_t nextl;
1031 	bool first;
1032 
1033 	for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
1034 	    first = false) {
1035 		nextl = (uintptr_t)atomic_load_ptr(&p->next);
1036 		pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
1037 		td = first ? NULL : __containerof(p, struct thread,
1038 		    td_md.md_invl_gen);
1039 		db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
1040 		    (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
1041 		    td != NULL ? td->td_tid : -1);
1042 	}
1043 }
1044 #endif
1045 
1046 #ifdef PV_STATS
1047 static COUNTER_U64_DEFINE_EARLY(invl_wait);
1048 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait,
1049     CTLFLAG_RD, &invl_wait,
1050     "Number of times DI invalidation blocked pmap_remove_all/write");
1051 
1052 static COUNTER_U64_DEFINE_EARLY(invl_wait_slow);
1053 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD,
1054      &invl_wait_slow, "Number of slow invalidation waits for lockless DI");
1055 
1056 #endif
1057 
1058 #ifdef NUMA
1059 static u_long *
pmap_delayed_invl_genp(vm_page_t m)1060 pmap_delayed_invl_genp(vm_page_t m)
1061 {
1062 	vm_paddr_t pa;
1063 	u_long *gen;
1064 
1065 	pa = VM_PAGE_TO_PHYS(m);
1066 	if (__predict_false((pa) > pmap_last_pa))
1067 		gen = &pv_dummy_large.pv_invl_gen;
1068 	else
1069 		gen = &(pa_to_pmdp(pa)->pv_invl_gen);
1070 
1071 	return (gen);
1072 }
1073 #else
1074 static u_long *
pmap_delayed_invl_genp(vm_page_t m)1075 pmap_delayed_invl_genp(vm_page_t m)
1076 {
1077 
1078 	return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
1079 }
1080 #endif
1081 
1082 static void
pmap_delayed_invl_callout_func(void * arg __unused)1083 pmap_delayed_invl_callout_func(void *arg __unused)
1084 {
1085 
1086 	if (atomic_load_int(&pmap_invl_waiters) == 0)
1087 		return;
1088 	pmap_delayed_invl_finish_unblock(0);
1089 }
1090 
1091 static void
pmap_delayed_invl_callout_init(void * arg __unused)1092 pmap_delayed_invl_callout_init(void *arg __unused)
1093 {
1094 
1095 	if (pmap_di_locked())
1096 		return;
1097 	callout_init(&pmap_invl_callout, 1);
1098 	pmap_invl_callout_inited = true;
1099 }
1100 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
1101     pmap_delayed_invl_callout_init, NULL);
1102 
1103 /*
1104  * Ensure that all currently executing DI blocks, that need to flush
1105  * TLB for the given page m, actually flushed the TLB at the time the
1106  * function returned.  If the page m has an empty PV list and we call
1107  * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1108  * valid mapping for the page m in either its page table or TLB.
1109  *
1110  * This function works by blocking until the global DI generation
1111  * number catches up with the generation number associated with the
1112  * given page m and its PV list.  Since this function's callers
1113  * typically own an object lock and sometimes own a page lock, it
1114  * cannot sleep.  Instead, it blocks on a turnstile to relinquish the
1115  * processor.
1116  */
1117 static void
pmap_delayed_invl_wait_l(vm_page_t m)1118 pmap_delayed_invl_wait_l(vm_page_t m)
1119 {
1120 	u_long *m_gen;
1121 #ifdef PV_STATS
1122 	bool accounted = false;
1123 #endif
1124 
1125 	m_gen = pmap_delayed_invl_genp(m);
1126 	while (*m_gen > pmap_invl_gen) {
1127 #ifdef PV_STATS
1128 		if (!accounted) {
1129 			counter_u64_add(invl_wait, 1);
1130 			accounted = true;
1131 		}
1132 #endif
1133 		pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1134 	}
1135 }
1136 
1137 static void
pmap_delayed_invl_wait_u(vm_page_t m)1138 pmap_delayed_invl_wait_u(vm_page_t m)
1139 {
1140 	u_long *m_gen;
1141 	struct lock_delay_arg lda;
1142 	bool fast;
1143 
1144 	fast = true;
1145 	m_gen = pmap_delayed_invl_genp(m);
1146 	lock_delay_arg_init(&lda, &di_delay);
1147 	while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1148 		if (fast || !pmap_invl_callout_inited) {
1149 			PV_STAT(counter_u64_add(invl_wait, 1));
1150 			lock_delay(&lda);
1151 			fast = false;
1152 		} else {
1153 			/*
1154 			 * The page's invalidation generation number
1155 			 * is still below the current thread's number.
1156 			 * Prepare to block so that we do not waste
1157 			 * CPU cycles or worse, suffer livelock.
1158 			 *
1159 			 * Since it is impossible to block without
1160 			 * racing with pmap_delayed_invl_finish_u(),
1161 			 * prepare for the race by incrementing
1162 			 * pmap_invl_waiters and arming a 1-tick
1163 			 * callout which will unblock us if we lose
1164 			 * the race.
1165 			 */
1166 			atomic_add_int(&pmap_invl_waiters, 1);
1167 
1168 			/*
1169 			 * Re-check the current thread's invalidation
1170 			 * generation after incrementing
1171 			 * pmap_invl_waiters, so that there is no race
1172 			 * with pmap_delayed_invl_finish_u() setting
1173 			 * the page generation and checking
1174 			 * pmap_invl_waiters.  The only race allowed
1175 			 * is for a missed unblock, which is handled
1176 			 * by the callout.
1177 			 */
1178 			if (*m_gen >
1179 			    atomic_load_long(&pmap_invl_gen_head.gen)) {
1180 				callout_reset(&pmap_invl_callout, 1,
1181 				    pmap_delayed_invl_callout_func, NULL);
1182 				PV_STAT(counter_u64_add(invl_wait_slow, 1));
1183 				pmap_delayed_invl_wait_block(m_gen,
1184 				    &pmap_invl_gen_head.gen);
1185 			}
1186 			atomic_add_int(&pmap_invl_waiters, -1);
1187 		}
1188 	}
1189 }
1190 
1191 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1192 {
1193 
1194 	return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1195 	    pmap_thread_init_invl_gen_u);
1196 }
1197 
1198 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1199 {
1200 
1201 	return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1202 	    pmap_delayed_invl_start_u);
1203 }
1204 
1205 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1206 {
1207 
1208 	return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1209 	    pmap_delayed_invl_finish_u);
1210 }
1211 
1212 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1213 {
1214 
1215 	return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1216 	    pmap_delayed_invl_wait_u);
1217 }
1218 
1219 /*
1220  * Mark the page m's PV list as participating in the current thread's
1221  * DI block.  Any threads concurrently using m's PV list to remove or
1222  * restrict all mappings to m will wait for the current thread's DI
1223  * block to complete before proceeding.
1224  *
1225  * The function works by setting the DI generation number for m's PV
1226  * list to at least the DI generation number of the current thread.
1227  * This forces a caller of pmap_delayed_invl_wait() to block until
1228  * current thread calls pmap_delayed_invl_finish().
1229  */
1230 static void
pmap_delayed_invl_page(vm_page_t m)1231 pmap_delayed_invl_page(vm_page_t m)
1232 {
1233 	u_long gen, *m_gen;
1234 
1235 	rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1236 	gen = curthread->td_md.md_invl_gen.gen;
1237 	if (gen == 0)
1238 		return;
1239 	m_gen = pmap_delayed_invl_genp(m);
1240 	if (*m_gen < gen)
1241 		*m_gen = gen;
1242 }
1243 
1244 /*
1245  * Crashdump maps.
1246  */
1247 static caddr_t crashdumpmap;
1248 
1249 /*
1250  * Internal flags for pmap_enter()'s helper functions.
1251  */
1252 #define	PMAP_ENTER_NORECLAIM	0x1000000	/* Don't reclaim PV entries. */
1253 #define	PMAP_ENTER_NOREPLACE	0x2000000	/* Don't replace mappings. */
1254 
1255 /*
1256  * Internal flags for pmap_mapdev_internal() and
1257  * pmap_change_props_locked().
1258  */
1259 #define	MAPDEV_FLUSHCACHE	0x00000001	/* Flush cache after mapping. */
1260 #define	MAPDEV_SETATTR		0x00000002	/* Modify existing attrs. */
1261 #define	MAPDEV_ASSERTVALID	0x00000004	/* Assert mapping validity. */
1262 
1263 TAILQ_HEAD(pv_chunklist, pv_chunk);
1264 
1265 static void	free_pv_chunk(struct pv_chunk *pc);
1266 static void	free_pv_chunk_batch(struct pv_chunklist *batch);
1267 static void	free_pv_entry(pmap_t pmap, pv_entry_t pv);
1268 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1269 static int	popcnt_pc_map_pq(uint64_t *map);
1270 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1271 static void	reserve_pv_entries(pmap_t pmap, int needed,
1272 		    struct rwlock **lockp);
1273 static void	pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1274 		    struct rwlock **lockp);
1275 static bool	pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1276 		    u_int flags, struct rwlock **lockp);
1277 #if VM_NRESERVLEVEL > 0
1278 static void	pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1279 		    struct rwlock **lockp);
1280 #endif
1281 static void	pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1282 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1283 		    vm_offset_t va);
1284 
1285 static void	pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
1286 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1287     vm_prot_t prot, int mode, int flags);
1288 static bool	pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1289 static bool	pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1290     vm_offset_t va, struct rwlock **lockp);
1291 static bool	pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1292     vm_offset_t va);
1293 static int	pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1294 		    vm_prot_t prot, struct rwlock **lockp);
1295 static int	pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1296 		    u_int flags, vm_page_t m, struct rwlock **lockp);
1297 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1298     vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1299 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1300 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
1301     bool allpte_PG_A_set);
1302 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1303     vm_offset_t eva);
1304 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1305     vm_offset_t eva);
1306 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1307 		    pd_entry_t pde);
1308 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1309 static vm_page_t pmap_large_map_getptp_unlocked(void);
1310 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1311 #if VM_NRESERVLEVEL > 0
1312 static bool pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1313     vm_page_t mpte, struct rwlock **lockp);
1314 #endif
1315 static bool pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1316     vm_prot_t prot);
1317 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1318 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1319     bool exec);
1320 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1321 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1322 static void pmap_pti_wire_pte(void *pte);
1323 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1324     struct spglist *free, struct rwlock **lockp);
1325 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1326     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1327 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1328 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1329     struct spglist *free);
1330 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1331 		    pd_entry_t *pde, struct spglist *free,
1332 		    struct rwlock **lockp);
1333 static bool pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1334     vm_page_t m, struct rwlock **lockp);
1335 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1336     pd_entry_t newpde);
1337 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1338 
1339 static pd_entry_t *pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
1340 		struct rwlock **lockp);
1341 static vm_page_t pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex,
1342 		struct rwlock **lockp, vm_offset_t va);
1343 static vm_page_t pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex,
1344 		struct rwlock **lockp, vm_offset_t va);
1345 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1346 		struct rwlock **lockp);
1347 
1348 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1349     struct spglist *free);
1350 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1351 
1352 static vm_page_t pmap_alloc_pt_page(pmap_t, vm_pindex_t, int);
1353 static void pmap_free_pt_page(pmap_t, vm_page_t, bool);
1354 
1355 /********************/
1356 /* Inline functions */
1357 /********************/
1358 
1359 /*
1360  * Return a non-clipped indexes for a given VA, which are page table
1361  * pages indexes at the corresponding level.
1362  */
1363 static __inline vm_pindex_t
pmap_pde_pindex(vm_offset_t va)1364 pmap_pde_pindex(vm_offset_t va)
1365 {
1366 	return (va >> PDRSHIFT);
1367 }
1368 
1369 static __inline vm_pindex_t
pmap_pdpe_pindex(vm_offset_t va)1370 pmap_pdpe_pindex(vm_offset_t va)
1371 {
1372 	return (NUPDE + (va >> PDPSHIFT));
1373 }
1374 
1375 static __inline vm_pindex_t
pmap_pml4e_pindex(vm_offset_t va)1376 pmap_pml4e_pindex(vm_offset_t va)
1377 {
1378 	return (NUPDE + NUPDPE + (va >> PML4SHIFT));
1379 }
1380 
1381 static __inline vm_pindex_t
pmap_pml5e_pindex(vm_offset_t va)1382 pmap_pml5e_pindex(vm_offset_t va)
1383 {
1384 	return (NUPDE + NUPDPE + NUPML4E + (va >> PML5SHIFT));
1385 }
1386 
1387 static __inline pml4_entry_t *
pmap_pml5e(pmap_t pmap,vm_offset_t va)1388 pmap_pml5e(pmap_t pmap, vm_offset_t va)
1389 {
1390 
1391 	MPASS(pmap_is_la57(pmap));
1392 	return (&pmap->pm_pmltop[pmap_pml5e_index(va)]);
1393 }
1394 
1395 static __inline pml4_entry_t *
pmap_pml5e_u(pmap_t pmap,vm_offset_t va)1396 pmap_pml5e_u(pmap_t pmap, vm_offset_t va)
1397 {
1398 
1399 	MPASS(pmap_is_la57(pmap));
1400 	return (&pmap->pm_pmltopu[pmap_pml5e_index(va)]);
1401 }
1402 
1403 static __inline pml4_entry_t *
pmap_pml5e_to_pml4e(pml5_entry_t * pml5e,vm_offset_t va)1404 pmap_pml5e_to_pml4e(pml5_entry_t *pml5e, vm_offset_t va)
1405 {
1406 	pml4_entry_t *pml4e;
1407 
1408 	/* XXX MPASS(pmap_is_la57(pmap); */
1409 	pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1410 	return (&pml4e[pmap_pml4e_index(va)]);
1411 }
1412 
1413 /* Return a pointer to the PML4 slot that corresponds to a VA */
1414 static __inline pml4_entry_t *
pmap_pml4e(pmap_t pmap,vm_offset_t va)1415 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1416 {
1417 	pml5_entry_t *pml5e;
1418 	pml4_entry_t *pml4e;
1419 	pt_entry_t PG_V;
1420 
1421 	if (pmap_is_la57(pmap)) {
1422 		pml5e = pmap_pml5e(pmap, va);
1423 		PG_V = pmap_valid_bit(pmap);
1424 		if ((*pml5e & PG_V) == 0)
1425 			return (NULL);
1426 		pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1427 	} else {
1428 		pml4e = pmap->pm_pmltop;
1429 	}
1430 	return (&pml4e[pmap_pml4e_index(va)]);
1431 }
1432 
1433 static __inline pml4_entry_t *
pmap_pml4e_u(pmap_t pmap,vm_offset_t va)1434 pmap_pml4e_u(pmap_t pmap, vm_offset_t va)
1435 {
1436 	MPASS(!pmap_is_la57(pmap));
1437 	return (&pmap->pm_pmltopu[pmap_pml4e_index(va)]);
1438 }
1439 
1440 /* Return a pointer to the PDP slot that corresponds to a VA */
1441 static __inline pdp_entry_t *
pmap_pml4e_to_pdpe(pml4_entry_t * pml4e,vm_offset_t va)1442 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1443 {
1444 	pdp_entry_t *pdpe;
1445 
1446 	pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1447 	return (&pdpe[pmap_pdpe_index(va)]);
1448 }
1449 
1450 /* Return a pointer to the PDP slot that corresponds to a VA */
1451 static __inline pdp_entry_t *
pmap_pdpe(pmap_t pmap,vm_offset_t va)1452 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1453 {
1454 	pml4_entry_t *pml4e;
1455 	pt_entry_t PG_V;
1456 
1457 	PG_V = pmap_valid_bit(pmap);
1458 	pml4e = pmap_pml4e(pmap, va);
1459 	if (pml4e == NULL || (*pml4e & PG_V) == 0)
1460 		return (NULL);
1461 	return (pmap_pml4e_to_pdpe(pml4e, va));
1462 }
1463 
1464 /* Return a pointer to the PD slot that corresponds to a VA */
1465 static __inline pd_entry_t *
pmap_pdpe_to_pde(pdp_entry_t * pdpe,vm_offset_t va)1466 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1467 {
1468 	pd_entry_t *pde;
1469 
1470 	KASSERT((*pdpe & PG_PS) == 0,
1471 	    ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
1472 	pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1473 	return (&pde[pmap_pde_index(va)]);
1474 }
1475 
1476 /* Return a pointer to the PD slot that corresponds to a VA */
1477 static __inline pd_entry_t *
pmap_pde(pmap_t pmap,vm_offset_t va)1478 pmap_pde(pmap_t pmap, vm_offset_t va)
1479 {
1480 	pdp_entry_t *pdpe;
1481 	pt_entry_t PG_V;
1482 
1483 	PG_V = pmap_valid_bit(pmap);
1484 	pdpe = pmap_pdpe(pmap, va);
1485 	if (pdpe == NULL || (*pdpe & PG_V) == 0)
1486 		return (NULL);
1487 	KASSERT((*pdpe & PG_PS) == 0,
1488 	    ("pmap_pde for 1G page, pmap %p va %#lx", pmap, va));
1489 	return (pmap_pdpe_to_pde(pdpe, va));
1490 }
1491 
1492 /* Return a pointer to the PT slot that corresponds to a VA */
1493 static __inline pt_entry_t *
pmap_pde_to_pte(pd_entry_t * pde,vm_offset_t va)1494 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1495 {
1496 	pt_entry_t *pte;
1497 
1498 	KASSERT((*pde & PG_PS) == 0,
1499 	    ("%s: pde %#lx is a leaf", __func__, *pde));
1500 	pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1501 	return (&pte[pmap_pte_index(va)]);
1502 }
1503 
1504 /* Return a pointer to the PT slot that corresponds to a VA */
1505 static __inline pt_entry_t *
pmap_pte(pmap_t pmap,vm_offset_t va)1506 pmap_pte(pmap_t pmap, vm_offset_t va)
1507 {
1508 	pd_entry_t *pde;
1509 	pt_entry_t PG_V;
1510 
1511 	PG_V = pmap_valid_bit(pmap);
1512 	pde = pmap_pde(pmap, va);
1513 	if (pde == NULL || (*pde & PG_V) == 0)
1514 		return (NULL);
1515 	if ((*pde & PG_PS) != 0)	/* compat with i386 pmap_pte() */
1516 		return ((pt_entry_t *)pde);
1517 	return (pmap_pde_to_pte(pde, va));
1518 }
1519 
1520 static __inline void
pmap_resident_count_adj(pmap_t pmap,int count)1521 pmap_resident_count_adj(pmap_t pmap, int count)
1522 {
1523 
1524 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1525 	KASSERT(pmap->pm_stats.resident_count + count >= 0,
1526 	    ("pmap %p resident count underflow %ld %d", pmap,
1527 	    pmap->pm_stats.resident_count, count));
1528 	pmap->pm_stats.resident_count += count;
1529 }
1530 
1531 static __inline void
pmap_pt_page_count_pinit(pmap_t pmap,int count)1532 pmap_pt_page_count_pinit(pmap_t pmap, int count)
1533 {
1534 	KASSERT(pmap->pm_stats.resident_count + count >= 0,
1535 	    ("pmap %p resident count underflow %ld %d", pmap,
1536 	    pmap->pm_stats.resident_count, count));
1537 	pmap->pm_stats.resident_count += count;
1538 }
1539 
1540 static __inline void
pmap_pt_page_count_adj(pmap_t pmap,int count)1541 pmap_pt_page_count_adj(pmap_t pmap, int count)
1542 {
1543 	if (pmap == kernel_pmap)
1544 		counter_u64_add(kernel_pt_page_count, count);
1545 	else {
1546 		if (pmap != NULL)
1547 			pmap_resident_count_adj(pmap, count);
1548 		counter_u64_add(user_pt_page_count, count);
1549 	}
1550 }
1551 
1552 pt_entry_t vtoptem __read_mostly = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
1553     NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1) << 3;
1554 vm_offset_t PTmap __read_mostly = (vm_offset_t)P4Tmap;
1555 
1556 pt_entry_t *
vtopte(vm_offset_t va)1557 vtopte(vm_offset_t va)
1558 {
1559 	KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1560 
1561 	return ((pt_entry_t *)(PTmap + ((va >> (PAGE_SHIFT - 3)) & vtoptem)));
1562 }
1563 
1564 pd_entry_t vtopdem __read_mostly = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
1565     NPML4EPGSHIFT)) - 1) << 3;
1566 vm_offset_t PDmap __read_mostly = (vm_offset_t)P4Dmap;
1567 
1568 static __inline pd_entry_t *
vtopde(vm_offset_t va)1569 vtopde(vm_offset_t va)
1570 {
1571 	KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1572 
1573 	return ((pt_entry_t *)(PDmap + ((va >> (PDRSHIFT - 3)) & vtopdem)));
1574 }
1575 
1576 static u_int64_t
allocpages(vm_paddr_t * firstaddr,int n)1577 allocpages(vm_paddr_t *firstaddr, int n)
1578 {
1579 	u_int64_t ret;
1580 
1581 	ret = *firstaddr;
1582 	bzero((void *)ret, n * PAGE_SIZE);
1583 	*firstaddr += n * PAGE_SIZE;
1584 	return (ret);
1585 }
1586 
1587 CTASSERT(powerof2(NDMPML4E));
1588 
1589 /* number of kernel PDP slots */
1590 #define	NKPDPE(ptpgs)		howmany(ptpgs, NPDEPG)
1591 
1592 static void
nkpt_init(vm_paddr_t addr)1593 nkpt_init(vm_paddr_t addr)
1594 {
1595 	int pt_pages;
1596 
1597 #ifdef NKPT
1598 	pt_pages = NKPT;
1599 #else
1600 	pt_pages = howmany(addr - kernphys, NBPDR) + 1; /* +1 for 2M hole @0 */
1601 	pt_pages += NKPDPE(pt_pages);
1602 
1603 	/*
1604 	 * Add some slop beyond the bare minimum required for bootstrapping
1605 	 * the kernel.
1606 	 *
1607 	 * This is quite important when allocating KVA for kernel modules.
1608 	 * The modules are required to be linked in the negative 2GB of
1609 	 * the address space.  If we run out of KVA in this region then
1610 	 * pmap_growkernel() will need to allocate page table pages to map
1611 	 * the entire 512GB of KVA space which is an unnecessary tax on
1612 	 * physical memory.
1613 	 *
1614 	 * Secondly, device memory mapped as part of setting up the low-
1615 	 * level console(s) is taken from KVA, starting at virtual_avail.
1616 	 * This is because cninit() is called after pmap_bootstrap() but
1617 	 * before vm_mem_init() and pmap_init(). 20MB for a frame buffer
1618 	 * is not uncommon.
1619 	 */
1620 	pt_pages += 32;		/* 64MB additional slop. */
1621 #endif
1622 	nkpt = pt_pages;
1623 }
1624 
1625 /*
1626  * Returns the proper write/execute permission for a physical page that is
1627  * part of the initial boot allocations.
1628  *
1629  * If the page has kernel text, it is marked as read-only. If the page has
1630  * kernel read-only data, it is marked as read-only/not-executable. If the
1631  * page has only read-write data, it is marked as read-write/not-executable.
1632  * If the page is below/above the kernel range, it is marked as read-write.
1633  *
1634  * This function operates on 2M pages, since we map the kernel space that
1635  * way.
1636  */
1637 static inline pt_entry_t
bootaddr_rwx(vm_paddr_t pa)1638 bootaddr_rwx(vm_paddr_t pa)
1639 {
1640 	/*
1641 	 * The kernel is loaded at a 2MB-aligned address, and memory below that
1642 	 * need not be executable.  The .bss section is padded to a 2MB
1643 	 * boundary, so memory following the kernel need not be executable
1644 	 * either.  Preloaded kernel modules have their mapping permissions
1645 	 * fixed up by the linker.
1646 	 */
1647 	if (pa < trunc_2mpage(kernphys + btext - KERNSTART) ||
1648 	    pa >= trunc_2mpage(kernphys + _end - KERNSTART))
1649 		return (X86_PG_RW | pg_nx);
1650 
1651 	/*
1652 	 * The linker should ensure that the read-only and read-write
1653 	 * portions don't share the same 2M page, so this shouldn't
1654 	 * impact read-only data. However, in any case, any page with
1655 	 * read-write data needs to be read-write.
1656 	 */
1657 	if (pa >= trunc_2mpage(kernphys + brwsection - KERNSTART))
1658 		return (X86_PG_RW | pg_nx);
1659 
1660 	/*
1661 	 * Mark any 2M page containing kernel text as read-only. Mark
1662 	 * other pages with read-only data as read-only and not executable.
1663 	 * (It is likely a small portion of the read-only data section will
1664 	 * be marked as read-only, but executable. This should be acceptable
1665 	 * since the read-only protection will keep the data from changing.)
1666 	 * Note that fixups to the .text section will still work until we
1667 	 * set CR0.WP.
1668 	 */
1669 	if (pa < round_2mpage(kernphys + etext - KERNSTART))
1670 		return (0);
1671 	return (pg_nx);
1672 }
1673 
1674 static void
create_pagetables(vm_paddr_t * firstaddr)1675 create_pagetables(vm_paddr_t *firstaddr)
1676 {
1677 	pd_entry_t *pd_p;
1678 	pdp_entry_t *pdp_p;
1679 	pml4_entry_t *p4_p;
1680 	uint64_t DMPDkernphys;
1681 	vm_paddr_t pax;
1682 #ifdef KASAN
1683 	pt_entry_t *pt_p;
1684 	uint64_t KASANPDphys, KASANPTphys, KASANphys;
1685 	vm_offset_t kasankernbase;
1686 	int kasankpdpi, kasankpdi, nkasanpte;
1687 #endif
1688 	int i, j, ndm1g, nkpdpe, nkdmpde;
1689 
1690 	TSENTER();
1691 	/* Allocate page table pages for the direct map */
1692 	ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1693 	if (ndmpdp < 4)		/* Minimum 4GB of dirmap */
1694 		ndmpdp = 4;
1695 	ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1696 	if (ndmpdpphys > NDMPML4E) {
1697 		/*
1698 		 * Each NDMPML4E allows 512 GB, so limit to that,
1699 		 * and then readjust ndmpdp and ndmpdpphys.
1700 		 */
1701 		printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1702 		Maxmem = atop(NDMPML4E * NBPML4);
1703 		ndmpdpphys = NDMPML4E;
1704 		ndmpdp = NDMPML4E * NPDEPG;
1705 	}
1706 	DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1707 	ndm1g = 0;
1708 	if ((amd_feature & AMDID_PAGE1GB) != 0) {
1709 		/*
1710 		 * Calculate the number of 1G pages that will fully fit in
1711 		 * Maxmem.
1712 		 */
1713 		ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1714 
1715 		/*
1716 		 * Allocate 2M pages for the kernel. These will be used in
1717 		 * place of the one or more 1G pages from ndm1g that maps
1718 		 * kernel memory into DMAP.
1719 		 */
1720 		nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1721 		    kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1722 		DMPDkernphys = allocpages(firstaddr, nkdmpde);
1723 	}
1724 	if (ndm1g < ndmpdp)
1725 		DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1726 	dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1727 
1728 	/* Allocate pages. */
1729 	KPML4phys = allocpages(firstaddr, 1);
1730 	KPDPphys = allocpages(firstaddr, NKPML4E);
1731 #ifdef KASAN
1732 	KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1733 	KASANPDphys = allocpages(firstaddr, 1);
1734 #endif
1735 #ifdef KMSAN
1736 	/*
1737 	 * The KMSAN shadow maps are initially left unpopulated, since there is
1738 	 * no need to shadow memory above KERNBASE.
1739 	 */
1740 	KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1741 	KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1742 #endif
1743 
1744 	/*
1745 	 * Allocate the initial number of kernel page table pages required to
1746 	 * bootstrap.  We defer this until after all memory-size dependent
1747 	 * allocations are done (e.g. direct map), so that we don't have to
1748 	 * build in too much slop in our estimate.
1749 	 *
1750 	 * Note that when NKPML4E > 1, we have an empty page underneath
1751 	 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1752 	 * pages.  (pmap_enter requires a PD page to exist for each KPML4E.)
1753 	 */
1754 	nkpt_init(*firstaddr);
1755 	nkpdpe = NKPDPE(nkpt);
1756 
1757 	KPTphys = allocpages(firstaddr, nkpt);
1758 	KPDphys = allocpages(firstaddr, nkpdpe);
1759 
1760 #ifdef KASAN
1761 	nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1762 	KASANPTphys = allocpages(firstaddr, nkasanpte);
1763 	KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1764 #endif
1765 
1766 	/*
1767 	 * Connect the zero-filled PT pages to their PD entries.  This
1768 	 * implicitly maps the PT pages at their correct locations within
1769 	 * the PTmap.
1770 	 */
1771 	pd_p = (pd_entry_t *)KPDphys;
1772 	for (i = 0; i < nkpt; i++)
1773 		pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1774 
1775 	/*
1776 	 * Map from start of the kernel in physical memory (staging
1777 	 * area) to the end of loader preallocated memory using 2MB
1778 	 * pages.  This replaces some of the PD entries created above.
1779 	 * For compatibility, identity map 2M at the start.
1780 	 */
1781 	pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1782 	    X86_PG_RW | pg_nx;
1783 	for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1784 		/* Preset PG_M and PG_A because demotion expects it. */
1785 		pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1786 		    X86_PG_A | bootaddr_rwx(pax);
1787 	}
1788 
1789 	/*
1790 	 * Because we map the physical blocks in 2M pages, adjust firstaddr
1791 	 * to record the physical blocks we've actually mapped into kernel
1792 	 * virtual address space.
1793 	 */
1794 	if (*firstaddr < round_2mpage(KERNend))
1795 		*firstaddr = round_2mpage(KERNend);
1796 
1797 	/* And connect up the PD to the PDP (leaving room for L4 pages) */
1798 	pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1799 	for (i = 0; i < nkpdpe; i++)
1800 		pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1801 
1802 #ifdef KASAN
1803 	kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1804 	kasankpdpi = pmap_pdpe_index(kasankernbase);
1805 	kasankpdi = pmap_pde_index(kasankernbase);
1806 
1807 	pdp_p = (pdp_entry_t *)KASANPDPphys;
1808 	pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1809 
1810 	pd_p = (pd_entry_t *)KASANPDphys;
1811 	for (i = 0; i < nkasanpte; i++)
1812 		pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1813 		    X86_PG_V | pg_nx;
1814 
1815 	pt_p = (pt_entry_t *)KASANPTphys;
1816 	for (i = 0; i < nkasanpte * NPTEPG; i++)
1817 		pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1818 		    X86_PG_M | X86_PG_A | pg_nx;
1819 #endif
1820 
1821 	/*
1822 	 * Now, set up the direct map region using 2MB and/or 1GB pages.  If
1823 	 * the end of physical memory is not aligned to a 1GB page boundary,
1824 	 * then the residual physical memory is mapped with 2MB pages.  Later,
1825 	 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1826 	 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1827 	 * that are partially used.
1828 	 */
1829 	pd_p = (pd_entry_t *)DMPDphys;
1830 	for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1831 		pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1832 		/* Preset PG_M and PG_A because demotion expects it. */
1833 		pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1834 		    X86_PG_M | X86_PG_A | pg_nx;
1835 	}
1836 	pdp_p = (pdp_entry_t *)DMPDPphys;
1837 	for (i = 0; i < ndm1g; i++) {
1838 		pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1839 		/* Preset PG_M and PG_A because demotion expects it. */
1840 		pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1841 		    X86_PG_M | X86_PG_A | pg_nx;
1842 	}
1843 	for (j = 0; i < ndmpdp; i++, j++) {
1844 		pdp_p[i] = DMPDphys + ptoa(j);
1845 		pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1846 	}
1847 
1848 	/*
1849 	 * Instead of using a 1G page for the memory containing the kernel,
1850 	 * use 2M pages with read-only and no-execute permissions.  (If using 1G
1851 	 * pages, this will partially overwrite the PDPEs above.)
1852 	 */
1853 	if (ndm1g > 0) {
1854 		pd_p = (pd_entry_t *)DMPDkernphys;
1855 		for (i = 0, pax = rounddown2(kernphys, NBPDP);
1856 		    i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1857 			pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1858 			    X86_PG_A | pg_nx | bootaddr_rwx(pax);
1859 		}
1860 		j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1861 		for (i = 0; i < nkdmpde; i++) {
1862 			pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1863 			    X86_PG_RW | X86_PG_V | pg_nx;
1864 		}
1865 	}
1866 
1867 	/* And recursively map PML4 to itself in order to get PTmap */
1868 	p4_p = (pml4_entry_t *)KPML4phys;
1869 	p4_p[PML4PML4I] = KPML4phys;
1870 	p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1871 
1872 #ifdef KASAN
1873 	/* Connect the KASAN shadow map slots up to the PML4. */
1874 	for (i = 0; i < NKASANPML4E; i++) {
1875 		p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1876 		p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1877 	}
1878 #endif
1879 
1880 #ifdef KMSAN
1881 	/* Connect the KMSAN shadow map slots up to the PML4. */
1882 	for (i = 0; i < NKMSANSHADPML4E; i++) {
1883 		p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1884 		p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1885 	}
1886 
1887 	/* Connect the KMSAN origin map slots up to the PML4. */
1888 	for (i = 0; i < NKMSANORIGPML4E; i++) {
1889 		p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1890 		p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1891 	}
1892 #endif
1893 
1894 	/* Connect the Direct Map slots up to the PML4. */
1895 	for (i = 0; i < ndmpdpphys; i++) {
1896 		p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1897 		p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1898 	}
1899 
1900 	/* Connect the KVA slots up to the PML4 */
1901 	for (i = 0; i < NKPML4E; i++) {
1902 		p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1903 		p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1904 	}
1905 
1906 	kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1907 	TSEXIT();
1908 }
1909 
1910 /*
1911  *	Bootstrap the system enough to run with virtual memory.
1912  *
1913  *	On amd64 this is called after mapping has already been enabled
1914  *	and just syncs the pmap module with what has already been done.
1915  *	[We can't call it easily with mapping off since the kernel is not
1916  *	mapped with PA == VA, hence we would have to relocate every address
1917  *	from the linked base (virtual) address "KERNBASE" to the actual
1918  *	(physical) address starting relative to 0]
1919  */
1920 void
pmap_bootstrap(vm_paddr_t * firstaddr)1921 pmap_bootstrap(vm_paddr_t *firstaddr)
1922 {
1923 	vm_offset_t va;
1924 	pt_entry_t *pte, *pcpu_pte;
1925 	struct region_descriptor r_gdt;
1926 	uint64_t cr4, pcpu0_phys;
1927 	u_long res;
1928 	int i;
1929 
1930 	TSENTER();
1931 	KERNend = *firstaddr;
1932 	res = atop(KERNend - (vm_paddr_t)kernphys);
1933 
1934 	if (!pti)
1935 		pg_g = X86_PG_G;
1936 
1937 	/*
1938 	 * Create an initial set of page tables to run the kernel in.
1939 	 */
1940 	create_pagetables(firstaddr);
1941 
1942 	pcpu0_phys = allocpages(firstaddr, 1);
1943 
1944 	/*
1945 	 * Add a physical memory segment (vm_phys_seg) corresponding to the
1946 	 * preallocated kernel page table pages so that vm_page structures
1947 	 * representing these pages will be created.  The vm_page structures
1948 	 * are required for promotion of the corresponding kernel virtual
1949 	 * addresses to superpage mappings.
1950 	 */
1951 	vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1952 
1953 	/*
1954 	 * Account for the virtual addresses mapped by create_pagetables().
1955 	 */
1956 	virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1957 	    (vm_paddr_t)kernphys);
1958 	virtual_end = VM_MAX_KERNEL_ADDRESS;
1959 
1960 	/*
1961 	 * Enable PG_G global pages, then switch to the kernel page
1962 	 * table from the bootstrap page table.  After the switch, it
1963 	 * is possible to enable SMEP and SMAP since PG_U bits are
1964 	 * correct now.
1965 	 */
1966 	cr4 = rcr4();
1967 	cr4 |= CR4_PGE;
1968 	load_cr4(cr4);
1969 	load_cr3(KPML4phys);
1970 	if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1971 		cr4 |= CR4_SMEP;
1972 	if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1973 		cr4 |= CR4_SMAP;
1974 	load_cr4(cr4);
1975 
1976 	/*
1977 	 * Initialize the kernel pmap (which is statically allocated).
1978 	 * Count bootstrap data as being resident in case any of this data is
1979 	 * later unmapped (using pmap_remove()) and freed.
1980 	 */
1981 	PMAP_LOCK_INIT(kernel_pmap);
1982 	kernel_pmap->pm_pmltop = kernel_pml4;
1983 	kernel_pmap->pm_cr3 = KPML4phys;
1984 	kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1985 	TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1986 	kernel_pmap->pm_stats.resident_count = res;
1987 	vm_radix_init(&kernel_pmap->pm_root);
1988 	kernel_pmap->pm_flags = pmap_flags;
1989 	if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
1990 		rangeset_init(&kernel_pmap->pm_pkru, pkru_dup_range,
1991 		    pkru_free_range, kernel_pmap, M_NOWAIT);
1992 	}
1993 
1994 	/*
1995 	 * The kernel pmap is always active on all CPUs.  Once CPUs are
1996 	 * enumerated, the mask will be set equal to all_cpus.
1997 	 */
1998 	CPU_FILL(&kernel_pmap->pm_active);
1999 
2000  	/*
2001 	 * Initialize the TLB invalidations generation number lock.
2002 	 */
2003 	mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
2004 
2005 	/*
2006 	 * Reserve some special page table entries/VA space for temporary
2007 	 * mapping of pages.
2008 	 */
2009 #define	SYSMAP(c, p, v, n)	\
2010 	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
2011 
2012 	va = virtual_avail;
2013 	pte = vtopte(va);
2014 
2015 	/*
2016 	 * Crashdump maps.  The first page is reused as CMAP1 for the
2017 	 * memory test.
2018 	 */
2019 	SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
2020 	CADDR1 = crashdumpmap;
2021 
2022 	SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
2023 	virtual_avail = va;
2024 
2025 	/*
2026 	 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2027 	 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2028 	 * number of CPUs and NUMA affinity.
2029 	 */
2030 	pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2031 	    X86_PG_M | X86_PG_A;
2032 	for (i = 1; i < MAXCPU; i++)
2033 		pcpu_pte[i] = 0;
2034 
2035 	/*
2036 	 * Re-initialize PCPU area for BSP after switching.
2037 	 * Make hardware use gdt and common_tss from the new PCPU.
2038 	 */
2039 	STAILQ_INIT(&cpuhead);
2040 	wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2041 	pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2042 	amd64_bsp_pcpu_init1(&__pcpu[0]);
2043 	amd64_bsp_ist_init(&__pcpu[0]);
2044 	__pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2045 	    IOPERM_BITMAP_SIZE;
2046 	memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2047 	    sizeof(struct user_segment_descriptor));
2048 	gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2049 	ssdtosyssd(&gdt_segs[GPROC0_SEL],
2050 	    (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2051 	r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2052 	r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2053 	lgdt(&r_gdt);
2054 	wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2055 	ltr(GSEL(GPROC0_SEL, SEL_KPL));
2056 	__pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2057 	__pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2058 
2059 	/*
2060 	 * Initialize the PAT MSR.
2061 	 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2062 	 * side-effect, invalidates stale PG_G TLB entries that might
2063 	 * have been created in our pre-boot environment.
2064 	 */
2065 	pmap_init_pat();
2066 
2067 	/* Initialize TLB Context Id. */
2068 	if (pmap_pcid_enabled) {
2069 		kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2070 		    offsetof(struct pcpu, pc_kpmap_store);
2071 
2072 		PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2073 		PCPU_SET(kpmap_store.pm_gen, 1);
2074 
2075 		/*
2076 		 * PMAP_PCID_KERN + 1 is used for initialization of
2077 		 * proc0 pmap.  The pmap' pcid state might be used by
2078 		 * EFIRT entry before first context switch, so it
2079 		 * needs to be valid.
2080 		 */
2081 		PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2082 		PCPU_SET(pcid_gen, 1);
2083 
2084 		/*
2085 		 * pcpu area for APs is zeroed during AP startup.
2086 		 * pc_pcid_next and pc_pcid_gen are initialized by AP
2087 		 * during pcpu setup.
2088 		 */
2089 		load_cr4(rcr4() | CR4_PCIDE);
2090 	}
2091 	TSEXIT();
2092 }
2093 
2094 /*
2095  * Setup the PAT MSR.
2096  */
2097 void
pmap_init_pat(void)2098 pmap_init_pat(void)
2099 {
2100 	uint64_t pat_msr;
2101 	u_long cr0, cr4;
2102 	int i;
2103 
2104 	/* Bail if this CPU doesn't implement PAT. */
2105 	if ((cpu_feature & CPUID_PAT) == 0)
2106 		panic("no PAT??");
2107 
2108 	/* Set default PAT index table. */
2109 	for (i = 0; i < PAT_INDEX_SIZE; i++)
2110 		pat_index[i] = -1;
2111 	pat_index[PAT_WRITE_BACK] = 0;
2112 	pat_index[PAT_WRITE_THROUGH] = 1;
2113 	pat_index[PAT_UNCACHEABLE] = 3;
2114 	pat_index[PAT_WRITE_COMBINING] = 6;
2115 	pat_index[PAT_WRITE_PROTECTED] = 5;
2116 	pat_index[PAT_UNCACHED] = 2;
2117 
2118 	/*
2119 	 * Initialize default PAT entries.
2120 	 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2121 	 * Program 5 and 6 as WP and WC.
2122 	 *
2123 	 * Leave 4 and 7 as WB and UC.  Note that a recursive page table
2124 	 * mapping for a 2M page uses a PAT value with the bit 3 set due
2125 	 * to its overload with PG_PS.
2126 	 */
2127 	pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2128 	    PAT_VALUE(1, PAT_WRITE_THROUGH) |
2129 	    PAT_VALUE(2, PAT_UNCACHED) |
2130 	    PAT_VALUE(3, PAT_UNCACHEABLE) |
2131 	    PAT_VALUE(4, PAT_WRITE_BACK) |
2132 	    PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2133 	    PAT_VALUE(6, PAT_WRITE_COMBINING) |
2134 	    PAT_VALUE(7, PAT_UNCACHEABLE);
2135 
2136 	/* Disable PGE. */
2137 	cr4 = rcr4();
2138 	load_cr4(cr4 & ~CR4_PGE);
2139 
2140 	/* Disable caches (CD = 1, NW = 0). */
2141 	cr0 = rcr0();
2142 	load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2143 
2144 	/* Flushes caches and TLBs. */
2145 	wbinvd();
2146 	invltlb();
2147 
2148 	/* Update PAT and index table. */
2149 	wrmsr(MSR_PAT, pat_msr);
2150 
2151 	/* Flush caches and TLBs again. */
2152 	wbinvd();
2153 	invltlb();
2154 
2155 	/* Restore caches and PGE. */
2156 	load_cr0(cr0);
2157 	load_cr4(cr4);
2158 }
2159 
2160 vm_page_t
pmap_page_alloc_below_4g(bool zeroed)2161 pmap_page_alloc_below_4g(bool zeroed)
2162 {
2163 	return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2164 	    1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2165 }
2166 
2167 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2168     la57_trampoline_gdt[], la57_trampoline_end[];
2169 
2170 static void
pmap_bootstrap_la57(void * arg __unused)2171 pmap_bootstrap_la57(void *arg __unused)
2172 {
2173 	char *v_code;
2174 	pml5_entry_t *v_pml5;
2175 	pml4_entry_t *v_pml4;
2176 	pdp_entry_t *v_pdp;
2177 	pd_entry_t *v_pd;
2178 	pt_entry_t *v_pt;
2179 	vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2180 	void (*la57_tramp)(uint64_t pml5);
2181 	struct region_descriptor r_gdt;
2182 
2183 	if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2184 		return;
2185 	TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2186 	if (!la57)
2187 		return;
2188 
2189 	r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2190 	r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2191 
2192 	m_code = pmap_page_alloc_below_4g(true);
2193 	v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2194 	m_pml5 = pmap_page_alloc_below_4g(true);
2195 	KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2196 	v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2197 	m_pml4 = pmap_page_alloc_below_4g(true);
2198 	v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2199 	m_pdp = pmap_page_alloc_below_4g(true);
2200 	v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2201 	m_pd = pmap_page_alloc_below_4g(true);
2202 	v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2203 	m_pt = pmap_page_alloc_below_4g(true);
2204 	v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2205 
2206 	/*
2207 	 * Map m_code 1:1, it appears below 4G in KVA due to physical
2208 	 * address being below 4G.  Since kernel KVA is in upper half,
2209 	 * the pml4e should be zero and free for temporary use.
2210 	 */
2211 	kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2212 	    VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2213 	    X86_PG_M;
2214 	v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2215 	    VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2216 	    X86_PG_M;
2217 	v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2218 	    VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2219 	    X86_PG_M;
2220 	v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2221 	    VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2222 	    X86_PG_M;
2223 
2224 	/*
2225 	 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2226 	 * entering all existing kernel mappings into level 5 table.
2227 	 */
2228 	v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2229 	    X86_PG_RW | X86_PG_A | X86_PG_M;
2230 
2231 	/*
2232 	 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2233 	 */
2234 	v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2235 	    VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2236 	    X86_PG_M;
2237 	v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2238 	    VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2239 	    X86_PG_M;
2240 
2241 	/*
2242 	 * Copy and call the 48->57 trampoline, hope we return there, alive.
2243 	 */
2244 	bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2245 	*(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2246 	    la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2247 	la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2248 	pmap_invalidate_all(kernel_pmap);
2249 	if (bootverbose) {
2250 		printf("entering LA57 trampoline at %#lx\n",
2251 		    (vm_offset_t)la57_tramp);
2252 	}
2253 	la57_tramp(KPML5phys);
2254 
2255 	/*
2256 	 * gdt was necessary reset, switch back to our gdt.
2257 	 */
2258 	lgdt(&r_gdt);
2259 	wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2260 	load_ds(_udatasel);
2261 	load_es(_udatasel);
2262 	load_fs(_ufssel);
2263 	ssdtosyssd(&gdt_segs[GPROC0_SEL],
2264 	    (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2265 	ltr(GSEL(GPROC0_SEL, SEL_KPL));
2266 	lidt(&r_idt);
2267 
2268 	if (bootverbose)
2269 		printf("LA57 trampoline returned, CR4 %#lx\n", rcr4());
2270 
2271 	/*
2272 	 * Now unmap the trampoline, and free the pages.
2273 	 * Clear pml5 entry used for 1:1 trampoline mapping.
2274 	 */
2275 	pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2276 	invlpg((vm_offset_t)v_code);
2277 	vm_page_free(m_code);
2278 	vm_page_free(m_pdp);
2279 	vm_page_free(m_pd);
2280 	vm_page_free(m_pt);
2281 
2282 	/*
2283 	 * Recursively map PML5 to itself in order to get PTmap and
2284 	 * PDmap.
2285 	 */
2286 	v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2287 
2288 	vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2289 	    NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2290 	PTmap = (vm_offset_t)P5Tmap;
2291 	vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2292 	    NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2293 	PDmap = (vm_offset_t)P5Dmap;
2294 
2295 	kernel_pmap->pm_cr3 = KPML5phys;
2296 	kernel_pmap->pm_pmltop = v_pml5;
2297 	pmap_pt_page_count_adj(kernel_pmap, 1);
2298 }
2299 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2300 
2301 /*
2302  *	Initialize a vm_page's machine-dependent fields.
2303  */
2304 void
pmap_page_init(vm_page_t m)2305 pmap_page_init(vm_page_t m)
2306 {
2307 
2308 	TAILQ_INIT(&m->md.pv_list);
2309 	m->md.pat_mode = PAT_WRITE_BACK;
2310 }
2311 
2312 static int pmap_allow_2m_x_ept;
2313 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2314     &pmap_allow_2m_x_ept, 0,
2315     "Allow executable superpage mappings in EPT");
2316 
2317 void
pmap_allow_2m_x_ept_recalculate(void)2318 pmap_allow_2m_x_ept_recalculate(void)
2319 {
2320 	/*
2321 	 * SKL002, SKL012S.  Since the EPT format is only used by
2322 	 * Intel CPUs, the vendor check is merely a formality.
2323 	 */
2324 	if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2325 	    (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2326 	    (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2327 	    (CPUID_TO_MODEL(cpu_id) == 0x26 ||	/* Atoms */
2328 	    CPUID_TO_MODEL(cpu_id) == 0x27 ||
2329 	    CPUID_TO_MODEL(cpu_id) == 0x35 ||
2330 	    CPUID_TO_MODEL(cpu_id) == 0x36 ||
2331 	    CPUID_TO_MODEL(cpu_id) == 0x37 ||
2332 	    CPUID_TO_MODEL(cpu_id) == 0x86 ||
2333 	    CPUID_TO_MODEL(cpu_id) == 0x1c ||
2334 	    CPUID_TO_MODEL(cpu_id) == 0x4a ||
2335 	    CPUID_TO_MODEL(cpu_id) == 0x4c ||
2336 	    CPUID_TO_MODEL(cpu_id) == 0x4d ||
2337 	    CPUID_TO_MODEL(cpu_id) == 0x5a ||
2338 	    CPUID_TO_MODEL(cpu_id) == 0x5c ||
2339 	    CPUID_TO_MODEL(cpu_id) == 0x5d ||
2340 	    CPUID_TO_MODEL(cpu_id) == 0x5f ||
2341 	    CPUID_TO_MODEL(cpu_id) == 0x6e ||
2342 	    CPUID_TO_MODEL(cpu_id) == 0x7a ||
2343 	    CPUID_TO_MODEL(cpu_id) == 0x57 ||	/* Knights */
2344 	    CPUID_TO_MODEL(cpu_id) == 0x85))))
2345 		pmap_allow_2m_x_ept = 1;
2346 #ifndef BURN_BRIDGES
2347 	TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2348 #endif
2349 	TUNABLE_INT_FETCH("vm.pmap.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2350 }
2351 
2352 static bool
pmap_allow_2m_x_page(pmap_t pmap,bool executable)2353 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2354 {
2355 
2356 	return (pmap->pm_type != PT_EPT || !executable ||
2357 	    !pmap_allow_2m_x_ept);
2358 }
2359 
2360 #ifdef NUMA
2361 static void
pmap_init_pv_table(void)2362 pmap_init_pv_table(void)
2363 {
2364 	struct pmap_large_md_page *pvd;
2365 	vm_size_t s;
2366 	long start, end, highest, pv_npg;
2367 	int domain, i, j, pages;
2368 
2369 	/*
2370 	 * For correctness we depend on the size being evenly divisible into a
2371 	 * page. As a tradeoff between performance and total memory use, the
2372 	 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2373 	 * avoids false-sharing, but not being 128 bytes potentially allows for
2374 	 * avoidable traffic due to adjacent cacheline prefetcher.
2375 	 *
2376 	 * Assert the size so that accidental changes fail to compile.
2377 	 */
2378 	CTASSERT((sizeof(*pvd) == 64));
2379 
2380 	/*
2381 	 * Calculate the size of the array.
2382 	 */
2383 	pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2384 	pv_npg = howmany(pmap_last_pa, NBPDR);
2385 	s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2386 	s = round_page(s);
2387 	pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2388 	if (pv_table == NULL)
2389 		panic("%s: kva_alloc failed\n", __func__);
2390 
2391 	/*
2392 	 * Iterate physical segments to allocate space for respective pages.
2393 	 */
2394 	highest = -1;
2395 	s = 0;
2396 	for (i = 0; i < vm_phys_nsegs; i++) {
2397 		end = vm_phys_segs[i].end / NBPDR;
2398 		domain = vm_phys_segs[i].domain;
2399 
2400 		if (highest >= end)
2401 			continue;
2402 
2403 		start = highest + 1;
2404 		pvd = &pv_table[start];
2405 
2406 		pages = end - start + 1;
2407 		s = round_page(pages * sizeof(*pvd));
2408 		highest = start + (s / sizeof(*pvd)) - 1;
2409 
2410 		for (j = 0; j < s; j += PAGE_SIZE) {
2411 			vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2412 			if (m == NULL)
2413 				panic("failed to allocate PV table page");
2414 			pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2415 		}
2416 
2417 		for (j = 0; j < s / sizeof(*pvd); j++) {
2418 			rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2419 			TAILQ_INIT(&pvd->pv_page.pv_list);
2420 			pvd->pv_page.pv_gen = 0;
2421 			pvd->pv_page.pat_mode = 0;
2422 			pvd->pv_invl_gen = 0;
2423 			pvd++;
2424 		}
2425 	}
2426 	pvd = &pv_dummy_large;
2427 	rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2428 	TAILQ_INIT(&pvd->pv_page.pv_list);
2429 	pvd->pv_page.pv_gen = 0;
2430 	pvd->pv_page.pat_mode = 0;
2431 	pvd->pv_invl_gen = 0;
2432 }
2433 #else
2434 static void
pmap_init_pv_table(void)2435 pmap_init_pv_table(void)
2436 {
2437 	vm_size_t s;
2438 	long i, pv_npg;
2439 
2440 	/*
2441 	 * Initialize the pool of pv list locks.
2442 	 */
2443 	for (i = 0; i < NPV_LIST_LOCKS; i++)
2444 		rw_init(&pv_list_locks[i], "pmap pv list");
2445 
2446 	/*
2447 	 * Calculate the size of the pv head table for superpages.
2448 	 */
2449 	pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2450 
2451 	/*
2452 	 * Allocate memory for the pv head table for superpages.
2453 	 */
2454 	s = (vm_size_t)pv_npg * sizeof(struct md_page);
2455 	s = round_page(s);
2456 	pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2457 	for (i = 0; i < pv_npg; i++)
2458 		TAILQ_INIT(&pv_table[i].pv_list);
2459 	TAILQ_INIT(&pv_dummy.pv_list);
2460 }
2461 #endif
2462 
2463 /*
2464  *	Initialize the pmap module.
2465  *
2466  *	Called by vm_mem_init(), to initialize any structures that the pmap
2467  *	system needs to map virtual memory.
2468  */
2469 void
pmap_init(void)2470 pmap_init(void)
2471 {
2472 	struct pmap_preinit_mapping *ppim;
2473 	vm_page_t m, mpte;
2474 	int error, i, ret, skz63;
2475 
2476 	/* L1TF, reserve page @0 unconditionally */
2477 	vm_page_blacklist_add(0, bootverbose);
2478 
2479 	/* Detect bare-metal Skylake Server and Skylake-X. */
2480 	if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2481 	    CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2482 		/*
2483 		 * Skylake-X errata SKZ63. Processor May Hang When
2484 		 * Executing Code In an HLE Transaction Region between
2485 		 * 40000000H and 403FFFFFH.
2486 		 *
2487 		 * Mark the pages in the range as preallocated.  It
2488 		 * seems to be impossible to distinguish between
2489 		 * Skylake Server and Skylake X.
2490 		 */
2491 		skz63 = 1;
2492 		TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2493 		if (skz63 != 0) {
2494 			if (bootverbose)
2495 				printf("SKZ63: skipping 4M RAM starting "
2496 				    "at physical 1G\n");
2497 			for (i = 0; i < atop(0x400000); i++) {
2498 				ret = vm_page_blacklist_add(0x40000000 +
2499 				    ptoa(i), false);
2500 				if (!ret && bootverbose)
2501 					printf("page at %#lx already used\n",
2502 					    0x40000000 + ptoa(i));
2503 			}
2504 		}
2505 	}
2506 
2507 	/* IFU */
2508 	pmap_allow_2m_x_ept_recalculate();
2509 
2510 	/*
2511 	 * Initialize the vm page array entries for the kernel pmap's
2512 	 * page table pages.
2513 	 */
2514 	PMAP_LOCK(kernel_pmap);
2515 	for (i = 0; i < nkpt; i++) {
2516 		mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2517 		KASSERT(mpte >= vm_page_array &&
2518 		    mpte < &vm_page_array[vm_page_array_size],
2519 		    ("pmap_init: page table page is out of range"));
2520 		mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2521 		mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2522 		mpte->ref_count = 1;
2523 
2524 		/*
2525 		 * Collect the page table pages that were replaced by a 2MB
2526 		 * page in create_pagetables().  They are zero filled.
2527 		 */
2528 		if ((i == 0 ||
2529 		    kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2530 		    pmap_insert_pt_page(kernel_pmap, mpte, false, false))
2531 			panic("pmap_init: pmap_insert_pt_page failed");
2532 	}
2533 	PMAP_UNLOCK(kernel_pmap);
2534 	vm_wire_add(nkpt);
2535 
2536 	/*
2537 	 * If the kernel is running on a virtual machine, then it must assume
2538 	 * that MCA is enabled by the hypervisor.  Moreover, the kernel must
2539 	 * be prepared for the hypervisor changing the vendor and family that
2540 	 * are reported by CPUID.  Consequently, the workaround for AMD Family
2541 	 * 10h Erratum 383 is enabled if the processor's feature set does not
2542 	 * include at least one feature that is only supported by older Intel
2543 	 * or newer AMD processors.
2544 	 */
2545 	if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2546 	    (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2547 	    CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2548 	    AMDID2_FMA4)) == 0)
2549 		workaround_erratum383 = 1;
2550 
2551 	/*
2552 	 * Are large page mappings enabled?
2553 	 */
2554 	TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2555 	if (pg_ps_enabled) {
2556 		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2557 		    ("pmap_init: can't assign to pagesizes[1]"));
2558 		pagesizes[1] = NBPDR;
2559 		if ((amd_feature & AMDID_PAGE1GB) != 0) {
2560 			KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2561 			    ("pmap_init: can't assign to pagesizes[2]"));
2562 			pagesizes[2] = NBPDP;
2563 		}
2564 	}
2565 
2566 	/*
2567 	 * Initialize pv chunk lists.
2568 	 */
2569 	for (i = 0; i < PMAP_MEMDOM; i++) {
2570 		mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2571 		TAILQ_INIT(&pv_chunks[i].pvc_list);
2572 	}
2573 	pmap_init_pv_table();
2574 
2575 	pmap_initialized = 1;
2576 	for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2577 		ppim = pmap_preinit_mapping + i;
2578 		if (ppim->va == 0)
2579 			continue;
2580 		/* Make the direct map consistent */
2581 		if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2582 			(void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2583 			    ppim->sz, ppim->mode);
2584 		}
2585 		if (!bootverbose)
2586 			continue;
2587 		printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2588 		    ppim->pa, ppim->va, ppim->sz, ppim->mode);
2589 	}
2590 
2591 	mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2592 	error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2593 	    (vmem_addr_t *)&qframe);
2594 	if (error != 0)
2595 		panic("qframe allocation failed");
2596 
2597 	lm_ents = 8;
2598 	TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2599 	if (lm_ents > LMEPML4I - LMSPML4I + 1)
2600 		lm_ents = LMEPML4I - LMSPML4I + 1;
2601 #ifdef KMSAN
2602 	if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2603 		printf(
2604 	    "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2605 		    lm_ents, KMSANORIGPML4I - LMSPML4I);
2606 		lm_ents = KMSANORIGPML4I - LMSPML4I;
2607 	}
2608 #endif
2609 	if (bootverbose)
2610 		printf("pmap: large map %u PML4 slots (%lu GB)\n",
2611 		    lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2612 	if (lm_ents != 0) {
2613 		large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2614 		    (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2615 		if (large_vmem == NULL) {
2616 			printf("pmap: cannot create large map\n");
2617 			lm_ents = 0;
2618 		}
2619 		for (i = 0; i < lm_ents; i++) {
2620 			m = pmap_large_map_getptp_unlocked();
2621 			/* XXXKIB la57 */
2622 			kernel_pml4[LMSPML4I + i] = X86_PG_V |
2623 			    X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2624 			    VM_PAGE_TO_PHYS(m);
2625 		}
2626 	}
2627 }
2628 
2629 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2630     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2631     "Maximum number of PML4 entries for use by large map (tunable).  "
2632     "Each entry corresponds to 512GB of address space.");
2633 
2634 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2635     "2MB page mapping counters");
2636 
2637 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2638 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2639     CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2640 
2641 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2642 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2643     &pmap_pde_mappings, "2MB page mappings");
2644 
2645 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2646 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2647     &pmap_pde_p_failures, "2MB page promotion failures");
2648 
2649 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2650 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2651     &pmap_pde_promotions, "2MB page promotions");
2652 
2653 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2654     "1GB page mapping counters");
2655 
2656 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2657 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2658     &pmap_pdpe_demotions, "1GB page demotions");
2659 
2660 /***************************************************
2661  * Low level helper routines.....
2662  ***************************************************/
2663 
2664 static pt_entry_t
pmap_swap_pat(pmap_t pmap,pt_entry_t entry)2665 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2666 {
2667 	int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2668 
2669 	switch (pmap->pm_type) {
2670 	case PT_X86:
2671 	case PT_RVI:
2672 		/* Verify that both PAT bits are not set at the same time */
2673 		KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2674 		    ("Invalid PAT bits in entry %#lx", entry));
2675 
2676 		/* Swap the PAT bits if one of them is set */
2677 		if ((entry & x86_pat_bits) != 0)
2678 			entry ^= x86_pat_bits;
2679 		break;
2680 	case PT_EPT:
2681 		/*
2682 		 * Nothing to do - the memory attributes are represented
2683 		 * the same way for regular pages and superpages.
2684 		 */
2685 		break;
2686 	default:
2687 		panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2688 	}
2689 
2690 	return (entry);
2691 }
2692 
2693 bool
pmap_is_valid_memattr(pmap_t pmap __unused,vm_memattr_t mode)2694 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2695 {
2696 
2697 	return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2698 	    pat_index[(int)mode] >= 0);
2699 }
2700 
2701 /*
2702  * Determine the appropriate bits to set in a PTE or PDE for a specified
2703  * caching mode.
2704  */
2705 int
pmap_cache_bits(pmap_t pmap,int mode,bool is_pde)2706 pmap_cache_bits(pmap_t pmap, int mode, bool is_pde)
2707 {
2708 	int cache_bits, pat_flag, pat_idx;
2709 
2710 	if (!pmap_is_valid_memattr(pmap, mode))
2711 		panic("Unknown caching mode %d\n", mode);
2712 
2713 	switch (pmap->pm_type) {
2714 	case PT_X86:
2715 	case PT_RVI:
2716 		/* The PAT bit is different for PTE's and PDE's. */
2717 		pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2718 
2719 		/* Map the caching mode to a PAT index. */
2720 		pat_idx = pat_index[mode];
2721 
2722 		/* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2723 		cache_bits = 0;
2724 		if (pat_idx & 0x4)
2725 			cache_bits |= pat_flag;
2726 		if (pat_idx & 0x2)
2727 			cache_bits |= PG_NC_PCD;
2728 		if (pat_idx & 0x1)
2729 			cache_bits |= PG_NC_PWT;
2730 		break;
2731 
2732 	case PT_EPT:
2733 		cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2734 		break;
2735 
2736 	default:
2737 		panic("unsupported pmap type %d", pmap->pm_type);
2738 	}
2739 
2740 	return (cache_bits);
2741 }
2742 
2743 static int
pmap_cache_mask(pmap_t pmap,bool is_pde)2744 pmap_cache_mask(pmap_t pmap, bool is_pde)
2745 {
2746 	int mask;
2747 
2748 	switch (pmap->pm_type) {
2749 	case PT_X86:
2750 	case PT_RVI:
2751 		mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2752 		break;
2753 	case PT_EPT:
2754 		mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2755 		break;
2756 	default:
2757 		panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2758 	}
2759 
2760 	return (mask);
2761 }
2762 
2763 static int
pmap_pat_index(pmap_t pmap,pt_entry_t pte,bool is_pde)2764 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2765 {
2766 	int pat_flag, pat_idx;
2767 
2768 	pat_idx = 0;
2769 	switch (pmap->pm_type) {
2770 	case PT_X86:
2771 	case PT_RVI:
2772 		/* The PAT bit is different for PTE's and PDE's. */
2773 		pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2774 
2775 		if ((pte & pat_flag) != 0)
2776 			pat_idx |= 0x4;
2777 		if ((pte & PG_NC_PCD) != 0)
2778 			pat_idx |= 0x2;
2779 		if ((pte & PG_NC_PWT) != 0)
2780 			pat_idx |= 0x1;
2781 		break;
2782 	case PT_EPT:
2783 		if ((pte & EPT_PG_IGNORE_PAT) != 0)
2784 			panic("EPT PTE %#lx has no PAT memory type", pte);
2785 		pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2786 		break;
2787 	}
2788 
2789 	/* See pmap_init_pat(). */
2790 	if (pat_idx == 4)
2791 		pat_idx = 0;
2792 	if (pat_idx == 7)
2793 		pat_idx = 3;
2794 
2795 	return (pat_idx);
2796 }
2797 
2798 bool
pmap_ps_enabled(pmap_t pmap)2799 pmap_ps_enabled(pmap_t pmap)
2800 {
2801 
2802 	return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2803 }
2804 
2805 static void
pmap_update_pde_store(pmap_t pmap,pd_entry_t * pde,pd_entry_t newpde)2806 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2807 {
2808 
2809 	switch (pmap->pm_type) {
2810 	case PT_X86:
2811 		break;
2812 	case PT_RVI:
2813 	case PT_EPT:
2814 		/*
2815 		 * XXX
2816 		 * This is a little bogus since the generation number is
2817 		 * supposed to be bumped up when a region of the address
2818 		 * space is invalidated in the page tables.
2819 		 *
2820 		 * In this case the old PDE entry is valid but yet we want
2821 		 * to make sure that any mappings using the old entry are
2822 		 * invalidated in the TLB.
2823 		 *
2824 		 * The reason this works as expected is because we rendezvous
2825 		 * "all" host cpus and force any vcpu context to exit as a
2826 		 * side-effect.
2827 		 */
2828 		atomic_add_long(&pmap->pm_eptgen, 1);
2829 		break;
2830 	default:
2831 		panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2832 	}
2833 	pde_store(pde, newpde);
2834 }
2835 
2836 /*
2837  * After changing the page size for the specified virtual address in the page
2838  * table, flush the corresponding entries from the processor's TLB.  Only the
2839  * calling processor's TLB is affected.
2840  *
2841  * The calling thread must be pinned to a processor.
2842  */
2843 static void
pmap_update_pde_invalidate(pmap_t pmap,vm_offset_t va,pd_entry_t newpde)2844 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2845 {
2846 	pt_entry_t PG_G;
2847 
2848 	if (pmap_type_guest(pmap))
2849 		return;
2850 
2851 	KASSERT(pmap->pm_type == PT_X86,
2852 	    ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2853 
2854 	PG_G = pmap_global_bit(pmap);
2855 
2856 	if ((newpde & PG_PS) == 0)
2857 		/* Demotion: flush a specific 2MB page mapping. */
2858 		pmap_invlpg(pmap, va);
2859 	else if ((newpde & PG_G) == 0)
2860 		/*
2861 		 * Promotion: flush every 4KB page mapping from the TLB
2862 		 * because there are too many to flush individually.
2863 		 */
2864 		invltlb();
2865 	else {
2866 		/*
2867 		 * Promotion: flush every 4KB page mapping from the TLB,
2868 		 * including any global (PG_G) mappings.
2869 		 */
2870 		invltlb_glob();
2871 	}
2872 }
2873 
2874 /*
2875  * The amd64 pmap uses different approaches to TLB invalidation
2876  * depending on the kernel configuration, available hardware features,
2877  * and known hardware errata.  The kernel configuration option that
2878  * has the greatest operational impact on TLB invalidation is PTI,
2879  * which is enabled automatically on affected Intel CPUs.  The most
2880  * impactful hardware features are first PCID, and then INVPCID
2881  * instruction presence.  PCID usage is quite different for PTI
2882  * vs. non-PTI.
2883  *
2884  * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2885  *   the Meltdown bug in some Intel CPUs.  Under PTI, each user address
2886  *   space is served by two page tables, user and kernel.  The user
2887  *   page table only maps user space and a kernel trampoline.  The
2888  *   kernel trampoline includes the entirety of the kernel text but
2889  *   only the kernel data that is needed to switch from user to kernel
2890  *   mode.  The kernel page table maps the user and kernel address
2891  *   spaces in their entirety.  It is identical to the per-process
2892  *   page table used in non-PTI mode.
2893  *
2894  *   User page tables are only used when the CPU is in user mode.
2895  *   Consequently, some TLB invalidations can be postponed until the
2896  *   switch from kernel to user mode.  In contrast, the user
2897  *   space part of the kernel page table is used for copyout(9), so
2898  *   TLB invalidations on this page table cannot be similarly postponed.
2899  *
2900  *   The existence of a user mode page table for the given pmap is
2901  *   indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2902  *   which case pm_ucr3 contains the %cr3 register value for the user
2903  *   mode page table's root.
2904  *
2905  * * The pm_active bitmask indicates which CPUs currently have the
2906  *   pmap active.  A CPU's bit is set on context switch to the pmap, and
2907  *   cleared on switching off this CPU.  For the kernel page table,
2908  *   the pm_active field is immutable and contains all CPUs.  The
2909  *   kernel page table is always logically active on every processor,
2910  *   but not necessarily in use by the hardware, e.g., in PTI mode.
2911  *
2912  *   When requesting invalidation of virtual addresses with
2913  *   pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2914  *   all CPUs recorded as active in pm_active.  Updates to and reads
2915  *   from pm_active are not synchronized, and so they may race with
2916  *   each other.  Shootdown handlers are prepared to handle the race.
2917  *
2918  * * PCID is an optional feature of the long mode x86 MMU where TLB
2919  *   entries are tagged with the 'Process ID' of the address space
2920  *   they belong to.  This feature provides a limited namespace for
2921  *   process identifiers, 12 bits, supporting 4095 simultaneous IDs
2922  *   total.
2923  *
2924  *   Allocation of a PCID to a pmap is done by an algorithm described
2925  *   in section 15.12, "Other TLB Consistency Algorithms", of
2926  *   Vahalia's book "Unix Internals".  A PCID cannot be allocated for
2927  *   the whole lifetime of a pmap in pmap_pinit() due to the limited
2928  *   namespace.  Instead, a per-CPU, per-pmap PCID is assigned when
2929  *   the CPU is about to start caching TLB entries from a pmap,
2930  *   i.e., on the context switch that activates the pmap on the CPU.
2931  *
2932  *   The PCID allocator maintains a per-CPU, per-pmap generation
2933  *   count, pm_gen, which is incremented each time a new PCID is
2934  *   allocated.  On TLB invalidation, the generation counters for the
2935  *   pmap are zeroed, which signals the context switch code that the
2936  *   previously allocated PCID is no longer valid.  Effectively,
2937  *   zeroing any of these counters triggers a TLB shootdown for the
2938  *   given CPU/address space, due to the allocation of a new PCID.
2939  *
2940  *   Zeroing can be performed remotely.  Consequently, if a pmap is
2941  *   inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2942  *   be initiated by an ordinary memory access to reset the target
2943  *   CPU's generation count within the pmap.  The CPU initiating the
2944  *   TLB shootdown does not need to send an IPI to the target CPU.
2945  *
2946  * * PTI + PCID.  The available PCIDs are divided into two sets: PCIDs
2947  *   for complete (kernel) page tables, and PCIDs for user mode page
2948  *   tables.  A user PCID value is obtained from the kernel PCID value
2949  *   by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2950  *
2951  *   User space page tables are activated on return to user mode, by
2952  *   loading pm_ucr3 into %cr3.  If the PCPU(ucr3_load_mask) requests
2953  *   clearing bit 63 of the loaded ucr3, this effectively causes
2954  *   complete invalidation of the user mode TLB entries for the
2955  *   current pmap.  In which case, local invalidations of individual
2956  *   pages in the user page table are skipped.
2957  *
2958  * * Local invalidation, all modes.  If the requested invalidation is
2959  *   for a specific address or the total invalidation of a currently
2960  *   active pmap, then the TLB is flushed using INVLPG for a kernel
2961  *   page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2962  *   user space page table(s).
2963  *
2964  *   If the INVPCID instruction is available, it is used to flush user
2965  *   entries from the kernel page table.
2966  *
2967  *   When PCID is enabled, the INVLPG instruction invalidates all TLB
2968  *   entries for the given page that either match the current PCID or
2969  *   are global. Since TLB entries for the same page under different
2970  *   PCIDs are unaffected, kernel pages which reside in all address
2971  *   spaces could be problematic.  We avoid the problem by creating
2972  *   all kernel PTEs with the global flag (PG_G) set, when PTI is
2973  *   disabled.
2974  *
2975  * * mode: PTI disabled, PCID present.  The kernel reserves PCID 0 for its
2976  *   address space, all other 4095 PCIDs are used for user mode spaces
2977  *   as described above.  A context switch allocates a new PCID if
2978  *   the recorded PCID is zero or the recorded generation does not match
2979  *   the CPU's generation, effectively flushing the TLB for this address space.
2980  *   Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2981  *	local user page: INVLPG
2982  *	local kernel page: INVLPG
2983  *	local user total: INVPCID(CTX)
2984  *	local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2985  *	remote user page, inactive pmap: zero pm_gen
2986  *	remote user page, active pmap: zero pm_gen + IPI:INVLPG
2987  *	(Both actions are required to handle the aforementioned pm_active races.)
2988  *	remote kernel page: IPI:INVLPG
2989  *	remote user total, inactive pmap: zero pm_gen
2990  *	remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2991  *          reload %cr3)
2992  *	(See note above about pm_active races.)
2993  *	remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2994  *
2995  * PTI enabled, PCID present.
2996  *	local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2997  *          for upt
2998  *	local kernel page: INVLPG
2999  *	local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
3000  *          on loading UCR3 into %cr3 for upt
3001  *	local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
3002  *	remote user page, inactive pmap: zero pm_gen
3003  *	remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
3004  *          INVPCID(ADDR) for upt)
3005  *	remote kernel page: IPI:INVLPG
3006  *	remote user total, inactive pmap: zero pm_gen
3007  *	remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
3008  *          clear PCID_SAVE on loading UCR3 into $cr3 for upt)
3009  *	remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
3010  *
3011  *  No PCID.
3012  *	local user page: INVLPG
3013  *	local kernel page: INVLPG
3014  *	local user total: reload %cr3
3015  *	local kernel total: invltlb_glob()
3016  *	remote user page, inactive pmap: -
3017  *	remote user page, active pmap: IPI:INVLPG
3018  *	remote kernel page: IPI:INVLPG
3019  *	remote user total, inactive pmap: -
3020  *	remote user total, active pmap: IPI:(reload %cr3)
3021  *	remote kernel total: IPI:invltlb_glob()
3022  *  Since on return to user mode, the reload of %cr3 with ucr3 causes
3023  *  TLB invalidation, no specific action is required for user page table.
3024  *
3025  * EPT.  EPT pmaps do not map KVA, all mappings are userspace.
3026  * XXX TODO
3027  */
3028 
3029 #ifdef SMP
3030 /*
3031  * Interrupt the cpus that are executing in the guest context.
3032  * This will force the vcpu to exit and the cached EPT mappings
3033  * will be invalidated by the host before the next vmresume.
3034  */
3035 static __inline void
pmap_invalidate_ept(pmap_t pmap)3036 pmap_invalidate_ept(pmap_t pmap)
3037 {
3038 	smr_seq_t goal;
3039 	int ipinum;
3040 
3041 	sched_pin();
3042 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3043 	    ("pmap_invalidate_ept: absurd pm_active"));
3044 
3045 	/*
3046 	 * The TLB mappings associated with a vcpu context are not
3047 	 * flushed each time a different vcpu is chosen to execute.
3048 	 *
3049 	 * This is in contrast with a process's vtop mappings that
3050 	 * are flushed from the TLB on each context switch.
3051 	 *
3052 	 * Therefore we need to do more than just a TLB shootdown on
3053 	 * the active cpus in 'pmap->pm_active'. To do this we keep
3054 	 * track of the number of invalidations performed on this pmap.
3055 	 *
3056 	 * Each vcpu keeps a cache of this counter and compares it
3057 	 * just before a vmresume. If the counter is out-of-date an
3058 	 * invept will be done to flush stale mappings from the TLB.
3059 	 *
3060 	 * To ensure that all vCPU threads have observed the new counter
3061 	 * value before returning, we use SMR.  Ordering is important here:
3062 	 * the VMM enters an SMR read section before loading the counter
3063 	 * and after updating the pm_active bit set.  Thus, pm_active is
3064 	 * a superset of active readers, and any reader that has observed
3065 	 * the goal has observed the new counter value.
3066 	 */
3067 	atomic_add_long(&pmap->pm_eptgen, 1);
3068 
3069 	goal = smr_advance(pmap->pm_eptsmr);
3070 
3071 	/*
3072 	 * Force the vcpu to exit and trap back into the hypervisor.
3073 	 */
3074 	ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3075 	ipi_selected(pmap->pm_active, ipinum);
3076 	sched_unpin();
3077 
3078 	/*
3079 	 * Ensure that all active vCPUs will observe the new generation counter
3080 	 * value before executing any more guest instructions.
3081 	 */
3082 	smr_wait(pmap->pm_eptsmr, goal);
3083 }
3084 
3085 static inline void
pmap_invalidate_preipi_pcid(pmap_t pmap)3086 pmap_invalidate_preipi_pcid(pmap_t pmap)
3087 {
3088 	struct pmap_pcid *pcidp;
3089 	u_int cpuid, i;
3090 
3091 	sched_pin();
3092 
3093 	cpuid = PCPU_GET(cpuid);
3094 	if (pmap != PCPU_GET(curpmap))
3095 		cpuid = 0xffffffff;	/* An impossible value */
3096 
3097 	CPU_FOREACH(i) {
3098 		if (cpuid != i) {
3099 			pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3100 			pcidp->pm_gen = 0;
3101 		}
3102 	}
3103 
3104 	/*
3105 	 * The fence is between stores to pm_gen and the read of the
3106 	 * pm_active mask.  We need to ensure that it is impossible
3107 	 * for us to miss the bit update in pm_active and
3108 	 * simultaneously observe a non-zero pm_gen in
3109 	 * pmap_activate_sw(), otherwise TLB update is missed.
3110 	 * Without the fence, IA32 allows such an outcome.  Note that
3111 	 * pm_active is updated by a locked operation, which provides
3112 	 * the reciprocal fence.
3113 	 */
3114 	atomic_thread_fence_seq_cst();
3115 }
3116 
3117 static void
pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)3118 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3119 {
3120 	sched_pin();
3121 }
3122 
3123 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3124 {
3125 	return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3126 	    pmap_invalidate_preipi_nopcid);
3127 }
3128 
3129 static inline void
pmap_invalidate_page_pcid_cb(pmap_t pmap,vm_offset_t va,const bool invpcid_works1)3130 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3131     const bool invpcid_works1)
3132 {
3133 	struct invpcid_descr d;
3134 	uint64_t kcr3, ucr3;
3135 	uint32_t pcid;
3136 
3137 	/*
3138 	 * Because pm_pcid is recalculated on a context switch, we
3139 	 * must ensure there is no preemption, not just pinning.
3140 	 * Otherwise, we might use a stale value below.
3141 	 */
3142 	CRITICAL_ASSERT(curthread);
3143 
3144 	/*
3145 	 * No need to do anything with user page tables invalidation
3146 	 * if there is no user page table, or invalidation is deferred
3147 	 * until the return to userspace.  ucr3_load_mask is stable
3148 	 * because we have preemption disabled.
3149 	 */
3150 	if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3151 	    PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3152 		return;
3153 
3154 	pcid = pmap_get_pcid(pmap);
3155 	if (invpcid_works1) {
3156 		d.pcid = pcid | PMAP_PCID_USER_PT;
3157 		d.pad = 0;
3158 		d.addr = va;
3159 		invpcid(&d, INVPCID_ADDR);
3160 	} else {
3161 		kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3162 		ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3163 		pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3164 	}
3165 }
3166 
3167 static void
pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap,vm_offset_t va)3168 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3169 {
3170 	pmap_invalidate_page_pcid_cb(pmap, va, true);
3171 }
3172 
3173 static void
pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap,vm_offset_t va)3174 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3175 {
3176 	pmap_invalidate_page_pcid_cb(pmap, va, false);
3177 }
3178 
3179 static void
pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused,vm_offset_t va __unused)3180 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3181 {
3182 }
3183 
3184 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3185 {
3186 	if (pmap_pcid_enabled)
3187 		return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3188 		    pmap_invalidate_page_pcid_noinvpcid_cb);
3189 	return (pmap_invalidate_page_nopcid_cb);
3190 }
3191 
3192 static void
pmap_invalidate_page_curcpu_cb(pmap_t pmap,vm_offset_t va,vm_offset_t addr2 __unused)3193 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3194     vm_offset_t addr2 __unused)
3195 {
3196 	if (pmap == kernel_pmap) {
3197 		pmap_invlpg(kernel_pmap, va);
3198 	} else if (pmap == PCPU_GET(curpmap)) {
3199 		invlpg(va);
3200 		pmap_invalidate_page_cb(pmap, va);
3201 	}
3202 }
3203 
3204 void
pmap_invalidate_page(pmap_t pmap,vm_offset_t va)3205 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3206 {
3207 	if (pmap_type_guest(pmap)) {
3208 		pmap_invalidate_ept(pmap);
3209 		return;
3210 	}
3211 
3212 	KASSERT(pmap->pm_type == PT_X86,
3213 	    ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3214 
3215 	pmap_invalidate_preipi(pmap);
3216 	smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3217 }
3218 
3219 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3220 #define	PMAP_INVLPG_THRESHOLD	(4 * 1024 * PAGE_SIZE)
3221 
3222 static void
pmap_invalidate_range_pcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,const bool invpcid_works1)3223 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3224     const bool invpcid_works1)
3225 {
3226 	struct invpcid_descr d;
3227 	uint64_t kcr3, ucr3;
3228 	uint32_t pcid;
3229 
3230 	CRITICAL_ASSERT(curthread);
3231 
3232 	if (pmap != PCPU_GET(curpmap) ||
3233 	    pmap->pm_ucr3 == PMAP_NO_CR3 ||
3234 	    PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3235 		return;
3236 
3237 	pcid = pmap_get_pcid(pmap);
3238 	if (invpcid_works1) {
3239 		d.pcid = pcid | PMAP_PCID_USER_PT;
3240 		d.pad = 0;
3241 		for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3242 			invpcid(&d, INVPCID_ADDR);
3243 	} else {
3244 		kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3245 		ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3246 		pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3247 	}
3248 }
3249 
3250 static void
pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3251 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3252     vm_offset_t eva)
3253 {
3254 	pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3255 }
3256 
3257 static void
pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3258 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3259     vm_offset_t eva)
3260 {
3261 	pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3262 }
3263 
3264 static void
pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused,vm_offset_t sva __unused,vm_offset_t eva __unused)3265 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3266     vm_offset_t eva __unused)
3267 {
3268 }
3269 
3270 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3271     vm_offset_t))
3272 {
3273 	if (pmap_pcid_enabled)
3274 		return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3275 		    pmap_invalidate_range_pcid_noinvpcid_cb);
3276 	return (pmap_invalidate_range_nopcid_cb);
3277 }
3278 
3279 static void
pmap_invalidate_range_curcpu_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3280 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3281 {
3282 	vm_offset_t addr;
3283 
3284 	if (pmap == kernel_pmap) {
3285 		if (PCPU_GET(pcid_invlpg_workaround)) {
3286 			struct invpcid_descr d = { 0 };
3287 
3288 			invpcid(&d, INVPCID_CTXGLOB);
3289 		} else {
3290 			for (addr = sva; addr < eva; addr += PAGE_SIZE)
3291 				invlpg(addr);
3292 		}
3293 	} else if (pmap == PCPU_GET(curpmap)) {
3294 		for (addr = sva; addr < eva; addr += PAGE_SIZE)
3295 			invlpg(addr);
3296 		pmap_invalidate_range_cb(pmap, sva, eva);
3297 	}
3298 }
3299 
3300 void
pmap_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3301 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3302 {
3303 	if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3304 		pmap_invalidate_all(pmap);
3305 		return;
3306 	}
3307 
3308 	if (pmap_type_guest(pmap)) {
3309 		pmap_invalidate_ept(pmap);
3310 		return;
3311 	}
3312 
3313 	KASSERT(pmap->pm_type == PT_X86,
3314 	    ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3315 
3316 	pmap_invalidate_preipi(pmap);
3317 	smp_masked_invlpg_range(sva, eva, pmap,
3318 	    pmap_invalidate_range_curcpu_cb);
3319 }
3320 
3321 static inline void
pmap_invalidate_all_pcid_cb(pmap_t pmap,bool invpcid_works1)3322 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3323 {
3324 	struct invpcid_descr d;
3325 	uint64_t kcr3;
3326 	uint32_t pcid;
3327 
3328 	if (pmap == kernel_pmap) {
3329 		if (invpcid_works1) {
3330 			bzero(&d, sizeof(d));
3331 			invpcid(&d, INVPCID_CTXGLOB);
3332 		} else {
3333 			invltlb_glob();
3334 		}
3335 	} else if (pmap == PCPU_GET(curpmap)) {
3336 		CRITICAL_ASSERT(curthread);
3337 
3338 		pcid = pmap_get_pcid(pmap);
3339 		if (invpcid_works1) {
3340 			d.pcid = pcid;
3341 			d.pad = 0;
3342 			d.addr = 0;
3343 			invpcid(&d, INVPCID_CTX);
3344 		} else {
3345 			kcr3 = pmap->pm_cr3 | pcid;
3346 			load_cr3(kcr3);
3347 		}
3348 		if (pmap->pm_ucr3 != PMAP_NO_CR3)
3349 			PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3350 	}
3351 }
3352 
3353 static void
pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)3354 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3355 {
3356 	pmap_invalidate_all_pcid_cb(pmap, true);
3357 }
3358 
3359 static void
pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)3360 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3361 {
3362 	pmap_invalidate_all_pcid_cb(pmap, false);
3363 }
3364 
3365 static void
pmap_invalidate_all_nopcid_cb(pmap_t pmap)3366 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3367 {
3368 	if (pmap == kernel_pmap)
3369 		invltlb_glob();
3370 	else if (pmap == PCPU_GET(curpmap))
3371 		invltlb();
3372 }
3373 
3374 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3375 {
3376 	if (pmap_pcid_enabled)
3377 		return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3378 		    pmap_invalidate_all_pcid_noinvpcid_cb);
3379 	return (pmap_invalidate_all_nopcid_cb);
3380 }
3381 
3382 static void
pmap_invalidate_all_curcpu_cb(pmap_t pmap,vm_offset_t addr1 __unused,vm_offset_t addr2 __unused)3383 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3384     vm_offset_t addr2 __unused)
3385 {
3386 	pmap_invalidate_all_cb(pmap);
3387 }
3388 
3389 void
pmap_invalidate_all(pmap_t pmap)3390 pmap_invalidate_all(pmap_t pmap)
3391 {
3392 	if (pmap_type_guest(pmap)) {
3393 		pmap_invalidate_ept(pmap);
3394 		return;
3395 	}
3396 
3397 	KASSERT(pmap->pm_type == PT_X86,
3398 	    ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3399 
3400 	pmap_invalidate_preipi(pmap);
3401 	smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3402 }
3403 
3404 static void
pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused,vm_offset_t va __unused,vm_offset_t addr2 __unused)3405 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3406     vm_offset_t addr2 __unused)
3407 {
3408 	wbinvd();
3409 }
3410 
3411 void
pmap_invalidate_cache(void)3412 pmap_invalidate_cache(void)
3413 {
3414 	sched_pin();
3415 	smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3416 }
3417 
3418 struct pde_action {
3419 	cpuset_t invalidate;	/* processors that invalidate their TLB */
3420 	pmap_t pmap;
3421 	vm_offset_t va;
3422 	pd_entry_t *pde;
3423 	pd_entry_t newpde;
3424 	u_int store;		/* processor that updates the PDE */
3425 };
3426 
3427 static void
pmap_update_pde_action(void * arg)3428 pmap_update_pde_action(void *arg)
3429 {
3430 	struct pde_action *act = arg;
3431 
3432 	if (act->store == PCPU_GET(cpuid))
3433 		pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3434 }
3435 
3436 static void
pmap_update_pde_teardown(void * arg)3437 pmap_update_pde_teardown(void *arg)
3438 {
3439 	struct pde_action *act = arg;
3440 
3441 	if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3442 		pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3443 }
3444 
3445 /*
3446  * Change the page size for the specified virtual address in a way that
3447  * prevents any possibility of the TLB ever having two entries that map the
3448  * same virtual address using different page sizes.  This is the recommended
3449  * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
3450  * machine check exception for a TLB state that is improperly diagnosed as a
3451  * hardware error.
3452  */
3453 static void
pmap_update_pde(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t newpde)3454 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3455 {
3456 	struct pde_action act;
3457 	cpuset_t active, other_cpus;
3458 	u_int cpuid;
3459 
3460 	sched_pin();
3461 	cpuid = PCPU_GET(cpuid);
3462 	other_cpus = all_cpus;
3463 	CPU_CLR(cpuid, &other_cpus);
3464 	if (pmap == kernel_pmap || pmap_type_guest(pmap))
3465 		active = all_cpus;
3466 	else {
3467 		active = pmap->pm_active;
3468 	}
3469 	if (CPU_OVERLAP(&active, &other_cpus)) {
3470 		act.store = cpuid;
3471 		act.invalidate = active;
3472 		act.va = va;
3473 		act.pmap = pmap;
3474 		act.pde = pde;
3475 		act.newpde = newpde;
3476 		CPU_SET(cpuid, &active);
3477 		smp_rendezvous_cpus(active,
3478 		    smp_no_rendezvous_barrier, pmap_update_pde_action,
3479 		    pmap_update_pde_teardown, &act);
3480 	} else {
3481 		pmap_update_pde_store(pmap, pde, newpde);
3482 		if (CPU_ISSET(cpuid, &active))
3483 			pmap_update_pde_invalidate(pmap, va, newpde);
3484 	}
3485 	sched_unpin();
3486 }
3487 #else /* !SMP */
3488 /*
3489  * Normal, non-SMP, invalidation functions.
3490  */
3491 void
pmap_invalidate_page(pmap_t pmap,vm_offset_t va)3492 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3493 {
3494 	struct invpcid_descr d;
3495 	struct pmap_pcid *pcidp;
3496 	uint64_t kcr3, ucr3;
3497 	uint32_t pcid;
3498 
3499 	if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3500 		pmap->pm_eptgen++;
3501 		return;
3502 	}
3503 	KASSERT(pmap->pm_type == PT_X86,
3504 	    ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3505 
3506 	if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3507 		invlpg(va);
3508 		if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3509 		    pmap->pm_ucr3 != PMAP_NO_CR3) {
3510 			critical_enter();
3511 			pcid = pmap_get_pcid(pmap);
3512 			if (invpcid_works) {
3513 				d.pcid = pcid | PMAP_PCID_USER_PT;
3514 				d.pad = 0;
3515 				d.addr = va;
3516 				invpcid(&d, INVPCID_ADDR);
3517 			} else {
3518 				kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3519 				ucr3 = pmap->pm_ucr3 | pcid |
3520 				    PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3521 				pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3522 			}
3523 			critical_exit();
3524 		}
3525 	} else if (pmap_pcid_enabled) {
3526 		pcidp = zpcpu_get(pmap->pm_pcidp);
3527 		pcidp->pm_gen = 0;
3528 	}
3529 }
3530 
3531 void
pmap_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3532 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3533 {
3534 	struct invpcid_descr d;
3535 	struct pmap_pcid *pcidp;
3536 	vm_offset_t addr;
3537 	uint64_t kcr3, ucr3;
3538 	uint32_t pcid;
3539 
3540 	if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3541 		pmap->pm_eptgen++;
3542 		return;
3543 	}
3544 	KASSERT(pmap->pm_type == PT_X86,
3545 	    ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3546 
3547 	if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3548 		for (addr = sva; addr < eva; addr += PAGE_SIZE)
3549 			invlpg(addr);
3550 		if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3551 		    pmap->pm_ucr3 != PMAP_NO_CR3) {
3552 			critical_enter();
3553 			pcid = pmap_get_pcid(pmap);
3554 			if (invpcid_works) {
3555 				d.pcid = pcid | PMAP_PCID_USER_PT;
3556 				d.pad = 0;
3557 				d.addr = sva;
3558 				for (; d.addr < eva; d.addr += PAGE_SIZE)
3559 					invpcid(&d, INVPCID_ADDR);
3560 			} else {
3561 				kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3562 				ucr3 = pmap->pm_ucr3 | pcid |
3563 				    PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3564 				pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3565 			}
3566 			critical_exit();
3567 		}
3568 	} else if (pmap_pcid_enabled) {
3569 		pcidp = zpcpu_get(pmap->pm_pcidp);
3570 		pcidp->pm_gen = 0;
3571 	}
3572 }
3573 
3574 void
pmap_invalidate_all(pmap_t pmap)3575 pmap_invalidate_all(pmap_t pmap)
3576 {
3577 	struct invpcid_descr d;
3578 	struct pmap_pcid *pcidp;
3579 	uint64_t kcr3, ucr3;
3580 	uint32_t pcid;
3581 
3582 	if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3583 		pmap->pm_eptgen++;
3584 		return;
3585 	}
3586 	KASSERT(pmap->pm_type == PT_X86,
3587 	    ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3588 
3589 	if (pmap == kernel_pmap) {
3590 		if (pmap_pcid_enabled && invpcid_works) {
3591 			bzero(&d, sizeof(d));
3592 			invpcid(&d, INVPCID_CTXGLOB);
3593 		} else {
3594 			invltlb_glob();
3595 		}
3596 	} else if (pmap == PCPU_GET(curpmap)) {
3597 		if (pmap_pcid_enabled) {
3598 			critical_enter();
3599 			pcid = pmap_get_pcid(pmap);
3600 			if (invpcid_works) {
3601 				d.pcid = pcid;
3602 				d.pad = 0;
3603 				d.addr = 0;
3604 				invpcid(&d, INVPCID_CTX);
3605 				if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3606 					d.pcid |= PMAP_PCID_USER_PT;
3607 					invpcid(&d, INVPCID_CTX);
3608 				}
3609 			} else {
3610 				kcr3 = pmap->pm_cr3 | pcid;
3611 				if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3612 					ucr3 = pmap->pm_ucr3 | pcid |
3613 					    PMAP_PCID_USER_PT;
3614 					pmap_pti_pcid_invalidate(ucr3, kcr3);
3615 				} else
3616 					load_cr3(kcr3);
3617 			}
3618 			critical_exit();
3619 		} else {
3620 			invltlb();
3621 		}
3622 	} else if (pmap_pcid_enabled) {
3623 		pcidp = zpcpu_get(pmap->pm_pcidp);
3624 		pcidp->pm_gen = 0;
3625 	}
3626 }
3627 
3628 void
pmap_invalidate_cache(void)3629 pmap_invalidate_cache(void)
3630 {
3631 
3632 	wbinvd();
3633 }
3634 
3635 static void
pmap_update_pde(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t newpde)3636 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3637 {
3638 	struct pmap_pcid *pcidp;
3639 
3640 	pmap_update_pde_store(pmap, pde, newpde);
3641 	if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3642 		pmap_update_pde_invalidate(pmap, va, newpde);
3643 	else {
3644 		pcidp = zpcpu_get(pmap->pm_pcidp);
3645 		pcidp->pm_gen = 0;
3646 	}
3647 }
3648 #endif /* !SMP */
3649 
3650 static void
pmap_invalidate_pde_page(pmap_t pmap,vm_offset_t va,pd_entry_t pde)3651 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3652 {
3653 
3654 	/*
3655 	 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3656 	 * by a promotion that did not invalidate the 512 4KB page mappings
3657 	 * that might exist in the TLB.  Consequently, at this point, the TLB
3658 	 * may hold both 4KB and 2MB page mappings for the address range [va,
3659 	 * va + NBPDR).  Therefore, the entire range must be invalidated here.
3660 	 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3661 	 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3662 	 * single INVLPG suffices to invalidate the 2MB page mapping from the
3663 	 * TLB.
3664 	 */
3665 	if ((pde & PG_PROMOTED) != 0)
3666 		pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3667 	else
3668 		pmap_invalidate_page(pmap, va);
3669 }
3670 
3671 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3672     (vm_offset_t sva, vm_offset_t eva))
3673 {
3674 
3675 	if ((cpu_feature & CPUID_SS) != 0)
3676 		return (pmap_invalidate_cache_range_selfsnoop);
3677 	if ((cpu_feature & CPUID_CLFSH) != 0)
3678 		return (pmap_force_invalidate_cache_range);
3679 	return (pmap_invalidate_cache_range_all);
3680 }
3681 
3682 #define PMAP_CLFLUSH_THRESHOLD   (2 * 1024 * 1024)
3683 
3684 static void
pmap_invalidate_cache_range_check_align(vm_offset_t sva,vm_offset_t eva)3685 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3686 {
3687 
3688 	KASSERT((sva & PAGE_MASK) == 0,
3689 	    ("pmap_invalidate_cache_range: sva not page-aligned"));
3690 	KASSERT((eva & PAGE_MASK) == 0,
3691 	    ("pmap_invalidate_cache_range: eva not page-aligned"));
3692 }
3693 
3694 static void
pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,vm_offset_t eva)3695 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3696 {
3697 
3698 	pmap_invalidate_cache_range_check_align(sva, eva);
3699 }
3700 
3701 void
pmap_force_invalidate_cache_range(vm_offset_t sva,vm_offset_t eva)3702 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3703 {
3704 
3705 	sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3706 
3707 	/*
3708 	 * XXX: Some CPUs fault, hang, or trash the local APIC
3709 	 * registers if we use CLFLUSH on the local APIC range.  The
3710 	 * local APIC is always uncached, so we don't need to flush
3711 	 * for that range anyway.
3712 	 */
3713 	if (pmap_kextract(sva) == lapic_paddr)
3714 		return;
3715 
3716 	if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3717 		/*
3718 		 * Do per-cache line flush.  Use a locked
3719 		 * instruction to insure that previous stores are
3720 		 * included in the write-back.  The processor
3721 		 * propagates flush to other processors in the cache
3722 		 * coherence domain.
3723 		 */
3724 		atomic_thread_fence_seq_cst();
3725 		for (; sva < eva; sva += cpu_clflush_line_size)
3726 			clflushopt(sva);
3727 		atomic_thread_fence_seq_cst();
3728 	} else {
3729 		/*
3730 		 * Writes are ordered by CLFLUSH on Intel CPUs.
3731 		 */
3732 		if (cpu_vendor_id != CPU_VENDOR_INTEL)
3733 			mfence();
3734 		for (; sva < eva; sva += cpu_clflush_line_size)
3735 			clflush(sva);
3736 		if (cpu_vendor_id != CPU_VENDOR_INTEL)
3737 			mfence();
3738 	}
3739 }
3740 
3741 static void
pmap_invalidate_cache_range_all(vm_offset_t sva,vm_offset_t eva)3742 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3743 {
3744 
3745 	pmap_invalidate_cache_range_check_align(sva, eva);
3746 	pmap_invalidate_cache();
3747 }
3748 
3749 /*
3750  * Remove the specified set of pages from the data and instruction caches.
3751  *
3752  * In contrast to pmap_invalidate_cache_range(), this function does not
3753  * rely on the CPU's self-snoop feature, because it is intended for use
3754  * when moving pages into a different cache domain.
3755  */
3756 void
pmap_invalidate_cache_pages(vm_page_t * pages,int count)3757 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3758 {
3759 	vm_offset_t daddr, eva;
3760 	int i;
3761 	bool useclflushopt;
3762 
3763 	useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3764 	if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3765 	    ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3766 		pmap_invalidate_cache();
3767 	else {
3768 		if (useclflushopt)
3769 			atomic_thread_fence_seq_cst();
3770 		else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3771 			mfence();
3772 		for (i = 0; i < count; i++) {
3773 			daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3774 			eva = daddr + PAGE_SIZE;
3775 			for (; daddr < eva; daddr += cpu_clflush_line_size) {
3776 				if (useclflushopt)
3777 					clflushopt(daddr);
3778 				else
3779 					clflush(daddr);
3780 			}
3781 		}
3782 		if (useclflushopt)
3783 			atomic_thread_fence_seq_cst();
3784 		else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3785 			mfence();
3786 	}
3787 }
3788 
3789 void
pmap_flush_cache_range(vm_offset_t sva,vm_offset_t eva)3790 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3791 {
3792 
3793 	pmap_invalidate_cache_range_check_align(sva, eva);
3794 
3795 	if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3796 		pmap_force_invalidate_cache_range(sva, eva);
3797 		return;
3798 	}
3799 
3800 	/* See comment in pmap_force_invalidate_cache_range(). */
3801 	if (pmap_kextract(sva) == lapic_paddr)
3802 		return;
3803 
3804 	atomic_thread_fence_seq_cst();
3805 	for (; sva < eva; sva += cpu_clflush_line_size)
3806 		clwb(sva);
3807 	atomic_thread_fence_seq_cst();
3808 }
3809 
3810 void
pmap_flush_cache_phys_range(vm_paddr_t spa,vm_paddr_t epa,vm_memattr_t mattr)3811 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3812 {
3813 	pt_entry_t *pte;
3814 	vm_offset_t vaddr;
3815 	int error __diagused;
3816 	int pte_bits;
3817 
3818 	KASSERT((spa & PAGE_MASK) == 0,
3819 	    ("pmap_flush_cache_phys_range: spa not page-aligned"));
3820 	KASSERT((epa & PAGE_MASK) == 0,
3821 	    ("pmap_flush_cache_phys_range: epa not page-aligned"));
3822 
3823 	if (spa < dmaplimit) {
3824 		pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3825 		    dmaplimit, epa)));
3826 		if (dmaplimit >= epa)
3827 			return;
3828 		spa = dmaplimit;
3829 	}
3830 
3831 	pte_bits = pmap_cache_bits(kernel_pmap, mattr, false) | X86_PG_RW |
3832 	    X86_PG_V;
3833 	error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3834 	    &vaddr);
3835 	KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3836 	pte = vtopte(vaddr);
3837 	for (; spa < epa; spa += PAGE_SIZE) {
3838 		sched_pin();
3839 		pte_store(pte, spa | pte_bits);
3840 		pmap_invlpg(kernel_pmap, vaddr);
3841 		/* XXXKIB atomic inside flush_cache_range are excessive */
3842 		pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3843 		sched_unpin();
3844 	}
3845 	vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3846 }
3847 
3848 /*
3849  *	Routine:	pmap_extract
3850  *	Function:
3851  *		Extract the physical page address associated
3852  *		with the given map/virtual_address pair.
3853  */
3854 vm_paddr_t
pmap_extract(pmap_t pmap,vm_offset_t va)3855 pmap_extract(pmap_t pmap, vm_offset_t va)
3856 {
3857 	pdp_entry_t *pdpe;
3858 	pd_entry_t *pde;
3859 	pt_entry_t *pte, PG_V;
3860 	vm_paddr_t pa;
3861 
3862 	pa = 0;
3863 	PG_V = pmap_valid_bit(pmap);
3864 	PMAP_LOCK(pmap);
3865 	pdpe = pmap_pdpe(pmap, va);
3866 	if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3867 		if ((*pdpe & PG_PS) != 0)
3868 			pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3869 		else {
3870 			pde = pmap_pdpe_to_pde(pdpe, va);
3871 			if ((*pde & PG_V) != 0) {
3872 				if ((*pde & PG_PS) != 0) {
3873 					pa = (*pde & PG_PS_FRAME) |
3874 					    (va & PDRMASK);
3875 				} else {
3876 					pte = pmap_pde_to_pte(pde, va);
3877 					pa = (*pte & PG_FRAME) |
3878 					    (va & PAGE_MASK);
3879 				}
3880 			}
3881 		}
3882 	}
3883 	PMAP_UNLOCK(pmap);
3884 	return (pa);
3885 }
3886 
3887 /*
3888  *	Routine:	pmap_extract_and_hold
3889  *	Function:
3890  *		Atomically extract and hold the physical page
3891  *		with the given pmap and virtual address pair
3892  *		if that mapping permits the given protection.
3893  */
3894 vm_page_t
pmap_extract_and_hold(pmap_t pmap,vm_offset_t va,vm_prot_t prot)3895 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3896 {
3897 	pdp_entry_t pdpe, *pdpep;
3898 	pd_entry_t pde, *pdep;
3899 	pt_entry_t pte, PG_RW, PG_V;
3900 	vm_page_t m;
3901 
3902 	m = NULL;
3903 	PG_RW = pmap_rw_bit(pmap);
3904 	PG_V = pmap_valid_bit(pmap);
3905 	PMAP_LOCK(pmap);
3906 
3907 	pdpep = pmap_pdpe(pmap, va);
3908 	if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3909 		goto out;
3910 	if ((pdpe & PG_PS) != 0) {
3911 		if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3912 			goto out;
3913 		m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3914 		goto check_page;
3915 	}
3916 
3917 	pdep = pmap_pdpe_to_pde(pdpep, va);
3918 	if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3919 		goto out;
3920 	if ((pde & PG_PS) != 0) {
3921 		if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3922 			goto out;
3923 		m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3924 		goto check_page;
3925 	}
3926 
3927 	pte = *pmap_pde_to_pte(pdep, va);
3928 	if ((pte & PG_V) == 0 ||
3929 	    ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3930 		goto out;
3931 	m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3932 
3933 check_page:
3934 	if (m != NULL && !vm_page_wire_mapped(m))
3935 		m = NULL;
3936 out:
3937 	PMAP_UNLOCK(pmap);
3938 	return (m);
3939 }
3940 
3941 /*
3942  *	Routine:	pmap_kextract
3943  *	Function:
3944  *		Extract the physical page address associated with the given kernel
3945  *		virtual address.
3946  */
3947 vm_paddr_t
pmap_kextract(vm_offset_t va)3948 pmap_kextract(vm_offset_t va)
3949 {
3950 	pd_entry_t pde;
3951 	vm_paddr_t pa;
3952 
3953 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3954 		pa = DMAP_TO_PHYS(va);
3955 	} else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3956 		pa = pmap_large_map_kextract(va);
3957 	} else {
3958 		pde = *vtopde(va);
3959 		if (pde & PG_PS) {
3960 			pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3961 		} else {
3962 			/*
3963 			 * Beware of a concurrent promotion that changes the
3964 			 * PDE at this point!  For example, vtopte() must not
3965 			 * be used to access the PTE because it would use the
3966 			 * new PDE.  It is, however, safe to use the old PDE
3967 			 * because the page table page is preserved by the
3968 			 * promotion.
3969 			 */
3970 			pa = *pmap_pde_to_pte(&pde, va);
3971 			pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3972 		}
3973 	}
3974 	return (pa);
3975 }
3976 
3977 /***************************************************
3978  * Low level mapping routines.....
3979  ***************************************************/
3980 
3981 /*
3982  * Add a wired page to the kva.
3983  * Note: not SMP coherent.
3984  */
3985 void
pmap_kenter(vm_offset_t va,vm_paddr_t pa)3986 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3987 {
3988 	pt_entry_t *pte;
3989 
3990 	pte = vtopte(va);
3991 	pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3992 	    X86_PG_RW | X86_PG_V);
3993 }
3994 
3995 static __inline void
pmap_kenter_attr(vm_offset_t va,vm_paddr_t pa,int mode)3996 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3997 {
3998 	pt_entry_t *pte;
3999 	int cache_bits;
4000 
4001 	pte = vtopte(va);
4002 	cache_bits = pmap_cache_bits(kernel_pmap, mode, false);
4003 	pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
4004 	    X86_PG_RW | X86_PG_V | cache_bits);
4005 }
4006 
4007 /*
4008  * Remove a page from the kernel pagetables.
4009  * Note: not SMP coherent.
4010  */
4011 void
pmap_kremove(vm_offset_t va)4012 pmap_kremove(vm_offset_t va)
4013 {
4014 	pt_entry_t *pte;
4015 
4016 	pte = vtopte(va);
4017 	pte_clear(pte);
4018 }
4019 
4020 /*
4021  *	Used to map a range of physical addresses into kernel
4022  *	virtual address space.
4023  *
4024  *	The value passed in '*virt' is a suggested virtual address for
4025  *	the mapping. Architectures which can support a direct-mapped
4026  *	physical to virtual region can return the appropriate address
4027  *	within that region, leaving '*virt' unchanged. Other
4028  *	architectures should map the pages starting at '*virt' and
4029  *	update '*virt' with the first usable address after the mapped
4030  *	region.
4031  */
4032 vm_offset_t
pmap_map(vm_offset_t * virt,vm_paddr_t start,vm_paddr_t end,int prot)4033 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
4034 {
4035 	return PHYS_TO_DMAP(start);
4036 }
4037 
4038 /*
4039  * Add a list of wired pages to the kva
4040  * this routine is only used for temporary
4041  * kernel mappings that do not need to have
4042  * page modification or references recorded.
4043  * Note that old mappings are simply written
4044  * over.  The page *must* be wired.
4045  * Note: SMP coherent.  Uses a ranged shootdown IPI.
4046  */
4047 void
pmap_qenter(vm_offset_t sva,vm_page_t * ma,int count)4048 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4049 {
4050 	pt_entry_t *endpte, oldpte, pa, *pte;
4051 	vm_page_t m;
4052 	int cache_bits;
4053 
4054 	oldpte = 0;
4055 	pte = vtopte(sva);
4056 	endpte = pte + count;
4057 	while (pte < endpte) {
4058 		m = *ma++;
4059 		cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, false);
4060 		pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4061 		if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4062 			oldpte |= *pte;
4063 			pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4064 			    X86_PG_M | X86_PG_RW | X86_PG_V);
4065 		}
4066 		pte++;
4067 	}
4068 	if (__predict_false((oldpte & X86_PG_V) != 0))
4069 		pmap_invalidate_range(kernel_pmap, sva, sva + count *
4070 		    PAGE_SIZE);
4071 }
4072 
4073 /*
4074  * This routine tears out page mappings from the
4075  * kernel -- it is meant only for temporary mappings.
4076  * Note: SMP coherent.  Uses a ranged shootdown IPI.
4077  */
4078 void
pmap_qremove(vm_offset_t sva,int count)4079 pmap_qremove(vm_offset_t sva, int count)
4080 {
4081 	vm_offset_t va;
4082 
4083 	va = sva;
4084 	while (count-- > 0) {
4085 		/*
4086 		 * pmap_enter() calls within the kernel virtual
4087 		 * address space happen on virtual addresses from
4088 		 * subarenas that import superpage-sized and -aligned
4089 		 * address ranges.  So, the virtual address that we
4090 		 * allocate to use with pmap_qenter() can't be close
4091 		 * enough to one of those pmap_enter() calls for it to
4092 		 * be caught up in a promotion.
4093 		 */
4094 		KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4095 		KASSERT((*vtopde(va) & X86_PG_PS) == 0,
4096 		    ("pmap_qremove on promoted va %#lx", va));
4097 
4098 		pmap_kremove(va);
4099 		va += PAGE_SIZE;
4100 	}
4101 	pmap_invalidate_range(kernel_pmap, sva, va);
4102 }
4103 
4104 /***************************************************
4105  * Page table page management routines.....
4106  ***************************************************/
4107 /*
4108  * Schedule the specified unused page table page to be freed.  Specifically,
4109  * add the page to the specified list of pages that will be released to the
4110  * physical memory manager after the TLB has been updated.
4111  */
4112 static __inline void
pmap_add_delayed_free_list(vm_page_t m,struct spglist * free,bool set_PG_ZERO)4113 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free, bool set_PG_ZERO)
4114 {
4115 
4116 	if (set_PG_ZERO)
4117 		m->flags |= PG_ZERO;
4118 	else
4119 		m->flags &= ~PG_ZERO;
4120 	SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4121 }
4122 
4123 /*
4124  * Inserts the specified page table page into the specified pmap's collection
4125  * of idle page table pages.  Each of a pmap's page table pages is responsible
4126  * for mapping a distinct range of virtual addresses.  The pmap's collection is
4127  * ordered by this virtual address range.
4128  *
4129  * If "promoted" is false, then the page table page "mpte" must be zero filled;
4130  * "mpte"'s valid field will be set to 0.
4131  *
4132  * If "promoted" is true and "allpte_PG_A_set" is false, then "mpte" must
4133  * contain valid mappings with identical attributes except for PG_A; "mpte"'s
4134  * valid field will be set to 1.
4135  *
4136  * If "promoted" and "allpte_PG_A_set" are both true, then "mpte" must contain
4137  * valid mappings with identical attributes including PG_A; "mpte"'s valid
4138  * field will be set to VM_PAGE_BITS_ALL.
4139  */
4140 static __inline int
pmap_insert_pt_page(pmap_t pmap,vm_page_t mpte,bool promoted,bool allpte_PG_A_set)4141 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4142     bool allpte_PG_A_set)
4143 {
4144 
4145 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4146 	KASSERT(promoted || !allpte_PG_A_set,
4147 	    ("a zero-filled PTP can't have PG_A set in every PTE"));
4148 	mpte->valid = promoted ? (allpte_PG_A_set ? VM_PAGE_BITS_ALL : 1) : 0;
4149 	return (vm_radix_insert(&pmap->pm_root, mpte));
4150 }
4151 
4152 /*
4153  * Removes the page table page mapping the specified virtual address from the
4154  * specified pmap's collection of idle page table pages, and returns it.
4155  * Otherwise, returns NULL if there is no page table page corresponding to the
4156  * specified virtual address.
4157  */
4158 static __inline vm_page_t
pmap_remove_pt_page(pmap_t pmap,vm_offset_t va)4159 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4160 {
4161 
4162 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4163 	return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4164 }
4165 
4166 /*
4167  * Decrements a page table page's reference count, which is used to record the
4168  * number of valid page table entries within the page.  If the reference count
4169  * drops to zero, then the page table page is unmapped.  Returns true if the
4170  * page table page was unmapped and false otherwise.
4171  */
4172 static inline bool
pmap_unwire_ptp(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)4173 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4174 {
4175 
4176 	--m->ref_count;
4177 	if (m->ref_count == 0) {
4178 		_pmap_unwire_ptp(pmap, va, m, free);
4179 		return (true);
4180 	} else
4181 		return (false);
4182 }
4183 
4184 static void
_pmap_unwire_ptp(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)4185 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4186 {
4187 	pml5_entry_t *pml5;
4188 	pml4_entry_t *pml4;
4189 	pdp_entry_t *pdp;
4190 	pd_entry_t *pd;
4191 	vm_page_t pdpg, pdppg, pml4pg;
4192 
4193 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4194 
4195 	/*
4196 	 * unmap the page table page
4197 	 */
4198 	if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4199 		/* PML4 page */
4200 		MPASS(pmap_is_la57(pmap));
4201 		pml5 = pmap_pml5e(pmap, va);
4202 		*pml5 = 0;
4203 		if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4204 			pml5 = pmap_pml5e_u(pmap, va);
4205 			*pml5 = 0;
4206 		}
4207 	} else if (m->pindex >= NUPDE + NUPDPE) {
4208 		/* PDP page */
4209 		pml4 = pmap_pml4e(pmap, va);
4210 		*pml4 = 0;
4211 		if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4212 		    va <= VM_MAXUSER_ADDRESS) {
4213 			pml4 = pmap_pml4e_u(pmap, va);
4214 			*pml4 = 0;
4215 		}
4216 	} else if (m->pindex >= NUPDE) {
4217 		/* PD page */
4218 		pdp = pmap_pdpe(pmap, va);
4219 		*pdp = 0;
4220 	} else {
4221 		/* PTE page */
4222 		pd = pmap_pde(pmap, va);
4223 		*pd = 0;
4224 	}
4225 	if (m->pindex < NUPDE) {
4226 		/* We just released a PT, unhold the matching PD */
4227 		pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4228 		pmap_unwire_ptp(pmap, va, pdpg, free);
4229 	} else if (m->pindex < NUPDE + NUPDPE) {
4230 		/* We just released a PD, unhold the matching PDP */
4231 		pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4232 		pmap_unwire_ptp(pmap, va, pdppg, free);
4233 	} else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4234 		/* We just released a PDP, unhold the matching PML4 */
4235 		pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4236 		pmap_unwire_ptp(pmap, va, pml4pg, free);
4237 	}
4238 
4239 	pmap_pt_page_count_adj(pmap, -1);
4240 
4241 	/*
4242 	 * Put page on a list so that it is released after
4243 	 * *ALL* TLB shootdown is done
4244 	 */
4245 	pmap_add_delayed_free_list(m, free, true);
4246 }
4247 
4248 /*
4249  * After removing a page table entry, this routine is used to
4250  * conditionally free the page, and manage the reference count.
4251  */
4252 static int
pmap_unuse_pt(pmap_t pmap,vm_offset_t va,pd_entry_t ptepde,struct spglist * free)4253 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4254     struct spglist *free)
4255 {
4256 	vm_page_t mpte;
4257 
4258 	if (va >= VM_MAXUSER_ADDRESS)
4259 		return (0);
4260 	KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4261 	mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4262 	return (pmap_unwire_ptp(pmap, va, mpte, free));
4263 }
4264 
4265 /*
4266  * Release a page table page reference after a failed attempt to create a
4267  * mapping.
4268  */
4269 static void
pmap_abort_ptp(pmap_t pmap,vm_offset_t va,vm_page_t mpte)4270 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4271 {
4272 	struct spglist free;
4273 
4274 	SLIST_INIT(&free);
4275 	if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4276 		/*
4277 		 * Although "va" was never mapped, paging-structure caches
4278 		 * could nonetheless have entries that refer to the freed
4279 		 * page table pages.  Invalidate those entries.
4280 		 */
4281 		pmap_invalidate_page(pmap, va);
4282 		vm_page_free_pages_toq(&free, true);
4283 	}
4284 }
4285 
4286 static void
pmap_pinit_pcids(pmap_t pmap,uint32_t pcid,int gen)4287 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4288 {
4289 	struct pmap_pcid *pcidp;
4290 	int i;
4291 
4292 	CPU_FOREACH(i) {
4293 		pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4294 		pcidp->pm_pcid = pcid;
4295 		pcidp->pm_gen = gen;
4296 	}
4297 }
4298 
4299 void
pmap_pinit0(pmap_t pmap)4300 pmap_pinit0(pmap_t pmap)
4301 {
4302 	struct proc *p;
4303 	struct thread *td;
4304 
4305 	PMAP_LOCK_INIT(pmap);
4306 	pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4307 	pmap->pm_pmltopu = NULL;
4308 	pmap->pm_cr3 = kernel_pmap->pm_cr3;
4309 	/* hack to keep pmap_pti_pcid_invalidate() alive */
4310 	pmap->pm_ucr3 = PMAP_NO_CR3;
4311 	vm_radix_init(&pmap->pm_root);
4312 	CPU_ZERO(&pmap->pm_active);
4313 	TAILQ_INIT(&pmap->pm_pvchunk);
4314 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4315 	pmap->pm_flags = pmap_flags;
4316 	pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4317 	pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4318 	pmap_activate_boot(pmap);
4319 	td = curthread;
4320 	if (pti) {
4321 		p = td->td_proc;
4322 		PROC_LOCK(p);
4323 		p->p_md.md_flags |= P_MD_KPTI;
4324 		PROC_UNLOCK(p);
4325 	}
4326 	pmap_thread_init_invl_gen(td);
4327 
4328 	if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4329 		pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4330 		    sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4331 		    UMA_ALIGN_PTR, 0);
4332 	}
4333 }
4334 
4335 void
pmap_pinit_pml4(vm_page_t pml4pg)4336 pmap_pinit_pml4(vm_page_t pml4pg)
4337 {
4338 	pml4_entry_t *pm_pml4;
4339 	int i;
4340 
4341 	pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4342 
4343 	/* Wire in kernel global address entries. */
4344 	for (i = 0; i < NKPML4E; i++) {
4345 		pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4346 		    X86_PG_V;
4347 	}
4348 #ifdef KASAN
4349 	for (i = 0; i < NKASANPML4E; i++) {
4350 		pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4351 		    X86_PG_V | pg_nx;
4352 	}
4353 #endif
4354 #ifdef KMSAN
4355 	for (i = 0; i < NKMSANSHADPML4E; i++) {
4356 		pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4357 		    X86_PG_RW | X86_PG_V | pg_nx;
4358 	}
4359 	for (i = 0; i < NKMSANORIGPML4E; i++) {
4360 		pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4361 		    X86_PG_RW | X86_PG_V | pg_nx;
4362 	}
4363 #endif
4364 	for (i = 0; i < ndmpdpphys; i++) {
4365 		pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4366 		    X86_PG_V;
4367 	}
4368 
4369 	/* install self-referential address mapping entry(s) */
4370 	pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4371 	    X86_PG_A | X86_PG_M;
4372 
4373 	/* install large map entries if configured */
4374 	for (i = 0; i < lm_ents; i++)
4375 		pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4376 }
4377 
4378 void
pmap_pinit_pml5(vm_page_t pml5pg)4379 pmap_pinit_pml5(vm_page_t pml5pg)
4380 {
4381 	pml5_entry_t *pm_pml5;
4382 
4383 	pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4384 
4385 	/*
4386 	 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4387 	 * entering all existing kernel mappings into level 5 table.
4388 	 */
4389 	pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4390 	    X86_PG_RW | X86_PG_A | X86_PG_M;
4391 
4392 	/*
4393 	 * Install self-referential address mapping entry.
4394 	 */
4395 	pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4396 	    X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A;
4397 }
4398 
4399 static void
pmap_pinit_pml4_pti(vm_page_t pml4pgu)4400 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4401 {
4402 	pml4_entry_t *pm_pml4u;
4403 	int i;
4404 
4405 	pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4406 	for (i = 0; i < NPML4EPG; i++)
4407 		pm_pml4u[i] = pti_pml4[i];
4408 }
4409 
4410 static void
pmap_pinit_pml5_pti(vm_page_t pml5pgu)4411 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4412 {
4413 	pml5_entry_t *pm_pml5u;
4414 
4415 	pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4416 	pagezero(pm_pml5u);
4417 
4418 	/*
4419 	 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4420 	 * table, entering all kernel mappings needed for usermode
4421 	 * into level 5 table.
4422 	 */
4423 	pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4424 	    pmap_kextract((vm_offset_t)pti_pml4) |
4425 	    X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
4426 }
4427 
4428 /* Allocate a page table page and do related bookkeeping */
4429 static vm_page_t
pmap_alloc_pt_page(pmap_t pmap,vm_pindex_t pindex,int flags)4430 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4431 {
4432 	vm_page_t m;
4433 
4434 	m = vm_page_alloc_noobj(flags);
4435 	if (__predict_false(m == NULL))
4436 		return (NULL);
4437 	m->pindex = pindex;
4438 	pmap_pt_page_count_adj(pmap, 1);
4439 	return (m);
4440 }
4441 
4442 static void
pmap_free_pt_page(pmap_t pmap,vm_page_t m,bool zerofilled)4443 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4444 {
4445 	/*
4446 	 * This function assumes the page will need to be unwired,
4447 	 * even though the counterpart allocation in pmap_alloc_pt_page()
4448 	 * doesn't enforce VM_ALLOC_WIRED.  However, all current uses
4449 	 * of pmap_free_pt_page() require unwiring.  The case in which
4450 	 * a PT page doesn't require unwiring because its ref_count has
4451 	 * naturally reached 0 is handled through _pmap_unwire_ptp().
4452 	 */
4453 	vm_page_unwire_noq(m);
4454 	if (zerofilled)
4455 		vm_page_free_zero(m);
4456 	else
4457 		vm_page_free(m);
4458 
4459 	pmap_pt_page_count_adj(pmap, -1);
4460 }
4461 
4462 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4463 
4464 /*
4465  * Initialize a preallocated and zeroed pmap structure,
4466  * such as one in a vmspace structure.
4467  */
4468 int
pmap_pinit_type(pmap_t pmap,enum pmap_type pm_type,int flags)4469 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4470 {
4471 	vm_page_t pmltop_pg, pmltop_pgu;
4472 	vm_paddr_t pmltop_phys;
4473 
4474 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4475 
4476 	/*
4477 	 * Allocate the page directory page.  Pass NULL instead of a
4478 	 * pointer to the pmap here to avoid calling
4479 	 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4480 	 * since that requires pmap lock.  Instead do the accounting
4481 	 * manually.
4482 	 *
4483 	 * Note that final call to pmap_remove() optimization that
4484 	 * checks for zero resident_count is basically disabled by
4485 	 * accounting for top-level page.  But the optimization was
4486 	 * not effective since we started using non-managed mapping of
4487 	 * the shared page.
4488 	 */
4489 	pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4490 	    VM_ALLOC_WAITOK);
4491 	pmap_pt_page_count_pinit(pmap, 1);
4492 
4493 	pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4494 	pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4495 
4496 	if (pmap_pcid_enabled) {
4497 		if (pmap->pm_pcidp == NULL)
4498 			pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4499 			    M_WAITOK);
4500 		pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4501 	}
4502 	pmap->pm_cr3 = PMAP_NO_CR3;	/* initialize to an invalid value */
4503 	pmap->pm_ucr3 = PMAP_NO_CR3;
4504 	pmap->pm_pmltopu = NULL;
4505 
4506 	pmap->pm_type = pm_type;
4507 
4508 	/*
4509 	 * Do not install the host kernel mappings in the nested page
4510 	 * tables. These mappings are meaningless in the guest physical
4511 	 * address space.
4512 	 * Install minimal kernel mappings in PTI case.
4513 	 */
4514 	switch (pm_type) {
4515 	case PT_X86:
4516 		pmap->pm_cr3 = pmltop_phys;
4517 		if (pmap_is_la57(pmap))
4518 			pmap_pinit_pml5(pmltop_pg);
4519 		else
4520 			pmap_pinit_pml4(pmltop_pg);
4521 		if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4522 			/*
4523 			 * As with pmltop_pg, pass NULL instead of a
4524 			 * pointer to the pmap to ensure that the PTI
4525 			 * page counted explicitly.
4526 			 */
4527 			pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4528 			    VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4529 			pmap_pt_page_count_pinit(pmap, 1);
4530 			pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4531 			    VM_PAGE_TO_PHYS(pmltop_pgu));
4532 			if (pmap_is_la57(pmap))
4533 				pmap_pinit_pml5_pti(pmltop_pgu);
4534 			else
4535 				pmap_pinit_pml4_pti(pmltop_pgu);
4536 			pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4537 		}
4538 		if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4539 			rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4540 			    pkru_free_range, pmap, M_NOWAIT);
4541 		}
4542 		break;
4543 	case PT_EPT:
4544 	case PT_RVI:
4545 		pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4546 		break;
4547 	}
4548 
4549 	vm_radix_init(&pmap->pm_root);
4550 	CPU_ZERO(&pmap->pm_active);
4551 	TAILQ_INIT(&pmap->pm_pvchunk);
4552 	pmap->pm_flags = flags;
4553 	pmap->pm_eptgen = 0;
4554 
4555 	return (1);
4556 }
4557 
4558 int
pmap_pinit(pmap_t pmap)4559 pmap_pinit(pmap_t pmap)
4560 {
4561 
4562 	return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4563 }
4564 
4565 static void
pmap_allocpte_free_unref(pmap_t pmap,vm_offset_t va,pt_entry_t * pte)4566 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4567 {
4568 	vm_page_t mpg;
4569 	struct spglist free;
4570 
4571 	mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4572 	if (mpg->ref_count != 0)
4573 		return;
4574 	SLIST_INIT(&free);
4575 	_pmap_unwire_ptp(pmap, va, mpg, &free);
4576 	pmap_invalidate_page(pmap, va);
4577 	vm_page_free_pages_toq(&free, true);
4578 }
4579 
4580 static pml4_entry_t *
pmap_allocpte_getpml4(pmap_t pmap,struct rwlock ** lockp,vm_offset_t va,bool addref)4581 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4582     bool addref)
4583 {
4584 	vm_pindex_t pml5index;
4585 	pml5_entry_t *pml5;
4586 	pml4_entry_t *pml4;
4587 	vm_page_t pml4pg;
4588 	pt_entry_t PG_V;
4589 	bool allocated;
4590 
4591 	if (!pmap_is_la57(pmap))
4592 		return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4593 
4594 	PG_V = pmap_valid_bit(pmap);
4595 	pml5index = pmap_pml5e_index(va);
4596 	pml5 = &pmap->pm_pmltop[pml5index];
4597 	if ((*pml5 & PG_V) == 0) {
4598 		if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4599 		    va) == NULL)
4600 			return (NULL);
4601 		allocated = true;
4602 	} else {
4603 		allocated = false;
4604 	}
4605 	pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4606 	pml4 = &pml4[pmap_pml4e_index(va)];
4607 	if ((*pml4 & PG_V) == 0) {
4608 		pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4609 		if (allocated && !addref)
4610 			pml4pg->ref_count--;
4611 		else if (!allocated && addref)
4612 			pml4pg->ref_count++;
4613 	}
4614 	return (pml4);
4615 }
4616 
4617 static pdp_entry_t *
pmap_allocpte_getpdp(pmap_t pmap,struct rwlock ** lockp,vm_offset_t va,bool addref)4618 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4619     bool addref)
4620 {
4621 	vm_page_t pdppg;
4622 	pml4_entry_t *pml4;
4623 	pdp_entry_t *pdp;
4624 	pt_entry_t PG_V;
4625 	bool allocated;
4626 
4627 	PG_V = pmap_valid_bit(pmap);
4628 
4629 	pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4630 	if (pml4 == NULL)
4631 		return (NULL);
4632 
4633 	if ((*pml4 & PG_V) == 0) {
4634 		/* Have to allocate a new pdp, recurse */
4635 		if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4636 		    va) == NULL) {
4637 			if (pmap_is_la57(pmap))
4638 				pmap_allocpte_free_unref(pmap, va,
4639 				    pmap_pml5e(pmap, va));
4640 			return (NULL);
4641 		}
4642 		allocated = true;
4643 	} else {
4644 		allocated = false;
4645 	}
4646 	pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4647 	pdp = &pdp[pmap_pdpe_index(va)];
4648 	if ((*pdp & PG_V) == 0) {
4649 		pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4650 		if (allocated && !addref)
4651 			pdppg->ref_count--;
4652 		else if (!allocated && addref)
4653 			pdppg->ref_count++;
4654 	}
4655 	return (pdp);
4656 }
4657 
4658 /*
4659  * The ptepindexes, i.e. page indices, of the page table pages encountered
4660  * while translating virtual address va are defined as follows:
4661  * - for the page table page (last level),
4662  *      ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4663  *   in other words, it is just the index of the PDE that maps the page
4664  *   table page.
4665  * - for the page directory page,
4666  *      ptepindex = NUPDE (number of userland PD entries) +
4667  *          (pmap_pde_index(va) >> NPDEPGSHIFT)
4668  *   i.e. index of PDPE is put after the last index of PDE,
4669  * - for the page directory pointer page,
4670  *      ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4671  *          NPML4EPGSHIFT),
4672  *   i.e. index of pml4e is put after the last index of PDPE,
4673  * - for the PML4 page (if LA57 mode is enabled),
4674  *      ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4675  *          (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4676  *   i.e. index of pml5e is put after the last index of PML4E.
4677  *
4678  * Define an order on the paging entries, where all entries of the
4679  * same height are put together, then heights are put from deepest to
4680  * root.  Then ptexpindex is the sequential number of the
4681  * corresponding paging entry in this order.
4682  *
4683  * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4684  * LA57 paging structures even in LA48 paging mode. Moreover, the
4685  * ptepindexes are calculated as if the paging structures were 5-level
4686  * regardless of the actual mode of operation.
4687  *
4688  * The root page at PML4/PML5 does not participate in this indexing scheme,
4689  * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4690  */
4691 static vm_page_t
pmap_allocpte_nosleep(pmap_t pmap,vm_pindex_t ptepindex,struct rwlock ** lockp,vm_offset_t va)4692 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4693     vm_offset_t va)
4694 {
4695 	vm_pindex_t pml5index, pml4index;
4696 	pml5_entry_t *pml5, *pml5u;
4697 	pml4_entry_t *pml4, *pml4u;
4698 	pdp_entry_t *pdp;
4699 	pd_entry_t *pd;
4700 	vm_page_t m, pdpg;
4701 	pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4702 
4703 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4704 
4705 	PG_A = pmap_accessed_bit(pmap);
4706 	PG_M = pmap_modified_bit(pmap);
4707 	PG_V = pmap_valid_bit(pmap);
4708 	PG_RW = pmap_rw_bit(pmap);
4709 
4710 	/*
4711 	 * Allocate a page table page.
4712 	 */
4713 	m = pmap_alloc_pt_page(pmap, ptepindex,
4714 	    VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4715 	if (m == NULL)
4716 		return (NULL);
4717 
4718 	/*
4719 	 * Map the pagetable page into the process address space, if
4720 	 * it isn't already there.
4721 	 */
4722 	if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4723 		MPASS(pmap_is_la57(pmap));
4724 
4725 		pml5index = pmap_pml5e_index(va);
4726 		pml5 = &pmap->pm_pmltop[pml5index];
4727 		KASSERT((*pml5 & PG_V) == 0,
4728 		    ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4729 		*pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4730 
4731 		if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4732 			MPASS(pmap->pm_ucr3 != PMAP_NO_CR3);
4733 			*pml5 |= pg_nx;
4734 
4735 			pml5u = &pmap->pm_pmltopu[pml5index];
4736 			*pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4737 			    PG_A | PG_M;
4738 		}
4739 	} else if (ptepindex >= NUPDE + NUPDPE) {
4740 		pml4index = pmap_pml4e_index(va);
4741 		/* Wire up a new PDPE page */
4742 		pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4743 		if (pml4 == NULL) {
4744 			pmap_free_pt_page(pmap, m, true);
4745 			return (NULL);
4746 		}
4747 		KASSERT((*pml4 & PG_V) == 0,
4748 		    ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4749 		*pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4750 
4751 		if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4752 		    pml4index < NUPML4E) {
4753 			MPASS(pmap->pm_ucr3 != PMAP_NO_CR3);
4754 
4755 			/*
4756 			 * PTI: Make all user-space mappings in the
4757 			 * kernel-mode page table no-execute so that
4758 			 * we detect any programming errors that leave
4759 			 * the kernel-mode page table active on return
4760 			 * to user space.
4761 			 */
4762 			*pml4 |= pg_nx;
4763 
4764 			pml4u = &pmap->pm_pmltopu[pml4index];
4765 			*pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4766 			    PG_A | PG_M;
4767 		}
4768 	} else if (ptepindex >= NUPDE) {
4769 		/* Wire up a new PDE page */
4770 		pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4771 		if (pdp == NULL) {
4772 			pmap_free_pt_page(pmap, m, true);
4773 			return (NULL);
4774 		}
4775 		KASSERT((*pdp & PG_V) == 0,
4776 		    ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4777 		*pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4778 	} else {
4779 		/* Wire up a new PTE page */
4780 		pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4781 		if (pdp == NULL) {
4782 			pmap_free_pt_page(pmap, m, true);
4783 			return (NULL);
4784 		}
4785 		if ((*pdp & PG_V) == 0) {
4786 			/* Have to allocate a new pd, recurse */
4787 			if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4788 			    lockp, va) == NULL) {
4789 				pmap_allocpte_free_unref(pmap, va,
4790 				    pmap_pml4e(pmap, va));
4791 				pmap_free_pt_page(pmap, m, true);
4792 				return (NULL);
4793 			}
4794 		} else {
4795 			/* Add reference to the pd page */
4796 			pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4797 			pdpg->ref_count++;
4798 		}
4799 		pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4800 
4801 		/* Now we know where the page directory page is */
4802 		pd = &pd[pmap_pde_index(va)];
4803 		KASSERT((*pd & PG_V) == 0,
4804 		    ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4805 		*pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4806 	}
4807 
4808 	return (m);
4809 }
4810 
4811 /*
4812  * This routine is called if the desired page table page does not exist.
4813  *
4814  * If page table page allocation fails, this routine may sleep before
4815  * returning NULL.  It sleeps only if a lock pointer was given.  Sleep
4816  * occurs right before returning to the caller. This way, we never
4817  * drop pmap lock to sleep while a page table page has ref_count == 0,
4818  * which prevents the page from being freed under us.
4819  */
4820 static vm_page_t
pmap_allocpte_alloc(pmap_t pmap,vm_pindex_t ptepindex,struct rwlock ** lockp,vm_offset_t va)4821 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4822     vm_offset_t va)
4823 {
4824 	vm_page_t m;
4825 
4826 	m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4827 	if (m == NULL && lockp != NULL) {
4828 		RELEASE_PV_LIST_LOCK(lockp);
4829 		PMAP_UNLOCK(pmap);
4830 		PMAP_ASSERT_NOT_IN_DI();
4831 		vm_wait(NULL);
4832 		PMAP_LOCK(pmap);
4833 	}
4834 	return (m);
4835 }
4836 
4837 static pd_entry_t *
pmap_alloc_pde(pmap_t pmap,vm_offset_t va,vm_page_t * pdpgp,struct rwlock ** lockp)4838 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4839     struct rwlock **lockp)
4840 {
4841 	pdp_entry_t *pdpe, PG_V;
4842 	pd_entry_t *pde;
4843 	vm_page_t pdpg;
4844 	vm_pindex_t pdpindex;
4845 
4846 	PG_V = pmap_valid_bit(pmap);
4847 
4848 retry:
4849 	pdpe = pmap_pdpe(pmap, va);
4850 	if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4851 		pde = pmap_pdpe_to_pde(pdpe, va);
4852 		if (va < VM_MAXUSER_ADDRESS) {
4853 			/* Add a reference to the pd page. */
4854 			pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4855 			pdpg->ref_count++;
4856 		} else
4857 			pdpg = NULL;
4858 	} else if (va < VM_MAXUSER_ADDRESS) {
4859 		/* Allocate a pd page. */
4860 		pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4861 		pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4862 		if (pdpg == NULL) {
4863 			if (lockp != NULL)
4864 				goto retry;
4865 			else
4866 				return (NULL);
4867 		}
4868 		pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4869 		pde = &pde[pmap_pde_index(va)];
4870 	} else
4871 		panic("pmap_alloc_pde: missing page table page for va %#lx",
4872 		    va);
4873 	*pdpgp = pdpg;
4874 	return (pde);
4875 }
4876 
4877 static vm_page_t
pmap_allocpte(pmap_t pmap,vm_offset_t va,struct rwlock ** lockp)4878 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4879 {
4880 	vm_pindex_t ptepindex;
4881 	pd_entry_t *pd, PG_V;
4882 	vm_page_t m;
4883 
4884 	PG_V = pmap_valid_bit(pmap);
4885 
4886 	/*
4887 	 * Calculate pagetable page index
4888 	 */
4889 	ptepindex = pmap_pde_pindex(va);
4890 retry:
4891 	/*
4892 	 * Get the page directory entry
4893 	 */
4894 	pd = pmap_pde(pmap, va);
4895 
4896 	/*
4897 	 * This supports switching from a 2MB page to a
4898 	 * normal 4K page.
4899 	 */
4900 	if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4901 		if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4902 			/*
4903 			 * Invalidation of the 2MB page mapping may have caused
4904 			 * the deallocation of the underlying PD page.
4905 			 */
4906 			pd = NULL;
4907 		}
4908 	}
4909 
4910 	/*
4911 	 * If the page table page is mapped, we just increment the
4912 	 * hold count, and activate it.
4913 	 */
4914 	if (pd != NULL && (*pd & PG_V) != 0) {
4915 		m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4916 		m->ref_count++;
4917 	} else {
4918 		/*
4919 		 * Here if the pte page isn't mapped, or if it has been
4920 		 * deallocated.
4921 		 */
4922 		m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4923 		if (m == NULL && lockp != NULL)
4924 			goto retry;
4925 	}
4926 	return (m);
4927 }
4928 
4929 /***************************************************
4930  * Pmap allocation/deallocation routines.
4931  ***************************************************/
4932 
4933 /*
4934  * Release any resources held by the given physical map.
4935  * Called when a pmap initialized by pmap_pinit is being released.
4936  * Should only be called if the map contains no valid mappings.
4937  */
4938 void
pmap_release(pmap_t pmap)4939 pmap_release(pmap_t pmap)
4940 {
4941 	vm_page_t m;
4942 	int i;
4943 
4944 	KASSERT(vm_radix_is_empty(&pmap->pm_root),
4945 	    ("pmap_release: pmap %p has reserved page table page(s)",
4946 	    pmap));
4947 	KASSERT(CPU_EMPTY(&pmap->pm_active),
4948 	    ("releasing active pmap %p", pmap));
4949 
4950 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4951 
4952 	if (pmap_is_la57(pmap)) {
4953 		pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4954 		pmap->pm_pmltop[PML5PML5I] = 0;
4955 	} else {
4956 		for (i = 0; i < NKPML4E; i++)	/* KVA */
4957 			pmap->pm_pmltop[KPML4BASE + i] = 0;
4958 #ifdef KASAN
4959 		for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4960 			pmap->pm_pmltop[KASANPML4I + i] = 0;
4961 #endif
4962 #ifdef KMSAN
4963 		for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4964 			pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4965 		for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4966 			pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4967 #endif
4968 		for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4969 			pmap->pm_pmltop[DMPML4I + i] = 0;
4970 		pmap->pm_pmltop[PML4PML4I] = 0;	/* Recursive Mapping */
4971 		for (i = 0; i < lm_ents; i++)	/* Large Map */
4972 			pmap->pm_pmltop[LMSPML4I + i] = 0;
4973 	}
4974 
4975 	pmap_free_pt_page(NULL, m, true);
4976 	pmap_pt_page_count_pinit(pmap, -1);
4977 
4978 	if (pmap->pm_pmltopu != NULL) {
4979 		m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4980 		    pm_pmltopu));
4981 		pmap_free_pt_page(NULL, m, false);
4982 		pmap_pt_page_count_pinit(pmap, -1);
4983 	}
4984 	if (pmap->pm_type == PT_X86 &&
4985 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4986 		rangeset_fini(&pmap->pm_pkru);
4987 
4988 	KASSERT(pmap->pm_stats.resident_count == 0,
4989 	    ("pmap_release: pmap %p resident count %ld != 0",
4990 	    pmap, pmap->pm_stats.resident_count));
4991 }
4992 
4993 static int
kvm_size(SYSCTL_HANDLER_ARGS)4994 kvm_size(SYSCTL_HANDLER_ARGS)
4995 {
4996 	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4997 
4998 	return sysctl_handle_long(oidp, &ksize, 0, req);
4999 }
5000 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
5001     0, 0, kvm_size, "LU",
5002     "Size of KVM");
5003 
5004 static int
kvm_free(SYSCTL_HANDLER_ARGS)5005 kvm_free(SYSCTL_HANDLER_ARGS)
5006 {
5007 	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
5008 
5009 	return sysctl_handle_long(oidp, &kfree, 0, req);
5010 }
5011 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
5012     0, 0, kvm_free, "LU",
5013     "Amount of KVM free");
5014 
5015 #ifdef KMSAN
5016 static void
pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa,vm_size_t size)5017 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
5018 {
5019 	pdp_entry_t *pdpe;
5020 	pd_entry_t *pde;
5021 	pt_entry_t *pte;
5022 	vm_paddr_t dummypa, dummypd, dummypt;
5023 	int i, npde, npdpg;
5024 
5025 	npdpg = howmany(size, NBPDP);
5026 	npde = size / NBPDR;
5027 
5028 	dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
5029 	pagezero((void *)PHYS_TO_DMAP(dummypa));
5030 
5031 	dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
5032 	pagezero((void *)PHYS_TO_DMAP(dummypt));
5033 	dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
5034 	for (i = 0; i < npdpg; i++)
5035 		pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
5036 
5037 	pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
5038 	for (i = 0; i < NPTEPG; i++)
5039 		pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
5040 		    X86_PG_A | X86_PG_M | pg_nx);
5041 
5042 	pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
5043 	for (i = 0; i < npde; i++)
5044 		pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
5045 
5046 	pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
5047 	for (i = 0; i < npdpg; i++)
5048 		pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
5049 		    X86_PG_RW | pg_nx);
5050 }
5051 
5052 static void
pmap_kmsan_page_array_startup(vm_offset_t start,vm_offset_t end)5053 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
5054 {
5055 	vm_size_t size;
5056 
5057 	KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
5058 
5059 	/*
5060 	 * The end of the page array's KVA region is 2MB aligned, see
5061 	 * kmem_init().
5062 	 */
5063 	size = round_2mpage(end) - start;
5064 	pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
5065 	pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
5066 }
5067 #endif
5068 
5069 /*
5070  * Allocate physical memory for the vm_page array and map it into KVA,
5071  * attempting to back the vm_pages with domain-local memory.
5072  */
5073 void
pmap_page_array_startup(long pages)5074 pmap_page_array_startup(long pages)
5075 {
5076 	pdp_entry_t *pdpe;
5077 	pd_entry_t *pde, newpdir;
5078 	vm_offset_t va, start, end;
5079 	vm_paddr_t pa;
5080 	long pfn;
5081 	int domain, i;
5082 
5083 	vm_page_array_size = pages;
5084 
5085 	start = VM_MIN_KERNEL_ADDRESS;
5086 	end = start + pages * sizeof(struct vm_page);
5087 	for (va = start; va < end; va += NBPDR) {
5088 		pfn = first_page + (va - start) / sizeof(struct vm_page);
5089 		domain = vm_phys_domain(ptoa(pfn));
5090 		pdpe = pmap_pdpe(kernel_pmap, va);
5091 		if ((*pdpe & X86_PG_V) == 0) {
5092 			pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5093 			dump_add_page(pa);
5094 			pagezero((void *)PHYS_TO_DMAP(pa));
5095 			*pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5096 			    X86_PG_A | X86_PG_M);
5097 		}
5098 		pde = pmap_pdpe_to_pde(pdpe, va);
5099 		if ((*pde & X86_PG_V) != 0)
5100 			panic("Unexpected pde");
5101 		pa = vm_phys_early_alloc(domain, NBPDR);
5102 		for (i = 0; i < NPDEPG; i++)
5103 			dump_add_page(pa + i * PAGE_SIZE);
5104 		newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5105 		    X86_PG_M | PG_PS | pg_g | pg_nx);
5106 		pde_store(pde, newpdir);
5107 	}
5108 	vm_page_array = (vm_page_t)start;
5109 
5110 #ifdef KMSAN
5111 	pmap_kmsan_page_array_startup(start, end);
5112 #endif
5113 }
5114 
5115 /*
5116  * grow the number of kernel page table entries, if needed
5117  */
5118 void
pmap_growkernel(vm_offset_t addr)5119 pmap_growkernel(vm_offset_t addr)
5120 {
5121 	vm_paddr_t paddr;
5122 	vm_page_t nkpg;
5123 	pd_entry_t *pde, newpdir;
5124 	pdp_entry_t *pdpe;
5125 	vm_offset_t end;
5126 
5127 	TSENTER();
5128 	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5129 
5130 	/*
5131 	 * The kernel map covers two distinct regions of KVA: that used
5132 	 * for dynamic kernel memory allocations, and the uppermost 2GB
5133 	 * of the virtual address space.  The latter is used to map the
5134 	 * kernel and loadable kernel modules.  This scheme enables the
5135 	 * use of a special code generation model for kernel code which
5136 	 * takes advantage of compact addressing modes in machine code.
5137 	 *
5138 	 * Both regions grow upwards; to avoid wasting memory, the gap
5139 	 * in between is unmapped.  If "addr" is above "KERNBASE", the
5140 	 * kernel's region is grown, otherwise the kmem region is grown.
5141 	 *
5142 	 * The correctness of this action is based on the following
5143 	 * argument: vm_map_insert() allocates contiguous ranges of the
5144 	 * kernel virtual address space.  It calls this function if a range
5145 	 * ends after "kernel_vm_end".  If the kernel is mapped between
5146 	 * "kernel_vm_end" and "addr", then the range cannot begin at
5147 	 * "kernel_vm_end".  In fact, its beginning address cannot be less
5148 	 * than the kernel.  Thus, there is no immediate need to allocate
5149 	 * any new kernel page table pages between "kernel_vm_end" and
5150 	 * "KERNBASE".
5151 	 */
5152 	if (KERNBASE < addr) {
5153 		end = KERNBASE + nkpt * NBPDR;
5154 		if (end == 0) {
5155 			TSEXIT();
5156 			return;
5157 		}
5158 	} else {
5159 		end = kernel_vm_end;
5160 	}
5161 
5162 	addr = roundup2(addr, NBPDR);
5163 	if (addr - 1 >= vm_map_max(kernel_map))
5164 		addr = vm_map_max(kernel_map);
5165 	if (addr <= end) {
5166 		/*
5167 		 * The grown region is already mapped, so there is
5168 		 * nothing to do.
5169 		 */
5170 		TSEXIT();
5171 		return;
5172 	}
5173 
5174 	kasan_shadow_map(end, addr - end);
5175 	kmsan_shadow_map(end, addr - end);
5176 	while (end < addr) {
5177 		pdpe = pmap_pdpe(kernel_pmap, end);
5178 		if ((*pdpe & X86_PG_V) == 0) {
5179 			nkpg = pmap_alloc_pt_page(kernel_pmap,
5180 			    pmap_pdpe_pindex(end), VM_ALLOC_INTERRUPT |
5181 			        VM_ALLOC_NOFREE | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
5182 			if (nkpg == NULL)
5183 				panic("pmap_growkernel: no memory to grow kernel");
5184 			paddr = VM_PAGE_TO_PHYS(nkpg);
5185 			*pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5186 			    X86_PG_A | X86_PG_M);
5187 			continue; /* try again */
5188 		}
5189 		pde = pmap_pdpe_to_pde(pdpe, end);
5190 		if ((*pde & X86_PG_V) != 0) {
5191 			end = (end + NBPDR) & ~PDRMASK;
5192 			if (end - 1 >= vm_map_max(kernel_map)) {
5193 				end = vm_map_max(kernel_map);
5194 				break;
5195 			}
5196 			continue;
5197 		}
5198 
5199 		nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5200 		    VM_ALLOC_INTERRUPT | VM_ALLOC_NOFREE | VM_ALLOC_WIRED |
5201 			VM_ALLOC_ZERO);
5202 		if (nkpg == NULL)
5203 			panic("pmap_growkernel: no memory to grow kernel");
5204 		paddr = VM_PAGE_TO_PHYS(nkpg);
5205 		newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5206 		pde_store(pde, newpdir);
5207 
5208 		end = (end + NBPDR) & ~PDRMASK;
5209 		if (end - 1 >= vm_map_max(kernel_map)) {
5210 			end = vm_map_max(kernel_map);
5211 			break;
5212 		}
5213 	}
5214 
5215 	if (end <= KERNBASE)
5216 		kernel_vm_end = end;
5217 	else
5218 		nkpt = howmany(end - KERNBASE, NBPDR);
5219 	TSEXIT();
5220 }
5221 
5222 /***************************************************
5223  * page management routines.
5224  ***************************************************/
5225 
5226 static const uint64_t pc_freemask[_NPCM] = {
5227 	[0 ... _NPCM - 2] = PC_FREEN,
5228 	[_NPCM - 1] = PC_FREEL
5229 };
5230 
5231 #ifdef PV_STATS
5232 
5233 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5234 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5235     &pc_chunk_count, "Current number of pv entry cnunks");
5236 
5237 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5238 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5239     &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5240 
5241 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5242 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5243     &pc_chunk_frees, "Total number of pv entry chunks freed");
5244 
5245 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5246 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5247     &pc_chunk_tryfail,
5248     "Number of failed attempts to get a pv entry chunk page");
5249 
5250 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5251 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5252     &pv_entry_frees, "Total number of pv entries freed");
5253 
5254 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5255 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5256     &pv_entry_allocs, "Total number of pv entries allocated");
5257 
5258 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5259 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5260     &pv_entry_count, "Current number of pv entries");
5261 
5262 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5263 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5264     &pv_entry_spare, "Current number of spare pv entries");
5265 #endif
5266 
5267 static void
reclaim_pv_chunk_leave_pmap(pmap_t pmap,pmap_t locked_pmap,bool start_di)5268 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5269 {
5270 
5271 	if (pmap == NULL)
5272 		return;
5273 	pmap_invalidate_all(pmap);
5274 	if (pmap != locked_pmap)
5275 		PMAP_UNLOCK(pmap);
5276 	if (start_di)
5277 		pmap_delayed_invl_finish();
5278 }
5279 
5280 /*
5281  * We are in a serious low memory condition.  Resort to
5282  * drastic measures to free some pages so we can allocate
5283  * another pv entry chunk.
5284  *
5285  * Returns NULL if PV entries were reclaimed from the specified pmap.
5286  *
5287  * We do not, however, unmap 2mpages because subsequent accesses will
5288  * allocate per-page pv entries until repromotion occurs, thereby
5289  * exacerbating the shortage of free pv entries.
5290  */
5291 static vm_page_t
reclaim_pv_chunk_domain(pmap_t locked_pmap,struct rwlock ** lockp,int domain)5292 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5293 {
5294 	struct pv_chunks_list *pvc;
5295 	struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5296 	struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5297 	struct md_page *pvh;
5298 	pd_entry_t *pde;
5299 	pmap_t next_pmap, pmap;
5300 	pt_entry_t *pte, tpte;
5301 	pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5302 	pv_entry_t pv;
5303 	vm_offset_t va;
5304 	vm_page_t m, m_pc;
5305 	struct spglist free;
5306 	uint64_t inuse;
5307 	int bit, field, freed;
5308 	bool start_di, restart;
5309 
5310 	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5311 	KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5312 	pmap = NULL;
5313 	m_pc = NULL;
5314 	PG_G = PG_A = PG_M = PG_RW = 0;
5315 	SLIST_INIT(&free);
5316 	bzero(&pc_marker_b, sizeof(pc_marker_b));
5317 	bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5318 	pc_marker = (struct pv_chunk *)&pc_marker_b;
5319 	pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5320 
5321 	/*
5322 	 * A delayed invalidation block should already be active if
5323 	 * pmap_advise() or pmap_remove() called this function by way
5324 	 * of pmap_demote_pde_locked().
5325 	 */
5326 	start_di = pmap_not_in_di();
5327 
5328 	pvc = &pv_chunks[domain];
5329 	mtx_lock(&pvc->pvc_lock);
5330 	pvc->active_reclaims++;
5331 	TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5332 	TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5333 	while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5334 	    SLIST_EMPTY(&free)) {
5335 		next_pmap = pc->pc_pmap;
5336 		if (next_pmap == NULL) {
5337 			/*
5338 			 * The next chunk is a marker.  However, it is
5339 			 * not our marker, so active_reclaims must be
5340 			 * > 1.  Consequently, the next_chunk code
5341 			 * will not rotate the pv_chunks list.
5342 			 */
5343 			goto next_chunk;
5344 		}
5345 		mtx_unlock(&pvc->pvc_lock);
5346 
5347 		/*
5348 		 * A pv_chunk can only be removed from the pc_lru list
5349 		 * when both pc_chunks_mutex is owned and the
5350 		 * corresponding pmap is locked.
5351 		 */
5352 		if (pmap != next_pmap) {
5353 			restart = false;
5354 			reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5355 			    start_di);
5356 			pmap = next_pmap;
5357 			/* Avoid deadlock and lock recursion. */
5358 			if (pmap > locked_pmap) {
5359 				RELEASE_PV_LIST_LOCK(lockp);
5360 				PMAP_LOCK(pmap);
5361 				if (start_di)
5362 					pmap_delayed_invl_start();
5363 				mtx_lock(&pvc->pvc_lock);
5364 				restart = true;
5365 			} else if (pmap != locked_pmap) {
5366 				if (PMAP_TRYLOCK(pmap)) {
5367 					if (start_di)
5368 						pmap_delayed_invl_start();
5369 					mtx_lock(&pvc->pvc_lock);
5370 					restart = true;
5371 				} else {
5372 					pmap = NULL; /* pmap is not locked */
5373 					mtx_lock(&pvc->pvc_lock);
5374 					pc = TAILQ_NEXT(pc_marker, pc_lru);
5375 					if (pc == NULL ||
5376 					    pc->pc_pmap != next_pmap)
5377 						continue;
5378 					goto next_chunk;
5379 				}
5380 			} else if (start_di)
5381 				pmap_delayed_invl_start();
5382 			PG_G = pmap_global_bit(pmap);
5383 			PG_A = pmap_accessed_bit(pmap);
5384 			PG_M = pmap_modified_bit(pmap);
5385 			PG_RW = pmap_rw_bit(pmap);
5386 			if (restart)
5387 				continue;
5388 		}
5389 
5390 		/*
5391 		 * Destroy every non-wired, 4 KB page mapping in the chunk.
5392 		 */
5393 		freed = 0;
5394 		for (field = 0; field < _NPCM; field++) {
5395 			for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5396 			    inuse != 0; inuse &= ~(1UL << bit)) {
5397 				bit = bsfq(inuse);
5398 				pv = &pc->pc_pventry[field * 64 + bit];
5399 				va = pv->pv_va;
5400 				pde = pmap_pde(pmap, va);
5401 				if ((*pde & PG_PS) != 0)
5402 					continue;
5403 				pte = pmap_pde_to_pte(pde, va);
5404 				if ((*pte & PG_W) != 0)
5405 					continue;
5406 				tpte = pte_load_clear(pte);
5407 				if ((tpte & PG_G) != 0)
5408 					pmap_invalidate_page(pmap, va);
5409 				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5410 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5411 					vm_page_dirty(m);
5412 				if ((tpte & PG_A) != 0)
5413 					vm_page_aflag_set(m, PGA_REFERENCED);
5414 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5415 				TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5416 				m->md.pv_gen++;
5417 				if (TAILQ_EMPTY(&m->md.pv_list) &&
5418 				    (m->flags & PG_FICTITIOUS) == 0) {
5419 					pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5420 					if (TAILQ_EMPTY(&pvh->pv_list)) {
5421 						vm_page_aflag_clear(m,
5422 						    PGA_WRITEABLE);
5423 					}
5424 				}
5425 				pmap_delayed_invl_page(m);
5426 				pc->pc_map[field] |= 1UL << bit;
5427 				pmap_unuse_pt(pmap, va, *pde, &free);
5428 				freed++;
5429 			}
5430 		}
5431 		if (freed == 0) {
5432 			mtx_lock(&pvc->pvc_lock);
5433 			goto next_chunk;
5434 		}
5435 		/* Every freed mapping is for a 4 KB page. */
5436 		pmap_resident_count_adj(pmap, -freed);
5437 		PV_STAT(counter_u64_add(pv_entry_frees, freed));
5438 		PV_STAT(counter_u64_add(pv_entry_spare, freed));
5439 		PV_STAT(counter_u64_add(pv_entry_count, -freed));
5440 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5441 		if (pc_is_free(pc)) {
5442 			PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5443 			PV_STAT(counter_u64_add(pc_chunk_count, -1));
5444 			PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5445 			/* Entire chunk is free; return it. */
5446 			m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5447 			dump_drop_page(m_pc->phys_addr);
5448 			mtx_lock(&pvc->pvc_lock);
5449 			TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5450 			break;
5451 		}
5452 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5453 		mtx_lock(&pvc->pvc_lock);
5454 		/* One freed pv entry in locked_pmap is sufficient. */
5455 		if (pmap == locked_pmap)
5456 			break;
5457 next_chunk:
5458 		TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5459 		TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5460 		if (pvc->active_reclaims == 1 && pmap != NULL) {
5461 			/*
5462 			 * Rotate the pv chunks list so that we do not
5463 			 * scan the same pv chunks that could not be
5464 			 * freed (because they contained a wired
5465 			 * and/or superpage mapping) on every
5466 			 * invocation of reclaim_pv_chunk().
5467 			 */
5468 			while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5469 				MPASS(pc->pc_pmap != NULL);
5470 				TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5471 				TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5472 			}
5473 		}
5474 	}
5475 	TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5476 	TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5477 	pvc->active_reclaims--;
5478 	mtx_unlock(&pvc->pvc_lock);
5479 	reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5480 	if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5481 		m_pc = SLIST_FIRST(&free);
5482 		SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5483 		/* Recycle a freed page table page. */
5484 		m_pc->ref_count = 1;
5485 	}
5486 	vm_page_free_pages_toq(&free, true);
5487 	return (m_pc);
5488 }
5489 
5490 static vm_page_t
reclaim_pv_chunk(pmap_t locked_pmap,struct rwlock ** lockp)5491 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5492 {
5493 	vm_page_t m;
5494 	int i, domain;
5495 
5496 	domain = PCPU_GET(domain);
5497 	for (i = 0; i < vm_ndomains; i++) {
5498 		m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5499 		if (m != NULL)
5500 			break;
5501 		domain = (domain + 1) % vm_ndomains;
5502 	}
5503 
5504 	return (m);
5505 }
5506 
5507 /*
5508  * free the pv_entry back to the free list
5509  */
5510 static void
free_pv_entry(pmap_t pmap,pv_entry_t pv)5511 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5512 {
5513 	struct pv_chunk *pc;
5514 	int idx, field, bit;
5515 
5516 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5517 	PV_STAT(counter_u64_add(pv_entry_frees, 1));
5518 	PV_STAT(counter_u64_add(pv_entry_spare, 1));
5519 	PV_STAT(counter_u64_add(pv_entry_count, -1));
5520 	pc = pv_to_chunk(pv);
5521 	idx = pv - &pc->pc_pventry[0];
5522 	field = idx / 64;
5523 	bit = idx % 64;
5524 	pc->pc_map[field] |= 1ul << bit;
5525 	if (!pc_is_free(pc)) {
5526 		/* 98% of the time, pc is already at the head of the list. */
5527 		if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5528 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5529 			TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5530 		}
5531 		return;
5532 	}
5533 	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5534 	free_pv_chunk(pc);
5535 }
5536 
5537 static void
free_pv_chunk_dequeued(struct pv_chunk * pc)5538 free_pv_chunk_dequeued(struct pv_chunk *pc)
5539 {
5540 	vm_page_t m;
5541 
5542 	PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5543 	PV_STAT(counter_u64_add(pc_chunk_count, -1));
5544 	PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5545 	counter_u64_add(pv_page_count, -1);
5546 	/* entire chunk is free, return it */
5547 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5548 	dump_drop_page(m->phys_addr);
5549 	vm_page_unwire_noq(m);
5550 	vm_page_free(m);
5551 }
5552 
5553 static void
free_pv_chunk(struct pv_chunk * pc)5554 free_pv_chunk(struct pv_chunk *pc)
5555 {
5556 	struct pv_chunks_list *pvc;
5557 
5558 	pvc = &pv_chunks[pc_to_domain(pc)];
5559 	mtx_lock(&pvc->pvc_lock);
5560 	TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5561 	mtx_unlock(&pvc->pvc_lock);
5562 	free_pv_chunk_dequeued(pc);
5563 }
5564 
5565 static void
free_pv_chunk_batch(struct pv_chunklist * batch)5566 free_pv_chunk_batch(struct pv_chunklist *batch)
5567 {
5568 	struct pv_chunks_list *pvc;
5569 	struct pv_chunk *pc, *npc;
5570 	int i;
5571 
5572 	for (i = 0; i < vm_ndomains; i++) {
5573 		if (TAILQ_EMPTY(&batch[i]))
5574 			continue;
5575 		pvc = &pv_chunks[i];
5576 		mtx_lock(&pvc->pvc_lock);
5577 		TAILQ_FOREACH(pc, &batch[i], pc_list) {
5578 			TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5579 		}
5580 		mtx_unlock(&pvc->pvc_lock);
5581 	}
5582 
5583 	for (i = 0; i < vm_ndomains; i++) {
5584 		TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5585 			free_pv_chunk_dequeued(pc);
5586 		}
5587 	}
5588 }
5589 
5590 /*
5591  * Returns a new PV entry, allocating a new PV chunk from the system when
5592  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
5593  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
5594  * returned.
5595  *
5596  * The given PV list lock may be released.
5597  */
5598 static pv_entry_t
get_pv_entry(pmap_t pmap,struct rwlock ** lockp)5599 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5600 {
5601 	struct pv_chunks_list *pvc;
5602 	int bit, field;
5603 	pv_entry_t pv;
5604 	struct pv_chunk *pc;
5605 	vm_page_t m;
5606 
5607 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5608 	PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5609 retry:
5610 	pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5611 	if (pc != NULL) {
5612 		for (field = 0; field < _NPCM; field++) {
5613 			if (pc->pc_map[field]) {
5614 				bit = bsfq(pc->pc_map[field]);
5615 				break;
5616 			}
5617 		}
5618 		if (field < _NPCM) {
5619 			pv = &pc->pc_pventry[field * 64 + bit];
5620 			pc->pc_map[field] &= ~(1ul << bit);
5621 			/* If this was the last item, move it to tail */
5622 			if (pc_is_full(pc)) {
5623 				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5624 				TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5625 				    pc_list);
5626 			}
5627 			PV_STAT(counter_u64_add(pv_entry_count, 1));
5628 			PV_STAT(counter_u64_add(pv_entry_spare, -1));
5629 			return (pv);
5630 		}
5631 	}
5632 	/* No free items, allocate another chunk */
5633 	m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5634 	if (m == NULL) {
5635 		if (lockp == NULL) {
5636 			PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5637 			return (NULL);
5638 		}
5639 		m = reclaim_pv_chunk(pmap, lockp);
5640 		if (m == NULL)
5641 			goto retry;
5642 	} else
5643 		counter_u64_add(pv_page_count, 1);
5644 	PV_STAT(counter_u64_add(pc_chunk_count, 1));
5645 	PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5646 	dump_add_page(m->phys_addr);
5647 	pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5648 	pc->pc_pmap = pmap;
5649 	pc->pc_map[0] = PC_FREEN & ~1ul;	/* preallocated bit 0 */
5650 	pc->pc_map[1] = PC_FREEN;
5651 	pc->pc_map[2] = PC_FREEL;
5652 	pvc = &pv_chunks[vm_page_domain(m)];
5653 	mtx_lock(&pvc->pvc_lock);
5654 	TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5655 	mtx_unlock(&pvc->pvc_lock);
5656 	pv = &pc->pc_pventry[0];
5657 	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5658 	PV_STAT(counter_u64_add(pv_entry_count, 1));
5659 	PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5660 	return (pv);
5661 }
5662 
5663 /*
5664  * Returns the number of one bits within the given PV chunk map.
5665  *
5666  * The erratas for Intel processors state that "POPCNT Instruction May
5667  * Take Longer to Execute Than Expected".  It is believed that the
5668  * issue is the spurious dependency on the destination register.
5669  * Provide a hint to the register rename logic that the destination
5670  * value is overwritten, by clearing it, as suggested in the
5671  * optimization manual.  It should be cheap for unaffected processors
5672  * as well.
5673  *
5674  * Reference numbers for erratas are
5675  * 4th Gen Core: HSD146
5676  * 5th Gen Core: BDM85
5677  * 6th Gen Core: SKL029
5678  */
5679 static int
popcnt_pc_map_pq(uint64_t * map)5680 popcnt_pc_map_pq(uint64_t *map)
5681 {
5682 	u_long result, tmp;
5683 
5684 	__asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5685 	    "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5686 	    "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5687 	    : "=&r" (result), "=&r" (tmp)
5688 	    : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5689 	return (result);
5690 }
5691 
5692 /*
5693  * Ensure that the number of spare PV entries in the specified pmap meets or
5694  * exceeds the given count, "needed".
5695  *
5696  * The given PV list lock may be released.
5697  */
5698 static void
reserve_pv_entries(pmap_t pmap,int needed,struct rwlock ** lockp)5699 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5700 {
5701 	struct pv_chunks_list *pvc;
5702 	struct pch new_tail[PMAP_MEMDOM];
5703 	struct pv_chunk *pc;
5704 	vm_page_t m;
5705 	int avail, free, i;
5706 	bool reclaimed;
5707 
5708 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5709 	KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5710 
5711 	/*
5712 	 * Newly allocated PV chunks must be stored in a private list until
5713 	 * the required number of PV chunks have been allocated.  Otherwise,
5714 	 * reclaim_pv_chunk() could recycle one of these chunks.  In
5715 	 * contrast, these chunks must be added to the pmap upon allocation.
5716 	 */
5717 	for (i = 0; i < PMAP_MEMDOM; i++)
5718 		TAILQ_INIT(&new_tail[i]);
5719 retry:
5720 	avail = 0;
5721 	TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5722 #ifndef __POPCNT__
5723 		if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5724 			bit_count((bitstr_t *)pc->pc_map, 0,
5725 			    sizeof(pc->pc_map) * NBBY, &free);
5726 		else
5727 #endif
5728 		free = popcnt_pc_map_pq(pc->pc_map);
5729 		if (free == 0)
5730 			break;
5731 		avail += free;
5732 		if (avail >= needed)
5733 			break;
5734 	}
5735 	for (reclaimed = false; avail < needed; avail += _NPCPV) {
5736 		m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5737 		if (m == NULL) {
5738 			m = reclaim_pv_chunk(pmap, lockp);
5739 			if (m == NULL)
5740 				goto retry;
5741 			reclaimed = true;
5742 		} else
5743 			counter_u64_add(pv_page_count, 1);
5744 		PV_STAT(counter_u64_add(pc_chunk_count, 1));
5745 		PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5746 		dump_add_page(m->phys_addr);
5747 		pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5748 		pc->pc_pmap = pmap;
5749 		pc->pc_map[0] = PC_FREEN;
5750 		pc->pc_map[1] = PC_FREEN;
5751 		pc->pc_map[2] = PC_FREEL;
5752 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5753 		TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5754 		PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5755 
5756 		/*
5757 		 * The reclaim might have freed a chunk from the current pmap.
5758 		 * If that chunk contained available entries, we need to
5759 		 * re-count the number of available entries.
5760 		 */
5761 		if (reclaimed)
5762 			goto retry;
5763 	}
5764 	for (i = 0; i < vm_ndomains; i++) {
5765 		if (TAILQ_EMPTY(&new_tail[i]))
5766 			continue;
5767 		pvc = &pv_chunks[i];
5768 		mtx_lock(&pvc->pvc_lock);
5769 		TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5770 		mtx_unlock(&pvc->pvc_lock);
5771 	}
5772 }
5773 
5774 /*
5775  * First find and then remove the pv entry for the specified pmap and virtual
5776  * address from the specified pv list.  Returns the pv entry if found and NULL
5777  * otherwise.  This operation can be performed on pv lists for either 4KB or
5778  * 2MB page mappings.
5779  */
5780 static __inline pv_entry_t
pmap_pvh_remove(struct md_page * pvh,pmap_t pmap,vm_offset_t va)5781 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5782 {
5783 	pv_entry_t pv;
5784 
5785 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5786 		if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5787 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5788 			pvh->pv_gen++;
5789 			break;
5790 		}
5791 	}
5792 	return (pv);
5793 }
5794 
5795 /*
5796  * After demotion from a 2MB page mapping to 512 4KB page mappings,
5797  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5798  * entries for each of the 4KB page mappings.
5799  */
5800 static void
pmap_pv_demote_pde(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)5801 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5802     struct rwlock **lockp)
5803 {
5804 	struct md_page *pvh;
5805 	struct pv_chunk *pc;
5806 	pv_entry_t pv;
5807 	vm_offset_t va_last;
5808 	vm_page_t m;
5809 	int bit, field;
5810 
5811 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5812 	KASSERT((pa & PDRMASK) == 0,
5813 	    ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5814 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5815 
5816 	/*
5817 	 * Transfer the 2mpage's pv entry for this mapping to the first
5818 	 * page's pv list.  Once this transfer begins, the pv list lock
5819 	 * must not be released until the last pv entry is reinstantiated.
5820 	 */
5821 	pvh = pa_to_pvh(pa);
5822 	va = trunc_2mpage(va);
5823 	pv = pmap_pvh_remove(pvh, pmap, va);
5824 	KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5825 	m = PHYS_TO_VM_PAGE(pa);
5826 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5827 	m->md.pv_gen++;
5828 	/* Instantiate the remaining NPTEPG - 1 pv entries. */
5829 	PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5830 	va_last = va + NBPDR - PAGE_SIZE;
5831 	for (;;) {
5832 		pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5833 		KASSERT(!pc_is_full(pc), ("pmap_pv_demote_pde: missing spare"));
5834 		for (field = 0; field < _NPCM; field++) {
5835 			while (pc->pc_map[field]) {
5836 				bit = bsfq(pc->pc_map[field]);
5837 				pc->pc_map[field] &= ~(1ul << bit);
5838 				pv = &pc->pc_pventry[field * 64 + bit];
5839 				va += PAGE_SIZE;
5840 				pv->pv_va = va;
5841 				m++;
5842 				KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5843 			    ("pmap_pv_demote_pde: page %p is not managed", m));
5844 				TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5845 				m->md.pv_gen++;
5846 				if (va == va_last)
5847 					goto out;
5848 			}
5849 		}
5850 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5851 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5852 	}
5853 out:
5854 	if (pc_is_full(pc)) {
5855 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5856 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5857 	}
5858 	PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5859 	PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5860 }
5861 
5862 #if VM_NRESERVLEVEL > 0
5863 /*
5864  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5865  * replace the many pv entries for the 4KB page mappings by a single pv entry
5866  * for the 2MB page mapping.
5867  */
5868 static void
pmap_pv_promote_pde(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)5869 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5870     struct rwlock **lockp)
5871 {
5872 	struct md_page *pvh;
5873 	pv_entry_t pv;
5874 	vm_offset_t va_last;
5875 	vm_page_t m;
5876 
5877 	KASSERT((pa & PDRMASK) == 0,
5878 	    ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5879 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5880 
5881 	/*
5882 	 * Transfer the first page's pv entry for this mapping to the 2mpage's
5883 	 * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
5884 	 * a transfer avoids the possibility that get_pv_entry() calls
5885 	 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5886 	 * mappings that is being promoted.
5887 	 */
5888 	m = PHYS_TO_VM_PAGE(pa);
5889 	va = trunc_2mpage(va);
5890 	pv = pmap_pvh_remove(&m->md, pmap, va);
5891 	KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5892 	pvh = pa_to_pvh(pa);
5893 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5894 	pvh->pv_gen++;
5895 	/* Free the remaining NPTEPG - 1 pv entries. */
5896 	va_last = va + NBPDR - PAGE_SIZE;
5897 	do {
5898 		m++;
5899 		va += PAGE_SIZE;
5900 		pmap_pvh_free(&m->md, pmap, va);
5901 	} while (va < va_last);
5902 }
5903 #endif /* VM_NRESERVLEVEL > 0 */
5904 
5905 /*
5906  * First find and then destroy the pv entry for the specified pmap and virtual
5907  * address.  This operation can be performed on pv lists for either 4KB or 2MB
5908  * page mappings.
5909  */
5910 static void
pmap_pvh_free(struct md_page * pvh,pmap_t pmap,vm_offset_t va)5911 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5912 {
5913 	pv_entry_t pv;
5914 
5915 	pv = pmap_pvh_remove(pvh, pmap, va);
5916 	KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5917 	free_pv_entry(pmap, pv);
5918 }
5919 
5920 /*
5921  * Conditionally create the PV entry for a 4KB page mapping if the required
5922  * memory can be allocated without resorting to reclamation.
5923  */
5924 static bool
pmap_try_insert_pv_entry(pmap_t pmap,vm_offset_t va,vm_page_t m,struct rwlock ** lockp)5925 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5926     struct rwlock **lockp)
5927 {
5928 	pv_entry_t pv;
5929 
5930 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5931 	/* Pass NULL instead of the lock pointer to disable reclamation. */
5932 	if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5933 		pv->pv_va = va;
5934 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5935 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5936 		m->md.pv_gen++;
5937 		return (true);
5938 	} else
5939 		return (false);
5940 }
5941 
5942 /*
5943  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
5944  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
5945  * false if the PV entry cannot be allocated without resorting to reclamation.
5946  */
5947 static bool
pmap_pv_insert_pde(pmap_t pmap,vm_offset_t va,pd_entry_t pde,u_int flags,struct rwlock ** lockp)5948 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5949     struct rwlock **lockp)
5950 {
5951 	struct md_page *pvh;
5952 	pv_entry_t pv;
5953 	vm_paddr_t pa;
5954 
5955 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5956 	/* Pass NULL instead of the lock pointer to disable reclamation. */
5957 	if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5958 	    NULL : lockp)) == NULL)
5959 		return (false);
5960 	pv->pv_va = va;
5961 	pa = pde & PG_PS_FRAME;
5962 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5963 	pvh = pa_to_pvh(pa);
5964 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5965 	pvh->pv_gen++;
5966 	return (true);
5967 }
5968 
5969 /*
5970  * Fills a page table page with mappings to consecutive physical pages.
5971  */
5972 static void
pmap_fill_ptp(pt_entry_t * firstpte,pt_entry_t newpte)5973 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5974 {
5975 	pt_entry_t *pte;
5976 
5977 	for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5978 		*pte = newpte;
5979 		newpte += PAGE_SIZE;
5980 	}
5981 }
5982 
5983 /*
5984  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
5985  * mapping is invalidated.
5986  */
5987 static bool
pmap_demote_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va)5988 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5989 {
5990 	struct rwlock *lock;
5991 	bool rv;
5992 
5993 	lock = NULL;
5994 	rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5995 	if (lock != NULL)
5996 		rw_wunlock(lock);
5997 	return (rv);
5998 }
5999 
6000 static void
pmap_demote_pde_check(pt_entry_t * firstpte __unused,pt_entry_t newpte __unused)6001 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
6002 {
6003 #ifdef INVARIANTS
6004 #ifdef DIAGNOSTIC
6005 	pt_entry_t *xpte, *ypte;
6006 
6007 	for (xpte = firstpte; xpte < firstpte + NPTEPG;
6008 	    xpte++, newpte += PAGE_SIZE) {
6009 		if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
6010 			printf("pmap_demote_pde: xpte %zd and newpte map "
6011 			    "different pages: found %#lx, expected %#lx\n",
6012 			    xpte - firstpte, *xpte, newpte);
6013 			printf("page table dump\n");
6014 			for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
6015 				printf("%zd %#lx\n", ypte - firstpte, *ypte);
6016 			panic("firstpte");
6017 		}
6018 	}
6019 #else
6020 	KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
6021 	    ("pmap_demote_pde: firstpte and newpte map different physical"
6022 	    " addresses"));
6023 #endif
6024 #endif
6025 }
6026 
6027 static void
pmap_demote_pde_abort(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t oldpde,struct rwlock ** lockp)6028 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6029     pd_entry_t oldpde, struct rwlock **lockp)
6030 {
6031 	struct spglist free;
6032 	vm_offset_t sva;
6033 
6034 	SLIST_INIT(&free);
6035 	sva = trunc_2mpage(va);
6036 	pmap_remove_pde(pmap, pde, sva, &free, lockp);
6037 	if ((oldpde & pmap_global_bit(pmap)) == 0)
6038 		pmap_invalidate_pde_page(pmap, sva, oldpde);
6039 	vm_page_free_pages_toq(&free, true);
6040 	CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
6041 	    va, pmap);
6042 }
6043 
6044 static bool
pmap_demote_pde_locked(pmap_t pmap,pd_entry_t * pde,vm_offset_t va,struct rwlock ** lockp)6045 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
6046     struct rwlock **lockp)
6047 {
6048 	pd_entry_t newpde, oldpde;
6049 	pt_entry_t *firstpte, newpte;
6050 	pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6051 	vm_paddr_t mptepa;
6052 	vm_page_t mpte;
6053 	int PG_PTE_CACHE;
6054 	bool in_kernel;
6055 
6056 	PG_A = pmap_accessed_bit(pmap);
6057 	PG_G = pmap_global_bit(pmap);
6058 	PG_M = pmap_modified_bit(pmap);
6059 	PG_RW = pmap_rw_bit(pmap);
6060 	PG_V = pmap_valid_bit(pmap);
6061 	PG_PTE_CACHE = pmap_cache_mask(pmap, false);
6062 	PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6063 
6064 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6065 	in_kernel = va >= VM_MAXUSER_ADDRESS;
6066 	oldpde = *pde;
6067 	KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
6068 	    ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
6069 
6070 	/*
6071 	 * Invalidate the 2MB page mapping and return "failure" if the
6072 	 * mapping was never accessed.
6073 	 */
6074 	if ((oldpde & PG_A) == 0) {
6075 		KASSERT((oldpde & PG_W) == 0,
6076 		    ("pmap_demote_pde: a wired mapping is missing PG_A"));
6077 		pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6078 		return (false);
6079 	}
6080 
6081 	mpte = pmap_remove_pt_page(pmap, va);
6082 	if (mpte == NULL) {
6083 		KASSERT((oldpde & PG_W) == 0,
6084 		    ("pmap_demote_pde: page table page for a wired mapping"
6085 		    " is missing"));
6086 
6087 		/*
6088 		 * If the page table page is missing and the mapping
6089 		 * is for a kernel address, the mapping must belong to
6090 		 * the direct map.  Page table pages are preallocated
6091 		 * for every other part of the kernel address space,
6092 		 * so the direct map region is the only part of the
6093 		 * kernel address space that must be handled here.
6094 		 */
6095 		KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6096 		    va < DMAP_MAX_ADDRESS),
6097 		    ("pmap_demote_pde: No saved mpte for va %#lx", va));
6098 
6099 		/*
6100 		 * If the 2MB page mapping belongs to the direct map
6101 		 * region of the kernel's address space, then the page
6102 		 * allocation request specifies the highest possible
6103 		 * priority (VM_ALLOC_INTERRUPT).  Otherwise, the
6104 		 * priority is normal.
6105 		 */
6106 		mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6107 		    (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6108 
6109 		/*
6110 		 * If the allocation of the new page table page fails,
6111 		 * invalidate the 2MB page mapping and return "failure".
6112 		 */
6113 		if (mpte == NULL) {
6114 			pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6115 			return (false);
6116 		}
6117 
6118 		if (!in_kernel)
6119 			mpte->ref_count = NPTEPG;
6120 	}
6121 	mptepa = VM_PAGE_TO_PHYS(mpte);
6122 	firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6123 	newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6124 	KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6125 	    ("pmap_demote_pde: oldpde is missing PG_M"));
6126 	newpte = oldpde & ~PG_PS;
6127 	newpte = pmap_swap_pat(pmap, newpte);
6128 
6129 	/*
6130 	 * If the PTP is not leftover from an earlier promotion or it does not
6131 	 * have PG_A set in every PTE, then fill it.  The new PTEs will all
6132 	 * have PG_A set.
6133 	 */
6134 	if (!vm_page_all_valid(mpte))
6135 		pmap_fill_ptp(firstpte, newpte);
6136 
6137 	pmap_demote_pde_check(firstpte, newpte);
6138 
6139 	/*
6140 	 * If the mapping has changed attributes, update the PTEs.
6141 	 */
6142 	if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6143 		pmap_fill_ptp(firstpte, newpte);
6144 
6145 	/*
6146 	 * The spare PV entries must be reserved prior to demoting the
6147 	 * mapping, that is, prior to changing the PDE.  Otherwise, the state
6148 	 * of the PDE and the PV lists will be inconsistent, which can result
6149 	 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6150 	 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6151 	 * PV entry for the 2MB page mapping that is being demoted.
6152 	 */
6153 	if ((oldpde & PG_MANAGED) != 0)
6154 		reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6155 
6156 	/*
6157 	 * Demote the mapping.  This pmap is locked.  The old PDE has
6158 	 * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
6159 	 * set.  Thus, there is no danger of a race with another
6160 	 * processor changing the setting of PG_A and/or PG_M between
6161 	 * the read above and the store below.
6162 	 */
6163 	if (workaround_erratum383)
6164 		pmap_update_pde(pmap, va, pde, newpde);
6165 	else
6166 		pde_store(pde, newpde);
6167 
6168 	/*
6169 	 * Invalidate a stale recursive mapping of the page table page.
6170 	 */
6171 	if (in_kernel)
6172 		pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6173 
6174 	/*
6175 	 * Demote the PV entry.
6176 	 */
6177 	if ((oldpde & PG_MANAGED) != 0)
6178 		pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6179 
6180 	counter_u64_add(pmap_pde_demotions, 1);
6181 	CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6182 	    va, pmap);
6183 	return (true);
6184 }
6185 
6186 /*
6187  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6188  */
6189 static void
pmap_remove_kernel_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va)6190 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6191 {
6192 	pd_entry_t newpde;
6193 	vm_paddr_t mptepa;
6194 	vm_page_t mpte;
6195 
6196 	KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6197 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6198 	mpte = pmap_remove_pt_page(pmap, va);
6199 	if (mpte == NULL)
6200 		panic("pmap_remove_kernel_pde: Missing pt page.");
6201 
6202 	mptepa = VM_PAGE_TO_PHYS(mpte);
6203 	newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6204 
6205 	/*
6206 	 * If this page table page was unmapped by a promotion, then it
6207 	 * contains valid mappings.  Zero it to invalidate those mappings.
6208 	 */
6209 	if (vm_page_any_valid(mpte))
6210 		pagezero((void *)PHYS_TO_DMAP(mptepa));
6211 
6212 	/*
6213 	 * Demote the mapping.
6214 	 */
6215 	if (workaround_erratum383)
6216 		pmap_update_pde(pmap, va, pde, newpde);
6217 	else
6218 		pde_store(pde, newpde);
6219 
6220 	/*
6221 	 * Invalidate a stale recursive mapping of the page table page.
6222 	 */
6223 	pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6224 }
6225 
6226 /*
6227  * pmap_remove_pde: do the things to unmap a superpage in a process
6228  */
6229 static int
pmap_remove_pde(pmap_t pmap,pd_entry_t * pdq,vm_offset_t sva,struct spglist * free,struct rwlock ** lockp)6230 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6231     struct spglist *free, struct rwlock **lockp)
6232 {
6233 	struct md_page *pvh;
6234 	pd_entry_t oldpde;
6235 	vm_offset_t eva, va;
6236 	vm_page_t m, mpte;
6237 	pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6238 
6239 	PG_G = pmap_global_bit(pmap);
6240 	PG_A = pmap_accessed_bit(pmap);
6241 	PG_M = pmap_modified_bit(pmap);
6242 	PG_RW = pmap_rw_bit(pmap);
6243 
6244 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6245 	KASSERT((sva & PDRMASK) == 0,
6246 	    ("pmap_remove_pde: sva is not 2mpage aligned"));
6247 	oldpde = pte_load_clear(pdq);
6248 	if (oldpde & PG_W)
6249 		pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6250 	if ((oldpde & PG_G) != 0)
6251 		pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6252 	pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6253 	if (oldpde & PG_MANAGED) {
6254 		CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6255 		pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6256 		pmap_pvh_free(pvh, pmap, sva);
6257 		eva = sva + NBPDR;
6258 		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6259 		    va < eva; va += PAGE_SIZE, m++) {
6260 			if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6261 				vm_page_dirty(m);
6262 			if (oldpde & PG_A)
6263 				vm_page_aflag_set(m, PGA_REFERENCED);
6264 			if (TAILQ_EMPTY(&m->md.pv_list) &&
6265 			    TAILQ_EMPTY(&pvh->pv_list))
6266 				vm_page_aflag_clear(m, PGA_WRITEABLE);
6267 			pmap_delayed_invl_page(m);
6268 		}
6269 	}
6270 	if (pmap == kernel_pmap) {
6271 		pmap_remove_kernel_pde(pmap, pdq, sva);
6272 	} else {
6273 		mpte = pmap_remove_pt_page(pmap, sva);
6274 		if (mpte != NULL) {
6275 			KASSERT(vm_page_any_valid(mpte),
6276 			    ("pmap_remove_pde: pte page not promoted"));
6277 			pmap_pt_page_count_adj(pmap, -1);
6278 			KASSERT(mpte->ref_count == NPTEPG,
6279 			    ("pmap_remove_pde: pte page ref count error"));
6280 			mpte->ref_count = 0;
6281 			pmap_add_delayed_free_list(mpte, free, false);
6282 		}
6283 	}
6284 	return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6285 }
6286 
6287 /*
6288  * pmap_remove_pte: do the things to unmap a page in a process
6289  */
6290 static int
pmap_remove_pte(pmap_t pmap,pt_entry_t * ptq,vm_offset_t va,pd_entry_t ptepde,struct spglist * free,struct rwlock ** lockp)6291 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6292     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6293 {
6294 	struct md_page *pvh;
6295 	pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6296 	vm_page_t m;
6297 
6298 	PG_A = pmap_accessed_bit(pmap);
6299 	PG_M = pmap_modified_bit(pmap);
6300 	PG_RW = pmap_rw_bit(pmap);
6301 
6302 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6303 	oldpte = pte_load_clear(ptq);
6304 	if (oldpte & PG_W)
6305 		pmap->pm_stats.wired_count -= 1;
6306 	pmap_resident_count_adj(pmap, -1);
6307 	if (oldpte & PG_MANAGED) {
6308 		m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6309 		if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6310 			vm_page_dirty(m);
6311 		if (oldpte & PG_A)
6312 			vm_page_aflag_set(m, PGA_REFERENCED);
6313 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6314 		pmap_pvh_free(&m->md, pmap, va);
6315 		if (TAILQ_EMPTY(&m->md.pv_list) &&
6316 		    (m->flags & PG_FICTITIOUS) == 0) {
6317 			pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6318 			if (TAILQ_EMPTY(&pvh->pv_list))
6319 				vm_page_aflag_clear(m, PGA_WRITEABLE);
6320 		}
6321 		pmap_delayed_invl_page(m);
6322 	}
6323 	return (pmap_unuse_pt(pmap, va, ptepde, free));
6324 }
6325 
6326 /*
6327  * Remove a single page from a process address space
6328  */
6329 static void
pmap_remove_page(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,struct spglist * free)6330 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6331     struct spglist *free)
6332 {
6333 	struct rwlock *lock;
6334 	pt_entry_t *pte, PG_V;
6335 
6336 	PG_V = pmap_valid_bit(pmap);
6337 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6338 	if ((*pde & PG_V) == 0)
6339 		return;
6340 	pte = pmap_pde_to_pte(pde, va);
6341 	if ((*pte & PG_V) == 0)
6342 		return;
6343 	lock = NULL;
6344 	pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6345 	if (lock != NULL)
6346 		rw_wunlock(lock);
6347 	pmap_invalidate_page(pmap, va);
6348 }
6349 
6350 /*
6351  * Removes the specified range of addresses from the page table page.
6352  */
6353 static bool
pmap_remove_ptes(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pd_entry_t * pde,struct spglist * free,struct rwlock ** lockp)6354 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6355     pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6356 {
6357 	pt_entry_t PG_G, *pte;
6358 	vm_offset_t va;
6359 	bool anyvalid;
6360 
6361 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6362 	PG_G = pmap_global_bit(pmap);
6363 	anyvalid = false;
6364 	va = eva;
6365 	for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6366 	    sva += PAGE_SIZE) {
6367 		if (*pte == 0) {
6368 			if (va != eva) {
6369 				pmap_invalidate_range(pmap, va, sva);
6370 				va = eva;
6371 			}
6372 			continue;
6373 		}
6374 		if ((*pte & PG_G) == 0)
6375 			anyvalid = true;
6376 		else if (va == eva)
6377 			va = sva;
6378 		if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6379 			sva += PAGE_SIZE;
6380 			break;
6381 		}
6382 	}
6383 	if (va != eva)
6384 		pmap_invalidate_range(pmap, va, sva);
6385 	return (anyvalid);
6386 }
6387 
6388 static void
pmap_remove1(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool map_delete)6389 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6390 {
6391 	struct rwlock *lock;
6392 	vm_page_t mt;
6393 	vm_offset_t va_next;
6394 	pml5_entry_t *pml5e;
6395 	pml4_entry_t *pml4e;
6396 	pdp_entry_t *pdpe;
6397 	pd_entry_t ptpaddr, *pde;
6398 	pt_entry_t PG_G, PG_V;
6399 	struct spglist free;
6400 	int anyvalid;
6401 
6402 	PG_G = pmap_global_bit(pmap);
6403 	PG_V = pmap_valid_bit(pmap);
6404 
6405 	/*
6406 	 * If there are no resident pages besides the top level page
6407 	 * table page(s), there is nothing to do.  Kernel pmap always
6408 	 * accounts whole preloaded area as resident, which makes its
6409 	 * resident count > 2.
6410 	 * Perform an unsynchronized read.  This is, however, safe.
6411 	 */
6412 	if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6413 	    1 : 0))
6414 		return;
6415 
6416 	anyvalid = 0;
6417 	SLIST_INIT(&free);
6418 
6419 	pmap_delayed_invl_start();
6420 	PMAP_LOCK(pmap);
6421 	if (map_delete)
6422 		pmap_pkru_on_remove(pmap, sva, eva);
6423 
6424 	/*
6425 	 * special handling of removing one page.  a very
6426 	 * common operation and easy to short circuit some
6427 	 * code.
6428 	 */
6429 	if (sva + PAGE_SIZE == eva) {
6430 		pde = pmap_pde(pmap, sva);
6431 		if (pde && (*pde & PG_PS) == 0) {
6432 			pmap_remove_page(pmap, sva, pde, &free);
6433 			goto out;
6434 		}
6435 	}
6436 
6437 	lock = NULL;
6438 	for (; sva < eva; sva = va_next) {
6439 		if (pmap->pm_stats.resident_count == 0)
6440 			break;
6441 
6442 		if (pmap_is_la57(pmap)) {
6443 			pml5e = pmap_pml5e(pmap, sva);
6444 			if ((*pml5e & PG_V) == 0) {
6445 				va_next = (sva + NBPML5) & ~PML5MASK;
6446 				if (va_next < sva)
6447 					va_next = eva;
6448 				continue;
6449 			}
6450 			pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6451 		} else {
6452 			pml4e = pmap_pml4e(pmap, sva);
6453 		}
6454 		if ((*pml4e & PG_V) == 0) {
6455 			va_next = (sva + NBPML4) & ~PML4MASK;
6456 			if (va_next < sva)
6457 				va_next = eva;
6458 			continue;
6459 		}
6460 
6461 		va_next = (sva + NBPDP) & ~PDPMASK;
6462 		if (va_next < sva)
6463 			va_next = eva;
6464 		pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6465 		if ((*pdpe & PG_V) == 0)
6466 			continue;
6467 		if ((*pdpe & PG_PS) != 0) {
6468 			KASSERT(va_next <= eva,
6469 			    ("partial update of non-transparent 1G mapping "
6470 			    "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6471 			    *pdpe, sva, eva, va_next));
6472 			MPASS(pmap != kernel_pmap); /* XXXKIB */
6473 			MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6474 			anyvalid = 1;
6475 			*pdpe = 0;
6476 			pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6477 			mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6478 			pmap_unwire_ptp(pmap, sva, mt, &free);
6479 			continue;
6480 		}
6481 
6482 		/*
6483 		 * Calculate index for next page table.
6484 		 */
6485 		va_next = (sva + NBPDR) & ~PDRMASK;
6486 		if (va_next < sva)
6487 			va_next = eva;
6488 
6489 		pde = pmap_pdpe_to_pde(pdpe, sva);
6490 		ptpaddr = *pde;
6491 
6492 		/*
6493 		 * Weed out invalid mappings.
6494 		 */
6495 		if (ptpaddr == 0)
6496 			continue;
6497 
6498 		/*
6499 		 * Check for large page.
6500 		 */
6501 		if ((ptpaddr & PG_PS) != 0) {
6502 			/*
6503 			 * Are we removing the entire large page?  If not,
6504 			 * demote the mapping and fall through.
6505 			 */
6506 			if (sva + NBPDR == va_next && eva >= va_next) {
6507 				/*
6508 				 * The TLB entry for a PG_G mapping is
6509 				 * invalidated by pmap_remove_pde().
6510 				 */
6511 				if ((ptpaddr & PG_G) == 0)
6512 					anyvalid = 1;
6513 				pmap_remove_pde(pmap, pde, sva, &free, &lock);
6514 				continue;
6515 			} else if (!pmap_demote_pde_locked(pmap, pde, sva,
6516 			    &lock)) {
6517 				/* The large page mapping was destroyed. */
6518 				continue;
6519 			} else
6520 				ptpaddr = *pde;
6521 		}
6522 
6523 		/*
6524 		 * Limit our scan to either the end of the va represented
6525 		 * by the current page table page, or to the end of the
6526 		 * range being removed.
6527 		 */
6528 		if (va_next > eva)
6529 			va_next = eva;
6530 
6531 		if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6532 			anyvalid = 1;
6533 	}
6534 	if (lock != NULL)
6535 		rw_wunlock(lock);
6536 out:
6537 	if (anyvalid)
6538 		pmap_invalidate_all(pmap);
6539 	PMAP_UNLOCK(pmap);
6540 	pmap_delayed_invl_finish();
6541 	vm_page_free_pages_toq(&free, true);
6542 }
6543 
6544 /*
6545  *	Remove the given range of addresses from the specified map.
6546  *
6547  *	It is assumed that the start and end are properly
6548  *	rounded to the page size.
6549  */
6550 void
pmap_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)6551 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6552 {
6553 	pmap_remove1(pmap, sva, eva, false);
6554 }
6555 
6556 /*
6557  *	Remove the given range of addresses as part of a logical unmap
6558  *	operation. This has the effect of calling pmap_remove(), but
6559  *	also clears any metadata that should persist for the lifetime
6560  *	of a logical mapping.
6561  */
6562 void
pmap_map_delete(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)6563 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6564 {
6565 	pmap_remove1(pmap, sva, eva, true);
6566 }
6567 
6568 /*
6569  *	Routine:	pmap_remove_all
6570  *	Function:
6571  *		Removes this physical page from
6572  *		all physical maps in which it resides.
6573  *		Reflects back modify bits to the pager.
6574  *
6575  *	Notes:
6576  *		Original versions of this routine were very
6577  *		inefficient because they iteratively called
6578  *		pmap_remove (slow...)
6579  */
6580 
6581 void
pmap_remove_all(vm_page_t m)6582 pmap_remove_all(vm_page_t m)
6583 {
6584 	struct md_page *pvh;
6585 	pv_entry_t pv;
6586 	pmap_t pmap;
6587 	struct rwlock *lock;
6588 	pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6589 	pd_entry_t *pde;
6590 	vm_offset_t va;
6591 	struct spglist free;
6592 	int pvh_gen, md_gen;
6593 
6594 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6595 	    ("pmap_remove_all: page %p is not managed", m));
6596 	SLIST_INIT(&free);
6597 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6598 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6599 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
6600 	rw_wlock(lock);
6601 retry:
6602 	while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6603 		pmap = PV_PMAP(pv);
6604 		if (!PMAP_TRYLOCK(pmap)) {
6605 			pvh_gen = pvh->pv_gen;
6606 			rw_wunlock(lock);
6607 			PMAP_LOCK(pmap);
6608 			rw_wlock(lock);
6609 			if (pvh_gen != pvh->pv_gen) {
6610 				PMAP_UNLOCK(pmap);
6611 				goto retry;
6612 			}
6613 		}
6614 		va = pv->pv_va;
6615 		pde = pmap_pde(pmap, va);
6616 		(void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6617 		PMAP_UNLOCK(pmap);
6618 	}
6619 	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6620 		pmap = PV_PMAP(pv);
6621 		if (!PMAP_TRYLOCK(pmap)) {
6622 			pvh_gen = pvh->pv_gen;
6623 			md_gen = m->md.pv_gen;
6624 			rw_wunlock(lock);
6625 			PMAP_LOCK(pmap);
6626 			rw_wlock(lock);
6627 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6628 				PMAP_UNLOCK(pmap);
6629 				goto retry;
6630 			}
6631 		}
6632 		PG_A = pmap_accessed_bit(pmap);
6633 		PG_M = pmap_modified_bit(pmap);
6634 		PG_RW = pmap_rw_bit(pmap);
6635 		pmap_resident_count_adj(pmap, -1);
6636 		pde = pmap_pde(pmap, pv->pv_va);
6637 		KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6638 		    " a 2mpage in page %p's pv list", m));
6639 		pte = pmap_pde_to_pte(pde, pv->pv_va);
6640 		tpte = pte_load_clear(pte);
6641 		if (tpte & PG_W)
6642 			pmap->pm_stats.wired_count--;
6643 		if (tpte & PG_A)
6644 			vm_page_aflag_set(m, PGA_REFERENCED);
6645 
6646 		/*
6647 		 * Update the vm_page_t clean and reference bits.
6648 		 */
6649 		if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6650 			vm_page_dirty(m);
6651 		pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6652 		pmap_invalidate_page(pmap, pv->pv_va);
6653 		TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6654 		m->md.pv_gen++;
6655 		free_pv_entry(pmap, pv);
6656 		PMAP_UNLOCK(pmap);
6657 	}
6658 	vm_page_aflag_clear(m, PGA_WRITEABLE);
6659 	rw_wunlock(lock);
6660 	pmap_delayed_invl_wait(m);
6661 	vm_page_free_pages_toq(&free, true);
6662 }
6663 
6664 /*
6665  * pmap_protect_pde: do the things to protect a 2mpage in a process
6666  */
6667 static bool
pmap_protect_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t sva,vm_prot_t prot)6668 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6669 {
6670 	pd_entry_t newpde, oldpde;
6671 	vm_page_t m, mt;
6672 	bool anychanged;
6673 	pt_entry_t PG_G, PG_M, PG_RW;
6674 
6675 	PG_G = pmap_global_bit(pmap);
6676 	PG_M = pmap_modified_bit(pmap);
6677 	PG_RW = pmap_rw_bit(pmap);
6678 
6679 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6680 	KASSERT((sva & PDRMASK) == 0,
6681 	    ("pmap_protect_pde: sva is not 2mpage aligned"));
6682 	anychanged = false;
6683 retry:
6684 	oldpde = newpde = *pde;
6685 	if ((prot & VM_PROT_WRITE) == 0) {
6686 		if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6687 		    (PG_MANAGED | PG_M | PG_RW)) {
6688 			m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6689 			for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6690 				vm_page_dirty(mt);
6691 		}
6692 		newpde &= ~(PG_RW | PG_M);
6693 	}
6694 	if ((prot & VM_PROT_EXECUTE) == 0)
6695 		newpde |= pg_nx;
6696 	if (newpde != oldpde) {
6697 		/*
6698 		 * As an optimization to future operations on this PDE, clear
6699 		 * PG_PROMOTED.  The impending invalidation will remove any
6700 		 * lingering 4KB page mappings from the TLB.
6701 		 */
6702 		if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6703 			goto retry;
6704 		if ((oldpde & PG_G) != 0)
6705 			pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6706 		else
6707 			anychanged = true;
6708 	}
6709 	return (anychanged);
6710 }
6711 
6712 /*
6713  *	Set the physical protection on the
6714  *	specified range of this map as requested.
6715  */
6716 void
pmap_protect(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,vm_prot_t prot)6717 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6718 {
6719 	vm_page_t m;
6720 	vm_offset_t va_next;
6721 	pml4_entry_t *pml4e;
6722 	pdp_entry_t *pdpe;
6723 	pd_entry_t ptpaddr, *pde;
6724 	pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6725 	pt_entry_t obits, pbits;
6726 	bool anychanged;
6727 
6728 	KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6729 	if (prot == VM_PROT_NONE) {
6730 		pmap_remove(pmap, sva, eva);
6731 		return;
6732 	}
6733 
6734 	if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6735 	    (VM_PROT_WRITE|VM_PROT_EXECUTE))
6736 		return;
6737 
6738 	PG_G = pmap_global_bit(pmap);
6739 	PG_M = pmap_modified_bit(pmap);
6740 	PG_V = pmap_valid_bit(pmap);
6741 	PG_RW = pmap_rw_bit(pmap);
6742 	anychanged = false;
6743 
6744 	/*
6745 	 * Although this function delays and batches the invalidation
6746 	 * of stale TLB entries, it does not need to call
6747 	 * pmap_delayed_invl_start() and
6748 	 * pmap_delayed_invl_finish(), because it does not
6749 	 * ordinarily destroy mappings.  Stale TLB entries from
6750 	 * protection-only changes need only be invalidated before the
6751 	 * pmap lock is released, because protection-only changes do
6752 	 * not destroy PV entries.  Even operations that iterate over
6753 	 * a physical page's PV list of mappings, like
6754 	 * pmap_remove_write(), acquire the pmap lock for each
6755 	 * mapping.  Consequently, for protection-only changes, the
6756 	 * pmap lock suffices to synchronize both page table and TLB
6757 	 * updates.
6758 	 *
6759 	 * This function only destroys a mapping if pmap_demote_pde()
6760 	 * fails.  In that case, stale TLB entries are immediately
6761 	 * invalidated.
6762 	 */
6763 
6764 	PMAP_LOCK(pmap);
6765 	for (; sva < eva; sva = va_next) {
6766 		pml4e = pmap_pml4e(pmap, sva);
6767 		if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6768 			va_next = (sva + NBPML4) & ~PML4MASK;
6769 			if (va_next < sva)
6770 				va_next = eva;
6771 			continue;
6772 		}
6773 
6774 		va_next = (sva + NBPDP) & ~PDPMASK;
6775 		if (va_next < sva)
6776 			va_next = eva;
6777 		pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6778 		if ((*pdpe & PG_V) == 0)
6779 			continue;
6780 		if ((*pdpe & PG_PS) != 0) {
6781 			KASSERT(va_next <= eva,
6782 			    ("partial update of non-transparent 1G mapping "
6783 			    "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6784 			    *pdpe, sva, eva, va_next));
6785 retry_pdpe:
6786 			obits = pbits = *pdpe;
6787 			MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6788 			MPASS(pmap != kernel_pmap); /* XXXKIB */
6789 			if ((prot & VM_PROT_WRITE) == 0)
6790 				pbits &= ~(PG_RW | PG_M);
6791 			if ((prot & VM_PROT_EXECUTE) == 0)
6792 				pbits |= pg_nx;
6793 
6794 			if (pbits != obits) {
6795 				if (!atomic_cmpset_long(pdpe, obits, pbits))
6796 					/* PG_PS cannot be cleared under us, */
6797 					goto retry_pdpe;
6798 				anychanged = true;
6799 			}
6800 			continue;
6801 		}
6802 
6803 		va_next = (sva + NBPDR) & ~PDRMASK;
6804 		if (va_next < sva)
6805 			va_next = eva;
6806 
6807 		pde = pmap_pdpe_to_pde(pdpe, sva);
6808 		ptpaddr = *pde;
6809 
6810 		/*
6811 		 * Weed out invalid mappings.
6812 		 */
6813 		if (ptpaddr == 0)
6814 			continue;
6815 
6816 		/*
6817 		 * Check for large page.
6818 		 */
6819 		if ((ptpaddr & PG_PS) != 0) {
6820 			/*
6821 			 * Are we protecting the entire large page?
6822 			 */
6823 			if (sva + NBPDR == va_next && eva >= va_next) {
6824 				/*
6825 				 * The TLB entry for a PG_G mapping is
6826 				 * invalidated by pmap_protect_pde().
6827 				 */
6828 				if (pmap_protect_pde(pmap, pde, sva, prot))
6829 					anychanged = true;
6830 				continue;
6831 			}
6832 
6833 			/*
6834 			 * Does the large page mapping need to change?  If so,
6835 			 * demote it and fall through.
6836 			 */
6837 			pbits = ptpaddr;
6838 			if ((prot & VM_PROT_WRITE) == 0)
6839 				pbits &= ~(PG_RW | PG_M);
6840 			if ((prot & VM_PROT_EXECUTE) == 0)
6841 				pbits |= pg_nx;
6842 			if (ptpaddr == pbits || !pmap_demote_pde(pmap, pde,
6843 			    sva)) {
6844 				/*
6845 				 * Either the large page mapping doesn't need
6846 				 * to change, or it was destroyed during
6847 				 * demotion.
6848 				 */
6849 				continue;
6850 			}
6851 		}
6852 
6853 		if (va_next > eva)
6854 			va_next = eva;
6855 
6856 		for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6857 		    sva += PAGE_SIZE) {
6858 retry:
6859 			obits = pbits = *pte;
6860 			if ((pbits & PG_V) == 0)
6861 				continue;
6862 
6863 			if ((prot & VM_PROT_WRITE) == 0) {
6864 				if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6865 				    (PG_MANAGED | PG_M | PG_RW)) {
6866 					m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6867 					vm_page_dirty(m);
6868 				}
6869 				pbits &= ~(PG_RW | PG_M);
6870 			}
6871 			if ((prot & VM_PROT_EXECUTE) == 0)
6872 				pbits |= pg_nx;
6873 
6874 			if (pbits != obits) {
6875 				if (!atomic_cmpset_long(pte, obits, pbits))
6876 					goto retry;
6877 				if (obits & PG_G)
6878 					pmap_invalidate_page(pmap, sva);
6879 				else
6880 					anychanged = true;
6881 			}
6882 		}
6883 	}
6884 	if (anychanged)
6885 		pmap_invalidate_all(pmap);
6886 	PMAP_UNLOCK(pmap);
6887 }
6888 
6889 static bool
pmap_pde_ept_executable(pmap_t pmap,pd_entry_t pde)6890 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6891 {
6892 
6893 	if (pmap->pm_type != PT_EPT)
6894 		return (false);
6895 	return ((pde & EPT_PG_EXECUTE) != 0);
6896 }
6897 
6898 #if VM_NRESERVLEVEL > 0
6899 /*
6900  * Tries to promote the 512, contiguous 4KB page mappings that are within a
6901  * single page table page (PTP) to a single 2MB page mapping.  For promotion
6902  * to occur, two conditions must be met: (1) the 4KB page mappings must map
6903  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6904  * identical characteristics.
6905  */
6906 static bool
pmap_promote_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va,vm_page_t mpte,struct rwlock ** lockp)6907 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6908     struct rwlock **lockp)
6909 {
6910 	pd_entry_t newpde;
6911 	pt_entry_t *firstpte, oldpte, pa, *pte;
6912 	pt_entry_t allpte_PG_A, PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6913 	int PG_PTE_CACHE;
6914 
6915 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6916 	if (!pmap_ps_enabled(pmap))
6917 		return (false);
6918 
6919 	PG_A = pmap_accessed_bit(pmap);
6920 	PG_G = pmap_global_bit(pmap);
6921 	PG_M = pmap_modified_bit(pmap);
6922 	PG_V = pmap_valid_bit(pmap);
6923 	PG_RW = pmap_rw_bit(pmap);
6924 	PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6925 	PG_PTE_CACHE = pmap_cache_mask(pmap, false);
6926 
6927 	/*
6928 	 * Examine the first PTE in the specified PTP.  Abort if this PTE is
6929 	 * ineligible for promotion due to hardware errata, invalid, or does
6930 	 * not map the first 4KB physical page within a 2MB page.
6931 	 */
6932 	firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6933 	newpde = *firstpte;
6934 	if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6935 		return (false);
6936 	if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6937 		counter_u64_add(pmap_pde_p_failures, 1);
6938 		CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6939 		    " in pmap %p", va, pmap);
6940 		return (false);
6941 	}
6942 
6943 	/*
6944 	 * Both here and in the below "for" loop, to allow for repromotion
6945 	 * after MADV_FREE, conditionally write protect a clean PTE before
6946 	 * possibly aborting the promotion due to other PTE attributes.  Why?
6947 	 * Suppose that MADV_FREE is applied to a part of a superpage, the
6948 	 * address range [S, E).  pmap_advise() will demote the superpage
6949 	 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6950 	 * clear PG_M and PG_A in the PTEs for the rest of [S, E).  Later,
6951 	 * imagine that the memory in [S, E) is recycled, but the last 4KB
6952 	 * page in [S, E) is not the last to be rewritten, or simply accessed.
6953 	 * In other words, there is still a 4KB page in [S, E), call it P,
6954 	 * that is writeable but PG_M and PG_A are clear in P's PTE.  Unless
6955 	 * we write protect P before aborting the promotion, if and when P is
6956 	 * finally rewritten, there won't be a page fault to trigger
6957 	 * repromotion.
6958 	 */
6959 setpde:
6960 	if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6961 		/*
6962 		 * When PG_M is already clear, PG_RW can be cleared without
6963 		 * a TLB invalidation.
6964 		 */
6965 		if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6966 			goto setpde;
6967 		newpde &= ~PG_RW;
6968 		CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6969 		    " in pmap %p", va & ~PDRMASK, pmap);
6970 	}
6971 
6972 	/*
6973 	 * Examine each of the other PTEs in the specified PTP.  Abort if this
6974 	 * PTE maps an unexpected 4KB physical page or does not have identical
6975 	 * characteristics to the first PTE.
6976 	 */
6977 	allpte_PG_A = newpde & PG_A;
6978 	pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6979 	for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6980 		oldpte = *pte;
6981 		if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6982 			counter_u64_add(pmap_pde_p_failures, 1);
6983 			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6984 			    " in pmap %p", va, pmap);
6985 			return (false);
6986 		}
6987 setpte:
6988 		if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6989 			/*
6990 			 * When PG_M is already clear, PG_RW can be cleared
6991 			 * without a TLB invalidation.
6992 			 */
6993 			if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6994 				goto setpte;
6995 			oldpte &= ~PG_RW;
6996 			CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6997 			    " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6998 			    (va & ~PDRMASK), pmap);
6999 		}
7000 		if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
7001 			counter_u64_add(pmap_pde_p_failures, 1);
7002 			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
7003 			    " in pmap %p", va, pmap);
7004 			return (false);
7005 		}
7006 		allpte_PG_A &= oldpte;
7007 		pa -= PAGE_SIZE;
7008 	}
7009 
7010 	/*
7011 	 * Unless all PTEs have PG_A set, clear it from the superpage mapping,
7012 	 * so that promotions triggered by speculative mappings, such as
7013 	 * pmap_enter_quick(), don't automatically mark the underlying pages
7014 	 * as referenced.
7015 	 */
7016 	newpde &= ~PG_A | allpte_PG_A;
7017 
7018 	/*
7019 	 * EPT PTEs with PG_M set and PG_A clear are not supported by early
7020 	 * MMUs supporting EPT.
7021 	 */
7022 	KASSERT((newpde & PG_A) != 0 || safe_to_clear_referenced(pmap, newpde),
7023 	    ("unsupported EPT PTE"));
7024 
7025 	/*
7026 	 * Save the PTP in its current state until the PDE mapping the
7027 	 * superpage is demoted by pmap_demote_pde() or destroyed by
7028 	 * pmap_remove_pde().  If PG_A is not set in every PTE, then request
7029 	 * that the PTP be refilled on demotion.
7030 	 */
7031 	if (mpte == NULL)
7032 		mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7033 	KASSERT(mpte >= vm_page_array &&
7034 	    mpte < &vm_page_array[vm_page_array_size],
7035 	    ("pmap_promote_pde: page table page is out of range"));
7036 	KASSERT(mpte->pindex == pmap_pde_pindex(va),
7037 	    ("pmap_promote_pde: page table page's pindex is wrong "
7038 	    "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
7039 	    mpte, mpte->pindex, va, pmap_pde_pindex(va)));
7040 	if (pmap_insert_pt_page(pmap, mpte, true, allpte_PG_A != 0)) {
7041 		counter_u64_add(pmap_pde_p_failures, 1);
7042 		CTR2(KTR_PMAP,
7043 		    "pmap_promote_pde: failure for va %#lx in pmap %p", va,
7044 		    pmap);
7045 		return (false);
7046 	}
7047 
7048 	/*
7049 	 * Promote the pv entries.
7050 	 */
7051 	if ((newpde & PG_MANAGED) != 0)
7052 		pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
7053 
7054 	/*
7055 	 * Propagate the PAT index to its proper position.
7056 	 */
7057 	newpde = pmap_swap_pat(pmap, newpde);
7058 
7059 	/*
7060 	 * Map the superpage.
7061 	 */
7062 	if (workaround_erratum383)
7063 		pmap_update_pde(pmap, va, pde, PG_PS | newpde);
7064 	else
7065 		pde_store(pde, PG_PROMOTED | PG_PS | newpde);
7066 
7067 	counter_u64_add(pmap_pde_promotions, 1);
7068 	CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
7069 	    " in pmap %p", va, pmap);
7070 	return (true);
7071 }
7072 #endif /* VM_NRESERVLEVEL > 0 */
7073 
7074 static int
pmap_enter_largepage(pmap_t pmap,vm_offset_t va,pt_entry_t newpte,int flags,int psind)7075 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
7076     int psind)
7077 {
7078 	vm_page_t mp;
7079 	pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
7080 
7081 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7082 	KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
7083 	    ("psind %d unexpected", psind));
7084 	KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
7085 	    ("unaligned phys address %#lx newpte %#lx psind %d",
7086 	    newpte & PG_FRAME, newpte, psind));
7087 	KASSERT((va & (pagesizes[psind] - 1)) == 0,
7088 	    ("unaligned va %#lx psind %d", va, psind));
7089 	KASSERT(va < VM_MAXUSER_ADDRESS,
7090 	    ("kernel mode non-transparent superpage")); /* XXXKIB */
7091 	KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
7092 	    ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
7093 
7094 	PG_V = pmap_valid_bit(pmap);
7095 
7096 restart:
7097 	pten = newpte;
7098 	if (!pmap_pkru_same(pmap, va, va + pagesizes[psind], &pten))
7099 		return (KERN_PROTECTION_FAILURE);
7100 
7101 	if (psind == 2) {	/* 1G */
7102 		pml4e = pmap_pml4e(pmap, va);
7103 		if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7104 			mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7105 			    NULL, va);
7106 			if (mp == NULL)
7107 				goto allocf;
7108 			pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7109 			pdpe = &pdpe[pmap_pdpe_index(va)];
7110 			origpte = *pdpe;
7111 			MPASS(origpte == 0);
7112 		} else {
7113 			pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7114 			KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7115 			origpte = *pdpe;
7116 			if ((origpte & PG_V) == 0) {
7117 				mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7118 				mp->ref_count++;
7119 			}
7120 		}
7121 		*pdpe = pten;
7122 	} else /* (psind == 1) */ {	/* 2M */
7123 		pde = pmap_pde(pmap, va);
7124 		if (pde == NULL) {
7125 			mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7126 			    NULL, va);
7127 			if (mp == NULL)
7128 				goto allocf;
7129 			pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7130 			pde = &pde[pmap_pde_index(va)];
7131 			origpte = *pde;
7132 			MPASS(origpte == 0);
7133 		} else {
7134 			origpte = *pde;
7135 			if ((origpte & PG_V) == 0) {
7136 				pdpe = pmap_pdpe(pmap, va);
7137 				MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7138 				mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7139 				mp->ref_count++;
7140 			}
7141 		}
7142 		*pde = pten;
7143 	}
7144 	KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7145 	    (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7146 	    ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7147 	    va, psind == 2 ? "1G" : "2M", origpte, pten));
7148 	if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7149 		pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7150 	else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7151 		pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7152 	if ((origpte & PG_V) == 0)
7153 		pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7154 
7155 	return (KERN_SUCCESS);
7156 
7157 allocf:
7158 	if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7159 		return (KERN_RESOURCE_SHORTAGE);
7160 	PMAP_UNLOCK(pmap);
7161 	vm_wait(NULL);
7162 	PMAP_LOCK(pmap);
7163 	goto restart;
7164 }
7165 
7166 /*
7167  *	Insert the given physical page (p) at
7168  *	the specified virtual address (v) in the
7169  *	target physical map with the protection requested.
7170  *
7171  *	If specified, the page will be wired down, meaning
7172  *	that the related pte can not be reclaimed.
7173  *
7174  *	NB:  This is the only routine which MAY NOT lazy-evaluate
7175  *	or lose information.  That is, this routine must actually
7176  *	insert this page into the given map NOW.
7177  *
7178  *	When destroying both a page table and PV entry, this function
7179  *	performs the TLB invalidation before releasing the PV list
7180  *	lock, so we do not need pmap_delayed_invl_page() calls here.
7181  */
7182 int
pmap_enter(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,u_int flags,int8_t psind)7183 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7184     u_int flags, int8_t psind)
7185 {
7186 	struct rwlock *lock;
7187 	pd_entry_t *pde;
7188 	pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7189 	pt_entry_t newpte, origpte;
7190 	pv_entry_t pv;
7191 	vm_paddr_t opa, pa;
7192 	vm_page_t mpte, om;
7193 	int rv;
7194 	bool nosleep;
7195 
7196 	PG_A = pmap_accessed_bit(pmap);
7197 	PG_G = pmap_global_bit(pmap);
7198 	PG_M = pmap_modified_bit(pmap);
7199 	PG_V = pmap_valid_bit(pmap);
7200 	PG_RW = pmap_rw_bit(pmap);
7201 
7202 	va = trunc_page(va);
7203 	KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7204 	KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7205 	    ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7206 	    va));
7207 	KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7208 	    ("pmap_enter: managed mapping within the clean submap"));
7209 	if ((m->oflags & VPO_UNMANAGED) == 0)
7210 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
7211 	KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7212 	    ("pmap_enter: flags %u has reserved bits set", flags));
7213 	pa = VM_PAGE_TO_PHYS(m);
7214 	newpte = (pt_entry_t)(pa | PG_A | PG_V);
7215 	if ((flags & VM_PROT_WRITE) != 0)
7216 		newpte |= PG_M;
7217 	if ((prot & VM_PROT_WRITE) != 0)
7218 		newpte |= PG_RW;
7219 	KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7220 	    ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7221 	if ((prot & VM_PROT_EXECUTE) == 0)
7222 		newpte |= pg_nx;
7223 	if ((flags & PMAP_ENTER_WIRED) != 0)
7224 		newpte |= PG_W;
7225 	if (va < VM_MAXUSER_ADDRESS)
7226 		newpte |= PG_U;
7227 	if (pmap == kernel_pmap)
7228 		newpte |= PG_G;
7229 	newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7230 
7231 	/*
7232 	 * Set modified bit gratuitously for writeable mappings if
7233 	 * the page is unmanaged. We do not want to take a fault
7234 	 * to do the dirty bit accounting for these mappings.
7235 	 */
7236 	if ((m->oflags & VPO_UNMANAGED) != 0) {
7237 		if ((newpte & PG_RW) != 0)
7238 			newpte |= PG_M;
7239 	} else
7240 		newpte |= PG_MANAGED;
7241 
7242 	lock = NULL;
7243 	PMAP_LOCK(pmap);
7244 	if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7245 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7246 		    ("managed largepage va %#lx flags %#x", va, flags));
7247 		rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7248 		    psind);
7249 		goto out;
7250 	}
7251 	if (psind == 1) {
7252 		/* Assert the required virtual and physical alignment. */
7253 		KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7254 		KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7255 		rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7256 		goto out;
7257 	}
7258 	mpte = NULL;
7259 
7260 	/*
7261 	 * In the case that a page table page is not
7262 	 * resident, we are creating it here.
7263 	 */
7264 retry:
7265 	pde = pmap_pde(pmap, va);
7266 	if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7267 	    pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7268 		pte = pmap_pde_to_pte(pde, va);
7269 		if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7270 			mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7271 			mpte->ref_count++;
7272 		}
7273 	} else if (va < VM_MAXUSER_ADDRESS) {
7274 		/*
7275 		 * Here if the pte page isn't mapped, or if it has been
7276 		 * deallocated.
7277 		 */
7278 		nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7279 		mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7280 		    nosleep ? NULL : &lock, va);
7281 		if (mpte == NULL && nosleep) {
7282 			rv = KERN_RESOURCE_SHORTAGE;
7283 			goto out;
7284 		}
7285 		goto retry;
7286 	} else
7287 		panic("pmap_enter: invalid page directory va=%#lx", va);
7288 
7289 	origpte = *pte;
7290 	pv = NULL;
7291 	if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7292 		newpte |= pmap_pkru_get(pmap, va);
7293 
7294 	/*
7295 	 * Is the specified virtual address already mapped?
7296 	 */
7297 	if ((origpte & PG_V) != 0) {
7298 		/*
7299 		 * Wiring change, just update stats. We don't worry about
7300 		 * wiring PT pages as they remain resident as long as there
7301 		 * are valid mappings in them. Hence, if a user page is wired,
7302 		 * the PT page will be also.
7303 		 */
7304 		if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7305 			pmap->pm_stats.wired_count++;
7306 		else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7307 			pmap->pm_stats.wired_count--;
7308 
7309 		/*
7310 		 * Remove the extra PT page reference.
7311 		 */
7312 		if (mpte != NULL) {
7313 			mpte->ref_count--;
7314 			KASSERT(mpte->ref_count > 0,
7315 			    ("pmap_enter: missing reference to page table page,"
7316 			     " va: 0x%lx", va));
7317 		}
7318 
7319 		/*
7320 		 * Has the physical page changed?
7321 		 */
7322 		opa = origpte & PG_FRAME;
7323 		if (opa == pa) {
7324 			/*
7325 			 * No, might be a protection or wiring change.
7326 			 */
7327 			if ((origpte & PG_MANAGED) != 0 &&
7328 			    (newpte & PG_RW) != 0)
7329 				vm_page_aflag_set(m, PGA_WRITEABLE);
7330 			if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7331 				goto unchanged;
7332 			goto validate;
7333 		}
7334 
7335 		/*
7336 		 * The physical page has changed.  Temporarily invalidate
7337 		 * the mapping.  This ensures that all threads sharing the
7338 		 * pmap keep a consistent view of the mapping, which is
7339 		 * necessary for the correct handling of COW faults.  It
7340 		 * also permits reuse of the old mapping's PV entry,
7341 		 * avoiding an allocation.
7342 		 *
7343 		 * For consistency, handle unmanaged mappings the same way.
7344 		 */
7345 		origpte = pte_load_clear(pte);
7346 		KASSERT((origpte & PG_FRAME) == opa,
7347 		    ("pmap_enter: unexpected pa update for %#lx", va));
7348 		if ((origpte & PG_MANAGED) != 0) {
7349 			om = PHYS_TO_VM_PAGE(opa);
7350 
7351 			/*
7352 			 * The pmap lock is sufficient to synchronize with
7353 			 * concurrent calls to pmap_page_test_mappings() and
7354 			 * pmap_ts_referenced().
7355 			 */
7356 			if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7357 				vm_page_dirty(om);
7358 			if ((origpte & PG_A) != 0) {
7359 				pmap_invalidate_page(pmap, va);
7360 				vm_page_aflag_set(om, PGA_REFERENCED);
7361 			}
7362 			CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7363 			pv = pmap_pvh_remove(&om->md, pmap, va);
7364 			KASSERT(pv != NULL,
7365 			    ("pmap_enter: no PV entry for %#lx", va));
7366 			if ((newpte & PG_MANAGED) == 0)
7367 				free_pv_entry(pmap, pv);
7368 			if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7369 			    TAILQ_EMPTY(&om->md.pv_list) &&
7370 			    ((om->flags & PG_FICTITIOUS) != 0 ||
7371 			    TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7372 				vm_page_aflag_clear(om, PGA_WRITEABLE);
7373 		} else {
7374 			/*
7375 			 * Since this mapping is unmanaged, assume that PG_A
7376 			 * is set.
7377 			 */
7378 			pmap_invalidate_page(pmap, va);
7379 		}
7380 		origpte = 0;
7381 	} else {
7382 		/*
7383 		 * Increment the counters.
7384 		 */
7385 		if ((newpte & PG_W) != 0)
7386 			pmap->pm_stats.wired_count++;
7387 		pmap_resident_count_adj(pmap, 1);
7388 	}
7389 
7390 	/*
7391 	 * Enter on the PV list if part of our managed memory.
7392 	 */
7393 	if ((newpte & PG_MANAGED) != 0) {
7394 		if (pv == NULL) {
7395 			pv = get_pv_entry(pmap, &lock);
7396 			pv->pv_va = va;
7397 		}
7398 		CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7399 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7400 		m->md.pv_gen++;
7401 		if ((newpte & PG_RW) != 0)
7402 			vm_page_aflag_set(m, PGA_WRITEABLE);
7403 	}
7404 
7405 	/*
7406 	 * Update the PTE.
7407 	 */
7408 	if ((origpte & PG_V) != 0) {
7409 validate:
7410 		origpte = pte_load_store(pte, newpte);
7411 		KASSERT((origpte & PG_FRAME) == pa,
7412 		    ("pmap_enter: unexpected pa update for %#lx", va));
7413 		if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7414 		    (PG_M | PG_RW)) {
7415 			if ((origpte & PG_MANAGED) != 0)
7416 				vm_page_dirty(m);
7417 
7418 			/*
7419 			 * Although the PTE may still have PG_RW set, TLB
7420 			 * invalidation may nonetheless be required because
7421 			 * the PTE no longer has PG_M set.
7422 			 */
7423 		} else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7424 			/*
7425 			 * This PTE change does not require TLB invalidation.
7426 			 */
7427 			goto unchanged;
7428 		}
7429 		if ((origpte & PG_A) != 0)
7430 			pmap_invalidate_page(pmap, va);
7431 	} else
7432 		pte_store(pte, newpte);
7433 
7434 unchanged:
7435 
7436 #if VM_NRESERVLEVEL > 0
7437 	/*
7438 	 * If both the page table page and the reservation are fully
7439 	 * populated, then attempt promotion.
7440 	 */
7441 	if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7442 	    (m->flags & PG_FICTITIOUS) == 0 &&
7443 	    vm_reserv_level_iffullpop(m) == 0)
7444 		(void)pmap_promote_pde(pmap, pde, va, mpte, &lock);
7445 #endif
7446 
7447 	rv = KERN_SUCCESS;
7448 out:
7449 	if (lock != NULL)
7450 		rw_wunlock(lock);
7451 	PMAP_UNLOCK(pmap);
7452 	return (rv);
7453 }
7454 
7455 /*
7456  * Tries to create a read- and/or execute-only 2MB page mapping.  Returns
7457  * KERN_SUCCESS if the mapping was created.  Otherwise, returns an error
7458  * value.  See pmap_enter_pde() for the possible error values when "no sleep",
7459  * "no replace", and "no reclaim" are specified.
7460  */
7461 static int
pmap_enter_2mpage(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,struct rwlock ** lockp)7462 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7463     struct rwlock **lockp)
7464 {
7465 	pd_entry_t newpde;
7466 	pt_entry_t PG_V;
7467 
7468 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7469 	PG_V = pmap_valid_bit(pmap);
7470 	newpde = VM_PAGE_TO_PHYS(m) |
7471 	    pmap_cache_bits(pmap, m->md.pat_mode, true) | PG_PS | PG_V;
7472 	if ((m->oflags & VPO_UNMANAGED) == 0)
7473 		newpde |= PG_MANAGED;
7474 	if ((prot & VM_PROT_EXECUTE) == 0)
7475 		newpde |= pg_nx;
7476 	if (va < VM_MAXUSER_ADDRESS)
7477 		newpde |= PG_U;
7478 	return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7479 	    PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7480 }
7481 
7482 /*
7483  * Returns true if every page table entry in the specified page table page is
7484  * zero.
7485  */
7486 static bool
pmap_every_pte_zero(vm_paddr_t pa)7487 pmap_every_pte_zero(vm_paddr_t pa)
7488 {
7489 	pt_entry_t *pt_end, *pte;
7490 
7491 	KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7492 	pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7493 	for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7494 		if (*pte != 0)
7495 			return (false);
7496 	}
7497 	return (true);
7498 }
7499 
7500 /*
7501  * Tries to create the specified 2MB page mapping.  Returns KERN_SUCCESS if
7502  * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7503  * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise.  Returns
7504  * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7505  * page mapping already exists within the 2MB virtual address range starting
7506  * at the specified virtual address or (2) the requested 2MB page mapping is
7507  * not supported due to hardware errata.  Returns KERN_NO_SPACE if
7508  * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7509  * the specified virtual address.  Returns KERN_PROTECTION_FAILURE if the PKRU
7510  * settings are not the same across the 2MB virtual address range starting at
7511  * the specified virtual address.  Returns KERN_RESOURCE_SHORTAGE if either
7512  * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7513  * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7514  * failed.
7515  *
7516  * The parameter "m" is only used when creating a managed, writeable mapping.
7517  */
7518 static int
pmap_enter_pde(pmap_t pmap,vm_offset_t va,pd_entry_t newpde,u_int flags,vm_page_t m,struct rwlock ** lockp)7519 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7520     vm_page_t m, struct rwlock **lockp)
7521 {
7522 	struct spglist free;
7523 	pd_entry_t oldpde, *pde;
7524 	pt_entry_t PG_G, PG_RW, PG_V;
7525 	vm_page_t mt, pdpg;
7526 	vm_page_t uwptpg;
7527 
7528 	PG_G = pmap_global_bit(pmap);
7529 	PG_RW = pmap_rw_bit(pmap);
7530 	KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7531 	    ("pmap_enter_pde: newpde is missing PG_M"));
7532 	PG_V = pmap_valid_bit(pmap);
7533 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7534 
7535 	if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7536 	    newpde))) {
7537 		CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7538 		    " in pmap %p", va, pmap);
7539 		return (KERN_FAILURE);
7540 	}
7541 	if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7542 	    PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7543 		CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7544 		    " in pmap %p", va, pmap);
7545 		return (KERN_RESOURCE_SHORTAGE);
7546 	}
7547 
7548 	/*
7549 	 * If pkru is not same for the whole pde range, return failure
7550 	 * and let vm_fault() cope.  Check after pde allocation, since
7551 	 * it could sleep.
7552 	 */
7553 	if (!pmap_pkru_same(pmap, va, va + NBPDR, &newpde)) {
7554 		pmap_abort_ptp(pmap, va, pdpg);
7555 		return (KERN_PROTECTION_FAILURE);
7556 	}
7557 
7558 	/*
7559 	 * If there are existing mappings, either abort or remove them.
7560 	 */
7561 	oldpde = *pde;
7562 	if ((oldpde & PG_V) != 0) {
7563 		KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7564 		    ("pmap_enter_pde: pdpg's reference count is too low"));
7565 		if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7566 			if ((oldpde & PG_PS) != 0) {
7567 				if (pdpg != NULL)
7568 					pdpg->ref_count--;
7569 				CTR2(KTR_PMAP,
7570 				    "pmap_enter_pde: no space for va %#lx"
7571 				    " in pmap %p", va, pmap);
7572 				return (KERN_NO_SPACE);
7573 			} else if (va < VM_MAXUSER_ADDRESS ||
7574 			    !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7575 				if (pdpg != NULL)
7576 					pdpg->ref_count--;
7577 				CTR2(KTR_PMAP,
7578 				    "pmap_enter_pde: failure for va %#lx"
7579 				    " in pmap %p", va, pmap);
7580 				return (KERN_FAILURE);
7581 			}
7582 		}
7583 		/* Break the existing mapping(s). */
7584 		SLIST_INIT(&free);
7585 		if ((oldpde & PG_PS) != 0) {
7586 			/*
7587 			 * The reference to the PD page that was acquired by
7588 			 * pmap_alloc_pde() ensures that it won't be freed.
7589 			 * However, if the PDE resulted from a promotion, then
7590 			 * a reserved PT page could be freed.
7591 			 */
7592 			(void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7593 			if ((oldpde & PG_G) == 0)
7594 				pmap_invalidate_pde_page(pmap, va, oldpde);
7595 		} else {
7596 			pmap_delayed_invl_start();
7597 			if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7598 			    lockp))
7599 		               pmap_invalidate_all(pmap);
7600 			pmap_delayed_invl_finish();
7601 		}
7602 		if (va < VM_MAXUSER_ADDRESS) {
7603 			vm_page_free_pages_toq(&free, true);
7604 			KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7605 			    pde));
7606 		} else {
7607 			KASSERT(SLIST_EMPTY(&free),
7608 			    ("pmap_enter_pde: freed kernel page table page"));
7609 
7610 			/*
7611 			 * Both pmap_remove_pde() and pmap_remove_ptes() will
7612 			 * leave the kernel page table page zero filled.
7613 			 */
7614 			mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7615 			if (pmap_insert_pt_page(pmap, mt, false, false))
7616 				panic("pmap_enter_pde: trie insert failed");
7617 		}
7618 	}
7619 
7620 	/*
7621 	 * Allocate leaf ptpage for wired userspace pages.
7622 	 */
7623 	uwptpg = NULL;
7624 	if ((newpde & PG_W) != 0 && pmap != kernel_pmap) {
7625 		uwptpg = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
7626 		    VM_ALLOC_WIRED);
7627 		if (uwptpg == NULL) {
7628 			pmap_abort_ptp(pmap, va, pdpg);
7629 			return (KERN_RESOURCE_SHORTAGE);
7630 		}
7631 		if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
7632 			pmap_free_pt_page(pmap, uwptpg, false);
7633 			pmap_abort_ptp(pmap, va, pdpg);
7634 			return (KERN_RESOURCE_SHORTAGE);
7635 		}
7636 
7637 		uwptpg->ref_count = NPTEPG;
7638 	}
7639 	if ((newpde & PG_MANAGED) != 0) {
7640 		/*
7641 		 * Abort this mapping if its PV entry could not be created.
7642 		 */
7643 		if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7644 			if (pdpg != NULL)
7645 				pmap_abort_ptp(pmap, va, pdpg);
7646 			if (uwptpg != NULL) {
7647 				mt = pmap_remove_pt_page(pmap, va);
7648 				KASSERT(mt == uwptpg,
7649 				    ("removed pt page %p, expected %p", mt,
7650 				    uwptpg));
7651 				uwptpg->ref_count = 1;
7652 				pmap_free_pt_page(pmap, uwptpg, false);
7653 			}
7654 			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7655 			    " in pmap %p", va, pmap);
7656 			return (KERN_RESOURCE_SHORTAGE);
7657 		}
7658 		if ((newpde & PG_RW) != 0) {
7659 			for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7660 				vm_page_aflag_set(mt, PGA_WRITEABLE);
7661 		}
7662 	}
7663 
7664 	/*
7665 	 * Increment counters.
7666 	 */
7667 	if ((newpde & PG_W) != 0)
7668 		pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7669 	pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7670 
7671 	/*
7672 	 * Map the superpage.  (This is not a promoted mapping; there will not
7673 	 * be any lingering 4KB page mappings in the TLB.)
7674 	 */
7675 	pde_store(pde, newpde);
7676 
7677 	counter_u64_add(pmap_pde_mappings, 1);
7678 	CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7679 	    va, pmap);
7680 	return (KERN_SUCCESS);
7681 }
7682 
7683 /*
7684  * Maps a sequence of resident pages belonging to the same object.
7685  * The sequence begins with the given page m_start.  This page is
7686  * mapped at the given virtual address start.  Each subsequent page is
7687  * mapped at a virtual address that is offset from start by the same
7688  * amount as the page is offset from m_start within the object.  The
7689  * last page in the sequence is the page with the largest offset from
7690  * m_start that can be mapped at a virtual address less than the given
7691  * virtual address end.  Not every virtual page between start and end
7692  * is mapped; only those for which a resident page exists with the
7693  * corresponding offset from m_start are mapped.
7694  */
7695 void
pmap_enter_object(pmap_t pmap,vm_offset_t start,vm_offset_t end,vm_page_t m_start,vm_prot_t prot)7696 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7697     vm_page_t m_start, vm_prot_t prot)
7698 {
7699 	struct rwlock *lock;
7700 	vm_offset_t va;
7701 	vm_page_t m, mpte;
7702 	vm_pindex_t diff, psize;
7703 	int rv;
7704 
7705 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
7706 
7707 	psize = atop(end - start);
7708 	mpte = NULL;
7709 	m = m_start;
7710 	lock = NULL;
7711 	PMAP_LOCK(pmap);
7712 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7713 		va = start + ptoa(diff);
7714 		if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7715 		    m->psind == 1 && pmap_ps_enabled(pmap) &&
7716 		    ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7717 		    KERN_SUCCESS || rv == KERN_NO_SPACE))
7718 			m = &m[NBPDR / PAGE_SIZE - 1];
7719 		else
7720 			mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7721 			    mpte, &lock);
7722 		m = TAILQ_NEXT(m, listq);
7723 	}
7724 	if (lock != NULL)
7725 		rw_wunlock(lock);
7726 	PMAP_UNLOCK(pmap);
7727 }
7728 
7729 /*
7730  * this code makes some *MAJOR* assumptions:
7731  * 1. Current pmap & pmap exists.
7732  * 2. Not wired.
7733  * 3. Read access.
7734  * 4. No page table pages.
7735  * but is *MUCH* faster than pmap_enter...
7736  */
7737 
7738 void
pmap_enter_quick(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot)7739 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7740 {
7741 	struct rwlock *lock;
7742 
7743 	lock = NULL;
7744 	PMAP_LOCK(pmap);
7745 	(void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7746 	if (lock != NULL)
7747 		rw_wunlock(lock);
7748 	PMAP_UNLOCK(pmap);
7749 }
7750 
7751 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,struct rwlock ** lockp)7752 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7753     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7754 {
7755 	pd_entry_t *pde;
7756 	pt_entry_t newpte, *pte, PG_V;
7757 
7758 	KASSERT(!VA_IS_CLEANMAP(va) ||
7759 	    (m->oflags & VPO_UNMANAGED) != 0,
7760 	    ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7761 	PG_V = pmap_valid_bit(pmap);
7762 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7763 	pde = NULL;
7764 
7765 	/*
7766 	 * In the case that a page table page is not
7767 	 * resident, we are creating it here.
7768 	 */
7769 	if (va < VM_MAXUSER_ADDRESS) {
7770 		pdp_entry_t *pdpe;
7771 		vm_pindex_t ptepindex;
7772 
7773 		/*
7774 		 * Calculate pagetable page index
7775 		 */
7776 		ptepindex = pmap_pde_pindex(va);
7777 		if (mpte && (mpte->pindex == ptepindex)) {
7778 			mpte->ref_count++;
7779 		} else {
7780 			/*
7781 			 * If the page table page is mapped, we just increment
7782 			 * the hold count, and activate it.  Otherwise, we
7783 			 * attempt to allocate a page table page, passing NULL
7784 			 * instead of the PV list lock pointer because we don't
7785 			 * intend to sleep.  If this attempt fails, we don't
7786 			 * retry.  Instead, we give up.
7787 			 */
7788 			pdpe = pmap_pdpe(pmap, va);
7789 			if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7790 				if ((*pdpe & PG_PS) != 0)
7791 					return (NULL);
7792 				pde = pmap_pdpe_to_pde(pdpe, va);
7793 				if ((*pde & PG_V) != 0) {
7794 					if ((*pde & PG_PS) != 0)
7795 						return (NULL);
7796 					mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7797 					mpte->ref_count++;
7798 				} else {
7799 					mpte = pmap_allocpte_alloc(pmap,
7800 					    ptepindex, NULL, va);
7801 					if (mpte == NULL)
7802 						return (NULL);
7803 				}
7804 			} else {
7805 				mpte = pmap_allocpte_alloc(pmap, ptepindex,
7806 				    NULL, va);
7807 				if (mpte == NULL)
7808 					return (NULL);
7809 			}
7810 		}
7811 		pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7812 		pte = &pte[pmap_pte_index(va)];
7813 	} else {
7814 		mpte = NULL;
7815 		pte = vtopte(va);
7816 	}
7817 	if (*pte) {
7818 		if (mpte != NULL)
7819 			mpte->ref_count--;
7820 		return (NULL);
7821 	}
7822 
7823 	/*
7824 	 * Enter on the PV list if part of our managed memory.
7825 	 */
7826 	if ((m->oflags & VPO_UNMANAGED) == 0 &&
7827 	    !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7828 		if (mpte != NULL)
7829 			pmap_abort_ptp(pmap, va, mpte);
7830 		return (NULL);
7831 	}
7832 
7833 	/*
7834 	 * Increment counters
7835 	 */
7836 	pmap_resident_count_adj(pmap, 1);
7837 
7838 	newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7839 	    pmap_cache_bits(pmap, m->md.pat_mode, false);
7840 	if ((m->oflags & VPO_UNMANAGED) == 0)
7841 		newpte |= PG_MANAGED;
7842 	if ((prot & VM_PROT_EXECUTE) == 0)
7843 		newpte |= pg_nx;
7844 	if (va < VM_MAXUSER_ADDRESS)
7845 		newpte |= PG_U | pmap_pkru_get(pmap, va);
7846 	pte_store(pte, newpte);
7847 
7848 #if VM_NRESERVLEVEL > 0
7849 	/*
7850 	 * If both the PTP and the reservation are fully populated, then
7851 	 * attempt promotion.
7852 	 */
7853 	if ((prot & VM_PROT_NO_PROMOTE) == 0 &&
7854 	    (mpte == NULL || mpte->ref_count == NPTEPG) &&
7855 	    (m->flags & PG_FICTITIOUS) == 0 &&
7856 	    vm_reserv_level_iffullpop(m) == 0) {
7857 		if (pde == NULL)
7858 			pde = pmap_pde(pmap, va);
7859 
7860 		/*
7861 		 * If promotion succeeds, then the next call to this function
7862 		 * should not be given the unmapped PTP as a hint.
7863 		 */
7864 		if (pmap_promote_pde(pmap, pde, va, mpte, lockp))
7865 			mpte = NULL;
7866 	}
7867 #endif
7868 
7869 	return (mpte);
7870 }
7871 
7872 /*
7873  * Make a temporary mapping for a physical address.  This is only intended
7874  * to be used for panic dumps.
7875  */
7876 void *
pmap_kenter_temporary(vm_paddr_t pa,int i)7877 pmap_kenter_temporary(vm_paddr_t pa, int i)
7878 {
7879 	vm_offset_t va;
7880 
7881 	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7882 	pmap_kenter(va, pa);
7883 	pmap_invlpg(kernel_pmap, va);
7884 	return ((void *)crashdumpmap);
7885 }
7886 
7887 /*
7888  * This code maps large physical mmap regions into the
7889  * processor address space.  Note that some shortcuts
7890  * are taken, but the code works.
7891  */
7892 void
pmap_object_init_pt(pmap_t pmap,vm_offset_t addr,vm_object_t object,vm_pindex_t pindex,vm_size_t size)7893 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7894     vm_pindex_t pindex, vm_size_t size)
7895 {
7896 	pd_entry_t *pde;
7897 	pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7898 	vm_paddr_t pa, ptepa;
7899 	vm_page_t p, pdpg;
7900 	int pat_mode;
7901 
7902 	PG_A = pmap_accessed_bit(pmap);
7903 	PG_M = pmap_modified_bit(pmap);
7904 	PG_V = pmap_valid_bit(pmap);
7905 	PG_RW = pmap_rw_bit(pmap);
7906 
7907 	VM_OBJECT_ASSERT_WLOCKED(object);
7908 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7909 	    ("pmap_object_init_pt: non-device object"));
7910 	if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7911 		if (!pmap_ps_enabled(pmap))
7912 			return;
7913 		if (!vm_object_populate(object, pindex, pindex + atop(size)))
7914 			return;
7915 		p = vm_page_lookup(object, pindex);
7916 		KASSERT(vm_page_all_valid(p),
7917 		    ("pmap_object_init_pt: invalid page %p", p));
7918 		pat_mode = p->md.pat_mode;
7919 
7920 		/*
7921 		 * Abort the mapping if the first page is not physically
7922 		 * aligned to a 2MB page boundary.
7923 		 */
7924 		ptepa = VM_PAGE_TO_PHYS(p);
7925 		if (ptepa & (NBPDR - 1))
7926 			return;
7927 
7928 		/*
7929 		 * Skip the first page.  Abort the mapping if the rest of
7930 		 * the pages are not physically contiguous or have differing
7931 		 * memory attributes.
7932 		 */
7933 		p = TAILQ_NEXT(p, listq);
7934 		for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7935 		    pa += PAGE_SIZE) {
7936 			KASSERT(vm_page_all_valid(p),
7937 			    ("pmap_object_init_pt: invalid page %p", p));
7938 			if (pa != VM_PAGE_TO_PHYS(p) ||
7939 			    pat_mode != p->md.pat_mode)
7940 				return;
7941 			p = TAILQ_NEXT(p, listq);
7942 		}
7943 
7944 		/*
7945 		 * Map using 2MB pages.  Since "ptepa" is 2M aligned and
7946 		 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7947 		 * will not affect the termination of this loop.
7948 		 */
7949 		PMAP_LOCK(pmap);
7950 		for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, true);
7951 		    pa < ptepa + size; pa += NBPDR) {
7952 			pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7953 			if (pde == NULL) {
7954 				/*
7955 				 * The creation of mappings below is only an
7956 				 * optimization.  If a page directory page
7957 				 * cannot be allocated without blocking,
7958 				 * continue on to the next mapping rather than
7959 				 * blocking.
7960 				 */
7961 				addr += NBPDR;
7962 				continue;
7963 			}
7964 			if ((*pde & PG_V) == 0) {
7965 				pde_store(pde, pa | PG_PS | PG_M | PG_A |
7966 				    PG_U | PG_RW | PG_V);
7967 				pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7968 				counter_u64_add(pmap_pde_mappings, 1);
7969 			} else {
7970 				/* Continue on if the PDE is already valid. */
7971 				pdpg->ref_count--;
7972 				KASSERT(pdpg->ref_count > 0,
7973 				    ("pmap_object_init_pt: missing reference "
7974 				    "to page directory page, va: 0x%lx", addr));
7975 			}
7976 			addr += NBPDR;
7977 		}
7978 		PMAP_UNLOCK(pmap);
7979 	}
7980 }
7981 
7982 /*
7983  *	Clear the wired attribute from the mappings for the specified range of
7984  *	addresses in the given pmap.  Every valid mapping within that range
7985  *	must have the wired attribute set.  In contrast, invalid mappings
7986  *	cannot have the wired attribute set, so they are ignored.
7987  *
7988  *	The wired attribute of the page table entry is not a hardware
7989  *	feature, so there is no need to invalidate any TLB entries.
7990  *	Since pmap_demote_pde() for the wired entry must never fail,
7991  *	pmap_delayed_invl_start()/finish() calls around the
7992  *	function are not needed.
7993  */
7994 void
pmap_unwire(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)7995 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7996 {
7997 	vm_offset_t va_next;
7998 	pml4_entry_t *pml4e;
7999 	pdp_entry_t *pdpe;
8000 	pd_entry_t *pde;
8001 	pt_entry_t *pte, PG_V, PG_G __diagused;
8002 
8003 	PG_V = pmap_valid_bit(pmap);
8004 	PG_G = pmap_global_bit(pmap);
8005 	PMAP_LOCK(pmap);
8006 	for (; sva < eva; sva = va_next) {
8007 		pml4e = pmap_pml4e(pmap, sva);
8008 		if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8009 			va_next = (sva + NBPML4) & ~PML4MASK;
8010 			if (va_next < sva)
8011 				va_next = eva;
8012 			continue;
8013 		}
8014 
8015 		va_next = (sva + NBPDP) & ~PDPMASK;
8016 		if (va_next < sva)
8017 			va_next = eva;
8018 		pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
8019 		if ((*pdpe & PG_V) == 0)
8020 			continue;
8021 		if ((*pdpe & PG_PS) != 0) {
8022 			KASSERT(va_next <= eva,
8023 			    ("partial update of non-transparent 1G mapping "
8024 			    "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8025 			    *pdpe, sva, eva, va_next));
8026 			MPASS(pmap != kernel_pmap); /* XXXKIB */
8027 			MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
8028 			atomic_clear_long(pdpe, PG_W);
8029 			pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
8030 			continue;
8031 		}
8032 
8033 		va_next = (sva + NBPDR) & ~PDRMASK;
8034 		if (va_next < sva)
8035 			va_next = eva;
8036 		pde = pmap_pdpe_to_pde(pdpe, sva);
8037 		if ((*pde & PG_V) == 0)
8038 			continue;
8039 		if ((*pde & PG_PS) != 0) {
8040 			if ((*pde & PG_W) == 0)
8041 				panic("pmap_unwire: pde %#jx is missing PG_W",
8042 				    (uintmax_t)*pde);
8043 
8044 			/*
8045 			 * Are we unwiring the entire large page?  If not,
8046 			 * demote the mapping and fall through.
8047 			 */
8048 			if (sva + NBPDR == va_next && eva >= va_next) {
8049 				atomic_clear_long(pde, PG_W);
8050 				pmap->pm_stats.wired_count -= NBPDR /
8051 				    PAGE_SIZE;
8052 				continue;
8053 			} else if (!pmap_demote_pde(pmap, pde, sva))
8054 				panic("pmap_unwire: demotion failed");
8055 		}
8056 		if (va_next > eva)
8057 			va_next = eva;
8058 		for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
8059 		    sva += PAGE_SIZE) {
8060 			if ((*pte & PG_V) == 0)
8061 				continue;
8062 			if ((*pte & PG_W) == 0)
8063 				panic("pmap_unwire: pte %#jx is missing PG_W",
8064 				    (uintmax_t)*pte);
8065 
8066 			/*
8067 			 * PG_W must be cleared atomically.  Although the pmap
8068 			 * lock synchronizes access to PG_W, another processor
8069 			 * could be setting PG_M and/or PG_A concurrently.
8070 			 */
8071 			atomic_clear_long(pte, PG_W);
8072 			pmap->pm_stats.wired_count--;
8073 		}
8074 	}
8075 	PMAP_UNLOCK(pmap);
8076 }
8077 
8078 /*
8079  *	Copy the range specified by src_addr/len
8080  *	from the source map to the range dst_addr/len
8081  *	in the destination map.
8082  *
8083  *	This routine is only advisory and need not do anything.
8084  */
8085 void
pmap_copy(pmap_t dst_pmap,pmap_t src_pmap,vm_offset_t dst_addr,vm_size_t len,vm_offset_t src_addr)8086 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
8087     vm_offset_t src_addr)
8088 {
8089 	struct rwlock *lock;
8090 	pml4_entry_t *pml4e;
8091 	pdp_entry_t *pdpe;
8092 	pd_entry_t *pde, srcptepaddr;
8093 	pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
8094 	vm_offset_t addr, end_addr, va_next;
8095 	vm_page_t dst_pdpg, dstmpte, srcmpte;
8096 
8097 	if (dst_addr != src_addr)
8098 		return;
8099 
8100 	if (dst_pmap->pm_type != src_pmap->pm_type)
8101 		return;
8102 
8103 	/*
8104 	 * EPT page table entries that require emulation of A/D bits are
8105 	 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
8106 	 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
8107 	 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
8108 	 * implementations flag an EPT misconfiguration for exec-only
8109 	 * mappings we skip this function entirely for emulated pmaps.
8110 	 */
8111 	if (pmap_emulate_ad_bits(dst_pmap))
8112 		return;
8113 
8114 	end_addr = src_addr + len;
8115 	lock = NULL;
8116 	if (dst_pmap < src_pmap) {
8117 		PMAP_LOCK(dst_pmap);
8118 		PMAP_LOCK(src_pmap);
8119 	} else {
8120 		PMAP_LOCK(src_pmap);
8121 		PMAP_LOCK(dst_pmap);
8122 	}
8123 
8124 	PG_A = pmap_accessed_bit(dst_pmap);
8125 	PG_M = pmap_modified_bit(dst_pmap);
8126 	PG_V = pmap_valid_bit(dst_pmap);
8127 
8128 	for (addr = src_addr; addr < end_addr; addr = va_next) {
8129 		KASSERT(addr < UPT_MIN_ADDRESS,
8130 		    ("pmap_copy: invalid to pmap_copy page tables"));
8131 
8132 		pml4e = pmap_pml4e(src_pmap, addr);
8133 		if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8134 			va_next = (addr + NBPML4) & ~PML4MASK;
8135 			if (va_next < addr)
8136 				va_next = end_addr;
8137 			continue;
8138 		}
8139 
8140 		va_next = (addr + NBPDP) & ~PDPMASK;
8141 		if (va_next < addr)
8142 			va_next = end_addr;
8143 		pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
8144 		if ((*pdpe & PG_V) == 0)
8145 			continue;
8146 		if ((*pdpe & PG_PS) != 0) {
8147 			KASSERT(va_next <= end_addr,
8148 			    ("partial update of non-transparent 1G mapping "
8149 			    "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8150 			    *pdpe, addr, end_addr, va_next));
8151 			MPASS((addr & PDPMASK) == 0);
8152 			MPASS((*pdpe & PG_MANAGED) == 0);
8153 			srcptepaddr = *pdpe;
8154 			pdpe = pmap_pdpe(dst_pmap, addr);
8155 			if (pdpe == NULL) {
8156 				if (pmap_allocpte_alloc(dst_pmap,
8157 				    pmap_pml4e_pindex(addr), NULL, addr) ==
8158 				    NULL)
8159 					break;
8160 				pdpe = pmap_pdpe(dst_pmap, addr);
8161 			} else {
8162 				pml4e = pmap_pml4e(dst_pmap, addr);
8163 				dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8164 				dst_pdpg->ref_count++;
8165 			}
8166 			KASSERT(*pdpe == 0,
8167 			    ("1G mapping present in dst pmap "
8168 			    "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8169 			    *pdpe, addr, end_addr, va_next));
8170 			*pdpe = srcptepaddr & ~PG_W;
8171 			pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8172 			continue;
8173 		}
8174 
8175 		va_next = (addr + NBPDR) & ~PDRMASK;
8176 		if (va_next < addr)
8177 			va_next = end_addr;
8178 
8179 		pde = pmap_pdpe_to_pde(pdpe, addr);
8180 		srcptepaddr = *pde;
8181 		if (srcptepaddr == 0)
8182 			continue;
8183 
8184 		if (srcptepaddr & PG_PS) {
8185 			/*
8186 			 * We can only virtual copy whole superpages.
8187 			 */
8188 			if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8189 				continue;
8190 			pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8191 			if (pde == NULL)
8192 				break;
8193 			if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8194 			    pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8195 			    PMAP_ENTER_NORECLAIM, &lock))) {
8196 				/*
8197 				 * We leave the dirty bit unchanged because
8198 				 * managed read/write superpage mappings are
8199 				 * required to be dirty.  However, managed
8200 				 * superpage mappings are not required to
8201 				 * have their accessed bit set, so we clear
8202 				 * it because we don't know if this mapping
8203 				 * will be used.
8204 				 */
8205 				srcptepaddr &= ~PG_W;
8206 				if ((srcptepaddr & PG_MANAGED) != 0)
8207 					srcptepaddr &= ~PG_A;
8208 				*pde = srcptepaddr;
8209 				pmap_resident_count_adj(dst_pmap, NBPDR /
8210 				    PAGE_SIZE);
8211 				counter_u64_add(pmap_pde_mappings, 1);
8212 			} else
8213 				pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8214 			continue;
8215 		}
8216 
8217 		srcptepaddr &= PG_FRAME;
8218 		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8219 		KASSERT(srcmpte->ref_count > 0,
8220 		    ("pmap_copy: source page table page is unused"));
8221 
8222 		if (va_next > end_addr)
8223 			va_next = end_addr;
8224 
8225 		src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8226 		src_pte = &src_pte[pmap_pte_index(addr)];
8227 		dstmpte = NULL;
8228 		for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8229 			ptetemp = *src_pte;
8230 
8231 			/*
8232 			 * We only virtual copy managed pages.
8233 			 */
8234 			if ((ptetemp & PG_MANAGED) == 0)
8235 				continue;
8236 
8237 			if (dstmpte != NULL) {
8238 				KASSERT(dstmpte->pindex ==
8239 				    pmap_pde_pindex(addr),
8240 				    ("dstmpte pindex/addr mismatch"));
8241 				dstmpte->ref_count++;
8242 			} else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8243 			    NULL)) == NULL)
8244 				goto out;
8245 			dst_pte = (pt_entry_t *)
8246 			    PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8247 			dst_pte = &dst_pte[pmap_pte_index(addr)];
8248 			if (*dst_pte == 0 &&
8249 			    pmap_try_insert_pv_entry(dst_pmap, addr,
8250 			    PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8251 				/*
8252 				 * Clear the wired, modified, and accessed
8253 				 * (referenced) bits during the copy.
8254 				 */
8255 				*dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8256 				pmap_resident_count_adj(dst_pmap, 1);
8257 			} else {
8258 				pmap_abort_ptp(dst_pmap, addr, dstmpte);
8259 				goto out;
8260 			}
8261 			/* Have we copied all of the valid mappings? */
8262 			if (dstmpte->ref_count >= srcmpte->ref_count)
8263 				break;
8264 		}
8265 	}
8266 out:
8267 	if (lock != NULL)
8268 		rw_wunlock(lock);
8269 	PMAP_UNLOCK(src_pmap);
8270 	PMAP_UNLOCK(dst_pmap);
8271 }
8272 
8273 int
pmap_vmspace_copy(pmap_t dst_pmap,pmap_t src_pmap)8274 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8275 {
8276 	int error;
8277 
8278 	if (dst_pmap->pm_type != src_pmap->pm_type ||
8279 	    dst_pmap->pm_type != PT_X86 ||
8280 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8281 		return (0);
8282 	for (;;) {
8283 		if (dst_pmap < src_pmap) {
8284 			PMAP_LOCK(dst_pmap);
8285 			PMAP_LOCK(src_pmap);
8286 		} else {
8287 			PMAP_LOCK(src_pmap);
8288 			PMAP_LOCK(dst_pmap);
8289 		}
8290 		error = pmap_pkru_copy(dst_pmap, src_pmap);
8291 		/* Clean up partial copy on failure due to no memory. */
8292 		if (error == ENOMEM)
8293 			pmap_pkru_deassign_all(dst_pmap);
8294 		PMAP_UNLOCK(src_pmap);
8295 		PMAP_UNLOCK(dst_pmap);
8296 		if (error != ENOMEM)
8297 			break;
8298 		vm_wait(NULL);
8299 	}
8300 	return (error);
8301 }
8302 
8303 /*
8304  * Zero the specified hardware page.
8305  */
8306 void
pmap_zero_page(vm_page_t m)8307 pmap_zero_page(vm_page_t m)
8308 {
8309 	vm_offset_t va;
8310 
8311 #ifdef TSLOG_PAGEZERO
8312 	TSENTER();
8313 #endif
8314 	va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8315 	pagezero((void *)va);
8316 #ifdef TSLOG_PAGEZERO
8317 	TSEXIT();
8318 #endif
8319 }
8320 
8321 /*
8322  * Zero an area within a single hardware page.  off and size must not
8323  * cover an area beyond a single hardware page.
8324  */
8325 void
pmap_zero_page_area(vm_page_t m,int off,int size)8326 pmap_zero_page_area(vm_page_t m, int off, int size)
8327 {
8328 	vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8329 
8330 	if (off == 0 && size == PAGE_SIZE)
8331 		pagezero((void *)va);
8332 	else
8333 		bzero((char *)va + off, size);
8334 }
8335 
8336 /*
8337  * Copy 1 specified hardware page to another.
8338  */
8339 void
pmap_copy_page(vm_page_t msrc,vm_page_t mdst)8340 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8341 {
8342 	vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8343 	vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8344 
8345 	pagecopy((void *)src, (void *)dst);
8346 }
8347 
8348 int unmapped_buf_allowed = 1;
8349 
8350 void
pmap_copy_pages(vm_page_t ma[],vm_offset_t a_offset,vm_page_t mb[],vm_offset_t b_offset,int xfersize)8351 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8352     vm_offset_t b_offset, int xfersize)
8353 {
8354 	void *a_cp, *b_cp;
8355 	vm_page_t pages[2];
8356 	vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8357 	int cnt;
8358 	bool mapped;
8359 
8360 	while (xfersize > 0) {
8361 		a_pg_offset = a_offset & PAGE_MASK;
8362 		pages[0] = ma[a_offset >> PAGE_SHIFT];
8363 		b_pg_offset = b_offset & PAGE_MASK;
8364 		pages[1] = mb[b_offset >> PAGE_SHIFT];
8365 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8366 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8367 		mapped = pmap_map_io_transient(pages, vaddr, 2, false);
8368 		a_cp = (char *)vaddr[0] + a_pg_offset;
8369 		b_cp = (char *)vaddr[1] + b_pg_offset;
8370 		bcopy(a_cp, b_cp, cnt);
8371 		if (__predict_false(mapped))
8372 			pmap_unmap_io_transient(pages, vaddr, 2, false);
8373 		a_offset += cnt;
8374 		b_offset += cnt;
8375 		xfersize -= cnt;
8376 	}
8377 }
8378 
8379 /*
8380  * Returns true if the pmap's pv is one of the first
8381  * 16 pvs linked to from this page.  This count may
8382  * be changed upwards or downwards in the future; it
8383  * is only necessary that true be returned for a small
8384  * subset of pmaps for proper page aging.
8385  */
8386 bool
pmap_page_exists_quick(pmap_t pmap,vm_page_t m)8387 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8388 {
8389 	struct md_page *pvh;
8390 	struct rwlock *lock;
8391 	pv_entry_t pv;
8392 	int loops = 0;
8393 	bool rv;
8394 
8395 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8396 	    ("pmap_page_exists_quick: page %p is not managed", m));
8397 	rv = false;
8398 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8399 	rw_rlock(lock);
8400 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8401 		if (PV_PMAP(pv) == pmap) {
8402 			rv = true;
8403 			break;
8404 		}
8405 		loops++;
8406 		if (loops >= 16)
8407 			break;
8408 	}
8409 	if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8410 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8411 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8412 			if (PV_PMAP(pv) == pmap) {
8413 				rv = true;
8414 				break;
8415 			}
8416 			loops++;
8417 			if (loops >= 16)
8418 				break;
8419 		}
8420 	}
8421 	rw_runlock(lock);
8422 	return (rv);
8423 }
8424 
8425 /*
8426  *	pmap_page_wired_mappings:
8427  *
8428  *	Return the number of managed mappings to the given physical page
8429  *	that are wired.
8430  */
8431 int
pmap_page_wired_mappings(vm_page_t m)8432 pmap_page_wired_mappings(vm_page_t m)
8433 {
8434 	struct rwlock *lock;
8435 	struct md_page *pvh;
8436 	pmap_t pmap;
8437 	pt_entry_t *pte;
8438 	pv_entry_t pv;
8439 	int count, md_gen, pvh_gen;
8440 
8441 	if ((m->oflags & VPO_UNMANAGED) != 0)
8442 		return (0);
8443 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8444 	rw_rlock(lock);
8445 restart:
8446 	count = 0;
8447 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8448 		pmap = PV_PMAP(pv);
8449 		if (!PMAP_TRYLOCK(pmap)) {
8450 			md_gen = m->md.pv_gen;
8451 			rw_runlock(lock);
8452 			PMAP_LOCK(pmap);
8453 			rw_rlock(lock);
8454 			if (md_gen != m->md.pv_gen) {
8455 				PMAP_UNLOCK(pmap);
8456 				goto restart;
8457 			}
8458 		}
8459 		pte = pmap_pte(pmap, pv->pv_va);
8460 		if ((*pte & PG_W) != 0)
8461 			count++;
8462 		PMAP_UNLOCK(pmap);
8463 	}
8464 	if ((m->flags & PG_FICTITIOUS) == 0) {
8465 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8466 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8467 			pmap = PV_PMAP(pv);
8468 			if (!PMAP_TRYLOCK(pmap)) {
8469 				md_gen = m->md.pv_gen;
8470 				pvh_gen = pvh->pv_gen;
8471 				rw_runlock(lock);
8472 				PMAP_LOCK(pmap);
8473 				rw_rlock(lock);
8474 				if (md_gen != m->md.pv_gen ||
8475 				    pvh_gen != pvh->pv_gen) {
8476 					PMAP_UNLOCK(pmap);
8477 					goto restart;
8478 				}
8479 			}
8480 			pte = pmap_pde(pmap, pv->pv_va);
8481 			if ((*pte & PG_W) != 0)
8482 				count++;
8483 			PMAP_UNLOCK(pmap);
8484 		}
8485 	}
8486 	rw_runlock(lock);
8487 	return (count);
8488 }
8489 
8490 /*
8491  * Returns true if the given page is mapped individually or as part of
8492  * a 2mpage.  Otherwise, returns false.
8493  */
8494 bool
pmap_page_is_mapped(vm_page_t m)8495 pmap_page_is_mapped(vm_page_t m)
8496 {
8497 	struct rwlock *lock;
8498 	bool rv;
8499 
8500 	if ((m->oflags & VPO_UNMANAGED) != 0)
8501 		return (false);
8502 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8503 	rw_rlock(lock);
8504 	rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8505 	    ((m->flags & PG_FICTITIOUS) == 0 &&
8506 	    !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8507 	rw_runlock(lock);
8508 	return (rv);
8509 }
8510 
8511 /*
8512  * Destroy all managed, non-wired mappings in the given user-space
8513  * pmap.  This pmap cannot be active on any processor besides the
8514  * caller.
8515  *
8516  * This function cannot be applied to the kernel pmap.  Moreover, it
8517  * is not intended for general use.  It is only to be used during
8518  * process termination.  Consequently, it can be implemented in ways
8519  * that make it faster than pmap_remove().  First, it can more quickly
8520  * destroy mappings by iterating over the pmap's collection of PV
8521  * entries, rather than searching the page table.  Second, it doesn't
8522  * have to test and clear the page table entries atomically, because
8523  * no processor is currently accessing the user address space.  In
8524  * particular, a page table entry's dirty bit won't change state once
8525  * this function starts.
8526  *
8527  * Although this function destroys all of the pmap's managed,
8528  * non-wired mappings, it can delay and batch the invalidation of TLB
8529  * entries without calling pmap_delayed_invl_start() and
8530  * pmap_delayed_invl_finish().  Because the pmap is not active on
8531  * any other processor, none of these TLB entries will ever be used
8532  * before their eventual invalidation.  Consequently, there is no need
8533  * for either pmap_remove_all() or pmap_remove_write() to wait for
8534  * that eventual TLB invalidation.
8535  */
8536 void
pmap_remove_pages(pmap_t pmap)8537 pmap_remove_pages(pmap_t pmap)
8538 {
8539 	pd_entry_t ptepde;
8540 	pt_entry_t *pte, tpte;
8541 	pt_entry_t PG_M, PG_RW, PG_V;
8542 	struct spglist free;
8543 	struct pv_chunklist free_chunks[PMAP_MEMDOM];
8544 	vm_page_t m, mpte, mt;
8545 	pv_entry_t pv;
8546 	struct md_page *pvh;
8547 	struct pv_chunk *pc, *npc;
8548 	struct rwlock *lock;
8549 	int64_t bit;
8550 	uint64_t inuse, bitmask;
8551 	int allfree, field, i, idx;
8552 #ifdef PV_STATS
8553 	int freed;
8554 #endif
8555 	bool superpage;
8556 	vm_paddr_t pa;
8557 
8558 	/*
8559 	 * Assert that the given pmap is only active on the current
8560 	 * CPU.  Unfortunately, we cannot block another CPU from
8561 	 * activating the pmap while this function is executing.
8562 	 */
8563 	KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8564 #ifdef INVARIANTS
8565 	{
8566 		cpuset_t other_cpus;
8567 
8568 		other_cpus = all_cpus;
8569 		critical_enter();
8570 		CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8571 		CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8572 		critical_exit();
8573 		KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8574 	}
8575 #endif
8576 
8577 	lock = NULL;
8578 	PG_M = pmap_modified_bit(pmap);
8579 	PG_V = pmap_valid_bit(pmap);
8580 	PG_RW = pmap_rw_bit(pmap);
8581 
8582 	for (i = 0; i < PMAP_MEMDOM; i++)
8583 		TAILQ_INIT(&free_chunks[i]);
8584 	SLIST_INIT(&free);
8585 	PMAP_LOCK(pmap);
8586 	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8587 		allfree = 1;
8588 #ifdef PV_STATS
8589 		freed = 0;
8590 #endif
8591 		for (field = 0; field < _NPCM; field++) {
8592 			inuse = ~pc->pc_map[field] & pc_freemask[field];
8593 			while (inuse != 0) {
8594 				bit = bsfq(inuse);
8595 				bitmask = 1UL << bit;
8596 				idx = field * 64 + bit;
8597 				pv = &pc->pc_pventry[idx];
8598 				inuse &= ~bitmask;
8599 
8600 				pte = pmap_pdpe(pmap, pv->pv_va);
8601 				ptepde = *pte;
8602 				pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8603 				tpte = *pte;
8604 				if ((tpte & (PG_PS | PG_V)) == PG_V) {
8605 					superpage = false;
8606 					ptepde = tpte;
8607 					pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8608 					    PG_FRAME);
8609 					pte = &pte[pmap_pte_index(pv->pv_va)];
8610 					tpte = *pte;
8611 				} else {
8612 					/*
8613 					 * Keep track whether 'tpte' is a
8614 					 * superpage explicitly instead of
8615 					 * relying on PG_PS being set.
8616 					 *
8617 					 * This is because PG_PS is numerically
8618 					 * identical to PG_PTE_PAT and thus a
8619 					 * regular page could be mistaken for
8620 					 * a superpage.
8621 					 */
8622 					superpage = true;
8623 				}
8624 
8625 				if ((tpte & PG_V) == 0) {
8626 					panic("bad pte va %lx pte %lx",
8627 					    pv->pv_va, tpte);
8628 				}
8629 
8630 /*
8631  * We cannot remove wired pages from a process' mapping at this time
8632  */
8633 				if (tpte & PG_W) {
8634 					allfree = 0;
8635 					continue;
8636 				}
8637 
8638 				/* Mark free */
8639 				pc->pc_map[field] |= bitmask;
8640 
8641 				/*
8642 				 * Because this pmap is not active on other
8643 				 * processors, the dirty bit cannot have
8644 				 * changed state since we last loaded pte.
8645 				 */
8646 				pte_clear(pte);
8647 
8648 				if (superpage)
8649 					pa = tpte & PG_PS_FRAME;
8650 				else
8651 					pa = tpte & PG_FRAME;
8652 
8653 				m = PHYS_TO_VM_PAGE(pa);
8654 				KASSERT(m->phys_addr == pa,
8655 				    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8656 				    m, (uintmax_t)m->phys_addr,
8657 				    (uintmax_t)tpte));
8658 
8659 				KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8660 				    m < &vm_page_array[vm_page_array_size],
8661 				    ("pmap_remove_pages: bad tpte %#jx",
8662 				    (uintmax_t)tpte));
8663 
8664 				/*
8665 				 * Update the vm_page_t clean/reference bits.
8666 				 */
8667 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8668 					if (superpage) {
8669 						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8670 							vm_page_dirty(mt);
8671 					} else
8672 						vm_page_dirty(m);
8673 				}
8674 
8675 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8676 
8677 				if (superpage) {
8678 					pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8679 					pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8680 					TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8681 					pvh->pv_gen++;
8682 					if (TAILQ_EMPTY(&pvh->pv_list)) {
8683 						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8684 							if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8685 							    TAILQ_EMPTY(&mt->md.pv_list))
8686 								vm_page_aflag_clear(mt, PGA_WRITEABLE);
8687 					}
8688 					mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8689 					if (mpte != NULL) {
8690 						KASSERT(vm_page_any_valid(mpte),
8691 						    ("pmap_remove_pages: pte page not promoted"));
8692 						pmap_pt_page_count_adj(pmap, -1);
8693 						KASSERT(mpte->ref_count == NPTEPG,
8694 						    ("pmap_remove_pages: pte page reference count error"));
8695 						mpte->ref_count = 0;
8696 						pmap_add_delayed_free_list(mpte, &free, false);
8697 					}
8698 				} else {
8699 					pmap_resident_count_adj(pmap, -1);
8700 					TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8701 					m->md.pv_gen++;
8702 					if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8703 					    TAILQ_EMPTY(&m->md.pv_list) &&
8704 					    (m->flags & PG_FICTITIOUS) == 0) {
8705 						pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8706 						if (TAILQ_EMPTY(&pvh->pv_list))
8707 							vm_page_aflag_clear(m, PGA_WRITEABLE);
8708 					}
8709 				}
8710 				pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8711 #ifdef PV_STATS
8712 				freed++;
8713 #endif
8714 			}
8715 		}
8716 		PV_STAT(counter_u64_add(pv_entry_frees, freed));
8717 		PV_STAT(counter_u64_add(pv_entry_spare, freed));
8718 		PV_STAT(counter_u64_add(pv_entry_count, -freed));
8719 		if (allfree) {
8720 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8721 			TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8722 		}
8723 	}
8724 	if (lock != NULL)
8725 		rw_wunlock(lock);
8726 	pmap_invalidate_all(pmap);
8727 	pmap_pkru_deassign_all(pmap);
8728 	free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8729 	PMAP_UNLOCK(pmap);
8730 	vm_page_free_pages_toq(&free, true);
8731 }
8732 
8733 static bool
pmap_page_test_mappings(vm_page_t m,bool accessed,bool modified)8734 pmap_page_test_mappings(vm_page_t m, bool accessed, bool modified)
8735 {
8736 	struct rwlock *lock;
8737 	pv_entry_t pv;
8738 	struct md_page *pvh;
8739 	pt_entry_t *pte, mask;
8740 	pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8741 	pmap_t pmap;
8742 	int md_gen, pvh_gen;
8743 	bool rv;
8744 
8745 	rv = false;
8746 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8747 	rw_rlock(lock);
8748 restart:
8749 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8750 		pmap = PV_PMAP(pv);
8751 		if (!PMAP_TRYLOCK(pmap)) {
8752 			md_gen = m->md.pv_gen;
8753 			rw_runlock(lock);
8754 			PMAP_LOCK(pmap);
8755 			rw_rlock(lock);
8756 			if (md_gen != m->md.pv_gen) {
8757 				PMAP_UNLOCK(pmap);
8758 				goto restart;
8759 			}
8760 		}
8761 		pte = pmap_pte(pmap, pv->pv_va);
8762 		mask = 0;
8763 		if (modified) {
8764 			PG_M = pmap_modified_bit(pmap);
8765 			PG_RW = pmap_rw_bit(pmap);
8766 			mask |= PG_RW | PG_M;
8767 		}
8768 		if (accessed) {
8769 			PG_A = pmap_accessed_bit(pmap);
8770 			PG_V = pmap_valid_bit(pmap);
8771 			mask |= PG_V | PG_A;
8772 		}
8773 		rv = (*pte & mask) == mask;
8774 		PMAP_UNLOCK(pmap);
8775 		if (rv)
8776 			goto out;
8777 	}
8778 	if ((m->flags & PG_FICTITIOUS) == 0) {
8779 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8780 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8781 			pmap = PV_PMAP(pv);
8782 			if (!PMAP_TRYLOCK(pmap)) {
8783 				md_gen = m->md.pv_gen;
8784 				pvh_gen = pvh->pv_gen;
8785 				rw_runlock(lock);
8786 				PMAP_LOCK(pmap);
8787 				rw_rlock(lock);
8788 				if (md_gen != m->md.pv_gen ||
8789 				    pvh_gen != pvh->pv_gen) {
8790 					PMAP_UNLOCK(pmap);
8791 					goto restart;
8792 				}
8793 			}
8794 			pte = pmap_pde(pmap, pv->pv_va);
8795 			mask = 0;
8796 			if (modified) {
8797 				PG_M = pmap_modified_bit(pmap);
8798 				PG_RW = pmap_rw_bit(pmap);
8799 				mask |= PG_RW | PG_M;
8800 			}
8801 			if (accessed) {
8802 				PG_A = pmap_accessed_bit(pmap);
8803 				PG_V = pmap_valid_bit(pmap);
8804 				mask |= PG_V | PG_A;
8805 			}
8806 			rv = (*pte & mask) == mask;
8807 			PMAP_UNLOCK(pmap);
8808 			if (rv)
8809 				goto out;
8810 		}
8811 	}
8812 out:
8813 	rw_runlock(lock);
8814 	return (rv);
8815 }
8816 
8817 /*
8818  *	pmap_is_modified:
8819  *
8820  *	Return whether or not the specified physical page was modified
8821  *	in any physical maps.
8822  */
8823 bool
pmap_is_modified(vm_page_t m)8824 pmap_is_modified(vm_page_t m)
8825 {
8826 
8827 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8828 	    ("pmap_is_modified: page %p is not managed", m));
8829 
8830 	/*
8831 	 * If the page is not busied then this check is racy.
8832 	 */
8833 	if (!pmap_page_is_write_mapped(m))
8834 		return (false);
8835 	return (pmap_page_test_mappings(m, false, true));
8836 }
8837 
8838 /*
8839  *	pmap_is_prefaultable:
8840  *
8841  *	Return whether or not the specified virtual address is eligible
8842  *	for prefault.
8843  */
8844 bool
pmap_is_prefaultable(pmap_t pmap,vm_offset_t addr)8845 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8846 {
8847 	pd_entry_t *pde;
8848 	pt_entry_t *pte, PG_V;
8849 	bool rv;
8850 
8851 	PG_V = pmap_valid_bit(pmap);
8852 
8853 	/*
8854 	 * Return true if and only if the PTE for the specified virtual
8855 	 * address is allocated but invalid.
8856 	 */
8857 	rv = false;
8858 	PMAP_LOCK(pmap);
8859 	pde = pmap_pde(pmap, addr);
8860 	if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8861 		pte = pmap_pde_to_pte(pde, addr);
8862 		rv = (*pte & PG_V) == 0;
8863 	}
8864 	PMAP_UNLOCK(pmap);
8865 	return (rv);
8866 }
8867 
8868 /*
8869  *	pmap_is_referenced:
8870  *
8871  *	Return whether or not the specified physical page was referenced
8872  *	in any physical maps.
8873  */
8874 bool
pmap_is_referenced(vm_page_t m)8875 pmap_is_referenced(vm_page_t m)
8876 {
8877 
8878 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8879 	    ("pmap_is_referenced: page %p is not managed", m));
8880 	return (pmap_page_test_mappings(m, true, false));
8881 }
8882 
8883 /*
8884  * Clear the write and modified bits in each of the given page's mappings.
8885  */
8886 void
pmap_remove_write(vm_page_t m)8887 pmap_remove_write(vm_page_t m)
8888 {
8889 	struct md_page *pvh;
8890 	pmap_t pmap;
8891 	struct rwlock *lock;
8892 	pv_entry_t next_pv, pv;
8893 	pd_entry_t *pde;
8894 	pt_entry_t oldpte, *pte, PG_M, PG_RW;
8895 	vm_offset_t va;
8896 	int pvh_gen, md_gen;
8897 
8898 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8899 	    ("pmap_remove_write: page %p is not managed", m));
8900 
8901 	vm_page_assert_busied(m);
8902 	if (!pmap_page_is_write_mapped(m))
8903 		return;
8904 
8905 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8906 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8907 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
8908 	rw_wlock(lock);
8909 retry:
8910 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8911 		pmap = PV_PMAP(pv);
8912 		if (!PMAP_TRYLOCK(pmap)) {
8913 			pvh_gen = pvh->pv_gen;
8914 			rw_wunlock(lock);
8915 			PMAP_LOCK(pmap);
8916 			rw_wlock(lock);
8917 			if (pvh_gen != pvh->pv_gen) {
8918 				PMAP_UNLOCK(pmap);
8919 				goto retry;
8920 			}
8921 		}
8922 		PG_RW = pmap_rw_bit(pmap);
8923 		va = pv->pv_va;
8924 		pde = pmap_pde(pmap, va);
8925 		if ((*pde & PG_RW) != 0)
8926 			(void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8927 		KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8928 		    ("inconsistent pv lock %p %p for page %p",
8929 		    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8930 		PMAP_UNLOCK(pmap);
8931 	}
8932 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8933 		pmap = PV_PMAP(pv);
8934 		if (!PMAP_TRYLOCK(pmap)) {
8935 			pvh_gen = pvh->pv_gen;
8936 			md_gen = m->md.pv_gen;
8937 			rw_wunlock(lock);
8938 			PMAP_LOCK(pmap);
8939 			rw_wlock(lock);
8940 			if (pvh_gen != pvh->pv_gen ||
8941 			    md_gen != m->md.pv_gen) {
8942 				PMAP_UNLOCK(pmap);
8943 				goto retry;
8944 			}
8945 		}
8946 		PG_M = pmap_modified_bit(pmap);
8947 		PG_RW = pmap_rw_bit(pmap);
8948 		pde = pmap_pde(pmap, pv->pv_va);
8949 		KASSERT((*pde & PG_PS) == 0,
8950 		    ("pmap_remove_write: found a 2mpage in page %p's pv list",
8951 		    m));
8952 		pte = pmap_pde_to_pte(pde, pv->pv_va);
8953 		oldpte = *pte;
8954 		if (oldpte & PG_RW) {
8955 			while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8956 			    ~(PG_RW | PG_M)))
8957 				cpu_spinwait();
8958 			if ((oldpte & PG_M) != 0)
8959 				vm_page_dirty(m);
8960 			pmap_invalidate_page(pmap, pv->pv_va);
8961 		}
8962 		PMAP_UNLOCK(pmap);
8963 	}
8964 	rw_wunlock(lock);
8965 	vm_page_aflag_clear(m, PGA_WRITEABLE);
8966 	pmap_delayed_invl_wait(m);
8967 }
8968 
8969 /*
8970  *	pmap_ts_referenced:
8971  *
8972  *	Return a count of reference bits for a page, clearing those bits.
8973  *	It is not necessary for every reference bit to be cleared, but it
8974  *	is necessary that 0 only be returned when there are truly no
8975  *	reference bits set.
8976  *
8977  *	As an optimization, update the page's dirty field if a modified bit is
8978  *	found while counting reference bits.  This opportunistic update can be
8979  *	performed at low cost and can eliminate the need for some future calls
8980  *	to pmap_is_modified().  However, since this function stops after
8981  *	finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8982  *	dirty pages.  Those dirty pages will only be detected by a future call
8983  *	to pmap_is_modified().
8984  *
8985  *	A DI block is not needed within this function, because
8986  *	invalidations are performed before the PV list lock is
8987  *	released.
8988  */
8989 int
pmap_ts_referenced(vm_page_t m)8990 pmap_ts_referenced(vm_page_t m)
8991 {
8992 	struct md_page *pvh;
8993 	pv_entry_t pv, pvf;
8994 	pmap_t pmap;
8995 	struct rwlock *lock;
8996 	pd_entry_t oldpde, *pde;
8997 	pt_entry_t *pte, PG_A, PG_M, PG_RW;
8998 	vm_offset_t va;
8999 	vm_paddr_t pa;
9000 	int cleared, md_gen, not_cleared, pvh_gen;
9001 	struct spglist free;
9002 	bool demoted;
9003 
9004 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9005 	    ("pmap_ts_referenced: page %p is not managed", m));
9006 	SLIST_INIT(&free);
9007 	cleared = 0;
9008 	pa = VM_PAGE_TO_PHYS(m);
9009 	lock = PHYS_TO_PV_LIST_LOCK(pa);
9010 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
9011 	rw_wlock(lock);
9012 retry:
9013 	not_cleared = 0;
9014 	if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
9015 		goto small_mappings;
9016 	pv = pvf;
9017 	do {
9018 		if (pvf == NULL)
9019 			pvf = pv;
9020 		pmap = PV_PMAP(pv);
9021 		if (!PMAP_TRYLOCK(pmap)) {
9022 			pvh_gen = pvh->pv_gen;
9023 			rw_wunlock(lock);
9024 			PMAP_LOCK(pmap);
9025 			rw_wlock(lock);
9026 			if (pvh_gen != pvh->pv_gen) {
9027 				PMAP_UNLOCK(pmap);
9028 				goto retry;
9029 			}
9030 		}
9031 		PG_A = pmap_accessed_bit(pmap);
9032 		PG_M = pmap_modified_bit(pmap);
9033 		PG_RW = pmap_rw_bit(pmap);
9034 		va = pv->pv_va;
9035 		pde = pmap_pde(pmap, pv->pv_va);
9036 		oldpde = *pde;
9037 		if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9038 			/*
9039 			 * Although "oldpde" is mapping a 2MB page, because
9040 			 * this function is called at a 4KB page granularity,
9041 			 * we only update the 4KB page under test.
9042 			 */
9043 			vm_page_dirty(m);
9044 		}
9045 		if ((oldpde & PG_A) != 0) {
9046 			/*
9047 			 * Since this reference bit is shared by 512 4KB
9048 			 * pages, it should not be cleared every time it is
9049 			 * tested.  Apply a simple "hash" function on the
9050 			 * physical page number, the virtual superpage number,
9051 			 * and the pmap address to select one 4KB page out of
9052 			 * the 512 on which testing the reference bit will
9053 			 * result in clearing that reference bit.  This
9054 			 * function is designed to avoid the selection of the
9055 			 * same 4KB page for every 2MB page mapping.
9056 			 *
9057 			 * On demotion, a mapping that hasn't been referenced
9058 			 * is simply destroyed.  To avoid the possibility of a
9059 			 * subsequent page fault on a demoted wired mapping,
9060 			 * always leave its reference bit set.  Moreover,
9061 			 * since the superpage is wired, the current state of
9062 			 * its reference bit won't affect page replacement.
9063 			 */
9064 			if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
9065 			    (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
9066 			    (oldpde & PG_W) == 0) {
9067 				if (safe_to_clear_referenced(pmap, oldpde)) {
9068 					atomic_clear_long(pde, PG_A);
9069 					pmap_invalidate_page(pmap, pv->pv_va);
9070 					demoted = false;
9071 				} else if (pmap_demote_pde_locked(pmap, pde,
9072 				    pv->pv_va, &lock)) {
9073 					/*
9074 					 * Remove the mapping to a single page
9075 					 * so that a subsequent access may
9076 					 * repromote.  Since the underlying
9077 					 * page table page is fully populated,
9078 					 * this removal never frees a page
9079 					 * table page.
9080 					 */
9081 					demoted = true;
9082 					va += VM_PAGE_TO_PHYS(m) - (oldpde &
9083 					    PG_PS_FRAME);
9084 					pte = pmap_pde_to_pte(pde, va);
9085 					pmap_remove_pte(pmap, pte, va, *pde,
9086 					    NULL, &lock);
9087 					pmap_invalidate_page(pmap, va);
9088 				} else
9089 					demoted = true;
9090 
9091 				if (demoted) {
9092 					/*
9093 					 * The superpage mapping was removed
9094 					 * entirely and therefore 'pv' is no
9095 					 * longer valid.
9096 					 */
9097 					if (pvf == pv)
9098 						pvf = NULL;
9099 					pv = NULL;
9100 				}
9101 				cleared++;
9102 				KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9103 				    ("inconsistent pv lock %p %p for page %p",
9104 				    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9105 			} else
9106 				not_cleared++;
9107 		}
9108 		PMAP_UNLOCK(pmap);
9109 		/* Rotate the PV list if it has more than one entry. */
9110 		if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9111 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
9112 			TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
9113 			pvh->pv_gen++;
9114 		}
9115 		if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
9116 			goto out;
9117 	} while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9118 small_mappings:
9119 	if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9120 		goto out;
9121 	pv = pvf;
9122 	do {
9123 		if (pvf == NULL)
9124 			pvf = pv;
9125 		pmap = PV_PMAP(pv);
9126 		if (!PMAP_TRYLOCK(pmap)) {
9127 			pvh_gen = pvh->pv_gen;
9128 			md_gen = m->md.pv_gen;
9129 			rw_wunlock(lock);
9130 			PMAP_LOCK(pmap);
9131 			rw_wlock(lock);
9132 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9133 				PMAP_UNLOCK(pmap);
9134 				goto retry;
9135 			}
9136 		}
9137 		PG_A = pmap_accessed_bit(pmap);
9138 		PG_M = pmap_modified_bit(pmap);
9139 		PG_RW = pmap_rw_bit(pmap);
9140 		pde = pmap_pde(pmap, pv->pv_va);
9141 		KASSERT((*pde & PG_PS) == 0,
9142 		    ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9143 		    m));
9144 		pte = pmap_pde_to_pte(pde, pv->pv_va);
9145 		if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9146 			vm_page_dirty(m);
9147 		if ((*pte & PG_A) != 0) {
9148 			if (safe_to_clear_referenced(pmap, *pte)) {
9149 				atomic_clear_long(pte, PG_A);
9150 				pmap_invalidate_page(pmap, pv->pv_va);
9151 				cleared++;
9152 			} else if ((*pte & PG_W) == 0) {
9153 				/*
9154 				 * Wired pages cannot be paged out so
9155 				 * doing accessed bit emulation for
9156 				 * them is wasted effort. We do the
9157 				 * hard work for unwired pages only.
9158 				 */
9159 				pmap_remove_pte(pmap, pte, pv->pv_va,
9160 				    *pde, &free, &lock);
9161 				pmap_invalidate_page(pmap, pv->pv_va);
9162 				cleared++;
9163 				if (pvf == pv)
9164 					pvf = NULL;
9165 				pv = NULL;
9166 				KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9167 				    ("inconsistent pv lock %p %p for page %p",
9168 				    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9169 			} else
9170 				not_cleared++;
9171 		}
9172 		PMAP_UNLOCK(pmap);
9173 		/* Rotate the PV list if it has more than one entry. */
9174 		if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9175 			TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9176 			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9177 			m->md.pv_gen++;
9178 		}
9179 	} while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9180 	    not_cleared < PMAP_TS_REFERENCED_MAX);
9181 out:
9182 	rw_wunlock(lock);
9183 	vm_page_free_pages_toq(&free, true);
9184 	return (cleared + not_cleared);
9185 }
9186 
9187 /*
9188  *	Apply the given advice to the specified range of addresses within the
9189  *	given pmap.  Depending on the advice, clear the referenced and/or
9190  *	modified flags in each mapping and set the mapped page's dirty field.
9191  */
9192 void
pmap_advise(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,int advice)9193 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9194 {
9195 	struct rwlock *lock;
9196 	pml4_entry_t *pml4e;
9197 	pdp_entry_t *pdpe;
9198 	pd_entry_t oldpde, *pde;
9199 	pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9200 	vm_offset_t va, va_next;
9201 	vm_page_t m;
9202 	bool anychanged;
9203 
9204 	if (advice != MADV_DONTNEED && advice != MADV_FREE)
9205 		return;
9206 
9207 	/*
9208 	 * A/D bit emulation requires an alternate code path when clearing
9209 	 * the modified and accessed bits below. Since this function is
9210 	 * advisory in nature we skip it entirely for pmaps that require
9211 	 * A/D bit emulation.
9212 	 */
9213 	if (pmap_emulate_ad_bits(pmap))
9214 		return;
9215 
9216 	PG_A = pmap_accessed_bit(pmap);
9217 	PG_G = pmap_global_bit(pmap);
9218 	PG_M = pmap_modified_bit(pmap);
9219 	PG_V = pmap_valid_bit(pmap);
9220 	PG_RW = pmap_rw_bit(pmap);
9221 	anychanged = false;
9222 	pmap_delayed_invl_start();
9223 	PMAP_LOCK(pmap);
9224 	for (; sva < eva; sva = va_next) {
9225 		pml4e = pmap_pml4e(pmap, sva);
9226 		if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9227 			va_next = (sva + NBPML4) & ~PML4MASK;
9228 			if (va_next < sva)
9229 				va_next = eva;
9230 			continue;
9231 		}
9232 
9233 		va_next = (sva + NBPDP) & ~PDPMASK;
9234 		if (va_next < sva)
9235 			va_next = eva;
9236 		pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9237 		if ((*pdpe & PG_V) == 0)
9238 			continue;
9239 		if ((*pdpe & PG_PS) != 0)
9240 			continue;
9241 
9242 		va_next = (sva + NBPDR) & ~PDRMASK;
9243 		if (va_next < sva)
9244 			va_next = eva;
9245 		pde = pmap_pdpe_to_pde(pdpe, sva);
9246 		oldpde = *pde;
9247 		if ((oldpde & PG_V) == 0)
9248 			continue;
9249 		else if ((oldpde & PG_PS) != 0) {
9250 			if ((oldpde & PG_MANAGED) == 0)
9251 				continue;
9252 			lock = NULL;
9253 			if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9254 				if (lock != NULL)
9255 					rw_wunlock(lock);
9256 
9257 				/*
9258 				 * The large page mapping was destroyed.
9259 				 */
9260 				continue;
9261 			}
9262 
9263 			/*
9264 			 * Unless the page mappings are wired, remove the
9265 			 * mapping to a single page so that a subsequent
9266 			 * access may repromote.  Choosing the last page
9267 			 * within the address range [sva, min(va_next, eva))
9268 			 * generally results in more repromotions.  Since the
9269 			 * underlying page table page is fully populated, this
9270 			 * removal never frees a page table page.
9271 			 */
9272 			if ((oldpde & PG_W) == 0) {
9273 				va = eva;
9274 				if (va > va_next)
9275 					va = va_next;
9276 				va -= PAGE_SIZE;
9277 				KASSERT(va >= sva,
9278 				    ("pmap_advise: no address gap"));
9279 				pte = pmap_pde_to_pte(pde, va);
9280 				KASSERT((*pte & PG_V) != 0,
9281 				    ("pmap_advise: invalid PTE"));
9282 				pmap_remove_pte(pmap, pte, va, *pde, NULL,
9283 				    &lock);
9284 				anychanged = true;
9285 			}
9286 			if (lock != NULL)
9287 				rw_wunlock(lock);
9288 		}
9289 		if (va_next > eva)
9290 			va_next = eva;
9291 		va = va_next;
9292 		for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9293 		    sva += PAGE_SIZE) {
9294 			if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9295 				goto maybe_invlrng;
9296 			else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9297 				if (advice == MADV_DONTNEED) {
9298 					/*
9299 					 * Future calls to pmap_is_modified()
9300 					 * can be avoided by making the page
9301 					 * dirty now.
9302 					 */
9303 					m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9304 					vm_page_dirty(m);
9305 				}
9306 				atomic_clear_long(pte, PG_M | PG_A);
9307 			} else if ((*pte & PG_A) != 0)
9308 				atomic_clear_long(pte, PG_A);
9309 			else
9310 				goto maybe_invlrng;
9311 
9312 			if ((*pte & PG_G) != 0) {
9313 				if (va == va_next)
9314 					va = sva;
9315 			} else
9316 				anychanged = true;
9317 			continue;
9318 maybe_invlrng:
9319 			if (va != va_next) {
9320 				pmap_invalidate_range(pmap, va, sva);
9321 				va = va_next;
9322 			}
9323 		}
9324 		if (va != va_next)
9325 			pmap_invalidate_range(pmap, va, sva);
9326 	}
9327 	if (anychanged)
9328 		pmap_invalidate_all(pmap);
9329 	PMAP_UNLOCK(pmap);
9330 	pmap_delayed_invl_finish();
9331 }
9332 
9333 /*
9334  *	Clear the modify bits on the specified physical page.
9335  */
9336 void
pmap_clear_modify(vm_page_t m)9337 pmap_clear_modify(vm_page_t m)
9338 {
9339 	struct md_page *pvh;
9340 	pmap_t pmap;
9341 	pv_entry_t next_pv, pv;
9342 	pd_entry_t oldpde, *pde;
9343 	pt_entry_t *pte, PG_M, PG_RW;
9344 	struct rwlock *lock;
9345 	vm_offset_t va;
9346 	int md_gen, pvh_gen;
9347 
9348 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9349 	    ("pmap_clear_modify: page %p is not managed", m));
9350 	vm_page_assert_busied(m);
9351 
9352 	if (!pmap_page_is_write_mapped(m))
9353 		return;
9354 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9355 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
9356 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9357 	rw_wlock(lock);
9358 restart:
9359 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9360 		pmap = PV_PMAP(pv);
9361 		if (!PMAP_TRYLOCK(pmap)) {
9362 			pvh_gen = pvh->pv_gen;
9363 			rw_wunlock(lock);
9364 			PMAP_LOCK(pmap);
9365 			rw_wlock(lock);
9366 			if (pvh_gen != pvh->pv_gen) {
9367 				PMAP_UNLOCK(pmap);
9368 				goto restart;
9369 			}
9370 		}
9371 		PG_M = pmap_modified_bit(pmap);
9372 		PG_RW = pmap_rw_bit(pmap);
9373 		va = pv->pv_va;
9374 		pde = pmap_pde(pmap, va);
9375 		oldpde = *pde;
9376 		/* If oldpde has PG_RW set, then it also has PG_M set. */
9377 		if ((oldpde & PG_RW) != 0 &&
9378 		    pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9379 		    (oldpde & PG_W) == 0) {
9380 			/*
9381 			 * Write protect the mapping to a single page so that
9382 			 * a subsequent write access may repromote.
9383 			 */
9384 			va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9385 			pte = pmap_pde_to_pte(pde, va);
9386 			atomic_clear_long(pte, PG_M | PG_RW);
9387 			vm_page_dirty(m);
9388 			pmap_invalidate_page(pmap, va);
9389 		}
9390 		PMAP_UNLOCK(pmap);
9391 	}
9392 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9393 		pmap = PV_PMAP(pv);
9394 		if (!PMAP_TRYLOCK(pmap)) {
9395 			md_gen = m->md.pv_gen;
9396 			pvh_gen = pvh->pv_gen;
9397 			rw_wunlock(lock);
9398 			PMAP_LOCK(pmap);
9399 			rw_wlock(lock);
9400 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9401 				PMAP_UNLOCK(pmap);
9402 				goto restart;
9403 			}
9404 		}
9405 		PG_M = pmap_modified_bit(pmap);
9406 		PG_RW = pmap_rw_bit(pmap);
9407 		pde = pmap_pde(pmap, pv->pv_va);
9408 		KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9409 		    " a 2mpage in page %p's pv list", m));
9410 		pte = pmap_pde_to_pte(pde, pv->pv_va);
9411 		if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9412 			atomic_clear_long(pte, PG_M);
9413 			pmap_invalidate_page(pmap, pv->pv_va);
9414 		}
9415 		PMAP_UNLOCK(pmap);
9416 	}
9417 	rw_wunlock(lock);
9418 }
9419 
9420 /*
9421  * Miscellaneous support routines follow
9422  */
9423 
9424 /* Adjust the properties for a leaf page table entry. */
9425 static __inline void
pmap_pte_props(pt_entry_t * pte,u_long bits,u_long mask)9426 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9427 {
9428 	u_long opte, npte;
9429 
9430 	opte = *(u_long *)pte;
9431 	do {
9432 		npte = opte & ~mask;
9433 		npte |= bits;
9434 	} while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9435 	    npte));
9436 }
9437 
9438 /*
9439  * Map a set of physical memory pages into the kernel virtual
9440  * address space. Return a pointer to where it is mapped. This
9441  * routine is intended to be used for mapping device memory,
9442  * NOT real memory.
9443  */
9444 static void *
pmap_mapdev_internal(vm_paddr_t pa,vm_size_t size,int mode,int flags)9445 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9446 {
9447 	struct pmap_preinit_mapping *ppim;
9448 	vm_offset_t va, offset;
9449 	vm_size_t tmpsize;
9450 	int i;
9451 
9452 	offset = pa & PAGE_MASK;
9453 	size = round_page(offset + size);
9454 	pa = trunc_page(pa);
9455 
9456 	if (!pmap_initialized) {
9457 		va = 0;
9458 		for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9459 			ppim = pmap_preinit_mapping + i;
9460 			if (ppim->va == 0) {
9461 				ppim->pa = pa;
9462 				ppim->sz = size;
9463 				ppim->mode = mode;
9464 				ppim->va = virtual_avail;
9465 				virtual_avail += size;
9466 				va = ppim->va;
9467 				break;
9468 			}
9469 		}
9470 		if (va == 0)
9471 			panic("%s: too many preinit mappings", __func__);
9472 	} else {
9473 		/*
9474 		 * If we have a preinit mapping, reuse it.
9475 		 */
9476 		for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9477 			ppim = pmap_preinit_mapping + i;
9478 			if (ppim->pa == pa && ppim->sz == size &&
9479 			    (ppim->mode == mode ||
9480 			    (flags & MAPDEV_SETATTR) == 0))
9481 				return ((void *)(ppim->va + offset));
9482 		}
9483 		/*
9484 		 * If the specified range of physical addresses fits within
9485 		 * the direct map window, use the direct map.
9486 		 */
9487 		if (pa < dmaplimit && pa + size <= dmaplimit) {
9488 			va = PHYS_TO_DMAP(pa);
9489 			if ((flags & MAPDEV_SETATTR) != 0) {
9490 				PMAP_LOCK(kernel_pmap);
9491 				i = pmap_change_props_locked(va, size,
9492 				    PROT_NONE, mode, flags);
9493 				PMAP_UNLOCK(kernel_pmap);
9494 			} else
9495 				i = 0;
9496 			if (!i)
9497 				return ((void *)(va + offset));
9498 		}
9499 		va = kva_alloc(size);
9500 		if (va == 0)
9501 			panic("%s: Couldn't allocate KVA", __func__);
9502 	}
9503 	for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9504 		pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9505 	pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9506 	if ((flags & MAPDEV_FLUSHCACHE) != 0)
9507 		pmap_invalidate_cache_range(va, va + tmpsize);
9508 	return ((void *)(va + offset));
9509 }
9510 
9511 void *
pmap_mapdev_attr(vm_paddr_t pa,vm_size_t size,int mode)9512 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9513 {
9514 
9515 	return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9516 	    MAPDEV_SETATTR));
9517 }
9518 
9519 void *
pmap_mapdev(vm_paddr_t pa,vm_size_t size)9520 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9521 {
9522 
9523 	return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9524 }
9525 
9526 void *
pmap_mapdev_pciecfg(vm_paddr_t pa,vm_size_t size)9527 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9528 {
9529 
9530 	return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9531 	    MAPDEV_SETATTR));
9532 }
9533 
9534 void *
pmap_mapbios(vm_paddr_t pa,vm_size_t size)9535 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9536 {
9537 
9538 	return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9539 	    MAPDEV_FLUSHCACHE));
9540 }
9541 
9542 void
pmap_unmapdev(void * p,vm_size_t size)9543 pmap_unmapdev(void *p, vm_size_t size)
9544 {
9545 	struct pmap_preinit_mapping *ppim;
9546 	vm_offset_t offset, va;
9547 	int i;
9548 
9549 	va = (vm_offset_t)p;
9550 
9551 	/* If we gave a direct map region in pmap_mapdev, do nothing */
9552 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9553 		return;
9554 	offset = va & PAGE_MASK;
9555 	size = round_page(offset + size);
9556 	va = trunc_page(va);
9557 	for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9558 		ppim = pmap_preinit_mapping + i;
9559 		if (ppim->va == va && ppim->sz == size) {
9560 			if (pmap_initialized)
9561 				return;
9562 			ppim->pa = 0;
9563 			ppim->va = 0;
9564 			ppim->sz = 0;
9565 			ppim->mode = 0;
9566 			if (va + size == virtual_avail)
9567 				virtual_avail = va;
9568 			return;
9569 		}
9570 	}
9571 	if (pmap_initialized) {
9572 		pmap_qremove(va, atop(size));
9573 		kva_free(va, size);
9574 	}
9575 }
9576 
9577 /*
9578  * Tries to demote a 1GB page mapping.
9579  */
9580 static bool
pmap_demote_pdpe(pmap_t pmap,pdp_entry_t * pdpe,vm_offset_t va)9581 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9582 {
9583 	pdp_entry_t newpdpe, oldpdpe;
9584 	pd_entry_t *firstpde, newpde, *pde;
9585 	pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9586 	vm_paddr_t pdpgpa;
9587 	vm_page_t pdpg;
9588 
9589 	PG_A = pmap_accessed_bit(pmap);
9590 	PG_M = pmap_modified_bit(pmap);
9591 	PG_V = pmap_valid_bit(pmap);
9592 	PG_RW = pmap_rw_bit(pmap);
9593 
9594 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9595 	oldpdpe = *pdpe;
9596 	KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9597 	    ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9598 	pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9599 	    VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9600 	if (pdpg  == NULL) {
9601 		CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9602 		    " in pmap %p", va, pmap);
9603 		return (false);
9604 	}
9605 	pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9606 	firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9607 	newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9608 	KASSERT((oldpdpe & PG_A) != 0,
9609 	    ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9610 	KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9611 	    ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9612 	newpde = oldpdpe;
9613 
9614 	/*
9615 	 * Initialize the page directory page.
9616 	 */
9617 	for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9618 		*pde = newpde;
9619 		newpde += NBPDR;
9620 	}
9621 
9622 	/*
9623 	 * Demote the mapping.
9624 	 */
9625 	*pdpe = newpdpe;
9626 
9627 	/*
9628 	 * Invalidate a stale recursive mapping of the page directory page.
9629 	 */
9630 	pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9631 
9632 	counter_u64_add(pmap_pdpe_demotions, 1);
9633 	CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9634 	    " in pmap %p", va, pmap);
9635 	return (true);
9636 }
9637 
9638 /*
9639  * Sets the memory attribute for the specified page.
9640  */
9641 void
pmap_page_set_memattr(vm_page_t m,vm_memattr_t ma)9642 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9643 {
9644 
9645 	m->md.pat_mode = ma;
9646 
9647 	/*
9648 	 * If "m" is a normal page, update its direct mapping.  This update
9649 	 * can be relied upon to perform any cache operations that are
9650 	 * required for data coherence.
9651 	 */
9652 	if ((m->flags & PG_FICTITIOUS) == 0 &&
9653 	    pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9654 	    m->md.pat_mode))
9655 		panic("memory attribute change on the direct map failed");
9656 }
9657 
9658 void
pmap_page_set_memattr_noflush(vm_page_t m,vm_memattr_t ma)9659 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9660 {
9661 	int error;
9662 
9663 	m->md.pat_mode = ma;
9664 
9665 	if ((m->flags & PG_FICTITIOUS) != 0)
9666 		return;
9667 	PMAP_LOCK(kernel_pmap);
9668 	error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9669 	    PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9670 	PMAP_UNLOCK(kernel_pmap);
9671 	if (error != 0)
9672 		panic("memory attribute change on the direct map failed");
9673 }
9674 
9675 /*
9676  * Changes the specified virtual address range's memory type to that given by
9677  * the parameter "mode".  The specified virtual address range must be
9678  * completely contained within either the direct map or the kernel map.  If
9679  * the virtual address range is contained within the kernel map, then the
9680  * memory type for each of the corresponding ranges of the direct map is also
9681  * changed.  (The corresponding ranges of the direct map are those ranges that
9682  * map the same physical pages as the specified virtual address range.)  These
9683  * changes to the direct map are necessary because Intel describes the
9684  * behavior of their processors as "undefined" if two or more mappings to the
9685  * same physical page have different memory types.
9686  *
9687  * Returns zero if the change completed successfully, and either EINVAL or
9688  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
9689  * of the virtual address range was not mapped, and ENOMEM is returned if
9690  * there was insufficient memory available to complete the change.  In the
9691  * latter case, the memory type may have been changed on some part of the
9692  * virtual address range or the direct map.
9693  */
9694 int
pmap_change_attr(vm_offset_t va,vm_size_t size,int mode)9695 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9696 {
9697 	int error;
9698 
9699 	PMAP_LOCK(kernel_pmap);
9700 	error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9701 	    MAPDEV_FLUSHCACHE);
9702 	PMAP_UNLOCK(kernel_pmap);
9703 	return (error);
9704 }
9705 
9706 /*
9707  * Changes the specified virtual address range's protections to those
9708  * specified by "prot".  Like pmap_change_attr(), protections for aliases
9709  * in the direct map are updated as well.  Protections on aliasing mappings may
9710  * be a subset of the requested protections; for example, mappings in the direct
9711  * map are never executable.
9712  */
9713 int
pmap_change_prot(vm_offset_t va,vm_size_t size,vm_prot_t prot)9714 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9715 {
9716 	int error;
9717 
9718 	/* Only supported within the kernel map. */
9719 	if (va < VM_MIN_KERNEL_ADDRESS)
9720 		return (EINVAL);
9721 
9722 	PMAP_LOCK(kernel_pmap);
9723 	error = pmap_change_props_locked(va, size, prot, -1,
9724 	    MAPDEV_ASSERTVALID);
9725 	PMAP_UNLOCK(kernel_pmap);
9726 	return (error);
9727 }
9728 
9729 static int
pmap_change_props_locked(vm_offset_t va,vm_size_t size,vm_prot_t prot,int mode,int flags)9730 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9731     int mode, int flags)
9732 {
9733 	vm_offset_t base, offset, tmpva;
9734 	vm_paddr_t pa_start, pa_end, pa_end1;
9735 	pdp_entry_t *pdpe;
9736 	pd_entry_t *pde, pde_bits, pde_mask;
9737 	pt_entry_t *pte, pte_bits, pte_mask;
9738 	int error;
9739 	bool changed;
9740 
9741 	PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9742 	base = trunc_page(va);
9743 	offset = va & PAGE_MASK;
9744 	size = round_page(offset + size);
9745 
9746 	/*
9747 	 * Only supported on kernel virtual addresses, including the direct
9748 	 * map but excluding the recursive map.
9749 	 */
9750 	if (base < DMAP_MIN_ADDRESS)
9751 		return (EINVAL);
9752 
9753 	/*
9754 	 * Construct our flag sets and masks.  "bits" is the subset of
9755 	 * "mask" that will be set in each modified PTE.
9756 	 *
9757 	 * Mappings in the direct map are never allowed to be executable.
9758 	 */
9759 	pde_bits = pte_bits = 0;
9760 	pde_mask = pte_mask = 0;
9761 	if (mode != -1) {
9762 		pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9763 		pde_mask |= X86_PG_PDE_CACHE;
9764 		pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9765 		pte_mask |= X86_PG_PTE_CACHE;
9766 	}
9767 	if (prot != VM_PROT_NONE) {
9768 		if ((prot & VM_PROT_WRITE) != 0) {
9769 			pde_bits |= X86_PG_RW;
9770 			pte_bits |= X86_PG_RW;
9771 		}
9772 		if ((prot & VM_PROT_EXECUTE) == 0 ||
9773 		    va < VM_MIN_KERNEL_ADDRESS) {
9774 			pde_bits |= pg_nx;
9775 			pte_bits |= pg_nx;
9776 		}
9777 		pde_mask |= X86_PG_RW | pg_nx;
9778 		pte_mask |= X86_PG_RW | pg_nx;
9779 	}
9780 
9781 	/*
9782 	 * Pages that aren't mapped aren't supported.  Also break down 2MB pages
9783 	 * into 4KB pages if required.
9784 	 */
9785 	for (tmpva = base; tmpva < base + size; ) {
9786 		pdpe = pmap_pdpe(kernel_pmap, tmpva);
9787 		if (pdpe == NULL || *pdpe == 0) {
9788 			KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9789 			    ("%s: addr %#lx is not mapped", __func__, tmpva));
9790 			return (EINVAL);
9791 		}
9792 		if (*pdpe & PG_PS) {
9793 			/*
9794 			 * If the current 1GB page already has the required
9795 			 * properties, then we need not demote this page.  Just
9796 			 * increment tmpva to the next 1GB page frame.
9797 			 */
9798 			if ((*pdpe & pde_mask) == pde_bits) {
9799 				tmpva = trunc_1gpage(tmpva) + NBPDP;
9800 				continue;
9801 			}
9802 
9803 			/*
9804 			 * If the current offset aligns with a 1GB page frame
9805 			 * and there is at least 1GB left within the range, then
9806 			 * we need not break down this page into 2MB pages.
9807 			 */
9808 			if ((tmpva & PDPMASK) == 0 &&
9809 			    tmpva + PDPMASK < base + size) {
9810 				tmpva += NBPDP;
9811 				continue;
9812 			}
9813 			if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9814 				return (ENOMEM);
9815 		}
9816 		pde = pmap_pdpe_to_pde(pdpe, tmpva);
9817 		if (*pde == 0) {
9818 			KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9819 			    ("%s: addr %#lx is not mapped", __func__, tmpva));
9820 			return (EINVAL);
9821 		}
9822 		if (*pde & PG_PS) {
9823 			/*
9824 			 * If the current 2MB page already has the required
9825 			 * properties, then we need not demote this page.  Just
9826 			 * increment tmpva to the next 2MB page frame.
9827 			 */
9828 			if ((*pde & pde_mask) == pde_bits) {
9829 				tmpva = trunc_2mpage(tmpva) + NBPDR;
9830 				continue;
9831 			}
9832 
9833 			/*
9834 			 * If the current offset aligns with a 2MB page frame
9835 			 * and there is at least 2MB left within the range, then
9836 			 * we need not break down this page into 4KB pages.
9837 			 */
9838 			if ((tmpva & PDRMASK) == 0 &&
9839 			    tmpva + PDRMASK < base + size) {
9840 				tmpva += NBPDR;
9841 				continue;
9842 			}
9843 			if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9844 				return (ENOMEM);
9845 		}
9846 		pte = pmap_pde_to_pte(pde, tmpva);
9847 		if (*pte == 0) {
9848 			KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9849 			    ("%s: addr %#lx is not mapped", __func__, tmpva));
9850 			return (EINVAL);
9851 		}
9852 		tmpva += PAGE_SIZE;
9853 	}
9854 	error = 0;
9855 
9856 	/*
9857 	 * Ok, all the pages exist, so run through them updating their
9858 	 * properties if required.
9859 	 */
9860 	changed = false;
9861 	pa_start = pa_end = 0;
9862 	for (tmpva = base; tmpva < base + size; ) {
9863 		pdpe = pmap_pdpe(kernel_pmap, tmpva);
9864 		if (*pdpe & PG_PS) {
9865 			if ((*pdpe & pde_mask) != pde_bits) {
9866 				pmap_pte_props(pdpe, pde_bits, pde_mask);
9867 				changed = true;
9868 			}
9869 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9870 			    (*pdpe & PG_PS_FRAME) < dmaplimit) {
9871 				if (pa_start == pa_end) {
9872 					/* Start physical address run. */
9873 					pa_start = *pdpe & PG_PS_FRAME;
9874 					pa_end = pa_start + NBPDP;
9875 				} else if (pa_end == (*pdpe & PG_PS_FRAME))
9876 					pa_end += NBPDP;
9877 				else {
9878 					/* Run ended, update direct map. */
9879 					error = pmap_change_props_locked(
9880 					    PHYS_TO_DMAP(pa_start),
9881 					    pa_end - pa_start, prot, mode,
9882 					    flags);
9883 					if (error != 0)
9884 						break;
9885 					/* Start physical address run. */
9886 					pa_start = *pdpe & PG_PS_FRAME;
9887 					pa_end = pa_start + NBPDP;
9888 				}
9889 			}
9890 			tmpva = trunc_1gpage(tmpva) + NBPDP;
9891 			continue;
9892 		}
9893 		pde = pmap_pdpe_to_pde(pdpe, tmpva);
9894 		if (*pde & PG_PS) {
9895 			if ((*pde & pde_mask) != pde_bits) {
9896 				pmap_pte_props(pde, pde_bits, pde_mask);
9897 				changed = true;
9898 			}
9899 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9900 			    (*pde & PG_PS_FRAME) < dmaplimit) {
9901 				if (pa_start == pa_end) {
9902 					/* Start physical address run. */
9903 					pa_start = *pde & PG_PS_FRAME;
9904 					pa_end = pa_start + NBPDR;
9905 				} else if (pa_end == (*pde & PG_PS_FRAME))
9906 					pa_end += NBPDR;
9907 				else {
9908 					/* Run ended, update direct map. */
9909 					error = pmap_change_props_locked(
9910 					    PHYS_TO_DMAP(pa_start),
9911 					    pa_end - pa_start, prot, mode,
9912 					    flags);
9913 					if (error != 0)
9914 						break;
9915 					/* Start physical address run. */
9916 					pa_start = *pde & PG_PS_FRAME;
9917 					pa_end = pa_start + NBPDR;
9918 				}
9919 			}
9920 			tmpva = trunc_2mpage(tmpva) + NBPDR;
9921 		} else {
9922 			pte = pmap_pde_to_pte(pde, tmpva);
9923 			if ((*pte & pte_mask) != pte_bits) {
9924 				pmap_pte_props(pte, pte_bits, pte_mask);
9925 				changed = true;
9926 			}
9927 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9928 			    (*pte & PG_FRAME) < dmaplimit) {
9929 				if (pa_start == pa_end) {
9930 					/* Start physical address run. */
9931 					pa_start = *pte & PG_FRAME;
9932 					pa_end = pa_start + PAGE_SIZE;
9933 				} else if (pa_end == (*pte & PG_FRAME))
9934 					pa_end += PAGE_SIZE;
9935 				else {
9936 					/* Run ended, update direct map. */
9937 					error = pmap_change_props_locked(
9938 					    PHYS_TO_DMAP(pa_start),
9939 					    pa_end - pa_start, prot, mode,
9940 					    flags);
9941 					if (error != 0)
9942 						break;
9943 					/* Start physical address run. */
9944 					pa_start = *pte & PG_FRAME;
9945 					pa_end = pa_start + PAGE_SIZE;
9946 				}
9947 			}
9948 			tmpva += PAGE_SIZE;
9949 		}
9950 	}
9951 	if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9952 		pa_end1 = MIN(pa_end, dmaplimit);
9953 		if (pa_start != pa_end1)
9954 			error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9955 			    pa_end1 - pa_start, prot, mode, flags);
9956 	}
9957 
9958 	/*
9959 	 * Flush CPU caches if required to make sure any data isn't cached that
9960 	 * shouldn't be, etc.
9961 	 */
9962 	if (changed) {
9963 		pmap_invalidate_range(kernel_pmap, base, tmpva);
9964 		if ((flags & MAPDEV_FLUSHCACHE) != 0)
9965 			pmap_invalidate_cache_range(base, tmpva);
9966 	}
9967 	return (error);
9968 }
9969 
9970 /*
9971  * Demotes any mapping within the direct map region that covers more than the
9972  * specified range of physical addresses.  This range's size must be a power
9973  * of two and its starting address must be a multiple of its size.  Since the
9974  * demotion does not change any attributes of the mapping, a TLB invalidation
9975  * is not mandatory.  The caller may, however, request a TLB invalidation.
9976  */
9977 void
pmap_demote_DMAP(vm_paddr_t base,vm_size_t len,bool invalidate)9978 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, bool invalidate)
9979 {
9980 	pdp_entry_t *pdpe;
9981 	pd_entry_t *pde;
9982 	vm_offset_t va;
9983 	bool changed;
9984 
9985 	if (len == 0)
9986 		return;
9987 	KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9988 	KASSERT((base & (len - 1)) == 0,
9989 	    ("pmap_demote_DMAP: base is not a multiple of len"));
9990 	if (len < NBPDP && base < dmaplimit) {
9991 		va = PHYS_TO_DMAP(base);
9992 		changed = false;
9993 		PMAP_LOCK(kernel_pmap);
9994 		pdpe = pmap_pdpe(kernel_pmap, va);
9995 		if ((*pdpe & X86_PG_V) == 0)
9996 			panic("pmap_demote_DMAP: invalid PDPE");
9997 		if ((*pdpe & PG_PS) != 0) {
9998 			if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9999 				panic("pmap_demote_DMAP: PDPE failed");
10000 			changed = true;
10001 		}
10002 		if (len < NBPDR) {
10003 			pde = pmap_pdpe_to_pde(pdpe, va);
10004 			if ((*pde & X86_PG_V) == 0)
10005 				panic("pmap_demote_DMAP: invalid PDE");
10006 			if ((*pde & PG_PS) != 0) {
10007 				if (!pmap_demote_pde(kernel_pmap, pde, va))
10008 					panic("pmap_demote_DMAP: PDE failed");
10009 				changed = true;
10010 			}
10011 		}
10012 		if (changed && invalidate)
10013 			pmap_invalidate_page(kernel_pmap, va);
10014 		PMAP_UNLOCK(kernel_pmap);
10015 	}
10016 }
10017 
10018 /*
10019  * Perform the pmap work for mincore(2).  If the page is not both referenced and
10020  * modified by this pmap, returns its physical address so that the caller can
10021  * find other mappings.
10022  */
10023 int
pmap_mincore(pmap_t pmap,vm_offset_t addr,vm_paddr_t * pap)10024 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
10025 {
10026 	pdp_entry_t *pdpe;
10027 	pd_entry_t *pdep;
10028 	pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
10029 	vm_paddr_t pa;
10030 	int val;
10031 
10032 	PG_A = pmap_accessed_bit(pmap);
10033 	PG_M = pmap_modified_bit(pmap);
10034 	PG_V = pmap_valid_bit(pmap);
10035 	PG_RW = pmap_rw_bit(pmap);
10036 
10037 	PMAP_LOCK(pmap);
10038 	pte = 0;
10039 	pa = 0;
10040 	val = 0;
10041 	pdpe = pmap_pdpe(pmap, addr);
10042 	if (pdpe == NULL)
10043 		goto out;
10044 	if ((*pdpe & PG_V) != 0) {
10045 		if ((*pdpe & PG_PS) != 0) {
10046 			pte = *pdpe;
10047 			pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
10048 			    PG_FRAME;
10049 			val = MINCORE_PSIND(2);
10050 		} else {
10051 			pdep = pmap_pde(pmap, addr);
10052 			if (pdep != NULL && (*pdep & PG_V) != 0) {
10053 				if ((*pdep & PG_PS) != 0) {
10054 					pte = *pdep;
10055 			/* Compute the physical address of the 4KB page. */
10056 					pa = ((pte & PG_PS_FRAME) | (addr &
10057 					    PDRMASK)) & PG_FRAME;
10058 					val = MINCORE_PSIND(1);
10059 				} else {
10060 					pte = *pmap_pde_to_pte(pdep, addr);
10061 					pa = pte & PG_FRAME;
10062 					val = 0;
10063 				}
10064 			}
10065 		}
10066 	}
10067 	if ((pte & PG_V) != 0) {
10068 		val |= MINCORE_INCORE;
10069 		if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
10070 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
10071 		if ((pte & PG_A) != 0)
10072 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
10073 	}
10074 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
10075 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
10076 	    (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
10077 		*pap = pa;
10078 	}
10079 out:
10080 	PMAP_UNLOCK(pmap);
10081 	return (val);
10082 }
10083 
10084 static uint64_t
pmap_pcid_alloc(pmap_t pmap,struct pmap_pcid * pcidp)10085 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
10086 {
10087 	uint32_t gen, new_gen, pcid_next;
10088 
10089 	CRITICAL_ASSERT(curthread);
10090 	gen = PCPU_GET(pcid_gen);
10091 	if (pcidp->pm_pcid == PMAP_PCID_KERN)
10092 		return (pti ? 0 : CR3_PCID_SAVE);
10093 	if (pcidp->pm_gen == gen)
10094 		return (CR3_PCID_SAVE);
10095 	pcid_next = PCPU_GET(pcid_next);
10096 	KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
10097 	    (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
10098 	    ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
10099 	if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
10100 	    (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
10101 		new_gen = gen + 1;
10102 		if (new_gen == 0)
10103 			new_gen = 1;
10104 		PCPU_SET(pcid_gen, new_gen);
10105 		pcid_next = PMAP_PCID_KERN + 1;
10106 	} else {
10107 		new_gen = gen;
10108 	}
10109 	pcidp->pm_pcid = pcid_next;
10110 	pcidp->pm_gen = new_gen;
10111 	PCPU_SET(pcid_next, pcid_next + 1);
10112 	return (0);
10113 }
10114 
10115 static uint64_t
pmap_pcid_alloc_checked(pmap_t pmap,struct pmap_pcid * pcidp)10116 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10117 {
10118 	uint64_t cached;
10119 
10120 	cached = pmap_pcid_alloc(pmap, pcidp);
10121 	KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10122 	    ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10123 	KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10124 	    ("non-kernel pmap pmap %p cpu %d pcid %#x",
10125 	    pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10126 	return (cached);
10127 }
10128 
10129 static void
pmap_activate_sw_pti_post(struct thread * td,pmap_t pmap)10130 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10131 {
10132 
10133 	PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10134 	    PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10135 }
10136 
10137 static void
pmap_activate_sw_pcid_pti(struct thread * td,pmap_t pmap,u_int cpuid)10138 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10139 {
10140 	pmap_t old_pmap;
10141 	struct pmap_pcid *pcidp, *old_pcidp;
10142 	uint64_t cached, cr3, kcr3, ucr3;
10143 
10144 	KASSERT((read_rflags() & PSL_I) == 0,
10145 	    ("PCID needs interrupts disabled in pmap_activate_sw()"));
10146 
10147 	/* See the comment in pmap_invalidate_page_pcid(). */
10148 	if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10149 		PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10150 		old_pmap = PCPU_GET(curpmap);
10151 		MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10152 		old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10153 		old_pcidp->pm_gen = 0;
10154 	}
10155 
10156 	pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10157 	cached = pmap_pcid_alloc_checked(pmap, pcidp);
10158 	cr3 = rcr3();
10159 	if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10160 		load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10161 	PCPU_SET(curpmap, pmap);
10162 	kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10163 	ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10164 
10165 	if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10166 		PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10167 
10168 	PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10169 	PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10170 	if (cached)
10171 		counter_u64_add(pcid_save_cnt, 1);
10172 
10173 	pmap_activate_sw_pti_post(td, pmap);
10174 }
10175 
10176 static void
pmap_activate_sw_pcid_nopti(struct thread * td __unused,pmap_t pmap,u_int cpuid)10177 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10178     u_int cpuid)
10179 {
10180 	struct pmap_pcid *pcidp;
10181 	uint64_t cached, cr3;
10182 
10183 	KASSERT((read_rflags() & PSL_I) == 0,
10184 	    ("PCID needs interrupts disabled in pmap_activate_sw()"));
10185 
10186 	pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10187 	cached = pmap_pcid_alloc_checked(pmap, pcidp);
10188 	cr3 = rcr3();
10189 	if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10190 		load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10191 	PCPU_SET(curpmap, pmap);
10192 	if (cached)
10193 		counter_u64_add(pcid_save_cnt, 1);
10194 }
10195 
10196 static void
pmap_activate_sw_nopcid_nopti(struct thread * td __unused,pmap_t pmap,u_int cpuid __unused)10197 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10198     u_int cpuid __unused)
10199 {
10200 
10201 	load_cr3(pmap->pm_cr3);
10202 	PCPU_SET(curpmap, pmap);
10203 }
10204 
10205 static void
pmap_activate_sw_nopcid_pti(struct thread * td,pmap_t pmap,u_int cpuid __unused)10206 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10207     u_int cpuid __unused)
10208 {
10209 
10210 	pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10211 	PCPU_SET(kcr3, pmap->pm_cr3);
10212 	PCPU_SET(ucr3, pmap->pm_ucr3);
10213 	pmap_activate_sw_pti_post(td, pmap);
10214 }
10215 
10216 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10217     u_int))
10218 {
10219 
10220 	if (pmap_pcid_enabled && pti)
10221 		return (pmap_activate_sw_pcid_pti);
10222 	else if (pmap_pcid_enabled && !pti)
10223 		return (pmap_activate_sw_pcid_nopti);
10224 	else if (!pmap_pcid_enabled && pti)
10225 		return (pmap_activate_sw_nopcid_pti);
10226 	else /* if (!pmap_pcid_enabled && !pti) */
10227 		return (pmap_activate_sw_nopcid_nopti);
10228 }
10229 
10230 void
pmap_activate_sw(struct thread * td)10231 pmap_activate_sw(struct thread *td)
10232 {
10233 	pmap_t oldpmap, pmap;
10234 	u_int cpuid;
10235 
10236 	oldpmap = PCPU_GET(curpmap);
10237 	pmap = vmspace_pmap(td->td_proc->p_vmspace);
10238 	if (oldpmap == pmap) {
10239 		if (cpu_vendor_id != CPU_VENDOR_INTEL)
10240 			mfence();
10241 		return;
10242 	}
10243 	cpuid = PCPU_GET(cpuid);
10244 #ifdef SMP
10245 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10246 #else
10247 	CPU_SET(cpuid, &pmap->pm_active);
10248 #endif
10249 	pmap_activate_sw_mode(td, pmap, cpuid);
10250 #ifdef SMP
10251 	CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10252 #else
10253 	CPU_CLR(cpuid, &oldpmap->pm_active);
10254 #endif
10255 }
10256 
10257 void
pmap_activate(struct thread * td)10258 pmap_activate(struct thread *td)
10259 {
10260 	/*
10261 	 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10262 	 * invalidate_all IPI, which checks for curpmap ==
10263 	 * smp_tlb_pmap.  The below sequence of operations has a
10264 	 * window where %CR3 is loaded with the new pmap's PML4
10265 	 * address, but the curpmap value has not yet been updated.
10266 	 * This causes the invltlb IPI handler, which is called
10267 	 * between the updates, to execute as a NOP, which leaves
10268 	 * stale TLB entries.
10269 	 *
10270 	 * Note that the most common use of pmap_activate_sw(), from
10271 	 * a context switch, is immune to this race, because
10272 	 * interrupts are disabled (while the thread lock is owned),
10273 	 * so the IPI is delayed until after curpmap is updated.  Protect
10274 	 * other callers in a similar way, by disabling interrupts
10275 	 * around the %cr3 register reload and curpmap assignment.
10276 	 */
10277 	spinlock_enter();
10278 	pmap_activate_sw(td);
10279 	spinlock_exit();
10280 }
10281 
10282 void
pmap_activate_boot(pmap_t pmap)10283 pmap_activate_boot(pmap_t pmap)
10284 {
10285 	uint64_t kcr3;
10286 	u_int cpuid;
10287 
10288 	/*
10289 	 * kernel_pmap must be never deactivated, and we ensure that
10290 	 * by never activating it at all.
10291 	 */
10292 	MPASS(pmap != kernel_pmap);
10293 
10294 	cpuid = PCPU_GET(cpuid);
10295 #ifdef SMP
10296 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10297 #else
10298 	CPU_SET(cpuid, &pmap->pm_active);
10299 #endif
10300 	PCPU_SET(curpmap, pmap);
10301 	if (pti) {
10302 		kcr3 = pmap->pm_cr3;
10303 		if (pmap_pcid_enabled)
10304 			kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10305 	} else {
10306 		kcr3 = PMAP_NO_CR3;
10307 	}
10308 	PCPU_SET(kcr3, kcr3);
10309 	PCPU_SET(ucr3, PMAP_NO_CR3);
10310 }
10311 
10312 void
pmap_active_cpus(pmap_t pmap,cpuset_t * res)10313 pmap_active_cpus(pmap_t pmap, cpuset_t *res)
10314 {
10315 	*res = pmap->pm_active;
10316 }
10317 
10318 void
pmap_sync_icache(pmap_t pm,vm_offset_t va,vm_size_t sz)10319 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10320 {
10321 }
10322 
10323 /*
10324  *	Increase the starting virtual address of the given mapping if a
10325  *	different alignment might result in more superpage mappings.
10326  */
10327 void
pmap_align_superpage(vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t size)10328 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10329     vm_offset_t *addr, vm_size_t size)
10330 {
10331 	vm_offset_t superpage_offset;
10332 
10333 	if (size < NBPDR)
10334 		return;
10335 	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10336 		offset += ptoa(object->pg_color);
10337 	superpage_offset = offset & PDRMASK;
10338 	if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10339 	    (*addr & PDRMASK) == superpage_offset)
10340 		return;
10341 	if ((*addr & PDRMASK) < superpage_offset)
10342 		*addr = (*addr & ~PDRMASK) + superpage_offset;
10343 	else
10344 		*addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10345 }
10346 
10347 #ifdef INVARIANTS
10348 static unsigned long num_dirty_emulations;
10349 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10350 	     &num_dirty_emulations, 0, NULL);
10351 
10352 static unsigned long num_accessed_emulations;
10353 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10354 	     &num_accessed_emulations, 0, NULL);
10355 
10356 static unsigned long num_superpage_accessed_emulations;
10357 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10358 	     &num_superpage_accessed_emulations, 0, NULL);
10359 
10360 static unsigned long ad_emulation_superpage_promotions;
10361 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10362 	     &ad_emulation_superpage_promotions, 0, NULL);
10363 #endif	/* INVARIANTS */
10364 
10365 int
pmap_emulate_accessed_dirty(pmap_t pmap,vm_offset_t va,int ftype)10366 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10367 {
10368 	int rv;
10369 	struct rwlock *lock;
10370 #if VM_NRESERVLEVEL > 0
10371 	vm_page_t m, mpte;
10372 #endif
10373 	pd_entry_t *pde;
10374 	pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10375 
10376 	KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10377 	    ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10378 
10379 	if (!pmap_emulate_ad_bits(pmap))
10380 		return (-1);
10381 
10382 	PG_A = pmap_accessed_bit(pmap);
10383 	PG_M = pmap_modified_bit(pmap);
10384 	PG_V = pmap_valid_bit(pmap);
10385 	PG_RW = pmap_rw_bit(pmap);
10386 
10387 	rv = -1;
10388 	lock = NULL;
10389 	PMAP_LOCK(pmap);
10390 
10391 	pde = pmap_pde(pmap, va);
10392 	if (pde == NULL || (*pde & PG_V) == 0)
10393 		goto done;
10394 
10395 	if ((*pde & PG_PS) != 0) {
10396 		if (ftype == VM_PROT_READ) {
10397 #ifdef INVARIANTS
10398 			atomic_add_long(&num_superpage_accessed_emulations, 1);
10399 #endif
10400 			*pde |= PG_A;
10401 			rv = 0;
10402 		}
10403 		goto done;
10404 	}
10405 
10406 	pte = pmap_pde_to_pte(pde, va);
10407 	if ((*pte & PG_V) == 0)
10408 		goto done;
10409 
10410 	if (ftype == VM_PROT_WRITE) {
10411 		if ((*pte & PG_RW) == 0)
10412 			goto done;
10413 		/*
10414 		 * Set the modified and accessed bits simultaneously.
10415 		 *
10416 		 * Intel EPT PTEs that do software emulation of A/D bits map
10417 		 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10418 		 * An EPT misconfiguration is triggered if the PTE is writable
10419 		 * but not readable (WR=10). This is avoided by setting PG_A
10420 		 * and PG_M simultaneously.
10421 		 */
10422 		*pte |= PG_M | PG_A;
10423 	} else {
10424 		*pte |= PG_A;
10425 	}
10426 
10427 #if VM_NRESERVLEVEL > 0
10428 	/* try to promote the mapping */
10429 	if (va < VM_MAXUSER_ADDRESS)
10430 		mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10431 	else
10432 		mpte = NULL;
10433 
10434 	m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10435 
10436 	if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10437 	    (m->flags & PG_FICTITIOUS) == 0 &&
10438 	    vm_reserv_level_iffullpop(m) == 0 &&
10439 	    pmap_promote_pde(pmap, pde, va, mpte, &lock)) {
10440 #ifdef INVARIANTS
10441 		atomic_add_long(&ad_emulation_superpage_promotions, 1);
10442 #endif
10443 	}
10444 #endif
10445 
10446 #ifdef INVARIANTS
10447 	if (ftype == VM_PROT_WRITE)
10448 		atomic_add_long(&num_dirty_emulations, 1);
10449 	else
10450 		atomic_add_long(&num_accessed_emulations, 1);
10451 #endif
10452 	rv = 0;		/* success */
10453 done:
10454 	if (lock != NULL)
10455 		rw_wunlock(lock);
10456 	PMAP_UNLOCK(pmap);
10457 	return (rv);
10458 }
10459 
10460 void
pmap_get_mapping(pmap_t pmap,vm_offset_t va,uint64_t * ptr,int * num)10461 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10462 {
10463 	pml4_entry_t *pml4;
10464 	pdp_entry_t *pdp;
10465 	pd_entry_t *pde;
10466 	pt_entry_t *pte, PG_V;
10467 	int idx;
10468 
10469 	idx = 0;
10470 	PG_V = pmap_valid_bit(pmap);
10471 	PMAP_LOCK(pmap);
10472 
10473 	pml4 = pmap_pml4e(pmap, va);
10474 	if (pml4 == NULL)
10475 		goto done;
10476 	ptr[idx++] = *pml4;
10477 	if ((*pml4 & PG_V) == 0)
10478 		goto done;
10479 
10480 	pdp = pmap_pml4e_to_pdpe(pml4, va);
10481 	ptr[idx++] = *pdp;
10482 	if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10483 		goto done;
10484 
10485 	pde = pmap_pdpe_to_pde(pdp, va);
10486 	ptr[idx++] = *pde;
10487 	if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10488 		goto done;
10489 
10490 	pte = pmap_pde_to_pte(pde, va);
10491 	ptr[idx++] = *pte;
10492 
10493 done:
10494 	PMAP_UNLOCK(pmap);
10495 	*num = idx;
10496 }
10497 
10498 /**
10499  * Get the kernel virtual address of a set of physical pages. If there are
10500  * physical addresses not covered by the DMAP perform a transient mapping
10501  * that will be removed when calling pmap_unmap_io_transient.
10502  *
10503  * \param page        The pages the caller wishes to obtain the virtual
10504  *                    address on the kernel memory map.
10505  * \param vaddr       On return contains the kernel virtual memory address
10506  *                    of the pages passed in the page parameter.
10507  * \param count       Number of pages passed in.
10508  * \param can_fault   true if the thread using the mapped pages can take
10509  *                    page faults, false otherwise.
10510  *
10511  * \returns true if the caller must call pmap_unmap_io_transient when
10512  *          finished or false otherwise.
10513  *
10514  */
10515 bool
pmap_map_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)10516 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10517     bool can_fault)
10518 {
10519 	vm_paddr_t paddr;
10520 	bool needs_mapping;
10521 	int error __unused, i;
10522 
10523 	/*
10524 	 * Allocate any KVA space that we need, this is done in a separate
10525 	 * loop to prevent calling vmem_alloc while pinned.
10526 	 */
10527 	needs_mapping = false;
10528 	for (i = 0; i < count; i++) {
10529 		paddr = VM_PAGE_TO_PHYS(page[i]);
10530 		if (__predict_false(paddr >= dmaplimit)) {
10531 			error = vmem_alloc(kernel_arena, PAGE_SIZE,
10532 			    M_BESTFIT | M_WAITOK, &vaddr[i]);
10533 			KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10534 			needs_mapping = true;
10535 		} else {
10536 			vaddr[i] = PHYS_TO_DMAP(paddr);
10537 		}
10538 	}
10539 
10540 	/* Exit early if everything is covered by the DMAP */
10541 	if (!needs_mapping)
10542 		return (false);
10543 
10544 	/*
10545 	 * NB:  The sequence of updating a page table followed by accesses
10546 	 * to the corresponding pages used in the !DMAP case is subject to
10547 	 * the situation described in the "AMD64 Architecture Programmer's
10548 	 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10549 	 * Coherency Considerations".  Therefore, issuing the INVLPG right
10550 	 * after modifying the PTE bits is crucial.
10551 	 */
10552 	if (!can_fault)
10553 		sched_pin();
10554 	for (i = 0; i < count; i++) {
10555 		paddr = VM_PAGE_TO_PHYS(page[i]);
10556 		if (paddr >= dmaplimit) {
10557 			if (can_fault) {
10558 				/*
10559 				 * Slow path, since we can get page faults
10560 				 * while mappings are active don't pin the
10561 				 * thread to the CPU and instead add a global
10562 				 * mapping visible to all CPUs.
10563 				 */
10564 				pmap_qenter(vaddr[i], &page[i], 1);
10565 			} else {
10566 				pmap_kenter_attr(vaddr[i], paddr,
10567 				    page[i]->md.pat_mode);
10568 				pmap_invlpg(kernel_pmap, vaddr[i]);
10569 			}
10570 		}
10571 	}
10572 
10573 	return (needs_mapping);
10574 }
10575 
10576 void
pmap_unmap_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)10577 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10578     bool can_fault)
10579 {
10580 	vm_paddr_t paddr;
10581 	int i;
10582 
10583 	if (!can_fault)
10584 		sched_unpin();
10585 	for (i = 0; i < count; i++) {
10586 		paddr = VM_PAGE_TO_PHYS(page[i]);
10587 		if (paddr >= dmaplimit) {
10588 			if (can_fault)
10589 				pmap_qremove(vaddr[i], 1);
10590 			vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10591 		}
10592 	}
10593 }
10594 
10595 vm_offset_t
pmap_quick_enter_page(vm_page_t m)10596 pmap_quick_enter_page(vm_page_t m)
10597 {
10598 	vm_paddr_t paddr;
10599 
10600 	paddr = VM_PAGE_TO_PHYS(m);
10601 	if (paddr < dmaplimit)
10602 		return (PHYS_TO_DMAP(paddr));
10603 	mtx_lock_spin(&qframe_mtx);
10604 	KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10605 
10606 	/*
10607 	 * Since qframe is exclusively mapped by us, and we do not set
10608 	 * PG_G, we can use INVLPG here.
10609 	 */
10610 	invlpg(qframe);
10611 
10612 	pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10613 	    X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, false));
10614 	return (qframe);
10615 }
10616 
10617 void
pmap_quick_remove_page(vm_offset_t addr)10618 pmap_quick_remove_page(vm_offset_t addr)
10619 {
10620 
10621 	if (addr != qframe)
10622 		return;
10623 	pte_store(vtopte(qframe), 0);
10624 	mtx_unlock_spin(&qframe_mtx);
10625 }
10626 
10627 /*
10628  * Pdp pages from the large map are managed differently from either
10629  * kernel or user page table pages.  They are permanently allocated at
10630  * initialization time, and their reference count is permanently set to
10631  * zero.  The pml4 entries pointing to those pages are copied into
10632  * each allocated pmap.
10633  *
10634  * In contrast, pd and pt pages are managed like user page table
10635  * pages.  They are dynamically allocated, and their reference count
10636  * represents the number of valid entries within the page.
10637  */
10638 static vm_page_t
pmap_large_map_getptp_unlocked(void)10639 pmap_large_map_getptp_unlocked(void)
10640 {
10641 	return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10642 }
10643 
10644 static vm_page_t
pmap_large_map_getptp(void)10645 pmap_large_map_getptp(void)
10646 {
10647 	vm_page_t m;
10648 
10649 	PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10650 	m = pmap_large_map_getptp_unlocked();
10651 	if (m == NULL) {
10652 		PMAP_UNLOCK(kernel_pmap);
10653 		vm_wait(NULL);
10654 		PMAP_LOCK(kernel_pmap);
10655 		/* Callers retry. */
10656 	}
10657 	return (m);
10658 }
10659 
10660 static pdp_entry_t *
pmap_large_map_pdpe(vm_offset_t va)10661 pmap_large_map_pdpe(vm_offset_t va)
10662 {
10663 	vm_pindex_t pml4_idx;
10664 	vm_paddr_t mphys;
10665 
10666 	pml4_idx = pmap_pml4e_index(va);
10667 	KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10668 	    ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10669 	    "%#jx lm_ents %d",
10670 	    (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10671 	KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10672 	    ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10673 	    "LMSPML4I %#jx lm_ents %d",
10674 	    (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10675 	mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10676 	return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10677 }
10678 
10679 static pd_entry_t *
pmap_large_map_pde(vm_offset_t va)10680 pmap_large_map_pde(vm_offset_t va)
10681 {
10682 	pdp_entry_t *pdpe;
10683 	vm_page_t m;
10684 	vm_paddr_t mphys;
10685 
10686 retry:
10687 	pdpe = pmap_large_map_pdpe(va);
10688 	if (*pdpe == 0) {
10689 		m = pmap_large_map_getptp();
10690 		if (m == NULL)
10691 			goto retry;
10692 		mphys = VM_PAGE_TO_PHYS(m);
10693 		*pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10694 	} else {
10695 		MPASS((*pdpe & X86_PG_PS) == 0);
10696 		mphys = *pdpe & PG_FRAME;
10697 	}
10698 	return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10699 }
10700 
10701 static pt_entry_t *
pmap_large_map_pte(vm_offset_t va)10702 pmap_large_map_pte(vm_offset_t va)
10703 {
10704 	pd_entry_t *pde;
10705 	vm_page_t m;
10706 	vm_paddr_t mphys;
10707 
10708 retry:
10709 	pde = pmap_large_map_pde(va);
10710 	if (*pde == 0) {
10711 		m = pmap_large_map_getptp();
10712 		if (m == NULL)
10713 			goto retry;
10714 		mphys = VM_PAGE_TO_PHYS(m);
10715 		*pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10716 		PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10717 	} else {
10718 		MPASS((*pde & X86_PG_PS) == 0);
10719 		mphys = *pde & PG_FRAME;
10720 	}
10721 	return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10722 }
10723 
10724 static vm_paddr_t
pmap_large_map_kextract(vm_offset_t va)10725 pmap_large_map_kextract(vm_offset_t va)
10726 {
10727 	pdp_entry_t *pdpe, pdp;
10728 	pd_entry_t *pde, pd;
10729 	pt_entry_t *pte, pt;
10730 
10731 	KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10732 	    ("not largemap range %#lx", (u_long)va));
10733 	pdpe = pmap_large_map_pdpe(va);
10734 	pdp = *pdpe;
10735 	KASSERT((pdp & X86_PG_V) != 0,
10736 	    ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10737 	    (u_long)pdpe, pdp));
10738 	if ((pdp & X86_PG_PS) != 0) {
10739 		KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10740 		    ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10741 		    (u_long)pdpe, pdp));
10742 		return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10743 	}
10744 	pde = pmap_pdpe_to_pde(pdpe, va);
10745 	pd = *pde;
10746 	KASSERT((pd & X86_PG_V) != 0,
10747 	    ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10748 	if ((pd & X86_PG_PS) != 0)
10749 		return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10750 	pte = pmap_pde_to_pte(pde, va);
10751 	pt = *pte;
10752 	KASSERT((pt & X86_PG_V) != 0,
10753 	    ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10754 	return ((pt & PG_FRAME) | (va & PAGE_MASK));
10755 }
10756 
10757 static int
pmap_large_map_getva(vm_size_t len,vm_offset_t align,vm_offset_t phase,vmem_addr_t * vmem_res)10758 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10759     vmem_addr_t *vmem_res)
10760 {
10761 
10762 	/*
10763 	 * Large mappings are all but static.  Consequently, there
10764 	 * is no point in waiting for an earlier allocation to be
10765 	 * freed.
10766 	 */
10767 	return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10768 	    VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10769 }
10770 
10771 int
pmap_large_map(vm_paddr_t spa,vm_size_t len,void ** addr,vm_memattr_t mattr)10772 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10773     vm_memattr_t mattr)
10774 {
10775 	pdp_entry_t *pdpe;
10776 	pd_entry_t *pde;
10777 	pt_entry_t *pte;
10778 	vm_offset_t va, inc;
10779 	vmem_addr_t vmem_res;
10780 	vm_paddr_t pa;
10781 	int error;
10782 
10783 	if (len == 0 || spa + len < spa)
10784 		return (EINVAL);
10785 
10786 	/* See if DMAP can serve. */
10787 	if (spa + len <= dmaplimit) {
10788 		va = PHYS_TO_DMAP(spa);
10789 		*addr = (void *)va;
10790 		return (pmap_change_attr(va, len, mattr));
10791 	}
10792 
10793 	/*
10794 	 * No, allocate KVA.  Fit the address with best possible
10795 	 * alignment for superpages.  Fall back to worse align if
10796 	 * failed.
10797 	 */
10798 	error = ENOMEM;
10799 	if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10800 	    NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10801 		error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10802 		    &vmem_res);
10803 	if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10804 	    NBPDR) + NBPDR)
10805 		error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10806 		    &vmem_res);
10807 	if (error != 0)
10808 		error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10809 	if (error != 0)
10810 		return (error);
10811 
10812 	/*
10813 	 * Fill pagetable.  PG_M is not pre-set, we scan modified bits
10814 	 * in the pagetable to minimize flushing.  No need to
10815 	 * invalidate TLB, since we only update invalid entries.
10816 	 */
10817 	PMAP_LOCK(kernel_pmap);
10818 	for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10819 	    len -= inc) {
10820 		if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10821 		    (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10822 			pdpe = pmap_large_map_pdpe(va);
10823 			MPASS(*pdpe == 0);
10824 			*pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10825 			    X86_PG_V | X86_PG_A | pg_nx |
10826 			    pmap_cache_bits(kernel_pmap, mattr, true);
10827 			inc = NBPDP;
10828 		} else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10829 		    (va & PDRMASK) == 0) {
10830 			pde = pmap_large_map_pde(va);
10831 			MPASS(*pde == 0);
10832 			*pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10833 			    X86_PG_V | X86_PG_A | pg_nx |
10834 			    pmap_cache_bits(kernel_pmap, mattr, true);
10835 			PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10836 			    ref_count++;
10837 			inc = NBPDR;
10838 		} else {
10839 			pte = pmap_large_map_pte(va);
10840 			MPASS(*pte == 0);
10841 			*pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10842 			    X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10843 			    mattr, false);
10844 			PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10845 			    ref_count++;
10846 			inc = PAGE_SIZE;
10847 		}
10848 	}
10849 	PMAP_UNLOCK(kernel_pmap);
10850 	MPASS(len == 0);
10851 
10852 	*addr = (void *)vmem_res;
10853 	return (0);
10854 }
10855 
10856 void
pmap_large_unmap(void * svaa,vm_size_t len)10857 pmap_large_unmap(void *svaa, vm_size_t len)
10858 {
10859 	vm_offset_t sva, va;
10860 	vm_size_t inc;
10861 	pdp_entry_t *pdpe, pdp;
10862 	pd_entry_t *pde, pd;
10863 	pt_entry_t *pte;
10864 	vm_page_t m;
10865 	struct spglist spgf;
10866 
10867 	sva = (vm_offset_t)svaa;
10868 	if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10869 	    sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10870 		return;
10871 
10872 	SLIST_INIT(&spgf);
10873 	KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10874 	    PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10875 	    ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10876 	PMAP_LOCK(kernel_pmap);
10877 	for (va = sva; va < sva + len; va += inc) {
10878 		pdpe = pmap_large_map_pdpe(va);
10879 		pdp = *pdpe;
10880 		KASSERT((pdp & X86_PG_V) != 0,
10881 		    ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10882 		    (u_long)pdpe, pdp));
10883 		if ((pdp & X86_PG_PS) != 0) {
10884 			KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10885 			    ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10886 			    (u_long)pdpe, pdp));
10887 			KASSERT((va & PDPMASK) == 0,
10888 			    ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10889 			    (u_long)pdpe, pdp));
10890 			KASSERT(va + NBPDP <= sva + len,
10891 			    ("unmap covers partial 1GB page, sva %#lx va %#lx "
10892 			    "pdpe %#lx pdp %#lx len %#lx", sva, va,
10893 			    (u_long)pdpe, pdp, len));
10894 			*pdpe = 0;
10895 			inc = NBPDP;
10896 			continue;
10897 		}
10898 		pde = pmap_pdpe_to_pde(pdpe, va);
10899 		pd = *pde;
10900 		KASSERT((pd & X86_PG_V) != 0,
10901 		    ("invalid pd va %#lx pde %#lx pd %#lx", va,
10902 		    (u_long)pde, pd));
10903 		if ((pd & X86_PG_PS) != 0) {
10904 			KASSERT((va & PDRMASK) == 0,
10905 			    ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10906 			    (u_long)pde, pd));
10907 			KASSERT(va + NBPDR <= sva + len,
10908 			    ("unmap covers partial 2MB page, sva %#lx va %#lx "
10909 			    "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10910 			    pd, len));
10911 			pde_store(pde, 0);
10912 			inc = NBPDR;
10913 			m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10914 			m->ref_count--;
10915 			if (m->ref_count == 0) {
10916 				*pdpe = 0;
10917 				SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10918 			}
10919 			continue;
10920 		}
10921 		pte = pmap_pde_to_pte(pde, va);
10922 		KASSERT((*pte & X86_PG_V) != 0,
10923 		    ("invalid pte va %#lx pte %#lx pt %#lx", va,
10924 		    (u_long)pte, *pte));
10925 		pte_clear(pte);
10926 		inc = PAGE_SIZE;
10927 		m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10928 		m->ref_count--;
10929 		if (m->ref_count == 0) {
10930 			*pde = 0;
10931 			SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10932 			m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10933 			m->ref_count--;
10934 			if (m->ref_count == 0) {
10935 				*pdpe = 0;
10936 				SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10937 			}
10938 		}
10939 	}
10940 	pmap_invalidate_range(kernel_pmap, sva, sva + len);
10941 	PMAP_UNLOCK(kernel_pmap);
10942 	vm_page_free_pages_toq(&spgf, false);
10943 	vmem_free(large_vmem, sva, len);
10944 }
10945 
10946 static void
pmap_large_map_wb_fence_mfence(void)10947 pmap_large_map_wb_fence_mfence(void)
10948 {
10949 
10950 	mfence();
10951 }
10952 
10953 static void
pmap_large_map_wb_fence_atomic(void)10954 pmap_large_map_wb_fence_atomic(void)
10955 {
10956 
10957 	atomic_thread_fence_seq_cst();
10958 }
10959 
10960 static void
pmap_large_map_wb_fence_nop(void)10961 pmap_large_map_wb_fence_nop(void)
10962 {
10963 }
10964 
10965 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10966 {
10967 
10968 	if (cpu_vendor_id != CPU_VENDOR_INTEL)
10969 		return (pmap_large_map_wb_fence_mfence);
10970 	else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10971 	    CPUID_STDEXT_CLFLUSHOPT)) == 0)
10972 		return (pmap_large_map_wb_fence_atomic);
10973 	else
10974 		/* clflush is strongly enough ordered */
10975 		return (pmap_large_map_wb_fence_nop);
10976 }
10977 
10978 static void
pmap_large_map_flush_range_clwb(vm_offset_t va,vm_size_t len)10979 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10980 {
10981 
10982 	for (; len > 0; len -= cpu_clflush_line_size,
10983 	    va += cpu_clflush_line_size)
10984 		clwb(va);
10985 }
10986 
10987 static void
pmap_large_map_flush_range_clflushopt(vm_offset_t va,vm_size_t len)10988 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10989 {
10990 
10991 	for (; len > 0; len -= cpu_clflush_line_size,
10992 	    va += cpu_clflush_line_size)
10993 		clflushopt(va);
10994 }
10995 
10996 static void
pmap_large_map_flush_range_clflush(vm_offset_t va,vm_size_t len)10997 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10998 {
10999 
11000 	for (; len > 0; len -= cpu_clflush_line_size,
11001 	    va += cpu_clflush_line_size)
11002 		clflush(va);
11003 }
11004 
11005 static void
pmap_large_map_flush_range_nop(vm_offset_t sva __unused,vm_size_t len __unused)11006 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
11007 {
11008 }
11009 
11010 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
11011 {
11012 
11013 	if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
11014 		return (pmap_large_map_flush_range_clwb);
11015 	else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
11016 		return (pmap_large_map_flush_range_clflushopt);
11017 	else if ((cpu_feature & CPUID_CLFSH) != 0)
11018 		return (pmap_large_map_flush_range_clflush);
11019 	else
11020 		return (pmap_large_map_flush_range_nop);
11021 }
11022 
11023 static void
pmap_large_map_wb_large(vm_offset_t sva,vm_offset_t eva)11024 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
11025 {
11026 	volatile u_long *pe;
11027 	u_long p;
11028 	vm_offset_t va;
11029 	vm_size_t inc;
11030 	bool seen_other;
11031 
11032 	for (va = sva; va < eva; va += inc) {
11033 		inc = 0;
11034 		if ((amd_feature & AMDID_PAGE1GB) != 0) {
11035 			pe = (volatile u_long *)pmap_large_map_pdpe(va);
11036 			p = *pe;
11037 			if ((p & X86_PG_PS) != 0)
11038 				inc = NBPDP;
11039 		}
11040 		if (inc == 0) {
11041 			pe = (volatile u_long *)pmap_large_map_pde(va);
11042 			p = *pe;
11043 			if ((p & X86_PG_PS) != 0)
11044 				inc = NBPDR;
11045 		}
11046 		if (inc == 0) {
11047 			pe = (volatile u_long *)pmap_large_map_pte(va);
11048 			p = *pe;
11049 			inc = PAGE_SIZE;
11050 		}
11051 		seen_other = false;
11052 		for (;;) {
11053 			if ((p & X86_PG_AVAIL1) != 0) {
11054 				/*
11055 				 * Spin-wait for the end of a parallel
11056 				 * write-back.
11057 				 */
11058 				cpu_spinwait();
11059 				p = *pe;
11060 
11061 				/*
11062 				 * If we saw other write-back
11063 				 * occurring, we cannot rely on PG_M to
11064 				 * indicate state of the cache.  The
11065 				 * PG_M bit is cleared before the
11066 				 * flush to avoid ignoring new writes,
11067 				 * and writes which are relevant for
11068 				 * us might happen after.
11069 				 */
11070 				seen_other = true;
11071 				continue;
11072 			}
11073 
11074 			if ((p & X86_PG_M) != 0 || seen_other) {
11075 				if (!atomic_fcmpset_long(pe, &p,
11076 				    (p & ~X86_PG_M) | X86_PG_AVAIL1))
11077 					/*
11078 					 * If we saw PG_M without
11079 					 * PG_AVAIL1, and then on the
11080 					 * next attempt we do not
11081 					 * observe either PG_M or
11082 					 * PG_AVAIL1, the other
11083 					 * write-back started after us
11084 					 * and finished before us.  We
11085 					 * can rely on it doing our
11086 					 * work.
11087 					 */
11088 					continue;
11089 				pmap_large_map_flush_range(va, inc);
11090 				atomic_clear_long(pe, X86_PG_AVAIL1);
11091 			}
11092 			break;
11093 		}
11094 		maybe_yield();
11095 	}
11096 }
11097 
11098 /*
11099  * Write-back cache lines for the given address range.
11100  *
11101  * Must be called only on the range or sub-range returned from
11102  * pmap_large_map().  Must not be called on the coalesced ranges.
11103  *
11104  * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
11105  * instructions support.
11106  */
11107 void
pmap_large_map_wb(void * svap,vm_size_t len)11108 pmap_large_map_wb(void *svap, vm_size_t len)
11109 {
11110 	vm_offset_t eva, sva;
11111 
11112 	sva = (vm_offset_t)svap;
11113 	eva = sva + len;
11114 	pmap_large_map_wb_fence();
11115 	if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
11116 		pmap_large_map_flush_range(sva, len);
11117 	} else {
11118 		KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
11119 		    eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11120 		    ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11121 		pmap_large_map_wb_large(sva, eva);
11122 	}
11123 	pmap_large_map_wb_fence();
11124 }
11125 
11126 static vm_page_t
pmap_pti_alloc_page(void)11127 pmap_pti_alloc_page(void)
11128 {
11129 	vm_page_t m;
11130 
11131 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11132 	m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11133 	return (m);
11134 }
11135 
11136 static bool
pmap_pti_free_page(vm_page_t m)11137 pmap_pti_free_page(vm_page_t m)
11138 {
11139 	if (!vm_page_unwire_noq(m))
11140 		return (false);
11141 	vm_page_xbusy_claim(m);
11142 	vm_page_free_zero(m);
11143 	return (true);
11144 }
11145 
11146 static void
pmap_pti_init(void)11147 pmap_pti_init(void)
11148 {
11149 	vm_page_t pml4_pg;
11150 	pdp_entry_t *pdpe;
11151 	vm_offset_t va;
11152 	int i;
11153 
11154 	if (!pti)
11155 		return;
11156 	pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11157 	VM_OBJECT_WLOCK(pti_obj);
11158 	pml4_pg = pmap_pti_alloc_page();
11159 	pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11160 	for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11161 	    va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11162 		pdpe = pmap_pti_pdpe(va);
11163 		pmap_pti_wire_pte(pdpe);
11164 	}
11165 	pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11166 	    (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11167 	pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11168 	    sizeof(struct gate_descriptor) * NIDT, false);
11169 	CPU_FOREACH(i) {
11170 		/* Doublefault stack IST 1 */
11171 		va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11172 		pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11173 		/* NMI stack IST 2 */
11174 		va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11175 		pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11176 		/* MC# stack IST 3 */
11177 		va = __pcpu[i].pc_common_tss.tss_ist3 +
11178 		    sizeof(struct nmi_pcpu);
11179 		pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11180 		/* DB# stack IST 4 */
11181 		va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11182 		pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11183 	}
11184 	pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11185 	    true);
11186 	pti_finalized = true;
11187 	VM_OBJECT_WUNLOCK(pti_obj);
11188 }
11189 
11190 static void
pmap_cpu_init(void * arg __unused)11191 pmap_cpu_init(void *arg __unused)
11192 {
11193 	CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11194 	pmap_pti_init();
11195 }
11196 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11197 
11198 static pdp_entry_t *
pmap_pti_pdpe(vm_offset_t va)11199 pmap_pti_pdpe(vm_offset_t va)
11200 {
11201 	pml4_entry_t *pml4e;
11202 	pdp_entry_t *pdpe;
11203 	vm_page_t m;
11204 	vm_pindex_t pml4_idx;
11205 	vm_paddr_t mphys;
11206 
11207 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11208 
11209 	pml4_idx = pmap_pml4e_index(va);
11210 	pml4e = &pti_pml4[pml4_idx];
11211 	m = NULL;
11212 	if (*pml4e == 0) {
11213 		if (pti_finalized)
11214 			panic("pml4 alloc after finalization\n");
11215 		m = pmap_pti_alloc_page();
11216 		if (*pml4e != 0) {
11217 			pmap_pti_free_page(m);
11218 			mphys = *pml4e & ~PAGE_MASK;
11219 		} else {
11220 			mphys = VM_PAGE_TO_PHYS(m);
11221 			*pml4e = mphys | X86_PG_RW | X86_PG_V;
11222 		}
11223 	} else {
11224 		mphys = *pml4e & ~PAGE_MASK;
11225 	}
11226 	pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11227 	return (pdpe);
11228 }
11229 
11230 static void
pmap_pti_wire_pte(void * pte)11231 pmap_pti_wire_pte(void *pte)
11232 {
11233 	vm_page_t m;
11234 
11235 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11236 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11237 	m->ref_count++;
11238 }
11239 
11240 static void
pmap_pti_unwire_pde(void * pde,bool only_ref)11241 pmap_pti_unwire_pde(void *pde, bool only_ref)
11242 {
11243 	vm_page_t m;
11244 
11245 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11246 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11247 	MPASS(only_ref || m->ref_count > 1);
11248 	pmap_pti_free_page(m);
11249 }
11250 
11251 static void
pmap_pti_unwire_pte(void * pte,vm_offset_t va)11252 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11253 {
11254 	vm_page_t m;
11255 	pd_entry_t *pde;
11256 
11257 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11258 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11259 	if (pmap_pti_free_page(m)) {
11260 		pde = pmap_pti_pde(va);
11261 		MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11262 		*pde = 0;
11263 		pmap_pti_unwire_pde(pde, false);
11264 	}
11265 }
11266 
11267 static pd_entry_t *
pmap_pti_pde(vm_offset_t va)11268 pmap_pti_pde(vm_offset_t va)
11269 {
11270 	pdp_entry_t *pdpe;
11271 	pd_entry_t *pde;
11272 	vm_page_t m;
11273 	vm_pindex_t pd_idx;
11274 	vm_paddr_t mphys;
11275 
11276 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11277 
11278 	pdpe = pmap_pti_pdpe(va);
11279 	if (*pdpe == 0) {
11280 		m = pmap_pti_alloc_page();
11281 		if (*pdpe != 0) {
11282 			pmap_pti_free_page(m);
11283 			MPASS((*pdpe & X86_PG_PS) == 0);
11284 			mphys = *pdpe & ~PAGE_MASK;
11285 		} else {
11286 			mphys =  VM_PAGE_TO_PHYS(m);
11287 			*pdpe = mphys | X86_PG_RW | X86_PG_V;
11288 		}
11289 	} else {
11290 		MPASS((*pdpe & X86_PG_PS) == 0);
11291 		mphys = *pdpe & ~PAGE_MASK;
11292 	}
11293 
11294 	pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11295 	pd_idx = pmap_pde_index(va);
11296 	pde += pd_idx;
11297 	return (pde);
11298 }
11299 
11300 static pt_entry_t *
pmap_pti_pte(vm_offset_t va,bool * unwire_pde)11301 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11302 {
11303 	pd_entry_t *pde;
11304 	pt_entry_t *pte;
11305 	vm_page_t m;
11306 	vm_paddr_t mphys;
11307 
11308 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11309 
11310 	pde = pmap_pti_pde(va);
11311 	if (unwire_pde != NULL) {
11312 		*unwire_pde = true;
11313 		pmap_pti_wire_pte(pde);
11314 	}
11315 	if (*pde == 0) {
11316 		m = pmap_pti_alloc_page();
11317 		if (*pde != 0) {
11318 			pmap_pti_free_page(m);
11319 			MPASS((*pde & X86_PG_PS) == 0);
11320 			mphys = *pde & ~(PAGE_MASK | pg_nx);
11321 		} else {
11322 			mphys = VM_PAGE_TO_PHYS(m);
11323 			*pde = mphys | X86_PG_RW | X86_PG_V;
11324 			if (unwire_pde != NULL)
11325 				*unwire_pde = false;
11326 		}
11327 	} else {
11328 		MPASS((*pde & X86_PG_PS) == 0);
11329 		mphys = *pde & ~(PAGE_MASK | pg_nx);
11330 	}
11331 
11332 	pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11333 	pte += pmap_pte_index(va);
11334 
11335 	return (pte);
11336 }
11337 
11338 static void
pmap_pti_add_kva_locked(vm_offset_t sva,vm_offset_t eva,bool exec)11339 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11340 {
11341 	vm_paddr_t pa;
11342 	pd_entry_t *pde;
11343 	pt_entry_t *pte, ptev;
11344 	bool unwire_pde;
11345 
11346 	VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11347 
11348 	sva = trunc_page(sva);
11349 	MPASS(sva > VM_MAXUSER_ADDRESS);
11350 	eva = round_page(eva);
11351 	MPASS(sva < eva);
11352 	for (; sva < eva; sva += PAGE_SIZE) {
11353 		pte = pmap_pti_pte(sva, &unwire_pde);
11354 		pa = pmap_kextract(sva);
11355 		ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11356 		    (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11357 		    VM_MEMATTR_DEFAULT, false);
11358 		if (*pte == 0) {
11359 			pte_store(pte, ptev);
11360 			pmap_pti_wire_pte(pte);
11361 		} else {
11362 			KASSERT(!pti_finalized,
11363 			    ("pti overlap after fin %#lx %#lx %#lx",
11364 			    sva, *pte, ptev));
11365 			KASSERT(*pte == ptev,
11366 			    ("pti non-identical pte after fin %#lx %#lx %#lx",
11367 			    sva, *pte, ptev));
11368 		}
11369 		if (unwire_pde) {
11370 			pde = pmap_pti_pde(sva);
11371 			pmap_pti_unwire_pde(pde, true);
11372 		}
11373 	}
11374 }
11375 
11376 void
pmap_pti_add_kva(vm_offset_t sva,vm_offset_t eva,bool exec)11377 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11378 {
11379 
11380 	if (!pti)
11381 		return;
11382 	VM_OBJECT_WLOCK(pti_obj);
11383 	pmap_pti_add_kva_locked(sva, eva, exec);
11384 	VM_OBJECT_WUNLOCK(pti_obj);
11385 }
11386 
11387 void
pmap_pti_remove_kva(vm_offset_t sva,vm_offset_t eva)11388 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11389 {
11390 	pt_entry_t *pte;
11391 	vm_offset_t va;
11392 
11393 	if (!pti)
11394 		return;
11395 	sva = rounddown2(sva, PAGE_SIZE);
11396 	MPASS(sva > VM_MAXUSER_ADDRESS);
11397 	eva = roundup2(eva, PAGE_SIZE);
11398 	MPASS(sva < eva);
11399 	VM_OBJECT_WLOCK(pti_obj);
11400 	for (va = sva; va < eva; va += PAGE_SIZE) {
11401 		pte = pmap_pti_pte(va, NULL);
11402 		KASSERT((*pte & X86_PG_V) != 0,
11403 		    ("invalid pte va %#lx pte %#lx pt %#lx", va,
11404 		    (u_long)pte, *pte));
11405 		pte_clear(pte);
11406 		pmap_pti_unwire_pte(pte, va);
11407 	}
11408 	pmap_invalidate_range(kernel_pmap, sva, eva);
11409 	VM_OBJECT_WUNLOCK(pti_obj);
11410 }
11411 
11412 static void *
pkru_dup_range(void * ctx __unused,void * data)11413 pkru_dup_range(void *ctx __unused, void *data)
11414 {
11415 	struct pmap_pkru_range *node, *new_node;
11416 
11417 	new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11418 	if (new_node == NULL)
11419 		return (NULL);
11420 	node = data;
11421 	memcpy(new_node, node, sizeof(*node));
11422 	return (new_node);
11423 }
11424 
11425 static void
pkru_free_range(void * ctx __unused,void * node)11426 pkru_free_range(void *ctx __unused, void *node)
11427 {
11428 
11429 	uma_zfree(pmap_pkru_ranges_zone, node);
11430 }
11431 
11432 static int
pmap_pkru_assign(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11433 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11434     int flags)
11435 {
11436 	struct pmap_pkru_range *ppr;
11437 	int error;
11438 
11439 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11440 	MPASS(pmap->pm_type == PT_X86);
11441 	MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11442 	if ((flags & AMD64_PKRU_EXCL) != 0 &&
11443 	    !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11444 		return (EBUSY);
11445 	ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11446 	if (ppr == NULL)
11447 		return (ENOMEM);
11448 	ppr->pkru_keyidx = keyidx;
11449 	ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11450 	error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11451 	if (error != 0)
11452 		uma_zfree(pmap_pkru_ranges_zone, ppr);
11453 	return (error);
11454 }
11455 
11456 static int
pmap_pkru_deassign(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11457 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11458 {
11459 
11460 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11461 	MPASS(pmap->pm_type == PT_X86);
11462 	MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11463 	return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11464 }
11465 
11466 static void
pmap_pkru_deassign_all(pmap_t pmap)11467 pmap_pkru_deassign_all(pmap_t pmap)
11468 {
11469 
11470 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11471 	if (pmap->pm_type == PT_X86 &&
11472 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11473 		rangeset_remove_all(&pmap->pm_pkru);
11474 }
11475 
11476 /*
11477  * Returns true if the PKU setting is the same across the specified address
11478  * range, and false otherwise.  When returning true, updates the referenced PTE
11479  * to reflect the PKU setting.
11480  */
11481 static bool
pmap_pkru_same(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pt_entry_t * pte)11482 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t *pte)
11483 {
11484 	struct pmap_pkru_range *ppr;
11485 	vm_offset_t va;
11486 	u_int keyidx;
11487 
11488 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11489 	KASSERT(pmap->pm_type != PT_X86 || (*pte & X86_PG_PKU_MASK) == 0,
11490 	    ("pte %p has unexpected PKU %ld", pte, *pte & X86_PG_PKU_MASK));
11491 	if (pmap->pm_type != PT_X86 ||
11492 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11493 	    sva >= VM_MAXUSER_ADDRESS)
11494 		return (true);
11495 	MPASS(eva <= VM_MAXUSER_ADDRESS);
11496 	ppr = rangeset_containing(&pmap->pm_pkru, sva);
11497 	if (ppr == NULL)
11498 		return (rangeset_empty(&pmap->pm_pkru, sva, eva));
11499 	keyidx = ppr->pkru_keyidx;
11500 	while ((va = ppr->pkru_rs_el.re_end) < eva) {
11501 		if ((ppr = rangeset_beginning(&pmap->pm_pkru, va)) == NULL ||
11502 		    keyidx != ppr->pkru_keyidx)
11503 			return (false);
11504 	}
11505 	*pte |= X86_PG_PKU(keyidx);
11506 	return (true);
11507 }
11508 
11509 static pt_entry_t
pmap_pkru_get(pmap_t pmap,vm_offset_t va)11510 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11511 {
11512 	struct pmap_pkru_range *ppr;
11513 
11514 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11515 	if (pmap->pm_type != PT_X86 ||
11516 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11517 	    va >= VM_MAXUSER_ADDRESS)
11518 		return (0);
11519 	ppr = rangeset_containing(&pmap->pm_pkru, va);
11520 	if (ppr != NULL)
11521 		return (X86_PG_PKU(ppr->pkru_keyidx));
11522 	return (0);
11523 }
11524 
11525 static bool
pred_pkru_on_remove(void * ctx __unused,void * r)11526 pred_pkru_on_remove(void *ctx __unused, void *r)
11527 {
11528 	struct pmap_pkru_range *ppr;
11529 
11530 	ppr = r;
11531 	return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11532 }
11533 
11534 static void
pmap_pkru_on_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11535 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11536 {
11537 
11538 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11539 	if (pmap->pm_type == PT_X86 &&
11540 	    (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11541 		rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11542 		    pred_pkru_on_remove);
11543 	}
11544 }
11545 
11546 static int
pmap_pkru_copy(pmap_t dst_pmap,pmap_t src_pmap)11547 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11548 {
11549 
11550 	PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11551 	PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11552 	MPASS(dst_pmap->pm_type == PT_X86);
11553 	MPASS(src_pmap->pm_type == PT_X86);
11554 	MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11555 	if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11556 		return (0);
11557 	return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11558 }
11559 
11560 static void
pmap_pkru_update_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx)11561 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11562     u_int keyidx)
11563 {
11564 	pml4_entry_t *pml4e;
11565 	pdp_entry_t *pdpe;
11566 	pd_entry_t newpde, ptpaddr, *pde;
11567 	pt_entry_t newpte, *ptep, pte;
11568 	vm_offset_t va, va_next;
11569 	bool changed;
11570 
11571 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11572 	MPASS(pmap->pm_type == PT_X86);
11573 	MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11574 
11575 	for (changed = false, va = sva; va < eva; va = va_next) {
11576 		pml4e = pmap_pml4e(pmap, va);
11577 		if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11578 			va_next = (va + NBPML4) & ~PML4MASK;
11579 			if (va_next < va)
11580 				va_next = eva;
11581 			continue;
11582 		}
11583 
11584 		pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11585 		if ((*pdpe & X86_PG_V) == 0) {
11586 			va_next = (va + NBPDP) & ~PDPMASK;
11587 			if (va_next < va)
11588 				va_next = eva;
11589 			continue;
11590 		}
11591 
11592 		va_next = (va + NBPDR) & ~PDRMASK;
11593 		if (va_next < va)
11594 			va_next = eva;
11595 
11596 		pde = pmap_pdpe_to_pde(pdpe, va);
11597 		ptpaddr = *pde;
11598 		if (ptpaddr == 0)
11599 			continue;
11600 
11601 		MPASS((ptpaddr & X86_PG_V) != 0);
11602 		if ((ptpaddr & PG_PS) != 0) {
11603 			if (va + NBPDR == va_next && eva >= va_next) {
11604 				newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11605 				    X86_PG_PKU(keyidx);
11606 				if (newpde != ptpaddr) {
11607 					*pde = newpde;
11608 					changed = true;
11609 				}
11610 				continue;
11611 			} else if (!pmap_demote_pde(pmap, pde, va)) {
11612 				continue;
11613 			}
11614 		}
11615 
11616 		if (va_next > eva)
11617 			va_next = eva;
11618 
11619 		for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11620 		    ptep++, va += PAGE_SIZE) {
11621 			pte = *ptep;
11622 			if ((pte & X86_PG_V) == 0)
11623 				continue;
11624 			newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11625 			if (newpte != pte) {
11626 				*ptep = newpte;
11627 				changed = true;
11628 			}
11629 		}
11630 	}
11631 	if (changed)
11632 		pmap_invalidate_range(pmap, sva, eva);
11633 }
11634 
11635 static int
pmap_pkru_check_uargs(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11636 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11637     u_int keyidx, int flags)
11638 {
11639 
11640 	if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11641 	    (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11642 		return (EINVAL);
11643 	if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11644 		return (EFAULT);
11645 	if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11646 		return (ENOTSUP);
11647 	return (0);
11648 }
11649 
11650 int
pmap_pkru_set(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11651 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11652     int flags)
11653 {
11654 	int error;
11655 
11656 	sva = trunc_page(sva);
11657 	eva = round_page(eva);
11658 	error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11659 	if (error != 0)
11660 		return (error);
11661 	for (;;) {
11662 		PMAP_LOCK(pmap);
11663 		error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11664 		if (error == 0)
11665 			pmap_pkru_update_range(pmap, sva, eva, keyidx);
11666 		PMAP_UNLOCK(pmap);
11667 		if (error != ENOMEM)
11668 			break;
11669 		vm_wait(NULL);
11670 	}
11671 	return (error);
11672 }
11673 
11674 int
pmap_pkru_clear(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11675 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11676 {
11677 	int error;
11678 
11679 	sva = trunc_page(sva);
11680 	eva = round_page(eva);
11681 	error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11682 	if (error != 0)
11683 		return (error);
11684 	for (;;) {
11685 		PMAP_LOCK(pmap);
11686 		error = pmap_pkru_deassign(pmap, sva, eva);
11687 		if (error == 0)
11688 			pmap_pkru_update_range(pmap, sva, eva, 0);
11689 		PMAP_UNLOCK(pmap);
11690 		if (error != ENOMEM)
11691 			break;
11692 		vm_wait(NULL);
11693 	}
11694 	return (error);
11695 }
11696 
11697 #if defined(KASAN) || defined(KMSAN)
11698 
11699 /*
11700  * Reserve enough memory to:
11701  * 1) allocate PDP pages for the shadow map(s),
11702  * 2) shadow the boot stack of KSTACK_PAGES pages,
11703  * 3) assuming that the kernel stack does not cross a 1GB boundary,
11704  * so we need one or two PD pages, one or two PT pages, and KSTACK_PAGES shadow
11705  * pages per shadow map.
11706  */
11707 #ifdef KASAN
11708 #define	SAN_EARLY_PAGES	\
11709 	(NKASANPML4E + 2 + 2 + howmany(KSTACK_PAGES, KASAN_SHADOW_SCALE))
11710 #else
11711 #define	SAN_EARLY_PAGES	\
11712 	(NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * (2 + 2 + KSTACK_PAGES))
11713 #endif
11714 
11715 static uint64_t __nosanitizeaddress __nosanitizememory
pmap_san_enter_early_alloc_4k(uint64_t pabase)11716 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11717 {
11718 	static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11719 	static size_t offset = 0;
11720 	uint64_t pa;
11721 
11722 	if (offset == sizeof(data)) {
11723 		panic("%s: ran out of memory for the bootstrap shadow map",
11724 		    __func__);
11725 	}
11726 
11727 	pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11728 	offset += PAGE_SIZE;
11729 	return (pa);
11730 }
11731 
11732 /*
11733  * Map a shadow page, before the kernel has bootstrapped its page tables.  This
11734  * is currently only used to shadow the temporary boot stack set up by locore.
11735  */
11736 static void __nosanitizeaddress __nosanitizememory
pmap_san_enter_early(vm_offset_t va)11737 pmap_san_enter_early(vm_offset_t va)
11738 {
11739 	static bool first = true;
11740 	pml4_entry_t *pml4e;
11741 	pdp_entry_t *pdpe;
11742 	pd_entry_t *pde;
11743 	pt_entry_t *pte;
11744 	uint64_t cr3, pa, base;
11745 	int i;
11746 
11747 	base = amd64_loadaddr();
11748 	cr3 = rcr3();
11749 
11750 	if (first) {
11751 		/*
11752 		 * If this the first call, we need to allocate new PML4Es for
11753 		 * the bootstrap shadow map(s).  We don't know how the PML4 page
11754 		 * was initialized by the boot loader, so we can't simply test
11755 		 * whether the shadow map's PML4Es are zero.
11756 		 */
11757 		first = false;
11758 #ifdef KASAN
11759 		for (i = 0; i < NKASANPML4E; i++) {
11760 			pa = pmap_san_enter_early_alloc_4k(base);
11761 
11762 			pml4e = (pml4_entry_t *)cr3 +
11763 			    pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11764 			*pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11765 		}
11766 #else
11767 		for (i = 0; i < NKMSANORIGPML4E; i++) {
11768 			pa = pmap_san_enter_early_alloc_4k(base);
11769 
11770 			pml4e = (pml4_entry_t *)cr3 +
11771 			    pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11772 			    i * NBPML4);
11773 			*pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11774 		}
11775 		for (i = 0; i < NKMSANSHADPML4E; i++) {
11776 			pa = pmap_san_enter_early_alloc_4k(base);
11777 
11778 			pml4e = (pml4_entry_t *)cr3 +
11779 			    pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11780 			    i * NBPML4);
11781 			*pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11782 		}
11783 #endif
11784 	}
11785 	pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11786 	pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11787 	if (*pdpe == 0) {
11788 		pa = pmap_san_enter_early_alloc_4k(base);
11789 		*pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11790 	}
11791 	pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11792 	if (*pde == 0) {
11793 		pa = pmap_san_enter_early_alloc_4k(base);
11794 		*pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11795 	}
11796 	pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11797 	if (*pte != 0)
11798 		panic("%s: PTE for %#lx is already initialized", __func__, va);
11799 	pa = pmap_san_enter_early_alloc_4k(base);
11800 	*pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11801 }
11802 
11803 static vm_page_t
pmap_san_enter_alloc_4k(void)11804 pmap_san_enter_alloc_4k(void)
11805 {
11806 	vm_page_t m;
11807 
11808 	m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11809 	    VM_ALLOC_ZERO);
11810 	if (m == NULL)
11811 		panic("%s: no memory to grow shadow map", __func__);
11812 	return (m);
11813 }
11814 
11815 static vm_page_t
pmap_san_enter_alloc_2m(void)11816 pmap_san_enter_alloc_2m(void)
11817 {
11818 	return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11819 	    NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11820 }
11821 
11822 /*
11823  * Grow a shadow map by at least one 4KB page at the specified address.  Use 2MB
11824  * pages when possible.
11825  */
11826 void __nosanitizeaddress __nosanitizememory
pmap_san_enter(vm_offset_t va)11827 pmap_san_enter(vm_offset_t va)
11828 {
11829 	pdp_entry_t *pdpe;
11830 	pd_entry_t *pde;
11831 	pt_entry_t *pte;
11832 	vm_page_t m;
11833 
11834 	if (kernphys == 0) {
11835 		/*
11836 		 * We're creating a temporary shadow map for the boot stack.
11837 		 */
11838 		pmap_san_enter_early(va);
11839 		return;
11840 	}
11841 
11842 	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11843 
11844 	pdpe = pmap_pdpe(kernel_pmap, va);
11845 	if ((*pdpe & X86_PG_V) == 0) {
11846 		m = pmap_san_enter_alloc_4k();
11847 		*pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11848 		    X86_PG_V | pg_nx);
11849 	}
11850 	pde = pmap_pdpe_to_pde(pdpe, va);
11851 	if ((*pde & X86_PG_V) == 0) {
11852 		m = pmap_san_enter_alloc_2m();
11853 		if (m != NULL) {
11854 			*pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11855 			    X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11856 		} else {
11857 			m = pmap_san_enter_alloc_4k();
11858 			*pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11859 			    X86_PG_V | pg_nx);
11860 		}
11861 	}
11862 	if ((*pde & X86_PG_PS) != 0)
11863 		return;
11864 	pte = pmap_pde_to_pte(pde, va);
11865 	if ((*pte & X86_PG_V) != 0)
11866 		return;
11867 	m = pmap_san_enter_alloc_4k();
11868 	*pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11869 	    X86_PG_M | X86_PG_A | pg_nx);
11870 }
11871 #endif
11872 
11873 /*
11874  * Track a range of the kernel's virtual address space that is contiguous
11875  * in various mapping attributes.
11876  */
11877 struct pmap_kernel_map_range {
11878 	vm_offset_t sva;
11879 	pt_entry_t attrs;
11880 	int ptes;
11881 	int pdes;
11882 	int pdpes;
11883 };
11884 
11885 static void
sysctl_kmaps_dump(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t eva)11886 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11887     vm_offset_t eva)
11888 {
11889 	const char *mode;
11890 	int i, pat_idx;
11891 
11892 	if (eva <= range->sva)
11893 		return;
11894 
11895 	pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11896 	for (i = 0; i < PAT_INDEX_SIZE; i++)
11897 		if (pat_index[i] == pat_idx)
11898 			break;
11899 
11900 	switch (i) {
11901 	case PAT_WRITE_BACK:
11902 		mode = "WB";
11903 		break;
11904 	case PAT_WRITE_THROUGH:
11905 		mode = "WT";
11906 		break;
11907 	case PAT_UNCACHEABLE:
11908 		mode = "UC";
11909 		break;
11910 	case PAT_UNCACHED:
11911 		mode = "U-";
11912 		break;
11913 	case PAT_WRITE_PROTECTED:
11914 		mode = "WP";
11915 		break;
11916 	case PAT_WRITE_COMBINING:
11917 		mode = "WC";
11918 		break;
11919 	default:
11920 		printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11921 		    __func__, pat_idx, range->sva, eva);
11922 		mode = "??";
11923 		break;
11924 	}
11925 
11926 	sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11927 	    range->sva, eva,
11928 	    (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11929 	    (range->attrs & pg_nx) != 0 ? '-' : 'x',
11930 	    (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11931 	    (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11932 	    mode, range->pdpes, range->pdes, range->ptes);
11933 
11934 	/* Reset to sentinel value. */
11935 	range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11936 	    NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11937 	    NPDEPG - 1, NPTEPG - 1);
11938 }
11939 
11940 /*
11941  * Determine whether the attributes specified by a page table entry match those
11942  * being tracked by the current range.  This is not quite as simple as a direct
11943  * flag comparison since some PAT modes have multiple representations.
11944  */
11945 static bool
sysctl_kmaps_match(struct pmap_kernel_map_range * range,pt_entry_t attrs)11946 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11947 {
11948 	pt_entry_t diff, mask;
11949 
11950 	mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11951 	diff = (range->attrs ^ attrs) & mask;
11952 	if (diff == 0)
11953 		return (true);
11954 	if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11955 	    pmap_pat_index(kernel_pmap, range->attrs, true) ==
11956 	    pmap_pat_index(kernel_pmap, attrs, true))
11957 		return (true);
11958 	return (false);
11959 }
11960 
11961 static void
sysctl_kmaps_reinit(struct pmap_kernel_map_range * range,vm_offset_t va,pt_entry_t attrs)11962 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11963     pt_entry_t attrs)
11964 {
11965 
11966 	memset(range, 0, sizeof(*range));
11967 	range->sva = va;
11968 	range->attrs = attrs;
11969 }
11970 
11971 /*
11972  * Given a leaf PTE, derive the mapping's attributes.  If they do not match
11973  * those of the current run, dump the address range and its attributes, and
11974  * begin a new run.
11975  */
11976 static void
sysctl_kmaps_check(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t va,pml4_entry_t pml4e,pdp_entry_t pdpe,pd_entry_t pde,pt_entry_t pte)11977 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11978     vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11979     pt_entry_t pte)
11980 {
11981 	pt_entry_t attrs;
11982 
11983 	attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11984 
11985 	attrs |= pdpe & pg_nx;
11986 	attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11987 	if ((pdpe & PG_PS) != 0) {
11988 		attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11989 	} else if (pde != 0) {
11990 		attrs |= pde & pg_nx;
11991 		attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11992 	}
11993 	if ((pde & PG_PS) != 0) {
11994 		attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11995 	} else if (pte != 0) {
11996 		attrs |= pte & pg_nx;
11997 		attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11998 		attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11999 
12000 		/* Canonicalize by always using the PDE PAT bit. */
12001 		if ((attrs & X86_PG_PTE_PAT) != 0)
12002 			attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
12003 	}
12004 
12005 	if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
12006 		sysctl_kmaps_dump(sb, range, va);
12007 		sysctl_kmaps_reinit(range, va, attrs);
12008 	}
12009 }
12010 
12011 static int
sysctl_kmaps(SYSCTL_HANDLER_ARGS)12012 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
12013 {
12014 	struct pmap_kernel_map_range range;
12015 	struct sbuf sbuf, *sb;
12016 	pml4_entry_t pml4e;
12017 	pdp_entry_t *pdp, pdpe;
12018 	pd_entry_t *pd, pde;
12019 	pt_entry_t *pt, pte;
12020 	vm_offset_t sva;
12021 	vm_paddr_t pa;
12022 	int error, i, j, k, l;
12023 
12024 	error = sysctl_wire_old_buffer(req, 0);
12025 	if (error != 0)
12026 		return (error);
12027 	sb = &sbuf;
12028 	sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
12029 
12030 	/* Sentinel value. */
12031 	range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
12032 	    NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
12033 	    NPDEPG - 1, NPTEPG - 1);
12034 
12035 	/*
12036 	 * Iterate over the kernel page tables without holding the kernel pmap
12037 	 * lock.  Outside of the large map, kernel page table pages are never
12038 	 * freed, so at worst we will observe inconsistencies in the output.
12039 	 * Within the large map, ensure that PDP and PD page addresses are
12040 	 * valid before descending.
12041 	 */
12042 	for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
12043 		switch (i) {
12044 		case PML4PML4I:
12045 			sbuf_printf(sb, "\nRecursive map:\n");
12046 			break;
12047 		case DMPML4I:
12048 			sbuf_printf(sb, "\nDirect map:\n");
12049 			break;
12050 #ifdef KASAN
12051 		case KASANPML4I:
12052 			sbuf_printf(sb, "\nKASAN shadow map:\n");
12053 			break;
12054 #endif
12055 #ifdef KMSAN
12056 		case KMSANSHADPML4I:
12057 			sbuf_printf(sb, "\nKMSAN shadow map:\n");
12058 			break;
12059 		case KMSANORIGPML4I:
12060 			sbuf_printf(sb, "\nKMSAN origin map:\n");
12061 			break;
12062 #endif
12063 		case KPML4BASE:
12064 			sbuf_printf(sb, "\nKernel map:\n");
12065 			break;
12066 		case LMSPML4I:
12067 			sbuf_printf(sb, "\nLarge map:\n");
12068 			break;
12069 		}
12070 
12071 		/* Convert to canonical form. */
12072 		if (sva == 1ul << 47)
12073 			sva |= -1ul << 48;
12074 
12075 restart:
12076 		pml4e = kernel_pml4[i];
12077 		if ((pml4e & X86_PG_V) == 0) {
12078 			sva = rounddown2(sva, NBPML4);
12079 			sysctl_kmaps_dump(sb, &range, sva);
12080 			sva += NBPML4;
12081 			continue;
12082 		}
12083 		pa = pml4e & PG_FRAME;
12084 		pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
12085 
12086 		for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
12087 			pdpe = pdp[j];
12088 			if ((pdpe & X86_PG_V) == 0) {
12089 				sva = rounddown2(sva, NBPDP);
12090 				sysctl_kmaps_dump(sb, &range, sva);
12091 				sva += NBPDP;
12092 				continue;
12093 			}
12094 			pa = pdpe & PG_FRAME;
12095 			if ((pdpe & PG_PS) != 0) {
12096 				sva = rounddown2(sva, NBPDP);
12097 				sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
12098 				    0, 0);
12099 				range.pdpes++;
12100 				sva += NBPDP;
12101 				continue;
12102 			}
12103 			if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12104 			    vm_phys_paddr_to_vm_page(pa) == NULL) {
12105 				/*
12106 				 * Page table pages for the large map may be
12107 				 * freed.  Validate the next-level address
12108 				 * before descending.
12109 				 */
12110 				goto restart;
12111 			}
12112 			pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
12113 
12114 			for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
12115 				pde = pd[k];
12116 				if ((pde & X86_PG_V) == 0) {
12117 					sva = rounddown2(sva, NBPDR);
12118 					sysctl_kmaps_dump(sb, &range, sva);
12119 					sva += NBPDR;
12120 					continue;
12121 				}
12122 				pa = pde & PG_FRAME;
12123 				if ((pde & PG_PS) != 0) {
12124 					sva = rounddown2(sva, NBPDR);
12125 					sysctl_kmaps_check(sb, &range, sva,
12126 					    pml4e, pdpe, pde, 0);
12127 					range.pdes++;
12128 					sva += NBPDR;
12129 					continue;
12130 				}
12131 				if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12132 				    vm_phys_paddr_to_vm_page(pa) == NULL) {
12133 					/*
12134 					 * Page table pages for the large map
12135 					 * may be freed.  Validate the
12136 					 * next-level address before descending.
12137 					 */
12138 					goto restart;
12139 				}
12140 				pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12141 
12142 				for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12143 				    sva += PAGE_SIZE) {
12144 					pte = pt[l];
12145 					if ((pte & X86_PG_V) == 0) {
12146 						sysctl_kmaps_dump(sb, &range,
12147 						    sva);
12148 						continue;
12149 					}
12150 					sysctl_kmaps_check(sb, &range, sva,
12151 					    pml4e, pdpe, pde, pte);
12152 					range.ptes++;
12153 				}
12154 			}
12155 		}
12156 	}
12157 
12158 	error = sbuf_finish(sb);
12159 	sbuf_delete(sb);
12160 	return (error);
12161 }
12162 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12163     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12164     NULL, 0, sysctl_kmaps, "A",
12165     "Dump kernel address layout");
12166 
12167 #ifdef DDB
DB_SHOW_COMMAND(pte,pmap_print_pte)12168 DB_SHOW_COMMAND(pte, pmap_print_pte)
12169 {
12170 	pmap_t pmap;
12171 	pml5_entry_t *pml5;
12172 	pml4_entry_t *pml4;
12173 	pdp_entry_t *pdp;
12174 	pd_entry_t *pde;
12175 	pt_entry_t *pte, PG_V;
12176 	vm_offset_t va;
12177 
12178 	if (!have_addr) {
12179 		db_printf("show pte addr\n");
12180 		return;
12181 	}
12182 	va = (vm_offset_t)addr;
12183 
12184 	if (kdb_thread != NULL)
12185 		pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12186 	else
12187 		pmap = PCPU_GET(curpmap);
12188 
12189 	PG_V = pmap_valid_bit(pmap);
12190 	db_printf("VA 0x%016lx", va);
12191 
12192 	if (pmap_is_la57(pmap)) {
12193 		pml5 = pmap_pml5e(pmap, va);
12194 		db_printf(" pml5e 0x%016lx", *pml5);
12195 		if ((*pml5 & PG_V) == 0) {
12196 			db_printf("\n");
12197 			return;
12198 		}
12199 		pml4 = pmap_pml5e_to_pml4e(pml5, va);
12200 	} else {
12201 		pml4 = pmap_pml4e(pmap, va);
12202 	}
12203 	db_printf(" pml4e 0x%016lx", *pml4);
12204 	if ((*pml4 & PG_V) == 0) {
12205 		db_printf("\n");
12206 		return;
12207 	}
12208 	pdp = pmap_pml4e_to_pdpe(pml4, va);
12209 	db_printf(" pdpe 0x%016lx", *pdp);
12210 	if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12211 		db_printf("\n");
12212 		return;
12213 	}
12214 	pde = pmap_pdpe_to_pde(pdp, va);
12215 	db_printf(" pde 0x%016lx", *pde);
12216 	if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12217 		db_printf("\n");
12218 		return;
12219 	}
12220 	pte = pmap_pde_to_pte(pde, va);
12221 	db_printf(" pte 0x%016lx\n", *pte);
12222 }
12223 
DB_SHOW_COMMAND(phys2dmap,pmap_phys2dmap)12224 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12225 {
12226 	vm_paddr_t a;
12227 
12228 	if (have_addr) {
12229 		a = (vm_paddr_t)addr;
12230 		db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12231 	} else {
12232 		db_printf("show phys2dmap addr\n");
12233 	}
12234 }
12235 
12236 static void
ptpages_show_page(int level,int idx,vm_page_t pg)12237 ptpages_show_page(int level, int idx, vm_page_t pg)
12238 {
12239 	db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12240 	    level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12241 }
12242 
12243 static void
ptpages_show_complain(int level,int idx,uint64_t pte)12244 ptpages_show_complain(int level, int idx, uint64_t pte)
12245 {
12246 	db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12247 }
12248 
12249 static void
ptpages_show_pml4(vm_page_t pg4,int num_entries,uint64_t PG_V)12250 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12251 {
12252 	vm_page_t pg3, pg2, pg1;
12253 	pml4_entry_t *pml4;
12254 	pdp_entry_t *pdp;
12255 	pd_entry_t *pd;
12256 	int i4, i3, i2;
12257 
12258 	pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12259 	for (i4 = 0; i4 < num_entries; i4++) {
12260 		if ((pml4[i4] & PG_V) == 0)
12261 			continue;
12262 		pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12263 		if (pg3 == NULL) {
12264 			ptpages_show_complain(3, i4, pml4[i4]);
12265 			continue;
12266 		}
12267 		ptpages_show_page(3, i4, pg3);
12268 		pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12269 		for (i3 = 0; i3 < NPDPEPG; i3++) {
12270 			if ((pdp[i3] & PG_V) == 0)
12271 				continue;
12272 			pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12273 			if (pg3 == NULL) {
12274 				ptpages_show_complain(2, i3, pdp[i3]);
12275 				continue;
12276 			}
12277 			ptpages_show_page(2, i3, pg2);
12278 			pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12279 			for (i2 = 0; i2 < NPDEPG; i2++) {
12280 				if ((pd[i2] & PG_V) == 0)
12281 					continue;
12282 				pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12283 				if (pg1 == NULL) {
12284 					ptpages_show_complain(1, i2, pd[i2]);
12285 					continue;
12286 				}
12287 				ptpages_show_page(1, i2, pg1);
12288 			}
12289 		}
12290 	}
12291 }
12292 
DB_SHOW_COMMAND(ptpages,pmap_ptpages)12293 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12294 {
12295 	pmap_t pmap;
12296 	vm_page_t pg;
12297 	pml5_entry_t *pml5;
12298 	uint64_t PG_V;
12299 	int i5;
12300 
12301 	if (have_addr)
12302 		pmap = (pmap_t)addr;
12303 	else
12304 		pmap = PCPU_GET(curpmap);
12305 
12306 	PG_V = pmap_valid_bit(pmap);
12307 
12308 	if (pmap_is_la57(pmap)) {
12309 		pml5 = pmap->pm_pmltop;
12310 		for (i5 = 0; i5 < NUPML5E; i5++) {
12311 			if ((pml5[i5] & PG_V) == 0)
12312 				continue;
12313 			pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12314 			if (pg == NULL) {
12315 				ptpages_show_complain(4, i5, pml5[i5]);
12316 				continue;
12317 			}
12318 			ptpages_show_page(4, i5, pg);
12319 			ptpages_show_pml4(pg, NPML4EPG, PG_V);
12320 		}
12321 	} else {
12322 		ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12323 		    (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);
12324 	}
12325 }
12326 #endif
12327