xref: /freebsd/sys/powerpc/aim/mmu_oea64.c (revision ff19fd624233a938b6a09ac75a87a2c69d65df08)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2008-2015 Nathan Whitehorn
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 /*
33  * Manages physical address maps.
34  *
35  * Since the information managed by this module is also stored by the
36  * logical address mapping module, this module may throw away valid virtual
37  * to physical mappings at almost any time.  However, invalidations of
38  * mappings must be done as requested.
39  *
40  * In order to cope with hardware architectures which make virtual to
41  * physical map invalidates expensive, this module may delay invalidate
42  * reduced protection operations until such time as they are actually
43  * necessary.  This module is given full information as to which processors
44  * are currently using which maps, and to when physical maps must be made
45  * correct.
46  */
47 
48 #include "opt_kstack_pages.h"
49 
50 #include <sys/param.h>
51 #include <sys/kernel.h>
52 #include <sys/conf.h>
53 #include <sys/queue.h>
54 #include <sys/cpuset.h>
55 #include <sys/kerneldump.h>
56 #include <sys/ktr.h>
57 #include <sys/lock.h>
58 #include <sys/msgbuf.h>
59 #include <sys/malloc.h>
60 #include <sys/mman.h>
61 #include <sys/mutex.h>
62 #include <sys/proc.h>
63 #include <sys/rwlock.h>
64 #include <sys/sched.h>
65 #include <sys/sysctl.h>
66 #include <sys/systm.h>
67 #include <sys/vmmeter.h>
68 #include <sys/smp.h>
69 #include <sys/reboot.h>
70 
71 #include <sys/kdb.h>
72 
73 #include <dev/ofw/openfirm.h>
74 
75 #include <vm/vm.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_param.h>
78 #include <vm/vm_kern.h>
79 #include <vm/vm_page.h>
80 #include <vm/vm_phys.h>
81 #include <vm/vm_map.h>
82 #include <vm/vm_object.h>
83 #include <vm/vm_extern.h>
84 #include <vm/vm_pageout.h>
85 #include <vm/vm_dumpset.h>
86 #include <vm/vm_reserv.h>
87 #include <vm/uma.h>
88 
89 #include <machine/_inttypes.h>
90 #include <machine/cpu.h>
91 #include <machine/ifunc.h>
92 #include <machine/platform.h>
93 #include <machine/frame.h>
94 #include <machine/md_var.h>
95 #include <machine/psl.h>
96 #include <machine/bat.h>
97 #include <machine/hid.h>
98 #include <machine/pte.h>
99 #include <machine/sr.h>
100 #include <machine/trap.h>
101 #include <machine/mmuvar.h>
102 
103 #include "mmu_oea64.h"
104 
105 void moea64_release_vsid(uint64_t vsid);
106 uintptr_t moea64_get_unique_vsid(void);
107 
108 #define DISABLE_TRANS(msr)	msr = mfmsr(); mtmsr(msr & ~PSL_DR)
109 #define ENABLE_TRANS(msr)	mtmsr(msr)
110 
111 #define	VSID_MAKE(sr, hash)	((sr) | (((hash) & 0xfffff) << 4))
112 #define	VSID_TO_HASH(vsid)	(((vsid) >> 4) & 0xfffff)
113 #define	VSID_HASH_MASK		0x0000007fffffffffULL
114 
115 /*
116  * Locking semantics:
117  *
118  * There are two locks of interest: the page locks and the pmap locks, which
119  * protect their individual PVO lists and are locked in that order. The contents
120  * of all PVO entries are protected by the locks of their respective pmaps.
121  * The pmap of any PVO is guaranteed not to change so long as the PVO is linked
122  * into any list.
123  *
124  */
125 
126 #define PV_LOCK_COUNT	PA_LOCK_COUNT
127 static struct mtx_padalign pv_lock[PV_LOCK_COUNT];
128 
129 /*
130  * Cheap NUMA-izing of the pv locks, to reduce contention across domains.
131  * NUMA domains on POWER9 appear to be indexed as sparse memory spaces, with the
132  * index at (N << 45).
133  */
134 #ifdef __powerpc64__
135 #define PV_LOCK_IDX(pa)	((pa_index(pa) * (((pa) >> 45) + 1)) % PV_LOCK_COUNT)
136 #else
137 #define PV_LOCK_IDX(pa)	(pa_index(pa) % PV_LOCK_COUNT)
138 #endif
139 #define PV_LOCKPTR(pa)	((struct mtx *)(&pv_lock[PV_LOCK_IDX(pa)]))
140 #define PV_LOCK(pa)		mtx_lock(PV_LOCKPTR(pa))
141 #define PV_UNLOCK(pa)		mtx_unlock(PV_LOCKPTR(pa))
142 #define PV_LOCKASSERT(pa) 	mtx_assert(PV_LOCKPTR(pa), MA_OWNED)
143 #define PV_PAGE_LOCK(m)		PV_LOCK(VM_PAGE_TO_PHYS(m))
144 #define PV_PAGE_UNLOCK(m)	PV_UNLOCK(VM_PAGE_TO_PHYS(m))
145 #define PV_PAGE_LOCKASSERT(m)	PV_LOCKASSERT(VM_PAGE_TO_PHYS(m))
146 
147 /* Superpage PV lock */
148 
149 #define	PV_LOCK_SIZE		(1<<PDRSHIFT)
150 
151 static __always_inline void
152 moea64_sp_pv_lock(vm_paddr_t pa)
153 {
154 	vm_paddr_t pa_end;
155 
156 	/* Note: breaking when pa_end is reached to avoid overflows */
157 	pa_end = pa + (HPT_SP_SIZE - PV_LOCK_SIZE);
158 	for (;;) {
159 		mtx_lock_flags(PV_LOCKPTR(pa), MTX_DUPOK);
160 		if (pa == pa_end)
161 			break;
162 		pa += PV_LOCK_SIZE;
163 	}
164 }
165 
166 static __always_inline void
167 moea64_sp_pv_unlock(vm_paddr_t pa)
168 {
169 	vm_paddr_t pa_end;
170 
171 	/* Note: breaking when pa_end is reached to avoid overflows */
172 	pa_end = pa;
173 	pa += HPT_SP_SIZE - PV_LOCK_SIZE;
174 	for (;;) {
175 		mtx_unlock_flags(PV_LOCKPTR(pa), MTX_DUPOK);
176 		if (pa == pa_end)
177 			break;
178 		pa -= PV_LOCK_SIZE;
179 	}
180 }
181 
182 #define	SP_PV_LOCK_ALIGNED(pa)		moea64_sp_pv_lock(pa)
183 #define	SP_PV_UNLOCK_ALIGNED(pa)	moea64_sp_pv_unlock(pa)
184 #define	SP_PV_LOCK(pa)			moea64_sp_pv_lock((pa) & ~HPT_SP_MASK)
185 #define	SP_PV_UNLOCK(pa)		moea64_sp_pv_unlock((pa) & ~HPT_SP_MASK)
186 #define	SP_PV_PAGE_LOCK(m)		SP_PV_LOCK(VM_PAGE_TO_PHYS(m))
187 #define	SP_PV_PAGE_UNLOCK(m)		SP_PV_UNLOCK(VM_PAGE_TO_PHYS(m))
188 
189 struct ofw_map {
190 	cell_t	om_va;
191 	cell_t	om_len;
192 	uint64_t om_pa;
193 	cell_t	om_mode;
194 };
195 
196 extern unsigned char _etext[];
197 extern unsigned char _end[];
198 
199 extern void *slbtrap, *slbtrapend;
200 
201 /*
202  * Map of physical memory regions.
203  */
204 static struct	mem_region *regions;
205 static struct	mem_region *pregions;
206 static struct	numa_mem_region *numa_pregions;
207 static u_int	phys_avail_count;
208 static int	regions_sz, pregions_sz, numapregions_sz;
209 
210 extern void bs_remap_earlyboot(void);
211 
212 /*
213  * Lock for the SLB tables.
214  */
215 struct mtx	moea64_slb_mutex;
216 
217 /*
218  * PTEG data.
219  */
220 u_long		moea64_pteg_count;
221 u_long		moea64_pteg_mask;
222 
223 /*
224  * PVO data.
225  */
226 
227 uma_zone_t	moea64_pvo_zone; /* zone for pvo entries */
228 
229 static struct	pvo_entry *moea64_bpvo_pool;
230 static int	moea64_bpvo_pool_index = 0;
231 static int	moea64_bpvo_pool_size = 0;
232 SYSCTL_INT(_machdep, OID_AUTO, moea64_allocated_bpvo_entries, CTLFLAG_RD,
233     &moea64_bpvo_pool_index, 0, "");
234 
235 #define	BPVO_POOL_SIZE	327680 /* Sensible historical default value */
236 #define	BPVO_POOL_EXPANSION_FACTOR	3
237 #define	VSID_NBPW	(sizeof(u_int32_t) * 8)
238 #ifdef __powerpc64__
239 #define	NVSIDS		(NPMAPS * 16)
240 #define VSID_HASHMASK	0xffffffffUL
241 #else
242 #define NVSIDS		NPMAPS
243 #define VSID_HASHMASK	0xfffffUL
244 #endif
245 static u_int	moea64_vsid_bitmap[NVSIDS / VSID_NBPW];
246 
247 static boolean_t moea64_initialized = FALSE;
248 
249 #ifdef MOEA64_STATS
250 /*
251  * Statistics.
252  */
253 u_int	moea64_pte_valid = 0;
254 u_int	moea64_pte_overflow = 0;
255 u_int	moea64_pvo_entries = 0;
256 u_int	moea64_pvo_enter_calls = 0;
257 u_int	moea64_pvo_remove_calls = 0;
258 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_valid, CTLFLAG_RD,
259     &moea64_pte_valid, 0, "");
260 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_overflow, CTLFLAG_RD,
261     &moea64_pte_overflow, 0, "");
262 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_entries, CTLFLAG_RD,
263     &moea64_pvo_entries, 0, "");
264 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_enter_calls, CTLFLAG_RD,
265     &moea64_pvo_enter_calls, 0, "");
266 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_remove_calls, CTLFLAG_RD,
267     &moea64_pvo_remove_calls, 0, "");
268 #endif
269 
270 vm_offset_t	moea64_scratchpage_va[2];
271 struct pvo_entry *moea64_scratchpage_pvo[2];
272 struct	mtx	moea64_scratchpage_mtx;
273 
274 uint64_t 	moea64_large_page_mask = 0;
275 uint64_t	moea64_large_page_size = 0;
276 int		moea64_large_page_shift = 0;
277 bool		moea64_has_lp_4k_16m = false;
278 
279 /*
280  * PVO calls.
281  */
282 static int	moea64_pvo_enter(struct pvo_entry *pvo,
283 		    struct pvo_head *pvo_head, struct pvo_entry **oldpvo);
284 static void	moea64_pvo_remove_from_pmap(struct pvo_entry *pvo);
285 static void	moea64_pvo_remove_from_page(struct pvo_entry *pvo);
286 static void	moea64_pvo_remove_from_page_locked(
287 		    struct pvo_entry *pvo, vm_page_t m);
288 static struct	pvo_entry *moea64_pvo_find_va(pmap_t, vm_offset_t);
289 
290 /*
291  * Utility routines.
292  */
293 static boolean_t	moea64_query_bit(vm_page_t, uint64_t);
294 static u_int		moea64_clear_bit(vm_page_t, uint64_t);
295 static void		moea64_kremove(vm_offset_t);
296 static void		moea64_syncicache(pmap_t pmap, vm_offset_t va,
297 			    vm_paddr_t pa, vm_size_t sz);
298 static void		moea64_pmap_init_qpages(void);
299 static void		moea64_remove_locked(pmap_t, vm_offset_t,
300 			    vm_offset_t, struct pvo_dlist *);
301 
302 /*
303  * Superpages data and routines.
304  */
305 
306 /*
307  * PVO flags (in vaddr) that must match for promotion to succeed.
308  * Note that protection bits are checked separately, as they reside in
309  * another field.
310  */
311 #define	PVO_FLAGS_PROMOTE	(PVO_WIRED | PVO_MANAGED | PVO_PTEGIDX_VALID)
312 
313 #define	PVO_IS_SP(pvo)		(((pvo)->pvo_vaddr & PVO_LARGE) && \
314 				 (pvo)->pvo_pmap != kernel_pmap)
315 
316 /* Get physical address from PVO. */
317 #define	PVO_PADDR(pvo)		moea64_pvo_paddr(pvo)
318 
319 /* MD page flag indicating that the page is a superpage. */
320 #define	MDPG_ATTR_SP		0x40000000
321 
322 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0,
323     "VM/pmap parameters");
324 
325 static int superpages_enabled = 0;
326 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled, CTLFLAG_RDTUN,
327     &superpages_enabled, 0, "Enable support for transparent superpages");
328 
329 static SYSCTL_NODE(_vm_pmap, OID_AUTO, sp, CTLFLAG_RD, 0,
330     "SP page mapping counters");
331 
332 static u_long sp_demotions;
333 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, demotions, CTLFLAG_RD,
334     &sp_demotions, 0, "SP page demotions");
335 
336 static u_long sp_mappings;
337 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, mappings, CTLFLAG_RD,
338     &sp_mappings, 0, "SP page mappings");
339 
340 static u_long sp_p_failures;
341 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, p_failures, CTLFLAG_RD,
342     &sp_p_failures, 0, "SP page promotion failures");
343 
344 static u_long sp_p_fail_pa;
345 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, p_fail_pa, CTLFLAG_RD,
346     &sp_p_fail_pa, 0, "SP page promotion failure: PAs don't match");
347 
348 static u_long sp_p_fail_flags;
349 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, p_fail_flags, CTLFLAG_RD,
350     &sp_p_fail_flags, 0, "SP page promotion failure: page flags don't match");
351 
352 static u_long sp_p_fail_prot;
353 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, p_fail_prot, CTLFLAG_RD,
354     &sp_p_fail_prot, 0,
355     "SP page promotion failure: page protections don't match");
356 
357 static u_long sp_p_fail_wimg;
358 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, p_fail_wimg, CTLFLAG_RD,
359     &sp_p_fail_wimg, 0, "SP page promotion failure: WIMG bits don't match");
360 
361 static u_long sp_promotions;
362 SYSCTL_ULONG(_vm_pmap_sp, OID_AUTO, promotions, CTLFLAG_RD,
363     &sp_promotions, 0, "SP page promotions");
364 
365 static bool moea64_ps_enabled(pmap_t);
366 static void moea64_align_superpage(vm_object_t, vm_ooffset_t,
367     vm_offset_t *, vm_size_t);
368 
369 static int moea64_sp_enter(pmap_t pmap, vm_offset_t va,
370     vm_page_t m, vm_prot_t prot, u_int flags, int8_t psind);
371 static struct pvo_entry *moea64_sp_remove(struct pvo_entry *sp,
372     struct pvo_dlist *tofree);
373 
374 static void moea64_sp_promote(pmap_t pmap, vm_offset_t va, vm_page_t m);
375 static void moea64_sp_demote_aligned(struct pvo_entry *sp);
376 static void moea64_sp_demote(struct pvo_entry *pvo);
377 
378 static struct pvo_entry *moea64_sp_unwire(struct pvo_entry *sp);
379 static struct pvo_entry *moea64_sp_protect(struct pvo_entry *sp,
380     vm_prot_t prot);
381 
382 static int64_t moea64_sp_query(struct pvo_entry *pvo, uint64_t ptebit);
383 static int64_t moea64_sp_clear(struct pvo_entry *pvo, vm_page_t m,
384     uint64_t ptebit);
385 
386 static __inline bool moea64_sp_pvo_in_range(struct pvo_entry *pvo,
387     vm_offset_t sva, vm_offset_t eva);
388 
389 /*
390  * Kernel MMU interface
391  */
392 void moea64_clear_modify(vm_page_t);
393 void moea64_copy_page(vm_page_t, vm_page_t);
394 void moea64_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
395     vm_page_t *mb, vm_offset_t b_offset, int xfersize);
396 int moea64_enter(pmap_t, vm_offset_t, vm_page_t, vm_prot_t,
397     u_int flags, int8_t psind);
398 void moea64_enter_object(pmap_t, vm_offset_t, vm_offset_t, vm_page_t,
399     vm_prot_t);
400 void moea64_enter_quick(pmap_t, vm_offset_t, vm_page_t, vm_prot_t);
401 vm_paddr_t moea64_extract(pmap_t, vm_offset_t);
402 vm_page_t moea64_extract_and_hold(pmap_t, vm_offset_t, vm_prot_t);
403 void moea64_init(void);
404 boolean_t moea64_is_modified(vm_page_t);
405 boolean_t moea64_is_prefaultable(pmap_t, vm_offset_t);
406 boolean_t moea64_is_referenced(vm_page_t);
407 int moea64_ts_referenced(vm_page_t);
408 vm_offset_t moea64_map(vm_offset_t *, vm_paddr_t, vm_paddr_t, int);
409 boolean_t moea64_page_exists_quick(pmap_t, vm_page_t);
410 void moea64_page_init(vm_page_t);
411 int moea64_page_wired_mappings(vm_page_t);
412 int moea64_pinit(pmap_t);
413 void moea64_pinit0(pmap_t);
414 void moea64_protect(pmap_t, vm_offset_t, vm_offset_t, vm_prot_t);
415 void moea64_qenter(vm_offset_t, vm_page_t *, int);
416 void moea64_qremove(vm_offset_t, int);
417 void moea64_release(pmap_t);
418 void moea64_remove(pmap_t, vm_offset_t, vm_offset_t);
419 void moea64_remove_pages(pmap_t);
420 void moea64_remove_all(vm_page_t);
421 void moea64_remove_write(vm_page_t);
422 void moea64_unwire(pmap_t, vm_offset_t, vm_offset_t);
423 void moea64_zero_page(vm_page_t);
424 void moea64_zero_page_area(vm_page_t, int, int);
425 void moea64_activate(struct thread *);
426 void moea64_deactivate(struct thread *);
427 void *moea64_mapdev(vm_paddr_t, vm_size_t);
428 void *moea64_mapdev_attr(vm_paddr_t, vm_size_t, vm_memattr_t);
429 void moea64_unmapdev(vm_offset_t, vm_size_t);
430 vm_paddr_t moea64_kextract(vm_offset_t);
431 void moea64_page_set_memattr(vm_page_t m, vm_memattr_t ma);
432 void moea64_kenter_attr(vm_offset_t, vm_paddr_t, vm_memattr_t ma);
433 void moea64_kenter(vm_offset_t, vm_paddr_t);
434 boolean_t moea64_dev_direct_mapped(vm_paddr_t, vm_size_t);
435 static void moea64_sync_icache(pmap_t, vm_offset_t, vm_size_t);
436 void moea64_dumpsys_map(vm_paddr_t pa, size_t sz,
437     void **va);
438 void moea64_scan_init(void);
439 vm_offset_t moea64_quick_enter_page(vm_page_t m);
440 void moea64_quick_remove_page(vm_offset_t addr);
441 boolean_t moea64_page_is_mapped(vm_page_t m);
442 static int moea64_map_user_ptr(pmap_t pm,
443     volatile const void *uaddr, void **kaddr, size_t ulen, size_t *klen);
444 static int moea64_decode_kernel_ptr(vm_offset_t addr,
445     int *is_user, vm_offset_t *decoded_addr);
446 static size_t moea64_scan_pmap(void);
447 static void *moea64_dump_pmap_init(unsigned blkpgs);
448 #ifdef __powerpc64__
449 static void moea64_page_array_startup(long);
450 #endif
451 static int moea64_mincore(pmap_t, vm_offset_t, vm_paddr_t *);
452 
453 static struct pmap_funcs moea64_methods = {
454 	.clear_modify = moea64_clear_modify,
455 	.copy_page = moea64_copy_page,
456 	.copy_pages = moea64_copy_pages,
457 	.enter = moea64_enter,
458 	.enter_object = moea64_enter_object,
459 	.enter_quick = moea64_enter_quick,
460 	.extract = moea64_extract,
461 	.extract_and_hold = moea64_extract_and_hold,
462 	.init = moea64_init,
463 	.is_modified = moea64_is_modified,
464 	.is_prefaultable = moea64_is_prefaultable,
465 	.is_referenced = moea64_is_referenced,
466 	.ts_referenced = moea64_ts_referenced,
467 	.map =      		moea64_map,
468 	.mincore = moea64_mincore,
469 	.page_exists_quick = moea64_page_exists_quick,
470 	.page_init = moea64_page_init,
471 	.page_wired_mappings = moea64_page_wired_mappings,
472 	.pinit = moea64_pinit,
473 	.pinit0 = moea64_pinit0,
474 	.protect = moea64_protect,
475 	.qenter = moea64_qenter,
476 	.qremove = moea64_qremove,
477 	.release = moea64_release,
478 	.remove = moea64_remove,
479 	.remove_pages = moea64_remove_pages,
480 	.remove_all =       	moea64_remove_all,
481 	.remove_write = moea64_remove_write,
482 	.sync_icache = moea64_sync_icache,
483 	.unwire = moea64_unwire,
484 	.zero_page =        	moea64_zero_page,
485 	.zero_page_area = moea64_zero_page_area,
486 	.activate = moea64_activate,
487 	.deactivate =       	moea64_deactivate,
488 	.page_set_memattr = moea64_page_set_memattr,
489 	.quick_enter_page =  moea64_quick_enter_page,
490 	.quick_remove_page =  moea64_quick_remove_page,
491 	.page_is_mapped = moea64_page_is_mapped,
492 #ifdef __powerpc64__
493 	.page_array_startup = moea64_page_array_startup,
494 #endif
495 	.ps_enabled = moea64_ps_enabled,
496 	.align_superpage = moea64_align_superpage,
497 
498 	/* Internal interfaces */
499 	.mapdev = moea64_mapdev,
500 	.mapdev_attr = moea64_mapdev_attr,
501 	.unmapdev = moea64_unmapdev,
502 	.kextract = moea64_kextract,
503 	.kenter = moea64_kenter,
504 	.kenter_attr = moea64_kenter_attr,
505 	.dev_direct_mapped = moea64_dev_direct_mapped,
506 	.dumpsys_pa_init = moea64_scan_init,
507 	.dumpsys_scan_pmap = moea64_scan_pmap,
508 	.dumpsys_dump_pmap_init =    moea64_dump_pmap_init,
509 	.dumpsys_map_chunk = moea64_dumpsys_map,
510 	.map_user_ptr = moea64_map_user_ptr,
511 	.decode_kernel_ptr =  moea64_decode_kernel_ptr,
512 };
513 
514 MMU_DEF(oea64_mmu, "mmu_oea64_base", moea64_methods);
515 
516 /*
517  * Get physical address from PVO.
518  *
519  * For superpages, the lower bits are not stored on pvo_pte.pa and must be
520  * obtained from VA.
521  */
522 static __always_inline vm_paddr_t
523 moea64_pvo_paddr(struct pvo_entry *pvo)
524 {
525 	vm_paddr_t pa;
526 
527 	pa = (pvo)->pvo_pte.pa & LPTE_RPGN;
528 
529 	if (PVO_IS_SP(pvo)) {
530 		pa &= ~HPT_SP_MASK; /* This is needed to clear LPTE_LP bits. */
531 		pa |= PVO_VADDR(pvo) & HPT_SP_MASK;
532 	}
533 	return (pa);
534 }
535 
536 static struct pvo_head *
537 vm_page_to_pvoh(vm_page_t m)
538 {
539 
540 	mtx_assert(PV_LOCKPTR(VM_PAGE_TO_PHYS(m)), MA_OWNED);
541 	return (&m->md.mdpg_pvoh);
542 }
543 
544 static struct pvo_entry *
545 alloc_pvo_entry(int bootstrap)
546 {
547 	struct pvo_entry *pvo;
548 
549 	if (!moea64_initialized || bootstrap) {
550 		if (moea64_bpvo_pool_index >= moea64_bpvo_pool_size) {
551 			panic("%s: bpvo pool exhausted, index=%d, size=%d, bytes=%zd."
552 			    "Try setting machdep.moea64_bpvo_pool_size tunable",
553 			    __func__, moea64_bpvo_pool_index,
554 			    moea64_bpvo_pool_size,
555 			    moea64_bpvo_pool_size * sizeof(struct pvo_entry));
556 		}
557 		pvo = &moea64_bpvo_pool[
558 		    atomic_fetchadd_int(&moea64_bpvo_pool_index, 1)];
559 		bzero(pvo, sizeof(*pvo));
560 		pvo->pvo_vaddr = PVO_BOOTSTRAP;
561 	} else
562 		pvo = uma_zalloc(moea64_pvo_zone, M_NOWAIT | M_ZERO);
563 
564 	return (pvo);
565 }
566 
567 static void
568 init_pvo_entry(struct pvo_entry *pvo, pmap_t pmap, vm_offset_t va)
569 {
570 	uint64_t vsid;
571 	uint64_t hash;
572 	int shift;
573 
574 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
575 
576 	pvo->pvo_pmap = pmap;
577 	va &= ~ADDR_POFF;
578 	pvo->pvo_vaddr |= va;
579 	vsid = va_to_vsid(pmap, va);
580 	pvo->pvo_vpn = (uint64_t)((va & ADDR_PIDX) >> ADDR_PIDX_SHFT)
581 	    | (vsid << 16);
582 
583 	if (pmap == kernel_pmap && (pvo->pvo_vaddr & PVO_LARGE) != 0)
584 		shift = moea64_large_page_shift;
585 	else
586 		shift = ADDR_PIDX_SHFT;
587 	hash = (vsid & VSID_HASH_MASK) ^ (((uint64_t)va & ADDR_PIDX) >> shift);
588 	pvo->pvo_pte.slot = (hash & moea64_pteg_mask) << 3;
589 }
590 
591 static void
592 free_pvo_entry(struct pvo_entry *pvo)
593 {
594 
595 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
596 		uma_zfree(moea64_pvo_zone, pvo);
597 }
598 
599 void
600 moea64_pte_from_pvo(const struct pvo_entry *pvo, struct lpte *lpte)
601 {
602 
603 	lpte->pte_hi = moea64_pte_vpn_from_pvo_vpn(pvo);
604 	lpte->pte_hi |= LPTE_VALID;
605 
606 	if (pvo->pvo_vaddr & PVO_LARGE)
607 		lpte->pte_hi |= LPTE_BIG;
608 	if (pvo->pvo_vaddr & PVO_WIRED)
609 		lpte->pte_hi |= LPTE_WIRED;
610 	if (pvo->pvo_vaddr & PVO_HID)
611 		lpte->pte_hi |= LPTE_HID;
612 
613 	lpte->pte_lo = pvo->pvo_pte.pa; /* Includes WIMG bits */
614 	if (pvo->pvo_pte.prot & VM_PROT_WRITE)
615 		lpte->pte_lo |= LPTE_BW;
616 	else
617 		lpte->pte_lo |= LPTE_BR;
618 
619 	if (!(pvo->pvo_pte.prot & VM_PROT_EXECUTE))
620 		lpte->pte_lo |= LPTE_NOEXEC;
621 }
622 
623 static __inline uint64_t
624 moea64_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
625 {
626 	uint64_t pte_lo;
627 	int i;
628 
629 	if (ma != VM_MEMATTR_DEFAULT) {
630 		switch (ma) {
631 		case VM_MEMATTR_UNCACHEABLE:
632 			return (LPTE_I | LPTE_G);
633 		case VM_MEMATTR_CACHEABLE:
634 			return (LPTE_M);
635 		case VM_MEMATTR_WRITE_COMBINING:
636 		case VM_MEMATTR_WRITE_BACK:
637 		case VM_MEMATTR_PREFETCHABLE:
638 			return (LPTE_I);
639 		case VM_MEMATTR_WRITE_THROUGH:
640 			return (LPTE_W | LPTE_M);
641 		}
642 	}
643 
644 	/*
645 	 * Assume the page is cache inhibited and access is guarded unless
646 	 * it's in our available memory array.
647 	 */
648 	pte_lo = LPTE_I | LPTE_G;
649 	for (i = 0; i < pregions_sz; i++) {
650 		if ((pa >= pregions[i].mr_start) &&
651 		    (pa < (pregions[i].mr_start + pregions[i].mr_size))) {
652 			pte_lo &= ~(LPTE_I | LPTE_G);
653 			pte_lo |= LPTE_M;
654 			break;
655 		}
656 	}
657 
658 	return pte_lo;
659 }
660 
661 /*
662  * Quick sort callout for comparing memory regions.
663  */
664 static int	om_cmp(const void *a, const void *b);
665 
666 static int
667 om_cmp(const void *a, const void *b)
668 {
669 	const struct	ofw_map *mapa;
670 	const struct	ofw_map *mapb;
671 
672 	mapa = a;
673 	mapb = b;
674 	if (mapa->om_pa < mapb->om_pa)
675 		return (-1);
676 	else if (mapa->om_pa > mapb->om_pa)
677 		return (1);
678 	else
679 		return (0);
680 }
681 
682 static void
683 moea64_add_ofw_mappings(phandle_t mmu, size_t sz)
684 {
685 	struct ofw_map	translations[sz/(4*sizeof(cell_t))]; /*>= 4 cells per */
686 	pcell_t		acells, trans_cells[sz/sizeof(cell_t)];
687 	struct pvo_entry *pvo;
688 	register_t	msr;
689 	vm_offset_t	off;
690 	vm_paddr_t	pa_base;
691 	int		i, j;
692 
693 	bzero(translations, sz);
694 	OF_getencprop(OF_finddevice("/"), "#address-cells", &acells,
695 	    sizeof(acells));
696 	if (OF_getencprop(mmu, "translations", trans_cells, sz) == -1)
697 		panic("moea64_bootstrap: can't get ofw translations");
698 
699 	CTR0(KTR_PMAP, "moea64_add_ofw_mappings: translations");
700 	sz /= sizeof(cell_t);
701 	for (i = 0, j = 0; i < sz; j++) {
702 		translations[j].om_va = trans_cells[i++];
703 		translations[j].om_len = trans_cells[i++];
704 		translations[j].om_pa = trans_cells[i++];
705 		if (acells == 2) {
706 			translations[j].om_pa <<= 32;
707 			translations[j].om_pa |= trans_cells[i++];
708 		}
709 		translations[j].om_mode = trans_cells[i++];
710 	}
711 	KASSERT(i == sz, ("Translations map has incorrect cell count (%d/%zd)",
712 	    i, sz));
713 
714 	sz = j;
715 	qsort(translations, sz, sizeof (*translations), om_cmp);
716 
717 	for (i = 0; i < sz; i++) {
718 		pa_base = translations[i].om_pa;
719 	      #ifndef __powerpc64__
720 		if ((translations[i].om_pa >> 32) != 0)
721 			panic("OFW translations above 32-bit boundary!");
722 	      #endif
723 
724 		if (pa_base % PAGE_SIZE)
725 			panic("OFW translation not page-aligned (phys)!");
726 		if (translations[i].om_va % PAGE_SIZE)
727 			panic("OFW translation not page-aligned (virt)!");
728 
729 		CTR3(KTR_PMAP, "translation: pa=%#zx va=%#x len=%#x",
730 		    pa_base, translations[i].om_va, translations[i].om_len);
731 
732 		/* Now enter the pages for this mapping */
733 
734 		DISABLE_TRANS(msr);
735 		for (off = 0; off < translations[i].om_len; off += PAGE_SIZE) {
736 			/* If this address is direct-mapped, skip remapping */
737 			if (hw_direct_map &&
738 			    translations[i].om_va == PHYS_TO_DMAP(pa_base) &&
739 			    moea64_calc_wimg(pa_base + off, VM_MEMATTR_DEFAULT)
740  			    == LPTE_M)
741 				continue;
742 
743 			PMAP_LOCK(kernel_pmap);
744 			pvo = moea64_pvo_find_va(kernel_pmap,
745 			    translations[i].om_va + off);
746 			PMAP_UNLOCK(kernel_pmap);
747 			if (pvo != NULL)
748 				continue;
749 
750 			moea64_kenter(translations[i].om_va + off,
751 			    pa_base + off);
752 		}
753 		ENABLE_TRANS(msr);
754 	}
755 }
756 
757 #ifdef __powerpc64__
758 static void
759 moea64_probe_large_page(void)
760 {
761 	uint16_t pvr = mfpvr() >> 16;
762 
763 	switch (pvr) {
764 	case IBM970:
765 	case IBM970FX:
766 	case IBM970MP:
767 		powerpc_sync(); isync();
768 		mtspr(SPR_HID4, mfspr(SPR_HID4) & ~HID4_970_DISABLE_LG_PG);
769 		powerpc_sync(); isync();
770 
771 		/* FALLTHROUGH */
772 	default:
773 		if (moea64_large_page_size == 0) {
774 			moea64_large_page_size = 0x1000000; /* 16 MB */
775 			moea64_large_page_shift = 24;
776 		}
777 	}
778 
779 	moea64_large_page_mask = moea64_large_page_size - 1;
780 }
781 
782 static void
783 moea64_bootstrap_slb_prefault(vm_offset_t va, int large)
784 {
785 	struct slb *cache;
786 	struct slb entry;
787 	uint64_t esid, slbe;
788 	uint64_t i;
789 
790 	cache = PCPU_GET(aim.slb);
791 	esid = va >> ADDR_SR_SHFT;
792 	slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
793 
794 	for (i = 0; i < 64; i++) {
795 		if (cache[i].slbe == (slbe | i))
796 			return;
797 	}
798 
799 	entry.slbe = slbe;
800 	entry.slbv = KERNEL_VSID(esid) << SLBV_VSID_SHIFT;
801 	if (large)
802 		entry.slbv |= SLBV_L;
803 
804 	slb_insert_kernel(entry.slbe, entry.slbv);
805 }
806 #endif
807 
808 static int
809 moea64_kenter_large(vm_offset_t va, vm_paddr_t pa, uint64_t attr, int bootstrap)
810 {
811 	struct pvo_entry *pvo;
812 	uint64_t pte_lo;
813 	int error;
814 
815 	pte_lo = LPTE_M;
816 	pte_lo |= attr;
817 
818 	pvo = alloc_pvo_entry(bootstrap);
819 	pvo->pvo_vaddr |= PVO_WIRED | PVO_LARGE;
820 	init_pvo_entry(pvo, kernel_pmap, va);
821 
822 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE |
823 	    VM_PROT_EXECUTE;
824 	pvo->pvo_pte.pa = pa | pte_lo;
825 	error = moea64_pvo_enter(pvo, NULL, NULL);
826 	if (error != 0)
827 		panic("Error %d inserting large page\n", error);
828 	return (0);
829 }
830 
831 static void
832 moea64_setup_direct_map(vm_offset_t kernelstart,
833     vm_offset_t kernelend)
834 {
835 	register_t msr;
836 	vm_paddr_t pa, pkernelstart, pkernelend;
837 	vm_offset_t size, off;
838 	uint64_t pte_lo;
839 	int i;
840 
841 	if (moea64_large_page_size == 0)
842 		hw_direct_map = 0;
843 
844 	DISABLE_TRANS(msr);
845 	if (hw_direct_map) {
846 		PMAP_LOCK(kernel_pmap);
847 		for (i = 0; i < pregions_sz; i++) {
848 		  for (pa = pregions[i].mr_start; pa < pregions[i].mr_start +
849 		     pregions[i].mr_size; pa += moea64_large_page_size) {
850 			pte_lo = LPTE_M;
851 			if (pa & moea64_large_page_mask) {
852 				pa &= moea64_large_page_mask;
853 				pte_lo |= LPTE_G;
854 			}
855 			if (pa + moea64_large_page_size >
856 			    pregions[i].mr_start + pregions[i].mr_size)
857 				pte_lo |= LPTE_G;
858 
859 			moea64_kenter_large(PHYS_TO_DMAP(pa), pa, pte_lo, 1);
860 		  }
861 		}
862 		PMAP_UNLOCK(kernel_pmap);
863 	}
864 
865 	/*
866 	 * Make sure the kernel and BPVO pool stay mapped on systems either
867 	 * without a direct map or on which the kernel is not already executing
868 	 * out of the direct-mapped region.
869 	 */
870 	if (kernelstart < DMAP_BASE_ADDRESS) {
871 		/*
872 		 * For pre-dmap execution, we need to use identity mapping
873 		 * because we will be operating with the mmu on but in the
874 		 * wrong address configuration until we __restartkernel().
875 		 */
876 		for (pa = kernelstart & ~PAGE_MASK; pa < kernelend;
877 		    pa += PAGE_SIZE)
878 			moea64_kenter(pa, pa);
879 	} else if (!hw_direct_map) {
880 		pkernelstart = kernelstart & ~DMAP_BASE_ADDRESS;
881 		pkernelend = kernelend & ~DMAP_BASE_ADDRESS;
882 		for (pa = pkernelstart & ~PAGE_MASK; pa < pkernelend;
883 		    pa += PAGE_SIZE)
884 			moea64_kenter(pa | DMAP_BASE_ADDRESS, pa);
885 	}
886 
887 	if (!hw_direct_map) {
888 		size = moea64_bpvo_pool_size*sizeof(struct pvo_entry);
889 		off = (vm_offset_t)(moea64_bpvo_pool);
890 		for (pa = off; pa < off + size; pa += PAGE_SIZE)
891 			moea64_kenter(pa, pa);
892 
893 		/* Map exception vectors */
894 		for (pa = EXC_RSVD; pa < EXC_LAST; pa += PAGE_SIZE)
895 			moea64_kenter(pa | DMAP_BASE_ADDRESS, pa);
896 	}
897 	ENABLE_TRANS(msr);
898 
899 	/*
900 	 * Allow user to override unmapped_buf_allowed for testing.
901 	 * XXXKIB Only direct map implementation was tested.
902 	 */
903 	if (!TUNABLE_INT_FETCH("vfs.unmapped_buf_allowed",
904 	    &unmapped_buf_allowed))
905 		unmapped_buf_allowed = hw_direct_map;
906 }
907 
908 /* Quick sort callout for comparing physical addresses. */
909 static int
910 pa_cmp(const void *a, const void *b)
911 {
912 	const vm_paddr_t *pa = a, *pb = b;
913 
914 	if (*pa < *pb)
915 		return (-1);
916 	else if (*pa > *pb)
917 		return (1);
918 	else
919 		return (0);
920 }
921 
922 void
923 moea64_early_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
924 {
925 	int		i, j;
926 	vm_size_t	physsz, hwphyssz;
927 	vm_paddr_t	kernelphysstart, kernelphysend;
928 	int		rm_pavail;
929 
930 	/* Level 0 reservations consist of 4096 pages (16MB superpage). */
931 	vm_level_0_order = 12;
932 
933 #ifndef __powerpc64__
934 	/* We don't have a direct map since there is no BAT */
935 	hw_direct_map = 0;
936 
937 	/* Make sure battable is zero, since we have no BAT */
938 	for (i = 0; i < 16; i++) {
939 		battable[i].batu = 0;
940 		battable[i].batl = 0;
941 	}
942 #else
943 	moea64_probe_large_page();
944 
945 	/* Use a direct map if we have large page support */
946 	if (moea64_large_page_size > 0)
947 		hw_direct_map = 1;
948 	else
949 		hw_direct_map = 0;
950 
951 	/* Install trap handlers for SLBs */
952 	bcopy(&slbtrap, (void *)EXC_DSE,(size_t)&slbtrapend - (size_t)&slbtrap);
953 	bcopy(&slbtrap, (void *)EXC_ISE,(size_t)&slbtrapend - (size_t)&slbtrap);
954 	__syncicache((void *)EXC_DSE, 0x80);
955 	__syncicache((void *)EXC_ISE, 0x80);
956 #endif
957 
958 	kernelphysstart = kernelstart & ~DMAP_BASE_ADDRESS;
959 	kernelphysend = kernelend & ~DMAP_BASE_ADDRESS;
960 
961 	/* Get physical memory regions from firmware */
962 	mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
963 	CTR0(KTR_PMAP, "moea64_bootstrap: physical memory");
964 
965 	if (PHYS_AVAIL_ENTRIES < regions_sz)
966 		panic("moea64_bootstrap: phys_avail too small");
967 
968 	phys_avail_count = 0;
969 	physsz = 0;
970 	hwphyssz = 0;
971 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
972 	for (i = 0, j = 0; i < regions_sz; i++, j += 2) {
973 		CTR3(KTR_PMAP, "region: %#zx - %#zx (%#zx)",
974 		    regions[i].mr_start, regions[i].mr_start +
975 		    regions[i].mr_size, regions[i].mr_size);
976 		if (hwphyssz != 0 &&
977 		    (physsz + regions[i].mr_size) >= hwphyssz) {
978 			if (physsz < hwphyssz) {
979 				phys_avail[j] = regions[i].mr_start;
980 				phys_avail[j + 1] = regions[i].mr_start +
981 				    hwphyssz - physsz;
982 				physsz = hwphyssz;
983 				phys_avail_count++;
984 				dump_avail[j] = phys_avail[j];
985 				dump_avail[j + 1] = phys_avail[j + 1];
986 			}
987 			break;
988 		}
989 		phys_avail[j] = regions[i].mr_start;
990 		phys_avail[j + 1] = regions[i].mr_start + regions[i].mr_size;
991 		phys_avail_count++;
992 		physsz += regions[i].mr_size;
993 		dump_avail[j] = phys_avail[j];
994 		dump_avail[j + 1] = phys_avail[j + 1];
995 	}
996 
997 	/* Check for overlap with the kernel and exception vectors */
998 	rm_pavail = 0;
999 	for (j = 0; j < 2*phys_avail_count; j+=2) {
1000 		if (phys_avail[j] < EXC_LAST)
1001 			phys_avail[j] += EXC_LAST;
1002 
1003 		if (phys_avail[j] >= kernelphysstart &&
1004 		    phys_avail[j+1] <= kernelphysend) {
1005 			phys_avail[j] = phys_avail[j+1] = ~0;
1006 			rm_pavail++;
1007 			continue;
1008 		}
1009 
1010 		if (kernelphysstart >= phys_avail[j] &&
1011 		    kernelphysstart < phys_avail[j+1]) {
1012 			if (kernelphysend < phys_avail[j+1]) {
1013 				phys_avail[2*phys_avail_count] =
1014 				    (kernelphysend & ~PAGE_MASK) + PAGE_SIZE;
1015 				phys_avail[2*phys_avail_count + 1] =
1016 				    phys_avail[j+1];
1017 				phys_avail_count++;
1018 			}
1019 
1020 			phys_avail[j+1] = kernelphysstart & ~PAGE_MASK;
1021 		}
1022 
1023 		if (kernelphysend >= phys_avail[j] &&
1024 		    kernelphysend < phys_avail[j+1]) {
1025 			if (kernelphysstart > phys_avail[j]) {
1026 				phys_avail[2*phys_avail_count] = phys_avail[j];
1027 				phys_avail[2*phys_avail_count + 1] =
1028 				    kernelphysstart & ~PAGE_MASK;
1029 				phys_avail_count++;
1030 			}
1031 
1032 			phys_avail[j] = (kernelphysend & ~PAGE_MASK) +
1033 			    PAGE_SIZE;
1034 		}
1035 	}
1036 
1037 	/* Remove physical available regions marked for removal (~0) */
1038 	if (rm_pavail) {
1039 		qsort(phys_avail, 2*phys_avail_count, sizeof(phys_avail[0]),
1040 			pa_cmp);
1041 		phys_avail_count -= rm_pavail;
1042 		for (i = 2*phys_avail_count;
1043 		     i < 2*(phys_avail_count + rm_pavail); i+=2)
1044 			phys_avail[i] = phys_avail[i+1] = 0;
1045 	}
1046 
1047 	physmem = btoc(physsz);
1048 
1049 #ifdef PTEGCOUNT
1050 	moea64_pteg_count = PTEGCOUNT;
1051 #else
1052 	moea64_pteg_count = 0x1000;
1053 
1054 	while (moea64_pteg_count < physmem)
1055 		moea64_pteg_count <<= 1;
1056 
1057 	moea64_pteg_count >>= 1;
1058 #endif /* PTEGCOUNT */
1059 }
1060 
1061 void
1062 moea64_mid_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
1063 {
1064 	int		i;
1065 
1066 	/*
1067 	 * Set PTEG mask
1068 	 */
1069 	moea64_pteg_mask = moea64_pteg_count - 1;
1070 
1071 	/*
1072 	 * Initialize SLB table lock and page locks
1073 	 */
1074 	mtx_init(&moea64_slb_mutex, "SLB table", NULL, MTX_DEF);
1075 	for (i = 0; i < PV_LOCK_COUNT; i++)
1076 		mtx_init(&pv_lock[i], "page pv", NULL, MTX_DEF);
1077 
1078 	/*
1079 	 * Initialise the bootstrap pvo pool.
1080 	 */
1081 	TUNABLE_INT_FETCH("machdep.moea64_bpvo_pool_size", &moea64_bpvo_pool_size);
1082 	if (moea64_bpvo_pool_size == 0) {
1083 		if (!hw_direct_map)
1084 			moea64_bpvo_pool_size = ((ptoa((uintmax_t)physmem) * sizeof(struct vm_page)) /
1085 			    (PAGE_SIZE * PAGE_SIZE)) * BPVO_POOL_EXPANSION_FACTOR;
1086 		else
1087 			moea64_bpvo_pool_size = BPVO_POOL_SIZE;
1088 	}
1089 
1090 	if (boothowto & RB_VERBOSE) {
1091 		printf("mmu_oea64: bpvo pool entries = %d, bpvo pool size = %zu MB\n",
1092 		    moea64_bpvo_pool_size,
1093 		    moea64_bpvo_pool_size*sizeof(struct pvo_entry) / 1048576);
1094 	}
1095 
1096 	moea64_bpvo_pool = (struct pvo_entry *)moea64_bootstrap_alloc(
1097 		moea64_bpvo_pool_size*sizeof(struct pvo_entry), PAGE_SIZE);
1098 	moea64_bpvo_pool_index = 0;
1099 
1100 	/* Place at address usable through the direct map */
1101 	if (hw_direct_map)
1102 		moea64_bpvo_pool = (struct pvo_entry *)
1103 		    PHYS_TO_DMAP((uintptr_t)moea64_bpvo_pool);
1104 
1105 	/*
1106 	 * Make sure kernel vsid is allocated as well as VSID 0.
1107 	 */
1108 	#ifndef __powerpc64__
1109 	moea64_vsid_bitmap[(KERNEL_VSIDBITS & (NVSIDS - 1)) / VSID_NBPW]
1110 		|= 1 << (KERNEL_VSIDBITS % VSID_NBPW);
1111 	moea64_vsid_bitmap[0] |= 1;
1112 	#endif
1113 
1114 	/*
1115 	 * Initialize the kernel pmap (which is statically allocated).
1116 	 */
1117 	#ifdef __powerpc64__
1118 	for (i = 0; i < 64; i++) {
1119 		pcpup->pc_aim.slb[i].slbv = 0;
1120 		pcpup->pc_aim.slb[i].slbe = 0;
1121 	}
1122 	#else
1123 	for (i = 0; i < 16; i++)
1124 		kernel_pmap->pm_sr[i] = EMPTY_SEGMENT + i;
1125 	#endif
1126 
1127 	kernel_pmap->pmap_phys = kernel_pmap;
1128 	CPU_FILL(&kernel_pmap->pm_active);
1129 	RB_INIT(&kernel_pmap->pmap_pvo);
1130 
1131 	PMAP_LOCK_INIT(kernel_pmap);
1132 
1133 	/*
1134 	 * Now map in all the other buffers we allocated earlier
1135 	 */
1136 
1137 	moea64_setup_direct_map(kernelstart, kernelend);
1138 }
1139 
1140 void
1141 moea64_late_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
1142 {
1143 	ihandle_t	mmui;
1144 	phandle_t	chosen;
1145 	phandle_t	mmu;
1146 	ssize_t		sz;
1147 	int		i;
1148 	vm_offset_t	pa, va;
1149 	void		*dpcpu;
1150 
1151 	/*
1152 	 * Set up the Open Firmware pmap and add its mappings if not in real
1153 	 * mode.
1154 	 */
1155 
1156 	chosen = OF_finddevice("/chosen");
1157 	if (chosen != -1 && OF_getencprop(chosen, "mmu", &mmui, 4) != -1) {
1158 		mmu = OF_instance_to_package(mmui);
1159 		if (mmu == -1 ||
1160 		    (sz = OF_getproplen(mmu, "translations")) == -1)
1161 			sz = 0;
1162 		if (sz > 6144 /* tmpstksz - 2 KB headroom */)
1163 			panic("moea64_bootstrap: too many ofw translations");
1164 
1165 		if (sz > 0)
1166 			moea64_add_ofw_mappings(mmu, sz);
1167 	}
1168 
1169 	/*
1170 	 * Calculate the last available physical address.
1171 	 */
1172 	Maxmem = 0;
1173 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
1174 		Maxmem = MAX(Maxmem, powerpc_btop(phys_avail[i + 1]));
1175 
1176 	/*
1177 	 * Initialize MMU.
1178 	 */
1179 	pmap_cpu_bootstrap(0);
1180 	mtmsr(mfmsr() | PSL_DR | PSL_IR);
1181 	pmap_bootstrapped++;
1182 
1183 	/*
1184 	 * Set the start and end of kva.
1185 	 */
1186 	virtual_avail = VM_MIN_KERNEL_ADDRESS;
1187 	virtual_end = VM_MAX_SAFE_KERNEL_ADDRESS;
1188 
1189 	/*
1190 	 * Map the entire KVA range into the SLB. We must not fault there.
1191 	 */
1192 	#ifdef __powerpc64__
1193 	for (va = virtual_avail; va < virtual_end; va += SEGMENT_LENGTH)
1194 		moea64_bootstrap_slb_prefault(va, 0);
1195 	#endif
1196 
1197 	/*
1198 	 * Remap any early IO mappings (console framebuffer, etc.)
1199 	 */
1200 	bs_remap_earlyboot();
1201 
1202 	/*
1203 	 * Figure out how far we can extend virtual_end into segment 16
1204 	 * without running into existing mappings. Segment 16 is guaranteed
1205 	 * to contain neither RAM nor devices (at least on Apple hardware),
1206 	 * but will generally contain some OFW mappings we should not
1207 	 * step on.
1208 	 */
1209 
1210 	#ifndef __powerpc64__	/* KVA is in high memory on PPC64 */
1211 	PMAP_LOCK(kernel_pmap);
1212 	while (virtual_end < VM_MAX_KERNEL_ADDRESS &&
1213 	    moea64_pvo_find_va(kernel_pmap, virtual_end+1) == NULL)
1214 		virtual_end += PAGE_SIZE;
1215 	PMAP_UNLOCK(kernel_pmap);
1216 	#endif
1217 
1218 	/*
1219 	 * Allocate a kernel stack with a guard page for thread0 and map it
1220 	 * into the kernel page map.
1221 	 */
1222 	pa = moea64_bootstrap_alloc(kstack_pages * PAGE_SIZE, PAGE_SIZE);
1223 	va = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
1224 	virtual_avail = va + kstack_pages * PAGE_SIZE;
1225 	CTR2(KTR_PMAP, "moea64_bootstrap: kstack0 at %#x (%#x)", pa, va);
1226 	thread0.td_kstack = va;
1227 	thread0.td_kstack_pages = kstack_pages;
1228 	for (i = 0; i < kstack_pages; i++) {
1229 		moea64_kenter(va, pa);
1230 		pa += PAGE_SIZE;
1231 		va += PAGE_SIZE;
1232 	}
1233 
1234 	/*
1235 	 * Allocate virtual address space for the message buffer.
1236 	 */
1237 	pa = msgbuf_phys = moea64_bootstrap_alloc(msgbufsize, PAGE_SIZE);
1238 	msgbufp = (struct msgbuf *)virtual_avail;
1239 	va = virtual_avail;
1240 	virtual_avail += round_page(msgbufsize);
1241 	while (va < virtual_avail) {
1242 		moea64_kenter(va, pa);
1243 		pa += PAGE_SIZE;
1244 		va += PAGE_SIZE;
1245 	}
1246 
1247 	/*
1248 	 * Allocate virtual address space for the dynamic percpu area.
1249 	 */
1250 	pa = moea64_bootstrap_alloc(DPCPU_SIZE, PAGE_SIZE);
1251 	dpcpu = (void *)virtual_avail;
1252 	va = virtual_avail;
1253 	virtual_avail += DPCPU_SIZE;
1254 	while (va < virtual_avail) {
1255 		moea64_kenter(va, pa);
1256 		pa += PAGE_SIZE;
1257 		va += PAGE_SIZE;
1258 	}
1259 	dpcpu_init(dpcpu, curcpu);
1260 
1261 	crashdumpmap = (caddr_t)virtual_avail;
1262 	virtual_avail += MAXDUMPPGS * PAGE_SIZE;
1263 
1264 	/*
1265 	 * Allocate some things for page zeroing. We put this directly
1266 	 * in the page table and use MOEA64_PTE_REPLACE to avoid any
1267 	 * of the PVO book-keeping or other parts of the VM system
1268 	 * from even knowing that this hack exists.
1269 	 */
1270 
1271 	if (!hw_direct_map) {
1272 		mtx_init(&moea64_scratchpage_mtx, "pvo zero page", NULL,
1273 		    MTX_DEF);
1274 		for (i = 0; i < 2; i++) {
1275 			moea64_scratchpage_va[i] = (virtual_end+1) - PAGE_SIZE;
1276 			virtual_end -= PAGE_SIZE;
1277 
1278 			moea64_kenter(moea64_scratchpage_va[i], 0);
1279 
1280 			PMAP_LOCK(kernel_pmap);
1281 			moea64_scratchpage_pvo[i] = moea64_pvo_find_va(
1282 			    kernel_pmap, (vm_offset_t)moea64_scratchpage_va[i]);
1283 			PMAP_UNLOCK(kernel_pmap);
1284 		}
1285 	}
1286 
1287 	numa_mem_regions(&numa_pregions, &numapregions_sz);
1288 }
1289 
1290 static void
1291 moea64_pmap_init_qpages(void)
1292 {
1293 	struct pcpu *pc;
1294 	int i;
1295 
1296 	if (hw_direct_map)
1297 		return;
1298 
1299 	CPU_FOREACH(i) {
1300 		pc = pcpu_find(i);
1301 		pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
1302 		if (pc->pc_qmap_addr == 0)
1303 			panic("pmap_init_qpages: unable to allocate KVA");
1304 		PMAP_LOCK(kernel_pmap);
1305 		pc->pc_aim.qmap_pvo =
1306 		    moea64_pvo_find_va(kernel_pmap, pc->pc_qmap_addr);
1307 		PMAP_UNLOCK(kernel_pmap);
1308 		mtx_init(&pc->pc_aim.qmap_lock, "qmap lock", NULL, MTX_DEF);
1309 	}
1310 }
1311 
1312 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, moea64_pmap_init_qpages, NULL);
1313 
1314 /*
1315  * Activate a user pmap.  This mostly involves setting some non-CPU
1316  * state.
1317  */
1318 void
1319 moea64_activate(struct thread *td)
1320 {
1321 	pmap_t	pm;
1322 
1323 	pm = &td->td_proc->p_vmspace->vm_pmap;
1324 	CPU_SET(PCPU_GET(cpuid), &pm->pm_active);
1325 
1326 	#ifdef __powerpc64__
1327 	PCPU_SET(aim.userslb, pm->pm_slb);
1328 	__asm __volatile("slbmte %0, %1; isync" ::
1329 	    "r"(td->td_pcb->pcb_cpu.aim.usr_vsid), "r"(USER_SLB_SLBE));
1330 	#else
1331 	PCPU_SET(curpmap, pm->pmap_phys);
1332 	mtsrin(USER_SR << ADDR_SR_SHFT, td->td_pcb->pcb_cpu.aim.usr_vsid);
1333 	#endif
1334 }
1335 
1336 void
1337 moea64_deactivate(struct thread *td)
1338 {
1339 	pmap_t	pm;
1340 
1341 	__asm __volatile("isync; slbie %0" :: "r"(USER_ADDR));
1342 
1343 	pm = &td->td_proc->p_vmspace->vm_pmap;
1344 	CPU_CLR(PCPU_GET(cpuid), &pm->pm_active);
1345 	#ifdef __powerpc64__
1346 	PCPU_SET(aim.userslb, NULL);
1347 	#else
1348 	PCPU_SET(curpmap, NULL);
1349 	#endif
1350 }
1351 
1352 void
1353 moea64_unwire(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1354 {
1355 	struct	pvo_entry key, *pvo;
1356 	vm_page_t m;
1357 	int64_t	refchg;
1358 
1359 	key.pvo_vaddr = sva;
1360 	PMAP_LOCK(pm);
1361 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1362 	    pvo != NULL && PVO_VADDR(pvo) < eva;
1363 	    pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
1364 		if (PVO_IS_SP(pvo)) {
1365 			if (moea64_sp_pvo_in_range(pvo, sva, eva)) {
1366 				pvo = moea64_sp_unwire(pvo);
1367 				continue;
1368 			} else {
1369 				CTR1(KTR_PMAP, "%s: demote before unwire",
1370 				    __func__);
1371 				moea64_sp_demote(pvo);
1372 			}
1373 		}
1374 
1375 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
1376 			panic("moea64_unwire: pvo %p is missing PVO_WIRED",
1377 			    pvo);
1378 		pvo->pvo_vaddr &= ~PVO_WIRED;
1379 		refchg = moea64_pte_replace(pvo, 0 /* No invalidation */);
1380 		if ((pvo->pvo_vaddr & PVO_MANAGED) &&
1381 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1382 			if (refchg < 0)
1383 				refchg = LPTE_CHG;
1384 			m = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
1385 
1386 			refchg |= atomic_readandclear_32(&m->md.mdpg_attrs);
1387 			if (refchg & LPTE_CHG)
1388 				vm_page_dirty(m);
1389 			if (refchg & LPTE_REF)
1390 				vm_page_aflag_set(m, PGA_REFERENCED);
1391 		}
1392 		pm->pm_stats.wired_count--;
1393 	}
1394 	PMAP_UNLOCK(pm);
1395 }
1396 
1397 static int
1398 moea64_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
1399 {
1400 	struct pvo_entry *pvo;
1401 	vm_paddr_t pa;
1402 	vm_page_t m;
1403 	int val;
1404 	bool managed;
1405 
1406 	PMAP_LOCK(pmap);
1407 
1408 	/* XXX Add support for superpages */
1409 	pvo = moea64_pvo_find_va(pmap, addr);
1410 	if (pvo != NULL) {
1411 		pa = PVO_PADDR(pvo);
1412 		m = PHYS_TO_VM_PAGE(pa);
1413 		managed = (pvo->pvo_vaddr & PVO_MANAGED) == PVO_MANAGED;
1414 		val = MINCORE_INCORE;
1415 	} else {
1416 		PMAP_UNLOCK(pmap);
1417 		return (0);
1418 	}
1419 
1420 	PMAP_UNLOCK(pmap);
1421 
1422 	if (m == NULL)
1423 		return (0);
1424 
1425 	if (managed) {
1426 		if (moea64_is_modified(m))
1427 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
1428 
1429 		if (moea64_is_referenced(m))
1430 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
1431 	}
1432 
1433 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
1434 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
1435 	    managed) {
1436 		*pap = pa;
1437 	}
1438 
1439 	return (val);
1440 }
1441 
1442 /*
1443  * This goes through and sets the physical address of our
1444  * special scratch PTE to the PA we want to zero or copy. Because
1445  * of locking issues (this can get called in pvo_enter() by
1446  * the UMA allocator), we can't use most other utility functions here
1447  */
1448 
1449 static __inline
1450 void moea64_set_scratchpage_pa(int which, vm_paddr_t pa)
1451 {
1452 	struct pvo_entry *pvo;
1453 
1454 	KASSERT(!hw_direct_map, ("Using OEA64 scratchpage with a direct map!"));
1455 	mtx_assert(&moea64_scratchpage_mtx, MA_OWNED);
1456 
1457 	pvo = moea64_scratchpage_pvo[which];
1458 	PMAP_LOCK(pvo->pvo_pmap);
1459 	pvo->pvo_pte.pa =
1460 	    moea64_calc_wimg(pa, VM_MEMATTR_DEFAULT) | (uint64_t)pa;
1461 	moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
1462 	PMAP_UNLOCK(pvo->pvo_pmap);
1463 	isync();
1464 }
1465 
1466 void
1467 moea64_copy_page(vm_page_t msrc, vm_page_t mdst)
1468 {
1469 	vm_offset_t	dst;
1470 	vm_offset_t	src;
1471 
1472 	dst = VM_PAGE_TO_PHYS(mdst);
1473 	src = VM_PAGE_TO_PHYS(msrc);
1474 
1475 	if (hw_direct_map) {
1476 		bcopy((void *)PHYS_TO_DMAP(src), (void *)PHYS_TO_DMAP(dst),
1477 		    PAGE_SIZE);
1478 	} else {
1479 		mtx_lock(&moea64_scratchpage_mtx);
1480 
1481 		moea64_set_scratchpage_pa(0, src);
1482 		moea64_set_scratchpage_pa(1, dst);
1483 
1484 		bcopy((void *)moea64_scratchpage_va[0],
1485 		    (void *)moea64_scratchpage_va[1], PAGE_SIZE);
1486 
1487 		mtx_unlock(&moea64_scratchpage_mtx);
1488 	}
1489 }
1490 
1491 static inline void
1492 moea64_copy_pages_dmap(vm_page_t *ma, vm_offset_t a_offset,
1493     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1494 {
1495 	void *a_cp, *b_cp;
1496 	vm_offset_t a_pg_offset, b_pg_offset;
1497 	int cnt;
1498 
1499 	while (xfersize > 0) {
1500 		a_pg_offset = a_offset & PAGE_MASK;
1501 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1502 		a_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
1503 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT])) +
1504 		    a_pg_offset;
1505 		b_pg_offset = b_offset & PAGE_MASK;
1506 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1507 		b_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
1508 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT])) +
1509 		    b_pg_offset;
1510 		bcopy(a_cp, b_cp, cnt);
1511 		a_offset += cnt;
1512 		b_offset += cnt;
1513 		xfersize -= cnt;
1514 	}
1515 }
1516 
1517 static inline void
1518 moea64_copy_pages_nodmap(vm_page_t *ma, vm_offset_t a_offset,
1519     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1520 {
1521 	void *a_cp, *b_cp;
1522 	vm_offset_t a_pg_offset, b_pg_offset;
1523 	int cnt;
1524 
1525 	mtx_lock(&moea64_scratchpage_mtx);
1526 	while (xfersize > 0) {
1527 		a_pg_offset = a_offset & PAGE_MASK;
1528 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1529 		moea64_set_scratchpage_pa(0,
1530 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]));
1531 		a_cp = (char *)moea64_scratchpage_va[0] + a_pg_offset;
1532 		b_pg_offset = b_offset & PAGE_MASK;
1533 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1534 		moea64_set_scratchpage_pa(1,
1535 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]));
1536 		b_cp = (char *)moea64_scratchpage_va[1] + b_pg_offset;
1537 		bcopy(a_cp, b_cp, cnt);
1538 		a_offset += cnt;
1539 		b_offset += cnt;
1540 		xfersize -= cnt;
1541 	}
1542 	mtx_unlock(&moea64_scratchpage_mtx);
1543 }
1544 
1545 void
1546 moea64_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
1547     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1548 {
1549 
1550 	if (hw_direct_map) {
1551 		moea64_copy_pages_dmap(ma, a_offset, mb, b_offset,
1552 		    xfersize);
1553 	} else {
1554 		moea64_copy_pages_nodmap(ma, a_offset, mb, b_offset,
1555 		    xfersize);
1556 	}
1557 }
1558 
1559 void
1560 moea64_zero_page_area(vm_page_t m, int off, int size)
1561 {
1562 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1563 
1564 	if (size + off > PAGE_SIZE)
1565 		panic("moea64_zero_page: size + off > PAGE_SIZE");
1566 
1567 	if (hw_direct_map) {
1568 		bzero((caddr_t)(uintptr_t)PHYS_TO_DMAP(pa) + off, size);
1569 	} else {
1570 		mtx_lock(&moea64_scratchpage_mtx);
1571 		moea64_set_scratchpage_pa(0, pa);
1572 		bzero((caddr_t)moea64_scratchpage_va[0] + off, size);
1573 		mtx_unlock(&moea64_scratchpage_mtx);
1574 	}
1575 }
1576 
1577 /*
1578  * Zero a page of physical memory by temporarily mapping it
1579  */
1580 void
1581 moea64_zero_page(vm_page_t m)
1582 {
1583 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1584 	vm_offset_t va, off;
1585 
1586 	if (!hw_direct_map) {
1587 		mtx_lock(&moea64_scratchpage_mtx);
1588 
1589 		moea64_set_scratchpage_pa(0, pa);
1590 		va = moea64_scratchpage_va[0];
1591 	} else {
1592 		va = PHYS_TO_DMAP(pa);
1593 	}
1594 
1595 	for (off = 0; off < PAGE_SIZE; off += cacheline_size)
1596 		__asm __volatile("dcbz 0,%0" :: "r"(va + off));
1597 
1598 	if (!hw_direct_map)
1599 		mtx_unlock(&moea64_scratchpage_mtx);
1600 }
1601 
1602 vm_offset_t
1603 moea64_quick_enter_page(vm_page_t m)
1604 {
1605 	struct pvo_entry *pvo;
1606 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1607 
1608 	if (hw_direct_map)
1609 		return (PHYS_TO_DMAP(pa));
1610 
1611 	/*
1612  	 * MOEA64_PTE_REPLACE does some locking, so we can't just grab
1613 	 * a critical section and access the PCPU data like on i386.
1614 	 * Instead, pin the thread and grab the PCPU lock to prevent
1615 	 * a preempting thread from using the same PCPU data.
1616 	 */
1617 	sched_pin();
1618 
1619 	mtx_assert(PCPU_PTR(aim.qmap_lock), MA_NOTOWNED);
1620 	pvo = PCPU_GET(aim.qmap_pvo);
1621 
1622 	mtx_lock(PCPU_PTR(aim.qmap_lock));
1623 	pvo->pvo_pte.pa = moea64_calc_wimg(pa, pmap_page_get_memattr(m)) |
1624 	    (uint64_t)pa;
1625 	moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
1626 	isync();
1627 
1628 	return (PCPU_GET(qmap_addr));
1629 }
1630 
1631 void
1632 moea64_quick_remove_page(vm_offset_t addr)
1633 {
1634 	if (hw_direct_map)
1635 		return;
1636 
1637 	mtx_assert(PCPU_PTR(aim.qmap_lock), MA_OWNED);
1638 	KASSERT(PCPU_GET(qmap_addr) == addr,
1639 	    ("moea64_quick_remove_page: invalid address"));
1640 	mtx_unlock(PCPU_PTR(aim.qmap_lock));
1641 	sched_unpin();
1642 }
1643 
1644 boolean_t
1645 moea64_page_is_mapped(vm_page_t m)
1646 {
1647 	return (!LIST_EMPTY(&(m)->md.mdpg_pvoh));
1648 }
1649 
1650 /*
1651  * Map the given physical page at the specified virtual address in the
1652  * target pmap with the protection requested.  If specified the page
1653  * will be wired down.
1654  */
1655 
1656 int
1657 moea64_enter(pmap_t pmap, vm_offset_t va, vm_page_t m,
1658     vm_prot_t prot, u_int flags, int8_t psind)
1659 {
1660 	struct		pvo_entry *pvo, *oldpvo, *tpvo;
1661 	struct		pvo_head *pvo_head;
1662 	uint64_t	pte_lo;
1663 	int		error;
1664 	vm_paddr_t	pa;
1665 
1666 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1667 		if ((flags & PMAP_ENTER_QUICK_LOCKED) == 0)
1668 			VM_PAGE_OBJECT_BUSY_ASSERT(m);
1669 		else
1670 			VM_OBJECT_ASSERT_LOCKED(m->object);
1671 	}
1672 
1673 	if (psind > 0)
1674 		return (moea64_sp_enter(pmap, va, m, prot, flags, psind));
1675 
1676 	pvo = alloc_pvo_entry(0);
1677 	if (pvo == NULL)
1678 		return (KERN_RESOURCE_SHORTAGE);
1679 	pvo->pvo_pmap = NULL; /* to be filled in later */
1680 	pvo->pvo_pte.prot = prot;
1681 
1682 	pa = VM_PAGE_TO_PHYS(m);
1683 	pte_lo = moea64_calc_wimg(pa, pmap_page_get_memattr(m));
1684 	pvo->pvo_pte.pa = pa | pte_lo;
1685 
1686 	if ((flags & PMAP_ENTER_WIRED) != 0)
1687 		pvo->pvo_vaddr |= PVO_WIRED;
1688 
1689 	if ((m->oflags & VPO_UNMANAGED) != 0 || !moea64_initialized) {
1690 		pvo_head = NULL;
1691 	} else {
1692 		pvo_head = &m->md.mdpg_pvoh;
1693 		pvo->pvo_vaddr |= PVO_MANAGED;
1694 	}
1695 
1696 	PV_LOCK(pa);
1697 	PMAP_LOCK(pmap);
1698 	if (pvo->pvo_pmap == NULL)
1699 		init_pvo_entry(pvo, pmap, va);
1700 
1701 	if (moea64_ps_enabled(pmap) &&
1702 	    (tpvo = moea64_pvo_find_va(pmap, va & ~HPT_SP_MASK)) != NULL &&
1703 	    PVO_IS_SP(tpvo)) {
1704 		/* Demote SP before entering a regular page */
1705 		CTR2(KTR_PMAP, "%s: demote before enter: va=%#jx",
1706 		    __func__, (uintmax_t)va);
1707 		moea64_sp_demote_aligned(tpvo);
1708 	}
1709 
1710 	if (prot & VM_PROT_WRITE)
1711 		if (pmap_bootstrapped &&
1712 		    (m->oflags & VPO_UNMANAGED) == 0)
1713 			vm_page_aflag_set(m, PGA_WRITEABLE);
1714 
1715 	error = moea64_pvo_enter(pvo, pvo_head, &oldpvo);
1716 	if (error == EEXIST) {
1717 		if (oldpvo->pvo_vaddr == pvo->pvo_vaddr &&
1718 		    oldpvo->pvo_pte.pa == pvo->pvo_pte.pa &&
1719 		    oldpvo->pvo_pte.prot == prot) {
1720 			/* Identical mapping already exists */
1721 			error = 0;
1722 
1723 			/* If not in page table, reinsert it */
1724 			if (moea64_pte_synch(oldpvo) < 0) {
1725 				STAT_MOEA64(moea64_pte_overflow--);
1726 				moea64_pte_insert(oldpvo);
1727 			}
1728 
1729 			/* Then just clean up and go home */
1730 			PMAP_UNLOCK(pmap);
1731 			PV_UNLOCK(pa);
1732 			free_pvo_entry(pvo);
1733 			pvo = NULL;
1734 			goto out;
1735 		} else {
1736 			/* Otherwise, need to kill it first */
1737 			KASSERT(oldpvo->pvo_pmap == pmap, ("pmap of old "
1738 			    "mapping does not match new mapping"));
1739 			moea64_pvo_remove_from_pmap(oldpvo);
1740 			moea64_pvo_enter(pvo, pvo_head, NULL);
1741 		}
1742 	}
1743 	PMAP_UNLOCK(pmap);
1744 	PV_UNLOCK(pa);
1745 
1746 	/* Free any dead pages */
1747 	if (error == EEXIST) {
1748 		moea64_pvo_remove_from_page(oldpvo);
1749 		free_pvo_entry(oldpvo);
1750 	}
1751 
1752 out:
1753 	/*
1754 	 * Flush the page from the instruction cache if this page is
1755 	 * mapped executable and cacheable.
1756 	 */
1757 	if (pmap != kernel_pmap && (m->a.flags & PGA_EXECUTABLE) == 0 &&
1758 	    (pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
1759 		vm_page_aflag_set(m, PGA_EXECUTABLE);
1760 		moea64_syncicache(pmap, va, pa, PAGE_SIZE);
1761 	}
1762 
1763 #if VM_NRESERVLEVEL > 0
1764 	/*
1765 	 * Try to promote pages.
1766 	 *
1767 	 * If the VA of the entered page is not aligned with its PA,
1768 	 * don't try page promotion as it is not possible.
1769 	 * This reduces the number of promotion failures dramatically.
1770 	 */
1771 	if (moea64_ps_enabled(pmap) && pmap != kernel_pmap && pvo != NULL &&
1772 	    (pvo->pvo_vaddr & PVO_MANAGED) != 0 &&
1773 	    (va & HPT_SP_MASK) == (pa & HPT_SP_MASK) &&
1774 	    (m->flags & PG_FICTITIOUS) == 0 &&
1775 	    vm_reserv_level_iffullpop(m) == 0)
1776 		moea64_sp_promote(pmap, va, m);
1777 #endif
1778 
1779 	return (KERN_SUCCESS);
1780 }
1781 
1782 static void
1783 moea64_syncicache(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1784     vm_size_t sz)
1785 {
1786 
1787 	/*
1788 	 * This is much trickier than on older systems because
1789 	 * we can't sync the icache on physical addresses directly
1790 	 * without a direct map. Instead we check a couple of cases
1791 	 * where the memory is already mapped in and, failing that,
1792 	 * use the same trick we use for page zeroing to create
1793 	 * a temporary mapping for this physical address.
1794 	 */
1795 
1796 	if (!pmap_bootstrapped) {
1797 		/*
1798 		 * If PMAP is not bootstrapped, we are likely to be
1799 		 * in real mode.
1800 		 */
1801 		__syncicache((void *)(uintptr_t)pa, sz);
1802 	} else if (pmap == kernel_pmap) {
1803 		__syncicache((void *)va, sz);
1804 	} else if (hw_direct_map) {
1805 		__syncicache((void *)(uintptr_t)PHYS_TO_DMAP(pa), sz);
1806 	} else {
1807 		/* Use the scratch page to set up a temp mapping */
1808 
1809 		mtx_lock(&moea64_scratchpage_mtx);
1810 
1811 		moea64_set_scratchpage_pa(1, pa & ~ADDR_POFF);
1812 		__syncicache((void *)(moea64_scratchpage_va[1] +
1813 		    (va & ADDR_POFF)), sz);
1814 
1815 		mtx_unlock(&moea64_scratchpage_mtx);
1816 	}
1817 }
1818 
1819 /*
1820  * Maps a sequence of resident pages belonging to the same object.
1821  * The sequence begins with the given page m_start.  This page is
1822  * mapped at the given virtual address start.  Each subsequent page is
1823  * mapped at a virtual address that is offset from start by the same
1824  * amount as the page is offset from m_start within the object.  The
1825  * last page in the sequence is the page with the largest offset from
1826  * m_start that can be mapped at a virtual address less than the given
1827  * virtual address end.  Not every virtual page between start and end
1828  * is mapped; only those for which a resident page exists with the
1829  * corresponding offset from m_start are mapped.
1830  */
1831 void
1832 moea64_enter_object(pmap_t pm, vm_offset_t start, vm_offset_t end,
1833     vm_page_t m_start, vm_prot_t prot)
1834 {
1835 	vm_page_t m;
1836 	vm_pindex_t diff, psize;
1837 	vm_offset_t va;
1838 	int8_t psind;
1839 
1840 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1841 
1842 	psize = atop(end - start);
1843 	m = m_start;
1844 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1845 		va = start + ptoa(diff);
1846 		if ((va & HPT_SP_MASK) == 0 && va + HPT_SP_SIZE <= end &&
1847 		    m->psind == 1 && moea64_ps_enabled(pm))
1848 			psind = 1;
1849 		else
1850 			psind = 0;
1851 		moea64_enter(pm, va, m, prot &
1852 		    (VM_PROT_READ | VM_PROT_EXECUTE),
1853 		    PMAP_ENTER_NOSLEEP | PMAP_ENTER_QUICK_LOCKED, psind);
1854 		if (psind == 1)
1855 			m = &m[HPT_SP_SIZE / PAGE_SIZE - 1];
1856 		m = TAILQ_NEXT(m, listq);
1857 	}
1858 }
1859 
1860 void
1861 moea64_enter_quick(pmap_t pm, vm_offset_t va, vm_page_t m,
1862     vm_prot_t prot)
1863 {
1864 
1865 	moea64_enter(pm, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1866 	    PMAP_ENTER_NOSLEEP | PMAP_ENTER_QUICK_LOCKED, 0);
1867 }
1868 
1869 vm_paddr_t
1870 moea64_extract(pmap_t pm, vm_offset_t va)
1871 {
1872 	struct	pvo_entry *pvo;
1873 	vm_paddr_t pa;
1874 
1875 	PMAP_LOCK(pm);
1876 	pvo = moea64_pvo_find_va(pm, va);
1877 	if (pvo == NULL)
1878 		pa = 0;
1879 	else
1880 		pa = PVO_PADDR(pvo) | (va - PVO_VADDR(pvo));
1881 	PMAP_UNLOCK(pm);
1882 
1883 	return (pa);
1884 }
1885 
1886 /*
1887  * Atomically extract and hold the physical page with the given
1888  * pmap and virtual address pair if that mapping permits the given
1889  * protection.
1890  */
1891 vm_page_t
1892 moea64_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1893 {
1894 	struct	pvo_entry *pvo;
1895 	vm_page_t m;
1896 
1897 	m = NULL;
1898 	PMAP_LOCK(pmap);
1899 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
1900 	if (pvo != NULL && (pvo->pvo_pte.prot & prot) == prot) {
1901 		m = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
1902 		if (!vm_page_wire_mapped(m))
1903 			m = NULL;
1904 	}
1905 	PMAP_UNLOCK(pmap);
1906 	return (m);
1907 }
1908 
1909 static void *
1910 moea64_uma_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain,
1911     uint8_t *flags, int wait)
1912 {
1913 	struct pvo_entry *pvo;
1914         vm_offset_t va;
1915         vm_page_t m;
1916         int needed_lock;
1917 
1918 	/*
1919 	 * This entire routine is a horrible hack to avoid bothering kmem
1920 	 * for new KVA addresses. Because this can get called from inside
1921 	 * kmem allocation routines, calling kmem for a new address here
1922 	 * can lead to multiply locking non-recursive mutexes.
1923 	 */
1924 
1925 	*flags = UMA_SLAB_PRIV;
1926 	needed_lock = !PMAP_LOCKED(kernel_pmap);
1927 
1928 	m = vm_page_alloc_domain(NULL, 0, domain,
1929 	    malloc2vm_flags(wait) | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ);
1930 	if (m == NULL)
1931 		return (NULL);
1932 
1933 	va = VM_PAGE_TO_PHYS(m);
1934 
1935 	pvo = alloc_pvo_entry(1 /* bootstrap */);
1936 
1937 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE;
1938 	pvo->pvo_pte.pa = VM_PAGE_TO_PHYS(m) | LPTE_M;
1939 
1940 	if (needed_lock)
1941 		PMAP_LOCK(kernel_pmap);
1942 
1943 	init_pvo_entry(pvo, kernel_pmap, va);
1944 	pvo->pvo_vaddr |= PVO_WIRED;
1945 
1946 	moea64_pvo_enter(pvo, NULL, NULL);
1947 
1948 	if (needed_lock)
1949 		PMAP_UNLOCK(kernel_pmap);
1950 
1951 	if ((wait & M_ZERO) && (m->flags & PG_ZERO) == 0)
1952                 bzero((void *)va, PAGE_SIZE);
1953 
1954 	return (void *)va;
1955 }
1956 
1957 extern int elf32_nxstack;
1958 
1959 void
1960 moea64_init()
1961 {
1962 
1963 	CTR0(KTR_PMAP, "moea64_init");
1964 
1965 	moea64_pvo_zone = uma_zcreate("UPVO entry", sizeof (struct pvo_entry),
1966 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1967 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1968 
1969 	/*
1970 	 * Are large page mappings enabled?
1971 	 */
1972 	TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1973 	if (superpages_enabled) {
1974 		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1975 		    ("moea64_init: can't assign to pagesizes[1]"));
1976 
1977 		if (moea64_large_page_size == 0) {
1978 			printf("mmu_oea64: HW does not support large pages. "
1979 					"Disabling superpages...\n");
1980 			superpages_enabled = 0;
1981 		} else if (!moea64_has_lp_4k_16m) {
1982 			printf("mmu_oea64: "
1983 			    "HW does not support mixed 4KB/16MB page sizes. "
1984 			    "Disabling superpages...\n");
1985 			superpages_enabled = 0;
1986 		} else
1987 			pagesizes[1] = HPT_SP_SIZE;
1988 	}
1989 
1990 	if (!hw_direct_map) {
1991 		uma_zone_set_allocf(moea64_pvo_zone, moea64_uma_page_alloc);
1992 	}
1993 
1994 #ifdef COMPAT_FREEBSD32
1995 	elf32_nxstack = 1;
1996 #endif
1997 
1998 	moea64_initialized = TRUE;
1999 }
2000 
2001 boolean_t
2002 moea64_is_referenced(vm_page_t m)
2003 {
2004 
2005 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2006 	    ("moea64_is_referenced: page %p is not managed", m));
2007 
2008 	return (moea64_query_bit(m, LPTE_REF));
2009 }
2010 
2011 boolean_t
2012 moea64_is_modified(vm_page_t m)
2013 {
2014 
2015 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2016 	    ("moea64_is_modified: page %p is not managed", m));
2017 
2018 	/*
2019 	 * If the page is not busied then this check is racy.
2020 	 */
2021 	if (!pmap_page_is_write_mapped(m))
2022 		return (FALSE);
2023 
2024 	return (moea64_query_bit(m, LPTE_CHG));
2025 }
2026 
2027 boolean_t
2028 moea64_is_prefaultable(pmap_t pmap, vm_offset_t va)
2029 {
2030 	struct pvo_entry *pvo;
2031 	boolean_t rv = TRUE;
2032 
2033 	PMAP_LOCK(pmap);
2034 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
2035 	if (pvo != NULL)
2036 		rv = FALSE;
2037 	PMAP_UNLOCK(pmap);
2038 	return (rv);
2039 }
2040 
2041 void
2042 moea64_clear_modify(vm_page_t m)
2043 {
2044 
2045 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2046 	    ("moea64_clear_modify: page %p is not managed", m));
2047 	vm_page_assert_busied(m);
2048 
2049 	if (!pmap_page_is_write_mapped(m))
2050 		return;
2051 	moea64_clear_bit(m, LPTE_CHG);
2052 }
2053 
2054 /*
2055  * Clear the write and modified bits in each of the given page's mappings.
2056  */
2057 void
2058 moea64_remove_write(vm_page_t m)
2059 {
2060 	struct	pvo_entry *pvo;
2061 	int64_t	refchg, ret;
2062 	pmap_t	pmap;
2063 
2064 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2065 	    ("moea64_remove_write: page %p is not managed", m));
2066 	vm_page_assert_busied(m);
2067 
2068 	if (!pmap_page_is_write_mapped(m))
2069 		return;
2070 
2071 	powerpc_sync();
2072 	PV_PAGE_LOCK(m);
2073 	refchg = 0;
2074 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2075 		pmap = pvo->pvo_pmap;
2076 		PMAP_LOCK(pmap);
2077 		if (!(pvo->pvo_vaddr & PVO_DEAD) &&
2078 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
2079 			if (PVO_IS_SP(pvo)) {
2080 				CTR1(KTR_PMAP, "%s: demote before remwr",
2081 				    __func__);
2082 				moea64_sp_demote(pvo);
2083 			}
2084 			pvo->pvo_pte.prot &= ~VM_PROT_WRITE;
2085 			ret = moea64_pte_replace(pvo, MOEA64_PTE_PROT_UPDATE);
2086 			if (ret < 0)
2087 				ret = LPTE_CHG;
2088 			refchg |= ret;
2089 			if (pvo->pvo_pmap == kernel_pmap)
2090 				isync();
2091 		}
2092 		PMAP_UNLOCK(pmap);
2093 	}
2094 	if ((refchg | atomic_readandclear_32(&m->md.mdpg_attrs)) & LPTE_CHG)
2095 		vm_page_dirty(m);
2096 	vm_page_aflag_clear(m, PGA_WRITEABLE);
2097 	PV_PAGE_UNLOCK(m);
2098 }
2099 
2100 /*
2101  *	moea64_ts_referenced:
2102  *
2103  *	Return a count of reference bits for a page, clearing those bits.
2104  *	It is not necessary for every reference bit to be cleared, but it
2105  *	is necessary that 0 only be returned when there are truly no
2106  *	reference bits set.
2107  *
2108  *	XXX: The exact number of bits to check and clear is a matter that
2109  *	should be tested and standardized at some point in the future for
2110  *	optimal aging of shared pages.
2111  */
2112 int
2113 moea64_ts_referenced(vm_page_t m)
2114 {
2115 
2116 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2117 	    ("moea64_ts_referenced: page %p is not managed", m));
2118 	return (moea64_clear_bit(m, LPTE_REF));
2119 }
2120 
2121 /*
2122  * Modify the WIMG settings of all mappings for a page.
2123  */
2124 void
2125 moea64_page_set_memattr(vm_page_t m, vm_memattr_t ma)
2126 {
2127 	struct	pvo_entry *pvo;
2128 	int64_t	refchg;
2129 	pmap_t	pmap;
2130 	uint64_t lo;
2131 
2132 	CTR3(KTR_PMAP, "%s: pa=%#jx, ma=%#x",
2133 	    __func__, (uintmax_t)VM_PAGE_TO_PHYS(m), ma);
2134 
2135 	if ((m->oflags & VPO_UNMANAGED) != 0) {
2136 		m->md.mdpg_cache_attrs = ma;
2137 		return;
2138 	}
2139 
2140 	lo = moea64_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
2141 
2142 	PV_PAGE_LOCK(m);
2143 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2144 		pmap = pvo->pvo_pmap;
2145 		PMAP_LOCK(pmap);
2146 		if (!(pvo->pvo_vaddr & PVO_DEAD)) {
2147 			if (PVO_IS_SP(pvo)) {
2148 				CTR1(KTR_PMAP,
2149 				    "%s: demote before set_memattr", __func__);
2150 				moea64_sp_demote(pvo);
2151 			}
2152 			pvo->pvo_pte.pa &= ~LPTE_WIMG;
2153 			pvo->pvo_pte.pa |= lo;
2154 			refchg = moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
2155 			if (refchg < 0)
2156 				refchg = (pvo->pvo_pte.prot & VM_PROT_WRITE) ?
2157 				    LPTE_CHG : 0;
2158 			if ((pvo->pvo_vaddr & PVO_MANAGED) &&
2159 			    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
2160 				refchg |=
2161 				    atomic_readandclear_32(&m->md.mdpg_attrs);
2162 				if (refchg & LPTE_CHG)
2163 					vm_page_dirty(m);
2164 				if (refchg & LPTE_REF)
2165 					vm_page_aflag_set(m, PGA_REFERENCED);
2166 			}
2167 			if (pvo->pvo_pmap == kernel_pmap)
2168 				isync();
2169 		}
2170 		PMAP_UNLOCK(pmap);
2171 	}
2172 	m->md.mdpg_cache_attrs = ma;
2173 	PV_PAGE_UNLOCK(m);
2174 }
2175 
2176 /*
2177  * Map a wired page into kernel virtual address space.
2178  */
2179 void
2180 moea64_kenter_attr(vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
2181 {
2182 	int		error;
2183 	struct pvo_entry *pvo, *oldpvo;
2184 
2185 	do {
2186 		pvo = alloc_pvo_entry(0);
2187 		if (pvo == NULL)
2188 			vm_wait(NULL);
2189 	} while (pvo == NULL);
2190 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
2191 	pvo->pvo_pte.pa = (pa & ~ADDR_POFF) | moea64_calc_wimg(pa, ma);
2192 	pvo->pvo_vaddr |= PVO_WIRED;
2193 
2194 	PMAP_LOCK(kernel_pmap);
2195 	oldpvo = moea64_pvo_find_va(kernel_pmap, va);
2196 	if (oldpvo != NULL)
2197 		moea64_pvo_remove_from_pmap(oldpvo);
2198 	init_pvo_entry(pvo, kernel_pmap, va);
2199 	error = moea64_pvo_enter(pvo, NULL, NULL);
2200 	PMAP_UNLOCK(kernel_pmap);
2201 
2202 	/* Free any dead pages */
2203 	if (oldpvo != NULL) {
2204 		moea64_pvo_remove_from_page(oldpvo);
2205 		free_pvo_entry(oldpvo);
2206 	}
2207 
2208 	if (error != 0)
2209 		panic("moea64_kenter: failed to enter va %#zx pa %#jx: %d", va,
2210 		    (uintmax_t)pa, error);
2211 }
2212 
2213 void
2214 moea64_kenter(vm_offset_t va, vm_paddr_t pa)
2215 {
2216 
2217 	moea64_kenter_attr(va, pa, VM_MEMATTR_DEFAULT);
2218 }
2219 
2220 /*
2221  * Extract the physical page address associated with the given kernel virtual
2222  * address.
2223  */
2224 vm_paddr_t
2225 moea64_kextract(vm_offset_t va)
2226 {
2227 	struct		pvo_entry *pvo;
2228 	vm_paddr_t pa;
2229 
2230 	/*
2231 	 * Shortcut the direct-mapped case when applicable.  We never put
2232 	 * anything but 1:1 (or 62-bit aliased) mappings below
2233 	 * VM_MIN_KERNEL_ADDRESS.
2234 	 */
2235 	if (va < VM_MIN_KERNEL_ADDRESS)
2236 		return (va & ~DMAP_BASE_ADDRESS);
2237 
2238 	PMAP_LOCK(kernel_pmap);
2239 	pvo = moea64_pvo_find_va(kernel_pmap, va);
2240 	KASSERT(pvo != NULL, ("moea64_kextract: no addr found for %#" PRIxPTR,
2241 	    va));
2242 	pa = PVO_PADDR(pvo) | (va - PVO_VADDR(pvo));
2243 	PMAP_UNLOCK(kernel_pmap);
2244 	return (pa);
2245 }
2246 
2247 /*
2248  * Remove a wired page from kernel virtual address space.
2249  */
2250 void
2251 moea64_kremove(vm_offset_t va)
2252 {
2253 	moea64_remove(kernel_pmap, va, va + PAGE_SIZE);
2254 }
2255 
2256 /*
2257  * Provide a kernel pointer corresponding to a given userland pointer.
2258  * The returned pointer is valid until the next time this function is
2259  * called in this thread. This is used internally in copyin/copyout.
2260  */
2261 static int
2262 moea64_map_user_ptr(pmap_t pm, volatile const void *uaddr,
2263     void **kaddr, size_t ulen, size_t *klen)
2264 {
2265 	size_t l;
2266 #ifdef __powerpc64__
2267 	struct slb *slb;
2268 #endif
2269 	register_t slbv;
2270 
2271 	*kaddr = (char *)USER_ADDR + ((uintptr_t)uaddr & ~SEGMENT_MASK);
2272 	l = ((char *)USER_ADDR + SEGMENT_LENGTH) - (char *)(*kaddr);
2273 	if (l > ulen)
2274 		l = ulen;
2275 	if (klen)
2276 		*klen = l;
2277 	else if (l != ulen)
2278 		return (EFAULT);
2279 
2280 #ifdef __powerpc64__
2281 	/* Try lockless look-up first */
2282 	slb = user_va_to_slb_entry(pm, (vm_offset_t)uaddr);
2283 
2284 	if (slb == NULL) {
2285 		/* If it isn't there, we need to pre-fault the VSID */
2286 		PMAP_LOCK(pm);
2287 		slbv = va_to_vsid(pm, (vm_offset_t)uaddr) << SLBV_VSID_SHIFT;
2288 		PMAP_UNLOCK(pm);
2289 	} else {
2290 		slbv = slb->slbv;
2291 	}
2292 
2293 	/* Mark segment no-execute */
2294 	slbv |= SLBV_N;
2295 #else
2296 	slbv = va_to_vsid(pm, (vm_offset_t)uaddr);
2297 
2298 	/* Mark segment no-execute */
2299 	slbv |= SR_N;
2300 #endif
2301 
2302 	/* If we have already set this VSID, we can just return */
2303 	if (curthread->td_pcb->pcb_cpu.aim.usr_vsid == slbv)
2304 		return (0);
2305 
2306 	__asm __volatile("isync");
2307 	curthread->td_pcb->pcb_cpu.aim.usr_segm =
2308 	    (uintptr_t)uaddr >> ADDR_SR_SHFT;
2309 	curthread->td_pcb->pcb_cpu.aim.usr_vsid = slbv;
2310 #ifdef __powerpc64__
2311 	__asm __volatile ("slbie %0; slbmte %1, %2; isync" ::
2312 	    "r"(USER_ADDR), "r"(slbv), "r"(USER_SLB_SLBE));
2313 #else
2314 	__asm __volatile("mtsr %0,%1; isync" :: "n"(USER_SR), "r"(slbv));
2315 #endif
2316 
2317 	return (0);
2318 }
2319 
2320 /*
2321  * Figure out where a given kernel pointer (usually in a fault) points
2322  * to from the VM's perspective, potentially remapping into userland's
2323  * address space.
2324  */
2325 static int
2326 moea64_decode_kernel_ptr(vm_offset_t addr, int *is_user,
2327     vm_offset_t *decoded_addr)
2328 {
2329 	vm_offset_t user_sr;
2330 
2331 	if ((addr >> ADDR_SR_SHFT) == (USER_ADDR >> ADDR_SR_SHFT)) {
2332 		user_sr = curthread->td_pcb->pcb_cpu.aim.usr_segm;
2333 		addr &= ADDR_PIDX | ADDR_POFF;
2334 		addr |= user_sr << ADDR_SR_SHFT;
2335 		*decoded_addr = addr;
2336 		*is_user = 1;
2337 	} else {
2338 		*decoded_addr = addr;
2339 		*is_user = 0;
2340 	}
2341 
2342 	return (0);
2343 }
2344 
2345 /*
2346  * Map a range of physical addresses into kernel virtual address space.
2347  *
2348  * The value passed in *virt is a suggested virtual address for the mapping.
2349  * Architectures which can support a direct-mapped physical to virtual region
2350  * can return the appropriate address within that region, leaving '*virt'
2351  * unchanged.  Other architectures should map the pages starting at '*virt' and
2352  * update '*virt' with the first usable address after the mapped region.
2353  */
2354 vm_offset_t
2355 moea64_map(vm_offset_t *virt, vm_paddr_t pa_start,
2356     vm_paddr_t pa_end, int prot)
2357 {
2358 	vm_offset_t	sva, va;
2359 
2360 	if (hw_direct_map) {
2361 		/*
2362 		 * Check if every page in the region is covered by the direct
2363 		 * map. The direct map covers all of physical memory. Use
2364 		 * moea64_calc_wimg() as a shortcut to see if the page is in
2365 		 * physical memory as a way to see if the direct map covers it.
2366 		 */
2367 		for (va = pa_start; va < pa_end; va += PAGE_SIZE)
2368 			if (moea64_calc_wimg(va, VM_MEMATTR_DEFAULT) != LPTE_M)
2369 				break;
2370 		if (va == pa_end)
2371 			return (PHYS_TO_DMAP(pa_start));
2372 	}
2373 	sva = *virt;
2374 	va = sva;
2375 	/* XXX respect prot argument */
2376 	for (; pa_start < pa_end; pa_start += PAGE_SIZE, va += PAGE_SIZE)
2377 		moea64_kenter(va, pa_start);
2378 	*virt = va;
2379 
2380 	return (sva);
2381 }
2382 
2383 /*
2384  * Returns true if the pmap's pv is one of the first
2385  * 16 pvs linked to from this page.  This count may
2386  * be changed upwards or downwards in the future; it
2387  * is only necessary that true be returned for a small
2388  * subset of pmaps for proper page aging.
2389  */
2390 boolean_t
2391 moea64_page_exists_quick(pmap_t pmap, vm_page_t m)
2392 {
2393         int loops;
2394 	struct pvo_entry *pvo;
2395 	boolean_t rv;
2396 
2397 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2398 	    ("moea64_page_exists_quick: page %p is not managed", m));
2399 	loops = 0;
2400 	rv = FALSE;
2401 	PV_PAGE_LOCK(m);
2402 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2403 		if (!(pvo->pvo_vaddr & PVO_DEAD) && pvo->pvo_pmap == pmap) {
2404 			rv = TRUE;
2405 			break;
2406 		}
2407 		if (++loops >= 16)
2408 			break;
2409 	}
2410 	PV_PAGE_UNLOCK(m);
2411 	return (rv);
2412 }
2413 
2414 void
2415 moea64_page_init(vm_page_t m)
2416 {
2417 
2418 	m->md.mdpg_attrs = 0;
2419 	m->md.mdpg_cache_attrs = VM_MEMATTR_DEFAULT;
2420 	LIST_INIT(&m->md.mdpg_pvoh);
2421 }
2422 
2423 /*
2424  * Return the number of managed mappings to the given physical page
2425  * that are wired.
2426  */
2427 int
2428 moea64_page_wired_mappings(vm_page_t m)
2429 {
2430 	struct pvo_entry *pvo;
2431 	int count;
2432 
2433 	count = 0;
2434 	if ((m->oflags & VPO_UNMANAGED) != 0)
2435 		return (count);
2436 	PV_PAGE_LOCK(m);
2437 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
2438 		if ((pvo->pvo_vaddr & (PVO_DEAD | PVO_WIRED)) == PVO_WIRED)
2439 			count++;
2440 	PV_PAGE_UNLOCK(m);
2441 	return (count);
2442 }
2443 
2444 static uintptr_t	moea64_vsidcontext;
2445 
2446 uintptr_t
2447 moea64_get_unique_vsid(void) {
2448 	u_int entropy;
2449 	register_t hash;
2450 	uint32_t mask;
2451 	int i;
2452 
2453 	entropy = 0;
2454 	__asm __volatile("mftb %0" : "=r"(entropy));
2455 
2456 	mtx_lock(&moea64_slb_mutex);
2457 	for (i = 0; i < NVSIDS; i += VSID_NBPW) {
2458 		u_int	n;
2459 
2460 		/*
2461 		 * Create a new value by mutiplying by a prime and adding in
2462 		 * entropy from the timebase register.  This is to make the
2463 		 * VSID more random so that the PT hash function collides
2464 		 * less often.  (Note that the prime casues gcc to do shifts
2465 		 * instead of a multiply.)
2466 		 */
2467 		moea64_vsidcontext = (moea64_vsidcontext * 0x1105) + entropy;
2468 		hash = moea64_vsidcontext & (NVSIDS - 1);
2469 		if (hash == 0)		/* 0 is special, avoid it */
2470 			continue;
2471 		n = hash >> 5;
2472 		mask = 1 << (hash & (VSID_NBPW - 1));
2473 		hash = (moea64_vsidcontext & VSID_HASHMASK);
2474 		if (moea64_vsid_bitmap[n] & mask) {	/* collision? */
2475 			/* anything free in this bucket? */
2476 			if (moea64_vsid_bitmap[n] == 0xffffffff) {
2477 				entropy = (moea64_vsidcontext >> 20);
2478 				continue;
2479 			}
2480 			i = ffs(~moea64_vsid_bitmap[n]) - 1;
2481 			mask = 1 << i;
2482 			hash &= rounddown2(VSID_HASHMASK, VSID_NBPW);
2483 			hash |= i;
2484 		}
2485 		if (hash == VSID_VRMA)	/* also special, avoid this too */
2486 			continue;
2487 		KASSERT(!(moea64_vsid_bitmap[n] & mask),
2488 		    ("Allocating in-use VSID %#zx\n", hash));
2489 		moea64_vsid_bitmap[n] |= mask;
2490 		mtx_unlock(&moea64_slb_mutex);
2491 		return (hash);
2492 	}
2493 
2494 	mtx_unlock(&moea64_slb_mutex);
2495 	panic("%s: out of segments",__func__);
2496 }
2497 
2498 #ifdef __powerpc64__
2499 int
2500 moea64_pinit(pmap_t pmap)
2501 {
2502 
2503 	RB_INIT(&pmap->pmap_pvo);
2504 
2505 	pmap->pm_slb_tree_root = slb_alloc_tree();
2506 	pmap->pm_slb = slb_alloc_user_cache();
2507 	pmap->pm_slb_len = 0;
2508 
2509 	return (1);
2510 }
2511 #else
2512 int
2513 moea64_pinit(pmap_t pmap)
2514 {
2515 	int	i;
2516 	uint32_t hash;
2517 
2518 	RB_INIT(&pmap->pmap_pvo);
2519 
2520 	if (pmap_bootstrapped)
2521 		pmap->pmap_phys = (pmap_t)moea64_kextract((vm_offset_t)pmap);
2522 	else
2523 		pmap->pmap_phys = pmap;
2524 
2525 	/*
2526 	 * Allocate some segment registers for this pmap.
2527 	 */
2528 	hash = moea64_get_unique_vsid();
2529 
2530 	for (i = 0; i < 16; i++)
2531 		pmap->pm_sr[i] = VSID_MAKE(i, hash);
2532 
2533 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_pinit: pm_sr[0] = 0"));
2534 
2535 	return (1);
2536 }
2537 #endif
2538 
2539 /*
2540  * Initialize the pmap associated with process 0.
2541  */
2542 void
2543 moea64_pinit0(pmap_t pm)
2544 {
2545 
2546 	PMAP_LOCK_INIT(pm);
2547 	moea64_pinit(pm);
2548 	bzero(&pm->pm_stats, sizeof(pm->pm_stats));
2549 }
2550 
2551 /*
2552  * Set the physical protection on the specified range of this map as requested.
2553  */
2554 static void
2555 moea64_pvo_protect( pmap_t pm, struct pvo_entry *pvo, vm_prot_t prot)
2556 {
2557 	struct vm_page *pg;
2558 	vm_prot_t oldprot;
2559 	int32_t refchg;
2560 
2561 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
2562 
2563 	/*
2564 	 * Change the protection of the page.
2565 	 */
2566 	oldprot = pvo->pvo_pte.prot;
2567 	pvo->pvo_pte.prot = prot;
2568 	pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2569 
2570 	/*
2571 	 * If the PVO is in the page table, update mapping
2572 	 */
2573 	refchg = moea64_pte_replace(pvo, MOEA64_PTE_PROT_UPDATE);
2574 	if (refchg < 0)
2575 		refchg = (oldprot & VM_PROT_WRITE) ? LPTE_CHG : 0;
2576 
2577 	if (pm != kernel_pmap && pg != NULL &&
2578 	    (pg->a.flags & PGA_EXECUTABLE) == 0 &&
2579 	    (pvo->pvo_pte.pa & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
2580 		if ((pg->oflags & VPO_UNMANAGED) == 0)
2581 			vm_page_aflag_set(pg, PGA_EXECUTABLE);
2582 		moea64_syncicache(pm, PVO_VADDR(pvo),
2583 		    PVO_PADDR(pvo), PAGE_SIZE);
2584 	}
2585 
2586 	/*
2587 	 * Update vm about the REF/CHG bits if the page is managed and we have
2588 	 * removed write access.
2589 	 */
2590 	if (pg != NULL && (pvo->pvo_vaddr & PVO_MANAGED) &&
2591 	    (oldprot & VM_PROT_WRITE)) {
2592 		refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2593 		if (refchg & LPTE_CHG)
2594 			vm_page_dirty(pg);
2595 		if (refchg & LPTE_REF)
2596 			vm_page_aflag_set(pg, PGA_REFERENCED);
2597 	}
2598 }
2599 
2600 void
2601 moea64_protect(pmap_t pm, vm_offset_t sva, vm_offset_t eva,
2602     vm_prot_t prot)
2603 {
2604 	struct	pvo_entry *pvo, key;
2605 
2606 	CTR4(KTR_PMAP, "moea64_protect: pm=%p sva=%#x eva=%#x prot=%#x", pm,
2607 	    sva, eva, prot);
2608 
2609 	KASSERT(pm == &curproc->p_vmspace->vm_pmap || pm == kernel_pmap,
2610 	    ("moea64_protect: non current pmap"));
2611 
2612 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2613 		moea64_remove(pm, sva, eva);
2614 		return;
2615 	}
2616 
2617 	PMAP_LOCK(pm);
2618 	key.pvo_vaddr = sva;
2619 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2620 	    pvo != NULL && PVO_VADDR(pvo) < eva;
2621 	    pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
2622 		if (PVO_IS_SP(pvo)) {
2623 			if (moea64_sp_pvo_in_range(pvo, sva, eva)) {
2624 				pvo = moea64_sp_protect(pvo, prot);
2625 				continue;
2626 			} else {
2627 				CTR1(KTR_PMAP, "%s: demote before protect",
2628 				    __func__);
2629 				moea64_sp_demote(pvo);
2630 			}
2631 		}
2632 		moea64_pvo_protect(pm, pvo, prot);
2633 	}
2634 	PMAP_UNLOCK(pm);
2635 }
2636 
2637 /*
2638  * Map a list of wired pages into kernel virtual address space.  This is
2639  * intended for temporary mappings which do not need page modification or
2640  * references recorded.  Existing mappings in the region are overwritten.
2641  */
2642 void
2643 moea64_qenter(vm_offset_t va, vm_page_t *m, int count)
2644 {
2645 	while (count-- > 0) {
2646 		moea64_kenter(va, VM_PAGE_TO_PHYS(*m));
2647 		va += PAGE_SIZE;
2648 		m++;
2649 	}
2650 }
2651 
2652 /*
2653  * Remove page mappings from kernel virtual address space.  Intended for
2654  * temporary mappings entered by moea64_qenter.
2655  */
2656 void
2657 moea64_qremove(vm_offset_t va, int count)
2658 {
2659 	while (count-- > 0) {
2660 		moea64_kremove(va);
2661 		va += PAGE_SIZE;
2662 	}
2663 }
2664 
2665 void
2666 moea64_release_vsid(uint64_t vsid)
2667 {
2668 	int idx, mask;
2669 
2670 	mtx_lock(&moea64_slb_mutex);
2671 	idx = vsid & (NVSIDS-1);
2672 	mask = 1 << (idx % VSID_NBPW);
2673 	idx /= VSID_NBPW;
2674 	KASSERT(moea64_vsid_bitmap[idx] & mask,
2675 	    ("Freeing unallocated VSID %#jx", vsid));
2676 	moea64_vsid_bitmap[idx] &= ~mask;
2677 	mtx_unlock(&moea64_slb_mutex);
2678 }
2679 
2680 void
2681 moea64_release(pmap_t pmap)
2682 {
2683 
2684 	/*
2685 	 * Free segment registers' VSIDs
2686 	 */
2687     #ifdef __powerpc64__
2688 	slb_free_tree(pmap);
2689 	slb_free_user_cache(pmap->pm_slb);
2690     #else
2691 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_release: pm_sr[0] = 0"));
2692 
2693 	moea64_release_vsid(VSID_TO_HASH(pmap->pm_sr[0]));
2694     #endif
2695 }
2696 
2697 /*
2698  * Remove all pages mapped by the specified pmap
2699  */
2700 void
2701 moea64_remove_pages(pmap_t pm)
2702 {
2703 	struct pvo_entry *pvo, *tpvo;
2704 	struct pvo_dlist tofree;
2705 
2706 	SLIST_INIT(&tofree);
2707 
2708 	PMAP_LOCK(pm);
2709 	RB_FOREACH_SAFE(pvo, pvo_tree, &pm->pmap_pvo, tpvo) {
2710 		if (pvo->pvo_vaddr & PVO_WIRED)
2711 			continue;
2712 
2713 		/*
2714 		 * For locking reasons, remove this from the page table and
2715 		 * pmap, but save delinking from the vm_page for a second
2716 		 * pass
2717 		 */
2718 		moea64_pvo_remove_from_pmap(pvo);
2719 		SLIST_INSERT_HEAD(&tofree, pvo, pvo_dlink);
2720 	}
2721 	PMAP_UNLOCK(pm);
2722 
2723 	while (!SLIST_EMPTY(&tofree)) {
2724 		pvo = SLIST_FIRST(&tofree);
2725 		SLIST_REMOVE_HEAD(&tofree, pvo_dlink);
2726 		moea64_pvo_remove_from_page(pvo);
2727 		free_pvo_entry(pvo);
2728 	}
2729 }
2730 
2731 static void
2732 moea64_remove_locked(pmap_t pm, vm_offset_t sva, vm_offset_t eva,
2733     struct pvo_dlist *tofree)
2734 {
2735 	struct pvo_entry *pvo, *tpvo, key;
2736 
2737 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
2738 
2739 	key.pvo_vaddr = sva;
2740 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2741 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
2742 		if (PVO_IS_SP(pvo)) {
2743 			if (moea64_sp_pvo_in_range(pvo, sva, eva)) {
2744 				tpvo = moea64_sp_remove(pvo, tofree);
2745 				continue;
2746 			} else {
2747 				CTR1(KTR_PMAP, "%s: demote before remove",
2748 				    __func__);
2749 				moea64_sp_demote(pvo);
2750 			}
2751 		}
2752 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
2753 
2754 		/*
2755 		 * For locking reasons, remove this from the page table and
2756 		 * pmap, but save delinking from the vm_page for a second
2757 		 * pass
2758 		 */
2759 		moea64_pvo_remove_from_pmap(pvo);
2760 		SLIST_INSERT_HEAD(tofree, pvo, pvo_dlink);
2761 	}
2762 }
2763 
2764 /*
2765  * Remove the given range of addresses from the specified map.
2766  */
2767 void
2768 moea64_remove(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
2769 {
2770 	struct pvo_entry *pvo;
2771 	struct pvo_dlist tofree;
2772 
2773 	/*
2774 	 * Perform an unsynchronized read.  This is, however, safe.
2775 	 */
2776 	if (pm->pm_stats.resident_count == 0)
2777 		return;
2778 
2779 	SLIST_INIT(&tofree);
2780 	PMAP_LOCK(pm);
2781 	moea64_remove_locked(pm, sva, eva, &tofree);
2782 	PMAP_UNLOCK(pm);
2783 
2784 	while (!SLIST_EMPTY(&tofree)) {
2785 		pvo = SLIST_FIRST(&tofree);
2786 		SLIST_REMOVE_HEAD(&tofree, pvo_dlink);
2787 		moea64_pvo_remove_from_page(pvo);
2788 		free_pvo_entry(pvo);
2789 	}
2790 }
2791 
2792 /*
2793  * Remove physical page from all pmaps in which it resides. moea64_pvo_remove()
2794  * will reflect changes in pte's back to the vm_page.
2795  */
2796 void
2797 moea64_remove_all(vm_page_t m)
2798 {
2799 	struct	pvo_entry *pvo, *next_pvo;
2800 	struct	pvo_head freequeue;
2801 	int	wasdead;
2802 	pmap_t	pmap;
2803 
2804 	LIST_INIT(&freequeue);
2805 
2806 	PV_PAGE_LOCK(m);
2807 	LIST_FOREACH_SAFE(pvo, vm_page_to_pvoh(m), pvo_vlink, next_pvo) {
2808 		pmap = pvo->pvo_pmap;
2809 		PMAP_LOCK(pmap);
2810 		wasdead = (pvo->pvo_vaddr & PVO_DEAD);
2811 		if (!wasdead) {
2812 			if (PVO_IS_SP(pvo)) {
2813 				CTR1(KTR_PMAP, "%s: demote before remove_all",
2814 				    __func__);
2815 				moea64_sp_demote(pvo);
2816 			}
2817 			moea64_pvo_remove_from_pmap(pvo);
2818 		}
2819 		moea64_pvo_remove_from_page_locked(pvo, m);
2820 		if (!wasdead)
2821 			LIST_INSERT_HEAD(&freequeue, pvo, pvo_vlink);
2822 		PMAP_UNLOCK(pmap);
2823 
2824 	}
2825 	KASSERT(!pmap_page_is_mapped(m), ("Page still has mappings"));
2826 	KASSERT((m->a.flags & PGA_WRITEABLE) == 0, ("Page still writable"));
2827 	PV_PAGE_UNLOCK(m);
2828 
2829 	/* Clean up UMA allocations */
2830 	LIST_FOREACH_SAFE(pvo, &freequeue, pvo_vlink, next_pvo)
2831 		free_pvo_entry(pvo);
2832 }
2833 
2834 /*
2835  * Allocate a physical page of memory directly from the phys_avail map.
2836  * Can only be called from moea64_bootstrap before avail start and end are
2837  * calculated.
2838  */
2839 vm_offset_t
2840 moea64_bootstrap_alloc(vm_size_t size, vm_size_t align)
2841 {
2842 	vm_offset_t	s, e;
2843 	int		i, j;
2844 
2845 	size = round_page(size);
2846 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
2847 		if (align != 0)
2848 			s = roundup2(phys_avail[i], align);
2849 		else
2850 			s = phys_avail[i];
2851 		e = s + size;
2852 
2853 		if (s < phys_avail[i] || e > phys_avail[i + 1])
2854 			continue;
2855 
2856 		if (s + size > platform_real_maxaddr())
2857 			continue;
2858 
2859 		if (s == phys_avail[i]) {
2860 			phys_avail[i] += size;
2861 		} else if (e == phys_avail[i + 1]) {
2862 			phys_avail[i + 1] -= size;
2863 		} else {
2864 			for (j = phys_avail_count * 2; j > i; j -= 2) {
2865 				phys_avail[j] = phys_avail[j - 2];
2866 				phys_avail[j + 1] = phys_avail[j - 1];
2867 			}
2868 
2869 			phys_avail[i + 3] = phys_avail[i + 1];
2870 			phys_avail[i + 1] = s;
2871 			phys_avail[i + 2] = e;
2872 			phys_avail_count++;
2873 		}
2874 
2875 		return (s);
2876 	}
2877 	panic("moea64_bootstrap_alloc: could not allocate memory");
2878 }
2879 
2880 static int
2881 moea64_pvo_enter(struct pvo_entry *pvo, struct pvo_head *pvo_head,
2882     struct pvo_entry **oldpvop)
2883 {
2884 	struct pvo_entry *old_pvo;
2885 	int err;
2886 
2887 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2888 
2889 	STAT_MOEA64(moea64_pvo_enter_calls++);
2890 
2891 	/*
2892 	 * Add to pmap list
2893 	 */
2894 	old_pvo = RB_INSERT(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2895 
2896 	if (old_pvo != NULL) {
2897 		if (oldpvop != NULL)
2898 			*oldpvop = old_pvo;
2899 		return (EEXIST);
2900 	}
2901 
2902 	if (pvo_head != NULL) {
2903 		LIST_INSERT_HEAD(pvo_head, pvo, pvo_vlink);
2904 	}
2905 
2906 	if (pvo->pvo_vaddr & PVO_WIRED)
2907 		pvo->pvo_pmap->pm_stats.wired_count++;
2908 	pvo->pvo_pmap->pm_stats.resident_count++;
2909 
2910 	/*
2911 	 * Insert it into the hardware page table
2912 	 */
2913 	err = moea64_pte_insert(pvo);
2914 	if (err != 0) {
2915 		panic("moea64_pvo_enter: overflow");
2916 	}
2917 
2918 	STAT_MOEA64(moea64_pvo_entries++);
2919 
2920 	if (pvo->pvo_pmap == kernel_pmap)
2921 		isync();
2922 
2923 #ifdef __powerpc64__
2924 	/*
2925 	 * Make sure all our bootstrap mappings are in the SLB as soon
2926 	 * as virtual memory is switched on.
2927 	 */
2928 	if (!pmap_bootstrapped)
2929 		moea64_bootstrap_slb_prefault(PVO_VADDR(pvo),
2930 		    pvo->pvo_vaddr & PVO_LARGE);
2931 #endif
2932 
2933 	return (0);
2934 }
2935 
2936 static void
2937 moea64_pvo_remove_from_pmap(struct pvo_entry *pvo)
2938 {
2939 	struct	vm_page *pg;
2940 	int32_t refchg;
2941 
2942 	KASSERT(pvo->pvo_pmap != NULL, ("Trying to remove PVO with no pmap"));
2943 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2944 	KASSERT(!(pvo->pvo_vaddr & PVO_DEAD), ("Trying to remove dead PVO"));
2945 
2946 	/*
2947 	 * If there is an active pte entry, we need to deactivate it
2948 	 */
2949 	refchg = moea64_pte_unset(pvo);
2950 	if (refchg < 0) {
2951 		/*
2952 		 * If it was evicted from the page table, be pessimistic and
2953 		 * dirty the page.
2954 		 */
2955 		if (pvo->pvo_pte.prot & VM_PROT_WRITE)
2956 			refchg = LPTE_CHG;
2957 		else
2958 			refchg = 0;
2959 	}
2960 
2961 	/*
2962 	 * Update our statistics.
2963 	 */
2964 	pvo->pvo_pmap->pm_stats.resident_count--;
2965 	if (pvo->pvo_vaddr & PVO_WIRED)
2966 		pvo->pvo_pmap->pm_stats.wired_count--;
2967 
2968 	/*
2969 	 * Remove this PVO from the pmap list.
2970 	 */
2971 	RB_REMOVE(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2972 
2973 	/*
2974 	 * Mark this for the next sweep
2975 	 */
2976 	pvo->pvo_vaddr |= PVO_DEAD;
2977 
2978 	/* Send RC bits to VM */
2979 	if ((pvo->pvo_vaddr & PVO_MANAGED) &&
2980 	    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
2981 		pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2982 		if (pg != NULL) {
2983 			refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2984 			if (refchg & LPTE_CHG)
2985 				vm_page_dirty(pg);
2986 			if (refchg & LPTE_REF)
2987 				vm_page_aflag_set(pg, PGA_REFERENCED);
2988 		}
2989 	}
2990 }
2991 
2992 static inline void
2993 moea64_pvo_remove_from_page_locked(struct pvo_entry *pvo,
2994     vm_page_t m)
2995 {
2996 
2997 	KASSERT(pvo->pvo_vaddr & PVO_DEAD, ("Trying to delink live page"));
2998 
2999 	/* Use NULL pmaps as a sentinel for races in page deletion */
3000 	if (pvo->pvo_pmap == NULL)
3001 		return;
3002 	pvo->pvo_pmap = NULL;
3003 
3004 	/*
3005 	 * Update vm about page writeability/executability if managed
3006 	 */
3007 	PV_LOCKASSERT(PVO_PADDR(pvo));
3008 	if (pvo->pvo_vaddr & PVO_MANAGED) {
3009 		if (m != NULL) {
3010 			LIST_REMOVE(pvo, pvo_vlink);
3011 			if (LIST_EMPTY(vm_page_to_pvoh(m)))
3012 				vm_page_aflag_clear(m,
3013 				    PGA_WRITEABLE | PGA_EXECUTABLE);
3014 		}
3015 	}
3016 
3017 	STAT_MOEA64(moea64_pvo_entries--);
3018 	STAT_MOEA64(moea64_pvo_remove_calls++);
3019 }
3020 
3021 static void
3022 moea64_pvo_remove_from_page(struct pvo_entry *pvo)
3023 {
3024 	vm_page_t pg = NULL;
3025 
3026 	if (pvo->pvo_vaddr & PVO_MANAGED)
3027 		pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
3028 
3029 	PV_LOCK(PVO_PADDR(pvo));
3030 	moea64_pvo_remove_from_page_locked(pvo, pg);
3031 	PV_UNLOCK(PVO_PADDR(pvo));
3032 }
3033 
3034 static struct pvo_entry *
3035 moea64_pvo_find_va(pmap_t pm, vm_offset_t va)
3036 {
3037 	struct pvo_entry key;
3038 
3039 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
3040 
3041 	key.pvo_vaddr = va & ~ADDR_POFF;
3042 	return (RB_FIND(pvo_tree, &pm->pmap_pvo, &key));
3043 }
3044 
3045 static boolean_t
3046 moea64_query_bit(vm_page_t m, uint64_t ptebit)
3047 {
3048 	struct	pvo_entry *pvo;
3049 	int64_t ret;
3050 	boolean_t rv;
3051 	vm_page_t sp;
3052 
3053 	/*
3054 	 * See if this bit is stored in the page already.
3055 	 *
3056 	 * For superpages, the bit is stored in the first vm page.
3057 	 */
3058 	if ((m->md.mdpg_attrs & ptebit) != 0 ||
3059 	    ((sp = PHYS_TO_VM_PAGE(VM_PAGE_TO_PHYS(m) & ~HPT_SP_MASK)) != NULL &&
3060 	     (sp->md.mdpg_attrs & (ptebit | MDPG_ATTR_SP)) ==
3061 	     (ptebit | MDPG_ATTR_SP)))
3062 		return (TRUE);
3063 
3064 	/*
3065 	 * Examine each PTE.  Sync so that any pending REF/CHG bits are
3066 	 * flushed to the PTEs.
3067 	 */
3068 	rv = FALSE;
3069 	powerpc_sync();
3070 	PV_PAGE_LOCK(m);
3071 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
3072 		if (PVO_IS_SP(pvo)) {
3073 			ret = moea64_sp_query(pvo, ptebit);
3074 			/*
3075 			 * If SP was not demoted, check its REF/CHG bits here.
3076 			 */
3077 			if (ret != -1) {
3078 				if ((ret & ptebit) != 0) {
3079 					rv = TRUE;
3080 					break;
3081 				}
3082 				continue;
3083 			}
3084 			/* else, fallthrough */
3085 		}
3086 
3087 		ret = 0;
3088 
3089 		/*
3090 		 * See if this pvo has a valid PTE.  if so, fetch the
3091 		 * REF/CHG bits from the valid PTE.  If the appropriate
3092 		 * ptebit is set, return success.
3093 		 */
3094 		PMAP_LOCK(pvo->pvo_pmap);
3095 		if (!(pvo->pvo_vaddr & PVO_DEAD))
3096 			ret = moea64_pte_synch(pvo);
3097 		PMAP_UNLOCK(pvo->pvo_pmap);
3098 
3099 		if (ret > 0) {
3100 			atomic_set_32(&m->md.mdpg_attrs,
3101 			    ret & (LPTE_CHG | LPTE_REF));
3102 			if (ret & ptebit) {
3103 				rv = TRUE;
3104 				break;
3105 			}
3106 		}
3107 	}
3108 	PV_PAGE_UNLOCK(m);
3109 
3110 	return (rv);
3111 }
3112 
3113 static u_int
3114 moea64_clear_bit(vm_page_t m, u_int64_t ptebit)
3115 {
3116 	u_int	count;
3117 	struct	pvo_entry *pvo;
3118 	int64_t ret;
3119 
3120 	/*
3121 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
3122 	 * we can reset the right ones).
3123 	 */
3124 	powerpc_sync();
3125 
3126 	/*
3127 	 * For each pvo entry, clear the pte's ptebit.
3128 	 */
3129 	count = 0;
3130 	PV_PAGE_LOCK(m);
3131 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
3132 		if (PVO_IS_SP(pvo)) {
3133 			if ((ret = moea64_sp_clear(pvo, m, ptebit)) != -1) {
3134 				count += ret;
3135 				continue;
3136 			}
3137 		}
3138 		ret = 0;
3139 
3140 		PMAP_LOCK(pvo->pvo_pmap);
3141 		if (!(pvo->pvo_vaddr & PVO_DEAD))
3142 			ret = moea64_pte_clear(pvo, ptebit);
3143 		PMAP_UNLOCK(pvo->pvo_pmap);
3144 
3145 		if (ret > 0 && (ret & ptebit))
3146 			count++;
3147 	}
3148 	atomic_clear_32(&m->md.mdpg_attrs, ptebit);
3149 	PV_PAGE_UNLOCK(m);
3150 
3151 	return (count);
3152 }
3153 
3154 boolean_t
3155 moea64_dev_direct_mapped(vm_paddr_t pa, vm_size_t size)
3156 {
3157 	struct pvo_entry *pvo, key;
3158 	vm_offset_t ppa;
3159 	int error = 0;
3160 
3161 	if (hw_direct_map && mem_valid(pa, size) == 0)
3162 		return (0);
3163 
3164 	PMAP_LOCK(kernel_pmap);
3165 	ppa = pa & ~ADDR_POFF;
3166 	key.pvo_vaddr = DMAP_BASE_ADDRESS + ppa;
3167 	for (pvo = RB_FIND(pvo_tree, &kernel_pmap->pmap_pvo, &key);
3168 	    ppa < pa + size; ppa += PAGE_SIZE,
3169 	    pvo = RB_NEXT(pvo_tree, &kernel_pmap->pmap_pvo, pvo)) {
3170 		if (pvo == NULL || PVO_PADDR(pvo) != ppa) {
3171 			error = EFAULT;
3172 			break;
3173 		}
3174 	}
3175 	PMAP_UNLOCK(kernel_pmap);
3176 
3177 	return (error);
3178 }
3179 
3180 /*
3181  * Map a set of physical memory pages into the kernel virtual
3182  * address space. Return a pointer to where it is mapped. This
3183  * routine is intended to be used for mapping device memory,
3184  * NOT real memory.
3185  */
3186 void *
3187 moea64_mapdev_attr(vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
3188 {
3189 	vm_offset_t va, tmpva, ppa, offset;
3190 
3191 	ppa = trunc_page(pa);
3192 	offset = pa & PAGE_MASK;
3193 	size = roundup2(offset + size, PAGE_SIZE);
3194 
3195 	va = kva_alloc(size);
3196 
3197 	if (!va)
3198 		panic("moea64_mapdev: Couldn't alloc kernel virtual memory");
3199 
3200 	for (tmpva = va; size > 0;) {
3201 		moea64_kenter_attr(tmpva, ppa, ma);
3202 		size -= PAGE_SIZE;
3203 		tmpva += PAGE_SIZE;
3204 		ppa += PAGE_SIZE;
3205 	}
3206 
3207 	return ((void *)(va + offset));
3208 }
3209 
3210 void *
3211 moea64_mapdev(vm_paddr_t pa, vm_size_t size)
3212 {
3213 
3214 	return moea64_mapdev_attr(pa, size, VM_MEMATTR_DEFAULT);
3215 }
3216 
3217 void
3218 moea64_unmapdev(vm_offset_t va, vm_size_t size)
3219 {
3220 	vm_offset_t base, offset;
3221 
3222 	base = trunc_page(va);
3223 	offset = va & PAGE_MASK;
3224 	size = roundup2(offset + size, PAGE_SIZE);
3225 
3226 	moea64_qremove(base, atop(size));
3227 	kva_free(base, size);
3228 }
3229 
3230 void
3231 moea64_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
3232 {
3233 	struct pvo_entry *pvo;
3234 	vm_offset_t lim;
3235 	vm_paddr_t pa;
3236 	vm_size_t len;
3237 
3238 	if (__predict_false(pm == NULL))
3239 		pm = &curthread->td_proc->p_vmspace->vm_pmap;
3240 
3241 	PMAP_LOCK(pm);
3242 	while (sz > 0) {
3243 		lim = round_page(va+1);
3244 		len = MIN(lim - va, sz);
3245 		pvo = moea64_pvo_find_va(pm, va & ~ADDR_POFF);
3246 		if (pvo != NULL && !(pvo->pvo_pte.pa & LPTE_I)) {
3247 			pa = PVO_PADDR(pvo) | (va & ADDR_POFF);
3248 			moea64_syncicache(pm, va, pa, len);
3249 		}
3250 		va += len;
3251 		sz -= len;
3252 	}
3253 	PMAP_UNLOCK(pm);
3254 }
3255 
3256 void
3257 moea64_dumpsys_map(vm_paddr_t pa, size_t sz, void **va)
3258 {
3259 
3260 	*va = (void *)(uintptr_t)pa;
3261 }
3262 
3263 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
3264 
3265 void
3266 moea64_scan_init()
3267 {
3268 	struct pvo_entry *pvo;
3269 	vm_offset_t va;
3270 	int i;
3271 
3272 	if (!do_minidump) {
3273 		/* Initialize phys. segments for dumpsys(). */
3274 		memset(&dump_map, 0, sizeof(dump_map));
3275 		mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
3276 		for (i = 0; i < pregions_sz; i++) {
3277 			dump_map[i].pa_start = pregions[i].mr_start;
3278 			dump_map[i].pa_size = pregions[i].mr_size;
3279 		}
3280 		return;
3281 	}
3282 
3283 	/* Virtual segments for minidumps: */
3284 	memset(&dump_map, 0, sizeof(dump_map));
3285 
3286 	/* 1st: kernel .data and .bss. */
3287 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
3288 	dump_map[0].pa_size = round_page((uintptr_t)_end) -
3289 	    dump_map[0].pa_start;
3290 
3291 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
3292 	dump_map[1].pa_start = (vm_paddr_t)(uintptr_t)msgbufp->msg_ptr;
3293 	dump_map[1].pa_size = round_page(msgbufp->msg_size);
3294 
3295 	/* 3rd: kernel VM. */
3296 	va = dump_map[1].pa_start + dump_map[1].pa_size;
3297 	/* Find start of next chunk (from va). */
3298 	while (va < virtual_end) {
3299 		/* Don't dump the buffer cache. */
3300 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
3301 			va = kmi.buffer_eva;
3302 			continue;
3303 		}
3304 		pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
3305 		if (pvo != NULL && !(pvo->pvo_vaddr & PVO_DEAD))
3306 			break;
3307 		va += PAGE_SIZE;
3308 	}
3309 	if (va < virtual_end) {
3310 		dump_map[2].pa_start = va;
3311 		va += PAGE_SIZE;
3312 		/* Find last page in chunk. */
3313 		while (va < virtual_end) {
3314 			/* Don't run into the buffer cache. */
3315 			if (va == kmi.buffer_sva)
3316 				break;
3317 			pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
3318 			if (pvo == NULL || (pvo->pvo_vaddr & PVO_DEAD))
3319 				break;
3320 			va += PAGE_SIZE;
3321 		}
3322 		dump_map[2].pa_size = va - dump_map[2].pa_start;
3323 	}
3324 }
3325 
3326 #ifdef __powerpc64__
3327 
3328 static size_t
3329 moea64_scan_pmap()
3330 {
3331 	struct pvo_entry *pvo;
3332 	vm_paddr_t pa, pa_end;
3333 	vm_offset_t va, pgva, kstart, kend, kstart_lp, kend_lp;
3334 	uint64_t lpsize;
3335 
3336 	lpsize = moea64_large_page_size;
3337 	kstart = trunc_page((vm_offset_t)_etext);
3338 	kend = round_page((vm_offset_t)_end);
3339 	kstart_lp = kstart & ~moea64_large_page_mask;
3340 	kend_lp = (kend + moea64_large_page_mask) & ~moea64_large_page_mask;
3341 
3342 	CTR4(KTR_PMAP, "moea64_scan_pmap: kstart=0x%016lx, kend=0x%016lx, "
3343 	    "kstart_lp=0x%016lx, kend_lp=0x%016lx",
3344 	    kstart, kend, kstart_lp, kend_lp);
3345 
3346 	PMAP_LOCK(kernel_pmap);
3347 	RB_FOREACH(pvo, pvo_tree, &kernel_pmap->pmap_pvo) {
3348 		va = pvo->pvo_vaddr;
3349 
3350 		if (va & PVO_DEAD)
3351 			continue;
3352 
3353 		/* Skip DMAP (except kernel area) */
3354 		if (va >= DMAP_BASE_ADDRESS && va <= DMAP_MAX_ADDRESS) {
3355 			if (va & PVO_LARGE) {
3356 				pgva = va & ~moea64_large_page_mask;
3357 				if (pgva < kstart_lp || pgva >= kend_lp)
3358 					continue;
3359 			} else {
3360 				pgva = trunc_page(va);
3361 				if (pgva < kstart || pgva >= kend)
3362 					continue;
3363 			}
3364 		}
3365 
3366 		pa = PVO_PADDR(pvo);
3367 
3368 		if (va & PVO_LARGE) {
3369 			pa_end = pa + lpsize;
3370 			for (; pa < pa_end; pa += PAGE_SIZE) {
3371 				if (is_dumpable(pa))
3372 					dump_add_page(pa);
3373 			}
3374 		} else {
3375 			if (is_dumpable(pa))
3376 				dump_add_page(pa);
3377 		}
3378 	}
3379 	PMAP_UNLOCK(kernel_pmap);
3380 
3381 	return (sizeof(struct lpte) * moea64_pteg_count * 8);
3382 }
3383 
3384 static struct dump_context dump_ctx;
3385 
3386 static void *
3387 moea64_dump_pmap_init(unsigned blkpgs)
3388 {
3389 	dump_ctx.ptex = 0;
3390 	dump_ctx.ptex_end = moea64_pteg_count * 8;
3391 	dump_ctx.blksz = blkpgs * PAGE_SIZE;
3392 	return (&dump_ctx);
3393 }
3394 
3395 #else
3396 
3397 static size_t
3398 moea64_scan_pmap()
3399 {
3400 	return (0);
3401 }
3402 
3403 static void *
3404 moea64_dump_pmap_init(unsigned blkpgs)
3405 {
3406 	return (NULL);
3407 }
3408 
3409 #endif
3410 
3411 #ifdef __powerpc64__
3412 static void
3413 moea64_map_range(vm_offset_t va, vm_paddr_t pa, vm_size_t npages)
3414 {
3415 
3416 	for (; npages > 0; --npages) {
3417 		if (moea64_large_page_size != 0 &&
3418 		    (pa & moea64_large_page_mask) == 0 &&
3419 		    (va & moea64_large_page_mask) == 0 &&
3420 		    npages >= (moea64_large_page_size >> PAGE_SHIFT)) {
3421 			PMAP_LOCK(kernel_pmap);
3422 			moea64_kenter_large(va, pa, 0, 0);
3423 			PMAP_UNLOCK(kernel_pmap);
3424 			pa += moea64_large_page_size;
3425 			va += moea64_large_page_size;
3426 			npages -= (moea64_large_page_size >> PAGE_SHIFT) - 1;
3427 		} else {
3428 			moea64_kenter(va, pa);
3429 			pa += PAGE_SIZE;
3430 			va += PAGE_SIZE;
3431 		}
3432 	}
3433 }
3434 
3435 static void
3436 moea64_page_array_startup(long pages)
3437 {
3438 	long dom_pages[MAXMEMDOM];
3439 	vm_paddr_t pa;
3440 	vm_offset_t va, vm_page_base;
3441 	vm_size_t needed, size;
3442 	long page;
3443 	int domain;
3444 	int i;
3445 
3446 	vm_page_base = 0xd000000000000000ULL;
3447 
3448 	/* Short-circuit single-domain systems. */
3449 	if (vm_ndomains == 1) {
3450 		size = round_page(pages * sizeof(struct vm_page));
3451 		pa = vm_phys_early_alloc(0, size);
3452 		vm_page_base = moea64_map(&vm_page_base,
3453 		    pa, pa + size, VM_PROT_READ | VM_PROT_WRITE);
3454 		vm_page_array_size = pages;
3455 		vm_page_array = (vm_page_t)vm_page_base;
3456 		return;
3457 	}
3458 
3459 	page = 0;
3460 	for (i = 0; i < MAXMEMDOM; i++)
3461 		dom_pages[i] = 0;
3462 
3463 	/* Now get the number of pages required per domain. */
3464 	for (i = 0; i < vm_phys_nsegs; i++) {
3465 		domain = vm_phys_segs[i].domain;
3466 		KASSERT(domain < MAXMEMDOM,
3467 		    ("Invalid vm_phys_segs NUMA domain %d!\n", domain));
3468 		/* Get size of vm_page_array needed for this segment. */
3469 		size = btoc(vm_phys_segs[i].end - vm_phys_segs[i].start);
3470 		dom_pages[domain] += size;
3471 	}
3472 
3473 	for (i = 0; phys_avail[i + 1] != 0; i+= 2) {
3474 		domain = _vm_phys_domain(phys_avail[i]);
3475 		KASSERT(domain < MAXMEMDOM,
3476 		    ("Invalid phys_avail NUMA domain %d!\n", domain));
3477 		size = btoc(phys_avail[i + 1] - phys_avail[i]);
3478 		dom_pages[domain] += size;
3479 	}
3480 
3481 	/*
3482 	 * Map in chunks that can get us all 16MB pages.  There will be some
3483 	 * overlap between domains, but that's acceptable for now.
3484 	 */
3485 	vm_page_array_size = 0;
3486 	va = vm_page_base;
3487 	for (i = 0; i < MAXMEMDOM && vm_page_array_size < pages; i++) {
3488 		if (dom_pages[i] == 0)
3489 			continue;
3490 		size = ulmin(pages - vm_page_array_size, dom_pages[i]);
3491 		size = round_page(size * sizeof(struct vm_page));
3492 		needed = size;
3493 		size = roundup2(size, moea64_large_page_size);
3494 		pa = vm_phys_early_alloc(i, size);
3495 		vm_page_array_size += size / sizeof(struct vm_page);
3496 		moea64_map_range(va, pa, size >> PAGE_SHIFT);
3497 		/* Scoot up domain 0, to reduce the domain page overlap. */
3498 		if (i == 0)
3499 			vm_page_base += size - needed;
3500 		va += size;
3501 	}
3502 	vm_page_array = (vm_page_t)vm_page_base;
3503 	vm_page_array_size = pages;
3504 }
3505 #endif
3506 
3507 static int64_t
3508 moea64_null_method(void)
3509 {
3510 	return (0);
3511 }
3512 
3513 static int64_t moea64_pte_replace_default(struct pvo_entry *pvo, int flags)
3514 {
3515 	int64_t refchg;
3516 
3517 	refchg = moea64_pte_unset(pvo);
3518 	moea64_pte_insert(pvo);
3519 
3520 	return (refchg);
3521 }
3522 
3523 struct moea64_funcs *moea64_ops;
3524 
3525 #define DEFINE_OEA64_IFUNC(ret, func, args, def)		\
3526 	DEFINE_IFUNC(, ret, moea64_##func, args) {		\
3527 		moea64_##func##_t f;				\
3528 		if (moea64_ops == NULL)				\
3529 			return ((moea64_##func##_t)def);	\
3530 		f = moea64_ops->func;				\
3531 		return (f != NULL ? f : (moea64_##func##_t)def);\
3532 	}
3533 
3534 DEFINE_OEA64_IFUNC(int64_t, pte_replace, (struct pvo_entry *, int),
3535     moea64_pte_replace_default)
3536 DEFINE_OEA64_IFUNC(int64_t, pte_insert, (struct pvo_entry *), moea64_null_method)
3537 DEFINE_OEA64_IFUNC(int64_t, pte_unset, (struct pvo_entry *), moea64_null_method)
3538 DEFINE_OEA64_IFUNC(int64_t, pte_clear, (struct pvo_entry *, uint64_t),
3539     moea64_null_method)
3540 DEFINE_OEA64_IFUNC(int64_t, pte_synch, (struct pvo_entry *), moea64_null_method)
3541 DEFINE_OEA64_IFUNC(int64_t, pte_insert_sp, (struct pvo_entry *), moea64_null_method)
3542 DEFINE_OEA64_IFUNC(int64_t, pte_unset_sp, (struct pvo_entry *), moea64_null_method)
3543 DEFINE_OEA64_IFUNC(int64_t, pte_replace_sp, (struct pvo_entry *), moea64_null_method)
3544 
3545 /* Superpage functions */
3546 
3547 /* MMU interface */
3548 
3549 static bool
3550 moea64_ps_enabled(pmap_t pmap)
3551 {
3552 	return (superpages_enabled);
3553 }
3554 
3555 static void
3556 moea64_align_superpage(vm_object_t object, vm_ooffset_t offset,
3557     vm_offset_t *addr, vm_size_t size)
3558 {
3559 	vm_offset_t sp_offset;
3560 
3561 	if (size < HPT_SP_SIZE)
3562 		return;
3563 
3564 	CTR4(KTR_PMAP, "%s: offs=%#jx, addr=%p, size=%#jx",
3565 	    __func__, (uintmax_t)offset, addr, (uintmax_t)size);
3566 
3567 	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
3568 		offset += ptoa(object->pg_color);
3569 	sp_offset = offset & HPT_SP_MASK;
3570 	if (size - ((HPT_SP_SIZE - sp_offset) & HPT_SP_MASK) < HPT_SP_SIZE ||
3571 	    (*addr & HPT_SP_MASK) == sp_offset)
3572 		return;
3573 	if ((*addr & HPT_SP_MASK) < sp_offset)
3574 		*addr = (*addr & ~HPT_SP_MASK) + sp_offset;
3575 	else
3576 		*addr = ((*addr + HPT_SP_MASK) & ~HPT_SP_MASK) + sp_offset;
3577 }
3578 
3579 /* Helpers */
3580 
3581 static __inline void
3582 moea64_pvo_cleanup(struct pvo_dlist *tofree)
3583 {
3584 	struct pvo_entry *pvo;
3585 
3586 	/* clean up */
3587 	while (!SLIST_EMPTY(tofree)) {
3588 		pvo = SLIST_FIRST(tofree);
3589 		SLIST_REMOVE_HEAD(tofree, pvo_dlink);
3590 		if (pvo->pvo_vaddr & PVO_DEAD)
3591 			moea64_pvo_remove_from_page(pvo);
3592 		free_pvo_entry(pvo);
3593 	}
3594 }
3595 
3596 static __inline uint16_t
3597 pvo_to_vmpage_flags(struct pvo_entry *pvo)
3598 {
3599 	uint16_t flags;
3600 
3601 	flags = 0;
3602 	if ((pvo->pvo_pte.prot & VM_PROT_WRITE) != 0)
3603 		flags |= PGA_WRITEABLE;
3604 	if ((pvo->pvo_pte.prot & VM_PROT_EXECUTE) != 0)
3605 		flags |= PGA_EXECUTABLE;
3606 
3607 	return (flags);
3608 }
3609 
3610 /*
3611  * Check if the given pvo and its superpage are in sva-eva range.
3612  */
3613 static __inline bool
3614 moea64_sp_pvo_in_range(struct pvo_entry *pvo, vm_offset_t sva, vm_offset_t eva)
3615 {
3616 	vm_offset_t spva;
3617 
3618 	spva = PVO_VADDR(pvo) & ~HPT_SP_MASK;
3619 	if (spva >= sva && spva + HPT_SP_SIZE <= eva) {
3620 		/*
3621 		 * Because this function is intended to be called from loops
3622 		 * that iterate over ordered pvo entries, if the condition
3623 		 * above is true then the pvo must be the first of its
3624 		 * superpage.
3625 		 */
3626 		KASSERT(PVO_VADDR(pvo) == spva,
3627 		    ("%s: unexpected unaligned superpage pvo", __func__));
3628 		return (true);
3629 	}
3630 	return (false);
3631 }
3632 
3633 /*
3634  * Update vm about the REF/CHG bits if the superpage is managed and
3635  * has (or had) write access.
3636  */
3637 static void
3638 moea64_sp_refchg_process(struct pvo_entry *sp, vm_page_t m,
3639     int64_t sp_refchg, vm_prot_t prot)
3640 {
3641 	vm_page_t m_end;
3642 	int64_t refchg;
3643 
3644 	if ((sp->pvo_vaddr & PVO_MANAGED) != 0 && (prot & VM_PROT_WRITE) != 0) {
3645 		for (m_end = &m[HPT_SP_PAGES]; m < m_end; m++) {
3646 			refchg = sp_refchg |
3647 			    atomic_readandclear_32(&m->md.mdpg_attrs);
3648 			if (refchg & LPTE_CHG)
3649 				vm_page_dirty(m);
3650 			if (refchg & LPTE_REF)
3651 				vm_page_aflag_set(m, PGA_REFERENCED);
3652 		}
3653 	}
3654 }
3655 
3656 /* Superpage ops */
3657 
3658 static int
3659 moea64_sp_enter(pmap_t pmap, vm_offset_t va, vm_page_t m,
3660     vm_prot_t prot, u_int flags, int8_t psind)
3661 {
3662 	struct pvo_entry *pvo, **pvos;
3663 	struct pvo_head *pvo_head;
3664 	vm_offset_t sva;
3665 	vm_page_t sm;
3666 	vm_paddr_t pa, spa;
3667 	bool sync;
3668 	struct pvo_dlist tofree;
3669 	int error, i;
3670 	uint16_t aflags;
3671 
3672 	KASSERT((va & HPT_SP_MASK) == 0, ("%s: va %#jx unaligned",
3673 	    __func__, (uintmax_t)va));
3674 	KASSERT(psind == 1, ("%s: invalid psind: %d", __func__, psind));
3675 	KASSERT(m->psind == 1, ("%s: invalid m->psind: %d",
3676 	    __func__, m->psind));
3677 	KASSERT(pmap != kernel_pmap,
3678 	    ("%s: function called with kernel pmap", __func__));
3679 
3680 	CTR5(KTR_PMAP, "%s: va=%#jx, pa=%#jx, prot=%#x, flags=%#x, psind=1",
3681 	    __func__, (uintmax_t)va, (uintmax_t)VM_PAGE_TO_PHYS(m),
3682 	    prot, flags);
3683 
3684 	SLIST_INIT(&tofree);
3685 
3686 	sva = va;
3687 	sm = m;
3688 	spa = pa = VM_PAGE_TO_PHYS(sm);
3689 
3690 	/* Try to allocate all PVOs first, to make failure handling easier. */
3691 	pvos = malloc(HPT_SP_PAGES * sizeof(struct pvo_entry *), M_TEMP,
3692 	    M_NOWAIT);
3693 	if (pvos == NULL) {
3694 		CTR1(KTR_PMAP, "%s: failed to alloc pvo array", __func__);
3695 		return (KERN_RESOURCE_SHORTAGE);
3696 	}
3697 
3698 	for (i = 0; i < HPT_SP_PAGES; i++) {
3699 		pvos[i] = alloc_pvo_entry(0);
3700 		if (pvos[i] == NULL) {
3701 			CTR1(KTR_PMAP, "%s: failed to alloc pvo", __func__);
3702 			for (i = i - 1; i >= 0; i--)
3703 				free_pvo_entry(pvos[i]);
3704 			free(pvos, M_TEMP);
3705 			return (KERN_RESOURCE_SHORTAGE);
3706 		}
3707 	}
3708 
3709 	SP_PV_LOCK_ALIGNED(spa);
3710 	PMAP_LOCK(pmap);
3711 
3712 	/* Note: moea64_remove_locked() also clears cached REF/CHG bits. */
3713 	moea64_remove_locked(pmap, va, va + HPT_SP_SIZE, &tofree);
3714 
3715 	/* Enter pages */
3716 	for (i = 0; i < HPT_SP_PAGES;
3717 	    i++, va += PAGE_SIZE, pa += PAGE_SIZE, m++) {
3718 		pvo = pvos[i];
3719 
3720 		pvo->pvo_pte.prot = prot;
3721 		pvo->pvo_pte.pa = (pa & ~LPTE_LP_MASK) | LPTE_LP_4K_16M |
3722 		    moea64_calc_wimg(pa, pmap_page_get_memattr(m));
3723 
3724 		if ((flags & PMAP_ENTER_WIRED) != 0)
3725 			pvo->pvo_vaddr |= PVO_WIRED;
3726 		pvo->pvo_vaddr |= PVO_LARGE;
3727 
3728 		if ((m->oflags & VPO_UNMANAGED) != 0)
3729 			pvo_head = NULL;
3730 		else {
3731 			pvo_head = &m->md.mdpg_pvoh;
3732 			pvo->pvo_vaddr |= PVO_MANAGED;
3733 		}
3734 
3735 		init_pvo_entry(pvo, pmap, va);
3736 
3737 		error = moea64_pvo_enter(pvo, pvo_head, NULL);
3738 		/*
3739 		 * All superpage PVOs were previously removed, so no errors
3740 		 * should occur while inserting the new ones.
3741 		 */
3742 		KASSERT(error == 0, ("%s: unexpected error "
3743 			    "when inserting superpage PVO: %d",
3744 			    __func__, error));
3745 	}
3746 
3747 	PMAP_UNLOCK(pmap);
3748 	SP_PV_UNLOCK_ALIGNED(spa);
3749 
3750 	sync = (sm->a.flags & PGA_EXECUTABLE) == 0;
3751 	/* Note: moea64_pvo_cleanup() also clears page prot. flags. */
3752 	moea64_pvo_cleanup(&tofree);
3753 	pvo = pvos[0];
3754 
3755 	/* Set vm page flags */
3756 	aflags = pvo_to_vmpage_flags(pvo);
3757 	if (aflags != 0)
3758 		for (m = sm; m < &sm[HPT_SP_PAGES]; m++)
3759 			vm_page_aflag_set(m, aflags);
3760 
3761 	/*
3762 	 * Flush the page from the instruction cache if this page is
3763 	 * mapped executable and cacheable.
3764 	 */
3765 	if (sync && (pvo->pvo_pte.pa & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0)
3766 		moea64_syncicache(pmap, sva, spa, HPT_SP_SIZE);
3767 
3768 	atomic_add_long(&sp_mappings, 1);
3769 	CTR3(KTR_PMAP, "%s: SP success for va %#jx in pmap %p",
3770 	    __func__, (uintmax_t)sva, pmap);
3771 
3772 	free(pvos, M_TEMP);
3773 	return (KERN_SUCCESS);
3774 }
3775 
3776 static void
3777 moea64_sp_promote(pmap_t pmap, vm_offset_t va, vm_page_t m)
3778 {
3779 	struct pvo_entry *first, *pvo;
3780 	vm_paddr_t pa, pa_end;
3781 	vm_offset_t sva, va_end;
3782 	int64_t sp_refchg;
3783 
3784 	/* This CTR may generate a lot of output. */
3785 	/* CTR2(KTR_PMAP, "%s: va=%#jx", __func__, (uintmax_t)va); */
3786 
3787 	va &= ~HPT_SP_MASK;
3788 	sva = va;
3789 	/* Get superpage */
3790 	pa = VM_PAGE_TO_PHYS(m) & ~HPT_SP_MASK;
3791 	m = PHYS_TO_VM_PAGE(pa);
3792 
3793 	PMAP_LOCK(pmap);
3794 
3795 	/*
3796 	 * Check if all pages meet promotion criteria.
3797 	 *
3798 	 * XXX In some cases the loop below may be executed for each or most
3799 	 * of the entered pages of a superpage, which can be expensive
3800 	 * (although it was not profiled) and need some optimization.
3801 	 *
3802 	 * Some cases where this seems to happen are:
3803 	 * - When a superpage is first entered read-only and later becomes
3804 	 *   read-write.
3805 	 * - When some of the superpage's virtual addresses map to previously
3806 	 *   wired/cached pages while others map to pages allocated from a
3807 	 *   different physical address range. A common scenario where this
3808 	 *   happens is when mmap'ing a file that is already present in FS
3809 	 *   block cache and doesn't fill a superpage.
3810 	 */
3811 	first = pvo = moea64_pvo_find_va(pmap, sva);
3812 	for (pa_end = pa + HPT_SP_SIZE;
3813 	    pa < pa_end; pa += PAGE_SIZE, va += PAGE_SIZE) {
3814 		if (pvo == NULL || (pvo->pvo_vaddr & PVO_DEAD) != 0) {
3815 			CTR3(KTR_PMAP,
3816 			    "%s: NULL or dead PVO: pmap=%p, va=%#jx",
3817 			    __func__, pmap, (uintmax_t)va);
3818 			goto error;
3819 		}
3820 		if (PVO_PADDR(pvo) != pa) {
3821 			CTR5(KTR_PMAP, "%s: PAs don't match: "
3822 			    "pmap=%p, va=%#jx, pvo_pa=%#jx, exp_pa=%#jx",
3823 			    __func__, pmap, (uintmax_t)va,
3824 			    (uintmax_t)PVO_PADDR(pvo), (uintmax_t)pa);
3825 			atomic_add_long(&sp_p_fail_pa, 1);
3826 			goto error;
3827 		}
3828 		if ((first->pvo_vaddr & PVO_FLAGS_PROMOTE) !=
3829 		    (pvo->pvo_vaddr & PVO_FLAGS_PROMOTE)) {
3830 			CTR5(KTR_PMAP, "%s: PVO flags don't match: "
3831 			    "pmap=%p, va=%#jx, pvo_flags=%#jx, exp_flags=%#jx",
3832 			    __func__, pmap, (uintmax_t)va,
3833 			    (uintmax_t)(pvo->pvo_vaddr & PVO_FLAGS_PROMOTE),
3834 			    (uintmax_t)(first->pvo_vaddr & PVO_FLAGS_PROMOTE));
3835 			atomic_add_long(&sp_p_fail_flags, 1);
3836 			goto error;
3837 		}
3838 		if (first->pvo_pte.prot != pvo->pvo_pte.prot) {
3839 			CTR5(KTR_PMAP, "%s: PVO protections don't match: "
3840 			    "pmap=%p, va=%#jx, pvo_prot=%#x, exp_prot=%#x",
3841 			    __func__, pmap, (uintmax_t)va,
3842 			    pvo->pvo_pte.prot, first->pvo_pte.prot);
3843 			atomic_add_long(&sp_p_fail_prot, 1);
3844 			goto error;
3845 		}
3846 		if ((first->pvo_pte.pa & LPTE_WIMG) !=
3847 		    (pvo->pvo_pte.pa & LPTE_WIMG)) {
3848 			CTR5(KTR_PMAP, "%s: WIMG bits don't match: "
3849 			    "pmap=%p, va=%#jx, pvo_wimg=%#jx, exp_wimg=%#jx",
3850 			    __func__, pmap, (uintmax_t)va,
3851 			    (uintmax_t)(pvo->pvo_pte.pa & LPTE_WIMG),
3852 			    (uintmax_t)(first->pvo_pte.pa & LPTE_WIMG));
3853 			atomic_add_long(&sp_p_fail_wimg, 1);
3854 			goto error;
3855 		}
3856 
3857 		pvo = RB_NEXT(pvo_tree, &pmap->pmap_pvo, pvo);
3858 	}
3859 
3860 	/* All OK, promote. */
3861 
3862 	/*
3863 	 * Handle superpage REF/CHG bits. If REF or CHG is set in
3864 	 * any page, then it must be set in the superpage.
3865 	 *
3866 	 * Instead of querying each page, we take advantage of two facts:
3867 	 * 1- If a page is being promoted, it was referenced.
3868 	 * 2- If promoted pages are writable, they were modified.
3869 	 */
3870 	sp_refchg = LPTE_REF |
3871 	    ((first->pvo_pte.prot & VM_PROT_WRITE) != 0 ? LPTE_CHG : 0);
3872 
3873 	/* Promote pages */
3874 
3875 	for (pvo = first, va_end = PVO_VADDR(pvo) + HPT_SP_SIZE;
3876 	    pvo != NULL && PVO_VADDR(pvo) < va_end;
3877 	    pvo = RB_NEXT(pvo_tree, &pmap->pmap_pvo, pvo)) {
3878 		pvo->pvo_pte.pa &= ~LPTE_LP_MASK;
3879 		pvo->pvo_pte.pa |= LPTE_LP_4K_16M;
3880 		pvo->pvo_vaddr |= PVO_LARGE;
3881 	}
3882 	moea64_pte_replace_sp(first);
3883 
3884 	/* Send REF/CHG bits to VM */
3885 	moea64_sp_refchg_process(first, m, sp_refchg, first->pvo_pte.prot);
3886 
3887 	/* Use first page to cache REF/CHG bits */
3888 	atomic_set_32(&m->md.mdpg_attrs, sp_refchg | MDPG_ATTR_SP);
3889 
3890 	PMAP_UNLOCK(pmap);
3891 
3892 	atomic_add_long(&sp_mappings, 1);
3893 	atomic_add_long(&sp_promotions, 1);
3894 	CTR3(KTR_PMAP, "%s: success for va %#jx in pmap %p",
3895 	    __func__, (uintmax_t)sva, pmap);
3896 	return;
3897 
3898 error:
3899 	atomic_add_long(&sp_p_failures, 1);
3900 	PMAP_UNLOCK(pmap);
3901 }
3902 
3903 static void
3904 moea64_sp_demote_aligned(struct pvo_entry *sp)
3905 {
3906 	struct pvo_entry *pvo;
3907 	vm_offset_t va, va_end;
3908 	vm_paddr_t pa;
3909 	vm_page_t m;
3910 	pmap_t pmap;
3911 	int64_t refchg;
3912 
3913 	CTR2(KTR_PMAP, "%s: va=%#jx", __func__, (uintmax_t)PVO_VADDR(sp));
3914 
3915 	pmap = sp->pvo_pmap;
3916 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3917 
3918 	pvo = sp;
3919 
3920 	/* Demote pages */
3921 
3922 	va = PVO_VADDR(pvo);
3923 	pa = PVO_PADDR(pvo);
3924 	m = PHYS_TO_VM_PAGE(pa);
3925 
3926 	for (pvo = sp, va_end = va + HPT_SP_SIZE;
3927 	    pvo != NULL && PVO_VADDR(pvo) < va_end;
3928 	    pvo = RB_NEXT(pvo_tree, &pmap->pmap_pvo, pvo),
3929 	    va += PAGE_SIZE, pa += PAGE_SIZE) {
3930 		KASSERT(pvo && PVO_VADDR(pvo) == va,
3931 		    ("%s: missing PVO for va %#jx", __func__, (uintmax_t)va));
3932 
3933 		pvo->pvo_vaddr &= ~PVO_LARGE;
3934 		pvo->pvo_pte.pa &= ~LPTE_RPGN;
3935 		pvo->pvo_pte.pa |= pa;
3936 
3937 	}
3938 	refchg = moea64_pte_replace_sp(sp);
3939 
3940 	/*
3941 	 * Clear SP flag
3942 	 *
3943 	 * XXX It is possible that another pmap has this page mapped as
3944 	 *     part of a superpage, but as the SP flag is used only for
3945 	 *     caching SP REF/CHG bits, that will be queried if not set
3946 	 *     in cache, it should be ok to clear it here.
3947 	 */
3948 	atomic_clear_32(&m->md.mdpg_attrs, MDPG_ATTR_SP);
3949 
3950 	/*
3951 	 * Handle superpage REF/CHG bits. A bit set in the superpage
3952 	 * means all pages should consider it set.
3953 	 */
3954 	moea64_sp_refchg_process(sp, m, refchg, sp->pvo_pte.prot);
3955 
3956 	atomic_add_long(&sp_demotions, 1);
3957 	CTR3(KTR_PMAP, "%s: success for va %#jx in pmap %p",
3958 	    __func__, (uintmax_t)PVO_VADDR(sp), pmap);
3959 }
3960 
3961 static void
3962 moea64_sp_demote(struct pvo_entry *pvo)
3963 {
3964 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
3965 
3966 	if ((PVO_VADDR(pvo) & HPT_SP_MASK) != 0) {
3967 		pvo = moea64_pvo_find_va(pvo->pvo_pmap,
3968 		    PVO_VADDR(pvo) & ~HPT_SP_MASK);
3969 		KASSERT(pvo != NULL, ("%s: missing PVO for va %#jx",
3970 		     __func__, (uintmax_t)(PVO_VADDR(pvo) & ~HPT_SP_MASK)));
3971 	}
3972 	moea64_sp_demote_aligned(pvo);
3973 }
3974 
3975 static struct pvo_entry *
3976 moea64_sp_unwire(struct pvo_entry *sp)
3977 {
3978 	struct pvo_entry *pvo, *prev;
3979 	vm_offset_t eva;
3980 	pmap_t pm;
3981 	int64_t ret, refchg;
3982 
3983 	CTR2(KTR_PMAP, "%s: va=%#jx", __func__, (uintmax_t)PVO_VADDR(sp));
3984 
3985 	pm = sp->pvo_pmap;
3986 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
3987 
3988 	eva = PVO_VADDR(sp) + HPT_SP_SIZE;
3989 	refchg = 0;
3990 	for (pvo = sp; pvo != NULL && PVO_VADDR(pvo) < eva;
3991 	    prev = pvo, pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
3992 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
3993 			panic("%s: pvo %p is missing PVO_WIRED",
3994 			    __func__, pvo);
3995 		pvo->pvo_vaddr &= ~PVO_WIRED;
3996 
3997 		ret = moea64_pte_replace(pvo, 0 /* No invalidation */);
3998 		if (ret < 0)
3999 			refchg |= LPTE_CHG;
4000 		else
4001 			refchg |= ret;
4002 
4003 		pm->pm_stats.wired_count--;
4004 	}
4005 
4006 	/* Send REF/CHG bits to VM */
4007 	moea64_sp_refchg_process(sp, PHYS_TO_VM_PAGE(PVO_PADDR(sp)),
4008 	    refchg, sp->pvo_pte.prot);
4009 
4010 	return (prev);
4011 }
4012 
4013 static struct pvo_entry *
4014 moea64_sp_protect(struct pvo_entry *sp, vm_prot_t prot)
4015 {
4016 	struct pvo_entry *pvo, *prev;
4017 	vm_offset_t eva;
4018 	pmap_t pm;
4019 	vm_page_t m, m_end;
4020 	int64_t ret, refchg;
4021 	vm_prot_t oldprot;
4022 
4023 	CTR3(KTR_PMAP, "%s: va=%#jx, prot=%x",
4024 	    __func__, (uintmax_t)PVO_VADDR(sp), prot);
4025 
4026 	pm = sp->pvo_pmap;
4027 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
4028 
4029 	oldprot = sp->pvo_pte.prot;
4030 	m = PHYS_TO_VM_PAGE(PVO_PADDR(sp));
4031 	KASSERT(m != NULL, ("%s: missing vm page for pa %#jx",
4032 	    __func__, (uintmax_t)PVO_PADDR(sp)));
4033 	eva = PVO_VADDR(sp) + HPT_SP_SIZE;
4034 	refchg = 0;
4035 
4036 	for (pvo = sp; pvo != NULL && PVO_VADDR(pvo) < eva;
4037 	    prev = pvo, pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
4038 		pvo->pvo_pte.prot = prot;
4039 		/*
4040 		 * If the PVO is in the page table, update mapping
4041 		 */
4042 		ret = moea64_pte_replace(pvo, MOEA64_PTE_PROT_UPDATE);
4043 		if (ret < 0)
4044 			refchg |= LPTE_CHG;
4045 		else
4046 			refchg |= ret;
4047 	}
4048 
4049 	/* Send REF/CHG bits to VM */
4050 	moea64_sp_refchg_process(sp, m, refchg, oldprot);
4051 
4052 	/* Handle pages that became executable */
4053 	if ((m->a.flags & PGA_EXECUTABLE) == 0 &&
4054 	    (sp->pvo_pte.pa & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
4055 		if ((m->oflags & VPO_UNMANAGED) == 0)
4056 			for (m_end = &m[HPT_SP_PAGES]; m < m_end; m++)
4057 				vm_page_aflag_set(m, PGA_EXECUTABLE);
4058 		moea64_syncicache(pm, PVO_VADDR(sp), PVO_PADDR(sp),
4059 		    HPT_SP_SIZE);
4060 	}
4061 
4062 	return (prev);
4063 }
4064 
4065 static struct pvo_entry *
4066 moea64_sp_remove(struct pvo_entry *sp, struct pvo_dlist *tofree)
4067 {
4068 	struct pvo_entry *pvo, *tpvo;
4069 	vm_offset_t eva;
4070 	pmap_t pm;
4071 
4072 	CTR2(KTR_PMAP, "%s: va=%#jx", __func__, (uintmax_t)PVO_VADDR(sp));
4073 
4074 	pm = sp->pvo_pmap;
4075 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
4076 
4077 	eva = PVO_VADDR(sp) + HPT_SP_SIZE;
4078 	for (pvo = sp; pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
4079 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
4080 
4081 		/*
4082 		 * For locking reasons, remove this from the page table and
4083 		 * pmap, but save delinking from the vm_page for a second
4084 		 * pass
4085 		 */
4086 		moea64_pvo_remove_from_pmap(pvo);
4087 		SLIST_INSERT_HEAD(tofree, pvo, pvo_dlink);
4088 	}
4089 
4090 	/*
4091 	 * Clear SP bit
4092 	 *
4093 	 * XXX See comment in moea64_sp_demote_aligned() for why it's
4094 	 *     ok to always clear the SP bit on remove/demote.
4095 	 */
4096 	atomic_clear_32(&PHYS_TO_VM_PAGE(PVO_PADDR(sp))->md.mdpg_attrs,
4097 	    MDPG_ATTR_SP);
4098 
4099 	return (tpvo);
4100 }
4101 
4102 static int64_t
4103 moea64_sp_query_locked(struct pvo_entry *pvo, uint64_t ptebit)
4104 {
4105 	int64_t refchg, ret;
4106 	vm_offset_t eva;
4107 	vm_page_t m;
4108 	pmap_t pmap;
4109 	struct pvo_entry *sp;
4110 
4111 	pmap = pvo->pvo_pmap;
4112 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4113 
4114 	/* Get first SP PVO */
4115 	if ((PVO_VADDR(pvo) & HPT_SP_MASK) != 0) {
4116 		sp = moea64_pvo_find_va(pmap, PVO_VADDR(pvo) & ~HPT_SP_MASK);
4117 		KASSERT(sp != NULL, ("%s: missing PVO for va %#jx",
4118 		     __func__, (uintmax_t)(PVO_VADDR(pvo) & ~HPT_SP_MASK)));
4119 	} else
4120 		sp = pvo;
4121 	eva = PVO_VADDR(sp) + HPT_SP_SIZE;
4122 
4123 	refchg = 0;
4124 	for (pvo = sp; pvo != NULL && PVO_VADDR(pvo) < eva;
4125 	    pvo = RB_NEXT(pvo_tree, &pmap->pmap_pvo, pvo)) {
4126 		ret = moea64_pte_synch(pvo);
4127 		if (ret > 0) {
4128 			refchg |= ret & (LPTE_CHG | LPTE_REF);
4129 			if ((refchg & ptebit) != 0)
4130 				break;
4131 		}
4132 	}
4133 
4134 	/* Save results */
4135 	if (refchg != 0) {
4136 		m = PHYS_TO_VM_PAGE(PVO_PADDR(sp));
4137 		atomic_set_32(&m->md.mdpg_attrs, refchg | MDPG_ATTR_SP);
4138 	}
4139 
4140 	return (refchg);
4141 }
4142 
4143 static int64_t
4144 moea64_sp_query(struct pvo_entry *pvo, uint64_t ptebit)
4145 {
4146 	int64_t refchg;
4147 	pmap_t pmap;
4148 
4149 	pmap = pvo->pvo_pmap;
4150 	PMAP_LOCK(pmap);
4151 
4152 	/*
4153 	 * Check if SP was demoted/removed before pmap lock was acquired.
4154 	 */
4155 	if (!PVO_IS_SP(pvo) || (pvo->pvo_vaddr & PVO_DEAD) != 0) {
4156 		CTR2(KTR_PMAP, "%s: demoted/removed: pa=%#jx",
4157 		    __func__, (uintmax_t)PVO_PADDR(pvo));
4158 		PMAP_UNLOCK(pmap);
4159 		return (-1);
4160 	}
4161 
4162 	refchg = moea64_sp_query_locked(pvo, ptebit);
4163 	PMAP_UNLOCK(pmap);
4164 
4165 	CTR4(KTR_PMAP, "%s: va=%#jx, pa=%#jx: refchg=%#jx",
4166 	    __func__, (uintmax_t)PVO_VADDR(pvo),
4167 	    (uintmax_t)PVO_PADDR(pvo), (uintmax_t)refchg);
4168 
4169 	return (refchg);
4170 }
4171 
4172 static int64_t
4173 moea64_sp_pvo_clear(struct pvo_entry *pvo, uint64_t ptebit)
4174 {
4175 	int64_t refchg, ret;
4176 	pmap_t pmap;
4177 	struct pvo_entry *sp;
4178 	vm_offset_t eva;
4179 	vm_page_t m;
4180 
4181 	pmap = pvo->pvo_pmap;
4182 	PMAP_LOCK(pmap);
4183 
4184 	/*
4185 	 * Check if SP was demoted/removed before pmap lock was acquired.
4186 	 */
4187 	if (!PVO_IS_SP(pvo) || (pvo->pvo_vaddr & PVO_DEAD) != 0) {
4188 		CTR2(KTR_PMAP, "%s: demoted/removed: pa=%#jx",
4189 		    __func__, (uintmax_t)PVO_PADDR(pvo));
4190 		PMAP_UNLOCK(pmap);
4191 		return (-1);
4192 	}
4193 
4194 	/* Get first SP PVO */
4195 	if ((PVO_VADDR(pvo) & HPT_SP_MASK) != 0) {
4196 		sp = moea64_pvo_find_va(pmap, PVO_VADDR(pvo) & ~HPT_SP_MASK);
4197 		KASSERT(sp != NULL, ("%s: missing PVO for va %#jx",
4198 		     __func__, (uintmax_t)(PVO_VADDR(pvo) & ~HPT_SP_MASK)));
4199 	} else
4200 		sp = pvo;
4201 	eva = PVO_VADDR(sp) + HPT_SP_SIZE;
4202 
4203 	refchg = 0;
4204 	for (pvo = sp; pvo != NULL && PVO_VADDR(pvo) < eva;
4205 	    pvo = RB_NEXT(pvo_tree, &pmap->pmap_pvo, pvo)) {
4206 		ret = moea64_pte_clear(pvo, ptebit);
4207 		if (ret > 0)
4208 			refchg |= ret & (LPTE_CHG | LPTE_REF);
4209 	}
4210 
4211 	m = PHYS_TO_VM_PAGE(PVO_PADDR(sp));
4212 	atomic_clear_32(&m->md.mdpg_attrs, ptebit);
4213 	PMAP_UNLOCK(pmap);
4214 
4215 	CTR4(KTR_PMAP, "%s: va=%#jx, pa=%#jx: refchg=%#jx",
4216 	    __func__, (uintmax_t)PVO_VADDR(sp),
4217 	    (uintmax_t)PVO_PADDR(sp), (uintmax_t)refchg);
4218 
4219 	return (refchg);
4220 }
4221 
4222 static int64_t
4223 moea64_sp_clear(struct pvo_entry *pvo, vm_page_t m, uint64_t ptebit)
4224 {
4225 	int64_t count, ret;
4226 	pmap_t pmap;
4227 
4228 	count = 0;
4229 	pmap = pvo->pvo_pmap;
4230 
4231 	/*
4232 	 * Since this reference bit is shared by 4096 4KB pages, it
4233 	 * should not be cleared every time it is tested. Apply a
4234 	 * simple "hash" function on the physical page number, the
4235 	 * virtual superpage number, and the pmap address to select
4236 	 * one 4KB page out of the 4096 on which testing the
4237 	 * reference bit will result in clearing that reference bit.
4238 	 * This function is designed to avoid the selection of the
4239 	 * same 4KB page for every 16MB page mapping.
4240 	 *
4241 	 * Always leave the reference bit of a wired mapping set, as
4242 	 * the current state of its reference bit won't affect page
4243 	 * replacement.
4244 	 */
4245 	if (ptebit == LPTE_REF && (((VM_PAGE_TO_PHYS(m) >> PAGE_SHIFT) ^
4246 	    (PVO_VADDR(pvo) >> HPT_SP_SHIFT) ^ (uintptr_t)pmap) &
4247 	    (HPT_SP_PAGES - 1)) == 0 && (pvo->pvo_vaddr & PVO_WIRED) == 0) {
4248 		if ((ret = moea64_sp_pvo_clear(pvo, ptebit)) == -1)
4249 			return (-1);
4250 
4251 		if ((ret & ptebit) != 0)
4252 			count++;
4253 
4254 	/*
4255 	 * If this page was not selected by the hash function, then assume
4256 	 * its REF bit was set.
4257 	 */
4258 	} else if (ptebit == LPTE_REF) {
4259 		count++;
4260 
4261 	/*
4262 	 * To clear the CHG bit of a single SP page, first it must be demoted.
4263 	 * But if no CHG bit is set, no bit clear and thus no SP demotion is
4264 	 * needed.
4265 	 */
4266 	} else {
4267 		CTR4(KTR_PMAP, "%s: ptebit=%#jx, va=%#jx, pa=%#jx",
4268 		    __func__, (uintmax_t)ptebit, (uintmax_t)PVO_VADDR(pvo),
4269 		    (uintmax_t)PVO_PADDR(pvo));
4270 
4271 		PMAP_LOCK(pmap);
4272 
4273 		/*
4274 		 * Make sure SP wasn't demoted/removed before pmap lock
4275 		 * was acquired.
4276 		 */
4277 		if (!PVO_IS_SP(pvo) || (pvo->pvo_vaddr & PVO_DEAD) != 0) {
4278 			CTR2(KTR_PMAP, "%s: demoted/removed: pa=%#jx",
4279 			    __func__, (uintmax_t)PVO_PADDR(pvo));
4280 			PMAP_UNLOCK(pmap);
4281 			return (-1);
4282 		}
4283 
4284 		ret = moea64_sp_query_locked(pvo, ptebit);
4285 		if ((ret & ptebit) != 0)
4286 			count++;
4287 		else {
4288 			PMAP_UNLOCK(pmap);
4289 			return (0);
4290 		}
4291 
4292 		moea64_sp_demote(pvo);
4293 		moea64_pte_clear(pvo, ptebit);
4294 
4295 		/*
4296 		 * Write protect the mapping to a single page so that a
4297 		 * subsequent write access may repromote.
4298 		 */
4299 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
4300 			moea64_pvo_protect(pmap, pvo,
4301 			    pvo->pvo_pte.prot & ~VM_PROT_WRITE);
4302 
4303 		PMAP_UNLOCK(pmap);
4304 	}
4305 
4306 	return (count);
4307 }
4308