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