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