xref: /freebsd/sys/powerpc/aim/mmu_oea64.c (revision 2ccda62ff8e78c384d3c55b8acc1bcf399d26f2c)
1 /*-
2  * Copyright (c) 2008-2015 Nathan Whitehorn
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  * Manages physical address maps.
32  *
33  * Since the information managed by this module is also stored by the
34  * logical address mapping module, this module may throw away valid virtual
35  * to physical mappings at almost any time.  However, invalidations of
36  * mappings must be done as requested.
37  *
38  * In order to cope with hardware architectures which make virtual to
39  * physical map invalidates expensive, this module may delay invalidate
40  * reduced protection operations until such time as they are actually
41  * necessary.  This module is given full information as to which processors
42  * are currently using which maps, and to when physical maps must be made
43  * correct.
44  */
45 
46 #include "opt_compat.h"
47 #include "opt_kstack_pages.h"
48 
49 #include <sys/param.h>
50 #include <sys/kernel.h>
51 #include <sys/conf.h>
52 #include <sys/queue.h>
53 #include <sys/cpuset.h>
54 #include <sys/kerneldump.h>
55 #include <sys/ktr.h>
56 #include <sys/lock.h>
57 #include <sys/msgbuf.h>
58 #include <sys/malloc.h>
59 #include <sys/mutex.h>
60 #include <sys/proc.h>
61 #include <sys/rwlock.h>
62 #include <sys/sched.h>
63 #include <sys/sysctl.h>
64 #include <sys/systm.h>
65 #include <sys/vmmeter.h>
66 
67 #include <sys/kdb.h>
68 
69 #include <dev/ofw/openfirm.h>
70 
71 #include <vm/vm.h>
72 #include <vm/vm_param.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_pageout.h>
79 #include <vm/uma.h>
80 
81 #include <machine/_inttypes.h>
82 #include <machine/cpu.h>
83 #include <machine/platform.h>
84 #include <machine/frame.h>
85 #include <machine/md_var.h>
86 #include <machine/psl.h>
87 #include <machine/bat.h>
88 #include <machine/hid.h>
89 #include <machine/pte.h>
90 #include <machine/sr.h>
91 #include <machine/trap.h>
92 #include <machine/mmuvar.h>
93 
94 #include "mmu_oea64.h"
95 #include "mmu_if.h"
96 #include "moea64_if.h"
97 
98 void moea64_release_vsid(uint64_t vsid);
99 uintptr_t moea64_get_unique_vsid(void);
100 
101 #define DISABLE_TRANS(msr)	msr = mfmsr(); mtmsr(msr & ~PSL_DR)
102 #define ENABLE_TRANS(msr)	mtmsr(msr)
103 
104 #define	VSID_MAKE(sr, hash)	((sr) | (((hash) & 0xfffff) << 4))
105 #define	VSID_TO_HASH(vsid)	(((vsid) >> 4) & 0xfffff)
106 #define	VSID_HASH_MASK		0x0000007fffffffffULL
107 
108 /*
109  * Locking semantics:
110  *
111  * There are two locks of interest: the page locks and the pmap locks, which
112  * protect their individual PVO lists and are locked in that order. The contents
113  * of all PVO entries are protected by the locks of their respective pmaps.
114  * The pmap of any PVO is guaranteed not to change so long as the PVO is linked
115  * into any list.
116  *
117  */
118 
119 #define PV_LOCK_COUNT	PA_LOCK_COUNT*3
120 static struct mtx_padalign pv_lock[PV_LOCK_COUNT];
121 
122 #define PV_LOCKPTR(pa)	((struct mtx *)(&pv_lock[pa_index(pa) % PV_LOCK_COUNT]))
123 #define PV_LOCK(pa)		mtx_lock(PV_LOCKPTR(pa))
124 #define PV_UNLOCK(pa)		mtx_unlock(PV_LOCKPTR(pa))
125 #define PV_LOCKASSERT(pa) 	mtx_assert(PV_LOCKPTR(pa), MA_OWNED)
126 #define PV_PAGE_LOCK(m)		PV_LOCK(VM_PAGE_TO_PHYS(m))
127 #define PV_PAGE_UNLOCK(m)	PV_UNLOCK(VM_PAGE_TO_PHYS(m))
128 #define PV_PAGE_LOCKASSERT(m)	PV_LOCKASSERT(VM_PAGE_TO_PHYS(m))
129 
130 struct ofw_map {
131 	cell_t	om_va;
132 	cell_t	om_len;
133 	uint64_t om_pa;
134 	cell_t	om_mode;
135 };
136 
137 extern unsigned char _etext[];
138 extern unsigned char _end[];
139 
140 /*
141  * Map of physical memory regions.
142  */
143 static struct	mem_region *regions;
144 static struct	mem_region *pregions;
145 static u_int	phys_avail_count;
146 static int	regions_sz, pregions_sz;
147 
148 extern void bs_remap_earlyboot(void);
149 
150 /*
151  * Lock for the SLB tables.
152  */
153 struct mtx	moea64_slb_mutex;
154 
155 /*
156  * PTEG data.
157  */
158 u_int		moea64_pteg_count;
159 u_int		moea64_pteg_mask;
160 
161 /*
162  * PVO data.
163  */
164 
165 uma_zone_t	moea64_pvo_zone; /* zone for pvo entries */
166 
167 static struct	pvo_entry *moea64_bpvo_pool;
168 static int	moea64_bpvo_pool_index = 0;
169 static int	moea64_bpvo_pool_size = 327680;
170 TUNABLE_INT("machdep.moea64_bpvo_pool_size", &moea64_bpvo_pool_size);
171 SYSCTL_INT(_machdep, OID_AUTO, moea64_allocated_bpvo_entries, CTLFLAG_RD,
172     &moea64_bpvo_pool_index, 0, "");
173 
174 #define	VSID_NBPW	(sizeof(u_int32_t) * 8)
175 #ifdef __powerpc64__
176 #define	NVSIDS		(NPMAPS * 16)
177 #define VSID_HASHMASK	0xffffffffUL
178 #else
179 #define NVSIDS		NPMAPS
180 #define VSID_HASHMASK	0xfffffUL
181 #endif
182 static u_int	moea64_vsid_bitmap[NVSIDS / VSID_NBPW];
183 
184 static boolean_t moea64_initialized = FALSE;
185 
186 /*
187  * Statistics.
188  */
189 u_int	moea64_pte_valid = 0;
190 u_int	moea64_pte_overflow = 0;
191 u_int	moea64_pvo_entries = 0;
192 u_int	moea64_pvo_enter_calls = 0;
193 u_int	moea64_pvo_remove_calls = 0;
194 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_valid, CTLFLAG_RD,
195     &moea64_pte_valid, 0, "");
196 SYSCTL_INT(_machdep, OID_AUTO, moea64_pte_overflow, CTLFLAG_RD,
197     &moea64_pte_overflow, 0, "");
198 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_entries, CTLFLAG_RD,
199     &moea64_pvo_entries, 0, "");
200 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_enter_calls, CTLFLAG_RD,
201     &moea64_pvo_enter_calls, 0, "");
202 SYSCTL_INT(_machdep, OID_AUTO, moea64_pvo_remove_calls, CTLFLAG_RD,
203     &moea64_pvo_remove_calls, 0, "");
204 
205 vm_offset_t	moea64_scratchpage_va[2];
206 struct pvo_entry *moea64_scratchpage_pvo[2];
207 struct	mtx	moea64_scratchpage_mtx;
208 
209 uint64_t 	moea64_large_page_mask = 0;
210 uint64_t	moea64_large_page_size = 0;
211 int		moea64_large_page_shift = 0;
212 
213 /*
214  * PVO calls.
215  */
216 static int	moea64_pvo_enter(mmu_t mmu, struct pvo_entry *pvo,
217 		    struct pvo_head *pvo_head);
218 static void	moea64_pvo_remove_from_pmap(mmu_t mmu, struct pvo_entry *pvo);
219 static void	moea64_pvo_remove_from_page(mmu_t mmu, struct pvo_entry *pvo);
220 static struct	pvo_entry *moea64_pvo_find_va(pmap_t, vm_offset_t);
221 
222 /*
223  * Utility routines.
224  */
225 static boolean_t	moea64_query_bit(mmu_t, vm_page_t, uint64_t);
226 static u_int		moea64_clear_bit(mmu_t, vm_page_t, uint64_t);
227 static void		moea64_kremove(mmu_t, vm_offset_t);
228 static void		moea64_syncicache(mmu_t, pmap_t pmap, vm_offset_t va,
229 			    vm_paddr_t pa, vm_size_t sz);
230 
231 /*
232  * Kernel MMU interface
233  */
234 void moea64_clear_modify(mmu_t, vm_page_t);
235 void moea64_copy_page(mmu_t, vm_page_t, vm_page_t);
236 void moea64_copy_pages(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
237     vm_page_t *mb, vm_offset_t b_offset, int xfersize);
238 int moea64_enter(mmu_t, pmap_t, vm_offset_t, vm_page_t, vm_prot_t,
239     u_int flags, int8_t psind);
240 void moea64_enter_object(mmu_t, pmap_t, vm_offset_t, vm_offset_t, vm_page_t,
241     vm_prot_t);
242 void moea64_enter_quick(mmu_t, pmap_t, vm_offset_t, vm_page_t, vm_prot_t);
243 vm_paddr_t moea64_extract(mmu_t, pmap_t, vm_offset_t);
244 vm_page_t moea64_extract_and_hold(mmu_t, pmap_t, vm_offset_t, vm_prot_t);
245 void moea64_init(mmu_t);
246 boolean_t moea64_is_modified(mmu_t, vm_page_t);
247 boolean_t moea64_is_prefaultable(mmu_t, pmap_t, vm_offset_t);
248 boolean_t moea64_is_referenced(mmu_t, vm_page_t);
249 int moea64_ts_referenced(mmu_t, vm_page_t);
250 vm_offset_t moea64_map(mmu_t, vm_offset_t *, vm_paddr_t, vm_paddr_t, int);
251 boolean_t moea64_page_exists_quick(mmu_t, pmap_t, vm_page_t);
252 int moea64_page_wired_mappings(mmu_t, vm_page_t);
253 void moea64_pinit(mmu_t, pmap_t);
254 void moea64_pinit0(mmu_t, pmap_t);
255 void moea64_protect(mmu_t, pmap_t, vm_offset_t, vm_offset_t, vm_prot_t);
256 void moea64_qenter(mmu_t, vm_offset_t, vm_page_t *, int);
257 void moea64_qremove(mmu_t, vm_offset_t, int);
258 void moea64_release(mmu_t, pmap_t);
259 void moea64_remove(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
260 void moea64_remove_pages(mmu_t, pmap_t);
261 void moea64_remove_all(mmu_t, vm_page_t);
262 void moea64_remove_write(mmu_t, vm_page_t);
263 void moea64_unwire(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
264 void moea64_zero_page(mmu_t, vm_page_t);
265 void moea64_zero_page_area(mmu_t, vm_page_t, int, int);
266 void moea64_zero_page_idle(mmu_t, vm_page_t);
267 void moea64_activate(mmu_t, struct thread *);
268 void moea64_deactivate(mmu_t, struct thread *);
269 void *moea64_mapdev(mmu_t, vm_paddr_t, vm_size_t);
270 void *moea64_mapdev_attr(mmu_t, vm_paddr_t, vm_size_t, vm_memattr_t);
271 void moea64_unmapdev(mmu_t, vm_offset_t, vm_size_t);
272 vm_paddr_t moea64_kextract(mmu_t, vm_offset_t);
273 void moea64_page_set_memattr(mmu_t, vm_page_t m, vm_memattr_t ma);
274 void moea64_kenter_attr(mmu_t, vm_offset_t, vm_paddr_t, vm_memattr_t ma);
275 void moea64_kenter(mmu_t, vm_offset_t, vm_paddr_t);
276 boolean_t moea64_dev_direct_mapped(mmu_t, vm_paddr_t, vm_size_t);
277 static void moea64_sync_icache(mmu_t, pmap_t, vm_offset_t, vm_size_t);
278 void moea64_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz,
279     void **va);
280 void moea64_scan_init(mmu_t mmu);
281 
282 static mmu_method_t moea64_methods[] = {
283 	MMUMETHOD(mmu_clear_modify,	moea64_clear_modify),
284 	MMUMETHOD(mmu_copy_page,	moea64_copy_page),
285 	MMUMETHOD(mmu_copy_pages,	moea64_copy_pages),
286 	MMUMETHOD(mmu_enter,		moea64_enter),
287 	MMUMETHOD(mmu_enter_object,	moea64_enter_object),
288 	MMUMETHOD(mmu_enter_quick,	moea64_enter_quick),
289 	MMUMETHOD(mmu_extract,		moea64_extract),
290 	MMUMETHOD(mmu_extract_and_hold,	moea64_extract_and_hold),
291 	MMUMETHOD(mmu_init,		moea64_init),
292 	MMUMETHOD(mmu_is_modified,	moea64_is_modified),
293 	MMUMETHOD(mmu_is_prefaultable,	moea64_is_prefaultable),
294 	MMUMETHOD(mmu_is_referenced,	moea64_is_referenced),
295 	MMUMETHOD(mmu_ts_referenced,	moea64_ts_referenced),
296 	MMUMETHOD(mmu_map,     		moea64_map),
297 	MMUMETHOD(mmu_page_exists_quick,moea64_page_exists_quick),
298 	MMUMETHOD(mmu_page_wired_mappings,moea64_page_wired_mappings),
299 	MMUMETHOD(mmu_pinit,		moea64_pinit),
300 	MMUMETHOD(mmu_pinit0,		moea64_pinit0),
301 	MMUMETHOD(mmu_protect,		moea64_protect),
302 	MMUMETHOD(mmu_qenter,		moea64_qenter),
303 	MMUMETHOD(mmu_qremove,		moea64_qremove),
304 	MMUMETHOD(mmu_release,		moea64_release),
305 	MMUMETHOD(mmu_remove,		moea64_remove),
306 	MMUMETHOD(mmu_remove_pages,	moea64_remove_pages),
307 	MMUMETHOD(mmu_remove_all,      	moea64_remove_all),
308 	MMUMETHOD(mmu_remove_write,	moea64_remove_write),
309 	MMUMETHOD(mmu_sync_icache,	moea64_sync_icache),
310 	MMUMETHOD(mmu_unwire,		moea64_unwire),
311 	MMUMETHOD(mmu_zero_page,       	moea64_zero_page),
312 	MMUMETHOD(mmu_zero_page_area,	moea64_zero_page_area),
313 	MMUMETHOD(mmu_zero_page_idle,	moea64_zero_page_idle),
314 	MMUMETHOD(mmu_activate,		moea64_activate),
315 	MMUMETHOD(mmu_deactivate,      	moea64_deactivate),
316 	MMUMETHOD(mmu_page_set_memattr,	moea64_page_set_memattr),
317 
318 	/* Internal interfaces */
319 	MMUMETHOD(mmu_mapdev,		moea64_mapdev),
320 	MMUMETHOD(mmu_mapdev_attr,	moea64_mapdev_attr),
321 	MMUMETHOD(mmu_unmapdev,		moea64_unmapdev),
322 	MMUMETHOD(mmu_kextract,		moea64_kextract),
323 	MMUMETHOD(mmu_kenter,		moea64_kenter),
324 	MMUMETHOD(mmu_kenter_attr,	moea64_kenter_attr),
325 	MMUMETHOD(mmu_dev_direct_mapped,moea64_dev_direct_mapped),
326 	MMUMETHOD(mmu_scan_init,	moea64_scan_init),
327 	MMUMETHOD(mmu_dumpsys_map,	moea64_dumpsys_map),
328 
329 	{ 0, 0 }
330 };
331 
332 MMU_DEF(oea64_mmu, "mmu_oea64_base", moea64_methods, 0);
333 
334 static struct pvo_head *
335 vm_page_to_pvoh(vm_page_t m)
336 {
337 
338 	mtx_assert(PV_LOCKPTR(VM_PAGE_TO_PHYS(m)), MA_OWNED);
339 	return (&m->md.mdpg_pvoh);
340 }
341 
342 static struct pvo_entry *
343 alloc_pvo_entry(int bootstrap)
344 {
345 	struct pvo_entry *pvo;
346 
347 	if (!moea64_initialized || bootstrap) {
348 		if (moea64_bpvo_pool_index >= moea64_bpvo_pool_size) {
349 			panic("moea64_enter: bpvo pool exhausted, %d, %d, %zd",
350 			      moea64_bpvo_pool_index, moea64_bpvo_pool_size,
351 			      moea64_bpvo_pool_size * sizeof(struct pvo_entry));
352 		}
353 		pvo = &moea64_bpvo_pool[
354 		    atomic_fetchadd_int(&moea64_bpvo_pool_index, 1)];
355 		bzero(pvo, sizeof(*pvo));
356 		pvo->pvo_vaddr = PVO_BOOTSTRAP;
357 	} else {
358 		pvo = uma_zalloc(moea64_pvo_zone, M_NOWAIT);
359 		bzero(pvo, sizeof(*pvo));
360 	}
361 
362 	return (pvo);
363 }
364 
365 
366 static void
367 init_pvo_entry(struct pvo_entry *pvo, pmap_t pmap, vm_offset_t va)
368 {
369 	uint64_t vsid;
370 	uint64_t hash;
371 	int shift;
372 
373 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
374 
375 	pvo->pvo_pmap = pmap;
376 	va &= ~ADDR_POFF;
377 	pvo->pvo_vaddr |= va;
378 	vsid = va_to_vsid(pmap, va);
379 	pvo->pvo_vpn = (uint64_t)((va & ADDR_PIDX) >> ADDR_PIDX_SHFT)
380 	    | (vsid << 16);
381 
382 	shift = (pvo->pvo_vaddr & PVO_LARGE) ? moea64_large_page_shift :
383 	    ADDR_PIDX_SHFT;
384 	hash = (vsid & VSID_HASH_MASK) ^ (((uint64_t)va & ADDR_PIDX) >> shift);
385 	pvo->pvo_pte.slot = (hash & moea64_pteg_mask) << 3;
386 }
387 
388 static void
389 free_pvo_entry(struct pvo_entry *pvo)
390 {
391 
392 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
393 		uma_zfree(moea64_pvo_zone, pvo);
394 }
395 
396 void
397 moea64_pte_from_pvo(const struct pvo_entry *pvo, struct lpte *lpte)
398 {
399 
400 	lpte->pte_hi = (pvo->pvo_vpn >> (ADDR_API_SHFT64 - ADDR_PIDX_SHFT)) &
401 	    LPTE_AVPN_MASK;
402 	lpte->pte_hi |= LPTE_VALID;
403 
404 	if (pvo->pvo_vaddr & PVO_LARGE)
405 		lpte->pte_hi |= LPTE_BIG;
406 	if (pvo->pvo_vaddr & PVO_WIRED)
407 		lpte->pte_hi |= LPTE_WIRED;
408 	if (pvo->pvo_vaddr & PVO_HID)
409 		lpte->pte_hi |= LPTE_HID;
410 
411 	lpte->pte_lo = pvo->pvo_pte.pa; /* Includes WIMG bits */
412 	if (pvo->pvo_pte.prot & VM_PROT_WRITE)
413 		lpte->pte_lo |= LPTE_BW;
414 	else
415 		lpte->pte_lo |= LPTE_BR;
416 
417 	if (!(pvo->pvo_pte.prot & VM_PROT_EXECUTE))
418 		lpte->pte_lo |= LPTE_NOEXEC;
419 }
420 
421 static __inline uint64_t
422 moea64_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
423 {
424 	uint64_t pte_lo;
425 	int i;
426 
427 	if (ma != VM_MEMATTR_DEFAULT) {
428 		switch (ma) {
429 		case VM_MEMATTR_UNCACHEABLE:
430 			return (LPTE_I | LPTE_G);
431 		case VM_MEMATTR_WRITE_COMBINING:
432 		case VM_MEMATTR_WRITE_BACK:
433 		case VM_MEMATTR_PREFETCHABLE:
434 			return (LPTE_I);
435 		case VM_MEMATTR_WRITE_THROUGH:
436 			return (LPTE_W | LPTE_M);
437 		}
438 	}
439 
440 	/*
441 	 * Assume the page is cache inhibited and access is guarded unless
442 	 * it's in our available memory array.
443 	 */
444 	pte_lo = LPTE_I | LPTE_G;
445 	for (i = 0; i < pregions_sz; i++) {
446 		if ((pa >= pregions[i].mr_start) &&
447 		    (pa < (pregions[i].mr_start + pregions[i].mr_size))) {
448 			pte_lo &= ~(LPTE_I | LPTE_G);
449 			pte_lo |= LPTE_M;
450 			break;
451 		}
452 	}
453 
454 	return pte_lo;
455 }
456 
457 /*
458  * Quick sort callout for comparing memory regions.
459  */
460 static int	om_cmp(const void *a, const void *b);
461 
462 static int
463 om_cmp(const void *a, const void *b)
464 {
465 	const struct	ofw_map *mapa;
466 	const struct	ofw_map *mapb;
467 
468 	mapa = a;
469 	mapb = b;
470 	if (mapa->om_pa < mapb->om_pa)
471 		return (-1);
472 	else if (mapa->om_pa > mapb->om_pa)
473 		return (1);
474 	else
475 		return (0);
476 }
477 
478 static void
479 moea64_add_ofw_mappings(mmu_t mmup, phandle_t mmu, size_t sz)
480 {
481 	struct ofw_map	translations[sz/(4*sizeof(cell_t))]; /*>= 4 cells per */
482 	pcell_t		acells, trans_cells[sz/sizeof(cell_t)];
483 	struct pvo_entry *pvo;
484 	register_t	msr;
485 	vm_offset_t	off;
486 	vm_paddr_t	pa_base;
487 	int		i, j;
488 
489 	bzero(translations, sz);
490 	OF_getprop(OF_finddevice("/"), "#address-cells", &acells,
491 	    sizeof(acells));
492 	if (OF_getprop(mmu, "translations", trans_cells, sz) == -1)
493 		panic("moea64_bootstrap: can't get ofw translations");
494 
495 	CTR0(KTR_PMAP, "moea64_add_ofw_mappings: translations");
496 	sz /= sizeof(cell_t);
497 	for (i = 0, j = 0; i < sz; j++) {
498 		translations[j].om_va = trans_cells[i++];
499 		translations[j].om_len = trans_cells[i++];
500 		translations[j].om_pa = trans_cells[i++];
501 		if (acells == 2) {
502 			translations[j].om_pa <<= 32;
503 			translations[j].om_pa |= trans_cells[i++];
504 		}
505 		translations[j].om_mode = trans_cells[i++];
506 	}
507 	KASSERT(i == sz, ("Translations map has incorrect cell count (%d/%zd)",
508 	    i, sz));
509 
510 	sz = j;
511 	qsort(translations, sz, sizeof (*translations), om_cmp);
512 
513 	for (i = 0; i < sz; i++) {
514 		pa_base = translations[i].om_pa;
515 	      #ifndef __powerpc64__
516 		if ((translations[i].om_pa >> 32) != 0)
517 			panic("OFW translations above 32-bit boundary!");
518 	      #endif
519 
520 		if (pa_base % PAGE_SIZE)
521 			panic("OFW translation not page-aligned (phys)!");
522 		if (translations[i].om_va % PAGE_SIZE)
523 			panic("OFW translation not page-aligned (virt)!");
524 
525 		CTR3(KTR_PMAP, "translation: pa=%#zx va=%#x len=%#x",
526 		    pa_base, translations[i].om_va, translations[i].om_len);
527 
528 		/* Now enter the pages for this mapping */
529 
530 		DISABLE_TRANS(msr);
531 		for (off = 0; off < translations[i].om_len; off += PAGE_SIZE) {
532 			/* If this address is direct-mapped, skip remapping */
533 			if (hw_direct_map && translations[i].om_va == pa_base &&
534 			    moea64_calc_wimg(pa_base + off, VM_MEMATTR_DEFAULT) 			    == LPTE_M)
535 				continue;
536 
537 			PMAP_LOCK(kernel_pmap);
538 			pvo = moea64_pvo_find_va(kernel_pmap,
539 			    translations[i].om_va + off);
540 			PMAP_UNLOCK(kernel_pmap);
541 			if (pvo != NULL)
542 				continue;
543 
544 			moea64_kenter(mmup, translations[i].om_va + off,
545 			    pa_base + off);
546 		}
547 		ENABLE_TRANS(msr);
548 	}
549 }
550 
551 #ifdef __powerpc64__
552 static void
553 moea64_probe_large_page(void)
554 {
555 	uint16_t pvr = mfpvr() >> 16;
556 
557 	switch (pvr) {
558 	case IBM970:
559 	case IBM970FX:
560 	case IBM970MP:
561 		powerpc_sync(); isync();
562 		mtspr(SPR_HID4, mfspr(SPR_HID4) & ~HID4_970_DISABLE_LG_PG);
563 		powerpc_sync(); isync();
564 
565 		/* FALLTHROUGH */
566 	default:
567 		moea64_large_page_size = 0x1000000; /* 16 MB */
568 		moea64_large_page_shift = 24;
569 	}
570 
571 	moea64_large_page_mask = moea64_large_page_size - 1;
572 }
573 
574 static void
575 moea64_bootstrap_slb_prefault(vm_offset_t va, int large)
576 {
577 	struct slb *cache;
578 	struct slb entry;
579 	uint64_t esid, slbe;
580 	uint64_t i;
581 
582 	cache = PCPU_GET(slb);
583 	esid = va >> ADDR_SR_SHFT;
584 	slbe = (esid << SLBE_ESID_SHIFT) | SLBE_VALID;
585 
586 	for (i = 0; i < 64; i++) {
587 		if (cache[i].slbe == (slbe | i))
588 			return;
589 	}
590 
591 	entry.slbe = slbe;
592 	entry.slbv = KERNEL_VSID(esid) << SLBV_VSID_SHIFT;
593 	if (large)
594 		entry.slbv |= SLBV_L;
595 
596 	slb_insert_kernel(entry.slbe, entry.slbv);
597 }
598 #endif
599 
600 static void
601 moea64_setup_direct_map(mmu_t mmup, vm_offset_t kernelstart,
602     vm_offset_t kernelend)
603 {
604 	struct pvo_entry *pvo;
605 	register_t msr;
606 	vm_paddr_t pa;
607 	vm_offset_t size, off;
608 	uint64_t pte_lo;
609 	int i;
610 
611 	if (moea64_large_page_size == 0)
612 		hw_direct_map = 0;
613 
614 	DISABLE_TRANS(msr);
615 	if (hw_direct_map) {
616 		PMAP_LOCK(kernel_pmap);
617 		for (i = 0; i < pregions_sz; i++) {
618 		  for (pa = pregions[i].mr_start; pa < pregions[i].mr_start +
619 		     pregions[i].mr_size; pa += moea64_large_page_size) {
620 			pte_lo = LPTE_M;
621 
622 			pvo = alloc_pvo_entry(1 /* bootstrap */);
623 			pvo->pvo_vaddr |= PVO_WIRED | PVO_LARGE;
624 			init_pvo_entry(pvo, kernel_pmap, pa);
625 
626 			/*
627 			 * Set memory access as guarded if prefetch within
628 			 * the page could exit the available physmem area.
629 			 */
630 			if (pa & moea64_large_page_mask) {
631 				pa &= moea64_large_page_mask;
632 				pte_lo |= LPTE_G;
633 			}
634 			if (pa + moea64_large_page_size >
635 			    pregions[i].mr_start + pregions[i].mr_size)
636 				pte_lo |= LPTE_G;
637 
638 			pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE |
639 			    VM_PROT_EXECUTE;
640 			pvo->pvo_pte.pa = pa | pte_lo;
641 			moea64_pvo_enter(mmup, pvo, NULL);
642 		  }
643 		}
644 		PMAP_UNLOCK(kernel_pmap);
645 	} else {
646 		size = moea64_bpvo_pool_size*sizeof(struct pvo_entry);
647 		off = (vm_offset_t)(moea64_bpvo_pool);
648 		for (pa = off; pa < off + size; pa += PAGE_SIZE)
649 		moea64_kenter(mmup, pa, pa);
650 
651 		/*
652 		 * Map certain important things, like ourselves.
653 		 *
654 		 * NOTE: We do not map the exception vector space. That code is
655 		 * used only in real mode, and leaving it unmapped allows us to
656 		 * catch NULL pointer deferences, instead of making NULL a valid
657 		 * address.
658 		 */
659 
660 		for (pa = kernelstart & ~PAGE_MASK; pa < kernelend;
661 		    pa += PAGE_SIZE)
662 			moea64_kenter(mmup, pa, pa);
663 	}
664 	ENABLE_TRANS(msr);
665 
666 	/*
667 	 * Allow user to override unmapped_buf_allowed for testing.
668 	 * XXXKIB Only direct map implementation was tested.
669 	 */
670 	if (!TUNABLE_INT_FETCH("vfs.unmapped_buf_allowed",
671 	    &unmapped_buf_allowed))
672 		unmapped_buf_allowed = hw_direct_map;
673 }
674 
675 void
676 moea64_early_bootstrap(mmu_t mmup, vm_offset_t kernelstart, vm_offset_t kernelend)
677 {
678 	int		i, j;
679 	vm_size_t	physsz, hwphyssz;
680 
681 #ifndef __powerpc64__
682 	/* We don't have a direct map since there is no BAT */
683 	hw_direct_map = 0;
684 
685 	/* Make sure battable is zero, since we have no BAT */
686 	for (i = 0; i < 16; i++) {
687 		battable[i].batu = 0;
688 		battable[i].batl = 0;
689 	}
690 #else
691 	moea64_probe_large_page();
692 
693 	/* Use a direct map if we have large page support */
694 	if (moea64_large_page_size > 0)
695 		hw_direct_map = 1;
696 	else
697 		hw_direct_map = 0;
698 #endif
699 
700 	/* Get physical memory regions from firmware */
701 	mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
702 	CTR0(KTR_PMAP, "moea64_bootstrap: physical memory");
703 
704 	if (sizeof(phys_avail)/sizeof(phys_avail[0]) < regions_sz)
705 		panic("moea64_bootstrap: phys_avail too small");
706 
707 	phys_avail_count = 0;
708 	physsz = 0;
709 	hwphyssz = 0;
710 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
711 	for (i = 0, j = 0; i < regions_sz; i++, j += 2) {
712 		CTR3(KTR_PMAP, "region: %#zx - %#zx (%#zx)",
713 		    regions[i].mr_start, regions[i].mr_start +
714 		    regions[i].mr_size, regions[i].mr_size);
715 		if (hwphyssz != 0 &&
716 		    (physsz + regions[i].mr_size) >= hwphyssz) {
717 			if (physsz < hwphyssz) {
718 				phys_avail[j] = regions[i].mr_start;
719 				phys_avail[j + 1] = regions[i].mr_start +
720 				    hwphyssz - physsz;
721 				physsz = hwphyssz;
722 				phys_avail_count++;
723 			}
724 			break;
725 		}
726 		phys_avail[j] = regions[i].mr_start;
727 		phys_avail[j + 1] = regions[i].mr_start + regions[i].mr_size;
728 		phys_avail_count++;
729 		physsz += regions[i].mr_size;
730 	}
731 
732 	/* Check for overlap with the kernel and exception vectors */
733 	for (j = 0; j < 2*phys_avail_count; j+=2) {
734 		if (phys_avail[j] < EXC_LAST)
735 			phys_avail[j] += EXC_LAST;
736 
737 		if (kernelstart >= phys_avail[j] &&
738 		    kernelstart < phys_avail[j+1]) {
739 			if (kernelend < phys_avail[j+1]) {
740 				phys_avail[2*phys_avail_count] =
741 				    (kernelend & ~PAGE_MASK) + PAGE_SIZE;
742 				phys_avail[2*phys_avail_count + 1] =
743 				    phys_avail[j+1];
744 				phys_avail_count++;
745 			}
746 
747 			phys_avail[j+1] = kernelstart & ~PAGE_MASK;
748 		}
749 
750 		if (kernelend >= phys_avail[j] &&
751 		    kernelend < phys_avail[j+1]) {
752 			if (kernelstart > phys_avail[j]) {
753 				phys_avail[2*phys_avail_count] = phys_avail[j];
754 				phys_avail[2*phys_avail_count + 1] =
755 				    kernelstart & ~PAGE_MASK;
756 				phys_avail_count++;
757 			}
758 
759 			phys_avail[j] = (kernelend & ~PAGE_MASK) + PAGE_SIZE;
760 		}
761 	}
762 
763 	physmem = btoc(physsz);
764 
765 #ifdef PTEGCOUNT
766 	moea64_pteg_count = PTEGCOUNT;
767 #else
768 	moea64_pteg_count = 0x1000;
769 
770 	while (moea64_pteg_count < physmem)
771 		moea64_pteg_count <<= 1;
772 
773 	moea64_pteg_count >>= 1;
774 #endif /* PTEGCOUNT */
775 }
776 
777 void
778 moea64_mid_bootstrap(mmu_t mmup, vm_offset_t kernelstart, vm_offset_t kernelend)
779 {
780 	int		i;
781 
782 	/*
783 	 * Set PTEG mask
784 	 */
785 	moea64_pteg_mask = moea64_pteg_count - 1;
786 
787 	/*
788 	 * Initialize SLB table lock and page locks
789 	 */
790 	mtx_init(&moea64_slb_mutex, "SLB table", NULL, MTX_DEF);
791 	for (i = 0; i < PV_LOCK_COUNT; i++)
792 		mtx_init(&pv_lock[i], "page pv", NULL, MTX_DEF);
793 
794 	/*
795 	 * Initialise the bootstrap pvo pool.
796 	 */
797 	moea64_bpvo_pool = (struct pvo_entry *)moea64_bootstrap_alloc(
798 		moea64_bpvo_pool_size*sizeof(struct pvo_entry), 0);
799 	moea64_bpvo_pool_index = 0;
800 
801 	/*
802 	 * Make sure kernel vsid is allocated as well as VSID 0.
803 	 */
804 	#ifndef __powerpc64__
805 	moea64_vsid_bitmap[(KERNEL_VSIDBITS & (NVSIDS - 1)) / VSID_NBPW]
806 		|= 1 << (KERNEL_VSIDBITS % VSID_NBPW);
807 	moea64_vsid_bitmap[0] |= 1;
808 	#endif
809 
810 	/*
811 	 * Initialize the kernel pmap (which is statically allocated).
812 	 */
813 	#ifdef __powerpc64__
814 	for (i = 0; i < 64; i++) {
815 		pcpup->pc_slb[i].slbv = 0;
816 		pcpup->pc_slb[i].slbe = 0;
817 	}
818 	#else
819 	for (i = 0; i < 16; i++)
820 		kernel_pmap->pm_sr[i] = EMPTY_SEGMENT + i;
821 	#endif
822 
823 	kernel_pmap->pmap_phys = kernel_pmap;
824 	CPU_FILL(&kernel_pmap->pm_active);
825 	RB_INIT(&kernel_pmap->pmap_pvo);
826 
827 	PMAP_LOCK_INIT(kernel_pmap);
828 
829 	/*
830 	 * Now map in all the other buffers we allocated earlier
831 	 */
832 
833 	moea64_setup_direct_map(mmup, kernelstart, kernelend);
834 }
835 
836 void
837 moea64_late_bootstrap(mmu_t mmup, vm_offset_t kernelstart, vm_offset_t kernelend)
838 {
839 	ihandle_t	mmui;
840 	phandle_t	chosen;
841 	phandle_t	mmu;
842 	ssize_t		sz;
843 	int		i;
844 	vm_offset_t	pa, va;
845 	void		*dpcpu;
846 
847 	/*
848 	 * Set up the Open Firmware pmap and add its mappings if not in real
849 	 * mode.
850 	 */
851 
852 	chosen = OF_finddevice("/chosen");
853 	if (chosen != -1 && OF_getprop(chosen, "mmu", &mmui, 4) != -1) {
854 		mmu = OF_instance_to_package(mmui);
855 		if (mmu == -1 ||
856 		    (sz = OF_getproplen(mmu, "translations")) == -1)
857 			sz = 0;
858 		if (sz > 6144 /* tmpstksz - 2 KB headroom */)
859 			panic("moea64_bootstrap: too many ofw translations");
860 
861 		if (sz > 0)
862 			moea64_add_ofw_mappings(mmup, mmu, sz);
863 	}
864 
865 	/*
866 	 * Calculate the last available physical address.
867 	 */
868 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
869 		;
870 	Maxmem = powerpc_btop(phys_avail[i + 1]);
871 
872 	/*
873 	 * Initialize MMU and remap early physical mappings
874 	 */
875 	MMU_CPU_BOOTSTRAP(mmup,0);
876 	mtmsr(mfmsr() | PSL_DR | PSL_IR);
877 	pmap_bootstrapped++;
878 	bs_remap_earlyboot();
879 
880 	/*
881 	 * Set the start and end of kva.
882 	 */
883 	virtual_avail = VM_MIN_KERNEL_ADDRESS;
884 	virtual_end = VM_MAX_SAFE_KERNEL_ADDRESS;
885 
886 	/*
887 	 * Map the entire KVA range into the SLB. We must not fault there.
888 	 */
889 	#ifdef __powerpc64__
890 	for (va = virtual_avail; va < virtual_end; va += SEGMENT_LENGTH)
891 		moea64_bootstrap_slb_prefault(va, 0);
892 	#endif
893 
894 	/*
895 	 * Figure out how far we can extend virtual_end into segment 16
896 	 * without running into existing mappings. Segment 16 is guaranteed
897 	 * to contain neither RAM nor devices (at least on Apple hardware),
898 	 * but will generally contain some OFW mappings we should not
899 	 * step on.
900 	 */
901 
902 	#ifndef __powerpc64__	/* KVA is in high memory on PPC64 */
903 	PMAP_LOCK(kernel_pmap);
904 	while (virtual_end < VM_MAX_KERNEL_ADDRESS &&
905 	    moea64_pvo_find_va(kernel_pmap, virtual_end+1) == NULL)
906 		virtual_end += PAGE_SIZE;
907 	PMAP_UNLOCK(kernel_pmap);
908 	#endif
909 
910 	/*
911 	 * Allocate a kernel stack with a guard page for thread0 and map it
912 	 * into the kernel page map.
913 	 */
914 	pa = moea64_bootstrap_alloc(KSTACK_PAGES * PAGE_SIZE, PAGE_SIZE);
915 	va = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
916 	virtual_avail = va + KSTACK_PAGES * PAGE_SIZE;
917 	CTR2(KTR_PMAP, "moea64_bootstrap: kstack0 at %#x (%#x)", pa, va);
918 	thread0.td_kstack = va;
919 	thread0.td_kstack_pages = KSTACK_PAGES;
920 	for (i = 0; i < KSTACK_PAGES; i++) {
921 		moea64_kenter(mmup, va, pa);
922 		pa += PAGE_SIZE;
923 		va += PAGE_SIZE;
924 	}
925 
926 	/*
927 	 * Allocate virtual address space for the message buffer.
928 	 */
929 	pa = msgbuf_phys = moea64_bootstrap_alloc(msgbufsize, PAGE_SIZE);
930 	msgbufp = (struct msgbuf *)virtual_avail;
931 	va = virtual_avail;
932 	virtual_avail += round_page(msgbufsize);
933 	while (va < virtual_avail) {
934 		moea64_kenter(mmup, va, pa);
935 		pa += PAGE_SIZE;
936 		va += PAGE_SIZE;
937 	}
938 
939 	/*
940 	 * Allocate virtual address space for the dynamic percpu area.
941 	 */
942 	pa = moea64_bootstrap_alloc(DPCPU_SIZE, PAGE_SIZE);
943 	dpcpu = (void *)virtual_avail;
944 	va = virtual_avail;
945 	virtual_avail += DPCPU_SIZE;
946 	while (va < virtual_avail) {
947 		moea64_kenter(mmup, va, pa);
948 		pa += PAGE_SIZE;
949 		va += PAGE_SIZE;
950 	}
951 	dpcpu_init(dpcpu, 0);
952 
953 	/*
954 	 * Allocate some things for page zeroing. We put this directly
955 	 * in the page table and use MOEA64_PTE_REPLACE to avoid any
956 	 * of the PVO book-keeping or other parts of the VM system
957 	 * from even knowing that this hack exists.
958 	 */
959 
960 	if (!hw_direct_map) {
961 		mtx_init(&moea64_scratchpage_mtx, "pvo zero page", NULL,
962 		    MTX_DEF);
963 		for (i = 0; i < 2; i++) {
964 			moea64_scratchpage_va[i] = (virtual_end+1) - PAGE_SIZE;
965 			virtual_end -= PAGE_SIZE;
966 
967 			moea64_kenter(mmup, moea64_scratchpage_va[i], 0);
968 
969 			PMAP_LOCK(kernel_pmap);
970 			moea64_scratchpage_pvo[i] = moea64_pvo_find_va(
971 			    kernel_pmap, (vm_offset_t)moea64_scratchpage_va[i]);
972 			PMAP_UNLOCK(kernel_pmap);
973 		}
974 	}
975 }
976 
977 /*
978  * Activate a user pmap.  This mostly involves setting some non-CPU
979  * state.
980  */
981 void
982 moea64_activate(mmu_t mmu, struct thread *td)
983 {
984 	pmap_t	pm;
985 
986 	pm = &td->td_proc->p_vmspace->vm_pmap;
987 	CPU_SET(PCPU_GET(cpuid), &pm->pm_active);
988 
989 	#ifdef __powerpc64__
990 	PCPU_SET(userslb, pm->pm_slb);
991 	__asm __volatile("slbmte %0, %1; isync" ::
992 	    "r"(td->td_pcb->pcb_cpu.aim.usr_vsid), "r"(USER_SLB_SLBE));
993 	#else
994 	PCPU_SET(curpmap, pm->pmap_phys);
995 	mtsrin(USER_SR << ADDR_SR_SHFT, td->td_pcb->pcb_cpu.aim.usr_vsid);
996 	#endif
997 }
998 
999 void
1000 moea64_deactivate(mmu_t mmu, struct thread *td)
1001 {
1002 	pmap_t	pm;
1003 
1004 	__asm __volatile("isync; slbie %0" :: "r"(USER_ADDR));
1005 
1006 	pm = &td->td_proc->p_vmspace->vm_pmap;
1007 	CPU_CLR(PCPU_GET(cpuid), &pm->pm_active);
1008 	#ifdef __powerpc64__
1009 	PCPU_SET(userslb, NULL);
1010 	#else
1011 	PCPU_SET(curpmap, NULL);
1012 	#endif
1013 }
1014 
1015 void
1016 moea64_unwire(mmu_t mmu, pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1017 {
1018 	struct	pvo_entry key, *pvo;
1019 	vm_page_t m;
1020 	int64_t	refchg;
1021 
1022 	key.pvo_vaddr = sva;
1023 	PMAP_LOCK(pm);
1024 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1025 	    pvo != NULL && PVO_VADDR(pvo) < eva;
1026 	    pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
1027 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
1028 			panic("moea64_unwire: pvo %p is missing PVO_WIRED",
1029 			    pvo);
1030 		pvo->pvo_vaddr &= ~PVO_WIRED;
1031 		refchg = MOEA64_PTE_REPLACE(mmu, pvo, 0 /* No invalidation */);
1032 		if ((pvo->pvo_vaddr & PVO_MANAGED) &&
1033 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1034 			if (refchg < 0)
1035 				refchg = LPTE_CHG;
1036 			m = PHYS_TO_VM_PAGE(pvo->pvo_pte.pa & LPTE_RPGN);
1037 
1038 			refchg |= atomic_readandclear_32(&m->md.mdpg_attrs);
1039 			if (refchg & LPTE_CHG)
1040 				vm_page_dirty(m);
1041 			if (refchg & LPTE_REF)
1042 				vm_page_aflag_set(m, PGA_REFERENCED);
1043 		}
1044 		pm->pm_stats.wired_count--;
1045 	}
1046 	PMAP_UNLOCK(pm);
1047 }
1048 
1049 /*
1050  * This goes through and sets the physical address of our
1051  * special scratch PTE to the PA we want to zero or copy. Because
1052  * of locking issues (this can get called in pvo_enter() by
1053  * the UMA allocator), we can't use most other utility functions here
1054  */
1055 
1056 static __inline
1057 void moea64_set_scratchpage_pa(mmu_t mmup, int which, vm_paddr_t pa) {
1058 
1059 	KASSERT(!hw_direct_map, ("Using OEA64 scratchpage with a direct map!"));
1060 	mtx_assert(&moea64_scratchpage_mtx, MA_OWNED);
1061 
1062 	moea64_scratchpage_pvo[which]->pvo_pte.pa =
1063 	    moea64_calc_wimg(pa, VM_MEMATTR_DEFAULT) | (uint64_t)pa;
1064 	MOEA64_PTE_REPLACE(mmup, moea64_scratchpage_pvo[which],
1065 	    MOEA64_PTE_INVALIDATE);
1066 	isync();
1067 }
1068 
1069 void
1070 moea64_copy_page(mmu_t mmu, vm_page_t msrc, vm_page_t mdst)
1071 {
1072 	vm_offset_t	dst;
1073 	vm_offset_t	src;
1074 
1075 	dst = VM_PAGE_TO_PHYS(mdst);
1076 	src = VM_PAGE_TO_PHYS(msrc);
1077 
1078 	if (hw_direct_map) {
1079 		bcopy((void *)src, (void *)dst, PAGE_SIZE);
1080 	} else {
1081 		mtx_lock(&moea64_scratchpage_mtx);
1082 
1083 		moea64_set_scratchpage_pa(mmu, 0, src);
1084 		moea64_set_scratchpage_pa(mmu, 1, dst);
1085 
1086 		bcopy((void *)moea64_scratchpage_va[0],
1087 		    (void *)moea64_scratchpage_va[1], PAGE_SIZE);
1088 
1089 		mtx_unlock(&moea64_scratchpage_mtx);
1090 	}
1091 }
1092 
1093 static inline void
1094 moea64_copy_pages_dmap(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
1095     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1096 {
1097 	void *a_cp, *b_cp;
1098 	vm_offset_t a_pg_offset, b_pg_offset;
1099 	int cnt;
1100 
1101 	while (xfersize > 0) {
1102 		a_pg_offset = a_offset & PAGE_MASK;
1103 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1104 		a_cp = (char *)VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]) +
1105 		    a_pg_offset;
1106 		b_pg_offset = b_offset & PAGE_MASK;
1107 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1108 		b_cp = (char *)VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]) +
1109 		    b_pg_offset;
1110 		bcopy(a_cp, b_cp, cnt);
1111 		a_offset += cnt;
1112 		b_offset += cnt;
1113 		xfersize -= cnt;
1114 	}
1115 }
1116 
1117 static inline void
1118 moea64_copy_pages_nodmap(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
1119     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1120 {
1121 	void *a_cp, *b_cp;
1122 	vm_offset_t a_pg_offset, b_pg_offset;
1123 	int cnt;
1124 
1125 	mtx_lock(&moea64_scratchpage_mtx);
1126 	while (xfersize > 0) {
1127 		a_pg_offset = a_offset & PAGE_MASK;
1128 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1129 		moea64_set_scratchpage_pa(mmu, 0,
1130 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]));
1131 		a_cp = (char *)moea64_scratchpage_va[0] + a_pg_offset;
1132 		b_pg_offset = b_offset & PAGE_MASK;
1133 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1134 		moea64_set_scratchpage_pa(mmu, 1,
1135 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]));
1136 		b_cp = (char *)moea64_scratchpage_va[1] + b_pg_offset;
1137 		bcopy(a_cp, b_cp, cnt);
1138 		a_offset += cnt;
1139 		b_offset += cnt;
1140 		xfersize -= cnt;
1141 	}
1142 	mtx_unlock(&moea64_scratchpage_mtx);
1143 }
1144 
1145 void
1146 moea64_copy_pages(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
1147     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1148 {
1149 
1150 	if (hw_direct_map) {
1151 		moea64_copy_pages_dmap(mmu, ma, a_offset, mb, b_offset,
1152 		    xfersize);
1153 	} else {
1154 		moea64_copy_pages_nodmap(mmu, ma, a_offset, mb, b_offset,
1155 		    xfersize);
1156 	}
1157 }
1158 
1159 void
1160 moea64_zero_page_area(mmu_t mmu, vm_page_t m, int off, int size)
1161 {
1162 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1163 
1164 	if (size + off > PAGE_SIZE)
1165 		panic("moea64_zero_page: size + off > PAGE_SIZE");
1166 
1167 	if (hw_direct_map) {
1168 		bzero((caddr_t)pa + off, size);
1169 	} else {
1170 		mtx_lock(&moea64_scratchpage_mtx);
1171 		moea64_set_scratchpage_pa(mmu, 0, pa);
1172 		bzero((caddr_t)moea64_scratchpage_va[0] + off, size);
1173 		mtx_unlock(&moea64_scratchpage_mtx);
1174 	}
1175 }
1176 
1177 /*
1178  * Zero a page of physical memory by temporarily mapping it
1179  */
1180 void
1181 moea64_zero_page(mmu_t mmu, vm_page_t m)
1182 {
1183 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
1184 	vm_offset_t va, off;
1185 
1186 	if (!hw_direct_map) {
1187 		mtx_lock(&moea64_scratchpage_mtx);
1188 
1189 		moea64_set_scratchpage_pa(mmu, 0, pa);
1190 		va = moea64_scratchpage_va[0];
1191 	} else {
1192 		va = pa;
1193 	}
1194 
1195 	for (off = 0; off < PAGE_SIZE; off += cacheline_size)
1196 		__asm __volatile("dcbz 0,%0" :: "r"(va + off));
1197 
1198 	if (!hw_direct_map)
1199 		mtx_unlock(&moea64_scratchpage_mtx);
1200 }
1201 
1202 void
1203 moea64_zero_page_idle(mmu_t mmu, vm_page_t m)
1204 {
1205 
1206 	moea64_zero_page(mmu, m);
1207 }
1208 
1209 /*
1210  * Map the given physical page at the specified virtual address in the
1211  * target pmap with the protection requested.  If specified the page
1212  * will be wired down.
1213  */
1214 
1215 int
1216 moea64_enter(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
1217     vm_prot_t prot, u_int flags, int8_t psind)
1218 {
1219 	struct		pvo_entry *pvo, *oldpvo;
1220 	struct		pvo_head *pvo_head;
1221 	uint64_t	pte_lo;
1222 	int		error;
1223 
1224 	if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
1225 		VM_OBJECT_ASSERT_LOCKED(m->object);
1226 
1227 	pvo = alloc_pvo_entry(0);
1228 	pvo->pvo_pmap = NULL; /* to be filled in later */
1229 	pvo->pvo_pte.prot = prot;
1230 
1231 	pte_lo = moea64_calc_wimg(VM_PAGE_TO_PHYS(m), pmap_page_get_memattr(m));
1232 	pvo->pvo_pte.pa = VM_PAGE_TO_PHYS(m) | pte_lo;
1233 
1234 	if ((flags & PMAP_ENTER_WIRED) != 0)
1235 		pvo->pvo_vaddr |= PVO_WIRED;
1236 
1237 	if ((m->oflags & VPO_UNMANAGED) != 0 || !moea64_initialized) {
1238 		pvo_head = NULL;
1239 	} else {
1240 		pvo_head = &m->md.mdpg_pvoh;
1241 		pvo->pvo_vaddr |= PVO_MANAGED;
1242 	}
1243 
1244 	for (;;) {
1245 		PV_PAGE_LOCK(m);
1246 		PMAP_LOCK(pmap);
1247 		if (pvo->pvo_pmap == NULL)
1248 			init_pvo_entry(pvo, pmap, va);
1249 		if (prot & VM_PROT_WRITE)
1250 			if (pmap_bootstrapped &&
1251 			    (m->oflags & VPO_UNMANAGED) == 0)
1252 				vm_page_aflag_set(m, PGA_WRITEABLE);
1253 
1254 		oldpvo = moea64_pvo_find_va(pmap, va);
1255 		if (oldpvo != NULL) {
1256 			if (oldpvo->pvo_vaddr == pvo->pvo_vaddr &&
1257 			    oldpvo->pvo_pte.pa == pvo->pvo_pte.pa &&
1258 			    oldpvo->pvo_pte.prot == prot) {
1259 				/* Identical mapping already exists */
1260 				error = 0;
1261 
1262 				/* If not in page table, reinsert it */
1263 				if (MOEA64_PTE_SYNCH(mmu, oldpvo) < 0) {
1264 					moea64_pte_overflow--;
1265 					MOEA64_PTE_INSERT(mmu, oldpvo);
1266 				}
1267 
1268 				/* Then just clean up and go home */
1269 				PV_PAGE_UNLOCK(m);
1270 				PMAP_UNLOCK(pmap);
1271 				free_pvo_entry(pvo);
1272 				break;
1273 			}
1274 
1275 			/* Otherwise, need to kill it first */
1276 			KASSERT(oldpvo->pvo_pmap == pmap, ("pmap of old "
1277 			    "mapping does not match new mapping"));
1278 			moea64_pvo_remove_from_pmap(mmu, oldpvo);
1279 		}
1280 		error = moea64_pvo_enter(mmu, pvo, pvo_head);
1281 		PV_PAGE_UNLOCK(m);
1282 		PMAP_UNLOCK(pmap);
1283 
1284 		/* Free any dead pages */
1285 		if (oldpvo != NULL) {
1286 			PV_LOCK(oldpvo->pvo_pte.pa & LPTE_RPGN);
1287 			moea64_pvo_remove_from_page(mmu, oldpvo);
1288 			PV_UNLOCK(oldpvo->pvo_pte.pa & LPTE_RPGN);
1289 			free_pvo_entry(oldpvo);
1290 		}
1291 
1292 		if (error != ENOMEM)
1293 			break;
1294 		if ((flags & PMAP_ENTER_NOSLEEP) != 0)
1295 			return (KERN_RESOURCE_SHORTAGE);
1296 		VM_OBJECT_ASSERT_UNLOCKED(m->object);
1297 		VM_WAIT;
1298 	}
1299 
1300 	/*
1301 	 * Flush the page from the instruction cache if this page is
1302 	 * mapped executable and cacheable.
1303 	 */
1304 	if (pmap != kernel_pmap && !(m->aflags & PGA_EXECUTABLE) &&
1305 	    (pte_lo & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
1306 		vm_page_aflag_set(m, PGA_EXECUTABLE);
1307 		moea64_syncicache(mmu, pmap, va, VM_PAGE_TO_PHYS(m), PAGE_SIZE);
1308 	}
1309 	return (KERN_SUCCESS);
1310 }
1311 
1312 static void
1313 moea64_syncicache(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1314     vm_size_t sz)
1315 {
1316 
1317 	/*
1318 	 * This is much trickier than on older systems because
1319 	 * we can't sync the icache on physical addresses directly
1320 	 * without a direct map. Instead we check a couple of cases
1321 	 * where the memory is already mapped in and, failing that,
1322 	 * use the same trick we use for page zeroing to create
1323 	 * a temporary mapping for this physical address.
1324 	 */
1325 
1326 	if (!pmap_bootstrapped) {
1327 		/*
1328 		 * If PMAP is not bootstrapped, we are likely to be
1329 		 * in real mode.
1330 		 */
1331 		__syncicache((void *)pa, sz);
1332 	} else if (pmap == kernel_pmap) {
1333 		__syncicache((void *)va, sz);
1334 	} else if (hw_direct_map) {
1335 		__syncicache((void *)pa, sz);
1336 	} else {
1337 		/* Use the scratch page to set up a temp mapping */
1338 
1339 		mtx_lock(&moea64_scratchpage_mtx);
1340 
1341 		moea64_set_scratchpage_pa(mmu, 1, pa & ~ADDR_POFF);
1342 		__syncicache((void *)(moea64_scratchpage_va[1] +
1343 		    (va & ADDR_POFF)), sz);
1344 
1345 		mtx_unlock(&moea64_scratchpage_mtx);
1346 	}
1347 }
1348 
1349 /*
1350  * Maps a sequence of resident pages belonging to the same object.
1351  * The sequence begins with the given page m_start.  This page is
1352  * mapped at the given virtual address start.  Each subsequent page is
1353  * mapped at a virtual address that is offset from start by the same
1354  * amount as the page is offset from m_start within the object.  The
1355  * last page in the sequence is the page with the largest offset from
1356  * m_start that can be mapped at a virtual address less than the given
1357  * virtual address end.  Not every virtual page between start and end
1358  * is mapped; only those for which a resident page exists with the
1359  * corresponding offset from m_start are mapped.
1360  */
1361 void
1362 moea64_enter_object(mmu_t mmu, pmap_t pm, vm_offset_t start, vm_offset_t end,
1363     vm_page_t m_start, vm_prot_t prot)
1364 {
1365 	vm_page_t m;
1366 	vm_pindex_t diff, psize;
1367 
1368 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1369 
1370 	psize = atop(end - start);
1371 	m = m_start;
1372 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1373 		moea64_enter(mmu, pm, start + ptoa(diff), m, prot &
1374 		    (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_NOSLEEP, 0);
1375 		m = TAILQ_NEXT(m, listq);
1376 	}
1377 }
1378 
1379 void
1380 moea64_enter_quick(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_page_t m,
1381     vm_prot_t prot)
1382 {
1383 
1384 	moea64_enter(mmu, pm, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1385 	    PMAP_ENTER_NOSLEEP, 0);
1386 }
1387 
1388 vm_paddr_t
1389 moea64_extract(mmu_t mmu, pmap_t pm, vm_offset_t va)
1390 {
1391 	struct	pvo_entry *pvo;
1392 	vm_paddr_t pa;
1393 
1394 	PMAP_LOCK(pm);
1395 	pvo = moea64_pvo_find_va(pm, va);
1396 	if (pvo == NULL)
1397 		pa = 0;
1398 	else
1399 		pa = (pvo->pvo_pte.pa & LPTE_RPGN) | (va - PVO_VADDR(pvo));
1400 	PMAP_UNLOCK(pm);
1401 
1402 	return (pa);
1403 }
1404 
1405 /*
1406  * Atomically extract and hold the physical page with the given
1407  * pmap and virtual address pair if that mapping permits the given
1408  * protection.
1409  */
1410 vm_page_t
1411 moea64_extract_and_hold(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1412 {
1413 	struct	pvo_entry *pvo;
1414 	vm_page_t m;
1415         vm_paddr_t pa;
1416 
1417 	m = NULL;
1418 	pa = 0;
1419 	PMAP_LOCK(pmap);
1420 retry:
1421 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
1422 	if (pvo != NULL && (pvo->pvo_pte.prot & prot) == prot) {
1423 		if (vm_page_pa_tryrelock(pmap,
1424 		    pvo->pvo_pte.pa & LPTE_RPGN, &pa))
1425 			goto retry;
1426 		m = PHYS_TO_VM_PAGE(pvo->pvo_pte.pa & LPTE_RPGN);
1427 		vm_page_hold(m);
1428 	}
1429 	PA_UNLOCK_COND(pa);
1430 	PMAP_UNLOCK(pmap);
1431 	return (m);
1432 }
1433 
1434 static mmu_t installed_mmu;
1435 
1436 static void *
1437 moea64_uma_page_alloc(uma_zone_t zone, vm_size_t bytes, uint8_t *flags,
1438     int wait)
1439 {
1440 	struct pvo_entry *pvo;
1441         vm_offset_t va;
1442         vm_page_t m;
1443         int pflags, needed_lock;
1444 
1445 	/*
1446 	 * This entire routine is a horrible hack to avoid bothering kmem
1447 	 * for new KVA addresses. Because this can get called from inside
1448 	 * kmem allocation routines, calling kmem for a new address here
1449 	 * can lead to multiply locking non-recursive mutexes.
1450 	 */
1451 
1452 	*flags = UMA_SLAB_PRIV;
1453 	needed_lock = !PMAP_LOCKED(kernel_pmap);
1454 	pflags = malloc2vm_flags(wait) | VM_ALLOC_WIRED;
1455 
1456         for (;;) {
1457                 m = vm_page_alloc(NULL, 0, pflags | VM_ALLOC_NOOBJ);
1458                 if (m == NULL) {
1459                         if (wait & M_NOWAIT)
1460                                 return (NULL);
1461                         VM_WAIT;
1462                 } else
1463                         break;
1464         }
1465 
1466 	va = VM_PAGE_TO_PHYS(m);
1467 
1468 	pvo = alloc_pvo_entry(1 /* bootstrap */);
1469 
1470 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE;
1471 	pvo->pvo_pte.pa = VM_PAGE_TO_PHYS(m) | LPTE_M;
1472 
1473 	if (needed_lock)
1474 		PMAP_LOCK(kernel_pmap);
1475 
1476 	init_pvo_entry(pvo, kernel_pmap, va);
1477 	pvo->pvo_vaddr |= PVO_WIRED;
1478 
1479 	moea64_pvo_enter(installed_mmu, pvo, NULL);
1480 
1481 	if (needed_lock)
1482 		PMAP_UNLOCK(kernel_pmap);
1483 
1484 	if ((wait & M_ZERO) && (m->flags & PG_ZERO) == 0)
1485                 bzero((void *)va, PAGE_SIZE);
1486 
1487 	return (void *)va;
1488 }
1489 
1490 extern int elf32_nxstack;
1491 
1492 void
1493 moea64_init(mmu_t mmu)
1494 {
1495 
1496 	CTR0(KTR_PMAP, "moea64_init");
1497 
1498 	moea64_pvo_zone = uma_zcreate("UPVO entry", sizeof (struct pvo_entry),
1499 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1500 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1501 
1502 	if (!hw_direct_map) {
1503 		installed_mmu = mmu;
1504 		uma_zone_set_allocf(moea64_pvo_zone,moea64_uma_page_alloc);
1505 	}
1506 
1507 #ifdef COMPAT_FREEBSD32
1508 	elf32_nxstack = 1;
1509 #endif
1510 
1511 	moea64_initialized = TRUE;
1512 }
1513 
1514 boolean_t
1515 moea64_is_referenced(mmu_t mmu, vm_page_t m)
1516 {
1517 
1518 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1519 	    ("moea64_is_referenced: page %p is not managed", m));
1520 
1521 	return (moea64_query_bit(mmu, m, LPTE_REF));
1522 }
1523 
1524 boolean_t
1525 moea64_is_modified(mmu_t mmu, vm_page_t m)
1526 {
1527 
1528 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1529 	    ("moea64_is_modified: page %p is not managed", m));
1530 
1531 	/*
1532 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
1533 	 * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
1534 	 * is clear, no PTEs can have LPTE_CHG set.
1535 	 */
1536 	VM_OBJECT_ASSERT_LOCKED(m->object);
1537 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
1538 		return (FALSE);
1539 	return (moea64_query_bit(mmu, m, LPTE_CHG));
1540 }
1541 
1542 boolean_t
1543 moea64_is_prefaultable(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1544 {
1545 	struct pvo_entry *pvo;
1546 	boolean_t rv = TRUE;
1547 
1548 	PMAP_LOCK(pmap);
1549 	pvo = moea64_pvo_find_va(pmap, va & ~ADDR_POFF);
1550 	if (pvo != NULL)
1551 		rv = FALSE;
1552 	PMAP_UNLOCK(pmap);
1553 	return (rv);
1554 }
1555 
1556 void
1557 moea64_clear_modify(mmu_t mmu, vm_page_t m)
1558 {
1559 
1560 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1561 	    ("moea64_clear_modify: page %p is not managed", m));
1562 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1563 	KASSERT(!vm_page_xbusied(m),
1564 	    ("moea64_clear_modify: page %p is exclusive busied", m));
1565 
1566 	/*
1567 	 * If the page is not PGA_WRITEABLE, then no PTEs can have LPTE_CHG
1568 	 * set.  If the object containing the page is locked and the page is
1569 	 * not exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
1570 	 */
1571 	if ((m->aflags & PGA_WRITEABLE) == 0)
1572 		return;
1573 	moea64_clear_bit(mmu, m, LPTE_CHG);
1574 }
1575 
1576 /*
1577  * Clear the write and modified bits in each of the given page's mappings.
1578  */
1579 void
1580 moea64_remove_write(mmu_t mmu, vm_page_t m)
1581 {
1582 	struct	pvo_entry *pvo;
1583 	int64_t	refchg, ret;
1584 	pmap_t	pmap;
1585 
1586 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1587 	    ("moea64_remove_write: page %p is not managed", m));
1588 
1589 	/*
1590 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
1591 	 * set by another thread while the object is locked.  Thus,
1592 	 * if PGA_WRITEABLE is clear, no page table entries need updating.
1593 	 */
1594 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1595 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
1596 		return;
1597 	powerpc_sync();
1598 	PV_PAGE_LOCK(m);
1599 	refchg = 0;
1600 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1601 		pmap = pvo->pvo_pmap;
1602 		PMAP_LOCK(pmap);
1603 		if (!(pvo->pvo_vaddr & PVO_DEAD) &&
1604 		    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1605 			pvo->pvo_pte.prot &= ~VM_PROT_WRITE;
1606 			ret = MOEA64_PTE_REPLACE(mmu, pvo,
1607 			    MOEA64_PTE_PROT_UPDATE);
1608 			if (ret < 0)
1609 				ret = LPTE_CHG;
1610 			refchg |= ret;
1611 			if (pvo->pvo_pmap == kernel_pmap)
1612 				isync();
1613 		}
1614 		PMAP_UNLOCK(pmap);
1615 	}
1616 	if ((refchg | atomic_readandclear_32(&m->md.mdpg_attrs)) & LPTE_CHG)
1617 		vm_page_dirty(m);
1618 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1619 	PV_PAGE_UNLOCK(m);
1620 }
1621 
1622 /*
1623  *	moea64_ts_referenced:
1624  *
1625  *	Return a count of reference bits for a page, clearing those bits.
1626  *	It is not necessary for every reference bit to be cleared, but it
1627  *	is necessary that 0 only be returned when there are truly no
1628  *	reference bits set.
1629  *
1630  *	XXX: The exact number of bits to check and clear is a matter that
1631  *	should be tested and standardized at some point in the future for
1632  *	optimal aging of shared pages.
1633  */
1634 int
1635 moea64_ts_referenced(mmu_t mmu, vm_page_t m)
1636 {
1637 
1638 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1639 	    ("moea64_ts_referenced: page %p is not managed", m));
1640 	return (moea64_clear_bit(mmu, m, LPTE_REF));
1641 }
1642 
1643 /*
1644  * Modify the WIMG settings of all mappings for a page.
1645  */
1646 void
1647 moea64_page_set_memattr(mmu_t mmu, vm_page_t m, vm_memattr_t ma)
1648 {
1649 	struct	pvo_entry *pvo;
1650 	int64_t	refchg;
1651 	pmap_t	pmap;
1652 	uint64_t lo;
1653 
1654 	if ((m->oflags & VPO_UNMANAGED) != 0) {
1655 		m->md.mdpg_cache_attrs = ma;
1656 		return;
1657 	}
1658 
1659 	lo = moea64_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
1660 
1661 	PV_PAGE_LOCK(m);
1662 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1663 		pmap = pvo->pvo_pmap;
1664 		PMAP_LOCK(pmap);
1665 		if (!(pvo->pvo_vaddr & PVO_DEAD)) {
1666 			pvo->pvo_pte.pa &= ~LPTE_WIMG;
1667 			pvo->pvo_pte.pa |= lo;
1668 			refchg = MOEA64_PTE_REPLACE(mmu, pvo,
1669 			    MOEA64_PTE_INVALIDATE);
1670 			if (refchg < 0)
1671 				refchg = (pvo->pvo_pte.prot & VM_PROT_WRITE) ?
1672 				    LPTE_CHG : 0;
1673 			if ((pvo->pvo_vaddr & PVO_MANAGED) &&
1674 			    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
1675 				refchg |=
1676 				    atomic_readandclear_32(&m->md.mdpg_attrs);
1677 				if (refchg & LPTE_CHG)
1678 					vm_page_dirty(m);
1679 				if (refchg & LPTE_REF)
1680 					vm_page_aflag_set(m, PGA_REFERENCED);
1681 			}
1682 			if (pvo->pvo_pmap == kernel_pmap)
1683 				isync();
1684 		}
1685 		PMAP_UNLOCK(pmap);
1686 	}
1687 	m->md.mdpg_cache_attrs = ma;
1688 	PV_PAGE_UNLOCK(m);
1689 }
1690 
1691 /*
1692  * Map a wired page into kernel virtual address space.
1693  */
1694 void
1695 moea64_kenter_attr(mmu_t mmu, vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1696 {
1697 	int		error;
1698 	struct pvo_entry *pvo, *oldpvo;
1699 
1700 	pvo = alloc_pvo_entry(0);
1701 	pvo->pvo_pte.prot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
1702 	pvo->pvo_pte.pa = (pa & ~ADDR_POFF) | moea64_calc_wimg(pa, ma);
1703 	pvo->pvo_vaddr |= PVO_WIRED;
1704 
1705 	PMAP_LOCK(kernel_pmap);
1706 	oldpvo = moea64_pvo_find_va(kernel_pmap, va);
1707 	if (oldpvo != NULL)
1708 		moea64_pvo_remove_from_pmap(mmu, oldpvo);
1709 	init_pvo_entry(pvo, kernel_pmap, va);
1710 	error = moea64_pvo_enter(mmu, pvo, NULL);
1711 	PMAP_UNLOCK(kernel_pmap);
1712 
1713 	/* Free any dead pages */
1714 	if (oldpvo != NULL) {
1715 		PV_LOCK(oldpvo->pvo_pte.pa & LPTE_RPGN);
1716 		moea64_pvo_remove_from_page(mmu, oldpvo);
1717 		PV_UNLOCK(oldpvo->pvo_pte.pa & LPTE_RPGN);
1718 		free_pvo_entry(oldpvo);
1719 	}
1720 
1721 	if (error != 0 && error != ENOENT)
1722 		panic("moea64_kenter: failed to enter va %#zx pa %#zx: %d", va,
1723 		    pa, error);
1724 }
1725 
1726 void
1727 moea64_kenter(mmu_t mmu, vm_offset_t va, vm_paddr_t pa)
1728 {
1729 
1730 	moea64_kenter_attr(mmu, va, pa, VM_MEMATTR_DEFAULT);
1731 }
1732 
1733 /*
1734  * Extract the physical page address associated with the given kernel virtual
1735  * address.
1736  */
1737 vm_paddr_t
1738 moea64_kextract(mmu_t mmu, vm_offset_t va)
1739 {
1740 	struct		pvo_entry *pvo;
1741 	vm_paddr_t pa;
1742 
1743 	/*
1744 	 * Shortcut the direct-mapped case when applicable.  We never put
1745 	 * anything but 1:1 mappings below VM_MIN_KERNEL_ADDRESS.
1746 	 */
1747 	if (va < VM_MIN_KERNEL_ADDRESS)
1748 		return (va);
1749 
1750 	PMAP_LOCK(kernel_pmap);
1751 	pvo = moea64_pvo_find_va(kernel_pmap, va);
1752 	KASSERT(pvo != NULL, ("moea64_kextract: no addr found for %#" PRIxPTR,
1753 	    va));
1754 	pa = (pvo->pvo_pte.pa & LPTE_RPGN) | (va - PVO_VADDR(pvo));
1755 	PMAP_UNLOCK(kernel_pmap);
1756 	return (pa);
1757 }
1758 
1759 /*
1760  * Remove a wired page from kernel virtual address space.
1761  */
1762 void
1763 moea64_kremove(mmu_t mmu, vm_offset_t va)
1764 {
1765 	moea64_remove(mmu, kernel_pmap, va, va + PAGE_SIZE);
1766 }
1767 
1768 /*
1769  * Map a range of physical addresses into kernel virtual address space.
1770  *
1771  * The value passed in *virt is a suggested virtual address for the mapping.
1772  * Architectures which can support a direct-mapped physical to virtual region
1773  * can return the appropriate address within that region, leaving '*virt'
1774  * unchanged.  Other architectures should map the pages starting at '*virt' and
1775  * update '*virt' with the first usable address after the mapped region.
1776  */
1777 vm_offset_t
1778 moea64_map(mmu_t mmu, vm_offset_t *virt, vm_paddr_t pa_start,
1779     vm_paddr_t pa_end, int prot)
1780 {
1781 	vm_offset_t	sva, va;
1782 
1783 	if (hw_direct_map) {
1784 		/*
1785 		 * Check if every page in the region is covered by the direct
1786 		 * map. The direct map covers all of physical memory. Use
1787 		 * moea64_calc_wimg() as a shortcut to see if the page is in
1788 		 * physical memory as a way to see if the direct map covers it.
1789 		 */
1790 		for (va = pa_start; va < pa_end; va += PAGE_SIZE)
1791 			if (moea64_calc_wimg(va, VM_MEMATTR_DEFAULT) != LPTE_M)
1792 				break;
1793 		if (va == pa_end)
1794 			return (pa_start);
1795 	}
1796 	sva = *virt;
1797 	va = sva;
1798 	/* XXX respect prot argument */
1799 	for (; pa_start < pa_end; pa_start += PAGE_SIZE, va += PAGE_SIZE)
1800 		moea64_kenter(mmu, va, pa_start);
1801 	*virt = va;
1802 
1803 	return (sva);
1804 }
1805 
1806 /*
1807  * Returns true if the pmap's pv is one of the first
1808  * 16 pvs linked to from this page.  This count may
1809  * be changed upwards or downwards in the future; it
1810  * is only necessary that true be returned for a small
1811  * subset of pmaps for proper page aging.
1812  */
1813 boolean_t
1814 moea64_page_exists_quick(mmu_t mmu, pmap_t pmap, vm_page_t m)
1815 {
1816         int loops;
1817 	struct pvo_entry *pvo;
1818 	boolean_t rv;
1819 
1820 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1821 	    ("moea64_page_exists_quick: page %p is not managed", m));
1822 	loops = 0;
1823 	rv = FALSE;
1824 	PV_PAGE_LOCK(m);
1825 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1826 		if (!(pvo->pvo_vaddr & PVO_DEAD) && pvo->pvo_pmap == pmap) {
1827 			rv = TRUE;
1828 			break;
1829 		}
1830 		if (++loops >= 16)
1831 			break;
1832 	}
1833 	PV_PAGE_UNLOCK(m);
1834 	return (rv);
1835 }
1836 
1837 /*
1838  * Return the number of managed mappings to the given physical page
1839  * that are wired.
1840  */
1841 int
1842 moea64_page_wired_mappings(mmu_t mmu, vm_page_t m)
1843 {
1844 	struct pvo_entry *pvo;
1845 	int count;
1846 
1847 	count = 0;
1848 	if ((m->oflags & VPO_UNMANAGED) != 0)
1849 		return (count);
1850 	PV_PAGE_LOCK(m);
1851 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
1852 		if ((pvo->pvo_vaddr & (PVO_DEAD | PVO_WIRED)) == PVO_WIRED)
1853 			count++;
1854 	PV_PAGE_UNLOCK(m);
1855 	return (count);
1856 }
1857 
1858 static uintptr_t	moea64_vsidcontext;
1859 
1860 uintptr_t
1861 moea64_get_unique_vsid(void) {
1862 	u_int entropy;
1863 	register_t hash;
1864 	uint32_t mask;
1865 	int i;
1866 
1867 	entropy = 0;
1868 	__asm __volatile("mftb %0" : "=r"(entropy));
1869 
1870 	mtx_lock(&moea64_slb_mutex);
1871 	for (i = 0; i < NVSIDS; i += VSID_NBPW) {
1872 		u_int	n;
1873 
1874 		/*
1875 		 * Create a new value by mutiplying by a prime and adding in
1876 		 * entropy from the timebase register.  This is to make the
1877 		 * VSID more random so that the PT hash function collides
1878 		 * less often.  (Note that the prime casues gcc to do shifts
1879 		 * instead of a multiply.)
1880 		 */
1881 		moea64_vsidcontext = (moea64_vsidcontext * 0x1105) + entropy;
1882 		hash = moea64_vsidcontext & (NVSIDS - 1);
1883 		if (hash == 0)		/* 0 is special, avoid it */
1884 			continue;
1885 		n = hash >> 5;
1886 		mask = 1 << (hash & (VSID_NBPW - 1));
1887 		hash = (moea64_vsidcontext & VSID_HASHMASK);
1888 		if (moea64_vsid_bitmap[n] & mask) {	/* collision? */
1889 			/* anything free in this bucket? */
1890 			if (moea64_vsid_bitmap[n] == 0xffffffff) {
1891 				entropy = (moea64_vsidcontext >> 20);
1892 				continue;
1893 			}
1894 			i = ffs(~moea64_vsid_bitmap[n]) - 1;
1895 			mask = 1 << i;
1896 			hash &= VSID_HASHMASK & ~(VSID_NBPW - 1);
1897 			hash |= i;
1898 		}
1899 		if (hash == VSID_VRMA)	/* also special, avoid this too */
1900 			continue;
1901 		KASSERT(!(moea64_vsid_bitmap[n] & mask),
1902 		    ("Allocating in-use VSID %#zx\n", hash));
1903 		moea64_vsid_bitmap[n] |= mask;
1904 		mtx_unlock(&moea64_slb_mutex);
1905 		return (hash);
1906 	}
1907 
1908 	mtx_unlock(&moea64_slb_mutex);
1909 	panic("%s: out of segments",__func__);
1910 }
1911 
1912 #ifdef __powerpc64__
1913 void
1914 moea64_pinit(mmu_t mmu, pmap_t pmap)
1915 {
1916 
1917 	RB_INIT(&pmap->pmap_pvo);
1918 
1919 	pmap->pm_slb_tree_root = slb_alloc_tree();
1920 	pmap->pm_slb = slb_alloc_user_cache();
1921 	pmap->pm_slb_len = 0;
1922 }
1923 #else
1924 void
1925 moea64_pinit(mmu_t mmu, pmap_t pmap)
1926 {
1927 	int	i;
1928 	uint32_t hash;
1929 
1930 	RB_INIT(&pmap->pmap_pvo);
1931 
1932 	if (pmap_bootstrapped)
1933 		pmap->pmap_phys = (pmap_t)moea64_kextract(mmu,
1934 		    (vm_offset_t)pmap);
1935 	else
1936 		pmap->pmap_phys = pmap;
1937 
1938 	/*
1939 	 * Allocate some segment registers for this pmap.
1940 	 */
1941 	hash = moea64_get_unique_vsid();
1942 
1943 	for (i = 0; i < 16; i++)
1944 		pmap->pm_sr[i] = VSID_MAKE(i, hash);
1945 
1946 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_pinit: pm_sr[0] = 0"));
1947 }
1948 #endif
1949 
1950 /*
1951  * Initialize the pmap associated with process 0.
1952  */
1953 void
1954 moea64_pinit0(mmu_t mmu, pmap_t pm)
1955 {
1956 
1957 	PMAP_LOCK_INIT(pm);
1958 	moea64_pinit(mmu, pm);
1959 	bzero(&pm->pm_stats, sizeof(pm->pm_stats));
1960 }
1961 
1962 /*
1963  * Set the physical protection on the specified range of this map as requested.
1964  */
1965 static void
1966 moea64_pvo_protect(mmu_t mmu,  pmap_t pm, struct pvo_entry *pvo, vm_prot_t prot)
1967 {
1968 	struct vm_page *pg;
1969 	vm_prot_t oldprot;
1970 	int32_t refchg;
1971 
1972 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
1973 
1974 	/*
1975 	 * Change the protection of the page.
1976 	 */
1977 	oldprot = pvo->pvo_pte.prot;
1978 	pvo->pvo_pte.prot = prot;
1979 	pg = PHYS_TO_VM_PAGE(pvo->pvo_pte.pa & LPTE_RPGN);
1980 
1981 	/*
1982 	 * If the PVO is in the page table, update mapping
1983 	 */
1984 	refchg = MOEA64_PTE_REPLACE(mmu, pvo, MOEA64_PTE_PROT_UPDATE);
1985 	if (refchg < 0)
1986 		refchg = (oldprot & VM_PROT_WRITE) ? LPTE_CHG : 0;
1987 
1988 	if (pm != kernel_pmap && pg != NULL && !(pg->aflags & PGA_EXECUTABLE) &&
1989 	    (pvo->pvo_pte.pa & (LPTE_I | LPTE_G | LPTE_NOEXEC)) == 0) {
1990 		if ((pg->oflags & VPO_UNMANAGED) == 0)
1991 			vm_page_aflag_set(pg, PGA_EXECUTABLE);
1992 		moea64_syncicache(mmu, pm, PVO_VADDR(pvo),
1993 		    pvo->pvo_pte.pa & LPTE_RPGN, PAGE_SIZE);
1994 	}
1995 
1996 	/*
1997 	 * Update vm about the REF/CHG bits if the page is managed and we have
1998 	 * removed write access.
1999 	 */
2000 	if (pg != NULL && (pvo->pvo_vaddr & PVO_MANAGED) &&
2001 	    (oldprot & VM_PROT_WRITE)) {
2002 		refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2003 		if (refchg & LPTE_CHG)
2004 			vm_page_dirty(pg);
2005 		if (refchg & LPTE_REF)
2006 			vm_page_aflag_set(pg, PGA_REFERENCED);
2007 	}
2008 }
2009 
2010 void
2011 moea64_protect(mmu_t mmu, pmap_t pm, vm_offset_t sva, vm_offset_t eva,
2012     vm_prot_t prot)
2013 {
2014 	struct	pvo_entry *pvo, *tpvo, key;
2015 
2016 	CTR4(KTR_PMAP, "moea64_protect: pm=%p sva=%#x eva=%#x prot=%#x", pm,
2017 	    sva, eva, prot);
2018 
2019 	KASSERT(pm == &curproc->p_vmspace->vm_pmap || pm == kernel_pmap,
2020 	    ("moea64_protect: non current pmap"));
2021 
2022 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2023 		moea64_remove(mmu, pm, sva, eva);
2024 		return;
2025 	}
2026 
2027 	PMAP_LOCK(pm);
2028 	key.pvo_vaddr = sva;
2029 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2030 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
2031 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
2032 		moea64_pvo_protect(mmu, pm, pvo, prot);
2033 	}
2034 	PMAP_UNLOCK(pm);
2035 }
2036 
2037 /*
2038  * Map a list of wired pages into kernel virtual address space.  This is
2039  * intended for temporary mappings which do not need page modification or
2040  * references recorded.  Existing mappings in the region are overwritten.
2041  */
2042 void
2043 moea64_qenter(mmu_t mmu, vm_offset_t va, vm_page_t *m, int count)
2044 {
2045 	while (count-- > 0) {
2046 		moea64_kenter(mmu, va, VM_PAGE_TO_PHYS(*m));
2047 		va += PAGE_SIZE;
2048 		m++;
2049 	}
2050 }
2051 
2052 /*
2053  * Remove page mappings from kernel virtual address space.  Intended for
2054  * temporary mappings entered by moea64_qenter.
2055  */
2056 void
2057 moea64_qremove(mmu_t mmu, vm_offset_t va, int count)
2058 {
2059 	while (count-- > 0) {
2060 		moea64_kremove(mmu, va);
2061 		va += PAGE_SIZE;
2062 	}
2063 }
2064 
2065 void
2066 moea64_release_vsid(uint64_t vsid)
2067 {
2068 	int idx, mask;
2069 
2070 	mtx_lock(&moea64_slb_mutex);
2071 	idx = vsid & (NVSIDS-1);
2072 	mask = 1 << (idx % VSID_NBPW);
2073 	idx /= VSID_NBPW;
2074 	KASSERT(moea64_vsid_bitmap[idx] & mask,
2075 	    ("Freeing unallocated VSID %#jx", vsid));
2076 	moea64_vsid_bitmap[idx] &= ~mask;
2077 	mtx_unlock(&moea64_slb_mutex);
2078 }
2079 
2080 
2081 void
2082 moea64_release(mmu_t mmu, pmap_t pmap)
2083 {
2084 
2085 	/*
2086 	 * Free segment registers' VSIDs
2087 	 */
2088     #ifdef __powerpc64__
2089 	slb_free_tree(pmap);
2090 	slb_free_user_cache(pmap->pm_slb);
2091     #else
2092 	KASSERT(pmap->pm_sr[0] != 0, ("moea64_release: pm_sr[0] = 0"));
2093 
2094 	moea64_release_vsid(VSID_TO_HASH(pmap->pm_sr[0]));
2095     #endif
2096 }
2097 
2098 /*
2099  * Remove all pages mapped by the specified pmap
2100  */
2101 void
2102 moea64_remove_pages(mmu_t mmu, pmap_t pm)
2103 {
2104 	struct pvo_entry *pvo, *tpvo;
2105 	struct pvo_tree tofree;
2106 
2107 	RB_INIT(&tofree);
2108 
2109 	PMAP_LOCK(pm);
2110 	RB_FOREACH_SAFE(pvo, pvo_tree, &pm->pmap_pvo, tpvo) {
2111 		if (pvo->pvo_vaddr & PVO_WIRED)
2112 			continue;
2113 
2114 		/*
2115 		 * For locking reasons, remove this from the page table and
2116 		 * pmap, but save delinking from the vm_page for a second
2117 		 * pass
2118 		 */
2119 		moea64_pvo_remove_from_pmap(mmu, pvo);
2120 		RB_INSERT(pvo_tree, &tofree, pvo);
2121 	}
2122 	PMAP_UNLOCK(pm);
2123 
2124 	RB_FOREACH_SAFE(pvo, pvo_tree, &tofree, tpvo) {
2125 		PV_LOCK(pvo->pvo_pte.pa & LPTE_RPGN);
2126 		moea64_pvo_remove_from_page(mmu, pvo);
2127 		PV_UNLOCK(pvo->pvo_pte.pa & LPTE_RPGN);
2128 		RB_REMOVE(pvo_tree, &tofree, pvo);
2129 		free_pvo_entry(pvo);
2130 	}
2131 }
2132 
2133 /*
2134  * Remove the given range of addresses from the specified map.
2135  */
2136 void
2137 moea64_remove(mmu_t mmu, pmap_t pm, vm_offset_t sva, vm_offset_t eva)
2138 {
2139 	struct  pvo_entry *pvo, *tpvo, key;
2140 	struct pvo_tree tofree;
2141 
2142 	/*
2143 	 * Perform an unsynchronized read.  This is, however, safe.
2144 	 */
2145 	if (pm->pm_stats.resident_count == 0)
2146 		return;
2147 
2148 	key.pvo_vaddr = sva;
2149 
2150 	RB_INIT(&tofree);
2151 
2152 	PMAP_LOCK(pm);
2153 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
2154 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
2155 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
2156 
2157 		/*
2158 		 * For locking reasons, remove this from the page table and
2159 		 * pmap, but save delinking from the vm_page for a second
2160 		 * pass
2161 		 */
2162 		moea64_pvo_remove_from_pmap(mmu, pvo);
2163 		RB_INSERT(pvo_tree, &tofree, pvo);
2164 	}
2165 	PMAP_UNLOCK(pm);
2166 
2167 	RB_FOREACH_SAFE(pvo, pvo_tree, &tofree, tpvo) {
2168 		PV_LOCK(pvo->pvo_pte.pa & LPTE_RPGN);
2169 		moea64_pvo_remove_from_page(mmu, pvo);
2170 		PV_UNLOCK(pvo->pvo_pte.pa & LPTE_RPGN);
2171 		RB_REMOVE(pvo_tree, &tofree, pvo);
2172 		free_pvo_entry(pvo);
2173 	}
2174 }
2175 
2176 /*
2177  * Remove physical page from all pmaps in which it resides. moea64_pvo_remove()
2178  * will reflect changes in pte's back to the vm_page.
2179  */
2180 void
2181 moea64_remove_all(mmu_t mmu, vm_page_t m)
2182 {
2183 	struct	pvo_entry *pvo, *next_pvo;
2184 	struct	pvo_head freequeue;
2185 	int	wasdead;
2186 	pmap_t	pmap;
2187 
2188 	LIST_INIT(&freequeue);
2189 
2190 	PV_PAGE_LOCK(m);
2191 	LIST_FOREACH_SAFE(pvo, vm_page_to_pvoh(m), pvo_vlink, next_pvo) {
2192 		pmap = pvo->pvo_pmap;
2193 		PMAP_LOCK(pmap);
2194 		wasdead = (pvo->pvo_vaddr & PVO_DEAD);
2195 		if (!wasdead)
2196 			moea64_pvo_remove_from_pmap(mmu, pvo);
2197 		moea64_pvo_remove_from_page(mmu, pvo);
2198 		if (!wasdead)
2199 			LIST_INSERT_HEAD(&freequeue, pvo, pvo_vlink);
2200 		PMAP_UNLOCK(pmap);
2201 
2202 	}
2203 	KASSERT(!pmap_page_is_mapped(m), ("Page still has mappings"));
2204 	KASSERT(!(m->aflags & PGA_WRITEABLE), ("Page still writable"));
2205 	PV_PAGE_UNLOCK(m);
2206 
2207 	/* Clean up UMA allocations */
2208 	LIST_FOREACH_SAFE(pvo, &freequeue, pvo_vlink, next_pvo)
2209 		free_pvo_entry(pvo);
2210 }
2211 
2212 /*
2213  * Allocate a physical page of memory directly from the phys_avail map.
2214  * Can only be called from moea64_bootstrap before avail start and end are
2215  * calculated.
2216  */
2217 vm_offset_t
2218 moea64_bootstrap_alloc(vm_size_t size, u_int align)
2219 {
2220 	vm_offset_t	s, e;
2221 	int		i, j;
2222 
2223 	size = round_page(size);
2224 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
2225 		if (align != 0)
2226 			s = (phys_avail[i] + align - 1) & ~(align - 1);
2227 		else
2228 			s = phys_avail[i];
2229 		e = s + size;
2230 
2231 		if (s < phys_avail[i] || e > phys_avail[i + 1])
2232 			continue;
2233 
2234 		if (s + size > platform_real_maxaddr())
2235 			continue;
2236 
2237 		if (s == phys_avail[i]) {
2238 			phys_avail[i] += size;
2239 		} else if (e == phys_avail[i + 1]) {
2240 			phys_avail[i + 1] -= size;
2241 		} else {
2242 			for (j = phys_avail_count * 2; j > i; j -= 2) {
2243 				phys_avail[j] = phys_avail[j - 2];
2244 				phys_avail[j + 1] = phys_avail[j - 1];
2245 			}
2246 
2247 			phys_avail[i + 3] = phys_avail[i + 1];
2248 			phys_avail[i + 1] = s;
2249 			phys_avail[i + 2] = e;
2250 			phys_avail_count++;
2251 		}
2252 
2253 		return (s);
2254 	}
2255 	panic("moea64_bootstrap_alloc: could not allocate memory");
2256 }
2257 
2258 static int
2259 moea64_pvo_enter(mmu_t mmu, struct pvo_entry *pvo, struct pvo_head *pvo_head)
2260 {
2261 	int first, err;
2262 
2263 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2264 	KASSERT(moea64_pvo_find_va(pvo->pvo_pmap, PVO_VADDR(pvo)) == NULL,
2265 	    ("Existing mapping for VA %#jx", (uintmax_t)PVO_VADDR(pvo)));
2266 
2267 	moea64_pvo_enter_calls++;
2268 
2269 	/*
2270 	 * Add to pmap list
2271 	 */
2272 	RB_INSERT(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2273 
2274 	/*
2275 	 * Remember if the list was empty and therefore will be the first
2276 	 * item.
2277 	 */
2278 	if (pvo_head != NULL) {
2279 		if (LIST_FIRST(pvo_head) == NULL)
2280 			first = 1;
2281 		LIST_INSERT_HEAD(pvo_head, pvo, pvo_vlink);
2282 	}
2283 
2284 	if (pvo->pvo_vaddr & PVO_WIRED)
2285 		pvo->pvo_pmap->pm_stats.wired_count++;
2286 	pvo->pvo_pmap->pm_stats.resident_count++;
2287 
2288 	/*
2289 	 * Insert it into the hardware page table
2290 	 */
2291 	err = MOEA64_PTE_INSERT(mmu, pvo);
2292 	if (err != 0) {
2293 		panic("moea64_pvo_enter: overflow");
2294 	}
2295 
2296 	moea64_pvo_entries++;
2297 
2298 	if (pvo->pvo_pmap == kernel_pmap)
2299 		isync();
2300 
2301 #ifdef __powerpc64__
2302 	/*
2303 	 * Make sure all our bootstrap mappings are in the SLB as soon
2304 	 * as virtual memory is switched on.
2305 	 */
2306 	if (!pmap_bootstrapped)
2307 		moea64_bootstrap_slb_prefault(PVO_VADDR(pvo),
2308 		    pvo->pvo_vaddr & PVO_LARGE);
2309 #endif
2310 
2311 	return (first ? ENOENT : 0);
2312 }
2313 
2314 static void
2315 moea64_pvo_remove_from_pmap(mmu_t mmu, struct pvo_entry *pvo)
2316 {
2317 	struct	vm_page *pg;
2318 	int32_t refchg;
2319 
2320 	KASSERT(pvo->pvo_pmap != NULL, ("Trying to remove PVO with no pmap"));
2321 	PMAP_LOCK_ASSERT(pvo->pvo_pmap, MA_OWNED);
2322 	KASSERT(!(pvo->pvo_vaddr & PVO_DEAD), ("Trying to remove dead PVO"));
2323 
2324 	/*
2325 	 * If there is an active pte entry, we need to deactivate it
2326 	 */
2327 	refchg = MOEA64_PTE_UNSET(mmu, pvo);
2328 	if (refchg < 0) {
2329 		/*
2330 		 * If it was evicted from the page table, be pessimistic and
2331 		 * dirty the page.
2332 		 */
2333 		if (pvo->pvo_pte.prot & VM_PROT_WRITE)
2334 			refchg = LPTE_CHG;
2335 		else
2336 			refchg = 0;
2337 	}
2338 
2339 	/*
2340 	 * Update our statistics.
2341 	 */
2342 	pvo->pvo_pmap->pm_stats.resident_count--;
2343 	if (pvo->pvo_vaddr & PVO_WIRED)
2344 		pvo->pvo_pmap->pm_stats.wired_count--;
2345 
2346 	/*
2347 	 * Remove this PVO from the pmap list.
2348 	 */
2349 	RB_REMOVE(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2350 
2351 	/*
2352 	 * Mark this for the next sweep
2353 	 */
2354 	pvo->pvo_vaddr |= PVO_DEAD;
2355 
2356 	/* Send RC bits to VM */
2357 	if ((pvo->pvo_vaddr & PVO_MANAGED) &&
2358 	    (pvo->pvo_pte.prot & VM_PROT_WRITE)) {
2359 		pg = PHYS_TO_VM_PAGE(pvo->pvo_pte.pa & LPTE_RPGN);
2360 		if (pg != NULL) {
2361 			refchg |= atomic_readandclear_32(&pg->md.mdpg_attrs);
2362 			if (refchg & LPTE_CHG)
2363 				vm_page_dirty(pg);
2364 			if (refchg & LPTE_REF)
2365 				vm_page_aflag_set(pg, PGA_REFERENCED);
2366 		}
2367 	}
2368 }
2369 
2370 static void
2371 moea64_pvo_remove_from_page(mmu_t mmu, struct pvo_entry *pvo)
2372 {
2373 	struct	vm_page *pg;
2374 
2375 	KASSERT(pvo->pvo_vaddr & PVO_DEAD, ("Trying to delink live page"));
2376 
2377 	/* Use NULL pmaps as a sentinel for races in page deletion */
2378 	if (pvo->pvo_pmap == NULL)
2379 		return;
2380 	pvo->pvo_pmap = NULL;
2381 
2382 	/*
2383 	 * Update vm about page writeability/executability if managed
2384 	 */
2385 	PV_LOCKASSERT(pvo->pvo_pte.pa & LPTE_RPGN);
2386 	pg = PHYS_TO_VM_PAGE(pvo->pvo_pte.pa & LPTE_RPGN);
2387 
2388 	if ((pvo->pvo_vaddr & PVO_MANAGED) && pg != NULL) {
2389 		LIST_REMOVE(pvo, pvo_vlink);
2390 		if (LIST_EMPTY(vm_page_to_pvoh(pg)))
2391 			vm_page_aflag_clear(pg, PGA_WRITEABLE | PGA_EXECUTABLE);
2392 	}
2393 
2394 	moea64_pvo_entries--;
2395 	moea64_pvo_remove_calls++;
2396 }
2397 
2398 static struct pvo_entry *
2399 moea64_pvo_find_va(pmap_t pm, vm_offset_t va)
2400 {
2401 	struct pvo_entry key;
2402 
2403 	PMAP_LOCK_ASSERT(pm, MA_OWNED);
2404 
2405 	key.pvo_vaddr = va & ~ADDR_POFF;
2406 	return (RB_FIND(pvo_tree, &pm->pmap_pvo, &key));
2407 }
2408 
2409 static boolean_t
2410 moea64_query_bit(mmu_t mmu, vm_page_t m, uint64_t ptebit)
2411 {
2412 	struct	pvo_entry *pvo;
2413 	int64_t ret;
2414 	boolean_t rv;
2415 
2416 	/*
2417 	 * See if this bit is stored in the page already.
2418 	 */
2419 	if (m->md.mdpg_attrs & ptebit)
2420 		return (TRUE);
2421 
2422 	/*
2423 	 * Examine each PTE.  Sync so that any pending REF/CHG bits are
2424 	 * flushed to the PTEs.
2425 	 */
2426 	rv = FALSE;
2427 	powerpc_sync();
2428 	PV_PAGE_LOCK(m);
2429 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2430 		ret = 0;
2431 
2432 		/*
2433 		 * See if this pvo has a valid PTE.  if so, fetch the
2434 		 * REF/CHG bits from the valid PTE.  If the appropriate
2435 		 * ptebit is set, return success.
2436 		 */
2437 		PMAP_LOCK(pvo->pvo_pmap);
2438 		if (!(pvo->pvo_vaddr & PVO_DEAD))
2439 			ret = MOEA64_PTE_SYNCH(mmu, pvo);
2440 		PMAP_UNLOCK(pvo->pvo_pmap);
2441 
2442 		if (ret > 0) {
2443 			atomic_set_32(&m->md.mdpg_attrs,
2444 			    ret & (LPTE_CHG | LPTE_REF));
2445 			if (ret & ptebit) {
2446 				rv = TRUE;
2447 				break;
2448 			}
2449 		}
2450 	}
2451 	PV_PAGE_UNLOCK(m);
2452 
2453 	return (rv);
2454 }
2455 
2456 static u_int
2457 moea64_clear_bit(mmu_t mmu, vm_page_t m, u_int64_t ptebit)
2458 {
2459 	u_int	count;
2460 	struct	pvo_entry *pvo;
2461 	int64_t ret;
2462 
2463 	/*
2464 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
2465 	 * we can reset the right ones).
2466 	 */
2467 	powerpc_sync();
2468 
2469 	/*
2470 	 * For each pvo entry, clear the pte's ptebit.
2471 	 */
2472 	count = 0;
2473 	PV_PAGE_LOCK(m);
2474 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2475 		ret = 0;
2476 
2477 		PMAP_LOCK(pvo->pvo_pmap);
2478 		if (!(pvo->pvo_vaddr & PVO_DEAD))
2479 			ret = MOEA64_PTE_CLEAR(mmu, pvo, ptebit);
2480 		PMAP_UNLOCK(pvo->pvo_pmap);
2481 
2482 		if (ret > 0 && (ret & ptebit))
2483 			count++;
2484 	}
2485 	atomic_clear_32(&m->md.mdpg_attrs, ptebit);
2486 	PV_PAGE_UNLOCK(m);
2487 
2488 	return (count);
2489 }
2490 
2491 boolean_t
2492 moea64_dev_direct_mapped(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2493 {
2494 	struct pvo_entry *pvo, key;
2495 	vm_offset_t ppa;
2496 	int error = 0;
2497 
2498 	PMAP_LOCK(kernel_pmap);
2499 	key.pvo_vaddr = ppa = pa & ~ADDR_POFF;
2500 	for (pvo = RB_FIND(pvo_tree, &kernel_pmap->pmap_pvo, &key);
2501 	    ppa < pa + size; ppa += PAGE_SIZE,
2502 	    pvo = RB_NEXT(pvo_tree, &kernel_pmap->pmap_pvo, pvo)) {
2503 		if (pvo == NULL || (pvo->pvo_pte.pa & LPTE_RPGN) != ppa) {
2504 			error = EFAULT;
2505 			break;
2506 		}
2507 	}
2508 	PMAP_UNLOCK(kernel_pmap);
2509 
2510 	return (error);
2511 }
2512 
2513 /*
2514  * Map a set of physical memory pages into the kernel virtual
2515  * address space. Return a pointer to where it is mapped. This
2516  * routine is intended to be used for mapping device memory,
2517  * NOT real memory.
2518  */
2519 void *
2520 moea64_mapdev_attr(mmu_t mmu, vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2521 {
2522 	vm_offset_t va, tmpva, ppa, offset;
2523 
2524 	ppa = trunc_page(pa);
2525 	offset = pa & PAGE_MASK;
2526 	size = roundup2(offset + size, PAGE_SIZE);
2527 
2528 	va = kva_alloc(size);
2529 
2530 	if (!va)
2531 		panic("moea64_mapdev: Couldn't alloc kernel virtual memory");
2532 
2533 	for (tmpva = va; size > 0;) {
2534 		moea64_kenter_attr(mmu, tmpva, ppa, ma);
2535 		size -= PAGE_SIZE;
2536 		tmpva += PAGE_SIZE;
2537 		ppa += PAGE_SIZE;
2538 	}
2539 
2540 	return ((void *)(va + offset));
2541 }
2542 
2543 void *
2544 moea64_mapdev(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2545 {
2546 
2547 	return moea64_mapdev_attr(mmu, pa, size, VM_MEMATTR_DEFAULT);
2548 }
2549 
2550 void
2551 moea64_unmapdev(mmu_t mmu, vm_offset_t va, vm_size_t size)
2552 {
2553 	vm_offset_t base, offset;
2554 
2555 	base = trunc_page(va);
2556 	offset = va & PAGE_MASK;
2557 	size = roundup2(offset + size, PAGE_SIZE);
2558 
2559 	kva_free(base, size);
2560 }
2561 
2562 void
2563 moea64_sync_icache(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_size_t sz)
2564 {
2565 	struct pvo_entry *pvo;
2566 	vm_offset_t lim;
2567 	vm_paddr_t pa;
2568 	vm_size_t len;
2569 
2570 	PMAP_LOCK(pm);
2571 	while (sz > 0) {
2572 		lim = round_page(va);
2573 		len = MIN(lim - va, sz);
2574 		pvo = moea64_pvo_find_va(pm, va & ~ADDR_POFF);
2575 		if (pvo != NULL && !(pvo->pvo_pte.pa & LPTE_I)) {
2576 			pa = (pvo->pvo_pte.pa & LPTE_RPGN) | (va & ADDR_POFF);
2577 			moea64_syncicache(mmu, pm, va, pa, len);
2578 		}
2579 		va += len;
2580 		sz -= len;
2581 	}
2582 	PMAP_UNLOCK(pm);
2583 }
2584 
2585 void
2586 moea64_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz, void **va)
2587 {
2588 
2589 	*va = (void *)pa;
2590 }
2591 
2592 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2593 
2594 void
2595 moea64_scan_init(mmu_t mmu)
2596 {
2597 	struct pvo_entry *pvo;
2598 	vm_offset_t va;
2599 	int i;
2600 
2601 	if (!do_minidump) {
2602 		/* Initialize phys. segments for dumpsys(). */
2603 		memset(&dump_map, 0, sizeof(dump_map));
2604 		mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
2605 		for (i = 0; i < pregions_sz; i++) {
2606 			dump_map[i].pa_start = pregions[i].mr_start;
2607 			dump_map[i].pa_size = pregions[i].mr_size;
2608 		}
2609 		return;
2610 	}
2611 
2612 	/* Virtual segments for minidumps: */
2613 	memset(&dump_map, 0, sizeof(dump_map));
2614 
2615 	/* 1st: kernel .data and .bss. */
2616 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2617 	dump_map[0].pa_size = round_page((uintptr_t)_end) -
2618 	    dump_map[0].pa_start;
2619 
2620 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2621 	dump_map[1].pa_start = (vm_paddr_t)msgbufp->msg_ptr;
2622 	dump_map[1].pa_size = round_page(msgbufp->msg_size);
2623 
2624 	/* 3rd: kernel VM. */
2625 	va = dump_map[1].pa_start + dump_map[1].pa_size;
2626 	/* Find start of next chunk (from va). */
2627 	while (va < virtual_end) {
2628 		/* Don't dump the buffer cache. */
2629 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2630 			va = kmi.buffer_eva;
2631 			continue;
2632 		}
2633 		pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
2634 		if (pvo != NULL && !(pvo->pvo_vaddr & PVO_DEAD))
2635 			break;
2636 		va += PAGE_SIZE;
2637 	}
2638 	if (va < virtual_end) {
2639 		dump_map[2].pa_start = va;
2640 		va += PAGE_SIZE;
2641 		/* Find last page in chunk. */
2642 		while (va < virtual_end) {
2643 			/* Don't run into the buffer cache. */
2644 			if (va == kmi.buffer_sva)
2645 				break;
2646 			pvo = moea64_pvo_find_va(kernel_pmap, va & ~ADDR_POFF);
2647 			if (pvo != NULL && !(pvo->pvo_vaddr & PVO_DEAD))
2648 				break;
2649 			va += PAGE_SIZE;
2650 		}
2651 		dump_map[2].pa_size = va - dump_map[2].pa_start;
2652 	}
2653 }
2654 
2655