xref: /freebsd/sys/arm64/arm64/pmap.c (revision 9d3dc1e5e0b0c59e1cc473953a8c509779685c2a)
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  * Copyright (c) 2003 Peter Wemm
9  * All rights reserved.
10  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11  * All rights reserved.
12  * Copyright (c) 2014 Andrew Turner
13  * All rights reserved.
14  * Copyright (c) 2014-2016 The FreeBSD Foundation
15  * All rights reserved.
16  *
17  * This code is derived from software contributed to Berkeley by
18  * the Systems Programming Group of the University of Utah Computer
19  * Science Department and William Jolitz of UUNET Technologies Inc.
20  *
21  * This software was developed by Andrew Turner under sponsorship from
22  * the FreeBSD Foundation.
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  * 3. All advertising materials mentioning features or use of this software
33  *    must display the following acknowledgement:
34  *	This product includes software developed by the University of
35  *	California, Berkeley and its contributors.
36  * 4. Neither the name of the University nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  */
52 /*-
53  * Copyright (c) 2003 Networks Associates Technology, Inc.
54  * All rights reserved.
55  *
56  * This software was developed for the FreeBSD Project by Jake Burkholder,
57  * Safeport Network Services, and Network Associates Laboratories, the
58  * Security Research Division of Network Associates, Inc. under
59  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
60  * CHATS research program.
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 #include <sys/cdefs.h>
85 /*
86  *	Manages physical address maps.
87  *
88  *	Since the information managed by this module is
89  *	also stored by the logical address mapping module,
90  *	this module may throw away valid virtual-to-physical
91  *	mappings at almost any time.  However, invalidations
92  *	of virtual-to-physical mappings must be done as
93  *	requested.
94  *
95  *	In order to cope with hardware architectures which
96  *	make virtual-to-physical map invalidates expensive,
97  *	this module may delay invalidate or reduced protection
98  *	operations until such time as they are actually
99  *	necessary.  This module is given full information as
100  *	to which processors are currently using which maps,
101  *	and to when physical maps must be made correct.
102  */
103 
104 #include "opt_vm.h"
105 
106 #include <sys/param.h>
107 #include <sys/asan.h>
108 #include <sys/bitstring.h>
109 #include <sys/bus.h>
110 #include <sys/systm.h>
111 #include <sys/kernel.h>
112 #include <sys/ktr.h>
113 #include <sys/limits.h>
114 #include <sys/lock.h>
115 #include <sys/malloc.h>
116 #include <sys/mman.h>
117 #include <sys/msan.h>
118 #include <sys/msgbuf.h>
119 #include <sys/mutex.h>
120 #include <sys/physmem.h>
121 #include <sys/proc.h>
122 #include <sys/rangeset.h>
123 #include <sys/rwlock.h>
124 #include <sys/sbuf.h>
125 #include <sys/sx.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
130 #include <sys/_unrhdr.h>
131 #include <sys/smp.h>
132 
133 #include <vm/vm.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
145 #include <vm/vm_dumpset.h>
146 #include <vm/uma.h>
147 
148 #include <machine/asan.h>
149 #include <machine/machdep.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
152 
153 #ifdef NUMA
154 #define	PMAP_MEMDOM	MAXMEMDOM
155 #else
156 #define	PMAP_MEMDOM	1
157 #endif
158 
159 #define	PMAP_ASSERT_STAGE1(pmap)	MPASS((pmap)->pm_stage == PM_STAGE1)
160 #define	PMAP_ASSERT_STAGE2(pmap)	MPASS((pmap)->pm_stage == PM_STAGE2)
161 
162 #define	NL0PG		(PAGE_SIZE/(sizeof (pd_entry_t)))
163 #define	NL1PG		(PAGE_SIZE/(sizeof (pd_entry_t)))
164 #define	NL2PG		(PAGE_SIZE/(sizeof (pd_entry_t)))
165 #define	NL3PG		(PAGE_SIZE/(sizeof (pt_entry_t)))
166 
167 #define	NUL0E		L0_ENTRIES
168 #define	NUL1E		(NUL0E * NL1PG)
169 #define	NUL2E		(NUL1E * NL2PG)
170 
171 #ifdef PV_STATS
172 #define PV_STAT(x)	do { x ; } while (0)
173 #define __pvused
174 #else
175 #define PV_STAT(x)	do { } while (0)
176 #define __pvused	__unused
177 #endif
178 
179 #define	pmap_l0_pindex(v)	(NUL2E + NUL1E + ((v) >> L0_SHIFT))
180 #define	pmap_l1_pindex(v)	(NUL2E + ((v) >> L1_SHIFT))
181 #define	pmap_l2_pindex(v)	((v) >> L2_SHIFT)
182 
183 #ifdef __ARM_FEATURE_BTI_DEFAULT
184 #define	ATTR_KERN_GP		ATTR_S1_GP
185 #else
186 #define	ATTR_KERN_GP		0
187 #endif
188 #define	PMAP_SAN_PTE_BITS	(ATTR_AF | ATTR_S1_XN | pmap_sh_attr | \
189   ATTR_KERN_GP | ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | ATTR_S1_AP(ATTR_S1_AP_RW))
190 
191 struct pmap_large_md_page {
192 	struct rwlock   pv_lock;
193 	struct md_page  pv_page;
194 	/* Pad to a power of 2, see pmap_init_pv_table(). */
195 	int		pv_pad[2];
196 };
197 
198 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
199 #define pv_dummy pv_dummy_large.pv_page
200 __read_mostly static struct pmap_large_md_page *pv_table;
201 
202 static struct pmap_large_md_page *
_pa_to_pmdp(vm_paddr_t pa)203 _pa_to_pmdp(vm_paddr_t pa)
204 {
205 	struct vm_phys_seg *seg;
206 
207 	if ((seg = vm_phys_paddr_to_seg(pa)) != NULL)
208 		return ((struct pmap_large_md_page *)seg->md_first +
209 		    pmap_l2_pindex(pa) - pmap_l2_pindex(seg->start));
210 	return (NULL);
211 }
212 
213 static struct pmap_large_md_page *
pa_to_pmdp(vm_paddr_t pa)214 pa_to_pmdp(vm_paddr_t pa)
215 {
216 	struct pmap_large_md_page *pvd;
217 
218 	pvd = _pa_to_pmdp(pa);
219 	if (pvd == NULL)
220 		panic("pa 0x%jx not within vm_phys_segs", (uintmax_t)pa);
221 	return (pvd);
222 }
223 
224 static struct pmap_large_md_page *
page_to_pmdp(vm_page_t m)225 page_to_pmdp(vm_page_t m)
226 {
227 	struct vm_phys_seg *seg;
228 
229 	seg = &vm_phys_segs[m->segind];
230 	return ((struct pmap_large_md_page *)seg->md_first +
231 	    pmap_l2_pindex(VM_PAGE_TO_PHYS(m)) - pmap_l2_pindex(seg->start));
232 }
233 
234 #define	pa_to_pvh(pa)	(&(pa_to_pmdp(pa)->pv_page))
235 #define	page_to_pvh(m)	(&(page_to_pmdp(m)->pv_page))
236 
237 #define	PHYS_TO_PV_LIST_LOCK(pa)	({			\
238 	struct pmap_large_md_page *_pvd;			\
239 	struct rwlock *_lock;					\
240 	_pvd = _pa_to_pmdp(pa);					\
241 	if (__predict_false(_pvd == NULL))			\
242 		_lock = &pv_dummy_large.pv_lock;		\
243 	else							\
244 		_lock = &(_pvd->pv_lock);			\
245 	_lock;							\
246 })
247 
248 static struct rwlock *
VM_PAGE_TO_PV_LIST_LOCK(vm_page_t m)249 VM_PAGE_TO_PV_LIST_LOCK(vm_page_t m)
250 {
251 	if ((m->flags & PG_FICTITIOUS) == 0)
252 		return (&page_to_pmdp(m)->pv_lock);
253 	else
254 		return (&pv_dummy_large.pv_lock);
255 }
256 
257 #define	CHANGE_PV_LIST_LOCK(lockp, new_lock)	do {	\
258 	struct rwlock **_lockp = (lockp);		\
259 	struct rwlock *_new_lock = (new_lock);		\
260 							\
261 	if (_new_lock != *_lockp) {			\
262 		if (*_lockp != NULL)			\
263 			rw_wunlock(*_lockp);		\
264 		*_lockp = _new_lock;			\
265 		rw_wlock(*_lockp);			\
266 	}						\
267 } while (0)
268 
269 #define	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)		\
270 			CHANGE_PV_LIST_LOCK(lockp, PHYS_TO_PV_LIST_LOCK(pa))
271 
272 #define	CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)	\
273 			CHANGE_PV_LIST_LOCK(lockp, VM_PAGE_TO_PV_LIST_LOCK(m))
274 
275 #define	RELEASE_PV_LIST_LOCK(lockp)		do {	\
276 	struct rwlock **_lockp = (lockp);		\
277 							\
278 	if (*_lockp != NULL) {				\
279 		rw_wunlock(*_lockp);			\
280 		*_lockp = NULL;				\
281 	}						\
282 } while (0)
283 
284 #define PTE_TO_VM_PAGE(pte) PHYS_TO_VM_PAGE(PTE_TO_PHYS(pte))
285 #define VM_PAGE_TO_PTE(m) PHYS_TO_PTE(VM_PAGE_TO_PHYS(m))
286 
287 /*
288  * The presence of this flag indicates that the mapping is writeable.
289  * If the ATTR_S1_AP_RO bit is also set, then the mapping is clean, otherwise
290  * it is dirty.  This flag may only be set on managed mappings.
291  *
292  * The DBM bit is reserved on ARMv8.0 but it seems we can safely treat it
293  * as a software managed bit.
294  */
295 #define	ATTR_SW_DBM	ATTR_DBM
296 
297 struct pmap kernel_pmap_store;
298 
299 /* Used for mapping ACPI memory before VM is initialized */
300 #define	PMAP_PREINIT_MAPPING_COUNT	32
301 #define	PMAP_PREINIT_MAPPING_SIZE	(PMAP_PREINIT_MAPPING_COUNT * L2_SIZE)
302 static vm_offset_t preinit_map_va;	/* Start VA of pre-init mapping space */
303 static int vm_initialized = 0;		/* No need to use pre-init maps when set */
304 
305 /*
306  * Reserve a few L2 blocks starting from 'preinit_map_va' pointer.
307  * Always map entire L2 block for simplicity.
308  * VA of L2 block = preinit_map_va + i * L2_SIZE
309  */
310 static struct pmap_preinit_mapping {
311 	vm_paddr_t	pa;
312 	vm_offset_t	va;
313 	vm_size_t	size;
314 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
315 
316 vm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
317 vm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
318 vm_offset_t kernel_vm_end = 0;
319 
320 /*
321  * Data for the pv entry allocation mechanism.
322  */
323 #ifdef NUMA
324 static __inline int
pc_to_domain(struct pv_chunk * pc)325 pc_to_domain(struct pv_chunk *pc)
326 {
327 	return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
328 }
329 #else
330 static __inline int
pc_to_domain(struct pv_chunk * pc __unused)331 pc_to_domain(struct pv_chunk *pc __unused)
332 {
333 	return (0);
334 }
335 #endif
336 
337 struct pv_chunks_list {
338 	struct mtx pvc_lock;
339 	TAILQ_HEAD(pch, pv_chunk) pvc_list;
340 	int active_reclaims;
341 } __aligned(CACHE_LINE_SIZE);
342 
343 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
344 
345 vm_paddr_t dmap_phys_base;	/* The start of the dmap region */
346 vm_paddr_t dmap_phys_max;	/* The limit of the dmap region */
347 vm_offset_t dmap_max_addr;	/* The virtual address limit of the dmap */
348 
349 extern pt_entry_t pagetable_l0_ttbr1[];
350 
351 #define	PHYSMAP_SIZE	(2 * (VM_PHYSSEG_MAX - 1))
352 static vm_paddr_t physmap[PHYSMAP_SIZE];
353 static u_int physmap_idx;
354 
355 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
356     "VM/pmap parameters");
357 
358 static bool pmap_lpa_enabled __read_mostly = false;
359 pt_entry_t pmap_sh_attr __read_mostly = ATTR_SH(ATTR_SH_IS);
360 
361 #if PAGE_SIZE == PAGE_SIZE_4K
362 #define	L1_BLOCKS_SUPPORTED	1
363 #else
364 #define	L1_BLOCKS_SUPPORTED	(pmap_lpa_enabled)
365 #endif
366 
367 #define	PMAP_ASSERT_L1_BLOCKS_SUPPORTED	MPASS(L1_BLOCKS_SUPPORTED)
368 
369 static bool pmap_l1_supported __read_mostly = false;
370 
371 /*
372  * This ASID allocator uses a bit vector ("asid_set") to remember which ASIDs
373  * that it has currently allocated to a pmap, a cursor ("asid_next") to
374  * optimize its search for a free ASID in the bit vector, and an epoch number
375  * ("asid_epoch") to indicate when it has reclaimed all previously allocated
376  * ASIDs that are not currently active on a processor.
377  *
378  * The current epoch number is always in the range [0, INT_MAX).  Negative
379  * numbers and INT_MAX are reserved for special cases that are described
380  * below.
381  */
382 struct asid_set {
383 	int asid_bits;
384 	bitstr_t *asid_set;
385 	int asid_set_size;
386 	int asid_next;
387 	int asid_epoch;
388 	struct mtx asid_set_mutex;
389 };
390 
391 static struct asid_set asids;
392 static struct asid_set vmids;
393 
394 static SYSCTL_NODE(_vm_pmap, OID_AUTO, asid, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
395     "ASID allocator");
396 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, bits, CTLFLAG_RD, &asids.asid_bits, 0,
397     "The number of bits in an ASID");
398 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, next, CTLFLAG_RD, &asids.asid_next, 0,
399     "The last allocated ASID plus one");
400 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, epoch, CTLFLAG_RD, &asids.asid_epoch, 0,
401     "The current epoch number");
402 
403 static SYSCTL_NODE(_vm_pmap, OID_AUTO, vmid, CTLFLAG_RD, 0, "VMID allocator");
404 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, bits, CTLFLAG_RD, &vmids.asid_bits, 0,
405     "The number of bits in an VMID");
406 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, next, CTLFLAG_RD, &vmids.asid_next, 0,
407     "The last allocated VMID plus one");
408 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, epoch, CTLFLAG_RD, &vmids.asid_epoch, 0,
409     "The current epoch number");
410 
411 void (*pmap_clean_stage2_tlbi)(void);
412 void (*pmap_stage2_invalidate_range)(uint64_t, vm_offset_t, vm_offset_t, bool);
413 void (*pmap_stage2_invalidate_all)(uint64_t);
414 
415 /*
416  * A pmap's cookie encodes an ASID and epoch number.  Cookies for reserved
417  * ASIDs have a negative epoch number, specifically, INT_MIN.  Cookies for
418  * dynamically allocated ASIDs have a non-negative epoch number.
419  *
420  * An invalid ASID is represented by -1.
421  *
422  * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
423  * which indicates that an ASID should never be allocated to the pmap, and
424  * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
425  * allocated when the pmap is next activated.
426  */
427 #define	COOKIE_FROM(asid, epoch)	((long)((u_int)(asid) |	\
428 					    ((u_long)(epoch) << 32)))
429 #define	COOKIE_TO_ASID(cookie)		((int)(cookie))
430 #define	COOKIE_TO_EPOCH(cookie)		((int)((u_long)(cookie) >> 32))
431 
432 #define	TLBI_VA_SHIFT			12
433 #define	TLBI_VA_MASK			((1ul << 44) - 1)
434 #define	TLBI_VA(addr)			(((addr) >> TLBI_VA_SHIFT) & TLBI_VA_MASK)
435 
436 static int __read_frequently superpages_enabled = 1;
437 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
438     CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
439     "Are large page mappings enabled?");
440 
441 /*
442  * True when Branch Target Identification should be used by userspace. This
443  * allows pmap to mark pages as guarded with ATTR_S1_GP.
444  */
445 __read_mostly static bool pmap_bti_support = false;
446 
447 /*
448  * Internal flags for pmap_enter()'s helper functions.
449  */
450 #define	PMAP_ENTER_NORECLAIM	0x1000000	/* Don't reclaim PV entries. */
451 #define	PMAP_ENTER_NOREPLACE	0x2000000	/* Don't replace mappings. */
452 
453 TAILQ_HEAD(pv_chunklist, pv_chunk);
454 
455 static void	free_pv_chunk(struct pv_chunk *pc);
456 static void	free_pv_chunk_batch(struct pv_chunklist *batch);
457 static void	free_pv_entry(pmap_t pmap, pv_entry_t pv);
458 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
459 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
460 static void	pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
461 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
462 		    vm_offset_t va);
463 
464 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
465 static bool pmap_activate_int(pmap_t pmap);
466 static void pmap_alloc_asid(pmap_t pmap);
467 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
468     vm_prot_t prot, int mode, bool skip_unmapped);
469 static bool pmap_copy_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va,
470     pt_entry_t l3e, vm_page_t ml3, struct rwlock **lockp);
471 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
472 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
473     vm_offset_t va, struct rwlock **lockp);
474 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
475 static bool pmap_demote_l2c(pmap_t pmap, pt_entry_t *l2p, vm_offset_t va);
476 static bool pmap_demote_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va);
477 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
478     vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
479 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
480     u_int flags, vm_page_t m, struct rwlock **lockp);
481 static int pmap_enter_l3c(pmap_t pmap, vm_offset_t va, pt_entry_t l3e, u_int flags,
482     vm_page_t m, vm_page_t *ml3p, struct rwlock **lockp);
483 static bool pmap_every_pte_zero(vm_paddr_t pa);
484 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
485     bool all_l3e_AF_set);
486 static pt_entry_t pmap_load_l3c(pt_entry_t *l3p);
487 static void pmap_mask_set_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va,
488     vm_offset_t *vap, vm_offset_t va_next, pt_entry_t mask, pt_entry_t nbits);
489 static bool pmap_pv_insert_l3c(pmap_t pmap, vm_offset_t va, vm_page_t m,
490     struct rwlock **lockp);
491 static void pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
492 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
493     pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
494 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
495     pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
496 static bool pmap_remove_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va,
497     vm_offset_t *vap, vm_offset_t va_next, vm_page_t ml3, struct spglist *free,
498     struct rwlock **lockp);
499 static void pmap_reset_asid_set(pmap_t pmap);
500 static bool pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
501     vm_page_t m, struct rwlock **lockp);
502 
503 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
504 		struct rwlock **lockp);
505 
506 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
507     struct spglist *free);
508 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
509 static void pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
510     vm_offset_t va, vm_size_t size);
511 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
512 
513 static uma_zone_t pmap_bti_ranges_zone;
514 static bool pmap_bti_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
515     pt_entry_t *pte);
516 static pt_entry_t pmap_pte_bti(pmap_t pmap, vm_offset_t va);
517 static void pmap_bti_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
518 static void *bti_dup_range(void *ctx, void *data);
519 static void bti_free_range(void *ctx, void *node);
520 static int pmap_bti_copy(pmap_t dst_pmap, pmap_t src_pmap);
521 static void pmap_bti_deassign_all(pmap_t pmap);
522 
523 /*
524  * These load the old table data and store the new value.
525  * They need to be atomic as the System MMU may write to the table at
526  * the same time as the CPU.
527  */
528 #define	pmap_clear(table)		atomic_store_64(table, 0)
529 #define	pmap_clear_bits(table, bits)	atomic_clear_64(table, bits)
530 #define	pmap_load(table)		(*table)
531 #define	pmap_load_clear(table)		atomic_swap_64(table, 0)
532 #define	pmap_load_store(table, entry)	atomic_swap_64(table, entry)
533 #define	pmap_set_bits(table, bits)	atomic_set_64(table, bits)
534 #define	pmap_store(table, entry)	atomic_store_64(table, entry)
535 
536 /********************/
537 /* Inline functions */
538 /********************/
539 
540 static __inline void
pagecopy(void * s,void * d)541 pagecopy(void *s, void *d)
542 {
543 
544 	memcpy(d, s, PAGE_SIZE);
545 }
546 
547 static __inline pd_entry_t *
pmap_l0(pmap_t pmap,vm_offset_t va)548 pmap_l0(pmap_t pmap, vm_offset_t va)
549 {
550 
551 	return (&pmap->pm_l0[pmap_l0_index(va)]);
552 }
553 
554 static __inline pd_entry_t *
pmap_l0_to_l1(pd_entry_t * l0,vm_offset_t va)555 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
556 {
557 	pd_entry_t *l1;
558 
559 	l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
560 	return (&l1[pmap_l1_index(va)]);
561 }
562 
563 static __inline pd_entry_t *
pmap_l1(pmap_t pmap,vm_offset_t va)564 pmap_l1(pmap_t pmap, vm_offset_t va)
565 {
566 	pd_entry_t *l0;
567 
568 	l0 = pmap_l0(pmap, va);
569 	if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
570 		return (NULL);
571 
572 	return (pmap_l0_to_l1(l0, va));
573 }
574 
575 static __inline pd_entry_t *
pmap_l1_to_l2(pd_entry_t * l1p,vm_offset_t va)576 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
577 {
578 	pd_entry_t l1, *l2p;
579 
580 	l1 = pmap_load(l1p);
581 
582 	KASSERT(ADDR_IS_CANONICAL(va),
583 	    ("%s: Address not in canonical form: %lx", __func__, va));
584 	/*
585 	 * The valid bit may be clear if pmap_update_entry() is concurrently
586 	 * modifying the entry, so for KVA only the entry type may be checked.
587 	 */
588 	KASSERT(ADDR_IS_KERNEL(va) || (l1 & ATTR_DESCR_VALID) != 0,
589 	    ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
590 	KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
591 	    ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
592 	l2p = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l1));
593 	return (&l2p[pmap_l2_index(va)]);
594 }
595 
596 static __inline pd_entry_t *
pmap_l2(pmap_t pmap,vm_offset_t va)597 pmap_l2(pmap_t pmap, vm_offset_t va)
598 {
599 	pd_entry_t *l1;
600 
601 	l1 = pmap_l1(pmap, va);
602 	if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
603 		return (NULL);
604 
605 	return (pmap_l1_to_l2(l1, va));
606 }
607 
608 static __inline pt_entry_t *
pmap_l2_to_l3(pd_entry_t * l2p,vm_offset_t va)609 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
610 {
611 	pd_entry_t l2;
612 	pt_entry_t *l3p;
613 
614 	l2 = pmap_load(l2p);
615 
616 	KASSERT(ADDR_IS_CANONICAL(va),
617 	    ("%s: Address not in canonical form: %lx", __func__, va));
618 	/*
619 	 * The valid bit may be clear if pmap_update_entry() is concurrently
620 	 * modifying the entry, so for KVA only the entry type may be checked.
621 	 */
622 	KASSERT(ADDR_IS_KERNEL(va) || (l2 & ATTR_DESCR_VALID) != 0,
623 	    ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
624 	KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
625 	    ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
626 	l3p = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l2));
627 	return (&l3p[pmap_l3_index(va)]);
628 }
629 
630 /*
631  * Returns the lowest valid pde for a given virtual address.
632  * The next level may or may not point to a valid page or block.
633  */
634 static __inline pd_entry_t *
pmap_pde(pmap_t pmap,vm_offset_t va,int * level)635 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
636 {
637 	pd_entry_t *l0, *l1, *l2, desc;
638 
639 	l0 = pmap_l0(pmap, va);
640 	desc = pmap_load(l0) & ATTR_DESCR_MASK;
641 	if (desc != L0_TABLE) {
642 		*level = -1;
643 		return (NULL);
644 	}
645 
646 	l1 = pmap_l0_to_l1(l0, va);
647 	desc = pmap_load(l1) & ATTR_DESCR_MASK;
648 	if (desc != L1_TABLE) {
649 		*level = 0;
650 		return (l0);
651 	}
652 
653 	l2 = pmap_l1_to_l2(l1, va);
654 	desc = pmap_load(l2) & ATTR_DESCR_MASK;
655 	if (desc != L2_TABLE) {
656 		*level = 1;
657 		return (l1);
658 	}
659 
660 	*level = 2;
661 	return (l2);
662 }
663 
664 /*
665  * Returns the lowest valid pte block or table entry for a given virtual
666  * address. If there are no valid entries return NULL and set the level to
667  * the first invalid level.
668  */
669 static __inline pt_entry_t *
pmap_pte(pmap_t pmap,vm_offset_t va,int * level)670 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
671 {
672 	pd_entry_t *l1, *l2, desc;
673 	pt_entry_t *l3;
674 
675 	l1 = pmap_l1(pmap, va);
676 	if (l1 == NULL) {
677 		*level = 0;
678 		return (NULL);
679 	}
680 	desc = pmap_load(l1) & ATTR_DESCR_MASK;
681 	if (desc == L1_BLOCK) {
682 		PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
683 		*level = 1;
684 		return (l1);
685 	}
686 
687 	if (desc != L1_TABLE) {
688 		*level = 1;
689 		return (NULL);
690 	}
691 
692 	l2 = pmap_l1_to_l2(l1, va);
693 	desc = pmap_load(l2) & ATTR_DESCR_MASK;
694 	if (desc == L2_BLOCK) {
695 		*level = 2;
696 		return (l2);
697 	}
698 
699 	if (desc != L2_TABLE) {
700 		*level = 2;
701 		return (NULL);
702 	}
703 
704 	*level = 3;
705 	l3 = pmap_l2_to_l3(l2, va);
706 	if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
707 		return (NULL);
708 
709 	return (l3);
710 }
711 
712 /*
713  * If the given pmap has an L{1,2}_BLOCK or L3_PAGE entry at the specified
714  * level that maps the specified virtual address, then a pointer to that entry
715  * is returned.  Otherwise, NULL is returned, unless INVARIANTS are enabled
716  * and a diagnostic message is provided, in which case this function panics.
717  */
718 static __always_inline pt_entry_t *
pmap_pte_exists(pmap_t pmap,vm_offset_t va,int level,const char * diag)719 pmap_pte_exists(pmap_t pmap, vm_offset_t va, int level, const char *diag)
720 {
721 	pd_entry_t *l0p, *l1p, *l2p;
722 	pt_entry_t desc, *l3p;
723 	int walk_level __diagused;
724 
725 	KASSERT(level >= 0 && level < 4,
726 	    ("%s: %s passed an out-of-range level (%d)", __func__, diag,
727 	    level));
728 	l0p = pmap_l0(pmap, va);
729 	desc = pmap_load(l0p) & ATTR_DESCR_MASK;
730 	if (desc == L0_TABLE && level > 0) {
731 		l1p = pmap_l0_to_l1(l0p, va);
732 		desc = pmap_load(l1p) & ATTR_DESCR_MASK;
733 		if (desc == L1_BLOCK && level == 1) {
734 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
735 			return (l1p);
736 		}
737 		if (desc == L1_TABLE && level > 1) {
738 			l2p = pmap_l1_to_l2(l1p, va);
739 			desc = pmap_load(l2p) & ATTR_DESCR_MASK;
740 			if (desc == L2_BLOCK && level == 2)
741 				return (l2p);
742 			else if (desc == L2_TABLE && level > 2) {
743 				l3p = pmap_l2_to_l3(l2p, va);
744 				desc = pmap_load(l3p) & ATTR_DESCR_MASK;
745 				if (desc == L3_PAGE && level == 3)
746 					return (l3p);
747 				else
748 					walk_level = 3;
749 			} else
750 				walk_level = 2;
751 		} else
752 			walk_level = 1;
753 	} else
754 		walk_level = 0;
755 	KASSERT(diag == NULL,
756 	    ("%s: va %#lx not mapped at level %d, desc %ld at level %d",
757 	    diag, va, level, desc, walk_level));
758 	return (NULL);
759 }
760 
761 bool
pmap_ps_enabled(pmap_t pmap)762 pmap_ps_enabled(pmap_t pmap)
763 {
764 	/*
765 	 * Promotion requires a hypervisor call when the kernel is running
766 	 * in EL1. To stop this disable superpage support on non-stage 1
767 	 * pmaps for now.
768 	 */
769 	if (pmap->pm_stage != PM_STAGE1)
770 		return (false);
771 
772 #ifdef KMSAN
773 	/*
774 	 * The break-before-make in pmap_update_entry() results in a situation
775 	 * where a CPU may call into the KMSAN runtime while the entry is
776 	 * invalid.  If the entry is used to map the current thread structure,
777 	 * then the runtime will attempt to access unmapped memory.  Avoid this
778 	 * by simply disabling superpage promotion for the kernel map.
779 	 */
780 	if (pmap == kernel_pmap)
781 		return (false);
782 #endif
783 
784 	return (superpages_enabled != 0);
785 }
786 
787 bool
pmap_get_tables(pmap_t pmap,vm_offset_t va,pd_entry_t ** l0,pd_entry_t ** l1,pd_entry_t ** l2,pt_entry_t ** l3)788 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
789     pd_entry_t **l2, pt_entry_t **l3)
790 {
791 	pd_entry_t *l0p, *l1p, *l2p;
792 
793 	if (pmap->pm_l0 == NULL)
794 		return (false);
795 
796 	l0p = pmap_l0(pmap, va);
797 	*l0 = l0p;
798 
799 	if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
800 		return (false);
801 
802 	l1p = pmap_l0_to_l1(l0p, va);
803 	*l1 = l1p;
804 
805 	if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
806 		PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
807 		*l2 = NULL;
808 		*l3 = NULL;
809 		return (true);
810 	}
811 
812 	if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
813 		return (false);
814 
815 	l2p = pmap_l1_to_l2(l1p, va);
816 	*l2 = l2p;
817 
818 	if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
819 		*l3 = NULL;
820 		return (true);
821 	}
822 
823 	if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
824 		return (false);
825 
826 	*l3 = pmap_l2_to_l3(l2p, va);
827 
828 	return (true);
829 }
830 
831 static __inline int
pmap_l3_valid(pt_entry_t l3)832 pmap_l3_valid(pt_entry_t l3)
833 {
834 
835 	return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
836 }
837 
838 CTASSERT(L1_BLOCK == L2_BLOCK);
839 
840 static pt_entry_t
pmap_pte_memattr(pmap_t pmap,vm_memattr_t memattr)841 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
842 {
843 	pt_entry_t val;
844 
845 	if (pmap->pm_stage == PM_STAGE1) {
846 		val = ATTR_S1_IDX(memattr);
847 		if (memattr == VM_MEMATTR_DEVICE)
848 			val |= ATTR_S1_XN;
849 		return (val);
850 	}
851 
852 	val = 0;
853 
854 	switch (memattr) {
855 	case VM_MEMATTR_DEVICE:
856 		return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
857 		    ATTR_S2_XN(ATTR_S2_XN_ALL));
858 	case VM_MEMATTR_UNCACHEABLE:
859 		return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
860 	case VM_MEMATTR_WRITE_BACK:
861 		return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
862 	case VM_MEMATTR_WRITE_THROUGH:
863 		return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
864 	default:
865 		panic("%s: invalid memory attribute %x", __func__, memattr);
866 	}
867 }
868 
869 static pt_entry_t
pmap_pte_prot(pmap_t pmap,vm_prot_t prot)870 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
871 {
872 	pt_entry_t val;
873 
874 	val = 0;
875 	if (pmap->pm_stage == PM_STAGE1) {
876 		if ((prot & VM_PROT_EXECUTE) == 0)
877 			val |= ATTR_S1_XN;
878 		if ((prot & VM_PROT_WRITE) == 0)
879 			val |= ATTR_S1_AP(ATTR_S1_AP_RO);
880 	} else {
881 		if ((prot & VM_PROT_WRITE) != 0)
882 			val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
883 		if ((prot & VM_PROT_READ) != 0)
884 			val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
885 		if ((prot & VM_PROT_EXECUTE) == 0)
886 			val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
887 	}
888 
889 	return (val);
890 }
891 
892 /*
893  * Checks if the PTE is dirty.
894  */
895 static inline int
pmap_pte_dirty(pmap_t pmap,pt_entry_t pte)896 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
897 {
898 
899 	KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
900 
901 	if (pmap->pm_stage == PM_STAGE1) {
902 		KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
903 		    ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
904 
905 		return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
906 		    (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
907 	}
908 
909 	return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
910 	    ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
911 }
912 
913 static __inline void
pmap_resident_count_inc(pmap_t pmap,int count)914 pmap_resident_count_inc(pmap_t pmap, int count)
915 {
916 
917 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
918 	pmap->pm_stats.resident_count += count;
919 }
920 
921 static __inline void
pmap_resident_count_dec(pmap_t pmap,int count)922 pmap_resident_count_dec(pmap_t pmap, int count)
923 {
924 
925 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
926 	KASSERT(pmap->pm_stats.resident_count >= count,
927 	    ("pmap %p resident count underflow %ld %d", pmap,
928 	    pmap->pm_stats.resident_count, count));
929 	pmap->pm_stats.resident_count -= count;
930 }
931 
932 static vm_paddr_t
pmap_early_vtophys(vm_offset_t va)933 pmap_early_vtophys(vm_offset_t va)
934 {
935 	vm_paddr_t pa_page;
936 
937 	pa_page = arm64_address_translate_s1e1r(va) & PAR_PA_MASK;
938 	return (pa_page | (va & PAR_LOW_MASK));
939 }
940 
941 /* State of the bootstrapped DMAP page tables */
942 struct pmap_bootstrap_state {
943 	pt_entry_t	*l1;
944 	pt_entry_t	*l2;
945 	pt_entry_t	*l3;
946 	vm_offset_t	freemempos;
947 	vm_offset_t	va;
948 	vm_paddr_t	pa;
949 	pt_entry_t	table_attrs;
950 	u_int		l0_slot;
951 	u_int		l1_slot;
952 	u_int		l2_slot;
953 	bool		dmap_valid;
954 };
955 
956 /* The bootstrap state */
957 static struct pmap_bootstrap_state bs_state = {
958 	.l1 = NULL,
959 	.l2 = NULL,
960 	.l3 = NULL,
961 	.table_attrs = TATTR_PXN_TABLE,
962 	.l0_slot = L0_ENTRIES,
963 	.l1_slot = Ln_ENTRIES,
964 	.l2_slot = Ln_ENTRIES,
965 	.dmap_valid = false,
966 };
967 
968 static void
pmap_bootstrap_l0_table(struct pmap_bootstrap_state * state)969 pmap_bootstrap_l0_table(struct pmap_bootstrap_state *state)
970 {
971 	vm_paddr_t l1_pa;
972 	pd_entry_t l0e;
973 	u_int l0_slot;
974 
975 	/* Link the level 0 table to a level 1 table */
976 	l0_slot = pmap_l0_index(state->va);
977 	if (l0_slot != state->l0_slot) {
978 		/*
979 		 * Make sure we move from a low address to high address
980 		 * before the DMAP region is ready. This ensures we never
981 		 * modify an existing mapping until we can map from a
982 		 * physical address to a virtual address.
983 		 */
984 		MPASS(state->l0_slot < l0_slot ||
985 		    state->l0_slot == L0_ENTRIES ||
986 		    state->dmap_valid);
987 
988 		/* Reset lower levels */
989 		state->l2 = NULL;
990 		state->l3 = NULL;
991 		state->l1_slot = Ln_ENTRIES;
992 		state->l2_slot = Ln_ENTRIES;
993 
994 		/* Check the existing L0 entry */
995 		state->l0_slot = l0_slot;
996 		if (state->dmap_valid) {
997 			l0e = pagetable_l0_ttbr1[l0_slot];
998 			if ((l0e & ATTR_DESCR_VALID) != 0) {
999 				MPASS((l0e & ATTR_DESCR_MASK) == L0_TABLE);
1000 				l1_pa = PTE_TO_PHYS(l0e);
1001 				state->l1 = (pt_entry_t *)PHYS_TO_DMAP(l1_pa);
1002 				return;
1003 			}
1004 		}
1005 
1006 		/* Create a new L0 table entry */
1007 		state->l1 = (pt_entry_t *)state->freemempos;
1008 		memset(state->l1, 0, PAGE_SIZE);
1009 		state->freemempos += PAGE_SIZE;
1010 
1011 		l1_pa = pmap_early_vtophys((vm_offset_t)state->l1);
1012 		MPASS((l1_pa & Ln_TABLE_MASK) == 0);
1013 		MPASS(pagetable_l0_ttbr1[l0_slot] == 0);
1014 		pmap_store(&pagetable_l0_ttbr1[l0_slot], PHYS_TO_PTE(l1_pa) |
1015 		    TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0 | L0_TABLE);
1016 	}
1017 	KASSERT(state->l1 != NULL, ("%s: NULL l1", __func__));
1018 }
1019 
1020 static void
pmap_bootstrap_l1_table(struct pmap_bootstrap_state * state)1021 pmap_bootstrap_l1_table(struct pmap_bootstrap_state *state)
1022 {
1023 	vm_paddr_t l2_pa;
1024 	pd_entry_t l1e;
1025 	u_int l1_slot;
1026 
1027 	/* Make sure there is a valid L0 -> L1 table */
1028 	pmap_bootstrap_l0_table(state);
1029 
1030 	/* Link the level 1 table to a level 2 table */
1031 	l1_slot = pmap_l1_index(state->va);
1032 	if (l1_slot != state->l1_slot) {
1033 		/* See pmap_bootstrap_l0_table for a description */
1034 		MPASS(state->l1_slot < l1_slot ||
1035 		    state->l1_slot == Ln_ENTRIES ||
1036 		    state->dmap_valid);
1037 
1038 		/* Reset lower levels */
1039 		state->l3 = NULL;
1040 		state->l2_slot = Ln_ENTRIES;
1041 
1042 		/* Check the existing L1 entry */
1043 		state->l1_slot = l1_slot;
1044 		if (state->dmap_valid) {
1045 			l1e = state->l1[l1_slot];
1046 			if ((l1e & ATTR_DESCR_VALID) != 0) {
1047 				MPASS((l1e & ATTR_DESCR_MASK) == L1_TABLE);
1048 				l2_pa = PTE_TO_PHYS(l1e);
1049 				state->l2 = (pt_entry_t *)PHYS_TO_DMAP(l2_pa);
1050 				return;
1051 			}
1052 		}
1053 
1054 		/* Create a new L1 table entry */
1055 		state->l2 = (pt_entry_t *)state->freemempos;
1056 		memset(state->l2, 0, PAGE_SIZE);
1057 		state->freemempos += PAGE_SIZE;
1058 
1059 		l2_pa = pmap_early_vtophys((vm_offset_t)state->l2);
1060 		MPASS((l2_pa & Ln_TABLE_MASK) == 0);
1061 		MPASS(state->l1[l1_slot] == 0);
1062 		pmap_store(&state->l1[l1_slot], PHYS_TO_PTE(l2_pa) |
1063 		    state->table_attrs | L1_TABLE);
1064 	}
1065 	KASSERT(state->l2 != NULL, ("%s: NULL l2", __func__));
1066 }
1067 
1068 static void
pmap_bootstrap_l2_table(struct pmap_bootstrap_state * state)1069 pmap_bootstrap_l2_table(struct pmap_bootstrap_state *state)
1070 {
1071 	vm_paddr_t l3_pa;
1072 	pd_entry_t l2e;
1073 	u_int l2_slot;
1074 
1075 	/* Make sure there is a valid L1 -> L2 table */
1076 	pmap_bootstrap_l1_table(state);
1077 
1078 	/* Link the level 2 table to a level 3 table */
1079 	l2_slot = pmap_l2_index(state->va);
1080 	if (l2_slot != state->l2_slot) {
1081 		/* See pmap_bootstrap_l0_table for a description */
1082 		MPASS(state->l2_slot < l2_slot ||
1083 		    state->l2_slot == Ln_ENTRIES ||
1084 		    state->dmap_valid);
1085 
1086 		/* Check the existing L2 entry */
1087 		state->l2_slot = l2_slot;
1088 		if (state->dmap_valid) {
1089 			l2e = state->l2[l2_slot];
1090 			if ((l2e & ATTR_DESCR_VALID) != 0) {
1091 				MPASS((l2e & ATTR_DESCR_MASK) == L2_TABLE);
1092 				l3_pa = PTE_TO_PHYS(l2e);
1093 				state->l3 = (pt_entry_t *)PHYS_TO_DMAP(l3_pa);
1094 				return;
1095 			}
1096 		}
1097 
1098 		/* Create a new L2 table entry */
1099 		state->l3 = (pt_entry_t *)state->freemempos;
1100 		memset(state->l3, 0, PAGE_SIZE);
1101 		state->freemempos += PAGE_SIZE;
1102 
1103 		l3_pa = pmap_early_vtophys((vm_offset_t)state->l3);
1104 		MPASS((l3_pa & Ln_TABLE_MASK) == 0);
1105 		MPASS(state->l2[l2_slot] == 0);
1106 		pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(l3_pa) |
1107 		    state->table_attrs | L2_TABLE);
1108 	}
1109 	KASSERT(state->l3 != NULL, ("%s: NULL l3", __func__));
1110 }
1111 
1112 static void
pmap_bootstrap_l2_block(struct pmap_bootstrap_state * state,int i)1113 pmap_bootstrap_l2_block(struct pmap_bootstrap_state *state, int i)
1114 {
1115 	pt_entry_t contig;
1116 	u_int l2_slot;
1117 	bool first;
1118 
1119 	if ((physmap[i + 1] - state->pa) < L2_SIZE)
1120 		return;
1121 
1122 	/* Make sure there is a valid L1 table */
1123 	pmap_bootstrap_l1_table(state);
1124 
1125 	MPASS((state->va & L2_OFFSET) == 0);
1126 	for (first = true, contig = 0;
1127 	    state->va < DMAP_MAX_ADDRESS &&
1128 	    (physmap[i + 1] - state->pa) >= L2_SIZE;
1129 	    state->va += L2_SIZE, state->pa += L2_SIZE) {
1130 		/*
1131 		 * Stop if we are about to walk off the end of what the
1132 		 * current L1 slot can address.
1133 		 */
1134 		if (!first && (state->pa & L1_OFFSET) == 0)
1135 			break;
1136 
1137 		/*
1138 		 * If we have an aligned, contiguous chunk of L2C_ENTRIES
1139 		 * L2 blocks, set the contiguous bit within each PTE so that
1140 		 * the chunk can be cached using only one TLB entry.
1141 		 */
1142 		if ((state->pa & L2C_OFFSET) == 0) {
1143 			if (state->va + L2C_SIZE < DMAP_MAX_ADDRESS &&
1144 			    physmap[i + 1] - state->pa >= L2C_SIZE) {
1145 				contig = ATTR_CONTIGUOUS;
1146 			} else {
1147 				contig = 0;
1148 			}
1149 		}
1150 
1151 		first = false;
1152 		l2_slot = pmap_l2_index(state->va);
1153 		MPASS((state->pa & L2_OFFSET) == 0);
1154 		MPASS(state->l2[l2_slot] == 0);
1155 		pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(state->pa) |
1156 		    ATTR_AF | pmap_sh_attr | ATTR_S1_XN | ATTR_KERN_GP |
1157 		    ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | contig | L2_BLOCK);
1158 	}
1159 	MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1160 }
1161 
1162 static void
pmap_bootstrap_l3_page(struct pmap_bootstrap_state * state,int i)1163 pmap_bootstrap_l3_page(struct pmap_bootstrap_state *state, int i)
1164 {
1165 	pt_entry_t contig;
1166 	u_int l3_slot;
1167 	bool first;
1168 
1169 	if (physmap[i + 1] - state->pa < L3_SIZE)
1170 		return;
1171 
1172 	/* Make sure there is a valid L2 table */
1173 	pmap_bootstrap_l2_table(state);
1174 
1175 	MPASS((state->va & L3_OFFSET) == 0);
1176 	for (first = true, contig = 0;
1177 	    state->va < DMAP_MAX_ADDRESS &&
1178 	    physmap[i + 1] - state->pa >= L3_SIZE;
1179 	    state->va += L3_SIZE, state->pa += L3_SIZE) {
1180 		/*
1181 		 * Stop if we are about to walk off the end of what the
1182 		 * current L2 slot can address.
1183 		 */
1184 		if (!first && (state->pa & L2_OFFSET) == 0)
1185 			break;
1186 
1187 		/*
1188 		 * If we have an aligned, contiguous chunk of L3C_ENTRIES
1189 		 * L3 pages, set the contiguous bit within each PTE so that
1190 		 * the chunk can be cached using only one TLB entry.
1191 		 */
1192 		if ((state->pa & L3C_OFFSET) == 0) {
1193 			if (state->va + L3C_SIZE < DMAP_MAX_ADDRESS &&
1194 			    physmap[i + 1] - state->pa >= L3C_SIZE) {
1195 				contig = ATTR_CONTIGUOUS;
1196 			} else {
1197 				contig = 0;
1198 			}
1199 		}
1200 
1201 		first = false;
1202 		l3_slot = pmap_l3_index(state->va);
1203 		MPASS((state->pa & L3_OFFSET) == 0);
1204 		MPASS(state->l3[l3_slot] == 0);
1205 		pmap_store(&state->l3[l3_slot], PHYS_TO_PTE(state->pa) |
1206 		    ATTR_AF | pmap_sh_attr | ATTR_S1_XN | ATTR_KERN_GP |
1207 		    ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | contig | L3_PAGE);
1208 	}
1209 	MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1210 }
1211 
1212 static void
pmap_bootstrap_dmap(void)1213 pmap_bootstrap_dmap(void)
1214 {
1215 	int i;
1216 
1217 	/* Fill in physmap array. */
1218 	physmap_idx = physmem_avail(physmap, nitems(physmap));
1219 
1220 	dmap_phys_base = physmap[0] & ~L1_OFFSET;
1221 	dmap_phys_max = 0;
1222 	dmap_max_addr = 0;
1223 
1224 	for (i = 0; i < physmap_idx; i += 2) {
1225 		bs_state.pa = physmap[i] & ~L3_OFFSET;
1226 		bs_state.va = bs_state.pa - dmap_phys_base + DMAP_MIN_ADDRESS;
1227 
1228 		/* Create L3 mappings at the start of the region */
1229 		if ((bs_state.pa & L2_OFFSET) != 0)
1230 			pmap_bootstrap_l3_page(&bs_state, i);
1231 		MPASS(bs_state.pa <= physmap[i + 1]);
1232 
1233 		if (L1_BLOCKS_SUPPORTED) {
1234 			/* Create L2 mappings at the start of the region */
1235 			if ((bs_state.pa & L1_OFFSET) != 0)
1236 				pmap_bootstrap_l2_block(&bs_state, i);
1237 			MPASS(bs_state.pa <= physmap[i + 1]);
1238 
1239 			/* Create the main L1 block mappings */
1240 			for (; bs_state.va < DMAP_MAX_ADDRESS &&
1241 			    (physmap[i + 1] - bs_state.pa) >= L1_SIZE;
1242 			    bs_state.va += L1_SIZE, bs_state.pa += L1_SIZE) {
1243 				/* Make sure there is a valid L1 table */
1244 				pmap_bootstrap_l0_table(&bs_state);
1245 				MPASS((bs_state.pa & L1_OFFSET) == 0);
1246 				pmap_store(
1247 				    &bs_state.l1[pmap_l1_index(bs_state.va)],
1248 				    PHYS_TO_PTE(bs_state.pa) | ATTR_AF |
1249 				    pmap_sh_attr |
1250 				    ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1251 				    ATTR_S1_XN | ATTR_KERN_GP | L1_BLOCK);
1252 			}
1253 			MPASS(bs_state.pa <= physmap[i + 1]);
1254 
1255 			/* Create L2 mappings at the end of the region */
1256 			pmap_bootstrap_l2_block(&bs_state, i);
1257 		} else {
1258 			while (bs_state.va < DMAP_MAX_ADDRESS &&
1259 			    (physmap[i + 1] - bs_state.pa) >= L2_SIZE) {
1260 				pmap_bootstrap_l2_block(&bs_state, i);
1261 			}
1262 		}
1263 		MPASS(bs_state.pa <= physmap[i + 1]);
1264 
1265 		/* Create L3 mappings at the end of the region */
1266 		pmap_bootstrap_l3_page(&bs_state, i);
1267 		MPASS(bs_state.pa == physmap[i + 1]);
1268 
1269 		if (bs_state.pa > dmap_phys_max) {
1270 			dmap_phys_max = bs_state.pa;
1271 			dmap_max_addr = bs_state.va;
1272 		}
1273 	}
1274 
1275 	cpu_tlb_flushID();
1276 }
1277 
1278 static void
pmap_bootstrap_l2(vm_offset_t va)1279 pmap_bootstrap_l2(vm_offset_t va)
1280 {
1281 	KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
1282 
1283 	/* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1284 	bs_state.va = va;
1285 
1286 	for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L1_SIZE)
1287 		pmap_bootstrap_l1_table(&bs_state);
1288 }
1289 
1290 static void
pmap_bootstrap_l3(vm_offset_t va)1291 pmap_bootstrap_l3(vm_offset_t va)
1292 {
1293 	KASSERT((va & L2_OFFSET) == 0, ("Invalid virtual address"));
1294 
1295 	/* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1296 	bs_state.va = va;
1297 
1298 	for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L2_SIZE)
1299 		pmap_bootstrap_l2_table(&bs_state);
1300 }
1301 
1302 /*
1303  *	Bootstrap the system enough to run with virtual memory.
1304  */
1305 void
pmap_bootstrap(vm_size_t kernlen)1306 pmap_bootstrap(vm_size_t kernlen)
1307 {
1308 	vm_offset_t dpcpu, msgbufpv;
1309 	vm_paddr_t start_pa, pa;
1310 	uint64_t tcr;
1311 
1312 	tcr = READ_SPECIALREG(tcr_el1);
1313 
1314 	/* Verify that the ASID is set through TTBR0. */
1315 	KASSERT((tcr & TCR_A1) == 0, ("pmap_bootstrap: TCR_EL1.A1 != 0"));
1316 
1317 	if ((tcr & TCR_DS) != 0)
1318 		pmap_lpa_enabled = true;
1319 
1320 	pmap_l1_supported = L1_BLOCKS_SUPPORTED;
1321 
1322 	/* Set this early so we can use the pagetable walking functions */
1323 	kernel_pmap_store.pm_l0 = pagetable_l0_ttbr1;
1324 	PMAP_LOCK_INIT(kernel_pmap);
1325 	kernel_pmap->pm_l0_paddr =
1326 	    pmap_early_vtophys((vm_offset_t)kernel_pmap_store.pm_l0);
1327 	TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1328 	vm_radix_init(&kernel_pmap->pm_root);
1329 	kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
1330 	kernel_pmap->pm_stage = PM_STAGE1;
1331 	kernel_pmap->pm_levels = 4;
1332 	kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
1333 	kernel_pmap->pm_asid_set = &asids;
1334 
1335 	bs_state.freemempos = KERNBASE + kernlen;
1336 	bs_state.freemempos = roundup2(bs_state.freemempos, PAGE_SIZE);
1337 
1338 	/* Create a direct map region early so we can use it for pa -> va */
1339 	pmap_bootstrap_dmap();
1340 	bs_state.dmap_valid = true;
1341 
1342 	/*
1343 	 * We only use PXN when we know nothing will be executed from it, e.g.
1344 	 * the DMAP region.
1345 	 */
1346 	bs_state.table_attrs &= ~TATTR_PXN_TABLE;
1347 
1348 	start_pa = pa = pmap_early_vtophys(KERNBASE);
1349 
1350 	/*
1351 	 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS.  We assume that the
1352 	 * loader allocated the first and only l2 page table page used to map
1353 	 * the kernel, preloaded files and module metadata.
1354 	 */
1355 	pmap_bootstrap_l2(KERNBASE + L1_SIZE);
1356 	/* And the l3 tables for the early devmap */
1357 	pmap_bootstrap_l3(VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE));
1358 
1359 	cpu_tlb_flushID();
1360 
1361 #define alloc_pages(var, np)						\
1362 	(var) = bs_state.freemempos;					\
1363 	bs_state.freemempos += (np * PAGE_SIZE);			\
1364 	memset((char *)(var), 0, ((np) * PAGE_SIZE));
1365 
1366 	/* Allocate dynamic per-cpu area. */
1367 	alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1368 	dpcpu_init((void *)dpcpu, 0);
1369 
1370 	/* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1371 	alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1372 	msgbufp = (void *)msgbufpv;
1373 
1374 	/* Reserve some VA space for early BIOS/ACPI mapping */
1375 	preinit_map_va = roundup2(bs_state.freemempos, L2_SIZE);
1376 
1377 	virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1378 	virtual_avail = roundup2(virtual_avail, L1_SIZE);
1379 	virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1380 	kernel_vm_end = virtual_avail;
1381 
1382 	pa = pmap_early_vtophys(bs_state.freemempos);
1383 
1384 	physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1385 
1386 	cpu_tlb_flushID();
1387 }
1388 
1389 #if defined(KASAN) || defined(KMSAN)
1390 static void
pmap_bootstrap_allocate_san_l2(vm_paddr_t start_pa,vm_paddr_t end_pa,vm_offset_t * vap,vm_offset_t eva)1391 pmap_bootstrap_allocate_san_l2(vm_paddr_t start_pa, vm_paddr_t end_pa,
1392     vm_offset_t *vap, vm_offset_t eva)
1393 {
1394 	vm_paddr_t pa;
1395 	vm_offset_t va;
1396 	pd_entry_t *l2;
1397 
1398 	va = *vap;
1399 	pa = rounddown2(end_pa - L2_SIZE, L2_SIZE);
1400 	for (; pa >= start_pa && va < eva; va += L2_SIZE, pa -= L2_SIZE) {
1401 		l2 = pmap_l2(kernel_pmap, va);
1402 
1403 		/*
1404 		 * KASAN stack checking results in us having already allocated
1405 		 * part of our shadow map, so we can just skip those segments.
1406 		 */
1407 		if ((pmap_load(l2) & ATTR_DESCR_VALID) != 0) {
1408 			pa += L2_SIZE;
1409 			continue;
1410 		}
1411 
1412 		bzero((void *)PHYS_TO_DMAP(pa), L2_SIZE);
1413 		physmem_exclude_region(pa, L2_SIZE, EXFLAG_NOALLOC);
1414 		pmap_store(l2, PHYS_TO_PTE(pa) | PMAP_SAN_PTE_BITS | L2_BLOCK);
1415 	}
1416 	*vap = va;
1417 }
1418 
1419 /*
1420  * Finish constructing the initial shadow map:
1421  * - Count how many pages from KERNBASE to virtual_avail (scaled for
1422  *   shadow map)
1423  * - Map that entire range using L2 superpages.
1424  */
1425 static void
pmap_bootstrap_san1(vm_offset_t va,int scale)1426 pmap_bootstrap_san1(vm_offset_t va, int scale)
1427 {
1428 	vm_offset_t eva;
1429 	vm_paddr_t kernstart;
1430 	int i;
1431 
1432 	kernstart = pmap_early_vtophys(KERNBASE);
1433 
1434 	/*
1435 	 * Rebuild physmap one more time, we may have excluded more regions from
1436 	 * allocation since pmap_bootstrap().
1437 	 */
1438 	physmap_idx = physmem_avail(physmap, nitems(physmap));
1439 
1440 	eva = va + (virtual_avail - VM_MIN_KERNEL_ADDRESS) / scale;
1441 
1442 	/*
1443 	 * Find a slot in the physmap large enough for what we needed.  We try to put
1444 	 * the shadow map as high up as we can to avoid depleting the lower 4GB in case
1445 	 * it's needed for, e.g., an xhci controller that can only do 32-bit DMA.
1446 	 */
1447 	for (i = physmap_idx - 2; i >= 0; i -= 2) {
1448 		vm_paddr_t plow, phigh;
1449 
1450 		/* L2 mappings must be backed by memory that is L2-aligned */
1451 		plow = roundup2(physmap[i], L2_SIZE);
1452 		phigh = physmap[i + 1];
1453 		if (plow >= phigh)
1454 			continue;
1455 		if (kernstart >= plow && kernstart < phigh)
1456 			phigh = kernstart;
1457 		if (phigh - plow >= L2_SIZE) {
1458 			pmap_bootstrap_allocate_san_l2(plow, phigh, &va, eva);
1459 			if (va >= eva)
1460 				break;
1461 		}
1462 	}
1463 	if (i < 0)
1464 		panic("Could not find phys region for shadow map");
1465 
1466 	/*
1467 	 * Done. We should now have a valid shadow address mapped for all KVA
1468 	 * that has been mapped so far, i.e., KERNBASE to virtual_avail. Thus,
1469 	 * shadow accesses by the sanitizer runtime will succeed for this range.
1470 	 * When the kernel virtual address range is later expanded, as will
1471 	 * happen in vm_mem_init(), the shadow map will be grown as well. This
1472 	 * is handled by pmap_san_enter().
1473 	 */
1474 }
1475 
1476 void
pmap_bootstrap_san(void)1477 pmap_bootstrap_san(void)
1478 {
1479 #ifdef KASAN
1480 	pmap_bootstrap_san1(KASAN_MIN_ADDRESS, KASAN_SHADOW_SCALE);
1481 #else
1482 	static uint8_t kmsan_shad_ptp[PAGE_SIZE * 2] __aligned(PAGE_SIZE);
1483 	static uint8_t kmsan_orig_ptp[PAGE_SIZE * 2] __aligned(PAGE_SIZE);
1484 	pd_entry_t *l0, *l1;
1485 
1486 	if (virtual_avail - VM_MIN_KERNEL_ADDRESS > L1_SIZE)
1487 		panic("initial kernel map is too large");
1488 
1489 	l0 = pmap_l0(kernel_pmap, KMSAN_SHAD_MIN_ADDRESS);
1490 	pmap_store(l0, L0_TABLE | PHYS_TO_PTE(
1491 	    pmap_early_vtophys((vm_offset_t)kmsan_shad_ptp)));
1492 	l1 = pmap_l0_to_l1(l0, KMSAN_SHAD_MIN_ADDRESS);
1493 	pmap_store(l1, L1_TABLE | PHYS_TO_PTE(
1494 	    pmap_early_vtophys((vm_offset_t)kmsan_shad_ptp + PAGE_SIZE)));
1495 	pmap_bootstrap_san1(KMSAN_SHAD_MIN_ADDRESS, 1);
1496 
1497 	l0 = pmap_l0(kernel_pmap, KMSAN_ORIG_MIN_ADDRESS);
1498 	pmap_store(l0, L0_TABLE | PHYS_TO_PTE(
1499 	    pmap_early_vtophys((vm_offset_t)kmsan_orig_ptp)));
1500 	l1 = pmap_l0_to_l1(l0, KMSAN_ORIG_MIN_ADDRESS);
1501 	pmap_store(l1, L1_TABLE | PHYS_TO_PTE(
1502 	    pmap_early_vtophys((vm_offset_t)kmsan_orig_ptp + PAGE_SIZE)));
1503 	pmap_bootstrap_san1(KMSAN_ORIG_MIN_ADDRESS, 1);
1504 #endif
1505 }
1506 #endif
1507 
1508 /*
1509  *	Initialize a vm_page's machine-dependent fields.
1510  */
1511 void
pmap_page_init(vm_page_t m)1512 pmap_page_init(vm_page_t m)
1513 {
1514 
1515 	TAILQ_INIT(&m->md.pv_list);
1516 	m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1517 }
1518 
1519 static void
pmap_init_asids(struct asid_set * set,int bits)1520 pmap_init_asids(struct asid_set *set, int bits)
1521 {
1522 	int i;
1523 
1524 	set->asid_bits = bits;
1525 
1526 	/*
1527 	 * We may be too early in the overall initialization process to use
1528 	 * bit_alloc().
1529 	 */
1530 	set->asid_set_size = 1 << set->asid_bits;
1531 	set->asid_set = kmem_malloc(bitstr_size(set->asid_set_size),
1532 	    M_WAITOK | M_ZERO);
1533 	for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1534 		bit_set(set->asid_set, i);
1535 	set->asid_next = ASID_FIRST_AVAILABLE;
1536 	mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1537 }
1538 
1539 static void
pmap_init_pv_table(void)1540 pmap_init_pv_table(void)
1541 {
1542 	struct vm_phys_seg *seg, *next_seg;
1543 	struct pmap_large_md_page *pvd;
1544 	vm_size_t s;
1545 	int domain, i, j, pages;
1546 
1547 	/*
1548 	 * We strongly depend on the size being a power of two, so the assert
1549 	 * is overzealous. However, should the struct be resized to a
1550 	 * different power of two, the code below needs to be revisited.
1551 	 */
1552 	CTASSERT((sizeof(*pvd) == 64));
1553 
1554 	/*
1555 	 * Calculate the size of the array.
1556 	 */
1557 	s = 0;
1558 	for (i = 0; i < vm_phys_nsegs; i++) {
1559 		seg = &vm_phys_segs[i];
1560 		pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1561 		    pmap_l2_pindex(seg->start);
1562 		s += round_page(pages * sizeof(*pvd));
1563 	}
1564 	pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1565 	if (pv_table == NULL)
1566 		panic("%s: kva_alloc failed\n", __func__);
1567 
1568 	/*
1569 	 * Iterate physical segments to allocate domain-local memory for PV
1570 	 * list headers.
1571 	 */
1572 	pvd = pv_table;
1573 	for (i = 0; i < vm_phys_nsegs; i++) {
1574 		seg = &vm_phys_segs[i];
1575 		pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1576 		    pmap_l2_pindex(seg->start);
1577 		domain = seg->domain;
1578 
1579 		s = round_page(pages * sizeof(*pvd));
1580 
1581 		for (j = 0; j < s; j += PAGE_SIZE) {
1582 			vm_page_t m = vm_page_alloc_noobj_domain(domain,
1583 			    VM_ALLOC_ZERO);
1584 			if (m == NULL)
1585 				panic("failed to allocate PV table page");
1586 			pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1587 		}
1588 
1589 		for (j = 0; j < s / sizeof(*pvd); j++) {
1590 			rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1591 			TAILQ_INIT(&pvd->pv_page.pv_list);
1592 			pvd++;
1593 		}
1594 	}
1595 	pvd = &pv_dummy_large;
1596 	memset(pvd, 0, sizeof(*pvd));
1597 	rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1598 	TAILQ_INIT(&pvd->pv_page.pv_list);
1599 
1600 	/*
1601 	 * Set pointers from vm_phys_segs to pv_table.
1602 	 */
1603 	for (i = 0, pvd = pv_table; i < vm_phys_nsegs; i++) {
1604 		seg = &vm_phys_segs[i];
1605 		seg->md_first = pvd;
1606 		pvd += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1607 		    pmap_l2_pindex(seg->start);
1608 
1609 		/*
1610 		 * If there is a following segment, and the final
1611 		 * superpage of this segment and the initial superpage
1612 		 * of the next segment are the same then adjust the
1613 		 * pv_table entry for that next segment down by one so
1614 		 * that the pv_table entries will be shared.
1615 		 */
1616 		if (i + 1 < vm_phys_nsegs) {
1617 			next_seg = &vm_phys_segs[i + 1];
1618 			if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1619 			    pmap_l2_pindex(next_seg->start)) {
1620 				pvd--;
1621 			}
1622 		}
1623 	}
1624 }
1625 
1626 /*
1627  *	Initialize the pmap module.
1628  *
1629  *	Called by vm_mem_init(), to initialize any structures that the pmap
1630  *	system needs to map virtual memory.
1631  */
1632 void
pmap_init(void)1633 pmap_init(void)
1634 {
1635 	uint64_t mmfr1;
1636 	int i, vmid_bits;
1637 
1638 	/*
1639 	 * Are large page mappings enabled?
1640 	 */
1641 	TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1642 	if (superpages_enabled) {
1643 		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1644 		    ("pmap_init: can't assign to pagesizes[1]"));
1645 		pagesizes[1] = L3C_SIZE;
1646 		KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1647 		    ("pmap_init: can't assign to pagesizes[2]"));
1648 		pagesizes[2] = L2_SIZE;
1649 		if (L1_BLOCKS_SUPPORTED) {
1650 			KASSERT(MAXPAGESIZES > 3 && pagesizes[3] == 0,
1651 			    ("pmap_init: can't assign to pagesizes[3]"));
1652 			pagesizes[3] = L1_SIZE;
1653 		}
1654 	}
1655 
1656 	/*
1657 	 * Initialize the ASID allocator.
1658 	 */
1659 	pmap_init_asids(&asids,
1660 	    (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1661 
1662 	if (has_hyp()) {
1663 		mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1664 		vmid_bits = 8;
1665 
1666 		if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1667 		    ID_AA64MMFR1_VMIDBits_16)
1668 			vmid_bits = 16;
1669 		pmap_init_asids(&vmids, vmid_bits);
1670 	}
1671 
1672 	/*
1673 	 * Initialize pv chunk lists.
1674 	 */
1675 	for (i = 0; i < PMAP_MEMDOM; i++) {
1676 		mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL,
1677 		    MTX_DEF);
1678 		TAILQ_INIT(&pv_chunks[i].pvc_list);
1679 	}
1680 	pmap_init_pv_table();
1681 
1682 	vm_initialized = 1;
1683 }
1684 
1685 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l1, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1686     "L1 (1GB/64GB) page mapping counters");
1687 
1688 static COUNTER_U64_DEFINE_EARLY(pmap_l1_demotions);
1689 SYSCTL_COUNTER_U64(_vm_pmap_l1, OID_AUTO, demotions, CTLFLAG_RD,
1690     &pmap_l1_demotions, "L1 (1GB/64GB) page demotions");
1691 
1692 SYSCTL_BOOL(_vm_pmap_l1, OID_AUTO, supported, CTLFLAG_RD, &pmap_l1_supported,
1693     0, "L1 blocks are supported");
1694 
1695 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2c, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1696     "L2C (32MB/1GB) page mapping counters");
1697 
1698 static COUNTER_U64_DEFINE_EARLY(pmap_l2c_demotions);
1699 SYSCTL_COUNTER_U64(_vm_pmap_l2c, OID_AUTO, demotions, CTLFLAG_RD,
1700     &pmap_l2c_demotions, "L2C (32MB/1GB) page demotions");
1701 
1702 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1703     "2MB page mapping counters");
1704 
1705 static u_long pmap_l2_demotions;
1706 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1707     &pmap_l2_demotions, 0, "2MB page demotions");
1708 
1709 static u_long pmap_l2_mappings;
1710 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1711     &pmap_l2_mappings, 0, "2MB page mappings");
1712 
1713 static u_long pmap_l2_p_failures;
1714 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1715     &pmap_l2_p_failures, 0, "2MB page promotion failures");
1716 
1717 static u_long pmap_l2_promotions;
1718 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1719     &pmap_l2_promotions, 0, "2MB page promotions");
1720 
1721 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l3c, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1722     "L3C (64KB/2MB) page mapping counters");
1723 
1724 static COUNTER_U64_DEFINE_EARLY(pmap_l3c_demotions);
1725 SYSCTL_COUNTER_U64(_vm_pmap_l3c, OID_AUTO, demotions, CTLFLAG_RD,
1726     &pmap_l3c_demotions, "L3C (64KB/2MB) page demotions");
1727 
1728 static COUNTER_U64_DEFINE_EARLY(pmap_l3c_mappings);
1729 SYSCTL_COUNTER_U64(_vm_pmap_l3c, OID_AUTO, mappings, CTLFLAG_RD,
1730     &pmap_l3c_mappings, "L3C (64KB/2MB) page mappings");
1731 
1732 static COUNTER_U64_DEFINE_EARLY(pmap_l3c_p_failures);
1733 SYSCTL_COUNTER_U64(_vm_pmap_l3c, OID_AUTO, p_failures, CTLFLAG_RD,
1734     &pmap_l3c_p_failures, "L3C (64KB/2MB) page promotion failures");
1735 
1736 static COUNTER_U64_DEFINE_EARLY(pmap_l3c_promotions);
1737 SYSCTL_COUNTER_U64(_vm_pmap_l3c, OID_AUTO, promotions, CTLFLAG_RD,
1738     &pmap_l3c_promotions, "L3C (64KB/2MB) page promotions");
1739 
1740 /*
1741  * If the given value for "final_only" is false, then any cached intermediate-
1742  * level entries, i.e., L{0,1,2}_TABLE entries, are invalidated in addition to
1743  * any cached final-level entry, i.e., either an L{1,2}_BLOCK or L3_PAGE entry.
1744  * Otherwise, just the cached final-level entry is invalidated.
1745  */
1746 static __inline void
pmap_s1_invalidate_kernel(uint64_t r,bool final_only)1747 pmap_s1_invalidate_kernel(uint64_t r, bool final_only)
1748 {
1749 	if (final_only)
1750 		__asm __volatile("tlbi vaale1is, %0" : : "r" (r));
1751 	else
1752 		__asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1753 }
1754 
1755 static __inline void
pmap_s1_invalidate_user(uint64_t r,bool final_only)1756 pmap_s1_invalidate_user(uint64_t r, bool final_only)
1757 {
1758 	if (final_only)
1759 		__asm __volatile("tlbi vale1is, %0" : : "r" (r));
1760 	else
1761 		__asm __volatile("tlbi vae1is, %0" : : "r" (r));
1762 }
1763 
1764 /*
1765  * Invalidates any cached final- and optionally intermediate-level TLB entries
1766  * for the specified virtual address in the given virtual address space.
1767  */
1768 static __inline void
pmap_s1_invalidate_page(pmap_t pmap,vm_offset_t va,bool final_only)1769 pmap_s1_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1770 {
1771 	uint64_t r;
1772 
1773 	PMAP_ASSERT_STAGE1(pmap);
1774 
1775 	dsb(ishst);
1776 	r = TLBI_VA(va);
1777 	if (pmap == kernel_pmap) {
1778 		pmap_s1_invalidate_kernel(r, final_only);
1779 	} else {
1780 		r |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1781 		pmap_s1_invalidate_user(r, final_only);
1782 	}
1783 	dsb(ish);
1784 	isb();
1785 }
1786 
1787 static __inline void
pmap_s2_invalidate_page(pmap_t pmap,vm_offset_t va,bool final_only)1788 pmap_s2_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1789 {
1790 	PMAP_ASSERT_STAGE2(pmap);
1791 	MPASS(pmap_stage2_invalidate_range != NULL);
1792 	pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), va, va + PAGE_SIZE,
1793 	    final_only);
1794 }
1795 
1796 static __inline void
pmap_invalidate_page(pmap_t pmap,vm_offset_t va,bool final_only)1797 pmap_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1798 {
1799 	if (pmap->pm_stage == PM_STAGE1)
1800 		pmap_s1_invalidate_page(pmap, va, final_only);
1801 	else
1802 		pmap_s2_invalidate_page(pmap, va, final_only);
1803 }
1804 
1805 /*
1806  * Use stride L{1,2}_SIZE when invalidating the TLB entries for L{1,2}_BLOCK
1807  * mappings.  Otherwise, use stride L3_SIZE.
1808  */
1809 static __inline void
pmap_s1_invalidate_strided(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,vm_offset_t stride,bool final_only)1810 pmap_s1_invalidate_strided(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1811     vm_offset_t stride, bool final_only)
1812 {
1813 	uint64_t end, r, start;
1814 
1815 	PMAP_ASSERT_STAGE1(pmap);
1816 
1817 	dsb(ishst);
1818 	if (pmap == kernel_pmap) {
1819 		start = TLBI_VA(sva);
1820 		end = TLBI_VA(eva);
1821 		for (r = start; r < end; r += TLBI_VA(stride))
1822 			pmap_s1_invalidate_kernel(r, final_only);
1823 	} else {
1824 		start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1825 		start |= TLBI_VA(sva);
1826 		end |= TLBI_VA(eva);
1827 		for (r = start; r < end; r += TLBI_VA(stride))
1828 			pmap_s1_invalidate_user(r, final_only);
1829 	}
1830 	dsb(ish);
1831 	isb();
1832 }
1833 
1834 /*
1835  * Invalidates any cached final- and optionally intermediate-level TLB entries
1836  * for the specified virtual address range in the given virtual address space.
1837  */
1838 static __inline void
pmap_s1_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool final_only)1839 pmap_s1_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1840     bool final_only)
1841 {
1842 	pmap_s1_invalidate_strided(pmap, sva, eva, L3_SIZE, final_only);
1843 }
1844 
1845 static __inline void
pmap_s2_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool final_only)1846 pmap_s2_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1847     bool final_only)
1848 {
1849 	PMAP_ASSERT_STAGE2(pmap);
1850 	MPASS(pmap_stage2_invalidate_range != NULL);
1851 	pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), sva, eva, final_only);
1852 }
1853 
1854 static __inline void
pmap_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool final_only)1855 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1856     bool final_only)
1857 {
1858 	if (pmap->pm_stage == PM_STAGE1)
1859 		pmap_s1_invalidate_range(pmap, sva, eva, final_only);
1860 	else
1861 		pmap_s2_invalidate_range(pmap, sva, eva, final_only);
1862 }
1863 
1864 /*
1865  * Invalidates all cached intermediate- and final-level TLB entries for the
1866  * given virtual address space.
1867  */
1868 static __inline void
pmap_s1_invalidate_all(pmap_t pmap)1869 pmap_s1_invalidate_all(pmap_t pmap)
1870 {
1871 	uint64_t r;
1872 
1873 	PMAP_ASSERT_STAGE1(pmap);
1874 
1875 	dsb(ishst);
1876 	if (pmap == kernel_pmap) {
1877 		__asm __volatile("tlbi vmalle1is");
1878 	} else {
1879 		r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1880 		__asm __volatile("tlbi aside1is, %0" : : "r" (r));
1881 	}
1882 	dsb(ish);
1883 	isb();
1884 }
1885 
1886 static __inline void
pmap_s2_invalidate_all(pmap_t pmap)1887 pmap_s2_invalidate_all(pmap_t pmap)
1888 {
1889 	PMAP_ASSERT_STAGE2(pmap);
1890 	MPASS(pmap_stage2_invalidate_all != NULL);
1891 	pmap_stage2_invalidate_all(pmap_to_ttbr0(pmap));
1892 }
1893 
1894 static __inline void
pmap_invalidate_all(pmap_t pmap)1895 pmap_invalidate_all(pmap_t pmap)
1896 {
1897 	if (pmap->pm_stage == PM_STAGE1)
1898 		pmap_s1_invalidate_all(pmap);
1899 	else
1900 		pmap_s2_invalidate_all(pmap);
1901 }
1902 
1903 /*
1904  *	Routine:	pmap_extract
1905  *	Function:
1906  *		Extract the physical page address associated
1907  *		with the given map/virtual_address pair.
1908  */
1909 vm_paddr_t
pmap_extract(pmap_t pmap,vm_offset_t va)1910 pmap_extract(pmap_t pmap, vm_offset_t va)
1911 {
1912 	pt_entry_t *pte, tpte;
1913 	vm_paddr_t pa;
1914 	int lvl;
1915 
1916 	pa = 0;
1917 	PMAP_LOCK(pmap);
1918 	/*
1919 	 * Find the block or page map for this virtual address. pmap_pte
1920 	 * will return either a valid block/page entry, or NULL.
1921 	 */
1922 	pte = pmap_pte(pmap, va, &lvl);
1923 	if (pte != NULL) {
1924 		tpte = pmap_load(pte);
1925 		pa = PTE_TO_PHYS(tpte);
1926 		switch(lvl) {
1927 		case 1:
1928 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
1929 			KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1930 			    ("pmap_extract: Invalid L1 pte found: %lx",
1931 			    tpte & ATTR_DESCR_MASK));
1932 			pa |= (va & L1_OFFSET);
1933 			break;
1934 		case 2:
1935 			KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1936 			    ("pmap_extract: Invalid L2 pte found: %lx",
1937 			    tpte & ATTR_DESCR_MASK));
1938 			pa |= (va & L2_OFFSET);
1939 			break;
1940 		case 3:
1941 			KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1942 			    ("pmap_extract: Invalid L3 pte found: %lx",
1943 			    tpte & ATTR_DESCR_MASK));
1944 			pa |= (va & L3_OFFSET);
1945 			break;
1946 		}
1947 	}
1948 	PMAP_UNLOCK(pmap);
1949 	return (pa);
1950 }
1951 
1952 /*
1953  *	Routine:	pmap_extract_and_hold
1954  *	Function:
1955  *		Atomically extract and hold the physical page
1956  *		with the given pmap and virtual address pair
1957  *		if that mapping permits the given protection.
1958  */
1959 vm_page_t
pmap_extract_and_hold(pmap_t pmap,vm_offset_t va,vm_prot_t prot)1960 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1961 {
1962 	pt_entry_t *pte, tpte;
1963 	vm_offset_t off;
1964 	vm_page_t m;
1965 	int lvl;
1966 	bool use;
1967 
1968 	m = NULL;
1969 	PMAP_LOCK(pmap);
1970 	pte = pmap_pte(pmap, va, &lvl);
1971 	if (pte != NULL) {
1972 		tpte = pmap_load(pte);
1973 
1974 		KASSERT(lvl > 0 && lvl <= 3,
1975 		    ("pmap_extract_and_hold: Invalid level %d", lvl));
1976 		/*
1977 		 * Check that the pte is either a L3 page, or a L1 or L2 block
1978 		 * entry. We can assume L1_BLOCK == L2_BLOCK.
1979 		 */
1980 		KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1981 		    (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1982 		    ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1983 		     tpte & ATTR_DESCR_MASK));
1984 
1985 		use = false;
1986 		if ((prot & VM_PROT_WRITE) == 0)
1987 			use = true;
1988 		else if (pmap->pm_stage == PM_STAGE1 &&
1989 		    (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1990 			use = true;
1991 		else if (pmap->pm_stage == PM_STAGE2 &&
1992 		    ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1993 		     ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1994 			use = true;
1995 
1996 		if (use) {
1997 			switch (lvl) {
1998 			case 1:
1999 				off = va & L1_OFFSET;
2000 				break;
2001 			case 2:
2002 				off = va & L2_OFFSET;
2003 				break;
2004 			case 3:
2005 			default:
2006 				off = 0;
2007 			}
2008 			m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte) | off);
2009 			if (m != NULL && !vm_page_wire_mapped(m))
2010 				m = NULL;
2011 		}
2012 	}
2013 	PMAP_UNLOCK(pmap);
2014 	return (m);
2015 }
2016 
2017 /*
2018  * Walks the page tables to translate a kernel virtual address to a
2019  * physical address. Returns true if the kva is valid and stores the
2020  * physical address in pa if it is not NULL.
2021  *
2022  * See the comment above data_abort() for the rationale for specifying
2023  * NO_PERTHREAD_SSP here.
2024  */
2025 bool NO_PERTHREAD_SSP
pmap_klookup(vm_offset_t va,vm_paddr_t * pa)2026 pmap_klookup(vm_offset_t va, vm_paddr_t *pa)
2027 {
2028 	pt_entry_t *pte, tpte;
2029 	register_t intr;
2030 	uint64_t par;
2031 
2032 	/*
2033 	 * Disable interrupts so we don't get interrupted between asking
2034 	 * for address translation, and getting the result back.
2035 	 */
2036 	intr = intr_disable();
2037 	par = arm64_address_translate_s1e1r(va);
2038 	intr_restore(intr);
2039 
2040 	if (PAR_SUCCESS(par)) {
2041 		if (pa != NULL)
2042 			*pa = (par & PAR_PA_MASK) | (va & PAR_LOW_MASK);
2043 		return (true);
2044 	}
2045 
2046 	/*
2047 	 * Fall back to walking the page table. The address translation
2048 	 * instruction may fail when the page is in a break-before-make
2049 	 * sequence. As we only clear the valid bit in said sequence we
2050 	 * can walk the page table to find the physical address.
2051 	 */
2052 
2053 	pte = pmap_l1(kernel_pmap, va);
2054 	if (pte == NULL)
2055 		return (false);
2056 
2057 	/*
2058 	 * A concurrent pmap_update_entry() will clear the entry's valid bit
2059 	 * but leave the rest of the entry unchanged.  Therefore, we treat a
2060 	 * non-zero entry as being valid, and we ignore the valid bit when
2061 	 * determining whether the entry maps a block, page, or table.
2062 	 */
2063 	tpte = pmap_load(pte);
2064 	if (tpte == 0)
2065 		return (false);
2066 	if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
2067 		if (pa != NULL)
2068 			*pa = PTE_TO_PHYS(tpte) | (va & L1_OFFSET);
2069 		return (true);
2070 	}
2071 	pte = pmap_l1_to_l2(&tpte, va);
2072 	tpte = pmap_load(pte);
2073 	if (tpte == 0)
2074 		return (false);
2075 	if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
2076 		if (pa != NULL)
2077 			*pa = PTE_TO_PHYS(tpte) | (va & L2_OFFSET);
2078 		return (true);
2079 	}
2080 	pte = pmap_l2_to_l3(&tpte, va);
2081 	tpte = pmap_load(pte);
2082 	if (tpte == 0)
2083 		return (false);
2084 	if (pa != NULL)
2085 		*pa = PTE_TO_PHYS(tpte) | (va & L3_OFFSET);
2086 	return (true);
2087 }
2088 
2089 /*
2090  *	Routine:	pmap_kextract
2091  *	Function:
2092  *		Extract the physical page address associated with the given kernel
2093  *		virtual address.
2094  */
2095 vm_paddr_t
pmap_kextract(vm_offset_t va)2096 pmap_kextract(vm_offset_t va)
2097 {
2098 	vm_paddr_t pa;
2099 
2100 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
2101 		return (DMAP_TO_PHYS(va));
2102 
2103 	if (pmap_klookup(va, &pa) == false)
2104 		return (0);
2105 	return (pa);
2106 }
2107 
2108 /***************************************************
2109  * Low level mapping routines.....
2110  ***************************************************/
2111 
2112 void
pmap_kenter(vm_offset_t sva,vm_size_t size,vm_paddr_t pa,int mode)2113 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
2114 {
2115 	pd_entry_t *pde;
2116 	pt_entry_t attr, old_l3e, *pte;
2117 	vm_offset_t va;
2118 	vm_page_t mpte;
2119 	int error, lvl;
2120 
2121 	KASSERT((pa & L3_OFFSET) == 0,
2122 	    ("pmap_kenter: Invalid physical address"));
2123 	KASSERT((sva & L3_OFFSET) == 0,
2124 	    ("pmap_kenter: Invalid virtual address"));
2125 	KASSERT((size & PAGE_MASK) == 0,
2126 	    ("pmap_kenter: Mapping is not page-sized"));
2127 
2128 	attr = ATTR_AF | pmap_sh_attr | ATTR_S1_AP(ATTR_S1_AP_RW) |
2129 	    ATTR_S1_XN | ATTR_KERN_GP | ATTR_S1_IDX(mode);
2130 	old_l3e = 0;
2131 	va = sva;
2132 	while (size != 0) {
2133 		pde = pmap_pde(kernel_pmap, va, &lvl);
2134 		KASSERT(pde != NULL,
2135 		    ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
2136 		KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
2137 
2138 		/*
2139 		 * If we have an aligned, contiguous chunk of L2_SIZE, try
2140 		 * to create an L2_BLOCK mapping.
2141 		 */
2142 		if ((va & L2_OFFSET) == 0 && size >= L2_SIZE &&
2143 		    (pa & L2_OFFSET) == 0 && vm_initialized) {
2144 			mpte = PTE_TO_VM_PAGE(pmap_load(pde));
2145 			KASSERT(pmap_every_pte_zero(VM_PAGE_TO_PHYS(mpte)),
2146 			    ("pmap_kenter: Unexpected mapping"));
2147 			PMAP_LOCK(kernel_pmap);
2148 			error = pmap_insert_pt_page(kernel_pmap, mpte, false,
2149 			    false);
2150 			if (error == 0) {
2151 				attr &= ~ATTR_CONTIGUOUS;
2152 
2153 				/*
2154 				 * Although the page table page "mpte" should
2155 				 * be devoid of mappings, the TLB might hold
2156 				 * intermediate entries that reference it, so
2157 				 * we perform a single-page invalidation.
2158 				 */
2159 				pmap_update_entry(kernel_pmap, pde,
2160 				    PHYS_TO_PTE(pa) | attr | L2_BLOCK, va,
2161 				    PAGE_SIZE);
2162 			}
2163 			PMAP_UNLOCK(kernel_pmap);
2164 			if (error == 0) {
2165 				va += L2_SIZE;
2166 				pa += L2_SIZE;
2167 				size -= L2_SIZE;
2168 				continue;
2169 			}
2170 		}
2171 
2172 		/*
2173 		 * If we have an aligned, contiguous chunk of L3C_ENTRIES
2174 		 * L3 pages, set the contiguous bit within each PTE so that
2175 		 * the chunk can be cached using only one TLB entry.
2176 		 */
2177 		if ((va & L3C_OFFSET) == 0 && (pa & L3C_OFFSET) == 0) {
2178 			if (size >= L3C_SIZE)
2179 				attr |= ATTR_CONTIGUOUS;
2180 			else
2181 				attr &= ~ATTR_CONTIGUOUS;
2182 		}
2183 
2184 		pte = pmap_l2_to_l3(pde, va);
2185 		old_l3e |= pmap_load_store(pte, PHYS_TO_PTE(pa) | attr |
2186 		    L3_PAGE);
2187 
2188 		va += PAGE_SIZE;
2189 		pa += PAGE_SIZE;
2190 		size -= PAGE_SIZE;
2191 	}
2192 	if ((old_l3e & ATTR_DESCR_VALID) != 0)
2193 		pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2194 	else {
2195 		/*
2196 		 * Because the old entries were invalid and the new mappings
2197 		 * are not executable, an isb is not required.
2198 		 */
2199 		dsb(ishst);
2200 	}
2201 }
2202 
2203 void
pmap_kenter_device(vm_offset_t sva,vm_size_t size,vm_paddr_t pa)2204 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
2205 {
2206 
2207 	pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
2208 }
2209 
2210 /*
2211  * Remove a page from the kernel pagetables.
2212  */
2213 void
pmap_kremove(vm_offset_t va)2214 pmap_kremove(vm_offset_t va)
2215 {
2216 	pt_entry_t *pte;
2217 
2218 	pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2219 	KASSERT((pmap_load(pte) & ATTR_CONTIGUOUS) == 0,
2220 	    ("pmap_kremove: unexpected ATTR_CONTIGUOUS"));
2221 	pmap_clear(pte);
2222 	pmap_s1_invalidate_page(kernel_pmap, va, true);
2223 }
2224 
2225 /*
2226  * Remove the specified range of mappings from the kernel address space.
2227  *
2228  * Should only be applied to mappings that were created by pmap_kenter() or
2229  * pmap_kenter_device().  Nothing about this function is actually specific
2230  * to device mappings.
2231  */
2232 void
pmap_kremove_device(vm_offset_t sva,vm_size_t size)2233 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
2234 {
2235 	pt_entry_t *ptep, *ptep_end;
2236 	vm_offset_t va;
2237 	int lvl;
2238 
2239 	KASSERT((sva & L3_OFFSET) == 0,
2240 	    ("pmap_kremove_device: Invalid virtual address"));
2241 	KASSERT((size & PAGE_MASK) == 0,
2242 	    ("pmap_kremove_device: Mapping is not page-sized"));
2243 
2244 	va = sva;
2245 	while (size != 0) {
2246 		ptep = pmap_pte(kernel_pmap, va, &lvl);
2247 		KASSERT(ptep != NULL, ("Invalid page table, va: 0x%lx", va));
2248 		switch (lvl) {
2249 		case 2:
2250 			KASSERT((va & L2_OFFSET) == 0,
2251 			    ("Unaligned virtual address"));
2252 			KASSERT(size >= L2_SIZE, ("Insufficient size"));
2253 
2254 			if (va != sva) {
2255 				pmap_s1_invalidate_range(kernel_pmap, sva, va,
2256 				    true);
2257 			}
2258 			pmap_clear(ptep);
2259 			pmap_s1_invalidate_page(kernel_pmap, va, true);
2260 			PMAP_LOCK(kernel_pmap);
2261 			pmap_remove_kernel_l2(kernel_pmap, ptep, va);
2262 			PMAP_UNLOCK(kernel_pmap);
2263 
2264 			va += L2_SIZE;
2265 			sva = va;
2266 			size -= L2_SIZE;
2267 			break;
2268 		case 3:
2269 			if ((pmap_load(ptep) & ATTR_CONTIGUOUS) != 0) {
2270 				KASSERT((va & L3C_OFFSET) == 0,
2271 				    ("Unaligned L3C virtual address"));
2272 				KASSERT(size >= L3C_SIZE,
2273 				    ("Insufficient L3C size"));
2274 
2275 				ptep_end = ptep + L3C_ENTRIES;
2276 				for (; ptep < ptep_end; ptep++)
2277 					pmap_clear(ptep);
2278 
2279 				va += L3C_SIZE;
2280 				size -= L3C_SIZE;
2281 				break;
2282 			}
2283 			pmap_clear(ptep);
2284 
2285 			va += PAGE_SIZE;
2286 			size -= PAGE_SIZE;
2287 			break;
2288 		default:
2289 			__assert_unreachable();
2290 			break;
2291 		}
2292 	}
2293 	if (va != sva)
2294 		pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2295 }
2296 
2297 /*
2298  *	Used to map a range of physical addresses into kernel
2299  *	virtual address space.
2300  *
2301  *	The value passed in '*virt' is a suggested virtual address for
2302  *	the mapping. Architectures which can support a direct-mapped
2303  *	physical to virtual region can return the appropriate address
2304  *	within that region, leaving '*virt' unchanged. Other
2305  *	architectures should map the pages starting at '*virt' and
2306  *	update '*virt' with the first usable address after the mapped
2307  *	region.
2308  */
2309 vm_offset_t
pmap_map(vm_offset_t * virt,vm_paddr_t start,vm_paddr_t end,int prot)2310 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2311 {
2312 	return PHYS_TO_DMAP(start);
2313 }
2314 
2315 /*
2316  * Add a list of wired pages to the kva
2317  * this routine is only used for temporary
2318  * kernel mappings that do not need to have
2319  * page modification or references recorded.
2320  * Note that old mappings are simply written
2321  * over.  The page *must* be wired.
2322  * Note: SMP coherent.  Uses a ranged shootdown IPI.
2323  */
2324 void
pmap_qenter(vm_offset_t sva,vm_page_t * ma,int count)2325 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2326 {
2327 	pd_entry_t *pde;
2328 	pt_entry_t attr, old_l3e, *pte;
2329 	vm_offset_t va;
2330 	vm_page_t m;
2331 	int i, lvl;
2332 
2333 	old_l3e = 0;
2334 	va = sva;
2335 	for (i = 0; i < count; i++) {
2336 		pde = pmap_pde(kernel_pmap, va, &lvl);
2337 		KASSERT(pde != NULL,
2338 		    ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
2339 		KASSERT(lvl == 2,
2340 		    ("pmap_qenter: Invalid level %d", lvl));
2341 
2342 		m = ma[i];
2343 		attr = ATTR_AF | pmap_sh_attr |
2344 		    ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
2345 		    ATTR_KERN_GP | ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
2346 		pte = pmap_l2_to_l3(pde, va);
2347 		old_l3e |= pmap_load_store(pte, VM_PAGE_TO_PTE(m) | attr);
2348 
2349 		va += L3_SIZE;
2350 	}
2351 	if ((old_l3e & ATTR_DESCR_VALID) != 0)
2352 		pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2353 	else {
2354 		/*
2355 		 * Because the old entries were invalid and the new mappings
2356 		 * are not executable, an isb is not required.
2357 		 */
2358 		dsb(ishst);
2359 	}
2360 }
2361 
2362 /*
2363  * This routine tears out page mappings from the
2364  * kernel -- it is meant only for temporary mappings.
2365  */
2366 void
pmap_qremove(vm_offset_t sva,int count)2367 pmap_qremove(vm_offset_t sva, int count)
2368 {
2369 	pt_entry_t *pte;
2370 	vm_offset_t va;
2371 
2372 	KASSERT(ADDR_IS_CANONICAL(sva),
2373 	    ("%s: Address not in canonical form: %lx", __func__, sva));
2374 	KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
2375 
2376 	va = sva;
2377 	while (count-- > 0) {
2378 		pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
2379 		if (pte != NULL) {
2380 			pmap_clear(pte);
2381 		}
2382 
2383 		va += PAGE_SIZE;
2384 	}
2385 	pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2386 }
2387 
2388 /***************************************************
2389  * Page table page management routines.....
2390  ***************************************************/
2391 /*
2392  * Schedule the specified unused page table page to be freed.  Specifically,
2393  * add the page to the specified list of pages that will be released to the
2394  * physical memory manager after the TLB has been updated.
2395  */
2396 static __inline void
pmap_add_delayed_free_list(vm_page_t m,struct spglist * free,bool set_PG_ZERO)2397 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free, bool set_PG_ZERO)
2398 {
2399 
2400 	if (set_PG_ZERO)
2401 		m->flags |= PG_ZERO;
2402 	else
2403 		m->flags &= ~PG_ZERO;
2404 	SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2405 }
2406 
2407 /*
2408  * Decrements a page table page's reference count, which is used to record the
2409  * number of valid page table entries within the page.  If the reference count
2410  * drops to zero, then the page table page is unmapped.  Returns true if the
2411  * page table page was unmapped and false otherwise.
2412  */
2413 static inline bool
pmap_unwire_l3(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)2414 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2415 {
2416 
2417 	--m->ref_count;
2418 	if (m->ref_count == 0) {
2419 		_pmap_unwire_l3(pmap, va, m, free);
2420 		return (true);
2421 	} else
2422 		return (false);
2423 }
2424 
2425 static void
_pmap_unwire_l3(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)2426 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2427 {
2428 
2429 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2430 	/*
2431 	 * unmap the page table page
2432 	 */
2433 	if (m->pindex >= (NUL2E + NUL1E)) {
2434 		/* l1 page */
2435 		pd_entry_t *l0;
2436 
2437 		l0 = pmap_l0(pmap, va);
2438 		pmap_clear(l0);
2439 	} else if (m->pindex >= NUL2E) {
2440 		/* l2 page */
2441 		pd_entry_t *l1;
2442 
2443 		l1 = pmap_l1(pmap, va);
2444 		pmap_clear(l1);
2445 	} else {
2446 		/* l3 page */
2447 		pd_entry_t *l2;
2448 
2449 		l2 = pmap_l2(pmap, va);
2450 		pmap_clear(l2);
2451 	}
2452 	pmap_resident_count_dec(pmap, 1);
2453 	if (m->pindex < NUL2E) {
2454 		/* We just released an l3, unhold the matching l2 */
2455 		pd_entry_t *l1, tl1;
2456 		vm_page_t l2pg;
2457 
2458 		l1 = pmap_l1(pmap, va);
2459 		tl1 = pmap_load(l1);
2460 		l2pg = PTE_TO_VM_PAGE(tl1);
2461 		pmap_unwire_l3(pmap, va, l2pg, free);
2462 	} else if (m->pindex < (NUL2E + NUL1E)) {
2463 		/* We just released an l2, unhold the matching l1 */
2464 		pd_entry_t *l0, tl0;
2465 		vm_page_t l1pg;
2466 
2467 		l0 = pmap_l0(pmap, va);
2468 		tl0 = pmap_load(l0);
2469 		l1pg = PTE_TO_VM_PAGE(tl0);
2470 		pmap_unwire_l3(pmap, va, l1pg, free);
2471 	}
2472 	pmap_invalidate_page(pmap, va, false);
2473 
2474 	/*
2475 	 * Put page on a list so that it is released after
2476 	 * *ALL* TLB shootdown is done
2477 	 */
2478 	pmap_add_delayed_free_list(m, free, true);
2479 }
2480 
2481 /*
2482  * After removing a page table entry, this routine is used to
2483  * conditionally free the page, and manage the reference count.
2484  */
2485 static int
pmap_unuse_pt(pmap_t pmap,vm_offset_t va,pd_entry_t ptepde,struct spglist * free)2486 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2487     struct spglist *free)
2488 {
2489 	vm_page_t mpte;
2490 
2491 	KASSERT(ADDR_IS_CANONICAL(va),
2492 	    ("%s: Address not in canonical form: %lx", __func__, va));
2493 	if (ADDR_IS_KERNEL(va))
2494 		return (0);
2495 	KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2496 	mpte = PTE_TO_VM_PAGE(ptepde);
2497 	return (pmap_unwire_l3(pmap, va, mpte, free));
2498 }
2499 
2500 /*
2501  * Release a page table page reference after a failed attempt to create a
2502  * mapping.
2503  */
2504 static void
pmap_abort_ptp(pmap_t pmap,vm_offset_t va,vm_page_t mpte)2505 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2506 {
2507 	struct spglist free;
2508 
2509 	SLIST_INIT(&free);
2510 	if (pmap_unwire_l3(pmap, va, mpte, &free))
2511 		vm_page_free_pages_toq(&free, true);
2512 }
2513 
2514 void
pmap_pinit0(pmap_t pmap)2515 pmap_pinit0(pmap_t pmap)
2516 {
2517 
2518 	PMAP_LOCK_INIT(pmap);
2519 	bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2520 	pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2521 	pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2522 	TAILQ_INIT(&pmap->pm_pvchunk);
2523 	vm_radix_init(&pmap->pm_root);
2524 	pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2525 	pmap->pm_stage = PM_STAGE1;
2526 	pmap->pm_levels = 4;
2527 	pmap->pm_ttbr = pmap->pm_l0_paddr;
2528 	pmap->pm_asid_set = &asids;
2529 	pmap->pm_bti = NULL;
2530 
2531 	PCPU_SET(curpmap, pmap);
2532 }
2533 
2534 int
pmap_pinit_stage(pmap_t pmap,enum pmap_stage stage,int levels)2535 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2536 {
2537 	vm_page_t m;
2538 
2539 	/*
2540 	 * allocate the l0 page
2541 	 */
2542 	m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2543 	    VM_ALLOC_ZERO);
2544 	pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2545 	pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2546 
2547 	TAILQ_INIT(&pmap->pm_pvchunk);
2548 	vm_radix_init(&pmap->pm_root);
2549 	bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2550 	pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2551 
2552 	MPASS(levels == 3 || levels == 4);
2553 	pmap->pm_levels = levels;
2554 	pmap->pm_stage = stage;
2555 	pmap->pm_bti = NULL;
2556 	switch (stage) {
2557 	case PM_STAGE1:
2558 		pmap->pm_asid_set = &asids;
2559 		if (pmap_bti_support) {
2560 			pmap->pm_bti = malloc(sizeof(struct rangeset), M_DEVBUF,
2561 			    M_ZERO | M_WAITOK);
2562 			rangeset_init(pmap->pm_bti, bti_dup_range,
2563 			    bti_free_range, pmap, M_NOWAIT);
2564 		}
2565 		break;
2566 	case PM_STAGE2:
2567 		pmap->pm_asid_set = &vmids;
2568 		break;
2569 	default:
2570 		panic("%s: Invalid pmap type %d", __func__, stage);
2571 		break;
2572 	}
2573 
2574 	/* XXX Temporarily disable deferred ASID allocation. */
2575 	pmap_alloc_asid(pmap);
2576 
2577 	/*
2578 	 * Allocate the level 1 entry to use as the root. This will increase
2579 	 * the refcount on the level 1 page so it won't be removed until
2580 	 * pmap_release() is called.
2581 	 */
2582 	if (pmap->pm_levels == 3) {
2583 		PMAP_LOCK(pmap);
2584 		m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2585 		PMAP_UNLOCK(pmap);
2586 	}
2587 	pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2588 
2589 	return (1);
2590 }
2591 
2592 int
pmap_pinit(pmap_t pmap)2593 pmap_pinit(pmap_t pmap)
2594 {
2595 
2596 	return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2597 }
2598 
2599 /*
2600  * This routine is called if the desired page table page does not exist.
2601  *
2602  * If page table page allocation fails, this routine may sleep before
2603  * returning NULL.  It sleeps only if a lock pointer was given.
2604  *
2605  * Note: If a page allocation fails at page table level two or three,
2606  * one or two pages may be held during the wait, only to be released
2607  * afterwards.  This conservative approach is easily argued to avoid
2608  * race conditions.
2609  */
2610 static vm_page_t
_pmap_alloc_l3(pmap_t pmap,vm_pindex_t ptepindex,struct rwlock ** lockp)2611 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2612 {
2613 	vm_page_t m, l1pg, l2pg;
2614 
2615 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2616 
2617 	/*
2618 	 * Allocate a page table page.
2619 	 */
2620 	if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2621 		if (lockp != NULL) {
2622 			RELEASE_PV_LIST_LOCK(lockp);
2623 			PMAP_UNLOCK(pmap);
2624 			vm_wait(NULL);
2625 			PMAP_LOCK(pmap);
2626 		}
2627 
2628 		/*
2629 		 * Indicate the need to retry.  While waiting, the page table
2630 		 * page may have been allocated.
2631 		 */
2632 		return (NULL);
2633 	}
2634 	m->pindex = ptepindex;
2635 
2636 	/*
2637 	 * Because of AArch64's weak memory consistency model, we must have a
2638 	 * barrier here to ensure that the stores for zeroing "m", whether by
2639 	 * pmap_zero_page() or an earlier function, are visible before adding
2640 	 * "m" to the page table.  Otherwise, a page table walk by another
2641 	 * processor's MMU could see the mapping to "m" and a stale, non-zero
2642 	 * PTE within "m".
2643 	 */
2644 	dmb(ishst);
2645 
2646 	/*
2647 	 * Map the pagetable page into the process address space, if
2648 	 * it isn't already there.
2649 	 */
2650 
2651 	if (ptepindex >= (NUL2E + NUL1E)) {
2652 		pd_entry_t *l0p, l0e;
2653 		vm_pindex_t l0index;
2654 
2655 		l0index = ptepindex - (NUL2E + NUL1E);
2656 		l0p = &pmap->pm_l0[l0index];
2657 		KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2658 		    ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2659 		l0e = VM_PAGE_TO_PTE(m) | L0_TABLE;
2660 
2661 		/*
2662 		 * Mark all kernel memory as not accessible from userspace
2663 		 * and userspace memory as not executable from the kernel.
2664 		 * This has been done for the bootstrap L0 entries in
2665 		 * locore.S.
2666 		 */
2667 		if (pmap == kernel_pmap)
2668 			l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2669 		else
2670 			l0e |= TATTR_PXN_TABLE;
2671 		pmap_store(l0p, l0e);
2672 	} else if (ptepindex >= NUL2E) {
2673 		vm_pindex_t l0index, l1index;
2674 		pd_entry_t *l0, *l1;
2675 		pd_entry_t tl0;
2676 
2677 		l1index = ptepindex - NUL2E;
2678 		l0index = l1index >> Ln_ENTRIES_SHIFT;
2679 
2680 		l0 = &pmap->pm_l0[l0index];
2681 		tl0 = pmap_load(l0);
2682 		if (tl0 == 0) {
2683 			/* recurse for allocating page dir */
2684 			if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2685 			    lockp) == NULL) {
2686 				vm_page_unwire_noq(m);
2687 				vm_page_free_zero(m);
2688 				return (NULL);
2689 			}
2690 		} else {
2691 			l1pg = PTE_TO_VM_PAGE(tl0);
2692 			l1pg->ref_count++;
2693 		}
2694 
2695 		l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
2696 		l1 = &l1[ptepindex & Ln_ADDR_MASK];
2697 		KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2698 		    ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2699 		pmap_store(l1, VM_PAGE_TO_PTE(m) | L1_TABLE);
2700 	} else {
2701 		vm_pindex_t l0index, l1index;
2702 		pd_entry_t *l0, *l1, *l2;
2703 		pd_entry_t tl0, tl1;
2704 
2705 		l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2706 		l0index = l1index >> Ln_ENTRIES_SHIFT;
2707 
2708 		l0 = &pmap->pm_l0[l0index];
2709 		tl0 = pmap_load(l0);
2710 		if (tl0 == 0) {
2711 			/* recurse for allocating page dir */
2712 			if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2713 			    lockp) == NULL) {
2714 				vm_page_unwire_noq(m);
2715 				vm_page_free_zero(m);
2716 				return (NULL);
2717 			}
2718 			tl0 = pmap_load(l0);
2719 			l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2720 			l1 = &l1[l1index & Ln_ADDR_MASK];
2721 		} else {
2722 			l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2723 			l1 = &l1[l1index & Ln_ADDR_MASK];
2724 			tl1 = pmap_load(l1);
2725 			if (tl1 == 0) {
2726 				/* recurse for allocating page dir */
2727 				if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2728 				    lockp) == NULL) {
2729 					vm_page_unwire_noq(m);
2730 					vm_page_free_zero(m);
2731 					return (NULL);
2732 				}
2733 			} else {
2734 				l2pg = PTE_TO_VM_PAGE(tl1);
2735 				l2pg->ref_count++;
2736 			}
2737 		}
2738 
2739 		l2 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l1)));
2740 		l2 = &l2[ptepindex & Ln_ADDR_MASK];
2741 		KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2742 		    ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2743 		pmap_store(l2, VM_PAGE_TO_PTE(m) | L2_TABLE);
2744 	}
2745 
2746 	pmap_resident_count_inc(pmap, 1);
2747 
2748 	return (m);
2749 }
2750 
2751 static pd_entry_t *
pmap_alloc_l2(pmap_t pmap,vm_offset_t va,vm_page_t * l2pgp,struct rwlock ** lockp)2752 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2753     struct rwlock **lockp)
2754 {
2755 	pd_entry_t *l1, *l2;
2756 	vm_page_t l2pg;
2757 	vm_pindex_t l2pindex;
2758 
2759 	KASSERT(ADDR_IS_CANONICAL(va),
2760 	    ("%s: Address not in canonical form: %lx", __func__, va));
2761 
2762 retry:
2763 	l1 = pmap_l1(pmap, va);
2764 	if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2765 		l2 = pmap_l1_to_l2(l1, va);
2766 		if (!ADDR_IS_KERNEL(va)) {
2767 			/* Add a reference to the L2 page. */
2768 			l2pg = PTE_TO_VM_PAGE(pmap_load(l1));
2769 			l2pg->ref_count++;
2770 		} else
2771 			l2pg = NULL;
2772 	} else if (!ADDR_IS_KERNEL(va)) {
2773 		/* Allocate a L2 page. */
2774 		l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2775 		l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2776 		if (l2pg == NULL) {
2777 			if (lockp != NULL)
2778 				goto retry;
2779 			else
2780 				return (NULL);
2781 		}
2782 		l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2783 		l2 = &l2[pmap_l2_index(va)];
2784 	} else
2785 		panic("pmap_alloc_l2: missing page table page for va %#lx",
2786 		    va);
2787 	*l2pgp = l2pg;
2788 	return (l2);
2789 }
2790 
2791 static vm_page_t
pmap_alloc_l3(pmap_t pmap,vm_offset_t va,struct rwlock ** lockp)2792 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2793 {
2794 	vm_pindex_t ptepindex;
2795 	pd_entry_t *pde, tpde;
2796 #ifdef INVARIANTS
2797 	pt_entry_t *pte;
2798 #endif
2799 	vm_page_t m;
2800 	int lvl;
2801 
2802 	/*
2803 	 * Calculate pagetable page index
2804 	 */
2805 	ptepindex = pmap_l2_pindex(va);
2806 retry:
2807 	/*
2808 	 * Get the page directory entry
2809 	 */
2810 	pde = pmap_pde(pmap, va, &lvl);
2811 
2812 	/*
2813 	 * If the page table page is mapped, we just increment the hold count,
2814 	 * and activate it. If we get a level 2 pde it will point to a level 3
2815 	 * table.
2816 	 */
2817 	switch (lvl) {
2818 	case -1:
2819 		break;
2820 	case 0:
2821 #ifdef INVARIANTS
2822 		pte = pmap_l0_to_l1(pde, va);
2823 		KASSERT(pmap_load(pte) == 0,
2824 		    ("pmap_alloc_l3: TODO: l0 superpages"));
2825 #endif
2826 		break;
2827 	case 1:
2828 #ifdef INVARIANTS
2829 		pte = pmap_l1_to_l2(pde, va);
2830 		KASSERT(pmap_load(pte) == 0,
2831 		    ("pmap_alloc_l3: TODO: l1 superpages"));
2832 #endif
2833 		break;
2834 	case 2:
2835 		tpde = pmap_load(pde);
2836 		if (tpde != 0) {
2837 			m = PTE_TO_VM_PAGE(tpde);
2838 			m->ref_count++;
2839 			return (m);
2840 		}
2841 		break;
2842 	default:
2843 		panic("pmap_alloc_l3: Invalid level %d", lvl);
2844 	}
2845 
2846 	/*
2847 	 * Here if the pte page isn't mapped, or if it has been deallocated.
2848 	 */
2849 	m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2850 	if (m == NULL && lockp != NULL)
2851 		goto retry;
2852 
2853 	return (m);
2854 }
2855 
2856 /***************************************************
2857  * Pmap allocation/deallocation routines.
2858  ***************************************************/
2859 
2860 /*
2861  * Release any resources held by the given physical map.
2862  * Called when a pmap initialized by pmap_pinit is being released.
2863  * Should only be called if the map contains no valid mappings.
2864  */
2865 void
pmap_release(pmap_t pmap)2866 pmap_release(pmap_t pmap)
2867 {
2868 	bool rv __diagused;
2869 	struct spglist freelist;
2870 	struct asid_set *set;
2871 	vm_page_t m;
2872 	int asid;
2873 
2874 	if (pmap->pm_levels != 4) {
2875 		PMAP_ASSERT_STAGE2(pmap);
2876 		KASSERT(pmap->pm_stats.resident_count == 1,
2877 		    ("pmap_release: pmap resident count %ld != 0",
2878 		    pmap->pm_stats.resident_count));
2879 		KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2880 		    ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2881 
2882 		SLIST_INIT(&freelist);
2883 		m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2884 		PMAP_LOCK(pmap);
2885 		rv = pmap_unwire_l3(pmap, 0, m, &freelist);
2886 		PMAP_UNLOCK(pmap);
2887 		MPASS(rv == true);
2888 		vm_page_free_pages_toq(&freelist, true);
2889 	}
2890 
2891 	KASSERT(pmap->pm_stats.resident_count == 0,
2892 	    ("pmap_release: pmap resident count %ld != 0",
2893 	    pmap->pm_stats.resident_count));
2894 	KASSERT(vm_radix_is_empty(&pmap->pm_root),
2895 	    ("pmap_release: pmap has reserved page table page(s)"));
2896 
2897 	set = pmap->pm_asid_set;
2898 	KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2899 
2900 	/*
2901 	 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2902 	 * the entries when removing them so rely on a later tlb invalidation.
2903 	 * this will happen when updating the VMID generation. Because of this
2904 	 * we don't reuse VMIDs within a generation.
2905 	 */
2906 	if (pmap->pm_stage == PM_STAGE1) {
2907 		mtx_lock_spin(&set->asid_set_mutex);
2908 		if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2909 			asid = COOKIE_TO_ASID(pmap->pm_cookie);
2910 			KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2911 			    asid < set->asid_set_size,
2912 			    ("pmap_release: pmap cookie has out-of-range asid"));
2913 			bit_clear(set->asid_set, asid);
2914 		}
2915 		mtx_unlock_spin(&set->asid_set_mutex);
2916 
2917 		if (pmap->pm_bti != NULL) {
2918 			rangeset_fini(pmap->pm_bti);
2919 			free(pmap->pm_bti, M_DEVBUF);
2920 		}
2921 	}
2922 
2923 	m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2924 	vm_page_unwire_noq(m);
2925 	vm_page_free_zero(m);
2926 }
2927 
2928 static int
kvm_size(SYSCTL_HANDLER_ARGS)2929 kvm_size(SYSCTL_HANDLER_ARGS)
2930 {
2931 	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2932 
2933 	return sysctl_handle_long(oidp, &ksize, 0, req);
2934 }
2935 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2936     0, 0, kvm_size, "LU",
2937     "Size of KVM");
2938 
2939 static int
kvm_free(SYSCTL_HANDLER_ARGS)2940 kvm_free(SYSCTL_HANDLER_ARGS)
2941 {
2942 	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2943 
2944 	return sysctl_handle_long(oidp, &kfree, 0, req);
2945 }
2946 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2947     0, 0, kvm_free, "LU",
2948     "Amount of KVM free");
2949 
2950 /*
2951  * grow the number of kernel page table entries, if needed
2952  */
2953 void
pmap_growkernel(vm_offset_t addr)2954 pmap_growkernel(vm_offset_t addr)
2955 {
2956 	vm_page_t nkpg;
2957 	pd_entry_t *l0, *l1, *l2;
2958 
2959 	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2960 
2961 	addr = roundup2(addr, L2_SIZE);
2962 	if (addr - 1 >= vm_map_max(kernel_map))
2963 		addr = vm_map_max(kernel_map);
2964 	if (kernel_vm_end < addr) {
2965 		kasan_shadow_map(kernel_vm_end, addr - kernel_vm_end);
2966 		kmsan_shadow_map(kernel_vm_end, addr - kernel_vm_end);
2967 	}
2968 	while (kernel_vm_end < addr) {
2969 		l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2970 		KASSERT(pmap_load(l0) != 0,
2971 		    ("pmap_growkernel: No level 0 kernel entry"));
2972 
2973 		l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2974 		if (pmap_load(l1) == 0) {
2975 			/* We need a new PDP entry */
2976 			nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2977 			    VM_ALLOC_NOFREE | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2978 			if (nkpg == NULL)
2979 				panic("pmap_growkernel: no memory to grow kernel");
2980 			nkpg->pindex = pmap_l1_pindex(kernel_vm_end);
2981 			/* See the dmb() in _pmap_alloc_l3(). */
2982 			dmb(ishst);
2983 			pmap_store(l1, VM_PAGE_TO_PTE(nkpg) | L1_TABLE);
2984 			continue; /* try again */
2985 		}
2986 		l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2987 		if (pmap_load(l2) != 0) {
2988 			kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2989 			if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2990 				kernel_vm_end = vm_map_max(kernel_map);
2991 				break;
2992 			}
2993 			continue;
2994 		}
2995 
2996 		nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2997 		    VM_ALLOC_NOFREE | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2998 		if (nkpg == NULL)
2999 			panic("pmap_growkernel: no memory to grow kernel");
3000 		nkpg->pindex = pmap_l2_pindex(kernel_vm_end);
3001 		/* See the dmb() in _pmap_alloc_l3(). */
3002 		dmb(ishst);
3003 		pmap_store(l2, VM_PAGE_TO_PTE(nkpg) | L2_TABLE);
3004 
3005 		kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
3006 		if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3007 			kernel_vm_end = vm_map_max(kernel_map);
3008 			break;
3009 		}
3010 	}
3011 }
3012 
3013 /***************************************************
3014  * page management routines.
3015  ***************************************************/
3016 
3017 static const uint64_t pc_freemask[_NPCM] = {
3018 	[0 ... _NPCM - 2] = PC_FREEN,
3019 	[_NPCM - 1] = PC_FREEL
3020 };
3021 
3022 #ifdef PV_STATS
3023 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3024 
3025 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3026 	"Current number of pv entry chunks");
3027 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3028 	"Current number of pv entry chunks allocated");
3029 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3030 	"Current number of pv entry chunks frees");
3031 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3032 	"Number of times tried to get a chunk page but failed.");
3033 
3034 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3035 static int pv_entry_spare;
3036 
3037 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3038 	"Current number of pv entry frees");
3039 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3040 	"Current number of pv entry allocs");
3041 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3042 	"Current number of pv entries");
3043 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3044 	"Current number of spare pv entries");
3045 #endif
3046 
3047 /*
3048  * We are in a serious low memory condition.  Resort to
3049  * drastic measures to free some pages so we can allocate
3050  * another pv entry chunk.
3051  *
3052  * Returns NULL if PV entries were reclaimed from the specified pmap.
3053  *
3054  * We do not, however, unmap 2mpages because subsequent accesses will
3055  * allocate per-page pv entries until repromotion occurs, thereby
3056  * exacerbating the shortage of free pv entries.
3057  */
3058 static vm_page_t
reclaim_pv_chunk_domain(pmap_t locked_pmap,struct rwlock ** lockp,int domain)3059 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
3060 {
3061 	struct pv_chunks_list *pvc;
3062 	struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3063 	struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3064 	struct md_page *pvh;
3065 	pd_entry_t *pde;
3066 	pmap_t next_pmap, pmap;
3067 	pt_entry_t *pte, tpte;
3068 	pv_entry_t pv;
3069 	vm_offset_t va;
3070 	vm_page_t m, m_pc;
3071 	struct spglist free;
3072 	uint64_t inuse;
3073 	int bit, field, freed, lvl;
3074 
3075 	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3076 	KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3077 
3078 	pmap = NULL;
3079 	m_pc = NULL;
3080 	SLIST_INIT(&free);
3081 	bzero(&pc_marker_b, sizeof(pc_marker_b));
3082 	bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3083 	pc_marker = (struct pv_chunk *)&pc_marker_b;
3084 	pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3085 
3086 	pvc = &pv_chunks[domain];
3087 	mtx_lock(&pvc->pvc_lock);
3088 	pvc->active_reclaims++;
3089 	TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
3090 	TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
3091 	while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3092 	    SLIST_EMPTY(&free)) {
3093 		next_pmap = pc->pc_pmap;
3094 		if (next_pmap == NULL) {
3095 			/*
3096 			 * The next chunk is a marker.  However, it is
3097 			 * not our marker, so active_reclaims must be
3098 			 * > 1.  Consequently, the next_chunk code
3099 			 * will not rotate the pv_chunks list.
3100 			 */
3101 			goto next_chunk;
3102 		}
3103 		mtx_unlock(&pvc->pvc_lock);
3104 
3105 		/*
3106 		 * A pv_chunk can only be removed from the pc_lru list
3107 		 * when both pvc->pvc_lock is owned and the
3108 		 * corresponding pmap is locked.
3109 		 */
3110 		if (pmap != next_pmap) {
3111 			if (pmap != NULL && pmap != locked_pmap)
3112 				PMAP_UNLOCK(pmap);
3113 			pmap = next_pmap;
3114 			/* Avoid deadlock and lock recursion. */
3115 			if (pmap > locked_pmap) {
3116 				RELEASE_PV_LIST_LOCK(lockp);
3117 				PMAP_LOCK(pmap);
3118 				mtx_lock(&pvc->pvc_lock);
3119 				continue;
3120 			} else if (pmap != locked_pmap) {
3121 				if (PMAP_TRYLOCK(pmap)) {
3122 					mtx_lock(&pvc->pvc_lock);
3123 					continue;
3124 				} else {
3125 					pmap = NULL; /* pmap is not locked */
3126 					mtx_lock(&pvc->pvc_lock);
3127 					pc = TAILQ_NEXT(pc_marker, pc_lru);
3128 					if (pc == NULL ||
3129 					    pc->pc_pmap != next_pmap)
3130 						continue;
3131 					goto next_chunk;
3132 				}
3133 			}
3134 		}
3135 
3136 		/*
3137 		 * Destroy every non-wired, 4 KB page mapping in the chunk.
3138 		 */
3139 		freed = 0;
3140 		for (field = 0; field < _NPCM; field++) {
3141 			for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3142 			    inuse != 0; inuse &= ~(1UL << bit)) {
3143 				bit = ffsl(inuse) - 1;
3144 				pv = &pc->pc_pventry[field * 64 + bit];
3145 				va = pv->pv_va;
3146 				pde = pmap_pde(pmap, va, &lvl);
3147 				if (lvl != 2)
3148 					continue;
3149 				pte = pmap_l2_to_l3(pde, va);
3150 				tpte = pmap_load(pte);
3151 				if ((tpte & ATTR_SW_WIRED) != 0)
3152 					continue;
3153 				if ((tpte & ATTR_CONTIGUOUS) != 0)
3154 					(void)pmap_demote_l3c(pmap, pte, va);
3155 				tpte = pmap_load_clear(pte);
3156 				m = PTE_TO_VM_PAGE(tpte);
3157 				if (pmap_pte_dirty(pmap, tpte))
3158 					vm_page_dirty(m);
3159 				if ((tpte & ATTR_AF) != 0) {
3160 					pmap_s1_invalidate_page(pmap, va, true);
3161 					vm_page_aflag_set(m, PGA_REFERENCED);
3162 				}
3163 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3164 				TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3165 				m->md.pv_gen++;
3166 				if (TAILQ_EMPTY(&m->md.pv_list) &&
3167 				    (m->flags & PG_FICTITIOUS) == 0) {
3168 					pvh = page_to_pvh(m);
3169 					if (TAILQ_EMPTY(&pvh->pv_list)) {
3170 						vm_page_aflag_clear(m,
3171 						    PGA_WRITEABLE);
3172 					}
3173 				}
3174 				pc->pc_map[field] |= 1UL << bit;
3175 				pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
3176 				freed++;
3177 			}
3178 		}
3179 		if (freed == 0) {
3180 			mtx_lock(&pvc->pvc_lock);
3181 			goto next_chunk;
3182 		}
3183 		/* Every freed mapping is for a 4 KB page. */
3184 		pmap_resident_count_dec(pmap, freed);
3185 		PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3186 		PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3187 		PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3188 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3189 		if (pc_is_free(pc)) {
3190 			PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3191 			PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3192 			PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3193 			/* Entire chunk is free; return it. */
3194 			m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3195 			dump_drop_page(m_pc->phys_addr);
3196 			mtx_lock(&pvc->pvc_lock);
3197 			TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3198 			break;
3199 		}
3200 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3201 		mtx_lock(&pvc->pvc_lock);
3202 		/* One freed pv entry in locked_pmap is sufficient. */
3203 		if (pmap == locked_pmap)
3204 			break;
3205 
3206 next_chunk:
3207 		TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
3208 		TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
3209 		if (pvc->active_reclaims == 1 && pmap != NULL) {
3210 			/*
3211 			 * Rotate the pv chunks list so that we do not
3212 			 * scan the same pv chunks that could not be
3213 			 * freed (because they contained a wired
3214 			 * and/or superpage mapping) on every
3215 			 * invocation of reclaim_pv_chunk().
3216 			 */
3217 			while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
3218 				MPASS(pc->pc_pmap != NULL);
3219 				TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3220 				TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3221 			}
3222 		}
3223 	}
3224 	TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
3225 	TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
3226 	pvc->active_reclaims--;
3227 	mtx_unlock(&pvc->pvc_lock);
3228 	if (pmap != NULL && pmap != locked_pmap)
3229 		PMAP_UNLOCK(pmap);
3230 	if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3231 		m_pc = SLIST_FIRST(&free);
3232 		SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3233 		/* Recycle a freed page table page. */
3234 		m_pc->ref_count = 1;
3235 	}
3236 	vm_page_free_pages_toq(&free, true);
3237 	return (m_pc);
3238 }
3239 
3240 static vm_page_t
reclaim_pv_chunk(pmap_t locked_pmap,struct rwlock ** lockp)3241 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3242 {
3243 	vm_page_t m;
3244 	int i, domain;
3245 
3246 	domain = PCPU_GET(domain);
3247 	for (i = 0; i < vm_ndomains; i++) {
3248 		m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
3249 		if (m != NULL)
3250 			break;
3251 		domain = (domain + 1) % vm_ndomains;
3252 	}
3253 
3254 	return (m);
3255 }
3256 
3257 /*
3258  * free the pv_entry back to the free list
3259  */
3260 static void
free_pv_entry(pmap_t pmap,pv_entry_t pv)3261 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3262 {
3263 	struct pv_chunk *pc;
3264 	int idx, field, bit;
3265 
3266 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3267 	PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3268 	PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3269 	PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3270 	pc = pv_to_chunk(pv);
3271 	idx = pv - &pc->pc_pventry[0];
3272 	field = idx / 64;
3273 	bit = idx % 64;
3274 	pc->pc_map[field] |= 1ul << bit;
3275 	if (!pc_is_free(pc)) {
3276 		/* 98% of the time, pc is already at the head of the list. */
3277 		if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3278 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3279 			TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3280 		}
3281 		return;
3282 	}
3283 	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3284 	free_pv_chunk(pc);
3285 }
3286 
3287 static void
free_pv_chunk_dequeued(struct pv_chunk * pc)3288 free_pv_chunk_dequeued(struct pv_chunk *pc)
3289 {
3290 	vm_page_t m;
3291 
3292 	PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3293 	PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3294 	PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3295 	/* entire chunk is free, return it */
3296 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3297 	dump_drop_page(m->phys_addr);
3298 	vm_page_unwire_noq(m);
3299 	vm_page_free(m);
3300 }
3301 
3302 static void
free_pv_chunk(struct pv_chunk * pc)3303 free_pv_chunk(struct pv_chunk *pc)
3304 {
3305 	struct pv_chunks_list *pvc;
3306 
3307 	pvc = &pv_chunks[pc_to_domain(pc)];
3308 	mtx_lock(&pvc->pvc_lock);
3309 	TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3310 	mtx_unlock(&pvc->pvc_lock);
3311 	free_pv_chunk_dequeued(pc);
3312 }
3313 
3314 static void
free_pv_chunk_batch(struct pv_chunklist * batch)3315 free_pv_chunk_batch(struct pv_chunklist *batch)
3316 {
3317 	struct pv_chunks_list *pvc;
3318 	struct pv_chunk *pc, *npc;
3319 	int i;
3320 
3321 	for (i = 0; i < vm_ndomains; i++) {
3322 		if (TAILQ_EMPTY(&batch[i]))
3323 			continue;
3324 		pvc = &pv_chunks[i];
3325 		mtx_lock(&pvc->pvc_lock);
3326 		TAILQ_FOREACH(pc, &batch[i], pc_list) {
3327 			TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3328 		}
3329 		mtx_unlock(&pvc->pvc_lock);
3330 	}
3331 
3332 	for (i = 0; i < vm_ndomains; i++) {
3333 		TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
3334 			free_pv_chunk_dequeued(pc);
3335 		}
3336 	}
3337 }
3338 
3339 /*
3340  * Returns a new PV entry, allocating a new PV chunk from the system when
3341  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
3342  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
3343  * returned.
3344  *
3345  * The given PV list lock may be released.
3346  */
3347 static pv_entry_t
get_pv_entry(pmap_t pmap,struct rwlock ** lockp)3348 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3349 {
3350 	struct pv_chunks_list *pvc;
3351 	int bit, field;
3352 	pv_entry_t pv;
3353 	struct pv_chunk *pc;
3354 	vm_page_t m;
3355 
3356 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3357 	PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3358 retry:
3359 	pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3360 	if (pc != NULL) {
3361 		for (field = 0; field < _NPCM; field++) {
3362 			if (pc->pc_map[field]) {
3363 				bit = ffsl(pc->pc_map[field]) - 1;
3364 				break;
3365 			}
3366 		}
3367 		if (field < _NPCM) {
3368 			pv = &pc->pc_pventry[field * 64 + bit];
3369 			pc->pc_map[field] &= ~(1ul << bit);
3370 			/* If this was the last item, move it to tail */
3371 			if (pc_is_full(pc)) {
3372 				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3373 				TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3374 				    pc_list);
3375 			}
3376 			PV_STAT(atomic_add_long(&pv_entry_count, 1));
3377 			PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3378 			return (pv);
3379 		}
3380 	}
3381 	/* No free items, allocate another chunk */
3382 	m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3383 	if (m == NULL) {
3384 		if (lockp == NULL) {
3385 			PV_STAT(pc_chunk_tryfail++);
3386 			return (NULL);
3387 		}
3388 		m = reclaim_pv_chunk(pmap, lockp);
3389 		if (m == NULL)
3390 			goto retry;
3391 	}
3392 	PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3393 	PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3394 	dump_add_page(m->phys_addr);
3395 	pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3396 	pc->pc_pmap = pmap;
3397 	memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3398 	pc->pc_map[0] &= ~1ul;		/* preallocated bit 0 */
3399 	pvc = &pv_chunks[vm_page_domain(m)];
3400 	mtx_lock(&pvc->pvc_lock);
3401 	TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3402 	mtx_unlock(&pvc->pvc_lock);
3403 	pv = &pc->pc_pventry[0];
3404 	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3405 	PV_STAT(atomic_add_long(&pv_entry_count, 1));
3406 	PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3407 	return (pv);
3408 }
3409 
3410 /*
3411  * Ensure that the number of spare PV entries in the specified pmap meets or
3412  * exceeds the given count, "needed".
3413  *
3414  * The given PV list lock may be released.
3415  */
3416 static void
reserve_pv_entries(pmap_t pmap,int needed,struct rwlock ** lockp)3417 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3418 {
3419 	struct pv_chunks_list *pvc;
3420 	struct pch new_tail[PMAP_MEMDOM];
3421 	struct pv_chunk *pc;
3422 	vm_page_t m;
3423 	int avail, free, i;
3424 	bool reclaimed;
3425 
3426 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3427 	KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3428 
3429 	/*
3430 	 * Newly allocated PV chunks must be stored in a private list until
3431 	 * the required number of PV chunks have been allocated.  Otherwise,
3432 	 * reclaim_pv_chunk() could recycle one of these chunks.  In
3433 	 * contrast, these chunks must be added to the pmap upon allocation.
3434 	 */
3435 	for (i = 0; i < PMAP_MEMDOM; i++)
3436 		TAILQ_INIT(&new_tail[i]);
3437 retry:
3438 	avail = 0;
3439 	TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3440 		bit_count((bitstr_t *)pc->pc_map, 0,
3441 		    sizeof(pc->pc_map) * NBBY, &free);
3442 		if (free == 0)
3443 			break;
3444 		avail += free;
3445 		if (avail >= needed)
3446 			break;
3447 	}
3448 	for (reclaimed = false; avail < needed; avail += _NPCPV) {
3449 		m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3450 		if (m == NULL) {
3451 			m = reclaim_pv_chunk(pmap, lockp);
3452 			if (m == NULL)
3453 				goto retry;
3454 			reclaimed = true;
3455 		}
3456 		PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3457 		PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3458 		dump_add_page(m->phys_addr);
3459 		pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3460 		pc->pc_pmap = pmap;
3461 		memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3462 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3463 		TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3464 		PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3465 
3466 		/*
3467 		 * The reclaim might have freed a chunk from the current pmap.
3468 		 * If that chunk contained available entries, we need to
3469 		 * re-count the number of available entries.
3470 		 */
3471 		if (reclaimed)
3472 			goto retry;
3473 	}
3474 	for (i = 0; i < vm_ndomains; i++) {
3475 		if (TAILQ_EMPTY(&new_tail[i]))
3476 			continue;
3477 		pvc = &pv_chunks[i];
3478 		mtx_lock(&pvc->pvc_lock);
3479 		TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3480 		mtx_unlock(&pvc->pvc_lock);
3481 	}
3482 }
3483 
3484 /*
3485  * First find and then remove the pv entry for the specified pmap and virtual
3486  * address from the specified pv list.  Returns the pv entry if found and NULL
3487  * otherwise.  This operation can be performed on pv lists for either 4KB or
3488  * 2MB page mappings.
3489  */
3490 static __inline pv_entry_t
pmap_pvh_remove(struct md_page * pvh,pmap_t pmap,vm_offset_t va)3491 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3492 {
3493 	pv_entry_t pv;
3494 
3495 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3496 		if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3497 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3498 			pvh->pv_gen++;
3499 			break;
3500 		}
3501 	}
3502 	return (pv);
3503 }
3504 
3505 /*
3506  * After demotion from a 2MB page mapping to 512 4KB page mappings,
3507  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3508  * entries for each of the 4KB page mappings.
3509  */
3510 static void
pmap_pv_demote_l2(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)3511 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3512     struct rwlock **lockp)
3513 {
3514 	struct md_page *pvh;
3515 	struct pv_chunk *pc;
3516 	pv_entry_t pv;
3517 	vm_offset_t va_last;
3518 	vm_page_t m;
3519 	int bit, field;
3520 
3521 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3522 	KASSERT((va & L2_OFFSET) == 0,
3523 	    ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3524 	KASSERT((pa & L2_OFFSET) == 0,
3525 	    ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3526 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3527 
3528 	/*
3529 	 * Transfer the 2mpage's pv entry for this mapping to the first
3530 	 * page's pv list.  Once this transfer begins, the pv list lock
3531 	 * must not be released until the last pv entry is reinstantiated.
3532 	 */
3533 	pvh = pa_to_pvh(pa);
3534 	pv = pmap_pvh_remove(pvh, pmap, va);
3535 	KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3536 	m = PHYS_TO_VM_PAGE(pa);
3537 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3538 	m->md.pv_gen++;
3539 	/* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3540 	PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3541 	va_last = va + L2_SIZE - PAGE_SIZE;
3542 	for (;;) {
3543 		pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3544 		KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3545 		for (field = 0; field < _NPCM; field++) {
3546 			while (pc->pc_map[field]) {
3547 				bit = ffsl(pc->pc_map[field]) - 1;
3548 				pc->pc_map[field] &= ~(1ul << bit);
3549 				pv = &pc->pc_pventry[field * 64 + bit];
3550 				va += PAGE_SIZE;
3551 				pv->pv_va = va;
3552 				m++;
3553 				KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3554 			    ("pmap_pv_demote_l2: page %p is not managed", m));
3555 				TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3556 				m->md.pv_gen++;
3557 				if (va == va_last)
3558 					goto out;
3559 			}
3560 		}
3561 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3562 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3563 	}
3564 out:
3565 	if (pc_is_full(pc)) {
3566 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3567 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3568 	}
3569 	PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3570 	PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3571 }
3572 
3573 /*
3574  * First find and then destroy the pv entry for the specified pmap and virtual
3575  * address.  This operation can be performed on pv lists for either 4KB or 2MB
3576  * page mappings.
3577  */
3578 static void
pmap_pvh_free(struct md_page * pvh,pmap_t pmap,vm_offset_t va)3579 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3580 {
3581 	pv_entry_t pv;
3582 
3583 	pv = pmap_pvh_remove(pvh, pmap, va);
3584 	KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3585 	free_pv_entry(pmap, pv);
3586 }
3587 
3588 /*
3589  * Conditionally create the PV entry for a 4KB page mapping if the required
3590  * memory can be allocated without resorting to reclamation.
3591  */
3592 static bool
pmap_try_insert_pv_entry(pmap_t pmap,vm_offset_t va,vm_page_t m,struct rwlock ** lockp)3593 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3594     struct rwlock **lockp)
3595 {
3596 	pv_entry_t pv;
3597 
3598 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3599 	/* Pass NULL instead of the lock pointer to disable reclamation. */
3600 	if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3601 		pv->pv_va = va;
3602 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3603 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3604 		m->md.pv_gen++;
3605 		return (true);
3606 	} else
3607 		return (false);
3608 }
3609 
3610 /*
3611  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
3612  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
3613  * false if the PV entry cannot be allocated without resorting to reclamation.
3614  */
3615 static bool
pmap_pv_insert_l2(pmap_t pmap,vm_offset_t va,pd_entry_t l2e,u_int flags,struct rwlock ** lockp)3616 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3617     struct rwlock **lockp)
3618 {
3619 	struct md_page *pvh;
3620 	pv_entry_t pv;
3621 	vm_paddr_t pa;
3622 
3623 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3624 	/* Pass NULL instead of the lock pointer to disable reclamation. */
3625 	if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3626 	    NULL : lockp)) == NULL)
3627 		return (false);
3628 	pv->pv_va = va;
3629 	pa = PTE_TO_PHYS(l2e);
3630 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3631 	pvh = pa_to_pvh(pa);
3632 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3633 	pvh->pv_gen++;
3634 	return (true);
3635 }
3636 
3637 /*
3638  * Conditionally creates the PV entries for a L3C superpage mapping if
3639  * the required memory can be allocated without resorting to reclamation.
3640  */
3641 static bool
pmap_pv_insert_l3c(pmap_t pmap,vm_offset_t va,vm_page_t m,struct rwlock ** lockp)3642 pmap_pv_insert_l3c(pmap_t pmap, vm_offset_t va, vm_page_t m,
3643     struct rwlock **lockp)
3644 {
3645 	pv_entry_t pv;
3646 	vm_offset_t tva;
3647 	vm_paddr_t pa __diagused;
3648 	vm_page_t mt;
3649 
3650 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3651 	KASSERT((va & L3C_OFFSET) == 0,
3652 	    ("pmap_pv_insert_l3c: va is not aligned"));
3653 	pa = VM_PAGE_TO_PHYS(m);
3654 	KASSERT((pa & L3C_OFFSET) == 0,
3655 	    ("pmap_pv_insert_l3c: pa is not aligned"));
3656 	CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3657 	for (mt = m, tva = va; mt < &m[L3C_ENTRIES]; mt++, tva += L3_SIZE) {
3658 		/* Pass NULL instead of lockp to disable reclamation. */
3659 		pv = get_pv_entry(pmap, NULL);
3660 		if (__predict_false(pv == NULL)) {
3661 			while (tva > va) {
3662 				mt--;
3663 				tva -= L3_SIZE;
3664 				pmap_pvh_free(&mt->md, pmap, tva);
3665 			}
3666 			return (false);
3667 		}
3668 		pv->pv_va = tva;
3669 		TAILQ_INSERT_TAIL(&mt->md.pv_list, pv, pv_next);
3670 		mt->md.pv_gen++;
3671 	}
3672 	return (true);
3673 }
3674 
3675 static void
pmap_remove_kernel_l2(pmap_t pmap,pt_entry_t * l2,vm_offset_t va)3676 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3677 {
3678 	pt_entry_t newl2, oldl2 __diagused;
3679 	vm_page_t ml3;
3680 	vm_paddr_t ml3pa;
3681 
3682 	KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3683 	KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3684 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3685 
3686 	ml3 = pmap_remove_pt_page(pmap, va);
3687 	if (ml3 == NULL)
3688 		panic("pmap_remove_kernel_l2: Missing pt page");
3689 
3690 	ml3pa = VM_PAGE_TO_PHYS(ml3);
3691 	newl2 = PHYS_TO_PTE(ml3pa) | L2_TABLE;
3692 
3693 	/*
3694 	 * If this page table page was unmapped by a promotion, then it
3695 	 * contains valid mappings.  Zero it to invalidate those mappings.
3696 	 */
3697 	if (vm_page_any_valid(ml3))
3698 		pagezero((void *)PHYS_TO_DMAP(ml3pa));
3699 
3700 	/*
3701 	 * Demote the mapping.  The caller must have already invalidated the
3702 	 * mapping (i.e., the "break" in break-before-make).
3703 	 */
3704 	oldl2 = pmap_load_store(l2, newl2);
3705 	KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3706 	    __func__, l2, oldl2));
3707 }
3708 
3709 /*
3710  * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3711  */
3712 static int
pmap_remove_l2(pmap_t pmap,pt_entry_t * l2,vm_offset_t sva,pd_entry_t l1e,struct spglist * free,struct rwlock ** lockp)3713 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3714     pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3715 {
3716 	struct md_page *pvh;
3717 	pt_entry_t old_l2;
3718 	vm_page_t m, ml3, mt;
3719 
3720 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3721 	KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3722 	old_l2 = pmap_load_clear(l2);
3723 	KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3724 	    ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3725 
3726 	/*
3727 	 * Since a promotion must break the 4KB page mappings before making
3728 	 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3729 	 */
3730 	pmap_s1_invalidate_page(pmap, sva, true);
3731 
3732 	if (old_l2 & ATTR_SW_WIRED)
3733 		pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3734 	pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3735 	if (old_l2 & ATTR_SW_MANAGED) {
3736 		m = PTE_TO_VM_PAGE(old_l2);
3737 		pvh = page_to_pvh(m);
3738 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3739 		pmap_pvh_free(pvh, pmap, sva);
3740 		for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3741 			if (pmap_pte_dirty(pmap, old_l2))
3742 				vm_page_dirty(mt);
3743 			if (old_l2 & ATTR_AF)
3744 				vm_page_aflag_set(mt, PGA_REFERENCED);
3745 			if (TAILQ_EMPTY(&mt->md.pv_list) &&
3746 			    TAILQ_EMPTY(&pvh->pv_list))
3747 				vm_page_aflag_clear(mt, PGA_WRITEABLE);
3748 		}
3749 	}
3750 	if (pmap == kernel_pmap) {
3751 		pmap_remove_kernel_l2(pmap, l2, sva);
3752 	} else {
3753 		ml3 = pmap_remove_pt_page(pmap, sva);
3754 		if (ml3 != NULL) {
3755 			KASSERT(vm_page_any_valid(ml3),
3756 			    ("pmap_remove_l2: l3 page not promoted"));
3757 			pmap_resident_count_dec(pmap, 1);
3758 			KASSERT(ml3->ref_count == NL3PG,
3759 			    ("pmap_remove_l2: l3 page ref count error"));
3760 			ml3->ref_count = 0;
3761 			pmap_add_delayed_free_list(ml3, free, false);
3762 		}
3763 	}
3764 	return (pmap_unuse_pt(pmap, sva, l1e, free));
3765 }
3766 
3767 /*
3768  * pmap_remove_l3: do the things to unmap a page in a process
3769  */
3770 static int
pmap_remove_l3(pmap_t pmap,pt_entry_t * l3,vm_offset_t va,pd_entry_t l2e,struct spglist * free,struct rwlock ** lockp)3771 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3772     pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3773 {
3774 	struct md_page *pvh;
3775 	pt_entry_t old_l3;
3776 	vm_page_t m;
3777 
3778 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3779 	old_l3 = pmap_load(l3);
3780 	if ((old_l3 & ATTR_CONTIGUOUS) != 0)
3781 		(void)pmap_demote_l3c(pmap, l3, va);
3782 	old_l3 = pmap_load_clear(l3);
3783 	pmap_s1_invalidate_page(pmap, va, true);
3784 	if (old_l3 & ATTR_SW_WIRED)
3785 		pmap->pm_stats.wired_count -= 1;
3786 	pmap_resident_count_dec(pmap, 1);
3787 	if (old_l3 & ATTR_SW_MANAGED) {
3788 		m = PTE_TO_VM_PAGE(old_l3);
3789 		if (pmap_pte_dirty(pmap, old_l3))
3790 			vm_page_dirty(m);
3791 		if (old_l3 & ATTR_AF)
3792 			vm_page_aflag_set(m, PGA_REFERENCED);
3793 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3794 		pmap_pvh_free(&m->md, pmap, va);
3795 		if (TAILQ_EMPTY(&m->md.pv_list) &&
3796 		    (m->flags & PG_FICTITIOUS) == 0) {
3797 			pvh = page_to_pvh(m);
3798 			if (TAILQ_EMPTY(&pvh->pv_list))
3799 				vm_page_aflag_clear(m, PGA_WRITEABLE);
3800 		}
3801 	}
3802 	return (pmap_unuse_pt(pmap, va, l2e, free));
3803 }
3804 
3805 /*
3806  * Removes the specified L3C superpage mapping.  Requests TLB invalidations
3807  * to be performed by the caller through the returned "*vap". Returns true
3808  * if the level 3 table "ml3" was unmapped and added to the spglist "free".
3809  * Otherwise, returns false.
3810  */
3811 static bool
pmap_remove_l3c(pmap_t pmap,pt_entry_t * l3p,vm_offset_t va,vm_offset_t * vap,vm_offset_t va_next,vm_page_t ml3,struct spglist * free,struct rwlock ** lockp)3812 pmap_remove_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va, vm_offset_t *vap,
3813     vm_offset_t va_next, vm_page_t ml3, struct spglist *free,
3814     struct rwlock **lockp)
3815 {
3816 	struct md_page *pvh;
3817 	struct rwlock *new_lock;
3818 	pt_entry_t first_l3e, l3e, *tl3p;
3819 	vm_offset_t tva;
3820 	vm_page_t m, mt;
3821 
3822 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3823 	KASSERT(((uintptr_t)l3p & ((L3C_ENTRIES * sizeof(pt_entry_t)) - 1)) ==
3824 	    0, ("pmap_remove_l3c: l3p is not aligned"));
3825 	KASSERT((va & L3C_OFFSET) == 0,
3826 	    ("pmap_remove_l3c: va is not aligned"));
3827 
3828 	/*
3829 	 * Hardware accessed and dirty bit maintenance might only update a
3830 	 * single L3 entry, so we must combine the accessed and dirty bits
3831 	 * from this entire set of contiguous L3 entries.
3832 	 */
3833 	first_l3e = pmap_load_clear(l3p);
3834 	for (tl3p = l3p + 1; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
3835 		l3e = pmap_load_clear(tl3p);
3836 		KASSERT((l3e & ATTR_CONTIGUOUS) != 0,
3837 		    ("pmap_remove_l3c: l3e is missing ATTR_CONTIGUOUS"));
3838 		if ((l3e & (ATTR_SW_DBM | ATTR_S1_AP_RW_BIT)) ==
3839 		    (ATTR_SW_DBM | ATTR_S1_AP(ATTR_S1_AP_RW)))
3840 			first_l3e &= ~ATTR_S1_AP_RW_BIT;
3841 		first_l3e |= l3e & ATTR_AF;
3842 	}
3843 	if ((first_l3e & ATTR_SW_WIRED) != 0)
3844 		pmap->pm_stats.wired_count -= L3C_ENTRIES;
3845 	pmap_resident_count_dec(pmap, L3C_ENTRIES);
3846 	if ((first_l3e & ATTR_SW_MANAGED) != 0) {
3847 		m = PTE_TO_VM_PAGE(first_l3e);
3848 		new_lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3849 		if (new_lock != *lockp) {
3850 			if (*lockp != NULL) {
3851 				/*
3852 				 * Pending TLB invalidations must be
3853 				 * performed before the PV list lock is
3854 				 * released.  Otherwise, a concurrent
3855 				 * pmap_remove_all() on a physical page
3856 				 * could return while a stale TLB entry
3857 				 * still provides access to that page.
3858 				 */
3859 				if (*vap != va_next) {
3860 					pmap_invalidate_range(pmap, *vap, va,
3861 					    true);
3862 					*vap = va_next;
3863 				}
3864 				rw_wunlock(*lockp);
3865 			}
3866 			*lockp = new_lock;
3867 			rw_wlock(*lockp);
3868 		}
3869 		pvh = page_to_pvh(m);
3870 		for (mt = m, tva = va; mt < &m[L3C_ENTRIES]; mt++, tva +=
3871 		    L3_SIZE) {
3872 			if (pmap_pte_dirty(pmap, first_l3e))
3873 				vm_page_dirty(mt);
3874 			if ((first_l3e & ATTR_AF) != 0)
3875 				vm_page_aflag_set(mt, PGA_REFERENCED);
3876 			pmap_pvh_free(&mt->md, pmap, tva);
3877 			if (TAILQ_EMPTY(&mt->md.pv_list) &&
3878 			    TAILQ_EMPTY(&pvh->pv_list))
3879 				vm_page_aflag_clear(mt, PGA_WRITEABLE);
3880 		}
3881 	}
3882 	if (*vap == va_next)
3883 		*vap = va;
3884 	if (ml3 != NULL) {
3885 		ml3->ref_count -= L3C_ENTRIES;
3886 		if (ml3->ref_count == 0) {
3887 			_pmap_unwire_l3(pmap, va, ml3, free);
3888 			return (true);
3889 		}
3890 	}
3891 	return (false);
3892 }
3893 
3894 /*
3895  * Remove the specified range of addresses from the L3 page table that is
3896  * identified by the given L2 entry.
3897  */
3898 static void
pmap_remove_l3_range(pmap_t pmap,pd_entry_t l2e,vm_offset_t sva,vm_offset_t eva,struct spglist * free,struct rwlock ** lockp)3899 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3900     vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3901 {
3902 	struct md_page *pvh;
3903 	struct rwlock *new_lock;
3904 	pt_entry_t *l3, old_l3;
3905 	vm_offset_t va;
3906 	vm_page_t l3pg, m;
3907 
3908 	KASSERT(ADDR_IS_CANONICAL(sva),
3909 	    ("%s: Start address not in canonical form: %lx", __func__, sva));
3910 	KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3911 	    ("%s: End address not in canonical form: %lx", __func__, eva));
3912 
3913 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3914 	KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3915 	    ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3916 	l3pg = !ADDR_IS_KERNEL(sva) ? PTE_TO_VM_PAGE(l2e) : NULL;
3917 	va = eva;
3918 	for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3919 		old_l3 = pmap_load(l3);
3920 		if (!pmap_l3_valid(old_l3)) {
3921 			if (va != eva) {
3922 				pmap_invalidate_range(pmap, va, sva, true);
3923 				va = eva;
3924 			}
3925 			continue;
3926 		}
3927 		if ((old_l3 & ATTR_CONTIGUOUS) != 0) {
3928 			/*
3929 			 * Is this entire set of contiguous L3 entries being
3930 			 * removed?  Handle the possibility that "eva" is zero
3931 			 * because of address wraparound.
3932 			 */
3933 			if ((sva & L3C_OFFSET) == 0 &&
3934 			    sva + L3C_OFFSET <= eva - 1) {
3935 				if (pmap_remove_l3c(pmap, l3, sva, &va, eva,
3936 				    l3pg, free, lockp)) {
3937 					/* The L3 table was unmapped. */
3938 					sva += L3C_SIZE;
3939 					break;
3940 				}
3941 				l3 += L3C_ENTRIES - 1;
3942 				sva += L3C_SIZE - L3_SIZE;
3943 				continue;
3944 			}
3945 
3946 			(void)pmap_demote_l3c(pmap, l3, sva);
3947 		}
3948 		old_l3 = pmap_load_clear(l3);
3949 		if ((old_l3 & ATTR_SW_WIRED) != 0)
3950 			pmap->pm_stats.wired_count--;
3951 		pmap_resident_count_dec(pmap, 1);
3952 		if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3953 			m = PTE_TO_VM_PAGE(old_l3);
3954 			if (pmap_pte_dirty(pmap, old_l3))
3955 				vm_page_dirty(m);
3956 			if ((old_l3 & ATTR_AF) != 0)
3957 				vm_page_aflag_set(m, PGA_REFERENCED);
3958 			new_lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3959 			if (new_lock != *lockp) {
3960 				if (*lockp != NULL) {
3961 					/*
3962 					 * Pending TLB invalidations must be
3963 					 * performed before the PV list lock is
3964 					 * released.  Otherwise, a concurrent
3965 					 * pmap_remove_all() on a physical page
3966 					 * could return while a stale TLB entry
3967 					 * still provides access to that page.
3968 					 */
3969 					if (va != eva) {
3970 						pmap_invalidate_range(pmap, va,
3971 						    sva, true);
3972 						va = eva;
3973 					}
3974 					rw_wunlock(*lockp);
3975 				}
3976 				*lockp = new_lock;
3977 				rw_wlock(*lockp);
3978 			}
3979 			pmap_pvh_free(&m->md, pmap, sva);
3980 			if (TAILQ_EMPTY(&m->md.pv_list) &&
3981 			    (m->flags & PG_FICTITIOUS) == 0) {
3982 				pvh = page_to_pvh(m);
3983 				if (TAILQ_EMPTY(&pvh->pv_list))
3984 					vm_page_aflag_clear(m, PGA_WRITEABLE);
3985 			}
3986 		}
3987 		if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3988 			/*
3989 			 * _pmap_unwire_l3() has already invalidated the TLB
3990 			 * entries at all levels for "sva".  So, we need not
3991 			 * perform "sva += L3_SIZE;" here.  Moreover, we need
3992 			 * not perform "va = sva;" if "sva" is at the start
3993 			 * of a new valid range consisting of a single page.
3994 			 */
3995 			break;
3996 		}
3997 		if (va == eva)
3998 			va = sva;
3999 	}
4000 	if (va != eva)
4001 		pmap_invalidate_range(pmap, va, sva, true);
4002 }
4003 
4004 static void
pmap_remove1(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool map_delete)4005 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
4006 {
4007 	struct rwlock *lock;
4008 	vm_offset_t va_next;
4009 	pd_entry_t *l0, *l1, *l2;
4010 	pt_entry_t l3_paddr;
4011 	struct spglist free;
4012 
4013 	/*
4014 	 * Perform an unsynchronized read.  This is, however, safe.
4015 	 */
4016 	if (pmap->pm_stats.resident_count == 0)
4017 		return;
4018 
4019 	SLIST_INIT(&free);
4020 
4021 	PMAP_LOCK(pmap);
4022 	if (map_delete)
4023 		pmap_bti_on_remove(pmap, sva, eva);
4024 
4025 	lock = NULL;
4026 	for (; sva < eva; sva = va_next) {
4027 		if (pmap->pm_stats.resident_count == 0)
4028 			break;
4029 
4030 		l0 = pmap_l0(pmap, sva);
4031 		if (pmap_load(l0) == 0) {
4032 			va_next = (sva + L0_SIZE) & ~L0_OFFSET;
4033 			if (va_next < sva)
4034 				va_next = eva;
4035 			continue;
4036 		}
4037 
4038 		va_next = (sva + L1_SIZE) & ~L1_OFFSET;
4039 		if (va_next < sva)
4040 			va_next = eva;
4041 		l1 = pmap_l0_to_l1(l0, sva);
4042 		if (pmap_load(l1) == 0)
4043 			continue;
4044 		if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4045 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4046 			KASSERT(va_next <= eva,
4047 			    ("partial update of non-transparent 1G page "
4048 			    "l1 %#lx sva %#lx eva %#lx va_next %#lx",
4049 			    pmap_load(l1), sva, eva, va_next));
4050 			MPASS(pmap != kernel_pmap);
4051 			MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
4052 			pmap_clear(l1);
4053 			pmap_s1_invalidate_page(pmap, sva, true);
4054 			pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
4055 			pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
4056 			continue;
4057 		}
4058 
4059 		/*
4060 		 * Calculate index for next page table.
4061 		 */
4062 		va_next = (sva + L2_SIZE) & ~L2_OFFSET;
4063 		if (va_next < sva)
4064 			va_next = eva;
4065 
4066 		l2 = pmap_l1_to_l2(l1, sva);
4067 		if (l2 == NULL)
4068 			continue;
4069 
4070 		l3_paddr = pmap_load(l2);
4071 
4072 		if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
4073 			if (sva + L2_SIZE == va_next && eva >= va_next) {
4074 				pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
4075 				    &free, &lock);
4076 				continue;
4077 			} else if (pmap_demote_l2_locked(pmap, l2, sva,
4078 			    &lock) == NULL)
4079 				continue;
4080 			l3_paddr = pmap_load(l2);
4081 		}
4082 
4083 		/*
4084 		 * Weed out invalid mappings.
4085 		 */
4086 		if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
4087 			continue;
4088 
4089 		/*
4090 		 * Limit our scan to either the end of the va represented
4091 		 * by the current page table page, or to the end of the
4092 		 * range being removed.
4093 		 */
4094 		if (va_next > eva)
4095 			va_next = eva;
4096 
4097 		pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
4098 		    &lock);
4099 	}
4100 	if (lock != NULL)
4101 		rw_wunlock(lock);
4102 	PMAP_UNLOCK(pmap);
4103 	vm_page_free_pages_toq(&free, true);
4104 }
4105 
4106 /*
4107  *	Remove the given range of addresses from the specified map.
4108  *
4109  *	It is assumed that the start and end are properly
4110  *	rounded to the page size.
4111  */
4112 void
pmap_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)4113 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4114 {
4115 	pmap_remove1(pmap, sva, eva, false);
4116 }
4117 
4118 /*
4119  *	Remove the given range of addresses as part of a logical unmap
4120  *	operation. This has the effect of calling pmap_remove(), but
4121  *	also clears any metadata that should persist for the lifetime
4122  *	of a logical mapping.
4123  */
4124 void
pmap_map_delete(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)4125 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4126 {
4127 	pmap_remove1(pmap, sva, eva, true);
4128 }
4129 
4130 /*
4131  *	Routine:	pmap_remove_all
4132  *	Function:
4133  *		Removes this physical page from
4134  *		all physical maps in which it resides.
4135  *		Reflects back modify bits to the pager.
4136  *
4137  *	Notes:
4138  *		Original versions of this routine were very
4139  *		inefficient because they iteratively called
4140  *		pmap_remove (slow...)
4141  */
4142 
4143 void
pmap_remove_all(vm_page_t m)4144 pmap_remove_all(vm_page_t m)
4145 {
4146 	struct md_page *pvh;
4147 	pv_entry_t pv;
4148 	pmap_t pmap;
4149 	struct rwlock *lock;
4150 	pd_entry_t *pde, tpde;
4151 	pt_entry_t *pte, tpte;
4152 	vm_offset_t va;
4153 	struct spglist free;
4154 	int lvl, pvh_gen, md_gen;
4155 
4156 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4157 	    ("pmap_remove_all: page %p is not managed", m));
4158 	SLIST_INIT(&free);
4159 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4160 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
4161 	rw_wlock(lock);
4162 retry:
4163 	while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4164 		pmap = PV_PMAP(pv);
4165 		if (!PMAP_TRYLOCK(pmap)) {
4166 			pvh_gen = pvh->pv_gen;
4167 			rw_wunlock(lock);
4168 			PMAP_LOCK(pmap);
4169 			rw_wlock(lock);
4170 			if (pvh_gen != pvh->pv_gen) {
4171 				PMAP_UNLOCK(pmap);
4172 				goto retry;
4173 			}
4174 		}
4175 		va = pv->pv_va;
4176 		pte = pmap_pte_exists(pmap, va, 2, __func__);
4177 		pmap_demote_l2_locked(pmap, pte, va, &lock);
4178 		PMAP_UNLOCK(pmap);
4179 	}
4180 	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4181 		pmap = PV_PMAP(pv);
4182 		if (!PMAP_TRYLOCK(pmap)) {
4183 			pvh_gen = pvh->pv_gen;
4184 			md_gen = m->md.pv_gen;
4185 			rw_wunlock(lock);
4186 			PMAP_LOCK(pmap);
4187 			rw_wlock(lock);
4188 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4189 				PMAP_UNLOCK(pmap);
4190 				goto retry;
4191 			}
4192 		}
4193 		pmap_resident_count_dec(pmap, 1);
4194 
4195 		pde = pmap_pde(pmap, pv->pv_va, &lvl);
4196 		KASSERT(pde != NULL,
4197 		    ("pmap_remove_all: no page directory entry found"));
4198 		KASSERT(lvl == 2,
4199 		    ("pmap_remove_all: invalid pde level %d", lvl));
4200 		tpde = pmap_load(pde);
4201 
4202 		pte = pmap_l2_to_l3(pde, pv->pv_va);
4203 		tpte = pmap_load(pte);
4204 		if ((tpte & ATTR_CONTIGUOUS) != 0)
4205 			(void)pmap_demote_l3c(pmap, pte, pv->pv_va);
4206 		tpte = pmap_load_clear(pte);
4207 		if (tpte & ATTR_SW_WIRED)
4208 			pmap->pm_stats.wired_count--;
4209 		if ((tpte & ATTR_AF) != 0) {
4210 			pmap_invalidate_page(pmap, pv->pv_va, true);
4211 			vm_page_aflag_set(m, PGA_REFERENCED);
4212 		}
4213 
4214 		/*
4215 		 * Update the vm_page_t clean and reference bits.
4216 		 */
4217 		if (pmap_pte_dirty(pmap, tpte))
4218 			vm_page_dirty(m);
4219 		pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
4220 		TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4221 		m->md.pv_gen++;
4222 		free_pv_entry(pmap, pv);
4223 		PMAP_UNLOCK(pmap);
4224 	}
4225 	vm_page_aflag_clear(m, PGA_WRITEABLE);
4226 	rw_wunlock(lock);
4227 	vm_page_free_pages_toq(&free, true);
4228 }
4229 
4230 /*
4231  * Masks and sets bits in a level 2 page table entries in the specified pmap
4232  */
4233 static void
pmap_protect_l2(pmap_t pmap,pt_entry_t * l2,vm_offset_t sva,pt_entry_t mask,pt_entry_t nbits)4234 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
4235     pt_entry_t nbits)
4236 {
4237 	pd_entry_t old_l2;
4238 	vm_page_t m, mt;
4239 
4240 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4241 	PMAP_ASSERT_STAGE1(pmap);
4242 	KASSERT((sva & L2_OFFSET) == 0,
4243 	    ("pmap_protect_l2: sva is not 2mpage aligned"));
4244 	old_l2 = pmap_load(l2);
4245 	KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
4246 	    ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
4247 
4248 	/*
4249 	 * Return if the L2 entry already has the desired access restrictions
4250 	 * in place.
4251 	 */
4252 	if ((old_l2 & mask) == nbits)
4253 		return;
4254 
4255 	while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
4256 		cpu_spinwait();
4257 
4258 	/*
4259 	 * When a dirty read/write superpage mapping is write protected,
4260 	 * update the dirty field of each of the superpage's constituent 4KB
4261 	 * pages.
4262 	 */
4263 	if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
4264 	    (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
4265 	    pmap_pte_dirty(pmap, old_l2)) {
4266 		m = PTE_TO_VM_PAGE(old_l2);
4267 		for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4268 			vm_page_dirty(mt);
4269 	}
4270 
4271 	/*
4272 	 * Since a promotion must break the 4KB page mappings before making
4273 	 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
4274 	 */
4275 	pmap_s1_invalidate_page(pmap, sva, true);
4276 }
4277 
4278 /*
4279  * Masks and sets bits in the specified L3C superpage mapping.
4280  *
4281  * Requests TLB invalidations to be performed by the caller through the
4282  * returned "*vap".
4283  */
4284 static void
pmap_mask_set_l3c(pmap_t pmap,pt_entry_t * l3p,vm_offset_t va,vm_offset_t * vap,vm_offset_t va_next,pt_entry_t mask,pt_entry_t nbits)4285 pmap_mask_set_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va,
4286     vm_offset_t *vap, vm_offset_t va_next, pt_entry_t mask, pt_entry_t nbits)
4287 {
4288 	pt_entry_t l3e, *tl3p;
4289 	vm_page_t m, mt;
4290 	bool dirty;
4291 
4292 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4293 	KASSERT(((uintptr_t)l3p & ((L3C_ENTRIES * sizeof(pt_entry_t)) - 1)) ==
4294 	    0, ("pmap_mask_set_l3c: l3p is not aligned"));
4295 	KASSERT((va & L3C_OFFSET) == 0,
4296 	    ("pmap_mask_set_l3c: va is not aligned"));
4297 	dirty = false;
4298 	for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
4299 		l3e = pmap_load(tl3p);
4300 		KASSERT((l3e & ATTR_CONTIGUOUS) != 0,
4301 		    ("pmap_mask_set_l3c: l3e is missing ATTR_CONTIGUOUS"));
4302 		while (!atomic_fcmpset_64(tl3p, &l3e, (l3e & ~mask) | nbits))
4303 			cpu_spinwait();
4304 		if ((l3e & (ATTR_SW_DBM | ATTR_S1_AP_RW_BIT)) ==
4305 		    (ATTR_SW_DBM | ATTR_S1_AP(ATTR_S1_AP_RW)))
4306 			dirty = true;
4307 	}
4308 
4309 	/*
4310 	 * When a dirty read/write superpage mapping is write protected,
4311 	 * update the dirty field of each of the superpage's constituent 4KB
4312 	 * pages.
4313 	 */
4314 	if ((l3e & ATTR_SW_MANAGED) != 0 &&
4315 	    (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
4316 	    dirty) {
4317 		m = PTE_TO_VM_PAGE(pmap_load(l3p));
4318 		for (mt = m; mt < &m[L3C_ENTRIES]; mt++)
4319 			vm_page_dirty(mt);
4320 	}
4321 
4322 	if (*vap == va_next)
4323 		*vap = va;
4324 }
4325 
4326 /*
4327  * Masks and sets bits in last level page table entries in the specified
4328  * pmap and range
4329  */
4330 static void
pmap_mask_set_locked(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pt_entry_t mask,pt_entry_t nbits,bool invalidate)4331 pmap_mask_set_locked(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
4332     pt_entry_t nbits, bool invalidate)
4333 {
4334 	vm_offset_t va, va_next;
4335 	pd_entry_t *l0, *l1, *l2;
4336 	pt_entry_t *l3p, l3;
4337 
4338 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4339 	for (; sva < eva; sva = va_next) {
4340 		l0 = pmap_l0(pmap, sva);
4341 		if (pmap_load(l0) == 0) {
4342 			va_next = (sva + L0_SIZE) & ~L0_OFFSET;
4343 			if (va_next < sva)
4344 				va_next = eva;
4345 			continue;
4346 		}
4347 
4348 		va_next = (sva + L1_SIZE) & ~L1_OFFSET;
4349 		if (va_next < sva)
4350 			va_next = eva;
4351 		l1 = pmap_l0_to_l1(l0, sva);
4352 		if (pmap_load(l1) == 0)
4353 			continue;
4354 		if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4355 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4356 			KASSERT(va_next <= eva,
4357 			    ("partial update of non-transparent 1G page "
4358 			    "l1 %#lx sva %#lx eva %#lx va_next %#lx",
4359 			    pmap_load(l1), sva, eva, va_next));
4360 			MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
4361 			if ((pmap_load(l1) & mask) != nbits) {
4362 				pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
4363 				if (invalidate)
4364 					pmap_s1_invalidate_page(pmap, sva, true);
4365 			}
4366 			continue;
4367 		}
4368 
4369 		va_next = (sva + L2_SIZE) & ~L2_OFFSET;
4370 		if (va_next < sva)
4371 			va_next = eva;
4372 
4373 		l2 = pmap_l1_to_l2(l1, sva);
4374 		if (pmap_load(l2) == 0)
4375 			continue;
4376 
4377 		if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
4378 			if (sva + L2_SIZE == va_next && eva >= va_next) {
4379 				pmap_protect_l2(pmap, l2, sva, mask, nbits);
4380 				continue;
4381 			} else if ((pmap_load(l2) & mask) == nbits ||
4382 			    pmap_demote_l2(pmap, l2, sva) == NULL)
4383 				continue;
4384 		}
4385 		KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
4386 		    ("pmap_protect: Invalid L2 entry after demotion"));
4387 
4388 		if (va_next > eva)
4389 			va_next = eva;
4390 
4391 		va = va_next;
4392 		for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
4393 		    sva += L3_SIZE) {
4394 			l3 = pmap_load(l3p);
4395 
4396 			/*
4397 			 * Go to the next L3 entry if the current one is
4398 			 * invalid or already has the desired access
4399 			 * restrictions in place.  (The latter case occurs
4400 			 * frequently.  For example, in a "buildworld"
4401 			 * workload, almost 1 out of 4 L3 entries already
4402 			 * have the desired restrictions.)
4403 			 */
4404 			if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
4405 				if (va != va_next) {
4406 					if (invalidate)
4407 						pmap_s1_invalidate_range(pmap,
4408 						    va, sva, true);
4409 					va = va_next;
4410 				}
4411 				if ((l3 & ATTR_CONTIGUOUS) != 0) {
4412 					/*
4413 					 * Does this L3C page extend beyond
4414 					 * the requested range?  Handle the
4415 					 * possibility that "va_next" is zero.
4416 					 */
4417 					if ((sva | L3C_OFFSET) > va_next - 1)
4418 						break;
4419 
4420 					/*
4421 					 * Skip ahead to the last L3_PAGE
4422 					 * within this L3C page.
4423 					 */
4424 					l3p = (pt_entry_t *)((uintptr_t)l3p |
4425 					    ((L3C_ENTRIES - 1) *
4426 					    sizeof(pt_entry_t)));
4427 					sva |= L3C_SIZE - L3_SIZE;
4428 				}
4429 				continue;
4430 			}
4431 
4432 			if ((l3 & ATTR_CONTIGUOUS) != 0) {
4433 				/*
4434 				 * Is this entire set of contiguous L3 entries
4435 				 * being protected?  Handle the possibility
4436 				 * that "va_next" is zero because of address
4437 				 * wraparound.
4438 				 */
4439 				if ((sva & L3C_OFFSET) == 0 &&
4440 				    sva + L3C_OFFSET <= va_next - 1) {
4441 					pmap_mask_set_l3c(pmap, l3p, sva, &va,
4442 					    va_next, mask, nbits);
4443 					l3p += L3C_ENTRIES - 1;
4444 					sva += L3C_SIZE - L3_SIZE;
4445 					continue;
4446 				}
4447 
4448 				(void)pmap_demote_l3c(pmap, l3p, sva);
4449 
4450 				/*
4451 				 * The L3 entry's accessed bit may have changed.
4452 				 */
4453 				l3 = pmap_load(l3p);
4454 			}
4455 			while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
4456 			    nbits))
4457 				cpu_spinwait();
4458 
4459 			/*
4460 			 * When a dirty read/write mapping is write protected,
4461 			 * update the page's dirty field.
4462 			 */
4463 			if ((l3 & ATTR_SW_MANAGED) != 0 &&
4464 			    (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
4465 			    pmap_pte_dirty(pmap, l3))
4466 				vm_page_dirty(PTE_TO_VM_PAGE(l3));
4467 
4468 			if (va == va_next)
4469 				va = sva;
4470 		}
4471 		if (va != va_next && invalidate)
4472 			pmap_s1_invalidate_range(pmap, va, sva, true);
4473 	}
4474 }
4475 
4476 static void
pmap_mask_set(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pt_entry_t mask,pt_entry_t nbits,bool invalidate)4477 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
4478     pt_entry_t nbits, bool invalidate)
4479 {
4480 	PMAP_LOCK(pmap);
4481 	pmap_mask_set_locked(pmap, sva, eva, mask, nbits, invalidate);
4482 	PMAP_UNLOCK(pmap);
4483 }
4484 
4485 /*
4486  *	Set the physical protection on the
4487  *	specified range of this map as requested.
4488  */
4489 void
pmap_protect(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,vm_prot_t prot)4490 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4491 {
4492 	pt_entry_t mask, nbits;
4493 
4494 	PMAP_ASSERT_STAGE1(pmap);
4495 	KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4496 	if (prot == VM_PROT_NONE) {
4497 		pmap_remove(pmap, sva, eva);
4498 		return;
4499 	}
4500 
4501 	mask = nbits = 0;
4502 	if ((prot & VM_PROT_WRITE) == 0) {
4503 		mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
4504 		nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
4505 	}
4506 	if ((prot & VM_PROT_EXECUTE) == 0) {
4507 		mask |= ATTR_S1_XN;
4508 		nbits |= ATTR_S1_XN;
4509 	}
4510 	if (pmap == kernel_pmap) {
4511 		mask |= ATTR_KERN_GP;
4512 		nbits |= ATTR_KERN_GP;
4513 	}
4514 	if (mask == 0)
4515 		return;
4516 
4517 	pmap_mask_set(pmap, sva, eva, mask, nbits, true);
4518 }
4519 
4520 void
pmap_disable_promotion(vm_offset_t sva,vm_size_t size)4521 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
4522 {
4523 
4524 	MPASS((sva & L3_OFFSET) == 0);
4525 	MPASS(((sva + size) & L3_OFFSET) == 0);
4526 
4527 	pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
4528 	    ATTR_SW_NO_PROMOTE, false);
4529 }
4530 
4531 /*
4532  * Inserts the specified page table page into the specified pmap's collection
4533  * of idle page table pages.  Each of a pmap's page table pages is responsible
4534  * for mapping a distinct range of virtual addresses.  The pmap's collection is
4535  * ordered by this virtual address range.
4536  *
4537  * If "promoted" is false, then the page table page "mpte" must be zero filled;
4538  * "mpte"'s valid field will be set to 0.
4539  *
4540  * If "promoted" is true and "all_l3e_AF_set" is false, then "mpte" must
4541  * contain valid mappings with identical attributes except for ATTR_AF;
4542  * "mpte"'s valid field will be set to 1.
4543  *
4544  * If "promoted" and "all_l3e_AF_set" are both true, then "mpte" must contain
4545  * valid mappings with identical attributes including ATTR_AF; "mpte"'s valid
4546  * field will be set to VM_PAGE_BITS_ALL.
4547  */
4548 static __inline int
pmap_insert_pt_page(pmap_t pmap,vm_page_t mpte,bool promoted,bool all_l3e_AF_set)4549 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4550     bool all_l3e_AF_set)
4551 {
4552 
4553 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4554 	KASSERT(promoted || !all_l3e_AF_set,
4555 	    ("a zero-filled PTP can't have ATTR_AF set in every PTE"));
4556 	mpte->valid = promoted ? (all_l3e_AF_set ? VM_PAGE_BITS_ALL : 1) : 0;
4557 	return (vm_radix_insert(&pmap->pm_root, mpte));
4558 }
4559 
4560 /*
4561  * Removes the page table page mapping the specified virtual address from the
4562  * specified pmap's collection of idle page table pages, and returns it.
4563  * Otherwise, returns NULL if there is no page table page corresponding to the
4564  * specified virtual address.
4565  */
4566 static __inline vm_page_t
pmap_remove_pt_page(pmap_t pmap,vm_offset_t va)4567 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4568 {
4569 
4570 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4571 	return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
4572 }
4573 
4574 /*
4575  * Performs a break-before-make update of a pmap entry. This is needed when
4576  * either promoting or demoting pages to ensure the TLB doesn't get into an
4577  * inconsistent state.
4578  */
4579 static void
pmap_update_entry(pmap_t pmap,pd_entry_t * ptep,pd_entry_t newpte,vm_offset_t va,vm_size_t size)4580 pmap_update_entry(pmap_t pmap, pd_entry_t *ptep, pd_entry_t newpte,
4581     vm_offset_t va, vm_size_t size)
4582 {
4583 	register_t intr;
4584 
4585 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4586 	KASSERT((newpte & ATTR_SW_NO_PROMOTE) == 0,
4587 	    ("%s: Updating non-promote pte", __func__));
4588 
4589 	/*
4590 	 * Ensure we don't get switched out with the page table in an
4591 	 * inconsistent state. We also need to ensure no interrupts fire
4592 	 * as they may make use of an address we are about to invalidate.
4593 	 */
4594 	intr = intr_disable();
4595 
4596 	/*
4597 	 * Clear the old mapping's valid bit, but leave the rest of the entry
4598 	 * unchanged, so that a lockless, concurrent pmap_kextract() can still
4599 	 * lookup the physical address.
4600 	 */
4601 	pmap_clear_bits(ptep, ATTR_DESCR_VALID);
4602 
4603 	/*
4604 	 * When promoting, the L{1,2}_TABLE entry that is being replaced might
4605 	 * be cached, so we invalidate intermediate entries as well as final
4606 	 * entries.
4607 	 */
4608 	pmap_s1_invalidate_range(pmap, va, va + size, false);
4609 
4610 	/* Create the new mapping */
4611 	pmap_store(ptep, newpte);
4612 	dsb(ishst);
4613 
4614 	intr_restore(intr);
4615 }
4616 
4617 /*
4618  * Performs a break-before-make update of an ATTR_CONTIGUOUS mapping.
4619  */
4620 static void __nosanitizecoverage
pmap_update_strided(pmap_t pmap,pd_entry_t * ptep,pd_entry_t * ptep_end,pd_entry_t newpte,vm_offset_t va,vm_offset_t stride,vm_size_t size)4621 pmap_update_strided(pmap_t pmap, pd_entry_t *ptep, pd_entry_t *ptep_end,
4622     pd_entry_t newpte, vm_offset_t va, vm_offset_t stride, vm_size_t size)
4623 {
4624 	pd_entry_t *lip;
4625 	register_t intr;
4626 
4627 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4628 	KASSERT((newpte & ATTR_SW_NO_PROMOTE) == 0,
4629 	    ("%s: Updating non-promote pte", __func__));
4630 
4631 	/*
4632 	 * Ensure we don't get switched out with the page table in an
4633 	 * inconsistent state. We also need to ensure no interrupts fire
4634 	 * as they may make use of an address we are about to invalidate.
4635 	 */
4636 	intr = intr_disable();
4637 
4638 	/*
4639 	 * Clear the old mapping's valid bits, but leave the rest of each
4640 	 * entry unchanged, so that a lockless, concurrent pmap_kextract() can
4641 	 * still lookup the physical address.
4642 	 */
4643 	for (lip = ptep; lip < ptep_end; lip++)
4644 		pmap_clear_bits(lip, ATTR_DESCR_VALID);
4645 
4646 	/* Only final entries are changing. */
4647 	pmap_s1_invalidate_strided(pmap, va, va + size, stride, true);
4648 
4649 	/* Create the new mapping. */
4650 	for (lip = ptep; lip < ptep_end; lip++) {
4651 		pmap_store(lip, newpte);
4652 		newpte += stride;
4653 	}
4654 	dsb(ishst);
4655 
4656 	intr_restore(intr);
4657 }
4658 
4659 #if VM_NRESERVLEVEL > 0
4660 /*
4661  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
4662  * replace the many pv entries for the 4KB page mappings by a single pv entry
4663  * for the 2MB page mapping.
4664  */
4665 static void
pmap_pv_promote_l2(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)4666 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4667     struct rwlock **lockp)
4668 {
4669 	struct md_page *pvh;
4670 	pv_entry_t pv;
4671 	vm_offset_t va_last;
4672 	vm_page_t m;
4673 
4674 	KASSERT((pa & L2_OFFSET) == 0,
4675 	    ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
4676 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4677 
4678 	/*
4679 	 * Transfer the first page's pv entry for this mapping to the 2mpage's
4680 	 * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
4681 	 * a transfer avoids the possibility that get_pv_entry() calls
4682 	 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
4683 	 * mappings that is being promoted.
4684 	 */
4685 	m = PHYS_TO_VM_PAGE(pa);
4686 	va = va & ~L2_OFFSET;
4687 	pv = pmap_pvh_remove(&m->md, pmap, va);
4688 	KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
4689 	pvh = page_to_pvh(m);
4690 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4691 	pvh->pv_gen++;
4692 	/* Free the remaining NPTEPG - 1 pv entries. */
4693 	va_last = va + L2_SIZE - PAGE_SIZE;
4694 	do {
4695 		m++;
4696 		va += PAGE_SIZE;
4697 		pmap_pvh_free(&m->md, pmap, va);
4698 	} while (va < va_last);
4699 }
4700 
4701 /*
4702  * Tries to promote the 512, contiguous 4KB page mappings that are within a
4703  * single level 2 table entry to a single 2MB page mapping.  For promotion
4704  * to occur, two conditions must be met: (1) the 4KB page mappings must map
4705  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4706  * identical characteristics.
4707  */
4708 static bool
pmap_promote_l2(pmap_t pmap,pd_entry_t * l2,vm_offset_t va,vm_page_t mpte,struct rwlock ** lockp)4709 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
4710     struct rwlock **lockp)
4711 {
4712 	pt_entry_t all_l3e_AF, *firstl3, *l3, newl2, oldl3, pa;
4713 
4714 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4715 
4716 	/*
4717 	 * Currently, this function only supports promotion on stage 1 pmaps
4718 	 * because it tests stage 1 specific fields and performs a break-
4719 	 * before-make sequence that is incorrect for stage 2 pmaps.
4720 	 */
4721 	if (pmap->pm_stage != PM_STAGE1 || !pmap_ps_enabled(pmap))
4722 		return (false);
4723 
4724 	/*
4725 	 * Examine the first L3E in the specified PTP.  Abort if this L3E is
4726 	 * ineligible for promotion...
4727 	 */
4728 	firstl3 = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l2)));
4729 	newl2 = pmap_load(firstl3);
4730 	if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
4731 		return (false);
4732 	/* ... is not the first physical page within an L2 block */
4733 	if ((PTE_TO_PHYS(newl2) & L2_OFFSET) != 0 ||
4734 	    ((newl2 & ATTR_DESCR_MASK) != L3_PAGE)) { /* ... or is invalid */
4735 		atomic_add_long(&pmap_l2_p_failures, 1);
4736 		CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4737 		    " in pmap %p", va, pmap);
4738 		return (false);
4739 	}
4740 
4741 	/*
4742 	 * Both here and in the below "for" loop, to allow for repromotion
4743 	 * after MADV_FREE, conditionally write protect a clean L3E before
4744 	 * possibly aborting the promotion due to other L3E attributes.  Why?
4745 	 * Suppose that MADV_FREE is applied to a part of a superpage, the
4746 	 * address range [S, E).  pmap_advise() will demote the superpage
4747 	 * mapping, destroy the 4KB page mapping at the end of [S, E), and
4748 	 * set AP_RO and clear AF in the L3Es for the rest of [S, E).  Later,
4749 	 * imagine that the memory in [S, E) is recycled, but the last 4KB
4750 	 * page in [S, E) is not the last to be rewritten, or simply accessed.
4751 	 * In other words, there is still a 4KB page in [S, E), call it P,
4752 	 * that is writeable but AP_RO is set and AF is clear in P's L3E.
4753 	 * Unless we write protect P before aborting the promotion, if and
4754 	 * when P is finally rewritten, there won't be a page fault to trigger
4755 	 * repromotion.
4756 	 */
4757 setl2:
4758 	if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4759 	    (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4760 		/*
4761 		 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4762 		 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4763 		 */
4764 		if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
4765 			goto setl2;
4766 		newl2 &= ~ATTR_SW_DBM;
4767 		CTR2(KTR_PMAP, "pmap_promote_l2: protect for va %#lx"
4768 		    " in pmap %p", va & ~L2_OFFSET, pmap);
4769 	}
4770 
4771 	/*
4772 	 * Examine each of the other L3Es in the specified PTP.  Abort if this
4773 	 * L3E maps an unexpected 4KB physical page or does not have identical
4774 	 * characteristics to the first L3E.  If ATTR_AF is not set in every
4775 	 * PTE, then request that the PTP be refilled on demotion.
4776 	 */
4777 	all_l3e_AF = newl2 & ATTR_AF;
4778 	pa = (PTE_TO_PHYS(newl2) | (newl2 & ATTR_DESCR_MASK))
4779 	    + L2_SIZE - PAGE_SIZE;
4780 	for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4781 		oldl3 = pmap_load(l3);
4782 		if ((PTE_TO_PHYS(oldl3) | (oldl3 & ATTR_DESCR_MASK)) != pa) {
4783 			atomic_add_long(&pmap_l2_p_failures, 1);
4784 			CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4785 			    " in pmap %p", va, pmap);
4786 			return (false);
4787 		}
4788 setl3:
4789 		if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4790 		    (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4791 			/*
4792 			 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4793 			 * set, ATTR_SW_DBM can be cleared without a TLB
4794 			 * invalidation.
4795 			 */
4796 			if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4797 			    ~ATTR_SW_DBM))
4798 				goto setl3;
4799 			oldl3 &= ~ATTR_SW_DBM;
4800 		}
4801 		if ((oldl3 & ATTR_PROMOTE) != (newl2 & ATTR_PROMOTE)) {
4802 			atomic_add_long(&pmap_l2_p_failures, 1);
4803 			CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4804 			    " in pmap %p", va, pmap);
4805 			return (false);
4806 		}
4807 		all_l3e_AF &= oldl3;
4808 		pa -= PAGE_SIZE;
4809 	}
4810 
4811 	/*
4812 	 * Unless all PTEs have ATTR_AF set, clear it from the superpage
4813 	 * mapping, so that promotions triggered by speculative mappings,
4814 	 * such as pmap_enter_quick(), don't automatically mark the
4815 	 * underlying pages as referenced.
4816 	 */
4817 	newl2 &= ~(ATTR_CONTIGUOUS | ATTR_AF | ATTR_DESCR_MASK) | all_l3e_AF;
4818 
4819 	/*
4820 	 * Save the page table page in its current state until the L2
4821 	 * mapping the superpage is demoted by pmap_demote_l2() or
4822 	 * destroyed by pmap_remove_l3().
4823 	 */
4824 	if (mpte == NULL)
4825 		mpte = PTE_TO_VM_PAGE(pmap_load(l2));
4826 	KASSERT(mpte >= vm_page_array &&
4827 	    mpte < &vm_page_array[vm_page_array_size],
4828 	    ("pmap_promote_l2: page table page is out of range"));
4829 	KASSERT(mpte->pindex == pmap_l2_pindex(va),
4830 	    ("pmap_promote_l2: page table page's pindex is wrong"));
4831 	if (pmap_insert_pt_page(pmap, mpte, true, all_l3e_AF != 0)) {
4832 		atomic_add_long(&pmap_l2_p_failures, 1);
4833 		CTR2(KTR_PMAP,
4834 		    "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4835 		    pmap);
4836 		return (false);
4837 	}
4838 
4839 	if ((newl2 & ATTR_SW_MANAGED) != 0)
4840 		pmap_pv_promote_l2(pmap, va, PTE_TO_PHYS(newl2), lockp);
4841 
4842 	pmap_update_entry(pmap, l2, newl2 | L2_BLOCK, va & ~L2_OFFSET, L2_SIZE);
4843 
4844 	atomic_add_long(&pmap_l2_promotions, 1);
4845 	CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4846 	    pmap);
4847 	return (true);
4848 }
4849 
4850 /*
4851  * Tries to promote an aligned, contiguous set of base page mappings to a
4852  * single L3C page mapping.  For promotion to occur, two conditions must be
4853  * met: (1) the base page mappings must map aligned, contiguous physical
4854  * memory and (2) the base page mappings must have identical characteristics
4855  * except for the accessed flag.
4856  */
4857 static bool
pmap_promote_l3c(pmap_t pmap,pd_entry_t * l3p,vm_offset_t va)4858 pmap_promote_l3c(pmap_t pmap, pd_entry_t *l3p, vm_offset_t va)
4859 {
4860 	pd_entry_t all_l3e_AF, firstl3c, *l3, oldl3, pa;
4861 
4862 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4863 
4864 	/*
4865 	 * Currently, this function only supports promotion on stage 1 pmaps
4866 	 * because it tests stage 1 specific fields and performs a break-
4867 	 * before-make sequence that is incorrect for stage 2 pmaps.
4868 	 */
4869 	if (pmap->pm_stage != PM_STAGE1 || !pmap_ps_enabled(pmap))
4870 		return (false);
4871 
4872 	/*
4873 	 * Compute the address of the first L3 entry in the superpage
4874 	 * candidate.
4875 	 */
4876 	l3p = (pt_entry_t *)((uintptr_t)l3p & ~((L3C_ENTRIES *
4877 	    sizeof(pt_entry_t)) - 1));
4878 
4879 	firstl3c = pmap_load(l3p);
4880 
4881 	/*
4882 	 * Examine the first L3 entry. Abort if this L3E is ineligible for
4883 	 * promotion...
4884 	 */
4885 	if ((firstl3c & ATTR_SW_NO_PROMOTE) != 0)
4886 		return (false);
4887 	/* ...is not properly aligned... */
4888 	if ((PTE_TO_PHYS(firstl3c) & L3C_OFFSET) != 0 ||
4889 	    (firstl3c & ATTR_DESCR_MASK) != L3_PAGE) { /* ...or is invalid. */
4890 		counter_u64_add(pmap_l3c_p_failures, 1);
4891 		CTR2(KTR_PMAP, "pmap_promote_l3c: failure for va %#lx"
4892 		    " in pmap %p", va, pmap);
4893 		return (false);
4894 	}
4895 
4896 	/*
4897 	 * If the first L3 entry is a clean read-write mapping, convert it
4898 	 * to a read-only mapping.  See pmap_promote_l2() for the rationale.
4899 	 */
4900 set_first:
4901 	if ((firstl3c & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4902 	    (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4903 		/*
4904 		 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4905 		 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4906 		 */
4907 		if (!atomic_fcmpset_64(l3p, &firstl3c, firstl3c & ~ATTR_SW_DBM))
4908 			goto set_first;
4909 		firstl3c &= ~ATTR_SW_DBM;
4910 		CTR2(KTR_PMAP, "pmap_promote_l3c: protect for va %#lx"
4911 		    " in pmap %p", va & ~L3C_OFFSET, pmap);
4912 	}
4913 
4914 	/*
4915 	 * Check that the rest of the L3 entries are compatible with the first,
4916 	 * and convert clean read-write mappings to read-only mappings.
4917 	 */
4918 	all_l3e_AF = firstl3c & ATTR_AF;
4919 	pa = (PTE_TO_PHYS(firstl3c) | (firstl3c & ATTR_DESCR_MASK)) +
4920 	    L3C_SIZE - PAGE_SIZE;
4921 	for (l3 = l3p + L3C_ENTRIES - 1; l3 > l3p; l3--) {
4922 		oldl3 = pmap_load(l3);
4923 		if ((PTE_TO_PHYS(oldl3) | (oldl3 & ATTR_DESCR_MASK)) != pa) {
4924 			counter_u64_add(pmap_l3c_p_failures, 1);
4925 			CTR2(KTR_PMAP, "pmap_promote_l3c: failure for va %#lx"
4926 			    " in pmap %p", va, pmap);
4927 			return (false);
4928 		}
4929 set_l3:
4930 		if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4931 		    (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4932 			/*
4933 			 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4934 			 * set, ATTR_SW_DBM can be cleared without a TLB
4935 			 * invalidation.
4936 			 */
4937 			if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4938 			    ~ATTR_SW_DBM))
4939 				goto set_l3;
4940 			oldl3 &= ~ATTR_SW_DBM;
4941 			CTR2(KTR_PMAP, "pmap_promote_l3c: protect for va %#lx"
4942 			    " in pmap %p", (oldl3 & ~ATTR_MASK & L3C_OFFSET) |
4943 			    (va & ~L3C_OFFSET), pmap);
4944 		}
4945 		if ((oldl3 & ATTR_PROMOTE) != (firstl3c & ATTR_PROMOTE)) {
4946 			counter_u64_add(pmap_l3c_p_failures, 1);
4947 			CTR2(KTR_PMAP, "pmap_promote_l3c: failure for va %#lx"
4948 			    " in pmap %p", va, pmap);
4949 			return (false);
4950 		}
4951 		all_l3e_AF &= oldl3;
4952 		pa -= PAGE_SIZE;
4953 	}
4954 
4955 	/*
4956 	 * Unless all PTEs have ATTR_AF set, clear it from the superpage
4957 	 * mapping, so that promotions triggered by speculative mappings,
4958 	 * such as pmap_enter_quick(), don't automatically mark the
4959 	 * underlying pages as referenced.
4960 	 */
4961 	firstl3c &= ~ATTR_AF | all_l3e_AF;
4962 
4963 	/*
4964 	 * Remake the mappings with the contiguous bit set.
4965 	 */
4966 	pmap_update_strided(pmap, l3p, l3p + L3C_ENTRIES, firstl3c |
4967 	    ATTR_CONTIGUOUS, va & ~L3C_OFFSET, L3_SIZE, L3C_SIZE);
4968 
4969 	counter_u64_add(pmap_l3c_promotions, 1);
4970 	CTR2(KTR_PMAP, "pmap_promote_l3c: success for va %#lx in pmap %p", va,
4971 	    pmap);
4972 	return (true);
4973 }
4974 #endif /* VM_NRESERVLEVEL > 0 */
4975 
4976 static int
pmap_enter_largepage(pmap_t pmap,vm_offset_t va,pt_entry_t pte,int flags,int psind)4977 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t pte, int flags,
4978     int psind)
4979 {
4980 	pd_entry_t *l0p, *l1p, *l2p, *l3p, newpte, origpte, *tl3p;
4981 	vm_page_t mp;
4982 
4983 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4984 	KASSERT(psind > 0 && psind < MAXPAGESIZES,
4985 	    ("psind %d unexpected", psind));
4986 	KASSERT((PTE_TO_PHYS(pte) & (pagesizes[psind] - 1)) == 0,
4987 	    ("unaligned phys address %#lx pte %#lx psind %d",
4988 	    PTE_TO_PHYS(pte), pte, psind));
4989 
4990 restart:
4991 	newpte = pte;
4992 	if (!pmap_bti_same(pmap, va, va + pagesizes[psind], &newpte))
4993 		return (KERN_PROTECTION_FAILURE);
4994 	if (psind == 3) {
4995 		PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4996 
4997 		KASSERT(pagesizes[psind] == L1_SIZE,
4998 		    ("pagesizes[%d] != L1_SIZE", psind));
4999 		l0p = pmap_l0(pmap, va);
5000 		if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
5001 			mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
5002 			if (mp == NULL) {
5003 				if ((flags & PMAP_ENTER_NOSLEEP) != 0)
5004 					return (KERN_RESOURCE_SHORTAGE);
5005 				PMAP_UNLOCK(pmap);
5006 				vm_wait(NULL);
5007 				PMAP_LOCK(pmap);
5008 				goto restart;
5009 			}
5010 			l1p = pmap_l0_to_l1(l0p, va);
5011 			KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
5012 			origpte = pmap_load(l1p);
5013 		} else {
5014 			l1p = pmap_l0_to_l1(l0p, va);
5015 			KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
5016 			origpte = pmap_load(l1p);
5017 			if ((origpte & ATTR_DESCR_VALID) == 0) {
5018 				mp = PTE_TO_VM_PAGE(pmap_load(l0p));
5019 				mp->ref_count++;
5020 			}
5021 		}
5022 		KASSERT((PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte) &&
5023 		    (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
5024 		    (origpte & ATTR_DESCR_VALID) == 0,
5025 		    ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
5026 		    va, origpte, newpte));
5027 		pmap_store(l1p, newpte);
5028 	} else if (psind == 2) {
5029 		KASSERT(pagesizes[psind] == L2_SIZE,
5030 		    ("pagesizes[%d] != L2_SIZE", psind));
5031 		l2p = pmap_l2(pmap, va);
5032 		if (l2p == NULL) {
5033 			mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
5034 			if (mp == NULL) {
5035 				if ((flags & PMAP_ENTER_NOSLEEP) != 0)
5036 					return (KERN_RESOURCE_SHORTAGE);
5037 				PMAP_UNLOCK(pmap);
5038 				vm_wait(NULL);
5039 				PMAP_LOCK(pmap);
5040 				goto restart;
5041 			}
5042 			l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
5043 			l2p = &l2p[pmap_l2_index(va)];
5044 			origpte = pmap_load(l2p);
5045 		} else {
5046 			l1p = pmap_l1(pmap, va);
5047 			origpte = pmap_load(l2p);
5048 			if ((origpte & ATTR_DESCR_VALID) == 0) {
5049 				mp = PTE_TO_VM_PAGE(pmap_load(l1p));
5050 				mp->ref_count++;
5051 			}
5052 		}
5053 		KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
5054 		    ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
5055 		    PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte)),
5056 		    ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
5057 		    va, origpte, newpte));
5058 		pmap_store(l2p, newpte);
5059 	} else /* (psind == 1) */ {
5060 		KASSERT(pagesizes[psind] == L3C_SIZE,
5061 		    ("pagesizes[%d] != L3C_SIZE", psind));
5062 		l2p = pmap_l2(pmap, va);
5063 		if (l2p == NULL || (pmap_load(l2p) & ATTR_DESCR_VALID) == 0) {
5064 			mp = _pmap_alloc_l3(pmap, pmap_l2_pindex(va), NULL);
5065 			if (mp == NULL) {
5066 				if ((flags & PMAP_ENTER_NOSLEEP) != 0)
5067 					return (KERN_RESOURCE_SHORTAGE);
5068 				PMAP_UNLOCK(pmap);
5069 				vm_wait(NULL);
5070 				PMAP_LOCK(pmap);
5071 				goto restart;
5072 			}
5073 			mp->ref_count += L3C_ENTRIES - 1;
5074 			l3p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
5075 			l3p = &l3p[pmap_l3_index(va)];
5076 		} else {
5077 			l3p = pmap_l2_to_l3(l2p, va);
5078 			if ((pmap_load(l3p) & ATTR_DESCR_VALID) == 0) {
5079 				mp = PTE_TO_VM_PAGE(pmap_load(l2p));
5080 				mp->ref_count += L3C_ENTRIES;
5081 			}
5082 		}
5083 		for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
5084 			origpte = pmap_load(tl3p);
5085 			KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
5086 			    ((origpte & ATTR_CONTIGUOUS) != 0 &&
5087 			    PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte)),
5088 			    ("va %#lx changing 64K phys page l3 %#lx newpte %#lx",
5089 			    va, origpte, newpte));
5090 			pmap_store(tl3p, newpte);
5091 			newpte += L3_SIZE;
5092 		}
5093 	}
5094 	dsb(ishst);
5095 
5096 	if ((origpte & ATTR_DESCR_VALID) == 0)
5097 		pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
5098 	if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
5099 		pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
5100 	else if ((newpte & ATTR_SW_WIRED) == 0 &&
5101 	    (origpte & ATTR_SW_WIRED) != 0)
5102 		pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
5103 
5104 	return (KERN_SUCCESS);
5105 }
5106 
5107 /*
5108  *	Insert the given physical page (p) at
5109  *	the specified virtual address (v) in the
5110  *	target physical map with the protection requested.
5111  *
5112  *	If specified, the page will be wired down, meaning
5113  *	that the related pte can not be reclaimed.
5114  *
5115  *	NB:  This is the only routine which MAY NOT lazy-evaluate
5116  *	or lose information.  That is, this routine must actually
5117  *	insert this page into the given map NOW.
5118  */
5119 int
pmap_enter(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,u_int flags,int8_t psind)5120 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5121     u_int flags, int8_t psind)
5122 {
5123 	struct rwlock *lock;
5124 	pd_entry_t *pde;
5125 	pt_entry_t new_l3, orig_l3;
5126 	pt_entry_t *l2, *l3;
5127 	pv_entry_t pv;
5128 	vm_paddr_t opa, pa;
5129 	vm_page_t mpte, om;
5130 	bool nosleep;
5131 	int full_lvl, lvl, rv;
5132 
5133 	KASSERT(ADDR_IS_CANONICAL(va),
5134 	    ("%s: Address not in canonical form: %lx", __func__, va));
5135 
5136 	va = trunc_page(va);
5137 	if ((m->oflags & VPO_UNMANAGED) == 0)
5138 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
5139 	pa = VM_PAGE_TO_PHYS(m);
5140 	new_l3 = (pt_entry_t)(PHYS_TO_PTE(pa) | ATTR_AF | pmap_sh_attr |
5141 	    L3_PAGE);
5142 	new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
5143 	new_l3 |= pmap_pte_prot(pmap, prot);
5144 	if ((flags & PMAP_ENTER_WIRED) != 0)
5145 		new_l3 |= ATTR_SW_WIRED;
5146 	if (pmap->pm_stage == PM_STAGE1) {
5147 		if (!ADDR_IS_KERNEL(va))
5148 			new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5149 		else
5150 			new_l3 |= ATTR_S1_UXN;
5151 		if (pmap != kernel_pmap)
5152 			new_l3 |= ATTR_S1_nG;
5153 	} else {
5154 		/*
5155 		 * Clear the access flag on executable mappings, this will be
5156 		 * set later when the page is accessed. The fault handler is
5157 		 * required to invalidate the I-cache.
5158 		 *
5159 		 * TODO: Switch to the valid flag to allow hardware management
5160 		 * of the access flag. Much of the pmap code assumes the
5161 		 * valid flag is set and fails to destroy the old page tables
5162 		 * correctly if it is clear.
5163 		 */
5164 		if (prot & VM_PROT_EXECUTE)
5165 			new_l3 &= ~ATTR_AF;
5166 	}
5167 	if ((m->oflags & VPO_UNMANAGED) == 0) {
5168 		new_l3 |= ATTR_SW_MANAGED;
5169 		if ((prot & VM_PROT_WRITE) != 0) {
5170 			new_l3 |= ATTR_SW_DBM;
5171 			if ((flags & VM_PROT_WRITE) == 0) {
5172 				if (pmap->pm_stage == PM_STAGE1)
5173 					new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
5174 				else
5175 					new_l3 &=
5176 					    ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
5177 			}
5178 		}
5179 	}
5180 
5181 	CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
5182 
5183 	lock = NULL;
5184 	PMAP_LOCK(pmap);
5185 	if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
5186 		KASSERT((m->oflags & VPO_UNMANAGED) != 0,
5187 		    ("managed largepage va %#lx flags %#x", va, flags));
5188 		if (psind == 3) {
5189 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5190 			new_l3 &= ~L3_PAGE;
5191 			new_l3 |= L1_BLOCK;
5192 		} else if (psind == 2) {
5193 			new_l3 &= ~L3_PAGE;
5194 			new_l3 |= L2_BLOCK;
5195 		} else /* (psind == 1) */
5196 			new_l3 |= ATTR_CONTIGUOUS;
5197 		rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
5198 		goto out;
5199 	}
5200 	if (psind == 2) {
5201 		/* Assert the required virtual and physical alignment. */
5202 		KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
5203 		KASSERT(m->psind > 1, ("pmap_enter: m->psind < psind"));
5204 		rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
5205 		    flags, m, &lock);
5206 		goto out;
5207 	}
5208 	mpte = NULL;
5209 	if (psind == 1) {
5210 		KASSERT((va & L3C_OFFSET) == 0, ("pmap_enter: va unaligned"));
5211 		KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
5212 		rv = pmap_enter_l3c(pmap, va, new_l3 | ATTR_CONTIGUOUS, flags,
5213 		    m, &mpte, &lock);
5214 #if VM_NRESERVLEVEL > 0
5215 		/*
5216 		 * Attempt L2 promotion, if both the PTP and a level 1
5217 		 * reservation are fully populated.
5218 		 */
5219 		if (rv == KERN_SUCCESS &&
5220 		    (mpte == NULL || mpte->ref_count == NL3PG) &&
5221 		    (m->flags & PG_FICTITIOUS) == 0 &&
5222 		    vm_reserv_level_iffullpop(m) == 1) {
5223 			pde = pmap_l2(pmap, va);
5224 			(void)pmap_promote_l2(pmap, pde, va, mpte, &lock);
5225 		}
5226 #endif
5227 		goto out;
5228 	}
5229 
5230 	/*
5231 	 * In the case that a page table page is not
5232 	 * resident, we are creating it here.
5233 	 */
5234 retry:
5235 	pde = pmap_pde(pmap, va, &lvl);
5236 	if (pde != NULL && lvl == 2) {
5237 		l3 = pmap_l2_to_l3(pde, va);
5238 		if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
5239 			mpte = PTE_TO_VM_PAGE(pmap_load(pde));
5240 			mpte->ref_count++;
5241 		}
5242 		goto havel3;
5243 	} else if (pde != NULL && lvl == 1) {
5244 		l2 = pmap_l1_to_l2(pde, va);
5245 		if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
5246 		    (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
5247 			l3 = &l3[pmap_l3_index(va)];
5248 			if (!ADDR_IS_KERNEL(va)) {
5249 				mpte = PTE_TO_VM_PAGE(pmap_load(l2));
5250 				mpte->ref_count++;
5251 			}
5252 			goto havel3;
5253 		}
5254 		/* We need to allocate an L3 table. */
5255 	}
5256 	if (!ADDR_IS_KERNEL(va)) {
5257 		nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
5258 
5259 		/*
5260 		 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
5261 		 * to handle the possibility that a superpage mapping for "va"
5262 		 * was created while we slept.
5263 		 */
5264 		mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
5265 		    nosleep ? NULL : &lock);
5266 		if (mpte == NULL && nosleep) {
5267 			CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
5268 			rv = KERN_RESOURCE_SHORTAGE;
5269 			goto out;
5270 		}
5271 		goto retry;
5272 	} else
5273 		panic("pmap_enter: missing L3 table for kernel va %#lx", va);
5274 
5275 havel3:
5276 	orig_l3 = pmap_load(l3);
5277 	opa = PTE_TO_PHYS(orig_l3);
5278 	pv = NULL;
5279 	new_l3 |= pmap_pte_bti(pmap, va);
5280 
5281 	/*
5282 	 * Is the specified virtual address already mapped?
5283 	 */
5284 	if (pmap_l3_valid(orig_l3)) {
5285 		/*
5286 		 * Wiring change, just update stats. We don't worry about
5287 		 * wiring PT pages as they remain resident as long as there
5288 		 * are valid mappings in them. Hence, if a user page is wired,
5289 		 * the PT page will be also.
5290 		 */
5291 		if ((flags & PMAP_ENTER_WIRED) != 0 &&
5292 		    (orig_l3 & ATTR_SW_WIRED) == 0)
5293 			pmap->pm_stats.wired_count++;
5294 		else if ((flags & PMAP_ENTER_WIRED) == 0 &&
5295 		    (orig_l3 & ATTR_SW_WIRED) != 0)
5296 			pmap->pm_stats.wired_count--;
5297 
5298 		/*
5299 		 * Remove the extra PT page reference.
5300 		 */
5301 		if (mpte != NULL) {
5302 			mpte->ref_count--;
5303 			KASSERT(mpte->ref_count > 0,
5304 			    ("pmap_enter: missing reference to page table page,"
5305 			     " va: 0x%lx", va));
5306 		}
5307 
5308 		/*
5309 		 * Has the physical page changed?
5310 		 */
5311 		if (opa == pa) {
5312 			/*
5313 			 * No, might be a protection or wiring change.
5314 			 */
5315 			if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
5316 			    (new_l3 & ATTR_SW_DBM) != 0)
5317 				vm_page_aflag_set(m, PGA_WRITEABLE);
5318 			goto validate;
5319 		}
5320 
5321 		/*
5322 		 * The physical page has changed.  Temporarily invalidate
5323 		 * the mapping.
5324 		 */
5325 		if ((orig_l3 & ATTR_CONTIGUOUS) != 0)
5326 			(void)pmap_demote_l3c(pmap, l3, va);
5327 		orig_l3 = pmap_load_clear(l3);
5328 		KASSERT(PTE_TO_PHYS(orig_l3) == opa,
5329 		    ("pmap_enter: unexpected pa update for %#lx", va));
5330 		if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
5331 			om = PHYS_TO_VM_PAGE(opa);
5332 
5333 			/*
5334 			 * The pmap lock is sufficient to synchronize with
5335 			 * concurrent calls to pmap_page_test_mappings() and
5336 			 * pmap_ts_referenced().
5337 			 */
5338 			if (pmap_pte_dirty(pmap, orig_l3))
5339 				vm_page_dirty(om);
5340 			if ((orig_l3 & ATTR_AF) != 0) {
5341 				pmap_invalidate_page(pmap, va, true);
5342 				vm_page_aflag_set(om, PGA_REFERENCED);
5343 			}
5344 			CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, om);
5345 			pv = pmap_pvh_remove(&om->md, pmap, va);
5346 			if ((m->oflags & VPO_UNMANAGED) != 0)
5347 				free_pv_entry(pmap, pv);
5348 			if ((om->a.flags & PGA_WRITEABLE) != 0 &&
5349 			    TAILQ_EMPTY(&om->md.pv_list) &&
5350 			    ((om->flags & PG_FICTITIOUS) != 0 ||
5351 			    TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
5352 				vm_page_aflag_clear(om, PGA_WRITEABLE);
5353 		} else {
5354 			KASSERT((orig_l3 & ATTR_AF) != 0,
5355 			    ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
5356 			pmap_invalidate_page(pmap, va, true);
5357 		}
5358 		orig_l3 = 0;
5359 	} else {
5360 		/*
5361 		 * Increment the counters.
5362 		 */
5363 		if ((new_l3 & ATTR_SW_WIRED) != 0)
5364 			pmap->pm_stats.wired_count++;
5365 		pmap_resident_count_inc(pmap, 1);
5366 	}
5367 	/*
5368 	 * Enter on the PV list if part of our managed memory.
5369 	 */
5370 	if ((m->oflags & VPO_UNMANAGED) == 0) {
5371 		if (pv == NULL) {
5372 			pv = get_pv_entry(pmap, &lock);
5373 			pv->pv_va = va;
5374 		}
5375 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5376 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5377 		m->md.pv_gen++;
5378 		if ((new_l3 & ATTR_SW_DBM) != 0)
5379 			vm_page_aflag_set(m, PGA_WRITEABLE);
5380 	}
5381 
5382 validate:
5383 	if (pmap->pm_stage == PM_STAGE1) {
5384 		/*
5385 		 * Sync icache if exec permission and attribute
5386 		 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
5387 		 * is stored and made valid for hardware table walk. If done
5388 		 * later, then other can access this page before caches are
5389 		 * properly synced. Don't do it for kernel memory which is
5390 		 * mapped with exec permission even if the memory isn't going
5391 		 * to hold executable code. The only time when icache sync is
5392 		 * needed is after kernel module is loaded and the relocation
5393 		 * info is processed. And it's done in elf_cpu_load_file().
5394 		*/
5395 		if ((prot & VM_PROT_EXECUTE) &&  pmap != kernel_pmap &&
5396 		    m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
5397 		    (opa != pa || (orig_l3 & ATTR_S1_XN))) {
5398 			PMAP_ASSERT_STAGE1(pmap);
5399 			cpu_icache_sync_range((void *)PHYS_TO_DMAP(pa),
5400 			    PAGE_SIZE);
5401 		}
5402 	} else {
5403 		cpu_dcache_wb_range((void *)PHYS_TO_DMAP(pa), PAGE_SIZE);
5404 	}
5405 
5406 	/*
5407 	 * Update the L3 entry
5408 	 */
5409 	if (pmap_l3_valid(orig_l3)) {
5410 		KASSERT(opa == pa, ("pmap_enter: invalid update"));
5411 		if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
5412 			/* same PA, different attributes */
5413 			if ((orig_l3 & ATTR_CONTIGUOUS) != 0)
5414 				(void)pmap_demote_l3c(pmap, l3, va);
5415 			orig_l3 = pmap_load_store(l3, new_l3);
5416 			pmap_invalidate_page(pmap, va, true);
5417 			if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
5418 			    pmap_pte_dirty(pmap, orig_l3))
5419 				vm_page_dirty(m);
5420 		} else {
5421 			/*
5422 			 * orig_l3 == new_l3
5423 			 * This can happens if multiple threads simultaneously
5424 			 * access not yet mapped page. This bad for performance
5425 			 * since this can cause full demotion-NOP-promotion
5426 			 * cycle.
5427 			 * Another possible reasons are:
5428 			 * - VM and pmap memory layout are diverged
5429 			 * - tlb flush is missing somewhere and CPU doesn't see
5430 			 *   actual mapping.
5431 			 */
5432 			CTR4(KTR_PMAP, "%s: already mapped page - "
5433 			    "pmap %p va 0x%#lx pte 0x%lx",
5434 			    __func__, pmap, va, new_l3);
5435 		}
5436 	} else {
5437 		/* New mapping */
5438 		pmap_store(l3, new_l3);
5439 		dsb(ishst);
5440 	}
5441 
5442 #if VM_NRESERVLEVEL > 0
5443 	/*
5444 	 * First, attempt L3C promotion, if the virtual and physical addresses
5445 	 * are aligned with each other and an underlying reservation has the
5446 	 * neighboring L3 pages allocated.  The first condition is simply an
5447 	 * optimization that recognizes some eventual promotion failures early
5448 	 * at a lower run-time cost.  Then, if both a level 1 reservation and
5449 	 * the PTP are fully populated, attempt L2 promotion.
5450 	 */
5451 	if ((va & L3C_OFFSET) == (pa & L3C_OFFSET) &&
5452 	    (m->flags & PG_FICTITIOUS) == 0 &&
5453 	    (full_lvl = vm_reserv_level_iffullpop(m)) >= 0 &&
5454 	    pmap_promote_l3c(pmap, l3, va) &&
5455 	    full_lvl == 1 && (mpte == NULL || mpte->ref_count == NL3PG))
5456 		(void)pmap_promote_l2(pmap, pde, va, mpte, &lock);
5457 #endif
5458 
5459 	rv = KERN_SUCCESS;
5460 out:
5461 	if (lock != NULL)
5462 		rw_wunlock(lock);
5463 	PMAP_UNLOCK(pmap);
5464 	return (rv);
5465 }
5466 
5467 /*
5468  * Tries to create a read- and/or execute-only L2 page mapping.  Returns
5469  * KERN_SUCCESS if the mapping was created.  Otherwise, returns an error
5470  * value.  See pmap_enter_l2() for the possible error values when "no sleep",
5471  * "no replace", and "no reclaim" are specified.
5472  */
5473 static int
pmap_enter_l2_rx(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,struct rwlock ** lockp)5474 pmap_enter_l2_rx(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5475     struct rwlock **lockp)
5476 {
5477 	pd_entry_t new_l2;
5478 
5479 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5480 	PMAP_ASSERT_STAGE1(pmap);
5481 	KASSERT(ADDR_IS_CANONICAL(va),
5482 	    ("%s: Address not in canonical form: %lx", __func__, va));
5483 
5484 	new_l2 = (pd_entry_t)(VM_PAGE_TO_PTE(m) | pmap_sh_attr |
5485 	    ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
5486 	    L2_BLOCK);
5487 	if ((m->oflags & VPO_UNMANAGED) == 0)
5488 		new_l2 |= ATTR_SW_MANAGED;
5489 	else
5490 		new_l2 |= ATTR_AF;
5491 	if ((prot & VM_PROT_EXECUTE) == 0 ||
5492 	    m->md.pv_memattr == VM_MEMATTR_DEVICE)
5493 		new_l2 |= ATTR_S1_XN;
5494 	if (!ADDR_IS_KERNEL(va))
5495 		new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5496 	else
5497 		new_l2 |= ATTR_S1_UXN;
5498 	if (pmap != kernel_pmap)
5499 		new_l2 |= ATTR_S1_nG;
5500 	return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
5501 	    PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
5502 }
5503 
5504 /*
5505  * Returns true if every page table entry in the specified page table is
5506  * zero.
5507  */
5508 static bool
pmap_every_pte_zero(vm_paddr_t pa)5509 pmap_every_pte_zero(vm_paddr_t pa)
5510 {
5511 	pt_entry_t *pt_end, *pte;
5512 
5513 	KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
5514 	pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
5515 	for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
5516 		if (*pte != 0)
5517 			return (false);
5518 	}
5519 	return (true);
5520 }
5521 
5522 /*
5523  * Tries to create the specified L2 page mapping.  Returns KERN_SUCCESS if
5524  * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
5525  * KERN_RESOURCE_SHORTAGE otherwise.  Returns KERN_FAILURE if
5526  * PMAP_ENTER_NOREPLACE was specified and a base page mapping already exists
5527  * within the L2 virtual address range starting at the specified virtual
5528  * address.  Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
5529  * L2 page mapping already exists at the specified virtual address.  Returns
5530  * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
5531  * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
5532  * and a PV entry allocation failed.
5533  */
5534 static int
pmap_enter_l2(pmap_t pmap,vm_offset_t va,pd_entry_t new_l2,u_int flags,vm_page_t m,struct rwlock ** lockp)5535 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
5536     vm_page_t m, struct rwlock **lockp)
5537 {
5538 	struct spglist free;
5539 	pd_entry_t *l2, old_l2;
5540 	vm_page_t l2pg, mt;
5541 	vm_page_t uwptpg;
5542 
5543 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5544 	KASSERT(ADDR_IS_CANONICAL(va),
5545 	    ("%s: Address not in canonical form: %lx", __func__, va));
5546 
5547 	if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
5548 	    PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
5549 		CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
5550 		    va, pmap);
5551 		return (KERN_RESOURCE_SHORTAGE);
5552 	}
5553 
5554 	/*
5555 	 * If bti is not the same for the whole l2 range, return failure
5556 	 * and let vm_fault() cope.  Check after l2 allocation, since
5557 	 * it could sleep.
5558 	 */
5559 	if (!pmap_bti_same(pmap, va, va + L2_SIZE, &new_l2)) {
5560 		KASSERT(l2pg != NULL, ("pmap_enter_l2: missing L2 PTP"));
5561 		pmap_abort_ptp(pmap, va, l2pg);
5562 		return (KERN_PROTECTION_FAILURE);
5563 	}
5564 
5565 	/*
5566 	 * If there are existing mappings, either abort or remove them.
5567 	 */
5568 	if ((old_l2 = pmap_load(l2)) != 0) {
5569 		KASSERT(l2pg == NULL || l2pg->ref_count > 1,
5570 		    ("pmap_enter_l2: l2pg's ref count is too low"));
5571 		if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5572 			if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
5573 				if (l2pg != NULL)
5574 					l2pg->ref_count--;
5575 				CTR2(KTR_PMAP,
5576 				    "pmap_enter_l2: no space for va %#lx"
5577 				    " in pmap %p", va, pmap);
5578 				return (KERN_NO_SPACE);
5579 			} else if (!ADDR_IS_KERNEL(va) ||
5580 			    !pmap_every_pte_zero(PTE_TO_PHYS(old_l2))) {
5581 				if (l2pg != NULL)
5582 					l2pg->ref_count--;
5583 				CTR2(KTR_PMAP,
5584 				    "pmap_enter_l2: failure for va %#lx"
5585 				    " in pmap %p", va, pmap);
5586 				return (KERN_FAILURE);
5587 			}
5588 		}
5589 		SLIST_INIT(&free);
5590 		if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
5591 			(void)pmap_remove_l2(pmap, l2, va,
5592 			    pmap_load(pmap_l1(pmap, va)), &free, lockp);
5593 		else
5594 			pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
5595 			    &free, lockp);
5596 		if (!ADDR_IS_KERNEL(va)) {
5597 			vm_page_free_pages_toq(&free, true);
5598 			KASSERT(pmap_load(l2) == 0,
5599 			    ("pmap_enter_l2: non-zero L2 entry %p", l2));
5600 		} else {
5601 			KASSERT(SLIST_EMPTY(&free),
5602 			    ("pmap_enter_l2: freed kernel page table page"));
5603 
5604 			/*
5605 			 * Both pmap_remove_l2() and pmap_remove_l3_range()
5606 			 * will leave the kernel page table page zero filled.
5607 			 * Nonetheless, the TLB could have an intermediate
5608 			 * entry for the kernel page table page, so request
5609 			 * an invalidation at all levels after clearing
5610 			 * the L2_TABLE entry.
5611 			 */
5612 			mt = PTE_TO_VM_PAGE(pmap_load(l2));
5613 			if (pmap_insert_pt_page(pmap, mt, false, false))
5614 				panic("pmap_enter_l2: trie insert failed");
5615 			pmap_clear(l2);
5616 			pmap_s1_invalidate_page(pmap, va, false);
5617 		}
5618 	}
5619 
5620 	/*
5621 	 * Allocate leaf ptpage for wired userspace pages.
5622 	 */
5623 	uwptpg = NULL;
5624 	if ((new_l2 & ATTR_SW_WIRED) != 0 && pmap != kernel_pmap) {
5625 		uwptpg = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5626 		if (uwptpg == NULL) {
5627 			pmap_abort_ptp(pmap, va, l2pg);
5628 			return (KERN_RESOURCE_SHORTAGE);
5629 		}
5630 		uwptpg->pindex = pmap_l2_pindex(va);
5631 		if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
5632 			vm_page_unwire_noq(uwptpg);
5633 			vm_page_free(uwptpg);
5634 			pmap_abort_ptp(pmap, va, l2pg);
5635 			return (KERN_RESOURCE_SHORTAGE);
5636 		}
5637 		pmap_resident_count_inc(pmap, 1);
5638 		uwptpg->ref_count = NL3PG;
5639 	}
5640 	if ((new_l2 & ATTR_SW_MANAGED) != 0) {
5641 		/*
5642 		 * Abort this mapping if its PV entry could not be created.
5643 		 */
5644 		if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
5645 			if (l2pg != NULL)
5646 				pmap_abort_ptp(pmap, va, l2pg);
5647 			if (uwptpg != NULL) {
5648 				mt = pmap_remove_pt_page(pmap, va);
5649 				KASSERT(mt == uwptpg,
5650 				    ("removed pt page %p, expected %p", mt,
5651 				    uwptpg));
5652 				pmap_resident_count_dec(pmap, 1);
5653 				uwptpg->ref_count = 1;
5654 				vm_page_unwire_noq(uwptpg);
5655 				vm_page_free(uwptpg);
5656 			}
5657 			CTR2(KTR_PMAP,
5658 			    "pmap_enter_l2: failure for va %#lx in pmap %p",
5659 			    va, pmap);
5660 			return (KERN_RESOURCE_SHORTAGE);
5661 		}
5662 		if ((new_l2 & ATTR_SW_DBM) != 0)
5663 			for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5664 				vm_page_aflag_set(mt, PGA_WRITEABLE);
5665 	}
5666 
5667 	/*
5668 	 * Increment counters.
5669 	 */
5670 	if ((new_l2 & ATTR_SW_WIRED) != 0)
5671 		pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
5672 	pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
5673 
5674 	/*
5675 	 * Conditionally sync the icache.  See pmap_enter() for details.
5676 	 */
5677 	if ((new_l2 & ATTR_S1_XN) == 0 && (PTE_TO_PHYS(new_l2) !=
5678 	    PTE_TO_PHYS(old_l2) || (old_l2 & ATTR_S1_XN) != 0) &&
5679 	    pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
5680 		cpu_icache_sync_range((void *)PHYS_TO_DMAP(PTE_TO_PHYS(new_l2)),
5681 		    L2_SIZE);
5682 	}
5683 
5684 	/*
5685 	 * Map the superpage.
5686 	 */
5687 	pmap_store(l2, new_l2);
5688 	dsb(ishst);
5689 
5690 	atomic_add_long(&pmap_l2_mappings, 1);
5691 	CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
5692 	    va, pmap);
5693 
5694 	return (KERN_SUCCESS);
5695 }
5696 
5697 /*
5698  * Tries to create a read- and/or execute-only L3C page mapping.  Returns
5699  * KERN_SUCCESS if the mapping was created.  Otherwise, returns an error
5700  * value.
5701  */
5702 static int
pmap_enter_l3c_rx(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_page_t * ml3p,vm_prot_t prot,struct rwlock ** lockp)5703 pmap_enter_l3c_rx(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_page_t *ml3p,
5704     vm_prot_t prot, struct rwlock **lockp)
5705 {
5706 	pt_entry_t l3e;
5707 
5708 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5709 	PMAP_ASSERT_STAGE1(pmap);
5710 	KASSERT(ADDR_IS_CANONICAL(va),
5711 	    ("%s: Address not in canonical form: %lx", __func__, va));
5712 
5713 	l3e = VM_PAGE_TO_PTE(m) | pmap_sh_attr |
5714 	    ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
5715 	    ATTR_CONTIGUOUS | L3_PAGE;
5716 	if ((m->oflags & VPO_UNMANAGED) == 0)
5717 		l3e |= ATTR_SW_MANAGED;
5718 	else
5719 		l3e |= ATTR_AF;
5720 	if ((prot & VM_PROT_EXECUTE) == 0 ||
5721 	    m->md.pv_memattr == VM_MEMATTR_DEVICE)
5722 		l3e |= ATTR_S1_XN;
5723 	if (!ADDR_IS_KERNEL(va))
5724 		l3e |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5725 	else
5726 		l3e |= ATTR_S1_UXN;
5727 	if (pmap != kernel_pmap)
5728 		l3e |= ATTR_S1_nG;
5729 	return (pmap_enter_l3c(pmap, va, l3e, PMAP_ENTER_NOSLEEP |
5730 	    PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, ml3p, lockp));
5731 }
5732 
5733 static int
pmap_enter_l3c(pmap_t pmap,vm_offset_t va,pt_entry_t l3e,u_int flags,vm_page_t m,vm_page_t * ml3p,struct rwlock ** lockp)5734 pmap_enter_l3c(pmap_t pmap, vm_offset_t va, pt_entry_t l3e, u_int flags,
5735     vm_page_t m, vm_page_t *ml3p, struct rwlock **lockp)
5736 {
5737 	pd_entry_t *l2p, *pde;
5738 	pt_entry_t *l3p, *tl3p;
5739 	vm_page_t mt;
5740 	vm_paddr_t pa;
5741 	vm_pindex_t l2pindex;
5742 	int lvl;
5743 
5744 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5745 	KASSERT((va & L3C_OFFSET) == 0,
5746 	    ("pmap_enter_l3c: va is not aligned"));
5747 	KASSERT(!VA_IS_CLEANMAP(va) || (l3e & ATTR_SW_MANAGED) == 0,
5748 	    ("pmap_enter_l3c: managed mapping within the clean submap"));
5749 	KASSERT((l3e & ATTR_CONTIGUOUS) != 0,
5750 	    ("pmap_enter_l3c: l3e is missing ATTR_CONTIGUOUS"));
5751 
5752 	/*
5753 	 * If the L3 PTP is not resident, we attempt to create it here.
5754 	 */
5755 	if (!ADDR_IS_KERNEL(va)) {
5756 		/*
5757 		 * Were we given the correct L3 PTP?  If so, we can simply
5758 		 * increment its ref count.
5759 		 */
5760 		l2pindex = pmap_l2_pindex(va);
5761 		if (*ml3p != NULL && (*ml3p)->pindex == l2pindex) {
5762 			(*ml3p)->ref_count += L3C_ENTRIES;
5763 		} else {
5764 retry:
5765 			/*
5766 			 * Get the L2 entry.
5767 			 */
5768 			pde = pmap_pde(pmap, va, &lvl);
5769 
5770 			/*
5771 			 * If the L2 entry is a superpage, we either abort or
5772 			 * demote depending on the given flags.
5773 			 */
5774 			if (lvl == 1) {
5775 				l2p = pmap_l1_to_l2(pde, va);
5776 				if ((pmap_load(l2p) & ATTR_DESCR_MASK) ==
5777 				    L2_BLOCK) {
5778 					if ((flags & PMAP_ENTER_NOREPLACE) != 0)
5779 						return (KERN_FAILURE);
5780 					l3p = pmap_demote_l2_locked(pmap, l2p,
5781 					    va, lockp);
5782 					if (l3p != NULL) {
5783 						*ml3p = PTE_TO_VM_PAGE(
5784 						    pmap_load(l2p));
5785 						(*ml3p)->ref_count +=
5786 						    L3C_ENTRIES;
5787 						goto have_l3p;
5788 					}
5789 				}
5790 				/* We need to allocate an L3 PTP. */
5791 			}
5792 
5793 			/*
5794 			 * If the L3 PTP is mapped, we just increment its ref
5795 			 * count.  Otherwise, we attempt to allocate it.
5796 			 */
5797 			if (lvl == 2 && pmap_load(pde) != 0) {
5798 				*ml3p = PTE_TO_VM_PAGE(pmap_load(pde));
5799 				(*ml3p)->ref_count += L3C_ENTRIES;
5800 			} else {
5801 				*ml3p = _pmap_alloc_l3(pmap, l2pindex, (flags &
5802 				    PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp);
5803 				if (*ml3p == NULL) {
5804 					if ((flags & PMAP_ENTER_NOSLEEP) != 0)
5805 						return (KERN_FAILURE);
5806 
5807 					/*
5808 					 * The page table may have changed
5809 					 * while we slept.
5810 					 */
5811 					goto retry;
5812 				}
5813 				(*ml3p)->ref_count += L3C_ENTRIES - 1;
5814 			}
5815 		}
5816 		l3p = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(*ml3p));
5817 	} else {
5818 		*ml3p = NULL;
5819 
5820 		/*
5821 		 * If the L2 entry is a superpage, we either abort or demote
5822 		 * depending on the given flags.
5823 		 */
5824 		pde = pmap_pde(kernel_pmap, va, &lvl);
5825 		if (lvl == 1) {
5826 			l2p = pmap_l1_to_l2(pde, va);
5827 			KASSERT((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK,
5828 			    ("pmap_enter_l3c: missing L2 block"));
5829 			if ((flags & PMAP_ENTER_NOREPLACE) != 0)
5830 				return (KERN_FAILURE);
5831 			l3p = pmap_demote_l2_locked(pmap, l2p, va, lockp);
5832 		} else {
5833 			KASSERT(lvl == 2,
5834 			    ("pmap_enter_l3c: Invalid level %d", lvl));
5835 			l3p = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(
5836 			    pmap_load(pde)));
5837 		}
5838 	}
5839 have_l3p:
5840 	l3p = &l3p[pmap_l3_index(va)];
5841 
5842 	/*
5843 	 * If bti is not the same for the whole L3C range, return failure
5844 	 * and let vm_fault() cope.  Check after L3 allocation, since
5845 	 * it could sleep.
5846 	 */
5847 	if (!pmap_bti_same(pmap, va, va + L3C_SIZE, &l3e)) {
5848 		KASSERT(*ml3p != NULL, ("pmap_enter_l3c: missing L3 PTP"));
5849 		(*ml3p)->ref_count -= L3C_ENTRIES - 1;
5850 		pmap_abort_ptp(pmap, va, *ml3p);
5851 		*ml3p = NULL;
5852 		return (KERN_PROTECTION_FAILURE);
5853 	}
5854 
5855 	/*
5856 	 * If there are existing mappings, either abort or remove them.
5857 	 */
5858 	if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5859 		for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
5860 			if (pmap_load(tl3p) != 0) {
5861 				if (*ml3p != NULL)
5862 					(*ml3p)->ref_count -= L3C_ENTRIES;
5863 				return (KERN_FAILURE);
5864 			}
5865 		}
5866 	} else {
5867 		/*
5868 		 * Because we increment the L3 page's reference count above,
5869 		 * it is guaranteed not to be freed here and we can pass NULL
5870 		 * instead of a valid free list.
5871 		 */
5872 		pmap_remove_l3_range(pmap, pmap_load(pmap_l2(pmap, va)), va,
5873 		    va + L3C_SIZE, NULL, lockp);
5874 	}
5875 
5876 	/*
5877 	 * Enter on the PV list if part of our managed memory.
5878 	 */
5879 	if ((l3e & ATTR_SW_MANAGED) != 0) {
5880 		if (!pmap_pv_insert_l3c(pmap, va, m, lockp)) {
5881 			if (*ml3p != NULL) {
5882 				(*ml3p)->ref_count -= L3C_ENTRIES - 1;
5883 				pmap_abort_ptp(pmap, va, *ml3p);
5884 				*ml3p = NULL;
5885 			}
5886 			return (KERN_RESOURCE_SHORTAGE);
5887 		}
5888 		if ((l3e & ATTR_SW_DBM) != 0)
5889 			for (mt = m; mt < &m[L3C_ENTRIES]; mt++)
5890 				vm_page_aflag_set(mt, PGA_WRITEABLE);
5891 	}
5892 
5893 	/*
5894 	 * Increment counters.
5895 	 */
5896 	if ((l3e & ATTR_SW_WIRED) != 0)
5897 		pmap->pm_stats.wired_count += L3C_ENTRIES;
5898 	pmap_resident_count_inc(pmap, L3C_ENTRIES);
5899 
5900 	pa = VM_PAGE_TO_PHYS(m);
5901 	KASSERT((pa & L3C_OFFSET) == 0, ("pmap_enter_l3c: pa is not aligned"));
5902 
5903 	/*
5904 	 * Sync the icache before the mapping is stored.
5905 	 */
5906 	if ((l3e & ATTR_S1_XN) == 0 && pmap != kernel_pmap &&
5907 	    m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
5908 		cpu_icache_sync_range((void *)PHYS_TO_DMAP(pa), L3C_SIZE);
5909 
5910 	/*
5911 	 * Map the superpage.
5912 	 */
5913 	for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
5914 		pmap_store(tl3p, l3e);
5915 		l3e += L3_SIZE;
5916 	}
5917 	dsb(ishst);
5918 
5919 	counter_u64_add(pmap_l3c_mappings, 1);
5920 	CTR2(KTR_PMAP, "pmap_enter_l3c: success for va %#lx in pmap %p",
5921 	    va, pmap);
5922 	return (KERN_SUCCESS);
5923 }
5924 
5925 /*
5926  * Maps a sequence of resident pages belonging to the same object.
5927  * The sequence begins with the given page m_start.  This page is
5928  * mapped at the given virtual address start.  Each subsequent page is
5929  * mapped at a virtual address that is offset from start by the same
5930  * amount as the page is offset from m_start within the object.  The
5931  * last page in the sequence is the page with the largest offset from
5932  * m_start that can be mapped at a virtual address less than the given
5933  * virtual address end.  Not every virtual page between start and end
5934  * is mapped; only those for which a resident page exists with the
5935  * corresponding offset from m_start are mapped.
5936  */
5937 void
pmap_enter_object(pmap_t pmap,vm_offset_t start,vm_offset_t end,vm_page_t m_start,vm_prot_t prot)5938 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5939     vm_page_t m_start, vm_prot_t prot)
5940 {
5941 	struct rwlock *lock;
5942 	vm_offset_t va;
5943 	vm_page_t m, mpte;
5944 	vm_pindex_t diff, psize;
5945 	int rv;
5946 
5947 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
5948 
5949 	psize = atop(end - start);
5950 	mpte = NULL;
5951 	m = m_start;
5952 	lock = NULL;
5953 	PMAP_LOCK(pmap);
5954 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5955 		va = start + ptoa(diff);
5956 		if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
5957 		    m->psind == 2 && pmap_ps_enabled(pmap) &&
5958 		    ((rv = pmap_enter_l2_rx(pmap, va, m, prot, &lock)) ==
5959 		    KERN_SUCCESS || rv == KERN_NO_SPACE))
5960 			m = &m[L2_SIZE / PAGE_SIZE - 1];
5961 		else if ((va & L3C_OFFSET) == 0 && va + L3C_SIZE <= end &&
5962 		    m->psind >= 1 && pmap_ps_enabled(pmap) &&
5963 		    ((rv = pmap_enter_l3c_rx(pmap, va, m, &mpte, prot,
5964 		    &lock)) == KERN_SUCCESS || rv == KERN_NO_SPACE))
5965 			m = &m[L3C_ENTRIES - 1];
5966 		else {
5967 			/*
5968 			 * In general, if a superpage mapping were possible,
5969 			 * it would have been created above.  That said, if
5970 			 * start and end are not superpage aligned, then
5971 			 * promotion might be possible at the ends of [start,
5972 			 * end).  However, in practice, those promotion
5973 			 * attempts are so unlikely to succeed that they are
5974 			 * not worth trying.
5975 			 */
5976 			mpte = pmap_enter_quick_locked(pmap, va, m, prot |
5977 			    VM_PROT_NO_PROMOTE, mpte, &lock);
5978 		}
5979 		m = TAILQ_NEXT(m, listq);
5980 	}
5981 	if (lock != NULL)
5982 		rw_wunlock(lock);
5983 	PMAP_UNLOCK(pmap);
5984 }
5985 
5986 /*
5987  * this code makes some *MAJOR* assumptions:
5988  * 1. Current pmap & pmap exists.
5989  * 2. Not wired.
5990  * 3. Read access.
5991  * 4. No page table pages.
5992  * but is *MUCH* faster than pmap_enter...
5993  */
5994 
5995 void
pmap_enter_quick(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot)5996 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5997 {
5998 	struct rwlock *lock;
5999 
6000 	lock = NULL;
6001 	PMAP_LOCK(pmap);
6002 	(void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
6003 	if (lock != NULL)
6004 		rw_wunlock(lock);
6005 	PMAP_UNLOCK(pmap);
6006 }
6007 
6008 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)6009 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
6010     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
6011 {
6012 	pt_entry_t *l1, *l2, *l3, l3_val;
6013 	vm_paddr_t pa;
6014 	int full_lvl, lvl;
6015 
6016 	KASSERT(!VA_IS_CLEANMAP(va) ||
6017 	    (m->oflags & VPO_UNMANAGED) != 0,
6018 	    ("pmap_enter_quick_locked: managed mapping within the clean submap"));
6019 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6020 	PMAP_ASSERT_STAGE1(pmap);
6021 	KASSERT(ADDR_IS_CANONICAL(va),
6022 	    ("%s: Address not in canonical form: %lx", __func__, va));
6023 	l2 = NULL;
6024 
6025 	CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
6026 	/*
6027 	 * In the case that a page table page is not
6028 	 * resident, we are creating it here.
6029 	 */
6030 	if (!ADDR_IS_KERNEL(va)) {
6031 		vm_pindex_t l2pindex;
6032 
6033 		/*
6034 		 * Calculate pagetable page index
6035 		 */
6036 		l2pindex = pmap_l2_pindex(va);
6037 		if (mpte && (mpte->pindex == l2pindex)) {
6038 			mpte->ref_count++;
6039 		} else {
6040 			/*
6041 			 * If the page table page is mapped, we just increment
6042 			 * the hold count, and activate it.  Otherwise, we
6043 			 * attempt to allocate a page table page, passing NULL
6044 			 * instead of the PV list lock pointer because we don't
6045 			 * intend to sleep.  If this attempt fails, we don't
6046 			 * retry.  Instead, we give up.
6047 			 */
6048 			l1 = pmap_l1(pmap, va);
6049 			if (l1 != NULL && pmap_load(l1) != 0) {
6050 				if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
6051 				    L1_BLOCK)
6052 					return (NULL);
6053 				l2 = pmap_l1_to_l2(l1, va);
6054 				if (pmap_load(l2) != 0) {
6055 					if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
6056 					    L2_BLOCK)
6057 						return (NULL);
6058 					mpte = PTE_TO_VM_PAGE(pmap_load(l2));
6059 					mpte->ref_count++;
6060 				} else {
6061 					mpte = _pmap_alloc_l3(pmap, l2pindex,
6062 					    NULL);
6063 					if (mpte == NULL)
6064 						return (mpte);
6065 				}
6066 			} else {
6067 				mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
6068 				if (mpte == NULL)
6069 					return (mpte);
6070 			}
6071 		}
6072 		l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
6073 		l3 = &l3[pmap_l3_index(va)];
6074 	} else {
6075 		mpte = NULL;
6076 		l2 = pmap_pde(kernel_pmap, va, &lvl);
6077 		KASSERT(l2 != NULL,
6078 		    ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
6079 		     va));
6080 		KASSERT(lvl == 2,
6081 		    ("pmap_enter_quick_locked: Invalid level %d", lvl));
6082 		l3 = pmap_l2_to_l3(l2, va);
6083 	}
6084 
6085 	/*
6086 	 * Abort if a mapping already exists.
6087 	 */
6088 	if (pmap_load(l3) != 0) {
6089 		if (mpte != NULL)
6090 			mpte->ref_count--;
6091 		return (NULL);
6092 	}
6093 
6094 	/*
6095 	 * Enter on the PV list if part of our managed memory.
6096 	 */
6097 	if ((m->oflags & VPO_UNMANAGED) == 0 &&
6098 	    !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
6099 		if (mpte != NULL)
6100 			pmap_abort_ptp(pmap, va, mpte);
6101 		return (NULL);
6102 	}
6103 
6104 	/*
6105 	 * Increment counters
6106 	 */
6107 	pmap_resident_count_inc(pmap, 1);
6108 
6109 	pa = VM_PAGE_TO_PHYS(m);
6110 	l3_val = PHYS_TO_PTE(pa) | pmap_sh_attr |
6111 	    ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
6112 	l3_val |= pmap_pte_bti(pmap, va);
6113 	if ((prot & VM_PROT_EXECUTE) == 0 ||
6114 	    m->md.pv_memattr == VM_MEMATTR_DEVICE)
6115 		l3_val |= ATTR_S1_XN;
6116 	if (!ADDR_IS_KERNEL(va))
6117 		l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
6118 	else
6119 		l3_val |= ATTR_S1_UXN;
6120 	if (pmap != kernel_pmap)
6121 		l3_val |= ATTR_S1_nG;
6122 
6123 	/*
6124 	 * Now validate mapping with RO protection
6125 	 */
6126 	if ((m->oflags & VPO_UNMANAGED) == 0)
6127 		l3_val |= ATTR_SW_MANAGED;
6128 	else
6129 		l3_val |= ATTR_AF;
6130 
6131 	/* Sync icache before the mapping is stored to PTE */
6132 	if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
6133 	    m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
6134 		cpu_icache_sync_range((void *)PHYS_TO_DMAP(pa), PAGE_SIZE);
6135 
6136 	pmap_store(l3, l3_val);
6137 	dsb(ishst);
6138 
6139 #if VM_NRESERVLEVEL > 0
6140 	/*
6141 	 * First, attempt L3C promotion, if the virtual and physical addresses
6142 	 * are aligned with each other and an underlying reservation has the
6143 	 * neighboring L3 pages allocated.  The first condition is simply an
6144 	 * optimization that recognizes some eventual promotion failures early
6145 	 * at a lower run-time cost.  Then, attempt L2 promotion, if both a
6146 	 * level 1 reservation and the PTP are fully populated.
6147 	 */
6148 	if ((prot & VM_PROT_NO_PROMOTE) == 0 &&
6149 	    (va & L3C_OFFSET) == (pa & L3C_OFFSET) &&
6150 	    (m->flags & PG_FICTITIOUS) == 0 &&
6151 	    (full_lvl = vm_reserv_level_iffullpop(m)) >= 0 &&
6152 	    pmap_promote_l3c(pmap, l3, va) &&
6153 	    full_lvl == 1 && (mpte == NULL || mpte->ref_count == NL3PG)) {
6154 		if (l2 == NULL)
6155 			l2 = pmap_l2(pmap, va);
6156 
6157 		/*
6158 		 * If promotion succeeds, then the next call to this function
6159 		 * should not be given the unmapped PTP as a hint.
6160 		 */
6161 		if (pmap_promote_l2(pmap, l2, va, mpte, lockp))
6162 			mpte = NULL;
6163 	}
6164 #endif
6165 
6166 	return (mpte);
6167 }
6168 
6169 /*
6170  * This code maps large physical mmap regions into the
6171  * processor address space.  Note that some shortcuts
6172  * are taken, but the code works.
6173  */
6174 void
pmap_object_init_pt(pmap_t pmap,vm_offset_t addr,vm_object_t object,vm_pindex_t pindex,vm_size_t size)6175 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
6176     vm_pindex_t pindex, vm_size_t size)
6177 {
6178 
6179 	VM_OBJECT_ASSERT_WLOCKED(object);
6180 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
6181 	    ("pmap_object_init_pt: non-device object"));
6182 }
6183 
6184 /*
6185  *	Clear the wired attribute from the mappings for the specified range of
6186  *	addresses in the given pmap.  Every valid mapping within that range
6187  *	must have the wired attribute set.  In contrast, invalid mappings
6188  *	cannot have the wired attribute set, so they are ignored.
6189  *
6190  *	The wired attribute of the page table entry is not a hardware feature,
6191  *	so there is no need to invalidate any TLB entries.
6192  */
6193 void
pmap_unwire(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)6194 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6195 {
6196 	vm_offset_t va_next;
6197 	pd_entry_t *l0, *l1, *l2;
6198 	pt_entry_t *l3;
6199 	bool partial_l3c;
6200 
6201 	PMAP_LOCK(pmap);
6202 	for (; sva < eva; sva = va_next) {
6203 		l0 = pmap_l0(pmap, sva);
6204 		if (pmap_load(l0) == 0) {
6205 			va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6206 			if (va_next < sva)
6207 				va_next = eva;
6208 			continue;
6209 		}
6210 
6211 		l1 = pmap_l0_to_l1(l0, sva);
6212 		va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6213 		if (va_next < sva)
6214 			va_next = eva;
6215 		if (pmap_load(l1) == 0)
6216 			continue;
6217 
6218 		if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6219 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6220 			KASSERT(va_next <= eva,
6221 			    ("partial update of non-transparent 1G page "
6222 			    "l1 %#lx sva %#lx eva %#lx va_next %#lx",
6223 			    pmap_load(l1), sva, eva, va_next));
6224 			MPASS(pmap != kernel_pmap);
6225 			MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
6226 			    ATTR_SW_WIRED)) == ATTR_SW_WIRED);
6227 			pmap_clear_bits(l1, ATTR_SW_WIRED);
6228 			pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
6229 			continue;
6230 		}
6231 
6232 		va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6233 		if (va_next < sva)
6234 			va_next = eva;
6235 
6236 		l2 = pmap_l1_to_l2(l1, sva);
6237 		if (pmap_load(l2) == 0)
6238 			continue;
6239 
6240 		if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
6241 			if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
6242 				panic("pmap_unwire: l2 %#jx is missing "
6243 				    "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
6244 
6245 			/*
6246 			 * Are we unwiring the entire large page?  If not,
6247 			 * demote the mapping and fall through.
6248 			 */
6249 			if (sva + L2_SIZE == va_next && eva >= va_next) {
6250 				pmap_clear_bits(l2, ATTR_SW_WIRED);
6251 				pmap->pm_stats.wired_count -= L2_SIZE /
6252 				    PAGE_SIZE;
6253 				continue;
6254 			} else if (pmap_demote_l2(pmap, l2, sva) == NULL)
6255 				panic("pmap_unwire: demotion failed");
6256 		}
6257 		KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6258 		    ("pmap_unwire: Invalid l2 entry after demotion"));
6259 
6260 		if (va_next > eva)
6261 			va_next = eva;
6262 		for (partial_l3c = true, l3 = pmap_l2_to_l3(l2, sva);
6263 		    sva != va_next; l3++, sva += L3_SIZE) {
6264 			if (pmap_load(l3) == 0)
6265 				continue;
6266 			if ((pmap_load(l3) & ATTR_CONTIGUOUS) != 0) {
6267 				/*
6268 				 * Avoid demotion for whole-page unwiring.
6269 				 */
6270 				if ((sva & L3C_OFFSET) == 0) {
6271 					/*
6272 					 * Handle the possibility that
6273 					 * "va_next" is zero because of
6274 					 * address wraparound.
6275 					 */
6276 					partial_l3c = sva + L3C_OFFSET >
6277 					    va_next - 1;
6278 				}
6279 				if (partial_l3c)
6280 					(void)pmap_demote_l3c(pmap, l3, sva);
6281 			}
6282 			if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
6283 				panic("pmap_unwire: l3 %#jx is missing "
6284 				    "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
6285 
6286 			/*
6287 			 * ATTR_SW_WIRED must be cleared atomically.  Although
6288 			 * the pmap lock synchronizes access to ATTR_SW_WIRED,
6289 			 * the System MMU may write to the entry concurrently.
6290 			 */
6291 			pmap_clear_bits(l3, ATTR_SW_WIRED);
6292 			pmap->pm_stats.wired_count--;
6293 		}
6294 	}
6295 	PMAP_UNLOCK(pmap);
6296 }
6297 
6298 /*
6299  * This function requires that the caller has already added one to ml3's
6300  * ref_count in anticipation of creating a 4KB page mapping.
6301  */
6302 static bool
pmap_copy_l3c(pmap_t pmap,pt_entry_t * l3p,vm_offset_t va,pt_entry_t l3e,vm_page_t ml3,struct rwlock ** lockp)6303 pmap_copy_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va, pt_entry_t l3e,
6304     vm_page_t ml3, struct rwlock **lockp)
6305 {
6306 	pt_entry_t *tl3p;
6307 
6308 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6309 	KASSERT((va & L3C_OFFSET) == 0,
6310 	    ("pmap_copy_l3c: va is not aligned"));
6311 	KASSERT((l3e & ATTR_SW_MANAGED) != 0,
6312 	    ("pmap_copy_l3c: l3e is not managed"));
6313 
6314 	/*
6315 	 * Abort if a mapping already exists.
6316 	 */
6317 	for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++)
6318 		if (pmap_load(tl3p) != 0) {
6319 			if (ml3 != NULL)
6320 				ml3->ref_count--;
6321 			return (false);
6322 		}
6323 
6324 	if (!pmap_pv_insert_l3c(pmap, va, PTE_TO_VM_PAGE(l3e), lockp)) {
6325 		if (ml3 != NULL)
6326 			pmap_abort_ptp(pmap, va, ml3);
6327 		return (false);
6328 	}
6329 	ml3->ref_count += L3C_ENTRIES - 1;
6330 
6331 	/*
6332 	 * Clear the wired and accessed bits.  However, leave the dirty bit
6333 	 * unchanged because read/write superpage mappings are required to be
6334 	 * dirty.
6335 	 */
6336 	l3e &= ~(ATTR_SW_WIRED | ATTR_AF);
6337 
6338 	for (tl3p = l3p; tl3p < &l3p[L3C_ENTRIES]; tl3p++) {
6339 		pmap_store(tl3p, l3e);
6340 		l3e += L3_SIZE;
6341 	}
6342 	pmap_resident_count_inc(pmap, L3C_ENTRIES);
6343 	counter_u64_add(pmap_l3c_mappings, 1);
6344 	CTR2(KTR_PMAP, "pmap_copy_l3c: success for va %#lx in pmap %p",
6345 	    va, pmap);
6346 	return (true);
6347 }
6348 
6349 /*
6350  *	Copy the range specified by src_addr/len
6351  *	from the source map to the range dst_addr/len
6352  *	in the destination map.
6353  *
6354  *	This routine is only advisory and need not do anything.
6355  *
6356  *	Because the executable mappings created by this routine are copied,
6357  *	it should not have to flush the instruction cache.
6358  */
6359 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)6360 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
6361     vm_offset_t src_addr)
6362 {
6363 	struct rwlock *lock;
6364 	pd_entry_t *l0, *l1, *l2, srcptepaddr;
6365 	pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
6366 	vm_offset_t addr, end_addr, va_next;
6367 	vm_page_t dst_m, dstmpte, srcmpte;
6368 
6369 	PMAP_ASSERT_STAGE1(dst_pmap);
6370 	PMAP_ASSERT_STAGE1(src_pmap);
6371 
6372 	if (dst_addr != src_addr)
6373 		return;
6374 	end_addr = src_addr + len;
6375 	lock = NULL;
6376 	if (dst_pmap < src_pmap) {
6377 		PMAP_LOCK(dst_pmap);
6378 		PMAP_LOCK(src_pmap);
6379 	} else {
6380 		PMAP_LOCK(src_pmap);
6381 		PMAP_LOCK(dst_pmap);
6382 	}
6383 	for (addr = src_addr; addr < end_addr; addr = va_next) {
6384 		l0 = pmap_l0(src_pmap, addr);
6385 		if (pmap_load(l0) == 0) {
6386 			va_next = (addr + L0_SIZE) & ~L0_OFFSET;
6387 			if (va_next < addr)
6388 				va_next = end_addr;
6389 			continue;
6390 		}
6391 
6392 		va_next = (addr + L1_SIZE) & ~L1_OFFSET;
6393 		if (va_next < addr)
6394 			va_next = end_addr;
6395 		l1 = pmap_l0_to_l1(l0, addr);
6396 		if (pmap_load(l1) == 0)
6397 			continue;
6398 		if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6399 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6400 			KASSERT(va_next <= end_addr,
6401 			    ("partial update of non-transparent 1G page "
6402 			    "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
6403 			    pmap_load(l1), addr, end_addr, va_next));
6404 			srcptepaddr = pmap_load(l1);
6405 			l1 = pmap_l1(dst_pmap, addr);
6406 			if (l1 == NULL) {
6407 				if (_pmap_alloc_l3(dst_pmap,
6408 				    pmap_l0_pindex(addr), NULL) == NULL)
6409 					break;
6410 				l1 = pmap_l1(dst_pmap, addr);
6411 			} else {
6412 				l0 = pmap_l0(dst_pmap, addr);
6413 				dst_m = PTE_TO_VM_PAGE(pmap_load(l0));
6414 				dst_m->ref_count++;
6415 			}
6416 			KASSERT(pmap_load(l1) == 0,
6417 			    ("1G mapping present in dst pmap "
6418 			    "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
6419 			    pmap_load(l1), addr, end_addr, va_next));
6420 			pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
6421 			pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
6422 			continue;
6423 		}
6424 
6425 		va_next = (addr + L2_SIZE) & ~L2_OFFSET;
6426 		if (va_next < addr)
6427 			va_next = end_addr;
6428 		l2 = pmap_l1_to_l2(l1, addr);
6429 		srcptepaddr = pmap_load(l2);
6430 		if (srcptepaddr == 0)
6431 			continue;
6432 		if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
6433 			/*
6434 			 * We can only virtual copy whole superpages.
6435 			 */
6436 			if ((addr & L2_OFFSET) != 0 ||
6437 			    addr + L2_SIZE > end_addr)
6438 				continue;
6439 			l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
6440 			if (l2 == NULL)
6441 				break;
6442 			if (pmap_load(l2) == 0 &&
6443 			    ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
6444 			    pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
6445 			    PMAP_ENTER_NORECLAIM, &lock))) {
6446 				/*
6447 				 * We leave the dirty bit unchanged because
6448 				 * managed read/write superpage mappings are
6449 				 * required to be dirty.  However, managed
6450 				 * superpage mappings are not required to
6451 				 * have their accessed bit set, so we clear
6452 				 * it because we don't know if this mapping
6453 				 * will be used.
6454 				 */
6455 				srcptepaddr &= ~ATTR_SW_WIRED;
6456 				if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
6457 					srcptepaddr &= ~ATTR_AF;
6458 				pmap_store(l2, srcptepaddr);
6459 				pmap_resident_count_inc(dst_pmap, L2_SIZE /
6460 				    PAGE_SIZE);
6461 				atomic_add_long(&pmap_l2_mappings, 1);
6462 			} else
6463 				pmap_abort_ptp(dst_pmap, addr, dst_m);
6464 			continue;
6465 		}
6466 		KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
6467 		    ("pmap_copy: invalid L2 entry"));
6468 		srcmpte = PTE_TO_VM_PAGE(srcptepaddr);
6469 		KASSERT(srcmpte->ref_count > 0,
6470 		    ("pmap_copy: source page table page is unused"));
6471 		if (va_next > end_addr)
6472 			va_next = end_addr;
6473 		src_pte = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(srcptepaddr));
6474 		src_pte = &src_pte[pmap_l3_index(addr)];
6475 		dstmpte = NULL;
6476 		for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
6477 			ptetemp = pmap_load(src_pte);
6478 
6479 			/*
6480 			 * We only virtual copy managed pages.
6481 			 */
6482 			if ((ptetemp & ATTR_SW_MANAGED) == 0)
6483 				continue;
6484 
6485 			if (dstmpte != NULL) {
6486 				KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
6487 				    ("dstmpte pindex/addr mismatch"));
6488 				dstmpte->ref_count++;
6489 			} else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
6490 			    NULL)) == NULL)
6491 				goto out;
6492 			dst_pte = (pt_entry_t *)
6493 			    PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
6494 			dst_pte = &dst_pte[pmap_l3_index(addr)];
6495 			if ((ptetemp & ATTR_CONTIGUOUS) != 0 && (addr &
6496 			    L3C_OFFSET) == 0 && addr + L3C_OFFSET <=
6497 			    va_next - 1) {
6498 				if (!pmap_copy_l3c(dst_pmap, dst_pte, addr,
6499 				    ptetemp, dstmpte, &lock))
6500 					goto out;
6501 				addr += L3C_SIZE - PAGE_SIZE;
6502 				src_pte += L3C_ENTRIES - 1;
6503 			} else if (pmap_load(dst_pte) == 0 &&
6504 			    pmap_try_insert_pv_entry(dst_pmap, addr,
6505 			    PTE_TO_VM_PAGE(ptetemp), &lock)) {
6506 				/*
6507 				 * Clear the wired, contiguous, modified, and
6508 				 * accessed bits from the destination PTE.
6509 				 * The contiguous bit is cleared because we
6510 				 * are not copying the entire L3C superpage.
6511 				 */
6512 				mask = ATTR_SW_WIRED | ATTR_CONTIGUOUS |
6513 				    ATTR_AF;
6514 				nbits = 0;
6515 				if ((ptetemp & ATTR_SW_DBM) != 0)
6516 					nbits |= ATTR_S1_AP_RW_BIT;
6517 				pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
6518 				pmap_resident_count_inc(dst_pmap, 1);
6519 			} else {
6520 				pmap_abort_ptp(dst_pmap, addr, dstmpte);
6521 				goto out;
6522 			}
6523 			/* Have we copied all of the valid mappings? */
6524 			if (dstmpte->ref_count >= srcmpte->ref_count)
6525 				break;
6526 		}
6527 	}
6528 out:
6529 	/*
6530 	 * XXX This barrier may not be needed because the destination pmap is
6531 	 * not active.
6532 	 */
6533 	dsb(ishst);
6534 
6535 	if (lock != NULL)
6536 		rw_wunlock(lock);
6537 	PMAP_UNLOCK(src_pmap);
6538 	PMAP_UNLOCK(dst_pmap);
6539 }
6540 
6541 int
pmap_vmspace_copy(pmap_t dst_pmap,pmap_t src_pmap)6542 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
6543 {
6544 	int error;
6545 
6546 	if (dst_pmap->pm_stage != src_pmap->pm_stage)
6547 		return (EINVAL);
6548 
6549 	if (dst_pmap->pm_stage != PM_STAGE1 || src_pmap->pm_bti == NULL)
6550 		return (0);
6551 
6552 	for (;;) {
6553 		if (dst_pmap < src_pmap) {
6554 			PMAP_LOCK(dst_pmap);
6555 			PMAP_LOCK(src_pmap);
6556 		} else {
6557 			PMAP_LOCK(src_pmap);
6558 			PMAP_LOCK(dst_pmap);
6559 		}
6560 		error = pmap_bti_copy(dst_pmap, src_pmap);
6561 		/* Clean up partial copy on failure due to no memory. */
6562 		if (error == ENOMEM)
6563 			pmap_bti_deassign_all(dst_pmap);
6564 		PMAP_UNLOCK(src_pmap);
6565 		PMAP_UNLOCK(dst_pmap);
6566 		if (error != ENOMEM)
6567 			break;
6568 		vm_wait(NULL);
6569 	}
6570 	return (error);
6571 }
6572 
6573 /*
6574  *	pmap_zero_page zeros the specified hardware page by mapping
6575  *	the page into KVM and using bzero to clear its contents.
6576  */
6577 void
pmap_zero_page(vm_page_t m)6578 pmap_zero_page(vm_page_t m)
6579 {
6580 	vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
6581 
6582 	pagezero((void *)va);
6583 }
6584 
6585 /*
6586  *	pmap_zero_page_area zeros the specified hardware page by mapping
6587  *	the page into KVM and using bzero to clear its contents.
6588  *
6589  *	off and size may not cover an area beyond a single hardware page.
6590  */
6591 void
pmap_zero_page_area(vm_page_t m,int off,int size)6592 pmap_zero_page_area(vm_page_t m, int off, int size)
6593 {
6594 	vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
6595 
6596 	if (off == 0 && size == PAGE_SIZE)
6597 		pagezero((void *)va);
6598 	else
6599 		bzero((char *)va + off, size);
6600 }
6601 
6602 /*
6603  *	pmap_copy_page copies the specified (machine independent)
6604  *	page by mapping the page into virtual memory and using
6605  *	bcopy to copy the page, one machine dependent page at a
6606  *	time.
6607  */
6608 void
pmap_copy_page(vm_page_t msrc,vm_page_t mdst)6609 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
6610 {
6611 	vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
6612 	vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
6613 
6614 	pagecopy((void *)src, (void *)dst);
6615 }
6616 
6617 int unmapped_buf_allowed = 1;
6618 
6619 void
pmap_copy_pages(vm_page_t ma[],vm_offset_t a_offset,vm_page_t mb[],vm_offset_t b_offset,int xfersize)6620 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
6621     vm_offset_t b_offset, int xfersize)
6622 {
6623 	void *a_cp, *b_cp;
6624 	vm_page_t m_a, m_b;
6625 	vm_paddr_t p_a, p_b;
6626 	vm_offset_t a_pg_offset, b_pg_offset;
6627 	int cnt;
6628 
6629 	while (xfersize > 0) {
6630 		a_pg_offset = a_offset & PAGE_MASK;
6631 		m_a = ma[a_offset >> PAGE_SHIFT];
6632 		p_a = m_a->phys_addr;
6633 		b_pg_offset = b_offset & PAGE_MASK;
6634 		m_b = mb[b_offset >> PAGE_SHIFT];
6635 		p_b = m_b->phys_addr;
6636 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
6637 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
6638 		if (__predict_false(!PHYS_IN_DMAP(p_a))) {
6639 			panic("!DMAP a %lx", p_a);
6640 		} else {
6641 			a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
6642 		}
6643 		if (__predict_false(!PHYS_IN_DMAP(p_b))) {
6644 			panic("!DMAP b %lx", p_b);
6645 		} else {
6646 			b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
6647 		}
6648 		bcopy(a_cp, b_cp, cnt);
6649 		a_offset += cnt;
6650 		b_offset += cnt;
6651 		xfersize -= cnt;
6652 	}
6653 }
6654 
6655 vm_offset_t
pmap_quick_enter_page(vm_page_t m)6656 pmap_quick_enter_page(vm_page_t m)
6657 {
6658 
6659 	return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
6660 }
6661 
6662 void
pmap_quick_remove_page(vm_offset_t addr)6663 pmap_quick_remove_page(vm_offset_t addr)
6664 {
6665 }
6666 
6667 /*
6668  * Returns true if the pmap's pv is one of the first
6669  * 16 pvs linked to from this page.  This count may
6670  * be changed upwards or downwards in the future; it
6671  * is only necessary that true be returned for a small
6672  * subset of pmaps for proper page aging.
6673  */
6674 bool
pmap_page_exists_quick(pmap_t pmap,vm_page_t m)6675 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
6676 {
6677 	struct md_page *pvh;
6678 	struct rwlock *lock;
6679 	pv_entry_t pv;
6680 	int loops = 0;
6681 	bool rv;
6682 
6683 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6684 	    ("pmap_page_exists_quick: page %p is not managed", m));
6685 	rv = false;
6686 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6687 	rw_rlock(lock);
6688 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6689 		if (PV_PMAP(pv) == pmap) {
6690 			rv = true;
6691 			break;
6692 		}
6693 		loops++;
6694 		if (loops >= 16)
6695 			break;
6696 	}
6697 	if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
6698 		pvh = page_to_pvh(m);
6699 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6700 			if (PV_PMAP(pv) == pmap) {
6701 				rv = true;
6702 				break;
6703 			}
6704 			loops++;
6705 			if (loops >= 16)
6706 				break;
6707 		}
6708 	}
6709 	rw_runlock(lock);
6710 	return (rv);
6711 }
6712 
6713 /*
6714  *	pmap_page_wired_mappings:
6715  *
6716  *	Return the number of managed mappings to the given physical page
6717  *	that are wired.
6718  */
6719 int
pmap_page_wired_mappings(vm_page_t m)6720 pmap_page_wired_mappings(vm_page_t m)
6721 {
6722 	struct rwlock *lock;
6723 	struct md_page *pvh;
6724 	pmap_t pmap;
6725 	pt_entry_t *pte;
6726 	pv_entry_t pv;
6727 	int count, md_gen, pvh_gen;
6728 
6729 	if ((m->oflags & VPO_UNMANAGED) != 0)
6730 		return (0);
6731 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6732 	rw_rlock(lock);
6733 restart:
6734 	count = 0;
6735 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6736 		pmap = PV_PMAP(pv);
6737 		if (!PMAP_TRYLOCK(pmap)) {
6738 			md_gen = m->md.pv_gen;
6739 			rw_runlock(lock);
6740 			PMAP_LOCK(pmap);
6741 			rw_rlock(lock);
6742 			if (md_gen != m->md.pv_gen) {
6743 				PMAP_UNLOCK(pmap);
6744 				goto restart;
6745 			}
6746 		}
6747 		pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6748 		if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
6749 			count++;
6750 		PMAP_UNLOCK(pmap);
6751 	}
6752 	if ((m->flags & PG_FICTITIOUS) == 0) {
6753 		pvh = page_to_pvh(m);
6754 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6755 			pmap = PV_PMAP(pv);
6756 			if (!PMAP_TRYLOCK(pmap)) {
6757 				md_gen = m->md.pv_gen;
6758 				pvh_gen = pvh->pv_gen;
6759 				rw_runlock(lock);
6760 				PMAP_LOCK(pmap);
6761 				rw_rlock(lock);
6762 				if (md_gen != m->md.pv_gen ||
6763 				    pvh_gen != pvh->pv_gen) {
6764 					PMAP_UNLOCK(pmap);
6765 					goto restart;
6766 				}
6767 			}
6768 			pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
6769 			if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
6770 				count++;
6771 			PMAP_UNLOCK(pmap);
6772 		}
6773 	}
6774 	rw_runlock(lock);
6775 	return (count);
6776 }
6777 
6778 /*
6779  * Returns true if the given page is mapped individually or as part of
6780  * a 2mpage.  Otherwise, returns false.
6781  */
6782 bool
pmap_page_is_mapped(vm_page_t m)6783 pmap_page_is_mapped(vm_page_t m)
6784 {
6785 	struct rwlock *lock;
6786 	bool rv;
6787 
6788 	if ((m->oflags & VPO_UNMANAGED) != 0)
6789 		return (false);
6790 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6791 	rw_rlock(lock);
6792 	rv = !TAILQ_EMPTY(&m->md.pv_list) ||
6793 	    ((m->flags & PG_FICTITIOUS) == 0 &&
6794 	    !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
6795 	rw_runlock(lock);
6796 	return (rv);
6797 }
6798 
6799 /*
6800  * Destroy all managed, non-wired mappings in the given user-space
6801  * pmap.  This pmap cannot be active on any processor besides the
6802  * caller.
6803  *
6804  * This function cannot be applied to the kernel pmap.  Moreover, it
6805  * is not intended for general use.  It is only to be used during
6806  * process termination.  Consequently, it can be implemented in ways
6807  * that make it faster than pmap_remove().  First, it can more quickly
6808  * destroy mappings by iterating over the pmap's collection of PV
6809  * entries, rather than searching the page table.  Second, it doesn't
6810  * have to test and clear the page table entries atomically, because
6811  * no processor is currently accessing the user address space.  In
6812  * particular, a page table entry's dirty bit won't change state once
6813  * this function starts.
6814  */
6815 void
pmap_remove_pages(pmap_t pmap)6816 pmap_remove_pages(pmap_t pmap)
6817 {
6818 	pd_entry_t *pde;
6819 	pt_entry_t *pte, tpte;
6820 	struct spglist free;
6821 	struct pv_chunklist free_chunks[PMAP_MEMDOM];
6822 	vm_page_t m, ml3, mt;
6823 	pv_entry_t pv;
6824 	struct md_page *pvh;
6825 	struct pv_chunk *pc, *npc;
6826 	struct rwlock *lock;
6827 	int64_t bit;
6828 	uint64_t inuse, bitmask;
6829 	int allfree, field, i, idx, lvl;
6830 	int freed __pvused;
6831 	vm_paddr_t pa;
6832 
6833 	lock = NULL;
6834 
6835 	for (i = 0; i < PMAP_MEMDOM; i++)
6836 		TAILQ_INIT(&free_chunks[i]);
6837 	SLIST_INIT(&free);
6838 	PMAP_LOCK(pmap);
6839 	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
6840 		allfree = 1;
6841 		freed = 0;
6842 		for (field = 0; field < _NPCM; field++) {
6843 			inuse = ~pc->pc_map[field] & pc_freemask[field];
6844 			while (inuse != 0) {
6845 				bit = ffsl(inuse) - 1;
6846 				bitmask = 1UL << bit;
6847 				idx = field * 64 + bit;
6848 				pv = &pc->pc_pventry[idx];
6849 				inuse &= ~bitmask;
6850 
6851 				pde = pmap_pde(pmap, pv->pv_va, &lvl);
6852 				KASSERT(pde != NULL,
6853 				    ("Attempting to remove an unmapped page"));
6854 
6855 				switch(lvl) {
6856 				case 1:
6857 					pte = pmap_l1_to_l2(pde, pv->pv_va);
6858 					tpte = pmap_load(pte);
6859 					KASSERT((tpte & ATTR_DESCR_MASK) ==
6860 					    L2_BLOCK,
6861 					    ("Attempting to remove an invalid "
6862 					    "block: %lx", tpte));
6863 					break;
6864 				case 2:
6865 					pte = pmap_l2_to_l3(pde, pv->pv_va);
6866 					tpte = pmap_load(pte);
6867 					KASSERT((tpte & ATTR_DESCR_MASK) ==
6868 					    L3_PAGE,
6869 					    ("Attempting to remove an invalid "
6870 					     "page: %lx", tpte));
6871 					break;
6872 				default:
6873 					panic(
6874 					    "Invalid page directory level: %d",
6875 					    lvl);
6876 				}
6877 
6878 				/*
6879 				 * We cannot remove wired mappings at this time.
6880 				 *
6881 				 * For L3C superpages, all of the constituent PTEs
6882 				 * should have the wired bit set, so we don't
6883 				 * check for ATTR_CONTIGUOUS here.
6884 				 */
6885 				if (tpte & ATTR_SW_WIRED) {
6886 					allfree = 0;
6887 					continue;
6888 				}
6889 
6890 				/* Mark free */
6891 				pc->pc_map[field] |= bitmask;
6892 
6893 				/*
6894 				 * Because this pmap is not active on other
6895 				 * processors, the dirty bit cannot have
6896 				 * changed state since we last loaded pte.
6897 				 */
6898 				pmap_clear(pte);
6899 
6900 				pa = PTE_TO_PHYS(tpte);
6901 
6902 				m = PHYS_TO_VM_PAGE(pa);
6903 				KASSERT(m->phys_addr == pa,
6904 				    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6905 				    m, (uintmax_t)m->phys_addr,
6906 				    (uintmax_t)tpte));
6907 
6908 				KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6909 				    m < &vm_page_array[vm_page_array_size],
6910 				    ("pmap_remove_pages: bad pte %#jx",
6911 				    (uintmax_t)tpte));
6912 
6913 				/*
6914 				 * Update the vm_page_t clean/reference bits.
6915 				 *
6916 				 * We don't check for ATTR_CONTIGUOUS here
6917 				 * because writeable L3C superpages are expected
6918 				 * to be dirty, i.e., every constituent PTE
6919 				 * should be dirty.
6920 				 */
6921 				if (pmap_pte_dirty(pmap, tpte)) {
6922 					switch (lvl) {
6923 					case 1:
6924 						for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
6925 							vm_page_dirty(mt);
6926 						break;
6927 					case 2:
6928 						vm_page_dirty(m);
6929 						break;
6930 					}
6931 				}
6932 
6933 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6934 
6935 				switch (lvl) {
6936 				case 1:
6937 					pmap_resident_count_dec(pmap,
6938 					    L2_SIZE / PAGE_SIZE);
6939 					pvh = page_to_pvh(m);
6940 					TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
6941 					pvh->pv_gen++;
6942 					if (TAILQ_EMPTY(&pvh->pv_list)) {
6943 						for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
6944 							if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
6945 							    TAILQ_EMPTY(&mt->md.pv_list))
6946 								vm_page_aflag_clear(mt, PGA_WRITEABLE);
6947 					}
6948 					ml3 = pmap_remove_pt_page(pmap,
6949 					    pv->pv_va);
6950 					if (ml3 != NULL) {
6951 						KASSERT(vm_page_any_valid(ml3),
6952 						    ("pmap_remove_pages: l3 page not promoted"));
6953 						pmap_resident_count_dec(pmap,1);
6954 						KASSERT(ml3->ref_count == NL3PG,
6955 						    ("pmap_remove_pages: l3 page ref count error"));
6956 						ml3->ref_count = 0;
6957 						pmap_add_delayed_free_list(ml3,
6958 						    &free, false);
6959 					}
6960 					break;
6961 				case 2:
6962 					pmap_resident_count_dec(pmap, 1);
6963 					TAILQ_REMOVE(&m->md.pv_list, pv,
6964 					    pv_next);
6965 					m->md.pv_gen++;
6966 					if ((m->a.flags & PGA_WRITEABLE) != 0 &&
6967 					    TAILQ_EMPTY(&m->md.pv_list) &&
6968 					    (m->flags & PG_FICTITIOUS) == 0) {
6969 						pvh = page_to_pvh(m);
6970 						if (TAILQ_EMPTY(&pvh->pv_list))
6971 							vm_page_aflag_clear(m,
6972 							    PGA_WRITEABLE);
6973 					}
6974 					break;
6975 				}
6976 				pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
6977 				    &free);
6978 				freed++;
6979 			}
6980 		}
6981 		PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6982 		PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6983 		PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6984 		if (allfree) {
6985 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6986 			TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
6987 			    pc_list);
6988 		}
6989 	}
6990 	if (lock != NULL)
6991 		rw_wunlock(lock);
6992 	pmap_invalidate_all(pmap);
6993 	pmap_bti_deassign_all(pmap);
6994 	free_pv_chunk_batch(free_chunks);
6995 	PMAP_UNLOCK(pmap);
6996 	vm_page_free_pages_toq(&free, true);
6997 }
6998 
6999 /*
7000  * This is used to check if a page has been accessed or modified.
7001  */
7002 static bool
pmap_page_test_mappings(vm_page_t m,bool accessed,bool modified)7003 pmap_page_test_mappings(vm_page_t m, bool accessed, bool modified)
7004 {
7005 	struct rwlock *lock;
7006 	pv_entry_t pv;
7007 	struct md_page *pvh;
7008 	pt_entry_t l3e, mask, *pte, value;
7009 	pmap_t pmap;
7010 	int md_gen, pvh_gen;
7011 	bool rv;
7012 
7013 	rv = false;
7014 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7015 	rw_rlock(lock);
7016 restart:
7017 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7018 		pmap = PV_PMAP(pv);
7019 		PMAP_ASSERT_STAGE1(pmap);
7020 		if (!PMAP_TRYLOCK(pmap)) {
7021 			md_gen = m->md.pv_gen;
7022 			rw_runlock(lock);
7023 			PMAP_LOCK(pmap);
7024 			rw_rlock(lock);
7025 			if (md_gen != m->md.pv_gen) {
7026 				PMAP_UNLOCK(pmap);
7027 				goto restart;
7028 			}
7029 		}
7030 		pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
7031 		mask = 0;
7032 		value = 0;
7033 		if (modified) {
7034 			mask |= ATTR_S1_AP_RW_BIT;
7035 			value |= ATTR_S1_AP(ATTR_S1_AP_RW);
7036 		}
7037 		if (accessed) {
7038 			mask |= ATTR_AF | ATTR_DESCR_MASK;
7039 			value |= ATTR_AF | L3_PAGE;
7040 		}
7041 		l3e = pmap_load(pte);
7042 		if ((l3e & ATTR_CONTIGUOUS) != 0)
7043 			l3e = pmap_load_l3c(pte);
7044 		PMAP_UNLOCK(pmap);
7045 		rv = (l3e & mask) == value;
7046 		if (rv)
7047 			goto out;
7048 	}
7049 	if ((m->flags & PG_FICTITIOUS) == 0) {
7050 		pvh = page_to_pvh(m);
7051 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
7052 			pmap = PV_PMAP(pv);
7053 			PMAP_ASSERT_STAGE1(pmap);
7054 			if (!PMAP_TRYLOCK(pmap)) {
7055 				md_gen = m->md.pv_gen;
7056 				pvh_gen = pvh->pv_gen;
7057 				rw_runlock(lock);
7058 				PMAP_LOCK(pmap);
7059 				rw_rlock(lock);
7060 				if (md_gen != m->md.pv_gen ||
7061 				    pvh_gen != pvh->pv_gen) {
7062 					PMAP_UNLOCK(pmap);
7063 					goto restart;
7064 				}
7065 			}
7066 			pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
7067 			mask = 0;
7068 			value = 0;
7069 			if (modified) {
7070 				mask |= ATTR_S1_AP_RW_BIT;
7071 				value |= ATTR_S1_AP(ATTR_S1_AP_RW);
7072 			}
7073 			if (accessed) {
7074 				mask |= ATTR_AF | ATTR_DESCR_MASK;
7075 				value |= ATTR_AF | L2_BLOCK;
7076 			}
7077 			rv = (pmap_load(pte) & mask) == value;
7078 			PMAP_UNLOCK(pmap);
7079 			if (rv)
7080 				goto out;
7081 		}
7082 	}
7083 out:
7084 	rw_runlock(lock);
7085 	return (rv);
7086 }
7087 
7088 /*
7089  *	pmap_is_modified:
7090  *
7091  *	Return whether or not the specified physical page was modified
7092  *	in any physical maps.
7093  */
7094 bool
pmap_is_modified(vm_page_t m)7095 pmap_is_modified(vm_page_t m)
7096 {
7097 
7098 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7099 	    ("pmap_is_modified: page %p is not managed", m));
7100 
7101 	/*
7102 	 * If the page is not busied then this check is racy.
7103 	 */
7104 	if (!pmap_page_is_write_mapped(m))
7105 		return (false);
7106 	return (pmap_page_test_mappings(m, false, true));
7107 }
7108 
7109 /*
7110  *	pmap_is_prefaultable:
7111  *
7112  *	Return whether or not the specified virtual address is eligible
7113  *	for prefault.
7114  */
7115 bool
pmap_is_prefaultable(pmap_t pmap,vm_offset_t addr)7116 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
7117 {
7118 	pd_entry_t *pde;
7119 	pt_entry_t *pte;
7120 	bool rv;
7121 	int lvl;
7122 
7123 	/*
7124 	 * Return true if and only if the L3 entry for the specified virtual
7125 	 * address is allocated but invalid.
7126 	 */
7127 	rv = false;
7128 	PMAP_LOCK(pmap);
7129 	pde = pmap_pde(pmap, addr, &lvl);
7130 	if (pde != NULL && lvl == 2) {
7131 		pte = pmap_l2_to_l3(pde, addr);
7132 		rv = pmap_load(pte) == 0;
7133 	}
7134 	PMAP_UNLOCK(pmap);
7135 	return (rv);
7136 }
7137 
7138 /*
7139  *	pmap_is_referenced:
7140  *
7141  *	Return whether or not the specified physical page was referenced
7142  *	in any physical maps.
7143  */
7144 bool
pmap_is_referenced(vm_page_t m)7145 pmap_is_referenced(vm_page_t m)
7146 {
7147 
7148 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7149 	    ("pmap_is_referenced: page %p is not managed", m));
7150 	return (pmap_page_test_mappings(m, true, false));
7151 }
7152 
7153 /*
7154  * Clear the write and modified bits in each of the given page's mappings.
7155  */
7156 void
pmap_remove_write(vm_page_t m)7157 pmap_remove_write(vm_page_t m)
7158 {
7159 	struct md_page *pvh;
7160 	pmap_t pmap;
7161 	struct rwlock *lock;
7162 	pv_entry_t next_pv, pv;
7163 	pt_entry_t oldpte, *pte, set, clear, mask, val;
7164 	vm_offset_t va;
7165 	int md_gen, pvh_gen;
7166 
7167 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7168 	    ("pmap_remove_write: page %p is not managed", m));
7169 	vm_page_assert_busied(m);
7170 
7171 	if (!pmap_page_is_write_mapped(m))
7172 		return;
7173 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7174 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
7175 	rw_wlock(lock);
7176 retry:
7177 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
7178 		pmap = PV_PMAP(pv);
7179 		PMAP_ASSERT_STAGE1(pmap);
7180 		if (!PMAP_TRYLOCK(pmap)) {
7181 			pvh_gen = pvh->pv_gen;
7182 			rw_wunlock(lock);
7183 			PMAP_LOCK(pmap);
7184 			rw_wlock(lock);
7185 			if (pvh_gen != pvh->pv_gen) {
7186 				PMAP_UNLOCK(pmap);
7187 				goto retry;
7188 			}
7189 		}
7190 		va = pv->pv_va;
7191 		pte = pmap_pte_exists(pmap, va, 2, __func__);
7192 		if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
7193 			(void)pmap_demote_l2_locked(pmap, pte, va, &lock);
7194 		KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
7195 		    ("inconsistent pv lock %p %p for page %p",
7196 		    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
7197 		PMAP_UNLOCK(pmap);
7198 	}
7199 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7200 		pmap = PV_PMAP(pv);
7201 		if (!PMAP_TRYLOCK(pmap)) {
7202 			pvh_gen = pvh->pv_gen;
7203 			md_gen = m->md.pv_gen;
7204 			rw_wunlock(lock);
7205 			PMAP_LOCK(pmap);
7206 			rw_wlock(lock);
7207 			if (pvh_gen != pvh->pv_gen ||
7208 			    md_gen != m->md.pv_gen) {
7209 				PMAP_UNLOCK(pmap);
7210 				goto retry;
7211 			}
7212 		}
7213 		pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
7214 		oldpte = pmap_load(pte);
7215 		if ((oldpte & ATTR_SW_DBM) != 0) {
7216 			if ((oldpte & ATTR_CONTIGUOUS) != 0) {
7217 				(void)pmap_demote_l3c(pmap, pte, pv->pv_va);
7218 
7219 				/*
7220 				 * The L3 entry's accessed bit may have
7221 				 * changed.
7222 				 */
7223 				oldpte = pmap_load(pte);
7224 			}
7225 			if (pmap->pm_stage == PM_STAGE1) {
7226 				set = ATTR_S1_AP_RW_BIT;
7227 				clear = 0;
7228 				mask = ATTR_S1_AP_RW_BIT;
7229 				val = ATTR_S1_AP(ATTR_S1_AP_RW);
7230 			} else {
7231 				set = 0;
7232 				clear = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
7233 				mask = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
7234 				val = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
7235 			}
7236 			clear |= ATTR_SW_DBM;
7237 			while (!atomic_fcmpset_64(pte, &oldpte,
7238 			    (oldpte | set) & ~clear))
7239 				cpu_spinwait();
7240 
7241 			if ((oldpte & mask) == val)
7242 				vm_page_dirty(m);
7243 			pmap_invalidate_page(pmap, pv->pv_va, true);
7244 		}
7245 		PMAP_UNLOCK(pmap);
7246 	}
7247 	rw_wunlock(lock);
7248 	vm_page_aflag_clear(m, PGA_WRITEABLE);
7249 }
7250 
7251 /*
7252  *	pmap_ts_referenced:
7253  *
7254  *	Return a count of reference bits for a page, clearing those bits.
7255  *	It is not necessary for every reference bit to be cleared, but it
7256  *	is necessary that 0 only be returned when there are truly no
7257  *	reference bits set.
7258  *
7259  *	As an optimization, update the page's dirty field if a modified bit is
7260  *	found while counting reference bits.  This opportunistic update can be
7261  *	performed at low cost and can eliminate the need for some future calls
7262  *	to pmap_is_modified().  However, since this function stops after
7263  *	finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
7264  *	dirty pages.  Those dirty pages will only be detected by a future call
7265  *	to pmap_is_modified().
7266  */
7267 int
pmap_ts_referenced(vm_page_t m)7268 pmap_ts_referenced(vm_page_t m)
7269 {
7270 	struct md_page *pvh;
7271 	pv_entry_t pv, pvf;
7272 	pmap_t pmap;
7273 	struct rwlock *lock;
7274 	pt_entry_t *pte, tpte;
7275 	vm_offset_t va;
7276 	vm_paddr_t pa;
7277 	int cleared, md_gen, not_cleared, pvh_gen;
7278 	struct spglist free;
7279 
7280 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7281 	    ("pmap_ts_referenced: page %p is not managed", m));
7282 	SLIST_INIT(&free);
7283 	cleared = 0;
7284 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
7285 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7286 	rw_wlock(lock);
7287 retry:
7288 	not_cleared = 0;
7289 	if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
7290 		goto small_mappings;
7291 	pv = pvf;
7292 	do {
7293 		if (pvf == NULL)
7294 			pvf = pv;
7295 		pmap = PV_PMAP(pv);
7296 		if (!PMAP_TRYLOCK(pmap)) {
7297 			pvh_gen = pvh->pv_gen;
7298 			rw_wunlock(lock);
7299 			PMAP_LOCK(pmap);
7300 			rw_wlock(lock);
7301 			if (pvh_gen != pvh->pv_gen) {
7302 				PMAP_UNLOCK(pmap);
7303 				goto retry;
7304 			}
7305 		}
7306 		va = pv->pv_va;
7307 		pte = pmap_pte_exists(pmap, va, 2, __func__);
7308 		tpte = pmap_load(pte);
7309 		if (pmap_pte_dirty(pmap, tpte)) {
7310 			/*
7311 			 * Although "tpte" is mapping a 2MB page, because
7312 			 * this function is called at a 4KB page granularity,
7313 			 * we only update the 4KB page under test.
7314 			 */
7315 			vm_page_dirty(m);
7316 		}
7317 		if ((tpte & ATTR_AF) != 0) {
7318 			pa = VM_PAGE_TO_PHYS(m);
7319 
7320 			/*
7321 			 * Since this reference bit is shared by 512 4KB pages,
7322 			 * it should not be cleared every time it is tested.
7323 			 * Apply a simple "hash" function on the physical page
7324 			 * number, the virtual superpage number, and the pmap
7325 			 * address to select one 4KB page out of the 512 on
7326 			 * which testing the reference bit will result in
7327 			 * clearing that reference bit.  This function is
7328 			 * designed to avoid the selection of the same 4KB page
7329 			 * for every 2MB page mapping.
7330 			 *
7331 			 * On demotion, a mapping that hasn't been referenced
7332 			 * is simply destroyed.  To avoid the possibility of a
7333 			 * subsequent page fault on a demoted wired mapping,
7334 			 * always leave its reference bit set.  Moreover,
7335 			 * since the superpage is wired, the current state of
7336 			 * its reference bit won't affect page replacement.
7337 			 */
7338 			if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
7339 			    (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
7340 			    (tpte & ATTR_SW_WIRED) == 0) {
7341 				pmap_clear_bits(pte, ATTR_AF);
7342 				pmap_invalidate_page(pmap, va, true);
7343 				cleared++;
7344 			} else
7345 				not_cleared++;
7346 		}
7347 		PMAP_UNLOCK(pmap);
7348 		/* Rotate the PV list if it has more than one entry. */
7349 		if (TAILQ_NEXT(pv, pv_next) != NULL) {
7350 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
7351 			TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
7352 			pvh->pv_gen++;
7353 		}
7354 		if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
7355 			goto out;
7356 	} while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
7357 small_mappings:
7358 	if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
7359 		goto out;
7360 	pv = pvf;
7361 	do {
7362 		if (pvf == NULL)
7363 			pvf = pv;
7364 		pmap = PV_PMAP(pv);
7365 		if (!PMAP_TRYLOCK(pmap)) {
7366 			pvh_gen = pvh->pv_gen;
7367 			md_gen = m->md.pv_gen;
7368 			rw_wunlock(lock);
7369 			PMAP_LOCK(pmap);
7370 			rw_wlock(lock);
7371 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
7372 				PMAP_UNLOCK(pmap);
7373 				goto retry;
7374 			}
7375 		}
7376 		pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
7377 		tpte = pmap_load(pte);
7378 		if (pmap_pte_dirty(pmap, tpte))
7379 			vm_page_dirty(m);
7380 		if ((tpte & ATTR_AF) != 0) {
7381 			if ((tpte & ATTR_SW_WIRED) == 0) {
7382 				/*
7383 				 * Clear the accessed bit in this L3 entry
7384 				 * regardless of the contiguous bit.
7385 				 */
7386 				pmap_clear_bits(pte, ATTR_AF);
7387 				pmap_invalidate_page(pmap, pv->pv_va, true);
7388 				cleared++;
7389 			} else
7390 				not_cleared++;
7391 		} else if ((tpte & ATTR_CONTIGUOUS) != 0 &&
7392 		    (pmap_load_l3c(pte) & ATTR_AF) != 0) {
7393 			/*
7394 			 * An L3C superpage mapping is regarded as accessed
7395 			 * until the accessed bit has been cleared in all
7396 			 * of its constituent entries.
7397 			 */
7398 			not_cleared++;
7399 		}
7400 		PMAP_UNLOCK(pmap);
7401 		/* Rotate the PV list if it has more than one entry. */
7402 		if (TAILQ_NEXT(pv, pv_next) != NULL) {
7403 			TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
7404 			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7405 			m->md.pv_gen++;
7406 		}
7407 	} while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
7408 	    not_cleared < PMAP_TS_REFERENCED_MAX);
7409 out:
7410 	rw_wunlock(lock);
7411 	vm_page_free_pages_toq(&free, true);
7412 	return (cleared + not_cleared);
7413 }
7414 
7415 /*
7416  *	Apply the given advice to the specified range of addresses within the
7417  *	given pmap.  Depending on the advice, clear the referenced and/or
7418  *	modified flags in each mapping and set the mapped page's dirty field.
7419  */
7420 void
pmap_advise(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,int advice)7421 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
7422 {
7423 	struct rwlock *lock;
7424 	vm_offset_t va, va_next, dva;
7425 	vm_page_t m;
7426 	pd_entry_t *l0, *l1, *l2, oldl2;
7427 	pt_entry_t *l3, *dl3, oldl3;
7428 
7429 	PMAP_ASSERT_STAGE1(pmap);
7430 
7431 	if (advice != MADV_DONTNEED && advice != MADV_FREE)
7432 		return;
7433 
7434 	PMAP_LOCK(pmap);
7435 	for (; sva < eva; sva = va_next) {
7436 		l0 = pmap_l0(pmap, sva);
7437 		if (pmap_load(l0) == 0) {
7438 			va_next = (sva + L0_SIZE) & ~L0_OFFSET;
7439 			if (va_next < sva)
7440 				va_next = eva;
7441 			continue;
7442 		}
7443 
7444 		va_next = (sva + L1_SIZE) & ~L1_OFFSET;
7445 		if (va_next < sva)
7446 			va_next = eva;
7447 		l1 = pmap_l0_to_l1(l0, sva);
7448 		if (pmap_load(l1) == 0)
7449 			continue;
7450 		if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
7451 			PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
7452 			continue;
7453 		}
7454 
7455 		va_next = (sva + L2_SIZE) & ~L2_OFFSET;
7456 		if (va_next < sva)
7457 			va_next = eva;
7458 		l2 = pmap_l1_to_l2(l1, sva);
7459 		oldl2 = pmap_load(l2);
7460 		if (oldl2 == 0)
7461 			continue;
7462 		if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
7463 			if ((oldl2 & ATTR_SW_MANAGED) == 0)
7464 				continue;
7465 			lock = NULL;
7466 			if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
7467 				if (lock != NULL)
7468 					rw_wunlock(lock);
7469 
7470 				/*
7471 				 * The 2MB page mapping was destroyed.
7472 				 */
7473 				continue;
7474 			}
7475 
7476 			/*
7477 			 * Unless the page mappings are wired, remove the
7478 			 * mapping to a single page so that a subsequent
7479 			 * access may repromote.  Choosing the last page
7480 			 * within the address range [sva, min(va_next, eva))
7481 			 * generally results in more repromotions.  Since the
7482 			 * underlying page table page is fully populated, this
7483 			 * removal never frees a page table page.
7484 			 */
7485 			if ((oldl2 & ATTR_SW_WIRED) == 0) {
7486 				va = eva;
7487 				if (va > va_next)
7488 					va = va_next;
7489 				va -= PAGE_SIZE;
7490 				KASSERT(va >= sva,
7491 				    ("pmap_advise: no address gap"));
7492 				l3 = pmap_l2_to_l3(l2, va);
7493 				KASSERT(pmap_load(l3) != 0,
7494 				    ("pmap_advise: invalid PTE"));
7495 				pmap_remove_l3(pmap, l3, va, pmap_load(l2),
7496 				    NULL, &lock);
7497 			}
7498 			if (lock != NULL)
7499 				rw_wunlock(lock);
7500 		}
7501 		KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
7502 		    ("pmap_advise: invalid L2 entry after demotion"));
7503 		if (va_next > eva)
7504 			va_next = eva;
7505 		va = va_next;
7506 		for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
7507 		    sva += L3_SIZE) {
7508 			oldl3 = pmap_load(l3);
7509 			if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
7510 			    (ATTR_SW_MANAGED | L3_PAGE))
7511 				goto maybe_invlrng;
7512 			else if (pmap_pte_dirty(pmap, oldl3)) {
7513 				if (advice == MADV_DONTNEED) {
7514 					/*
7515 					 * Future calls to pmap_is_modified()
7516 					 * can be avoided by making the page
7517 					 * dirty now.
7518 					 */
7519 					m = PTE_TO_VM_PAGE(oldl3);
7520 					vm_page_dirty(m);
7521 				}
7522 				if ((oldl3 & ATTR_CONTIGUOUS) != 0) {
7523 					/*
7524 					 * Unconditionally demote the L3C
7525 					 * superpage because we do not allow
7526 					 * writeable, clean superpages.
7527 					 */
7528 					(void)pmap_demote_l3c(pmap, l3, sva);
7529 
7530 					/*
7531                                          * Destroy the final mapping before the
7532                                          * next L3C boundary or va_next,
7533 					 * whichever comes first, so that a
7534 					 * subsequent access may act as a
7535 					 * repromotion trigger.
7536 					 */
7537                                         if ((oldl3 & ATTR_SW_WIRED) == 0) {
7538 						dva = MIN((sva & ~L3C_OFFSET) +
7539 						    L3C_SIZE - PAGE_SIZE,
7540 						    va_next - PAGE_SIZE);
7541 						dl3 = pmap_l2_to_l3(l2, dva);
7542 						KASSERT(pmap_load(dl3) != 0,
7543 						    ("pmap_advise: invalid PTE"));
7544 						lock = NULL;
7545 						pmap_remove_l3(pmap, dl3, dva,
7546 						    pmap_load(l2), NULL, &lock);
7547 						if (lock != NULL)
7548 							rw_wunlock(lock);
7549 					}
7550 
7551 					/*
7552 					 * The L3 entry's accessed bit may have
7553 					 * changed.
7554 					 */
7555 					oldl3 = pmap_load(l3);
7556 				}
7557 
7558 				/*
7559 				 * Check that we did not just destroy this entry so
7560 				 * we avoid corrupting the page able.
7561 				 */
7562 				if (oldl3 != 0) {
7563 					while (!atomic_fcmpset_long(l3, &oldl3,
7564 					    (oldl3 & ~ATTR_AF) |
7565 					    ATTR_S1_AP(ATTR_S1_AP_RO)))
7566 						cpu_spinwait();
7567 				}
7568 			} else if ((oldl3 & ATTR_AF) != 0) {
7569 				/*
7570 				 * Clear the accessed bit in this L3 entry
7571 				 * regardless of the contiguous bit.
7572 				 */
7573 				pmap_clear_bits(l3, ATTR_AF);
7574 			} else
7575 				goto maybe_invlrng;
7576 			if (va == va_next)
7577 				va = sva;
7578 			continue;
7579 maybe_invlrng:
7580 			if (va != va_next) {
7581 				pmap_s1_invalidate_range(pmap, va, sva, true);
7582 				va = va_next;
7583 			}
7584 		}
7585 		if (va != va_next)
7586 			pmap_s1_invalidate_range(pmap, va, sva, true);
7587 	}
7588 	PMAP_UNLOCK(pmap);
7589 }
7590 
7591 /*
7592  *	Clear the modify bits on the specified physical page.
7593  */
7594 void
pmap_clear_modify(vm_page_t m)7595 pmap_clear_modify(vm_page_t m)
7596 {
7597 	struct md_page *pvh;
7598 	struct rwlock *lock;
7599 	pmap_t pmap;
7600 	pv_entry_t next_pv, pv;
7601 	pd_entry_t *l2, oldl2;
7602 	pt_entry_t *l3, oldl3;
7603 	vm_offset_t va;
7604 	int md_gen, pvh_gen;
7605 
7606 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7607 	    ("pmap_clear_modify: page %p is not managed", m));
7608 	vm_page_assert_busied(m);
7609 
7610 	if (!pmap_page_is_write_mapped(m))
7611 		return;
7612 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
7613 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7614 	rw_wlock(lock);
7615 restart:
7616 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
7617 		pmap = PV_PMAP(pv);
7618 		PMAP_ASSERT_STAGE1(pmap);
7619 		if (!PMAP_TRYLOCK(pmap)) {
7620 			pvh_gen = pvh->pv_gen;
7621 			rw_wunlock(lock);
7622 			PMAP_LOCK(pmap);
7623 			rw_wlock(lock);
7624 			if (pvh_gen != pvh->pv_gen) {
7625 				PMAP_UNLOCK(pmap);
7626 				goto restart;
7627 			}
7628 		}
7629 		va = pv->pv_va;
7630 		l2 = pmap_l2(pmap, va);
7631 		oldl2 = pmap_load(l2);
7632 		/* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
7633 		if ((oldl2 & ATTR_SW_DBM) != 0 &&
7634 		    pmap_demote_l2_locked(pmap, l2, va, &lock) &&
7635 		    (oldl2 & ATTR_SW_WIRED) == 0) {
7636 			/*
7637 			 * Write protect the mapping to a single page so that
7638 			 * a subsequent write access may repromote.
7639 			 */
7640 			va += VM_PAGE_TO_PHYS(m) - PTE_TO_PHYS(oldl2);
7641 			l3 = pmap_l2_to_l3(l2, va);
7642 			oldl3 = pmap_load(l3);
7643 			while (!atomic_fcmpset_long(l3, &oldl3,
7644 			    (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
7645 				cpu_spinwait();
7646 			vm_page_dirty(m);
7647 			pmap_s1_invalidate_page(pmap, va, true);
7648 		}
7649 		PMAP_UNLOCK(pmap);
7650 	}
7651 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7652 		pmap = PV_PMAP(pv);
7653 		PMAP_ASSERT_STAGE1(pmap);
7654 		if (!PMAP_TRYLOCK(pmap)) {
7655 			md_gen = m->md.pv_gen;
7656 			pvh_gen = pvh->pv_gen;
7657 			rw_wunlock(lock);
7658 			PMAP_LOCK(pmap);
7659 			rw_wlock(lock);
7660 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
7661 				PMAP_UNLOCK(pmap);
7662 				goto restart;
7663 			}
7664 		}
7665 		l2 = pmap_l2(pmap, pv->pv_va);
7666 		l3 = pmap_l2_to_l3(l2, pv->pv_va);
7667 		oldl3 = pmap_load(l3);
7668 		KASSERT((oldl3 & ATTR_CONTIGUOUS) == 0 ||
7669 		    (oldl3 & (ATTR_SW_DBM | ATTR_S1_AP_RW_BIT)) !=
7670 		    (ATTR_SW_DBM | ATTR_S1_AP(ATTR_S1_AP_RO)),
7671 		    ("writeable L3C superpage not dirty"));
7672 		if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM) {
7673 			if ((oldl3 & ATTR_CONTIGUOUS) != 0)
7674 				(void)pmap_demote_l3c(pmap, l3, pv->pv_va);
7675 			pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
7676 			pmap_s1_invalidate_page(pmap, pv->pv_va, true);
7677 		}
7678 		PMAP_UNLOCK(pmap);
7679 	}
7680 	rw_wunlock(lock);
7681 }
7682 
7683 void *
pmap_mapbios(vm_paddr_t pa,vm_size_t size)7684 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
7685 {
7686 	struct pmap_preinit_mapping *ppim;
7687 	vm_offset_t va, offset;
7688 	pd_entry_t old_l2e, *pde;
7689 	pt_entry_t *l2;
7690 	int i, lvl, l2_blocks, free_l2_count, start_idx;
7691 
7692 	if (!vm_initialized) {
7693 		/*
7694 		 * No L3 ptables so map entire L2 blocks where start VA is:
7695 		 * 	preinit_map_va + start_idx * L2_SIZE
7696 		 * There may be duplicate mappings (multiple VA -> same PA) but
7697 		 * ARM64 dcache is always PIPT so that's acceptable.
7698 		 */
7699 		 if (size == 0)
7700 			 return (NULL);
7701 
7702 		 /* Calculate how many L2 blocks are needed for the mapping */
7703 		l2_blocks = (roundup2(pa + size, L2_SIZE) -
7704 		    rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
7705 
7706 		offset = pa & L2_OFFSET;
7707 
7708 		if (preinit_map_va == 0)
7709 			return (NULL);
7710 
7711 		/* Map 2MiB L2 blocks from reserved VA space */
7712 
7713 		free_l2_count = 0;
7714 		start_idx = -1;
7715 		/* Find enough free contiguous VA space */
7716 		for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7717 			ppim = pmap_preinit_mapping + i;
7718 			if (free_l2_count > 0 && ppim->pa != 0) {
7719 				/* Not enough space here */
7720 				free_l2_count = 0;
7721 				start_idx = -1;
7722 				continue;
7723 			}
7724 
7725 			if (ppim->pa == 0) {
7726 				/* Free L2 block */
7727 				if (start_idx == -1)
7728 					start_idx = i;
7729 				free_l2_count++;
7730 				if (free_l2_count == l2_blocks)
7731 					break;
7732 			}
7733 		}
7734 		if (free_l2_count != l2_blocks)
7735 			panic("%s: too many preinit mappings", __func__);
7736 
7737 		va = preinit_map_va + (start_idx * L2_SIZE);
7738 		for (i = start_idx; i < start_idx + l2_blocks; i++) {
7739 			/* Mark entries as allocated */
7740 			ppim = pmap_preinit_mapping + i;
7741 			ppim->pa = pa;
7742 			ppim->va = va + offset;
7743 			ppim->size = size;
7744 		}
7745 
7746 		/* Map L2 blocks */
7747 		pa = rounddown2(pa, L2_SIZE);
7748 		old_l2e = 0;
7749 		for (i = 0; i < l2_blocks; i++) {
7750 			pde = pmap_pde(kernel_pmap, va, &lvl);
7751 			KASSERT(pde != NULL,
7752 			    ("pmap_mapbios: Invalid page entry, va: 0x%lx",
7753 			    va));
7754 			KASSERT(lvl == 1,
7755 			    ("pmap_mapbios: Invalid level %d", lvl));
7756 
7757 			/* Insert L2_BLOCK */
7758 			l2 = pmap_l1_to_l2(pde, va);
7759 			old_l2e |= pmap_load_store(l2,
7760 			    PHYS_TO_PTE(pa) | ATTR_AF | pmap_sh_attr |
7761 			    ATTR_S1_XN | ATTR_KERN_GP |
7762 			    ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
7763 
7764 			va += L2_SIZE;
7765 			pa += L2_SIZE;
7766 		}
7767 		if ((old_l2e & ATTR_DESCR_VALID) != 0)
7768 			pmap_s1_invalidate_all(kernel_pmap);
7769 		else {
7770 			/*
7771 			 * Because the old entries were invalid and the new
7772 			 * mappings are not executable, an isb is not required.
7773 			 */
7774 			dsb(ishst);
7775 		}
7776 
7777 		va = preinit_map_va + (start_idx * L2_SIZE);
7778 
7779 	} else {
7780 		/* kva_alloc may be used to map the pages */
7781 		offset = pa & PAGE_MASK;
7782 		size = round_page(offset + size);
7783 
7784 		va = kva_alloc(size);
7785 		if (va == 0)
7786 			panic("%s: Couldn't allocate KVA", __func__);
7787 
7788 		pde = pmap_pde(kernel_pmap, va, &lvl);
7789 		KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
7790 
7791 		/* L3 table is linked */
7792 		va = trunc_page(va);
7793 		pa = trunc_page(pa);
7794 		pmap_kenter(va, size, pa, memory_mapping_mode(pa));
7795 	}
7796 
7797 	return ((void *)(va + offset));
7798 }
7799 
7800 void
pmap_unmapbios(void * p,vm_size_t size)7801 pmap_unmapbios(void *p, vm_size_t size)
7802 {
7803 	struct pmap_preinit_mapping *ppim;
7804 	vm_offset_t offset, va, va_trunc;
7805 	pd_entry_t *pde;
7806 	pt_entry_t *l2;
7807 	int i, lvl, l2_blocks, block;
7808 	bool preinit_map;
7809 
7810 	va = (vm_offset_t)p;
7811 	l2_blocks =
7812 	   (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
7813 	KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
7814 
7815 	/* Remove preinit mapping */
7816 	preinit_map = false;
7817 	block = 0;
7818 	for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7819 		ppim = pmap_preinit_mapping + i;
7820 		if (ppim->va == va) {
7821 			KASSERT(ppim->size == size,
7822 			    ("pmap_unmapbios: size mismatch"));
7823 			ppim->va = 0;
7824 			ppim->pa = 0;
7825 			ppim->size = 0;
7826 			preinit_map = true;
7827 			offset = block * L2_SIZE;
7828 			va_trunc = rounddown2(va, L2_SIZE) + offset;
7829 
7830 			/* Remove L2_BLOCK */
7831 			pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
7832 			KASSERT(pde != NULL,
7833 			    ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
7834 			    va_trunc));
7835 			l2 = pmap_l1_to_l2(pde, va_trunc);
7836 			pmap_clear(l2);
7837 
7838 			if (block == (l2_blocks - 1))
7839 				break;
7840 			block++;
7841 		}
7842 	}
7843 	if (preinit_map) {
7844 		pmap_s1_invalidate_all(kernel_pmap);
7845 		return;
7846 	}
7847 
7848 	/* Unmap the pages reserved with kva_alloc. */
7849 	if (vm_initialized) {
7850 		offset = va & PAGE_MASK;
7851 		size = round_page(offset + size);
7852 		va = trunc_page(va);
7853 
7854 		/* Unmap and invalidate the pages */
7855 		pmap_kremove_device(va, size);
7856 
7857 		kva_free(va, size);
7858 	}
7859 }
7860 
7861 /*
7862  * Sets the memory attribute for the specified page.
7863  */
7864 void
pmap_page_set_memattr(vm_page_t m,vm_memattr_t ma)7865 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7866 {
7867 
7868 	m->md.pv_memattr = ma;
7869 
7870 	/*
7871 	 * If "m" is a normal page, update its direct mapping.  This update
7872 	 * can be relied upon to perform any cache operations that are
7873 	 * required for data coherence.
7874 	 */
7875 	if ((m->flags & PG_FICTITIOUS) == 0 &&
7876 	    pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7877 	    m->md.pv_memattr) != 0)
7878 		panic("memory attribute change on the direct map failed");
7879 }
7880 
7881 /*
7882  * Changes the specified virtual address range's memory type to that given by
7883  * the parameter "mode".  The specified virtual address range must be
7884  * completely contained within either the direct map or the kernel map.  If
7885  * the virtual address range is contained within the kernel map, then the
7886  * memory type for each of the corresponding ranges of the direct map is also
7887  * changed.  (The corresponding ranges of the direct map are those ranges that
7888  * map the same physical pages as the specified virtual address range.)  These
7889  * changes to the direct map are necessary because Intel describes the
7890  * behavior of their processors as "undefined" if two or more mappings to the
7891  * same physical page have different memory types.
7892  *
7893  * Returns zero if the change completed successfully, and either EINVAL or
7894  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
7895  * of the virtual address range was not mapped, and ENOMEM is returned if
7896  * there was insufficient memory available to complete the change.  In the
7897  * latter case, the memory type may have been changed on some part of the
7898  * virtual address range or the direct map.
7899  */
7900 int
pmap_change_attr(vm_offset_t va,vm_size_t size,int mode)7901 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7902 {
7903 	int error;
7904 
7905 	PMAP_LOCK(kernel_pmap);
7906 	error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
7907 	PMAP_UNLOCK(kernel_pmap);
7908 	return (error);
7909 }
7910 
7911 /*
7912  * Changes the specified virtual address range's protections to those
7913  * specified by "prot".  Like pmap_change_attr(), protections for aliases
7914  * in the direct map are updated as well.  Protections on aliasing mappings may
7915  * be a subset of the requested protections; for example, mappings in the direct
7916  * map are never executable.
7917  */
7918 int
pmap_change_prot(vm_offset_t va,vm_size_t size,vm_prot_t prot)7919 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
7920 {
7921 	int error;
7922 
7923 	/* Only supported within the kernel map. */
7924 	if (va < VM_MIN_KERNEL_ADDRESS)
7925 		return (EINVAL);
7926 
7927 	PMAP_LOCK(kernel_pmap);
7928 	error = pmap_change_props_locked(va, size, prot, -1, false);
7929 	PMAP_UNLOCK(kernel_pmap);
7930 	return (error);
7931 }
7932 
7933 static int
pmap_change_props_locked(vm_offset_t va,vm_size_t size,vm_prot_t prot,int mode,bool skip_unmapped)7934 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
7935     int mode, bool skip_unmapped)
7936 {
7937 	vm_offset_t base, offset, tmpva;
7938 	vm_size_t pte_size;
7939 	vm_paddr_t pa;
7940 	pt_entry_t pte, *ptep, *newpte;
7941 	pt_entry_t bits, mask;
7942 	int lvl, rv;
7943 
7944 	PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7945 	base = trunc_page(va);
7946 	offset = va & PAGE_MASK;
7947 	size = round_page(offset + size);
7948 
7949 	if (!VIRT_IN_DMAP(base) &&
7950 	    !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
7951 		return (EINVAL);
7952 
7953 	bits = 0;
7954 	mask = 0;
7955 	if (mode != -1) {
7956 		bits = ATTR_S1_IDX(mode);
7957 		mask = ATTR_S1_IDX_MASK;
7958 		if (mode == VM_MEMATTR_DEVICE) {
7959 			mask |= ATTR_S1_XN;
7960 			bits |= ATTR_S1_XN;
7961 		}
7962 	}
7963 	if (prot != VM_PROT_NONE) {
7964 		/* Don't mark the DMAP as executable. It never is on arm64. */
7965 		if (VIRT_IN_DMAP(base)) {
7966 			prot &= ~VM_PROT_EXECUTE;
7967 			/*
7968 			 * XXX Mark the DMAP as writable for now. We rely
7969 			 * on this in ddb & dtrace to insert breakpoint
7970 			 * instructions.
7971 			 */
7972 			prot |= VM_PROT_WRITE;
7973 		}
7974 
7975 		if ((prot & VM_PROT_WRITE) == 0) {
7976 			bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
7977 		}
7978 		if ((prot & VM_PROT_EXECUTE) == 0) {
7979 			bits |= ATTR_S1_PXN;
7980 		}
7981 		bits |= ATTR_S1_UXN;
7982 		mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
7983 	}
7984 
7985 	for (tmpva = base; tmpva < base + size; ) {
7986 		ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
7987 		if (ptep == NULL && !skip_unmapped) {
7988 			return (EINVAL);
7989 		} else if ((ptep == NULL && skip_unmapped) ||
7990 		    (pmap_load(ptep) & mask) == bits) {
7991 			/*
7992 			 * We already have the correct attribute or there
7993 			 * is no memory mapped at this address and we are
7994 			 * skipping unmapped memory.
7995 			 */
7996 			switch (lvl) {
7997 			default:
7998 				panic("Invalid DMAP table level: %d\n", lvl);
7999 			case 1:
8000 				tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
8001 				break;
8002 			case 2:
8003 				tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
8004 				break;
8005 			case 3:
8006 				tmpva += PAGE_SIZE;
8007 				break;
8008 			}
8009 		} else {
8010 			/* We can't demote/promote this entry */
8011 			MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
8012 
8013 			/*
8014 			 * Find the entry and demote it if the requested change
8015 			 * only applies to part of the address range mapped by
8016 			 * the entry.
8017 			 */
8018 			switch (lvl) {
8019 			default:
8020 				panic("Invalid DMAP table level: %d\n", lvl);
8021 			case 1:
8022 				PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
8023 				if ((tmpva & L1_OFFSET) == 0 &&
8024 				    (base + size - tmpva) >= L1_SIZE) {
8025 					pte_size = L1_SIZE;
8026 					break;
8027 				}
8028 				newpte = pmap_demote_l1(kernel_pmap, ptep,
8029 				    tmpva & ~L1_OFFSET);
8030 				if (newpte == NULL)
8031 					return (EINVAL);
8032 				ptep = pmap_l1_to_l2(ptep, tmpva);
8033 				/* FALLTHROUGH */
8034 			case 2:
8035 				if ((pmap_load(ptep) & ATTR_CONTIGUOUS) != 0) {
8036 					if ((tmpva & L2C_OFFSET) == 0 &&
8037 					    (base + size - tmpva) >= L2C_SIZE) {
8038 						pte_size = L2C_SIZE;
8039 						break;
8040 					}
8041 					if (!pmap_demote_l2c(kernel_pmap, ptep,
8042 					    tmpva))
8043 						return (EINVAL);
8044 				}
8045 				if ((tmpva & L2_OFFSET) == 0 &&
8046 				    (base + size - tmpva) >= L2_SIZE) {
8047 					pte_size = L2_SIZE;
8048 					break;
8049 				}
8050 				newpte = pmap_demote_l2(kernel_pmap, ptep,
8051 				    tmpva);
8052 				if (newpte == NULL)
8053 					return (EINVAL);
8054 				ptep = pmap_l2_to_l3(ptep, tmpva);
8055 				/* FALLTHROUGH */
8056 			case 3:
8057 				if ((pmap_load(ptep) & ATTR_CONTIGUOUS) != 0) {
8058 					if ((tmpva & L3C_OFFSET) == 0 &&
8059 					    (base + size - tmpva) >= L3C_SIZE) {
8060 						pte_size = L3C_SIZE;
8061 						break;
8062 					}
8063 					if (!pmap_demote_l3c(kernel_pmap, ptep,
8064 					    tmpva))
8065 						return (EINVAL);
8066 				}
8067 				pte_size = PAGE_SIZE;
8068 				break;
8069 			}
8070 
8071 			/* Update the entry */
8072 			pte = pmap_load(ptep);
8073 			pte &= ~mask;
8074 			pte |= bits;
8075 
8076 			switch (pte_size) {
8077 			case L2C_SIZE:
8078 				pmap_update_strided(kernel_pmap, ptep, ptep +
8079 				    L2C_ENTRIES, pte, tmpva, L2_SIZE, L2C_SIZE);
8080 				break;
8081 			case L3C_SIZE:
8082 				pmap_update_strided(kernel_pmap, ptep, ptep +
8083 				    L3C_ENTRIES, pte, tmpva, L3_SIZE, L3C_SIZE);
8084 				break;
8085 			default:
8086 				/*
8087 				 * We are updating a single block or page entry,
8088 				 * so regardless of pte_size pass PAGE_SIZE in
8089 				 * order that a single TLB invalidation is
8090 				 * performed.
8091 				 */
8092 				pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
8093 				    PAGE_SIZE);
8094 				break;
8095 			}
8096 
8097 			pa = PTE_TO_PHYS(pte);
8098 			if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
8099 				/*
8100 				 * Keep the DMAP memory in sync.
8101 				 */
8102 				rv = pmap_change_props_locked(
8103 				    PHYS_TO_DMAP(pa), pte_size,
8104 				    prot, mode, true);
8105 				if (rv != 0)
8106 					return (rv);
8107 			}
8108 
8109 			/*
8110 			 * If moving to a non-cacheable entry flush
8111 			 * the cache.
8112 			 */
8113 			if (mode == VM_MEMATTR_UNCACHEABLE)
8114 				cpu_dcache_wbinv_range((void *)tmpva, pte_size);
8115 			tmpva += pte_size;
8116 		}
8117 	}
8118 
8119 	return (0);
8120 }
8121 
8122 /*
8123  * Create an L2 table to map all addresses within an L1 mapping.
8124  */
8125 static pt_entry_t *
pmap_demote_l1(pmap_t pmap,pt_entry_t * l1,vm_offset_t va)8126 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
8127 {
8128 	pt_entry_t *l2, newl2, oldl1;
8129 	vm_offset_t tmpl1;
8130 	vm_paddr_t l2phys, phys;
8131 	vm_page_t ml2;
8132 	int i;
8133 
8134 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
8135 	oldl1 = pmap_load(l1);
8136 	PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
8137 	KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
8138 	    ("pmap_demote_l1: Demoting a non-block entry"));
8139 	KASSERT((va & L1_OFFSET) == 0,
8140 	    ("pmap_demote_l1: Invalid virtual address %#lx", va));
8141 	KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
8142 	    ("pmap_demote_l1: Level 1 table shouldn't be managed"));
8143 	KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
8144 	    ("pmap_demote_l1: Demoting entry with no-demote flag set"));
8145 
8146 	tmpl1 = 0;
8147 	if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
8148 		tmpl1 = kva_alloc(PAGE_SIZE);
8149 		if (tmpl1 == 0)
8150 			return (NULL);
8151 	}
8152 
8153 	if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
8154 	    NULL) {
8155 		CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
8156 		    " in pmap %p", va, pmap);
8157 		l2 = NULL;
8158 		goto fail;
8159 	}
8160 
8161 	l2phys = VM_PAGE_TO_PHYS(ml2);
8162 	l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
8163 
8164 	/* Address the range points at */
8165 	phys = PTE_TO_PHYS(oldl1);
8166 	/* The attributed from the old l1 table to be copied */
8167 	newl2 = oldl1 & ATTR_MASK;
8168 
8169 	/* Create the new entries */
8170 	newl2 |= ATTR_CONTIGUOUS;
8171 	for (i = 0; i < Ln_ENTRIES; i++) {
8172 		l2[i] = newl2 | phys;
8173 		phys += L2_SIZE;
8174 	}
8175 	KASSERT(l2[0] == (ATTR_CONTIGUOUS | (oldl1 & ~ATTR_DESCR_MASK) |
8176 	    L2_BLOCK), ("Invalid l2 page (%lx != %lx)", l2[0],
8177 	    ATTR_CONTIGUOUS | (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
8178 
8179 	if (tmpl1 != 0) {
8180 		pmap_kenter(tmpl1, PAGE_SIZE,
8181 		    DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
8182 		    VM_MEMATTR_WRITE_BACK);
8183 		l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
8184 	}
8185 
8186 	pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
8187 
8188 	counter_u64_add(pmap_l1_demotions, 1);
8189 fail:
8190 	if (tmpl1 != 0) {
8191 		pmap_kremove(tmpl1);
8192 		kva_free(tmpl1, PAGE_SIZE);
8193 	}
8194 
8195 	return (l2);
8196 }
8197 
8198 static void
pmap_fill_l3(pt_entry_t * firstl3,pt_entry_t newl3)8199 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
8200 {
8201 	pt_entry_t *l3;
8202 
8203 	for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
8204 		*l3 = newl3;
8205 		newl3 += L3_SIZE;
8206 	}
8207 }
8208 
8209 static void
pmap_demote_l2_check(pt_entry_t * firstl3p __unused,pt_entry_t newl3e __unused)8210 pmap_demote_l2_check(pt_entry_t *firstl3p __unused, pt_entry_t newl3e __unused)
8211 {
8212 #ifdef INVARIANTS
8213 #ifdef DIAGNOSTIC
8214 	pt_entry_t *xl3p, *yl3p;
8215 
8216 	for (xl3p = firstl3p; xl3p < firstl3p + Ln_ENTRIES;
8217 	    xl3p++, newl3e += PAGE_SIZE) {
8218 		if (PTE_TO_PHYS(pmap_load(xl3p)) != PTE_TO_PHYS(newl3e)) {
8219 			printf("pmap_demote_l2: xl3e %zd and newl3e map "
8220 			    "different pages: found %#lx, expected %#lx\n",
8221 			    xl3p - firstl3p, pmap_load(xl3p), newl3e);
8222 			printf("page table dump\n");
8223 			for (yl3p = firstl3p; yl3p < firstl3p + Ln_ENTRIES;
8224 			    yl3p++) {
8225 				printf("%zd %#lx\n", yl3p - firstl3p,
8226 				    pmap_load(yl3p));
8227 			}
8228 			panic("firstpte");
8229 		}
8230 	}
8231 #else
8232 	KASSERT(PTE_TO_PHYS(pmap_load(firstl3p)) == PTE_TO_PHYS(newl3e),
8233 	    ("pmap_demote_l2: firstl3 and newl3e map different physical"
8234 	    " addresses"));
8235 #endif
8236 #endif
8237 }
8238 
8239 static void
pmap_demote_l2_abort(pmap_t pmap,vm_offset_t va,pt_entry_t * l2,struct rwlock ** lockp)8240 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
8241     struct rwlock **lockp)
8242 {
8243 	struct spglist free;
8244 
8245 	SLIST_INIT(&free);
8246 	(void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
8247 	    lockp);
8248 	vm_page_free_pages_toq(&free, true);
8249 }
8250 
8251 /*
8252  * Create an L3 table to map all addresses within an L2 mapping.
8253  */
8254 static pt_entry_t *
pmap_demote_l2_locked(pmap_t pmap,pt_entry_t * l2,vm_offset_t va,struct rwlock ** lockp)8255 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
8256     struct rwlock **lockp)
8257 {
8258 	pt_entry_t *l3, newl3, oldl2;
8259 	vm_offset_t tmpl2;
8260 	vm_paddr_t l3phys;
8261 	vm_page_t ml3;
8262 
8263 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
8264 	PMAP_ASSERT_STAGE1(pmap);
8265 	KASSERT(ADDR_IS_CANONICAL(va),
8266 	    ("%s: Address not in canonical form: %lx", __func__, va));
8267 
8268 	l3 = NULL;
8269 	oldl2 = pmap_load(l2);
8270 	KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
8271 	    ("pmap_demote_l2: Demoting a non-block entry"));
8272 	KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
8273 	    ("pmap_demote_l2: Demoting entry with no-demote flag set"));
8274 	va &= ~L2_OFFSET;
8275 
8276 	tmpl2 = 0;
8277 	if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
8278 		tmpl2 = kva_alloc(PAGE_SIZE);
8279 		if (tmpl2 == 0)
8280 			return (NULL);
8281 	}
8282 
8283 	/*
8284 	 * Invalidate the 2MB page mapping and return "failure" if the
8285 	 * mapping was never accessed.
8286 	 */
8287 	if ((oldl2 & ATTR_AF) == 0) {
8288 		KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
8289 		    ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
8290 		pmap_demote_l2_abort(pmap, va, l2, lockp);
8291 		CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
8292 		    va, pmap);
8293 		goto fail;
8294 	}
8295 
8296 	if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
8297 		KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
8298 		    ("pmap_demote_l2: page table page for a wired mapping"
8299 		    " is missing"));
8300 
8301 		/*
8302 		 * If the page table page is missing and the mapping
8303 		 * is for a kernel address, the mapping must belong to
8304 		 * either the direct map or the early kernel memory.
8305 		 * Page table pages are preallocated for every other
8306 		 * part of the kernel address space, so the direct map
8307 		 * region and early kernel memory are the only parts of the
8308 		 * kernel address space that must be handled here.
8309 		 */
8310 		KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
8311 		    (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
8312 		    ("pmap_demote_l2: No saved mpte for va %#lx", va));
8313 
8314 		/*
8315 		 * If the 2MB page mapping belongs to the direct map
8316 		 * region of the kernel's address space, then the page
8317 		 * allocation request specifies the highest possible
8318 		 * priority (VM_ALLOC_INTERRUPT).  Otherwise, the
8319 		 * priority is normal.
8320 		 */
8321 		ml3 = vm_page_alloc_noobj(
8322 		    (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
8323 		    VM_ALLOC_WIRED);
8324 
8325 		/*
8326 		 * If the allocation of the new page table page fails,
8327 		 * invalidate the 2MB page mapping and return "failure".
8328 		 */
8329 		if (ml3 == NULL) {
8330 			pmap_demote_l2_abort(pmap, va, l2, lockp);
8331 			CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
8332 			    " in pmap %p", va, pmap);
8333 			goto fail;
8334 		}
8335 		ml3->pindex = pmap_l2_pindex(va);
8336 
8337 		if (!ADDR_IS_KERNEL(va)) {
8338 			ml3->ref_count = NL3PG;
8339 			pmap_resident_count_inc(pmap, 1);
8340 		}
8341 	}
8342 	l3phys = VM_PAGE_TO_PHYS(ml3);
8343 	l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
8344 	newl3 = ATTR_CONTIGUOUS | (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
8345 	KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
8346 	    (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
8347 	    ("pmap_demote_l2: L2 entry is writeable but not dirty"));
8348 
8349 	/*
8350 	 * If the PTP is not leftover from an earlier promotion or it does not
8351 	 * have ATTR_AF set in every L3E, then fill it.  The new L3Es will all
8352 	 * have ATTR_AF set.
8353 	 *
8354 	 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
8355 	 * performs a dsb().  That dsb() ensures that the stores for filling
8356 	 * "l3" are visible before "l3" is added to the page table.
8357 	 */
8358 	if (!vm_page_all_valid(ml3))
8359 		pmap_fill_l3(l3, newl3);
8360 
8361 	pmap_demote_l2_check(l3, newl3);
8362 
8363 	/*
8364 	 * If the mapping has changed attributes, update the L3Es.
8365 	 */
8366 	if ((pmap_load(l3) & ATTR_PROMOTE) != (newl3 & ATTR_PROMOTE))
8367 		pmap_fill_l3(l3, newl3);
8368 
8369 	/*
8370 	 * Map the temporary page so we don't lose access to the l2 table.
8371 	 */
8372 	if (tmpl2 != 0) {
8373 		pmap_kenter(tmpl2, PAGE_SIZE,
8374 		    DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
8375 		    VM_MEMATTR_WRITE_BACK);
8376 		l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
8377 	}
8378 
8379 	/*
8380 	 * The spare PV entries must be reserved prior to demoting the
8381 	 * mapping, that is, prior to changing the PDE.  Otherwise, the state
8382 	 * of the L2 and the PV lists will be inconsistent, which can result
8383 	 * in reclaim_pv_chunk() attempting to remove a PV entry from the
8384 	 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
8385 	 * PV entry for the 2MB page mapping that is being demoted.
8386 	 */
8387 	if ((oldl2 & ATTR_SW_MANAGED) != 0)
8388 		reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
8389 
8390 	/*
8391 	 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
8392 	 * the 2MB page mapping.
8393 	 */
8394 	pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
8395 
8396 	/*
8397 	 * Demote the PV entry.
8398 	 */
8399 	if ((oldl2 & ATTR_SW_MANAGED) != 0)
8400 		pmap_pv_demote_l2(pmap, va, PTE_TO_PHYS(oldl2), lockp);
8401 
8402 	atomic_add_long(&pmap_l2_demotions, 1);
8403 	CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
8404 	    " in pmap %p %lx", va, pmap, l3[0]);
8405 
8406 fail:
8407 	if (tmpl2 != 0) {
8408 		pmap_kremove(tmpl2);
8409 		kva_free(tmpl2, PAGE_SIZE);
8410 	}
8411 
8412 	return (l3);
8413 
8414 }
8415 
8416 static pt_entry_t *
pmap_demote_l2(pmap_t pmap,pt_entry_t * l2,vm_offset_t va)8417 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
8418 {
8419 	struct rwlock *lock;
8420 	pt_entry_t *l3;
8421 
8422 	lock = NULL;
8423 	l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
8424 	if (lock != NULL)
8425 		rw_wunlock(lock);
8426 	return (l3);
8427 }
8428 
8429 /*
8430  * Demote an L2C superpage mapping to L2C_ENTRIES L2 block mappings.
8431  */
8432 static bool
pmap_demote_l2c(pmap_t pmap,pt_entry_t * l2p,vm_offset_t va)8433 pmap_demote_l2c(pmap_t pmap, pt_entry_t *l2p, vm_offset_t va)
8434 {
8435 	pd_entry_t *l2c_end, *l2c_start, l2e, mask, nbits, *tl2p;
8436 	vm_offset_t tmpl3;
8437 	register_t intr;
8438 
8439 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
8440 	PMAP_ASSERT_STAGE1(pmap);
8441 	l2c_start = (pd_entry_t *)((uintptr_t)l2p & ~((L2C_ENTRIES *
8442 	    sizeof(pd_entry_t)) - 1));
8443 	l2c_end = l2c_start + L2C_ENTRIES;
8444 	tmpl3 = 0;
8445 	if ((va & ~L2C_OFFSET) < (vm_offset_t)l2c_end &&
8446 	    (vm_offset_t)l2c_start < (va & ~L2C_OFFSET) + L2C_SIZE) {
8447 		tmpl3 = kva_alloc(PAGE_SIZE);
8448 		if (tmpl3 == 0)
8449 			return (false);
8450 		pmap_kenter(tmpl3, PAGE_SIZE,
8451 		    DMAP_TO_PHYS((vm_offset_t)l2c_start) & ~L3_OFFSET,
8452 		    VM_MEMATTR_WRITE_BACK);
8453 		l2c_start = (pd_entry_t *)(tmpl3 +
8454 		    ((vm_offset_t)l2c_start & PAGE_MASK));
8455 		l2c_end = (pd_entry_t *)(tmpl3 +
8456 		    ((vm_offset_t)l2c_end & PAGE_MASK));
8457 	}
8458 	mask = 0;
8459 	nbits = ATTR_DESCR_VALID;
8460 	intr = intr_disable();
8461 
8462 	/*
8463 	 * Break the mappings.
8464 	 */
8465 	for (tl2p = l2c_start; tl2p < l2c_end; tl2p++) {
8466 		/*
8467 		 * Clear the mapping's contiguous and valid bits, but leave
8468 		 * the rest of the entry unchanged, so that a lockless,
8469 		 * concurrent pmap_kextract() can still lookup the physical
8470 		 * address.
8471 		 */
8472 		l2e = pmap_load(tl2p);
8473 		KASSERT((l2e & ATTR_CONTIGUOUS) != 0,
8474 		    ("pmap_demote_l2c: missing ATTR_CONTIGUOUS"));
8475 		KASSERT((l2e & (ATTR_SW_DBM | ATTR_S1_AP_RW_BIT)) !=
8476 		    (ATTR_SW_DBM | ATTR_S1_AP(ATTR_S1_AP_RO)),
8477 		    ("pmap_demote_l2c: missing ATTR_S1_AP_RW"));
8478 		while (!atomic_fcmpset_64(tl2p, &l2e, l2e & ~(ATTR_CONTIGUOUS |
8479 		    ATTR_DESCR_VALID)))
8480 			cpu_spinwait();
8481 
8482 		/*
8483 		 * Hardware accessed and dirty bit maintenance might only
8484 		 * update a single L2 entry, so we must combine the accessed
8485 		 * and dirty bits from this entire set of contiguous L2
8486 		 * entries.
8487 		 */
8488 		if ((l2e & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
8489 		    (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM))
8490 			mask = ATTR_S1_AP_RW_BIT;
8491 		nbits |= l2e & ATTR_AF;
8492 	}
8493 	if ((nbits & ATTR_AF) != 0) {
8494 		pmap_s1_invalidate_strided(pmap, va & ~L2C_OFFSET, (va +
8495 		    L2C_SIZE) & ~L2C_OFFSET, L2_SIZE, true);
8496 	}
8497 
8498 	/*
8499 	 * Remake the mappings, updating the accessed and dirty bits.
8500 	 */
8501 	for (tl2p = l2c_start; tl2p < l2c_end; tl2p++) {
8502 		l2e = pmap_load(tl2p);
8503 		while (!atomic_fcmpset_64(tl2p, &l2e, (l2e & ~mask) | nbits))
8504 			cpu_spinwait();
8505 	}
8506 	dsb(ishst);
8507 
8508 	intr_restore(intr);
8509 	if (tmpl3 != 0) {
8510 		pmap_kremove(tmpl3);
8511 		kva_free(tmpl3, PAGE_SIZE);
8512 	}
8513 	counter_u64_add(pmap_l2c_demotions, 1);
8514 	CTR2(KTR_PMAP, "pmap_demote_l2c: success for va %#lx in pmap %p",
8515 	    va, pmap);
8516 	return (true);
8517 }
8518 
8519 /*
8520  * Demote a L3C superpage mapping to L3C_ENTRIES 4KB page mappings.
8521  */
8522 static bool
pmap_demote_l3c(pmap_t pmap,pt_entry_t * l3p,vm_offset_t va)8523 pmap_demote_l3c(pmap_t pmap, pt_entry_t *l3p, vm_offset_t va)
8524 {
8525 	pt_entry_t *l3c_end, *l3c_start, l3e, mask, nbits, *tl3p;
8526 	vm_offset_t tmpl3;
8527 	register_t intr;
8528 
8529 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
8530 	l3c_start = (pt_entry_t *)((uintptr_t)l3p & ~((L3C_ENTRIES *
8531 	    sizeof(pt_entry_t)) - 1));
8532 	l3c_end = l3c_start + L3C_ENTRIES;
8533 	tmpl3 = 0;
8534 	if ((va & ~L3C_OFFSET) < (vm_offset_t)l3c_end &&
8535 	    (vm_offset_t)l3c_start < (va & ~L3C_OFFSET) + L3C_SIZE) {
8536 		tmpl3 = kva_alloc(PAGE_SIZE);
8537 		if (tmpl3 == 0)
8538 			return (false);
8539 		pmap_kenter(tmpl3, PAGE_SIZE,
8540 		    DMAP_TO_PHYS((vm_offset_t)l3c_start) & ~L3_OFFSET,
8541 		    VM_MEMATTR_WRITE_BACK);
8542 		l3c_start = (pt_entry_t *)(tmpl3 +
8543 		    ((vm_offset_t)l3c_start & PAGE_MASK));
8544 		l3c_end = (pt_entry_t *)(tmpl3 +
8545 		    ((vm_offset_t)l3c_end & PAGE_MASK));
8546 	}
8547 	mask = 0;
8548 	nbits = ATTR_DESCR_VALID;
8549 	intr = intr_disable();
8550 
8551 	/*
8552 	 * Break the mappings.
8553 	 */
8554 	for (tl3p = l3c_start; tl3p < l3c_end; tl3p++) {
8555 		/*
8556 		 * Clear the mapping's contiguous and valid bits, but leave
8557 		 * the rest of the entry unchanged, so that a lockless,
8558 		 * concurrent pmap_kextract() can still lookup the physical
8559 		 * address.
8560 		 */
8561 		l3e = pmap_load(tl3p);
8562 		KASSERT((l3e & ATTR_CONTIGUOUS) != 0,
8563 		    ("pmap_demote_l3c: missing ATTR_CONTIGUOUS"));
8564 		KASSERT((l3e & (ATTR_SW_DBM | ATTR_S1_AP_RW_BIT)) !=
8565 		    (ATTR_SW_DBM | ATTR_S1_AP(ATTR_S1_AP_RO)),
8566 		    ("pmap_demote_l3c: missing ATTR_S1_AP_RW"));
8567 		while (!atomic_fcmpset_64(tl3p, &l3e, l3e & ~(ATTR_CONTIGUOUS |
8568 		    ATTR_DESCR_VALID)))
8569 			cpu_spinwait();
8570 
8571 		/*
8572 		 * Hardware accessed and dirty bit maintenance might only
8573 		 * update a single L3 entry, so we must combine the accessed
8574 		 * and dirty bits from this entire set of contiguous L3
8575 		 * entries.
8576 		 */
8577 		if ((l3e & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
8578 		    (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM))
8579 			mask = ATTR_S1_AP_RW_BIT;
8580 		nbits |= l3e & ATTR_AF;
8581 	}
8582 	if ((nbits & ATTR_AF) != 0) {
8583 		pmap_invalidate_range(pmap, va & ~L3C_OFFSET, (va + L3C_SIZE) &
8584 		    ~L3C_OFFSET, true);
8585 	}
8586 
8587 	/*
8588 	 * Remake the mappings, updating the accessed and dirty bits.
8589 	 */
8590 	for (tl3p = l3c_start; tl3p < l3c_end; tl3p++) {
8591 		l3e = pmap_load(tl3p);
8592 		while (!atomic_fcmpset_64(tl3p, &l3e, (l3e & ~mask) | nbits))
8593 			cpu_spinwait();
8594 	}
8595 	dsb(ishst);
8596 
8597 	intr_restore(intr);
8598 	if (tmpl3 != 0) {
8599 		pmap_kremove(tmpl3);
8600 		kva_free(tmpl3, PAGE_SIZE);
8601 	}
8602 	counter_u64_add(pmap_l3c_demotions, 1);
8603 	CTR2(KTR_PMAP, "pmap_demote_l3c: success for va %#lx in pmap %p",
8604 	    va, pmap);
8605 	return (true);
8606 }
8607 
8608 /*
8609  * Accumulate the accessed and dirty bits within a L3C superpage and
8610  * return the specified PTE with them applied correctly.
8611  */
8612 static pt_entry_t
pmap_load_l3c(pt_entry_t * l3p)8613 pmap_load_l3c(pt_entry_t *l3p)
8614 {
8615 	pt_entry_t *l3c_end, *l3c_start, l3e, mask, nbits, *tl3p;
8616 
8617 	l3c_start = (pt_entry_t *)((uintptr_t)l3p & ~((L3C_ENTRIES *
8618 	    sizeof(pt_entry_t)) - 1));
8619 	l3c_end = l3c_start + L3C_ENTRIES;
8620 	mask = 0;
8621 	nbits = 0;
8622 	/* Iterate over each mapping in the superpage. */
8623 	for (tl3p = l3c_start; tl3p < l3c_end; tl3p++) {
8624 		l3e = pmap_load(tl3p);
8625 		KASSERT((l3e & ATTR_CONTIGUOUS) != 0,
8626 		    ("pmap_load_l3c: missing ATTR_CONTIGUOUS"));
8627 		/* Update mask if the current page has its dirty bit set. */
8628 		if ((l3e & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
8629 		    (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM))
8630 			mask = ATTR_S1_AP_RW_BIT;
8631 		/* Update nbits if the accessed bit is set. */
8632 		nbits |= l3e & ATTR_AF;
8633 	}
8634 	return ((pmap_load(l3p) & ~mask) | nbits);
8635 }
8636 
8637 /*
8638  * Perform the pmap work for mincore(2).  If the page is not both referenced and
8639  * modified by this pmap, returns its physical address so that the caller can
8640  * find other mappings.
8641  */
8642 int
pmap_mincore(pmap_t pmap,vm_offset_t addr,vm_paddr_t * pap)8643 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
8644 {
8645 	pt_entry_t *pte, tpte;
8646 	vm_paddr_t mask, pa;
8647 	int lvl, psind, val;
8648 	bool managed;
8649 
8650 	PMAP_ASSERT_STAGE1(pmap);
8651 	PMAP_LOCK(pmap);
8652 	pte = pmap_pte(pmap, addr, &lvl);
8653 	if (pte != NULL) {
8654 		tpte = pmap_load(pte);
8655 
8656 		switch (lvl) {
8657 		case 3:
8658 			mask = L3_OFFSET;
8659 			psind = (tpte & ATTR_CONTIGUOUS) != 0 ? 1 : 0;
8660 			break;
8661 		case 2:
8662 			mask = L2_OFFSET;
8663 			psind = 2;
8664 			break;
8665 		case 1:
8666 			mask = L1_OFFSET;
8667 			psind = 3;
8668 			break;
8669 		default:
8670 			panic("pmap_mincore: invalid level %d", lvl);
8671 		}
8672 
8673 		managed = (tpte & ATTR_SW_MANAGED) != 0;
8674 		val = MINCORE_INCORE | MINCORE_PSIND(psind);
8675 		if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
8676 		    (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
8677 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
8678 		if ((tpte & ATTR_AF) == ATTR_AF)
8679 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
8680 
8681 		pa = PTE_TO_PHYS(tpte) | (addr & mask);
8682 	} else {
8683 		managed = false;
8684 		val = 0;
8685 	}
8686 
8687 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
8688 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
8689 		*pap = pa;
8690 	}
8691 	PMAP_UNLOCK(pmap);
8692 	return (val);
8693 }
8694 
8695 /*
8696  * Garbage collect every ASID that is neither active on a processor nor
8697  * reserved.
8698  */
8699 static void
pmap_reset_asid_set(pmap_t pmap)8700 pmap_reset_asid_set(pmap_t pmap)
8701 {
8702 	pmap_t curpmap;
8703 	int asid, cpuid, epoch;
8704 	struct asid_set *set;
8705 	enum pmap_stage stage;
8706 
8707 	set = pmap->pm_asid_set;
8708 	stage = pmap->pm_stage;
8709 
8710 	set = pmap->pm_asid_set;
8711 	KASSERT(set != NULL, ("%s: NULL asid set", __func__));
8712 	mtx_assert(&set->asid_set_mutex, MA_OWNED);
8713 
8714 	/*
8715 	 * Ensure that the store to asid_epoch is globally visible before the
8716 	 * loads from pc_curpmap are performed.
8717 	 */
8718 	epoch = set->asid_epoch + 1;
8719 	if (epoch == INT_MAX)
8720 		epoch = 0;
8721 	set->asid_epoch = epoch;
8722 	dsb(ishst);
8723 	if (stage == PM_STAGE1) {
8724 		__asm __volatile("tlbi vmalle1is");
8725 	} else {
8726 		KASSERT(pmap_clean_stage2_tlbi != NULL,
8727 		    ("%s: Unset stage 2 tlb invalidation callback\n",
8728 		    __func__));
8729 		pmap_clean_stage2_tlbi();
8730 	}
8731 	dsb(ish);
8732 	bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
8733 	    set->asid_set_size - 1);
8734 	CPU_FOREACH(cpuid) {
8735 		if (cpuid == curcpu)
8736 			continue;
8737 		if (stage == PM_STAGE1) {
8738 			curpmap = pcpu_find(cpuid)->pc_curpmap;
8739 			PMAP_ASSERT_STAGE1(pmap);
8740 		} else {
8741 			curpmap = pcpu_find(cpuid)->pc_curvmpmap;
8742 			if (curpmap == NULL)
8743 				continue;
8744 			PMAP_ASSERT_STAGE2(pmap);
8745 		}
8746 		KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
8747 		asid = COOKIE_TO_ASID(curpmap->pm_cookie);
8748 		if (asid == -1)
8749 			continue;
8750 		bit_set(set->asid_set, asid);
8751 		curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
8752 	}
8753 }
8754 
8755 /*
8756  * Allocate a new ASID for the specified pmap.
8757  */
8758 static void
pmap_alloc_asid(pmap_t pmap)8759 pmap_alloc_asid(pmap_t pmap)
8760 {
8761 	struct asid_set *set;
8762 	int new_asid;
8763 
8764 	set = pmap->pm_asid_set;
8765 	KASSERT(set != NULL, ("%s: NULL asid set", __func__));
8766 
8767 	mtx_lock_spin(&set->asid_set_mutex);
8768 
8769 	/*
8770 	 * While this processor was waiting to acquire the asid set mutex,
8771 	 * pmap_reset_asid_set() running on another processor might have
8772 	 * updated this pmap's cookie to the current epoch.  In which case, we
8773 	 * don't need to allocate a new ASID.
8774 	 */
8775 	if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
8776 		goto out;
8777 
8778 	bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
8779 	    &new_asid);
8780 	if (new_asid == -1) {
8781 		bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
8782 		    set->asid_next, &new_asid);
8783 		if (new_asid == -1) {
8784 			pmap_reset_asid_set(pmap);
8785 			bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
8786 			    set->asid_set_size, &new_asid);
8787 			KASSERT(new_asid != -1, ("ASID allocation failure"));
8788 		}
8789 	}
8790 	bit_set(set->asid_set, new_asid);
8791 	set->asid_next = new_asid + 1;
8792 	pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
8793 out:
8794 	mtx_unlock_spin(&set->asid_set_mutex);
8795 }
8796 
8797 static uint64_t __read_mostly ttbr_flags;
8798 
8799 /*
8800  * Compute the value that should be stored in ttbr0 to activate the specified
8801  * pmap.  This value may change from time to time.
8802  */
8803 uint64_t
pmap_to_ttbr0(pmap_t pmap)8804 pmap_to_ttbr0(pmap_t pmap)
8805 {
8806 	uint64_t ttbr;
8807 
8808 	ttbr = pmap->pm_ttbr;
8809 	ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
8810 	ttbr |= ttbr_flags;
8811 
8812 	return (ttbr);
8813 }
8814 
8815 static void
pmap_set_cnp(void * arg)8816 pmap_set_cnp(void *arg)
8817 {
8818 	uint64_t ttbr0, ttbr1;
8819 	u_int cpuid;
8820 
8821 	cpuid = *(u_int *)arg;
8822 	if (cpuid == curcpu) {
8823 		/*
8824 		 * Set the flags while all CPUs are handling the
8825 		 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
8826 		 * to pmap_to_ttbr0 after this will have the CnP flag set.
8827 		 * The dsb after invalidating the TLB will act as a barrier
8828 		 * to ensure all CPUs can observe this change.
8829 		 */
8830 		ttbr_flags |= TTBR_CnP;
8831 	}
8832 
8833 	ttbr0 = READ_SPECIALREG(ttbr0_el1);
8834 	ttbr0 |= TTBR_CnP;
8835 
8836 	ttbr1 = READ_SPECIALREG(ttbr1_el1);
8837 	ttbr1 |= TTBR_CnP;
8838 
8839 	/* Update ttbr{0,1}_el1 with the CnP flag */
8840 	WRITE_SPECIALREG(ttbr0_el1, ttbr0);
8841 	WRITE_SPECIALREG(ttbr1_el1, ttbr1);
8842 	isb();
8843 	__asm __volatile("tlbi vmalle1is");
8844 	dsb(ish);
8845 	isb();
8846 }
8847 
8848 /*
8849  * Defer enabling some features until we have read the ID registers to know
8850  * if they are supported on all CPUs.
8851  */
8852 static void
pmap_init_mp(void * dummy __unused)8853 pmap_init_mp(void *dummy __unused)
8854 {
8855 	uint64_t reg;
8856 
8857 	if (get_kernel_reg(ID_AA64PFR1_EL1, &reg)) {
8858 		if (ID_AA64PFR1_BT_VAL(reg) != ID_AA64PFR1_BT_NONE) {
8859 			if (bootverbose)
8860 				printf("Enabling BTI\n");
8861 			pmap_bti_support = true;
8862 
8863 			pmap_bti_ranges_zone = uma_zcreate("BTI ranges",
8864 			    sizeof(struct rs_el), NULL, NULL, NULL, NULL,
8865 			    UMA_ALIGN_PTR, 0);
8866 		}
8867 	}
8868 }
8869 SYSINIT(pmap_init_mp, SI_SUB_CPU, SI_ORDER_ANY, pmap_init_mp, NULL);
8870 
8871 /*
8872  * Defer enabling CnP until we have read the ID registers to know if it's
8873  * supported on all CPUs.
8874  */
8875 static void
pmap_init_cnp(void * dummy __unused)8876 pmap_init_cnp(void *dummy __unused)
8877 {
8878 	uint64_t reg;
8879 	u_int cpuid;
8880 
8881 	if (!get_kernel_reg(ID_AA64MMFR2_EL1, &reg))
8882 		return;
8883 
8884 	if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
8885 		if (bootverbose)
8886 			printf("Enabling CnP\n");
8887 		cpuid = curcpu;
8888 		smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
8889 	}
8890 
8891 }
8892 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
8893 
8894 static bool
pmap_activate_int(pmap_t pmap)8895 pmap_activate_int(pmap_t pmap)
8896 {
8897 	struct asid_set *set;
8898 	int epoch;
8899 
8900 	KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
8901 	KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
8902 
8903 	if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
8904 	    (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
8905 		/*
8906 		 * Handle the possibility that the old thread was preempted
8907 		 * after an "ic" or "tlbi" instruction but before it performed
8908 		 * a "dsb" instruction.  If the old thread migrates to a new
8909 		 * processor, its completion of a "dsb" instruction on that
8910 		 * new processor does not guarantee that the "ic" or "tlbi"
8911 		 * instructions performed on the old processor have completed.
8912 		 */
8913 		dsb(ish);
8914 		return (false);
8915 	}
8916 
8917 	set = pmap->pm_asid_set;
8918 	KASSERT(set != NULL, ("%s: NULL asid set", __func__));
8919 
8920 	/*
8921 	 * Ensure that the store to curpmap is globally visible before the
8922 	 * load from asid_epoch is performed.
8923 	 */
8924 	if (pmap->pm_stage == PM_STAGE1)
8925 		PCPU_SET(curpmap, pmap);
8926 	else
8927 		PCPU_SET(curvmpmap, pmap);
8928 	dsb(ish);
8929 	epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
8930 	if (epoch >= 0 && epoch != set->asid_epoch)
8931 		pmap_alloc_asid(pmap);
8932 
8933 	if (pmap->pm_stage == PM_STAGE1) {
8934 		set_ttbr0(pmap_to_ttbr0(pmap));
8935 		if (PCPU_GET(bcast_tlbi_workaround) != 0)
8936 			invalidate_local_icache();
8937 	}
8938 	return (true);
8939 }
8940 
8941 void
pmap_activate_vm(pmap_t pmap)8942 pmap_activate_vm(pmap_t pmap)
8943 {
8944 
8945 	PMAP_ASSERT_STAGE2(pmap);
8946 
8947 	(void)pmap_activate_int(pmap);
8948 }
8949 
8950 void
pmap_activate(struct thread * td)8951 pmap_activate(struct thread *td)
8952 {
8953 	pmap_t	pmap;
8954 
8955 	pmap = vmspace_pmap(td->td_proc->p_vmspace);
8956 	PMAP_ASSERT_STAGE1(pmap);
8957 	critical_enter();
8958 	(void)pmap_activate_int(pmap);
8959 	critical_exit();
8960 }
8961 
8962 /*
8963  * Activate the thread we are switching to.
8964  * To simplify the assembly in cpu_throw return the new threads pcb.
8965  */
8966 struct pcb *
pmap_switch(struct thread * new)8967 pmap_switch(struct thread *new)
8968 {
8969 	pcpu_bp_harden bp_harden;
8970 	struct pcb *pcb;
8971 
8972 	/* Store the new curthread */
8973 	PCPU_SET(curthread, new);
8974 
8975 	/* And the new pcb */
8976 	pcb = new->td_pcb;
8977 	PCPU_SET(curpcb, pcb);
8978 
8979 	/*
8980 	 * TODO: We may need to flush the cache here if switching
8981 	 * to a user process.
8982 	 */
8983 
8984 	if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
8985 		/*
8986 		 * Stop userspace from training the branch predictor against
8987 		 * other processes. This will call into a CPU specific
8988 		 * function that clears the branch predictor state.
8989 		 */
8990 		bp_harden = PCPU_GET(bp_harden);
8991 		if (bp_harden != NULL)
8992 			bp_harden();
8993 	}
8994 
8995 	return (pcb);
8996 }
8997 
8998 void
pmap_sync_icache(pmap_t pmap,vm_offset_t va,vm_size_t sz)8999 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
9000 {
9001 
9002 	PMAP_ASSERT_STAGE1(pmap);
9003 	KASSERT(ADDR_IS_CANONICAL(va),
9004 	    ("%s: Address not in canonical form: %lx", __func__, va));
9005 
9006 	if (ADDR_IS_KERNEL(va)) {
9007 		cpu_icache_sync_range((void *)va, sz);
9008 	} else {
9009 		u_int len, offset;
9010 		vm_paddr_t pa;
9011 
9012 		/* Find the length of data in this page to flush */
9013 		offset = va & PAGE_MASK;
9014 		len = imin(PAGE_SIZE - offset, sz);
9015 
9016 		while (sz != 0) {
9017 			/* Extract the physical address & find it in the DMAP */
9018 			pa = pmap_extract(pmap, va);
9019 			if (pa != 0)
9020 				cpu_icache_sync_range((void *)PHYS_TO_DMAP(pa),
9021 				    len);
9022 
9023 			/* Move to the next page */
9024 			sz -= len;
9025 			va += len;
9026 			/* Set the length for the next iteration */
9027 			len = imin(PAGE_SIZE, sz);
9028 		}
9029 	}
9030 }
9031 
9032 static int
pmap_stage2_fault(pmap_t pmap,uint64_t esr,uint64_t far)9033 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
9034 {
9035 	pd_entry_t *pdep;
9036 	pt_entry_t *ptep, pte;
9037 	int rv, lvl, dfsc;
9038 
9039 	PMAP_ASSERT_STAGE2(pmap);
9040 	rv = KERN_FAILURE;
9041 
9042 	/* Data and insn aborts use same encoding for FSC field. */
9043 	dfsc = esr & ISS_DATA_DFSC_MASK;
9044 	switch (dfsc) {
9045 	case ISS_DATA_DFSC_TF_L0:
9046 	case ISS_DATA_DFSC_TF_L1:
9047 	case ISS_DATA_DFSC_TF_L2:
9048 	case ISS_DATA_DFSC_TF_L3:
9049 		PMAP_LOCK(pmap);
9050 		pdep = pmap_pde(pmap, far, &lvl);
9051 		if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
9052 			PMAP_UNLOCK(pmap);
9053 			break;
9054 		}
9055 
9056 		switch (lvl) {
9057 		case 0:
9058 			ptep = pmap_l0_to_l1(pdep, far);
9059 			break;
9060 		case 1:
9061 			ptep = pmap_l1_to_l2(pdep, far);
9062 			break;
9063 		case 2:
9064 			ptep = pmap_l2_to_l3(pdep, far);
9065 			break;
9066 		default:
9067 			panic("%s: Invalid pde level %d", __func__,lvl);
9068 		}
9069 		goto fault_exec;
9070 
9071 	case ISS_DATA_DFSC_AFF_L1:
9072 	case ISS_DATA_DFSC_AFF_L2:
9073 	case ISS_DATA_DFSC_AFF_L3:
9074 		PMAP_LOCK(pmap);
9075 		ptep = pmap_pte(pmap, far, &lvl);
9076 fault_exec:
9077 		if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
9078 			/*
9079 			 * If accessing an executable page invalidate
9080 			 * the I-cache so it will be valid when we
9081 			 * continue execution in the guest. The D-cache
9082 			 * is assumed to already be clean to the Point
9083 			 * of Coherency.
9084 			 */
9085 			if ((pte & ATTR_S2_XN_MASK) !=
9086 			    ATTR_S2_XN(ATTR_S2_XN_NONE)) {
9087 				invalidate_icache();
9088 			}
9089 			pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
9090 			rv = KERN_SUCCESS;
9091 		}
9092 		PMAP_UNLOCK(pmap);
9093 		break;
9094 	}
9095 
9096 	return (rv);
9097 }
9098 
9099 int
pmap_fault(pmap_t pmap,uint64_t esr,uint64_t far)9100 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
9101 {
9102 	pt_entry_t pte, *ptep;
9103 	register_t intr;
9104 	uint64_t ec, par;
9105 	int lvl, rv;
9106 
9107 	rv = KERN_FAILURE;
9108 
9109 	ec = ESR_ELx_EXCEPTION(esr);
9110 	switch (ec) {
9111 	case EXCP_INSN_ABORT_L:
9112 	case EXCP_INSN_ABORT:
9113 	case EXCP_DATA_ABORT_L:
9114 	case EXCP_DATA_ABORT:
9115 		break;
9116 	default:
9117 		return (rv);
9118 	}
9119 
9120 	if (pmap->pm_stage == PM_STAGE2)
9121 		return (pmap_stage2_fault(pmap, esr, far));
9122 
9123 	/* Data and insn aborts use same encoding for FSC field. */
9124 	switch (esr & ISS_DATA_DFSC_MASK) {
9125 	case ISS_DATA_DFSC_AFF_L1:
9126 	case ISS_DATA_DFSC_AFF_L2:
9127 	case ISS_DATA_DFSC_AFF_L3:
9128 		PMAP_LOCK(pmap);
9129 		ptep = pmap_pte(pmap, far, &lvl);
9130 		if (ptep != NULL) {
9131 			pmap_set_bits(ptep, ATTR_AF);
9132 			rv = KERN_SUCCESS;
9133 			/*
9134 			 * XXXMJ as an optimization we could mark the entry
9135 			 * dirty if this is a write fault.
9136 			 */
9137 		}
9138 		PMAP_UNLOCK(pmap);
9139 		break;
9140 	case ISS_DATA_DFSC_PF_L1:
9141 	case ISS_DATA_DFSC_PF_L2:
9142 	case ISS_DATA_DFSC_PF_L3:
9143 		if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
9144 		    (esr & ISS_DATA_WnR) == 0)
9145 			return (rv);
9146 		PMAP_LOCK(pmap);
9147 		ptep = pmap_pte(pmap, far, &lvl);
9148 		if (ptep != NULL &&
9149 		    ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
9150 			if ((pte & ATTR_S1_AP_RW_BIT) ==
9151 			    ATTR_S1_AP(ATTR_S1_AP_RO)) {
9152 				pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
9153 				pmap_s1_invalidate_page(pmap, far, true);
9154 			}
9155 			rv = KERN_SUCCESS;
9156 		}
9157 		PMAP_UNLOCK(pmap);
9158 		break;
9159 	case ISS_DATA_DFSC_TF_L0:
9160 	case ISS_DATA_DFSC_TF_L1:
9161 	case ISS_DATA_DFSC_TF_L2:
9162 	case ISS_DATA_DFSC_TF_L3:
9163 		/*
9164 		 * Retry the translation.  A break-before-make sequence can
9165 		 * produce a transient fault.
9166 		 */
9167 		if (pmap == kernel_pmap) {
9168 			/*
9169 			 * The translation fault may have occurred within a
9170 			 * critical section.  Therefore, we must check the
9171 			 * address without acquiring the kernel pmap's lock.
9172 			 */
9173 			if (pmap_klookup(far, NULL))
9174 				rv = KERN_SUCCESS;
9175 		} else {
9176 			bool owned;
9177 
9178 			/*
9179 			 * In the EFIRT driver we lock the pmap before
9180 			 * calling into the runtime service. As the lock
9181 			 * is already owned by the current thread skip
9182 			 * locking it again.
9183 			 */
9184 			owned = PMAP_OWNED(pmap);
9185 			if (!owned)
9186 				PMAP_LOCK(pmap);
9187 			/* Ask the MMU to check the address. */
9188 			intr = intr_disable();
9189 			par = arm64_address_translate_s1e0r(far);
9190 			intr_restore(intr);
9191 			if (!owned)
9192 				PMAP_UNLOCK(pmap);
9193 
9194 			/*
9195 			 * If the translation was successful, then we can
9196 			 * return success to the trap handler.
9197 			 */
9198 			if (PAR_SUCCESS(par))
9199 				rv = KERN_SUCCESS;
9200 		}
9201 		break;
9202 	}
9203 
9204 	return (rv);
9205 }
9206 
9207 /*
9208  *	Increase the starting virtual address of the given mapping if a
9209  *	different alignment might result in more superpage mappings.
9210  */
9211 void
pmap_align_superpage(vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t size)9212 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
9213     vm_offset_t *addr, vm_size_t size)
9214 {
9215 	vm_offset_t superpage_offset;
9216 
9217 	if (size < L3C_SIZE)
9218 		return;
9219 	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
9220 		offset += ptoa(object->pg_color);
9221 
9222 	/*
9223 	 * Considering the object's physical alignment, is the mapping large
9224 	 * enough to encompass an L2 (2MB/32MB) superpage ...
9225 	 */
9226 	superpage_offset = offset & L2_OFFSET;
9227 	if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) >= L2_SIZE) {
9228 		/*
9229 		 * If the virtual and physical alignments differ, then
9230 		 * increase the virtual address so that the alignments match.
9231 		 */
9232 		if ((*addr & L2_OFFSET) < superpage_offset)
9233 			*addr = (*addr & ~L2_OFFSET) + superpage_offset;
9234 		else if ((*addr & L2_OFFSET) > superpage_offset)
9235 			*addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) +
9236 			    superpage_offset;
9237 		return;
9238 	}
9239 	/* ... or an L3C (64KB/2MB) superpage? */
9240 	superpage_offset = offset & L3C_OFFSET;
9241 	if (size - ((L3C_SIZE - superpage_offset) & L3C_OFFSET) >= L3C_SIZE) {
9242 		if ((*addr & L3C_OFFSET) < superpage_offset)
9243 			*addr = (*addr & ~L3C_OFFSET) + superpage_offset;
9244 		else if ((*addr & L3C_OFFSET) > superpage_offset)
9245 			*addr = ((*addr + L3C_OFFSET) & ~L3C_OFFSET) +
9246 			    superpage_offset;
9247 	}
9248 }
9249 
9250 /**
9251  * Get the kernel virtual address of a set of physical pages. If there are
9252  * physical addresses not covered by the DMAP perform a transient mapping
9253  * that will be removed when calling pmap_unmap_io_transient.
9254  *
9255  * \param page        The pages the caller wishes to obtain the virtual
9256  *                    address on the kernel memory map.
9257  * \param vaddr       On return contains the kernel virtual memory address
9258  *                    of the pages passed in the page parameter.
9259  * \param count       Number of pages passed in.
9260  * \param can_fault   true if the thread using the mapped pages can take
9261  *                    page faults, false otherwise.
9262  *
9263  * \returns true if the caller must call pmap_unmap_io_transient when
9264  *          finished or false otherwise.
9265  *
9266  */
9267 bool
pmap_map_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)9268 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
9269     bool can_fault)
9270 {
9271 	vm_paddr_t paddr;
9272 	bool needs_mapping;
9273 	int error __diagused, i;
9274 
9275 	/*
9276 	 * Allocate any KVA space that we need, this is done in a separate
9277 	 * loop to prevent calling vmem_alloc while pinned.
9278 	 */
9279 	needs_mapping = false;
9280 	for (i = 0; i < count; i++) {
9281 		paddr = VM_PAGE_TO_PHYS(page[i]);
9282 		if (__predict_false(!PHYS_IN_DMAP(paddr))) {
9283 			error = vmem_alloc(kernel_arena, PAGE_SIZE,
9284 			    M_BESTFIT | M_WAITOK, &vaddr[i]);
9285 			KASSERT(error == 0, ("vmem_alloc failed: %d", error));
9286 			needs_mapping = true;
9287 		} else {
9288 			vaddr[i] = PHYS_TO_DMAP(paddr);
9289 		}
9290 	}
9291 
9292 	/* Exit early if everything is covered by the DMAP */
9293 	if (!needs_mapping)
9294 		return (false);
9295 
9296 	if (!can_fault)
9297 		sched_pin();
9298 	for (i = 0; i < count; i++) {
9299 		paddr = VM_PAGE_TO_PHYS(page[i]);
9300 		if (!PHYS_IN_DMAP(paddr)) {
9301 			panic(
9302 			   "pmap_map_io_transient: TODO: Map out of DMAP data");
9303 		}
9304 	}
9305 
9306 	return (needs_mapping);
9307 }
9308 
9309 void
pmap_unmap_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)9310 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
9311     bool can_fault)
9312 {
9313 	vm_paddr_t paddr;
9314 	int i;
9315 
9316 	if (!can_fault)
9317 		sched_unpin();
9318 	for (i = 0; i < count; i++) {
9319 		paddr = VM_PAGE_TO_PHYS(page[i]);
9320 		if (!PHYS_IN_DMAP(paddr)) {
9321 			panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
9322 		}
9323 	}
9324 }
9325 
9326 bool
pmap_is_valid_memattr(pmap_t pmap __unused,vm_memattr_t mode)9327 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
9328 {
9329 
9330 	return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
9331 }
9332 
9333 static void *
bti_dup_range(void * ctx __unused,void * data)9334 bti_dup_range(void *ctx __unused, void *data)
9335 {
9336 	struct rs_el *node, *new_node;
9337 
9338 	new_node = uma_zalloc(pmap_bti_ranges_zone, M_NOWAIT);
9339 	if (new_node == NULL)
9340 		return (NULL);
9341 	node = data;
9342 	memcpy(new_node, node, sizeof(*node));
9343 	return (new_node);
9344 }
9345 
9346 static void
bti_free_range(void * ctx __unused,void * node)9347 bti_free_range(void *ctx __unused, void *node)
9348 {
9349 
9350 	uma_zfree(pmap_bti_ranges_zone, node);
9351 }
9352 
9353 static int
pmap_bti_assign(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)9354 pmap_bti_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
9355 {
9356 	struct rs_el *rs;
9357 	int error;
9358 
9359 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9360 	PMAP_ASSERT_STAGE1(pmap);
9361 	MPASS(pmap->pm_bti != NULL);
9362 	rs = uma_zalloc(pmap_bti_ranges_zone, M_NOWAIT);
9363 	if (rs == NULL)
9364 		return (ENOMEM);
9365 	error = rangeset_insert(pmap->pm_bti, sva, eva, rs);
9366 	if (error != 0)
9367 		uma_zfree(pmap_bti_ranges_zone, rs);
9368 	return (error);
9369 }
9370 
9371 static void
pmap_bti_deassign_all(pmap_t pmap)9372 pmap_bti_deassign_all(pmap_t pmap)
9373 {
9374 
9375 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9376 	if (pmap->pm_bti != NULL)
9377 		rangeset_remove_all(pmap->pm_bti);
9378 }
9379 
9380 /*
9381  * Returns true if the BTI setting is the same across the specified address
9382  * range, and false otherwise.  When returning true, updates the referenced PTE
9383  * to reflect the BTI setting.
9384  *
9385  * Only stage 1 pmaps support BTI.  The kernel pmap is always a stage 1 pmap
9386  * that has the same BTI setting implicitly across its entire address range.
9387  */
9388 static bool
pmap_bti_same(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pt_entry_t * pte)9389 pmap_bti_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t *pte)
9390 {
9391 	struct rs_el *rs;
9392 	vm_offset_t va;
9393 
9394 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9395 	KASSERT(ADDR_IS_CANONICAL(sva),
9396 	    ("%s: Start address not in canonical form: %lx", __func__, sva));
9397 	KASSERT(ADDR_IS_CANONICAL(eva),
9398 	    ("%s: End address not in canonical form: %lx", __func__, eva));
9399 	KASSERT((*pte & ATTR_S1_GP) == 0,
9400 	    ("%s: pte %lx has ATTR_S1_GP preset", __func__, *pte));
9401 
9402 	if (pmap == kernel_pmap) {
9403 		*pte |= ATTR_KERN_GP;
9404 		return (true);
9405 	}
9406 	if (pmap->pm_bti == NULL)
9407 		return (true);
9408 	PMAP_ASSERT_STAGE1(pmap);
9409 	rs = rangeset_containing(pmap->pm_bti, sva);
9410 	if (rs == NULL)
9411 		return (rangeset_empty(pmap->pm_bti, sva, eva));
9412 	while ((va = rs->re_end) < eva) {
9413 		if ((rs = rangeset_beginning(pmap->pm_bti, va)) == NULL)
9414 			return (false);
9415 	}
9416 	*pte |= ATTR_S1_GP;
9417 	return (true);
9418 }
9419 
9420 static pt_entry_t
pmap_pte_bti(pmap_t pmap,vm_offset_t va)9421 pmap_pte_bti(pmap_t pmap, vm_offset_t va)
9422 {
9423 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9424 	MPASS(ADDR_IS_CANONICAL(va));
9425 
9426 	if (pmap->pm_stage != PM_STAGE1)
9427 		return (0);
9428 	if (pmap == kernel_pmap)
9429 		return (ATTR_KERN_GP);
9430 	if (pmap->pm_bti != NULL &&
9431 	    rangeset_containing(pmap->pm_bti, va) != NULL)
9432 		return (ATTR_S1_GP);
9433 	return (0);
9434 }
9435 
9436 static void
pmap_bti_on_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)9437 pmap_bti_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
9438 {
9439 
9440 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9441 	if (pmap->pm_bti != NULL)
9442 		rangeset_remove(pmap->pm_bti, sva, eva);
9443 }
9444 
9445 static int
pmap_bti_copy(pmap_t dst_pmap,pmap_t src_pmap)9446 pmap_bti_copy(pmap_t dst_pmap, pmap_t src_pmap)
9447 {
9448 
9449 	PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
9450 	PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
9451 	MPASS(src_pmap->pm_stage == dst_pmap->pm_stage);
9452 	MPASS(src_pmap->pm_bti != NULL);
9453 	MPASS(dst_pmap->pm_bti != NULL);
9454 	if (src_pmap->pm_bti->rs_data_ctx == NULL)
9455 		return (0);
9456 	return (rangeset_copy(dst_pmap->pm_bti, src_pmap->pm_bti));
9457 }
9458 
9459 static void
pmap_bti_update_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool set)9460 pmap_bti_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool set)
9461 {
9462 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9463 	PMAP_ASSERT_STAGE1(pmap);
9464 
9465 	pmap_mask_set_locked(pmap, sva, eva, ATTR_S1_GP, set ? ATTR_S1_GP : 0,
9466 	    true);
9467 }
9468 
9469 int
pmap_bti_set(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)9470 pmap_bti_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
9471 {
9472 	int error;
9473 
9474 	if (pmap->pm_bti == NULL)
9475 		return (0);
9476 	if (!ADDR_IS_CANONICAL(sva) || !ADDR_IS_CANONICAL(eva))
9477 		return (EINVAL);
9478 	if (pmap->pm_stage != PM_STAGE1)
9479 		return (EINVAL);
9480 	if (eva <= sva || ADDR_IS_KERNEL(eva))
9481 		return (EFAULT);
9482 
9483 	sva = trunc_page(sva);
9484 	eva = round_page(eva);
9485 	for (;;) {
9486 		PMAP_LOCK(pmap);
9487 		error = pmap_bti_assign(pmap, sva, eva);
9488 		if (error == 0)
9489 			pmap_bti_update_range(pmap, sva, eva, true);
9490 		PMAP_UNLOCK(pmap);
9491 		if (error != ENOMEM)
9492 			break;
9493 		vm_wait(NULL);
9494 	}
9495 	return (error);
9496 }
9497 
9498 #if defined(KASAN) || defined(KMSAN)
9499 static pd_entry_t	*pmap_san_early_l2;
9500 
9501 #define	SAN_BOOTSTRAP_L2_SIZE	(1 * L2_SIZE)
9502 #define	SAN_BOOTSTRAP_SIZE	(2 * PAGE_SIZE)
9503 static vm_offset_t __nosanitizeaddress
pmap_san_enter_bootstrap_alloc_l2(void)9504 pmap_san_enter_bootstrap_alloc_l2(void)
9505 {
9506 	static uint8_t bootstrap_data[SAN_BOOTSTRAP_L2_SIZE] __aligned(L2_SIZE);
9507 	static size_t offset = 0;
9508 	vm_offset_t addr;
9509 
9510 	if (offset + L2_SIZE > sizeof(bootstrap_data)) {
9511 		panic("%s: out of memory for the bootstrap shadow map L2 entries",
9512 		    __func__);
9513 	}
9514 
9515 	addr = (uintptr_t)&bootstrap_data[offset];
9516 	offset += L2_SIZE;
9517 	return (addr);
9518 }
9519 
9520 /*
9521  * SAN L1 + L2 pages, maybe L3 entries later?
9522  */
9523 static vm_offset_t __nosanitizeaddress
pmap_san_enter_bootstrap_alloc_pages(int npages)9524 pmap_san_enter_bootstrap_alloc_pages(int npages)
9525 {
9526 	static uint8_t bootstrap_data[SAN_BOOTSTRAP_SIZE] __aligned(PAGE_SIZE);
9527 	static size_t offset = 0;
9528 	vm_offset_t addr;
9529 
9530 	if (offset + (npages * PAGE_SIZE) > sizeof(bootstrap_data)) {
9531 		panic("%s: out of memory for the bootstrap shadow map",
9532 		    __func__);
9533 	}
9534 
9535 	addr = (uintptr_t)&bootstrap_data[offset];
9536 	offset += (npages * PAGE_SIZE);
9537 	return (addr);
9538 }
9539 
9540 static void __nosanitizeaddress
pmap_san_enter_bootstrap(void)9541 pmap_san_enter_bootstrap(void)
9542 {
9543 	vm_offset_t freemempos;
9544 
9545 	/* L1, L2 */
9546 	freemempos = pmap_san_enter_bootstrap_alloc_pages(2);
9547 	bs_state.freemempos = freemempos;
9548 	bs_state.va = KASAN_MIN_ADDRESS;
9549 	pmap_bootstrap_l1_table(&bs_state);
9550 	pmap_san_early_l2 = bs_state.l2;
9551 }
9552 
9553 static vm_page_t
pmap_san_enter_alloc_l3(void)9554 pmap_san_enter_alloc_l3(void)
9555 {
9556 	vm_page_t m;
9557 
9558 	m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
9559 	    VM_ALLOC_ZERO);
9560 	if (m == NULL)
9561 		panic("%s: no memory to grow shadow map", __func__);
9562 	return (m);
9563 }
9564 
9565 static vm_page_t
pmap_san_enter_alloc_l2(void)9566 pmap_san_enter_alloc_l2(void)
9567 {
9568 	return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
9569 	    Ln_ENTRIES, 0, ~0ul, L2_SIZE, 0, VM_MEMATTR_DEFAULT));
9570 }
9571 
9572 void __nosanitizeaddress __nosanitizememory
pmap_san_enter(vm_offset_t va)9573 pmap_san_enter(vm_offset_t va)
9574 {
9575 	pd_entry_t *l1, *l2;
9576 	pt_entry_t *l3;
9577 	vm_page_t m;
9578 
9579 	if (virtual_avail == 0) {
9580 		vm_offset_t block;
9581 		int slot;
9582 		bool first;
9583 
9584 		/* Temporary shadow map prior to pmap_bootstrap(). */
9585 		first = pmap_san_early_l2 == NULL;
9586 		if (first)
9587 			pmap_san_enter_bootstrap();
9588 
9589 		l2 = pmap_san_early_l2;
9590 		slot = pmap_l2_index(va);
9591 
9592 		if ((pmap_load(&l2[slot]) & ATTR_DESCR_VALID) == 0) {
9593 			MPASS(first);
9594 			block = pmap_san_enter_bootstrap_alloc_l2();
9595 			pmap_store(&l2[slot],
9596 			    PHYS_TO_PTE(pmap_early_vtophys(block)) |
9597 			    PMAP_SAN_PTE_BITS | L2_BLOCK);
9598 			dmb(ishst);
9599 		}
9600 
9601 		return;
9602 	}
9603 
9604 	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
9605 	l1 = pmap_l1(kernel_pmap, va);
9606 	MPASS(l1 != NULL);
9607 	if ((pmap_load(l1) & ATTR_DESCR_VALID) == 0) {
9608 		m = pmap_san_enter_alloc_l3();
9609 		pmap_store(l1, VM_PAGE_TO_PTE(m) | L1_TABLE);
9610 	}
9611 	l2 = pmap_l1_to_l2(l1, va);
9612 	if ((pmap_load(l2) & ATTR_DESCR_VALID) == 0) {
9613 		m = pmap_san_enter_alloc_l2();
9614 		if (m != NULL) {
9615 			pmap_store(l2, VM_PAGE_TO_PTE(m) |
9616 			    PMAP_SAN_PTE_BITS | L2_BLOCK);
9617 		} else {
9618 			m = pmap_san_enter_alloc_l3();
9619 			pmap_store(l2, VM_PAGE_TO_PTE(m) | L2_TABLE);
9620 		}
9621 		dmb(ishst);
9622 	}
9623 	if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK)
9624 		return;
9625 	l3 = pmap_l2_to_l3(l2, va);
9626 	if ((pmap_load(l3) & ATTR_DESCR_VALID) != 0)
9627 		return;
9628 	m = pmap_san_enter_alloc_l3();
9629 	pmap_store(l3, VM_PAGE_TO_PTE(m) | PMAP_SAN_PTE_BITS | L3_PAGE);
9630 	dmb(ishst);
9631 }
9632 #endif /* KASAN || KMSAN */
9633 
9634 /*
9635  * Track a range of the kernel's virtual address space that is contiguous
9636  * in various mapping attributes.
9637  */
9638 struct pmap_kernel_map_range {
9639 	vm_offset_t sva;
9640 	pt_entry_t attrs;
9641 	int l3pages;
9642 	int l3contig;
9643 	int l2blocks;
9644 	int l2contig;
9645 	int l1blocks;
9646 };
9647 
9648 static void
sysctl_kmaps_dump(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t eva)9649 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
9650     vm_offset_t eva)
9651 {
9652 	const char *mode;
9653 	int index;
9654 
9655 	if (eva <= range->sva)
9656 		return;
9657 
9658 	index = range->attrs & ATTR_S1_IDX_MASK;
9659 	switch (index) {
9660 	case ATTR_S1_IDX(VM_MEMATTR_DEVICE_NP):
9661 		mode = "DEV-NP";
9662 		break;
9663 	case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
9664 		mode = "DEV";
9665 		break;
9666 	case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
9667 		mode = "UC";
9668 		break;
9669 	case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
9670 		mode = "WB";
9671 		break;
9672 	case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
9673 		mode = "WT";
9674 		break;
9675 	default:
9676 		printf(
9677 		    "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
9678 		    __func__, index, range->sva, eva);
9679 		mode = "??";
9680 		break;
9681 	}
9682 
9683 	sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c%c %6s %d %d %d %d %d\n",
9684 	    range->sva, eva,
9685 	    (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
9686 	    (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
9687 	    (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
9688 	    (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
9689 	    (range->attrs & ATTR_S1_GP) != 0 ? 'g' : '-',
9690 	    mode, range->l1blocks, range->l2contig, range->l2blocks,
9691 	    range->l3contig, range->l3pages);
9692 
9693 	/* Reset to sentinel value. */
9694 	range->sva = 0xfffffffffffffffful;
9695 }
9696 
9697 /*
9698  * Determine whether the attributes specified by a page table entry match those
9699  * being tracked by the current range.
9700  */
9701 static bool
sysctl_kmaps_match(struct pmap_kernel_map_range * range,pt_entry_t attrs)9702 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
9703 {
9704 
9705 	return (range->attrs == attrs);
9706 }
9707 
9708 static void
sysctl_kmaps_reinit(struct pmap_kernel_map_range * range,vm_offset_t va,pt_entry_t attrs)9709 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
9710     pt_entry_t attrs)
9711 {
9712 
9713 	memset(range, 0, sizeof(*range));
9714 	range->sva = va;
9715 	range->attrs = attrs;
9716 }
9717 
9718 /* Get the block/page attributes that correspond to the table attributes */
9719 static pt_entry_t
sysctl_kmaps_table_attrs(pd_entry_t table)9720 sysctl_kmaps_table_attrs(pd_entry_t table)
9721 {
9722 	pt_entry_t attrs;
9723 
9724 	attrs = 0;
9725 	if ((table & TATTR_UXN_TABLE) != 0)
9726 		attrs |= ATTR_S1_UXN;
9727 	if ((table & TATTR_PXN_TABLE) != 0)
9728 		attrs |= ATTR_S1_PXN;
9729 	if ((table & TATTR_AP_TABLE_RO) != 0)
9730 		attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
9731 
9732 	return (attrs);
9733 }
9734 
9735 /* Read the block/page attributes we care about */
9736 static pt_entry_t
sysctl_kmaps_block_attrs(pt_entry_t block)9737 sysctl_kmaps_block_attrs(pt_entry_t block)
9738 {
9739 	return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK |
9740 	    ATTR_S1_GP));
9741 }
9742 
9743 /*
9744  * Given a leaf PTE, derive the mapping's attributes.  If they do not match
9745  * those of the current run, dump the address range and its attributes, and
9746  * begin a new run.
9747  */
9748 static void
sysctl_kmaps_check(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t va,pd_entry_t l0e,pd_entry_t l1e,pd_entry_t l2e,pt_entry_t l3e)9749 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
9750     vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
9751     pt_entry_t l3e)
9752 {
9753 	pt_entry_t attrs;
9754 
9755 	attrs = sysctl_kmaps_table_attrs(l0e);
9756 
9757 	if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
9758 		attrs |= sysctl_kmaps_block_attrs(l1e);
9759 		goto done;
9760 	}
9761 	attrs |= sysctl_kmaps_table_attrs(l1e);
9762 
9763 	if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
9764 		attrs |= sysctl_kmaps_block_attrs(l2e);
9765 		goto done;
9766 	}
9767 	attrs |= sysctl_kmaps_table_attrs(l2e);
9768 	attrs |= sysctl_kmaps_block_attrs(l3e);
9769 
9770 done:
9771 	if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
9772 		sysctl_kmaps_dump(sb, range, va);
9773 		sysctl_kmaps_reinit(range, va, attrs);
9774 	}
9775 }
9776 
9777 static int
sysctl_kmaps(SYSCTL_HANDLER_ARGS)9778 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
9779 {
9780 	struct pmap_kernel_map_range range;
9781 	struct sbuf sbuf, *sb;
9782 	pd_entry_t l0e, *l1, l1e, *l2, l2e;
9783 	pt_entry_t *l3, l3e;
9784 	vm_offset_t sva;
9785 	vm_paddr_t pa;
9786 	int error, i, j, k, l;
9787 
9788 	error = sysctl_wire_old_buffer(req, 0);
9789 	if (error != 0)
9790 		return (error);
9791 	sb = &sbuf;
9792 	sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
9793 
9794 	/* Sentinel value. */
9795 	range.sva = 0xfffffffffffffffful;
9796 
9797 	/*
9798 	 * Iterate over the kernel page tables without holding the kernel pmap
9799 	 * lock.  Kernel page table pages are never freed, so at worst we will
9800 	 * observe inconsistencies in the output.
9801 	 */
9802 	for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
9803 	    i++) {
9804 		if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
9805 			sbuf_printf(sb, "\nDirect map:\n");
9806 		else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
9807 			sbuf_printf(sb, "\nKernel map:\n");
9808 #ifdef KASAN
9809 		else if (i == pmap_l0_index(KASAN_MIN_ADDRESS))
9810 			sbuf_printf(sb, "\nKASAN shadow map:\n");
9811 #endif
9812 #ifdef KMSAN
9813 		else if (i == pmap_l0_index(KMSAN_SHAD_MIN_ADDRESS))
9814 			sbuf_printf(sb, "\nKMSAN shadow map:\n");
9815 		else if (i == pmap_l0_index(KMSAN_ORIG_MIN_ADDRESS))
9816 			sbuf_printf(sb, "\nKMSAN origin map:\n");
9817 #endif
9818 
9819 		l0e = kernel_pmap->pm_l0[i];
9820 		if ((l0e & ATTR_DESCR_VALID) == 0) {
9821 			sysctl_kmaps_dump(sb, &range, sva);
9822 			sva += L0_SIZE;
9823 			continue;
9824 		}
9825 		pa = PTE_TO_PHYS(l0e);
9826 		l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
9827 
9828 		for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
9829 			l1e = l1[j];
9830 			if ((l1e & ATTR_DESCR_VALID) == 0) {
9831 				sysctl_kmaps_dump(sb, &range, sva);
9832 				sva += L1_SIZE;
9833 				continue;
9834 			}
9835 			if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
9836 				PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
9837 				sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
9838 				    0, 0);
9839 				range.l1blocks++;
9840 				sva += L1_SIZE;
9841 				continue;
9842 			}
9843 			pa = PTE_TO_PHYS(l1e);
9844 			l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
9845 
9846 			for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
9847 				l2e = l2[k];
9848 				if ((l2e & ATTR_DESCR_VALID) == 0) {
9849 					sysctl_kmaps_dump(sb, &range, sva);
9850 					sva += L2_SIZE;
9851 					continue;
9852 				}
9853 				if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
9854 					sysctl_kmaps_check(sb, &range, sva,
9855 					    l0e, l1e, l2e, 0);
9856 					if ((l2e & ATTR_CONTIGUOUS) != 0)
9857 						range.l2contig +=
9858 						    k % L2C_ENTRIES == 0 ?
9859 						    1 : 0;
9860 					else
9861 						range.l2blocks++;
9862 					sva += L2_SIZE;
9863 					continue;
9864 				}
9865 				pa = PTE_TO_PHYS(l2e);
9866 				l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
9867 
9868 				for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
9869 				    l++, sva += L3_SIZE) {
9870 					l3e = l3[l];
9871 					if ((l3e & ATTR_DESCR_VALID) == 0) {
9872 						sysctl_kmaps_dump(sb, &range,
9873 						    sva);
9874 						continue;
9875 					}
9876 					sysctl_kmaps_check(sb, &range, sva,
9877 					    l0e, l1e, l2e, l3e);
9878 					if ((l3e & ATTR_CONTIGUOUS) != 0)
9879 						range.l3contig +=
9880 						    l % L3C_ENTRIES == 0 ?
9881 						    1 : 0;
9882 					else
9883 						range.l3pages++;
9884 				}
9885 			}
9886 		}
9887 	}
9888 
9889 	error = sbuf_finish(sb);
9890 	sbuf_delete(sb);
9891 	return (error);
9892 }
9893 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
9894     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
9895     NULL, 0, sysctl_kmaps, "A",
9896     "Dump kernel address layout");
9897