xref: /freebsd/sys/powerpc/aim/mmu_oea.c (revision 9286d46a794f25482880d29864a8901ef6666fae)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause AND BSD-4-Clause
3  *
4  * Copyright (c) 2001 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Matt Thomas <matt@3am-software.com> of Allegro Networks, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 /*-
32  * Copyright (C) 1995, 1996 Wolfgang Solfrank.
33  * Copyright (C) 1995, 1996 TooLs GmbH.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. All advertising materials mentioning features or use of this software
45  *    must display the following acknowledgement:
46  *	This product includes software developed by TooLs GmbH.
47  * 4. The name of TooLs GmbH may not be used to endorse or promote products
48  *    derived from this software without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
51  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
54  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
55  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
56  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
57  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
58  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
59  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60  *
61  * $NetBSD: pmap.c,v 1.28 2000/03/26 20:42:36 kleink Exp $
62  */
63 /*-
64  * Copyright (C) 2001 Benno Rice.
65  * All rights reserved.
66  *
67  * Redistribution and use in source and binary forms, with or without
68  * modification, are permitted provided that the following conditions
69  * are met:
70  * 1. Redistributions of source code must retain the above copyright
71  *    notice, this list of conditions and the following disclaimer.
72  * 2. Redistributions in binary form must reproduce the above copyright
73  *    notice, this list of conditions and the following disclaimer in the
74  *    documentation and/or other materials provided with the distribution.
75  *
76  * THIS SOFTWARE IS PROVIDED BY Benno Rice ``AS IS'' AND ANY EXPRESS OR
77  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
78  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
79  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
80  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
81  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
82  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
83  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
84  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
85  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
86  */
87 
88 #include <sys/cdefs.h>
89 /*
90  * Manages physical address maps.
91  *
92  * Since the information managed by this module is also stored by the
93  * logical address mapping module, this module may throw away valid virtual
94  * to physical mappings at almost any time.  However, invalidations of
95  * mappings must be done as requested.
96  *
97  * In order to cope with hardware architectures which make virtual to
98  * physical map invalidates expensive, this module may delay invalidate
99  * reduced protection operations until such time as they are actually
100  * necessary.  This module is given full information as to which processors
101  * are currently using which maps, and to when physical maps must be made
102  * correct.
103  */
104 
105 #include "opt_kstack_pages.h"
106 
107 #include <sys/param.h>
108 #include <sys/kernel.h>
109 #include <sys/conf.h>
110 #include <sys/queue.h>
111 #include <sys/cpuset.h>
112 #include <sys/kerneldump.h>
113 #include <sys/ktr.h>
114 #include <sys/lock.h>
115 #include <sys/mman.h>
116 #include <sys/msgbuf.h>
117 #include <sys/mutex.h>
118 #include <sys/proc.h>
119 #include <sys/rwlock.h>
120 #include <sys/sched.h>
121 #include <sys/sysctl.h>
122 #include <sys/systm.h>
123 #include <sys/vmmeter.h>
124 
125 #include <dev/ofw/openfirm.h>
126 
127 #include <vm/vm.h>
128 #include <vm/pmap.h>
129 #include <vm/vm_param.h>
130 #include <vm/vm_kern.h>
131 #include <vm/vm_page.h>
132 #include <vm/vm_map.h>
133 #include <vm/vm_object.h>
134 #include <vm/vm_extern.h>
135 #include <vm/vm_page.h>
136 #include <vm/vm_phys.h>
137 #include <vm/vm_pageout.h>
138 #include <vm/uma.h>
139 
140 #include <machine/cpu.h>
141 #include <machine/platform.h>
142 #include <machine/bat.h>
143 #include <machine/frame.h>
144 #include <machine/md_var.h>
145 #include <machine/psl.h>
146 #include <machine/pte.h>
147 #include <machine/smp.h>
148 #include <machine/sr.h>
149 #include <machine/mmuvar.h>
150 #include <machine/trap.h>
151 
152 #define	MOEA_DEBUG
153 
154 #define TODO	panic("%s: not implemented", __func__);
155 
156 #define	VSID_MAKE(sr, hash)	((sr) | (((hash) & 0xfffff) << 4))
157 #define	VSID_TO_SR(vsid)	((vsid) & 0xf)
158 #define	VSID_TO_HASH(vsid)	(((vsid) >> 4) & 0xfffff)
159 
160 /* Get physical address from PVO. */
161 #define PVO_PADDR(pvo)		((pvo)->pvo_pte.pte.pte_lo & PTE_RPGN)
162 
163 struct ofw_map {
164 	vm_offset_t	om_va;
165 	vm_size_t	om_len;
166 	vm_offset_t	om_pa;
167 	u_int		om_mode;
168 };
169 
170 extern unsigned char _etext[];
171 extern unsigned char _end[];
172 
173 /*
174  * Map of physical memory regions.
175  */
176 static struct	mem_region *regions;
177 static struct	mem_region *pregions;
178 static u_int    phys_avail_count;
179 static int	regions_sz, pregions_sz;
180 static struct	ofw_map *translations;
181 
182 /*
183  * Lock for the pteg and pvo tables.
184  */
185 struct mtx	moea_table_mutex;
186 struct mtx	moea_vsid_mutex;
187 
188 /* tlbie instruction synchronization */
189 static struct mtx tlbie_mtx;
190 
191 /*
192  * PTEG data.
193  */
194 static struct	pteg *moea_pteg_table;
195 u_int		moea_pteg_count;
196 u_int		moea_pteg_mask;
197 
198 /*
199  * PVO data.
200  */
201 struct	pvo_head *moea_pvo_table;		/* pvo entries by pteg index */
202 struct	pvo_head moea_pvo_kunmanaged =
203     LIST_HEAD_INITIALIZER(moea_pvo_kunmanaged);	/* list of unmanaged pages */
204 
205 static struct rwlock_padalign pvh_global_lock;
206 
207 uma_zone_t	moea_upvo_zone;	/* zone for pvo entries for unmanaged pages */
208 uma_zone_t	moea_mpvo_zone;	/* zone for pvo entries for managed pages */
209 
210 #define	BPVO_POOL_SIZE	32768
211 static struct	pvo_entry *moea_bpvo_pool;
212 static int	moea_bpvo_pool_index = 0;
213 
214 #define	VSID_NBPW	(sizeof(u_int32_t) * 8)
215 static u_int	moea_vsid_bitmap[NPMAPS / VSID_NBPW];
216 
217 static bool	moea_initialized = false;
218 
219 /*
220  * Statistics.
221  */
222 u_int	moea_pte_valid = 0;
223 u_int	moea_pte_overflow = 0;
224 u_int	moea_pte_replacements = 0;
225 u_int	moea_pvo_entries = 0;
226 u_int	moea_pvo_enter_calls = 0;
227 u_int	moea_pvo_remove_calls = 0;
228 u_int	moea_pte_spills = 0;
229 SYSCTL_INT(_machdep, OID_AUTO, moea_pte_valid, CTLFLAG_RD, &moea_pte_valid,
230     0, "");
231 SYSCTL_INT(_machdep, OID_AUTO, moea_pte_overflow, CTLFLAG_RD,
232     &moea_pte_overflow, 0, "");
233 SYSCTL_INT(_machdep, OID_AUTO, moea_pte_replacements, CTLFLAG_RD,
234     &moea_pte_replacements, 0, "");
235 SYSCTL_INT(_machdep, OID_AUTO, moea_pvo_entries, CTLFLAG_RD, &moea_pvo_entries,
236     0, "");
237 SYSCTL_INT(_machdep, OID_AUTO, moea_pvo_enter_calls, CTLFLAG_RD,
238     &moea_pvo_enter_calls, 0, "");
239 SYSCTL_INT(_machdep, OID_AUTO, moea_pvo_remove_calls, CTLFLAG_RD,
240     &moea_pvo_remove_calls, 0, "");
241 SYSCTL_INT(_machdep, OID_AUTO, moea_pte_spills, CTLFLAG_RD,
242     &moea_pte_spills, 0, "");
243 
244 /*
245  * Allocate physical memory for use in moea_bootstrap.
246  */
247 static vm_offset_t	moea_bootstrap_alloc(vm_size_t, u_int);
248 
249 /*
250  * PTE calls.
251  */
252 static int		moea_pte_insert(u_int, struct pte *);
253 
254 /*
255  * PVO calls.
256  */
257 static int	moea_pvo_enter(pmap_t, uma_zone_t, struct pvo_head *,
258 		    vm_offset_t, vm_paddr_t, u_int, int);
259 static void	moea_pvo_remove(struct pvo_entry *, int);
260 static struct	pvo_entry *moea_pvo_find_va(pmap_t, vm_offset_t, int *);
261 static struct	pte *moea_pvo_to_pte(const struct pvo_entry *, int);
262 
263 /*
264  * Utility routines.
265  */
266 static int		moea_enter_locked(pmap_t, vm_offset_t, vm_page_t,
267 			    vm_prot_t, u_int, int8_t);
268 static void		moea_syncicache(vm_paddr_t, vm_size_t);
269 static bool		moea_query_bit(vm_page_t, int);
270 static u_int		moea_clear_bit(vm_page_t, int);
271 static void		moea_kremove(vm_offset_t);
272 int		moea_pte_spill(vm_offset_t);
273 
274 /*
275  * Kernel MMU interface
276  */
277 void moea_clear_modify(vm_page_t);
278 void moea_copy_page(vm_page_t, vm_page_t);
279 void moea_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
280     vm_page_t *mb, vm_offset_t b_offset, int xfersize);
281 int moea_enter(pmap_t, vm_offset_t, vm_page_t, vm_prot_t, u_int,
282     int8_t);
283 void moea_enter_object(pmap_t, vm_offset_t, vm_offset_t, vm_page_t,
284     vm_prot_t);
285 void moea_enter_quick(pmap_t, vm_offset_t, vm_page_t, vm_prot_t);
286 vm_paddr_t moea_extract(pmap_t, vm_offset_t);
287 vm_page_t moea_extract_and_hold(pmap_t, vm_offset_t, vm_prot_t);
288 void moea_init(void);
289 bool moea_is_modified(vm_page_t);
290 bool moea_is_prefaultable(pmap_t, vm_offset_t);
291 bool moea_is_referenced(vm_page_t);
292 int moea_ts_referenced(vm_page_t);
293 vm_offset_t moea_map(vm_offset_t *, vm_paddr_t, vm_paddr_t, int);
294 static int moea_mincore(pmap_t, vm_offset_t, vm_paddr_t *);
295 bool moea_page_exists_quick(pmap_t, vm_page_t);
296 void moea_page_init(vm_page_t);
297 int moea_page_wired_mappings(vm_page_t);
298 int moea_pinit(pmap_t);
299 void moea_pinit0(pmap_t);
300 void moea_protect(pmap_t, vm_offset_t, vm_offset_t, vm_prot_t);
301 void moea_qenter(vm_offset_t, vm_page_t *, int);
302 void moea_qremove(vm_offset_t, int);
303 void moea_release(pmap_t);
304 void moea_remove(pmap_t, vm_offset_t, vm_offset_t);
305 void moea_remove_all(vm_page_t);
306 void moea_remove_write(vm_page_t);
307 void moea_unwire(pmap_t, vm_offset_t, vm_offset_t);
308 void moea_zero_page(vm_page_t);
309 void moea_zero_page_area(vm_page_t, int, int);
310 void moea_activate(struct thread *);
311 void moea_deactivate(struct thread *);
312 void moea_cpu_bootstrap(int);
313 void moea_bootstrap(vm_offset_t, vm_offset_t);
314 void *moea_mapdev(vm_paddr_t, vm_size_t);
315 void *moea_mapdev_attr(vm_paddr_t, vm_size_t, vm_memattr_t);
316 void moea_unmapdev(void *, vm_size_t);
317 vm_paddr_t moea_kextract(vm_offset_t);
318 void moea_kenter_attr(vm_offset_t, vm_paddr_t, vm_memattr_t);
319 void moea_kenter(vm_offset_t, vm_paddr_t);
320 void moea_page_set_memattr(vm_page_t m, vm_memattr_t ma);
321 int moea_dev_direct_mapped(vm_paddr_t, vm_size_t);
322 static void moea_sync_icache(pmap_t, vm_offset_t, vm_size_t);
323 void moea_dumpsys_map(vm_paddr_t pa, size_t sz, void **va);
324 void moea_scan_init(void);
325 vm_offset_t moea_quick_enter_page(vm_page_t m);
326 void moea_quick_remove_page(vm_offset_t addr);
327 bool moea_page_is_mapped(vm_page_t m);
328 bool moea_ps_enabled(pmap_t pmap);
329 static int moea_map_user_ptr(pmap_t pm,
330     volatile const void *uaddr, void **kaddr, size_t ulen, size_t *klen);
331 static int moea_decode_kernel_ptr(vm_offset_t addr,
332     int *is_user, vm_offset_t *decoded_addr);
333 
334 static struct pmap_funcs moea_methods = {
335 	.clear_modify = moea_clear_modify,
336 	.copy_page = moea_copy_page,
337 	.copy_pages = moea_copy_pages,
338 	.enter = moea_enter,
339 	.enter_object = moea_enter_object,
340 	.enter_quick = moea_enter_quick,
341 	.extract = moea_extract,
342 	.extract_and_hold = moea_extract_and_hold,
343 	.init = moea_init,
344 	.is_modified = moea_is_modified,
345 	.is_prefaultable = moea_is_prefaultable,
346 	.is_referenced = moea_is_referenced,
347 	.ts_referenced = moea_ts_referenced,
348 	.map =      		moea_map,
349 	.page_exists_quick = moea_page_exists_quick,
350 	.page_init = moea_page_init,
351 	.page_wired_mappings = moea_page_wired_mappings,
352 	.pinit = moea_pinit,
353 	.pinit0 = moea_pinit0,
354 	.protect = moea_protect,
355 	.qenter = moea_qenter,
356 	.qremove = moea_qremove,
357 	.release = moea_release,
358 	.remove = moea_remove,
359 	.remove_all = moea_remove_all,
360 	.mincore = moea_mincore,
361 	.remove_write = moea_remove_write,
362 	.sync_icache = moea_sync_icache,
363 	.unwire = moea_unwire,
364 	.zero_page =        	moea_zero_page,
365 	.zero_page_area = moea_zero_page_area,
366 	.activate = moea_activate,
367 	.deactivate =       	moea_deactivate,
368 	.page_set_memattr = moea_page_set_memattr,
369 	.quick_enter_page =  moea_quick_enter_page,
370 	.quick_remove_page =  moea_quick_remove_page,
371 	.page_is_mapped = moea_page_is_mapped,
372 	.ps_enabled = moea_ps_enabled,
373 
374 	/* Internal interfaces */
375 	.bootstrap =        	moea_bootstrap,
376 	.cpu_bootstrap =    	moea_cpu_bootstrap,
377 	.mapdev_attr = moea_mapdev_attr,
378 	.mapdev = moea_mapdev,
379 	.unmapdev = moea_unmapdev,
380 	.kextract = moea_kextract,
381 	.kenter = moea_kenter,
382 	.kenter_attr = moea_kenter_attr,
383 	.dev_direct_mapped = moea_dev_direct_mapped,
384 	.dumpsys_pa_init = moea_scan_init,
385 	.dumpsys_map_chunk = moea_dumpsys_map,
386 	.map_user_ptr = moea_map_user_ptr,
387 	.decode_kernel_ptr =  moea_decode_kernel_ptr,
388 };
389 
390 MMU_DEF(oea_mmu, MMU_TYPE_OEA, moea_methods);
391 
392 static __inline uint32_t
393 moea_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
394 {
395 	uint32_t pte_lo;
396 	int i;
397 
398 	if (ma != VM_MEMATTR_DEFAULT) {
399 		switch (ma) {
400 		case VM_MEMATTR_UNCACHEABLE:
401 			return (PTE_I | PTE_G);
402 		case VM_MEMATTR_CACHEABLE:
403 			return (PTE_M);
404 		case VM_MEMATTR_WRITE_COMBINING:
405 		case VM_MEMATTR_WRITE_BACK:
406 		case VM_MEMATTR_PREFETCHABLE:
407 			return (PTE_I);
408 		case VM_MEMATTR_WRITE_THROUGH:
409 			return (PTE_W | PTE_M);
410 		}
411 	}
412 
413 	/*
414 	 * Assume the page is cache inhibited and access is guarded unless
415 	 * it's in our available memory array.
416 	 */
417 	pte_lo = PTE_I | PTE_G;
418 	for (i = 0; i < pregions_sz; i++) {
419 		if ((pa >= pregions[i].mr_start) &&
420 		    (pa < (pregions[i].mr_start + pregions[i].mr_size))) {
421 			pte_lo = PTE_M;
422 			break;
423 		}
424 	}
425 
426 	return pte_lo;
427 }
428 
429 /*
430  * Translate OFW translations into VM attributes.
431  */
432 static __inline vm_memattr_t
433 moea_bootstrap_convert_wimg(uint32_t mode)
434 {
435 
436 	switch (mode) {
437 	case (PTE_I | PTE_G):
438 		/* PCI device memory */
439 		return VM_MEMATTR_UNCACHEABLE;
440 	case (PTE_M):
441 		/* Explicitly coherent */
442 		return VM_MEMATTR_CACHEABLE;
443 	case 0: /* Default claim */
444 	case 2: /* Alternate PP bits set by OF for the original payload */
445 		/* "Normal" memory. */
446 		return VM_MEMATTR_DEFAULT;
447 
448 	default:
449 		/* Err on the side of caution for unknowns */
450 		/* XXX should we panic instead? */
451 		return VM_MEMATTR_UNCACHEABLE;
452 	}
453 }
454 
455 static void
456 tlbie(vm_offset_t va)
457 {
458 
459 	mtx_lock_spin(&tlbie_mtx);
460 	__asm __volatile("ptesync");
461 	__asm __volatile("tlbie %0" :: "r"(va));
462 	__asm __volatile("eieio; tlbsync; ptesync");
463 	mtx_unlock_spin(&tlbie_mtx);
464 }
465 
466 static void
467 tlbia(void)
468 {
469 	vm_offset_t va;
470 
471 	for (va = 0; va < 0x00040000; va += 0x00001000) {
472 		__asm __volatile("tlbie %0" :: "r"(va));
473 		powerpc_sync();
474 	}
475 	__asm __volatile("tlbsync");
476 	powerpc_sync();
477 }
478 
479 static __inline int
480 va_to_sr(u_int *sr, vm_offset_t va)
481 {
482 	return (sr[(uintptr_t)va >> ADDR_SR_SHFT]);
483 }
484 
485 static __inline u_int
486 va_to_pteg(u_int sr, vm_offset_t addr)
487 {
488 	u_int hash;
489 
490 	hash = (sr & SR_VSID_MASK) ^ (((u_int)addr & ADDR_PIDX) >>
491 	    ADDR_PIDX_SHFT);
492 	return (hash & moea_pteg_mask);
493 }
494 
495 static __inline struct pvo_head *
496 vm_page_to_pvoh(vm_page_t m)
497 {
498 
499 	return (&m->md.mdpg_pvoh);
500 }
501 
502 static __inline void
503 moea_attr_clear(vm_page_t m, int ptebit)
504 {
505 
506 	rw_assert(&pvh_global_lock, RA_WLOCKED);
507 	m->md.mdpg_attrs &= ~ptebit;
508 }
509 
510 static __inline int
511 moea_attr_fetch(vm_page_t m)
512 {
513 
514 	return (m->md.mdpg_attrs);
515 }
516 
517 static __inline void
518 moea_attr_save(vm_page_t m, int ptebit)
519 {
520 
521 	rw_assert(&pvh_global_lock, RA_WLOCKED);
522 	m->md.mdpg_attrs |= ptebit;
523 }
524 
525 static __inline int
526 moea_pte_compare(const struct pte *pt, const struct pte *pvo_pt)
527 {
528 	if (pt->pte_hi == pvo_pt->pte_hi)
529 		return (1);
530 
531 	return (0);
532 }
533 
534 static __inline int
535 moea_pte_match(struct pte *pt, u_int sr, vm_offset_t va, int which)
536 {
537 	return (pt->pte_hi & ~PTE_VALID) ==
538 	    (((sr & SR_VSID_MASK) << PTE_VSID_SHFT) |
539 	    ((va >> ADDR_API_SHFT) & PTE_API) | which);
540 }
541 
542 static __inline void
543 moea_pte_create(struct pte *pt, u_int sr, vm_offset_t va, u_int pte_lo)
544 {
545 
546 	mtx_assert(&moea_table_mutex, MA_OWNED);
547 
548 	/*
549 	 * Construct a PTE.  Default to IMB initially.  Valid bit only gets
550 	 * set when the real pte is set in memory.
551 	 *
552 	 * Note: Don't set the valid bit for correct operation of tlb update.
553 	 */
554 	pt->pte_hi = ((sr & SR_VSID_MASK) << PTE_VSID_SHFT) |
555 	    (((va & ADDR_PIDX) >> ADDR_API_SHFT) & PTE_API);
556 	pt->pte_lo = pte_lo;
557 }
558 
559 static __inline void
560 moea_pte_synch(struct pte *pt, struct pte *pvo_pt)
561 {
562 
563 	mtx_assert(&moea_table_mutex, MA_OWNED);
564 	pvo_pt->pte_lo |= pt->pte_lo & (PTE_REF | PTE_CHG);
565 }
566 
567 static __inline void
568 moea_pte_clear(struct pte *pt, vm_offset_t va, int ptebit)
569 {
570 
571 	mtx_assert(&moea_table_mutex, MA_OWNED);
572 
573 	/*
574 	 * As shown in Section 7.6.3.2.3
575 	 */
576 	pt->pte_lo &= ~ptebit;
577 	tlbie(va);
578 }
579 
580 static __inline void
581 moea_pte_set(struct pte *pt, struct pte *pvo_pt)
582 {
583 
584 	mtx_assert(&moea_table_mutex, MA_OWNED);
585 	pvo_pt->pte_hi |= PTE_VALID;
586 
587 	/*
588 	 * Update the PTE as defined in section 7.6.3.1.
589 	 * Note that the REF/CHG bits are from pvo_pt and thus should have
590 	 * been saved so this routine can restore them (if desired).
591 	 */
592 	pt->pte_lo = pvo_pt->pte_lo;
593 	powerpc_sync();
594 	pt->pte_hi = pvo_pt->pte_hi;
595 	powerpc_sync();
596 	moea_pte_valid++;
597 }
598 
599 static __inline void
600 moea_pte_unset(struct pte *pt, struct pte *pvo_pt, vm_offset_t va)
601 {
602 
603 	mtx_assert(&moea_table_mutex, MA_OWNED);
604 	pvo_pt->pte_hi &= ~PTE_VALID;
605 
606 	/*
607 	 * Force the reg & chg bits back into the PTEs.
608 	 */
609 	powerpc_sync();
610 
611 	/*
612 	 * Invalidate the pte.
613 	 */
614 	pt->pte_hi &= ~PTE_VALID;
615 
616 	tlbie(va);
617 
618 	/*
619 	 * Save the reg & chg bits.
620 	 */
621 	moea_pte_synch(pt, pvo_pt);
622 	moea_pte_valid--;
623 }
624 
625 static __inline void
626 moea_pte_change(struct pte *pt, struct pte *pvo_pt, vm_offset_t va)
627 {
628 
629 	/*
630 	 * Invalidate the PTE
631 	 */
632 	moea_pte_unset(pt, pvo_pt, va);
633 	moea_pte_set(pt, pvo_pt);
634 }
635 
636 /*
637  * Quick sort callout for comparing memory regions.
638  */
639 static int	om_cmp(const void *a, const void *b);
640 
641 static int
642 om_cmp(const void *a, const void *b)
643 {
644 	const struct	ofw_map *mapa;
645 	const struct	ofw_map *mapb;
646 
647 	mapa = a;
648 	mapb = b;
649 	if (mapa->om_pa < mapb->om_pa)
650 		return (-1);
651 	else if (mapa->om_pa > mapb->om_pa)
652 		return (1);
653 	else
654 		return (0);
655 }
656 
657 void
658 moea_cpu_bootstrap(int ap)
659 {
660 	u_int sdr;
661 	int i;
662 
663 	if (ap) {
664 		powerpc_sync();
665 		__asm __volatile("mtdbatu 0,%0" :: "r"(battable[0].batu));
666 		__asm __volatile("mtdbatl 0,%0" :: "r"(battable[0].batl));
667 		isync();
668 		__asm __volatile("mtibatu 0,%0" :: "r"(battable[0].batu));
669 		__asm __volatile("mtibatl 0,%0" :: "r"(battable[0].batl));
670 		isync();
671 	}
672 
673 	__asm __volatile("mtdbatu 1,%0" :: "r"(battable[8].batu));
674 	__asm __volatile("mtdbatl 1,%0" :: "r"(battable[8].batl));
675 	isync();
676 
677 	__asm __volatile("mtibatu 1,%0" :: "r"(0));
678 	__asm __volatile("mtdbatu 2,%0" :: "r"(0));
679 	__asm __volatile("mtibatu 2,%0" :: "r"(0));
680 	__asm __volatile("mtdbatu 3,%0" :: "r"(0));
681 	__asm __volatile("mtibatu 3,%0" :: "r"(0));
682 	isync();
683 
684 	for (i = 0; i < 16; i++)
685 		mtsrin(i << ADDR_SR_SHFT, kernel_pmap->pm_sr[i]);
686 	powerpc_sync();
687 
688 	sdr = (u_int)moea_pteg_table | (moea_pteg_mask >> 10);
689 	__asm __volatile("mtsdr1 %0" :: "r"(sdr));
690 	isync();
691 
692 	tlbia();
693 }
694 
695 void
696 moea_bootstrap(vm_offset_t kernelstart, vm_offset_t kernelend)
697 {
698 	ihandle_t	mmui;
699 	phandle_t	chosen, mmu;
700 	int		sz;
701 	int		i, j;
702 	vm_size_t	size, physsz, hwphyssz;
703 	vm_offset_t	pa, va, off;
704 	void		*dpcpu;
705 
706 	/*
707 	 * Map PCI memory space.
708 	 */
709 	battable[0x8].batl = BATL(0x80000000, BAT_I|BAT_G, BAT_PP_RW);
710 	battable[0x8].batu = BATU(0x80000000, BAT_BL_256M, BAT_Vs);
711 
712 	battable[0x9].batl = BATL(0x90000000, BAT_I|BAT_G, BAT_PP_RW);
713 	battable[0x9].batu = BATU(0x90000000, BAT_BL_256M, BAT_Vs);
714 
715 	battable[0xa].batl = BATL(0xa0000000, BAT_I|BAT_G, BAT_PP_RW);
716 	battable[0xa].batu = BATU(0xa0000000, BAT_BL_256M, BAT_Vs);
717 
718 	battable[0xb].batl = BATL(0xb0000000, BAT_I|BAT_G, BAT_PP_RW);
719 	battable[0xb].batu = BATU(0xb0000000, BAT_BL_256M, BAT_Vs);
720 
721 	powerpc_sync();
722 
723 	/* map pci space */
724 	__asm __volatile("mtdbatu 1,%0" :: "r"(battable[8].batu));
725 	__asm __volatile("mtdbatl 1,%0" :: "r"(battable[8].batl));
726 	isync();
727 
728 	/* set global direct map flag */
729 	hw_direct_map = 1;
730 
731 	mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
732 	CTR0(KTR_PMAP, "moea_bootstrap: physical memory");
733 
734 	for (i = 0; i < pregions_sz; i++) {
735 		vm_offset_t pa;
736 		vm_offset_t end;
737 
738 		CTR3(KTR_PMAP, "physregion: %#x - %#x (%#x)",
739 			pregions[i].mr_start,
740 			pregions[i].mr_start + pregions[i].mr_size,
741 			pregions[i].mr_size);
742 		/*
743 		 * Install entries into the BAT table to allow all
744 		 * of physmem to be convered by on-demand BAT entries.
745 		 * The loop will sometimes set the same battable element
746 		 * twice, but that's fine since they won't be used for
747 		 * a while yet.
748 		 */
749 		pa = pregions[i].mr_start & 0xf0000000;
750 		end = pregions[i].mr_start + pregions[i].mr_size;
751 		do {
752                         u_int n = pa >> ADDR_SR_SHFT;
753 
754 			battable[n].batl = BATL(pa, BAT_M, BAT_PP_RW);
755 			battable[n].batu = BATU(pa, BAT_BL_256M, BAT_Vs);
756 			pa += SEGMENT_LENGTH;
757 		} while (pa < end);
758 	}
759 
760 	if (PHYS_AVAIL_ENTRIES < regions_sz)
761 		panic("moea_bootstrap: phys_avail too small");
762 
763 	phys_avail_count = 0;
764 	physsz = 0;
765 	hwphyssz = 0;
766 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
767 	for (i = 0, j = 0; i < regions_sz; i++, j += 2) {
768 		CTR3(KTR_PMAP, "region: %#x - %#x (%#x)", regions[i].mr_start,
769 		    regions[i].mr_start + regions[i].mr_size,
770 		    regions[i].mr_size);
771 		if (hwphyssz != 0 &&
772 		    (physsz + regions[i].mr_size) >= hwphyssz) {
773 			if (physsz < hwphyssz) {
774 				phys_avail[j] = regions[i].mr_start;
775 				phys_avail[j + 1] = regions[i].mr_start +
776 				    hwphyssz - physsz;
777 				physsz = hwphyssz;
778 				phys_avail_count++;
779 			}
780 			break;
781 		}
782 		phys_avail[j] = regions[i].mr_start;
783 		phys_avail[j + 1] = regions[i].mr_start + regions[i].mr_size;
784 		phys_avail_count++;
785 		physsz += regions[i].mr_size;
786 	}
787 
788 	/* Check for overlap with the kernel and exception vectors */
789 	for (j = 0; j < 2*phys_avail_count; j+=2) {
790 		if (phys_avail[j] < EXC_LAST)
791 			phys_avail[j] += EXC_LAST;
792 
793 		if (kernelstart >= phys_avail[j] &&
794 		    kernelstart < phys_avail[j+1]) {
795 			if (kernelend < phys_avail[j+1]) {
796 				phys_avail[2*phys_avail_count] =
797 				    (kernelend & ~PAGE_MASK) + PAGE_SIZE;
798 				phys_avail[2*phys_avail_count + 1] =
799 				    phys_avail[j+1];
800 				phys_avail_count++;
801 			}
802 
803 			phys_avail[j+1] = kernelstart & ~PAGE_MASK;
804 		}
805 
806 		if (kernelend >= phys_avail[j] &&
807 		    kernelend < phys_avail[j+1]) {
808 			if (kernelstart > phys_avail[j]) {
809 				phys_avail[2*phys_avail_count] = phys_avail[j];
810 				phys_avail[2*phys_avail_count + 1] =
811 				    kernelstart & ~PAGE_MASK;
812 				phys_avail_count++;
813 			}
814 
815 			phys_avail[j] = (kernelend & ~PAGE_MASK) + PAGE_SIZE;
816 		}
817 	}
818 
819 	physmem = btoc(physsz);
820 
821 	/*
822 	 * Allocate PTEG table.
823 	 */
824 #ifdef PTEGCOUNT
825 	moea_pteg_count = PTEGCOUNT;
826 #else
827 	moea_pteg_count = 0x1000;
828 
829 	while (moea_pteg_count < physmem)
830 		moea_pteg_count <<= 1;
831 
832 	moea_pteg_count >>= 1;
833 #endif /* PTEGCOUNT */
834 
835 	size = moea_pteg_count * sizeof(struct pteg);
836 	CTR2(KTR_PMAP, "moea_bootstrap: %d PTEGs, %d bytes", moea_pteg_count,
837 	    size);
838 	moea_pteg_table = (struct pteg *)moea_bootstrap_alloc(size, size);
839 	CTR1(KTR_PMAP, "moea_bootstrap: PTEG table at %p", moea_pteg_table);
840 	bzero((void *)moea_pteg_table, moea_pteg_count * sizeof(struct pteg));
841 	moea_pteg_mask = moea_pteg_count - 1;
842 
843 	/*
844 	 * Allocate pv/overflow lists.
845 	 */
846 	size = sizeof(struct pvo_head) * moea_pteg_count;
847 	moea_pvo_table = (struct pvo_head *)moea_bootstrap_alloc(size,
848 	    PAGE_SIZE);
849 	CTR1(KTR_PMAP, "moea_bootstrap: PVO table at %p", moea_pvo_table);
850 	for (i = 0; i < moea_pteg_count; i++)
851 		LIST_INIT(&moea_pvo_table[i]);
852 
853 	/*
854 	 * Initialize the lock that synchronizes access to the pteg and pvo
855 	 * tables.
856 	 */
857 	mtx_init(&moea_table_mutex, "pmap table", NULL, MTX_DEF |
858 	    MTX_RECURSE);
859 	mtx_init(&moea_vsid_mutex, "VSID table", NULL, MTX_DEF);
860 
861 	mtx_init(&tlbie_mtx, "tlbie", NULL, MTX_SPIN);
862 
863 	/*
864 	 * Initialise the unmanaged pvo pool.
865 	 */
866 	moea_bpvo_pool = (struct pvo_entry *)moea_bootstrap_alloc(
867 		BPVO_POOL_SIZE*sizeof(struct pvo_entry), 0);
868 	moea_bpvo_pool_index = 0;
869 
870 	/*
871 	 * Make sure kernel vsid is allocated as well as VSID 0.
872 	 */
873 	moea_vsid_bitmap[(KERNEL_VSIDBITS & (NPMAPS - 1)) / VSID_NBPW]
874 		|= 1 << (KERNEL_VSIDBITS % VSID_NBPW);
875 	moea_vsid_bitmap[0] |= 1;
876 
877 	/*
878 	 * Initialize the kernel pmap (which is statically allocated).
879 	 */
880 	PMAP_LOCK_INIT(kernel_pmap);
881 	for (i = 0; i < 16; i++)
882 		kernel_pmap->pm_sr[i] = EMPTY_SEGMENT + i;
883 	CPU_FILL(&kernel_pmap->pm_active);
884 	RB_INIT(&kernel_pmap->pmap_pvo);
885 
886  	/*
887 	 * Initialize the global pv list lock.
888 	 */
889 	rw_init(&pvh_global_lock, "pmap pv global");
890 
891 	/*
892 	 * Set up the Open Firmware mappings
893 	 */
894 	chosen = OF_finddevice("/chosen");
895 	if (chosen != -1 && OF_getprop(chosen, "mmu", &mmui, 4) != -1 &&
896 	    (mmu = OF_instance_to_package(mmui)) != -1 &&
897 	    (sz = OF_getproplen(mmu, "translations")) != -1) {
898 		translations = NULL;
899 		for (i = 0; phys_avail[i] != 0; i += 2) {
900 			if (phys_avail[i + 1] >= sz) {
901 				translations = (struct ofw_map *)phys_avail[i];
902 				break;
903 			}
904 		}
905 		if (translations == NULL)
906 			panic("moea_bootstrap: no space to copy translations");
907 		bzero(translations, sz);
908 		if (OF_getprop(mmu, "translations", translations, sz) == -1)
909 			panic("moea_bootstrap: can't get ofw translations");
910 		CTR0(KTR_PMAP, "moea_bootstrap: translations");
911 		sz /= sizeof(*translations);
912 		qsort(translations, sz, sizeof (*translations), om_cmp);
913 		for (i = 0; i < sz; i++) {
914 			CTR3(KTR_PMAP, "translation: pa=%#x va=%#x len=%#x",
915 			    translations[i].om_pa, translations[i].om_va,
916 			    translations[i].om_len);
917 
918 			/*
919 			 * If the mapping is 1:1, let the RAM and device
920 			 * on-demand BAT tables take care of the translation.
921 			 *
922 			 * However, always enter mappings for segment 16,
923 			 * which is mixed-protection and therefore not
924 			 * compatible with a BAT entry.
925 			 */
926 			if ((translations[i].om_va >> ADDR_SR_SHFT) != 0xf &&
927 				translations[i].om_va == translations[i].om_pa)
928 					continue;
929 
930 			/* Enter the pages */
931 			for (off = 0; off < translations[i].om_len;
932 			    off += PAGE_SIZE)
933 				moea_kenter_attr(translations[i].om_va + off,
934 				    translations[i].om_pa + off,
935 				    moea_bootstrap_convert_wimg(translations[i].om_mode));
936 		}
937 	}
938 
939 	/*
940 	 * Calculate the last available physical address.
941 	 */
942 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
943 		;
944 	Maxmem = powerpc_btop(phys_avail[i + 1]);
945 
946 	moea_cpu_bootstrap(0);
947 	mtmsr(mfmsr() | PSL_DR | PSL_IR);
948 	pmap_bootstrapped++;
949 
950 	/*
951 	 * Set the start and end of kva.
952 	 */
953 	virtual_avail = VM_MIN_KERNEL_ADDRESS;
954 	virtual_end = VM_MAX_SAFE_KERNEL_ADDRESS;
955 
956 	/*
957 	 * Allocate a kernel stack with a guard page for thread0 and map it
958 	 * into the kernel page map.
959 	 */
960 	pa = moea_bootstrap_alloc(kstack_pages * PAGE_SIZE, PAGE_SIZE);
961 	va = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
962 	virtual_avail = va + kstack_pages * PAGE_SIZE;
963 	CTR2(KTR_PMAP, "moea_bootstrap: kstack0 at %#x (%#x)", pa, va);
964 	thread0.td_kstack = va;
965 	thread0.td_kstack_pages = kstack_pages;
966 	for (i = 0; i < kstack_pages; i++) {
967 		moea_kenter(va, pa);
968 		pa += PAGE_SIZE;
969 		va += PAGE_SIZE;
970 	}
971 
972 	/*
973 	 * Allocate virtual address space for the message buffer.
974 	 */
975 	pa = msgbuf_phys = moea_bootstrap_alloc(msgbufsize, PAGE_SIZE);
976 	msgbufp = (struct msgbuf *)virtual_avail;
977 	va = virtual_avail;
978 	virtual_avail += round_page(msgbufsize);
979 	while (va < virtual_avail) {
980 		moea_kenter(va, pa);
981 		pa += PAGE_SIZE;
982 		va += PAGE_SIZE;
983 	}
984 
985 	/*
986 	 * Allocate virtual address space for the dynamic percpu area.
987 	 */
988 	pa = moea_bootstrap_alloc(DPCPU_SIZE, PAGE_SIZE);
989 	dpcpu = (void *)virtual_avail;
990 	va = virtual_avail;
991 	virtual_avail += DPCPU_SIZE;
992 	while (va < virtual_avail) {
993 		moea_kenter(va, pa);
994 		pa += PAGE_SIZE;
995 		va += PAGE_SIZE;
996 	}
997 	dpcpu_init(dpcpu, 0);
998 }
999 
1000 /*
1001  * Activate a user pmap.  The pmap must be activated before it's address
1002  * space can be accessed in any way.
1003  */
1004 void
1005 moea_activate(struct thread *td)
1006 {
1007 	pmap_t	pm, pmr;
1008 
1009 	/*
1010 	 * Load all the data we need up front to encourage the compiler to
1011 	 * not issue any loads while we have interrupts disabled below.
1012 	 */
1013 	pm = &td->td_proc->p_vmspace->vm_pmap;
1014 	pmr = pm->pmap_phys;
1015 
1016 	CPU_SET(PCPU_GET(cpuid), &pm->pm_active);
1017 	PCPU_SET(curpmap, pmr);
1018 
1019 	mtsrin(USER_SR << ADDR_SR_SHFT, td->td_pcb->pcb_cpu.aim.usr_vsid);
1020 }
1021 
1022 void
1023 moea_deactivate(struct thread *td)
1024 {
1025 	pmap_t	pm;
1026 
1027 	pm = &td->td_proc->p_vmspace->vm_pmap;
1028 	CPU_CLR(PCPU_GET(cpuid), &pm->pm_active);
1029 	PCPU_SET(curpmap, NULL);
1030 }
1031 
1032 void
1033 moea_unwire(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1034 {
1035 	struct	pvo_entry key, *pvo;
1036 
1037 	PMAP_LOCK(pm);
1038 	key.pvo_vaddr = sva;
1039 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1040 	    pvo != NULL && PVO_VADDR(pvo) < eva;
1041 	    pvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo)) {
1042 		if ((pvo->pvo_vaddr & PVO_WIRED) == 0)
1043 			panic("moea_unwire: pvo %p is missing PVO_WIRED", pvo);
1044 		pvo->pvo_vaddr &= ~PVO_WIRED;
1045 		pm->pm_stats.wired_count--;
1046 	}
1047 	PMAP_UNLOCK(pm);
1048 }
1049 
1050 void
1051 moea_copy_page(vm_page_t msrc, vm_page_t mdst)
1052 {
1053 	vm_offset_t	dst;
1054 	vm_offset_t	src;
1055 
1056 	dst = VM_PAGE_TO_PHYS(mdst);
1057 	src = VM_PAGE_TO_PHYS(msrc);
1058 
1059 	bcopy((void *)src, (void *)dst, PAGE_SIZE);
1060 }
1061 
1062 void
1063 moea_copy_pages(vm_page_t *ma, vm_offset_t a_offset,
1064     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
1065 {
1066 	void *a_cp, *b_cp;
1067 	vm_offset_t a_pg_offset, b_pg_offset;
1068 	int cnt;
1069 
1070 	while (xfersize > 0) {
1071 		a_pg_offset = a_offset & PAGE_MASK;
1072 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
1073 		a_cp = (char *)VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]) +
1074 		    a_pg_offset;
1075 		b_pg_offset = b_offset & PAGE_MASK;
1076 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
1077 		b_cp = (char *)VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]) +
1078 		    b_pg_offset;
1079 		bcopy(a_cp, b_cp, cnt);
1080 		a_offset += cnt;
1081 		b_offset += cnt;
1082 		xfersize -= cnt;
1083 	}
1084 }
1085 
1086 /*
1087  * Zero a page of physical memory by temporarily mapping it into the tlb.
1088  */
1089 void
1090 moea_zero_page(vm_page_t m)
1091 {
1092 	vm_offset_t off, pa = VM_PAGE_TO_PHYS(m);
1093 
1094 	for (off = 0; off < PAGE_SIZE; off += cacheline_size)
1095 		__asm __volatile("dcbz 0,%0" :: "r"(pa + off));
1096 }
1097 
1098 void
1099 moea_zero_page_area(vm_page_t m, int off, int size)
1100 {
1101 	vm_offset_t pa = VM_PAGE_TO_PHYS(m);
1102 	void *va = (void *)(pa + off);
1103 
1104 	bzero(va, size);
1105 }
1106 
1107 vm_offset_t
1108 moea_quick_enter_page(vm_page_t m)
1109 {
1110 
1111 	return (VM_PAGE_TO_PHYS(m));
1112 }
1113 
1114 void
1115 moea_quick_remove_page(vm_offset_t addr)
1116 {
1117 }
1118 
1119 bool
1120 moea_page_is_mapped(vm_page_t m)
1121 {
1122 	return (!LIST_EMPTY(&(m)->md.mdpg_pvoh));
1123 }
1124 
1125 bool
1126 moea_ps_enabled(pmap_t pmap __unused)
1127 {
1128 	return (false);
1129 }
1130 
1131 /*
1132  * Map the given physical page at the specified virtual address in the
1133  * target pmap with the protection requested.  If specified the page
1134  * will be wired down.
1135  */
1136 int
1137 moea_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1138     u_int flags, int8_t psind)
1139 {
1140 	int error;
1141 
1142 	for (;;) {
1143 		rw_wlock(&pvh_global_lock);
1144 		PMAP_LOCK(pmap);
1145 		error = moea_enter_locked(pmap, va, m, prot, flags, psind);
1146 		rw_wunlock(&pvh_global_lock);
1147 		PMAP_UNLOCK(pmap);
1148 		if (error != ENOMEM)
1149 			return (KERN_SUCCESS);
1150 		if ((flags & PMAP_ENTER_NOSLEEP) != 0)
1151 			return (KERN_RESOURCE_SHORTAGE);
1152 		VM_OBJECT_ASSERT_UNLOCKED(m->object);
1153 		vm_wait(NULL);
1154 	}
1155 }
1156 
1157 /*
1158  * Map the given physical page at the specified virtual address in the
1159  * target pmap with the protection requested.  If specified the page
1160  * will be wired down.
1161  *
1162  * The global pvh and pmap must be locked.
1163  */
1164 static int
1165 moea_enter_locked(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1166     u_int flags, int8_t psind __unused)
1167 {
1168 	struct		pvo_head *pvo_head;
1169 	uma_zone_t	zone;
1170 	u_int		pte_lo, pvo_flags;
1171 	int		error;
1172 
1173 	if (pmap_bootstrapped)
1174 		rw_assert(&pvh_global_lock, RA_WLOCKED);
1175 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1176 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1177 		if ((flags & PMAP_ENTER_QUICK_LOCKED) == 0)
1178 			VM_PAGE_OBJECT_BUSY_ASSERT(m);
1179 		else
1180 			VM_OBJECT_ASSERT_LOCKED(m->object);
1181 	}
1182 
1183 	if ((m->oflags & VPO_UNMANAGED) != 0 || !moea_initialized) {
1184 		pvo_head = &moea_pvo_kunmanaged;
1185 		zone = moea_upvo_zone;
1186 		pvo_flags = 0;
1187 	} else {
1188 		pvo_head = vm_page_to_pvoh(m);
1189 		zone = moea_mpvo_zone;
1190 		pvo_flags = PVO_MANAGED;
1191 	}
1192 
1193 	pte_lo = moea_calc_wimg(VM_PAGE_TO_PHYS(m), pmap_page_get_memattr(m));
1194 
1195 	if (prot & VM_PROT_WRITE) {
1196 		pte_lo |= PTE_BW;
1197 		if (pmap_bootstrapped &&
1198 		    (m->oflags & VPO_UNMANAGED) == 0)
1199 			vm_page_aflag_set(m, PGA_WRITEABLE);
1200 	} else
1201 		pte_lo |= PTE_BR;
1202 
1203 	if ((flags & PMAP_ENTER_WIRED) != 0)
1204 		pvo_flags |= PVO_WIRED;
1205 
1206 	error = moea_pvo_enter(pmap, zone, pvo_head, va, VM_PAGE_TO_PHYS(m),
1207 	    pte_lo, pvo_flags);
1208 
1209 	/*
1210 	 * Flush the real page from the instruction cache. This has be done
1211 	 * for all user mappings to prevent information leakage via the
1212 	 * instruction cache. moea_pvo_enter() returns ENOENT for the first
1213 	 * mapping for a page.
1214 	 */
1215 	if (pmap != kernel_pmap && error == ENOENT &&
1216 	    (pte_lo & (PTE_I | PTE_G)) == 0)
1217 		moea_syncicache(VM_PAGE_TO_PHYS(m), PAGE_SIZE);
1218 
1219 	return (error);
1220 }
1221 
1222 /*
1223  * Maps a sequence of resident pages belonging to the same object.
1224  * The sequence begins with the given page m_start.  This page is
1225  * mapped at the given virtual address start.  Each subsequent page is
1226  * mapped at a virtual address that is offset from start by the same
1227  * amount as the page is offset from m_start within the object.  The
1228  * last page in the sequence is the page with the largest offset from
1229  * m_start that can be mapped at a virtual address less than the given
1230  * virtual address end.  Not every virtual page between start and end
1231  * is mapped; only those for which a resident page exists with the
1232  * corresponding offset from m_start are mapped.
1233  */
1234 void
1235 moea_enter_object(pmap_t pm, vm_offset_t start, vm_offset_t end,
1236     vm_page_t m_start, vm_prot_t prot)
1237 {
1238 	vm_page_t m;
1239 	vm_pindex_t diff, psize;
1240 
1241 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1242 
1243 	psize = atop(end - start);
1244 	m = m_start;
1245 	rw_wlock(&pvh_global_lock);
1246 	PMAP_LOCK(pm);
1247 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1248 		moea_enter_locked(pm, start + ptoa(diff), m, prot &
1249 		    (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_QUICK_LOCKED,
1250 		    0);
1251 		m = TAILQ_NEXT(m, listq);
1252 	}
1253 	rw_wunlock(&pvh_global_lock);
1254 	PMAP_UNLOCK(pm);
1255 }
1256 
1257 void
1258 moea_enter_quick(pmap_t pm, vm_offset_t va, vm_page_t m,
1259     vm_prot_t prot)
1260 {
1261 
1262 	rw_wlock(&pvh_global_lock);
1263 	PMAP_LOCK(pm);
1264 	moea_enter_locked(pm, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1265 	    PMAP_ENTER_QUICK_LOCKED, 0);
1266 	rw_wunlock(&pvh_global_lock);
1267 	PMAP_UNLOCK(pm);
1268 }
1269 
1270 vm_paddr_t
1271 moea_extract(pmap_t pm, vm_offset_t va)
1272 {
1273 	struct	pvo_entry *pvo;
1274 	vm_paddr_t pa;
1275 
1276 	PMAP_LOCK(pm);
1277 	pvo = moea_pvo_find_va(pm, va & ~ADDR_POFF, NULL);
1278 	if (pvo == NULL)
1279 		pa = 0;
1280 	else
1281 		pa = PVO_PADDR(pvo) | (va & ADDR_POFF);
1282 	PMAP_UNLOCK(pm);
1283 	return (pa);
1284 }
1285 
1286 /*
1287  * Atomically extract and hold the physical page with the given
1288  * pmap and virtual address pair if that mapping permits the given
1289  * protection.
1290  */
1291 vm_page_t
1292 moea_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1293 {
1294 	struct	pvo_entry *pvo;
1295 	vm_page_t m;
1296 
1297 	m = NULL;
1298 	PMAP_LOCK(pmap);
1299 	pvo = moea_pvo_find_va(pmap, va & ~ADDR_POFF, NULL);
1300 	if (pvo != NULL && (pvo->pvo_pte.pte.pte_hi & PTE_VALID) &&
1301 	    ((pvo->pvo_pte.pte.pte_lo & PTE_PP) == PTE_RW ||
1302 	     (prot & VM_PROT_WRITE) == 0)) {
1303 		m = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
1304 		if (!vm_page_wire_mapped(m))
1305 			m = NULL;
1306 	}
1307 	PMAP_UNLOCK(pmap);
1308 	return (m);
1309 }
1310 
1311 void
1312 moea_init(void)
1313 {
1314 
1315 	moea_upvo_zone = uma_zcreate("UPVO entry", sizeof (struct pvo_entry),
1316 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1317 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1318 	moea_mpvo_zone = uma_zcreate("MPVO entry", sizeof(struct pvo_entry),
1319 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1320 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1321 	moea_initialized = true;
1322 }
1323 
1324 bool
1325 moea_is_referenced(vm_page_t m)
1326 {
1327 	bool rv;
1328 
1329 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1330 	    ("moea_is_referenced: page %p is not managed", m));
1331 	rw_wlock(&pvh_global_lock);
1332 	rv = moea_query_bit(m, PTE_REF);
1333 	rw_wunlock(&pvh_global_lock);
1334 	return (rv);
1335 }
1336 
1337 bool
1338 moea_is_modified(vm_page_t m)
1339 {
1340 	bool rv;
1341 
1342 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1343 	    ("moea_is_modified: page %p is not managed", m));
1344 
1345 	/*
1346 	 * If the page is not busied then this check is racy.
1347 	 */
1348 	if (!pmap_page_is_write_mapped(m))
1349 		return (false);
1350 
1351 	rw_wlock(&pvh_global_lock);
1352 	rv = moea_query_bit(m, PTE_CHG);
1353 	rw_wunlock(&pvh_global_lock);
1354 	return (rv);
1355 }
1356 
1357 bool
1358 moea_is_prefaultable(pmap_t pmap, vm_offset_t va)
1359 {
1360 	struct pvo_entry *pvo;
1361 	bool rv;
1362 
1363 	PMAP_LOCK(pmap);
1364 	pvo = moea_pvo_find_va(pmap, va & ~ADDR_POFF, NULL);
1365 	rv = pvo == NULL || (pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0;
1366 	PMAP_UNLOCK(pmap);
1367 	return (rv);
1368 }
1369 
1370 void
1371 moea_clear_modify(vm_page_t m)
1372 {
1373 
1374 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1375 	    ("moea_clear_modify: page %p is not managed", m));
1376 	vm_page_assert_busied(m);
1377 
1378 	if (!pmap_page_is_write_mapped(m))
1379 		return;
1380 	rw_wlock(&pvh_global_lock);
1381 	moea_clear_bit(m, PTE_CHG);
1382 	rw_wunlock(&pvh_global_lock);
1383 }
1384 
1385 /*
1386  * Clear the write and modified bits in each of the given page's mappings.
1387  */
1388 void
1389 moea_remove_write(vm_page_t m)
1390 {
1391 	struct	pvo_entry *pvo;
1392 	struct	pte *pt;
1393 	pmap_t	pmap;
1394 	u_int	lo;
1395 
1396 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1397 	    ("moea_remove_write: page %p is not managed", m));
1398 	vm_page_assert_busied(m);
1399 
1400 	if (!pmap_page_is_write_mapped(m))
1401 		return;
1402 	rw_wlock(&pvh_global_lock);
1403 	lo = moea_attr_fetch(m);
1404 	powerpc_sync();
1405 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1406 		pmap = pvo->pvo_pmap;
1407 		PMAP_LOCK(pmap);
1408 		if ((pvo->pvo_pte.pte.pte_lo & PTE_PP) != PTE_BR) {
1409 			pt = moea_pvo_to_pte(pvo, -1);
1410 			pvo->pvo_pte.pte.pte_lo &= ~PTE_PP;
1411 			pvo->pvo_pte.pte.pte_lo |= PTE_BR;
1412 			if (pt != NULL) {
1413 				moea_pte_synch(pt, &pvo->pvo_pte.pte);
1414 				lo |= pvo->pvo_pte.pte.pte_lo;
1415 				pvo->pvo_pte.pte.pte_lo &= ~PTE_CHG;
1416 				moea_pte_change(pt, &pvo->pvo_pte.pte,
1417 				    pvo->pvo_vaddr);
1418 				mtx_unlock(&moea_table_mutex);
1419 			}
1420 		}
1421 		PMAP_UNLOCK(pmap);
1422 	}
1423 	if ((lo & PTE_CHG) != 0) {
1424 		moea_attr_clear(m, PTE_CHG);
1425 		vm_page_dirty(m);
1426 	}
1427 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1428 	rw_wunlock(&pvh_global_lock);
1429 }
1430 
1431 /*
1432  *	moea_ts_referenced:
1433  *
1434  *	Return a count of reference bits for a page, clearing those bits.
1435  *	It is not necessary for every reference bit to be cleared, but it
1436  *	is necessary that 0 only be returned when there are truly no
1437  *	reference bits set.
1438  *
1439  *	XXX: The exact number of bits to check and clear is a matter that
1440  *	should be tested and standardized at some point in the future for
1441  *	optimal aging of shared pages.
1442  */
1443 int
1444 moea_ts_referenced(vm_page_t m)
1445 {
1446 	int count;
1447 
1448 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1449 	    ("moea_ts_referenced: page %p is not managed", m));
1450 	rw_wlock(&pvh_global_lock);
1451 	count = moea_clear_bit(m, PTE_REF);
1452 	rw_wunlock(&pvh_global_lock);
1453 	return (count);
1454 }
1455 
1456 /*
1457  * Modify the WIMG settings of all mappings for a page.
1458  */
1459 void
1460 moea_page_set_memattr(vm_page_t m, vm_memattr_t ma)
1461 {
1462 	struct	pvo_entry *pvo;
1463 	struct	pvo_head *pvo_head;
1464 	struct	pte *pt;
1465 	pmap_t	pmap;
1466 	u_int	lo;
1467 
1468 	if ((m->oflags & VPO_UNMANAGED) != 0) {
1469 		m->md.mdpg_cache_attrs = ma;
1470 		return;
1471 	}
1472 
1473 	rw_wlock(&pvh_global_lock);
1474 	pvo_head = vm_page_to_pvoh(m);
1475 	lo = moea_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
1476 
1477 	LIST_FOREACH(pvo, pvo_head, pvo_vlink) {
1478 		pmap = pvo->pvo_pmap;
1479 		PMAP_LOCK(pmap);
1480 		pt = moea_pvo_to_pte(pvo, -1);
1481 		pvo->pvo_pte.pte.pte_lo &= ~PTE_WIMG;
1482 		pvo->pvo_pte.pte.pte_lo |= lo;
1483 		if (pt != NULL) {
1484 			moea_pte_change(pt, &pvo->pvo_pte.pte,
1485 			    pvo->pvo_vaddr);
1486 			if (pvo->pvo_pmap == kernel_pmap)
1487 				isync();
1488 		}
1489 		mtx_unlock(&moea_table_mutex);
1490 		PMAP_UNLOCK(pmap);
1491 	}
1492 	m->md.mdpg_cache_attrs = ma;
1493 	rw_wunlock(&pvh_global_lock);
1494 }
1495 
1496 /*
1497  * Map a wired page into kernel virtual address space.
1498  */
1499 void
1500 moea_kenter(vm_offset_t va, vm_paddr_t pa)
1501 {
1502 
1503 	moea_kenter_attr(va, pa, VM_MEMATTR_DEFAULT);
1504 }
1505 
1506 void
1507 moea_kenter_attr(vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1508 {
1509 	u_int		pte_lo;
1510 	int		error;
1511 
1512 #if 0
1513 	if (va < VM_MIN_KERNEL_ADDRESS)
1514 		panic("moea_kenter: attempt to enter non-kernel address %#x",
1515 		    va);
1516 #endif
1517 
1518 	pte_lo = moea_calc_wimg(pa, ma);
1519 
1520 	PMAP_LOCK(kernel_pmap);
1521 	error = moea_pvo_enter(kernel_pmap, moea_upvo_zone,
1522 	    &moea_pvo_kunmanaged, va, pa, pte_lo, PVO_WIRED);
1523 
1524 	if (error != 0 && error != ENOENT)
1525 		panic("moea_kenter: failed to enter va %#x pa %#x: %d", va,
1526 		    pa, error);
1527 
1528 	PMAP_UNLOCK(kernel_pmap);
1529 }
1530 
1531 /*
1532  * Extract the physical page address associated with the given kernel virtual
1533  * address.
1534  */
1535 vm_paddr_t
1536 moea_kextract(vm_offset_t va)
1537 {
1538 	struct		pvo_entry *pvo;
1539 	vm_paddr_t pa;
1540 
1541 	/*
1542 	 * Allow direct mappings on 32-bit OEA
1543 	 */
1544 	if (va < VM_MIN_KERNEL_ADDRESS) {
1545 		return (va);
1546 	}
1547 
1548 	PMAP_LOCK(kernel_pmap);
1549 	pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF, NULL);
1550 	KASSERT(pvo != NULL, ("moea_kextract: no addr found"));
1551 	pa = PVO_PADDR(pvo) | (va & ADDR_POFF);
1552 	PMAP_UNLOCK(kernel_pmap);
1553 	return (pa);
1554 }
1555 
1556 /*
1557  * Remove a wired page from kernel virtual address space.
1558  */
1559 void
1560 moea_kremove(vm_offset_t va)
1561 {
1562 
1563 	moea_remove(kernel_pmap, va, va + PAGE_SIZE);
1564 }
1565 
1566 /*
1567  * Provide a kernel pointer corresponding to a given userland pointer.
1568  * The returned pointer is valid until the next time this function is
1569  * called in this thread. This is used internally in copyin/copyout.
1570  */
1571 int
1572 moea_map_user_ptr(pmap_t pm, volatile const void *uaddr,
1573     void **kaddr, size_t ulen, size_t *klen)
1574 {
1575 	size_t l;
1576 	register_t vsid;
1577 
1578 	*kaddr = (char *)USER_ADDR + ((uintptr_t)uaddr & ~SEGMENT_MASK);
1579 	l = ((char *)USER_ADDR + SEGMENT_LENGTH) - (char *)(*kaddr);
1580 	if (l > ulen)
1581 		l = ulen;
1582 	if (klen)
1583 		*klen = l;
1584 	else if (l != ulen)
1585 		return (EFAULT);
1586 
1587 	vsid = va_to_vsid(pm, (vm_offset_t)uaddr);
1588 
1589 	/* Mark segment no-execute */
1590 	vsid |= SR_N;
1591 
1592 	/* If we have already set this VSID, we can just return */
1593 	if (curthread->td_pcb->pcb_cpu.aim.usr_vsid == vsid)
1594 		return (0);
1595 
1596 	__asm __volatile("isync");
1597 	curthread->td_pcb->pcb_cpu.aim.usr_segm =
1598 	    (uintptr_t)uaddr >> ADDR_SR_SHFT;
1599 	curthread->td_pcb->pcb_cpu.aim.usr_vsid = vsid;
1600 	__asm __volatile("mtsr %0,%1; isync" :: "n"(USER_SR), "r"(vsid));
1601 
1602 	return (0);
1603 }
1604 
1605 /*
1606  * Figure out where a given kernel pointer (usually in a fault) points
1607  * to from the VM's perspective, potentially remapping into userland's
1608  * address space.
1609  */
1610 static int
1611 moea_decode_kernel_ptr(vm_offset_t addr, int *is_user,
1612     vm_offset_t *decoded_addr)
1613 {
1614 	vm_offset_t user_sr;
1615 
1616 	if ((addr >> ADDR_SR_SHFT) == (USER_ADDR >> ADDR_SR_SHFT)) {
1617 		user_sr = curthread->td_pcb->pcb_cpu.aim.usr_segm;
1618 		addr &= ADDR_PIDX | ADDR_POFF;
1619 		addr |= user_sr << ADDR_SR_SHFT;
1620 		*decoded_addr = addr;
1621 		*is_user = 1;
1622 	} else {
1623 		*decoded_addr = addr;
1624 		*is_user = 0;
1625 	}
1626 
1627 	return (0);
1628 }
1629 
1630 /*
1631  * Map a range of physical addresses into kernel virtual address space.
1632  *
1633  * The value passed in *virt is a suggested virtual address for the mapping.
1634  * Architectures which can support a direct-mapped physical to virtual region
1635  * can return the appropriate address within that region, leaving '*virt'
1636  * unchanged.  We cannot and therefore do not; *virt is updated with the
1637  * first usable address after the mapped region.
1638  */
1639 vm_offset_t
1640 moea_map(vm_offset_t *virt, vm_paddr_t pa_start,
1641     vm_paddr_t pa_end, int prot)
1642 {
1643 	vm_offset_t	sva, va;
1644 
1645 	sva = *virt;
1646 	va = sva;
1647 	for (; pa_start < pa_end; pa_start += PAGE_SIZE, va += PAGE_SIZE)
1648 		moea_kenter(va, pa_start);
1649 	*virt = va;
1650 	return (sva);
1651 }
1652 
1653 /*
1654  * Returns true if the pmap's pv is one of the first
1655  * 16 pvs linked to from this page.  This count may
1656  * be changed upwards or downwards in the future; it
1657  * is only necessary that true be returned for a small
1658  * subset of pmaps for proper page aging.
1659  */
1660 bool
1661 moea_page_exists_quick(pmap_t pmap, vm_page_t m)
1662 {
1663         int loops;
1664 	struct pvo_entry *pvo;
1665 	bool rv;
1666 
1667 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1668 	    ("moea_page_exists_quick: page %p is not managed", m));
1669 	loops = 0;
1670 	rv = false;
1671 	rw_wlock(&pvh_global_lock);
1672 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1673 		if (pvo->pvo_pmap == pmap) {
1674 			rv = true;
1675 			break;
1676 		}
1677 		if (++loops >= 16)
1678 			break;
1679 	}
1680 	rw_wunlock(&pvh_global_lock);
1681 	return (rv);
1682 }
1683 
1684 void
1685 moea_page_init(vm_page_t m)
1686 {
1687 
1688 	m->md.mdpg_attrs = 0;
1689 	m->md.mdpg_cache_attrs = VM_MEMATTR_DEFAULT;
1690 	LIST_INIT(&m->md.mdpg_pvoh);
1691 }
1692 
1693 /*
1694  * Return the number of managed mappings to the given physical page
1695  * that are wired.
1696  */
1697 int
1698 moea_page_wired_mappings(vm_page_t m)
1699 {
1700 	struct pvo_entry *pvo;
1701 	int count;
1702 
1703 	count = 0;
1704 	if ((m->oflags & VPO_UNMANAGED) != 0)
1705 		return (count);
1706 	rw_wlock(&pvh_global_lock);
1707 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
1708 		if ((pvo->pvo_vaddr & PVO_WIRED) != 0)
1709 			count++;
1710 	rw_wunlock(&pvh_global_lock);
1711 	return (count);
1712 }
1713 
1714 static u_int	moea_vsidcontext;
1715 
1716 int
1717 moea_pinit(pmap_t pmap)
1718 {
1719 	int	i, mask;
1720 	u_int	entropy;
1721 
1722 	RB_INIT(&pmap->pmap_pvo);
1723 
1724 	entropy = 0;
1725 	__asm __volatile("mftb %0" : "=r"(entropy));
1726 
1727 	if ((pmap->pmap_phys = (pmap_t)moea_kextract((vm_offset_t)pmap))
1728 	    == NULL) {
1729 		pmap->pmap_phys = pmap;
1730 	}
1731 
1732 	mtx_lock(&moea_vsid_mutex);
1733 	/*
1734 	 * Allocate some segment registers for this pmap.
1735 	 */
1736 	for (i = 0; i < NPMAPS; i += VSID_NBPW) {
1737 		u_int	hash, n;
1738 
1739 		/*
1740 		 * Create a new value by multiplying by a prime and adding in
1741 		 * entropy from the timebase register.  This is to make the
1742 		 * VSID more random so that the PT hash function collides
1743 		 * less often.  (Note that the prime casues gcc to do shifts
1744 		 * instead of a multiply.)
1745 		 */
1746 		moea_vsidcontext = (moea_vsidcontext * 0x1105) + entropy;
1747 		hash = moea_vsidcontext & (NPMAPS - 1);
1748 		if (hash == 0)		/* 0 is special, avoid it */
1749 			continue;
1750 		n = hash >> 5;
1751 		mask = 1 << (hash & (VSID_NBPW - 1));
1752 		hash = (moea_vsidcontext & 0xfffff);
1753 		if (moea_vsid_bitmap[n] & mask) {	/* collision? */
1754 			/* anything free in this bucket? */
1755 			if (moea_vsid_bitmap[n] == 0xffffffff) {
1756 				entropy = (moea_vsidcontext >> 20);
1757 				continue;
1758 			}
1759 			i = ffs(~moea_vsid_bitmap[n]) - 1;
1760 			mask = 1 << i;
1761 			hash &= rounddown2(0xfffff, VSID_NBPW);
1762 			hash |= i;
1763 		}
1764 		KASSERT(!(moea_vsid_bitmap[n] & mask),
1765 		    ("Allocating in-use VSID group %#x\n", hash));
1766 		moea_vsid_bitmap[n] |= mask;
1767 		for (i = 0; i < 16; i++)
1768 			pmap->pm_sr[i] = VSID_MAKE(i, hash);
1769 		mtx_unlock(&moea_vsid_mutex);
1770 		return (1);
1771 	}
1772 
1773 	mtx_unlock(&moea_vsid_mutex);
1774 	panic("moea_pinit: out of segments");
1775 }
1776 
1777 /*
1778  * Initialize the pmap associated with process 0.
1779  */
1780 void
1781 moea_pinit0(pmap_t pm)
1782 {
1783 
1784 	PMAP_LOCK_INIT(pm);
1785 	moea_pinit(pm);
1786 	bzero(&pm->pm_stats, sizeof(pm->pm_stats));
1787 }
1788 
1789 /*
1790  * Set the physical protection on the specified range of this map as requested.
1791  */
1792 void
1793 moea_protect(pmap_t pm, vm_offset_t sva, vm_offset_t eva,
1794     vm_prot_t prot)
1795 {
1796 	struct	pvo_entry *pvo, *tpvo, key;
1797 	struct	pte *pt;
1798 
1799 	KASSERT(pm == &curproc->p_vmspace->vm_pmap || pm == kernel_pmap,
1800 	    ("moea_protect: non current pmap"));
1801 
1802 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1803 		moea_remove(pm, sva, eva);
1804 		return;
1805 	}
1806 
1807 	rw_wlock(&pvh_global_lock);
1808 	PMAP_LOCK(pm);
1809 	key.pvo_vaddr = sva;
1810 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1811 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
1812 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
1813 
1814 		/*
1815 		 * Grab the PTE pointer before we diddle with the cached PTE
1816 		 * copy.
1817 		 */
1818 		pt = moea_pvo_to_pte(pvo, -1);
1819 		/*
1820 		 * Change the protection of the page.
1821 		 */
1822 		pvo->pvo_pte.pte.pte_lo &= ~PTE_PP;
1823 		pvo->pvo_pte.pte.pte_lo |= PTE_BR;
1824 
1825 		/*
1826 		 * If the PVO is in the page table, update that pte as well.
1827 		 */
1828 		if (pt != NULL) {
1829 			moea_pte_change(pt, &pvo->pvo_pte.pte, pvo->pvo_vaddr);
1830 			mtx_unlock(&moea_table_mutex);
1831 		}
1832 	}
1833 	rw_wunlock(&pvh_global_lock);
1834 	PMAP_UNLOCK(pm);
1835 }
1836 
1837 /*
1838  * Map a list of wired pages into kernel virtual address space.  This is
1839  * intended for temporary mappings which do not need page modification or
1840  * references recorded.  Existing mappings in the region are overwritten.
1841  */
1842 void
1843 moea_qenter(vm_offset_t sva, vm_page_t *m, int count)
1844 {
1845 	vm_offset_t va;
1846 
1847 	va = sva;
1848 	while (count-- > 0) {
1849 		moea_kenter(va, VM_PAGE_TO_PHYS(*m));
1850 		va += PAGE_SIZE;
1851 		m++;
1852 	}
1853 }
1854 
1855 /*
1856  * Remove page mappings from kernel virtual address space.  Intended for
1857  * temporary mappings entered by moea_qenter.
1858  */
1859 void
1860 moea_qremove(vm_offset_t sva, int count)
1861 {
1862 	vm_offset_t va;
1863 
1864 	va = sva;
1865 	while (count-- > 0) {
1866 		moea_kremove(va);
1867 		va += PAGE_SIZE;
1868 	}
1869 }
1870 
1871 void
1872 moea_release(pmap_t pmap)
1873 {
1874         int idx, mask;
1875 
1876 	/*
1877 	 * Free segment register's VSID
1878 	 */
1879         if (pmap->pm_sr[0] == 0)
1880                 panic("moea_release");
1881 
1882 	mtx_lock(&moea_vsid_mutex);
1883         idx = VSID_TO_HASH(pmap->pm_sr[0]) & (NPMAPS-1);
1884         mask = 1 << (idx % VSID_NBPW);
1885         idx /= VSID_NBPW;
1886         moea_vsid_bitmap[idx] &= ~mask;
1887 	mtx_unlock(&moea_vsid_mutex);
1888 }
1889 
1890 /*
1891  * Remove the given range of addresses from the specified map.
1892  */
1893 void
1894 moea_remove(pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1895 {
1896 	struct	pvo_entry *pvo, *tpvo, key;
1897 
1898 	rw_wlock(&pvh_global_lock);
1899 	PMAP_LOCK(pm);
1900 	key.pvo_vaddr = sva;
1901 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1902 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
1903 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
1904 		moea_pvo_remove(pvo, -1);
1905 	}
1906 	PMAP_UNLOCK(pm);
1907 	rw_wunlock(&pvh_global_lock);
1908 }
1909 
1910 /*
1911  * Remove physical page from all pmaps in which it resides. moea_pvo_remove()
1912  * will reflect changes in pte's back to the vm_page.
1913  */
1914 void
1915 moea_remove_all(vm_page_t m)
1916 {
1917 	struct  pvo_head *pvo_head;
1918 	struct	pvo_entry *pvo, *next_pvo;
1919 	pmap_t	pmap;
1920 
1921 	rw_wlock(&pvh_global_lock);
1922 	pvo_head = vm_page_to_pvoh(m);
1923 	for (pvo = LIST_FIRST(pvo_head); pvo != NULL; pvo = next_pvo) {
1924 		next_pvo = LIST_NEXT(pvo, pvo_vlink);
1925 
1926 		pmap = pvo->pvo_pmap;
1927 		PMAP_LOCK(pmap);
1928 		moea_pvo_remove(pvo, -1);
1929 		PMAP_UNLOCK(pmap);
1930 	}
1931 	if ((m->a.flags & PGA_WRITEABLE) && moea_query_bit(m, PTE_CHG)) {
1932 		moea_attr_clear(m, PTE_CHG);
1933 		vm_page_dirty(m);
1934 	}
1935 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1936 	rw_wunlock(&pvh_global_lock);
1937 }
1938 
1939 static int
1940 moea_mincore(pmap_t pm, vm_offset_t va, vm_paddr_t *pap)
1941 {
1942 	struct pvo_entry *pvo;
1943 	vm_paddr_t pa;
1944 	vm_page_t m;
1945 	int val;
1946 	bool managed;
1947 
1948 	PMAP_LOCK(pm);
1949 
1950 	pvo = moea_pvo_find_va(pm, va & ~ADDR_POFF, NULL);
1951 	if (pvo != NULL) {
1952 		pa = PVO_PADDR(pvo);
1953 		m = PHYS_TO_VM_PAGE(pa);
1954 		managed = (pvo->pvo_vaddr & PVO_MANAGED) == PVO_MANAGED;
1955 		val = MINCORE_INCORE;
1956 	} else {
1957 		PMAP_UNLOCK(pm);
1958 		return (0);
1959 	}
1960 
1961 	PMAP_UNLOCK(pm);
1962 
1963 	if (m == NULL)
1964 		return (0);
1965 
1966 	if (managed) {
1967 		if (moea_is_modified(m))
1968 			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
1969 
1970 		if (moea_is_referenced(m))
1971 			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
1972 	}
1973 
1974 	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
1975 	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
1976 	    managed) {
1977 		*pap = pa;
1978 	}
1979 
1980 	return (val);
1981 }
1982 
1983 /*
1984  * Allocate a physical page of memory directly from the phys_avail map.
1985  * Can only be called from moea_bootstrap before avail start and end are
1986  * calculated.
1987  */
1988 static vm_offset_t
1989 moea_bootstrap_alloc(vm_size_t size, u_int align)
1990 {
1991 	vm_offset_t	s, e;
1992 	int		i, j;
1993 
1994 	size = round_page(size);
1995 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
1996 		if (align != 0)
1997 			s = roundup2(phys_avail[i], align);
1998 		else
1999 			s = phys_avail[i];
2000 		e = s + size;
2001 
2002 		if (s < phys_avail[i] || e > phys_avail[i + 1])
2003 			continue;
2004 
2005 		if (s == phys_avail[i]) {
2006 			phys_avail[i] += size;
2007 		} else if (e == phys_avail[i + 1]) {
2008 			phys_avail[i + 1] -= size;
2009 		} else {
2010 			for (j = phys_avail_count * 2; j > i; j -= 2) {
2011 				phys_avail[j] = phys_avail[j - 2];
2012 				phys_avail[j + 1] = phys_avail[j - 1];
2013 			}
2014 
2015 			phys_avail[i + 3] = phys_avail[i + 1];
2016 			phys_avail[i + 1] = s;
2017 			phys_avail[i + 2] = e;
2018 			phys_avail_count++;
2019 		}
2020 
2021 		return (s);
2022 	}
2023 	panic("moea_bootstrap_alloc: could not allocate memory");
2024 }
2025 
2026 static void
2027 moea_syncicache(vm_paddr_t pa, vm_size_t len)
2028 {
2029 	__syncicache((void *)pa, len);
2030 }
2031 
2032 static int
2033 moea_pvo_enter(pmap_t pm, uma_zone_t zone, struct pvo_head *pvo_head,
2034     vm_offset_t va, vm_paddr_t pa, u_int pte_lo, int flags)
2035 {
2036 	struct	pvo_entry *pvo;
2037 	u_int	sr;
2038 	int	first;
2039 	u_int	ptegidx;
2040 	int	i;
2041 	int     bootstrap;
2042 
2043 	moea_pvo_enter_calls++;
2044 	first = 0;
2045 	bootstrap = 0;
2046 
2047 	/*
2048 	 * Compute the PTE Group index.
2049 	 */
2050 	va &= ~ADDR_POFF;
2051 	sr = va_to_sr(pm->pm_sr, va);
2052 	ptegidx = va_to_pteg(sr, va);
2053 
2054 	/*
2055 	 * Remove any existing mapping for this page.  Reuse the pvo entry if
2056 	 * there is a mapping.
2057 	 */
2058 	mtx_lock(&moea_table_mutex);
2059 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
2060 		if (pvo->pvo_pmap == pm && PVO_VADDR(pvo) == va) {
2061 			if (PVO_PADDR(pvo) == pa &&
2062 			    (pvo->pvo_pte.pte.pte_lo & PTE_PP) ==
2063 			    (pte_lo & PTE_PP)) {
2064 				/*
2065 				 * The PTE is not changing.  Instead, this may
2066 				 * be a request to change the mapping's wired
2067 				 * attribute.
2068 				 */
2069 				mtx_unlock(&moea_table_mutex);
2070 				if ((flags & PVO_WIRED) != 0 &&
2071 				    (pvo->pvo_vaddr & PVO_WIRED) == 0) {
2072 					pvo->pvo_vaddr |= PVO_WIRED;
2073 					pm->pm_stats.wired_count++;
2074 				} else if ((flags & PVO_WIRED) == 0 &&
2075 				    (pvo->pvo_vaddr & PVO_WIRED) != 0) {
2076 					pvo->pvo_vaddr &= ~PVO_WIRED;
2077 					pm->pm_stats.wired_count--;
2078 				}
2079 				return (0);
2080 			}
2081 			moea_pvo_remove(pvo, -1);
2082 			break;
2083 		}
2084 	}
2085 
2086 	/*
2087 	 * If we aren't overwriting a mapping, try to allocate.
2088 	 */
2089 	if (moea_initialized) {
2090 		pvo = uma_zalloc(zone, M_NOWAIT);
2091 	} else {
2092 		if (moea_bpvo_pool_index >= BPVO_POOL_SIZE) {
2093 			panic("moea_enter: bpvo pool exhausted, %d, %d, %d",
2094 			      moea_bpvo_pool_index, BPVO_POOL_SIZE,
2095 			      BPVO_POOL_SIZE * sizeof(struct pvo_entry));
2096 		}
2097 		pvo = &moea_bpvo_pool[moea_bpvo_pool_index];
2098 		moea_bpvo_pool_index++;
2099 		bootstrap = 1;
2100 	}
2101 
2102 	if (pvo == NULL) {
2103 		mtx_unlock(&moea_table_mutex);
2104 		return (ENOMEM);
2105 	}
2106 
2107 	moea_pvo_entries++;
2108 	pvo->pvo_vaddr = va;
2109 	pvo->pvo_pmap = pm;
2110 	LIST_INSERT_HEAD(&moea_pvo_table[ptegidx], pvo, pvo_olink);
2111 	pvo->pvo_vaddr &= ~ADDR_POFF;
2112 	if (flags & PVO_WIRED)
2113 		pvo->pvo_vaddr |= PVO_WIRED;
2114 	if (pvo_head != &moea_pvo_kunmanaged)
2115 		pvo->pvo_vaddr |= PVO_MANAGED;
2116 	if (bootstrap)
2117 		pvo->pvo_vaddr |= PVO_BOOTSTRAP;
2118 
2119 	moea_pte_create(&pvo->pvo_pte.pte, sr, va, pa | pte_lo);
2120 
2121 	/*
2122 	 * Add to pmap list
2123 	 */
2124 	RB_INSERT(pvo_tree, &pm->pmap_pvo, pvo);
2125 
2126 	/*
2127 	 * Remember if the list was empty and therefore will be the first
2128 	 * item.
2129 	 */
2130 	if (LIST_FIRST(pvo_head) == NULL)
2131 		first = 1;
2132 	LIST_INSERT_HEAD(pvo_head, pvo, pvo_vlink);
2133 
2134 	if (pvo->pvo_vaddr & PVO_WIRED)
2135 		pm->pm_stats.wired_count++;
2136 	pm->pm_stats.resident_count++;
2137 
2138 	i = moea_pte_insert(ptegidx, &pvo->pvo_pte.pte);
2139 	KASSERT(i < 8, ("Invalid PTE index"));
2140 	if (i >= 0) {
2141 		PVO_PTEGIDX_SET(pvo, i);
2142 	} else {
2143 		panic("moea_pvo_enter: overflow");
2144 		moea_pte_overflow++;
2145 	}
2146 	mtx_unlock(&moea_table_mutex);
2147 
2148 	return (first ? ENOENT : 0);
2149 }
2150 
2151 static void
2152 moea_pvo_remove(struct pvo_entry *pvo, int pteidx)
2153 {
2154 	struct	pte *pt;
2155 
2156 	/*
2157 	 * If there is an active pte entry, we need to deactivate it (and
2158 	 * save the ref & cfg bits).
2159 	 */
2160 	pt = moea_pvo_to_pte(pvo, pteidx);
2161 	if (pt != NULL) {
2162 		moea_pte_unset(pt, &pvo->pvo_pte.pte, pvo->pvo_vaddr);
2163 		mtx_unlock(&moea_table_mutex);
2164 		PVO_PTEGIDX_CLR(pvo);
2165 	} else {
2166 		moea_pte_overflow--;
2167 	}
2168 
2169 	/*
2170 	 * Update our statistics.
2171 	 */
2172 	pvo->pvo_pmap->pm_stats.resident_count--;
2173 	if (pvo->pvo_vaddr & PVO_WIRED)
2174 		pvo->pvo_pmap->pm_stats.wired_count--;
2175 
2176 	/*
2177 	 * Remove this PVO from the PV and pmap lists.
2178 	 */
2179 	LIST_REMOVE(pvo, pvo_vlink);
2180 	RB_REMOVE(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2181 
2182 	/*
2183 	 * Save the REF/CHG bits into their cache if the page is managed.
2184 	 * Clear PGA_WRITEABLE if all mappings of the page have been removed.
2185 	 */
2186 	if ((pvo->pvo_vaddr & PVO_MANAGED) == PVO_MANAGED) {
2187 		struct vm_page *pg;
2188 
2189 		pg = PHYS_TO_VM_PAGE(PVO_PADDR(pvo));
2190 		if (pg != NULL) {
2191 			moea_attr_save(pg, pvo->pvo_pte.pte.pte_lo &
2192 			    (PTE_REF | PTE_CHG));
2193 			if (LIST_EMPTY(&pg->md.mdpg_pvoh))
2194 				vm_page_aflag_clear(pg, PGA_WRITEABLE);
2195 		}
2196 	}
2197 
2198 	/*
2199 	 * Remove this from the overflow list and return it to the pool
2200 	 * if we aren't going to reuse it.
2201 	 */
2202 	LIST_REMOVE(pvo, pvo_olink);
2203 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
2204 		uma_zfree(pvo->pvo_vaddr & PVO_MANAGED ? moea_mpvo_zone :
2205 		    moea_upvo_zone, pvo);
2206 	moea_pvo_entries--;
2207 	moea_pvo_remove_calls++;
2208 }
2209 
2210 static __inline int
2211 moea_pvo_pte_index(const struct pvo_entry *pvo, int ptegidx)
2212 {
2213 	int	pteidx;
2214 
2215 	/*
2216 	 * We can find the actual pte entry without searching by grabbing
2217 	 * the PTEG index from 3 unused bits in pte_lo[11:9] and by
2218 	 * noticing the HID bit.
2219 	 */
2220 	pteidx = ptegidx * 8 + PVO_PTEGIDX_GET(pvo);
2221 	if (pvo->pvo_pte.pte.pte_hi & PTE_HID)
2222 		pteidx ^= moea_pteg_mask * 8;
2223 
2224 	return (pteidx);
2225 }
2226 
2227 static struct pvo_entry *
2228 moea_pvo_find_va(pmap_t pm, vm_offset_t va, int *pteidx_p)
2229 {
2230 	struct	pvo_entry *pvo;
2231 	int	ptegidx;
2232 	u_int	sr;
2233 
2234 	va &= ~ADDR_POFF;
2235 	sr = va_to_sr(pm->pm_sr, va);
2236 	ptegidx = va_to_pteg(sr, va);
2237 
2238 	mtx_lock(&moea_table_mutex);
2239 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
2240 		if (pvo->pvo_pmap == pm && PVO_VADDR(pvo) == va) {
2241 			if (pteidx_p)
2242 				*pteidx_p = moea_pvo_pte_index(pvo, ptegidx);
2243 			break;
2244 		}
2245 	}
2246 	mtx_unlock(&moea_table_mutex);
2247 
2248 	return (pvo);
2249 }
2250 
2251 static struct pte *
2252 moea_pvo_to_pte(const struct pvo_entry *pvo, int pteidx)
2253 {
2254 	struct	pte *pt;
2255 
2256 	/*
2257 	 * If we haven't been supplied the ptegidx, calculate it.
2258 	 */
2259 	if (pteidx == -1) {
2260 		int	ptegidx;
2261 		u_int	sr;
2262 
2263 		sr = va_to_sr(pvo->pvo_pmap->pm_sr, pvo->pvo_vaddr);
2264 		ptegidx = va_to_pteg(sr, pvo->pvo_vaddr);
2265 		pteidx = moea_pvo_pte_index(pvo, ptegidx);
2266 	}
2267 
2268 	pt = &moea_pteg_table[pteidx >> 3].pt[pteidx & 7];
2269 	mtx_lock(&moea_table_mutex);
2270 
2271 	if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) && !PVO_PTEGIDX_ISSET(pvo)) {
2272 		panic("moea_pvo_to_pte: pvo %p has valid pte in pvo but no "
2273 		    "valid pte index", pvo);
2274 	}
2275 
2276 	if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0 && PVO_PTEGIDX_ISSET(pvo)) {
2277 		panic("moea_pvo_to_pte: pvo %p has valid pte index in pvo "
2278 		    "pvo but no valid pte", pvo);
2279 	}
2280 
2281 	if ((pt->pte_hi ^ (pvo->pvo_pte.pte.pte_hi & ~PTE_VALID)) == PTE_VALID) {
2282 		if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0) {
2283 			panic("moea_pvo_to_pte: pvo %p has valid pte in "
2284 			    "moea_pteg_table %p but invalid in pvo", pvo, pt);
2285 		}
2286 
2287 		if (((pt->pte_lo ^ pvo->pvo_pte.pte.pte_lo) & ~(PTE_CHG|PTE_REF))
2288 		    != 0) {
2289 			panic("moea_pvo_to_pte: pvo %p pte does not match "
2290 			    "pte %p in moea_pteg_table", pvo, pt);
2291 		}
2292 
2293 		mtx_assert(&moea_table_mutex, MA_OWNED);
2294 		return (pt);
2295 	}
2296 
2297 	if (pvo->pvo_pte.pte.pte_hi & PTE_VALID) {
2298 		panic("moea_pvo_to_pte: pvo %p has invalid pte %p in "
2299 		    "moea_pteg_table but valid in pvo: %8x, %8x", pvo, pt, pvo->pvo_pte.pte.pte_hi, pt->pte_hi);
2300 	}
2301 
2302 	mtx_unlock(&moea_table_mutex);
2303 	return (NULL);
2304 }
2305 
2306 /*
2307  * XXX: THIS STUFF SHOULD BE IN pte.c?
2308  */
2309 int
2310 moea_pte_spill(vm_offset_t addr)
2311 {
2312 	struct	pvo_entry *source_pvo, *victim_pvo;
2313 	struct	pvo_entry *pvo;
2314 	int	ptegidx, i, j;
2315 	u_int	sr;
2316 	struct	pteg *pteg;
2317 	struct	pte *pt;
2318 
2319 	moea_pte_spills++;
2320 
2321 	sr = mfsrin(addr);
2322 	ptegidx = va_to_pteg(sr, addr);
2323 
2324 	/*
2325 	 * Have to substitute some entry.  Use the primary hash for this.
2326 	 * Use low bits of timebase as random generator.
2327 	 */
2328 	pteg = &moea_pteg_table[ptegidx];
2329 	mtx_lock(&moea_table_mutex);
2330 	__asm __volatile("mftb %0" : "=r"(i));
2331 	i &= 7;
2332 	pt = &pteg->pt[i];
2333 
2334 	source_pvo = NULL;
2335 	victim_pvo = NULL;
2336 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
2337 		/*
2338 		 * We need to find a pvo entry for this address.
2339 		 */
2340 		if (source_pvo == NULL &&
2341 		    moea_pte_match(&pvo->pvo_pte.pte, sr, addr,
2342 		    pvo->pvo_pte.pte.pte_hi & PTE_HID)) {
2343 			/*
2344 			 * Now found an entry to be spilled into the pteg.
2345 			 * The PTE is now valid, so we know it's active.
2346 			 */
2347 			j = moea_pte_insert(ptegidx, &pvo->pvo_pte.pte);
2348 
2349 			if (j >= 0) {
2350 				PVO_PTEGIDX_SET(pvo, j);
2351 				moea_pte_overflow--;
2352 				mtx_unlock(&moea_table_mutex);
2353 				return (1);
2354 			}
2355 
2356 			source_pvo = pvo;
2357 
2358 			if (victim_pvo != NULL)
2359 				break;
2360 		}
2361 
2362 		/*
2363 		 * We also need the pvo entry of the victim we are replacing
2364 		 * so save the R & C bits of the PTE.
2365 		 */
2366 		if ((pt->pte_hi & PTE_HID) == 0 && victim_pvo == NULL &&
2367 		    moea_pte_compare(pt, &pvo->pvo_pte.pte)) {
2368 			victim_pvo = pvo;
2369 			if (source_pvo != NULL)
2370 				break;
2371 		}
2372 	}
2373 
2374 	if (source_pvo == NULL) {
2375 		mtx_unlock(&moea_table_mutex);
2376 		return (0);
2377 	}
2378 
2379 	if (victim_pvo == NULL) {
2380 		if ((pt->pte_hi & PTE_HID) == 0)
2381 			panic("moea_pte_spill: victim p-pte (%p) has no pvo"
2382 			    "entry", pt);
2383 
2384 		/*
2385 		 * If this is a secondary PTE, we need to search it's primary
2386 		 * pvo bucket for the matching PVO.
2387 		 */
2388 		LIST_FOREACH(pvo, &moea_pvo_table[ptegidx ^ moea_pteg_mask],
2389 		    pvo_olink) {
2390 			/*
2391 			 * We also need the pvo entry of the victim we are
2392 			 * replacing so save the R & C bits of the PTE.
2393 			 */
2394 			if (moea_pte_compare(pt, &pvo->pvo_pte.pte)) {
2395 				victim_pvo = pvo;
2396 				break;
2397 			}
2398 		}
2399 
2400 		if (victim_pvo == NULL)
2401 			panic("moea_pte_spill: victim s-pte (%p) has no pvo"
2402 			    "entry", pt);
2403 	}
2404 
2405 	/*
2406 	 * We are invalidating the TLB entry for the EA we are replacing even
2407 	 * though it's valid.  If we don't, we lose any ref/chg bit changes
2408 	 * contained in the TLB entry.
2409 	 */
2410 	source_pvo->pvo_pte.pte.pte_hi &= ~PTE_HID;
2411 
2412 	moea_pte_unset(pt, &victim_pvo->pvo_pte.pte, victim_pvo->pvo_vaddr);
2413 	moea_pte_set(pt, &source_pvo->pvo_pte.pte);
2414 
2415 	PVO_PTEGIDX_CLR(victim_pvo);
2416 	PVO_PTEGIDX_SET(source_pvo, i);
2417 	moea_pte_replacements++;
2418 
2419 	mtx_unlock(&moea_table_mutex);
2420 	return (1);
2421 }
2422 
2423 static __inline struct pvo_entry *
2424 moea_pte_spillable_ident(u_int ptegidx)
2425 {
2426 	struct	pte *pt;
2427 	struct	pvo_entry *pvo_walk, *pvo = NULL;
2428 
2429 	LIST_FOREACH(pvo_walk, &moea_pvo_table[ptegidx], pvo_olink) {
2430 		if (pvo_walk->pvo_vaddr & PVO_WIRED)
2431 			continue;
2432 
2433 		if (!(pvo_walk->pvo_pte.pte.pte_hi & PTE_VALID))
2434 			continue;
2435 
2436 		pt = moea_pvo_to_pte(pvo_walk, -1);
2437 
2438 		if (pt == NULL)
2439 			continue;
2440 
2441 		pvo = pvo_walk;
2442 
2443 		mtx_unlock(&moea_table_mutex);
2444 		if (!(pt->pte_lo & PTE_REF))
2445 			return (pvo_walk);
2446 	}
2447 
2448 	return (pvo);
2449 }
2450 
2451 static int
2452 moea_pte_insert(u_int ptegidx, struct pte *pvo_pt)
2453 {
2454 	struct	pte *pt;
2455 	struct	pvo_entry *victim_pvo;
2456 	int	i;
2457 	int	victim_idx;
2458 	u_int	pteg_bkpidx = ptegidx;
2459 
2460 	mtx_assert(&moea_table_mutex, MA_OWNED);
2461 
2462 	/*
2463 	 * First try primary hash.
2464 	 */
2465 	for (pt = moea_pteg_table[ptegidx].pt, i = 0; i < 8; i++, pt++) {
2466 		if ((pt->pte_hi & PTE_VALID) == 0) {
2467 			pvo_pt->pte_hi &= ~PTE_HID;
2468 			moea_pte_set(pt, pvo_pt);
2469 			return (i);
2470 		}
2471 	}
2472 
2473 	/*
2474 	 * Now try secondary hash.
2475 	 */
2476 	ptegidx ^= moea_pteg_mask;
2477 
2478 	for (pt = moea_pteg_table[ptegidx].pt, i = 0; i < 8; i++, pt++) {
2479 		if ((pt->pte_hi & PTE_VALID) == 0) {
2480 			pvo_pt->pte_hi |= PTE_HID;
2481 			moea_pte_set(pt, pvo_pt);
2482 			return (i);
2483 		}
2484 	}
2485 
2486 	/* Try again, but this time try to force a PTE out. */
2487 	ptegidx = pteg_bkpidx;
2488 
2489 	victim_pvo = moea_pte_spillable_ident(ptegidx);
2490 	if (victim_pvo == NULL) {
2491 		ptegidx ^= moea_pteg_mask;
2492 		victim_pvo = moea_pte_spillable_ident(ptegidx);
2493 	}
2494 
2495 	if (victim_pvo == NULL) {
2496 		panic("moea_pte_insert: overflow");
2497 		return (-1);
2498 	}
2499 
2500 	victim_idx = moea_pvo_pte_index(victim_pvo, ptegidx);
2501 
2502 	if (pteg_bkpidx == ptegidx)
2503 		pvo_pt->pte_hi &= ~PTE_HID;
2504 	else
2505 		pvo_pt->pte_hi |= PTE_HID;
2506 
2507 	/*
2508 	 * Synchronize the sacrifice PTE with its PVO, then mark both
2509 	 * invalid. The PVO will be reused when/if the VM system comes
2510 	 * here after a fault.
2511 	 */
2512 	pt = &moea_pteg_table[victim_idx >> 3].pt[victim_idx & 7];
2513 
2514 	if (pt->pte_hi != victim_pvo->pvo_pte.pte.pte_hi)
2515 	    panic("Victim PVO doesn't match PTE! PVO: %8x, PTE: %8x", victim_pvo->pvo_pte.pte.pte_hi, pt->pte_hi);
2516 
2517 	/*
2518 	 * Set the new PTE.
2519 	 */
2520 	moea_pte_unset(pt, &victim_pvo->pvo_pte.pte, victim_pvo->pvo_vaddr);
2521 	PVO_PTEGIDX_CLR(victim_pvo);
2522 	moea_pte_overflow++;
2523 	moea_pte_set(pt, pvo_pt);
2524 
2525 	return (victim_idx & 7);
2526 }
2527 
2528 static bool
2529 moea_query_bit(vm_page_t m, int ptebit)
2530 {
2531 	struct	pvo_entry *pvo;
2532 	struct	pte *pt;
2533 
2534 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2535 	if (moea_attr_fetch(m) & ptebit)
2536 		return (true);
2537 
2538 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2539 		/*
2540 		 * See if we saved the bit off.  If so, cache it and return
2541 		 * success.
2542 		 */
2543 		if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2544 			moea_attr_save(m, ptebit);
2545 			return (true);
2546 		}
2547 	}
2548 
2549 	/*
2550 	 * No luck, now go through the hard part of looking at the PTEs
2551 	 * themselves.  Sync so that any pending REF/CHG bits are flushed to
2552 	 * the PTEs.
2553 	 */
2554 	powerpc_sync();
2555 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2556 		/*
2557 		 * See if this pvo has a valid PTE.  if so, fetch the
2558 		 * REF/CHG bits from the valid PTE.  If the appropriate
2559 		 * ptebit is set, cache it and return success.
2560 		 */
2561 		pt = moea_pvo_to_pte(pvo, -1);
2562 		if (pt != NULL) {
2563 			moea_pte_synch(pt, &pvo->pvo_pte.pte);
2564 			mtx_unlock(&moea_table_mutex);
2565 			if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2566 				moea_attr_save(m, ptebit);
2567 				return (true);
2568 			}
2569 		}
2570 	}
2571 
2572 	return (false);
2573 }
2574 
2575 static u_int
2576 moea_clear_bit(vm_page_t m, int ptebit)
2577 {
2578 	u_int	count;
2579 	struct	pvo_entry *pvo;
2580 	struct	pte *pt;
2581 
2582 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2583 
2584 	/*
2585 	 * Clear the cached value.
2586 	 */
2587 	moea_attr_clear(m, ptebit);
2588 
2589 	/*
2590 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
2591 	 * we can reset the right ones).  note that since the pvo entries and
2592 	 * list heads are accessed via BAT0 and are never placed in the page
2593 	 * table, we don't have to worry about further accesses setting the
2594 	 * REF/CHG bits.
2595 	 */
2596 	powerpc_sync();
2597 
2598 	/*
2599 	 * For each pvo entry, clear the pvo's ptebit.  If this pvo has a
2600 	 * valid pte clear the ptebit from the valid pte.
2601 	 */
2602 	count = 0;
2603 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2604 		pt = moea_pvo_to_pte(pvo, -1);
2605 		if (pt != NULL) {
2606 			moea_pte_synch(pt, &pvo->pvo_pte.pte);
2607 			if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2608 				count++;
2609 				moea_pte_clear(pt, PVO_VADDR(pvo), ptebit);
2610 			}
2611 			mtx_unlock(&moea_table_mutex);
2612 		}
2613 		pvo->pvo_pte.pte.pte_lo &= ~ptebit;
2614 	}
2615 
2616 	return (count);
2617 }
2618 
2619 /*
2620  * Return true if the physical range is encompassed by the battable[idx]
2621  */
2622 static int
2623 moea_bat_mapped(int idx, vm_paddr_t pa, vm_size_t size)
2624 {
2625 	u_int prot;
2626 	u_int32_t start;
2627 	u_int32_t end;
2628 	u_int32_t bat_ble;
2629 
2630 	/*
2631 	 * Return immediately if not a valid mapping
2632 	 */
2633 	if (!(battable[idx].batu & BAT_Vs))
2634 		return (EINVAL);
2635 
2636 	/*
2637 	 * The BAT entry must be cache-inhibited, guarded, and r/w
2638 	 * so it can function as an i/o page
2639 	 */
2640 	prot = battable[idx].batl & (BAT_I|BAT_G|BAT_PP_RW);
2641 	if (prot != (BAT_I|BAT_G|BAT_PP_RW))
2642 		return (EPERM);
2643 
2644 	/*
2645 	 * The address should be within the BAT range. Assume that the
2646 	 * start address in the BAT has the correct alignment (thus
2647 	 * not requiring masking)
2648 	 */
2649 	start = battable[idx].batl & BAT_PBS;
2650 	bat_ble = (battable[idx].batu & ~(BAT_EBS)) | 0x03;
2651 	end = start | (bat_ble << 15) | 0x7fff;
2652 
2653 	if ((pa < start) || ((pa + size) > end))
2654 		return (ERANGE);
2655 
2656 	return (0);
2657 }
2658 
2659 int
2660 moea_dev_direct_mapped(vm_paddr_t pa, vm_size_t size)
2661 {
2662 	int i;
2663 
2664 	/*
2665 	 * This currently does not work for entries that
2666 	 * overlap 256M BAT segments.
2667 	 */
2668 
2669 	for(i = 0; i < 16; i++)
2670 		if (moea_bat_mapped(i, pa, size) == 0)
2671 			return (0);
2672 
2673 	return (EFAULT);
2674 }
2675 
2676 /*
2677  * Map a set of physical memory pages into the kernel virtual
2678  * address space. Return a pointer to where it is mapped. This
2679  * routine is intended to be used for mapping device memory,
2680  * NOT real memory.
2681  */
2682 void *
2683 moea_mapdev(vm_paddr_t pa, vm_size_t size)
2684 {
2685 
2686 	return (moea_mapdev_attr(pa, size, VM_MEMATTR_DEFAULT));
2687 }
2688 
2689 void *
2690 moea_mapdev_attr(vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2691 {
2692 	vm_offset_t va, tmpva, ppa, offset;
2693 	int i;
2694 
2695 	ppa = trunc_page(pa);
2696 	offset = pa & PAGE_MASK;
2697 	size = roundup(offset + size, PAGE_SIZE);
2698 
2699 	/*
2700 	 * If the physical address lies within a valid BAT table entry,
2701 	 * return the 1:1 mapping. This currently doesn't work
2702 	 * for regions that overlap 256M BAT segments.
2703 	 */
2704 	for (i = 0; i < 16; i++) {
2705 		if (moea_bat_mapped(i, pa, size) == 0)
2706 			return ((void *) pa);
2707 	}
2708 
2709 	va = kva_alloc(size);
2710 	if (!va)
2711 		panic("moea_mapdev: Couldn't alloc kernel virtual memory");
2712 
2713 	for (tmpva = va; size > 0;) {
2714 		moea_kenter_attr(tmpva, ppa, ma);
2715 		tlbie(tmpva);
2716 		size -= PAGE_SIZE;
2717 		tmpva += PAGE_SIZE;
2718 		ppa += PAGE_SIZE;
2719 	}
2720 
2721 	return ((void *)(va + offset));
2722 }
2723 
2724 void
2725 moea_unmapdev(void *p, vm_size_t size)
2726 {
2727 	vm_offset_t base, offset, va;
2728 
2729 	/*
2730 	 * If this is outside kernel virtual space, then it's a
2731 	 * battable entry and doesn't require unmapping
2732 	 */
2733 	va = (vm_offset_t)p;
2734 	if ((va >= VM_MIN_KERNEL_ADDRESS) && (va <= virtual_end)) {
2735 		base = trunc_page(va);
2736 		offset = va & PAGE_MASK;
2737 		size = roundup(offset + size, PAGE_SIZE);
2738 		moea_qremove(base, atop(size));
2739 		kva_free(base, size);
2740 	}
2741 }
2742 
2743 static void
2744 moea_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
2745 {
2746 	struct pvo_entry *pvo;
2747 	vm_offset_t lim;
2748 	vm_paddr_t pa;
2749 	vm_size_t len;
2750 
2751 	PMAP_LOCK(pm);
2752 	while (sz > 0) {
2753 		lim = round_page(va + 1);
2754 		len = MIN(lim - va, sz);
2755 		pvo = moea_pvo_find_va(pm, va & ~ADDR_POFF, NULL);
2756 		if (pvo != NULL) {
2757 			pa = PVO_PADDR(pvo) | (va & ADDR_POFF);
2758 			moea_syncicache(pa, len);
2759 		}
2760 		va += len;
2761 		sz -= len;
2762 	}
2763 	PMAP_UNLOCK(pm);
2764 }
2765 
2766 void
2767 moea_dumpsys_map(vm_paddr_t pa, size_t sz, void **va)
2768 {
2769 
2770 	*va = (void *)pa;
2771 }
2772 
2773 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2774 
2775 void
2776 moea_scan_init(void)
2777 {
2778 	struct pvo_entry *pvo;
2779 	vm_offset_t va;
2780 	int i;
2781 
2782 	if (!do_minidump) {
2783 		/* Initialize phys. segments for dumpsys(). */
2784 		memset(&dump_map, 0, sizeof(dump_map));
2785 		mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
2786 		for (i = 0; i < pregions_sz; i++) {
2787 			dump_map[i].pa_start = pregions[i].mr_start;
2788 			dump_map[i].pa_size = pregions[i].mr_size;
2789 		}
2790 		return;
2791 	}
2792 
2793 	/* Virtual segments for minidumps: */
2794 	memset(&dump_map, 0, sizeof(dump_map));
2795 
2796 	/* 1st: kernel .data and .bss. */
2797 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2798 	dump_map[0].pa_size =
2799 	    round_page((uintptr_t)_end) - dump_map[0].pa_start;
2800 
2801 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2802 	dump_map[1].pa_start = (vm_paddr_t)msgbufp->msg_ptr;
2803 	dump_map[1].pa_size = round_page(msgbufp->msg_size);
2804 
2805 	/* 3rd: kernel VM. */
2806 	va = dump_map[1].pa_start + dump_map[1].pa_size;
2807 	/* Find start of next chunk (from va). */
2808 	while (va < virtual_end) {
2809 		/* Don't dump the buffer cache. */
2810 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2811 			va = kmi.buffer_eva;
2812 			continue;
2813 		}
2814 		pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF, NULL);
2815 		if (pvo != NULL && (pvo->pvo_pte.pte.pte_hi & PTE_VALID))
2816 			break;
2817 		va += PAGE_SIZE;
2818 	}
2819 	if (va < virtual_end) {
2820 		dump_map[2].pa_start = va;
2821 		va += PAGE_SIZE;
2822 		/* Find last page in chunk. */
2823 		while (va < virtual_end) {
2824 			/* Don't run into the buffer cache. */
2825 			if (va == kmi.buffer_sva)
2826 				break;
2827 			pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF,
2828 			    NULL);
2829 			if (pvo == NULL ||
2830 			    !(pvo->pvo_pte.pte.pte_hi & PTE_VALID))
2831 				break;
2832 			va += PAGE_SIZE;
2833 		}
2834 		dump_map[2].pa_size = va - dump_map[2].pa_start;
2835 	}
2836 }
2837