xref: /freebsd/sys/powerpc/aim/mmu_radix.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2018 Matthew Macy
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>
32 #include <sys/kernel.h>
33 #include <sys/systm.h>
34 #include <sys/conf.h>
35 #include <sys/bitstring.h>
36 #include <sys/queue.h>
37 #include <sys/cpuset.h>
38 #include <sys/endian.h>
39 #include <sys/kerneldump.h>
40 #include <sys/ktr.h>
41 #include <sys/lock.h>
42 #include <sys/syslog.h>
43 #include <sys/msgbuf.h>
44 #include <sys/malloc.h>
45 #include <sys/mman.h>
46 #include <sys/mutex.h>
47 #include <sys/proc.h>
48 #include <sys/rwlock.h>
49 #include <sys/sched.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52 #include <sys/vmem.h>
53 #include <sys/vmmeter.h>
54 #include <sys/smp.h>
55 
56 #include <sys/kdb.h>
57 
58 #include <dev/ofw/openfirm.h>
59 
60 #include <vm/vm.h>
61 #include <vm/pmap.h>
62 #include <vm/vm_param.h>
63 #include <vm/vm_kern.h>
64 #include <vm/vm_page.h>
65 #include <vm/vm_map.h>
66 #include <vm/vm_object.h>
67 #include <vm/vm_extern.h>
68 #include <vm/vm_pageout.h>
69 #include <vm/vm_phys.h>
70 #include <vm/vm_reserv.h>
71 #include <vm/vm_dumpset.h>
72 #include <vm/uma.h>
73 
74 #include <machine/_inttypes.h>
75 #include <machine/cpu.h>
76 #include <machine/platform.h>
77 #include <machine/frame.h>
78 #include <machine/md_var.h>
79 #include <machine/psl.h>
80 #include <machine/bat.h>
81 #include <machine/hid.h>
82 #include <machine/pte.h>
83 #include <machine/sr.h>
84 #include <machine/trap.h>
85 #include <machine/mmuvar.h>
86 
87 #ifdef INVARIANTS
88 #include <vm/uma_dbg.h>
89 #endif
90 
91 #define PPC_BITLSHIFT(bit)	(sizeof(long)*NBBY - 1 - (bit))
92 #define PPC_BIT(bit)		(1UL << PPC_BITLSHIFT(bit))
93 #define PPC_BITLSHIFT_VAL(val, bit) ((val) << PPC_BITLSHIFT(bit))
94 
95 #include "opt_ddb.h"
96 #ifdef DDB
97 static void pmap_pte_walk(pml1_entry_t *l1, vm_offset_t va);
98 #endif
99 
100 #define PG_W	RPTE_WIRED
101 #define PG_V	RPTE_VALID
102 #define PG_MANAGED	RPTE_MANAGED
103 #define PG_PROMOTED	RPTE_PROMOTED
104 #define PG_M	RPTE_C
105 #define PG_A	RPTE_R
106 #define PG_X	RPTE_EAA_X
107 #define PG_RW	RPTE_EAA_W
108 #define PG_PTE_CACHE RPTE_ATTR_MASK
109 
110 #define RPTE_SHIFT 9
111 #define NLS_MASK ((1UL<<5)-1)
112 #define RPTE_ENTRIES (1UL<<RPTE_SHIFT)
113 #define RPTE_MASK (RPTE_ENTRIES-1)
114 
115 #define NLB_SHIFT 0
116 #define NLB_MASK (((1UL<<52)-1) << 8)
117 
118 extern int nkpt;
119 extern caddr_t crashdumpmap;
120 
121 #define RIC_FLUSH_TLB 0
122 #define RIC_FLUSH_PWC 1
123 #define RIC_FLUSH_ALL 2
124 
125 #define POWER9_TLB_SETS_RADIX	128	/* # sets in POWER9 TLB Radix mode */
126 
127 #define PPC_INST_TLBIE			0x7c000264
128 #define PPC_INST_TLBIEL			0x7c000224
129 #define PPC_INST_SLBIA			0x7c0003e4
130 
131 #define ___PPC_RA(a)	(((a) & 0x1f) << 16)
132 #define ___PPC_RB(b)	(((b) & 0x1f) << 11)
133 #define ___PPC_RS(s)	(((s) & 0x1f) << 21)
134 #define ___PPC_RT(t)	___PPC_RS(t)
135 #define ___PPC_R(r)	(((r) & 0x1) << 16)
136 #define ___PPC_PRS(prs)	(((prs) & 0x1) << 17)
137 #define ___PPC_RIC(ric)	(((ric) & 0x3) << 18)
138 
139 #define PPC_SLBIA(IH)	__XSTRING(.long PPC_INST_SLBIA | \
140 				       ((IH & 0x7) << 21))
141 #define	PPC_TLBIE_5(rb,rs,ric,prs,r)				\
142 	__XSTRING(.long PPC_INST_TLBIE |			\
143 			  ___PPC_RB(rb) | ___PPC_RS(rs) |	\
144 			  ___PPC_RIC(ric) | ___PPC_PRS(prs) |	\
145 			  ___PPC_R(r))
146 
147 #define	PPC_TLBIEL(rb,rs,ric,prs,r) \
148 	 __XSTRING(.long PPC_INST_TLBIEL | \
149 			   ___PPC_RB(rb) | ___PPC_RS(rs) |	\
150 			   ___PPC_RIC(ric) | ___PPC_PRS(prs) |	\
151 			   ___PPC_R(r))
152 
153 #define PPC_INVALIDATE_ERAT		PPC_SLBIA(7)
154 
155 static __inline void
156 ttusync(void)
157 {
158 	__asm __volatile("eieio; tlbsync; ptesync" ::: "memory");
159 }
160 
161 #define TLBIEL_INVAL_SEL_MASK	0xc00	/* invalidation selector */
162 #define  TLBIEL_INVAL_PAGE	0x000	/* invalidate a single page */
163 #define  TLBIEL_INVAL_SET_PID	0x400	/* invalidate a set for the current PID */
164 #define  TLBIEL_INVAL_SET_LPID	0x800	/* invalidate a set for current LPID */
165 #define  TLBIEL_INVAL_SET	0xc00	/* invalidate a set for all LPIDs */
166 
167 #define TLBIE_ACTUAL_PAGE_MASK		0xe0
168 #define  TLBIE_ACTUAL_PAGE_4K		0x00
169 #define  TLBIE_ACTUAL_PAGE_64K		0xa0
170 #define  TLBIE_ACTUAL_PAGE_2M		0x20
171 #define  TLBIE_ACTUAL_PAGE_1G		0x40
172 
173 #define TLBIE_PRS_PARTITION_SCOPE	0x0
174 #define TLBIE_PRS_PROCESS_SCOPE	0x1
175 
176 #define TLBIE_RIC_INVALIDATE_TLB	0x0	/* Invalidate just TLB */
177 #define TLBIE_RIC_INVALIDATE_PWC	0x1	/* Invalidate just PWC */
178 #define TLBIE_RIC_INVALIDATE_ALL	0x2	/* Invalidate TLB, PWC,
179 						 * cached {proc, part}tab entries
180 						 */
181 #define TLBIE_RIC_INVALIDATE_SEQ	0x3	/* HPT - only:
182 						 * Invalidate a range of translations
183 						 */
184 
185 static __always_inline void
186 radix_tlbie(uint8_t ric, uint8_t prs, uint16_t is, uint32_t pid, uint32_t lpid,
187 			vm_offset_t va, uint16_t ap)
188 {
189 	uint64_t rb, rs;
190 
191 	MPASS((va & PAGE_MASK) == 0);
192 
193 	rs = ((uint64_t)pid << 32) | lpid;
194 	rb = va | is | ap;
195 	__asm __volatile(PPC_TLBIE_5(%0, %1, %2, %3, 1) : :
196 		"r" (rb), "r" (rs), "i" (ric), "i" (prs) : "memory");
197 }
198 
199 static __inline void
200 radix_tlbie_fixup(uint32_t pid, vm_offset_t va, int ap)
201 {
202 
203 	__asm __volatile("ptesync" ::: "memory");
204 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
205 	    TLBIEL_INVAL_PAGE, 0, 0, va, ap);
206 	__asm __volatile("ptesync" ::: "memory");
207 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
208 	    TLBIEL_INVAL_PAGE, pid, 0, va, ap);
209 }
210 
211 static __inline void
212 radix_tlbie_invlpg_user_4k(uint32_t pid, vm_offset_t va)
213 {
214 
215 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
216 		TLBIEL_INVAL_PAGE, pid, 0, va, TLBIE_ACTUAL_PAGE_4K);
217 	radix_tlbie_fixup(pid, va, TLBIE_ACTUAL_PAGE_4K);
218 }
219 
220 static __inline void
221 radix_tlbie_invlpg_user_2m(uint32_t pid, vm_offset_t va)
222 {
223 
224 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
225 		TLBIEL_INVAL_PAGE, pid, 0, va, TLBIE_ACTUAL_PAGE_2M);
226 	radix_tlbie_fixup(pid, va, TLBIE_ACTUAL_PAGE_2M);
227 }
228 
229 static __inline void
230 radix_tlbie_invlpwc_user(uint32_t pid)
231 {
232 
233 	radix_tlbie(TLBIE_RIC_INVALIDATE_PWC, TLBIE_PRS_PROCESS_SCOPE,
234 		TLBIEL_INVAL_SET_PID, pid, 0, 0, 0);
235 }
236 
237 static __inline void
238 radix_tlbie_flush_user(uint32_t pid)
239 {
240 
241 	radix_tlbie(TLBIE_RIC_INVALIDATE_ALL, TLBIE_PRS_PROCESS_SCOPE,
242 		TLBIEL_INVAL_SET_PID, pid, 0, 0, 0);
243 }
244 
245 static __inline void
246 radix_tlbie_invlpg_kernel_4k(vm_offset_t va)
247 {
248 
249 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
250 	    TLBIEL_INVAL_PAGE, 0, 0, va, TLBIE_ACTUAL_PAGE_4K);
251 	radix_tlbie_fixup(0, va, TLBIE_ACTUAL_PAGE_4K);
252 }
253 
254 static __inline void
255 radix_tlbie_invlpg_kernel_2m(vm_offset_t va)
256 {
257 
258 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
259 	    TLBIEL_INVAL_PAGE, 0, 0, va, TLBIE_ACTUAL_PAGE_2M);
260 	radix_tlbie_fixup(0, va, TLBIE_ACTUAL_PAGE_2M);
261 }
262 
263 /* 1GB pages aren't currently supported. */
264 static __inline __unused void
265 radix_tlbie_invlpg_kernel_1g(vm_offset_t va)
266 {
267 
268 	radix_tlbie(TLBIE_RIC_INVALIDATE_TLB, TLBIE_PRS_PROCESS_SCOPE,
269 	    TLBIEL_INVAL_PAGE, 0, 0, va, TLBIE_ACTUAL_PAGE_1G);
270 	radix_tlbie_fixup(0, va, TLBIE_ACTUAL_PAGE_1G);
271 }
272 
273 static __inline void
274 radix_tlbie_invlpwc_kernel(void)
275 {
276 
277 	radix_tlbie(TLBIE_RIC_INVALIDATE_PWC, TLBIE_PRS_PROCESS_SCOPE,
278 	    TLBIEL_INVAL_SET_LPID, 0, 0, 0, 0);
279 }
280 
281 static __inline void
282 radix_tlbie_flush_kernel(void)
283 {
284 
285 	radix_tlbie(TLBIE_RIC_INVALIDATE_ALL, TLBIE_PRS_PROCESS_SCOPE,
286 	    TLBIEL_INVAL_SET_LPID, 0, 0, 0, 0);
287 }
288 
289 static __inline vm_pindex_t
290 pmap_l3e_pindex(vm_offset_t va)
291 {
292 	return ((va & PG_FRAME) >> L3_PAGE_SIZE_SHIFT);
293 }
294 
295 static __inline vm_pindex_t
296 pmap_pml3e_index(vm_offset_t va)
297 {
298 
299 	return ((va >> L3_PAGE_SIZE_SHIFT) & RPTE_MASK);
300 }
301 
302 static __inline vm_pindex_t
303 pmap_pml2e_index(vm_offset_t va)
304 {
305 	return ((va >> L2_PAGE_SIZE_SHIFT) & RPTE_MASK);
306 }
307 
308 static __inline vm_pindex_t
309 pmap_pml1e_index(vm_offset_t va)
310 {
311 	return ((va & PG_FRAME) >> L1_PAGE_SIZE_SHIFT);
312 }
313 
314 /* Return various clipped indexes for a given VA */
315 static __inline vm_pindex_t
316 pmap_pte_index(vm_offset_t va)
317 {
318 
319 	return ((va >> PAGE_SHIFT) & RPTE_MASK);
320 }
321 
322 /* Return a pointer to the PT slot that corresponds to a VA */
323 static __inline pt_entry_t *
324 pmap_l3e_to_pte(pt_entry_t *l3e, vm_offset_t va)
325 {
326 	pt_entry_t *pte;
327 	vm_paddr_t ptepa;
328 
329 	ptepa = (be64toh(*l3e) & NLB_MASK);
330 	pte = (pt_entry_t *)PHYS_TO_DMAP(ptepa);
331 	return (&pte[pmap_pte_index(va)]);
332 }
333 
334 /* Return a pointer to the PD slot that corresponds to a VA */
335 static __inline pt_entry_t *
336 pmap_l2e_to_l3e(pt_entry_t *l2e, vm_offset_t va)
337 {
338 	pt_entry_t *l3e;
339 	vm_paddr_t l3pa;
340 
341 	l3pa = (be64toh(*l2e) & NLB_MASK);
342 	l3e = (pml3_entry_t *)PHYS_TO_DMAP(l3pa);
343 	return (&l3e[pmap_pml3e_index(va)]);
344 }
345 
346 /* Return a pointer to the PD slot that corresponds to a VA */
347 static __inline pt_entry_t *
348 pmap_l1e_to_l2e(pt_entry_t *l1e, vm_offset_t va)
349 {
350 	pt_entry_t *l2e;
351 	vm_paddr_t l2pa;
352 
353 	l2pa = (be64toh(*l1e) & NLB_MASK);
354 
355 	l2e = (pml2_entry_t *)PHYS_TO_DMAP(l2pa);
356 	return (&l2e[pmap_pml2e_index(va)]);
357 }
358 
359 static __inline pml1_entry_t *
360 pmap_pml1e(pmap_t pmap, vm_offset_t va)
361 {
362 
363 	return (&pmap->pm_pml1[pmap_pml1e_index(va)]);
364 }
365 
366 static pt_entry_t *
367 pmap_pml2e(pmap_t pmap, vm_offset_t va)
368 {
369 	pt_entry_t *l1e;
370 
371 	l1e = pmap_pml1e(pmap, va);
372 	if (l1e == NULL || (be64toh(*l1e) & RPTE_VALID) == 0)
373 		return (NULL);
374 	return (pmap_l1e_to_l2e(l1e, va));
375 }
376 
377 static __inline pt_entry_t *
378 pmap_pml3e(pmap_t pmap, vm_offset_t va)
379 {
380 	pt_entry_t *l2e;
381 
382 	l2e = pmap_pml2e(pmap, va);
383 	if (l2e == NULL || (be64toh(*l2e) & RPTE_VALID) == 0)
384 		return (NULL);
385 	return (pmap_l2e_to_l3e(l2e, va));
386 }
387 
388 static __inline pt_entry_t *
389 pmap_pte(pmap_t pmap, vm_offset_t va)
390 {
391 	pt_entry_t *l3e;
392 
393 	l3e = pmap_pml3e(pmap, va);
394 	if (l3e == NULL || (be64toh(*l3e) & RPTE_VALID) == 0)
395 		return (NULL);
396 	return (pmap_l3e_to_pte(l3e, va));
397 }
398 
399 int nkpt = 64;
400 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
401     "Number of kernel page table pages allocated on bootup");
402 
403 vm_paddr_t dmaplimit;
404 
405 SYSCTL_DECL(_vm_pmap);
406 
407 #ifdef INVARIANTS
408 #define VERBOSE_PMAP 0
409 #define VERBOSE_PROTECT 0
410 static int pmap_logging;
411 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_logging, CTLFLAG_RWTUN,
412     &pmap_logging, 0, "verbose debug logging");
413 #endif
414 
415 static u_int64_t	KPTphys;	/* phys addr of kernel level 1 */
416 
417 //static vm_paddr_t	KERNend;	/* phys addr of end of bootstrap data */
418 
419 static vm_offset_t qframe = 0;
420 static struct mtx qframe_mtx;
421 
422 void mmu_radix_activate(struct thread *);
423 void mmu_radix_advise(pmap_t, vm_offset_t, vm_offset_t, int);
424 void mmu_radix_align_superpage(vm_object_t, vm_ooffset_t, vm_offset_t *,
425     vm_size_t);
426 void mmu_radix_clear_modify(vm_page_t);
427 void mmu_radix_copy(pmap_t, pmap_t, vm_offset_t, vm_size_t, vm_offset_t);
428 int mmu_radix_decode_kernel_ptr(vm_offset_t, int *, vm_offset_t *);
429 int mmu_radix_enter(pmap_t, vm_offset_t, vm_page_t, vm_prot_t, u_int, int8_t);
430 void mmu_radix_enter_object(pmap_t, vm_offset_t, vm_offset_t, vm_page_t,
431 	vm_prot_t);
432 void mmu_radix_enter_quick(pmap_t, vm_offset_t, vm_page_t, vm_prot_t);
433 vm_paddr_t mmu_radix_extract(pmap_t pmap, vm_offset_t va);
434 vm_page_t mmu_radix_extract_and_hold(pmap_t, vm_offset_t, vm_prot_t);
435 void mmu_radix_kenter(vm_offset_t, vm_paddr_t);
436 vm_paddr_t mmu_radix_kextract(vm_offset_t);
437 void mmu_radix_kremove(vm_offset_t);
438 boolean_t mmu_radix_is_modified(vm_page_t);
439 boolean_t mmu_radix_is_prefaultable(pmap_t, vm_offset_t);
440 boolean_t mmu_radix_is_referenced(vm_page_t);
441 void mmu_radix_object_init_pt(pmap_t, vm_offset_t, vm_object_t,
442 	vm_pindex_t, vm_size_t);
443 boolean_t mmu_radix_page_exists_quick(pmap_t, vm_page_t);
444 void mmu_radix_page_init(vm_page_t);
445 boolean_t mmu_radix_page_is_mapped(vm_page_t m);
446 void mmu_radix_page_set_memattr(vm_page_t, vm_memattr_t);
447 int mmu_radix_page_wired_mappings(vm_page_t);
448 int mmu_radix_pinit(pmap_t);
449 void mmu_radix_protect(pmap_t, vm_offset_t, vm_offset_t, vm_prot_t);
450 bool mmu_radix_ps_enabled(pmap_t);
451 void mmu_radix_qenter(vm_offset_t, vm_page_t *, int);
452 void mmu_radix_qremove(vm_offset_t, int);
453 vm_offset_t mmu_radix_quick_enter_page(vm_page_t);
454 void mmu_radix_quick_remove_page(vm_offset_t);
455 boolean_t mmu_radix_ts_referenced(vm_page_t);
456 void mmu_radix_release(pmap_t);
457 void mmu_radix_remove(pmap_t, vm_offset_t, vm_offset_t);
458 void mmu_radix_remove_all(vm_page_t);
459 void mmu_radix_remove_pages(pmap_t);
460 void mmu_radix_remove_write(vm_page_t);
461 void mmu_radix_unwire(pmap_t, vm_offset_t, vm_offset_t);
462 void mmu_radix_zero_page(vm_page_t);
463 void mmu_radix_zero_page_area(vm_page_t, int, int);
464 int mmu_radix_change_attr(vm_offset_t, vm_size_t, vm_memattr_t);
465 void mmu_radix_page_array_startup(long pages);
466 
467 #include "mmu_oea64.h"
468 
469 /*
470  * Kernel MMU interface
471  */
472 
473 static void	mmu_radix_bootstrap(vm_offset_t, vm_offset_t);
474 
475 static void mmu_radix_copy_page(vm_page_t, vm_page_t);
476 static void mmu_radix_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
477     vm_page_t *mb, vm_offset_t b_offset, int xfersize);
478 static void mmu_radix_growkernel(vm_offset_t);
479 static void mmu_radix_init(void);
480 static int mmu_radix_mincore(pmap_t, vm_offset_t, vm_paddr_t *);
481 static vm_offset_t mmu_radix_map(vm_offset_t *, vm_paddr_t, vm_paddr_t, int);
482 static void mmu_radix_pinit0(pmap_t);
483 
484 static void *mmu_radix_mapdev(vm_paddr_t, vm_size_t);
485 static void *mmu_radix_mapdev_attr(vm_paddr_t, vm_size_t, vm_memattr_t);
486 static void mmu_radix_unmapdev(vm_offset_t, vm_size_t);
487 static void mmu_radix_kenter_attr(vm_offset_t, vm_paddr_t, vm_memattr_t ma);
488 static boolean_t mmu_radix_dev_direct_mapped(vm_paddr_t, vm_size_t);
489 static void mmu_radix_dumpsys_map(vm_paddr_t pa, size_t sz, void **va);
490 static void mmu_radix_scan_init(void);
491 static void	mmu_radix_cpu_bootstrap(int ap);
492 static void	mmu_radix_tlbie_all(void);
493 
494 static struct pmap_funcs mmu_radix_methods = {
495 	.bootstrap = mmu_radix_bootstrap,
496 	.copy_page = mmu_radix_copy_page,
497 	.copy_pages = mmu_radix_copy_pages,
498 	.cpu_bootstrap = mmu_radix_cpu_bootstrap,
499 	.growkernel = mmu_radix_growkernel,
500 	.init = mmu_radix_init,
501 	.map =      		mmu_radix_map,
502 	.mincore =      	mmu_radix_mincore,
503 	.pinit = mmu_radix_pinit,
504 	.pinit0 = mmu_radix_pinit0,
505 
506 	.mapdev = mmu_radix_mapdev,
507 	.mapdev_attr = mmu_radix_mapdev_attr,
508 	.unmapdev = mmu_radix_unmapdev,
509 	.kenter_attr = mmu_radix_kenter_attr,
510 	.dev_direct_mapped = mmu_radix_dev_direct_mapped,
511 	.dumpsys_pa_init = mmu_radix_scan_init,
512 	.dumpsys_map_chunk = mmu_radix_dumpsys_map,
513 	.page_is_mapped = mmu_radix_page_is_mapped,
514 	.ps_enabled = mmu_radix_ps_enabled,
515 	.object_init_pt = mmu_radix_object_init_pt,
516 	.protect = mmu_radix_protect,
517 	/* pmap dispatcher interface */
518 	.clear_modify = mmu_radix_clear_modify,
519 	.copy = mmu_radix_copy,
520 	.enter = mmu_radix_enter,
521 	.enter_object = mmu_radix_enter_object,
522 	.enter_quick = mmu_radix_enter_quick,
523 	.extract = mmu_radix_extract,
524 	.extract_and_hold = mmu_radix_extract_and_hold,
525 	.is_modified = mmu_radix_is_modified,
526 	.is_prefaultable = mmu_radix_is_prefaultable,
527 	.is_referenced = mmu_radix_is_referenced,
528 	.ts_referenced = mmu_radix_ts_referenced,
529 	.page_exists_quick = mmu_radix_page_exists_quick,
530 	.page_init = mmu_radix_page_init,
531 	.page_wired_mappings =  mmu_radix_page_wired_mappings,
532 	.qenter = mmu_radix_qenter,
533 	.qremove = mmu_radix_qremove,
534 	.release = mmu_radix_release,
535 	.remove = mmu_radix_remove,
536 	.remove_all = mmu_radix_remove_all,
537 	.remove_write = mmu_radix_remove_write,
538 	.unwire = mmu_radix_unwire,
539 	.zero_page = mmu_radix_zero_page,
540 	.zero_page_area = mmu_radix_zero_page_area,
541 	.activate = mmu_radix_activate,
542 	.quick_enter_page =  mmu_radix_quick_enter_page,
543 	.quick_remove_page =  mmu_radix_quick_remove_page,
544 	.page_set_memattr = mmu_radix_page_set_memattr,
545 	.page_array_startup =  mmu_radix_page_array_startup,
546 
547 	/* Internal interfaces */
548 	.kenter = mmu_radix_kenter,
549 	.kextract = mmu_radix_kextract,
550 	.kremove = mmu_radix_kremove,
551 	.change_attr = mmu_radix_change_attr,
552 	.decode_kernel_ptr =  mmu_radix_decode_kernel_ptr,
553 
554 	.tlbie_all = mmu_radix_tlbie_all,
555 };
556 
557 MMU_DEF(mmu_radix, MMU_TYPE_RADIX, mmu_radix_methods);
558 
559 static boolean_t pmap_demote_l3e_locked(pmap_t pmap, pml3_entry_t *l3e, vm_offset_t va,
560 	struct rwlock **lockp);
561 static boolean_t pmap_demote_l3e(pmap_t pmap, pml3_entry_t *pde, vm_offset_t va);
562 static int pmap_unuse_pt(pmap_t, vm_offset_t, pml3_entry_t, struct spglist *);
563 static int pmap_remove_l3e(pmap_t pmap, pml3_entry_t *pdq, vm_offset_t sva,
564     struct spglist *free, struct rwlock **lockp);
565 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
566     pml3_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
567 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
568 static bool pmap_remove_page(pmap_t pmap, vm_offset_t va, pml3_entry_t *pde,
569     struct spglist *free);
570 static bool	pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
571 	pml3_entry_t *l3e, struct spglist *free, struct rwlock **lockp);
572 
573 static bool	pmap_pv_insert_l3e(pmap_t pmap, vm_offset_t va, pml3_entry_t l3e,
574 		    u_int flags, struct rwlock **lockp);
575 #if VM_NRESERVLEVEL > 0
576 static void	pmap_pv_promote_l3e(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
577 	struct rwlock **lockp);
578 #endif
579 static void	pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
580 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
581 static vm_page_t mmu_radix_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
582 	vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp, bool *invalidate);
583 
584 static bool	pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
585 	vm_prot_t prot, struct rwlock **lockp);
586 static int	pmap_enter_l3e(pmap_t pmap, vm_offset_t va, pml3_entry_t newpde,
587 	u_int flags, vm_page_t m, struct rwlock **lockp);
588 
589 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
590 static void free_pv_chunk(struct pv_chunk *pc);
591 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp);
592 static vm_page_t pmap_allocl3e(pmap_t pmap, vm_offset_t va,
593 	struct rwlock **lockp);
594 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
595 	struct rwlock **lockp);
596 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
597     struct spglist *free);
598 static boolean_t pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free);
599 
600 static void pmap_invalidate_page(pmap_t pmap, vm_offset_t start);
601 static void pmap_invalidate_all(pmap_t pmap);
602 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode, bool flush);
603 
604 /*
605  * Internal flags for pmap_enter()'s helper functions.
606  */
607 #define	PMAP_ENTER_NORECLAIM	0x1000000	/* Don't reclaim PV entries. */
608 #define	PMAP_ENTER_NOREPLACE	0x2000000	/* Don't replace mappings. */
609 
610 #define UNIMPLEMENTED() panic("%s not implemented", __func__)
611 #define UNTESTED() panic("%s not yet tested", __func__)
612 
613 /* Number of supported PID bits */
614 static unsigned int isa3_pid_bits;
615 
616 /* PID to start allocating from */
617 static unsigned int isa3_base_pid;
618 
619 #define PROCTAB_SIZE_SHIFT	(isa3_pid_bits + 4)
620 #define PROCTAB_ENTRIES	(1ul << isa3_pid_bits)
621 
622 /*
623  * Map of physical memory regions.
624  */
625 static struct	mem_region *regions, *pregions;
626 static struct	numa_mem_region *numa_pregions;
627 static u_int	phys_avail_count;
628 static int	regions_sz, pregions_sz, numa_pregions_sz;
629 static struct pate *isa3_parttab;
630 static struct prte *isa3_proctab;
631 static vmem_t *asid_arena;
632 
633 extern void bs_remap_earlyboot(void);
634 
635 #define	RADIX_PGD_SIZE_SHIFT	16
636 #define RADIX_PGD_SIZE	(1UL << RADIX_PGD_SIZE_SHIFT)
637 
638 #define	RADIX_PGD_INDEX_SHIFT	(RADIX_PGD_SIZE_SHIFT-3)
639 #define NL2EPG (PAGE_SIZE/sizeof(pml2_entry_t))
640 #define NL3EPG (PAGE_SIZE/sizeof(pml3_entry_t))
641 
642 #define	NUPML1E		(RADIX_PGD_SIZE/sizeof(uint64_t))	/* number of userland PML1 pages */
643 #define	NUPDPE		(NUPML1E * NL2EPG)/* number of userland PDP pages */
644 #define	NUPDE		(NUPDPE * NL3EPG)	/* number of userland PD entries */
645 
646 /* POWER9 only permits a 64k partition table size. */
647 #define	PARTTAB_SIZE_SHIFT	16
648 #define PARTTAB_SIZE	(1UL << PARTTAB_SIZE_SHIFT)
649 
650 #define PARTTAB_HR		(1UL << 63) /* host uses radix */
651 #define PARTTAB_GR		(1UL << 63) /* guest uses radix must match host */
652 
653 /* TLB flush actions. Used as argument to tlbiel_all() */
654 enum {
655 	TLB_INVAL_SCOPE_LPID = 0,	/* invalidate TLBs for current LPID */
656 	TLB_INVAL_SCOPE_GLOBAL = 1,	/* invalidate all TLBs */
657 };
658 
659 #define	NPV_LIST_LOCKS	MAXCPU
660 static int pmap_initialized;
661 static vm_paddr_t proctab0pa;
662 static vm_paddr_t parttab_phys;
663 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
664 
665 /*
666  * Data for the pv entry allocation mechanism.
667  * Updates to pv_invl_gen are protected by the pv_list_locks[]
668  * elements, but reads are not.
669  */
670 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
671 static struct mtx __exclusive_cache_line pv_chunks_mutex;
672 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
673 static struct md_page *pv_table;
674 static struct md_page pv_dummy;
675 
676 #ifdef PV_STATS
677 #define PV_STAT(x)	do { x ; } while (0)
678 #else
679 #define PV_STAT(x)	do { } while (0)
680 #endif
681 
682 #define	pa_radix_index(pa)	((pa) >> L3_PAGE_SIZE_SHIFT)
683 #define	pa_to_pvh(pa)	(&pv_table[pa_radix_index(pa)])
684 
685 #define	PHYS_TO_PV_LIST_LOCK(pa)	\
686 			(&pv_list_locks[pa_radix_index(pa) % NPV_LIST_LOCKS])
687 
688 #define	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)	do {	\
689 	struct rwlock **_lockp = (lockp);		\
690 	struct rwlock *_new_lock;			\
691 							\
692 	_new_lock = PHYS_TO_PV_LIST_LOCK(pa);		\
693 	if (_new_lock != *_lockp) {			\
694 		if (*_lockp != NULL)			\
695 			rw_wunlock(*_lockp);		\
696 		*_lockp = _new_lock;			\
697 		rw_wlock(*_lockp);			\
698 	}						\
699 } while (0)
700 
701 #define	CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)	\
702 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
703 
704 #define	RELEASE_PV_LIST_LOCK(lockp)		do {	\
705 	struct rwlock **_lockp = (lockp);		\
706 							\
707 	if (*_lockp != NULL) {				\
708 		rw_wunlock(*_lockp);			\
709 		*_lockp = NULL;				\
710 	}						\
711 } while (0)
712 
713 #define	VM_PAGE_TO_PV_LIST_LOCK(m)	\
714 	PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
715 
716 /*
717  * We support 52 bits, hence:
718  * bits 52 - 31 = 21, 0b10101
719  * RTS encoding details
720  * bits 0 - 3 of rts -> bits 6 - 8 unsigned long
721  * bits 4 - 5 of rts -> bits 62 - 63 of unsigned long
722  */
723 #define RTS_SIZE ((0x2UL << 61) | (0x5UL << 5))
724 
725 static int powernv_enabled = 1;
726 
727 static __always_inline void
728 tlbiel_radix_set_isa300(uint32_t set, uint32_t is,
729 	uint32_t pid, uint32_t ric, uint32_t prs)
730 {
731 	uint64_t rb;
732 	uint64_t rs;
733 
734 	rb = PPC_BITLSHIFT_VAL(set, 51) | PPC_BITLSHIFT_VAL(is, 53);
735 	rs = PPC_BITLSHIFT_VAL((uint64_t)pid, 31);
736 
737 	__asm __volatile(PPC_TLBIEL(%0, %1, %2, %3, 1)
738 		     : : "r"(rb), "r"(rs), "i"(ric), "i"(prs)
739 		     : "memory");
740 }
741 
742 static void
743 tlbiel_flush_isa3(uint32_t num_sets, uint32_t is)
744 {
745 	uint32_t set;
746 
747 	__asm __volatile("ptesync": : :"memory");
748 
749 	/*
750 	 * Flush the first set of the TLB, and the entire Page Walk Cache
751 	 * and partition table entries. Then flush the remaining sets of the
752 	 * TLB.
753 	 */
754 	tlbiel_radix_set_isa300(0, is, 0, RIC_FLUSH_ALL, 0);
755 	for (set = 1; set < num_sets; set++)
756 		tlbiel_radix_set_isa300(set, is, 0, RIC_FLUSH_TLB, 0);
757 
758 	/* Do the same for process scoped entries. */
759 	tlbiel_radix_set_isa300(0, is, 0, RIC_FLUSH_ALL, 1);
760 	for (set = 1; set < num_sets; set++)
761 		tlbiel_radix_set_isa300(set, is, 0, RIC_FLUSH_TLB, 1);
762 
763 	__asm __volatile("ptesync": : :"memory");
764 }
765 
766 static void
767 mmu_radix_tlbiel_flush(int scope)
768 {
769 	int is;
770 
771 	MPASS(scope == TLB_INVAL_SCOPE_LPID ||
772 		  scope == TLB_INVAL_SCOPE_GLOBAL);
773 	is = scope + 2;
774 
775 	tlbiel_flush_isa3(POWER9_TLB_SETS_RADIX, is);
776 	__asm __volatile(PPC_INVALIDATE_ERAT "; isync" : : :"memory");
777 }
778 
779 static void
780 mmu_radix_tlbie_all()
781 {
782 	/* TODO: LPID invalidate */
783 	mmu_radix_tlbiel_flush(TLB_INVAL_SCOPE_GLOBAL);
784 }
785 
786 static void
787 mmu_radix_init_amor(void)
788 {
789 	/*
790 	* In HV mode, we init AMOR (Authority Mask Override Register) so that
791 	* the hypervisor and guest can setup IAMR (Instruction Authority Mask
792 	* Register), enable key 0 and set it to 1.
793 	*
794 	* AMOR = 0b1100 .... 0000 (Mask for key 0 is 11)
795 	*/
796 	mtspr(SPR_AMOR, (3ul << 62));
797 }
798 
799 static void
800 mmu_radix_init_iamr(void)
801 {
802 	/*
803 	 * Radix always uses key0 of the IAMR to determine if an access is
804 	 * allowed. We set bit 0 (IBM bit 1) of key0, to prevent instruction
805 	 * fetch.
806 	 */
807 	mtspr(SPR_IAMR, (1ul << 62));
808 }
809 
810 static void
811 mmu_radix_pid_set(pmap_t pmap)
812 {
813 
814 	mtspr(SPR_PID, pmap->pm_pid);
815 	isync();
816 }
817 
818 /* Quick sort callout for comparing physical addresses. */
819 static int
820 pa_cmp(const void *a, const void *b)
821 {
822 	const vm_paddr_t *pa = a, *pb = b;
823 
824 	if (*pa < *pb)
825 		return (-1);
826 	else if (*pa > *pb)
827 		return (1);
828 	else
829 		return (0);
830 }
831 
832 #define	pte_load_store(ptep, pte)	atomic_swap_long(ptep, pte)
833 #define	pte_load_clear(ptep)		atomic_swap_long(ptep, 0)
834 #define	pte_store(ptep, pte) do {	   \
835 	MPASS((pte) & (RPTE_EAA_R | RPTE_EAA_W | RPTE_EAA_X));	\
836 	*(u_long *)(ptep) = htobe64((u_long)((pte) | PG_V | RPTE_LEAF)); \
837 } while (0)
838 /*
839  * NB: should only be used for adding directories - not for direct mappings
840  */
841 #define	pde_store(ptep, pa) do {				\
842 	*(u_long *)(ptep) = htobe64((u_long)(pa|RPTE_VALID|RPTE_SHIFT)); \
843 } while (0)
844 
845 #define	pte_clear(ptep) do {					\
846 		*(u_long *)(ptep) = (u_long)(0);		\
847 } while (0)
848 
849 #define	PMAP_PDE_SUPERPAGE	(1 << 8)	/* supports 2MB superpages */
850 
851 /*
852  * Promotion to a 2MB (PDE) page mapping requires that the corresponding 4KB
853  * (PTE) page mappings have identical settings for the following fields:
854  */
855 #define	PG_PTE_PROMOTE	(PG_X | PG_MANAGED | PG_W | PG_PTE_CACHE | \
856 	    PG_M | PG_A | RPTE_EAA_MASK | PG_V)
857 
858 static __inline void
859 pmap_resident_count_inc(pmap_t pmap, int count)
860 {
861 
862 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
863 	pmap->pm_stats.resident_count += count;
864 }
865 
866 static __inline void
867 pmap_resident_count_dec(pmap_t pmap, int count)
868 {
869 
870 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
871 	KASSERT(pmap->pm_stats.resident_count >= count,
872 	    ("pmap %p resident count underflow %ld %d", pmap,
873 	    pmap->pm_stats.resident_count, count));
874 	pmap->pm_stats.resident_count -= count;
875 }
876 
877 static void
878 pagezero(vm_offset_t va)
879 {
880 	va = trunc_page(va);
881 
882 	bzero((void *)va, PAGE_SIZE);
883 }
884 
885 static uint64_t
886 allocpages(int n)
887 {
888 	u_int64_t ret;
889 
890 	ret = moea64_bootstrap_alloc(n * PAGE_SIZE, PAGE_SIZE);
891 	for (int i = 0; i < n; i++)
892 		pagezero(PHYS_TO_DMAP(ret + i * PAGE_SIZE));
893 	return (ret);
894 }
895 
896 static pt_entry_t *
897 kvtopte(vm_offset_t va)
898 {
899 	pt_entry_t *l3e;
900 
901 	l3e = pmap_pml3e(kernel_pmap, va);
902 	if ((be64toh(*l3e) & RPTE_VALID) == 0)
903 		return (NULL);
904 	return (pmap_l3e_to_pte(l3e, va));
905 }
906 
907 void
908 mmu_radix_kenter(vm_offset_t va, vm_paddr_t pa)
909 {
910 	pt_entry_t *pte;
911 
912 	pte = kvtopte(va);
913 	MPASS(pte != NULL);
914 	*pte = htobe64(pa | RPTE_VALID | RPTE_LEAF | RPTE_EAA_R | \
915 	    RPTE_EAA_W | RPTE_EAA_P | PG_M | PG_A);
916 }
917 
918 bool
919 mmu_radix_ps_enabled(pmap_t pmap)
920 {
921 	return (superpages_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
922 }
923 
924 static pt_entry_t *
925 pmap_nofault_pte(pmap_t pmap, vm_offset_t va, int *is_l3e)
926 {
927 	pml3_entry_t *l3e;
928 	pt_entry_t *pte;
929 
930 	va &= PG_PS_FRAME;
931 	l3e = pmap_pml3e(pmap, va);
932 	if (l3e == NULL || (be64toh(*l3e) & PG_V) == 0)
933 		return (NULL);
934 
935 	if (be64toh(*l3e) & RPTE_LEAF) {
936 		*is_l3e = 1;
937 		return (l3e);
938 	}
939 	*is_l3e = 0;
940 	va &= PG_FRAME;
941 	pte = pmap_l3e_to_pte(l3e, va);
942 	if (pte == NULL || (be64toh(*pte) & PG_V) == 0)
943 		return (NULL);
944 	return (pte);
945 }
946 
947 int
948 pmap_nofault(pmap_t pmap, vm_offset_t va, vm_prot_t flags)
949 {
950 	pt_entry_t *pte;
951 	pt_entry_t startpte, origpte, newpte;
952 	vm_page_t m;
953 	int is_l3e;
954 
955 	startpte = 0;
956  retry:
957 	if ((pte = pmap_nofault_pte(pmap, va, &is_l3e)) == NULL)
958 		return (KERN_INVALID_ADDRESS);
959 	origpte = newpte = be64toh(*pte);
960 	if (startpte == 0) {
961 		startpte = origpte;
962 		if (((flags & VM_PROT_WRITE) && (startpte & PG_M)) ||
963 		    ((flags & VM_PROT_READ) && (startpte & PG_A))) {
964 			pmap_invalidate_all(pmap);
965 #ifdef INVARIANTS
966 			if (VERBOSE_PMAP || pmap_logging)
967 				printf("%s(%p, %#lx, %#x) (%#lx) -- invalidate all\n",
968 				    __func__, pmap, va, flags, origpte);
969 #endif
970 			return (KERN_FAILURE);
971 		}
972 	}
973 #ifdef INVARIANTS
974 	if (VERBOSE_PMAP || pmap_logging)
975 		printf("%s(%p, %#lx, %#x) (%#lx)\n", __func__, pmap, va,
976 		    flags, origpte);
977 #endif
978 	PMAP_LOCK(pmap);
979 	if ((pte = pmap_nofault_pte(pmap, va, &is_l3e)) == NULL ||
980 	    be64toh(*pte) != origpte) {
981 		PMAP_UNLOCK(pmap);
982 		return (KERN_FAILURE);
983 	}
984 	m = PHYS_TO_VM_PAGE(newpte & PG_FRAME);
985 	MPASS(m != NULL);
986 	switch (flags) {
987 	case VM_PROT_READ:
988 		if ((newpte & (RPTE_EAA_R|RPTE_EAA_X)) == 0)
989 			goto protfail;
990 		newpte |= PG_A;
991 		vm_page_aflag_set(m, PGA_REFERENCED);
992 		break;
993 	case VM_PROT_WRITE:
994 		if ((newpte & RPTE_EAA_W) == 0)
995 			goto protfail;
996 		if (is_l3e)
997 			goto protfail;
998 		newpte |= PG_M;
999 		vm_page_dirty(m);
1000 		break;
1001 	case VM_PROT_EXECUTE:
1002 		if ((newpte & RPTE_EAA_X) == 0)
1003 			goto protfail;
1004 		newpte |= PG_A;
1005 		vm_page_aflag_set(m, PGA_REFERENCED);
1006 		break;
1007 	}
1008 
1009 	if (!atomic_cmpset_long(pte, htobe64(origpte), htobe64(newpte)))
1010 		goto retry;
1011 	ptesync();
1012 	PMAP_UNLOCK(pmap);
1013 	if (startpte == newpte)
1014 		return (KERN_FAILURE);
1015 	return (0);
1016  protfail:
1017 	PMAP_UNLOCK(pmap);
1018 	return (KERN_PROTECTION_FAILURE);
1019 }
1020 
1021 /*
1022  * Returns TRUE if the given page is mapped individually or as part of
1023  * a 2mpage.  Otherwise, returns FALSE.
1024  */
1025 boolean_t
1026 mmu_radix_page_is_mapped(vm_page_t m)
1027 {
1028 	struct rwlock *lock;
1029 	boolean_t rv;
1030 
1031 	if ((m->oflags & VPO_UNMANAGED) != 0)
1032 		return (FALSE);
1033 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
1034 	rw_rlock(lock);
1035 	rv = !TAILQ_EMPTY(&m->md.pv_list) ||
1036 	    ((m->flags & PG_FICTITIOUS) == 0 &&
1037 	    !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
1038 	rw_runlock(lock);
1039 	return (rv);
1040 }
1041 
1042 /*
1043  * Determine the appropriate bits to set in a PTE or PDE for a specified
1044  * caching mode.
1045  */
1046 static int
1047 pmap_cache_bits(vm_memattr_t ma)
1048 {
1049 	if (ma != VM_MEMATTR_DEFAULT) {
1050 		switch (ma) {
1051 		case VM_MEMATTR_UNCACHEABLE:
1052 			return (RPTE_ATTR_GUARDEDIO);
1053 		case VM_MEMATTR_CACHEABLE:
1054 			return (RPTE_ATTR_MEM);
1055 		case VM_MEMATTR_WRITE_BACK:
1056 		case VM_MEMATTR_PREFETCHABLE:
1057 		case VM_MEMATTR_WRITE_COMBINING:
1058 			return (RPTE_ATTR_UNGUARDEDIO);
1059 		}
1060 	}
1061 	return (0);
1062 }
1063 
1064 static void
1065 pmap_invalidate_page(pmap_t pmap, vm_offset_t start)
1066 {
1067 	ptesync();
1068 	if (pmap == kernel_pmap)
1069 		radix_tlbie_invlpg_kernel_4k(start);
1070 	else
1071 		radix_tlbie_invlpg_user_4k(pmap->pm_pid, start);
1072 	ttusync();
1073 }
1074 
1075 static void
1076 pmap_invalidate_page_2m(pmap_t pmap, vm_offset_t start)
1077 {
1078 	ptesync();
1079 	if (pmap == kernel_pmap)
1080 		radix_tlbie_invlpg_kernel_2m(start);
1081 	else
1082 		radix_tlbie_invlpg_user_2m(pmap->pm_pid, start);
1083 	ttusync();
1084 }
1085 
1086 static void
1087 pmap_invalidate_pwc(pmap_t pmap)
1088 {
1089 	ptesync();
1090 	if (pmap == kernel_pmap)
1091 		radix_tlbie_invlpwc_kernel();
1092 	else
1093 		radix_tlbie_invlpwc_user(pmap->pm_pid);
1094 	ttusync();
1095 }
1096 
1097 static void
1098 pmap_invalidate_range(pmap_t pmap, vm_offset_t start, vm_offset_t end)
1099 {
1100 	if (((start - end) >> PAGE_SHIFT) > 8) {
1101 		pmap_invalidate_all(pmap);
1102 		return;
1103 	}
1104 	ptesync();
1105 	if (pmap == kernel_pmap) {
1106 		while (start < end) {
1107 			radix_tlbie_invlpg_kernel_4k(start);
1108 			start += PAGE_SIZE;
1109 		}
1110 	} else {
1111 		while (start < end) {
1112 			radix_tlbie_invlpg_user_4k(pmap->pm_pid, start);
1113 			start += PAGE_SIZE;
1114 		}
1115 	}
1116 	ttusync();
1117 }
1118 
1119 static void
1120 pmap_invalidate_all(pmap_t pmap)
1121 {
1122 	ptesync();
1123 	if (pmap == kernel_pmap)
1124 		radix_tlbie_flush_kernel();
1125 	else
1126 		radix_tlbie_flush_user(pmap->pm_pid);
1127 	ttusync();
1128 }
1129 
1130 static void
1131 pmap_invalidate_l3e_page(pmap_t pmap, vm_offset_t va, pml3_entry_t l3e)
1132 {
1133 
1134 	/*
1135 	 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
1136 	 * by a promotion that did not invalidate the 512 4KB page mappings
1137 	 * that might exist in the TLB.  Consequently, at this point, the TLB
1138 	 * may hold both 4KB and 2MB page mappings for the address range [va,
1139 	 * va + L3_PAGE_SIZE).  Therefore, the entire range must be invalidated here.
1140 	 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
1141 	 * 4KB page mappings for the address range [va, va + L3_PAGE_SIZE), and so a
1142 	 * single INVLPG suffices to invalidate the 2MB page mapping from the
1143 	 * TLB.
1144 	 */
1145 	ptesync();
1146 	if ((l3e & PG_PROMOTED) != 0)
1147 		pmap_invalidate_range(pmap, va, va + L3_PAGE_SIZE - 1);
1148 	else
1149 		pmap_invalidate_page_2m(pmap, va);
1150 
1151 	pmap_invalidate_pwc(pmap);
1152 }
1153 
1154 static __inline struct pv_chunk *
1155 pv_to_chunk(pv_entry_t pv)
1156 {
1157 
1158 	return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
1159 }
1160 
1161 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
1162 
1163 #define	PC_FREE0	0xfffffffffffffffful
1164 #define	PC_FREE1	0x3ffffffffffffffful
1165 
1166 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1 };
1167 
1168 /*
1169  * Ensure that the number of spare PV entries in the specified pmap meets or
1170  * exceeds the given count, "needed".
1171  *
1172  * The given PV list lock may be released.
1173  */
1174 static void
1175 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
1176 {
1177 	struct pch new_tail;
1178 	struct pv_chunk *pc;
1179 	vm_page_t m;
1180 	int avail, free;
1181 	bool reclaimed;
1182 
1183 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1184 	KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
1185 
1186 	/*
1187 	 * Newly allocated PV chunks must be stored in a private list until
1188 	 * the required number of PV chunks have been allocated.  Otherwise,
1189 	 * reclaim_pv_chunk() could recycle one of these chunks.  In
1190 	 * contrast, these chunks must be added to the pmap upon allocation.
1191 	 */
1192 	TAILQ_INIT(&new_tail);
1193 retry:
1194 	avail = 0;
1195 	TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
1196 		//		if ((cpu_feature2 & CPUID2_POPCNT) == 0)
1197 		bit_count((bitstr_t *)pc->pc_map, 0,
1198 				  sizeof(pc->pc_map) * NBBY, &free);
1199 #if 0
1200 		free = popcnt_pc_map_pq(pc->pc_map);
1201 #endif
1202 		if (free == 0)
1203 			break;
1204 		avail += free;
1205 		if (avail >= needed)
1206 			break;
1207 	}
1208 	for (reclaimed = false; avail < needed; avail += _NPCPV) {
1209 		m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
1210 		    VM_ALLOC_WIRED);
1211 		if (m == NULL) {
1212 			m = reclaim_pv_chunk(pmap, lockp);
1213 			if (m == NULL)
1214 				goto retry;
1215 			reclaimed = true;
1216 		}
1217 		PV_STAT(atomic_add_int(&pc_chunk_count, 1));
1218 		PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
1219 		dump_add_page(m->phys_addr);
1220 		pc = (void *)PHYS_TO_DMAP(m->phys_addr);
1221 		pc->pc_pmap = pmap;
1222 		pc->pc_map[0] = PC_FREE0;
1223 		pc->pc_map[1] = PC_FREE1;
1224 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1225 		TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
1226 		PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
1227 
1228 		/*
1229 		 * The reclaim might have freed a chunk from the current pmap.
1230 		 * If that chunk contained available entries, we need to
1231 		 * re-count the number of available entries.
1232 		 */
1233 		if (reclaimed)
1234 			goto retry;
1235 	}
1236 	if (!TAILQ_EMPTY(&new_tail)) {
1237 		mtx_lock(&pv_chunks_mutex);
1238 		TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
1239 		mtx_unlock(&pv_chunks_mutex);
1240 	}
1241 }
1242 
1243 /*
1244  * First find and then remove the pv entry for the specified pmap and virtual
1245  * address from the specified pv list.  Returns the pv entry if found and NULL
1246  * otherwise.  This operation can be performed on pv lists for either 4KB or
1247  * 2MB page mappings.
1248  */
1249 static __inline pv_entry_t
1250 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
1251 {
1252 	pv_entry_t pv;
1253 
1254 	TAILQ_FOREACH(pv, &pvh->pv_list, pv_link) {
1255 #ifdef INVARIANTS
1256 		if (PV_PMAP(pv) == NULL) {
1257 			printf("corrupted pv_chunk/pv %p\n", pv);
1258 			printf("pv_chunk: %64D\n", pv_to_chunk(pv), ":");
1259 		}
1260 		MPASS(PV_PMAP(pv) != NULL);
1261 		MPASS(pv->pv_va != 0);
1262 #endif
1263 		if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
1264 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_link);
1265 			pvh->pv_gen++;
1266 			break;
1267 		}
1268 	}
1269 	return (pv);
1270 }
1271 
1272 /*
1273  * After demotion from a 2MB page mapping to 512 4KB page mappings,
1274  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
1275  * entries for each of the 4KB page mappings.
1276  */
1277 static void
1278 pmap_pv_demote_l3e(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1279     struct rwlock **lockp)
1280 {
1281 	struct md_page *pvh;
1282 	struct pv_chunk *pc;
1283 	pv_entry_t pv;
1284 	vm_offset_t va_last;
1285 	vm_page_t m;
1286 	int bit, field;
1287 
1288 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1289 	KASSERT((pa & L3_PAGE_MASK) == 0,
1290 	    ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
1291 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
1292 
1293 	/*
1294 	 * Transfer the 2mpage's pv entry for this mapping to the first
1295 	 * page's pv list.  Once this transfer begins, the pv list lock
1296 	 * must not be released until the last pv entry is reinstantiated.
1297 	 */
1298 	pvh = pa_to_pvh(pa);
1299 	va = trunc_2mpage(va);
1300 	pv = pmap_pvh_remove(pvh, pmap, va);
1301 	KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
1302 	m = PHYS_TO_VM_PAGE(pa);
1303 	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_link);
1304 
1305 	m->md.pv_gen++;
1306 	/* Instantiate the remaining NPTEPG - 1 pv entries. */
1307 	PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
1308 	va_last = va + L3_PAGE_SIZE - PAGE_SIZE;
1309 	for (;;) {
1310 		pc = TAILQ_FIRST(&pmap->pm_pvchunk);
1311 		KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0
1312 		    , ("pmap_pv_demote_pde: missing spare"));
1313 		for (field = 0; field < _NPCM; field++) {
1314 			while (pc->pc_map[field]) {
1315 				bit = cnttzd(pc->pc_map[field]);
1316 				pc->pc_map[field] &= ~(1ul << bit);
1317 				pv = &pc->pc_pventry[field * 64 + bit];
1318 				va += PAGE_SIZE;
1319 				pv->pv_va = va;
1320 				m++;
1321 				KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1322 			    ("pmap_pv_demote_pde: page %p is not managed", m));
1323 				TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_link);
1324 
1325 				m->md.pv_gen++;
1326 				if (va == va_last)
1327 					goto out;
1328 			}
1329 		}
1330 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1331 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
1332 	}
1333 out:
1334 	if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0) {
1335 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1336 		TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
1337 	}
1338 	PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
1339 	PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
1340 }
1341 
1342 static void
1343 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap)
1344 {
1345 
1346 	if (pmap == NULL)
1347 		return;
1348 	pmap_invalidate_all(pmap);
1349 	if (pmap != locked_pmap)
1350 		PMAP_UNLOCK(pmap);
1351 }
1352 
1353 /*
1354  * We are in a serious low memory condition.  Resort to
1355  * drastic measures to free some pages so we can allocate
1356  * another pv entry chunk.
1357  *
1358  * Returns NULL if PV entries were reclaimed from the specified pmap.
1359  *
1360  * We do not, however, unmap 2mpages because subsequent accesses will
1361  * allocate per-page pv entries until repromotion occurs, thereby
1362  * exacerbating the shortage of free pv entries.
1363  */
1364 static int active_reclaims = 0;
1365 static vm_page_t
1366 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
1367 {
1368 	struct pv_chunk *pc, *pc_marker, *pc_marker_end;
1369 	struct pv_chunk_header pc_marker_b, pc_marker_end_b;
1370 	struct md_page *pvh;
1371 	pml3_entry_t *l3e;
1372 	pmap_t next_pmap, pmap;
1373 	pt_entry_t *pte, tpte;
1374 	pv_entry_t pv;
1375 	vm_offset_t va;
1376 	vm_page_t m, m_pc;
1377 	struct spglist free;
1378 	uint64_t inuse;
1379 	int bit, field, freed;
1380 
1381 	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
1382 	KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
1383 	pmap = NULL;
1384 	m_pc = NULL;
1385 	SLIST_INIT(&free);
1386 	bzero(&pc_marker_b, sizeof(pc_marker_b));
1387 	bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
1388 	pc_marker = (struct pv_chunk *)&pc_marker_b;
1389 	pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
1390 
1391 	mtx_lock(&pv_chunks_mutex);
1392 	active_reclaims++;
1393 	TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
1394 	TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
1395 	while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
1396 	    SLIST_EMPTY(&free)) {
1397 		next_pmap = pc->pc_pmap;
1398 		if (next_pmap == NULL) {
1399 			/*
1400 			 * The next chunk is a marker.  However, it is
1401 			 * not our marker, so active_reclaims must be
1402 			 * > 1.  Consequently, the next_chunk code
1403 			 * will not rotate the pv_chunks list.
1404 			 */
1405 			goto next_chunk;
1406 		}
1407 		mtx_unlock(&pv_chunks_mutex);
1408 
1409 		/*
1410 		 * A pv_chunk can only be removed from the pc_lru list
1411 		 * when both pc_chunks_mutex is owned and the
1412 		 * corresponding pmap is locked.
1413 		 */
1414 		if (pmap != next_pmap) {
1415 			reclaim_pv_chunk_leave_pmap(pmap, locked_pmap);
1416 			pmap = next_pmap;
1417 			/* Avoid deadlock and lock recursion. */
1418 			if (pmap > locked_pmap) {
1419 				RELEASE_PV_LIST_LOCK(lockp);
1420 				PMAP_LOCK(pmap);
1421 				mtx_lock(&pv_chunks_mutex);
1422 				continue;
1423 			} else if (pmap != locked_pmap) {
1424 				if (PMAP_TRYLOCK(pmap)) {
1425 					mtx_lock(&pv_chunks_mutex);
1426 					continue;
1427 				} else {
1428 					pmap = NULL; /* pmap is not locked */
1429 					mtx_lock(&pv_chunks_mutex);
1430 					pc = TAILQ_NEXT(pc_marker, pc_lru);
1431 					if (pc == NULL ||
1432 					    pc->pc_pmap != next_pmap)
1433 						continue;
1434 					goto next_chunk;
1435 				}
1436 			}
1437 		}
1438 
1439 		/*
1440 		 * Destroy every non-wired, 4 KB page mapping in the chunk.
1441 		 */
1442 		freed = 0;
1443 		for (field = 0; field < _NPCM; field++) {
1444 			for (inuse = ~pc->pc_map[field] & pc_freemask[field];
1445 			    inuse != 0; inuse &= ~(1UL << bit)) {
1446 				bit = cnttzd(inuse);
1447 				pv = &pc->pc_pventry[field * 64 + bit];
1448 				va = pv->pv_va;
1449 				l3e = pmap_pml3e(pmap, va);
1450 				if ((be64toh(*l3e) & RPTE_LEAF) != 0)
1451 					continue;
1452 				pte = pmap_l3e_to_pte(l3e, va);
1453 				if ((be64toh(*pte) & PG_W) != 0)
1454 					continue;
1455 				tpte = be64toh(pte_load_clear(pte));
1456 				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
1457 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
1458 					vm_page_dirty(m);
1459 				if ((tpte & PG_A) != 0)
1460 					vm_page_aflag_set(m, PGA_REFERENCED);
1461 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
1462 				TAILQ_REMOVE(&m->md.pv_list, pv, pv_link);
1463 
1464 				m->md.pv_gen++;
1465 				if (TAILQ_EMPTY(&m->md.pv_list) &&
1466 				    (m->flags & PG_FICTITIOUS) == 0) {
1467 					pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
1468 					if (TAILQ_EMPTY(&pvh->pv_list)) {
1469 						vm_page_aflag_clear(m,
1470 						    PGA_WRITEABLE);
1471 					}
1472 				}
1473 				pc->pc_map[field] |= 1UL << bit;
1474 				pmap_unuse_pt(pmap, va, be64toh(*l3e), &free);
1475 				freed++;
1476 			}
1477 		}
1478 		if (freed == 0) {
1479 			mtx_lock(&pv_chunks_mutex);
1480 			goto next_chunk;
1481 		}
1482 		/* Every freed mapping is for a 4 KB page. */
1483 		pmap_resident_count_dec(pmap, freed);
1484 		PV_STAT(atomic_add_long(&pv_entry_frees, freed));
1485 		PV_STAT(atomic_add_int(&pv_entry_spare, freed));
1486 		PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
1487 		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1488 		if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1) {
1489 			PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
1490 			PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
1491 			PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
1492 			/* Entire chunk is free; return it. */
1493 			m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
1494 			dump_drop_page(m_pc->phys_addr);
1495 			mtx_lock(&pv_chunks_mutex);
1496 			TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
1497 			break;
1498 		}
1499 		TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1500 		mtx_lock(&pv_chunks_mutex);
1501 		/* One freed pv entry in locked_pmap is sufficient. */
1502 		if (pmap == locked_pmap)
1503 			break;
1504 next_chunk:
1505 		TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
1506 		TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
1507 		if (active_reclaims == 1 && pmap != NULL) {
1508 			/*
1509 			 * Rotate the pv chunks list so that we do not
1510 			 * scan the same pv chunks that could not be
1511 			 * freed (because they contained a wired
1512 			 * and/or superpage mapping) on every
1513 			 * invocation of reclaim_pv_chunk().
1514 			 */
1515 			while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
1516 				MPASS(pc->pc_pmap != NULL);
1517 				TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
1518 				TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
1519 			}
1520 		}
1521 	}
1522 	TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
1523 	TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
1524 	active_reclaims--;
1525 	mtx_unlock(&pv_chunks_mutex);
1526 	reclaim_pv_chunk_leave_pmap(pmap, locked_pmap);
1527 	if (m_pc == NULL && !SLIST_EMPTY(&free)) {
1528 		m_pc = SLIST_FIRST(&free);
1529 		SLIST_REMOVE_HEAD(&free, plinks.s.ss);
1530 		/* Recycle a freed page table page. */
1531 		m_pc->ref_count = 1;
1532 	}
1533 	vm_page_free_pages_toq(&free, true);
1534 	return (m_pc);
1535 }
1536 
1537 /*
1538  * free the pv_entry back to the free list
1539  */
1540 static void
1541 free_pv_entry(pmap_t pmap, pv_entry_t pv)
1542 {
1543 	struct pv_chunk *pc;
1544 	int idx, field, bit;
1545 
1546 #ifdef VERBOSE_PV
1547 	if (pmap != kernel_pmap)
1548 		printf("%s(%p, %p)\n", __func__, pmap, pv);
1549 #endif
1550 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1551 	PV_STAT(atomic_add_long(&pv_entry_frees, 1));
1552 	PV_STAT(atomic_add_int(&pv_entry_spare, 1));
1553 	PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
1554 	pc = pv_to_chunk(pv);
1555 	idx = pv - &pc->pc_pventry[0];
1556 	field = idx / 64;
1557 	bit = idx % 64;
1558 	pc->pc_map[field] |= 1ul << bit;
1559 	if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1) {
1560 		/* 98% of the time, pc is already at the head of the list. */
1561 		if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
1562 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1563 			TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1564 		}
1565 		return;
1566 	}
1567 	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1568 	free_pv_chunk(pc);
1569 }
1570 
1571 static void
1572 free_pv_chunk(struct pv_chunk *pc)
1573 {
1574 	vm_page_t m;
1575 
1576 	mtx_lock(&pv_chunks_mutex);
1577  	TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
1578 	mtx_unlock(&pv_chunks_mutex);
1579 	PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
1580 	PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
1581 	PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
1582 	/* entire chunk is free, return it */
1583 	m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
1584 	dump_drop_page(m->phys_addr);
1585 	vm_page_unwire_noq(m);
1586 	vm_page_free(m);
1587 }
1588 
1589 /*
1590  * Returns a new PV entry, allocating a new PV chunk from the system when
1591  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
1592  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
1593  * returned.
1594  *
1595  * The given PV list lock may be released.
1596  */
1597 static pv_entry_t
1598 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
1599 {
1600 	int bit, field;
1601 	pv_entry_t pv;
1602 	struct pv_chunk *pc;
1603 	vm_page_t m;
1604 
1605 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1606 	PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
1607 retry:
1608 	pc = TAILQ_FIRST(&pmap->pm_pvchunk);
1609 	if (pc != NULL) {
1610 		for (field = 0; field < _NPCM; field++) {
1611 			if (pc->pc_map[field]) {
1612 				bit = cnttzd(pc->pc_map[field]);
1613 				break;
1614 			}
1615 		}
1616 		if (field < _NPCM) {
1617 			pv = &pc->pc_pventry[field * 64 + bit];
1618 			pc->pc_map[field] &= ~(1ul << bit);
1619 			/* If this was the last item, move it to tail */
1620 			if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0) {
1621 				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1622 				TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
1623 				    pc_list);
1624 			}
1625 			PV_STAT(atomic_add_long(&pv_entry_count, 1));
1626 			PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
1627 			MPASS(PV_PMAP(pv) != NULL);
1628 			return (pv);
1629 		}
1630 	}
1631 	/* No free items, allocate another chunk */
1632 	m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
1633 	    VM_ALLOC_WIRED);
1634 	if (m == NULL) {
1635 		if (lockp == NULL) {
1636 			PV_STAT(pc_chunk_tryfail++);
1637 			return (NULL);
1638 		}
1639 		m = reclaim_pv_chunk(pmap, lockp);
1640 		if (m == NULL)
1641 			goto retry;
1642 	}
1643 	PV_STAT(atomic_add_int(&pc_chunk_count, 1));
1644 	PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
1645 	dump_add_page(m->phys_addr);
1646 	pc = (void *)PHYS_TO_DMAP(m->phys_addr);
1647 	pc->pc_pmap = pmap;
1648 	pc->pc_map[0] = PC_FREE0 & ~1ul;	/* preallocated bit 0 */
1649 	pc->pc_map[1] = PC_FREE1;
1650 	mtx_lock(&pv_chunks_mutex);
1651 	TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
1652 	mtx_unlock(&pv_chunks_mutex);
1653 	pv = &pc->pc_pventry[0];
1654 	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1655 	PV_STAT(atomic_add_long(&pv_entry_count, 1));
1656 	PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
1657 	MPASS(PV_PMAP(pv) != NULL);
1658 	return (pv);
1659 }
1660 
1661 #if VM_NRESERVLEVEL > 0
1662 /*
1663  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
1664  * replace the many pv entries for the 4KB page mappings by a single pv entry
1665  * for the 2MB page mapping.
1666  */
1667 static void
1668 pmap_pv_promote_l3e(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1669     struct rwlock **lockp)
1670 {
1671 	struct md_page *pvh;
1672 	pv_entry_t pv;
1673 	vm_offset_t va_last;
1674 	vm_page_t m;
1675 
1676 	KASSERT((pa & L3_PAGE_MASK) == 0,
1677 	    ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
1678 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
1679 
1680 	/*
1681 	 * Transfer the first page's pv entry for this mapping to the 2mpage's
1682 	 * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
1683 	 * a transfer avoids the possibility that get_pv_entry() calls
1684 	 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
1685 	 * mappings that is being promoted.
1686 	 */
1687 	m = PHYS_TO_VM_PAGE(pa);
1688 	va = trunc_2mpage(va);
1689 	pv = pmap_pvh_remove(&m->md, pmap, va);
1690 	KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
1691 	pvh = pa_to_pvh(pa);
1692 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_link);
1693 	pvh->pv_gen++;
1694 	/* Free the remaining NPTEPG - 1 pv entries. */
1695 	va_last = va + L3_PAGE_SIZE - PAGE_SIZE;
1696 	do {
1697 		m++;
1698 		va += PAGE_SIZE;
1699 		pmap_pvh_free(&m->md, pmap, va);
1700 	} while (va < va_last);
1701 }
1702 #endif /* VM_NRESERVLEVEL > 0 */
1703 
1704 /*
1705  * First find and then destroy the pv entry for the specified pmap and virtual
1706  * address.  This operation can be performed on pv lists for either 4KB or 2MB
1707  * page mappings.
1708  */
1709 static void
1710 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
1711 {
1712 	pv_entry_t pv;
1713 
1714 	pv = pmap_pvh_remove(pvh, pmap, va);
1715 	KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
1716 	free_pv_entry(pmap, pv);
1717 }
1718 
1719 /*
1720  * Conditionally create the PV entry for a 4KB page mapping if the required
1721  * memory can be allocated without resorting to reclamation.
1722  */
1723 static boolean_t
1724 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
1725     struct rwlock **lockp)
1726 {
1727 	pv_entry_t pv;
1728 
1729 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1730 	/* Pass NULL instead of the lock pointer to disable reclamation. */
1731 	if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
1732 		pv->pv_va = va;
1733 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
1734 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_link);
1735 		m->md.pv_gen++;
1736 		return (TRUE);
1737 	} else
1738 		return (FALSE);
1739 }
1740 
1741 vm_paddr_t phys_avail_debug[2 * VM_PHYSSEG_MAX];
1742 #ifdef INVARIANTS
1743 static void
1744 validate_addr(vm_paddr_t addr, vm_size_t size)
1745 {
1746 	vm_paddr_t end = addr + size;
1747 	bool found = false;
1748 
1749 	for (int i = 0; i < 2 * phys_avail_count; i += 2) {
1750 		if (addr >= phys_avail_debug[i] &&
1751 			end <= phys_avail_debug[i + 1]) {
1752 			found = true;
1753 			break;
1754 		}
1755 	}
1756 	KASSERT(found, ("%#lx-%#lx outside of initial phys_avail array",
1757 					addr, end));
1758 }
1759 #else
1760 static void validate_addr(vm_paddr_t addr, vm_size_t size) {}
1761 #endif
1762 #define DMAP_PAGE_BITS (RPTE_VALID | RPTE_LEAF | RPTE_EAA_MASK | PG_M | PG_A)
1763 
1764 static vm_paddr_t
1765 alloc_pt_page(void)
1766 {
1767 	vm_paddr_t page;
1768 
1769 	page = allocpages(1);
1770 	pagezero(PHYS_TO_DMAP(page));
1771 	return (page);
1772 }
1773 
1774 static void
1775 mmu_radix_dmap_range(vm_paddr_t start, vm_paddr_t end)
1776 {
1777 	pt_entry_t *pte, pteval;
1778 	vm_paddr_t page;
1779 
1780 	if (bootverbose)
1781 		printf("%s %lx -> %lx\n", __func__, start, end);
1782 	while (start < end) {
1783 		pteval = start | DMAP_PAGE_BITS;
1784 		pte = pmap_pml1e(kernel_pmap, PHYS_TO_DMAP(start));
1785 		if ((be64toh(*pte) & RPTE_VALID) == 0) {
1786 			page = alloc_pt_page();
1787 			pde_store(pte, page);
1788 		}
1789 		pte = pmap_l1e_to_l2e(pte, PHYS_TO_DMAP(start));
1790 		if ((start & L2_PAGE_MASK) == 0 &&
1791 			end - start >= L2_PAGE_SIZE) {
1792 			start += L2_PAGE_SIZE;
1793 			goto done;
1794 		} else if ((be64toh(*pte) & RPTE_VALID) == 0) {
1795 			page = alloc_pt_page();
1796 			pde_store(pte, page);
1797 		}
1798 
1799 		pte = pmap_l2e_to_l3e(pte, PHYS_TO_DMAP(start));
1800 		if ((start & L3_PAGE_MASK) == 0 &&
1801 			end - start >= L3_PAGE_SIZE) {
1802 			start += L3_PAGE_SIZE;
1803 			goto done;
1804 		} else if ((be64toh(*pte) & RPTE_VALID) == 0) {
1805 			page = alloc_pt_page();
1806 			pde_store(pte, page);
1807 		}
1808 		pte = pmap_l3e_to_pte(pte, PHYS_TO_DMAP(start));
1809 		start += PAGE_SIZE;
1810 	done:
1811 		pte_store(pte, pteval);
1812 	}
1813 }
1814 
1815 static void
1816 mmu_radix_dmap_populate(vm_size_t hwphyssz)
1817 {
1818 	vm_paddr_t start, end;
1819 
1820 	for (int i = 0; i < pregions_sz; i++) {
1821 		start = pregions[i].mr_start;
1822 		end = start + pregions[i].mr_size;
1823 		if (hwphyssz && start >= hwphyssz)
1824 			break;
1825 		if (hwphyssz && hwphyssz < end)
1826 			end = hwphyssz;
1827 		mmu_radix_dmap_range(start, end);
1828 	}
1829 }
1830 
1831 static void
1832 mmu_radix_setup_pagetables(vm_size_t hwphyssz)
1833 {
1834 	vm_paddr_t ptpages, pages;
1835 	pt_entry_t *pte;
1836 	vm_paddr_t l1phys;
1837 
1838 	bzero(kernel_pmap, sizeof(struct pmap));
1839 	PMAP_LOCK_INIT(kernel_pmap);
1840 
1841 	ptpages = allocpages(3);
1842 	l1phys = moea64_bootstrap_alloc(RADIX_PGD_SIZE, RADIX_PGD_SIZE);
1843 	validate_addr(l1phys, RADIX_PGD_SIZE);
1844 	if (bootverbose)
1845 		printf("l1phys=%lx\n", l1phys);
1846 	MPASS((l1phys & (RADIX_PGD_SIZE-1)) == 0);
1847 	for (int i = 0; i < RADIX_PGD_SIZE/PAGE_SIZE; i++)
1848 		pagezero(PHYS_TO_DMAP(l1phys + i * PAGE_SIZE));
1849 	kernel_pmap->pm_pml1 = (pml1_entry_t *)PHYS_TO_DMAP(l1phys);
1850 
1851 	mmu_radix_dmap_populate(hwphyssz);
1852 
1853 	/*
1854 	 * Create page tables for first 128MB of KVA
1855 	 */
1856 	pages = ptpages;
1857 	pte = pmap_pml1e(kernel_pmap, VM_MIN_KERNEL_ADDRESS);
1858 	*pte = htobe64(pages | RPTE_VALID | RPTE_SHIFT);
1859 	pages += PAGE_SIZE;
1860 	pte = pmap_l1e_to_l2e(pte, VM_MIN_KERNEL_ADDRESS);
1861 	*pte = htobe64(pages | RPTE_VALID | RPTE_SHIFT);
1862 	pages += PAGE_SIZE;
1863 	pte = pmap_l2e_to_l3e(pte, VM_MIN_KERNEL_ADDRESS);
1864 	/*
1865 	 * the kernel page table pages need to be preserved in
1866 	 * phys_avail and not overlap with previous  allocations
1867 	 */
1868 	pages = allocpages(nkpt);
1869 	if (bootverbose) {
1870 		printf("phys_avail after dmap populate and nkpt allocation\n");
1871 		for (int j = 0; j < 2 * phys_avail_count; j+=2)
1872 			printf("phys_avail[%d]=%08lx - phys_avail[%d]=%08lx\n",
1873 				   j, phys_avail[j], j + 1, phys_avail[j + 1]);
1874 	}
1875 	KPTphys = pages;
1876 	for (int i = 0; i < nkpt; i++, pte++, pages += PAGE_SIZE)
1877 		*pte = htobe64(pages | RPTE_VALID | RPTE_SHIFT);
1878 	kernel_vm_end = VM_MIN_KERNEL_ADDRESS + nkpt * L3_PAGE_SIZE;
1879 	if (bootverbose)
1880 		printf("kernel_pmap pml1 %p\n", kernel_pmap->pm_pml1);
1881 	/*
1882 	 * Add a physical memory segment (vm_phys_seg) corresponding to the
1883 	 * preallocated kernel page table pages so that vm_page structures
1884 	 * representing these pages will be created.  The vm_page structures
1885 	 * are required for promotion of the corresponding kernel virtual
1886 	 * addresses to superpage mappings.
1887 	 */
1888 	vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1889 }
1890 
1891 static void
1892 mmu_radix_early_bootstrap(vm_offset_t start, vm_offset_t end)
1893 {
1894 	vm_paddr_t	kpstart, kpend;
1895 	vm_size_t	physsz, hwphyssz;
1896 	//uint64_t	l2virt;
1897 	int		rm_pavail, proctab_size;
1898 	int		i, j;
1899 
1900 	kpstart = start & ~DMAP_BASE_ADDRESS;
1901 	kpend = end & ~DMAP_BASE_ADDRESS;
1902 
1903 	/* Get physical memory regions from firmware */
1904 	mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
1905 	CTR0(KTR_PMAP, "mmu_radix_early_bootstrap: physical memory");
1906 
1907 	if (2 * VM_PHYSSEG_MAX < regions_sz)
1908 		panic("mmu_radix_early_bootstrap: phys_avail too small");
1909 
1910 	if (bootverbose)
1911 		for (int i = 0; i < regions_sz; i++)
1912 			printf("regions[%d].mr_start=%lx regions[%d].mr_size=%lx\n",
1913 			    i, regions[i].mr_start, i, regions[i].mr_size);
1914 	/*
1915 	 * XXX workaround a simulator bug
1916 	 */
1917 	for (int i = 0; i < regions_sz; i++)
1918 		if (regions[i].mr_start & PAGE_MASK) {
1919 			regions[i].mr_start += PAGE_MASK;
1920 			regions[i].mr_start &= ~PAGE_MASK;
1921 			regions[i].mr_size &= ~PAGE_MASK;
1922 		}
1923 	if (bootverbose)
1924 		for (int i = 0; i < pregions_sz; i++)
1925 			printf("pregions[%d].mr_start=%lx pregions[%d].mr_size=%lx\n",
1926 			    i, pregions[i].mr_start, i, pregions[i].mr_size);
1927 
1928 	phys_avail_count = 0;
1929 	physsz = 0;
1930 	hwphyssz = 0;
1931 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
1932 	for (i = 0, j = 0; i < regions_sz; i++) {
1933 		if (bootverbose)
1934 			printf("regions[%d].mr_start=%016lx regions[%d].mr_size=%016lx\n",
1935 			    i, regions[i].mr_start, i, regions[i].mr_size);
1936 
1937 		if (regions[i].mr_size < PAGE_SIZE)
1938 			continue;
1939 
1940 		if (hwphyssz != 0 &&
1941 		    (physsz + regions[i].mr_size) >= hwphyssz) {
1942 			if (physsz < hwphyssz) {
1943 				phys_avail[j] = regions[i].mr_start;
1944 				phys_avail[j + 1] = regions[i].mr_start +
1945 				    (hwphyssz - physsz);
1946 				physsz = hwphyssz;
1947 				phys_avail_count++;
1948 				dump_avail[j] = phys_avail[j];
1949 				dump_avail[j + 1] = phys_avail[j + 1];
1950 			}
1951 			break;
1952 		}
1953 		phys_avail[j] = regions[i].mr_start;
1954 		phys_avail[j + 1] = regions[i].mr_start + regions[i].mr_size;
1955 		dump_avail[j] = phys_avail[j];
1956 		dump_avail[j + 1] = phys_avail[j + 1];
1957 
1958 		phys_avail_count++;
1959 		physsz += regions[i].mr_size;
1960 		j += 2;
1961 	}
1962 
1963 	/* Check for overlap with the kernel and exception vectors */
1964 	rm_pavail = 0;
1965 	for (j = 0; j < 2 * phys_avail_count; j+=2) {
1966 		if (phys_avail[j] < EXC_LAST)
1967 			phys_avail[j] += EXC_LAST;
1968 
1969 		if (phys_avail[j] >= kpstart &&
1970 		    phys_avail[j + 1] <= kpend) {
1971 			phys_avail[j] = phys_avail[j + 1] = ~0;
1972 			rm_pavail++;
1973 			continue;
1974 		}
1975 
1976 		if (kpstart >= phys_avail[j] &&
1977 		    kpstart < phys_avail[j + 1]) {
1978 			if (kpend < phys_avail[j + 1]) {
1979 				phys_avail[2 * phys_avail_count] =
1980 				    (kpend & ~PAGE_MASK) + PAGE_SIZE;
1981 				phys_avail[2 * phys_avail_count + 1] =
1982 				    phys_avail[j + 1];
1983 				phys_avail_count++;
1984 			}
1985 
1986 			phys_avail[j + 1] = kpstart & ~PAGE_MASK;
1987 		}
1988 
1989 		if (kpend >= phys_avail[j] &&
1990 		    kpend < phys_avail[j + 1]) {
1991 			if (kpstart > phys_avail[j]) {
1992 				phys_avail[2 * phys_avail_count] = phys_avail[j];
1993 				phys_avail[2 * phys_avail_count + 1] =
1994 				    kpstart & ~PAGE_MASK;
1995 				phys_avail_count++;
1996 			}
1997 
1998 			phys_avail[j] = (kpend & ~PAGE_MASK) +
1999 			    PAGE_SIZE;
2000 		}
2001 	}
2002 	qsort(phys_avail, 2 * phys_avail_count, sizeof(phys_avail[0]), pa_cmp);
2003 	for (i = 0; i < 2 * phys_avail_count; i++)
2004 		phys_avail_debug[i] = phys_avail[i];
2005 
2006 	/* Remove physical available regions marked for removal (~0) */
2007 	if (rm_pavail) {
2008 		phys_avail_count -= rm_pavail;
2009 		for (i = 2 * phys_avail_count;
2010 		     i < 2*(phys_avail_count + rm_pavail); i+=2)
2011 			phys_avail[i] = phys_avail[i + 1] = 0;
2012 	}
2013 	if (bootverbose) {
2014 		printf("phys_avail ranges after filtering:\n");
2015 		for (j = 0; j < 2 * phys_avail_count; j+=2)
2016 			printf("phys_avail[%d]=%08lx - phys_avail[%d]=%08lx\n",
2017 				   j, phys_avail[j], j + 1, phys_avail[j + 1]);
2018 	}
2019 	physmem = btoc(physsz);
2020 
2021 	/* XXX assume we're running non-virtualized and
2022 	 * we don't support BHYVE
2023 	 */
2024 	if (isa3_pid_bits == 0)
2025 		isa3_pid_bits = 20;
2026 	parttab_phys = moea64_bootstrap_alloc(PARTTAB_SIZE, PARTTAB_SIZE);
2027 	validate_addr(parttab_phys, PARTTAB_SIZE);
2028 	for (int i = 0; i < PARTTAB_SIZE/PAGE_SIZE; i++)
2029 		pagezero(PHYS_TO_DMAP(parttab_phys + i * PAGE_SIZE));
2030 
2031 	proctab_size = 1UL << PROCTAB_SIZE_SHIFT;
2032 	proctab0pa = moea64_bootstrap_alloc(proctab_size, proctab_size);
2033 	validate_addr(proctab0pa, proctab_size);
2034 	for (int i = 0; i < proctab_size/PAGE_SIZE; i++)
2035 		pagezero(PHYS_TO_DMAP(proctab0pa + i * PAGE_SIZE));
2036 
2037 	mmu_radix_setup_pagetables(hwphyssz);
2038 }
2039 
2040 static void
2041 mmu_radix_late_bootstrap(vm_offset_t start, vm_offset_t end)
2042 {
2043 	int		i;
2044 	vm_paddr_t	pa;
2045 	void		*dpcpu;
2046 	vm_offset_t va;
2047 
2048 	/*
2049 	 * Set up the Open Firmware pmap and add its mappings if not in real
2050 	 * mode.
2051 	 */
2052 	if (bootverbose)
2053 		printf("%s enter\n", __func__);
2054 
2055 	/*
2056 	 * Calculate the last available physical address, and reserve the
2057 	 * vm_page_array (upper bound).
2058 	 */
2059 	Maxmem = 0;
2060 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
2061 		Maxmem = MAX(Maxmem, powerpc_btop(phys_avail[i + 1]));
2062 
2063 	/*
2064 	 * Set the start and end of kva.
2065 	 */
2066 	virtual_avail = VM_MIN_KERNEL_ADDRESS;
2067 	virtual_end = VM_MAX_SAFE_KERNEL_ADDRESS;
2068 
2069 	/*
2070 	 * Remap any early IO mappings (console framebuffer, etc.)
2071 	 */
2072 	bs_remap_earlyboot();
2073 
2074 	/*
2075 	 * Allocate a kernel stack with a guard page for thread0 and map it
2076 	 * into the kernel page map.
2077 	 */
2078 	pa = allocpages(kstack_pages);
2079 	va = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
2080 	virtual_avail = va + kstack_pages * PAGE_SIZE;
2081 	CTR2(KTR_PMAP, "moea64_bootstrap: kstack0 at %#x (%#x)", pa, va);
2082 	thread0.td_kstack = va;
2083 	for (i = 0; i < kstack_pages; i++) {
2084 		mmu_radix_kenter(va, pa);
2085 		pa += PAGE_SIZE;
2086 		va += PAGE_SIZE;
2087 	}
2088 	thread0.td_kstack_pages = kstack_pages;
2089 
2090 	/*
2091 	 * Allocate virtual address space for the message buffer.
2092 	 */
2093 	pa = msgbuf_phys = allocpages((msgbufsize + PAGE_MASK)  >> PAGE_SHIFT);
2094 	msgbufp = (struct msgbuf *)PHYS_TO_DMAP(pa);
2095 
2096 	/*
2097 	 * Allocate virtual address space for the dynamic percpu area.
2098 	 */
2099 	pa = allocpages(DPCPU_SIZE >> PAGE_SHIFT);
2100 	dpcpu = (void *)PHYS_TO_DMAP(pa);
2101 	dpcpu_init(dpcpu, curcpu);
2102 
2103 	crashdumpmap = (caddr_t)virtual_avail;
2104 	virtual_avail += MAXDUMPPGS * PAGE_SIZE;
2105 
2106 	/*
2107 	 * Reserve some special page table entries/VA space for temporary
2108 	 * mapping of pages.
2109 	 */
2110 }
2111 
2112 static void
2113 mmu_parttab_init(void)
2114 {
2115 	uint64_t ptcr;
2116 
2117 	isa3_parttab = (struct pate *)PHYS_TO_DMAP(parttab_phys);
2118 
2119 	if (bootverbose)
2120 		printf("%s parttab: %p\n", __func__, isa3_parttab);
2121 	ptcr = parttab_phys | (PARTTAB_SIZE_SHIFT-12);
2122 	if (bootverbose)
2123 		printf("setting ptcr %lx\n", ptcr);
2124 	mtspr(SPR_PTCR, ptcr);
2125 }
2126 
2127 static void
2128 mmu_parttab_update(uint64_t lpid, uint64_t pagetab, uint64_t proctab)
2129 {
2130 	uint64_t prev;
2131 
2132 	if (bootverbose)
2133 		printf("%s isa3_parttab %p lpid %lx pagetab %lx proctab %lx\n", __func__, isa3_parttab,
2134 			   lpid, pagetab, proctab);
2135 	prev = be64toh(isa3_parttab[lpid].pagetab);
2136 	isa3_parttab[lpid].pagetab = htobe64(pagetab);
2137 	isa3_parttab[lpid].proctab = htobe64(proctab);
2138 
2139 	if (prev & PARTTAB_HR) {
2140 		__asm __volatile(PPC_TLBIE_5(%0,%1,2,0,1) : :
2141 			     "r" (TLBIEL_INVAL_SET_LPID), "r" (lpid));
2142 		__asm __volatile(PPC_TLBIE_5(%0,%1,2,1,1) : :
2143 			     "r" (TLBIEL_INVAL_SET_LPID), "r" (lpid));
2144 	} else {
2145 		__asm __volatile(PPC_TLBIE_5(%0,%1,2,0,0) : :
2146 			     "r" (TLBIEL_INVAL_SET_LPID), "r" (lpid));
2147 	}
2148 	ttusync();
2149 }
2150 
2151 static void
2152 mmu_radix_parttab_init(void)
2153 {
2154 	uint64_t pagetab;
2155 
2156 	mmu_parttab_init();
2157 	pagetab = RTS_SIZE | DMAP_TO_PHYS((vm_offset_t)kernel_pmap->pm_pml1) | \
2158 		         RADIX_PGD_INDEX_SHIFT | PARTTAB_HR;
2159 	mmu_parttab_update(0, pagetab, 0);
2160 }
2161 
2162 static void
2163 mmu_radix_proctab_register(vm_paddr_t proctabpa, uint64_t table_size)
2164 {
2165 	uint64_t pagetab, proctab;
2166 
2167 	pagetab = be64toh(isa3_parttab[0].pagetab);
2168 	proctab = proctabpa | table_size | PARTTAB_GR;
2169 	mmu_parttab_update(0, pagetab, proctab);
2170 }
2171 
2172 static void
2173 mmu_radix_proctab_init(void)
2174 {
2175 
2176 	isa3_base_pid = 1;
2177 
2178 	isa3_proctab = (void*)PHYS_TO_DMAP(proctab0pa);
2179 	isa3_proctab->proctab0 =
2180 	    htobe64(RTS_SIZE | DMAP_TO_PHYS((vm_offset_t)kernel_pmap->pm_pml1) |
2181 		RADIX_PGD_INDEX_SHIFT);
2182 
2183 	mmu_radix_proctab_register(proctab0pa, PROCTAB_SIZE_SHIFT - 12);
2184 
2185 	__asm __volatile("ptesync" : : : "memory");
2186 	__asm __volatile(PPC_TLBIE_5(%0,%1,2,1,1) : :
2187 		     "r" (TLBIEL_INVAL_SET_LPID), "r" (0));
2188 	__asm __volatile("eieio; tlbsync; ptesync" : : : "memory");
2189 	if (bootverbose)
2190 		printf("process table %p and kernel radix PDE: %p\n",
2191 			   isa3_proctab, kernel_pmap->pm_pml1);
2192 	mtmsr(mfmsr() | PSL_DR );
2193 	mtmsr(mfmsr() &  ~PSL_DR);
2194 	kernel_pmap->pm_pid = isa3_base_pid;
2195 	isa3_base_pid++;
2196 }
2197 
2198 void
2199 mmu_radix_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
2200     int advice)
2201 {
2202 	struct rwlock *lock;
2203 	pml1_entry_t *l1e;
2204 	pml2_entry_t *l2e;
2205 	pml3_entry_t oldl3e, *l3e;
2206 	pt_entry_t *pte;
2207 	vm_offset_t va, va_next;
2208 	vm_page_t m;
2209 	boolean_t anychanged;
2210 
2211 	if (advice != MADV_DONTNEED && advice != MADV_FREE)
2212 		return;
2213 	anychanged = FALSE;
2214 	PMAP_LOCK(pmap);
2215 	for (; sva < eva; sva = va_next) {
2216 		l1e = pmap_pml1e(pmap, sva);
2217 		if ((be64toh(*l1e) & PG_V) == 0) {
2218 			va_next = (sva + L1_PAGE_SIZE) & ~L1_PAGE_MASK;
2219 			if (va_next < sva)
2220 				va_next = eva;
2221 			continue;
2222 		}
2223 		l2e = pmap_l1e_to_l2e(l1e, sva);
2224 		if ((be64toh(*l2e) & PG_V) == 0) {
2225 			va_next = (sva + L2_PAGE_SIZE) & ~L2_PAGE_MASK;
2226 			if (va_next < sva)
2227 				va_next = eva;
2228 			continue;
2229 		}
2230 		va_next = (sva + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
2231 		if (va_next < sva)
2232 			va_next = eva;
2233 		l3e = pmap_l2e_to_l3e(l2e, sva);
2234 		oldl3e = be64toh(*l3e);
2235 		if ((oldl3e & PG_V) == 0)
2236 			continue;
2237 		else if ((oldl3e & RPTE_LEAF) != 0) {
2238 			if ((oldl3e & PG_MANAGED) == 0)
2239 				continue;
2240 			lock = NULL;
2241 			if (!pmap_demote_l3e_locked(pmap, l3e, sva, &lock)) {
2242 				if (lock != NULL)
2243 					rw_wunlock(lock);
2244 
2245 				/*
2246 				 * The large page mapping was destroyed.
2247 				 */
2248 				continue;
2249 			}
2250 
2251 			/*
2252 			 * Unless the page mappings are wired, remove the
2253 			 * mapping to a single page so that a subsequent
2254 			 * access may repromote.  Since the underlying page
2255 			 * table page is fully populated, this removal never
2256 			 * frees a page table page.
2257 			 */
2258 			if ((oldl3e & PG_W) == 0) {
2259 				pte = pmap_l3e_to_pte(l3e, sva);
2260 				KASSERT((be64toh(*pte) & PG_V) != 0,
2261 				    ("pmap_advise: invalid PTE"));
2262 				pmap_remove_pte(pmap, pte, sva, be64toh(*l3e), NULL,
2263 				    &lock);
2264 				anychanged = TRUE;
2265 			}
2266 			if (lock != NULL)
2267 				rw_wunlock(lock);
2268 		}
2269 		if (va_next > eva)
2270 			va_next = eva;
2271 		va = va_next;
2272 		for (pte = pmap_l3e_to_pte(l3e, sva); sva != va_next;
2273 			 pte++, sva += PAGE_SIZE) {
2274 			MPASS(pte == pmap_pte(pmap, sva));
2275 
2276 			if ((be64toh(*pte) & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
2277 				goto maybe_invlrng;
2278 			else if ((be64toh(*pte) & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
2279 				if (advice == MADV_DONTNEED) {
2280 					/*
2281 					 * Future calls to pmap_is_modified()
2282 					 * can be avoided by making the page
2283 					 * dirty now.
2284 					 */
2285 					m = PHYS_TO_VM_PAGE(be64toh(*pte) & PG_FRAME);
2286 					vm_page_dirty(m);
2287 				}
2288 				atomic_clear_long(pte, htobe64(PG_M | PG_A));
2289 			} else if ((be64toh(*pte) & PG_A) != 0)
2290 				atomic_clear_long(pte, htobe64(PG_A));
2291 			else
2292 				goto maybe_invlrng;
2293 			anychanged = TRUE;
2294 			continue;
2295 maybe_invlrng:
2296 			if (va != va_next) {
2297 				anychanged = true;
2298 				va = va_next;
2299 			}
2300 		}
2301 		if (va != va_next)
2302 			anychanged = true;
2303 	}
2304 	if (anychanged)
2305 		pmap_invalidate_all(pmap);
2306 	PMAP_UNLOCK(pmap);
2307 }
2308 
2309 /*
2310  * Routines used in machine-dependent code
2311  */
2312 static void
2313 mmu_radix_bootstrap(vm_offset_t start, vm_offset_t end)
2314 {
2315 	uint64_t lpcr;
2316 
2317 	if (bootverbose)
2318 		printf("%s\n", __func__);
2319 	hw_direct_map = 1;
2320 	mmu_radix_early_bootstrap(start, end);
2321 	if (bootverbose)
2322 		printf("early bootstrap complete\n");
2323 	if (powernv_enabled) {
2324 		lpcr = mfspr(SPR_LPCR);
2325 		mtspr(SPR_LPCR, lpcr | LPCR_UPRT | LPCR_HR);
2326 		mmu_radix_parttab_init();
2327 		mmu_radix_init_amor();
2328 		if (bootverbose)
2329 			printf("powernv init complete\n");
2330 	}
2331 	mmu_radix_init_iamr();
2332 	mmu_radix_proctab_init();
2333 	mmu_radix_pid_set(kernel_pmap);
2334 	/* XXX assume CPU_FTR_HVMODE */
2335 	mmu_radix_tlbiel_flush(TLB_INVAL_SCOPE_GLOBAL);
2336 
2337 	mmu_radix_late_bootstrap(start, end);
2338 	numa_mem_regions(&numa_pregions, &numa_pregions_sz);
2339 	if (bootverbose)
2340 		printf("%s done\n", __func__);
2341 	pmap_bootstrapped = 1;
2342 	dmaplimit = roundup2(powerpc_ptob(Maxmem), L2_PAGE_SIZE);
2343 	PCPU_SET(flags, PCPU_GET(flags) | PC_FLAG_NOSRS);
2344 }
2345 
2346 static void
2347 mmu_radix_cpu_bootstrap(int ap)
2348 {
2349 	uint64_t lpcr;
2350 	uint64_t ptcr;
2351 
2352 	if (powernv_enabled) {
2353 		lpcr = mfspr(SPR_LPCR);
2354 		mtspr(SPR_LPCR, lpcr | LPCR_UPRT | LPCR_HR);
2355 
2356 		ptcr = parttab_phys | (PARTTAB_SIZE_SHIFT-12);
2357 		mtspr(SPR_PTCR, ptcr);
2358 		mmu_radix_init_amor();
2359 	}
2360 	mmu_radix_init_iamr();
2361 	mmu_radix_pid_set(kernel_pmap);
2362 	mmu_radix_tlbiel_flush(TLB_INVAL_SCOPE_GLOBAL);
2363 }
2364 
2365 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l3e, CTLFLAG_RD, 0,
2366     "2MB page mapping counters");
2367 
2368 static u_long pmap_l3e_demotions;
2369 SYSCTL_ULONG(_vm_pmap_l3e, OID_AUTO, demotions, CTLFLAG_RD,
2370     &pmap_l3e_demotions, 0, "2MB page demotions");
2371 
2372 static u_long pmap_l3e_mappings;
2373 SYSCTL_ULONG(_vm_pmap_l3e, OID_AUTO, mappings, CTLFLAG_RD,
2374     &pmap_l3e_mappings, 0, "2MB page mappings");
2375 
2376 static u_long pmap_l3e_p_failures;
2377 SYSCTL_ULONG(_vm_pmap_l3e, OID_AUTO, p_failures, CTLFLAG_RD,
2378     &pmap_l3e_p_failures, 0, "2MB page promotion failures");
2379 
2380 static u_long pmap_l3e_promotions;
2381 SYSCTL_ULONG(_vm_pmap_l3e, OID_AUTO, promotions, CTLFLAG_RD,
2382     &pmap_l3e_promotions, 0, "2MB page promotions");
2383 
2384 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2e, CTLFLAG_RD, 0,
2385     "1GB page mapping counters");
2386 
2387 static u_long pmap_l2e_demotions;
2388 SYSCTL_ULONG(_vm_pmap_l2e, OID_AUTO, demotions, CTLFLAG_RD,
2389     &pmap_l2e_demotions, 0, "1GB page demotions");
2390 
2391 void
2392 mmu_radix_clear_modify(vm_page_t m)
2393 {
2394 	struct md_page *pvh;
2395 	pmap_t pmap;
2396 	pv_entry_t next_pv, pv;
2397 	pml3_entry_t oldl3e, *l3e;
2398 	pt_entry_t oldpte, *pte;
2399 	struct rwlock *lock;
2400 	vm_offset_t va;
2401 	int md_gen, pvh_gen;
2402 
2403 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2404 	    ("pmap_clear_modify: page %p is not managed", m));
2405 	vm_page_assert_busied(m);
2406 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
2407 
2408 	/*
2409 	 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
2410 	 * If the object containing the page is locked and the page is not
2411 	 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
2412 	 */
2413 	if ((m->a.flags & PGA_WRITEABLE) == 0)
2414 		return;
2415 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
2416 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
2417 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
2418 	rw_wlock(lock);
2419 restart:
2420 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_link, next_pv) {
2421 		pmap = PV_PMAP(pv);
2422 		if (!PMAP_TRYLOCK(pmap)) {
2423 			pvh_gen = pvh->pv_gen;
2424 			rw_wunlock(lock);
2425 			PMAP_LOCK(pmap);
2426 			rw_wlock(lock);
2427 			if (pvh_gen != pvh->pv_gen) {
2428 				PMAP_UNLOCK(pmap);
2429 				goto restart;
2430 			}
2431 		}
2432 		va = pv->pv_va;
2433 		l3e = pmap_pml3e(pmap, va);
2434 		oldl3e = be64toh(*l3e);
2435 		if ((oldl3e & PG_RW) != 0) {
2436 			if (pmap_demote_l3e_locked(pmap, l3e, va, &lock)) {
2437 				if ((oldl3e & PG_W) == 0) {
2438 					/*
2439 					 * Write protect the mapping to a
2440 					 * single page so that a subsequent
2441 					 * write access may repromote.
2442 					 */
2443 					va += VM_PAGE_TO_PHYS(m) - (oldl3e &
2444 					    PG_PS_FRAME);
2445 					pte = pmap_l3e_to_pte(l3e, va);
2446 					oldpte = be64toh(*pte);
2447 					if ((oldpte & PG_V) != 0) {
2448 						while (!atomic_cmpset_long(pte,
2449 						    htobe64(oldpte),
2450 							htobe64((oldpte | RPTE_EAA_R) & ~(PG_M | PG_RW))))
2451 							   oldpte = be64toh(*pte);
2452 						vm_page_dirty(m);
2453 						pmap_invalidate_page(pmap, va);
2454 					}
2455 				}
2456 			}
2457 		}
2458 		PMAP_UNLOCK(pmap);
2459 	}
2460 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2461 		pmap = PV_PMAP(pv);
2462 		if (!PMAP_TRYLOCK(pmap)) {
2463 			md_gen = m->md.pv_gen;
2464 			pvh_gen = pvh->pv_gen;
2465 			rw_wunlock(lock);
2466 			PMAP_LOCK(pmap);
2467 			rw_wlock(lock);
2468 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
2469 				PMAP_UNLOCK(pmap);
2470 				goto restart;
2471 			}
2472 		}
2473 		l3e = pmap_pml3e(pmap, pv->pv_va);
2474 		KASSERT((be64toh(*l3e) & RPTE_LEAF) == 0, ("pmap_clear_modify: found"
2475 		    " a 2mpage in page %p's pv list", m));
2476 		pte = pmap_l3e_to_pte(l3e, pv->pv_va);
2477 		if ((be64toh(*pte) & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
2478 			atomic_clear_long(pte, htobe64(PG_M));
2479 			pmap_invalidate_page(pmap, pv->pv_va);
2480 		}
2481 		PMAP_UNLOCK(pmap);
2482 	}
2483 	rw_wunlock(lock);
2484 }
2485 
2486 void
2487 mmu_radix_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr,
2488     vm_size_t len, vm_offset_t src_addr)
2489 {
2490 	struct rwlock *lock;
2491 	struct spglist free;
2492 	vm_offset_t addr;
2493 	vm_offset_t end_addr = src_addr + len;
2494 	vm_offset_t va_next;
2495 	vm_page_t dst_pdpg, dstmpte, srcmpte;
2496 	bool invalidate_all;
2497 
2498 	CTR6(KTR_PMAP,
2499 	    "%s(dst_pmap=%p, src_pmap=%p, dst_addr=%lx, len=%lu, src_addr=%lx)\n",
2500 	    __func__, dst_pmap, src_pmap, dst_addr, len, src_addr);
2501 
2502 	if (dst_addr != src_addr)
2503 		return;
2504 	lock = NULL;
2505 	invalidate_all = false;
2506 	if (dst_pmap < src_pmap) {
2507 		PMAP_LOCK(dst_pmap);
2508 		PMAP_LOCK(src_pmap);
2509 	} else {
2510 		PMAP_LOCK(src_pmap);
2511 		PMAP_LOCK(dst_pmap);
2512 	}
2513 
2514 	for (addr = src_addr; addr < end_addr; addr = va_next) {
2515 		pml1_entry_t *l1e;
2516 		pml2_entry_t *l2e;
2517 		pml3_entry_t srcptepaddr, *l3e;
2518 		pt_entry_t *src_pte, *dst_pte;
2519 
2520 		l1e = pmap_pml1e(src_pmap, addr);
2521 		if ((be64toh(*l1e) & PG_V) == 0) {
2522 			va_next = (addr + L1_PAGE_SIZE) & ~L1_PAGE_MASK;
2523 			if (va_next < addr)
2524 				va_next = end_addr;
2525 			continue;
2526 		}
2527 
2528 		l2e = pmap_l1e_to_l2e(l1e, addr);
2529 		if ((be64toh(*l2e) & PG_V) == 0) {
2530 			va_next = (addr + L2_PAGE_SIZE) & ~L2_PAGE_MASK;
2531 			if (va_next < addr)
2532 				va_next = end_addr;
2533 			continue;
2534 		}
2535 
2536 		va_next = (addr + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
2537 		if (va_next < addr)
2538 			va_next = end_addr;
2539 
2540 		l3e = pmap_l2e_to_l3e(l2e, addr);
2541 		srcptepaddr = be64toh(*l3e);
2542 		if (srcptepaddr == 0)
2543 			continue;
2544 
2545 		if (srcptepaddr & RPTE_LEAF) {
2546 			if ((addr & L3_PAGE_MASK) != 0 ||
2547 			    addr + L3_PAGE_SIZE > end_addr)
2548 				continue;
2549 			dst_pdpg = pmap_allocl3e(dst_pmap, addr, NULL);
2550 			if (dst_pdpg == NULL)
2551 				break;
2552 			l3e = (pml3_entry_t *)
2553 			    PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
2554 			l3e = &l3e[pmap_pml3e_index(addr)];
2555 			if (be64toh(*l3e) == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
2556 			    pmap_pv_insert_l3e(dst_pmap, addr, srcptepaddr,
2557 			    PMAP_ENTER_NORECLAIM, &lock))) {
2558 				*l3e = htobe64(srcptepaddr & ~PG_W);
2559 				pmap_resident_count_inc(dst_pmap,
2560 				    L3_PAGE_SIZE / PAGE_SIZE);
2561 				atomic_add_long(&pmap_l3e_mappings, 1);
2562 			} else
2563 				dst_pdpg->ref_count--;
2564 			continue;
2565 		}
2566 
2567 		srcptepaddr &= PG_FRAME;
2568 		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
2569 		KASSERT(srcmpte->ref_count > 0,
2570 		    ("pmap_copy: source page table page is unused"));
2571 
2572 		if (va_next > end_addr)
2573 			va_next = end_addr;
2574 
2575 		src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
2576 		src_pte = &src_pte[pmap_pte_index(addr)];
2577 		dstmpte = NULL;
2578 		while (addr < va_next) {
2579 			pt_entry_t ptetemp;
2580 			ptetemp = be64toh(*src_pte);
2581 			/*
2582 			 * we only virtual copy managed pages
2583 			 */
2584 			if ((ptetemp & PG_MANAGED) != 0) {
2585 				if (dstmpte != NULL &&
2586 				    dstmpte->pindex == pmap_l3e_pindex(addr))
2587 					dstmpte->ref_count++;
2588 				else if ((dstmpte = pmap_allocpte(dst_pmap,
2589 				    addr, NULL)) == NULL)
2590 					goto out;
2591 				dst_pte = (pt_entry_t *)
2592 				    PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
2593 				dst_pte = &dst_pte[pmap_pte_index(addr)];
2594 				if (be64toh(*dst_pte) == 0 &&
2595 				    pmap_try_insert_pv_entry(dst_pmap, addr,
2596 				    PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
2597 				    &lock)) {
2598 					/*
2599 					 * Clear the wired, modified, and
2600 					 * accessed (referenced) bits
2601 					 * during the copy.
2602 					 */
2603 					*dst_pte = htobe64(ptetemp & ~(PG_W | PG_M |
2604 					    PG_A));
2605 					pmap_resident_count_inc(dst_pmap, 1);
2606 				} else {
2607 					SLIST_INIT(&free);
2608 					if (pmap_unwire_ptp(dst_pmap, addr,
2609 					    dstmpte, &free)) {
2610 						/*
2611 						 * Although "addr" is not
2612 						 * mapped, paging-structure
2613 						 * caches could nonetheless
2614 						 * have entries that refer to
2615 						 * the freed page table pages.
2616 						 * Invalidate those entries.
2617 						 */
2618 						invalidate_all = true;
2619 						vm_page_free_pages_toq(&free,
2620 						    true);
2621 					}
2622 					goto out;
2623 				}
2624 				if (dstmpte->ref_count >= srcmpte->ref_count)
2625 					break;
2626 			}
2627 			addr += PAGE_SIZE;
2628 			if (__predict_false((addr & L3_PAGE_MASK) == 0))
2629 				src_pte = pmap_pte(src_pmap, addr);
2630 			else
2631 				src_pte++;
2632 		}
2633 	}
2634 out:
2635 	if (invalidate_all)
2636 		pmap_invalidate_all(dst_pmap);
2637 	if (lock != NULL)
2638 		rw_wunlock(lock);
2639 	PMAP_UNLOCK(src_pmap);
2640 	PMAP_UNLOCK(dst_pmap);
2641 }
2642 
2643 static void
2644 mmu_radix_copy_page(vm_page_t msrc, vm_page_t mdst)
2645 {
2646 	vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
2647 	vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
2648 
2649 	CTR3(KTR_PMAP, "%s(%p, %p)", __func__, src, dst);
2650 	/*
2651 	 * XXX slow
2652 	 */
2653 	bcopy((void *)src, (void *)dst, PAGE_SIZE);
2654 }
2655 
2656 static void
2657 mmu_radix_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
2658     vm_offset_t b_offset, int xfersize)
2659 {
2660         void *a_cp, *b_cp;
2661         vm_offset_t a_pg_offset, b_pg_offset;
2662         int cnt;
2663 
2664 	CTR6(KTR_PMAP, "%s(%p, %#x, %p, %#x, %#x)", __func__, ma,
2665 	    a_offset, mb, b_offset, xfersize);
2666 
2667         while (xfersize > 0) {
2668                 a_pg_offset = a_offset & PAGE_MASK;
2669                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
2670                 a_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
2671                     VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT])) +
2672                     a_pg_offset;
2673                 b_pg_offset = b_offset & PAGE_MASK;
2674                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
2675                 b_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
2676                     VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT])) +
2677                     b_pg_offset;
2678                 bcopy(a_cp, b_cp, cnt);
2679                 a_offset += cnt;
2680                 b_offset += cnt;
2681                 xfersize -= cnt;
2682         }
2683 }
2684 
2685 #if VM_NRESERVLEVEL > 0
2686 /*
2687  * Tries to promote the 512, contiguous 4KB page mappings that are within a
2688  * single page table page (PTP) to a single 2MB page mapping.  For promotion
2689  * to occur, two conditions must be met: (1) the 4KB page mappings must map
2690  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
2691  * identical characteristics.
2692  */
2693 static int
2694 pmap_promote_l3e(pmap_t pmap, pml3_entry_t *pde, vm_offset_t va,
2695     struct rwlock **lockp)
2696 {
2697 	pml3_entry_t newpde;
2698 	pt_entry_t *firstpte, oldpte, pa, *pte;
2699 	vm_page_t mpte;
2700 
2701 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2702 
2703 	/*
2704 	 * Examine the first PTE in the specified PTP.  Abort if this PTE is
2705 	 * either invalid, unused, or does not map the first 4KB physical page
2706 	 * within a 2MB page.
2707 	 */
2708 	firstpte = (pt_entry_t *)PHYS_TO_DMAP(be64toh(*pde) & PG_FRAME);
2709 setpde:
2710 	newpde = *firstpte;
2711 	if ((newpde & ((PG_FRAME & L3_PAGE_MASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
2712 		CTR2(KTR_PMAP, "pmap_promote_l3e: failure for va %#lx"
2713 		    " in pmap %p", va, pmap);
2714 		goto fail;
2715 	}
2716 	if ((newpde & (PG_M | PG_RW)) == PG_RW) {
2717 		/*
2718 		 * When PG_M is already clear, PG_RW can be cleared without
2719 		 * a TLB invalidation.
2720 		 */
2721 		if (!atomic_cmpset_long(firstpte, htobe64(newpde), htobe64((newpde | RPTE_EAA_R) & ~RPTE_EAA_W)))
2722 			goto setpde;
2723 		newpde &= ~RPTE_EAA_W;
2724 	}
2725 
2726 	/*
2727 	 * Examine each of the other PTEs in the specified PTP.  Abort if this
2728 	 * PTE maps an unexpected 4KB physical page or does not have identical
2729 	 * characteristics to the first PTE.
2730 	 */
2731 	pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + L3_PAGE_SIZE - PAGE_SIZE;
2732 	for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
2733 setpte:
2734 		oldpte = be64toh(*pte);
2735 		if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
2736 			CTR2(KTR_PMAP, "pmap_promote_l3e: failure for va %#lx"
2737 			    " in pmap %p", va, pmap);
2738 			goto fail;
2739 		}
2740 		if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
2741 			/*
2742 			 * When PG_M is already clear, PG_RW can be cleared
2743 			 * without a TLB invalidation.
2744 			 */
2745 			if (!atomic_cmpset_long(pte, htobe64(oldpte), htobe64((oldpte | RPTE_EAA_R) & ~RPTE_EAA_W)))
2746 				goto setpte;
2747 			oldpte &= ~RPTE_EAA_W;
2748 			CTR2(KTR_PMAP, "pmap_promote_l3e: protect for va %#lx"
2749 			    " in pmap %p", (oldpte & PG_FRAME & L3_PAGE_MASK) |
2750 			    (va & ~L3_PAGE_MASK), pmap);
2751 		}
2752 		if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
2753 			CTR2(KTR_PMAP, "pmap_promote_l3e: failure for va %#lx"
2754 			    " in pmap %p", va, pmap);
2755 			goto fail;
2756 		}
2757 		pa -= PAGE_SIZE;
2758 	}
2759 
2760 	/*
2761 	 * Save the page table page in its current state until the PDE
2762 	 * mapping the superpage is demoted by pmap_demote_pde() or
2763 	 * destroyed by pmap_remove_pde().
2764 	 */
2765 	mpte = PHYS_TO_VM_PAGE(be64toh(*pde) & PG_FRAME);
2766 	KASSERT(mpte >= vm_page_array &&
2767 	    mpte < &vm_page_array[vm_page_array_size],
2768 	    ("pmap_promote_l3e: page table page is out of range"));
2769 	KASSERT(mpte->pindex == pmap_l3e_pindex(va),
2770 	    ("pmap_promote_l3e: page table page's pindex is wrong"));
2771 	if (pmap_insert_pt_page(pmap, mpte)) {
2772 		CTR2(KTR_PMAP,
2773 		    "pmap_promote_l3e: failure for va %#lx in pmap %p", va,
2774 		    pmap);
2775 		goto fail;
2776 	}
2777 
2778 	/*
2779 	 * Promote the pv entries.
2780 	 */
2781 	if ((newpde & PG_MANAGED) != 0)
2782 		pmap_pv_promote_l3e(pmap, va, newpde & PG_PS_FRAME, lockp);
2783 
2784 	pte_store(pde, PG_PROMOTED | newpde);
2785 	ptesync();
2786 	atomic_add_long(&pmap_l3e_promotions, 1);
2787 	CTR2(KTR_PMAP, "pmap_promote_l3e: success for va %#lx"
2788 	    " in pmap %p", va, pmap);
2789 	return (0);
2790  fail:
2791 	atomic_add_long(&pmap_l3e_p_failures, 1);
2792 	return (KERN_FAILURE);
2793 }
2794 #endif /* VM_NRESERVLEVEL > 0 */
2795 
2796 int
2797 mmu_radix_enter(pmap_t pmap, vm_offset_t va, vm_page_t m,
2798     vm_prot_t prot, u_int flags, int8_t psind)
2799 {
2800 	struct rwlock *lock;
2801 	pml3_entry_t *l3e;
2802 	pt_entry_t *pte;
2803 	pt_entry_t newpte, origpte;
2804 	pv_entry_t pv;
2805 	vm_paddr_t opa, pa;
2806 	vm_page_t mpte, om;
2807 	int rv, retrycount;
2808 	boolean_t nosleep, invalidate_all, invalidate_page;
2809 
2810 	va = trunc_page(va);
2811 	retrycount = 0;
2812 	invalidate_page = invalidate_all = false;
2813 	CTR6(KTR_PMAP, "pmap_enter(%p, %#lx, %p, %#x, %#x, %d)", pmap, va,
2814 	    m, prot, flags, psind);
2815 	KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
2816 	KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
2817 	    va >= kmi.clean_eva,
2818 	    ("pmap_enter: managed mapping within the clean submap"));
2819 	if ((m->oflags & VPO_UNMANAGED) == 0)
2820 		VM_PAGE_OBJECT_BUSY_ASSERT(m);
2821 
2822 	KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
2823 	    ("pmap_enter: flags %u has reserved bits set", flags));
2824 	pa = VM_PAGE_TO_PHYS(m);
2825 	newpte = (pt_entry_t)(pa | PG_A | PG_V | RPTE_LEAF);
2826 	if ((flags & VM_PROT_WRITE) != 0)
2827 		newpte |= PG_M;
2828 	if ((flags & VM_PROT_READ) != 0)
2829 		newpte |= PG_A;
2830 	if (prot & VM_PROT_READ)
2831 		newpte |= RPTE_EAA_R;
2832 	if ((prot & VM_PROT_WRITE) != 0)
2833 		newpte |= RPTE_EAA_W;
2834 	KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
2835 	    ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
2836 
2837 	if (prot & VM_PROT_EXECUTE)
2838 		newpte |= PG_X;
2839 	if ((flags & PMAP_ENTER_WIRED) != 0)
2840 		newpte |= PG_W;
2841 	if (va >= DMAP_MIN_ADDRESS)
2842 		newpte |= RPTE_EAA_P;
2843 	newpte |= pmap_cache_bits(m->md.mdpg_cache_attrs);
2844 	/*
2845 	 * Set modified bit gratuitously for writeable mappings if
2846 	 * the page is unmanaged. We do not want to take a fault
2847 	 * to do the dirty bit accounting for these mappings.
2848 	 */
2849 	if ((m->oflags & VPO_UNMANAGED) != 0) {
2850 		if ((newpte & PG_RW) != 0)
2851 			newpte |= PG_M;
2852 	} else
2853 		newpte |= PG_MANAGED;
2854 
2855 	lock = NULL;
2856 	PMAP_LOCK(pmap);
2857 	if (psind == 1) {
2858 		/* Assert the required virtual and physical alignment. */
2859 		KASSERT((va & L3_PAGE_MASK) == 0, ("pmap_enter: va unaligned"));
2860 		KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
2861 		rv = pmap_enter_l3e(pmap, va, newpte | RPTE_LEAF, flags, m, &lock);
2862 		goto out;
2863 	}
2864 	mpte = NULL;
2865 
2866 	/*
2867 	 * In the case that a page table page is not
2868 	 * resident, we are creating it here.
2869 	 */
2870 retry:
2871 	l3e = pmap_pml3e(pmap, va);
2872 	if (l3e != NULL && (be64toh(*l3e) & PG_V) != 0 && ((be64toh(*l3e) & RPTE_LEAF) == 0 ||
2873 	    pmap_demote_l3e_locked(pmap, l3e, va, &lock))) {
2874 		pte = pmap_l3e_to_pte(l3e, va);
2875 		if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
2876 			mpte = PHYS_TO_VM_PAGE(be64toh(*l3e) & PG_FRAME);
2877 			mpte->ref_count++;
2878 		}
2879 	} else if (va < VM_MAXUSER_ADDRESS) {
2880 		/*
2881 		 * Here if the pte page isn't mapped, or if it has been
2882 		 * deallocated.
2883 		 */
2884 		nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
2885 		mpte = _pmap_allocpte(pmap, pmap_l3e_pindex(va),
2886 		    nosleep ? NULL : &lock);
2887 		if (mpte == NULL && nosleep) {
2888 			rv = KERN_RESOURCE_SHORTAGE;
2889 			goto out;
2890 		}
2891 		if (__predict_false(retrycount++ == 6))
2892 			panic("too many retries");
2893 		invalidate_all = true;
2894 		goto retry;
2895 	} else
2896 		panic("pmap_enter: invalid page directory va=%#lx", va);
2897 
2898 	origpte = be64toh(*pte);
2899 	pv = NULL;
2900 
2901 	/*
2902 	 * Is the specified virtual address already mapped?
2903 	 */
2904 	if ((origpte & PG_V) != 0) {
2905 #ifdef INVARIANTS
2906 		if (VERBOSE_PMAP || pmap_logging) {
2907 			printf("cow fault pmap_enter(%p, %#lx, %p, %#x, %x, %d) --"
2908 			    " asid=%lu curpid=%d name=%s origpte0x%lx\n",
2909 			    pmap, va, m, prot, flags, psind, pmap->pm_pid,
2910 			    curproc->p_pid, curproc->p_comm, origpte);
2911 			pmap_pte_walk(pmap->pm_pml1, va);
2912 		}
2913 #endif
2914 		/*
2915 		 * Wiring change, just update stats. We don't worry about
2916 		 * wiring PT pages as they remain resident as long as there
2917 		 * are valid mappings in them. Hence, if a user page is wired,
2918 		 * the PT page will be also.
2919 		 */
2920 		if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
2921 			pmap->pm_stats.wired_count++;
2922 		else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
2923 			pmap->pm_stats.wired_count--;
2924 
2925 		/*
2926 		 * Remove the extra PT page reference.
2927 		 */
2928 		if (mpte != NULL) {
2929 			mpte->ref_count--;
2930 			KASSERT(mpte->ref_count > 0,
2931 			    ("pmap_enter: missing reference to page table page,"
2932 			     " va: 0x%lx", va));
2933 		}
2934 
2935 		/*
2936 		 * Has the physical page changed?
2937 		 */
2938 		opa = origpte & PG_FRAME;
2939 		if (opa == pa) {
2940 			/*
2941 			 * No, might be a protection or wiring change.
2942 			 */
2943 			if ((origpte & PG_MANAGED) != 0 &&
2944 			    (newpte & PG_RW) != 0)
2945 				vm_page_aflag_set(m, PGA_WRITEABLE);
2946 			if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0) {
2947 				if ((newpte & (PG_A|PG_M)) != (origpte & (PG_A|PG_M))) {
2948 					if (!atomic_cmpset_long(pte, htobe64(origpte), htobe64(newpte)))
2949 						goto retry;
2950 					if ((newpte & PG_M) != (origpte & PG_M))
2951 						vm_page_dirty(m);
2952 					if ((newpte & PG_A) != (origpte & PG_A))
2953 						vm_page_aflag_set(m, PGA_REFERENCED);
2954 					ptesync();
2955 				} else
2956 					invalidate_all = true;
2957 				if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
2958 					goto unchanged;
2959 			}
2960 			goto validate;
2961 		}
2962 
2963 		/*
2964 		 * The physical page has changed.  Temporarily invalidate
2965 		 * the mapping.  This ensures that all threads sharing the
2966 		 * pmap keep a consistent view of the mapping, which is
2967 		 * necessary for the correct handling of COW faults.  It
2968 		 * also permits reuse of the old mapping's PV entry,
2969 		 * avoiding an allocation.
2970 		 *
2971 		 * For consistency, handle unmanaged mappings the same way.
2972 		 */
2973 		origpte = be64toh(pte_load_clear(pte));
2974 		KASSERT((origpte & PG_FRAME) == opa,
2975 		    ("pmap_enter: unexpected pa update for %#lx", va));
2976 		if ((origpte & PG_MANAGED) != 0) {
2977 			om = PHYS_TO_VM_PAGE(opa);
2978 
2979 			/*
2980 			 * The pmap lock is sufficient to synchronize with
2981 			 * concurrent calls to pmap_page_test_mappings() and
2982 			 * pmap_ts_referenced().
2983 			 */
2984 			if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2985 				vm_page_dirty(om);
2986 			if ((origpte & PG_A) != 0)
2987 				vm_page_aflag_set(om, PGA_REFERENCED);
2988 			CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
2989 			pv = pmap_pvh_remove(&om->md, pmap, va);
2990 			if ((newpte & PG_MANAGED) == 0)
2991 				free_pv_entry(pmap, pv);
2992 #ifdef INVARIANTS
2993 			else if (origpte & PG_MANAGED) {
2994 				if (pv == NULL) {
2995 					pmap_page_print_mappings(om);
2996 					MPASS(pv != NULL);
2997 				}
2998 			}
2999 #endif
3000 			if ((om->a.flags & PGA_WRITEABLE) != 0 &&
3001 			    TAILQ_EMPTY(&om->md.pv_list) &&
3002 			    ((om->flags & PG_FICTITIOUS) != 0 ||
3003 			    TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
3004 				vm_page_aflag_clear(om, PGA_WRITEABLE);
3005 		}
3006 		if ((origpte & PG_A) != 0)
3007 			invalidate_page = true;
3008 		origpte = 0;
3009 	} else {
3010 		if (pmap != kernel_pmap) {
3011 #ifdef INVARIANTS
3012 			if (VERBOSE_PMAP || pmap_logging)
3013 				printf("pmap_enter(%p, %#lx, %p, %#x, %x, %d) -- asid=%lu curpid=%d name=%s\n",
3014 				    pmap, va, m, prot, flags, psind,
3015 				    pmap->pm_pid, curproc->p_pid,
3016 				    curproc->p_comm);
3017 #endif
3018 		}
3019 
3020 		/*
3021 		 * Increment the counters.
3022 		 */
3023 		if ((newpte & PG_W) != 0)
3024 			pmap->pm_stats.wired_count++;
3025 		pmap_resident_count_inc(pmap, 1);
3026 	}
3027 
3028 	/*
3029 	 * Enter on the PV list if part of our managed memory.
3030 	 */
3031 	if ((newpte & PG_MANAGED) != 0) {
3032 		if (pv == NULL) {
3033 			pv = get_pv_entry(pmap, &lock);
3034 			pv->pv_va = va;
3035 		}
3036 #ifdef VERBOSE_PV
3037 		else
3038 			printf("reassigning pv: %p to pmap: %p\n",
3039 				   pv, pmap);
3040 #endif
3041 		CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
3042 		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_link);
3043 		m->md.pv_gen++;
3044 		if ((newpte & PG_RW) != 0)
3045 			vm_page_aflag_set(m, PGA_WRITEABLE);
3046 	}
3047 
3048 	/*
3049 	 * Update the PTE.
3050 	 */
3051 	if ((origpte & PG_V) != 0) {
3052 validate:
3053 		origpte = be64toh(pte_load_store(pte, htobe64(newpte)));
3054 		KASSERT((origpte & PG_FRAME) == pa,
3055 		    ("pmap_enter: unexpected pa update for %#lx", va));
3056 		if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
3057 		    (PG_M | PG_RW)) {
3058 			if ((origpte & PG_MANAGED) != 0)
3059 				vm_page_dirty(m);
3060 			invalidate_page = true;
3061 
3062 			/*
3063 			 * Although the PTE may still have PG_RW set, TLB
3064 			 * invalidation may nonetheless be required because
3065 			 * the PTE no longer has PG_M set.
3066 			 */
3067 		} else if ((origpte & PG_X) != 0 || (newpte & PG_X) == 0) {
3068 			/*
3069 			 * Removing capabilities requires invalidation on POWER
3070 			 */
3071 			invalidate_page = true;
3072 			goto unchanged;
3073 		}
3074 		if ((origpte & PG_A) != 0)
3075 			invalidate_page = true;
3076 	} else {
3077 		pte_store(pte, newpte);
3078 		ptesync();
3079 	}
3080 unchanged:
3081 
3082 #if VM_NRESERVLEVEL > 0
3083 	/*
3084 	 * If both the page table page and the reservation are fully
3085 	 * populated, then attempt promotion.
3086 	 */
3087 	if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
3088 	    mmu_radix_ps_enabled(pmap) &&
3089 	    (m->flags & PG_FICTITIOUS) == 0 &&
3090 	    vm_reserv_level_iffullpop(m) == 0 &&
3091 		pmap_promote_l3e(pmap, l3e, va, &lock) == 0)
3092 		invalidate_all = true;
3093 #endif
3094 	if (invalidate_all)
3095 		pmap_invalidate_all(pmap);
3096 	else if (invalidate_page)
3097 		pmap_invalidate_page(pmap, va);
3098 
3099 	rv = KERN_SUCCESS;
3100 out:
3101 	if (lock != NULL)
3102 		rw_wunlock(lock);
3103 	PMAP_UNLOCK(pmap);
3104 
3105 	return (rv);
3106 }
3107 
3108 /*
3109  * Tries to create a read- and/or execute-only 2MB page mapping.  Returns true
3110  * if successful.  Returns false if (1) a page table page cannot be allocated
3111  * without sleeping, (2) a mapping already exists at the specified virtual
3112  * address, or (3) a PV entry cannot be allocated without reclaiming another
3113  * PV entry.
3114  */
3115 static bool
3116 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3117     struct rwlock **lockp)
3118 {
3119 	pml3_entry_t newpde;
3120 
3121 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3122 	newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.mdpg_cache_attrs) |
3123 	    RPTE_LEAF | PG_V;
3124 	if ((m->oflags & VPO_UNMANAGED) == 0)
3125 		newpde |= PG_MANAGED;
3126 	if (prot & VM_PROT_EXECUTE)
3127 		newpde |= PG_X;
3128 	if (prot & VM_PROT_READ)
3129 		newpde |= RPTE_EAA_R;
3130 	if (va >= DMAP_MIN_ADDRESS)
3131 		newpde |= RPTE_EAA_P;
3132 	return (pmap_enter_l3e(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
3133 	    PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
3134 	    KERN_SUCCESS);
3135 }
3136 
3137 /*
3138  * Tries to create the specified 2MB page mapping.  Returns KERN_SUCCESS if
3139  * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
3140  * otherwise.  Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
3141  * a mapping already exists at the specified virtual address.  Returns
3142  * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
3143  * page allocation failed.  Returns KERN_RESOURCE_SHORTAGE if
3144  * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
3145  *
3146  * The parameter "m" is only used when creating a managed, writeable mapping.
3147  */
3148 static int
3149 pmap_enter_l3e(pmap_t pmap, vm_offset_t va, pml3_entry_t newpde, u_int flags,
3150     vm_page_t m, struct rwlock **lockp)
3151 {
3152 	struct spglist free;
3153 	pml3_entry_t oldl3e, *l3e;
3154 	vm_page_t mt, pdpg;
3155 
3156 	KASSERT((newpde & (PG_M | PG_RW)) != PG_RW,
3157 	    ("pmap_enter_pde: newpde is missing PG_M"));
3158 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3159 
3160 	if ((pdpg = pmap_allocl3e(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
3161 	    NULL : lockp)) == NULL) {
3162 		CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3163 		    " in pmap %p", va, pmap);
3164 		return (KERN_RESOURCE_SHORTAGE);
3165 	}
3166 	l3e = (pml3_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
3167 	l3e = &l3e[pmap_pml3e_index(va)];
3168 	oldl3e = be64toh(*l3e);
3169 	if ((oldl3e & PG_V) != 0) {
3170 		KASSERT(pdpg->ref_count > 1,
3171 		    ("pmap_enter_pde: pdpg's wire count is too low"));
3172 		if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
3173 			pdpg->ref_count--;
3174 			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3175 			    " in pmap %p", va, pmap);
3176 			return (KERN_FAILURE);
3177 		}
3178 		/* Break the existing mapping(s). */
3179 		SLIST_INIT(&free);
3180 		if ((oldl3e & RPTE_LEAF) != 0) {
3181 			/*
3182 			 * The reference to the PD page that was acquired by
3183 			 * pmap_allocl3e() ensures that it won't be freed.
3184 			 * However, if the PDE resulted from a promotion, then
3185 			 * a reserved PT page could be freed.
3186 			 */
3187 			(void)pmap_remove_l3e(pmap, l3e, va, &free, lockp);
3188 		} else {
3189 			if (pmap_remove_ptes(pmap, va, va + L3_PAGE_SIZE, l3e,
3190 			    &free, lockp))
3191 		               pmap_invalidate_all(pmap);
3192 		}
3193 		vm_page_free_pages_toq(&free, true);
3194 		if (va >= VM_MAXUSER_ADDRESS) {
3195 			mt = PHYS_TO_VM_PAGE(be64toh(*l3e) & PG_FRAME);
3196 			if (pmap_insert_pt_page(pmap, mt)) {
3197 				/*
3198 				 * XXX Currently, this can't happen because
3199 				 * we do not perform pmap_enter(psind == 1)
3200 				 * on the kernel pmap.
3201 				 */
3202 				panic("pmap_enter_pde: trie insert failed");
3203 			}
3204 		} else
3205 			KASSERT(be64toh(*l3e) == 0, ("pmap_enter_pde: non-zero pde %p",
3206 			    l3e));
3207 	}
3208 	if ((newpde & PG_MANAGED) != 0) {
3209 		/*
3210 		 * Abort this mapping if its PV entry could not be created.
3211 		 */
3212 		if (!pmap_pv_insert_l3e(pmap, va, newpde, flags, lockp)) {
3213 			SLIST_INIT(&free);
3214 			if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
3215 				/*
3216 				 * Although "va" is not mapped, paging-
3217 				 * structure caches could nonetheless have
3218 				 * entries that refer to the freed page table
3219 				 * pages.  Invalidate those entries.
3220 				 */
3221 				pmap_invalidate_page(pmap, va);
3222 				vm_page_free_pages_toq(&free, true);
3223 			}
3224 			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3225 			    " in pmap %p", va, pmap);
3226 			return (KERN_RESOURCE_SHORTAGE);
3227 		}
3228 		if ((newpde & PG_RW) != 0) {
3229 			for (mt = m; mt < &m[L3_PAGE_SIZE / PAGE_SIZE]; mt++)
3230 				vm_page_aflag_set(mt, PGA_WRITEABLE);
3231 		}
3232 	}
3233 
3234 	/*
3235 	 * Increment counters.
3236 	 */
3237 	if ((newpde & PG_W) != 0)
3238 		pmap->pm_stats.wired_count += L3_PAGE_SIZE / PAGE_SIZE;
3239 	pmap_resident_count_inc(pmap, L3_PAGE_SIZE / PAGE_SIZE);
3240 
3241 	/*
3242 	 * Map the superpage.  (This is not a promoted mapping; there will not
3243 	 * be any lingering 4KB page mappings in the TLB.)
3244 	 */
3245 	pte_store(l3e, newpde);
3246 
3247 	atomic_add_long(&pmap_l3e_mappings, 1);
3248 	CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
3249 	    " in pmap %p", va, pmap);
3250 	return (KERN_SUCCESS);
3251 }
3252 
3253 void
3254 mmu_radix_enter_object(pmap_t pmap, vm_offset_t start,
3255     vm_offset_t end, vm_page_t m_start, vm_prot_t prot)
3256 {
3257 
3258 	struct rwlock *lock;
3259 	vm_offset_t va;
3260 	vm_page_t m, mpte;
3261 	vm_pindex_t diff, psize;
3262 	bool invalidate;
3263 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
3264 
3265 	CTR6(KTR_PMAP, "%s(%p, %#x, %#x, %p, %#x)", __func__, pmap, start,
3266 	    end, m_start, prot);
3267 
3268 	invalidate = false;
3269 	psize = atop(end - start);
3270 	mpte = NULL;
3271 	m = m_start;
3272 	lock = NULL;
3273 	PMAP_LOCK(pmap);
3274 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
3275 		va = start + ptoa(diff);
3276 		if ((va & L3_PAGE_MASK) == 0 && va + L3_PAGE_SIZE <= end &&
3277 		    m->psind == 1 && mmu_radix_ps_enabled(pmap) &&
3278 		    pmap_enter_2mpage(pmap, va, m, prot, &lock))
3279 			m = &m[L3_PAGE_SIZE / PAGE_SIZE - 1];
3280 		else
3281 			mpte = mmu_radix_enter_quick_locked(pmap, va, m, prot,
3282 			    mpte, &lock, &invalidate);
3283 		m = TAILQ_NEXT(m, listq);
3284 	}
3285 	ptesync();
3286 	if (lock != NULL)
3287 		rw_wunlock(lock);
3288 	if (invalidate)
3289 		pmap_invalidate_all(pmap);
3290 	PMAP_UNLOCK(pmap);
3291 }
3292 
3293 static vm_page_t
3294 mmu_radix_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
3295     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp, bool *invalidate)
3296 {
3297 	struct spglist free;
3298 	pt_entry_t *pte;
3299 	vm_paddr_t pa;
3300 
3301 	KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
3302 	    (m->oflags & VPO_UNMANAGED) != 0,
3303 	    ("mmu_radix_enter_quick_locked: managed mapping within the clean submap"));
3304 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3305 
3306 	/*
3307 	 * In the case that a page table page is not
3308 	 * resident, we are creating it here.
3309 	 */
3310 	if (va < VM_MAXUSER_ADDRESS) {
3311 		vm_pindex_t ptepindex;
3312 		pml3_entry_t *ptepa;
3313 
3314 		/*
3315 		 * Calculate pagetable page index
3316 		 */
3317 		ptepindex = pmap_l3e_pindex(va);
3318 		if (mpte && (mpte->pindex == ptepindex)) {
3319 			mpte->ref_count++;
3320 		} else {
3321 			/*
3322 			 * Get the page directory entry
3323 			 */
3324 			ptepa = pmap_pml3e(pmap, va);
3325 
3326 			/*
3327 			 * If the page table page is mapped, we just increment
3328 			 * the hold count, and activate it.  Otherwise, we
3329 			 * attempt to allocate a page table page.  If this
3330 			 * attempt fails, we don't retry.  Instead, we give up.
3331 			 */
3332 			if (ptepa && (be64toh(*ptepa) & PG_V) != 0) {
3333 				if (be64toh(*ptepa) & RPTE_LEAF)
3334 					return (NULL);
3335 				mpte = PHYS_TO_VM_PAGE(be64toh(*ptepa) & PG_FRAME);
3336 				mpte->ref_count++;
3337 			} else {
3338 				/*
3339 				 * Pass NULL instead of the PV list lock
3340 				 * pointer, because we don't intend to sleep.
3341 				 */
3342 				mpte = _pmap_allocpte(pmap, ptepindex, NULL);
3343 				if (mpte == NULL)
3344 					return (mpte);
3345 			}
3346 		}
3347 		pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
3348 		pte = &pte[pmap_pte_index(va)];
3349 	} else {
3350 		mpte = NULL;
3351 		pte = pmap_pte(pmap, va);
3352 	}
3353 	if (be64toh(*pte)) {
3354 		if (mpte != NULL) {
3355 			mpte->ref_count--;
3356 			mpte = NULL;
3357 		}
3358 		return (mpte);
3359 	}
3360 
3361 	/*
3362 	 * Enter on the PV list if part of our managed memory.
3363 	 */
3364 	if ((m->oflags & VPO_UNMANAGED) == 0 &&
3365 	    !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
3366 		if (mpte != NULL) {
3367 			SLIST_INIT(&free);
3368 			if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
3369 				/*
3370 				 * Although "va" is not mapped, paging-
3371 				 * structure caches could nonetheless have
3372 				 * entries that refer to the freed page table
3373 				 * pages.  Invalidate those entries.
3374 				 */
3375 				*invalidate = true;
3376 				vm_page_free_pages_toq(&free, true);
3377 			}
3378 			mpte = NULL;
3379 		}
3380 		return (mpte);
3381 	}
3382 
3383 	/*
3384 	 * Increment counters
3385 	 */
3386 	pmap_resident_count_inc(pmap, 1);
3387 
3388 	pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.mdpg_cache_attrs);
3389 	if (prot & VM_PROT_EXECUTE)
3390 		pa |= PG_X;
3391 	else
3392 		pa |= RPTE_EAA_R;
3393 	if ((m->oflags & VPO_UNMANAGED) == 0)
3394 		pa |= PG_MANAGED;
3395 
3396 	pte_store(pte, pa);
3397 	return (mpte);
3398 }
3399 
3400 void
3401 mmu_radix_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m,
3402     vm_prot_t prot)
3403 {
3404 	struct rwlock *lock;
3405 	bool invalidate;
3406 
3407 	lock = NULL;
3408 	invalidate = false;
3409 	PMAP_LOCK(pmap);
3410 	mmu_radix_enter_quick_locked(pmap, va, m, prot, NULL, &lock,
3411 	    &invalidate);
3412 	ptesync();
3413 	if (lock != NULL)
3414 		rw_wunlock(lock);
3415 	if (invalidate)
3416 		pmap_invalidate_all(pmap);
3417 	PMAP_UNLOCK(pmap);
3418 }
3419 
3420 vm_paddr_t
3421 mmu_radix_extract(pmap_t pmap, vm_offset_t va)
3422 {
3423 	pml3_entry_t *l3e;
3424 	pt_entry_t *pte;
3425 	vm_paddr_t pa;
3426 
3427 	l3e = pmap_pml3e(pmap, va);
3428 	if (__predict_false(l3e == NULL))
3429 		return (0);
3430 	if (be64toh(*l3e) & RPTE_LEAF) {
3431 		pa = (be64toh(*l3e) & PG_PS_FRAME) | (va & L3_PAGE_MASK);
3432 		pa |= (va & L3_PAGE_MASK);
3433 	} else {
3434 		/*
3435 		 * Beware of a concurrent promotion that changes the
3436 		 * PDE at this point!  For example, vtopte() must not
3437 		 * be used to access the PTE because it would use the
3438 		 * new PDE.  It is, however, safe to use the old PDE
3439 		 * because the page table page is preserved by the
3440 		 * promotion.
3441 		 */
3442 		pte = pmap_l3e_to_pte(l3e, va);
3443 		if (__predict_false(pte == NULL))
3444 			return (0);
3445 		pa = be64toh(*pte);
3446 		pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3447 		pa |= (va & PAGE_MASK);
3448 	}
3449 	return (pa);
3450 }
3451 
3452 vm_page_t
3453 mmu_radix_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3454 {
3455 	pml3_entry_t l3e, *l3ep;
3456 	pt_entry_t pte;
3457 	vm_paddr_t pa;
3458 	vm_page_t m;
3459 
3460 	pa = 0;
3461 	m = NULL;
3462 	CTR4(KTR_PMAP, "%s(%p, %#x, %#x)", __func__, pmap, va, prot);
3463 	PMAP_LOCK(pmap);
3464 	l3ep = pmap_pml3e(pmap, va);
3465 	if (l3ep != NULL && (l3e = be64toh(*l3ep))) {
3466 		if (l3e & RPTE_LEAF) {
3467 			if ((l3e & PG_RW) || (prot & VM_PROT_WRITE) == 0)
3468 				m = PHYS_TO_VM_PAGE((l3e & PG_PS_FRAME) |
3469 				    (va & L3_PAGE_MASK));
3470 		} else {
3471 			/* Native endian PTE, do not pass to pmap functions */
3472 			pte = be64toh(*pmap_l3e_to_pte(l3ep, va));
3473 			if ((pte & PG_V) &&
3474 			    ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0))
3475 				m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3476 		}
3477 		if (m != NULL && !vm_page_wire_mapped(m))
3478 			m = NULL;
3479 	}
3480 	PMAP_UNLOCK(pmap);
3481 	return (m);
3482 }
3483 
3484 static void
3485 mmu_radix_growkernel(vm_offset_t addr)
3486 {
3487 	vm_paddr_t paddr;
3488 	vm_page_t nkpg;
3489 	pml3_entry_t *l3e;
3490 	pml2_entry_t *l2e;
3491 
3492 	CTR2(KTR_PMAP, "%s(%#x)", __func__, addr);
3493 	if (VM_MIN_KERNEL_ADDRESS < addr &&
3494 		addr < (VM_MIN_KERNEL_ADDRESS + nkpt * L3_PAGE_SIZE))
3495 		return;
3496 
3497 	addr = roundup2(addr, L3_PAGE_SIZE);
3498 	if (addr - 1 >= vm_map_max(kernel_map))
3499 		addr = vm_map_max(kernel_map);
3500 	while (kernel_vm_end < addr) {
3501 		l2e = pmap_pml2e(kernel_pmap, kernel_vm_end);
3502 		if ((be64toh(*l2e) & PG_V) == 0) {
3503 			/* We need a new PDP entry */
3504 			nkpg = vm_page_alloc(NULL, kernel_vm_end >> L2_PAGE_SIZE_SHIFT,
3505 			    VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3506 			    VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3507 			if (nkpg == NULL)
3508 				panic("pmap_growkernel: no memory to grow kernel");
3509 			if ((nkpg->flags & PG_ZERO) == 0)
3510 				mmu_radix_zero_page(nkpg);
3511 			paddr = VM_PAGE_TO_PHYS(nkpg);
3512 			pde_store(l2e, paddr);
3513 			continue; /* try again */
3514 		}
3515 		l3e = pmap_l2e_to_l3e(l2e, kernel_vm_end);
3516 		if ((be64toh(*l3e) & PG_V) != 0) {
3517 			kernel_vm_end = (kernel_vm_end + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
3518 			if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3519 				kernel_vm_end = vm_map_max(kernel_map);
3520 				break;
3521 			}
3522 			continue;
3523 		}
3524 
3525 		nkpg = vm_page_alloc(NULL, pmap_l3e_pindex(kernel_vm_end),
3526 		    VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3527 		    VM_ALLOC_ZERO);
3528 		if (nkpg == NULL)
3529 			panic("pmap_growkernel: no memory to grow kernel");
3530 		if ((nkpg->flags & PG_ZERO) == 0)
3531 			mmu_radix_zero_page(nkpg);
3532 		paddr = VM_PAGE_TO_PHYS(nkpg);
3533 		pde_store(l3e, paddr);
3534 
3535 		kernel_vm_end = (kernel_vm_end + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
3536 		if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3537 			kernel_vm_end = vm_map_max(kernel_map);
3538 			break;
3539 		}
3540 	}
3541 	ptesync();
3542 }
3543 
3544 static MALLOC_DEFINE(M_RADIX_PGD, "radix_pgd", "radix page table root directory");
3545 static uma_zone_t zone_radix_pgd;
3546 
3547 static int
3548 radix_pgd_import(void *arg __unused, void **store, int count, int domain __unused,
3549     int flags)
3550 {
3551 
3552 	for (int i = 0; i < count; i++) {
3553 		vm_page_t m = vm_page_alloc_contig(NULL, 0,
3554 		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3555 		    VM_ALLOC_ZERO | VM_ALLOC_WAITOK, RADIX_PGD_SIZE/PAGE_SIZE,
3556 		    0, (vm_paddr_t)-1, RADIX_PGD_SIZE, L1_PAGE_SIZE,
3557 		    VM_MEMATTR_DEFAULT);
3558 		/* XXX zero on alloc here so we don't have to later */
3559 		store[i] = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
3560 	}
3561 	return (count);
3562 }
3563 
3564 static void
3565 radix_pgd_release(void *arg __unused, void **store, int count)
3566 {
3567 	vm_page_t m;
3568 	struct spglist free;
3569 	int page_count;
3570 
3571 	SLIST_INIT(&free);
3572 	page_count = RADIX_PGD_SIZE/PAGE_SIZE;
3573 
3574 	for (int i = 0; i < count; i++) {
3575 		/*
3576 		 * XXX selectively remove dmap and KVA entries so we don't
3577 		 * need to bzero
3578 		 */
3579 		m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)store[i]));
3580 		for (int j = page_count-1; j >= 0; j--) {
3581 			vm_page_unwire_noq(&m[j]);
3582 			SLIST_INSERT_HEAD(&free, &m[j], plinks.s.ss);
3583 		}
3584 		vm_page_free_pages_toq(&free, false);
3585 	}
3586 }
3587 
3588 static void
3589 mmu_radix_init()
3590 {
3591 	vm_page_t mpte;
3592 	vm_size_t s;
3593 	int error, i, pv_npg;
3594 
3595 	/* XXX is this really needed for POWER? */
3596 	/* L1TF, reserve page @0 unconditionally */
3597 	vm_page_blacklist_add(0, bootverbose);
3598 
3599 	zone_radix_pgd = uma_zcache_create("radix_pgd_cache",
3600 		RADIX_PGD_SIZE, NULL, NULL,
3601 #ifdef INVARIANTS
3602 	    trash_init, trash_fini,
3603 #else
3604 	    NULL, NULL,
3605 #endif
3606 		radix_pgd_import, radix_pgd_release,
3607 		NULL, UMA_ZONE_NOBUCKET);
3608 
3609 	/*
3610 	 * Initialize the vm page array entries for the kernel pmap's
3611 	 * page table pages.
3612 	 */
3613 	PMAP_LOCK(kernel_pmap);
3614 	for (i = 0; i < nkpt; i++) {
3615 		mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
3616 		KASSERT(mpte >= vm_page_array &&
3617 		    mpte < &vm_page_array[vm_page_array_size],
3618 		    ("pmap_init: page table page is out of range size: %lu",
3619 		     vm_page_array_size));
3620 		mpte->pindex = pmap_l3e_pindex(VM_MIN_KERNEL_ADDRESS) + i;
3621 		mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
3622 		MPASS(PHYS_TO_VM_PAGE(mpte->phys_addr) == mpte);
3623 		//pmap_insert_pt_page(kernel_pmap, mpte);
3624 		mpte->ref_count = 1;
3625 	}
3626 	PMAP_UNLOCK(kernel_pmap);
3627 	vm_wire_add(nkpt);
3628 
3629 	CTR1(KTR_PMAP, "%s()", __func__);
3630 	TAILQ_INIT(&pv_dummy.pv_list);
3631 
3632 	/*
3633 	 * Are large page mappings enabled?
3634 	 */
3635 	TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
3636 	if (superpages_enabled) {
3637 		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
3638 		    ("pmap_init: can't assign to pagesizes[1]"));
3639 		pagesizes[1] = L3_PAGE_SIZE;
3640 	}
3641 
3642 	/*
3643 	 * Initialize the pv chunk list mutex.
3644 	 */
3645 	mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
3646 
3647 	/*
3648 	 * Initialize the pool of pv list locks.
3649 	 */
3650 	for (i = 0; i < NPV_LIST_LOCKS; i++)
3651 		rw_init(&pv_list_locks[i], "pmap pv list");
3652 
3653 	/*
3654 	 * Calculate the size of the pv head table for superpages.
3655 	 */
3656 	pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, L3_PAGE_SIZE);
3657 
3658 	/*
3659 	 * Allocate memory for the pv head table for superpages.
3660 	 */
3661 	s = (vm_size_t)(pv_npg * sizeof(struct md_page));
3662 	s = round_page(s);
3663 	pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
3664 	for (i = 0; i < pv_npg; i++)
3665 		TAILQ_INIT(&pv_table[i].pv_list);
3666 	TAILQ_INIT(&pv_dummy.pv_list);
3667 
3668 	pmap_initialized = 1;
3669 	mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
3670 	error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3671 	    (vmem_addr_t *)&qframe);
3672 
3673 	if (error != 0)
3674 		panic("qframe allocation failed");
3675 	asid_arena = vmem_create("ASID", isa3_base_pid + 1, (1<<isa3_pid_bits),
3676 	    1, 1, M_WAITOK);
3677 }
3678 
3679 static boolean_t
3680 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
3681 {
3682 	struct rwlock *lock;
3683 	pv_entry_t pv;
3684 	struct md_page *pvh;
3685 	pt_entry_t *pte, mask;
3686 	pmap_t pmap;
3687 	int md_gen, pvh_gen;
3688 	boolean_t rv;
3689 
3690 	rv = FALSE;
3691 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3692 	rw_rlock(lock);
3693 restart:
3694 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3695 		pmap = PV_PMAP(pv);
3696 		if (!PMAP_TRYLOCK(pmap)) {
3697 			md_gen = m->md.pv_gen;
3698 			rw_runlock(lock);
3699 			PMAP_LOCK(pmap);
3700 			rw_rlock(lock);
3701 			if (md_gen != m->md.pv_gen) {
3702 				PMAP_UNLOCK(pmap);
3703 				goto restart;
3704 			}
3705 		}
3706 		pte = pmap_pte(pmap, pv->pv_va);
3707 		mask = 0;
3708 		if (modified)
3709 			mask |= PG_RW | PG_M;
3710 		if (accessed)
3711 			mask |= PG_V | PG_A;
3712 		rv = (be64toh(*pte) & mask) == mask;
3713 		PMAP_UNLOCK(pmap);
3714 		if (rv)
3715 			goto out;
3716 	}
3717 	if ((m->flags & PG_FICTITIOUS) == 0) {
3718 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3719 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_link) {
3720 			pmap = PV_PMAP(pv);
3721 			if (!PMAP_TRYLOCK(pmap)) {
3722 				md_gen = m->md.pv_gen;
3723 				pvh_gen = pvh->pv_gen;
3724 				rw_runlock(lock);
3725 				PMAP_LOCK(pmap);
3726 				rw_rlock(lock);
3727 				if (md_gen != m->md.pv_gen ||
3728 				    pvh_gen != pvh->pv_gen) {
3729 					PMAP_UNLOCK(pmap);
3730 					goto restart;
3731 				}
3732 			}
3733 			pte = pmap_pml3e(pmap, pv->pv_va);
3734 			mask = 0;
3735 			if (modified)
3736 				mask |= PG_RW | PG_M;
3737 			if (accessed)
3738 				mask |= PG_V | PG_A;
3739 			rv = (be64toh(*pte) & mask) == mask;
3740 			PMAP_UNLOCK(pmap);
3741 			if (rv)
3742 				goto out;
3743 		}
3744 	}
3745 out:
3746 	rw_runlock(lock);
3747 	return (rv);
3748 }
3749 
3750 /*
3751  *	pmap_is_modified:
3752  *
3753  *	Return whether or not the specified physical page was modified
3754  *	in any physical maps.
3755  */
3756 boolean_t
3757 mmu_radix_is_modified(vm_page_t m)
3758 {
3759 
3760 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3761 	    ("pmap_is_modified: page %p is not managed", m));
3762 
3763 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
3764 	/*
3765 	 * If the page is not busied then this check is racy.
3766 	 */
3767 	if (!pmap_page_is_write_mapped(m))
3768 		return (FALSE);
3769 	return (pmap_page_test_mappings(m, FALSE, TRUE));
3770 }
3771 
3772 boolean_t
3773 mmu_radix_is_prefaultable(pmap_t pmap, vm_offset_t addr)
3774 {
3775 	pml3_entry_t *l3e;
3776 	pt_entry_t *pte;
3777 	boolean_t rv;
3778 
3779 	CTR3(KTR_PMAP, "%s(%p, %#x)", __func__, pmap, addr);
3780 	rv = FALSE;
3781 	PMAP_LOCK(pmap);
3782 	l3e = pmap_pml3e(pmap, addr);
3783 	if (l3e != NULL && (be64toh(*l3e) & (RPTE_LEAF | PG_V)) == PG_V) {
3784 		pte = pmap_l3e_to_pte(l3e, addr);
3785 		rv = (be64toh(*pte) & PG_V) == 0;
3786 	}
3787 	PMAP_UNLOCK(pmap);
3788 	return (rv);
3789 }
3790 
3791 boolean_t
3792 mmu_radix_is_referenced(vm_page_t m)
3793 {
3794 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3795 	    ("pmap_is_referenced: page %p is not managed", m));
3796 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
3797 	return (pmap_page_test_mappings(m, TRUE, FALSE));
3798 }
3799 
3800 /*
3801  *	pmap_ts_referenced:
3802  *
3803  *	Return a count of reference bits for a page, clearing those bits.
3804  *	It is not necessary for every reference bit to be cleared, but it
3805  *	is necessary that 0 only be returned when there are truly no
3806  *	reference bits set.
3807  *
3808  *	As an optimization, update the page's dirty field if a modified bit is
3809  *	found while counting reference bits.  This opportunistic update can be
3810  *	performed at low cost and can eliminate the need for some future calls
3811  *	to pmap_is_modified().  However, since this function stops after
3812  *	finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
3813  *	dirty pages.  Those dirty pages will only be detected by a future call
3814  *	to pmap_is_modified().
3815  *
3816  *	A DI block is not needed within this function, because
3817  *	invalidations are performed before the PV list lock is
3818  *	released.
3819  */
3820 boolean_t
3821 mmu_radix_ts_referenced(vm_page_t m)
3822 {
3823 	struct md_page *pvh;
3824 	pv_entry_t pv, pvf;
3825 	pmap_t pmap;
3826 	struct rwlock *lock;
3827 	pml3_entry_t oldl3e, *l3e;
3828 	pt_entry_t *pte;
3829 	vm_paddr_t pa;
3830 	int cleared, md_gen, not_cleared, pvh_gen;
3831 	struct spglist free;
3832 
3833 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
3834 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3835 	    ("pmap_ts_referenced: page %p is not managed", m));
3836 	SLIST_INIT(&free);
3837 	cleared = 0;
3838 	pa = VM_PAGE_TO_PHYS(m);
3839 	lock = PHYS_TO_PV_LIST_LOCK(pa);
3840 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
3841 	rw_wlock(lock);
3842 retry:
3843 	not_cleared = 0;
3844 	if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
3845 		goto small_mappings;
3846 	pv = pvf;
3847 	do {
3848 		if (pvf == NULL)
3849 			pvf = pv;
3850 		pmap = PV_PMAP(pv);
3851 		if (!PMAP_TRYLOCK(pmap)) {
3852 			pvh_gen = pvh->pv_gen;
3853 			rw_wunlock(lock);
3854 			PMAP_LOCK(pmap);
3855 			rw_wlock(lock);
3856 			if (pvh_gen != pvh->pv_gen) {
3857 				PMAP_UNLOCK(pmap);
3858 				goto retry;
3859 			}
3860 		}
3861 		l3e = pmap_pml3e(pmap, pv->pv_va);
3862 		oldl3e = be64toh(*l3e);
3863 		if ((oldl3e & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
3864 			/*
3865 			 * Although "oldpde" is mapping a 2MB page, because
3866 			 * this function is called at a 4KB page granularity,
3867 			 * we only update the 4KB page under test.
3868 			 */
3869 			vm_page_dirty(m);
3870 		}
3871 		if ((oldl3e & PG_A) != 0) {
3872 			/*
3873 			 * Since this reference bit is shared by 512 4KB
3874 			 * pages, it should not be cleared every time it is
3875 			 * tested.  Apply a simple "hash" function on the
3876 			 * physical page number, the virtual superpage number,
3877 			 * and the pmap address to select one 4KB page out of
3878 			 * the 512 on which testing the reference bit will
3879 			 * result in clearing that reference bit.  This
3880 			 * function is designed to avoid the selection of the
3881 			 * same 4KB page for every 2MB page mapping.
3882 			 *
3883 			 * On demotion, a mapping that hasn't been referenced
3884 			 * is simply destroyed.  To avoid the possibility of a
3885 			 * subsequent page fault on a demoted wired mapping,
3886 			 * always leave its reference bit set.  Moreover,
3887 			 * since the superpage is wired, the current state of
3888 			 * its reference bit won't affect page replacement.
3889 			 */
3890 			if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> L3_PAGE_SIZE_SHIFT) ^
3891 			    (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
3892 			    (oldl3e & PG_W) == 0) {
3893 				atomic_clear_long(l3e, htobe64(PG_A));
3894 				pmap_invalidate_page(pmap, pv->pv_va);
3895 				cleared++;
3896 				KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
3897 				    ("inconsistent pv lock %p %p for page %p",
3898 				    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
3899 			} else
3900 				not_cleared++;
3901 		}
3902 		PMAP_UNLOCK(pmap);
3903 		/* Rotate the PV list if it has more than one entry. */
3904 		if (pv != NULL && TAILQ_NEXT(pv, pv_link) != NULL) {
3905 			TAILQ_REMOVE(&pvh->pv_list, pv, pv_link);
3906 			TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_link);
3907 			pvh->pv_gen++;
3908 		}
3909 		if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
3910 			goto out;
3911 	} while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
3912 small_mappings:
3913 	if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
3914 		goto out;
3915 	pv = pvf;
3916 	do {
3917 		if (pvf == NULL)
3918 			pvf = pv;
3919 		pmap = PV_PMAP(pv);
3920 		if (!PMAP_TRYLOCK(pmap)) {
3921 			pvh_gen = pvh->pv_gen;
3922 			md_gen = m->md.pv_gen;
3923 			rw_wunlock(lock);
3924 			PMAP_LOCK(pmap);
3925 			rw_wlock(lock);
3926 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3927 				PMAP_UNLOCK(pmap);
3928 				goto retry;
3929 			}
3930 		}
3931 		l3e = pmap_pml3e(pmap, pv->pv_va);
3932 		KASSERT((be64toh(*l3e) & RPTE_LEAF) == 0,
3933 		    ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
3934 		    m));
3935 		pte = pmap_l3e_to_pte(l3e, pv->pv_va);
3936 		if ((be64toh(*pte) & (PG_M | PG_RW)) == (PG_M | PG_RW))
3937 			vm_page_dirty(m);
3938 		if ((be64toh(*pte) & PG_A) != 0) {
3939 			atomic_clear_long(pte, htobe64(PG_A));
3940 			pmap_invalidate_page(pmap, pv->pv_va);
3941 			cleared++;
3942 		}
3943 		PMAP_UNLOCK(pmap);
3944 		/* Rotate the PV list if it has more than one entry. */
3945 		if (pv != NULL && TAILQ_NEXT(pv, pv_link) != NULL) {
3946 			TAILQ_REMOVE(&m->md.pv_list, pv, pv_link);
3947 			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_link);
3948 			m->md.pv_gen++;
3949 		}
3950 	} while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
3951 	    not_cleared < PMAP_TS_REFERENCED_MAX);
3952 out:
3953 	rw_wunlock(lock);
3954 	vm_page_free_pages_toq(&free, true);
3955 	return (cleared + not_cleared);
3956 }
3957 
3958 static vm_offset_t
3959 mmu_radix_map(vm_offset_t *virt __unused, vm_paddr_t start,
3960     vm_paddr_t end, int prot __unused)
3961 {
3962 
3963 	CTR5(KTR_PMAP, "%s(%p, %#x, %#x, %#x)", __func__, virt, start, end,
3964 		 prot);
3965 	return (PHYS_TO_DMAP(start));
3966 }
3967 
3968 void
3969 mmu_radix_object_init_pt(pmap_t pmap, vm_offset_t addr,
3970     vm_object_t object, vm_pindex_t pindex, vm_size_t size)
3971 {
3972 	pml3_entry_t *l3e;
3973 	vm_paddr_t pa, ptepa;
3974 	vm_page_t p, pdpg;
3975 	vm_memattr_t ma;
3976 
3977 	CTR6(KTR_PMAP, "%s(%p, %#x, %p, %u, %#x)", __func__, pmap, addr,
3978 	    object, pindex, size);
3979 	VM_OBJECT_ASSERT_WLOCKED(object);
3980 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
3981 			("pmap_object_init_pt: non-device object"));
3982 	/* NB: size can be logically ored with addr here */
3983 	if ((addr & L3_PAGE_MASK) == 0 && (size & L3_PAGE_MASK) == 0) {
3984 		if (!mmu_radix_ps_enabled(pmap))
3985 			return;
3986 		if (!vm_object_populate(object, pindex, pindex + atop(size)))
3987 			return;
3988 		p = vm_page_lookup(object, pindex);
3989 		KASSERT(p->valid == VM_PAGE_BITS_ALL,
3990 		    ("pmap_object_init_pt: invalid page %p", p));
3991 		ma = p->md.mdpg_cache_attrs;
3992 
3993 		/*
3994 		 * Abort the mapping if the first page is not physically
3995 		 * aligned to a 2MB page boundary.
3996 		 */
3997 		ptepa = VM_PAGE_TO_PHYS(p);
3998 		if (ptepa & L3_PAGE_MASK)
3999 			return;
4000 
4001 		/*
4002 		 * Skip the first page.  Abort the mapping if the rest of
4003 		 * the pages are not physically contiguous or have differing
4004 		 * memory attributes.
4005 		 */
4006 		p = TAILQ_NEXT(p, listq);
4007 		for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4008 		    pa += PAGE_SIZE) {
4009 			KASSERT(p->valid == VM_PAGE_BITS_ALL,
4010 			    ("pmap_object_init_pt: invalid page %p", p));
4011 			if (pa != VM_PAGE_TO_PHYS(p) ||
4012 			    ma != p->md.mdpg_cache_attrs)
4013 				return;
4014 			p = TAILQ_NEXT(p, listq);
4015 		}
4016 
4017 		PMAP_LOCK(pmap);
4018 		for (pa = ptepa | pmap_cache_bits(ma);
4019 		    pa < ptepa + size; pa += L3_PAGE_SIZE) {
4020 			pdpg = pmap_allocl3e(pmap, addr, NULL);
4021 			if (pdpg == NULL) {
4022 				/*
4023 				 * The creation of mappings below is only an
4024 				 * optimization.  If a page directory page
4025 				 * cannot be allocated without blocking,
4026 				 * continue on to the next mapping rather than
4027 				 * blocking.
4028 				 */
4029 				addr += L3_PAGE_SIZE;
4030 				continue;
4031 			}
4032 			l3e = (pml3_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4033 			l3e = &l3e[pmap_pml3e_index(addr)];
4034 			if ((be64toh(*l3e) & PG_V) == 0) {
4035 				pa |= PG_M | PG_A | PG_RW;
4036 				pte_store(l3e, pa);
4037 				pmap_resident_count_inc(pmap, L3_PAGE_SIZE / PAGE_SIZE);
4038 				atomic_add_long(&pmap_l3e_mappings, 1);
4039 			} else {
4040 				/* Continue on if the PDE is already valid. */
4041 				pdpg->ref_count--;
4042 				KASSERT(pdpg->ref_count > 0,
4043 				    ("pmap_object_init_pt: missing reference "
4044 				    "to page directory page, va: 0x%lx", addr));
4045 			}
4046 			addr += L3_PAGE_SIZE;
4047 		}
4048 		ptesync();
4049 		PMAP_UNLOCK(pmap);
4050 	}
4051 }
4052 
4053 boolean_t
4054 mmu_radix_page_exists_quick(pmap_t pmap, vm_page_t m)
4055 {
4056 	struct md_page *pvh;
4057 	struct rwlock *lock;
4058 	pv_entry_t pv;
4059 	int loops = 0;
4060 	boolean_t rv;
4061 
4062 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4063 	    ("pmap_page_exists_quick: page %p is not managed", m));
4064 	CTR3(KTR_PMAP, "%s(%p, %p)", __func__, pmap, m);
4065 	rv = FALSE;
4066 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4067 	rw_rlock(lock);
4068 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
4069 		if (PV_PMAP(pv) == pmap) {
4070 			rv = TRUE;
4071 			break;
4072 		}
4073 		loops++;
4074 		if (loops >= 16)
4075 			break;
4076 	}
4077 	if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4078 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4079 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_link) {
4080 			if (PV_PMAP(pv) == pmap) {
4081 				rv = TRUE;
4082 				break;
4083 			}
4084 			loops++;
4085 			if (loops >= 16)
4086 				break;
4087 		}
4088 	}
4089 	rw_runlock(lock);
4090 	return (rv);
4091 }
4092 
4093 void
4094 mmu_radix_page_init(vm_page_t m)
4095 {
4096 
4097 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
4098 	TAILQ_INIT(&m->md.pv_list);
4099 	m->md.mdpg_cache_attrs = VM_MEMATTR_DEFAULT;
4100 }
4101 
4102 int
4103 mmu_radix_page_wired_mappings(vm_page_t m)
4104 {
4105 	struct rwlock *lock;
4106 	struct md_page *pvh;
4107 	pmap_t pmap;
4108 	pt_entry_t *pte;
4109 	pv_entry_t pv;
4110 	int count, md_gen, pvh_gen;
4111 
4112 	if ((m->oflags & VPO_UNMANAGED) != 0)
4113 		return (0);
4114 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
4115 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4116 	rw_rlock(lock);
4117 restart:
4118 	count = 0;
4119 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
4120 		pmap = PV_PMAP(pv);
4121 		if (!PMAP_TRYLOCK(pmap)) {
4122 			md_gen = m->md.pv_gen;
4123 			rw_runlock(lock);
4124 			PMAP_LOCK(pmap);
4125 			rw_rlock(lock);
4126 			if (md_gen != m->md.pv_gen) {
4127 				PMAP_UNLOCK(pmap);
4128 				goto restart;
4129 			}
4130 		}
4131 		pte = pmap_pte(pmap, pv->pv_va);
4132 		if ((be64toh(*pte) & PG_W) != 0)
4133 			count++;
4134 		PMAP_UNLOCK(pmap);
4135 	}
4136 	if ((m->flags & PG_FICTITIOUS) == 0) {
4137 		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4138 		TAILQ_FOREACH(pv, &pvh->pv_list, pv_link) {
4139 			pmap = PV_PMAP(pv);
4140 			if (!PMAP_TRYLOCK(pmap)) {
4141 				md_gen = m->md.pv_gen;
4142 				pvh_gen = pvh->pv_gen;
4143 				rw_runlock(lock);
4144 				PMAP_LOCK(pmap);
4145 				rw_rlock(lock);
4146 				if (md_gen != m->md.pv_gen ||
4147 				    pvh_gen != pvh->pv_gen) {
4148 					PMAP_UNLOCK(pmap);
4149 					goto restart;
4150 				}
4151 			}
4152 			pte = pmap_pml3e(pmap, pv->pv_va);
4153 			if ((be64toh(*pte) & PG_W) != 0)
4154 				count++;
4155 			PMAP_UNLOCK(pmap);
4156 		}
4157 	}
4158 	rw_runlock(lock);
4159 	return (count);
4160 }
4161 
4162 static void
4163 mmu_radix_update_proctab(int pid, pml1_entry_t l1pa)
4164 {
4165 	isa3_proctab[pid].proctab0 = htobe64(RTS_SIZE |  l1pa | RADIX_PGD_INDEX_SHIFT);
4166 }
4167 
4168 int
4169 mmu_radix_pinit(pmap_t pmap)
4170 {
4171 	vmem_addr_t pid;
4172 	vm_paddr_t l1pa;
4173 
4174 	CTR2(KTR_PMAP, "%s(%p)", __func__, pmap);
4175 
4176 	/*
4177 	 * allocate the page directory page
4178 	 */
4179 	pmap->pm_pml1 = uma_zalloc(zone_radix_pgd, M_WAITOK);
4180 
4181 	for (int j = 0; j <  RADIX_PGD_SIZE_SHIFT; j++)
4182 		pagezero((vm_offset_t)pmap->pm_pml1 + j * PAGE_SIZE);
4183 	pmap->pm_radix.rt_root = 0;
4184 	TAILQ_INIT(&pmap->pm_pvchunk);
4185 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4186 	pmap->pm_flags = PMAP_PDE_SUPERPAGE;
4187 	vmem_alloc(asid_arena, 1, M_FIRSTFIT|M_WAITOK, &pid);
4188 
4189 	pmap->pm_pid = pid;
4190 	l1pa = DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml1);
4191 	mmu_radix_update_proctab(pid, l1pa);
4192 	__asm __volatile("ptesync;isync" : : : "memory");
4193 
4194 	return (1);
4195 }
4196 
4197 /*
4198  * This routine is called if the desired page table page does not exist.
4199  *
4200  * If page table page allocation fails, this routine may sleep before
4201  * returning NULL.  It sleeps only if a lock pointer was given.
4202  *
4203  * Note: If a page allocation fails at page table level two or three,
4204  * one or two pages may be held during the wait, only to be released
4205  * afterwards.  This conservative approach is easily argued to avoid
4206  * race conditions.
4207  */
4208 static vm_page_t
4209 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
4210 {
4211 	vm_page_t m, pdppg, pdpg;
4212 
4213 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4214 
4215 	/*
4216 	 * Allocate a page table page.
4217 	 */
4218 	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
4219 	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
4220 		if (lockp != NULL) {
4221 			RELEASE_PV_LIST_LOCK(lockp);
4222 			PMAP_UNLOCK(pmap);
4223 			vm_wait(NULL);
4224 			PMAP_LOCK(pmap);
4225 		}
4226 		/*
4227 		 * Indicate the need to retry.  While waiting, the page table
4228 		 * page may have been allocated.
4229 		 */
4230 		return (NULL);
4231 	}
4232 	if ((m->flags & PG_ZERO) == 0)
4233 		mmu_radix_zero_page(m);
4234 
4235 	/*
4236 	 * Map the pagetable page into the process address space, if
4237 	 * it isn't already there.
4238 	 */
4239 
4240 	if (ptepindex >= (NUPDE + NUPDPE)) {
4241 		pml1_entry_t *l1e;
4242 		vm_pindex_t pml1index;
4243 
4244 		/* Wire up a new PDPE page */
4245 		pml1index = ptepindex - (NUPDE + NUPDPE);
4246 		l1e = &pmap->pm_pml1[pml1index];
4247 		pde_store(l1e, VM_PAGE_TO_PHYS(m));
4248 
4249 	} else if (ptepindex >= NUPDE) {
4250 		vm_pindex_t pml1index;
4251 		vm_pindex_t pdpindex;
4252 		pml1_entry_t *l1e;
4253 		pml2_entry_t *l2e;
4254 
4255 		/* Wire up a new l2e page */
4256 		pdpindex = ptepindex - NUPDE;
4257 		pml1index = pdpindex >> RPTE_SHIFT;
4258 
4259 		l1e = &pmap->pm_pml1[pml1index];
4260 		if ((be64toh(*l1e) & PG_V) == 0) {
4261 			/* Have to allocate a new pdp, recurse */
4262 			if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml1index,
4263 				lockp) == NULL) {
4264 				vm_page_unwire_noq(m);
4265 				vm_page_free_zero(m);
4266 				return (NULL);
4267 			}
4268 		} else {
4269 			/* Add reference to l2e page */
4270 			pdppg = PHYS_TO_VM_PAGE(be64toh(*l1e) & PG_FRAME);
4271 			pdppg->ref_count++;
4272 		}
4273 		l2e = (pml2_entry_t *)PHYS_TO_DMAP(be64toh(*l1e) & PG_FRAME);
4274 
4275 		/* Now find the pdp page */
4276 		l2e = &l2e[pdpindex & RPTE_MASK];
4277 		pde_store(l2e, VM_PAGE_TO_PHYS(m));
4278 
4279 	} else {
4280 		vm_pindex_t pml1index;
4281 		vm_pindex_t pdpindex;
4282 		pml1_entry_t *l1e;
4283 		pml2_entry_t *l2e;
4284 		pml3_entry_t *l3e;
4285 
4286 		/* Wire up a new PTE page */
4287 		pdpindex = ptepindex >> RPTE_SHIFT;
4288 		pml1index = pdpindex >> RPTE_SHIFT;
4289 
4290 		/* First, find the pdp and check that its valid. */
4291 		l1e = &pmap->pm_pml1[pml1index];
4292 		if ((be64toh(*l1e) & PG_V) == 0) {
4293 			/* Have to allocate a new pd, recurse */
4294 			if (_pmap_allocpte(pmap, NUPDE + pdpindex,
4295 			    lockp) == NULL) {
4296 				vm_page_unwire_noq(m);
4297 				vm_page_free_zero(m);
4298 				return (NULL);
4299 			}
4300 			l2e = (pml2_entry_t *)PHYS_TO_DMAP(be64toh(*l1e) & PG_FRAME);
4301 			l2e = &l2e[pdpindex & RPTE_MASK];
4302 		} else {
4303 			l2e = (pml2_entry_t *)PHYS_TO_DMAP(be64toh(*l1e) & PG_FRAME);
4304 			l2e = &l2e[pdpindex & RPTE_MASK];
4305 			if ((be64toh(*l2e) & PG_V) == 0) {
4306 				/* Have to allocate a new pd, recurse */
4307 				if (_pmap_allocpte(pmap, NUPDE + pdpindex,
4308 				    lockp) == NULL) {
4309 					vm_page_unwire_noq(m);
4310 					vm_page_free_zero(m);
4311 					return (NULL);
4312 				}
4313 			} else {
4314 				/* Add reference to the pd page */
4315 				pdpg = PHYS_TO_VM_PAGE(be64toh(*l2e) & PG_FRAME);
4316 				pdpg->ref_count++;
4317 			}
4318 		}
4319 		l3e = (pml3_entry_t *)PHYS_TO_DMAP(be64toh(*l2e) & PG_FRAME);
4320 
4321 		/* Now we know where the page directory page is */
4322 		l3e = &l3e[ptepindex & RPTE_MASK];
4323 		pde_store(l3e, VM_PAGE_TO_PHYS(m));
4324 	}
4325 
4326 	pmap_resident_count_inc(pmap, 1);
4327 	return (m);
4328 }
4329 static vm_page_t
4330 pmap_allocl3e(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4331 {
4332 	vm_pindex_t pdpindex, ptepindex;
4333 	pml2_entry_t *pdpe;
4334 	vm_page_t pdpg;
4335 
4336 retry:
4337 	pdpe = pmap_pml2e(pmap, va);
4338 	if (pdpe != NULL && (be64toh(*pdpe) & PG_V) != 0) {
4339 		/* Add a reference to the pd page. */
4340 		pdpg = PHYS_TO_VM_PAGE(be64toh(*pdpe) & PG_FRAME);
4341 		pdpg->ref_count++;
4342 	} else {
4343 		/* Allocate a pd page. */
4344 		ptepindex = pmap_l3e_pindex(va);
4345 		pdpindex = ptepindex >> RPTE_SHIFT;
4346 		pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
4347 		if (pdpg == NULL && lockp != NULL)
4348 			goto retry;
4349 	}
4350 	return (pdpg);
4351 }
4352 
4353 static vm_page_t
4354 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4355 {
4356 	vm_pindex_t ptepindex;
4357 	pml3_entry_t *pd;
4358 	vm_page_t m;
4359 
4360 	/*
4361 	 * Calculate pagetable page index
4362 	 */
4363 	ptepindex = pmap_l3e_pindex(va);
4364 retry:
4365 	/*
4366 	 * Get the page directory entry
4367 	 */
4368 	pd = pmap_pml3e(pmap, va);
4369 
4370 	/*
4371 	 * This supports switching from a 2MB page to a
4372 	 * normal 4K page.
4373 	 */
4374 	if (pd != NULL && (be64toh(*pd) & (RPTE_LEAF | PG_V)) == (RPTE_LEAF | PG_V)) {
4375 		if (!pmap_demote_l3e_locked(pmap, pd, va, lockp)) {
4376 			/*
4377 			 * Invalidation of the 2MB page mapping may have caused
4378 			 * the deallocation of the underlying PD page.
4379 			 */
4380 			pd = NULL;
4381 		}
4382 	}
4383 
4384 	/*
4385 	 * If the page table page is mapped, we just increment the
4386 	 * hold count, and activate it.
4387 	 */
4388 	if (pd != NULL && (be64toh(*pd) & PG_V) != 0) {
4389 		m = PHYS_TO_VM_PAGE(be64toh(*pd) & PG_FRAME);
4390 		m->ref_count++;
4391 	} else {
4392 		/*
4393 		 * Here if the pte page isn't mapped, or if it has been
4394 		 * deallocated.
4395 		 */
4396 		m = _pmap_allocpte(pmap, ptepindex, lockp);
4397 		if (m == NULL && lockp != NULL)
4398 			goto retry;
4399 	}
4400 	return (m);
4401 }
4402 
4403 static void
4404 mmu_radix_pinit0(pmap_t pmap)
4405 {
4406 
4407 	CTR2(KTR_PMAP, "%s(%p)", __func__, pmap);
4408 	PMAP_LOCK_INIT(pmap);
4409 	pmap->pm_pml1 = kernel_pmap->pm_pml1;
4410 	pmap->pm_pid = kernel_pmap->pm_pid;
4411 
4412 	pmap->pm_radix.rt_root = 0;
4413 	TAILQ_INIT(&pmap->pm_pvchunk);
4414 	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4415 	kernel_pmap->pm_flags =
4416 		pmap->pm_flags = PMAP_PDE_SUPERPAGE;
4417 }
4418 /*
4419  * pmap_protect_l3e: do the things to protect a 2mpage in a process
4420  */
4421 static boolean_t
4422 pmap_protect_l3e(pmap_t pmap, pt_entry_t *l3e, vm_offset_t sva, vm_prot_t prot)
4423 {
4424 	pt_entry_t newpde, oldpde;
4425 	vm_offset_t eva, va;
4426 	vm_page_t m;
4427 	boolean_t anychanged;
4428 
4429 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4430 	KASSERT((sva & L3_PAGE_MASK) == 0,
4431 	    ("pmap_protect_l3e: sva is not 2mpage aligned"));
4432 	anychanged = FALSE;
4433 retry:
4434 	oldpde = newpde = be64toh(*l3e);
4435 	if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4436 	    (PG_MANAGED | PG_M | PG_RW)) {
4437 		eva = sva + L3_PAGE_SIZE;
4438 		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4439 		    va < eva; va += PAGE_SIZE, m++)
4440 			vm_page_dirty(m);
4441 	}
4442 	if ((prot & VM_PROT_WRITE) == 0) {
4443 		newpde &= ~(PG_RW | PG_M);
4444 		newpde |= RPTE_EAA_R;
4445 	}
4446 	if (prot & VM_PROT_EXECUTE)
4447 		newpde |= PG_X;
4448 	if (newpde != oldpde) {
4449 		/*
4450 		 * As an optimization to future operations on this PDE, clear
4451 		 * PG_PROMOTED.  The impending invalidation will remove any
4452 		 * lingering 4KB page mappings from the TLB.
4453 		 */
4454 		if (!atomic_cmpset_long(l3e, htobe64(oldpde), htobe64(newpde & ~PG_PROMOTED)))
4455 			goto retry;
4456 		anychanged = TRUE;
4457 	}
4458 	return (anychanged);
4459 }
4460 
4461 void
4462 mmu_radix_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4463     vm_prot_t prot)
4464 {
4465 	vm_offset_t va_next;
4466 	pml1_entry_t *l1e;
4467 	pml2_entry_t *l2e;
4468 	pml3_entry_t ptpaddr, *l3e;
4469 	pt_entry_t *pte;
4470 	boolean_t anychanged;
4471 
4472 	CTR5(KTR_PMAP, "%s(%p, %#x, %#x, %#x)", __func__, pmap, sva, eva,
4473 	    prot);
4474 
4475 	KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4476 	if (prot == VM_PROT_NONE) {
4477 		mmu_radix_remove(pmap, sva, eva);
4478 		return;
4479 	}
4480 
4481 	if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4482 	    (VM_PROT_WRITE|VM_PROT_EXECUTE))
4483 		return;
4484 
4485 #ifdef INVARIANTS
4486 	if (VERBOSE_PROTECT || pmap_logging)
4487 		printf("pmap_protect(%p, %#lx, %#lx, %x) - asid: %lu\n",
4488 			   pmap, sva, eva, prot, pmap->pm_pid);
4489 #endif
4490 	anychanged = FALSE;
4491 
4492 	PMAP_LOCK(pmap);
4493 	for (; sva < eva; sva = va_next) {
4494 		l1e = pmap_pml1e(pmap, sva);
4495 		if ((be64toh(*l1e) & PG_V) == 0) {
4496 			va_next = (sva + L1_PAGE_SIZE) & ~L1_PAGE_MASK;
4497 			if (va_next < sva)
4498 				va_next = eva;
4499 			continue;
4500 		}
4501 
4502 		l2e = pmap_l1e_to_l2e(l1e, sva);
4503 		if ((be64toh(*l2e) & PG_V) == 0) {
4504 			va_next = (sva + L2_PAGE_SIZE) & ~L2_PAGE_MASK;
4505 			if (va_next < sva)
4506 				va_next = eva;
4507 			continue;
4508 		}
4509 
4510 		va_next = (sva + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
4511 		if (va_next < sva)
4512 			va_next = eva;
4513 
4514 		l3e = pmap_l2e_to_l3e(l2e, sva);
4515 		ptpaddr = be64toh(*l3e);
4516 
4517 		/*
4518 		 * Weed out invalid mappings.
4519 		 */
4520 		if (ptpaddr == 0)
4521 			continue;
4522 
4523 		/*
4524 		 * Check for large page.
4525 		 */
4526 		if ((ptpaddr & RPTE_LEAF) != 0) {
4527 			/*
4528 			 * Are we protecting the entire large page?  If not,
4529 			 * demote the mapping and fall through.
4530 			 */
4531 			if (sva + L3_PAGE_SIZE == va_next && eva >= va_next) {
4532 				if (pmap_protect_l3e(pmap, l3e, sva, prot))
4533 					anychanged = TRUE;
4534 				continue;
4535 			} else if (!pmap_demote_l3e(pmap, l3e, sva)) {
4536 				/*
4537 				 * The large page mapping was destroyed.
4538 				 */
4539 				continue;
4540 			}
4541 		}
4542 
4543 		if (va_next > eva)
4544 			va_next = eva;
4545 
4546 		for (pte = pmap_l3e_to_pte(l3e, sva); sva != va_next; pte++,
4547 		    sva += PAGE_SIZE) {
4548 			pt_entry_t obits, pbits;
4549 			vm_page_t m;
4550 
4551 retry:
4552 			MPASS(pte == pmap_pte(pmap, sva));
4553 			obits = pbits = be64toh(*pte);
4554 			if ((pbits & PG_V) == 0)
4555 				continue;
4556 
4557 			if ((prot & VM_PROT_WRITE) == 0) {
4558 				if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4559 				    (PG_MANAGED | PG_M | PG_RW)) {
4560 					m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4561 					vm_page_dirty(m);
4562 				}
4563 				pbits &= ~(PG_RW | PG_M);
4564 				pbits |= RPTE_EAA_R;
4565 			}
4566 			if (prot & VM_PROT_EXECUTE)
4567 				pbits |= PG_X;
4568 
4569 			if (pbits != obits) {
4570 				if (!atomic_cmpset_long(pte, htobe64(obits), htobe64(pbits)))
4571 					goto retry;
4572 				if (obits & (PG_A|PG_M)) {
4573 					anychanged = TRUE;
4574 #ifdef INVARIANTS
4575 					if (VERBOSE_PROTECT || pmap_logging)
4576 						printf("%#lx %#lx -> %#lx\n",
4577 						    sva, obits, pbits);
4578 #endif
4579 				}
4580 			}
4581 		}
4582 	}
4583 	if (anychanged)
4584 		pmap_invalidate_all(pmap);
4585 	PMAP_UNLOCK(pmap);
4586 }
4587 
4588 void
4589 mmu_radix_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4590 {
4591 
4592 	CTR4(KTR_PMAP, "%s(%#x, %p, %d)", __func__, sva, ma, count);
4593 	pt_entry_t oldpte, pa, *pte;
4594 	vm_page_t m;
4595 	uint64_t cache_bits, attr_bits;
4596 	vm_offset_t va;
4597 
4598 	oldpte = 0;
4599 	attr_bits = RPTE_EAA_R | RPTE_EAA_W | RPTE_EAA_P | PG_M | PG_A;
4600 	va = sva;
4601 	pte = kvtopte(va);
4602 	while (va < sva + PAGE_SIZE * count) {
4603 		if (__predict_false((va & L3_PAGE_MASK) == 0))
4604 			pte = kvtopte(va);
4605 		MPASS(pte == pmap_pte(kernel_pmap, va));
4606 
4607 		/*
4608 		 * XXX there has to be a more efficient way than traversing
4609 		 * the page table every time - but go for correctness for
4610 		 * today
4611 		 */
4612 
4613 		m = *ma++;
4614 		cache_bits = pmap_cache_bits(m->md.mdpg_cache_attrs);
4615 		pa = VM_PAGE_TO_PHYS(m) | cache_bits | attr_bits;
4616 		if (be64toh(*pte) != pa) {
4617 			oldpte |= be64toh(*pte);
4618 			pte_store(pte, pa);
4619 		}
4620 		va += PAGE_SIZE;
4621 		pte++;
4622 	}
4623 	if (__predict_false((oldpte & RPTE_VALID) != 0))
4624 		pmap_invalidate_range(kernel_pmap, sva, sva + count *
4625 		    PAGE_SIZE);
4626 	else
4627 		ptesync();
4628 }
4629 
4630 void
4631 mmu_radix_qremove(vm_offset_t sva, int count)
4632 {
4633 	vm_offset_t va;
4634 	pt_entry_t *pte;
4635 
4636 	CTR3(KTR_PMAP, "%s(%#x, %d)", __func__, sva, count);
4637 	KASSERT(sva >= VM_MIN_KERNEL_ADDRESS, ("usermode or dmap va %lx", sva));
4638 
4639 	va = sva;
4640 	pte = kvtopte(va);
4641 	while (va < sva + PAGE_SIZE * count) {
4642 		if (__predict_false((va & L3_PAGE_MASK) == 0))
4643 			pte = kvtopte(va);
4644 		pte_clear(pte);
4645 		pte++;
4646 		va += PAGE_SIZE;
4647 	}
4648 	pmap_invalidate_range(kernel_pmap, sva, va);
4649 }
4650 
4651 /***************************************************
4652  * Page table page management routines.....
4653  ***************************************************/
4654 /*
4655  * Schedule the specified unused page table page to be freed.  Specifically,
4656  * add the page to the specified list of pages that will be released to the
4657  * physical memory manager after the TLB has been updated.
4658  */
4659 static __inline void
4660 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4661     boolean_t set_PG_ZERO)
4662 {
4663 
4664 	if (set_PG_ZERO)
4665 		m->flags |= PG_ZERO;
4666 	else
4667 		m->flags &= ~PG_ZERO;
4668 	SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4669 }
4670 
4671 /*
4672  * Inserts the specified page table page into the specified pmap's collection
4673  * of idle page table pages.  Each of a pmap's page table pages is responsible
4674  * for mapping a distinct range of virtual addresses.  The pmap's collection is
4675  * ordered by this virtual address range.
4676  */
4677 static __inline int
4678 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
4679 {
4680 
4681 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4682 	return (vm_radix_insert(&pmap->pm_radix, mpte));
4683 }
4684 
4685 /*
4686  * Removes the page table page mapping the specified virtual address from the
4687  * specified pmap's collection of idle page table pages, and returns it.
4688  * Otherwise, returns NULL if there is no page table page corresponding to the
4689  * specified virtual address.
4690  */
4691 static __inline vm_page_t
4692 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4693 {
4694 
4695 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4696 	return (vm_radix_remove(&pmap->pm_radix, pmap_l3e_pindex(va)));
4697 }
4698 
4699 /*
4700  * Decrements a page table page's wire count, which is used to record the
4701  * number of valid page table entries within the page.  If the wire count
4702  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
4703  * page table page was unmapped and FALSE otherwise.
4704  */
4705 static inline boolean_t
4706 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4707 {
4708 
4709 	--m->ref_count;
4710 	if (m->ref_count == 0) {
4711 		_pmap_unwire_ptp(pmap, va, m, free);
4712 		return (TRUE);
4713 	} else
4714 		return (FALSE);
4715 }
4716 
4717 static void
4718 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4719 {
4720 
4721 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4722 	/*
4723 	 * unmap the page table page
4724 	 */
4725 	if (m->pindex >= (NUPDE + NUPDPE)) {
4726 		/* PDP page */
4727 		pml1_entry_t *pml1;
4728 		pml1 = pmap_pml1e(pmap, va);
4729 		*pml1 = 0;
4730 	} else if (m->pindex >= NUPDE) {
4731 		/* PD page */
4732 		pml2_entry_t *l2e;
4733 		l2e = pmap_pml2e(pmap, va);
4734 		*l2e = 0;
4735 	} else {
4736 		/* PTE page */
4737 		pml3_entry_t *l3e;
4738 		l3e = pmap_pml3e(pmap, va);
4739 		*l3e = 0;
4740 	}
4741 	pmap_resident_count_dec(pmap, 1);
4742 	if (m->pindex < NUPDE) {
4743 		/* We just released a PT, unhold the matching PD */
4744 		vm_page_t pdpg;
4745 
4746 		pdpg = PHYS_TO_VM_PAGE(be64toh(*pmap_pml2e(pmap, va)) & PG_FRAME);
4747 		pmap_unwire_ptp(pmap, va, pdpg, free);
4748 	}
4749 	if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
4750 		/* We just released a PD, unhold the matching PDP */
4751 		vm_page_t pdppg;
4752 
4753 		pdppg = PHYS_TO_VM_PAGE(be64toh(*pmap_pml1e(pmap, va)) & PG_FRAME);
4754 		pmap_unwire_ptp(pmap, va, pdppg, free);
4755 	}
4756 
4757 	/*
4758 	 * Put page on a list so that it is released after
4759 	 * *ALL* TLB shootdown is done
4760 	 */
4761 	pmap_add_delayed_free_list(m, free, TRUE);
4762 }
4763 
4764 /*
4765  * After removing a page table entry, this routine is used to
4766  * conditionally free the page, and manage the hold/wire counts.
4767  */
4768 static int
4769 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pml3_entry_t ptepde,
4770     struct spglist *free)
4771 {
4772 	vm_page_t mpte;
4773 
4774 	if (va >= VM_MAXUSER_ADDRESS)
4775 		return (0);
4776 	KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4777 	mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4778 	return (pmap_unwire_ptp(pmap, va, mpte, free));
4779 }
4780 
4781 void
4782 mmu_radix_release(pmap_t pmap)
4783 {
4784 
4785 	CTR2(KTR_PMAP, "%s(%p)", __func__, pmap);
4786 	KASSERT(pmap->pm_stats.resident_count == 0,
4787 	    ("pmap_release: pmap resident count %ld != 0",
4788 	    pmap->pm_stats.resident_count));
4789 	KASSERT(vm_radix_is_empty(&pmap->pm_radix),
4790 	    ("pmap_release: pmap has reserved page table page(s)"));
4791 
4792 	pmap_invalidate_all(pmap);
4793 	isa3_proctab[pmap->pm_pid].proctab0 = 0;
4794 	uma_zfree(zone_radix_pgd, pmap->pm_pml1);
4795 	vmem_free(asid_arena, pmap->pm_pid, 1);
4796 }
4797 
4798 /*
4799  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
4800  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
4801  * false if the PV entry cannot be allocated without resorting to reclamation.
4802  */
4803 static bool
4804 pmap_pv_insert_l3e(pmap_t pmap, vm_offset_t va, pml3_entry_t pde, u_int flags,
4805     struct rwlock **lockp)
4806 {
4807 	struct md_page *pvh;
4808 	pv_entry_t pv;
4809 	vm_paddr_t pa;
4810 
4811 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4812 	/* Pass NULL instead of the lock pointer to disable reclamation. */
4813 	if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
4814 	    NULL : lockp)) == NULL)
4815 		return (false);
4816 	pv->pv_va = va;
4817 	pa = pde & PG_PS_FRAME;
4818 	CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4819 	pvh = pa_to_pvh(pa);
4820 	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_link);
4821 	pvh->pv_gen++;
4822 	return (true);
4823 }
4824 
4825 /*
4826  * Fills a page table page with mappings to consecutive physical pages.
4827  */
4828 static void
4829 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
4830 {
4831 	pt_entry_t *pte;
4832 
4833 	for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
4834 		*pte = htobe64(newpte);
4835 		newpte += PAGE_SIZE;
4836 	}
4837 }
4838 
4839 static boolean_t
4840 pmap_demote_l3e(pmap_t pmap, pml3_entry_t *pde, vm_offset_t va)
4841 {
4842 	struct rwlock *lock;
4843 	boolean_t rv;
4844 
4845 	lock = NULL;
4846 	rv = pmap_demote_l3e_locked(pmap, pde, va, &lock);
4847 	if (lock != NULL)
4848 		rw_wunlock(lock);
4849 	return (rv);
4850 }
4851 
4852 static boolean_t
4853 pmap_demote_l3e_locked(pmap_t pmap, pml3_entry_t *l3e, vm_offset_t va,
4854     struct rwlock **lockp)
4855 {
4856 	pml3_entry_t oldpde;
4857 	pt_entry_t *firstpte;
4858 	vm_paddr_t mptepa;
4859 	vm_page_t mpte;
4860 	struct spglist free;
4861 	vm_offset_t sva;
4862 
4863 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4864 	oldpde = be64toh(*l3e);
4865 	KASSERT((oldpde & (RPTE_LEAF | PG_V)) == (RPTE_LEAF | PG_V),
4866 	    ("pmap_demote_l3e: oldpde is missing RPTE_LEAF and/or PG_V %lx",
4867 	    oldpde));
4868 	if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
4869 	    NULL) {
4870 		KASSERT((oldpde & PG_W) == 0,
4871 		    ("pmap_demote_l3e: page table page for a wired mapping"
4872 		    " is missing"));
4873 
4874 		/*
4875 		 * Invalidate the 2MB page mapping and return "failure" if the
4876 		 * mapping was never accessed or the allocation of the new
4877 		 * page table page fails.  If the 2MB page mapping belongs to
4878 		 * the direct map region of the kernel's address space, then
4879 		 * the page allocation request specifies the highest possible
4880 		 * priority (VM_ALLOC_INTERRUPT).  Otherwise, the priority is
4881 		 * normal.  Page table pages are preallocated for every other
4882 		 * part of the kernel address space, so the direct map region
4883 		 * is the only part of the kernel address space that must be
4884 		 * handled here.
4885 		 */
4886 		if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
4887 		    pmap_l3e_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
4888 		    DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
4889 		    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
4890 			SLIST_INIT(&free);
4891 			sva = trunc_2mpage(va);
4892 			pmap_remove_l3e(pmap, l3e, sva, &free, lockp);
4893 			pmap_invalidate_l3e_page(pmap, sva, oldpde);
4894 			vm_page_free_pages_toq(&free, true);
4895 			CTR2(KTR_PMAP, "pmap_demote_l3e: failure for va %#lx"
4896 			    " in pmap %p", va, pmap);
4897 			return (FALSE);
4898 		}
4899 		if (va < VM_MAXUSER_ADDRESS)
4900 			pmap_resident_count_inc(pmap, 1);
4901 	}
4902 	mptepa = VM_PAGE_TO_PHYS(mpte);
4903 	firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
4904 	KASSERT((oldpde & PG_A) != 0,
4905 	    ("pmap_demote_l3e: oldpde is missing PG_A"));
4906 	KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
4907 	    ("pmap_demote_l3e: oldpde is missing PG_M"));
4908 
4909 	/*
4910 	 * If the page table page is new, initialize it.
4911 	 */
4912 	if (mpte->ref_count == 1) {
4913 		mpte->ref_count = NPTEPG;
4914 		pmap_fill_ptp(firstpte, oldpde);
4915 	}
4916 
4917 	KASSERT((be64toh(*firstpte) & PG_FRAME) == (oldpde & PG_FRAME),
4918 	    ("pmap_demote_l3e: firstpte and newpte map different physical"
4919 	    " addresses"));
4920 
4921 	/*
4922 	 * If the mapping has changed attributes, update the page table
4923 	 * entries.
4924 	 */
4925 	if ((be64toh(*firstpte) & PG_PTE_PROMOTE) != (oldpde & PG_PTE_PROMOTE))
4926 		pmap_fill_ptp(firstpte, oldpde);
4927 
4928 	/*
4929 	 * The spare PV entries must be reserved prior to demoting the
4930 	 * mapping, that is, prior to changing the PDE.  Otherwise, the state
4931 	 * of the PDE and the PV lists will be inconsistent, which can result
4932 	 * in reclaim_pv_chunk() attempting to remove a PV entry from the
4933 	 * wrong PV list and pmap_pv_demote_l3e() failing to find the expected
4934 	 * PV entry for the 2MB page mapping that is being demoted.
4935 	 */
4936 	if ((oldpde & PG_MANAGED) != 0)
4937 		reserve_pv_entries(pmap, NPTEPG - 1, lockp);
4938 
4939 	/*
4940 	 * Demote the mapping.  This pmap is locked.  The old PDE has
4941 	 * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
4942 	 * set.  Thus, there is no danger of a race with another
4943 	 * processor changing the setting of PG_A and/or PG_M between
4944 	 * the read above and the store below.
4945 	 */
4946 	pde_store(l3e, mptepa);
4947 	ptesync();
4948 	/*
4949 	 * Demote the PV entry.
4950 	 */
4951 	if ((oldpde & PG_MANAGED) != 0)
4952 		pmap_pv_demote_l3e(pmap, va, oldpde & PG_PS_FRAME, lockp);
4953 
4954 	atomic_add_long(&pmap_l3e_demotions, 1);
4955 	CTR2(KTR_PMAP, "pmap_demote_l3e: success for va %#lx"
4956 	    " in pmap %p", va, pmap);
4957 	return (TRUE);
4958 }
4959 
4960 /*
4961  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
4962  */
4963 static void
4964 pmap_remove_kernel_l3e(pmap_t pmap, pml3_entry_t *l3e, vm_offset_t va)
4965 {
4966 	vm_paddr_t mptepa;
4967 	vm_page_t mpte;
4968 
4969 	KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
4970 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4971 	mpte = pmap_remove_pt_page(pmap, va);
4972 	if (mpte == NULL)
4973 		panic("pmap_remove_kernel_pde: Missing pt page.");
4974 
4975 	mptepa = VM_PAGE_TO_PHYS(mpte);
4976 
4977 	/*
4978 	 * Initialize the page table page.
4979 	 */
4980 	pagezero(PHYS_TO_DMAP(mptepa));
4981 
4982 	/*
4983 	 * Demote the mapping.
4984 	 */
4985 	pde_store(l3e, mptepa);
4986 	ptesync();
4987 }
4988 
4989 /*
4990  * pmap_remove_l3e: do the things to unmap a superpage in a process
4991  */
4992 static int
4993 pmap_remove_l3e(pmap_t pmap, pml3_entry_t *pdq, vm_offset_t sva,
4994     struct spglist *free, struct rwlock **lockp)
4995 {
4996 	struct md_page *pvh;
4997 	pml3_entry_t oldpde;
4998 	vm_offset_t eva, va;
4999 	vm_page_t m, mpte;
5000 
5001 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5002 	KASSERT((sva & L3_PAGE_MASK) == 0,
5003 	    ("pmap_remove_l3e: sva is not 2mpage aligned"));
5004 	oldpde = be64toh(pte_load_clear(pdq));
5005 	if (oldpde & PG_W)
5006 		pmap->pm_stats.wired_count -= (L3_PAGE_SIZE / PAGE_SIZE);
5007 	pmap_resident_count_dec(pmap, L3_PAGE_SIZE / PAGE_SIZE);
5008 	if (oldpde & PG_MANAGED) {
5009 		CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
5010 		pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
5011 		pmap_pvh_free(pvh, pmap, sva);
5012 		eva = sva + L3_PAGE_SIZE;
5013 		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
5014 		    va < eva; va += PAGE_SIZE, m++) {
5015 			if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
5016 				vm_page_dirty(m);
5017 			if (oldpde & PG_A)
5018 				vm_page_aflag_set(m, PGA_REFERENCED);
5019 			if (TAILQ_EMPTY(&m->md.pv_list) &&
5020 			    TAILQ_EMPTY(&pvh->pv_list))
5021 				vm_page_aflag_clear(m, PGA_WRITEABLE);
5022 		}
5023 	}
5024 	if (pmap == kernel_pmap) {
5025 		pmap_remove_kernel_l3e(pmap, pdq, sva);
5026 	} else {
5027 		mpte = pmap_remove_pt_page(pmap, sva);
5028 		if (mpte != NULL) {
5029 			pmap_resident_count_dec(pmap, 1);
5030 			KASSERT(mpte->ref_count == NPTEPG,
5031 			    ("pmap_remove_l3e: pte page wire count error"));
5032 			mpte->ref_count = 0;
5033 			pmap_add_delayed_free_list(mpte, free, FALSE);
5034 		}
5035 	}
5036 	return (pmap_unuse_pt(pmap, sva, be64toh(*pmap_pml2e(pmap, sva)), free));
5037 }
5038 
5039 /*
5040  * pmap_remove_pte: do the things to unmap a page in a process
5041  */
5042 static int
5043 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
5044     pml3_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
5045 {
5046 	struct md_page *pvh;
5047 	pt_entry_t oldpte;
5048 	vm_page_t m;
5049 
5050 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5051 	oldpte = be64toh(pte_load_clear(ptq));
5052 	if (oldpte & RPTE_WIRED)
5053 		pmap->pm_stats.wired_count -= 1;
5054 	pmap_resident_count_dec(pmap, 1);
5055 	if (oldpte & RPTE_MANAGED) {
5056 		m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
5057 		if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5058 			vm_page_dirty(m);
5059 		if (oldpte & PG_A)
5060 			vm_page_aflag_set(m, PGA_REFERENCED);
5061 		CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5062 		pmap_pvh_free(&m->md, pmap, va);
5063 		if (TAILQ_EMPTY(&m->md.pv_list) &&
5064 		    (m->flags & PG_FICTITIOUS) == 0) {
5065 			pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5066 			if (TAILQ_EMPTY(&pvh->pv_list))
5067 				vm_page_aflag_clear(m, PGA_WRITEABLE);
5068 		}
5069 	}
5070 	return (pmap_unuse_pt(pmap, va, ptepde, free));
5071 }
5072 
5073 /*
5074  * Remove a single page from a process address space
5075  */
5076 static bool
5077 pmap_remove_page(pmap_t pmap, vm_offset_t va, pml3_entry_t *l3e,
5078     struct spglist *free)
5079 {
5080 	struct rwlock *lock;
5081 	pt_entry_t *pte;
5082 	bool invalidate_all;
5083 
5084 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5085 	if ((be64toh(*l3e) & RPTE_VALID) == 0) {
5086 		return (false);
5087 	}
5088 	pte = pmap_l3e_to_pte(l3e, va);
5089 	if ((be64toh(*pte) & RPTE_VALID) == 0) {
5090 		return (false);
5091 	}
5092 	lock = NULL;
5093 
5094 	invalidate_all = pmap_remove_pte(pmap, pte, va, be64toh(*l3e), free, &lock);
5095 	if (lock != NULL)
5096 		rw_wunlock(lock);
5097 	if (!invalidate_all)
5098 		pmap_invalidate_page(pmap, va);
5099 	return (invalidate_all);
5100 }
5101 
5102 /*
5103  * Removes the specified range of addresses from the page table page.
5104  */
5105 static bool
5106 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
5107     pml3_entry_t *l3e, struct spglist *free, struct rwlock **lockp)
5108 {
5109 	pt_entry_t *pte;
5110 	vm_offset_t va;
5111 	bool anyvalid;
5112 
5113 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5114 	anyvalid = false;
5115 	va = eva;
5116 	for (pte = pmap_l3e_to_pte(l3e, sva); sva != eva; pte++,
5117 	    sva += PAGE_SIZE) {
5118 		MPASS(pte == pmap_pte(pmap, sva));
5119 		if (*pte == 0) {
5120 			if (va != eva) {
5121 				anyvalid = true;
5122 				va = eva;
5123 			}
5124 			continue;
5125 		}
5126 		if (va == eva)
5127 			va = sva;
5128 		if (pmap_remove_pte(pmap, pte, sva, be64toh(*l3e), free, lockp)) {
5129 			anyvalid = true;
5130 			sva += PAGE_SIZE;
5131 			break;
5132 		}
5133 	}
5134 	if (anyvalid)
5135 		pmap_invalidate_all(pmap);
5136 	else if (va != eva)
5137 		pmap_invalidate_range(pmap, va, sva);
5138 	return (anyvalid);
5139 }
5140 
5141 void
5142 mmu_radix_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5143 {
5144 	struct rwlock *lock;
5145 	vm_offset_t va_next;
5146 	pml1_entry_t *l1e;
5147 	pml2_entry_t *l2e;
5148 	pml3_entry_t ptpaddr, *l3e;
5149 	struct spglist free;
5150 	bool anyvalid;
5151 
5152 	CTR4(KTR_PMAP, "%s(%p, %#x, %#x)", __func__, pmap, sva, eva);
5153 
5154 	/*
5155 	 * Perform an unsynchronized read.  This is, however, safe.
5156 	 */
5157 	if (pmap->pm_stats.resident_count == 0)
5158 		return;
5159 
5160 	anyvalid = false;
5161 	SLIST_INIT(&free);
5162 
5163 	/* XXX something fishy here */
5164 	sva = (sva + PAGE_MASK) & ~PAGE_MASK;
5165 	eva = (eva + PAGE_MASK) & ~PAGE_MASK;
5166 
5167 	PMAP_LOCK(pmap);
5168 
5169 	/*
5170 	 * special handling of removing one page.  a very
5171 	 * common operation and easy to short circuit some
5172 	 * code.
5173 	 */
5174 	if (sva + PAGE_SIZE == eva) {
5175 		l3e = pmap_pml3e(pmap, sva);
5176 		if (l3e && (be64toh(*l3e) & RPTE_LEAF) == 0) {
5177 			anyvalid = pmap_remove_page(pmap, sva, l3e, &free);
5178 			goto out;
5179 		}
5180 	}
5181 
5182 	lock = NULL;
5183 	for (; sva < eva; sva = va_next) {
5184 		if (pmap->pm_stats.resident_count == 0)
5185 			break;
5186 		l1e = pmap_pml1e(pmap, sva);
5187 		if (l1e == NULL || (be64toh(*l1e) & PG_V) == 0) {
5188 			va_next = (sva + L1_PAGE_SIZE) & ~L1_PAGE_MASK;
5189 			if (va_next < sva)
5190 				va_next = eva;
5191 			continue;
5192 		}
5193 
5194 		l2e = pmap_l1e_to_l2e(l1e, sva);
5195 		if (l2e == NULL || (be64toh(*l2e) & PG_V) == 0) {
5196 			va_next = (sva + L2_PAGE_SIZE) & ~L2_PAGE_MASK;
5197 			if (va_next < sva)
5198 				va_next = eva;
5199 			continue;
5200 		}
5201 
5202 		/*
5203 		 * Calculate index for next page table.
5204 		 */
5205 		va_next = (sva + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
5206 		if (va_next < sva)
5207 			va_next = eva;
5208 
5209 		l3e = pmap_l2e_to_l3e(l2e, sva);
5210 		ptpaddr = be64toh(*l3e);
5211 
5212 		/*
5213 		 * Weed out invalid mappings.
5214 		 */
5215 		if (ptpaddr == 0)
5216 			continue;
5217 
5218 		/*
5219 		 * Check for large page.
5220 		 */
5221 		if ((ptpaddr & RPTE_LEAF) != 0) {
5222 			/*
5223 			 * Are we removing the entire large page?  If not,
5224 			 * demote the mapping and fall through.
5225 			 */
5226 			if (sva + L3_PAGE_SIZE == va_next && eva >= va_next) {
5227 				pmap_remove_l3e(pmap, l3e, sva, &free, &lock);
5228 				continue;
5229 			} else if (!pmap_demote_l3e_locked(pmap, l3e, sva,
5230 			    &lock)) {
5231 				/* The large page mapping was destroyed. */
5232 				continue;
5233 			} else
5234 				ptpaddr = be64toh(*l3e);
5235 		}
5236 
5237 		/*
5238 		 * Limit our scan to either the end of the va represented
5239 		 * by the current page table page, or to the end of the
5240 		 * range being removed.
5241 		 */
5242 		if (va_next > eva)
5243 			va_next = eva;
5244 
5245 		if (pmap_remove_ptes(pmap, sva, va_next, l3e, &free, &lock))
5246 			anyvalid = true;
5247 	}
5248 	if (lock != NULL)
5249 		rw_wunlock(lock);
5250 out:
5251 	if (anyvalid)
5252 		pmap_invalidate_all(pmap);
5253 	PMAP_UNLOCK(pmap);
5254 	vm_page_free_pages_toq(&free, true);
5255 }
5256 
5257 void
5258 mmu_radix_remove_all(vm_page_t m)
5259 {
5260 	struct md_page *pvh;
5261 	pv_entry_t pv;
5262 	pmap_t pmap;
5263 	struct rwlock *lock;
5264 	pt_entry_t *pte, tpte;
5265 	pml3_entry_t *l3e;
5266 	vm_offset_t va;
5267 	struct spglist free;
5268 	int pvh_gen, md_gen;
5269 
5270 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
5271 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5272 	    ("pmap_remove_all: page %p is not managed", m));
5273 	SLIST_INIT(&free);
5274 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5275 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5276 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
5277 retry:
5278 	rw_wlock(lock);
5279 	while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
5280 		pmap = PV_PMAP(pv);
5281 		if (!PMAP_TRYLOCK(pmap)) {
5282 			pvh_gen = pvh->pv_gen;
5283 			rw_wunlock(lock);
5284 			PMAP_LOCK(pmap);
5285 			rw_wlock(lock);
5286 			if (pvh_gen != pvh->pv_gen) {
5287 				rw_wunlock(lock);
5288 				PMAP_UNLOCK(pmap);
5289 				goto retry;
5290 			}
5291 		}
5292 		va = pv->pv_va;
5293 		l3e = pmap_pml3e(pmap, va);
5294 		(void)pmap_demote_l3e_locked(pmap, l3e, va, &lock);
5295 		PMAP_UNLOCK(pmap);
5296 	}
5297 	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
5298 		pmap = PV_PMAP(pv);
5299 		if (!PMAP_TRYLOCK(pmap)) {
5300 			pvh_gen = pvh->pv_gen;
5301 			md_gen = m->md.pv_gen;
5302 			rw_wunlock(lock);
5303 			PMAP_LOCK(pmap);
5304 			rw_wlock(lock);
5305 			if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5306 				rw_wunlock(lock);
5307 				PMAP_UNLOCK(pmap);
5308 				goto retry;
5309 			}
5310 		}
5311 		pmap_resident_count_dec(pmap, 1);
5312 		l3e = pmap_pml3e(pmap, pv->pv_va);
5313 		KASSERT((be64toh(*l3e) & RPTE_LEAF) == 0, ("pmap_remove_all: found"
5314 		    " a 2mpage in page %p's pv list", m));
5315 		pte = pmap_l3e_to_pte(l3e, pv->pv_va);
5316 		tpte = be64toh(pte_load_clear(pte));
5317 		if (tpte & PG_W)
5318 			pmap->pm_stats.wired_count--;
5319 		if (tpte & PG_A)
5320 			vm_page_aflag_set(m, PGA_REFERENCED);
5321 
5322 		/*
5323 		 * Update the vm_page_t clean and reference bits.
5324 		 */
5325 		if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5326 			vm_page_dirty(m);
5327 		pmap_unuse_pt(pmap, pv->pv_va, be64toh(*l3e), &free);
5328 		pmap_invalidate_page(pmap, pv->pv_va);
5329 		TAILQ_REMOVE(&m->md.pv_list, pv, pv_link);
5330 		m->md.pv_gen++;
5331 		free_pv_entry(pmap, pv);
5332 		PMAP_UNLOCK(pmap);
5333 	}
5334 	vm_page_aflag_clear(m, PGA_WRITEABLE);
5335 	rw_wunlock(lock);
5336 	vm_page_free_pages_toq(&free, true);
5337 }
5338 
5339 /*
5340  * Destroy all managed, non-wired mappings in the given user-space
5341  * pmap.  This pmap cannot be active on any processor besides the
5342  * caller.
5343  *
5344  * This function cannot be applied to the kernel pmap.  Moreover, it
5345  * is not intended for general use.  It is only to be used during
5346  * process termination.  Consequently, it can be implemented in ways
5347  * that make it faster than pmap_remove().  First, it can more quickly
5348  * destroy mappings by iterating over the pmap's collection of PV
5349  * entries, rather than searching the page table.  Second, it doesn't
5350  * have to test and clear the page table entries atomically, because
5351  * no processor is currently accessing the user address space.  In
5352  * particular, a page table entry's dirty bit won't change state once
5353  * this function starts.
5354  *
5355  * Although this function destroys all of the pmap's managed,
5356  * non-wired mappings, it can delay and batch the invalidation of TLB
5357  * entries without calling pmap_delayed_invl_started() and
5358  * pmap_delayed_invl_finished().  Because the pmap is not active on
5359  * any other processor, none of these TLB entries will ever be used
5360  * before their eventual invalidation.  Consequently, there is no need
5361  * for either pmap_remove_all() or pmap_remove_write() to wait for
5362  * that eventual TLB invalidation.
5363  */
5364 
5365 void
5366 mmu_radix_remove_pages(pmap_t pmap)
5367 {
5368 
5369 	CTR2(KTR_PMAP, "%s(%p)", __func__, pmap);
5370 	pml3_entry_t ptel3e;
5371 	pt_entry_t *pte, tpte;
5372 	struct spglist free;
5373 	vm_page_t m, mpte, mt;
5374 	pv_entry_t pv;
5375 	struct md_page *pvh;
5376 	struct pv_chunk *pc, *npc;
5377 	struct rwlock *lock;
5378 	int64_t bit;
5379 	uint64_t inuse, bitmask;
5380 	int allfree, field, freed, idx;
5381 	boolean_t superpage;
5382 	vm_paddr_t pa;
5383 
5384 	/*
5385 	 * Assert that the given pmap is only active on the current
5386 	 * CPU.  Unfortunately, we cannot block another CPU from
5387 	 * activating the pmap while this function is executing.
5388 	 */
5389 	KASSERT(pmap->pm_pid == mfspr(SPR_PID),
5390 	    ("non-current asid %lu - expected %lu", pmap->pm_pid,
5391 	    mfspr(SPR_PID)));
5392 
5393 	lock = NULL;
5394 
5395 	SLIST_INIT(&free);
5396 	PMAP_LOCK(pmap);
5397 	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5398 		allfree = 1;
5399 		freed = 0;
5400 		for (field = 0; field < _NPCM; field++) {
5401 			inuse = ~pc->pc_map[field] & pc_freemask[field];
5402 			while (inuse != 0) {
5403 				bit = cnttzd(inuse);
5404 				bitmask = 1UL << bit;
5405 				idx = field * 64 + bit;
5406 				pv = &pc->pc_pventry[idx];
5407 				inuse &= ~bitmask;
5408 
5409 				pte = pmap_pml2e(pmap, pv->pv_va);
5410 				ptel3e = be64toh(*pte);
5411 				pte = pmap_l2e_to_l3e(pte, pv->pv_va);
5412 				tpte = be64toh(*pte);
5413 				if ((tpte & (RPTE_LEAF | PG_V)) == PG_V) {
5414 					superpage = FALSE;
5415 					ptel3e = tpte;
5416 					pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5417 					    PG_FRAME);
5418 					pte = &pte[pmap_pte_index(pv->pv_va)];
5419 					tpte = be64toh(*pte);
5420 				} else {
5421 					/*
5422 					 * Keep track whether 'tpte' is a
5423 					 * superpage explicitly instead of
5424 					 * relying on RPTE_LEAF being set.
5425 					 *
5426 					 * This is because RPTE_LEAF is numerically
5427 					 * identical to PG_PTE_PAT and thus a
5428 					 * regular page could be mistaken for
5429 					 * a superpage.
5430 					 */
5431 					superpage = TRUE;
5432 				}
5433 
5434 				if ((tpte & PG_V) == 0) {
5435 					panic("bad pte va %lx pte %lx",
5436 					    pv->pv_va, tpte);
5437 				}
5438 
5439 /*
5440  * We cannot remove wired pages from a process' mapping at this time
5441  */
5442 				if (tpte & PG_W) {
5443 					allfree = 0;
5444 					continue;
5445 				}
5446 
5447 				if (superpage)
5448 					pa = tpte & PG_PS_FRAME;
5449 				else
5450 					pa = tpte & PG_FRAME;
5451 
5452 				m = PHYS_TO_VM_PAGE(pa);
5453 				KASSERT(m->phys_addr == pa,
5454 				    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5455 				    m, (uintmax_t)m->phys_addr,
5456 				    (uintmax_t)tpte));
5457 
5458 				KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5459 				    m < &vm_page_array[vm_page_array_size],
5460 				    ("pmap_remove_pages: bad tpte %#jx",
5461 				    (uintmax_t)tpte));
5462 
5463 				pte_clear(pte);
5464 
5465 				/*
5466 				 * Update the vm_page_t clean/reference bits.
5467 				 */
5468 				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5469 					if (superpage) {
5470 						for (mt = m; mt < &m[L3_PAGE_SIZE / PAGE_SIZE]; mt++)
5471 							vm_page_dirty(mt);
5472 					} else
5473 						vm_page_dirty(m);
5474 				}
5475 
5476 				CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5477 
5478 				/* Mark free */
5479 				pc->pc_map[field] |= bitmask;
5480 				if (superpage) {
5481 					pmap_resident_count_dec(pmap, L3_PAGE_SIZE / PAGE_SIZE);
5482 					pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5483 					TAILQ_REMOVE(&pvh->pv_list, pv, pv_link);
5484 					pvh->pv_gen++;
5485 					if (TAILQ_EMPTY(&pvh->pv_list)) {
5486 						for (mt = m; mt < &m[L3_PAGE_SIZE / PAGE_SIZE]; mt++)
5487 							if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5488 							    TAILQ_EMPTY(&mt->md.pv_list))
5489 								vm_page_aflag_clear(mt, PGA_WRITEABLE);
5490 					}
5491 					mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5492 					if (mpte != NULL) {
5493 						pmap_resident_count_dec(pmap, 1);
5494 						KASSERT(mpte->ref_count == NPTEPG,
5495 						    ("pmap_remove_pages: pte page wire count error"));
5496 						mpte->ref_count = 0;
5497 						pmap_add_delayed_free_list(mpte, &free, FALSE);
5498 					}
5499 				} else {
5500 					pmap_resident_count_dec(pmap, 1);
5501 #ifdef VERBOSE_PV
5502 					printf("freeing pv (%p, %p)\n",
5503 						   pmap, pv);
5504 #endif
5505 					TAILQ_REMOVE(&m->md.pv_list, pv, pv_link);
5506 					m->md.pv_gen++;
5507 					if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5508 					    TAILQ_EMPTY(&m->md.pv_list) &&
5509 					    (m->flags & PG_FICTITIOUS) == 0) {
5510 						pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5511 						if (TAILQ_EMPTY(&pvh->pv_list))
5512 							vm_page_aflag_clear(m, PGA_WRITEABLE);
5513 					}
5514 				}
5515 				pmap_unuse_pt(pmap, pv->pv_va, ptel3e, &free);
5516 				freed++;
5517 			}
5518 		}
5519 		PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5520 		PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5521 		PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5522 		if (allfree) {
5523 			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5524 			free_pv_chunk(pc);
5525 		}
5526 	}
5527 	if (lock != NULL)
5528 		rw_wunlock(lock);
5529 	pmap_invalidate_all(pmap);
5530 	PMAP_UNLOCK(pmap);
5531 	vm_page_free_pages_toq(&free, true);
5532 }
5533 
5534 void
5535 mmu_radix_remove_write(vm_page_t m)
5536 {
5537 	struct md_page *pvh;
5538 	pmap_t pmap;
5539 	struct rwlock *lock;
5540 	pv_entry_t next_pv, pv;
5541 	pml3_entry_t *l3e;
5542 	pt_entry_t oldpte, *pte;
5543 	int pvh_gen, md_gen;
5544 
5545 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
5546 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5547 	    ("pmap_remove_write: page %p is not managed", m));
5548 	vm_page_assert_busied(m);
5549 
5550 	if (!pmap_page_is_write_mapped(m))
5551 		return;
5552 	lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5553 	pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5554 	    pa_to_pvh(VM_PAGE_TO_PHYS(m));
5555 retry_pv_loop:
5556 	rw_wlock(lock);
5557 	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_link, next_pv) {
5558 		pmap = PV_PMAP(pv);
5559 		if (!PMAP_TRYLOCK(pmap)) {
5560 			pvh_gen = pvh->pv_gen;
5561 			rw_wunlock(lock);
5562 			PMAP_LOCK(pmap);
5563 			rw_wlock(lock);
5564 			if (pvh_gen != pvh->pv_gen) {
5565 				PMAP_UNLOCK(pmap);
5566 				rw_wunlock(lock);
5567 				goto retry_pv_loop;
5568 			}
5569 		}
5570 		l3e = pmap_pml3e(pmap, pv->pv_va);
5571 		if ((be64toh(*l3e) & PG_RW) != 0)
5572 			(void)pmap_demote_l3e_locked(pmap, l3e, pv->pv_va, &lock);
5573 		KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5574 		    ("inconsistent pv lock %p %p for page %p",
5575 		    lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5576 		PMAP_UNLOCK(pmap);
5577 	}
5578 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
5579 		pmap = PV_PMAP(pv);
5580 		if (!PMAP_TRYLOCK(pmap)) {
5581 			pvh_gen = pvh->pv_gen;
5582 			md_gen = m->md.pv_gen;
5583 			rw_wunlock(lock);
5584 			PMAP_LOCK(pmap);
5585 			rw_wlock(lock);
5586 			if (pvh_gen != pvh->pv_gen ||
5587 			    md_gen != m->md.pv_gen) {
5588 				PMAP_UNLOCK(pmap);
5589 				rw_wunlock(lock);
5590 				goto retry_pv_loop;
5591 			}
5592 		}
5593 		l3e = pmap_pml3e(pmap, pv->pv_va);
5594 		KASSERT((be64toh(*l3e) & RPTE_LEAF) == 0,
5595 		    ("pmap_remove_write: found a 2mpage in page %p's pv list",
5596 		    m));
5597 		pte = pmap_l3e_to_pte(l3e, pv->pv_va);
5598 retry:
5599 		oldpte = be64toh(*pte);
5600 		if (oldpte & PG_RW) {
5601 			if (!atomic_cmpset_long(pte, htobe64(oldpte),
5602 			    htobe64((oldpte | RPTE_EAA_R) & ~(PG_RW | PG_M))))
5603 				goto retry;
5604 			if ((oldpte & PG_M) != 0)
5605 				vm_page_dirty(m);
5606 			pmap_invalidate_page(pmap, pv->pv_va);
5607 		}
5608 		PMAP_UNLOCK(pmap);
5609 	}
5610 	rw_wunlock(lock);
5611 	vm_page_aflag_clear(m, PGA_WRITEABLE);
5612 }
5613 
5614 /*
5615  *	Clear the wired attribute from the mappings for the specified range of
5616  *	addresses in the given pmap.  Every valid mapping within that range
5617  *	must have the wired attribute set.  In contrast, invalid mappings
5618  *	cannot have the wired attribute set, so they are ignored.
5619  *
5620  *	The wired attribute of the page table entry is not a hardware
5621  *	feature, so there is no need to invalidate any TLB entries.
5622  *	Since pmap_demote_l3e() for the wired entry must never fail,
5623  *	pmap_delayed_invl_started()/finished() calls around the
5624  *	function are not needed.
5625  */
5626 void
5627 mmu_radix_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5628 {
5629 	vm_offset_t va_next;
5630 	pml1_entry_t *l1e;
5631 	pml2_entry_t *l2e;
5632 	pml3_entry_t *l3e;
5633 	pt_entry_t *pte;
5634 
5635 	CTR4(KTR_PMAP, "%s(%p, %#x, %#x)", __func__, pmap, sva, eva);
5636 	PMAP_LOCK(pmap);
5637 	for (; sva < eva; sva = va_next) {
5638 		l1e = pmap_pml1e(pmap, sva);
5639 		if ((be64toh(*l1e) & PG_V) == 0) {
5640 			va_next = (sva + L1_PAGE_SIZE) & ~L1_PAGE_MASK;
5641 			if (va_next < sva)
5642 				va_next = eva;
5643 			continue;
5644 		}
5645 		l2e = pmap_l1e_to_l2e(l1e, sva);
5646 		if ((be64toh(*l2e) & PG_V) == 0) {
5647 			va_next = (sva + L2_PAGE_SIZE) & ~L2_PAGE_MASK;
5648 			if (va_next < sva)
5649 				va_next = eva;
5650 			continue;
5651 		}
5652 		va_next = (sva + L3_PAGE_SIZE) & ~L3_PAGE_MASK;
5653 		if (va_next < sva)
5654 			va_next = eva;
5655 		l3e = pmap_l2e_to_l3e(l2e, sva);
5656 		if ((be64toh(*l3e) & PG_V) == 0)
5657 			continue;
5658 		if ((be64toh(*l3e) & RPTE_LEAF) != 0) {
5659 			if ((be64toh(*l3e) & PG_W) == 0)
5660 				panic("pmap_unwire: pde %#jx is missing PG_W",
5661 				    (uintmax_t)(be64toh(*l3e)));
5662 
5663 			/*
5664 			 * Are we unwiring the entire large page?  If not,
5665 			 * demote the mapping and fall through.
5666 			 */
5667 			if (sva + L3_PAGE_SIZE == va_next && eva >= va_next) {
5668 				atomic_clear_long(l3e, htobe64(PG_W));
5669 				pmap->pm_stats.wired_count -= L3_PAGE_SIZE /
5670 				    PAGE_SIZE;
5671 				continue;
5672 			} else if (!pmap_demote_l3e(pmap, l3e, sva))
5673 				panic("pmap_unwire: demotion failed");
5674 		}
5675 		if (va_next > eva)
5676 			va_next = eva;
5677 		for (pte = pmap_l3e_to_pte(l3e, sva); sva != va_next; pte++,
5678 		    sva += PAGE_SIZE) {
5679 			MPASS(pte == pmap_pte(pmap, sva));
5680 			if ((be64toh(*pte) & PG_V) == 0)
5681 				continue;
5682 			if ((be64toh(*pte) & PG_W) == 0)
5683 				panic("pmap_unwire: pte %#jx is missing PG_W",
5684 				    (uintmax_t)(be64toh(*pte)));
5685 
5686 			/*
5687 			 * PG_W must be cleared atomically.  Although the pmap
5688 			 * lock synchronizes access to PG_W, another processor
5689 			 * could be setting PG_M and/or PG_A concurrently.
5690 			 */
5691 			atomic_clear_long(pte, htobe64(PG_W));
5692 			pmap->pm_stats.wired_count--;
5693 		}
5694 	}
5695 	PMAP_UNLOCK(pmap);
5696 }
5697 
5698 void
5699 mmu_radix_zero_page(vm_page_t m)
5700 {
5701 	vm_offset_t addr;
5702 
5703 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
5704 	addr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5705 	pagezero(addr);
5706 }
5707 
5708 void
5709 mmu_radix_zero_page_area(vm_page_t m, int off, int size)
5710 {
5711 	caddr_t addr;
5712 
5713 	CTR4(KTR_PMAP, "%s(%p, %d, %d)", __func__, m, off, size);
5714 	MPASS(off + size <= PAGE_SIZE);
5715 	addr = (caddr_t)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5716 	memset(addr + off, 0, size);
5717 }
5718 
5719 static int
5720 mmu_radix_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
5721 {
5722 	pml3_entry_t *l3ep;
5723 	pt_entry_t pte;
5724 	vm_paddr_t pa;
5725 	int val;
5726 
5727 	CTR3(KTR_PMAP, "%s(%p, %#x)", __func__, pmap, addr);
5728 	PMAP_LOCK(pmap);
5729 
5730 	l3ep = pmap_pml3e(pmap, addr);
5731 	if (l3ep != NULL && (be64toh(*l3ep) & PG_V)) {
5732 		if (be64toh(*l3ep) & RPTE_LEAF) {
5733 			pte = be64toh(*l3ep);
5734 			/* Compute the physical address of the 4KB page. */
5735 			pa = ((be64toh(*l3ep) & PG_PS_FRAME) | (addr & L3_PAGE_MASK)) &
5736 			    PG_FRAME;
5737 			val = MINCORE_PSIND(1);
5738 		} else {
5739 			/* Native endian PTE, do not pass to functions */
5740 			pte = be64toh(*pmap_l3e_to_pte(l3ep, addr));
5741 			pa = pte & PG_FRAME;
5742 			val = 0;
5743 		}
5744 	} else {
5745 		pte = 0;
5746 		pa = 0;
5747 		val = 0;
5748 	}
5749 	if ((pte & PG_V) != 0) {
5750 		val |= MINCORE_INCORE;
5751 		if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5752 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5753 		if ((pte & PG_A) != 0)
5754 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5755 	}
5756 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5757 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
5758 	    (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
5759 		*locked_pa = pa;
5760 	}
5761 	PMAP_UNLOCK(pmap);
5762 	return (val);
5763 }
5764 
5765 void
5766 mmu_radix_activate(struct thread *td)
5767 {
5768 	pmap_t pmap;
5769 	uint32_t curpid;
5770 
5771 	CTR2(KTR_PMAP, "%s(%p)", __func__, td);
5772 	critical_enter();
5773 	pmap = vmspace_pmap(td->td_proc->p_vmspace);
5774 	curpid = mfspr(SPR_PID);
5775 	if (pmap->pm_pid > isa3_base_pid &&
5776 		curpid != pmap->pm_pid) {
5777 		mmu_radix_pid_set(pmap);
5778 	}
5779 	critical_exit();
5780 }
5781 
5782 /*
5783  *	Increase the starting virtual address of the given mapping if a
5784  *	different alignment might result in more superpage mappings.
5785  */
5786 void
5787 mmu_radix_align_superpage(vm_object_t object, vm_ooffset_t offset,
5788     vm_offset_t *addr, vm_size_t size)
5789 {
5790 
5791 	CTR5(KTR_PMAP, "%s(%p, %#x, %p, %#x)", __func__, object, offset, addr,
5792 	    size);
5793 	vm_offset_t superpage_offset;
5794 
5795 	if (size < L3_PAGE_SIZE)
5796 		return;
5797 	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5798 		offset += ptoa(object->pg_color);
5799 	superpage_offset = offset & L3_PAGE_MASK;
5800 	if (size - ((L3_PAGE_SIZE - superpage_offset) & L3_PAGE_MASK) < L3_PAGE_SIZE ||
5801 	    (*addr & L3_PAGE_MASK) == superpage_offset)
5802 		return;
5803 	if ((*addr & L3_PAGE_MASK) < superpage_offset)
5804 		*addr = (*addr & ~L3_PAGE_MASK) + superpage_offset;
5805 	else
5806 		*addr = ((*addr + L3_PAGE_MASK) & ~L3_PAGE_MASK) + superpage_offset;
5807 }
5808 
5809 static void *
5810 mmu_radix_mapdev_attr(vm_paddr_t pa, vm_size_t size, vm_memattr_t attr)
5811 {
5812 	vm_offset_t va, tmpva, ppa, offset;
5813 
5814 	ppa = trunc_page(pa);
5815 	offset = pa & PAGE_MASK;
5816 	size = roundup2(offset + size, PAGE_SIZE);
5817 	if (pa < powerpc_ptob(Maxmem))
5818 		panic("bad pa: %#lx less than Maxmem %#lx\n",
5819 			  pa, powerpc_ptob(Maxmem));
5820 	va = kva_alloc(size);
5821 	if (bootverbose)
5822 		printf("%s(%#lx, %lu, %d)\n", __func__, pa, size, attr);
5823 	KASSERT(size > 0, ("%s(%#lx, %lu, %d)", __func__, pa, size, attr));
5824 
5825 	if (!va)
5826 		panic("%s: Couldn't alloc kernel virtual memory", __func__);
5827 
5828 	for (tmpva = va; size > 0;) {
5829 		mmu_radix_kenter_attr(tmpva, ppa, attr);
5830 		size -= PAGE_SIZE;
5831 		tmpva += PAGE_SIZE;
5832 		ppa += PAGE_SIZE;
5833 	}
5834 	ptesync();
5835 
5836 	return ((void *)(va + offset));
5837 }
5838 
5839 static void *
5840 mmu_radix_mapdev(vm_paddr_t pa, vm_size_t size)
5841 {
5842 
5843 	CTR3(KTR_PMAP, "%s(%#x, %#x)", __func__, pa, size);
5844 
5845 	return (mmu_radix_mapdev_attr(pa, size, VM_MEMATTR_DEFAULT));
5846 }
5847 
5848 void
5849 mmu_radix_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5850 {
5851 
5852 	CTR3(KTR_PMAP, "%s(%p, %#x)", __func__, m, ma);
5853 	m->md.mdpg_cache_attrs = ma;
5854 
5855 	/*
5856 	 * If "m" is a normal page, update its direct mapping.  This update
5857 	 * can be relied upon to perform any cache operations that are
5858 	 * required for data coherence.
5859 	 */
5860 	if ((m->flags & PG_FICTITIOUS) == 0 &&
5861 	    mmu_radix_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
5862 	    PAGE_SIZE, m->md.mdpg_cache_attrs))
5863 		panic("memory attribute change on the direct map failed");
5864 }
5865 
5866 static void
5867 mmu_radix_unmapdev(vm_offset_t va, vm_size_t size)
5868 {
5869 	vm_offset_t offset;
5870 
5871 	CTR3(KTR_PMAP, "%s(%#x, %#x)", __func__, va, size);
5872 	/* If we gave a direct map region in pmap_mapdev, do nothing */
5873 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
5874 		return;
5875 
5876 	offset = va & PAGE_MASK;
5877 	size = round_page(offset + size);
5878 	va = trunc_page(va);
5879 
5880 	if (pmap_initialized) {
5881 		mmu_radix_qremove(va, atop(size));
5882 		kva_free(va, size);
5883 	}
5884 }
5885 
5886 static __inline void
5887 pmap_pte_attr(pt_entry_t *pte, uint64_t cache_bits, uint64_t mask)
5888 {
5889 	uint64_t opte, npte;
5890 
5891 	/*
5892 	 * The cache mode bits are all in the low 32-bits of the
5893 	 * PTE, so we can just spin on updating the low 32-bits.
5894 	 */
5895 	do {
5896 		opte = be64toh(*pte);
5897 		npte = opte & ~mask;
5898 		npte |= cache_bits;
5899 	} while (npte != opte && !atomic_cmpset_long(pte, htobe64(opte), htobe64(npte)));
5900 }
5901 
5902 /*
5903  * Tries to demote a 1GB page mapping.
5904  */
5905 static boolean_t
5906 pmap_demote_l2e(pmap_t pmap, pml2_entry_t *l2e, vm_offset_t va)
5907 {
5908 	pml2_entry_t oldpdpe;
5909 	pml3_entry_t *firstpde, newpde, *pde;
5910 	vm_paddr_t pdpgpa;
5911 	vm_page_t pdpg;
5912 
5913 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5914 	oldpdpe = be64toh(*l2e);
5915 	KASSERT((oldpdpe & (RPTE_LEAF | PG_V)) == (RPTE_LEAF | PG_V),
5916 	    ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
5917 	pdpg = vm_page_alloc(NULL, va >> L2_PAGE_SIZE_SHIFT,
5918 	    VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
5919 	if (pdpg == NULL) {
5920 		CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
5921 		    " in pmap %p", va, pmap);
5922 		return (FALSE);
5923 	}
5924 	pdpgpa = VM_PAGE_TO_PHYS(pdpg);
5925 	firstpde = (pml3_entry_t *)PHYS_TO_DMAP(pdpgpa);
5926 	KASSERT((oldpdpe & PG_A) != 0,
5927 	    ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
5928 	KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
5929 	    ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
5930 	newpde = oldpdpe;
5931 
5932 	/*
5933 	 * Initialize the page directory page.
5934 	 */
5935 	for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
5936 		*pde = htobe64(newpde);
5937 		newpde += L3_PAGE_SIZE;
5938 	}
5939 
5940 	/*
5941 	 * Demote the mapping.
5942 	 */
5943 	pde_store(l2e, pdpgpa);
5944 
5945 	/*
5946 	 * Flush PWC --- XXX revisit
5947 	 */
5948 	pmap_invalidate_all(pmap);
5949 
5950 	pmap_l2e_demotions++;
5951 	CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
5952 	    " in pmap %p", va, pmap);
5953 	return (TRUE);
5954 }
5955 
5956 vm_paddr_t
5957 mmu_radix_kextract(vm_offset_t va)
5958 {
5959 	pml3_entry_t l3e;
5960 	vm_paddr_t pa;
5961 
5962 	CTR2(KTR_PMAP, "%s(%#x)", __func__, va);
5963 	if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
5964 		pa = DMAP_TO_PHYS(va);
5965 	} else {
5966 		/* Big-endian PTE on stack */
5967 		l3e = *pmap_pml3e(kernel_pmap, va);
5968 		if (be64toh(l3e) & RPTE_LEAF) {
5969 			pa = (be64toh(l3e) & PG_PS_FRAME) | (va & L3_PAGE_MASK);
5970 			pa |= (va & L3_PAGE_MASK);
5971 		} else {
5972 			/*
5973 			 * Beware of a concurrent promotion that changes the
5974 			 * PDE at this point!  For example, vtopte() must not
5975 			 * be used to access the PTE because it would use the
5976 			 * new PDE.  It is, however, safe to use the old PDE
5977 			 * because the page table page is preserved by the
5978 			 * promotion.
5979 			 */
5980 			pa = be64toh(*pmap_l3e_to_pte(&l3e, va));
5981 			pa = (pa & PG_FRAME) | (va & PAGE_MASK);
5982 			pa |= (va & PAGE_MASK);
5983 		}
5984 	}
5985 	return (pa);
5986 }
5987 
5988 static pt_entry_t
5989 mmu_radix_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
5990 {
5991 
5992 	if (ma != VM_MEMATTR_DEFAULT) {
5993 		return pmap_cache_bits(ma);
5994 	}
5995 
5996 	/*
5997 	 * Assume the page is cache inhibited and access is guarded unless
5998 	 * it's in our available memory array.
5999 	 */
6000 	for (int i = 0; i < pregions_sz; i++) {
6001 		if ((pa >= pregions[i].mr_start) &&
6002 		    (pa < (pregions[i].mr_start + pregions[i].mr_size)))
6003 			return (RPTE_ATTR_MEM);
6004 	}
6005 	return (RPTE_ATTR_GUARDEDIO);
6006 }
6007 
6008 static void
6009 mmu_radix_kenter_attr(vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
6010 {
6011 	pt_entry_t *pte, pteval;
6012 	uint64_t cache_bits;
6013 
6014 	pte = kvtopte(va);
6015 	MPASS(pte != NULL);
6016 	pteval = pa | RPTE_EAA_R | RPTE_EAA_W | RPTE_EAA_P | PG_M | PG_A;
6017 	cache_bits = mmu_radix_calc_wimg(pa, ma);
6018 	pte_store(pte, pteval | cache_bits);
6019 }
6020 
6021 void
6022 mmu_radix_kremove(vm_offset_t va)
6023 {
6024 	pt_entry_t *pte;
6025 
6026 	CTR2(KTR_PMAP, "%s(%#x)", __func__, va);
6027 
6028 	pte = kvtopte(va);
6029 	pte_clear(pte);
6030 }
6031 
6032 int
6033 mmu_radix_decode_kernel_ptr(vm_offset_t addr,
6034     int *is_user, vm_offset_t *decoded)
6035 {
6036 
6037 	CTR2(KTR_PMAP, "%s(%#jx)", __func__, (uintmax_t)addr);
6038 	*decoded = addr;
6039 	*is_user = (addr < VM_MAXUSER_ADDRESS);
6040 	return (0);
6041 }
6042 
6043 static boolean_t
6044 mmu_radix_dev_direct_mapped(vm_paddr_t pa, vm_size_t size)
6045 {
6046 
6047 	CTR3(KTR_PMAP, "%s(%#x, %#x)", __func__, pa, size);
6048 	return (mem_valid(pa, size));
6049 }
6050 
6051 static void
6052 mmu_radix_scan_init()
6053 {
6054 
6055 	CTR1(KTR_PMAP, "%s()", __func__);
6056 	UNIMPLEMENTED();
6057 }
6058 
6059 static void
6060 mmu_radix_dumpsys_map(vm_paddr_t pa, size_t sz,
6061 	void **va)
6062 {
6063 	CTR4(KTR_PMAP, "%s(%#jx, %#zx, %p)", __func__, (uintmax_t)pa, sz, va);
6064 	UNIMPLEMENTED();
6065 }
6066 
6067 vm_offset_t
6068 mmu_radix_quick_enter_page(vm_page_t m)
6069 {
6070 	vm_paddr_t paddr;
6071 
6072 	CTR2(KTR_PMAP, "%s(%p)", __func__, m);
6073 	paddr = VM_PAGE_TO_PHYS(m);
6074 	return (PHYS_TO_DMAP(paddr));
6075 }
6076 
6077 void
6078 mmu_radix_quick_remove_page(vm_offset_t addr __unused)
6079 {
6080 	/* no work to do here */
6081 	CTR2(KTR_PMAP, "%s(%#x)", __func__, addr);
6082 }
6083 
6084 static void
6085 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
6086 {
6087 	cpu_flush_dcache((void *)sva, eva - sva);
6088 }
6089 
6090 int
6091 mmu_radix_change_attr(vm_offset_t va, vm_size_t size,
6092     vm_memattr_t mode)
6093 {
6094 	int error;
6095 
6096 	CTR4(KTR_PMAP, "%s(%#x, %#zx, %d)", __func__, va, size, mode);
6097 	PMAP_LOCK(kernel_pmap);
6098 	error = pmap_change_attr_locked(va, size, mode, true);
6099 	PMAP_UNLOCK(kernel_pmap);
6100 	return (error);
6101 }
6102 
6103 static int
6104 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode, bool flush)
6105 {
6106 	vm_offset_t base, offset, tmpva;
6107 	vm_paddr_t pa_start, pa_end, pa_end1;
6108 	pml2_entry_t *l2e;
6109 	pml3_entry_t *l3e;
6110 	pt_entry_t *pte;
6111 	int cache_bits, error;
6112 	boolean_t changed;
6113 
6114 	PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6115 	base = trunc_page(va);
6116 	offset = va & PAGE_MASK;
6117 	size = round_page(offset + size);
6118 
6119 	/*
6120 	 * Only supported on kernel virtual addresses, including the direct
6121 	 * map but excluding the recursive map.
6122 	 */
6123 	if (base < DMAP_MIN_ADDRESS)
6124 		return (EINVAL);
6125 
6126 	cache_bits = pmap_cache_bits(mode);
6127 	changed = FALSE;
6128 
6129 	/*
6130 	 * Pages that aren't mapped aren't supported.  Also break down 2MB pages
6131 	 * into 4KB pages if required.
6132 	 */
6133 	for (tmpva = base; tmpva < base + size; ) {
6134 		l2e = pmap_pml2e(kernel_pmap, tmpva);
6135 		if (l2e == NULL || *l2e == 0)
6136 			return (EINVAL);
6137 		if (be64toh(*l2e) & RPTE_LEAF) {
6138 			/*
6139 			 * If the current 1GB page already has the required
6140 			 * memory type, then we need not demote this page. Just
6141 			 * increment tmpva to the next 1GB page frame.
6142 			 */
6143 			if ((be64toh(*l2e) & RPTE_ATTR_MASK) == cache_bits) {
6144 				tmpva = trunc_1gpage(tmpva) + L2_PAGE_SIZE;
6145 				continue;
6146 			}
6147 
6148 			/*
6149 			 * If the current offset aligns with a 1GB page frame
6150 			 * and there is at least 1GB left within the range, then
6151 			 * we need not break down this page into 2MB pages.
6152 			 */
6153 			if ((tmpva & L2_PAGE_MASK) == 0 &&
6154 			    tmpva + L2_PAGE_MASK < base + size) {
6155 				tmpva += L2_PAGE_MASK;
6156 				continue;
6157 			}
6158 			if (!pmap_demote_l2e(kernel_pmap, l2e, tmpva))
6159 				return (ENOMEM);
6160 		}
6161 		l3e = pmap_l2e_to_l3e(l2e, tmpva);
6162 		KASSERT(l3e != NULL, ("no l3e entry for %#lx in %p\n",
6163 		    tmpva, l2e));
6164 		if (*l3e == 0)
6165 			return (EINVAL);
6166 		if (be64toh(*l3e) & RPTE_LEAF) {
6167 			/*
6168 			 * If the current 2MB page already has the required
6169 			 * memory type, then we need not demote this page. Just
6170 			 * increment tmpva to the next 2MB page frame.
6171 			 */
6172 			if ((be64toh(*l3e) & RPTE_ATTR_MASK) == cache_bits) {
6173 				tmpva = trunc_2mpage(tmpva) + L3_PAGE_SIZE;
6174 				continue;
6175 			}
6176 
6177 			/*
6178 			 * If the current offset aligns with a 2MB page frame
6179 			 * and there is at least 2MB left within the range, then
6180 			 * we need not break down this page into 4KB pages.
6181 			 */
6182 			if ((tmpva & L3_PAGE_MASK) == 0 &&
6183 			    tmpva + L3_PAGE_MASK < base + size) {
6184 				tmpva += L3_PAGE_SIZE;
6185 				continue;
6186 			}
6187 			if (!pmap_demote_l3e(kernel_pmap, l3e, tmpva))
6188 				return (ENOMEM);
6189 		}
6190 		pte = pmap_l3e_to_pte(l3e, tmpva);
6191 		if (*pte == 0)
6192 			return (EINVAL);
6193 		tmpva += PAGE_SIZE;
6194 	}
6195 	error = 0;
6196 
6197 	/*
6198 	 * Ok, all the pages exist, so run through them updating their
6199 	 * cache mode if required.
6200 	 */
6201 	pa_start = pa_end = 0;
6202 	for (tmpva = base; tmpva < base + size; ) {
6203 		l2e = pmap_pml2e(kernel_pmap, tmpva);
6204 		if (be64toh(*l2e) & RPTE_LEAF) {
6205 			if ((be64toh(*l2e) & RPTE_ATTR_MASK) != cache_bits) {
6206 				pmap_pte_attr(l2e, cache_bits,
6207 				    RPTE_ATTR_MASK);
6208 				changed = TRUE;
6209 			}
6210 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6211 			    (*l2e & PG_PS_FRAME) < dmaplimit) {
6212 				if (pa_start == pa_end) {
6213 					/* Start physical address run. */
6214 					pa_start = be64toh(*l2e) & PG_PS_FRAME;
6215 					pa_end = pa_start + L2_PAGE_SIZE;
6216 				} else if (pa_end == (be64toh(*l2e) & PG_PS_FRAME))
6217 					pa_end += L2_PAGE_SIZE;
6218 				else {
6219 					/* Run ended, update direct map. */
6220 					error = pmap_change_attr_locked(
6221 					    PHYS_TO_DMAP(pa_start),
6222 					    pa_end - pa_start, mode, flush);
6223 					if (error != 0)
6224 						break;
6225 					/* Start physical address run. */
6226 					pa_start = be64toh(*l2e) & PG_PS_FRAME;
6227 					pa_end = pa_start + L2_PAGE_SIZE;
6228 				}
6229 			}
6230 			tmpva = trunc_1gpage(tmpva) + L2_PAGE_SIZE;
6231 			continue;
6232 		}
6233 		l3e = pmap_l2e_to_l3e(l2e, tmpva);
6234 		if (be64toh(*l3e) & RPTE_LEAF) {
6235 			if ((be64toh(*l3e) & RPTE_ATTR_MASK) != cache_bits) {
6236 				pmap_pte_attr(l3e, cache_bits,
6237 				    RPTE_ATTR_MASK);
6238 				changed = TRUE;
6239 			}
6240 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6241 			    (be64toh(*l3e) & PG_PS_FRAME) < dmaplimit) {
6242 				if (pa_start == pa_end) {
6243 					/* Start physical address run. */
6244 					pa_start = be64toh(*l3e) & PG_PS_FRAME;
6245 					pa_end = pa_start + L3_PAGE_SIZE;
6246 				} else if (pa_end == (be64toh(*l3e) & PG_PS_FRAME))
6247 					pa_end += L3_PAGE_SIZE;
6248 				else {
6249 					/* Run ended, update direct map. */
6250 					error = pmap_change_attr_locked(
6251 					    PHYS_TO_DMAP(pa_start),
6252 					    pa_end - pa_start, mode, flush);
6253 					if (error != 0)
6254 						break;
6255 					/* Start physical address run. */
6256 					pa_start = be64toh(*l3e) & PG_PS_FRAME;
6257 					pa_end = pa_start + L3_PAGE_SIZE;
6258 				}
6259 			}
6260 			tmpva = trunc_2mpage(tmpva) + L3_PAGE_SIZE;
6261 		} else {
6262 			pte = pmap_l3e_to_pte(l3e, tmpva);
6263 			if ((be64toh(*pte) & RPTE_ATTR_MASK) != cache_bits) {
6264 				pmap_pte_attr(pte, cache_bits,
6265 				    RPTE_ATTR_MASK);
6266 				changed = TRUE;
6267 			}
6268 			if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6269 			    (be64toh(*pte) & PG_FRAME) < dmaplimit) {
6270 				if (pa_start == pa_end) {
6271 					/* Start physical address run. */
6272 					pa_start = be64toh(*pte) & PG_FRAME;
6273 					pa_end = pa_start + PAGE_SIZE;
6274 				} else if (pa_end == (be64toh(*pte) & PG_FRAME))
6275 					pa_end += PAGE_SIZE;
6276 				else {
6277 					/* Run ended, update direct map. */
6278 					error = pmap_change_attr_locked(
6279 					    PHYS_TO_DMAP(pa_start),
6280 					    pa_end - pa_start, mode, flush);
6281 					if (error != 0)
6282 						break;
6283 					/* Start physical address run. */
6284 					pa_start = be64toh(*pte) & PG_FRAME;
6285 					pa_end = pa_start + PAGE_SIZE;
6286 				}
6287 			}
6288 			tmpva += PAGE_SIZE;
6289 		}
6290 	}
6291 	if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6292 		pa_end1 = MIN(pa_end, dmaplimit);
6293 		if (pa_start != pa_end1)
6294 			error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6295 			    pa_end1 - pa_start, mode, flush);
6296 	}
6297 
6298 	/*
6299 	 * Flush CPU caches if required to make sure any data isn't cached that
6300 	 * shouldn't be, etc.
6301 	 */
6302 	if (changed) {
6303 		pmap_invalidate_all(kernel_pmap);
6304 
6305 		if (flush)
6306 			pmap_invalidate_cache_range(base, tmpva);
6307 	}
6308 	return (error);
6309 }
6310 
6311 /*
6312  * Allocate physical memory for the vm_page array and map it into KVA,
6313  * attempting to back the vm_pages with domain-local memory.
6314  */
6315 void
6316 mmu_radix_page_array_startup(long pages)
6317 {
6318 #ifdef notyet
6319 	pml2_entry_t *l2e;
6320 	pml3_entry_t *pde;
6321 	pml3_entry_t newl3;
6322 	vm_offset_t va;
6323 	long pfn;
6324 	int domain, i;
6325 #endif
6326 	vm_paddr_t pa;
6327 	vm_offset_t start, end;
6328 
6329 	vm_page_array_size = pages;
6330 
6331 	start = VM_MIN_KERNEL_ADDRESS;
6332 	end = start + pages * sizeof(struct vm_page);
6333 
6334 	pa = vm_phys_early_alloc(0, end - start);
6335 
6336 	start = mmu_radix_map(&start, pa, end - start, VM_MEMATTR_DEFAULT);
6337 #ifdef notyet
6338 	/* TODO: NUMA vm_page_array.  Blocked out until then (copied from amd64). */
6339 	for (va = start; va < end; va += L3_PAGE_SIZE) {
6340 		pfn = first_page + (va - start) / sizeof(struct vm_page);
6341 		domain = vm_phys_domain(ptoa(pfn));
6342 		l2e = pmap_pml2e(kernel_pmap, va);
6343 		if ((be64toh(*l2e) & PG_V) == 0) {
6344 			pa = vm_phys_early_alloc(domain, PAGE_SIZE);
6345 			dump_add_page(pa);
6346 			pagezero(PHYS_TO_DMAP(pa));
6347 			pde_store(l2e, (pml2_entry_t)pa);
6348 		}
6349 		pde = pmap_l2e_to_l3e(l2e, va);
6350 		if ((be64toh(*pde) & PG_V) != 0)
6351 			panic("Unexpected pde %p", pde);
6352 		pa = vm_phys_early_alloc(domain, L3_PAGE_SIZE);
6353 		for (i = 0; i < NPDEPG; i++)
6354 			dump_add_page(pa + i * PAGE_SIZE);
6355 		newl3 = (pml3_entry_t)(pa | RPTE_EAA_P | RPTE_EAA_R | RPTE_EAA_W);
6356 		pte_store(pde, newl3);
6357 	}
6358 #endif
6359 	vm_page_array = (vm_page_t)start;
6360 }
6361 
6362 #ifdef DDB
6363 #include <sys/kdb.h>
6364 #include <ddb/ddb.h>
6365 
6366 static void
6367 pmap_pte_walk(pml1_entry_t *l1, vm_offset_t va)
6368 {
6369 	pml1_entry_t *l1e;
6370 	pml2_entry_t *l2e;
6371 	pml3_entry_t *l3e;
6372 	pt_entry_t *pte;
6373 
6374 	l1e = &l1[pmap_pml1e_index(va)];
6375 	db_printf("VA %#016lx l1e %#016lx", va, be64toh(*l1e));
6376 	if ((be64toh(*l1e) & PG_V) == 0) {
6377 		db_printf("\n");
6378 		return;
6379 	}
6380 	l2e = pmap_l1e_to_l2e(l1e, va);
6381 	db_printf(" l2e %#016lx", be64toh(*l2e));
6382 	if ((be64toh(*l2e) & PG_V) == 0 || (be64toh(*l2e) & RPTE_LEAF) != 0) {
6383 		db_printf("\n");
6384 		return;
6385 	}
6386 	l3e = pmap_l2e_to_l3e(l2e, va);
6387 	db_printf(" l3e %#016lx", be64toh(*l3e));
6388 	if ((be64toh(*l3e) & PG_V) == 0 || (be64toh(*l3e) & RPTE_LEAF) != 0) {
6389 		db_printf("\n");
6390 		return;
6391 	}
6392 	pte = pmap_l3e_to_pte(l3e, va);
6393 	db_printf(" pte %#016lx\n", be64toh(*pte));
6394 }
6395 
6396 void
6397 pmap_page_print_mappings(vm_page_t m)
6398 {
6399 	pmap_t pmap;
6400 	pv_entry_t pv;
6401 
6402 	db_printf("page %p(%lx)\n", m, m->phys_addr);
6403 	/* need to elide locks if running in ddb */
6404 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
6405 		db_printf("pv: %p ", pv);
6406 		db_printf("va: %#016lx ", pv->pv_va);
6407 		pmap = PV_PMAP(pv);
6408 		db_printf("pmap %p  ", pmap);
6409 		if (pmap != NULL) {
6410 			db_printf("asid: %lu\n", pmap->pm_pid);
6411 			pmap_pte_walk(pmap->pm_pml1, pv->pv_va);
6412 		}
6413 	}
6414 }
6415 
6416 DB_SHOW_COMMAND(pte, pmap_print_pte)
6417 {
6418 	vm_offset_t va;
6419 	pmap_t pmap;
6420 
6421 	if (!have_addr) {
6422 		db_printf("show pte addr\n");
6423 		return;
6424 	}
6425 	va = (vm_offset_t)addr;
6426 
6427 	if (va >= DMAP_MIN_ADDRESS)
6428 		pmap = kernel_pmap;
6429 	else if (kdb_thread != NULL)
6430 		pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
6431 	else
6432 		pmap = vmspace_pmap(curthread->td_proc->p_vmspace);
6433 
6434 	pmap_pte_walk(pmap->pm_pml1, va);
6435 }
6436 
6437 #endif
6438