xref: /freebsd/sys/powerpc/booke/pmap.c (revision ca987d4641cdcd7f27e153db17c5bf064934faf5)
1 /*-
2  * Copyright (C) 2007-2009 Semihalf, Rafal Jaworowski <raj@semihalf.com>
3  * Copyright (C) 2006 Semihalf, Marian Balakowicz <m8@semihalf.com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
18  * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
20  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
22  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
23  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * Some hw specific parts of this pmap were derived or influenced
27  * by NetBSD's ibm4xx pmap module. More generic code is shared with
28  * a few other pmap modules from the FreeBSD tree.
29  */
30 
31  /*
32   * VM layout notes:
33   *
34   * Kernel and user threads run within one common virtual address space
35   * defined by AS=0.
36   *
37   * 32-bit pmap:
38   * Virtual address space layout:
39   * -----------------------------
40   * 0x0000_0000 - 0x7fff_ffff	: user process
41   * 0x8000_0000 - 0xbfff_ffff	: pmap_mapdev()-ed area (PCI/PCIE etc.)
42   * 0xc000_0000 - 0xc0ff_ffff	: kernel reserved
43   *   0xc000_0000 - data_end	: kernel code+data, env, metadata etc.
44   * 0xc100_0000 - 0xffff_ffff	: KVA
45   *   0xc100_0000 - 0xc100_3fff : reserved for page zero/copy
46   *   0xc100_4000 - 0xc200_3fff : reserved for ptbl bufs
47   *   0xc200_4000 - 0xc200_8fff : guard page + kstack0
48   *   0xc200_9000 - 0xfeef_ffff	: actual free KVA space
49   *
50   * 64-bit pmap:
51   * Virtual address space layout:
52   * -----------------------------
53   * 0x0000_0000_0000_0000 - 0xbfff_ffff_ffff_ffff      : user process
54   *   0x0000_0000_0000_0000 - 0x8fff_ffff_ffff_ffff    : text, data, heap, maps, libraries
55   *   0x9000_0000_0000_0000 - 0xafff_ffff_ffff_ffff    : mmio region
56   *   0xb000_0000_0000_0000 - 0xbfff_ffff_ffff_ffff    : stack
57   * 0xc000_0000_0000_0000 - 0xcfff_ffff_ffff_ffff      : kernel reserved
58   *   0xc000_0000_0000_0000 - endkernel-1              : kernel code & data
59   *               endkernel - msgbufp-1                : flat device tree
60   *                 msgbufp - ptbl_bufs-1              : message buffer
61   *               ptbl_bufs - kernel_pdir-1            : kernel page tables
62   *             kernel_pdir - kernel_pp2d-1            : kernel page directory
63   *             kernel_pp2d - .                        : kernel pointers to page directory
64   *      pmap_zero_copy_min - crashdumpmap-1           : reserved for page zero/copy
65   *            crashdumpmap - ptbl_buf_pool_vabase-1   : reserved for ptbl bufs
66   *    ptbl_buf_pool_vabase - virtual_avail-1          : user page directories and page tables
67   *           virtual_avail - 0xcfff_ffff_ffff_ffff    : actual free KVA space
68   * 0xd000_0000_0000_0000 - 0xdfff_ffff_ffff_ffff      : coprocessor region
69   * 0xe000_0000_0000_0000 - 0xefff_ffff_ffff_ffff      : mmio region
70   * 0xf000_0000_0000_0000 - 0xffff_ffff_ffff_ffff      : direct map
71   *   0xf000_0000_0000_0000 - +Maxmem                  : physmem map
72   *                         - 0xffff_ffff_ffff_ffff    : device direct map
73   */
74 
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77 
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/linker.h>
91 #include <sys/msgbuf.h>
92 #include <sys/lock.h>
93 #include <sys/mutex.h>
94 #include <sys/rwlock.h>
95 #include <sys/sched.h>
96 #include <sys/smp.h>
97 #include <sys/vmmeter.h>
98 
99 #include <vm/vm.h>
100 #include <vm/vm_page.h>
101 #include <vm/vm_kern.h>
102 #include <vm/vm_pageout.h>
103 #include <vm/vm_extern.h>
104 #include <vm/vm_object.h>
105 #include <vm/vm_param.h>
106 #include <vm/vm_map.h>
107 #include <vm/vm_pager.h>
108 #include <vm/uma.h>
109 
110 #include <machine/_inttypes.h>
111 #include <machine/cpu.h>
112 #include <machine/pcb.h>
113 #include <machine/platform.h>
114 
115 #include <machine/tlb.h>
116 #include <machine/spr.h>
117 #include <machine/md_var.h>
118 #include <machine/mmuvar.h>
119 #include <machine/pmap.h>
120 #include <machine/pte.h>
121 
122 #include "mmu_if.h"
123 
124 #define	SPARSE_MAPDEV
125 #ifdef  DEBUG
126 #define debugf(fmt, args...) printf(fmt, ##args)
127 #else
128 #define debugf(fmt, args...)
129 #endif
130 
131 #ifdef __powerpc64__
132 #define	PRI0ptrX	"016lx"
133 #else
134 #define	PRI0ptrX	"08x"
135 #endif
136 
137 #define TODO			panic("%s: not implemented", __func__);
138 
139 extern unsigned char _etext[];
140 extern unsigned char _end[];
141 
142 extern uint32_t *bootinfo;
143 
144 vm_paddr_t kernload;
145 vm_offset_t kernstart;
146 vm_size_t kernsize;
147 
148 /* Message buffer and tables. */
149 static vm_offset_t data_start;
150 static vm_size_t data_end;
151 
152 /* Phys/avail memory regions. */
153 static struct mem_region *availmem_regions;
154 static int availmem_regions_sz;
155 static struct mem_region *physmem_regions;
156 static int physmem_regions_sz;
157 
158 /* Reserved KVA space and mutex for mmu_booke_zero_page. */
159 static vm_offset_t zero_page_va;
160 static struct mtx zero_page_mutex;
161 
162 static struct mtx tlbivax_mutex;
163 
164 /* Reserved KVA space and mutex for mmu_booke_copy_page. */
165 static vm_offset_t copy_page_src_va;
166 static vm_offset_t copy_page_dst_va;
167 static struct mtx copy_page_mutex;
168 
169 /**************************************************************************/
170 /* PMAP */
171 /**************************************************************************/
172 
173 static int mmu_booke_enter_locked(mmu_t, pmap_t, vm_offset_t, vm_page_t,
174     vm_prot_t, u_int flags, int8_t psind);
175 
176 unsigned int kptbl_min;		/* Index of the first kernel ptbl. */
177 unsigned int kernel_ptbls;	/* Number of KVA ptbls. */
178 #ifdef __powerpc64__
179 unsigned int kernel_pdirs;
180 #endif
181 
182 /*
183  * If user pmap is processed with mmu_booke_remove and the resident count
184  * drops to 0, there are no more pages to remove, so we need not continue.
185  */
186 #define PMAP_REMOVE_DONE(pmap) \
187 	((pmap) != kernel_pmap && (pmap)->pm_stats.resident_count == 0)
188 
189 #if defined(COMPAT_FREEBSD32) || !defined(__powerpc64__)
190 extern int elf32_nxstack;
191 #endif
192 
193 /**************************************************************************/
194 /* TLB and TID handling */
195 /**************************************************************************/
196 
197 /* Translation ID busy table */
198 static volatile pmap_t tidbusy[MAXCPU][TID_MAX + 1];
199 
200 /*
201  * TLB0 capabilities (entry, way numbers etc.). These can vary between e500
202  * core revisions and should be read from h/w registers during early config.
203  */
204 uint32_t tlb0_entries;
205 uint32_t tlb0_ways;
206 uint32_t tlb0_entries_per_way;
207 uint32_t tlb1_entries;
208 
209 #define TLB0_ENTRIES		(tlb0_entries)
210 #define TLB0_WAYS		(tlb0_ways)
211 #define TLB0_ENTRIES_PER_WAY	(tlb0_entries_per_way)
212 
213 #define TLB1_ENTRIES (tlb1_entries)
214 
215 static vm_offset_t tlb1_map_base = VM_MAXUSER_ADDRESS + PAGE_SIZE;
216 
217 static tlbtid_t tid_alloc(struct pmap *);
218 static void tid_flush(tlbtid_t tid);
219 
220 #ifdef __powerpc64__
221 static void tlb_print_entry(int, uint32_t, uint64_t, uint32_t, uint32_t);
222 #else
223 static void tlb_print_entry(int, uint32_t, uint32_t, uint32_t, uint32_t);
224 #endif
225 
226 static void tlb1_read_entry(tlb_entry_t *, unsigned int);
227 static void tlb1_write_entry(tlb_entry_t *, unsigned int);
228 static int tlb1_iomapped(int, vm_paddr_t, vm_size_t, vm_offset_t *);
229 static vm_size_t tlb1_mapin_region(vm_offset_t, vm_paddr_t, vm_size_t);
230 
231 static vm_size_t tsize2size(unsigned int);
232 static unsigned int size2tsize(vm_size_t);
233 static unsigned int ilog2(unsigned int);
234 
235 static void set_mas4_defaults(void);
236 
237 static inline void tlb0_flush_entry(vm_offset_t);
238 static inline unsigned int tlb0_tableidx(vm_offset_t, unsigned int);
239 
240 /**************************************************************************/
241 /* Page table management */
242 /**************************************************************************/
243 
244 static struct rwlock_padalign pvh_global_lock;
245 
246 /* Data for the pv entry allocation mechanism */
247 static uma_zone_t pvzone;
248 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
249 
250 #define PV_ENTRY_ZONE_MIN	2048	/* min pv entries in uma zone */
251 
252 #ifndef PMAP_SHPGPERPROC
253 #define PMAP_SHPGPERPROC	200
254 #endif
255 
256 static void ptbl_init(void);
257 static struct ptbl_buf *ptbl_buf_alloc(void);
258 static void ptbl_buf_free(struct ptbl_buf *);
259 static void ptbl_free_pmap_ptbl(pmap_t, pte_t *);
260 
261 #ifdef __powerpc64__
262 static pte_t *ptbl_alloc(mmu_t, pmap_t, pte_t **,
263 			 unsigned int, boolean_t);
264 static void ptbl_free(mmu_t, pmap_t, pte_t **, unsigned int);
265 static void ptbl_hold(mmu_t, pmap_t, pte_t **, unsigned int);
266 static int ptbl_unhold(mmu_t, pmap_t, vm_offset_t);
267 #else
268 static pte_t *ptbl_alloc(mmu_t, pmap_t, unsigned int, boolean_t);
269 static void ptbl_free(mmu_t, pmap_t, unsigned int);
270 static void ptbl_hold(mmu_t, pmap_t, unsigned int);
271 static int ptbl_unhold(mmu_t, pmap_t, unsigned int);
272 #endif
273 
274 static vm_paddr_t pte_vatopa(mmu_t, pmap_t, vm_offset_t);
275 static int pte_enter(mmu_t, pmap_t, vm_page_t, vm_offset_t, uint32_t, boolean_t);
276 static int pte_remove(mmu_t, pmap_t, vm_offset_t, uint8_t);
277 static pte_t *pte_find(mmu_t, pmap_t, vm_offset_t);
278 static void kernel_pte_alloc(vm_offset_t, vm_offset_t, vm_offset_t);
279 
280 static pv_entry_t pv_alloc(void);
281 static void pv_free(pv_entry_t);
282 static void pv_insert(pmap_t, vm_offset_t, vm_page_t);
283 static void pv_remove(pmap_t, vm_offset_t, vm_page_t);
284 
285 static void booke_pmap_init_qpages(void);
286 
287 /* Number of kva ptbl buffers, each covering one ptbl (PTBL_PAGES). */
288 #ifdef __powerpc64__
289 #define PTBL_BUFS               (16UL * 16 * 16)
290 #else
291 #define PTBL_BUFS		(128 * 16)
292 #endif
293 
294 struct ptbl_buf {
295 	TAILQ_ENTRY(ptbl_buf) link;	/* list link */
296 	vm_offset_t kva;		/* va of mapping */
297 };
298 
299 /* ptbl free list and a lock used for access synchronization. */
300 static TAILQ_HEAD(, ptbl_buf) ptbl_buf_freelist;
301 static struct mtx ptbl_buf_freelist_lock;
302 
303 /* Base address of kva space allocated fot ptbl bufs. */
304 static vm_offset_t ptbl_buf_pool_vabase;
305 
306 /* Pointer to ptbl_buf structures. */
307 static struct ptbl_buf *ptbl_bufs;
308 
309 #ifdef SMP
310 extern tlb_entry_t __boot_tlb1[];
311 void pmap_bootstrap_ap(volatile uint32_t *);
312 #endif
313 
314 /*
315  * Kernel MMU interface
316  */
317 static void		mmu_booke_clear_modify(mmu_t, vm_page_t);
318 static void		mmu_booke_copy(mmu_t, pmap_t, pmap_t, vm_offset_t,
319     vm_size_t, vm_offset_t);
320 static void		mmu_booke_copy_page(mmu_t, vm_page_t, vm_page_t);
321 static void		mmu_booke_copy_pages(mmu_t, vm_page_t *,
322     vm_offset_t, vm_page_t *, vm_offset_t, int);
323 static int		mmu_booke_enter(mmu_t, pmap_t, vm_offset_t, vm_page_t,
324     vm_prot_t, u_int flags, int8_t psind);
325 static void		mmu_booke_enter_object(mmu_t, pmap_t, vm_offset_t, vm_offset_t,
326     vm_page_t, vm_prot_t);
327 static void		mmu_booke_enter_quick(mmu_t, pmap_t, vm_offset_t, vm_page_t,
328     vm_prot_t);
329 static vm_paddr_t	mmu_booke_extract(mmu_t, pmap_t, vm_offset_t);
330 static vm_page_t	mmu_booke_extract_and_hold(mmu_t, pmap_t, vm_offset_t,
331     vm_prot_t);
332 static void		mmu_booke_init(mmu_t);
333 static boolean_t	mmu_booke_is_modified(mmu_t, vm_page_t);
334 static boolean_t	mmu_booke_is_prefaultable(mmu_t, pmap_t, vm_offset_t);
335 static boolean_t	mmu_booke_is_referenced(mmu_t, vm_page_t);
336 static int		mmu_booke_ts_referenced(mmu_t, vm_page_t);
337 static vm_offset_t	mmu_booke_map(mmu_t, vm_offset_t *, vm_paddr_t, vm_paddr_t,
338     int);
339 static int		mmu_booke_mincore(mmu_t, pmap_t, vm_offset_t,
340     vm_paddr_t *);
341 static void		mmu_booke_object_init_pt(mmu_t, pmap_t, vm_offset_t,
342     vm_object_t, vm_pindex_t, vm_size_t);
343 static boolean_t	mmu_booke_page_exists_quick(mmu_t, pmap_t, vm_page_t);
344 static void		mmu_booke_page_init(mmu_t, vm_page_t);
345 static int		mmu_booke_page_wired_mappings(mmu_t, vm_page_t);
346 static void		mmu_booke_pinit(mmu_t, pmap_t);
347 static void		mmu_booke_pinit0(mmu_t, pmap_t);
348 static void		mmu_booke_protect(mmu_t, pmap_t, vm_offset_t, vm_offset_t,
349     vm_prot_t);
350 static void		mmu_booke_qenter(mmu_t, vm_offset_t, vm_page_t *, int);
351 static void		mmu_booke_qremove(mmu_t, vm_offset_t, int);
352 static void		mmu_booke_release(mmu_t, pmap_t);
353 static void		mmu_booke_remove(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
354 static void		mmu_booke_remove_all(mmu_t, vm_page_t);
355 static void		mmu_booke_remove_write(mmu_t, vm_page_t);
356 static void		mmu_booke_unwire(mmu_t, pmap_t, vm_offset_t, vm_offset_t);
357 static void		mmu_booke_zero_page(mmu_t, vm_page_t);
358 static void		mmu_booke_zero_page_area(mmu_t, vm_page_t, int, int);
359 static void		mmu_booke_activate(mmu_t, struct thread *);
360 static void		mmu_booke_deactivate(mmu_t, struct thread *);
361 static void		mmu_booke_bootstrap(mmu_t, vm_offset_t, vm_offset_t);
362 static void		*mmu_booke_mapdev(mmu_t, vm_paddr_t, vm_size_t);
363 static void		*mmu_booke_mapdev_attr(mmu_t, vm_paddr_t, vm_size_t, vm_memattr_t);
364 static void		mmu_booke_unmapdev(mmu_t, vm_offset_t, vm_size_t);
365 static vm_paddr_t	mmu_booke_kextract(mmu_t, vm_offset_t);
366 static void		mmu_booke_kenter(mmu_t, vm_offset_t, vm_paddr_t);
367 static void		mmu_booke_kenter_attr(mmu_t, vm_offset_t, vm_paddr_t, vm_memattr_t);
368 static void		mmu_booke_kremove(mmu_t, vm_offset_t);
369 static boolean_t	mmu_booke_dev_direct_mapped(mmu_t, vm_paddr_t, vm_size_t);
370 static void		mmu_booke_sync_icache(mmu_t, pmap_t, vm_offset_t,
371     vm_size_t);
372 static void		mmu_booke_dumpsys_map(mmu_t, vm_paddr_t pa, size_t,
373     void **);
374 static void		mmu_booke_dumpsys_unmap(mmu_t, vm_paddr_t pa, size_t,
375     void *);
376 static void		mmu_booke_scan_init(mmu_t);
377 static vm_offset_t	mmu_booke_quick_enter_page(mmu_t mmu, vm_page_t m);
378 static void		mmu_booke_quick_remove_page(mmu_t mmu, vm_offset_t addr);
379 static int		mmu_booke_change_attr(mmu_t mmu, vm_offset_t addr,
380     vm_size_t sz, vm_memattr_t mode);
381 
382 static mmu_method_t mmu_booke_methods[] = {
383 	/* pmap dispatcher interface */
384 	MMUMETHOD(mmu_clear_modify,	mmu_booke_clear_modify),
385 	MMUMETHOD(mmu_copy,		mmu_booke_copy),
386 	MMUMETHOD(mmu_copy_page,	mmu_booke_copy_page),
387 	MMUMETHOD(mmu_copy_pages,	mmu_booke_copy_pages),
388 	MMUMETHOD(mmu_enter,		mmu_booke_enter),
389 	MMUMETHOD(mmu_enter_object,	mmu_booke_enter_object),
390 	MMUMETHOD(mmu_enter_quick,	mmu_booke_enter_quick),
391 	MMUMETHOD(mmu_extract,		mmu_booke_extract),
392 	MMUMETHOD(mmu_extract_and_hold,	mmu_booke_extract_and_hold),
393 	MMUMETHOD(mmu_init,		mmu_booke_init),
394 	MMUMETHOD(mmu_is_modified,	mmu_booke_is_modified),
395 	MMUMETHOD(mmu_is_prefaultable,	mmu_booke_is_prefaultable),
396 	MMUMETHOD(mmu_is_referenced,	mmu_booke_is_referenced),
397 	MMUMETHOD(mmu_ts_referenced,	mmu_booke_ts_referenced),
398 	MMUMETHOD(mmu_map,		mmu_booke_map),
399 	MMUMETHOD(mmu_mincore,		mmu_booke_mincore),
400 	MMUMETHOD(mmu_object_init_pt,	mmu_booke_object_init_pt),
401 	MMUMETHOD(mmu_page_exists_quick,mmu_booke_page_exists_quick),
402 	MMUMETHOD(mmu_page_init,	mmu_booke_page_init),
403 	MMUMETHOD(mmu_page_wired_mappings, mmu_booke_page_wired_mappings),
404 	MMUMETHOD(mmu_pinit,		mmu_booke_pinit),
405 	MMUMETHOD(mmu_pinit0,		mmu_booke_pinit0),
406 	MMUMETHOD(mmu_protect,		mmu_booke_protect),
407 	MMUMETHOD(mmu_qenter,		mmu_booke_qenter),
408 	MMUMETHOD(mmu_qremove,		mmu_booke_qremove),
409 	MMUMETHOD(mmu_release,		mmu_booke_release),
410 	MMUMETHOD(mmu_remove,		mmu_booke_remove),
411 	MMUMETHOD(mmu_remove_all,	mmu_booke_remove_all),
412 	MMUMETHOD(mmu_remove_write,	mmu_booke_remove_write),
413 	MMUMETHOD(mmu_sync_icache,	mmu_booke_sync_icache),
414 	MMUMETHOD(mmu_unwire,		mmu_booke_unwire),
415 	MMUMETHOD(mmu_zero_page,	mmu_booke_zero_page),
416 	MMUMETHOD(mmu_zero_page_area,	mmu_booke_zero_page_area),
417 	MMUMETHOD(mmu_activate,		mmu_booke_activate),
418 	MMUMETHOD(mmu_deactivate,	mmu_booke_deactivate),
419 	MMUMETHOD(mmu_quick_enter_page, mmu_booke_quick_enter_page),
420 	MMUMETHOD(mmu_quick_remove_page, mmu_booke_quick_remove_page),
421 
422 	/* Internal interfaces */
423 	MMUMETHOD(mmu_bootstrap,	mmu_booke_bootstrap),
424 	MMUMETHOD(mmu_dev_direct_mapped,mmu_booke_dev_direct_mapped),
425 	MMUMETHOD(mmu_mapdev,		mmu_booke_mapdev),
426 	MMUMETHOD(mmu_mapdev_attr,	mmu_booke_mapdev_attr),
427 	MMUMETHOD(mmu_kenter,		mmu_booke_kenter),
428 	MMUMETHOD(mmu_kenter_attr,	mmu_booke_kenter_attr),
429 	MMUMETHOD(mmu_kextract,		mmu_booke_kextract),
430 	MMUMETHOD(mmu_kremove,		mmu_booke_kremove),
431 	MMUMETHOD(mmu_unmapdev,		mmu_booke_unmapdev),
432 	MMUMETHOD(mmu_change_attr,	mmu_booke_change_attr),
433 
434 	/* dumpsys() support */
435 	MMUMETHOD(mmu_dumpsys_map,	mmu_booke_dumpsys_map),
436 	MMUMETHOD(mmu_dumpsys_unmap,	mmu_booke_dumpsys_unmap),
437 	MMUMETHOD(mmu_scan_init,	mmu_booke_scan_init),
438 
439 	{ 0, 0 }
440 };
441 
442 MMU_DEF(booke_mmu, MMU_TYPE_BOOKE, mmu_booke_methods, 0);
443 
444 static __inline uint32_t
445 tlb_calc_wimg(vm_paddr_t pa, vm_memattr_t ma)
446 {
447 	uint32_t attrib;
448 	int i;
449 
450 	if (ma != VM_MEMATTR_DEFAULT) {
451 		switch (ma) {
452 		case VM_MEMATTR_UNCACHEABLE:
453 			return (MAS2_I | MAS2_G);
454 		case VM_MEMATTR_WRITE_COMBINING:
455 		case VM_MEMATTR_WRITE_BACK:
456 		case VM_MEMATTR_PREFETCHABLE:
457 			return (MAS2_I);
458 		case VM_MEMATTR_WRITE_THROUGH:
459 			return (MAS2_W | MAS2_M);
460 		case VM_MEMATTR_CACHEABLE:
461 			return (MAS2_M);
462 		}
463 	}
464 
465 	/*
466 	 * Assume the page is cache inhibited and access is guarded unless
467 	 * it's in our available memory array.
468 	 */
469 	attrib = _TLB_ENTRY_IO;
470 	for (i = 0; i < physmem_regions_sz; i++) {
471 		if ((pa >= physmem_regions[i].mr_start) &&
472 		    (pa < (physmem_regions[i].mr_start +
473 		     physmem_regions[i].mr_size))) {
474 			attrib = _TLB_ENTRY_MEM;
475 			break;
476 		}
477 	}
478 
479 	return (attrib);
480 }
481 
482 static inline void
483 tlb_miss_lock(void)
484 {
485 #ifdef SMP
486 	struct pcpu *pc;
487 
488 	if (!smp_started)
489 		return;
490 
491 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
492 		if (pc != pcpup) {
493 
494 			CTR3(KTR_PMAP, "%s: tlb miss LOCK of CPU=%d, "
495 			    "tlb_lock=%p", __func__, pc->pc_cpuid, pc->pc_booke_tlb_lock);
496 
497 			KASSERT((pc->pc_cpuid != PCPU_GET(cpuid)),
498 			    ("tlb_miss_lock: tried to lock self"));
499 
500 			tlb_lock(pc->pc_booke_tlb_lock);
501 
502 			CTR1(KTR_PMAP, "%s: locked", __func__);
503 		}
504 	}
505 #endif
506 }
507 
508 static inline void
509 tlb_miss_unlock(void)
510 {
511 #ifdef SMP
512 	struct pcpu *pc;
513 
514 	if (!smp_started)
515 		return;
516 
517 	STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
518 		if (pc != pcpup) {
519 			CTR2(KTR_PMAP, "%s: tlb miss UNLOCK of CPU=%d",
520 			    __func__, pc->pc_cpuid);
521 
522 			tlb_unlock(pc->pc_booke_tlb_lock);
523 
524 			CTR1(KTR_PMAP, "%s: unlocked", __func__);
525 		}
526 	}
527 #endif
528 }
529 
530 /* Return number of entries in TLB0. */
531 static __inline void
532 tlb0_get_tlbconf(void)
533 {
534 	uint32_t tlb0_cfg;
535 
536 	tlb0_cfg = mfspr(SPR_TLB0CFG);
537 	tlb0_entries = tlb0_cfg & TLBCFG_NENTRY_MASK;
538 	tlb0_ways = (tlb0_cfg & TLBCFG_ASSOC_MASK) >> TLBCFG_ASSOC_SHIFT;
539 	tlb0_entries_per_way = tlb0_entries / tlb0_ways;
540 }
541 
542 /* Return number of entries in TLB1. */
543 static __inline void
544 tlb1_get_tlbconf(void)
545 {
546 	uint32_t tlb1_cfg;
547 
548 	tlb1_cfg = mfspr(SPR_TLB1CFG);
549 	tlb1_entries = tlb1_cfg & TLBCFG_NENTRY_MASK;
550 }
551 
552 /**************************************************************************/
553 /* Page table related */
554 /**************************************************************************/
555 
556 #ifdef __powerpc64__
557 /* Initialize pool of kva ptbl buffers. */
558 static void
559 ptbl_init(void)
560 {
561 	int		i;
562 
563 	mtx_init(&ptbl_buf_freelist_lock, "ptbl bufs lock", NULL, MTX_DEF);
564 	TAILQ_INIT(&ptbl_buf_freelist);
565 
566 	for (i = 0; i < PTBL_BUFS; i++) {
567 		ptbl_bufs[i].kva = ptbl_buf_pool_vabase +
568 		    i * MAX(PTBL_PAGES,PDIR_PAGES) * PAGE_SIZE;
569 		TAILQ_INSERT_TAIL(&ptbl_buf_freelist, &ptbl_bufs[i], link);
570 	}
571 }
572 
573 /* Get an sf_buf from the freelist. */
574 static struct ptbl_buf *
575 ptbl_buf_alloc(void)
576 {
577 	struct ptbl_buf *buf;
578 
579 	mtx_lock(&ptbl_buf_freelist_lock);
580 	buf = TAILQ_FIRST(&ptbl_buf_freelist);
581 	if (buf != NULL)
582 		TAILQ_REMOVE(&ptbl_buf_freelist, buf, link);
583 	mtx_unlock(&ptbl_buf_freelist_lock);
584 
585 	return (buf);
586 }
587 
588 /* Return ptbl buff to free pool. */
589 static void
590 ptbl_buf_free(struct ptbl_buf *buf)
591 {
592 	mtx_lock(&ptbl_buf_freelist_lock);
593 	TAILQ_INSERT_TAIL(&ptbl_buf_freelist, buf, link);
594 	mtx_unlock(&ptbl_buf_freelist_lock);
595 }
596 
597 /*
598  * Search the list of allocated ptbl bufs and find on list of allocated ptbls
599  */
600 static void
601 ptbl_free_pmap_ptbl(pmap_t pmap, pte_t * ptbl)
602 {
603 	struct ptbl_buf *pbuf;
604 
605 	TAILQ_FOREACH(pbuf, &pmap->pm_ptbl_list, link) {
606 		if (pbuf->kva == (vm_offset_t) ptbl) {
607 			/* Remove from pmap ptbl buf list. */
608 			TAILQ_REMOVE(&pmap->pm_ptbl_list, pbuf, link);
609 
610 			/* Free corresponding ptbl buf. */
611 			ptbl_buf_free(pbuf);
612 
613 			break;
614 		}
615 	}
616 }
617 
618 /* Get a pointer to a PTE in a page table. */
619 static __inline pte_t *
620 pte_find(mmu_t mmu, pmap_t pmap, vm_offset_t va)
621 {
622 	pte_t         **pdir;
623 	pte_t          *ptbl;
624 
625 	KASSERT((pmap != NULL), ("pte_find: invalid pmap"));
626 
627 	pdir = pmap->pm_pp2d[PP2D_IDX(va)];
628 	if (!pdir)
629 		return NULL;
630 	ptbl = pdir[PDIR_IDX(va)];
631 	return ((ptbl != NULL) ? &ptbl[PTBL_IDX(va)] : NULL);
632 }
633 
634 /*
635  * Search the list of allocated pdir bufs and find on list of allocated pdirs
636  */
637 static void
638 ptbl_free_pmap_pdir(mmu_t mmu, pmap_t pmap, pte_t ** pdir)
639 {
640 	struct ptbl_buf *pbuf;
641 
642 	TAILQ_FOREACH(pbuf, &pmap->pm_pdir_list, link) {
643 		if (pbuf->kva == (vm_offset_t) pdir) {
644 			/* Remove from pmap ptbl buf list. */
645 			TAILQ_REMOVE(&pmap->pm_pdir_list, pbuf, link);
646 
647 			/* Free corresponding pdir buf. */
648 			ptbl_buf_free(pbuf);
649 
650 			break;
651 		}
652 	}
653 }
654 /* Free pdir pages and invalidate pdir entry. */
655 static void
656 pdir_free(mmu_t mmu, pmap_t pmap, unsigned int pp2d_idx)
657 {
658 	pte_t         **pdir;
659 	vm_paddr_t	pa;
660 	vm_offset_t	va;
661 	vm_page_t	m;
662 	int		i;
663 
664 	pdir = pmap->pm_pp2d[pp2d_idx];
665 
666 	KASSERT((pdir != NULL), ("pdir_free: null pdir"));
667 
668 	pmap->pm_pp2d[pp2d_idx] = NULL;
669 
670 	for (i = 0; i < PDIR_PAGES; i++) {
671 		va = ((vm_offset_t) pdir + (i * PAGE_SIZE));
672 		pa = pte_vatopa(mmu, kernel_pmap, va);
673 		m = PHYS_TO_VM_PAGE(pa);
674 		vm_page_free_zero(m);
675 		atomic_subtract_int(&vm_cnt.v_wire_count, 1);
676 		pmap_kremove(va);
677 	}
678 
679 	ptbl_free_pmap_pdir(mmu, pmap, pdir);
680 }
681 
682 /*
683  * Decrement pdir pages hold count and attempt to free pdir pages. Called
684  * when removing directory entry from pdir.
685  *
686  * Return 1 if pdir pages were freed.
687  */
688 static int
689 pdir_unhold(mmu_t mmu, pmap_t pmap, u_int pp2d_idx)
690 {
691 	pte_t         **pdir;
692 	vm_paddr_t	pa;
693 	vm_page_t	m;
694 	int		i;
695 
696 	KASSERT((pmap != kernel_pmap),
697 		("pdir_unhold: unholding kernel pdir!"));
698 
699 	pdir = pmap->pm_pp2d[pp2d_idx];
700 
701 	KASSERT(((vm_offset_t) pdir >= VM_MIN_KERNEL_ADDRESS),
702 	    ("pdir_unhold: non kva pdir"));
703 
704 	/* decrement hold count */
705 	for (i = 0; i < PDIR_PAGES; i++) {
706 		pa = pte_vatopa(mmu, kernel_pmap,
707 		    (vm_offset_t) pdir + (i * PAGE_SIZE));
708 		m = PHYS_TO_VM_PAGE(pa);
709 		m->wire_count--;
710 	}
711 
712 	/*
713 	 * Free pdir pages if there are no dir entries in this pdir.
714 	 * wire_count has the same value for all ptbl pages, so check the
715 	 * last page.
716 	 */
717 	if (m->wire_count == 0) {
718 		pdir_free(mmu, pmap, pp2d_idx);
719 		return (1);
720 	}
721 	return (0);
722 }
723 
724 /*
725  * Increment hold count for pdir pages. This routine is used when new ptlb
726  * entry is being inserted into pdir.
727  */
728 static void
729 pdir_hold(mmu_t mmu, pmap_t pmap, pte_t ** pdir)
730 {
731 	vm_paddr_t	pa;
732 	vm_page_t	m;
733 	int		i;
734 
735 	KASSERT((pmap != kernel_pmap),
736 		("pdir_hold: holding kernel pdir!"));
737 
738 	KASSERT((pdir != NULL), ("pdir_hold: null pdir"));
739 
740 	for (i = 0; i < PDIR_PAGES; i++) {
741 		pa = pte_vatopa(mmu, kernel_pmap,
742 				(vm_offset_t) pdir + (i * PAGE_SIZE));
743 		m = PHYS_TO_VM_PAGE(pa);
744 		m->wire_count++;
745 	}
746 }
747 
748 /* Allocate page table. */
749 static pte_t   *
750 ptbl_alloc(mmu_t mmu, pmap_t pmap, pte_t ** pdir, unsigned int pdir_idx,
751     boolean_t nosleep)
752 {
753 	vm_page_t	mtbl  [PTBL_PAGES];
754 	vm_page_t	m;
755 	struct ptbl_buf *pbuf;
756 	unsigned int	pidx;
757 	pte_t          *ptbl;
758 	int		i, j;
759 	int		req;
760 
761 	KASSERT((pdir[pdir_idx] == NULL),
762 		("%s: valid ptbl entry exists!", __func__));
763 
764 	pbuf = ptbl_buf_alloc();
765 	if (pbuf == NULL)
766 		panic("%s: couldn't alloc kernel virtual memory", __func__);
767 
768 	ptbl = (pte_t *) pbuf->kva;
769 
770 	for (i = 0; i < PTBL_PAGES; i++) {
771 		pidx = (PTBL_PAGES * pdir_idx) + i;
772 		req = VM_ALLOC_NOOBJ | VM_ALLOC_WIRED;
773 		while ((m = vm_page_alloc(NULL, pidx, req)) == NULL) {
774 			PMAP_UNLOCK(pmap);
775 			rw_wunlock(&pvh_global_lock);
776 			if (nosleep) {
777 				ptbl_free_pmap_ptbl(pmap, ptbl);
778 				for (j = 0; j < i; j++)
779 					vm_page_free(mtbl[j]);
780 				atomic_subtract_int(&vm_cnt.v_wire_count, i);
781 				return (NULL);
782 			}
783 			VM_WAIT;
784 			rw_wlock(&pvh_global_lock);
785 			PMAP_LOCK(pmap);
786 		}
787 		mtbl[i] = m;
788 	}
789 
790 	/* Mapin allocated pages into kernel_pmap. */
791 	mmu_booke_qenter(mmu, (vm_offset_t) ptbl, mtbl, PTBL_PAGES);
792 	/* Zero whole ptbl. */
793 	bzero((caddr_t) ptbl, PTBL_PAGES * PAGE_SIZE);
794 
795 	/* Add pbuf to the pmap ptbl bufs list. */
796 	TAILQ_INSERT_TAIL(&pmap->pm_ptbl_list, pbuf, link);
797 
798 	return (ptbl);
799 }
800 
801 /* Free ptbl pages and invalidate pdir entry. */
802 static void
803 ptbl_free(mmu_t mmu, pmap_t pmap, pte_t ** pdir, unsigned int pdir_idx)
804 {
805 	pte_t          *ptbl;
806 	vm_paddr_t	pa;
807 	vm_offset_t	va;
808 	vm_page_t	m;
809 	int		i;
810 
811 	ptbl = pdir[pdir_idx];
812 
813 	KASSERT((ptbl != NULL), ("ptbl_free: null ptbl"));
814 
815 	pdir[pdir_idx] = NULL;
816 
817 	for (i = 0; i < PTBL_PAGES; i++) {
818 		va = ((vm_offset_t) ptbl + (i * PAGE_SIZE));
819 		pa = pte_vatopa(mmu, kernel_pmap, va);
820 		m = PHYS_TO_VM_PAGE(pa);
821 		vm_page_free_zero(m);
822 		atomic_subtract_int(&vm_cnt.v_wire_count, 1);
823 		pmap_kremove(va);
824 	}
825 
826 	ptbl_free_pmap_ptbl(pmap, ptbl);
827 }
828 
829 /*
830  * Decrement ptbl pages hold count and attempt to free ptbl pages. Called
831  * when removing pte entry from ptbl.
832  *
833  * Return 1 if ptbl pages were freed.
834  */
835 static int
836 ptbl_unhold(mmu_t mmu, pmap_t pmap, vm_offset_t va)
837 {
838 	pte_t          *ptbl;
839 	vm_paddr_t	pa;
840 	vm_page_t	m;
841 	u_int		pp2d_idx;
842 	pte_t         **pdir;
843 	u_int		pdir_idx;
844 	int		i;
845 
846 	pp2d_idx = PP2D_IDX(va);
847 	pdir_idx = PDIR_IDX(va);
848 
849 	KASSERT((pmap != kernel_pmap),
850 		("ptbl_unhold: unholding kernel ptbl!"));
851 
852 	pdir = pmap->pm_pp2d[pp2d_idx];
853 	ptbl = pdir[pdir_idx];
854 
855 	KASSERT(((vm_offset_t) ptbl >= VM_MIN_KERNEL_ADDRESS),
856 	    ("ptbl_unhold: non kva ptbl"));
857 
858 	/* decrement hold count */
859 	for (i = 0; i < PTBL_PAGES; i++) {
860 		pa = pte_vatopa(mmu, kernel_pmap,
861 		    (vm_offset_t) ptbl + (i * PAGE_SIZE));
862 		m = PHYS_TO_VM_PAGE(pa);
863 		m->wire_count--;
864 	}
865 
866 	/*
867 	 * Free ptbl pages if there are no pte entries in this ptbl.
868 	 * wire_count has the same value for all ptbl pages, so check the
869 	 * last page.
870 	 */
871 	if (m->wire_count == 0) {
872 		/* A pair of indirect entries might point to this ptbl page */
873 #if 0
874 		tlb_flush_entry(pmap, va & ~((2UL * PAGE_SIZE_1M) - 1),
875 				TLB_SIZE_1M, MAS6_SIND);
876 		tlb_flush_entry(pmap, (va & ~((2UL * PAGE_SIZE_1M) - 1)) | PAGE_SIZE_1M,
877 				TLB_SIZE_1M, MAS6_SIND);
878 #endif
879 		ptbl_free(mmu, pmap, pdir, pdir_idx);
880 		pdir_unhold(mmu, pmap, pp2d_idx);
881 		return (1);
882 	}
883 	return (0);
884 }
885 
886 /*
887  * Increment hold count for ptbl pages. This routine is used when new pte
888  * entry is being inserted into ptbl.
889  */
890 static void
891 ptbl_hold(mmu_t mmu, pmap_t pmap, pte_t ** pdir, unsigned int pdir_idx)
892 {
893 	vm_paddr_t	pa;
894 	pte_t          *ptbl;
895 	vm_page_t	m;
896 	int		i;
897 
898 	KASSERT((pmap != kernel_pmap),
899 		("ptbl_hold: holding kernel ptbl!"));
900 
901 	ptbl = pdir[pdir_idx];
902 
903 	KASSERT((ptbl != NULL), ("ptbl_hold: null ptbl"));
904 
905 	for (i = 0; i < PTBL_PAGES; i++) {
906 		pa = pte_vatopa(mmu, kernel_pmap,
907 				(vm_offset_t) ptbl + (i * PAGE_SIZE));
908 		m = PHYS_TO_VM_PAGE(pa);
909 		m->wire_count++;
910 	}
911 }
912 #else
913 
914 /* Initialize pool of kva ptbl buffers. */
915 static void
916 ptbl_init(void)
917 {
918 	int i;
919 
920 	CTR3(KTR_PMAP, "%s: s (ptbl_bufs = 0x%08x size 0x%08x)", __func__,
921 	    (uint32_t)ptbl_bufs, sizeof(struct ptbl_buf) * PTBL_BUFS);
922 	CTR3(KTR_PMAP, "%s: s (ptbl_buf_pool_vabase = 0x%08x size = 0x%08x)",
923 	    __func__, ptbl_buf_pool_vabase, PTBL_BUFS * PTBL_PAGES * PAGE_SIZE);
924 
925 	mtx_init(&ptbl_buf_freelist_lock, "ptbl bufs lock", NULL, MTX_DEF);
926 	TAILQ_INIT(&ptbl_buf_freelist);
927 
928 	for (i = 0; i < PTBL_BUFS; i++) {
929 		ptbl_bufs[i].kva =
930 		    ptbl_buf_pool_vabase + i * PTBL_PAGES * PAGE_SIZE;
931 		TAILQ_INSERT_TAIL(&ptbl_buf_freelist, &ptbl_bufs[i], link);
932 	}
933 }
934 
935 /* Get a ptbl_buf from the freelist. */
936 static struct ptbl_buf *
937 ptbl_buf_alloc(void)
938 {
939 	struct ptbl_buf *buf;
940 
941 	mtx_lock(&ptbl_buf_freelist_lock);
942 	buf = TAILQ_FIRST(&ptbl_buf_freelist);
943 	if (buf != NULL)
944 		TAILQ_REMOVE(&ptbl_buf_freelist, buf, link);
945 	mtx_unlock(&ptbl_buf_freelist_lock);
946 
947 	CTR2(KTR_PMAP, "%s: buf = %p", __func__, buf);
948 
949 	return (buf);
950 }
951 
952 /* Return ptbl buff to free pool. */
953 static void
954 ptbl_buf_free(struct ptbl_buf *buf)
955 {
956 
957 	CTR2(KTR_PMAP, "%s: buf = %p", __func__, buf);
958 
959 	mtx_lock(&ptbl_buf_freelist_lock);
960 	TAILQ_INSERT_TAIL(&ptbl_buf_freelist, buf, link);
961 	mtx_unlock(&ptbl_buf_freelist_lock);
962 }
963 
964 /*
965  * Search the list of allocated ptbl bufs and find on list of allocated ptbls
966  */
967 static void
968 ptbl_free_pmap_ptbl(pmap_t pmap, pte_t *ptbl)
969 {
970 	struct ptbl_buf *pbuf;
971 
972 	CTR2(KTR_PMAP, "%s: ptbl = %p", __func__, ptbl);
973 
974 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
975 
976 	TAILQ_FOREACH(pbuf, &pmap->pm_ptbl_list, link)
977 		if (pbuf->kva == (vm_offset_t)ptbl) {
978 			/* Remove from pmap ptbl buf list. */
979 			TAILQ_REMOVE(&pmap->pm_ptbl_list, pbuf, link);
980 
981 			/* Free corresponding ptbl buf. */
982 			ptbl_buf_free(pbuf);
983 			break;
984 		}
985 }
986 
987 /* Allocate page table. */
988 static pte_t *
989 ptbl_alloc(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx, boolean_t nosleep)
990 {
991 	vm_page_t mtbl[PTBL_PAGES];
992 	vm_page_t m;
993 	struct ptbl_buf *pbuf;
994 	unsigned int pidx;
995 	pte_t *ptbl;
996 	int i, j;
997 
998 	CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
999 	    (pmap == kernel_pmap), pdir_idx);
1000 
1001 	KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
1002 	    ("ptbl_alloc: invalid pdir_idx"));
1003 	KASSERT((pmap->pm_pdir[pdir_idx] == NULL),
1004 	    ("pte_alloc: valid ptbl entry exists!"));
1005 
1006 	pbuf = ptbl_buf_alloc();
1007 	if (pbuf == NULL)
1008 		panic("pte_alloc: couldn't alloc kernel virtual memory");
1009 
1010 	ptbl = (pte_t *)pbuf->kva;
1011 
1012 	CTR2(KTR_PMAP, "%s: ptbl kva = %p", __func__, ptbl);
1013 
1014 	for (i = 0; i < PTBL_PAGES; i++) {
1015 		pidx = (PTBL_PAGES * pdir_idx) + i;
1016 		while ((m = vm_page_alloc(NULL, pidx,
1017 		    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
1018 			PMAP_UNLOCK(pmap);
1019 			rw_wunlock(&pvh_global_lock);
1020 			if (nosleep) {
1021 				ptbl_free_pmap_ptbl(pmap, ptbl);
1022 				for (j = 0; j < i; j++)
1023 					vm_page_free(mtbl[j]);
1024 				atomic_subtract_int(&vm_cnt.v_wire_count, i);
1025 				return (NULL);
1026 			}
1027 			VM_WAIT;
1028 			rw_wlock(&pvh_global_lock);
1029 			PMAP_LOCK(pmap);
1030 		}
1031 		mtbl[i] = m;
1032 	}
1033 
1034 	/* Map allocated pages into kernel_pmap. */
1035 	mmu_booke_qenter(mmu, (vm_offset_t)ptbl, mtbl, PTBL_PAGES);
1036 
1037 	/* Zero whole ptbl. */
1038 	bzero((caddr_t)ptbl, PTBL_PAGES * PAGE_SIZE);
1039 
1040 	/* Add pbuf to the pmap ptbl bufs list. */
1041 	TAILQ_INSERT_TAIL(&pmap->pm_ptbl_list, pbuf, link);
1042 
1043 	return (ptbl);
1044 }
1045 
1046 /* Free ptbl pages and invalidate pdir entry. */
1047 static void
1048 ptbl_free(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
1049 {
1050 	pte_t *ptbl;
1051 	vm_paddr_t pa;
1052 	vm_offset_t va;
1053 	vm_page_t m;
1054 	int i;
1055 
1056 	CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
1057 	    (pmap == kernel_pmap), pdir_idx);
1058 
1059 	KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
1060 	    ("ptbl_free: invalid pdir_idx"));
1061 
1062 	ptbl = pmap->pm_pdir[pdir_idx];
1063 
1064 	CTR2(KTR_PMAP, "%s: ptbl = %p", __func__, ptbl);
1065 
1066 	KASSERT((ptbl != NULL), ("ptbl_free: null ptbl"));
1067 
1068 	/*
1069 	 * Invalidate the pdir entry as soon as possible, so that other CPUs
1070 	 * don't attempt to look up the page tables we are releasing.
1071 	 */
1072 	mtx_lock_spin(&tlbivax_mutex);
1073 	tlb_miss_lock();
1074 
1075 	pmap->pm_pdir[pdir_idx] = NULL;
1076 
1077 	tlb_miss_unlock();
1078 	mtx_unlock_spin(&tlbivax_mutex);
1079 
1080 	for (i = 0; i < PTBL_PAGES; i++) {
1081 		va = ((vm_offset_t)ptbl + (i * PAGE_SIZE));
1082 		pa = pte_vatopa(mmu, kernel_pmap, va);
1083 		m = PHYS_TO_VM_PAGE(pa);
1084 		vm_page_free_zero(m);
1085 		atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1086 		mmu_booke_kremove(mmu, va);
1087 	}
1088 
1089 	ptbl_free_pmap_ptbl(pmap, ptbl);
1090 }
1091 
1092 /*
1093  * Decrement ptbl pages hold count and attempt to free ptbl pages.
1094  * Called when removing pte entry from ptbl.
1095  *
1096  * Return 1 if ptbl pages were freed.
1097  */
1098 static int
1099 ptbl_unhold(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
1100 {
1101 	pte_t *ptbl;
1102 	vm_paddr_t pa;
1103 	vm_page_t m;
1104 	int i;
1105 
1106 	CTR4(KTR_PMAP, "%s: pmap = %p su = %d pdir_idx = %d", __func__, pmap,
1107 	    (pmap == kernel_pmap), pdir_idx);
1108 
1109 	KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
1110 	    ("ptbl_unhold: invalid pdir_idx"));
1111 	KASSERT((pmap != kernel_pmap),
1112 	    ("ptbl_unhold: unholding kernel ptbl!"));
1113 
1114 	ptbl = pmap->pm_pdir[pdir_idx];
1115 
1116 	//debugf("ptbl_unhold: ptbl = 0x%08x\n", (u_int32_t)ptbl);
1117 	KASSERT(((vm_offset_t)ptbl >= VM_MIN_KERNEL_ADDRESS),
1118 	    ("ptbl_unhold: non kva ptbl"));
1119 
1120 	/* decrement hold count */
1121 	for (i = 0; i < PTBL_PAGES; i++) {
1122 		pa = pte_vatopa(mmu, kernel_pmap,
1123 		    (vm_offset_t)ptbl + (i * PAGE_SIZE));
1124 		m = PHYS_TO_VM_PAGE(pa);
1125 		m->wire_count--;
1126 	}
1127 
1128 	/*
1129 	 * Free ptbl pages if there are no pte etries in this ptbl.
1130 	 * wire_count has the same value for all ptbl pages, so check the last
1131 	 * page.
1132 	 */
1133 	if (m->wire_count == 0) {
1134 		ptbl_free(mmu, pmap, pdir_idx);
1135 
1136 		//debugf("ptbl_unhold: e (freed ptbl)\n");
1137 		return (1);
1138 	}
1139 
1140 	return (0);
1141 }
1142 
1143 /*
1144  * Increment hold count for ptbl pages. This routine is used when a new pte
1145  * entry is being inserted into the ptbl.
1146  */
1147 static void
1148 ptbl_hold(mmu_t mmu, pmap_t pmap, unsigned int pdir_idx)
1149 {
1150 	vm_paddr_t pa;
1151 	pte_t *ptbl;
1152 	vm_page_t m;
1153 	int i;
1154 
1155 	CTR3(KTR_PMAP, "%s: pmap = %p pdir_idx = %d", __func__, pmap,
1156 	    pdir_idx);
1157 
1158 	KASSERT((pdir_idx <= (VM_MAXUSER_ADDRESS / PDIR_SIZE)),
1159 	    ("ptbl_hold: invalid pdir_idx"));
1160 	KASSERT((pmap != kernel_pmap),
1161 	    ("ptbl_hold: holding kernel ptbl!"));
1162 
1163 	ptbl = pmap->pm_pdir[pdir_idx];
1164 
1165 	KASSERT((ptbl != NULL), ("ptbl_hold: null ptbl"));
1166 
1167 	for (i = 0; i < PTBL_PAGES; i++) {
1168 		pa = pte_vatopa(mmu, kernel_pmap,
1169 		    (vm_offset_t)ptbl + (i * PAGE_SIZE));
1170 		m = PHYS_TO_VM_PAGE(pa);
1171 		m->wire_count++;
1172 	}
1173 }
1174 #endif
1175 
1176 /* Allocate pv_entry structure. */
1177 pv_entry_t
1178 pv_alloc(void)
1179 {
1180 	pv_entry_t pv;
1181 
1182 	pv_entry_count++;
1183 	if (pv_entry_count > pv_entry_high_water)
1184 		pagedaemon_wakeup();
1185 	pv = uma_zalloc(pvzone, M_NOWAIT);
1186 
1187 	return (pv);
1188 }
1189 
1190 /* Free pv_entry structure. */
1191 static __inline void
1192 pv_free(pv_entry_t pve)
1193 {
1194 
1195 	pv_entry_count--;
1196 	uma_zfree(pvzone, pve);
1197 }
1198 
1199 
1200 /* Allocate and initialize pv_entry structure. */
1201 static void
1202 pv_insert(pmap_t pmap, vm_offset_t va, vm_page_t m)
1203 {
1204 	pv_entry_t pve;
1205 
1206 	//int su = (pmap == kernel_pmap);
1207 	//debugf("pv_insert: s (su = %d pmap = 0x%08x va = 0x%08x m = 0x%08x)\n", su,
1208 	//	(u_int32_t)pmap, va, (u_int32_t)m);
1209 
1210 	pve = pv_alloc();
1211 	if (pve == NULL)
1212 		panic("pv_insert: no pv entries!");
1213 
1214 	pve->pv_pmap = pmap;
1215 	pve->pv_va = va;
1216 
1217 	/* add to pv_list */
1218 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1219 	rw_assert(&pvh_global_lock, RA_WLOCKED);
1220 
1221 	TAILQ_INSERT_TAIL(&m->md.pv_list, pve, pv_link);
1222 
1223 	//debugf("pv_insert: e\n");
1224 }
1225 
1226 /* Destroy pv entry. */
1227 static void
1228 pv_remove(pmap_t pmap, vm_offset_t va, vm_page_t m)
1229 {
1230 	pv_entry_t pve;
1231 
1232 	//int su = (pmap == kernel_pmap);
1233 	//debugf("pv_remove: s (su = %d pmap = 0x%08x va = 0x%08x)\n", su, (u_int32_t)pmap, va);
1234 
1235 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1236 	rw_assert(&pvh_global_lock, RA_WLOCKED);
1237 
1238 	/* find pv entry */
1239 	TAILQ_FOREACH(pve, &m->md.pv_list, pv_link) {
1240 		if ((pmap == pve->pv_pmap) && (va == pve->pv_va)) {
1241 			/* remove from pv_list */
1242 			TAILQ_REMOVE(&m->md.pv_list, pve, pv_link);
1243 			if (TAILQ_EMPTY(&m->md.pv_list))
1244 				vm_page_aflag_clear(m, PGA_WRITEABLE);
1245 
1246 			/* free pv entry struct */
1247 			pv_free(pve);
1248 			break;
1249 		}
1250 	}
1251 
1252 	//debugf("pv_remove: e\n");
1253 }
1254 
1255 #ifdef __powerpc64__
1256 /*
1257  * Clean pte entry, try to free page table page if requested.
1258  *
1259  * Return 1 if ptbl pages were freed, otherwise return 0.
1260  */
1261 static int
1262 pte_remove(mmu_t mmu, pmap_t pmap, vm_offset_t va, u_int8_t flags)
1263 {
1264 	vm_page_t	m;
1265 	pte_t          *pte;
1266 
1267 	pte = pte_find(mmu, pmap, va);
1268 	KASSERT(pte != NULL, ("%s: NULL pte", __func__));
1269 
1270 	if (!PTE_ISVALID(pte))
1271 		return (0);
1272 
1273 	/* Get vm_page_t for mapped pte. */
1274 	m = PHYS_TO_VM_PAGE(PTE_PA(pte));
1275 
1276 	if (PTE_ISWIRED(pte))
1277 		pmap->pm_stats.wired_count--;
1278 
1279 	/* Handle managed entry. */
1280 	if (PTE_ISMANAGED(pte)) {
1281 
1282 		/* Handle modified pages. */
1283 		if (PTE_ISMODIFIED(pte))
1284 			vm_page_dirty(m);
1285 
1286 		/* Referenced pages. */
1287 		if (PTE_ISREFERENCED(pte))
1288 			vm_page_aflag_set(m, PGA_REFERENCED);
1289 
1290 		/* Remove pv_entry from pv_list. */
1291 		pv_remove(pmap, va, m);
1292 	}
1293 	mtx_lock_spin(&tlbivax_mutex);
1294 	tlb_miss_lock();
1295 
1296 	tlb0_flush_entry(va);
1297 	*pte = 0;
1298 
1299 	tlb_miss_unlock();
1300 	mtx_unlock_spin(&tlbivax_mutex);
1301 
1302 	pmap->pm_stats.resident_count--;
1303 
1304 	if (flags & PTBL_UNHOLD) {
1305 		return (ptbl_unhold(mmu, pmap, va));
1306 	}
1307 	return (0);
1308 }
1309 
1310 /*
1311  * allocate a page of pointers to page directories, do not preallocate the
1312  * page tables
1313  */
1314 static pte_t  **
1315 pdir_alloc(mmu_t mmu, pmap_t pmap, unsigned int pp2d_idx, bool nosleep)
1316 {
1317 	vm_page_t	mtbl  [PDIR_PAGES];
1318 	vm_page_t	m;
1319 	struct ptbl_buf *pbuf;
1320 	pte_t         **pdir;
1321 	unsigned int	pidx;
1322 	int		i;
1323 	int		req;
1324 
1325 	pbuf = ptbl_buf_alloc();
1326 
1327 	if (pbuf == NULL)
1328 		panic("%s: couldn't alloc kernel virtual memory", __func__);
1329 
1330 	/* Allocate pdir pages, this will sleep! */
1331 	for (i = 0; i < PDIR_PAGES; i++) {
1332 		pidx = (PDIR_PAGES * pp2d_idx) + i;
1333 		req = VM_ALLOC_NOOBJ | VM_ALLOC_WIRED;
1334 		while ((m = vm_page_alloc(NULL, pidx, req)) == NULL) {
1335 			PMAP_UNLOCK(pmap);
1336 			VM_WAIT;
1337 			PMAP_LOCK(pmap);
1338 		}
1339 		mtbl[i] = m;
1340 	}
1341 
1342 	/* Mapin allocated pages into kernel_pmap. */
1343 	pdir = (pte_t **) pbuf->kva;
1344 	pmap_qenter((vm_offset_t) pdir, mtbl, PDIR_PAGES);
1345 
1346 	/* Zero whole pdir. */
1347 	bzero((caddr_t) pdir, PDIR_PAGES * PAGE_SIZE);
1348 
1349 	/* Add pdir to the pmap pdir bufs list. */
1350 	TAILQ_INSERT_TAIL(&pmap->pm_pdir_list, pbuf, link);
1351 
1352 	return pdir;
1353 }
1354 
1355 /*
1356  * Insert PTE for a given page and virtual address.
1357  */
1358 static int
1359 pte_enter(mmu_t mmu, pmap_t pmap, vm_page_t m, vm_offset_t va, uint32_t flags,
1360     boolean_t nosleep)
1361 {
1362 	unsigned int	pp2d_idx = PP2D_IDX(va);
1363 	unsigned int	pdir_idx = PDIR_IDX(va);
1364 	unsigned int	ptbl_idx = PTBL_IDX(va);
1365 	pte_t          *ptbl, *pte;
1366 	pte_t         **pdir;
1367 
1368 	/* Get the page directory pointer. */
1369 	pdir = pmap->pm_pp2d[pp2d_idx];
1370 	if (pdir == NULL)
1371 		pdir = pdir_alloc(mmu, pmap, pp2d_idx, nosleep);
1372 
1373 	/* Get the page table pointer. */
1374 	ptbl = pdir[pdir_idx];
1375 
1376 	if (ptbl == NULL) {
1377 		/* Allocate page table pages. */
1378 		ptbl = ptbl_alloc(mmu, pmap, pdir, pdir_idx, nosleep);
1379 		if (ptbl == NULL) {
1380 			KASSERT(nosleep, ("nosleep and NULL ptbl"));
1381 			return (ENOMEM);
1382 		}
1383 	} else {
1384 		/*
1385 		 * Check if there is valid mapping for requested va, if there
1386 		 * is, remove it.
1387 		 */
1388 		pte = &pdir[pdir_idx][ptbl_idx];
1389 		if (PTE_ISVALID(pte)) {
1390 			pte_remove(mmu, pmap, va, PTBL_HOLD);
1391 		} else {
1392 			/*
1393 			 * pte is not used, increment hold count for ptbl
1394 			 * pages.
1395 			 */
1396 			if (pmap != kernel_pmap)
1397 				ptbl_hold(mmu, pmap, pdir, pdir_idx);
1398 		}
1399 	}
1400 
1401 	if (pdir[pdir_idx] == NULL) {
1402 		if (pmap != kernel_pmap && pmap->pm_pp2d[pp2d_idx] != NULL)
1403 			pdir_hold(mmu, pmap, pdir);
1404 		pdir[pdir_idx] = ptbl;
1405 	}
1406 	if (pmap->pm_pp2d[pp2d_idx] == NULL)
1407 		pmap->pm_pp2d[pp2d_idx] = pdir;
1408 
1409 	/*
1410 	 * Insert pv_entry into pv_list for mapped page if part of managed
1411 	 * memory.
1412 	 */
1413 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1414 		flags |= PTE_MANAGED;
1415 
1416 		/* Create and insert pv entry. */
1417 		pv_insert(pmap, va, m);
1418 	}
1419 
1420 	mtx_lock_spin(&tlbivax_mutex);
1421 	tlb_miss_lock();
1422 
1423 	tlb0_flush_entry(va);
1424 	pmap->pm_stats.resident_count++;
1425 	pte = &pdir[pdir_idx][ptbl_idx];
1426 	*pte = PTE_RPN_FROM_PA(VM_PAGE_TO_PHYS(m));
1427 	*pte |= (PTE_VALID | flags);
1428 
1429 	tlb_miss_unlock();
1430 	mtx_unlock_spin(&tlbivax_mutex);
1431 
1432 	return (0);
1433 }
1434 
1435 /* Return the pa for the given pmap/va. */
1436 static	vm_paddr_t
1437 pte_vatopa(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1438 {
1439 	vm_paddr_t	pa = 0;
1440 	pte_t          *pte;
1441 
1442 	pte = pte_find(mmu, pmap, va);
1443 	if ((pte != NULL) && PTE_ISVALID(pte))
1444 		pa = (PTE_PA(pte) | (va & PTE_PA_MASK));
1445 	return (pa);
1446 }
1447 
1448 
1449 /* allocate pte entries to manage (addr & mask) to (addr & mask) + size */
1450 static void
1451 kernel_pte_alloc(vm_offset_t data_end, vm_offset_t addr, vm_offset_t pdir)
1452 {
1453 	int		i, j;
1454 	vm_offset_t	va;
1455 	pte_t		*pte;
1456 
1457 	va = addr;
1458 	/* Initialize kernel pdir */
1459 	for (i = 0; i < kernel_pdirs; i++) {
1460 		kernel_pmap->pm_pp2d[i + PP2D_IDX(va)] =
1461 		    (pte_t **)(pdir + (i * PAGE_SIZE * PDIR_PAGES));
1462 		for (j = PDIR_IDX(va + (i * PAGE_SIZE * PDIR_NENTRIES * PTBL_NENTRIES));
1463 		    j < PDIR_NENTRIES; j++) {
1464 			kernel_pmap->pm_pp2d[i + PP2D_IDX(va)][j] =
1465 			    (pte_t *)(pdir + (kernel_pdirs * PAGE_SIZE * PDIR_PAGES) +
1466 			     (((i * PDIR_NENTRIES) + j) * PAGE_SIZE * PTBL_PAGES));
1467 		}
1468 	}
1469 
1470 	/*
1471 	 * Fill in PTEs covering kernel code and data. They are not required
1472 	 * for address translation, as this area is covered by static TLB1
1473 	 * entries, but for pte_vatopa() to work correctly with kernel area
1474 	 * addresses.
1475 	 */
1476 	for (va = addr; va < data_end; va += PAGE_SIZE) {
1477 		pte = &(kernel_pmap->pm_pp2d[PP2D_IDX(va)][PDIR_IDX(va)][PTBL_IDX(va)]);
1478 		*pte = PTE_RPN_FROM_PA(kernload + (va - kernstart));
1479 		*pte |= PTE_M | PTE_SR | PTE_SW | PTE_SX | PTE_WIRED |
1480 		    PTE_VALID | PTE_PS_4KB;
1481 	}
1482 }
1483 #else
1484 /*
1485  * Clean pte entry, try to free page table page if requested.
1486  *
1487  * Return 1 if ptbl pages were freed, otherwise return 0.
1488  */
1489 static int
1490 pte_remove(mmu_t mmu, pmap_t pmap, vm_offset_t va, uint8_t flags)
1491 {
1492 	unsigned int pdir_idx = PDIR_IDX(va);
1493 	unsigned int ptbl_idx = PTBL_IDX(va);
1494 	vm_page_t m;
1495 	pte_t *ptbl;
1496 	pte_t *pte;
1497 
1498 	//int su = (pmap == kernel_pmap);
1499 	//debugf("pte_remove: s (su = %d pmap = 0x%08x va = 0x%08x flags = %d)\n",
1500 	//		su, (u_int32_t)pmap, va, flags);
1501 
1502 	ptbl = pmap->pm_pdir[pdir_idx];
1503 	KASSERT(ptbl, ("pte_remove: null ptbl"));
1504 
1505 	pte = &ptbl[ptbl_idx];
1506 
1507 	if (pte == NULL || !PTE_ISVALID(pte))
1508 		return (0);
1509 
1510 	if (PTE_ISWIRED(pte))
1511 		pmap->pm_stats.wired_count--;
1512 
1513 	/* Get vm_page_t for mapped pte. */
1514 	m = PHYS_TO_VM_PAGE(PTE_PA(pte));
1515 
1516 	/* Handle managed entry. */
1517 	if (PTE_ISMANAGED(pte)) {
1518 
1519 		if (PTE_ISMODIFIED(pte))
1520 			vm_page_dirty(m);
1521 
1522 		if (PTE_ISREFERENCED(pte))
1523 			vm_page_aflag_set(m, PGA_REFERENCED);
1524 
1525 		pv_remove(pmap, va, m);
1526 	} else if (m->md.pv_tracked) {
1527 		/*
1528 		 * Always pv_insert()/pv_remove() on MPC85XX, in case DPAA is
1529 		 * used.  This is needed by the NCSW support code for fast
1530 		 * VA<->PA translation.
1531 		 */
1532 		pv_remove(pmap, va, m);
1533 		if (TAILQ_EMPTY(&m->md.pv_list))
1534 			m->md.pv_tracked = false;
1535 	}
1536 
1537 	mtx_lock_spin(&tlbivax_mutex);
1538 	tlb_miss_lock();
1539 
1540 	tlb0_flush_entry(va);
1541 	*pte = 0;
1542 
1543 	tlb_miss_unlock();
1544 	mtx_unlock_spin(&tlbivax_mutex);
1545 
1546 	pmap->pm_stats.resident_count--;
1547 
1548 	if (flags & PTBL_UNHOLD) {
1549 		//debugf("pte_remove: e (unhold)\n");
1550 		return (ptbl_unhold(mmu, pmap, pdir_idx));
1551 	}
1552 
1553 	//debugf("pte_remove: e\n");
1554 	return (0);
1555 }
1556 
1557 /*
1558  * Insert PTE for a given page and virtual address.
1559  */
1560 static int
1561 pte_enter(mmu_t mmu, pmap_t pmap, vm_page_t m, vm_offset_t va, uint32_t flags,
1562     boolean_t nosleep)
1563 {
1564 	unsigned int pdir_idx = PDIR_IDX(va);
1565 	unsigned int ptbl_idx = PTBL_IDX(va);
1566 	pte_t *ptbl, *pte;
1567 
1568 	CTR4(KTR_PMAP, "%s: su = %d pmap = %p va = %p", __func__,
1569 	    pmap == kernel_pmap, pmap, va);
1570 
1571 	/* Get the page table pointer. */
1572 	ptbl = pmap->pm_pdir[pdir_idx];
1573 
1574 	if (ptbl == NULL) {
1575 		/* Allocate page table pages. */
1576 		ptbl = ptbl_alloc(mmu, pmap, pdir_idx, nosleep);
1577 		if (ptbl == NULL) {
1578 			KASSERT(nosleep, ("nosleep and NULL ptbl"));
1579 			return (ENOMEM);
1580 		}
1581 	} else {
1582 		/*
1583 		 * Check if there is valid mapping for requested
1584 		 * va, if there is, remove it.
1585 		 */
1586 		pte = &pmap->pm_pdir[pdir_idx][ptbl_idx];
1587 		if (PTE_ISVALID(pte)) {
1588 			pte_remove(mmu, pmap, va, PTBL_HOLD);
1589 		} else {
1590 			/*
1591 			 * pte is not used, increment hold count
1592 			 * for ptbl pages.
1593 			 */
1594 			if (pmap != kernel_pmap)
1595 				ptbl_hold(mmu, pmap, pdir_idx);
1596 		}
1597 	}
1598 
1599 	/*
1600 	 * Insert pv_entry into pv_list for mapped page if part of managed
1601 	 * memory.
1602 	 */
1603 	if ((m->oflags & VPO_UNMANAGED) == 0) {
1604 		flags |= PTE_MANAGED;
1605 
1606 		/* Create and insert pv entry. */
1607 		pv_insert(pmap, va, m);
1608 	}
1609 
1610 	pmap->pm_stats.resident_count++;
1611 
1612 	mtx_lock_spin(&tlbivax_mutex);
1613 	tlb_miss_lock();
1614 
1615 	tlb0_flush_entry(va);
1616 	if (pmap->pm_pdir[pdir_idx] == NULL) {
1617 		/*
1618 		 * If we just allocated a new page table, hook it in
1619 		 * the pdir.
1620 		 */
1621 		pmap->pm_pdir[pdir_idx] = ptbl;
1622 	}
1623 	pte = &(pmap->pm_pdir[pdir_idx][ptbl_idx]);
1624 	*pte = PTE_RPN_FROM_PA(VM_PAGE_TO_PHYS(m));
1625 	*pte |= (PTE_VALID | flags | PTE_PS_4KB); /* 4KB pages only */
1626 
1627 	tlb_miss_unlock();
1628 	mtx_unlock_spin(&tlbivax_mutex);
1629 	return (0);
1630 }
1631 
1632 /* Return the pa for the given pmap/va. */
1633 static vm_paddr_t
1634 pte_vatopa(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1635 {
1636 	vm_paddr_t pa = 0;
1637 	pte_t *pte;
1638 
1639 	pte = pte_find(mmu, pmap, va);
1640 	if ((pte != NULL) && PTE_ISVALID(pte))
1641 		pa = (PTE_PA(pte) | (va & PTE_PA_MASK));
1642 	return (pa);
1643 }
1644 
1645 /* Get a pointer to a PTE in a page table. */
1646 static pte_t *
1647 pte_find(mmu_t mmu, pmap_t pmap, vm_offset_t va)
1648 {
1649 	unsigned int pdir_idx = PDIR_IDX(va);
1650 	unsigned int ptbl_idx = PTBL_IDX(va);
1651 
1652 	KASSERT((pmap != NULL), ("pte_find: invalid pmap"));
1653 
1654 	if (pmap->pm_pdir[pdir_idx])
1655 		return (&(pmap->pm_pdir[pdir_idx][ptbl_idx]));
1656 
1657 	return (NULL);
1658 }
1659 
1660 /* Set up kernel page tables. */
1661 static void
1662 kernel_pte_alloc(vm_offset_t data_end, vm_offset_t addr, vm_offset_t pdir)
1663 {
1664 	int		i;
1665 	vm_offset_t	va;
1666 	pte_t		*pte;
1667 
1668 	/* Initialize kernel pdir */
1669 	for (i = 0; i < kernel_ptbls; i++)
1670 		kernel_pmap->pm_pdir[kptbl_min + i] =
1671 		    (pte_t *)(pdir + (i * PAGE_SIZE * PTBL_PAGES));
1672 
1673 	/*
1674 	 * Fill in PTEs covering kernel code and data. They are not required
1675 	 * for address translation, as this area is covered by static TLB1
1676 	 * entries, but for pte_vatopa() to work correctly with kernel area
1677 	 * addresses.
1678 	 */
1679 	for (va = addr; va < data_end; va += PAGE_SIZE) {
1680 		pte = &(kernel_pmap->pm_pdir[PDIR_IDX(va)][PTBL_IDX(va)]);
1681 		*pte = PTE_RPN_FROM_PA(kernload + (va - kernstart));
1682 		*pte |= PTE_M | PTE_SR | PTE_SW | PTE_SX | PTE_WIRED |
1683 		    PTE_VALID | PTE_PS_4KB;
1684 	}
1685 }
1686 #endif
1687 
1688 /**************************************************************************/
1689 /* PMAP related */
1690 /**************************************************************************/
1691 
1692 /*
1693  * This is called during booke_init, before the system is really initialized.
1694  */
1695 static void
1696 mmu_booke_bootstrap(mmu_t mmu, vm_offset_t start, vm_offset_t kernelend)
1697 {
1698 	vm_paddr_t phys_kernelend;
1699 	struct mem_region *mp, *mp1;
1700 	int cnt, i, j;
1701 	vm_paddr_t s, e, sz;
1702 	vm_paddr_t physsz, hwphyssz;
1703 	u_int phys_avail_count;
1704 	vm_size_t kstack0_sz;
1705 	vm_offset_t kernel_pdir, kstack0;
1706 	vm_paddr_t kstack0_phys;
1707 	void *dpcpu;
1708 
1709 	debugf("mmu_booke_bootstrap: entered\n");
1710 
1711 	/* Set interesting system properties */
1712 	hw_direct_map = 0;
1713 #if defined(COMPAT_FREEBSD32) || !defined(__powerpc64__)
1714 	elf32_nxstack = 1;
1715 #endif
1716 
1717 	/* Initialize invalidation mutex */
1718 	mtx_init(&tlbivax_mutex, "tlbivax", NULL, MTX_SPIN);
1719 
1720 	/* Read TLB0 size and associativity. */
1721 	tlb0_get_tlbconf();
1722 
1723 	/*
1724 	 * Align kernel start and end address (kernel image).
1725 	 * Note that kernel end does not necessarily relate to kernsize.
1726 	 * kernsize is the size of the kernel that is actually mapped.
1727 	 */
1728 	kernstart = trunc_page(start);
1729 	data_start = round_page(kernelend);
1730 	data_end = data_start;
1731 
1732 	/*
1733 	 * Addresses of preloaded modules (like file systems) use
1734 	 * physical addresses. Make sure we relocate those into
1735 	 * virtual addresses.
1736 	 */
1737 	preload_addr_relocate = kernstart - kernload;
1738 
1739 	/* Allocate the dynamic per-cpu area. */
1740 	dpcpu = (void *)data_end;
1741 	data_end += DPCPU_SIZE;
1742 
1743 	/* Allocate space for the message buffer. */
1744 	msgbufp = (struct msgbuf *)data_end;
1745 	data_end += msgbufsize;
1746 	debugf(" msgbufp at 0x%"PRI0ptrX" end = 0x%"PRI0ptrX"\n",
1747 	    (uintptr_t)msgbufp, data_end);
1748 
1749 	data_end = round_page(data_end);
1750 
1751 	/* Allocate space for ptbl_bufs. */
1752 	ptbl_bufs = (struct ptbl_buf *)data_end;
1753 	data_end += sizeof(struct ptbl_buf) * PTBL_BUFS;
1754 	debugf(" ptbl_bufs at 0x%"PRI0ptrX" end = 0x%"PRI0ptrX"\n",
1755 	    (uintptr_t)ptbl_bufs, data_end);
1756 
1757 	data_end = round_page(data_end);
1758 
1759 	/* Allocate PTE tables for kernel KVA. */
1760 	kernel_pdir = data_end;
1761 	kernel_ptbls = howmany(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS,
1762 	    PDIR_SIZE);
1763 #ifdef __powerpc64__
1764 	kernel_pdirs = howmany(kernel_ptbls, PDIR_NENTRIES);
1765 	data_end += kernel_pdirs * PDIR_PAGES * PAGE_SIZE;
1766 #endif
1767 	data_end += kernel_ptbls * PTBL_PAGES * PAGE_SIZE;
1768 	debugf(" kernel ptbls: %d\n", kernel_ptbls);
1769 	debugf(" kernel pdir at 0x%"PRI0ptrX" end = 0x%"PRI0ptrX"\n",
1770 	    kernel_pdir, data_end);
1771 
1772 	debugf(" data_end: 0x%"PRI0ptrX"\n", data_end);
1773 	if (data_end - kernstart > kernsize) {
1774 		kernsize += tlb1_mapin_region(kernstart + kernsize,
1775 		    kernload + kernsize, (data_end - kernstart) - kernsize);
1776 	}
1777 	data_end = kernstart + kernsize;
1778 	debugf(" updated data_end: 0x%"PRI0ptrX"\n", data_end);
1779 
1780 	/*
1781 	 * Clear the structures - note we can only do it safely after the
1782 	 * possible additional TLB1 translations are in place (above) so that
1783 	 * all range up to the currently calculated 'data_end' is covered.
1784 	 */
1785 	dpcpu_init(dpcpu, 0);
1786 	memset((void *)ptbl_bufs, 0, sizeof(struct ptbl_buf) * PTBL_SIZE);
1787 #ifdef __powerpc64__
1788 	memset((void *)kernel_pdir, 0,
1789 	    kernel_pdirs * PDIR_PAGES * PAGE_SIZE +
1790 	    kernel_ptbls * PTBL_PAGES * PAGE_SIZE);
1791 #else
1792 	memset((void *)kernel_pdir, 0, kernel_ptbls * PTBL_PAGES * PAGE_SIZE);
1793 #endif
1794 
1795 	/*******************************************************/
1796 	/* Set the start and end of kva. */
1797 	/*******************************************************/
1798 	virtual_avail = round_page(data_end);
1799 	virtual_end = VM_MAX_KERNEL_ADDRESS;
1800 
1801 	/* Allocate KVA space for page zero/copy operations. */
1802 	zero_page_va = virtual_avail;
1803 	virtual_avail += PAGE_SIZE;
1804 	copy_page_src_va = virtual_avail;
1805 	virtual_avail += PAGE_SIZE;
1806 	copy_page_dst_va = virtual_avail;
1807 	virtual_avail += PAGE_SIZE;
1808 	debugf("zero_page_va = 0x%08x\n", zero_page_va);
1809 	debugf("copy_page_src_va = 0x%08x\n", copy_page_src_va);
1810 	debugf("copy_page_dst_va = 0x%08x\n", copy_page_dst_va);
1811 
1812 	/* Initialize page zero/copy mutexes. */
1813 	mtx_init(&zero_page_mutex, "mmu_booke_zero_page", NULL, MTX_DEF);
1814 	mtx_init(&copy_page_mutex, "mmu_booke_copy_page", NULL, MTX_DEF);
1815 
1816 	/* Allocate KVA space for ptbl bufs. */
1817 	ptbl_buf_pool_vabase = virtual_avail;
1818 	virtual_avail += PTBL_BUFS * PTBL_PAGES * PAGE_SIZE;
1819 	debugf("ptbl_buf_pool_vabase = 0x%08x end = 0x%08x\n",
1820 	    ptbl_buf_pool_vabase, virtual_avail);
1821 
1822 	/* Calculate corresponding physical addresses for the kernel region. */
1823 	phys_kernelend = kernload + kernsize;
1824 	debugf("kernel image and allocated data:\n");
1825 	debugf(" kernload    = 0x%09llx\n", (uint64_t)kernload);
1826 	debugf(" kernstart   = 0x%08x\n", kernstart);
1827 	debugf(" kernsize    = 0x%08x\n", kernsize);
1828 
1829 	if (sizeof(phys_avail) / sizeof(phys_avail[0]) < availmem_regions_sz)
1830 		panic("mmu_booke_bootstrap: phys_avail too small");
1831 
1832 	/*
1833 	 * Remove kernel physical address range from avail regions list. Page
1834 	 * align all regions.  Non-page aligned memory isn't very interesting
1835 	 * to us.  Also, sort the entries for ascending addresses.
1836 	 */
1837 
1838 	/* Retrieve phys/avail mem regions */
1839 	mem_regions(&physmem_regions, &physmem_regions_sz,
1840 	    &availmem_regions, &availmem_regions_sz);
1841 	sz = 0;
1842 	cnt = availmem_regions_sz;
1843 	debugf("processing avail regions:\n");
1844 	for (mp = availmem_regions; mp->mr_size; mp++) {
1845 		s = mp->mr_start;
1846 		e = mp->mr_start + mp->mr_size;
1847 		debugf(" %09jx-%09jx -> ", (uintmax_t)s, (uintmax_t)e);
1848 		/* Check whether this region holds all of the kernel. */
1849 		if (s < kernload && e > phys_kernelend) {
1850 			availmem_regions[cnt].mr_start = phys_kernelend;
1851 			availmem_regions[cnt++].mr_size = e - phys_kernelend;
1852 			e = kernload;
1853 		}
1854 		/* Look whether this regions starts within the kernel. */
1855 		if (s >= kernload && s < phys_kernelend) {
1856 			if (e <= phys_kernelend)
1857 				goto empty;
1858 			s = phys_kernelend;
1859 		}
1860 		/* Now look whether this region ends within the kernel. */
1861 		if (e > kernload && e <= phys_kernelend) {
1862 			if (s >= kernload)
1863 				goto empty;
1864 			e = kernload;
1865 		}
1866 		/* Now page align the start and size of the region. */
1867 		s = round_page(s);
1868 		e = trunc_page(e);
1869 		if (e < s)
1870 			e = s;
1871 		sz = e - s;
1872 		debugf("%09jx-%09jx = %jx\n",
1873 		    (uintmax_t)s, (uintmax_t)e, (uintmax_t)sz);
1874 
1875 		/* Check whether some memory is left here. */
1876 		if (sz == 0) {
1877 		empty:
1878 			memmove(mp, mp + 1,
1879 			    (cnt - (mp - availmem_regions)) * sizeof(*mp));
1880 			cnt--;
1881 			mp--;
1882 			continue;
1883 		}
1884 
1885 		/* Do an insertion sort. */
1886 		for (mp1 = availmem_regions; mp1 < mp; mp1++)
1887 			if (s < mp1->mr_start)
1888 				break;
1889 		if (mp1 < mp) {
1890 			memmove(mp1 + 1, mp1, (char *)mp - (char *)mp1);
1891 			mp1->mr_start = s;
1892 			mp1->mr_size = sz;
1893 		} else {
1894 			mp->mr_start = s;
1895 			mp->mr_size = sz;
1896 		}
1897 	}
1898 	availmem_regions_sz = cnt;
1899 
1900 	/*******************************************************/
1901 	/* Steal physical memory for kernel stack from the end */
1902 	/* of the first avail region                           */
1903 	/*******************************************************/
1904 	kstack0_sz = kstack_pages * PAGE_SIZE;
1905 	kstack0_phys = availmem_regions[0].mr_start +
1906 	    availmem_regions[0].mr_size;
1907 	kstack0_phys -= kstack0_sz;
1908 	availmem_regions[0].mr_size -= kstack0_sz;
1909 
1910 	/*******************************************************/
1911 	/* Fill in phys_avail table, based on availmem_regions */
1912 	/*******************************************************/
1913 	phys_avail_count = 0;
1914 	physsz = 0;
1915 	hwphyssz = 0;
1916 	TUNABLE_ULONG_FETCH("hw.physmem", (u_long *) &hwphyssz);
1917 
1918 	debugf("fill in phys_avail:\n");
1919 	for (i = 0, j = 0; i < availmem_regions_sz; i++, j += 2) {
1920 
1921 		debugf(" region: 0x%jx - 0x%jx (0x%jx)\n",
1922 		    (uintmax_t)availmem_regions[i].mr_start,
1923 		    (uintmax_t)availmem_regions[i].mr_start +
1924 		        availmem_regions[i].mr_size,
1925 		    (uintmax_t)availmem_regions[i].mr_size);
1926 
1927 		if (hwphyssz != 0 &&
1928 		    (physsz + availmem_regions[i].mr_size) >= hwphyssz) {
1929 			debugf(" hw.physmem adjust\n");
1930 			if (physsz < hwphyssz) {
1931 				phys_avail[j] = availmem_regions[i].mr_start;
1932 				phys_avail[j + 1] =
1933 				    availmem_regions[i].mr_start +
1934 				    hwphyssz - physsz;
1935 				physsz = hwphyssz;
1936 				phys_avail_count++;
1937 			}
1938 			break;
1939 		}
1940 
1941 		phys_avail[j] = availmem_regions[i].mr_start;
1942 		phys_avail[j + 1] = availmem_regions[i].mr_start +
1943 		    availmem_regions[i].mr_size;
1944 		phys_avail_count++;
1945 		physsz += availmem_regions[i].mr_size;
1946 	}
1947 	physmem = btoc(physsz);
1948 
1949 	/* Calculate the last available physical address. */
1950 	for (i = 0; phys_avail[i + 2] != 0; i += 2)
1951 		;
1952 	Maxmem = powerpc_btop(phys_avail[i + 1]);
1953 
1954 	debugf("Maxmem = 0x%08lx\n", Maxmem);
1955 	debugf("phys_avail_count = %d\n", phys_avail_count);
1956 	debugf("physsz = 0x%09jx physmem = %jd (0x%09jx)\n",
1957 	    (uintmax_t)physsz, (uintmax_t)physmem, (uintmax_t)physmem);
1958 
1959 	/*******************************************************/
1960 	/* Initialize (statically allocated) kernel pmap. */
1961 	/*******************************************************/
1962 	PMAP_LOCK_INIT(kernel_pmap);
1963 #ifndef __powerpc64__
1964 	kptbl_min = VM_MIN_KERNEL_ADDRESS / PDIR_SIZE;
1965 #endif
1966 
1967 	debugf("kernel_pmap = 0x%"PRI0ptrX"\n", (uintptr_t)kernel_pmap);
1968 	kernel_pte_alloc(virtual_avail, kernstart, kernel_pdir);
1969 	for (i = 0; i < MAXCPU; i++) {
1970 		kernel_pmap->pm_tid[i] = TID_KERNEL;
1971 
1972 		/* Initialize each CPU's tidbusy entry 0 with kernel_pmap */
1973 		tidbusy[i][TID_KERNEL] = kernel_pmap;
1974 	}
1975 
1976 	/* Mark kernel_pmap active on all CPUs */
1977 	CPU_FILL(&kernel_pmap->pm_active);
1978 
1979  	/*
1980 	 * Initialize the global pv list lock.
1981 	 */
1982 	rw_init(&pvh_global_lock, "pmap pv global");
1983 
1984 	/*******************************************************/
1985 	/* Final setup */
1986 	/*******************************************************/
1987 
1988 	/* Enter kstack0 into kernel map, provide guard page */
1989 	kstack0 = virtual_avail + KSTACK_GUARD_PAGES * PAGE_SIZE;
1990 	thread0.td_kstack = kstack0;
1991 	thread0.td_kstack_pages = kstack_pages;
1992 
1993 	debugf("kstack_sz = 0x%08x\n", kstack0_sz);
1994 	debugf("kstack0_phys at 0x%09llx - 0x%09llx\n",
1995 	    kstack0_phys, kstack0_phys + kstack0_sz);
1996 	debugf("kstack0 at 0x%"PRI0ptrX" - 0x%"PRI0ptrX"\n",
1997 	    kstack0, kstack0 + kstack0_sz);
1998 
1999 	virtual_avail += KSTACK_GUARD_PAGES * PAGE_SIZE + kstack0_sz;
2000 	for (i = 0; i < kstack_pages; i++) {
2001 		mmu_booke_kenter(mmu, kstack0, kstack0_phys);
2002 		kstack0 += PAGE_SIZE;
2003 		kstack0_phys += PAGE_SIZE;
2004 	}
2005 
2006 	pmap_bootstrapped = 1;
2007 
2008 	debugf("virtual_avail = %"PRI0ptrX"\n", virtual_avail);
2009 	debugf("virtual_end   = %"PRI0ptrX"\n", virtual_end);
2010 
2011 	debugf("mmu_booke_bootstrap: exit\n");
2012 }
2013 
2014 #ifdef SMP
2015  void
2016 tlb1_ap_prep(void)
2017 {
2018 	tlb_entry_t *e, tmp;
2019 	unsigned int i;
2020 
2021 	/* Prepare TLB1 image for AP processors */
2022 	e = __boot_tlb1;
2023 	for (i = 0; i < TLB1_ENTRIES; i++) {
2024 		tlb1_read_entry(&tmp, i);
2025 
2026 		if ((tmp.mas1 & MAS1_VALID) && (tmp.mas2 & _TLB_ENTRY_SHARED))
2027 			memcpy(e++, &tmp, sizeof(tmp));
2028 	}
2029 }
2030 
2031 void
2032 pmap_bootstrap_ap(volatile uint32_t *trcp __unused)
2033 {
2034 	int i;
2035 
2036 	/*
2037 	 * Finish TLB1 configuration: the BSP already set up its TLB1 and we
2038 	 * have the snapshot of its contents in the s/w __boot_tlb1[] table
2039 	 * created by tlb1_ap_prep(), so use these values directly to
2040 	 * (re)program AP's TLB1 hardware.
2041 	 *
2042 	 * Start at index 1 because index 0 has the kernel map.
2043 	 */
2044 	for (i = 1; i < TLB1_ENTRIES; i++) {
2045 		if (__boot_tlb1[i].mas1 & MAS1_VALID)
2046 			tlb1_write_entry(&__boot_tlb1[i], i);
2047 	}
2048 
2049 	set_mas4_defaults();
2050 }
2051 #endif
2052 
2053 static void
2054 booke_pmap_init_qpages(void)
2055 {
2056 	struct pcpu *pc;
2057 	int i;
2058 
2059 	CPU_FOREACH(i) {
2060 		pc = pcpu_find(i);
2061 		pc->pc_qmap_addr = kva_alloc(PAGE_SIZE);
2062 		if (pc->pc_qmap_addr == 0)
2063 			panic("pmap_init_qpages: unable to allocate KVA");
2064 	}
2065 }
2066 
2067 SYSINIT(qpages_init, SI_SUB_CPU, SI_ORDER_ANY, booke_pmap_init_qpages, NULL);
2068 
2069 /*
2070  * Get the physical page address for the given pmap/virtual address.
2071  */
2072 static vm_paddr_t
2073 mmu_booke_extract(mmu_t mmu, pmap_t pmap, vm_offset_t va)
2074 {
2075 	vm_paddr_t pa;
2076 
2077 	PMAP_LOCK(pmap);
2078 	pa = pte_vatopa(mmu, pmap, va);
2079 	PMAP_UNLOCK(pmap);
2080 
2081 	return (pa);
2082 }
2083 
2084 /*
2085  * Extract the physical page address associated with the given
2086  * kernel virtual address.
2087  */
2088 static vm_paddr_t
2089 mmu_booke_kextract(mmu_t mmu, vm_offset_t va)
2090 {
2091 	tlb_entry_t e;
2092 	int i;
2093 
2094 	/* Check TLB1 mappings */
2095 	for (i = 0; i < TLB1_ENTRIES; i++) {
2096 		tlb1_read_entry(&e, i);
2097 		if (!(e.mas1 & MAS1_VALID))
2098 			continue;
2099 		if (va >= e.virt && va < e.virt + e.size)
2100 			return (e.phys + (va - e.virt));
2101 	}
2102 
2103 	return (pte_vatopa(mmu, kernel_pmap, va));
2104 }
2105 
2106 /*
2107  * Initialize the pmap module.
2108  * Called by vm_init, to initialize any structures that the pmap
2109  * system needs to map virtual memory.
2110  */
2111 static void
2112 mmu_booke_init(mmu_t mmu)
2113 {
2114 	int shpgperproc = PMAP_SHPGPERPROC;
2115 
2116 	/*
2117 	 * Initialize the address space (zone) for the pv entries.  Set a
2118 	 * high water mark so that the system can recover from excessive
2119 	 * numbers of pv entries.
2120 	 */
2121 	pvzone = uma_zcreate("PV ENTRY", sizeof(struct pv_entry), NULL, NULL,
2122 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
2123 
2124 	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
2125 	pv_entry_max = shpgperproc * maxproc + vm_cnt.v_page_count;
2126 
2127 	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
2128 	pv_entry_high_water = 9 * (pv_entry_max / 10);
2129 
2130 	uma_zone_reserve_kva(pvzone, pv_entry_max);
2131 
2132 	/* Pre-fill pvzone with initial number of pv entries. */
2133 	uma_prealloc(pvzone, PV_ENTRY_ZONE_MIN);
2134 
2135 	/* Initialize ptbl allocation. */
2136 	ptbl_init();
2137 }
2138 
2139 /*
2140  * Map a list of wired pages into kernel virtual address space.  This is
2141  * intended for temporary mappings which do not need page modification or
2142  * references recorded.  Existing mappings in the region are overwritten.
2143  */
2144 static void
2145 mmu_booke_qenter(mmu_t mmu, vm_offset_t sva, vm_page_t *m, int count)
2146 {
2147 	vm_offset_t va;
2148 
2149 	va = sva;
2150 	while (count-- > 0) {
2151 		mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(*m));
2152 		va += PAGE_SIZE;
2153 		m++;
2154 	}
2155 }
2156 
2157 /*
2158  * Remove page mappings from kernel virtual address space.  Intended for
2159  * temporary mappings entered by mmu_booke_qenter.
2160  */
2161 static void
2162 mmu_booke_qremove(mmu_t mmu, vm_offset_t sva, int count)
2163 {
2164 	vm_offset_t va;
2165 
2166 	va = sva;
2167 	while (count-- > 0) {
2168 		mmu_booke_kremove(mmu, va);
2169 		va += PAGE_SIZE;
2170 	}
2171 }
2172 
2173 /*
2174  * Map a wired page into kernel virtual address space.
2175  */
2176 static void
2177 mmu_booke_kenter(mmu_t mmu, vm_offset_t va, vm_paddr_t pa)
2178 {
2179 
2180 	mmu_booke_kenter_attr(mmu, va, pa, VM_MEMATTR_DEFAULT);
2181 }
2182 
2183 static void
2184 mmu_booke_kenter_attr(mmu_t mmu, vm_offset_t va, vm_paddr_t pa, vm_memattr_t ma)
2185 {
2186 	uint32_t flags;
2187 	pte_t *pte;
2188 
2189 	KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
2190 	    (va <= VM_MAX_KERNEL_ADDRESS)), ("mmu_booke_kenter: invalid va"));
2191 
2192 	flags = PTE_SR | PTE_SW | PTE_SX | PTE_WIRED | PTE_VALID;
2193 	flags |= tlb_calc_wimg(pa, ma) << PTE_MAS2_SHIFT;
2194 	flags |= PTE_PS_4KB;
2195 
2196 	pte = pte_find(mmu, kernel_pmap, va);
2197 	KASSERT((pte != NULL), ("mmu_booke_kenter: invalid va.  NULL PTE"));
2198 
2199 	mtx_lock_spin(&tlbivax_mutex);
2200 	tlb_miss_lock();
2201 
2202 	if (PTE_ISVALID(pte)) {
2203 
2204 		CTR1(KTR_PMAP, "%s: replacing entry!", __func__);
2205 
2206 		/* Flush entry from TLB0 */
2207 		tlb0_flush_entry(va);
2208 	}
2209 
2210 	*pte = PTE_RPN_FROM_PA(pa) | flags;
2211 
2212 	//debugf("mmu_booke_kenter: pdir_idx = %d ptbl_idx = %d va=0x%08x "
2213 	//		"pa=0x%08x rpn=0x%08x flags=0x%08x\n",
2214 	//		pdir_idx, ptbl_idx, va, pa, pte->rpn, pte->flags);
2215 
2216 	/* Flush the real memory from the instruction cache. */
2217 	if ((flags & (PTE_I | PTE_G)) == 0)
2218 		__syncicache((void *)va, PAGE_SIZE);
2219 
2220 	tlb_miss_unlock();
2221 	mtx_unlock_spin(&tlbivax_mutex);
2222 }
2223 
2224 /*
2225  * Remove a page from kernel page table.
2226  */
2227 static void
2228 mmu_booke_kremove(mmu_t mmu, vm_offset_t va)
2229 {
2230 	pte_t *pte;
2231 
2232 	CTR2(KTR_PMAP,"%s: s (va = 0x%08x)\n", __func__, va);
2233 
2234 	KASSERT(((va >= VM_MIN_KERNEL_ADDRESS) &&
2235 	    (va <= VM_MAX_KERNEL_ADDRESS)),
2236 	    ("mmu_booke_kremove: invalid va"));
2237 
2238 	pte = pte_find(mmu, kernel_pmap, va);
2239 
2240 	if (!PTE_ISVALID(pte)) {
2241 
2242 		CTR1(KTR_PMAP, "%s: invalid pte", __func__);
2243 
2244 		return;
2245 	}
2246 
2247 	mtx_lock_spin(&tlbivax_mutex);
2248 	tlb_miss_lock();
2249 
2250 	/* Invalidate entry in TLB0, update PTE. */
2251 	tlb0_flush_entry(va);
2252 	*pte = 0;
2253 
2254 	tlb_miss_unlock();
2255 	mtx_unlock_spin(&tlbivax_mutex);
2256 }
2257 
2258 /*
2259  * Initialize pmap associated with process 0.
2260  */
2261 static void
2262 mmu_booke_pinit0(mmu_t mmu, pmap_t pmap)
2263 {
2264 
2265 	PMAP_LOCK_INIT(pmap);
2266 	mmu_booke_pinit(mmu, pmap);
2267 	PCPU_SET(curpmap, pmap);
2268 }
2269 
2270 /*
2271  * Initialize a preallocated and zeroed pmap structure,
2272  * such as one in a vmspace structure.
2273  */
2274 static void
2275 mmu_booke_pinit(mmu_t mmu, pmap_t pmap)
2276 {
2277 	int i;
2278 
2279 	CTR4(KTR_PMAP, "%s: pmap = %p, proc %d '%s'", __func__, pmap,
2280 	    curthread->td_proc->p_pid, curthread->td_proc->p_comm);
2281 
2282 	KASSERT((pmap != kernel_pmap), ("pmap_pinit: initializing kernel_pmap"));
2283 
2284 	for (i = 0; i < MAXCPU; i++)
2285 		pmap->pm_tid[i] = TID_NONE;
2286 	CPU_ZERO(&kernel_pmap->pm_active);
2287 	bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2288 #ifdef __powerpc64__
2289 	bzero(&pmap->pm_pp2d, sizeof(pte_t **) * PP2D_NENTRIES);
2290 	TAILQ_INIT(&pmap->pm_pdir_list);
2291 #else
2292 	bzero(&pmap->pm_pdir, sizeof(pte_t *) * PDIR_NENTRIES);
2293 #endif
2294 	TAILQ_INIT(&pmap->pm_ptbl_list);
2295 }
2296 
2297 /*
2298  * Release any resources held by the given physical map.
2299  * Called when a pmap initialized by mmu_booke_pinit is being released.
2300  * Should only be called if the map contains no valid mappings.
2301  */
2302 static void
2303 mmu_booke_release(mmu_t mmu, pmap_t pmap)
2304 {
2305 
2306 	KASSERT(pmap->pm_stats.resident_count == 0,
2307 	    ("pmap_release: pmap resident count %ld != 0",
2308 	    pmap->pm_stats.resident_count));
2309 }
2310 
2311 /*
2312  * Insert the given physical page at the specified virtual address in the
2313  * target physical map with the protection requested. If specified the page
2314  * will be wired down.
2315  */
2316 static int
2317 mmu_booke_enter(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
2318     vm_prot_t prot, u_int flags, int8_t psind)
2319 {
2320 	int error;
2321 
2322 	rw_wlock(&pvh_global_lock);
2323 	PMAP_LOCK(pmap);
2324 	error = mmu_booke_enter_locked(mmu, pmap, va, m, prot, flags, psind);
2325 	PMAP_UNLOCK(pmap);
2326 	rw_wunlock(&pvh_global_lock);
2327 	return (error);
2328 }
2329 
2330 static int
2331 mmu_booke_enter_locked(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
2332     vm_prot_t prot, u_int pmap_flags, int8_t psind __unused)
2333 {
2334 	pte_t *pte;
2335 	vm_paddr_t pa;
2336 	uint32_t flags;
2337 	int error, su, sync;
2338 
2339 	pa = VM_PAGE_TO_PHYS(m);
2340 	su = (pmap == kernel_pmap);
2341 	sync = 0;
2342 
2343 	//debugf("mmu_booke_enter_locked: s (pmap=0x%08x su=%d tid=%d m=0x%08x va=0x%08x "
2344 	//		"pa=0x%08x prot=0x%08x flags=%#x)\n",
2345 	//		(u_int32_t)pmap, su, pmap->pm_tid,
2346 	//		(u_int32_t)m, va, pa, prot, flags);
2347 
2348 	if (su) {
2349 		KASSERT(((va >= virtual_avail) &&
2350 		    (va <= VM_MAX_KERNEL_ADDRESS)),
2351 		    ("mmu_booke_enter_locked: kernel pmap, non kernel va"));
2352 	} else {
2353 		KASSERT((va <= VM_MAXUSER_ADDRESS),
2354 		    ("mmu_booke_enter_locked: user pmap, non user va"));
2355 	}
2356 	if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
2357 		VM_OBJECT_ASSERT_LOCKED(m->object);
2358 
2359 	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2360 
2361 	/*
2362 	 * If there is an existing mapping, and the physical address has not
2363 	 * changed, must be protection or wiring change.
2364 	 */
2365 	if (((pte = pte_find(mmu, pmap, va)) != NULL) &&
2366 	    (PTE_ISVALID(pte)) && (PTE_PA(pte) == pa)) {
2367 
2368 		/*
2369 		 * Before actually updating pte->flags we calculate and
2370 		 * prepare its new value in a helper var.
2371 		 */
2372 		flags = *pte;
2373 		flags &= ~(PTE_UW | PTE_UX | PTE_SW | PTE_SX | PTE_MODIFIED);
2374 
2375 		/* Wiring change, just update stats. */
2376 		if ((pmap_flags & PMAP_ENTER_WIRED) != 0) {
2377 			if (!PTE_ISWIRED(pte)) {
2378 				flags |= PTE_WIRED;
2379 				pmap->pm_stats.wired_count++;
2380 			}
2381 		} else {
2382 			if (PTE_ISWIRED(pte)) {
2383 				flags &= ~PTE_WIRED;
2384 				pmap->pm_stats.wired_count--;
2385 			}
2386 		}
2387 
2388 		if (prot & VM_PROT_WRITE) {
2389 			/* Add write permissions. */
2390 			flags |= PTE_SW;
2391 			if (!su)
2392 				flags |= PTE_UW;
2393 
2394 			if ((flags & PTE_MANAGED) != 0)
2395 				vm_page_aflag_set(m, PGA_WRITEABLE);
2396 		} else {
2397 			/* Handle modified pages, sense modify status. */
2398 
2399 			/*
2400 			 * The PTE_MODIFIED flag could be set by underlying
2401 			 * TLB misses since we last read it (above), possibly
2402 			 * other CPUs could update it so we check in the PTE
2403 			 * directly rather than rely on that saved local flags
2404 			 * copy.
2405 			 */
2406 			if (PTE_ISMODIFIED(pte))
2407 				vm_page_dirty(m);
2408 		}
2409 
2410 		if (prot & VM_PROT_EXECUTE) {
2411 			flags |= PTE_SX;
2412 			if (!su)
2413 				flags |= PTE_UX;
2414 
2415 			/*
2416 			 * Check existing flags for execute permissions: if we
2417 			 * are turning execute permissions on, icache should
2418 			 * be flushed.
2419 			 */
2420 			if ((*pte & (PTE_UX | PTE_SX)) == 0)
2421 				sync++;
2422 		}
2423 
2424 		flags &= ~PTE_REFERENCED;
2425 
2426 		/*
2427 		 * The new flags value is all calculated -- only now actually
2428 		 * update the PTE.
2429 		 */
2430 		mtx_lock_spin(&tlbivax_mutex);
2431 		tlb_miss_lock();
2432 
2433 		tlb0_flush_entry(va);
2434 		*pte &= ~PTE_FLAGS_MASK;
2435 		*pte |= flags;
2436 
2437 		tlb_miss_unlock();
2438 		mtx_unlock_spin(&tlbivax_mutex);
2439 
2440 	} else {
2441 		/*
2442 		 * If there is an existing mapping, but it's for a different
2443 		 * physical address, pte_enter() will delete the old mapping.
2444 		 */
2445 		//if ((pte != NULL) && PTE_ISVALID(pte))
2446 		//	debugf("mmu_booke_enter_locked: replace\n");
2447 		//else
2448 		//	debugf("mmu_booke_enter_locked: new\n");
2449 
2450 		/* Now set up the flags and install the new mapping. */
2451 		flags = (PTE_SR | PTE_VALID);
2452 		flags |= PTE_M;
2453 
2454 		if (!su)
2455 			flags |= PTE_UR;
2456 
2457 		if (prot & VM_PROT_WRITE) {
2458 			flags |= PTE_SW;
2459 			if (!su)
2460 				flags |= PTE_UW;
2461 
2462 			if ((m->oflags & VPO_UNMANAGED) == 0)
2463 				vm_page_aflag_set(m, PGA_WRITEABLE);
2464 		}
2465 
2466 		if (prot & VM_PROT_EXECUTE) {
2467 			flags |= PTE_SX;
2468 			if (!su)
2469 				flags |= PTE_UX;
2470 		}
2471 
2472 		/* If its wired update stats. */
2473 		if ((pmap_flags & PMAP_ENTER_WIRED) != 0)
2474 			flags |= PTE_WIRED;
2475 
2476 		error = pte_enter(mmu, pmap, m, va, flags,
2477 		    (pmap_flags & PMAP_ENTER_NOSLEEP) != 0);
2478 		if (error != 0)
2479 			return (KERN_RESOURCE_SHORTAGE);
2480 
2481 		if ((flags & PMAP_ENTER_WIRED) != 0)
2482 			pmap->pm_stats.wired_count++;
2483 
2484 		/* Flush the real memory from the instruction cache. */
2485 		if (prot & VM_PROT_EXECUTE)
2486 			sync++;
2487 	}
2488 
2489 	if (sync && (su || pmap == PCPU_GET(curpmap))) {
2490 		__syncicache((void *)va, PAGE_SIZE);
2491 		sync = 0;
2492 	}
2493 
2494 	return (KERN_SUCCESS);
2495 }
2496 
2497 /*
2498  * Maps a sequence of resident pages belonging to the same object.
2499  * The sequence begins with the given page m_start.  This page is
2500  * mapped at the given virtual address start.  Each subsequent page is
2501  * mapped at a virtual address that is offset from start by the same
2502  * amount as the page is offset from m_start within the object.  The
2503  * last page in the sequence is the page with the largest offset from
2504  * m_start that can be mapped at a virtual address less than the given
2505  * virtual address end.  Not every virtual page between start and end
2506  * is mapped; only those for which a resident page exists with the
2507  * corresponding offset from m_start are mapped.
2508  */
2509 static void
2510 mmu_booke_enter_object(mmu_t mmu, pmap_t pmap, vm_offset_t start,
2511     vm_offset_t end, vm_page_t m_start, vm_prot_t prot)
2512 {
2513 	vm_page_t m;
2514 	vm_pindex_t diff, psize;
2515 
2516 	VM_OBJECT_ASSERT_LOCKED(m_start->object);
2517 
2518 	psize = atop(end - start);
2519 	m = m_start;
2520 	rw_wlock(&pvh_global_lock);
2521 	PMAP_LOCK(pmap);
2522 	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
2523 		mmu_booke_enter_locked(mmu, pmap, start + ptoa(diff), m,
2524 		    prot & (VM_PROT_READ | VM_PROT_EXECUTE),
2525 		    PMAP_ENTER_NOSLEEP, 0);
2526 		m = TAILQ_NEXT(m, listq);
2527 	}
2528 	rw_wunlock(&pvh_global_lock);
2529 	PMAP_UNLOCK(pmap);
2530 }
2531 
2532 static void
2533 mmu_booke_enter_quick(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_page_t m,
2534     vm_prot_t prot)
2535 {
2536 
2537 	rw_wlock(&pvh_global_lock);
2538 	PMAP_LOCK(pmap);
2539 	mmu_booke_enter_locked(mmu, pmap, va, m,
2540 	    prot & (VM_PROT_READ | VM_PROT_EXECUTE), PMAP_ENTER_NOSLEEP,
2541 	    0);
2542 	rw_wunlock(&pvh_global_lock);
2543 	PMAP_UNLOCK(pmap);
2544 }
2545 
2546 /*
2547  * Remove the given range of addresses from the specified map.
2548  *
2549  * It is assumed that the start and end are properly rounded to the page size.
2550  */
2551 static void
2552 mmu_booke_remove(mmu_t mmu, pmap_t pmap, vm_offset_t va, vm_offset_t endva)
2553 {
2554 	pte_t *pte;
2555 	uint8_t hold_flag;
2556 
2557 	int su = (pmap == kernel_pmap);
2558 
2559 	//debugf("mmu_booke_remove: s (su = %d pmap=0x%08x tid=%d va=0x%08x endva=0x%08x)\n",
2560 	//		su, (u_int32_t)pmap, pmap->pm_tid, va, endva);
2561 
2562 	if (su) {
2563 		KASSERT(((va >= virtual_avail) &&
2564 		    (va <= VM_MAX_KERNEL_ADDRESS)),
2565 		    ("mmu_booke_remove: kernel pmap, non kernel va"));
2566 	} else {
2567 		KASSERT((va <= VM_MAXUSER_ADDRESS),
2568 		    ("mmu_booke_remove: user pmap, non user va"));
2569 	}
2570 
2571 	if (PMAP_REMOVE_DONE(pmap)) {
2572 		//debugf("mmu_booke_remove: e (empty)\n");
2573 		return;
2574 	}
2575 
2576 	hold_flag = PTBL_HOLD_FLAG(pmap);
2577 	//debugf("mmu_booke_remove: hold_flag = %d\n", hold_flag);
2578 
2579 	rw_wlock(&pvh_global_lock);
2580 	PMAP_LOCK(pmap);
2581 	for (; va < endva; va += PAGE_SIZE) {
2582 		pte = pte_find(mmu, pmap, va);
2583 		if ((pte != NULL) && PTE_ISVALID(pte))
2584 			pte_remove(mmu, pmap, va, hold_flag);
2585 	}
2586 	PMAP_UNLOCK(pmap);
2587 	rw_wunlock(&pvh_global_lock);
2588 
2589 	//debugf("mmu_booke_remove: e\n");
2590 }
2591 
2592 /*
2593  * Remove physical page from all pmaps in which it resides.
2594  */
2595 static void
2596 mmu_booke_remove_all(mmu_t mmu, vm_page_t m)
2597 {
2598 	pv_entry_t pv, pvn;
2599 	uint8_t hold_flag;
2600 
2601 	rw_wlock(&pvh_global_lock);
2602 	for (pv = TAILQ_FIRST(&m->md.pv_list); pv != NULL; pv = pvn) {
2603 		pvn = TAILQ_NEXT(pv, pv_link);
2604 
2605 		PMAP_LOCK(pv->pv_pmap);
2606 		hold_flag = PTBL_HOLD_FLAG(pv->pv_pmap);
2607 		pte_remove(mmu, pv->pv_pmap, pv->pv_va, hold_flag);
2608 		PMAP_UNLOCK(pv->pv_pmap);
2609 	}
2610 	vm_page_aflag_clear(m, PGA_WRITEABLE);
2611 	rw_wunlock(&pvh_global_lock);
2612 }
2613 
2614 /*
2615  * Map a range of physical addresses into kernel virtual address space.
2616  */
2617 static vm_offset_t
2618 mmu_booke_map(mmu_t mmu, vm_offset_t *virt, vm_paddr_t pa_start,
2619     vm_paddr_t pa_end, int prot)
2620 {
2621 	vm_offset_t sva = *virt;
2622 	vm_offset_t va = sva;
2623 
2624 	//debugf("mmu_booke_map: s (sva = 0x%08x pa_start = 0x%08x pa_end = 0x%08x)\n",
2625 	//		sva, pa_start, pa_end);
2626 
2627 	while (pa_start < pa_end) {
2628 		mmu_booke_kenter(mmu, va, pa_start);
2629 		va += PAGE_SIZE;
2630 		pa_start += PAGE_SIZE;
2631 	}
2632 	*virt = va;
2633 
2634 	//debugf("mmu_booke_map: e (va = 0x%08x)\n", va);
2635 	return (sva);
2636 }
2637 
2638 /*
2639  * The pmap must be activated before it's address space can be accessed in any
2640  * way.
2641  */
2642 static void
2643 mmu_booke_activate(mmu_t mmu, struct thread *td)
2644 {
2645 	pmap_t pmap;
2646 	u_int cpuid;
2647 
2648 	pmap = &td->td_proc->p_vmspace->vm_pmap;
2649 
2650 	CTR5(KTR_PMAP, "%s: s (td = %p, proc = '%s', id = %d, pmap = 0x%08x)",
2651 	    __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
2652 
2653 	KASSERT((pmap != kernel_pmap), ("mmu_booke_activate: kernel_pmap!"));
2654 
2655 	sched_pin();
2656 
2657 	cpuid = PCPU_GET(cpuid);
2658 	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
2659 	PCPU_SET(curpmap, pmap);
2660 
2661 	if (pmap->pm_tid[cpuid] == TID_NONE)
2662 		tid_alloc(pmap);
2663 
2664 	/* Load PID0 register with pmap tid value. */
2665 	mtspr(SPR_PID0, pmap->pm_tid[cpuid]);
2666 	__asm __volatile("isync");
2667 
2668 	mtspr(SPR_DBCR0, td->td_pcb->pcb_cpu.booke.dbcr0);
2669 
2670 	sched_unpin();
2671 
2672 	CTR3(KTR_PMAP, "%s: e (tid = %d for '%s')", __func__,
2673 	    pmap->pm_tid[PCPU_GET(cpuid)], td->td_proc->p_comm);
2674 }
2675 
2676 /*
2677  * Deactivate the specified process's address space.
2678  */
2679 static void
2680 mmu_booke_deactivate(mmu_t mmu, struct thread *td)
2681 {
2682 	pmap_t pmap;
2683 
2684 	pmap = &td->td_proc->p_vmspace->vm_pmap;
2685 
2686 	CTR5(KTR_PMAP, "%s: td=%p, proc = '%s', id = %d, pmap = 0x%08x",
2687 	    __func__, td, td->td_proc->p_comm, td->td_proc->p_pid, pmap);
2688 
2689 	td->td_pcb->pcb_cpu.booke.dbcr0 = mfspr(SPR_DBCR0);
2690 
2691 	CPU_CLR_ATOMIC(PCPU_GET(cpuid), &pmap->pm_active);
2692 	PCPU_SET(curpmap, NULL);
2693 }
2694 
2695 /*
2696  * Copy the range specified by src_addr/len
2697  * from the source map to the range dst_addr/len
2698  * in the destination map.
2699  *
2700  * This routine is only advisory and need not do anything.
2701  */
2702 static void
2703 mmu_booke_copy(mmu_t mmu, pmap_t dst_pmap, pmap_t src_pmap,
2704     vm_offset_t dst_addr, vm_size_t len, vm_offset_t src_addr)
2705 {
2706 
2707 }
2708 
2709 /*
2710  * Set the physical protection on the specified range of this map as requested.
2711  */
2712 static void
2713 mmu_booke_protect(mmu_t mmu, pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
2714     vm_prot_t prot)
2715 {
2716 	vm_offset_t va;
2717 	vm_page_t m;
2718 	pte_t *pte;
2719 
2720 	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2721 		mmu_booke_remove(mmu, pmap, sva, eva);
2722 		return;
2723 	}
2724 
2725 	if (prot & VM_PROT_WRITE)
2726 		return;
2727 
2728 	PMAP_LOCK(pmap);
2729 	for (va = sva; va < eva; va += PAGE_SIZE) {
2730 		if ((pte = pte_find(mmu, pmap, va)) != NULL) {
2731 			if (PTE_ISVALID(pte)) {
2732 				m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2733 
2734 				mtx_lock_spin(&tlbivax_mutex);
2735 				tlb_miss_lock();
2736 
2737 				/* Handle modified pages. */
2738 				if (PTE_ISMODIFIED(pte) && PTE_ISMANAGED(pte))
2739 					vm_page_dirty(m);
2740 
2741 				tlb0_flush_entry(va);
2742 				*pte &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
2743 
2744 				tlb_miss_unlock();
2745 				mtx_unlock_spin(&tlbivax_mutex);
2746 			}
2747 		}
2748 	}
2749 	PMAP_UNLOCK(pmap);
2750 }
2751 
2752 /*
2753  * Clear the write and modified bits in each of the given page's mappings.
2754  */
2755 static void
2756 mmu_booke_remove_write(mmu_t mmu, vm_page_t m)
2757 {
2758 	pv_entry_t pv;
2759 	pte_t *pte;
2760 
2761 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2762 	    ("mmu_booke_remove_write: page %p is not managed", m));
2763 
2764 	/*
2765 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
2766 	 * set by another thread while the object is locked.  Thus,
2767 	 * if PGA_WRITEABLE is clear, no page table entries need updating.
2768 	 */
2769 	VM_OBJECT_ASSERT_WLOCKED(m->object);
2770 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
2771 		return;
2772 	rw_wlock(&pvh_global_lock);
2773 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
2774 		PMAP_LOCK(pv->pv_pmap);
2775 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL) {
2776 			if (PTE_ISVALID(pte)) {
2777 				m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2778 
2779 				mtx_lock_spin(&tlbivax_mutex);
2780 				tlb_miss_lock();
2781 
2782 				/* Handle modified pages. */
2783 				if (PTE_ISMODIFIED(pte))
2784 					vm_page_dirty(m);
2785 
2786 				/* Flush mapping from TLB0. */
2787 				*pte &= ~(PTE_UW | PTE_SW | PTE_MODIFIED);
2788 
2789 				tlb_miss_unlock();
2790 				mtx_unlock_spin(&tlbivax_mutex);
2791 			}
2792 		}
2793 		PMAP_UNLOCK(pv->pv_pmap);
2794 	}
2795 	vm_page_aflag_clear(m, PGA_WRITEABLE);
2796 	rw_wunlock(&pvh_global_lock);
2797 }
2798 
2799 static void
2800 mmu_booke_sync_icache(mmu_t mmu, pmap_t pm, vm_offset_t va, vm_size_t sz)
2801 {
2802 	pte_t *pte;
2803 	pmap_t pmap;
2804 	vm_page_t m;
2805 	vm_offset_t addr;
2806 	vm_paddr_t pa = 0;
2807 	int active, valid;
2808 
2809 	va = trunc_page(va);
2810 	sz = round_page(sz);
2811 
2812 	rw_wlock(&pvh_global_lock);
2813 	pmap = PCPU_GET(curpmap);
2814 	active = (pm == kernel_pmap || pm == pmap) ? 1 : 0;
2815 	while (sz > 0) {
2816 		PMAP_LOCK(pm);
2817 		pte = pte_find(mmu, pm, va);
2818 		valid = (pte != NULL && PTE_ISVALID(pte)) ? 1 : 0;
2819 		if (valid)
2820 			pa = PTE_PA(pte);
2821 		PMAP_UNLOCK(pm);
2822 		if (valid) {
2823 			if (!active) {
2824 				/* Create a mapping in the active pmap. */
2825 				addr = 0;
2826 				m = PHYS_TO_VM_PAGE(pa);
2827 				PMAP_LOCK(pmap);
2828 				pte_enter(mmu, pmap, m, addr,
2829 				    PTE_SR | PTE_VALID | PTE_UR, FALSE);
2830 				__syncicache((void *)addr, PAGE_SIZE);
2831 				pte_remove(mmu, pmap, addr, PTBL_UNHOLD);
2832 				PMAP_UNLOCK(pmap);
2833 			} else
2834 				__syncicache((void *)va, PAGE_SIZE);
2835 		}
2836 		va += PAGE_SIZE;
2837 		sz -= PAGE_SIZE;
2838 	}
2839 	rw_wunlock(&pvh_global_lock);
2840 }
2841 
2842 /*
2843  * Atomically extract and hold the physical page with the given
2844  * pmap and virtual address pair if that mapping permits the given
2845  * protection.
2846  */
2847 static vm_page_t
2848 mmu_booke_extract_and_hold(mmu_t mmu, pmap_t pmap, vm_offset_t va,
2849     vm_prot_t prot)
2850 {
2851 	pte_t *pte;
2852 	vm_page_t m;
2853 	uint32_t pte_wbit;
2854 	vm_paddr_t pa;
2855 
2856 	m = NULL;
2857 	pa = 0;
2858 	PMAP_LOCK(pmap);
2859 retry:
2860 	pte = pte_find(mmu, pmap, va);
2861 	if ((pte != NULL) && PTE_ISVALID(pte)) {
2862 		if (pmap == kernel_pmap)
2863 			pte_wbit = PTE_SW;
2864 		else
2865 			pte_wbit = PTE_UW;
2866 
2867 		if ((*pte & pte_wbit) || ((prot & VM_PROT_WRITE) == 0)) {
2868 			if (vm_page_pa_tryrelock(pmap, PTE_PA(pte), &pa))
2869 				goto retry;
2870 			m = PHYS_TO_VM_PAGE(PTE_PA(pte));
2871 			vm_page_hold(m);
2872 		}
2873 	}
2874 
2875 	PA_UNLOCK_COND(pa);
2876 	PMAP_UNLOCK(pmap);
2877 	return (m);
2878 }
2879 
2880 /*
2881  * Initialize a vm_page's machine-dependent fields.
2882  */
2883 static void
2884 mmu_booke_page_init(mmu_t mmu, vm_page_t m)
2885 {
2886 
2887 	m->md.pv_tracked = 0;
2888 	TAILQ_INIT(&m->md.pv_list);
2889 }
2890 
2891 /*
2892  * mmu_booke_zero_page_area zeros the specified hardware page by
2893  * mapping it into virtual memory and using bzero to clear
2894  * its contents.
2895  *
2896  * off and size must reside within a single page.
2897  */
2898 static void
2899 mmu_booke_zero_page_area(mmu_t mmu, vm_page_t m, int off, int size)
2900 {
2901 	vm_offset_t va;
2902 
2903 	/* XXX KASSERT off and size are within a single page? */
2904 
2905 	mtx_lock(&zero_page_mutex);
2906 	va = zero_page_va;
2907 
2908 	mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(m));
2909 	bzero((caddr_t)va + off, size);
2910 	mmu_booke_kremove(mmu, va);
2911 
2912 	mtx_unlock(&zero_page_mutex);
2913 }
2914 
2915 /*
2916  * mmu_booke_zero_page zeros the specified hardware page.
2917  */
2918 static void
2919 mmu_booke_zero_page(mmu_t mmu, vm_page_t m)
2920 {
2921 	vm_offset_t off, va;
2922 
2923 	mtx_lock(&zero_page_mutex);
2924 	va = zero_page_va;
2925 
2926 	mmu_booke_kenter(mmu, va, VM_PAGE_TO_PHYS(m));
2927 	for (off = 0; off < PAGE_SIZE; off += cacheline_size)
2928 		__asm __volatile("dcbz 0,%0" :: "r"(va + off));
2929 	mmu_booke_kremove(mmu, va);
2930 
2931 	mtx_unlock(&zero_page_mutex);
2932 }
2933 
2934 /*
2935  * mmu_booke_copy_page copies the specified (machine independent) page by
2936  * mapping the page into virtual memory and using memcopy to copy the page,
2937  * one machine dependent page at a time.
2938  */
2939 static void
2940 mmu_booke_copy_page(mmu_t mmu, vm_page_t sm, vm_page_t dm)
2941 {
2942 	vm_offset_t sva, dva;
2943 
2944 	sva = copy_page_src_va;
2945 	dva = copy_page_dst_va;
2946 
2947 	mtx_lock(&copy_page_mutex);
2948 	mmu_booke_kenter(mmu, sva, VM_PAGE_TO_PHYS(sm));
2949 	mmu_booke_kenter(mmu, dva, VM_PAGE_TO_PHYS(dm));
2950 	memcpy((caddr_t)dva, (caddr_t)sva, PAGE_SIZE);
2951 	mmu_booke_kremove(mmu, dva);
2952 	mmu_booke_kremove(mmu, sva);
2953 	mtx_unlock(&copy_page_mutex);
2954 }
2955 
2956 static inline void
2957 mmu_booke_copy_pages(mmu_t mmu, vm_page_t *ma, vm_offset_t a_offset,
2958     vm_page_t *mb, vm_offset_t b_offset, int xfersize)
2959 {
2960 	void *a_cp, *b_cp;
2961 	vm_offset_t a_pg_offset, b_pg_offset;
2962 	int cnt;
2963 
2964 	mtx_lock(&copy_page_mutex);
2965 	while (xfersize > 0) {
2966 		a_pg_offset = a_offset & PAGE_MASK;
2967 		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
2968 		mmu_booke_kenter(mmu, copy_page_src_va,
2969 		    VM_PAGE_TO_PHYS(ma[a_offset >> PAGE_SHIFT]));
2970 		a_cp = (char *)copy_page_src_va + a_pg_offset;
2971 		b_pg_offset = b_offset & PAGE_MASK;
2972 		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
2973 		mmu_booke_kenter(mmu, copy_page_dst_va,
2974 		    VM_PAGE_TO_PHYS(mb[b_offset >> PAGE_SHIFT]));
2975 		b_cp = (char *)copy_page_dst_va + b_pg_offset;
2976 		bcopy(a_cp, b_cp, cnt);
2977 		mmu_booke_kremove(mmu, copy_page_dst_va);
2978 		mmu_booke_kremove(mmu, copy_page_src_va);
2979 		a_offset += cnt;
2980 		b_offset += cnt;
2981 		xfersize -= cnt;
2982 	}
2983 	mtx_unlock(&copy_page_mutex);
2984 }
2985 
2986 static vm_offset_t
2987 mmu_booke_quick_enter_page(mmu_t mmu, vm_page_t m)
2988 {
2989 	vm_paddr_t paddr;
2990 	vm_offset_t qaddr;
2991 	uint32_t flags;
2992 	pte_t *pte;
2993 
2994 	paddr = VM_PAGE_TO_PHYS(m);
2995 
2996 	flags = PTE_SR | PTE_SW | PTE_SX | PTE_WIRED | PTE_VALID;
2997 	flags |= tlb_calc_wimg(paddr, pmap_page_get_memattr(m)) << PTE_MAS2_SHIFT;
2998 	flags |= PTE_PS_4KB;
2999 
3000 	critical_enter();
3001 	qaddr = PCPU_GET(qmap_addr);
3002 
3003 	pte = pte_find(mmu, kernel_pmap, qaddr);
3004 
3005 	KASSERT(*pte == 0, ("mmu_booke_quick_enter_page: PTE busy"));
3006 
3007 	/*
3008 	 * XXX: tlbivax is broadcast to other cores, but qaddr should
3009  	 * not be present in other TLBs.  Is there a better instruction
3010 	 * sequence to use? Or just forget it & use mmu_booke_kenter()...
3011 	 */
3012 	__asm __volatile("tlbivax 0, %0" :: "r"(qaddr & MAS2_EPN_MASK));
3013 	__asm __volatile("isync; msync");
3014 
3015 	*pte = PTE_RPN_FROM_PA(paddr) | flags;
3016 
3017 	/* Flush the real memory from the instruction cache. */
3018 	if ((flags & (PTE_I | PTE_G)) == 0)
3019 		__syncicache((void *)qaddr, PAGE_SIZE);
3020 
3021 	return (qaddr);
3022 }
3023 
3024 static void
3025 mmu_booke_quick_remove_page(mmu_t mmu, vm_offset_t addr)
3026 {
3027 	pte_t *pte;
3028 
3029 	pte = pte_find(mmu, kernel_pmap, addr);
3030 
3031 	KASSERT(PCPU_GET(qmap_addr) == addr,
3032 	    ("mmu_booke_quick_remove_page: invalid address"));
3033 	KASSERT(*pte != 0,
3034 	    ("mmu_booke_quick_remove_page: PTE not in use"));
3035 
3036 	*pte = 0;
3037 	critical_exit();
3038 }
3039 
3040 /*
3041  * Return whether or not the specified physical page was modified
3042  * in any of physical maps.
3043  */
3044 static boolean_t
3045 mmu_booke_is_modified(mmu_t mmu, vm_page_t m)
3046 {
3047 	pte_t *pte;
3048 	pv_entry_t pv;
3049 	boolean_t rv;
3050 
3051 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3052 	    ("mmu_booke_is_modified: page %p is not managed", m));
3053 	rv = FALSE;
3054 
3055 	/*
3056 	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
3057 	 * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
3058 	 * is clear, no PTEs can be modified.
3059 	 */
3060 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3061 	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
3062 		return (rv);
3063 	rw_wlock(&pvh_global_lock);
3064 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3065 		PMAP_LOCK(pv->pv_pmap);
3066 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
3067 		    PTE_ISVALID(pte)) {
3068 			if (PTE_ISMODIFIED(pte))
3069 				rv = TRUE;
3070 		}
3071 		PMAP_UNLOCK(pv->pv_pmap);
3072 		if (rv)
3073 			break;
3074 	}
3075 	rw_wunlock(&pvh_global_lock);
3076 	return (rv);
3077 }
3078 
3079 /*
3080  * Return whether or not the specified virtual address is eligible
3081  * for prefault.
3082  */
3083 static boolean_t
3084 mmu_booke_is_prefaultable(mmu_t mmu, pmap_t pmap, vm_offset_t addr)
3085 {
3086 
3087 	return (FALSE);
3088 }
3089 
3090 /*
3091  * Return whether or not the specified physical page was referenced
3092  * in any physical maps.
3093  */
3094 static boolean_t
3095 mmu_booke_is_referenced(mmu_t mmu, vm_page_t m)
3096 {
3097 	pte_t *pte;
3098 	pv_entry_t pv;
3099 	boolean_t rv;
3100 
3101 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3102 	    ("mmu_booke_is_referenced: page %p is not managed", m));
3103 	rv = FALSE;
3104 	rw_wlock(&pvh_global_lock);
3105 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3106 		PMAP_LOCK(pv->pv_pmap);
3107 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
3108 		    PTE_ISVALID(pte)) {
3109 			if (PTE_ISREFERENCED(pte))
3110 				rv = TRUE;
3111 		}
3112 		PMAP_UNLOCK(pv->pv_pmap);
3113 		if (rv)
3114 			break;
3115 	}
3116 	rw_wunlock(&pvh_global_lock);
3117 	return (rv);
3118 }
3119 
3120 /*
3121  * Clear the modify bits on the specified physical page.
3122  */
3123 static void
3124 mmu_booke_clear_modify(mmu_t mmu, vm_page_t m)
3125 {
3126 	pte_t *pte;
3127 	pv_entry_t pv;
3128 
3129 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3130 	    ("mmu_booke_clear_modify: page %p is not managed", m));
3131 	VM_OBJECT_ASSERT_WLOCKED(m->object);
3132 	KASSERT(!vm_page_xbusied(m),
3133 	    ("mmu_booke_clear_modify: page %p is exclusive busied", m));
3134 
3135 	/*
3136 	 * If the page is not PG_AWRITEABLE, then no PTEs can be modified.
3137 	 * If the object containing the page is locked and the page is not
3138 	 * exclusive busied, then PG_AWRITEABLE cannot be concurrently set.
3139 	 */
3140 	if ((m->aflags & PGA_WRITEABLE) == 0)
3141 		return;
3142 	rw_wlock(&pvh_global_lock);
3143 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3144 		PMAP_LOCK(pv->pv_pmap);
3145 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
3146 		    PTE_ISVALID(pte)) {
3147 			mtx_lock_spin(&tlbivax_mutex);
3148 			tlb_miss_lock();
3149 
3150 			if (*pte & (PTE_SW | PTE_UW | PTE_MODIFIED)) {
3151 				tlb0_flush_entry(pv->pv_va);
3152 				*pte &= ~(PTE_SW | PTE_UW | PTE_MODIFIED |
3153 				    PTE_REFERENCED);
3154 			}
3155 
3156 			tlb_miss_unlock();
3157 			mtx_unlock_spin(&tlbivax_mutex);
3158 		}
3159 		PMAP_UNLOCK(pv->pv_pmap);
3160 	}
3161 	rw_wunlock(&pvh_global_lock);
3162 }
3163 
3164 /*
3165  * Return a count of reference bits for a page, clearing those bits.
3166  * It is not necessary for every reference bit to be cleared, but it
3167  * is necessary that 0 only be returned when there are truly no
3168  * reference bits set.
3169  *
3170  * As an optimization, update the page's dirty field if a modified bit is
3171  * found while counting reference bits.  This opportunistic update can be
3172  * performed at low cost and can eliminate the need for some future calls
3173  * to pmap_is_modified().  However, since this function stops after
3174  * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
3175  * dirty pages.  Those dirty pages will only be detected by a future call
3176  * to pmap_is_modified().
3177  */
3178 static int
3179 mmu_booke_ts_referenced(mmu_t mmu, vm_page_t m)
3180 {
3181 	pte_t *pte;
3182 	pv_entry_t pv;
3183 	int count;
3184 
3185 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3186 	    ("mmu_booke_ts_referenced: page %p is not managed", m));
3187 	count = 0;
3188 	rw_wlock(&pvh_global_lock);
3189 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3190 		PMAP_LOCK(pv->pv_pmap);
3191 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL &&
3192 		    PTE_ISVALID(pte)) {
3193 			if (PTE_ISMODIFIED(pte))
3194 				vm_page_dirty(m);
3195 			if (PTE_ISREFERENCED(pte)) {
3196 				mtx_lock_spin(&tlbivax_mutex);
3197 				tlb_miss_lock();
3198 
3199 				tlb0_flush_entry(pv->pv_va);
3200 				*pte &= ~PTE_REFERENCED;
3201 
3202 				tlb_miss_unlock();
3203 				mtx_unlock_spin(&tlbivax_mutex);
3204 
3205 				if (++count >= PMAP_TS_REFERENCED_MAX) {
3206 					PMAP_UNLOCK(pv->pv_pmap);
3207 					break;
3208 				}
3209 			}
3210 		}
3211 		PMAP_UNLOCK(pv->pv_pmap);
3212 	}
3213 	rw_wunlock(&pvh_global_lock);
3214 	return (count);
3215 }
3216 
3217 /*
3218  * Clear the wired attribute from the mappings for the specified range of
3219  * addresses in the given pmap.  Every valid mapping within that range must
3220  * have the wired attribute set.  In contrast, invalid mappings cannot have
3221  * the wired attribute set, so they are ignored.
3222  *
3223  * The wired attribute of the page table entry is not a hardware feature, so
3224  * there is no need to invalidate any TLB entries.
3225  */
3226 static void
3227 mmu_booke_unwire(mmu_t mmu, pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3228 {
3229 	vm_offset_t va;
3230 	pte_t *pte;
3231 
3232 	PMAP_LOCK(pmap);
3233 	for (va = sva; va < eva; va += PAGE_SIZE) {
3234 		if ((pte = pte_find(mmu, pmap, va)) != NULL &&
3235 		    PTE_ISVALID(pte)) {
3236 			if (!PTE_ISWIRED(pte))
3237 				panic("mmu_booke_unwire: pte %p isn't wired",
3238 				    pte);
3239 			*pte &= ~PTE_WIRED;
3240 			pmap->pm_stats.wired_count--;
3241 		}
3242 	}
3243 	PMAP_UNLOCK(pmap);
3244 
3245 }
3246 
3247 /*
3248  * Return true if the pmap's pv is one of the first 16 pvs linked to from this
3249  * page.  This count may be changed upwards or downwards in the future; it is
3250  * only necessary that true be returned for a small subset of pmaps for proper
3251  * page aging.
3252  */
3253 static boolean_t
3254 mmu_booke_page_exists_quick(mmu_t mmu, pmap_t pmap, vm_page_t m)
3255 {
3256 	pv_entry_t pv;
3257 	int loops;
3258 	boolean_t rv;
3259 
3260 	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3261 	    ("mmu_booke_page_exists_quick: page %p is not managed", m));
3262 	loops = 0;
3263 	rv = FALSE;
3264 	rw_wlock(&pvh_global_lock);
3265 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3266 		if (pv->pv_pmap == pmap) {
3267 			rv = TRUE;
3268 			break;
3269 		}
3270 		if (++loops >= 16)
3271 			break;
3272 	}
3273 	rw_wunlock(&pvh_global_lock);
3274 	return (rv);
3275 }
3276 
3277 /*
3278  * Return the number of managed mappings to the given physical page that are
3279  * wired.
3280  */
3281 static int
3282 mmu_booke_page_wired_mappings(mmu_t mmu, vm_page_t m)
3283 {
3284 	pv_entry_t pv;
3285 	pte_t *pte;
3286 	int count = 0;
3287 
3288 	if ((m->oflags & VPO_UNMANAGED) != 0)
3289 		return (count);
3290 	rw_wlock(&pvh_global_lock);
3291 	TAILQ_FOREACH(pv, &m->md.pv_list, pv_link) {
3292 		PMAP_LOCK(pv->pv_pmap);
3293 		if ((pte = pte_find(mmu, pv->pv_pmap, pv->pv_va)) != NULL)
3294 			if (PTE_ISVALID(pte) && PTE_ISWIRED(pte))
3295 				count++;
3296 		PMAP_UNLOCK(pv->pv_pmap);
3297 	}
3298 	rw_wunlock(&pvh_global_lock);
3299 	return (count);
3300 }
3301 
3302 static int
3303 mmu_booke_dev_direct_mapped(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
3304 {
3305 	int i;
3306 	vm_offset_t va;
3307 
3308 	/*
3309 	 * This currently does not work for entries that
3310 	 * overlap TLB1 entries.
3311 	 */
3312 	for (i = 0; i < TLB1_ENTRIES; i ++) {
3313 		if (tlb1_iomapped(i, pa, size, &va) == 0)
3314 			return (0);
3315 	}
3316 
3317 	return (EFAULT);
3318 }
3319 
3320 void
3321 mmu_booke_dumpsys_map(mmu_t mmu, vm_paddr_t pa, size_t sz, void **va)
3322 {
3323 	vm_paddr_t ppa;
3324 	vm_offset_t ofs;
3325 	vm_size_t gran;
3326 
3327 	/* Minidumps are based on virtual memory addresses. */
3328 	if (do_minidump) {
3329 		*va = (void *)(vm_offset_t)pa;
3330 		return;
3331 	}
3332 
3333 	/* Raw physical memory dumps don't have a virtual address. */
3334 	/* We always map a 256MB page at 256M. */
3335 	gran = 256 * 1024 * 1024;
3336 	ppa = rounddown2(pa, gran);
3337 	ofs = pa - ppa;
3338 	*va = (void *)gran;
3339 	tlb1_set_entry((vm_offset_t)va, ppa, gran, _TLB_ENTRY_IO);
3340 
3341 	if (sz > (gran - ofs))
3342 		tlb1_set_entry((vm_offset_t)(va + gran), ppa + gran, gran,
3343 		    _TLB_ENTRY_IO);
3344 }
3345 
3346 void
3347 mmu_booke_dumpsys_unmap(mmu_t mmu, vm_paddr_t pa, size_t sz, void *va)
3348 {
3349 	vm_paddr_t ppa;
3350 	vm_offset_t ofs;
3351 	vm_size_t gran;
3352 	tlb_entry_t e;
3353 	int i;
3354 
3355 	/* Minidumps are based on virtual memory addresses. */
3356 	/* Nothing to do... */
3357 	if (do_minidump)
3358 		return;
3359 
3360 	for (i = 0; i < TLB1_ENTRIES; i++) {
3361 		tlb1_read_entry(&e, i);
3362 		if (!(e.mas1 & MAS1_VALID))
3363 			break;
3364 	}
3365 
3366 	/* Raw physical memory dumps don't have a virtual address. */
3367 	i--;
3368 	e.mas1 = 0;
3369 	e.mas2 = 0;
3370 	e.mas3 = 0;
3371 	tlb1_write_entry(&e, i);
3372 
3373 	gran = 256 * 1024 * 1024;
3374 	ppa = rounddown2(pa, gran);
3375 	ofs = pa - ppa;
3376 	if (sz > (gran - ofs)) {
3377 		i--;
3378 		e.mas1 = 0;
3379 		e.mas2 = 0;
3380 		e.mas3 = 0;
3381 		tlb1_write_entry(&e, i);
3382 	}
3383 }
3384 
3385 extern struct dump_pa dump_map[PHYS_AVAIL_SZ + 1];
3386 
3387 void
3388 mmu_booke_scan_init(mmu_t mmu)
3389 {
3390 	vm_offset_t va;
3391 	pte_t *pte;
3392 	int i;
3393 
3394 	if (!do_minidump) {
3395 		/* Initialize phys. segments for dumpsys(). */
3396 		memset(&dump_map, 0, sizeof(dump_map));
3397 		mem_regions(&physmem_regions, &physmem_regions_sz, &availmem_regions,
3398 		    &availmem_regions_sz);
3399 		for (i = 0; i < physmem_regions_sz; i++) {
3400 			dump_map[i].pa_start = physmem_regions[i].mr_start;
3401 			dump_map[i].pa_size = physmem_regions[i].mr_size;
3402 		}
3403 		return;
3404 	}
3405 
3406 	/* Virtual segments for minidumps: */
3407 	memset(&dump_map, 0, sizeof(dump_map));
3408 
3409 	/* 1st: kernel .data and .bss. */
3410 	dump_map[0].pa_start = trunc_page((uintptr_t)_etext);
3411 	dump_map[0].pa_size =
3412 	    round_page((uintptr_t)_end) - dump_map[0].pa_start;
3413 
3414 	/* 2nd: msgbuf and tables (see pmap_bootstrap()). */
3415 	dump_map[1].pa_start = data_start;
3416 	dump_map[1].pa_size = data_end - data_start;
3417 
3418 	/* 3rd: kernel VM. */
3419 	va = dump_map[1].pa_start + dump_map[1].pa_size;
3420 	/* Find start of next chunk (from va). */
3421 	while (va < virtual_end) {
3422 		/* Don't dump the buffer cache. */
3423 		if (va >= kmi.buffer_sva && va < kmi.buffer_eva) {
3424 			va = kmi.buffer_eva;
3425 			continue;
3426 		}
3427 		pte = pte_find(mmu, kernel_pmap, va);
3428 		if (pte != NULL && PTE_ISVALID(pte))
3429 			break;
3430 		va += PAGE_SIZE;
3431 	}
3432 	if (va < virtual_end) {
3433 		dump_map[2].pa_start = va;
3434 		va += PAGE_SIZE;
3435 		/* Find last page in chunk. */
3436 		while (va < virtual_end) {
3437 			/* Don't run into the buffer cache. */
3438 			if (va == kmi.buffer_sva)
3439 				break;
3440 			pte = pte_find(mmu, kernel_pmap, va);
3441 			if (pte == NULL || !PTE_ISVALID(pte))
3442 				break;
3443 			va += PAGE_SIZE;
3444 		}
3445 		dump_map[2].pa_size = va - dump_map[2].pa_start;
3446 	}
3447 }
3448 
3449 /*
3450  * Map a set of physical memory pages into the kernel virtual address space.
3451  * Return a pointer to where it is mapped. This routine is intended to be used
3452  * for mapping device memory, NOT real memory.
3453  */
3454 static void *
3455 mmu_booke_mapdev(mmu_t mmu, vm_paddr_t pa, vm_size_t size)
3456 {
3457 
3458 	return (mmu_booke_mapdev_attr(mmu, pa, size, VM_MEMATTR_DEFAULT));
3459 }
3460 
3461 static void *
3462 mmu_booke_mapdev_attr(mmu_t mmu, vm_paddr_t pa, vm_size_t size, vm_memattr_t ma)
3463 {
3464 	tlb_entry_t e;
3465 	void *res;
3466 	uintptr_t va, tmpva;
3467 	vm_size_t sz;
3468 	int i;
3469 
3470 	/*
3471 	 * Check if this is premapped in TLB1. Note: this should probably also
3472 	 * check whether a sequence of TLB1 entries exist that match the
3473 	 * requirement, but now only checks the easy case.
3474 	 */
3475 	for (i = 0; i < TLB1_ENTRIES; i++) {
3476 		tlb1_read_entry(&e, i);
3477 		if (!(e.mas1 & MAS1_VALID))
3478 			continue;
3479 		if (pa >= e.phys &&
3480 		    (pa + size) <= (e.phys + e.size) &&
3481 		    (ma == VM_MEMATTR_DEFAULT ||
3482 		     tlb_calc_wimg(pa, ma) ==
3483 		      (e.mas2 & (MAS2_WIMGE_MASK & ~_TLB_ENTRY_SHARED))))
3484 			return (void *)(e.virt +
3485 			    (vm_offset_t)(pa - e.phys));
3486 	}
3487 
3488 	size = roundup(size, PAGE_SIZE);
3489 
3490 	/*
3491 	 * The device mapping area is between VM_MAXUSER_ADDRESS and
3492 	 * VM_MIN_KERNEL_ADDRESS.  This gives 1GB of device addressing.
3493 	 */
3494 #ifdef SPARSE_MAPDEV
3495 	/*
3496 	 * With a sparse mapdev, align to the largest starting region.  This
3497 	 * could feasibly be optimized for a 'best-fit' alignment, but that
3498 	 * calculation could be very costly.
3499 	 * Align to the smaller of:
3500 	 * - first set bit in overlap of (pa & size mask)
3501 	 * - largest size envelope
3502 	 *
3503 	 * It's possible the device mapping may start at a PA that's not larger
3504 	 * than the size mask, so we need to offset in to maximize the TLB entry
3505 	 * range and minimize the number of used TLB entries.
3506 	 */
3507 	do {
3508 	    tmpva = tlb1_map_base;
3509 	    sz = ffsl(((1 << flsl(size-1)) - 1) & pa);
3510 	    sz = sz ? min(roundup(sz + 3, 4), flsl(size) - 1) : flsl(size) - 1;
3511 	    va = roundup(tlb1_map_base, 1 << sz) | (((1 << sz) - 1) & pa);
3512 #ifdef __powerpc64__
3513 	} while (!atomic_cmpset_long(&tlb1_map_base, tmpva, va + size));
3514 #else
3515 	} while (!atomic_cmpset_int(&tlb1_map_base, tmpva, va + size));
3516 #endif
3517 #else
3518 #ifdef __powerpc64__
3519 	va = atomic_fetchadd_long(&tlb1_map_base, size);
3520 #else
3521 	va = atomic_fetchadd_int(&tlb1_map_base, size);
3522 #endif
3523 #endif
3524 	res = (void *)va;
3525 
3526 	do {
3527 		sz = 1 << (ilog2(size) & ~1);
3528 		/* Align size to PA */
3529 		if (pa % sz != 0) {
3530 			do {
3531 				sz >>= 2;
3532 			} while (pa % sz != 0);
3533 		}
3534 		/* Now align from there to VA */
3535 		if (va % sz != 0) {
3536 			do {
3537 				sz >>= 2;
3538 			} while (va % sz != 0);
3539 		}
3540 		if (bootverbose)
3541 			printf("Wiring VA=%lx to PA=%jx (size=%lx)\n",
3542 			    va, (uintmax_t)pa, sz);
3543 		if (tlb1_set_entry(va, pa, sz,
3544 		    _TLB_ENTRY_SHARED | tlb_calc_wimg(pa, ma)) < 0)
3545 			return (NULL);
3546 		size -= sz;
3547 		pa += sz;
3548 		va += sz;
3549 	} while (size > 0);
3550 
3551 	return (res);
3552 }
3553 
3554 /*
3555  * 'Unmap' a range mapped by mmu_booke_mapdev().
3556  */
3557 static void
3558 mmu_booke_unmapdev(mmu_t mmu, vm_offset_t va, vm_size_t size)
3559 {
3560 #ifdef SUPPORTS_SHRINKING_TLB1
3561 	vm_offset_t base, offset;
3562 
3563 	/*
3564 	 * Unmap only if this is inside kernel virtual space.
3565 	 */
3566 	if ((va >= VM_MIN_KERNEL_ADDRESS) && (va <= VM_MAX_KERNEL_ADDRESS)) {
3567 		base = trunc_page(va);
3568 		offset = va & PAGE_MASK;
3569 		size = roundup(offset + size, PAGE_SIZE);
3570 		kva_free(base, size);
3571 	}
3572 #endif
3573 }
3574 
3575 /*
3576  * mmu_booke_object_init_pt preloads the ptes for a given object into the
3577  * specified pmap. This eliminates the blast of soft faults on process startup
3578  * and immediately after an mmap.
3579  */
3580 static void
3581 mmu_booke_object_init_pt(mmu_t mmu, pmap_t pmap, vm_offset_t addr,
3582     vm_object_t object, vm_pindex_t pindex, vm_size_t size)
3583 {
3584 
3585 	VM_OBJECT_ASSERT_WLOCKED(object);
3586 	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
3587 	    ("mmu_booke_object_init_pt: non-device object"));
3588 }
3589 
3590 /*
3591  * Perform the pmap work for mincore.
3592  */
3593 static int
3594 mmu_booke_mincore(mmu_t mmu, pmap_t pmap, vm_offset_t addr,
3595     vm_paddr_t *locked_pa)
3596 {
3597 
3598 	/* XXX: this should be implemented at some point */
3599 	return (0);
3600 }
3601 
3602 static int
3603 mmu_booke_change_attr(mmu_t mmu, vm_offset_t addr, vm_size_t sz,
3604     vm_memattr_t mode)
3605 {
3606 	vm_offset_t va;
3607 	pte_t *pte;
3608 	int i, j;
3609 	tlb_entry_t e;
3610 
3611 	/* Check TLB1 mappings */
3612 	for (i = 0; i < TLB1_ENTRIES; i++) {
3613 		tlb1_read_entry(&e, i);
3614 		if (!(e.mas1 & MAS1_VALID))
3615 			continue;
3616 		if (addr >= e.virt && addr < e.virt + e.size)
3617 			break;
3618 	}
3619 	if (i < TLB1_ENTRIES) {
3620 		/* Only allow full mappings to be modified for now. */
3621 		/* Validate the range. */
3622 		for (j = i, va = addr; va < addr + sz; va += e.size, j++) {
3623 			tlb1_read_entry(&e, j);
3624 			if (va != e.virt || (sz - (va - addr) < e.size))
3625 				return (EINVAL);
3626 		}
3627 		for (va = addr; va < addr + sz; va += e.size, i++) {
3628 			tlb1_read_entry(&e, i);
3629 			e.mas2 &= ~MAS2_WIMGE_MASK;
3630 			e.mas2 |= tlb_calc_wimg(e.phys, mode);
3631 
3632 			/*
3633 			 * Write it out to the TLB.  Should really re-sync with other
3634 			 * cores.
3635 			 */
3636 			tlb1_write_entry(&e, i);
3637 		}
3638 		return (0);
3639 	}
3640 
3641 	/* Not in TLB1, try through pmap */
3642 	/* First validate the range. */
3643 	for (va = addr; va < addr + sz; va += PAGE_SIZE) {
3644 		pte = pte_find(mmu, kernel_pmap, va);
3645 		if (pte == NULL || !PTE_ISVALID(pte))
3646 			return (EINVAL);
3647 	}
3648 
3649 	mtx_lock_spin(&tlbivax_mutex);
3650 	tlb_miss_lock();
3651 	for (va = addr; va < addr + sz; va += PAGE_SIZE) {
3652 		pte = pte_find(mmu, kernel_pmap, va);
3653 		*pte &= ~(PTE_MAS2_MASK << PTE_MAS2_SHIFT);
3654 		*pte |= tlb_calc_wimg(PTE_PA(pte), mode) << PTE_MAS2_SHIFT;
3655 		tlb0_flush_entry(va);
3656 	}
3657 	tlb_miss_unlock();
3658 	mtx_unlock_spin(&tlbivax_mutex);
3659 
3660 	return (0);
3661 }
3662 
3663 /**************************************************************************/
3664 /* TID handling */
3665 /**************************************************************************/
3666 
3667 /*
3668  * Allocate a TID. If necessary, steal one from someone else.
3669  * The new TID is flushed from the TLB before returning.
3670  */
3671 static tlbtid_t
3672 tid_alloc(pmap_t pmap)
3673 {
3674 	tlbtid_t tid;
3675 	int thiscpu;
3676 
3677 	KASSERT((pmap != kernel_pmap), ("tid_alloc: kernel pmap"));
3678 
3679 	CTR2(KTR_PMAP, "%s: s (pmap = %p)", __func__, pmap);
3680 
3681 	thiscpu = PCPU_GET(cpuid);
3682 
3683 	tid = PCPU_GET(tid_next);
3684 	if (tid > TID_MAX)
3685 		tid = TID_MIN;
3686 	PCPU_SET(tid_next, tid + 1);
3687 
3688 	/* If we are stealing TID then clear the relevant pmap's field */
3689 	if (tidbusy[thiscpu][tid] != NULL) {
3690 
3691 		CTR2(KTR_PMAP, "%s: warning: stealing tid %d", __func__, tid);
3692 
3693 		tidbusy[thiscpu][tid]->pm_tid[thiscpu] = TID_NONE;
3694 
3695 		/* Flush all entries from TLB0 matching this TID. */
3696 		tid_flush(tid);
3697 	}
3698 
3699 	tidbusy[thiscpu][tid] = pmap;
3700 	pmap->pm_tid[thiscpu] = tid;
3701 	__asm __volatile("msync; isync");
3702 
3703 	CTR3(KTR_PMAP, "%s: e (%02d next = %02d)", __func__, tid,
3704 	    PCPU_GET(tid_next));
3705 
3706 	return (tid);
3707 }
3708 
3709 /**************************************************************************/
3710 /* TLB0 handling */
3711 /**************************************************************************/
3712 
3713 static void
3714 #ifdef __powerpc64__
3715 tlb_print_entry(int i, uint32_t mas1, uint64_t mas2, uint32_t mas3,
3716 #else
3717 tlb_print_entry(int i, uint32_t mas1, uint32_t mas2, uint32_t mas3,
3718 #endif
3719     uint32_t mas7)
3720 {
3721 	int as;
3722 	char desc[3];
3723 	tlbtid_t tid;
3724 	vm_size_t size;
3725 	unsigned int tsize;
3726 
3727 	desc[2] = '\0';
3728 	if (mas1 & MAS1_VALID)
3729 		desc[0] = 'V';
3730 	else
3731 		desc[0] = ' ';
3732 
3733 	if (mas1 & MAS1_IPROT)
3734 		desc[1] = 'P';
3735 	else
3736 		desc[1] = ' ';
3737 
3738 	as = (mas1 & MAS1_TS_MASK) ? 1 : 0;
3739 	tid = MAS1_GETTID(mas1);
3740 
3741 	tsize = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
3742 	size = 0;
3743 	if (tsize)
3744 		size = tsize2size(tsize);
3745 
3746 	debugf("%3d: (%s) [AS=%d] "
3747 	    "sz = 0x%08x tsz = %d tid = %d mas1 = 0x%08x "
3748 	    "mas2(va) = 0x%"PRI0ptrX" mas3(pa) = 0x%08x mas7 = 0x%08x\n",
3749 	    i, desc, as, size, tsize, tid, mas1, mas2, mas3, mas7);
3750 }
3751 
3752 /* Convert TLB0 va and way number to tlb0[] table index. */
3753 static inline unsigned int
3754 tlb0_tableidx(vm_offset_t va, unsigned int way)
3755 {
3756 	unsigned int idx;
3757 
3758 	idx = (way * TLB0_ENTRIES_PER_WAY);
3759 	idx += (va & MAS2_TLB0_ENTRY_IDX_MASK) >> MAS2_TLB0_ENTRY_IDX_SHIFT;
3760 	return (idx);
3761 }
3762 
3763 /*
3764  * Invalidate TLB0 entry.
3765  */
3766 static inline void
3767 tlb0_flush_entry(vm_offset_t va)
3768 {
3769 
3770 	CTR2(KTR_PMAP, "%s: s va=0x%08x", __func__, va);
3771 
3772 	mtx_assert(&tlbivax_mutex, MA_OWNED);
3773 
3774 	__asm __volatile("tlbivax 0, %0" :: "r"(va & MAS2_EPN_MASK));
3775 	__asm __volatile("isync; msync");
3776 	__asm __volatile("tlbsync; msync");
3777 
3778 	CTR1(KTR_PMAP, "%s: e", __func__);
3779 }
3780 
3781 /* Print out contents of the MAS registers for each TLB0 entry */
3782 void
3783 tlb0_print_tlbentries(void)
3784 {
3785 	uint32_t mas0, mas1, mas3, mas7;
3786 #ifdef __powerpc64__
3787 	uint64_t mas2;
3788 #else
3789 	uint32_t mas2;
3790 #endif
3791 	int entryidx, way, idx;
3792 
3793 	debugf("TLB0 entries:\n");
3794 	for (way = 0; way < TLB0_WAYS; way ++)
3795 		for (entryidx = 0; entryidx < TLB0_ENTRIES_PER_WAY; entryidx++) {
3796 
3797 			mas0 = MAS0_TLBSEL(0) | MAS0_ESEL(way);
3798 			mtspr(SPR_MAS0, mas0);
3799 			__asm __volatile("isync");
3800 
3801 			mas2 = entryidx << MAS2_TLB0_ENTRY_IDX_SHIFT;
3802 			mtspr(SPR_MAS2, mas2);
3803 
3804 			__asm __volatile("isync; tlbre");
3805 
3806 			mas1 = mfspr(SPR_MAS1);
3807 			mas2 = mfspr(SPR_MAS2);
3808 			mas3 = mfspr(SPR_MAS3);
3809 			mas7 = mfspr(SPR_MAS7);
3810 
3811 			idx = tlb0_tableidx(mas2, way);
3812 			tlb_print_entry(idx, mas1, mas2, mas3, mas7);
3813 		}
3814 }
3815 
3816 /**************************************************************************/
3817 /* TLB1 handling */
3818 /**************************************************************************/
3819 
3820 /*
3821  * TLB1 mapping notes:
3822  *
3823  * TLB1[0]	Kernel text and data.
3824  * TLB1[1-15]	Additional kernel text and data mappings (if required), PCI
3825  *		windows, other devices mappings.
3826  */
3827 
3828  /*
3829  * Read an entry from given TLB1 slot.
3830  */
3831 void
3832 tlb1_read_entry(tlb_entry_t *entry, unsigned int slot)
3833 {
3834 	register_t msr;
3835 	uint32_t mas0;
3836 
3837 	KASSERT((entry != NULL), ("%s(): Entry is NULL!", __func__));
3838 
3839 	msr = mfmsr();
3840 	__asm __volatile("wrteei 0");
3841 
3842 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(slot);
3843 	mtspr(SPR_MAS0, mas0);
3844 	__asm __volatile("isync; tlbre");
3845 
3846 	entry->mas1 = mfspr(SPR_MAS1);
3847 	entry->mas2 = mfspr(SPR_MAS2);
3848 	entry->mas3 = mfspr(SPR_MAS3);
3849 
3850 	switch ((mfpvr() >> 16) & 0xFFFF) {
3851 	case FSL_E500v2:
3852 	case FSL_E500mc:
3853 	case FSL_E5500:
3854 	case FSL_E6500:
3855 		entry->mas7 = mfspr(SPR_MAS7);
3856 		break;
3857 	default:
3858 		entry->mas7 = 0;
3859 		break;
3860 	}
3861 	mtmsr(msr);
3862 
3863 	entry->virt = entry->mas2 & MAS2_EPN_MASK;
3864 	entry->phys = ((vm_paddr_t)(entry->mas7 & MAS7_RPN) << 32) |
3865 	    (entry->mas3 & MAS3_RPN);
3866 	entry->size =
3867 	    tsize2size((entry->mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT);
3868 }
3869 
3870 /*
3871  * Write given entry to TLB1 hardware.
3872  */
3873 static void
3874 tlb1_write_entry(tlb_entry_t *e, unsigned int idx)
3875 {
3876 	register_t msr;
3877 	uint32_t mas0;
3878 
3879 	//debugf("tlb1_write_entry: s\n");
3880 
3881 	/* Select entry */
3882 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(idx);
3883 	//debugf("tlb1_write_entry: mas0 = 0x%08x\n", mas0);
3884 
3885 	msr = mfmsr();
3886 	__asm __volatile("wrteei 0");
3887 
3888 	mtspr(SPR_MAS0, mas0);
3889 	__asm __volatile("isync");
3890 	mtspr(SPR_MAS1, e->mas1);
3891 	__asm __volatile("isync");
3892 	mtspr(SPR_MAS2, e->mas2);
3893 	__asm __volatile("isync");
3894 	mtspr(SPR_MAS3, e->mas3);
3895 	__asm __volatile("isync");
3896 	switch ((mfpvr() >> 16) & 0xFFFF) {
3897 	case FSL_E500mc:
3898 	case FSL_E5500:
3899 	case FSL_E6500:
3900 		mtspr(SPR_MAS8, 0);
3901 		__asm __volatile("isync");
3902 		/* FALLTHROUGH */
3903 	case FSL_E500v2:
3904 		mtspr(SPR_MAS7, e->mas7);
3905 		__asm __volatile("isync");
3906 		break;
3907 	default:
3908 		break;
3909 	}
3910 
3911 	__asm __volatile("tlbwe; isync; msync");
3912 	mtmsr(msr);
3913 
3914 	//debugf("tlb1_write_entry: e\n");
3915 }
3916 
3917 /*
3918  * Return the largest uint value log such that 2^log <= num.
3919  */
3920 static unsigned int
3921 ilog2(unsigned int num)
3922 {
3923 	int lz;
3924 
3925 	__asm ("cntlzw %0, %1" : "=r" (lz) : "r" (num));
3926 	return (31 - lz);
3927 }
3928 
3929 /*
3930  * Convert TLB TSIZE value to mapped region size.
3931  */
3932 static vm_size_t
3933 tsize2size(unsigned int tsize)
3934 {
3935 
3936 	/*
3937 	 * size = 4^tsize KB
3938 	 * size = 4^tsize * 2^10 = 2^(2 * tsize - 10)
3939 	 */
3940 
3941 	return ((1 << (2 * tsize)) * 1024);
3942 }
3943 
3944 /*
3945  * Convert region size (must be power of 4) to TLB TSIZE value.
3946  */
3947 static unsigned int
3948 size2tsize(vm_size_t size)
3949 {
3950 
3951 	return (ilog2(size) / 2 - 5);
3952 }
3953 
3954 /*
3955  * Register permanent kernel mapping in TLB1.
3956  *
3957  * Entries are created starting from index 0 (current free entry is
3958  * kept in tlb1_idx) and are not supposed to be invalidated.
3959  */
3960 int
3961 tlb1_set_entry(vm_offset_t va, vm_paddr_t pa, vm_size_t size,
3962     uint32_t flags)
3963 {
3964 	tlb_entry_t e;
3965 	uint32_t ts, tid;
3966 	int tsize, index;
3967 
3968 	for (index = 0; index < TLB1_ENTRIES; index++) {
3969 		tlb1_read_entry(&e, index);
3970 		if ((e.mas1 & MAS1_VALID) == 0)
3971 			break;
3972 		/* Check if we're just updating the flags, and update them. */
3973 		if (e.phys == pa && e.virt == va && e.size == size) {
3974 			e.mas2 = (va & MAS2_EPN_MASK) | flags;
3975 			tlb1_write_entry(&e, index);
3976 			return (0);
3977 		}
3978 	}
3979 	if (index >= TLB1_ENTRIES) {
3980 		printf("tlb1_set_entry: TLB1 full!\n");
3981 		return (-1);
3982 	}
3983 
3984 	/* Convert size to TSIZE */
3985 	tsize = size2tsize(size);
3986 
3987 	tid = (TID_KERNEL << MAS1_TID_SHIFT) & MAS1_TID_MASK;
3988 	/* XXX TS is hard coded to 0 for now as we only use single address space */
3989 	ts = (0 << MAS1_TS_SHIFT) & MAS1_TS_MASK;
3990 
3991 	e.phys = pa;
3992 	e.virt = va;
3993 	e.size = size;
3994 	e.mas1 = MAS1_VALID | MAS1_IPROT | ts | tid;
3995 	e.mas1 |= ((tsize << MAS1_TSIZE_SHIFT) & MAS1_TSIZE_MASK);
3996 	e.mas2 = (va & MAS2_EPN_MASK) | flags;
3997 
3998 	/* Set supervisor RWX permission bits */
3999 	e.mas3 = (pa & MAS3_RPN) | MAS3_SR | MAS3_SW | MAS3_SX;
4000 	e.mas7 = (pa >> 32) & MAS7_RPN;
4001 
4002 	tlb1_write_entry(&e, index);
4003 
4004 	/*
4005 	 * XXX in general TLB1 updates should be propagated between CPUs,
4006 	 * since current design assumes to have the same TLB1 set-up on all
4007 	 * cores.
4008 	 */
4009 	return (0);
4010 }
4011 
4012 /*
4013  * Map in contiguous RAM region into the TLB1 using maximum of
4014  * KERNEL_REGION_MAX_TLB_ENTRIES entries.
4015  *
4016  * If necessary round up last entry size and return total size
4017  * used by all allocated entries.
4018  */
4019 vm_size_t
4020 tlb1_mapin_region(vm_offset_t va, vm_paddr_t pa, vm_size_t size)
4021 {
4022 	vm_size_t pgs[KERNEL_REGION_MAX_TLB_ENTRIES];
4023 	vm_size_t mapped, pgsz, base, mask;
4024 	int idx, nents;
4025 
4026 	/* Round up to the next 1M */
4027 	size = roundup2(size, 1 << 20);
4028 
4029 	mapped = 0;
4030 	idx = 0;
4031 	base = va;
4032 	pgsz = 64*1024*1024;
4033 	while (mapped < size) {
4034 		while (mapped < size && idx < KERNEL_REGION_MAX_TLB_ENTRIES) {
4035 			while (pgsz > (size - mapped))
4036 				pgsz >>= 2;
4037 			pgs[idx++] = pgsz;
4038 			mapped += pgsz;
4039 		}
4040 
4041 		/* We under-map. Correct for this. */
4042 		if (mapped < size) {
4043 			while (pgs[idx - 1] == pgsz) {
4044 				idx--;
4045 				mapped -= pgsz;
4046 			}
4047 			/* XXX We may increase beyond out starting point. */
4048 			pgsz <<= 2;
4049 			pgs[idx++] = pgsz;
4050 			mapped += pgsz;
4051 		}
4052 	}
4053 
4054 	nents = idx;
4055 	mask = pgs[0] - 1;
4056 	/* Align address to the boundary */
4057 	if (va & mask) {
4058 		va = (va + mask) & ~mask;
4059 		pa = (pa + mask) & ~mask;
4060 	}
4061 
4062 	for (idx = 0; idx < nents; idx++) {
4063 		pgsz = pgs[idx];
4064 		debugf("%u: %llx -> %x, size=%x\n", idx, pa, va, pgsz);
4065 		tlb1_set_entry(va, pa, pgsz,
4066 		    _TLB_ENTRY_SHARED | _TLB_ENTRY_MEM);
4067 		pa += pgsz;
4068 		va += pgsz;
4069 	}
4070 
4071 	mapped = (va - base);
4072 	printf("mapped size 0x%"PRI0ptrX" (wasted space 0x%"PRIxPTR")\n",
4073 	    mapped, mapped - size);
4074 	return (mapped);
4075 }
4076 
4077 /*
4078  * TLB1 initialization routine, to be called after the very first
4079  * assembler level setup done in locore.S.
4080  */
4081 void
4082 tlb1_init()
4083 {
4084 	uint32_t mas0, mas1, mas2, mas3, mas7;
4085 	uint32_t tsz;
4086 
4087 	tlb1_get_tlbconf();
4088 
4089 	mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(0);
4090 	mtspr(SPR_MAS0, mas0);
4091 	__asm __volatile("isync; tlbre");
4092 
4093 	mas1 = mfspr(SPR_MAS1);
4094 	mas2 = mfspr(SPR_MAS2);
4095 	mas3 = mfspr(SPR_MAS3);
4096 	mas7 = mfspr(SPR_MAS7);
4097 
4098 	kernload =  ((vm_paddr_t)(mas7 & MAS7_RPN) << 32) |
4099 	    (mas3 & MAS3_RPN);
4100 
4101 	tsz = (mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
4102 	kernsize += (tsz > 0) ? tsize2size(tsz) : 0;
4103 
4104 	/* Setup TLB miss defaults */
4105 	set_mas4_defaults();
4106 }
4107 
4108 /*
4109  * pmap_early_io_unmap() should be used in short conjunction with
4110  * pmap_early_io_map(), as in the following snippet:
4111  *
4112  * x = pmap_early_io_map(...);
4113  * <do something with x>
4114  * pmap_early_io_unmap(x, size);
4115  *
4116  * And avoiding more allocations between.
4117  */
4118 void
4119 pmap_early_io_unmap(vm_offset_t va, vm_size_t size)
4120 {
4121 	int i;
4122 	tlb_entry_t e;
4123 	vm_size_t isize;
4124 
4125 	size = roundup(size, PAGE_SIZE);
4126 	isize = size;
4127 	for (i = 0; i < TLB1_ENTRIES && size > 0; i++) {
4128 		tlb1_read_entry(&e, i);
4129 		if (!(e.mas1 & MAS1_VALID))
4130 			continue;
4131 		if (va <= e.virt && (va + isize) >= (e.virt + e.size)) {
4132 			size -= e.size;
4133 			e.mas1 &= ~MAS1_VALID;
4134 			tlb1_write_entry(&e, i);
4135 		}
4136 	}
4137 	if (tlb1_map_base == va + isize)
4138 		tlb1_map_base -= isize;
4139 }
4140 
4141 vm_offset_t
4142 pmap_early_io_map(vm_paddr_t pa, vm_size_t size)
4143 {
4144 	vm_paddr_t pa_base;
4145 	vm_offset_t va, sz;
4146 	int i;
4147 	tlb_entry_t e;
4148 
4149 	KASSERT(!pmap_bootstrapped, ("Do not use after PMAP is up!"));
4150 
4151 	for (i = 0; i < TLB1_ENTRIES; i++) {
4152 		tlb1_read_entry(&e, i);
4153 		if (!(e.mas1 & MAS1_VALID))
4154 			continue;
4155 		if (pa >= e.phys && (pa + size) <=
4156 		    (e.phys + e.size))
4157 			return (e.virt + (pa - e.phys));
4158 	}
4159 
4160 	pa_base = rounddown(pa, PAGE_SIZE);
4161 	size = roundup(size + (pa - pa_base), PAGE_SIZE);
4162 	tlb1_map_base = roundup2(tlb1_map_base, 1 << (ilog2(size) & ~1));
4163 	va = tlb1_map_base + (pa - pa_base);
4164 
4165 	do {
4166 		sz = 1 << (ilog2(size) & ~1);
4167 		tlb1_set_entry(tlb1_map_base, pa_base, sz,
4168 		    _TLB_ENTRY_SHARED | _TLB_ENTRY_IO);
4169 		size -= sz;
4170 		pa_base += sz;
4171 		tlb1_map_base += sz;
4172 	} while (size > 0);
4173 
4174 	return (va);
4175 }
4176 
4177 void
4178 pmap_track_page(pmap_t pmap, vm_offset_t va)
4179 {
4180 	vm_paddr_t pa;
4181 	vm_page_t page;
4182 	struct pv_entry *pve;
4183 
4184 	va = trunc_page(va);
4185 	pa = pmap_kextract(va);
4186 
4187 	rw_wlock(&pvh_global_lock);
4188 	PMAP_LOCK(pmap);
4189 	page = PHYS_TO_VM_PAGE(pa);
4190 
4191 	TAILQ_FOREACH(pve, &page->md.pv_list, pv_link) {
4192 		if ((pmap == pve->pv_pmap) && (va == pve->pv_va)) {
4193 			goto out;
4194 		}
4195 	}
4196 	page->md.pv_tracked = true;
4197 	pv_insert(pmap, va, page);
4198 out:
4199 	PMAP_UNLOCK(pmap);
4200 	rw_wunlock(&pvh_global_lock);
4201 }
4202 
4203 
4204 /*
4205  * Setup MAS4 defaults.
4206  * These values are loaded to MAS0-2 on a TLB miss.
4207  */
4208 static void
4209 set_mas4_defaults(void)
4210 {
4211 	uint32_t mas4;
4212 
4213 	/* Defaults: TLB0, PID0, TSIZED=4K */
4214 	mas4 = MAS4_TLBSELD0;
4215 	mas4 |= (TLB_SIZE_4K << MAS4_TSIZED_SHIFT) & MAS4_TSIZED_MASK;
4216 #ifdef SMP
4217 	mas4 |= MAS4_MD;
4218 #endif
4219 	mtspr(SPR_MAS4, mas4);
4220 	__asm __volatile("isync");
4221 }
4222 
4223 /*
4224  * Print out contents of the MAS registers for each TLB1 entry
4225  */
4226 void
4227 tlb1_print_tlbentries(void)
4228 {
4229 	uint32_t mas0, mas1, mas3, mas7;
4230 #ifdef __powerpc64__
4231 	uint64_t mas2;
4232 #else
4233 	uint32_t mas2;
4234 #endif
4235 	int i;
4236 
4237 	debugf("TLB1 entries:\n");
4238 	for (i = 0; i < TLB1_ENTRIES; i++) {
4239 
4240 		mas0 = MAS0_TLBSEL(1) | MAS0_ESEL(i);
4241 		mtspr(SPR_MAS0, mas0);
4242 
4243 		__asm __volatile("isync; tlbre");
4244 
4245 		mas1 = mfspr(SPR_MAS1);
4246 		mas2 = mfspr(SPR_MAS2);
4247 		mas3 = mfspr(SPR_MAS3);
4248 		mas7 = mfspr(SPR_MAS7);
4249 
4250 		tlb_print_entry(i, mas1, mas2, mas3, mas7);
4251 	}
4252 }
4253 
4254 /*
4255  * Return 0 if the physical IO range is encompassed by one of the
4256  * the TLB1 entries, otherwise return related error code.
4257  */
4258 static int
4259 tlb1_iomapped(int i, vm_paddr_t pa, vm_size_t size, vm_offset_t *va)
4260 {
4261 	uint32_t prot;
4262 	vm_paddr_t pa_start;
4263 	vm_paddr_t pa_end;
4264 	unsigned int entry_tsize;
4265 	vm_size_t entry_size;
4266 	tlb_entry_t e;
4267 
4268 	*va = (vm_offset_t)NULL;
4269 
4270 	tlb1_read_entry(&e, i);
4271 	/* Skip invalid entries */
4272 	if (!(e.mas1 & MAS1_VALID))
4273 		return (EINVAL);
4274 
4275 	/*
4276 	 * The entry must be cache-inhibited, guarded, and r/w
4277 	 * so it can function as an i/o page
4278 	 */
4279 	prot = e.mas2 & (MAS2_I | MAS2_G);
4280 	if (prot != (MAS2_I | MAS2_G))
4281 		return (EPERM);
4282 
4283 	prot = e.mas3 & (MAS3_SR | MAS3_SW);
4284 	if (prot != (MAS3_SR | MAS3_SW))
4285 		return (EPERM);
4286 
4287 	/* The address should be within the entry range. */
4288 	entry_tsize = (e.mas1 & MAS1_TSIZE_MASK) >> MAS1_TSIZE_SHIFT;
4289 	KASSERT((entry_tsize), ("tlb1_iomapped: invalid entry tsize"));
4290 
4291 	entry_size = tsize2size(entry_tsize);
4292 	pa_start = (((vm_paddr_t)e.mas7 & MAS7_RPN) << 32) |
4293 	    (e.mas3 & MAS3_RPN);
4294 	pa_end = pa_start + entry_size;
4295 
4296 	if ((pa < pa_start) || ((pa + size) > pa_end))
4297 		return (ERANGE);
4298 
4299 	/* Return virtual address of this mapping. */
4300 	*va = (e.mas2 & MAS2_EPN_MASK) + (pa - pa_start);
4301 	return (0);
4302 }
4303 
4304 /*
4305  * Invalidate all TLB0 entries which match the given TID. Note this is
4306  * dedicated for cases when invalidations should NOT be propagated to other
4307  * CPUs.
4308  */
4309 static void
4310 tid_flush(tlbtid_t tid)
4311 {
4312 	register_t msr;
4313 	uint32_t mas0, mas1, mas2;
4314 	int entry, way;
4315 
4316 
4317 	/* Don't evict kernel translations */
4318 	if (tid == TID_KERNEL)
4319 		return;
4320 
4321 	msr = mfmsr();
4322 	__asm __volatile("wrteei 0");
4323 
4324 	for (way = 0; way < TLB0_WAYS; way++)
4325 		for (entry = 0; entry < TLB0_ENTRIES_PER_WAY; entry++) {
4326 
4327 			mas0 = MAS0_TLBSEL(0) | MAS0_ESEL(way);
4328 			mtspr(SPR_MAS0, mas0);
4329 			__asm __volatile("isync");
4330 
4331 			mas2 = entry << MAS2_TLB0_ENTRY_IDX_SHIFT;
4332 			mtspr(SPR_MAS2, mas2);
4333 
4334 			__asm __volatile("isync; tlbre");
4335 
4336 			mas1 = mfspr(SPR_MAS1);
4337 
4338 			if (!(mas1 & MAS1_VALID))
4339 				continue;
4340 			if (((mas1 & MAS1_TID_MASK) >> MAS1_TID_SHIFT) != tid)
4341 				continue;
4342 			mas1 &= ~MAS1_VALID;
4343 			mtspr(SPR_MAS1, mas1);
4344 			__asm __volatile("isync; tlbwe; isync; msync");
4345 		}
4346 	mtmsr(msr);
4347 }
4348