Home | History | Annotate | Line # | Download | only in arm32
pmap.c revision 1.348
      1 /*	$NetBSD: pmap.c,v 1.348 2017/05/24 06:27:33 skrll Exp $	*/
      2 
      3 /*
      4  * Copyright 2003 Wasabi Systems, Inc.
      5  * All rights reserved.
      6  *
      7  * Written by Steve C. Woodford for Wasabi Systems, Inc.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *      This product includes software developed for the NetBSD Project by
     20  *      Wasabi Systems, Inc.
     21  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
     22  *    or promote products derived from this software without specific prior
     23  *    written permission.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
     26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     27  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     28  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
     29  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     30  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     31  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     32  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     33  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     34  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     35  * POSSIBILITY OF SUCH DAMAGE.
     36  */
     37 
     38 /*
     39  * Copyright (c) 2002-2003 Wasabi Systems, Inc.
     40  * Copyright (c) 2001 Richard Earnshaw
     41  * Copyright (c) 2001-2002 Christopher Gilbert
     42  * All rights reserved.
     43  *
     44  * 1. Redistributions of source code must retain the above copyright
     45  *    notice, this list of conditions and the following disclaimer.
     46  * 2. Redistributions in binary form must reproduce the above copyright
     47  *    notice, this list of conditions and the following disclaimer in the
     48  *    documentation and/or other materials provided with the distribution.
     49  * 3. The name of the company nor the name of the author may be used to
     50  *    endorse or promote products derived from this software without specific
     51  *    prior written permission.
     52  *
     53  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
     54  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
     55  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     56  * IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
     57  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     58  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     59  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     63  * SUCH DAMAGE.
     64  */
     65 
     66 /*-
     67  * Copyright (c) 1999 The NetBSD Foundation, Inc.
     68  * All rights reserved.
     69  *
     70  * This code is derived from software contributed to The NetBSD Foundation
     71  * by Charles M. Hannum.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  *
     82  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     83  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     84  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     85  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     86  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     87  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     88  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     89  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     90  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     91  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     92  * POSSIBILITY OF SUCH DAMAGE.
     93  */
     94 
     95 /*
     96  * Copyright (c) 1994-1998 Mark Brinicombe.
     97  * Copyright (c) 1994 Brini.
     98  * All rights reserved.
     99  *
    100  * This code is derived from software written for Brini by Mark Brinicombe
    101  *
    102  * Redistribution and use in source and binary forms, with or without
    103  * modification, are permitted provided that the following conditions
    104  * are met:
    105  * 1. Redistributions of source code must retain the above copyright
    106  *    notice, this list of conditions and the following disclaimer.
    107  * 2. Redistributions in binary form must reproduce the above copyright
    108  *    notice, this list of conditions and the following disclaimer in the
    109  *    documentation and/or other materials provided with the distribution.
    110  * 3. All advertising materials mentioning features or use of this software
    111  *    must display the following acknowledgement:
    112  *	This product includes software developed by Mark Brinicombe.
    113  * 4. The name of the author may not be used to endorse or promote products
    114  *    derived from this software without specific prior written permission.
    115  *
    116  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
    117  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    118  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    119  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
    120  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    121  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    122  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    123  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    124  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
    125  *
    126  * RiscBSD kernel project
    127  *
    128  * pmap.c
    129  *
    130  * Machine dependent vm stuff
    131  *
    132  * Created      : 20/09/94
    133  */
    134 
    135 /*
    136  * armv6 and VIPT cache support by 3am Software Foundry,
    137  * Copyright (c) 2007 Microsoft
    138  */
    139 
    140 /*
    141  * Performance improvements, UVM changes, overhauls and part-rewrites
    142  * were contributed by Neil A. Carson <neil (at) causality.com>.
    143  */
    144 
    145 /*
    146  * Overhauled again to speedup the pmap, use MMU Domains so that L1 tables
    147  * can be shared, and re-work the KVM layout, by Steve Woodford of Wasabi
    148  * Systems, Inc.
    149  *
    150  * There are still a few things outstanding at this time:
    151  *
    152  *   - There are some unresolved issues for MP systems:
    153  *
    154  *     o The L1 metadata needs a lock, or more specifically, some places
    155  *       need to acquire an exclusive lock when modifying L1 translation
    156  *       table entries.
    157  *
    158  *     o When one cpu modifies an L1 entry, and that L1 table is also
    159  *       being used by another cpu, then the latter will need to be told
    160  *       that a tlb invalidation may be necessary. (But only if the old
    161  *       domain number in the L1 entry being over-written is currently
    162  *       the active domain on that cpu). I guess there are lots more tlb
    163  *       shootdown issues too...
    164  *
    165  *     o If the vector_page is at 0x00000000 instead of in kernel VA space,
    166  *       then MP systems will lose big-time because of the MMU domain hack.
    167  *       The only way this can be solved (apart from moving the vector
    168  *       page to 0xffff0000) is to reserve the first 1MB of user address
    169  *       space for kernel use only. This would require re-linking all
    170  *       applications so that the text section starts above this 1MB
    171  *       boundary.
    172  *
    173  *     o Tracking which VM space is resident in the cache/tlb has not yet
    174  *       been implemented for MP systems.
    175  *
    176  *     o Finally, there is a pathological condition where two cpus running
    177  *       two separate processes (not lwps) which happen to share an L1
    178  *       can get into a fight over one or more L1 entries. This will result
    179  *       in a significant slow-down if both processes are in tight loops.
    180  */
    181 
    182 /*
    183  * Special compilation symbols
    184  * PMAP_DEBUG		- Build in pmap_debug_level code
    185  */
    186 
    187 /* Include header files */
    188 
    189 #include "opt_arm_debug.h"
    190 #include "opt_cpuoptions.h"
    191 #include "opt_pmap_debug.h"
    192 #include "opt_ddb.h"
    193 #include "opt_lockdebug.h"
    194 #include "opt_multiprocessor.h"
    195 
    196 #ifdef MULTIPROCESSOR
    197 #define _INTR_PRIVATE
    198 #endif
    199 
    200 #include <sys/param.h>
    201 #include <sys/types.h>
    202 #include <sys/kernel.h>
    203 #include <sys/systm.h>
    204 #include <sys/proc.h>
    205 #include <sys/intr.h>
    206 #include <sys/pool.h>
    207 #include <sys/kmem.h>
    208 #include <sys/cdefs.h>
    209 #include <sys/cpu.h>
    210 #include <sys/sysctl.h>
    211 #include <sys/bus.h>
    212 #include <sys/atomic.h>
    213 #include <sys/kernhist.h>
    214 
    215 #include <uvm/uvm.h>
    216 #include <uvm/pmap/pmap_pvt.h>
    217 
    218 #include <arm/locore.h>
    219 
    220 __KERNEL_RCSID(0, "$NetBSD: pmap.c,v 1.348 2017/05/24 06:27:33 skrll Exp $");
    221 
    222 //#define PMAP_DEBUG
    223 #ifdef PMAP_DEBUG
    224 
    225 /* XXX need to get rid of all refs to this */
    226 int pmap_debug_level = 0;
    227 
    228 /*
    229  * for switching to potentially finer grained debugging
    230  */
    231 #define	PDB_FOLLOW	0x0001
    232 #define	PDB_INIT	0x0002
    233 #define	PDB_ENTER	0x0004
    234 #define	PDB_REMOVE	0x0008
    235 #define	PDB_CREATE	0x0010
    236 #define	PDB_PTPAGE	0x0020
    237 #define	PDB_GROWKERN	0x0040
    238 #define	PDB_BITS	0x0080
    239 #define	PDB_COLLECT	0x0100
    240 #define	PDB_PROTECT	0x0200
    241 #define	PDB_MAP_L1	0x0400
    242 #define	PDB_BOOTSTRAP	0x1000
    243 #define	PDB_PARANOIA	0x2000
    244 #define	PDB_WIRING	0x4000
    245 #define	PDB_PVDUMP	0x8000
    246 #define	PDB_VAC		0x10000
    247 #define	PDB_KENTER	0x20000
    248 #define	PDB_KREMOVE	0x40000
    249 #define	PDB_EXEC	0x80000
    250 
    251 int debugmap = 1;
    252 int pmapdebug = 0;
    253 #define	NPDEBUG(_lev_,_stat_) \
    254 	if (pmapdebug & (_lev_)) \
    255         	((_stat_))
    256 
    257 #else	/* PMAP_DEBUG */
    258 #define NPDEBUG(_lev_,_stat_) /* Nothing */
    259 #endif	/* PMAP_DEBUG */
    260 
    261 /*
    262  * pmap_kernel() points here
    263  */
    264 static struct pmap	kernel_pmap_store = {
    265 #ifndef ARM_MMU_EXTENDED
    266 	.pm_activated = true,
    267 	.pm_domain = PMAP_DOMAIN_KERNEL,
    268 	.pm_cstate.cs_all = PMAP_CACHE_STATE_ALL,
    269 #endif
    270 };
    271 struct pmap * const	kernel_pmap_ptr = &kernel_pmap_store;
    272 #undef pmap_kernel
    273 #define pmap_kernel()	(&kernel_pmap_store)
    274 #ifdef PMAP_NEED_ALLOC_POOLPAGE
    275 int			arm_poolpage_vmfreelist = VM_FREELIST_DEFAULT;
    276 #endif
    277 
    278 /*
    279  * Pool and cache that pmap structures are allocated from.
    280  * We use a cache to avoid clearing the pm_l2[] array (1KB)
    281  * in pmap_create().
    282  */
    283 static struct pool_cache pmap_cache;
    284 
    285 /*
    286  * Pool of PV structures
    287  */
    288 static struct pool pmap_pv_pool;
    289 static void *pmap_bootstrap_pv_page_alloc(struct pool *, int);
    290 static void pmap_bootstrap_pv_page_free(struct pool *, void *);
    291 static struct pool_allocator pmap_bootstrap_pv_allocator = {
    292 	pmap_bootstrap_pv_page_alloc, pmap_bootstrap_pv_page_free
    293 };
    294 
    295 /*
    296  * Pool and cache of l2_dtable structures.
    297  * We use a cache to avoid clearing the structures when they're
    298  * allocated. (196 bytes)
    299  */
    300 static struct pool_cache pmap_l2dtable_cache;
    301 static vaddr_t pmap_kernel_l2dtable_kva;
    302 
    303 /*
    304  * Pool and cache of L2 page descriptors.
    305  * We use a cache to avoid clearing the descriptor table
    306  * when they're allocated. (1KB)
    307  */
    308 static struct pool_cache pmap_l2ptp_cache;
    309 static vaddr_t pmap_kernel_l2ptp_kva;
    310 static paddr_t pmap_kernel_l2ptp_phys;
    311 
    312 #ifdef PMAPCOUNTERS
    313 #define	PMAP_EVCNT_INITIALIZER(name) \
    314 	EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap", name)
    315 
    316 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
    317 static struct evcnt pmap_ev_vac_clean_one =
    318    PMAP_EVCNT_INITIALIZER("clean page (1 color)");
    319 static struct evcnt pmap_ev_vac_flush_one =
    320    PMAP_EVCNT_INITIALIZER("flush page (1 color)");
    321 static struct evcnt pmap_ev_vac_flush_lots =
    322    PMAP_EVCNT_INITIALIZER("flush page (2+ colors)");
    323 static struct evcnt pmap_ev_vac_flush_lots2 =
    324    PMAP_EVCNT_INITIALIZER("flush page (2+ colors, kmpage)");
    325 EVCNT_ATTACH_STATIC(pmap_ev_vac_clean_one);
    326 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_one);
    327 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_lots);
    328 EVCNT_ATTACH_STATIC(pmap_ev_vac_flush_lots2);
    329 
    330 static struct evcnt pmap_ev_vac_color_new =
    331    PMAP_EVCNT_INITIALIZER("new page color");
    332 static struct evcnt pmap_ev_vac_color_reuse =
    333    PMAP_EVCNT_INITIALIZER("ok first page color");
    334 static struct evcnt pmap_ev_vac_color_ok =
    335    PMAP_EVCNT_INITIALIZER("ok page color");
    336 static struct evcnt pmap_ev_vac_color_blind =
    337    PMAP_EVCNT_INITIALIZER("blind page color");
    338 static struct evcnt pmap_ev_vac_color_change =
    339    PMAP_EVCNT_INITIALIZER("change page color");
    340 static struct evcnt pmap_ev_vac_color_erase =
    341    PMAP_EVCNT_INITIALIZER("erase page color");
    342 static struct evcnt pmap_ev_vac_color_none =
    343    PMAP_EVCNT_INITIALIZER("no page color");
    344 static struct evcnt pmap_ev_vac_color_restore =
    345    PMAP_EVCNT_INITIALIZER("restore page color");
    346 
    347 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_new);
    348 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_reuse);
    349 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_ok);
    350 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_blind);
    351 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_change);
    352 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_erase);
    353 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_none);
    354 EVCNT_ATTACH_STATIC(pmap_ev_vac_color_restore);
    355 #endif
    356 
    357 static struct evcnt pmap_ev_mappings =
    358    PMAP_EVCNT_INITIALIZER("pages mapped");
    359 static struct evcnt pmap_ev_unmappings =
    360    PMAP_EVCNT_INITIALIZER("pages unmapped");
    361 static struct evcnt pmap_ev_remappings =
    362    PMAP_EVCNT_INITIALIZER("pages remapped");
    363 
    364 EVCNT_ATTACH_STATIC(pmap_ev_mappings);
    365 EVCNT_ATTACH_STATIC(pmap_ev_unmappings);
    366 EVCNT_ATTACH_STATIC(pmap_ev_remappings);
    367 
    368 static struct evcnt pmap_ev_kernel_mappings =
    369    PMAP_EVCNT_INITIALIZER("kernel pages mapped");
    370 static struct evcnt pmap_ev_kernel_unmappings =
    371    PMAP_EVCNT_INITIALIZER("kernel pages unmapped");
    372 static struct evcnt pmap_ev_kernel_remappings =
    373    PMAP_EVCNT_INITIALIZER("kernel pages remapped");
    374 
    375 EVCNT_ATTACH_STATIC(pmap_ev_kernel_mappings);
    376 EVCNT_ATTACH_STATIC(pmap_ev_kernel_unmappings);
    377 EVCNT_ATTACH_STATIC(pmap_ev_kernel_remappings);
    378 
    379 static struct evcnt pmap_ev_kenter_mappings =
    380    PMAP_EVCNT_INITIALIZER("kenter pages mapped");
    381 static struct evcnt pmap_ev_kenter_unmappings =
    382    PMAP_EVCNT_INITIALIZER("kenter pages unmapped");
    383 static struct evcnt pmap_ev_kenter_remappings =
    384    PMAP_EVCNT_INITIALIZER("kenter pages remapped");
    385 static struct evcnt pmap_ev_pt_mappings =
    386    PMAP_EVCNT_INITIALIZER("page table pages mapped");
    387 
    388 EVCNT_ATTACH_STATIC(pmap_ev_kenter_mappings);
    389 EVCNT_ATTACH_STATIC(pmap_ev_kenter_unmappings);
    390 EVCNT_ATTACH_STATIC(pmap_ev_kenter_remappings);
    391 EVCNT_ATTACH_STATIC(pmap_ev_pt_mappings);
    392 
    393 static struct evcnt pmap_ev_fixup_mod =
    394    PMAP_EVCNT_INITIALIZER("page modification emulations");
    395 static struct evcnt pmap_ev_fixup_ref =
    396    PMAP_EVCNT_INITIALIZER("page reference emulations");
    397 static struct evcnt pmap_ev_fixup_exec =
    398    PMAP_EVCNT_INITIALIZER("exec pages fixed up");
    399 static struct evcnt pmap_ev_fixup_pdes =
    400    PMAP_EVCNT_INITIALIZER("pdes fixed up");
    401 #ifndef ARM_MMU_EXTENDED
    402 static struct evcnt pmap_ev_fixup_ptesync =
    403    PMAP_EVCNT_INITIALIZER("ptesync fixed");
    404 #endif
    405 
    406 EVCNT_ATTACH_STATIC(pmap_ev_fixup_mod);
    407 EVCNT_ATTACH_STATIC(pmap_ev_fixup_ref);
    408 EVCNT_ATTACH_STATIC(pmap_ev_fixup_exec);
    409 EVCNT_ATTACH_STATIC(pmap_ev_fixup_pdes);
    410 #ifndef ARM_MMU_EXTENDED
    411 EVCNT_ATTACH_STATIC(pmap_ev_fixup_ptesync);
    412 #endif
    413 
    414 #ifdef PMAP_CACHE_VIPT
    415 static struct evcnt pmap_ev_exec_mappings =
    416    PMAP_EVCNT_INITIALIZER("exec pages mapped");
    417 static struct evcnt pmap_ev_exec_cached =
    418    PMAP_EVCNT_INITIALIZER("exec pages cached");
    419 
    420 EVCNT_ATTACH_STATIC(pmap_ev_exec_mappings);
    421 EVCNT_ATTACH_STATIC(pmap_ev_exec_cached);
    422 
    423 static struct evcnt pmap_ev_exec_synced =
    424    PMAP_EVCNT_INITIALIZER("exec pages synced");
    425 static struct evcnt pmap_ev_exec_synced_map =
    426    PMAP_EVCNT_INITIALIZER("exec pages synced (MP)");
    427 static struct evcnt pmap_ev_exec_synced_unmap =
    428    PMAP_EVCNT_INITIALIZER("exec pages synced (UM)");
    429 static struct evcnt pmap_ev_exec_synced_remap =
    430    PMAP_EVCNT_INITIALIZER("exec pages synced (RM)");
    431 static struct evcnt pmap_ev_exec_synced_clearbit =
    432    PMAP_EVCNT_INITIALIZER("exec pages synced (DG)");
    433 #ifndef ARM_MMU_EXTENDED
    434 static struct evcnt pmap_ev_exec_synced_kremove =
    435    PMAP_EVCNT_INITIALIZER("exec pages synced (KU)");
    436 #endif
    437 
    438 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced);
    439 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_map);
    440 #ifndef ARM_MMU_EXTENDED
    441 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_unmap);
    442 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_remap);
    443 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_clearbit);
    444 EVCNT_ATTACH_STATIC(pmap_ev_exec_synced_kremove);
    445 #endif
    446 
    447 static struct evcnt pmap_ev_exec_discarded_unmap =
    448    PMAP_EVCNT_INITIALIZER("exec pages discarded (UM)");
    449 static struct evcnt pmap_ev_exec_discarded_zero =
    450    PMAP_EVCNT_INITIALIZER("exec pages discarded (ZP)");
    451 static struct evcnt pmap_ev_exec_discarded_copy =
    452    PMAP_EVCNT_INITIALIZER("exec pages discarded (CP)");
    453 static struct evcnt pmap_ev_exec_discarded_page_protect =
    454    PMAP_EVCNT_INITIALIZER("exec pages discarded (PP)");
    455 static struct evcnt pmap_ev_exec_discarded_clearbit =
    456    PMAP_EVCNT_INITIALIZER("exec pages discarded (DG)");
    457 static struct evcnt pmap_ev_exec_discarded_kremove =
    458    PMAP_EVCNT_INITIALIZER("exec pages discarded (KU)");
    459 #ifdef ARM_MMU_EXTENDED
    460 static struct evcnt pmap_ev_exec_discarded_modfixup =
    461    PMAP_EVCNT_INITIALIZER("exec pages discarded (MF)");
    462 #endif
    463 
    464 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_unmap);
    465 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_zero);
    466 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_copy);
    467 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_page_protect);
    468 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_clearbit);
    469 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_kremove);
    470 #ifdef ARM_MMU_EXTENDED
    471 EVCNT_ATTACH_STATIC(pmap_ev_exec_discarded_modfixup);
    472 #endif
    473 #endif /* PMAP_CACHE_VIPT */
    474 
    475 static struct evcnt pmap_ev_updates = PMAP_EVCNT_INITIALIZER("updates");
    476 static struct evcnt pmap_ev_collects = PMAP_EVCNT_INITIALIZER("collects");
    477 static struct evcnt pmap_ev_activations = PMAP_EVCNT_INITIALIZER("activations");
    478 
    479 EVCNT_ATTACH_STATIC(pmap_ev_updates);
    480 EVCNT_ATTACH_STATIC(pmap_ev_collects);
    481 EVCNT_ATTACH_STATIC(pmap_ev_activations);
    482 
    483 #define	PMAPCOUNT(x)	((void)(pmap_ev_##x.ev_count++))
    484 #else
    485 #define	PMAPCOUNT(x)	((void)0)
    486 #endif
    487 
    488 #ifdef ARM_MMU_EXTENDED
    489 void pmap_md_pdetab_activate(pmap_t, struct lwp *);
    490 void pmap_md_pdetab_deactivate(pmap_t pm);
    491 #endif
    492 
    493 /*
    494  * pmap copy/zero page, and mem(5) hook point
    495  */
    496 static pt_entry_t *csrc_pte, *cdst_pte;
    497 static vaddr_t csrcp, cdstp;
    498 #ifdef MULTIPROCESSOR
    499 static size_t cnptes;
    500 #define	cpu_csrc_pte(o)	(csrc_pte + cnptes * cpu_number() + ((o) >> L2_S_SHIFT))
    501 #define	cpu_cdst_pte(o)	(cdst_pte + cnptes * cpu_number() + ((o) >> L2_S_SHIFT))
    502 #define	cpu_csrcp(o)	(csrcp + L2_S_SIZE * cnptes * cpu_number() + (o))
    503 #define	cpu_cdstp(o)	(cdstp + L2_S_SIZE * cnptes * cpu_number() + (o))
    504 #else
    505 #define	cpu_csrc_pte(o)	(csrc_pte + ((o) >> L2_S_SHIFT))
    506 #define	cpu_cdst_pte(o)	(cdst_pte + ((o) >> L2_S_SHIFT))
    507 #define	cpu_csrcp(o)	(csrcp + (o))
    508 #define	cpu_cdstp(o)	(cdstp + (o))
    509 #endif
    510 vaddr_t memhook;			/* used by mem.c & others */
    511 kmutex_t memlock __cacheline_aligned;	/* used by mem.c & others */
    512 kmutex_t pmap_lock __cacheline_aligned;
    513 extern void *msgbufaddr;
    514 int pmap_kmpages;
    515 /*
    516  * Flag to indicate if pmap_init() has done its thing
    517  */
    518 bool pmap_initialized;
    519 
    520 #if defined(ARM_MMU_EXTENDED) && defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS)
    521 /*
    522  * Virtual end of direct-mapped memory
    523  */
    524 vaddr_t pmap_directlimit;
    525 #endif
    526 
    527 /*
    528  * Misc. locking data structures
    529  */
    530 
    531 static inline void
    532 pmap_acquire_pmap_lock(pmap_t pm)
    533 {
    534 	if (pm == pmap_kernel()) {
    535 #ifdef MULTIPROCESSOR
    536 		KERNEL_LOCK(1, NULL);
    537 #endif
    538 	} else {
    539 		mutex_enter(pm->pm_lock);
    540 	}
    541 }
    542 
    543 static inline void
    544 pmap_release_pmap_lock(pmap_t pm)
    545 {
    546 	if (pm == pmap_kernel()) {
    547 #ifdef MULTIPROCESSOR
    548 		KERNEL_UNLOCK_ONE(NULL);
    549 #endif
    550 	} else {
    551 		mutex_exit(pm->pm_lock);
    552 	}
    553 }
    554 
    555 static inline void
    556 pmap_acquire_page_lock(struct vm_page_md *md)
    557 {
    558 	mutex_enter(&pmap_lock);
    559 }
    560 
    561 static inline void
    562 pmap_release_page_lock(struct vm_page_md *md)
    563 {
    564 	mutex_exit(&pmap_lock);
    565 }
    566 
    567 #ifdef DIAGNOSTIC
    568 static inline int
    569 pmap_page_locked_p(struct vm_page_md *md)
    570 {
    571 	return mutex_owned(&pmap_lock);
    572 }
    573 #endif
    574 
    575 
    576 /*
    577  * Metadata for L1 translation tables.
    578  */
    579 #ifndef ARM_MMU_EXTENDED
    580 struct l1_ttable {
    581 	/* Entry on the L1 Table list */
    582 	SLIST_ENTRY(l1_ttable) l1_link;
    583 
    584 	/* Entry on the L1 Least Recently Used list */
    585 	TAILQ_ENTRY(l1_ttable) l1_lru;
    586 
    587 	/* Track how many domains are allocated from this L1 */
    588 	volatile u_int l1_domain_use_count;
    589 
    590 	/*
    591 	 * A free-list of domain numbers for this L1.
    592 	 * We avoid using ffs() and a bitmap to track domains since ffs()
    593 	 * is slow on ARM.
    594 	 */
    595 	uint8_t l1_domain_first;
    596 	uint8_t l1_domain_free[PMAP_DOMAINS];
    597 
    598 	/* Physical address of this L1 page table */
    599 	paddr_t l1_physaddr;
    600 
    601 	/* KVA of this L1 page table */
    602 	pd_entry_t *l1_kva;
    603 };
    604 
    605 /*
    606  * L1 Page Tables are tracked using a Least Recently Used list.
    607  *  - New L1s are allocated from the HEAD.
    608  *  - Freed L1s are added to the TAIl.
    609  *  - Recently accessed L1s (where an 'access' is some change to one of
    610  *    the userland pmaps which owns this L1) are moved to the TAIL.
    611  */
    612 static TAILQ_HEAD(, l1_ttable) l1_lru_list;
    613 static kmutex_t l1_lru_lock __cacheline_aligned;
    614 
    615 /*
    616  * A list of all L1 tables
    617  */
    618 static SLIST_HEAD(, l1_ttable) l1_list;
    619 #endif /* ARM_MMU_EXTENDED */
    620 
    621 /*
    622  * The l2_dtable tracks L2_BUCKET_SIZE worth of L1 slots.
    623  *
    624  * This is normally 16MB worth L2 page descriptors for any given pmap.
    625  * Reference counts are maintained for L2 descriptors so they can be
    626  * freed when empty.
    627  */
    628 struct l2_bucket {
    629 	pt_entry_t *l2b_kva;		/* KVA of L2 Descriptor Table */
    630 	paddr_t l2b_pa;			/* Physical address of same */
    631 	u_short l2b_l1slot;		/* This L2 table's L1 index */
    632 	u_short l2b_occupancy;		/* How many active descriptors */
    633 };
    634 
    635 struct l2_dtable {
    636 	/* The number of L2 page descriptors allocated to this l2_dtable */
    637 	u_int l2_occupancy;
    638 
    639 	/* List of L2 page descriptors */
    640 	struct l2_bucket l2_bucket[L2_BUCKET_SIZE];
    641 };
    642 
    643 /*
    644  * Given an L1 table index, calculate the corresponding l2_dtable index
    645  * and bucket index within the l2_dtable.
    646  */
    647 #define L2_BUCKET_XSHIFT	(L2_BUCKET_XLOG2 - L1_S_SHIFT)
    648 #define L2_BUCKET_XFRAME	(~(vaddr_t)0 << L2_BUCKET_XLOG2)
    649 #define L2_BUCKET_IDX(l1slot)	((l1slot) >> L2_BUCKET_XSHIFT)
    650 #define L2_IDX(l1slot)		(L2_BUCKET_IDX(l1slot) >> L2_BUCKET_LOG2)
    651 #define L2_BUCKET(l1slot)	(L2_BUCKET_IDX(l1slot) & (L2_BUCKET_SIZE - 1))
    652 
    653 __CTASSERT(0x100000000ULL == ((uint64_t)L2_SIZE * L2_BUCKET_SIZE * L1_S_SIZE));
    654 __CTASSERT(L2_BUCKET_XFRAME == ~(L2_BUCKET_XSIZE-1));
    655 
    656 /*
    657  * Given a virtual address, this macro returns the
    658  * virtual address required to drop into the next L2 bucket.
    659  */
    660 #define	L2_NEXT_BUCKET_VA(va)	(((va) & L2_BUCKET_XFRAME) + L2_BUCKET_XSIZE)
    661 
    662 /*
    663  * L2 allocation.
    664  */
    665 #define	pmap_alloc_l2_dtable()		\
    666 	    pool_cache_get(&pmap_l2dtable_cache, PR_NOWAIT)
    667 #define	pmap_free_l2_dtable(l2)		\
    668 	    pool_cache_put(&pmap_l2dtable_cache, (l2))
    669 #define pmap_alloc_l2_ptp(pap)		\
    670 	    ((pt_entry_t *)pool_cache_get_paddr(&pmap_l2ptp_cache,\
    671 	    PR_NOWAIT, (pap)))
    672 
    673 /*
    674  * We try to map the page tables write-through, if possible.  However, not
    675  * all CPUs have a write-through cache mode, so on those we have to sync
    676  * the cache when we frob page tables.
    677  *
    678  * We try to evaluate this at compile time, if possible.  However, it's
    679  * not always possible to do that, hence this run-time var.
    680  */
    681 int	pmap_needs_pte_sync;
    682 
    683 /*
    684  * Real definition of pv_entry.
    685  */
    686 struct pv_entry {
    687 	SLIST_ENTRY(pv_entry) pv_link;	/* next pv_entry */
    688 	pmap_t		pv_pmap;        /* pmap where mapping lies */
    689 	vaddr_t		pv_va;          /* virtual address for mapping */
    690 	u_int		pv_flags;       /* flags */
    691 };
    692 
    693 /*
    694  * Macros to determine if a mapping might be resident in the
    695  * instruction/data cache and/or TLB
    696  */
    697 #if ARM_MMU_V7 > 0 && !defined(ARM_MMU_EXTENDED)
    698 /*
    699  * Speculative loads by Cortex cores can cause TLB entries to be filled even if
    700  * there are no explicit accesses, so there may be always be TLB entries to
    701  * flush.  If we used ASIDs then this would not be a problem.
    702  */
    703 #define	PV_BEEN_EXECD(f)  (((f) & PVF_EXEC) == PVF_EXEC)
    704 #define	PV_BEEN_REFD(f)   (true)
    705 #else
    706 #define	PV_BEEN_EXECD(f)  (((f) & (PVF_REF | PVF_EXEC)) == (PVF_REF | PVF_EXEC))
    707 #define	PV_BEEN_REFD(f)   (((f) & PVF_REF) != 0)
    708 #endif
    709 #define	PV_IS_EXEC_P(f)   (((f) & PVF_EXEC) != 0)
    710 #define	PV_IS_KENTRY_P(f) (((f) & PVF_KENTRY) != 0)
    711 #define	PV_IS_WRITE_P(f)  (((f) & PVF_WRITE) != 0)
    712 
    713 /*
    714  * Local prototypes
    715  */
    716 static bool		pmap_set_pt_cache_mode(pd_entry_t *, vaddr_t, size_t);
    717 static void		pmap_alloc_specials(vaddr_t *, int, vaddr_t *,
    718 			    pt_entry_t **);
    719 static bool		pmap_is_current(pmap_t) __unused;
    720 static bool		pmap_is_cached(pmap_t);
    721 static void		pmap_enter_pv(struct vm_page_md *, paddr_t, struct pv_entry *,
    722 			    pmap_t, vaddr_t, u_int);
    723 static struct pv_entry *pmap_find_pv(struct vm_page_md *, pmap_t, vaddr_t);
    724 static struct pv_entry *pmap_remove_pv(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
    725 static u_int		pmap_modify_pv(struct vm_page_md *, paddr_t, pmap_t, vaddr_t,
    726 			    u_int, u_int);
    727 
    728 static void		pmap_pinit(pmap_t);
    729 static int		pmap_pmap_ctor(void *, void *, int);
    730 
    731 static void		pmap_alloc_l1(pmap_t);
    732 static void		pmap_free_l1(pmap_t);
    733 #ifndef ARM_MMU_EXTENDED
    734 static void		pmap_use_l1(pmap_t);
    735 #endif
    736 
    737 static struct l2_bucket *pmap_get_l2_bucket(pmap_t, vaddr_t);
    738 static struct l2_bucket *pmap_alloc_l2_bucket(pmap_t, vaddr_t);
    739 static void		pmap_free_l2_bucket(pmap_t, struct l2_bucket *, u_int);
    740 static int		pmap_l2ptp_ctor(void *, void *, int);
    741 static int		pmap_l2dtable_ctor(void *, void *, int);
    742 
    743 static void		pmap_vac_me_harder(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
    744 #ifdef PMAP_CACHE_VIVT
    745 static void		pmap_vac_me_kpmap(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
    746 static void		pmap_vac_me_user(struct vm_page_md *, paddr_t, pmap_t, vaddr_t);
    747 #endif
    748 
    749 static void		pmap_clearbit(struct vm_page_md *, paddr_t, u_int);
    750 #ifdef PMAP_CACHE_VIVT
    751 static bool		pmap_clean_page(struct vm_page_md *, bool);
    752 #endif
    753 #ifdef PMAP_CACHE_VIPT
    754 static void		pmap_syncicache_page(struct vm_page_md *, paddr_t);
    755 enum pmap_flush_op {
    756 	PMAP_FLUSH_PRIMARY,
    757 	PMAP_FLUSH_SECONDARY,
    758 	PMAP_CLEAN_PRIMARY
    759 };
    760 #ifndef ARM_MMU_EXTENDED
    761 static void		pmap_flush_page(struct vm_page_md *, paddr_t, enum pmap_flush_op);
    762 #endif
    763 #endif
    764 static void		pmap_page_remove(struct vm_page_md *, paddr_t);
    765 static void		pmap_pv_remove(paddr_t);
    766 
    767 #ifndef ARM_MMU_EXTENDED
    768 static void		pmap_init_l1(struct l1_ttable *, pd_entry_t *);
    769 #endif
    770 static vaddr_t		kernel_pt_lookup(paddr_t);
    771 
    772 
    773 /*
    774  * Misc variables
    775  */
    776 vaddr_t virtual_avail;
    777 vaddr_t virtual_end;
    778 vaddr_t pmap_curmaxkvaddr;
    779 
    780 paddr_t avail_start;
    781 paddr_t avail_end;
    782 
    783 pv_addrqh_t pmap_boot_freeq = SLIST_HEAD_INITIALIZER(&pmap_boot_freeq);
    784 pv_addr_t kernelpages;
    785 pv_addr_t kernel_l1pt;
    786 pv_addr_t systempage;
    787 
    788 /* Function to set the debug level of the pmap code */
    789 
    790 #ifdef PMAP_DEBUG
    791 void
    792 pmap_debug(int level)
    793 {
    794 	pmap_debug_level = level;
    795 	printf("pmap_debug: level=%d\n", pmap_debug_level);
    796 }
    797 #endif	/* PMAP_DEBUG */
    798 
    799 #ifdef PMAP_CACHE_VIPT
    800 #define PMAP_VALIDATE_MD_PAGE(md)	\
    801 	KASSERTMSG(arm_cache_prefer_mask == 0 || (((md)->pvh_attrs & PVF_WRITE) == 0) == ((md)->urw_mappings + (md)->krw_mappings == 0), \
    802 	    "(md) %p: attrs=%#x urw=%u krw=%u", (md), \
    803 	    (md)->pvh_attrs, (md)->urw_mappings, (md)->krw_mappings);
    804 #endif /* PMAP_CACHE_VIPT */
    805 /*
    806  * A bunch of routines to conditionally flush the caches/TLB depending
    807  * on whether the specified pmap actually needs to be flushed at any
    808  * given time.
    809  */
    810 static inline void
    811 pmap_tlb_flush_SE(pmap_t pm, vaddr_t va, u_int flags)
    812 {
    813 #ifdef ARM_MMU_EXTENDED
    814 	pmap_tlb_invalidate_addr(pm, va);
    815 #else
    816 	if (pm->pm_cstate.cs_tlb_id != 0) {
    817 		if (PV_BEEN_EXECD(flags)) {
    818 			cpu_tlb_flushID_SE(va);
    819 		} else if (PV_BEEN_REFD(flags)) {
    820 			cpu_tlb_flushD_SE(va);
    821 		}
    822 	}
    823 #endif /* ARM_MMU_EXTENDED */
    824 }
    825 
    826 #ifndef ARM_MMU_EXTENDED
    827 static inline void
    828 pmap_tlb_flushID(pmap_t pm)
    829 {
    830 	if (pm->pm_cstate.cs_tlb_id) {
    831 		cpu_tlb_flushID();
    832 #if ARM_MMU_V7 == 0
    833 		/*
    834 		 * Speculative loads by Cortex cores can cause TLB entries to
    835 		 * be filled even if there are no explicit accesses, so there
    836 		 * may be always be TLB entries to flush.  If we used ASIDs
    837 		 * then it would not be a problem.
    838 		 * This is not true for other CPUs.
    839 		 */
    840 		pm->pm_cstate.cs_tlb = 0;
    841 #endif /* ARM_MMU_V7 */
    842 	}
    843 }
    844 
    845 static inline void
    846 pmap_tlb_flushD(pmap_t pm)
    847 {
    848 	if (pm->pm_cstate.cs_tlb_d) {
    849 		cpu_tlb_flushD();
    850 #if ARM_MMU_V7 == 0
    851 		/*
    852 		 * Speculative loads by Cortex cores can cause TLB entries to
    853 		 * be filled even if there are no explicit accesses, so there
    854 		 * may be always be TLB entries to flush.  If we used ASIDs
    855 		 * then it would not be a problem.
    856 		 * This is not true for other CPUs.
    857 		 */
    858 		pm->pm_cstate.cs_tlb_d = 0;
    859 #endif /* ARM_MMU_V7 */
    860 	}
    861 }
    862 #endif /* ARM_MMU_EXTENDED */
    863 
    864 #ifdef PMAP_CACHE_VIVT
    865 static inline void
    866 pmap_cache_wbinv_page(pmap_t pm, vaddr_t va, bool do_inv, u_int flags)
    867 {
    868 	if (PV_BEEN_EXECD(flags) && pm->pm_cstate.cs_cache_id) {
    869 		cpu_idcache_wbinv_range(va, PAGE_SIZE);
    870 	} else if (PV_BEEN_REFD(flags) && pm->pm_cstate.cs_cache_d) {
    871 		if (do_inv) {
    872 			if (flags & PVF_WRITE)
    873 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
    874 			else
    875 				cpu_dcache_inv_range(va, PAGE_SIZE);
    876 		} else if (flags & PVF_WRITE) {
    877 			cpu_dcache_wb_range(va, PAGE_SIZE);
    878 		}
    879 	}
    880 }
    881 
    882 static inline void
    883 pmap_cache_wbinv_all(pmap_t pm, u_int flags)
    884 {
    885 	if (PV_BEEN_EXECD(flags)) {
    886 		if (pm->pm_cstate.cs_cache_id) {
    887 			cpu_idcache_wbinv_all();
    888 			pm->pm_cstate.cs_cache = 0;
    889 		}
    890 	} else if (pm->pm_cstate.cs_cache_d) {
    891 		cpu_dcache_wbinv_all();
    892 		pm->pm_cstate.cs_cache_d = 0;
    893 	}
    894 }
    895 #endif /* PMAP_CACHE_VIVT */
    896 
    897 static inline uint8_t
    898 pmap_domain(pmap_t pm)
    899 {
    900 #ifdef ARM_MMU_EXTENDED
    901 	return pm == pmap_kernel() ? PMAP_DOMAIN_KERNEL : PMAP_DOMAIN_USER;
    902 #else
    903 	return pm->pm_domain;
    904 #endif
    905 }
    906 
    907 static inline pd_entry_t *
    908 pmap_l1_kva(pmap_t pm)
    909 {
    910 #ifdef ARM_MMU_EXTENDED
    911 	return pm->pm_l1;
    912 #else
    913 	return pm->pm_l1->l1_kva;
    914 #endif
    915 }
    916 
    917 static inline bool
    918 pmap_is_current(pmap_t pm)
    919 {
    920 	if (pm == pmap_kernel() || curproc->p_vmspace->vm_map.pmap == pm)
    921 		return true;
    922 
    923 	return false;
    924 }
    925 
    926 static inline bool
    927 pmap_is_cached(pmap_t pm)
    928 {
    929 #ifdef ARM_MMU_EXTENDED
    930 	if (pm == pmap_kernel())
    931 		return true;
    932 #ifdef MULTIPROCESSOR
    933 	// Is this pmap active on any CPU?
    934 	if (!kcpuset_iszero(pm->pm_active))
    935 		return true;
    936 #else
    937 	struct pmap_tlb_info * const ti = cpu_tlb_info(curcpu());
    938 	// Is this pmap active?
    939 	if (PMAP_PAI_ASIDVALID_P(PMAP_PAI(pm, ti), ti))
    940 		return true;
    941 #endif
    942 #else
    943 	struct cpu_info * const ci = curcpu();
    944 	if (pm == pmap_kernel() || ci->ci_pmap_lastuser == NULL
    945 	    || ci->ci_pmap_lastuser == pm)
    946 		return true;
    947 #endif /* ARM_MMU_EXTENDED */
    948 
    949 	return false;
    950 }
    951 
    952 /*
    953  * PTE_SYNC_CURRENT:
    954  *
    955  *     Make sure the pte is written out to RAM.
    956  *     We need to do this for one of two cases:
    957  *       - We're dealing with the kernel pmap
    958  *       - There is no pmap active in the cache/tlb.
    959  *       - The specified pmap is 'active' in the cache/tlb.
    960  */
    961 
    962 #ifdef PMAP_INCLUDE_PTE_SYNC
    963 static inline void
    964 pmap_pte_sync_current(pmap_t pm, pt_entry_t *ptep)
    965 {
    966 	if (PMAP_NEEDS_PTE_SYNC && pmap_is_cached(pm))
    967 		PTE_SYNC(ptep);
    968 	arm_dsb();
    969 }
    970 
    971 # define PTE_SYNC_CURRENT(pm, ptep)	pmap_pte_sync_current(pm, ptep)
    972 #else
    973 # define PTE_SYNC_CURRENT(pm, ptep)	__nothing
    974 #endif
    975 
    976 /*
    977  * main pv_entry manipulation functions:
    978  *   pmap_enter_pv: enter a mapping onto a vm_page list
    979  *   pmap_remove_pv: remove a mapping from a vm_page list
    980  *
    981  * NOTE: pmap_enter_pv expects to lock the pvh itself
    982  *       pmap_remove_pv expects the caller to lock the pvh before calling
    983  */
    984 
    985 /*
    986  * pmap_enter_pv: enter a mapping onto a vm_page lst
    987  *
    988  * => caller should hold the proper lock on pmap_main_lock
    989  * => caller should have pmap locked
    990  * => we will gain the lock on the vm_page and allocate the new pv_entry
    991  * => caller should adjust ptp's wire_count before calling
    992  * => caller should not adjust pmap's wire_count
    993  */
    994 static void
    995 pmap_enter_pv(struct vm_page_md *md, paddr_t pa, struct pv_entry *pv, pmap_t pm,
    996     vaddr_t va, u_int flags)
    997 {
    998 	struct pv_entry **pvp;
    999 
   1000 	NPDEBUG(PDB_PVDUMP,
   1001 	    printf("pmap_enter_pv: pm %p, md %p, flags 0x%x\n", pm, md, flags));
   1002 
   1003 	pv->pv_pmap = pm;
   1004 	pv->pv_va = va;
   1005 	pv->pv_flags = flags;
   1006 
   1007 	pvp = &SLIST_FIRST(&md->pvh_list);
   1008 #ifdef PMAP_CACHE_VIPT
   1009 	/*
   1010 	 * Insert unmanaged entries, writeable first, at the head of
   1011 	 * the pv list.
   1012 	 */
   1013 	if (__predict_true(!PV_IS_KENTRY_P(flags))) {
   1014 		while (*pvp != NULL && PV_IS_KENTRY_P((*pvp)->pv_flags))
   1015 			pvp = &SLIST_NEXT(*pvp, pv_link);
   1016 	}
   1017 	if (!PV_IS_WRITE_P(flags)) {
   1018 		while (*pvp != NULL && PV_IS_WRITE_P((*pvp)->pv_flags))
   1019 			pvp = &SLIST_NEXT(*pvp, pv_link);
   1020 	}
   1021 #endif
   1022 	SLIST_NEXT(pv, pv_link) = *pvp;		/* add to ... */
   1023 	*pvp = pv;				/* ... locked list */
   1024 	md->pvh_attrs |= flags & (PVF_REF | PVF_MOD);
   1025 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   1026 	if ((pv->pv_flags & PVF_KWRITE) == PVF_KWRITE)
   1027 		md->pvh_attrs |= PVF_KMOD;
   1028 	if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) != PVF_NC)
   1029 		md->pvh_attrs |= PVF_DIRTY;
   1030 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   1031 #endif
   1032 	if (pm == pmap_kernel()) {
   1033 		PMAPCOUNT(kernel_mappings);
   1034 		if (flags & PVF_WRITE)
   1035 			md->krw_mappings++;
   1036 		else
   1037 			md->kro_mappings++;
   1038 	} else {
   1039 		if (flags & PVF_WRITE)
   1040 			md->urw_mappings++;
   1041 		else
   1042 			md->uro_mappings++;
   1043 	}
   1044 
   1045 #ifdef PMAP_CACHE_VIPT
   1046 #ifndef ARM_MMU_EXTENDED
   1047 	/*
   1048 	 * Even though pmap_vac_me_harder will set PVF_WRITE for us,
   1049 	 * do it here as well to keep the mappings & KVF_WRITE consistent.
   1050 	 */
   1051 	if (arm_cache_prefer_mask != 0 && (flags & PVF_WRITE) != 0) {
   1052 		md->pvh_attrs |= PVF_WRITE;
   1053 	}
   1054 #endif
   1055 	/*
   1056 	 * If this is an exec mapping and its the first exec mapping
   1057 	 * for this page, make sure to sync the I-cache.
   1058 	 */
   1059 	if (PV_IS_EXEC_P(flags)) {
   1060 		if (!PV_IS_EXEC_P(md->pvh_attrs)) {
   1061 			pmap_syncicache_page(md, pa);
   1062 			PMAPCOUNT(exec_synced_map);
   1063 		}
   1064 		PMAPCOUNT(exec_mappings);
   1065 	}
   1066 #endif
   1067 
   1068 	PMAPCOUNT(mappings);
   1069 
   1070 	if (pv->pv_flags & PVF_WIRED)
   1071 		++pm->pm_stats.wired_count;
   1072 }
   1073 
   1074 /*
   1075  *
   1076  * pmap_find_pv: Find a pv entry
   1077  *
   1078  * => caller should hold lock on vm_page
   1079  */
   1080 static inline struct pv_entry *
   1081 pmap_find_pv(struct vm_page_md *md, pmap_t pm, vaddr_t va)
   1082 {
   1083 	struct pv_entry *pv;
   1084 
   1085 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   1086 		if (pm == pv->pv_pmap && va == pv->pv_va)
   1087 			break;
   1088 	}
   1089 
   1090 	return (pv);
   1091 }
   1092 
   1093 /*
   1094  * pmap_remove_pv: try to remove a mapping from a pv_list
   1095  *
   1096  * => caller should hold proper lock on pmap_main_lock
   1097  * => pmap should be locked
   1098  * => caller should hold lock on vm_page [so that attrs can be adjusted]
   1099  * => caller should adjust ptp's wire_count and free PTP if needed
   1100  * => caller should NOT adjust pmap's wire_count
   1101  * => we return the removed pv
   1102  */
   1103 static struct pv_entry *
   1104 pmap_remove_pv(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
   1105 {
   1106 	struct pv_entry *pv, **prevptr;
   1107 
   1108 	NPDEBUG(PDB_PVDUMP,
   1109 	    printf("pmap_remove_pv: pm %p, md %p, va 0x%08lx\n", pm, md, va));
   1110 
   1111 	prevptr = &SLIST_FIRST(&md->pvh_list); /* prev pv_entry ptr */
   1112 	pv = *prevptr;
   1113 
   1114 	while (pv) {
   1115 		if (pv->pv_pmap == pm && pv->pv_va == va) {	/* match? */
   1116 			NPDEBUG(PDB_PVDUMP, printf("pmap_remove_pv: pm %p, md "
   1117 			    "%p, flags 0x%x\n", pm, md, pv->pv_flags));
   1118 			if (pv->pv_flags & PVF_WIRED) {
   1119 				--pm->pm_stats.wired_count;
   1120 			}
   1121 			*prevptr = SLIST_NEXT(pv, pv_link);	/* remove it! */
   1122 			if (pm == pmap_kernel()) {
   1123 				PMAPCOUNT(kernel_unmappings);
   1124 				if (pv->pv_flags & PVF_WRITE)
   1125 					md->krw_mappings--;
   1126 				else
   1127 					md->kro_mappings--;
   1128 			} else {
   1129 				if (pv->pv_flags & PVF_WRITE)
   1130 					md->urw_mappings--;
   1131 				else
   1132 					md->uro_mappings--;
   1133 			}
   1134 
   1135 			PMAPCOUNT(unmappings);
   1136 #ifdef PMAP_CACHE_VIPT
   1137 			/*
   1138 			 * If this page has had an exec mapping, then if
   1139 			 * this was the last mapping, discard the contents,
   1140 			 * otherwise sync the i-cache for this page.
   1141 			 */
   1142 			if (PV_IS_EXEC_P(md->pvh_attrs)) {
   1143 				if (SLIST_EMPTY(&md->pvh_list)) {
   1144 					md->pvh_attrs &= ~PVF_EXEC;
   1145 					PMAPCOUNT(exec_discarded_unmap);
   1146 				} else if (pv->pv_flags & PVF_WRITE) {
   1147 					pmap_syncicache_page(md, pa);
   1148 					PMAPCOUNT(exec_synced_unmap);
   1149 				}
   1150 			}
   1151 #endif /* PMAP_CACHE_VIPT */
   1152 			break;
   1153 		}
   1154 		prevptr = &SLIST_NEXT(pv, pv_link);	/* previous pointer */
   1155 		pv = *prevptr;				/* advance */
   1156 	}
   1157 
   1158 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   1159 	/*
   1160 	 * If we no longer have a WRITEABLE KENTRY at the head of list,
   1161 	 * clear the KMOD attribute from the page.
   1162 	 */
   1163 	if (SLIST_FIRST(&md->pvh_list) == NULL
   1164 	    || (SLIST_FIRST(&md->pvh_list)->pv_flags & PVF_KWRITE) != PVF_KWRITE)
   1165 		md->pvh_attrs &= ~PVF_KMOD;
   1166 
   1167 	/*
   1168 	 * If this was a writeable page and there are no more writeable
   1169 	 * mappings (ignoring KMPAGE), clear the WRITE flag and writeback
   1170 	 * the contents to memory.
   1171 	 */
   1172 	if (arm_cache_prefer_mask != 0) {
   1173 		if (md->krw_mappings + md->urw_mappings == 0)
   1174 			md->pvh_attrs &= ~PVF_WRITE;
   1175 		PMAP_VALIDATE_MD_PAGE(md);
   1176 	}
   1177 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   1178 #endif /* PMAP_CACHE_VIPT && !ARM_MMU_EXTENDED */
   1179 
   1180 	/* return removed pv */
   1181 	return pv;
   1182 }
   1183 
   1184 /*
   1185  *
   1186  * pmap_modify_pv: Update pv flags
   1187  *
   1188  * => caller should hold lock on vm_page [so that attrs can be adjusted]
   1189  * => caller should NOT adjust pmap's wire_count
   1190  * => caller must call pmap_vac_me_harder() if writable status of a page
   1191  *    may have changed.
   1192  * => we return the old flags
   1193  *
   1194  * Modify a physical-virtual mapping in the pv table
   1195  */
   1196 static u_int
   1197 pmap_modify_pv(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va,
   1198     u_int clr_mask, u_int set_mask)
   1199 {
   1200 	struct pv_entry *npv;
   1201 	u_int flags, oflags;
   1202 
   1203 	KASSERT(!PV_IS_KENTRY_P(clr_mask));
   1204 	KASSERT(!PV_IS_KENTRY_P(set_mask));
   1205 
   1206 	if ((npv = pmap_find_pv(md, pm, va)) == NULL)
   1207 		return (0);
   1208 
   1209 	NPDEBUG(PDB_PVDUMP,
   1210 	    printf("pmap_modify_pv: pm %p, md %p, clr 0x%x, set 0x%x, flags 0x%x\n", pm, md, clr_mask, set_mask, npv->pv_flags));
   1211 
   1212 	/*
   1213 	 * There is at least one VA mapping this page.
   1214 	 */
   1215 
   1216 	if (clr_mask & (PVF_REF | PVF_MOD)) {
   1217 		md->pvh_attrs |= set_mask & (PVF_REF | PVF_MOD);
   1218 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   1219 		if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) != PVF_NC)
   1220 			md->pvh_attrs |= PVF_DIRTY;
   1221 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   1222 #endif /* PMAP_CACHE_VIPT && !ARM_MMU_EXTENDED */
   1223 	}
   1224 
   1225 	oflags = npv->pv_flags;
   1226 	npv->pv_flags = flags = (oflags & ~clr_mask) | set_mask;
   1227 
   1228 	if ((flags ^ oflags) & PVF_WIRED) {
   1229 		if (flags & PVF_WIRED)
   1230 			++pm->pm_stats.wired_count;
   1231 		else
   1232 			--pm->pm_stats.wired_count;
   1233 	}
   1234 
   1235 	if ((flags ^ oflags) & PVF_WRITE) {
   1236 		if (pm == pmap_kernel()) {
   1237 			if (flags & PVF_WRITE) {
   1238 				md->krw_mappings++;
   1239 				md->kro_mappings--;
   1240 			} else {
   1241 				md->kro_mappings++;
   1242 				md->krw_mappings--;
   1243 			}
   1244 		} else {
   1245 			if (flags & PVF_WRITE) {
   1246 				md->urw_mappings++;
   1247 				md->uro_mappings--;
   1248 			} else {
   1249 				md->uro_mappings++;
   1250 				md->urw_mappings--;
   1251 			}
   1252 		}
   1253 	}
   1254 #ifdef PMAP_CACHE_VIPT
   1255 	if (arm_cache_prefer_mask != 0) {
   1256 		if (md->urw_mappings + md->krw_mappings == 0) {
   1257 			md->pvh_attrs &= ~PVF_WRITE;
   1258 		} else {
   1259 			md->pvh_attrs |= PVF_WRITE;
   1260 		}
   1261 	}
   1262 	/*
   1263 	 * We have two cases here: the first is from enter_pv (new exec
   1264 	 * page), the second is a combined pmap_remove_pv/pmap_enter_pv.
   1265 	 * Since in latter, pmap_enter_pv won't do anything, we just have
   1266 	 * to do what pmap_remove_pv would do.
   1267 	 */
   1268 	if ((PV_IS_EXEC_P(flags) && !PV_IS_EXEC_P(md->pvh_attrs))
   1269 	    || (PV_IS_EXEC_P(md->pvh_attrs)
   1270 		|| (!(flags & PVF_WRITE) && (oflags & PVF_WRITE)))) {
   1271 		pmap_syncicache_page(md, pa);
   1272 		PMAPCOUNT(exec_synced_remap);
   1273 	}
   1274 #ifndef ARM_MMU_EXTENDED
   1275 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   1276 #endif /* !ARM_MMU_EXTENDED */
   1277 #endif /* PMAP_CACHE_VIPT */
   1278 
   1279 	PMAPCOUNT(remappings);
   1280 
   1281 	return (oflags);
   1282 }
   1283 
   1284 /*
   1285  * Allocate an L1 translation table for the specified pmap.
   1286  * This is called at pmap creation time.
   1287  */
   1288 static void
   1289 pmap_alloc_l1(pmap_t pm)
   1290 {
   1291 #ifdef ARM_MMU_EXTENDED
   1292 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   1293 	struct vm_page *pg;
   1294 	bool ok __diagused;
   1295 	for (;;) {
   1296 #ifdef PMAP_NEED_ALLOC_POOLPAGE
   1297 		pg = arm_pmap_alloc_poolpage(UVM_PGA_ZERO);
   1298 #else
   1299 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_ZERO);
   1300 #endif
   1301 		if (pg != NULL)
   1302 			break;
   1303 		uvm_wait("pmapl1alloc");
   1304 	}
   1305 	pm->pm_l1_pa = VM_PAGE_TO_PHYS(pg);
   1306 	vaddr_t va = pmap_direct_mapped_phys(pm->pm_l1_pa, &ok, 0);
   1307 	KASSERT(ok);
   1308 	KASSERT(va >= KERNEL_BASE);
   1309 
   1310 #else
   1311 	KASSERTMSG(kernel_map != NULL, "pm %p", pm);
   1312 	vaddr_t va = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
   1313 	    UVM_KMF_WIRED|UVM_KMF_ZERO);
   1314 	KASSERT(va);
   1315 	pmap_extract(pmap_kernel(), va, &pm->pm_l1_pa);
   1316 #endif
   1317 	pm->pm_l1 = (pd_entry_t *)va;
   1318 	PTE_SYNC_RANGE(pm->pm_l1, PAGE_SIZE / sizeof(pt_entry_t));
   1319 #else
   1320 	struct l1_ttable *l1;
   1321 	uint8_t domain;
   1322 
   1323 	/*
   1324 	 * Remove the L1 at the head of the LRU list
   1325 	 */
   1326 	mutex_spin_enter(&l1_lru_lock);
   1327 	l1 = TAILQ_FIRST(&l1_lru_list);
   1328 	KDASSERT(l1 != NULL);
   1329 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
   1330 
   1331 	/*
   1332 	 * Pick the first available domain number, and update
   1333 	 * the link to the next number.
   1334 	 */
   1335 	domain = l1->l1_domain_first;
   1336 	l1->l1_domain_first = l1->l1_domain_free[domain];
   1337 
   1338 	/*
   1339 	 * If there are still free domain numbers in this L1,
   1340 	 * put it back on the TAIL of the LRU list.
   1341 	 */
   1342 	if (++l1->l1_domain_use_count < PMAP_DOMAINS)
   1343 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
   1344 
   1345 	mutex_spin_exit(&l1_lru_lock);
   1346 
   1347 	/*
   1348 	 * Fix up the relevant bits in the pmap structure
   1349 	 */
   1350 	pm->pm_l1 = l1;
   1351 	pm->pm_domain = domain + 1;
   1352 #endif
   1353 }
   1354 
   1355 /*
   1356  * Free an L1 translation table.
   1357  * This is called at pmap destruction time.
   1358  */
   1359 static void
   1360 pmap_free_l1(pmap_t pm)
   1361 {
   1362 #ifdef ARM_MMU_EXTENDED
   1363 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   1364 	struct vm_page *pg = PHYS_TO_VM_PAGE(pm->pm_l1_pa);
   1365 	uvm_pagefree(pg);
   1366 #else
   1367 	uvm_km_free(kernel_map, (vaddr_t)pm->pm_l1, PAGE_SIZE, UVM_KMF_WIRED);
   1368 #endif
   1369 	pm->pm_l1 = NULL;
   1370 	pm->pm_l1_pa = 0;
   1371 #else
   1372 	struct l1_ttable *l1 = pm->pm_l1;
   1373 
   1374 	mutex_spin_enter(&l1_lru_lock);
   1375 
   1376 	/*
   1377 	 * If this L1 is currently on the LRU list, remove it.
   1378 	 */
   1379 	if (l1->l1_domain_use_count < PMAP_DOMAINS)
   1380 		TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
   1381 
   1382 	/*
   1383 	 * Free up the domain number which was allocated to the pmap
   1384 	 */
   1385 	l1->l1_domain_free[pmap_domain(pm) - 1] = l1->l1_domain_first;
   1386 	l1->l1_domain_first = pmap_domain(pm) - 1;
   1387 	l1->l1_domain_use_count--;
   1388 
   1389 	/*
   1390 	 * The L1 now must have at least 1 free domain, so add
   1391 	 * it back to the LRU list. If the use count is zero,
   1392 	 * put it at the head of the list, otherwise it goes
   1393 	 * to the tail.
   1394 	 */
   1395 	if (l1->l1_domain_use_count == 0)
   1396 		TAILQ_INSERT_HEAD(&l1_lru_list, l1, l1_lru);
   1397 	else
   1398 		TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
   1399 
   1400 	mutex_spin_exit(&l1_lru_lock);
   1401 #endif /* ARM_MMU_EXTENDED */
   1402 }
   1403 
   1404 #ifndef ARM_MMU_EXTENDED
   1405 static inline void
   1406 pmap_use_l1(pmap_t pm)
   1407 {
   1408 	struct l1_ttable *l1;
   1409 
   1410 	/*
   1411 	 * Do nothing if we're in interrupt context.
   1412 	 * Access to an L1 by the kernel pmap must not affect
   1413 	 * the LRU list.
   1414 	 */
   1415 	if (cpu_intr_p() || pm == pmap_kernel())
   1416 		return;
   1417 
   1418 	l1 = pm->pm_l1;
   1419 
   1420 	/*
   1421 	 * If the L1 is not currently on the LRU list, just return
   1422 	 */
   1423 	if (l1->l1_domain_use_count == PMAP_DOMAINS)
   1424 		return;
   1425 
   1426 	mutex_spin_enter(&l1_lru_lock);
   1427 
   1428 	/*
   1429 	 * Check the use count again, now that we've acquired the lock
   1430 	 */
   1431 	if (l1->l1_domain_use_count == PMAP_DOMAINS) {
   1432 		mutex_spin_exit(&l1_lru_lock);
   1433 		return;
   1434 	}
   1435 
   1436 	/*
   1437 	 * Move the L1 to the back of the LRU list
   1438 	 */
   1439 	TAILQ_REMOVE(&l1_lru_list, l1, l1_lru);
   1440 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
   1441 
   1442 	mutex_spin_exit(&l1_lru_lock);
   1443 }
   1444 #endif /* !ARM_MMU_EXTENDED */
   1445 
   1446 /*
   1447  * void pmap_free_l2_ptp(pt_entry_t *, paddr_t *)
   1448  *
   1449  * Free an L2 descriptor table.
   1450  */
   1451 static inline void
   1452 #if defined(PMAP_INCLUDE_PTE_SYNC) && defined(PMAP_CACHE_VIVT)
   1453 pmap_free_l2_ptp(bool need_sync, pt_entry_t *l2, paddr_t pa)
   1454 #else
   1455 pmap_free_l2_ptp(pt_entry_t *l2, paddr_t pa)
   1456 #endif
   1457 {
   1458 #if defined(PMAP_INCLUDE_PTE_SYNC) && defined(PMAP_CACHE_VIVT)
   1459 	/*
   1460 	 * Note: With a write-back cache, we may need to sync this
   1461 	 * L2 table before re-using it.
   1462 	 * This is because it may have belonged to a non-current
   1463 	 * pmap, in which case the cache syncs would have been
   1464 	 * skipped for the pages that were being unmapped. If the
   1465 	 * L2 table were then to be immediately re-allocated to
   1466 	 * the *current* pmap, it may well contain stale mappings
   1467 	 * which have not yet been cleared by a cache write-back
   1468 	 * and so would still be visible to the mmu.
   1469 	 */
   1470 	if (need_sync)
   1471 		PTE_SYNC_RANGE(l2, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
   1472 #endif /* PMAP_INCLUDE_PTE_SYNC && PMAP_CACHE_VIVT */
   1473 	pool_cache_put_paddr(&pmap_l2ptp_cache, (void *)l2, pa);
   1474 }
   1475 
   1476 /*
   1477  * Returns a pointer to the L2 bucket associated with the specified pmap
   1478  * and VA, or NULL if no L2 bucket exists for the address.
   1479  */
   1480 static inline struct l2_bucket *
   1481 pmap_get_l2_bucket(pmap_t pm, vaddr_t va)
   1482 {
   1483 	const size_t l1slot = l1pte_index(va);
   1484 	struct l2_dtable *l2;
   1485 	struct l2_bucket *l2b;
   1486 
   1487 	if ((l2 = pm->pm_l2[L2_IDX(l1slot)]) == NULL ||
   1488 	    (l2b = &l2->l2_bucket[L2_BUCKET(l1slot)])->l2b_kva == NULL)
   1489 		return (NULL);
   1490 
   1491 	return (l2b);
   1492 }
   1493 
   1494 /*
   1495  * Returns a pointer to the L2 bucket associated with the specified pmap
   1496  * and VA.
   1497  *
   1498  * If no L2 bucket exists, perform the necessary allocations to put an L2
   1499  * bucket/page table in place.
   1500  *
   1501  * Note that if a new L2 bucket/page was allocated, the caller *must*
   1502  * increment the bucket occupancy counter appropriately *before*
   1503  * releasing the pmap's lock to ensure no other thread or cpu deallocates
   1504  * the bucket/page in the meantime.
   1505  */
   1506 static struct l2_bucket *
   1507 pmap_alloc_l2_bucket(pmap_t pm, vaddr_t va)
   1508 {
   1509 	const size_t l1slot = l1pte_index(va);
   1510 	struct l2_dtable *l2;
   1511 
   1512 	if ((l2 = pm->pm_l2[L2_IDX(l1slot)]) == NULL) {
   1513 		/*
   1514 		 * No mapping at this address, as there is
   1515 		 * no entry in the L1 table.
   1516 		 * Need to allocate a new l2_dtable.
   1517 		 */
   1518 		if ((l2 = pmap_alloc_l2_dtable()) == NULL)
   1519 			return (NULL);
   1520 
   1521 		/*
   1522 		 * Link it into the parent pmap
   1523 		 */
   1524 		pm->pm_l2[L2_IDX(l1slot)] = l2;
   1525 	}
   1526 
   1527 	struct l2_bucket * const l2b = &l2->l2_bucket[L2_BUCKET(l1slot)];
   1528 
   1529 	/*
   1530 	 * Fetch pointer to the L2 page table associated with the address.
   1531 	 */
   1532 	if (l2b->l2b_kva == NULL) {
   1533 		pt_entry_t *ptep;
   1534 
   1535 		/*
   1536 		 * No L2 page table has been allocated. Chances are, this
   1537 		 * is because we just allocated the l2_dtable, above.
   1538 		 */
   1539 		if ((ptep = pmap_alloc_l2_ptp(&l2b->l2b_pa)) == NULL) {
   1540 			/*
   1541 			 * Oops, no more L2 page tables available at this
   1542 			 * time. We may need to deallocate the l2_dtable
   1543 			 * if we allocated a new one above.
   1544 			 */
   1545 			if (l2->l2_occupancy == 0) {
   1546 				pm->pm_l2[L2_IDX(l1slot)] = NULL;
   1547 				pmap_free_l2_dtable(l2);
   1548 			}
   1549 			return (NULL);
   1550 		}
   1551 
   1552 		l2->l2_occupancy++;
   1553 		l2b->l2b_kva = ptep;
   1554 		l2b->l2b_l1slot = l1slot;
   1555 
   1556 #ifdef ARM_MMU_EXTENDED
   1557 		/*
   1558 		 * We know there will be a mapping here, so simply
   1559 		 * enter this PTP into the L1 now.
   1560 		 */
   1561 		pd_entry_t * const pdep = pmap_l1_kva(pm) + l1slot;
   1562 		pd_entry_t npde = L1_C_PROTO | l2b->l2b_pa
   1563 		    | L1_C_DOM(pmap_domain(pm));
   1564 		KASSERT(*pdep == 0);
   1565 		l1pte_setone(pdep, npde);
   1566 		PDE_SYNC(pdep);
   1567 #endif
   1568 	}
   1569 
   1570 	return (l2b);
   1571 }
   1572 
   1573 /*
   1574  * One or more mappings in the specified L2 descriptor table have just been
   1575  * invalidated.
   1576  *
   1577  * Garbage collect the metadata and descriptor table itself if necessary.
   1578  *
   1579  * The pmap lock must be acquired when this is called (not necessary
   1580  * for the kernel pmap).
   1581  */
   1582 static void
   1583 pmap_free_l2_bucket(pmap_t pm, struct l2_bucket *l2b, u_int count)
   1584 {
   1585 	KDASSERT(count <= l2b->l2b_occupancy);
   1586 
   1587 	/*
   1588 	 * Update the bucket's reference count according to how many
   1589 	 * PTEs the caller has just invalidated.
   1590 	 */
   1591 	l2b->l2b_occupancy -= count;
   1592 
   1593 	/*
   1594 	 * Note:
   1595 	 *
   1596 	 * Level 2 page tables allocated to the kernel pmap are never freed
   1597 	 * as that would require checking all Level 1 page tables and
   1598 	 * removing any references to the Level 2 page table. See also the
   1599 	 * comment elsewhere about never freeing bootstrap L2 descriptors.
   1600 	 *
   1601 	 * We make do with just invalidating the mapping in the L2 table.
   1602 	 *
   1603 	 * This isn't really a big deal in practice and, in fact, leads
   1604 	 * to a performance win over time as we don't need to continually
   1605 	 * alloc/free.
   1606 	 */
   1607 	if (l2b->l2b_occupancy > 0 || pm == pmap_kernel())
   1608 		return;
   1609 
   1610 	/*
   1611 	 * There are no more valid mappings in this level 2 page table.
   1612 	 * Go ahead and NULL-out the pointer in the bucket, then
   1613 	 * free the page table.
   1614 	 */
   1615 	const size_t l1slot = l2b->l2b_l1slot;
   1616 	pt_entry_t * const ptep = l2b->l2b_kva;
   1617 	l2b->l2b_kva = NULL;
   1618 
   1619 	pd_entry_t * const pdep = pmap_l1_kva(pm) + l1slot;
   1620 	pd_entry_t pde __diagused = *pdep;
   1621 
   1622 #ifdef ARM_MMU_EXTENDED
   1623 	/*
   1624 	 * Invalidate the L1 slot.
   1625 	 */
   1626 	KASSERT((pde & L1_TYPE_MASK) == L1_TYPE_C);
   1627 #else
   1628 	/*
   1629 	 * If the L1 slot matches the pmap's domain number, then invalidate it.
   1630 	 */
   1631 	if ((pde & (L1_C_DOM_MASK|L1_TYPE_MASK))
   1632 	    == (L1_C_DOM(pmap_domain(pm))|L1_TYPE_C)) {
   1633 #endif
   1634 		l1pte_setone(pdep, 0);
   1635 		PDE_SYNC(pdep);
   1636 #ifndef ARM_MMU_EXTENDED
   1637 	}
   1638 #endif
   1639 
   1640 	/*
   1641 	 * Release the L2 descriptor table back to the pool cache.
   1642 	 */
   1643 #if defined(PMAP_INCLUDE_PTE_SYNC) && defined(PMAP_CACHE_VIVT)
   1644 	pmap_free_l2_ptp(!pmap_is_cached(pm), ptep, l2b->l2b_pa);
   1645 #else
   1646 	pmap_free_l2_ptp(ptep, l2b->l2b_pa);
   1647 #endif
   1648 
   1649 	/*
   1650 	 * Update the reference count in the associated l2_dtable
   1651 	 */
   1652 	struct l2_dtable * const l2 = pm->pm_l2[L2_IDX(l1slot)];
   1653 	if (--l2->l2_occupancy > 0)
   1654 		return;
   1655 
   1656 	/*
   1657 	 * There are no more valid mappings in any of the Level 1
   1658 	 * slots managed by this l2_dtable. Go ahead and NULL-out
   1659 	 * the pointer in the parent pmap and free the l2_dtable.
   1660 	 */
   1661 	pm->pm_l2[L2_IDX(l1slot)] = NULL;
   1662 	pmap_free_l2_dtable(l2);
   1663 }
   1664 
   1665 /*
   1666  * Pool cache constructors for L2 descriptor tables, metadata and pmap
   1667  * structures.
   1668  */
   1669 static int
   1670 pmap_l2ptp_ctor(void *arg, void *v, int flags)
   1671 {
   1672 #ifndef PMAP_INCLUDE_PTE_SYNC
   1673 	vaddr_t va = (vaddr_t)v & ~PGOFSET;
   1674 
   1675 	/*
   1676 	 * The mappings for these page tables were initially made using
   1677 	 * pmap_kenter_pa() by the pool subsystem. Therefore, the cache-
   1678 	 * mode will not be right for page table mappings. To avoid
   1679 	 * polluting the pmap_kenter_pa() code with a special case for
   1680 	 * page tables, we simply fix up the cache-mode here if it's not
   1681 	 * correct.
   1682 	 */
   1683 	if (pte_l2_s_cache_mode != pte_l2_s_cache_mode_pt) {
   1684 		const struct l2_bucket * const l2b =
   1685 		    pmap_get_l2_bucket(pmap_kernel(), va);
   1686 		KASSERTMSG(l2b != NULL, "%#lx", va);
   1687 		pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   1688 		const pt_entry_t opte = *ptep;
   1689 
   1690 		if ((opte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
   1691 			/*
   1692 			 * Page tables must have the cache-mode set correctly.
   1693 			 */
   1694 			const pt_entry_t npte = (opte & ~L2_S_CACHE_MASK)
   1695 			    | pte_l2_s_cache_mode_pt;
   1696 			l2pte_set(ptep, npte, opte);
   1697 			PTE_SYNC(ptep);
   1698 			cpu_tlb_flushD_SE(va);
   1699 			cpu_cpwait();
   1700 		}
   1701 	}
   1702 #endif
   1703 
   1704 	memset(v, 0, L2_TABLE_SIZE_REAL);
   1705 	PTE_SYNC_RANGE(v, L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
   1706 	return (0);
   1707 }
   1708 
   1709 static int
   1710 pmap_l2dtable_ctor(void *arg, void *v, int flags)
   1711 {
   1712 
   1713 	memset(v, 0, sizeof(struct l2_dtable));
   1714 	return (0);
   1715 }
   1716 
   1717 static int
   1718 pmap_pmap_ctor(void *arg, void *v, int flags)
   1719 {
   1720 
   1721 	memset(v, 0, sizeof(struct pmap));
   1722 	return (0);
   1723 }
   1724 
   1725 static void
   1726 pmap_pinit(pmap_t pm)
   1727 {
   1728 #ifndef ARM_HAS_VBAR
   1729 	struct l2_bucket *l2b;
   1730 
   1731 	if (vector_page < KERNEL_BASE) {
   1732 		/*
   1733 		 * Map the vector page.
   1734 		 */
   1735 		pmap_enter(pm, vector_page, systempage.pv_pa,
   1736 		    VM_PROT_READ | VM_PROT_EXECUTE,
   1737 		    VM_PROT_READ | VM_PROT_EXECUTE | PMAP_WIRED);
   1738 		pmap_update(pm);
   1739 
   1740 		pm->pm_pl1vec = pmap_l1_kva(pm) + l1pte_index(vector_page);
   1741 		l2b = pmap_get_l2_bucket(pm, vector_page);
   1742 		KASSERTMSG(l2b != NULL, "%#lx", vector_page);
   1743 		pm->pm_l1vec = l2b->l2b_pa | L1_C_PROTO |
   1744 		    L1_C_DOM(pmap_domain(pm));
   1745 	} else
   1746 		pm->pm_pl1vec = NULL;
   1747 #endif
   1748 }
   1749 
   1750 #ifdef PMAP_CACHE_VIVT
   1751 /*
   1752  * Since we have a virtually indexed cache, we may need to inhibit caching if
   1753  * there is more than one mapping and at least one of them is writable.
   1754  * Since we purge the cache on every context switch, we only need to check for
   1755  * other mappings within the same pmap, or kernel_pmap.
   1756  * This function is also called when a page is unmapped, to possibly reenable
   1757  * caching on any remaining mappings.
   1758  *
   1759  * The code implements the following logic, where:
   1760  *
   1761  * KW = # of kernel read/write pages
   1762  * KR = # of kernel read only pages
   1763  * UW = # of user read/write pages
   1764  * UR = # of user read only pages
   1765  *
   1766  * KC = kernel mapping is cacheable
   1767  * UC = user mapping is cacheable
   1768  *
   1769  *               KW=0,KR=0  KW=0,KR>0  KW=1,KR=0  KW>1,KR>=0
   1770  *             +---------------------------------------------
   1771  * UW=0,UR=0   | ---        KC=1       KC=1       KC=0
   1772  * UW=0,UR>0   | UC=1       KC=1,UC=1  KC=0,UC=0  KC=0,UC=0
   1773  * UW=1,UR=0   | UC=1       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
   1774  * UW>1,UR>=0  | UC=0       KC=0,UC=0  KC=0,UC=0  KC=0,UC=0
   1775  */
   1776 
   1777 static const int pmap_vac_flags[4][4] = {
   1778 	{-1,		0,		0,		PVF_KNC},
   1779 	{0,		0,		PVF_NC,		PVF_NC},
   1780 	{0,		PVF_NC,		PVF_NC,		PVF_NC},
   1781 	{PVF_UNC,	PVF_NC,		PVF_NC,		PVF_NC}
   1782 };
   1783 
   1784 static inline int
   1785 pmap_get_vac_flags(const struct vm_page_md *md)
   1786 {
   1787 	int kidx, uidx;
   1788 
   1789 	kidx = 0;
   1790 	if (md->kro_mappings || md->krw_mappings > 1)
   1791 		kidx |= 1;
   1792 	if (md->krw_mappings)
   1793 		kidx |= 2;
   1794 
   1795 	uidx = 0;
   1796 	if (md->uro_mappings || md->urw_mappings > 1)
   1797 		uidx |= 1;
   1798 	if (md->urw_mappings)
   1799 		uidx |= 2;
   1800 
   1801 	return (pmap_vac_flags[uidx][kidx]);
   1802 }
   1803 
   1804 static inline void
   1805 pmap_vac_me_harder(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
   1806 {
   1807 	int nattr;
   1808 
   1809 	nattr = pmap_get_vac_flags(md);
   1810 
   1811 	if (nattr < 0) {
   1812 		md->pvh_attrs &= ~PVF_NC;
   1813 		return;
   1814 	}
   1815 
   1816 	if (nattr == 0 && (md->pvh_attrs & PVF_NC) == 0)
   1817 		return;
   1818 
   1819 	if (pm == pmap_kernel())
   1820 		pmap_vac_me_kpmap(md, pa, pm, va);
   1821 	else
   1822 		pmap_vac_me_user(md, pa, pm, va);
   1823 
   1824 	md->pvh_attrs = (md->pvh_attrs & ~PVF_NC) | nattr;
   1825 }
   1826 
   1827 static void
   1828 pmap_vac_me_kpmap(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
   1829 {
   1830 	u_int u_cacheable, u_entries;
   1831 	struct pv_entry *pv;
   1832 	pmap_t last_pmap = pm;
   1833 
   1834 	/*
   1835 	 * Pass one, see if there are both kernel and user pmaps for
   1836 	 * this page.  Calculate whether there are user-writable or
   1837 	 * kernel-writable pages.
   1838 	 */
   1839 	u_cacheable = 0;
   1840 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   1841 		if (pv->pv_pmap != pm && (pv->pv_flags & PVF_NC) == 0)
   1842 			u_cacheable++;
   1843 	}
   1844 
   1845 	u_entries = md->urw_mappings + md->uro_mappings;
   1846 
   1847 	/*
   1848 	 * We know we have just been updating a kernel entry, so if
   1849 	 * all user pages are already cacheable, then there is nothing
   1850 	 * further to do.
   1851 	 */
   1852 	if (md->k_mappings == 0 && u_cacheable == u_entries)
   1853 		return;
   1854 
   1855 	if (u_entries) {
   1856 		/*
   1857 		 * Scan over the list again, for each entry, if it
   1858 		 * might not be set correctly, call pmap_vac_me_user
   1859 		 * to recalculate the settings.
   1860 		 */
   1861 		SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   1862 			/*
   1863 			 * We know kernel mappings will get set
   1864 			 * correctly in other calls.  We also know
   1865 			 * that if the pmap is the same as last_pmap
   1866 			 * then we've just handled this entry.
   1867 			 */
   1868 			if (pv->pv_pmap == pm || pv->pv_pmap == last_pmap)
   1869 				continue;
   1870 
   1871 			/*
   1872 			 * If there are kernel entries and this page
   1873 			 * is writable but non-cacheable, then we can
   1874 			 * skip this entry also.
   1875 			 */
   1876 			if (md->k_mappings &&
   1877 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) ==
   1878 			    (PVF_NC | PVF_WRITE))
   1879 				continue;
   1880 
   1881 			/*
   1882 			 * Similarly if there are no kernel-writable
   1883 			 * entries and the page is already
   1884 			 * read-only/cacheable.
   1885 			 */
   1886 			if (md->krw_mappings == 0 &&
   1887 			    (pv->pv_flags & (PVF_NC | PVF_WRITE)) == 0)
   1888 				continue;
   1889 
   1890 			/*
   1891 			 * For some of the remaining cases, we know
   1892 			 * that we must recalculate, but for others we
   1893 			 * can't tell if they are correct or not, so
   1894 			 * we recalculate anyway.
   1895 			 */
   1896 			pmap_vac_me_user(md, pa, (last_pmap = pv->pv_pmap), 0);
   1897 		}
   1898 
   1899 		if (md->k_mappings == 0)
   1900 			return;
   1901 	}
   1902 
   1903 	pmap_vac_me_user(md, pa, pm, va);
   1904 }
   1905 
   1906 static void
   1907 pmap_vac_me_user(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
   1908 {
   1909 	pmap_t kpmap = pmap_kernel();
   1910 	struct pv_entry *pv, *npv = NULL;
   1911 	u_int entries = 0;
   1912 	u_int writable = 0;
   1913 	u_int cacheable_entries = 0;
   1914 	u_int kern_cacheable = 0;
   1915 	u_int other_writable = 0;
   1916 
   1917 	/*
   1918 	 * Count mappings and writable mappings in this pmap.
   1919 	 * Include kernel mappings as part of our own.
   1920 	 * Keep a pointer to the first one.
   1921 	 */
   1922 	npv = NULL;
   1923 	KASSERT(pmap_page_locked_p(md));
   1924 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   1925 		/* Count mappings in the same pmap */
   1926 		if (pm == pv->pv_pmap || kpmap == pv->pv_pmap) {
   1927 			if (entries++ == 0)
   1928 				npv = pv;
   1929 
   1930 			/* Cacheable mappings */
   1931 			if ((pv->pv_flags & PVF_NC) == 0) {
   1932 				cacheable_entries++;
   1933 				if (kpmap == pv->pv_pmap)
   1934 					kern_cacheable++;
   1935 			}
   1936 
   1937 			/* Writable mappings */
   1938 			if (pv->pv_flags & PVF_WRITE)
   1939 				++writable;
   1940 		} else
   1941 		if (pv->pv_flags & PVF_WRITE)
   1942 			other_writable = 1;
   1943 	}
   1944 
   1945 	/*
   1946 	 * Enable or disable caching as necessary.
   1947 	 * Note: the first entry might be part of the kernel pmap,
   1948 	 * so we can't assume this is indicative of the state of the
   1949 	 * other (maybe non-kpmap) entries.
   1950 	 */
   1951 	if ((entries > 1 && writable) ||
   1952 	    (entries > 0 && pm == kpmap && other_writable)) {
   1953 		if (cacheable_entries == 0) {
   1954 			return;
   1955 		}
   1956 
   1957 		for (pv = npv; pv; pv = SLIST_NEXT(pv, pv_link)) {
   1958 			if ((pm != pv->pv_pmap && kpmap != pv->pv_pmap) ||
   1959 			    (pv->pv_flags & PVF_NC))
   1960 				continue;
   1961 
   1962 			pv->pv_flags |= PVF_NC;
   1963 
   1964 			struct l2_bucket * const l2b
   1965 			    = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
   1966 			KASSERTMSG(l2b != NULL, "%#lx", va);
   1967 			pt_entry_t * const ptep
   1968 			    = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
   1969 			const pt_entry_t opte = *ptep;
   1970 			pt_entry_t npte = opte & ~L2_S_CACHE_MASK;
   1971 
   1972 			if ((va != pv->pv_va || pm != pv->pv_pmap)
   1973 			    && l2pte_valid_p(opte)) {
   1974 #ifdef PMAP_CACHE_VIVT
   1975 				pmap_cache_wbinv_page(pv->pv_pmap, pv->pv_va,
   1976 				    true, pv->pv_flags);
   1977 #endif
   1978 				pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va,
   1979 				    pv->pv_flags);
   1980 			}
   1981 
   1982 			l2pte_set(ptep, npte, opte);
   1983 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
   1984 		}
   1985 		cpu_cpwait();
   1986 	} else
   1987 	if (entries > cacheable_entries) {
   1988 		/*
   1989 		 * Turn cacheing back on for some pages.  If it is a kernel
   1990 		 * page, only do so if there are no other writable pages.
   1991 		 */
   1992 		for (pv = npv; pv; pv = SLIST_NEXT(pv, pv_link)) {
   1993 			if (!(pv->pv_flags & PVF_NC) || (pm != pv->pv_pmap &&
   1994 			    (kpmap != pv->pv_pmap || other_writable)))
   1995 				continue;
   1996 
   1997 			pv->pv_flags &= ~PVF_NC;
   1998 
   1999 			struct l2_bucket * const l2b
   2000 			    = pmap_get_l2_bucket(pv->pv_pmap, pv->pv_va);
   2001 			KASSERTMSG(l2b != NULL, "%#lx", va);
   2002 			pt_entry_t * const ptep
   2003 			    = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
   2004 			const pt_entry_t opte = *ptep;
   2005 			pt_entry_t npte = (opte & ~L2_S_CACHE_MASK)
   2006 			    | pte_l2_s_cache_mode;
   2007 
   2008 			if (l2pte_valid_p(opte)) {
   2009 				pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va,
   2010 				    pv->pv_flags);
   2011 			}
   2012 
   2013 			l2pte_set(ptep, npte, opte);
   2014 			PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
   2015 		}
   2016 	}
   2017 }
   2018 #endif
   2019 
   2020 #ifdef PMAP_CACHE_VIPT
   2021 static void
   2022 pmap_vac_me_harder(struct vm_page_md *md, paddr_t pa, pmap_t pm, vaddr_t va)
   2023 {
   2024 #ifndef ARM_MMU_EXTENDED
   2025 	struct pv_entry *pv;
   2026 	vaddr_t tst_mask;
   2027 	bool bad_alias;
   2028 	const u_int
   2029 	    rw_mappings = md->urw_mappings + md->krw_mappings,
   2030 	    ro_mappings = md->uro_mappings + md->kro_mappings;
   2031 
   2032 	/* do we need to do anything? */
   2033 	if (arm_cache_prefer_mask == 0)
   2034 		return;
   2035 
   2036 	NPDEBUG(PDB_VAC, printf("pmap_vac_me_harder: md=%p, pmap=%p va=%08lx\n",
   2037 	    md, pm, va));
   2038 
   2039 	KASSERT(!va || pm);
   2040 	KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2041 
   2042 	/* Already a conflict? */
   2043 	if (__predict_false(md->pvh_attrs & PVF_NC)) {
   2044 		/* just an add, things are already non-cached */
   2045 		KASSERT(!(md->pvh_attrs & PVF_DIRTY));
   2046 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
   2047 		bad_alias = false;
   2048 		if (va) {
   2049 			PMAPCOUNT(vac_color_none);
   2050 			bad_alias = true;
   2051 			KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2052 			goto fixup;
   2053 		}
   2054 		pv = SLIST_FIRST(&md->pvh_list);
   2055 		/* the list can't be empty because it would be cachable */
   2056 		if (md->pvh_attrs & PVF_KMPAGE) {
   2057 			tst_mask = md->pvh_attrs;
   2058 		} else {
   2059 			KASSERT(pv);
   2060 			tst_mask = pv->pv_va;
   2061 			pv = SLIST_NEXT(pv, pv_link);
   2062 		}
   2063 		/*
   2064 		 * Only check for a bad alias if we have writable mappings.
   2065 		 */
   2066 		tst_mask &= arm_cache_prefer_mask;
   2067 		if (rw_mappings > 0) {
   2068 			for (; pv && !bad_alias; pv = SLIST_NEXT(pv, pv_link)) {
   2069 				/* if there's a bad alias, stop checking. */
   2070 				if (tst_mask != (pv->pv_va & arm_cache_prefer_mask))
   2071 					bad_alias = true;
   2072 			}
   2073 			md->pvh_attrs |= PVF_WRITE;
   2074 			if (!bad_alias)
   2075 				md->pvh_attrs |= PVF_DIRTY;
   2076 		} else {
   2077 			/*
   2078 			 * We have only read-only mappings.  Let's see if there
   2079 			 * are multiple colors in use or if we mapped a KMPAGE.
   2080 			 * If the latter, we have a bad alias.  If the former,
   2081 			 * we need to remember that.
   2082 			 */
   2083 			for (; pv; pv = SLIST_NEXT(pv, pv_link)) {
   2084 				if (tst_mask != (pv->pv_va & arm_cache_prefer_mask)) {
   2085 					if (md->pvh_attrs & PVF_KMPAGE)
   2086 						bad_alias = true;
   2087 					break;
   2088 				}
   2089 			}
   2090 			md->pvh_attrs &= ~PVF_WRITE;
   2091 			/*
   2092 			 * No KMPAGE and we exited early, so we must have
   2093 			 * multiple color mappings.
   2094 			 */
   2095 			if (!bad_alias && pv != NULL)
   2096 				md->pvh_attrs |= PVF_MULTCLR;
   2097 		}
   2098 
   2099 		/* If no conflicting colors, set everything back to cached */
   2100 		if (!bad_alias) {
   2101 #ifdef DEBUG
   2102 			if ((md->pvh_attrs & PVF_WRITE)
   2103 			    || ro_mappings < 2) {
   2104 				SLIST_FOREACH(pv, &md->pvh_list, pv_link)
   2105 					KDASSERT(((tst_mask ^ pv->pv_va) & arm_cache_prefer_mask) == 0);
   2106 			}
   2107 #endif
   2108 			md->pvh_attrs &= (PAGE_SIZE - 1) & ~PVF_NC;
   2109 			md->pvh_attrs |= tst_mask | PVF_COLORED;
   2110 			/*
   2111 			 * Restore DIRTY bit if page is modified
   2112 			 */
   2113 			if (md->pvh_attrs & PVF_DMOD)
   2114 				md->pvh_attrs |= PVF_DIRTY;
   2115 			PMAPCOUNT(vac_color_restore);
   2116 		} else {
   2117 			KASSERT(SLIST_FIRST(&md->pvh_list) != NULL);
   2118 			KASSERT(SLIST_NEXT(SLIST_FIRST(&md->pvh_list), pv_link) != NULL);
   2119 		}
   2120 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2121 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2122 	} else if (!va) {
   2123 		KASSERT(pmap_is_page_colored_p(md));
   2124 		KASSERT(!(md->pvh_attrs & PVF_WRITE)
   2125 		    || (md->pvh_attrs & PVF_DIRTY));
   2126 		if (rw_mappings == 0) {
   2127 			md->pvh_attrs &= ~PVF_WRITE;
   2128 			if (ro_mappings == 1
   2129 			    && (md->pvh_attrs & PVF_MULTCLR)) {
   2130 				/*
   2131 				 * If this is the last readonly mapping
   2132 				 * but it doesn't match the current color
   2133 				 * for the page, change the current color
   2134 				 * to match this last readonly mapping.
   2135 				 */
   2136 				pv = SLIST_FIRST(&md->pvh_list);
   2137 				tst_mask = (md->pvh_attrs ^ pv->pv_va)
   2138 				    & arm_cache_prefer_mask;
   2139 				if (tst_mask) {
   2140 					md->pvh_attrs ^= tst_mask;
   2141 					PMAPCOUNT(vac_color_change);
   2142 				}
   2143 			}
   2144 		}
   2145 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2146 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2147 		return;
   2148 	} else if (!pmap_is_page_colored_p(md)) {
   2149 		/* not colored so we just use its color */
   2150 		KASSERT(md->pvh_attrs & (PVF_WRITE|PVF_DIRTY));
   2151 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
   2152 		PMAPCOUNT(vac_color_new);
   2153 		md->pvh_attrs &= PAGE_SIZE - 1;
   2154 		md->pvh_attrs |= PVF_COLORED
   2155 		    | (va & arm_cache_prefer_mask)
   2156 		    | (rw_mappings > 0 ? PVF_WRITE : 0);
   2157 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2158 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2159 		return;
   2160 	} else if (((md->pvh_attrs ^ va) & arm_cache_prefer_mask) == 0) {
   2161 		bad_alias = false;
   2162 		if (rw_mappings > 0) {
   2163 			/*
   2164 			 * We now have writeable mappings and if we have
   2165 			 * readonly mappings in more than once color, we have
   2166 			 * an aliasing problem.  Regardless mark the page as
   2167 			 * writeable.
   2168 			 */
   2169 			if (md->pvh_attrs & PVF_MULTCLR) {
   2170 				if (ro_mappings < 2) {
   2171 					/*
   2172 					 * If we only have less than two
   2173 					 * read-only mappings, just flush the
   2174 					 * non-primary colors from the cache.
   2175 					 */
   2176 					pmap_flush_page(md, pa,
   2177 					    PMAP_FLUSH_SECONDARY);
   2178 				} else {
   2179 					bad_alias = true;
   2180 				}
   2181 			}
   2182 			md->pvh_attrs |= PVF_WRITE;
   2183 		}
   2184 		/* If no conflicting colors, set everything back to cached */
   2185 		if (!bad_alias) {
   2186 #ifdef DEBUG
   2187 			if (rw_mappings > 0
   2188 			    || (md->pvh_attrs & PMAP_KMPAGE)) {
   2189 				tst_mask = md->pvh_attrs & arm_cache_prefer_mask;
   2190 				SLIST_FOREACH(pv, &md->pvh_list, pv_link)
   2191 					KDASSERT(((tst_mask ^ pv->pv_va) & arm_cache_prefer_mask) == 0);
   2192 			}
   2193 #endif
   2194 			if (SLIST_EMPTY(&md->pvh_list))
   2195 				PMAPCOUNT(vac_color_reuse);
   2196 			else
   2197 				PMAPCOUNT(vac_color_ok);
   2198 
   2199 			/* matching color, just return */
   2200 			KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2201 			KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2202 			return;
   2203 		}
   2204 		KASSERT(SLIST_FIRST(&md->pvh_list) != NULL);
   2205 		KASSERT(SLIST_NEXT(SLIST_FIRST(&md->pvh_list), pv_link) != NULL);
   2206 
   2207 		/* color conflict.  evict from cache. */
   2208 
   2209 		pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
   2210 		md->pvh_attrs &= ~PVF_COLORED;
   2211 		md->pvh_attrs |= PVF_NC;
   2212 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2213 		KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
   2214 		PMAPCOUNT(vac_color_erase);
   2215 	} else if (rw_mappings == 0
   2216 		   && (md->pvh_attrs & PVF_KMPAGE) == 0) {
   2217 		KASSERT((md->pvh_attrs & PVF_WRITE) == 0);
   2218 
   2219 		/*
   2220 		 * If the page has dirty cache lines, clean it.
   2221 		 */
   2222 		if (md->pvh_attrs & PVF_DIRTY)
   2223 			pmap_flush_page(md, pa, PMAP_CLEAN_PRIMARY);
   2224 
   2225 		/*
   2226 		 * If this is the first remapping (we know that there are no
   2227 		 * writeable mappings), then this is a simple color change.
   2228 		 * Otherwise this is a seconary r/o mapping, which means
   2229 		 * we don't have to do anything.
   2230 		 */
   2231 		if (ro_mappings == 1) {
   2232 			KASSERT(((md->pvh_attrs ^ va) & arm_cache_prefer_mask) != 0);
   2233 			md->pvh_attrs &= PAGE_SIZE - 1;
   2234 			md->pvh_attrs |= (va & arm_cache_prefer_mask);
   2235 			PMAPCOUNT(vac_color_change);
   2236 		} else {
   2237 			PMAPCOUNT(vac_color_blind);
   2238 		}
   2239 		md->pvh_attrs |= PVF_MULTCLR;
   2240 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2241 		KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2242 		return;
   2243 	} else {
   2244 		if (rw_mappings > 0)
   2245 			md->pvh_attrs |= PVF_WRITE;
   2246 
   2247 		/* color conflict.  evict from cache. */
   2248 		pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
   2249 
   2250 		/* the list can't be empty because this was a enter/modify */
   2251 		pv = SLIST_FIRST(&md->pvh_list);
   2252 		if ((md->pvh_attrs & PVF_KMPAGE) == 0) {
   2253 			KASSERT(pv);
   2254 			/*
   2255 			 * If there's only one mapped page, change color to the
   2256 			 * page's new color and return.  Restore the DIRTY bit
   2257 			 * that was erased by pmap_flush_page.
   2258 			 */
   2259 			if (SLIST_NEXT(pv, pv_link) == NULL) {
   2260 				md->pvh_attrs &= PAGE_SIZE - 1;
   2261 				md->pvh_attrs |= (va & arm_cache_prefer_mask);
   2262 				if (md->pvh_attrs & PVF_DMOD)
   2263 					md->pvh_attrs |= PVF_DIRTY;
   2264 				PMAPCOUNT(vac_color_change);
   2265 				KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2266 				KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2267 				KASSERT(!(md->pvh_attrs & PVF_MULTCLR));
   2268 				return;
   2269 			}
   2270 		}
   2271 		bad_alias = true;
   2272 		md->pvh_attrs &= ~PVF_COLORED;
   2273 		md->pvh_attrs |= PVF_NC;
   2274 		PMAPCOUNT(vac_color_erase);
   2275 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   2276 	}
   2277 
   2278   fixup:
   2279 	KASSERT((rw_mappings == 0) == !(md->pvh_attrs & PVF_WRITE));
   2280 
   2281 	/*
   2282 	 * Turn cacheing on/off for all pages.
   2283 	 */
   2284 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   2285 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pv->pv_pmap,
   2286 		    pv->pv_va);
   2287 		KASSERTMSG(l2b != NULL, "%#lx", va);
   2288 		pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
   2289 		const pt_entry_t opte = *ptep;
   2290 		pt_entry_t npte = opte & ~L2_S_CACHE_MASK;
   2291 		if (bad_alias) {
   2292 			pv->pv_flags |= PVF_NC;
   2293 		} else {
   2294 			pv->pv_flags &= ~PVF_NC;
   2295 			npte |= pte_l2_s_cache_mode;
   2296 		}
   2297 
   2298 		if (opte == npte)	/* only update is there's a change */
   2299 			continue;
   2300 
   2301 		if (l2pte_valid_p(opte)) {
   2302 			pmap_tlb_flush_SE(pv->pv_pmap, pv->pv_va, pv->pv_flags);
   2303 		}
   2304 
   2305 		l2pte_set(ptep, npte, opte);
   2306 		PTE_SYNC_CURRENT(pv->pv_pmap, ptep);
   2307 	}
   2308 #endif /* !ARM_MMU_EXTENDED */
   2309 }
   2310 #endif	/* PMAP_CACHE_VIPT */
   2311 
   2312 
   2313 /*
   2314  * Modify pte bits for all ptes corresponding to the given physical address.
   2315  * We use `maskbits' rather than `clearbits' because we're always passing
   2316  * constants and the latter would require an extra inversion at run-time.
   2317  */
   2318 static void
   2319 pmap_clearbit(struct vm_page_md *md, paddr_t pa, u_int maskbits)
   2320 {
   2321 	struct pv_entry *pv;
   2322 #ifdef PMAP_CACHE_VIPT
   2323 	const bool want_syncicache = PV_IS_EXEC_P(md->pvh_attrs);
   2324 	bool need_syncicache = false;
   2325 #ifdef ARM_MMU_EXTENDED
   2326 	const u_int execbits = (maskbits & PVF_EXEC) ? L2_XS_XN : 0;
   2327 #else
   2328 	const u_int execbits = 0;
   2329 	bool need_vac_me_harder = false;
   2330 #endif
   2331 #else
   2332 	const u_int execbits = 0;
   2333 #endif
   2334 
   2335 	NPDEBUG(PDB_BITS,
   2336 	    printf("pmap_clearbit: md %p mask 0x%x\n",
   2337 	    md, maskbits));
   2338 
   2339 #ifdef PMAP_CACHE_VIPT
   2340 	/*
   2341 	 * If we might want to sync the I-cache and we've modified it,
   2342 	 * then we know we definitely need to sync or discard it.
   2343 	 */
   2344 	if (want_syncicache) {
   2345 		if (md->pvh_attrs & PVF_MOD) {
   2346 			need_syncicache = true;
   2347 		}
   2348 	}
   2349 #endif
   2350 	KASSERT(pmap_page_locked_p(md));
   2351 
   2352 	/*
   2353 	 * Clear saved attributes (modify, reference)
   2354 	 */
   2355 	md->pvh_attrs &= ~(maskbits & (PVF_MOD | PVF_REF));
   2356 
   2357 	if (SLIST_EMPTY(&md->pvh_list)) {
   2358 #if defined(PMAP_CACHE_VIPT)
   2359 		if (need_syncicache) {
   2360 			/*
   2361 			 * No one has it mapped, so just discard it.  The next
   2362 			 * exec remapping will cause it to be synced.
   2363 			 */
   2364 			md->pvh_attrs &= ~PVF_EXEC;
   2365 			PMAPCOUNT(exec_discarded_clearbit);
   2366 		}
   2367 #endif
   2368 		return;
   2369 	}
   2370 
   2371 	/*
   2372 	 * Loop over all current mappings setting/clearing as appropos
   2373 	 */
   2374 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   2375 		pmap_t pm = pv->pv_pmap;
   2376 		const vaddr_t va = pv->pv_va;
   2377 		const u_int oflags = pv->pv_flags;
   2378 #ifndef ARM_MMU_EXTENDED
   2379 		/*
   2380 		 * Kernel entries are unmanaged and as such not to be changed.
   2381 		 */
   2382 		if (PV_IS_KENTRY_P(oflags))
   2383 			continue;
   2384 #endif
   2385 		pv->pv_flags &= ~maskbits;
   2386 
   2387 		pmap_release_page_lock(md);
   2388 		pmap_acquire_pmap_lock(pm);
   2389 
   2390 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pm, va);
   2391 		if (l2b == NULL) {
   2392 			pmap_release_pmap_lock(pm);
   2393 			pmap_acquire_page_lock(md);
   2394 			continue;
   2395 		}
   2396 		KASSERTMSG(l2b != NULL, "%#lx", va);
   2397 
   2398 		pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   2399 		const pt_entry_t opte = *ptep;
   2400 		pt_entry_t npte = opte | execbits;
   2401 
   2402 #ifdef ARM_MMU_EXTENDED
   2403 		KASSERT((opte & L2_XS_nG) == (pm == pmap_kernel() ? 0 : L2_XS_nG));
   2404 #endif
   2405 
   2406 		NPDEBUG(PDB_BITS,
   2407 		    printf( "%s: pv %p, pm %p, va 0x%08lx, flag 0x%x\n",
   2408 			__func__, pv, pm, va, oflags));
   2409 
   2410 		if (maskbits & (PVF_WRITE|PVF_MOD)) {
   2411 #ifdef PMAP_CACHE_VIVT
   2412 			if ((oflags & PVF_NC)) {
   2413 				/*
   2414 				 * Entry is not cacheable:
   2415 				 *
   2416 				 * Don't turn caching on again if this is a
   2417 				 * modified emulation. This would be
   2418 				 * inconsitent with the settings created by
   2419 				 * pmap_vac_me_harder(). Otherwise, it's safe
   2420 				 * to re-enable cacheing.
   2421 				 *
   2422 				 * There's no need to call pmap_vac_me_harder()
   2423 				 * here: all pages are losing their write
   2424 				 * permission.
   2425 				 */
   2426 				if (maskbits & PVF_WRITE) {
   2427 					npte |= pte_l2_s_cache_mode;
   2428 					pv->pv_flags &= ~PVF_NC;
   2429 				}
   2430 			} else
   2431 			if (l2pte_writable_p(opte)) {
   2432 				/*
   2433 				 * Entry is writable/cacheable: check if pmap
   2434 				 * is current if it is flush it, otherwise it
   2435 				 * won't be in the cache
   2436 				 */
   2437 				pmap_cache_wbinv_page(pm, va,
   2438 				    (maskbits & PVF_REF) != 0,
   2439 				    oflags|PVF_WRITE);
   2440 			}
   2441 #endif
   2442 
   2443 			/* make the pte read only */
   2444 			npte = l2pte_set_readonly(npte);
   2445 
   2446 			pmap_acquire_page_lock(md);
   2447 #ifdef MULTIPROCESSOR
   2448 			pv = pmap_find_pv(md, pm, va);
   2449 #endif
   2450 			if (pv != NULL && (maskbits & oflags & PVF_WRITE)) {
   2451 				/*
   2452 				 * Keep alias accounting up to date
   2453 				 */
   2454 				if (pm == pmap_kernel()) {
   2455 					md->krw_mappings--;
   2456 					md->kro_mappings++;
   2457 				} else {
   2458 					md->urw_mappings--;
   2459 					md->uro_mappings++;
   2460 				}
   2461 #ifdef PMAP_CACHE_VIPT
   2462 				if (arm_cache_prefer_mask != 0) {
   2463 					if (md->urw_mappings + md->krw_mappings == 0) {
   2464 						md->pvh_attrs &= ~PVF_WRITE;
   2465 					} else {
   2466 						PMAP_VALIDATE_MD_PAGE(md);
   2467 					}
   2468 				}
   2469 				if (want_syncicache)
   2470 					need_syncicache = true;
   2471 #ifndef ARM_MMU_EXTENDED
   2472 				need_vac_me_harder = true;
   2473 #endif
   2474 #endif /* PMAP_CACHE_VIPT */
   2475 			}
   2476 			pmap_release_page_lock(md);
   2477 		}
   2478 
   2479 		if (maskbits & PVF_REF) {
   2480 			if (true
   2481 #ifndef ARM_MMU_EXTENDED
   2482 			    && (oflags & PVF_NC) == 0
   2483 #endif
   2484 			    && (maskbits & (PVF_WRITE|PVF_MOD)) == 0
   2485 			    && l2pte_valid_p(npte)) {
   2486 #ifdef PMAP_CACHE_VIVT
   2487 				/*
   2488 				 * Check npte here; we may have already
   2489 				 * done the wbinv above, and the validity
   2490 				 * of the PTE is the same for opte and
   2491 				 * npte.
   2492 				 */
   2493 				pmap_cache_wbinv_page(pm, va, true, oflags);
   2494 #endif
   2495 			}
   2496 
   2497 			/*
   2498 			 * Make the PTE invalid so that we will take a
   2499 			 * page fault the next time the mapping is
   2500 			 * referenced.
   2501 			 */
   2502 			npte &= ~L2_TYPE_MASK;
   2503 			npte |= L2_TYPE_INV;
   2504 		}
   2505 
   2506 		if (npte != opte) {
   2507 			l2pte_reset(ptep);
   2508 			PTE_SYNC(ptep);
   2509 
   2510 			/* Flush the TLB entry if a current pmap. */
   2511 			pmap_tlb_flush_SE(pm, va, oflags);
   2512 
   2513 			l2pte_set(ptep, npte, 0);
   2514 			PTE_SYNC(ptep);
   2515 		}
   2516 
   2517 		pmap_release_pmap_lock(pm);
   2518 		pmap_acquire_page_lock(md);
   2519 
   2520 		NPDEBUG(PDB_BITS,
   2521 		    printf("pmap_clearbit: pm %p va 0x%lx opte 0x%08x npte 0x%08x\n",
   2522 		    pm, va, opte, npte));
   2523 	}
   2524 
   2525 #if defined(PMAP_CACHE_VIPT)
   2526 	/*
   2527 	 * If we need to sync the I-cache and we haven't done it yet, do it.
   2528 	 */
   2529 	if (need_syncicache) {
   2530 		pmap_release_page_lock(md);
   2531 		pmap_syncicache_page(md, pa);
   2532 		pmap_acquire_page_lock(md);
   2533 		PMAPCOUNT(exec_synced_clearbit);
   2534 	}
   2535 #ifndef ARM_MMU_EXTENDED
   2536 	/*
   2537 	 * If we are changing this to read-only, we need to call vac_me_harder
   2538 	 * so we can change all the read-only pages to cacheable.  We pretend
   2539 	 * this as a page deletion.
   2540 	 */
   2541 	if (need_vac_me_harder) {
   2542 		if (md->pvh_attrs & PVF_NC)
   2543 			pmap_vac_me_harder(md, pa, NULL, 0);
   2544 	}
   2545 #endif /* !ARM_MMU_EXTENDED */
   2546 #endif /* PMAP_CACHE_VIPT */
   2547 }
   2548 
   2549 /*
   2550  * pmap_clean_page()
   2551  *
   2552  * This is a local function used to work out the best strategy to clean
   2553  * a single page referenced by its entry in the PV table. It's used by
   2554  * pmap_copy_page, pmap_zero_page and maybe some others later on.
   2555  *
   2556  * Its policy is effectively:
   2557  *  o If there are no mappings, we don't bother doing anything with the cache.
   2558  *  o If there is one mapping, we clean just that page.
   2559  *  o If there are multiple mappings, we clean the entire cache.
   2560  *
   2561  * So that some functions can be further optimised, it returns 0 if it didn't
   2562  * clean the entire cache, or 1 if it did.
   2563  *
   2564  * XXX One bug in this routine is that if the pv_entry has a single page
   2565  * mapped at 0x00000000 a whole cache clean will be performed rather than
   2566  * just the 1 page. Since this should not occur in everyday use and if it does
   2567  * it will just result in not the most efficient clean for the page.
   2568  */
   2569 #ifdef PMAP_CACHE_VIVT
   2570 static bool
   2571 pmap_clean_page(struct vm_page_md *md, bool is_src)
   2572 {
   2573 	struct pv_entry *pv;
   2574 	pmap_t pm_to_clean = NULL;
   2575 	bool cache_needs_cleaning = false;
   2576 	vaddr_t page_to_clean = 0;
   2577 	u_int flags = 0;
   2578 
   2579 	/*
   2580 	 * Since we flush the cache each time we change to a different
   2581 	 * user vmspace, we only need to flush the page if it is in the
   2582 	 * current pmap.
   2583 	 */
   2584 	KASSERT(pmap_page_locked_p(md));
   2585 	SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   2586 		if (pmap_is_current(pv->pv_pmap)) {
   2587 			flags |= pv->pv_flags;
   2588 			/*
   2589 			 * The page is mapped non-cacheable in
   2590 			 * this map.  No need to flush the cache.
   2591 			 */
   2592 			if (pv->pv_flags & PVF_NC) {
   2593 #ifdef DIAGNOSTIC
   2594 				KASSERT(!cache_needs_cleaning);
   2595 #endif
   2596 				break;
   2597 			} else if (is_src && (pv->pv_flags & PVF_WRITE) == 0)
   2598 				continue;
   2599 			if (cache_needs_cleaning) {
   2600 				page_to_clean = 0;
   2601 				break;
   2602 			} else {
   2603 				page_to_clean = pv->pv_va;
   2604 				pm_to_clean = pv->pv_pmap;
   2605 			}
   2606 			cache_needs_cleaning = true;
   2607 		}
   2608 	}
   2609 
   2610 	if (page_to_clean) {
   2611 		pmap_cache_wbinv_page(pm_to_clean, page_to_clean,
   2612 		    !is_src, flags | PVF_REF);
   2613 	} else if (cache_needs_cleaning) {
   2614 		pmap_t const pm = curproc->p_vmspace->vm_map.pmap;
   2615 
   2616 		pmap_cache_wbinv_all(pm, flags);
   2617 		return true;
   2618 	}
   2619 	return false;
   2620 }
   2621 #endif
   2622 
   2623 #ifdef PMAP_CACHE_VIPT
   2624 /*
   2625  * Sync a page with the I-cache.  Since this is a VIPT, we must pick the
   2626  * right cache alias to make sure we flush the right stuff.
   2627  */
   2628 void
   2629 pmap_syncicache_page(struct vm_page_md *md, paddr_t pa)
   2630 {
   2631 	pmap_t kpm = pmap_kernel();
   2632 	const size_t way_size = arm_pcache.icache_type == CACHE_TYPE_PIPT
   2633 	    ? PAGE_SIZE
   2634 	    : arm_pcache.icache_way_size;
   2635 
   2636 	NPDEBUG(PDB_EXEC, printf("pmap_syncicache_page: md=%p (attrs=%#x)\n",
   2637 	    md, md->pvh_attrs));
   2638 	/*
   2639 	 * No need to clean the page if it's non-cached.
   2640 	 */
   2641 #ifndef ARM_MMU_EXTENDED
   2642 	if (md->pvh_attrs & PVF_NC)
   2643 		return;
   2644 	KASSERT(arm_cache_prefer_mask == 0 || md->pvh_attrs & PVF_COLORED);
   2645 #endif
   2646 
   2647 	pt_entry_t * const ptep = cpu_cdst_pte(0);
   2648 	const vaddr_t dstp = cpu_cdstp(0);
   2649 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   2650 	if (way_size <= PAGE_SIZE) {
   2651 		bool ok = false;
   2652 		vaddr_t vdstp = pmap_direct_mapped_phys(pa, &ok, dstp);
   2653 		if (ok) {
   2654 			cpu_icache_sync_range(vdstp, way_size);
   2655 			return;
   2656 		}
   2657 	}
   2658 #endif
   2659 
   2660 	/*
   2661 	 * We don't worry about the color of the exec page, we map the
   2662 	 * same page to pages in the way and then do the icache_sync on
   2663 	 * the entire way making sure we are cleaned.
   2664 	 */
   2665 	const pt_entry_t npte = L2_S_PROTO | pa | pte_l2_s_cache_mode
   2666 	    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ|VM_PROT_WRITE);
   2667 
   2668 	for (size_t i = 0, j = 0; i < way_size;
   2669 	     i += PAGE_SIZE, j += PAGE_SIZE / L2_S_SIZE) {
   2670 		l2pte_reset(ptep + j);
   2671 		PTE_SYNC(ptep + j);
   2672 
   2673 		pmap_tlb_flush_SE(kpm, dstp + i, PVF_REF | PVF_EXEC);
   2674 		/*
   2675 		 * Set up a PTE with to flush these cache lines.
   2676 		 */
   2677 		l2pte_set(ptep + j, npte, 0);
   2678 	}
   2679 	PTE_SYNC_RANGE(ptep, way_size / L2_S_SIZE);
   2680 
   2681 	/*
   2682 	 * Flush it.
   2683 	 */
   2684 	cpu_icache_sync_range(dstp, way_size);
   2685 
   2686 	for (size_t i = 0, j = 0; i < way_size;
   2687 	     i += PAGE_SIZE, j += PAGE_SIZE / L2_S_SIZE) {
   2688 		/*
   2689 		 * Unmap the page(s).
   2690 		 */
   2691 		l2pte_reset(ptep + j);
   2692 		pmap_tlb_flush_SE(kpm, dstp + i, PVF_REF | PVF_EXEC);
   2693 	}
   2694 	PTE_SYNC_RANGE(ptep, way_size / L2_S_SIZE);
   2695 
   2696 	md->pvh_attrs |= PVF_EXEC;
   2697 	PMAPCOUNT(exec_synced);
   2698 }
   2699 
   2700 #ifndef ARM_MMU_EXTENDED
   2701 void
   2702 pmap_flush_page(struct vm_page_md *md, paddr_t pa, enum pmap_flush_op flush)
   2703 {
   2704 	vsize_t va_offset, end_va;
   2705 	bool wbinv_p;
   2706 
   2707 	if (arm_cache_prefer_mask == 0)
   2708 		return;
   2709 
   2710 	switch (flush) {
   2711 	case PMAP_FLUSH_PRIMARY:
   2712 		if (md->pvh_attrs & PVF_MULTCLR) {
   2713 			va_offset = 0;
   2714 			end_va = arm_cache_prefer_mask;
   2715 			md->pvh_attrs &= ~PVF_MULTCLR;
   2716 			PMAPCOUNT(vac_flush_lots);
   2717 		} else {
   2718 			va_offset = md->pvh_attrs & arm_cache_prefer_mask;
   2719 			end_va = va_offset;
   2720 			PMAPCOUNT(vac_flush_one);
   2721 		}
   2722 		/*
   2723 		 * Mark that the page is no longer dirty.
   2724 		 */
   2725 		md->pvh_attrs &= ~PVF_DIRTY;
   2726 		wbinv_p = true;
   2727 		break;
   2728 	case PMAP_FLUSH_SECONDARY:
   2729 		va_offset = 0;
   2730 		end_va = arm_cache_prefer_mask;
   2731 		wbinv_p = true;
   2732 		md->pvh_attrs &= ~PVF_MULTCLR;
   2733 		PMAPCOUNT(vac_flush_lots);
   2734 		break;
   2735 	case PMAP_CLEAN_PRIMARY:
   2736 		va_offset = md->pvh_attrs & arm_cache_prefer_mask;
   2737 		end_va = va_offset;
   2738 		wbinv_p = false;
   2739 		/*
   2740 		 * Mark that the page is no longer dirty.
   2741 		 */
   2742 		if ((md->pvh_attrs & PVF_DMOD) == 0)
   2743 			md->pvh_attrs &= ~PVF_DIRTY;
   2744 		PMAPCOUNT(vac_clean_one);
   2745 		break;
   2746 	default:
   2747 		return;
   2748 	}
   2749 
   2750 	KASSERT(!(md->pvh_attrs & PVF_NC));
   2751 
   2752 	NPDEBUG(PDB_VAC, printf("pmap_flush_page: md=%p (attrs=%#x)\n",
   2753 	    md, md->pvh_attrs));
   2754 
   2755 	const size_t scache_line_size = arm_scache.dcache_line_size;
   2756 
   2757 	for (; va_offset <= end_va; va_offset += PAGE_SIZE) {
   2758 		pt_entry_t * const ptep = cpu_cdst_pte(va_offset);
   2759 		const vaddr_t dstp = cpu_cdstp(va_offset);
   2760 		const pt_entry_t opte = *ptep;
   2761 
   2762 		if (flush == PMAP_FLUSH_SECONDARY
   2763 		    && va_offset == (md->pvh_attrs & arm_cache_prefer_mask))
   2764 			continue;
   2765 
   2766 		pmap_tlb_flush_SE(pmap_kernel(), dstp, PVF_REF | PVF_EXEC);
   2767 		/*
   2768 		 * Set up a PTE with the right coloring to flush
   2769 		 * existing cache entries.
   2770 		 */
   2771 		const pt_entry_t npte = L2_S_PROTO
   2772 		    | pa
   2773 		    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ|VM_PROT_WRITE)
   2774 		    | pte_l2_s_cache_mode;
   2775 		l2pte_set(ptep, npte, opte);
   2776 		PTE_SYNC(ptep);
   2777 
   2778 		/*
   2779 		 * Flush it.  Make sure to flush secondary cache too since
   2780 		 * bus_dma will ignore uncached pages.
   2781 		 */
   2782 		if (scache_line_size != 0) {
   2783 			cpu_dcache_wb_range(dstp, PAGE_SIZE);
   2784 			if (wbinv_p) {
   2785 				cpu_sdcache_wbinv_range(dstp, pa, PAGE_SIZE);
   2786 				cpu_dcache_inv_range(dstp, PAGE_SIZE);
   2787 			} else {
   2788 				cpu_sdcache_wb_range(dstp, pa, PAGE_SIZE);
   2789 			}
   2790 		} else {
   2791 			if (wbinv_p) {
   2792 				cpu_dcache_wbinv_range(dstp, PAGE_SIZE);
   2793 			} else {
   2794 				cpu_dcache_wb_range(dstp, PAGE_SIZE);
   2795 			}
   2796 		}
   2797 
   2798 		/*
   2799 		 * Restore the page table entry since we might have interrupted
   2800 		 * pmap_zero_page or pmap_copy_page which was already using
   2801 		 * this pte.
   2802 		 */
   2803 		if (opte) {
   2804 			l2pte_set(ptep, opte, npte);
   2805 		} else {
   2806 			l2pte_reset(ptep);
   2807 		}
   2808 		PTE_SYNC(ptep);
   2809 		pmap_tlb_flush_SE(pmap_kernel(), dstp, PVF_REF | PVF_EXEC);
   2810 	}
   2811 }
   2812 #endif /* ARM_MMU_EXTENDED */
   2813 #endif /* PMAP_CACHE_VIPT */
   2814 
   2815 /*
   2816  * Routine:	pmap_page_remove
   2817  * Function:
   2818  *		Removes this physical page from
   2819  *		all physical maps in which it resides.
   2820  *		Reflects back modify bits to the pager.
   2821  */
   2822 static void
   2823 pmap_page_remove(struct vm_page_md *md, paddr_t pa)
   2824 {
   2825 	struct l2_bucket *l2b;
   2826 	struct pv_entry *pv;
   2827 	pt_entry_t *ptep;
   2828 #ifndef ARM_MMU_EXTENDED
   2829 	bool flush = false;
   2830 #endif
   2831 	u_int flags = 0;
   2832 
   2833 	NPDEBUG(PDB_FOLLOW,
   2834 	    printf("pmap_page_remove: md %p (0x%08lx)\n", md,
   2835 	    pa));
   2836 
   2837 	struct pv_entry **pvp = &SLIST_FIRST(&md->pvh_list);
   2838 	pmap_acquire_page_lock(md);
   2839 	if (*pvp == NULL) {
   2840 #ifdef PMAP_CACHE_VIPT
   2841 		/*
   2842 		 * We *know* the page contents are about to be replaced.
   2843 		 * Discard the exec contents
   2844 		 */
   2845 		if (PV_IS_EXEC_P(md->pvh_attrs))
   2846 			PMAPCOUNT(exec_discarded_page_protect);
   2847 		md->pvh_attrs &= ~PVF_EXEC;
   2848 		PMAP_VALIDATE_MD_PAGE(md);
   2849 #endif
   2850 		pmap_release_page_lock(md);
   2851 		return;
   2852 	}
   2853 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   2854 	KASSERT(arm_cache_prefer_mask == 0 || pmap_is_page_colored_p(md));
   2855 #endif
   2856 
   2857 	/*
   2858 	 * Clear alias counts
   2859 	 */
   2860 #ifdef PMAP_CACHE_VIVT
   2861 	md->k_mappings = 0;
   2862 #endif
   2863 	md->urw_mappings = md->uro_mappings = 0;
   2864 
   2865 #ifdef PMAP_CACHE_VIVT
   2866 	pmap_clean_page(md, false);
   2867 #endif
   2868 
   2869 	while ((pv = *pvp) != NULL) {
   2870 		pmap_t pm = pv->pv_pmap;
   2871 #ifndef ARM_MMU_EXTENDED
   2872 		if (flush == false && pmap_is_current(pm))
   2873 			flush = true;
   2874 #endif
   2875 
   2876 		if (pm == pmap_kernel()) {
   2877 #ifdef PMAP_CACHE_VIPT
   2878 			/*
   2879 			 * If this was unmanaged mapping, it must be preserved.
   2880 			 * Move it back on the list and advance the end-of-list
   2881 			 * pointer.
   2882 			 */
   2883 			if (PV_IS_KENTRY_P(pv->pv_flags)) {
   2884 				*pvp = pv;
   2885 				pvp = &SLIST_NEXT(pv, pv_link);
   2886 				continue;
   2887 			}
   2888 			if (pv->pv_flags & PVF_WRITE)
   2889 				md->krw_mappings--;
   2890 			else
   2891 				md->kro_mappings--;
   2892 #endif
   2893 			PMAPCOUNT(kernel_unmappings);
   2894 		}
   2895 		*pvp = SLIST_NEXT(pv, pv_link); /* remove from list */
   2896 		PMAPCOUNT(unmappings);
   2897 
   2898 		pmap_release_page_lock(md);
   2899 		pmap_acquire_pmap_lock(pm);
   2900 
   2901 		l2b = pmap_get_l2_bucket(pm, pv->pv_va);
   2902 		KASSERTMSG(l2b != NULL, "%#lx", pv->pv_va);
   2903 
   2904 		ptep = &l2b->l2b_kva[l2pte_index(pv->pv_va)];
   2905 
   2906 		/*
   2907 		 * Update statistics
   2908 		 */
   2909 		--pm->pm_stats.resident_count;
   2910 
   2911 		/* Wired bit */
   2912 		if (pv->pv_flags & PVF_WIRED)
   2913 			--pm->pm_stats.wired_count;
   2914 
   2915 		flags |= pv->pv_flags;
   2916 
   2917 		/*
   2918 		 * Invalidate the PTEs.
   2919 		 */
   2920 		l2pte_reset(ptep);
   2921 		PTE_SYNC_CURRENT(pm, ptep);
   2922 
   2923 #ifdef ARM_MMU_EXTENDED
   2924 		pmap_tlb_invalidate_addr(pm, pv->pv_va);
   2925 #endif
   2926 
   2927 		pmap_free_l2_bucket(pm, l2b, PAGE_SIZE / L2_S_SIZE);
   2928 
   2929 		pmap_release_pmap_lock(pm);
   2930 
   2931 		pool_put(&pmap_pv_pool, pv);
   2932 		pmap_acquire_page_lock(md);
   2933 #ifdef MULTIPROCESSOR
   2934 		/*
   2935 		 * Restart of the beginning of the list.
   2936 		 */
   2937 		pvp = &SLIST_FIRST(&md->pvh_list);
   2938 #endif
   2939 	}
   2940 	/*
   2941 	 * if we reach the end of the list and there are still mappings, they
   2942 	 * might be able to be cached now.  And they must be kernel mappings.
   2943 	 */
   2944 	if (!SLIST_EMPTY(&md->pvh_list)) {
   2945 		pmap_vac_me_harder(md, pa, pmap_kernel(), 0);
   2946 	}
   2947 
   2948 #ifdef PMAP_CACHE_VIPT
   2949 	/*
   2950 	 * Its EXEC cache is now gone.
   2951 	 */
   2952 	if (PV_IS_EXEC_P(md->pvh_attrs))
   2953 		PMAPCOUNT(exec_discarded_page_protect);
   2954 	md->pvh_attrs &= ~PVF_EXEC;
   2955 	KASSERT(md->urw_mappings == 0);
   2956 	KASSERT(md->uro_mappings == 0);
   2957 #ifndef ARM_MMU_EXTENDED
   2958 	if (arm_cache_prefer_mask != 0) {
   2959 		if (md->krw_mappings == 0)
   2960 			md->pvh_attrs &= ~PVF_WRITE;
   2961 		PMAP_VALIDATE_MD_PAGE(md);
   2962 	}
   2963 #endif /* ARM_MMU_EXTENDED */
   2964 #endif /* PMAP_CACHE_VIPT */
   2965 	pmap_release_page_lock(md);
   2966 
   2967 #ifndef ARM_MMU_EXTENDED
   2968 	if (flush) {
   2969 		/*
   2970 		 * Note: We can't use pmap_tlb_flush{I,D}() here since that
   2971 		 * would need a subsequent call to pmap_update() to ensure
   2972 		 * curpm->pm_cstate.cs_all is reset. Our callers are not
   2973 		 * required to do that (see pmap(9)), so we can't modify
   2974 		 * the current pmap's state.
   2975 		 */
   2976 		if (PV_BEEN_EXECD(flags))
   2977 			cpu_tlb_flushID();
   2978 		else
   2979 			cpu_tlb_flushD();
   2980 	}
   2981 	cpu_cpwait();
   2982 #endif /* ARM_MMU_EXTENDED */
   2983 }
   2984 
   2985 /*
   2986  * pmap_t pmap_create(void)
   2987  *
   2988  *      Create a new pmap structure from scratch.
   2989  */
   2990 pmap_t
   2991 pmap_create(void)
   2992 {
   2993 	pmap_t pm;
   2994 
   2995 	pm = pool_cache_get(&pmap_cache, PR_WAITOK);
   2996 
   2997 	mutex_init(&pm->pm_obj_lock, MUTEX_DEFAULT, IPL_NONE);
   2998 	uvm_obj_init(&pm->pm_obj, NULL, false, 1);
   2999 	uvm_obj_setlock(&pm->pm_obj, &pm->pm_obj_lock);
   3000 
   3001 	pm->pm_stats.wired_count = 0;
   3002 	pm->pm_stats.resident_count = 1;
   3003 #ifdef ARM_MMU_EXTENDED
   3004 #ifdef MULTIPROCESSOR
   3005 	kcpuset_create(&pm->pm_active, true);
   3006 	kcpuset_create(&pm->pm_onproc, true);
   3007 #endif
   3008 #else
   3009 	pm->pm_cstate.cs_all = 0;
   3010 #endif
   3011 	pmap_alloc_l1(pm);
   3012 
   3013 	/*
   3014 	 * Note: The pool cache ensures that the pm_l2[] array is already
   3015 	 * initialised to zero.
   3016 	 */
   3017 
   3018 	pmap_pinit(pm);
   3019 
   3020 	return (pm);
   3021 }
   3022 
   3023 u_int
   3024 arm32_mmap_flags(paddr_t pa)
   3025 {
   3026 	/*
   3027 	 * the upper 8 bits in pmap_enter()'s flags are reserved for MD stuff
   3028 	 * and we're using the upper bits in page numbers to pass flags around
   3029 	 * so we might as well use the same bits
   3030 	 */
   3031 	return (u_int)pa & PMAP_MD_MASK;
   3032 }
   3033 /*
   3034  * int pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot,
   3035  *      u_int flags)
   3036  *
   3037  *      Insert the given physical page (p) at
   3038  *      the specified virtual address (v) in the
   3039  *      target physical map with the protection requested.
   3040  *
   3041  *      NB:  This is the only routine which MAY NOT lazy-evaluate
   3042  *      or lose information.  That is, this routine must actually
   3043  *      insert this page into the given map NOW.
   3044  */
   3045 int
   3046 pmap_enter(pmap_t pm, vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
   3047 {
   3048 	struct l2_bucket *l2b;
   3049 	struct vm_page *pg, *opg;
   3050 	u_int nflags;
   3051 	u_int oflags;
   3052 	const bool kpm_p = (pm == pmap_kernel());
   3053 #ifdef ARM_HAS_VBAR
   3054 	const bool vector_page_p = false;
   3055 #else
   3056 	const bool vector_page_p = (va == vector_page);
   3057 #endif
   3058 
   3059 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   3060 
   3061 	UVMHIST_LOG(maphist, " (pm %p va %#x pa %#x prot %#x",
   3062 	    pm, va, pa, prot);
   3063 	UVMHIST_LOG(maphist, "  flag %#x", flags, 0, 0, 0);
   3064 
   3065 	KDASSERT((flags & PMAP_WIRED) == 0 || (flags & VM_PROT_ALL) != 0);
   3066 	KDASSERT(((va | pa) & PGOFSET) == 0);
   3067 
   3068 	/*
   3069 	 * Get a pointer to the page.  Later on in this function, we
   3070 	 * test for a managed page by checking pg != NULL.
   3071 	 */
   3072 	pg = pmap_initialized ? PHYS_TO_VM_PAGE(pa) : NULL;
   3073 
   3074 	nflags = 0;
   3075 	if (prot & VM_PROT_WRITE)
   3076 		nflags |= PVF_WRITE;
   3077 	if (prot & VM_PROT_EXECUTE)
   3078 		nflags |= PVF_EXEC;
   3079 	if (flags & PMAP_WIRED)
   3080 		nflags |= PVF_WIRED;
   3081 
   3082 	pmap_acquire_pmap_lock(pm);
   3083 
   3084 	/*
   3085 	 * Fetch the L2 bucket which maps this page, allocating one if
   3086 	 * necessary for user pmaps.
   3087 	 */
   3088 	if (kpm_p) {
   3089 		l2b = pmap_get_l2_bucket(pm, va);
   3090 	} else {
   3091 		l2b = pmap_alloc_l2_bucket(pm, va);
   3092 	}
   3093 	if (l2b == NULL) {
   3094 		if (flags & PMAP_CANFAIL) {
   3095 			pmap_release_pmap_lock(pm);
   3096 			return (ENOMEM);
   3097 		}
   3098 		panic("pmap_enter: failed to allocate L2 bucket");
   3099 	}
   3100 	pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(va)];
   3101 	const pt_entry_t opte = *ptep;
   3102 	pt_entry_t npte = pa;
   3103 	oflags = 0;
   3104 
   3105 	if (opte) {
   3106 		/*
   3107 		 * There is already a mapping at this address.
   3108 		 * If the physical address is different, lookup the
   3109 		 * vm_page.
   3110 		 */
   3111 		if (l2pte_pa(opte) != pa) {
   3112 			KASSERT(!pmap_pv_tracked(pa));
   3113 			opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
   3114 		} else
   3115 			opg = pg;
   3116 	} else
   3117 		opg = NULL;
   3118 
   3119 	struct pmap_page *pp = pmap_pv_tracked(pa);
   3120 
   3121 	if (pg || pp) {
   3122 		KASSERT((pg != NULL) != (pp != NULL));
   3123 		struct vm_page_md *md = (pg != NULL) ? VM_PAGE_TO_MD(pg) :
   3124 		    PMAP_PAGE_TO_MD(pp);
   3125 
   3126 		/*
   3127 		 * This is to be a managed mapping.
   3128 		 */
   3129 		pmap_acquire_page_lock(md);
   3130 		if ((flags & VM_PROT_ALL) || (md->pvh_attrs & PVF_REF)) {
   3131 			/*
   3132 			 * - The access type indicates that we don't need
   3133 			 *   to do referenced emulation.
   3134 			 * OR
   3135 			 * - The physical page has already been referenced
   3136 			 *   so no need to re-do referenced emulation here.
   3137 			 */
   3138 			npte |= l2pte_set_readonly(L2_S_PROTO);
   3139 
   3140 			nflags |= PVF_REF;
   3141 
   3142 			if ((prot & VM_PROT_WRITE) != 0 &&
   3143 			    ((flags & VM_PROT_WRITE) != 0 ||
   3144 			     (md->pvh_attrs & PVF_MOD) != 0)) {
   3145 				/*
   3146 				 * This is a writable mapping, and the
   3147 				 * page's mod state indicates it has
   3148 				 * already been modified. Make it
   3149 				 * writable from the outset.
   3150 				 */
   3151 				npte = l2pte_set_writable(npte);
   3152 				nflags |= PVF_MOD;
   3153 			}
   3154 
   3155 #ifdef ARM_MMU_EXTENDED
   3156 			/*
   3157 			 * If the page has been cleaned, then the pvh_attrs
   3158 			 * will have PVF_EXEC set, so mark it execute so we
   3159 			 * don't get an access fault when trying to execute
   3160 			 * from it.
   3161 			 */
   3162 			if (md->pvh_attrs & nflags & PVF_EXEC) {
   3163 				npte &= ~L2_XS_XN;
   3164 			}
   3165 #endif
   3166 		} else {
   3167 			/*
   3168 			 * Need to do page referenced emulation.
   3169 			 */
   3170 			npte |= L2_TYPE_INV;
   3171 		}
   3172 
   3173 		if (flags & ARM32_MMAP_WRITECOMBINE) {
   3174 			npte |= pte_l2_s_wc_mode;
   3175 		} else
   3176 			npte |= pte_l2_s_cache_mode;
   3177 
   3178 		if (pg != NULL && pg == opg) {
   3179 			/*
   3180 			 * We're changing the attrs of an existing mapping.
   3181 			 */
   3182 			oflags = pmap_modify_pv(md, pa, pm, va,
   3183 			    PVF_WRITE | PVF_EXEC | PVF_WIRED |
   3184 			    PVF_MOD | PVF_REF, nflags);
   3185 
   3186 #ifdef PMAP_CACHE_VIVT
   3187 			/*
   3188 			 * We may need to flush the cache if we're
   3189 			 * doing rw-ro...
   3190 			 */
   3191 			if (pm->pm_cstate.cs_cache_d &&
   3192 			    (oflags & PVF_NC) == 0 &&
   3193 			    l2pte_writable_p(opte) &&
   3194 			    (prot & VM_PROT_WRITE) == 0)
   3195 				cpu_dcache_wb_range(va, PAGE_SIZE);
   3196 #endif
   3197 		} else {
   3198 			struct pv_entry *pv;
   3199 			/*
   3200 			 * New mapping, or changing the backing page
   3201 			 * of an existing mapping.
   3202 			 */
   3203 			if (opg) {
   3204 				struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
   3205 				paddr_t opa = VM_PAGE_TO_PHYS(opg);
   3206 
   3207 				/*
   3208 				 * Replacing an existing mapping with a new one.
   3209 				 * It is part of our managed memory so we
   3210 				 * must remove it from the PV list
   3211 				 */
   3212 				pv = pmap_remove_pv(omd, opa, pm, va);
   3213 				pmap_vac_me_harder(omd, opa, pm, 0);
   3214 				oflags = pv->pv_flags;
   3215 
   3216 #ifdef PMAP_CACHE_VIVT
   3217 				/*
   3218 				 * If the old mapping was valid (ref/mod
   3219 				 * emulation creates 'invalid' mappings
   3220 				 * initially) then make sure to frob
   3221 				 * the cache.
   3222 				 */
   3223 				if (!(oflags & PVF_NC) && l2pte_valid_p(opte)) {
   3224 					pmap_cache_wbinv_page(pm, va, true,
   3225 					    oflags);
   3226 				}
   3227 #endif
   3228 			} else {
   3229 				pmap_release_page_lock(md);
   3230 				pv = pool_get(&pmap_pv_pool, PR_NOWAIT);
   3231 				if (pv == NULL) {
   3232 					pmap_release_pmap_lock(pm);
   3233 					if ((flags & PMAP_CANFAIL) == 0)
   3234 						panic("pmap_enter: "
   3235 						    "no pv entries");
   3236 
   3237 					pmap_free_l2_bucket(pm, l2b, 0);
   3238 					UVMHIST_LOG(maphist, "  <-- done (ENOMEM)",
   3239 					    0, 0, 0, 0);
   3240 					return (ENOMEM);
   3241 				}
   3242 				pmap_acquire_page_lock(md);
   3243 			}
   3244 
   3245 			pmap_enter_pv(md, pa, pv, pm, va, nflags);
   3246 		}
   3247 		pmap_release_page_lock(md);
   3248 	} else {
   3249 		/*
   3250 		 * We're mapping an unmanaged page.
   3251 		 * These are always readable, and possibly writable, from
   3252 		 * the get go as we don't need to track ref/mod status.
   3253 		 */
   3254 		npte |= l2pte_set_readonly(L2_S_PROTO);
   3255 		if (prot & VM_PROT_WRITE)
   3256 			npte = l2pte_set_writable(npte);
   3257 
   3258 		/*
   3259 		 * Make sure the vector table is mapped cacheable
   3260 		 */
   3261 		if ((vector_page_p && !kpm_p)
   3262 		    || (flags & ARM32_MMAP_CACHEABLE)) {
   3263 			npte |= pte_l2_s_cache_mode;
   3264 #ifdef ARM_MMU_EXTENDED
   3265 			npte &= ~L2_XS_XN;	/* and executable */
   3266 #endif
   3267 		} else if (flags & ARM32_MMAP_WRITECOMBINE) {
   3268 			npte |= pte_l2_s_wc_mode;
   3269 		}
   3270 		if (opg) {
   3271 			/*
   3272 			 * Looks like there's an existing 'managed' mapping
   3273 			 * at this address.
   3274 			 */
   3275 			struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
   3276 			paddr_t opa = VM_PAGE_TO_PHYS(opg);
   3277 
   3278 			pmap_acquire_page_lock(omd);
   3279 			struct pv_entry *pv = pmap_remove_pv(omd, opa, pm, va);
   3280 			pmap_vac_me_harder(omd, opa, pm, 0);
   3281 			oflags = pv->pv_flags;
   3282 			pmap_release_page_lock(omd);
   3283 
   3284 #ifdef PMAP_CACHE_VIVT
   3285 			if (!(oflags & PVF_NC) && l2pte_valid_p(opte)) {
   3286 				pmap_cache_wbinv_page(pm, va, true, oflags);
   3287 			}
   3288 #endif
   3289 			pool_put(&pmap_pv_pool, pv);
   3290 		}
   3291 	}
   3292 
   3293 	/*
   3294 	 * Make sure userland mappings get the right permissions
   3295 	 */
   3296 	if (!vector_page_p && !kpm_p) {
   3297 		npte |= L2_S_PROT_U;
   3298 #ifdef ARM_MMU_EXTENDED
   3299 		npte |= L2_XS_nG;	/* user pages are not global */
   3300 #endif
   3301 	}
   3302 
   3303 	/*
   3304 	 * Keep the stats up to date
   3305 	 */
   3306 	if (opte == 0) {
   3307 		l2b->l2b_occupancy += PAGE_SIZE / L2_S_SIZE;
   3308 		pm->pm_stats.resident_count++;
   3309 	}
   3310 
   3311 	UVMHIST_LOG(maphist, " opte %#x npte %#x", opte, npte, 0, 0);
   3312 
   3313 #if defined(ARM_MMU_EXTENDED)
   3314 	/*
   3315 	 * If exec protection was requested but the page hasn't been synced,
   3316 	 * sync it now and allow execution from it.
   3317 	 */
   3318 	if ((nflags & PVF_EXEC) && (npte & L2_XS_XN)) {
   3319 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   3320 		npte &= ~L2_XS_XN;
   3321 		pmap_syncicache_page(md, pa);
   3322 		PMAPCOUNT(exec_synced_map);
   3323 	}
   3324 #endif
   3325 	/*
   3326 	 * If this is just a wiring change, the two PTEs will be
   3327 	 * identical, so there's no need to update the page table.
   3328 	 */
   3329 	if (npte != opte) {
   3330 		l2pte_reset(ptep);
   3331 		PTE_SYNC(ptep);
   3332 		if (l2pte_valid_p(opte)) {
   3333 			pmap_tlb_flush_SE(pm, va, oflags);
   3334 		}
   3335 		l2pte_set(ptep, npte, 0);
   3336 		PTE_SYNC(ptep);
   3337 #ifndef ARM_MMU_EXTENDED
   3338 		bool is_cached = pmap_is_cached(pm);
   3339 		if (is_cached) {
   3340 			/*
   3341 			 * We only need to frob the cache/tlb if this pmap
   3342 			 * is current
   3343 			 */
   3344 			if (!vector_page_p && l2pte_valid_p(npte)) {
   3345 				/*
   3346 				 * This mapping is likely to be accessed as
   3347 				 * soon as we return to userland. Fix up the
   3348 				 * L1 entry to avoid taking another
   3349 				 * page/domain fault.
   3350 				 */
   3351 				pd_entry_t *pdep = pmap_l1_kva(pm)
   3352 				     + l1pte_index(va);
   3353 				pd_entry_t pde = L1_C_PROTO | l2b->l2b_pa
   3354 				    | L1_C_DOM(pmap_domain(pm));
   3355 				if (*pdep != pde) {
   3356 					l1pte_setone(pdep, pde);
   3357 					PDE_SYNC(pdep);
   3358 				}
   3359 			}
   3360 		}
   3361 #endif /* !ARM_MMU_EXTENDED */
   3362 
   3363 #ifndef ARM_MMU_EXTENDED
   3364 		UVMHIST_LOG(maphist, "  is_cached %d cs 0x%08x\n",
   3365 		    is_cached, pm->pm_cstate.cs_all, 0, 0);
   3366 
   3367 		if (pg != NULL) {
   3368 			struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   3369 
   3370 			pmap_acquire_page_lock(md);
   3371 			pmap_vac_me_harder(md, pa, pm, va);
   3372 			pmap_release_page_lock(md);
   3373 		}
   3374 #endif
   3375 	}
   3376 #if defined(PMAP_CACHE_VIPT) && defined(DIAGNOSTIC)
   3377 	if (pg) {
   3378 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   3379 
   3380 		pmap_acquire_page_lock(md);
   3381 #ifndef ARM_MMU_EXTENDED
   3382 		KASSERT((md->pvh_attrs & PVF_DMOD) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   3383 #endif
   3384 		PMAP_VALIDATE_MD_PAGE(md);
   3385 		pmap_release_page_lock(md);
   3386 	}
   3387 #endif
   3388 
   3389 	pmap_release_pmap_lock(pm);
   3390 
   3391 	return (0);
   3392 }
   3393 
   3394 /*
   3395  * pmap_remove()
   3396  *
   3397  * pmap_remove is responsible for nuking a number of mappings for a range
   3398  * of virtual address space in the current pmap. To do this efficiently
   3399  * is interesting, because in a number of cases a wide virtual address
   3400  * range may be supplied that contains few actual mappings. So, the
   3401  * optimisations are:
   3402  *  1. Skip over hunks of address space for which no L1 or L2 entry exists.
   3403  *  2. Build up a list of pages we've hit, up to a maximum, so we can
   3404  *     maybe do just a partial cache clean. This path of execution is
   3405  *     complicated by the fact that the cache must be flushed _before_
   3406  *     the PTE is nuked, being a VAC :-)
   3407  *  3. If we're called after UVM calls pmap_remove_all(), we can defer
   3408  *     all invalidations until pmap_update(), since pmap_remove_all() has
   3409  *     already flushed the cache.
   3410  *  4. Maybe later fast-case a single page, but I don't think this is
   3411  *     going to make _that_ much difference overall.
   3412  */
   3413 
   3414 #define	PMAP_REMOVE_CLEAN_LIST_SIZE	3
   3415 
   3416 void
   3417 pmap_remove(pmap_t pm, vaddr_t sva, vaddr_t eva)
   3418 {
   3419 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   3420 	UVMHIST_LOG(maphist, " (pm=%p, sva=%#x, eva=%#x)", pm, sva, eva, 0);
   3421 
   3422 	/*
   3423 	 * we lock in the pmap => pv_head direction
   3424 	 */
   3425 	pmap_acquire_pmap_lock(pm);
   3426 
   3427 #ifndef ARM_MMU_EXTENDED
   3428 	u_int cleanlist_idx, total, cnt;
   3429 	struct {
   3430 		vaddr_t va;
   3431 		pt_entry_t *ptep;
   3432 	} cleanlist[PMAP_REMOVE_CLEAN_LIST_SIZE];
   3433 
   3434 	if (pm->pm_remove_all || !pmap_is_cached(pm)) {
   3435 		cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
   3436 		if (pm->pm_cstate.cs_tlb == 0)
   3437 			pm->pm_remove_all = true;
   3438 	} else
   3439 		cleanlist_idx = 0;
   3440 	total = 0;
   3441 #endif
   3442 
   3443 	while (sva < eva) {
   3444 		/*
   3445 		 * Do one L2 bucket's worth at a time.
   3446 		 */
   3447 		vaddr_t next_bucket = L2_NEXT_BUCKET_VA(sva);
   3448 		if (next_bucket > eva)
   3449 			next_bucket = eva;
   3450 
   3451 		struct l2_bucket * const l2b = pmap_get_l2_bucket(pm, sva);
   3452 		if (l2b == NULL) {
   3453 			sva = next_bucket;
   3454 			continue;
   3455 		}
   3456 
   3457 		pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(sva)];
   3458 		u_int mappings = 0;
   3459 
   3460 		for (;sva < next_bucket;
   3461 		     sva += PAGE_SIZE, ptep += PAGE_SIZE / L2_S_SIZE) {
   3462 			pt_entry_t opte = *ptep;
   3463 
   3464 			if (opte == 0) {
   3465 				/* Nothing here, move along */
   3466 				continue;
   3467 			}
   3468 
   3469 			u_int flags = PVF_REF;
   3470 			paddr_t pa = l2pte_pa(opte);
   3471 			struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   3472 
   3473 			/*
   3474 			 * Update flags. In a number of circumstances,
   3475 			 * we could cluster a lot of these and do a
   3476 			 * number of sequential pages in one go.
   3477 			 */
   3478 			if (pg != NULL) {
   3479 				struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   3480 				struct pv_entry *pv;
   3481 
   3482 				pmap_acquire_page_lock(md);
   3483 				pv = pmap_remove_pv(md, pa, pm, sva);
   3484 				pmap_vac_me_harder(md, pa, pm, 0);
   3485 				pmap_release_page_lock(md);
   3486 				if (pv != NULL) {
   3487 					if (pm->pm_remove_all == false) {
   3488 						flags = pv->pv_flags;
   3489 					}
   3490 					pool_put(&pmap_pv_pool, pv);
   3491 				}
   3492 			}
   3493 			mappings += PAGE_SIZE / L2_S_SIZE;
   3494 
   3495 			if (!l2pte_valid_p(opte)) {
   3496 				/*
   3497 				 * Ref/Mod emulation is still active for this
   3498 				 * mapping, therefore it is has not yet been
   3499 				 * accessed. No need to frob the cache/tlb.
   3500 				 */
   3501 				l2pte_reset(ptep);
   3502 				PTE_SYNC_CURRENT(pm, ptep);
   3503 				continue;
   3504 			}
   3505 
   3506 #ifdef ARM_MMU_EXTENDED
   3507 			l2pte_reset(ptep);
   3508 			PTE_SYNC(ptep);
   3509 			if (__predict_false(pm->pm_remove_all == false)) {
   3510 				pmap_tlb_flush_SE(pm, sva, flags);
   3511 			}
   3512 #else
   3513 			if (cleanlist_idx < PMAP_REMOVE_CLEAN_LIST_SIZE) {
   3514 				/* Add to the clean list. */
   3515 				cleanlist[cleanlist_idx].ptep = ptep;
   3516 				cleanlist[cleanlist_idx].va =
   3517 				    sva | (flags & PVF_EXEC);
   3518 				cleanlist_idx++;
   3519 			} else if (cleanlist_idx == PMAP_REMOVE_CLEAN_LIST_SIZE) {
   3520 				/* Nuke everything if needed. */
   3521 #ifdef PMAP_CACHE_VIVT
   3522 				pmap_cache_wbinv_all(pm, PVF_EXEC);
   3523 #endif
   3524 				/*
   3525 				 * Roll back the previous PTE list,
   3526 				 * and zero out the current PTE.
   3527 				 */
   3528 				for (cnt = 0;
   3529 				     cnt < PMAP_REMOVE_CLEAN_LIST_SIZE; cnt++) {
   3530 					l2pte_reset(cleanlist[cnt].ptep);
   3531 					PTE_SYNC(cleanlist[cnt].ptep);
   3532 				}
   3533 				l2pte_reset(ptep);
   3534 				PTE_SYNC(ptep);
   3535 				cleanlist_idx++;
   3536 				pm->pm_remove_all = true;
   3537 			} else {
   3538 				l2pte_reset(ptep);
   3539 				PTE_SYNC(ptep);
   3540 				if (pm->pm_remove_all == false) {
   3541 					pmap_tlb_flush_SE(pm, sva, flags);
   3542 				}
   3543 			}
   3544 #endif
   3545 		}
   3546 
   3547 #ifndef ARM_MMU_EXTENDED
   3548 		/*
   3549 		 * Deal with any left overs
   3550 		 */
   3551 		if (cleanlist_idx <= PMAP_REMOVE_CLEAN_LIST_SIZE) {
   3552 			total += cleanlist_idx;
   3553 			for (cnt = 0; cnt < cleanlist_idx; cnt++) {
   3554 				l2pte_reset(cleanlist[cnt].ptep);
   3555 				PTE_SYNC_CURRENT(pm, cleanlist[cnt].ptep);
   3556 				vaddr_t va = cleanlist[cnt].va;
   3557 				if (pm->pm_cstate.cs_all != 0) {
   3558 					vaddr_t clva = va & ~PAGE_MASK;
   3559 					u_int flags = va & PVF_EXEC;
   3560 #ifdef PMAP_CACHE_VIVT
   3561 					pmap_cache_wbinv_page(pm, clva, true,
   3562 					    PVF_REF | PVF_WRITE | flags);
   3563 #endif
   3564 					pmap_tlb_flush_SE(pm, clva,
   3565 					    PVF_REF | flags);
   3566 				}
   3567 			}
   3568 
   3569 			/*
   3570 			 * If it looks like we're removing a whole bunch
   3571 			 * of mappings, it's faster to just write-back
   3572 			 * the whole cache now and defer TLB flushes until
   3573 			 * pmap_update() is called.
   3574 			 */
   3575 			if (total <= PMAP_REMOVE_CLEAN_LIST_SIZE)
   3576 				cleanlist_idx = 0;
   3577 			else {
   3578 				cleanlist_idx = PMAP_REMOVE_CLEAN_LIST_SIZE + 1;
   3579 #ifdef PMAP_CACHE_VIVT
   3580 				pmap_cache_wbinv_all(pm, PVF_EXEC);
   3581 #endif
   3582 				pm->pm_remove_all = true;
   3583 			}
   3584 		}
   3585 #endif /* ARM_MMU_EXTENDED */
   3586 
   3587 		pmap_free_l2_bucket(pm, l2b, mappings);
   3588 		pm->pm_stats.resident_count -= mappings / (PAGE_SIZE/L2_S_SIZE);
   3589 	}
   3590 
   3591 	pmap_release_pmap_lock(pm);
   3592 }
   3593 
   3594 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3595 static struct pv_entry *
   3596 pmap_kremove_pg(struct vm_page *pg, vaddr_t va)
   3597 {
   3598 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   3599 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
   3600 	struct pv_entry *pv;
   3601 
   3602 	KASSERT(arm_cache_prefer_mask == 0 || md->pvh_attrs & (PVF_COLORED|PVF_NC));
   3603 	KASSERT((md->pvh_attrs & PVF_KMPAGE) == 0);
   3604 	KASSERT(pmap_page_locked_p(md));
   3605 
   3606 	pv = pmap_remove_pv(md, pa, pmap_kernel(), va);
   3607 	KASSERTMSG(pv, "pg %p (pa #%lx) va %#lx", pg, pa, va);
   3608 	KASSERT(PV_IS_KENTRY_P(pv->pv_flags));
   3609 
   3610 	/*
   3611 	 * If we are removing a writeable mapping to a cached exec page,
   3612 	 * if it's the last mapping then clear it execness other sync
   3613 	 * the page to the icache.
   3614 	 */
   3615 	if ((md->pvh_attrs & (PVF_NC|PVF_EXEC)) == PVF_EXEC
   3616 	    && (pv->pv_flags & PVF_WRITE) != 0) {
   3617 		if (SLIST_EMPTY(&md->pvh_list)) {
   3618 			md->pvh_attrs &= ~PVF_EXEC;
   3619 			PMAPCOUNT(exec_discarded_kremove);
   3620 		} else {
   3621 			pmap_syncicache_page(md, pa);
   3622 			PMAPCOUNT(exec_synced_kremove);
   3623 		}
   3624 	}
   3625 	pmap_vac_me_harder(md, pa, pmap_kernel(), 0);
   3626 
   3627 	return pv;
   3628 }
   3629 #endif /* PMAP_CACHE_VIPT && !ARM_MMU_EXTENDED */
   3630 
   3631 /*
   3632  * pmap_kenter_pa: enter an unmanaged, wired kernel mapping
   3633  *
   3634  * We assume there is already sufficient KVM space available
   3635  * to do this, as we can't allocate L2 descriptor tables/metadata
   3636  * from here.
   3637  */
   3638 void
   3639 pmap_kenter_pa(vaddr_t va, paddr_t pa, vm_prot_t prot, u_int flags)
   3640 {
   3641 #ifdef PMAP_CACHE_VIVT
   3642 	struct vm_page *pg = (flags & PMAP_KMPAGE) ? PHYS_TO_VM_PAGE(pa) : NULL;
   3643 #endif
   3644 #ifdef PMAP_CACHE_VIPT
   3645 	struct vm_page *pg = PHYS_TO_VM_PAGE(pa);
   3646 	struct vm_page *opg;
   3647 #ifndef ARM_MMU_EXTENDED
   3648 	struct pv_entry *pv = NULL;
   3649 #endif
   3650 #endif
   3651 	struct vm_page_md *md = pg != NULL ? VM_PAGE_TO_MD(pg) : NULL;
   3652 
   3653 	UVMHIST_FUNC(__func__);
   3654 
   3655 	if (pmap_initialized) {
   3656 		UVMHIST_CALLED(maphist);
   3657 		UVMHIST_LOG(maphist, " (va=%#x, pa=%#x, prot=%#x, flags=%#x",
   3658 		    va, pa, prot, flags);
   3659 	}
   3660 
   3661 	pmap_t kpm = pmap_kernel();
   3662 	pmap_acquire_pmap_lock(kpm);
   3663 	struct l2_bucket * const l2b = pmap_get_l2_bucket(kpm, va);
   3664 	const size_t l1slot __diagused = l1pte_index(va);
   3665 	KASSERTMSG(l2b != NULL,
   3666 	    "va %#lx pa %#lx prot %d maxkvaddr %#lx: l2 %p l2b %p kva %p",
   3667 	    va, pa, prot, pmap_curmaxkvaddr, kpm->pm_l2[L2_IDX(l1slot)],
   3668 	    kpm->pm_l2[L2_IDX(l1slot)]
   3669 		? &kpm->pm_l2[L2_IDX(l1slot)]->l2_bucket[L2_BUCKET(l1slot)]
   3670 		: NULL,
   3671 	    kpm->pm_l2[L2_IDX(l1slot)]
   3672 		? kpm->pm_l2[L2_IDX(l1slot)]->l2_bucket[L2_BUCKET(l1slot)].l2b_kva
   3673 		: NULL);
   3674 	KASSERT(l2b->l2b_kva != NULL);
   3675 
   3676 	pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   3677 	const pt_entry_t opte = *ptep;
   3678 
   3679 	if (opte == 0) {
   3680 		PMAPCOUNT(kenter_mappings);
   3681 		l2b->l2b_occupancy += PAGE_SIZE / L2_S_SIZE;
   3682 	} else {
   3683 		PMAPCOUNT(kenter_remappings);
   3684 #ifdef PMAP_CACHE_VIPT
   3685 		opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
   3686 #if !defined(ARM_MMU_EXTENDED) || defined(DIAGNOSTIC)
   3687 		struct vm_page_md *omd __diagused = VM_PAGE_TO_MD(opg);
   3688 #endif
   3689 		if (opg && arm_cache_prefer_mask != 0) {
   3690 			KASSERT(opg != pg);
   3691 			KASSERT((omd->pvh_attrs & PVF_KMPAGE) == 0);
   3692 			KASSERT((flags & PMAP_KMPAGE) == 0);
   3693 #ifndef ARM_MMU_EXTENDED
   3694 			pmap_acquire_page_lock(omd);
   3695 			pv = pmap_kremove_pg(opg, va);
   3696 			pmap_release_page_lock(omd);
   3697 #endif
   3698 		}
   3699 #endif
   3700 		if (l2pte_valid_p(opte)) {
   3701 			l2pte_reset(ptep);
   3702 			PTE_SYNC(ptep);
   3703 #ifdef PMAP_CACHE_VIVT
   3704 			cpu_dcache_wbinv_range(va, PAGE_SIZE);
   3705 #endif
   3706 			cpu_tlb_flushD_SE(va);
   3707 			cpu_cpwait();
   3708 		}
   3709 	}
   3710 	pmap_release_pmap_lock(kpm);
   3711 
   3712 	pt_entry_t npte = L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot)
   3713 	    | ((flags & PMAP_NOCACHE)
   3714 		? 0
   3715 		: ((flags & PMAP_PTE)
   3716 		    ? pte_l2_s_cache_mode_pt : pte_l2_s_cache_mode));
   3717 #ifdef ARM_MMU_EXTENDED
   3718 	if (prot & VM_PROT_EXECUTE)
   3719 		npte &= ~L2_XS_XN;
   3720 #endif
   3721 	l2pte_set(ptep, npte, 0);
   3722 	PTE_SYNC(ptep);
   3723 
   3724 	if (pg) {
   3725 		if (flags & PMAP_KMPAGE) {
   3726 			KASSERT(md->urw_mappings == 0);
   3727 			KASSERT(md->uro_mappings == 0);
   3728 			KASSERT(md->krw_mappings == 0);
   3729 			KASSERT(md->kro_mappings == 0);
   3730 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3731 			KASSERT(pv == NULL);
   3732 			KASSERT(arm_cache_prefer_mask == 0 || (va & PVF_COLORED) == 0);
   3733 			KASSERT((md->pvh_attrs & PVF_NC) == 0);
   3734 			/* if there is a color conflict, evict from cache. */
   3735 			if (pmap_is_page_colored_p(md)
   3736 			    && ((va ^ md->pvh_attrs) & arm_cache_prefer_mask)) {
   3737 				PMAPCOUNT(vac_color_change);
   3738 				pmap_flush_page(md, pa, PMAP_FLUSH_PRIMARY);
   3739 			} else if (md->pvh_attrs & PVF_MULTCLR) {
   3740 				/*
   3741 				 * If this page has multiple colors, expunge
   3742 				 * them.
   3743 				 */
   3744 				PMAPCOUNT(vac_flush_lots2);
   3745 				pmap_flush_page(md, pa, PMAP_FLUSH_SECONDARY);
   3746 			}
   3747 			/*
   3748 			 * Since this is a KMPAGE, there can be no contention
   3749 			 * for this page so don't lock it.
   3750 			 */
   3751 			md->pvh_attrs &= PAGE_SIZE - 1;
   3752 			md->pvh_attrs |= PVF_KMPAGE | PVF_COLORED | PVF_DIRTY
   3753 			    | (va & arm_cache_prefer_mask);
   3754 #else /* !PMAP_CACHE_VIPT || ARM_MMU_EXTENDED */
   3755 			md->pvh_attrs |= PVF_KMPAGE;
   3756 #endif
   3757 			atomic_inc_32(&pmap_kmpages);
   3758 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3759 		} else if (arm_cache_prefer_mask != 0) {
   3760 			if (pv == NULL) {
   3761 				pv = pool_get(&pmap_pv_pool, PR_NOWAIT);
   3762 				KASSERT(pv != NULL);
   3763 			}
   3764 			pmap_acquire_page_lock(md);
   3765 			pmap_enter_pv(md, pa, pv, pmap_kernel(), va,
   3766 			    PVF_WIRED | PVF_KENTRY
   3767 			    | (prot & VM_PROT_WRITE ? PVF_WRITE : 0));
   3768 			if ((prot & VM_PROT_WRITE)
   3769 			    && !(md->pvh_attrs & PVF_NC))
   3770 				md->pvh_attrs |= PVF_DIRTY;
   3771 			KASSERT((prot & VM_PROT_WRITE) == 0 || (md->pvh_attrs & (PVF_DIRTY|PVF_NC)));
   3772 			pmap_vac_me_harder(md, pa, pmap_kernel(), va);
   3773 			pmap_release_page_lock(md);
   3774 #endif
   3775 		}
   3776 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3777 	} else {
   3778 		if (pv != NULL)
   3779 			pool_put(&pmap_pv_pool, pv);
   3780 #endif
   3781 	}
   3782 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3783 	KASSERT(md == NULL || !pmap_page_locked_p(md));
   3784 #endif
   3785 	if (pmap_initialized) {
   3786 		UVMHIST_LOG(maphist, "  <-- done (ptep %p: %#x -> %#x)",
   3787 		    ptep, opte, npte, 0);
   3788 	}
   3789 
   3790 }
   3791 
   3792 void
   3793 pmap_kremove(vaddr_t va, vsize_t len)
   3794 {
   3795 #ifdef UVMHIST
   3796 	u_int total_mappings = 0;
   3797 #endif
   3798 
   3799 	PMAPCOUNT(kenter_unmappings);
   3800 
   3801 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   3802 
   3803 	UVMHIST_LOG(maphist, " (va=%#x, len=%#x)", va, len, 0, 0);
   3804 
   3805 	const vaddr_t eva = va + len;
   3806 
   3807 	pmap_acquire_pmap_lock(pmap_kernel());
   3808 
   3809 	while (va < eva) {
   3810 		vaddr_t next_bucket = L2_NEXT_BUCKET_VA(va);
   3811 		if (next_bucket > eva)
   3812 			next_bucket = eva;
   3813 
   3814 		pmap_t kpm = pmap_kernel();
   3815 		struct l2_bucket * const l2b = pmap_get_l2_bucket(kpm, va);
   3816 		KDASSERT(l2b != NULL);
   3817 
   3818 		pt_entry_t * const sptep = &l2b->l2b_kva[l2pte_index(va)];
   3819 		pt_entry_t *ptep = sptep;
   3820 		u_int mappings = 0;
   3821 
   3822 		while (va < next_bucket) {
   3823 			const pt_entry_t opte = *ptep;
   3824 			struct vm_page *opg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
   3825 			if (opg != NULL) {
   3826 				struct vm_page_md *omd = VM_PAGE_TO_MD(opg);
   3827 
   3828 				if (omd->pvh_attrs & PVF_KMPAGE) {
   3829 					KASSERT(omd->urw_mappings == 0);
   3830 					KASSERT(omd->uro_mappings == 0);
   3831 					KASSERT(omd->krw_mappings == 0);
   3832 					KASSERT(omd->kro_mappings == 0);
   3833 					omd->pvh_attrs &= ~PVF_KMPAGE;
   3834 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3835 					if (arm_cache_prefer_mask != 0) {
   3836 						omd->pvh_attrs &= ~PVF_WRITE;
   3837 					}
   3838 #endif
   3839 					atomic_dec_32(&pmap_kmpages);
   3840 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   3841 				} else if (arm_cache_prefer_mask != 0) {
   3842 					pmap_acquire_page_lock(omd);
   3843 					pool_put(&pmap_pv_pool,
   3844 					    pmap_kremove_pg(opg, va));
   3845 					pmap_release_page_lock(omd);
   3846 #endif
   3847 				}
   3848 			}
   3849 			if (l2pte_valid_p(opte)) {
   3850 				l2pte_reset(ptep);
   3851 				PTE_SYNC(ptep);
   3852 #ifdef PMAP_CACHE_VIVT
   3853 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
   3854 #endif
   3855 				cpu_tlb_flushD_SE(va);
   3856 
   3857 				mappings += PAGE_SIZE / L2_S_SIZE;
   3858 			}
   3859 			va += PAGE_SIZE;
   3860 			ptep += PAGE_SIZE / L2_S_SIZE;
   3861 		}
   3862 		KDASSERTMSG(mappings <= l2b->l2b_occupancy, "%u %u",
   3863 		    mappings, l2b->l2b_occupancy);
   3864 		l2b->l2b_occupancy -= mappings;
   3865 		//PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
   3866 #ifdef UVMHIST
   3867 		total_mappings += mappings;
   3868 #endif
   3869 	}
   3870 	pmap_release_pmap_lock(pmap_kernel());
   3871 	cpu_cpwait();
   3872 	UVMHIST_LOG(maphist, "  <--- done (%u mappings removed)",
   3873 	    total_mappings, 0, 0, 0);
   3874 }
   3875 
   3876 bool
   3877 pmap_extract(pmap_t pm, vaddr_t va, paddr_t *pap)
   3878 {
   3879 	struct l2_dtable *l2;
   3880 	pd_entry_t *pdep, pde;
   3881 	pt_entry_t *ptep, pte;
   3882 	paddr_t pa;
   3883 	u_int l1slot;
   3884 
   3885 	pmap_acquire_pmap_lock(pm);
   3886 
   3887 	l1slot = l1pte_index(va);
   3888 	pdep = pmap_l1_kva(pm) + l1slot;
   3889 	pde = *pdep;
   3890 
   3891 	if (l1pte_section_p(pde)) {
   3892 		/*
   3893 		 * These should only happen for pmap_kernel()
   3894 		 */
   3895 		KDASSERT(pm == pmap_kernel());
   3896 		pmap_release_pmap_lock(pm);
   3897 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
   3898 		if (l1pte_supersection_p(pde)) {
   3899 			pa = (pde & L1_SS_FRAME) | (va & L1_SS_OFFSET);
   3900 		} else
   3901 #endif
   3902 			pa = (pde & L1_S_FRAME) | (va & L1_S_OFFSET);
   3903 	} else {
   3904 		/*
   3905 		 * Note that we can't rely on the validity of the L1
   3906 		 * descriptor as an indication that a mapping exists.
   3907 		 * We have to look it up in the L2 dtable.
   3908 		 */
   3909 		l2 = pm->pm_l2[L2_IDX(l1slot)];
   3910 
   3911 		if (l2 == NULL ||
   3912 		    (ptep = l2->l2_bucket[L2_BUCKET(l1slot)].l2b_kva) == NULL) {
   3913 			pmap_release_pmap_lock(pm);
   3914 			return false;
   3915 		}
   3916 
   3917 		pte = ptep[l2pte_index(va)];
   3918 		pmap_release_pmap_lock(pm);
   3919 
   3920 		if (pte == 0)
   3921 			return false;
   3922 
   3923 		switch (pte & L2_TYPE_MASK) {
   3924 		case L2_TYPE_L:
   3925 			pa = (pte & L2_L_FRAME) | (va & L2_L_OFFSET);
   3926 			break;
   3927 
   3928 		default:
   3929 			pa = (pte & ~PAGE_MASK) | (va & PAGE_MASK);
   3930 			break;
   3931 		}
   3932 	}
   3933 
   3934 	if (pap != NULL)
   3935 		*pap = pa;
   3936 
   3937 	return true;
   3938 }
   3939 
   3940 /*
   3941  * pmap_pv_remove: remove an unmanaged pv-tracked page from all pmaps
   3942  *	that map it
   3943  */
   3944 
   3945 static void
   3946 pmap_pv_remove(paddr_t pa)
   3947 {
   3948 	struct pmap_page *pp;
   3949 
   3950 	pp = pmap_pv_tracked(pa);
   3951 	if (pp == NULL)
   3952 		panic("pmap_pv_protect: page not pv-tracked: 0x%"PRIxPADDR,
   3953 		    pa);
   3954 
   3955 	struct vm_page_md *md = PMAP_PAGE_TO_MD(pp);
   3956 	pmap_page_remove(md, pa);
   3957 }
   3958 
   3959 void
   3960 pmap_pv_protect(paddr_t pa, vm_prot_t prot)
   3961 {
   3962 
   3963 	/* the only case is remove at the moment */
   3964 	KASSERT(prot == VM_PROT_NONE);
   3965 	pmap_pv_remove(pa);
   3966 }
   3967 
   3968 void
   3969 pmap_protect(pmap_t pm, vaddr_t sva, vaddr_t eva, vm_prot_t prot)
   3970 {
   3971 	struct l2_bucket *l2b;
   3972 	vaddr_t next_bucket;
   3973 
   3974 	NPDEBUG(PDB_PROTECT,
   3975 	    printf("pmap_protect: pm %p sva 0x%lx eva 0x%lx prot 0x%x\n",
   3976 	    pm, sva, eva, prot));
   3977 
   3978 	if ((prot & VM_PROT_READ) == 0) {
   3979 		pmap_remove(pm, sva, eva);
   3980 		return;
   3981 	}
   3982 
   3983 	if (prot & VM_PROT_WRITE) {
   3984 		/*
   3985 		 * If this is a read->write transition, just ignore it and let
   3986 		 * uvm_fault() take care of it later.
   3987 		 */
   3988 		return;
   3989 	}
   3990 
   3991 	pmap_acquire_pmap_lock(pm);
   3992 
   3993 #ifndef ARM_MMU_EXTENDED
   3994 	const bool flush = eva - sva >= PAGE_SIZE * 4;
   3995 	u_int flags = 0;
   3996 #endif
   3997 	u_int clr_mask = PVF_WRITE | ((prot & VM_PROT_EXECUTE) ? 0 : PVF_EXEC);
   3998 
   3999 	while (sva < eva) {
   4000 		next_bucket = L2_NEXT_BUCKET_VA(sva);
   4001 		if (next_bucket > eva)
   4002 			next_bucket = eva;
   4003 
   4004 		l2b = pmap_get_l2_bucket(pm, sva);
   4005 		if (l2b == NULL) {
   4006 			sva = next_bucket;
   4007 			continue;
   4008 		}
   4009 
   4010 		pt_entry_t *ptep = &l2b->l2b_kva[l2pte_index(sva)];
   4011 
   4012 		while (sva < next_bucket) {
   4013 			const pt_entry_t opte = *ptep;
   4014 			if (l2pte_valid_p(opte) && l2pte_writable_p(opte)) {
   4015 				struct vm_page *pg;
   4016 #ifndef ARM_MMU_EXTENDED
   4017 				u_int f;
   4018 #endif
   4019 
   4020 #ifdef PMAP_CACHE_VIVT
   4021 				/*
   4022 				 * OK, at this point, we know we're doing
   4023 				 * write-protect operation.  If the pmap is
   4024 				 * active, write-back the page.
   4025 				 */
   4026 				pmap_cache_wbinv_page(pm, sva, false,
   4027 				    PVF_REF | PVF_WRITE);
   4028 #endif
   4029 
   4030 				pg = PHYS_TO_VM_PAGE(l2pte_pa(opte));
   4031 				pt_entry_t npte = l2pte_set_readonly(opte);
   4032 				l2pte_reset(ptep);
   4033 				PTE_SYNC(ptep);
   4034 #ifdef ARM_MMU_EXTENDED
   4035 				pmap_tlb_flush_SE(pm, sva, PVF_REF);
   4036 #endif
   4037 				l2pte_set(ptep, npte, 0);
   4038 				PTE_SYNC(ptep);
   4039 
   4040 				if (pg != NULL) {
   4041 					struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4042 					paddr_t pa = VM_PAGE_TO_PHYS(pg);
   4043 
   4044 					pmap_acquire_page_lock(md);
   4045 #ifndef ARM_MMU_EXTENDED
   4046 					f =
   4047 #endif
   4048 					    pmap_modify_pv(md, pa, pm, sva,
   4049 					       clr_mask, 0);
   4050 					pmap_vac_me_harder(md, pa, pm, sva);
   4051 					pmap_release_page_lock(md);
   4052 #ifndef ARM_MMU_EXTENDED
   4053 				} else {
   4054 					f = PVF_REF | PVF_EXEC;
   4055 				}
   4056 
   4057 				if (flush) {
   4058 					flags |= f;
   4059 				} else {
   4060 					pmap_tlb_flush_SE(pm, sva, f);
   4061 #endif
   4062 				}
   4063 			}
   4064 
   4065 			sva += PAGE_SIZE;
   4066 			ptep += PAGE_SIZE / L2_S_SIZE;
   4067 		}
   4068 	}
   4069 
   4070 #ifndef ARM_MMU_EXTENDED
   4071 	if (flush) {
   4072 		if (PV_BEEN_EXECD(flags)) {
   4073 			pmap_tlb_flushID(pm);
   4074 		} else if (PV_BEEN_REFD(flags)) {
   4075 			pmap_tlb_flushD(pm);
   4076 		}
   4077 	}
   4078 #endif
   4079 
   4080 	pmap_release_pmap_lock(pm);
   4081 }
   4082 
   4083 void
   4084 pmap_icache_sync_range(pmap_t pm, vaddr_t sva, vaddr_t eva)
   4085 {
   4086 	struct l2_bucket *l2b;
   4087 	pt_entry_t *ptep;
   4088 	vaddr_t next_bucket;
   4089 	vsize_t page_size = trunc_page(sva) + PAGE_SIZE - sva;
   4090 
   4091 	NPDEBUG(PDB_EXEC,
   4092 	    printf("pmap_icache_sync_range: pm %p sva 0x%lx eva 0x%lx\n",
   4093 	    pm, sva, eva));
   4094 
   4095 	pmap_acquire_pmap_lock(pm);
   4096 
   4097 	while (sva < eva) {
   4098 		next_bucket = L2_NEXT_BUCKET_VA(sva);
   4099 		if (next_bucket > eva)
   4100 			next_bucket = eva;
   4101 
   4102 		l2b = pmap_get_l2_bucket(pm, sva);
   4103 		if (l2b == NULL) {
   4104 			sva = next_bucket;
   4105 			continue;
   4106 		}
   4107 
   4108 		for (ptep = &l2b->l2b_kva[l2pte_index(sva)];
   4109 		     sva < next_bucket;
   4110 		     sva += page_size,
   4111 		     ptep += PAGE_SIZE / L2_S_SIZE,
   4112 		     page_size = PAGE_SIZE) {
   4113 			if (l2pte_valid_p(*ptep)) {
   4114 				cpu_icache_sync_range(sva,
   4115 				    min(page_size, eva - sva));
   4116 			}
   4117 		}
   4118 	}
   4119 
   4120 	pmap_release_pmap_lock(pm);
   4121 }
   4122 
   4123 void
   4124 pmap_page_protect(struct vm_page *pg, vm_prot_t prot)
   4125 {
   4126 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4127 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
   4128 
   4129 	NPDEBUG(PDB_PROTECT,
   4130 	    printf("pmap_page_protect: md %p (0x%08lx), prot 0x%x\n",
   4131 	    md, pa, prot));
   4132 
   4133 	switch(prot) {
   4134 	case VM_PROT_READ|VM_PROT_WRITE:
   4135 #if defined(ARM_MMU_EXTENDED)
   4136 		pmap_acquire_page_lock(md);
   4137 		pmap_clearbit(md, pa, PVF_EXEC);
   4138 		pmap_release_page_lock(md);
   4139 		break;
   4140 #endif
   4141 	case VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE:
   4142 		break;
   4143 
   4144 	case VM_PROT_READ:
   4145 #if defined(ARM_MMU_EXTENDED)
   4146 		pmap_acquire_page_lock(md);
   4147 		pmap_clearbit(md, pa, PVF_WRITE|PVF_EXEC);
   4148 		pmap_release_page_lock(md);
   4149 		break;
   4150 #endif
   4151 	case VM_PROT_READ|VM_PROT_EXECUTE:
   4152 		pmap_acquire_page_lock(md);
   4153 		pmap_clearbit(md, pa, PVF_WRITE);
   4154 		pmap_release_page_lock(md);
   4155 		break;
   4156 
   4157 	default:
   4158 		pmap_page_remove(md, pa);
   4159 		break;
   4160 	}
   4161 }
   4162 
   4163 /*
   4164  * pmap_clear_modify:
   4165  *
   4166  *	Clear the "modified" attribute for a page.
   4167  */
   4168 bool
   4169 pmap_clear_modify(struct vm_page *pg)
   4170 {
   4171 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4172 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
   4173 	bool rv;
   4174 
   4175 	pmap_acquire_page_lock(md);
   4176 
   4177 	if (md->pvh_attrs & PVF_MOD) {
   4178 		rv = true;
   4179 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   4180 		/*
   4181 		 * If we are going to clear the modified bit and there are
   4182 		 * no other modified bits set, flush the page to memory and
   4183 		 * mark it clean.
   4184 		 */
   4185 		if ((md->pvh_attrs & (PVF_DMOD|PVF_NC)) == PVF_MOD)
   4186 			pmap_flush_page(md, pa, PMAP_CLEAN_PRIMARY);
   4187 #endif
   4188 		pmap_clearbit(md, pa, PVF_MOD);
   4189 	} else {
   4190 		rv = false;
   4191 	}
   4192 	pmap_release_page_lock(md);
   4193 
   4194 	return rv;
   4195 }
   4196 
   4197 /*
   4198  * pmap_clear_reference:
   4199  *
   4200  *	Clear the "referenced" attribute for a page.
   4201  */
   4202 bool
   4203 pmap_clear_reference(struct vm_page *pg)
   4204 {
   4205 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4206 	paddr_t pa = VM_PAGE_TO_PHYS(pg);
   4207 	bool rv;
   4208 
   4209 	pmap_acquire_page_lock(md);
   4210 
   4211 	if (md->pvh_attrs & PVF_REF) {
   4212 		rv = true;
   4213 		pmap_clearbit(md, pa, PVF_REF);
   4214 	} else {
   4215 		rv = false;
   4216 	}
   4217 	pmap_release_page_lock(md);
   4218 
   4219 	return rv;
   4220 }
   4221 
   4222 /*
   4223  * pmap_is_modified:
   4224  *
   4225  *	Test if a page has the "modified" attribute.
   4226  */
   4227 /* See <arm/arm32/pmap.h> */
   4228 
   4229 /*
   4230  * pmap_is_referenced:
   4231  *
   4232  *	Test if a page has the "referenced" attribute.
   4233  */
   4234 /* See <arm/arm32/pmap.h> */
   4235 
   4236 #if defined(ARM_MMU_EXTENDED) && 0
   4237 int
   4238 pmap_prefetchabt_fixup(void *v)
   4239 {
   4240 	struct trapframe * const tf = v;
   4241 	vaddr_t va = trunc_page(tf->tf_pc);
   4242 	int rv = ABORT_FIXUP_FAILED;
   4243 
   4244 	if (!TRAP_USERMODE(tf) && va < VM_MAXUSER_ADDRESS)
   4245 		return rv;
   4246 
   4247 	kpreempt_disable();
   4248 	pmap_t pm = curcpu()->ci_pmap_cur;
   4249 	const size_t l1slot = l1pte_index(va);
   4250 	struct l2_dtable * const l2 = pm->pm_l2[L2_IDX(l1slot)];
   4251 	if (l2 == NULL)
   4252 		goto out;
   4253 
   4254 	struct l2_bucket * const l2b = &l2->l2_bucket[L2_BUCKET(l1slot)];
   4255 	if (l2b->l2b_kva == NULL)
   4256 		goto out;
   4257 
   4258 	/*
   4259 	 * Check the PTE itself.
   4260 	 */
   4261 	pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   4262 	const pt_entry_t opte = *ptep;
   4263 	if ((opte & L2_S_PROT_U) == 0 || (opte & L2_XS_XN) == 0)
   4264 		goto out;
   4265 
   4266 	paddr_t pa = l2pte_pa(opte);
   4267 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   4268 	KASSERT(pg != NULL);
   4269 
   4270 	struct vm_page_md * const md = VM_PAGE_TO_MD(pg);
   4271 
   4272 	pmap_acquire_page_lock(md);
   4273 	struct pv_entry * const pv = pmap_find_pv(md, pm, va);
   4274 	KASSERT(pv != NULL);
   4275 
   4276 	if (PV_IS_EXEC_P(pv->pv_flags)) {
   4277 		l2pte_reset(ptep);
   4278 		PTE_SYNC(ptep);
   4279 		pmap_tlb_flush_SE(pm, va, PVF_EXEC | PVF_REF);
   4280 		if (!PV_IS_EXEC_P(md->pvh_attrs)) {
   4281 			pmap_syncicache_page(md, pa);
   4282 		}
   4283 		rv = ABORT_FIXUP_RETURN;
   4284 		l2pte_set(ptep, opte & ~L2_XS_XN, 0);
   4285 		PTE_SYNC(ptep);
   4286 	}
   4287 	pmap_release_page_lock(md);
   4288 
   4289   out:
   4290 	kpreempt_enable();
   4291 	return rv;
   4292 }
   4293 #endif
   4294 
   4295 int
   4296 pmap_fault_fixup(pmap_t pm, vaddr_t va, vm_prot_t ftype, int user)
   4297 {
   4298 	struct l2_dtable *l2;
   4299 	struct l2_bucket *l2b;
   4300 	paddr_t pa;
   4301 	const size_t l1slot = l1pte_index(va);
   4302 	int rv = 0;
   4303 
   4304 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   4305 
   4306 	va = trunc_page(va);
   4307 
   4308 	KASSERT(!user || (pm != pmap_kernel()));
   4309 
   4310 	UVMHIST_LOG(maphist, " (pm=%#x, va=%#x, ftype=%#x, user=%d)",
   4311 	    pm, va, ftype, user);
   4312 #ifdef ARM_MMU_EXTENDED
   4313 	UVMHIST_LOG(maphist, " ti=%#x pai=%#x asid=%#x",
   4314 	    cpu_tlb_info(curcpu()), PMAP_PAI(pm, cpu_tlb_info(curcpu())),
   4315 	    PMAP_PAI(pm, cpu_tlb_info(curcpu()))->pai_asid, 0);
   4316 #endif
   4317 
   4318 	pmap_acquire_pmap_lock(pm);
   4319 
   4320 	/*
   4321 	 * If there is no l2_dtable for this address, then the process
   4322 	 * has no business accessing it.
   4323 	 *
   4324 	 * Note: This will catch userland processes trying to access
   4325 	 * kernel addresses.
   4326 	 */
   4327 	l2 = pm->pm_l2[L2_IDX(l1slot)];
   4328 	if (l2 == NULL) {
   4329 		UVMHIST_LOG(maphist, " no l2 for l1slot %#x", l1slot, 0, 0, 0);
   4330 		goto out;
   4331 	}
   4332 
   4333 	/*
   4334 	 * Likewise if there is no L2 descriptor table
   4335 	 */
   4336 	l2b = &l2->l2_bucket[L2_BUCKET(l1slot)];
   4337 	if (l2b->l2b_kva == NULL) {
   4338 		UVMHIST_LOG(maphist, " <-- done (no ptep for l1slot %#x)", l1slot, 0, 0, 0);
   4339 		goto out;
   4340 	}
   4341 
   4342 	/*
   4343 	 * Check the PTE itself.
   4344 	 */
   4345 	pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   4346 	pt_entry_t const opte = *ptep;
   4347 	if (opte == 0 || (opte & L2_TYPE_MASK) == L2_TYPE_L) {
   4348 		UVMHIST_LOG(maphist, " <-- done (empty pde for l1slot %#x)", l1slot, 0, 0, 0);
   4349 		goto out;
   4350 	}
   4351 
   4352 #ifndef ARM_HAS_VBAR
   4353 	/*
   4354 	 * Catch a userland access to the vector page mapped at 0x0
   4355 	 */
   4356 	if (user && (opte & L2_S_PROT_U) == 0) {
   4357 		UVMHIST_LOG(maphist, " <-- done (vector_page)", 0, 0, 0, 0);
   4358 		goto out;
   4359 	}
   4360 #endif
   4361 
   4362 	pa = l2pte_pa(opte);
   4363 
   4364 	if ((ftype & VM_PROT_WRITE) && !l2pte_writable_p(opte)) {
   4365 		/*
   4366 		 * This looks like a good candidate for "page modified"
   4367 		 * emulation...
   4368 		 */
   4369 		struct pv_entry *pv;
   4370 		struct vm_page *pg;
   4371 
   4372 		/* Extract the physical address of the page */
   4373 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL) {
   4374 			UVMHIST_LOG(maphist, " <-- done (mod/ref unmanaged page)", 0, 0, 0, 0);
   4375 			goto out;
   4376 		}
   4377 
   4378 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4379 
   4380 		/* Get the current flags for this page. */
   4381 		pmap_acquire_page_lock(md);
   4382 		pv = pmap_find_pv(md, pm, va);
   4383 		if (pv == NULL || PV_IS_KENTRY_P(pv->pv_flags)) {
   4384 			pmap_release_page_lock(md);
   4385 			UVMHIST_LOG(maphist, " <-- done (mod/ref emul: no PV)", 0, 0, 0, 0);
   4386 			goto out;
   4387 		}
   4388 
   4389 		/*
   4390 		 * Do the flags say this page is writable? If not then it
   4391 		 * is a genuine write fault. If yes then the write fault is
   4392 		 * our fault as we did not reflect the write access in the
   4393 		 * PTE. Now we know a write has occurred we can correct this
   4394 		 * and also set the modified bit
   4395 		 */
   4396 		if ((pv->pv_flags & PVF_WRITE) == 0) {
   4397 			pmap_release_page_lock(md);
   4398 			goto out;
   4399 		}
   4400 
   4401 		md->pvh_attrs |= PVF_REF | PVF_MOD;
   4402 		pv->pv_flags |= PVF_REF | PVF_MOD;
   4403 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   4404 		/*
   4405 		 * If there are cacheable mappings for this page, mark it dirty.
   4406 		 */
   4407 		if ((md->pvh_attrs & PVF_NC) == 0)
   4408 			md->pvh_attrs |= PVF_DIRTY;
   4409 #endif
   4410 #ifdef ARM_MMU_EXTENDED
   4411 		if (md->pvh_attrs & PVF_EXEC) {
   4412 			md->pvh_attrs &= ~PVF_EXEC;
   4413 			PMAPCOUNT(exec_discarded_modfixup);
   4414 		}
   4415 #endif
   4416 		pmap_release_page_lock(md);
   4417 
   4418 		/*
   4419 		 * Re-enable write permissions for the page.  No need to call
   4420 		 * pmap_vac_me_harder(), since this is just a
   4421 		 * modified-emulation fault, and the PVF_WRITE bit isn't
   4422 		 * changing. We've already set the cacheable bits based on
   4423 		 * the assumption that we can write to this page.
   4424 		 */
   4425 		const pt_entry_t npte =
   4426 		    l2pte_set_writable((opte & ~L2_TYPE_MASK) | L2_S_PROTO)
   4427 #ifdef ARM_MMU_EXTENDED
   4428 		    | (pm != pmap_kernel() ? L2_XS_nG : 0)
   4429 #endif
   4430 		    | 0;
   4431 		l2pte_reset(ptep);
   4432 		PTE_SYNC(ptep);
   4433 		pmap_tlb_flush_SE(pm, va,
   4434 		    (ftype & VM_PROT_EXECUTE) ? PVF_EXEC | PVF_REF : PVF_REF);
   4435 		l2pte_set(ptep, npte, 0);
   4436 		PTE_SYNC(ptep);
   4437 		PMAPCOUNT(fixup_mod);
   4438 		rv = 1;
   4439 		UVMHIST_LOG(maphist, " <-- done (mod/ref emul: changed pte from %#x to %#x)",
   4440 		    opte, npte, 0, 0);
   4441 	} else if ((opte & L2_TYPE_MASK) == L2_TYPE_INV) {
   4442 		/*
   4443 		 * This looks like a good candidate for "page referenced"
   4444 		 * emulation.
   4445 		 */
   4446 		struct vm_page *pg;
   4447 
   4448 		/* Extract the physical address of the page */
   4449 		if ((pg = PHYS_TO_VM_PAGE(pa)) == NULL) {
   4450 			UVMHIST_LOG(maphist, " <-- done (ref emul: unmanaged page)", 0, 0, 0, 0);
   4451 			goto out;
   4452 		}
   4453 
   4454 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4455 
   4456 		/* Get the current flags for this page. */
   4457 		pmap_acquire_page_lock(md);
   4458 		struct pv_entry *pv = pmap_find_pv(md, pm, va);
   4459 		if (pv == NULL || PV_IS_KENTRY_P(pv->pv_flags)) {
   4460 			pmap_release_page_lock(md);
   4461 			UVMHIST_LOG(maphist, " <-- done (ref emul no PV)", 0, 0, 0, 0);
   4462 			goto out;
   4463 		}
   4464 
   4465 		md->pvh_attrs |= PVF_REF;
   4466 		pv->pv_flags |= PVF_REF;
   4467 
   4468 		pt_entry_t npte =
   4469 		    l2pte_set_readonly((opte & ~L2_TYPE_MASK) | L2_S_PROTO);
   4470 #ifdef ARM_MMU_EXTENDED
   4471 		if (pm != pmap_kernel()) {
   4472 			npte |= L2_XS_nG;
   4473 		}
   4474 		/*
   4475 		 * If we got called from prefetch abort, then ftype will have
   4476 		 * VM_PROT_EXECUTE set.  Now see if we have no-execute set in
   4477 		 * the PTE.
   4478 		 */
   4479 		if (user && (ftype & VM_PROT_EXECUTE) && (npte & L2_XS_XN)) {
   4480 			/*
   4481 			 * Is this a mapping of an executable page?
   4482 			 */
   4483 			if ((pv->pv_flags & PVF_EXEC) == 0) {
   4484 				pmap_release_page_lock(md);
   4485 				UVMHIST_LOG(maphist, " <-- done (ref emul: no exec)",
   4486 				    0, 0, 0, 0);
   4487 				goto out;
   4488 			}
   4489 			/*
   4490 			 * If we haven't synced the page, do so now.
   4491 			 */
   4492 			if ((md->pvh_attrs & PVF_EXEC) == 0) {
   4493 				UVMHIST_LOG(maphist, " ref emul: syncicache page #%#x",
   4494 				    pa, 0, 0, 0);
   4495 				pmap_syncicache_page(md, pa);
   4496 				PMAPCOUNT(fixup_exec);
   4497 			}
   4498 			npte &= ~L2_XS_XN;
   4499 		}
   4500 #endif /* ARM_MMU_EXTENDED */
   4501 		pmap_release_page_lock(md);
   4502 		l2pte_reset(ptep);
   4503 		PTE_SYNC(ptep);
   4504 		pmap_tlb_flush_SE(pm, va,
   4505 		    (ftype & VM_PROT_EXECUTE) ? PVF_EXEC | PVF_REF : PVF_REF);
   4506 		l2pte_set(ptep, npte, 0);
   4507 		PTE_SYNC(ptep);
   4508 		PMAPCOUNT(fixup_ref);
   4509 		rv = 1;
   4510 		UVMHIST_LOG(maphist, " <-- done (ref emul: changed pte from %#x to %#x)",
   4511 		    opte, npte, 0, 0);
   4512 #ifdef ARM_MMU_EXTENDED
   4513 	} else if (user && (ftype & VM_PROT_EXECUTE) && (opte & L2_XS_XN)) {
   4514 		struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   4515 		if (pg == NULL) {
   4516 			UVMHIST_LOG(maphist, " <-- done (unmanaged page)", 0, 0, 0, 0);
   4517 			goto out;
   4518 		}
   4519 
   4520 		struct vm_page_md * const md = VM_PAGE_TO_MD(pg);
   4521 
   4522 		/* Get the current flags for this page. */
   4523 		pmap_acquire_page_lock(md);
   4524 		struct pv_entry * const pv = pmap_find_pv(md, pm, va);
   4525 		if (pv == NULL || (pv->pv_flags & PVF_EXEC) == 0) {
   4526 			pmap_release_page_lock(md);
   4527 			UVMHIST_LOG(maphist, " <-- done (no PV or not EXEC)", 0, 0, 0, 0);
   4528 			goto out;
   4529 		}
   4530 
   4531 		/*
   4532 		 * If we haven't synced the page, do so now.
   4533 		 */
   4534 		if ((md->pvh_attrs & PVF_EXEC) == 0) {
   4535 			UVMHIST_LOG(maphist, "syncicache page #%#x",
   4536 			    pa, 0, 0, 0);
   4537 			pmap_syncicache_page(md, pa);
   4538 		}
   4539 		pmap_release_page_lock(md);
   4540 		/*
   4541 		 * Turn off no-execute.
   4542 		 */
   4543 		KASSERT(opte & L2_XS_nG);
   4544 		l2pte_reset(ptep);
   4545 		PTE_SYNC(ptep);
   4546 		pmap_tlb_flush_SE(pm, va, PVF_EXEC | PVF_REF);
   4547 		l2pte_set(ptep, opte & ~L2_XS_XN, 0);
   4548 		PTE_SYNC(ptep);
   4549 		rv = 1;
   4550 		PMAPCOUNT(fixup_exec);
   4551 		UVMHIST_LOG(maphist, "exec: changed pte from %#x to %#x",
   4552 		    opte, opte & ~L2_XS_XN, 0, 0);
   4553 #endif
   4554 	}
   4555 
   4556 #ifndef ARM_MMU_EXTENDED
   4557 	/*
   4558 	 * We know there is a valid mapping here, so simply
   4559 	 * fix up the L1 if necessary.
   4560 	 */
   4561 	pd_entry_t * const pdep = pmap_l1_kva(pm) + l1slot;
   4562 	pd_entry_t pde = L1_C_PROTO | l2b->l2b_pa | L1_C_DOM(pmap_domain(pm));
   4563 	if (*pdep != pde) {
   4564 		l1pte_setone(pdep, pde);
   4565 		PDE_SYNC(pdep);
   4566 		rv = 1;
   4567 		PMAPCOUNT(fixup_pdes);
   4568 	}
   4569 #endif
   4570 
   4571 #ifdef CPU_SA110
   4572 	/*
   4573 	 * There are bugs in the rev K SA110.  This is a check for one
   4574 	 * of them.
   4575 	 */
   4576 	if (rv == 0 && curcpu()->ci_arm_cputype == CPU_ID_SA110 &&
   4577 	    curcpu()->ci_arm_cpurev < 3) {
   4578 		/* Always current pmap */
   4579 		if (l2pte_valid_p(opte)) {
   4580 			extern int kernel_debug;
   4581 			if (kernel_debug & 1) {
   4582 				struct proc *p = curlwp->l_proc;
   4583 				printf("prefetch_abort: page is already "
   4584 				    "mapped - pte=%p *pte=%08x\n", ptep, opte);
   4585 				printf("prefetch_abort: pc=%08lx proc=%p "
   4586 				    "process=%s\n", va, p, p->p_comm);
   4587 				printf("prefetch_abort: far=%08x fs=%x\n",
   4588 				    cpu_faultaddress(), cpu_faultstatus());
   4589 			}
   4590 #ifdef DDB
   4591 			if (kernel_debug & 2)
   4592 				Debugger();
   4593 #endif
   4594 			rv = 1;
   4595 		}
   4596 	}
   4597 #endif /* CPU_SA110 */
   4598 
   4599 #ifndef ARM_MMU_EXTENDED
   4600 	/*
   4601 	 * If 'rv == 0' at this point, it generally indicates that there is a
   4602 	 * stale TLB entry for the faulting address.  That might be due to a
   4603 	 * wrong setting of pmap_needs_pte_sync.  So set it and retry.
   4604 	 */
   4605 	if (rv == 0
   4606 	    && pm->pm_l1->l1_domain_use_count == 1
   4607 	    && pmap_needs_pte_sync == 0) {
   4608 		pmap_needs_pte_sync = 1;
   4609 		PTE_SYNC(ptep);
   4610 		PMAPCOUNT(fixup_ptesync);
   4611 		rv = 1;
   4612 	}
   4613 #endif
   4614 
   4615 #ifndef MULTIPROCESSOR
   4616 #if defined(DEBUG) || 1
   4617 	/*
   4618 	 * If 'rv == 0' at this point, it generally indicates that there is a
   4619 	 * stale TLB entry for the faulting address. This happens when two or
   4620 	 * more processes are sharing an L1. Since we don't flush the TLB on
   4621 	 * a context switch between such processes, we can take domain faults
   4622 	 * for mappings which exist at the same VA in both processes. EVEN IF
   4623 	 * WE'VE RECENTLY FIXED UP THE CORRESPONDING L1 in pmap_enter(), for
   4624 	 * example.
   4625 	 *
   4626 	 * This is extremely likely to happen if pmap_enter() updated the L1
   4627 	 * entry for a recently entered mapping. In this case, the TLB is
   4628 	 * flushed for the new mapping, but there may still be TLB entries for
   4629 	 * other mappings belonging to other processes in the 1MB range
   4630 	 * covered by the L1 entry.
   4631 	 *
   4632 	 * Since 'rv == 0', we know that the L1 already contains the correct
   4633 	 * value, so the fault must be due to a stale TLB entry.
   4634 	 *
   4635 	 * Since we always need to flush the TLB anyway in the case where we
   4636 	 * fixed up the L1, or frobbed the L2 PTE, we effectively deal with
   4637 	 * stale TLB entries dynamically.
   4638 	 *
   4639 	 * However, the above condition can ONLY happen if the current L1 is
   4640 	 * being shared. If it happens when the L1 is unshared, it indicates
   4641 	 * that other parts of the pmap are not doing their job WRT managing
   4642 	 * the TLB.
   4643 	 */
   4644 	if (rv == 0
   4645 #ifndef ARM_MMU_EXTENDED
   4646 	    && pm->pm_l1->l1_domain_use_count == 1
   4647 #endif
   4648 	    && true) {
   4649 #ifdef DEBUG
   4650 		extern int last_fault_code;
   4651 #else
   4652 		int last_fault_code = ftype & VM_PROT_EXECUTE
   4653 		    ? armreg_ifsr_read()
   4654 		    : armreg_dfsr_read();
   4655 #endif
   4656 		printf("fixup: pm %p, va 0x%lx, ftype %d - nothing to do!\n",
   4657 		    pm, va, ftype);
   4658 		printf("fixup: l2 %p, l2b %p, ptep %p, pte %#x\n",
   4659 		    l2, l2b, ptep, opte);
   4660 
   4661 #ifndef ARM_MMU_EXTENDED
   4662 		printf("fixup: pdep %p, pde %#x, fsr %#x\n",
   4663 		    pdep, pde, last_fault_code);
   4664 #else
   4665 		printf("fixup: pdep %p, pde %#x, ttbcr %#x\n",
   4666 		    &pmap_l1_kva(pm)[l1slot], pmap_l1_kva(pm)[l1slot],
   4667 		   armreg_ttbcr_read());
   4668 		printf("fixup: fsr %#x cpm %p casid %#x contextidr %#x dacr %#x\n",
   4669 		    last_fault_code, curcpu()->ci_pmap_cur,
   4670 		    curcpu()->ci_pmap_asid_cur,
   4671 		    armreg_contextidr_read(), armreg_dacr_read());
   4672 #ifdef _ARM_ARCH_7
   4673 		if (ftype & VM_PROT_WRITE)
   4674 			armreg_ats1cuw_write(va);
   4675 		else
   4676 			armreg_ats1cur_write(va);
   4677 		arm_isb();
   4678 		printf("fixup: par %#x\n", armreg_par_read());
   4679 #endif
   4680 #endif
   4681 #ifdef DDB
   4682 		extern int kernel_debug;
   4683 
   4684 		if (kernel_debug & 2) {
   4685 			pmap_release_pmap_lock(pm);
   4686 #ifdef UVMHIST
   4687 			KERNHIST_DUMP(maphist);
   4688 #endif
   4689 			cpu_Debugger();
   4690 			pmap_acquire_pmap_lock(pm);
   4691 		}
   4692 #endif
   4693 	}
   4694 #endif
   4695 #endif
   4696 
   4697 #ifndef ARM_MMU_EXTENDED
   4698 	/* Flush the TLB in the shared L1 case - see comment above */
   4699 	pmap_tlb_flush_SE(pm, va,
   4700 	    (ftype & VM_PROT_EXECUTE) ? PVF_EXEC | PVF_REF : PVF_REF);
   4701 #endif
   4702 
   4703 	rv = 1;
   4704 
   4705 out:
   4706 	pmap_release_pmap_lock(pm);
   4707 
   4708 	return (rv);
   4709 }
   4710 
   4711 /*
   4712  * Routine:	pmap_procwr
   4713  *
   4714  * Function:
   4715  *	Synchronize caches corresponding to [addr, addr+len) in p.
   4716  *
   4717  */
   4718 void
   4719 pmap_procwr(struct proc *p, vaddr_t va, int len)
   4720 {
   4721 #ifndef ARM_MMU_EXTENDED
   4722 
   4723 	/* We only need to do anything if it is the current process. */
   4724 	if (p == curproc)
   4725 		cpu_icache_sync_range(va, len);
   4726 #endif
   4727 }
   4728 
   4729 /*
   4730  * Routine:	pmap_unwire
   4731  * Function:	Clear the wired attribute for a map/virtual-address pair.
   4732  *
   4733  * In/out conditions:
   4734  *		The mapping must already exist in the pmap.
   4735  */
   4736 void
   4737 pmap_unwire(pmap_t pm, vaddr_t va)
   4738 {
   4739 	struct l2_bucket *l2b;
   4740 	pt_entry_t *ptep, pte;
   4741 	struct vm_page *pg;
   4742 	paddr_t pa;
   4743 
   4744 	NPDEBUG(PDB_WIRING, printf("pmap_unwire: pm %p, va 0x%08lx\n", pm, va));
   4745 
   4746 	pmap_acquire_pmap_lock(pm);
   4747 
   4748 	l2b = pmap_get_l2_bucket(pm, va);
   4749 	KDASSERT(l2b != NULL);
   4750 
   4751 	ptep = &l2b->l2b_kva[l2pte_index(va)];
   4752 	pte = *ptep;
   4753 
   4754 	/* Extract the physical address of the page */
   4755 	pa = l2pte_pa(pte);
   4756 
   4757 	if ((pg = PHYS_TO_VM_PAGE(pa)) != NULL) {
   4758 		/* Update the wired bit in the pv entry for this page. */
   4759 		struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   4760 
   4761 		pmap_acquire_page_lock(md);
   4762 		(void) pmap_modify_pv(md, pa, pm, va, PVF_WIRED, 0);
   4763 		pmap_release_page_lock(md);
   4764 	}
   4765 
   4766 	pmap_release_pmap_lock(pm);
   4767 }
   4768 
   4769 #ifdef ARM_MMU_EXTENDED
   4770 void
   4771 pmap_md_pdetab_activate(pmap_t pm, struct lwp *l)
   4772 {
   4773 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   4774 
   4775 	/*
   4776 	 * Assume that TTBR1 has only global mappings and TTBR0 only
   4777 	 * has non-global mappings.  To prevent speculation from doing
   4778 	 * evil things we disable translation table walks using TTBR0
   4779 	 * before setting the CONTEXTIDR (ASID) or new TTBR0 value.
   4780 	 * Once both are set, table walks are reenabled.
   4781 	 */
   4782 	const uint32_t old_ttbcr = armreg_ttbcr_read();
   4783 	armreg_ttbcr_write(old_ttbcr | TTBCR_S_PD0);
   4784 	arm_isb();
   4785 
   4786 	pmap_tlb_asid_acquire(pm, l);
   4787 
   4788 	struct cpu_info * const ci = curcpu();
   4789 	struct pmap_asid_info * const pai = PMAP_PAI(pm, cpu_tlb_info(ci));
   4790 
   4791 	cpu_setttb(pm->pm_l1_pa, pai->pai_asid);
   4792 	/*
   4793 	 * Now we can reenable tablewalks since the CONTEXTIDR and TTRB0
   4794 	 * have been updated.
   4795 	 */
   4796 	arm_isb();
   4797 
   4798 	if (pm != pmap_kernel()) {
   4799 		armreg_ttbcr_write(old_ttbcr & ~TTBCR_S_PD0);
   4800 	}
   4801 	cpu_cpwait();
   4802 
   4803 	UVMHIST_LOG(maphist, " pm %p pm->pm_l1_pa %08x asid %u... done", pm,
   4804 	    pm->pm_l1_pa, pai->pai_asid, 0);
   4805 
   4806 	KASSERTMSG(ci->ci_pmap_asid_cur == pai->pai_asid, "%u vs %u",
   4807 	    ci->ci_pmap_asid_cur, pai->pai_asid);
   4808 	ci->ci_pmap_cur = pm;
   4809 }
   4810 
   4811 void
   4812 pmap_md_pdetab_deactivate(pmap_t pm)
   4813 {
   4814 
   4815 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   4816 
   4817 	kpreempt_disable();
   4818 	struct cpu_info * const ci = curcpu();
   4819 	/*
   4820 	 * Disable translation table walks from TTBR0 while no pmap has been
   4821 	 * activated.
   4822 	 */
   4823 	const uint32_t old_ttbcr = armreg_ttbcr_read();
   4824 	armreg_ttbcr_write(old_ttbcr | TTBCR_S_PD0);
   4825 	arm_isb();
   4826 	pmap_tlb_asid_deactivate(pm);
   4827 	cpu_setttb(pmap_kernel()->pm_l1_pa, KERNEL_PID);
   4828 	arm_isb();
   4829 
   4830 	ci->ci_pmap_cur = pmap_kernel();
   4831 	KASSERTMSG(ci->ci_pmap_asid_cur == KERNEL_PID, "ci_pmap_asid_cur %u",
   4832 	    ci->ci_pmap_asid_cur);
   4833 	kpreempt_enable();
   4834 }
   4835 #endif
   4836 
   4837 void
   4838 pmap_activate(struct lwp *l)
   4839 {
   4840 	extern int block_userspace_access;
   4841 	pmap_t npm = l->l_proc->p_vmspace->vm_map.pmap;
   4842 
   4843 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   4844 
   4845 	UVMHIST_LOG(maphist, "(l=%#x) pm=%#x", l, npm, 0, 0);
   4846 
   4847 	struct cpu_info * const ci = curcpu();
   4848 
   4849 	/*
   4850 	 * If activating a non-current lwp or the current lwp is
   4851 	 * already active, just return.
   4852 	 */
   4853 	if (false
   4854 	    || l != curlwp
   4855 #ifdef ARM_MMU_EXTENDED
   4856 	    || (ci->ci_pmap_cur == npm &&
   4857 		(npm == pmap_kernel()
   4858 		 /* || PMAP_PAI_ASIDVALID_P(pai, cpu_tlb_info(ci)) */))
   4859 #else
   4860 	    || npm->pm_activated == true
   4861 #endif
   4862 	    || false) {
   4863 		UVMHIST_LOG(maphist, " <-- (same pmap)", curlwp, l, 0, 0);
   4864 		return;
   4865 	}
   4866 
   4867 #ifndef ARM_MMU_EXTENDED
   4868 	const uint32_t ndacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2))
   4869 	    | (DOMAIN_CLIENT << (pmap_domain(npm) * 2));
   4870 
   4871 	/*
   4872 	 * If TTB and DACR are unchanged, short-circuit all the
   4873 	 * TLB/cache management stuff.
   4874 	 */
   4875 	pmap_t opm = ci->ci_lastlwp
   4876 	    ? ci->ci_lastlwp->l_proc->p_vmspace->vm_map.pmap
   4877 	    : NULL;
   4878 	if (opm != NULL) {
   4879 		uint32_t odacr = (DOMAIN_CLIENT << (PMAP_DOMAIN_KERNEL * 2))
   4880 		    | (DOMAIN_CLIENT << (pmap_domain(opm) * 2));
   4881 
   4882 		if (opm->pm_l1 == npm->pm_l1 && odacr == ndacr)
   4883 			goto all_done;
   4884 	}
   4885 #endif /* !ARM_MMU_EXTENDED */
   4886 
   4887 	PMAPCOUNT(activations);
   4888 	block_userspace_access = 1;
   4889 
   4890 #ifndef ARM_MMU_EXTENDED
   4891 	/*
   4892 	 * If switching to a user vmspace which is different to the
   4893 	 * most recent one, and the most recent one is potentially
   4894 	 * live in the cache, we must write-back and invalidate the
   4895 	 * entire cache.
   4896 	 */
   4897 	pmap_t rpm = ci->ci_pmap_lastuser;
   4898 
   4899 	/*
   4900 	 * XXXSCW: There's a corner case here which can leave turds in the
   4901 	 * cache as reported in kern/41058. They're probably left over during
   4902 	 * tear-down and switching away from an exiting process. Until the root
   4903 	 * cause is identified and fixed, zap the cache when switching pmaps.
   4904 	 * This will result in a few unnecessary cache flushes, but that's
   4905 	 * better than silently corrupting data.
   4906 	 */
   4907 #if 0
   4908 	if (npm != pmap_kernel() && rpm && npm != rpm &&
   4909 	    rpm->pm_cstate.cs_cache) {
   4910 		rpm->pm_cstate.cs_cache = 0;
   4911 #ifdef PMAP_CACHE_VIVT
   4912 		cpu_idcache_wbinv_all();
   4913 #endif
   4914 	}
   4915 #else
   4916 	if (rpm) {
   4917 		rpm->pm_cstate.cs_cache = 0;
   4918 		if (npm == pmap_kernel())
   4919 			ci->ci_pmap_lastuser = NULL;
   4920 #ifdef PMAP_CACHE_VIVT
   4921 		cpu_idcache_wbinv_all();
   4922 #endif
   4923 	}
   4924 #endif
   4925 
   4926 	/* No interrupts while we frob the TTB/DACR */
   4927 	uint32_t oldirqstate = disable_interrupts(IF32_bits);
   4928 #endif /* !ARM_MMU_EXTENDED */
   4929 
   4930 #ifndef ARM_HAS_VBAR
   4931 	/*
   4932 	 * For ARM_VECTORS_LOW, we MUST, I repeat, MUST fix up the L1
   4933 	 * entry corresponding to 'vector_page' in the incoming L1 table
   4934 	 * before switching to it otherwise subsequent interrupts/exceptions
   4935 	 * (including domain faults!) will jump into hyperspace.
   4936 	 */
   4937 	if (npm->pm_pl1vec != NULL) {
   4938 		cpu_tlb_flushID_SE((u_int)vector_page);
   4939 		cpu_cpwait();
   4940 		*npm->pm_pl1vec = npm->pm_l1vec;
   4941 		PTE_SYNC(npm->pm_pl1vec);
   4942 	}
   4943 #endif
   4944 
   4945 #ifdef ARM_MMU_EXTENDED
   4946 	pmap_md_pdetab_activate(npm, l);
   4947 #else
   4948 	cpu_domains(ndacr);
   4949 	if (npm == pmap_kernel() || npm == rpm) {
   4950 		/*
   4951 		 * Switching to a kernel thread, or back to the
   4952 		 * same user vmspace as before... Simply update
   4953 		 * the TTB (no TLB flush required)
   4954 		 */
   4955 		cpu_setttb(npm->pm_l1->l1_physaddr, false);
   4956 		cpu_cpwait();
   4957 	} else {
   4958 		/*
   4959 		 * Otherwise, update TTB and flush TLB
   4960 		 */
   4961 		cpu_context_switch(npm->pm_l1->l1_physaddr);
   4962 		if (rpm != NULL)
   4963 			rpm->pm_cstate.cs_tlb = 0;
   4964 	}
   4965 
   4966 	restore_interrupts(oldirqstate);
   4967 #endif /* ARM_MMU_EXTENDED */
   4968 
   4969 	block_userspace_access = 0;
   4970 
   4971 #ifndef ARM_MMU_EXTENDED
   4972  all_done:
   4973 	/*
   4974 	 * The new pmap is resident. Make sure it's marked
   4975 	 * as resident in the cache/TLB.
   4976 	 */
   4977 	npm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
   4978 	if (npm != pmap_kernel())
   4979 		ci->ci_pmap_lastuser = npm;
   4980 
   4981 	/* The old pmap is not longer active */
   4982 	if (opm != npm) {
   4983 		if (opm != NULL)
   4984 			opm->pm_activated = false;
   4985 
   4986 		/* But the new one is */
   4987 		npm->pm_activated = true;
   4988 	}
   4989 	ci->ci_pmap_cur = npm;
   4990 #endif
   4991 	UVMHIST_LOG(maphist, " <-- done", 0, 0, 0, 0);
   4992 }
   4993 
   4994 void
   4995 pmap_deactivate(struct lwp *l)
   4996 {
   4997 	pmap_t pm = l->l_proc->p_vmspace->vm_map.pmap;
   4998 
   4999 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   5000 
   5001 	UVMHIST_LOG(maphist, "(l=%#x) pm=%#x", l, pm, 0, 0);
   5002 
   5003 #ifdef ARM_MMU_EXTENDED
   5004 	pmap_md_pdetab_deactivate(pm);
   5005 #else
   5006 	/*
   5007 	 * If the process is exiting, make sure pmap_activate() does
   5008 	 * a full MMU context-switch and cache flush, which we might
   5009 	 * otherwise skip. See PR port-arm/38950.
   5010 	 */
   5011 	if (l->l_proc->p_sflag & PS_WEXIT)
   5012 		curcpu()->ci_lastlwp = NULL;
   5013 
   5014 	pm->pm_activated = false;
   5015 #endif
   5016 	UVMHIST_LOG(maphist, "  <-- done", 0, 0, 0, 0);
   5017 }
   5018 
   5019 void
   5020 pmap_update(pmap_t pm)
   5021 {
   5022 
   5023 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   5024 
   5025 	UVMHIST_LOG(maphist, "pm=%#x remove_all %d", pm, pm->pm_remove_all, 0,
   5026 	    0);
   5027 
   5028 #ifndef ARM_MMU_EXTENDED
   5029 	if (pm->pm_remove_all) {
   5030 		/*
   5031 		 * Finish up the pmap_remove_all() optimisation by flushing
   5032 		 * the TLB.
   5033 		 */
   5034 		pmap_tlb_flushID(pm);
   5035 		pm->pm_remove_all = false;
   5036 	}
   5037 
   5038 	if (pmap_is_current(pm)) {
   5039 		/*
   5040 		 * If we're dealing with a current userland pmap, move its L1
   5041 		 * to the end of the LRU.
   5042 		 */
   5043 		if (pm != pmap_kernel())
   5044 			pmap_use_l1(pm);
   5045 
   5046 		/*
   5047 		 * We can assume we're done with frobbing the cache/tlb for
   5048 		 * now. Make sure any future pmap ops don't skip cache/tlb
   5049 		 * flushes.
   5050 		 */
   5051 		pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
   5052 	}
   5053 #else
   5054 
   5055 	kpreempt_disable();
   5056 #if defined(MULTIPROCESSOR) && PMAP_TLB_MAX > 1
   5057 	u_int pending = atomic_swap_uint(&pmap->pm_shootdown_pending, 0);
   5058 	if (pending && pmap_tlb_shootdown_bystanders(pmap)) {
   5059 		PMAP_COUNT(shootdown_ipis);
   5060 	}
   5061 #endif
   5062 
   5063 	/*
   5064 	 * If pmap_remove_all was called, we deactivated ourselves and released
   5065 	 * our ASID.  Now we have to reactivate ourselves.
   5066 	 */
   5067 	if (__predict_false(pm->pm_remove_all)) {
   5068 		pm->pm_remove_all = false;
   5069 
   5070 		KASSERT(pm != pmap_kernel());
   5071 		pmap_md_pdetab_activate(pm, curlwp);
   5072 	}
   5073 
   5074 #if defined(MULTIPROCESSOR)
   5075 	armreg_bpiallis_write(0);
   5076 #else
   5077 	armreg_bpiall_write(0);
   5078 #endif
   5079 	kpreempt_enable();
   5080 
   5081 	KASSERTMSG(pm == pmap_kernel()
   5082 	    || curcpu()->ci_pmap_cur != pm
   5083 	    || pm->pm_pai[0].pai_asid == curcpu()->ci_pmap_asid_cur,
   5084 	    "pmap/asid %p/%#x != %s cur pmap/asid %p/%#x", pm,
   5085 	    pm->pm_pai[0].pai_asid, curcpu()->ci_data.cpu_name,
   5086 	    curcpu()->ci_pmap_cur, curcpu()->ci_pmap_asid_cur);
   5087 #endif
   5088 
   5089 	PMAPCOUNT(updates);
   5090 
   5091 	/*
   5092 	 * make sure TLB/cache operations have completed.
   5093 	 */
   5094 	cpu_cpwait();
   5095 	UVMHIST_LOG(maphist, "  <-- done", 0, 0, 0, 0);
   5096 }
   5097 
   5098 void
   5099 pmap_remove_all(pmap_t pm)
   5100 {
   5101 
   5102 	/*
   5103 	 * The vmspace described by this pmap is about to be torn down.
   5104 	 * Until pmap_update() is called, UVM will only make calls
   5105 	 * to pmap_remove(). We can make life much simpler by flushing
   5106 	 * the cache now, and deferring TLB invalidation to pmap_update().
   5107 	 */
   5108 #ifdef PMAP_CACHE_VIVT
   5109 	pmap_cache_wbinv_all(pm, PVF_EXEC);
   5110 #endif
   5111 #ifdef ARM_MMU_EXTENDED
   5112 #ifdef MULTIPROCESSOR
   5113 	struct cpu_info * const ci = curcpu();
   5114 	// This should be the last CPU with this pmap onproc
   5115 	KASSERT(!kcpuset_isotherset(pm->pm_onproc, cpu_index(ci)));
   5116 	if (kcpuset_isset(pm->pm_onproc, cpu_index(ci)))
   5117 #endif
   5118 		pmap_tlb_asid_deactivate(pm);
   5119 #ifdef MULTIPROCESSOR
   5120 	KASSERT(kcpuset_iszero(pm->pm_onproc));
   5121 #endif
   5122 
   5123 	pmap_tlb_asid_release_all(pm);
   5124 #endif
   5125 	pm->pm_remove_all = true;
   5126 }
   5127 
   5128 /*
   5129  * Retire the given physical map from service.
   5130  * Should only be called if the map contains no valid mappings.
   5131  */
   5132 void
   5133 pmap_destroy(pmap_t pm)
   5134 {
   5135 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(maphist);
   5136 
   5137 	u_int count;
   5138 
   5139 	if (pm == NULL)
   5140 		return;
   5141 
   5142 	UVMHIST_LOG(maphist, "pm=%#x remove_all %d", pm, pm->pm_remove_all, 0,
   5143 	    0);
   5144 
   5145 	if (pm->pm_remove_all) {
   5146 #ifdef ARM_MMU_EXTENDED
   5147  		pmap_tlb_asid_release_all(pm);
   5148 #else
   5149 		pmap_tlb_flushID(pm);
   5150 #endif
   5151 		pm->pm_remove_all = false;
   5152 	}
   5153 
   5154 	/*
   5155 	 * Drop reference count
   5156 	 */
   5157 	mutex_enter(pm->pm_lock);
   5158 	count = --pm->pm_obj.uo_refs;
   5159 	mutex_exit(pm->pm_lock);
   5160 	if (count > 0) {
   5161 #ifndef ARM_MMU_EXTENDED
   5162 		if (pmap_is_current(pm)) {
   5163 			if (pm != pmap_kernel())
   5164 				pmap_use_l1(pm);
   5165 			pm->pm_cstate.cs_all = PMAP_CACHE_STATE_ALL;
   5166 		}
   5167 #endif
   5168 		return;
   5169 	}
   5170 
   5171 	/*
   5172 	 * reference count is zero, free pmap resources and then free pmap.
   5173 	 */
   5174 
   5175 #ifndef ARM_HAS_VBAR
   5176 	if (vector_page < KERNEL_BASE) {
   5177 		KDASSERT(!pmap_is_current(pm));
   5178 
   5179 		/* Remove the vector page mapping */
   5180 		pmap_remove(pm, vector_page, vector_page + PAGE_SIZE);
   5181 		pmap_update(pm);
   5182 	}
   5183 #endif
   5184 
   5185 	pmap_free_l1(pm);
   5186 
   5187 #ifdef ARM_MMU_EXTENDED
   5188 #ifdef MULTIPROCESSOR
   5189 	kcpuset_destroy(pm->pm_active);
   5190 	kcpuset_destroy(pm->pm_onproc);
   5191 #endif
   5192 #else
   5193 	struct cpu_info * const ci = curcpu();
   5194 	if (ci->ci_pmap_lastuser == pm)
   5195 		ci->ci_pmap_lastuser = NULL;
   5196 #endif
   5197 
   5198 	uvm_obj_destroy(&pm->pm_obj, false);
   5199 	mutex_destroy(&pm->pm_obj_lock);
   5200 	pool_cache_put(&pmap_cache, pm);
   5201 	UVMHIST_LOG(maphist, "  <-- done", 0, 0, 0, 0);
   5202 }
   5203 
   5204 
   5205 /*
   5206  * void pmap_reference(pmap_t pm)
   5207  *
   5208  * Add a reference to the specified pmap.
   5209  */
   5210 void
   5211 pmap_reference(pmap_t pm)
   5212 {
   5213 
   5214 	if (pm == NULL)
   5215 		return;
   5216 
   5217 #ifndef ARM_MMU_EXTENDED
   5218 	pmap_use_l1(pm);
   5219 #endif
   5220 
   5221 	mutex_enter(pm->pm_lock);
   5222 	pm->pm_obj.uo_refs++;
   5223 	mutex_exit(pm->pm_lock);
   5224 }
   5225 
   5226 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
   5227 
   5228 static struct evcnt pmap_prefer_nochange_ev =
   5229     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap prefer", "nochange");
   5230 static struct evcnt pmap_prefer_change_ev =
   5231     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, NULL, "pmap prefer", "change");
   5232 
   5233 EVCNT_ATTACH_STATIC(pmap_prefer_change_ev);
   5234 EVCNT_ATTACH_STATIC(pmap_prefer_nochange_ev);
   5235 
   5236 void
   5237 pmap_prefer(vaddr_t hint, vaddr_t *vap, int td)
   5238 {
   5239 	vsize_t mask = arm_cache_prefer_mask | (PAGE_SIZE - 1);
   5240 	vaddr_t va = *vap;
   5241 	vaddr_t diff = (hint - va) & mask;
   5242 	if (diff == 0) {
   5243 		pmap_prefer_nochange_ev.ev_count++;
   5244 	} else {
   5245 		pmap_prefer_change_ev.ev_count++;
   5246 		if (__predict_false(td))
   5247 			va -= mask + 1;
   5248 		*vap = va + diff;
   5249 	}
   5250 }
   5251 #endif /* ARM_MMU_V6 | ARM_MMU_V7 */
   5252 
   5253 /*
   5254  * pmap_zero_page()
   5255  *
   5256  * Zero a given physical page by mapping it at a page hook point.
   5257  * In doing the zero page op, the page we zero is mapped cachable, as with
   5258  * StrongARM accesses to non-cached pages are non-burst making writing
   5259  * _any_ bulk data very slow.
   5260  */
   5261 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
   5262 void
   5263 pmap_zero_page_generic(paddr_t pa)
   5264 {
   5265 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
   5266 	struct vm_page *pg = PHYS_TO_VM_PAGE(pa);
   5267 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   5268 #endif
   5269 #if defined(PMAP_CACHE_VIPT)
   5270 	/* Choose the last page color it had, if any */
   5271 	const vsize_t va_offset = md->pvh_attrs & arm_cache_prefer_mask;
   5272 #else
   5273 	const vsize_t va_offset = 0;
   5274 #endif
   5275 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS)
   5276 	/*
   5277 	 * Is this page mapped at its natural color?
   5278 	 * If we have all of memory mapped, then just convert PA to VA.
   5279 	 */
   5280 	bool okcolor = arm_pcache.dcache_type == CACHE_TYPE_PIPT
   5281 	   || va_offset == (pa & arm_cache_prefer_mask);
   5282 	const vaddr_t vdstp = okcolor
   5283 	    ? pmap_direct_mapped_phys(pa, &okcolor, cpu_cdstp(va_offset))
   5284 	    : cpu_cdstp(va_offset);
   5285 #else
   5286 	const bool okcolor = false;
   5287 	const vaddr_t vdstp = cpu_cdstp(va_offset);
   5288 #endif
   5289 	pt_entry_t * const ptep = cpu_cdst_pte(va_offset);
   5290 
   5291 
   5292 #ifdef DEBUG
   5293 	if (!SLIST_EMPTY(&md->pvh_list))
   5294 		panic("pmap_zero_page: page has mappings");
   5295 #endif
   5296 
   5297 	KDASSERT((pa & PGOFSET) == 0);
   5298 
   5299 	if (!okcolor) {
   5300 		/*
   5301 		 * Hook in the page, zero it, and purge the cache for that
   5302 		 * zeroed page. Invalidate the TLB as needed.
   5303 		 */
   5304 		const pt_entry_t npte = L2_S_PROTO | pa | pte_l2_s_cache_mode
   5305 		    | L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE);
   5306 		l2pte_set(ptep, npte, 0);
   5307 		PTE_SYNC(ptep);
   5308 		cpu_tlb_flushD_SE(vdstp);
   5309 		cpu_cpwait();
   5310 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS) && defined(PMAP_CACHE_VIPT) \
   5311     && !defined(ARM_MMU_EXTENDED)
   5312 		/*
   5313 		 * If we are direct-mapped and our color isn't ok, then before
   5314 		 * we bzero the page invalidate its contents from the cache and
   5315 		 * reset the color to its natural color.
   5316 		 */
   5317 		cpu_dcache_inv_range(vdstp, PAGE_SIZE);
   5318 		md->pvh_attrs &= ~arm_cache_prefer_mask;
   5319 		md->pvh_attrs |= (pa & arm_cache_prefer_mask);
   5320 #endif
   5321 	}
   5322 	bzero_page(vdstp);
   5323 	if (!okcolor) {
   5324 		/*
   5325 		 * Unmap the page.
   5326 		 */
   5327 		l2pte_reset(ptep);
   5328 		PTE_SYNC(ptep);
   5329 		cpu_tlb_flushD_SE(vdstp);
   5330 #ifdef PMAP_CACHE_VIVT
   5331 		cpu_dcache_wbinv_range(vdstp, PAGE_SIZE);
   5332 #endif
   5333 	}
   5334 #ifdef PMAP_CACHE_VIPT
   5335 	/*
   5336 	 * This page is now cache resident so it now has a page color.
   5337 	 * Any contents have been obliterated so clear the EXEC flag.
   5338 	 */
   5339 #ifndef ARM_MMU_EXTENDED
   5340 	if (!pmap_is_page_colored_p(md)) {
   5341 		PMAPCOUNT(vac_color_new);
   5342 		md->pvh_attrs |= PVF_COLORED;
   5343 	}
   5344 	md->pvh_attrs |= PVF_DIRTY;
   5345 #endif
   5346 	if (PV_IS_EXEC_P(md->pvh_attrs)) {
   5347 		md->pvh_attrs &= ~PVF_EXEC;
   5348 		PMAPCOUNT(exec_discarded_zero);
   5349 	}
   5350 #endif
   5351 }
   5352 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
   5353 
   5354 #if ARM_MMU_XSCALE == 1
   5355 void
   5356 pmap_zero_page_xscale(paddr_t pa)
   5357 {
   5358 #ifdef DEBUG
   5359 	struct vm_page *pg = PHYS_TO_VM_PAGE(pa);
   5360 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   5361 
   5362 	if (!SLIST_EMPTY(&md->pvh_list))
   5363 		panic("pmap_zero_page: page has mappings");
   5364 #endif
   5365 
   5366 	KDASSERT((pa & PGOFSET) == 0);
   5367 
   5368 	/*
   5369 	 * Hook in the page, zero it, and purge the cache for that
   5370 	 * zeroed page. Invalidate the TLB as needed.
   5371 	 */
   5372 
   5373 	pt_entry_t npte = L2_S_PROTO | pa |
   5374 	    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) |
   5375 	    L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
   5376 	l2pte_set(cdst_pte, npte, 0);
   5377 	PTE_SYNC(cdst_pte);
   5378 	cpu_tlb_flushD_SE(cdstp);
   5379 	cpu_cpwait();
   5380 	bzero_page(cdstp);
   5381 	xscale_cache_clean_minidata();
   5382 	l2pte_reset(cdst_pte);
   5383 	PTE_SYNC(cdst_pte);
   5384 }
   5385 #endif /* ARM_MMU_XSCALE == 1 */
   5386 
   5387 /* pmap_pageidlezero()
   5388  *
   5389  * The same as above, except that we assume that the page is not
   5390  * mapped.  This means we never have to flush the cache first.  Called
   5391  * from the idle loop.
   5392  */
   5393 bool
   5394 pmap_pageidlezero(paddr_t pa)
   5395 {
   5396 	bool rv = true;
   5397 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
   5398 	struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   5399 	struct vm_page_md *md = VM_PAGE_TO_MD(pg);
   5400 #endif
   5401 #ifdef PMAP_CACHE_VIPT
   5402 	/* Choose the last page color it had, if any */
   5403 	const vsize_t va_offset = md->pvh_attrs & arm_cache_prefer_mask;
   5404 #else
   5405 	const vsize_t va_offset = 0;
   5406 #endif
   5407 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   5408 	bool okcolor = arm_pcache.dcache_type == CACHE_TYPE_PIPT
   5409 	   || va_offset == (pa & arm_cache_prefer_mask);
   5410 	const vaddr_t vdstp = okcolor
   5411 	    ? pmap_direct_mapped_phys(pa, &okcolor, cpu_cdstp(va_offset))
   5412 	    : cpu_cdstp(va_offset);
   5413 #else
   5414 	const bool okcolor = false;
   5415 	const vaddr_t vdstp = cpu_cdstp(va_offset);
   5416 #endif
   5417 	pt_entry_t * const ptep = cpu_cdst_pte(va_offset);
   5418 
   5419 
   5420 #ifdef DEBUG
   5421 	if (!SLIST_EMPTY(&md->pvh_list))
   5422 		panic("pmap_pageidlezero: page has mappings");
   5423 #endif
   5424 
   5425 	KDASSERT((pa & PGOFSET) == 0);
   5426 
   5427 	if (!okcolor) {
   5428 		/*
   5429 		 * Hook in the page, zero it, and purge the cache for that
   5430 		 * zeroed page. Invalidate the TLB as needed.
   5431 		 */
   5432 		const pt_entry_t npte = L2_S_PROTO | pa |
   5433 		    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
   5434 		l2pte_set(ptep, npte, 0);
   5435 		PTE_SYNC(ptep);
   5436 		cpu_tlb_flushD_SE(vdstp);
   5437 		cpu_cpwait();
   5438 	}
   5439 
   5440 	uint64_t *ptr = (uint64_t *)vdstp;
   5441 	for (size_t i = 0; i < PAGE_SIZE / sizeof(*ptr); i++) {
   5442 		if (sched_curcpu_runnable_p() != 0) {
   5443 			/*
   5444 			 * A process has become ready.  Abort now,
   5445 			 * so we don't keep it waiting while we
   5446 			 * do slow memory access to finish this
   5447 			 * page.
   5448 			 */
   5449 			rv = false;
   5450 			break;
   5451 		}
   5452 		*ptr++ = 0;
   5453 	}
   5454 
   5455 #ifdef PMAP_CACHE_VIVT
   5456 	if (rv)
   5457 		/*
   5458 		 * if we aborted we'll rezero this page again later so don't
   5459 		 * purge it unless we finished it
   5460 		 */
   5461 		cpu_dcache_wbinv_range(vdstp, PAGE_SIZE);
   5462 #elif defined(PMAP_CACHE_VIPT)
   5463 	/*
   5464 	 * This page is now cache resident so it now has a page color.
   5465 	 * Any contents have been obliterated so clear the EXEC flag.
   5466 	 */
   5467 #ifndef ARM_MMU_EXTENDED
   5468 	if (!pmap_is_page_colored_p(md)) {
   5469 		PMAPCOUNT(vac_color_new);
   5470 		md->pvh_attrs |= PVF_COLORED;
   5471 	}
   5472 #endif
   5473 	if (PV_IS_EXEC_P(md->pvh_attrs)) {
   5474 		md->pvh_attrs &= ~PVF_EXEC;
   5475 		PMAPCOUNT(exec_discarded_zero);
   5476 	}
   5477 #endif
   5478 	/*
   5479 	 * Unmap the page.
   5480 	 */
   5481 	if (!okcolor) {
   5482 		l2pte_reset(ptep);
   5483 		PTE_SYNC(ptep);
   5484 		cpu_tlb_flushD_SE(vdstp);
   5485 	}
   5486 
   5487 	return rv;
   5488 }
   5489 
   5490 /*
   5491  * pmap_copy_page()
   5492  *
   5493  * Copy one physical page into another, by mapping the pages into
   5494  * hook points. The same comment regarding cachability as in
   5495  * pmap_zero_page also applies here.
   5496  */
   5497 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
   5498 void
   5499 pmap_copy_page_generic(paddr_t src, paddr_t dst)
   5500 {
   5501 	struct vm_page * const src_pg = PHYS_TO_VM_PAGE(src);
   5502 	struct vm_page_md *src_md = VM_PAGE_TO_MD(src_pg);
   5503 #if defined(PMAP_CACHE_VIPT) || defined(DEBUG)
   5504 	struct vm_page * const dst_pg = PHYS_TO_VM_PAGE(dst);
   5505 	struct vm_page_md *dst_md = VM_PAGE_TO_MD(dst_pg);
   5506 #endif
   5507 #ifdef PMAP_CACHE_VIPT
   5508 	const vsize_t src_va_offset = src_md->pvh_attrs & arm_cache_prefer_mask;
   5509 	const vsize_t dst_va_offset = dst_md->pvh_attrs & arm_cache_prefer_mask;
   5510 #else
   5511 	const vsize_t src_va_offset = 0;
   5512 	const vsize_t dst_va_offset = 0;
   5513 #endif
   5514 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS)
   5515 	/*
   5516 	 * Is this page mapped at its natural color?
   5517 	 * If we have all of memory mapped, then just convert PA to VA.
   5518 	 */
   5519 	bool src_okcolor = arm_pcache.dcache_type == CACHE_TYPE_PIPT
   5520 	    || src_va_offset == (src & arm_cache_prefer_mask);
   5521 	bool dst_okcolor = arm_pcache.dcache_type == CACHE_TYPE_PIPT
   5522 	    || dst_va_offset == (dst & arm_cache_prefer_mask);
   5523 	const vaddr_t vsrcp = src_okcolor
   5524 	    ? pmap_direct_mapped_phys(src, &src_okcolor,
   5525 		cpu_csrcp(src_va_offset))
   5526 	    : cpu_csrcp(src_va_offset);
   5527 	const vaddr_t vdstp = pmap_direct_mapped_phys(dst, &dst_okcolor,
   5528 	    cpu_cdstp(dst_va_offset));
   5529 #else
   5530 	const bool src_okcolor = false;
   5531 	const bool dst_okcolor = false;
   5532 	const vaddr_t vsrcp = cpu_csrcp(src_va_offset);
   5533 	const vaddr_t vdstp = cpu_cdstp(dst_va_offset);
   5534 #endif
   5535 	pt_entry_t * const src_ptep = cpu_csrc_pte(src_va_offset);
   5536 	pt_entry_t * const dst_ptep = cpu_cdst_pte(dst_va_offset);
   5537 
   5538 #ifdef DEBUG
   5539 	if (!SLIST_EMPTY(&dst_md->pvh_list))
   5540 		panic("pmap_copy_page: dst page has mappings");
   5541 #endif
   5542 
   5543 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   5544 	KASSERT(arm_cache_prefer_mask == 0 || src_md->pvh_attrs & (PVF_COLORED|PVF_NC));
   5545 #endif
   5546 	KDASSERT((src & PGOFSET) == 0);
   5547 	KDASSERT((dst & PGOFSET) == 0);
   5548 
   5549 	/*
   5550 	 * Clean the source page.  Hold the source page's lock for
   5551 	 * the duration of the copy so that no other mappings can
   5552 	 * be created while we have a potentially aliased mapping.
   5553 	 */
   5554 #ifdef PMAP_CACHE_VIVT
   5555 	pmap_acquire_page_lock(src_md);
   5556 	(void) pmap_clean_page(src_md, true);
   5557 	pmap_release_page_lock(src_md);
   5558 #endif
   5559 
   5560 	/*
   5561 	 * Map the pages into the page hook points, copy them, and purge
   5562 	 * the cache for the appropriate page. Invalidate the TLB
   5563 	 * as required.
   5564 	 */
   5565 	if (!src_okcolor) {
   5566 		const pt_entry_t nsrc_pte = L2_S_PROTO
   5567 		    | src
   5568 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   5569 		    | ((src_md->pvh_attrs & PVF_NC) ? 0 : pte_l2_s_cache_mode)
   5570 #else // defined(PMAP_CACHE_VIVT) || defined(ARM_MMU_EXTENDED)
   5571 		    | pte_l2_s_cache_mode
   5572 #endif
   5573 		    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ);
   5574 		l2pte_set(src_ptep, nsrc_pte, 0);
   5575 		PTE_SYNC(src_ptep);
   5576 		cpu_tlb_flushD_SE(vsrcp);
   5577 		cpu_cpwait();
   5578 	}
   5579 	if (!dst_okcolor) {
   5580 		const pt_entry_t ndst_pte = L2_S_PROTO | dst |
   5581 		    L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE) | pte_l2_s_cache_mode;
   5582 		l2pte_set(dst_ptep, ndst_pte, 0);
   5583 		PTE_SYNC(dst_ptep);
   5584 		cpu_tlb_flushD_SE(vdstp);
   5585 		cpu_cpwait();
   5586 #if defined(__HAVE_MM_MD_DIRECT_MAPPED_PHYS) && defined(PMAP_CACHE_VIPT)
   5587 		/*
   5588 		 * If we are direct-mapped and our color isn't ok, then before
   5589 		 * we bcopy to the new page invalidate its contents from the
   5590 		 * cache and reset its color to its natural color.
   5591 		 */
   5592 		cpu_dcache_inv_range(vdstp, PAGE_SIZE);
   5593 		dst_md->pvh_attrs &= ~arm_cache_prefer_mask;
   5594 		dst_md->pvh_attrs |= (dst & arm_cache_prefer_mask);
   5595 #endif
   5596 	}
   5597 	bcopy_page(vsrcp, vdstp);
   5598 #ifdef PMAP_CACHE_VIVT
   5599 	cpu_dcache_inv_range(vsrcp, PAGE_SIZE);
   5600 	cpu_dcache_wbinv_range(vdstp, PAGE_SIZE);
   5601 #endif
   5602 	/*
   5603 	 * Unmap the pages.
   5604 	 */
   5605 	if (!src_okcolor) {
   5606 		l2pte_reset(src_ptep);
   5607 		PTE_SYNC(src_ptep);
   5608 		cpu_tlb_flushD_SE(vsrcp);
   5609 		cpu_cpwait();
   5610 	}
   5611 	if (!dst_okcolor) {
   5612 		l2pte_reset(dst_ptep);
   5613 		PTE_SYNC(dst_ptep);
   5614 		cpu_tlb_flushD_SE(vdstp);
   5615 		cpu_cpwait();
   5616 	}
   5617 #ifdef PMAP_CACHE_VIPT
   5618 	/*
   5619 	 * Now that the destination page is in the cache, mark it as colored.
   5620 	 * If this was an exec page, discard it.
   5621 	 */
   5622 	pmap_acquire_page_lock(dst_md);
   5623 #ifndef ARM_MMU_EXTENDED
   5624 	if (arm_pcache.cache_type == CACHE_TYPE_PIPT) {
   5625 		dst_md->pvh_attrs &= ~arm_cache_prefer_mask;
   5626 		dst_md->pvh_attrs |= (dst & arm_cache_prefer_mask);
   5627 	}
   5628 	if (!pmap_is_page_colored_p(dst_md)) {
   5629 		PMAPCOUNT(vac_color_new);
   5630 		dst_md->pvh_attrs |= PVF_COLORED;
   5631 	}
   5632 	dst_md->pvh_attrs |= PVF_DIRTY;
   5633 #endif
   5634 	if (PV_IS_EXEC_P(dst_md->pvh_attrs)) {
   5635 		dst_md->pvh_attrs &= ~PVF_EXEC;
   5636 		PMAPCOUNT(exec_discarded_copy);
   5637 	}
   5638 	pmap_release_page_lock(dst_md);
   5639 #endif
   5640 }
   5641 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
   5642 
   5643 #if ARM_MMU_XSCALE == 1
   5644 void
   5645 pmap_copy_page_xscale(paddr_t src, paddr_t dst)
   5646 {
   5647 	struct vm_page *src_pg = PHYS_TO_VM_PAGE(src);
   5648 	struct vm_page_md *src_md = VM_PAGE_TO_MD(src_pg);
   5649 #ifdef DEBUG
   5650 	struct vm_page_md *dst_md = VM_PAGE_TO_MD(PHYS_TO_VM_PAGE(dst));
   5651 
   5652 	if (!SLIST_EMPTY(&dst_md->pvh_list))
   5653 		panic("pmap_copy_page: dst page has mappings");
   5654 #endif
   5655 
   5656 	KDASSERT((src & PGOFSET) == 0);
   5657 	KDASSERT((dst & PGOFSET) == 0);
   5658 
   5659 	/*
   5660 	 * Clean the source page.  Hold the source page's lock for
   5661 	 * the duration of the copy so that no other mappings can
   5662 	 * be created while we have a potentially aliased mapping.
   5663 	 */
   5664 #ifdef PMAP_CACHE_VIVT
   5665 	pmap_acquire_page_lock(src_md);
   5666 	(void) pmap_clean_page(src_md, true);
   5667 	pmap_release_page_lock(src_md);
   5668 #endif
   5669 
   5670 	/*
   5671 	 * Map the pages into the page hook points, copy them, and purge
   5672 	 * the cache for the appropriate page. Invalidate the TLB
   5673 	 * as required.
   5674 	 */
   5675 	const pt_entry_t nsrc_pte = L2_S_PROTO | src
   5676 	    | L2_S_PROT(PTE_KERNEL, VM_PROT_READ)
   5677 	    | L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
   5678 	l2pte_set(csrc_pte, nsrc_pte, 0);
   5679 	PTE_SYNC(csrc_pte);
   5680 
   5681 	const pt_entry_t ndst_pte = L2_S_PROTO | dst
   5682 	    | L2_S_PROT(PTE_KERNEL, VM_PROT_WRITE)
   5683 	    | L2_C | L2_XS_T_TEX(TEX_XSCALE_X);	/* mini-data */
   5684 	l2pte_set(cdst_pte, ndst_pte, 0);
   5685 	PTE_SYNC(cdst_pte);
   5686 
   5687 	cpu_tlb_flushD_SE(csrcp);
   5688 	cpu_tlb_flushD_SE(cdstp);
   5689 	cpu_cpwait();
   5690 	bcopy_page(csrcp, cdstp);
   5691 	xscale_cache_clean_minidata();
   5692 	l2pte_reset(csrc_pte);
   5693 	l2pte_reset(cdst_pte);
   5694 	PTE_SYNC(csrc_pte);
   5695 	PTE_SYNC(cdst_pte);
   5696 }
   5697 #endif /* ARM_MMU_XSCALE == 1 */
   5698 
   5699 /*
   5700  * void pmap_virtual_space(vaddr_t *start, vaddr_t *end)
   5701  *
   5702  * Return the start and end addresses of the kernel's virtual space.
   5703  * These values are setup in pmap_bootstrap and are updated as pages
   5704  * are allocated.
   5705  */
   5706 void
   5707 pmap_virtual_space(vaddr_t *start, vaddr_t *end)
   5708 {
   5709 	*start = virtual_avail;
   5710 	*end = virtual_end;
   5711 }
   5712 
   5713 /*
   5714  * Helper function for pmap_grow_l2_bucket()
   5715  */
   5716 static inline int
   5717 pmap_grow_map(vaddr_t va, paddr_t *pap)
   5718 {
   5719 	paddr_t pa;
   5720 
   5721 	if (uvm.page_init_done == false) {
   5722 #ifdef PMAP_STEAL_MEMORY
   5723 		pv_addr_t pv;
   5724 		pmap_boot_pagealloc(PAGE_SIZE,
   5725 #ifdef PMAP_CACHE_VIPT
   5726 		    arm_cache_prefer_mask,
   5727 		    va & arm_cache_prefer_mask,
   5728 #else
   5729 		    0, 0,
   5730 #endif
   5731 		    &pv);
   5732 		pa = pv.pv_pa;
   5733 #else
   5734 		if (uvm_page_physget(&pa) == false)
   5735 			return (1);
   5736 #endif	/* PMAP_STEAL_MEMORY */
   5737 	} else {
   5738 		struct vm_page *pg;
   5739 		pg = uvm_pagealloc(NULL, 0, NULL, UVM_PGA_USERESERVE);
   5740 		if (pg == NULL)
   5741 			return (1);
   5742 		pa = VM_PAGE_TO_PHYS(pg);
   5743 		/*
   5744 		 * This new page must not have any mappings.  Enter it via
   5745 		 * pmap_kenter_pa and let that routine do the hard work.
   5746 		 */
   5747 		struct vm_page_md *md __diagused = VM_PAGE_TO_MD(pg);
   5748 		KASSERT(SLIST_EMPTY(&md->pvh_list));
   5749 		pmap_kenter_pa(va, pa,
   5750 		    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE|PMAP_PTE);
   5751 	}
   5752 
   5753 	if (pap)
   5754 		*pap = pa;
   5755 
   5756 	PMAPCOUNT(pt_mappings);
   5757 #ifdef DEBUG
   5758 	struct l2_bucket * const l2b = pmap_get_l2_bucket(pmap_kernel(), va);
   5759 	KDASSERT(l2b != NULL);
   5760 
   5761 	pt_entry_t * const ptep = &l2b->l2b_kva[l2pte_index(va)];
   5762 	const pt_entry_t opte = *ptep;
   5763 	KDASSERT((opte & L2_S_CACHE_MASK) == pte_l2_s_cache_mode_pt);
   5764 #endif
   5765 	memset((void *)va, 0, PAGE_SIZE);
   5766 	return (0);
   5767 }
   5768 
   5769 /*
   5770  * This is the same as pmap_alloc_l2_bucket(), except that it is only
   5771  * used by pmap_growkernel().
   5772  */
   5773 static inline struct l2_bucket *
   5774 pmap_grow_l2_bucket(pmap_t pm, vaddr_t va)
   5775 {
   5776 	struct l2_dtable *l2;
   5777 	struct l2_bucket *l2b;
   5778 	u_short l1slot;
   5779 	vaddr_t nva;
   5780 
   5781 	l1slot = l1pte_index(va);
   5782 
   5783 	if ((l2 = pm->pm_l2[L2_IDX(l1slot)]) == NULL) {
   5784 		/*
   5785 		 * No mapping at this address, as there is
   5786 		 * no entry in the L1 table.
   5787 		 * Need to allocate a new l2_dtable.
   5788 		 */
   5789 		nva = pmap_kernel_l2dtable_kva;
   5790 		if ((nva & PGOFSET) == 0) {
   5791 			/*
   5792 			 * Need to allocate a backing page
   5793 			 */
   5794 			if (pmap_grow_map(nva, NULL))
   5795 				return (NULL);
   5796 		}
   5797 
   5798 		l2 = (struct l2_dtable *)nva;
   5799 		nva += sizeof(struct l2_dtable);
   5800 
   5801 		if ((nva & PGOFSET) < (pmap_kernel_l2dtable_kva & PGOFSET)) {
   5802 			/*
   5803 			 * The new l2_dtable straddles a page boundary.
   5804 			 * Map in another page to cover it.
   5805 			 */
   5806 			if (pmap_grow_map(nva, NULL))
   5807 				return (NULL);
   5808 		}
   5809 
   5810 		pmap_kernel_l2dtable_kva = nva;
   5811 
   5812 		/*
   5813 		 * Link it into the parent pmap
   5814 		 */
   5815 		pm->pm_l2[L2_IDX(l1slot)] = l2;
   5816 	}
   5817 
   5818 	l2b = &l2->l2_bucket[L2_BUCKET(l1slot)];
   5819 
   5820 	/*
   5821 	 * Fetch pointer to the L2 page table associated with the address.
   5822 	 */
   5823 	if (l2b->l2b_kva == NULL) {
   5824 		pt_entry_t *ptep;
   5825 
   5826 		/*
   5827 		 * No L2 page table has been allocated. Chances are, this
   5828 		 * is because we just allocated the l2_dtable, above.
   5829 		 */
   5830 		nva = pmap_kernel_l2ptp_kva;
   5831 		ptep = (pt_entry_t *)nva;
   5832 		if ((nva & PGOFSET) == 0) {
   5833 			/*
   5834 			 * Need to allocate a backing page
   5835 			 */
   5836 			if (pmap_grow_map(nva, &pmap_kernel_l2ptp_phys))
   5837 				return (NULL);
   5838 			PTE_SYNC_RANGE(ptep, PAGE_SIZE / sizeof(pt_entry_t));
   5839 		}
   5840 
   5841 		l2->l2_occupancy++;
   5842 		l2b->l2b_kva = ptep;
   5843 		l2b->l2b_l1slot = l1slot;
   5844 		l2b->l2b_pa = pmap_kernel_l2ptp_phys;
   5845 
   5846 		pmap_kernel_l2ptp_kva += L2_TABLE_SIZE_REAL;
   5847 		pmap_kernel_l2ptp_phys += L2_TABLE_SIZE_REAL;
   5848 	}
   5849 
   5850 	return (l2b);
   5851 }
   5852 
   5853 vaddr_t
   5854 pmap_growkernel(vaddr_t maxkvaddr)
   5855 {
   5856 	pmap_t kpm = pmap_kernel();
   5857 #ifndef ARM_MMU_EXTENDED
   5858 	struct l1_ttable *l1;
   5859 #endif
   5860 	int s;
   5861 
   5862 	if (maxkvaddr <= pmap_curmaxkvaddr)
   5863 		goto out;		/* we are OK */
   5864 
   5865 	NPDEBUG(PDB_GROWKERN,
   5866 	    printf("pmap_growkernel: growing kernel from 0x%lx to 0x%lx\n",
   5867 	    pmap_curmaxkvaddr, maxkvaddr));
   5868 
   5869 	KDASSERT(maxkvaddr <= virtual_end);
   5870 
   5871 	/*
   5872 	 * whoops!   we need to add kernel PTPs
   5873 	 */
   5874 
   5875 	s = splhigh();	/* to be safe */
   5876 	mutex_enter(kpm->pm_lock);
   5877 
   5878 	/* Map 1MB at a time */
   5879 	size_t l1slot = l1pte_index(pmap_curmaxkvaddr);
   5880 #ifdef ARM_MMU_EXTENDED
   5881 	pd_entry_t * const spdep = &kpm->pm_l1[l1slot];
   5882 	pd_entry_t *pdep = spdep;
   5883 #endif
   5884 	for (;pmap_curmaxkvaddr < maxkvaddr; pmap_curmaxkvaddr += L1_S_SIZE,
   5885 #ifdef ARM_MMU_EXTENDED
   5886 	     pdep++,
   5887 #endif
   5888 	     l1slot++) {
   5889 		struct l2_bucket *l2b =
   5890 		    pmap_grow_l2_bucket(kpm, pmap_curmaxkvaddr);
   5891 		KASSERT(l2b != NULL);
   5892 
   5893 		const pd_entry_t npde = L1_C_PROTO | l2b->l2b_pa
   5894 		    | L1_C_DOM(PMAP_DOMAIN_KERNEL);
   5895 #ifdef ARM_MMU_EXTENDED
   5896 		l1pte_setone(pdep, npde);
   5897 #else
   5898 		/* Distribute new L1 entry to all other L1s */
   5899 		SLIST_FOREACH(l1, &l1_list, l1_link) {
   5900 			pd_entry_t * const pdep = &l1->l1_kva[l1slot];
   5901 			l1pte_setone(pdep, npde);
   5902 			PDE_SYNC(pdep);
   5903 		}
   5904 #endif
   5905 	}
   5906 #ifdef ARM_MMU_EXTENDED
   5907 	PDE_SYNC_RANGE(spdep, pdep - spdep);
   5908 #endif
   5909 
   5910 #ifdef PMAP_CACHE_VIVT
   5911 	/*
   5912 	 * flush out the cache, expensive but growkernel will happen so
   5913 	 * rarely
   5914 	 */
   5915 	cpu_dcache_wbinv_all();
   5916 	cpu_tlb_flushD();
   5917 	cpu_cpwait();
   5918 #endif
   5919 
   5920 	mutex_exit(kpm->pm_lock);
   5921 	splx(s);
   5922 
   5923 out:
   5924 	return (pmap_curmaxkvaddr);
   5925 }
   5926 
   5927 /************************ Utility routines ****************************/
   5928 
   5929 #ifndef ARM_HAS_VBAR
   5930 /*
   5931  * vector_page_setprot:
   5932  *
   5933  *	Manipulate the protection of the vector page.
   5934  */
   5935 void
   5936 vector_page_setprot(int prot)
   5937 {
   5938 	struct l2_bucket *l2b;
   5939 	pt_entry_t *ptep;
   5940 
   5941 #if defined(CPU_ARMV7) || defined(CPU_ARM11)
   5942 	/*
   5943 	 * If we are using VBAR to use the vectors in the kernel, then it's
   5944 	 * already mapped in the kernel text so no need to anything here.
   5945 	 */
   5946 	if (vector_page != ARM_VECTORS_LOW && vector_page != ARM_VECTORS_HIGH) {
   5947 		KASSERT((armreg_pfr1_read() & ARM_PFR1_SEC_MASK) != 0);
   5948 		return;
   5949 	}
   5950 #endif
   5951 
   5952 	l2b = pmap_get_l2_bucket(pmap_kernel(), vector_page);
   5953 	KASSERT(l2b != NULL);
   5954 
   5955 	ptep = &l2b->l2b_kva[l2pte_index(vector_page)];
   5956 
   5957 	const pt_entry_t opte = *ptep;
   5958 #ifdef ARM_MMU_EXTENDED
   5959 	const pt_entry_t npte = (opte & ~(L2_S_PROT_MASK|L2_XS_XN))
   5960 	    | L2_S_PROT(PTE_KERNEL, prot);
   5961 #else
   5962 	const pt_entry_t npte = (opte & ~L2_S_PROT_MASK)
   5963 	    | L2_S_PROT(PTE_KERNEL, prot);
   5964 #endif
   5965 	l2pte_set(ptep, npte, opte);
   5966 	PTE_SYNC(ptep);
   5967 	cpu_tlb_flushD_SE(vector_page);
   5968 	cpu_cpwait();
   5969 }
   5970 #endif
   5971 
   5972 /*
   5973  * Fetch pointers to the PDE/PTE for the given pmap/VA pair.
   5974  * Returns true if the mapping exists, else false.
   5975  *
   5976  * NOTE: This function is only used by a couple of arm-specific modules.
   5977  * It is not safe to take any pmap locks here, since we could be right
   5978  * in the middle of debugging the pmap anyway...
   5979  *
   5980  * It is possible for this routine to return false even though a valid
   5981  * mapping does exist. This is because we don't lock, so the metadata
   5982  * state may be inconsistent.
   5983  *
   5984  * NOTE: We can return a NULL *ptp in the case where the L1 pde is
   5985  * a "section" mapping.
   5986  */
   5987 bool
   5988 pmap_get_pde_pte(pmap_t pm, vaddr_t va, pd_entry_t **pdp, pt_entry_t **ptp)
   5989 {
   5990 	struct l2_dtable *l2;
   5991 	pd_entry_t *pdep, pde;
   5992 	pt_entry_t *ptep;
   5993 	u_short l1slot;
   5994 
   5995 	if (pm->pm_l1 == NULL)
   5996 		return false;
   5997 
   5998 	l1slot = l1pte_index(va);
   5999 	*pdp = pdep = pmap_l1_kva(pm) + l1slot;
   6000 	pde = *pdep;
   6001 
   6002 	if (l1pte_section_p(pde)) {
   6003 		*ptp = NULL;
   6004 		return true;
   6005 	}
   6006 
   6007 	l2 = pm->pm_l2[L2_IDX(l1slot)];
   6008 	if (l2 == NULL ||
   6009 	    (ptep = l2->l2_bucket[L2_BUCKET(l1slot)].l2b_kva) == NULL) {
   6010 		return false;
   6011 	}
   6012 
   6013 	*ptp = &ptep[l2pte_index(va)];
   6014 	return true;
   6015 }
   6016 
   6017 bool
   6018 pmap_get_pde(pmap_t pm, vaddr_t va, pd_entry_t **pdp)
   6019 {
   6020 
   6021 	if (pm->pm_l1 == NULL)
   6022 		return false;
   6023 
   6024 	*pdp = pmap_l1_kva(pm) + l1pte_index(va);
   6025 
   6026 	return true;
   6027 }
   6028 
   6029 /************************ Bootstrapping routines ****************************/
   6030 
   6031 #ifndef ARM_MMU_EXTENDED
   6032 static void
   6033 pmap_init_l1(struct l1_ttable *l1, pd_entry_t *l1pt)
   6034 {
   6035 	int i;
   6036 
   6037 	l1->l1_kva = l1pt;
   6038 	l1->l1_domain_use_count = 0;
   6039 	l1->l1_domain_first = 0;
   6040 
   6041 	for (i = 0; i < PMAP_DOMAINS; i++)
   6042 		l1->l1_domain_free[i] = i + 1;
   6043 
   6044 	/*
   6045 	 * Copy the kernel's L1 entries to each new L1.
   6046 	 */
   6047 	if (pmap_initialized)
   6048 		memcpy(l1pt, pmap_l1_kva(pmap_kernel()), L1_TABLE_SIZE);
   6049 
   6050 	if (pmap_extract(pmap_kernel(), (vaddr_t)l1pt,
   6051 	    &l1->l1_physaddr) == false)
   6052 		panic("pmap_init_l1: can't get PA of L1 at %p", l1pt);
   6053 
   6054 	SLIST_INSERT_HEAD(&l1_list, l1, l1_link);
   6055 	TAILQ_INSERT_TAIL(&l1_lru_list, l1, l1_lru);
   6056 }
   6057 #endif /* !ARM_MMU_EXTENDED */
   6058 
   6059 /*
   6060  * pmap_bootstrap() is called from the board-specific initarm() routine
   6061  * once the kernel L1/L2 descriptors tables have been set up.
   6062  *
   6063  * This is a somewhat convoluted process since pmap bootstrap is, effectively,
   6064  * spread over a number of disparate files/functions.
   6065  *
   6066  * We are passed the following parameters
   6067  *  - kernel_l1pt
   6068  *    This is a pointer to the base of the kernel's L1 translation table.
   6069  *  - vstart
   6070  *    1MB-aligned start of managed kernel virtual memory.
   6071  *  - vend
   6072  *    1MB-aligned end of managed kernel virtual memory.
   6073  *
   6074  * We use the first parameter to build the metadata (struct l1_ttable and
   6075  * struct l2_dtable) necessary to track kernel mappings.
   6076  */
   6077 #define	PMAP_STATIC_L2_SIZE 16
   6078 void
   6079 pmap_bootstrap(vaddr_t vstart, vaddr_t vend)
   6080 {
   6081 	static struct l2_dtable static_l2[PMAP_STATIC_L2_SIZE];
   6082 #ifndef ARM_MMU_EXTENDED
   6083 	static struct l1_ttable static_l1;
   6084 	struct l1_ttable *l1 = &static_l1;
   6085 #endif
   6086 	struct l2_dtable *l2;
   6087 	struct l2_bucket *l2b;
   6088 	pd_entry_t *l1pt = (pd_entry_t *) kernel_l1pt.pv_va;
   6089 	pmap_t pm = pmap_kernel();
   6090 	pt_entry_t *ptep;
   6091 	paddr_t pa;
   6092 	vsize_t size;
   6093 	int nptes, l2idx, l2next = 0;
   6094 
   6095 #ifdef ARM_MMU_EXTENDED
   6096 	KASSERT(pte_l1_s_cache_mode == pte_l1_s_cache_mode_pt);
   6097 	KASSERT(pte_l2_s_cache_mode == pte_l2_s_cache_mode_pt);
   6098 #endif
   6099 
   6100 #ifdef VERBOSE_INIT_ARM
   6101 	printf("kpm ");
   6102 #endif
   6103 	/*
   6104 	 * Initialise the kernel pmap object
   6105 	 */
   6106 	curcpu()->ci_pmap_cur = pm;
   6107 #ifdef ARM_MMU_EXTENDED
   6108 	pm->pm_l1 = l1pt;
   6109 	pm->pm_l1_pa = kernel_l1pt.pv_pa;
   6110 #ifdef VERBOSE_INIT_ARM
   6111 	printf("tlb0 ");
   6112 #endif
   6113 	pmap_tlb_info_init(&pmap_tlb0_info);
   6114 #ifdef MULTIPROCESSOR
   6115 #ifdef VERBOSE_INIT_ARM
   6116 	printf("kcpusets ");
   6117 #endif
   6118 	pm->pm_onproc = kcpuset_running;
   6119 	pm->pm_active = kcpuset_running;
   6120 #endif
   6121 #else
   6122 	pm->pm_l1 = l1;
   6123 #endif
   6124 
   6125 #ifdef VERBOSE_INIT_ARM
   6126 	printf("locks ");
   6127 #endif
   6128 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   6129 	if (arm_cache_prefer_mask != 0) {
   6130 		mutex_init(&pmap_lock, MUTEX_DEFAULT, IPL_VM);
   6131 	} else {
   6132 #endif
   6133 		mutex_init(&pmap_lock, MUTEX_DEFAULT, IPL_NONE);
   6134 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   6135 	}
   6136 #endif
   6137 	mutex_init(&pm->pm_obj_lock, MUTEX_DEFAULT, IPL_NONE);
   6138 	uvm_obj_init(&pm->pm_obj, NULL, false, 1);
   6139 	uvm_obj_setlock(&pm->pm_obj, &pm->pm_obj_lock);
   6140 
   6141 #ifdef VERBOSE_INIT_ARM
   6142 	printf("l1pt ");
   6143 #endif
   6144 	/*
   6145 	 * Scan the L1 translation table created by initarm() and create
   6146 	 * the required metadata for all valid mappings found in it.
   6147 	 */
   6148 	for (size_t l1slot = 0;
   6149 	     l1slot < L1_TABLE_SIZE / sizeof(pd_entry_t);
   6150 	     l1slot++) {
   6151 		pd_entry_t pde = l1pt[l1slot];
   6152 
   6153 		/*
   6154 		 * We're only interested in Coarse mappings.
   6155 		 * pmap_extract() can deal with section mappings without
   6156 		 * recourse to checking L2 metadata.
   6157 		 */
   6158 		if ((pde & L1_TYPE_MASK) != L1_TYPE_C)
   6159 			continue;
   6160 
   6161 		/*
   6162 		 * Lookup the KVA of this L2 descriptor table
   6163 		 */
   6164 		pa = l1pte_pa(pde);
   6165 		ptep = (pt_entry_t *)kernel_pt_lookup(pa);
   6166 		if (ptep == NULL) {
   6167 			panic("pmap_bootstrap: No L2 for va 0x%x, pa 0x%lx",
   6168 			    (u_int)l1slot << L1_S_SHIFT, pa);
   6169 		}
   6170 
   6171 		/*
   6172 		 * Fetch the associated L2 metadata structure.
   6173 		 * Allocate a new one if necessary.
   6174 		 */
   6175 		if ((l2 = pm->pm_l2[L2_IDX(l1slot)]) == NULL) {
   6176 			if (l2next == PMAP_STATIC_L2_SIZE)
   6177 				panic("pmap_bootstrap: out of static L2s");
   6178 			pm->pm_l2[L2_IDX(l1slot)] = l2 = &static_l2[l2next++];
   6179 		}
   6180 
   6181 		/*
   6182 		 * One more L1 slot tracked...
   6183 		 */
   6184 		l2->l2_occupancy++;
   6185 
   6186 		/*
   6187 		 * Fill in the details of the L2 descriptor in the
   6188 		 * appropriate bucket.
   6189 		 */
   6190 		l2b = &l2->l2_bucket[L2_BUCKET(l1slot)];
   6191 		l2b->l2b_kva = ptep;
   6192 		l2b->l2b_pa = pa;
   6193 		l2b->l2b_l1slot = l1slot;
   6194 
   6195 		/*
   6196 		 * Establish an initial occupancy count for this descriptor
   6197 		 */
   6198 		for (l2idx = 0;
   6199 		    l2idx < (L2_TABLE_SIZE_REAL / sizeof(pt_entry_t));
   6200 		    l2idx++) {
   6201 			if ((ptep[l2idx] & L2_TYPE_MASK) != L2_TYPE_INV) {
   6202 				l2b->l2b_occupancy++;
   6203 			}
   6204 		}
   6205 
   6206 		/*
   6207 		 * Make sure the descriptor itself has the correct cache mode.
   6208 		 * If not, fix it, but whine about the problem. Port-meisters
   6209 		 * should consider this a clue to fix up their initarm()
   6210 		 * function. :)
   6211 		 */
   6212 		if (pmap_set_pt_cache_mode(l1pt, (vaddr_t)ptep, 1)) {
   6213 			printf("pmap_bootstrap: WARNING! wrong cache mode for "
   6214 			    "L2 pte @ %p\n", ptep);
   6215 		}
   6216 	}
   6217 
   6218 #ifdef VERBOSE_INIT_ARM
   6219 	printf("cache(l1pt) ");
   6220 #endif
   6221 	/*
   6222 	 * Ensure the primary (kernel) L1 has the correct cache mode for
   6223 	 * a page table. Bitch if it is not correctly set.
   6224 	 */
   6225 	if (pmap_set_pt_cache_mode(l1pt, kernel_l1pt.pv_va,
   6226 		    L1_TABLE_SIZE / L2_S_SIZE)) {
   6227 		printf("pmap_bootstrap: WARNING! wrong cache mode for "
   6228 		    "primary L1 @ 0x%lx\n", kernel_l1pt.pv_va);
   6229 	}
   6230 
   6231 #ifdef PMAP_CACHE_VIVT
   6232 	cpu_dcache_wbinv_all();
   6233 	cpu_tlb_flushID();
   6234 	cpu_cpwait();
   6235 #endif
   6236 
   6237 	/*
   6238 	 * now we allocate the "special" VAs which are used for tmp mappings
   6239 	 * by the pmap (and other modules).  we allocate the VAs by advancing
   6240 	 * virtual_avail (note that there are no pages mapped at these VAs).
   6241 	 *
   6242 	 * Managed KVM space start from wherever initarm() tells us.
   6243 	 */
   6244 	virtual_avail = vstart;
   6245 	virtual_end = vend;
   6246 
   6247 #ifdef VERBOSE_INIT_ARM
   6248 	printf("specials ");
   6249 #endif
   6250 #ifdef PMAP_CACHE_VIPT
   6251 	/*
   6252 	 * If we have a VIPT cache, we need one page/pte per possible alias
   6253 	 * page so we won't violate cache aliasing rules.
   6254 	 */
   6255 	virtual_avail = (virtual_avail + arm_cache_prefer_mask) & ~arm_cache_prefer_mask;
   6256 	nptes = (arm_cache_prefer_mask >> L2_S_SHIFT) + 1;
   6257 	nptes = roundup(nptes, PAGE_SIZE / L2_S_SIZE);
   6258 	if (arm_pcache.icache_type != CACHE_TYPE_PIPT
   6259 	    && arm_pcache.icache_way_size > nptes * L2_S_SIZE) {
   6260 		nptes = arm_pcache.icache_way_size >> L2_S_SHIFT;
   6261 		nptes = roundup(nptes, PAGE_SIZE / L2_S_SIZE);
   6262 	}
   6263 #else
   6264 	nptes = PAGE_SIZE / L2_S_SIZE;
   6265 #endif
   6266 #ifdef MULTIPROCESSOR
   6267 	cnptes = nptes;
   6268 	nptes *= arm_cpu_max;
   6269 #endif
   6270 	pmap_alloc_specials(&virtual_avail, nptes, &csrcp, &csrc_pte);
   6271 	pmap_set_pt_cache_mode(l1pt, (vaddr_t)csrc_pte, nptes);
   6272 	pmap_alloc_specials(&virtual_avail, nptes, &cdstp, &cdst_pte);
   6273 	pmap_set_pt_cache_mode(l1pt, (vaddr_t)cdst_pte, nptes);
   6274 	pmap_alloc_specials(&virtual_avail, nptes, &memhook, NULL);
   6275 	if (msgbufaddr == NULL) {
   6276 		pmap_alloc_specials(&virtual_avail,
   6277 		    round_page(MSGBUFSIZE) / PAGE_SIZE,
   6278 		    (void *)&msgbufaddr, NULL);
   6279 	}
   6280 
   6281 	/*
   6282 	 * Allocate a range of kernel virtual address space to be used
   6283 	 * for L2 descriptor tables and metadata allocation in
   6284 	 * pmap_growkernel().
   6285 	 */
   6286 	size = ((virtual_end - pmap_curmaxkvaddr) + L1_S_OFFSET) / L1_S_SIZE;
   6287 	pmap_alloc_specials(&virtual_avail,
   6288 	    round_page(size * L2_TABLE_SIZE_REAL) / PAGE_SIZE,
   6289 	    &pmap_kernel_l2ptp_kva, NULL);
   6290 
   6291 	size = (size + (L2_BUCKET_SIZE - 1)) / L2_BUCKET_SIZE;
   6292 	pmap_alloc_specials(&virtual_avail,
   6293 	    round_page(size * sizeof(struct l2_dtable)) / PAGE_SIZE,
   6294 	    &pmap_kernel_l2dtable_kva, NULL);
   6295 
   6296 #ifndef ARM_MMU_EXTENDED
   6297 	/*
   6298 	 * init the static-global locks and global pmap list.
   6299 	 */
   6300 	mutex_init(&l1_lru_lock, MUTEX_DEFAULT, IPL_VM);
   6301 
   6302 	/*
   6303 	 * We can now initialise the first L1's metadata.
   6304 	 */
   6305 	SLIST_INIT(&l1_list);
   6306 	TAILQ_INIT(&l1_lru_list);
   6307 	pmap_init_l1(l1, l1pt);
   6308 #endif /* ARM_MMU_EXTENDED */
   6309 
   6310 #ifndef ARM_HAS_VBAR
   6311 	/* Set up vector page L1 details, if necessary */
   6312 	if (vector_page < KERNEL_BASE) {
   6313 		pm->pm_pl1vec = pmap_l1_kva(pm) + l1pte_index(vector_page);
   6314 		l2b = pmap_get_l2_bucket(pm, vector_page);
   6315 		KDASSERT(l2b != NULL);
   6316 		pm->pm_l1vec = l2b->l2b_pa | L1_C_PROTO |
   6317 		    L1_C_DOM(pmap_domain(pm));
   6318 	} else
   6319 		pm->pm_pl1vec = NULL;
   6320 #endif
   6321 
   6322 #ifdef VERBOSE_INIT_ARM
   6323 	printf("pools ");
   6324 #endif
   6325 	/*
   6326 	 * Initialize the pmap cache
   6327 	 */
   6328 	pool_cache_bootstrap(&pmap_cache, sizeof(struct pmap), 0, 0, 0,
   6329 	    "pmappl", NULL, IPL_NONE, pmap_pmap_ctor, NULL, NULL);
   6330 
   6331 	/*
   6332 	 * Initialize the pv pool.
   6333 	 */
   6334 	pool_init(&pmap_pv_pool, sizeof(struct pv_entry), 0, 0, 0, "pvepl",
   6335 	    &pmap_bootstrap_pv_allocator, IPL_NONE);
   6336 
   6337 	/*
   6338 	 * Initialize the L2 dtable pool and cache.
   6339 	 */
   6340 	pool_cache_bootstrap(&pmap_l2dtable_cache, sizeof(struct l2_dtable), 0,
   6341 	    0, 0, "l2dtblpl", NULL, IPL_NONE, pmap_l2dtable_ctor, NULL, NULL);
   6342 
   6343 	/*
   6344 	 * Initialise the L2 descriptor table pool and cache
   6345 	 */
   6346 	pool_cache_bootstrap(&pmap_l2ptp_cache, L2_TABLE_SIZE_REAL, 0,
   6347 	    L2_TABLE_SIZE_REAL, 0, "l2ptppl", NULL, IPL_NONE,
   6348 	    pmap_l2ptp_ctor, NULL, NULL);
   6349 
   6350 	mutex_init(&memlock, MUTEX_DEFAULT, IPL_NONE);
   6351 
   6352 	cpu_dcache_wbinv_all();
   6353 }
   6354 
   6355 static bool
   6356 pmap_set_pt_cache_mode(pd_entry_t *kl1, vaddr_t va, size_t nptes)
   6357 {
   6358 #ifdef ARM_MMU_EXTENDED
   6359 	return false;
   6360 #else
   6361 	if (pte_l1_s_cache_mode == pte_l1_s_cache_mode_pt
   6362 	    && pte_l2_s_cache_mode == pte_l2_s_cache_mode_pt)
   6363 		return false;
   6364 
   6365 	const vaddr_t eva = va + nptes * PAGE_SIZE;
   6366 	int rv = 0;
   6367 
   6368 	while (va < eva) {
   6369 		/*
   6370 		 * Make sure the descriptor itself has the correct cache mode
   6371 		 */
   6372 		pd_entry_t * const pdep = &kl1[l1pte_index(va)];
   6373 		pd_entry_t pde = *pdep;
   6374 
   6375 		if (l1pte_section_p(pde)) {
   6376 			__CTASSERT((L1_S_CACHE_MASK & L1_S_V6_SUPER) == 0);
   6377 			if ((pde & L1_S_CACHE_MASK) != pte_l1_s_cache_mode_pt) {
   6378 				*pdep = (pde & ~L1_S_CACHE_MASK) |
   6379 				    pte_l1_s_cache_mode_pt;
   6380 				PDE_SYNC(pdep);
   6381 				cpu_dcache_wbinv_range((vaddr_t)pdep,
   6382 				    sizeof(*pdep));
   6383 				rv = 1;
   6384 			}
   6385 			return rv;
   6386 		}
   6387 		vaddr_t pa = l1pte_pa(pde);
   6388 		pt_entry_t *ptep = (pt_entry_t *)kernel_pt_lookup(pa);
   6389 		if (ptep == NULL)
   6390 			panic("pmap_bootstrap: No PTP for va %#lx\n", va);
   6391 
   6392 		ptep += l2pte_index(va);
   6393 		const pt_entry_t opte = *ptep;
   6394 		if ((opte & L2_S_CACHE_MASK) != pte_l2_s_cache_mode_pt) {
   6395 			const pt_entry_t npte = (opte & ~L2_S_CACHE_MASK)
   6396 			    | pte_l2_s_cache_mode_pt;
   6397 			l2pte_set(ptep, npte, opte);
   6398 			PTE_SYNC(ptep);
   6399 			cpu_dcache_wbinv_range((vaddr_t)ptep, sizeof(*ptep));
   6400 			rv = 1;
   6401 		}
   6402 		va += PAGE_SIZE;
   6403 	}
   6404 
   6405 	return (rv);
   6406 #endif
   6407 }
   6408 
   6409 static void
   6410 pmap_alloc_specials(vaddr_t *availp, int pages, vaddr_t *vap, pt_entry_t **ptep)
   6411 {
   6412 	vaddr_t va = *availp;
   6413 	struct l2_bucket *l2b;
   6414 
   6415 	if (ptep) {
   6416 		l2b = pmap_get_l2_bucket(pmap_kernel(), va);
   6417 		if (l2b == NULL)
   6418 			panic("pmap_alloc_specials: no l2b for 0x%lx", va);
   6419 
   6420 		if (ptep)
   6421 			*ptep = &l2b->l2b_kva[l2pte_index(va)];
   6422 	}
   6423 
   6424 	*vap = va;
   6425 	*availp = va + (PAGE_SIZE * pages);
   6426 }
   6427 
   6428 void
   6429 pmap_init(void)
   6430 {
   6431 
   6432 	/*
   6433 	 * Set the available memory vars - These do not map to real memory
   6434 	 * addresses and cannot as the physical memory is fragmented.
   6435 	 * They are used by ps for %mem calculations.
   6436 	 * One could argue whether this should be the entire memory or just
   6437 	 * the memory that is useable in a user process.
   6438 	 */
   6439 	avail_start = ptoa(uvm_physseg_get_avail_start(uvm_physseg_get_first()));
   6440 	avail_end = ptoa(uvm_physseg_get_avail_end(uvm_physseg_get_last()));
   6441 
   6442 	/*
   6443 	 * Now we need to free enough pv_entry structures to allow us to get
   6444 	 * the kmem_map/kmem_object allocated and inited (done after this
   6445 	 * function is finished).  to do this we allocate one bootstrap page out
   6446 	 * of kernel_map and use it to provide an initial pool of pv_entry
   6447 	 * structures.   we never free this page.
   6448 	 */
   6449 	pool_setlowat(&pmap_pv_pool, (PAGE_SIZE / sizeof(struct pv_entry)) * 2);
   6450 
   6451 #ifdef ARM_MMU_EXTENDED
   6452 	pmap_tlb_info_evcnt_attach(&pmap_tlb0_info);
   6453 #endif
   6454 
   6455 	pmap_initialized = true;
   6456 }
   6457 
   6458 static vaddr_t last_bootstrap_page = 0;
   6459 static void *free_bootstrap_pages = NULL;
   6460 
   6461 static void *
   6462 pmap_bootstrap_pv_page_alloc(struct pool *pp, int flags)
   6463 {
   6464 	extern void *pool_page_alloc(struct pool *, int);
   6465 	vaddr_t new_page;
   6466 	void *rv;
   6467 
   6468 	if (pmap_initialized)
   6469 		return (pool_page_alloc(pp, flags));
   6470 
   6471 	if (free_bootstrap_pages) {
   6472 		rv = free_bootstrap_pages;
   6473 		free_bootstrap_pages = *((void **)rv);
   6474 		return (rv);
   6475 	}
   6476 
   6477 	KASSERT(kernel_map != NULL);
   6478 	new_page = uvm_km_alloc(kernel_map, PAGE_SIZE, 0,
   6479 	    UVM_KMF_WIRED | ((flags & PR_WAITOK) ? 0 : UVM_KMF_NOWAIT));
   6480 
   6481 	KASSERT(new_page > last_bootstrap_page);
   6482 	last_bootstrap_page = new_page;
   6483 	return ((void *)new_page);
   6484 }
   6485 
   6486 static void
   6487 pmap_bootstrap_pv_page_free(struct pool *pp, void *v)
   6488 {
   6489 	extern void pool_page_free(struct pool *, void *);
   6490 
   6491 	if ((vaddr_t)v <= last_bootstrap_page) {
   6492 		*((void **)v) = free_bootstrap_pages;
   6493 		free_bootstrap_pages = v;
   6494 		return;
   6495 	}
   6496 
   6497 	if (pmap_initialized) {
   6498 		pool_page_free(pp, v);
   6499 		return;
   6500 	}
   6501 }
   6502 
   6503 /*
   6504  * pmap_postinit()
   6505  *
   6506  * This routine is called after the vm and kmem subsystems have been
   6507  * initialised. This allows the pmap code to perform any initialisation
   6508  * that can only be done once the memory allocation is in place.
   6509  */
   6510 void
   6511 pmap_postinit(void)
   6512 {
   6513 #ifndef ARM_MMU_EXTENDED
   6514 	extern paddr_t physical_start, physical_end;
   6515 	struct l1_ttable *l1;
   6516 	struct pglist plist;
   6517 	struct vm_page *m;
   6518 	pd_entry_t *pdep;
   6519 	vaddr_t va, eva;
   6520 	u_int loop, needed;
   6521 	int error;
   6522 #endif
   6523 
   6524 	pool_cache_setlowat(&pmap_l2ptp_cache, (PAGE_SIZE / L2_TABLE_SIZE_REAL) * 4);
   6525 	pool_cache_setlowat(&pmap_l2dtable_cache,
   6526 	    (PAGE_SIZE / sizeof(struct l2_dtable)) * 2);
   6527 
   6528 #ifndef ARM_MMU_EXTENDED
   6529 	needed = (maxproc / PMAP_DOMAINS) + ((maxproc % PMAP_DOMAINS) ? 1 : 0);
   6530 	needed -= 1;
   6531 
   6532 	l1 = kmem_alloc(sizeof(*l1) * needed, KM_SLEEP);
   6533 
   6534 	for (loop = 0; loop < needed; loop++, l1++) {
   6535 		/* Allocate a L1 page table */
   6536 		va = uvm_km_alloc(kernel_map, L1_TABLE_SIZE, 0, UVM_KMF_VAONLY);
   6537 		if (va == 0)
   6538 			panic("Cannot allocate L1 KVM");
   6539 
   6540 		error = uvm_pglistalloc(L1_TABLE_SIZE, physical_start,
   6541 		    physical_end, L1_TABLE_SIZE, 0, &plist, 1, 1);
   6542 		if (error)
   6543 			panic("Cannot allocate L1 physical pages");
   6544 
   6545 		m = TAILQ_FIRST(&plist);
   6546 		eva = va + L1_TABLE_SIZE;
   6547 		pdep = (pd_entry_t *)va;
   6548 
   6549 		while (m && va < eva) {
   6550 			paddr_t pa = VM_PAGE_TO_PHYS(m);
   6551 
   6552 			pmap_kenter_pa(va, pa,
   6553 			    VM_PROT_READ|VM_PROT_WRITE, PMAP_KMPAGE|PMAP_PTE);
   6554 
   6555 			va += PAGE_SIZE;
   6556 			m = TAILQ_NEXT(m, pageq.queue);
   6557 		}
   6558 
   6559 #ifdef DIAGNOSTIC
   6560 		if (m)
   6561 			panic("pmap_alloc_l1pt: pglist not empty");
   6562 #endif	/* DIAGNOSTIC */
   6563 
   6564 		pmap_init_l1(l1, pdep);
   6565 	}
   6566 
   6567 #ifdef DEBUG
   6568 	printf("pmap_postinit: Allocated %d static L1 descriptor tables\n",
   6569 	    needed);
   6570 #endif
   6571 #endif /* !ARM_MMU_EXTENDED */
   6572 }
   6573 
   6574 /*
   6575  * Note that the following routines are used by board-specific initialisation
   6576  * code to configure the initial kernel page tables.
   6577  *
   6578  * If ARM32_NEW_VM_LAYOUT is *not* defined, they operate on the assumption that
   6579  * L2 page-table pages are 4KB in size and use 4 L1 slots. This mimics the
   6580  * behaviour of the old pmap, and provides an easy migration path for
   6581  * initial bring-up of the new pmap on existing ports. Fortunately,
   6582  * pmap_bootstrap() compensates for this hackery. This is only a stop-gap and
   6583  * will be deprecated.
   6584  *
   6585  * If ARM32_NEW_VM_LAYOUT *is* defined, these functions deal with 1KB L2 page
   6586  * tables.
   6587  */
   6588 
   6589 /*
   6590  * This list exists for the benefit of pmap_map_chunk().  It keeps track
   6591  * of the kernel L2 tables during bootstrap, so that pmap_map_chunk() can
   6592  * find them as necessary.
   6593  *
   6594  * Note that the data on this list MUST remain valid after initarm() returns,
   6595  * as pmap_bootstrap() uses it to contruct L2 table metadata.
   6596  */
   6597 SLIST_HEAD(, pv_addr) kernel_pt_list = SLIST_HEAD_INITIALIZER(kernel_pt_list);
   6598 
   6599 static vaddr_t
   6600 kernel_pt_lookup(paddr_t pa)
   6601 {
   6602 	pv_addr_t *pv;
   6603 
   6604 	SLIST_FOREACH(pv, &kernel_pt_list, pv_list) {
   6605 		if (pv->pv_pa == (pa & ~PGOFSET))
   6606 			return (pv->pv_va | (pa & PGOFSET));
   6607 	}
   6608 	return (0);
   6609 }
   6610 
   6611 /*
   6612  * pmap_map_section:
   6613  *
   6614  *	Create a single section mapping.
   6615  */
   6616 void
   6617 pmap_map_section(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
   6618 {
   6619 	pd_entry_t * const pdep = (pd_entry_t *) l1pt;
   6620 	const size_t l1slot = l1pte_index(va);
   6621 	pd_entry_t fl;
   6622 
   6623 	KASSERT(((va | pa) & L1_S_OFFSET) == 0);
   6624 
   6625 	switch (cache) {
   6626 	case PTE_NOCACHE:
   6627 	default:
   6628 		fl = 0;
   6629 		break;
   6630 
   6631 	case PTE_CACHE:
   6632 		fl = pte_l1_s_cache_mode;
   6633 		break;
   6634 
   6635 	case PTE_PAGETABLE:
   6636 		fl = pte_l1_s_cache_mode_pt;
   6637 		break;
   6638 	}
   6639 
   6640 	const pd_entry_t npde = L1_S_PROTO | pa |
   6641 	    L1_S_PROT(PTE_KERNEL, prot) | fl | L1_S_DOM(PMAP_DOMAIN_KERNEL);
   6642 	l1pte_setone(pdep + l1slot, npde);
   6643 	PDE_SYNC(pdep + l1slot);
   6644 }
   6645 
   6646 /*
   6647  * pmap_map_entry:
   6648  *
   6649  *	Create a single page mapping.
   6650  */
   6651 void
   6652 pmap_map_entry(vaddr_t l1pt, vaddr_t va, paddr_t pa, int prot, int cache)
   6653 {
   6654 	pd_entry_t * const pdep = (pd_entry_t *) l1pt;
   6655 	const size_t l1slot = l1pte_index(va);
   6656 	pt_entry_t npte;
   6657 	pt_entry_t *ptep;
   6658 
   6659 	KASSERT(((va | pa) & PGOFSET) == 0);
   6660 
   6661 	switch (cache) {
   6662 	case PTE_NOCACHE:
   6663 	default:
   6664 		npte = 0;
   6665 		break;
   6666 
   6667 	case PTE_CACHE:
   6668 		npte = pte_l2_s_cache_mode;
   6669 		break;
   6670 
   6671 	case PTE_PAGETABLE:
   6672 		npte = pte_l2_s_cache_mode_pt;
   6673 		break;
   6674 	}
   6675 
   6676 	if ((pdep[l1slot] & L1_TYPE_MASK) != L1_TYPE_C)
   6677 		panic("pmap_map_entry: no L2 table for VA 0x%08lx", va);
   6678 
   6679 	ptep = (pt_entry_t *) kernel_pt_lookup(l1pte_pa(pdep[l1slot]));
   6680 	if (ptep == NULL)
   6681 		panic("pmap_map_entry: can't find L2 table for VA 0x%08lx", va);
   6682 
   6683 	npte |= L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, prot);
   6684 #ifdef ARM_MMU_EXTENDED
   6685 	if (prot & VM_PROT_EXECUTE) {
   6686 		npte &= ~L2_XS_XN;
   6687 	}
   6688 #endif
   6689 	ptep += l2pte_index(va);
   6690 	l2pte_set(ptep, npte, 0);
   6691 	PTE_SYNC(ptep);
   6692 }
   6693 
   6694 /*
   6695  * pmap_link_l2pt:
   6696  *
   6697  *	Link the L2 page table specified by "l2pv" into the L1
   6698  *	page table at the slot for "va".
   6699  */
   6700 void
   6701 pmap_link_l2pt(vaddr_t l1pt, vaddr_t va, pv_addr_t *l2pv)
   6702 {
   6703 	pd_entry_t * const pdep = (pd_entry_t *) l1pt + l1pte_index(va);
   6704 
   6705 	KASSERT((va & ((L1_S_SIZE * (PAGE_SIZE / L2_T_SIZE)) - 1)) == 0);
   6706 	KASSERT((l2pv->pv_pa & PGOFSET) == 0);
   6707 
   6708 	const pd_entry_t npde = L1_S_DOM(PMAP_DOMAIN_KERNEL) | L1_C_PROTO
   6709 	    | l2pv->pv_pa;
   6710 
   6711 	l1pte_set(pdep, npde);
   6712 	PDE_SYNC_RANGE(pdep, PAGE_SIZE / L2_T_SIZE);
   6713 
   6714 	SLIST_INSERT_HEAD(&kernel_pt_list, l2pv, pv_list);
   6715 }
   6716 
   6717 /*
   6718  * pmap_map_chunk:
   6719  *
   6720  *	Map a chunk of memory using the most efficient mappings
   6721  *	possible (section, large page, small page) into the
   6722  *	provided L1 and L2 tables at the specified virtual address.
   6723  */
   6724 vsize_t
   6725 pmap_map_chunk(vaddr_t l1pt, vaddr_t va, paddr_t pa, vsize_t size,
   6726     int prot, int cache)
   6727 {
   6728 	pd_entry_t * const pdep = (pd_entry_t *) l1pt;
   6729 	pt_entry_t f1, f2s, f2l;
   6730 	vsize_t resid;
   6731 
   6732 	resid = (size + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
   6733 
   6734 	if (l1pt == 0)
   6735 		panic("pmap_map_chunk: no L1 table provided");
   6736 
   6737 #ifdef VERBOSE_INIT_ARM
   6738 	printf("pmap_map_chunk: pa=0x%lx va=0x%lx size=0x%lx resid=0x%lx "
   6739 	    "prot=0x%x cache=%d\n", pa, va, size, resid, prot, cache);
   6740 #endif
   6741 
   6742 	switch (cache) {
   6743 	case PTE_NOCACHE:
   6744 	default:
   6745 		f1 = 0;
   6746 		f2l = 0;
   6747 		f2s = 0;
   6748 		break;
   6749 
   6750 	case PTE_CACHE:
   6751 		f1 = pte_l1_s_cache_mode;
   6752 		f2l = pte_l2_l_cache_mode;
   6753 		f2s = pte_l2_s_cache_mode;
   6754 		break;
   6755 
   6756 	case PTE_PAGETABLE:
   6757 		f1 = pte_l1_s_cache_mode_pt;
   6758 		f2l = pte_l2_l_cache_mode_pt;
   6759 		f2s = pte_l2_s_cache_mode_pt;
   6760 		break;
   6761 	}
   6762 
   6763 	size = resid;
   6764 
   6765 	while (resid > 0) {
   6766 		const size_t l1slot = l1pte_index(va);
   6767 #if (ARM_MMU_V6 + ARM_MMU_V7) > 0
   6768 		/* See if we can use a supersection mapping. */
   6769 		if (L1_SS_PROTO && L1_SS_MAPPABLE_P(va, pa, resid)) {
   6770 			/* Supersection are always domain 0 */
   6771 			const pd_entry_t npde = L1_SS_PROTO | pa
   6772 #ifdef ARM_MMU_EXTENDED
   6773 			    | ((prot & VM_PROT_EXECUTE) ? 0 : L1_S_V6_XN)
   6774 			    | (va & 0x80000000 ? 0 : L1_S_V6_nG)
   6775 #endif
   6776 			    | L1_S_PROT(PTE_KERNEL, prot) | f1;
   6777 #ifdef VERBOSE_INIT_ARM
   6778 			printf("sS");
   6779 #endif
   6780 			l1pte_set(&pdep[l1slot], npde);
   6781 			PDE_SYNC_RANGE(&pdep[l1slot], L1_SS_SIZE / L1_S_SIZE);
   6782 			va += L1_SS_SIZE;
   6783 			pa += L1_SS_SIZE;
   6784 			resid -= L1_SS_SIZE;
   6785 			continue;
   6786 		}
   6787 #endif
   6788 		/* See if we can use a section mapping. */
   6789 		if (L1_S_MAPPABLE_P(va, pa, resid)) {
   6790 			const pd_entry_t npde = L1_S_PROTO | pa
   6791 #ifdef ARM_MMU_EXTENDED
   6792 			    | ((prot & VM_PROT_EXECUTE) ? 0 : L1_S_V6_XN)
   6793 			    | (va & 0x80000000 ? 0 : L1_S_V6_nG)
   6794 #endif
   6795 			    | L1_S_PROT(PTE_KERNEL, prot) | f1
   6796 			    | L1_S_DOM(PMAP_DOMAIN_KERNEL);
   6797 #ifdef VERBOSE_INIT_ARM
   6798 			printf("S");
   6799 #endif
   6800 			l1pte_set(&pdep[l1slot], npde);
   6801 			PDE_SYNC(&pdep[l1slot]);
   6802 			va += L1_S_SIZE;
   6803 			pa += L1_S_SIZE;
   6804 			resid -= L1_S_SIZE;
   6805 			continue;
   6806 		}
   6807 
   6808 		/*
   6809 		 * Ok, we're going to use an L2 table.  Make sure
   6810 		 * one is actually in the corresponding L1 slot
   6811 		 * for the current VA.
   6812 		 */
   6813 		if ((pdep[l1slot] & L1_TYPE_MASK) != L1_TYPE_C)
   6814 			panic("%s: no L2 table for VA %#lx", __func__, va);
   6815 
   6816 		pt_entry_t *ptep = (pt_entry_t *) kernel_pt_lookup(l1pte_pa(pdep[l1slot]));
   6817 		if (ptep == NULL)
   6818 			panic("%s: can't find L2 table for VA %#lx", __func__,
   6819 			    va);
   6820 
   6821 		ptep += l2pte_index(va);
   6822 
   6823 		/* See if we can use a L2 large page mapping. */
   6824 		if (L2_L_MAPPABLE_P(va, pa, resid)) {
   6825 			const pt_entry_t npte = L2_L_PROTO | pa
   6826 #ifdef ARM_MMU_EXTENDED
   6827 			    | ((prot & VM_PROT_EXECUTE) ? 0 : L2_XS_L_XN)
   6828 			    | (va & 0x80000000 ? 0 : L2_XS_nG)
   6829 #endif
   6830 			    | L2_L_PROT(PTE_KERNEL, prot) | f2l;
   6831 #ifdef VERBOSE_INIT_ARM
   6832 			printf("L");
   6833 #endif
   6834 			l2pte_set(ptep, npte, 0);
   6835 			PTE_SYNC_RANGE(ptep, L2_L_SIZE / L2_S_SIZE);
   6836 			va += L2_L_SIZE;
   6837 			pa += L2_L_SIZE;
   6838 			resid -= L2_L_SIZE;
   6839 			continue;
   6840 		}
   6841 
   6842 #ifdef VERBOSE_INIT_ARM
   6843 		printf("P");
   6844 #endif
   6845 		/* Use a small page mapping. */
   6846 		pt_entry_t npte = L2_S_PROTO | pa
   6847 #ifdef ARM_MMU_EXTENDED
   6848 		    | ((prot & VM_PROT_EXECUTE) ? 0 : L2_XS_XN)
   6849 		    | (va & 0x80000000 ? 0 : L2_XS_nG)
   6850 #endif
   6851 		    | L2_S_PROT(PTE_KERNEL, prot) | f2s;
   6852 #ifdef ARM_MMU_EXTENDED
   6853 		npte &= ((prot & VM_PROT_EXECUTE) ? ~L2_XS_XN : ~0);
   6854 #endif
   6855 		l2pte_set(ptep, npte, 0);
   6856 		PTE_SYNC(ptep);
   6857 		va += PAGE_SIZE;
   6858 		pa += PAGE_SIZE;
   6859 		resid -= PAGE_SIZE;
   6860 	}
   6861 #ifdef VERBOSE_INIT_ARM
   6862 	printf("\n");
   6863 #endif
   6864 	return (size);
   6865 }
   6866 
   6867 /********************** Static device map routines ***************************/
   6868 
   6869 static const struct pmap_devmap *pmap_devmap_table;
   6870 
   6871 /*
   6872  * Register the devmap table.  This is provided in case early console
   6873  * initialization needs to register mappings created by bootstrap code
   6874  * before pmap_devmap_bootstrap() is called.
   6875  */
   6876 void
   6877 pmap_devmap_register(const struct pmap_devmap *table)
   6878 {
   6879 
   6880 	pmap_devmap_table = table;
   6881 }
   6882 
   6883 /*
   6884  * Map all of the static regions in the devmap table, and remember
   6885  * the devmap table so other parts of the kernel can look up entries
   6886  * later.
   6887  */
   6888 void
   6889 pmap_devmap_bootstrap(vaddr_t l1pt, const struct pmap_devmap *table)
   6890 {
   6891 	int i;
   6892 
   6893 	pmap_devmap_table = table;
   6894 
   6895 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
   6896 #ifdef VERBOSE_INIT_ARM
   6897 		printf("devmap: %08lx -> %08lx @ %08lx\n",
   6898 		    pmap_devmap_table[i].pd_pa,
   6899 		    pmap_devmap_table[i].pd_pa +
   6900 			pmap_devmap_table[i].pd_size - 1,
   6901 		    pmap_devmap_table[i].pd_va);
   6902 #endif
   6903 		pmap_map_chunk(l1pt, pmap_devmap_table[i].pd_va,
   6904 		    pmap_devmap_table[i].pd_pa,
   6905 		    pmap_devmap_table[i].pd_size,
   6906 		    pmap_devmap_table[i].pd_prot,
   6907 		    pmap_devmap_table[i].pd_cache);
   6908 	}
   6909 }
   6910 
   6911 const struct pmap_devmap *
   6912 pmap_devmap_find_pa(paddr_t pa, psize_t size)
   6913 {
   6914 	uint64_t endpa;
   6915 	int i;
   6916 
   6917 	if (pmap_devmap_table == NULL)
   6918 		return (NULL);
   6919 
   6920 	endpa = (uint64_t)pa + (uint64_t)(size - 1);
   6921 
   6922 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
   6923 		if (pa >= pmap_devmap_table[i].pd_pa &&
   6924 		    endpa <= (uint64_t)pmap_devmap_table[i].pd_pa +
   6925 			     (uint64_t)(pmap_devmap_table[i].pd_size - 1))
   6926 			return (&pmap_devmap_table[i]);
   6927 	}
   6928 
   6929 	return (NULL);
   6930 }
   6931 
   6932 const struct pmap_devmap *
   6933 pmap_devmap_find_va(vaddr_t va, vsize_t size)
   6934 {
   6935 	int i;
   6936 
   6937 	if (pmap_devmap_table == NULL)
   6938 		return (NULL);
   6939 
   6940 	for (i = 0; pmap_devmap_table[i].pd_size != 0; i++) {
   6941 		if (va >= pmap_devmap_table[i].pd_va &&
   6942 		    va + size - 1 <= pmap_devmap_table[i].pd_va +
   6943 				     pmap_devmap_table[i].pd_size - 1)
   6944 			return (&pmap_devmap_table[i]);
   6945 	}
   6946 
   6947 	return (NULL);
   6948 }
   6949 
   6950 /********************** PTE initialization routines **************************/
   6951 
   6952 /*
   6953  * These routines are called when the CPU type is identified to set up
   6954  * the PTE prototypes, cache modes, etc.
   6955  *
   6956  * The variables are always here, just in case modules need to reference
   6957  * them (though, they shouldn't).
   6958  */
   6959 
   6960 pt_entry_t	pte_l1_s_cache_mode;
   6961 pt_entry_t	pte_l1_s_wc_mode;
   6962 pt_entry_t	pte_l1_s_cache_mode_pt;
   6963 pt_entry_t	pte_l1_s_cache_mask;
   6964 
   6965 pt_entry_t	pte_l2_l_cache_mode;
   6966 pt_entry_t	pte_l2_l_wc_mode;
   6967 pt_entry_t	pte_l2_l_cache_mode_pt;
   6968 pt_entry_t	pte_l2_l_cache_mask;
   6969 
   6970 pt_entry_t	pte_l2_s_cache_mode;
   6971 pt_entry_t	pte_l2_s_wc_mode;
   6972 pt_entry_t	pte_l2_s_cache_mode_pt;
   6973 pt_entry_t	pte_l2_s_cache_mask;
   6974 
   6975 pt_entry_t	pte_l1_s_prot_u;
   6976 pt_entry_t	pte_l1_s_prot_w;
   6977 pt_entry_t	pte_l1_s_prot_ro;
   6978 pt_entry_t	pte_l1_s_prot_mask;
   6979 
   6980 pt_entry_t	pte_l2_s_prot_u;
   6981 pt_entry_t	pte_l2_s_prot_w;
   6982 pt_entry_t	pte_l2_s_prot_ro;
   6983 pt_entry_t	pte_l2_s_prot_mask;
   6984 
   6985 pt_entry_t	pte_l2_l_prot_u;
   6986 pt_entry_t	pte_l2_l_prot_w;
   6987 pt_entry_t	pte_l2_l_prot_ro;
   6988 pt_entry_t	pte_l2_l_prot_mask;
   6989 
   6990 pt_entry_t	pte_l1_ss_proto;
   6991 pt_entry_t	pte_l1_s_proto;
   6992 pt_entry_t	pte_l1_c_proto;
   6993 pt_entry_t	pte_l2_s_proto;
   6994 
   6995 void		(*pmap_copy_page_func)(paddr_t, paddr_t);
   6996 void		(*pmap_zero_page_func)(paddr_t);
   6997 
   6998 #if (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6 + ARM_MMU_V7) != 0
   6999 void
   7000 pmap_pte_init_generic(void)
   7001 {
   7002 
   7003 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
   7004 	pte_l1_s_wc_mode = L1_S_B;
   7005 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_generic;
   7006 
   7007 	pte_l2_l_cache_mode = L2_B|L2_C;
   7008 	pte_l2_l_wc_mode = L2_B;
   7009 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_generic;
   7010 
   7011 	pte_l2_s_cache_mode = L2_B|L2_C;
   7012 	pte_l2_s_wc_mode = L2_B;
   7013 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_generic;
   7014 
   7015 	/*
   7016 	 * If we have a write-through cache, set B and C.  If
   7017 	 * we have a write-back cache, then we assume setting
   7018 	 * only C will make those pages write-through (except for those
   7019 	 * Cortex CPUs which can read the L1 caches).
   7020 	 */
   7021 	if (cpufuncs.cf_dcache_wb_range == (void *) cpufunc_nullop
   7022 #if ARM_MMU_V7 > 0
   7023 	    || CPU_ID_CORTEX_P(curcpu()->ci_arm_cpuid)
   7024 #endif
   7025 #if ARM_MMU_V6 > 0
   7026 	    || CPU_ID_ARM11_P(curcpu()->ci_arm_cpuid) /* arm116 errata 399234 */
   7027 #endif
   7028 	    || false) {
   7029 		pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
   7030 		pte_l2_l_cache_mode_pt = L2_B|L2_C;
   7031 		pte_l2_s_cache_mode_pt = L2_B|L2_C;
   7032 	} else {
   7033 		pte_l1_s_cache_mode_pt = L1_S_C;	/* write through */
   7034 		pte_l2_l_cache_mode_pt = L2_C;		/* write through */
   7035 		pte_l2_s_cache_mode_pt = L2_C;		/* write through */
   7036 	}
   7037 
   7038 	pte_l1_s_prot_u = L1_S_PROT_U_generic;
   7039 	pte_l1_s_prot_w = L1_S_PROT_W_generic;
   7040 	pte_l1_s_prot_ro = L1_S_PROT_RO_generic;
   7041 	pte_l1_s_prot_mask = L1_S_PROT_MASK_generic;
   7042 
   7043 	pte_l2_s_prot_u = L2_S_PROT_U_generic;
   7044 	pte_l2_s_prot_w = L2_S_PROT_W_generic;
   7045 	pte_l2_s_prot_ro = L2_S_PROT_RO_generic;
   7046 	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;
   7047 
   7048 	pte_l2_l_prot_u = L2_L_PROT_U_generic;
   7049 	pte_l2_l_prot_w = L2_L_PROT_W_generic;
   7050 	pte_l2_l_prot_ro = L2_L_PROT_RO_generic;
   7051 	pte_l2_l_prot_mask = L2_L_PROT_MASK_generic;
   7052 
   7053 	pte_l1_ss_proto = L1_SS_PROTO_generic;
   7054 	pte_l1_s_proto = L1_S_PROTO_generic;
   7055 	pte_l1_c_proto = L1_C_PROTO_generic;
   7056 	pte_l2_s_proto = L2_S_PROTO_generic;
   7057 
   7058 	pmap_copy_page_func = pmap_copy_page_generic;
   7059 	pmap_zero_page_func = pmap_zero_page_generic;
   7060 }
   7061 
   7062 #if defined(CPU_ARM8)
   7063 void
   7064 pmap_pte_init_arm8(void)
   7065 {
   7066 
   7067 	/*
   7068 	 * ARM8 is compatible with generic, but we need to use
   7069 	 * the page tables uncached.
   7070 	 */
   7071 	pmap_pte_init_generic();
   7072 
   7073 	pte_l1_s_cache_mode_pt = 0;
   7074 	pte_l2_l_cache_mode_pt = 0;
   7075 	pte_l2_s_cache_mode_pt = 0;
   7076 }
   7077 #endif /* CPU_ARM8 */
   7078 
   7079 #if defined(CPU_ARM9) && defined(ARM9_CACHE_WRITE_THROUGH)
   7080 void
   7081 pmap_pte_init_arm9(void)
   7082 {
   7083 
   7084 	/*
   7085 	 * ARM9 is compatible with generic, but we want to use
   7086 	 * write-through caching for now.
   7087 	 */
   7088 	pmap_pte_init_generic();
   7089 
   7090 	pte_l1_s_cache_mode = L1_S_C;
   7091 	pte_l2_l_cache_mode = L2_C;
   7092 	pte_l2_s_cache_mode = L2_C;
   7093 
   7094 	pte_l1_s_wc_mode = L1_S_B;
   7095 	pte_l2_l_wc_mode = L2_B;
   7096 	pte_l2_s_wc_mode = L2_B;
   7097 
   7098 	pte_l1_s_cache_mode_pt = L1_S_C;
   7099 	pte_l2_l_cache_mode_pt = L2_C;
   7100 	pte_l2_s_cache_mode_pt = L2_C;
   7101 }
   7102 #endif /* CPU_ARM9 && ARM9_CACHE_WRITE_THROUGH */
   7103 #endif /* (ARM_MMU_GENERIC + ARM_MMU_SA1 + ARM_MMU_V6) != 0 */
   7104 
   7105 #if defined(CPU_ARM10)
   7106 void
   7107 pmap_pte_init_arm10(void)
   7108 {
   7109 
   7110 	/*
   7111 	 * ARM10 is compatible with generic, but we want to use
   7112 	 * write-through caching for now.
   7113 	 */
   7114 	pmap_pte_init_generic();
   7115 
   7116 	pte_l1_s_cache_mode = L1_S_B | L1_S_C;
   7117 	pte_l2_l_cache_mode = L2_B | L2_C;
   7118 	pte_l2_s_cache_mode = L2_B | L2_C;
   7119 
   7120 	pte_l1_s_cache_mode = L1_S_B;
   7121 	pte_l2_l_cache_mode = L2_B;
   7122 	pte_l2_s_cache_mode = L2_B;
   7123 
   7124 	pte_l1_s_cache_mode_pt = L1_S_C;
   7125 	pte_l2_l_cache_mode_pt = L2_C;
   7126 	pte_l2_s_cache_mode_pt = L2_C;
   7127 
   7128 }
   7129 #endif /* CPU_ARM10 */
   7130 
   7131 #if defined(CPU_ARM11) && defined(ARM11_CACHE_WRITE_THROUGH)
   7132 void
   7133 pmap_pte_init_arm11(void)
   7134 {
   7135 
   7136 	/*
   7137 	 * ARM11 is compatible with generic, but we want to use
   7138 	 * write-through caching for now.
   7139 	 */
   7140 	pmap_pte_init_generic();
   7141 
   7142 	pte_l1_s_cache_mode = L1_S_C;
   7143 	pte_l2_l_cache_mode = L2_C;
   7144 	pte_l2_s_cache_mode = L2_C;
   7145 
   7146 	pte_l1_s_wc_mode = L1_S_B;
   7147 	pte_l2_l_wc_mode = L2_B;
   7148 	pte_l2_s_wc_mode = L2_B;
   7149 
   7150 	pte_l1_s_cache_mode_pt = L1_S_C;
   7151 	pte_l2_l_cache_mode_pt = L2_C;
   7152 	pte_l2_s_cache_mode_pt = L2_C;
   7153 }
   7154 #endif /* CPU_ARM11 && ARM11_CACHE_WRITE_THROUGH */
   7155 
   7156 #if ARM_MMU_SA1 == 1
   7157 void
   7158 pmap_pte_init_sa1(void)
   7159 {
   7160 
   7161 	/*
   7162 	 * The StrongARM SA-1 cache does not have a write-through
   7163 	 * mode.  So, do the generic initialization, then reset
   7164 	 * the page table cache mode to B=1,C=1, and note that
   7165 	 * the PTEs need to be sync'd.
   7166 	 */
   7167 	pmap_pte_init_generic();
   7168 
   7169 	pte_l1_s_cache_mode_pt = L1_S_B|L1_S_C;
   7170 	pte_l2_l_cache_mode_pt = L2_B|L2_C;
   7171 	pte_l2_s_cache_mode_pt = L2_B|L2_C;
   7172 
   7173 	pmap_needs_pte_sync = 1;
   7174 }
   7175 #endif /* ARM_MMU_SA1 == 1*/
   7176 
   7177 #if ARM_MMU_XSCALE == 1
   7178 #if (ARM_NMMUS > 1)
   7179 static u_int xscale_use_minidata;
   7180 #endif
   7181 
   7182 void
   7183 pmap_pte_init_xscale(void)
   7184 {
   7185 	uint32_t auxctl;
   7186 	int write_through = 0;
   7187 
   7188 	pte_l1_s_cache_mode = L1_S_B|L1_S_C;
   7189 	pte_l1_s_wc_mode = L1_S_B;
   7190 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_xscale;
   7191 
   7192 	pte_l2_l_cache_mode = L2_B|L2_C;
   7193 	pte_l2_l_wc_mode = L2_B;
   7194 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_xscale;
   7195 
   7196 	pte_l2_s_cache_mode = L2_B|L2_C;
   7197 	pte_l2_s_wc_mode = L2_B;
   7198 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_xscale;
   7199 
   7200 	pte_l1_s_cache_mode_pt = L1_S_C;
   7201 	pte_l2_l_cache_mode_pt = L2_C;
   7202 	pte_l2_s_cache_mode_pt = L2_C;
   7203 
   7204 #ifdef XSCALE_CACHE_READ_WRITE_ALLOCATE
   7205 	/*
   7206 	 * The XScale core has an enhanced mode where writes that
   7207 	 * miss the cache cause a cache line to be allocated.  This
   7208 	 * is significantly faster than the traditional, write-through
   7209 	 * behavior of this case.
   7210 	 */
   7211 	pte_l1_s_cache_mode |= L1_S_XS_TEX(TEX_XSCALE_X);
   7212 	pte_l2_l_cache_mode |= L2_XS_L_TEX(TEX_XSCALE_X);
   7213 	pte_l2_s_cache_mode |= L2_XS_T_TEX(TEX_XSCALE_X);
   7214 #endif /* XSCALE_CACHE_READ_WRITE_ALLOCATE */
   7215 
   7216 #ifdef XSCALE_CACHE_WRITE_THROUGH
   7217 	/*
   7218 	 * Some versions of the XScale core have various bugs in
   7219 	 * their cache units, the work-around for which is to run
   7220 	 * the cache in write-through mode.  Unfortunately, this
   7221 	 * has a major (negative) impact on performance.  So, we
   7222 	 * go ahead and run fast-and-loose, in the hopes that we
   7223 	 * don't line up the planets in a way that will trip the
   7224 	 * bugs.
   7225 	 *
   7226 	 * However, we give you the option to be slow-but-correct.
   7227 	 */
   7228 	write_through = 1;
   7229 #elif defined(XSCALE_CACHE_WRITE_BACK)
   7230 	/* force write back cache mode */
   7231 	write_through = 0;
   7232 #elif defined(CPU_XSCALE_PXA250) || defined(CPU_XSCALE_PXA270)
   7233 	/*
   7234 	 * Intel PXA2[15]0 processors are known to have a bug in
   7235 	 * write-back cache on revision 4 and earlier (stepping
   7236 	 * A[01] and B[012]).  Fixed for C0 and later.
   7237 	 */
   7238 	{
   7239 		uint32_t id, type;
   7240 
   7241 		id = cpufunc_id();
   7242 		type = id & ~(CPU_ID_XSCALE_COREREV_MASK|CPU_ID_REVISION_MASK);
   7243 
   7244 		if (type == CPU_ID_PXA250 || type == CPU_ID_PXA210) {
   7245 			if ((id & CPU_ID_REVISION_MASK) < 5) {
   7246 				/* write through for stepping A0-1 and B0-2 */
   7247 				write_through = 1;
   7248 			}
   7249 		}
   7250 	}
   7251 #endif /* XSCALE_CACHE_WRITE_THROUGH */
   7252 
   7253 	if (write_through) {
   7254 		pte_l1_s_cache_mode = L1_S_C;
   7255 		pte_l2_l_cache_mode = L2_C;
   7256 		pte_l2_s_cache_mode = L2_C;
   7257 	}
   7258 
   7259 #if (ARM_NMMUS > 1)
   7260 	xscale_use_minidata = 1;
   7261 #endif
   7262 
   7263 	pte_l1_s_prot_u = L1_S_PROT_U_xscale;
   7264 	pte_l1_s_prot_w = L1_S_PROT_W_xscale;
   7265 	pte_l1_s_prot_ro = L1_S_PROT_RO_xscale;
   7266 	pte_l1_s_prot_mask = L1_S_PROT_MASK_xscale;
   7267 
   7268 	pte_l2_s_prot_u = L2_S_PROT_U_xscale;
   7269 	pte_l2_s_prot_w = L2_S_PROT_W_xscale;
   7270 	pte_l2_s_prot_ro = L2_S_PROT_RO_xscale;
   7271 	pte_l2_s_prot_mask = L2_S_PROT_MASK_xscale;
   7272 
   7273 	pte_l2_l_prot_u = L2_L_PROT_U_xscale;
   7274 	pte_l2_l_prot_w = L2_L_PROT_W_xscale;
   7275 	pte_l2_l_prot_ro = L2_L_PROT_RO_xscale;
   7276 	pte_l2_l_prot_mask = L2_L_PROT_MASK_xscale;
   7277 
   7278 	pte_l1_ss_proto = L1_SS_PROTO_xscale;
   7279 	pte_l1_s_proto = L1_S_PROTO_xscale;
   7280 	pte_l1_c_proto = L1_C_PROTO_xscale;
   7281 	pte_l2_s_proto = L2_S_PROTO_xscale;
   7282 
   7283 	pmap_copy_page_func = pmap_copy_page_xscale;
   7284 	pmap_zero_page_func = pmap_zero_page_xscale;
   7285 
   7286 	/*
   7287 	 * Disable ECC protection of page table access, for now.
   7288 	 */
   7289 	auxctl = armreg_auxctl_read();
   7290 	auxctl &= ~XSCALE_AUXCTL_P;
   7291 	armreg_auxctl_write(auxctl);
   7292 }
   7293 
   7294 /*
   7295  * xscale_setup_minidata:
   7296  *
   7297  *	Set up the mini-data cache clean area.  We require the
   7298  *	caller to allocate the right amount of physically and
   7299  *	virtually contiguous space.
   7300  */
   7301 void
   7302 xscale_setup_minidata(vaddr_t l1pt, vaddr_t va, paddr_t pa)
   7303 {
   7304 	extern vaddr_t xscale_minidata_clean_addr;
   7305 	extern vsize_t xscale_minidata_clean_size; /* already initialized */
   7306 	pd_entry_t *pde = (pd_entry_t *) l1pt;
   7307 	vsize_t size;
   7308 	uint32_t auxctl;
   7309 
   7310 	xscale_minidata_clean_addr = va;
   7311 
   7312 	/* Round it to page size. */
   7313 	size = (xscale_minidata_clean_size + L2_S_OFFSET) & L2_S_FRAME;
   7314 
   7315 	for (; size != 0;
   7316 	     va += L2_S_SIZE, pa += L2_S_SIZE, size -= L2_S_SIZE) {
   7317 		const size_t l1slot = l1pte_index(va);
   7318 		pt_entry_t *ptep = (pt_entry_t *) kernel_pt_lookup(l1pte_pa(pde[l1slot]));
   7319 		if (ptep == NULL)
   7320 			panic("xscale_setup_minidata: can't find L2 table for "
   7321 			    "VA 0x%08lx", va);
   7322 
   7323 		ptep += l2pte_index(va);
   7324 		pt_entry_t opte = *ptep;
   7325 		l2pte_set(ptep,
   7326 		    L2_S_PROTO | pa | L2_S_PROT(PTE_KERNEL, VM_PROT_READ)
   7327 		    | L2_C | L2_XS_T_TEX(TEX_XSCALE_X), opte);
   7328 	}
   7329 
   7330 	/*
   7331 	 * Configure the mini-data cache for write-back with
   7332 	 * read/write-allocate.
   7333 	 *
   7334 	 * NOTE: In order to reconfigure the mini-data cache, we must
   7335 	 * make sure it contains no valid data!  In order to do that,
   7336 	 * we must issue a global data cache invalidate command!
   7337 	 *
   7338 	 * WE ASSUME WE ARE RUNNING UN-CACHED WHEN THIS ROUTINE IS CALLED!
   7339 	 * THIS IS VERY IMPORTANT!
   7340 	 */
   7341 
   7342 	/* Invalidate data and mini-data. */
   7343 	__asm volatile("mcr p15, 0, %0, c7, c6, 0" : : "r" (0));
   7344 	auxctl = armreg_auxctl_read();
   7345 	auxctl = (auxctl & ~XSCALE_AUXCTL_MD_MASK) | XSCALE_AUXCTL_MD_WB_RWA;
   7346 	armreg_auxctl_write(auxctl);
   7347 }
   7348 
   7349 /*
   7350  * Change the PTEs for the specified kernel mappings such that they
   7351  * will use the mini data cache instead of the main data cache.
   7352  */
   7353 void
   7354 pmap_uarea(vaddr_t va)
   7355 {
   7356 	vaddr_t next_bucket, eva;
   7357 
   7358 #if (ARM_NMMUS > 1)
   7359 	if (xscale_use_minidata == 0)
   7360 		return;
   7361 #endif
   7362 
   7363 	eva = va + USPACE;
   7364 
   7365 	while (va < eva) {
   7366 		next_bucket = L2_NEXT_BUCKET_VA(va);
   7367 		if (next_bucket > eva)
   7368 			next_bucket = eva;
   7369 
   7370 		struct l2_bucket *l2b = pmap_get_l2_bucket(pmap_kernel(), va);
   7371 		KDASSERT(l2b != NULL);
   7372 
   7373 		pt_entry_t * const sptep = &l2b->l2b_kva[l2pte_index(va)];
   7374 		pt_entry_t *ptep = sptep;
   7375 
   7376 		while (va < next_bucket) {
   7377 			const pt_entry_t opte = *ptep;
   7378 			if (!l2pte_minidata_p(opte)) {
   7379 				cpu_dcache_wbinv_range(va, PAGE_SIZE);
   7380 				cpu_tlb_flushD_SE(va);
   7381 				l2pte_set(ptep, opte & ~L2_B, opte);
   7382 			}
   7383 			ptep += PAGE_SIZE / L2_S_SIZE;
   7384 			va += PAGE_SIZE;
   7385 		}
   7386 		PTE_SYNC_RANGE(sptep, (u_int)(ptep - sptep));
   7387 	}
   7388 	cpu_cpwait();
   7389 }
   7390 #endif /* ARM_MMU_XSCALE == 1 */
   7391 
   7392 
   7393 #if defined(CPU_ARM11MPCORE)
   7394 
   7395 void
   7396 pmap_pte_init_arm11mpcore(void)
   7397 {
   7398 
   7399 	/* cache mode is controlled by 5 bits (B, C, TEX) */
   7400 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_armv6;
   7401 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_armv6;
   7402 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
   7403 	/* use extended small page (without APn, with TEX) */
   7404 	pte_l2_s_cache_mask = L2_XS_CACHE_MASK_armv6;
   7405 #else
   7406 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_armv6c;
   7407 #endif
   7408 
   7409 	/* write-back, write-allocate */
   7410 	pte_l1_s_cache_mode = L1_S_C | L1_S_B | L1_S_V6_TEX(0x01);
   7411 	pte_l2_l_cache_mode = L2_C | L2_B | L2_V6_L_TEX(0x01);
   7412 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
   7413 	pte_l2_s_cache_mode = L2_C | L2_B | L2_V6_XS_TEX(0x01);
   7414 #else
   7415 	/* no TEX. read-allocate */
   7416 	pte_l2_s_cache_mode = L2_C | L2_B;
   7417 #endif
   7418 	/*
   7419 	 * write-back, write-allocate for page tables.
   7420 	 */
   7421 	pte_l1_s_cache_mode_pt = L1_S_C | L1_S_B | L1_S_V6_TEX(0x01);
   7422 	pte_l2_l_cache_mode_pt = L2_C | L2_B | L2_V6_L_TEX(0x01);
   7423 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
   7424 	pte_l2_s_cache_mode_pt = L2_C | L2_B | L2_V6_XS_TEX(0x01);
   7425 #else
   7426 	pte_l2_s_cache_mode_pt = L2_C | L2_B;
   7427 #endif
   7428 
   7429 	pte_l1_s_prot_u = L1_S_PROT_U_armv6;
   7430 	pte_l1_s_prot_w = L1_S_PROT_W_armv6;
   7431 	pte_l1_s_prot_ro = L1_S_PROT_RO_armv6;
   7432 	pte_l1_s_prot_mask = L1_S_PROT_MASK_armv6;
   7433 
   7434 #if defined(ARM11MPCORE_COMPAT_MMU) || defined(ARMV6_EXTENDED_SMALL_PAGE)
   7435 	pte_l2_s_prot_u = L2_S_PROT_U_armv6n;
   7436 	pte_l2_s_prot_w = L2_S_PROT_W_armv6n;
   7437 	pte_l2_s_prot_ro = L2_S_PROT_RO_armv6n;
   7438 	pte_l2_s_prot_mask = L2_S_PROT_MASK_armv6n;
   7439 
   7440 #else
   7441 	/* with AP[0..3] */
   7442 	pte_l2_s_prot_u = L2_S_PROT_U_generic;
   7443 	pte_l2_s_prot_w = L2_S_PROT_W_generic;
   7444 	pte_l2_s_prot_ro = L2_S_PROT_RO_generic;
   7445 	pte_l2_s_prot_mask = L2_S_PROT_MASK_generic;
   7446 #endif
   7447 
   7448 #ifdef	ARM11MPCORE_COMPAT_MMU
   7449 	/* with AP[0..3] */
   7450 	pte_l2_l_prot_u = L2_L_PROT_U_generic;
   7451 	pte_l2_l_prot_w = L2_L_PROT_W_generic;
   7452 	pte_l2_l_prot_ro = L2_L_PROT_RO_generic;
   7453 	pte_l2_l_prot_mask = L2_L_PROT_MASK_generic;
   7454 
   7455 	pte_l1_ss_proto = L1_SS_PROTO_armv6;
   7456 	pte_l1_s_proto = L1_S_PROTO_armv6;
   7457 	pte_l1_c_proto = L1_C_PROTO_armv6;
   7458 	pte_l2_s_proto = L2_S_PROTO_armv6c;
   7459 #else
   7460 	pte_l2_l_prot_u = L2_L_PROT_U_armv6n;
   7461 	pte_l2_l_prot_w = L2_L_PROT_W_armv6n;
   7462 	pte_l2_l_prot_ro = L2_L_PROT_RO_armv6n;
   7463 	pte_l2_l_prot_mask = L2_L_PROT_MASK_armv6n;
   7464 
   7465 	pte_l1_ss_proto = L1_SS_PROTO_armv6;
   7466 	pte_l1_s_proto = L1_S_PROTO_armv6;
   7467 	pte_l1_c_proto = L1_C_PROTO_armv6;
   7468 	pte_l2_s_proto = L2_S_PROTO_armv6n;
   7469 #endif
   7470 
   7471 	pmap_copy_page_func = pmap_copy_page_generic;
   7472 	pmap_zero_page_func = pmap_zero_page_generic;
   7473 	pmap_needs_pte_sync = 1;
   7474 }
   7475 #endif	/* CPU_ARM11MPCORE */
   7476 
   7477 
   7478 #if ARM_MMU_V7 == 1
   7479 void
   7480 pmap_pte_init_armv7(void)
   7481 {
   7482 	/*
   7483 	 * The ARMv7-A MMU is mostly compatible with generic. If the
   7484 	 * AP field is zero, that now means "no access" rather than
   7485 	 * read-only. The prototypes are a little different because of
   7486 	 * the XN bit.
   7487 	 */
   7488 	pmap_pte_init_generic();
   7489 
   7490 	pmap_needs_pte_sync = 1;
   7491 
   7492 	pte_l1_s_cache_mask = L1_S_CACHE_MASK_armv7;
   7493 	pte_l2_l_cache_mask = L2_L_CACHE_MASK_armv7;
   7494 	pte_l2_s_cache_mask = L2_S_CACHE_MASK_armv7;
   7495 
   7496 	/*
   7497 	 * If the core support coherent walk then updates to translation tables
   7498 	 * do not require a clean to the point of unification to ensure
   7499 	 * visibility by subsequent translation table walks.  That means we can
   7500 	 * map everything shareable and cached and the right thing will happen.
   7501 	 */
   7502         if (__SHIFTOUT(armreg_mmfr3_read(), __BITS(23,20))) {
   7503 		pmap_needs_pte_sync = 0;
   7504 
   7505 		/*
   7506 		 * write-back, no write-allocate, shareable for normal pages.
   7507 		 */
   7508 		pte_l1_s_cache_mode |= L1_S_V6_S;
   7509 		pte_l2_l_cache_mode |= L2_XS_S;
   7510 		pte_l2_s_cache_mode |= L2_XS_S;
   7511 	}
   7512 
   7513 	/*
   7514 	 * Page tables are just all other memory.  We can use write-back since
   7515 	 * pmap_needs_pte_sync is 1 (or the MMU can read out of cache).
   7516 	 */
   7517 	pte_l1_s_cache_mode_pt = pte_l1_s_cache_mode;
   7518 	pte_l2_l_cache_mode_pt = pte_l2_l_cache_mode;
   7519 	pte_l2_s_cache_mode_pt = pte_l2_s_cache_mode;
   7520 
   7521 	/*
   7522 	 * Check the Memory Model Features to see if this CPU supports
   7523 	 * the TLBIASID coproc op.
   7524 	 */
   7525 	if (__SHIFTOUT(armreg_mmfr2_read(), __BITS(16,19)) >= 2) {
   7526 		arm_has_tlbiasid_p = true;
   7527 	}
   7528 
   7529 	pte_l1_s_prot_u = L1_S_PROT_U_armv7;
   7530 	pte_l1_s_prot_w = L1_S_PROT_W_armv7;
   7531 	pte_l1_s_prot_ro = L1_S_PROT_RO_armv7;
   7532 	pte_l1_s_prot_mask = L1_S_PROT_MASK_armv7;
   7533 
   7534 	pte_l2_s_prot_u = L2_S_PROT_U_armv7;
   7535 	pte_l2_s_prot_w = L2_S_PROT_W_armv7;
   7536 	pte_l2_s_prot_ro = L2_S_PROT_RO_armv7;
   7537 	pte_l2_s_prot_mask = L2_S_PROT_MASK_armv7;
   7538 
   7539 	pte_l2_l_prot_u = L2_L_PROT_U_armv7;
   7540 	pte_l2_l_prot_w = L2_L_PROT_W_armv7;
   7541 	pte_l2_l_prot_ro = L2_L_PROT_RO_armv7;
   7542 	pte_l2_l_prot_mask = L2_L_PROT_MASK_armv7;
   7543 
   7544 	pte_l1_ss_proto = L1_SS_PROTO_armv7;
   7545 	pte_l1_s_proto = L1_S_PROTO_armv7;
   7546 	pte_l1_c_proto = L1_C_PROTO_armv7;
   7547 	pte_l2_s_proto = L2_S_PROTO_armv7;
   7548 
   7549 }
   7550 #endif /* ARM_MMU_V7 */
   7551 
   7552 /*
   7553  * return the PA of the current L1 table, for use when handling a crash dump
   7554  */
   7555 uint32_t
   7556 pmap_kernel_L1_addr(void)
   7557 {
   7558 #ifdef ARM_MMU_EXTENDED
   7559 	return pmap_kernel()->pm_l1_pa;
   7560 #else
   7561 	return pmap_kernel()->pm_l1->l1_physaddr;
   7562 #endif
   7563 }
   7564 
   7565 #if defined(DDB)
   7566 /*
   7567  * A couple of ddb-callable functions for dumping pmaps
   7568  */
   7569 void pmap_dump(pmap_t);
   7570 
   7571 static pt_entry_t ncptes[64];
   7572 static void pmap_dump_ncpg(pmap_t);
   7573 
   7574 void
   7575 pmap_dump(pmap_t pm)
   7576 {
   7577 	struct l2_dtable *l2;
   7578 	struct l2_bucket *l2b;
   7579 	pt_entry_t *ptep, pte;
   7580 	vaddr_t l2_va, l2b_va, va;
   7581 	int i, j, k, occ, rows = 0;
   7582 
   7583 	if (pm == pmap_kernel())
   7584 		printf("pmap_kernel (%p): ", pm);
   7585 	else
   7586 		printf("user pmap (%p): ", pm);
   7587 
   7588 #ifdef ARM_MMU_EXTENDED
   7589 	printf("l1 at %p\n", pmap_l1_kva(pm));
   7590 #else
   7591 	printf("domain %d, l1 at %p\n", pmap_domain(pm), pmap_l1_kva(pm));
   7592 #endif
   7593 
   7594 	l2_va = 0;
   7595 	for (i = 0; i < L2_SIZE; i++, l2_va += 0x01000000) {
   7596 		l2 = pm->pm_l2[i];
   7597 
   7598 		if (l2 == NULL || l2->l2_occupancy == 0)
   7599 			continue;
   7600 
   7601 		l2b_va = l2_va;
   7602 		for (j = 0; j < L2_BUCKET_SIZE; j++, l2b_va += 0x00100000) {
   7603 			l2b = &l2->l2_bucket[j];
   7604 
   7605 			if (l2b->l2b_occupancy == 0 || l2b->l2b_kva == NULL)
   7606 				continue;
   7607 
   7608 			ptep = l2b->l2b_kva;
   7609 
   7610 			for (k = 0; k < 256 && ptep[k] == 0; k++)
   7611 				;
   7612 
   7613 			k &= ~63;
   7614 			occ = l2b->l2b_occupancy;
   7615 			va = l2b_va + (k * 4096);
   7616 			for (; k < 256; k++, va += 0x1000) {
   7617 				char ch = ' ';
   7618 				if ((k % 64) == 0) {
   7619 					if ((rows % 8) == 0) {
   7620 						printf(
   7621 "          |0000   |8000   |10000  |18000  |20000  |28000  |30000  |38000\n");
   7622 					}
   7623 					printf("%08lx: ", va);
   7624 				}
   7625 
   7626 				ncptes[k & 63] = 0;
   7627 				pte = ptep[k];
   7628 				if (pte == 0) {
   7629 					ch = '.';
   7630 				} else {
   7631 					occ--;
   7632 					switch (pte & 0x0c) {
   7633 					case 0x00:
   7634 						ch = 'D'; /* No cache No buff */
   7635 						break;
   7636 					case 0x04:
   7637 						ch = 'B'; /* No cache buff */
   7638 						break;
   7639 					case 0x08:
   7640 						if (pte & 0x40)
   7641 							ch = 'm';
   7642 						else
   7643 						   ch = 'C'; /* Cache No buff */
   7644 						break;
   7645 					case 0x0c:
   7646 						ch = 'F'; /* Cache Buff */
   7647 						break;
   7648 					}
   7649 
   7650 					if ((pte & L2_S_PROT_U) == L2_S_PROT_U)
   7651 						ch += 0x20;
   7652 
   7653 					if ((pte & 0xc) == 0)
   7654 						ncptes[k & 63] = pte;
   7655 				}
   7656 
   7657 				if ((k % 64) == 63) {
   7658 					rows++;
   7659 					printf("%c\n", ch);
   7660 					pmap_dump_ncpg(pm);
   7661 					if (occ == 0)
   7662 						break;
   7663 				} else
   7664 					printf("%c", ch);
   7665 			}
   7666 		}
   7667 	}
   7668 }
   7669 
   7670 static void
   7671 pmap_dump_ncpg(pmap_t pm)
   7672 {
   7673 	struct vm_page *pg;
   7674 	struct vm_page_md *md;
   7675 	struct pv_entry *pv;
   7676 	int i;
   7677 
   7678 	for (i = 0; i < 63; i++) {
   7679 		if (ncptes[i] == 0)
   7680 			continue;
   7681 
   7682 		pg = PHYS_TO_VM_PAGE(l2pte_pa(ncptes[i]));
   7683 		if (pg == NULL)
   7684 			continue;
   7685 		md = VM_PAGE_TO_MD(pg);
   7686 
   7687 		printf(" pa 0x%08lx: krw %d kro %d urw %d uro %d\n",
   7688 		    VM_PAGE_TO_PHYS(pg),
   7689 		    md->krw_mappings, md->kro_mappings,
   7690 		    md->urw_mappings, md->uro_mappings);
   7691 
   7692 		SLIST_FOREACH(pv, &md->pvh_list, pv_link) {
   7693 			printf("   %c va 0x%08lx, flags 0x%x\n",
   7694 			    (pm == pv->pv_pmap) ? '*' : ' ',
   7695 			    pv->pv_va, pv->pv_flags);
   7696 		}
   7697 	}
   7698 }
   7699 #endif
   7700 
   7701 #ifdef PMAP_STEAL_MEMORY
   7702 void
   7703 pmap_boot_pageadd(pv_addr_t *newpv)
   7704 {
   7705 	pv_addr_t *pv, *npv;
   7706 
   7707 	if ((pv = SLIST_FIRST(&pmap_boot_freeq)) != NULL) {
   7708 		if (newpv->pv_pa < pv->pv_va) {
   7709 			KASSERT(newpv->pv_pa + newpv->pv_size <= pv->pv_pa);
   7710 			if (newpv->pv_pa + newpv->pv_size == pv->pv_pa) {
   7711 				newpv->pv_size += pv->pv_size;
   7712 				SLIST_REMOVE_HEAD(&pmap_boot_freeq, pv_list);
   7713 			}
   7714 			pv = NULL;
   7715 		} else {
   7716 			for (; (npv = SLIST_NEXT(pv, pv_list)) != NULL;
   7717 			     pv = npv) {
   7718 				KASSERT(pv->pv_pa + pv->pv_size < npv->pv_pa);
   7719 				KASSERT(pv->pv_pa < newpv->pv_pa);
   7720 				if (newpv->pv_pa > npv->pv_pa)
   7721 					continue;
   7722 				if (pv->pv_pa + pv->pv_size == newpv->pv_pa) {
   7723 					pv->pv_size += newpv->pv_size;
   7724 					return;
   7725 				}
   7726 				if (newpv->pv_pa + newpv->pv_size < npv->pv_pa)
   7727 					break;
   7728 				newpv->pv_size += npv->pv_size;
   7729 				SLIST_INSERT_AFTER(pv, newpv, pv_list);
   7730 				SLIST_REMOVE_AFTER(newpv, pv_list);
   7731 				return;
   7732 			}
   7733 		}
   7734 	}
   7735 
   7736 	if (pv) {
   7737 		SLIST_INSERT_AFTER(pv, newpv, pv_list);
   7738 	} else {
   7739 		SLIST_INSERT_HEAD(&pmap_boot_freeq, newpv, pv_list);
   7740 	}
   7741 }
   7742 
   7743 void
   7744 pmap_boot_pagealloc(psize_t amount, psize_t mask, psize_t match,
   7745 	pv_addr_t *rpv)
   7746 {
   7747 	pv_addr_t *pv, **pvp;
   7748 	struct vm_physseg *ps;
   7749 	size_t i;
   7750 
   7751 	KASSERT(amount & PGOFSET);
   7752 	KASSERT((mask & PGOFSET) == 0);
   7753 	KASSERT((match & PGOFSET) == 0);
   7754 	KASSERT(amount != 0);
   7755 
   7756 	for (pvp = &SLIST_FIRST(&pmap_boot_freeq);
   7757 	     (pv = *pvp) != NULL;
   7758 	     pvp = &SLIST_NEXT(pv, pv_list)) {
   7759 		pv_addr_t *newpv;
   7760 		psize_t off;
   7761 		/*
   7762 		 * If this entry is too small to satify the request...
   7763 		 */
   7764 		KASSERT(pv->pv_size > 0);
   7765 		if (pv->pv_size < amount)
   7766 			continue;
   7767 
   7768 		for (off = 0; off <= mask; off += PAGE_SIZE) {
   7769 			if (((pv->pv_pa + off) & mask) == match
   7770 			    && off + amount <= pv->pv_size)
   7771 				break;
   7772 		}
   7773 		if (off > mask)
   7774 			continue;
   7775 
   7776 		rpv->pv_va = pv->pv_va + off;
   7777 		rpv->pv_pa = pv->pv_pa + off;
   7778 		rpv->pv_size = amount;
   7779 		pv->pv_size -= amount;
   7780 		if (pv->pv_size == 0) {
   7781 			KASSERT(off == 0);
   7782 			KASSERT((vaddr_t) pv == rpv->pv_va);
   7783 			*pvp = SLIST_NEXT(pv, pv_list);
   7784 		} else if (off == 0) {
   7785 			KASSERT((vaddr_t) pv == rpv->pv_va);
   7786 			newpv = (pv_addr_t *) (rpv->pv_va + amount);
   7787 			*newpv = *pv;
   7788 			newpv->pv_pa += amount;
   7789 			newpv->pv_va += amount;
   7790 			*pvp = newpv;
   7791 		} else if (off < pv->pv_size) {
   7792 			newpv = (pv_addr_t *) (rpv->pv_va + amount);
   7793 			*newpv = *pv;
   7794 			newpv->pv_size -= off;
   7795 			newpv->pv_pa += off + amount;
   7796 			newpv->pv_va += off + amount;
   7797 
   7798 			SLIST_NEXT(pv, pv_list) = newpv;
   7799 			pv->pv_size = off;
   7800 		} else {
   7801 			KASSERT((vaddr_t) pv != rpv->pv_va);
   7802 		}
   7803 		memset((void *)rpv->pv_va, 0, amount);
   7804 		return;
   7805 	}
   7806 
   7807 	if (vm_nphysseg == 0)
   7808 		panic("pmap_boot_pagealloc: couldn't allocate memory");
   7809 
   7810 	for (pvp = &SLIST_FIRST(&pmap_boot_freeq);
   7811 	     (pv = *pvp) != NULL;
   7812 	     pvp = &SLIST_NEXT(pv, pv_list)) {
   7813 		if (SLIST_NEXT(pv, pv_list) == NULL)
   7814 			break;
   7815 	}
   7816 	KASSERT(mask == 0);
   7817 	for (i = 0; i < vm_nphysseg; i++) {
   7818 		ps = VM_PHYSMEM_PTR(i);
   7819 		if (ps->avail_start == atop(pv->pv_pa + pv->pv_size)
   7820 		    && pv->pv_va + pv->pv_size <= ptoa(ps->avail_end)) {
   7821 			rpv->pv_va = pv->pv_va;
   7822 			rpv->pv_pa = pv->pv_pa;
   7823 			rpv->pv_size = amount;
   7824 			*pvp = NULL;
   7825 			pmap_map_chunk(kernel_l1pt.pv_va,
   7826 			     ptoa(ps->avail_start) + (pv->pv_va - pv->pv_pa),
   7827 			     ptoa(ps->avail_start),
   7828 			     amount - pv->pv_size,
   7829 			     VM_PROT_READ|VM_PROT_WRITE,
   7830 			     PTE_CACHE);
   7831 			ps->avail_start += atop(amount - pv->pv_size);
   7832 			/*
   7833 			 * If we consumed the entire physseg, remove it.
   7834 			 */
   7835 			if (ps->avail_start == ps->avail_end) {
   7836 				for (--vm_nphysseg; i < vm_nphysseg; i++)
   7837 					VM_PHYSMEM_PTR_SWAP(i, i + 1);
   7838 			}
   7839 			memset((void *)rpv->pv_va, 0, rpv->pv_size);
   7840 			return;
   7841 		}
   7842 	}
   7843 
   7844 	panic("pmap_boot_pagealloc: couldn't allocate memory");
   7845 }
   7846 
   7847 vaddr_t
   7848 pmap_steal_memory(vsize_t size, vaddr_t *vstartp, vaddr_t *vendp)
   7849 {
   7850 	pv_addr_t pv;
   7851 
   7852 	pmap_boot_pagealloc(size, 0, 0, &pv);
   7853 
   7854 	return pv.pv_va;
   7855 }
   7856 #endif /* PMAP_STEAL_MEMORY */
   7857 
   7858 SYSCTL_SETUP(sysctl_machdep_pmap_setup, "sysctl machdep.kmpages setup")
   7859 {
   7860 	sysctl_createv(clog, 0, NULL, NULL,
   7861 			CTLFLAG_PERMANENT,
   7862 			CTLTYPE_NODE, "machdep", NULL,
   7863 			NULL, 0, NULL, 0,
   7864 			CTL_MACHDEP, CTL_EOL);
   7865 
   7866 	sysctl_createv(clog, 0, NULL, NULL,
   7867 			CTLFLAG_PERMANENT,
   7868 			CTLTYPE_INT, "kmpages",
   7869 			SYSCTL_DESCR("count of pages allocated to kernel memory allocators"),
   7870 			NULL, 0, &pmap_kmpages, 0,
   7871 			CTL_MACHDEP, CTL_CREATE, CTL_EOL);
   7872 }
   7873 
   7874 #ifdef PMAP_NEED_ALLOC_POOLPAGE
   7875 struct vm_page *
   7876 arm_pmap_alloc_poolpage(int flags)
   7877 {
   7878 	/*
   7879 	 * On some systems, only some pages may be "coherent" for dma and we
   7880 	 * want to prefer those for pool pages (think mbufs) but fallback to
   7881 	 * any page if none is available.  But we can only fallback if we
   7882 	 * aren't direct mapping memory or all of memory can be direct-mapped.
   7883 	 * If that isn't true, pool changes can only come from direct-mapped
   7884 	 * memory.
   7885 	 */
   7886 	if (arm_poolpage_vmfreelist != VM_FREELIST_DEFAULT) {
   7887 		return uvm_pagealloc_strat(NULL, 0, NULL, flags,
   7888 		    UVM_PGA_STRAT_FALLBACK,
   7889 		    arm_poolpage_vmfreelist);
   7890 	}
   7891 
   7892 	return uvm_pagealloc(NULL, 0, NULL, flags);
   7893 }
   7894 #endif
   7895 
   7896 #if defined(ARM_MMU_EXTENDED) && defined(MULTIPROCESSOR)
   7897 void
   7898 pmap_md_tlb_info_attach(struct pmap_tlb_info *ti, struct cpu_info *ci)
   7899 {
   7900         /* nothing */
   7901 }
   7902 
   7903 int
   7904 pic_ipi_shootdown(void *arg)
   7905 {
   7906 #if PMAP_TLB_NEED_SHOOTDOWN
   7907 	pmap_tlb_shootdown_process();
   7908 #endif
   7909 	return 1;
   7910 }
   7911 #endif /* ARM_MMU_EXTENDED && MULTIPROCESSOR */
   7912 
   7913 
   7914 #ifdef __HAVE_MM_MD_DIRECT_MAPPED_PHYS
   7915 vaddr_t
   7916 pmap_direct_mapped_phys(paddr_t pa, bool *ok_p, vaddr_t va)
   7917 {
   7918 	bool ok = false;
   7919 	if (physical_start <= pa && pa < physical_end) {
   7920 #ifdef KERNEL_BASE_VOFFSET
   7921 		const vaddr_t newva = pa + KERNEL_BASE_VOFFSET;
   7922 #else
   7923 		const vaddr_t newva = KERNEL_BASE + pa - physical_start;
   7924 #endif
   7925 #ifdef ARM_MMU_EXTENDED
   7926 		if (newva >= KERNEL_BASE && newva < pmap_directlimit) {
   7927 #endif
   7928 			va = newva;
   7929 			ok = true;
   7930 #ifdef ARM_MMU_EXTENDED
   7931 		}
   7932 #endif
   7933 	}
   7934 	KASSERT(ok_p);
   7935 	*ok_p = ok;
   7936 	return va;
   7937 }
   7938 
   7939 vaddr_t
   7940 pmap_map_poolpage(paddr_t pa)
   7941 {
   7942 	bool ok __diagused;
   7943 	vaddr_t va = pmap_direct_mapped_phys(pa, &ok, 0);
   7944 	KASSERTMSG(ok, "pa %#lx not direct mappable", pa);
   7945 #if defined(PMAP_CACHE_VIPT) && !defined(ARM_MMU_EXTENDED)
   7946 	if (arm_cache_prefer_mask != 0) {
   7947 		struct vm_page * const pg = PHYS_TO_VM_PAGE(pa);
   7948 		struct vm_page_md * const md = VM_PAGE_TO_MD(pg);
   7949 		pmap_acquire_page_lock(md);
   7950 		pmap_vac_me_harder(md, pa, pmap_kernel(), va);
   7951 		pmap_release_page_lock(md);
   7952 	}
   7953 #endif
   7954 	return va;
   7955 }
   7956 
   7957 paddr_t
   7958 pmap_unmap_poolpage(vaddr_t va)
   7959 {
   7960 	KASSERT(va >= KERNEL_BASE);
   7961 #ifdef PMAP_CACHE_VIVT
   7962 	cpu_idcache_wbinv_range(va, PAGE_SIZE);
   7963 #endif
   7964 #if defined(KERNEL_BASE_VOFFSET)
   7965         return va - KERNEL_BASE_VOFFSET;
   7966 #else
   7967         return va - KERNEL_BASE + physical_start;
   7968 #endif
   7969 }
   7970 #endif /* __HAVE_MM_MD_DIRECT_MAPPED_PHYS */
   7971