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