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