xref: /freebsd/sys/powerpc/aim/mmu_oea64.c (revision b820822823cc5f76af5cc8be6d96483a31b36151)
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/uma.h>
87 
88 #include <machine/_inttypes.h>
89 #include <machine/cpu.h>
90 #include <machine/ifunc.h>
91 #include <machine/platform.h>
92 #include <machine/frame.h>
93 #include <machine/md_var.h>
94 #include <machine/psl.h>
95 #include <machine/bat.h>
96 #include <machine/hid.h>
97 #include <machine/pte.h>
98 #include <machine/sr.h>
99 #include <machine/trap.h>
100 #include <machine/mmuvar.h>
101 
102 #include "mmu_oea64.h"
103 
104 void moea64_release_vsid(uint64_t vsid);
105 uintptr_t moea64_get_unique_vsid(void);
106 
107 #define DISABLE_TRANS(msr)	msr = mfmsr(); mtmsr(msr & ~PSL_DR)
108 #define ENABLE_TRANS(msr)	mtmsr(msr)
109 
110 #define	VSID_MAKE(sr, hash)	((sr) | (((hash) & 0xfffff) << 4))
111 #define	VSID_TO_HASH(vsid)	(((vsid) >> 4) & 0xfffff)
112 #define	VSID_HASH_MASK		0x0000007fffffffffULL
113 
114 /* Get physical address from PVO. */
115 #define	PVO_PADDR(pvo)		((pvo)->pvo_pte.pa & LPTE_RPGN)
116 
117 /*
118  * Locking semantics:
119  *
120  * There are two locks of interest: the page locks and the pmap locks, which
121  * protect their individual PVO lists and are locked in that order. The contents
122  * of all PVO entries are protected by the locks of their respective pmaps.
123  * The pmap of any PVO is guaranteed not to change so long as the PVO is linked
124  * into any list.
125  *
126  */
127 
128 #define PV_LOCK_COUNT	PA_LOCK_COUNT
129 static struct mtx_padalign pv_lock[PV_LOCK_COUNT];
130 
131 /*
132  * Cheap NUMA-izing of the pv locks, to reduce contention across domains.
133  * NUMA domains on POWER9 appear to be indexed as sparse memory spaces, with the
134  * index at (N << 45).
135  */
136 #ifdef __powerpc64__
137 #define PV_LOCK_IDX(pa)	((pa_index(pa) * (((pa) >> 45) + 1)) % PV_LOCK_COUNT)
138 #else
139 #define PV_LOCK_IDX(pa)	(pa_index(pa) % PV_LOCK_COUNT)
140 #endif
141 #define PV_LOCKPTR(pa)	((struct mtx *)(&pv_lock[PV_LOCK_IDX(pa)]))
142 #define PV_LOCK(pa)		mtx_lock(PV_LOCKPTR(pa))
143 #define PV_UNLOCK(pa)		mtx_unlock(PV_LOCKPTR(pa))
144 #define PV_LOCKASSERT(pa) 	mtx_assert(PV_LOCKPTR(pa), MA_OWNED)
145 #define PV_PAGE_LOCK(m)		PV_LOCK(VM_PAGE_TO_PHYS(m))
146 #define PV_PAGE_UNLOCK(m)	PV_UNLOCK(VM_PAGE_TO_PHYS(m))
147 #define PV_PAGE_LOCKASSERT(m)	PV_LOCKASSERT(VM_PAGE_TO_PHYS(m))
148 
149 struct ofw_map {
150 	cell_t	om_va;
151 	cell_t	om_len;
152 	uint64_t om_pa;
153 	cell_t	om_mode;
154 };
155 
156 extern unsigned char _etext[];
157 extern unsigned char _end[];
158 
159 extern void *slbtrap, *slbtrapend;
160 
161 /*
162  * Map of physical memory regions.
163  */
164 static struct	mem_region *regions;
165 static struct	mem_region *pregions;
166 static struct	numa_mem_region *numa_pregions;
167 static u_int	phys_avail_count;
168 static int	regions_sz, pregions_sz, numapregions_sz;
169 
170 extern void bs_remap_earlyboot(void);
171 
172 /*
173  * Lock for the SLB tables.
174  */
175 struct mtx	moea64_slb_mutex;
176 
177 /*
178  * PTEG data.
179  */
180 u_long		moea64_pteg_count;
181 u_long		moea64_pteg_mask;
182 
183 /*
184  * PVO data.
185  */
186 
187 uma_zone_t	moea64_pvo_zone; /* zone for pvo entries */
188 
189 static struct	pvo_entry *moea64_bpvo_pool;
190 static int	moea64_bpvo_pool_index = 0;
191 static int	moea64_bpvo_pool_size = 0;
192 SYSCTL_INT(_machdep, OID_AUTO, moea64_allocated_bpvo_entries, CTLFLAG_RD,
193     &moea64_bpvo_pool_index, 0, "");
194 
195 #define	BPVO_POOL_SIZE	327680 /* Sensible historical default value */
196 #define	BPVO_POOL_EXPANSION_FACTOR	3
197 #define	VSID_NBPW	(sizeof(u_int32_t) * 8)
198 #ifdef __powerpc64__
199 #define	NVSIDS		(NPMAPS * 16)
200 #define VSID_HASHMASK	0xffffffffUL
201 #else
202 #define NVSIDS		NPMAPS
203 #define VSID_HASHMASK	0xfffffUL
204 #endif
205 static u_int	moea64_vsid_bitmap[NVSIDS / VSID_NBPW];
206 
207 static boolean_t moea64_initialized = FALSE;
208 
209 #ifdef MOEA64_STATS
210 /*
211  * Statistics.
212  */
213 u_int	moea64_pte_valid = 0;
214 u_int	moea64_pte_overflow = 0;
215 u_int	moea64_pvo_entries = 0;
216 u_int	moea64_pvo_enter_calls = 0;
217 u_int	moea64_pvo_remove_calls = 0;
218 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_valid, CTLFLAG_RD,
219     &moea64_pte_valid, 0, "");
220 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_overflow, CTLFLAG_RD,
221     &moea64_pte_overflow, 0, "");
222 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_entries, CTLFLAG_RD,
223     &moea64_pvo_entries, 0, "");
224 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_enter_calls, CTLFLAG_RD,
225     &moea64_pvo_enter_calls, 0, "");
226 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_remove_calls, CTLFLAG_RD,
227     &moea64_pvo_remove_calls, 0, "");
228 #endif
229 
230 vm_offset_t	moea64_scratchpage_va[2];
231 struct pvo_entry *moea64_scratchpage_pvo[2];
232 struct	mtx	moea64_scratchpage_mtx;
233 
234 uint64_t 	moea64_large_page_mask = 0;
235 uint64_t	moea64_large_page_size = 0;
236 int		moea64_large_page_shift = 0;
237 
238 /*
239  * PVO calls.
240  */
241 static int	moea64_pvo_enter(struct pvo_entry *pvo,
242 		    struct pvo_head *pvo_head, struct pvo_entry **oldpvo);
243 static void	moea64_pvo_remove_from_pmap(struct pvo_entry *pvo);
244 static void	moea64_pvo_remove_from_page(struct pvo_entry *pvo);
245 static void	moea64_pvo_remove_from_page_locked(
246 		    struct pvo_entry *pvo, vm_page_t m);
247 static struct	pvo_entry *moea64_pvo_find_va(pmap_t, vm_offset_t);
248 
249 /*
250  * Utility routines.
251  */
252 static boolean_t	moea64_query_bit(vm_page_t, uint64_t);
253 static u_int		moea64_clear_bit(vm_page_t, uint64_t);
254 static void		moea64_kremove(vm_offset_t);
255 static void		moea64_syncicache(pmap_t pmap, vm_offset_t va,
256 			    vm_paddr_t pa, vm_size_t sz);
257 static void		moea64_pmap_init_qpages(void);
258 
259 /*
260  * Kernel MMU interface
261  */
262 void moea64_clear_modify(vm_page_t);
263 void moea64_copy_page(vm_page_t, vm_page_t);
264 void moea64_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
265     vm_page_t *mb, vm_offset_t b_offset, int xfersize);
266 int moea64_enter(pmap_t, vm_offset_t, vm_page_t, vm_prot_t,
267     u_int flags, int8_t psind);
268 void moea64_enter_object(pmap_t, vm_offset_t, vm_offset_t, vm_page_t,
269     vm_prot_t);
270 void moea64_enter_quick(pmap_t, vm_offset_t, vm_page_t, vm_prot_t);
271 vm_paddr_t moea64_extract(pmap_t, vm_offset_t);
272 vm_page_t moea64_extract_and_hold(pmap_t, vm_offset_t, vm_prot_t);
273 void moea64_init(void);
274 boolean_t moea64_is_modified(vm_page_t);
275 boolean_t moea64_is_prefaultable(pmap_t, vm_offset_t);
276 boolean_t moea64_is_referenced(vm_page_t);
277 int moea64_ts_referenced(vm_page_t);
278 vm_offset_t moea64_map(vm_offset_t *, vm_paddr_t, vm_paddr_t, int);
279 boolean_t moea64_page_exists_quick(pmap_t, vm_page_t);
280 void moea64_page_init(vm_page_t);
281 int moea64_page_wired_mappings(vm_page_t);
282 int moea64_pinit(pmap_t);
283 void moea64_pinit0(pmap_t);
284 void moea64_protect(pmap_t, vm_offset_t, vm_offset_t, vm_prot_t);
285 void moea64_qenter(vm_offset_t, vm_page_t *, int);
286 void moea64_qremove(vm_offset_t, int);
287 void moea64_release(pmap_t);
288 void moea64_remove(pmap_t, vm_offset_t, vm_offset_t);
289 void moea64_remove_pages(pmap_t);
290 void moea64_remove_all(vm_page_t);
291 void moea64_remove_write(vm_page_t);
292 void moea64_unwire(pmap_t, vm_offset_t, vm_offset_t);
293 void moea64_zero_page(vm_page_t);
294 void moea64_zero_page_area(vm_page_t, int, int);
295 void moea64_activate(struct thread *);
296 void moea64_deactivate(struct thread *);
297 void *moea64_mapdev(vm_paddr_t, vm_size_t);
298 void *moea64_mapdev_attr(vm_paddr_t, vm_size_t, vm_memattr_t);
299 void moea64_unmapdev(vm_offset_t, vm_size_t);
300 vm_paddr_t moea64_kextract(vm_offset_t);
301 void moea64_page_set_memattr(vm_page_t m, vm_memattr_t ma);
302 void moea64_kenter_attr(vm_offset_t, vm_paddr_t, vm_memattr_t ma);
303 void moea64_kenter(vm_offset_t, vm_paddr_t);
304 boolean_t moea64_dev_direct_mapped(vm_paddr_t, vm_size_t);
305 static void moea64_sync_icache(pmap_t, vm_offset_t, vm_size_t);
306 void moea64_dumpsys_map(vm_paddr_t pa, size_t sz,
307     void **va);
308 void moea64_scan_init(void);
309 vm_offset_t moea64_quick_enter_page(vm_page_t m);
310 void moea64_quick_remove_page(vm_offset_t addr);
311 boolean_t moea64_page_is_mapped(vm_page_t m);
312 static int moea64_map_user_ptr(pmap_t pm,
313     volatile const void *uaddr, void **kaddr, size_t ulen, size_t *klen);
314 static int moea64_decode_kernel_ptr(vm_offset_t addr,
315     int *is_user, vm_offset_t *decoded_addr);
316 static size_t moea64_scan_pmap(void);
317 static void *moea64_dump_pmap_init(unsigned blkpgs);
318 #ifdef __powerpc64__
319 static void moea64_page_array_startup(long);
320 #endif
321 static int moea64_mincore(pmap_t, vm_offset_t, vm_paddr_t *);
322 
323 static struct pmap_funcs moea64_methods = {
324 	.clear_modify = moea64_clear_modify,
325 	.copy_page = moea64_copy_page,
326 	.copy_pages = moea64_copy_pages,
327 	.enter = moea64_enter,
328 	.enter_object = moea64_enter_object,
329 	.enter_quick = moea64_enter_quick,
330 	.extract = moea64_extract,
331 	.extract_and_hold = moea64_extract_and_hold,
332 	.init = moea64_init,
333 	.is_modified = moea64_is_modified,
334 	.is_prefaultable = moea64_is_prefaultable,
335 	.is_referenced = moea64_is_referenced,
336 	.ts_referenced = moea64_ts_referenced,
337 	.map =      		moea64_map,
338 	.mincore = moea64_mincore,
339 	.page_exists_quick = moea64_page_exists_quick,
340 	.page_init = moea64_page_init,
341 	.page_wired_mappings = moea64_page_wired_mappings,
342 	.pinit = moea64_pinit,
343 	.pinit0 = moea64_pinit0,
344 	.protect = moea64_protect,
345 	.qenter = moea64_qenter,
346 	.qremove = moea64_qremove,
347 	.release = moea64_release,
348 	.remove = moea64_remove,
349 	.remove_pages = moea64_remove_pages,
350 	.remove_all =       	moea64_remove_all,
351 	.remove_write = moea64_remove_write,
352 	.sync_icache = moea64_sync_icache,
353 	.unwire = moea64_unwire,
354 	.zero_page =        	moea64_zero_page,
355 	.zero_page_area = moea64_zero_page_area,
356 	.activate = moea64_activate,
357 	.deactivate =       	moea64_deactivate,
358 	.page_set_memattr = moea64_page_set_memattr,
359 	.quick_enter_page =  moea64_quick_enter_page,
360 	.quick_remove_page =  moea64_quick_remove_page,
361 	.page_is_mapped = moea64_page_is_mapped,
362 #ifdef __powerpc64__
363 	.page_array_startup = moea64_page_array_startup,
364 #endif
365 
366 	/* Internal interfaces */
367 	.mapdev = moea64_mapdev,
368 	.mapdev_attr = moea64_mapdev_attr,
369 	.unmapdev = moea64_unmapdev,
370 	.kextract = moea64_kextract,
371 	.kenter = moea64_kenter,
372 	.kenter_attr = moea64_kenter_attr,
373 	.dev_direct_mapped = moea64_dev_direct_mapped,
374 	.dumpsys_pa_init = moea64_scan_init,
375 	.dumpsys_scan_pmap = moea64_scan_pmap,
376 	.dumpsys_dump_pmap_init =    moea64_dump_pmap_init,
377 	.dumpsys_map_chunk = moea64_dumpsys_map,
378 	.map_user_ptr = moea64_map_user_ptr,
379 	.decode_kernel_ptr =  moea64_decode_kernel_ptr,
380 };
381 
382 MMU_DEF(oea64_mmu, "mmu_oea64_base", moea64_methods);
383 
384 static struct pvo_head *
385 vm_page_to_pvoh(vm_page_t m)
386 {
387 
388 	mtx_assert(PV_LOCKPTR(VM_PAGE_TO_PHYS(m)), MA_OWNED);
389 	return (&m->md.mdpg_pvoh);
390 }
391 
392 static struct pvo_entry *
393 alloc_pvo_entry(int bootstrap)
394 {
395 	struct pvo_entry *pvo;
396 
397 	if (!moea64_initialized || bootstrap) {
398 		if (moea64_bpvo_pool_index >= moea64_bpvo_pool_size) {
399 			panic("%s: bpvo pool exhausted, index=%d, size=%d, bytes=%zd."
400 			    "Try setting machdep.moea64_bpvo_pool_size tunable",
401 			    __func__, moea64_bpvo_pool_index,
402 			    moea64_bpvo_pool_size,
403 			    moea64_bpvo_pool_size * sizeof(struct pvo_entry));
404 		}
405 		pvo = &moea64_bpvo_pool[
406 		    atomic_fetchadd_int(&moea64_bpvo_pool_index, 1)];
407 		bzero(pvo, sizeof(*pvo));
408 		pvo->pvo_vaddr = PVO_BOOTSTRAP;
409 	} else
410 		pvo = uma_zalloc(moea64_pvo_zone, M_NOWAIT | M_ZERO);
411 
412 	return (pvo);
413 }
414 
415 static void
416 init_pvo_entry(struct pvo_entry *pvo, pmap_t pmap, vm_offset_t va)
417 {
418 	uint64_t vsid;
419 	uint64_t hash;
420 	int shift;
421 
422 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
423 
424 	pvo->pvo_pmap = pmap;
425 	va &= ~ADDR_POFF;
426 	pvo->pvo_vaddr |= va;
427 	vsid = va_to_vsid(pmap, va);
428 	pvo->pvo_vpn = (uint64_t)((va & ADDR_PIDX) >> ADDR_PIDX_SHFT)
429 	    | (vsid << 16);
430 
431 	shift = (pvo->pvo_vaddr & PVO_LARGE) ? moea64_large_page_shift :
432 	    ADDR_PIDX_SHFT;
433 	hash = (vsid & VSID_HASH_MASK) ^ (((uint64_t)va & ADDR_PIDX) >> shift);
434 	pvo->pvo_pte.slot = (hash & moea64_pteg_mask) << 3;
435 }
436 
437 static void
438 free_pvo_entry(struct pvo_entry *pvo)
439 {
440 
441 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
442 		uma_zfree(moea64_pvo_zone, pvo);
443 }
444 
445 void
446 moea64_pte_from_pvo(const struct pvo_entry *pvo, struct lpte *lpte)
447 {
448 
449 	lpte->pte_hi = moea64_pte_vpn_from_pvo_vpn(pvo);
450 	lpte->pte_hi |= LPTE_VALID;
451 
452 	if (pvo->pvo_vaddr & PVO_LARGE)
453 		lpte->pte_hi |= LPTE_BIG;
454 	if (pvo->pvo_vaddr & PVO_WIRED)
455 		lpte->pte_hi |= LPTE_WIRED;
456 	if (pvo->pvo_vaddr & PVO_HID)
457 		lpte->pte_hi |= LPTE_HID;
458 
459 	lpte->pte_lo = pvo->pvo_pte.pa; /* Includes WIMG bits */
460 	if (pvo->pvo_pte.prot & VM_PROT_WRITE)
461 		lpte->pte_lo |= LPTE_BW;
462 	else
463 		lpte->pte_lo |= LPTE_BR;
464 
465 	if (!(pvo->pvo_pte.prot & VM_PROT_EXECUTE))
466 		lpte->pte_lo |= LPTE_NOEXEC;
467 }
468 
469 static __inline uint64_t
470 moea64_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
471 {
472 	uint64_t pte_lo;
473 	int i;
474 
475 	if (ma != VM_MEMATTR_DEFAULT) {
476 		switch (ma) {
477 		case VM_MEMATTR_UNCACHEABLE:
478 			return (LPTE_I | LPTE_G);
479 		case VM_MEMATTR_CACHEABLE:
480 			return (LPTE_M);
481 		case VM_MEMATTR_WRITE_COMBINING:
482 		case VM_MEMATTR_WRITE_BACK:
483 		case VM_MEMATTR_PREFETCHABLE:
484 			return (LPTE_I);
485 		case VM_MEMATTR_WRITE_THROUGH:
486 			return (LPTE_W | LPTE_M);
487 		}
488 	}
489 
490 	/*
491 	 * Assume the page is cache inhibited and access is guarded unless
492 	 * it's in our available memory array.
493 	 */
494 	pte_lo = LPTE_I | LPTE_G;
495 	for (i = 0; i < pregions_sz; i++) {
496 		if ((pa >= pregions[i].mr_start) &&
497 		    (pa < (pregions[i].mr_start + pregions[i].mr_size))) {
498 			pte_lo &= ~(LPTE_I | LPTE_G);
499 			pte_lo |= LPTE_M;
500 			break;
501 		}
502 	}
503 
504 	return pte_lo;
505 }
506 
507 /*
508  * Quick sort callout for comparing memory regions.
509  */
510 static int	om_cmp(const void *a, const void *b);
511 
512 static int
513 om_cmp(const void *a, const void *b)
514 {
515 	const struct	ofw_map *mapa;
516 	const struct	ofw_map *mapb;
517 
518 	mapa = a;
519 	mapb = b;
520 	if (mapa->om_pa < mapb->om_pa)
521 		return (-1);
522 	else if (mapa->om_pa > mapb->om_pa)
523 		return (1);
524 	else
525 		return (0);
526 }
527 
528 static void
529 moea64_add_ofw_mappings(phandle_t mmu, size_t sz)
530 {
531 	struct ofw_map	translations[sz/(4*sizeof(cell_t))]; /*>= 4 cells per */
532 	pcell_t		acells, trans_cells[sz/sizeof(cell_t)];
533 	struct pvo_entry *pvo;
534 	register_t	msr;
535 	vm_offset_t	off;
536 	vm_paddr_t	pa_base;
537 	int		i, j;
538 
539 	bzero(translations, sz);
540 	OF_getencprop(OF_finddevice("/"), "#address-cells", &acells,
541 	    sizeof(acells));
542 	if (OF_getencprop(mmu, "translations", trans_cells, sz) == -1)
543 		panic("moea64_bootstrap: can't get ofw translations");
544 
545 	CTR0(KTR_PMAP, "moea64_add_ofw_mappings: translations");
546 	sz /= sizeof(cell_t);
547 	for (i = 0, j = 0; i < sz; j++) {
548 		translations[j].om_va = trans_cells[i++];
549 		translations[j].om_len = trans_cells[i++];
550 		translations[j].om_pa = trans_cells[i++];
551 		if (acells == 2) {
552 			translations[j].om_pa <<= 32;
553 			translations[j].om_pa |= trans_cells[i++];
554 		}
555 		translations[j].om_mode = trans_cells[i++];
556 	}
557 	KASSERT(i == sz, ("Translations map has incorrect cell count (%d/%zd)",
558 	    i, sz));
559 
560 	sz = j;
561 	qsort(translations, sz, sizeof (*translations), om_cmp);
562 
563 	for (i = 0; i < sz; i++) {
564 		pa_base = translations[i].om_pa;
565 	      #ifndef __powerpc64__
566 		if ((translations[i].om_pa >> 32) != 0)
567 			panic("OFW translations above 32-bit boundary!");
568 	      #endif
569 
570 		if (pa_base % PAGE_SIZE)
571 			panic("OFW translation not page-aligned (phys)!");
572 		if (translations[i].om_va % PAGE_SIZE)
573 			panic("OFW translation not page-aligned (virt)!");
574 
575 		CTR3(KTR_PMAP, "translation: pa=%#zx va=%#x len=%#x",
576 		    pa_base, translations[i].om_va, translations[i].om_len);
577 
578 		/* Now enter the pages for this mapping */
579 
580 		DISABLE_TRANS(msr);
581 		for (off = 0; off < translations[i].om_len; off += PAGE_SIZE) {
582 			/* If this address is direct-mapped, skip remapping */
583 			if (hw_direct_map &&
584 			    translations[i].om_va == PHYS_TO_DMAP(pa_base) &&
585 			    moea64_calc_wimg(pa_base + off, VM_MEMATTR_DEFAULT)
586  			    == LPTE_M)
587 				continue;
588 
589 			PMAP_LOCK(kernel_pmap);
590 			pvo = moea64_pvo_find_va(kernel_pmap,
591 			    translations[i].om_va + off);
592 			PMAP_UNLOCK(kernel_pmap);
593 			if (pvo != NULL)
594 				continue;
595 
596 			moea64_kenter(translations[i].om_va + off,
597 			    pa_base + off);
598 		}
599 		ENABLE_TRANS(msr);
600 	}
601 }
602 
603 #ifdef __powerpc64__
604 static void
605 moea64_probe_large_page(void)
606 {
607 	uint16_t pvr = mfpvr() >> 16;
608 
609 	switch (pvr) {
610 	case IBM970:
611 	case IBM970FX:
612 	case IBM970MP:
613 		powerpc_sync(); isync();
614 		mtspr(SPR_HID4, mfspr(SPR_HID4) & ~HID4_970_DISABLE_LG_PG);
615 		powerpc_sync(); isync();
616 
617 		/* FALLTHROUGH */
618 	default:
619 		if (moea64_large_page_size == 0) {
620 			moea64_large_page_size = 0x1000000; /* 16 MB */
621 			moea64_large_page_shift = 24;
622 		}
623 	}
624 
625 	moea64_large_page_mask = moea64_large_page_size - 1;
626 }
627 
628 static void
629 moea64_bootstrap_slb_prefault(vm_offset_t va, int large)
630 {
631 	struct slb *cache;
632 	struct slb entry;
633 	uint64_t esid, slbe;
634 	uint64_t i;
635 
636 	cache = PCPU_GET(aim.slb);
637 	esid = va >> ADDR_SR_SHFT;
638 	slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
639 
640 	for (i = 0; i < 64; i++) {
641 		if (cache[i].slbe == (slbe | i))
642 			return;
643 	}
644 
645 	entry.slbe = slbe;
646 	entry.slbv = KERNEL_VSID(esid) << SLBV_VSID_SHIFT;
647 	if (large)
648 		entry.slbv |= SLBV_L;
649 
650 	slb_insert_kernel(entry.slbe, entry.slbv);
651 }
652 #endif
653 
654 static int
655 moea64_kenter_large(vm_offset_t va, vm_paddr_t pa, uint64_t attr, int bootstrap)
656 {
657 	struct pvo_entry *pvo;
658 	uint64_t pte_lo;
659 	int error;
660 
661 	pte_lo = LPTE_M;
662 	pte_lo |= attr;
663 
664 	pvo = alloc_pvo_entry(bootstrap);
665 	pvo->pvo_vaddr |= PVO_WIRED | PVO_LARGE;
666 	init_pvo_entry(pvo, kernel_pmap, va);
667 
668 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE |
669 	    VM_PROT_EXECUTE;
670 	pvo->pvo_pte.pa = pa | pte_lo;
671 	error = moea64_pvo_enter(pvo, NULL, NULL);
672 	if (error != 0)
673 		panic("Error %d inserting large page\n", error);
674 	return (0);
675 }
676 
677 static void
678 moea64_setup_direct_map(vm_offset_t kernelstart,
679     vm_offset_t kernelend)
680 {
681 	register_t msr;
682 	vm_paddr_t pa, pkernelstart, pkernelend;
683 	vm_offset_t size, off;
684 	uint64_t pte_lo;
685 	int i;
686 
687 	if (moea64_large_page_size == 0)
688 		hw_direct_map = 0;
689 
690 	DISABLE_TRANS(msr);
691 	if (hw_direct_map) {
692 		PMAP_LOCK(kernel_pmap);
693 		for (i = 0; i < pregions_sz; i++) {
694 		  for (pa = pregions[i].mr_start; pa < pregions[i].mr_start +
695 		     pregions[i].mr_size; pa += moea64_large_page_size) {
696 			pte_lo = LPTE_M;
697 			if (pa & moea64_large_page_mask) {
698 				pa &= moea64_large_page_mask;
699 				pte_lo |= LPTE_G;
700 			}
701 			if (pa + moea64_large_page_size >
702 			    pregions[i].mr_start + pregions[i].mr_size)
703 				pte_lo |= LPTE_G;
704 
705 			moea64_kenter_large(PHYS_TO_DMAP(pa), pa, pte_lo, 1);
706 		  }
707 		}
708 		PMAP_UNLOCK(kernel_pmap);
709 	}
710 
711 	/*
712 	 * Make sure the kernel and BPVO pool stay mapped on systems either
713 	 * without a direct map or on which the kernel is not already executing
714 	 * out of the direct-mapped region.
715 	 */
716 	if (kernelstart < DMAP_BASE_ADDRESS) {
717 		/*
718 		 * For pre-dmap execution, we need to use identity mapping
719 		 * because we will be operating with the mmu on but in the
720 		 * wrong address configuration until we __restartkernel().
721 		 */
722 		for (pa = kernelstart & ~PAGE_MASK; pa < kernelend;
723 		    pa += PAGE_SIZE)
724 			moea64_kenter(pa, pa);
725 	} else if (!hw_direct_map) {
726 		pkernelstart = kernelstart & ~DMAP_BASE_ADDRESS;
727 		pkernelend = kernelend & ~DMAP_BASE_ADDRESS;
728 		for (pa = pkernelstart & ~PAGE_MASK; pa < pkernelend;
729 		    pa += PAGE_SIZE)
730 			moea64_kenter(pa | DMAP_BASE_ADDRESS, pa);
731 	}
732 
733 	if (!hw_direct_map) {
734 		size = moea64_bpvo_pool_size*sizeof(struct pvo_entry);
735 		off = (vm_offset_t)(moea64_bpvo_pool);
736 		for (pa = off; pa < off + size; pa += PAGE_SIZE)
737 			moea64_kenter(pa, pa);
738 
739 		/* Map exception vectors */
740 		for (pa = EXC_RSVD; pa < EXC_LAST; pa += PAGE_SIZE)
741 			moea64_kenter(pa | DMAP_BASE_ADDRESS, pa);
742 	}
743 	ENABLE_TRANS(msr);
744 
745 	/*
746 	 * Allow user to override unmapped_buf_allowed for testing.
747 	 * XXXKIB Only direct map implementation was tested.
748 	 */
749 	if (!TUNABLE_INT_FETCH("vfs.unmapped_buf_allowed",
750 	    &unmapped_buf_allowed))
751 		unmapped_buf_allowed = hw_direct_map;
752 }
753 
754 /* Quick sort callout for comparing physical addresses. */
755 static int
756 pa_cmp(const void *a, const void *b)
757 {
758 	const vm_paddr_t *pa = a, *pb = b;
759 
760 	if (*pa < *pb)
761 		return (-1);
762 	else if (*pa > *pb)
763 		return (1);
764 	else
765 		return (0);
766 }
767 
768 void
769 moea64_early_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
770 {
771 	int		i, j;
772 	vm_size_t	physsz, hwphyssz;
773 	vm_paddr_t	kernelphysstart, kernelphysend;
774 	int		rm_pavail;
775 
776 #ifndef __powerpc64__
777 	/* We don't have a direct map since there is no BAT */
778 	hw_direct_map = 0;
779 
780 	/* Make sure battable is zero, since we have no BAT */
781 	for (i = 0; i < 16; i++) {
782 		battable[i].batu = 0;
783 		battable[i].batl = 0;
784 	}
785 #else
786 	moea64_probe_large_page();
787 
788 	/* Use a direct map if we have large page support */
789 	if (moea64_large_page_size > 0)
790 		hw_direct_map = 1;
791 	else
792 		hw_direct_map = 0;
793 
794 	/* Install trap handlers for SLBs */
795 	bcopy(&slbtrap, (void *)EXC_DSE,(size_t)&slbtrapend - (size_t)&slbtrap);
796 	bcopy(&slbtrap, (void *)EXC_ISE,(size_t)&slbtrapend - (size_t)&slbtrap);
797 	__syncicache((void *)EXC_DSE, 0x80);
798 	__syncicache((void *)EXC_ISE, 0x80);
799 #endif
800 
801 	kernelphysstart = kernelstart & ~DMAP_BASE_ADDRESS;
802 	kernelphysend = kernelend & ~DMAP_BASE_ADDRESS;
803 
804 	/* Get physical memory regions from firmware */
805 	mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
806 	CTR0(KTR_PMAP, "moea64_bootstrap: physical memory");
807 
808 	if (PHYS_AVAIL_ENTRIES < regions_sz)
809 		panic("moea64_bootstrap: phys_avail too small");
810 
811 	phys_avail_count = 0;
812 	physsz = 0;
813 	hwphyssz = 0;
814 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
815 	for (i = 0, j = 0; i < regions_sz; i++, j += 2) {
816 		CTR3(KTR_PMAP, "region: %#zx - %#zx (%#zx)",
817 		    regions[i].mr_start, regions[i].mr_start +
818 		    regions[i].mr_size, regions[i].mr_size);
819 		if (hwphyssz != 0 &&
820 		    (physsz + regions[i].mr_size) >= hwphyssz) {
821 			if (physsz < hwphyssz) {
822 				phys_avail[j] = regions[i].mr_start;
823 				phys_avail[j + 1] = regions[i].mr_start +
824 				    hwphyssz - physsz;
825 				physsz = hwphyssz;
826 				phys_avail_count++;
827 				dump_avail[j] = phys_avail[j];
828 				dump_avail[j + 1] = phys_avail[j + 1];
829 			}
830 			break;
831 		}
832 		phys_avail[j] = regions[i].mr_start;
833 		phys_avail[j + 1] = regions[i].mr_start + regions[i].mr_size;
834 		phys_avail_count++;
835 		physsz += regions[i].mr_size;
836 		dump_avail[j] = phys_avail[j];
837 		dump_avail[j + 1] = phys_avail[j + 1];
838 	}
839 
840 	/* Check for overlap with the kernel and exception vectors */
841 	rm_pavail = 0;
842 	for (j = 0; j < 2*phys_avail_count; j+=2) {
843 		if (phys_avail[j] < EXC_LAST)
844 			phys_avail[j] += EXC_LAST;
845 
846 		if (phys_avail[j] >= kernelphysstart &&
847 		    phys_avail[j+1] <= kernelphysend) {
848 			phys_avail[j] = phys_avail[j+1] = ~0;
849 			rm_pavail++;
850 			continue;
851 		}
852 
853 		if (kernelphysstart >= phys_avail[j] &&
854 		    kernelphysstart < phys_avail[j+1]) {
855 			if (kernelphysend < phys_avail[j+1]) {
856 				phys_avail[2*phys_avail_count] =
857 				    (kernelphysend & ~PAGE_MASK) + PAGE_SIZE;
858 				phys_avail[2*phys_avail_count + 1] =
859 				    phys_avail[j+1];
860 				phys_avail_count++;
861 			}
862 
863 			phys_avail[j+1] = kernelphysstart & ~PAGE_MASK;
864 		}
865 
866 		if (kernelphysend >= phys_avail[j] &&
867 		    kernelphysend < phys_avail[j+1]) {
868 			if (kernelphysstart > phys_avail[j]) {
869 				phys_avail[2*phys_avail_count] = phys_avail[j];
870 				phys_avail[2*phys_avail_count + 1] =
871 				    kernelphysstart & ~PAGE_MASK;
872 				phys_avail_count++;
873 			}
874 
875 			phys_avail[j] = (kernelphysend & ~PAGE_MASK) +
876 			    PAGE_SIZE;
877 		}
878 	}
879 
880 	/* Remove physical available regions marked for removal (~0) */
881 	if (rm_pavail) {
882 		qsort(phys_avail, 2*phys_avail_count, sizeof(phys_avail[0]),
883 			pa_cmp);
884 		phys_avail_count -= rm_pavail;
885 		for (i = 2*phys_avail_count;
886 		     i < 2*(phys_avail_count + rm_pavail); i+=2)
887 			phys_avail[i] = phys_avail[i+1] = 0;
888 	}
889 
890 	physmem = btoc(physsz);
891 
892 #ifdef PTEGCOUNT
893 	moea64_pteg_count = PTEGCOUNT;
894 #else
895 	moea64_pteg_count = 0x1000;
896 
897 	while (moea64_pteg_count < physmem)
898 		moea64_pteg_count <<= 1;
899 
900 	moea64_pteg_count >>= 1;
901 #endif /* PTEGCOUNT */
902 }
903 
904 void
905 moea64_mid_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
906 {
907 	int		i;
908 
909 	/*
910 	 * Set PTEG mask
911 	 */
912 	moea64_pteg_mask = moea64_pteg_count - 1;
913 
914 	/*
915 	 * Initialize SLB table lock and page locks
916 	 */
917 	mtx_init(&moea64_slb_mutex, "SLB table", NULL, MTX_DEF);
918 	for (i = 0; i < PV_LOCK_COUNT; i++)
919 		mtx_init(&pv_lock[i], "page pv", NULL, MTX_DEF);
920 
921 	/*
922 	 * Initialise the bootstrap pvo pool.
923 	 */
924 	TUNABLE_INT_FETCH("machdep.moea64_bpvo_pool_size", &moea64_bpvo_pool_size);
925 	if (moea64_bpvo_pool_size == 0) {
926 		if (!hw_direct_map)
927 			moea64_bpvo_pool_size = ((ptoa((uintmax_t)physmem) * sizeof(struct vm_page)) /
928 			    (PAGE_SIZE * PAGE_SIZE)) * BPVO_POOL_EXPANSION_FACTOR;
929 		else
930 			moea64_bpvo_pool_size = BPVO_POOL_SIZE;
931 	}
932 
933 	if (boothowto & RB_VERBOSE) {
934 		printf("mmu_oea64: bpvo pool entries = %d, bpvo pool size = %zu MB\n",
935 		    moea64_bpvo_pool_size,
936 		    moea64_bpvo_pool_size*sizeof(struct pvo_entry) / 1048576);
937 	}
938 
939 	moea64_bpvo_pool = (struct pvo_entry *)moea64_bootstrap_alloc(
940 		moea64_bpvo_pool_size*sizeof(struct pvo_entry), PAGE_SIZE);
941 	moea64_bpvo_pool_index = 0;
942 
943 	/* Place at address usable through the direct map */
944 	if (hw_direct_map)
945 		moea64_bpvo_pool = (struct pvo_entry *)
946 		    PHYS_TO_DMAP((uintptr_t)moea64_bpvo_pool);
947 
948 	/*
949 	 * Make sure kernel vsid is allocated as well as VSID 0.
950 	 */
951 	#ifndef __powerpc64__
952 	moea64_vsid_bitmap[(KERNEL_VSIDBITS & (NVSIDS - 1)) / VSID_NBPW]
953 		|= 1 << (KERNEL_VSIDBITS % VSID_NBPW);
954 	moea64_vsid_bitmap[0] |= 1;
955 	#endif
956 
957 	/*
958 	 * Initialize the kernel pmap (which is statically allocated).
959 	 */
960 	#ifdef __powerpc64__
961 	for (i = 0; i < 64; i++) {
962 		pcpup->pc_aim.slb[i].slbv = 0;
963 		pcpup->pc_aim.slb[i].slbe = 0;
964 	}
965 	#else
966 	for (i = 0; i < 16; i++)
967 		kernel_pmap->pm_sr[i] = EMPTY_SEGMENT + i;
968 	#endif
969 
970 	kernel_pmap->pmap_phys = kernel_pmap;
971 	CPU_FILL(&kernel_pmap->pm_active);
972 	RB_INIT(&kernel_pmap->pmap_pvo);
973 
974 	PMAP_LOCK_INIT(kernel_pmap);
975 
976 	/*
977 	 * Now map in all the other buffers we allocated earlier
978 	 */
979 
980 	moea64_setup_direct_map(kernelstart, kernelend);
981 }
982 
983 void
984 moea64_late_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
985 {
986 	ihandle_t	mmui;
987 	phandle_t	chosen;
988 	phandle_t	mmu;
989 	ssize_t		sz;
990 	int		i;
991 	vm_offset_t	pa, va;
992 	void		*dpcpu;
993 
994 	/*
995 	 * Set up the Open Firmware pmap and add its mappings if not in real
996 	 * mode.
997 	 */
998 
999 	chosen = OF_finddevice("/chosen");
1000 	if (chosen != -1 && OF_getencprop(chosen, "mmu", &mmui, 4) != -1) {
1001 		mmu = OF_instance_to_package(mmui);
1002 		if (mmu == -1 ||
1003 		    (sz = OF_getproplen(mmu, "translations")) == -1)
1004 			sz = 0;
1005 		if (sz > 6144 /* tmpstksz - 2 KB headroom */)
1006 			panic("moea64_bootstrap: too many ofw translations");
1007 
1008 		if (sz > 0)
1009 			moea64_add_ofw_mappings(mmu, sz);
1010 	}
1011 
1012 	/*
1013 	 * Calculate the last available physical address.
1014 	 */
1015 	Maxmem = 0;
1016 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
1017 		Maxmem = MAX(Maxmem, powerpc_btop(phys_avail[i + 1]));
1018 
1019 	/*
1020 	 * Initialize MMU.
1021 	 */
1022 	pmap_cpu_bootstrap(0);
1023 	mtmsr(mfmsr() | PSL_DR | PSL_IR);
1024 	pmap_bootstrapped++;
1025 
1026 	/*
1027 	 * Set the start and end of kva.
1028 	 */
1029 	virtual_avail = VM_MIN_KERNEL_ADDRESS;
1030 	virtual_end = VM_MAX_SAFE_KERNEL_ADDRESS;
1031 
1032 	/*
1033 	 * Map the entire KVA range into the SLB. We must not fault there.
1034 	 */
1035 	#ifdef __powerpc64__
1036 	for (va = virtual_avail; va < virtual_end; va += SEGMENT_LENGTH)
1037 		moea64_bootstrap_slb_prefault(va, 0);
1038 	#endif
1039 
1040 	/*
1041 	 * Remap any early IO mappings (console framebuffer, etc.)
1042 	 */
1043 	bs_remap_earlyboot();
1044 
1045 	/*
1046 	 * Figure out how far we can extend virtual_end into segment 16
1047 	 * without running into existing mappings. Segment 16 is guaranteed
1048 	 * to contain neither RAM nor devices (at least on Apple hardware),
1049 	 * but will generally contain some OFW mappings we should not
1050 	 * step on.
1051 	 */
1052 
1053 	#ifndef __powerpc64__	/* KVA is in high memory on PPC64 */
1054 	PMAP_LOCK(kernel_pmap);
1055 	while (virtual_end < VM_MAX_KERNEL_ADDRESS &&
1056 	    moea64_pvo_find_va(kernel_pmap, virtual_end+1) == NULL)
1057 		virtual_end += PAGE_SIZE;
1058 	PMAP_UNLOCK(kernel_pmap);
1059 	#endif
1060 
1061 	/*
1062 	 * Allocate a kernel stack with a guard page for thread0 and map it
1063 	 * into the kernel page map.
1064 	 */
1065 	pa = moea64_bootstrap_alloc(kstack_pages * PAGE_SIZE, PAGE_SIZE);
1066 	va = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
1067 	virtual_avail = va + kstack_pages * PAGE_SIZE;
1068 	CTR2(KTR_PMAP, "moea64_bootstrap: kstack0 at %#x (%#x)", pa, va);
1069 	thread0.td_kstack = va;
1070 	thread0.td_kstack_pages = kstack_pages;
1071 	for (i = 0; i < kstack_pages; i++) {
1072 		moea64_kenter(va, pa);
1073 		pa += PAGE_SIZE;
1074 		va += PAGE_SIZE;
1075 	}
1076 
1077 	/*
1078 	 * Allocate virtual address space for the message buffer.
1079 	 */
1080 	pa = msgbuf_phys = moea64_bootstrap_alloc(msgbufsize, PAGE_SIZE);
1081 	msgbufp = (struct msgbuf *)virtual_avail;
1082 	va = virtual_avail;
1083 	virtual_avail += round_page(msgbufsize);
1084 	while (va < virtual_avail) {
1085 		moea64_kenter(va, pa);
1086 		pa += PAGE_SIZE;
1087 		va += PAGE_SIZE;
1088 	}
1089 
1090 	/*
1091 	 * Allocate virtual address space for the dynamic percpu area.
1092 	 */
1093 	pa = moea64_bootstrap_alloc(DPCPU_SIZE, PAGE_SIZE);
1094 	dpcpu = (void *)virtual_avail;
1095 	va = virtual_avail;
1096 	virtual_avail += DPCPU_SIZE;
1097 	while (va < virtual_avail) {
1098 		moea64_kenter(va, pa);
1099 		pa += PAGE_SIZE;
1100 		va += PAGE_SIZE;
1101 	}
1102 	dpcpu_init(dpcpu, curcpu);
1103 
1104 	crashdumpmap = (caddr_t)virtual_avail;
1105 	virtual_avail += MAXDUMPPGS * PAGE_SIZE;
1106 
1107 	/*
1108 	 * Allocate some things for page zeroing. We put this directly
1109 	 * in the page table and use MOEA64_PTE_REPLACE to avoid any
1110 	 * of the PVO book-keeping or other parts of the VM system
1111 	 * from even knowing that this hack exists.
1112 	 */
1113 
1114 	if (!hw_direct_map) {
1115 		mtx_init(&moea64_scratchpage_mtx, "pvo zero page", NULL,
1116 		    MTX_DEF);
1117 		for (i = 0; i < 2; i++) {
1118 			moea64_scratchpage_va[i] = (virtual_end+1) - PAGE_SIZE;
1119 			virtual_end -= PAGE_SIZE;
1120 
1121 			moea64_kenter(moea64_scratchpage_va[i], 0);
1122 
1123 			PMAP_LOCK(kernel_pmap);
1124 			moea64_scratchpage_pvo[i] = moea64_pvo_find_va(
1125 			    kernel_pmap, (vm_offset_t)moea64_scratchpage_va[i]);
1126 			PMAP_UNLOCK(kernel_pmap);
1127 		}
1128 	}
1129 
1130 	numa_mem_regions(&numa_pregions, &numapregions_sz);
1131 }
1132 
1133 static void
1134 moea64_pmap_init_qpages(void)
1135 {
1136 	struct pcpu *pc;
1137 	int i;
1138 
1139 	if (hw_direct_map)
1140 		return;
1141 
1142 	CPU_FOREACH(i) {
1143 		pc = pcpu_find(i);
1144 		pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
1145 		if (pc->pc_qmap_addr == 0)
1146 			panic("pmap_init_qpages: unable to allocate KVA");
1147 		PMAP_LOCK(kernel_pmap);
1148 		pc->pc_aim.qmap_pvo =
1149 		    moea64_pvo_find_va(kernel_pmap, pc->pc_qmap_addr);
1150 		PMAP_UNLOCK(kernel_pmap);
1151 		mtx_init(&pc->pc_aim.qmap_lock, "qmap lock", NULL, MTX_DEF);
1152 	}
1153 }
1154 
1155 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, moea64_pmap_init_qpages, NULL);
1156 
1157 /*
1158  * Activate a user pmap.  This mostly involves setting some non-CPU
1159  * state.
1160  */
1161 void
1162 moea64_activate(struct thread *td)
1163 {
1164 	pmap_t	pm;
1165 
1166 	pm = &td->td_proc->p_vmspace->vm_pmap;
1167 	CPU_SET(PCPU_GET(cpuid), &pm->pm_active);
1168 
1169 	#ifdef __powerpc64__
1170 	PCPU_SET(aim.userslb, pm->pm_slb);
1171 	__asm __volatile("slbmte %0, %1; isync" ::
1172 	    "r"(td->td_pcb->pcb_cpu.aim.usr_vsid), "r"(USER_SLB_SLBE));
1173 	#else
1174 	PCPU_SET(curpmap, pm->pmap_phys);
1175 	mtsrin(USER_SR << ADDR_SR_SHFT, td->td_pcb->pcb_cpu.aim.usr_vsid);
1176 	#endif
1177 }
1178 
1179 void
1180 moea64_deactivate(struct thread *td)
1181 {
1182 	pmap_t	pm;
1183 
1184 	__asm __volatile("isync; slbie %0" :: "r"(USER_ADDR));
1185 
1186 	pm = &td->td_proc->p_vmspace->vm_pmap;
1187 	CPU_CLR(PCPU_GET(cpuid), &pm->pm_active);
1188 	#ifdef __powerpc64__
1189 	PCPU_SET(aim.userslb, NULL);
1190 	#else
1191 	PCPU_SET(curpmap, NULL);
1192 	#endif
1193 }
1194 
1195 void
1196 moea64_unwire(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1197 {
1198 	struct	pvo_entry key, *pvo;
1199 	vm_page_t m;
1200 	int64_t	refchg;
1201 
1202 	key.pvo_vaddr = sva;
1203 	PMAP_LOCK(pm);
1204 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1205 	    pvo != NULL && PVO_VADDR(pvo) < eva;
1206 	    pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
1207 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
1208 			panic("moea64_unwire: pvo %p is missing PVO_WIRED",
1209 			    pvo);
1210 		pvo->pvo_vaddr &= ~PVO_WIRED;
1211 		refchg = moea64_pte_replace(pvo, 0 /* No invalidation */);
1212 		if ((pvo->pvo_vaddr & PVO_MANAGED) &&
1213 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1214 			if (refchg < 0)
1215 				refchg = LPTE_CHG;
1216 			m = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
1217 
1218 			refchg |= atomic_readandclear_32(&m->md.mdpg_attrs);
1219 			if (refchg & LPTE_CHG)
1220 				vm_page_dirty(m);
1221 			if (refchg & LPTE_REF)
1222 				vm_page_aflag_set(m, PGA_REFERENCED);
1223 		}
1224 		pm->pm_stats.wired_count--;
1225 	}
1226 	PMAP_UNLOCK(pm);
1227 }
1228 
1229 static int
1230 moea64_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
1231 {
1232 	struct pvo_entry *pvo;
1233 	vm_paddr_t pa;
1234 	vm_page_t m;
1235 	int val;
1236 	bool managed;
1237 
1238 	PMAP_LOCK(pmap);
1239 
1240 	/* XXX Add support for superpages */
1241 	pvo = moea64_pvo_find_va(pmap, addr);
1242 	if (pvo != NULL) {
1243 		pa = PVO_PADDR(pvo);
1244 		m = PHYS_TO_VM_PAGE(pa);
1245 		managed = (pvo->pvo_vaddr & PVO_MANAGED) == PVO_MANAGED;
1246 		val = MINCORE_INCORE;
1247 	} else {
1248 		PMAP_UNLOCK(pmap);
1249 		return (0);
1250 	}
1251 
1252 	PMAP_UNLOCK(pmap);
1253 
1254 	if (m == NULL)
1255 		return (0);
1256 
1257 	if (managed) {
1258 		if (moea64_is_modified(m))
1259 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
1260 
1261 		if (moea64_is_referenced(m))
1262 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
1263 	}
1264 
1265 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
1266 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
1267 	    managed) {
1268 		*pap = pa;
1269 	}
1270 
1271 	return (val);
1272 }
1273 
1274 /*
1275  * This goes through and sets the physical address of our
1276  * special scratch PTE to the PA we want to zero or copy. Because
1277  * of locking issues (this can get called in pvo_enter() by
1278  * the UMA allocator), we can't use most other utility functions here
1279  */
1280 
1281 static __inline
1282 void moea64_set_scratchpage_pa(int which, vm_paddr_t pa)
1283 {
1284 	struct pvo_entry *pvo;
1285 
1286 	KASSERT(!hw_direct_map, ("Using OEA64 scratchpage with a direct map!"));
1287 	mtx_assert(&moea64_scratchpage_mtx, MA_OWNED);
1288 
1289 	pvo = moea64_scratchpage_pvo[which];
1290 	PMAP_LOCK(pvo->pvo_pmap);
1291 	pvo->pvo_pte.pa =
1292 	    moea64_calc_wimg(pa, VM_MEMATTR_DEFAULT) | (uint64_t)pa;
1293 	moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
1294 	PMAP_UNLOCK(pvo->pvo_pmap);
1295 	isync();
1296 }
1297 
1298 void
1299 moea64_copy_page(vm_page_t msrc, vm_page_t mdst)
1300 {
1301 	vm_offset_t	dst;
1302 	vm_offset_t	src;
1303 
1304 	dst = VM_PAGE_TO_PHYS(mdst);
1305 	src = VM_PAGE_TO_PHYS(msrc);
1306 
1307 	if (hw_direct_map) {
1308 		bcopy((void *)PHYS_TO_DMAP(src), (void *)PHYS_TO_DMAP(dst),
1309 		    PAGE_SIZE);
1310 	} else {
1311 		mtx_lock(&moea64_scratchpage_mtx);
1312 
1313 		moea64_set_scratchpage_pa(0, src);
1314 		moea64_set_scratchpage_pa(1, dst);
1315 
1316 		bcopy((void *)moea64_scratchpage_va[0],
1317 		    (void *)moea64_scratchpage_va[1], PAGE_SIZE);
1318 
1319 		mtx_unlock(&moea64_scratchpage_mtx);
1320 	}
1321 }
1322 
1323 static inline void
1324 moea64_copy_pages_dmap(vm_page_t *ma, vm_offset_t a_offset,
1325     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1326 {
1327 	void *a_cp, *b_cp;
1328 	vm_offset_t a_pg_offset, b_pg_offset;
1329 	int cnt;
1330 
1331 	while (xfersize > 0) {
1332 		a_pg_offset = a_offset & PAGE_MASK;
1333 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1334 		a_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
1335 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT])) +
1336 		    a_pg_offset;
1337 		b_pg_offset = b_offset & PAGE_MASK;
1338 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1339 		b_cp = (char *)(uintptr_t)PHYS_TO_DMAP(
1340 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT])) +
1341 		    b_pg_offset;
1342 		bcopy(a_cp, b_cp, cnt);
1343 		a_offset += cnt;
1344 		b_offset += cnt;
1345 		xfersize -= cnt;
1346 	}
1347 }
1348 
1349 static inline void
1350 moea64_copy_pages_nodmap(vm_page_t *ma, vm_offset_t a_offset,
1351     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1352 {
1353 	void *a_cp, *b_cp;
1354 	vm_offset_t a_pg_offset, b_pg_offset;
1355 	int cnt;
1356 
1357 	mtx_lock(&moea64_scratchpage_mtx);
1358 	while (xfersize > 0) {
1359 		a_pg_offset = a_offset & PAGE_MASK;
1360 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1361 		moea64_set_scratchpage_pa(0,
1362 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]));
1363 		a_cp = (char *)moea64_scratchpage_va[0] + a_pg_offset;
1364 		b_pg_offset = b_offset & PAGE_MASK;
1365 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1366 		moea64_set_scratchpage_pa(1,
1367 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]));
1368 		b_cp = (char *)moea64_scratchpage_va[1] + b_pg_offset;
1369 		bcopy(a_cp, b_cp, cnt);
1370 		a_offset += cnt;
1371 		b_offset += cnt;
1372 		xfersize -= cnt;
1373 	}
1374 	mtx_unlock(&moea64_scratchpage_mtx);
1375 }
1376 
1377 void
1378 moea64_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
1379     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1380 {
1381 
1382 	if (hw_direct_map) {
1383 		moea64_copy_pages_dmap(ma, a_offset, mb, b_offset,
1384 		    xfersize);
1385 	} else {
1386 		moea64_copy_pages_nodmap(ma, a_offset, mb, b_offset,
1387 		    xfersize);
1388 	}
1389 }
1390 
1391 void
1392 moea64_zero_page_area(vm_page_t m, int off, int size)
1393 {
1394 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1395 
1396 	if (size + off > PAGE_SIZE)
1397 		panic("moea64_zero_page: size + off > PAGE_SIZE");
1398 
1399 	if (hw_direct_map) {
1400 		bzero((caddr_t)(uintptr_t)PHYS_TO_DMAP(pa) + off, size);
1401 	} else {
1402 		mtx_lock(&moea64_scratchpage_mtx);
1403 		moea64_set_scratchpage_pa(0, pa);
1404 		bzero((caddr_t)moea64_scratchpage_va[0] + off, size);
1405 		mtx_unlock(&moea64_scratchpage_mtx);
1406 	}
1407 }
1408 
1409 /*
1410  * Zero a page of physical memory by temporarily mapping it
1411  */
1412 void
1413 moea64_zero_page(vm_page_t m)
1414 {
1415 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1416 	vm_offset_t va, off;
1417 
1418 	if (!hw_direct_map) {
1419 		mtx_lock(&moea64_scratchpage_mtx);
1420 
1421 		moea64_set_scratchpage_pa(0, pa);
1422 		va = moea64_scratchpage_va[0];
1423 	} else {
1424 		va = PHYS_TO_DMAP(pa);
1425 	}
1426 
1427 	for (off = 0; off < PAGE_SIZE; off += cacheline_size)
1428 		__asm __volatile("dcbz 0,%0" :: "r"(va + off));
1429 
1430 	if (!hw_direct_map)
1431 		mtx_unlock(&moea64_scratchpage_mtx);
1432 }
1433 
1434 vm_offset_t
1435 moea64_quick_enter_page(vm_page_t m)
1436 {
1437 	struct pvo_entry *pvo;
1438 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1439 
1440 	if (hw_direct_map)
1441 		return (PHYS_TO_DMAP(pa));
1442 
1443 	/*
1444  	 * MOEA64_PTE_REPLACE does some locking, so we can't just grab
1445 	 * a critical section and access the PCPU data like on i386.
1446 	 * Instead, pin the thread and grab the PCPU lock to prevent
1447 	 * a preempting thread from using the same PCPU data.
1448 	 */
1449 	sched_pin();
1450 
1451 	mtx_assert(PCPU_PTR(aim.qmap_lock), MA_NOTOWNED);
1452 	pvo = PCPU_GET(aim.qmap_pvo);
1453 
1454 	mtx_lock(PCPU_PTR(aim.qmap_lock));
1455 	pvo->pvo_pte.pa = moea64_calc_wimg(pa, pmap_page_get_memattr(m)) |
1456 	    (uint64_t)pa;
1457 	moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
1458 	isync();
1459 
1460 	return (PCPU_GET(qmap_addr));
1461 }
1462 
1463 void
1464 moea64_quick_remove_page(vm_offset_t addr)
1465 {
1466 	if (hw_direct_map)
1467 		return;
1468 
1469 	mtx_assert(PCPU_PTR(aim.qmap_lock), MA_OWNED);
1470 	KASSERT(PCPU_GET(qmap_addr) == addr,
1471 	    ("moea64_quick_remove_page: invalid address"));
1472 	mtx_unlock(PCPU_PTR(aim.qmap_lock));
1473 	sched_unpin();
1474 }
1475 
1476 boolean_t
1477 moea64_page_is_mapped(vm_page_t m)
1478 {
1479 	return (!LIST_EMPTY(&(m)->md.mdpg_pvoh));
1480 }
1481 
1482 /*
1483  * Map the given physical page at the specified virtual address in the
1484  * target pmap with the protection requested.  If specified the page
1485  * will be wired down.
1486  */
1487 
1488 int
1489 moea64_enter(pmap_t pmap, vm_offset_t va, vm_page_t m,
1490     vm_prot_t prot, u_int flags, int8_t psind)
1491 {
1492 	struct		pvo_entry *pvo, *oldpvo;
1493 	struct		pvo_head *pvo_head;
1494 	uint64_t	pte_lo;
1495 	int		error;
1496 
1497 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1498 		if ((flags & PMAP_ENTER_QUICK_LOCKED) == 0)
1499 			VM_PAGE_OBJECT_BUSY_ASSERT(m);
1500 		else
1501 			VM_OBJECT_ASSERT_LOCKED(m->object);
1502 	}
1503 
1504 	pvo = alloc_pvo_entry(0);
1505 	if (pvo == NULL)
1506 		return (KERN_RESOURCE_SHORTAGE);
1507 	pvo->pvo_pmap = NULL; /* to be filled in later */
1508 	pvo->pvo_pte.prot = prot;
1509 
1510 	pte_lo = moea64_calc_wimg(VM_PAGE_TO_PHYS(m), pmap_page_get_memattr(m));
1511 	pvo->pvo_pte.pa = VM_PAGE_TO_PHYS(m) | pte_lo;
1512 
1513 	if ((flags & PMAP_ENTER_WIRED) != 0)
1514 		pvo->pvo_vaddr |= PVO_WIRED;
1515 
1516 	if ((m->oflags & VPO_UNMANAGED) != 0 || !moea64_initialized) {
1517 		pvo_head = NULL;
1518 	} else {
1519 		pvo_head = &m->md.mdpg_pvoh;
1520 		pvo->pvo_vaddr |= PVO_MANAGED;
1521 	}
1522 
1523 	PV_PAGE_LOCK(m);
1524 	PMAP_LOCK(pmap);
1525 	if (pvo->pvo_pmap == NULL)
1526 		init_pvo_entry(pvo, pmap, va);
1527 	if (prot & VM_PROT_WRITE)
1528 		if (pmap_bootstrapped &&
1529 		    (m->oflags & VPO_UNMANAGED) == 0)
1530 			vm_page_aflag_set(m, PGA_WRITEABLE);
1531 
1532 	error = moea64_pvo_enter(pvo, pvo_head, &oldpvo);
1533 	if (error == EEXIST) {
1534 		if (oldpvo->pvo_vaddr == pvo->pvo_vaddr &&
1535 		    oldpvo->pvo_pte.pa == pvo->pvo_pte.pa &&
1536 		    oldpvo->pvo_pte.prot == prot) {
1537 			/* Identical mapping already exists */
1538 			error = 0;
1539 
1540 			/* If not in page table, reinsert it */
1541 			if (moea64_pte_synch(oldpvo) < 0) {
1542 				STAT_MOEA64(moea64_pte_overflow--);
1543 				moea64_pte_insert(oldpvo);
1544 			}
1545 
1546 			/* Then just clean up and go home */
1547 			PV_PAGE_UNLOCK(m);
1548 			PMAP_UNLOCK(pmap);
1549 			free_pvo_entry(pvo);
1550 			goto out;
1551 		} else {
1552 			/* Otherwise, need to kill it first */
1553 			KASSERT(oldpvo->pvo_pmap == pmap, ("pmap of old "
1554 			    "mapping does not match new mapping"));
1555 			moea64_pvo_remove_from_pmap(oldpvo);
1556 			moea64_pvo_enter(pvo, pvo_head, NULL);
1557 		}
1558 	}
1559 	PMAP_UNLOCK(pmap);
1560 	PV_PAGE_UNLOCK(m);
1561 
1562 	/* Free any dead pages */
1563 	if (error == EEXIST) {
1564 		moea64_pvo_remove_from_page(oldpvo);
1565 		free_pvo_entry(oldpvo);
1566 	}
1567 
1568 out:
1569 	/*
1570 	 * Flush the page from the instruction cache if this page is
1571 	 * mapped executable and cacheable.
1572 	 */
1573 	if (pmap != kernel_pmap && (m->a.flags & PGA_EXECUTABLE) == 0 &&
1574 	    (pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
1575 		vm_page_aflag_set(m, PGA_EXECUTABLE);
1576 		moea64_syncicache(pmap, va, VM_PAGE_TO_PHYS(m), PAGE_SIZE);
1577 	}
1578 	return (KERN_SUCCESS);
1579 }
1580 
1581 static void
1582 moea64_syncicache(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1583     vm_size_t sz)
1584 {
1585 
1586 	/*
1587 	 * This is much trickier than on older systems because
1588 	 * we can't sync the icache on physical addresses directly
1589 	 * without a direct map. Instead we check a couple of cases
1590 	 * where the memory is already mapped in and, failing that,
1591 	 * use the same trick we use for page zeroing to create
1592 	 * a temporary mapping for this physical address.
1593 	 */
1594 
1595 	if (!pmap_bootstrapped) {
1596 		/*
1597 		 * If PMAP is not bootstrapped, we are likely to be
1598 		 * in real mode.
1599 		 */
1600 		__syncicache((void *)(uintptr_t)pa, sz);
1601 	} else if (pmap == kernel_pmap) {
1602 		__syncicache((void *)va, sz);
1603 	} else if (hw_direct_map) {
1604 		__syncicache((void *)(uintptr_t)PHYS_TO_DMAP(pa), sz);
1605 	} else {
1606 		/* Use the scratch page to set up a temp mapping */
1607 
1608 		mtx_lock(&moea64_scratchpage_mtx);
1609 
1610 		moea64_set_scratchpage_pa(1, pa & ~ADDR_POFF);
1611 		__syncicache((void *)(moea64_scratchpage_va[1] +
1612 		    (va & ADDR_POFF)), sz);
1613 
1614 		mtx_unlock(&moea64_scratchpage_mtx);
1615 	}
1616 }
1617 
1618 /*
1619  * Maps a sequence of resident pages belonging to the same object.
1620  * The sequence begins with the given page m_start.  This page is
1621  * mapped at the given virtual address start.  Each subsequent page is
1622  * mapped at a virtual address that is offset from start by the same
1623  * amount as the page is offset from m_start within the object.  The
1624  * last page in the sequence is the page with the largest offset from
1625  * m_start that can be mapped at a virtual address less than the given
1626  * virtual address end.  Not every virtual page between start and end
1627  * is mapped; only those for which a resident page exists with the
1628  * corresponding offset from m_start are mapped.
1629  */
1630 void
1631 moea64_enter_object(pmap_t pm, vm_offset_t start, vm_offset_t end,
1632     vm_page_t m_start, vm_prot_t prot)
1633 {
1634 	vm_page_t m;
1635 	vm_pindex_t diff, psize;
1636 
1637 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1638 
1639 	psize = atop(end - start);
1640 	m = m_start;
1641 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1642 		moea64_enter(pm, start + ptoa(diff), m, prot &
1643 		    (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_NOSLEEP |
1644 		    PMAP_ENTER_QUICK_LOCKED, 0);
1645 		m = TAILQ_NEXT(m, listq);
1646 	}
1647 }
1648 
1649 void
1650 moea64_enter_quick(pmap_t pm, vm_offset_t va, vm_page_t m,
1651     vm_prot_t prot)
1652 {
1653 
1654 	moea64_enter(pm, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1655 	    PMAP_ENTER_NOSLEEP | PMAP_ENTER_QUICK_LOCKED, 0);
1656 }
1657 
1658 vm_paddr_t
1659 moea64_extract(pmap_t pm, vm_offset_t va)
1660 {
1661 	struct	pvo_entry *pvo;
1662 	vm_paddr_t pa;
1663 
1664 	PMAP_LOCK(pm);
1665 	pvo = moea64_pvo_find_va(pm, va);
1666 	if (pvo == NULL)
1667 		pa = 0;
1668 	else
1669 		pa = PVO_PADDR(pvo) | (va - PVO_VADDR(pvo));
1670 	PMAP_UNLOCK(pm);
1671 
1672 	return (pa);
1673 }
1674 
1675 /*
1676  * Atomically extract and hold the physical page with the given
1677  * pmap and virtual address pair if that mapping permits the given
1678  * protection.
1679  */
1680 vm_page_t
1681 moea64_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1682 {
1683 	struct	pvo_entry *pvo;
1684 	vm_page_t m;
1685 
1686 	m = NULL;
1687 	PMAP_LOCK(pmap);
1688 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
1689 	if (pvo != NULL && (pvo->pvo_pte.prot & prot) == prot) {
1690 		m = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
1691 		if (!vm_page_wire_mapped(m))
1692 			m = NULL;
1693 	}
1694 	PMAP_UNLOCK(pmap);
1695 	return (m);
1696 }
1697 
1698 static void *
1699 moea64_uma_page_alloc(uma_zone_t zone, vm_size_t bytes, int domain,
1700     uint8_t *flags, int wait)
1701 {
1702 	struct pvo_entry *pvo;
1703         vm_offset_t va;
1704         vm_page_t m;
1705         int needed_lock;
1706 
1707 	/*
1708 	 * This entire routine is a horrible hack to avoid bothering kmem
1709 	 * for new KVA addresses. Because this can get called from inside
1710 	 * kmem allocation routines, calling kmem for a new address here
1711 	 * can lead to multiply locking non-recursive mutexes.
1712 	 */
1713 
1714 	*flags = UMA_SLAB_PRIV;
1715 	needed_lock = !PMAP_LOCKED(kernel_pmap);
1716 
1717 	m = vm_page_alloc_domain(NULL, 0, domain,
1718 	    malloc2vm_flags(wait) | VM_ALLOC_WIRED | VM_ALLOC_NOOBJ);
1719 	if (m == NULL)
1720 		return (NULL);
1721 
1722 	va = VM_PAGE_TO_PHYS(m);
1723 
1724 	pvo = alloc_pvo_entry(1 /* bootstrap */);
1725 
1726 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE;
1727 	pvo->pvo_pte.pa = VM_PAGE_TO_PHYS(m) | LPTE_M;
1728 
1729 	if (needed_lock)
1730 		PMAP_LOCK(kernel_pmap);
1731 
1732 	init_pvo_entry(pvo, kernel_pmap, va);
1733 	pvo->pvo_vaddr |= PVO_WIRED;
1734 
1735 	moea64_pvo_enter(pvo, NULL, NULL);
1736 
1737 	if (needed_lock)
1738 		PMAP_UNLOCK(kernel_pmap);
1739 
1740 	if ((wait & M_ZERO) && (m->flags & PG_ZERO) == 0)
1741                 bzero((void *)va, PAGE_SIZE);
1742 
1743 	return (void *)va;
1744 }
1745 
1746 extern int elf32_nxstack;
1747 
1748 void
1749 moea64_init()
1750 {
1751 
1752 	CTR0(KTR_PMAP, "moea64_init");
1753 
1754 	moea64_pvo_zone = uma_zcreate("UPVO entry", sizeof (struct pvo_entry),
1755 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1756 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1757 
1758 	if (!hw_direct_map) {
1759 		uma_zone_set_allocf(moea64_pvo_zone, moea64_uma_page_alloc);
1760 	}
1761 
1762 #ifdef COMPAT_FREEBSD32
1763 	elf32_nxstack = 1;
1764 #endif
1765 
1766 	moea64_initialized = TRUE;
1767 }
1768 
1769 boolean_t
1770 moea64_is_referenced(vm_page_t m)
1771 {
1772 
1773 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1774 	    ("moea64_is_referenced: page %p is not managed", m));
1775 
1776 	return (moea64_query_bit(m, LPTE_REF));
1777 }
1778 
1779 boolean_t
1780 moea64_is_modified(vm_page_t m)
1781 {
1782 
1783 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1784 	    ("moea64_is_modified: page %p is not managed", m));
1785 
1786 	/*
1787 	 * If the page is not busied then this check is racy.
1788 	 */
1789 	if (!pmap_page_is_write_mapped(m))
1790 		return (FALSE);
1791 
1792 	return (moea64_query_bit(m, LPTE_CHG));
1793 }
1794 
1795 boolean_t
1796 moea64_is_prefaultable(pmap_t pmap, vm_offset_t va)
1797 {
1798 	struct pvo_entry *pvo;
1799 	boolean_t rv = TRUE;
1800 
1801 	PMAP_LOCK(pmap);
1802 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
1803 	if (pvo != NULL)
1804 		rv = FALSE;
1805 	PMAP_UNLOCK(pmap);
1806 	return (rv);
1807 }
1808 
1809 void
1810 moea64_clear_modify(vm_page_t m)
1811 {
1812 
1813 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1814 	    ("moea64_clear_modify: page %p is not managed", m));
1815 	vm_page_assert_busied(m);
1816 
1817 	if (!pmap_page_is_write_mapped(m))
1818 		return;
1819 	moea64_clear_bit(m, LPTE_CHG);
1820 }
1821 
1822 /*
1823  * Clear the write and modified bits in each of the given page's mappings.
1824  */
1825 void
1826 moea64_remove_write(vm_page_t m)
1827 {
1828 	struct	pvo_entry *pvo;
1829 	int64_t	refchg, ret;
1830 	pmap_t	pmap;
1831 
1832 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1833 	    ("moea64_remove_write: page %p is not managed", m));
1834 	vm_page_assert_busied(m);
1835 
1836 	if (!pmap_page_is_write_mapped(m))
1837 		return
1838 
1839 	powerpc_sync();
1840 	PV_PAGE_LOCK(m);
1841 	refchg = 0;
1842 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1843 		pmap = pvo->pvo_pmap;
1844 		PMAP_LOCK(pmap);
1845 		if (!(pvo->pvo_vaddr & PVO_DEAD) &&
1846 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1847 			pvo->pvo_pte.prot &= ~VM_PROT_WRITE;
1848 			ret = moea64_pte_replace(pvo, MOEA64_PTE_PROT_UPDATE);
1849 			if (ret < 0)
1850 				ret = LPTE_CHG;
1851 			refchg |= ret;
1852 			if (pvo->pvo_pmap == kernel_pmap)
1853 				isync();
1854 		}
1855 		PMAP_UNLOCK(pmap);
1856 	}
1857 	if ((refchg | atomic_readandclear_32(&m->md.mdpg_attrs)) & LPTE_CHG)
1858 		vm_page_dirty(m);
1859 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1860 	PV_PAGE_UNLOCK(m);
1861 }
1862 
1863 /*
1864  *	moea64_ts_referenced:
1865  *
1866  *	Return a count of reference bits for a page, clearing those bits.
1867  *	It is not necessary for every reference bit to be cleared, but it
1868  *	is necessary that 0 only be returned when there are truly no
1869  *	reference bits set.
1870  *
1871  *	XXX: The exact number of bits to check and clear is a matter that
1872  *	should be tested and standardized at some point in the future for
1873  *	optimal aging of shared pages.
1874  */
1875 int
1876 moea64_ts_referenced(vm_page_t m)
1877 {
1878 
1879 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1880 	    ("moea64_ts_referenced: page %p is not managed", m));
1881 	return (moea64_clear_bit(m, LPTE_REF));
1882 }
1883 
1884 /*
1885  * Modify the WIMG settings of all mappings for a page.
1886  */
1887 void
1888 moea64_page_set_memattr(vm_page_t m, vm_memattr_t ma)
1889 {
1890 	struct	pvo_entry *pvo;
1891 	int64_t	refchg;
1892 	pmap_t	pmap;
1893 	uint64_t lo;
1894 
1895 	if ((m->oflags & VPO_UNMANAGED) != 0) {
1896 		m->md.mdpg_cache_attrs = ma;
1897 		return;
1898 	}
1899 
1900 	lo = moea64_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
1901 
1902 	PV_PAGE_LOCK(m);
1903 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1904 		pmap = pvo->pvo_pmap;
1905 		PMAP_LOCK(pmap);
1906 		if (!(pvo->pvo_vaddr & PVO_DEAD)) {
1907 			pvo->pvo_pte.pa &= ~LPTE_WIMG;
1908 			pvo->pvo_pte.pa |= lo;
1909 			refchg = moea64_pte_replace(pvo, MOEA64_PTE_INVALIDATE);
1910 			if (refchg < 0)
1911 				refchg = (pvo->pvo_pte.prot & VM_PROT_WRITE) ?
1912 				    LPTE_CHG : 0;
1913 			if ((pvo->pvo_vaddr & PVO_MANAGED) &&
1914 			    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1915 				refchg |=
1916 				    atomic_readandclear_32(&m->md.mdpg_attrs);
1917 				if (refchg & LPTE_CHG)
1918 					vm_page_dirty(m);
1919 				if (refchg & LPTE_REF)
1920 					vm_page_aflag_set(m, PGA_REFERENCED);
1921 			}
1922 			if (pvo->pvo_pmap == kernel_pmap)
1923 				isync();
1924 		}
1925 		PMAP_UNLOCK(pmap);
1926 	}
1927 	m->md.mdpg_cache_attrs = ma;
1928 	PV_PAGE_UNLOCK(m);
1929 }
1930 
1931 /*
1932  * Map a wired page into kernel virtual address space.
1933  */
1934 void
1935 moea64_kenter_attr(vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1936 {
1937 	int		error;
1938 	struct pvo_entry *pvo, *oldpvo;
1939 
1940 	do {
1941 		pvo = alloc_pvo_entry(0);
1942 		if (pvo == NULL)
1943 			vm_wait(NULL);
1944 	} while (pvo == NULL);
1945 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
1946 	pvo->pvo_pte.pa = (pa & ~ADDR_POFF) | moea64_calc_wimg(pa, ma);
1947 	pvo->pvo_vaddr |= PVO_WIRED;
1948 
1949 	PMAP_LOCK(kernel_pmap);
1950 	oldpvo = moea64_pvo_find_va(kernel_pmap, va);
1951 	if (oldpvo != NULL)
1952 		moea64_pvo_remove_from_pmap(oldpvo);
1953 	init_pvo_entry(pvo, kernel_pmap, va);
1954 	error = moea64_pvo_enter(pvo, NULL, NULL);
1955 	PMAP_UNLOCK(kernel_pmap);
1956 
1957 	/* Free any dead pages */
1958 	if (oldpvo != NULL) {
1959 		moea64_pvo_remove_from_page(oldpvo);
1960 		free_pvo_entry(oldpvo);
1961 	}
1962 
1963 	if (error != 0)
1964 		panic("moea64_kenter: failed to enter va %#zx pa %#jx: %d", va,
1965 		    (uintmax_t)pa, error);
1966 }
1967 
1968 void
1969 moea64_kenter(vm_offset_t va, vm_paddr_t pa)
1970 {
1971 
1972 	moea64_kenter_attr(va, pa, VM_MEMATTR_DEFAULT);
1973 }
1974 
1975 /*
1976  * Extract the physical page address associated with the given kernel virtual
1977  * address.
1978  */
1979 vm_paddr_t
1980 moea64_kextract(vm_offset_t va)
1981 {
1982 	struct		pvo_entry *pvo;
1983 	vm_paddr_t pa;
1984 
1985 	/*
1986 	 * Shortcut the direct-mapped case when applicable.  We never put
1987 	 * anything but 1:1 (or 62-bit aliased) mappings below
1988 	 * VM_MIN_KERNEL_ADDRESS.
1989 	 */
1990 	if (va < VM_MIN_KERNEL_ADDRESS)
1991 		return (va & ~DMAP_BASE_ADDRESS);
1992 
1993 	PMAP_LOCK(kernel_pmap);
1994 	pvo = moea64_pvo_find_va(kernel_pmap, va);
1995 	KASSERT(pvo != NULL, ("moea64_kextract: no addr found for %#" PRIxPTR,
1996 	    va));
1997 	pa = PVO_PADDR(pvo) | (va - PVO_VADDR(pvo));
1998 	PMAP_UNLOCK(kernel_pmap);
1999 	return (pa);
2000 }
2001 
2002 /*
2003  * Remove a wired page from kernel virtual address space.
2004  */
2005 void
2006 moea64_kremove(vm_offset_t va)
2007 {
2008 	moea64_remove(kernel_pmap, va, va + PAGE_SIZE);
2009 }
2010 
2011 /*
2012  * Provide a kernel pointer corresponding to a given userland pointer.
2013  * The returned pointer is valid until the next time this function is
2014  * called in this thread. This is used internally in copyin/copyout.
2015  */
2016 static int
2017 moea64_map_user_ptr(pmap_t pm, volatile const void *uaddr,
2018     void **kaddr, size_t ulen, size_t *klen)
2019 {
2020 	size_t l;
2021 #ifdef __powerpc64__
2022 	struct slb *slb;
2023 #endif
2024 	register_t slbv;
2025 
2026 	*kaddr = (char *)USER_ADDR + ((uintptr_t)uaddr & ~SEGMENT_MASK);
2027 	l = ((char *)USER_ADDR + SEGMENT_LENGTH) - (char *)(*kaddr);
2028 	if (l > ulen)
2029 		l = ulen;
2030 	if (klen)
2031 		*klen = l;
2032 	else if (l != ulen)
2033 		return (EFAULT);
2034 
2035 #ifdef __powerpc64__
2036 	/* Try lockless look-up first */
2037 	slb = user_va_to_slb_entry(pm, (vm_offset_t)uaddr);
2038 
2039 	if (slb == NULL) {
2040 		/* If it isn't there, we need to pre-fault the VSID */
2041 		PMAP_LOCK(pm);
2042 		slbv = va_to_vsid(pm, (vm_offset_t)uaddr) << SLBV_VSID_SHIFT;
2043 		PMAP_UNLOCK(pm);
2044 	} else {
2045 		slbv = slb->slbv;
2046 	}
2047 
2048 	/* Mark segment no-execute */
2049 	slbv |= SLBV_N;
2050 #else
2051 	slbv = va_to_vsid(pm, (vm_offset_t)uaddr);
2052 
2053 	/* Mark segment no-execute */
2054 	slbv |= SR_N;
2055 #endif
2056 
2057 	/* If we have already set this VSID, we can just return */
2058 	if (curthread->td_pcb->pcb_cpu.aim.usr_vsid == slbv)
2059 		return (0);
2060 
2061 	__asm __volatile("isync");
2062 	curthread->td_pcb->pcb_cpu.aim.usr_segm =
2063 	    (uintptr_t)uaddr >> ADDR_SR_SHFT;
2064 	curthread->td_pcb->pcb_cpu.aim.usr_vsid = slbv;
2065 #ifdef __powerpc64__
2066 	__asm __volatile ("slbie %0; slbmte %1, %2; isync" ::
2067 	    "r"(USER_ADDR), "r"(slbv), "r"(USER_SLB_SLBE));
2068 #else
2069 	__asm __volatile("mtsr %0,%1; isync" :: "n"(USER_SR), "r"(slbv));
2070 #endif
2071 
2072 	return (0);
2073 }
2074 
2075 /*
2076  * Figure out where a given kernel pointer (usually in a fault) points
2077  * to from the VM's perspective, potentially remapping into userland's
2078  * address space.
2079  */
2080 static int
2081 moea64_decode_kernel_ptr(vm_offset_t addr, int *is_user,
2082     vm_offset_t *decoded_addr)
2083 {
2084 	vm_offset_t user_sr;
2085 
2086 	if ((addr >> ADDR_SR_SHFT) == (USER_ADDR >> ADDR_SR_SHFT)) {
2087 		user_sr = curthread->td_pcb->pcb_cpu.aim.usr_segm;
2088 		addr &= ADDR_PIDX | ADDR_POFF;
2089 		addr |= user_sr << ADDR_SR_SHFT;
2090 		*decoded_addr = addr;
2091 		*is_user = 1;
2092 	} else {
2093 		*decoded_addr = addr;
2094 		*is_user = 0;
2095 	}
2096 
2097 	return (0);
2098 }
2099 
2100 /*
2101  * Map a range of physical addresses into kernel virtual address space.
2102  *
2103  * The value passed in *virt is a suggested virtual address for the mapping.
2104  * Architectures which can support a direct-mapped physical to virtual region
2105  * can return the appropriate address within that region, leaving '*virt'
2106  * unchanged.  Other architectures should map the pages starting at '*virt' and
2107  * update '*virt' with the first usable address after the mapped region.
2108  */
2109 vm_offset_t
2110 moea64_map(vm_offset_t *virt, vm_paddr_t pa_start,
2111     vm_paddr_t pa_end, int prot)
2112 {
2113 	vm_offset_t	sva, va;
2114 
2115 	if (hw_direct_map) {
2116 		/*
2117 		 * Check if every page in the region is covered by the direct
2118 		 * map. The direct map covers all of physical memory. Use
2119 		 * moea64_calc_wimg() as a shortcut to see if the page is in
2120 		 * physical memory as a way to see if the direct map covers it.
2121 		 */
2122 		for (va = pa_start; va < pa_end; va += PAGE_SIZE)
2123 			if (moea64_calc_wimg(va, VM_MEMATTR_DEFAULT) != LPTE_M)
2124 				break;
2125 		if (va == pa_end)
2126 			return (PHYS_TO_DMAP(pa_start));
2127 	}
2128 	sva = *virt;
2129 	va = sva;
2130 	/* XXX respect prot argument */
2131 	for (; pa_start < pa_end; pa_start += PAGE_SIZE, va += PAGE_SIZE)
2132 		moea64_kenter(va, pa_start);
2133 	*virt = va;
2134 
2135 	return (sva);
2136 }
2137 
2138 /*
2139  * Returns true if the pmap's pv is one of the first
2140  * 16 pvs linked to from this page.  This count may
2141  * be changed upwards or downwards in the future; it
2142  * is only necessary that true be returned for a small
2143  * subset of pmaps for proper page aging.
2144  */
2145 boolean_t
2146 moea64_page_exists_quick(pmap_t pmap, vm_page_t m)
2147 {
2148         int loops;
2149 	struct pvo_entry *pvo;
2150 	boolean_t rv;
2151 
2152 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2153 	    ("moea64_page_exists_quick: page %p is not managed", m));
2154 	loops = 0;
2155 	rv = FALSE;
2156 	PV_PAGE_LOCK(m);
2157 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2158 		if (!(pvo->pvo_vaddr & PVO_DEAD) && pvo->pvo_pmap == pmap) {
2159 			rv = TRUE;
2160 			break;
2161 		}
2162 		if (++loops >= 16)
2163 			break;
2164 	}
2165 	PV_PAGE_UNLOCK(m);
2166 	return (rv);
2167 }
2168 
2169 void
2170 moea64_page_init(vm_page_t m)
2171 {
2172 
2173 	m->md.mdpg_attrs = 0;
2174 	m->md.mdpg_cache_attrs = VM_MEMATTR_DEFAULT;
2175 	LIST_INIT(&m->md.mdpg_pvoh);
2176 }
2177 
2178 /*
2179  * Return the number of managed mappings to the given physical page
2180  * that are wired.
2181  */
2182 int
2183 moea64_page_wired_mappings(vm_page_t m)
2184 {
2185 	struct pvo_entry *pvo;
2186 	int count;
2187 
2188 	count = 0;
2189 	if ((m->oflags & VPO_UNMANAGED) != 0)
2190 		return (count);
2191 	PV_PAGE_LOCK(m);
2192 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
2193 		if ((pvo->pvo_vaddr & (PVO_DEAD | PVO_WIRED)) == PVO_WIRED)
2194 			count++;
2195 	PV_PAGE_UNLOCK(m);
2196 	return (count);
2197 }
2198 
2199 static uintptr_t	moea64_vsidcontext;
2200 
2201 uintptr_t
2202 moea64_get_unique_vsid(void) {
2203 	u_int entropy;
2204 	register_t hash;
2205 	uint32_t mask;
2206 	int i;
2207 
2208 	entropy = 0;
2209 	__asm __volatile("mftb %0" : "=r"(entropy));
2210 
2211 	mtx_lock(&moea64_slb_mutex);
2212 	for (i = 0; i < NVSIDS; i += VSID_NBPW) {
2213 		u_int	n;
2214 
2215 		/*
2216 		 * Create a new value by mutiplying by a prime and adding in
2217 		 * entropy from the timebase register.  This is to make the
2218 		 * VSID more random so that the PT hash function collides
2219 		 * less often.  (Note that the prime casues gcc to do shifts
2220 		 * instead of a multiply.)
2221 		 */
2222 		moea64_vsidcontext = (moea64_vsidcontext * 0x1105) + entropy;
2223 		hash = moea64_vsidcontext & (NVSIDS - 1);
2224 		if (hash == 0)		/* 0 is special, avoid it */
2225 			continue;
2226 		n = hash >> 5;
2227 		mask = 1 << (hash & (VSID_NBPW - 1));
2228 		hash = (moea64_vsidcontext & VSID_HASHMASK);
2229 		if (moea64_vsid_bitmap[n] & mask) {	/* collision? */
2230 			/* anything free in this bucket? */
2231 			if (moea64_vsid_bitmap[n] == 0xffffffff) {
2232 				entropy = (moea64_vsidcontext >> 20);
2233 				continue;
2234 			}
2235 			i = ffs(~moea64_vsid_bitmap[n]) - 1;
2236 			mask = 1 << i;
2237 			hash &= rounddown2(VSID_HASHMASK, VSID_NBPW);
2238 			hash |= i;
2239 		}
2240 		if (hash == VSID_VRMA)	/* also special, avoid this too */
2241 			continue;
2242 		KASSERT(!(moea64_vsid_bitmap[n] & mask),
2243 		    ("Allocating in-use VSID %#zx\n", hash));
2244 		moea64_vsid_bitmap[n] |= mask;
2245 		mtx_unlock(&moea64_slb_mutex);
2246 		return (hash);
2247 	}
2248 
2249 	mtx_unlock(&moea64_slb_mutex);
2250 	panic("%s: out of segments",__func__);
2251 }
2252 
2253 #ifdef __powerpc64__
2254 int
2255 moea64_pinit(pmap_t pmap)
2256 {
2257 
2258 	RB_INIT(&pmap->pmap_pvo);
2259 
2260 	pmap->pm_slb_tree_root = slb_alloc_tree();
2261 	pmap->pm_slb = slb_alloc_user_cache();
2262 	pmap->pm_slb_len = 0;
2263 
2264 	return (1);
2265 }
2266 #else
2267 int
2268 moea64_pinit(pmap_t pmap)
2269 {
2270 	int	i;
2271 	uint32_t hash;
2272 
2273 	RB_INIT(&pmap->pmap_pvo);
2274 
2275 	if (pmap_bootstrapped)
2276 		pmap->pmap_phys = (pmap_t)moea64_kextract((vm_offset_t)pmap);
2277 	else
2278 		pmap->pmap_phys = pmap;
2279 
2280 	/*
2281 	 * Allocate some segment registers for this pmap.
2282 	 */
2283 	hash = moea64_get_unique_vsid();
2284 
2285 	for (i = 0; i < 16; i++)
2286 		pmap->pm_sr[i] = VSID_MAKE(i, hash);
2287 
2288 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_pinit: pm_sr[0] = 0"));
2289 
2290 	return (1);
2291 }
2292 #endif
2293 
2294 /*
2295  * Initialize the pmap associated with process 0.
2296  */
2297 void
2298 moea64_pinit0(pmap_t pm)
2299 {
2300 
2301 	PMAP_LOCK_INIT(pm);
2302 	moea64_pinit(pm);
2303 	bzero(&pm->pm_stats, sizeof(pm->pm_stats));
2304 }
2305 
2306 /*
2307  * Set the physical protection on the specified range of this map as requested.
2308  */
2309 static void
2310 moea64_pvo_protect( pmap_t pm, struct pvo_entry *pvo, vm_prot_t prot)
2311 {
2312 	struct vm_page *pg;
2313 	vm_prot_t oldprot;
2314 	int32_t refchg;
2315 
2316 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
2317 
2318 	/*
2319 	 * Change the protection of the page.
2320 	 */
2321 	oldprot = pvo->pvo_pte.prot;
2322 	pvo->pvo_pte.prot = prot;
2323 	pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2324 
2325 	/*
2326 	 * If the PVO is in the page table, update mapping
2327 	 */
2328 	refchg = moea64_pte_replace(pvo, MOEA64_PTE_PROT_UPDATE);
2329 	if (refchg < 0)
2330 		refchg = (oldprot & VM_PROT_WRITE) ? LPTE_CHG : 0;
2331 
2332 	if (pm != kernel_pmap && pg != NULL &&
2333 	    (pg->a.flags & PGA_EXECUTABLE) == 0 &&
2334 	    (pvo->pvo_pte.pa & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
2335 		if ((pg->oflags & VPO_UNMANAGED) == 0)
2336 			vm_page_aflag_set(pg, PGA_EXECUTABLE);
2337 		moea64_syncicache(pm, PVO_VADDR(pvo),
2338 		    PVO_PADDR(pvo), PAGE_SIZE);
2339 	}
2340 
2341 	/*
2342 	 * Update vm about the REF/CHG bits if the page is managed and we have
2343 	 * removed write access.
2344 	 */
2345 	if (pg != NULL && (pvo->pvo_vaddr & PVO_MANAGED) &&
2346 	    (oldprot & VM_PROT_WRITE)) {
2347 		refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2348 		if (refchg & LPTE_CHG)
2349 			vm_page_dirty(pg);
2350 		if (refchg & LPTE_REF)
2351 			vm_page_aflag_set(pg, PGA_REFERENCED);
2352 	}
2353 }
2354 
2355 void
2356 moea64_protect(pmap_t pm, vm_offset_t sva, vm_offset_t eva,
2357     vm_prot_t prot)
2358 {
2359 	struct	pvo_entry *pvo, *tpvo, key;
2360 
2361 	CTR4(KTR_PMAP, "moea64_protect: pm=%p sva=%#x eva=%#x prot=%#x", pm,
2362 	    sva, eva, prot);
2363 
2364 	KASSERT(pm == &curproc->p_vmspace->vm_pmap || pm == kernel_pmap,
2365 	    ("moea64_protect: non current pmap"));
2366 
2367 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2368 		moea64_remove(pm, sva, eva);
2369 		return;
2370 	}
2371 
2372 	PMAP_LOCK(pm);
2373 	key.pvo_vaddr = sva;
2374 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2375 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
2376 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
2377 		moea64_pvo_protect(pm, pvo, prot);
2378 	}
2379 	PMAP_UNLOCK(pm);
2380 }
2381 
2382 /*
2383  * Map a list of wired pages into kernel virtual address space.  This is
2384  * intended for temporary mappings which do not need page modification or
2385  * references recorded.  Existing mappings in the region are overwritten.
2386  */
2387 void
2388 moea64_qenter(vm_offset_t va, vm_page_t *m, int count)
2389 {
2390 	while (count-- > 0) {
2391 		moea64_kenter(va, VM_PAGE_TO_PHYS(*m));
2392 		va += PAGE_SIZE;
2393 		m++;
2394 	}
2395 }
2396 
2397 /*
2398  * Remove page mappings from kernel virtual address space.  Intended for
2399  * temporary mappings entered by moea64_qenter.
2400  */
2401 void
2402 moea64_qremove(vm_offset_t va, int count)
2403 {
2404 	while (count-- > 0) {
2405 		moea64_kremove(va);
2406 		va += PAGE_SIZE;
2407 	}
2408 }
2409 
2410 void
2411 moea64_release_vsid(uint64_t vsid)
2412 {
2413 	int idx, mask;
2414 
2415 	mtx_lock(&moea64_slb_mutex);
2416 	idx = vsid & (NVSIDS-1);
2417 	mask = 1 << (idx % VSID_NBPW);
2418 	idx /= VSID_NBPW;
2419 	KASSERT(moea64_vsid_bitmap[idx] & mask,
2420 	    ("Freeing unallocated VSID %#jx", vsid));
2421 	moea64_vsid_bitmap[idx] &= ~mask;
2422 	mtx_unlock(&moea64_slb_mutex);
2423 }
2424 
2425 void
2426 moea64_release(pmap_t pmap)
2427 {
2428 
2429 	/*
2430 	 * Free segment registers' VSIDs
2431 	 */
2432     #ifdef __powerpc64__
2433 	slb_free_tree(pmap);
2434 	slb_free_user_cache(pmap->pm_slb);
2435     #else
2436 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_release: pm_sr[0] = 0"));
2437 
2438 	moea64_release_vsid(VSID_TO_HASH(pmap->pm_sr[0]));
2439     #endif
2440 }
2441 
2442 /*
2443  * Remove all pages mapped by the specified pmap
2444  */
2445 void
2446 moea64_remove_pages(pmap_t pm)
2447 {
2448 	struct pvo_entry *pvo, *tpvo;
2449 	struct pvo_dlist tofree;
2450 
2451 	SLIST_INIT(&tofree);
2452 
2453 	PMAP_LOCK(pm);
2454 	RB_FOREACH_SAFE(pvo, pvo_tree, &pm->pmap_pvo, tpvo) {
2455 		if (pvo->pvo_vaddr & PVO_WIRED)
2456 			continue;
2457 
2458 		/*
2459 		 * For locking reasons, remove this from the page table and
2460 		 * pmap, but save delinking from the vm_page for a second
2461 		 * pass
2462 		 */
2463 		moea64_pvo_remove_from_pmap(pvo);
2464 		SLIST_INSERT_HEAD(&tofree, pvo, pvo_dlink);
2465 	}
2466 	PMAP_UNLOCK(pm);
2467 
2468 	while (!SLIST_EMPTY(&tofree)) {
2469 		pvo = SLIST_FIRST(&tofree);
2470 		SLIST_REMOVE_HEAD(&tofree, pvo_dlink);
2471 		moea64_pvo_remove_from_page(pvo);
2472 		free_pvo_entry(pvo);
2473 	}
2474 }
2475 
2476 /*
2477  * Remove the given range of addresses from the specified map.
2478  */
2479 void
2480 moea64_remove(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
2481 {
2482 	struct  pvo_entry *pvo, *tpvo, key;
2483 	struct pvo_dlist tofree;
2484 
2485 	/*
2486 	 * Perform an unsynchronized read.  This is, however, safe.
2487 	 */
2488 	if (pm->pm_stats.resident_count == 0)
2489 		return;
2490 
2491 	key.pvo_vaddr = sva;
2492 
2493 	SLIST_INIT(&tofree);
2494 
2495 	PMAP_LOCK(pm);
2496 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2497 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
2498 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
2499 
2500 		/*
2501 		 * For locking reasons, remove this from the page table and
2502 		 * pmap, but save delinking from the vm_page for a second
2503 		 * pass
2504 		 */
2505 		moea64_pvo_remove_from_pmap(pvo);
2506 		SLIST_INSERT_HEAD(&tofree, pvo, pvo_dlink);
2507 	}
2508 	PMAP_UNLOCK(pm);
2509 
2510 	while (!SLIST_EMPTY(&tofree)) {
2511 		pvo = SLIST_FIRST(&tofree);
2512 		SLIST_REMOVE_HEAD(&tofree, pvo_dlink);
2513 		moea64_pvo_remove_from_page(pvo);
2514 		free_pvo_entry(pvo);
2515 	}
2516 }
2517 
2518 /*
2519  * Remove physical page from all pmaps in which it resides. moea64_pvo_remove()
2520  * will reflect changes in pte's back to the vm_page.
2521  */
2522 void
2523 moea64_remove_all(vm_page_t m)
2524 {
2525 	struct	pvo_entry *pvo, *next_pvo;
2526 	struct	pvo_head freequeue;
2527 	int	wasdead;
2528 	pmap_t	pmap;
2529 
2530 	LIST_INIT(&freequeue);
2531 
2532 	PV_PAGE_LOCK(m);
2533 	LIST_FOREACH_SAFE(pvo, vm_page_to_pvoh(m), pvo_vlink, next_pvo) {
2534 		pmap = pvo->pvo_pmap;
2535 		PMAP_LOCK(pmap);
2536 		wasdead = (pvo->pvo_vaddr & PVO_DEAD);
2537 		if (!wasdead)
2538 			moea64_pvo_remove_from_pmap(pvo);
2539 		moea64_pvo_remove_from_page_locked(pvo, m);
2540 		if (!wasdead)
2541 			LIST_INSERT_HEAD(&freequeue, pvo, pvo_vlink);
2542 		PMAP_UNLOCK(pmap);
2543 
2544 	}
2545 	KASSERT(!pmap_page_is_mapped(m), ("Page still has mappings"));
2546 	KASSERT((m->a.flags & PGA_WRITEABLE) == 0, ("Page still writable"));
2547 	PV_PAGE_UNLOCK(m);
2548 
2549 	/* Clean up UMA allocations */
2550 	LIST_FOREACH_SAFE(pvo, &freequeue, pvo_vlink, next_pvo)
2551 		free_pvo_entry(pvo);
2552 }
2553 
2554 /*
2555  * Allocate a physical page of memory directly from the phys_avail map.
2556  * Can only be called from moea64_bootstrap before avail start and end are
2557  * calculated.
2558  */
2559 vm_offset_t
2560 moea64_bootstrap_alloc(vm_size_t size, vm_size_t align)
2561 {
2562 	vm_offset_t	s, e;
2563 	int		i, j;
2564 
2565 	size = round_page(size);
2566 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
2567 		if (align != 0)
2568 			s = roundup2(phys_avail[i], align);
2569 		else
2570 			s = phys_avail[i];
2571 		e = s + size;
2572 
2573 		if (s < phys_avail[i] || e > phys_avail[i + 1])
2574 			continue;
2575 
2576 		if (s + size > platform_real_maxaddr())
2577 			continue;
2578 
2579 		if (s == phys_avail[i]) {
2580 			phys_avail[i] += size;
2581 		} else if (e == phys_avail[i + 1]) {
2582 			phys_avail[i + 1] -= size;
2583 		} else {
2584 			for (j = phys_avail_count * 2; j > i; j -= 2) {
2585 				phys_avail[j] = phys_avail[j - 2];
2586 				phys_avail[j + 1] = phys_avail[j - 1];
2587 			}
2588 
2589 			phys_avail[i + 3] = phys_avail[i + 1];
2590 			phys_avail[i + 1] = s;
2591 			phys_avail[i + 2] = e;
2592 			phys_avail_count++;
2593 		}
2594 
2595 		return (s);
2596 	}
2597 	panic("moea64_bootstrap_alloc: could not allocate memory");
2598 }
2599 
2600 static int
2601 moea64_pvo_enter(struct pvo_entry *pvo, struct pvo_head *pvo_head,
2602     struct pvo_entry **oldpvop)
2603 {
2604 	struct pvo_entry *old_pvo;
2605 	int err;
2606 
2607 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2608 
2609 	STAT_MOEA64(moea64_pvo_enter_calls++);
2610 
2611 	/*
2612 	 * Add to pmap list
2613 	 */
2614 	old_pvo = RB_INSERT(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2615 
2616 	if (old_pvo != NULL) {
2617 		if (oldpvop != NULL)
2618 			*oldpvop = old_pvo;
2619 		return (EEXIST);
2620 	}
2621 
2622 	if (pvo_head != NULL) {
2623 		LIST_INSERT_HEAD(pvo_head, pvo, pvo_vlink);
2624 	}
2625 
2626 	if (pvo->pvo_vaddr & PVO_WIRED)
2627 		pvo->pvo_pmap->pm_stats.wired_count++;
2628 	pvo->pvo_pmap->pm_stats.resident_count++;
2629 
2630 	/*
2631 	 * Insert it into the hardware page table
2632 	 */
2633 	err = moea64_pte_insert(pvo);
2634 	if (err != 0) {
2635 		panic("moea64_pvo_enter: overflow");
2636 	}
2637 
2638 	STAT_MOEA64(moea64_pvo_entries++);
2639 
2640 	if (pvo->pvo_pmap == kernel_pmap)
2641 		isync();
2642 
2643 #ifdef __powerpc64__
2644 	/*
2645 	 * Make sure all our bootstrap mappings are in the SLB as soon
2646 	 * as virtual memory is switched on.
2647 	 */
2648 	if (!pmap_bootstrapped)
2649 		moea64_bootstrap_slb_prefault(PVO_VADDR(pvo),
2650 		    pvo->pvo_vaddr & PVO_LARGE);
2651 #endif
2652 
2653 	return (0);
2654 }
2655 
2656 static void
2657 moea64_pvo_remove_from_pmap(struct pvo_entry *pvo)
2658 {
2659 	struct	vm_page *pg;
2660 	int32_t refchg;
2661 
2662 	KASSERT(pvo->pvo_pmap != NULL, ("Trying to remove PVO with no pmap"));
2663 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2664 	KASSERT(!(pvo->pvo_vaddr & PVO_DEAD), ("Trying to remove dead PVO"));
2665 
2666 	/*
2667 	 * If there is an active pte entry, we need to deactivate it
2668 	 */
2669 	refchg = moea64_pte_unset(pvo);
2670 	if (refchg < 0) {
2671 		/*
2672 		 * If it was evicted from the page table, be pessimistic and
2673 		 * dirty the page.
2674 		 */
2675 		if (pvo->pvo_pte.prot & VM_PROT_WRITE)
2676 			refchg = LPTE_CHG;
2677 		else
2678 			refchg = 0;
2679 	}
2680 
2681 	/*
2682 	 * Update our statistics.
2683 	 */
2684 	pvo->pvo_pmap->pm_stats.resident_count--;
2685 	if (pvo->pvo_vaddr & PVO_WIRED)
2686 		pvo->pvo_pmap->pm_stats.wired_count--;
2687 
2688 	/*
2689 	 * Remove this PVO from the pmap list.
2690 	 */
2691 	RB_REMOVE(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2692 
2693 	/*
2694 	 * Mark this for the next sweep
2695 	 */
2696 	pvo->pvo_vaddr |= PVO_DEAD;
2697 
2698 	/* Send RC bits to VM */
2699 	if ((pvo->pvo_vaddr & PVO_MANAGED) &&
2700 	    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
2701 		pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2702 		if (pg != NULL) {
2703 			refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2704 			if (refchg & LPTE_CHG)
2705 				vm_page_dirty(pg);
2706 			if (refchg & LPTE_REF)
2707 				vm_page_aflag_set(pg, PGA_REFERENCED);
2708 		}
2709 	}
2710 }
2711 
2712 static inline void
2713 moea64_pvo_remove_from_page_locked(struct pvo_entry *pvo,
2714     vm_page_t m)
2715 {
2716 
2717 	KASSERT(pvo->pvo_vaddr & PVO_DEAD, ("Trying to delink live page"));
2718 
2719 	/* Use NULL pmaps as a sentinel for races in page deletion */
2720 	if (pvo->pvo_pmap == NULL)
2721 		return;
2722 	pvo->pvo_pmap = NULL;
2723 
2724 	/*
2725 	 * Update vm about page writeability/executability if managed
2726 	 */
2727 	PV_LOCKASSERT(PVO_PADDR(pvo));
2728 	if (pvo->pvo_vaddr & PVO_MANAGED) {
2729 		if (m != NULL) {
2730 			LIST_REMOVE(pvo, pvo_vlink);
2731 			if (LIST_EMPTY(vm_page_to_pvoh(m)))
2732 				vm_page_aflag_clear(m,
2733 				    PGA_WRITEABLE | PGA_EXECUTABLE);
2734 		}
2735 	}
2736 
2737 	STAT_MOEA64(moea64_pvo_entries--);
2738 	STAT_MOEA64(moea64_pvo_remove_calls++);
2739 }
2740 
2741 static void
2742 moea64_pvo_remove_from_page(struct pvo_entry *pvo)
2743 {
2744 	vm_page_t pg = NULL;
2745 
2746 	if (pvo->pvo_vaddr & PVO_MANAGED)
2747 		pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2748 
2749 	PV_LOCK(PVO_PADDR(pvo));
2750 	moea64_pvo_remove_from_page_locked(pvo, pg);
2751 	PV_UNLOCK(PVO_PADDR(pvo));
2752 }
2753 
2754 static struct pvo_entry *
2755 moea64_pvo_find_va(pmap_t pm, vm_offset_t va)
2756 {
2757 	struct pvo_entry key;
2758 
2759 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
2760 
2761 	key.pvo_vaddr = va & ~ADDR_POFF;
2762 	return (RB_FIND(pvo_tree, &pm->pmap_pvo, &key));
2763 }
2764 
2765 static boolean_t
2766 moea64_query_bit(vm_page_t m, uint64_t ptebit)
2767 {
2768 	struct	pvo_entry *pvo;
2769 	int64_t ret;
2770 	boolean_t rv;
2771 
2772 	/*
2773 	 * See if this bit is stored in the page already.
2774 	 */
2775 	if (m->md.mdpg_attrs & ptebit)
2776 		return (TRUE);
2777 
2778 	/*
2779 	 * Examine each PTE.  Sync so that any pending REF/CHG bits are
2780 	 * flushed to the PTEs.
2781 	 */
2782 	rv = FALSE;
2783 	powerpc_sync();
2784 	PV_PAGE_LOCK(m);
2785 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2786 		ret = 0;
2787 
2788 		/*
2789 		 * See if this pvo has a valid PTE.  if so, fetch the
2790 		 * REF/CHG bits from the valid PTE.  If the appropriate
2791 		 * ptebit is set, return success.
2792 		 */
2793 		PMAP_LOCK(pvo->pvo_pmap);
2794 		if (!(pvo->pvo_vaddr & PVO_DEAD))
2795 			ret = moea64_pte_synch(pvo);
2796 		PMAP_UNLOCK(pvo->pvo_pmap);
2797 
2798 		if (ret > 0) {
2799 			atomic_set_32(&m->md.mdpg_attrs,
2800 			    ret & (LPTE_CHG | LPTE_REF));
2801 			if (ret & ptebit) {
2802 				rv = TRUE;
2803 				break;
2804 			}
2805 		}
2806 	}
2807 	PV_PAGE_UNLOCK(m);
2808 
2809 	return (rv);
2810 }
2811 
2812 static u_int
2813 moea64_clear_bit(vm_page_t m, u_int64_t ptebit)
2814 {
2815 	u_int	count;
2816 	struct	pvo_entry *pvo;
2817 	int64_t ret;
2818 
2819 	/*
2820 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
2821 	 * we can reset the right ones).
2822 	 */
2823 	powerpc_sync();
2824 
2825 	/*
2826 	 * For each pvo entry, clear the pte's ptebit.
2827 	 */
2828 	count = 0;
2829 	PV_PAGE_LOCK(m);
2830 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2831 		ret = 0;
2832 
2833 		PMAP_LOCK(pvo->pvo_pmap);
2834 		if (!(pvo->pvo_vaddr & PVO_DEAD))
2835 			ret = moea64_pte_clear(pvo, ptebit);
2836 		PMAP_UNLOCK(pvo->pvo_pmap);
2837 
2838 		if (ret > 0 && (ret & ptebit))
2839 			count++;
2840 	}
2841 	atomic_clear_32(&m->md.mdpg_attrs, ptebit);
2842 	PV_PAGE_UNLOCK(m);
2843 
2844 	return (count);
2845 }
2846 
2847 boolean_t
2848 moea64_dev_direct_mapped(vm_paddr_t pa, vm_size_t size)
2849 {
2850 	struct pvo_entry *pvo, key;
2851 	vm_offset_t ppa;
2852 	int error = 0;
2853 
2854 	if (hw_direct_map && mem_valid(pa, size) == 0)
2855 		return (0);
2856 
2857 	PMAP_LOCK(kernel_pmap);
2858 	ppa = pa & ~ADDR_POFF;
2859 	key.pvo_vaddr = DMAP_BASE_ADDRESS + ppa;
2860 	for (pvo = RB_FIND(pvo_tree, &kernel_pmap->pmap_pvo, &key);
2861 	    ppa < pa + size; ppa += PAGE_SIZE,
2862 	    pvo = RB_NEXT(pvo_tree, &kernel_pmap->pmap_pvo, pvo)) {
2863 		if (pvo == NULL || PVO_PADDR(pvo) != ppa) {
2864 			error = EFAULT;
2865 			break;
2866 		}
2867 	}
2868 	PMAP_UNLOCK(kernel_pmap);
2869 
2870 	return (error);
2871 }
2872 
2873 /*
2874  * Map a set of physical memory pages into the kernel virtual
2875  * address space. Return a pointer to where it is mapped. This
2876  * routine is intended to be used for mapping device memory,
2877  * NOT real memory.
2878  */
2879 void *
2880 moea64_mapdev_attr(vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2881 {
2882 	vm_offset_t va, tmpva, ppa, offset;
2883 
2884 	ppa = trunc_page(pa);
2885 	offset = pa & PAGE_MASK;
2886 	size = roundup2(offset + size, PAGE_SIZE);
2887 
2888 	va = kva_alloc(size);
2889 
2890 	if (!va)
2891 		panic("moea64_mapdev: Couldn't alloc kernel virtual memory");
2892 
2893 	for (tmpva = va; size > 0;) {
2894 		moea64_kenter_attr(tmpva, ppa, ma);
2895 		size -= PAGE_SIZE;
2896 		tmpva += PAGE_SIZE;
2897 		ppa += PAGE_SIZE;
2898 	}
2899 
2900 	return ((void *)(va + offset));
2901 }
2902 
2903 void *
2904 moea64_mapdev(vm_paddr_t pa, vm_size_t size)
2905 {
2906 
2907 	return moea64_mapdev_attr(pa, size, VM_MEMATTR_DEFAULT);
2908 }
2909 
2910 void
2911 moea64_unmapdev(vm_offset_t va, vm_size_t size)
2912 {
2913 	vm_offset_t base, offset;
2914 
2915 	base = trunc_page(va);
2916 	offset = va & PAGE_MASK;
2917 	size = roundup2(offset + size, PAGE_SIZE);
2918 
2919 	moea64_qremove(base, atop(size));
2920 	kva_free(base, size);
2921 }
2922 
2923 void
2924 moea64_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
2925 {
2926 	struct pvo_entry *pvo;
2927 	vm_offset_t lim;
2928 	vm_paddr_t pa;
2929 	vm_size_t len;
2930 
2931 	if (__predict_false(pm == NULL))
2932 		pm = &curthread->td_proc->p_vmspace->vm_pmap;
2933 
2934 	PMAP_LOCK(pm);
2935 	while (sz > 0) {
2936 		lim = round_page(va+1);
2937 		len = MIN(lim - va, sz);
2938 		pvo = moea64_pvo_find_va(pm, va & ~ADDR_POFF);
2939 		if (pvo != NULL && !(pvo->pvo_pte.pa & LPTE_I)) {
2940 			pa = PVO_PADDR(pvo) | (va & ADDR_POFF);
2941 			moea64_syncicache(pm, va, pa, len);
2942 		}
2943 		va += len;
2944 		sz -= len;
2945 	}
2946 	PMAP_UNLOCK(pm);
2947 }
2948 
2949 void
2950 moea64_dumpsys_map(vm_paddr_t pa, size_t sz, void **va)
2951 {
2952 
2953 	*va = (void *)(uintptr_t)pa;
2954 }
2955 
2956 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2957 
2958 void
2959 moea64_scan_init()
2960 {
2961 	struct pvo_entry *pvo;
2962 	vm_offset_t va;
2963 	int i;
2964 
2965 	if (!do_minidump) {
2966 		/* Initialize phys. segments for dumpsys(). */
2967 		memset(&dump_map, 0, sizeof(dump_map));
2968 		mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
2969 		for (i = 0; i < pregions_sz; i++) {
2970 			dump_map[i].pa_start = pregions[i].mr_start;
2971 			dump_map[i].pa_size = pregions[i].mr_size;
2972 		}
2973 		return;
2974 	}
2975 
2976 	/* Virtual segments for minidumps: */
2977 	memset(&dump_map, 0, sizeof(dump_map));
2978 
2979 	/* 1st: kernel .data and .bss. */
2980 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2981 	dump_map[0].pa_size = round_page((uintptr_t)_end) -
2982 	    dump_map[0].pa_start;
2983 
2984 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2985 	dump_map[1].pa_start = (vm_paddr_t)(uintptr_t)msgbufp->msg_ptr;
2986 	dump_map[1].pa_size = round_page(msgbufp->msg_size);
2987 
2988 	/* 3rd: kernel VM. */
2989 	va = dump_map[1].pa_start + dump_map[1].pa_size;
2990 	/* Find start of next chunk (from va). */
2991 	while (va < virtual_end) {
2992 		/* Don't dump the buffer cache. */
2993 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2994 			va = kmi.buffer_eva;
2995 			continue;
2996 		}
2997 		pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
2998 		if (pvo != NULL && !(pvo->pvo_vaddr & PVO_DEAD))
2999 			break;
3000 		va += PAGE_SIZE;
3001 	}
3002 	if (va < virtual_end) {
3003 		dump_map[2].pa_start = va;
3004 		va += PAGE_SIZE;
3005 		/* Find last page in chunk. */
3006 		while (va < virtual_end) {
3007 			/* Don't run into the buffer cache. */
3008 			if (va == kmi.buffer_sva)
3009 				break;
3010 			pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
3011 			if (pvo == NULL || (pvo->pvo_vaddr & PVO_DEAD))
3012 				break;
3013 			va += PAGE_SIZE;
3014 		}
3015 		dump_map[2].pa_size = va - dump_map[2].pa_start;
3016 	}
3017 }
3018 
3019 #ifdef __powerpc64__
3020 
3021 static size_t
3022 moea64_scan_pmap()
3023 {
3024 	struct pvo_entry *pvo;
3025 	vm_paddr_t pa, pa_end;
3026 	vm_offset_t va, pgva, kstart, kend, kstart_lp, kend_lp;
3027 	uint64_t lpsize;
3028 
3029 	lpsize = moea64_large_page_size;
3030 	kstart = trunc_page((vm_offset_t)_etext);
3031 	kend = round_page((vm_offset_t)_end);
3032 	kstart_lp = kstart & ~moea64_large_page_mask;
3033 	kend_lp = (kend + moea64_large_page_mask) & ~moea64_large_page_mask;
3034 
3035 	CTR4(KTR_PMAP, "moea64_scan_pmap: kstart=0x%016lx, kend=0x%016lx, "
3036 	    "kstart_lp=0x%016lx, kend_lp=0x%016lx",
3037 	    kstart, kend, kstart_lp, kend_lp);
3038 
3039 	PMAP_LOCK(kernel_pmap);
3040 	RB_FOREACH(pvo, pvo_tree, &kernel_pmap->pmap_pvo) {
3041 		va = pvo->pvo_vaddr;
3042 
3043 		if (va & PVO_DEAD)
3044 			continue;
3045 
3046 		/* Skip DMAP (except kernel area) */
3047 		if (va >= DMAP_BASE_ADDRESS && va <= DMAP_MAX_ADDRESS) {
3048 			if (va & PVO_LARGE) {
3049 				pgva = va & ~moea64_large_page_mask;
3050 				if (pgva < kstart_lp || pgva >= kend_lp)
3051 					continue;
3052 			} else {
3053 				pgva = trunc_page(va);
3054 				if (pgva < kstart || pgva >= kend)
3055 					continue;
3056 			}
3057 		}
3058 
3059 		pa = PVO_PADDR(pvo);
3060 
3061 		if (va & PVO_LARGE) {
3062 			pa_end = pa + lpsize;
3063 			for (; pa < pa_end; pa += PAGE_SIZE) {
3064 				if (is_dumpable(pa))
3065 					dump_add_page(pa);
3066 			}
3067 		} else {
3068 			if (is_dumpable(pa))
3069 				dump_add_page(pa);
3070 		}
3071 	}
3072 	PMAP_UNLOCK(kernel_pmap);
3073 
3074 	return (sizeof(struct lpte) * moea64_pteg_count * 8);
3075 }
3076 
3077 static struct dump_context dump_ctx;
3078 
3079 static void *
3080 moea64_dump_pmap_init(unsigned blkpgs)
3081 {
3082 	dump_ctx.ptex = 0;
3083 	dump_ctx.ptex_end = moea64_pteg_count * 8;
3084 	dump_ctx.blksz = blkpgs * PAGE_SIZE;
3085 	return (&dump_ctx);
3086 }
3087 
3088 #else
3089 
3090 static size_t
3091 moea64_scan_pmap()
3092 {
3093 	return (0);
3094 }
3095 
3096 static void *
3097 moea64_dump_pmap_init(unsigned blkpgs)
3098 {
3099 	return (NULL);
3100 }
3101 
3102 #endif
3103 
3104 #ifdef __powerpc64__
3105 static void
3106 moea64_map_range(vm_offset_t va, vm_paddr_t pa, vm_size_t npages)
3107 {
3108 
3109 	for (; npages > 0; --npages) {
3110 		if (moea64_large_page_size != 0 &&
3111 		    (pa & moea64_large_page_mask) == 0 &&
3112 		    (va & moea64_large_page_mask) == 0 &&
3113 		    npages >= (moea64_large_page_size >> PAGE_SHIFT)) {
3114 			PMAP_LOCK(kernel_pmap);
3115 			moea64_kenter_large(va, pa, 0, 0);
3116 			PMAP_UNLOCK(kernel_pmap);
3117 			pa += moea64_large_page_size;
3118 			va += moea64_large_page_size;
3119 			npages -= (moea64_large_page_size >> PAGE_SHIFT) - 1;
3120 		} else {
3121 			moea64_kenter(va, pa);
3122 			pa += PAGE_SIZE;
3123 			va += PAGE_SIZE;
3124 		}
3125 	}
3126 }
3127 
3128 static void
3129 moea64_page_array_startup(long pages)
3130 {
3131 	long dom_pages[MAXMEMDOM];
3132 	vm_paddr_t pa;
3133 	vm_offset_t va, vm_page_base;
3134 	vm_size_t needed, size;
3135 	long page;
3136 	int domain;
3137 	int i;
3138 
3139 	vm_page_base = 0xd000000000000000ULL;
3140 
3141 	/* Short-circuit single-domain systems. */
3142 	if (vm_ndomains == 1) {
3143 		size = round_page(pages * sizeof(struct vm_page));
3144 		pa = vm_phys_early_alloc(0, size);
3145 		vm_page_base = moea64_map(&vm_page_base,
3146 		    pa, pa + size, VM_PROT_READ | VM_PROT_WRITE);
3147 		vm_page_array_size = pages;
3148 		vm_page_array = (vm_page_t)vm_page_base;
3149 		return;
3150 	}
3151 
3152 	page = 0;
3153 	for (i = 0; i < MAXMEMDOM; i++)
3154 		dom_pages[i] = 0;
3155 
3156 	/* Now get the number of pages required per domain. */
3157 	for (i = 0; i < vm_phys_nsegs; i++) {
3158 		domain = vm_phys_segs[i].domain;
3159 		KASSERT(domain < MAXMEMDOM,
3160 		    ("Invalid vm_phys_segs NUMA domain %d!\n", domain));
3161 		/* Get size of vm_page_array needed for this segment. */
3162 		size = btoc(vm_phys_segs[i].end - vm_phys_segs[i].start);
3163 		dom_pages[domain] += size;
3164 	}
3165 
3166 	for (i = 0; phys_avail[i + 1] != 0; i+= 2) {
3167 		domain = _vm_phys_domain(phys_avail[i]);
3168 		KASSERT(domain < MAXMEMDOM,
3169 		    ("Invalid phys_avail NUMA domain %d!\n", domain));
3170 		size = btoc(phys_avail[i + 1] - phys_avail[i]);
3171 		dom_pages[domain] += size;
3172 	}
3173 
3174 	/*
3175 	 * Map in chunks that can get us all 16MB pages.  There will be some
3176 	 * overlap between domains, but that's acceptable for now.
3177 	 */
3178 	vm_page_array_size = 0;
3179 	va = vm_page_base;
3180 	for (i = 0; i < MAXMEMDOM && vm_page_array_size < pages; i++) {
3181 		if (dom_pages[i] == 0)
3182 			continue;
3183 		size = ulmin(pages - vm_page_array_size, dom_pages[i]);
3184 		size = round_page(size * sizeof(struct vm_page));
3185 		needed = size;
3186 		size = roundup2(size, moea64_large_page_size);
3187 		pa = vm_phys_early_alloc(i, size);
3188 		vm_page_array_size += size / sizeof(struct vm_page);
3189 		moea64_map_range(va, pa, size >> PAGE_SHIFT);
3190 		/* Scoot up domain 0, to reduce the domain page overlap. */
3191 		if (i == 0)
3192 			vm_page_base += size - needed;
3193 		va += size;
3194 	}
3195 	vm_page_array = (vm_page_t)vm_page_base;
3196 	vm_page_array_size = pages;
3197 }
3198 #endif
3199 
3200 static int64_t
3201 moea64_null_method(void)
3202 {
3203 	return (0);
3204 }
3205 
3206 static int64_t moea64_pte_replace_default(struct pvo_entry *pvo, int flags)
3207 {
3208 	int64_t refchg;
3209 
3210 	refchg = moea64_pte_unset(pvo);
3211 	moea64_pte_insert(pvo);
3212 
3213 	return (refchg);
3214 }
3215 
3216 struct moea64_funcs *moea64_ops;
3217 
3218 #define DEFINE_OEA64_IFUNC(ret, func, args, def)		\
3219 	DEFINE_IFUNC(, ret, moea64_##func, args) {		\
3220 		moea64_##func##_t f;				\
3221 		if (moea64_ops == NULL)				\
3222 			return ((moea64_##func##_t)def);	\
3223 		f = moea64_ops->func;				\
3224 		return (f != NULL ? f : (moea64_##func##_t)def);\
3225 	}
3226 
3227 DEFINE_OEA64_IFUNC(int64_t, pte_replace, (struct pvo_entry *, int),
3228     moea64_pte_replace_default)
3229 DEFINE_OEA64_IFUNC(int64_t, pte_insert, (struct pvo_entry *), moea64_null_method)
3230 DEFINE_OEA64_IFUNC(int64_t, pte_unset, (struct pvo_entry *), moea64_null_method)
3231 DEFINE_OEA64_IFUNC(int64_t, pte_clear, (struct pvo_entry *, uint64_t),
3232     moea64_null_method)
3233 DEFINE_OEA64_IFUNC(int64_t, pte_synch, (struct pvo_entry *), moea64_null_method)
3234