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