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