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