The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/amd64/amd64/pmap.c

Version: -  FREEBSD  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-2  -  FREEBSD-11-1  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-4  -  FREEBSD-10-3  -  FREEBSD-10-2  -  FREEBSD-10-1  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-3  -  FREEBSD-9-2  -  FREEBSD-9-1  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-4  -  FREEBSD-8-3  -  FREEBSD-8-2  -  FREEBSD-8-1  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-4  -  FREEBSD-7-3  -  FREEBSD-7-2  -  FREEBSD-7-1  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-4  -  FREEBSD-6-3  -  FREEBSD-6-2  -  FREEBSD-6-1  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-5  -  FREEBSD-5-4  -  FREEBSD-5-3  -  FREEBSD-5-2  -  FREEBSD-5-1  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * SPDX-License-Identifier: BSD-4-Clause
    3  *
    4  * Copyright (c) 1991 Regents of the University of California.
    5  * All rights reserved.
    6  * Copyright (c) 1994 John S. Dyson
    7  * All rights reserved.
    8  * Copyright (c) 1994 David Greenman
    9  * All rights reserved.
   10  * Copyright (c) 2003 Peter Wemm
   11  * All rights reserved.
   12  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
   13  * All rights reserved.
   14  *
   15  * This code is derived from software contributed to Berkeley by
   16  * the Systems Programming Group of the University of Utah Computer
   17  * Science Department and William Jolitz of UUNET Technologies Inc.
   18  *
   19  * Redistribution and use in source and binary forms, with or without
   20  * modification, are permitted provided that the following conditions
   21  * are met:
   22  * 1. Redistributions of source code must retain the above copyright
   23  *    notice, this list of conditions and the following disclaimer.
   24  * 2. Redistributions in binary form must reproduce the above copyright
   25  *    notice, this list of conditions and the following disclaimer in the
   26  *    documentation and/or other materials provided with the distribution.
   27  * 3. All advertising materials mentioning features or use of this software
   28  *    must display the following acknowledgement:
   29  *      This product includes software developed by the University of
   30  *      California, Berkeley and its contributors.
   31  * 4. Neither the name of the University nor the names of its contributors
   32  *    may be used to endorse or promote products derived from this software
   33  *    without specific prior written permission.
   34  *
   35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   45  * SUCH DAMAGE.
   46  *
   47  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
   48  */
   49 /*-
   50  * Copyright (c) 2003 Networks Associates Technology, Inc.
   51  * Copyright (c) 2014-2019 The FreeBSD Foundation
   52  * All rights reserved.
   53  *
   54  * This software was developed for the FreeBSD Project by Jake Burkholder,
   55  * Safeport Network Services, and Network Associates Laboratories, the
   56  * Security Research Division of Network Associates, Inc. under
   57  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
   58  * CHATS research program.
   59  *
   60  * Portions of this software were developed by
   61  * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
   62  * the FreeBSD Foundation.
   63  *
   64  * Redistribution and use in source and binary forms, with or without
   65  * modification, are permitted provided that the following conditions
   66  * are met:
   67  * 1. Redistributions of source code must retain the above copyright
   68  *    notice, this list of conditions and the following disclaimer.
   69  * 2. Redistributions in binary form must reproduce the above copyright
   70  *    notice, this list of conditions and the following disclaimer in the
   71  *    documentation and/or other materials provided with the distribution.
   72  *
   73  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   74  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   75  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   76  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   77  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   78  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   79  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   80  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   81  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   82  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   83  * SUCH DAMAGE.
   84  */
   85 
   86 #define AMD64_NPT_AWARE
   87 
   88 #include <sys/cdefs.h>
   89 __FBSDID("$FreeBSD: head/sys/amd64/amd64/pmap.c 345382 2019-03-21 19:52:50Z markj $");
   90 
   91 /*
   92  *      Manages physical address maps.
   93  *
   94  *      Since the information managed by this module is
   95  *      also stored by the logical address mapping module,
   96  *      this module may throw away valid virtual-to-physical
   97  *      mappings at almost any time.  However, invalidations
   98  *      of virtual-to-physical mappings must be done as
   99  *      requested.
  100  *
  101  *      In order to cope with hardware architectures which
  102  *      make virtual-to-physical map invalidates expensive,
  103  *      this module may delay invalidate or reduced protection
  104  *      operations until such time as they are actually
  105  *      necessary.  This module is given full information as
  106  *      to which processors are currently using which maps,
  107  *      and to when physical maps must be made correct.
  108  */
  109 
  110 #include "opt_pmap.h"
  111 #include "opt_vm.h"
  112 
  113 #include <sys/param.h>
  114 #include <sys/bitstring.h>
  115 #include <sys/bus.h>
  116 #include <sys/systm.h>
  117 #include <sys/kernel.h>
  118 #include <sys/ktr.h>
  119 #include <sys/lock.h>
  120 #include <sys/malloc.h>
  121 #include <sys/mman.h>
  122 #include <sys/mutex.h>
  123 #include <sys/proc.h>
  124 #include <sys/rangeset.h>
  125 #include <sys/rwlock.h>
  126 #include <sys/sx.h>
  127 #include <sys/turnstile.h>
  128 #include <sys/vmem.h>
  129 #include <sys/vmmeter.h>
  130 #include <sys/sched.h>
  131 #include <sys/sysctl.h>
  132 #include <sys/smp.h>
  133 
  134 #include <vm/vm.h>
  135 #include <vm/vm_param.h>
  136 #include <vm/vm_kern.h>
  137 #include <vm/vm_page.h>
  138 #include <vm/vm_map.h>
  139 #include <vm/vm_object.h>
  140 #include <vm/vm_extern.h>
  141 #include <vm/vm_pageout.h>
  142 #include <vm/vm_pager.h>
  143 #include <vm/vm_phys.h>
  144 #include <vm/vm_radix.h>
  145 #include <vm/vm_reserv.h>
  146 #include <vm/uma.h>
  147 
  148 #include <machine/intr_machdep.h>
  149 #include <x86/apicvar.h>
  150 #include <x86/ifunc.h>
  151 #include <machine/cpu.h>
  152 #include <machine/cputypes.h>
  153 #include <machine/md_var.h>
  154 #include <machine/pcb.h>
  155 #include <machine/specialreg.h>
  156 #ifdef SMP
  157 #include <machine/smp.h>
  158 #endif
  159 #include <machine/sysarch.h>
  160 #include <machine/tss.h>
  161 
  162 static __inline boolean_t
  163 pmap_type_guest(pmap_t pmap)
  164 {
  165 
  166         return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
  167 }
  168 
  169 static __inline boolean_t
  170 pmap_emulate_ad_bits(pmap_t pmap)
  171 {
  172 
  173         return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
  174 }
  175 
  176 static __inline pt_entry_t
  177 pmap_valid_bit(pmap_t pmap)
  178 {
  179         pt_entry_t mask;
  180 
  181         switch (pmap->pm_type) {
  182         case PT_X86:
  183         case PT_RVI:
  184                 mask = X86_PG_V;
  185                 break;
  186         case PT_EPT:
  187                 if (pmap_emulate_ad_bits(pmap))
  188                         mask = EPT_PG_EMUL_V;
  189                 else
  190                         mask = EPT_PG_READ;
  191                 break;
  192         default:
  193                 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
  194         }
  195 
  196         return (mask);
  197 }
  198 
  199 static __inline pt_entry_t
  200 pmap_rw_bit(pmap_t pmap)
  201 {
  202         pt_entry_t mask;
  203 
  204         switch (pmap->pm_type) {
  205         case PT_X86:
  206         case PT_RVI:
  207                 mask = X86_PG_RW;
  208                 break;
  209         case PT_EPT:
  210                 if (pmap_emulate_ad_bits(pmap))
  211                         mask = EPT_PG_EMUL_RW;
  212                 else
  213                         mask = EPT_PG_WRITE;
  214                 break;
  215         default:
  216                 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
  217         }
  218 
  219         return (mask);
  220 }
  221 
  222 static pt_entry_t pg_g;
  223 
  224 static __inline pt_entry_t
  225 pmap_global_bit(pmap_t pmap)
  226 {
  227         pt_entry_t mask;
  228 
  229         switch (pmap->pm_type) {
  230         case PT_X86:
  231                 mask = pg_g;
  232                 break;
  233         case PT_RVI:
  234         case PT_EPT:
  235                 mask = 0;
  236                 break;
  237         default:
  238                 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
  239         }
  240 
  241         return (mask);
  242 }
  243 
  244 static __inline pt_entry_t
  245 pmap_accessed_bit(pmap_t pmap)
  246 {
  247         pt_entry_t mask;
  248 
  249         switch (pmap->pm_type) {
  250         case PT_X86:
  251         case PT_RVI:
  252                 mask = X86_PG_A;
  253                 break;
  254         case PT_EPT:
  255                 if (pmap_emulate_ad_bits(pmap))
  256                         mask = EPT_PG_READ;
  257                 else
  258                         mask = EPT_PG_A;
  259                 break;
  260         default:
  261                 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
  262         }
  263 
  264         return (mask);
  265 }
  266 
  267 static __inline pt_entry_t
  268 pmap_modified_bit(pmap_t pmap)
  269 {
  270         pt_entry_t mask;
  271 
  272         switch (pmap->pm_type) {
  273         case PT_X86:
  274         case PT_RVI:
  275                 mask = X86_PG_M;
  276                 break;
  277         case PT_EPT:
  278                 if (pmap_emulate_ad_bits(pmap))
  279                         mask = EPT_PG_WRITE;
  280                 else
  281                         mask = EPT_PG_M;
  282                 break;
  283         default:
  284                 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
  285         }
  286 
  287         return (mask);
  288 }
  289 
  290 static __inline pt_entry_t
  291 pmap_pku_mask_bit(pmap_t pmap)
  292 {
  293 
  294         return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
  295 }
  296 
  297 #if !defined(DIAGNOSTIC)
  298 #ifdef __GNUC_GNU_INLINE__
  299 #define PMAP_INLINE     __attribute__((__gnu_inline__)) inline
  300 #else
  301 #define PMAP_INLINE     extern inline
  302 #endif
  303 #else
  304 #define PMAP_INLINE
  305 #endif
  306 
  307 #ifdef PV_STATS
  308 #define PV_STAT(x)      do { x ; } while (0)
  309 #else
  310 #define PV_STAT(x)      do { } while (0)
  311 #endif
  312 
  313 #define pa_index(pa)    ((pa) >> PDRSHIFT)
  314 #define pa_to_pvh(pa)   (&pv_table[pa_index(pa)])
  315 
  316 #define NPV_LIST_LOCKS  MAXCPU
  317 
  318 #define PHYS_TO_PV_LIST_LOCK(pa)        \
  319                         (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
  320 
  321 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)  do {    \
  322         struct rwlock **_lockp = (lockp);               \
  323         struct rwlock *_new_lock;                       \
  324                                                         \
  325         _new_lock = PHYS_TO_PV_LIST_LOCK(pa);           \
  326         if (_new_lock != *_lockp) {                     \
  327                 if (*_lockp != NULL)                    \
  328                         rw_wunlock(*_lockp);            \
  329                 *_lockp = _new_lock;                    \
  330                 rw_wlock(*_lockp);                      \
  331         }                                               \
  332 } while (0)
  333 
  334 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)        \
  335                         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
  336 
  337 #define RELEASE_PV_LIST_LOCK(lockp)             do {    \
  338         struct rwlock **_lockp = (lockp);               \
  339                                                         \
  340         if (*_lockp != NULL) {                          \
  341                 rw_wunlock(*_lockp);                    \
  342                 *_lockp = NULL;                         \
  343         }                                               \
  344 } while (0)
  345 
  346 #define VM_PAGE_TO_PV_LIST_LOCK(m)      \
  347                         PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
  348 
  349 struct pmap kernel_pmap_store;
  350 
  351 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
  352 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
  353 
  354 int nkpt;
  355 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
  356     "Number of kernel page table pages allocated on bootup");
  357 
  358 static int ndmpdp;
  359 vm_paddr_t dmaplimit;
  360 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
  361 pt_entry_t pg_nx;
  362 
  363 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
  364 
  365 static int pg_ps_enabled = 1;
  366 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  367     &pg_ps_enabled, 0, "Are large page mappings enabled?");
  368 
  369 #define PAT_INDEX_SIZE  8
  370 static int pat_index[PAT_INDEX_SIZE];   /* cache mode to PAT index conversion */
  371 
  372 static u_int64_t        KPTphys;        /* phys addr of kernel level 1 */
  373 static u_int64_t        KPDphys;        /* phys addr of kernel level 2 */
  374 u_int64_t               KPDPphys;       /* phys addr of kernel level 3 */
  375 u_int64_t               KPML4phys;      /* phys addr of kernel level 4 */
  376 
  377 static u_int64_t        DMPDphys;       /* phys addr of direct mapped level 2 */
  378 static u_int64_t        DMPDPphys;      /* phys addr of direct mapped level 3 */
  379 static int              ndmpdpphys;     /* number of DMPDPphys pages */
  380 
  381 static vm_paddr_t       KERNend;        /* phys addr of end of bootstrap data */
  382 
  383 /*
  384  * pmap_mapdev support pre initialization (i.e. console)
  385  */
  386 #define PMAP_PREINIT_MAPPING_COUNT      8
  387 static struct pmap_preinit_mapping {
  388         vm_paddr_t      pa;
  389         vm_offset_t     va;
  390         vm_size_t       sz;
  391         int             mode;
  392 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
  393 static int pmap_initialized;
  394 
  395 /*
  396  * Data for the pv entry allocation mechanism.
  397  * Updates to pv_invl_gen are protected by the pv_list_locks[]
  398  * elements, but reads are not.
  399  */
  400 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
  401 static struct mtx __exclusive_cache_line pv_chunks_mutex;
  402 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
  403 static u_long pv_invl_gen[NPV_LIST_LOCKS];
  404 static struct md_page *pv_table;
  405 static struct md_page pv_dummy;
  406 
  407 /*
  408  * All those kernel PT submaps that BSD is so fond of
  409  */
  410 pt_entry_t *CMAP1 = NULL;
  411 caddr_t CADDR1 = 0;
  412 static vm_offset_t qframe = 0;
  413 static struct mtx qframe_mtx;
  414 
  415 static int pmap_flags = PMAP_PDE_SUPERPAGE;     /* flags for x86 pmaps */
  416 
  417 static vmem_t *large_vmem;
  418 static u_int lm_ents;
  419 
  420 int pmap_pcid_enabled = 1;
  421 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  422     &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
  423 int invpcid_works = 0;
  424 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
  425     "Is the invpcid instruction available ?");
  426 
  427 int __read_frequently pti = 0;
  428 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  429     &pti, 0,
  430     "Page Table Isolation enabled");
  431 static vm_object_t pti_obj;
  432 static pml4_entry_t *pti_pml4;
  433 static vm_pindex_t pti_pg_idx;
  434 static bool pti_finalized;
  435 
  436 struct pmap_pkru_range {
  437         struct rs_el    pkru_rs_el;
  438         u_int           pkru_keyidx;
  439         int             pkru_flags;
  440 };
  441 
  442 static uma_zone_t pmap_pkru_ranges_zone;
  443 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  444 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
  445 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  446 static void *pkru_dup_range(void *ctx, void *data);
  447 static void pkru_free_range(void *ctx, void *node);
  448 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
  449 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  450 static void pmap_pkru_deassign_all(pmap_t pmap);
  451 
  452 static int
  453 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
  454 {
  455         int i;
  456         uint64_t res;
  457 
  458         res = 0;
  459         CPU_FOREACH(i) {
  460                 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
  461         }
  462         return (sysctl_handle_64(oidp, &res, 0, req));
  463 }
  464 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
  465     CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
  466     "Count of saved TLB context on switch");
  467 
  468 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
  469     LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
  470 static struct mtx invl_gen_mtx;
  471 static u_long pmap_invl_gen = 0;
  472 /* Fake lock object to satisfy turnstiles interface. */
  473 static struct lock_object invl_gen_ts = {
  474         .lo_name = "invlts",
  475 };
  476 
  477 static bool
  478 pmap_not_in_di(void)
  479 {
  480 
  481         return (curthread->td_md.md_invl_gen.gen == 0);
  482 }
  483 
  484 #define PMAP_ASSERT_NOT_IN_DI() \
  485     KASSERT(pmap_not_in_di(), ("DI already started"))
  486 
  487 /*
  488  * Start a new Delayed Invalidation (DI) block of code, executed by
  489  * the current thread.  Within a DI block, the current thread may
  490  * destroy both the page table and PV list entries for a mapping and
  491  * then release the corresponding PV list lock before ensuring that
  492  * the mapping is flushed from the TLBs of any processors with the
  493  * pmap active.
  494  */
  495 static void
  496 pmap_delayed_invl_started(void)
  497 {
  498         struct pmap_invl_gen *invl_gen;
  499         u_long currgen;
  500 
  501         invl_gen = &curthread->td_md.md_invl_gen;
  502         PMAP_ASSERT_NOT_IN_DI();
  503         mtx_lock(&invl_gen_mtx);
  504         if (LIST_EMPTY(&pmap_invl_gen_tracker))
  505                 currgen = pmap_invl_gen;
  506         else
  507                 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
  508         invl_gen->gen = currgen + 1;
  509         LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
  510         mtx_unlock(&invl_gen_mtx);
  511 }
  512 
  513 /*
  514  * Finish the DI block, previously started by the current thread.  All
  515  * required TLB flushes for the pages marked by
  516  * pmap_delayed_invl_page() must be finished before this function is
  517  * called.
  518  *
  519  * This function works by bumping the global DI generation number to
  520  * the generation number of the current thread's DI, unless there is a
  521  * pending DI that started earlier.  In the latter case, bumping the
  522  * global DI generation number would incorrectly signal that the
  523  * earlier DI had finished.  Instead, this function bumps the earlier
  524  * DI's generation number to match the generation number of the
  525  * current thread's DI.
  526  */
  527 static void
  528 pmap_delayed_invl_finished(void)
  529 {
  530         struct pmap_invl_gen *invl_gen, *next;
  531         struct turnstile *ts;
  532 
  533         invl_gen = &curthread->td_md.md_invl_gen;
  534         KASSERT(invl_gen->gen != 0, ("missed invl_started"));
  535         mtx_lock(&invl_gen_mtx);
  536         next = LIST_NEXT(invl_gen, link);
  537         if (next == NULL) {
  538                 turnstile_chain_lock(&invl_gen_ts);
  539                 ts = turnstile_lookup(&invl_gen_ts);
  540                 pmap_invl_gen = invl_gen->gen;
  541                 if (ts != NULL) {
  542                         turnstile_broadcast(ts, TS_SHARED_QUEUE);
  543                         turnstile_unpend(ts);
  544                 }
  545                 turnstile_chain_unlock(&invl_gen_ts);
  546         } else {
  547                 next->gen = invl_gen->gen;
  548         }
  549         LIST_REMOVE(invl_gen, link);
  550         mtx_unlock(&invl_gen_mtx);
  551         invl_gen->gen = 0;
  552 }
  553 
  554 #ifdef PV_STATS
  555 static long invl_wait;
  556 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
  557     "Number of times DI invalidation blocked pmap_remove_all/write");
  558 #endif
  559 
  560 static u_long *
  561 pmap_delayed_invl_genp(vm_page_t m)
  562 {
  563 
  564         return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
  565 }
  566 
  567 /*
  568  * Ensure that all currently executing DI blocks, that need to flush
  569  * TLB for the given page m, actually flushed the TLB at the time the
  570  * function returned.  If the page m has an empty PV list and we call
  571  * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
  572  * valid mapping for the page m in either its page table or TLB.
  573  *
  574  * This function works by blocking until the global DI generation
  575  * number catches up with the generation number associated with the
  576  * given page m and its PV list.  Since this function's callers
  577  * typically own an object lock and sometimes own a page lock, it
  578  * cannot sleep.  Instead, it blocks on a turnstile to relinquish the
  579  * processor.
  580  */
  581 static void
  582 pmap_delayed_invl_wait(vm_page_t m)
  583 {
  584         struct turnstile *ts;
  585         u_long *m_gen;
  586 #ifdef PV_STATS
  587         bool accounted = false;
  588 #endif
  589 
  590         m_gen = pmap_delayed_invl_genp(m);
  591         while (*m_gen > pmap_invl_gen) {
  592 #ifdef PV_STATS
  593                 if (!accounted) {
  594                         atomic_add_long(&invl_wait, 1);
  595                         accounted = true;
  596                 }
  597 #endif
  598                 ts = turnstile_trywait(&invl_gen_ts);
  599                 if (*m_gen > pmap_invl_gen)
  600                         turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
  601                 else
  602                         turnstile_cancel(ts);
  603         }
  604 }
  605 
  606 /*
  607  * Mark the page m's PV list as participating in the current thread's
  608  * DI block.  Any threads concurrently using m's PV list to remove or
  609  * restrict all mappings to m will wait for the current thread's DI
  610  * block to complete before proceeding.
  611  *
  612  * The function works by setting the DI generation number for m's PV
  613  * list to at least the DI generation number of the current thread.
  614  * This forces a caller of pmap_delayed_invl_wait() to block until
  615  * current thread calls pmap_delayed_invl_finished().
  616  */
  617 static void
  618 pmap_delayed_invl_page(vm_page_t m)
  619 {
  620         u_long gen, *m_gen;
  621 
  622         rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
  623         gen = curthread->td_md.md_invl_gen.gen;
  624         if (gen == 0)
  625                 return;
  626         m_gen = pmap_delayed_invl_genp(m);
  627         if (*m_gen < gen)
  628                 *m_gen = gen;
  629 }
  630 
  631 /*
  632  * Crashdump maps.
  633  */
  634 static caddr_t crashdumpmap;
  635 
  636 /*
  637  * Internal flags for pmap_enter()'s helper functions.
  638  */
  639 #define PMAP_ENTER_NORECLAIM    0x1000000       /* Don't reclaim PV entries. */
  640 #define PMAP_ENTER_NOREPLACE    0x2000000       /* Don't replace mappings. */
  641 
  642 static void     free_pv_chunk(struct pv_chunk *pc);
  643 static void     free_pv_entry(pmap_t pmap, pv_entry_t pv);
  644 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
  645 static int      popcnt_pc_map_pq(uint64_t *map);
  646 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
  647 static void     reserve_pv_entries(pmap_t pmap, int needed,
  648                     struct rwlock **lockp);
  649 static void     pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
  650                     struct rwlock **lockp);
  651 static bool     pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
  652                     u_int flags, struct rwlock **lockp);
  653 #if VM_NRESERVLEVEL > 0
  654 static void     pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
  655                     struct rwlock **lockp);
  656 #endif
  657 static void     pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
  658 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
  659                     vm_offset_t va);
  660 
  661 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode,
  662     bool noflush);
  663 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
  664 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
  665     vm_offset_t va, struct rwlock **lockp);
  666 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
  667     vm_offset_t va);
  668 static bool     pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
  669                     vm_prot_t prot, struct rwlock **lockp);
  670 static int      pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
  671                     u_int flags, vm_page_t m, struct rwlock **lockp);
  672 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
  673     vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
  674 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
  675 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
  676 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
  677     vm_offset_t eva);
  678 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
  679     vm_offset_t eva);
  680 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
  681                     pd_entry_t pde);
  682 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
  683 static vm_page_t pmap_large_map_getptp_unlocked(void);
  684 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
  685 #if VM_NRESERVLEVEL > 0
  686 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
  687     struct rwlock **lockp);
  688 #endif
  689 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
  690     vm_prot_t prot);
  691 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
  692 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
  693     bool exec);
  694 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
  695 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
  696 static void pmap_pti_wire_pte(void *pte);
  697 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
  698     struct spglist *free, struct rwlock **lockp);
  699 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
  700     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
  701 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
  702 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
  703     struct spglist *free);
  704 static bool     pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
  705                     pd_entry_t *pde, struct spglist *free,
  706                     struct rwlock **lockp);
  707 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
  708     vm_page_t m, struct rwlock **lockp);
  709 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
  710     pd_entry_t newpde);
  711 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
  712 
  713 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
  714                 struct rwlock **lockp);
  715 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
  716                 struct rwlock **lockp);
  717 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
  718                 struct rwlock **lockp);
  719 
  720 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
  721     struct spglist *free);
  722 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
  723 
  724 /********************/
  725 /* Inline functions */
  726 /********************/
  727 
  728 /* Return a non-clipped PD index for a given VA */
  729 static __inline vm_pindex_t
  730 pmap_pde_pindex(vm_offset_t va)
  731 {
  732         return (va >> PDRSHIFT);
  733 }
  734 
  735 
  736 /* Return a pointer to the PML4 slot that corresponds to a VA */
  737 static __inline pml4_entry_t *
  738 pmap_pml4e(pmap_t pmap, vm_offset_t va)
  739 {
  740 
  741         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
  742 }
  743 
  744 /* Return a pointer to the PDP slot that corresponds to a VA */
  745 static __inline pdp_entry_t *
  746 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
  747 {
  748         pdp_entry_t *pdpe;
  749 
  750         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
  751         return (&pdpe[pmap_pdpe_index(va)]);
  752 }
  753 
  754 /* Return a pointer to the PDP slot that corresponds to a VA */
  755 static __inline pdp_entry_t *
  756 pmap_pdpe(pmap_t pmap, vm_offset_t va)
  757 {
  758         pml4_entry_t *pml4e;
  759         pt_entry_t PG_V;
  760 
  761         PG_V = pmap_valid_bit(pmap);
  762         pml4e = pmap_pml4e(pmap, va);
  763         if ((*pml4e & PG_V) == 0)
  764                 return (NULL);
  765         return (pmap_pml4e_to_pdpe(pml4e, va));
  766 }
  767 
  768 /* Return a pointer to the PD slot that corresponds to a VA */
  769 static __inline pd_entry_t *
  770 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
  771 {
  772         pd_entry_t *pde;
  773 
  774         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
  775         return (&pde[pmap_pde_index(va)]);
  776 }
  777 
  778 /* Return a pointer to the PD slot that corresponds to a VA */
  779 static __inline pd_entry_t *
  780 pmap_pde(pmap_t pmap, vm_offset_t va)
  781 {
  782         pdp_entry_t *pdpe;
  783         pt_entry_t PG_V;
  784 
  785         PG_V = pmap_valid_bit(pmap);
  786         pdpe = pmap_pdpe(pmap, va);
  787         if (pdpe == NULL || (*pdpe & PG_V) == 0)
  788                 return (NULL);
  789         return (pmap_pdpe_to_pde(pdpe, va));
  790 }
  791 
  792 /* Return a pointer to the PT slot that corresponds to a VA */
  793 static __inline pt_entry_t *
  794 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
  795 {
  796         pt_entry_t *pte;
  797 
  798         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
  799         return (&pte[pmap_pte_index(va)]);
  800 }
  801 
  802 /* Return a pointer to the PT slot that corresponds to a VA */
  803 static __inline pt_entry_t *
  804 pmap_pte(pmap_t pmap, vm_offset_t va)
  805 {
  806         pd_entry_t *pde;
  807         pt_entry_t PG_V;
  808 
  809         PG_V = pmap_valid_bit(pmap);
  810         pde = pmap_pde(pmap, va);
  811         if (pde == NULL || (*pde & PG_V) == 0)
  812                 return (NULL);
  813         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
  814                 return ((pt_entry_t *)pde);
  815         return (pmap_pde_to_pte(pde, va));
  816 }
  817 
  818 static __inline void
  819 pmap_resident_count_inc(pmap_t pmap, int count)
  820 {
  821 
  822         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
  823         pmap->pm_stats.resident_count += count;
  824 }
  825 
  826 static __inline void
  827 pmap_resident_count_dec(pmap_t pmap, int count)
  828 {
  829 
  830         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
  831         KASSERT(pmap->pm_stats.resident_count >= count,
  832             ("pmap %p resident count underflow %ld %d", pmap,
  833             pmap->pm_stats.resident_count, count));
  834         pmap->pm_stats.resident_count -= count;
  835 }
  836 
  837 PMAP_INLINE pt_entry_t *
  838 vtopte(vm_offset_t va)
  839 {
  840         u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
  841 
  842         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
  843 
  844         return (PTmap + ((va >> PAGE_SHIFT) & mask));
  845 }
  846 
  847 static __inline pd_entry_t *
  848 vtopde(vm_offset_t va)
  849 {
  850         u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
  851 
  852         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
  853 
  854         return (PDmap + ((va >> PDRSHIFT) & mask));
  855 }
  856 
  857 static u_int64_t
  858 allocpages(vm_paddr_t *firstaddr, int n)
  859 {
  860         u_int64_t ret;
  861 
  862         ret = *firstaddr;
  863         bzero((void *)ret, n * PAGE_SIZE);
  864         *firstaddr += n * PAGE_SIZE;
  865         return (ret);
  866 }
  867 
  868 CTASSERT(powerof2(NDMPML4E));
  869 
  870 /* number of kernel PDP slots */
  871 #define NKPDPE(ptpgs)           howmany(ptpgs, NPDEPG)
  872 
  873 static void
  874 nkpt_init(vm_paddr_t addr)
  875 {
  876         int pt_pages;
  877         
  878 #ifdef NKPT
  879         pt_pages = NKPT;
  880 #else
  881         pt_pages = howmany(addr, 1 << PDRSHIFT);
  882         pt_pages += NKPDPE(pt_pages);
  883 
  884         /*
  885          * Add some slop beyond the bare minimum required for bootstrapping
  886          * the kernel.
  887          *
  888          * This is quite important when allocating KVA for kernel modules.
  889          * The modules are required to be linked in the negative 2GB of
  890          * the address space.  If we run out of KVA in this region then
  891          * pmap_growkernel() will need to allocate page table pages to map
  892          * the entire 512GB of KVA space which is an unnecessary tax on
  893          * physical memory.
  894          *
  895          * Secondly, device memory mapped as part of setting up the low-
  896          * level console(s) is taken from KVA, starting at virtual_avail.
  897          * This is because cninit() is called after pmap_bootstrap() but
  898          * before vm_init() and pmap_init(). 20MB for a frame buffer is
  899          * not uncommon.
  900          */
  901         pt_pages += 32;         /* 64MB additional slop. */
  902 #endif
  903         nkpt = pt_pages;
  904 }
  905 
  906 /*
  907  * Returns the proper write/execute permission for a physical page that is
  908  * part of the initial boot allocations.
  909  *
  910  * If the page has kernel text, it is marked as read-only. If the page has
  911  * kernel read-only data, it is marked as read-only/not-executable. If the
  912  * page has only read-write data, it is marked as read-write/not-executable.
  913  * If the page is below/above the kernel range, it is marked as read-write.
  914  *
  915  * This function operates on 2M pages, since we map the kernel space that
  916  * way.
  917  *
  918  * Note that this doesn't currently provide any protection for modules.
  919  */
  920 static inline pt_entry_t
  921 bootaddr_rwx(vm_paddr_t pa)
  922 {
  923 
  924         /*
  925          * Everything in the same 2M page as the start of the kernel
  926          * should be static. On the other hand, things in the same 2M
  927          * page as the end of the kernel could be read-write/executable,
  928          * as the kernel image is not guaranteed to end on a 2M boundary.
  929          */
  930         if (pa < trunc_2mpage(btext - KERNBASE) ||
  931            pa >= trunc_2mpage(_end - KERNBASE))
  932                 return (X86_PG_RW);
  933         /*
  934          * The linker should ensure that the read-only and read-write
  935          * portions don't share the same 2M page, so this shouldn't
  936          * impact read-only data. However, in any case, any page with
  937          * read-write data needs to be read-write.
  938          */
  939         if (pa >= trunc_2mpage(brwsection - KERNBASE))
  940                 return (X86_PG_RW | pg_nx);
  941         /*
  942          * Mark any 2M page containing kernel text as read-only. Mark
  943          * other pages with read-only data as read-only and not executable.
  944          * (It is likely a small portion of the read-only data section will
  945          * be marked as read-only, but executable. This should be acceptable
  946          * since the read-only protection will keep the data from changing.)
  947          * Note that fixups to the .text section will still work until we
  948          * set CR0.WP.
  949          */
  950         if (pa < round_2mpage(etext - KERNBASE))
  951                 return (0);
  952         return (pg_nx);
  953 }
  954 
  955 static void
  956 create_pagetables(vm_paddr_t *firstaddr)
  957 {
  958         int i, j, ndm1g, nkpdpe, nkdmpde;
  959         pt_entry_t *pt_p;
  960         pd_entry_t *pd_p;
  961         pdp_entry_t *pdp_p;
  962         pml4_entry_t *p4_p;
  963         uint64_t DMPDkernphys;
  964 
  965         /* Allocate page table pages for the direct map */
  966         ndmpdp = howmany(ptoa(Maxmem), NBPDP);
  967         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
  968                 ndmpdp = 4;
  969         ndmpdpphys = howmany(ndmpdp, NPDPEPG);
  970         if (ndmpdpphys > NDMPML4E) {
  971                 /*
  972                  * Each NDMPML4E allows 512 GB, so limit to that,
  973                  * and then readjust ndmpdp and ndmpdpphys.
  974                  */
  975                 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
  976                 Maxmem = atop(NDMPML4E * NBPML4);
  977                 ndmpdpphys = NDMPML4E;
  978                 ndmpdp = NDMPML4E * NPDEPG;
  979         }
  980         DMPDPphys = allocpages(firstaddr, ndmpdpphys);
  981         ndm1g = 0;
  982         if ((amd_feature & AMDID_PAGE1GB) != 0) {
  983                 /*
  984                  * Calculate the number of 1G pages that will fully fit in
  985                  * Maxmem.
  986                  */
  987                 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
  988 
  989                 /*
  990                  * Allocate 2M pages for the kernel. These will be used in
  991                  * place of the first one or more 1G pages from ndm1g.
  992                  */
  993                 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
  994                 DMPDkernphys = allocpages(firstaddr, nkdmpde);
  995         }
  996         if (ndm1g < ndmpdp)
  997                 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
  998         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
  999 
 1000         /* Allocate pages */
 1001         KPML4phys = allocpages(firstaddr, 1);
 1002         KPDPphys = allocpages(firstaddr, NKPML4E);
 1003 
 1004         /*
 1005          * Allocate the initial number of kernel page table pages required to
 1006          * bootstrap.  We defer this until after all memory-size dependent
 1007          * allocations are done (e.g. direct map), so that we don't have to
 1008          * build in too much slop in our estimate.
 1009          *
 1010          * Note that when NKPML4E > 1, we have an empty page underneath
 1011          * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
 1012          * pages.  (pmap_enter requires a PD page to exist for each KPML4E.)
 1013          */
 1014         nkpt_init(*firstaddr);
 1015         nkpdpe = NKPDPE(nkpt);
 1016 
 1017         KPTphys = allocpages(firstaddr, nkpt);
 1018         KPDphys = allocpages(firstaddr, nkpdpe);
 1019 
 1020         /* Fill in the underlying page table pages */
 1021         /* XXX not fully used, underneath 2M pages */
 1022         pt_p = (pt_entry_t *)KPTphys;
 1023         for (i = 0; ptoa(i) < *firstaddr; i++)
 1024                 pt_p[i] = ptoa(i) | X86_PG_V | pg_g | bootaddr_rwx(ptoa(i));
 1025 
 1026         /* Now map the page tables at their location within PTmap */
 1027         pd_p = (pd_entry_t *)KPDphys;
 1028         for (i = 0; i < nkpt; i++)
 1029                 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
 1030 
 1031         /* Map from zero to end of allocations under 2M pages */
 1032         /* This replaces some of the KPTphys entries above */
 1033         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
 1034                 /* Preset PG_M and PG_A because demotion expects it. */
 1035                 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
 1036                     X86_PG_M | X86_PG_A | bootaddr_rwx(i << PDRSHIFT);
 1037 
 1038         /*
 1039          * Because we map the physical blocks in 2M pages, adjust firstaddr
 1040          * to record the physical blocks we've actually mapped into kernel
 1041          * virtual address space.
 1042          */
 1043         *firstaddr = round_2mpage(*firstaddr);
 1044 
 1045         /* And connect up the PD to the PDP (leaving room for L4 pages) */
 1046         pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
 1047         for (i = 0; i < nkpdpe; i++)
 1048                 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
 1049 
 1050         /*
 1051          * Now, set up the direct map region using 2MB and/or 1GB pages.  If
 1052          * the end of physical memory is not aligned to a 1GB page boundary,
 1053          * then the residual physical memory is mapped with 2MB pages.  Later,
 1054          * if pmap_mapdev{_attr}() uses the direct map for non-write-back
 1055          * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
 1056          * that are partially used. 
 1057          */
 1058         pd_p = (pd_entry_t *)DMPDphys;
 1059         for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
 1060                 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
 1061                 /* Preset PG_M and PG_A because demotion expects it. */
 1062                 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
 1063                     X86_PG_M | X86_PG_A | pg_nx;
 1064         }
 1065         pdp_p = (pdp_entry_t *)DMPDPphys;
 1066         for (i = 0; i < ndm1g; i++) {
 1067                 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
 1068                 /* Preset PG_M and PG_A because demotion expects it. */
 1069                 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
 1070                     X86_PG_M | X86_PG_A | pg_nx;
 1071         }
 1072         for (j = 0; i < ndmpdp; i++, j++) {
 1073                 pdp_p[i] = DMPDphys + ptoa(j);
 1074                 pdp_p[i] |= X86_PG_RW | X86_PG_V;
 1075         }
 1076 
 1077         /*
 1078          * Instead of using a 1G page for the memory containing the kernel,
 1079          * use 2M pages with appropriate permissions. (If using 1G pages,
 1080          * this will partially overwrite the PDPEs above.)
 1081          */
 1082         if (ndm1g) {
 1083                 pd_p = (pd_entry_t *)DMPDkernphys;
 1084                 for (i = 0; i < (NPDEPG * nkdmpde); i++)
 1085                         pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
 1086                             X86_PG_M | X86_PG_A | pg_nx |
 1087                             bootaddr_rwx(i << PDRSHIFT);
 1088                 for (i = 0; i < nkdmpde; i++)
 1089                         pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
 1090                             X86_PG_V;
 1091         }
 1092 
 1093         /* And recursively map PML4 to itself in order to get PTmap */
 1094         p4_p = (pml4_entry_t *)KPML4phys;
 1095         p4_p[PML4PML4I] = KPML4phys;
 1096         p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
 1097 
 1098         /* Connect the Direct Map slot(s) up to the PML4. */
 1099         for (i = 0; i < ndmpdpphys; i++) {
 1100                 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
 1101                 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
 1102         }
 1103 
 1104         /* Connect the KVA slots up to the PML4 */
 1105         for (i = 0; i < NKPML4E; i++) {
 1106                 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
 1107                 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
 1108         }
 1109 }
 1110 
 1111 /*
 1112  *      Bootstrap the system enough to run with virtual memory.
 1113  *
 1114  *      On amd64 this is called after mapping has already been enabled
 1115  *      and just syncs the pmap module with what has already been done.
 1116  *      [We can't call it easily with mapping off since the kernel is not
 1117  *      mapped with PA == VA, hence we would have to relocate every address
 1118  *      from the linked base (virtual) address "KERNBASE" to the actual
 1119  *      (physical) address starting relative to 0]
 1120  */
 1121 void
 1122 pmap_bootstrap(vm_paddr_t *firstaddr)
 1123 {
 1124         vm_offset_t va;
 1125         pt_entry_t *pte;
 1126         uint64_t cr4;
 1127         u_long res;
 1128         int i;
 1129 
 1130         KERNend = *firstaddr;
 1131         res = atop(KERNend - (vm_paddr_t)kernphys);
 1132 
 1133         if (!pti)
 1134                 pg_g = X86_PG_G;
 1135 
 1136         /*
 1137          * Create an initial set of page tables to run the kernel in.
 1138          */
 1139         create_pagetables(firstaddr);
 1140 
 1141         /*
 1142          * Add a physical memory segment (vm_phys_seg) corresponding to the
 1143          * preallocated kernel page table pages so that vm_page structures
 1144          * representing these pages will be created.  The vm_page structures
 1145          * are required for promotion of the corresponding kernel virtual
 1146          * addresses to superpage mappings.
 1147          */
 1148         vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
 1149 
 1150         virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
 1151         virtual_end = VM_MAX_KERNEL_ADDRESS;
 1152 
 1153         /*
 1154          * Enable PG_G global pages, then switch to the kernel page
 1155          * table from the bootstrap page table.  After the switch, it
 1156          * is possible to enable SMEP and SMAP since PG_U bits are
 1157          * correct now.
 1158          */
 1159         cr4 = rcr4();
 1160         cr4 |= CR4_PGE;
 1161         load_cr4(cr4);
 1162         load_cr3(KPML4phys);
 1163         if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
 1164                 cr4 |= CR4_SMEP;
 1165         if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
 1166                 cr4 |= CR4_SMAP;
 1167         load_cr4(cr4);
 1168 
 1169         /*
 1170          * Initialize the kernel pmap (which is statically allocated).
 1171          * Count bootstrap data as being resident in case any of this data is
 1172          * later unmapped (using pmap_remove()) and freed.
 1173          */
 1174         PMAP_LOCK_INIT(kernel_pmap);
 1175         kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
 1176         kernel_pmap->pm_cr3 = KPML4phys;
 1177         kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
 1178         CPU_FILL(&kernel_pmap->pm_active);      /* don't allow deactivation */
 1179         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
 1180         kernel_pmap->pm_stats.resident_count = res;
 1181         kernel_pmap->pm_flags = pmap_flags;
 1182 
 1183         /*
 1184          * Initialize the TLB invalidations generation number lock.
 1185          */
 1186         mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
 1187 
 1188         /*
 1189          * Reserve some special page table entries/VA space for temporary
 1190          * mapping of pages.
 1191          */
 1192 #define SYSMAP(c, p, v, n)      \
 1193         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
 1194 
 1195         va = virtual_avail;
 1196         pte = vtopte(va);
 1197 
 1198         /*
 1199          * Crashdump maps.  The first page is reused as CMAP1 for the
 1200          * memory test.
 1201          */
 1202         SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
 1203         CADDR1 = crashdumpmap;
 1204 
 1205         virtual_avail = va;
 1206 
 1207         /*
 1208          * Initialize the PAT MSR.
 1209          * pmap_init_pat() clears and sets CR4_PGE, which, as a
 1210          * side-effect, invalidates stale PG_G TLB entries that might
 1211          * have been created in our pre-boot environment.
 1212          */
 1213         pmap_init_pat();
 1214 
 1215         /* Initialize TLB Context Id. */
 1216         if (pmap_pcid_enabled) {
 1217                 for (i = 0; i < MAXCPU; i++) {
 1218                         kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
 1219                         kernel_pmap->pm_pcids[i].pm_gen = 1;
 1220                 }
 1221 
 1222                 /*
 1223                  * PMAP_PCID_KERN + 1 is used for initialization of
 1224                  * proc0 pmap.  The pmap' pcid state might be used by
 1225                  * EFIRT entry before first context switch, so it
 1226                  * needs to be valid.
 1227                  */
 1228                 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
 1229                 PCPU_SET(pcid_gen, 1);
 1230 
 1231                 /*
 1232                  * pcpu area for APs is zeroed during AP startup.
 1233                  * pc_pcid_next and pc_pcid_gen are initialized by AP
 1234                  * during pcpu setup.
 1235                  */
 1236                 load_cr4(rcr4() | CR4_PCIDE);
 1237         }
 1238 }
 1239 
 1240 /*
 1241  * Setup the PAT MSR.
 1242  */
 1243 void
 1244 pmap_init_pat(void)
 1245 {
 1246         uint64_t pat_msr;
 1247         u_long cr0, cr4;
 1248         int i;
 1249 
 1250         /* Bail if this CPU doesn't implement PAT. */
 1251         if ((cpu_feature & CPUID_PAT) == 0)
 1252                 panic("no PAT??");
 1253 
 1254         /* Set default PAT index table. */
 1255         for (i = 0; i < PAT_INDEX_SIZE; i++)
 1256                 pat_index[i] = -1;
 1257         pat_index[PAT_WRITE_BACK] = 0;
 1258         pat_index[PAT_WRITE_THROUGH] = 1;
 1259         pat_index[PAT_UNCACHEABLE] = 3;
 1260         pat_index[PAT_WRITE_COMBINING] = 6;
 1261         pat_index[PAT_WRITE_PROTECTED] = 5;
 1262         pat_index[PAT_UNCACHED] = 2;
 1263 
 1264         /*
 1265          * Initialize default PAT entries.
 1266          * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
 1267          * Program 5 and 6 as WP and WC.
 1268          *
 1269          * Leave 4 and 7 as WB and UC.  Note that a recursive page table
 1270          * mapping for a 2M page uses a PAT value with the bit 3 set due
 1271          * to its overload with PG_PS.
 1272          */
 1273         pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
 1274             PAT_VALUE(1, PAT_WRITE_THROUGH) |
 1275             PAT_VALUE(2, PAT_UNCACHED) |
 1276             PAT_VALUE(3, PAT_UNCACHEABLE) |
 1277             PAT_VALUE(4, PAT_WRITE_BACK) |
 1278             PAT_VALUE(5, PAT_WRITE_PROTECTED) |
 1279             PAT_VALUE(6, PAT_WRITE_COMBINING) |
 1280             PAT_VALUE(7, PAT_UNCACHEABLE);
 1281 
 1282         /* Disable PGE. */
 1283         cr4 = rcr4();
 1284         load_cr4(cr4 & ~CR4_PGE);
 1285 
 1286         /* Disable caches (CD = 1, NW = 0). */
 1287         cr0 = rcr0();
 1288         load_cr0((cr0 & ~CR0_NW) | CR0_CD);
 1289 
 1290         /* Flushes caches and TLBs. */
 1291         wbinvd();
 1292         invltlb();
 1293 
 1294         /* Update PAT and index table. */
 1295         wrmsr(MSR_PAT, pat_msr);
 1296 
 1297         /* Flush caches and TLBs again. */
 1298         wbinvd();
 1299         invltlb();
 1300 
 1301         /* Restore caches and PGE. */
 1302         load_cr0(cr0);
 1303         load_cr4(cr4);
 1304 }
 1305 
 1306 /*
 1307  *      Initialize a vm_page's machine-dependent fields.
 1308  */
 1309 void
 1310 pmap_page_init(vm_page_t m)
 1311 {
 1312 
 1313         TAILQ_INIT(&m->md.pv_list);
 1314         m->md.pat_mode = PAT_WRITE_BACK;
 1315 }
 1316 
 1317 /*
 1318  *      Initialize the pmap module.
 1319  *      Called by vm_init, to initialize any structures that the pmap
 1320  *      system needs to map virtual memory.
 1321  */
 1322 void
 1323 pmap_init(void)
 1324 {
 1325         struct pmap_preinit_mapping *ppim;
 1326         vm_page_t m, mpte;
 1327         vm_size_t s;
 1328         int error, i, pv_npg, ret, skz63;
 1329 
 1330         /* L1TF, reserve page @0 unconditionally */
 1331         vm_page_blacklist_add(0, bootverbose);
 1332 
 1333         /* Detect bare-metal Skylake Server and Skylake-X. */
 1334         if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
 1335             CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
 1336                 /*
 1337                  * Skylake-X errata SKZ63. Processor May Hang When
 1338                  * Executing Code In an HLE Transaction Region between
 1339                  * 40000000H and 403FFFFFH.
 1340                  *
 1341                  * Mark the pages in the range as preallocated.  It
 1342                  * seems to be impossible to distinguish between
 1343                  * Skylake Server and Skylake X.
 1344                  */
 1345                 skz63 = 1;
 1346                 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
 1347                 if (skz63 != 0) {
 1348                         if (bootverbose)
 1349                                 printf("SKZ63: skipping 4M RAM starting "
 1350                                     "at physical 1G\n");
 1351                         for (i = 0; i < atop(0x400000); i++) {
 1352                                 ret = vm_page_blacklist_add(0x40000000 +
 1353                                     ptoa(i), FALSE);
 1354                                 if (!ret && bootverbose)
 1355                                         printf("page at %#lx already used\n",
 1356                                             0x40000000 + ptoa(i));
 1357                         }
 1358                 }
 1359         }
 1360 
 1361         /*
 1362          * Initialize the vm page array entries for the kernel pmap's
 1363          * page table pages.
 1364          */ 
 1365         PMAP_LOCK(kernel_pmap);
 1366         for (i = 0; i < nkpt; i++) {
 1367                 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
 1368                 KASSERT(mpte >= vm_page_array &&
 1369                     mpte < &vm_page_array[vm_page_array_size],
 1370                     ("pmap_init: page table page is out of range"));
 1371                 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
 1372                 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
 1373                 mpte->wire_count = 1;
 1374                 if (i << PDRSHIFT < KERNend &&
 1375                     pmap_insert_pt_page(kernel_pmap, mpte))
 1376                         panic("pmap_init: pmap_insert_pt_page failed");
 1377         }
 1378         PMAP_UNLOCK(kernel_pmap);
 1379         vm_wire_add(nkpt);
 1380 
 1381         /*
 1382          * If the kernel is running on a virtual machine, then it must assume
 1383          * that MCA is enabled by the hypervisor.  Moreover, the kernel must
 1384          * be prepared for the hypervisor changing the vendor and family that
 1385          * are reported by CPUID.  Consequently, the workaround for AMD Family
 1386          * 10h Erratum 383 is enabled if the processor's feature set does not
 1387          * include at least one feature that is only supported by older Intel
 1388          * or newer AMD processors.
 1389          */
 1390         if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
 1391             (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
 1392             CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
 1393             AMDID2_FMA4)) == 0)
 1394                 workaround_erratum383 = 1;
 1395 
 1396         /*
 1397          * Are large page mappings enabled?
 1398          */
 1399         TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
 1400         if (pg_ps_enabled) {
 1401                 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
 1402                     ("pmap_init: can't assign to pagesizes[1]"));
 1403                 pagesizes[1] = NBPDR;
 1404         }
 1405 
 1406         /*
 1407          * Initialize the pv chunk list mutex.
 1408          */
 1409         mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
 1410 
 1411         /*
 1412          * Initialize the pool of pv list locks.
 1413          */
 1414         for (i = 0; i < NPV_LIST_LOCKS; i++)
 1415                 rw_init(&pv_list_locks[i], "pmap pv list");
 1416 
 1417         /*
 1418          * Calculate the size of the pv head table for superpages.
 1419          */
 1420         pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
 1421 
 1422         /*
 1423          * Allocate memory for the pv head table for superpages.
 1424          */
 1425         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
 1426         s = round_page(s);
 1427         pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
 1428         for (i = 0; i < pv_npg; i++)
 1429                 TAILQ_INIT(&pv_table[i].pv_list);
 1430         TAILQ_INIT(&pv_dummy.pv_list);
 1431 
 1432         pmap_initialized = 1;
 1433         for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
 1434                 ppim = pmap_preinit_mapping + i;
 1435                 if (ppim->va == 0)
 1436                         continue;
 1437                 /* Make the direct map consistent */
 1438                 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
 1439                         (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
 1440                             ppim->sz, ppim->mode);
 1441                 }
 1442                 if (!bootverbose)
 1443                         continue;
 1444                 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
 1445                     ppim->pa, ppim->va, ppim->sz, ppim->mode);
 1446         }
 1447 
 1448         mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
 1449         error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
 1450             (vmem_addr_t *)&qframe);
 1451         if (error != 0)
 1452                 panic("qframe allocation failed");
 1453 
 1454         lm_ents = 8;
 1455         TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
 1456         if (lm_ents > LMEPML4I - LMSPML4I + 1)
 1457                 lm_ents = LMEPML4I - LMSPML4I + 1;
 1458         if (bootverbose)
 1459                 printf("pmap: large map %u PML4 slots (%lu Gb)\n",
 1460                     lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
 1461         if (lm_ents != 0) {
 1462                 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
 1463                     (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
 1464                 if (large_vmem == NULL) {
 1465                         printf("pmap: cannot create large map\n");
 1466                         lm_ents = 0;
 1467                 }
 1468                 for (i = 0; i < lm_ents; i++) {
 1469                         m = pmap_large_map_getptp_unlocked();
 1470                         kernel_pmap->pm_pml4[LMSPML4I + i] = X86_PG_V |
 1471                             X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
 1472                             VM_PAGE_TO_PHYS(m);
 1473                 }
 1474         }
 1475 }
 1476 
 1477 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
 1478     "2MB page mapping counters");
 1479 
 1480 static u_long pmap_pde_demotions;
 1481 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
 1482     &pmap_pde_demotions, 0, "2MB page demotions");
 1483 
 1484 static u_long pmap_pde_mappings;
 1485 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
 1486     &pmap_pde_mappings, 0, "2MB page mappings");
 1487 
 1488 static u_long pmap_pde_p_failures;
 1489 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
 1490     &pmap_pde_p_failures, 0, "2MB page promotion failures");
 1491 
 1492 static u_long pmap_pde_promotions;
 1493 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
 1494     &pmap_pde_promotions, 0, "2MB page promotions");
 1495 
 1496 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
 1497     "1GB page mapping counters");
 1498 
 1499 static u_long pmap_pdpe_demotions;
 1500 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
 1501     &pmap_pdpe_demotions, 0, "1GB page demotions");
 1502 
 1503 /***************************************************
 1504  * Low level helper routines.....
 1505  ***************************************************/
 1506 
 1507 static pt_entry_t
 1508 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
 1509 {
 1510         int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
 1511 
 1512         switch (pmap->pm_type) {
 1513         case PT_X86:
 1514         case PT_RVI:
 1515                 /* Verify that both PAT bits are not set at the same time */
 1516                 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
 1517                     ("Invalid PAT bits in entry %#lx", entry));
 1518 
 1519                 /* Swap the PAT bits if one of them is set */
 1520                 if ((entry & x86_pat_bits) != 0)
 1521                         entry ^= x86_pat_bits;
 1522                 break;
 1523         case PT_EPT:
 1524                 /*
 1525                  * Nothing to do - the memory attributes are represented
 1526                  * the same way for regular pages and superpages.
 1527                  */
 1528                 break;
 1529         default:
 1530                 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
 1531         }
 1532 
 1533         return (entry);
 1534 }
 1535 
 1536 boolean_t
 1537 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
 1538 {
 1539 
 1540         return (mode >= 0 && mode < PAT_INDEX_SIZE &&
 1541             pat_index[(int)mode] >= 0);
 1542 }
 1543 
 1544 /*
 1545  * Determine the appropriate bits to set in a PTE or PDE for a specified
 1546  * caching mode.
 1547  */
 1548 int
 1549 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
 1550 {
 1551         int cache_bits, pat_flag, pat_idx;
 1552 
 1553         if (!pmap_is_valid_memattr(pmap, mode))
 1554                 panic("Unknown caching mode %d\n", mode);
 1555 
 1556         switch (pmap->pm_type) {
 1557         case PT_X86:
 1558         case PT_RVI:
 1559                 /* The PAT bit is different for PTE's and PDE's. */
 1560                 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
 1561 
 1562                 /* Map the caching mode to a PAT index. */
 1563                 pat_idx = pat_index[mode];
 1564 
 1565                 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
 1566                 cache_bits = 0;
 1567                 if (pat_idx & 0x4)
 1568                         cache_bits |= pat_flag;
 1569                 if (pat_idx & 0x2)
 1570                         cache_bits |= PG_NC_PCD;
 1571                 if (pat_idx & 0x1)
 1572                         cache_bits |= PG_NC_PWT;
 1573                 break;
 1574 
 1575         case PT_EPT:
 1576                 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
 1577                 break;
 1578 
 1579         default:
 1580                 panic("unsupported pmap type %d", pmap->pm_type);
 1581         }
 1582 
 1583         return (cache_bits);
 1584 }
 1585 
 1586 static int
 1587 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
 1588 {
 1589         int mask;
 1590 
 1591         switch (pmap->pm_type) {
 1592         case PT_X86:
 1593         case PT_RVI:
 1594                 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
 1595                 break;
 1596         case PT_EPT:
 1597                 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
 1598                 break;
 1599         default:
 1600                 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
 1601         }
 1602 
 1603         return (mask);
 1604 }
 1605 
 1606 bool
 1607 pmap_ps_enabled(pmap_t pmap)
 1608 {
 1609 
 1610         return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
 1611 }
 1612 
 1613 static void
 1614 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
 1615 {
 1616 
 1617         switch (pmap->pm_type) {
 1618         case PT_X86:
 1619                 break;
 1620         case PT_RVI:
 1621         case PT_EPT:
 1622                 /*
 1623                  * XXX
 1624                  * This is a little bogus since the generation number is
 1625                  * supposed to be bumped up when a region of the address
 1626                  * space is invalidated in the page tables.
 1627                  *
 1628                  * In this case the old PDE entry is valid but yet we want
 1629                  * to make sure that any mappings using the old entry are
 1630                  * invalidated in the TLB.
 1631                  *
 1632                  * The reason this works as expected is because we rendezvous
 1633                  * "all" host cpus and force any vcpu context to exit as a
 1634                  * side-effect.
 1635                  */
 1636                 atomic_add_acq_long(&pmap->pm_eptgen, 1);
 1637                 break;
 1638         default:
 1639                 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
 1640         }
 1641         pde_store(pde, newpde);
 1642 }
 1643 
 1644 /*
 1645  * After changing the page size for the specified virtual address in the page
 1646  * table, flush the corresponding entries from the processor's TLB.  Only the
 1647  * calling processor's TLB is affected.
 1648  *
 1649  * The calling thread must be pinned to a processor.
 1650  */
 1651 static void
 1652 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
 1653 {
 1654         pt_entry_t PG_G;
 1655 
 1656         if (pmap_type_guest(pmap))
 1657                 return;
 1658 
 1659         KASSERT(pmap->pm_type == PT_X86,
 1660             ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
 1661 
 1662         PG_G = pmap_global_bit(pmap);
 1663 
 1664         if ((newpde & PG_PS) == 0)
 1665                 /* Demotion: flush a specific 2MB page mapping. */
 1666                 invlpg(va);
 1667         else if ((newpde & PG_G) == 0)
 1668                 /*
 1669                  * Promotion: flush every 4KB page mapping from the TLB
 1670                  * because there are too many to flush individually.
 1671                  */
 1672                 invltlb();
 1673         else {
 1674                 /*
 1675                  * Promotion: flush every 4KB page mapping from the TLB,
 1676                  * including any global (PG_G) mappings.
 1677                  */
 1678                 invltlb_glob();
 1679         }
 1680 }
 1681 #ifdef SMP
 1682 
 1683 /*
 1684  * For SMP, these functions have to use the IPI mechanism for coherence.
 1685  *
 1686  * N.B.: Before calling any of the following TLB invalidation functions,
 1687  * the calling processor must ensure that all stores updating a non-
 1688  * kernel page table are globally performed.  Otherwise, another
 1689  * processor could cache an old, pre-update entry without being
 1690  * invalidated.  This can happen one of two ways: (1) The pmap becomes
 1691  * active on another processor after its pm_active field is checked by
 1692  * one of the following functions but before a store updating the page
 1693  * table is globally performed. (2) The pmap becomes active on another
 1694  * processor before its pm_active field is checked but due to
 1695  * speculative loads one of the following functions stills reads the
 1696  * pmap as inactive on the other processor.
 1697  * 
 1698  * The kernel page table is exempt because its pm_active field is
 1699  * immutable.  The kernel page table is always active on every
 1700  * processor.
 1701  */
 1702 
 1703 /*
 1704  * Interrupt the cpus that are executing in the guest context.
 1705  * This will force the vcpu to exit and the cached EPT mappings
 1706  * will be invalidated by the host before the next vmresume.
 1707  */
 1708 static __inline void
 1709 pmap_invalidate_ept(pmap_t pmap)
 1710 {
 1711         int ipinum;
 1712 
 1713         sched_pin();
 1714         KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
 1715             ("pmap_invalidate_ept: absurd pm_active"));
 1716 
 1717         /*
 1718          * The TLB mappings associated with a vcpu context are not
 1719          * flushed each time a different vcpu is chosen to execute.
 1720          *
 1721          * This is in contrast with a process's vtop mappings that
 1722          * are flushed from the TLB on each context switch.
 1723          *
 1724          * Therefore we need to do more than just a TLB shootdown on
 1725          * the active cpus in 'pmap->pm_active'. To do this we keep
 1726          * track of the number of invalidations performed on this pmap.
 1727          *
 1728          * Each vcpu keeps a cache of this counter and compares it
 1729          * just before a vmresume. If the counter is out-of-date an
 1730          * invept will be done to flush stale mappings from the TLB.
 1731          */
 1732         atomic_add_acq_long(&pmap->pm_eptgen, 1);
 1733 
 1734         /*
 1735          * Force the vcpu to exit and trap back into the hypervisor.
 1736          */
 1737         ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
 1738         ipi_selected(pmap->pm_active, ipinum);
 1739         sched_unpin();
 1740 }
 1741 
 1742 static cpuset_t
 1743 pmap_invalidate_cpu_mask(pmap_t pmap)
 1744 {
 1745 
 1746         return (pmap == kernel_pmap ? all_cpus : pmap->pm_active);
 1747 }
 1748 
 1749 static inline void
 1750 pmap_invalidate_page_pcid(pmap_t pmap, vm_offset_t va,
 1751     const bool invpcid_works1)
 1752 {
 1753         struct invpcid_descr d;
 1754         uint64_t kcr3, ucr3;
 1755         uint32_t pcid;
 1756         u_int cpuid, i;
 1757 
 1758         cpuid = PCPU_GET(cpuid);
 1759         if (pmap == PCPU_GET(curpmap)) {
 1760                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 1761                         /*
 1762                          * Because pm_pcid is recalculated on a
 1763                          * context switch, we must disable switching.
 1764                          * Otherwise, we might use a stale value
 1765                          * below.
 1766                          */
 1767                         critical_enter();
 1768                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 1769                         if (invpcid_works1) {
 1770                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 1771                                 d.pad = 0;
 1772                                 d.addr = va;
 1773                                 invpcid(&d, INVPCID_ADDR);
 1774                         } else {
 1775                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 1776                                 ucr3 = pmap->pm_ucr3 | pcid |
 1777                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 1778                                 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
 1779                         }
 1780                         critical_exit();
 1781                 }
 1782         } else
 1783                 pmap->pm_pcids[cpuid].pm_gen = 0;
 1784 
 1785         CPU_FOREACH(i) {
 1786                 if (cpuid != i)
 1787                         pmap->pm_pcids[i].pm_gen = 0;
 1788         }
 1789 
 1790         /*
 1791          * The fence is between stores to pm_gen and the read of the
 1792          * pm_active mask.  We need to ensure that it is impossible
 1793          * for us to miss the bit update in pm_active and
 1794          * simultaneously observe a non-zero pm_gen in
 1795          * pmap_activate_sw(), otherwise TLB update is missed.
 1796          * Without the fence, IA32 allows such an outcome.  Note that
 1797          * pm_active is updated by a locked operation, which provides
 1798          * the reciprocal fence.
 1799          */
 1800         atomic_thread_fence_seq_cst();
 1801 }
 1802 
 1803 static void
 1804 pmap_invalidate_page_pcid_invpcid(pmap_t pmap, vm_offset_t va)
 1805 {
 1806 
 1807         pmap_invalidate_page_pcid(pmap, va, true);
 1808 }
 1809 
 1810 static void
 1811 pmap_invalidate_page_pcid_noinvpcid(pmap_t pmap, vm_offset_t va)
 1812 {
 1813 
 1814         pmap_invalidate_page_pcid(pmap, va, false);
 1815 }
 1816 
 1817 static void
 1818 pmap_invalidate_page_nopcid(pmap_t pmap, vm_offset_t va)
 1819 {
 1820 }
 1821 
 1822 DEFINE_IFUNC(static, void, pmap_invalidate_page_mode, (pmap_t, vm_offset_t),
 1823     static)
 1824 {
 1825 
 1826         if (pmap_pcid_enabled)
 1827                 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid :
 1828                     pmap_invalidate_page_pcid_noinvpcid);
 1829         return (pmap_invalidate_page_nopcid);
 1830 }
 1831 
 1832 void
 1833 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
 1834 {
 1835 
 1836         if (pmap_type_guest(pmap)) {
 1837                 pmap_invalidate_ept(pmap);
 1838                 return;
 1839         }
 1840 
 1841         KASSERT(pmap->pm_type == PT_X86,
 1842             ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
 1843 
 1844         sched_pin();
 1845         if (pmap == kernel_pmap) {
 1846                 invlpg(va);
 1847         } else {
 1848                 if (pmap == PCPU_GET(curpmap))
 1849                         invlpg(va);
 1850                 pmap_invalidate_page_mode(pmap, va);
 1851         }
 1852         smp_masked_invlpg(pmap_invalidate_cpu_mask(pmap), va, pmap);
 1853         sched_unpin();
 1854 }
 1855 
 1856 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
 1857 #define PMAP_INVLPG_THRESHOLD   (4 * 1024 * PAGE_SIZE)
 1858 
 1859 static void
 1860 pmap_invalidate_range_pcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
 1861     const bool invpcid_works1)
 1862 {
 1863         struct invpcid_descr d;
 1864         uint64_t kcr3, ucr3;
 1865         uint32_t pcid;
 1866         u_int cpuid, i;
 1867 
 1868         cpuid = PCPU_GET(cpuid);
 1869         if (pmap == PCPU_GET(curpmap)) {
 1870                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 1871                         critical_enter();
 1872                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 1873                         if (invpcid_works1) {
 1874                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 1875                                 d.pad = 0;
 1876                                 d.addr = sva;
 1877                                 for (; d.addr < eva; d.addr += PAGE_SIZE)
 1878                                         invpcid(&d, INVPCID_ADDR);
 1879                         } else {
 1880                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 1881                                 ucr3 = pmap->pm_ucr3 | pcid |
 1882                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 1883                                 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
 1884                         }
 1885                         critical_exit();
 1886                 }
 1887         } else
 1888                 pmap->pm_pcids[cpuid].pm_gen = 0;
 1889 
 1890         CPU_FOREACH(i) {
 1891                 if (cpuid != i)
 1892                         pmap->pm_pcids[i].pm_gen = 0;
 1893         }
 1894         /* See the comment in pmap_invalidate_page_pcid(). */
 1895         atomic_thread_fence_seq_cst();
 1896 }
 1897 
 1898 static void
 1899 pmap_invalidate_range_pcid_invpcid(pmap_t pmap, vm_offset_t sva,
 1900     vm_offset_t eva)
 1901 {
 1902 
 1903         pmap_invalidate_range_pcid(pmap, sva, eva, true);
 1904 }
 1905 
 1906 static void
 1907 pmap_invalidate_range_pcid_noinvpcid(pmap_t pmap, vm_offset_t sva,
 1908     vm_offset_t eva)
 1909 {
 1910 
 1911         pmap_invalidate_range_pcid(pmap, sva, eva, false);
 1912 }
 1913 
 1914 static void
 1915 pmap_invalidate_range_nopcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 1916 {
 1917 }
 1918 
 1919 DEFINE_IFUNC(static, void, pmap_invalidate_range_mode, (pmap_t, vm_offset_t,
 1920     vm_offset_t), static)
 1921 {
 1922 
 1923         if (pmap_pcid_enabled)
 1924                 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid :
 1925                     pmap_invalidate_range_pcid_noinvpcid);
 1926         return (pmap_invalidate_range_nopcid);
 1927 }
 1928 
 1929 void
 1930 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 1931 {
 1932         vm_offset_t addr;
 1933 
 1934         if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
 1935                 pmap_invalidate_all(pmap);
 1936                 return;
 1937         }
 1938 
 1939         if (pmap_type_guest(pmap)) {
 1940                 pmap_invalidate_ept(pmap);
 1941                 return;
 1942         }
 1943 
 1944         KASSERT(pmap->pm_type == PT_X86,
 1945             ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
 1946 
 1947         sched_pin();
 1948         if (pmap == kernel_pmap) {
 1949                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
 1950                         invlpg(addr);
 1951         } else {
 1952                 if (pmap == PCPU_GET(curpmap)) {
 1953                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
 1954                                 invlpg(addr);
 1955                 }
 1956                 pmap_invalidate_range_mode(pmap, sva, eva);
 1957         }
 1958         smp_masked_invlpg_range(pmap_invalidate_cpu_mask(pmap), sva, eva, pmap);
 1959         sched_unpin();
 1960 }
 1961 
 1962 static inline void
 1963 pmap_invalidate_all_pcid(pmap_t pmap, bool invpcid_works1)
 1964 {
 1965         struct invpcid_descr d;
 1966         uint64_t kcr3, ucr3;
 1967         uint32_t pcid;
 1968         u_int cpuid, i;
 1969 
 1970         if (pmap == kernel_pmap) {
 1971                 if (invpcid_works1) {
 1972                         bzero(&d, sizeof(d));
 1973                         invpcid(&d, INVPCID_CTXGLOB);
 1974                 } else {
 1975                         invltlb_glob();
 1976                 }
 1977         } else {
 1978                 cpuid = PCPU_GET(cpuid);
 1979                 if (pmap == PCPU_GET(curpmap)) {
 1980                         critical_enter();
 1981                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 1982                         if (invpcid_works1) {
 1983                                 d.pcid = pcid;
 1984                                 d.pad = 0;
 1985                                 d.addr = 0;
 1986                                 invpcid(&d, INVPCID_CTX);
 1987                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 1988                                         d.pcid |= PMAP_PCID_USER_PT;
 1989                                         invpcid(&d, INVPCID_CTX);
 1990                                 }
 1991                         } else {
 1992                                 kcr3 = pmap->pm_cr3 | pcid;
 1993                                 ucr3 = pmap->pm_ucr3;
 1994                                 if (ucr3 != PMAP_NO_CR3) {
 1995                                         ucr3 |= pcid | PMAP_PCID_USER_PT;
 1996                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
 1997                                 } else {
 1998                                         load_cr3(kcr3);
 1999                                 }
 2000                         }
 2001                         critical_exit();
 2002                 } else
 2003                         pmap->pm_pcids[cpuid].pm_gen = 0;
 2004                 CPU_FOREACH(i) {
 2005                         if (cpuid != i)
 2006                                 pmap->pm_pcids[i].pm_gen = 0;
 2007                 }
 2008         }
 2009         /* See the comment in pmap_invalidate_page_pcid(). */
 2010         atomic_thread_fence_seq_cst();
 2011 }
 2012 
 2013 static void
 2014 pmap_invalidate_all_pcid_invpcid(pmap_t pmap)
 2015 {
 2016 
 2017         pmap_invalidate_all_pcid(pmap, true);
 2018 }
 2019 
 2020 static void
 2021 pmap_invalidate_all_pcid_noinvpcid(pmap_t pmap)
 2022 {
 2023 
 2024         pmap_invalidate_all_pcid(pmap, false);
 2025 }
 2026 
 2027 static void
 2028 pmap_invalidate_all_nopcid(pmap_t pmap)
 2029 {
 2030 
 2031         if (pmap == kernel_pmap)
 2032                 invltlb_glob();
 2033         else if (pmap == PCPU_GET(curpmap))
 2034                 invltlb();
 2035 }
 2036 
 2037 DEFINE_IFUNC(static, void, pmap_invalidate_all_mode, (pmap_t), static)
 2038 {
 2039 
 2040         if (pmap_pcid_enabled)
 2041                 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid :
 2042                     pmap_invalidate_all_pcid_noinvpcid);
 2043         return (pmap_invalidate_all_nopcid);
 2044 }
 2045 
 2046 void
 2047 pmap_invalidate_all(pmap_t pmap)
 2048 {
 2049 
 2050         if (pmap_type_guest(pmap)) {
 2051                 pmap_invalidate_ept(pmap);
 2052                 return;
 2053         }
 2054 
 2055         KASSERT(pmap->pm_type == PT_X86,
 2056             ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
 2057 
 2058         sched_pin();
 2059         pmap_invalidate_all_mode(pmap);
 2060         smp_masked_invltlb(pmap_invalidate_cpu_mask(pmap), pmap);
 2061         sched_unpin();
 2062 }
 2063 
 2064 void
 2065 pmap_invalidate_cache(void)
 2066 {
 2067 
 2068         sched_pin();
 2069         wbinvd();
 2070         smp_cache_flush();
 2071         sched_unpin();
 2072 }
 2073 
 2074 struct pde_action {
 2075         cpuset_t invalidate;    /* processors that invalidate their TLB */
 2076         pmap_t pmap;
 2077         vm_offset_t va;
 2078         pd_entry_t *pde;
 2079         pd_entry_t newpde;
 2080         u_int store;            /* processor that updates the PDE */
 2081 };
 2082 
 2083 static void
 2084 pmap_update_pde_action(void *arg)
 2085 {
 2086         struct pde_action *act = arg;
 2087 
 2088         if (act->store == PCPU_GET(cpuid))
 2089                 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
 2090 }
 2091 
 2092 static void
 2093 pmap_update_pde_teardown(void *arg)
 2094 {
 2095         struct pde_action *act = arg;
 2096 
 2097         if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
 2098                 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
 2099 }
 2100 
 2101 /*
 2102  * Change the page size for the specified virtual address in a way that
 2103  * prevents any possibility of the TLB ever having two entries that map the
 2104  * same virtual address using different page sizes.  This is the recommended
 2105  * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
 2106  * machine check exception for a TLB state that is improperly diagnosed as a
 2107  * hardware error.
 2108  */
 2109 static void
 2110 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
 2111 {
 2112         struct pde_action act;
 2113         cpuset_t active, other_cpus;
 2114         u_int cpuid;
 2115 
 2116         sched_pin();
 2117         cpuid = PCPU_GET(cpuid);
 2118         other_cpus = all_cpus;
 2119         CPU_CLR(cpuid, &other_cpus);
 2120         if (pmap == kernel_pmap || pmap_type_guest(pmap)) 
 2121                 active = all_cpus;
 2122         else {
 2123                 active = pmap->pm_active;
 2124         }
 2125         if (CPU_OVERLAP(&active, &other_cpus)) { 
 2126                 act.store = cpuid;
 2127                 act.invalidate = active;
 2128                 act.va = va;
 2129                 act.pmap = pmap;
 2130                 act.pde = pde;
 2131                 act.newpde = newpde;
 2132                 CPU_SET(cpuid, &active);
 2133                 smp_rendezvous_cpus(active,
 2134                     smp_no_rendezvous_barrier, pmap_update_pde_action,
 2135                     pmap_update_pde_teardown, &act);
 2136         } else {
 2137                 pmap_update_pde_store(pmap, pde, newpde);
 2138                 if (CPU_ISSET(cpuid, &active))
 2139                         pmap_update_pde_invalidate(pmap, va, newpde);
 2140         }
 2141         sched_unpin();
 2142 }
 2143 #else /* !SMP */
 2144 /*
 2145  * Normal, non-SMP, invalidation functions.
 2146  */
 2147 void
 2148 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
 2149 {
 2150         struct invpcid_descr d;
 2151         uint64_t kcr3, ucr3;
 2152         uint32_t pcid;
 2153 
 2154         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2155                 pmap->pm_eptgen++;
 2156                 return;
 2157         }
 2158         KASSERT(pmap->pm_type == PT_X86,
 2159             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
 2160 
 2161         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
 2162                 invlpg(va);
 2163                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
 2164                     pmap->pm_ucr3 != PMAP_NO_CR3) {
 2165                         critical_enter();
 2166                         pcid = pmap->pm_pcids[0].pm_pcid;
 2167                         if (invpcid_works) {
 2168                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 2169                                 d.pad = 0;
 2170                                 d.addr = va;
 2171                                 invpcid(&d, INVPCID_ADDR);
 2172                         } else {
 2173                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 2174                                 ucr3 = pmap->pm_ucr3 | pcid |
 2175                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2176                                 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
 2177                         }
 2178                         critical_exit();
 2179                 }
 2180         } else if (pmap_pcid_enabled)
 2181                 pmap->pm_pcids[0].pm_gen = 0;
 2182 }
 2183 
 2184 void
 2185 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2186 {
 2187         struct invpcid_descr d;
 2188         vm_offset_t addr;
 2189         uint64_t kcr3, ucr3;
 2190 
 2191         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2192                 pmap->pm_eptgen++;
 2193                 return;
 2194         }
 2195         KASSERT(pmap->pm_type == PT_X86,
 2196             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
 2197 
 2198         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
 2199                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
 2200                         invlpg(addr);
 2201                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
 2202                     pmap->pm_ucr3 != PMAP_NO_CR3) {
 2203                         critical_enter();
 2204                         if (invpcid_works) {
 2205                                 d.pcid = pmap->pm_pcids[0].pm_pcid |
 2206                                     PMAP_PCID_USER_PT;
 2207                                 d.pad = 0;
 2208                                 d.addr = sva;
 2209                                 for (; d.addr < eva; d.addr += PAGE_SIZE)
 2210                                         invpcid(&d, INVPCID_ADDR);
 2211                         } else {
 2212                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
 2213                                     pm_pcid | CR3_PCID_SAVE;
 2214                                 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
 2215                                     pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2216                                 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
 2217                         }
 2218                         critical_exit();
 2219                 }
 2220         } else if (pmap_pcid_enabled) {
 2221                 pmap->pm_pcids[0].pm_gen = 0;
 2222         }
 2223 }
 2224 
 2225 void
 2226 pmap_invalidate_all(pmap_t pmap)
 2227 {
 2228         struct invpcid_descr d;
 2229         uint64_t kcr3, ucr3;
 2230 
 2231         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2232                 pmap->pm_eptgen++;
 2233                 return;
 2234         }
 2235         KASSERT(pmap->pm_type == PT_X86,
 2236             ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
 2237 
 2238         if (pmap == kernel_pmap) {
 2239                 if (pmap_pcid_enabled && invpcid_works) {
 2240                         bzero(&d, sizeof(d));
 2241                         invpcid(&d, INVPCID_CTXGLOB);
 2242                 } else {
 2243                         invltlb_glob();
 2244                 }
 2245         } else if (pmap == PCPU_GET(curpmap)) {
 2246                 if (pmap_pcid_enabled) {
 2247                         critical_enter();
 2248                         if (invpcid_works) {
 2249                                 d.pcid = pmap->pm_pcids[0].pm_pcid;
 2250                                 d.pad = 0;
 2251                                 d.addr = 0;
 2252                                 invpcid(&d, INVPCID_CTX);
 2253                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2254                                         d.pcid |= PMAP_PCID_USER_PT;
 2255                                         invpcid(&d, INVPCID_CTX);
 2256                                 }
 2257                         } else {
 2258                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
 2259                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2260                                         ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
 2261                                             0].pm_pcid | PMAP_PCID_USER_PT;
 2262                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
 2263                                 } else
 2264                                         load_cr3(kcr3);
 2265                         }
 2266                         critical_exit();
 2267                 } else {
 2268                         invltlb();
 2269                 }
 2270         } else if (pmap_pcid_enabled) {
 2271                 pmap->pm_pcids[0].pm_gen = 0;
 2272         }
 2273 }
 2274 
 2275 PMAP_INLINE void
 2276 pmap_invalidate_cache(void)
 2277 {
 2278 
 2279         wbinvd();
 2280 }
 2281 
 2282 static void
 2283 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
 2284 {
 2285 
 2286         pmap_update_pde_store(pmap, pde, newpde);
 2287         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
 2288                 pmap_update_pde_invalidate(pmap, va, newpde);
 2289         else
 2290                 pmap->pm_pcids[0].pm_gen = 0;
 2291 }
 2292 #endif /* !SMP */
 2293 
 2294 static void
 2295 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
 2296 {
 2297 
 2298         /*
 2299          * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
 2300          * by a promotion that did not invalidate the 512 4KB page mappings
 2301          * that might exist in the TLB.  Consequently, at this point, the TLB
 2302          * may hold both 4KB and 2MB page mappings for the address range [va,
 2303          * va + NBPDR).  Therefore, the entire range must be invalidated here.
 2304          * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
 2305          * 4KB page mappings for the address range [va, va + NBPDR), and so a
 2306          * single INVLPG suffices to invalidate the 2MB page mapping from the
 2307          * TLB.
 2308          */
 2309         if ((pde & PG_PROMOTED) != 0)
 2310                 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
 2311         else
 2312                 pmap_invalidate_page(pmap, va);
 2313 }
 2314 
 2315 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
 2316     (vm_offset_t sva, vm_offset_t eva), static)
 2317 {
 2318 
 2319         if ((cpu_feature & CPUID_SS) != 0)
 2320                 return (pmap_invalidate_cache_range_selfsnoop);
 2321         if ((cpu_feature & CPUID_CLFSH) != 0)
 2322                 return (pmap_force_invalidate_cache_range);
 2323         return (pmap_invalidate_cache_range_all);
 2324 }
 2325 
 2326 #define PMAP_CLFLUSH_THRESHOLD   (2 * 1024 * 1024)
 2327 
 2328 static void
 2329 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
 2330 {
 2331 
 2332         KASSERT((sva & PAGE_MASK) == 0,
 2333             ("pmap_invalidate_cache_range: sva not page-aligned"));
 2334         KASSERT((eva & PAGE_MASK) == 0,
 2335             ("pmap_invalidate_cache_range: eva not page-aligned"));
 2336 }
 2337 
 2338 static void
 2339 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
 2340 {
 2341 
 2342         pmap_invalidate_cache_range_check_align(sva, eva);
 2343 }
 2344 
 2345 void
 2346 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
 2347 {
 2348 
 2349         sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
 2350 
 2351         /*
 2352          * XXX: Some CPUs fault, hang, or trash the local APIC
 2353          * registers if we use CLFLUSH on the local APIC range.  The
 2354          * local APIC is always uncached, so we don't need to flush
 2355          * for that range anyway.
 2356          */
 2357         if (pmap_kextract(sva) == lapic_paddr)
 2358                 return;
 2359 
 2360         if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
 2361                 /*
 2362                  * Do per-cache line flush.  Use the sfence
 2363                  * instruction to insure that previous stores are
 2364                  * included in the write-back.  The processor
 2365                  * propagates flush to other processors in the cache
 2366                  * coherence domain.
 2367                  */
 2368                 sfence();
 2369                 for (; sva < eva; sva += cpu_clflush_line_size)
 2370                         clflushopt(sva);
 2371                 sfence();
 2372         } else {
 2373                 /*
 2374                  * Writes are ordered by CLFLUSH on Intel CPUs.
 2375                  */
 2376                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2377                         mfence();
 2378                 for (; sva < eva; sva += cpu_clflush_line_size)
 2379                         clflush(sva);
 2380                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2381                         mfence();
 2382         }
 2383 }
 2384 
 2385 static void
 2386 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
 2387 {
 2388 
 2389         pmap_invalidate_cache_range_check_align(sva, eva);
 2390         pmap_invalidate_cache();
 2391 }
 2392 
 2393 /*
 2394  * Remove the specified set of pages from the data and instruction caches.
 2395  *
 2396  * In contrast to pmap_invalidate_cache_range(), this function does not
 2397  * rely on the CPU's self-snoop feature, because it is intended for use
 2398  * when moving pages into a different cache domain.
 2399  */
 2400 void
 2401 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
 2402 {
 2403         vm_offset_t daddr, eva;
 2404         int i;
 2405         bool useclflushopt;
 2406 
 2407         useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
 2408         if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
 2409             ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
 2410                 pmap_invalidate_cache();
 2411         else {
 2412                 if (useclflushopt)
 2413                         sfence();
 2414                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2415                         mfence();
 2416                 for (i = 0; i < count; i++) {
 2417                         daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
 2418                         eva = daddr + PAGE_SIZE;
 2419                         for (; daddr < eva; daddr += cpu_clflush_line_size) {
 2420                                 if (useclflushopt)
 2421                                         clflushopt(daddr);
 2422                                 else
 2423                                         clflush(daddr);
 2424                         }
 2425                 }
 2426                 if (useclflushopt)
 2427                         sfence();
 2428                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2429                         mfence();
 2430         }
 2431 }
 2432 
 2433 void
 2434 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
 2435 {
 2436 
 2437         pmap_invalidate_cache_range_check_align(sva, eva);
 2438 
 2439         if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
 2440                 pmap_force_invalidate_cache_range(sva, eva);
 2441                 return;
 2442         }
 2443 
 2444         /* See comment in pmap_force_invalidate_cache_range(). */
 2445         if (pmap_kextract(sva) == lapic_paddr)
 2446                 return;
 2447 
 2448         sfence();
 2449         for (; sva < eva; sva += cpu_clflush_line_size)
 2450                 clwb(sva);
 2451         sfence();
 2452 }
 2453 
 2454 void
 2455 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
 2456 {
 2457         pt_entry_t *pte;
 2458         vm_offset_t vaddr;
 2459         int error, pte_bits;
 2460 
 2461         KASSERT((spa & PAGE_MASK) == 0,
 2462             ("pmap_flush_cache_phys_range: spa not page-aligned"));
 2463         KASSERT((epa & PAGE_MASK) == 0,
 2464             ("pmap_flush_cache_phys_range: epa not page-aligned"));
 2465 
 2466         if (spa < dmaplimit) {
 2467                 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
 2468                     dmaplimit, epa)));
 2469                 if (dmaplimit >= epa)
 2470                         return;
 2471                 spa = dmaplimit;
 2472         }
 2473 
 2474         pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
 2475             X86_PG_V;
 2476         error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
 2477             &vaddr);
 2478         KASSERT(error == 0, ("vmem_alloc failed: %d", error));
 2479         pte = vtopte(vaddr);
 2480         for (; spa < epa; spa += PAGE_SIZE) {
 2481                 sched_pin();
 2482                 pte_store(pte, spa | pte_bits);
 2483                 invlpg(vaddr);
 2484                 /* XXXKIB sfences inside flush_cache_range are excessive */
 2485                 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
 2486                 sched_unpin();
 2487         }
 2488         vmem_free(kernel_arena, vaddr, PAGE_SIZE);
 2489 }
 2490 
 2491 /*
 2492  *      Routine:        pmap_extract
 2493  *      Function:
 2494  *              Extract the physical page address associated
 2495  *              with the given map/virtual_address pair.
 2496  */
 2497 vm_paddr_t 
 2498 pmap_extract(pmap_t pmap, vm_offset_t va)
 2499 {
 2500         pdp_entry_t *pdpe;
 2501         pd_entry_t *pde;
 2502         pt_entry_t *pte, PG_V;
 2503         vm_paddr_t pa;
 2504 
 2505         pa = 0;
 2506         PG_V = pmap_valid_bit(pmap);
 2507         PMAP_LOCK(pmap);
 2508         pdpe = pmap_pdpe(pmap, va);
 2509         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
 2510                 if ((*pdpe & PG_PS) != 0)
 2511                         pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
 2512                 else {
 2513                         pde = pmap_pdpe_to_pde(pdpe, va);
 2514                         if ((*pde & PG_V) != 0) {
 2515                                 if ((*pde & PG_PS) != 0) {
 2516                                         pa = (*pde & PG_PS_FRAME) |
 2517                                             (va & PDRMASK);
 2518                                 } else {
 2519                                         pte = pmap_pde_to_pte(pde, va);
 2520                                         pa = (*pte & PG_FRAME) |
 2521                                             (va & PAGE_MASK);
 2522                                 }
 2523                         }
 2524                 }
 2525         }
 2526         PMAP_UNLOCK(pmap);
 2527         return (pa);
 2528 }
 2529 
 2530 /*
 2531  *      Routine:        pmap_extract_and_hold
 2532  *      Function:
 2533  *              Atomically extract and hold the physical page
 2534  *              with the given pmap and virtual address pair
 2535  *              if that mapping permits the given protection.
 2536  */
 2537 vm_page_t
 2538 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
 2539 {
 2540         pd_entry_t pde, *pdep;
 2541         pt_entry_t pte, PG_RW, PG_V;
 2542         vm_paddr_t pa;
 2543         vm_page_t m;
 2544 
 2545         pa = 0;
 2546         m = NULL;
 2547         PG_RW = pmap_rw_bit(pmap);
 2548         PG_V = pmap_valid_bit(pmap);
 2549         PMAP_LOCK(pmap);
 2550 retry:
 2551         pdep = pmap_pde(pmap, va);
 2552         if (pdep != NULL && (pde = *pdep)) {
 2553                 if (pde & PG_PS) {
 2554                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
 2555                                 if (vm_page_pa_tryrelock(pmap, (pde &
 2556                                     PG_PS_FRAME) | (va & PDRMASK), &pa))
 2557                                         goto retry;
 2558                                 m = PHYS_TO_VM_PAGE(pa);
 2559                         }
 2560                 } else {
 2561                         pte = *pmap_pde_to_pte(pdep, va);
 2562                         if ((pte & PG_V) &&
 2563                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
 2564                                 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
 2565                                     &pa))
 2566                                         goto retry;
 2567                                 m = PHYS_TO_VM_PAGE(pa);
 2568                         }
 2569                 }
 2570                 if (m != NULL)
 2571                         vm_page_hold(m);
 2572         }
 2573         PA_UNLOCK_COND(pa);
 2574         PMAP_UNLOCK(pmap);
 2575         return (m);
 2576 }
 2577 
 2578 vm_paddr_t
 2579 pmap_kextract(vm_offset_t va)
 2580 {
 2581         pd_entry_t pde;
 2582         vm_paddr_t pa;
 2583 
 2584         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
 2585                 pa = DMAP_TO_PHYS(va);
 2586         } else {
 2587                 pde = *vtopde(va);
 2588                 if (pde & PG_PS) {
 2589                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
 2590                 } else {
 2591                         /*
 2592                          * Beware of a concurrent promotion that changes the
 2593                          * PDE at this point!  For example, vtopte() must not
 2594                          * be used to access the PTE because it would use the
 2595                          * new PDE.  It is, however, safe to use the old PDE
 2596                          * because the page table page is preserved by the
 2597                          * promotion.
 2598                          */
 2599                         pa = *pmap_pde_to_pte(&pde, va);
 2600                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
 2601                 }
 2602         }
 2603         return (pa);
 2604 }
 2605 
 2606 /***************************************************
 2607  * Low level mapping routines.....
 2608  ***************************************************/
 2609 
 2610 /*
 2611  * Add a wired page to the kva.
 2612  * Note: not SMP coherent.
 2613  */
 2614 PMAP_INLINE void 
 2615 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 2616 {
 2617         pt_entry_t *pte;
 2618 
 2619         pte = vtopte(va);
 2620         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
 2621 }
 2622 
 2623 static __inline void
 2624 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
 2625 {
 2626         pt_entry_t *pte;
 2627         int cache_bits;
 2628 
 2629         pte = vtopte(va);
 2630         cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
 2631         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
 2632 }
 2633 
 2634 /*
 2635  * Remove a page from the kernel pagetables.
 2636  * Note: not SMP coherent.
 2637  */
 2638 PMAP_INLINE void
 2639 pmap_kremove(vm_offset_t va)
 2640 {
 2641         pt_entry_t *pte;
 2642 
 2643         pte = vtopte(va);
 2644         pte_clear(pte);
 2645 }
 2646 
 2647 /*
 2648  *      Used to map a range of physical addresses into kernel
 2649  *      virtual address space.
 2650  *
 2651  *      The value passed in '*virt' is a suggested virtual address for
 2652  *      the mapping. Architectures which can support a direct-mapped
 2653  *      physical to virtual region can return the appropriate address
 2654  *      within that region, leaving '*virt' unchanged. Other
 2655  *      architectures should map the pages starting at '*virt' and
 2656  *      update '*virt' with the first usable address after the mapped
 2657  *      region.
 2658  */
 2659 vm_offset_t
 2660 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
 2661 {
 2662         return PHYS_TO_DMAP(start);
 2663 }
 2664 
 2665 
 2666 /*
 2667  * Add a list of wired pages to the kva
 2668  * this routine is only used for temporary
 2669  * kernel mappings that do not need to have
 2670  * page modification or references recorded.
 2671  * Note that old mappings are simply written
 2672  * over.  The page *must* be wired.
 2673  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 2674  */
 2675 void
 2676 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
 2677 {
 2678         pt_entry_t *endpte, oldpte, pa, *pte;
 2679         vm_page_t m;
 2680         int cache_bits;
 2681 
 2682         oldpte = 0;
 2683         pte = vtopte(sva);
 2684         endpte = pte + count;
 2685         while (pte < endpte) {
 2686                 m = *ma++;
 2687                 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
 2688                 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
 2689                 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
 2690                         oldpte |= *pte;
 2691                         pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
 2692                 }
 2693                 pte++;
 2694         }
 2695         if (__predict_false((oldpte & X86_PG_V) != 0))
 2696                 pmap_invalidate_range(kernel_pmap, sva, sva + count *
 2697                     PAGE_SIZE);
 2698 }
 2699 
 2700 /*
 2701  * This routine tears out page mappings from the
 2702  * kernel -- it is meant only for temporary mappings.
 2703  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 2704  */
 2705 void
 2706 pmap_qremove(vm_offset_t sva, int count)
 2707 {
 2708         vm_offset_t va;
 2709 
 2710         va = sva;
 2711         while (count-- > 0) {
 2712                 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
 2713                 pmap_kremove(va);
 2714                 va += PAGE_SIZE;
 2715         }
 2716         pmap_invalidate_range(kernel_pmap, sva, va);
 2717 }
 2718 
 2719 /***************************************************
 2720  * Page table page management routines.....
 2721  ***************************************************/
 2722 /*
 2723  * Schedule the specified unused page table page to be freed.  Specifically,
 2724  * add the page to the specified list of pages that will be released to the
 2725  * physical memory manager after the TLB has been updated.
 2726  */
 2727 static __inline void
 2728 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
 2729     boolean_t set_PG_ZERO)
 2730 {
 2731 
 2732         if (set_PG_ZERO)
 2733                 m->flags |= PG_ZERO;
 2734         else
 2735                 m->flags &= ~PG_ZERO;
 2736         SLIST_INSERT_HEAD(free, m, plinks.s.ss);
 2737 }
 2738         
 2739 /*
 2740  * Inserts the specified page table page into the specified pmap's collection
 2741  * of idle page table pages.  Each of a pmap's page table pages is responsible
 2742  * for mapping a distinct range of virtual addresses.  The pmap's collection is
 2743  * ordered by this virtual address range.
 2744  */
 2745 static __inline int
 2746 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
 2747 {
 2748 
 2749         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2750         return (vm_radix_insert(&pmap->pm_root, mpte));
 2751 }
 2752 
 2753 /*
 2754  * Removes the page table page mapping the specified virtual address from the
 2755  * specified pmap's collection of idle page table pages, and returns it.
 2756  * Otherwise, returns NULL if there is no page table page corresponding to the
 2757  * specified virtual address.
 2758  */
 2759 static __inline vm_page_t
 2760 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
 2761 {
 2762 
 2763         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2764         return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
 2765 }
 2766 
 2767 /*
 2768  * Decrements a page table page's wire count, which is used to record the
 2769  * number of valid page table entries within the page.  If the wire count
 2770  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
 2771  * page table page was unmapped and FALSE otherwise.
 2772  */
 2773 static inline boolean_t
 2774 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
 2775 {
 2776 
 2777         --m->wire_count;
 2778         if (m->wire_count == 0) {
 2779                 _pmap_unwire_ptp(pmap, va, m, free);
 2780                 return (TRUE);
 2781         } else
 2782                 return (FALSE);
 2783 }
 2784 
 2785 static void
 2786 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
 2787 {
 2788 
 2789         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2790         /*
 2791          * unmap the page table page
 2792          */
 2793         if (m->pindex >= (NUPDE + NUPDPE)) {
 2794                 /* PDP page */
 2795                 pml4_entry_t *pml4;
 2796                 pml4 = pmap_pml4e(pmap, va);
 2797                 *pml4 = 0;
 2798                 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
 2799                         pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
 2800                         *pml4 = 0;
 2801                 }
 2802         } else if (m->pindex >= NUPDE) {
 2803                 /* PD page */
 2804                 pdp_entry_t *pdp;
 2805                 pdp = pmap_pdpe(pmap, va);
 2806                 *pdp = 0;
 2807         } else {
 2808                 /* PTE page */
 2809                 pd_entry_t *pd;
 2810                 pd = pmap_pde(pmap, va);
 2811                 *pd = 0;
 2812         }
 2813         pmap_resident_count_dec(pmap, 1);
 2814         if (m->pindex < NUPDE) {
 2815                 /* We just released a PT, unhold the matching PD */
 2816                 vm_page_t pdpg;
 2817 
 2818                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
 2819                 pmap_unwire_ptp(pmap, va, pdpg, free);
 2820         }
 2821         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
 2822                 /* We just released a PD, unhold the matching PDP */
 2823                 vm_page_t pdppg;
 2824 
 2825                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
 2826                 pmap_unwire_ptp(pmap, va, pdppg, free);
 2827         }
 2828 
 2829         /* 
 2830          * Put page on a list so that it is released after
 2831          * *ALL* TLB shootdown is done
 2832          */
 2833         pmap_add_delayed_free_list(m, free, TRUE);
 2834 }
 2835 
 2836 /*
 2837  * After removing a page table entry, this routine is used to
 2838  * conditionally free the page, and manage the hold/wire counts.
 2839  */
 2840 static int
 2841 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
 2842     struct spglist *free)
 2843 {
 2844         vm_page_t mpte;
 2845 
 2846         if (va >= VM_MAXUSER_ADDRESS)
 2847                 return (0);
 2848         KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
 2849         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
 2850         return (pmap_unwire_ptp(pmap, va, mpte, free));
 2851 }
 2852 
 2853 void
 2854 pmap_pinit0(pmap_t pmap)
 2855 {
 2856         struct proc *p;
 2857         int i;
 2858 
 2859         PMAP_LOCK_INIT(pmap);
 2860         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
 2861         pmap->pm_pml4u = NULL;
 2862         pmap->pm_cr3 = KPML4phys;
 2863         /* hack to keep pmap_pti_pcid_invalidate() alive */
 2864         pmap->pm_ucr3 = PMAP_NO_CR3;
 2865         pmap->pm_root.rt_root = 0;
 2866         CPU_ZERO(&pmap->pm_active);
 2867         TAILQ_INIT(&pmap->pm_pvchunk);
 2868         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 2869         pmap->pm_flags = pmap_flags;
 2870         CPU_FOREACH(i) {
 2871                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
 2872                 pmap->pm_pcids[i].pm_gen = 1;
 2873         }
 2874         pmap_activate_boot(pmap);
 2875         if (pti) {
 2876                 p = curproc;
 2877                 PROC_LOCK(p);
 2878                 p->p_md.md_flags |= P_MD_KPTI;
 2879                 PROC_UNLOCK(p);
 2880         }
 2881 
 2882         if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
 2883                 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
 2884                     sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
 2885                     UMA_ALIGN_PTR, 0);
 2886         }
 2887 }
 2888 
 2889 void
 2890 pmap_pinit_pml4(vm_page_t pml4pg)
 2891 {
 2892         pml4_entry_t *pm_pml4;
 2893         int i;
 2894 
 2895         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
 2896 
 2897         /* Wire in kernel global address entries. */
 2898         for (i = 0; i < NKPML4E; i++) {
 2899                 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
 2900                     X86_PG_V;
 2901         }
 2902         for (i = 0; i < ndmpdpphys; i++) {
 2903                 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
 2904                     X86_PG_V;
 2905         }
 2906 
 2907         /* install self-referential address mapping entry(s) */
 2908         pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
 2909             X86_PG_A | X86_PG_M;
 2910 
 2911         /* install large map entries if configured */
 2912         for (i = 0; i < lm_ents; i++)
 2913                 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pml4[LMSPML4I + i];
 2914 }
 2915 
 2916 static void
 2917 pmap_pinit_pml4_pti(vm_page_t pml4pg)
 2918 {
 2919         pml4_entry_t *pm_pml4;
 2920         int i;
 2921 
 2922         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
 2923         for (i = 0; i < NPML4EPG; i++)
 2924                 pm_pml4[i] = pti_pml4[i];
 2925 }
 2926 
 2927 /*
 2928  * Initialize a preallocated and zeroed pmap structure,
 2929  * such as one in a vmspace structure.
 2930  */
 2931 int
 2932 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
 2933 {
 2934         vm_page_t pml4pg, pml4pgu;
 2935         vm_paddr_t pml4phys;
 2936         int i;
 2937 
 2938         /*
 2939          * allocate the page directory page
 2940          */
 2941         pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 2942             VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
 2943 
 2944         pml4phys = VM_PAGE_TO_PHYS(pml4pg);
 2945         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
 2946         CPU_FOREACH(i) {
 2947                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
 2948                 pmap->pm_pcids[i].pm_gen = 0;
 2949         }
 2950         pmap->pm_cr3 = PMAP_NO_CR3;     /* initialize to an invalid value */
 2951         pmap->pm_ucr3 = PMAP_NO_CR3;
 2952         pmap->pm_pml4u = NULL;
 2953 
 2954         pmap->pm_type = pm_type;
 2955         if ((pml4pg->flags & PG_ZERO) == 0)
 2956                 pagezero(pmap->pm_pml4);
 2957 
 2958         /*
 2959          * Do not install the host kernel mappings in the nested page
 2960          * tables. These mappings are meaningless in the guest physical
 2961          * address space.
 2962          * Install minimal kernel mappings in PTI case.
 2963          */
 2964         if (pm_type == PT_X86) {
 2965                 pmap->pm_cr3 = pml4phys;
 2966                 pmap_pinit_pml4(pml4pg);
 2967                 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
 2968                         pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
 2969                             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
 2970                         pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
 2971                             VM_PAGE_TO_PHYS(pml4pgu));
 2972                         pmap_pinit_pml4_pti(pml4pgu);
 2973                         pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
 2974                 }
 2975                 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
 2976                         rangeset_init(&pmap->pm_pkru, pkru_dup_range,
 2977                             pkru_free_range, pmap, M_NOWAIT);
 2978                 }
 2979         }
 2980 
 2981         pmap->pm_root.rt_root = 0;
 2982         CPU_ZERO(&pmap->pm_active);
 2983         TAILQ_INIT(&pmap->pm_pvchunk);
 2984         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 2985         pmap->pm_flags = flags;
 2986         pmap->pm_eptgen = 0;
 2987 
 2988         return (1);
 2989 }
 2990 
 2991 int
 2992 pmap_pinit(pmap_t pmap)
 2993 {
 2994 
 2995         return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
 2996 }
 2997 
 2998 /*
 2999  * This routine is called if the desired page table page does not exist.
 3000  *
 3001  * If page table page allocation fails, this routine may sleep before
 3002  * returning NULL.  It sleeps only if a lock pointer was given.
 3003  *
 3004  * Note: If a page allocation fails at page table level two or three,
 3005  * one or two pages may be held during the wait, only to be released
 3006  * afterwards.  This conservative approach is easily argued to avoid
 3007  * race conditions.
 3008  */
 3009 static vm_page_t
 3010 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
 3011 {
 3012         vm_page_t m, pdppg, pdpg;
 3013         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
 3014 
 3015         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3016 
 3017         PG_A = pmap_accessed_bit(pmap);
 3018         PG_M = pmap_modified_bit(pmap);
 3019         PG_V = pmap_valid_bit(pmap);
 3020         PG_RW = pmap_rw_bit(pmap);
 3021 
 3022         /*
 3023          * Allocate a page table page.
 3024          */
 3025         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
 3026             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
 3027                 if (lockp != NULL) {
 3028                         RELEASE_PV_LIST_LOCK(lockp);
 3029                         PMAP_UNLOCK(pmap);
 3030                         PMAP_ASSERT_NOT_IN_DI();
 3031                         vm_wait(NULL);
 3032                         PMAP_LOCK(pmap);
 3033                 }
 3034 
 3035                 /*
 3036                  * Indicate the need to retry.  While waiting, the page table
 3037                  * page may have been allocated.
 3038                  */
 3039                 return (NULL);
 3040         }
 3041         if ((m->flags & PG_ZERO) == 0)
 3042                 pmap_zero_page(m);
 3043 
 3044         /*
 3045          * Map the pagetable page into the process address space, if
 3046          * it isn't already there.
 3047          */
 3048 
 3049         if (ptepindex >= (NUPDE + NUPDPE)) {
 3050                 pml4_entry_t *pml4, *pml4u;
 3051                 vm_pindex_t pml4index;
 3052 
 3053                 /* Wire up a new PDPE page */
 3054                 pml4index = ptepindex - (NUPDE + NUPDPE);
 3055                 pml4 = &pmap->pm_pml4[pml4index];
 3056                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3057                 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
 3058                         /*
 3059                          * PTI: Make all user-space mappings in the
 3060                          * kernel-mode page table no-execute so that
 3061                          * we detect any programming errors that leave
 3062                          * the kernel-mode page table active on return
 3063                          * to user space.
 3064                          */
 3065                         if (pmap->pm_ucr3 != PMAP_NO_CR3)
 3066                                 *pml4 |= pg_nx;
 3067 
 3068                         pml4u = &pmap->pm_pml4u[pml4index];
 3069                         *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
 3070                             PG_A | PG_M;
 3071                 }
 3072 
 3073         } else if (ptepindex >= NUPDE) {
 3074                 vm_pindex_t pml4index;
 3075                 vm_pindex_t pdpindex;
 3076                 pml4_entry_t *pml4;
 3077                 pdp_entry_t *pdp;
 3078 
 3079                 /* Wire up a new PDE page */
 3080                 pdpindex = ptepindex - NUPDE;
 3081                 pml4index = pdpindex >> NPML4EPGSHIFT;
 3082 
 3083                 pml4 = &pmap->pm_pml4[pml4index];
 3084                 if ((*pml4 & PG_V) == 0) {
 3085                         /* Have to allocate a new pdp, recurse */
 3086                         if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
 3087                             lockp) == NULL) {
 3088                                 vm_page_unwire_noq(m);
 3089                                 vm_page_free_zero(m);
 3090                                 return (NULL);
 3091                         }
 3092                 } else {
 3093                         /* Add reference to pdp page */
 3094                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
 3095                         pdppg->wire_count++;
 3096                 }
 3097                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3098 
 3099                 /* Now find the pdp page */
 3100                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3101                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3102 
 3103         } else {
 3104                 vm_pindex_t pml4index;
 3105                 vm_pindex_t pdpindex;
 3106                 pml4_entry_t *pml4;
 3107                 pdp_entry_t *pdp;
 3108                 pd_entry_t *pd;
 3109 
 3110                 /* Wire up a new PTE page */
 3111                 pdpindex = ptepindex >> NPDPEPGSHIFT;
 3112                 pml4index = pdpindex >> NPML4EPGSHIFT;
 3113 
 3114                 /* First, find the pdp and check that its valid. */
 3115                 pml4 = &pmap->pm_pml4[pml4index];
 3116                 if ((*pml4 & PG_V) == 0) {
 3117                         /* Have to allocate a new pd, recurse */
 3118                         if (_pmap_allocpte(pmap, NUPDE + pdpindex,
 3119                             lockp) == NULL) {
 3120                                 vm_page_unwire_noq(m);
 3121                                 vm_page_free_zero(m);
 3122                                 return (NULL);
 3123                         }
 3124                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3125                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3126                 } else {
 3127                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3128                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3129                         if ((*pdp & PG_V) == 0) {
 3130                                 /* Have to allocate a new pd, recurse */
 3131                                 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
 3132                                     lockp) == NULL) {
 3133                                         vm_page_unwire_noq(m);
 3134                                         vm_page_free_zero(m);
 3135                                         return (NULL);
 3136                                 }
 3137                         } else {
 3138                                 /* Add reference to the pd page */
 3139                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
 3140                                 pdpg->wire_count++;
 3141                         }
 3142                 }
 3143                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
 3144 
 3145                 /* Now we know where the page directory page is */
 3146                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
 3147                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3148         }
 3149 
 3150         pmap_resident_count_inc(pmap, 1);
 3151 
 3152         return (m);
 3153 }
 3154 
 3155 static vm_page_t
 3156 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
 3157 {
 3158         vm_pindex_t pdpindex, ptepindex;
 3159         pdp_entry_t *pdpe, PG_V;
 3160         vm_page_t pdpg;
 3161 
 3162         PG_V = pmap_valid_bit(pmap);
 3163 
 3164 retry:
 3165         pdpe = pmap_pdpe(pmap, va);
 3166         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
 3167                 /* Add a reference to the pd page. */
 3168                 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
 3169                 pdpg->wire_count++;
 3170         } else {
 3171                 /* Allocate a pd page. */
 3172                 ptepindex = pmap_pde_pindex(va);
 3173                 pdpindex = ptepindex >> NPDPEPGSHIFT;
 3174                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
 3175                 if (pdpg == NULL && lockp != NULL)
 3176                         goto retry;
 3177         }
 3178         return (pdpg);
 3179 }
 3180 
 3181 static vm_page_t
 3182 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
 3183 {
 3184         vm_pindex_t ptepindex;
 3185         pd_entry_t *pd, PG_V;
 3186         vm_page_t m;
 3187 
 3188         PG_V = pmap_valid_bit(pmap);
 3189 
 3190         /*
 3191          * Calculate pagetable page index
 3192          */
 3193         ptepindex = pmap_pde_pindex(va);
 3194 retry:
 3195         /*
 3196          * Get the page directory entry
 3197          */
 3198         pd = pmap_pde(pmap, va);
 3199 
 3200         /*
 3201          * This supports switching from a 2MB page to a
 3202          * normal 4K page.
 3203          */
 3204         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
 3205                 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
 3206                         /*
 3207                          * Invalidation of the 2MB page mapping may have caused
 3208                          * the deallocation of the underlying PD page.
 3209                          */
 3210                         pd = NULL;
 3211                 }
 3212         }
 3213 
 3214         /*
 3215          * If the page table page is mapped, we just increment the
 3216          * hold count, and activate it.
 3217          */
 3218         if (pd != NULL && (*pd & PG_V) != 0) {
 3219                 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
 3220                 m->wire_count++;
 3221         } else {
 3222                 /*
 3223                  * Here if the pte page isn't mapped, or if it has been
 3224                  * deallocated.
 3225                  */
 3226                 m = _pmap_allocpte(pmap, ptepindex, lockp);
 3227                 if (m == NULL && lockp != NULL)
 3228                         goto retry;
 3229         }
 3230         return (m);
 3231 }
 3232 
 3233 
 3234 /***************************************************
 3235  * Pmap allocation/deallocation routines.
 3236  ***************************************************/
 3237 
 3238 /*
 3239  * Release any resources held by the given physical map.
 3240  * Called when a pmap initialized by pmap_pinit is being released.
 3241  * Should only be called if the map contains no valid mappings.
 3242  */
 3243 void
 3244 pmap_release(pmap_t pmap)
 3245 {
 3246         vm_page_t m;
 3247         int i;
 3248 
 3249         KASSERT(pmap->pm_stats.resident_count == 0,
 3250             ("pmap_release: pmap resident count %ld != 0",
 3251             pmap->pm_stats.resident_count));
 3252         KASSERT(vm_radix_is_empty(&pmap->pm_root),
 3253             ("pmap_release: pmap has reserved page table page(s)"));
 3254         KASSERT(CPU_EMPTY(&pmap->pm_active),
 3255             ("releasing active pmap %p", pmap));
 3256 
 3257         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
 3258 
 3259         for (i = 0; i < NKPML4E; i++)   /* KVA */
 3260                 pmap->pm_pml4[KPML4BASE + i] = 0;
 3261         for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
 3262                 pmap->pm_pml4[DMPML4I + i] = 0;
 3263         pmap->pm_pml4[PML4PML4I] = 0;   /* Recursive Mapping */
 3264         for (i = 0; i < lm_ents; i++)   /* Large Map */
 3265                 pmap->pm_pml4[LMSPML4I + i] = 0;
 3266 
 3267         vm_page_unwire_noq(m);
 3268         vm_page_free_zero(m);
 3269 
 3270         if (pmap->pm_pml4u != NULL) {
 3271                 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
 3272                 vm_page_unwire_noq(m);
 3273                 vm_page_free(m);
 3274         }
 3275         if (pmap->pm_type == PT_X86 &&
 3276             (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
 3277                 rangeset_fini(&pmap->pm_pkru);
 3278 }
 3279 
 3280 static int
 3281 kvm_size(SYSCTL_HANDLER_ARGS)
 3282 {
 3283         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
 3284 
 3285         return sysctl_handle_long(oidp, &ksize, 0, req);
 3286 }
 3287 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
 3288     0, 0, kvm_size, "LU", "Size of KVM");
 3289 
 3290 static int
 3291 kvm_free(SYSCTL_HANDLER_ARGS)
 3292 {
 3293         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
 3294 
 3295         return sysctl_handle_long(oidp, &kfree, 0, req);
 3296 }
 3297 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
 3298     0, 0, kvm_free, "LU", "Amount of KVM free");
 3299 
 3300 /*
 3301  * grow the number of kernel page table entries, if needed
 3302  */
 3303 void
 3304 pmap_growkernel(vm_offset_t addr)
 3305 {
 3306         vm_paddr_t paddr;
 3307         vm_page_t nkpg;
 3308         pd_entry_t *pde, newpdir;
 3309         pdp_entry_t *pdpe;
 3310 
 3311         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
 3312 
 3313         /*
 3314          * Return if "addr" is within the range of kernel page table pages
 3315          * that were preallocated during pmap bootstrap.  Moreover, leave
 3316          * "kernel_vm_end" and the kernel page table as they were.
 3317          *
 3318          * The correctness of this action is based on the following
 3319          * argument: vm_map_insert() allocates contiguous ranges of the
 3320          * kernel virtual address space.  It calls this function if a range
 3321          * ends after "kernel_vm_end".  If the kernel is mapped between
 3322          * "kernel_vm_end" and "addr", then the range cannot begin at
 3323          * "kernel_vm_end".  In fact, its beginning address cannot be less
 3324          * than the kernel.  Thus, there is no immediate need to allocate
 3325          * any new kernel page table pages between "kernel_vm_end" and
 3326          * "KERNBASE".
 3327          */
 3328         if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
 3329                 return;
 3330 
 3331         addr = roundup2(addr, NBPDR);
 3332         if (addr - 1 >= vm_map_max(kernel_map))
 3333                 addr = vm_map_max(kernel_map);
 3334         while (kernel_vm_end < addr) {
 3335                 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
 3336                 if ((*pdpe & X86_PG_V) == 0) {
 3337                         /* We need a new PDP entry */
 3338                         nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
 3339                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
 3340                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
 3341                         if (nkpg == NULL)
 3342                                 panic("pmap_growkernel: no memory to grow kernel");
 3343                         if ((nkpg->flags & PG_ZERO) == 0)
 3344                                 pmap_zero_page(nkpg);
 3345                         paddr = VM_PAGE_TO_PHYS(nkpg);
 3346                         *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
 3347                             X86_PG_A | X86_PG_M);
 3348                         continue; /* try again */
 3349                 }
 3350                 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
 3351                 if ((*pde & X86_PG_V) != 0) {
 3352                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 3353                         if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
 3354                                 kernel_vm_end = vm_map_max(kernel_map);
 3355                                 break;                       
 3356                         }
 3357                         continue;
 3358                 }
 3359 
 3360                 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
 3361                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
 3362                     VM_ALLOC_ZERO);
 3363                 if (nkpg == NULL)
 3364                         panic("pmap_growkernel: no memory to grow kernel");
 3365                 if ((nkpg->flags & PG_ZERO) == 0)
 3366                         pmap_zero_page(nkpg);
 3367                 paddr = VM_PAGE_TO_PHYS(nkpg);
 3368                 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
 3369                 pde_store(pde, newpdir);
 3370 
 3371                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 3372                 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
 3373                         kernel_vm_end = vm_map_max(kernel_map);
 3374                         break;                       
 3375                 }
 3376         }
 3377 }
 3378 
 3379 
 3380 /***************************************************
 3381  * page management routines.
 3382  ***************************************************/
 3383 
 3384 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
 3385 CTASSERT(_NPCM == 3);
 3386 CTASSERT(_NPCPV == 168);
 3387 
 3388 static __inline struct pv_chunk *
 3389 pv_to_chunk(pv_entry_t pv)
 3390 {
 3391 
 3392         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
 3393 }
 3394 
 3395 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
 3396 
 3397 #define PC_FREE0        0xfffffffffffffffful
 3398 #define PC_FREE1        0xfffffffffffffffful
 3399 #define PC_FREE2        0x000000fffffffffful
 3400 
 3401 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
 3402 
 3403 #ifdef PV_STATS
 3404 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
 3405 
 3406 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
 3407         "Current number of pv entry chunks");
 3408 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
 3409         "Current number of pv entry chunks allocated");
 3410 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
 3411         "Current number of pv entry chunks frees");
 3412 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
 3413         "Number of times tried to get a chunk page but failed.");
 3414 
 3415 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
 3416 static int pv_entry_spare;
 3417 
 3418 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
 3419         "Current number of pv entry frees");
 3420 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
 3421         "Current number of pv entry allocs");
 3422 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
 3423         "Current number of pv entries");
 3424 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
 3425         "Current number of spare pv entries");
 3426 #endif
 3427 
 3428 static void
 3429 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
 3430 {
 3431 
 3432         if (pmap == NULL)
 3433                 return;
 3434         pmap_invalidate_all(pmap);
 3435         if (pmap != locked_pmap)
 3436                 PMAP_UNLOCK(pmap);
 3437         if (start_di)
 3438                 pmap_delayed_invl_finished();
 3439 }
 3440 
 3441 /*
 3442  * We are in a serious low memory condition.  Resort to
 3443  * drastic measures to free some pages so we can allocate
 3444  * another pv entry chunk.
 3445  *
 3446  * Returns NULL if PV entries were reclaimed from the specified pmap.
 3447  *
 3448  * We do not, however, unmap 2mpages because subsequent accesses will
 3449  * allocate per-page pv entries until repromotion occurs, thereby
 3450  * exacerbating the shortage of free pv entries.
 3451  */
 3452 static vm_page_t
 3453 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
 3454 {
 3455         struct pv_chunk *pc, *pc_marker, *pc_marker_end;
 3456         struct pv_chunk_header pc_marker_b, pc_marker_end_b;
 3457         struct md_page *pvh;
 3458         pd_entry_t *pde;
 3459         pmap_t next_pmap, pmap;
 3460         pt_entry_t *pte, tpte;
 3461         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
 3462         pv_entry_t pv;
 3463         vm_offset_t va;
 3464         vm_page_t m, m_pc;
 3465         struct spglist free;
 3466         uint64_t inuse;
 3467         int bit, field, freed;
 3468         bool start_di;
 3469         static int active_reclaims = 0;
 3470 
 3471         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
 3472         KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
 3473         pmap = NULL;
 3474         m_pc = NULL;
 3475         PG_G = PG_A = PG_M = PG_RW = 0;
 3476         SLIST_INIT(&free);
 3477         bzero(&pc_marker_b, sizeof(pc_marker_b));
 3478         bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
 3479         pc_marker = (struct pv_chunk *)&pc_marker_b;
 3480         pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
 3481 
 3482         /*
 3483          * A delayed invalidation block should already be active if
 3484          * pmap_advise() or pmap_remove() called this function by way
 3485          * of pmap_demote_pde_locked().
 3486          */
 3487         start_di = pmap_not_in_di();
 3488 
 3489         mtx_lock(&pv_chunks_mutex);
 3490         active_reclaims++;
 3491         TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
 3492         TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
 3493         while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
 3494             SLIST_EMPTY(&free)) {
 3495                 next_pmap = pc->pc_pmap;
 3496                 if (next_pmap == NULL) {
 3497                         /*
 3498                          * The next chunk is a marker.  However, it is
 3499                          * not our marker, so active_reclaims must be
 3500                          * > 1.  Consequently, the next_chunk code
 3501                          * will not rotate the pv_chunks list.
 3502                          */
 3503                         goto next_chunk;
 3504                 }
 3505                 mtx_unlock(&pv_chunks_mutex);
 3506 
 3507                 /*
 3508                  * A pv_chunk can only be removed from the pc_lru list
 3509                  * when both pc_chunks_mutex is owned and the
 3510                  * corresponding pmap is locked.
 3511                  */
 3512                 if (pmap != next_pmap) {
 3513                         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
 3514                             start_di);
 3515                         pmap = next_pmap;
 3516                         /* Avoid deadlock and lock recursion. */
 3517                         if (pmap > locked_pmap) {
 3518                                 RELEASE_PV_LIST_LOCK(lockp);
 3519                                 PMAP_LOCK(pmap);
 3520                                 if (start_di)
 3521                                         pmap_delayed_invl_started();
 3522                                 mtx_lock(&pv_chunks_mutex);
 3523                                 continue;
 3524                         } else if (pmap != locked_pmap) {
 3525                                 if (PMAP_TRYLOCK(pmap)) {
 3526                                         if (start_di)
 3527                                                 pmap_delayed_invl_started();
 3528                                         mtx_lock(&pv_chunks_mutex);
 3529                                         continue;
 3530                                 } else {
 3531                                         pmap = NULL; /* pmap is not locked */
 3532                                         mtx_lock(&pv_chunks_mutex);
 3533                                         pc = TAILQ_NEXT(pc_marker, pc_lru);
 3534                                         if (pc == NULL ||
 3535                                             pc->pc_pmap != next_pmap)
 3536                                                 continue;
 3537                                         goto next_chunk;
 3538                                 }
 3539                         } else if (start_di)
 3540                                 pmap_delayed_invl_started();
 3541                         PG_G = pmap_global_bit(pmap);
 3542                         PG_A = pmap_accessed_bit(pmap);
 3543                         PG_M = pmap_modified_bit(pmap);
 3544                         PG_RW = pmap_rw_bit(pmap);
 3545                 }
 3546 
 3547                 /*
 3548                  * Destroy every non-wired, 4 KB page mapping in the chunk.
 3549                  */
 3550                 freed = 0;
 3551                 for (field = 0; field < _NPCM; field++) {
 3552                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
 3553                             inuse != 0; inuse &= ~(1UL << bit)) {
 3554                                 bit = bsfq(inuse);
 3555                                 pv = &pc->pc_pventry[field * 64 + bit];
 3556                                 va = pv->pv_va;
 3557                                 pde = pmap_pde(pmap, va);
 3558                                 if ((*pde & PG_PS) != 0)
 3559                                         continue;
 3560                                 pte = pmap_pde_to_pte(pde, va);
 3561                                 if ((*pte & PG_W) != 0)
 3562                                         continue;
 3563                                 tpte = pte_load_clear(pte);
 3564                                 if ((tpte & PG_G) != 0)
 3565                                         pmap_invalidate_page(pmap, va);
 3566                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
 3567                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 3568                                         vm_page_dirty(m);
 3569                                 if ((tpte & PG_A) != 0)
 3570                                         vm_page_aflag_set(m, PGA_REFERENCED);
 3571                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 3572                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 3573                                 m->md.pv_gen++;
 3574                                 if (TAILQ_EMPTY(&m->md.pv_list) &&
 3575                                     (m->flags & PG_FICTITIOUS) == 0) {
 3576                                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 3577                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
 3578                                                 vm_page_aflag_clear(m,
 3579                                                     PGA_WRITEABLE);
 3580                                         }
 3581                                 }
 3582                                 pmap_delayed_invl_page(m);
 3583                                 pc->pc_map[field] |= 1UL << bit;
 3584                                 pmap_unuse_pt(pmap, va, *pde, &free);
 3585                                 freed++;
 3586                         }
 3587                 }
 3588                 if (freed == 0) {
 3589                         mtx_lock(&pv_chunks_mutex);
 3590                         goto next_chunk;
 3591                 }
 3592                 /* Every freed mapping is for a 4 KB page. */
 3593                 pmap_resident_count_dec(pmap, freed);
 3594                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
 3595                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
 3596                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
 3597                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3598                 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
 3599                     pc->pc_map[2] == PC_FREE2) {
 3600                         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
 3601                         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
 3602                         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
 3603                         /* Entire chunk is free; return it. */
 3604                         m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
 3605                         dump_drop_page(m_pc->phys_addr);
 3606                         mtx_lock(&pv_chunks_mutex);
 3607                         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 3608                         break;
 3609                 }
 3610                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 3611                 mtx_lock(&pv_chunks_mutex);
 3612                 /* One freed pv entry in locked_pmap is sufficient. */
 3613                 if (pmap == locked_pmap)
 3614                         break;
 3615 next_chunk:
 3616                 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
 3617                 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
 3618                 if (active_reclaims == 1 && pmap != NULL) {
 3619                         /*
 3620                          * Rotate the pv chunks list so that we do not
 3621                          * scan the same pv chunks that could not be
 3622                          * freed (because they contained a wired
 3623                          * and/or superpage mapping) on every
 3624                          * invocation of reclaim_pv_chunk().
 3625                          */
 3626                         while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
 3627                                 MPASS(pc->pc_pmap != NULL);
 3628                                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 3629                                 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
 3630                         }
 3631                 }
 3632         }
 3633         TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
 3634         TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
 3635         active_reclaims--;
 3636         mtx_unlock(&pv_chunks_mutex);
 3637         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
 3638         if (m_pc == NULL && !SLIST_EMPTY(&free)) {
 3639                 m_pc = SLIST_FIRST(&free);
 3640                 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
 3641                 /* Recycle a freed page table page. */
 3642                 m_pc->wire_count = 1;
 3643         }
 3644         vm_page_free_pages_toq(&free, true);
 3645         return (m_pc);
 3646 }
 3647 
 3648 /*
 3649  * free the pv_entry back to the free list
 3650  */
 3651 static void
 3652 free_pv_entry(pmap_t pmap, pv_entry_t pv)
 3653 {
 3654         struct pv_chunk *pc;
 3655         int idx, field, bit;
 3656 
 3657         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3658         PV_STAT(atomic_add_long(&pv_entry_frees, 1));
 3659         PV_STAT(atomic_add_int(&pv_entry_spare, 1));
 3660         PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
 3661         pc = pv_to_chunk(pv);
 3662         idx = pv - &pc->pc_pventry[0];
 3663         field = idx / 64;
 3664         bit = idx % 64;
 3665         pc->pc_map[field] |= 1ul << bit;
 3666         if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
 3667             pc->pc_map[2] != PC_FREE2) {
 3668                 /* 98% of the time, pc is already at the head of the list. */
 3669                 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
 3670                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3671                         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 3672                 }
 3673                 return;
 3674         }
 3675         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3676         free_pv_chunk(pc);
 3677 }
 3678 
 3679 static void
 3680 free_pv_chunk(struct pv_chunk *pc)
 3681 {
 3682         vm_page_t m;
 3683 
 3684         mtx_lock(&pv_chunks_mutex);
 3685         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 3686         mtx_unlock(&pv_chunks_mutex);
 3687         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
 3688         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
 3689         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
 3690         /* entire chunk is free, return it */
 3691         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
 3692         dump_drop_page(m->phys_addr);
 3693         vm_page_unwire(m, PQ_NONE);
 3694         vm_page_free(m);
 3695 }
 3696 
 3697 /*
 3698  * Returns a new PV entry, allocating a new PV chunk from the system when
 3699  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
 3700  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
 3701  * returned.
 3702  *
 3703  * The given PV list lock may be released.
 3704  */
 3705 static pv_entry_t
 3706 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
 3707 {
 3708         int bit, field;
 3709         pv_entry_t pv;
 3710         struct pv_chunk *pc;
 3711         vm_page_t m;
 3712 
 3713         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3714         PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
 3715 retry:
 3716         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 3717         if (pc != NULL) {
 3718                 for (field = 0; field < _NPCM; field++) {
 3719                         if (pc->pc_map[field]) {
 3720                                 bit = bsfq(pc->pc_map[field]);
 3721                                 break;
 3722                         }
 3723                 }
 3724                 if (field < _NPCM) {
 3725                         pv = &pc->pc_pventry[field * 64 + bit];
 3726                         pc->pc_map[field] &= ~(1ul << bit);
 3727                         /* If this was the last item, move it to tail */
 3728                         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
 3729                             pc->pc_map[2] == 0) {
 3730                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3731                                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
 3732                                     pc_list);
 3733                         }
 3734                         PV_STAT(atomic_add_long(&pv_entry_count, 1));
 3735                         PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
 3736                         return (pv);
 3737                 }
 3738         }
 3739         /* No free items, allocate another chunk */
 3740         m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 3741             VM_ALLOC_WIRED);
 3742         if (m == NULL) {
 3743                 if (lockp == NULL) {
 3744                         PV_STAT(pc_chunk_tryfail++);
 3745                         return (NULL);
 3746                 }
 3747                 m = reclaim_pv_chunk(pmap, lockp);
 3748                 if (m == NULL)
 3749                         goto retry;
 3750         }
 3751         PV_STAT(atomic_add_int(&pc_chunk_count, 1));
 3752         PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
 3753         dump_add_page(m->phys_addr);
 3754         pc = (void *)PHYS_TO_DMAP(m->phys_addr);
 3755         pc->pc_pmap = pmap;
 3756         pc->pc_map[0] = PC_FREE0 & ~1ul;        /* preallocated bit 0 */
 3757         pc->pc_map[1] = PC_FREE1;
 3758         pc->pc_map[2] = PC_FREE2;
 3759         mtx_lock(&pv_chunks_mutex);
 3760         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
 3761         mtx_unlock(&pv_chunks_mutex);
 3762         pv = &pc->pc_pventry[0];
 3763         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 3764         PV_STAT(atomic_add_long(&pv_entry_count, 1));
 3765         PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
 3766         return (pv);
 3767 }
 3768 
 3769 /*
 3770  * Returns the number of one bits within the given PV chunk map.
 3771  *
 3772  * The erratas for Intel processors state that "POPCNT Instruction May
 3773  * Take Longer to Execute Than Expected".  It is believed that the
 3774  * issue is the spurious dependency on the destination register.
 3775  * Provide a hint to the register rename logic that the destination
 3776  * value is overwritten, by clearing it, as suggested in the
 3777  * optimization manual.  It should be cheap for unaffected processors
 3778  * as well.
 3779  *
 3780  * Reference numbers for erratas are
 3781  * 4th Gen Core: HSD146
 3782  * 5th Gen Core: BDM85
 3783  * 6th Gen Core: SKL029
 3784  */
 3785 static int
 3786 popcnt_pc_map_pq(uint64_t *map)
 3787 {
 3788         u_long result, tmp;
 3789 
 3790         __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
 3791             "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
 3792             "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
 3793             : "=&r" (result), "=&r" (tmp)
 3794             : "m" (map[0]), "m" (map[1]), "m" (map[2]));
 3795         return (result);
 3796 }
 3797 
 3798 /*
 3799  * Ensure that the number of spare PV entries in the specified pmap meets or
 3800  * exceeds the given count, "needed".
 3801  *
 3802  * The given PV list lock may be released.
 3803  */
 3804 static void
 3805 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
 3806 {
 3807         struct pch new_tail;
 3808         struct pv_chunk *pc;
 3809         vm_page_t m;
 3810         int avail, free;
 3811         bool reclaimed;
 3812 
 3813         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3814         KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
 3815 
 3816         /*
 3817          * Newly allocated PV chunks must be stored in a private list until
 3818          * the required number of PV chunks have been allocated.  Otherwise,
 3819          * reclaim_pv_chunk() could recycle one of these chunks.  In
 3820          * contrast, these chunks must be added to the pmap upon allocation.
 3821          */
 3822         TAILQ_INIT(&new_tail);
 3823 retry:
 3824         avail = 0;
 3825         TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
 3826 #ifndef __POPCNT__
 3827                 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
 3828                         bit_count((bitstr_t *)pc->pc_map, 0,
 3829                             sizeof(pc->pc_map) * NBBY, &free);
 3830                 else
 3831 #endif
 3832                 free = popcnt_pc_map_pq(pc->pc_map);
 3833                 if (free == 0)
 3834                         break;
 3835                 avail += free;
 3836                 if (avail >= needed)
 3837                         break;
 3838         }
 3839         for (reclaimed = false; avail < needed; avail += _NPCPV) {
 3840                 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 3841                     VM_ALLOC_WIRED);
 3842                 if (m == NULL) {
 3843                         m = reclaim_pv_chunk(pmap, lockp);
 3844                         if (m == NULL)
 3845                                 goto retry;
 3846                         reclaimed = true;
 3847                 }
 3848                 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
 3849                 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
 3850                 dump_add_page(m->phys_addr);
 3851                 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
 3852                 pc->pc_pmap = pmap;
 3853                 pc->pc_map[0] = PC_FREE0;
 3854                 pc->pc_map[1] = PC_FREE1;
 3855                 pc->pc_map[2] = PC_FREE2;
 3856                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 3857                 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
 3858                 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
 3859 
 3860                 /*
 3861                  * The reclaim might have freed a chunk from the current pmap.
 3862                  * If that chunk contained available entries, we need to
 3863                  * re-count the number of available entries.
 3864                  */
 3865                 if (reclaimed)
 3866                         goto retry;
 3867         }
 3868         if (!TAILQ_EMPTY(&new_tail)) {
 3869                 mtx_lock(&pv_chunks_mutex);
 3870                 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
 3871                 mtx_unlock(&pv_chunks_mutex);
 3872         }
 3873 }
 3874 
 3875 /*
 3876  * First find and then remove the pv entry for the specified pmap and virtual
 3877  * address from the specified pv list.  Returns the pv entry if found and NULL
 3878  * otherwise.  This operation can be performed on pv lists for either 4KB or
 3879  * 2MB page mappings.
 3880  */
 3881 static __inline pv_entry_t
 3882 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 3883 {
 3884         pv_entry_t pv;
 3885 
 3886         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
 3887                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
 3888                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
 3889                         pvh->pv_gen++;
 3890                         break;
 3891                 }
 3892         }
 3893         return (pv);
 3894 }
 3895 
 3896 /*
 3897  * After demotion from a 2MB page mapping to 512 4KB page mappings,
 3898  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
 3899  * entries for each of the 4KB page mappings.
 3900  */
 3901 static void
 3902 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 3903     struct rwlock **lockp)
 3904 {
 3905         struct md_page *pvh;
 3906         struct pv_chunk *pc;
 3907         pv_entry_t pv;
 3908         vm_offset_t va_last;
 3909         vm_page_t m;
 3910         int bit, field;
 3911 
 3912         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3913         KASSERT((pa & PDRMASK) == 0,
 3914             ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
 3915         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 3916 
 3917         /*
 3918          * Transfer the 2mpage's pv entry for this mapping to the first
 3919          * page's pv list.  Once this transfer begins, the pv list lock
 3920          * must not be released until the last pv entry is reinstantiated.
 3921          */
 3922         pvh = pa_to_pvh(pa);
 3923         va = trunc_2mpage(va);
 3924         pv = pmap_pvh_remove(pvh, pmap, va);
 3925         KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
 3926         m = PHYS_TO_VM_PAGE(pa);
 3927         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 3928         m->md.pv_gen++;
 3929         /* Instantiate the remaining NPTEPG - 1 pv entries. */
 3930         PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
 3931         va_last = va + NBPDR - PAGE_SIZE;
 3932         for (;;) {
 3933                 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 3934                 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
 3935                     pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
 3936                 for (field = 0; field < _NPCM; field++) {
 3937                         while (pc->pc_map[field]) {
 3938                                 bit = bsfq(pc->pc_map[field]);
 3939                                 pc->pc_map[field] &= ~(1ul << bit);
 3940                                 pv = &pc->pc_pventry[field * 64 + bit];
 3941                                 va += PAGE_SIZE;
 3942                                 pv->pv_va = va;
 3943                                 m++;
 3944                                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3945                             ("pmap_pv_demote_pde: page %p is not managed", m));
 3946                                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 3947                                 m->md.pv_gen++;
 3948                                 if (va == va_last)
 3949                                         goto out;
 3950                         }
 3951                 }
 3952                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3953                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 3954         }
 3955 out:
 3956         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
 3957                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3958                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 3959         }
 3960         PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
 3961         PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
 3962 }
 3963 
 3964 #if VM_NRESERVLEVEL > 0
 3965 /*
 3966  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
 3967  * replace the many pv entries for the 4KB page mappings by a single pv entry
 3968  * for the 2MB page mapping.
 3969  */
 3970 static void
 3971 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 3972     struct rwlock **lockp)
 3973 {
 3974         struct md_page *pvh;
 3975         pv_entry_t pv;
 3976         vm_offset_t va_last;
 3977         vm_page_t m;
 3978 
 3979         KASSERT((pa & PDRMASK) == 0,
 3980             ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
 3981         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 3982 
 3983         /*
 3984          * Transfer the first page's pv entry for this mapping to the 2mpage's
 3985          * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
 3986          * a transfer avoids the possibility that get_pv_entry() calls
 3987          * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
 3988          * mappings that is being promoted.
 3989          */
 3990         m = PHYS_TO_VM_PAGE(pa);
 3991         va = trunc_2mpage(va);
 3992         pv = pmap_pvh_remove(&m->md, pmap, va);
 3993         KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
 3994         pvh = pa_to_pvh(pa);
 3995         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
 3996         pvh->pv_gen++;
 3997         /* Free the remaining NPTEPG - 1 pv entries. */
 3998         va_last = va + NBPDR - PAGE_SIZE;
 3999         do {
 4000                 m++;
 4001                 va += PAGE_SIZE;
 4002                 pmap_pvh_free(&m->md, pmap, va);
 4003         } while (va < va_last);
 4004 }
 4005 #endif /* VM_NRESERVLEVEL > 0 */
 4006 
 4007 /*
 4008  * First find and then destroy the pv entry for the specified pmap and virtual
 4009  * address.  This operation can be performed on pv lists for either 4KB or 2MB
 4010  * page mappings.
 4011  */
 4012 static void
 4013 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 4014 {
 4015         pv_entry_t pv;
 4016 
 4017         pv = pmap_pvh_remove(pvh, pmap, va);
 4018         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
 4019         free_pv_entry(pmap, pv);
 4020 }
 4021 
 4022 /*
 4023  * Conditionally create the PV entry for a 4KB page mapping if the required
 4024  * memory can be allocated without resorting to reclamation.
 4025  */
 4026 static boolean_t
 4027 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
 4028     struct rwlock **lockp)
 4029 {
 4030         pv_entry_t pv;
 4031 
 4032         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4033         /* Pass NULL instead of the lock pointer to disable reclamation. */
 4034         if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
 4035                 pv->pv_va = va;
 4036                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 4037                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 4038                 m->md.pv_gen++;
 4039                 return (TRUE);
 4040         } else
 4041                 return (FALSE);
 4042 }
 4043 
 4044 /*
 4045  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
 4046  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
 4047  * false if the PV entry cannot be allocated without resorting to reclamation.
 4048  */
 4049 static bool
 4050 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
 4051     struct rwlock **lockp)
 4052 {
 4053         struct md_page *pvh;
 4054         pv_entry_t pv;
 4055         vm_paddr_t pa;
 4056 
 4057         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4058         /* Pass NULL instead of the lock pointer to disable reclamation. */
 4059         if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
 4060             NULL : lockp)) == NULL)
 4061                 return (false);
 4062         pv->pv_va = va;
 4063         pa = pde & PG_PS_FRAME;
 4064         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 4065         pvh = pa_to_pvh(pa);
 4066         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
 4067         pvh->pv_gen++;
 4068         return (true);
 4069 }
 4070 
 4071 /*
 4072  * Fills a page table page with mappings to consecutive physical pages.
 4073  */
 4074 static void
 4075 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
 4076 {
 4077         pt_entry_t *pte;
 4078 
 4079         for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
 4080                 *pte = newpte;
 4081                 newpte += PAGE_SIZE;
 4082         }
 4083 }
 4084 
 4085 /*
 4086  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
 4087  * mapping is invalidated.
 4088  */
 4089 static boolean_t
 4090 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
 4091 {
 4092         struct rwlock *lock;
 4093         boolean_t rv;
 4094 
 4095         lock = NULL;
 4096         rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
 4097         if (lock != NULL)
 4098                 rw_wunlock(lock);
 4099         return (rv);
 4100 }
 4101 
 4102 static boolean_t
 4103 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
 4104     struct rwlock **lockp)
 4105 {
 4106         pd_entry_t newpde, oldpde;
 4107         pt_entry_t *firstpte, newpte;
 4108         pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
 4109         vm_paddr_t mptepa;
 4110         vm_page_t mpte;
 4111         struct spglist free;
 4112         vm_offset_t sva;
 4113         int PG_PTE_CACHE;
 4114 
 4115         PG_G = pmap_global_bit(pmap);
 4116         PG_A = pmap_accessed_bit(pmap);
 4117         PG_M = pmap_modified_bit(pmap);
 4118         PG_RW = pmap_rw_bit(pmap);
 4119         PG_V = pmap_valid_bit(pmap);
 4120         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
 4121         PG_PKU_MASK = pmap_pku_mask_bit(pmap);
 4122 
 4123         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4124         oldpde = *pde;
 4125         KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
 4126             ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
 4127         if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
 4128             NULL) {
 4129                 KASSERT((oldpde & PG_W) == 0,
 4130                     ("pmap_demote_pde: page table page for a wired mapping"
 4131                     " is missing"));
 4132 
 4133                 /*
 4134                  * Invalidate the 2MB page mapping and return "failure" if the
 4135                  * mapping was never accessed or the allocation of the new
 4136                  * page table page fails.  If the 2MB page mapping belongs to
 4137                  * the direct map region of the kernel's address space, then
 4138                  * the page allocation request specifies the highest possible
 4139                  * priority (VM_ALLOC_INTERRUPT).  Otherwise, the priority is
 4140                  * normal.  Page table pages are preallocated for every other
 4141                  * part of the kernel address space, so the direct map region
 4142                  * is the only part of the kernel address space that must be
 4143                  * handled here.
 4144                  */
 4145                 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
 4146                     pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
 4147                     DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
 4148                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
 4149                         SLIST_INIT(&free);
 4150                         sva = trunc_2mpage(va);
 4151                         pmap_remove_pde(pmap, pde, sva, &free, lockp);
 4152                         if ((oldpde & PG_G) == 0)
 4153                                 pmap_invalidate_pde_page(pmap, sva, oldpde);
 4154                         vm_page_free_pages_toq(&free, true);
 4155                         CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
 4156                             " in pmap %p", va, pmap);
 4157                         return (FALSE);
 4158                 }
 4159                 if (va < VM_MAXUSER_ADDRESS)
 4160                         pmap_resident_count_inc(pmap, 1);
 4161         }
 4162         mptepa = VM_PAGE_TO_PHYS(mpte);
 4163         firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
 4164         newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
 4165         KASSERT((oldpde & PG_A) != 0,
 4166             ("pmap_demote_pde: oldpde is missing PG_A"));
 4167         KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
 4168             ("pmap_demote_pde: oldpde is missing PG_M"));
 4169         newpte = oldpde & ~PG_PS;
 4170         newpte = pmap_swap_pat(pmap, newpte);
 4171 
 4172         /*
 4173          * If the page table page is new, initialize it.
 4174          */
 4175         if (mpte->wire_count == 1) {
 4176                 mpte->wire_count = NPTEPG;
 4177                 pmap_fill_ptp(firstpte, newpte);
 4178         }
 4179         KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
 4180             ("pmap_demote_pde: firstpte and newpte map different physical"
 4181             " addresses"));
 4182 
 4183         /*
 4184          * If the mapping has changed attributes, update the page table
 4185          * entries.
 4186          */
 4187         if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
 4188                 pmap_fill_ptp(firstpte, newpte);
 4189 
 4190         /*
 4191          * The spare PV entries must be reserved prior to demoting the
 4192          * mapping, that is, prior to changing the PDE.  Otherwise, the state
 4193          * of the PDE and the PV lists will be inconsistent, which can result
 4194          * in reclaim_pv_chunk() attempting to remove a PV entry from the
 4195          * wrong PV list and pmap_pv_demote_pde() failing to find the expected
 4196          * PV entry for the 2MB page mapping that is being demoted.
 4197          */
 4198         if ((oldpde & PG_MANAGED) != 0)
 4199                 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
 4200 
 4201         /*
 4202          * Demote the mapping.  This pmap is locked.  The old PDE has
 4203          * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
 4204          * set.  Thus, there is no danger of a race with another
 4205          * processor changing the setting of PG_A and/or PG_M between
 4206          * the read above and the store below. 
 4207          */
 4208         if (workaround_erratum383)
 4209                 pmap_update_pde(pmap, va, pde, newpde);
 4210         else
 4211                 pde_store(pde, newpde);
 4212 
 4213         /*
 4214          * Invalidate a stale recursive mapping of the page table page.
 4215          */
 4216         if (va >= VM_MAXUSER_ADDRESS)
 4217                 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
 4218 
 4219         /*
 4220          * Demote the PV entry.
 4221          */
 4222         if ((oldpde & PG_MANAGED) != 0)
 4223                 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
 4224 
 4225         atomic_add_long(&pmap_pde_demotions, 1);
 4226         CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
 4227             " in pmap %p", va, pmap);
 4228         return (TRUE);
 4229 }
 4230 
 4231 /*
 4232  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
 4233  */
 4234 static void
 4235 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
 4236 {
 4237         pd_entry_t newpde;
 4238         vm_paddr_t mptepa;
 4239         vm_page_t mpte;
 4240 
 4241         KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
 4242         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4243         mpte = pmap_remove_pt_page(pmap, va);
 4244         if (mpte == NULL)
 4245                 panic("pmap_remove_kernel_pde: Missing pt page.");
 4246 
 4247         mptepa = VM_PAGE_TO_PHYS(mpte);
 4248         newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
 4249 
 4250         /*
 4251          * Initialize the page table page.
 4252          */
 4253         pagezero((void *)PHYS_TO_DMAP(mptepa));
 4254 
 4255         /*
 4256          * Demote the mapping.
 4257          */
 4258         if (workaround_erratum383)
 4259                 pmap_update_pde(pmap, va, pde, newpde);
 4260         else
 4261                 pde_store(pde, newpde);
 4262 
 4263         /*
 4264          * Invalidate a stale recursive mapping of the page table page.
 4265          */
 4266         pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
 4267 }
 4268 
 4269 /*
 4270  * pmap_remove_pde: do the things to unmap a superpage in a process
 4271  */
 4272 static int
 4273 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
 4274     struct spglist *free, struct rwlock **lockp)
 4275 {
 4276         struct md_page *pvh;
 4277         pd_entry_t oldpde;
 4278         vm_offset_t eva, va;
 4279         vm_page_t m, mpte;
 4280         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
 4281 
 4282         PG_G = pmap_global_bit(pmap);
 4283         PG_A = pmap_accessed_bit(pmap);
 4284         PG_M = pmap_modified_bit(pmap);
 4285         PG_RW = pmap_rw_bit(pmap);
 4286 
 4287         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4288         KASSERT((sva & PDRMASK) == 0,
 4289             ("pmap_remove_pde: sva is not 2mpage aligned"));
 4290         oldpde = pte_load_clear(pdq);
 4291         if (oldpde & PG_W)
 4292                 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
 4293         if ((oldpde & PG_G) != 0)
 4294                 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
 4295         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
 4296         if (oldpde & PG_MANAGED) {
 4297                 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
 4298                 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
 4299                 pmap_pvh_free(pvh, pmap, sva);
 4300                 eva = sva + NBPDR;
 4301                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
 4302                     va < eva; va += PAGE_SIZE, m++) {
 4303                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
 4304                                 vm_page_dirty(m);
 4305                         if (oldpde & PG_A)
 4306                                 vm_page_aflag_set(m, PGA_REFERENCED);
 4307                         if (TAILQ_EMPTY(&m->md.pv_list) &&
 4308                             TAILQ_EMPTY(&pvh->pv_list))
 4309                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
 4310                         pmap_delayed_invl_page(m);
 4311                 }
 4312         }
 4313         if (pmap == kernel_pmap) {
 4314                 pmap_remove_kernel_pde(pmap, pdq, sva);
 4315         } else {
 4316                 mpte = pmap_remove_pt_page(pmap, sva);
 4317                 if (mpte != NULL) {
 4318                         pmap_resident_count_dec(pmap, 1);
 4319                         KASSERT(mpte->wire_count == NPTEPG,
 4320                             ("pmap_remove_pde: pte page wire count error"));
 4321                         mpte->wire_count = 0;
 4322                         pmap_add_delayed_free_list(mpte, free, FALSE);
 4323                 }
 4324         }
 4325         return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
 4326 }
 4327 
 4328 /*
 4329  * pmap_remove_pte: do the things to unmap a page in a process
 4330  */
 4331 static int
 4332 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, 
 4333     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
 4334 {
 4335         struct md_page *pvh;
 4336         pt_entry_t oldpte, PG_A, PG_M, PG_RW;
 4337         vm_page_t m;
 4338 
 4339         PG_A = pmap_accessed_bit(pmap);
 4340         PG_M = pmap_modified_bit(pmap);
 4341         PG_RW = pmap_rw_bit(pmap);
 4342 
 4343         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4344         oldpte = pte_load_clear(ptq);
 4345         if (oldpte & PG_W)
 4346                 pmap->pm_stats.wired_count -= 1;
 4347         pmap_resident_count_dec(pmap, 1);
 4348         if (oldpte & PG_MANAGED) {
 4349                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
 4350                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 4351                         vm_page_dirty(m);
 4352                 if (oldpte & PG_A)
 4353                         vm_page_aflag_set(m, PGA_REFERENCED);
 4354                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 4355                 pmap_pvh_free(&m->md, pmap, va);
 4356                 if (TAILQ_EMPTY(&m->md.pv_list) &&
 4357                     (m->flags & PG_FICTITIOUS) == 0) {
 4358                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 4359                         if (TAILQ_EMPTY(&pvh->pv_list))
 4360                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
 4361                 }
 4362                 pmap_delayed_invl_page(m);
 4363         }
 4364         return (pmap_unuse_pt(pmap, va, ptepde, free));
 4365 }
 4366 
 4367 /*
 4368  * Remove a single page from a process address space
 4369  */
 4370 static void
 4371 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
 4372     struct spglist *free)
 4373 {
 4374         struct rwlock *lock;
 4375         pt_entry_t *pte, PG_V;
 4376 
 4377         PG_V = pmap_valid_bit(pmap);
 4378         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4379         if ((*pde & PG_V) == 0)
 4380                 return;
 4381         pte = pmap_pde_to_pte(pde, va);
 4382         if ((*pte & PG_V) == 0)
 4383                 return;
 4384         lock = NULL;
 4385         pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
 4386         if (lock != NULL)
 4387                 rw_wunlock(lock);
 4388         pmap_invalidate_page(pmap, va);
 4389 }
 4390 
 4391 /*
 4392  * Removes the specified range of addresses from the page table page.
 4393  */
 4394 static bool
 4395 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
 4396     pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
 4397 {
 4398         pt_entry_t PG_G, *pte;
 4399         vm_offset_t va;
 4400         bool anyvalid;
 4401 
 4402         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4403         PG_G = pmap_global_bit(pmap);
 4404         anyvalid = false;
 4405         va = eva;
 4406         for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
 4407             sva += PAGE_SIZE) {
 4408                 if (*pte == 0) {
 4409                         if (va != eva) {
 4410                                 pmap_invalidate_range(pmap, va, sva);
 4411                                 va = eva;
 4412                         }
 4413                         continue;
 4414                 }
 4415                 if ((*pte & PG_G) == 0)
 4416                         anyvalid = true;
 4417                 else if (va == eva)
 4418                         va = sva;
 4419                 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
 4420                         sva += PAGE_SIZE;
 4421                         break;
 4422                 }
 4423         }
 4424         if (va != eva)
 4425                 pmap_invalidate_range(pmap, va, sva);
 4426         return (anyvalid);
 4427 }
 4428 
 4429 /*
 4430  *      Remove the given range of addresses from the specified map.
 4431  *
 4432  *      It is assumed that the start and end are properly
 4433  *      rounded to the page size.
 4434  */
 4435 void
 4436 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 4437 {
 4438         struct rwlock *lock;
 4439         vm_offset_t va_next;
 4440         pml4_entry_t *pml4e;
 4441         pdp_entry_t *pdpe;
 4442         pd_entry_t ptpaddr, *pde;
 4443         pt_entry_t PG_G, PG_V;
 4444         struct spglist free;
 4445         int anyvalid;
 4446 
 4447         PG_G = pmap_global_bit(pmap);
 4448         PG_V = pmap_valid_bit(pmap);
 4449 
 4450         /*
 4451          * Perform an unsynchronized read.  This is, however, safe.
 4452          */
 4453         if (pmap->pm_stats.resident_count == 0)
 4454                 return;
 4455 
 4456         anyvalid = 0;
 4457         SLIST_INIT(&free);
 4458 
 4459         pmap_delayed_invl_started();
 4460         PMAP_LOCK(pmap);
 4461 
 4462         /*
 4463          * special handling of removing one page.  a very
 4464          * common operation and easy to short circuit some
 4465          * code.
 4466          */
 4467         if (sva + PAGE_SIZE == eva) {
 4468                 pde = pmap_pde(pmap, sva);
 4469                 if (pde && (*pde & PG_PS) == 0) {
 4470                         pmap_remove_page(pmap, sva, pde, &free);
 4471                         goto out;
 4472                 }
 4473         }
 4474 
 4475         lock = NULL;
 4476         for (; sva < eva; sva = va_next) {
 4477 
 4478                 if (pmap->pm_stats.resident_count == 0)
 4479                         break;
 4480 
 4481                 pml4e = pmap_pml4e(pmap, sva);
 4482                 if ((*pml4e & PG_V) == 0) {
 4483                         va_next = (sva + NBPML4) & ~PML4MASK;
 4484                         if (va_next < sva)
 4485                                 va_next = eva;
 4486                         continue;
 4487                 }
 4488 
 4489                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
 4490                 if ((*pdpe & PG_V) == 0) {
 4491                         va_next = (sva + NBPDP) & ~PDPMASK;
 4492                         if (va_next < sva)
 4493                                 va_next = eva;
 4494                         continue;
 4495                 }
 4496 
 4497                 /*
 4498                  * Calculate index for next page table.
 4499                  */
 4500                 va_next = (sva + NBPDR) & ~PDRMASK;
 4501                 if (va_next < sva)
 4502                         va_next = eva;
 4503 
 4504                 pde = pmap_pdpe_to_pde(pdpe, sva);
 4505                 ptpaddr = *pde;
 4506 
 4507                 /*
 4508                  * Weed out invalid mappings.
 4509                  */
 4510                 if (ptpaddr == 0)
 4511                         continue;
 4512 
 4513                 /*
 4514                  * Check for large page.
 4515                  */
 4516                 if ((ptpaddr & PG_PS) != 0) {
 4517                         /*
 4518                          * Are we removing the entire large page?  If not,
 4519                          * demote the mapping and fall through.
 4520                          */
 4521                         if (sva + NBPDR == va_next && eva >= va_next) {
 4522                                 /*
 4523                                  * The TLB entry for a PG_G mapping is
 4524                                  * invalidated by pmap_remove_pde().
 4525                                  */
 4526                                 if ((ptpaddr & PG_G) == 0)
 4527                                         anyvalid = 1;
 4528                                 pmap_remove_pde(pmap, pde, sva, &free, &lock);
 4529                                 continue;
 4530                         } else if (!pmap_demote_pde_locked(pmap, pde, sva,
 4531                             &lock)) {
 4532                                 /* The large page mapping was destroyed. */
 4533                                 continue;
 4534                         } else
 4535                                 ptpaddr = *pde;
 4536                 }
 4537 
 4538                 /*
 4539                  * Limit our scan to either the end of the va represented
 4540                  * by the current page table page, or to the end of the
 4541                  * range being removed.
 4542                  */
 4543                 if (va_next > eva)
 4544                         va_next = eva;
 4545 
 4546                 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
 4547                         anyvalid = 1;
 4548         }
 4549         if (lock != NULL)
 4550                 rw_wunlock(lock);
 4551 out:
 4552         if (anyvalid)
 4553                 pmap_invalidate_all(pmap);
 4554         pmap_pkru_on_remove(pmap, sva, eva);
 4555         PMAP_UNLOCK(pmap);
 4556         pmap_delayed_invl_finished();
 4557         vm_page_free_pages_toq(&free, true);
 4558 }
 4559 
 4560 /*
 4561  *      Routine:        pmap_remove_all
 4562  *      Function:
 4563  *              Removes this physical page from
 4564  *              all physical maps in which it resides.
 4565  *              Reflects back modify bits to the pager.
 4566  *
 4567  *      Notes:
 4568  *              Original versions of this routine were very
 4569  *              inefficient because they iteratively called
 4570  *              pmap_remove (slow...)
 4571  */
 4572 
 4573 void
 4574 pmap_remove_all(vm_page_t m)
 4575 {
 4576         struct md_page *pvh;
 4577         pv_entry_t pv;
 4578         pmap_t pmap;
 4579         struct rwlock *lock;
 4580         pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
 4581         pd_entry_t *pde;
 4582         vm_offset_t va;
 4583         struct spglist free;
 4584         int pvh_gen, md_gen;
 4585 
 4586         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 4587             ("pmap_remove_all: page %p is not managed", m));
 4588         SLIST_INIT(&free);
 4589         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 4590         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
 4591             pa_to_pvh(VM_PAGE_TO_PHYS(m));
 4592 retry:
 4593         rw_wlock(lock);
 4594         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
 4595                 pmap = PV_PMAP(pv);
 4596                 if (!PMAP_TRYLOCK(pmap)) {
 4597                         pvh_gen = pvh->pv_gen;
 4598                         rw_wunlock(lock);
 4599                         PMAP_LOCK(pmap);
 4600                         rw_wlock(lock);
 4601                         if (pvh_gen != pvh->pv_gen) {
 4602                                 rw_wunlock(lock);
 4603                                 PMAP_UNLOCK(pmap);
 4604                                 goto retry;
 4605                         }
 4606                 }
 4607                 va = pv->pv_va;
 4608                 pde = pmap_pde(pmap, va);
 4609                 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
 4610                 PMAP_UNLOCK(pmap);
 4611         }
 4612         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 4613                 pmap = PV_PMAP(pv);
 4614                 if (!PMAP_TRYLOCK(pmap)) {
 4615                         pvh_gen = pvh->pv_gen;
 4616                         md_gen = m->md.pv_gen;
 4617                         rw_wunlock(lock);
 4618                         PMAP_LOCK(pmap);
 4619                         rw_wlock(lock);
 4620                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
 4621                                 rw_wunlock(lock);
 4622                                 PMAP_UNLOCK(pmap);
 4623                                 goto retry;
 4624                         }
 4625                 }
 4626                 PG_A = pmap_accessed_bit(pmap);
 4627                 PG_M = pmap_modified_bit(pmap);
 4628                 PG_RW = pmap_rw_bit(pmap);
 4629                 pmap_resident_count_dec(pmap, 1);
 4630                 pde = pmap_pde(pmap, pv->pv_va);
 4631                 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
 4632                     " a 2mpage in page %p's pv list", m));
 4633                 pte = pmap_pde_to_pte(pde, pv->pv_va);
 4634                 tpte = pte_load_clear(pte);
 4635                 if (tpte & PG_W)
 4636                         pmap->pm_stats.wired_count--;
 4637                 if (tpte & PG_A)
 4638                         vm_page_aflag_set(m, PGA_REFERENCED);
 4639 
 4640                 /*
 4641                  * Update the vm_page_t clean and reference bits.
 4642                  */
 4643                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 4644                         vm_page_dirty(m);
 4645                 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
 4646                 pmap_invalidate_page(pmap, pv->pv_va);
 4647                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 4648                 m->md.pv_gen++;
 4649                 free_pv_entry(pmap, pv);
 4650                 PMAP_UNLOCK(pmap);
 4651         }
 4652         vm_page_aflag_clear(m, PGA_WRITEABLE);
 4653         rw_wunlock(lock);
 4654         pmap_delayed_invl_wait(m);
 4655         vm_page_free_pages_toq(&free, true);
 4656 }
 4657 
 4658 /*
 4659  * pmap_protect_pde: do the things to protect a 2mpage in a process
 4660  */
 4661 static boolean_t
 4662 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
 4663 {
 4664         pd_entry_t newpde, oldpde;
 4665         vm_offset_t eva, va;
 4666         vm_page_t m;
 4667         boolean_t anychanged;
 4668         pt_entry_t PG_G, PG_M, PG_RW;
 4669 
 4670         PG_G = pmap_global_bit(pmap);
 4671         PG_M = pmap_modified_bit(pmap);
 4672         PG_RW = pmap_rw_bit(pmap);
 4673 
 4674         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4675         KASSERT((sva & PDRMASK) == 0,
 4676             ("pmap_protect_pde: sva is not 2mpage aligned"));
 4677         anychanged = FALSE;
 4678 retry:
 4679         oldpde = newpde = *pde;
 4680         if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
 4681             (PG_MANAGED | PG_M | PG_RW)) {
 4682                 eva = sva + NBPDR;
 4683                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
 4684                     va < eva; va += PAGE_SIZE, m++)
 4685                         vm_page_dirty(m);
 4686         }
 4687         if ((prot & VM_PROT_WRITE) == 0)
 4688                 newpde &= ~(PG_RW | PG_M);
 4689         if ((prot & VM_PROT_EXECUTE) == 0)
 4690                 newpde |= pg_nx;
 4691         if (newpde != oldpde) {
 4692                 /*
 4693                  * As an optimization to future operations on this PDE, clear
 4694                  * PG_PROMOTED.  The impending invalidation will remove any
 4695                  * lingering 4KB page mappings from the TLB.
 4696                  */
 4697                 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
 4698                         goto retry;
 4699                 if ((oldpde & PG_G) != 0)
 4700                         pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
 4701                 else
 4702                         anychanged = TRUE;
 4703         }
 4704         return (anychanged);
 4705 }
 4706 
 4707 /*
 4708  *      Set the physical protection on the
 4709  *      specified range of this map as requested.
 4710  */
 4711 void
 4712 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
 4713 {
 4714         vm_offset_t va_next;
 4715         pml4_entry_t *pml4e;
 4716         pdp_entry_t *pdpe;
 4717         pd_entry_t ptpaddr, *pde;
 4718         pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
 4719         boolean_t anychanged;
 4720 
 4721         KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
 4722         if (prot == VM_PROT_NONE) {
 4723                 pmap_remove(pmap, sva, eva);
 4724                 return;
 4725         }
 4726 
 4727         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
 4728             (VM_PROT_WRITE|VM_PROT_EXECUTE))
 4729                 return;
 4730 
 4731         PG_G = pmap_global_bit(pmap);
 4732         PG_M = pmap_modified_bit(pmap);
 4733         PG_V = pmap_valid_bit(pmap);
 4734         PG_RW = pmap_rw_bit(pmap);
 4735         anychanged = FALSE;
 4736 
 4737         /*
 4738          * Although this function delays and batches the invalidation
 4739          * of stale TLB entries, it does not need to call
 4740          * pmap_delayed_invl_started() and
 4741          * pmap_delayed_invl_finished(), because it does not
 4742          * ordinarily destroy mappings.  Stale TLB entries from
 4743          * protection-only changes need only be invalidated before the
 4744          * pmap lock is released, because protection-only changes do
 4745          * not destroy PV entries.  Even operations that iterate over
 4746          * a physical page's PV list of mappings, like
 4747          * pmap_remove_write(), acquire the pmap lock for each
 4748          * mapping.  Consequently, for protection-only changes, the
 4749          * pmap lock suffices to synchronize both page table and TLB
 4750          * updates.
 4751          *
 4752          * This function only destroys a mapping if pmap_demote_pde()
 4753          * fails.  In that case, stale TLB entries are immediately
 4754          * invalidated.
 4755          */
 4756         
 4757         PMAP_LOCK(pmap);
 4758         for (; sva < eva; sva = va_next) {
 4759 
 4760                 pml4e = pmap_pml4e(pmap, sva);
 4761                 if ((*pml4e & PG_V) == 0) {
 4762                         va_next = (sva + NBPML4) & ~PML4MASK;
 4763                         if (va_next < sva)
 4764                                 va_next = eva;
 4765                         continue;
 4766                 }
 4767 
 4768                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
 4769                 if ((*pdpe & PG_V) == 0) {
 4770                         va_next = (sva + NBPDP) & ~PDPMASK;
 4771                         if (va_next < sva)
 4772                                 va_next = eva;
 4773                         continue;
 4774                 }
 4775 
 4776                 va_next = (sva + NBPDR) & ~PDRMASK;
 4777                 if (va_next < sva)
 4778                         va_next = eva;
 4779 
 4780                 pde = pmap_pdpe_to_pde(pdpe, sva);
 4781                 ptpaddr = *pde;
 4782 
 4783                 /*
 4784                  * Weed out invalid mappings.
 4785                  */
 4786                 if (ptpaddr == 0)
 4787                         continue;
 4788 
 4789                 /*
 4790                  * Check for large page.
 4791                  */
 4792                 if ((ptpaddr & PG_PS) != 0) {
 4793                         /*
 4794                          * Are we protecting the entire large page?  If not,
 4795                          * demote the mapping and fall through.
 4796                          */
 4797                         if (sva + NBPDR == va_next && eva >= va_next) {
 4798                                 /*
 4799                                  * The TLB entry for a PG_G mapping is
 4800                                  * invalidated by pmap_protect_pde().
 4801                                  */
 4802                                 if (pmap_protect_pde(pmap, pde, sva, prot))
 4803                                         anychanged = TRUE;
 4804                                 continue;
 4805                         } else if (!pmap_demote_pde(pmap, pde, sva)) {
 4806                                 /*
 4807                                  * The large page mapping was destroyed.
 4808                                  */
 4809                                 continue;
 4810                         }
 4811                 }
 4812 
 4813                 if (va_next > eva)
 4814                         va_next = eva;
 4815 
 4816                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
 4817                     sva += PAGE_SIZE) {
 4818                         pt_entry_t obits, pbits;
 4819                         vm_page_t m;
 4820 
 4821 retry:
 4822                         obits = pbits = *pte;
 4823                         if ((pbits & PG_V) == 0)
 4824                                 continue;
 4825 
 4826                         if ((prot & VM_PROT_WRITE) == 0) {
 4827                                 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
 4828                                     (PG_MANAGED | PG_M | PG_RW)) {
 4829                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
 4830                                         vm_page_dirty(m);
 4831                                 }
 4832                                 pbits &= ~(PG_RW | PG_M);
 4833                         }
 4834                         if ((prot & VM_PROT_EXECUTE) == 0)
 4835                                 pbits |= pg_nx;
 4836 
 4837                         if (pbits != obits) {
 4838                                 if (!atomic_cmpset_long(pte, obits, pbits))
 4839                                         goto retry;
 4840                                 if (obits & PG_G)
 4841                                         pmap_invalidate_page(pmap, sva);
 4842                                 else
 4843                                         anychanged = TRUE;
 4844                         }
 4845                 }
 4846         }
 4847         if (anychanged)
 4848                 pmap_invalidate_all(pmap);
 4849         PMAP_UNLOCK(pmap);
 4850 }
 4851 
 4852 #if VM_NRESERVLEVEL > 0
 4853 /*
 4854  * Tries to promote the 512, contiguous 4KB page mappings that are within a
 4855  * single page table page (PTP) to a single 2MB page mapping.  For promotion
 4856  * to occur, two conditions must be met: (1) the 4KB page mappings must map
 4857  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
 4858  * identical characteristics. 
 4859  */
 4860 static void
 4861 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
 4862     struct rwlock **lockp)
 4863 {
 4864         pd_entry_t newpde;
 4865         pt_entry_t *firstpte, oldpte, pa, *pte;
 4866         pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V, PG_PKU_MASK;
 4867         vm_page_t mpte;
 4868         int PG_PTE_CACHE;
 4869 
 4870         PG_A = pmap_accessed_bit(pmap);
 4871         PG_G = pmap_global_bit(pmap);
 4872         PG_M = pmap_modified_bit(pmap);
 4873         PG_V = pmap_valid_bit(pmap);
 4874         PG_RW = pmap_rw_bit(pmap);
 4875         PG_PKU_MASK = pmap_pku_mask_bit(pmap);
 4876         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
 4877 
 4878         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4879 
 4880         /*
 4881          * Examine the first PTE in the specified PTP.  Abort if this PTE is
 4882          * either invalid, unused, or does not map the first 4KB physical page
 4883          * within a 2MB page. 
 4884          */
 4885         firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
 4886 setpde:
 4887         newpde = *firstpte;
 4888         if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
 4889                 atomic_add_long(&pmap_pde_p_failures, 1);
 4890                 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
 4891                     " in pmap %p", va, pmap);
 4892                 return;
 4893         }
 4894         if ((newpde & (PG_M | PG_RW)) == PG_RW) {
 4895                 /*
 4896                  * When PG_M is already clear, PG_RW can be cleared without
 4897                  * a TLB invalidation.
 4898                  */
 4899                 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
 4900                         goto setpde;
 4901                 newpde &= ~PG_RW;
 4902         }
 4903 
 4904         /*
 4905          * Examine each of the other PTEs in the specified PTP.  Abort if this
 4906          * PTE maps an unexpected 4KB physical page or does not have identical
 4907          * characteristics to the first PTE.
 4908          */
 4909         pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
 4910         for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
 4911 setpte:
 4912                 oldpte = *pte;
 4913                 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
 4914                         atomic_add_long(&pmap_pde_p_failures, 1);
 4915                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
 4916                             " in pmap %p", va, pmap);
 4917                         return;
 4918                 }
 4919                 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
 4920                         /*
 4921                          * When PG_M is already clear, PG_RW can be cleared
 4922                          * without a TLB invalidation.
 4923                          */
 4924                         if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
 4925                                 goto setpte;
 4926                         oldpte &= ~PG_RW;
 4927                         CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
 4928                             " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
 4929                             (va & ~PDRMASK), pmap);
 4930                 }
 4931                 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
 4932                         atomic_add_long(&pmap_pde_p_failures, 1);
 4933                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
 4934                             " in pmap %p", va, pmap);
 4935                         return;
 4936                 }
 4937                 pa -= PAGE_SIZE;
 4938         }
 4939 
 4940         /*
 4941          * Save the page table page in its current state until the PDE
 4942          * mapping the superpage is demoted by pmap_demote_pde() or
 4943          * destroyed by pmap_remove_pde(). 
 4944          */
 4945         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
 4946         KASSERT(mpte >= vm_page_array &&
 4947             mpte < &vm_page_array[vm_page_array_size],
 4948             ("pmap_promote_pde: page table page is out of range"));
 4949         KASSERT(mpte->pindex == pmap_pde_pindex(va),
 4950             ("pmap_promote_pde: page table page's pindex is wrong"));
 4951         if (pmap_insert_pt_page(pmap, mpte)) {
 4952                 atomic_add_long(&pmap_pde_p_failures, 1);
 4953                 CTR2(KTR_PMAP,
 4954                     "pmap_promote_pde: failure for va %#lx in pmap %p", va,
 4955                     pmap);
 4956                 return;
 4957         }
 4958 
 4959         /*
 4960          * Promote the pv entries.
 4961          */
 4962         if ((newpde & PG_MANAGED) != 0)
 4963                 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
 4964 
 4965         /*
 4966          * Propagate the PAT index to its proper position.
 4967          */
 4968         newpde = pmap_swap_pat(pmap, newpde);
 4969 
 4970         /*
 4971          * Map the superpage.
 4972          */
 4973         if (workaround_erratum383)
 4974                 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
 4975         else
 4976                 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
 4977 
 4978         atomic_add_long(&pmap_pde_promotions, 1);
 4979         CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
 4980             " in pmap %p", va, pmap);
 4981 }
 4982 #endif /* VM_NRESERVLEVEL > 0 */
 4983 
 4984 /*
 4985  *      Insert the given physical page (p) at
 4986  *      the specified virtual address (v) in the
 4987  *      target physical map with the protection requested.
 4988  *
 4989  *      If specified, the page will be wired down, meaning
 4990  *      that the related pte can not be reclaimed.
 4991  *
 4992  *      NB:  This is the only routine which MAY NOT lazy-evaluate
 4993  *      or lose information.  That is, this routine must actually
 4994  *      insert this page into the given map NOW.
 4995  *
 4996  *      When destroying both a page table and PV entry, this function
 4997  *      performs the TLB invalidation before releasing the PV list
 4998  *      lock, so we do not need pmap_delayed_invl_page() calls here.
 4999  */
 5000 int
 5001 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 5002     u_int flags, int8_t psind)
 5003 {
 5004         struct rwlock *lock;
 5005         pd_entry_t *pde;
 5006         pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
 5007         pt_entry_t newpte, origpte;
 5008         pv_entry_t pv;
 5009         vm_paddr_t opa, pa;
 5010         vm_page_t mpte, om;
 5011         int rv;
 5012         boolean_t nosleep;
 5013 
 5014         PG_A = pmap_accessed_bit(pmap);
 5015         PG_G = pmap_global_bit(pmap);
 5016         PG_M = pmap_modified_bit(pmap);
 5017         PG_V = pmap_valid_bit(pmap);
 5018         PG_RW = pmap_rw_bit(pmap);
 5019 
 5020         va = trunc_page(va);
 5021         KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
 5022         KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
 5023             ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
 5024             va));
 5025         KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
 5026             va >= kmi.clean_eva,
 5027             ("pmap_enter: managed mapping within the clean submap"));
 5028         if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
 5029                 VM_OBJECT_ASSERT_LOCKED(m->object);
 5030         KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
 5031             ("pmap_enter: flags %u has reserved bits set", flags));
 5032         pa = VM_PAGE_TO_PHYS(m);
 5033         newpte = (pt_entry_t)(pa | PG_A | PG_V);
 5034         if ((flags & VM_PROT_WRITE) != 0)
 5035                 newpte |= PG_M;
 5036         if ((prot & VM_PROT_WRITE) != 0)
 5037                 newpte |= PG_RW;
 5038         KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
 5039             ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
 5040         if ((prot & VM_PROT_EXECUTE) == 0)
 5041                 newpte |= pg_nx;
 5042         if ((flags & PMAP_ENTER_WIRED) != 0)
 5043                 newpte |= PG_W;
 5044         if (va < VM_MAXUSER_ADDRESS)
 5045                 newpte |= PG_U;
 5046         if (pmap == kernel_pmap)
 5047                 newpte |= PG_G;
 5048         newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
 5049 
 5050         /*
 5051          * Set modified bit gratuitously for writeable mappings if
 5052          * the page is unmanaged. We do not want to take a fault
 5053          * to do the dirty bit accounting for these mappings.
 5054          */
 5055         if ((m->oflags & VPO_UNMANAGED) != 0) {
 5056                 if ((newpte & PG_RW) != 0)
 5057                         newpte |= PG_M;
 5058         } else
 5059                 newpte |= PG_MANAGED;
 5060 
 5061         lock = NULL;
 5062         PMAP_LOCK(pmap);
 5063         if (psind == 1) {
 5064                 /* Assert the required virtual and physical alignment. */ 
 5065                 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
 5066                 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
 5067                 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
 5068                 goto out;
 5069         }
 5070         mpte = NULL;
 5071 
 5072         /*
 5073          * In the case that a page table page is not
 5074          * resident, we are creating it here.
 5075          */
 5076 retry:
 5077         pde = pmap_pde(pmap, va);
 5078         if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
 5079             pmap_demote_pde_locked(pmap, pde, va, &lock))) {
 5080                 pte = pmap_pde_to_pte(pde, va);
 5081                 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
 5082                         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
 5083                         mpte->wire_count++;
 5084                 }
 5085         } else if (va < VM_MAXUSER_ADDRESS) {
 5086                 /*
 5087                  * Here if the pte page isn't mapped, or if it has been
 5088                  * deallocated.
 5089                  */
 5090                 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
 5091                 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
 5092                     nosleep ? NULL : &lock);
 5093                 if (mpte == NULL && nosleep) {
 5094                         rv = KERN_RESOURCE_SHORTAGE;
 5095                         goto out;
 5096                 }
 5097                 goto retry;
 5098         } else
 5099                 panic("pmap_enter: invalid page directory va=%#lx", va);
 5100 
 5101         origpte = *pte;
 5102         pv = NULL;
 5103         if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
 5104                 newpte |= pmap_pkru_get(pmap, va);
 5105 
 5106         /*
 5107          * Is the specified virtual address already mapped?
 5108          */
 5109         if ((origpte & PG_V) != 0) {
 5110                 /*
 5111                  * Wiring change, just update stats. We don't worry about
 5112                  * wiring PT pages as they remain resident as long as there
 5113                  * are valid mappings in them. Hence, if a user page is wired,
 5114                  * the PT page will be also.
 5115                  */
 5116                 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
 5117                         pmap->pm_stats.wired_count++;
 5118                 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
 5119                         pmap->pm_stats.wired_count--;
 5120 
 5121                 /*
 5122                  * Remove the extra PT page reference.
 5123                  */
 5124                 if (mpte != NULL) {
 5125                         mpte->wire_count--;
 5126                         KASSERT(mpte->wire_count > 0,
 5127                             ("pmap_enter: missing reference to page table page,"
 5128                              " va: 0x%lx", va));
 5129                 }
 5130 
 5131                 /*
 5132                  * Has the physical page changed?
 5133                  */
 5134                 opa = origpte & PG_FRAME;
 5135                 if (opa == pa) {
 5136                         /*
 5137                          * No, might be a protection or wiring change.
 5138                          */
 5139                         if ((origpte & PG_MANAGED) != 0 &&
 5140                             (newpte & PG_RW) != 0)
 5141                                 vm_page_aflag_set(m, PGA_WRITEABLE);
 5142                         if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
 5143                                 goto unchanged;
 5144                         goto validate;
 5145                 }
 5146 
 5147                 /*
 5148                  * The physical page has changed.  Temporarily invalidate
 5149                  * the mapping.  This ensures that all threads sharing the
 5150                  * pmap keep a consistent view of the mapping, which is
 5151                  * necessary for the correct handling of COW faults.  It
 5152                  * also permits reuse of the old mapping's PV entry,
 5153                  * avoiding an allocation.
 5154                  *
 5155                  * For consistency, handle unmanaged mappings the same way.
 5156                  */
 5157                 origpte = pte_load_clear(pte);
 5158                 KASSERT((origpte & PG_FRAME) == opa,
 5159                     ("pmap_enter: unexpected pa update for %#lx", va));
 5160                 if ((origpte & PG_MANAGED) != 0) {
 5161                         om = PHYS_TO_VM_PAGE(opa);
 5162 
 5163                         /*
 5164                          * The pmap lock is sufficient to synchronize with
 5165                          * concurrent calls to pmap_page_test_mappings() and
 5166                          * pmap_ts_referenced().
 5167                          */
 5168                         if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 5169                                 vm_page_dirty(om);
 5170                         if ((origpte & PG_A) != 0)
 5171                                 vm_page_aflag_set(om, PGA_REFERENCED);
 5172                         CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
 5173                         pv = pmap_pvh_remove(&om->md, pmap, va);
 5174                         KASSERT(pv != NULL,
 5175                             ("pmap_enter: no PV entry for %#lx", va));
 5176                         if ((newpte & PG_MANAGED) == 0)
 5177                                 free_pv_entry(pmap, pv);
 5178                         if ((om->aflags & PGA_WRITEABLE) != 0 &&
 5179                             TAILQ_EMPTY(&om->md.pv_list) &&
 5180                             ((om->flags & PG_FICTITIOUS) != 0 ||
 5181                             TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
 5182                                 vm_page_aflag_clear(om, PGA_WRITEABLE);
 5183                 }
 5184                 if ((origpte & PG_A) != 0)
 5185                         pmap_invalidate_page(pmap, va);
 5186                 origpte = 0;
 5187         } else {
 5188                 /*
 5189                  * Increment the counters.
 5190                  */
 5191                 if ((newpte & PG_W) != 0)
 5192                         pmap->pm_stats.wired_count++;
 5193                 pmap_resident_count_inc(pmap, 1);
 5194         }
 5195 
 5196         /*
 5197          * Enter on the PV list if part of our managed memory.
 5198          */
 5199         if ((newpte & PG_MANAGED) != 0) {
 5200                 if (pv == NULL) {
 5201                         pv = get_pv_entry(pmap, &lock);
 5202                         pv->pv_va = va;
 5203                 }
 5204                 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
 5205                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 5206                 m->md.pv_gen++;
 5207                 if ((newpte & PG_RW) != 0)
 5208                         vm_page_aflag_set(m, PGA_WRITEABLE);
 5209         }
 5210 
 5211         /*
 5212          * Update the PTE.
 5213          */
 5214         if ((origpte & PG_V) != 0) {
 5215 validate:
 5216                 origpte = pte_load_store(pte, newpte);
 5217                 KASSERT((origpte & PG_FRAME) == pa,
 5218                     ("pmap_enter: unexpected pa update for %#lx", va));
 5219                 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
 5220                     (PG_M | PG_RW)) {
 5221                         if ((origpte & PG_MANAGED) != 0)
 5222                                 vm_page_dirty(m);
 5223 
 5224                         /*
 5225                          * Although the PTE may still have PG_RW set, TLB
 5226                          * invalidation may nonetheless be required because
 5227                          * the PTE no longer has PG_M set.
 5228                          */
 5229                 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
 5230                         /*
 5231                          * This PTE change does not require TLB invalidation.
 5232                          */
 5233                         goto unchanged;
 5234                 }
 5235                 if ((origpte & PG_A) != 0)
 5236                         pmap_invalidate_page(pmap, va);
 5237         } else
 5238                 pte_store(pte, newpte);
 5239 
 5240 unchanged:
 5241 
 5242 #if VM_NRESERVLEVEL > 0
 5243         /*
 5244          * If both the page table page and the reservation are fully
 5245          * populated, then attempt promotion.
 5246          */
 5247         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
 5248             pmap_ps_enabled(pmap) &&
 5249             (m->flags & PG_FICTITIOUS) == 0 &&
 5250             vm_reserv_level_iffullpop(m) == 0)
 5251                 pmap_promote_pde(pmap, pde, va, &lock);
 5252 #endif
 5253 
 5254         rv = KERN_SUCCESS;
 5255 out:
 5256         if (lock != NULL)
 5257                 rw_wunlock(lock);
 5258         PMAP_UNLOCK(pmap);
 5259         return (rv);
 5260 }
 5261 
 5262 /*
 5263  * Tries to create a read- and/or execute-only 2MB page mapping.  Returns true
 5264  * if successful.  Returns false if (1) a page table page cannot be allocated
 5265  * without sleeping, (2) a mapping already exists at the specified virtual
 5266  * address, or (3) a PV entry cannot be allocated without reclaiming another
 5267  * PV entry.
 5268  */
 5269 static bool
 5270 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
 5271     struct rwlock **lockp)
 5272 {
 5273         pd_entry_t newpde;
 5274         pt_entry_t PG_V;
 5275 
 5276         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5277         PG_V = pmap_valid_bit(pmap);
 5278         newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
 5279             PG_PS | PG_V;
 5280         if ((m->oflags & VPO_UNMANAGED) == 0)
 5281                 newpde |= PG_MANAGED;
 5282         if ((prot & VM_PROT_EXECUTE) == 0)
 5283                 newpde |= pg_nx;
 5284         if (va < VM_MAXUSER_ADDRESS)
 5285                 newpde |= PG_U;
 5286         return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
 5287             PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
 5288             KERN_SUCCESS);
 5289 }
 5290 
 5291 /*
 5292  * Tries to create the specified 2MB page mapping.  Returns KERN_SUCCESS if
 5293  * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
 5294  * otherwise.  Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
 5295  * a mapping already exists at the specified virtual address.  Returns
 5296  * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
 5297  * page allocation failed.  Returns KERN_RESOURCE_SHORTAGE if
 5298  * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
 5299  *
 5300  * The parameter "m" is only used when creating a managed, writeable mapping.
 5301  */
 5302 static int
 5303 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
 5304     vm_page_t m, struct rwlock **lockp)
 5305 {
 5306         struct spglist free;
 5307         pd_entry_t oldpde, *pde;
 5308         pt_entry_t PG_G, PG_RW, PG_V;
 5309         vm_page_t mt, pdpg;
 5310 
 5311         KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
 5312             ("pmap_enter_pde: cannot create wired user mapping"));
 5313         PG_G = pmap_global_bit(pmap);
 5314         PG_RW = pmap_rw_bit(pmap);
 5315         KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
 5316             ("pmap_enter_pde: newpde is missing PG_M"));
 5317         PG_V = pmap_valid_bit(pmap);
 5318         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5319 
 5320         if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
 5321             NULL : lockp)) == NULL) {
 5322                 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
 5323                     " in pmap %p", va, pmap);
 5324                 return (KERN_RESOURCE_SHORTAGE);
 5325         }
 5326 
 5327         /*
 5328          * If pkru is not same for the whole pde range, return failure
 5329          * and let vm_fault() cope.  Check after pde allocation, since
 5330          * it could sleep.
 5331          */
 5332         if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
 5333                 SLIST_INIT(&free);
 5334                 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
 5335                         pmap_invalidate_page(pmap, va);
 5336                         vm_page_free_pages_toq(&free, true);
 5337                 }
 5338                 return (KERN_FAILURE);
 5339         }
 5340         if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
 5341                 newpde &= ~X86_PG_PKU_MASK;
 5342                 newpde |= pmap_pkru_get(pmap, va);
 5343         }
 5344 
 5345         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
 5346         pde = &pde[pmap_pde_index(va)];
 5347         oldpde = *pde;
 5348         if ((oldpde & PG_V) != 0) {
 5349                 KASSERT(pdpg->wire_count > 1,
 5350                     ("pmap_enter_pde: pdpg's wire count is too low"));
 5351                 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
 5352                         pdpg->wire_count--;
 5353                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
 5354                             " in pmap %p", va, pmap);
 5355                         return (KERN_FAILURE);
 5356                 }
 5357                 /* Break the existing mapping(s). */
 5358                 SLIST_INIT(&free);
 5359                 if ((oldpde & PG_PS) != 0) {
 5360                         /*
 5361                          * The reference to the PD page that was acquired by
 5362                          * pmap_allocpde() ensures that it won't be freed.
 5363                          * However, if the PDE resulted from a promotion, then
 5364                          * a reserved PT page could be freed.
 5365                          */
 5366                         (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
 5367                         if ((oldpde & PG_G) == 0)
 5368                                 pmap_invalidate_pde_page(pmap, va, oldpde);
 5369                 } else {
 5370                         pmap_delayed_invl_started();
 5371                         if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
 5372                             lockp))
 5373                                pmap_invalidate_all(pmap);
 5374                         pmap_delayed_invl_finished();
 5375                 }
 5376                 vm_page_free_pages_toq(&free, true);
 5377                 if (va >= VM_MAXUSER_ADDRESS) {
 5378                         mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
 5379                         if (pmap_insert_pt_page(pmap, mt)) {
 5380                                 /*
 5381                                  * XXX Currently, this can't happen because
 5382                                  * we do not perform pmap_enter(psind == 1)
 5383                                  * on the kernel pmap.
 5384                                  */
 5385                                 panic("pmap_enter_pde: trie insert failed");
 5386                         }
 5387                 } else
 5388                         KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
 5389                             pde));
 5390         }
 5391         if ((newpde & PG_MANAGED) != 0) {
 5392                 /*
 5393                  * Abort this mapping if its PV entry could not be created.
 5394                  */
 5395                 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
 5396                         SLIST_INIT(&free);
 5397                         if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
 5398                                 /*
 5399                                  * Although "va" is not mapped, paging-
 5400                                  * structure caches could nonetheless have
 5401                                  * entries that refer to the freed page table
 5402                                  * pages.  Invalidate those entries.
 5403                                  */
 5404                                 pmap_invalidate_page(pmap, va);
 5405                                 vm_page_free_pages_toq(&free, true);
 5406                         }
 5407                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
 5408                             " in pmap %p", va, pmap);
 5409                         return (KERN_RESOURCE_SHORTAGE);
 5410                 }
 5411                 if ((newpde & PG_RW) != 0) {
 5412                         for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
 5413                                 vm_page_aflag_set(mt, PGA_WRITEABLE);
 5414                 }
 5415         }
 5416 
 5417         /*
 5418          * Increment counters.
 5419          */
 5420         if ((newpde & PG_W) != 0)
 5421                 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
 5422         pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
 5423 
 5424         /*
 5425          * Map the superpage.  (This is not a promoted mapping; there will not
 5426          * be any lingering 4KB page mappings in the TLB.)
 5427          */
 5428         pde_store(pde, newpde);
 5429 
 5430         atomic_add_long(&pmap_pde_mappings, 1);
 5431         CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
 5432             " in pmap %p", va, pmap);
 5433         return (KERN_SUCCESS);
 5434 }
 5435 
 5436 /*
 5437  * Maps a sequence of resident pages belonging to the same object.
 5438  * The sequence begins with the given page m_start.  This page is
 5439  * mapped at the given virtual address start.  Each subsequent page is
 5440  * mapped at a virtual address that is offset from start by the same
 5441  * amount as the page is offset from m_start within the object.  The
 5442  * last page in the sequence is the page with the largest offset from
 5443  * m_start that can be mapped at a virtual address less than the given
 5444  * virtual address end.  Not every virtual page between start and end
 5445  * is mapped; only those for which a resident page exists with the
 5446  * corresponding offset from m_start are mapped.
 5447  */
 5448 void
 5449 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
 5450     vm_page_t m_start, vm_prot_t prot)
 5451 {
 5452         struct rwlock *lock;
 5453         vm_offset_t va;
 5454         vm_page_t m, mpte;
 5455         vm_pindex_t diff, psize;
 5456 
 5457         VM_OBJECT_ASSERT_LOCKED(m_start->object);
 5458 
 5459         psize = atop(end - start);
 5460         mpte = NULL;
 5461         m = m_start;
 5462         lock = NULL;
 5463         PMAP_LOCK(pmap);
 5464         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
 5465                 va = start + ptoa(diff);
 5466                 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
 5467                     m->psind == 1 && pmap_ps_enabled(pmap) &&
 5468                     pmap_enter_2mpage(pmap, va, m, prot, &lock))
 5469                         m = &m[NBPDR / PAGE_SIZE - 1];
 5470                 else
 5471                         mpte = pmap_enter_quick_locked(pmap, va, m, prot,
 5472                             mpte, &lock);
 5473                 m = TAILQ_NEXT(m, listq);
 5474         }
 5475         if (lock != NULL)
 5476                 rw_wunlock(lock);
 5477         PMAP_UNLOCK(pmap);
 5478 }
 5479 
 5480 /*
 5481  * this code makes some *MAJOR* assumptions:
 5482  * 1. Current pmap & pmap exists.
 5483  * 2. Not wired.
 5484  * 3. Read access.
 5485  * 4. No page table pages.
 5486  * but is *MUCH* faster than pmap_enter...
 5487  */
 5488 
 5489 void
 5490 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
 5491 {
 5492         struct rwlock *lock;
 5493 
 5494         lock = NULL;
 5495         PMAP_LOCK(pmap);
 5496         (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
 5497         if (lock != NULL)
 5498                 rw_wunlock(lock);
 5499         PMAP_UNLOCK(pmap);
 5500 }
 5501 
 5502 static vm_page_t
 5503 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
 5504     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
 5505 {
 5506         struct spglist free;
 5507         pt_entry_t newpte, *pte, PG_V;
 5508 
 5509         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
 5510             (m->oflags & VPO_UNMANAGED) != 0,
 5511             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
 5512         PG_V = pmap_valid_bit(pmap);
 5513         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5514 
 5515         /*
 5516          * In the case that a page table page is not
 5517          * resident, we are creating it here.
 5518          */
 5519         if (va < VM_MAXUSER_ADDRESS) {
 5520                 vm_pindex_t ptepindex;
 5521                 pd_entry_t *ptepa;
 5522 
 5523                 /*
 5524                  * Calculate pagetable page index
 5525                  */
 5526                 ptepindex = pmap_pde_pindex(va);
 5527                 if (mpte && (mpte->pindex == ptepindex)) {
 5528                         mpte->wire_count++;
 5529                 } else {
 5530                         /*
 5531                          * Get the page directory entry
 5532                          */
 5533                         ptepa = pmap_pde(pmap, va);
 5534 
 5535                         /*
 5536                          * If the page table page is mapped, we just increment
 5537                          * the hold count, and activate it.  Otherwise, we
 5538                          * attempt to allocate a page table page.  If this
 5539                          * attempt fails, we don't retry.  Instead, we give up.
 5540                          */
 5541                         if (ptepa && (*ptepa & PG_V) != 0) {
 5542                                 if (*ptepa & PG_PS)
 5543                                         return (NULL);
 5544                                 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
 5545                                 mpte->wire_count++;
 5546                         } else {
 5547                                 /*
 5548                                  * Pass NULL instead of the PV list lock
 5549                                  * pointer, because we don't intend to sleep.
 5550                                  */
 5551                                 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
 5552                                 if (mpte == NULL)
 5553                                         return (mpte);
 5554                         }
 5555                 }
 5556                 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
 5557                 pte = &pte[pmap_pte_index(va)];
 5558         } else {
 5559                 mpte = NULL;
 5560                 pte = vtopte(va);
 5561         }
 5562         if (*pte) {
 5563                 if (mpte != NULL) {
 5564                         mpte->wire_count--;
 5565                         mpte = NULL;
 5566                 }
 5567                 return (mpte);
 5568         }
 5569 
 5570         /*
 5571          * Enter on the PV list if part of our managed memory.
 5572          */
 5573         if ((m->oflags & VPO_UNMANAGED) == 0 &&
 5574             !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
 5575                 if (mpte != NULL) {
 5576                         SLIST_INIT(&free);
 5577                         if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
 5578                                 /*
 5579                                  * Although "va" is not mapped, paging-
 5580                                  * structure caches could nonetheless have
 5581                                  * entries that refer to the freed page table
 5582                                  * pages.  Invalidate those entries.
 5583                                  */
 5584                                 pmap_invalidate_page(pmap, va);
 5585                                 vm_page_free_pages_toq(&free, true);
 5586                         }
 5587                         mpte = NULL;
 5588                 }
 5589                 return (mpte);
 5590         }
 5591 
 5592         /*
 5593          * Increment counters
 5594          */
 5595         pmap_resident_count_inc(pmap, 1);
 5596 
 5597         newpte = VM_PAGE_TO_PHYS(m) | PG_V |
 5598             pmap_cache_bits(pmap, m->md.pat_mode, 0);
 5599         if ((m->oflags & VPO_UNMANAGED) == 0)
 5600                 newpte |= PG_MANAGED;
 5601         if ((prot & VM_PROT_EXECUTE) == 0)
 5602                 newpte |= pg_nx;
 5603         if (va < VM_MAXUSER_ADDRESS)
 5604                 newpte |= PG_U | pmap_pkru_get(pmap, va);
 5605         pte_store(pte, newpte);
 5606         return (mpte);
 5607 }
 5608 
 5609 /*
 5610  * Make a temporary mapping for a physical address.  This is only intended
 5611  * to be used for panic dumps.
 5612  */
 5613 void *
 5614 pmap_kenter_temporary(vm_paddr_t pa, int i)
 5615 {
 5616         vm_offset_t va;
 5617 
 5618         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
 5619         pmap_kenter(va, pa);
 5620         invlpg(va);
 5621         return ((void *)crashdumpmap);
 5622 }
 5623 
 5624 /*
 5625  * This code maps large physical mmap regions into the
 5626  * processor address space.  Note that some shortcuts
 5627  * are taken, but the code works.
 5628  */
 5629 void
 5630 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
 5631     vm_pindex_t pindex, vm_size_t size)
 5632 {
 5633         pd_entry_t *pde;
 5634         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
 5635         vm_paddr_t pa, ptepa;
 5636         vm_page_t p, pdpg;
 5637         int pat_mode;
 5638 
 5639         PG_A = pmap_accessed_bit(pmap);
 5640         PG_M = pmap_modified_bit(pmap);
 5641         PG_V = pmap_valid_bit(pmap);
 5642         PG_RW = pmap_rw_bit(pmap);
 5643 
 5644         VM_OBJECT_ASSERT_WLOCKED(object);
 5645         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
 5646             ("pmap_object_init_pt: non-device object"));
 5647         if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
 5648                 if (!pmap_ps_enabled(pmap))
 5649                         return;
 5650                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
 5651                         return;
 5652                 p = vm_page_lookup(object, pindex);
 5653                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
 5654                     ("pmap_object_init_pt: invalid page %p", p));
 5655                 pat_mode = p->md.pat_mode;
 5656 
 5657                 /*
 5658                  * Abort the mapping if the first page is not physically
 5659                  * aligned to a 2MB page boundary.
 5660                  */
 5661                 ptepa = VM_PAGE_TO_PHYS(p);
 5662                 if (ptepa & (NBPDR - 1))
 5663                         return;
 5664 
 5665                 /*
 5666                  * Skip the first page.  Abort the mapping if the rest of
 5667                  * the pages are not physically contiguous or have differing
 5668                  * memory attributes.
 5669                  */
 5670                 p = TAILQ_NEXT(p, listq);
 5671                 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
 5672                     pa += PAGE_SIZE) {
 5673                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
 5674                             ("pmap_object_init_pt: invalid page %p", p));
 5675                         if (pa != VM_PAGE_TO_PHYS(p) ||
 5676                             pat_mode != p->md.pat_mode)
 5677                                 return;
 5678                         p = TAILQ_NEXT(p, listq);
 5679                 }
 5680 
 5681                 /*
 5682                  * Map using 2MB pages.  Since "ptepa" is 2M aligned and
 5683                  * "size" is a multiple of 2M, adding the PAT setting to "pa"
 5684                  * will not affect the termination of this loop.
 5685                  */ 
 5686                 PMAP_LOCK(pmap);
 5687                 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
 5688                     pa < ptepa + size; pa += NBPDR) {
 5689                         pdpg = pmap_allocpde(pmap, addr, NULL);
 5690                         if (pdpg == NULL) {
 5691                                 /*
 5692                                  * The creation of mappings below is only an
 5693                                  * optimization.  If a page directory page
 5694                                  * cannot be allocated without blocking,
 5695                                  * continue on to the next mapping rather than
 5696                                  * blocking.
 5697                                  */
 5698                                 addr += NBPDR;
 5699                                 continue;
 5700                         }
 5701                         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
 5702                         pde = &pde[pmap_pde_index(addr)];
 5703                         if ((*pde & PG_V) == 0) {
 5704                                 pde_store(pde, pa | PG_PS | PG_M | PG_A |
 5705                                     PG_U | PG_RW | PG_V);
 5706                                 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
 5707                                 atomic_add_long(&pmap_pde_mappings, 1);
 5708                         } else {
 5709                                 /* Continue on if the PDE is already valid. */
 5710                                 pdpg->wire_count--;
 5711                                 KASSERT(pdpg->wire_count > 0,
 5712                                     ("pmap_object_init_pt: missing reference "
 5713                                     "to page directory page, va: 0x%lx", addr));
 5714                         }
 5715                         addr += NBPDR;
 5716                 }
 5717                 PMAP_UNLOCK(pmap);
 5718         }
 5719 }
 5720 
 5721 /*
 5722  *      Clear the wired attribute from the mappings for the specified range of
 5723  *      addresses in the given pmap.  Every valid mapping within that range
 5724  *      must have the wired attribute set.  In contrast, invalid mappings
 5725  *      cannot have the wired attribute set, so they are ignored.
 5726  *
 5727  *      The wired attribute of the page table entry is not a hardware
 5728  *      feature, so there is no need to invalidate any TLB entries.
 5729  *      Since pmap_demote_pde() for the wired entry must never fail,
 5730  *      pmap_delayed_invl_started()/finished() calls around the
 5731  *      function are not needed.
 5732  */
 5733 void
 5734 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 5735 {
 5736         vm_offset_t va_next;
 5737         pml4_entry_t *pml4e;
 5738         pdp_entry_t *pdpe;
 5739         pd_entry_t *pde;
 5740         pt_entry_t *pte, PG_V;
 5741 
 5742         PG_V = pmap_valid_bit(pmap);
 5743         PMAP_LOCK(pmap);
 5744         for (; sva < eva; sva = va_next) {
 5745                 pml4e = pmap_pml4e(pmap, sva);
 5746                 if ((*pml4e & PG_V) == 0) {
 5747                         va_next = (sva + NBPML4) & ~PML4MASK;
 5748                         if (va_next < sva)
 5749                                 va_next = eva;
 5750                         continue;
 5751                 }
 5752                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
 5753                 if ((*pdpe & PG_V) == 0) {
 5754                         va_next = (sva + NBPDP) & ~PDPMASK;
 5755                         if (va_next < sva)
 5756                                 va_next = eva;
 5757                         continue;
 5758                 }
 5759                 va_next = (sva + NBPDR) & ~PDRMASK;
 5760                 if (va_next < sva)
 5761                         va_next = eva;
 5762                 pde = pmap_pdpe_to_pde(pdpe, sva);
 5763                 if ((*pde & PG_V) == 0)
 5764                         continue;
 5765                 if ((*pde & PG_PS) != 0) {
 5766                         if ((*pde & PG_W) == 0)
 5767                                 panic("pmap_unwire: pde %#jx is missing PG_W",
 5768                                     (uintmax_t)*pde);
 5769 
 5770                         /*
 5771                          * Are we unwiring the entire large page?  If not,
 5772                          * demote the mapping and fall through.
 5773                          */
 5774                         if (sva + NBPDR == va_next && eva >= va_next) {
 5775                                 atomic_clear_long(pde, PG_W);
 5776                                 pmap->pm_stats.wired_count -= NBPDR /
 5777                                     PAGE_SIZE;
 5778                                 continue;
 5779                         } else if (!pmap_demote_pde(pmap, pde, sva))
 5780                                 panic("pmap_unwire: demotion failed");
 5781                 }
 5782                 if (va_next > eva)
 5783                         va_next = eva;
 5784                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
 5785                     sva += PAGE_SIZE) {
 5786                         if ((*pte & PG_V) == 0)
 5787                                 continue;
 5788                         if ((*pte & PG_W) == 0)
 5789                                 panic("pmap_unwire: pte %#jx is missing PG_W",
 5790                                     (uintmax_t)*pte);
 5791 
 5792                         /*
 5793                          * PG_W must be cleared atomically.  Although the pmap
 5794                          * lock synchronizes access to PG_W, another processor
 5795                          * could be setting PG_M and/or PG_A concurrently.
 5796                          */
 5797                         atomic_clear_long(pte, PG_W);
 5798                         pmap->pm_stats.wired_count--;
 5799                 }
 5800         }
 5801         PMAP_UNLOCK(pmap);
 5802 }
 5803 
 5804 /*
 5805  *      Copy the range specified by src_addr/len
 5806  *      from the source map to the range dst_addr/len
 5807  *      in the destination map.
 5808  *
 5809  *      This routine is only advisory and need not do anything.
 5810  */
 5811 
 5812 void
 5813 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
 5814     vm_offset_t src_addr)
 5815 {
 5816         struct rwlock *lock;
 5817         struct spglist free;
 5818         vm_offset_t addr;
 5819         vm_offset_t end_addr = src_addr + len;
 5820         vm_offset_t va_next;
 5821         vm_page_t dst_pdpg, dstmpte, srcmpte;
 5822         pt_entry_t PG_A, PG_M, PG_V;
 5823 
 5824         if (dst_addr != src_addr)
 5825                 return;
 5826 
 5827         if (dst_pmap->pm_type != src_pmap->pm_type)
 5828                 return;
 5829 
 5830         /*
 5831          * EPT page table entries that require emulation of A/D bits are
 5832          * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
 5833          * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
 5834          * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
 5835          * implementations flag an EPT misconfiguration for exec-only
 5836          * mappings we skip this function entirely for emulated pmaps.
 5837          */
 5838         if (pmap_emulate_ad_bits(dst_pmap))
 5839                 return;
 5840 
 5841         lock = NULL;
 5842         if (dst_pmap < src_pmap) {
 5843                 PMAP_LOCK(dst_pmap);
 5844                 PMAP_LOCK(src_pmap);
 5845         } else {
 5846                 PMAP_LOCK(src_pmap);
 5847                 PMAP_LOCK(dst_pmap);
 5848         }
 5849 
 5850         PG_A = pmap_accessed_bit(dst_pmap);
 5851         PG_M = pmap_modified_bit(dst_pmap);
 5852         PG_V = pmap_valid_bit(dst_pmap);
 5853 
 5854         for (addr = src_addr; addr < end_addr; addr = va_next) {
 5855                 pt_entry_t *src_pte, *dst_pte;
 5856                 pml4_entry_t *pml4e;
 5857                 pdp_entry_t *pdpe;
 5858                 pd_entry_t srcptepaddr, *pde;
 5859 
 5860                 KASSERT(addr < UPT_MIN_ADDRESS,
 5861                     ("pmap_copy: invalid to pmap_copy page tables"));
 5862 
 5863                 pml4e = pmap_pml4e(src_pmap, addr);
 5864                 if ((*pml4e & PG_V) == 0) {
 5865                         va_next = (addr + NBPML4) & ~PML4MASK;
 5866                         if (va_next < addr)
 5867                                 va_next = end_addr;
 5868                         continue;
 5869                 }
 5870 
 5871                 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
 5872                 if ((*pdpe & PG_V) == 0) {
 5873                         va_next = (addr + NBPDP) & ~PDPMASK;
 5874                         if (va_next < addr)
 5875                                 va_next = end_addr;
 5876                         continue;
 5877                 }
 5878 
 5879                 va_next = (addr + NBPDR) & ~PDRMASK;
 5880                 if (va_next < addr)
 5881                         va_next = end_addr;
 5882 
 5883                 pde = pmap_pdpe_to_pde(pdpe, addr);
 5884                 srcptepaddr = *pde;
 5885                 if (srcptepaddr == 0)
 5886                         continue;
 5887                         
 5888                 if (srcptepaddr & PG_PS) {
 5889                         if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
 5890                                 continue;
 5891                         dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
 5892                         if (dst_pdpg == NULL)
 5893                                 break;
 5894                         pde = (pd_entry_t *)
 5895                             PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
 5896                         pde = &pde[pmap_pde_index(addr)];
 5897                         if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
 5898                             pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
 5899                             PMAP_ENTER_NORECLAIM, &lock))) {
 5900                                 *pde = srcptepaddr & ~PG_W;
 5901                                 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
 5902                                 atomic_add_long(&pmap_pde_mappings, 1);
 5903                         } else
 5904                                 dst_pdpg->wire_count--;
 5905                         continue;
 5906                 }
 5907 
 5908                 srcptepaddr &= PG_FRAME;
 5909                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
 5910                 KASSERT(srcmpte->wire_count > 0,
 5911                     ("pmap_copy: source page table page is unused"));
 5912 
 5913                 if (va_next > end_addr)
 5914                         va_next = end_addr;
 5915 
 5916                 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
 5917                 src_pte = &src_pte[pmap_pte_index(addr)];
 5918                 dstmpte = NULL;
 5919                 while (addr < va_next) {
 5920                         pt_entry_t ptetemp;
 5921                         ptetemp = *src_pte;
 5922                         /*
 5923                          * we only virtual copy managed pages
 5924                          */
 5925                         if ((ptetemp & PG_MANAGED) != 0) {
 5926                                 if (dstmpte != NULL &&
 5927                                     dstmpte->pindex == pmap_pde_pindex(addr))
 5928                                         dstmpte->wire_count++;
 5929                                 else if ((dstmpte = pmap_allocpte(dst_pmap,
 5930                                     addr, NULL)) == NULL)
 5931                                         goto out;
 5932                                 dst_pte = (pt_entry_t *)
 5933                                     PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
 5934                                 dst_pte = &dst_pte[pmap_pte_index(addr)];
 5935                                 if (*dst_pte == 0 &&
 5936                                     pmap_try_insert_pv_entry(dst_pmap, addr,
 5937                                     PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
 5938                                     &lock)) {
 5939                                         /*
 5940                                          * Clear the wired, modified, and
 5941                                          * accessed (referenced) bits
 5942                                          * during the copy.
 5943                                          */
 5944                                         *dst_pte = ptetemp & ~(PG_W | PG_M |
 5945                                             PG_A);
 5946                                         pmap_resident_count_inc(dst_pmap, 1);
 5947                                 } else {
 5948                                         SLIST_INIT(&free);
 5949                                         if (pmap_unwire_ptp(dst_pmap, addr,
 5950                                             dstmpte, &free)) {
 5951                                                 /*
 5952                                                  * Although "addr" is not
 5953                                                  * mapped, paging-structure
 5954                                                  * caches could nonetheless
 5955                                                  * have entries that refer to
 5956                                                  * the freed page table pages.
 5957                                                  * Invalidate those entries.
 5958                                                  */
 5959                                                 pmap_invalidate_page(dst_pmap,
 5960                                                     addr);
 5961                                                 vm_page_free_pages_toq(&free,
 5962                                                     true);
 5963                                         }
 5964                                         goto out;
 5965                                 }
 5966                                 if (dstmpte->wire_count >= srcmpte->wire_count)
 5967                                         break;
 5968                         }
 5969                         addr += PAGE_SIZE;
 5970                         src_pte++;
 5971                 }
 5972         }
 5973 out:
 5974         if (lock != NULL)
 5975                 rw_wunlock(lock);
 5976         PMAP_UNLOCK(src_pmap);
 5977         PMAP_UNLOCK(dst_pmap);
 5978 }
 5979 
 5980 int
 5981 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
 5982 {
 5983         int error;
 5984 
 5985         if (dst_pmap->pm_type != src_pmap->pm_type ||
 5986             dst_pmap->pm_type != PT_X86 ||
 5987             (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
 5988                 return (0);
 5989         for (;;) {
 5990                 if (dst_pmap < src_pmap) {
 5991                         PMAP_LOCK(dst_pmap);
 5992                         PMAP_LOCK(src_pmap);
 5993                 } else {
 5994                         PMAP_LOCK(src_pmap);
 5995                         PMAP_LOCK(dst_pmap);
 5996                 }
 5997                 error = pmap_pkru_copy(dst_pmap, src_pmap);
 5998                 /* Clean up partial copy on failure due to no memory. */
 5999                 if (error == ENOMEM)
 6000                         pmap_pkru_deassign_all(dst_pmap);
 6001                 PMAP_UNLOCK(src_pmap);
 6002                 PMAP_UNLOCK(dst_pmap);
 6003                 if (error != ENOMEM)
 6004                         break;
 6005                 vm_wait(NULL);
 6006         }
 6007         return (error);
 6008 }
 6009 
 6010 /*
 6011  * Zero the specified hardware page.
 6012  */
 6013 void
 6014 pmap_zero_page(vm_page_t m)
 6015 {
 6016         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
 6017 
 6018         pagezero((void *)va);
 6019 }
 6020 
 6021 /*
 6022  * Zero an an area within a single hardware page.  off and size must not
 6023  * cover an area beyond a single hardware page.
 6024  */
 6025 void
 6026 pmap_zero_page_area(vm_page_t m, int off, int size)
 6027 {
 6028         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
 6029 
 6030         if (off == 0 && size == PAGE_SIZE)
 6031                 pagezero((void *)va);
 6032         else
 6033                 bzero((char *)va + off, size);
 6034 }
 6035 
 6036 /*
 6037  * Copy 1 specified hardware page to another.
 6038  */
 6039 void
 6040 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
 6041 {
 6042         vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
 6043         vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
 6044 
 6045         pagecopy((void *)src, (void *)dst);
 6046 }
 6047 
 6048 int unmapped_buf_allowed = 1;
 6049 
 6050 void
 6051 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
 6052     vm_offset_t b_offset, int xfersize)
 6053 {
 6054         void *a_cp, *b_cp;
 6055         vm_page_t pages[2];
 6056         vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
 6057         int cnt;
 6058         boolean_t mapped;
 6059 
 6060         while (xfersize > 0) {
 6061                 a_pg_offset = a_offset & PAGE_MASK;
 6062                 pages[0] = ma[a_offset >> PAGE_SHIFT];
 6063                 b_pg_offset = b_offset & PAGE_MASK;
 6064                 pages[1] = mb[b_offset >> PAGE_SHIFT];
 6065                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
 6066                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
 6067                 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
 6068                 a_cp = (char *)vaddr[0] + a_pg_offset;
 6069                 b_cp = (char *)vaddr[1] + b_pg_offset;
 6070                 bcopy(a_cp, b_cp, cnt);
 6071                 if (__predict_false(mapped))
 6072                         pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
 6073                 a_offset += cnt;
 6074                 b_offset += cnt;
 6075                 xfersize -= cnt;
 6076         }
 6077 }
 6078 
 6079 /*
 6080  * Returns true if the pmap's pv is one of the first
 6081  * 16 pvs linked to from this page.  This count may
 6082  * be changed upwards or downwards in the future; it
 6083  * is only necessary that true be returned for a small
 6084  * subset of pmaps for proper page aging.
 6085  */
 6086 boolean_t
 6087 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
 6088 {
 6089         struct md_page *pvh;
 6090         struct rwlock *lock;
 6091         pv_entry_t pv;
 6092         int loops = 0;
 6093         boolean_t rv;
 6094 
 6095         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 6096             ("pmap_page_exists_quick: page %p is not managed", m));
 6097         rv = FALSE;
 6098         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 6099         rw_rlock(lock);
 6100         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
 6101                 if (PV_PMAP(pv) == pmap) {
 6102                         rv = TRUE;
 6103                         break;
 6104                 }
 6105                 loops++;
 6106                 if (loops >= 16)
 6107                         break;
 6108         }
 6109         if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
 6110                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 6111                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
 6112                         if (PV_PMAP(pv) == pmap) {
 6113                                 rv = TRUE;
 6114                                 break;
 6115                         }
 6116                         loops++;
 6117                         if (loops >= 16)
 6118                                 break;
 6119                 }
 6120         }
 6121         rw_runlock(lock);
 6122         return (rv);
 6123 }
 6124 
 6125 /*
 6126  *      pmap_page_wired_mappings:
 6127  *
 6128  *      Return the number of managed mappings to the given physical page
 6129  *      that are wired.
 6130  */
 6131 int
 6132 pmap_page_wired_mappings(vm_page_t m)
 6133 {
 6134         struct rwlock *lock;
 6135         struct md_page *pvh;
 6136         pmap_t pmap;
 6137         pt_entry_t *pte;
 6138         pv_entry_t pv;
 6139         int count, md_gen, pvh_gen;
 6140 
 6141         if ((m->oflags & VPO_UNMANAGED) != 0)
 6142                 return (0);
 6143         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 6144         rw_rlock(lock);
 6145 restart:
 6146         count = 0;
 6147         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
 6148                 pmap = PV_PMAP(pv);
 6149                 if (!PMAP_TRYLOCK(pmap)) {
 6150                         md_gen = m->md.pv_gen;
 6151                         rw_runlock(lock);
 6152                         PMAP_LOCK(pmap);
 6153                         rw_rlock(lock);
 6154                         if (md_gen != m->md.pv_gen) {
 6155                                 PMAP_UNLOCK(pmap);
 6156                                 goto restart;
 6157                         }
 6158                 }
 6159                 pte = pmap_pte(pmap, pv->pv_va);
 6160                 if ((*pte & PG_W) != 0)
 6161                         count++;
 6162                 PMAP_UNLOCK(pmap);
 6163         }
 6164         if ((m->flags & PG_FICTITIOUS) == 0) {
 6165                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 6166                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
 6167                         pmap = PV_PMAP(pv);
 6168                         if (!PMAP_TRYLOCK(pmap)) {
 6169                                 md_gen = m->md.pv_gen;
 6170                                 pvh_gen = pvh->pv_gen;
 6171                                 rw_runlock(lock);
 6172                                 PMAP_LOCK(pmap);
 6173                                 rw_rlock(lock);
 6174                                 if (md_gen != m->md.pv_gen ||
 6175                                     pvh_gen != pvh->pv_gen) {
 6176                                         PMAP_UNLOCK(pmap);
 6177                                         goto restart;
 6178                                 }
 6179                         }
 6180                         pte = pmap_pde(pmap, pv->pv_va);
 6181                         if ((*pte & PG_W) != 0)
 6182                                 count++;
 6183                         PMAP_UNLOCK(pmap);
 6184                 }
 6185         }
 6186         rw_runlock(lock);
 6187         return (count);
 6188 }
 6189 
 6190 /*
 6191  * Returns TRUE if the given page is mapped individually or as part of
 6192  * a 2mpage.  Otherwise, returns FALSE.
 6193  */
 6194 boolean_t
 6195 pmap_page_is_mapped(vm_page_t m)
 6196 {
 6197         struct rwlock *lock;
 6198         boolean_t rv;
 6199 
 6200         if ((m->oflags & VPO_UNMANAGED) != 0)
 6201                 return (FALSE);
 6202         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 6203         rw_rlock(lock);
 6204         rv = !TAILQ_EMPTY(&m->md.pv_list) ||
 6205             ((m->flags & PG_FICTITIOUS) == 0 &&
 6206             !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
 6207         rw_runlock(lock);
 6208         return (rv);
 6209 }
 6210 
 6211 /*
 6212  * Destroy all managed, non-wired mappings in the given user-space
 6213  * pmap.  This pmap cannot be active on any processor besides the
 6214  * caller.
 6215  *
 6216  * This function cannot be applied to the kernel pmap.  Moreover, it
 6217  * is not intended for general use.  It is only to be used during
 6218  * process termination.  Consequently, it can be implemented in ways
 6219  * that make it faster than pmap_remove().  First, it can more quickly
 6220  * destroy mappings by iterating over the pmap's collection of PV
 6221  * entries, rather than searching the page table.  Second, it doesn't
 6222  * have to test and clear the page table entries atomically, because
 6223  * no processor is currently accessing the user address space.  In
 6224  * particular, a page table entry's dirty bit won't change state once
 6225  * this function starts.
 6226  *
 6227  * Although this function destroys all of the pmap's managed,
 6228  * non-wired mappings, it can delay and batch the invalidation of TLB
 6229  * entries without calling pmap_delayed_invl_started() and
 6230  * pmap_delayed_invl_finished().  Because the pmap is not active on
 6231  * any other processor, none of these TLB entries will ever be used
 6232  * before their eventual invalidation.  Consequently, there is no need
 6233  * for either pmap_remove_all() or pmap_remove_write() to wait for
 6234  * that eventual TLB invalidation.
 6235  */
 6236 void
 6237 pmap_remove_pages(pmap_t pmap)
 6238 {
 6239         pd_entry_t ptepde;
 6240         pt_entry_t *pte, tpte;
 6241         pt_entry_t PG_M, PG_RW, PG_V;
 6242         struct spglist free;
 6243         vm_page_t m, mpte, mt;
 6244         pv_entry_t pv;
 6245         struct md_page *pvh;
 6246         struct pv_chunk *pc, *npc;
 6247         struct rwlock *lock;
 6248         int64_t bit;
 6249         uint64_t inuse, bitmask;
 6250         int allfree, field, freed, idx;
 6251         boolean_t superpage;
 6252         vm_paddr_t pa;
 6253 
 6254         /*
 6255          * Assert that the given pmap is only active on the current
 6256          * CPU.  Unfortunately, we cannot block another CPU from
 6257          * activating the pmap while this function is executing.
 6258          */
 6259         KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
 6260 #ifdef INVARIANTS
 6261         {
 6262                 cpuset_t other_cpus;
 6263 
 6264                 other_cpus = all_cpus;
 6265                 critical_enter();
 6266                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
 6267                 CPU_AND(&other_cpus, &pmap->pm_active);
 6268                 critical_exit();
 6269                 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
 6270         }
 6271 #endif
 6272 
 6273         lock = NULL;
 6274         PG_M = pmap_modified_bit(pmap);
 6275         PG_V = pmap_valid_bit(pmap);
 6276         PG_RW = pmap_rw_bit(pmap);
 6277 
 6278         SLIST_INIT(&free);
 6279         PMAP_LOCK(pmap);
 6280         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
 6281                 allfree = 1;
 6282                 freed = 0;
 6283                 for (field = 0; field < _NPCM; field++) {
 6284                         inuse = ~pc->pc_map[field] & pc_freemask[field];
 6285                         while (inuse != 0) {
 6286                                 bit = bsfq(inuse);
 6287                                 bitmask = 1UL << bit;
 6288                                 idx = field * 64 + bit;
 6289                                 pv = &pc->pc_pventry[idx];
 6290                                 inuse &= ~bitmask;
 6291 
 6292                                 pte = pmap_pdpe(pmap, pv->pv_va);
 6293                                 ptepde = *pte;
 6294                                 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
 6295                                 tpte = *pte;
 6296                                 if ((tpte & (PG_PS | PG_V)) == PG_V) {
 6297                                         superpage = FALSE;
 6298                                         ptepde = tpte;
 6299                                         pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
 6300                                             PG_FRAME);
 6301                                         pte = &pte[pmap_pte_index(pv->pv_va)];
 6302                                         tpte = *pte;
 6303                                 } else {
 6304                                         /*
 6305                                          * Keep track whether 'tpte' is a
 6306                                          * superpage explicitly instead of
 6307                                          * relying on PG_PS being set.
 6308                                          *
 6309                                          * This is because PG_PS is numerically
 6310                                          * identical to PG_PTE_PAT and thus a
 6311                                          * regular page could be mistaken for
 6312                                          * a superpage.
 6313                                          */
 6314                                         superpage = TRUE;
 6315                                 }
 6316 
 6317                                 if ((tpte & PG_V) == 0) {
 6318                                         panic("bad pte va %lx pte %lx",
 6319                                             pv->pv_va, tpte);
 6320                                 }
 6321 
 6322 /*
 6323  * We cannot remove wired pages from a process' mapping at this time
 6324  */
 6325                                 if (tpte & PG_W) {
 6326                                         allfree = 0;
 6327                                         continue;
 6328                                 }
 6329 
 6330                                 if (superpage)
 6331                                         pa = tpte & PG_PS_FRAME;
 6332                                 else
 6333                                         pa = tpte & PG_FRAME;
 6334 
 6335                                 m = PHYS_TO_VM_PAGE(pa);
 6336                                 KASSERT(m->phys_addr == pa,
 6337                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
 6338                                     m, (uintmax_t)m->phys_addr,
 6339                                     (uintmax_t)tpte));
 6340 
 6341                                 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
 6342                                     m < &vm_page_array[vm_page_array_size],
 6343                                     ("pmap_remove_pages: bad tpte %#jx",
 6344                                     (uintmax_t)tpte));
 6345 
 6346                                 pte_clear(pte);
 6347 
 6348                                 /*
 6349                                  * Update the vm_page_t clean/reference bits.
 6350                                  */
 6351                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
 6352                                         if (superpage) {
 6353                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
 6354                                                         vm_page_dirty(mt);
 6355                                         } else
 6356                                                 vm_page_dirty(m);
 6357                                 }
 6358 
 6359                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
 6360 
 6361                                 /* Mark free */
 6362                                 pc->pc_map[field] |= bitmask;
 6363                                 if (superpage) {
 6364                                         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
 6365                                         pvh = pa_to_pvh(tpte & PG_PS_FRAME);
 6366                                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
 6367                                         pvh->pv_gen++;
 6368                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
 6369                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
 6370                                                         if ((mt->aflags & PGA_WRITEABLE) != 0 &&
 6371                                                             TAILQ_EMPTY(&mt->md.pv_list))
 6372                                                                 vm_page_aflag_clear(mt, PGA_WRITEABLE);
 6373                                         }
 6374                                         mpte = pmap_remove_pt_page(pmap, pv->pv_va);
 6375                                         if (mpte != NULL) {
 6376                                                 pmap_resident_count_dec(pmap, 1);
 6377                                                 KASSERT(mpte->wire_count == NPTEPG,
 6378                                                     ("pmap_remove_pages: pte page wire count error"));
 6379                                                 mpte->wire_count = 0;
 6380                                                 pmap_add_delayed_free_list(mpte, &free, FALSE);
 6381                                         }
 6382                                 } else {
 6383                                         pmap_resident_count_dec(pmap, 1);
 6384                                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 6385                                         m->md.pv_gen++;
 6386                                         if ((m->aflags & PGA_WRITEABLE) != 0 &&
 6387                                             TAILQ_EMPTY(&m->md.pv_list) &&
 6388                                             (m->flags & PG_FICTITIOUS) == 0) {
 6389                                                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 6390                                                 if (TAILQ_EMPTY(&pvh->pv_list))
 6391                                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
 6392                                         }
 6393                                 }
 6394                                 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
 6395                                 freed++;
 6396                         }
 6397                 }
 6398                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
 6399                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
 6400                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
 6401                 if (allfree) {
 6402                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 6403                         free_pv_chunk(pc);
 6404                 }
 6405         }
 6406         if (lock != NULL)
 6407                 rw_wunlock(lock);
 6408         pmap_invalidate_all(pmap);
 6409         pmap_pkru_deassign_all(pmap);
 6410         PMAP_UNLOCK(pmap);
 6411         vm_page_free_pages_toq(&free, true);
 6412 }
 6413 
 6414 static boolean_t
 6415 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
 6416 {
 6417         struct rwlock *lock;
 6418         pv_entry_t pv;
 6419         struct md_page *pvh;
 6420         pt_entry_t *pte, mask;
 6421         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
 6422         pmap_t pmap;
 6423         int md_gen, pvh_gen;
 6424         boolean_t rv;
 6425 
 6426         rv = FALSE;
 6427         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 6428         rw_rlock(lock);
 6429 restart:
 6430         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
 6431                 pmap = PV_PMAP(pv);
 6432                 if (!PMAP_TRYLOCK(pmap)) {
 6433                         md_gen = m->md.pv_gen;
 6434                         rw_runlock(lock);
 6435                         PMAP_LOCK(pmap);
 6436                         rw_rlock(lock);
 6437                         if (md_gen != m->md.pv_gen) {
 6438                                 PMAP_UNLOCK(pmap);
 6439                                 goto restart;
 6440                         }
 6441                 }
 6442                 pte = pmap_pte(pmap, pv->pv_va);
 6443                 mask = 0;
 6444                 if (modified) {
 6445                         PG_M = pmap_modified_bit(pmap);
 6446                         PG_RW = pmap_rw_bit(pmap);
 6447                         mask |= PG_RW | PG_M;
 6448                 }
 6449                 if (accessed) {
 6450                         PG_A = pmap_accessed_bit(pmap);
 6451                         PG_V = pmap_valid_bit(pmap);
 6452                         mask |= PG_V | PG_A;
 6453                 }
 6454                 rv = (*pte & mask) == mask;
 6455                 PMAP_UNLOCK(pmap);
 6456                 if (rv)
 6457                         goto out;
 6458         }
 6459         if ((m->flags & PG_FICTITIOUS) == 0) {
 6460                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 6461                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
 6462                         pmap = PV_PMAP(pv);
 6463                         if (!PMAP_TRYLOCK(pmap)) {
 6464                                 md_gen = m->md.pv_gen;
 6465                                 pvh_gen = pvh->pv_gen;
 6466                                 rw_runlock(lock);
 6467                                 PMAP_LOCK(pmap);
 6468                                 rw_rlock(lock);
 6469                                 if (md_gen != m->md.pv_gen ||
 6470                                     pvh_gen != pvh->pv_gen) {
 6471                                         PMAP_UNLOCK(pmap);
 6472                                         goto restart;
 6473                                 }
 6474                         }
 6475                         pte = pmap_pde(pmap, pv->pv_va);
 6476                         mask = 0;
 6477                         if (modified) {
 6478                                 PG_M = pmap_modified_bit(pmap);
 6479                                 PG_RW = pmap_rw_bit(pmap);
 6480                                 mask |= PG_RW | PG_M;
 6481                         }
 6482                         if (accessed) {
 6483                                 PG_A = pmap_accessed_bit(pmap);
 6484                                 PG_V = pmap_valid_bit(pmap);
 6485                                 mask |= PG_V | PG_A;
 6486                         }
 6487                         rv = (*pte & mask) == mask;
 6488                         PMAP_UNLOCK(pmap);
 6489                         if (rv)
 6490                                 goto out;
 6491                 }
 6492         }
 6493 out:
 6494         rw_runlock(lock);
 6495         return (rv);
 6496 }
 6497 
 6498 /*
 6499  *      pmap_is_modified:
 6500  *
 6501  *      Return whether or not the specified physical page was modified
 6502  *      in any physical maps.
 6503  */
 6504 boolean_t
 6505 pmap_is_modified(vm_page_t m)
 6506 {
 6507 
 6508         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 6509             ("pmap_is_modified: page %p is not managed", m));
 6510 
 6511         /*
 6512          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
 6513          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
 6514          * is clear, no PTEs can have PG_M set.
 6515          */
 6516         VM_OBJECT_ASSERT_WLOCKED(m->object);
 6517         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
 6518                 return (FALSE);
 6519         return (pmap_page_test_mappings(m, FALSE, TRUE));
 6520 }
 6521 
 6522 /*
 6523  *      pmap_is_prefaultable:
 6524  *
 6525  *      Return whether or not the specified virtual address is eligible
 6526  *      for prefault.
 6527  */
 6528 boolean_t
 6529 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
 6530 {
 6531         pd_entry_t *pde;
 6532         pt_entry_t *pte, PG_V;
 6533         boolean_t rv;
 6534 
 6535         PG_V = pmap_valid_bit(pmap);
 6536         rv = FALSE;
 6537         PMAP_LOCK(pmap);
 6538         pde = pmap_pde(pmap, addr);
 6539         if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
 6540                 pte = pmap_pde_to_pte(pde, addr);
 6541                 rv = (*pte & PG_V) == 0;
 6542         }
 6543         PMAP_UNLOCK(pmap);
 6544         return (rv);
 6545 }
 6546 
 6547 /*
 6548  *      pmap_is_referenced:
 6549  *
 6550  *      Return whether or not the specified physical page was referenced
 6551  *      in any physical maps.
 6552  */
 6553 boolean_t
 6554 pmap_is_referenced(vm_page_t m)
 6555 {
 6556 
 6557         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 6558             ("pmap_is_referenced: page %p is not managed", m));
 6559         return (pmap_page_test_mappings(m, TRUE, FALSE));
 6560 }
 6561 
 6562 /*
 6563  * Clear the write and modified bits in each of the given page's mappings.
 6564  */
 6565 void
 6566 pmap_remove_write(vm_page_t m)
 6567 {
 6568         struct md_page *pvh;
 6569         pmap_t pmap;
 6570         struct rwlock *lock;
 6571         pv_entry_t next_pv, pv;
 6572         pd_entry_t *pde;
 6573         pt_entry_t oldpte, *pte, PG_M, PG_RW;
 6574         vm_offset_t va;
 6575         int pvh_gen, md_gen;
 6576 
 6577         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 6578             ("pmap_remove_write: page %p is not managed", m));
 6579 
 6580         /*
 6581          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
 6582          * set by another thread while the object is locked.  Thus,
 6583          * if PGA_WRITEABLE is clear, no page table entries need updating.
 6584          */
 6585         VM_OBJECT_ASSERT_WLOCKED(m->object);
 6586         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
 6587                 return;
 6588         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 6589         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
 6590             pa_to_pvh(VM_PAGE_TO_PHYS(m));
 6591 retry_pv_loop:
 6592         rw_wlock(lock);
 6593         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
 6594                 pmap = PV_PMAP(pv);
 6595                 if (!PMAP_TRYLOCK(pmap)) {
 6596                         pvh_gen = pvh->pv_gen;
 6597                         rw_wunlock(lock);
 6598                         PMAP_LOCK(pmap);
 6599                         rw_wlock(lock);
 6600                         if (pvh_gen != pvh->pv_gen) {
 6601                                 PMAP_UNLOCK(pmap);
 6602                                 rw_wunlock(lock);
 6603                                 goto retry_pv_loop;
 6604                         }
 6605                 }
 6606                 PG_RW = pmap_rw_bit(pmap);
 6607                 va = pv->pv_va;
 6608                 pde = pmap_pde(pmap, va);
 6609                 if ((*pde & PG_RW) != 0)
 6610                         (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
 6611                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
 6612                     ("inconsistent pv lock %p %p for page %p",
 6613                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
 6614                 PMAP_UNLOCK(pmap);
 6615         }
 6616         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
 6617                 pmap = PV_PMAP(pv);
 6618                 if (!PMAP_TRYLOCK(pmap)) {
 6619                         pvh_gen = pvh->pv_gen;
 6620                         md_gen = m->md.pv_gen;
 6621                         rw_wunlock(lock);
 6622                         PMAP_LOCK(pmap);
 6623                         rw_wlock(lock);
 6624                         if (pvh_gen != pvh->pv_gen ||
 6625                             md_gen != m->md.pv_gen) {
 6626                                 PMAP_UNLOCK(pmap);
 6627                                 rw_wunlock(lock);
 6628                                 goto retry_pv_loop;
 6629                         }
 6630                 }
 6631                 PG_M = pmap_modified_bit(pmap);
 6632                 PG_RW = pmap_rw_bit(pmap);
 6633                 pde = pmap_pde(pmap, pv->pv_va);
 6634                 KASSERT((*pde & PG_PS) == 0,
 6635                     ("pmap_remove_write: found a 2mpage in page %p's pv list",
 6636                     m));
 6637                 pte = pmap_pde_to_pte(pde, pv->pv_va);
 6638 retry:
 6639                 oldpte = *pte;
 6640                 if (oldpte & PG_RW) {
 6641                         if (!atomic_cmpset_long(pte, oldpte, oldpte &
 6642                             ~(PG_RW | PG_M)))
 6643                                 goto retry;
 6644                         if ((oldpte & PG_M) != 0)
 6645                                 vm_page_dirty(m);
 6646                         pmap_invalidate_page(pmap, pv->pv_va);
 6647                 }
 6648                 PMAP_UNLOCK(pmap);
 6649         }
 6650         rw_wunlock(lock);
 6651         vm_page_aflag_clear(m, PGA_WRITEABLE);
 6652         pmap_delayed_invl_wait(m);
 6653 }
 6654 
 6655 static __inline boolean_t
 6656 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
 6657 {
 6658 
 6659         if (!pmap_emulate_ad_bits(pmap))
 6660                 return (TRUE);
 6661 
 6662         KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
 6663 
 6664         /*
 6665          * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
 6666          * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
 6667          * if the EPT_PG_WRITE bit is set.
 6668          */
 6669         if ((pte & EPT_PG_WRITE) != 0)
 6670                 return (FALSE);
 6671 
 6672         /*
 6673          * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
 6674          */
 6675         if ((pte & EPT_PG_EXECUTE) == 0 ||
 6676             ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
 6677                 return (TRUE);
 6678         else
 6679                 return (FALSE);
 6680 }
 6681 
 6682 /*
 6683  *      pmap_ts_referenced:
 6684  *
 6685  *      Return a count of reference bits for a page, clearing those bits.
 6686  *      It is not necessary for every reference bit to be cleared, but it
 6687  *      is necessary that 0 only be returned when there are truly no
 6688  *      reference bits set.
 6689  *
 6690  *      As an optimization, update the page's dirty field if a modified bit is
 6691  *      found while counting reference bits.  This opportunistic update can be
 6692  *      performed at low cost and can eliminate the need for some future calls
 6693  *      to pmap_is_modified().  However, since this function stops after
 6694  *      finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
 6695  *      dirty pages.  Those dirty pages will only be detected by a future call
 6696  *      to pmap_is_modified().
 6697  *
 6698  *      A DI block is not needed within this function, because
 6699  *      invalidations are performed before the PV list lock is
 6700  *      released.
 6701  */
 6702 int
 6703 pmap_ts_referenced(vm_page_t m)
 6704 {
 6705         struct md_page *pvh;
 6706         pv_entry_t pv, pvf;
 6707         pmap_t pmap;
 6708         struct rwlock *lock;
 6709         pd_entry_t oldpde, *pde;
 6710         pt_entry_t *pte, PG_A, PG_M, PG_RW;
 6711         vm_offset_t va;
 6712         vm_paddr_t pa;
 6713         int cleared, md_gen, not_cleared, pvh_gen;
 6714         struct spglist free;
 6715         boolean_t demoted;
 6716 
 6717         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 6718             ("pmap_ts_referenced: page %p is not managed", m));
 6719         SLIST_INIT(&free);
 6720         cleared = 0;
 6721         pa = VM_PAGE_TO_PHYS(m);
 6722         lock = PHYS_TO_PV_LIST_LOCK(pa);
 6723         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
 6724         rw_wlock(lock);
 6725 retry:
 6726         not_cleared = 0;
 6727         if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
 6728                 goto small_mappings;
 6729         pv = pvf;
 6730         do {
 6731                 if (pvf == NULL)
 6732                         pvf = pv;
 6733                 pmap = PV_PMAP(pv);
 6734                 if (!PMAP_TRYLOCK(pmap)) {
 6735                         pvh_gen = pvh->pv_gen;
 6736                         rw_wunlock(lock);
 6737                         PMAP_LOCK(pmap);
 6738                         rw_wlock(lock);
 6739                         if (pvh_gen != pvh->pv_gen) {
 6740                                 PMAP_UNLOCK(pmap);
 6741                                 goto retry;
 6742                         }
 6743                 }
 6744                 PG_A = pmap_accessed_bit(pmap);
 6745                 PG_M = pmap_modified_bit(pmap);
 6746                 PG_RW = pmap_rw_bit(pmap);
 6747                 va = pv->pv_va;
 6748                 pde = pmap_pde(pmap, pv->pv_va);
 6749                 oldpde = *pde;
 6750                 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
 6751                         /*
 6752                          * Although "oldpde" is mapping a 2MB page, because
 6753                          * this function is called at a 4KB page granularity,
 6754                          * we only update the 4KB page under test.
 6755                          */
 6756                         vm_page_dirty(m);
 6757                 }
 6758                 if ((oldpde & PG_A) != 0) {
 6759                         /*
 6760                          * Since this reference bit is shared by 512 4KB
 6761                          * pages, it should not be cleared every time it is
 6762                          * tested.  Apply a simple "hash" function on the
 6763                          * physical page number, the virtual superpage number,
 6764                          * and the pmap address to select one 4KB page out of
 6765                          * the 512 on which testing the reference bit will
 6766                          * result in clearing that reference bit.  This
 6767                          * function is designed to avoid the selection of the
 6768                          * same 4KB page for every 2MB page mapping.
 6769                          *
 6770                          * On demotion, a mapping that hasn't been referenced
 6771                          * is simply destroyed.  To avoid the possibility of a
 6772                          * subsequent page fault on a demoted wired mapping,
 6773                          * always leave its reference bit set.  Moreover,
 6774                          * since the superpage is wired, the current state of
 6775                          * its reference bit won't affect page replacement.
 6776                          */
 6777                         if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
 6778                             (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
 6779                             (oldpde & PG_W) == 0) {
 6780                                 if (safe_to_clear_referenced(pmap, oldpde)) {
 6781                                         atomic_clear_long(pde, PG_A);
 6782                                         pmap_invalidate_page(pmap, pv->pv_va);
 6783                                         demoted = FALSE;
 6784                                 } else if (pmap_demote_pde_locked(pmap, pde,
 6785                                     pv->pv_va, &lock)) {
 6786                                         /*
 6787                                          * Remove the mapping to a single page
 6788                                          * so that a subsequent access may
 6789                                          * repromote.  Since the underlying
 6790                                          * page table page is fully populated,
 6791                                          * this removal never frees a page
 6792                                          * table page.
 6793                                          */
 6794                                         demoted = TRUE;
 6795                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
 6796                                             PG_PS_FRAME);
 6797                                         pte = pmap_pde_to_pte(pde, va);
 6798                                         pmap_remove_pte(pmap, pte, va, *pde,
 6799                                             NULL, &lock);
 6800                                         pmap_invalidate_page(pmap, va);
 6801                                 } else
 6802                                         demoted = TRUE;
 6803 
 6804                                 if (demoted) {
 6805                                         /*
 6806                                          * The superpage mapping was removed
 6807                                          * entirely and therefore 'pv' is no
 6808                                          * longer valid.
 6809                                          */
 6810                                         if (pvf == pv)
 6811                                                 pvf = NULL;
 6812                                         pv = NULL;
 6813                                 }
 6814                                 cleared++;
 6815                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
 6816                                     ("inconsistent pv lock %p %p for page %p",
 6817                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
 6818                         } else
 6819                                 not_cleared++;
 6820                 }
 6821                 PMAP_UNLOCK(pmap);
 6822                 /* Rotate the PV list if it has more than one entry. */
 6823                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
 6824                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
 6825                         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
 6826                         pvh->pv_gen++;
 6827                 }
 6828                 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
 6829                         goto out;
 6830         } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
 6831 small_mappings:
 6832         if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
 6833                 goto out;
 6834         pv = pvf;
 6835         do {
 6836                 if (pvf == NULL)
 6837                         pvf = pv;
 6838                 pmap = PV_PMAP(pv);
 6839                 if (!PMAP_TRYLOCK(pmap)) {
 6840                         pvh_gen = pvh->pv_gen;
 6841                         md_gen = m->md.pv_gen;
 6842                         rw_wunlock(lock);
 6843                         PMAP_LOCK(pmap);
 6844                         rw_wlock(lock);
 6845                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
 6846                                 PMAP_UNLOCK(pmap);
 6847                                 goto retry;
 6848                         }
 6849                 }
 6850                 PG_A = pmap_accessed_bit(pmap);
 6851                 PG_M = pmap_modified_bit(pmap);
 6852                 PG_RW = pmap_rw_bit(pmap);
 6853                 pde = pmap_pde(pmap, pv->pv_va);
 6854                 KASSERT((*pde & PG_PS) == 0,
 6855                     ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
 6856                     m));
 6857                 pte = pmap_pde_to_pte(pde, pv->pv_va);
 6858                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 6859                         vm_page_dirty(m);
 6860                 if ((*pte & PG_A) != 0) {
 6861                         if (safe_to_clear_referenced(pmap, *pte)) {
 6862                                 atomic_clear_long(pte, PG_A);
 6863                                 pmap_invalidate_page(pmap, pv->pv_va);
 6864                                 cleared++;
 6865                         } else if ((*pte & PG_W) == 0) {
 6866                                 /*
 6867                                  * Wired pages cannot be paged out so
 6868                                  * doing accessed bit emulation for
 6869                                  * them is wasted effort. We do the
 6870                                  * hard work for unwired pages only.
 6871                                  */
 6872                                 pmap_remove_pte(pmap, pte, pv->pv_va,
 6873                                     *pde, &free, &lock);
 6874                                 pmap_invalidate_page(pmap, pv->pv_va);
 6875                                 cleared++;
 6876                                 if (pvf == pv)
 6877                                         pvf = NULL;
 6878                                 pv = NULL;
 6879                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
 6880                                     ("inconsistent pv lock %p %p for page %p",
 6881                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
 6882                         } else
 6883                                 not_cleared++;
 6884                 }
 6885                 PMAP_UNLOCK(pmap);
 6886                 /* Rotate the PV list if it has more than one entry. */
 6887                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
 6888                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 6889                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 6890                         m->md.pv_gen++;
 6891                 }
 6892         } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
 6893             not_cleared < PMAP_TS_REFERENCED_MAX);
 6894 out:
 6895         rw_wunlock(lock);
 6896