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