]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/powerpc/booke/pmap.c
Missed local diff.
[FreeBSD/FreeBSD.git] / sys / powerpc / booke / pmap.c
1 /*-
2  * Copyright (C) 2007-2009 Semihalf, Rafal Jaworowski <raj@semihalf.com>
3  * Copyright (C) 2006 Semihalf, Marian Balakowicz <m8@semihalf.com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
18  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
20  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
22  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * Some hw specific parts of this pmap were derived or influenced
27  * by NetBSD's ibm4xx pmap module. More generic code is shared with
28  * a few other pmap modules from the FreeBSD tree.
29  */
30
31  /*
32   * VM layout notes:
33   *
34   * Kernel and user threads run within one common virtual address space
35   * defined by AS=0.
36   *
37   * Virtual address space layout:
38   * -----------------------------
39   * 0x0000_0000 - 0xafff_ffff   : user process
40   * 0xb000_0000 - 0xbfff_ffff   : pmap_mapdev()-ed area (PCI/PCIE etc.)
41   * 0xc000_0000 - 0xc0ff_ffff   : kernel reserved
42   *   0xc000_0000 - data_end    : kernel code+data, env, metadata etc.
43   * 0xc100_0000 - 0xfeef_ffff   : KVA
44   *   0xc100_0000 - 0xc100_3fff : reserved for page zero/copy
45   *   0xc100_4000 - 0xc200_3fff : reserved for ptbl bufs
46   *   0xc200_4000 - 0xc200_8fff : guard page + kstack0
47   *   0xc200_9000 - 0xfeef_ffff : actual free KVA space
48   * 0xfef0_0000 - 0xffff_ffff   : I/O devices region
49   */
50
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD$");
53
54 #include <sys/param.h>
55 #include <sys/conf.h>
56 #include <sys/malloc.h>
57 #include <sys/ktr.h>
58 #include <sys/proc.h>
59 #include <sys/user.h>
60 #include <sys/queue.h>
61 #include <sys/systm.h>
62 #include <sys/kernel.h>
63 #include <sys/kerneldump.h>
64 #include <sys/linker.h>
65 #include <sys/msgbuf.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/rwlock.h>
69 #include <sys/sched.h>
70 #include <sys/smp.h>
71 #include <sys/vmmeter.h>
72
73 #include <vm/vm.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_kern.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_object.h>
79 #include <vm/vm_param.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_pager.h>
82 #include <vm/uma.h>
83
84 #include <machine/cpu.h>
85 #include <machine/pcb.h>
86 #include <machine/platform.h>
87
88 #include <machine/tlb.h>
89 #include <machine/spr.h>
90 #include <machine/md_var.h>
91 #include <machine/mmuvar.h>
92 #include <machine/pmap.h>
93 #include <machine/pte.h>
94
95 #include "mmu_if.h"
96
97 #ifdef  DEBUG
98 #define debugf(fmt, args...) printf(fmt, ##args)
99 #else
100 #define debugf(fmt, args...)
101 #endif
102
103 #define TODO                    panic("%s: not implemented", __func__);
104
105 extern unsigned char _etext[];
106 extern unsigned char _end[];
107
108 extern uint32_t *bootinfo;
109
110 #ifdef SMP
111 extern uint32_t bp_ntlb1s;
112 #endif
113
114 vm_paddr_t kernload;
115 vm_offset_t kernstart;
116 vm_size_t kernsize;
117
118 /* Message buffer and tables. */
119 static vm_offset_t data_start;
120 static vm_size_t data_end;
121
122 /* Phys/avail memory regions. */
123 static struct mem_region *availmem_regions;
124 static int availmem_regions_sz;
125 static struct mem_region *physmem_regions;
126 static int physmem_regions_sz;
127
128 /* Reserved KVA space and mutex for mmu_booke_zero_page. */
129 static vm_offset_t zero_page_va;
130 static struct mtx zero_page_mutex;
131
132 static struct mtx tlbivax_mutex;
133
134 /*
135  * Reserved KVA space for mmu_booke_zero_page_idle. This is used
136  * by idle thred only, no lock required.
137  */
138 static vm_offset_t zero_page_idle_va;
139
140 /* Reserved KVA space and mutex for mmu_booke_copy_page. */
141 static vm_offset_t copy_page_src_va;
142 static vm_offset_t copy_page_dst_va;
143 static struct mtx copy_page_mutex;
144
145 /**************************************************************************/
146 /* PMAP */
147 /**************************************************************************/
148
149 static int mmu_booke_enter_locked(mmu_t, pmap_t, vm_offset_t, vm_page_t,
150     vm_prot_t, u_int flags, int8_t psind);
151
152 unsigned int kptbl_min;         /* Index of the first kernel ptbl. */
153 unsigned int kernel_ptbls;      /* Number of KVA ptbls. */
154
155 /*
156  * If user pmap is processed with mmu_booke_remove and the resident count
157  * drops to 0, there are no more pages to remove, so we need not continue.
158  */
159 #define PMAP_REMOVE_DONE(pmap) \
160         ((pmap) != kernel_pmap && (pmap)->pm_stats.resident_count == 0)
161
162 extern void tid_flush(tlbtid_t);
163 extern int elf32_nxstack;
164
165 /**************************************************************************/
166 /* TLB and TID handling */
167 /**************************************************************************/
168
169 /* Translation ID busy table */
170 static volatile pmap_t tidbusy[MAXCPU][TID_MAX + 1];
171
172 /*
173  * TLB0 capabilities (entry, way numbers etc.). These can vary between e500
174  * core revisions and should be read from h/w registers during early config.
175  */
176 uint32_t tlb0_entries;
177 uint32_t tlb0_ways;
178 uint32_t tlb0_entries_per_way;
179
180 #define TLB0_ENTRIES            (tlb0_entries)
181 #define TLB0_WAYS               (tlb0_ways)
182 #define TLB0_ENTRIES_PER_WAY    (tlb0_entries_per_way)
183
184 #define TLB1_ENTRIES 16
185
186 /* In-ram copy of the TLB1 */
187 static tlb_entry_t tlb1[TLB1_ENTRIES];
188
189 /* Next free entry in the TLB1 */
190 static unsigned int tlb1_idx;
191 static vm_offset_t tlb1_map_base = VM_MAX_KERNEL_ADDRESS;
192
193 static tlbtid_t tid_alloc(struct pmap *);
194
195 static void tlb_print_entry(int, uint32_t, uint32_t, uint32_t, uint32_t);
196
197 static int tlb1_set_entry(vm_offset_t, vm_offset_t, vm_size_t, uint32_t);
198 static void tlb1_write_entry(unsigned int);
199 static int tlb1_iomapped(int, vm_paddr_t, vm_size_t, vm_offset_t *);
200 static vm_size_t tlb1_mapin_region(vm_offset_t, vm_paddr_t, vm_size_t);
201
202 static vm_size_t tsize2size(unsigned int);
203 static unsigned int size2tsize(vm_size_t);
204 static unsigned int ilog2(unsigned int);
205
206 static void set_mas4_defaults(void);
207
208 static inline void tlb0_flush_entry(vm_offset_t);
209 static inline unsigned int tlb0_tableidx(vm_offset_t, unsigned int);
210
211 /**************************************************************************/
212 /* Page table management */
213 /**************************************************************************/
214
215 static struct rwlock_padalign pvh_global_lock;
216
217 /* Data for the pv entry allocation mechanism */
218 static uma_zone_t pvzone;
219 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
220
221 #define PV_ENTRY_ZONE_MIN       2048    /* min pv entries in uma zone */
222
223 #ifndef PMAP_SHPGPERPROC
224 #define PMAP_SHPGPERPROC        200
225 #endif
226
227 static void ptbl_init(void);
228 static struct ptbl_buf *ptbl_buf_alloc(void);
229 static void ptbl_buf_free(struct ptbl_buf *);
230 static void ptbl_free_pmap_ptbl(pmap_t, pte_t *);
231
232 static pte_t *ptbl_alloc(mmu_t, pmap_t, unsigned int, boolean_t);
233 static void ptbl_free(mmu_t, pmap_t, unsigned int);
234 static void ptbl_hold(mmu_t, pmap_t, unsigned int);
235 static int ptbl_unhold(mmu_t, pmap_t, unsigned int);
236
237 static vm_paddr_t pte_vatopa(mmu_t, pmap_t, vm_offset_t);
238 static pte_t *pte_find(mmu_t, pmap_t, vm_offset_t);
239 static int pte_enter(mmu_t, pmap_t, vm_page_t, vm_offset_t, uint32_t, boolean_t);
240 static int pte_remove(mmu_t, pmap_t, vm_offset_t, uint8_t);
241
242 static pv_entry_t pv_alloc(void);
243 static void pv_free(pv_entry_t);
244 static void pv_insert(pmap_t, vm_offset_t, vm_page_t);
245 static void pv_remove(pmap_t, vm_offset_t, vm_page_t);
246
247 /* Number of kva ptbl buffers, each covering one ptbl (PTBL_PAGES). */
248 #define PTBL_BUFS               (128 * 16)
249
250 struct ptbl_buf {
251         TAILQ_ENTRY(ptbl_buf) link;     /* list link */
252         vm_offset_t kva;                /* va of mapping */
253 };
254
255 /* ptbl free list and a lock used for access synchronization. */
256 static TAILQ_HEAD(, ptbl_buf) ptbl_buf_freelist;
257 static struct mtx ptbl_buf_freelist_lock;
258
259 /* Base address of kva space allocated fot ptbl bufs. */
260 static vm_offset_t ptbl_buf_pool_vabase;
261
262 /* Pointer to ptbl_buf structures. */
263 static struct ptbl_buf *ptbl_bufs;
264
265 void pmap_bootstrap_ap(volatile uint32_t *);
266
267 /*
268  * Kernel MMU interface
269  */
270 static void             mmu_booke_clear_modify(mmu_t, vm_page_t);
271 static void             mmu_booke_copy(mmu_t, pmap_t, pmap_t, vm_offset_t,
272     vm_size_t, vm_offset_t);
273 static void             mmu_booke_copy_page(mmu_t, vm_page_t, vm_page_t);
274 static void             mmu_booke_copy_pages(mmu_t, vm_page_t *,
275     vm_offset_t, vm_page_t *, vm_offset_t, int);
276 static int              mmu_booke_enter(mmu_t, pmap_t, vm_offset_t, vm_page_t,
277     vm_prot_t, u_int flags, int8_t psind);
278 static void             mmu_booke_enter_object(mmu_t, pmap_t, vm_offset_t, vm_offset_t,
279     vm_page_t, vm_prot_t);
280 static void             mmu_booke_enter_quick(mmu_t, pmap_t, vm_offset_t, vm_page_t,
281     vm_prot_t);
282 static vm_paddr_t       mmu_booke_extract(mmu_t, pmap_t, vm_offset_t);
283 static vm_page_t        mmu_booke_extract_and_hold(mmu_t, pmap_t, vm_offset_t,
284     vm_prot_t);
285 static void             mmu_booke_init(mmu_t);
286 static boolean_t        mmu_booke_is_modified(mmu_t, vm_page_t);
287 static boolean_t        mmu_booke_is_prefaultable(mmu_t, pmap_t, vm_offset_t);
288 static boolean_t        mmu_booke_is_referenced(mmu_t, vm_page_t);
289 static int              mmu_booke_ts_referenced(mmu_t, vm_page_t);
290 static vm_offset_t      mmu_booke_map(mmu_t, vm_offset_t *, vm_paddr_t, vm_paddr_t,
291     int);
292 static int              mmu_booke_mincore(mmu_t, pmap_t, vm_offset_t,
293     vm_paddr_t *);
294 static void             mmu_booke_object_init_pt(mmu_t, pmap_t, vm_offset_t,
295     vm_object_t, vm_pindex_t, vm_size_t);
296 static boolean_t        mmu_booke_page_exists_quick(mmu_t, pmap_t, vm_page_t);
297 static void             mmu_booke_page_init(mmu_t, vm_page_t);
298 static int              mmu_booke_page_wired_mappings(mmu_t, vm_page_t);
299 static void             mmu_booke_pinit(mmu_t, pmap_t);
300 static void             mmu_booke_pinit0(mmu_t, pmap_t);
301 static void             mmu_booke_protect(mmu_t, pmap_t, vm_offset_t, vm_offset_t,
302     vm_prot_t);
303 static void             mmu_booke_qenter(mmu_t, vm_offset_t, vm_page_t *, int);
304 static void             mmu_booke_qremove(mmu_t, vm_offset_t, int);
305 static void             mmu_booke_release(mmu_t, pmap_t);
306 static void             mmu_booke_remove(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
307 static void             mmu_booke_remove_all(mmu_t, vm_page_t);
308 static void             mmu_booke_remove_write(mmu_t, vm_page_t);
309 static void             mmu_booke_unwire(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
310 static void             mmu_booke_zero_page(mmu_t, vm_page_t);
311 static void             mmu_booke_zero_page_area(mmu_t, vm_page_t, int, int);
312 static void             mmu_booke_zero_page_idle(mmu_t, vm_page_t);
313 static void             mmu_booke_activate(mmu_t, struct thread *);
314 static void             mmu_booke_deactivate(mmu_t, struct thread *);
315 static void             mmu_booke_bootstrap(mmu_t, vm_offset_t, vm_offset_t);
316 static void             *mmu_booke_mapdev(mmu_t, vm_paddr_t, vm_size_t);
317 static void             *mmu_booke_mapdev_attr(mmu_t, vm_paddr_t, vm_size_t, vm_memattr_t);
318 static void             mmu_booke_unmapdev(mmu_t, vm_offset_t, vm_size_t);
319 static vm_paddr_t       mmu_booke_kextract(mmu_t, vm_offset_t);
320 static void             mmu_booke_kenter(mmu_t, vm_offset_t, vm_paddr_t);
321 static void             mmu_booke_kenter_attr(mmu_t, vm_offset_t, vm_paddr_t, vm_memattr_t);
322 static void             mmu_booke_kremove(mmu_t, vm_offset_t);
323 static boolean_t        mmu_booke_dev_direct_mapped(mmu_t, vm_paddr_t, vm_size_t);
324 static void             mmu_booke_sync_icache(mmu_t, pmap_t, vm_offset_t,
325     vm_size_t);
326 static void             mmu_booke_dumpsys_map(mmu_t, vm_paddr_t pa, size_t,
327     void **);
328 static void             mmu_booke_dumpsys_unmap(mmu_t, vm_paddr_t pa, size_t,
329     void *);
330 static void             mmu_booke_scan_init(mmu_t);
331
332 static mmu_method_t mmu_booke_methods[] = {
333         /* pmap dispatcher interface */
334         MMUMETHOD(mmu_clear_modify,     mmu_booke_clear_modify),
335         MMUMETHOD(mmu_copy,             mmu_booke_copy),
336         MMUMETHOD(mmu_copy_page,        mmu_booke_copy_page),
337         MMUMETHOD(mmu_copy_pages,       mmu_booke_copy_pages),
338         MMUMETHOD(mmu_enter,            mmu_booke_enter),
339         MMUMETHOD(mmu_enter_object,     mmu_booke_enter_object),
340         MMUMETHOD(mmu_enter_quick,      mmu_booke_enter_quick),
341         MMUMETHOD(mmu_extract,          mmu_booke_extract),
342         MMUMETHOD(mmu_extract_and_hold, mmu_booke_extract_and_hold),
343         MMUMETHOD(mmu_init,             mmu_booke_init),
344         MMUMETHOD(mmu_is_modified,      mmu_booke_is_modified),
345         MMUMETHOD(mmu_is_prefaultable,  mmu_booke_is_prefaultable),
346         MMUMETHOD(mmu_is_referenced,    mmu_booke_is_referenced),
347         MMUMETHOD(mmu_ts_referenced,    mmu_booke_ts_referenced),
348         MMUMETHOD(mmu_map,              mmu_booke_map),
349         MMUMETHOD(mmu_mincore,          mmu_booke_mincore),
350         MMUMETHOD(mmu_object_init_pt,   mmu_booke_object_init_pt),
351         MMUMETHOD(mmu_page_exists_quick,mmu_booke_page_exists_quick),
352         MMUMETHOD(mmu_page_init,        mmu_booke_page_init),
353         MMUMETHOD(mmu_page_wired_mappings, mmu_booke_page_wired_mappings),
354         MMUMETHOD(mmu_pinit,            mmu_booke_pinit),
355         MMUMETHOD(mmu_pinit0,           mmu_booke_pinit0),
356         MMUMETHOD(mmu_protect,          mmu_booke_protect),
357         MMUMETHOD(mmu_qenter,           mmu_booke_qenter),
358         MMUMETHOD(mmu_qremove,          mmu_booke_qremove),
359         MMUMETHOD(mmu_release,          mmu_booke_release),
360         MMUMETHOD(mmu_remove,           mmu_booke_remove),
361         MMUMETHOD(mmu_remove_all,       mmu_booke_remove_all),
362         MMUMETHOD(mmu_remove_write,     mmu_booke_remove_write),
363         MMUMETHOD(mmu_sync_icache,      mmu_booke_sync_icache),
364         MMUMETHOD(mmu_unwire,           mmu_booke_unwire),
365         MMUMETHOD(mmu_zero_page,        mmu_booke_zero_page),
366         MMUMETHOD(mmu_zero_page_area,   mmu_booke_zero_page_area),
367         MMUMETHOD(mmu_zero_page_idle,   mmu_booke_zero_page_idle),
368         MMUMETHOD(mmu_activate,         mmu_booke_activate),
369         MMUMETHOD(mmu_deactivate,       mmu_booke_deactivate),
370
371         /* Internal interfaces */
372         MMUMETHOD(mmu_bootstrap,        mmu_booke_bootstrap),
373         MMUMETHOD(mmu_dev_direct_mapped,mmu_booke_dev_direct_mapped),
374         MMUMETHOD(mmu_mapdev,           mmu_booke_mapdev),
375         MMUMETHOD(mmu_mapdev_attr,      mmu_booke_mapdev_attr),
376         MMUMETHOD(mmu_kenter,           mmu_booke_kenter),
377         MMUMETHOD(mmu_kenter_attr,      mmu_booke_kenter_attr),
378         MMUMETHOD(mmu_kextract,         mmu_booke_kextract),
379 /*      MMUMETHOD(mmu_kremove,          mmu_booke_kremove),     */
380         MMUMETHOD(mmu_unmapdev,         mmu_booke_unmapdev),
381
382         /* dumpsys() support */
383         MMUMETHOD(mmu_dumpsys_map,      mmu_booke_dumpsys_map),
384         MMUMETHOD(mmu_dumpsys_unmap,    mmu_booke_dumpsys_unmap),
385         MMUMETHOD(mmu_scan_init,        mmu_booke_scan_init),
386
387         { 0, 0 }
388 };
389
390 MMU_DEF(booke_mmu, MMU_TYPE_BOOKE, mmu_booke_methods, 0);
391
392 static __inline uint32_t
393 tlb_calc_wimg(vm_offset_t pa, vm_memattr_t ma)
394 {
395         uint32_t attrib;
396         int i;
397
398         if (ma != VM_MEMATTR_DEFAULT) {
399                 switch (ma) {
400                 case VM_MEMATTR_UNCACHEABLE:
401                         return (PTE_I | PTE_G);
402                 case VM_MEMATTR_WRITE_COMBINING:
403                 case VM_MEMATTR_WRITE_BACK:
404                 case VM_MEMATTR_PREFETCHABLE:
405                         return (PTE_I);
406                 case VM_MEMATTR_WRITE_THROUGH:
407                         return (PTE_W | PTE_M);
408                 }
409         }
410
411         /*
412          * Assume the page is cache inhibited and access is guarded unless
413          * it's in our available memory array.
414          */
415         attrib = _TLB_ENTRY_IO;
416         for (i = 0; i < physmem_regions_sz; i++) {
417                 if ((pa >= physmem_regions[i].mr_start) &&
418                     (pa < (physmem_regions[i].mr_start +
419                      physmem_regions[i].mr_size))) {
420                         attrib = _TLB_ENTRY_MEM;
421                         break;
422                 }
423         }
424
425         return (attrib);
426 }
427
428 static inline void
429 tlb_miss_lock(void)
430 {
431 #ifdef SMP
432         struct pcpu *pc;
433
434         if (!smp_started)
435                 return;
436
437         STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
438                 if (pc != pcpup) {
439
440                         CTR3(KTR_PMAP, "%s: tlb miss LOCK of CPU=%d, "
441                             "tlb_lock=%p", __func__, pc->pc_cpuid, pc->pc_booke_tlb_lock);
442
443                         KASSERT((pc->pc_cpuid != PCPU_GET(cpuid)),
444                             ("tlb_miss_lock: tried to lock self"));
445
446                         tlb_lock(pc->pc_booke_tlb_lock);
447
448                         CTR1(KTR_PMAP, "%s: locked", __func__);
449                 }
450         }
451 #endif
452 }
453
454 static inline void
455 tlb_miss_unlock(void)
456 {
457 #ifdef SMP
458         struct pcpu *pc;
459
460         if (!smp_started)
461                 return;
462
463         STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
464                 if (pc != pcpup) {
465                         CTR2(KTR_PMAP, "%s: tlb miss UNLOCK of CPU=%d",
466                             __func__, pc->pc_cpuid);
467
468                         tlb_unlock(pc->pc_booke_tlb_lock);
469
470                         CTR1(KTR_PMAP, "%s: unlocked", __func__);
471                 }
472         }
473 #endif
474 }
475
476 /* Return number of entries in TLB0. */
477 static __inline void
478 tlb0_get_tlbconf(void)
479 {
480         uint32_t tlb0_cfg;
481
482         tlb0_cfg = mfspr(SPR_TLB0CFG);
483         tlb0_entries = tlb0_cfg & TLBCFG_NENTRY_MASK;
484         tlb0_ways = (tlb0_cfg & TLBCFG_ASSOC_MASK) >> TLBCFG_ASSOC_SHIFT;
485         tlb0_entries_per_way = tlb0_entries / tlb0_ways;
486 }
487
488 /* Initialize pool of kva ptbl buffers. */
489 static void
490 ptbl_init(void)
491 {
492         int i;
493
494         CTR3(KTR_PMAP, "%s: s (ptbl_bufs = 0x%08x size 0x%08x)", __func__,
495             (uint32_t)ptbl_bufs, sizeof(struct ptbl_buf) * PTBL_BUFS);
496         CTR3(KTR_PMAP, "%s: s (ptbl_buf_pool_vabase = 0x%08x size = 0x%08x)",
497             __func__, ptbl_buf_pool_vabase, PTBL_BUFS * PTBL_PAGES * PAGE_SIZE);
498
499         mtx_init(&ptbl_buf_freelist_lock, "ptbl bufs lock", NULL, MTX_DEF);
500         TAILQ_INIT(&ptbl_buf_freelist);
501
502         for (i = 0; i < PTBL_BUFS; i++) {
503                 ptbl_bufs[i].kva = ptbl_buf_pool_vabase + i * PTBL_PAGES * PAGE_SIZE;
504                 TAILQ_INSERT_TAIL(&ptbl_buf_freelist, &ptbl_bufs[i], link);
505         }
506 }
507
508 /* Get a ptbl_buf from the freelist. */
509 static struct ptbl_buf *
510 ptbl_buf_alloc(void)
511 {
512         struct ptbl_buf *buf;
513
514         mtx_lock(&ptbl_buf_freelist_lock);
515         buf = TAILQ_FIRST(&ptbl_buf_freelist);
516         if (buf != NULL)
517                 TAILQ_REMOVE(&ptbl_buf_freelist, buf, link);
518         mtx_unlock(&ptbl_buf_freelist_lock);
519
520         CTR2(KTR_PMAP, "%s: buf = %p", __func__, buf);
521
522         return (buf);
523 }
524
525 /* Return ptbl buff to free pool. */
526 static void
527 ptbl_buf_free(struct ptbl_buf *buf)
528 {
529
530         CTR2(KTR_PMAP, "%s: buf = %p", __func__, buf);
531
532         mtx_lock(&ptbl_buf_freelist_lock);
533         TAILQ_INSERT_TAIL(&ptbl_buf_freelist, buf, link);
534         mtx_unlock(&ptbl_buf_freelist_lock);
535 }
536
537 /*
538  * Search the list of allocated ptbl bufs and find on list of allocated ptbls
539  */
540 static void
541 ptbl_free_pmap_ptbl(pmap_t pmap, pte_t *ptbl)
542 {
543         struct ptbl_buf *pbuf;
544
545         CTR2(KTR_PMAP, "%s: ptbl = %p", __func__, ptbl);
546
547         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
548
549         TAILQ_FOREACH(pbuf, &pmap->pm_ptbl_list, link)
550                 if (pbuf->kva == (vm_offset_t)ptbl) {
551                         /* Remove from pmap ptbl buf list. */
552                         TAILQ_REMOVE(&pmap->pm_ptbl_list, pbuf, link);
553
554                         /* Free corresponding ptbl buf. */
555                         ptbl_buf_free(pbuf);
556                         break;
557                 }
558 }
559
560 /* Allocate page table. */
561 static pte_t *
562 ptbl_alloc(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx, boolean_t nosleep)
563 {
564         vm_page_t mtbl[PTBL_PAGES];
565         vm_page_t m;
566         struct ptbl_buf *pbuf;
567         unsigned int pidx;
568         pte_t *ptbl;
569         int i, j;
570
571         CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
572             (pmap == kernel_pmap), pdir_idx);
573
574         KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
575             ("ptbl_alloc: invalid pdir_idx"));
576         KASSERT((pmap->pm_pdir[pdir_idx] == NULL),
577             ("pte_alloc: valid ptbl entry exists!"));
578
579         pbuf = ptbl_buf_alloc();
580         if (pbuf == NULL)
581                 panic("pte_alloc: couldn't alloc kernel virtual memory");
582                 
583         ptbl = (pte_t *)pbuf->kva;
584
585         CTR2(KTR_PMAP, "%s: ptbl kva = %p", __func__, ptbl);
586
587         /* Allocate ptbl pages, this will sleep! */
588         for (i = 0; i < PTBL_PAGES; i++) {
589                 pidx = (PTBL_PAGES * pdir_idx) + i;
590                 while ((m = vm_page_alloc(NULL, pidx,
591                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
592                         PMAP_UNLOCK(pmap);
593                         rw_wunlock(&pvh_global_lock);
594                         if (nosleep) {
595                                 ptbl_free_pmap_ptbl(pmap, ptbl);
596                                 for (j = 0; j < i; j++)
597                                         vm_page_free(mtbl[j]);
598                                 atomic_subtract_int(&vm_cnt.v_wire_count, i);
599                                 return (NULL);
600                         }
601                         VM_WAIT;
602                         rw_wlock(&pvh_global_lock);
603                         PMAP_LOCK(pmap);
604                 }
605                 mtbl[i] = m;
606         }
607
608         /* Map allocated pages into kernel_pmap. */
609         mmu_booke_qenter(mmu, (vm_offset_t)ptbl, mtbl, PTBL_PAGES);
610
611         /* Zero whole ptbl. */
612         bzero((caddr_t)ptbl, PTBL_PAGES * PAGE_SIZE);
613
614         /* Add pbuf to the pmap ptbl bufs list. */
615         TAILQ_INSERT_TAIL(&pmap->pm_ptbl_list, pbuf, link);
616
617         return (ptbl);
618 }
619
620 /* Free ptbl pages and invalidate pdir entry. */
621 static void
622 ptbl_free(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
623 {
624         pte_t *ptbl;
625         vm_paddr_t pa;
626         vm_offset_t va;
627         vm_page_t m;
628         int i;
629
630         CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
631             (pmap == kernel_pmap), pdir_idx);
632
633         KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
634             ("ptbl_free: invalid pdir_idx"));
635
636         ptbl = pmap->pm_pdir[pdir_idx];
637
638         CTR2(KTR_PMAP, "%s: ptbl = %p", __func__, ptbl);
639
640         KASSERT((ptbl != NULL), ("ptbl_free: null ptbl"));
641
642         /*
643          * Invalidate the pdir entry as soon as possible, so that other CPUs
644          * don't attempt to look up the page tables we are releasing.
645          */
646         mtx_lock_spin(&tlbivax_mutex);
647         tlb_miss_lock();
648         
649         pmap->pm_pdir[pdir_idx] = NULL;
650
651         tlb_miss_unlock();
652         mtx_unlock_spin(&tlbivax_mutex);
653
654         for (i = 0; i < PTBL_PAGES; i++) {
655                 va = ((vm_offset_t)ptbl + (i * PAGE_SIZE));
656                 pa = pte_vatopa(mmu, kernel_pmap, va);
657                 m = PHYS_TO_VM_PAGE(pa);
658                 vm_page_free_zero(m);
659                 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
660                 mmu_booke_kremove(mmu, va);
661         }
662
663         ptbl_free_pmap_ptbl(pmap, ptbl);
664 }
665
666 /*
667  * Decrement ptbl pages hold count and attempt to free ptbl pages.
668  * Called when removing pte entry from ptbl.
669  *
670  * Return 1 if ptbl pages were freed.
671  */
672 static int
673 ptbl_unhold(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
674 {
675         pte_t *ptbl;
676         vm_paddr_t pa;
677         vm_page_t m;
678         int i;
679
680         CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
681             (pmap == kernel_pmap), pdir_idx);
682
683         KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
684             ("ptbl_unhold: invalid pdir_idx"));
685         KASSERT((pmap != kernel_pmap),
686             ("ptbl_unhold: unholding kernel ptbl!"));
687
688         ptbl = pmap->pm_pdir[pdir_idx];
689
690         //debugf("ptbl_unhold: ptbl = 0x%08x\n", (u_int32_t)ptbl);
691         KASSERT(((vm_offset_t)ptbl >= VM_MIN_KERNEL_ADDRESS),
692             ("ptbl_unhold: non kva ptbl"));
693
694         /* decrement hold count */
695         for (i = 0; i < PTBL_PAGES; i++) {
696                 pa = pte_vatopa(mmu, kernel_pmap,
697                     (vm_offset_t)ptbl + (i * PAGE_SIZE));
698                 m = PHYS_TO_VM_PAGE(pa);
699                 m->wire_count--;
700         }
701
702         /*
703          * Free ptbl pages if there are no pte etries in this ptbl.
704          * wire_count has the same value for all ptbl pages, so check the last
705          * page.
706          */
707         if (m->wire_count == 0) {
708                 ptbl_free(mmu, pmap, pdir_idx);
709
710                 //debugf("ptbl_unhold: e (freed ptbl)\n");
711                 return (1);
712         }
713
714         return (0);
715 }
716
717 /*
718  * Increment hold count for ptbl pages. This routine is used when a new pte
719  * entry is being inserted into the ptbl.
720  */
721 static void
722 ptbl_hold(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
723 {
724         vm_paddr_t pa;
725         pte_t *ptbl;
726         vm_page_t m;
727         int i;
728
729         CTR3(KTR_PMAP, "%s: pmap = %p pdir_idx = %d", __func__, pmap,
730             pdir_idx);
731
732         KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
733             ("ptbl_hold: invalid pdir_idx"));
734         KASSERT((pmap != kernel_pmap),
735             ("ptbl_hold: holding kernel ptbl!"));
736
737         ptbl = pmap->pm_pdir[pdir_idx];
738
739         KASSERT((ptbl != NULL), ("ptbl_hold: null ptbl"));
740
741         for (i = 0; i < PTBL_PAGES; i++) {
742                 pa = pte_vatopa(mmu, kernel_pmap,
743                     (vm_offset_t)ptbl + (i * PAGE_SIZE));
744                 m = PHYS_TO_VM_PAGE(pa);
745                 m->wire_count++;
746         }
747 }
748
749 /* Allocate pv_entry structure. */
750 pv_entry_t
751 pv_alloc(void)
752 {
753         pv_entry_t pv;
754
755         pv_entry_count++;
756         if (pv_entry_count > pv_entry_high_water)
757                 pagedaemon_wakeup();
758         pv = uma_zalloc(pvzone, M_NOWAIT);
759
760         return (pv);
761 }
762
763 /* Free pv_entry structure. */
764 static __inline void
765 pv_free(pv_entry_t pve)
766 {
767
768         pv_entry_count--;
769         uma_zfree(pvzone, pve);
770 }
771
772
773 /* Allocate and initialize pv_entry structure. */
774 static void
775 pv_insert(pmap_t pmap, vm_offset_t va, vm_page_t m)
776 {
777         pv_entry_t pve;
778
779         //int su = (pmap == kernel_pmap);
780         //debugf("pv_insert: s (su = %d pmap = 0x%08x va = 0x%08x m = 0x%08x)\n", su,
781         //      (u_int32_t)pmap, va, (u_int32_t)m);
782
783         pve = pv_alloc();
784         if (pve == NULL)
785                 panic("pv_insert: no pv entries!");
786
787         pve->pv_pmap = pmap;
788         pve->pv_va = va;
789
790         /* add to pv_list */
791         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
792         rw_assert(&pvh_global_lock, RA_WLOCKED);
793
794         TAILQ_INSERT_TAIL(&m->md.pv_list, pve, pv_link);
795
796         //debugf("pv_insert: e\n");
797 }
798
799 /* Destroy pv entry. */
800 static void
801 pv_remove(pmap_t pmap, vm_offset_t va, vm_page_t m)
802 {
803         pv_entry_t pve;
804
805         //int su = (pmap == kernel_pmap);
806         //debugf("pv_remove: s (su = %d pmap = 0x%08x va = 0x%08x)\n", su, (u_int32_t)pmap, va);
807
808         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
809         rw_assert(&pvh_global_lock, RA_WLOCKED);
810
811         /* find pv entry */
812         TAILQ_FOREACH(pve, &m->md.pv_list, pv_link) {
813                 if ((pmap == pve->pv_pmap) && (va == pve->pv_va)) {
814                         /* remove from pv_list */
815                         TAILQ_REMOVE(&m->md.pv_list, pve, pv_link);
816                         if (TAILQ_EMPTY(&m->md.pv_list))
817                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
818
819                         /* free pv entry struct */
820                         pv_free(pve);
821                         break;
822                 }
823         }
824
825         //debugf("pv_remove: e\n");
826 }
827
828 /*
829  * Clean pte entry, try to free page table page if requested.
830  *
831  * Return 1 if ptbl pages were freed, otherwise return 0.
832  */
833 static int
834 pte_remove(mmu_t mmu, pmap_t pmap, vm_offset_t va, uint8_t flags)
835 {
836         unsigned int pdir_idx = PDIR_IDX(va);
837         unsigned int ptbl_idx = PTBL_IDX(va);
838         vm_page_t m;
839         pte_t *ptbl;
840         pte_t *pte;
841
842         //int su = (pmap == kernel_pmap);
843         //debugf("pte_remove: s (su = %d pmap = 0x%08x va = 0x%08x flags = %d)\n",
844         //              su, (u_int32_t)pmap, va, flags);
845
846         ptbl = pmap->pm_pdir[pdir_idx];
847         KASSERT(ptbl, ("pte_remove: null ptbl"));
848
849         pte = &ptbl[ptbl_idx];
850
851         if (pte == NULL || !PTE_ISVALID(pte))
852                 return (0);
853
854         if (PTE_ISWIRED(pte))
855                 pmap->pm_stats.wired_count--;
856
857         /* Handle managed entry. */
858         if (PTE_ISMANAGED(pte)) {
859                 /* Get vm_page_t for mapped pte. */
860                 m = PHYS_TO_VM_PAGE(PTE_PA(pte));
861
862                 if (PTE_ISMODIFIED(pte))
863                         vm_page_dirty(m);
864
865                 if (PTE_ISREFERENCED(pte))
866                         vm_page_aflag_set(m, PGA_REFERENCED);
867
868                 pv_remove(pmap, va, m);
869         }
870
871         mtx_lock_spin(&tlbivax_mutex);
872         tlb_miss_lock();
873
874         tlb0_flush_entry(va);
875         pte->flags = 0;
876         pte->rpn = 0;
877
878         tlb_miss_unlock();
879         mtx_unlock_spin(&tlbivax_mutex);
880
881         pmap->pm_stats.resident_count--;
882
883         if (flags & PTBL_UNHOLD) {
884                 //debugf("pte_remove: e (unhold)\n");
885                 return (ptbl_unhold(mmu, pmap, pdir_idx));
886         }
887
888         //debugf("pte_remove: e\n");
889         return (0);
890 }
891
892 /*
893  * Insert PTE for a given page and virtual address.
894  */
895 static int
896 pte_enter(mmu_t mmu, pmap_t pmap, vm_page_t m, vm_offset_t va, uint32_t flags,
897     boolean_t nosleep)
898 {
899         unsigned int pdir_idx = PDIR_IDX(va);
900         unsigned int ptbl_idx = PTBL_IDX(va);
901         pte_t *ptbl, *pte;
902
903         CTR4(KTR_PMAP, "%s: su = %d pmap = %p va = %p", __func__,
904             pmap == kernel_pmap, pmap, va);
905
906         /* Get the page table pointer. */
907         ptbl = pmap->pm_pdir[pdir_idx];
908
909         if (ptbl == NULL) {
910                 /* Allocate page table pages. */
911                 ptbl = ptbl_alloc(mmu, pmap, pdir_idx, nosleep);
912                 if (ptbl == NULL) {
913                         KASSERT(nosleep, ("nosleep and NULL ptbl"));
914                         return (ENOMEM);
915                 }
916         } else {
917                 /*
918                  * Check if there is valid mapping for requested
919                  * va, if there is, remove it.
920                  */
921                 pte = &pmap->pm_pdir[pdir_idx][ptbl_idx];
922                 if (PTE_ISVALID(pte)) {
923                         pte_remove(mmu, pmap, va, PTBL_HOLD);
924                 } else {
925                         /*
926                          * pte is not used, increment hold count
927                          * for ptbl pages.
928                          */
929                         if (pmap != kernel_pmap)
930                                 ptbl_hold(mmu, pmap, pdir_idx);
931                 }
932         }
933
934         /*
935          * Insert pv_entry into pv_list for mapped page if part of managed
936          * memory.
937          */
938         if ((m->oflags & VPO_UNMANAGED) == 0) {
939                 flags |= PTE_MANAGED;
940
941                 /* Create and insert pv entry. */
942                 pv_insert(pmap, va, m);
943         }
944
945         pmap->pm_stats.resident_count++;
946         
947         mtx_lock_spin(&tlbivax_mutex);
948         tlb_miss_lock();
949
950         tlb0_flush_entry(va);
951         if (pmap->pm_pdir[pdir_idx] == NULL) {
952                 /*
953                  * If we just allocated a new page table, hook it in
954                  * the pdir.
955                  */
956                 pmap->pm_pdir[pdir_idx] = ptbl;
957         }
958         pte = &(pmap->pm_pdir[pdir_idx][ptbl_idx]);
959         pte->rpn = VM_PAGE_TO_PHYS(m) & ~PTE_PA_MASK;
960         pte->flags |= (PTE_VALID | flags);
961
962         tlb_miss_unlock();
963         mtx_unlock_spin(&tlbivax_mutex);
964         return (0);
965 }
966
967 /* Return the pa for the given pmap/va. */
968 static vm_paddr_t
969 pte_vatopa(mmu_t mmu, pmap_t pmap, vm_offset_t va)
970 {
971         vm_paddr_t pa = 0;
972         pte_t *pte;
973
974         pte = pte_find(mmu, pmap, va);
975         if ((pte != NULL) && PTE_ISVALID(pte))
976                 pa = (PTE_PA(pte) | (va & PTE_PA_MASK));
977         return (pa);
978 }
979
980 /* Get a pointer to a PTE in a page table. */
981 static pte_t *
982 pte_find(mmu_t mmu, pmap_t pmap, vm_offset_t va)
983 {
984         unsigned int pdir_idx = PDIR_IDX(va);
985         unsigned int ptbl_idx = PTBL_IDX(va);
986
987         KASSERT((pmap != NULL), ("pte_find: invalid pmap"));
988
989         if (pmap->pm_pdir[pdir_idx])
990                 return (&(pmap->pm_pdir[pdir_idx][ptbl_idx]));
991
992         return (NULL);
993 }
994
995 /**************************************************************************/
996 /* PMAP related */
997 /**************************************************************************/
998
999 /*
1000  * This is called during booke_init, before the system is really initialized.
1001  */
1002 static void
1003 mmu_booke_bootstrap(mmu_t mmu, vm_offset_t start, vm_offset_t kernelend)
1004 {
1005         vm_offset_t phys_kernelend;
1006         struct mem_region *mp, *mp1;
1007         int cnt, i, j;
1008         u_int s, e, sz;
1009         u_int phys_avail_count;
1010         vm_size_t physsz, hwphyssz, kstack0_sz;
1011         vm_offset_t kernel_pdir, kstack0, va;
1012         vm_paddr_t kstack0_phys;
1013         void *dpcpu;
1014         pte_t *pte;
1015
1016         debugf("mmu_booke_bootstrap: entered\n");
1017
1018         /* Set interesting system properties */
1019         hw_direct_map = 0;
1020         elf32_nxstack = 1;
1021
1022         /* Initialize invalidation mutex */
1023         mtx_init(&tlbivax_mutex, "tlbivax", NULL, MTX_SPIN);
1024
1025         /* Read TLB0 size and associativity. */
1026         tlb0_get_tlbconf();
1027
1028         /*
1029          * Align kernel start and end address (kernel image).
1030          * Note that kernel end does not necessarily relate to kernsize.
1031          * kernsize is the size of the kernel that is actually mapped.
1032          * Also note that "start - 1" is deliberate. With SMP, the
1033          * entry point is exactly a page from the actual load address.
1034          * As such, trunc_page() has no effect and we're off by a page.
1035          * Since we always have the ELF header between the load address
1036          * and the entry point, we can safely subtract 1 to compensate.
1037          */
1038         kernstart = trunc_page(start - 1);
1039         data_start = round_page(kernelend);
1040         data_end = data_start;
1041
1042         /*
1043          * Addresses of preloaded modules (like file systems) use
1044          * physical addresses. Make sure we relocate those into
1045          * virtual addresses.
1046          */
1047         preload_addr_relocate = kernstart - kernload;
1048
1049         /* Allocate the dynamic per-cpu area. */
1050         dpcpu = (void *)data_end;
1051         data_end += DPCPU_SIZE;
1052
1053         /* Allocate space for the message buffer. */
1054         msgbufp = (struct msgbuf *)data_end;
1055         data_end += msgbufsize;
1056         debugf(" msgbufp at 0x%08x end = 0x%08x\n", (uint32_t)msgbufp,
1057             data_end);
1058
1059         data_end = round_page(data_end);
1060
1061         /* Allocate space for ptbl_bufs. */
1062         ptbl_bufs = (struct ptbl_buf *)data_end;
1063         data_end += sizeof(struct ptbl_buf) * PTBL_BUFS;
1064         debugf(" ptbl_bufs at 0x%08x end = 0x%08x\n", (uint32_t)ptbl_bufs,
1065             data_end);
1066
1067         data_end = round_page(data_end);
1068
1069         /* Allocate PTE tables for kernel KVA. */
1070         kernel_pdir = data_end;
1071         kernel_ptbls = (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS +
1072             PDIR_SIZE - 1) / PDIR_SIZE;
1073         data_end += kernel_ptbls * PTBL_PAGES * PAGE_SIZE;
1074         debugf(" kernel ptbls: %d\n", kernel_ptbls);
1075         debugf(" kernel pdir at 0x%08x end = 0x%08x\n", kernel_pdir, data_end);
1076
1077         debugf(" data_end: 0x%08x\n", data_end);
1078         if (data_end - kernstart > kernsize) {
1079                 kernsize += tlb1_mapin_region(kernstart + kernsize,
1080                     kernload + kernsize, (data_end - kernstart) - kernsize);
1081         }
1082         data_end = kernstart + kernsize;
1083         debugf(" updated data_end: 0x%08x\n", data_end);
1084
1085         /*
1086          * Clear the structures - note we can only do it safely after the
1087          * possible additional TLB1 translations are in place (above) so that
1088          * all range up to the currently calculated 'data_end' is covered.
1089          */
1090         dpcpu_init(dpcpu, 0);
1091         memset((void *)ptbl_bufs, 0, sizeof(struct ptbl_buf) * PTBL_SIZE);
1092         memset((void *)kernel_pdir, 0, kernel_ptbls * PTBL_PAGES * PAGE_SIZE);
1093
1094         /*******************************************************/
1095         /* Set the start and end of kva. */
1096         /*******************************************************/
1097         virtual_avail = round_page(data_end);
1098         virtual_end = VM_MAX_KERNEL_ADDRESS;
1099
1100         /* Allocate KVA space for page zero/copy operations. */
1101         zero_page_va = virtual_avail;
1102         virtual_avail += PAGE_SIZE;
1103         zero_page_idle_va = virtual_avail;
1104         virtual_avail += PAGE_SIZE;
1105         copy_page_src_va = virtual_avail;
1106         virtual_avail += PAGE_SIZE;
1107         copy_page_dst_va = virtual_avail;
1108         virtual_avail += PAGE_SIZE;
1109         debugf("zero_page_va = 0x%08x\n", zero_page_va);
1110         debugf("zero_page_idle_va = 0x%08x\n", zero_page_idle_va);
1111         debugf("copy_page_src_va = 0x%08x\n", copy_page_src_va);
1112         debugf("copy_page_dst_va = 0x%08x\n", copy_page_dst_va);
1113
1114         /* Initialize page zero/copy mutexes. */
1115         mtx_init(&zero_page_mutex, "mmu_booke_zero_page", NULL, MTX_DEF);
1116         mtx_init(&copy_page_mutex, "mmu_booke_copy_page", NULL, MTX_DEF);
1117
1118         /* Allocate KVA space for ptbl bufs. */
1119         ptbl_buf_pool_vabase = virtual_avail;
1120         virtual_avail += PTBL_BUFS * PTBL_PAGES * PAGE_SIZE;
1121         debugf("ptbl_buf_pool_vabase = 0x%08x end = 0x%08x\n",
1122             ptbl_buf_pool_vabase, virtual_avail);
1123
1124         /* Calculate corresponding physical addresses for the kernel region. */
1125         phys_kernelend = kernload + kernsize;
1126         debugf("kernel image and allocated data:\n");
1127         debugf(" kernload    = 0x%08x\n", kernload);
1128         debugf(" kernstart   = 0x%08x\n", kernstart);
1129         debugf(" kernsize    = 0x%08x\n", kernsize);
1130
1131         if (sizeof(phys_avail) / sizeof(phys_avail[0]) < availmem_regions_sz)
1132                 panic("mmu_booke_bootstrap: phys_avail too small");
1133
1134         /*
1135          * Remove kernel physical address range from avail regions list. Page
1136          * align all regions.  Non-page aligned memory isn't very interesting
1137          * to us.  Also, sort the entries for ascending addresses.
1138          */
1139
1140         /* Retrieve phys/avail mem regions */
1141         mem_regions(&physmem_regions, &physmem_regions_sz,
1142             &availmem_regions, &availmem_regions_sz);
1143         sz = 0;
1144         cnt = availmem_regions_sz;
1145         debugf("processing avail regions:\n");
1146         for (mp = availmem_regions; mp->mr_size; mp++) {
1147                 s = mp->mr_start;
1148                 e = mp->mr_start + mp->mr_size;
1149                 debugf(" %08x-%08x -> ", s, e);
1150                 /* Check whether this region holds all of the kernel. */
1151                 if (s < kernload && e > phys_kernelend) {
1152                         availmem_regions[cnt].mr_start = phys_kernelend;
1153                         availmem_regions[cnt++].mr_size = e - phys_kernelend;
1154                         e = kernload;
1155                 }
1156                 /* Look whether this regions starts within the kernel. */
1157                 if (s >= kernload && s < phys_kernelend) {
1158                         if (e <= phys_kernelend)
1159                                 goto empty;
1160                         s = phys_kernelend;
1161                 }
1162                 /* Now look whether this region ends within the kernel. */
1163                 if (e > kernload && e <= phys_kernelend) {
1164                         if (s >= kernload)
1165                                 goto empty;
1166                         e = kernload;
1167                 }
1168                 /* Now page align the start and size of the region. */
1169                 s = round_page(s);
1170                 e = trunc_page(e);
1171                 if (e < s)
1172                         e = s;
1173                 sz = e - s;
1174                 debugf("%08x-%08x = %x\n", s, e, sz);
1175
1176                 /* Check whether some memory is left here. */
1177                 if (sz == 0) {
1178                 empty:
1179                         memmove(mp, mp + 1,
1180                             (cnt - (mp - availmem_regions)) * sizeof(*mp));
1181                         cnt--;
1182                         mp--;
1183                         continue;
1184                 }
1185
1186                 /* Do an insertion sort. */
1187                 for (mp1 = availmem_regions; mp1 < mp; mp1++)
1188                         if (s < mp1->mr_start)
1189                                 break;
1190                 if (mp1 < mp) {
1191                         memmove(mp1 + 1, mp1, (char *)mp - (char *)mp1);
1192                         mp1->mr_start = s;
1193                         mp1->mr_size = sz;
1194                 } else {
1195                         mp->mr_start = s;
1196                         mp->mr_size = sz;
1197                 }
1198         }
1199         availmem_regions_sz = cnt;
1200
1201         /*******************************************************/
1202         /* Steal physical memory for kernel stack from the end */
1203         /* of the first avail region                           */
1204         /*******************************************************/
1205         kstack0_sz = KSTACK_PAGES * PAGE_SIZE;
1206         kstack0_phys = availmem_regions[0].mr_start +
1207             availmem_regions[0].mr_size;
1208         kstack0_phys -= kstack0_sz;
1209         availmem_regions[0].mr_size -= kstack0_sz;
1210
1211         /*******************************************************/
1212         /* Fill in phys_avail table, based on availmem_regions */
1213         /*******************************************************/
1214         phys_avail_count = 0;
1215         physsz = 0;
1216         hwphyssz = 0;
1217         TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
1218
1219         debugf("fill in phys_avail:\n");
1220         for (i = 0, j = 0; i < availmem_regions_sz; i++, j += 2) {
1221
1222                 debugf(" region: 0x%08x - 0x%08x (0x%08x)\n",
1223                     availmem_regions[i].mr_start,
1224                     availmem_regions[i].mr_start +
1225                         availmem_regions[i].mr_size,
1226                     availmem_regions[i].mr_size);
1227
1228                 if (hwphyssz != 0 &&
1229                     (physsz + availmem_regions[i].mr_size) >= hwphyssz) {
1230                         debugf(" hw.physmem adjust\n");
1231                         if (physsz < hwphyssz) {
1232                                 phys_avail[j] = availmem_regions[i].mr_start;
1233                                 phys_avail[j + 1] =
1234                                     availmem_regions[i].mr_start +
1235                                     hwphyssz - physsz;
1236                                 physsz = hwphyssz;
1237                                 phys_avail_count++;
1238                         }
1239                         break;
1240                 }
1241
1242                 phys_avail[j] = availmem_regions[i].mr_start;
1243                 phys_avail[j + 1] = availmem_regions[i].mr_start +
1244                     availmem_regions[i].mr_size;
1245                 phys_avail_count++;
1246                 physsz += availmem_regions[i].mr_size;
1247         }
1248         physmem = btoc(physsz);
1249
1250         /* Calculate the last available physical address. */
1251         for (i = 0; phys_avail[i + 2] != 0; i += 2)
1252                 ;
1253         Maxmem = powerpc_btop(phys_avail[i + 1]);
1254
1255         debugf("Maxmem = 0x%08lx\n", Maxmem);
1256         debugf("phys_avail_count = %d\n", phys_avail_count);
1257         debugf("physsz = 0x%08x physmem = %ld (0x%08lx)\n", physsz, physmem,
1258             physmem);
1259
1260         /*******************************************************/
1261         /* Initialize (statically allocated) kernel pmap. */
1262         /*******************************************************/
1263         PMAP_LOCK_INIT(kernel_pmap);
1264         kptbl_min = VM_MIN_KERNEL_ADDRESS / PDIR_SIZE;
1265
1266         debugf("kernel_pmap = 0x%08x\n", (uint32_t)kernel_pmap);
1267         debugf("kptbl_min = %d, kernel_ptbls = %d\n", kptbl_min, kernel_ptbls);
1268         debugf("kernel pdir range: 0x%08x - 0x%08x\n",
1269             kptbl_min * PDIR_SIZE, (kptbl_min + kernel_ptbls) * PDIR_SIZE - 1);
1270
1271         /* Initialize kernel pdir */
1272         for (i = 0; i < kernel_ptbls; i++)
1273                 kernel_pmap->pm_pdir[kptbl_min + i] =
1274                     (pte_t *)(kernel_pdir + (i * PAGE_SIZE * PTBL_PAGES));
1275
1276         for (i = 0; i < MAXCPU; i++) {
1277                 kernel_pmap->pm_tid[i] = TID_KERNEL;
1278                 
1279                 /* Initialize each CPU's tidbusy entry 0 with kernel_pmap */
1280                 tidbusy[i][0] = kernel_pmap;
1281         }
1282
1283         /*
1284          * Fill in PTEs covering kernel code and data. They are not required
1285          * for address translation, as this area is covered by static TLB1
1286          * entries, but for pte_vatopa() to work correctly with kernel area
1287          * addresses.
1288          */
1289         for (va = kernstart; va < data_end; va += PAGE_SIZE) {
1290                 pte = &(kernel_pmap->pm_pdir[PDIR_IDX(va)][PTBL_IDX(va)]);
1291                 pte->rpn = kernload + (va - kernstart);
1292                 pte->flags = PTE_M | PTE_SR | PTE_SW | PTE_SX | PTE_WIRED |
1293                     PTE_VALID;
1294         }
1295         /* Mark kernel_pmap active on all CPUs */
1296         CPU_FILL(&kernel_pmap->pm_active);
1297
1298         /*
1299          * Initialize the global pv list lock.
1300          */
1301         rw_init(&pvh_global_lock, "pmap pv global");
1302
1303         /*******************************************************/
1304         /* Final setup */
1305         /*******************************************************/
1306
1307         /* Enter kstack0 into kernel map, provide guard page */
1308         kstack0 = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
1309         thread0.td_kstack = kstack0;
1310         thread0.td_kstack_pages = KSTACK_PAGES;
1311
1312         debugf("kstack_sz = 0x%08x\n", kstack0_sz);
1313         debugf("kstack0_phys at 0x%08x - 0x%08x\n",
1314             kstack0_phys, kstack0_phys + kstack0_sz);
1315         debugf("kstack0 at 0x%08x - 0x%08x\n", kstack0, kstack0 + kstack0_sz);
1316         
1317         virtual_avail += KSTACK_GUARD_PAGES * PAGE_SIZE + kstack0_sz;
1318         for (i = 0; i < KSTACK_PAGES; i++) {
1319                 mmu_booke_kenter(mmu, kstack0, kstack0_phys);
1320                 kstack0 += PAGE_SIZE;
1321                 kstack0_phys += PAGE_SIZE;
1322         }
1323
1324         pmap_bootstrapped = 1;
1325         
1326         debugf("virtual_avail = %08x\n", virtual_avail);
1327         debugf("virtual_end   = %08x\n", virtual_end);
1328
1329         debugf("mmu_booke_bootstrap: exit\n");
1330 }
1331
1332 void
1333 pmap_bootstrap_ap(volatile uint32_t *trcp __unused)
1334 {
1335         int i;
1336
1337         /*
1338          * Finish TLB1 configuration: the BSP already set up its TLB1 and we
1339          * have the snapshot of its contents in the s/w tlb1[] table, so use
1340          * these values directly to (re)program AP's TLB1 hardware.
1341          */
1342         for (i = bp_ntlb1s; i < tlb1_idx; i++) {
1343                 /* Skip invalid entries */
1344                 if (!(tlb1[i].mas1 & MAS1_VALID))
1345                         continue;
1346
1347                 tlb1_write_entry(i);
1348         }
1349
1350         set_mas4_defaults();
1351 }
1352
1353 /*
1354  * Get the physical page address for the given pmap/virtual address.
1355  */
1356 static vm_paddr_t
1357 mmu_booke_extract(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1358 {
1359         vm_paddr_t pa;
1360
1361         PMAP_LOCK(pmap);
1362         pa = pte_vatopa(mmu, pmap, va);
1363         PMAP_UNLOCK(pmap);
1364
1365         return (pa);
1366 }
1367
1368 /*
1369  * Extract the physical page address associated with the given
1370  * kernel virtual address.
1371  */
1372 static vm_paddr_t
1373 mmu_booke_kextract(mmu_t mmu, vm_offset_t va)
1374 {
1375         int i;
1376
1377         /* Check TLB1 mappings */
1378         for (i = 0; i < tlb1_idx; i++) {
1379                 if (!(tlb1[i].mas1 & MAS1_VALID))
1380                         continue;
1381                 if (va >= tlb1[i].virt && va < tlb1[i].virt + tlb1[i].size)
1382                         return (tlb1[i].phys + (va - tlb1[i].virt));
1383         }
1384
1385         return (pte_vatopa(mmu, kernel_pmap, va));
1386 }
1387
1388 /*
1389  * Initialize the pmap module.
1390  * Called by vm_init, to initialize any structures that the pmap
1391  * system needs to map virtual memory.
1392  */
1393 static void
1394 mmu_booke_init(mmu_t mmu)
1395 {
1396         int shpgperproc = PMAP_SHPGPERPROC;
1397
1398         /*
1399          * Initialize the address space (zone) for the pv entries.  Set a
1400          * high water mark so that the system can recover from excessive
1401          * numbers of pv entries.
1402          */
1403         pvzone = uma_zcreate("PV ENTRY", sizeof(struct pv_entry), NULL, NULL,
1404             NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
1405
1406         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1407         pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
1408
1409         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1410         pv_entry_high_water = 9 * (pv_entry_max / 10);
1411
1412         uma_zone_reserve_kva(pvzone, pv_entry_max);
1413
1414         /* Pre-fill pvzone with initial number of pv entries. */
1415         uma_prealloc(pvzone, PV_ENTRY_ZONE_MIN);
1416
1417         /* Initialize ptbl allocation. */
1418         ptbl_init();
1419 }
1420
1421 /*
1422  * Map a list of wired pages into kernel virtual address space.  This is
1423  * intended for temporary mappings which do not need page modification or
1424  * references recorded.  Existing mappings in the region are overwritten.
1425  */
1426 static void
1427 mmu_booke_qenter(mmu_t mmu, vm_offset_t sva, vm_page_t *m, int count)
1428 {
1429         vm_offset_t va;
1430
1431         va = sva;
1432         while (count-- > 0) {
1433                 mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(*m));
1434                 va += PAGE_SIZE;
1435                 m++;
1436         }
1437 }
1438
1439 /*
1440  * Remove page mappings from kernel virtual address space.  Intended for
1441  * temporary mappings entered by mmu_booke_qenter.
1442  */
1443 static void
1444 mmu_booke_qremove(mmu_t mmu, vm_offset_t sva, int count)
1445 {
1446         vm_offset_t va;
1447
1448         va = sva;
1449         while (count-- > 0) {
1450                 mmu_booke_kremove(mmu, va);
1451                 va += PAGE_SIZE;
1452         }
1453 }
1454
1455 /*
1456  * Map a wired page into kernel virtual address space.
1457  */
1458 static void
1459 mmu_booke_kenter(mmu_t mmu, vm_offset_t va, vm_paddr_t pa)
1460 {
1461
1462         mmu_booke_kenter_attr(mmu, va, pa, VM_MEMATTR_DEFAULT);
1463 }
1464
1465 static void
1466 mmu_booke_kenter_attr(mmu_t mmu, vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
1467 {
1468         unsigned int pdir_idx = PDIR_IDX(va);
1469         unsigned int ptbl_idx = PTBL_IDX(va);
1470         uint32_t flags;
1471         pte_t *pte;
1472
1473         KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
1474             (va <= VM_MAX_KERNEL_ADDRESS)), ("mmu_booke_kenter: invalid va"));
1475
1476         flags = PTE_SR | PTE_SW | PTE_SX | PTE_WIRED | PTE_VALID;
1477         flags |= tlb_calc_wimg(pa, ma);
1478
1479         pte = &(kernel_pmap->pm_pdir[pdir_idx][ptbl_idx]);
1480
1481         mtx_lock_spin(&tlbivax_mutex);
1482         tlb_miss_lock();
1483         
1484         if (PTE_ISVALID(pte)) {
1485         
1486                 CTR1(KTR_PMAP, "%s: replacing entry!", __func__);
1487
1488                 /* Flush entry from TLB0 */
1489                 tlb0_flush_entry(va);
1490         }
1491
1492         pte->rpn = pa & ~PTE_PA_MASK;
1493         pte->flags = flags;
1494
1495         //debugf("mmu_booke_kenter: pdir_idx = %d ptbl_idx = %d va=0x%08x "
1496         //              "pa=0x%08x rpn=0x%08x flags=0x%08x\n",
1497         //              pdir_idx, ptbl_idx, va, pa, pte->rpn, pte->flags);
1498
1499         /* Flush the real memory from the instruction cache. */
1500         if ((flags & (PTE_I | PTE_G)) == 0) {
1501                 __syncicache((void *)va, PAGE_SIZE);
1502         }
1503
1504         tlb_miss_unlock();
1505         mtx_unlock_spin(&tlbivax_mutex);
1506 }
1507
1508 /*
1509  * Remove a page from kernel page table.
1510  */
1511 static void
1512 mmu_booke_kremove(mmu_t mmu, vm_offset_t va)
1513 {
1514         unsigned int pdir_idx = PDIR_IDX(va);
1515         unsigned int ptbl_idx = PTBL_IDX(va);
1516         pte_t *pte;
1517
1518 //      CTR2(KTR_PMAP,("%s: s (va = 0x%08x)\n", __func__, va));
1519
1520         KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
1521             (va <= VM_MAX_KERNEL_ADDRESS)),
1522             ("mmu_booke_kremove: invalid va"));
1523
1524         pte = &(kernel_pmap->pm_pdir[pdir_idx][ptbl_idx]);
1525
1526         if (!PTE_ISVALID(pte)) {
1527         
1528                 CTR1(KTR_PMAP, "%s: invalid pte", __func__);
1529
1530                 return;
1531         }
1532
1533         mtx_lock_spin(&tlbivax_mutex);
1534         tlb_miss_lock();
1535
1536         /* Invalidate entry in TLB0, update PTE. */
1537         tlb0_flush_entry(va);
1538         pte->flags = 0;
1539         pte->rpn = 0;
1540
1541         tlb_miss_unlock();
1542         mtx_unlock_spin(&tlbivax_mutex);
1543 }
1544
1545 /*
1546  * Initialize pmap associated with process 0.
1547  */
1548 static void
1549 mmu_booke_pinit0(mmu_t mmu, pmap_t pmap)
1550 {
1551
1552         PMAP_LOCK_INIT(pmap);
1553         mmu_booke_pinit(mmu, pmap);
1554         PCPU_SET(curpmap, pmap);
1555 }
1556
1557 /*
1558  * Initialize a preallocated and zeroed pmap structure,
1559  * such as one in a vmspace structure.
1560  */
1561 static void
1562 mmu_booke_pinit(mmu_t mmu, pmap_t pmap)
1563 {
1564         int i;
1565
1566         CTR4(KTR_PMAP, "%s: pmap = %p, proc %d '%s'", __func__, pmap,
1567             curthread->td_proc->p_pid, curthread->td_proc->p_comm);
1568
1569         KASSERT((pmap != kernel_pmap), ("pmap_pinit: initializing kernel_pmap"));
1570
1571         for (i = 0; i < MAXCPU; i++)
1572                 pmap->pm_tid[i] = TID_NONE;
1573         CPU_ZERO(&kernel_pmap->pm_active);
1574         bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
1575         bzero(&pmap->pm_pdir, sizeof(pte_t *) * PDIR_NENTRIES);
1576         TAILQ_INIT(&pmap->pm_ptbl_list);
1577 }
1578
1579 /*
1580  * Release any resources held by the given physical map.
1581  * Called when a pmap initialized by mmu_booke_pinit is being released.
1582  * Should only be called if the map contains no valid mappings.
1583  */
1584 static void
1585 mmu_booke_release(mmu_t mmu, pmap_t pmap)
1586 {
1587
1588         KASSERT(pmap->pm_stats.resident_count == 0,
1589             ("pmap_release: pmap resident count %ld != 0",
1590             pmap->pm_stats.resident_count));
1591 }
1592
1593 /*
1594  * Insert the given physical page at the specified virtual address in the
1595  * target physical map with the protection requested. If specified the page
1596  * will be wired down.
1597  */
1598 static int
1599 mmu_booke_enter(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
1600     vm_prot_t prot, u_int flags, int8_t psind)
1601 {
1602         int error;
1603
1604         rw_wlock(&pvh_global_lock);
1605         PMAP_LOCK(pmap);
1606         error = mmu_booke_enter_locked(mmu, pmap, va, m, prot, flags, psind);
1607         rw_wunlock(&pvh_global_lock);
1608         PMAP_UNLOCK(pmap);
1609         return (error);
1610 }
1611
1612 static int
1613 mmu_booke_enter_locked(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
1614     vm_prot_t prot, u_int pmap_flags, int8_t psind __unused)
1615 {
1616         pte_t *pte;
1617         vm_paddr_t pa;
1618         uint32_t flags;
1619         int error, su, sync;
1620
1621         pa = VM_PAGE_TO_PHYS(m);
1622         su = (pmap == kernel_pmap);
1623         sync = 0;
1624
1625         //debugf("mmu_booke_enter_locked: s (pmap=0x%08x su=%d tid=%d m=0x%08x va=0x%08x "
1626         //              "pa=0x%08x prot=0x%08x flags=%#x)\n",
1627         //              (u_int32_t)pmap, su, pmap->pm_tid,
1628         //              (u_int32_t)m, va, pa, prot, flags);
1629
1630         if (su) {
1631                 KASSERT(((va >= virtual_avail) &&
1632                     (va <= VM_MAX_KERNEL_ADDRESS)),
1633                     ("mmu_booke_enter_locked: kernel pmap, non kernel va"));
1634         } else {
1635                 KASSERT((va <= VM_MAXUSER_ADDRESS),
1636                     ("mmu_booke_enter_locked: user pmap, non user va"));
1637         }
1638         if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
1639                 VM_OBJECT_ASSERT_LOCKED(m->object);
1640
1641         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1642
1643         /*
1644          * If there is an existing mapping, and the physical address has not
1645          * changed, must be protection or wiring change.
1646          */
1647         if (((pte = pte_find(mmu, pmap, va)) != NULL) &&
1648             (PTE_ISVALID(pte)) && (PTE_PA(pte) == pa)) {
1649             
1650                 /*
1651                  * Before actually updating pte->flags we calculate and
1652                  * prepare its new value in a helper var.
1653                  */
1654                 flags = pte->flags;
1655                 flags &= ~(PTE_UW | PTE_UX | PTE_SW | PTE_SX | PTE_MODIFIED);
1656
1657                 /* Wiring change, just update stats. */
1658                 if ((pmap_flags & PMAP_ENTER_WIRED) != 0) {
1659                         if (!PTE_ISWIRED(pte)) {
1660                                 flags |= PTE_WIRED;
1661                                 pmap->pm_stats.wired_count++;
1662                         }
1663                 } else {
1664                         if (PTE_ISWIRED(pte)) {
1665                                 flags &= ~PTE_WIRED;
1666                                 pmap->pm_stats.wired_count--;
1667                         }
1668                 }
1669
1670                 if (prot & VM_PROT_WRITE) {
1671                         /* Add write permissions. */
1672                         flags |= PTE_SW;
1673                         if (!su)
1674                                 flags |= PTE_UW;
1675
1676                         if ((flags & PTE_MANAGED) != 0)
1677                                 vm_page_aflag_set(m, PGA_WRITEABLE);
1678                 } else {
1679                         /* Handle modified pages, sense modify status. */
1680
1681                         /*
1682                          * The PTE_MODIFIED flag could be set by underlying
1683                          * TLB misses since we last read it (above), possibly
1684                          * other CPUs could update it so we check in the PTE
1685                          * directly rather than rely on that saved local flags
1686                          * copy.
1687                          */
1688                         if (PTE_ISMODIFIED(pte))
1689                                 vm_page_dirty(m);
1690                 }
1691
1692                 if (prot & VM_PROT_EXECUTE) {
1693                         flags |= PTE_SX;
1694                         if (!su)
1695                                 flags |= PTE_UX;
1696
1697                         /*
1698                          * Check existing flags for execute permissions: if we
1699                          * are turning execute permissions on, icache should
1700                          * be flushed.
1701                          */
1702                         if ((pte->flags & (PTE_UX | PTE_SX)) == 0)
1703                                 sync++;
1704                 }
1705
1706                 flags &= ~PTE_REFERENCED;
1707
1708                 /*
1709                  * The new flags value is all calculated -- only now actually
1710                  * update the PTE.
1711                  */
1712                 mtx_lock_spin(&tlbivax_mutex);
1713                 tlb_miss_lock();
1714
1715                 tlb0_flush_entry(va);
1716                 pte->flags = flags;
1717
1718                 tlb_miss_unlock();
1719                 mtx_unlock_spin(&tlbivax_mutex);
1720
1721         } else {
1722                 /*
1723                  * If there is an existing mapping, but it's for a different
1724                  * physical address, pte_enter() will delete the old mapping.
1725                  */
1726                 //if ((pte != NULL) && PTE_ISVALID(pte))
1727                 //      debugf("mmu_booke_enter_locked: replace\n");
1728                 //else
1729                 //      debugf("mmu_booke_enter_locked: new\n");
1730
1731                 /* Now set up the flags and install the new mapping. */
1732                 flags = (PTE_SR | PTE_VALID);
1733                 flags |= PTE_M;
1734
1735                 if (!su)
1736                         flags |= PTE_UR;
1737
1738                 if (prot & VM_PROT_WRITE) {
1739                         flags |= PTE_SW;
1740                         if (!su)
1741                                 flags |= PTE_UW;
1742
1743                         if ((m->oflags & VPO_UNMANAGED) == 0)
1744                                 vm_page_aflag_set(m, PGA_WRITEABLE);
1745                 }
1746
1747                 if (prot & VM_PROT_EXECUTE) {
1748                         flags |= PTE_SX;
1749                         if (!su)
1750                                 flags |= PTE_UX;
1751                 }
1752
1753                 /* If its wired update stats. */
1754                 if ((pmap_flags & PMAP_ENTER_WIRED) != 0)
1755                         flags |= PTE_WIRED;
1756
1757                 error = pte_enter(mmu, pmap, m, va, flags,
1758                     (pmap_flags & PMAP_ENTER_NOSLEEP) != 0);
1759                 if (error != 0)
1760                         return (KERN_RESOURCE_SHORTAGE);
1761
1762                 if ((flags & PMAP_ENTER_WIRED) != 0)
1763                         pmap->pm_stats.wired_count++;
1764
1765                 /* Flush the real memory from the instruction cache. */
1766                 if (prot & VM_PROT_EXECUTE)
1767                         sync++;
1768         }
1769
1770         if (sync && (su || pmap == PCPU_GET(curpmap))) {
1771                 __syncicache((void *)va, PAGE_SIZE);
1772                 sync = 0;
1773         }
1774
1775         return (KERN_SUCCESS);
1776 }
1777
1778 /*
1779  * Maps a sequence of resident pages belonging to the same object.
1780  * The sequence begins with the given page m_start.  This page is
1781  * mapped at the given virtual address start.  Each subsequent page is
1782  * mapped at a virtual address that is offset from start by the same
1783  * amount as the page is offset from m_start within the object.  The
1784  * last page in the sequence is the page with the largest offset from
1785  * m_start that can be mapped at a virtual address less than the given
1786  * virtual address end.  Not every virtual page between start and end
1787  * is mapped; only those for which a resident page exists with the
1788  * corresponding offset from m_start are mapped.
1789  */
1790 static void
1791 mmu_booke_enter_object(mmu_t mmu, pmap_t pmap, vm_offset_t start,
1792     vm_offset_t end, vm_page_t m_start, vm_prot_t prot)
1793 {
1794         vm_page_t m;
1795         vm_pindex_t diff, psize;
1796
1797         VM_OBJECT_ASSERT_LOCKED(m_start->object);
1798
1799         psize = atop(end - start);
1800         m = m_start;
1801         rw_wlock(&pvh_global_lock);
1802         PMAP_LOCK(pmap);
1803         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
1804                 mmu_booke_enter_locked(mmu, pmap, start + ptoa(diff), m,
1805                     prot & (VM_PROT_READ | VM_PROT_EXECUTE),
1806                     PMAP_ENTER_NOSLEEP, 0);
1807                 m = TAILQ_NEXT(m, listq);
1808         }
1809         rw_wunlock(&pvh_global_lock);
1810         PMAP_UNLOCK(pmap);
1811 }
1812
1813 static void
1814 mmu_booke_enter_quick(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
1815     vm_prot_t prot)
1816 {
1817
1818         rw_wlock(&pvh_global_lock);
1819         PMAP_LOCK(pmap);
1820         mmu_booke_enter_locked(mmu, pmap, va, m,
1821             prot & (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_NOSLEEP,
1822             0);
1823         rw_wunlock(&pvh_global_lock);
1824         PMAP_UNLOCK(pmap);
1825 }
1826
1827 /*
1828  * Remove the given range of addresses from the specified map.
1829  *
1830  * It is assumed that the start and end are properly rounded to the page size.
1831  */
1832 static void
1833 mmu_booke_remove(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_offset_t endva)
1834 {
1835         pte_t *pte;
1836         uint8_t hold_flag;
1837
1838         int su = (pmap == kernel_pmap);
1839
1840         //debugf("mmu_booke_remove: s (su = %d pmap=0x%08x tid=%d va=0x%08x endva=0x%08x)\n",
1841         //              su, (u_int32_t)pmap, pmap->pm_tid, va, endva);
1842
1843         if (su) {
1844                 KASSERT(((va >= virtual_avail) &&
1845                     (va <= VM_MAX_KERNEL_ADDRESS)),
1846                     ("mmu_booke_remove: kernel pmap, non kernel va"));
1847         } else {
1848                 KASSERT((va <= VM_MAXUSER_ADDRESS),
1849                     ("mmu_booke_remove: user pmap, non user va"));
1850         }
1851
1852         if (PMAP_REMOVE_DONE(pmap)) {
1853                 //debugf("mmu_booke_remove: e (empty)\n");
1854                 return;
1855         }
1856
1857         hold_flag = PTBL_HOLD_FLAG(pmap);
1858         //debugf("mmu_booke_remove: hold_flag = %d\n", hold_flag);
1859
1860         rw_wlock(&pvh_global_lock);
1861         PMAP_LOCK(pmap);
1862         for (; va < endva; va += PAGE_SIZE) {
1863                 pte = pte_find(mmu, pmap, va);
1864                 if ((pte != NULL) && PTE_ISVALID(pte))
1865                         pte_remove(mmu, pmap, va, hold_flag);
1866         }
1867         PMAP_UNLOCK(pmap);
1868         rw_wunlock(&pvh_global_lock);
1869
1870         //debugf("mmu_booke_remove: e\n");
1871 }
1872
1873 /*
1874  * Remove physical page from all pmaps in which it resides.
1875  */
1876 static void
1877 mmu_booke_remove_all(mmu_t mmu, vm_page_t m)
1878 {
1879         pv_entry_t pv, pvn;
1880         uint8_t hold_flag;
1881
1882         rw_wlock(&pvh_global_lock);
1883         for (pv = TAILQ_FIRST(&m->md.pv_list); pv != NULL; pv = pvn) {
1884                 pvn = TAILQ_NEXT(pv, pv_link);
1885
1886                 PMAP_LOCK(pv->pv_pmap);
1887                 hold_flag = PTBL_HOLD_FLAG(pv->pv_pmap);
1888                 pte_remove(mmu, pv->pv_pmap, pv->pv_va, hold_flag);
1889                 PMAP_UNLOCK(pv->pv_pmap);
1890         }
1891         vm_page_aflag_clear(m, PGA_WRITEABLE);
1892         rw_wunlock(&pvh_global_lock);
1893 }
1894
1895 /*
1896  * Map a range of physical addresses into kernel virtual address space.
1897  */
1898 static vm_offset_t
1899 mmu_booke_map(mmu_t mmu, vm_offset_t *virt, vm_paddr_t pa_start,
1900     vm_paddr_t pa_end, int prot)
1901 {
1902         vm_offset_t sva = *virt;
1903         vm_offset_t va = sva;
1904
1905         //debugf("mmu_booke_map: s (sva = 0x%08x pa_start = 0x%08x pa_end = 0x%08x)\n",
1906         //              sva, pa_start, pa_end);
1907
1908         while (pa_start < pa_end) {
1909                 mmu_booke_kenter(mmu, va, pa_start);
1910                 va += PAGE_SIZE;
1911                 pa_start += PAGE_SIZE;
1912         }
1913         *virt = va;
1914
1915         //debugf("mmu_booke_map: e (va = 0x%08x)\n", va);
1916         return (sva);
1917 }
1918
1919 /*
1920  * The pmap must be activated before it's address space can be accessed in any
1921  * way.
1922  */
1923 static void
1924 mmu_booke_activate(mmu_t mmu, struct thread *td)
1925 {
1926         pmap_t pmap;
1927         u_int cpuid;
1928
1929         pmap = &td->td_proc->p_vmspace->vm_pmap;
1930
1931         CTR5(KTR_PMAP, "%s: s (td = %p, proc = '%s', id = %d, pmap = 0x%08x)",
1932             __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
1933
1934         KASSERT((pmap != kernel_pmap), ("mmu_booke_activate: kernel_pmap!"));
1935
1936         sched_pin();
1937
1938         cpuid = PCPU_GET(cpuid);
1939         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
1940         PCPU_SET(curpmap, pmap);
1941         
1942         if (pmap->pm_tid[cpuid] == TID_NONE)
1943                 tid_alloc(pmap);
1944
1945         /* Load PID0 register with pmap tid value. */
1946         mtspr(SPR_PID0, pmap->pm_tid[cpuid]);
1947         __asm __volatile("isync");
1948
1949         sched_unpin();
1950
1951         CTR3(KTR_PMAP, "%s: e (tid = %d for '%s')", __func__,
1952             pmap->pm_tid[PCPU_GET(cpuid)], td->td_proc->p_comm);
1953 }
1954
1955 /*
1956  * Deactivate the specified process's address space.
1957  */
1958 static void
1959 mmu_booke_deactivate(mmu_t mmu, struct thread *td)
1960 {
1961         pmap_t pmap;
1962
1963         pmap = &td->td_proc->p_vmspace->vm_pmap;
1964         
1965         CTR5(KTR_PMAP, "%s: td=%p, proc = '%s', id = %d, pmap = 0x%08x",
1966             __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
1967
1968         CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmap->pm_active);
1969         PCPU_SET(curpmap, NULL);
1970 }
1971
1972 /*
1973  * Copy the range specified by src_addr/len
1974  * from the source map to the range dst_addr/len
1975  * in the destination map.
1976  *
1977  * This routine is only advisory and need not do anything.
1978  */
1979 static void
1980 mmu_booke_copy(mmu_t mmu, pmap_t dst_pmap, pmap_t src_pmap,
1981     vm_offset_t dst_addr, vm_size_t len, vm_offset_t src_addr)
1982 {
1983
1984 }
1985
1986 /*
1987  * Set the physical protection on the specified range of this map as requested.
1988  */
1989 static void
1990 mmu_booke_protect(mmu_t mmu, pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1991     vm_prot_t prot)
1992 {
1993         vm_offset_t va;
1994         vm_page_t m;
1995         pte_t *pte;
1996
1997         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1998                 mmu_booke_remove(mmu, pmap, sva, eva);
1999                 return;
2000         }
2001
2002         if (prot & VM_PROT_WRITE)
2003                 return;
2004
2005         PMAP_LOCK(pmap);
2006         for (va = sva; va < eva; va += PAGE_SIZE) {
2007                 if ((pte = pte_find(mmu, pmap, va)) != NULL) {
2008                         if (PTE_ISVALID(pte)) {
2009                                 m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2010
2011                                 mtx_lock_spin(&tlbivax_mutex);
2012                                 tlb_miss_lock();
2013
2014                                 /* Handle modified pages. */
2015                                 if (PTE_ISMODIFIED(pte) && PTE_ISMANAGED(pte))
2016                                         vm_page_dirty(m);
2017
2018                                 tlb0_flush_entry(va);
2019                                 pte->flags &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
2020
2021                                 tlb_miss_unlock();
2022                                 mtx_unlock_spin(&tlbivax_mutex);
2023                         }
2024                 }
2025         }
2026         PMAP_UNLOCK(pmap);
2027 }
2028
2029 /*
2030  * Clear the write and modified bits in each of the given page's mappings.
2031  */
2032 static void
2033 mmu_booke_remove_write(mmu_t mmu, vm_page_t m)
2034 {
2035         pv_entry_t pv;
2036         pte_t *pte;
2037
2038         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2039             ("mmu_booke_remove_write: page %p is not managed", m));
2040
2041         /*
2042          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
2043          * set by another thread while the object is locked.  Thus,
2044          * if PGA_WRITEABLE is clear, no page table entries need updating.
2045          */
2046         VM_OBJECT_ASSERT_WLOCKED(m->object);
2047         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
2048                 return;
2049         rw_wlock(&pvh_global_lock);
2050         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2051                 PMAP_LOCK(pv->pv_pmap);
2052                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL) {
2053                         if (PTE_ISVALID(pte)) {
2054                                 m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2055
2056                                 mtx_lock_spin(&tlbivax_mutex);
2057                                 tlb_miss_lock();
2058
2059                                 /* Handle modified pages. */
2060                                 if (PTE_ISMODIFIED(pte))
2061                                         vm_page_dirty(m);
2062
2063                                 /* Flush mapping from TLB0. */
2064                                 pte->flags &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
2065
2066                                 tlb_miss_unlock();
2067                                 mtx_unlock_spin(&tlbivax_mutex);
2068                         }
2069                 }
2070                 PMAP_UNLOCK(pv->pv_pmap);
2071         }
2072         vm_page_aflag_clear(m, PGA_WRITEABLE);
2073         rw_wunlock(&pvh_global_lock);
2074 }
2075
2076 static void
2077 mmu_booke_sync_icache(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_size_t sz)
2078 {
2079         pte_t *pte;
2080         pmap_t pmap;
2081         vm_page_t m;
2082         vm_offset_t addr;
2083         vm_paddr_t pa = 0;
2084         int active, valid;
2085  
2086         va = trunc_page(va);
2087         sz = round_page(sz);
2088
2089         rw_wlock(&pvh_global_lock);
2090         pmap = PCPU_GET(curpmap);
2091         active = (pm == kernel_pmap || pm == pmap) ? 1 : 0;
2092         while (sz > 0) {
2093                 PMAP_LOCK(pm);
2094                 pte = pte_find(mmu, pm, va);
2095                 valid = (pte != NULL && PTE_ISVALID(pte)) ? 1 : 0;
2096                 if (valid)
2097                         pa = PTE_PA(pte);
2098                 PMAP_UNLOCK(pm);
2099                 if (valid) {
2100                         if (!active) {
2101                                 /* Create a mapping in the active pmap. */
2102                                 addr = 0;
2103                                 m = PHYS_TO_VM_PAGE(pa);
2104                                 PMAP_LOCK(pmap);
2105                                 pte_enter(mmu, pmap, m, addr,
2106                                     PTE_SR | PTE_VALID | PTE_UR, FALSE);
2107                                 __syncicache((void *)addr, PAGE_SIZE);
2108                                 pte_remove(mmu, pmap, addr, PTBL_UNHOLD);
2109                                 PMAP_UNLOCK(pmap);
2110                         } else
2111                                 __syncicache((void *)va, PAGE_SIZE);
2112                 }
2113                 va += PAGE_SIZE;
2114                 sz -= PAGE_SIZE;
2115         }
2116         rw_wunlock(&pvh_global_lock);
2117 }
2118
2119 /*
2120  * Atomically extract and hold the physical page with the given
2121  * pmap and virtual address pair if that mapping permits the given
2122  * protection.
2123  */
2124 static vm_page_t
2125 mmu_booke_extract_and_hold(mmu_t mmu, pmap_t pmap, vm_offset_t va,
2126     vm_prot_t prot)
2127 {
2128         pte_t *pte;
2129         vm_page_t m;
2130         uint32_t pte_wbit;
2131         vm_paddr_t pa;
2132         
2133         m = NULL;
2134         pa = 0; 
2135         PMAP_LOCK(pmap);
2136 retry:
2137         pte = pte_find(mmu, pmap, va);
2138         if ((pte != NULL) && PTE_ISVALID(pte)) {
2139                 if (pmap == kernel_pmap)
2140                         pte_wbit = PTE_SW;
2141                 else
2142                         pte_wbit = PTE_UW;
2143
2144                 if ((pte->flags & pte_wbit) || ((prot & VM_PROT_WRITE) == 0)) {
2145                         if (vm_page_pa_tryrelock(pmap, PTE_PA(pte), &pa))
2146                                 goto retry;
2147                         m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2148                         vm_page_hold(m);
2149                 }
2150         }
2151
2152         PA_UNLOCK_COND(pa);
2153         PMAP_UNLOCK(pmap);
2154         return (m);
2155 }
2156
2157 /*
2158  * Initialize a vm_page's machine-dependent fields.
2159  */
2160 static void
2161 mmu_booke_page_init(mmu_t mmu, vm_page_t m)
2162 {
2163
2164         TAILQ_INIT(&m->md.pv_list);
2165 }
2166
2167 /*
2168  * mmu_booke_zero_page_area zeros the specified hardware page by
2169  * mapping it into virtual memory and using bzero to clear
2170  * its contents.
2171  *
2172  * off and size must reside within a single page.
2173  */
2174 static void
2175 mmu_booke_zero_page_area(mmu_t mmu, vm_page_t m, int off, int size)
2176 {
2177         vm_offset_t va;
2178
2179         /* XXX KASSERT off and size are within a single page? */
2180
2181         mtx_lock(&zero_page_mutex);
2182         va = zero_page_va;
2183
2184         mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(m));
2185         bzero((caddr_t)va + off, size);
2186         mmu_booke_kremove(mmu, va);
2187
2188         mtx_unlock(&zero_page_mutex);
2189 }
2190
2191 /*
2192  * mmu_booke_zero_page zeros the specified hardware page.
2193  */
2194 static void
2195 mmu_booke_zero_page(mmu_t mmu, vm_page_t m)
2196 {
2197
2198         mmu_booke_zero_page_area(mmu, m, 0, PAGE_SIZE);
2199 }
2200
2201 /*
2202  * mmu_booke_copy_page copies the specified (machine independent) page by
2203  * mapping the page into virtual memory and using memcopy to copy the page,
2204  * one machine dependent page at a time.
2205  */
2206 static void
2207 mmu_booke_copy_page(mmu_t mmu, vm_page_t sm, vm_page_t dm)
2208 {
2209         vm_offset_t sva, dva;
2210
2211         sva = copy_page_src_va;
2212         dva = copy_page_dst_va;
2213
2214         mtx_lock(&copy_page_mutex);
2215         mmu_booke_kenter(mmu, sva, VM_PAGE_TO_PHYS(sm));
2216         mmu_booke_kenter(mmu, dva, VM_PAGE_TO_PHYS(dm));
2217         memcpy((caddr_t)dva, (caddr_t)sva, PAGE_SIZE);
2218         mmu_booke_kremove(mmu, dva);
2219         mmu_booke_kremove(mmu, sva);
2220         mtx_unlock(&copy_page_mutex);
2221 }
2222
2223 static inline void
2224 mmu_booke_copy_pages(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
2225     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
2226 {
2227         void *a_cp, *b_cp;
2228         vm_offset_t a_pg_offset, b_pg_offset;
2229         int cnt;
2230
2231         mtx_lock(&copy_page_mutex);
2232         while (xfersize > 0) {
2233                 a_pg_offset = a_offset & PAGE_MASK;
2234                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
2235                 mmu_booke_kenter(mmu, copy_page_src_va,
2236                     VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]));
2237                 a_cp = (char *)copy_page_src_va + a_pg_offset;
2238                 b_pg_offset = b_offset & PAGE_MASK;
2239                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
2240                 mmu_booke_kenter(mmu, copy_page_dst_va,
2241                     VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]));
2242                 b_cp = (char *)copy_page_dst_va + b_pg_offset;
2243                 bcopy(a_cp, b_cp, cnt);
2244                 mmu_booke_kremove(mmu, copy_page_dst_va);
2245                 mmu_booke_kremove(mmu, copy_page_src_va);
2246                 a_offset += cnt;
2247                 b_offset += cnt;
2248                 xfersize -= cnt;
2249         }
2250         mtx_unlock(&copy_page_mutex);
2251 }
2252
2253 /*
2254  * mmu_booke_zero_page_idle zeros the specified hardware page by mapping it
2255  * into virtual memory and using bzero to clear its contents. This is intended
2256  * to be called from the vm_pagezero process only and outside of Giant. No
2257  * lock is required.
2258  */
2259 static void
2260 mmu_booke_zero_page_idle(mmu_t mmu, vm_page_t m)
2261 {
2262         vm_offset_t va;
2263
2264         va = zero_page_idle_va;
2265         mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(m));
2266         bzero((caddr_t)va, PAGE_SIZE);
2267         mmu_booke_kremove(mmu, va);
2268 }
2269
2270 /*
2271  * Return whether or not the specified physical page was modified
2272  * in any of physical maps.
2273  */
2274 static boolean_t
2275 mmu_booke_is_modified(mmu_t mmu, vm_page_t m)
2276 {
2277         pte_t *pte;
2278         pv_entry_t pv;
2279         boolean_t rv;
2280
2281         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2282             ("mmu_booke_is_modified: page %p is not managed", m));
2283         rv = FALSE;
2284
2285         /*
2286          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
2287          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
2288          * is clear, no PTEs can be modified.
2289          */
2290         VM_OBJECT_ASSERT_WLOCKED(m->object);
2291         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
2292                 return (rv);
2293         rw_wlock(&pvh_global_lock);
2294         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2295                 PMAP_LOCK(pv->pv_pmap);
2296                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
2297                     PTE_ISVALID(pte)) {
2298                         if (PTE_ISMODIFIED(pte))
2299                                 rv = TRUE;
2300                 }
2301                 PMAP_UNLOCK(pv->pv_pmap);
2302                 if (rv)
2303                         break;
2304         }
2305         rw_wunlock(&pvh_global_lock);
2306         return (rv);
2307 }
2308
2309 /*
2310  * Return whether or not the specified virtual address is eligible
2311  * for prefault.
2312  */
2313 static boolean_t
2314 mmu_booke_is_prefaultable(mmu_t mmu, pmap_t pmap, vm_offset_t addr)
2315 {
2316
2317         return (FALSE);
2318 }
2319
2320 /*
2321  * Return whether or not the specified physical page was referenced
2322  * in any physical maps.
2323  */
2324 static boolean_t
2325 mmu_booke_is_referenced(mmu_t mmu, vm_page_t m)
2326 {
2327         pte_t *pte;
2328         pv_entry_t pv;
2329         boolean_t rv;
2330
2331         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2332             ("mmu_booke_is_referenced: page %p is not managed", m));
2333         rv = FALSE;
2334         rw_wlock(&pvh_global_lock);
2335         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2336                 PMAP_LOCK(pv->pv_pmap);
2337                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
2338                     PTE_ISVALID(pte)) {
2339                         if (PTE_ISREFERENCED(pte))
2340                                 rv = TRUE;
2341                 }
2342                 PMAP_UNLOCK(pv->pv_pmap);
2343                 if (rv)
2344                         break;
2345         }
2346         rw_wunlock(&pvh_global_lock);
2347         return (rv);
2348 }
2349
2350 /*
2351  * Clear the modify bits on the specified physical page.
2352  */
2353 static void
2354 mmu_booke_clear_modify(mmu_t mmu, vm_page_t m)
2355 {
2356         pte_t *pte;
2357         pv_entry_t pv;
2358
2359         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2360             ("mmu_booke_clear_modify: page %p is not managed", m));
2361         VM_OBJECT_ASSERT_WLOCKED(m->object);
2362         KASSERT(!vm_page_xbusied(m),
2363             ("mmu_booke_clear_modify: page %p is exclusive busied", m));
2364
2365         /*
2366          * If the page is not PG_AWRITEABLE, then no PTEs can be modified.
2367          * If the object containing the page is locked and the page is not
2368          * exclusive busied, then PG_AWRITEABLE cannot be concurrently set.
2369          */
2370         if ((m->aflags & PGA_WRITEABLE) == 0)
2371                 return;
2372         rw_wlock(&pvh_global_lock);
2373         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2374                 PMAP_LOCK(pv->pv_pmap);
2375                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
2376                     PTE_ISVALID(pte)) {
2377                         mtx_lock_spin(&tlbivax_mutex);
2378                         tlb_miss_lock();
2379                         
2380                         if (pte->flags & (PTE_SW | PTE_UW | PTE_MODIFIED)) {
2381                                 tlb0_flush_entry(pv->pv_va);
2382                                 pte->flags &= ~(PTE_SW | PTE_UW | PTE_MODIFIED |
2383                                     PTE_REFERENCED);
2384                         }
2385
2386                         tlb_miss_unlock();
2387                         mtx_unlock_spin(&tlbivax_mutex);
2388                 }
2389                 PMAP_UNLOCK(pv->pv_pmap);
2390         }
2391         rw_wunlock(&pvh_global_lock);
2392 }
2393
2394 /*
2395  * Return a count of reference bits for a page, clearing those bits.
2396  * It is not necessary for every reference bit to be cleared, but it
2397  * is necessary that 0 only be returned when there are truly no
2398  * reference bits set.
2399  *
2400  * XXX: The exact number of bits to check and clear is a matter that
2401  * should be tested and standardized at some point in the future for
2402  * optimal aging of shared pages.
2403  */
2404 static int
2405 mmu_booke_ts_referenced(mmu_t mmu, vm_page_t m)
2406 {
2407         pte_t *pte;
2408         pv_entry_t pv;
2409         int count;
2410
2411         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2412             ("mmu_booke_ts_referenced: page %p is not managed", m));
2413         count = 0;
2414         rw_wlock(&pvh_global_lock);
2415         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2416                 PMAP_LOCK(pv->pv_pmap);
2417                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
2418                     PTE_ISVALID(pte)) {
2419                         if (PTE_ISREFERENCED(pte)) {
2420                                 mtx_lock_spin(&tlbivax_mutex);
2421                                 tlb_miss_lock();
2422
2423                                 tlb0_flush_entry(pv->pv_va);
2424                                 pte->flags &= ~PTE_REFERENCED;
2425
2426                                 tlb_miss_unlock();
2427                                 mtx_unlock_spin(&tlbivax_mutex);
2428
2429                                 if (++count > 4) {
2430                                         PMAP_UNLOCK(pv->pv_pmap);
2431                                         break;
2432                                 }
2433                         }
2434                 }
2435                 PMAP_UNLOCK(pv->pv_pmap);
2436         }
2437         rw_wunlock(&pvh_global_lock);
2438         return (count);
2439 }
2440
2441 /*
2442  * Clear the wired attribute from the mappings for the specified range of
2443  * addresses in the given pmap.  Every valid mapping within that range must
2444  * have the wired attribute set.  In contrast, invalid mappings cannot have
2445  * the wired attribute set, so they are ignored.
2446  *
2447  * The wired attribute of the page table entry is not a hardware feature, so
2448  * there is no need to invalidate any TLB entries.
2449  */
2450 static void
2451 mmu_booke_unwire(mmu_t mmu, pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2452 {
2453         vm_offset_t va;
2454         pte_t *pte;
2455
2456         PMAP_LOCK(pmap);
2457         for (va = sva; va < eva; va += PAGE_SIZE) {
2458                 if ((pte = pte_find(mmu, pmap, va)) != NULL &&
2459                     PTE_ISVALID(pte)) {
2460                         if (!PTE_ISWIRED(pte))
2461                                 panic("mmu_booke_unwire: pte %p isn't wired",
2462                                     pte);
2463                         pte->flags &= ~PTE_WIRED;
2464                         pmap->pm_stats.wired_count--;
2465                 }
2466         }
2467         PMAP_UNLOCK(pmap);
2468
2469 }
2470
2471 /*
2472  * Return true if the pmap's pv is one of the first 16 pvs linked to from this
2473  * page.  This count may be changed upwards or downwards in the future; it is
2474  * only necessary that true be returned for a small subset of pmaps for proper
2475  * page aging.
2476  */
2477 static boolean_t
2478 mmu_booke_page_exists_quick(mmu_t mmu, pmap_t pmap, vm_page_t m)
2479 {
2480         pv_entry_t pv;
2481         int loops;
2482         boolean_t rv;
2483
2484         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2485             ("mmu_booke_page_exists_quick: page %p is not managed", m));
2486         loops = 0;
2487         rv = FALSE;
2488         rw_wlock(&pvh_global_lock);
2489         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2490                 if (pv->pv_pmap == pmap) {
2491                         rv = TRUE;
2492                         break;
2493                 }
2494                 if (++loops >= 16)
2495                         break;
2496         }
2497         rw_wunlock(&pvh_global_lock);
2498         return (rv);
2499 }
2500
2501 /*
2502  * Return the number of managed mappings to the given physical page that are
2503  * wired.
2504  */
2505 static int
2506 mmu_booke_page_wired_mappings(mmu_t mmu, vm_page_t m)
2507 {
2508         pv_entry_t pv;
2509         pte_t *pte;
2510         int count = 0;
2511
2512         if ((m->oflags & VPO_UNMANAGED) != 0)
2513                 return (count);
2514         rw_wlock(&pvh_global_lock);
2515         TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2516                 PMAP_LOCK(pv->pv_pmap);
2517                 if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL)
2518                         if (PTE_ISVALID(pte) && PTE_ISWIRED(pte))
2519                                 count++;
2520                 PMAP_UNLOCK(pv->pv_pmap);
2521         }
2522         rw_wunlock(&pvh_global_lock);
2523         return (count);
2524 }
2525
2526 static int
2527 mmu_booke_dev_direct_mapped(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2528 {
2529         int i;
2530         vm_offset_t va;
2531
2532         /*
2533          * This currently does not work for entries that
2534          * overlap TLB1 entries.
2535          */
2536         for (i = 0; i < tlb1_idx; i ++) {
2537                 if (tlb1_iomapped(i, pa, size, &va) == 0)
2538                         return (0);
2539         }
2540
2541         return (EFAULT);
2542 }
2543
2544 void
2545 mmu_booke_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz, void **va)
2546 {
2547         vm_paddr_t ppa;
2548         vm_offset_t ofs;
2549         vm_size_t gran;
2550
2551         /* Minidumps are based on virtual memory addresses. */
2552         if (do_minidump) {
2553                 *va = (void *)pa;
2554                 return;
2555         }
2556
2557         /* Raw physical memory dumps don't have a virtual address. */
2558         /* We always map a 256MB page at 256M. */
2559         gran = 256 * 1024 * 1024;
2560         ppa = pa & ~(gran - 1);
2561         ofs = pa - ppa;
2562         *va = (void *)gran;
2563         tlb1_set_entry((vm_offset_t)va, ppa, gran, _TLB_ENTRY_IO);
2564
2565         if (sz > (gran - ofs))
2566                 tlb1_set_entry((vm_offset_t)(va + gran), ppa + gran, gran,
2567                     _TLB_ENTRY_IO);
2568 }
2569
2570 void
2571 mmu_booke_dumpsys_unmap(mmu_t mmu, vm_paddr_t pa, size_t sz, void *va)
2572 {
2573         vm_paddr_t ppa;
2574         vm_offset_t ofs;
2575         vm_size_t gran;
2576
2577         /* Minidumps are based on virtual memory addresses. */
2578         /* Nothing to do... */
2579         if (do_minidump)
2580                 return;
2581
2582         /* Raw physical memory dumps don't have a virtual address. */
2583         tlb1_idx--;
2584         tlb1[tlb1_idx].mas1 = 0;
2585         tlb1[tlb1_idx].mas2 = 0;
2586         tlb1[tlb1_idx].mas3 = 0;
2587         tlb1_write_entry(tlb1_idx);
2588
2589         gran = 256 * 1024 * 1024;
2590         ppa = pa & ~(gran - 1);
2591         ofs = pa - ppa;
2592         if (sz > (gran - ofs)) {
2593                 tlb1_idx--;
2594                 tlb1[tlb1_idx].mas1 = 0;
2595                 tlb1[tlb1_idx].mas2 = 0;
2596                 tlb1[tlb1_idx].mas3 = 0;
2597                 tlb1_write_entry(tlb1_idx);
2598         }
2599 }
2600
2601 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
2602
2603 void
2604 mmu_booke_scan_init(mmu_t mmu)
2605 {
2606         vm_offset_t va;
2607         pte_t *pte;
2608         int i;
2609
2610         if (!do_minidump) {
2611                 /* Initialize phys. segments for dumpsys(). */
2612                 memset(&dump_map, 0, sizeof(dump_map));
2613                 mem_regions(&physmem_regions, &physmem_regions_sz, &availmem_regions,
2614                     &availmem_regions_sz);
2615                 for (i = 0; i < physmem_regions_sz; i++) {
2616                         dump_map[i].pa_start = physmem_regions[i].mr_start;
2617                         dump_map[i].pa_size = physmem_regions[i].mr_size;
2618                 }
2619                 return;
2620         }
2621
2622         /* Virtual segments for minidumps: */
2623         memset(&dump_map, 0, sizeof(dump_map));
2624
2625         /* 1st: kernel .data and .bss. */
2626         dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
2627         dump_map[0].pa_size =
2628             round_page((uintptr_t)_end) - dump_map[0].pa_start;
2629
2630         /* 2nd: msgbuf and tables (see pmap_bootstrap()). */
2631         dump_map[1].pa_start = data_start;
2632         dump_map[1].pa_size = data_end - data_start;
2633
2634         /* 3rd: kernel VM. */
2635         va = dump_map[1].pa_start + dump_map[1].pa_size;
2636         /* Find start of next chunk (from va). */
2637         while (va < virtual_end) {
2638                 /* Don't dump the buffer cache. */
2639                 if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
2640                         va = kmi.buffer_eva;
2641                         continue;
2642                 }
2643                 pte = pte_find(mmu, kernel_pmap, va);
2644                 if (pte != NULL && PTE_ISVALID(pte))
2645                         break;
2646                 va += PAGE_SIZE;
2647         }
2648         if (va < virtual_end) {
2649                 dump_map[2].pa_start = va;
2650                 va += PAGE_SIZE;
2651                 /* Find last page in chunk. */
2652                 while (va < virtual_end) {
2653                         /* Don't run into the buffer cache. */
2654                         if (va == kmi.buffer_sva)
2655                                 break;
2656                         pte = pte_find(mmu, kernel_pmap, va);
2657                         if (pte == NULL || !PTE_ISVALID(pte))
2658                                 break;
2659                         va += PAGE_SIZE;
2660                 }
2661                 dump_map[2].pa_size = va - dump_map[2].pa_start;
2662         }
2663 }
2664
2665 /*
2666  * Map a set of physical memory pages into the kernel virtual address space.
2667  * Return a pointer to where it is mapped. This routine is intended to be used
2668  * for mapping device memory, NOT real memory.
2669  */
2670 static void *
2671 mmu_booke_mapdev(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
2672 {
2673
2674         return (mmu_booke_mapdev_attr(mmu, pa, size, VM_MEMATTR_DEFAULT));
2675 }
2676
2677 static void *
2678 mmu_booke_mapdev_attr(mmu_t mmu, vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
2679 {
2680         void *res;
2681         uintptr_t va;
2682         vm_size_t sz;
2683         int i;
2684
2685         /*
2686          * Check if this is premapped in TLB1. Note: this should probably also
2687          * check whether a sequence of TLB1 entries exist that match the
2688          * requirement, but now only checks the easy case.
2689          */
2690         if (ma == VM_MEMATTR_DEFAULT) {
2691                 for (i = 0; i < tlb1_idx; i++) {
2692                         if (!(tlb1[i].mas1 & MAS1_VALID))
2693                                 continue;
2694                         if (pa >= tlb1[i].phys &&
2695                             (pa + size) <= (tlb1[i].phys + tlb1[i].size))
2696                                 return (void *)(tlb1[i].virt +
2697                                     (pa - tlb1[i].phys));
2698                 }
2699         }
2700
2701         size = roundup(size, PAGE_SIZE);
2702
2703         /*
2704          * We leave a hole for device direct mapping between the maximum user
2705          * address (0x8000000) and the minimum KVA address (0xc0000000). If
2706          * devices are in there, just map them 1:1. If not, map them to the
2707          * device mapping area about VM_MAX_KERNEL_ADDRESS. These mapped
2708          * addresses should be pulled from an allocator, but since we do not
2709          * ever free TLB1 entries, it is safe just to increment a counter.
2710          * Note that there isn't a lot of address space here (128 MB) and it
2711          * is not at all difficult to imagine running out, since that is a 4:1
2712          * compression from the 0xc0000000 - 0xf0000000 address space that gets
2713          * mapped there.
2714          */
2715         if (pa >= (VM_MAXUSER_ADDRESS + PAGE_SIZE) &&
2716             (pa + size - 1) < VM_MIN_KERNEL_ADDRESS) 
2717                 va = pa;
2718         else
2719                 va = atomic_fetchadd_int(&tlb1_map_base, size);
2720         res = (void *)va;
2721
2722         do {
2723                 sz = 1 << (ilog2(size) & ~1);
2724                 if (bootverbose)
2725                         printf("Wiring VA=%x to PA=%x (size=%x), "
2726                             "using TLB1[%d]\n", va, pa, sz, tlb1_idx);
2727                 tlb1_set_entry(va, pa, sz, tlb_calc_wimg(pa, ma));
2728                 size -= sz;
2729                 pa += sz;
2730                 va += sz;
2731         } while (size > 0);
2732
2733         return (res);
2734 }
2735
2736 /*
2737  * 'Unmap' a range mapped by mmu_booke_mapdev().
2738  */
2739 static void
2740 mmu_booke_unmapdev(mmu_t mmu, vm_offset_t va, vm_size_t size)
2741 {
2742 #ifdef SUPPORTS_SHRINKING_TLB1
2743         vm_offset_t base, offset;
2744
2745         /*
2746          * Unmap only if this is inside kernel virtual space.
2747          */
2748         if ((va >= VM_MIN_KERNEL_ADDRESS) && (va <= VM_MAX_KERNEL_ADDRESS)) {
2749                 base = trunc_page(va);
2750                 offset = va & PAGE_MASK;
2751                 size = roundup(offset + size, PAGE_SIZE);
2752                 kva_free(base, size);
2753         }
2754 #endif
2755 }
2756
2757 /*
2758  * mmu_booke_object_init_pt preloads the ptes for a given object into the
2759  * specified pmap. This eliminates the blast of soft faults on process startup
2760  * and immediately after an mmap.
2761  */
2762 static void
2763 mmu_booke_object_init_pt(mmu_t mmu, pmap_t pmap, vm_offset_t addr,
2764     vm_object_t object, vm_pindex_t pindex, vm_size_t size)
2765 {
2766
2767         VM_OBJECT_ASSERT_WLOCKED(object);
2768         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
2769             ("mmu_booke_object_init_pt: non-device object"));
2770 }
2771
2772 /*
2773  * Perform the pmap work for mincore.
2774  */
2775 static int
2776 mmu_booke_mincore(mmu_t mmu, pmap_t pmap, vm_offset_t addr,
2777     vm_paddr_t *locked_pa)
2778 {
2779
2780         /* XXX: this should be implemented at some point */
2781         return (0);
2782 }
2783
2784 /**************************************************************************/
2785 /* TID handling */
2786 /**************************************************************************/
2787
2788 /*
2789  * Allocate a TID. If necessary, steal one from someone else.
2790  * The new TID is flushed from the TLB before returning.
2791  */
2792 static tlbtid_t
2793 tid_alloc(pmap_t pmap)
2794 {
2795         tlbtid_t tid;
2796         int thiscpu;
2797
2798         KASSERT((pmap != kernel_pmap), ("tid_alloc: kernel pmap"));
2799
2800         CTR2(KTR_PMAP, "%s: s (pmap = %p)", __func__, pmap);
2801
2802         thiscpu = PCPU_GET(cpuid);
2803
2804         tid = PCPU_GET(tid_next);
2805         if (tid > TID_MAX)
2806                 tid = TID_MIN;
2807         PCPU_SET(tid_next, tid + 1);
2808
2809         /* If we are stealing TID then clear the relevant pmap's field */
2810         if (tidbusy[thiscpu][tid] != NULL) {
2811
2812                 CTR2(KTR_PMAP, "%s: warning: stealing tid %d", __func__, tid);
2813                 
2814                 tidbusy[thiscpu][tid]->pm_tid[thiscpu] = TID_NONE;
2815
2816                 /* Flush all entries from TLB0 matching this TID. */
2817                 tid_flush(tid);
2818         }
2819
2820         tidbusy[thiscpu][tid] = pmap;
2821         pmap->pm_tid[thiscpu] = tid;
2822         __asm __volatile("msync; isync");
2823
2824         CTR3(KTR_PMAP, "%s: e (%02d next = %02d)", __func__, tid,
2825             PCPU_GET(tid_next));
2826
2827         return (tid);
2828 }
2829
2830 /**************************************************************************/
2831 /* TLB0 handling */
2832 /**************************************************************************/
2833
2834 static void
2835 tlb_print_entry(int i, uint32_t mas1, uint32_t mas2, uint32_t mas3,
2836     uint32_t mas7)
2837 {
2838         int as;
2839         char desc[3];
2840         tlbtid_t tid;
2841         vm_size_t size;
2842         unsigned int tsize;
2843
2844         desc[2] = '\0';
2845         if (mas1 & MAS1_VALID)
2846                 desc[0] = 'V';
2847         else
2848                 desc[0] = ' ';
2849
2850         if (mas1 & MAS1_IPROT)
2851                 desc[1] = 'P';
2852         else
2853                 desc[1] = ' ';
2854
2855         as = (mas1 & MAS1_TS_MASK) ? 1 : 0;
2856         tid = MAS1_GETTID(mas1);
2857
2858         tsize = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
2859         size = 0;
2860         if (tsize)
2861                 size = tsize2size(tsize);
2862
2863         debugf("%3d: (%s) [AS=%d] "
2864             "sz = 0x%08x tsz = %d tid = %d mas1 = 0x%08x "
2865             "mas2(va) = 0x%08x mas3(pa) = 0x%08x mas7 = 0x%08x\n",
2866             i, desc, as, size, tsize, tid, mas1, mas2, mas3, mas7);
2867 }
2868
2869 /* Convert TLB0 va and way number to tlb0[] table index. */
2870 static inline unsigned int
2871 tlb0_tableidx(vm_offset_t va, unsigned int way)
2872 {
2873         unsigned int idx;
2874
2875         idx = (way * TLB0_ENTRIES_PER_WAY);
2876         idx += (va & MAS2_TLB0_ENTRY_IDX_MASK) >> MAS2_TLB0_ENTRY_IDX_SHIFT;
2877         return (idx);
2878 }
2879
2880 /*
2881  * Invalidate TLB0 entry.
2882  */
2883 static inline void
2884 tlb0_flush_entry(vm_offset_t va)
2885 {
2886
2887         CTR2(KTR_PMAP, "%s: s va=0x%08x", __func__, va);
2888
2889         mtx_assert(&tlbivax_mutex, MA_OWNED);
2890
2891         __asm __volatile("tlbivax 0, %0" :: "r"(va & MAS2_EPN_MASK));
2892         __asm __volatile("isync; msync");
2893         __asm __volatile("tlbsync; msync");
2894
2895         CTR1(KTR_PMAP, "%s: e", __func__);
2896 }
2897
2898 /* Print out contents of the MAS registers for each TLB0 entry */
2899 void
2900 tlb0_print_tlbentries(void)
2901 {
2902         uint32_t mas0, mas1, mas2, mas3, mas7;
2903         int entryidx, way, idx;
2904
2905         debugf("TLB0 entries:\n");
2906         for (way = 0; way < TLB0_WAYS; way ++)
2907                 for (entryidx = 0; entryidx < TLB0_ENTRIES_PER_WAY; entryidx++) {
2908
2909                         mas0 = MAS0_TLBSEL(0) | MAS0_ESEL(way);
2910                         mtspr(SPR_MAS0, mas0);
2911                         __asm __volatile("isync");
2912
2913                         mas2 = entryidx << MAS2_TLB0_ENTRY_IDX_SHIFT;
2914                         mtspr(SPR_MAS2, mas2);
2915
2916                         __asm __volatile("isync; tlbre");
2917
2918                         mas1 = mfspr(SPR_MAS1);
2919                         mas2 = mfspr(SPR_MAS2);
2920                         mas3 = mfspr(SPR_MAS3);
2921                         mas7 = mfspr(SPR_MAS7);
2922
2923                         idx = tlb0_tableidx(mas2, way);
2924                         tlb_print_entry(idx, mas1, mas2, mas3, mas7);
2925                 }
2926 }
2927
2928 /**************************************************************************/
2929 /* TLB1 handling */
2930 /**************************************************************************/
2931
2932 /*
2933  * TLB1 mapping notes:
2934  *
2935  * TLB1[0]      Kernel text and data.
2936  * TLB1[1-15]   Additional kernel text and data mappings (if required), PCI
2937  *              windows, other devices mappings.
2938  */
2939
2940 /*
2941  * Write given entry to TLB1 hardware.
2942  * Use 32 bit pa, clear 4 high-order bits of RPN (mas7).
2943  */
2944 static void
2945 tlb1_write_entry(unsigned int idx)
2946 {
2947         uint32_t mas0, mas7;
2948
2949         //debugf("tlb1_write_entry: s\n");
2950
2951         /* Clear high order RPN bits */
2952         mas7 = 0;
2953
2954         /* Select entry */
2955         mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(idx);
2956         //debugf("tlb1_write_entry: mas0 = 0x%08x\n", mas0);
2957
2958         mtspr(SPR_MAS0, mas0);
2959         __asm __volatile("isync");
2960         mtspr(SPR_MAS1, tlb1[idx].mas1);
2961         __asm __volatile("isync");
2962         mtspr(SPR_MAS2, tlb1[idx].mas2);
2963         __asm __volatile("isync");
2964         mtspr(SPR_MAS3, tlb1[idx].mas3);
2965         __asm __volatile("isync");
2966         mtspr(SPR_MAS7, mas7);
2967         __asm __volatile("isync; tlbwe; isync; msync");
2968
2969         //debugf("tlb1_write_entry: e\n");
2970 }
2971
2972 /*
2973  * Return the largest uint value log such that 2^log <= num.
2974  */
2975 static unsigned int
2976 ilog2(unsigned int num)
2977 {
2978         int lz;
2979
2980         __asm ("cntlzw %0, %1" : "=r" (lz) : "r" (num));
2981         return (31 - lz);
2982 }
2983
2984 /*
2985  * Convert TLB TSIZE value to mapped region size.
2986  */
2987 static vm_size_t
2988 tsize2size(unsigned int tsize)
2989 {
2990
2991         /*
2992          * size = 4^tsize KB
2993          * size = 4^tsize * 2^10 = 2^(2 * tsize - 10)
2994          */
2995
2996         return ((1 << (2 * tsize)) * 1024);
2997 }
2998
2999 /*
3000  * Convert region size (must be power of 4) to TLB TSIZE value.
3001  */
3002 static unsigned int
3003 size2tsize(vm_size_t size)
3004 {
3005
3006         return (ilog2(size) / 2 - 5);
3007 }
3008
3009 /*
3010  * Register permanent kernel mapping in TLB1.
3011  *
3012  * Entries are created starting from index 0 (current free entry is
3013  * kept in tlb1_idx) and are not supposed to be invalidated.
3014  */
3015 static int
3016 tlb1_set_entry(vm_offset_t va, vm_offset_t pa, vm_size_t size,
3017     uint32_t flags)
3018 {
3019         uint32_t ts, tid;
3020         int tsize, index;
3021
3022         index = atomic_fetchadd_int(&tlb1_idx, 1);
3023         if (index >= TLB1_ENTRIES) {
3024                 printf("tlb1_set_entry: TLB1 full!\n");
3025                 return (-1);
3026         }
3027
3028         /* Convert size to TSIZE */
3029         tsize = size2tsize(size);
3030
3031         tid = (TID_KERNEL << MAS1_TID_SHIFT) & MAS1_TID_MASK;
3032         /* XXX TS is hard coded to 0 for now as we only use single address space */
3033         ts = (0 << MAS1_TS_SHIFT) & MAS1_TS_MASK;
3034
3035         /*
3036          * Atomicity is preserved by the atomic increment above since nothing
3037          * is ever removed from tlb1.
3038          */
3039
3040         tlb1[index].phys = pa;
3041         tlb1[index].virt = va;
3042         tlb1[index].size = size;
3043         tlb1[index].mas1 = MAS1_VALID | MAS1_IPROT | ts | tid;
3044         tlb1[index].mas1 |= ((tsize << MAS1_TSIZE_SHIFT) & MAS1_TSIZE_MASK);
3045         tlb1[index].mas2 = (va & MAS2_EPN_MASK) | flags;
3046
3047         /* Set supervisor RWX permission bits */
3048         tlb1[index].mas3 = (pa & MAS3_RPN) | MAS3_SR | MAS3_SW | MAS3_SX;
3049
3050         tlb1_write_entry(index);
3051
3052         /*
3053          * XXX in general TLB1 updates should be propagated between CPUs,
3054          * since current design assumes to have the same TLB1 set-up on all
3055          * cores.
3056          */
3057         return (0);
3058 }
3059
3060 /*
3061  * Map in contiguous RAM region into the TLB1 using maximum of
3062  * KERNEL_REGION_MAX_TLB_ENTRIES entries.
3063  *
3064  * If necessary round up last entry size and return total size
3065  * used by all allocated entries.
3066  */
3067 vm_size_t
3068 tlb1_mapin_region(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
3069 {
3070         vm_size_t pgs[KERNEL_REGION_MAX_TLB_ENTRIES];
3071         vm_size_t mapped, pgsz, base, mask;
3072         int idx, nents;
3073
3074         /* Round up to the next 1M */
3075         size = (size + (1 << 20) - 1) & ~((1 << 20) - 1);
3076
3077         mapped = 0;
3078         idx = 0;
3079         base = va;
3080         pgsz = 64*1024*1024;
3081         while (mapped < size) {
3082                 while (mapped < size && idx < KERNEL_REGION_MAX_TLB_ENTRIES) {
3083                         while (pgsz > (size - mapped))
3084                                 pgsz >>= 2;
3085                         pgs[idx++] = pgsz;
3086                         mapped += pgsz;
3087                 }
3088
3089                 /* We under-map. Correct for this. */
3090                 if (mapped < size) {
3091                         while (pgs[idx - 1] == pgsz) {
3092                                 idx--;
3093                                 mapped -= pgsz;
3094                         }
3095                         /* XXX We may increase beyond out starting point. */
3096                         pgsz <<= 2;
3097                         pgs[idx++] = pgsz;
3098                         mapped += pgsz;
3099                 }
3100         }
3101
3102         nents = idx;
3103         mask = pgs[0] - 1;
3104         /* Align address to the boundary */
3105         if (va & mask) {
3106                 va = (va + mask) & ~mask;
3107                 pa = (pa + mask) & ~mask;
3108         }
3109
3110         for (idx = 0; idx < nents; idx++) {
3111                 pgsz = pgs[idx];
3112                 debugf("%u: %x -> %x, size=%x\n", idx, pa, va, pgsz);
3113                 tlb1_set_entry(va, pa, pgsz, _TLB_ENTRY_MEM);
3114                 pa += pgsz;
3115                 va += pgsz;
3116         }
3117
3118         mapped = (va - base);
3119         printf("mapped size 0x%08x (wasted space 0x%08x)\n",
3120             mapped, mapped - size);
3121         return (mapped);
3122 }
3123
3124 /*
3125  * TLB1 initialization routine, to be called after the very first
3126  * assembler level setup done in locore.S.
3127  */
3128 void
3129 tlb1_init()
3130 {
3131         uint32_t mas0, mas1, mas2, mas3;
3132         uint32_t tsz;
3133         u_int i;
3134
3135         if (bootinfo != NULL && bootinfo[0] != 1) {
3136                 tlb1_idx = *((uint16_t *)(bootinfo + 8));
3137         } else
3138                 tlb1_idx = 1;
3139
3140         /* The first entry/entries are used to map the kernel. */
3141         for (i = 0; i < tlb1_idx; i++) {
3142                 mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(i);
3143                 mtspr(SPR_MAS0, mas0);
3144                 __asm __volatile("isync; tlbre");
3145
3146                 mas1 = mfspr(SPR_MAS1);
3147                 if ((mas1 & MAS1_VALID) == 0)
3148                         continue;
3149
3150                 mas2 = mfspr(SPR_MAS2);
3151                 mas3 = mfspr(SPR_MAS3);
3152
3153                 tlb1[i].mas1 = mas1;
3154                 tlb1[i].mas2 = mfspr(SPR_MAS2);
3155                 tlb1[i].mas3 = mas3;
3156                 tlb1[i].virt = mas2 & MAS2_EPN_MASK;
3157                 tlb1[i].phys = mas3 & MAS3_RPN;
3158
3159                 if (i == 0)
3160                         kernload = mas3 & MAS3_RPN;
3161
3162                 tsz = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
3163                 tlb1[i].size = (tsz > 0) ? tsize2size(tsz) : 0;
3164                 kernsize += tlb1[i].size;
3165         }
3166
3167 #ifdef SMP
3168         bp_ntlb1s = tlb1_idx;
3169 #endif
3170
3171         /* Purge the remaining entries */
3172         for (i = tlb1_idx; i < TLB1_ENTRIES; i++)
3173                 tlb1_write_entry(i);
3174
3175         /* Setup TLB miss defaults */
3176         set_mas4_defaults();
3177 }
3178
3179 vm_offset_t 
3180 pmap_early_io_map(vm_paddr_t pa, vm_size_t size)
3181 {
3182         vm_paddr_t pa_base;
3183         vm_offset_t va, sz;
3184         int i;
3185
3186         KASSERT(!pmap_bootstrapped, ("Do not use after PMAP is up!"));
3187         
3188         for (i = 0; i < tlb1_idx; i++) {
3189                 if (!(tlb1[i].mas1 & MAS1_VALID))
3190                         continue;
3191                 if (pa >= tlb1[i].phys && (pa + size) <=
3192                     (tlb1[i].phys + tlb1[i].size))
3193                         return (tlb1[i].virt + (pa - tlb1[i].phys));
3194         }
3195
3196         pa_base = trunc_page(pa);
3197         size = roundup(size + (pa - pa_base), PAGE_SIZE);
3198         tlb1_map_base = roundup2(tlb1_map_base, 1 << (ilog2(size) & ~1));
3199         va = tlb1_map_base + (pa - pa_base);
3200
3201         do {
3202                 sz = 1 << (ilog2(size) & ~1);
3203                 tlb1_set_entry(tlb1_map_base, pa_base, sz, _TLB_ENTRY_IO);
3204                 size -= sz;
3205                 pa_base += sz;
3206                 tlb1_map_base += sz;
3207         } while (size > 0);
3208
3209 #ifdef SMP
3210         bp_ntlb1s = tlb1_idx;
3211 #endif
3212
3213         return (va);
3214 }
3215
3216 /*
3217  * Setup MAS4 defaults.
3218  * These values are loaded to MAS0-2 on a TLB miss.
3219  */
3220 static void
3221 set_mas4_defaults(void)
3222 {
3223         uint32_t mas4;
3224
3225         /* Defaults: TLB0, PID0, TSIZED=4K */
3226         mas4 = MAS4_TLBSELD0;
3227         mas4 |= (TLB_SIZE_4K << MAS4_TSIZED_SHIFT) & MAS4_TSIZED_MASK;
3228 #ifdef SMP
3229         mas4 |= MAS4_MD;
3230 #endif
3231         mtspr(SPR_MAS4, mas4);
3232         __asm __volatile("isync");
3233 }
3234
3235 /*
3236  * Print out contents of the MAS registers for each TLB1 entry
3237  */
3238 void
3239 tlb1_print_tlbentries(void)
3240 {
3241         uint32_t mas0, mas1, mas2, mas3, mas7;
3242         int i;
3243
3244         debugf("TLB1 entries:\n");
3245         for (i = 0; i < TLB1_ENTRIES; i++) {
3246
3247                 mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(i);
3248                 mtspr(SPR_MAS0, mas0);
3249
3250                 __asm __volatile("isync; tlbre");
3251
3252                 mas1 = mfspr(SPR_MAS1);
3253                 mas2 = mfspr(SPR_MAS2);
3254                 mas3 = mfspr(SPR_MAS3);
3255                 mas7 = mfspr(SPR_MAS7);
3256
3257                 tlb_print_entry(i, mas1, mas2, mas3, mas7);
3258         }
3259 }
3260
3261 /*
3262  * Print out contents of the in-ram tlb1 table.
3263  */
3264 void
3265 tlb1_print_entries(void)
3266 {
3267         int i;
3268
3269         debugf("tlb1[] table entries:\n");
3270         for (i = 0; i < TLB1_ENTRIES; i++)
3271                 tlb_print_entry(i, tlb1[i].mas1, tlb1[i].mas2, tlb1[i].mas3, 0);
3272 }
3273
3274 /*
3275  * Return 0 if the physical IO range is encompassed by one of the
3276  * the TLB1 entries, otherwise return related error code.
3277  */
3278 static int
3279 tlb1_iomapped(int i, vm_paddr_t pa, vm_size_t size, vm_offset_t *va)
3280 {
3281         uint32_t prot;
3282         vm_paddr_t pa_start;
3283         vm_paddr_t pa_end;
3284         unsigned int entry_tsize;
3285         vm_size_t entry_size;
3286
3287         *va = (vm_offset_t)NULL;
3288
3289         /* Skip invalid entries */
3290         if (!(tlb1[i].mas1 & MAS1_VALID))
3291                 return (EINVAL);
3292
3293         /*
3294          * The entry must be cache-inhibited, guarded, and r/w
3295          * so it can function as an i/o page
3296          */
3297         prot = tlb1[i].mas2 & (MAS2_I | MAS2_G);
3298         if (prot != (MAS2_I | MAS2_G))
3299                 return (EPERM);
3300
3301         prot = tlb1[i].mas3 & (MAS3_SR | MAS3_SW);
3302         if (prot != (MAS3_SR | MAS3_SW))
3303                 return (EPERM);
3304
3305         /* The address should be within the entry range. */
3306         entry_tsize = (tlb1[i].mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
3307         KASSERT((entry_tsize), ("tlb1_iomapped: invalid entry tsize"));
3308
3309         entry_size = tsize2size(entry_tsize);
3310         pa_start = tlb1[i].mas3 & MAS3_RPN;
3311         pa_end = pa_start + entry_size - 1;
3312
3313         if ((pa < pa_start) || ((pa + size) > pa_end))
3314                 return (ERANGE);
3315
3316         /* Return virtual address of this mapping. */
3317         *va = (tlb1[i].mas2 & MAS2_EPN_MASK) + (pa - pa_start);
3318         return (0);
3319 }