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