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