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