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