xref: /netbsd-src/sys/arch/arm/arm32/pmap.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: pmap.c,v 1.157 2005/12/24 20:06:47 perry Exp $	*/
2 
3 /*
4  * Copyright 2003 Wasabi Systems, Inc.
5  * All rights reserved.
6  *
7  * Written by Steve C. Woodford for Wasabi Systems, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed for the NetBSD Project by
20  *      Wasabi Systems, Inc.
21  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
22  *    or promote products derived from this software without specific prior
23  *    written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35  * POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 /*
39  * Copyright (c) 2002-2003 Wasabi Systems, Inc.
40  * Copyright (c) 2001 Richard Earnshaw
41  * Copyright (c) 2001-2002 Christopher Gilbert
42  * All rights reserved.
43  *
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. The name of the company nor the name of the author may be used to
50  *    endorse or promote products derived from this software without specific
51  *    prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
54  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
55  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
56  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
57  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
58  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
59  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  */
65 
66 /*-
67  * Copyright (c) 1999 The NetBSD Foundation, Inc.
68  * All rights reserved.
69  *
70  * This code is derived from software contributed to The NetBSD Foundation
71  * by Charles M. Hannum.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *        This product includes software developed by the NetBSD
84  *        Foundation, Inc. and its contributors.
85  * 4. Neither the name of The NetBSD Foundation nor the names of its
86  *    contributors may be used to endorse or promote products derived
87  *    from this software without specific prior written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
90  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
91  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
92  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
93  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
94  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
95  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
96  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
97  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
98  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
99  * POSSIBILITY OF SUCH DAMAGE.
100  */
101 
102 /*
103  * Copyright (c) 1994-1998 Mark Brinicombe.
104  * Copyright (c) 1994 Brini.
105  * All rights reserved.
106  *
107  * This code is derived from software written for Brini by Mark Brinicombe
108  *
109  * Redistribution and use in source and binary forms, with or without
110  * modification, are permitted provided that the following conditions
111  * are met:
112  * 1. Redistributions of source code must retain the above copyright
113  *    notice, this list of conditions and the following disclaimer.
114  * 2. Redistributions in binary form must reproduce the above copyright
115  *    notice, this list of conditions and the following disclaimer in the
116  *    documentation and/or other materials provided with the distribution.
117  * 3. All advertising materials mentioning features or use of this software
118  *    must display the following acknowledgement:
119  *	This product includes software developed by Mark Brinicombe.
120  * 4. The name of the author may not be used to endorse or promote products
121  *    derived from this software without specific prior written permission.
122  *
123  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
124  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
125  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
126  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
127  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
128  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
129  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
130  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
131  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
132  *
133  * RiscBSD kernel project
134  *
135  * pmap.c
136  *
137  * Machine dependant vm stuff
138  *
139  * Created      : 20/09/94
140  */
141 
142 /*
143  * Performance improvements, UVM changes, overhauls and part-rewrites
144  * were contributed by Neil A. Carson <neil@causality.com>.
145  */
146 
147 /*
148  * Overhauled again to speedup the pmap, use MMU Domains so that L1 tables
149  * can be shared, and re-work the KVM layout, by Steve Woodford of Wasabi
150  * Systems, Inc.
151  *
152  * There are still a few things outstanding at this time:
153  *
154  *   - There are some unresolved issues for MP systems:
155  *
156  *     o The L1 metadata needs a lock, or more specifically, some places
157  *       need to acquire an exclusive lock when modifying L1 translation
158  *       table entries.
159  *
160  *     o When one cpu modifies an L1 entry, and that L1 table is also
161  *       being used by another cpu, then the latter will need to be told
162  *       that a tlb invalidation may be necessary. (But only if the old
163  *       domain number in the L1 entry being over-written is currently
164  *       the active domain on that cpu). I guess there are lots more tlb
165  *       shootdown issues too...
166  *
167  *     o If the vector_page is at 0x00000000 instead of 0xffff0000, then
168  *       MP systems will lose big-time because of the MMU domain hack.
169  *       The only way this can be solved (apart from moving the vector
170  *       page to 0xffff0000) is to reserve the first 1MB of user address
171  *       space for kernel use only. This would require re-linking all
172  *       applications so that the text section starts above this 1MB
173  *       boundary.
174  *
175  *     o Tracking which VM space is resident in the cache/tlb has not yet
176  *       been implemented for MP systems.
177  *
178  *     o Finally, there is a pathological condition where two cpus running
179  *       two separate processes (not lwps) which happen to share an L1
180  *       can get into a fight over one or more L1 entries. This will result
181  *       in a significant slow-down if both processes are in tight loops.
182  */
183 
184 /*
185  * Special compilation symbols
186  * PMAP_DEBUG		- Build in pmap_debug_level code
187  */
188 
189 /* Include header files */
190 
191 #include "opt_cpuoptions.h"
192 #include "opt_pmap_debug.h"
193 #include "opt_ddb.h"
194 #include "opt_lockdebug.h"
195 #include "opt_multiprocessor.h"
196 
197 #include <sys/types.h>
198 #include <sys/param.h>
199 #include <sys/kernel.h>
200 #include <sys/systm.h>
201 #include <sys/proc.h>
202 #include <sys/malloc.h>
203 #include <sys/user.h>
204 #include <sys/pool.h>
205 #include <sys/cdefs.h>
206 
207 #include <uvm/uvm.h>
208 
209 #include <machine/bus.h>
210 #include <machine/pmap.h>
211 #include <machine/pcb.h>
212 #include <machine/param.h>
213 #include <arm/arm32/katelib.h>
214 
215 __KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.157 2005/12/24 20:06:47 perry Exp $");
216 
217 #ifdef PMAP_DEBUG
218 
219 /* XXX need to get rid of all refs to this */
220 int pmap_debug_level = 0;
221 
222 /*
223  * for switching to potentially finer grained debugging
224  */
225 #define	PDB_FOLLOW	0x0001
226 #define	PDB_INIT	0x0002
227 #define	PDB_ENTER	0x0004
228 #define	PDB_REMOVE	0x0008
229 #define	PDB_CREATE	0x0010
230 #define	PDB_PTPAGE	0x0020
231 #define	PDB_GROWKERN	0x0040
232 #define	PDB_BITS	0x0080
233 #define	PDB_COLLECT	0x0100
234 #define	PDB_PROTECT	0x0200
235 #define	PDB_MAP_L1	0x0400
236 #define	PDB_BOOTSTRAP	0x1000
237 #define	PDB_PARANOIA	0x2000
238 #define	PDB_WIRING	0x4000
239 #define	PDB_PVDUMP	0x8000
240 #define	PDB_VAC		0x10000
241 #define	PDB_KENTER	0x20000
242 #define	PDB_KREMOVE	0x40000
243 
244 int debugmap = 1;
245 int pmapdebug = 0;
246 #define	NPDEBUG(_lev_,_stat_) \
247 	if (pmapdebug & (_lev_)) \
248         	((_stat_))
249 
250 #else	/* PMAP_DEBUG */
251 #define NPDEBUG(_lev_,_stat_) /* Nothing */
252 #endif	/* PMAP_DEBUG */
253 
254 /*
255  * pmap_kernel() points here
256  */
257 struct pmap     kernel_pmap_store;
258 
259 /*
260  * Which pmap is currently 'live' in the cache
261  *
262  * XXXSCW: Fix for SMP ...
263  */
264 union pmap_cache_state *pmap_cache_state;
265 
266 /*
267  * Pool and cache that pmap structures are allocated from.
268  * We use a cache to avoid clearing the pm_l2[] array (1KB)
269  * in pmap_create().
270  */
271 static struct pool pmap_pmap_pool;
272 static struct pool_cache pmap_pmap_cache;
273 static LIST_HEAD(, pmap) pmap_pmaps;
274 
275 /*
276  * Pool of PV structures
277  */
278 static struct pool pmap_pv_pool;
279 static void *pmap_bootstrap_pv_page_alloc(struct pool *, int);
280 static void pmap_bootstrap_pv_page_free(struct pool *, void *);
281 static struct pool_allocator pmap_bootstrap_pv_allocator = {
282 	pmap_bootstrap_pv_page_alloc, pmap_bootstrap_pv_page_free
283 };
284 
285 /*
286  * Pool and cache of l2_dtable structures.
287  * We use a cache to avoid clearing the structures when they're
288  * allocated. (196 bytes)
289  */
290 static struct pool pmap_l2dtable_pool;
291 static struct pool_cache pmap_l2dtable_cache;
292 static vaddr_t pmap_kernel_l2dtable_kva;
293 
294 /*
295  * Pool and cache of L2 page descriptors.
296  * We use a cache to avoid clearing the descriptor table
297  * when they're allocated. (1KB)
298  */
299 static struct pool pmap_l2ptp_pool;
300 static struct pool_cache pmap_l2ptp_cache;
301 static vaddr_t pmap_kernel_l2ptp_kva;
302 static paddr_t pmap_kernel_l2ptp_phys;
303 
304 /*
305  * pmap copy/zero page, and mem(5) hook point
306  */
307 static pt_entry_t *csrc_pte, *cdst_pte;
308 static vaddr_t csrcp, cdstp;
309 char *memhook;
310 extern caddr_t msgbufaddr;
311 
312 /*
313  * Flag to indicate if pmap_init() has done its thing
314  */
315 boolean_t pmap_initialized;
316 
317 /*
318  * Misc. locking data structures
319  */
320 
321 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
322 static struct lock pmap_main_lock;
323 
324 #define PMAP_MAP_TO_HEAD_LOCK() \
325      (void) spinlockmgr(&pmap_main_lock, LK_SHARED, NULL)
326 #define PMAP_MAP_TO_HEAD_UNLOCK() \
327      (void) spinlockmgr(&pmap_main_lock, LK_RELEASE, NULL)
328 #define PMAP_HEAD_TO_MAP_LOCK() \
329      (void) spinlockmgr(&pmap_main_lock, LK_EXCLUSIVE, NULL)
330 #define PMAP_HEAD_TO_MAP_UNLOCK() \
331      spinlockmgr(&pmap_main_lock, LK_RELEASE, (void *) 0)
332 #else
333 #define PMAP_MAP_TO_HEAD_LOCK()		/* null */
334 #define PMAP_MAP_TO_HEAD_UNLOCK()	/* null */
335 #define PMAP_HEAD_TO_MAP_LOCK()		/* null */
336 #define PMAP_HEAD_TO_MAP_UNLOCK()	/* null */
337 #endif
338 
339 #define	pmap_acquire_pmap_lock(pm)			\
340 	do {						\
341 		if ((pm) != pmap_kernel())		\
342 			simple_lock(&(pm)->pm_lock);	\
343 	} while (/*CONSTCOND*/0)
344 
345 #define	pmap_release_pmap_lock(pm)			\
346 	do {						\
347 		if ((pm) != pmap_kernel())		\
348 			simple_unlock(&(pm)->pm_lock);	\
349 	} while (/*CONSTCOND*/0)
350 
351 
352 /*
353  * Metadata for L1 translation tables.
354  */
355 struct l1_ttable {
356 	/* Entry on the L1 Table list */
357 	SLIST_ENTRY(l1_ttable) l1_link;
358 
359 	/* Entry on the L1 Least Recently Used list */
360 	TAILQ_ENTRY(l1_ttable) l1_lru;
361 
362 	/* Track how many domains are allocated from this L1 */
363 	volatile u_int l1_domain_use_count;
364 
365 	/*
366 	 * A free-list of domain numbers for this L1.
367 	 * We avoid using ffs() and a bitmap to track domains since ffs()
368 	 * is slow on ARM.
369 	 */
370 	u_int8_t l1_domain_first;
371 	u_int8_t l1_domain_free[PMAP_DOMAINS];
372 
373 	/* Physical address of this L1 page table */
374 	paddr_t l1_physaddr;
375 
376 	/* KVA of this L1 page table */
377 	pd_entry_t *l1_kva;
378 };
379 
380 /*
381  * Convert a virtual address into its L1 table index. That is, the
382  * index used to locate the L2 descriptor table pointer in an L1 table.
383  * This is basically used to index l1->l1_kva[].
384  *
385  * Each L2 descriptor table represents 1MB of VA space.
386  */
387 #define	L1_IDX(va)		(((vaddr_t)(va)) >> L1_S_SHIFT)
388 
389 /*
390  * L1 Page Tables are tracked using a Least Recently Used list.
391  *  - New L1s are allocated from the HEAD.
392  *  - Freed L1s are added to the TAIl.
393  *  - Recently accessed L1s (where an 'access' is some change to one of
394  *    the userland pmaps which owns this L1) are moved to the TAIL.
395  */
396 static TAILQ_HEAD(, l1_ttable) l1_lru_list;
397 static struct simplelock l1_lru_lock;
398 
399 /*
400  * A list of all L1 tables
401  */
402 static SLIST_HEAD(, l1_ttable) l1_list;
403 
404 /*
405  * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
406  *
407  * This is normally 16MB worth L2 page descriptors for any given pmap.
408  * Reference counts are maintained for L2 descriptors so they can be
409  * freed when empty.
410  */
411 struct l2_dtable {
412 	/* The number of L2 page descriptors allocated to this l2_dtable */
413 	u_int l2_occupancy;
414 
415 	/* List of L2 page descriptors */
416 	struct l2_bucket {
417 		pt_entry_t *l2b_kva;	/* KVA of L2 Descriptor Table */
418 		paddr_t l2b_phys;	/* Physical address of same */
419 		u_short l2b_l1idx;	/* This L2 table's L1 index */
420 		u_short l2b_occupancy;	/* How many active descriptors */
421 	} l2_bucket[L2_BUCKET_SIZE];
422 };
423 
424 /*
425  * Given an L1 table index, calculate the corresponding l2_dtable index
426  * and bucket index within the l2_dtable.
427  */
428 #define	L2_IDX(l1idx)		(((l1idx) >> L2_BUCKET_LOG2) & \
429 				 (L2_SIZE - 1))
430 #define	L2_BUCKET(l1idx)	((l1idx) & (L2_BUCKET_SIZE - 1))
431 
432 /*
433  * Given a virtual address, this macro returns the
434  * virtual address required to drop into the next L2 bucket.
435  */
436 #define	L2_NEXT_BUCKET(va)	(((va) & L1_S_FRAME) + L1_S_SIZE)
437 
438 /*
439  * L2 allocation.
440  */
441 #define	pmap_alloc_l2_dtable()		\
442 	    pool_cache_get(&pmap_l2dtable_cache, PR_NOWAIT)
443 #define	pmap_free_l2_dtable(l2)		\
444 	    pool_cache_put(&pmap_l2dtable_cache, (l2))
445 #define pmap_alloc_l2_ptp(pap)		\
446 	    ((pt_entry_t *)pool_cache_get_paddr(&pmap_l2ptp_cache,\
447 	    PR_NOWAIT, (pap)))
448 
449 /*
450  * We try to map the page tables write-through, if possible.  However, not
451  * all CPUs have a write-through cache mode, so on those we have to sync
452  * the cache when we frob page tables.
453  *
454  * We try to evaluate this at compile time, if possible.  However, it's
455  * not always possible to do that, hence this run-time var.
456  */
457 int	pmap_needs_pte_sync;
458 
459 /*
460  * Real definition of pv_entry.
461  */
462 struct pv_entry {
463 	struct pv_entry *pv_next;       /* next pv_entry */
464 	pmap_t		pv_pmap;        /* pmap where mapping lies */
465 	vaddr_t		pv_va;          /* virtual address for mapping */
466 	u_int		pv_flags;       /* flags */
467 };
468 
469 /*
470  * Macro to determine if a mapping might be resident in the
471  * instruction cache and/or TLB
472  */
473 #define	PV_BEEN_EXECD(f)  (((f) & (PVF_REF | PVF_EXEC)) == (PVF_REF | PVF_EXEC))
474 
475 /*
476  * Macro to determine if a mapping might be resident in the
477  * data cache and/or TLB
478  */
479 #define	PV_BEEN_REFD(f)   (((f) & PVF_REF) != 0)
480 
481 /*
482  * Local prototypes
483  */
484 static int		pmap_set_pt_cache_mode(pd_entry_t *, vaddr_t);
485 static void		pmap_alloc_specials(vaddr_t *, int, vaddr_t *,
486 			    pt_entry_t **);
487 static boolean_t	pmap_is_current(pmap_t);
488 static boolean_t	pmap_is_cached(pmap_t);
489 static void		pmap_enter_pv(struct vm_page *, struct pv_entry *,
490 			    pmap_t, vaddr_t, u_int);
491 static struct pv_entry *pmap_find_pv(struct vm_page *, pmap_t, vaddr_t);
492 static struct pv_entry *pmap_remove_pv(struct vm_page *, pmap_t, vaddr_t, int);
493 static u_int		pmap_modify_pv(struct vm_page *, pmap_t, vaddr_t,
494 			    u_int, u_int);
495 
496 static void		pmap_pinit(pmap_t);
497 static int		pmap_pmap_ctor(void *, void *, int);
498 
499 static void		pmap_alloc_l1(pmap_t);
500 static void		pmap_free_l1(pmap_t);
501 static void		pmap_use_l1(pmap_t);
502 
503 static struct l2_bucket *pmap_get_l2_bucket(pmap_t, vaddr_t);
504 static struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vaddr_t);
505 static void		pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
506 static int		pmap_l2ptp_ctor(void *, void *, int);
507 static int		pmap_l2dtable_ctor(void *, void *, int);
508 
509 static void		pmap_vac_me_harder(struct vm_page *, pmap_t, vaddr_t);
510 static void		pmap_vac_me_kpmap(struct vm_page *, pmap_t, vaddr_t);
511 static void		pmap_vac_me_user(struct vm_page *, pmap_t, vaddr_t);
512 
513 static void		pmap_clearbit(struct vm_page *, u_int);
514 static int		pmap_clean_page(struct pv_entry *, boolean_t);
515 static void		pmap_page_remove(struct vm_page *);
516 
517 static void		pmap_init_l1(struct l1_ttable *, pd_entry_t *);
518 static vaddr_t		kernel_pt_lookup(paddr_t);
519 
520 
521 /*
522  * External function prototypes
523  */
524 extern void bzero_page(vaddr_t);
525 extern void bcopy_page(vaddr_t, vaddr_t);
526 
527 /*
528  * Misc variables
529  */
530 vaddr_t virtual_avail;
531 vaddr_t virtual_end;
532 vaddr_t pmap_curmaxkvaddr;
533 
534 vaddr_t avail_start;
535 vaddr_t avail_end;
536 
537 extern pv_addr_t systempage;
538 
539 /* Function to set the debug level of the pmap code */
540 
541 #ifdef PMAP_DEBUG
542 void
543 pmap_debug(int level)
544 {
545 	pmap_debug_level = level;
546 	printf("pmap_debug: level=%d\n", pmap_debug_level);
547 }
548 #endif	/* PMAP_DEBUG */
549 
550 /*
551  * A bunch of routines to conditionally flush the caches/TLB depending
552  * on whether the specified pmap actually needs to be flushed at any
553  * given time.
554  */
555 static inline void
556 pmap_tlb_flushID_SE(pmap_t pm, vaddr_t va)
557 {
558 
559 	if (pm->pm_cstate.cs_tlb_id)
560 		cpu_tlb_flushID_SE(va);
561 }
562 
563 static inline void
564 pmap_tlb_flushD_SE(pmap_t pm, vaddr_t va)
565 {
566 
567 	if (pm->pm_cstate.cs_tlb_d)
568 		cpu_tlb_flushD_SE(va);
569 }
570 
571 static inline void
572 pmap_tlb_flushID(pmap_t pm)
573 {
574 
575 	if (pm->pm_cstate.cs_tlb_id) {
576 		cpu_tlb_flushID();
577 		pm->pm_cstate.cs_tlb = 0;
578 	}
579 }
580 
581 static inline void
582 pmap_tlb_flushD(pmap_t pm)
583 {
584 
585 	if (pm->pm_cstate.cs_tlb_d) {
586 		cpu_tlb_flushD();
587 		pm->pm_cstate.cs_tlb_d = 0;
588 	}
589 }
590 
591 static inline void
592 pmap_idcache_wbinv_range(pmap_t pm, vaddr_t va, vsize_t len)
593 {
594 
595 	if (pm->pm_cstate.cs_cache_id)
596 		cpu_idcache_wbinv_range(va, len);
597 }
598 
599 static inline void
600 pmap_dcache_wb_range(pmap_t pm, vaddr_t va, vsize_t len,
601     boolean_t do_inv, boolean_t rd_only)
602 {
603 
604 	if (pm->pm_cstate.cs_cache_d) {
605 		if (do_inv) {
606 			if (rd_only)
607 				cpu_dcache_inv_range(va, len);
608 			else
609 				cpu_dcache_wbinv_range(va, len);
610 		} else
611 		if (!rd_only)
612 			cpu_dcache_wb_range(va, len);
613 	}
614 }
615 
616 static inline void
617 pmap_idcache_wbinv_all(pmap_t pm)
618 {
619 
620 	if (pm->pm_cstate.cs_cache_id) {
621 		cpu_idcache_wbinv_all();
622 		pm->pm_cstate.cs_cache = 0;
623 	}
624 }
625 
626 static inline void
627 pmap_dcache_wbinv_all(pmap_t pm)
628 {
629 
630 	if (pm->pm_cstate.cs_cache_d) {
631 		cpu_dcache_wbinv_all();
632 		pm->pm_cstate.cs_cache_d = 0;
633 	}
634 }
635 
636 static inline boolean_t
637 pmap_is_current(pmap_t pm)
638 {
639 
640 	if (pm == pmap_kernel() ||
641 	    (curproc && curproc->p_vmspace->vm_map.pmap == pm))
642 		return (TRUE);
643 
644 	return (FALSE);
645 }
646 
647 static inline boolean_t
648 pmap_is_cached(pmap_t pm)
649 {
650 
651 	if (pm == pmap_kernel() || pmap_cache_state == NULL ||
652 	   pmap_cache_state == &pm->pm_cstate)
653 		return (TRUE);
654 
655 	return (FALSE);
656 }
657 
658 /*
659  * PTE_SYNC_CURRENT:
660  *
661  *     Make sure the pte is written out to RAM.
662  *     We need to do this for one of two cases:
663  *       - We're dealing with the kernel pmap
664  *       - There is no pmap active in the cache/tlb.
665  *       - The specified pmap is 'active' in the cache/tlb.
666  */
667 #ifdef PMAP_INCLUDE_PTE_SYNC
668 #define	PTE_SYNC_CURRENT(pm, ptep)	\
669 do {					\
670 	if (PMAP_NEEDS_PTE_SYNC && 	\
671 	    pmap_is_cached(pm))		\
672 		PTE_SYNC(ptep);		\
673 } while (/*CONSTCOND*/0)
674 #else
675 #define	PTE_SYNC_CURRENT(pm, ptep)	/* nothing */
676 #endif
677 
678 /*
679  * main pv_entry manipulation functions:
680  *   pmap_enter_pv: enter a mapping onto a vm_page list
681  *   pmap_remove_pv: remove a mappiing from a vm_page list
682  *
683  * NOTE: pmap_enter_pv expects to lock the pvh itself
684  *       pmap_remove_pv expects te caller to lock the pvh before calling
685  */
686 
687 /*
688  * pmap_enter_pv: enter a mapping onto a vm_page lst
689  *
690  * => caller should hold the proper lock on pmap_main_lock
691  * => caller should have pmap locked
692  * => we will gain the lock on the vm_page and allocate the new pv_entry
693  * => caller should adjust ptp's wire_count before calling
694  * => caller should not adjust pmap's wire_count
695  */
696 static void
697 pmap_enter_pv(struct vm_page *pg, struct pv_entry *pve, pmap_t pm,
698     vaddr_t va, u_int flags)
699 {
700 
701 	NPDEBUG(PDB_PVDUMP,
702 	    printf("pmap_enter_pv: pm %p, pg %p, flags 0x%x\n", pm, pg, flags));
703 
704 	pve->pv_pmap = pm;
705 	pve->pv_va = va;
706 	pve->pv_flags = flags;
707 
708 	simple_lock(&pg->mdpage.pvh_slock);	/* lock vm_page */
709 	pve->pv_next = pg->mdpage.pvh_list;	/* add to ... */
710 	pg->mdpage.pvh_list = pve;		/* ... locked list */
711 	pg->mdpage.pvh_attrs |= flags & (PVF_REF | PVF_MOD);
712 	if (pm == pmap_kernel()) {
713 		if (flags & PVF_WRITE)
714 			pg->mdpage.krw_mappings++;
715 		else
716 			pg->mdpage.kro_mappings++;
717 	} else
718 	if (flags & PVF_WRITE)
719 		pg->mdpage.urw_mappings++;
720 	else
721 		pg->mdpage.uro_mappings++;
722 	simple_unlock(&pg->mdpage.pvh_slock);	/* unlock, done! */
723 
724 	if (pve->pv_flags & PVF_WIRED)
725 		++pm->pm_stats.wired_count;
726 }
727 
728 /*
729  *
730  * pmap_find_pv: Find a pv entry
731  *
732  * => caller should hold lock on vm_page
733  */
734 static inline struct pv_entry *
735 pmap_find_pv(struct vm_page *pg, pmap_t pm, vaddr_t va)
736 {
737 	struct pv_entry *pv;
738 
739 	for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
740 		if (pm == pv->pv_pmap && va == pv->pv_va)
741 			break;
742 	}
743 
744 	return (pv);
745 }
746 
747 /*
748  * pmap_remove_pv: try to remove a mapping from a pv_list
749  *
750  * => caller should hold proper lock on pmap_main_lock
751  * => pmap should be locked
752  * => caller should hold lock on vm_page [so that attrs can be adjusted]
753  * => caller should adjust ptp's wire_count and free PTP if needed
754  * => caller should NOT adjust pmap's wire_count
755  * => we return the removed pve
756  */
757 static struct pv_entry *
758 pmap_remove_pv(struct vm_page *pg, pmap_t pm, vaddr_t va, int skip_wired)
759 {
760 	struct pv_entry *pve, **prevptr;
761 
762 	NPDEBUG(PDB_PVDUMP,
763 	    printf("pmap_remove_pv: pm %p, pg %p, va 0x%08lx\n", pm, pg, va));
764 
765 	prevptr = &pg->mdpage.pvh_list;		/* previous pv_entry pointer */
766 	pve = *prevptr;
767 
768 	while (pve) {
769 		if (pve->pv_pmap == pm && pve->pv_va == va) {	/* match? */
770 			NPDEBUG(PDB_PVDUMP, printf("pmap_remove_pv: pm %p, pg "
771 			    "%p, flags 0x%x\n", pm, pg, pve->pv_flags));
772 			if (pve->pv_flags & PVF_WIRED) {
773 				if (skip_wired)
774 					return (NULL);
775 				--pm->pm_stats.wired_count;
776 			}
777 			*prevptr = pve->pv_next;		/* remove it! */
778 			if (pm == pmap_kernel()) {
779 				if (pve->pv_flags & PVF_WRITE)
780 					pg->mdpage.krw_mappings--;
781 				else
782 					pg->mdpage.kro_mappings--;
783 			} else
784 			if (pve->pv_flags & PVF_WRITE)
785 				pg->mdpage.urw_mappings--;
786 			else
787 				pg->mdpage.uro_mappings--;
788 			break;
789 		}
790 		prevptr = &pve->pv_next;		/* previous pointer */
791 		pve = pve->pv_next;			/* advance */
792 	}
793 
794 	return(pve);				/* return removed pve */
795 }
796 
797 /*
798  *
799  * pmap_modify_pv: Update pv flags
800  *
801  * => caller should hold lock on vm_page [so that attrs can be adjusted]
802  * => caller should NOT adjust pmap's wire_count
803  * => caller must call pmap_vac_me_harder() if writable status of a page
804  *    may have changed.
805  * => we return the old flags
806  *
807  * Modify a physical-virtual mapping in the pv table
808  */
809 static u_int
810 pmap_modify_pv(struct vm_page *pg, pmap_t pm, vaddr_t va,
811     u_int clr_mask, u_int set_mask)
812 {
813 	struct pv_entry *npv;
814 	u_int flags, oflags;
815 
816 	if ((npv = pmap_find_pv(pg, pm, va)) == NULL)
817 		return (0);
818 
819 	NPDEBUG(PDB_PVDUMP,
820 	    printf("pmap_modify_pv: pm %p, pg %p, clr 0x%x, set 0x%x, flags 0x%x\n", pm, pg, clr_mask, set_mask, npv->pv_flags));
821 
822 	/*
823 	 * There is at least one VA mapping this page.
824 	 */
825 
826 	if (clr_mask & (PVF_REF | PVF_MOD))
827 		pg->mdpage.pvh_attrs |= set_mask & (PVF_REF | PVF_MOD);
828 
829 	oflags = npv->pv_flags;
830 	npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;
831 
832 	if ((flags ^ oflags) & PVF_WIRED) {
833 		if (flags & PVF_WIRED)
834 			++pm->pm_stats.wired_count;
835 		else
836 			--pm->pm_stats.wired_count;
837 	}
838 
839 	if ((flags ^ oflags) & PVF_WRITE) {
840 		if (pm == pmap_kernel()) {
841 			if (flags & PVF_WRITE) {
842 				pg->mdpage.krw_mappings++;
843 				pg->mdpage.kro_mappings--;
844 			} else {
845 				pg->mdpage.kro_mappings++;
846 				pg->mdpage.krw_mappings--;
847 			}
848 		} else
849 		if (flags & PVF_WRITE) {
850 			pg->mdpage.urw_mappings++;
851 			pg->mdpage.uro_mappings--;
852 		} else {
853 			pg->mdpage.uro_mappings++;
854 			pg->mdpage.urw_mappings--;
855 		}
856 	}
857 
858 	return (oflags);
859 }
860 
861 static void
862 pmap_pinit(pmap_t pm)
863 {
864 
865 	if (vector_page < KERNEL_BASE) {
866 		/*
867 		 * Map the vector page.
868 		 */
869 		pmap_enter(pm, vector_page, systempage.pv_pa,
870 		    VM_PROT_READ, VM_PROT_READ | PMAP_WIRED);
871 		pmap_update(pm);
872 	}
873 }
874 
875 /*
876  * Allocate an L1 translation table for the specified pmap.
877  * This is called at pmap creation time.
878  */
879 static void
880 pmap_alloc_l1(pmap_t pm)
881 {
882 	struct l1_ttable *l1;
883 	u_int8_t domain;
884 
885 	/*
886 	 * Remove the L1 at the head of the LRU list
887 	 */
888 	simple_lock(&l1_lru_lock);
889 	l1 = TAILQ_FIRST(&l1_lru_list);
890 	KDASSERT(l1 != NULL);
891 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
892 
893 	/*
894 	 * Pick the first available domain number, and update
895 	 * the link to the next number.
896 	 */
897 	domain = l1->l1_domain_first;
898 	l1->l1_domain_first = l1->l1_domain_free[domain];
899 
900 	/*
901 	 * If there are still free domain numbers in this L1,
902 	 * put it back on the TAIL of the LRU list.
903 	 */
904 	if (++l1->l1_domain_use_count < PMAP_DOMAINS)
905 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
906 
907 	simple_unlock(&l1_lru_lock);
908 
909 	/*
910 	 * Fix up the relevant bits in the pmap structure
911 	 */
912 	pm->pm_l1 = l1;
913 	pm->pm_domain = domain;
914 }
915 
916 /*
917  * Free an L1 translation table.
918  * This is called at pmap destruction time.
919  */
920 static void
921 pmap_free_l1(pmap_t pm)
922 {
923 	struct l1_ttable *l1 = pm->pm_l1;
924 
925 	simple_lock(&l1_lru_lock);
926 
927 	/*
928 	 * If this L1 is currently on the LRU list, remove it.
929 	 */
930 	if (l1->l1_domain_use_count < PMAP_DOMAINS)
931 		TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
932 
933 	/*
934 	 * Free up the domain number which was allocated to the pmap
935 	 */
936 	l1->l1_domain_free[pm->pm_domain] = l1->l1_domain_first;
937 	l1->l1_domain_first = pm->pm_domain;
938 	l1->l1_domain_use_count--;
939 
940 	/*
941 	 * The L1 now must have at least 1 free domain, so add
942 	 * it back to the LRU list. If the use count is zero,
943 	 * put it at the head of the list, otherwise it goes
944 	 * to the tail.
945 	 */
946 	if (l1->l1_domain_use_count == 0)
947 		TAILQ_INSERT_HEAD(&l1_lru_list, l1, l1_lru);
948 	else
949 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
950 
951 	simple_unlock(&l1_lru_lock);
952 }
953 
954 static inline void
955 pmap_use_l1(pmap_t pm)
956 {
957 	struct l1_ttable *l1;
958 
959 	/*
960 	 * Do nothing if we're in interrupt context.
961 	 * Access to an L1 by the kernel pmap must not affect
962 	 * the LRU list.
963 	 */
964 	if (current_intr_depth || pm == pmap_kernel())
965 		return;
966 
967 	l1 = pm->pm_l1;
968 
969 	/*
970 	 * If the L1 is not currently on the LRU list, just return
971 	 */
972 	if (l1->l1_domain_use_count == PMAP_DOMAINS)
973 		return;
974 
975 	simple_lock(&l1_lru_lock);
976 
977 	/*
978 	 * Check the use count again, now that we've acquired the lock
979 	 */
980 	if (l1->l1_domain_use_count == PMAP_DOMAINS) {
981 		simple_unlock(&l1_lru_lock);
982 		return;
983 	}
984 
985 	/*
986 	 * Move the L1 to the back of the LRU list
987 	 */
988 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
989 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
990 
991 	simple_unlock(&l1_lru_lock);
992 }
993 
994 /*
995  * void pmap_free_l2_ptp(pt_entry_t *, paddr_t *)
996  *
997  * Free an L2 descriptor table.
998  */
999 static inline void
1000 #ifndef PMAP_INCLUDE_PTE_SYNC
1001 pmap_free_l2_ptp(pt_entry_t *l2, paddr_t pa)
1002 #else
1003 pmap_free_l2_ptp(boolean_t need_sync, pt_entry_t *l2, paddr_t pa)
1004 #endif
1005 {
1006 #ifdef PMAP_INCLUDE_PTE_SYNC
1007 	/*
1008 	 * Note: With a write-back cache, we may need to sync this
1009 	 * L2 table before re-using it.
1010 	 * This is because it may have belonged to a non-current
1011 	 * pmap, in which case the cache syncs would have been
1012 	 * skipped when the pages were being unmapped. If the
1013 	 * L2 table were then to be immediately re-allocated to
1014 	 * the *current* pmap, it may well contain stale mappings
1015 	 * which have not yet been cleared by a cache write-back
1016 	 * and so would still be visible to the mmu.
1017 	 */
1018 	if (need_sync)
1019 		PTE_SYNC_RANGE(l2, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1020 #endif
1021 	pool_cache_put_paddr(&pmap_l2ptp_cache, (void *)l2, pa);
1022 }
1023 
1024 /*
1025  * Returns a pointer to the L2 bucket associated with the specified pmap
1026  * and VA, or NULL if no L2 bucket exists for the address.
1027  */
1028 static inline struct l2_bucket *
1029 pmap_get_l2_bucket(pmap_t pm, vaddr_t va)
1030 {
1031 	struct l2_dtable *l2;
1032 	struct l2_bucket *l2b;
1033 	u_short l1idx;
1034 
1035 	l1idx = L1_IDX(va);
1036 
1037 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL ||
1038 	    (l2b = &l2->l2_bucket[L2_BUCKET(l1idx)])->l2b_kva == NULL)
1039 		return (NULL);
1040 
1041 	return (l2b);
1042 }
1043 
1044 /*
1045  * Returns a pointer to the L2 bucket associated with the specified pmap
1046  * and VA.
1047  *
1048  * If no L2 bucket exists, perform the necessary allocations to put an L2
1049  * bucket/page table in place.
1050  *
1051  * Note that if a new L2 bucket/page was allocated, the caller *must*
1052  * increment the bucket occupancy counter appropriately *before*
1053  * releasing the pmap's lock to ensure no other thread or cpu deallocates
1054  * the bucket/page in the meantime.
1055  */
1056 static struct l2_bucket *
1057 pmap_alloc_l2_bucket(pmap_t pm, vaddr_t va)
1058 {
1059 	struct l2_dtable *l2;
1060 	struct l2_bucket *l2b;
1061 	u_short l1idx;
1062 
1063 	l1idx = L1_IDX(va);
1064 
1065 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
1066 		/*
1067 		 * No mapping at this address, as there is
1068 		 * no entry in the L1 table.
1069 		 * Need to allocate a new l2_dtable.
1070 		 */
1071 		if ((l2 = pmap_alloc_l2_dtable()) == NULL)
1072 			return (NULL);
1073 
1074 		/*
1075 		 * Link it into the parent pmap
1076 		 */
1077 		pm->pm_l2[L2_IDX(l1idx)] = l2;
1078 	}
1079 
1080 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1081 
1082 	/*
1083 	 * Fetch pointer to the L2 page table associated with the address.
1084 	 */
1085 	if (l2b->l2b_kva == NULL) {
1086 		pt_entry_t *ptep;
1087 
1088 		/*
1089 		 * No L2 page table has been allocated. Chances are, this
1090 		 * is because we just allocated the l2_dtable, above.
1091 		 */
1092 		if ((ptep = pmap_alloc_l2_ptp(&l2b->l2b_phys)) == NULL) {
1093 			/*
1094 			 * Oops, no more L2 page tables available at this
1095 			 * time. We may need to deallocate the l2_dtable
1096 			 * if we allocated a new one above.
1097 			 */
1098 			if (l2->l2_occupancy == 0) {
1099 				pm->pm_l2[L2_IDX(l1idx)] = NULL;
1100 				pmap_free_l2_dtable(l2);
1101 			}
1102 			return (NULL);
1103 		}
1104 
1105 		l2->l2_occupancy++;
1106 		l2b->l2b_kva = ptep;
1107 		l2b->l2b_l1idx = l1idx;
1108 	}
1109 
1110 	return (l2b);
1111 }
1112 
1113 /*
1114  * One or more mappings in the specified L2 descriptor table have just been
1115  * invalidated.
1116  *
1117  * Garbage collect the metadata and descriptor table itself if necessary.
1118  *
1119  * The pmap lock must be acquired when this is called (not necessary
1120  * for the kernel pmap).
1121  */
1122 static void
1123 pmap_free_l2_bucket(pmap_t pm, struct l2_bucket *l2b, u_int count)
1124 {
1125 	struct l2_dtable *l2;
1126 	pd_entry_t *pl1pd, l1pd;
1127 	pt_entry_t *ptep;
1128 	u_short l1idx;
1129 
1130 	KDASSERT(count <= l2b->l2b_occupancy);
1131 
1132 	/*
1133 	 * Update the bucket's reference count according to how many
1134 	 * PTEs the caller has just invalidated.
1135 	 */
1136 	l2b->l2b_occupancy -= count;
1137 
1138 	/*
1139 	 * Note:
1140 	 *
1141 	 * Level 2 page tables allocated to the kernel pmap are never freed
1142 	 * as that would require checking all Level 1 page tables and
1143 	 * removing any references to the Level 2 page table. See also the
1144 	 * comment elsewhere about never freeing bootstrap L2 descriptors.
1145 	 *
1146 	 * We make do with just invalidating the mapping in the L2 table.
1147 	 *
1148 	 * This isn't really a big deal in practice and, in fact, leads
1149 	 * to a performance win over time as we don't need to continually
1150 	 * alloc/free.
1151 	 */
1152 	if (l2b->l2b_occupancy > 0 || pm == pmap_kernel())
1153 		return;
1154 
1155 	/*
1156 	 * There are no more valid mappings in this level 2 page table.
1157 	 * Go ahead and NULL-out the pointer in the bucket, then
1158 	 * free the page table.
1159 	 */
1160 	l1idx = l2b->l2b_l1idx;
1161 	ptep = l2b->l2b_kva;
1162 	l2b->l2b_kva = NULL;
1163 
1164 	pl1pd = &pm->pm_l1->l1_kva[l1idx];
1165 
1166 	/*
1167 	 * If the L1 slot matches the pmap's domain
1168 	 * number, then invalidate it.
1169 	 */
1170 	l1pd = *pl1pd & (L1_TYPE_MASK | L1_C_DOM_MASK);
1171 	if (l1pd == (L1_C_DOM(pm->pm_domain) | L1_TYPE_C)) {
1172 		*pl1pd = 0;
1173 		PTE_SYNC(pl1pd);
1174 	}
1175 
1176 	/*
1177 	 * Release the L2 descriptor table back to the pool cache.
1178 	 */
1179 #ifndef PMAP_INCLUDE_PTE_SYNC
1180 	pmap_free_l2_ptp(ptep, l2b->l2b_phys);
1181 #else
1182 	pmap_free_l2_ptp(!pmap_is_cached(pm), ptep, l2b->l2b_phys);
1183 #endif
1184 
1185 	/*
1186 	 * Update the reference count in the associated l2_dtable
1187 	 */
1188 	l2 = pm->pm_l2[L2_IDX(l1idx)];
1189 	if (--l2->l2_occupancy > 0)
1190 		return;
1191 
1192 	/*
1193 	 * There are no more valid mappings in any of the Level 1
1194 	 * slots managed by this l2_dtable. Go ahead and NULL-out
1195 	 * the pointer in the parent pmap and free the l2_dtable.
1196 	 */
1197 	pm->pm_l2[L2_IDX(l1idx)] = NULL;
1198 	pmap_free_l2_dtable(l2);
1199 }
1200 
1201 /*
1202  * Pool cache constructors for L2 descriptor tables, metadata and pmap
1203  * structures.
1204  */
1205 static int
1206 pmap_l2ptp_ctor(void *arg, void *v, int flags)
1207 {
1208 #ifndef PMAP_INCLUDE_PTE_SYNC
1209 	struct l2_bucket *l2b;
1210 	pt_entry_t *ptep, pte;
1211 	vaddr_t va = (vaddr_t)v & ~PGOFSET;
1212 
1213 	/*
1214 	 * The mappings for these page tables were initially made using
1215 	 * pmap_kenter_pa() by the pool subsystem. Therefore, the cache-
1216 	 * mode will not be right for page table mappings. To avoid
1217 	 * polluting the pmap_kenter_pa() code with a special case for
1218 	 * page tables, we simply fix up the cache-mode here if it's not
1219 	 * correct.
1220 	 */
1221 	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1222 	KDASSERT(l2b != NULL);
1223 	ptep = &l2b->l2b_kva[l2pte_index(va)];
1224 	pte = *ptep;
1225 
1226 	if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
1227 		/*
1228 		 * Page tables must have the cache-mode set to Write-Thru.
1229 		 */
1230 		*ptep = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
1231 		PTE_SYNC(ptep);
1232 		cpu_tlb_flushD_SE(va);
1233 		cpu_cpwait();
1234 	}
1235 #endif
1236 
1237 	memset(v, 0, L2_TABLE_SIZE_REAL);
1238 	PTE_SYNC_RANGE(v, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1239 	return (0);
1240 }
1241 
1242 static int
1243 pmap_l2dtable_ctor(void *arg, void *v, int flags)
1244 {
1245 
1246 	memset(v, 0, sizeof(struct l2_dtable));
1247 	return (0);
1248 }
1249 
1250 static int
1251 pmap_pmap_ctor(void *arg, void *v, int flags)
1252 {
1253 
1254 	memset(v, 0, sizeof(struct pmap));
1255 	return (0);
1256 }
1257 
1258 /*
1259  * Since we have a virtually indexed cache, we may need to inhibit caching if
1260  * there is more than one mapping and at least one of them is writable.
1261  * Since we purge the cache on every context switch, we only need to check for
1262  * other mappings within the same pmap, or kernel_pmap.
1263  * This function is also called when a page is unmapped, to possibly reenable
1264  * caching on any remaining mappings.
1265  *
1266  * The code implements the following logic, where:
1267  *
1268  * KW = # of kernel read/write pages
1269  * KR = # of kernel read only pages
1270  * UW = # of user read/write pages
1271  * UR = # of user read only pages
1272  *
1273  * KC = kernel mapping is cacheable
1274  * UC = user mapping is cacheable
1275  *
1276  *               KW=0,KR=0  KW=0,KR>0  KW=1,KR=0  KW>1,KR>=0
1277  *             +---------------------------------------------
1278  * UW=0,UR=0   | ---        KC=1       KC=1       KC=0
1279  * UW=0,UR>0   | UC=1       KC=1,UC=1  KC=0,UC=0  KC=0,UC=0
1280  * UW=1,UR=0   | UC=1       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
1281  * UW>1,UR>=0  | UC=0       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
1282  */
1283 
1284 static const int pmap_vac_flags[4][4] = {
1285 	{-1,		0,		0,		PVF_KNC},
1286 	{0,		0,		PVF_NC,		PVF_NC},
1287 	{0,		PVF_NC,		PVF_NC,		PVF_NC},
1288 	{PVF_UNC,	PVF_NC,		PVF_NC,		PVF_NC}
1289 };
1290 
1291 static inline int
1292 pmap_get_vac_flags(const struct vm_page *pg)
1293 {
1294 	int kidx, uidx;
1295 
1296 	kidx = 0;
1297 	if (pg->mdpage.kro_mappings || pg->mdpage.krw_mappings > 1)
1298 		kidx |= 1;
1299 	if (pg->mdpage.krw_mappings)
1300 		kidx |= 2;
1301 
1302 	uidx = 0;
1303 	if (pg->mdpage.uro_mappings || pg->mdpage.urw_mappings > 1)
1304 		uidx |= 1;
1305 	if (pg->mdpage.urw_mappings)
1306 		uidx |= 2;
1307 
1308 	return (pmap_vac_flags[uidx][kidx]);
1309 }
1310 
1311 static inline void
1312 pmap_vac_me_harder(struct vm_page *pg, pmap_t pm, vaddr_t va)
1313 {
1314 	int nattr;
1315 
1316 	nattr = pmap_get_vac_flags(pg);
1317 
1318 	if (nattr < 0) {
1319 		pg->mdpage.pvh_attrs &= ~PVF_NC;
1320 		return;
1321 	}
1322 
1323 	if (nattr == 0 && (pg->mdpage.pvh_attrs & PVF_NC) == 0)
1324 		return;
1325 
1326 	if (pm == pmap_kernel())
1327 		pmap_vac_me_kpmap(pg, pm, va);
1328 	else
1329 		pmap_vac_me_user(pg, pm, va);
1330 
1331 	pg->mdpage.pvh_attrs = (pg->mdpage.pvh_attrs & ~PVF_NC) | nattr;
1332 }
1333 
1334 static void
1335 pmap_vac_me_kpmap(struct vm_page *pg, pmap_t pm, vaddr_t va)
1336 {
1337 	u_int u_cacheable, u_entries;
1338 	struct pv_entry *pv;
1339 	pmap_t last_pmap = pm;
1340 
1341 	/*
1342 	 * Pass one, see if there are both kernel and user pmaps for
1343 	 * this page.  Calculate whether there are user-writable or
1344 	 * kernel-writable pages.
1345 	 */
1346 	u_cacheable = 0;
1347 	for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
1348 		if (pv->pv_pmap != pm && (pv->pv_flags & PVF_NC) == 0)
1349 			u_cacheable++;
1350 	}
1351 
1352 	u_entries = pg->mdpage.urw_mappings + pg->mdpage.uro_mappings;
1353 
1354 	/*
1355 	 * We know we have just been updating a kernel entry, so if
1356 	 * all user pages are already cacheable, then there is nothing
1357 	 * further to do.
1358 	 */
1359 	if (pg->mdpage.k_mappings == 0 && u_cacheable == u_entries)
1360 		return;
1361 
1362 	if (u_entries) {
1363 		/*
1364 		 * Scan over the list again, for each entry, if it
1365 		 * might not be set correctly, call pmap_vac_me_user
1366 		 * to recalculate the settings.
1367 		 */
1368 		for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
1369 			/*
1370 			 * We know kernel mappings will get set
1371 			 * correctly in other calls.  We also know
1372 			 * that if the pmap is the same as last_pmap
1373 			 * then we've just handled this entry.
1374 			 */
1375 			if (pv->pv_pmap == pm || pv->pv_pmap == last_pmap)
1376 				continue;
1377 
1378 			/*
1379 			 * If there are kernel entries and this page
1380 			 * is writable but non-cacheable, then we can
1381 			 * skip this entry also.
1382 			 */
1383 			if (pg->mdpage.k_mappings &&
1384 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) ==
1385 			    (PVF_NC | PVF_WRITE))
1386 				continue;
1387 
1388 			/*
1389 			 * Similarly if there are no kernel-writable
1390 			 * entries and the page is already
1391 			 * read-only/cacheable.
1392 			 */
1393 			if (pg->mdpage.krw_mappings == 0 &&
1394 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) == 0)
1395 				continue;
1396 
1397 			/*
1398 			 * For some of the remaining cases, we know
1399 			 * that we must recalculate, but for others we
1400 			 * can't tell if they are correct or not, so
1401 			 * we recalculate anyway.
1402 			 */
1403 			pmap_vac_me_user(pg, (last_pmap = pv->pv_pmap), 0);
1404 		}
1405 
1406 		if (pg->mdpage.k_mappings == 0)
1407 			return;
1408 	}
1409 
1410 	pmap_vac_me_user(pg, pm, va);
1411 }
1412 
1413 static void
1414 pmap_vac_me_user(struct vm_page *pg, pmap_t pm, vaddr_t va)
1415 {
1416 	pmap_t kpmap = pmap_kernel();
1417 	struct pv_entry *pv, *npv;
1418 	struct l2_bucket *l2b;
1419 	pt_entry_t *ptep, pte;
1420 	u_int entries = 0;
1421 	u_int writable = 0;
1422 	u_int cacheable_entries = 0;
1423 	u_int kern_cacheable = 0;
1424 	u_int other_writable = 0;
1425 
1426 	/*
1427 	 * Count mappings and writable mappings in this pmap.
1428 	 * Include kernel mappings as part of our own.
1429 	 * Keep a pointer to the first one.
1430 	 */
1431 	for (pv = npv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
1432 		/* Count mappings in the same pmap */
1433 		if (pm == pv->pv_pmap || kpmap == pv->pv_pmap) {
1434 			if (entries++ == 0)
1435 				npv = pv;
1436 
1437 			/* Cacheable mappings */
1438 			if ((pv->pv_flags & PVF_NC) == 0) {
1439 				cacheable_entries++;
1440 				if (kpmap == pv->pv_pmap)
1441 					kern_cacheable++;
1442 			}
1443 
1444 			/* Writable mappings */
1445 			if (pv->pv_flags & PVF_WRITE)
1446 				++writable;
1447 		} else
1448 		if (pv->pv_flags & PVF_WRITE)
1449 			other_writable = 1;
1450 	}
1451 
1452 	/*
1453 	 * Enable or disable caching as necessary.
1454 	 * Note: the first entry might be part of the kernel pmap,
1455 	 * so we can't assume this is indicative of the state of the
1456 	 * other (maybe non-kpmap) entries.
1457 	 */
1458 	if ((entries > 1 && writable) ||
1459 	    (entries > 0 && pm == kpmap && other_writable)) {
1460 		if (cacheable_entries == 0)
1461 			return;
1462 
1463 		for (pv = npv; pv; pv = pv->pv_next) {
1464 			if ((pm != pv->pv_pmap && kpmap != pv->pv_pmap) ||
1465 			    (pv->pv_flags & PVF_NC))
1466 				continue;
1467 
1468 			pv->pv_flags |= PVF_NC;
1469 
1470 			l2b = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
1471 			ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
1472 			pte = *ptep & ~L2_S_CACHE_MASK;
1473 
1474 			if ((va != pv->pv_va || pm != pv->pv_pmap) &&
1475 			    l2pte_valid(pte)) {
1476 				if (PV_BEEN_EXECD(pv->pv_flags)) {
1477 					pmap_idcache_wbinv_range(pv->pv_pmap,
1478 					    pv->pv_va, PAGE_SIZE);
1479 					pmap_tlb_flushID_SE(pv->pv_pmap,
1480 					    pv->pv_va);
1481 				} else
1482 				if (PV_BEEN_REFD(pv->pv_flags)) {
1483 					pmap_dcache_wb_range(pv->pv_pmap,
1484 					    pv->pv_va, PAGE_SIZE, TRUE,
1485 					    (pv->pv_flags & PVF_WRITE) == 0);
1486 					pmap_tlb_flushD_SE(pv->pv_pmap,
1487 					    pv->pv_va);
1488 				}
1489 			}
1490 
1491 			*ptep = pte;
1492 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
1493 		}
1494 		cpu_cpwait();
1495 	} else
1496 	if (entries > cacheable_entries) {
1497 		/*
1498 		 * Turn cacheing back on for some pages.  If it is a kernel
1499 		 * page, only do so if there are no other writable pages.
1500 		 */
1501 		for (pv = npv; pv; pv = pv->pv_next) {
1502 			if (!(pv->pv_flags & PVF_NC) || (pm != pv->pv_pmap &&
1503 			    (kpmap != pv->pv_pmap || other_writable)))
1504 				continue;
1505 
1506 			pv->pv_flags &= ~PVF_NC;
1507 
1508 			l2b = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
1509 			ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
1510 			pte = (*ptep & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode;
1511 
1512 			if (l2pte_valid(pte)) {
1513 				if (PV_BEEN_EXECD(pv->pv_flags)) {
1514 					pmap_tlb_flushID_SE(pv->pv_pmap,
1515 					    pv->pv_va);
1516 				} else
1517 				if (PV_BEEN_REFD(pv->pv_flags)) {
1518 					pmap_tlb_flushD_SE(pv->pv_pmap,
1519 					    pv->pv_va);
1520 				}
1521 			}
1522 
1523 			*ptep = pte;
1524 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
1525 		}
1526 	}
1527 }
1528 
1529 /*
1530  * Modify pte bits for all ptes corresponding to the given physical address.
1531  * We use `maskbits' rather than `clearbits' because we're always passing
1532  * constants and the latter would require an extra inversion at run-time.
1533  */
1534 static void
1535 pmap_clearbit(struct vm_page *pg, u_int maskbits)
1536 {
1537 	struct l2_bucket *l2b;
1538 	struct pv_entry *pv;
1539 	pt_entry_t *ptep, npte, opte;
1540 	pmap_t pm;
1541 	vaddr_t va;
1542 	u_int oflags;
1543 
1544 	NPDEBUG(PDB_BITS,
1545 	    printf("pmap_clearbit: pg %p (0x%08lx) mask 0x%x\n",
1546 	    pg, VM_PAGE_TO_PHYS(pg), maskbits));
1547 
1548 	PMAP_HEAD_TO_MAP_LOCK();
1549 	simple_lock(&pg->mdpage.pvh_slock);
1550 
1551 	/*
1552 	 * Clear saved attributes (modify, reference)
1553 	 */
1554 	pg->mdpage.pvh_attrs &= ~(maskbits & (PVF_MOD | PVF_REF));
1555 
1556 	if (pg->mdpage.pvh_list == NULL) {
1557 		simple_unlock(&pg->mdpage.pvh_slock);
1558 		PMAP_HEAD_TO_MAP_UNLOCK();
1559 		return;
1560 	}
1561 
1562 	/*
1563 	 * Loop over all current mappings setting/clearing as appropos
1564 	 */
1565 	for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
1566 		va = pv->pv_va;
1567 		pm = pv->pv_pmap;
1568 		oflags = pv->pv_flags;
1569 		pv->pv_flags &= ~maskbits;
1570 
1571 		pmap_acquire_pmap_lock(pm);
1572 
1573 		l2b = pmap_get_l2_bucket(pm, va);
1574 		KDASSERT(l2b != NULL);
1575 
1576 		ptep = &l2b->l2b_kva[l2pte_index(va)];
1577 		npte = opte = *ptep;
1578 
1579 		NPDEBUG(PDB_BITS,
1580 		    printf(
1581 		    "pmap_clearbit: pv %p, pm %p, va 0x%08lx, flag 0x%x\n",
1582 		    pv, pv->pv_pmap, pv->pv_va, oflags));
1583 
1584 		if (maskbits & (PVF_WRITE|PVF_MOD)) {
1585 			if ((pv->pv_flags & PVF_NC)) {
1586 				/*
1587 				 * Entry is not cacheable:
1588 				 *
1589 				 * Don't turn caching on again if this is a
1590 				 * modified emulation. This would be
1591 				 * inconsitent with the settings created by
1592 				 * pmap_vac_me_harder(). Otherwise, it's safe
1593 				 * to re-enable cacheing.
1594 				 *
1595 				 * There's no need to call pmap_vac_me_harder()
1596 				 * here: all pages are losing their write
1597 				 * permission.
1598 				 */
1599 				if (maskbits & PVF_WRITE) {
1600 					npte |= pte_l2_s_cache_mode;
1601 					pv->pv_flags &= ~PVF_NC;
1602 				}
1603 			} else
1604 			if (opte & L2_S_PROT_W) {
1605 				/*
1606 				 * Entry is writable/cacheable: check if pmap
1607 				 * is current if it is flush it, otherwise it
1608 				 * won't be in the cache
1609 				 */
1610 				if (PV_BEEN_EXECD(oflags))
1611 					pmap_idcache_wbinv_range(pm, pv->pv_va,
1612 					    PAGE_SIZE);
1613 				else
1614 				if (PV_BEEN_REFD(oflags))
1615 					pmap_dcache_wb_range(pm, pv->pv_va,
1616 					    PAGE_SIZE,
1617 					    (maskbits & PVF_REF) ? TRUE : FALSE,
1618 					    FALSE);
1619 			}
1620 
1621 			/* make the pte read only */
1622 			npte &= ~L2_S_PROT_W;
1623 
1624 			if (maskbits & PVF_WRITE) {
1625 				/*
1626 				 * Keep alias accounting up to date
1627 				 */
1628 				if (pv->pv_pmap == pmap_kernel()) {
1629 					if (oflags & PVF_WRITE) {
1630 						pg->mdpage.krw_mappings--;
1631 						pg->mdpage.kro_mappings++;
1632 					}
1633 				} else
1634 				if (oflags & PVF_WRITE) {
1635 					pg->mdpage.urw_mappings--;
1636 					pg->mdpage.uro_mappings++;
1637 				}
1638 			}
1639 		}
1640 
1641 		if (maskbits & PVF_REF) {
1642 			if ((pv->pv_flags & PVF_NC) == 0 &&
1643 			    (maskbits & (PVF_WRITE|PVF_MOD)) == 0) {
1644 				/*
1645 				 * Check npte here; we may have already
1646 				 * done the wbinv above, and the validity
1647 				 * of the PTE is the same for opte and
1648 				 * npte.
1649 				 */
1650 				if (npte & L2_S_PROT_W) {
1651 					if (PV_BEEN_EXECD(oflags))
1652 						pmap_idcache_wbinv_range(pm,
1653 						    pv->pv_va, PAGE_SIZE);
1654 					else
1655 					if (PV_BEEN_REFD(oflags))
1656 						pmap_dcache_wb_range(pm,
1657 						    pv->pv_va, PAGE_SIZE,
1658 						    TRUE, FALSE);
1659 				} else
1660 				if ((npte & L2_TYPE_MASK) != L2_TYPE_INV) {
1661 					/* XXXJRT need idcache_inv_range */
1662 					if (PV_BEEN_EXECD(oflags))
1663 						pmap_idcache_wbinv_range(pm,
1664 						    pv->pv_va, PAGE_SIZE);
1665 					else
1666 					if (PV_BEEN_REFD(oflags))
1667 						pmap_dcache_wb_range(pm,
1668 						    pv->pv_va, PAGE_SIZE,
1669 						    TRUE, TRUE);
1670 				}
1671 			}
1672 
1673 			/*
1674 			 * Make the PTE invalid so that we will take a
1675 			 * page fault the next time the mapping is
1676 			 * referenced.
1677 			 */
1678 			npte &= ~L2_TYPE_MASK;
1679 			npte |= L2_TYPE_INV;
1680 		}
1681 
1682 		if (npte != opte) {
1683 			*ptep = npte;
1684 			PTE_SYNC(ptep);
1685 			/* Flush the TLB entry if a current pmap. */
1686 			if (PV_BEEN_EXECD(oflags))
1687 				pmap_tlb_flushID_SE(pm, pv->pv_va);
1688 			else
1689 			if (PV_BEEN_REFD(oflags))
1690 				pmap_tlb_flushD_SE(pm, pv->pv_va);
1691 		}
1692 
1693 		pmap_release_pmap_lock(pm);
1694 
1695 		NPDEBUG(PDB_BITS,
1696 		    printf("pmap_clearbit: pm %p va 0x%lx opte 0x%08x npte 0x%08x\n",
1697 		    pm, va, opte, npte));
1698 	}
1699 
1700 	simple_unlock(&pg->mdpage.pvh_slock);
1701 	PMAP_HEAD_TO_MAP_UNLOCK();
1702 }
1703 
1704 /*
1705  * pmap_clean_page()
1706  *
1707  * This is a local function used to work out the best strategy to clean
1708  * a single page referenced by its entry in the PV table. It's used by
1709  * pmap_copy_page, pmap_zero page and maybe some others later on.
1710  *
1711  * Its policy is effectively:
1712  *  o If there are no mappings, we don't bother doing anything with the cache.
1713  *  o If there is one mapping, we clean just that page.
1714  *  o If there are multiple mappings, we clean the entire cache.
1715  *
1716  * So that some functions can be further optimised, it returns 0 if it didn't
1717  * clean the entire cache, or 1 if it did.
1718  *
1719  * XXX One bug in this routine is that if the pv_entry has a single page
1720  * mapped at 0x00000000 a whole cache clean will be performed rather than
1721  * just the 1 page. Since this should not occur in everyday use and if it does
1722  * it will just result in not the most efficient clean for the page.
1723  */
1724 static int
1725 pmap_clean_page(struct pv_entry *pv, boolean_t is_src)
1726 {
1727 	pmap_t pm, pm_to_clean = NULL;
1728 	struct pv_entry *npv;
1729 	u_int cache_needs_cleaning = 0;
1730 	u_int flags = 0;
1731 	vaddr_t page_to_clean = 0;
1732 
1733 	if (pv == NULL) {
1734 		/* nothing mapped in so nothing to flush */
1735 		return (0);
1736 	}
1737 
1738 	/*
1739 	 * Since we flush the cache each time we change to a different
1740 	 * user vmspace, we only need to flush the page if it is in the
1741 	 * current pmap.
1742 	 */
1743 	if (curproc)
1744 		pm = curproc->p_vmspace->vm_map.pmap;
1745 	else
1746 		pm = pmap_kernel();
1747 
1748 	for (npv = pv; npv; npv = npv->pv_next) {
1749 		if (npv->pv_pmap == pmap_kernel() || npv->pv_pmap == pm) {
1750 			flags |= npv->pv_flags;
1751 			/*
1752 			 * The page is mapped non-cacheable in
1753 			 * this map.  No need to flush the cache.
1754 			 */
1755 			if (npv->pv_flags & PVF_NC) {
1756 #ifdef DIAGNOSTIC
1757 				if (cache_needs_cleaning)
1758 					panic("pmap_clean_page: "
1759 					    "cache inconsistency");
1760 #endif
1761 				break;
1762 			} else if (is_src && (npv->pv_flags & PVF_WRITE) == 0)
1763 				continue;
1764 			if (cache_needs_cleaning) {
1765 				page_to_clean = 0;
1766 				break;
1767 			} else {
1768 				page_to_clean = npv->pv_va;
1769 				pm_to_clean = npv->pv_pmap;
1770 			}
1771 			cache_needs_cleaning = 1;
1772 		}
1773 	}
1774 
1775 	if (page_to_clean) {
1776 		if (PV_BEEN_EXECD(flags))
1777 			pmap_idcache_wbinv_range(pm_to_clean, page_to_clean,
1778 			    PAGE_SIZE);
1779 		else
1780 			pmap_dcache_wb_range(pm_to_clean, page_to_clean,
1781 			    PAGE_SIZE, !is_src, (flags & PVF_WRITE) == 0);
1782 	} else if (cache_needs_cleaning) {
1783 		if (PV_BEEN_EXECD(flags))
1784 			pmap_idcache_wbinv_all(pm);
1785 		else
1786 			pmap_dcache_wbinv_all(pm);
1787 		return (1);
1788 	}
1789 	return (0);
1790 }
1791 
1792 /*
1793  * Routine:	pmap_page_remove
1794  * Function:
1795  *		Removes this physical page from
1796  *		all physical maps in which it resides.
1797  *		Reflects back modify bits to the pager.
1798  */
1799 static void
1800 pmap_page_remove(struct vm_page *pg)
1801 {
1802 	struct l2_bucket *l2b;
1803 	struct pv_entry *pv, *npv;
1804 	pmap_t pm, curpm;
1805 	pt_entry_t *ptep, pte;
1806 	boolean_t flush;
1807 	u_int flags;
1808 
1809 	NPDEBUG(PDB_FOLLOW,
1810 	    printf("pmap_page_remove: pg %p (0x%08lx)\n", pg,
1811 	    VM_PAGE_TO_PHYS(pg)));
1812 
1813 	PMAP_HEAD_TO_MAP_LOCK();
1814 	simple_lock(&pg->mdpage.pvh_slock);
1815 
1816 	pv = pg->mdpage.pvh_list;
1817 	if (pv == NULL) {
1818 		simple_unlock(&pg->mdpage.pvh_slock);
1819 		PMAP_HEAD_TO_MAP_UNLOCK();
1820 		return;
1821 	}
1822 
1823 	/*
1824 	 * Clear alias counts
1825 	 */
1826 	pg->mdpage.k_mappings = 0;
1827 	pg->mdpage.urw_mappings = pg->mdpage.uro_mappings = 0;
1828 
1829 	flush = FALSE;
1830 	flags = 0;
1831 	if (curproc)
1832 		curpm = curproc->p_vmspace->vm_map.pmap;
1833 	else
1834 		curpm = pmap_kernel();
1835 
1836 	pmap_clean_page(pv, FALSE);
1837 
1838 	while (pv) {
1839 		pm = pv->pv_pmap;
1840 		if (flush == FALSE && (pm == curpm || pm == pmap_kernel()))
1841 			flush = TRUE;
1842 
1843 		pmap_acquire_pmap_lock(pm);
1844 
1845 		l2b = pmap_get_l2_bucket(pm, pv->pv_va);
1846 		KDASSERT(l2b != NULL);
1847 
1848 		ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
1849 		pte = *ptep;
1850 
1851 		/*
1852 		 * Update statistics
1853 		 */
1854 		--pm->pm_stats.resident_count;
1855 
1856 		/* Wired bit */
1857 		if (pv->pv_flags & PVF_WIRED)
1858 			--pm->pm_stats.wired_count;
1859 
1860 		flags |= pv->pv_flags;
1861 
1862 		/*
1863 		 * Invalidate the PTEs.
1864 		 */
1865 		*ptep = 0;
1866 		PTE_SYNC_CURRENT(pm, ptep);
1867 		pmap_free_l2_bucket(pm, l2b, 1);
1868 
1869 		npv = pv->pv_next;
1870 		pool_put(&pmap_pv_pool, pv);
1871 		pv = npv;
1872 		pmap_release_pmap_lock(pm);
1873 	}
1874 	pg->mdpage.pvh_list = NULL;
1875 	simple_unlock(&pg->mdpage.pvh_slock);
1876 	PMAP_HEAD_TO_MAP_UNLOCK();
1877 
1878 	if (flush) {
1879 		/*
1880 		 * Note: We can't use pmap_tlb_flush{I,}D() here since that
1881 		 * would need a subsequent call to pmap_update() to ensure
1882 		 * curpm->pm_cstate.cs_all is reset. Our callers are not
1883 		 * required to do that (see pmap(9)), so we can't modify
1884 		 * the current pmap's state.
1885 		 */
1886 		if (PV_BEEN_EXECD(flags))
1887 			cpu_tlb_flushID();
1888 		else
1889 			cpu_tlb_flushD();
1890 	}
1891 	cpu_cpwait();
1892 }
1893 
1894 /*
1895  * pmap_t pmap_create(void)
1896  *
1897  *      Create a new pmap structure from scratch.
1898  */
1899 pmap_t
1900 pmap_create(void)
1901 {
1902 	pmap_t pm;
1903 
1904 	pm = pool_cache_get(&pmap_pmap_cache, PR_WAITOK);
1905 
1906 	simple_lock_init(&pm->pm_lock);
1907 	pm->pm_obj.pgops = NULL;	/* currently not a mappable object */
1908 	TAILQ_INIT(&pm->pm_obj.memq);
1909 	pm->pm_obj.uo_npages = 0;
1910 	pm->pm_obj.uo_refs = 1;
1911 	pm->pm_stats.wired_count = 0;
1912 	pm->pm_stats.resident_count = 1;
1913 	pm->pm_cstate.cs_all = 0;
1914 	pmap_alloc_l1(pm);
1915 
1916 	/*
1917 	 * Note: The pool cache ensures that the pm_l2[] array is already
1918 	 * initialised to zero.
1919 	 */
1920 
1921 	pmap_pinit(pm);
1922 
1923 	LIST_INSERT_HEAD(&pmap_pmaps, pm, pm_list);
1924 
1925 	return (pm);
1926 }
1927 
1928 /*
1929  * void pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot,
1930  *     int flags)
1931  *
1932  *      Insert the given physical page (p) at
1933  *      the specified virtual address (v) in the
1934  *      target physical map with the protection requested.
1935  *
1936  *      NB:  This is the only routine which MAY NOT lazy-evaluate
1937  *      or lose information.  That is, this routine must actually
1938  *      insert this page into the given map NOW.
1939  */
1940 int
1941 pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot, int flags)
1942 {
1943 	struct l2_bucket *l2b;
1944 	struct vm_page *pg, *opg;
1945 	struct pv_entry *pve;
1946 	pt_entry_t *ptep, npte, opte;
1947 	u_int nflags;
1948 	u_int oflags;
1949 
1950 	NPDEBUG(PDB_ENTER, printf("pmap_enter: pm %p va 0x%lx pa 0x%lx prot %x flag %x\n", pm, va, pa, prot, flags));
1951 
1952 	KDASSERT((flags & PMAP_WIRED) == 0 || (flags & VM_PROT_ALL) != 0);
1953 	KDASSERT(((va | pa) & PGOFSET) == 0);
1954 
1955 	/*
1956 	 * Get a pointer to the page.  Later on in this function, we
1957 	 * test for a managed page by checking pg != NULL.
1958 	 */
1959 	pg = pmap_initialized ? PHYS_TO_VM_PAGE(pa) : NULL;
1960 
1961 	nflags = 0;
1962 	if (prot & VM_PROT_WRITE)
1963 		nflags |= PVF_WRITE;
1964 	if (prot & VM_PROT_EXECUTE)
1965 		nflags |= PVF_EXEC;
1966 	if (flags & PMAP_WIRED)
1967 		nflags |= PVF_WIRED;
1968 
1969 	PMAP_MAP_TO_HEAD_LOCK();
1970 	pmap_acquire_pmap_lock(pm);
1971 
1972 	/*
1973 	 * Fetch the L2 bucket which maps this page, allocating one if
1974 	 * necessary for user pmaps.
1975 	 */
1976 	if (pm == pmap_kernel())
1977 		l2b = pmap_get_l2_bucket(pm, va);
1978 	else
1979 		l2b = pmap_alloc_l2_bucket(pm, va);
1980 	if (l2b == NULL) {
1981 		if (flags & PMAP_CANFAIL) {
1982 			pmap_release_pmap_lock(pm);
1983 			PMAP_MAP_TO_HEAD_UNLOCK();
1984 			return (ENOMEM);
1985 		}
1986 		panic("pmap_enter: failed to allocate L2 bucket");
1987 	}
1988 	ptep = &l2b->l2b_kva[l2pte_index(va)];
1989 	opte = *ptep;
1990 	npte = pa;
1991 	oflags = 0;
1992 
1993 	if (opte) {
1994 		/*
1995 		 * There is already a mapping at this address.
1996 		 * If the physical address is different, lookup the
1997 		 * vm_page.
1998 		 */
1999 		if (l2pte_pa(opte) != pa)
2000 			opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
2001 		else
2002 			opg = pg;
2003 	} else
2004 		opg = NULL;
2005 
2006 	if (pg) {
2007 		/*
2008 		 * This is to be a managed mapping.
2009 		 */
2010 		if ((flags & VM_PROT_ALL) ||
2011 		    (pg->mdpage.pvh_attrs & PVF_REF)) {
2012 			/*
2013 			 * - The access type indicates that we don't need
2014 			 *   to do referenced emulation.
2015 			 * OR
2016 			 * - The physical page has already been referenced
2017 			 *   so no need to re-do referenced emulation here.
2018 			 */
2019 			npte |= L2_S_PROTO;
2020 
2021 			nflags |= PVF_REF;
2022 
2023 			if ((prot & VM_PROT_WRITE) != 0 &&
2024 			    ((flags & VM_PROT_WRITE) != 0 ||
2025 			     (pg->mdpage.pvh_attrs & PVF_MOD) != 0)) {
2026 				/*
2027 				 * This is a writable mapping, and the
2028 				 * page's mod state indicates it has
2029 				 * already been modified. Make it
2030 				 * writable from the outset.
2031 				 */
2032 				npte |= L2_S_PROT_W;
2033 				nflags |= PVF_MOD;
2034 			}
2035 		} else {
2036 			/*
2037 			 * Need to do page referenced emulation.
2038 			 */
2039 			npte |= L2_TYPE_INV;
2040 		}
2041 
2042 		npte |= pte_l2_s_cache_mode;
2043 
2044 		if (pg == opg) {
2045 			/*
2046 			 * We're changing the attrs of an existing mapping.
2047 			 */
2048 			simple_lock(&pg->mdpage.pvh_slock);
2049 			oflags = pmap_modify_pv(pg, pm, va,
2050 			    PVF_WRITE | PVF_EXEC | PVF_WIRED |
2051 			    PVF_MOD | PVF_REF, nflags);
2052 			simple_unlock(&pg->mdpage.pvh_slock);
2053 
2054 			/*
2055 			 * We may need to flush the cache if we're
2056 			 * doing rw-ro...
2057 			 */
2058 			if (pm->pm_cstate.cs_cache_d &&
2059 			    (oflags & PVF_NC) == 0 &&
2060 			    (opte & L2_S_PROT_W) != 0 &&
2061 			    (prot & VM_PROT_WRITE) == 0)
2062 				cpu_dcache_wb_range(va, PAGE_SIZE);
2063 		} else {
2064 			/*
2065 			 * New mapping, or changing the backing page
2066 			 * of an existing mapping.
2067 			 */
2068 			if (opg) {
2069 				/*
2070 				 * Replacing an existing mapping with a new one.
2071 				 * It is part of our managed memory so we
2072 				 * must remove it from the PV list
2073 				 */
2074 				simple_lock(&opg->mdpage.pvh_slock);
2075 				pve = pmap_remove_pv(opg, pm, va, 0);
2076 				pmap_vac_me_harder(opg, pm, 0);
2077 				simple_unlock(&opg->mdpage.pvh_slock);
2078 				oflags = pve->pv_flags;
2079 
2080 				/*
2081 				 * If the old mapping was valid (ref/mod
2082 				 * emulation creates 'invalid' mappings
2083 				 * initially) then make sure to frob
2084 				 * the cache.
2085 				 */
2086 				if ((oflags & PVF_NC) == 0 &&
2087 				    l2pte_valid(opte)) {
2088 					if (PV_BEEN_EXECD(oflags)) {
2089 						pmap_idcache_wbinv_range(pm, va,
2090 						    PAGE_SIZE);
2091 					} else
2092 					if (PV_BEEN_REFD(oflags)) {
2093 						pmap_dcache_wb_range(pm, va,
2094 						    PAGE_SIZE, TRUE,
2095 						    (oflags & PVF_WRITE) == 0);
2096 					}
2097 				}
2098 			} else
2099 			if ((pve = pool_get(&pmap_pv_pool, PR_NOWAIT)) == NULL){
2100 				if ((flags & PMAP_CANFAIL) == 0)
2101 					panic("pmap_enter: no pv entries");
2102 
2103 				if (pm != pmap_kernel())
2104 					pmap_free_l2_bucket(pm, l2b, 0);
2105 				pmap_release_pmap_lock(pm);
2106 				PMAP_MAP_TO_HEAD_UNLOCK();
2107 				NPDEBUG(PDB_ENTER,
2108 				    printf("pmap_enter: ENOMEM\n"));
2109 				return (ENOMEM);
2110 			}
2111 
2112 			pmap_enter_pv(pg, pve, pm, va, nflags);
2113 		}
2114 	} else {
2115 		/*
2116 		 * We're mapping an unmanaged page.
2117 		 * These are always readable, and possibly writable, from
2118 		 * the get go as we don't need to track ref/mod status.
2119 		 */
2120 		npte |= L2_S_PROTO;
2121 		if (prot & VM_PROT_WRITE)
2122 			npte |= L2_S_PROT_W;
2123 
2124 		/*
2125 		 * Make sure the vector table is mapped cacheable
2126 		 */
2127 		if (pm != pmap_kernel() && va == vector_page)
2128 			npte |= pte_l2_s_cache_mode;
2129 
2130 		if (opg) {
2131 			/*
2132 			 * Looks like there's an existing 'managed' mapping
2133 			 * at this address.
2134 			 */
2135 			simple_lock(&opg->mdpage.pvh_slock);
2136 			pve = pmap_remove_pv(opg, pm, va, 0);
2137 			pmap_vac_me_harder(opg, pm, 0);
2138 			simple_unlock(&opg->mdpage.pvh_slock);
2139 			oflags = pve->pv_flags;
2140 
2141 			if ((oflags & PVF_NC) == 0 && l2pte_valid(opte)) {
2142 				if (PV_BEEN_EXECD(oflags))
2143 					pmap_idcache_wbinv_range(pm, va,
2144 					    PAGE_SIZE);
2145 				else
2146 				if (PV_BEEN_REFD(oflags))
2147 					pmap_dcache_wb_range(pm, va, PAGE_SIZE,
2148 					    TRUE, (oflags & PVF_WRITE) == 0);
2149 			}
2150 			pool_put(&pmap_pv_pool, pve);
2151 		}
2152 	}
2153 
2154 	/*
2155 	 * Make sure userland mappings get the right permissions
2156 	 */
2157 	if (pm != pmap_kernel() && va != vector_page)
2158 		npte |= L2_S_PROT_U;
2159 
2160 	/*
2161 	 * Keep the stats up to date
2162 	 */
2163 	if (opte == 0) {
2164 		l2b->l2b_occupancy++;
2165 		pm->pm_stats.resident_count++;
2166 	}
2167 
2168 	NPDEBUG(PDB_ENTER,
2169 	    printf("pmap_enter: opte 0x%08x npte 0x%08x\n", opte, npte));
2170 
2171 	/*
2172 	 * If this is just a wiring change, the two PTEs will be
2173 	 * identical, so there's no need to update the page table.
2174 	 */
2175 	if (npte != opte) {
2176 		boolean_t is_cached = pmap_is_cached(pm);
2177 
2178 		*ptep = npte;
2179 		if (is_cached) {
2180 			/*
2181 			 * We only need to frob the cache/tlb if this pmap
2182 			 * is current
2183 			 */
2184 			PTE_SYNC(ptep);
2185 			if (va != vector_page && l2pte_valid(npte)) {
2186 				/*
2187 				 * This mapping is likely to be accessed as
2188 				 * soon as we return to userland. Fix up the
2189 				 * L1 entry to avoid taking another
2190 				 * page/domain fault.
2191 				 */
2192 				pd_entry_t *pl1pd, l1pd;
2193 
2194 				pl1pd = &pm->pm_l1->l1_kva[L1_IDX(va)];
2195 				l1pd = l2b->l2b_phys | L1_C_DOM(pm->pm_domain) |
2196 				    L1_C_PROTO;
2197 				if (*pl1pd != l1pd) {
2198 					*pl1pd = l1pd;
2199 					PTE_SYNC(pl1pd);
2200 				}
2201 			}
2202 		}
2203 
2204 		if (PV_BEEN_EXECD(oflags))
2205 			pmap_tlb_flushID_SE(pm, va);
2206 		else
2207 		if (PV_BEEN_REFD(oflags))
2208 			pmap_tlb_flushD_SE(pm, va);
2209 
2210 		NPDEBUG(PDB_ENTER,
2211 		    printf("pmap_enter: is_cached %d cs 0x%08x\n",
2212 		    is_cached, pm->pm_cstate.cs_all));
2213 
2214 		if (pg != NULL) {
2215 			simple_lock(&pg->mdpage.pvh_slock);
2216 			pmap_vac_me_harder(pg, pm, va);
2217 			simple_unlock(&pg->mdpage.pvh_slock);
2218 		}
2219 	}
2220 
2221 	pmap_release_pmap_lock(pm);
2222 	PMAP_MAP_TO_HEAD_UNLOCK();
2223 
2224 	return (0);
2225 }
2226 
2227 /*
2228  * pmap_remove()
2229  *
2230  * pmap_remove is responsible for nuking a number of mappings for a range
2231  * of virtual address space in the current pmap. To do this efficiently
2232  * is interesting, because in a number of cases a wide virtual address
2233  * range may be supplied that contains few actual mappings. So, the
2234  * optimisations are:
2235  *  1. Skip over hunks of address space for which no L1 or L2 entry exists.
2236  *  2. Build up a list of pages we've hit, up to a maximum, so we can
2237  *     maybe do just a partial cache clean. This path of execution is
2238  *     complicated by the fact that the cache must be flushed _before_
2239  *     the PTE is nuked, being a VAC :-)
2240  *  3. If we're called after UVM calls pmap_remove_all(), we can defer
2241  *     all invalidations until pmap_update(), since pmap_remove_all() has
2242  *     already flushed the cache.
2243  *  4. Maybe later fast-case a single page, but I don't think this is
2244  *     going to make _that_ much difference overall.
2245  */
2246 
2247 #define	PMAP_REMOVE_CLEAN_LIST_SIZE	3
2248 
2249 void
2250 pmap_do_remove(pmap_t pm, vaddr_t sva, vaddr_t eva, int skip_wired)
2251 {
2252 	struct l2_bucket *l2b;
2253 	vaddr_t next_bucket;
2254 	pt_entry_t *ptep;
2255 	u_int cleanlist_idx, total, cnt;
2256 	struct {
2257 		vaddr_t va;
2258 		pt_entry_t *pte;
2259 	} cleanlist[PMAP_REMOVE_CLEAN_LIST_SIZE];
2260 	u_int mappings, is_exec, is_refd;
2261 
2262 	NPDEBUG(PDB_REMOVE, printf("pmap_do_remove: pmap=%p sva=%08lx "
2263 	    "eva=%08lx\n", pm, sva, eva));
2264 
2265 	/*
2266 	 * we lock in the pmap => pv_head direction
2267 	 */
2268 	PMAP_MAP_TO_HEAD_LOCK();
2269 	pmap_acquire_pmap_lock(pm);
2270 
2271 	if (pm->pm_remove_all || !pmap_is_cached(pm)) {
2272 		cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
2273 		if (pm->pm_cstate.cs_tlb == 0)
2274 			pm->pm_remove_all = TRUE;
2275 	} else
2276 		cleanlist_idx = 0;
2277 
2278 	total = 0;
2279 
2280 	while (sva < eva) {
2281 		/*
2282 		 * Do one L2 bucket's worth at a time.
2283 		 */
2284 		next_bucket = L2_NEXT_BUCKET(sva);
2285 		if (next_bucket > eva)
2286 			next_bucket = eva;
2287 
2288 		l2b = pmap_get_l2_bucket(pm, sva);
2289 		if (l2b == NULL) {
2290 			sva = next_bucket;
2291 			continue;
2292 		}
2293 
2294 		ptep = &l2b->l2b_kva[l2pte_index(sva)];
2295 
2296 		for (mappings = 0; sva < next_bucket; sva += PAGE_SIZE, ptep++){
2297 			struct vm_page *pg;
2298 			pt_entry_t pte;
2299 			paddr_t pa;
2300 
2301 			pte = *ptep;
2302 
2303 			if (pte == 0) {
2304 				/* Nothing here, move along */
2305 				continue;
2306 			}
2307 
2308 			pa = l2pte_pa(pte);
2309 			is_exec = 0;
2310 			is_refd = 1;
2311 
2312 			/*
2313 			 * Update flags. In a number of circumstances,
2314 			 * we could cluster a lot of these and do a
2315 			 * number of sequential pages in one go.
2316 			 */
2317 			if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
2318 				struct pv_entry *pve;
2319 				simple_lock(&pg->mdpage.pvh_slock);
2320 				pve = pmap_remove_pv(pg, pm, sva, skip_wired);
2321 				pmap_vac_me_harder(pg, pm, 0);
2322 				simple_unlock(&pg->mdpage.pvh_slock);
2323 				if (pve != NULL) {
2324 					if (pm->pm_remove_all == FALSE) {
2325 						is_exec =
2326 						   PV_BEEN_EXECD(pve->pv_flags);
2327 						is_refd =
2328 						   PV_BEEN_REFD(pve->pv_flags);
2329 					}
2330 					pool_put(&pmap_pv_pool, pve);
2331 				} else
2332 				if (skip_wired) {
2333 					/* The mapping is wired. Skip it */
2334 					continue;
2335 				}
2336 			} else
2337 			if (skip_wired) {
2338 				/* Unmanaged pages are always wired. */
2339 				continue;
2340 			}
2341 
2342 			mappings++;
2343 
2344 			if (!l2pte_valid(pte)) {
2345 				/*
2346 				 * Ref/Mod emulation is still active for this
2347 				 * mapping, therefore it is has not yet been
2348 				 * accessed. No need to frob the cache/tlb.
2349 				 */
2350 				*ptep = 0;
2351 				PTE_SYNC_CURRENT(pm, ptep);
2352 				continue;
2353 			}
2354 
2355 			if (cleanlist_idx < PMAP_REMOVE_CLEAN_LIST_SIZE) {
2356 				/* Add to the clean list. */
2357 				cleanlist[cleanlist_idx].pte = ptep;
2358 				cleanlist[cleanlist_idx].va =
2359 				    sva | (is_exec & 1);
2360 				cleanlist_idx++;
2361 			} else
2362 			if (cleanlist_idx == PMAP_REMOVE_CLEAN_LIST_SIZE) {
2363 				/* Nuke everything if needed. */
2364 				pmap_idcache_wbinv_all(pm);
2365 				pmap_tlb_flushID(pm);
2366 
2367 				/*
2368 				 * Roll back the previous PTE list,
2369 				 * and zero out the current PTE.
2370 				 */
2371 				for (cnt = 0;
2372 				     cnt < PMAP_REMOVE_CLEAN_LIST_SIZE; cnt++) {
2373 					*cleanlist[cnt].pte = 0;
2374 				}
2375 				*ptep = 0;
2376 				PTE_SYNC(ptep);
2377 				cleanlist_idx++;
2378 				pm->pm_remove_all = TRUE;
2379 			} else {
2380 				*ptep = 0;
2381 				PTE_SYNC(ptep);
2382 				if (pm->pm_remove_all == FALSE) {
2383 					if (is_exec)
2384 						pmap_tlb_flushID_SE(pm, sva);
2385 					else
2386 					if (is_refd)
2387 						pmap_tlb_flushD_SE(pm, sva);
2388 				}
2389 			}
2390 		}
2391 
2392 		/*
2393 		 * Deal with any left overs
2394 		 */
2395 		if (cleanlist_idx <= PMAP_REMOVE_CLEAN_LIST_SIZE) {
2396 			total += cleanlist_idx;
2397 			for (cnt = 0; cnt < cleanlist_idx; cnt++) {
2398 				if (pm->pm_cstate.cs_all != 0) {
2399 					vaddr_t clva = cleanlist[cnt].va & ~1;
2400 					if (cleanlist[cnt].va & 1) {
2401 						pmap_idcache_wbinv_range(pm,
2402 						    clva, PAGE_SIZE);
2403 						pmap_tlb_flushID_SE(pm, clva);
2404 					} else {
2405 						pmap_dcache_wb_range(pm,
2406 						    clva, PAGE_SIZE, TRUE,
2407 						    FALSE);
2408 						pmap_tlb_flushD_SE(pm, clva);
2409 					}
2410 				}
2411 				*cleanlist[cnt].pte = 0;
2412 				PTE_SYNC_CURRENT(pm, cleanlist[cnt].pte);
2413 			}
2414 
2415 			/*
2416 			 * If it looks like we're removing a whole bunch
2417 			 * of mappings, it's faster to just write-back
2418 			 * the whole cache now and defer TLB flushes until
2419 			 * pmap_update() is called.
2420 			 */
2421 			if (total <= PMAP_REMOVE_CLEAN_LIST_SIZE)
2422 				cleanlist_idx = 0;
2423 			else {
2424 				cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
2425 				pmap_idcache_wbinv_all(pm);
2426 				pm->pm_remove_all = TRUE;
2427 			}
2428 		}
2429 
2430 		pmap_free_l2_bucket(pm, l2b, mappings);
2431 		pm->pm_stats.resident_count -= mappings;
2432 	}
2433 
2434 	pmap_release_pmap_lock(pm);
2435 	PMAP_MAP_TO_HEAD_UNLOCK();
2436 }
2437 
2438 /*
2439  * pmap_kenter_pa: enter an unmanaged, wired kernel mapping
2440  *
2441  * We assume there is already sufficient KVM space available
2442  * to do this, as we can't allocate L2 descriptor tables/metadata
2443  * from here.
2444  */
2445 void
2446 pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot)
2447 {
2448 	struct l2_bucket *l2b;
2449 	pt_entry_t *ptep, opte;
2450 
2451 	NPDEBUG(PDB_KENTER,
2452 	    printf("pmap_kenter_pa: va 0x%08lx, pa 0x%08lx, prot 0x%x\n",
2453 	    va, pa, prot));
2454 
2455 	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2456 	KDASSERT(l2b != NULL);
2457 
2458 	ptep = &l2b->l2b_kva[l2pte_index(va)];
2459 	opte = *ptep;
2460 
2461 	if (l2pte_valid(opte)) {
2462 		cpu_dcache_wbinv_range(va, PAGE_SIZE);
2463 		cpu_tlb_flushD_SE(va);
2464 		cpu_cpwait();
2465 	} else
2466 	if (opte == 0)
2467 		l2b->l2b_occupancy++;
2468 
2469 	*ptep = L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) |
2470 	    pte_l2_s_cache_mode;
2471 	PTE_SYNC(ptep);
2472 }
2473 
2474 void
2475 pmap_kremove(vaddr_t va, vsize_t len)
2476 {
2477 	struct l2_bucket *l2b;
2478 	pt_entry_t *ptep, *sptep, opte;
2479 	vaddr_t next_bucket, eva;
2480 	u_int mappings;
2481 
2482 	NPDEBUG(PDB_KREMOVE, printf("pmap_kremove: va 0x%08lx, len 0x%08lx\n",
2483 	    va, len));
2484 
2485 	eva = va + len;
2486 
2487 	while (va < eva) {
2488 		next_bucket = L2_NEXT_BUCKET(va);
2489 		if (next_bucket > eva)
2490 			next_bucket = eva;
2491 
2492 		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
2493 		KDASSERT(l2b != NULL);
2494 
2495 		sptep = ptep = &l2b->l2b_kva[l2pte_index(va)];
2496 		mappings = 0;
2497 
2498 		while (va < next_bucket) {
2499 			opte = *ptep;
2500 			if (l2pte_valid(opte)) {
2501 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
2502 				cpu_tlb_flushD_SE(va);
2503 			}
2504 			if (opte) {
2505 				*ptep = 0;
2506 				mappings++;
2507 			}
2508 			va += PAGE_SIZE;
2509 			ptep++;
2510 		}
2511 		KDASSERT(mappings <= l2b->l2b_occupancy);
2512 		l2b->l2b_occupancy -= mappings;
2513 		PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
2514 	}
2515 	cpu_cpwait();
2516 }
2517 
2518 boolean_t
2519 pmap_extract(pmap_t pm, vaddr_t va, paddr_t *pap)
2520 {
2521 	struct l2_dtable *l2;
2522 	pd_entry_t *pl1pd, l1pd;
2523 	pt_entry_t *ptep, pte;
2524 	paddr_t pa;
2525 	u_int l1idx;
2526 
2527 	pmap_acquire_pmap_lock(pm);
2528 
2529 	l1idx = L1_IDX(va);
2530 	pl1pd = &pm->pm_l1->l1_kva[l1idx];
2531 	l1pd = *pl1pd;
2532 
2533 	if (l1pte_section_p(l1pd)) {
2534 		/*
2535 		 * These should only happen for pmap_kernel()
2536 		 */
2537 		KDASSERT(pm == pmap_kernel());
2538 		pmap_release_pmap_lock(pm);
2539 		pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
2540 	} else {
2541 		/*
2542 		 * Note that we can't rely on the validity of the L1
2543 		 * descriptor as an indication that a mapping exists.
2544 		 * We have to look it up in the L2 dtable.
2545 		 */
2546 		l2 = pm->pm_l2[L2_IDX(l1idx)];
2547 
2548 		if (l2 == NULL ||
2549 		    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
2550 			pmap_release_pmap_lock(pm);
2551 			return (FALSE);
2552 		}
2553 
2554 		ptep = &ptep[l2pte_index(va)];
2555 		pte = *ptep;
2556 		pmap_release_pmap_lock(pm);
2557 
2558 		if (pte == 0)
2559 			return (FALSE);
2560 
2561 		switch (pte & L2_TYPE_MASK) {
2562 		case L2_TYPE_L:
2563 			pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
2564 			break;
2565 
2566 		default:
2567 			pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
2568 			break;
2569 		}
2570 	}
2571 
2572 	if (pap != NULL)
2573 		*pap = pa;
2574 
2575 	return (TRUE);
2576 }
2577 
2578 void
2579 pmap_protect(pmap_t pm, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
2580 {
2581 	struct l2_bucket *l2b;
2582 	pt_entry_t *ptep, pte;
2583 	vaddr_t next_bucket;
2584 	u_int flags;
2585 	int flush;
2586 
2587 	NPDEBUG(PDB_PROTECT,
2588 	    printf("pmap_protect: pm %p sva 0x%lx eva 0x%lx prot 0x%x\n",
2589 	    pm, sva, eva, prot));
2590 
2591 	if ((prot & VM_PROT_READ) == 0) {
2592 		pmap_remove(pm, sva, eva);
2593 		return;
2594 	}
2595 
2596 	if (prot & VM_PROT_WRITE) {
2597 		/*
2598 		 * If this is a read->write transition, just ignore it and let
2599 		 * uvm_fault() take care of it later.
2600 		 */
2601 		return;
2602 	}
2603 
2604 	PMAP_MAP_TO_HEAD_LOCK();
2605 	pmap_acquire_pmap_lock(pm);
2606 
2607 	/*
2608 	 * OK, at this point, we know we're doing write-protect operation.
2609 	 * If the pmap is active, write-back the range.
2610 	 */
2611 	pmap_dcache_wb_range(pm, sva, eva - sva, FALSE, FALSE);
2612 
2613 	flush = ((eva - sva) >= (PAGE_SIZE * 4)) ? 0 : -1;
2614 	flags = 0;
2615 
2616 	while (sva < eva) {
2617 		next_bucket = L2_NEXT_BUCKET(sva);
2618 		if (next_bucket > eva)
2619 			next_bucket = eva;
2620 
2621 		l2b = pmap_get_l2_bucket(pm, sva);
2622 		if (l2b == NULL) {
2623 			sva = next_bucket;
2624 			continue;
2625 		}
2626 
2627 		ptep = &l2b->l2b_kva[l2pte_index(sva)];
2628 
2629 		while (sva < next_bucket) {
2630 			if ((pte = *ptep) != 0 && (pte & L2_S_PROT_W) != 0) {
2631 				struct vm_page *pg;
2632 				u_int f;
2633 
2634 				pg = PHYS_TO_VM_PAGE(l2pte_pa(pte));
2635 				pte &= ~L2_S_PROT_W;
2636 				*ptep = pte;
2637 				PTE_SYNC(ptep);
2638 
2639 				if (pg != NULL) {
2640 					simple_lock(&pg->mdpage.pvh_slock);
2641 					f = pmap_modify_pv(pg, pm, sva,
2642 					    PVF_WRITE, 0);
2643 					pmap_vac_me_harder(pg, pm, sva);
2644 					simple_unlock(&pg->mdpage.pvh_slock);
2645 				} else
2646 					f = PVF_REF | PVF_EXEC;
2647 
2648 				if (flush >= 0) {
2649 					flush++;
2650 					flags |= f;
2651 				} else
2652 				if (PV_BEEN_EXECD(f))
2653 					pmap_tlb_flushID_SE(pm, sva);
2654 				else
2655 				if (PV_BEEN_REFD(f))
2656 					pmap_tlb_flushD_SE(pm, sva);
2657 			}
2658 
2659 			sva += PAGE_SIZE;
2660 			ptep++;
2661 		}
2662 	}
2663 
2664 	pmap_release_pmap_lock(pm);
2665 	PMAP_MAP_TO_HEAD_UNLOCK();
2666 
2667 	if (flush) {
2668 		if (PV_BEEN_EXECD(flags))
2669 			pmap_tlb_flushID(pm);
2670 		else
2671 		if (PV_BEEN_REFD(flags))
2672 			pmap_tlb_flushD(pm);
2673 	}
2674 }
2675 
2676 void
2677 pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
2678 {
2679 
2680 	NPDEBUG(PDB_PROTECT,
2681 	    printf("pmap_page_protect: pg %p (0x%08lx), prot 0x%x\n",
2682 	    pg, VM_PAGE_TO_PHYS(pg), prot));
2683 
2684 	switch(prot) {
2685 	case VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE:
2686 	case VM_PROT_READ|VM_PROT_WRITE:
2687 		return;
2688 
2689 	case VM_PROT_READ:
2690 	case VM_PROT_READ|VM_PROT_EXECUTE:
2691 		pmap_clearbit(pg, PVF_WRITE);
2692 		break;
2693 
2694 	default:
2695 		pmap_page_remove(pg);
2696 		break;
2697 	}
2698 }
2699 
2700 /*
2701  * pmap_clear_modify:
2702  *
2703  *	Clear the "modified" attribute for a page.
2704  */
2705 boolean_t
2706 pmap_clear_modify(struct vm_page *pg)
2707 {
2708 	boolean_t rv;
2709 
2710 	if (pg->mdpage.pvh_attrs & PVF_MOD) {
2711 		rv = TRUE;
2712 		pmap_clearbit(pg, PVF_MOD);
2713 	} else
2714 		rv = FALSE;
2715 
2716 	return (rv);
2717 }
2718 
2719 /*
2720  * pmap_clear_reference:
2721  *
2722  *	Clear the "referenced" attribute for a page.
2723  */
2724 boolean_t
2725 pmap_clear_reference(struct vm_page *pg)
2726 {
2727 	boolean_t rv;
2728 
2729 	if (pg->mdpage.pvh_attrs & PVF_REF) {
2730 		rv = TRUE;
2731 		pmap_clearbit(pg, PVF_REF);
2732 	} else
2733 		rv = FALSE;
2734 
2735 	return (rv);
2736 }
2737 
2738 /*
2739  * pmap_is_modified:
2740  *
2741  *	Test if a page has the "modified" attribute.
2742  */
2743 /* See <arm/arm32/pmap.h> */
2744 
2745 /*
2746  * pmap_is_referenced:
2747  *
2748  *	Test if a page has the "referenced" attribute.
2749  */
2750 /* See <arm/arm32/pmap.h> */
2751 
2752 int
2753 pmap_fault_fixup(pmap_t pm, vaddr_t va, vm_prot_t ftype, int user)
2754 {
2755 	struct l2_dtable *l2;
2756 	struct l2_bucket *l2b;
2757 	pd_entry_t *pl1pd, l1pd;
2758 	pt_entry_t *ptep, pte;
2759 	paddr_t pa;
2760 	u_int l1idx;
2761 	int rv = 0;
2762 
2763 	PMAP_MAP_TO_HEAD_LOCK();
2764 	pmap_acquire_pmap_lock(pm);
2765 
2766 	l1idx = L1_IDX(va);
2767 
2768 	/*
2769 	 * If there is no l2_dtable for this address, then the process
2770 	 * has no business accessing it.
2771 	 *
2772 	 * Note: This will catch userland processes trying to access
2773 	 * kernel addresses.
2774 	 */
2775 	l2 = pm->pm_l2[L2_IDX(l1idx)];
2776 	if (l2 == NULL)
2777 		goto out;
2778 
2779 	/*
2780 	 * Likewise if there is no L2 descriptor table
2781 	 */
2782 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
2783 	if (l2b->l2b_kva == NULL)
2784 		goto out;
2785 
2786 	/*
2787 	 * Check the PTE itself.
2788 	 */
2789 	ptep = &l2b->l2b_kva[l2pte_index(va)];
2790 	pte = *ptep;
2791 	if (pte == 0)
2792 		goto out;
2793 
2794 	/*
2795 	 * Catch a userland access to the vector page mapped at 0x0
2796 	 */
2797 	if (user && (pte & L2_S_PROT_U) == 0)
2798 		goto out;
2799 
2800 	pa = l2pte_pa(pte);
2801 
2802 	if ((ftype & VM_PROT_WRITE) && (pte & L2_S_PROT_W) == 0) {
2803 		/*
2804 		 * This looks like a good candidate for "page modified"
2805 		 * emulation...
2806 		 */
2807 		struct pv_entry *pv;
2808 		struct vm_page *pg;
2809 
2810 		/* Extract the physical address of the page */
2811 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
2812 			goto out;
2813 
2814 		/* Get the current flags for this page. */
2815 		simple_lock(&pg->mdpage.pvh_slock);
2816 
2817 		pv = pmap_find_pv(pg, pm, va);
2818 		if (pv == NULL) {
2819 	    		simple_unlock(&pg->mdpage.pvh_slock);
2820 			goto out;
2821 		}
2822 
2823 		/*
2824 		 * Do the flags say this page is writable? If not then it
2825 		 * is a genuine write fault. If yes then the write fault is
2826 		 * our fault as we did not reflect the write access in the
2827 		 * PTE. Now we know a write has occurred we can correct this
2828 		 * and also set the modified bit
2829 		 */
2830 		if ((pv->pv_flags & PVF_WRITE) == 0) {
2831 		    	simple_unlock(&pg->mdpage.pvh_slock);
2832 			goto out;
2833 		}
2834 
2835 		NPDEBUG(PDB_FOLLOW,
2836 		    printf("pmap_fault_fixup: mod emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
2837 		    pm, va, VM_PAGE_TO_PHYS(pg)));
2838 
2839 		pg->mdpage.pvh_attrs |= PVF_REF | PVF_MOD;
2840 		pv->pv_flags |= PVF_REF | PVF_MOD;
2841 		simple_unlock(&pg->mdpage.pvh_slock);
2842 
2843 		/*
2844 		 * Re-enable write permissions for the page.  No need to call
2845 		 * pmap_vac_me_harder(), since this is just a
2846 		 * modified-emulation fault, and the PVF_WRITE bit isn't
2847 		 * changing. We've already set the cacheable bits based on
2848 		 * the assumption that we can write to this page.
2849 		 */
2850 		*ptep = (pte & ~L2_TYPE_MASK) | L2_S_PROTO | L2_S_PROT_W;
2851 		PTE_SYNC(ptep);
2852 		rv = 1;
2853 	} else
2854 	if ((pte & L2_TYPE_MASK) == L2_TYPE_INV) {
2855 		/*
2856 		 * This looks like a good candidate for "page referenced"
2857 		 * emulation.
2858 		 */
2859 		struct pv_entry *pv;
2860 		struct vm_page *pg;
2861 
2862 		/* Extract the physical address of the page */
2863 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
2864 			goto out;
2865 
2866 		/* Get the current flags for this page. */
2867 		simple_lock(&pg->mdpage.pvh_slock);
2868 
2869 		pv = pmap_find_pv(pg, pm, va);
2870 		if (pv == NULL) {
2871 	    		simple_unlock(&pg->mdpage.pvh_slock);
2872 			goto out;
2873 		}
2874 
2875 		pg->mdpage.pvh_attrs |= PVF_REF;
2876 		pv->pv_flags |= PVF_REF;
2877 		simple_unlock(&pg->mdpage.pvh_slock);
2878 
2879 		NPDEBUG(PDB_FOLLOW,
2880 		    printf("pmap_fault_fixup: ref emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
2881 		    pm, va, VM_PAGE_TO_PHYS(pg)));
2882 
2883 		*ptep = (pte & ~L2_TYPE_MASK) | L2_S_PROTO;
2884 		PTE_SYNC(ptep);
2885 		rv = 1;
2886 	}
2887 
2888 	/*
2889 	 * We know there is a valid mapping here, so simply
2890 	 * fix up the L1 if necessary.
2891 	 */
2892 	pl1pd = &pm->pm_l1->l1_kva[l1idx];
2893 	l1pd = l2b->l2b_phys | L1_C_DOM(pm->pm_domain) | L1_C_PROTO;
2894 	if (*pl1pd != l1pd) {
2895 		*pl1pd = l1pd;
2896 		PTE_SYNC(pl1pd);
2897 		rv = 1;
2898 	}
2899 
2900 #ifdef CPU_SA110
2901 	/*
2902 	 * There are bugs in the rev K SA110.  This is a check for one
2903 	 * of them.
2904 	 */
2905 	if (rv == 0 && curcpu()->ci_arm_cputype == CPU_ID_SA110 &&
2906 	    curcpu()->ci_arm_cpurev < 3) {
2907 		/* Always current pmap */
2908 		if (l2pte_valid(pte)) {
2909 			extern int kernel_debug;
2910 			if (kernel_debug & 1) {
2911 				struct proc *p = curlwp->l_proc;
2912 				printf("prefetch_abort: page is already "
2913 				    "mapped - pte=%p *pte=%08x\n", ptep, pte);
2914 				printf("prefetch_abort: pc=%08lx proc=%p "
2915 				    "process=%s\n", va, p, p->p_comm);
2916 				printf("prefetch_abort: far=%08x fs=%x\n",
2917 				    cpu_faultaddress(), cpu_faultstatus());
2918 			}
2919 #ifdef DDB
2920 			if (kernel_debug & 2)
2921 				Debugger();
2922 #endif
2923 			rv = 1;
2924 		}
2925 	}
2926 #endif /* CPU_SA110 */
2927 
2928 #ifdef DEBUG
2929 	/*
2930 	 * If 'rv == 0' at this point, it generally indicates that there is a
2931 	 * stale TLB entry for the faulting address. This happens when two or
2932 	 * more processes are sharing an L1. Since we don't flush the TLB on
2933 	 * a context switch between such processes, we can take domain faults
2934 	 * for mappings which exist at the same VA in both processes. EVEN IF
2935 	 * WE'VE RECENTLY FIXED UP THE CORRESPONDING L1 in pmap_enter(), for
2936 	 * example.
2937 	 *
2938 	 * This is extremely likely to happen if pmap_enter() updated the L1
2939 	 * entry for a recently entered mapping. In this case, the TLB is
2940 	 * flushed for the new mapping, but there may still be TLB entries for
2941 	 * other mappings belonging to other processes in the 1MB range
2942 	 * covered by the L1 entry.
2943 	 *
2944 	 * Since 'rv == 0', we know that the L1 already contains the correct
2945 	 * value, so the fault must be due to a stale TLB entry.
2946 	 *
2947 	 * Since we always need to flush the TLB anyway in the case where we
2948 	 * fixed up the L1, or frobbed the L2 PTE, we effectively deal with
2949 	 * stale TLB entries dynamically.
2950 	 *
2951 	 * However, the above condition can ONLY happen if the current L1 is
2952 	 * being shared. If it happens when the L1 is unshared, it indicates
2953 	 * that other parts of the pmap are not doing their job WRT managing
2954 	 * the TLB.
2955 	 */
2956 	if (rv == 0 && pm->pm_l1->l1_domain_use_count == 1) {
2957 		extern int last_fault_code;
2958 		printf("fixup: pm %p, va 0x%lx, ftype %d - nothing to do!\n",
2959 		    pm, va, ftype);
2960 		printf("fixup: l2 %p, l2b %p, ptep %p, pl1pd %p\n",
2961 		    l2, l2b, ptep, pl1pd);
2962 		printf("fixup: pte 0x%x, l1pd 0x%x, last code 0x%x\n",
2963 		    pte, l1pd, last_fault_code);
2964 #ifdef DDB
2965 		Debugger();
2966 #endif
2967 	}
2968 #endif
2969 
2970 	cpu_tlb_flushID_SE(va);
2971 	cpu_cpwait();
2972 
2973 	rv = 1;
2974 
2975 out:
2976 	pmap_release_pmap_lock(pm);
2977 	PMAP_MAP_TO_HEAD_UNLOCK();
2978 
2979 	return (rv);
2980 }
2981 
2982 /*
2983  * pmap_collect: free resources held by a pmap
2984  *
2985  * => optional function.
2986  * => called when a process is swapped out to free memory.
2987  */
2988 void
2989 pmap_collect(pmap_t pm)
2990 {
2991 
2992 	pmap_idcache_wbinv_all(pm);
2993 	pm->pm_remove_all = TRUE;
2994 	pmap_do_remove(pm, VM_MIN_ADDRESS, VM_MAX_ADDRESS, 1);
2995 	pmap_update(pm);
2996 }
2997 
2998 /*
2999  * Routine:	pmap_procwr
3000  *
3001  * Function:
3002  *	Synchronize caches corresponding to [addr, addr+len) in p.
3003  *
3004  */
3005 void
3006 pmap_procwr(struct proc *p, vaddr_t va, int len)
3007 {
3008 	/* We only need to do anything if it is the current process. */
3009 	if (p == curproc)
3010 		cpu_icache_sync_range(va, len);
3011 }
3012 
3013 /*
3014  * Routine:	pmap_unwire
3015  * Function:	Clear the wired attribute for a map/virtual-address pair.
3016  *
3017  * In/out conditions:
3018  *		The mapping must already exist in the pmap.
3019  */
3020 void
3021 pmap_unwire(pmap_t pm, vaddr_t va)
3022 {
3023 	struct l2_bucket *l2b;
3024 	pt_entry_t *ptep, pte;
3025 	struct vm_page *pg;
3026 	paddr_t pa;
3027 
3028 	NPDEBUG(PDB_WIRING, printf("pmap_unwire: pm %p, va 0x%08lx\n", pm, va));
3029 
3030 	PMAP_MAP_TO_HEAD_LOCK();
3031 	pmap_acquire_pmap_lock(pm);
3032 
3033 	l2b = pmap_get_l2_bucket(pm, va);
3034 	KDASSERT(l2b != NULL);
3035 
3036 	ptep = &l2b->l2b_kva[l2pte_index(va)];
3037 	pte = *ptep;
3038 
3039 	/* Extract the physical address of the page */
3040 	pa = l2pte_pa(pte);
3041 
3042 	if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
3043 		/* Update the wired bit in the pv entry for this page. */
3044 		simple_lock(&pg->mdpage.pvh_slock);
3045 		(void) pmap_modify_pv(pg, pm, va, PVF_WIRED, 0);
3046 		simple_unlock(&pg->mdpage.pvh_slock);
3047 	}
3048 
3049 	pmap_release_pmap_lock(pm);
3050 	PMAP_MAP_TO_HEAD_UNLOCK();
3051 }
3052 
3053 void
3054 pmap_activate(struct lwp *l)
3055 {
3056 	pmap_t pm;
3057 	struct pcb *pcb;
3058 	int s;
3059 
3060 	pm = l->l_proc->p_vmspace->vm_map.pmap;
3061 	pcb = &l->l_addr->u_pcb;
3062 
3063 	pmap_set_pcb_pagedir(pm, pcb);
3064 
3065 	if (l == curlwp) {
3066 		u_int cur_dacr, cur_ttb;
3067 
3068 		__asm volatile("mrc p15, 0, %0, c2, c0, 0" : "=r"(cur_ttb));
3069 		__asm volatile("mrc p15, 0, %0, c3, c0, 0" : "=r"(cur_dacr));
3070 
3071 		cur_ttb &= ~(L1_TABLE_SIZE - 1);
3072 
3073 		if (cur_ttb == (u_int)pcb->pcb_pagedir &&
3074 		    cur_dacr == pcb->pcb_dacr) {
3075 			/*
3076 			 * No need to switch address spaces.
3077 			 */
3078 			return;
3079 		}
3080 
3081 		s = splhigh();
3082 		pmap_acquire_pmap_lock(pm);
3083 		disable_interrupts(I32_bit | F32_bit);
3084 
3085 		/*
3086 		 * We MUST, I repeat, MUST fix up the L1 entry corresponding
3087 		 * to 'vector_page' in the incoming L1 table before switching
3088 		 * to it otherwise subsequent interrupts/exceptions (including
3089 		 * domain faults!) will jump into hyperspace.
3090 		 */
3091 		if (pcb->pcb_pl1vec) {
3092 			*pcb->pcb_pl1vec = pcb->pcb_l1vec;
3093 			/*
3094 			 * Don't need to PTE_SYNC() at this point since
3095 			 * cpu_setttb() is about to flush both the cache
3096 			 * and the TLB.
3097 			 */
3098 		}
3099 
3100 		cpu_domains(pcb->pcb_dacr);
3101 		cpu_setttb(pcb->pcb_pagedir);
3102 
3103 		enable_interrupts(I32_bit | F32_bit);
3104 
3105 		/*
3106 		 * Flag any previous userland pmap as being NOT
3107 		 * resident in the cache/tlb.
3108 		 */
3109 		if (pmap_cache_state && pmap_cache_state != &pm->pm_cstate)
3110 			pmap_cache_state->cs_all = 0;
3111 
3112 		/*
3113 		 * The new pmap, however, IS resident.
3114 		 */
3115 		pmap_cache_state = &pm->pm_cstate;
3116 		pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
3117 		pmap_release_pmap_lock(pm);
3118 		splx(s);
3119 	}
3120 }
3121 
3122 void
3123 pmap_deactivate(struct lwp *l)
3124 {
3125 }
3126 
3127 void
3128 pmap_update(pmap_t pm)
3129 {
3130 
3131 	if (pm->pm_remove_all) {
3132 		/*
3133 		 * Finish up the pmap_remove_all() optimisation by flushing
3134 		 * the TLB.
3135 		 */
3136 		pmap_tlb_flushID(pm);
3137 		pm->pm_remove_all = FALSE;
3138 	}
3139 
3140 	if (pmap_is_current(pm)) {
3141 		/*
3142 		 * If we're dealing with a current userland pmap, move its L1
3143 		 * to the end of the LRU.
3144 		 */
3145 		if (pm != pmap_kernel())
3146 			pmap_use_l1(pm);
3147 
3148 		/*
3149 		 * We can assume we're done with frobbing the cache/tlb for
3150 		 * now. Make sure any future pmap ops don't skip cache/tlb
3151 		 * flushes.
3152 		 */
3153 		pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
3154 	}
3155 
3156 	/*
3157 	 * make sure TLB/cache operations have completed.
3158 	 */
3159 	cpu_cpwait();
3160 }
3161 
3162 void
3163 pmap_remove_all(pmap_t pm)
3164 {
3165 
3166 	/*
3167 	 * The vmspace described by this pmap is about to be torn down.
3168 	 * Until pmap_update() is called, UVM will only make calls
3169 	 * to pmap_remove(). We can make life much simpler by flushing
3170 	 * the cache now, and deferring TLB invalidation to pmap_update().
3171 	 */
3172 	pmap_idcache_wbinv_all(pm);
3173 	pm->pm_remove_all = TRUE;
3174 }
3175 
3176 /*
3177  * Retire the given physical map from service.
3178  * Should only be called if the map contains no valid mappings.
3179  */
3180 void
3181 pmap_destroy(pmap_t pm)
3182 {
3183 	u_int count;
3184 
3185 	if (pm == NULL)
3186 		return;
3187 
3188 	if (pm->pm_remove_all) {
3189 		pmap_tlb_flushID(pm);
3190 		pm->pm_remove_all = FALSE;
3191 	}
3192 
3193 	/*
3194 	 * Drop reference count
3195 	 */
3196 	simple_lock(&pm->pm_lock);
3197 	count = --pm->pm_obj.uo_refs;
3198 	simple_unlock(&pm->pm_lock);
3199 	if (count > 0) {
3200 		if (pmap_is_current(pm)) {
3201 			if (pm != pmap_kernel())
3202 				pmap_use_l1(pm);
3203 			pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
3204 		}
3205 		return;
3206 	}
3207 
3208 	/*
3209 	 * reference count is zero, free pmap resources and then free pmap.
3210 	 */
3211 
3212 	if (vector_page < KERNEL_BASE) {
3213 		struct pcb *pcb = &lwp0.l_addr->u_pcb;
3214 
3215 		if (pmap_is_current(pm)) {
3216 			/*
3217 			 * Frob the L1 entry corresponding to the vector
3218 			 * page so that it contains the kernel pmap's domain
3219 			 * number. This will ensure pmap_remove() does not
3220 			 * pull the current vector page out from under us.
3221 			 */
3222 			disable_interrupts(I32_bit | F32_bit);
3223 			*pcb->pcb_pl1vec = pcb->pcb_l1vec;
3224 			cpu_domains(pcb->pcb_dacr);
3225 			cpu_setttb(pcb->pcb_pagedir);
3226 			enable_interrupts(I32_bit | F32_bit);
3227 		}
3228 
3229 		/* Remove the vector page mapping */
3230 		pmap_remove(pm, vector_page, vector_page + PAGE_SIZE);
3231 		pmap_update(pm);
3232 
3233 		/*
3234 		 * Make sure cpu_switch(), et al, DTRT. This is safe to do
3235 		 * since this process has no remaining mappings of its own.
3236 		 */
3237 		curpcb->pcb_pl1vec = pcb->pcb_pl1vec;
3238 		curpcb->pcb_l1vec = pcb->pcb_l1vec;
3239 		curpcb->pcb_dacr = pcb->pcb_dacr;
3240 		curpcb->pcb_pagedir = pcb->pcb_pagedir;
3241 	}
3242 
3243 	LIST_REMOVE(pm, pm_list);
3244 
3245 	pmap_free_l1(pm);
3246 
3247 	/* return the pmap to the pool */
3248 	pool_cache_put(&pmap_pmap_cache, pm);
3249 }
3250 
3251 
3252 /*
3253  * void pmap_reference(pmap_t pm)
3254  *
3255  * Add a reference to the specified pmap.
3256  */
3257 void
3258 pmap_reference(pmap_t pm)
3259 {
3260 
3261 	if (pm == NULL)
3262 		return;
3263 
3264 	pmap_use_l1(pm);
3265 
3266 	simple_lock(&pm->pm_lock);
3267 	pm->pm_obj.uo_refs++;
3268 	simple_unlock(&pm->pm_lock);
3269 }
3270 
3271 /*
3272  * pmap_zero_page()
3273  *
3274  * Zero a given physical page by mapping it at a page hook point.
3275  * In doing the zero page op, the page we zero is mapped cachable, as with
3276  * StrongARM accesses to non-cached pages are non-burst making writing
3277  * _any_ bulk data very slow.
3278  */
3279 #if (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0
3280 void
3281 pmap_zero_page_generic(paddr_t phys)
3282 {
3283 #ifdef DEBUG
3284 	struct vm_page *pg = PHYS_TO_VM_PAGE(phys);
3285 
3286 	if (pg->mdpage.pvh_list != NULL)
3287 		panic("pmap_zero_page: page has mappings");
3288 #endif
3289 
3290 	KDASSERT((phys & PGOFSET) == 0);
3291 
3292 	/*
3293 	 * Hook in the page, zero it, and purge the cache for that
3294 	 * zeroed page. Invalidate the TLB as needed.
3295 	 */
3296 	*cdst_pte = L2_S_PROTO | phys |
3297 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
3298 	PTE_SYNC(cdst_pte);
3299 	cpu_tlb_flushD_SE(cdstp);
3300 	cpu_cpwait();
3301 	bzero_page(cdstp);
3302 	cpu_dcache_wbinv_range(cdstp, PAGE_SIZE);
3303 }
3304 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0 */
3305 
3306 #if ARM_MMU_XSCALE == 1
3307 void
3308 pmap_zero_page_xscale(paddr_t phys)
3309 {
3310 #ifdef DEBUG
3311 	struct vm_page *pg = PHYS_TO_VM_PAGE(phys);
3312 
3313 	if (pg->mdpage.pvh_list != NULL)
3314 		panic("pmap_zero_page: page has mappings");
3315 #endif
3316 
3317 	KDASSERT((phys & PGOFSET) == 0);
3318 
3319 	/*
3320 	 * Hook in the page, zero it, and purge the cache for that
3321 	 * zeroed page. Invalidate the TLB as needed.
3322 	 */
3323 	*cdst_pte = L2_S_PROTO | phys |
3324 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) |
3325 	    L2_C | L2_XSCALE_T_TEX(TEX_XSCALE_X);	/* mini-data */
3326 	PTE_SYNC(cdst_pte);
3327 	cpu_tlb_flushD_SE(cdstp);
3328 	cpu_cpwait();
3329 	bzero_page(cdstp);
3330 	xscale_cache_clean_minidata();
3331 }
3332 #endif /* ARM_MMU_XSCALE == 1 */
3333 
3334 /* pmap_pageidlezero()
3335  *
3336  * The same as above, except that we assume that the page is not
3337  * mapped.  This means we never have to flush the cache first.  Called
3338  * from the idle loop.
3339  */
3340 boolean_t
3341 pmap_pageidlezero(paddr_t phys)
3342 {
3343 	unsigned int i;
3344 	int *ptr;
3345 	boolean_t rv = TRUE;
3346 #ifdef DEBUG
3347 	struct vm_page *pg;
3348 
3349 	pg = PHYS_TO_VM_PAGE(phys);
3350 	if (pg->mdpage.pvh_list != NULL)
3351 		panic("pmap_pageidlezero: page has mappings");
3352 #endif
3353 
3354 	KDASSERT((phys & PGOFSET) == 0);
3355 
3356 	/*
3357 	 * Hook in the page, zero it, and purge the cache for that
3358 	 * zeroed page. Invalidate the TLB as needed.
3359 	 */
3360 	*cdst_pte = L2_S_PROTO | phys |
3361 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
3362 	PTE_SYNC(cdst_pte);
3363 	cpu_tlb_flushD_SE(cdstp);
3364 	cpu_cpwait();
3365 
3366 	for (i = 0, ptr = (int *)cdstp;
3367 			i < (PAGE_SIZE / sizeof(int)); i++) {
3368 		if (sched_whichqs != 0) {
3369 			/*
3370 			 * A process has become ready.  Abort now,
3371 			 * so we don't keep it waiting while we
3372 			 * do slow memory access to finish this
3373 			 * page.
3374 			 */
3375 			rv = FALSE;
3376 			break;
3377 		}
3378 		*ptr++ = 0;
3379 	}
3380 
3381 	if (rv)
3382 		/*
3383 		 * if we aborted we'll rezero this page again later so don't
3384 		 * purge it unless we finished it
3385 		 */
3386 		cpu_dcache_wbinv_range(cdstp, PAGE_SIZE);
3387 
3388 	return (rv);
3389 }
3390 
3391 /*
3392  * pmap_copy_page()
3393  *
3394  * Copy one physical page into another, by mapping the pages into
3395  * hook points. The same comment regarding cachability as in
3396  * pmap_zero_page also applies here.
3397  */
3398 #if (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0
3399 void
3400 pmap_copy_page_generic(paddr_t src, paddr_t dst)
3401 {
3402 	struct vm_page *src_pg = PHYS_TO_VM_PAGE(src);
3403 #ifdef DEBUG
3404 	struct vm_page *dst_pg = PHYS_TO_VM_PAGE(dst);
3405 
3406 	if (dst_pg->mdpage.pvh_list != NULL)
3407 		panic("pmap_copy_page: dst page has mappings");
3408 #endif
3409 
3410 	KDASSERT((src & PGOFSET) == 0);
3411 	KDASSERT((dst & PGOFSET) == 0);
3412 
3413 	/*
3414 	 * Clean the source page.  Hold the source page's lock for
3415 	 * the duration of the copy so that no other mappings can
3416 	 * be created while we have a potentially aliased mapping.
3417 	 */
3418 	simple_lock(&src_pg->mdpage.pvh_slock);
3419 	(void) pmap_clean_page(src_pg->mdpage.pvh_list, TRUE);
3420 
3421 	/*
3422 	 * Map the pages into the page hook points, copy them, and purge
3423 	 * the cache for the appropriate page. Invalidate the TLB
3424 	 * as required.
3425 	 */
3426 	*csrc_pte = L2_S_PROTO | src |
3427 	    L2_S_PROT(PTE_KERNEL, VM_PROT_READ) | pte_l2_s_cache_mode;
3428 	PTE_SYNC(csrc_pte);
3429 	*cdst_pte = L2_S_PROTO | dst |
3430 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
3431 	PTE_SYNC(cdst_pte);
3432 	cpu_tlb_flushD_SE(csrcp);
3433 	cpu_tlb_flushD_SE(cdstp);
3434 	cpu_cpwait();
3435 	bcopy_page(csrcp, cdstp);
3436 	cpu_dcache_inv_range(csrcp, PAGE_SIZE);
3437 	simple_unlock(&src_pg->mdpage.pvh_slock); /* cache is safe again */
3438 	cpu_dcache_wbinv_range(cdstp, PAGE_SIZE);
3439 }
3440 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0 */
3441 
3442 #if ARM_MMU_XSCALE == 1
3443 void
3444 pmap_copy_page_xscale(paddr_t src, paddr_t dst)
3445 {
3446 	struct vm_page *src_pg = PHYS_TO_VM_PAGE(src);
3447 #ifdef DEBUG
3448 	struct vm_page *dst_pg = PHYS_TO_VM_PAGE(dst);
3449 
3450 	if (dst_pg->mdpage.pvh_list != NULL)
3451 		panic("pmap_copy_page: dst page has mappings");
3452 #endif
3453 
3454 	KDASSERT((src & PGOFSET) == 0);
3455 	KDASSERT((dst & PGOFSET) == 0);
3456 
3457 	/*
3458 	 * Clean the source page.  Hold the source page's lock for
3459 	 * the duration of the copy so that no other mappings can
3460 	 * be created while we have a potentially aliased mapping.
3461 	 */
3462 	simple_lock(&src_pg->mdpage.pvh_slock);
3463 	(void) pmap_clean_page(src_pg->mdpage.pvh_list, TRUE);
3464 
3465 	/*
3466 	 * Map the pages into the page hook points, copy them, and purge
3467 	 * the cache for the appropriate page. Invalidate the TLB
3468 	 * as required.
3469 	 */
3470 	*csrc_pte = L2_S_PROTO | src |
3471 	    L2_S_PROT(PTE_KERNEL, VM_PROT_READ) |
3472 	    L2_C | L2_XSCALE_T_TEX(TEX_XSCALE_X);	/* mini-data */
3473 	PTE_SYNC(csrc_pte);
3474 	*cdst_pte = L2_S_PROTO | dst |
3475 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) |
3476 	    L2_C | L2_XSCALE_T_TEX(TEX_XSCALE_X);	/* mini-data */
3477 	PTE_SYNC(cdst_pte);
3478 	cpu_tlb_flushD_SE(csrcp);
3479 	cpu_tlb_flushD_SE(cdstp);
3480 	cpu_cpwait();
3481 	bcopy_page(csrcp, cdstp);
3482 	simple_unlock(&src_pg->mdpage.pvh_slock); /* cache is safe again */
3483 	xscale_cache_clean_minidata();
3484 }
3485 #endif /* ARM_MMU_XSCALE == 1 */
3486 
3487 /*
3488  * void pmap_virtual_space(vaddr_t *start, vaddr_t *end)
3489  *
3490  * Return the start and end addresses of the kernel's virtual space.
3491  * These values are setup in pmap_bootstrap and are updated as pages
3492  * are allocated.
3493  */
3494 void
3495 pmap_virtual_space(vaddr_t *start, vaddr_t *end)
3496 {
3497 	*start = virtual_avail;
3498 	*end = virtual_end;
3499 }
3500 
3501 /*
3502  * Helper function for pmap_grow_l2_bucket()
3503  */
3504 static inline int
3505 pmap_grow_map(vaddr_t va, pt_entry_t cache_mode, paddr_t *pap)
3506 {
3507 	struct l2_bucket *l2b;
3508 	pt_entry_t *ptep;
3509 	paddr_t pa;
3510 
3511 	if (uvm.page_init_done == FALSE) {
3512 		if (uvm_page_physget(&pa) == FALSE)
3513 			return (1);
3514 	} else {
3515 		struct vm_page *pg;
3516 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_USERESERVE);
3517 		if (pg == NULL)
3518 			return (1);
3519 		pa = VM_PAGE_TO_PHYS(pg);
3520 	}
3521 
3522 	if (pap)
3523 		*pap = pa;
3524 
3525 	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
3526 	KDASSERT(l2b != NULL);
3527 
3528 	ptep = &l2b->l2b_kva[l2pte_index(va)];
3529 	*ptep = L2_S_PROTO | pa | cache_mode |
3530 	    L2_S_PROT(PTE_KERNEL, VM_PROT_READ | VM_PROT_WRITE);
3531 	PTE_SYNC(ptep);
3532 	memset((void *)va, 0, PAGE_SIZE);
3533 	return (0);
3534 }
3535 
3536 /*
3537  * This is the same as pmap_alloc_l2_bucket(), except that it is only
3538  * used by pmap_growkernel().
3539  */
3540 static inline struct l2_bucket *
3541 pmap_grow_l2_bucket(pmap_t pm, vaddr_t va)
3542 {
3543 	struct l2_dtable *l2;
3544 	struct l2_bucket *l2b;
3545 	u_short l1idx;
3546 	vaddr_t nva;
3547 
3548 	l1idx = L1_IDX(va);
3549 
3550 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
3551 		/*
3552 		 * No mapping at this address, as there is
3553 		 * no entry in the L1 table.
3554 		 * Need to allocate a new l2_dtable.
3555 		 */
3556 		nva = pmap_kernel_l2dtable_kva;
3557 		if ((nva & PGOFSET) == 0) {
3558 			/*
3559 			 * Need to allocate a backing page
3560 			 */
3561 			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
3562 				return (NULL);
3563 		}
3564 
3565 		l2 = (struct l2_dtable *)nva;
3566 		nva += sizeof(struct l2_dtable);
3567 
3568 		if ((nva & PGOFSET) < (pmap_kernel_l2dtable_kva & PGOFSET)) {
3569 			/*
3570 			 * The new l2_dtable straddles a page boundary.
3571 			 * Map in another page to cover it.
3572 			 */
3573 			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
3574 				return (NULL);
3575 		}
3576 
3577 		pmap_kernel_l2dtable_kva = nva;
3578 
3579 		/*
3580 		 * Link it into the parent pmap
3581 		 */
3582 		pm->pm_l2[L2_IDX(l1idx)] = l2;
3583 	}
3584 
3585 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
3586 
3587 	/*
3588 	 * Fetch pointer to the L2 page table associated with the address.
3589 	 */
3590 	if (l2b->l2b_kva == NULL) {
3591 		pt_entry_t *ptep;
3592 
3593 		/*
3594 		 * No L2 page table has been allocated. Chances are, this
3595 		 * is because we just allocated the l2_dtable, above.
3596 		 */
3597 		nva = pmap_kernel_l2ptp_kva;
3598 		ptep = (pt_entry_t *)nva;
3599 		if ((nva & PGOFSET) == 0) {
3600 			/*
3601 			 * Need to allocate a backing page
3602 			 */
3603 			if (pmap_grow_map(nva, pte_l2_s_cache_mode_pt,
3604 			    &pmap_kernel_l2ptp_phys))
3605 				return (NULL);
3606 			PTE_SYNC_RANGE(ptep, PAGE_SIZE / sizeof(pt_entry_t));
3607 		}
3608 
3609 		l2->l2_occupancy++;
3610 		l2b->l2b_kva = ptep;
3611 		l2b->l2b_l1idx = l1idx;
3612 		l2b->l2b_phys = pmap_kernel_l2ptp_phys;
3613 
3614 		pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
3615 		pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
3616 	}
3617 
3618 	return (l2b);
3619 }
3620 
3621 vaddr_t
3622 pmap_growkernel(vaddr_t maxkvaddr)
3623 {
3624 	pmap_t kpm = pmap_kernel();
3625 	struct l1_ttable *l1;
3626 	struct l2_bucket *l2b;
3627 	pd_entry_t *pl1pd;
3628 	int s;
3629 
3630 	if (maxkvaddr <= pmap_curmaxkvaddr)
3631 		goto out;		/* we are OK */
3632 
3633 	NPDEBUG(PDB_GROWKERN,
3634 	    printf("pmap_growkernel: growing kernel from 0x%lx to 0x%lx\n",
3635 	    pmap_curmaxkvaddr, maxkvaddr));
3636 
3637 	KDASSERT(maxkvaddr <= virtual_end);
3638 
3639 	/*
3640 	 * whoops!   we need to add kernel PTPs
3641 	 */
3642 
3643 	s = splhigh();	/* to be safe */
3644 	simple_lock(&kpm->pm_lock);
3645 
3646 	/* Map 1MB at a time */
3647 	for (; pmap_curmaxkvaddr < maxkvaddr; pmap_curmaxkvaddr += L1_S_SIZE) {
3648 
3649 		l2b = pmap_grow_l2_bucket(kpm, pmap_curmaxkvaddr);
3650 		KDASSERT(l2b != NULL);
3651 
3652 		/* Distribute new L1 entry to all other L1s */
3653 		SLIST_FOREACH(l1, &l1_list, l1_link) {
3654 			pl1pd = &l1->l1_kva[L1_IDX(pmap_curmaxkvaddr)];
3655 			*pl1pd = l2b->l2b_phys | L1_C_DOM(PMAP_DOMAIN_KERNEL) |
3656 			    L1_C_PROTO;
3657 			PTE_SYNC(pl1pd);
3658 		}
3659 	}
3660 
3661 	/*
3662 	 * flush out the cache, expensive but growkernel will happen so
3663 	 * rarely
3664 	 */
3665 	cpu_dcache_wbinv_all();
3666 	cpu_tlb_flushD();
3667 	cpu_cpwait();
3668 
3669 	simple_unlock(&kpm->pm_lock);
3670 	splx(s);
3671 
3672 out:
3673 	return (pmap_curmaxkvaddr);
3674 }
3675 
3676 /************************ Utility routines ****************************/
3677 
3678 /*
3679  * vector_page_setprot:
3680  *
3681  *	Manipulate the protection of the vector page.
3682  */
3683 void
3684 vector_page_setprot(int prot)
3685 {
3686 	struct l2_bucket *l2b;
3687 	pt_entry_t *ptep;
3688 
3689 	l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
3690 	KDASSERT(l2b != NULL);
3691 
3692 	ptep = &l2b->l2b_kva[l2pte_index(vector_page)];
3693 
3694 	*ptep = (*ptep & ~L1_S_PROT_MASK) | L2_S_PROT(PTE_KERNEL, prot);
3695 	PTE_SYNC(ptep);
3696 	cpu_tlb_flushD_SE(vector_page);
3697 	cpu_cpwait();
3698 }
3699 
3700 /*
3701  * This is used to stuff certain critical values into the PCB where they
3702  * can be accessed quickly from cpu_switch() et al.
3703  */
3704 void
3705 pmap_set_pcb_pagedir(pmap_t pm, struct pcb *pcb)
3706 {
3707 	struct l2_bucket *l2b;
3708 
3709 	KDASSERT(pm->pm_l1);
3710 
3711 	pcb->pcb_pagedir = pm->pm_l1->l1_physaddr;
3712 	pcb->pcb_dacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
3713 	    (DOMAIN_CLIENT << (pm->pm_domain * 2));
3714 	pcb->pcb_cstate = (void *)&pm->pm_cstate;
3715 
3716 	if (vector_page < KERNEL_BASE) {
3717 		pcb->pcb_pl1vec = &pm->pm_l1->l1_kva[L1_IDX(vector_page)];
3718 		l2b = pmap_get_l2_bucket(pm, vector_page);
3719 		pcb->pcb_l1vec = l2b->l2b_phys | L1_C_PROTO |
3720 		    L1_C_DOM(pm->pm_domain);
3721 	} else
3722 		pcb->pcb_pl1vec = NULL;
3723 }
3724 
3725 /*
3726  * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
3727  * Returns TRUE if the mapping exists, else FALSE.
3728  *
3729  * NOTE: This function is only used by a couple of arm-specific modules.
3730  * It is not safe to take any pmap locks here, since we could be right
3731  * in the middle of debugging the pmap anyway...
3732  *
3733  * It is possible for this routine to return FALSE even though a valid
3734  * mapping does exist. This is because we don't lock, so the metadata
3735  * state may be inconsistent.
3736  *
3737  * NOTE: We can return a NULL *ptp in the case where the L1 pde is
3738  * a "section" mapping.
3739  */
3740 boolean_t
3741 pmap_get_pde_pte(pmap_t pm, vaddr_t va, pd_entry_t **pdp, pt_entry_t **ptp)
3742 {
3743 	struct l2_dtable *l2;
3744 	pd_entry_t *pl1pd, l1pd;
3745 	pt_entry_t *ptep;
3746 	u_short l1idx;
3747 
3748 	if (pm->pm_l1 == NULL)
3749 		return (FALSE);
3750 
3751 	l1idx = L1_IDX(va);
3752 	*pdp = pl1pd = &pm->pm_l1->l1_kva[l1idx];
3753 	l1pd = *pl1pd;
3754 
3755 	if (l1pte_section_p(l1pd)) {
3756 		*ptp = NULL;
3757 		return (TRUE);
3758 	}
3759 
3760 	if (pm->pm_l2 == NULL)
3761 		return (FALSE);
3762 
3763 	l2 = pm->pm_l2[L2_IDX(l1idx)];
3764 
3765 	if (l2 == NULL ||
3766 	    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
3767 		return (FALSE);
3768 	}
3769 
3770 	*ptp = &ptep[l2pte_index(va)];
3771 	return (TRUE);
3772 }
3773 
3774 boolean_t
3775 pmap_get_pde(pmap_t pm, vaddr_t va, pd_entry_t **pdp)
3776 {
3777 	u_short l1idx;
3778 
3779 	if (pm->pm_l1 == NULL)
3780 		return (FALSE);
3781 
3782 	l1idx = L1_IDX(va);
3783 	*pdp = &pm->pm_l1->l1_kva[l1idx];
3784 
3785 	return (TRUE);
3786 }
3787 
3788 /************************ Bootstrapping routines ****************************/
3789 
3790 static void
3791 pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
3792 {
3793 	int i;
3794 
3795 	l1->l1_kva = l1pt;
3796 	l1->l1_domain_use_count = 0;
3797 	l1->l1_domain_first = 0;
3798 
3799 	for (i = 0; i < PMAP_DOMAINS; i++)
3800 		l1->l1_domain_free[i] = i + 1;
3801 
3802 	/*
3803 	 * Copy the kernel's L1 entries to each new L1.
3804 	 */
3805 	if (pmap_initialized)
3806 		memcpy(l1pt, pmap_kernel()->pm_l1->l1_kva, L1_TABLE_SIZE);
3807 
3808 	if (pmap_extract(pmap_kernel(), (vaddr_t)l1pt,
3809 	    &l1->l1_physaddr) == FALSE)
3810 		panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);
3811 
3812 	SLIST_INSERT_HEAD(&l1_list, l1, l1_link);
3813 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
3814 }
3815 
3816 /*
3817  * pmap_bootstrap() is called from the board-specific initarm() routine
3818  * once the kernel L1/L2 descriptors tables have been set up.
3819  *
3820  * This is a somewhat convoluted process since pmap bootstrap is, effectively,
3821  * spread over a number of disparate files/functions.
3822  *
3823  * We are passed the following parameters
3824  *  - kernel_l1pt
3825  *    This is a pointer to the base of the kernel's L1 translation table.
3826  *  - vstart
3827  *    1MB-aligned start of managed kernel virtual memory.
3828  *  - vend
3829  *    1MB-aligned end of managed kernel virtual memory.
3830  *
3831  * We use the first parameter to build the metadata (struct l1_ttable and
3832  * struct l2_dtable) necessary to track kernel mappings.
3833  */
3834 #define	PMAP_STATIC_L2_SIZE 16
3835 void
3836 pmap_bootstrap(pd_entry_t *kernel_l1pt, vaddr_t vstart, vaddr_t vend)
3837 {
3838 	static struct l1_ttable static_l1;
3839 	static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
3840 	struct l1_ttable *l1 = &static_l1;
3841 	struct l2_dtable *l2;
3842 	struct l2_bucket *l2b;
3843 	pmap_t pm = pmap_kernel();
3844 	pd_entry_t pde;
3845 	pt_entry_t *ptep;
3846 	paddr_t pa;
3847 	vaddr_t va;
3848 	vsize_t size;
3849 	int l1idx, l2idx, l2next = 0;
3850 
3851 	/*
3852 	 * Initialise the kernel pmap object
3853 	 */
3854 	pm->pm_l1 = l1;
3855 	pm->pm_domain = PMAP_DOMAIN_KERNEL;
3856 	pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
3857 	simple_lock_init(&pm->pm_lock);
3858 	pm->pm_obj.pgops = NULL;
3859 	TAILQ_INIT(&pm->pm_obj.memq);
3860 	pm->pm_obj.uo_npages = 0;
3861 	pm->pm_obj.uo_refs = 1;
3862 
3863 	/*
3864 	 * Scan the L1 translation table created by initarm() and create
3865 	 * the required metadata for all valid mappings found in it.
3866 	 */
3867 	for (l1idx = 0; l1idx < (L1_TABLE_SIZE / sizeof(pd_entry_t)); l1idx++) {
3868 		pde = kernel_l1pt[l1idx];
3869 
3870 		/*
3871 		 * We're only interested in Coarse mappings.
3872 		 * pmap_extract() can deal with section mappings without
3873 		 * recourse to checking L2 metadata.
3874 		 */
3875 		if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
3876 			continue;
3877 
3878 		/*
3879 		 * Lookup the KVA of this L2 descriptor table
3880 		 */
3881 		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
3882 		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
3883 		if (ptep == NULL) {
3884 			panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
3885 			    (u_int)l1idx << L1_S_SHIFT, pa);
3886 		}
3887 
3888 		/*
3889 		 * Fetch the associated L2 metadata structure.
3890 		 * Allocate a new one if necessary.
3891 		 */
3892 		if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
3893 			if (l2next == PMAP_STATIC_L2_SIZE)
3894 				panic("pmap_bootstrap: out of static L2s");
3895 			pm->pm_l2[L2_IDX(l1idx)] = l2 = &static_l2[l2next++];
3896 		}
3897 
3898 		/*
3899 		 * One more L1 slot tracked...
3900 		 */
3901 		l2->l2_occupancy++;
3902 
3903 		/*
3904 		 * Fill in the details of the L2 descriptor in the
3905 		 * appropriate bucket.
3906 		 */
3907 		l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
3908 		l2b->l2b_kva = ptep;
3909 		l2b->l2b_phys = pa;
3910 		l2b->l2b_l1idx = l1idx;
3911 
3912 		/*
3913 		 * Establish an initial occupancy count for this descriptor
3914 		 */
3915 		for (l2idx = 0;
3916 		    l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
3917 		    l2idx++) {
3918 			if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV) {
3919 				l2b->l2b_occupancy++;
3920 			}
3921 		}
3922 
3923 		/*
3924 		 * Make sure the descriptor itself has the correct cache mode.
3925 		 * If not, fix it, but whine about the problem. Port-meisters
3926 		 * should consider this a clue to fix up their initarm()
3927 		 * function. :)
3928 		 */
3929 		if (pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)ptep)) {
3930 			printf("pmap_bootstrap: WARNING! wrong cache mode for "
3931 			    "L2 pte @ %p\n", ptep);
3932 		}
3933 	}
3934 
3935 	/*
3936 	 * Ensure the primary (kernel) L1 has the correct cache mode for
3937 	 * a page table. Bitch if it is not correctly set.
3938 	 */
3939 	for (va = (vaddr_t)kernel_l1pt;
3940 	    va < ((vaddr_t)kernel_l1pt + L1_TABLE_SIZE); va += PAGE_SIZE) {
3941 		if (pmap_set_pt_cache_mode(kernel_l1pt, va))
3942 			printf("pmap_bootstrap: WARNING! wrong cache mode for "
3943 			    "primary L1 @ 0x%lx\n", va);
3944 	}
3945 
3946 	cpu_dcache_wbinv_all();
3947 	cpu_tlb_flushID();
3948 	cpu_cpwait();
3949 
3950 	/*
3951 	 * now we allocate the "special" VAs which are used for tmp mappings
3952 	 * by the pmap (and other modules).  we allocate the VAs by advancing
3953 	 * virtual_avail (note that there are no pages mapped at these VAs).
3954 	 *
3955 	 * Managed KVM space start from wherever initarm() tells us.
3956 	 */
3957 	virtual_avail = vstart;
3958 	virtual_end = vend;
3959 
3960 	pmap_alloc_specials(&virtual_avail, 1, &csrcp, &csrc_pte);
3961 	pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)csrc_pte);
3962 	pmap_alloc_specials(&virtual_avail, 1, &cdstp, &cdst_pte);
3963 	pmap_set_pt_cache_mode(kernel_l1pt, (vaddr_t)cdst_pte);
3964 	pmap_alloc_specials(&virtual_avail, 1, (void *)&memhook, NULL);
3965 	pmap_alloc_specials(&virtual_avail, round_page(MSGBUFSIZE) / PAGE_SIZE,
3966 	    (void *)&msgbufaddr, NULL);
3967 
3968 	/*
3969 	 * Allocate a range of kernel virtual address space to be used
3970 	 * for L2 descriptor tables and metadata allocation in
3971 	 * pmap_growkernel().
3972 	 */
3973 	size = ((virtual_end - pmap_curmaxkvaddr) + L1_S_OFFSET) / L1_S_SIZE;
3974 	pmap_alloc_specials(&virtual_avail,
3975 	    round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
3976 	    &pmap_kernel_l2ptp_kva, NULL);
3977 
3978 	size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
3979 	pmap_alloc_specials(&virtual_avail,
3980 	    round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
3981 	    &pmap_kernel_l2dtable_kva, NULL);
3982 
3983 	/*
3984 	 * init the static-global locks and global pmap list.
3985 	 */
3986 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
3987 	spinlockinit(&pmap_main_lock, "pmaplk", 0);
3988 #endif
3989 
3990 	/*
3991 	 * We can now initialise the first L1's metadata.
3992 	 */
3993 	SLIST_INIT(&l1_list);
3994 	TAILQ_INIT(&l1_lru_list);
3995 	simple_lock_init(&l1_lru_lock);
3996 	pmap_init_l1(l1, kernel_l1pt);
3997 
3998 	/*
3999 	 * Initialize the pmap pool and cache
4000 	 */
4001 	pool_init(&pmap_pmap_pool, sizeof(struct pmap), 0, 0, 0, "pmappl",
4002 	    &pool_allocator_nointr);
4003 	pool_cache_init(&pmap_pmap_cache, &pmap_pmap_pool,
4004 	    pmap_pmap_ctor, NULL, NULL);
4005 	LIST_INIT(&pmap_pmaps);
4006 	LIST_INSERT_HEAD(&pmap_pmaps, pm, pm_list);
4007 
4008 	/*
4009 	 * Initialize the pv pool.
4010 	 */
4011 	pool_init(&pmap_pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pvepl",
4012 	    &pmap_bootstrap_pv_allocator);
4013 
4014 	/*
4015 	 * Initialize the L2 dtable pool and cache.
4016 	 */
4017 	pool_init(&pmap_l2dtable_pool, sizeof(struct l2_dtable), 0, 0, 0,
4018 	    "l2dtblpl", NULL);
4019 	pool_cache_init(&pmap_l2dtable_cache, &pmap_l2dtable_pool,
4020 	    pmap_l2dtable_ctor, NULL, NULL);
4021 
4022 	/*
4023 	 * Initialise the L2 descriptor table pool and cache
4024 	 */
4025 	pool_init(&pmap_l2ptp_pool, L2_TABLE_SIZE_REAL, 0, L2_TABLE_SIZE_REAL,
4026 	    0, "l2ptppl", NULL);
4027 	pool_cache_init(&pmap_l2ptp_cache, &pmap_l2ptp_pool,
4028 	    pmap_l2ptp_ctor, NULL, NULL);
4029 
4030 	cpu_dcache_wbinv_all();
4031 }
4032 
4033 static int
4034 pmap_set_pt_cache_mode(pd_entry_t *kl1, vaddr_t va)
4035 {
4036 	pd_entry_t *pdep, pde;
4037 	pt_entry_t *ptep, pte;
4038 	vaddr_t pa;
4039 	int rv = 0;
4040 
4041 	/*
4042 	 * Make sure the descriptor itself has the correct cache mode
4043 	 */
4044 	pdep = &kl1[L1_IDX(va)];
4045 	pde = *pdep;
4046 
4047 	if (l1pte_section_p(pde)) {
4048 		if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
4049 			*pdep = (pde & ~L1_S_CACHE_MASK) |
4050 			    pte_l1_s_cache_mode_pt;
4051 			PTE_SYNC(pdep);
4052 			cpu_dcache_wbinv_range((vaddr_t)pdep, sizeof(*pdep));
4053 			rv = 1;
4054 		}
4055 	} else {
4056 		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
4057 		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
4058 		if (ptep == NULL)
4059 			panic("pmap_bootstrap: No L2 for L2 @ va %p\n", ptep);
4060 
4061 		ptep = &ptep[l2pte_index(va)];
4062 		pte = *ptep;
4063 		if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
4064 			*ptep = (pte & ~L2_S_CACHE_MASK) |
4065 			    pte_l2_s_cache_mode_pt;
4066 			PTE_SYNC(ptep);
4067 			cpu_dcache_wbinv_range((vaddr_t)ptep, sizeof(*ptep));
4068 			rv = 1;
4069 		}
4070 	}
4071 
4072 	return (rv);
4073 }
4074 
4075 static void
4076 pmap_alloc_specials(vaddr_t *availp, int pages, vaddr_t *vap, pt_entry_t **ptep)
4077 {
4078 	vaddr_t va = *availp;
4079 	struct l2_bucket *l2b;
4080 
4081 	if (ptep) {
4082 		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
4083 		if (l2b == NULL)
4084 			panic("pmap_alloc_specials: no l2b for 0x%lx", va);
4085 
4086 		if (ptep)
4087 			*ptep = &l2b->l2b_kva[l2pte_index(va)];
4088 	}
4089 
4090 	*vap = va;
4091 	*availp = va + (PAGE_SIZE * pages);
4092 }
4093 
4094 void
4095 pmap_init(void)
4096 {
4097 	extern int physmem;
4098 
4099 	/*
4100 	 * Set the available memory vars - These do not map to real memory
4101 	 * addresses and cannot as the physical memory is fragmented.
4102 	 * They are used by ps for %mem calculations.
4103 	 * One could argue whether this should be the entire memory or just
4104 	 * the memory that is useable in a user process.
4105 	 */
4106 	avail_start = 0;
4107 	avail_end = physmem * PAGE_SIZE;
4108 
4109 	/*
4110 	 * Now we need to free enough pv_entry structures to allow us to get
4111 	 * the kmem_map/kmem_object allocated and inited (done after this
4112 	 * function is finished).  to do this we allocate one bootstrap page out
4113 	 * of kernel_map and use it to provide an initial pool of pv_entry
4114 	 * structures.   we never free this page.
4115 	 */
4116 	pool_setlowat(&pmap_pv_pool,
4117 	    (PAGE_SIZE / sizeof(struct pv_entry)) * 2);
4118 
4119 	pmap_initialized = TRUE;
4120 }
4121 
4122 static vaddr_t last_bootstrap_page = 0;
4123 static void *free_bootstrap_pages = NULL;
4124 
4125 static void *
4126 pmap_bootstrap_pv_page_alloc(struct pool *pp, int flags)
4127 {
4128 	extern void *pool_page_alloc(struct pool *, int);
4129 	vaddr_t new_page;
4130 	void *rv;
4131 
4132 	if (pmap_initialized)
4133 		return (pool_page_alloc(pp, flags));
4134 
4135 	if (free_bootstrap_pages) {
4136 		rv = free_bootstrap_pages;
4137 		free_bootstrap_pages = *((void **)rv);
4138 		return (rv);
4139 	}
4140 
4141 	new_page = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
4142 	    UVM_KMF_WIRED | ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT));
4143 
4144 	KASSERT(new_page > last_bootstrap_page);
4145 	last_bootstrap_page = new_page;
4146 	return ((void *)new_page);
4147 }
4148 
4149 static void
4150 pmap_bootstrap_pv_page_free(struct pool *pp, void *v)
4151 {
4152 	extern void pool_page_free(struct pool *, void *);
4153 
4154 	if ((vaddr_t)v <= last_bootstrap_page) {
4155 		*((void **)v) = free_bootstrap_pages;
4156 		free_bootstrap_pages = v;
4157 		return;
4158 	}
4159 
4160 	if (pmap_initialized) {
4161 		pool_page_free(pp, v);
4162 		return;
4163 	}
4164 }
4165 
4166 /*
4167  * pmap_postinit()
4168  *
4169  * This routine is called after the vm and kmem subsystems have been
4170  * initialised. This allows the pmap code to perform any initialisation
4171  * that can only be done one the memory allocation is in place.
4172  */
4173 void
4174 pmap_postinit(void)
4175 {
4176 	extern paddr_t physical_start, physical_end;
4177 	struct l2_bucket *l2b;
4178 	struct l1_ttable *l1;
4179 	struct pglist plist;
4180 	struct vm_page *m;
4181 	pd_entry_t *pl1pt;
4182 	pt_entry_t *ptep, pte;
4183 	vaddr_t va, eva;
4184 	u_int loop, needed;
4185 	int error;
4186 
4187 	pool_setlowat(&pmap_l2ptp_pool,
4188 	    (PAGE_SIZE / L2_TABLE_SIZE_REAL) * 4);
4189 	pool_setlowat(&pmap_l2dtable_pool,
4190 	    (PAGE_SIZE / sizeof(struct l2_dtable)) * 2);
4191 
4192 	needed = (maxproc / PMAP_DOMAINS) + ((maxproc % PMAP_DOMAINS) ? 1 : 0);
4193 	needed -= 1;
4194 
4195 	l1 = malloc(sizeof(*l1) * needed, M_VMPMAP, M_WAITOK);
4196 
4197 	for (loop = 0; loop < needed; loop++, l1++) {
4198 		/* Allocate a L1 page table */
4199 		va = uvm_km_alloc(kernel_map, L1_TABLE_SIZE, 0, UVM_KMF_VAONLY);
4200 		if (va == 0)
4201 			panic("Cannot allocate L1 KVM");
4202 
4203 		error = uvm_pglistalloc(L1_TABLE_SIZE, physical_start,
4204 		    physical_end, L1_TABLE_SIZE, 0, &plist, 1, M_WAITOK);
4205 		if (error)
4206 			panic("Cannot allocate L1 physical pages");
4207 
4208 		m = TAILQ_FIRST(&plist);
4209 		eva = va + L1_TABLE_SIZE;
4210 		pl1pt = (pd_entry_t *)va;
4211 
4212 		while (m && va < eva) {
4213 			paddr_t pa = VM_PAGE_TO_PHYS(m);
4214 
4215 			pmap_kenter_pa(va, pa, VM_PROT_READ | VM_PROT_WRITE);
4216 
4217 			/*
4218 			 * Make sure the L1 descriptor table is mapped
4219 			 * with the cache-mode set to write-through.
4220 			 */
4221 			l2b = pmap_get_l2_bucket(pmap_kernel(), va);
4222 			ptep = &l2b->l2b_kva[l2pte_index(va)];
4223 			pte = *ptep;
4224 			pte = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
4225 			*ptep = pte;
4226 			PTE_SYNC(ptep);
4227 			cpu_tlb_flushD_SE(va);
4228 
4229 			va += PAGE_SIZE;
4230 			m = TAILQ_NEXT(m, pageq);
4231 		}
4232 
4233 #ifdef DIAGNOSTIC
4234 		if (m)
4235 			panic("pmap_alloc_l1pt: pglist not empty");
4236 #endif	/* DIAGNOSTIC */
4237 
4238 		pmap_init_l1(l1, pl1pt);
4239 	}
4240 
4241 #ifdef DEBUG
4242 	printf("pmap_postinit: Allocated %d static L1 descriptor tables\n",
4243 	    needed);
4244 #endif
4245 }
4246 
4247 /*
4248  * Note that the following routines are used by board-specific initialisation
4249  * code to configure the initial kernel page tables.
4250  *
4251  * If ARM32_NEW_VM_LAYOUT is *not* defined, they operate on the assumption that
4252  * L2 page-table pages are 4KB in size and use 4 L1 slots. This mimics the
4253  * behaviour of the old pmap, and provides an easy migration path for
4254  * initial bring-up of the new pmap on existing ports. Fortunately,
4255  * pmap_bootstrap() compensates for this hackery. This is only a stop-gap and
4256  * will be deprecated.
4257  *
4258  * If ARM32_NEW_VM_LAYOUT *is* defined, these functions deal with 1KB L2 page
4259  * tables.
4260  */
4261 
4262 /*
4263  * This list exists for the benefit of pmap_map_chunk().  It keeps track
4264  * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
4265  * find them as necessary.
4266  *
4267  * Note that the data on this list MUST remain valid after initarm() returns,
4268  * as pmap_bootstrap() uses it to contruct L2 table metadata.
4269  */
4270 SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);
4271 
4272 static vaddr_t
4273 kernel_pt_lookup(paddr_t pa)
4274 {
4275 	pv_addr_t *pv;
4276 
4277 	SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
4278 #ifndef ARM32_NEW_VM_LAYOUT
4279 		if (pv->pv_pa == (pa & ~PGOFSET))
4280 			return (pv->pv_va | (pa & PGOFSET));
4281 #else
4282 		if (pv->pv_pa == pa)
4283 			return (pv->pv_va);
4284 #endif
4285 	}
4286 	return (0);
4287 }
4288 
4289 /*
4290  * pmap_map_section:
4291  *
4292  *	Create a single section mapping.
4293  */
4294 void
4295 pmap_map_section(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
4296 {
4297 	pd_entry_t *pde = (pd_entry_t *) l1pt;
4298 	pd_entry_t fl;
4299 
4300 	KASSERT(((va | pa) & L1_S_OFFSET) == 0);
4301 
4302 	switch (cache) {
4303 	case PTE_NOCACHE:
4304 	default:
4305 		fl = 0;
4306 		break;
4307 
4308 	case PTE_CACHE:
4309 		fl = pte_l1_s_cache_mode;
4310 		break;
4311 
4312 	case PTE_PAGETABLE:
4313 		fl = pte_l1_s_cache_mode_pt;
4314 		break;
4315 	}
4316 
4317 	pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
4318 	    L1_S_PROT(PTE_KERNEL, prot) | fl | L1_S_DOM(PMAP_DOMAIN_KERNEL);
4319 	PTE_SYNC(&pde[va >> L1_S_SHIFT]);
4320 }
4321 
4322 /*
4323  * pmap_map_entry:
4324  *
4325  *	Create a single page mapping.
4326  */
4327 void
4328 pmap_map_entry(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
4329 {
4330 	pd_entry_t *pde = (pd_entry_t *) l1pt;
4331 	pt_entry_t fl;
4332 	pt_entry_t *pte;
4333 
4334 	KASSERT(((va | pa) & PGOFSET) == 0);
4335 
4336 	switch (cache) {
4337 	case PTE_NOCACHE:
4338 	default:
4339 		fl = 0;
4340 		break;
4341 
4342 	case PTE_CACHE:
4343 		fl = pte_l2_s_cache_mode;
4344 		break;
4345 
4346 	case PTE_PAGETABLE:
4347 		fl = pte_l2_s_cache_mode_pt;
4348 		break;
4349 	}
4350 
4351 	if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
4352 		panic("pmap_map_entry: no L2 table for VA 0x%08lx", va);
4353 
4354 #ifndef ARM32_NEW_VM_LAYOUT
4355 	pte = (pt_entry_t *)
4356 	    kernel_pt_lookup(pde[va >> L1_S_SHIFT] & L2_S_FRAME);
4357 #else
4358 	pte = (pt_entry_t *) kernel_pt_lookup(pde[L1_IDX(va)] & L1_C_ADDR_MASK);
4359 #endif
4360 	if (pte == NULL)
4361 		panic("pmap_map_entry: can't find L2 table for VA 0x%08lx", va);
4362 
4363 #ifndef ARM32_NEW_VM_LAYOUT
4364 	pte[(va >> PGSHIFT) & 0x3ff] =
4365 	    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | fl;
4366 	PTE_SYNC(&pte[(va >> PGSHIFT) & 0x3ff]);
4367 #else
4368 	pte[l2pte_index(va)] =
4369 	    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | fl;
4370 	PTE_SYNC(&pte[l2pte_index(va)]);
4371 #endif
4372 }
4373 
4374 /*
4375  * pmap_link_l2pt:
4376  *
4377  *	Link the L2 page table specified by "l2pv" into the L1
4378  *	page table at the slot for "va".
4379  */
4380 void
4381 pmap_link_l2pt(vaddr_t l1pt, vaddr_t va, pv_addr_t *l2pv)
4382 {
4383 	pd_entry_t *pde = (pd_entry_t *) l1pt, proto;
4384 	u_int slot = va >> L1_S_SHIFT;
4385 
4386 #ifndef ARM32_NEW_VM_LAYOUT
4387 	KASSERT((va & ((L1_S_SIZE * 4) - 1)) == 0);
4388 	KASSERT((l2pv->pv_pa & PGOFSET) == 0);
4389 #endif
4390 
4391 	proto = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO;
4392 
4393 	pde[slot + 0] = proto | (l2pv->pv_pa + 0x000);
4394 #ifdef ARM32_NEW_VM_LAYOUT
4395 	PTE_SYNC(&pde[slot]);
4396 #else
4397 	pde[slot + 1] = proto | (l2pv->pv_pa + 0x400);
4398 	pde[slot + 2] = proto | (l2pv->pv_pa + 0x800);
4399 	pde[slot + 3] = proto | (l2pv->pv_pa + 0xc00);
4400 	PTE_SYNC_RANGE(&pde[slot + 0], 4);
4401 #endif
4402 
4403 	SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
4404 }
4405 
4406 /*
4407  * pmap_map_chunk:
4408  *
4409  *	Map a chunk of memory using the most efficient mappings
4410  *	possible (section, large page, small page) into the
4411  *	provided L1 and L2 tables at the specified virtual address.
4412  */
4413 vsize_t
4414 pmap_map_chunk(vaddr_t l1pt, vaddr_t va, paddr_t pa, vsize_t size,
4415     int prot, int cache)
4416 {
4417 	pd_entry_t *pde = (pd_entry_t *) l1pt;
4418 	pt_entry_t *pte, f1, f2s, f2l;
4419 	vsize_t resid;
4420 	int i;
4421 
4422 	resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
4423 
4424 	if (l1pt == 0)
4425 		panic("pmap_map_chunk: no L1 table provided");
4426 
4427 #ifdef VERBOSE_INIT_ARM
4428 	printf("pmap_map_chunk: pa=0x%lx va=0x%lx size=0x%lx resid=0x%lx "
4429 	    "prot=0x%x cache=%d\n", pa, va, size, resid, prot, cache);
4430 #endif
4431 
4432 	switch (cache) {
4433 	case PTE_NOCACHE:
4434 	default:
4435 		f1 = 0;
4436 		f2l = 0;
4437 		f2s = 0;
4438 		break;
4439 
4440 	case PTE_CACHE:
4441 		f1 = pte_l1_s_cache_mode;
4442 		f2l = pte_l2_l_cache_mode;
4443 		f2s = pte_l2_s_cache_mode;
4444 		break;
4445 
4446 	case PTE_PAGETABLE:
4447 		f1 = pte_l1_s_cache_mode_pt;
4448 		f2l = pte_l2_l_cache_mode_pt;
4449 		f2s = pte_l2_s_cache_mode_pt;
4450 		break;
4451 	}
4452 
4453 	size = resid;
4454 
4455 	while (resid > 0) {
4456 		/* See if we can use a section mapping. */
4457 		if (L1_S_MAPPABLE_P(va, pa, resid)) {
4458 #ifdef VERBOSE_INIT_ARM
4459 			printf("S");
4460 #endif
4461 			pde[va >> L1_S_SHIFT] = L1_S_PROTO | pa |
4462 			    L1_S_PROT(PTE_KERNEL, prot) | f1 |
4463 			    L1_S_DOM(PMAP_DOMAIN_KERNEL);
4464 			PTE_SYNC(&pde[va >> L1_S_SHIFT]);
4465 			va += L1_S_SIZE;
4466 			pa += L1_S_SIZE;
4467 			resid -= L1_S_SIZE;
4468 			continue;
4469 		}
4470 
4471 		/*
4472 		 * Ok, we're going to use an L2 table.  Make sure
4473 		 * one is actually in the corresponding L1 slot
4474 		 * for the current VA.
4475 		 */
4476 		if ((pde[va >> L1_S_SHIFT] & L1_TYPE_MASK) != L1_TYPE_C)
4477 			panic("pmap_map_chunk: no L2 table for VA 0x%08lx", va);
4478 
4479 #ifndef ARM32_NEW_VM_LAYOUT
4480 		pte = (pt_entry_t *)
4481 		    kernel_pt_lookup(pde[va >> L1_S_SHIFT] & L2_S_FRAME);
4482 #else
4483 		pte = (pt_entry_t *) kernel_pt_lookup(
4484 		    pde[L1_IDX(va)] & L1_C_ADDR_MASK);
4485 #endif
4486 		if (pte == NULL)
4487 			panic("pmap_map_chunk: can't find L2 table for VA"
4488 			    "0x%08lx", va);
4489 
4490 		/* See if we can use a L2 large page mapping. */
4491 		if (L2_L_MAPPABLE_P(va, pa, resid)) {
4492 #ifdef VERBOSE_INIT_ARM
4493 			printf("L");
4494 #endif
4495 			for (i = 0; i < 16; i++) {
4496 #ifndef ARM32_NEW_VM_LAYOUT
4497 				pte[((va >> PGSHIFT) & 0x3f0) + i] =
4498 				    L2_L_PROTO | pa |
4499 				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
4500 				PTE_SYNC(&pte[((va >> PGSHIFT) & 0x3f0) + i]);
4501 #else
4502 				pte[l2pte_index(va) + i] =
4503 				    L2_L_PROTO | pa |
4504 				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
4505 				PTE_SYNC(&pte[l2pte_index(va) + i]);
4506 #endif
4507 			}
4508 			va += L2_L_SIZE;
4509 			pa += L2_L_SIZE;
4510 			resid -= L2_L_SIZE;
4511 			continue;
4512 		}
4513 
4514 		/* Use a small page mapping. */
4515 #ifdef VERBOSE_INIT_ARM
4516 		printf("P");
4517 #endif
4518 #ifndef ARM32_NEW_VM_LAYOUT
4519 		pte[(va >> PGSHIFT) & 0x3ff] =
4520 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | f2s;
4521 		PTE_SYNC(&pte[(va >> PGSHIFT) & 0x3ff]);
4522 #else
4523 		pte[l2pte_index(va)] =
4524 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | f2s;
4525 		PTE_SYNC(&pte[l2pte_index(va)]);
4526 #endif
4527 		va += PAGE_SIZE;
4528 		pa += PAGE_SIZE;
4529 		resid -= PAGE_SIZE;
4530 	}
4531 #ifdef VERBOSE_INIT_ARM
4532 	printf("\n");
4533 #endif
4534 	return (size);
4535 }
4536 
4537 /********************** Static device map routines ***************************/
4538 
4539 static const struct pmap_devmap *pmap_devmap_table;
4540 
4541 /*
4542  * Register the devmap table.  This is provided in case early console
4543  * initialization needs to register mappings created by bootstrap code
4544  * before pmap_devmap_bootstrap() is called.
4545  */
4546 void
4547 pmap_devmap_register(const struct pmap_devmap *table)
4548 {
4549 
4550 	pmap_devmap_table = table;
4551 }
4552 
4553 /*
4554  * Map all of the static regions in the devmap table, and remember
4555  * the devmap table so other parts of the kernel can look up entries
4556  * later.
4557  */
4558 void
4559 pmap_devmap_bootstrap(vaddr_t l1pt, const struct pmap_devmap *table)
4560 {
4561 	int i;
4562 
4563 	pmap_devmap_table = table;
4564 
4565 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4566 #ifdef VERBOSE_INIT_ARM
4567 		printf("devmap: %08lx -> %08lx @ %08lx\n",
4568 		    pmap_devmap_table[i].pd_pa,
4569 		    pmap_devmap_table[i].pd_pa +
4570 			pmap_devmap_table[i].pd_size - 1,
4571 		    pmap_devmap_table[i].pd_va);
4572 #endif
4573 		pmap_map_chunk(l1pt, pmap_devmap_table[i].pd_va,
4574 		    pmap_devmap_table[i].pd_pa,
4575 		    pmap_devmap_table[i].pd_size,
4576 		    pmap_devmap_table[i].pd_prot,
4577 		    pmap_devmap_table[i].pd_cache);
4578 	}
4579 }
4580 
4581 const struct pmap_devmap *
4582 pmap_devmap_find_pa(paddr_t pa, psize_t size)
4583 {
4584 	uint64_t endpa;
4585 	int i;
4586 
4587 	if (pmap_devmap_table == NULL)
4588 		return (NULL);
4589 
4590 	endpa = (uint64_t)pa + (uint64_t)size;
4591 
4592 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4593 		if (pa >= pmap_devmap_table[i].pd_pa &&
4594 		    endpa <= (uint64_t)pmap_devmap_table[i].pd_pa +
4595 			     (uint64_t)pmap_devmap_table[i].pd_size)
4596 			return (&pmap_devmap_table[i]);
4597 	}
4598 
4599 	return (NULL);
4600 }
4601 
4602 const struct pmap_devmap *
4603 pmap_devmap_find_va(vaddr_t va, vsize_t size)
4604 {
4605 	int i;
4606 
4607 	if (pmap_devmap_table == NULL)
4608 		return (NULL);
4609 
4610 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
4611 		if (va >= pmap_devmap_table[i].pd_va &&
4612 		    va + size <= pmap_devmap_table[i].pd_va +
4613 				 pmap_devmap_table[i].pd_size)
4614 			return (&pmap_devmap_table[i]);
4615 	}
4616 
4617 	return (NULL);
4618 }
4619 
4620 /********************** PTE initialization routines **************************/
4621 
4622 /*
4623  * These routines are called when the CPU type is identified to set up
4624  * the PTE prototypes, cache modes, etc.
4625  *
4626  * The variables are always here, just in case LKMs need to reference
4627  * them (though, they shouldn't).
4628  */
4629 
4630 pt_entry_t	pte_l1_s_cache_mode;
4631 pt_entry_t	pte_l1_s_cache_mode_pt;
4632 pt_entry_t	pte_l1_s_cache_mask;
4633 
4634 pt_entry_t	pte_l2_l_cache_mode;
4635 pt_entry_t	pte_l2_l_cache_mode_pt;
4636 pt_entry_t	pte_l2_l_cache_mask;
4637 
4638 pt_entry_t	pte_l2_s_cache_mode;
4639 pt_entry_t	pte_l2_s_cache_mode_pt;
4640 pt_entry_t	pte_l2_s_cache_mask;
4641 
4642 pt_entry_t	pte_l2_s_prot_u;
4643 pt_entry_t	pte_l2_s_prot_w;
4644 pt_entry_t	pte_l2_s_prot_mask;
4645 
4646 pt_entry_t	pte_l1_s_proto;
4647 pt_entry_t	pte_l1_c_proto;
4648 pt_entry_t	pte_l2_s_proto;
4649 
4650 void		(*pmap_copy_page_func)(paddr_t, paddr_t);
4651 void		(*pmap_zero_page_func)(paddr_t);
4652 
4653 #if (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0
4654 void
4655 pmap_pte_init_generic(void)
4656 {
4657 
4658 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
4659 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_generic;
4660 
4661 	pte_l2_l_cache_mode = L2_B|L2_C;
4662 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_generic;
4663 
4664 	pte_l2_s_cache_mode = L2_B|L2_C;
4665 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_generic;
4666 
4667 	/*
4668 	 * If we have a write-through cache, set B and C.  If
4669 	 * we have a write-back cache, then we assume setting
4670 	 * only C will make those pages write-through.
4671 	 */
4672 	if (cpufuncs.cf_dcache_wb_range == (void *) cpufunc_nullop) {
4673 		pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
4674 		pte_l2_l_cache_mode_pt = L2_B|L2_C;
4675 		pte_l2_s_cache_mode_pt = L2_B|L2_C;
4676 	} else {
4677 		pte_l1_s_cache_mode_pt = L1_S_C;
4678 		pte_l2_l_cache_mode_pt = L2_C;
4679 		pte_l2_s_cache_mode_pt = L2_C;
4680 	}
4681 
4682 	pte_l2_s_prot_u = L2_S_PROT_U_generic;
4683 	pte_l2_s_prot_w = L2_S_PROT_W_generic;
4684 	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;
4685 
4686 	pte_l1_s_proto = L1_S_PROTO_generic;
4687 	pte_l1_c_proto = L1_C_PROTO_generic;
4688 	pte_l2_s_proto = L2_S_PROTO_generic;
4689 
4690 	pmap_copy_page_func = pmap_copy_page_generic;
4691 	pmap_zero_page_func = pmap_zero_page_generic;
4692 }
4693 
4694 #if defined(CPU_ARM8)
4695 void
4696 pmap_pte_init_arm8(void)
4697 {
4698 
4699 	/*
4700 	 * ARM8 is compatible with generic, but we need to use
4701 	 * the page tables uncached.
4702 	 */
4703 	pmap_pte_init_generic();
4704 
4705 	pte_l1_s_cache_mode_pt = 0;
4706 	pte_l2_l_cache_mode_pt = 0;
4707 	pte_l2_s_cache_mode_pt = 0;
4708 }
4709 #endif /* CPU_ARM8 */
4710 
4711 #if defined(CPU_ARM9) && defined(ARM9_CACHE_WRITE_THROUGH)
4712 void
4713 pmap_pte_init_arm9(void)
4714 {
4715 
4716 	/*
4717 	 * ARM9 is compatible with generic, but we want to use
4718 	 * write-through caching for now.
4719 	 */
4720 	pmap_pte_init_generic();
4721 
4722 	pte_l1_s_cache_mode = L1_S_C;
4723 	pte_l2_l_cache_mode = L2_C;
4724 	pte_l2_s_cache_mode = L2_C;
4725 
4726 	pte_l1_s_cache_mode_pt = L1_S_C;
4727 	pte_l2_l_cache_mode_pt = L2_C;
4728 	pte_l2_s_cache_mode_pt = L2_C;
4729 }
4730 #endif /* CPU_ARM9 */
4731 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1) != 0 */
4732 
4733 #if defined(CPU_ARM10)
4734 void
4735 pmap_pte_init_arm10(void)
4736 {
4737 
4738 	/*
4739 	 * ARM10 is compatible with generic, but we want to use
4740 	 * write-through caching for now.
4741 	 */
4742 	pmap_pte_init_generic();
4743 
4744 	pte_l1_s_cache_mode = L1_S_B | L1_S_C;
4745 	pte_l2_l_cache_mode = L2_B | L2_C;
4746 	pte_l2_s_cache_mode = L2_B | L2_C;
4747 
4748 	pte_l1_s_cache_mode_pt = L1_S_C;
4749 	pte_l2_l_cache_mode_pt = L2_C;
4750 	pte_l2_s_cache_mode_pt = L2_C;
4751 
4752 }
4753 #endif /* CPU_ARM10 */
4754 
4755 #if ARM_MMU_SA1 == 1
4756 void
4757 pmap_pte_init_sa1(void)
4758 {
4759 
4760 	/*
4761 	 * The StrongARM SA-1 cache does not have a write-through
4762 	 * mode.  So, do the generic initialization, then reset
4763 	 * the page table cache mode to B=1,C=1, and note that
4764 	 * the PTEs need to be sync'd.
4765 	 */
4766 	pmap_pte_init_generic();
4767 
4768 	pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
4769 	pte_l2_l_cache_mode_pt = L2_B|L2_C;
4770 	pte_l2_s_cache_mode_pt = L2_B|L2_C;
4771 
4772 	pmap_needs_pte_sync = 1;
4773 }
4774 #endif /* ARM_MMU_SA1 == 1*/
4775 
4776 #if ARM_MMU_XSCALE == 1
4777 #if (ARM_NMMUS > 1)
4778 static u_int xscale_use_minidata;
4779 #endif
4780 
4781 void
4782 pmap_pte_init_xscale(void)
4783 {
4784 	uint32_t auxctl;
4785 	int write_through = 0;
4786 
4787 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
4788 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_xscale;
4789 
4790 	pte_l2_l_cache_mode = L2_B|L2_C;
4791 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_xscale;
4792 
4793 	pte_l2_s_cache_mode = L2_B|L2_C;
4794 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_xscale;
4795 
4796 	pte_l1_s_cache_mode_pt = L1_S_C;
4797 	pte_l2_l_cache_mode_pt = L2_C;
4798 	pte_l2_s_cache_mode_pt = L2_C;
4799 
4800 #ifdef XSCALE_CACHE_READ_WRITE_ALLOCATE
4801 	/*
4802 	 * The XScale core has an enhanced mode where writes that
4803 	 * miss the cache cause a cache line to be allocated.  This
4804 	 * is significantly faster than the traditional, write-through
4805 	 * behavior of this case.
4806 	 */
4807 	pte_l1_s_cache_mode |= L1_S_XSCALE_TEX(TEX_XSCALE_X);
4808 	pte_l2_l_cache_mode |= L2_XSCALE_L_TEX(TEX_XSCALE_X);
4809 	pte_l2_s_cache_mode |= L2_XSCALE_T_TEX(TEX_XSCALE_X);
4810 #endif /* XSCALE_CACHE_READ_WRITE_ALLOCATE */
4811 
4812 #ifdef XSCALE_CACHE_WRITE_THROUGH
4813 	/*
4814 	 * Some versions of the XScale core have various bugs in
4815 	 * their cache units, the work-around for which is to run
4816 	 * the cache in write-through mode.  Unfortunately, this
4817 	 * has a major (negative) impact on performance.  So, we
4818 	 * go ahead and run fast-and-loose, in the hopes that we
4819 	 * don't line up the planets in a way that will trip the
4820 	 * bugs.
4821 	 *
4822 	 * However, we give you the option to be slow-but-correct.
4823 	 */
4824 	write_through = 1;
4825 #elif defined(XSCALE_CACHE_WRITE_BACK)
4826 	/* force write back cache mode */
4827 	write_through = 0;
4828 #elif defined(CPU_XSCALE_PXA250) || defined(CPU_XSCALE_PXA270)
4829 	/*
4830 	 * Intel PXA2[15]0 processors are known to have a bug in
4831 	 * write-back cache on revision 4 and earlier (stepping
4832 	 * A[01] and B[012]).  Fixed for C0 and later.
4833 	 */
4834 	{
4835 		uint32_t id, type;
4836 
4837 		id = cpufunc_id();
4838 		type = id & ~(CPU_ID_XSCALE_COREREV_MASK|CPU_ID_REVISION_MASK);
4839 
4840 		if (type == CPU_ID_PXA250 || type == CPU_ID_PXA210) {
4841 			if ((id & CPU_ID_REVISION_MASK) < 5) {
4842 				/* write through for stepping A0-1 and B0-2 */
4843 				write_through = 1;
4844 			}
4845 		}
4846 	}
4847 #endif /* XSCALE_CACHE_WRITE_THROUGH */
4848 
4849 	if (write_through) {
4850 		pte_l1_s_cache_mode = L1_S_C;
4851 		pte_l2_l_cache_mode = L2_C;
4852 		pte_l2_s_cache_mode = L2_C;
4853 	}
4854 
4855 #if (ARM_NMMUS > 1)
4856 	xscale_use_minidata = 1;
4857 #endif
4858 
4859 	pte_l2_s_prot_u = L2_S_PROT_U_xscale;
4860 	pte_l2_s_prot_w = L2_S_PROT_W_xscale;
4861 	pte_l2_s_prot_mask = L2_S_PROT_MASK_xscale;
4862 
4863 	pte_l1_s_proto = L1_S_PROTO_xscale;
4864 	pte_l1_c_proto = L1_C_PROTO_xscale;
4865 	pte_l2_s_proto = L2_S_PROTO_xscale;
4866 
4867 	pmap_copy_page_func = pmap_copy_page_xscale;
4868 	pmap_zero_page_func = pmap_zero_page_xscale;
4869 
4870 	/*
4871 	 * Disable ECC protection of page table access, for now.
4872 	 */
4873 	__asm volatile("mrc p15, 0, %0, c1, c0, 1" : "=r" (auxctl));
4874 	auxctl &= ~XSCALE_AUXCTL_P;
4875 	__asm volatile("mcr p15, 0, %0, c1, c0, 1" : : "r" (auxctl));
4876 }
4877 
4878 /*
4879  * xscale_setup_minidata:
4880  *
4881  *	Set up the mini-data cache clean area.  We require the
4882  *	caller to allocate the right amount of physically and
4883  *	virtually contiguous space.
4884  */
4885 void
4886 xscale_setup_minidata(vaddr_t l1pt, vaddr_t va, paddr_t pa)
4887 {
4888 	extern vaddr_t xscale_minidata_clean_addr;
4889 	extern vsize_t xscale_minidata_clean_size; /* already initialized */
4890 	pd_entry_t *pde = (pd_entry_t *) l1pt;
4891 	pt_entry_t *pte;
4892 	vsize_t size;
4893 	uint32_t auxctl;
4894 
4895 	xscale_minidata_clean_addr = va;
4896 
4897 	/* Round it to page size. */
4898 	size = (xscale_minidata_clean_size + L2_S_OFFSET) & L2_S_FRAME;
4899 
4900 	for (; size != 0;
4901 	     va += L2_S_SIZE, pa += L2_S_SIZE, size -= L2_S_SIZE) {
4902 #ifndef ARM32_NEW_VM_LAYOUT
4903 		pte = (pt_entry_t *)
4904 		    kernel_pt_lookup(pde[va >> L1_S_SHIFT] & L2_S_FRAME);
4905 #else
4906 		pte = (pt_entry_t *) kernel_pt_lookup(
4907 		    pde[L1_IDX(va)] & L1_C_ADDR_MASK);
4908 #endif
4909 		if (pte == NULL)
4910 			panic("xscale_setup_minidata: can't find L2 table for "
4911 			    "VA 0x%08lx", va);
4912 #ifndef ARM32_NEW_VM_LAYOUT
4913 		pte[(va >> PGSHIFT) & 0x3ff] =
4914 #else
4915 		pte[l2pte_index(va)] =
4916 #endif
4917 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, VM_PROT_READ) |
4918 		    L2_C | L2_XSCALE_T_TEX(TEX_XSCALE_X);
4919 	}
4920 
4921 	/*
4922 	 * Configure the mini-data cache for write-back with
4923 	 * read/write-allocate.
4924 	 *
4925 	 * NOTE: In order to reconfigure the mini-data cache, we must
4926 	 * make sure it contains no valid data!  In order to do that,
4927 	 * we must issue a global data cache invalidate command!
4928 	 *
4929 	 * WE ASSUME WE ARE RUNNING UN-CACHED WHEN THIS ROUTINE IS CALLED!
4930 	 * THIS IS VERY IMPORTANT!
4931 	 */
4932 
4933 	/* Invalidate data and mini-data. */
4934 	__asm volatile("mcr p15, 0, %0, c7, c6, 0" : : "r" (0));
4935 	__asm volatile("mrc p15, 0, %0, c1, c0, 1" : "=r" (auxctl));
4936 	auxctl = (auxctl & ~XSCALE_AUXCTL_MD_MASK) | XSCALE_AUXCTL_MD_WB_RWA;
4937 	__asm volatile("mcr p15, 0, %0, c1, c0, 1" : : "r" (auxctl));
4938 }
4939 
4940 /*
4941  * Change the PTEs for the specified kernel mappings such that they
4942  * will use the mini data cache instead of the main data cache.
4943  */
4944 void
4945 pmap_uarea(vaddr_t va)
4946 {
4947 	struct l2_bucket *l2b;
4948 	pt_entry_t *ptep, *sptep, pte;
4949 	vaddr_t next_bucket, eva;
4950 
4951 #if (ARM_NMMUS > 1)
4952 	if (xscale_use_minidata == 0)
4953 		return;
4954 #endif
4955 
4956 	eva = va + USPACE;
4957 
4958 	while (va < eva) {
4959 		next_bucket = L2_NEXT_BUCKET(va);
4960 		if (next_bucket > eva)
4961 			next_bucket = eva;
4962 
4963 		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
4964 		KDASSERT(l2b != NULL);
4965 
4966 		sptep = ptep = &l2b->l2b_kva[l2pte_index(va)];
4967 
4968 		while (va < next_bucket) {
4969 			pte = *ptep;
4970 			if (!l2pte_minidata(pte)) {
4971 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
4972 				cpu_tlb_flushD_SE(va);
4973 				*ptep = pte & ~L2_B;
4974 			}
4975 			ptep++;
4976 			va += PAGE_SIZE;
4977 		}
4978 		PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
4979 	}
4980 	cpu_cpwait();
4981 }
4982 #endif /* ARM_MMU_XSCALE == 1 */
4983 
4984 #if defined(DDB)
4985 /*
4986  * A couple of ddb-callable functions for dumping pmaps
4987  */
4988 void pmap_dump_all(void);
4989 void pmap_dump(pmap_t);
4990 
4991 void
4992 pmap_dump_all(void)
4993 {
4994 	pmap_t pm;
4995 
4996 	LIST_FOREACH(pm, &pmap_pmaps, pm_list) {
4997 		if (pm == pmap_kernel())
4998 			continue;
4999 		pmap_dump(pm);
5000 		printf("\n");
5001 	}
5002 }
5003 
5004 static pt_entry_t ncptes[64];
5005 static void pmap_dump_ncpg(pmap_t);
5006 
5007 void
5008 pmap_dump(pmap_t pm)
5009 {
5010 	struct l2_dtable *l2;
5011 	struct l2_bucket *l2b;
5012 	pt_entry_t *ptep, pte;
5013 	vaddr_t l2_va, l2b_va, va;
5014 	int i, j, k, occ, rows = 0;
5015 
5016 	if (pm == pmap_kernel())
5017 		printf("pmap_kernel (%p): ", pm);
5018 	else
5019 		printf("user pmap (%p): ", pm);
5020 
5021 	printf("domain %d, l1 at %p\n", pm->pm_domain, pm->pm_l1->l1_kva);
5022 
5023 	l2_va = 0;
5024 	for (i = 0; i < L2_SIZE; i++, l2_va += 0x01000000) {
5025 		l2 = pm->pm_l2[i];
5026 
5027 		if (l2 == NULL || l2->l2_occupancy == 0)
5028 			continue;
5029 
5030 		l2b_va = l2_va;
5031 		for (j = 0; j < L2_BUCKET_SIZE; j++, l2b_va += 0x00100000) {
5032 			l2b = &l2->l2_bucket[j];
5033 
5034 			if (l2b->l2b_occupancy == 0 || l2b->l2b_kva == NULL)
5035 				continue;
5036 
5037 			ptep = l2b->l2b_kva;
5038 
5039 			for (k = 0; k < 256 && ptep[k] == 0; k++)
5040 				;
5041 
5042 			k &= ~63;
5043 			occ = l2b->l2b_occupancy;
5044 			va = l2b_va + (k * 4096);
5045 			for (; k < 256; k++, va += 0x1000) {
5046 				char ch = ' ';
5047 				if ((k % 64) == 0) {
5048 					if ((rows % 8) == 0) {
5049 						printf(
5050 "          |0000   |8000   |10000  |18000  |20000  |28000  |30000  |38000\n");
5051 					}
5052 					printf("%08lx: ", va);
5053 				}
5054 
5055 				ncptes[k & 63] = 0;
5056 				pte = ptep[k];
5057 				if (pte == 0) {
5058 					ch = '.';
5059 				} else {
5060 					occ--;
5061 					switch (pte & 0x0c) {
5062 					case 0x00:
5063 						ch = 'D'; /* No cache No buff */
5064 						break;
5065 					case 0x04:
5066 						ch = 'B'; /* No cache buff */
5067 						break;
5068 					case 0x08:
5069 						if (pte & 0x40)
5070 							ch = 'm';
5071 						else
5072 						   ch = 'C'; /* Cache No buff */
5073 						break;
5074 					case 0x0c:
5075 						ch = 'F'; /* Cache Buff */
5076 						break;
5077 					}
5078 
5079 					if ((pte & L2_S_PROT_U) == L2_S_PROT_U)
5080 						ch += 0x20;
5081 
5082 					if ((pte & 0xc) == 0)
5083 						ncptes[k & 63] = pte;
5084 				}
5085 
5086 				if ((k % 64) == 63) {
5087 					rows++;
5088 					printf("%c\n", ch);
5089 					pmap_dump_ncpg(pm);
5090 					if (occ == 0)
5091 						break;
5092 				} else
5093 					printf("%c", ch);
5094 			}
5095 		}
5096 	}
5097 }
5098 
5099 static void
5100 pmap_dump_ncpg(pmap_t pm)
5101 {
5102 	struct vm_page *pg;
5103 	struct pv_entry *pv;
5104 	int i;
5105 
5106 	for (i = 0; i < 63; i++) {
5107 		if (ncptes[i] == 0)
5108 			continue;
5109 
5110 		pg = PHYS_TO_VM_PAGE(l2pte_pa(ncptes[i]));
5111 		if (pg == NULL)
5112 			continue;
5113 
5114 		printf(" pa 0x%08lx: krw %d kro %d urw %d uro %d\n",
5115 		    VM_PAGE_TO_PHYS(pg),
5116 		    pg->mdpage.krw_mappings, pg->mdpage.kro_mappings,
5117 		    pg->mdpage.urw_mappings, pg->mdpage.uro_mappings);
5118 
5119 		for (pv = pg->mdpage.pvh_list; pv; pv = pv->pv_next) {
5120 			printf("   %c va 0x%08lx, flags 0x%x\n",
5121 			    (pm == pv->pv_pmap) ? '*' : ' ',
5122 			    pv->pv_va, pv->pv_flags);
5123 		}
5124 	}
5125 }
5126 #endif
5127