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