xref: /freebsd/sys/powerpc/aim/mmu_oea.c (revision b2d48be1bc7df45ddd13b143a160d0acb5a383c5)
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_zero_page_idle(mmu_t, vm_page_t);
304 void moea_activate(mmu_t, struct thread *);
305 void moea_deactivate(mmu_t, struct thread *);
306 void moea_cpu_bootstrap(mmu_t, int);
307 void moea_bootstrap(mmu_t, vm_offset_t, vm_offset_t);
308 void *moea_mapdev(mmu_t, vm_paddr_t, vm_size_t);
309 void *moea_mapdev_attr(mmu_t, vm_paddr_t, vm_size_t, vm_memattr_t);
310 void moea_unmapdev(mmu_t, vm_offset_t, vm_size_t);
311 vm_paddr_t moea_kextract(mmu_t, vm_offset_t);
312 void moea_kenter_attr(mmu_t, vm_offset_t, vm_paddr_t, vm_memattr_t);
313 void moea_kenter(mmu_t, vm_offset_t, vm_paddr_t);
314 void moea_page_set_memattr(mmu_t mmu, vm_page_t m, vm_memattr_t ma);
315 boolean_t moea_dev_direct_mapped(mmu_t, vm_paddr_t, vm_size_t);
316 static void moea_sync_icache(mmu_t, pmap_t, vm_offset_t, vm_size_t);
317 void moea_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz, void **va);
318 void moea_scan_init(mmu_t mmu);
319 vm_offset_t moea_quick_enter_page(mmu_t mmu, vm_page_t m);
320 void moea_quick_remove_page(mmu_t mmu, vm_offset_t addr);
321 
322 static mmu_method_t moea_methods[] = {
323 	MMUMETHOD(mmu_clear_modify,	moea_clear_modify),
324 	MMUMETHOD(mmu_copy_page,	moea_copy_page),
325 	MMUMETHOD(mmu_copy_pages,	moea_copy_pages),
326 	MMUMETHOD(mmu_enter,		moea_enter),
327 	MMUMETHOD(mmu_enter_object,	moea_enter_object),
328 	MMUMETHOD(mmu_enter_quick,	moea_enter_quick),
329 	MMUMETHOD(mmu_extract,		moea_extract),
330 	MMUMETHOD(mmu_extract_and_hold,	moea_extract_and_hold),
331 	MMUMETHOD(mmu_init,		moea_init),
332 	MMUMETHOD(mmu_is_modified,	moea_is_modified),
333 	MMUMETHOD(mmu_is_prefaultable,	moea_is_prefaultable),
334 	MMUMETHOD(mmu_is_referenced,	moea_is_referenced),
335 	MMUMETHOD(mmu_ts_referenced,	moea_ts_referenced),
336 	MMUMETHOD(mmu_map,     		moea_map),
337 	MMUMETHOD(mmu_page_exists_quick,moea_page_exists_quick),
338 	MMUMETHOD(mmu_page_wired_mappings,moea_page_wired_mappings),
339 	MMUMETHOD(mmu_pinit,		moea_pinit),
340 	MMUMETHOD(mmu_pinit0,		moea_pinit0),
341 	MMUMETHOD(mmu_protect,		moea_protect),
342 	MMUMETHOD(mmu_qenter,		moea_qenter),
343 	MMUMETHOD(mmu_qremove,		moea_qremove),
344 	MMUMETHOD(mmu_release,		moea_release),
345 	MMUMETHOD(mmu_remove,		moea_remove),
346 	MMUMETHOD(mmu_remove_all,      	moea_remove_all),
347 	MMUMETHOD(mmu_remove_write,	moea_remove_write),
348 	MMUMETHOD(mmu_sync_icache,	moea_sync_icache),
349 	MMUMETHOD(mmu_unwire,		moea_unwire),
350 	MMUMETHOD(mmu_zero_page,       	moea_zero_page),
351 	MMUMETHOD(mmu_zero_page_area,	moea_zero_page_area),
352 	MMUMETHOD(mmu_zero_page_idle,	moea_zero_page_idle),
353 	MMUMETHOD(mmu_activate,		moea_activate),
354 	MMUMETHOD(mmu_deactivate,      	moea_deactivate),
355 	MMUMETHOD(mmu_page_set_memattr,	moea_page_set_memattr),
356 	MMUMETHOD(mmu_quick_enter_page, moea_quick_enter_page),
357 	MMUMETHOD(mmu_quick_remove_page, moea_quick_remove_page),
358 
359 	/* Internal interfaces */
360 	MMUMETHOD(mmu_bootstrap,       	moea_bootstrap),
361 	MMUMETHOD(mmu_cpu_bootstrap,   	moea_cpu_bootstrap),
362 	MMUMETHOD(mmu_mapdev_attr,	moea_mapdev_attr),
363 	MMUMETHOD(mmu_mapdev,		moea_mapdev),
364 	MMUMETHOD(mmu_unmapdev,		moea_unmapdev),
365 	MMUMETHOD(mmu_kextract,		moea_kextract),
366 	MMUMETHOD(mmu_kenter,		moea_kenter),
367 	MMUMETHOD(mmu_kenter_attr,	moea_kenter_attr),
368 	MMUMETHOD(mmu_dev_direct_mapped,moea_dev_direct_mapped),
369 	MMUMETHOD(mmu_scan_init,	moea_scan_init),
370 	MMUMETHOD(mmu_dumpsys_map,	moea_dumpsys_map),
371 
372 	{ 0, 0 }
373 };
374 
375 MMU_DEF(oea_mmu, MMU_TYPE_OEA, moea_methods, 0);
376 
377 static __inline uint32_t
378 moea_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
379 {
380 	uint32_t pte_lo;
381 	int i;
382 
383 	if (ma != VM_MEMATTR_DEFAULT) {
384 		switch (ma) {
385 		case VM_MEMATTR_UNCACHEABLE:
386 			return (PTE_I | PTE_G);
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 
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 void
1083 moea_zero_page_idle(mmu_t mmu, vm_page_t m)
1084 {
1085 
1086 	moea_zero_page(mmu, m);
1087 }
1088 
1089 vm_offset_t
1090 moea_quick_enter_page(mmu_t mmu, vm_page_t m)
1091 {
1092 
1093 	return (VM_PAGE_TO_PHYS(m));
1094 }
1095 
1096 void
1097 moea_quick_remove_page(mmu_t mmu, vm_offset_t addr)
1098 {
1099 }
1100 
1101 /*
1102  * Map the given physical page at the specified virtual address in the
1103  * target pmap with the protection requested.  If specified the page
1104  * will be wired down.
1105  */
1106 int
1107 moea_enter(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1108     u_int flags, int8_t psind)
1109 {
1110 	int error;
1111 
1112 	for (;;) {
1113 		rw_wlock(&pvh_global_lock);
1114 		PMAP_LOCK(pmap);
1115 		error = moea_enter_locked(pmap, va, m, prot, flags, psind);
1116 		rw_wunlock(&pvh_global_lock);
1117 		PMAP_UNLOCK(pmap);
1118 		if (error != ENOMEM)
1119 			return (KERN_SUCCESS);
1120 		if ((flags & PMAP_ENTER_NOSLEEP) != 0)
1121 			return (KERN_RESOURCE_SHORTAGE);
1122 		VM_OBJECT_ASSERT_UNLOCKED(m->object);
1123 		VM_WAIT;
1124 	}
1125 }
1126 
1127 /*
1128  * Map the given physical page at the specified virtual address in the
1129  * target pmap with the protection requested.  If specified the page
1130  * will be wired down.
1131  *
1132  * The global pvh and pmap must be locked.
1133  */
1134 static int
1135 moea_enter_locked(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1136     u_int flags, int8_t psind __unused)
1137 {
1138 	struct		pvo_head *pvo_head;
1139 	uma_zone_t	zone;
1140 	u_int		pte_lo, pvo_flags;
1141 	int		error;
1142 
1143 	if (pmap_bootstrapped)
1144 		rw_assert(&pvh_global_lock, RA_WLOCKED);
1145 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1146 	if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
1147 		VM_OBJECT_ASSERT_LOCKED(m->object);
1148 
1149 	if ((m->oflags & VPO_UNMANAGED) != 0 || !moea_initialized) {
1150 		pvo_head = &moea_pvo_kunmanaged;
1151 		zone = moea_upvo_zone;
1152 		pvo_flags = 0;
1153 	} else {
1154 		pvo_head = vm_page_to_pvoh(m);
1155 		zone = moea_mpvo_zone;
1156 		pvo_flags = PVO_MANAGED;
1157 	}
1158 
1159 	pte_lo = moea_calc_wimg(VM_PAGE_TO_PHYS(m), pmap_page_get_memattr(m));
1160 
1161 	if (prot & VM_PROT_WRITE) {
1162 		pte_lo |= PTE_BW;
1163 		if (pmap_bootstrapped &&
1164 		    (m->oflags & VPO_UNMANAGED) == 0)
1165 			vm_page_aflag_set(m, PGA_WRITEABLE);
1166 	} else
1167 		pte_lo |= PTE_BR;
1168 
1169 	if ((flags & PMAP_ENTER_WIRED) != 0)
1170 		pvo_flags |= PVO_WIRED;
1171 
1172 	error = moea_pvo_enter(pmap, zone, pvo_head, va, VM_PAGE_TO_PHYS(m),
1173 	    pte_lo, pvo_flags);
1174 
1175 	/*
1176 	 * Flush the real page from the instruction cache. This has be done
1177 	 * for all user mappings to prevent information leakage via the
1178 	 * instruction cache. moea_pvo_enter() returns ENOENT for the first
1179 	 * mapping for a page.
1180 	 */
1181 	if (pmap != kernel_pmap && error == ENOENT &&
1182 	    (pte_lo & (PTE_I | PTE_G)) == 0)
1183 		moea_syncicache(VM_PAGE_TO_PHYS(m), PAGE_SIZE);
1184 
1185 	return (error);
1186 }
1187 
1188 /*
1189  * Maps a sequence of resident pages belonging to the same object.
1190  * The sequence begins with the given page m_start.  This page is
1191  * mapped at the given virtual address start.  Each subsequent page is
1192  * mapped at a virtual address that is offset from start by the same
1193  * amount as the page is offset from m_start within the object.  The
1194  * last page in the sequence is the page with the largest offset from
1195  * m_start that can be mapped at a virtual address less than the given
1196  * virtual address end.  Not every virtual page between start and end
1197  * is mapped; only those for which a resident page exists with the
1198  * corresponding offset from m_start are mapped.
1199  */
1200 void
1201 moea_enter_object(mmu_t mmu, pmap_t pm, vm_offset_t start, vm_offset_t end,
1202     vm_page_t m_start, vm_prot_t prot)
1203 {
1204 	vm_page_t m;
1205 	vm_pindex_t diff, psize;
1206 
1207 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
1208 
1209 	psize = atop(end - start);
1210 	m = m_start;
1211 	rw_wlock(&pvh_global_lock);
1212 	PMAP_LOCK(pm);
1213 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1214 		moea_enter_locked(pm, start + ptoa(diff), m, prot &
1215 		    (VM_PROT_READ | VM_PROT_EXECUTE), 0, 0);
1216 		m = TAILQ_NEXT(m, listq);
1217 	}
1218 	rw_wunlock(&pvh_global_lock);
1219 	PMAP_UNLOCK(pm);
1220 }
1221 
1222 void
1223 moea_enter_quick(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_page_t m,
1224     vm_prot_t prot)
1225 {
1226 
1227 	rw_wlock(&pvh_global_lock);
1228 	PMAP_LOCK(pm);
1229 	moea_enter_locked(pm, va, m, prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1230 	    0, 0);
1231 	rw_wunlock(&pvh_global_lock);
1232 	PMAP_UNLOCK(pm);
1233 }
1234 
1235 vm_paddr_t
1236 moea_extract(mmu_t mmu, pmap_t pm, vm_offset_t va)
1237 {
1238 	struct	pvo_entry *pvo;
1239 	vm_paddr_t pa;
1240 
1241 	PMAP_LOCK(pm);
1242 	pvo = moea_pvo_find_va(pm, va & ~ADDR_POFF, NULL);
1243 	if (pvo == NULL)
1244 		pa = 0;
1245 	else
1246 		pa = (pvo->pvo_pte.pte.pte_lo & PTE_RPGN) | (va & ADDR_POFF);
1247 	PMAP_UNLOCK(pm);
1248 	return (pa);
1249 }
1250 
1251 /*
1252  * Atomically extract and hold the physical page with the given
1253  * pmap and virtual address pair if that mapping permits the given
1254  * protection.
1255  */
1256 vm_page_t
1257 moea_extract_and_hold(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1258 {
1259 	struct	pvo_entry *pvo;
1260 	vm_page_t m;
1261         vm_paddr_t pa;
1262 
1263 	m = NULL;
1264 	pa = 0;
1265 	PMAP_LOCK(pmap);
1266 retry:
1267 	pvo = moea_pvo_find_va(pmap, va & ~ADDR_POFF, NULL);
1268 	if (pvo != NULL && (pvo->pvo_pte.pte.pte_hi & PTE_VALID) &&
1269 	    ((pvo->pvo_pte.pte.pte_lo & PTE_PP) == PTE_RW ||
1270 	     (prot & VM_PROT_WRITE) == 0)) {
1271 		if (vm_page_pa_tryrelock(pmap, pvo->pvo_pte.pte.pte_lo & PTE_RPGN, &pa))
1272 			goto retry;
1273 		m = PHYS_TO_VM_PAGE(pvo->pvo_pte.pte.pte_lo & PTE_RPGN);
1274 		vm_page_hold(m);
1275 	}
1276 	PA_UNLOCK_COND(pa);
1277 	PMAP_UNLOCK(pmap);
1278 	return (m);
1279 }
1280 
1281 void
1282 moea_init(mmu_t mmu)
1283 {
1284 
1285 	moea_upvo_zone = uma_zcreate("UPVO entry", sizeof (struct pvo_entry),
1286 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1287 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1288 	moea_mpvo_zone = uma_zcreate("MPVO entry", sizeof(struct pvo_entry),
1289 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
1290 	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
1291 	moea_initialized = TRUE;
1292 }
1293 
1294 boolean_t
1295 moea_is_referenced(mmu_t mmu, vm_page_t m)
1296 {
1297 	boolean_t rv;
1298 
1299 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1300 	    ("moea_is_referenced: page %p is not managed", m));
1301 	rw_wlock(&pvh_global_lock);
1302 	rv = moea_query_bit(m, PTE_REF);
1303 	rw_wunlock(&pvh_global_lock);
1304 	return (rv);
1305 }
1306 
1307 boolean_t
1308 moea_is_modified(mmu_t mmu, vm_page_t m)
1309 {
1310 	boolean_t rv;
1311 
1312 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1313 	    ("moea_is_modified: page %p is not managed", m));
1314 
1315 	/*
1316 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
1317 	 * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
1318 	 * is clear, no PTEs can have PTE_CHG set.
1319 	 */
1320 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1321 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
1322 		return (FALSE);
1323 	rw_wlock(&pvh_global_lock);
1324 	rv = moea_query_bit(m, PTE_CHG);
1325 	rw_wunlock(&pvh_global_lock);
1326 	return (rv);
1327 }
1328 
1329 boolean_t
1330 moea_is_prefaultable(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1331 {
1332 	struct pvo_entry *pvo;
1333 	boolean_t rv;
1334 
1335 	PMAP_LOCK(pmap);
1336 	pvo = moea_pvo_find_va(pmap, va & ~ADDR_POFF, NULL);
1337 	rv = pvo == NULL || (pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0;
1338 	PMAP_UNLOCK(pmap);
1339 	return (rv);
1340 }
1341 
1342 void
1343 moea_clear_modify(mmu_t mmu, vm_page_t m)
1344 {
1345 
1346 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1347 	    ("moea_clear_modify: page %p is not managed", m));
1348 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1349 	KASSERT(!vm_page_xbusied(m),
1350 	    ("moea_clear_modify: page %p is exclusive busy", m));
1351 
1352 	/*
1353 	 * If the page is not PGA_WRITEABLE, then no PTEs can have PTE_CHG
1354 	 * set.  If the object containing the page is locked and the page is
1355 	 * not exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
1356 	 */
1357 	if ((m->aflags & PGA_WRITEABLE) == 0)
1358 		return;
1359 	rw_wlock(&pvh_global_lock);
1360 	moea_clear_bit(m, PTE_CHG);
1361 	rw_wunlock(&pvh_global_lock);
1362 }
1363 
1364 /*
1365  * Clear the write and modified bits in each of the given page's mappings.
1366  */
1367 void
1368 moea_remove_write(mmu_t mmu, vm_page_t m)
1369 {
1370 	struct	pvo_entry *pvo;
1371 	struct	pte *pt;
1372 	pmap_t	pmap;
1373 	u_int	lo;
1374 
1375 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1376 	    ("moea_remove_write: page %p is not managed", m));
1377 
1378 	/*
1379 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
1380 	 * set by another thread while the object is locked.  Thus,
1381 	 * if PGA_WRITEABLE is clear, no page table entries need updating.
1382 	 */
1383 	VM_OBJECT_ASSERT_WLOCKED(m->object);
1384 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
1385 		return;
1386 	rw_wlock(&pvh_global_lock);
1387 	lo = moea_attr_fetch(m);
1388 	powerpc_sync();
1389 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1390 		pmap = pvo->pvo_pmap;
1391 		PMAP_LOCK(pmap);
1392 		if ((pvo->pvo_pte.pte.pte_lo & PTE_PP) != PTE_BR) {
1393 			pt = moea_pvo_to_pte(pvo, -1);
1394 			pvo->pvo_pte.pte.pte_lo &= ~PTE_PP;
1395 			pvo->pvo_pte.pte.pte_lo |= PTE_BR;
1396 			if (pt != NULL) {
1397 				moea_pte_synch(pt, &pvo->pvo_pte.pte);
1398 				lo |= pvo->pvo_pte.pte.pte_lo;
1399 				pvo->pvo_pte.pte.pte_lo &= ~PTE_CHG;
1400 				moea_pte_change(pt, &pvo->pvo_pte.pte,
1401 				    pvo->pvo_vaddr);
1402 				mtx_unlock(&moea_table_mutex);
1403 			}
1404 		}
1405 		PMAP_UNLOCK(pmap);
1406 	}
1407 	if ((lo & PTE_CHG) != 0) {
1408 		moea_attr_clear(m, PTE_CHG);
1409 		vm_page_dirty(m);
1410 	}
1411 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1412 	rw_wunlock(&pvh_global_lock);
1413 }
1414 
1415 /*
1416  *	moea_ts_referenced:
1417  *
1418  *	Return a count of reference bits for a page, clearing those bits.
1419  *	It is not necessary for every reference bit to be cleared, but it
1420  *	is necessary that 0 only be returned when there are truly no
1421  *	reference bits set.
1422  *
1423  *	XXX: The exact number of bits to check and clear is a matter that
1424  *	should be tested and standardized at some point in the future for
1425  *	optimal aging of shared pages.
1426  */
1427 int
1428 moea_ts_referenced(mmu_t mmu, vm_page_t m)
1429 {
1430 	int count;
1431 
1432 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1433 	    ("moea_ts_referenced: page %p is not managed", m));
1434 	rw_wlock(&pvh_global_lock);
1435 	count = moea_clear_bit(m, PTE_REF);
1436 	rw_wunlock(&pvh_global_lock);
1437 	return (count);
1438 }
1439 
1440 /*
1441  * Modify the WIMG settings of all mappings for a page.
1442  */
1443 void
1444 moea_page_set_memattr(mmu_t mmu, vm_page_t m, vm_memattr_t ma)
1445 {
1446 	struct	pvo_entry *pvo;
1447 	struct	pvo_head *pvo_head;
1448 	struct	pte *pt;
1449 	pmap_t	pmap;
1450 	u_int	lo;
1451 
1452 	if ((m->oflags & VPO_UNMANAGED) != 0) {
1453 		m->md.mdpg_cache_attrs = ma;
1454 		return;
1455 	}
1456 
1457 	rw_wlock(&pvh_global_lock);
1458 	pvo_head = vm_page_to_pvoh(m);
1459 	lo = moea_calc_wimg(VM_PAGE_TO_PHYS(m), ma);
1460 
1461 	LIST_FOREACH(pvo, pvo_head, pvo_vlink) {
1462 		pmap = pvo->pvo_pmap;
1463 		PMAP_LOCK(pmap);
1464 		pt = moea_pvo_to_pte(pvo, -1);
1465 		pvo->pvo_pte.pte.pte_lo &= ~PTE_WIMG;
1466 		pvo->pvo_pte.pte.pte_lo |= lo;
1467 		if (pt != NULL) {
1468 			moea_pte_change(pt, &pvo->pvo_pte.pte,
1469 			    pvo->pvo_vaddr);
1470 			if (pvo->pvo_pmap == kernel_pmap)
1471 				isync();
1472 		}
1473 		mtx_unlock(&moea_table_mutex);
1474 		PMAP_UNLOCK(pmap);
1475 	}
1476 	m->md.mdpg_cache_attrs = ma;
1477 	rw_wunlock(&pvh_global_lock);
1478 }
1479 
1480 /*
1481  * Map a wired page into kernel virtual address space.
1482  */
1483 void
1484 moea_kenter(mmu_t mmu, vm_offset_t va, vm_paddr_t pa)
1485 {
1486 
1487 	moea_kenter_attr(mmu, va, pa, VM_MEMATTR_DEFAULT);
1488 }
1489 
1490 void
1491 moea_kenter_attr(mmu_t mmu, vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1492 {
1493 	u_int		pte_lo;
1494 	int		error;
1495 
1496 #if 0
1497 	if (va < VM_MIN_KERNEL_ADDRESS)
1498 		panic("moea_kenter: attempt to enter non-kernel address %#x",
1499 		    va);
1500 #endif
1501 
1502 	pte_lo = moea_calc_wimg(pa, ma);
1503 
1504 	PMAP_LOCK(kernel_pmap);
1505 	error = moea_pvo_enter(kernel_pmap, moea_upvo_zone,
1506 	    &moea_pvo_kunmanaged, va, pa, pte_lo, PVO_WIRED);
1507 
1508 	if (error != 0 && error != ENOENT)
1509 		panic("moea_kenter: failed to enter va %#x pa %#x: %d", va,
1510 		    pa, error);
1511 
1512 	PMAP_UNLOCK(kernel_pmap);
1513 }
1514 
1515 /*
1516  * Extract the physical page address associated with the given kernel virtual
1517  * address.
1518  */
1519 vm_paddr_t
1520 moea_kextract(mmu_t mmu, vm_offset_t va)
1521 {
1522 	struct		pvo_entry *pvo;
1523 	vm_paddr_t pa;
1524 
1525 	/*
1526 	 * Allow direct mappings on 32-bit OEA
1527 	 */
1528 	if (va < VM_MIN_KERNEL_ADDRESS) {
1529 		return (va);
1530 	}
1531 
1532 	PMAP_LOCK(kernel_pmap);
1533 	pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF, NULL);
1534 	KASSERT(pvo != NULL, ("moea_kextract: no addr found"));
1535 	pa = (pvo->pvo_pte.pte.pte_lo & PTE_RPGN) | (va & ADDR_POFF);
1536 	PMAP_UNLOCK(kernel_pmap);
1537 	return (pa);
1538 }
1539 
1540 /*
1541  * Remove a wired page from kernel virtual address space.
1542  */
1543 void
1544 moea_kremove(mmu_t mmu, vm_offset_t va)
1545 {
1546 
1547 	moea_remove(mmu, kernel_pmap, va, va + PAGE_SIZE);
1548 }
1549 
1550 /*
1551  * Map a range of physical addresses into kernel virtual address space.
1552  *
1553  * The value passed in *virt is a suggested virtual address for the mapping.
1554  * Architectures which can support a direct-mapped physical to virtual region
1555  * can return the appropriate address within that region, leaving '*virt'
1556  * unchanged.  We cannot and therefore do not; *virt is updated with the
1557  * first usable address after the mapped region.
1558  */
1559 vm_offset_t
1560 moea_map(mmu_t mmu, vm_offset_t *virt, vm_paddr_t pa_start,
1561     vm_paddr_t pa_end, int prot)
1562 {
1563 	vm_offset_t	sva, va;
1564 
1565 	sva = *virt;
1566 	va = sva;
1567 	for (; pa_start < pa_end; pa_start += PAGE_SIZE, va += PAGE_SIZE)
1568 		moea_kenter(mmu, va, pa_start);
1569 	*virt = va;
1570 	return (sva);
1571 }
1572 
1573 /*
1574  * Returns true if the pmap's pv is one of the first
1575  * 16 pvs linked to from this page.  This count may
1576  * be changed upwards or downwards in the future; it
1577  * is only necessary that true be returned for a small
1578  * subset of pmaps for proper page aging.
1579  */
1580 boolean_t
1581 moea_page_exists_quick(mmu_t mmu, pmap_t pmap, vm_page_t m)
1582 {
1583         int loops;
1584 	struct pvo_entry *pvo;
1585 	boolean_t rv;
1586 
1587 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1588 	    ("moea_page_exists_quick: page %p is not managed", m));
1589 	loops = 0;
1590 	rv = FALSE;
1591 	rw_wlock(&pvh_global_lock);
1592 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
1593 		if (pvo->pvo_pmap == pmap) {
1594 			rv = TRUE;
1595 			break;
1596 		}
1597 		if (++loops >= 16)
1598 			break;
1599 	}
1600 	rw_wunlock(&pvh_global_lock);
1601 	return (rv);
1602 }
1603 
1604 /*
1605  * Return the number of managed mappings to the given physical page
1606  * that are wired.
1607  */
1608 int
1609 moea_page_wired_mappings(mmu_t mmu, vm_page_t m)
1610 {
1611 	struct pvo_entry *pvo;
1612 	int count;
1613 
1614 	count = 0;
1615 	if ((m->oflags & VPO_UNMANAGED) != 0)
1616 		return (count);
1617 	rw_wlock(&pvh_global_lock);
1618 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink)
1619 		if ((pvo->pvo_vaddr & PVO_WIRED) != 0)
1620 			count++;
1621 	rw_wunlock(&pvh_global_lock);
1622 	return (count);
1623 }
1624 
1625 static u_int	moea_vsidcontext;
1626 
1627 void
1628 moea_pinit(mmu_t mmu, pmap_t pmap)
1629 {
1630 	int	i, mask;
1631 	u_int	entropy;
1632 
1633 	KASSERT((int)pmap < VM_MIN_KERNEL_ADDRESS, ("moea_pinit: virt pmap"));
1634 	RB_INIT(&pmap->pmap_pvo);
1635 
1636 	entropy = 0;
1637 	__asm __volatile("mftb %0" : "=r"(entropy));
1638 
1639 	if ((pmap->pmap_phys = (pmap_t)moea_kextract(mmu, (vm_offset_t)pmap))
1640 	    == NULL) {
1641 		pmap->pmap_phys = pmap;
1642 	}
1643 
1644 
1645 	mtx_lock(&moea_vsid_mutex);
1646 	/*
1647 	 * Allocate some segment registers for this pmap.
1648 	 */
1649 	for (i = 0; i < NPMAPS; i += VSID_NBPW) {
1650 		u_int	hash, n;
1651 
1652 		/*
1653 		 * Create a new value by mutiplying by a prime and adding in
1654 		 * entropy from the timebase register.  This is to make the
1655 		 * VSID more random so that the PT hash function collides
1656 		 * less often.  (Note that the prime casues gcc to do shifts
1657 		 * instead of a multiply.)
1658 		 */
1659 		moea_vsidcontext = (moea_vsidcontext * 0x1105) + entropy;
1660 		hash = moea_vsidcontext & (NPMAPS - 1);
1661 		if (hash == 0)		/* 0 is special, avoid it */
1662 			continue;
1663 		n = hash >> 5;
1664 		mask = 1 << (hash & (VSID_NBPW - 1));
1665 		hash = (moea_vsidcontext & 0xfffff);
1666 		if (moea_vsid_bitmap[n] & mask) {	/* collision? */
1667 			/* anything free in this bucket? */
1668 			if (moea_vsid_bitmap[n] == 0xffffffff) {
1669 				entropy = (moea_vsidcontext >> 20);
1670 				continue;
1671 			}
1672 			i = ffs(~moea_vsid_bitmap[n]) - 1;
1673 			mask = 1 << i;
1674 			hash &= 0xfffff & ~(VSID_NBPW - 1);
1675 			hash |= i;
1676 		}
1677 		KASSERT(!(moea_vsid_bitmap[n] & mask),
1678 		    ("Allocating in-use VSID group %#x\n", hash));
1679 		moea_vsid_bitmap[n] |= mask;
1680 		for (i = 0; i < 16; i++)
1681 			pmap->pm_sr[i] = VSID_MAKE(i, hash);
1682 		mtx_unlock(&moea_vsid_mutex);
1683 		return;
1684 	}
1685 
1686 	mtx_unlock(&moea_vsid_mutex);
1687 	panic("moea_pinit: out of segments");
1688 }
1689 
1690 /*
1691  * Initialize the pmap associated with process 0.
1692  */
1693 void
1694 moea_pinit0(mmu_t mmu, pmap_t pm)
1695 {
1696 
1697 	PMAP_LOCK_INIT(pm);
1698 	moea_pinit(mmu, pm);
1699 	bzero(&pm->pm_stats, sizeof(pm->pm_stats));
1700 }
1701 
1702 /*
1703  * Set the physical protection on the specified range of this map as requested.
1704  */
1705 void
1706 moea_protect(mmu_t mmu, pmap_t pm, vm_offset_t sva, vm_offset_t eva,
1707     vm_prot_t prot)
1708 {
1709 	struct	pvo_entry *pvo, *tpvo, key;
1710 	struct	pte *pt;
1711 
1712 	KASSERT(pm == &curproc->p_vmspace->vm_pmap || pm == kernel_pmap,
1713 	    ("moea_protect: non current pmap"));
1714 
1715 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1716 		moea_remove(mmu, pm, sva, eva);
1717 		return;
1718 	}
1719 
1720 	rw_wlock(&pvh_global_lock);
1721 	PMAP_LOCK(pm);
1722 	key.pvo_vaddr = sva;
1723 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1724 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
1725 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
1726 
1727 		/*
1728 		 * Grab the PTE pointer before we diddle with the cached PTE
1729 		 * copy.
1730 		 */
1731 		pt = moea_pvo_to_pte(pvo, -1);
1732 		/*
1733 		 * Change the protection of the page.
1734 		 */
1735 		pvo->pvo_pte.pte.pte_lo &= ~PTE_PP;
1736 		pvo->pvo_pte.pte.pte_lo |= PTE_BR;
1737 
1738 		/*
1739 		 * If the PVO is in the page table, update that pte as well.
1740 		 */
1741 		if (pt != NULL) {
1742 			moea_pte_change(pt, &pvo->pvo_pte.pte, pvo->pvo_vaddr);
1743 			mtx_unlock(&moea_table_mutex);
1744 		}
1745 	}
1746 	rw_wunlock(&pvh_global_lock);
1747 	PMAP_UNLOCK(pm);
1748 }
1749 
1750 /*
1751  * Map a list of wired pages into kernel virtual address space.  This is
1752  * intended for temporary mappings which do not need page modification or
1753  * references recorded.  Existing mappings in the region are overwritten.
1754  */
1755 void
1756 moea_qenter(mmu_t mmu, vm_offset_t sva, vm_page_t *m, int count)
1757 {
1758 	vm_offset_t va;
1759 
1760 	va = sva;
1761 	while (count-- > 0) {
1762 		moea_kenter(mmu, va, VM_PAGE_TO_PHYS(*m));
1763 		va += PAGE_SIZE;
1764 		m++;
1765 	}
1766 }
1767 
1768 /*
1769  * Remove page mappings from kernel virtual address space.  Intended for
1770  * temporary mappings entered by moea_qenter.
1771  */
1772 void
1773 moea_qremove(mmu_t mmu, vm_offset_t sva, int count)
1774 {
1775 	vm_offset_t va;
1776 
1777 	va = sva;
1778 	while (count-- > 0) {
1779 		moea_kremove(mmu, va);
1780 		va += PAGE_SIZE;
1781 	}
1782 }
1783 
1784 void
1785 moea_release(mmu_t mmu, pmap_t pmap)
1786 {
1787         int idx, mask;
1788 
1789 	/*
1790 	 * Free segment register's VSID
1791 	 */
1792         if (pmap->pm_sr[0] == 0)
1793                 panic("moea_release");
1794 
1795 	mtx_lock(&moea_vsid_mutex);
1796         idx = VSID_TO_HASH(pmap->pm_sr[0]) & (NPMAPS-1);
1797         mask = 1 << (idx % VSID_NBPW);
1798         idx /= VSID_NBPW;
1799         moea_vsid_bitmap[idx] &= ~mask;
1800 	mtx_unlock(&moea_vsid_mutex);
1801 }
1802 
1803 /*
1804  * Remove the given range of addresses from the specified map.
1805  */
1806 void
1807 moea_remove(mmu_t mmu, pmap_t pm, vm_offset_t sva, vm_offset_t eva)
1808 {
1809 	struct	pvo_entry *pvo, *tpvo, key;
1810 
1811 	rw_wlock(&pvh_global_lock);
1812 	PMAP_LOCK(pm);
1813 	key.pvo_vaddr = sva;
1814 	for (pvo = RB_NFIND(pvo_tree, &pm->pmap_pvo, &key);
1815 	    pvo != NULL && PVO_VADDR(pvo) < eva; pvo = tpvo) {
1816 		tpvo = RB_NEXT(pvo_tree, &pm->pmap_pvo, pvo);
1817 		moea_pvo_remove(pvo, -1);
1818 	}
1819 	PMAP_UNLOCK(pm);
1820 	rw_wunlock(&pvh_global_lock);
1821 }
1822 
1823 /*
1824  * Remove physical page from all pmaps in which it resides. moea_pvo_remove()
1825  * will reflect changes in pte's back to the vm_page.
1826  */
1827 void
1828 moea_remove_all(mmu_t mmu, vm_page_t m)
1829 {
1830 	struct  pvo_head *pvo_head;
1831 	struct	pvo_entry *pvo, *next_pvo;
1832 	pmap_t	pmap;
1833 
1834 	rw_wlock(&pvh_global_lock);
1835 	pvo_head = vm_page_to_pvoh(m);
1836 	for (pvo = LIST_FIRST(pvo_head); pvo != NULL; pvo = next_pvo) {
1837 		next_pvo = LIST_NEXT(pvo, pvo_vlink);
1838 
1839 		pmap = pvo->pvo_pmap;
1840 		PMAP_LOCK(pmap);
1841 		moea_pvo_remove(pvo, -1);
1842 		PMAP_UNLOCK(pmap);
1843 	}
1844 	if ((m->aflags & PGA_WRITEABLE) && moea_query_bit(m, PTE_CHG)) {
1845 		moea_attr_clear(m, PTE_CHG);
1846 		vm_page_dirty(m);
1847 	}
1848 	vm_page_aflag_clear(m, PGA_WRITEABLE);
1849 	rw_wunlock(&pvh_global_lock);
1850 }
1851 
1852 /*
1853  * Allocate a physical page of memory directly from the phys_avail map.
1854  * Can only be called from moea_bootstrap before avail start and end are
1855  * calculated.
1856  */
1857 static vm_offset_t
1858 moea_bootstrap_alloc(vm_size_t size, u_int align)
1859 {
1860 	vm_offset_t	s, e;
1861 	int		i, j;
1862 
1863 	size = round_page(size);
1864 	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
1865 		if (align != 0)
1866 			s = (phys_avail[i] + align - 1) & ~(align - 1);
1867 		else
1868 			s = phys_avail[i];
1869 		e = s + size;
1870 
1871 		if (s < phys_avail[i] || e > phys_avail[i + 1])
1872 			continue;
1873 
1874 		if (s == phys_avail[i]) {
1875 			phys_avail[i] += size;
1876 		} else if (e == phys_avail[i + 1]) {
1877 			phys_avail[i + 1] -= size;
1878 		} else {
1879 			for (j = phys_avail_count * 2; j > i; j -= 2) {
1880 				phys_avail[j] = phys_avail[j - 2];
1881 				phys_avail[j + 1] = phys_avail[j - 1];
1882 			}
1883 
1884 			phys_avail[i + 3] = phys_avail[i + 1];
1885 			phys_avail[i + 1] = s;
1886 			phys_avail[i + 2] = e;
1887 			phys_avail_count++;
1888 		}
1889 
1890 		return (s);
1891 	}
1892 	panic("moea_bootstrap_alloc: could not allocate memory");
1893 }
1894 
1895 static void
1896 moea_syncicache(vm_paddr_t pa, vm_size_t len)
1897 {
1898 	__syncicache((void *)pa, len);
1899 }
1900 
1901 static int
1902 moea_pvo_enter(pmap_t pm, uma_zone_t zone, struct pvo_head *pvo_head,
1903     vm_offset_t va, vm_paddr_t pa, u_int pte_lo, int flags)
1904 {
1905 	struct	pvo_entry *pvo;
1906 	u_int	sr;
1907 	int	first;
1908 	u_int	ptegidx;
1909 	int	i;
1910 	int     bootstrap;
1911 
1912 	moea_pvo_enter_calls++;
1913 	first = 0;
1914 	bootstrap = 0;
1915 
1916 	/*
1917 	 * Compute the PTE Group index.
1918 	 */
1919 	va &= ~ADDR_POFF;
1920 	sr = va_to_sr(pm->pm_sr, va);
1921 	ptegidx = va_to_pteg(sr, va);
1922 
1923 	/*
1924 	 * Remove any existing mapping for this page.  Reuse the pvo entry if
1925 	 * there is a mapping.
1926 	 */
1927 	mtx_lock(&moea_table_mutex);
1928 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
1929 		if (pvo->pvo_pmap == pm && PVO_VADDR(pvo) == va) {
1930 			if ((pvo->pvo_pte.pte.pte_lo & PTE_RPGN) == pa &&
1931 			    (pvo->pvo_pte.pte.pte_lo & PTE_PP) ==
1932 			    (pte_lo & PTE_PP)) {
1933 				/*
1934 				 * The PTE is not changing.  Instead, this may
1935 				 * be a request to change the mapping's wired
1936 				 * attribute.
1937 				 */
1938 				mtx_unlock(&moea_table_mutex);
1939 				if ((flags & PVO_WIRED) != 0 &&
1940 				    (pvo->pvo_vaddr & PVO_WIRED) == 0) {
1941 					pvo->pvo_vaddr |= PVO_WIRED;
1942 					pm->pm_stats.wired_count++;
1943 				} else if ((flags & PVO_WIRED) == 0 &&
1944 				    (pvo->pvo_vaddr & PVO_WIRED) != 0) {
1945 					pvo->pvo_vaddr &= ~PVO_WIRED;
1946 					pm->pm_stats.wired_count--;
1947 				}
1948 				return (0);
1949 			}
1950 			moea_pvo_remove(pvo, -1);
1951 			break;
1952 		}
1953 	}
1954 
1955 	/*
1956 	 * If we aren't overwriting a mapping, try to allocate.
1957 	 */
1958 	if (moea_initialized) {
1959 		pvo = uma_zalloc(zone, M_NOWAIT);
1960 	} else {
1961 		if (moea_bpvo_pool_index >= BPVO_POOL_SIZE) {
1962 			panic("moea_enter: bpvo pool exhausted, %d, %d, %d",
1963 			      moea_bpvo_pool_index, BPVO_POOL_SIZE,
1964 			      BPVO_POOL_SIZE * sizeof(struct pvo_entry));
1965 		}
1966 		pvo = &moea_bpvo_pool[moea_bpvo_pool_index];
1967 		moea_bpvo_pool_index++;
1968 		bootstrap = 1;
1969 	}
1970 
1971 	if (pvo == NULL) {
1972 		mtx_unlock(&moea_table_mutex);
1973 		return (ENOMEM);
1974 	}
1975 
1976 	moea_pvo_entries++;
1977 	pvo->pvo_vaddr = va;
1978 	pvo->pvo_pmap = pm;
1979 	LIST_INSERT_HEAD(&moea_pvo_table[ptegidx], pvo, pvo_olink);
1980 	pvo->pvo_vaddr &= ~ADDR_POFF;
1981 	if (flags & PVO_WIRED)
1982 		pvo->pvo_vaddr |= PVO_WIRED;
1983 	if (pvo_head != &moea_pvo_kunmanaged)
1984 		pvo->pvo_vaddr |= PVO_MANAGED;
1985 	if (bootstrap)
1986 		pvo->pvo_vaddr |= PVO_BOOTSTRAP;
1987 
1988 	moea_pte_create(&pvo->pvo_pte.pte, sr, va, pa | pte_lo);
1989 
1990 	/*
1991 	 * Add to pmap list
1992 	 */
1993 	RB_INSERT(pvo_tree, &pm->pmap_pvo, pvo);
1994 
1995 	/*
1996 	 * Remember if the list was empty and therefore will be the first
1997 	 * item.
1998 	 */
1999 	if (LIST_FIRST(pvo_head) == NULL)
2000 		first = 1;
2001 	LIST_INSERT_HEAD(pvo_head, pvo, pvo_vlink);
2002 
2003 	if (pvo->pvo_vaddr & PVO_WIRED)
2004 		pm->pm_stats.wired_count++;
2005 	pm->pm_stats.resident_count++;
2006 
2007 	i = moea_pte_insert(ptegidx, &pvo->pvo_pte.pte);
2008 	KASSERT(i < 8, ("Invalid PTE index"));
2009 	if (i >= 0) {
2010 		PVO_PTEGIDX_SET(pvo, i);
2011 	} else {
2012 		panic("moea_pvo_enter: overflow");
2013 		moea_pte_overflow++;
2014 	}
2015 	mtx_unlock(&moea_table_mutex);
2016 
2017 	return (first ? ENOENT : 0);
2018 }
2019 
2020 static void
2021 moea_pvo_remove(struct pvo_entry *pvo, int pteidx)
2022 {
2023 	struct	pte *pt;
2024 
2025 	/*
2026 	 * If there is an active pte entry, we need to deactivate it (and
2027 	 * save the ref & cfg bits).
2028 	 */
2029 	pt = moea_pvo_to_pte(pvo, pteidx);
2030 	if (pt != NULL) {
2031 		moea_pte_unset(pt, &pvo->pvo_pte.pte, pvo->pvo_vaddr);
2032 		mtx_unlock(&moea_table_mutex);
2033 		PVO_PTEGIDX_CLR(pvo);
2034 	} else {
2035 		moea_pte_overflow--;
2036 	}
2037 
2038 	/*
2039 	 * Update our statistics.
2040 	 */
2041 	pvo->pvo_pmap->pm_stats.resident_count--;
2042 	if (pvo->pvo_vaddr & PVO_WIRED)
2043 		pvo->pvo_pmap->pm_stats.wired_count--;
2044 
2045 	/*
2046 	 * Save the REF/CHG bits into their cache if the page is managed.
2047 	 */
2048 	if ((pvo->pvo_vaddr & PVO_MANAGED) == PVO_MANAGED) {
2049 		struct	vm_page *pg;
2050 
2051 		pg = PHYS_TO_VM_PAGE(pvo->pvo_pte.pte.pte_lo & PTE_RPGN);
2052 		if (pg != NULL) {
2053 			moea_attr_save(pg, pvo->pvo_pte.pte.pte_lo &
2054 			    (PTE_REF | PTE_CHG));
2055 		}
2056 	}
2057 
2058 	/*
2059 	 * Remove this PVO from the PV and pmap lists.
2060 	 */
2061 	LIST_REMOVE(pvo, pvo_vlink);
2062 	RB_REMOVE(pvo_tree, &pvo->pvo_pmap->pmap_pvo, pvo);
2063 
2064 	/*
2065 	 * Remove this from the overflow list and return it to the pool
2066 	 * if we aren't going to reuse it.
2067 	 */
2068 	LIST_REMOVE(pvo, pvo_olink);
2069 	if (!(pvo->pvo_vaddr & PVO_BOOTSTRAP))
2070 		uma_zfree(pvo->pvo_vaddr & PVO_MANAGED ? moea_mpvo_zone :
2071 		    moea_upvo_zone, pvo);
2072 	moea_pvo_entries--;
2073 	moea_pvo_remove_calls++;
2074 }
2075 
2076 static __inline int
2077 moea_pvo_pte_index(const struct pvo_entry *pvo, int ptegidx)
2078 {
2079 	int	pteidx;
2080 
2081 	/*
2082 	 * We can find the actual pte entry without searching by grabbing
2083 	 * the PTEG index from 3 unused bits in pte_lo[11:9] and by
2084 	 * noticing the HID bit.
2085 	 */
2086 	pteidx = ptegidx * 8 + PVO_PTEGIDX_GET(pvo);
2087 	if (pvo->pvo_pte.pte.pte_hi & PTE_HID)
2088 		pteidx ^= moea_pteg_mask * 8;
2089 
2090 	return (pteidx);
2091 }
2092 
2093 static struct pvo_entry *
2094 moea_pvo_find_va(pmap_t pm, vm_offset_t va, int *pteidx_p)
2095 {
2096 	struct	pvo_entry *pvo;
2097 	int	ptegidx;
2098 	u_int	sr;
2099 
2100 	va &= ~ADDR_POFF;
2101 	sr = va_to_sr(pm->pm_sr, va);
2102 	ptegidx = va_to_pteg(sr, va);
2103 
2104 	mtx_lock(&moea_table_mutex);
2105 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
2106 		if (pvo->pvo_pmap == pm && PVO_VADDR(pvo) == va) {
2107 			if (pteidx_p)
2108 				*pteidx_p = moea_pvo_pte_index(pvo, ptegidx);
2109 			break;
2110 		}
2111 	}
2112 	mtx_unlock(&moea_table_mutex);
2113 
2114 	return (pvo);
2115 }
2116 
2117 static struct pte *
2118 moea_pvo_to_pte(const struct pvo_entry *pvo, int pteidx)
2119 {
2120 	struct	pte *pt;
2121 
2122 	/*
2123 	 * If we haven't been supplied the ptegidx, calculate it.
2124 	 */
2125 	if (pteidx == -1) {
2126 		int	ptegidx;
2127 		u_int	sr;
2128 
2129 		sr = va_to_sr(pvo->pvo_pmap->pm_sr, pvo->pvo_vaddr);
2130 		ptegidx = va_to_pteg(sr, pvo->pvo_vaddr);
2131 		pteidx = moea_pvo_pte_index(pvo, ptegidx);
2132 	}
2133 
2134 	pt = &moea_pteg_table[pteidx >> 3].pt[pteidx & 7];
2135 	mtx_lock(&moea_table_mutex);
2136 
2137 	if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) && !PVO_PTEGIDX_ISSET(pvo)) {
2138 		panic("moea_pvo_to_pte: pvo %p has valid pte in pvo but no "
2139 		    "valid pte index", pvo);
2140 	}
2141 
2142 	if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0 && PVO_PTEGIDX_ISSET(pvo)) {
2143 		panic("moea_pvo_to_pte: pvo %p has valid pte index in pvo "
2144 		    "pvo but no valid pte", pvo);
2145 	}
2146 
2147 	if ((pt->pte_hi ^ (pvo->pvo_pte.pte.pte_hi & ~PTE_VALID)) == PTE_VALID) {
2148 		if ((pvo->pvo_pte.pte.pte_hi & PTE_VALID) == 0) {
2149 			panic("moea_pvo_to_pte: pvo %p has valid pte in "
2150 			    "moea_pteg_table %p but invalid in pvo", pvo, pt);
2151 		}
2152 
2153 		if (((pt->pte_lo ^ pvo->pvo_pte.pte.pte_lo) & ~(PTE_CHG|PTE_REF))
2154 		    != 0) {
2155 			panic("moea_pvo_to_pte: pvo %p pte does not match "
2156 			    "pte %p in moea_pteg_table", pvo, pt);
2157 		}
2158 
2159 		mtx_assert(&moea_table_mutex, MA_OWNED);
2160 		return (pt);
2161 	}
2162 
2163 	if (pvo->pvo_pte.pte.pte_hi & PTE_VALID) {
2164 		panic("moea_pvo_to_pte: pvo %p has invalid pte %p in "
2165 		    "moea_pteg_table but valid in pvo: %8x, %8x", pvo, pt, pvo->pvo_pte.pte.pte_hi, pt->pte_hi);
2166 	}
2167 
2168 	mtx_unlock(&moea_table_mutex);
2169 	return (NULL);
2170 }
2171 
2172 /*
2173  * XXX: THIS STUFF SHOULD BE IN pte.c?
2174  */
2175 int
2176 moea_pte_spill(vm_offset_t addr)
2177 {
2178 	struct	pvo_entry *source_pvo, *victim_pvo;
2179 	struct	pvo_entry *pvo;
2180 	int	ptegidx, i, j;
2181 	u_int	sr;
2182 	struct	pteg *pteg;
2183 	struct	pte *pt;
2184 
2185 	moea_pte_spills++;
2186 
2187 	sr = mfsrin(addr);
2188 	ptegidx = va_to_pteg(sr, addr);
2189 
2190 	/*
2191 	 * Have to substitute some entry.  Use the primary hash for this.
2192 	 * Use low bits of timebase as random generator.
2193 	 */
2194 	pteg = &moea_pteg_table[ptegidx];
2195 	mtx_lock(&moea_table_mutex);
2196 	__asm __volatile("mftb %0" : "=r"(i));
2197 	i &= 7;
2198 	pt = &pteg->pt[i];
2199 
2200 	source_pvo = NULL;
2201 	victim_pvo = NULL;
2202 	LIST_FOREACH(pvo, &moea_pvo_table[ptegidx], pvo_olink) {
2203 		/*
2204 		 * We need to find a pvo entry for this address.
2205 		 */
2206 		if (source_pvo == NULL &&
2207 		    moea_pte_match(&pvo->pvo_pte.pte, sr, addr,
2208 		    pvo->pvo_pte.pte.pte_hi & PTE_HID)) {
2209 			/*
2210 			 * Now found an entry to be spilled into the pteg.
2211 			 * The PTE is now valid, so we know it's active.
2212 			 */
2213 			j = moea_pte_insert(ptegidx, &pvo->pvo_pte.pte);
2214 
2215 			if (j >= 0) {
2216 				PVO_PTEGIDX_SET(pvo, j);
2217 				moea_pte_overflow--;
2218 				mtx_unlock(&moea_table_mutex);
2219 				return (1);
2220 			}
2221 
2222 			source_pvo = pvo;
2223 
2224 			if (victim_pvo != NULL)
2225 				break;
2226 		}
2227 
2228 		/*
2229 		 * We also need the pvo entry of the victim we are replacing
2230 		 * so save the R & C bits of the PTE.
2231 		 */
2232 		if ((pt->pte_hi & PTE_HID) == 0 && victim_pvo == NULL &&
2233 		    moea_pte_compare(pt, &pvo->pvo_pte.pte)) {
2234 			victim_pvo = pvo;
2235 			if (source_pvo != NULL)
2236 				break;
2237 		}
2238 	}
2239 
2240 	if (source_pvo == NULL) {
2241 		mtx_unlock(&moea_table_mutex);
2242 		return (0);
2243 	}
2244 
2245 	if (victim_pvo == NULL) {
2246 		if ((pt->pte_hi & PTE_HID) == 0)
2247 			panic("moea_pte_spill: victim p-pte (%p) has no pvo"
2248 			    "entry", pt);
2249 
2250 		/*
2251 		 * If this is a secondary PTE, we need to search it's primary
2252 		 * pvo bucket for the matching PVO.
2253 		 */
2254 		LIST_FOREACH(pvo, &moea_pvo_table[ptegidx ^ moea_pteg_mask],
2255 		    pvo_olink) {
2256 			/*
2257 			 * We also need the pvo entry of the victim we are
2258 			 * replacing so save the R & C bits of the PTE.
2259 			 */
2260 			if (moea_pte_compare(pt, &pvo->pvo_pte.pte)) {
2261 				victim_pvo = pvo;
2262 				break;
2263 			}
2264 		}
2265 
2266 		if (victim_pvo == NULL)
2267 			panic("moea_pte_spill: victim s-pte (%p) has no pvo"
2268 			    "entry", pt);
2269 	}
2270 
2271 	/*
2272 	 * We are invalidating the TLB entry for the EA we are replacing even
2273 	 * though it's valid.  If we don't, we lose any ref/chg bit changes
2274 	 * contained in the TLB entry.
2275 	 */
2276 	source_pvo->pvo_pte.pte.pte_hi &= ~PTE_HID;
2277 
2278 	moea_pte_unset(pt, &victim_pvo->pvo_pte.pte, victim_pvo->pvo_vaddr);
2279 	moea_pte_set(pt, &source_pvo->pvo_pte.pte);
2280 
2281 	PVO_PTEGIDX_CLR(victim_pvo);
2282 	PVO_PTEGIDX_SET(source_pvo, i);
2283 	moea_pte_replacements++;
2284 
2285 	mtx_unlock(&moea_table_mutex);
2286 	return (1);
2287 }
2288 
2289 static __inline struct pvo_entry *
2290 moea_pte_spillable_ident(u_int ptegidx)
2291 {
2292 	struct	pte *pt;
2293 	struct	pvo_entry *pvo_walk, *pvo = NULL;
2294 
2295 	LIST_FOREACH(pvo_walk, &moea_pvo_table[ptegidx], pvo_olink) {
2296 		if (pvo_walk->pvo_vaddr & PVO_WIRED)
2297 			continue;
2298 
2299 		if (!(pvo_walk->pvo_pte.pte.pte_hi & PTE_VALID))
2300 			continue;
2301 
2302 		pt = moea_pvo_to_pte(pvo_walk, -1);
2303 
2304 		if (pt == NULL)
2305 			continue;
2306 
2307 		pvo = pvo_walk;
2308 
2309 		mtx_unlock(&moea_table_mutex);
2310 		if (!(pt->pte_lo & PTE_REF))
2311 			return (pvo_walk);
2312 	}
2313 
2314 	return (pvo);
2315 }
2316 
2317 static int
2318 moea_pte_insert(u_int ptegidx, struct pte *pvo_pt)
2319 {
2320 	struct	pte *pt;
2321 	struct	pvo_entry *victim_pvo;
2322 	int	i;
2323 	int	victim_idx;
2324 	u_int	pteg_bkpidx = ptegidx;
2325 
2326 	mtx_assert(&moea_table_mutex, MA_OWNED);
2327 
2328 	/*
2329 	 * First try primary hash.
2330 	 */
2331 	for (pt = moea_pteg_table[ptegidx].pt, i = 0; i < 8; i++, pt++) {
2332 		if ((pt->pte_hi & PTE_VALID) == 0) {
2333 			pvo_pt->pte_hi &= ~PTE_HID;
2334 			moea_pte_set(pt, pvo_pt);
2335 			return (i);
2336 		}
2337 	}
2338 
2339 	/*
2340 	 * Now try secondary hash.
2341 	 */
2342 	ptegidx ^= moea_pteg_mask;
2343 
2344 	for (pt = moea_pteg_table[ptegidx].pt, i = 0; i < 8; i++, pt++) {
2345 		if ((pt->pte_hi & PTE_VALID) == 0) {
2346 			pvo_pt->pte_hi |= PTE_HID;
2347 			moea_pte_set(pt, pvo_pt);
2348 			return (i);
2349 		}
2350 	}
2351 
2352 	/* Try again, but this time try to force a PTE out. */
2353 	ptegidx = pteg_bkpidx;
2354 
2355 	victim_pvo = moea_pte_spillable_ident(ptegidx);
2356 	if (victim_pvo == NULL) {
2357 		ptegidx ^= moea_pteg_mask;
2358 		victim_pvo = moea_pte_spillable_ident(ptegidx);
2359 	}
2360 
2361 	if (victim_pvo == NULL) {
2362 		panic("moea_pte_insert: overflow");
2363 		return (-1);
2364 	}
2365 
2366 	victim_idx = moea_pvo_pte_index(victim_pvo, ptegidx);
2367 
2368 	if (pteg_bkpidx == ptegidx)
2369 		pvo_pt->pte_hi &= ~PTE_HID;
2370 	else
2371 		pvo_pt->pte_hi |= PTE_HID;
2372 
2373 	/*
2374 	 * Synchronize the sacrifice PTE with its PVO, then mark both
2375 	 * invalid. The PVO will be reused when/if the VM system comes
2376 	 * here after a fault.
2377 	 */
2378 	pt = &moea_pteg_table[victim_idx >> 3].pt[victim_idx & 7];
2379 
2380 	if (pt->pte_hi != victim_pvo->pvo_pte.pte.pte_hi)
2381 	    panic("Victim PVO doesn't match PTE! PVO: %8x, PTE: %8x", victim_pvo->pvo_pte.pte.pte_hi, pt->pte_hi);
2382 
2383 	/*
2384 	 * Set the new PTE.
2385 	 */
2386 	moea_pte_unset(pt, &victim_pvo->pvo_pte.pte, victim_pvo->pvo_vaddr);
2387 	PVO_PTEGIDX_CLR(victim_pvo);
2388 	moea_pte_overflow++;
2389 	moea_pte_set(pt, pvo_pt);
2390 
2391 	return (victim_idx & 7);
2392 }
2393 
2394 static boolean_t
2395 moea_query_bit(vm_page_t m, int ptebit)
2396 {
2397 	struct	pvo_entry *pvo;
2398 	struct	pte *pt;
2399 
2400 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2401 	if (moea_attr_fetch(m) & ptebit)
2402 		return (TRUE);
2403 
2404 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2405 
2406 		/*
2407 		 * See if we saved the bit off.  If so, cache it and return
2408 		 * success.
2409 		 */
2410 		if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2411 			moea_attr_save(m, ptebit);
2412 			return (TRUE);
2413 		}
2414 	}
2415 
2416 	/*
2417 	 * No luck, now go through the hard part of looking at the PTEs
2418 	 * themselves.  Sync so that any pending REF/CHG bits are flushed to
2419 	 * the PTEs.
2420 	 */
2421 	powerpc_sync();
2422 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2423 
2424 		/*
2425 		 * See if this pvo has a valid PTE.  if so, fetch the
2426 		 * REF/CHG bits from the valid PTE.  If the appropriate
2427 		 * ptebit is set, cache it and return success.
2428 		 */
2429 		pt = moea_pvo_to_pte(pvo, -1);
2430 		if (pt != NULL) {
2431 			moea_pte_synch(pt, &pvo->pvo_pte.pte);
2432 			mtx_unlock(&moea_table_mutex);
2433 			if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2434 				moea_attr_save(m, ptebit);
2435 				return (TRUE);
2436 			}
2437 		}
2438 	}
2439 
2440 	return (FALSE);
2441 }
2442 
2443 static u_int
2444 moea_clear_bit(vm_page_t m, int ptebit)
2445 {
2446 	u_int	count;
2447 	struct	pvo_entry *pvo;
2448 	struct	pte *pt;
2449 
2450 	rw_assert(&pvh_global_lock, RA_WLOCKED);
2451 
2452 	/*
2453 	 * Clear the cached value.
2454 	 */
2455 	moea_attr_clear(m, ptebit);
2456 
2457 	/*
2458 	 * Sync so that any pending REF/CHG bits are flushed to the PTEs (so
2459 	 * we can reset the right ones).  note that since the pvo entries and
2460 	 * list heads are accessed via BAT0 and are never placed in the page
2461 	 * table, we don't have to worry about further accesses setting the
2462 	 * REF/CHG bits.
2463 	 */
2464 	powerpc_sync();
2465 
2466 	/*
2467 	 * For each pvo entry, clear the pvo's ptebit.  If this pvo has a
2468 	 * valid pte clear the ptebit from the valid pte.
2469 	 */
2470 	count = 0;
2471 	LIST_FOREACH(pvo, vm_page_to_pvoh(m), pvo_vlink) {
2472 		pt = moea_pvo_to_pte(pvo, -1);
2473 		if (pt != NULL) {
2474 			moea_pte_synch(pt, &pvo->pvo_pte.pte);
2475 			if (pvo->pvo_pte.pte.pte_lo & ptebit) {
2476 				count++;
2477 				moea_pte_clear(pt, PVO_VADDR(pvo), ptebit);
2478 			}
2479 			mtx_unlock(&moea_table_mutex);
2480 		}
2481 		pvo->pvo_pte.pte.pte_lo &= ~ptebit;
2482 	}
2483 
2484 	return (count);
2485 }
2486 
2487 /*
2488  * Return true if the physical range is encompassed by the battable[idx]
2489  */
2490 static int
2491 moea_bat_mapped(int idx, vm_paddr_t pa, vm_size_t size)
2492 {
2493 	u_int prot;
2494 	u_int32_t start;
2495 	u_int32_t end;
2496 	u_int32_t bat_ble;
2497 
2498 	/*
2499 	 * Return immediately if not a valid mapping
2500 	 */
2501 	if (!(battable[idx].batu & BAT_Vs))
2502 		return (EINVAL);
2503 
2504 	/*
2505 	 * The BAT entry must be cache-inhibited, guarded, and r/w
2506 	 * so it can function as an i/o page
2507 	 */
2508 	prot = battable[idx].batl & (BAT_I|BAT_G|BAT_PP_RW);
2509 	if (prot != (BAT_I|BAT_G|BAT_PP_RW))
2510 		return (EPERM);
2511 
2512 	/*
2513 	 * The address should be within the BAT range. Assume that the
2514 	 * start address in the BAT has the correct alignment (thus
2515 	 * not requiring masking)
2516 	 */
2517 	start = battable[idx].batl & BAT_PBS;
2518 	bat_ble = (battable[idx].batu & ~(BAT_EBS)) | 0x03;
2519 	end = start | (bat_ble << 15) | 0x7fff;
2520 
2521 	if ((pa < start) || ((pa + size) > end))
2522 		return (ERANGE);
2523 
2524 	return (0);
2525 }
2526 
2527 boolean_t
2528 moea_dev_direct_mapped(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2529 {
2530 	int i;
2531 
2532 	/*
2533 	 * This currently does not work for entries that
2534 	 * overlap 256M BAT segments.
2535 	 */
2536 
2537 	for(i = 0; i < 16; i++)
2538 		if (moea_bat_mapped(i, pa, size) == 0)
2539 			return (0);
2540 
2541 	return (EFAULT);
2542 }
2543 
2544 /*
2545  * Map a set of physical memory pages into the kernel virtual
2546  * address space. Return a pointer to where it is mapped. This
2547  * routine is intended to be used for mapping device memory,
2548  * NOT real memory.
2549  */
2550 void *
2551 moea_mapdev(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2552 {
2553 
2554 	return (moea_mapdev_attr(mmu, pa, size, VM_MEMATTR_DEFAULT));
2555 }
2556 
2557 void *
2558 moea_mapdev_attr(mmu_t mmu, vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2559 {
2560 	vm_offset_t va, tmpva, ppa, offset;
2561 	int i;
2562 
2563 	ppa = trunc_page(pa);
2564 	offset = pa & PAGE_MASK;
2565 	size = roundup(offset + size, PAGE_SIZE);
2566 
2567 	/*
2568 	 * If the physical address lies within a valid BAT table entry,
2569 	 * return the 1:1 mapping. This currently doesn't work
2570 	 * for regions that overlap 256M BAT segments.
2571 	 */
2572 	for (i = 0; i < 16; i++) {
2573 		if (moea_bat_mapped(i, pa, size) == 0)
2574 			return ((void *) pa);
2575 	}
2576 
2577 	va = kva_alloc(size);
2578 	if (!va)
2579 		panic("moea_mapdev: Couldn't alloc kernel virtual memory");
2580 
2581 	for (tmpva = va; size > 0;) {
2582 		moea_kenter_attr(mmu, tmpva, ppa, ma);
2583 		tlbie(tmpva);
2584 		size -= PAGE_SIZE;
2585 		tmpva += PAGE_SIZE;
2586 		ppa += PAGE_SIZE;
2587 	}
2588 
2589 	return ((void *)(va + offset));
2590 }
2591 
2592 void
2593 moea_unmapdev(mmu_t mmu, vm_offset_t va, vm_size_t size)
2594 {
2595 	vm_offset_t base, offset;
2596 
2597 	/*
2598 	 * If this is outside kernel virtual space, then it's a
2599 	 * battable entry and doesn't require unmapping
2600 	 */
2601 	if ((va >= VM_MIN_KERNEL_ADDRESS) && (va <= virtual_end)) {
2602 		base = trunc_page(va);
2603 		offset = va & PAGE_MASK;
2604 		size = roundup(offset + size, PAGE_SIZE);
2605 		kva_free(base, size);
2606 	}
2607 }
2608 
2609 static void
2610 moea_sync_icache(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_size_t sz)
2611 {
2612 	struct pvo_entry *pvo;
2613 	vm_offset_t lim;
2614 	vm_paddr_t pa;
2615 	vm_size_t len;
2616 
2617 	PMAP_LOCK(pm);
2618 	while (sz > 0) {
2619 		lim = round_page(va);
2620 		len = MIN(lim - va, sz);
2621 		pvo = moea_pvo_find_va(pm, va & ~ADDR_POFF, NULL);
2622 		if (pvo != NULL) {
2623 			pa = (pvo->pvo_pte.pte.pte_lo & PTE_RPGN) |
2624 			    (va & ADDR_POFF);
2625 			moea_syncicache(pa, len);
2626 		}
2627 		va += len;
2628 		sz -= len;
2629 	}
2630 	PMAP_UNLOCK(pm);
2631 }
2632 
2633 void
2634 moea_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz, void **va)
2635 {
2636 
2637 	*va = (void *)pa;
2638 }
2639 
2640 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2641 
2642 void
2643 moea_scan_init(mmu_t mmu)
2644 {
2645 	struct pvo_entry *pvo;
2646 	vm_offset_t va;
2647 	int i;
2648 
2649 	if (!do_minidump) {
2650 		/* Initialize phys. segments for dumpsys(). */
2651 		memset(&dump_map, 0, sizeof(dump_map));
2652 		mem_regions(&pregions, &pregions_sz, &regions, &regions_sz);
2653 		for (i = 0; i < pregions_sz; i++) {
2654 			dump_map[i].pa_start = pregions[i].mr_start;
2655 			dump_map[i].pa_size = pregions[i].mr_size;
2656 		}
2657 		return;
2658 	}
2659 
2660 	/* Virtual segments for minidumps: */
2661 	memset(&dump_map, 0, sizeof(dump_map));
2662 
2663 	/* 1st: kernel .data and .bss. */
2664 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2665 	dump_map[0].pa_size =
2666 	    round_page((uintptr_t)_end) - dump_map[0].pa_start;
2667 
2668 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2669 	dump_map[1].pa_start = (vm_paddr_t)msgbufp->msg_ptr;
2670 	dump_map[1].pa_size = round_page(msgbufp->msg_size);
2671 
2672 	/* 3rd: kernel VM. */
2673 	va = dump_map[1].pa_start + dump_map[1].pa_size;
2674 	/* Find start of next chunk (from va). */
2675 	while (va < virtual_end) {
2676 		/* Don't dump the buffer cache. */
2677 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2678 			va = kmi.buffer_eva;
2679 			continue;
2680 		}
2681 		pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF, NULL);
2682 		if (pvo != NULL && (pvo->pvo_pte.pte.pte_hi & PTE_VALID))
2683 			break;
2684 		va += PAGE_SIZE;
2685 	}
2686 	if (va < virtual_end) {
2687 		dump_map[2].pa_start = va;
2688 		va += PAGE_SIZE;
2689 		/* Find last page in chunk. */
2690 		while (va < virtual_end) {
2691 			/* Don't run into the buffer cache. */
2692 			if (va == kmi.buffer_sva)
2693 				break;
2694 			pvo = moea_pvo_find_va(kernel_pmap, va & ~ADDR_POFF,
2695 			    NULL);
2696 			if (pvo == NULL ||
2697 			    !(pvo->pvo_pte.pte.pte_hi & PTE_VALID))
2698 				break;
2699 			va += PAGE_SIZE;
2700 		}
2701 		dump_map[2].pa_size = va - dump_map[2].pa_start;
2702 	}
2703 }
2704