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