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