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