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