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