xref: /netbsd-src/sys/arch/arm/arm32/pmap.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: pmap.c,v 1.262 2013/07/03 21:37:35 matt 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  *
82  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
83  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
84  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
85  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
86  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
87  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
88  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
89  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
90  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
91  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
92  * POSSIBILITY OF SUCH DAMAGE.
93  */
94 
95 /*
96  * Copyright (c) 1994-1998 Mark Brinicombe.
97  * Copyright (c) 1994 Brini.
98  * All rights reserved.
99  *
100  * This code is derived from software written for Brini by Mark Brinicombe
101  *
102  * Redistribution and use in source and binary forms, with or without
103  * modification, are permitted provided that the following conditions
104  * are met:
105  * 1. Redistributions of source code must retain the above copyright
106  *    notice, this list of conditions and the following disclaimer.
107  * 2. Redistributions in binary form must reproduce the above copyright
108  *    notice, this list of conditions and the following disclaimer in the
109  *    documentation and/or other materials provided with the distribution.
110  * 3. All advertising materials mentioning features or use of this software
111  *    must display the following acknowledgement:
112  *	This product includes software developed by Mark Brinicombe.
113  * 4. The name of the author may not be used to endorse or promote products
114  *    derived from this software without specific prior written permission.
115  *
116  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
117  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
118  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
119  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
120  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
121  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
122  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
123  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
124  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
125  *
126  * RiscBSD kernel project
127  *
128  * pmap.c
129  *
130  * Machine dependent vm stuff
131  *
132  * Created      : 20/09/94
133  */
134 
135 /*
136  * armv6 and VIPT cache support by 3am Software Foundry,
137  * Copyright (c) 2007 Microsoft
138  */
139 
140 /*
141  * Performance improvements, UVM changes, overhauls and part-rewrites
142  * were contributed by Neil A. Carson <neil@causality.com>.
143  */
144 
145 /*
146  * Overhauled again to speedup the pmap, use MMU Domains so that L1 tables
147  * can be shared, and re-work the KVM layout, by Steve Woodford of Wasabi
148  * Systems, Inc.
149  *
150  * There are still a few things outstanding at this time:
151  *
152  *   - There are some unresolved issues for MP systems:
153  *
154  *     o The L1 metadata needs a lock, or more specifically, some places
155  *       need to acquire an exclusive lock when modifying L1 translation
156  *       table entries.
157  *
158  *     o When one cpu modifies an L1 entry, and that L1 table is also
159  *       being used by another cpu, then the latter will need to be told
160  *       that a tlb invalidation may be necessary. (But only if the old
161  *       domain number in the L1 entry being over-written is currently
162  *       the active domain on that cpu). I guess there are lots more tlb
163  *       shootdown issues too...
164  *
165  *     o If the vector_page is at 0x00000000 instead of in kernel VA space,
166  *       then MP systems will lose big-time because of the MMU domain hack.
167  *       The only way this can be solved (apart from moving the vector
168  *       page to 0xffff0000) is to reserve the first 1MB of user address
169  *       space for kernel use only. This would require re-linking all
170  *       applications so that the text section starts above this 1MB
171  *       boundary.
172  *
173  *     o Tracking which VM space is resident in the cache/tlb has not yet
174  *       been implemented for MP systems.
175  *
176  *     o Finally, there is a pathological condition where two cpus running
177  *       two separate processes (not lwps) which happen to share an L1
178  *       can get into a fight over one or more L1 entries. This will result
179  *       in a significant slow-down if both processes are in tight loops.
180  */
181 
182 /*
183  * Special compilation symbols
184  * PMAP_DEBUG		- Build in pmap_debug_level code
185  */
186 
187 /* Include header files */
188 
189 #include "opt_cpuoptions.h"
190 #include "opt_pmap_debug.h"
191 #include "opt_ddb.h"
192 #include "opt_lockdebug.h"
193 #include "opt_multiprocessor.h"
194 
195 #include <sys/param.h>
196 #include <sys/types.h>
197 #include <sys/kernel.h>
198 #include <sys/systm.h>
199 #include <sys/proc.h>
200 #include <sys/pool.h>
201 #include <sys/kmem.h>
202 #include <sys/cdefs.h>
203 #include <sys/cpu.h>
204 #include <sys/sysctl.h>
205 
206 #include <uvm/uvm.h>
207 
208 #include <sys/bus.h>
209 #include <machine/pmap.h>
210 #include <machine/pcb.h>
211 #include <machine/param.h>
212 #include <arm/cpuconf.h>
213 #include <arm/arm32/katelib.h>
214 
215 __KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.262 2013/07/03 21:37:35 matt 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 #define	PDB_EXEC	0x80000
244 
245 int debugmap = 1;
246 int pmapdebug = 0;
247 #define	NPDEBUG(_lev_,_stat_) \
248 	if (pmapdebug & (_lev_)) \
249         	((_stat_))
250 
251 #else	/* PMAP_DEBUG */
252 #define NPDEBUG(_lev_,_stat_) /* Nothing */
253 #endif	/* PMAP_DEBUG */
254 
255 /*
256  * pmap_kernel() points here
257  */
258 static struct pmap	kernel_pmap_store;
259 struct pmap		*const kernel_pmap_ptr = &kernel_pmap_store;
260 #ifdef PMAP_NEED_ALLOC_POOLPAGE
261 int			arm_poolpage_vmfreelist = VM_FREELIST_DEFAULT;
262 #endif
263 
264 /*
265  * Which pmap is currently 'live' in the cache
266  *
267  * XXXSCW: Fix for SMP ...
268  */
269 static pmap_t pmap_recent_user;
270 
271 /*
272  * Pointer to last active lwp, or NULL if it exited.
273  */
274 struct lwp *pmap_previous_active_lwp;
275 
276 /*
277  * Pool and cache that pmap structures are allocated from.
278  * We use a cache to avoid clearing the pm_l2[] array (1KB)
279  * in pmap_create().
280  */
281 static struct pool_cache pmap_cache;
282 static LIST_HEAD(, pmap) pmap_pmaps;
283 
284 /*
285  * Pool of PV structures
286  */
287 static struct pool pmap_pv_pool;
288 static void *pmap_bootstrap_pv_page_alloc(struct pool *, int);
289 static void pmap_bootstrap_pv_page_free(struct pool *, void *);
290 static struct pool_allocator pmap_bootstrap_pv_allocator = {
291 	pmap_bootstrap_pv_page_alloc, pmap_bootstrap_pv_page_free
292 };
293 
294 /*
295  * Pool and cache of l2_dtable structures.
296  * We use a cache to avoid clearing the structures when they're
297  * allocated. (196 bytes)
298  */
299 static struct pool_cache pmap_l2dtable_cache;
300 static vaddr_t pmap_kernel_l2dtable_kva;
301 
302 /*
303  * Pool and cache of L2 page descriptors.
304  * We use a cache to avoid clearing the descriptor table
305  * when they're allocated. (1KB)
306  */
307 static struct pool_cache pmap_l2ptp_cache;
308 static vaddr_t pmap_kernel_l2ptp_kva;
309 static paddr_t pmap_kernel_l2ptp_phys;
310 
311 #ifdef PMAPCOUNTERS
312 #define	PMAP_EVCNT_INITIALIZER(name) \
313 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap", name)
314 
315 #ifdef PMAP_CACHE_VIPT
316 static struct evcnt pmap_ev_vac_clean_one =
317    PMAP_EVCNT_INITIALIZER("clean page (1 color)");
318 static struct evcnt pmap_ev_vac_flush_one =
319    PMAP_EVCNT_INITIALIZER("flush page (1 color)");
320 static struct evcnt pmap_ev_vac_flush_lots =
321    PMAP_EVCNT_INITIALIZER("flush page (2+ colors)");
322 static struct evcnt pmap_ev_vac_flush_lots2 =
323    PMAP_EVCNT_INITIALIZER("flush page (2+ colors, kmpage)");
324 EVCNT_ATTACH_STATIC(pmap_ev_vac_clean_one);
325 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_one);
326 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_lots);
327 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_lots2);
328 
329 static struct evcnt pmap_ev_vac_color_new =
330    PMAP_EVCNT_INITIALIZER("new page color");
331 static struct evcnt pmap_ev_vac_color_reuse =
332    PMAP_EVCNT_INITIALIZER("ok first page color");
333 static struct evcnt pmap_ev_vac_color_ok =
334    PMAP_EVCNT_INITIALIZER("ok page color");
335 static struct evcnt pmap_ev_vac_color_blind =
336    PMAP_EVCNT_INITIALIZER("blind page color");
337 static struct evcnt pmap_ev_vac_color_change =
338    PMAP_EVCNT_INITIALIZER("change page color");
339 static struct evcnt pmap_ev_vac_color_erase =
340    PMAP_EVCNT_INITIALIZER("erase page color");
341 static struct evcnt pmap_ev_vac_color_none =
342    PMAP_EVCNT_INITIALIZER("no page color");
343 static struct evcnt pmap_ev_vac_color_restore =
344    PMAP_EVCNT_INITIALIZER("restore page color");
345 
346 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_new);
347 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_reuse);
348 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_ok);
349 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_blind);
350 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_change);
351 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_erase);
352 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_none);
353 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_restore);
354 #endif
355 
356 static struct evcnt pmap_ev_mappings =
357    PMAP_EVCNT_INITIALIZER("pages mapped");
358 static struct evcnt pmap_ev_unmappings =
359    PMAP_EVCNT_INITIALIZER("pages unmapped");
360 static struct evcnt pmap_ev_remappings =
361    PMAP_EVCNT_INITIALIZER("pages remapped");
362 
363 EVCNT_ATTACH_STATIC(pmap_ev_mappings);
364 EVCNT_ATTACH_STATIC(pmap_ev_unmappings);
365 EVCNT_ATTACH_STATIC(pmap_ev_remappings);
366 
367 static struct evcnt pmap_ev_kernel_mappings =
368    PMAP_EVCNT_INITIALIZER("kernel pages mapped");
369 static struct evcnt pmap_ev_kernel_unmappings =
370    PMAP_EVCNT_INITIALIZER("kernel pages unmapped");
371 static struct evcnt pmap_ev_kernel_remappings =
372    PMAP_EVCNT_INITIALIZER("kernel pages remapped");
373 
374 EVCNT_ATTACH_STATIC(pmap_ev_kernel_mappings);
375 EVCNT_ATTACH_STATIC(pmap_ev_kernel_unmappings);
376 EVCNT_ATTACH_STATIC(pmap_ev_kernel_remappings);
377 
378 static struct evcnt pmap_ev_kenter_mappings =
379    PMAP_EVCNT_INITIALIZER("kenter pages mapped");
380 static struct evcnt pmap_ev_kenter_unmappings =
381    PMAP_EVCNT_INITIALIZER("kenter pages unmapped");
382 static struct evcnt pmap_ev_kenter_remappings =
383    PMAP_EVCNT_INITIALIZER("kenter pages remapped");
384 static struct evcnt pmap_ev_pt_mappings =
385    PMAP_EVCNT_INITIALIZER("page table pages mapped");
386 
387 EVCNT_ATTACH_STATIC(pmap_ev_kenter_mappings);
388 EVCNT_ATTACH_STATIC(pmap_ev_kenter_unmappings);
389 EVCNT_ATTACH_STATIC(pmap_ev_kenter_remappings);
390 EVCNT_ATTACH_STATIC(pmap_ev_pt_mappings);
391 
392 #ifdef PMAP_CACHE_VIPT
393 static struct evcnt pmap_ev_exec_mappings =
394    PMAP_EVCNT_INITIALIZER("exec pages mapped");
395 static struct evcnt pmap_ev_exec_cached =
396    PMAP_EVCNT_INITIALIZER("exec pages cached");
397 
398 EVCNT_ATTACH_STATIC(pmap_ev_exec_mappings);
399 EVCNT_ATTACH_STATIC(pmap_ev_exec_cached);
400 
401 static struct evcnt pmap_ev_exec_synced =
402    PMAP_EVCNT_INITIALIZER("exec pages synced");
403 static struct evcnt pmap_ev_exec_synced_map =
404    PMAP_EVCNT_INITIALIZER("exec pages synced (MP)");
405 static struct evcnt pmap_ev_exec_synced_unmap =
406    PMAP_EVCNT_INITIALIZER("exec pages synced (UM)");
407 static struct evcnt pmap_ev_exec_synced_remap =
408    PMAP_EVCNT_INITIALIZER("exec pages synced (RM)");
409 static struct evcnt pmap_ev_exec_synced_clearbit =
410    PMAP_EVCNT_INITIALIZER("exec pages synced (DG)");
411 static struct evcnt pmap_ev_exec_synced_kremove =
412    PMAP_EVCNT_INITIALIZER("exec pages synced (KU)");
413 
414 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced);
415 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_map);
416 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_unmap);
417 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_remap);
418 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_clearbit);
419 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_kremove);
420 
421 static struct evcnt pmap_ev_exec_discarded_unmap =
422    PMAP_EVCNT_INITIALIZER("exec pages discarded (UM)");
423 static struct evcnt pmap_ev_exec_discarded_zero =
424    PMAP_EVCNT_INITIALIZER("exec pages discarded (ZP)");
425 static struct evcnt pmap_ev_exec_discarded_copy =
426    PMAP_EVCNT_INITIALIZER("exec pages discarded (CP)");
427 static struct evcnt pmap_ev_exec_discarded_page_protect =
428    PMAP_EVCNT_INITIALIZER("exec pages discarded (PP)");
429 static struct evcnt pmap_ev_exec_discarded_clearbit =
430    PMAP_EVCNT_INITIALIZER("exec pages discarded (DG)");
431 static struct evcnt pmap_ev_exec_discarded_kremove =
432    PMAP_EVCNT_INITIALIZER("exec pages discarded (KU)");
433 
434 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_unmap);
435 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_zero);
436 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_copy);
437 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_page_protect);
438 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_clearbit);
439 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_kremove);
440 #endif /* PMAP_CACHE_VIPT */
441 
442 static struct evcnt pmap_ev_updates = PMAP_EVCNT_INITIALIZER("updates");
443 static struct evcnt pmap_ev_collects = PMAP_EVCNT_INITIALIZER("collects");
444 static struct evcnt pmap_ev_activations = PMAP_EVCNT_INITIALIZER("activations");
445 
446 EVCNT_ATTACH_STATIC(pmap_ev_updates);
447 EVCNT_ATTACH_STATIC(pmap_ev_collects);
448 EVCNT_ATTACH_STATIC(pmap_ev_activations);
449 
450 #define	PMAPCOUNT(x)	((void)(pmap_ev_##x.ev_count++))
451 #else
452 #define	PMAPCOUNT(x)	((void)0)
453 #endif
454 
455 /*
456  * pmap copy/zero page, and mem(5) hook point
457  */
458 static pt_entry_t *csrc_pte, *cdst_pte;
459 static vaddr_t csrcp, cdstp;
460 vaddr_t memhook;			/* used by mem.c */
461 kmutex_t memlock;			/* used by mem.c */
462 void *zeropage;				/* used by mem.c */
463 extern void *msgbufaddr;
464 int pmap_kmpages;
465 /*
466  * Flag to indicate if pmap_init() has done its thing
467  */
468 bool pmap_initialized;
469 
470 /*
471  * Misc. locking data structures
472  */
473 
474 #define	pmap_acquire_pmap_lock(pm)			\
475 	do {						\
476 		if ((pm) != pmap_kernel())		\
477 			mutex_enter((pm)->pm_lock);	\
478 	} while (/*CONSTCOND*/0)
479 
480 #define	pmap_release_pmap_lock(pm)			\
481 	do {						\
482 		if ((pm) != pmap_kernel())		\
483 			mutex_exit((pm)->pm_lock);	\
484 	} while (/*CONSTCOND*/0)
485 
486 
487 /*
488  * Metadata for L1 translation tables.
489  */
490 struct l1_ttable {
491 	/* Entry on the L1 Table list */
492 	SLIST_ENTRY(l1_ttable) l1_link;
493 
494 	/* Entry on the L1 Least Recently Used list */
495 	TAILQ_ENTRY(l1_ttable) l1_lru;
496 
497 	/* Track how many domains are allocated from this L1 */
498 	volatile u_int l1_domain_use_count;
499 
500 	/*
501 	 * A free-list of domain numbers for this L1.
502 	 * We avoid using ffs() and a bitmap to track domains since ffs()
503 	 * is slow on ARM.
504 	 */
505 	uint8_t l1_domain_first;
506 	uint8_t l1_domain_free[PMAP_DOMAINS];
507 
508 	/* Physical address of this L1 page table */
509 	paddr_t l1_physaddr;
510 
511 	/* KVA of this L1 page table */
512 	pd_entry_t *l1_kva;
513 };
514 
515 /*
516  * Convert a virtual address into its L1 table index. That is, the
517  * index used to locate the L2 descriptor table pointer in an L1 table.
518  * This is basically used to index l1->l1_kva[].
519  *
520  * Each L2 descriptor table represents 1MB of VA space.
521  */
522 #define	L1_IDX(va)		(((vaddr_t)(va)) >> L1_S_SHIFT)
523 
524 /*
525  * L1 Page Tables are tracked using a Least Recently Used list.
526  *  - New L1s are allocated from the HEAD.
527  *  - Freed L1s are added to the TAIl.
528  *  - Recently accessed L1s (where an 'access' is some change to one of
529  *    the userland pmaps which owns this L1) are moved to the TAIL.
530  */
531 static TAILQ_HEAD(, l1_ttable) l1_lru_list;
532 static kmutex_t l1_lru_lock __cacheline_aligned;
533 
534 /*
535  * A list of all L1 tables
536  */
537 static SLIST_HEAD(, l1_ttable) l1_list;
538 
539 /*
540  * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
541  *
542  * This is normally 16MB worth L2 page descriptors for any given pmap.
543  * Reference counts are maintained for L2 descriptors so they can be
544  * freed when empty.
545  */
546 struct l2_dtable {
547 	/* The number of L2 page descriptors allocated to this l2_dtable */
548 	u_int l2_occupancy;
549 
550 	/* List of L2 page descriptors */
551 	struct l2_bucket {
552 		pt_entry_t *l2b_kva;	/* KVA of L2 Descriptor Table */
553 		paddr_t l2b_phys;	/* Physical address of same */
554 		u_short l2b_l1idx;	/* This L2 table's L1 index */
555 		u_short l2b_occupancy;	/* How many active descriptors */
556 	} l2_bucket[L2_BUCKET_SIZE];
557 };
558 
559 /*
560  * Given an L1 table index, calculate the corresponding l2_dtable index
561  * and bucket index within the l2_dtable.
562  */
563 #define	L2_IDX(l1idx)		(((l1idx) >> L2_BUCKET_LOG2) & \
564 				 (L2_SIZE - 1))
565 #define	L2_BUCKET(l1idx)	((l1idx) & (L2_BUCKET_SIZE - 1))
566 
567 /*
568  * Given a virtual address, this macro returns the
569  * virtual address required to drop into the next L2 bucket.
570  */
571 #define	L2_NEXT_BUCKET(va)	(((va) & L1_S_FRAME) + L1_S_SIZE)
572 
573 /*
574  * L2 allocation.
575  */
576 #define	pmap_alloc_l2_dtable()		\
577 	    pool_cache_get(&pmap_l2dtable_cache, PR_NOWAIT)
578 #define	pmap_free_l2_dtable(l2)		\
579 	    pool_cache_put(&pmap_l2dtable_cache, (l2))
580 #define pmap_alloc_l2_ptp(pap)		\
581 	    ((pt_entry_t *)pool_cache_get_paddr(&pmap_l2ptp_cache,\
582 	    PR_NOWAIT, (pap)))
583 
584 /*
585  * We try to map the page tables write-through, if possible.  However, not
586  * all CPUs have a write-through cache mode, so on those we have to sync
587  * the cache when we frob page tables.
588  *
589  * We try to evaluate this at compile time, if possible.  However, it's
590  * not always possible to do that, hence this run-time var.
591  */
592 int	pmap_needs_pte_sync;
593 
594 /*
595  * Real definition of pv_entry.
596  */
597 struct pv_entry {
598 	SLIST_ENTRY(pv_entry) pv_link;	/* next pv_entry */
599 	pmap_t		pv_pmap;        /* pmap where mapping lies */
600 	vaddr_t		pv_va;          /* virtual address for mapping */
601 	u_int		pv_flags;       /* flags */
602 };
603 
604 /*
605  * Macro to determine if a mapping might be resident in the
606  * instruction cache and/or TLB
607  */
608 #if ARM_MMU_V7 > 0
609 /*
610  * Speculative loads by Cortex cores can cause TLB entries to be filled even if
611  * there are no explicit accesses, so there may be always be TLB entries to
612  * flush.  If we used ASIDs then this would not be a problem.
613  */
614 #define	PV_BEEN_EXECD(f)  (((f) & PVF_EXEC) == PVF_EXEC)
615 #else
616 #define	PV_BEEN_EXECD(f)  (((f) & (PVF_REF | PVF_EXEC)) == (PVF_REF | PVF_EXEC))
617 #endif
618 #define	PV_IS_EXEC_P(f)   (((f) & PVF_EXEC) != 0)
619 
620 /*
621  * Macro to determine if a mapping might be resident in the
622  * data cache and/or TLB
623  */
624 #if ARM_MMU_V7 > 0
625 /*
626  * Speculative loads by Cortex cores can cause TLB entries to be filled even if
627  * there are no explicit accesses, so there may be always be TLB entries to
628  * flush.  If we used ASIDs then this would not be a problem.
629  */
630 #define	PV_BEEN_REFD(f)   (1)
631 #else
632 #define	PV_BEEN_REFD(f)   (((f) & PVF_REF) != 0)
633 #endif
634 
635 /*
636  * Local prototypes
637  */
638 static int		pmap_set_pt_cache_mode(pd_entry_t *, vaddr_t);
639 static void		pmap_alloc_specials(vaddr_t *, int, vaddr_t *,
640 			    pt_entry_t **);
641 static bool		pmap_is_current(pmap_t);
642 static bool		pmap_is_cached(pmap_t);
643 static void		pmap_enter_pv(struct vm_page_md *, paddr_t, struct pv_entry *,
644 			    pmap_t, vaddr_t, u_int);
645 static struct pv_entry *pmap_find_pv(struct vm_page_md *, pmap_t, vaddr_t);
646 static struct pv_entry *pmap_remove_pv(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
647 static u_int		pmap_modify_pv(struct vm_page_md *, paddr_t, pmap_t, vaddr_t,
648 			    u_int, u_int);
649 
650 static void		pmap_pinit(pmap_t);
651 static int		pmap_pmap_ctor(void *, void *, int);
652 
653 static void		pmap_alloc_l1(pmap_t);
654 static void		pmap_free_l1(pmap_t);
655 static void		pmap_use_l1(pmap_t);
656 
657 static struct l2_bucket *pmap_get_l2_bucket(pmap_t, vaddr_t);
658 static struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vaddr_t);
659 static void		pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
660 static int		pmap_l2ptp_ctor(void *, void *, int);
661 static int		pmap_l2dtable_ctor(void *, void *, int);
662 
663 static void		pmap_vac_me_harder(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
664 #ifdef PMAP_CACHE_VIVT
665 static void		pmap_vac_me_kpmap(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
666 static void		pmap_vac_me_user(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
667 #endif
668 
669 static void		pmap_clearbit(struct vm_page_md *, paddr_t, u_int);
670 #ifdef PMAP_CACHE_VIVT
671 static int		pmap_clean_page(struct pv_entry *, bool);
672 #endif
673 #ifdef PMAP_CACHE_VIPT
674 static void		pmap_syncicache_page(struct vm_page_md *, paddr_t);
675 enum pmap_flush_op {
676 	PMAP_FLUSH_PRIMARY,
677 	PMAP_FLUSH_SECONDARY,
678 	PMAP_CLEAN_PRIMARY
679 };
680 static void		pmap_flush_page(struct vm_page_md *, paddr_t, enum pmap_flush_op);
681 #endif
682 static void		pmap_page_remove(struct vm_page_md *, paddr_t);
683 
684 static void		pmap_init_l1(struct l1_ttable *, pd_entry_t *);
685 static vaddr_t		kernel_pt_lookup(paddr_t);
686 
687 
688 /*
689  * Misc variables
690  */
691 vaddr_t virtual_avail;
692 vaddr_t virtual_end;
693 vaddr_t pmap_curmaxkvaddr;
694 
695 paddr_t avail_start;
696 paddr_t avail_end;
697 
698 pv_addrqh_t pmap_boot_freeq = SLIST_HEAD_INITIALIZER(&pmap_boot_freeq);
699 pv_addr_t kernelpages;
700 pv_addr_t kernel_l1pt;
701 pv_addr_t systempage;
702 
703 /* Function to set the debug level of the pmap code */
704 
705 #ifdef PMAP_DEBUG
706 void
707 pmap_debug(int level)
708 {
709 	pmap_debug_level = level;
710 	printf("pmap_debug: level=%d\n", pmap_debug_level);
711 }
712 #endif	/* PMAP_DEBUG */
713 
714 #ifdef PMAP_CACHE_VIPT
715 #define PMAP_VALIDATE_MD_PAGE(md)	\
716 	KASSERTMSG(arm_cache_prefer_mask == 0 || (((md)->pvh_attrs & PVF_WRITE) == 0) == ((md)->urw_mappings + (md)->krw_mappings == 0), \
717 	    "(md) %p: attrs=%#x urw=%u krw=%u", (md), \
718 	    (md)->pvh_attrs, (md)->urw_mappings, (md)->krw_mappings);
719 #endif /* PMAP_CACHE_VIPT */
720 /*
721  * A bunch of routines to conditionally flush the caches/TLB depending
722  * on whether the specified pmap actually needs to be flushed at any
723  * given time.
724  */
725 static inline void
726 pmap_tlb_flush_SE(pmap_t pm, vaddr_t va, u_int flags)
727 {
728 	if (pm->pm_cstate.cs_tlb_id != 0) {
729 		if (PV_BEEN_EXECD(flags)) {
730 			cpu_tlb_flushID_SE(va);
731 		} else if (PV_BEEN_REFD(flags)) {
732 			cpu_tlb_flushD_SE(va);
733 		}
734 	}
735 }
736 
737 static inline void
738 pmap_tlb_flushID(pmap_t pm)
739 {
740 	if (pm->pm_cstate.cs_tlb_id) {
741 		cpu_tlb_flushID();
742 #if ARM_MMU_V7 == 0
743 		/*
744 		 * Speculative loads by Cortex cores can cause TLB entries to
745 		 * be filled even if there are no explicit accesses, so there
746 		 * may be always be TLB entries to flush.  If we used ASIDs
747 		 * then it would not be a problem.
748 		 * This is not true for other CPUs.
749 		 */
750 		pm->pm_cstate.cs_tlb = 0;
751 #endif /* ARM_MMU_V7 */
752 	}
753 }
754 
755 static inline void
756 pmap_tlb_flushD(pmap_t pm)
757 {
758 	if (pm->pm_cstate.cs_tlb_d) {
759 		cpu_tlb_flushD();
760 #if ARM_MMU_V7 == 0
761 		/*
762 		 * Speculative loads by Cortex cores can cause TLB entries to
763 		 * be filled even if there are no explicit accesses, so there
764 		 * may be always be TLB entries to flush.  If we used ASIDs
765 		 * then it would not be a problem.
766 		 * This is not true for other CPUs.
767 		 */
768 		pm->pm_cstate.cs_tlb_d = 0;
769 #endif /* ARM_MMU_V7 */
770 	}
771 }
772 
773 #ifdef PMAP_CACHE_VIVT
774 static inline void
775 pmap_cache_wbinv_page(pmap_t pm, vaddr_t va, bool do_inv, u_int flags)
776 {
777 	if (PV_BEEN_EXECD(flags) && pm->pm_cstate.cs_cache_id) {
778 		cpu_idcache_wbinv_range(va, PAGE_SIZE);
779 	} else if (PV_BEEN_REFD(flags) && pm->pm_cstate.cs_cache_d) {
780 		if (do_inv) {
781 			if (flags & PVF_WRITE)
782 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
783 			else
784 				cpu_dcache_inv_range(va, PAGE_SIZE);
785 		} else if (flags & PVF_WRITE) {
786 			cpu_dcache_wb_range(va, PAGE_SIZE);
787 		}
788 	}
789 }
790 
791 static inline void
792 pmap_cache_wbinv_all(pmap_t pm, u_int flags)
793 {
794 	if (PV_BEEN_EXECD(flags)) {
795 		if (pm->pm_cstate.cs_cache_id) {
796 			cpu_idcache_wbinv_all();
797 			pm->pm_cstate.cs_cache = 0;
798 		}
799 	} else if (pm->pm_cstate.cs_cache_d) {
800 		cpu_dcache_wbinv_all();
801 		pm->pm_cstate.cs_cache_d = 0;
802 	}
803 }
804 #endif /* PMAP_CACHE_VIVT */
805 
806 static inline uint8_t
807 pmap_domain(pmap_t pm)
808 {
809 	return pm->pm_domain;
810 }
811 
812 static inline pd_entry_t *
813 pmap_l1_kva(pmap_t pm)
814 {
815 	return pm->pm_l1->l1_kva;
816 }
817 
818 static inline bool
819 pmap_is_current(pmap_t pm)
820 {
821 
822 	if (pm == pmap_kernel() || curproc->p_vmspace->vm_map.pmap == pm)
823 		return true;
824 
825 	return false;
826 }
827 
828 static inline bool
829 pmap_is_cached(pmap_t pm)
830 {
831 
832 	if (pm == pmap_kernel() || pmap_recent_user == NULL ||
833 	    pmap_recent_user == pm)
834 		return (true);
835 
836 	return false;
837 }
838 
839 /*
840  * PTE_SYNC_CURRENT:
841  *
842  *     Make sure the pte is written out to RAM.
843  *     We need to do this for one of two cases:
844  *       - We're dealing with the kernel pmap
845  *       - There is no pmap active in the cache/tlb.
846  *       - The specified pmap is 'active' in the cache/tlb.
847  */
848 #ifdef PMAP_INCLUDE_PTE_SYNC
849 #define	PTE_SYNC_CURRENT(pm, ptep)	\
850 do {					\
851 	if (PMAP_NEEDS_PTE_SYNC && 	\
852 	    pmap_is_cached(pm))		\
853 		PTE_SYNC(ptep);		\
854 } while (/*CONSTCOND*/0)
855 #else
856 #define	PTE_SYNC_CURRENT(pm, ptep)	/* nothing */
857 #endif
858 
859 /*
860  * main pv_entry manipulation functions:
861  *   pmap_enter_pv: enter a mapping onto a vm_page list
862  *   pmap_remove_pv: remove a mapping from a vm_page list
863  *
864  * NOTE: pmap_enter_pv expects to lock the pvh itself
865  *       pmap_remove_pv expects the caller to lock the pvh before calling
866  */
867 
868 /*
869  * pmap_enter_pv: enter a mapping onto a vm_page lst
870  *
871  * => caller should hold the proper lock on pmap_main_lock
872  * => caller should have pmap locked
873  * => we will gain the lock on the vm_page and allocate the new pv_entry
874  * => caller should adjust ptp's wire_count before calling
875  * => caller should not adjust pmap's wire_count
876  */
877 static void
878 pmap_enter_pv(struct vm_page_md *md, paddr_t pa, struct pv_entry *pv, pmap_t pm,
879     vaddr_t va, u_int flags)
880 {
881 	struct pv_entry **pvp;
882 
883 	NPDEBUG(PDB_PVDUMP,
884 	    printf("pmap_enter_pv: pm %p, md %p, flags 0x%x\n", pm, md, flags));
885 
886 	pv->pv_pmap = pm;
887 	pv->pv_va = va;
888 	pv->pv_flags = flags;
889 
890 	pvp = &SLIST_FIRST(&md->pvh_list);
891 #ifdef PMAP_CACHE_VIPT
892 	/*
893 	 * Insert unmanaged entries, writeable first, at the head of
894 	 * the pv list.
895 	 */
896 	if (__predict_true((flags & PVF_KENTRY) == 0)) {
897 		while (*pvp != NULL && (*pvp)->pv_flags & PVF_KENTRY)
898 			pvp = &SLIST_NEXT(*pvp, pv_link);
899 	} else if ((flags & PVF_WRITE) == 0) {
900 		while (*pvp != NULL && (*pvp)->pv_flags & PVF_WRITE)
901 			pvp = &SLIST_NEXT(*pvp, pv_link);
902 	}
903 #endif
904 	SLIST_NEXT(pv, pv_link) = *pvp;		/* add to ... */
905 	*pvp = pv;				/* ... locked list */
906 	md->pvh_attrs |= flags & (PVF_REF | PVF_MOD);
907 #ifdef PMAP_CACHE_VIPT
908 	if ((pv->pv_flags & PVF_KWRITE) == PVF_KWRITE)
909 		md->pvh_attrs |= PVF_KMOD;
910 	if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) != PVF_NC)
911 		md->pvh_attrs |= PVF_DIRTY;
912 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
913 #endif
914 	if (pm == pmap_kernel()) {
915 		PMAPCOUNT(kernel_mappings);
916 		if (flags & PVF_WRITE)
917 			md->krw_mappings++;
918 		else
919 			md->kro_mappings++;
920 	} else {
921 		if (flags & PVF_WRITE)
922 			md->urw_mappings++;
923 		else
924 			md->uro_mappings++;
925 	}
926 
927 #ifdef PMAP_CACHE_VIPT
928 	/*
929 	 * Even though pmap_vac_me_harder will set PVF_WRITE for us,
930 	 * do it here as well to keep the mappings & KVF_WRITE consistent.
931 	 */
932 	if (arm_cache_prefer_mask != 0 && (flags & PVF_WRITE) != 0) {
933 		md->pvh_attrs |= PVF_WRITE;
934 	}
935 	/*
936 	 * If this is an exec mapping and its the first exec mapping
937 	 * for this page, make sure to sync the I-cache.
938 	 */
939 	if (PV_IS_EXEC_P(flags)) {
940 		if (!PV_IS_EXEC_P(md->pvh_attrs)) {
941 			pmap_syncicache_page(md, pa);
942 			PMAPCOUNT(exec_synced_map);
943 		}
944 		PMAPCOUNT(exec_mappings);
945 	}
946 #endif
947 
948 	PMAPCOUNT(mappings);
949 
950 	if (pv->pv_flags & PVF_WIRED)
951 		++pm->pm_stats.wired_count;
952 }
953 
954 /*
955  *
956  * pmap_find_pv: Find a pv entry
957  *
958  * => caller should hold lock on vm_page
959  */
960 static inline struct pv_entry *
961 pmap_find_pv(struct vm_page_md *md, pmap_t pm, vaddr_t va)
962 {
963 	struct pv_entry *pv;
964 
965 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
966 		if (pm == pv->pv_pmap && va == pv->pv_va)
967 			break;
968 	}
969 
970 	return (pv);
971 }
972 
973 /*
974  * pmap_remove_pv: try to remove a mapping from a pv_list
975  *
976  * => caller should hold proper lock on pmap_main_lock
977  * => pmap should be locked
978  * => caller should hold lock on vm_page [so that attrs can be adjusted]
979  * => caller should adjust ptp's wire_count and free PTP if needed
980  * => caller should NOT adjust pmap's wire_count
981  * => we return the removed pv
982  */
983 static struct pv_entry *
984 pmap_remove_pv(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
985 {
986 	struct pv_entry *pv, **prevptr;
987 
988 	NPDEBUG(PDB_PVDUMP,
989 	    printf("pmap_remove_pv: pm %p, md %p, va 0x%08lx\n", pm, md, va));
990 
991 	prevptr = &SLIST_FIRST(&md->pvh_list); /* prev pv_entry ptr */
992 	pv = *prevptr;
993 
994 	while (pv) {
995 		if (pv->pv_pmap == pm && pv->pv_va == va) {	/* match? */
996 			NPDEBUG(PDB_PVDUMP, printf("pmap_remove_pv: pm %p, md "
997 			    "%p, flags 0x%x\n", pm, md, pv->pv_flags));
998 			if (pv->pv_flags & PVF_WIRED) {
999 				--pm->pm_stats.wired_count;
1000 			}
1001 			*prevptr = SLIST_NEXT(pv, pv_link);	/* remove it! */
1002 			if (pm == pmap_kernel()) {
1003 				PMAPCOUNT(kernel_unmappings);
1004 				if (pv->pv_flags & PVF_WRITE)
1005 					md->krw_mappings--;
1006 				else
1007 					md->kro_mappings--;
1008 			} else {
1009 				if (pv->pv_flags & PVF_WRITE)
1010 					md->urw_mappings--;
1011 				else
1012 					md->uro_mappings--;
1013 			}
1014 
1015 			PMAPCOUNT(unmappings);
1016 #ifdef PMAP_CACHE_VIPT
1017 			if (!(pv->pv_flags & PVF_WRITE))
1018 				break;
1019 			/*
1020 			 * If this page has had an exec mapping, then if
1021 			 * this was the last mapping, discard the contents,
1022 			 * otherwise sync the i-cache for this page.
1023 			 */
1024 			if (PV_IS_EXEC_P(md->pvh_attrs)) {
1025 				if (SLIST_EMPTY(&md->pvh_list)) {
1026 					md->pvh_attrs &= ~PVF_EXEC;
1027 					PMAPCOUNT(exec_discarded_unmap);
1028 				} else {
1029 					pmap_syncicache_page(md, pa);
1030 					PMAPCOUNT(exec_synced_unmap);
1031 				}
1032 			}
1033 #endif /* PMAP_CACHE_VIPT */
1034 			break;
1035 		}
1036 		prevptr = &SLIST_NEXT(pv, pv_link);	/* previous pointer */
1037 		pv = *prevptr;				/* advance */
1038 	}
1039 
1040 #ifdef PMAP_CACHE_VIPT
1041 	/*
1042 	 * If we no longer have a WRITEABLE KENTRY at the head of list,
1043 	 * clear the KMOD attribute from the page.
1044 	 */
1045 	if (SLIST_FIRST(&md->pvh_list) == NULL
1046 	    || (SLIST_FIRST(&md->pvh_list)->pv_flags & PVF_KWRITE) != PVF_KWRITE)
1047 		md->pvh_attrs &= ~PVF_KMOD;
1048 
1049 	/*
1050 	 * If this was a writeable page and there are no more writeable
1051 	 * mappings (ignoring KMPAGE), clear the WRITE flag and writeback
1052 	 * the contents to memory.
1053 	 */
1054 	if (arm_cache_prefer_mask != 0) {
1055 		if (md->krw_mappings + md->urw_mappings == 0)
1056 			md->pvh_attrs &= ~PVF_WRITE;
1057 		PMAP_VALIDATE_MD_PAGE(md);
1058 	}
1059 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1060 #endif /* PMAP_CACHE_VIPT */
1061 
1062 	return(pv);				/* return removed pv */
1063 }
1064 
1065 /*
1066  *
1067  * pmap_modify_pv: Update pv flags
1068  *
1069  * => caller should hold lock on vm_page [so that attrs can be adjusted]
1070  * => caller should NOT adjust pmap's wire_count
1071  * => caller must call pmap_vac_me_harder() if writable status of a page
1072  *    may have changed.
1073  * => we return the old flags
1074  *
1075  * Modify a physical-virtual mapping in the pv table
1076  */
1077 static u_int
1078 pmap_modify_pv(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va,
1079     u_int clr_mask, u_int set_mask)
1080 {
1081 	struct pv_entry *npv;
1082 	u_int flags, oflags;
1083 
1084 	KASSERT((clr_mask & PVF_KENTRY) == 0);
1085 	KASSERT((set_mask & PVF_KENTRY) == 0);
1086 
1087 	if ((npv = pmap_find_pv(md, pm, va)) == NULL)
1088 		return (0);
1089 
1090 	NPDEBUG(PDB_PVDUMP,
1091 	    printf("pmap_modify_pv: pm %p, md %p, clr 0x%x, set 0x%x, flags 0x%x\n", pm, md, clr_mask, set_mask, npv->pv_flags));
1092 
1093 	/*
1094 	 * There is at least one VA mapping this page.
1095 	 */
1096 
1097 	if (clr_mask & (PVF_REF | PVF_MOD)) {
1098 		md->pvh_attrs |= set_mask & (PVF_REF | PVF_MOD);
1099 #ifdef PMAP_CACHE_VIPT
1100 		if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) != PVF_NC)
1101 			md->pvh_attrs |= PVF_DIRTY;
1102 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1103 #endif
1104 	}
1105 
1106 	oflags = npv->pv_flags;
1107 	npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;
1108 
1109 	if ((flags ^ oflags) & PVF_WIRED) {
1110 		if (flags & PVF_WIRED)
1111 			++pm->pm_stats.wired_count;
1112 		else
1113 			--pm->pm_stats.wired_count;
1114 	}
1115 
1116 	if ((flags ^ oflags) & PVF_WRITE) {
1117 		if (pm == pmap_kernel()) {
1118 			if (flags & PVF_WRITE) {
1119 				md->krw_mappings++;
1120 				md->kro_mappings--;
1121 			} else {
1122 				md->kro_mappings++;
1123 				md->krw_mappings--;
1124 			}
1125 		} else {
1126 			if (flags & PVF_WRITE) {
1127 				md->urw_mappings++;
1128 				md->uro_mappings--;
1129 			} else {
1130 				md->uro_mappings++;
1131 				md->urw_mappings--;
1132 			}
1133 		}
1134 	}
1135 #ifdef PMAP_CACHE_VIPT
1136 	if (arm_cache_prefer_mask != 0) {
1137 		if (md->urw_mappings + md->krw_mappings == 0) {
1138 			md->pvh_attrs &= ~PVF_WRITE;
1139 		} else {
1140 			md->pvh_attrs |= PVF_WRITE;
1141 		}
1142 	}
1143 	/*
1144 	 * We have two cases here: the first is from enter_pv (new exec
1145 	 * page), the second is a combined pmap_remove_pv/pmap_enter_pv.
1146 	 * Since in latter, pmap_enter_pv won't do anything, we just have
1147 	 * to do what pmap_remove_pv would do.
1148 	 */
1149 	if ((PV_IS_EXEC_P(flags) && !PV_IS_EXEC_P(md->pvh_attrs))
1150 	    || (PV_IS_EXEC_P(md->pvh_attrs)
1151 		|| (!(flags & PVF_WRITE) && (oflags & PVF_WRITE)))) {
1152 		pmap_syncicache_page(md, pa);
1153 		PMAPCOUNT(exec_synced_remap);
1154 	}
1155 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1156 #endif
1157 
1158 	PMAPCOUNT(remappings);
1159 
1160 	return (oflags);
1161 }
1162 
1163 /*
1164  * Allocate an L1 translation table for the specified pmap.
1165  * This is called at pmap creation time.
1166  */
1167 static void
1168 pmap_alloc_l1(pmap_t pm)
1169 {
1170 	struct l1_ttable *l1;
1171 	uint8_t domain;
1172 
1173 	/*
1174 	 * Remove the L1 at the head of the LRU list
1175 	 */
1176 	mutex_spin_enter(&l1_lru_lock);
1177 	l1 = TAILQ_FIRST(&l1_lru_list);
1178 	KDASSERT(l1 != NULL);
1179 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
1180 
1181 	/*
1182 	 * Pick the first available domain number, and update
1183 	 * the link to the next number.
1184 	 */
1185 	domain = l1->l1_domain_first;
1186 	l1->l1_domain_first = l1->l1_domain_free[domain];
1187 
1188 	/*
1189 	 * If there are still free domain numbers in this L1,
1190 	 * put it back on the TAIL of the LRU list.
1191 	 */
1192 	if (++l1->l1_domain_use_count < PMAP_DOMAINS)
1193 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
1194 
1195 	mutex_spin_exit(&l1_lru_lock);
1196 
1197 	/*
1198 	 * Fix up the relevant bits in the pmap structure
1199 	 */
1200 	pm->pm_l1 = l1;
1201 	pm->pm_domain = domain + 1;
1202 }
1203 
1204 /*
1205  * Free an L1 translation table.
1206  * This is called at pmap destruction time.
1207  */
1208 static void
1209 pmap_free_l1(pmap_t pm)
1210 {
1211 	struct l1_ttable *l1 = pm->pm_l1;
1212 
1213 	mutex_spin_enter(&l1_lru_lock);
1214 
1215 	/*
1216 	 * If this L1 is currently on the LRU list, remove it.
1217 	 */
1218 	if (l1->l1_domain_use_count < PMAP_DOMAINS)
1219 		TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
1220 
1221 	/*
1222 	 * Free up the domain number which was allocated to the pmap
1223 	 */
1224 	l1->l1_domain_free[pmap_domain(pm) - 1] = l1->l1_domain_first;
1225 	l1->l1_domain_first = pmap_domain(pm) - 1;
1226 	l1->l1_domain_use_count--;
1227 
1228 	/*
1229 	 * The L1 now must have at least 1 free domain, so add
1230 	 * it back to the LRU list. If the use count is zero,
1231 	 * put it at the head of the list, otherwise it goes
1232 	 * to the tail.
1233 	 */
1234 	if (l1->l1_domain_use_count == 0)
1235 		TAILQ_INSERT_HEAD(&l1_lru_list, l1, l1_lru);
1236 	else
1237 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
1238 
1239 	mutex_spin_exit(&l1_lru_lock);
1240 }
1241 
1242 static inline void
1243 pmap_use_l1(pmap_t pm)
1244 {
1245 	struct l1_ttable *l1;
1246 
1247 	/*
1248 	 * Do nothing if we're in interrupt context.
1249 	 * Access to an L1 by the kernel pmap must not affect
1250 	 * the LRU list.
1251 	 */
1252 	if (cpu_intr_p() || pm == pmap_kernel())
1253 		return;
1254 
1255 	l1 = pm->pm_l1;
1256 
1257 	/*
1258 	 * If the L1 is not currently on the LRU list, just return
1259 	 */
1260 	if (l1->l1_domain_use_count == PMAP_DOMAINS)
1261 		return;
1262 
1263 	mutex_spin_enter(&l1_lru_lock);
1264 
1265 	/*
1266 	 * Check the use count again, now that we've acquired the lock
1267 	 */
1268 	if (l1->l1_domain_use_count == PMAP_DOMAINS) {
1269 		mutex_spin_exit(&l1_lru_lock);
1270 		return;
1271 	}
1272 
1273 	/*
1274 	 * Move the L1 to the back of the LRU list
1275 	 */
1276 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
1277 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
1278 
1279 	mutex_spin_exit(&l1_lru_lock);
1280 }
1281 
1282 /*
1283  * void pmap_free_l2_ptp(pt_entry_t *, paddr_t *)
1284  *
1285  * Free an L2 descriptor table.
1286  */
1287 static inline void
1288 #ifndef PMAP_INCLUDE_PTE_SYNC
1289 pmap_free_l2_ptp(pt_entry_t *l2, paddr_t pa)
1290 #else
1291 pmap_free_l2_ptp(bool need_sync, pt_entry_t *l2, paddr_t pa)
1292 #endif
1293 {
1294 #ifdef PMAP_INCLUDE_PTE_SYNC
1295 #ifdef PMAP_CACHE_VIVT
1296 	/*
1297 	 * Note: With a write-back cache, we may need to sync this
1298 	 * L2 table before re-using it.
1299 	 * This is because it may have belonged to a non-current
1300 	 * pmap, in which case the cache syncs would have been
1301 	 * skipped for the pages that were being unmapped. If the
1302 	 * L2 table were then to be immediately re-allocated to
1303 	 * the *current* pmap, it may well contain stale mappings
1304 	 * which have not yet been cleared by a cache write-back
1305 	 * and so would still be visible to the mmu.
1306 	 */
1307 	if (need_sync)
1308 		PTE_SYNC_RANGE(l2, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1309 #endif /* PMAP_CACHE_VIVT */
1310 #endif /* PMAP_INCLUDE_PTE_SYNC */
1311 	pool_cache_put_paddr(&pmap_l2ptp_cache, (void *)l2, pa);
1312 }
1313 
1314 /*
1315  * Returns a pointer to the L2 bucket associated with the specified pmap
1316  * and VA, or NULL if no L2 bucket exists for the address.
1317  */
1318 static inline struct l2_bucket *
1319 pmap_get_l2_bucket(pmap_t pm, vaddr_t va)
1320 {
1321 	struct l2_dtable *l2;
1322 	struct l2_bucket *l2b;
1323 	u_short l1idx;
1324 
1325 	l1idx = L1_IDX(va);
1326 
1327 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL ||
1328 	    (l2b = &l2->l2_bucket[L2_BUCKET(l1idx)])->l2b_kva == NULL)
1329 		return (NULL);
1330 
1331 	return (l2b);
1332 }
1333 
1334 /*
1335  * Returns a pointer to the L2 bucket associated with the specified pmap
1336  * and VA.
1337  *
1338  * If no L2 bucket exists, perform the necessary allocations to put an L2
1339  * bucket/page table in place.
1340  *
1341  * Note that if a new L2 bucket/page was allocated, the caller *must*
1342  * increment the bucket occupancy counter appropriately *before*
1343  * releasing the pmap's lock to ensure no other thread or cpu deallocates
1344  * the bucket/page in the meantime.
1345  */
1346 static struct l2_bucket *
1347 pmap_alloc_l2_bucket(pmap_t pm, vaddr_t va)
1348 {
1349 	struct l2_dtable *l2;
1350 	struct l2_bucket *l2b;
1351 	u_short l1idx;
1352 
1353 	l1idx = L1_IDX(va);
1354 
1355 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
1356 		/*
1357 		 * No mapping at this address, as there is
1358 		 * no entry in the L1 table.
1359 		 * Need to allocate a new l2_dtable.
1360 		 */
1361 		if ((l2 = pmap_alloc_l2_dtable()) == NULL)
1362 			return (NULL);
1363 
1364 		/*
1365 		 * Link it into the parent pmap
1366 		 */
1367 		pm->pm_l2[L2_IDX(l1idx)] = l2;
1368 	}
1369 
1370 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
1371 
1372 	/*
1373 	 * Fetch pointer to the L2 page table associated with the address.
1374 	 */
1375 	if (l2b->l2b_kva == NULL) {
1376 		pt_entry_t *ptep;
1377 
1378 		/*
1379 		 * No L2 page table has been allocated. Chances are, this
1380 		 * is because we just allocated the l2_dtable, above.
1381 		 */
1382 		if ((ptep = pmap_alloc_l2_ptp(&l2b->l2b_phys)) == NULL) {
1383 			/*
1384 			 * Oops, no more L2 page tables available at this
1385 			 * time. We may need to deallocate the l2_dtable
1386 			 * if we allocated a new one above.
1387 			 */
1388 			if (l2->l2_occupancy == 0) {
1389 				pm->pm_l2[L2_IDX(l1idx)] = NULL;
1390 				pmap_free_l2_dtable(l2);
1391 			}
1392 			return (NULL);
1393 		}
1394 
1395 		l2->l2_occupancy++;
1396 		l2b->l2b_kva = ptep;
1397 		l2b->l2b_l1idx = l1idx;
1398 	}
1399 
1400 	return (l2b);
1401 }
1402 
1403 /*
1404  * One or more mappings in the specified L2 descriptor table have just been
1405  * invalidated.
1406  *
1407  * Garbage collect the metadata and descriptor table itself if necessary.
1408  *
1409  * The pmap lock must be acquired when this is called (not necessary
1410  * for the kernel pmap).
1411  */
1412 static void
1413 pmap_free_l2_bucket(pmap_t pm, struct l2_bucket *l2b, u_int count)
1414 {
1415 	struct l2_dtable *l2;
1416 	pd_entry_t *pl1pd, l1pd;
1417 	pt_entry_t *ptep;
1418 	u_short l1idx;
1419 
1420 	KDASSERT(count <= l2b->l2b_occupancy);
1421 
1422 	/*
1423 	 * Update the bucket's reference count according to how many
1424 	 * PTEs the caller has just invalidated.
1425 	 */
1426 	l2b->l2b_occupancy -= count;
1427 
1428 	/*
1429 	 * Note:
1430 	 *
1431 	 * Level 2 page tables allocated to the kernel pmap are never freed
1432 	 * as that would require checking all Level 1 page tables and
1433 	 * removing any references to the Level 2 page table. See also the
1434 	 * comment elsewhere about never freeing bootstrap L2 descriptors.
1435 	 *
1436 	 * We make do with just invalidating the mapping in the L2 table.
1437 	 *
1438 	 * This isn't really a big deal in practice and, in fact, leads
1439 	 * to a performance win over time as we don't need to continually
1440 	 * alloc/free.
1441 	 */
1442 	if (l2b->l2b_occupancy > 0 || pm == pmap_kernel())
1443 		return;
1444 
1445 	/*
1446 	 * There are no more valid mappings in this level 2 page table.
1447 	 * Go ahead and NULL-out the pointer in the bucket, then
1448 	 * free the page table.
1449 	 */
1450 	l1idx = l2b->l2b_l1idx;
1451 	ptep = l2b->l2b_kva;
1452 	l2b->l2b_kva = NULL;
1453 
1454 	pl1pd = pmap_l1_kva(pm) + l1idx;
1455 
1456 	/*
1457 	 * If the L1 slot matches the pmap's domain
1458 	 * number, then invalidate it.
1459 	 */
1460 	l1pd = *pl1pd & (L1_TYPE_MASK | L1_C_DOM_MASK);
1461 	if (l1pd == (L1_C_DOM(pmap_domain(pm)) | L1_TYPE_C)) {
1462 		*pl1pd = 0;
1463 		PTE_SYNC(pl1pd);
1464 	}
1465 
1466 	/*
1467 	 * Release the L2 descriptor table back to the pool cache.
1468 	 */
1469 #ifndef PMAP_INCLUDE_PTE_SYNC
1470 	pmap_free_l2_ptp(ptep, l2b->l2b_phys);
1471 #else
1472 	pmap_free_l2_ptp(!pmap_is_cached(pm), ptep, l2b->l2b_phys);
1473 #endif
1474 
1475 	/*
1476 	 * Update the reference count in the associated l2_dtable
1477 	 */
1478 	l2 = pm->pm_l2[L2_IDX(l1idx)];
1479 	if (--l2->l2_occupancy > 0)
1480 		return;
1481 
1482 	/*
1483 	 * There are no more valid mappings in any of the Level 1
1484 	 * slots managed by this l2_dtable. Go ahead and NULL-out
1485 	 * the pointer in the parent pmap and free the l2_dtable.
1486 	 */
1487 	pm->pm_l2[L2_IDX(l1idx)] = NULL;
1488 	pmap_free_l2_dtable(l2);
1489 }
1490 
1491 /*
1492  * Pool cache constructors for L2 descriptor tables, metadata and pmap
1493  * structures.
1494  */
1495 static int
1496 pmap_l2ptp_ctor(void *arg, void *v, int flags)
1497 {
1498 #ifndef PMAP_INCLUDE_PTE_SYNC
1499 	vaddr_t va = (vaddr_t)v & ~PGOFSET;
1500 
1501 	/*
1502 	 * The mappings for these page tables were initially made using
1503 	 * pmap_kenter_pa() by the pool subsystem. Therefore, the cache-
1504 	 * mode will not be right for page table mappings. To avoid
1505 	 * polluting the pmap_kenter_pa() code with a special case for
1506 	 * page tables, we simply fix up the cache-mode here if it's not
1507 	 * correct.
1508 	 */
1509 	struct l2_bucket * const l2b = pmap_get_l2_bucket(pmap_kernel(), va);
1510 	KDASSERT(l2b != NULL);
1511 	pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(va)];
1512 	pt_entry_t opte = *ptep;
1513 
1514 	if ((opte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
1515 		/*
1516 		 * Page tables must have the cache-mode set to Write-Thru.
1517 		 */
1518 		const pt_entry_t npte = (pte & ~L2_S_CACHE_MASK)
1519 		    | pte_l2_s_cache_mode_pt;
1520 		l2pte_set(ptep, npte, opte);
1521 		PTE_SYNC(ptep);
1522 		cpu_tlb_flushD_SE(va);
1523 		cpu_cpwait();
1524 	}
1525 #endif
1526 
1527 	memset(v, 0, L2_TABLE_SIZE_REAL);
1528 	PTE_SYNC_RANGE(v, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
1529 	return (0);
1530 }
1531 
1532 static int
1533 pmap_l2dtable_ctor(void *arg, void *v, int flags)
1534 {
1535 
1536 	memset(v, 0, sizeof(struct l2_dtable));
1537 	return (0);
1538 }
1539 
1540 static int
1541 pmap_pmap_ctor(void *arg, void *v, int flags)
1542 {
1543 
1544 	memset(v, 0, sizeof(struct pmap));
1545 	return (0);
1546 }
1547 
1548 static void
1549 pmap_pinit(pmap_t pm)
1550 {
1551 #ifndef ARM_HAS_VBAR
1552 	struct l2_bucket *l2b;
1553 
1554 	if (vector_page < KERNEL_BASE) {
1555 		/*
1556 		 * Map the vector page.
1557 		 */
1558 		pmap_enter(pm, vector_page, systempage.pv_pa,
1559 		    VM_PROT_READ | VM_PROT_EXECUTE,
1560 		    VM_PROT_READ | VM_PROT_EXECUTE | PMAP_WIRED);
1561 		pmap_update(pm);
1562 
1563 		pm->pm_pl1vec = pmap_l1_kva(pm) + L1_IDX(vector_page);
1564 		l2b = pmap_get_l2_bucket(pm, vector_page);
1565 		KDASSERT(l2b != NULL);
1566 		pm->pm_l1vec = l2b->l2b_phys | L1_C_PROTO |
1567 		    L1_C_DOM(pmap_domain(pm));
1568 	} else
1569 		pm->pm_pl1vec = NULL;
1570 #endif
1571 }
1572 
1573 #ifdef PMAP_CACHE_VIVT
1574 /*
1575  * Since we have a virtually indexed cache, we may need to inhibit caching if
1576  * there is more than one mapping and at least one of them is writable.
1577  * Since we purge the cache on every context switch, we only need to check for
1578  * other mappings within the same pmap, or kernel_pmap.
1579  * This function is also called when a page is unmapped, to possibly reenable
1580  * caching on any remaining mappings.
1581  *
1582  * The code implements the following logic, where:
1583  *
1584  * KW = # of kernel read/write pages
1585  * KR = # of kernel read only pages
1586  * UW = # of user read/write pages
1587  * UR = # of user read only pages
1588  *
1589  * KC = kernel mapping is cacheable
1590  * UC = user mapping is cacheable
1591  *
1592  *               KW=0,KR=0  KW=0,KR>0  KW=1,KR=0  KW>1,KR>=0
1593  *             +---------------------------------------------
1594  * UW=0,UR=0   | ---        KC=1       KC=1       KC=0
1595  * UW=0,UR>0   | UC=1       KC=1,UC=1  KC=0,UC=0  KC=0,UC=0
1596  * UW=1,UR=0   | UC=1       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
1597  * UW>1,UR>=0  | UC=0       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
1598  */
1599 
1600 static const int pmap_vac_flags[4][4] = {
1601 	{-1,		0,		0,		PVF_KNC},
1602 	{0,		0,		PVF_NC,		PVF_NC},
1603 	{0,		PVF_NC,		PVF_NC,		PVF_NC},
1604 	{PVF_UNC,	PVF_NC,		PVF_NC,		PVF_NC}
1605 };
1606 
1607 static inline int
1608 pmap_get_vac_flags(const struct vm_page_md *md)
1609 {
1610 	int kidx, uidx;
1611 
1612 	kidx = 0;
1613 	if (md->kro_mappings || md->krw_mappings > 1)
1614 		kidx |= 1;
1615 	if (md->krw_mappings)
1616 		kidx |= 2;
1617 
1618 	uidx = 0;
1619 	if (md->uro_mappings || md->urw_mappings > 1)
1620 		uidx |= 1;
1621 	if (md->urw_mappings)
1622 		uidx |= 2;
1623 
1624 	return (pmap_vac_flags[uidx][kidx]);
1625 }
1626 
1627 static inline void
1628 pmap_vac_me_harder(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
1629 {
1630 	int nattr;
1631 
1632 	nattr = pmap_get_vac_flags(md);
1633 
1634 	if (nattr < 0) {
1635 		md->pvh_attrs &= ~PVF_NC;
1636 		return;
1637 	}
1638 
1639 	if (nattr == 0 && (md->pvh_attrs & PVF_NC) == 0)
1640 		return;
1641 
1642 	if (pm == pmap_kernel())
1643 		pmap_vac_me_kpmap(md, pa, pm, va);
1644 	else
1645 		pmap_vac_me_user(md, pa, pm, va);
1646 
1647 	md->pvh_attrs = (md->pvh_attrs & ~PVF_NC) | nattr;
1648 }
1649 
1650 static void
1651 pmap_vac_me_kpmap(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
1652 {
1653 	u_int u_cacheable, u_entries;
1654 	struct pv_entry *pv;
1655 	pmap_t last_pmap = pm;
1656 
1657 	/*
1658 	 * Pass one, see if there are both kernel and user pmaps for
1659 	 * this page.  Calculate whether there are user-writable or
1660 	 * kernel-writable pages.
1661 	 */
1662 	u_cacheable = 0;
1663 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
1664 		if (pv->pv_pmap != pm && (pv->pv_flags & PVF_NC) == 0)
1665 			u_cacheable++;
1666 	}
1667 
1668 	u_entries = md->urw_mappings + md->uro_mappings;
1669 
1670 	/*
1671 	 * We know we have just been updating a kernel entry, so if
1672 	 * all user pages are already cacheable, then there is nothing
1673 	 * further to do.
1674 	 */
1675 	if (md->k_mappings == 0 && u_cacheable == u_entries)
1676 		return;
1677 
1678 	if (u_entries) {
1679 		/*
1680 		 * Scan over the list again, for each entry, if it
1681 		 * might not be set correctly, call pmap_vac_me_user
1682 		 * to recalculate the settings.
1683 		 */
1684 		SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
1685 			/*
1686 			 * We know kernel mappings will get set
1687 			 * correctly in other calls.  We also know
1688 			 * that if the pmap is the same as last_pmap
1689 			 * then we've just handled this entry.
1690 			 */
1691 			if (pv->pv_pmap == pm || pv->pv_pmap == last_pmap)
1692 				continue;
1693 
1694 			/*
1695 			 * If there are kernel entries and this page
1696 			 * is writable but non-cacheable, then we can
1697 			 * skip this entry also.
1698 			 */
1699 			if (md->k_mappings &&
1700 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) ==
1701 			    (PVF_NC | PVF_WRITE))
1702 				continue;
1703 
1704 			/*
1705 			 * Similarly if there are no kernel-writable
1706 			 * entries and the page is already
1707 			 * read-only/cacheable.
1708 			 */
1709 			if (md->krw_mappings == 0 &&
1710 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) == 0)
1711 				continue;
1712 
1713 			/*
1714 			 * For some of the remaining cases, we know
1715 			 * that we must recalculate, but for others we
1716 			 * can't tell if they are correct or not, so
1717 			 * we recalculate anyway.
1718 			 */
1719 			pmap_vac_me_user(md, pa, (last_pmap = pv->pv_pmap), 0);
1720 		}
1721 
1722 		if (md->k_mappings == 0)
1723 			return;
1724 	}
1725 
1726 	pmap_vac_me_user(md, pa, pm, va);
1727 }
1728 
1729 static void
1730 pmap_vac_me_user(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
1731 {
1732 	pmap_t kpmap = pmap_kernel();
1733 	struct pv_entry *pv, *npv = NULL;
1734 	u_int entries = 0;
1735 	u_int writable = 0;
1736 	u_int cacheable_entries = 0;
1737 	u_int kern_cacheable = 0;
1738 	u_int other_writable = 0;
1739 
1740 	/*
1741 	 * Count mappings and writable mappings in this pmap.
1742 	 * Include kernel mappings as part of our own.
1743 	 * Keep a pointer to the first one.
1744 	 */
1745 	npv = NULL;
1746 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
1747 		/* Count mappings in the same pmap */
1748 		if (pm == pv->pv_pmap || kpmap == pv->pv_pmap) {
1749 			if (entries++ == 0)
1750 				npv = pv;
1751 
1752 			/* Cacheable mappings */
1753 			if ((pv->pv_flags & PVF_NC) == 0) {
1754 				cacheable_entries++;
1755 				if (kpmap == pv->pv_pmap)
1756 					kern_cacheable++;
1757 			}
1758 
1759 			/* Writable mappings */
1760 			if (pv->pv_flags & PVF_WRITE)
1761 				++writable;
1762 		} else
1763 		if (pv->pv_flags & PVF_WRITE)
1764 			other_writable = 1;
1765 	}
1766 
1767 	/*
1768 	 * Enable or disable caching as necessary.
1769 	 * Note: the first entry might be part of the kernel pmap,
1770 	 * so we can't assume this is indicative of the state of the
1771 	 * other (maybe non-kpmap) entries.
1772 	 */
1773 	if ((entries > 1 && writable) ||
1774 	    (entries > 0 && pm == kpmap && other_writable)) {
1775 		if (cacheable_entries == 0)
1776 			return;
1777 
1778 		for (pv = npv; pv; pv = SLIST_NEXT(pv, pv_link)) {
1779 			if ((pm != pv->pv_pmap && kpmap != pv->pv_pmap) ||
1780 			    (pv->pv_flags & PVF_NC))
1781 				continue;
1782 
1783 			pv->pv_flags |= PVF_NC;
1784 
1785 			struct l2_bucket * const l2b
1786 			    = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
1787 			KDASSERT(l2b != NULL);
1788 			pt_entry_t * const ptep
1789 			    = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
1790 			const pt_entry_t opte = *ptep;
1791 			pt_entry_t npte = opte & ~L2_S_CACHE_MASK;
1792 
1793 			if ((va != pv->pv_va || pm != pv->pv_pmap)
1794 			    && l2pte_valid(npte)) {
1795 #ifdef PMAP_CACHE_VIVT
1796 				pmap_cache_wbinv_page(pv->pv_pmap, pv->pv_va,
1797 				    true, pv->pv_flags);
1798 #endif
1799 				pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va,
1800 				    pv->pv_flags);
1801 			}
1802 
1803 			l2pte_set(ptep, npte, opte);
1804 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
1805 		}
1806 		cpu_cpwait();
1807 	} else
1808 	if (entries > cacheable_entries) {
1809 		/*
1810 		 * Turn cacheing back on for some pages.  If it is a kernel
1811 		 * page, only do so if there are no other writable pages.
1812 		 */
1813 		for (pv = npv; pv; pv = SLIST_NEXT(pv, pv_link)) {
1814 			if (!(pv->pv_flags & PVF_NC) || (pm != pv->pv_pmap &&
1815 			    (kpmap != pv->pv_pmap || other_writable)))
1816 				continue;
1817 
1818 			pv->pv_flags &= ~PVF_NC;
1819 
1820 			struct l2_bucket * const l2b
1821 			    = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
1822 			KDASSERT(l2b != NULL);
1823 			pt_entry_t * const ptep
1824 			    = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
1825 			const pt_entry_t opte = *ptep;
1826 			pt_entry_t npte = (opte & ~L2_S_CACHE_MASK)
1827 			    | pte_l2_s_cache_mode;
1828 
1829 			if (l2pte_valid(opte)) {
1830 				pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va,
1831 				    pv->pv_flags);
1832 			}
1833 
1834 			l2pte_set(ptep, npte, opte);
1835 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
1836 		}
1837 	}
1838 }
1839 #endif
1840 
1841 #ifdef PMAP_CACHE_VIPT
1842 static void
1843 pmap_vac_me_harder(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
1844 {
1845 	struct pv_entry *pv;
1846 	vaddr_t tst_mask;
1847 	bool bad_alias;
1848 	const u_int
1849 	    rw_mappings = md->urw_mappings + md->krw_mappings,
1850 	    ro_mappings = md->uro_mappings + md->kro_mappings;
1851 
1852 	/* do we need to do anything? */
1853 	if (arm_cache_prefer_mask == 0)
1854 		return;
1855 
1856 	NPDEBUG(PDB_VAC, printf("pmap_vac_me_harder: md=%p, pmap=%p va=%08lx\n",
1857 	    md, pm, va));
1858 
1859 	KASSERT(!va || pm);
1860 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1861 
1862 	/* Already a conflict? */
1863 	if (__predict_false(md->pvh_attrs & PVF_NC)) {
1864 		/* just an add, things are already non-cached */
1865 		KASSERT(!(md->pvh_attrs & PVF_DIRTY));
1866 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
1867 		bad_alias = false;
1868 		if (va) {
1869 			PMAPCOUNT(vac_color_none);
1870 			bad_alias = true;
1871 			KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
1872 			goto fixup;
1873 		}
1874 		pv = SLIST_FIRST(&md->pvh_list);
1875 		/* the list can't be empty because it would be cachable */
1876 		if (md->pvh_attrs & PVF_KMPAGE) {
1877 			tst_mask = md->pvh_attrs;
1878 		} else {
1879 			KASSERT(pv);
1880 			tst_mask = pv->pv_va;
1881 			pv = SLIST_NEXT(pv, pv_link);
1882 		}
1883 		/*
1884 		 * Only check for a bad alias if we have writable mappings.
1885 		 */
1886 		tst_mask &= arm_cache_prefer_mask;
1887 		if (rw_mappings > 0) {
1888 			for (; pv && !bad_alias; pv = SLIST_NEXT(pv, pv_link)) {
1889 				/* if there's a bad alias, stop checking. */
1890 				if (tst_mask != (pv->pv_va & arm_cache_prefer_mask))
1891 					bad_alias = true;
1892 			}
1893 			md->pvh_attrs |= PVF_WRITE;
1894 			if (!bad_alias)
1895 				md->pvh_attrs |= PVF_DIRTY;
1896 		} else {
1897 			/*
1898 			 * We have only read-only mappings.  Let's see if there
1899 			 * are multiple colors in use or if we mapped a KMPAGE.
1900 			 * If the latter, we have a bad alias.  If the former,
1901 			 * we need to remember that.
1902 			 */
1903 			for (; pv; pv = SLIST_NEXT(pv, pv_link)) {
1904 				if (tst_mask != (pv->pv_va & arm_cache_prefer_mask)) {
1905 					if (md->pvh_attrs & PVF_KMPAGE)
1906 						bad_alias = true;
1907 					break;
1908 				}
1909 			}
1910 			md->pvh_attrs &= ~PVF_WRITE;
1911 			/*
1912 			 * No KMPAGE and we exited early, so we must have
1913 			 * multiple color mappings.
1914 			 */
1915 			if (!bad_alias && pv != NULL)
1916 				md->pvh_attrs |= PVF_MULTCLR;
1917 		}
1918 
1919 		/* If no conflicting colors, set everything back to cached */
1920 		if (!bad_alias) {
1921 #ifdef DEBUG
1922 			if ((md->pvh_attrs & PVF_WRITE)
1923 			    || ro_mappings < 2) {
1924 				SLIST_FOREACH(pv, &md->pvh_list, pv_link)
1925 					KDASSERT(((tst_mask ^ pv->pv_va) & arm_cache_prefer_mask) == 0);
1926 			}
1927 #endif
1928 			md->pvh_attrs &= (PAGE_SIZE - 1) & ~PVF_NC;
1929 			md->pvh_attrs |= tst_mask | PVF_COLORED;
1930 			/*
1931 			 * Restore DIRTY bit if page is modified
1932 			 */
1933 			if (md->pvh_attrs & PVF_DMOD)
1934 				md->pvh_attrs |= PVF_DIRTY;
1935 			PMAPCOUNT(vac_color_restore);
1936 		} else {
1937 			KASSERT(SLIST_FIRST(&md->pvh_list) != NULL);
1938 			KASSERT(SLIST_NEXT(SLIST_FIRST(&md->pvh_list), pv_link) != NULL);
1939 		}
1940 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1941 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
1942 	} else if (!va) {
1943 		KASSERT(pmap_is_page_colored_p(md));
1944 		KASSERT(!(md->pvh_attrs & PVF_WRITE)
1945 		    || (md->pvh_attrs & PVF_DIRTY));
1946 		if (rw_mappings == 0) {
1947 			md->pvh_attrs &= ~PVF_WRITE;
1948 			if (ro_mappings == 1
1949 			    && (md->pvh_attrs & PVF_MULTCLR)) {
1950 				/*
1951 				 * If this is the last readonly mapping
1952 				 * but it doesn't match the current color
1953 				 * for the page, change the current color
1954 				 * to match this last readonly mapping.
1955 				 */
1956 				pv = SLIST_FIRST(&md->pvh_list);
1957 				tst_mask = (md->pvh_attrs ^ pv->pv_va)
1958 				    & arm_cache_prefer_mask;
1959 				if (tst_mask) {
1960 					md->pvh_attrs ^= tst_mask;
1961 					PMAPCOUNT(vac_color_change);
1962 				}
1963 			}
1964 		}
1965 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1966 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
1967 		return;
1968 	} else if (!pmap_is_page_colored_p(md)) {
1969 		/* not colored so we just use its color */
1970 		KASSERT(md->pvh_attrs & (PVF_WRITE|PVF_DIRTY));
1971 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
1972 		PMAPCOUNT(vac_color_new);
1973 		md->pvh_attrs &= PAGE_SIZE - 1;
1974 		md->pvh_attrs |= PVF_COLORED
1975 		    | (va & arm_cache_prefer_mask)
1976 		    | (rw_mappings > 0 ? PVF_WRITE : 0);
1977 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
1978 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
1979 		return;
1980 	} else if (((md->pvh_attrs ^ va) & arm_cache_prefer_mask) == 0) {
1981 		bad_alias = false;
1982 		if (rw_mappings > 0) {
1983 			/*
1984 			 * We now have writeable mappings and if we have
1985 			 * readonly mappings in more than once color, we have
1986 			 * an aliasing problem.  Regardless mark the page as
1987 			 * writeable.
1988 			 */
1989 			if (md->pvh_attrs & PVF_MULTCLR) {
1990 				if (ro_mappings < 2) {
1991 					/*
1992 					 * If we only have less than two
1993 					 * read-only mappings, just flush the
1994 					 * non-primary colors from the cache.
1995 					 */
1996 					pmap_flush_page(md, pa,
1997 					    PMAP_FLUSH_SECONDARY);
1998 				} else {
1999 					bad_alias = true;
2000 				}
2001 			}
2002 			md->pvh_attrs |= PVF_WRITE;
2003 		}
2004 		/* If no conflicting colors, set everything back to cached */
2005 		if (!bad_alias) {
2006 #ifdef DEBUG
2007 			if (rw_mappings > 0
2008 			    || (md->pvh_attrs & PMAP_KMPAGE)) {
2009 				tst_mask = md->pvh_attrs & arm_cache_prefer_mask;
2010 				SLIST_FOREACH(pv, &md->pvh_list, pv_link)
2011 					KDASSERT(((tst_mask ^ pv->pv_va) & arm_cache_prefer_mask) == 0);
2012 			}
2013 #endif
2014 			if (SLIST_EMPTY(&md->pvh_list))
2015 				PMAPCOUNT(vac_color_reuse);
2016 			else
2017 				PMAPCOUNT(vac_color_ok);
2018 
2019 			/* matching color, just return */
2020 			KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
2021 			KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
2022 			return;
2023 		}
2024 		KASSERT(SLIST_FIRST(&md->pvh_list) != NULL);
2025 		KASSERT(SLIST_NEXT(SLIST_FIRST(&md->pvh_list), pv_link) != NULL);
2026 
2027 		/* color conflict.  evict from cache. */
2028 
2029 		pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
2030 		md->pvh_attrs &= ~PVF_COLORED;
2031 		md->pvh_attrs |= PVF_NC;
2032 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
2033 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
2034 		PMAPCOUNT(vac_color_erase);
2035 	} else if (rw_mappings == 0
2036 		   && (md->pvh_attrs & PVF_KMPAGE) == 0) {
2037 		KASSERT((md->pvh_attrs & PVF_WRITE) == 0);
2038 
2039 		/*
2040 		 * If the page has dirty cache lines, clean it.
2041 		 */
2042 		if (md->pvh_attrs & PVF_DIRTY)
2043 			pmap_flush_page(md, pa, PMAP_CLEAN_PRIMARY);
2044 
2045 		/*
2046 		 * If this is the first remapping (we know that there are no
2047 		 * writeable mappings), then this is a simple color change.
2048 		 * Otherwise this is a seconary r/o mapping, which means
2049 		 * we don't have to do anything.
2050 		 */
2051 		if (ro_mappings == 1) {
2052 			KASSERT(((md->pvh_attrs ^ va) & arm_cache_prefer_mask) != 0);
2053 			md->pvh_attrs &= PAGE_SIZE - 1;
2054 			md->pvh_attrs |= (va & arm_cache_prefer_mask);
2055 			PMAPCOUNT(vac_color_change);
2056 		} else {
2057 			PMAPCOUNT(vac_color_blind);
2058 		}
2059 		md->pvh_attrs |= PVF_MULTCLR;
2060 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
2061 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
2062 		return;
2063 	} else {
2064 		if (rw_mappings > 0)
2065 			md->pvh_attrs |= PVF_WRITE;
2066 
2067 		/* color conflict.  evict from cache. */
2068 		pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
2069 
2070 		/* the list can't be empty because this was a enter/modify */
2071 		pv = SLIST_FIRST(&md->pvh_list);
2072 		if ((md->pvh_attrs & PVF_KMPAGE) == 0) {
2073 			KASSERT(pv);
2074 			/*
2075 			 * If there's only one mapped page, change color to the
2076 			 * page's new color and return.  Restore the DIRTY bit
2077 			 * that was erased by pmap_flush_page.
2078 			 */
2079 			if (SLIST_NEXT(pv, pv_link) == NULL) {
2080 				md->pvh_attrs &= PAGE_SIZE - 1;
2081 				md->pvh_attrs |= (va & arm_cache_prefer_mask);
2082 				if (md->pvh_attrs & PVF_DMOD)
2083 					md->pvh_attrs |= PVF_DIRTY;
2084 				PMAPCOUNT(vac_color_change);
2085 				KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
2086 				KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
2087 				KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
2088 				return;
2089 			}
2090 		}
2091 		bad_alias = true;
2092 		md->pvh_attrs &= ~PVF_COLORED;
2093 		md->pvh_attrs |= PVF_NC;
2094 		PMAPCOUNT(vac_color_erase);
2095 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
2096 	}
2097 
2098   fixup:
2099 	KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
2100 
2101 	/*
2102 	 * Turn cacheing on/off for all pages.
2103 	 */
2104 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
2105 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pv->pv_pmap,
2106 		    pv->pv_va);
2107 		KDASSERT(l2b != NULL);
2108 		pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
2109 		const pt_entry_t opte = *ptep;
2110 		pt_entry_t npte = opte & ~L2_S_CACHE_MASK;
2111 		if (bad_alias) {
2112 			pv->pv_flags |= PVF_NC;
2113 		} else {
2114 			pv->pv_flags &= ~PVF_NC;
2115 			npte |= pte_l2_s_cache_mode;
2116 		}
2117 
2118 		if (opte == npte)	/* only update is there's a change */
2119 			continue;
2120 
2121 		if (l2pte_valid(npte)) {
2122 			pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va, pv->pv_flags);
2123 		}
2124 
2125 		l2pte_set(ptep, npte, opte);
2126 		PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
2127 	}
2128 }
2129 #endif	/* PMAP_CACHE_VIPT */
2130 
2131 
2132 /*
2133  * Modify pte bits for all ptes corresponding to the given physical address.
2134  * We use `maskbits' rather than `clearbits' because we're always passing
2135  * constants and the latter would require an extra inversion at run-time.
2136  */
2137 static void
2138 pmap_clearbit(struct vm_page_md *md, paddr_t pa, u_int maskbits)
2139 {
2140 	struct pv_entry *pv;
2141 	pmap_t pm;
2142 	vaddr_t va;
2143 	u_int oflags;
2144 #ifdef PMAP_CACHE_VIPT
2145 	const bool want_syncicache = PV_IS_EXEC_P(md->pvh_attrs);
2146 	bool need_vac_me_harder = false;
2147 	bool need_syncicache = false;
2148 #endif
2149 
2150 	NPDEBUG(PDB_BITS,
2151 	    printf("pmap_clearbit: md %p mask 0x%x\n",
2152 	    md, maskbits));
2153 
2154 #ifdef PMAP_CACHE_VIPT
2155 	/*
2156 	 * If we might want to sync the I-cache and we've modified it,
2157 	 * then we know we definitely need to sync or discard it.
2158 	 */
2159 	if (want_syncicache) {
2160 		need_syncicache = md->pvh_attrs & PVF_MOD;
2161 	}
2162 #endif
2163 	/*
2164 	 * Clear saved attributes (modify, reference)
2165 	 */
2166 	md->pvh_attrs &= ~(maskbits & (PVF_MOD | PVF_REF));
2167 
2168 	if (SLIST_EMPTY(&md->pvh_list)) {
2169 #if defined(PMAP_CACHE_VIPT)
2170 		if (need_syncicache) {
2171 			/*
2172 			 * No one has it mapped, so just discard it.  The next
2173 			 * exec remapping will cause it to be synced.
2174 			 */
2175 			md->pvh_attrs &= ~PVF_EXEC;
2176 			PMAPCOUNT(exec_discarded_clearbit);
2177 		}
2178 #endif
2179 		return;
2180 	}
2181 
2182 	/*
2183 	 * Loop over all current mappings setting/clearing as appropos
2184 	 */
2185 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
2186 		va = pv->pv_va;
2187 		pm = pv->pv_pmap;
2188 		oflags = pv->pv_flags;
2189 		/*
2190 		 * Kernel entries are unmanaged and as such not to be changed.
2191 		 */
2192 		if (oflags & PVF_KENTRY)
2193 			continue;
2194 		pv->pv_flags &= ~maskbits;
2195 
2196 		pmap_acquire_pmap_lock(pm);
2197 
2198 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pm, va);
2199 		KDASSERT(l2b != NULL);
2200 
2201 		pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
2202 		const pt_entry_t opte = *ptep;
2203 		pt_entry_t npte = opte;
2204 
2205 		NPDEBUG(PDB_BITS,
2206 		    printf(
2207 		    "pmap_clearbit: pv %p, pm %p, va 0x%08lx, flag 0x%x\n",
2208 		    pv, pv->pv_pmap, pv->pv_va, oflags));
2209 
2210 		if (maskbits & (PVF_WRITE|PVF_MOD)) {
2211 #ifdef PMAP_CACHE_VIVT
2212 			if ((pv->pv_flags & PVF_NC)) {
2213 				/*
2214 				 * Entry is not cacheable:
2215 				 *
2216 				 * Don't turn caching on again if this is a
2217 				 * modified emulation. This would be
2218 				 * inconsitent with the settings created by
2219 				 * pmap_vac_me_harder(). Otherwise, it's safe
2220 				 * to re-enable cacheing.
2221 				 *
2222 				 * There's no need to call pmap_vac_me_harder()
2223 				 * here: all pages are losing their write
2224 				 * permission.
2225 				 */
2226 				if (maskbits & PVF_WRITE) {
2227 					npte |= pte_l2_s_cache_mode;
2228 					pv->pv_flags &= ~PVF_NC;
2229 				}
2230 			} else
2231 			if (l2pte_writable_p(opte)) {
2232 				/*
2233 				 * Entry is writable/cacheable: check if pmap
2234 				 * is current if it is flush it, otherwise it
2235 				 * won't be in the cache
2236 				 */
2237 				pmap_cache_wbinv_page(pm, pv->pv_va,
2238 				    (maskbits & PVF_REF) != 0,
2239 				    oflags|PVF_WRITE);
2240 			}
2241 #endif
2242 
2243 			/* make the pte read only */
2244 			npte = l2pte_set_readonly(npte);
2245 
2246 			if (maskbits & oflags & PVF_WRITE) {
2247 				/*
2248 				 * Keep alias accounting up to date
2249 				 */
2250 				if (pv->pv_pmap == pmap_kernel()) {
2251 					md->krw_mappings--;
2252 					md->kro_mappings++;
2253 				} else {
2254 					md->urw_mappings--;
2255 					md->uro_mappings++;
2256 				}
2257 #ifdef PMAP_CACHE_VIPT
2258 				if (arm_cache_prefer_mask != 0) {
2259 					if (md->urw_mappings + md->krw_mappings == 0) {
2260 						md->pvh_attrs &= ~PVF_WRITE;
2261 					} else {
2262 						PMAP_VALIDATE_MD_PAGE(md);
2263 					}
2264 				}
2265 				if (want_syncicache)
2266 					need_syncicache = true;
2267 				need_vac_me_harder = true;
2268 #endif
2269 			}
2270 		}
2271 
2272 		if (maskbits & PVF_REF) {
2273 			if ((pv->pv_flags & PVF_NC) == 0
2274 			    && (maskbits & (PVF_WRITE|PVF_MOD)) == 0
2275 			    && l2pte_valid(npte)) {
2276 #ifdef PMAP_CACHE_VIVT
2277 				/*
2278 				 * Check npte here; we may have already
2279 				 * done the wbinv above, and the validity
2280 				 * of the PTE is the same for opte and
2281 				 * npte.
2282 				 */
2283 				pmap_cache_wbinv_page(pm, pv->pv_va, true,
2284 				    oflags);
2285 #endif
2286 			}
2287 
2288 			/*
2289 			 * Make the PTE invalid so that we will take a
2290 			 * page fault the next time the mapping is
2291 			 * referenced.
2292 			 */
2293 			npte &= ~L2_TYPE_MASK;
2294 			npte |= L2_TYPE_INV;
2295 		}
2296 
2297 		if (npte != opte) {
2298 			l2pte_set(ptep, npte, opte);
2299 			PTE_SYNC(ptep);
2300 
2301 			/* Flush the TLB entry if a current pmap. */
2302 			pmap_tlb_flush_SE(pm, pv->pv_va, oflags);
2303 		}
2304 
2305 		pmap_release_pmap_lock(pm);
2306 
2307 		NPDEBUG(PDB_BITS,
2308 		    printf("pmap_clearbit: pm %p va 0x%lx opte 0x%08x npte 0x%08x\n",
2309 		    pm, va, opte, npte));
2310 	}
2311 
2312 #ifdef PMAP_CACHE_VIPT
2313 	/*
2314 	 * If we need to sync the I-cache and we haven't done it yet, do it.
2315 	 */
2316 	if (need_syncicache) {
2317 		pmap_syncicache_page(md, pa);
2318 		PMAPCOUNT(exec_synced_clearbit);
2319 	}
2320 
2321 	/*
2322 	 * If we are changing this to read-only, we need to call vac_me_harder
2323 	 * so we can change all the read-only pages to cacheable.  We pretend
2324 	 * this as a page deletion.
2325 	 */
2326 	if (need_vac_me_harder) {
2327 		if (md->pvh_attrs & PVF_NC)
2328 			pmap_vac_me_harder(md, pa, NULL, 0);
2329 	}
2330 #endif
2331 }
2332 
2333 /*
2334  * pmap_clean_page()
2335  *
2336  * This is a local function used to work out the best strategy to clean
2337  * a single page referenced by its entry in the PV table. It's used by
2338  * pmap_copy_page, pmap_zero page and maybe some others later on.
2339  *
2340  * Its policy is effectively:
2341  *  o If there are no mappings, we don't bother doing anything with the cache.
2342  *  o If there is one mapping, we clean just that page.
2343  *  o If there are multiple mappings, we clean the entire cache.
2344  *
2345  * So that some functions can be further optimised, it returns 0 if it didn't
2346  * clean the entire cache, or 1 if it did.
2347  *
2348  * XXX One bug in this routine is that if the pv_entry has a single page
2349  * mapped at 0x00000000 a whole cache clean will be performed rather than
2350  * just the 1 page. Since this should not occur in everyday use and if it does
2351  * it will just result in not the most efficient clean for the page.
2352  */
2353 #ifdef PMAP_CACHE_VIVT
2354 static int
2355 pmap_clean_page(struct pv_entry *pv, bool is_src)
2356 {
2357 	pmap_t pm_to_clean = NULL;
2358 	struct pv_entry *npv;
2359 	u_int cache_needs_cleaning = 0;
2360 	u_int flags = 0;
2361 	vaddr_t page_to_clean = 0;
2362 
2363 	if (pv == NULL) {
2364 		/* nothing mapped in so nothing to flush */
2365 		return (0);
2366 	}
2367 
2368 	/*
2369 	 * Since we flush the cache each time we change to a different
2370 	 * user vmspace, we only need to flush the page if it is in the
2371 	 * current pmap.
2372 	 */
2373 
2374 	for (npv = pv; npv; npv = SLIST_NEXT(npv, pv_link)) {
2375 		if (pmap_is_current(npv->pv_pmap)) {
2376 			flags |= npv->pv_flags;
2377 			/*
2378 			 * The page is mapped non-cacheable in
2379 			 * this map.  No need to flush the cache.
2380 			 */
2381 			if (npv->pv_flags & PVF_NC) {
2382 #ifdef DIAGNOSTIC
2383 				if (cache_needs_cleaning)
2384 					panic("pmap_clean_page: "
2385 					    "cache inconsistency");
2386 #endif
2387 				break;
2388 			} else if (is_src && (npv->pv_flags & PVF_WRITE) == 0)
2389 				continue;
2390 			if (cache_needs_cleaning) {
2391 				page_to_clean = 0;
2392 				break;
2393 			} else {
2394 				page_to_clean = npv->pv_va;
2395 				pm_to_clean = npv->pv_pmap;
2396 			}
2397 			cache_needs_cleaning = 1;
2398 		}
2399 	}
2400 
2401 	if (page_to_clean) {
2402 		pmap_cache_wbinv_page(pm_to_clean, page_to_clean,
2403 		    !is_src, flags | PVF_REF);
2404 	} else if (cache_needs_cleaning) {
2405 		pmap_t const pm = curproc->p_vmspace->vm_map.pmap;
2406 
2407 		pmap_cache_wbinv_all(pm, flags);
2408 		return (1);
2409 	}
2410 	return (0);
2411 }
2412 #endif
2413 
2414 #ifdef PMAP_CACHE_VIPT
2415 /*
2416  * Sync a page with the I-cache.  Since this is a VIPT, we must pick the
2417  * right cache alias to make sure we flush the right stuff.
2418  */
2419 void
2420 pmap_syncicache_page(struct vm_page_md *md, paddr_t pa)
2421 {
2422 	const vsize_t va_offset = md->pvh_attrs & arm_cache_prefer_mask;
2423 	pt_entry_t * const ptep = &cdst_pte[va_offset >> PGSHIFT];
2424 
2425 	NPDEBUG(PDB_EXEC, printf("pmap_syncicache_page: md=%p (attrs=%#x)\n",
2426 	    md, md->pvh_attrs));
2427 	/*
2428 	 * No need to clean the page if it's non-cached.
2429 	 */
2430 	if (md->pvh_attrs & PVF_NC)
2431 		return;
2432 	KASSERT(arm_cache_prefer_mask == 0 || md->pvh_attrs & PVF_COLORED);
2433 
2434 	pmap_tlb_flush_SE(pmap_kernel(), cdstp + va_offset, PVF_REF | PVF_EXEC);
2435 	/*
2436 	 * Set up a PTE with the right coloring to flush existing cache lines.
2437 	 */
2438 	const pt_entry_t npte = L2_S_PROTO |
2439 	    pa
2440 	    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ|VM_PROT_WRITE)
2441 	    | pte_l2_s_cache_mode;
2442 	l2pte_set(ptep, npte, 0);
2443 	PTE_SYNC(ptep);
2444 
2445 	/*
2446 	 * Flush it.
2447 	 */
2448 	cpu_icache_sync_range(cdstp + va_offset, PAGE_SIZE);
2449 	/*
2450 	 * Unmap the page.
2451 	 */
2452 	l2pte_reset(ptep);
2453 	PTE_SYNC(ptep);
2454 	pmap_tlb_flush_SE(pmap_kernel(), cdstp + va_offset, PVF_REF | PVF_EXEC);
2455 
2456 	md->pvh_attrs |= PVF_EXEC;
2457 	PMAPCOUNT(exec_synced);
2458 }
2459 
2460 void
2461 pmap_flush_page(struct vm_page_md *md, paddr_t pa, enum pmap_flush_op flush)
2462 {
2463 	vsize_t va_offset, end_va;
2464 	bool wbinv_p;
2465 
2466 	if (arm_cache_prefer_mask == 0)
2467 		return;
2468 
2469 	switch (flush) {
2470 	case PMAP_FLUSH_PRIMARY:
2471 		if (md->pvh_attrs & PVF_MULTCLR) {
2472 			va_offset = 0;
2473 			end_va = arm_cache_prefer_mask;
2474 			md->pvh_attrs &= ~PVF_MULTCLR;
2475 			PMAPCOUNT(vac_flush_lots);
2476 		} else {
2477 			va_offset = md->pvh_attrs & arm_cache_prefer_mask;
2478 			end_va = va_offset;
2479 			PMAPCOUNT(vac_flush_one);
2480 		}
2481 		/*
2482 		 * Mark that the page is no longer dirty.
2483 		 */
2484 		md->pvh_attrs &= ~PVF_DIRTY;
2485 		wbinv_p = true;
2486 		break;
2487 	case PMAP_FLUSH_SECONDARY:
2488 		va_offset = 0;
2489 		end_va = arm_cache_prefer_mask;
2490 		wbinv_p = true;
2491 		md->pvh_attrs &= ~PVF_MULTCLR;
2492 		PMAPCOUNT(vac_flush_lots);
2493 		break;
2494 	case PMAP_CLEAN_PRIMARY:
2495 		va_offset = md->pvh_attrs & arm_cache_prefer_mask;
2496 		end_va = va_offset;
2497 		wbinv_p = false;
2498 		/*
2499 		 * Mark that the page is no longer dirty.
2500 		 */
2501 		if ((md->pvh_attrs & PVF_DMOD) == 0)
2502 			md->pvh_attrs &= ~PVF_DIRTY;
2503 		PMAPCOUNT(vac_clean_one);
2504 		break;
2505 	default:
2506 		return;
2507 	}
2508 
2509 	KASSERT(!(md->pvh_attrs & PVF_NC));
2510 
2511 	NPDEBUG(PDB_VAC, printf("pmap_flush_page: md=%p (attrs=%#x)\n",
2512 	    md, md->pvh_attrs));
2513 
2514 	const size_t scache_line_size = arm_scache.dcache_line_size;
2515 
2516 	for (; va_offset <= end_va; va_offset += PAGE_SIZE) {
2517 		const size_t pte_offset = va_offset >> PGSHIFT;
2518 		pt_entry_t * const ptep = &cdst_pte[pte_offset];
2519 		const pt_entry_t opte = *ptep;
2520 
2521 		if (flush == PMAP_FLUSH_SECONDARY
2522 		    && va_offset == (md->pvh_attrs & arm_cache_prefer_mask))
2523 			continue;
2524 
2525 		pmap_tlb_flush_SE(pmap_kernel(), cdstp + va_offset,
2526 		    PVF_REF | PVF_EXEC);
2527 		/*
2528 		 * Set up a PTE with the right coloring to flush
2529 		 * existing cache entries.
2530 		 */
2531 		const pt_entry_t npte = L2_S_PROTO
2532 		    | pa
2533 		    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ|VM_PROT_WRITE)
2534 		    | pte_l2_s_cache_mode;
2535 		l2pte_set(ptep, npte, opte);
2536 		PTE_SYNC(ptep);
2537 
2538 		/*
2539 		 * Flush it.  Make sure to flush secondary cache too since
2540 		 * bus_dma will ignore uncached pages.
2541 		 */
2542                 vaddr_t va = cdstp + va_offset;
2543 		if (scache_line_size != 0) {
2544 			cpu_dcache_wb_range(va, PAGE_SIZE);
2545 			if (wbinv_p) {
2546 				cpu_sdcache_wbinv_range(va, pa, PAGE_SIZE);
2547 				cpu_dcache_inv_range(va, PAGE_SIZE);
2548 			} else {
2549 				cpu_sdcache_wb_range(va, pa, PAGE_SIZE);
2550 			}
2551 		} else {
2552 			if (wbinv_p) {
2553 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
2554 			} else {
2555 				cpu_dcache_wb_range(va, PAGE_SIZE);
2556 			}
2557 		}
2558 
2559 		/*
2560 		 * Restore the page table entry since we might have interrupted
2561 		 * pmap_zero_page or pmap_copy_page which was already using
2562 		 * this pte.
2563 		 */
2564 		l2pte_set(ptep, opte, npte);
2565 		PTE_SYNC(ptep);
2566 		pmap_tlb_flush_SE(pmap_kernel(), cdstp + va_offset,
2567 		    PVF_REF | PVF_EXEC);
2568 	}
2569 }
2570 #endif /* PMAP_CACHE_VIPT */
2571 
2572 /*
2573  * Routine:	pmap_page_remove
2574  * Function:
2575  *		Removes this physical page from
2576  *		all physical maps in which it resides.
2577  *		Reflects back modify bits to the pager.
2578  */
2579 static void
2580 pmap_page_remove(struct vm_page_md *md, paddr_t pa)
2581 {
2582 	struct l2_bucket *l2b;
2583 	struct pv_entry *pv, *npv, **pvp;
2584 	pmap_t pm;
2585 	pt_entry_t *ptep;
2586 	bool flush;
2587 	u_int flags;
2588 
2589 	NPDEBUG(PDB_FOLLOW,
2590 	    printf("pmap_page_remove: md %p (0x%08lx)\n", md,
2591 	    pa));
2592 
2593 	pv = SLIST_FIRST(&md->pvh_list);
2594 	if (pv == NULL) {
2595 #ifdef PMAP_CACHE_VIPT
2596 		/*
2597 		 * We *know* the page contents are about to be replaced.
2598 		 * Discard the exec contents
2599 		 */
2600 		if (PV_IS_EXEC_P(md->pvh_attrs))
2601 			PMAPCOUNT(exec_discarded_page_protect);
2602 		md->pvh_attrs &= ~PVF_EXEC;
2603 		PMAP_VALIDATE_MD_PAGE(md);
2604 #endif
2605 		return;
2606 	}
2607 #ifdef PMAP_CACHE_VIPT
2608 	KASSERT(arm_cache_prefer_mask == 0 || pmap_is_page_colored_p(md));
2609 #endif
2610 
2611 	/*
2612 	 * Clear alias counts
2613 	 */
2614 #ifdef PMAP_CACHE_VIVT
2615 	md->k_mappings = 0;
2616 #endif
2617 	md->urw_mappings = md->uro_mappings = 0;
2618 
2619 	flush = false;
2620 	flags = 0;
2621 
2622 #ifdef PMAP_CACHE_VIVT
2623 	pmap_clean_page(pv, false);
2624 #endif
2625 
2626 	pvp = &SLIST_FIRST(&md->pvh_list);
2627 	while (pv) {
2628 		pm = pv->pv_pmap;
2629 		npv = SLIST_NEXT(pv, pv_link);
2630 		if (flush == false && pmap_is_current(pm))
2631 			flush = true;
2632 
2633 		if (pm == pmap_kernel()) {
2634 #ifdef PMAP_CACHE_VIPT
2635 			/*
2636 			 * If this was unmanaged mapping, it must be preserved.
2637 			 * Move it back on the list and advance the end-of-list
2638 			 * pointer.
2639 			 */
2640 			if (pv->pv_flags & PVF_KENTRY) {
2641 				*pvp = pv;
2642 				pvp = &SLIST_NEXT(pv, pv_link);
2643 				pv = npv;
2644 				continue;
2645 			}
2646 			if (pv->pv_flags & PVF_WRITE)
2647 				md->krw_mappings--;
2648 			else
2649 				md->kro_mappings--;
2650 #endif
2651 			PMAPCOUNT(kernel_unmappings);
2652 		}
2653 		PMAPCOUNT(unmappings);
2654 
2655 		pmap_acquire_pmap_lock(pm);
2656 
2657 		l2b = pmap_get_l2_bucket(pm, pv->pv_va);
2658 		KDASSERT(l2b != NULL);
2659 
2660 		ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
2661 
2662 		/*
2663 		 * Update statistics
2664 		 */
2665 		--pm->pm_stats.resident_count;
2666 
2667 		/* Wired bit */
2668 		if (pv->pv_flags & PVF_WIRED)
2669 			--pm->pm_stats.wired_count;
2670 
2671 		flags |= pv->pv_flags;
2672 
2673 		/*
2674 		 * Invalidate the PTEs.
2675 		 */
2676 		l2pte_reset(ptep);
2677 		PTE_SYNC_CURRENT(pm, ptep);
2678 		pmap_free_l2_bucket(pm, l2b, 1);
2679 
2680 		pool_put(&pmap_pv_pool, pv);
2681 		pv = npv;
2682 		/*
2683 		 * if we reach the end of the list and there are still
2684 		 * mappings, they might be able to be cached now.
2685 		 */
2686 		if (pv == NULL) {
2687 			*pvp = NULL;
2688 			if (!SLIST_EMPTY(&md->pvh_list))
2689 				pmap_vac_me_harder(md, pa, pm, 0);
2690 		}
2691 		pmap_release_pmap_lock(pm);
2692 	}
2693 #ifdef PMAP_CACHE_VIPT
2694 	/*
2695 	 * Its EXEC cache is now gone.
2696 	 */
2697 	if (PV_IS_EXEC_P(md->pvh_attrs))
2698 		PMAPCOUNT(exec_discarded_page_protect);
2699 	md->pvh_attrs &= ~PVF_EXEC;
2700 	KASSERT(md->urw_mappings == 0);
2701 	KASSERT(md->uro_mappings == 0);
2702 	if (arm_cache_prefer_mask != 0) {
2703 		if (md->krw_mappings == 0)
2704 			md->pvh_attrs &= ~PVF_WRITE;
2705 		PMAP_VALIDATE_MD_PAGE(md);
2706 	}
2707 #endif
2708 
2709 	if (flush) {
2710 		/*
2711 		 * Note: We can't use pmap_tlb_flush{I,D}() here since that
2712 		 * would need a subsequent call to pmap_update() to ensure
2713 		 * curpm->pm_cstate.cs_all is reset. Our callers are not
2714 		 * required to do that (see pmap(9)), so we can't modify
2715 		 * the current pmap's state.
2716 		 */
2717 		if (PV_BEEN_EXECD(flags))
2718 			cpu_tlb_flushID();
2719 		else
2720 			cpu_tlb_flushD();
2721 	}
2722 	cpu_cpwait();
2723 }
2724 
2725 /*
2726  * pmap_t pmap_create(void)
2727  *
2728  *      Create a new pmap structure from scratch.
2729  */
2730 pmap_t
2731 pmap_create(void)
2732 {
2733 	pmap_t pm;
2734 
2735 	pm = pool_cache_get(&pmap_cache, PR_WAITOK);
2736 
2737 	mutex_init(&pm->pm_obj_lock, MUTEX_DEFAULT, IPL_NONE);
2738 	uvm_obj_init(&pm->pm_obj, NULL, false, 1);
2739 	uvm_obj_setlock(&pm->pm_obj, &pm->pm_obj_lock);
2740 
2741 	pm->pm_stats.wired_count = 0;
2742 	pm->pm_stats.resident_count = 1;
2743 	pm->pm_cstate.cs_all = 0;
2744 	pmap_alloc_l1(pm);
2745 
2746 	/*
2747 	 * Note: The pool cache ensures that the pm_l2[] array is already
2748 	 * initialised to zero.
2749 	 */
2750 
2751 	pmap_pinit(pm);
2752 
2753 	LIST_INSERT_HEAD(&pmap_pmaps, pm, pm_list);
2754 
2755 	return (pm);
2756 }
2757 
2758 u_int
2759 arm32_mmap_flags(paddr_t pa)
2760 {
2761 	/*
2762 	 * the upper 8 bits in pmap_enter()'s flags are reserved for MD stuff
2763 	 * and we're using the upper bits in page numbers to pass flags around
2764 	 * so we might as well use the same bits
2765 	 */
2766 	return (u_int)pa & PMAP_MD_MASK;
2767 }
2768 /*
2769  * int pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot,
2770  *      u_int flags)
2771  *
2772  *      Insert the given physical page (p) at
2773  *      the specified virtual address (v) in the
2774  *      target physical map with the protection requested.
2775  *
2776  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2777  *      or lose information.  That is, this routine must actually
2778  *      insert this page into the given map NOW.
2779  */
2780 int
2781 pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
2782 {
2783 	struct l2_bucket *l2b;
2784 	struct vm_page *pg, *opg;
2785 	struct pv_entry *pv;
2786 	u_int nflags;
2787 	u_int oflags;
2788 #ifdef ARM_HAS_VBAR
2789 	const bool vector_page_p = false;
2790 #else
2791 	const bool vector_page_p = (va == vector_page);
2792 #endif
2793 
2794 	NPDEBUG(PDB_ENTER, printf("pmap_enter: pm %p va 0x%lx pa 0x%lx prot %x flag %x\n", pm, va, pa, prot, flags));
2795 
2796 	KDASSERT((flags & PMAP_WIRED) == 0 || (flags & VM_PROT_ALL) != 0);
2797 	KDASSERT(((va | pa) & PGOFSET) == 0);
2798 
2799 	/*
2800 	 * Get a pointer to the page.  Later on in this function, we
2801 	 * test for a managed page by checking pg != NULL.
2802 	 */
2803 	pg = pmap_initialized ? PHYS_TO_VM_PAGE(pa) : NULL;
2804 
2805 	nflags = 0;
2806 	if (prot & VM_PROT_WRITE)
2807 		nflags |= PVF_WRITE;
2808 	if (prot & VM_PROT_EXECUTE)
2809 		nflags |= PVF_EXEC;
2810 	if (flags & PMAP_WIRED)
2811 		nflags |= PVF_WIRED;
2812 
2813 	pmap_acquire_pmap_lock(pm);
2814 
2815 	/*
2816 	 * Fetch the L2 bucket which maps this page, allocating one if
2817 	 * necessary for user pmaps.
2818 	 */
2819 	if (pm == pmap_kernel())
2820 		l2b = pmap_get_l2_bucket(pm, va);
2821 	else
2822 		l2b = pmap_alloc_l2_bucket(pm, va);
2823 	if (l2b == NULL) {
2824 		if (flags & PMAP_CANFAIL) {
2825 			pmap_release_pmap_lock(pm);
2826 			return (ENOMEM);
2827 		}
2828 		panic("pmap_enter: failed to allocate L2 bucket");
2829 	}
2830 	pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(va)];
2831 	const pt_entry_t opte = *ptep;
2832 	pt_entry_t npte = pa;
2833 	oflags = 0;
2834 
2835 	if (opte) {
2836 		/*
2837 		 * There is already a mapping at this address.
2838 		 * If the physical address is different, lookup the
2839 		 * vm_page.
2840 		 */
2841 		if (l2pte_pa(opte) != pa)
2842 			opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
2843 		else
2844 			opg = pg;
2845 	} else
2846 		opg = NULL;
2847 
2848 	if (pg) {
2849 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
2850 
2851 		/*
2852 		 * This is to be a managed mapping.
2853 		 */
2854 		if ((flags & VM_PROT_ALL) || (md->pvh_attrs & PVF_REF)) {
2855 			/*
2856 			 * - The access type indicates that we don't need
2857 			 *   to do referenced emulation.
2858 			 * OR
2859 			 * - The physical page has already been referenced
2860 			 *   so no need to re-do referenced emulation here.
2861 			 */
2862 			npte |= l2pte_set_readonly(L2_S_PROTO);
2863 
2864 			nflags |= PVF_REF;
2865 
2866 			if ((prot & VM_PROT_WRITE) != 0 &&
2867 			    ((flags & VM_PROT_WRITE) != 0 ||
2868 			     (md->pvh_attrs & PVF_MOD) != 0)) {
2869 				/*
2870 				 * This is a writable mapping, and the
2871 				 * page's mod state indicates it has
2872 				 * already been modified. Make it
2873 				 * writable from the outset.
2874 				 */
2875 				npte = l2pte_set_writable(npte);
2876 				nflags |= PVF_MOD;
2877 			}
2878 		} else {
2879 			/*
2880 			 * Need to do page referenced emulation.
2881 			 */
2882 			npte |= L2_TYPE_INV;
2883 		}
2884 
2885 		if (flags & ARM32_MMAP_WRITECOMBINE) {
2886 			npte |= pte_l2_s_wc_mode;
2887 		} else
2888 			npte |= pte_l2_s_cache_mode;
2889 
2890 		if (pg == opg) {
2891 			/*
2892 			 * We're changing the attrs of an existing mapping.
2893 			 */
2894 #ifdef MULTIPROCESSOR
2895 			KASSERT(uvm_page_locked_p(pg));
2896 #endif
2897 			oflags = pmap_modify_pv(md, pa, pm, va,
2898 			    PVF_WRITE | PVF_EXEC | PVF_WIRED |
2899 			    PVF_MOD | PVF_REF, nflags);
2900 
2901 #ifdef PMAP_CACHE_VIVT
2902 			/*
2903 			 * We may need to flush the cache if we're
2904 			 * doing rw-ro...
2905 			 */
2906 			if (pm->pm_cstate.cs_cache_d &&
2907 			    (oflags & PVF_NC) == 0 &&
2908 			    l2pte_writable_p(opte) &&
2909 			    (prot & VM_PROT_WRITE) == 0)
2910 				cpu_dcache_wb_range(va, PAGE_SIZE);
2911 #endif
2912 		} else {
2913 			/*
2914 			 * New mapping, or changing the backing page
2915 			 * of an existing mapping.
2916 			 */
2917 			if (opg) {
2918 				struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
2919 				paddr_t opa = VM_PAGE_TO_PHYS(opg);
2920 
2921 				/*
2922 				 * Replacing an existing mapping with a new one.
2923 				 * It is part of our managed memory so we
2924 				 * must remove it from the PV list
2925 				 */
2926 #ifdef MULTIPROCESSOR
2927 				KASSERT(uvm_page_locked_p(opg));
2928 #endif
2929 				pv = pmap_remove_pv(omd, opa, pm, va);
2930 				pmap_vac_me_harder(omd, opa, pm, 0);
2931 				oflags = pv->pv_flags;
2932 
2933 #ifdef PMAP_CACHE_VIVT
2934 				/*
2935 				 * If the old mapping was valid (ref/mod
2936 				 * emulation creates 'invalid' mappings
2937 				 * initially) then make sure to frob
2938 				 * the cache.
2939 				 */
2940 				if (!(oflags & PVF_NC) && l2pte_valid(opte)) {
2941 					pmap_cache_wbinv_page(pm, va, true,
2942 					    oflags);
2943 				}
2944 #endif
2945 			} else
2946 			if ((pv = pool_get(&pmap_pv_pool, PR_NOWAIT)) == NULL){
2947 				if ((flags & PMAP_CANFAIL) == 0)
2948 					panic("pmap_enter: no pv entries");
2949 
2950 				if (pm != pmap_kernel())
2951 					pmap_free_l2_bucket(pm, l2b, 0);
2952 				pmap_release_pmap_lock(pm);
2953 				NPDEBUG(PDB_ENTER,
2954 				    printf("pmap_enter: ENOMEM\n"));
2955 				return (ENOMEM);
2956 			}
2957 
2958 #ifdef MULTIPROCESSOR
2959 			KASSERT(uvm_page_locked_p(pg));
2960 #endif
2961 			pmap_enter_pv(md, pa, pv, pm, va, nflags);
2962 		}
2963 	} else {
2964 		/*
2965 		 * We're mapping an unmanaged page.
2966 		 * These are always readable, and possibly writable, from
2967 		 * the get go as we don't need to track ref/mod status.
2968 		 */
2969 		npte |= l2pte_set_readonly(L2_S_PROTO);
2970 		if (prot & VM_PROT_WRITE)
2971 			npte = l2pte_set_writable(npte);
2972 
2973 		/*
2974 		 * Make sure the vector table is mapped cacheable
2975 		 */
2976 		if ((vector_page_p && pm != pmap_kernel())
2977 		    || (flags & ARM32_MMAP_CACHEABLE)) {
2978 			npte |= pte_l2_s_cache_mode;
2979 		} else if (flags & ARM32_MMAP_WRITECOMBINE) {
2980 			npte |= pte_l2_s_wc_mode;
2981 		}
2982 		if (opg) {
2983 			/*
2984 			 * Looks like there's an existing 'managed' mapping
2985 			 * at this address.
2986 			 */
2987 			struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
2988 			paddr_t opa = VM_PAGE_TO_PHYS(opg);
2989 
2990 #ifdef MULTIPROCESSOR
2991 			KASSERT(uvm_page_locked_p(opg));
2992 #endif
2993 			pv = pmap_remove_pv(omd, opa, pm, va);
2994 			pmap_vac_me_harder(omd, opa, pm, 0);
2995 			oflags = pv->pv_flags;
2996 
2997 #ifdef PMAP_CACHE_VIVT
2998 			if (!(oflags & PVF_NC) == 0 && l2pte_valid(opte)) {
2999 				pmap_cache_wbinv_page(pm, va, true, oflags);
3000 			}
3001 #endif
3002 			pool_put(&pmap_pv_pool, pv);
3003 		}
3004 	}
3005 
3006 	/*
3007 	 * Make sure userland mappings get the right permissions
3008 	 */
3009 	if (!vector_page_p && pm != pmap_kernel()) {
3010 		npte |= L2_S_PROT_U;
3011 	}
3012 
3013 	/*
3014 	 * Keep the stats up to date
3015 	 */
3016 	if (opte == 0) {
3017 		l2b->l2b_occupancy++;
3018 		pm->pm_stats.resident_count++;
3019 	}
3020 
3021 	NPDEBUG(PDB_ENTER,
3022 	    printf("pmap_enter: opte 0x%08x npte 0x%08x\n", opte, npte));
3023 
3024 	/*
3025 	 * If this is just a wiring change, the two PTEs will be
3026 	 * identical, so there's no need to update the page table.
3027 	 */
3028 	if (npte != opte) {
3029 		bool is_cached = pmap_is_cached(pm);
3030 
3031 		l2pte_set(ptep, npte, opte);
3032 		PTE_SYNC(ptep);
3033 		if (is_cached) {
3034 			/*
3035 			 * We only need to frob the cache/tlb if this pmap
3036 			 * is current
3037 			 */
3038 			if (!vector_page_p && l2pte_valid(npte)) {
3039 				/*
3040 				 * This mapping is likely to be accessed as
3041 				 * soon as we return to userland. Fix up the
3042 				 * L1 entry to avoid taking another
3043 				 * page/domain fault.
3044 				 */
3045 				pd_entry_t *pl1pd, l1pd;
3046 
3047 				pl1pd = pmap_l1_kva(pm) + L1_IDX(va);
3048 				l1pd = l2b->l2b_phys | L1_C_DOM(pmap_domain(pm)) |
3049 				    L1_C_PROTO;
3050 				if (*pl1pd != l1pd) {
3051 					*pl1pd = l1pd;
3052 					PTE_SYNC(pl1pd);
3053 				}
3054 			}
3055 		}
3056 
3057 		pmap_tlb_flush_SE(pm, va, oflags);
3058 
3059 		NPDEBUG(PDB_ENTER,
3060 		    printf("pmap_enter: is_cached %d cs 0x%08x\n",
3061 		    is_cached, pm->pm_cstate.cs_all));
3062 
3063 		if (pg != NULL) {
3064 			struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3065 
3066 #ifdef MULTIPROCESSOR
3067 			KASSERT(uvm_page_locked_p(pg));
3068 #endif
3069 			pmap_vac_me_harder(md, pa, pm, va);
3070 		}
3071 	}
3072 #if defined(PMAP_CACHE_VIPT) && defined(DIAGNOSTIC)
3073 	if (pg) {
3074 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3075 
3076 #ifdef MULTIPROCESSOR
3077 		KASSERT(uvm_page_locked_p(pg));
3078 #endif
3079 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
3080 		PMAP_VALIDATE_MD_PAGE(md);
3081 	}
3082 #endif
3083 
3084 	pmap_release_pmap_lock(pm);
3085 
3086 	return (0);
3087 }
3088 
3089 /*
3090  * pmap_remove()
3091  *
3092  * pmap_remove is responsible for nuking a number of mappings for a range
3093  * of virtual address space in the current pmap. To do this efficiently
3094  * is interesting, because in a number of cases a wide virtual address
3095  * range may be supplied that contains few actual mappings. So, the
3096  * optimisations are:
3097  *  1. Skip over hunks of address space for which no L1 or L2 entry exists.
3098  *  2. Build up a list of pages we've hit, up to a maximum, so we can
3099  *     maybe do just a partial cache clean. This path of execution is
3100  *     complicated by the fact that the cache must be flushed _before_
3101  *     the PTE is nuked, being a VAC :-)
3102  *  3. If we're called after UVM calls pmap_remove_all(), we can defer
3103  *     all invalidations until pmap_update(), since pmap_remove_all() has
3104  *     already flushed the cache.
3105  *  4. Maybe later fast-case a single page, but I don't think this is
3106  *     going to make _that_ much difference overall.
3107  */
3108 
3109 #define	PMAP_REMOVE_CLEAN_LIST_SIZE	3
3110 
3111 void
3112 pmap_remove(pmap_t pm, vaddr_t sva, vaddr_t eva)
3113 {
3114 	vaddr_t next_bucket;
3115 	u_int cleanlist_idx, total, cnt;
3116 	struct {
3117 		vaddr_t va;
3118 		pt_entry_t *ptep;
3119 	} cleanlist[PMAP_REMOVE_CLEAN_LIST_SIZE];
3120 	u_int mappings;
3121 
3122 	NPDEBUG(PDB_REMOVE, printf("pmap_do_remove: pmap=%p sva=%08lx "
3123 	    "eva=%08lx\n", pm, sva, eva));
3124 
3125 	/*
3126 	 * we lock in the pmap => pv_head direction
3127 	 */
3128 	pmap_acquire_pmap_lock(pm);
3129 
3130 	if (pm->pm_remove_all || !pmap_is_cached(pm)) {
3131 		cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
3132 		if (pm->pm_cstate.cs_tlb == 0)
3133 			pm->pm_remove_all = true;
3134 	} else
3135 		cleanlist_idx = 0;
3136 
3137 	total = 0;
3138 
3139 	while (sva < eva) {
3140 		/*
3141 		 * Do one L2 bucket's worth at a time.
3142 		 */
3143 		next_bucket = L2_NEXT_BUCKET(sva);
3144 		if (next_bucket > eva)
3145 			next_bucket = eva;
3146 
3147 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pm, sva);
3148 		if (l2b == NULL) {
3149 			sva = next_bucket;
3150 			continue;
3151 		}
3152 
3153 		pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(sva)];
3154 
3155 		for (mappings = 0;
3156 		     sva < next_bucket;
3157 		     sva += PAGE_SIZE, ptep += PAGE_SIZE / L2_S_SIZE) {
3158 			pt_entry_t opte = *ptep;
3159 
3160 			if (opte == 0) {
3161 				/* Nothing here, move along */
3162 				continue;
3163 			}
3164 
3165 			u_int flags = PVF_REF;
3166 			paddr_t pa = l2pte_pa(opte);
3167 			struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
3168 
3169 			/*
3170 			 * Update flags. In a number of circumstances,
3171 			 * we could cluster a lot of these and do a
3172 			 * number of sequential pages in one go.
3173 			 */
3174 			if (pg != NULL) {
3175 				struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3176 				struct pv_entry *pv;
3177 
3178 #ifdef MULTIPROCESSOR
3179 				KASSERT(uvm_page_locked_p(pg));
3180 #endif
3181 				pv = pmap_remove_pv(md, pa, pm, sva);
3182 				pmap_vac_me_harder(md, pa, pm, 0);
3183 				if (pv != NULL) {
3184 					if (pm->pm_remove_all == false) {
3185 						flags = pv->pv_flags;
3186 					}
3187 					pool_put(&pmap_pv_pool, pv);
3188 				}
3189 			}
3190 			mappings++;
3191 
3192 			if (!l2pte_valid(opte)) {
3193 				/*
3194 				 * Ref/Mod emulation is still active for this
3195 				 * mapping, therefore it is has not yet been
3196 				 * accessed. No need to frob the cache/tlb.
3197 				 */
3198 				l2pte_reset(ptep);
3199 				PTE_SYNC_CURRENT(pm, ptep);
3200 				continue;
3201 			}
3202 
3203 			if (cleanlist_idx < PMAP_REMOVE_CLEAN_LIST_SIZE) {
3204 				/* Add to the clean list. */
3205 				cleanlist[cleanlist_idx].ptep = ptep;
3206 				cleanlist[cleanlist_idx].va =
3207 				    sva | (flags & PVF_EXEC);
3208 				cleanlist_idx++;
3209 			} else
3210 			if (cleanlist_idx == PMAP_REMOVE_CLEAN_LIST_SIZE) {
3211 				/* Nuke everything if needed. */
3212 #ifdef PMAP_CACHE_VIVT
3213 				pmap_cache_wbinv_all(pm, PVF_EXEC);
3214 #endif
3215 				pmap_tlb_flushID(pm);
3216 
3217 				/*
3218 				 * Roll back the previous PTE list,
3219 				 * and zero out the current PTE.
3220 				 */
3221 				for (cnt = 0;
3222 				     cnt < PMAP_REMOVE_CLEAN_LIST_SIZE; cnt++) {
3223 					l2pte_reset(cleanlist[cnt].ptep);
3224 					PTE_SYNC(cleanlist[cnt].ptep);
3225 				}
3226 				l2pte_reset(ptep);
3227 				PTE_SYNC(ptep);
3228 				cleanlist_idx++;
3229 				pm->pm_remove_all = true;
3230 			} else {
3231 				l2pte_reset(ptep);
3232 				PTE_SYNC(ptep);
3233 				if (pm->pm_remove_all == false) {
3234 					pmap_tlb_flush_SE(pm, sva, flags);
3235 				}
3236 			}
3237 		}
3238 
3239 		/*
3240 		 * Deal with any left overs
3241 		 */
3242 		if (cleanlist_idx <= PMAP_REMOVE_CLEAN_LIST_SIZE) {
3243 			total += cleanlist_idx;
3244 			for (cnt = 0; cnt < cleanlist_idx; cnt++) {
3245 				vaddr_t va = cleanlist[cnt].va;
3246 				if (pm->pm_cstate.cs_all != 0) {
3247 					vaddr_t clva = va & ~PAGE_MASK;
3248 					u_int flags = va & PVF_EXEC;
3249 #ifdef PMAP_CACHE_VIVT
3250 					pmap_cache_wbinv_page(pm, clva, true,
3251 					    PVF_REF | PVF_WRITE | flags);
3252 #endif
3253 					pmap_tlb_flush_SE(pm, clva,
3254 					    PVF_REF | flags);
3255 				}
3256 				l2pte_reset(cleanlist[cnt].ptep);
3257 				PTE_SYNC_CURRENT(pm, cleanlist[cnt].ptep);
3258 			}
3259 
3260 			/*
3261 			 * If it looks like we're removing a whole bunch
3262 			 * of mappings, it's faster to just write-back
3263 			 * the whole cache now and defer TLB flushes until
3264 			 * pmap_update() is called.
3265 			 */
3266 			if (total <= PMAP_REMOVE_CLEAN_LIST_SIZE)
3267 				cleanlist_idx = 0;
3268 			else {
3269 				cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
3270 #ifdef PMAP_CACHE_VIVT
3271 				pmap_cache_wbinv_all(pm, PVF_EXEC);
3272 #endif
3273 				pm->pm_remove_all = true;
3274 			}
3275 		}
3276 
3277 		pmap_free_l2_bucket(pm, l2b, mappings);
3278 		pm->pm_stats.resident_count -= mappings;
3279 	}
3280 
3281 	pmap_release_pmap_lock(pm);
3282 }
3283 
3284 #ifdef PMAP_CACHE_VIPT
3285 static struct pv_entry *
3286 pmap_kremove_pg(struct vm_page *pg, vaddr_t va)
3287 {
3288 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3289 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
3290 	struct pv_entry *pv;
3291 
3292 	KASSERT(arm_cache_prefer_mask == 0 || md->pvh_attrs & (PVF_COLORED|PVF_NC));
3293 	KASSERT((md->pvh_attrs & PVF_KMPAGE) == 0);
3294 
3295 	pv = pmap_remove_pv(md, pa, pmap_kernel(), va);
3296 	KASSERT(pv);
3297 	KASSERT(pv->pv_flags & PVF_KENTRY);
3298 
3299 	/*
3300 	 * If we are removing a writeable mapping to a cached exec page,
3301 	 * if it's the last mapping then clear it execness other sync
3302 	 * the page to the icache.
3303 	 */
3304 	if ((md->pvh_attrs & (PVF_NC|PVF_EXEC)) == PVF_EXEC
3305 	    && (pv->pv_flags & PVF_WRITE) != 0) {
3306 		if (SLIST_EMPTY(&md->pvh_list)) {
3307 			md->pvh_attrs &= ~PVF_EXEC;
3308 			PMAPCOUNT(exec_discarded_kremove);
3309 		} else {
3310 			pmap_syncicache_page(md, pa);
3311 			PMAPCOUNT(exec_synced_kremove);
3312 		}
3313 	}
3314 	pmap_vac_me_harder(md, pa, pmap_kernel(), 0);
3315 
3316 	return pv;
3317 }
3318 #endif /* PMAP_CACHE_VIPT */
3319 
3320 /*
3321  * pmap_kenter_pa: enter an unmanaged, wired kernel mapping
3322  *
3323  * We assume there is already sufficient KVM space available
3324  * to do this, as we can't allocate L2 descriptor tables/metadata
3325  * from here.
3326  */
3327 void
3328 pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
3329 {
3330 #ifdef PMAP_CACHE_VIVT
3331 	struct vm_page *pg = (flags & PMAP_KMPAGE) ? PHYS_TO_VM_PAGE(pa) : NULL;
3332 #endif
3333 #ifdef PMAP_CACHE_VIPT
3334 	struct vm_page *pg = PHYS_TO_VM_PAGE(pa);
3335 	struct vm_page *opg;
3336 	struct pv_entry *pv = NULL;
3337 #endif
3338 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3339 
3340 	NPDEBUG(PDB_KENTER,
3341 	    printf("pmap_kenter_pa: va 0x%08lx, pa 0x%08lx, prot 0x%x\n",
3342 	    va, pa, prot));
3343 
3344 	struct l2_bucket * const l2b = pmap_get_l2_bucket(pmap_kernel(), va);
3345 	KDASSERT(l2b != NULL);
3346 
3347 	pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
3348 	const pt_entry_t opte = *ptep;
3349 
3350 	if (opte == 0) {
3351 		PMAPCOUNT(kenter_mappings);
3352 		l2b->l2b_occupancy++;
3353 	} else {
3354 		PMAPCOUNT(kenter_remappings);
3355 #ifdef PMAP_CACHE_VIPT
3356 		opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
3357 #ifdef DIAGNOSTIC
3358 		struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
3359 #endif
3360 		if (opg) {
3361 			KASSERT(opg != pg);
3362 			KASSERT((omd->pvh_attrs & PVF_KMPAGE) == 0);
3363 			KASSERT((flags & PMAP_KMPAGE) == 0);
3364 			pv = pmap_kremove_pg(opg, va);
3365 		}
3366 #endif
3367 		if (l2pte_valid(opte)) {
3368 #ifdef PMAP_CACHE_VIVT
3369 			cpu_dcache_wbinv_range(va, PAGE_SIZE);
3370 #endif
3371 			cpu_tlb_flushD_SE(va);
3372 			cpu_cpwait();
3373 		}
3374 	}
3375 
3376 	const pt_entry_t npte = L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot)
3377 	    | ((flags & PMAP_NOCACHE) ? 0 : pte_l2_s_cache_mode);
3378 	l2pte_set(ptep, npte, opte);
3379 	PTE_SYNC(ptep);
3380 
3381 	if (pg) {
3382 #ifdef MULTIPROCESSOR
3383 		KASSERT(uvm_page_locked_p(pg));
3384 #endif
3385 		if (flags & PMAP_KMPAGE) {
3386 			KASSERT(md->urw_mappings == 0);
3387 			KASSERT(md->uro_mappings == 0);
3388 			KASSERT(md->krw_mappings == 0);
3389 			KASSERT(md->kro_mappings == 0);
3390 #ifdef PMAP_CACHE_VIPT
3391 			KASSERT(pv == NULL);
3392 			KASSERT(arm_cache_prefer_mask == 0 || (va & PVF_COLORED) == 0);
3393 			KASSERT((md->pvh_attrs & PVF_NC) == 0);
3394 			/* if there is a color conflict, evict from cache. */
3395 			if (pmap_is_page_colored_p(md)
3396 			    && ((va ^ md->pvh_attrs) & arm_cache_prefer_mask)) {
3397 				PMAPCOUNT(vac_color_change);
3398 				pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
3399 			} else if (md->pvh_attrs & PVF_MULTCLR) {
3400 				/*
3401 				 * If this page has multiple colors, expunge
3402 				 * them.
3403 				 */
3404 				PMAPCOUNT(vac_flush_lots2);
3405 				pmap_flush_page(md, pa, PMAP_FLUSH_SECONDARY);
3406 			}
3407 			md->pvh_attrs &= PAGE_SIZE - 1;
3408 			md->pvh_attrs |= PVF_KMPAGE
3409 			    | PVF_COLORED | PVF_DIRTY
3410 			    | (va & arm_cache_prefer_mask);
3411 #endif
3412 #ifdef PMAP_CACHE_VIVT
3413 			md->pvh_attrs |= PVF_KMPAGE;
3414 #endif
3415 			pmap_kmpages++;
3416 #ifdef PMAP_CACHE_VIPT
3417 		} else {
3418 			if (pv == NULL) {
3419 				pv = pool_get(&pmap_pv_pool, PR_NOWAIT);
3420 				KASSERT(pv != NULL);
3421 			}
3422 			pmap_enter_pv(md, pa, pv, pmap_kernel(), va,
3423 			    PVF_WIRED | PVF_KENTRY
3424 			    | (prot & VM_PROT_WRITE ? PVF_WRITE : 0));
3425 			if ((prot & VM_PROT_WRITE)
3426 			    && !(md->pvh_attrs & PVF_NC))
3427 				md->pvh_attrs |= PVF_DIRTY;
3428 			KASSERT((prot & VM_PROT_WRITE) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
3429 			pmap_vac_me_harder(md, pa, pmap_kernel(), va);
3430 #endif
3431 		}
3432 #ifdef PMAP_CACHE_VIPT
3433 	} else {
3434 		if (pv != NULL)
3435 			pool_put(&pmap_pv_pool, pv);
3436 #endif
3437 	}
3438 }
3439 
3440 void
3441 pmap_kremove(vaddr_t va, vsize_t len)
3442 {
3443 	vaddr_t next_bucket, eva;
3444 	u_int mappings;
3445 
3446 	PMAPCOUNT(kenter_unmappings);
3447 
3448 	NPDEBUG(PDB_KREMOVE, printf("pmap_kremove: va 0x%08lx, len 0x%08lx\n",
3449 	    va, len));
3450 
3451 	eva = va + len;
3452 
3453 	while (va < eva) {
3454 		next_bucket = L2_NEXT_BUCKET(va);
3455 		if (next_bucket > eva)
3456 			next_bucket = eva;
3457 
3458 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pmap_kernel(), va);
3459 		KDASSERT(l2b != NULL);
3460 
3461 		pt_entry_t * const sptep = &l2b->l2b_kva[l2pte_index(va)];
3462 		pt_entry_t *ptep = sptep;
3463 		mappings = 0;
3464 
3465 		while (va < next_bucket) {
3466 			const pt_entry_t opte = *ptep;
3467 			struct vm_page *opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
3468 			if (opg != NULL) {
3469 				struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
3470 
3471 				if (omd->pvh_attrs & PVF_KMPAGE) {
3472 					KASSERT(omd->urw_mappings == 0);
3473 					KASSERT(omd->uro_mappings == 0);
3474 					KASSERT(omd->krw_mappings == 0);
3475 					KASSERT(omd->kro_mappings == 0);
3476 					omd->pvh_attrs &= ~PVF_KMPAGE;
3477 #ifdef PMAP_CACHE_VIPT
3478 					if (arm_cache_prefer_mask != 0) {
3479 						omd->pvh_attrs &= ~PVF_WRITE;
3480 					}
3481 #endif
3482 					pmap_kmpages--;
3483 #ifdef PMAP_CACHE_VIPT
3484 				} else {
3485 					pool_put(&pmap_pv_pool,
3486 					    pmap_kremove_pg(opg, va));
3487 #endif
3488 				}
3489 			}
3490 			if (l2pte_valid(opte)) {
3491 #ifdef PMAP_CACHE_VIVT
3492 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
3493 #endif
3494 				cpu_tlb_flushD_SE(va);
3495 			}
3496 			if (opte) {
3497 				l2pte_reset(ptep);
3498 				mappings++;
3499 			}
3500 			va += PAGE_SIZE;
3501 			ptep += PAGE_SIZE / L2_S_SIZE;
3502 		}
3503 		KDASSERT(mappings <= l2b->l2b_occupancy);
3504 		l2b->l2b_occupancy -= mappings;
3505 		PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
3506 	}
3507 	cpu_cpwait();
3508 }
3509 
3510 bool
3511 pmap_extract(pmap_t pm, vaddr_t va, paddr_t *pap)
3512 {
3513 	struct l2_dtable *l2;
3514 	pd_entry_t *pl1pd, l1pd;
3515 	pt_entry_t *ptep, pte;
3516 	paddr_t pa;
3517 	u_int l1idx;
3518 
3519 	pmap_acquire_pmap_lock(pm);
3520 
3521 	l1idx = L1_IDX(va);
3522 	pl1pd = pmap_l1_kva(pm) + l1idx;
3523 	l1pd = *pl1pd;
3524 
3525 	if (l1pte_section_p(l1pd)) {
3526 		/*
3527 		 * These should only happen for pmap_kernel()
3528 		 */
3529 		KDASSERT(pm == pmap_kernel());
3530 		pmap_release_pmap_lock(pm);
3531 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
3532 		if (l1pte_supersection_p(l1pd)) {
3533 			pa = (l1pd & L1_SS_FRAME) | (va & L1_SS_OFFSET);
3534 		} else
3535 #endif
3536 			pa = (l1pd & L1_S_FRAME) | (va & L1_S_OFFSET);
3537 	} else {
3538 		/*
3539 		 * Note that we can't rely on the validity of the L1
3540 		 * descriptor as an indication that a mapping exists.
3541 		 * We have to look it up in the L2 dtable.
3542 		 */
3543 		l2 = pm->pm_l2[L2_IDX(l1idx)];
3544 
3545 		if (l2 == NULL ||
3546 		    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
3547 			pmap_release_pmap_lock(pm);
3548 			return false;
3549 		}
3550 
3551 		ptep = &ptep[l2pte_index(va)];
3552 		pte = *ptep;
3553 		pmap_release_pmap_lock(pm);
3554 
3555 		if (pte == 0)
3556 			return false;
3557 
3558 		switch (pte & L2_TYPE_MASK) {
3559 		case L2_TYPE_L:
3560 			pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
3561 			break;
3562 
3563 		default:
3564 			pa = (pte & L2_S_FRAME) | (va & L2_S_OFFSET);
3565 			break;
3566 		}
3567 	}
3568 
3569 	if (pap != NULL)
3570 		*pap = pa;
3571 
3572 	return true;
3573 }
3574 
3575 void
3576 pmap_protect(pmap_t pm, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
3577 {
3578 	struct l2_bucket *l2b;
3579 	pt_entry_t *ptep, pte;
3580 	vaddr_t next_bucket;
3581 
3582 	NPDEBUG(PDB_PROTECT,
3583 	    printf("pmap_protect: pm %p sva 0x%lx eva 0x%lx prot 0x%x\n",
3584 	    pm, sva, eva, prot));
3585 
3586 	if ((prot & VM_PROT_READ) == 0) {
3587 		pmap_remove(pm, sva, eva);
3588 		return;
3589 	}
3590 
3591 	if (prot & VM_PROT_WRITE) {
3592 		/*
3593 		 * If this is a read->write transition, just ignore it and let
3594 		 * uvm_fault() take care of it later.
3595 		 */
3596 		return;
3597 	}
3598 
3599 	pmap_acquire_pmap_lock(pm);
3600 
3601 	const bool flush = eva - sva >= PAGE_SIZE * 4;
3602 	u_int clr_mask = PVF_WRITE | ((prot & VM_PROT_EXECUTE) ? 0 : PVF_EXEC);
3603 	u_int flags = 0;
3604 
3605 	while (sva < eva) {
3606 		next_bucket = L2_NEXT_BUCKET(sva);
3607 		if (next_bucket > eva)
3608 			next_bucket = eva;
3609 
3610 		l2b = pmap_get_l2_bucket(pm, sva);
3611 		if (l2b == NULL) {
3612 			sva = next_bucket;
3613 			continue;
3614 		}
3615 
3616 		ptep = &l2b->l2b_kva[l2pte_index(sva)];
3617 
3618 		while (sva < next_bucket) {
3619 			pte = *ptep;
3620 			if (l2pte_valid(pte) != 0 && l2pte_writable_p(pte)) {
3621 				struct vm_page *pg;
3622 				u_int f;
3623 
3624 #ifdef PMAP_CACHE_VIVT
3625 				/*
3626 				 * OK, at this point, we know we're doing
3627 				 * write-protect operation.  If the pmap is
3628 				 * active, write-back the page.
3629 				 */
3630 				pmap_cache_wbinv_page(pm, sva, false, PVF_REF);
3631 #endif
3632 
3633 				pg = PHYS_TO_VM_PAGE(l2pte_pa(pte));
3634 				pte = l2pte_set_readonly(pte);
3635 				*ptep = pte;
3636 				PTE_SYNC(ptep);
3637 
3638 				if (pg != NULL) {
3639 					struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3640 					paddr_t pa = VM_PAGE_TO_PHYS(pg);
3641 
3642 #ifdef MULTIPROCESSOR
3643 					KASSERT(uvm_page_locked_p(pg));
3644 #endif
3645 					f = pmap_modify_pv(md, pa, pm, sva,
3646 					    clr_mask, 0);
3647 					pmap_vac_me_harder(md, pa, pm, sva);
3648 				} else {
3649 					f = PVF_REF | PVF_EXEC;
3650 				}
3651 
3652 				if (flush) {
3653 					flags |= f;
3654 				} else {
3655 					pmap_tlb_flush_SE(pm, sva, f);
3656 				}
3657 			}
3658 
3659 			sva += PAGE_SIZE;
3660 			ptep++;
3661 		}
3662 	}
3663 
3664 	if (flush) {
3665 		if (PV_BEEN_EXECD(flags)) {
3666 			pmap_tlb_flushID(pm);
3667 		} else if (PV_BEEN_REFD(flags)) {
3668 			pmap_tlb_flushD(pm);
3669 		}
3670 	}
3671 
3672 	pmap_release_pmap_lock(pm);
3673 }
3674 
3675 void
3676 pmap_icache_sync_range(pmap_t pm, vaddr_t sva, vaddr_t eva)
3677 {
3678 	struct l2_bucket *l2b;
3679 	pt_entry_t *ptep;
3680 	vaddr_t next_bucket;
3681 	vsize_t page_size = trunc_page(sva) + PAGE_SIZE - sva;
3682 
3683 	NPDEBUG(PDB_EXEC,
3684 	    printf("pmap_icache_sync_range: pm %p sva 0x%lx eva 0x%lx\n",
3685 	    pm, sva, eva));
3686 
3687 	pmap_acquire_pmap_lock(pm);
3688 
3689 	while (sva < eva) {
3690 		next_bucket = L2_NEXT_BUCKET(sva);
3691 		if (next_bucket > eva)
3692 			next_bucket = eva;
3693 
3694 		l2b = pmap_get_l2_bucket(pm, sva);
3695 		if (l2b == NULL) {
3696 			sva = next_bucket;
3697 			continue;
3698 		}
3699 
3700 		for (ptep = &l2b->l2b_kva[l2pte_index(sva)];
3701 		     sva < next_bucket;
3702 		     sva += page_size, ptep++, page_size = PAGE_SIZE) {
3703 			if (l2pte_valid(*ptep)) {
3704 				cpu_icache_sync_range(sva,
3705 				    min(page_size, eva - sva));
3706 			}
3707 		}
3708 	}
3709 
3710 	pmap_release_pmap_lock(pm);
3711 }
3712 
3713 void
3714 pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
3715 {
3716 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3717 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
3718 
3719 	NPDEBUG(PDB_PROTECT,
3720 	    printf("pmap_page_protect: md %p (0x%08lx), prot 0x%x\n",
3721 	    md, pa, prot));
3722 
3723 #ifdef MULTIPROCESSOR
3724 	KASSERT(uvm_page_locked_p(pg));
3725 #endif
3726 
3727 	switch(prot) {
3728 	case VM_PROT_READ|VM_PROT_WRITE:
3729 #if defined(PMAP_CHECK_VIPT) && defined(PMAP_APX)
3730 		pmap_clearbit(md, pa, PVF_EXEC);
3731 		break;
3732 #endif
3733 	case VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE:
3734 		break;
3735 
3736 	case VM_PROT_READ:
3737 #if defined(PMAP_CHECK_VIPT) && defined(PMAP_APX)
3738 		pmap_clearbit(md, pa, PVF_WRITE|PVF_EXEC);
3739 		break;
3740 #endif
3741 	case VM_PROT_READ|VM_PROT_EXECUTE:
3742 		pmap_clearbit(md, pa, PVF_WRITE);
3743 		break;
3744 
3745 	default:
3746 		pmap_page_remove(md, pa);
3747 		break;
3748 	}
3749 }
3750 
3751 /*
3752  * pmap_clear_modify:
3753  *
3754  *	Clear the "modified" attribute for a page.
3755  */
3756 bool
3757 pmap_clear_modify(struct vm_page *pg)
3758 {
3759 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3760 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
3761 	bool rv;
3762 
3763 #ifdef MULTIPROCESSOR
3764 	KASSERT(uvm_page_locked_p(pg));
3765 #endif
3766 
3767 	if (md->pvh_attrs & PVF_MOD) {
3768 		rv = true;
3769 #ifdef PMAP_CACHE_VIPT
3770 		/*
3771 		 * If we are going to clear the modified bit and there are
3772 		 * no other modified bits set, flush the page to memory and
3773 		 * mark it clean.
3774 		 */
3775 		if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) == PVF_MOD)
3776 			pmap_flush_page(md, pa, PMAP_CLEAN_PRIMARY);
3777 #endif
3778 		pmap_clearbit(md, pa, PVF_MOD);
3779 	} else
3780 		rv = false;
3781 
3782 	return (rv);
3783 }
3784 
3785 /*
3786  * pmap_clear_reference:
3787  *
3788  *	Clear the "referenced" attribute for a page.
3789  */
3790 bool
3791 pmap_clear_reference(struct vm_page *pg)
3792 {
3793 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3794 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
3795 	bool rv;
3796 
3797 #ifdef MULTIPROCESSOR
3798 	KASSERT(uvm_page_locked_p(pg));
3799 #endif
3800 
3801 	if (md->pvh_attrs & PVF_REF) {
3802 		rv = true;
3803 		pmap_clearbit(md, pa, PVF_REF);
3804 	} else
3805 		rv = false;
3806 
3807 	return (rv);
3808 }
3809 
3810 /*
3811  * pmap_is_modified:
3812  *
3813  *	Test if a page has the "modified" attribute.
3814  */
3815 /* See <arm/arm32/pmap.h> */
3816 
3817 /*
3818  * pmap_is_referenced:
3819  *
3820  *	Test if a page has the "referenced" attribute.
3821  */
3822 /* See <arm/arm32/pmap.h> */
3823 
3824 int
3825 pmap_fault_fixup(pmap_t pm, vaddr_t va, vm_prot_t ftype, int user)
3826 {
3827 	struct l2_dtable *l2;
3828 	struct l2_bucket *l2b;
3829 	pd_entry_t *pl1pd, l1pd;
3830 	pt_entry_t *ptep, pte;
3831 	paddr_t pa;
3832 	u_int l1idx;
3833 	int rv = 0;
3834 
3835 	pmap_acquire_pmap_lock(pm);
3836 
3837 	l1idx = L1_IDX(va);
3838 
3839 	/*
3840 	 * If there is no l2_dtable for this address, then the process
3841 	 * has no business accessing it.
3842 	 *
3843 	 * Note: This will catch userland processes trying to access
3844 	 * kernel addresses.
3845 	 */
3846 	l2 = pm->pm_l2[L2_IDX(l1idx)];
3847 	if (l2 == NULL)
3848 		goto out;
3849 
3850 	/*
3851 	 * Likewise if there is no L2 descriptor table
3852 	 */
3853 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
3854 	if (l2b->l2b_kva == NULL)
3855 		goto out;
3856 
3857 	/*
3858 	 * Check the PTE itself.
3859 	 */
3860 	ptep = &l2b->l2b_kva[l2pte_index(va)];
3861 	pte = *ptep;
3862 	if (pte == 0)
3863 		goto out;
3864 
3865 	/*
3866 	 * Catch a userland access to the vector page mapped at 0x0
3867 	 */
3868 	if (user && (pte & L2_S_PROT_U) == 0)
3869 		goto out;
3870 
3871 	pa = l2pte_pa(pte);
3872 
3873 	if ((ftype & VM_PROT_WRITE) && !l2pte_writable_p(pte)) {
3874 		/*
3875 		 * This looks like a good candidate for "page modified"
3876 		 * emulation...
3877 		 */
3878 		struct pv_entry *pv;
3879 		struct vm_page *pg;
3880 
3881 		/* Extract the physical address of the page */
3882 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
3883 			goto out;
3884 
3885 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3886 
3887 		/* Get the current flags for this page. */
3888 #ifdef MULTIPROCESSOR
3889 		KASSERT(uvm_page_locked_p(pg));
3890 #endif
3891 
3892 		pv = pmap_find_pv(md, pm, va);
3893 		if (pv == NULL) {
3894 			goto out;
3895 		}
3896 
3897 		/*
3898 		 * Do the flags say this page is writable? If not then it
3899 		 * is a genuine write fault. If yes then the write fault is
3900 		 * our fault as we did not reflect the write access in the
3901 		 * PTE. Now we know a write has occurred we can correct this
3902 		 * and also set the modified bit
3903 		 */
3904 		if ((pv->pv_flags & PVF_WRITE) == 0) {
3905 			goto out;
3906 		}
3907 
3908 		NPDEBUG(PDB_FOLLOW,
3909 		    printf("pmap_fault_fixup: mod emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
3910 		    pm, va, pa));
3911 
3912 		md->pvh_attrs |= PVF_REF | PVF_MOD;
3913 		pv->pv_flags |= PVF_REF | PVF_MOD;
3914 #ifdef PMAP_CACHE_VIPT
3915 		/*
3916 		 * If there are cacheable mappings for this page, mark it dirty.
3917 		 */
3918 		if ((md->pvh_attrs & PVF_NC) == 0)
3919 			md->pvh_attrs |= PVF_DIRTY;
3920 #endif
3921 
3922 		/*
3923 		 * Re-enable write permissions for the page.  No need to call
3924 		 * pmap_vac_me_harder(), since this is just a
3925 		 * modified-emulation fault, and the PVF_WRITE bit isn't
3926 		 * changing. We've already set the cacheable bits based on
3927 		 * the assumption that we can write to this page.
3928 		 */
3929 		*ptep = l2pte_set_writable((pte & ~L2_TYPE_MASK) | L2_S_PROTO);
3930 		PTE_SYNC(ptep);
3931 		rv = 1;
3932 	} else
3933 	if ((pte & L2_TYPE_MASK) == L2_TYPE_INV) {
3934 		/*
3935 		 * This looks like a good candidate for "page referenced"
3936 		 * emulation.
3937 		 */
3938 		struct pv_entry *pv;
3939 		struct vm_page *pg;
3940 
3941 		/* Extract the physical address of the page */
3942 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL)
3943 			goto out;
3944 
3945 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
3946 
3947 		/* Get the current flags for this page. */
3948 #ifdef MULTIPROCESSOR
3949 		KASSERT(uvm_page_locked_p(pg));
3950 #endif
3951 
3952 		pv = pmap_find_pv(md, pm, va);
3953 		if (pv == NULL) {
3954 			goto out;
3955 		}
3956 
3957 		md->pvh_attrs |= PVF_REF;
3958 		pv->pv_flags |= PVF_REF;
3959 
3960 		NPDEBUG(PDB_FOLLOW,
3961 		    printf("pmap_fault_fixup: ref emul. pm %p, va 0x%08lx, pa 0x%08lx\n",
3962 		    pm, va, pa));
3963 
3964 		*ptep = l2pte_set_readonly((pte & ~L2_TYPE_MASK) | L2_S_PROTO);
3965 		PTE_SYNC(ptep);
3966 		rv = 1;
3967 	}
3968 
3969 	/*
3970 	 * We know there is a valid mapping here, so simply
3971 	 * fix up the L1 if necessary.
3972 	 */
3973 	pl1pd = pmap_l1_kva(pm) + l1idx;
3974 	l1pd = l2b->l2b_phys | L1_C_DOM(pmap_domain(pm)) | L1_C_PROTO;
3975 	if (*pl1pd != l1pd) {
3976 		*pl1pd = l1pd;
3977 		PTE_SYNC(pl1pd);
3978 		rv = 1;
3979 	}
3980 
3981 #ifdef CPU_SA110
3982 	/*
3983 	 * There are bugs in the rev K SA110.  This is a check for one
3984 	 * of them.
3985 	 */
3986 	if (rv == 0 && curcpu()->ci_arm_cputype == CPU_ID_SA110 &&
3987 	    curcpu()->ci_arm_cpurev < 3) {
3988 		/* Always current pmap */
3989 		if (l2pte_valid(pte)) {
3990 			extern int kernel_debug;
3991 			if (kernel_debug & 1) {
3992 				struct proc *p = curlwp->l_proc;
3993 				printf("prefetch_abort: page is already "
3994 				    "mapped - pte=%p *pte=%08x\n", ptep, pte);
3995 				printf("prefetch_abort: pc=%08lx proc=%p "
3996 				    "process=%s\n", va, p, p->p_comm);
3997 				printf("prefetch_abort: far=%08x fs=%x\n",
3998 				    cpu_faultaddress(), cpu_faultstatus());
3999 			}
4000 #ifdef DDB
4001 			if (kernel_debug & 2)
4002 				Debugger();
4003 #endif
4004 			rv = 1;
4005 		}
4006 	}
4007 #endif /* CPU_SA110 */
4008 
4009 	/*
4010 	 * If 'rv == 0' at this point, it generally indicates that there is a
4011 	 * stale TLB entry for the faulting address.  That might be due to a
4012 	 * wrong setting of pmap_needs_pte_sync.  So set it and retry.
4013 	 */
4014 	if (rv == 0 && pm->pm_l1->l1_domain_use_count == 1
4015 	    && pmap_needs_pte_sync == 0) {
4016 		pmap_needs_pte_sync = 1;
4017 		PTE_SYNC(ptep);
4018 		rv = 1;
4019 	}
4020 
4021 #ifdef DEBUG
4022 	/*
4023 	 * If 'rv == 0' at this point, it generally indicates that there is a
4024 	 * stale TLB entry for the faulting address. This happens when two or
4025 	 * more processes are sharing an L1. Since we don't flush the TLB on
4026 	 * a context switch between such processes, we can take domain faults
4027 	 * for mappings which exist at the same VA in both processes. EVEN IF
4028 	 * WE'VE RECENTLY FIXED UP THE CORRESPONDING L1 in pmap_enter(), for
4029 	 * example.
4030 	 *
4031 	 * This is extremely likely to happen if pmap_enter() updated the L1
4032 	 * entry for a recently entered mapping. In this case, the TLB is
4033 	 * flushed for the new mapping, but there may still be TLB entries for
4034 	 * other mappings belonging to other processes in the 1MB range
4035 	 * covered by the L1 entry.
4036 	 *
4037 	 * Since 'rv == 0', we know that the L1 already contains the correct
4038 	 * value, so the fault must be due to a stale TLB entry.
4039 	 *
4040 	 * Since we always need to flush the TLB anyway in the case where we
4041 	 * fixed up the L1, or frobbed the L2 PTE, we effectively deal with
4042 	 * stale TLB entries dynamically.
4043 	 *
4044 	 * However, the above condition can ONLY happen if the current L1 is
4045 	 * being shared. If it happens when the L1 is unshared, it indicates
4046 	 * that other parts of the pmap are not doing their job WRT managing
4047 	 * the TLB.
4048 	 */
4049 	if (rv == 0 && pm->pm_l1->l1_domain_use_count == 1) {
4050 		extern int last_fault_code;
4051 		printf("fixup: pm %p, va 0x%lx, ftype %d - nothing to do!\n",
4052 		    pm, va, ftype);
4053 		printf("fixup: l2 %p, l2b %p, ptep %p, pl1pd %p\n",
4054 		    l2, l2b, ptep, pl1pd);
4055 		printf("fixup: pte 0x%x, l1pd 0x%x, last code 0x%x\n",
4056 		    pte, l1pd, last_fault_code);
4057 #ifdef DDB
4058 		extern int kernel_debug;
4059 
4060 		if (kernel_debug & 2)
4061 			Debugger();
4062 #endif
4063 	}
4064 #endif
4065 
4066 	cpu_tlb_flushID_SE(va);
4067 	cpu_cpwait();
4068 
4069 	rv = 1;
4070 
4071 out:
4072 	pmap_release_pmap_lock(pm);
4073 
4074 	return (rv);
4075 }
4076 
4077 /*
4078  * Routine:	pmap_procwr
4079  *
4080  * Function:
4081  *	Synchronize caches corresponding to [addr, addr+len) in p.
4082  *
4083  */
4084 void
4085 pmap_procwr(struct proc *p, vaddr_t va, int len)
4086 {
4087 	/* We only need to do anything if it is the current process. */
4088 	if (p == curproc)
4089 		cpu_icache_sync_range(va, len);
4090 }
4091 
4092 /*
4093  * Routine:	pmap_unwire
4094  * Function:	Clear the wired attribute for a map/virtual-address pair.
4095  *
4096  * In/out conditions:
4097  *		The mapping must already exist in the pmap.
4098  */
4099 void
4100 pmap_unwire(pmap_t pm, vaddr_t va)
4101 {
4102 	struct l2_bucket *l2b;
4103 	pt_entry_t *ptep, pte;
4104 	struct vm_page *pg;
4105 	paddr_t pa;
4106 
4107 	NPDEBUG(PDB_WIRING, printf("pmap_unwire: pm %p, va 0x%08lx\n", pm, va));
4108 
4109 	pmap_acquire_pmap_lock(pm);
4110 
4111 	l2b = pmap_get_l2_bucket(pm, va);
4112 	KDASSERT(l2b != NULL);
4113 
4114 	ptep = &l2b->l2b_kva[l2pte_index(va)];
4115 	pte = *ptep;
4116 
4117 	/* Extract the physical address of the page */
4118 	pa = l2pte_pa(pte);
4119 
4120 	if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
4121 		/* Update the wired bit in the pv entry for this page. */
4122 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
4123 
4124 #ifdef MULTIPROCESSOR
4125 		KASSERT(uvm_page_locked_p(pg));
4126 #endif
4127 		(void) pmap_modify_pv(md, pa, pm, va, PVF_WIRED, 0);
4128 	}
4129 
4130 	pmap_release_pmap_lock(pm);
4131 }
4132 
4133 void
4134 pmap_activate(struct lwp *l)
4135 {
4136 	extern int block_userspace_access;
4137 	pmap_t opm, npm, rpm;
4138 	uint32_t odacr, ndacr;
4139 	int oldirqstate;
4140 
4141 	/*
4142 	 * If activating a non-current lwp or the current lwp is
4143 	 * already active, just return.
4144 	 */
4145 	if (l != curlwp ||
4146 	    l->l_proc->p_vmspace->vm_map.pmap->pm_activated == true)
4147 		return;
4148 
4149 	npm = l->l_proc->p_vmspace->vm_map.pmap;
4150 	ndacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
4151 	    (DOMAIN_CLIENT << (pmap_domain(npm) * 2));
4152 
4153 	/*
4154 	 * If TTB and DACR are unchanged, short-circuit all the
4155 	 * TLB/cache management stuff.
4156 	 */
4157 	if (pmap_previous_active_lwp != NULL) {
4158 		opm = pmap_previous_active_lwp->l_proc->p_vmspace->vm_map.pmap;
4159 		odacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2)) |
4160 		    (DOMAIN_CLIENT << (pmap_domain(opm) * 2));
4161 
4162 		if (opm->pm_l1 == npm->pm_l1 && odacr == ndacr)
4163 			goto all_done;
4164 	} else
4165 		opm = NULL;
4166 
4167 	PMAPCOUNT(activations);
4168 	block_userspace_access = 1;
4169 
4170 	/*
4171 	 * If switching to a user vmspace which is different to the
4172 	 * most recent one, and the most recent one is potentially
4173 	 * live in the cache, we must write-back and invalidate the
4174 	 * entire cache.
4175 	 */
4176 	rpm = pmap_recent_user;
4177 
4178 /*
4179  * XXXSCW: There's a corner case here which can leave turds in the cache as
4180  * reported in kern/41058. They're probably left over during tear-down and
4181  * switching away from an exiting process. Until the root cause is identified
4182  * and fixed, zap the cache when switching pmaps. This will result in a few
4183  * unnecessary cache flushes, but that's better than silently corrupting data.
4184  */
4185 #if 0
4186 	if (npm != pmap_kernel() && rpm && npm != rpm &&
4187 	    rpm->pm_cstate.cs_cache) {
4188 		rpm->pm_cstate.cs_cache = 0;
4189 #ifdef PMAP_CACHE_VIVT
4190 		cpu_idcache_wbinv_all();
4191 #endif
4192 	}
4193 #else
4194 	if (rpm) {
4195 		rpm->pm_cstate.cs_cache = 0;
4196 		if (npm == pmap_kernel())
4197 			pmap_recent_user = NULL;
4198 #ifdef PMAP_CACHE_VIVT
4199 		cpu_idcache_wbinv_all();
4200 #endif
4201 	}
4202 #endif
4203 
4204 	/* No interrupts while we frob the TTB/DACR */
4205 	oldirqstate = disable_interrupts(IF32_bits);
4206 
4207 #ifndef ARM_HAS_VBAR
4208 	/*
4209 	 * For ARM_VECTORS_LOW, we MUST, I repeat, MUST fix up the L1
4210 	 * entry corresponding to 'vector_page' in the incoming L1 table
4211 	 * before switching to it otherwise subsequent interrupts/exceptions
4212 	 * (including domain faults!) will jump into hyperspace.
4213 	 */
4214 	if (npm->pm_pl1vec != NULL) {
4215 		cpu_tlb_flushID_SE((u_int)vector_page);
4216 		cpu_cpwait();
4217 		*npm->pm_pl1vec = npm->pm_l1vec;
4218 		PTE_SYNC(npm->pm_pl1vec);
4219 	}
4220 #endif
4221 
4222 	cpu_domains(ndacr);
4223 
4224 	if (npm == pmap_kernel() || npm == rpm) {
4225 		/*
4226 		 * Switching to a kernel thread, or back to the
4227 		 * same user vmspace as before... Simply update
4228 		 * the TTB (no TLB flush required)
4229 		 */
4230 		cpu_setttb(npm->pm_l1->l1_physaddr, false);
4231 		cpu_cpwait();
4232 	} else {
4233 		/*
4234 		 * Otherwise, update TTB and flush TLB
4235 		 */
4236 		cpu_context_switch(npm->pm_l1->l1_physaddr);
4237 		if (rpm != NULL)
4238 			rpm->pm_cstate.cs_tlb = 0;
4239 	}
4240 
4241 	restore_interrupts(oldirqstate);
4242 
4243 	block_userspace_access = 0;
4244 
4245  all_done:
4246 	/*
4247 	 * The new pmap is resident. Make sure it's marked
4248 	 * as resident in the cache/TLB.
4249 	 */
4250 	npm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
4251 	if (npm != pmap_kernel())
4252 		pmap_recent_user = npm;
4253 
4254 	/* The old pmap is not longer active */
4255 	if (opm != NULL)
4256 		opm->pm_activated = false;
4257 
4258 	/* But the new one is */
4259 	npm->pm_activated = true;
4260 }
4261 
4262 void
4263 pmap_deactivate(struct lwp *l)
4264 {
4265 
4266 	/*
4267 	 * If the process is exiting, make sure pmap_activate() does
4268 	 * a full MMU context-switch and cache flush, which we might
4269 	 * otherwise skip. See PR port-arm/38950.
4270 	 */
4271 	if (l->l_proc->p_sflag & PS_WEXIT)
4272 		pmap_previous_active_lwp = NULL;
4273 
4274 	l->l_proc->p_vmspace->vm_map.pmap->pm_activated = false;
4275 }
4276 
4277 void
4278 pmap_update(pmap_t pm)
4279 {
4280 
4281 	if (pm->pm_remove_all) {
4282 		/*
4283 		 * Finish up the pmap_remove_all() optimisation by flushing
4284 		 * the TLB.
4285 		 */
4286 		pmap_tlb_flushID(pm);
4287 		pm->pm_remove_all = false;
4288 	}
4289 
4290 	if (pmap_is_current(pm)) {
4291 		/*
4292 		 * If we're dealing with a current userland pmap, move its L1
4293 		 * to the end of the LRU.
4294 		 */
4295 		if (pm != pmap_kernel())
4296 			pmap_use_l1(pm);
4297 
4298 		/*
4299 		 * We can assume we're done with frobbing the cache/tlb for
4300 		 * now. Make sure any future pmap ops don't skip cache/tlb
4301 		 * flushes.
4302 		 */
4303 		pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
4304 	}
4305 
4306 	PMAPCOUNT(updates);
4307 
4308 	/*
4309 	 * make sure TLB/cache operations have completed.
4310 	 */
4311 	cpu_cpwait();
4312 }
4313 
4314 void
4315 pmap_remove_all(pmap_t pm)
4316 {
4317 
4318 	/*
4319 	 * The vmspace described by this pmap is about to be torn down.
4320 	 * Until pmap_update() is called, UVM will only make calls
4321 	 * to pmap_remove(). We can make life much simpler by flushing
4322 	 * the cache now, and deferring TLB invalidation to pmap_update().
4323 	 */
4324 #ifdef PMAP_CACHE_VIVT
4325 	pmap_cache_wbinv_all(pm, PVF_EXEC);
4326 #endif
4327 	pm->pm_remove_all = true;
4328 }
4329 
4330 /*
4331  * Retire the given physical map from service.
4332  * Should only be called if the map contains no valid mappings.
4333  */
4334 void
4335 pmap_destroy(pmap_t pm)
4336 {
4337 	u_int count;
4338 
4339 	if (pm == NULL)
4340 		return;
4341 
4342 	if (pm->pm_remove_all) {
4343 		pmap_tlb_flushID(pm);
4344 		pm->pm_remove_all = false;
4345 	}
4346 
4347 	/*
4348 	 * Drop reference count
4349 	 */
4350 	mutex_enter(pm->pm_lock);
4351 	count = --pm->pm_obj.uo_refs;
4352 	mutex_exit(pm->pm_lock);
4353 	if (count > 0) {
4354 		if (pmap_is_current(pm)) {
4355 			if (pm != pmap_kernel())
4356 				pmap_use_l1(pm);
4357 			pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
4358 		}
4359 		return;
4360 	}
4361 
4362 	/*
4363 	 * reference count is zero, free pmap resources and then free pmap.
4364 	 */
4365 
4366 #ifndef ARM_HAS_VBAR
4367 	if (vector_page < KERNEL_BASE) {
4368 		KDASSERT(!pmap_is_current(pm));
4369 
4370 		/* Remove the vector page mapping */
4371 		pmap_remove(pm, vector_page, vector_page + PAGE_SIZE);
4372 		pmap_update(pm);
4373 	}
4374 #endif
4375 
4376 	LIST_REMOVE(pm, pm_list);
4377 
4378 	pmap_free_l1(pm);
4379 
4380 	if (pmap_recent_user == pm)
4381 		pmap_recent_user = NULL;
4382 
4383 	uvm_obj_destroy(&pm->pm_obj, false);
4384 	mutex_destroy(&pm->pm_obj_lock);
4385 	pool_cache_put(&pmap_cache, pm);
4386 }
4387 
4388 
4389 /*
4390  * void pmap_reference(pmap_t pm)
4391  *
4392  * Add a reference to the specified pmap.
4393  */
4394 void
4395 pmap_reference(pmap_t pm)
4396 {
4397 
4398 	if (pm == NULL)
4399 		return;
4400 
4401 	pmap_use_l1(pm);
4402 
4403 	mutex_enter(pm->pm_lock);
4404 	pm->pm_obj.uo_refs++;
4405 	mutex_exit(pm->pm_lock);
4406 }
4407 
4408 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
4409 
4410 static struct evcnt pmap_prefer_nochange_ev =
4411     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap prefer", "nochange");
4412 static struct evcnt pmap_prefer_change_ev =
4413     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap prefer", "change");
4414 
4415 EVCNT_ATTACH_STATIC(pmap_prefer_change_ev);
4416 EVCNT_ATTACH_STATIC(pmap_prefer_nochange_ev);
4417 
4418 void
4419 pmap_prefer(vaddr_t hint, vaddr_t *vap, int td)
4420 {
4421 	vsize_t mask = arm_cache_prefer_mask | (PAGE_SIZE - 1);
4422 	vaddr_t va = *vap;
4423 	vaddr_t diff = (hint - va) & mask;
4424 	if (diff == 0) {
4425 		pmap_prefer_nochange_ev.ev_count++;
4426 	} else {
4427 		pmap_prefer_change_ev.ev_count++;
4428 		if (__predict_false(td))
4429 			va -= mask + 1;
4430 		*vap = va + diff;
4431 	}
4432 }
4433 #endif /* ARM_MMU_V6 | ARM_MMU_V7 */
4434 
4435 /*
4436  * pmap_zero_page()
4437  *
4438  * Zero a given physical page by mapping it at a page hook point.
4439  * In doing the zero page op, the page we zero is mapped cachable, as with
4440  * StrongARM accesses to non-cached pages are non-burst making writing
4441  * _any_ bulk data very slow.
4442  */
4443 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
4444 void
4445 pmap_zero_page_generic(paddr_t phys)
4446 {
4447 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
4448 	struct vm_page *pg = PHYS_TO_VM_PAGE(phys);
4449 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
4450 #endif
4451 #if defined(PMAP_CACHE_VIPT)
4452 	/* Choose the last page color it had, if any */
4453 	const vsize_t va_offset = md->pvh_attrs & arm_cache_prefer_mask;
4454 #else
4455 	const vsize_t va_offset = 0;
4456 #endif
4457 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS)
4458 	/*
4459 	 * Is this page mapped at its natural color?
4460 	 * If we have all of memory mapped, then just convert PA to VA.
4461 	 */
4462 	const bool okcolor = va_offset == (phys & arm_cache_prefer_mask);
4463 	const vaddr_t vdstp = KERNEL_BASE + (phys - physical_start);
4464 #else
4465 	const bool okcolor = false;
4466 	const vaddr_t vdstp = cdstp + va_offset;
4467 #endif
4468 	pt_entry_t * const ptep = &cdst_pte[va_offset >> PGSHIFT];
4469 
4470 
4471 #ifdef DEBUG
4472 	if (!SLIST_EMPTY(&md->pvh_list))
4473 		panic("pmap_zero_page: page has mappings");
4474 #endif
4475 
4476 	KDASSERT((phys & PGOFSET) == 0);
4477 
4478 	if (!okcolor) {
4479 		/*
4480 		 * Hook in the page, zero it, and purge the cache for that
4481 		 * zeroed page. Invalidate the TLB as needed.
4482 		 */
4483 		*ptep = L2_S_PROTO | phys |
4484 		    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
4485 		PTE_SYNC(ptep);
4486 		cpu_tlb_flushD_SE(cdstp + va_offset);
4487 		cpu_cpwait();
4488 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS) && defined(PMAP_CACHE_VIPT)
4489 		/*
4490 		 * If we are direct-mapped and our color isn't ok, then before
4491 		 * we bzero the page invalidate its contents from the cache and
4492 		 * reset the color to its natural color.
4493 		 */
4494 		cpu_dcache_inv_range(cdstp + va_offset, PAGE_SIZE);
4495 		md->pvh_attrs &= ~arm_cache_prefer_mask;
4496 		md->pvh_attrs |= (phys & arm_cache_prefer_mask);
4497 #endif
4498 	}
4499 	bzero_page(vdstp);
4500 	if (!okcolor) {
4501 		/*
4502 		 * Unmap the page.
4503 		 */
4504 		*ptep = 0;
4505 		PTE_SYNC(ptep);
4506 		cpu_tlb_flushD_SE(cdstp + va_offset);
4507 #ifdef PMAP_CACHE_VIVT
4508 		cpu_dcache_wbinv_range(cdstp + va_offset, PAGE_SIZE);
4509 #endif
4510 	}
4511 #ifdef PMAP_CACHE_VIPT
4512 	/*
4513 	 * This page is now cache resident so it now has a page color.
4514 	 * Any contents have been obliterated so clear the EXEC flag.
4515 	 */
4516 	if (!pmap_is_page_colored_p(md)) {
4517 		PMAPCOUNT(vac_color_new);
4518 		md->pvh_attrs |= PVF_COLORED;
4519 	}
4520 	if (PV_IS_EXEC_P(md->pvh_attrs)) {
4521 		md->pvh_attrs &= ~PVF_EXEC;
4522 		PMAPCOUNT(exec_discarded_zero);
4523 	}
4524 	md->pvh_attrs |= PVF_DIRTY;
4525 #endif
4526 }
4527 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
4528 
4529 #if ARM_MMU_XSCALE == 1
4530 void
4531 pmap_zero_page_xscale(paddr_t phys)
4532 {
4533 #ifdef DEBUG
4534 	struct vm_page *pg = PHYS_TO_VM_PAGE(phys);
4535 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
4536 
4537 	if (!SLIST_EMPTY(&md->pvh_list))
4538 		panic("pmap_zero_page: page has mappings");
4539 #endif
4540 
4541 	KDASSERT((phys & PGOFSET) == 0);
4542 
4543 	/*
4544 	 * Hook in the page, zero it, and purge the cache for that
4545 	 * zeroed page. Invalidate the TLB as needed.
4546 	 */
4547 	*cdst_pte = L2_S_PROTO | phys |
4548 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) |
4549 	    L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
4550 	PTE_SYNC(cdst_pte);
4551 	cpu_tlb_flushD_SE(cdstp);
4552 	cpu_cpwait();
4553 	bzero_page(cdstp);
4554 	xscale_cache_clean_minidata();
4555 }
4556 #endif /* ARM_MMU_XSCALE == 1 */
4557 
4558 /* pmap_pageidlezero()
4559  *
4560  * The same as above, except that we assume that the page is not
4561  * mapped.  This means we never have to flush the cache first.  Called
4562  * from the idle loop.
4563  */
4564 bool
4565 pmap_pageidlezero(paddr_t phys)
4566 {
4567 	unsigned int i;
4568 	int *ptr;
4569 	bool rv = true;
4570 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
4571 	struct vm_page * const pg = PHYS_TO_VM_PAGE(phys);
4572 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
4573 #endif
4574 #ifdef PMAP_CACHE_VIPT
4575 	/* Choose the last page color it had, if any */
4576 	const vsize_t va_offset = md->pvh_attrs & arm_cache_prefer_mask;
4577 #else
4578 	const vsize_t va_offset = 0;
4579 #endif
4580 	pt_entry_t * const ptep = &csrc_pte[va_offset >> PGSHIFT];
4581 
4582 
4583 #ifdef DEBUG
4584 	if (!SLIST_EMPTY(&md->pvh_list))
4585 		panic("pmap_pageidlezero: page has mappings");
4586 #endif
4587 
4588 	KDASSERT((phys & PGOFSET) == 0);
4589 
4590 	/*
4591 	 * Hook in the page, zero it, and purge the cache for that
4592 	 * zeroed page. Invalidate the TLB as needed.
4593 	 */
4594 	*ptep = L2_S_PROTO | phys |
4595 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
4596 	PTE_SYNC(ptep);
4597 	cpu_tlb_flushD_SE(cdstp + va_offset);
4598 	cpu_cpwait();
4599 
4600 	for (i = 0, ptr = (int *)(cdstp + va_offset);
4601 			i < (PAGE_SIZE / sizeof(int)); i++) {
4602 		if (sched_curcpu_runnable_p() != 0) {
4603 			/*
4604 			 * A process has become ready.  Abort now,
4605 			 * so we don't keep it waiting while we
4606 			 * do slow memory access to finish this
4607 			 * page.
4608 			 */
4609 			rv = false;
4610 			break;
4611 		}
4612 		*ptr++ = 0;
4613 	}
4614 
4615 #ifdef PMAP_CACHE_VIVT
4616 	if (rv)
4617 		/*
4618 		 * if we aborted we'll rezero this page again later so don't
4619 		 * purge it unless we finished it
4620 		 */
4621 		cpu_dcache_wbinv_range(cdstp, PAGE_SIZE);
4622 #elif defined(PMAP_CACHE_VIPT)
4623 	/*
4624 	 * This page is now cache resident so it now has a page color.
4625 	 * Any contents have been obliterated so clear the EXEC flag.
4626 	 */
4627 	if (!pmap_is_page_colored_p(md)) {
4628 		PMAPCOUNT(vac_color_new);
4629 		md->pvh_attrs |= PVF_COLORED;
4630 	}
4631 	if (PV_IS_EXEC_P(md->pvh_attrs)) {
4632 		md->pvh_attrs &= ~PVF_EXEC;
4633 		PMAPCOUNT(exec_discarded_zero);
4634 	}
4635 #endif
4636 	/*
4637 	 * Unmap the page.
4638 	 */
4639 	*ptep = 0;
4640 	PTE_SYNC(ptep);
4641 	cpu_tlb_flushD_SE(cdstp + va_offset);
4642 
4643 	return (rv);
4644 }
4645 
4646 /*
4647  * pmap_copy_page()
4648  *
4649  * Copy one physical page into another, by mapping the pages into
4650  * hook points. The same comment regarding cachability as in
4651  * pmap_zero_page also applies here.
4652  */
4653 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
4654 void
4655 pmap_copy_page_generic(paddr_t src, paddr_t dst)
4656 {
4657 	struct vm_page * const src_pg = PHYS_TO_VM_PAGE(src);
4658 	struct vm_page_md *src_md = VM_PAGE_TO_MD(src_pg);
4659 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
4660 	struct vm_page * const dst_pg = PHYS_TO_VM_PAGE(dst);
4661 	struct vm_page_md *dst_md = VM_PAGE_TO_MD(dst_pg);
4662 #endif
4663 #ifdef PMAP_CACHE_VIPT
4664 	const vsize_t src_va_offset = src_md->pvh_attrs & arm_cache_prefer_mask;
4665 	const vsize_t dst_va_offset = dst_md->pvh_attrs & arm_cache_prefer_mask;
4666 #else
4667 	const vsize_t src_va_offset = 0;
4668 	const vsize_t dst_va_offset = 0;
4669 #endif
4670 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS)
4671 	/*
4672 	 * Is this page mapped at its natural color?
4673 	 * If we have all of memory mapped, then just convert PA to VA.
4674 	 */
4675 	const bool src_okcolor = src_va_offset == (src & arm_cache_prefer_mask);
4676 	const bool dst_okcolor = dst_va_offset == (dst & arm_cache_prefer_mask);
4677 	const vaddr_t vsrcp = src_okcolor
4678 	    ? KERNEL_BASE + (src - physical_start)
4679 	    : csrcp + src_va_offset;
4680 	const vaddr_t vdstp = KERNEL_BASE + (dst - physical_start);
4681 #else
4682 	const bool src_okcolor = false;
4683 	const bool dst_okcolor = false;
4684 	const vaddr_t vsrcp = csrcp + src_va_offset;
4685 	const vaddr_t vdstp = cdstp + dst_va_offset;
4686 #endif
4687 	pt_entry_t * const src_ptep = &csrc_pte[src_va_offset >> PGSHIFT];
4688 	pt_entry_t * const dst_ptep = &cdst_pte[dst_va_offset >> PGSHIFT];
4689 
4690 #ifdef DEBUG
4691 	if (!SLIST_EMPTY(&dst_md->pvh_list))
4692 		panic("pmap_copy_page: dst page has mappings");
4693 #endif
4694 
4695 #ifdef PMAP_CACHE_VIPT
4696 	KASSERT(arm_cache_prefer_mask == 0 || src_md->pvh_attrs & (PVF_COLORED|PVF_NC));
4697 #endif
4698 	KDASSERT((src & PGOFSET) == 0);
4699 	KDASSERT((dst & PGOFSET) == 0);
4700 
4701 	/*
4702 	 * Clean the source page.  Hold the source page's lock for
4703 	 * the duration of the copy so that no other mappings can
4704 	 * be created while we have a potentially aliased mapping.
4705 	 */
4706 #ifdef MULTIPROCESSOR
4707 	KASSERT(uvm_page_locked_p(src_pg));
4708 #endif
4709 #ifdef PMAP_CACHE_VIVT
4710 	(void) pmap_clean_page(SLIST_FIRST(&src_md->pvh_list), true);
4711 #endif
4712 
4713 	/*
4714 	 * Map the pages into the page hook points, copy them, and purge
4715 	 * the cache for the appropriate page. Invalidate the TLB
4716 	 * as required.
4717 	 */
4718 	if (!src_okcolor) {
4719 		*src_ptep = L2_S_PROTO
4720 		    | src
4721 #ifdef PMAP_CACHE_VIPT
4722 		    | ((src_md->pvh_attrs & PVF_NC) ? 0 : pte_l2_s_cache_mode)
4723 #endif
4724 #ifdef PMAP_CACHE_VIVT
4725 		    | pte_l2_s_cache_mode
4726 #endif
4727 		    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ);
4728 		PTE_SYNC(src_ptep);
4729 		cpu_tlb_flushD_SE(csrcp + src_va_offset);
4730 		cpu_cpwait();
4731 	}
4732 	if (!dst_okcolor) {
4733 		*dst_ptep = L2_S_PROTO | dst |
4734 		    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
4735 		PTE_SYNC(dst_ptep);
4736 		cpu_tlb_flushD_SE(cdstp + dst_va_offset);
4737 		cpu_cpwait();
4738 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS) && defined(PMAP_CACHE_VIPT)
4739 		/*
4740 		 * If we are direct-mapped and our color isn't ok, then before
4741 		 * we bcopy to the new page invalidate its contents from the
4742 		 * cache and reset its color to its natural color.
4743 		 */
4744 		cpu_dcache_inv_range(cdstp + dst_va_offset, PAGE_SIZE);
4745 		dst_md->pvh_attrs &= ~arm_cache_prefer_mask;
4746 		dst_md->pvh_attrs |= (dst & arm_cache_prefer_mask);
4747 #endif
4748 	}
4749 	bcopy_page(vsrcp, vdstp);
4750 #ifdef PMAP_CACHE_VIVT
4751 	cpu_dcache_inv_range(vsrcp, PAGE_SIZE);
4752 	cpu_dcache_wbinv_range(vdstp, PAGE_SIZE);
4753 #endif
4754 	/*
4755 	 * Unmap the pages.
4756 	 */
4757 	if (!src_okcolor) {
4758 		*src_ptep = 0;
4759 		PTE_SYNC(src_ptep);
4760 		cpu_tlb_flushD_SE(csrcp + src_va_offset);
4761 		cpu_cpwait();
4762 	}
4763 	if (!dst_okcolor) {
4764 		*dst_ptep = 0;
4765 		PTE_SYNC(dst_ptep);
4766 		cpu_tlb_flushD_SE(cdstp + dst_va_offset);
4767 		cpu_cpwait();
4768 	}
4769 #ifdef PMAP_CACHE_VIPT
4770 	/*
4771 	 * Now that the destination page is in the cache, mark it as colored.
4772 	 * If this was an exec page, discard it.
4773 	 */
4774 	if (!pmap_is_page_colored_p(dst_md)) {
4775 		PMAPCOUNT(vac_color_new);
4776 		dst_md->pvh_attrs |= PVF_COLORED;
4777 	}
4778 	if (PV_IS_EXEC_P(dst_md->pvh_attrs)) {
4779 		dst_md->pvh_attrs &= ~PVF_EXEC;
4780 		PMAPCOUNT(exec_discarded_copy);
4781 	}
4782 	dst_md->pvh_attrs |= PVF_DIRTY;
4783 #endif
4784 }
4785 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
4786 
4787 #if ARM_MMU_XSCALE == 1
4788 void
4789 pmap_copy_page_xscale(paddr_t src, paddr_t dst)
4790 {
4791 	struct vm_page *src_pg = PHYS_TO_VM_PAGE(src);
4792 	struct vm_page_md *src_md = VM_PAGE_TO_MD(src_pg);
4793 #ifdef DEBUG
4794 	struct vm_page_md *dst_md = VM_PAGE_TO_MD(PHYS_TO_VM_PAGE(dst));
4795 
4796 	if (!SLIST_EMPTY(&dst_md->pvh_list))
4797 		panic("pmap_copy_page: dst page has mappings");
4798 #endif
4799 
4800 	KDASSERT((src & PGOFSET) == 0);
4801 	KDASSERT((dst & PGOFSET) == 0);
4802 
4803 	/*
4804 	 * Clean the source page.  Hold the source page's lock for
4805 	 * the duration of the copy so that no other mappings can
4806 	 * be created while we have a potentially aliased mapping.
4807 	 */
4808 #ifdef MULTIPROCESSOR
4809 	KASSERT(uvm_page_locked_p(src_pg));
4810 #endif
4811 #ifdef PMAP_CACHE_VIVT
4812 	(void) pmap_clean_page(SLIST_FIRST(&src_md->pvh_list), true);
4813 #endif
4814 
4815 	/*
4816 	 * Map the pages into the page hook points, copy them, and purge
4817 	 * the cache for the appropriate page. Invalidate the TLB
4818 	 * as required.
4819 	 */
4820 	*csrc_pte = L2_S_PROTO | src |
4821 	    L2_S_PROT(PTE_KERNEL, VM_PROT_READ) |
4822 	    L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
4823 	PTE_SYNC(csrc_pte);
4824 	*cdst_pte = L2_S_PROTO | dst |
4825 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) |
4826 	    L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
4827 	PTE_SYNC(cdst_pte);
4828 	cpu_tlb_flushD_SE(csrcp);
4829 	cpu_tlb_flushD_SE(cdstp);
4830 	cpu_cpwait();
4831 	bcopy_page(csrcp, cdstp);
4832 	xscale_cache_clean_minidata();
4833 }
4834 #endif /* ARM_MMU_XSCALE == 1 */
4835 
4836 /*
4837  * void pmap_virtual_space(vaddr_t *start, vaddr_t *end)
4838  *
4839  * Return the start and end addresses of the kernel's virtual space.
4840  * These values are setup in pmap_bootstrap and are updated as pages
4841  * are allocated.
4842  */
4843 void
4844 pmap_virtual_space(vaddr_t *start, vaddr_t *end)
4845 {
4846 	*start = virtual_avail;
4847 	*end = virtual_end;
4848 }
4849 
4850 /*
4851  * Helper function for pmap_grow_l2_bucket()
4852  */
4853 static inline int
4854 pmap_grow_map(vaddr_t va, pt_entry_t cache_mode, paddr_t *pap)
4855 {
4856 	struct l2_bucket *l2b;
4857 	pt_entry_t *ptep;
4858 	paddr_t pa;
4859 
4860 	if (uvm.page_init_done == false) {
4861 #ifdef PMAP_STEAL_MEMORY
4862 		pv_addr_t pv;
4863 		pmap_boot_pagealloc(PAGE_SIZE,
4864 #ifdef PMAP_CACHE_VIPT
4865 		    arm_cache_prefer_mask,
4866 		    va & arm_cache_prefer_mask,
4867 #else
4868 		    0, 0,
4869 #endif
4870 		    &pv);
4871 		pa = pv.pv_pa;
4872 #else
4873 		if (uvm_page_physget(&pa) == false)
4874 			return (1);
4875 #endif	/* PMAP_STEAL_MEMORY */
4876 	} else {
4877 		struct vm_page *pg;
4878 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_USERESERVE);
4879 		if (pg == NULL)
4880 			return (1);
4881 		pa = VM_PAGE_TO_PHYS(pg);
4882 #ifdef PMAP_CACHE_VIPT
4883 #ifdef DIAGNOSTIC
4884 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
4885 #endif
4886 		/*
4887 		 * This new page must not have any mappings.  Enter it via
4888 		 * pmap_kenter_pa and let that routine do the hard work.
4889 		 */
4890 		KASSERT(SLIST_EMPTY(&md->pvh_list));
4891 		pmap_kenter_pa(va, pa,
4892 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
4893 #endif
4894 	}
4895 
4896 	if (pap)
4897 		*pap = pa;
4898 
4899 	PMAPCOUNT(pt_mappings);
4900 	l2b = pmap_get_l2_bucket(pmap_kernel(), va);
4901 	KDASSERT(l2b != NULL);
4902 
4903 	ptep = &l2b->l2b_kva[l2pte_index(va)];
4904 	*ptep = L2_S_PROTO | pa | cache_mode |
4905 	    L2_S_PROT(PTE_KERNEL, VM_PROT_READ | VM_PROT_WRITE);
4906 	PTE_SYNC(ptep);
4907 	memset((void *)va, 0, PAGE_SIZE);
4908 	return (0);
4909 }
4910 
4911 /*
4912  * This is the same as pmap_alloc_l2_bucket(), except that it is only
4913  * used by pmap_growkernel().
4914  */
4915 static inline struct l2_bucket *
4916 pmap_grow_l2_bucket(pmap_t pm, vaddr_t va)
4917 {
4918 	struct l2_dtable *l2;
4919 	struct l2_bucket *l2b;
4920 	u_short l1idx;
4921 	vaddr_t nva;
4922 
4923 	l1idx = L1_IDX(va);
4924 
4925 	if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
4926 		/*
4927 		 * No mapping at this address, as there is
4928 		 * no entry in the L1 table.
4929 		 * Need to allocate a new l2_dtable.
4930 		 */
4931 		nva = pmap_kernel_l2dtable_kva;
4932 		if ((nva & PGOFSET) == 0) {
4933 			/*
4934 			 * Need to allocate a backing page
4935 			 */
4936 			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
4937 				return (NULL);
4938 		}
4939 
4940 		l2 = (struct l2_dtable *)nva;
4941 		nva += sizeof(struct l2_dtable);
4942 
4943 		if ((nva & PGOFSET) < (pmap_kernel_l2dtable_kva & PGOFSET)) {
4944 			/*
4945 			 * The new l2_dtable straddles a page boundary.
4946 			 * Map in another page to cover it.
4947 			 */
4948 			if (pmap_grow_map(nva, pte_l2_s_cache_mode, NULL))
4949 				return (NULL);
4950 		}
4951 
4952 		pmap_kernel_l2dtable_kva = nva;
4953 
4954 		/*
4955 		 * Link it into the parent pmap
4956 		 */
4957 		pm->pm_l2[L2_IDX(l1idx)] = l2;
4958 	}
4959 
4960 	l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
4961 
4962 	/*
4963 	 * Fetch pointer to the L2 page table associated with the address.
4964 	 */
4965 	if (l2b->l2b_kva == NULL) {
4966 		pt_entry_t *ptep;
4967 
4968 		/*
4969 		 * No L2 page table has been allocated. Chances are, this
4970 		 * is because we just allocated the l2_dtable, above.
4971 		 */
4972 		nva = pmap_kernel_l2ptp_kva;
4973 		ptep = (pt_entry_t *)nva;
4974 		if ((nva & PGOFSET) == 0) {
4975 			/*
4976 			 * Need to allocate a backing page
4977 			 */
4978 			if (pmap_grow_map(nva, pte_l2_s_cache_mode_pt,
4979 			    &pmap_kernel_l2ptp_phys))
4980 				return (NULL);
4981 			PTE_SYNC_RANGE(ptep, PAGE_SIZE / sizeof(pt_entry_t));
4982 		}
4983 
4984 		l2->l2_occupancy++;
4985 		l2b->l2b_kva = ptep;
4986 		l2b->l2b_l1idx = l1idx;
4987 		l2b->l2b_phys = pmap_kernel_l2ptp_phys;
4988 
4989 		pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
4990 		pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
4991 	}
4992 
4993 	return (l2b);
4994 }
4995 
4996 vaddr_t
4997 pmap_growkernel(vaddr_t maxkvaddr)
4998 {
4999 	pmap_t kpm = pmap_kernel();
5000 	struct l1_ttable *l1;
5001 	struct l2_bucket *l2b;
5002 	pd_entry_t *pl1pd;
5003 	int s;
5004 
5005 	if (maxkvaddr <= pmap_curmaxkvaddr)
5006 		goto out;		/* we are OK */
5007 
5008 	NPDEBUG(PDB_GROWKERN,
5009 	    printf("pmap_growkernel: growing kernel from 0x%lx to 0x%lx\n",
5010 	    pmap_curmaxkvaddr, maxkvaddr));
5011 
5012 	KDASSERT(maxkvaddr <= virtual_end);
5013 
5014 	/*
5015 	 * whoops!   we need to add kernel PTPs
5016 	 */
5017 
5018 	s = splhigh();	/* to be safe */
5019 	mutex_enter(kpm->pm_lock);
5020 
5021 	/* Map 1MB at a time */
5022 	for (; pmap_curmaxkvaddr < maxkvaddr; pmap_curmaxkvaddr += L1_S_SIZE) {
5023 
5024 		l2b = pmap_grow_l2_bucket(kpm, pmap_curmaxkvaddr);
5025 		KDASSERT(l2b != NULL);
5026 
5027 		/* Distribute new L1 entry to all other L1s */
5028 		SLIST_FOREACH(l1, &l1_list, l1_link) {
5029 			pl1pd = &l1->l1_kva[L1_IDX(pmap_curmaxkvaddr)];
5030 			*pl1pd = l2b->l2b_phys | L1_C_DOM(PMAP_DOMAIN_KERNEL) |
5031 			    L1_C_PROTO;
5032 			PTE_SYNC(pl1pd);
5033 		}
5034 	}
5035 
5036 	/*
5037 	 * flush out the cache, expensive but growkernel will happen so
5038 	 * rarely
5039 	 */
5040 	cpu_dcache_wbinv_all();
5041 	cpu_tlb_flushD();
5042 	cpu_cpwait();
5043 
5044 	mutex_exit(kpm->pm_lock);
5045 	splx(s);
5046 
5047 out:
5048 	return (pmap_curmaxkvaddr);
5049 }
5050 
5051 /************************ Utility routines ****************************/
5052 
5053 #ifndef ARM_HAS_VBAR
5054 /*
5055  * vector_page_setprot:
5056  *
5057  *	Manipulate the protection of the vector page.
5058  */
5059 void
5060 vector_page_setprot(int prot)
5061 {
5062 	struct l2_bucket *l2b;
5063 	pt_entry_t *ptep;
5064 
5065 #if defined(CPU_ARMV7) || defined(CPU_ARM11)
5066 	/*
5067 	 * If we are using VBAR to use the vectors in the kernel, then it's
5068 	 * already mapped in the kernel text so no need to anything here.
5069 	 */
5070 	if (vector_page != ARM_VECTORS_LOW && vector_page != ARM_VECTORS_HIGH) {
5071 		KASSERT((armreg_pfr1_read() & ARM_PFR1_SEC_MASK) != 0);
5072 		return;
5073 	}
5074 #endif
5075 
5076 	l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
5077 	KDASSERT(l2b != NULL);
5078 
5079 	ptep = &l2b->l2b_kva[l2pte_index(vector_page)];
5080 
5081 	*ptep = (*ptep & ~L2_S_PROT_MASK) | L2_S_PROT(PTE_KERNEL, prot);
5082 	PTE_SYNC(ptep);
5083 	cpu_tlb_flushD_SE(vector_page);
5084 	cpu_cpwait();
5085 }
5086 #endif
5087 
5088 /*
5089  * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
5090  * Returns true if the mapping exists, else false.
5091  *
5092  * NOTE: This function is only used by a couple of arm-specific modules.
5093  * It is not safe to take any pmap locks here, since we could be right
5094  * in the middle of debugging the pmap anyway...
5095  *
5096  * It is possible for this routine to return false even though a valid
5097  * mapping does exist. This is because we don't lock, so the metadata
5098  * state may be inconsistent.
5099  *
5100  * NOTE: We can return a NULL *ptp in the case where the L1 pde is
5101  * a "section" mapping.
5102  */
5103 bool
5104 pmap_get_pde_pte(pmap_t pm, vaddr_t va, pd_entry_t **pdp, pt_entry_t **ptp)
5105 {
5106 	struct l2_dtable *l2;
5107 	pd_entry_t *pl1pd, l1pd;
5108 	pt_entry_t *ptep;
5109 	u_short l1idx;
5110 
5111 	if (pm->pm_l1 == NULL)
5112 		return false;
5113 
5114 	l1idx = L1_IDX(va);
5115 	*pdp = pl1pd = pmap_l1_kva(pm) + l1idx;
5116 	l1pd = *pl1pd;
5117 
5118 	if (l1pte_section_p(l1pd)) {
5119 		*ptp = NULL;
5120 		return true;
5121 	}
5122 
5123 	if (pm->pm_l2 == NULL)
5124 		return false;
5125 
5126 	l2 = pm->pm_l2[L2_IDX(l1idx)];
5127 
5128 	if (l2 == NULL ||
5129 	    (ptep = l2->l2_bucket[L2_BUCKET(l1idx)].l2b_kva) == NULL) {
5130 		return false;
5131 	}
5132 
5133 	*ptp = &ptep[l2pte_index(va)];
5134 	return true;
5135 }
5136 
5137 bool
5138 pmap_get_pde(pmap_t pm, vaddr_t va, pd_entry_t **pdp)
5139 {
5140 
5141 	if (pm->pm_l1 == NULL)
5142 		return false;
5143 
5144 	*pdp = pmap_l1_kva(pm) + L1_IDX(va);
5145 
5146 	return true;
5147 }
5148 
5149 /************************ Bootstrapping routines ****************************/
5150 
5151 static void
5152 pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
5153 {
5154 	int i;
5155 
5156 	l1->l1_kva = l1pt;
5157 	l1->l1_domain_use_count = 0;
5158 	l1->l1_domain_first = 0;
5159 
5160 	for (i = 0; i < PMAP_DOMAINS; i++)
5161 		l1->l1_domain_free[i] = i + 1;
5162 
5163 	/*
5164 	 * Copy the kernel's L1 entries to each new L1.
5165 	 */
5166 	if (pmap_initialized)
5167 		memcpy(l1pt, pmap_l1_kva(pmap_kernel()), L1_TABLE_SIZE);
5168 
5169 	if (pmap_extract(pmap_kernel(), (vaddr_t)l1pt,
5170 	    &l1->l1_physaddr) == false)
5171 		panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);
5172 
5173 	SLIST_INSERT_HEAD(&l1_list, l1, l1_link);
5174 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
5175 }
5176 
5177 /*
5178  * pmap_bootstrap() is called from the board-specific initarm() routine
5179  * once the kernel L1/L2 descriptors tables have been set up.
5180  *
5181  * This is a somewhat convoluted process since pmap bootstrap is, effectively,
5182  * spread over a number of disparate files/functions.
5183  *
5184  * We are passed the following parameters
5185  *  - kernel_l1pt
5186  *    This is a pointer to the base of the kernel's L1 translation table.
5187  *  - vstart
5188  *    1MB-aligned start of managed kernel virtual memory.
5189  *  - vend
5190  *    1MB-aligned end of managed kernel virtual memory.
5191  *
5192  * We use the first parameter to build the metadata (struct l1_ttable and
5193  * struct l2_dtable) necessary to track kernel mappings.
5194  */
5195 #define	PMAP_STATIC_L2_SIZE 16
5196 void
5197 pmap_bootstrap(vaddr_t vstart, vaddr_t vend)
5198 {
5199 	static struct l1_ttable static_l1;
5200 	static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
5201 	struct l1_ttable *l1 = &static_l1;
5202 	struct l2_dtable *l2;
5203 	struct l2_bucket *l2b;
5204 	pd_entry_t *l1pt = (pd_entry_t *) kernel_l1pt.pv_va;
5205 	pmap_t pm = pmap_kernel();
5206 	pd_entry_t pde;
5207 	pt_entry_t *ptep;
5208 	paddr_t pa;
5209 	vaddr_t va;
5210 	vsize_t size;
5211 	int nptes, l1idx, l2idx, l2next = 0;
5212 
5213 	/*
5214 	 * Initialise the kernel pmap object
5215 	 */
5216 	pm->pm_l1 = l1;
5217 	pm->pm_domain = PMAP_DOMAIN_KERNEL;
5218 	pm->pm_activated = true;
5219 	pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
5220 
5221 	mutex_init(&pm->pm_obj_lock, MUTEX_DEFAULT, IPL_NONE);
5222 	uvm_obj_init(&pm->pm_obj, NULL, false, 1);
5223 	uvm_obj_setlock(&pm->pm_obj, &pm->pm_obj_lock);
5224 
5225 	/*
5226 	 * Scan the L1 translation table created by initarm() and create
5227 	 * the required metadata for all valid mappings found in it.
5228 	 */
5229 	for (l1idx = 0; l1idx < (L1_TABLE_SIZE / sizeof(pd_entry_t)); l1idx++) {
5230 		pde = l1pt[l1idx];
5231 
5232 		/*
5233 		 * We're only interested in Coarse mappings.
5234 		 * pmap_extract() can deal with section mappings without
5235 		 * recourse to checking L2 metadata.
5236 		 */
5237 		if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
5238 			continue;
5239 
5240 		/*
5241 		 * Lookup the KVA of this L2 descriptor table
5242 		 */
5243 		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
5244 		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
5245 		if (ptep == NULL) {
5246 			panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
5247 			    (u_int)l1idx << L1_S_SHIFT, pa);
5248 		}
5249 
5250 		/*
5251 		 * Fetch the associated L2 metadata structure.
5252 		 * Allocate a new one if necessary.
5253 		 */
5254 		if ((l2 = pm->pm_l2[L2_IDX(l1idx)]) == NULL) {
5255 			if (l2next == PMAP_STATIC_L2_SIZE)
5256 				panic("pmap_bootstrap: out of static L2s");
5257 			pm->pm_l2[L2_IDX(l1idx)] = l2 = &static_l2[l2next++];
5258 		}
5259 
5260 		/*
5261 		 * One more L1 slot tracked...
5262 		 */
5263 		l2->l2_occupancy++;
5264 
5265 		/*
5266 		 * Fill in the details of the L2 descriptor in the
5267 		 * appropriate bucket.
5268 		 */
5269 		l2b = &l2->l2_bucket[L2_BUCKET(l1idx)];
5270 		l2b->l2b_kva = ptep;
5271 		l2b->l2b_phys = pa;
5272 		l2b->l2b_l1idx = l1idx;
5273 
5274 		/*
5275 		 * Establish an initial occupancy count for this descriptor
5276 		 */
5277 		for (l2idx = 0;
5278 		    l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
5279 		    l2idx++) {
5280 			if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV) {
5281 				l2b->l2b_occupancy++;
5282 			}
5283 		}
5284 
5285 		/*
5286 		 * Make sure the descriptor itself has the correct cache mode.
5287 		 * If not, fix it, but whine about the problem. Port-meisters
5288 		 * should consider this a clue to fix up their initarm()
5289 		 * function. :)
5290 		 */
5291 		if (pmap_set_pt_cache_mode(l1pt, (vaddr_t)ptep)) {
5292 			printf("pmap_bootstrap: WARNING! wrong cache mode for "
5293 			    "L2 pte @ %p\n", ptep);
5294 		}
5295 	}
5296 
5297 	/*
5298 	 * Ensure the primary (kernel) L1 has the correct cache mode for
5299 	 * a page table. Bitch if it is not correctly set.
5300 	 */
5301 	for (va = (vaddr_t)l1pt;
5302 	    va < ((vaddr_t)l1pt + L1_TABLE_SIZE); va += PAGE_SIZE) {
5303 		if (pmap_set_pt_cache_mode(l1pt, va))
5304 			printf("pmap_bootstrap: WARNING! wrong cache mode for "
5305 			    "primary L1 @ 0x%lx\n", va);
5306 	}
5307 
5308 	cpu_dcache_wbinv_all();
5309 	cpu_tlb_flushID();
5310 	cpu_cpwait();
5311 
5312 	/*
5313 	 * now we allocate the "special" VAs which are used for tmp mappings
5314 	 * by the pmap (and other modules).  we allocate the VAs by advancing
5315 	 * virtual_avail (note that there are no pages mapped at these VAs).
5316 	 *
5317 	 * Managed KVM space start from wherever initarm() tells us.
5318 	 */
5319 	virtual_avail = vstart;
5320 	virtual_end = vend;
5321 
5322 #ifdef PMAP_CACHE_VIPT
5323 	/*
5324 	 * If we have a VIPT cache, we need one page/pte per possible alias
5325 	 * page so we won't violate cache aliasing rules.
5326 	 */
5327 	virtual_avail = (virtual_avail + arm_cache_prefer_mask) & ~arm_cache_prefer_mask;
5328 	nptes = (arm_cache_prefer_mask >> PGSHIFT) + 1;
5329 #else
5330 	nptes = 1;
5331 #endif
5332 	pmap_alloc_specials(&virtual_avail, nptes, &csrcp, &csrc_pte);
5333 	pmap_set_pt_cache_mode(l1pt, (vaddr_t)csrc_pte);
5334 	pmap_alloc_specials(&virtual_avail, nptes, &cdstp, &cdst_pte);
5335 	pmap_set_pt_cache_mode(l1pt, (vaddr_t)cdst_pte);
5336 	pmap_alloc_specials(&virtual_avail, nptes, &memhook, NULL);
5337 	pmap_alloc_specials(&virtual_avail, round_page(MSGBUFSIZE) / PAGE_SIZE,
5338 	    (void *)&msgbufaddr, NULL);
5339 
5340 	/*
5341 	 * Allocate a range of kernel virtual address space to be used
5342 	 * for L2 descriptor tables and metadata allocation in
5343 	 * pmap_growkernel().
5344 	 */
5345 	size = ((virtual_end - pmap_curmaxkvaddr) + L1_S_OFFSET) / L1_S_SIZE;
5346 	pmap_alloc_specials(&virtual_avail,
5347 	    round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
5348 	    &pmap_kernel_l2ptp_kva, NULL);
5349 
5350 	size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
5351 	pmap_alloc_specials(&virtual_avail,
5352 	    round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
5353 	    &pmap_kernel_l2dtable_kva, NULL);
5354 
5355 	/*
5356 	 * init the static-global locks and global pmap list.
5357 	 */
5358 	mutex_init(&l1_lru_lock, MUTEX_DEFAULT, IPL_VM);
5359 
5360 	/*
5361 	 * We can now initialise the first L1's metadata.
5362 	 */
5363 	SLIST_INIT(&l1_list);
5364 	TAILQ_INIT(&l1_lru_list);
5365 	pmap_init_l1(l1, l1pt);
5366 
5367 #ifndef ARM_HAS_VBAR
5368 	/* Set up vector page L1 details, if necessary */
5369 	if (vector_page < KERNEL_BASE) {
5370 		pm->pm_pl1vec = pmap_l1_kva(pm) + L1_IDX(vector_page);
5371 		l2b = pmap_get_l2_bucket(pm, vector_page);
5372 		KDASSERT(l2b != NULL);
5373 		pm->pm_l1vec = l2b->l2b_phys | L1_C_PROTO |
5374 		    L1_C_DOM(pmap_domain(pm));
5375 	} else
5376 		pm->pm_pl1vec = NULL;
5377 #endif
5378 
5379 	/*
5380 	 * Initialize the pmap cache
5381 	 */
5382 	pool_cache_bootstrap(&pmap_cache, sizeof(struct pmap), 0, 0, 0,
5383 	    "pmappl", NULL, IPL_NONE, pmap_pmap_ctor, NULL, NULL);
5384 	LIST_INIT(&pmap_pmaps);
5385 	LIST_INSERT_HEAD(&pmap_pmaps, pm, pm_list);
5386 
5387 	/*
5388 	 * Initialize the pv pool.
5389 	 */
5390 	pool_init(&pmap_pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pvepl",
5391 	    &pmap_bootstrap_pv_allocator, IPL_NONE);
5392 
5393 	/*
5394 	 * Initialize the L2 dtable pool and cache.
5395 	 */
5396 	pool_cache_bootstrap(&pmap_l2dtable_cache, sizeof(struct l2_dtable), 0,
5397 	    0, 0, "l2dtblpl", NULL, IPL_NONE, pmap_l2dtable_ctor, NULL, NULL);
5398 
5399 	/*
5400 	 * Initialise the L2 descriptor table pool and cache
5401 	 */
5402 	pool_cache_bootstrap(&pmap_l2ptp_cache, L2_TABLE_SIZE_REAL, 0,
5403 	    L2_TABLE_SIZE_REAL, 0, "l2ptppl", NULL, IPL_NONE,
5404 	    pmap_l2ptp_ctor, NULL, NULL);
5405 
5406 	cpu_dcache_wbinv_all();
5407 }
5408 
5409 static int
5410 pmap_set_pt_cache_mode(pd_entry_t *kl1, vaddr_t va)
5411 {
5412 	pd_entry_t *pdep, pde;
5413 	pt_entry_t *ptep, pte;
5414 	vaddr_t pa;
5415 	int rv = 0;
5416 
5417 	/*
5418 	 * Make sure the descriptor itself has the correct cache mode
5419 	 */
5420 	pdep = &kl1[L1_IDX(va)];
5421 	pde = *pdep;
5422 
5423 	if (l1pte_section_p(pde)) {
5424 		__CTASSERT((L1_S_CACHE_MASK & L1_S_V6_SUPER) == 0);
5425 		if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
5426 			*pdep = (pde & ~L1_S_CACHE_MASK) |
5427 			    pte_l1_s_cache_mode_pt;
5428 			PTE_SYNC(pdep);
5429 			cpu_dcache_wbinv_range((vaddr_t)pdep, sizeof(*pdep));
5430 			rv = 1;
5431 		}
5432 	} else {
5433 		pa = (paddr_t)(pde & L1_C_ADDR_MASK);
5434 		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
5435 		if (ptep == NULL)
5436 			panic("pmap_bootstrap: No L2 for L2 @ va %p\n", ptep);
5437 
5438 		ptep = &ptep[l2pte_index(va)];
5439 		pte = *ptep;
5440 		if ((pte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
5441 			*ptep = (pte & ~L2_S_CACHE_MASK) |
5442 			    pte_l2_s_cache_mode_pt;
5443 			PTE_SYNC(ptep);
5444 			cpu_dcache_wbinv_range((vaddr_t)ptep, sizeof(*ptep));
5445 			rv = 1;
5446 		}
5447 	}
5448 
5449 	return (rv);
5450 }
5451 
5452 static void
5453 pmap_alloc_specials(vaddr_t *availp, int pages, vaddr_t *vap, pt_entry_t **ptep)
5454 {
5455 	vaddr_t va = *availp;
5456 	struct l2_bucket *l2b;
5457 
5458 	if (ptep) {
5459 		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
5460 		if (l2b == NULL)
5461 			panic("pmap_alloc_specials: no l2b for 0x%lx", va);
5462 
5463 		if (ptep)
5464 			*ptep = &l2b->l2b_kva[l2pte_index(va)];
5465 	}
5466 
5467 	*vap = va;
5468 	*availp = va + (PAGE_SIZE * pages);
5469 }
5470 
5471 void
5472 pmap_init(void)
5473 {
5474 
5475 	/*
5476 	 * Set the available memory vars - These do not map to real memory
5477 	 * addresses and cannot as the physical memory is fragmented.
5478 	 * They are used by ps for %mem calculations.
5479 	 * One could argue whether this should be the entire memory or just
5480 	 * the memory that is useable in a user process.
5481 	 */
5482 	avail_start = ptoa(VM_PHYSMEM_PTR(0)->start);
5483 	avail_end = ptoa(VM_PHYSMEM_PTR(vm_nphysseg - 1)->end);
5484 
5485 	/*
5486 	 * Now we need to free enough pv_entry structures to allow us to get
5487 	 * the kmem_map/kmem_object allocated and inited (done after this
5488 	 * function is finished).  to do this we allocate one bootstrap page out
5489 	 * of kernel_map and use it to provide an initial pool of pv_entry
5490 	 * structures.   we never free this page.
5491 	 */
5492 	pool_setlowat(&pmap_pv_pool,
5493 	    (PAGE_SIZE / sizeof(struct pv_entry)) * 2);
5494 
5495 	mutex_init(&memlock, MUTEX_DEFAULT, IPL_NONE);
5496 	zeropage = (void *)uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
5497 	    UVM_KMF_WIRED|UVM_KMF_ZERO);
5498 
5499 	pmap_initialized = true;
5500 }
5501 
5502 static vaddr_t last_bootstrap_page = 0;
5503 static void *free_bootstrap_pages = NULL;
5504 
5505 static void *
5506 pmap_bootstrap_pv_page_alloc(struct pool *pp, int flags)
5507 {
5508 	extern void *pool_page_alloc(struct pool *, int);
5509 	vaddr_t new_page;
5510 	void *rv;
5511 
5512 	if (pmap_initialized)
5513 		return (pool_page_alloc(pp, flags));
5514 
5515 	if (free_bootstrap_pages) {
5516 		rv = free_bootstrap_pages;
5517 		free_bootstrap_pages = *((void **)rv);
5518 		return (rv);
5519 	}
5520 
5521 	new_page = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
5522 	    UVM_KMF_WIRED | ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT));
5523 
5524 	KASSERT(new_page > last_bootstrap_page);
5525 	last_bootstrap_page = new_page;
5526 	return ((void *)new_page);
5527 }
5528 
5529 static void
5530 pmap_bootstrap_pv_page_free(struct pool *pp, void *v)
5531 {
5532 	extern void pool_page_free(struct pool *, void *);
5533 
5534 	if ((vaddr_t)v <= last_bootstrap_page) {
5535 		*((void **)v) = free_bootstrap_pages;
5536 		free_bootstrap_pages = v;
5537 		return;
5538 	}
5539 
5540 	if (pmap_initialized) {
5541 		pool_page_free(pp, v);
5542 		return;
5543 	}
5544 }
5545 
5546 /*
5547  * pmap_postinit()
5548  *
5549  * This routine is called after the vm and kmem subsystems have been
5550  * initialised. This allows the pmap code to perform any initialisation
5551  * that can only be done one the memory allocation is in place.
5552  */
5553 void
5554 pmap_postinit(void)
5555 {
5556 	extern paddr_t physical_start, physical_end;
5557 	struct l2_bucket *l2b;
5558 	struct l1_ttable *l1;
5559 	struct pglist plist;
5560 	struct vm_page *m;
5561 	pd_entry_t *pl1pt;
5562 	pt_entry_t *ptep, pte;
5563 	vaddr_t va, eva;
5564 	u_int loop, needed;
5565 	int error;
5566 
5567 	pool_cache_setlowat(&pmap_l2ptp_cache,
5568 	    (PAGE_SIZE / L2_TABLE_SIZE_REAL) * 4);
5569 	pool_cache_setlowat(&pmap_l2dtable_cache,
5570 	    (PAGE_SIZE / sizeof(struct l2_dtable)) * 2);
5571 
5572 	needed = (maxproc / PMAP_DOMAINS) + ((maxproc % PMAP_DOMAINS) ? 1 : 0);
5573 	needed -= 1;
5574 
5575 	l1 = kmem_alloc(sizeof(*l1) * needed, KM_SLEEP);
5576 
5577 	for (loop = 0; loop < needed; loop++, l1++) {
5578 		/* Allocate a L1 page table */
5579 		va = uvm_km_alloc(kernel_map, L1_TABLE_SIZE, 0, UVM_KMF_VAONLY);
5580 		if (va == 0)
5581 			panic("Cannot allocate L1 KVM");
5582 
5583 		error = uvm_pglistalloc(L1_TABLE_SIZE, physical_start,
5584 		    physical_end, L1_TABLE_SIZE, 0, &plist, 1, 1);
5585 		if (error)
5586 			panic("Cannot allocate L1 physical pages");
5587 
5588 		m = TAILQ_FIRST(&plist);
5589 		eva = va + L1_TABLE_SIZE;
5590 		pl1pt = (pd_entry_t *)va;
5591 
5592 		while (m && va < eva) {
5593 			paddr_t pa = VM_PAGE_TO_PHYS(m);
5594 
5595 			pmap_kenter_pa(va, pa,
5596 			    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE);
5597 
5598 			/*
5599 			 * Make sure the L1 descriptor table is mapped
5600 			 * with the cache-mode set to write-through.
5601 			 */
5602 			l2b = pmap_get_l2_bucket(pmap_kernel(), va);
5603 			KDASSERT(l2b != NULL);
5604 			ptep = &l2b->l2b_kva[l2pte_index(va)];
5605 			pte = *ptep;
5606 			pte = (pte & ~L2_S_CACHE_MASK) | pte_l2_s_cache_mode_pt;
5607 			*ptep = pte;
5608 			PTE_SYNC(ptep);
5609 			cpu_tlb_flushD_SE(va);
5610 
5611 			va += PAGE_SIZE;
5612 			m = TAILQ_NEXT(m, pageq.queue);
5613 		}
5614 
5615 #ifdef DIAGNOSTIC
5616 		if (m)
5617 			panic("pmap_alloc_l1pt: pglist not empty");
5618 #endif	/* DIAGNOSTIC */
5619 
5620 		pmap_init_l1(l1, pl1pt);
5621 	}
5622 
5623 #ifdef DEBUG
5624 	printf("pmap_postinit: Allocated %d static L1 descriptor tables\n",
5625 	    needed);
5626 #endif
5627 }
5628 
5629 /*
5630  * Note that the following routines are used by board-specific initialisation
5631  * code to configure the initial kernel page tables.
5632  *
5633  * If ARM32_NEW_VM_LAYOUT is *not* defined, they operate on the assumption that
5634  * L2 page-table pages are 4KB in size and use 4 L1 slots. This mimics the
5635  * behaviour of the old pmap, and provides an easy migration path for
5636  * initial bring-up of the new pmap on existing ports. Fortunately,
5637  * pmap_bootstrap() compensates for this hackery. This is only a stop-gap and
5638  * will be deprecated.
5639  *
5640  * If ARM32_NEW_VM_LAYOUT *is* defined, these functions deal with 1KB L2 page
5641  * tables.
5642  */
5643 
5644 /*
5645  * This list exists for the benefit of pmap_map_chunk().  It keeps track
5646  * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
5647  * find them as necessary.
5648  *
5649  * Note that the data on this list MUST remain valid after initarm() returns,
5650  * as pmap_bootstrap() uses it to contruct L2 table metadata.
5651  */
5652 SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);
5653 
5654 static vaddr_t
5655 kernel_pt_lookup(paddr_t pa)
5656 {
5657 	pv_addr_t *pv;
5658 
5659 	SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
5660 #ifndef ARM32_NEW_VM_LAYOUT
5661 		if (pv->pv_pa == (pa & ~PGOFSET))
5662 			return (pv->pv_va | (pa & PGOFSET));
5663 #else
5664 		if (pv->pv_pa == pa)
5665 			return (pv->pv_va);
5666 #endif
5667 	}
5668 	return (0);
5669 }
5670 
5671 /*
5672  * pmap_map_section:
5673  *
5674  *	Create a single section mapping.
5675  */
5676 void
5677 pmap_map_section(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
5678 {
5679 	pd_entry_t *pde = (pd_entry_t *) l1pt;
5680 	pd_entry_t fl;
5681 
5682 	KASSERT(((va | pa) & L1_S_OFFSET) == 0);
5683 
5684 	switch (cache) {
5685 	case PTE_NOCACHE:
5686 	default:
5687 		fl = 0;
5688 		break;
5689 
5690 	case PTE_CACHE:
5691 		fl = pte_l1_s_cache_mode;
5692 		break;
5693 
5694 	case PTE_PAGETABLE:
5695 		fl = pte_l1_s_cache_mode_pt;
5696 		break;
5697 	}
5698 
5699 	pde[L1_IDX(va)] = L1_S_PROTO | pa |
5700 	    L1_S_PROT(PTE_KERNEL, prot) | fl | L1_S_DOM(PMAP_DOMAIN_KERNEL);
5701 	PTE_SYNC(&pde[L1_IDX(va)]);
5702 }
5703 
5704 /*
5705  * pmap_map_entry:
5706  *
5707  *	Create a single page mapping.
5708  */
5709 void
5710 pmap_map_entry(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
5711 {
5712 	pd_entry_t *pde = (pd_entry_t *) l1pt;
5713 	pt_entry_t npte;
5714 	pt_entry_t *ptep;
5715 
5716 	KASSERT(((va | pa) & PGOFSET) == 0);
5717 
5718 	switch (cache) {
5719 	case PTE_NOCACHE:
5720 	default:
5721 		npte = 0;
5722 		break;
5723 
5724 	case PTE_CACHE:
5725 		npte = pte_l2_s_cache_mode;
5726 		break;
5727 
5728 	case PTE_PAGETABLE:
5729 		npte = pte_l2_s_cache_mode_pt;
5730 		break;
5731 	}
5732 
5733 	if ((pde[L1_IDX(va)] & L1_TYPE_MASK) != L1_TYPE_C)
5734 		panic("pmap_map_entry: no L2 table for VA 0x%08lx", va);
5735 
5736 #ifndef ARM32_NEW_VM_LAYOUT
5737 	ptep = (pt_entry_t *)
5738 	    kernel_pt_lookup(pde[L1_IDX(va)] & L2_S_FRAME);
5739 #else
5740 	ptep = (pt_entry_t *) kernel_pt_lookup(pde[L1_IDX(va)] & L1_C_ADDR_MASK);
5741 #endif
5742 	if (ptep == NULL)
5743 		panic("pmap_map_entry: can't find L2 table for VA 0x%08lx", va);
5744 
5745 	npte |= L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot);
5746 #ifndef ARM32_NEW_VM_LAYOUT
5747 	ptep += (va >> PGSHIFT) & 0x3ff;
5748 #else
5749 	ptep += l2pte_index(va);
5750 #endif
5751 	l2pte_set(ptep, npte, 0);
5752 	PTE_SYNC(ptep);
5753 }
5754 
5755 /*
5756  * pmap_link_l2pt:
5757  *
5758  *	Link the L2 page table specified by "l2pv" into the L1
5759  *	page table at the slot for "va".
5760  */
5761 void
5762 pmap_link_l2pt(vaddr_t l1pt, vaddr_t va, pv_addr_t *l2pv)
5763 {
5764 	pd_entry_t *pde = (pd_entry_t *) l1pt, proto;
5765 	u_int slot = L1_IDX(va);
5766 
5767 #ifndef ARM32_NEW_VM_LAYOUT
5768 	KASSERT((va & ((L1_S_SIZE * 4) - 1)) == 0);
5769 	KASSERT((l2pv->pv_pa & PGOFSET) == 0);
5770 #endif
5771 
5772 	proto = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO;
5773 
5774 	pde[slot + 0] = proto | (l2pv->pv_pa + 0x000);
5775 #ifdef ARM32_NEW_VM_LAYOUT
5776 	PTE_SYNC(&pde[slot]);
5777 #else
5778 	for (u_int off = 0, i = 0; off < PAGE_SIZE; off += L2_T_SIZE, i++) {
5779 		pde[slot + i] = proto | (l2pv->pv_pa + off);
5780 	}
5781 	PTE_SYNC_RANGE(&pde[slot + 0], PAGE_SIZE / L2_T_SIZE);
5782 #endif
5783 
5784 	SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
5785 }
5786 
5787 /*
5788  * pmap_map_chunk:
5789  *
5790  *	Map a chunk of memory using the most efficient mappings
5791  *	possible (section, large page, small page) into the
5792  *	provided L1 and L2 tables at the specified virtual address.
5793  */
5794 vsize_t
5795 pmap_map_chunk(vaddr_t l1pt, vaddr_t va, paddr_t pa, vsize_t size,
5796     int prot, int cache)
5797 {
5798 	pd_entry_t *pdep = (pd_entry_t *) l1pt;
5799 	pt_entry_t *pte, f1, f2s, f2l;
5800 	vsize_t resid;
5801 	int i;
5802 
5803 	resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
5804 
5805 	if (l1pt == 0)
5806 		panic("pmap_map_chunk: no L1 table provided");
5807 
5808 #ifdef VERBOSE_INIT_ARM
5809 	printf("pmap_map_chunk: pa=0x%lx va=0x%lx size=0x%lx resid=0x%lx "
5810 	    "prot=0x%x cache=%d\n", pa, va, size, resid, prot, cache);
5811 #endif
5812 
5813 	switch (cache) {
5814 	case PTE_NOCACHE:
5815 	default:
5816 		f1 = 0;
5817 		f2l = 0;
5818 		f2s = 0;
5819 		break;
5820 
5821 	case PTE_CACHE:
5822 		f1 = pte_l1_s_cache_mode;
5823 		f2l = pte_l2_l_cache_mode;
5824 		f2s = pte_l2_s_cache_mode;
5825 		break;
5826 
5827 	case PTE_PAGETABLE:
5828 		f1 = pte_l1_s_cache_mode_pt;
5829 		f2l = pte_l2_l_cache_mode_pt;
5830 		f2s = pte_l2_s_cache_mode_pt;
5831 		break;
5832 	}
5833 
5834 	size = resid;
5835 
5836 	while (resid > 0) {
5837 		size_t l1idx = L1_IDX(va);
5838 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
5839 		/* See if we can use a supersection mapping. */
5840 		if (L1_SS_PROTO && L1_SS_MAPPABLE_P(va, pa, resid)) {
5841 			/* Supersection are always domain 0 */
5842 			pd_entry_t pde = L1_SS_PROTO | pa |
5843 			    L1_S_PROT(PTE_KERNEL, prot) | f1;
5844 #ifdef VERBOSE_INIT_ARM
5845 			printf("sS");
5846 #endif
5847 			for (size_t s = l1idx,
5848 			     e = s + L1_SS_SIZE / L1_S_SIZE;
5849 			     s < e;
5850 			     s++) {
5851 				pdep[s] = pde;
5852 				PTE_SYNC(&pdep[s]);
5853 			}
5854 			va += L1_SS_SIZE;
5855 			pa += L1_SS_SIZE;
5856 			resid -= L1_SS_SIZE;
5857 			continue;
5858 		}
5859 #endif
5860 		/* See if we can use a section mapping. */
5861 		if (L1_S_MAPPABLE_P(va, pa, resid)) {
5862 #ifdef VERBOSE_INIT_ARM
5863 			printf("S");
5864 #endif
5865 			pdep[l1idx] = L1_S_PROTO | pa |
5866 			    L1_S_PROT(PTE_KERNEL, prot) | f1 |
5867 			    L1_S_DOM(PMAP_DOMAIN_KERNEL);
5868 			PTE_SYNC(&pdep[l1idx]);
5869 			va += L1_S_SIZE;
5870 			pa += L1_S_SIZE;
5871 			resid -= L1_S_SIZE;
5872 			continue;
5873 		}
5874 
5875 		/*
5876 		 * Ok, we're going to use an L2 table.  Make sure
5877 		 * one is actually in the corresponding L1 slot
5878 		 * for the current VA.
5879 		 */
5880 		if ((pdep[l1idx] & L1_TYPE_MASK) != L1_TYPE_C)
5881 			panic("pmap_map_chunk: no L2 table for VA 0x%08lx", va);
5882 
5883 #ifndef ARM32_NEW_VM_LAYOUT
5884 		pte = (pt_entry_t *)
5885 		    kernel_pt_lookup(pdep[l1idx] & L2_S_FRAME);
5886 #else
5887 		pte = (pt_entry_t *) kernel_pt_lookup(
5888 		    pdep[l1idx] & L1_C_ADDR_MASK);
5889 #endif
5890 		if (pte == NULL)
5891 			panic("pmap_map_chunk: can't find L2 table for VA"
5892 			    "0x%08lx", va);
5893 
5894 		/* See if we can use a L2 large page mapping. */
5895 		if (L2_L_MAPPABLE_P(va, pa, resid)) {
5896 #ifdef VERBOSE_INIT_ARM
5897 			printf("L");
5898 #endif
5899 			for (i = 0; i < 16; i++) {
5900 #ifndef ARM32_NEW_VM_LAYOUT
5901 				pte[((va >> PGSHIFT) & 0x3f0) + i] =
5902 				    L2_L_PROTO | pa |
5903 				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
5904 				PTE_SYNC(&pte[((va >> PGSHIFT) & 0x3f0) + i]);
5905 #else
5906 				pte[l2pte_index(va) + i] =
5907 				    L2_L_PROTO | pa |
5908 				    L2_L_PROT(PTE_KERNEL, prot) | f2l;
5909 				PTE_SYNC(&pte[l2pte_index(va) + i]);
5910 #endif
5911 			}
5912 			va += L2_L_SIZE;
5913 			pa += L2_L_SIZE;
5914 			resid -= L2_L_SIZE;
5915 			continue;
5916 		}
5917 
5918 		/* Use a small page mapping. */
5919 #ifdef VERBOSE_INIT_ARM
5920 		printf("P");
5921 #endif
5922 		pt_entry_t npte =
5923 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot) | f2s;
5924 #ifndef ARM32_NEW_VM_LAYOUT
5925 		pt_entry_t *ptep = &pte[(va >> PGSHIFT) & 0x3ff];
5926 #else
5927 		pt_entry_t *ptep = &pte[l2pte_index(va)];
5928 #endif
5929 		l2pte_set(ptep, npte, 0);
5930 		PTE_SYNC(ptep);
5931 		va += PAGE_SIZE;
5932 		pa += PAGE_SIZE;
5933 		resid -= PAGE_SIZE;
5934 	}
5935 #ifdef VERBOSE_INIT_ARM
5936 	printf("\n");
5937 #endif
5938 	return (size);
5939 }
5940 
5941 /********************** Static device map routines ***************************/
5942 
5943 static const struct pmap_devmap *pmap_devmap_table;
5944 
5945 /*
5946  * Register the devmap table.  This is provided in case early console
5947  * initialization needs to register mappings created by bootstrap code
5948  * before pmap_devmap_bootstrap() is called.
5949  */
5950 void
5951 pmap_devmap_register(const struct pmap_devmap *table)
5952 {
5953 
5954 	pmap_devmap_table = table;
5955 }
5956 
5957 /*
5958  * Map all of the static regions in the devmap table, and remember
5959  * the devmap table so other parts of the kernel can look up entries
5960  * later.
5961  */
5962 void
5963 pmap_devmap_bootstrap(vaddr_t l1pt, const struct pmap_devmap *table)
5964 {
5965 	int i;
5966 
5967 	pmap_devmap_table = table;
5968 
5969 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
5970 #ifdef VERBOSE_INIT_ARM
5971 		printf("devmap: %08lx -> %08lx @ %08lx\n",
5972 		    pmap_devmap_table[i].pd_pa,
5973 		    pmap_devmap_table[i].pd_pa +
5974 			pmap_devmap_table[i].pd_size - 1,
5975 		    pmap_devmap_table[i].pd_va);
5976 #endif
5977 		pmap_map_chunk(l1pt, pmap_devmap_table[i].pd_va,
5978 		    pmap_devmap_table[i].pd_pa,
5979 		    pmap_devmap_table[i].pd_size,
5980 		    pmap_devmap_table[i].pd_prot,
5981 		    pmap_devmap_table[i].pd_cache);
5982 	}
5983 }
5984 
5985 const struct pmap_devmap *
5986 pmap_devmap_find_pa(paddr_t pa, psize_t size)
5987 {
5988 	uint64_t endpa;
5989 	int i;
5990 
5991 	if (pmap_devmap_table == NULL)
5992 		return (NULL);
5993 
5994 	endpa = (uint64_t)pa + (uint64_t)(size - 1);
5995 
5996 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
5997 		if (pa >= pmap_devmap_table[i].pd_pa &&
5998 		    endpa <= (uint64_t)pmap_devmap_table[i].pd_pa +
5999 			     (uint64_t)(pmap_devmap_table[i].pd_size - 1))
6000 			return (&pmap_devmap_table[i]);
6001 	}
6002 
6003 	return (NULL);
6004 }
6005 
6006 const struct pmap_devmap *
6007 pmap_devmap_find_va(vaddr_t va, vsize_t size)
6008 {
6009 	int i;
6010 
6011 	if (pmap_devmap_table == NULL)
6012 		return (NULL);
6013 
6014 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
6015 		if (va >= pmap_devmap_table[i].pd_va &&
6016 		    va + size - 1 <= pmap_devmap_table[i].pd_va +
6017 				     pmap_devmap_table[i].pd_size - 1)
6018 			return (&pmap_devmap_table[i]);
6019 	}
6020 
6021 	return (NULL);
6022 }
6023 
6024 /********************** PTE initialization routines **************************/
6025 
6026 /*
6027  * These routines are called when the CPU type is identified to set up
6028  * the PTE prototypes, cache modes, etc.
6029  *
6030  * The variables are always here, just in case modules need to reference
6031  * them (though, they shouldn't).
6032  */
6033 
6034 pt_entry_t	pte_l1_s_cache_mode;
6035 pt_entry_t	pte_l1_s_wc_mode;
6036 pt_entry_t	pte_l1_s_cache_mode_pt;
6037 pt_entry_t	pte_l1_s_cache_mask;
6038 
6039 pt_entry_t	pte_l2_l_cache_mode;
6040 pt_entry_t	pte_l2_l_wc_mode;
6041 pt_entry_t	pte_l2_l_cache_mode_pt;
6042 pt_entry_t	pte_l2_l_cache_mask;
6043 
6044 pt_entry_t	pte_l2_s_cache_mode;
6045 pt_entry_t	pte_l2_s_wc_mode;
6046 pt_entry_t	pte_l2_s_cache_mode_pt;
6047 pt_entry_t	pte_l2_s_cache_mask;
6048 
6049 pt_entry_t	pte_l1_s_prot_u;
6050 pt_entry_t	pte_l1_s_prot_w;
6051 pt_entry_t	pte_l1_s_prot_ro;
6052 pt_entry_t	pte_l1_s_prot_mask;
6053 
6054 pt_entry_t	pte_l2_s_prot_u;
6055 pt_entry_t	pte_l2_s_prot_w;
6056 pt_entry_t	pte_l2_s_prot_ro;
6057 pt_entry_t	pte_l2_s_prot_mask;
6058 
6059 pt_entry_t	pte_l2_l_prot_u;
6060 pt_entry_t	pte_l2_l_prot_w;
6061 pt_entry_t	pte_l2_l_prot_ro;
6062 pt_entry_t	pte_l2_l_prot_mask;
6063 
6064 pt_entry_t	pte_l1_ss_proto;
6065 pt_entry_t	pte_l1_s_proto;
6066 pt_entry_t	pte_l1_c_proto;
6067 pt_entry_t	pte_l2_s_proto;
6068 
6069 void		(*pmap_copy_page_func)(paddr_t, paddr_t);
6070 void		(*pmap_zero_page_func)(paddr_t);
6071 
6072 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
6073 void
6074 pmap_pte_init_generic(void)
6075 {
6076 
6077 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
6078 	pte_l1_s_wc_mode = L1_S_B;
6079 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_generic;
6080 
6081 	pte_l2_l_cache_mode = L2_B|L2_C;
6082 	pte_l2_l_wc_mode = L2_B;
6083 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_generic;
6084 
6085 	pte_l2_s_cache_mode = L2_B|L2_C;
6086 	pte_l2_s_wc_mode = L2_B;
6087 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_generic;
6088 
6089 	/*
6090 	 * If we have a write-through cache, set B and C.  If
6091 	 * we have a write-back cache, then we assume setting
6092 	 * only C will make those pages write-through (except for those
6093 	 * Cortex CPUs which can read the L1 caches).
6094 	 */
6095 	if (cpufuncs.cf_dcache_wb_range == (void *) cpufunc_nullop
6096 #if ARM_MMU_V7 > 0
6097 	    || CPU_ID_CORTEX_P(curcpu()->ci_arm_cpuid)
6098 #endif
6099 #if ARM_MMU_V6 > 0
6100 	    || CPU_ID_ARM11_P(curcpu()->ci_arm_cpuid) /* arm116 errata 399234 */
6101 #endif
6102 	    || false) {
6103 		pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
6104 		pte_l2_l_cache_mode_pt = L2_B|L2_C;
6105 		pte_l2_s_cache_mode_pt = L2_B|L2_C;
6106 	} else {
6107 		pte_l1_s_cache_mode_pt = L1_S_C;	/* write through */
6108 		pte_l2_l_cache_mode_pt = L2_C;		/* write through */
6109 		pte_l2_s_cache_mode_pt = L2_C;		/* write through */
6110 	}
6111 
6112 	pte_l1_s_prot_u = L1_S_PROT_U_generic;
6113 	pte_l1_s_prot_w = L1_S_PROT_W_generic;
6114 	pte_l1_s_prot_ro = L1_S_PROT_RO_generic;
6115 	pte_l1_s_prot_mask = L1_S_PROT_MASK_generic;
6116 
6117 	pte_l2_s_prot_u = L2_S_PROT_U_generic;
6118 	pte_l2_s_prot_w = L2_S_PROT_W_generic;
6119 	pte_l2_s_prot_ro = L2_S_PROT_RO_generic;
6120 	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;
6121 
6122 	pte_l2_l_prot_u = L2_L_PROT_U_generic;
6123 	pte_l2_l_prot_w = L2_L_PROT_W_generic;
6124 	pte_l2_l_prot_ro = L2_L_PROT_RO_generic;
6125 	pte_l2_l_prot_mask = L2_L_PROT_MASK_generic;
6126 
6127 	pte_l1_ss_proto = L1_SS_PROTO_generic;
6128 	pte_l1_s_proto = L1_S_PROTO_generic;
6129 	pte_l1_c_proto = L1_C_PROTO_generic;
6130 	pte_l2_s_proto = L2_S_PROTO_generic;
6131 
6132 	pmap_copy_page_func = pmap_copy_page_generic;
6133 	pmap_zero_page_func = pmap_zero_page_generic;
6134 }
6135 
6136 #if defined(CPU_ARM8)
6137 void
6138 pmap_pte_init_arm8(void)
6139 {
6140 
6141 	/*
6142 	 * ARM8 is compatible with generic, but we need to use
6143 	 * the page tables uncached.
6144 	 */
6145 	pmap_pte_init_generic();
6146 
6147 	pte_l1_s_cache_mode_pt = 0;
6148 	pte_l2_l_cache_mode_pt = 0;
6149 	pte_l2_s_cache_mode_pt = 0;
6150 }
6151 #endif /* CPU_ARM8 */
6152 
6153 #if defined(CPU_ARM9) && defined(ARM9_CACHE_WRITE_THROUGH)
6154 void
6155 pmap_pte_init_arm9(void)
6156 {
6157 
6158 	/*
6159 	 * ARM9 is compatible with generic, but we want to use
6160 	 * write-through caching for now.
6161 	 */
6162 	pmap_pte_init_generic();
6163 
6164 	pte_l1_s_cache_mode = L1_S_C;
6165 	pte_l2_l_cache_mode = L2_C;
6166 	pte_l2_s_cache_mode = L2_C;
6167 
6168 	pte_l1_s_wc_mode = L1_S_B;
6169 	pte_l2_l_wc_mode = L2_B;
6170 	pte_l2_s_wc_mode = L2_B;
6171 
6172 	pte_l1_s_cache_mode_pt = L1_S_C;
6173 	pte_l2_l_cache_mode_pt = L2_C;
6174 	pte_l2_s_cache_mode_pt = L2_C;
6175 }
6176 #endif /* CPU_ARM9 && ARM9_CACHE_WRITE_THROUGH */
6177 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
6178 
6179 #if defined(CPU_ARM10)
6180 void
6181 pmap_pte_init_arm10(void)
6182 {
6183 
6184 	/*
6185 	 * ARM10 is compatible with generic, but we want to use
6186 	 * write-through caching for now.
6187 	 */
6188 	pmap_pte_init_generic();
6189 
6190 	pte_l1_s_cache_mode = L1_S_B | L1_S_C;
6191 	pte_l2_l_cache_mode = L2_B | L2_C;
6192 	pte_l2_s_cache_mode = L2_B | L2_C;
6193 
6194 	pte_l1_s_cache_mode = L1_S_B;
6195 	pte_l2_l_cache_mode = L2_B;
6196 	pte_l2_s_cache_mode = L2_B;
6197 
6198 	pte_l1_s_cache_mode_pt = L1_S_C;
6199 	pte_l2_l_cache_mode_pt = L2_C;
6200 	pte_l2_s_cache_mode_pt = L2_C;
6201 
6202 }
6203 #endif /* CPU_ARM10 */
6204 
6205 #if defined(CPU_ARM11) && defined(ARM11_CACHE_WRITE_THROUGH)
6206 void
6207 pmap_pte_init_arm11(void)
6208 {
6209 
6210 	/*
6211 	 * ARM11 is compatible with generic, but we want to use
6212 	 * write-through caching for now.
6213 	 */
6214 	pmap_pte_init_generic();
6215 
6216 	pte_l1_s_cache_mode = L1_S_C;
6217 	pte_l2_l_cache_mode = L2_C;
6218 	pte_l2_s_cache_mode = L2_C;
6219 
6220 	pte_l1_s_wc_mode = L1_S_B;
6221 	pte_l2_l_wc_mode = L2_B;
6222 	pte_l2_s_wc_mode = L2_B;
6223 
6224 	pte_l1_s_cache_mode_pt = L1_S_C;
6225 	pte_l2_l_cache_mode_pt = L2_C;
6226 	pte_l2_s_cache_mode_pt = L2_C;
6227 }
6228 #endif /* CPU_ARM11 && ARM11_CACHE_WRITE_THROUGH */
6229 
6230 #if ARM_MMU_SA1 == 1
6231 void
6232 pmap_pte_init_sa1(void)
6233 {
6234 
6235 	/*
6236 	 * The StrongARM SA-1 cache does not have a write-through
6237 	 * mode.  So, do the generic initialization, then reset
6238 	 * the page table cache mode to B=1,C=1, and note that
6239 	 * the PTEs need to be sync'd.
6240 	 */
6241 	pmap_pte_init_generic();
6242 
6243 	pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
6244 	pte_l2_l_cache_mode_pt = L2_B|L2_C;
6245 	pte_l2_s_cache_mode_pt = L2_B|L2_C;
6246 
6247 	pmap_needs_pte_sync = 1;
6248 }
6249 #endif /* ARM_MMU_SA1 == 1*/
6250 
6251 #if ARM_MMU_XSCALE == 1
6252 #if (ARM_NMMUS > 1)
6253 static u_int xscale_use_minidata;
6254 #endif
6255 
6256 void
6257 pmap_pte_init_xscale(void)
6258 {
6259 	uint32_t auxctl;
6260 	int write_through = 0;
6261 
6262 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
6263 	pte_l1_s_wc_mode = L1_S_B;
6264 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_xscale;
6265 
6266 	pte_l2_l_cache_mode = L2_B|L2_C;
6267 	pte_l2_l_wc_mode = L2_B;
6268 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_xscale;
6269 
6270 	pte_l2_s_cache_mode = L2_B|L2_C;
6271 	pte_l2_s_wc_mode = L2_B;
6272 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_xscale;
6273 
6274 	pte_l1_s_cache_mode_pt = L1_S_C;
6275 	pte_l2_l_cache_mode_pt = L2_C;
6276 	pte_l2_s_cache_mode_pt = L2_C;
6277 
6278 #ifdef XSCALE_CACHE_READ_WRITE_ALLOCATE
6279 	/*
6280 	 * The XScale core has an enhanced mode where writes that
6281 	 * miss the cache cause a cache line to be allocated.  This
6282 	 * is significantly faster than the traditional, write-through
6283 	 * behavior of this case.
6284 	 */
6285 	pte_l1_s_cache_mode |= L1_S_XS_TEX(TEX_XSCALE_X);
6286 	pte_l2_l_cache_mode |= L2_XS_L_TEX(TEX_XSCALE_X);
6287 	pte_l2_s_cache_mode |= L2_XS_T_TEX(TEX_XSCALE_X);
6288 #endif /* XSCALE_CACHE_READ_WRITE_ALLOCATE */
6289 
6290 #ifdef XSCALE_CACHE_WRITE_THROUGH
6291 	/*
6292 	 * Some versions of the XScale core have various bugs in
6293 	 * their cache units, the work-around for which is to run
6294 	 * the cache in write-through mode.  Unfortunately, this
6295 	 * has a major (negative) impact on performance.  So, we
6296 	 * go ahead and run fast-and-loose, in the hopes that we
6297 	 * don't line up the planets in a way that will trip the
6298 	 * bugs.
6299 	 *
6300 	 * However, we give you the option to be slow-but-correct.
6301 	 */
6302 	write_through = 1;
6303 #elif defined(XSCALE_CACHE_WRITE_BACK)
6304 	/* force write back cache mode */
6305 	write_through = 0;
6306 #elif defined(CPU_XSCALE_PXA250) || defined(CPU_XSCALE_PXA270)
6307 	/*
6308 	 * Intel PXA2[15]0 processors are known to have a bug in
6309 	 * write-back cache on revision 4 and earlier (stepping
6310 	 * A[01] and B[012]).  Fixed for C0 and later.
6311 	 */
6312 	{
6313 		uint32_t id, type;
6314 
6315 		id = cpufunc_id();
6316 		type = id & ~(CPU_ID_XSCALE_COREREV_MASK|CPU_ID_REVISION_MASK);
6317 
6318 		if (type == CPU_ID_PXA250 || type == CPU_ID_PXA210) {
6319 			if ((id & CPU_ID_REVISION_MASK) < 5) {
6320 				/* write through for stepping A0-1 and B0-2 */
6321 				write_through = 1;
6322 			}
6323 		}
6324 	}
6325 #endif /* XSCALE_CACHE_WRITE_THROUGH */
6326 
6327 	if (write_through) {
6328 		pte_l1_s_cache_mode = L1_S_C;
6329 		pte_l2_l_cache_mode = L2_C;
6330 		pte_l2_s_cache_mode = L2_C;
6331 	}
6332 
6333 #if (ARM_NMMUS > 1)
6334 	xscale_use_minidata = 1;
6335 #endif
6336 
6337 	pte_l1_s_prot_u = L1_S_PROT_U_xscale;
6338 	pte_l1_s_prot_w = L1_S_PROT_W_xscale;
6339 	pte_l1_s_prot_ro = L1_S_PROT_RO_xscale;
6340 	pte_l1_s_prot_mask = L1_S_PROT_MASK_xscale;
6341 
6342 	pte_l2_s_prot_u = L2_S_PROT_U_xscale;
6343 	pte_l2_s_prot_w = L2_S_PROT_W_xscale;
6344 	pte_l2_s_prot_ro = L2_S_PROT_RO_xscale;
6345 	pte_l2_s_prot_mask = L2_S_PROT_MASK_xscale;
6346 
6347 	pte_l2_l_prot_u = L2_L_PROT_U_xscale;
6348 	pte_l2_l_prot_w = L2_L_PROT_W_xscale;
6349 	pte_l2_l_prot_ro = L2_L_PROT_RO_xscale;
6350 	pte_l2_l_prot_mask = L2_L_PROT_MASK_xscale;
6351 
6352 	pte_l1_ss_proto = L1_SS_PROTO_xscale;
6353 	pte_l1_s_proto = L1_S_PROTO_xscale;
6354 	pte_l1_c_proto = L1_C_PROTO_xscale;
6355 	pte_l2_s_proto = L2_S_PROTO_xscale;
6356 
6357 	pmap_copy_page_func = pmap_copy_page_xscale;
6358 	pmap_zero_page_func = pmap_zero_page_xscale;
6359 
6360 	/*
6361 	 * Disable ECC protection of page table access, for now.
6362 	 */
6363 	__asm volatile("mrc p15, 0, %0, c1, c0, 1" : "=r" (auxctl));
6364 	auxctl &= ~XSCALE_AUXCTL_P;
6365 	__asm volatile("mcr p15, 0, %0, c1, c0, 1" : : "r" (auxctl));
6366 }
6367 
6368 /*
6369  * xscale_setup_minidata:
6370  *
6371  *	Set up the mini-data cache clean area.  We require the
6372  *	caller to allocate the right amount of physically and
6373  *	virtually contiguous space.
6374  */
6375 void
6376 xscale_setup_minidata(vaddr_t l1pt, vaddr_t va, paddr_t pa)
6377 {
6378 	extern vaddr_t xscale_minidata_clean_addr;
6379 	extern vsize_t xscale_minidata_clean_size; /* already initialized */
6380 	pd_entry_t *pde = (pd_entry_t *) l1pt;
6381 	vsize_t size;
6382 	uint32_t auxctl;
6383 
6384 	xscale_minidata_clean_addr = va;
6385 
6386 	/* Round it to page size. */
6387 	size = (xscale_minidata_clean_size + L2_S_OFFSET) & L2_S_FRAME;
6388 
6389 	for (; size != 0;
6390 	     va += L2_S_SIZE, pa += L2_S_SIZE, size -= L2_S_SIZE) {
6391 		const size_t l1idx = L1_IDX(va);
6392 #ifndef ARM32_NEW_VM_LAYOUT
6393 		pt_entry_t *ptep = (pt_entry_t *)
6394 		    kernel_pt_lookup(pde[l1idx] & L2_S_FRAME);
6395 #else
6396 		pt_entry_t *ptep = (pt_entry_t *) kernel_pt_lookup(
6397 		    pde[l1idx] & L1_C_ADDR_MASK);
6398 #endif
6399 		if (ptep == NULL)
6400 			panic("xscale_setup_minidata: can't find L2 table for "
6401 			    "VA 0x%08lx", va);
6402 
6403 #ifndef ARM32_NEW_VM_LAYOUT
6404 		ptep += (va >> PGSHIFT) & 0x3ff;
6405 #else
6406 		ptep += l2pte_index(va);
6407 #endif
6408 		pt_entry_t opte = *ptep;
6409 		l2pte_set(ptep,
6410 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, VM_PROT_READ)
6411 		    | L2_C | L2_XS_T_TEX(TEX_XSCALE_X), opte);
6412 	}
6413 
6414 	/*
6415 	 * Configure the mini-data cache for write-back with
6416 	 * read/write-allocate.
6417 	 *
6418 	 * NOTE: In order to reconfigure the mini-data cache, we must
6419 	 * make sure it contains no valid data!  In order to do that,
6420 	 * we must issue a global data cache invalidate command!
6421 	 *
6422 	 * WE ASSUME WE ARE RUNNING UN-CACHED WHEN THIS ROUTINE IS CALLED!
6423 	 * THIS IS VERY IMPORTANT!
6424 	 */
6425 
6426 	/* Invalidate data and mini-data. */
6427 	__asm volatile("mcr p15, 0, %0, c7, c6, 0" : : "r" (0));
6428 	__asm volatile("mrc p15, 0, %0, c1, c0, 1" : "=r" (auxctl));
6429 	auxctl = (auxctl & ~XSCALE_AUXCTL_MD_MASK) | XSCALE_AUXCTL_MD_WB_RWA;
6430 	__asm volatile("mcr p15, 0, %0, c1, c0, 1" : : "r" (auxctl));
6431 }
6432 
6433 /*
6434  * Change the PTEs for the specified kernel mappings such that they
6435  * will use the mini data cache instead of the main data cache.
6436  */
6437 void
6438 pmap_uarea(vaddr_t va)
6439 {
6440 	vaddr_t next_bucket, eva;
6441 
6442 #if (ARM_NMMUS > 1)
6443 	if (xscale_use_minidata == 0)
6444 		return;
6445 #endif
6446 
6447 	eva = va + USPACE;
6448 
6449 	while (va < eva) {
6450 		next_bucket = L2_NEXT_BUCKET(va);
6451 		if (next_bucket > eva)
6452 			next_bucket = eva;
6453 
6454 		struct l2_bucket *l2b = pmap_get_l2_bucket(pmap_kernel(), va);
6455 		KDASSERT(l2b != NULL);
6456 
6457 		pt_entry_t * const sptep = &l2b->l2b_kva[l2pte_index(va)];
6458 		pt_entry_t *ptep = sptep;
6459 
6460 		while (va < next_bucket) {
6461 			const pt_entry_t opte = *ptep;
6462 			if (!l2pte_minidata(opte)) {
6463 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
6464 				cpu_tlb_flushD_SE(va);
6465 				l2pte_set(ptep, opte & ~L2_B, opte);
6466 			}
6467 			ptep += PAGE_SIZE / L2_S_SIZE;
6468 			va += PAGE_SIZE;
6469 		}
6470 		PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
6471 	}
6472 	cpu_cpwait();
6473 }
6474 #endif /* ARM_MMU_XSCALE == 1 */
6475 
6476 
6477 #if defined(CPU_ARM11MPCORE)
6478 
6479 void
6480 pmap_pte_init_arm11mpcore(void)
6481 {
6482 
6483 	/* cache mode is controlled by 5 bits (B, C, TEX) */
6484 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_armv6;
6485 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_armv6;
6486 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
6487 	/* use extended small page (without APn, with TEX) */
6488 	pte_l2_s_cache_mask = L2_XS_CACHE_MASK_armv6;
6489 #else
6490 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_armv6c;
6491 #endif
6492 
6493 	/* write-back, write-allocate */
6494 	pte_l1_s_cache_mode = L1_S_C | L1_S_B | L1_S_V6_TEX(0x01);
6495 	pte_l2_l_cache_mode = L2_C | L2_B | L2_V6_L_TEX(0x01);
6496 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
6497 	pte_l2_s_cache_mode = L2_C | L2_B | L2_V6_XS_TEX(0x01);
6498 #else
6499 	/* no TEX. read-allocate */
6500 	pte_l2_s_cache_mode = L2_C | L2_B;
6501 #endif
6502 	/*
6503 	 * write-back, write-allocate for page tables.
6504 	 */
6505 	pte_l1_s_cache_mode_pt = L1_S_C | L1_S_B | L1_S_V6_TEX(0x01);
6506 	pte_l2_l_cache_mode_pt = L2_C | L2_B | L2_V6_L_TEX(0x01);
6507 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
6508 	pte_l2_s_cache_mode_pt = L2_C | L2_B | L2_V6_XS_TEX(0x01);
6509 #else
6510 	pte_l2_s_cache_mode_pt = L2_C | L2_B;
6511 #endif
6512 
6513 	pte_l1_s_prot_u = L1_S_PROT_U_armv6;
6514 	pte_l1_s_prot_w = L1_S_PROT_W_armv6;
6515 	pte_l1_s_prot_ro = L1_S_PROT_RO_armv6;
6516 	pte_l1_s_prot_mask = L1_S_PROT_MASK_armv6;
6517 
6518 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
6519 	pte_l2_s_prot_u = L2_S_PROT_U_armv6n;
6520 	pte_l2_s_prot_w = L2_S_PROT_W_armv6n;
6521 	pte_l2_s_prot_ro = L2_S_PROT_RO_armv6n;
6522 	pte_l2_s_prot_mask = L2_S_PROT_MASK_armv6n;
6523 
6524 #else
6525 	/* with AP[0..3] */
6526 	pte_l2_s_prot_u = L2_S_PROT_U_generic;
6527 	pte_l2_s_prot_w = L2_S_PROT_W_generic;
6528 	pte_l2_s_prot_ro = L2_S_PROT_RO_generic;
6529 	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;
6530 #endif
6531 
6532 #ifdef	ARM11MPCORE_COMPAT_MMU
6533 	/* with AP[0..3] */
6534 	pte_l2_l_prot_u = L2_L_PROT_U_generic;
6535 	pte_l2_l_prot_w = L2_L_PROT_W_generic;
6536 	pte_l2_l_prot_ro = L2_L_PROT_RO_generic;
6537 	pte_l2_l_prot_mask = L2_L_PROT_MASK_generic;
6538 
6539 	pte_l1_ss_proto = L1_SS_PROTO_armv6;
6540 	pte_l1_s_proto = L1_S_PROTO_armv6;
6541 	pte_l1_c_proto = L1_C_PROTO_armv6;
6542 	pte_l2_s_proto = L2_S_PROTO_armv6c;
6543 #else
6544 	pte_l2_l_prot_u = L2_L_PROT_U_armv6n;
6545 	pte_l2_l_prot_w = L2_L_PROT_W_armv6n;
6546 	pte_l2_l_prot_ro = L2_L_PROT_RO_armv6n;
6547 	pte_l2_l_prot_mask = L2_L_PROT_MASK_armv6n;
6548 
6549 	pte_l1_ss_proto = L1_SS_PROTO_armv6;
6550 	pte_l1_s_proto = L1_S_PROTO_armv6;
6551 	pte_l1_c_proto = L1_C_PROTO_armv6;
6552 	pte_l2_s_proto = L2_S_PROTO_armv6n;
6553 #endif
6554 
6555 	pmap_copy_page_func = pmap_copy_page_generic;
6556 	pmap_zero_page_func = pmap_zero_page_generic;
6557 	pmap_needs_pte_sync = 1;
6558 }
6559 #endif	/* CPU_ARM11MPCORE */
6560 
6561 
6562 #if ARM_MMU_V7 == 1
6563 void
6564 pmap_pte_init_armv7(void)
6565 {
6566 	/*
6567 	 * The ARMv7-A MMU is mostly compatible with generic. If the
6568 	 * AP field is zero, that now means "no access" rather than
6569 	 * read-only. The prototypes are a little different because of
6570 	 * the XN bit.
6571 	 */
6572 	pmap_pte_init_generic();
6573 
6574 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_armv7;
6575 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_armv7;
6576 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_armv7;
6577 
6578 	if (CPU_ID_CORTEX_A9_P(curcpu()->ci_arm_cpuid)) {
6579 		/*
6580 		 * write-back, no write-allocate, shareable for normal pages.
6581 		 */
6582 		pte_l1_s_cache_mode = L1_S_C | L1_S_B | L1_S_V6_S;
6583 		pte_l2_l_cache_mode = L2_C | L2_B | L2_XS_S;
6584 		pte_l2_s_cache_mode = L2_C | L2_B | L2_XS_S;
6585 
6586 		/*
6587 		 * write-back, no write-allocate, shareable for page tables.
6588 		 */
6589 		pte_l1_s_cache_mode_pt = L1_S_C | L1_S_B | L1_S_V6_S;
6590 		pte_l2_l_cache_mode_pt = L2_C | L2_B | L2_XS_S;
6591 		pte_l2_s_cache_mode_pt = L2_C | L2_B | L2_XS_S;
6592 	}
6593 
6594 	pte_l1_s_prot_u = L1_S_PROT_U_armv7;
6595 	pte_l1_s_prot_w = L1_S_PROT_W_armv7;
6596 	pte_l1_s_prot_ro = L1_S_PROT_RO_armv7;
6597 	pte_l1_s_prot_mask = L1_S_PROT_MASK_armv7;
6598 
6599 	pte_l2_s_prot_u = L2_S_PROT_U_armv7;
6600 	pte_l2_s_prot_w = L2_S_PROT_W_armv7;
6601 	pte_l2_s_prot_ro = L2_S_PROT_RO_armv7;
6602 	pte_l2_s_prot_mask = L2_S_PROT_MASK_armv7;
6603 
6604 	pte_l2_l_prot_u = L2_L_PROT_U_armv7;
6605 	pte_l2_l_prot_w = L2_L_PROT_W_armv7;
6606 	pte_l2_l_prot_ro = L2_L_PROT_RO_armv7;
6607 	pte_l2_l_prot_mask = L2_L_PROT_MASK_armv7;
6608 
6609 	pte_l1_ss_proto = L1_SS_PROTO_armv7;
6610 	pte_l1_s_proto = L1_S_PROTO_armv7;
6611 	pte_l1_c_proto = L1_C_PROTO_armv7;
6612 	pte_l2_s_proto = L2_S_PROTO_armv7;
6613 
6614 	pmap_needs_pte_sync = 1;
6615 }
6616 #endif /* ARM_MMU_V7 */
6617 
6618 /*
6619  * return the PA of the current L1 table, for use when handling a crash dump
6620  */
6621 uint32_t pmap_kernel_L1_addr(void)
6622 {
6623 	return pmap_kernel()->pm_l1->l1_physaddr;
6624 }
6625 
6626 #if defined(DDB)
6627 /*
6628  * A couple of ddb-callable functions for dumping pmaps
6629  */
6630 void pmap_dump_all(void);
6631 void pmap_dump(pmap_t);
6632 
6633 void
6634 pmap_dump_all(void)
6635 {
6636 	pmap_t pm;
6637 
6638 	LIST_FOREACH(pm, &pmap_pmaps, pm_list) {
6639 		if (pm == pmap_kernel())
6640 			continue;
6641 		pmap_dump(pm);
6642 		printf("\n");
6643 	}
6644 }
6645 
6646 static pt_entry_t ncptes[64];
6647 static void pmap_dump_ncpg(pmap_t);
6648 
6649 void
6650 pmap_dump(pmap_t pm)
6651 {
6652 	struct l2_dtable *l2;
6653 	struct l2_bucket *l2b;
6654 	pt_entry_t *ptep, pte;
6655 	vaddr_t l2_va, l2b_va, va;
6656 	int i, j, k, occ, rows = 0;
6657 
6658 	if (pm == pmap_kernel())
6659 		printf("pmap_kernel (%p): ", pm);
6660 	else
6661 		printf("user pmap (%p): ", pm);
6662 
6663 	printf("domain %d, l1 at %p\n", pmap_domain(pm), pmap_l1_kva(pm));
6664 
6665 	l2_va = 0;
6666 	for (i = 0; i < L2_SIZE; i++, l2_va += 0x01000000) {
6667 		l2 = pm->pm_l2[i];
6668 
6669 		if (l2 == NULL || l2->l2_occupancy == 0)
6670 			continue;
6671 
6672 		l2b_va = l2_va;
6673 		for (j = 0; j < L2_BUCKET_SIZE; j++, l2b_va += 0x00100000) {
6674 			l2b = &l2->l2_bucket[j];
6675 
6676 			if (l2b->l2b_occupancy == 0 || l2b->l2b_kva == NULL)
6677 				continue;
6678 
6679 			ptep = l2b->l2b_kva;
6680 
6681 			for (k = 0; k < 256 && ptep[k] == 0; k++)
6682 				;
6683 
6684 			k &= ~63;
6685 			occ = l2b->l2b_occupancy;
6686 			va = l2b_va + (k * 4096);
6687 			for (; k < 256; k++, va += 0x1000) {
6688 				char ch = ' ';
6689 				if ((k % 64) == 0) {
6690 					if ((rows % 8) == 0) {
6691 						printf(
6692 "          |0000   |8000   |10000  |18000  |20000  |28000  |30000  |38000\n");
6693 					}
6694 					printf("%08lx: ", va);
6695 				}
6696 
6697 				ncptes[k & 63] = 0;
6698 				pte = ptep[k];
6699 				if (pte == 0) {
6700 					ch = '.';
6701 				} else {
6702 					occ--;
6703 					switch (pte & 0x0c) {
6704 					case 0x00:
6705 						ch = 'D'; /* No cache No buff */
6706 						break;
6707 					case 0x04:
6708 						ch = 'B'; /* No cache buff */
6709 						break;
6710 					case 0x08:
6711 						if (pte & 0x40)
6712 							ch = 'm';
6713 						else
6714 						   ch = 'C'; /* Cache No buff */
6715 						break;
6716 					case 0x0c:
6717 						ch = 'F'; /* Cache Buff */
6718 						break;
6719 					}
6720 
6721 					if ((pte & L2_S_PROT_U) == L2_S_PROT_U)
6722 						ch += 0x20;
6723 
6724 					if ((pte & 0xc) == 0)
6725 						ncptes[k & 63] = pte;
6726 				}
6727 
6728 				if ((k % 64) == 63) {
6729 					rows++;
6730 					printf("%c\n", ch);
6731 					pmap_dump_ncpg(pm);
6732 					if (occ == 0)
6733 						break;
6734 				} else
6735 					printf("%c", ch);
6736 			}
6737 		}
6738 	}
6739 }
6740 
6741 static void
6742 pmap_dump_ncpg(pmap_t pm)
6743 {
6744 	struct vm_page *pg;
6745 	struct vm_page_md *md;
6746 	struct pv_entry *pv;
6747 	int i;
6748 
6749 	for (i = 0; i < 63; i++) {
6750 		if (ncptes[i] == 0)
6751 			continue;
6752 
6753 		pg = PHYS_TO_VM_PAGE(l2pte_pa(ncptes[i]));
6754 		if (pg == NULL)
6755 			continue;
6756 		md = VM_PAGE_TO_MD(pg);
6757 
6758 		printf(" pa 0x%08lx: krw %d kro %d urw %d uro %d\n",
6759 		    VM_PAGE_TO_PHYS(pg),
6760 		    md->krw_mappings, md->kro_mappings,
6761 		    md->urw_mappings, md->uro_mappings);
6762 
6763 		SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
6764 			printf("   %c va 0x%08lx, flags 0x%x\n",
6765 			    (pm == pv->pv_pmap) ? '*' : ' ',
6766 			    pv->pv_va, pv->pv_flags);
6767 		}
6768 	}
6769 }
6770 #endif
6771 
6772 #ifdef PMAP_STEAL_MEMORY
6773 void
6774 pmap_boot_pageadd(pv_addr_t *newpv)
6775 {
6776 	pv_addr_t *pv, *npv;
6777 
6778 	if ((pv = SLIST_FIRST(&pmap_boot_freeq)) != NULL) {
6779 		if (newpv->pv_pa < pv->pv_va) {
6780 			KASSERT(newpv->pv_pa + newpv->pv_size <= pv->pv_pa);
6781 			if (newpv->pv_pa + newpv->pv_size == pv->pv_pa) {
6782 				newpv->pv_size += pv->pv_size;
6783 				SLIST_REMOVE_HEAD(&pmap_boot_freeq, pv_list);
6784 			}
6785 			pv = NULL;
6786 		} else {
6787 			for (; (npv = SLIST_NEXT(pv, pv_list)) != NULL;
6788 			     pv = npv) {
6789 				KASSERT(pv->pv_pa + pv->pv_size < npv->pv_pa);
6790 				KASSERT(pv->pv_pa < newpv->pv_pa);
6791 				if (newpv->pv_pa > npv->pv_pa)
6792 					continue;
6793 				if (pv->pv_pa + pv->pv_size == newpv->pv_pa) {
6794 					pv->pv_size += newpv->pv_size;
6795 					return;
6796 				}
6797 				if (newpv->pv_pa + newpv->pv_size < npv->pv_pa)
6798 					break;
6799 				newpv->pv_size += npv->pv_size;
6800 				SLIST_INSERT_AFTER(pv, newpv, pv_list);
6801 				SLIST_REMOVE_AFTER(newpv, pv_list);
6802 				return;
6803 			}
6804 		}
6805 	}
6806 
6807 	if (pv) {
6808 		SLIST_INSERT_AFTER(pv, newpv, pv_list);
6809 	} else {
6810 		SLIST_INSERT_HEAD(&pmap_boot_freeq, newpv, pv_list);
6811 	}
6812 }
6813 
6814 void
6815 pmap_boot_pagealloc(psize_t amount, psize_t mask, psize_t match,
6816 	pv_addr_t *rpv)
6817 {
6818 	pv_addr_t *pv, **pvp;
6819 	struct vm_physseg *ps;
6820 	size_t i;
6821 
6822 	KASSERT(amount & PGOFSET);
6823 	KASSERT((mask & PGOFSET) == 0);
6824 	KASSERT((match & PGOFSET) == 0);
6825 	KASSERT(amount != 0);
6826 
6827 	for (pvp = &SLIST_FIRST(&pmap_boot_freeq);
6828 	     (pv = *pvp) != NULL;
6829 	     pvp = &SLIST_NEXT(pv, pv_list)) {
6830 		pv_addr_t *newpv;
6831 		psize_t off;
6832 		/*
6833 		 * If this entry is too small to satify the request...
6834 		 */
6835 		KASSERT(pv->pv_size > 0);
6836 		if (pv->pv_size < amount)
6837 			continue;
6838 
6839 		for (off = 0; off <= mask; off += PAGE_SIZE) {
6840 			if (((pv->pv_pa + off) & mask) == match
6841 			    && off + amount <= pv->pv_size)
6842 				break;
6843 		}
6844 		if (off > mask)
6845 			continue;
6846 
6847 		rpv->pv_va = pv->pv_va + off;
6848 		rpv->pv_pa = pv->pv_pa + off;
6849 		rpv->pv_size = amount;
6850 		pv->pv_size -= amount;
6851 		if (pv->pv_size == 0) {
6852 			KASSERT(off == 0);
6853 			KASSERT((vaddr_t) pv == rpv->pv_va);
6854 			*pvp = SLIST_NEXT(pv, pv_list);
6855 		} else if (off == 0) {
6856 			KASSERT((vaddr_t) pv == rpv->pv_va);
6857 			newpv = (pv_addr_t *) (rpv->pv_va + amount);
6858 			*newpv = *pv;
6859 			newpv->pv_pa += amount;
6860 			newpv->pv_va += amount;
6861 			*pvp = newpv;
6862 		} else if (off < pv->pv_size) {
6863 			newpv = (pv_addr_t *) (rpv->pv_va + amount);
6864 			*newpv = *pv;
6865 			newpv->pv_size -= off;
6866 			newpv->pv_pa += off + amount;
6867 			newpv->pv_va += off + amount;
6868 
6869 			SLIST_NEXT(pv, pv_list) = newpv;
6870 			pv->pv_size = off;
6871 		} else {
6872 			KASSERT((vaddr_t) pv != rpv->pv_va);
6873 		}
6874 		memset((void *)rpv->pv_va, 0, amount);
6875 		return;
6876 	}
6877 
6878 	if (vm_nphysseg == 0)
6879 		panic("pmap_boot_pagealloc: couldn't allocate memory");
6880 
6881 	for (pvp = &SLIST_FIRST(&pmap_boot_freeq);
6882 	     (pv = *pvp) != NULL;
6883 	     pvp = &SLIST_NEXT(pv, pv_list)) {
6884 		if (SLIST_NEXT(pv, pv_list) == NULL)
6885 			break;
6886 	}
6887 	KASSERT(mask == 0);
6888 	for (i = 0; i < vm_nphysseg; i++) {
6889 		ps = VM_PHYSMEM_PTR(i);
6890 		if (ps->avail_start == atop(pv->pv_pa + pv->pv_size)
6891 		    && pv->pv_va + pv->pv_size <= ptoa(ps->avail_end)) {
6892 			rpv->pv_va = pv->pv_va;
6893 			rpv->pv_pa = pv->pv_pa;
6894 			rpv->pv_size = amount;
6895 			*pvp = NULL;
6896 			pmap_map_chunk(kernel_l1pt.pv_va,
6897 			     ptoa(ps->avail_start) + (pv->pv_va - pv->pv_pa),
6898 			     ptoa(ps->avail_start),
6899 			     amount - pv->pv_size,
6900 			     VM_PROT_READ|VM_PROT_WRITE,
6901 			     PTE_CACHE);
6902 			ps->avail_start += atop(amount - pv->pv_size);
6903 			/*
6904 			 * If we consumed the entire physseg, remove it.
6905 			 */
6906 			if (ps->avail_start == ps->avail_end) {
6907 				for (--vm_nphysseg; i < vm_nphysseg; i++)
6908 					VM_PHYSMEM_PTR_SWAP(i, i + 1);
6909 			}
6910 			memset((void *)rpv->pv_va, 0, rpv->pv_size);
6911 			return;
6912 		}
6913 	}
6914 
6915 	panic("pmap_boot_pagealloc: couldn't allocate memory");
6916 }
6917 
6918 vaddr_t
6919 pmap_steal_memory(vsize_t size, vaddr_t *vstartp, vaddr_t *vendp)
6920 {
6921 	pv_addr_t pv;
6922 
6923 	pmap_boot_pagealloc(size, 0, 0, &pv);
6924 
6925 	return pv.pv_va;
6926 }
6927 #endif /* PMAP_STEAL_MEMORY */
6928 
6929 SYSCTL_SETUP(sysctl_machdep_pmap_setup, "sysctl machdep.kmpages setup")
6930 {
6931 	sysctl_createv(clog, 0, NULL, NULL,
6932 			CTLFLAG_PERMANENT,
6933 			CTLTYPE_NODE, "machdep", NULL,
6934 			NULL, 0, NULL, 0,
6935 			CTL_MACHDEP, CTL_EOL);
6936 
6937 	sysctl_createv(clog, 0, NULL, NULL,
6938 			CTLFLAG_PERMANENT,
6939 			CTLTYPE_INT, "kmpages",
6940 			SYSCTL_DESCR("count of pages allocated to kernel memory allocators"),
6941 			NULL, 0, &pmap_kmpages, 0,
6942 			CTL_MACHDEP, CTL_CREATE, CTL_EOL);
6943 }
6944 
6945 #ifdef PMAP_NEED_ALLOC_POOLPAGE
6946 struct vm_page *
6947 arm_pmap_alloc_poolpage(int flags)
6948 {
6949 	/*
6950 	 * On some systems, only some pages may be "coherent" for dma and we
6951 	 * want to prefer those for pool pages (think mbufs) but fallback to
6952 	 * any page if none is available.
6953 	 */
6954 	if (arm_poolpage_vmfreelist != VM_FREELIST_DEFAULT) {
6955 		return uvm_pagealloc_strat(NULL, 0, NULL, flags,
6956 		    UVM_PGA_STRAT_FALLBACK, arm_poolpage_vmfreelist);
6957 	}
6958 
6959 	return uvm_pagealloc(NULL, 0, NULL, flags);
6960 }
6961 #endif
6962