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