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