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