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