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