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