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