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: stable/12/sys/amd64/amd64/pmap.c 363500 2020-07-24 23:44:35Z mjg $");
   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_ddb.h"
  111 #include "opt_pmap.h"
  112 #include "opt_vm.h"
  113 
  114 #include <sys/param.h>
  115 #include <sys/bitstring.h>
  116 #include <sys/bus.h>
  117 #include <sys/systm.h>
  118 #include <sys/kernel.h>
  119 #include <sys/ktr.h>
  120 #include <sys/lock.h>
  121 #include <sys/malloc.h>
  122 #include <sys/mman.h>
  123 #include <sys/mutex.h>
  124 #include <sys/proc.h>
  125 #include <sys/rangeset.h>
  126 #include <sys/rwlock.h>
  127 #include <sys/sbuf.h>
  128 #include <sys/sx.h>
  129 #include <sys/turnstile.h>
  130 #include <sys/vmem.h>
  131 #include <sys/vmmeter.h>
  132 #include <sys/sched.h>
  133 #include <sys/sysctl.h>
  134 #include <sys/smp.h>
  135 #ifdef DDB
  136 #include <sys/kdb.h>
  137 #include <ddb/ddb.h>
  138 #endif
  139 
  140 #include <vm/vm.h>
  141 #include <vm/vm_param.h>
  142 #include <vm/vm_kern.h>
  143 #include <vm/vm_page.h>
  144 #include <vm/vm_map.h>
  145 #include <vm/vm_object.h>
  146 #include <vm/vm_extern.h>
  147 #include <vm/vm_pageout.h>
  148 #include <vm/vm_pager.h>
  149 #include <vm/vm_phys.h>
  150 #include <vm/vm_radix.h>
  151 #include <vm/vm_reserv.h>
  152 #include <vm/uma.h>
  153 
  154 #include <machine/intr_machdep.h>
  155 #include <x86/apicvar.h>
  156 #include <x86/ifunc.h>
  157 #include <machine/cpu.h>
  158 #include <machine/cputypes.h>
  159 #include <machine/md_var.h>
  160 #include <machine/pcb.h>
  161 #include <machine/specialreg.h>
  162 #ifdef SMP
  163 #include <machine/smp.h>
  164 #endif
  165 #include <machine/sysarch.h>
  166 #include <machine/tss.h>
  167 
  168 static __inline boolean_t
  169 pmap_type_guest(pmap_t pmap)
  170 {
  171 
  172         return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
  173 }
  174 
  175 static __inline boolean_t
  176 pmap_emulate_ad_bits(pmap_t pmap)
  177 {
  178 
  179         return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
  180 }
  181 
  182 static __inline pt_entry_t
  183 pmap_valid_bit(pmap_t pmap)
  184 {
  185         pt_entry_t mask;
  186 
  187         switch (pmap->pm_type) {
  188         case PT_X86:
  189         case PT_RVI:
  190                 mask = X86_PG_V;
  191                 break;
  192         case PT_EPT:
  193                 if (pmap_emulate_ad_bits(pmap))
  194                         mask = EPT_PG_EMUL_V;
  195                 else
  196                         mask = EPT_PG_READ;
  197                 break;
  198         default:
  199                 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
  200         }
  201 
  202         return (mask);
  203 }
  204 
  205 static __inline pt_entry_t
  206 pmap_rw_bit(pmap_t pmap)
  207 {
  208         pt_entry_t mask;
  209 
  210         switch (pmap->pm_type) {
  211         case PT_X86:
  212         case PT_RVI:
  213                 mask = X86_PG_RW;
  214                 break;
  215         case PT_EPT:
  216                 if (pmap_emulate_ad_bits(pmap))
  217                         mask = EPT_PG_EMUL_RW;
  218                 else
  219                         mask = EPT_PG_WRITE;
  220                 break;
  221         default:
  222                 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
  223         }
  224 
  225         return (mask);
  226 }
  227 
  228 static pt_entry_t pg_g;
  229 
  230 static __inline pt_entry_t
  231 pmap_global_bit(pmap_t pmap)
  232 {
  233         pt_entry_t mask;
  234 
  235         switch (pmap->pm_type) {
  236         case PT_X86:
  237                 mask = pg_g;
  238                 break;
  239         case PT_RVI:
  240         case PT_EPT:
  241                 mask = 0;
  242                 break;
  243         default:
  244                 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
  245         }
  246 
  247         return (mask);
  248 }
  249 
  250 static __inline pt_entry_t
  251 pmap_accessed_bit(pmap_t pmap)
  252 {
  253         pt_entry_t mask;
  254 
  255         switch (pmap->pm_type) {
  256         case PT_X86:
  257         case PT_RVI:
  258                 mask = X86_PG_A;
  259                 break;
  260         case PT_EPT:
  261                 if (pmap_emulate_ad_bits(pmap))
  262                         mask = EPT_PG_READ;
  263                 else
  264                         mask = EPT_PG_A;
  265                 break;
  266         default:
  267                 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
  268         }
  269 
  270         return (mask);
  271 }
  272 
  273 static __inline pt_entry_t
  274 pmap_modified_bit(pmap_t pmap)
  275 {
  276         pt_entry_t mask;
  277 
  278         switch (pmap->pm_type) {
  279         case PT_X86:
  280         case PT_RVI:
  281                 mask = X86_PG_M;
  282                 break;
  283         case PT_EPT:
  284                 if (pmap_emulate_ad_bits(pmap))
  285                         mask = EPT_PG_WRITE;
  286                 else
  287                         mask = EPT_PG_M;
  288                 break;
  289         default:
  290                 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
  291         }
  292 
  293         return (mask);
  294 }
  295 
  296 static __inline pt_entry_t
  297 pmap_pku_mask_bit(pmap_t pmap)
  298 {
  299 
  300         return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
  301 }
  302 
  303 #if !defined(DIAGNOSTIC)
  304 #ifdef __GNUC_GNU_INLINE__
  305 #define PMAP_INLINE     __attribute__((__gnu_inline__)) inline
  306 #else
  307 #define PMAP_INLINE     extern inline
  308 #endif
  309 #else
  310 #define PMAP_INLINE
  311 #endif
  312 
  313 #ifdef PV_STATS
  314 #define PV_STAT(x)      do { x ; } while (0)
  315 #else
  316 #define PV_STAT(x)      do { } while (0)
  317 #endif
  318 
  319 #define pa_index(pa)    ((pa) >> PDRSHIFT)
  320 #define pa_to_pvh(pa)   (&pv_table[pa_index(pa)])
  321 
  322 #define NPV_LIST_LOCKS  MAXCPU
  323 
  324 #define PHYS_TO_PV_LIST_LOCK(pa)        \
  325                         (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
  326 
  327 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)  do {    \
  328         struct rwlock **_lockp = (lockp);               \
  329         struct rwlock *_new_lock;                       \
  330                                                         \
  331         _new_lock = PHYS_TO_PV_LIST_LOCK(pa);           \
  332         if (_new_lock != *_lockp) {                     \
  333                 if (*_lockp != NULL)                    \
  334                         rw_wunlock(*_lockp);            \
  335                 *_lockp = _new_lock;                    \
  336                 rw_wlock(*_lockp);                      \
  337         }                                               \
  338 } while (0)
  339 
  340 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)        \
  341                         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
  342 
  343 #define RELEASE_PV_LIST_LOCK(lockp)             do {    \
  344         struct rwlock **_lockp = (lockp);               \
  345                                                         \
  346         if (*_lockp != NULL) {                          \
  347                 rw_wunlock(*_lockp);                    \
  348                 *_lockp = NULL;                         \
  349         }                                               \
  350 } while (0)
  351 
  352 #define VM_PAGE_TO_PV_LIST_LOCK(m)      \
  353                         PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
  354 
  355 struct pmap kernel_pmap_store;
  356 
  357 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
  358 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
  359 
  360 int nkpt;
  361 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
  362     "Number of kernel page table pages allocated on bootup");
  363 
  364 static int ndmpdp;
  365 vm_paddr_t dmaplimit;
  366 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
  367 pt_entry_t pg_nx;
  368 
  369 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
  370 
  371 /* Unused, kept for ABI stability on the stable branch. */
  372 static int pat_works = 1;
  373 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
  374     "Is page attribute table fully functional?");
  375 
  376 static int pg_ps_enabled = 1;
  377 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  378     &pg_ps_enabled, 0, "Are large page mappings enabled?");
  379 
  380 #define PAT_INDEX_SIZE  8
  381 static int pat_index[PAT_INDEX_SIZE];   /* cache mode to PAT index conversion */
  382 
  383 static u_int64_t        KPTphys;        /* phys addr of kernel level 1 */
  384 static u_int64_t        KPDphys;        /* phys addr of kernel level 2 */
  385 u_int64_t               KPDPphys;       /* phys addr of kernel level 3 */
  386 u_int64_t               KPML4phys;      /* phys addr of kernel level 4 */
  387 
  388 static u_int64_t        DMPDphys;       /* phys addr of direct mapped level 2 */
  389 static u_int64_t        DMPDPphys;      /* phys addr of direct mapped level 3 */
  390 static int              ndmpdpphys;     /* number of DMPDPphys pages */
  391 
  392 static vm_paddr_t       KERNend;        /* phys addr of end of bootstrap data */
  393 
  394 /*
  395  * pmap_mapdev support pre initialization (i.e. console)
  396  */
  397 #define PMAP_PREINIT_MAPPING_COUNT      8
  398 static struct pmap_preinit_mapping {
  399         vm_paddr_t      pa;
  400         vm_offset_t     va;
  401         vm_size_t       sz;
  402         int             mode;
  403 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
  404 static int pmap_initialized;
  405 
  406 /*
  407  * Data for the pv entry allocation mechanism.
  408  * Updates to pv_invl_gen are protected by the pv_list_locks[]
  409  * elements, but reads are not.
  410  */
  411 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
  412 static struct mtx __exclusive_cache_line pv_chunks_mutex;
  413 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
  414 static u_long pv_invl_gen[NPV_LIST_LOCKS];
  415 static struct md_page *pv_table;
  416 static struct md_page pv_dummy;
  417 
  418 /*
  419  * All those kernel PT submaps that BSD is so fond of
  420  */
  421 pt_entry_t *CMAP1 = NULL;
  422 caddr_t CADDR1 = 0;
  423 static vm_offset_t qframe = 0;
  424 static struct mtx qframe_mtx;
  425 
  426 static int pmap_flags = PMAP_PDE_SUPERPAGE;     /* flags for x86 pmaps */
  427 
  428 static vmem_t *large_vmem;
  429 static u_int lm_ents;
  430 #define PMAP_ADDRESS_IN_LARGEMAP(va)    ((va) >= LARGEMAP_MIN_ADDRESS && \
  431         (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
  432 
  433 int pmap_pcid_enabled = 1;
  434 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  435     &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
  436 int invpcid_works = 0;
  437 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
  438     "Is the invpcid instruction available ?");
  439 
  440 int __read_frequently pti = 0;
  441 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
  442     &pti, 0,
  443     "Page Table Isolation enabled");
  444 static vm_object_t pti_obj;
  445 static pml4_entry_t *pti_pml4;
  446 static vm_pindex_t pti_pg_idx;
  447 static bool pti_finalized;
  448 
  449 struct pmap_pkru_range {
  450         struct rs_el    pkru_rs_el;
  451         u_int           pkru_keyidx;
  452         int             pkru_flags;
  453 };
  454 
  455 static uma_zone_t pmap_pkru_ranges_zone;
  456 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  457 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
  458 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  459 static void *pkru_dup_range(void *ctx, void *data);
  460 static void pkru_free_range(void *ctx, void *node);
  461 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
  462 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
  463 static void pmap_pkru_deassign_all(pmap_t pmap);
  464 
  465 static int
  466 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
  467 {
  468         int i;
  469         uint64_t res;
  470 
  471         res = 0;
  472         CPU_FOREACH(i) {
  473                 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
  474         }
  475         return (sysctl_handle_64(oidp, &res, 0, req));
  476 }
  477 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RD |
  478     CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
  479     "Count of saved TLB context on switch");
  480 
  481 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
  482     LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
  483 static struct mtx invl_gen_mtx;
  484 /* Fake lock object to satisfy turnstiles interface. */
  485 static struct lock_object invl_gen_ts = {
  486         .lo_name = "invlts",
  487 };
  488 static struct pmap_invl_gen pmap_invl_gen_head = {
  489         .gen = 1,
  490         .next = NULL,
  491 };
  492 static u_long pmap_invl_gen = 1;
  493 static int pmap_invl_waiters;
  494 static struct callout pmap_invl_callout;
  495 static bool pmap_invl_callout_inited;
  496 
  497 #define PMAP_ASSERT_NOT_IN_DI() \
  498     KASSERT(pmap_not_in_di(), ("DI already started"))
  499 
  500 static bool
  501 pmap_di_locked(void)
  502 {
  503         int tun;
  504 
  505         if ((cpu_feature2 & CPUID2_CX16) == 0)
  506                 return (true);
  507         tun = 0;
  508         TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
  509         return (tun != 0);
  510 }
  511 
  512 static int
  513 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
  514 {
  515         int locked;
  516 
  517         locked = pmap_di_locked();
  518         return (sysctl_handle_int(oidp, &locked, 0, req));
  519 }
  520 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
  521     CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
  522     "Locked delayed invalidation");
  523 
  524 static bool pmap_not_in_di_l(void);
  525 static bool pmap_not_in_di_u(void);
  526 DEFINE_IFUNC(, bool, pmap_not_in_di, (void), static)
  527 {
  528 
  529         return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
  530 }
  531 
  532 static bool
  533 pmap_not_in_di_l(void)
  534 {
  535         struct pmap_invl_gen *invl_gen;
  536 
  537         invl_gen = &curthread->td_md.md_invl_gen;
  538         return (invl_gen->gen == 0);
  539 }
  540 
  541 static void
  542 pmap_thread_init_invl_gen_l(struct thread *td)
  543 {
  544         struct pmap_invl_gen *invl_gen;
  545 
  546         invl_gen = &td->td_md.md_invl_gen;
  547         invl_gen->gen = 0;
  548 }
  549 
  550 static void
  551 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
  552 {
  553         struct turnstile *ts;
  554 
  555         ts = turnstile_trywait(&invl_gen_ts);
  556         if (*m_gen > atomic_load_long(invl_gen))
  557                 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
  558         else
  559                 turnstile_cancel(ts);
  560 }
  561 
  562 static void
  563 pmap_delayed_invl_finish_unblock(u_long new_gen)
  564 {
  565         struct turnstile *ts;
  566 
  567         turnstile_chain_lock(&invl_gen_ts);
  568         ts = turnstile_lookup(&invl_gen_ts);
  569         if (new_gen != 0)
  570                 pmap_invl_gen = new_gen;
  571         if (ts != NULL) {
  572                 turnstile_broadcast(ts, TS_SHARED_QUEUE);
  573                 turnstile_unpend(ts);
  574         }
  575         turnstile_chain_unlock(&invl_gen_ts);
  576 }
  577 
  578 /*
  579  * Start a new Delayed Invalidation (DI) block of code, executed by
  580  * the current thread.  Within a DI block, the current thread may
  581  * destroy both the page table and PV list entries for a mapping and
  582  * then release the corresponding PV list lock before ensuring that
  583  * the mapping is flushed from the TLBs of any processors with the
  584  * pmap active.
  585  */
  586 static void
  587 pmap_delayed_invl_start_l(void)
  588 {
  589         struct pmap_invl_gen *invl_gen;
  590         u_long currgen;
  591 
  592         invl_gen = &curthread->td_md.md_invl_gen;
  593         PMAP_ASSERT_NOT_IN_DI();
  594         mtx_lock(&invl_gen_mtx);
  595         if (LIST_EMPTY(&pmap_invl_gen_tracker))
  596                 currgen = pmap_invl_gen;
  597         else
  598                 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
  599         invl_gen->gen = currgen + 1;
  600         LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
  601         mtx_unlock(&invl_gen_mtx);
  602 }
  603 
  604 /*
  605  * Finish the DI block, previously started by the current thread.  All
  606  * required TLB flushes for the pages marked by
  607  * pmap_delayed_invl_page() must be finished before this function is
  608  * called.
  609  *
  610  * This function works by bumping the global DI generation number to
  611  * the generation number of the current thread's DI, unless there is a
  612  * pending DI that started earlier.  In the latter case, bumping the
  613  * global DI generation number would incorrectly signal that the
  614  * earlier DI had finished.  Instead, this function bumps the earlier
  615  * DI's generation number to match the generation number of the
  616  * current thread's DI.
  617  */
  618 static void
  619 pmap_delayed_invl_finish_l(void)
  620 {
  621         struct pmap_invl_gen *invl_gen, *next;
  622 
  623         invl_gen = &curthread->td_md.md_invl_gen;
  624         KASSERT(invl_gen->gen != 0, ("missed invl_start"));
  625         mtx_lock(&invl_gen_mtx);
  626         next = LIST_NEXT(invl_gen, link);
  627         if (next == NULL)
  628                 pmap_delayed_invl_finish_unblock(invl_gen->gen);
  629         else
  630                 next->gen = invl_gen->gen;
  631         LIST_REMOVE(invl_gen, link);
  632         mtx_unlock(&invl_gen_mtx);
  633         invl_gen->gen = 0;
  634 }
  635 
  636 static bool
  637 pmap_not_in_di_u(void)
  638 {
  639         struct pmap_invl_gen *invl_gen;
  640 
  641         invl_gen = &curthread->td_md.md_invl_gen;
  642         return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
  643 }
  644 
  645 static void
  646 pmap_thread_init_invl_gen_u(struct thread *td)
  647 {
  648         struct pmap_invl_gen *invl_gen;
  649 
  650         invl_gen = &td->td_md.md_invl_gen;
  651         invl_gen->gen = 0;
  652         invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
  653 }
  654 
  655 static bool
  656 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
  657 {
  658         uint64_t new_high, new_low, old_high, old_low;
  659         char res;
  660 
  661         old_low = new_low = 0;
  662         old_high = new_high = (uintptr_t)0;
  663 
  664         __asm volatile("lock;cmpxchg16b\t%1;sete\t%0"
  665             : "=r" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
  666             : "b"(new_low), "c" (new_high)
  667             : "memory", "cc");
  668         if (res == 0) {
  669                 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
  670                         return (false);
  671                 out->gen = old_low;
  672                 out->next = (void *)old_high;
  673         } else {
  674                 out->gen = new_low;
  675                 out->next = (void *)new_high;
  676         }
  677         return (true);
  678 }
  679 
  680 static bool
  681 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
  682     struct pmap_invl_gen *new_val)
  683 {
  684         uint64_t new_high, new_low, old_high, old_low;
  685         char res;
  686 
  687         new_low = new_val->gen;
  688         new_high = (uintptr_t)new_val->next;
  689         old_low = old_val->gen;
  690         old_high = (uintptr_t)old_val->next;
  691 
  692         __asm volatile("lock;cmpxchg16b\t%1;sete\t%0"
  693             : "=r" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
  694             : "b"(new_low), "c" (new_high)
  695             : "memory", "cc");
  696         return (res);
  697 }
  698 
  699 #ifdef PV_STATS
  700 static long invl_start_restart;
  701 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_start_restart, CTLFLAG_RD,
  702     &invl_start_restart, 0,
  703     "");
  704 static long invl_finish_restart;
  705 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
  706     &invl_finish_restart, 0,
  707     "");
  708 static int invl_max_qlen;
  709 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
  710     &invl_max_qlen, 0,
  711     "");
  712 #endif
  713 
  714 static struct lock_delay_config __read_frequently di_delay;
  715 LOCK_DELAY_SYSINIT_DEFAULT(di_delay);
  716 
  717 static void
  718 pmap_delayed_invl_start_u(void)
  719 {
  720         struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
  721         struct thread *td;
  722         struct lock_delay_arg lda;
  723         uintptr_t prevl;
  724         u_char pri;
  725 #ifdef PV_STATS
  726         int i, ii;
  727 #endif
  728 
  729         td = curthread;
  730         invl_gen = &td->td_md.md_invl_gen;
  731         PMAP_ASSERT_NOT_IN_DI();
  732         lock_delay_arg_init(&lda, &di_delay);
  733         invl_gen->saved_pri = 0;
  734         pri = td->td_base_pri;
  735         if (pri > PVM) {
  736                 thread_lock(td);
  737                 pri = td->td_base_pri;
  738                 if (pri > PVM) {
  739                         invl_gen->saved_pri = pri;
  740                         sched_prio(td, PVM);
  741                 }
  742                 thread_unlock(td);
  743         }
  744 again:
  745         PV_STAT(i = 0);
  746         for (p = &pmap_invl_gen_head;; p = prev.next) {
  747                 PV_STAT(i++);
  748                 prevl = atomic_load_ptr(&p->next);
  749                 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
  750                         PV_STAT(atomic_add_long(&invl_start_restart, 1));
  751                         lock_delay(&lda);
  752                         goto again;
  753                 }
  754                 if (prevl == 0)
  755                         break;
  756                 prev.next = (void *)prevl;
  757         }
  758 #ifdef PV_STATS
  759         if ((ii = invl_max_qlen) < i)
  760                 atomic_cmpset_int(&invl_max_qlen, ii, i);
  761 #endif
  762 
  763         if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
  764                 PV_STAT(atomic_add_long(&invl_start_restart, 1));
  765                 lock_delay(&lda);
  766                 goto again;
  767         }
  768 
  769         new_prev.gen = prev.gen;
  770         new_prev.next = invl_gen;
  771         invl_gen->gen = prev.gen + 1;
  772 
  773         /* Formal fence between store to invl->gen and updating *p. */
  774         atomic_thread_fence_rel();
  775 
  776         /*
  777          * After inserting an invl_gen element with invalid bit set,
  778          * this thread blocks any other thread trying to enter the
  779          * delayed invalidation block.  Do not allow to remove us from
  780          * the CPU, because it causes starvation for other threads.
  781          */
  782         critical_enter();
  783 
  784         /*
  785          * ABA for *p is not possible there, since p->gen can only
  786          * increase.  So if the *p thread finished its di, then
  787          * started a new one and got inserted into the list at the
  788          * same place, its gen will appear greater than the previously
  789          * read gen.
  790          */
  791         if (!pmap_di_store_invl(p, &prev, &new_prev)) {
  792                 critical_exit();
  793                 PV_STAT(atomic_add_long(&invl_start_restart, 1));
  794                 lock_delay(&lda);
  795                 goto again;
  796         }
  797 
  798         /*
  799          * There we clear PMAP_INVL_GEN_NEXT_INVALID in
  800          * invl_gen->next, allowing other threads to iterate past us.
  801          * pmap_di_store_invl() provides fence between the generation
  802          * write and the update of next.
  803          */
  804         invl_gen->next = NULL;
  805         critical_exit();
  806 }
  807 
  808 static bool
  809 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
  810     struct pmap_invl_gen *p)
  811 {
  812         struct pmap_invl_gen prev, new_prev;
  813         u_long mygen;
  814 
  815         /*
  816          * Load invl_gen->gen after setting invl_gen->next
  817          * PMAP_INVL_GEN_NEXT_INVALID.  This prevents larger
  818          * generations to propagate to our invl_gen->gen.  Lock prefix
  819          * in atomic_set_ptr() worked as seq_cst fence.
  820          */
  821         mygen = atomic_load_long(&invl_gen->gen);
  822 
  823         if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
  824                 return (false);
  825 
  826         KASSERT(prev.gen < mygen,
  827             ("invalid di gen sequence %lu %lu", prev.gen, mygen));
  828         new_prev.gen = mygen;
  829         new_prev.next = (void *)((uintptr_t)invl_gen->next &
  830             ~PMAP_INVL_GEN_NEXT_INVALID);
  831 
  832         /* Formal fence between load of prev and storing update to it. */
  833         atomic_thread_fence_rel();
  834 
  835         return (pmap_di_store_invl(p, &prev, &new_prev));
  836 }
  837 
  838 static void
  839 pmap_delayed_invl_finish_u(void)
  840 {
  841         struct pmap_invl_gen *invl_gen, *p;
  842         struct thread *td;
  843         struct lock_delay_arg lda;
  844         uintptr_t prevl;
  845 
  846         td = curthread;
  847         invl_gen = &td->td_md.md_invl_gen;
  848         KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
  849         KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
  850             ("missed invl_start: INVALID"));
  851         lock_delay_arg_init(&lda, &di_delay);
  852 
  853 again:
  854         for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
  855                 prevl = atomic_load_ptr(&p->next);
  856                 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
  857                         PV_STAT(atomic_add_long(&invl_finish_restart, 1));
  858                         lock_delay(&lda);
  859                         goto again;
  860                 }
  861                 if ((void *)prevl == invl_gen)
  862                         break;
  863         }
  864 
  865         /*
  866          * It is legitimate to not find ourself on the list if a
  867          * thread before us finished its DI and started it again.
  868          */
  869         if (__predict_false(p == NULL)) {
  870                 PV_STAT(atomic_add_long(&invl_finish_restart, 1));
  871                 lock_delay(&lda);
  872                 goto again;
  873         }
  874 
  875         critical_enter();
  876         atomic_set_ptr((uintptr_t *)&invl_gen->next,
  877             PMAP_INVL_GEN_NEXT_INVALID);
  878         if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
  879                 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
  880                     PMAP_INVL_GEN_NEXT_INVALID);
  881                 critical_exit();
  882                 PV_STAT(atomic_add_long(&invl_finish_restart, 1));
  883                 lock_delay(&lda);
  884                 goto again;
  885         }
  886         critical_exit();
  887         if (atomic_load_int(&pmap_invl_waiters) > 0)
  888                 pmap_delayed_invl_finish_unblock(0);
  889         if (invl_gen->saved_pri != 0) {
  890                 thread_lock(td);
  891                 sched_prio(td, invl_gen->saved_pri);
  892                 thread_unlock(td);
  893         }
  894 }
  895 
  896 #ifdef DDB
  897 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
  898 {
  899         struct pmap_invl_gen *p, *pn;
  900         struct thread *td;
  901         uintptr_t nextl;
  902         bool first;
  903 
  904         for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
  905             first = false) {
  906                 nextl = atomic_load_ptr(&p->next);
  907                 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
  908                 td = first ? NULL : __containerof(p, struct thread,
  909                     td_md.md_invl_gen);
  910                 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
  911                     (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
  912                     td != NULL ? td->td_tid : -1);
  913         }
  914 }
  915 #endif
  916 
  917 #ifdef PV_STATS
  918 static long invl_wait;
  919 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
  920     "Number of times DI invalidation blocked pmap_remove_all/write");
  921 static long invl_wait_slow;
  922 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD, &invl_wait_slow, 0,
  923     "Number of slow invalidation waits for lockless DI");
  924 #endif
  925 
  926 static u_long *
  927 pmap_delayed_invl_genp(vm_page_t m)
  928 {
  929 
  930         return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
  931 }
  932 
  933 static void
  934 pmap_delayed_invl_callout_func(void *arg __unused)
  935 {
  936 
  937         if (atomic_load_int(&pmap_invl_waiters) == 0)
  938                 return;
  939         pmap_delayed_invl_finish_unblock(0);
  940 }
  941 
  942 static void
  943 pmap_delayed_invl_callout_init(void *arg __unused)
  944 {
  945 
  946         if (pmap_di_locked())
  947                 return;
  948         callout_init(&pmap_invl_callout, 1);
  949         pmap_invl_callout_inited = true;
  950 }
  951 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
  952     pmap_delayed_invl_callout_init, NULL);
  953 
  954 /*
  955  * Ensure that all currently executing DI blocks, that need to flush
  956  * TLB for the given page m, actually flushed the TLB at the time the
  957  * function returned.  If the page m has an empty PV list and we call
  958  * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
  959  * valid mapping for the page m in either its page table or TLB.
  960  *
  961  * This function works by blocking until the global DI generation
  962  * number catches up with the generation number associated with the
  963  * given page m and its PV list.  Since this function's callers
  964  * typically own an object lock and sometimes own a page lock, it
  965  * cannot sleep.  Instead, it blocks on a turnstile to relinquish the
  966  * processor.
  967  */
  968 static void
  969 pmap_delayed_invl_wait_l(vm_page_t m)
  970 {
  971         u_long *m_gen;
  972 #ifdef PV_STATS
  973         bool accounted = false;
  974 #endif
  975 
  976         m_gen = pmap_delayed_invl_genp(m);
  977         while (*m_gen > pmap_invl_gen) {
  978 #ifdef PV_STATS
  979                 if (!accounted) {
  980                         atomic_add_long(&invl_wait, 1);
  981                         accounted = true;
  982                 }
  983 #endif
  984                 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
  985         }
  986 }
  987 
  988 static void
  989 pmap_delayed_invl_wait_u(vm_page_t m)
  990 {
  991         u_long *m_gen;
  992         struct lock_delay_arg lda;
  993         bool fast;
  994 
  995         fast = true;
  996         m_gen = pmap_delayed_invl_genp(m);
  997         lock_delay_arg_init(&lda, &di_delay);
  998         while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
  999                 if (fast || !pmap_invl_callout_inited) {
 1000                         PV_STAT(atomic_add_long(&invl_wait, 1));
 1001                         lock_delay(&lda);
 1002                         fast = false;
 1003                 } else {
 1004                         /*
 1005                          * The page's invalidation generation number
 1006                          * is still below the current thread's number.
 1007                          * Prepare to block so that we do not waste
 1008                          * CPU cycles or worse, suffer livelock.
 1009                          *
 1010                          * Since it is impossible to block without
 1011                          * racing with pmap_delayed_invl_finish_u(),
 1012                          * prepare for the race by incrementing
 1013                          * pmap_invl_waiters and arming a 1-tick
 1014                          * callout which will unblock us if we lose
 1015                          * the race.
 1016                          */
 1017                         atomic_add_int(&pmap_invl_waiters, 1);
 1018 
 1019                         /*
 1020                          * Re-check the current thread's invalidation
 1021                          * generation after incrementing
 1022                          * pmap_invl_waiters, so that there is no race
 1023                          * with pmap_delayed_invl_finish_u() setting
 1024                          * the page generation and checking
 1025                          * pmap_invl_waiters.  The only race allowed
 1026                          * is for a missed unblock, which is handled
 1027                          * by the callout.
 1028                          */
 1029                         if (*m_gen >
 1030                             atomic_load_long(&pmap_invl_gen_head.gen)) {
 1031                                 callout_reset(&pmap_invl_callout, 1,
 1032                                     pmap_delayed_invl_callout_func, NULL);
 1033                                 PV_STAT(atomic_add_long(&invl_wait_slow, 1));
 1034                                 pmap_delayed_invl_wait_block(m_gen,
 1035                                     &pmap_invl_gen_head.gen);
 1036                         }
 1037                         atomic_add_int(&pmap_invl_waiters, -1);
 1038                 }
 1039         }
 1040 }
 1041 
 1042 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *), static)
 1043 {
 1044 
 1045         return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
 1046             pmap_thread_init_invl_gen_u);
 1047 }
 1048 
 1049 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void), static)
 1050 {
 1051 
 1052         return (pmap_di_locked() ? pmap_delayed_invl_start_l :
 1053             pmap_delayed_invl_start_u);
 1054 }
 1055 
 1056 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void), static)
 1057 {
 1058 
 1059         return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
 1060             pmap_delayed_invl_finish_u);
 1061 }
 1062 
 1063 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t), static)
 1064 {
 1065 
 1066         return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
 1067             pmap_delayed_invl_wait_u);
 1068 }
 1069 
 1070 /*
 1071  * Mark the page m's PV list as participating in the current thread's
 1072  * DI block.  Any threads concurrently using m's PV list to remove or
 1073  * restrict all mappings to m will wait for the current thread's DI
 1074  * block to complete before proceeding.
 1075  *
 1076  * The function works by setting the DI generation number for m's PV
 1077  * list to at least the DI generation number of the current thread.
 1078  * This forces a caller of pmap_delayed_invl_wait() to block until
 1079  * current thread calls pmap_delayed_invl_finish().
 1080  */
 1081 static void
 1082 pmap_delayed_invl_page(vm_page_t m)
 1083 {
 1084         u_long gen, *m_gen;
 1085 
 1086         rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
 1087         gen = curthread->td_md.md_invl_gen.gen;
 1088         if (gen == 0)
 1089                 return;
 1090         m_gen = pmap_delayed_invl_genp(m);
 1091         if (*m_gen < gen)
 1092                 *m_gen = gen;
 1093 }
 1094 
 1095 /*
 1096  * Crashdump maps.
 1097  */
 1098 static caddr_t crashdumpmap;
 1099 
 1100 /*
 1101  * Internal flags for pmap_enter()'s helper functions.
 1102  */
 1103 #define PMAP_ENTER_NORECLAIM    0x1000000       /* Don't reclaim PV entries. */
 1104 #define PMAP_ENTER_NOREPLACE    0x2000000       /* Don't replace mappings. */
 1105 
 1106 /*
 1107  * Internal flags for pmap_mapdev_internal() and
 1108  * pmap_change_props_locked().
 1109  */
 1110 #define MAPDEV_FLUSHCACHE       0x00000001      /* Flush cache after mapping. */
 1111 #define MAPDEV_SETATTR          0x00000002      /* Modify existing attrs. */
 1112 #define MAPDEV_ASSERTVALID      0x00000004      /* Assert mapping validity. */
 1113 
 1114 TAILQ_HEAD(pv_chunklist, pv_chunk);
 1115 
 1116 static void     free_pv_chunk(struct pv_chunk *pc);
 1117 static void     free_pv_chunk_batch(struct pv_chunklist *batch);
 1118 static void     free_pv_entry(pmap_t pmap, pv_entry_t pv);
 1119 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
 1120 static int      popcnt_pc_map_pq(uint64_t *map);
 1121 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
 1122 static void     reserve_pv_entries(pmap_t pmap, int needed,
 1123                     struct rwlock **lockp);
 1124 static void     pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 1125                     struct rwlock **lockp);
 1126 static bool     pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
 1127                     u_int flags, struct rwlock **lockp);
 1128 #if VM_NRESERVLEVEL > 0
 1129 static void     pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 1130                     struct rwlock **lockp);
 1131 #endif
 1132 static void     pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
 1133 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
 1134                     vm_offset_t va);
 1135 
 1136 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
 1137     vm_prot_t prot, int mode, int flags);
 1138 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
 1139 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
 1140     vm_offset_t va, struct rwlock **lockp);
 1141 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
 1142     vm_offset_t va);
 1143 static bool     pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
 1144                     vm_prot_t prot, struct rwlock **lockp);
 1145 static int      pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
 1146                     u_int flags, vm_page_t m, struct rwlock **lockp);
 1147 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
 1148     vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
 1149 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
 1150 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted);
 1151 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
 1152     vm_offset_t eva);
 1153 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
 1154     vm_offset_t eva);
 1155 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
 1156                     pd_entry_t pde);
 1157 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
 1158 static vm_page_t pmap_large_map_getptp_unlocked(void);
 1159 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
 1160 #if VM_NRESERVLEVEL > 0
 1161 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
 1162     struct rwlock **lockp);
 1163 #endif
 1164 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
 1165     vm_prot_t prot);
 1166 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
 1167 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
 1168     bool exec);
 1169 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
 1170 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
 1171 static void pmap_pti_wire_pte(void *pte);
 1172 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
 1173     struct spglist *free, struct rwlock **lockp);
 1174 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
 1175     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
 1176 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
 1177 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
 1178     struct spglist *free);
 1179 static bool     pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
 1180                     pd_entry_t *pde, struct spglist *free,
 1181                     struct rwlock **lockp);
 1182 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
 1183     vm_page_t m, struct rwlock **lockp);
 1184 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
 1185     pd_entry_t newpde);
 1186 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
 1187 
 1188 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
 1189                 struct rwlock **lockp);
 1190 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
 1191                 struct rwlock **lockp);
 1192 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
 1193                 struct rwlock **lockp);
 1194 
 1195 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
 1196     struct spglist *free);
 1197 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
 1198 
 1199 /********************/
 1200 /* Inline functions */
 1201 /********************/
 1202 
 1203 /* Return a non-clipped PD index for a given VA */
 1204 static __inline vm_pindex_t
 1205 pmap_pde_pindex(vm_offset_t va)
 1206 {
 1207         return (va >> PDRSHIFT);
 1208 }
 1209 
 1210 
 1211 /* Return a pointer to the PML4 slot that corresponds to a VA */
 1212 static __inline pml4_entry_t *
 1213 pmap_pml4e(pmap_t pmap, vm_offset_t va)
 1214 {
 1215 
 1216         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
 1217 }
 1218 
 1219 /* Return a pointer to the PDP slot that corresponds to a VA */
 1220 static __inline pdp_entry_t *
 1221 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
 1222 {
 1223         pdp_entry_t *pdpe;
 1224 
 1225         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
 1226         return (&pdpe[pmap_pdpe_index(va)]);
 1227 }
 1228 
 1229 /* Return a pointer to the PDP slot that corresponds to a VA */
 1230 static __inline pdp_entry_t *
 1231 pmap_pdpe(pmap_t pmap, vm_offset_t va)
 1232 {
 1233         pml4_entry_t *pml4e;
 1234         pt_entry_t PG_V;
 1235 
 1236         PG_V = pmap_valid_bit(pmap);
 1237         pml4e = pmap_pml4e(pmap, va);
 1238         if ((*pml4e & PG_V) == 0)
 1239                 return (NULL);
 1240         return (pmap_pml4e_to_pdpe(pml4e, va));
 1241 }
 1242 
 1243 /* Return a pointer to the PD slot that corresponds to a VA */
 1244 static __inline pd_entry_t *
 1245 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
 1246 {
 1247         pd_entry_t *pde;
 1248 
 1249         KASSERT((*pdpe & PG_PS) == 0,
 1250             ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
 1251         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
 1252         return (&pde[pmap_pde_index(va)]);
 1253 }
 1254 
 1255 /* Return a pointer to the PD slot that corresponds to a VA */
 1256 static __inline pd_entry_t *
 1257 pmap_pde(pmap_t pmap, vm_offset_t va)
 1258 {
 1259         pdp_entry_t *pdpe;
 1260         pt_entry_t PG_V;
 1261 
 1262         PG_V = pmap_valid_bit(pmap);
 1263         pdpe = pmap_pdpe(pmap, va);
 1264         if (pdpe == NULL || (*pdpe & PG_V) == 0)
 1265                 return (NULL);
 1266         return (pmap_pdpe_to_pde(pdpe, va));
 1267 }
 1268 
 1269 /* Return a pointer to the PT slot that corresponds to a VA */
 1270 static __inline pt_entry_t *
 1271 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
 1272 {
 1273         pt_entry_t *pte;
 1274 
 1275         KASSERT((*pde & PG_PS) == 0,
 1276             ("%s: pde %#lx is a leaf", __func__, *pde));
 1277         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
 1278         return (&pte[pmap_pte_index(va)]);
 1279 }
 1280 
 1281 /* Return a pointer to the PT slot that corresponds to a VA */
 1282 static __inline pt_entry_t *
 1283 pmap_pte(pmap_t pmap, vm_offset_t va)
 1284 {
 1285         pd_entry_t *pde;
 1286         pt_entry_t PG_V;
 1287 
 1288         PG_V = pmap_valid_bit(pmap);
 1289         pde = pmap_pde(pmap, va);
 1290         if (pde == NULL || (*pde & PG_V) == 0)
 1291                 return (NULL);
 1292         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
 1293                 return ((pt_entry_t *)pde);
 1294         return (pmap_pde_to_pte(pde, va));
 1295 }
 1296 
 1297 static __inline void
 1298 pmap_resident_count_inc(pmap_t pmap, int count)
 1299 {
 1300 
 1301         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 1302         pmap->pm_stats.resident_count += count;
 1303 }
 1304 
 1305 static __inline void
 1306 pmap_resident_count_dec(pmap_t pmap, int count)
 1307 {
 1308 
 1309         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 1310         KASSERT(pmap->pm_stats.resident_count >= count,
 1311             ("pmap %p resident count underflow %ld %d", pmap,
 1312             pmap->pm_stats.resident_count, count));
 1313         pmap->pm_stats.resident_count -= count;
 1314 }
 1315 
 1316 PMAP_INLINE pt_entry_t *
 1317 vtopte(vm_offset_t va)
 1318 {
 1319         u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
 1320 
 1321         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
 1322 
 1323         return (PTmap + ((va >> PAGE_SHIFT) & mask));
 1324 }
 1325 
 1326 static __inline pd_entry_t *
 1327 vtopde(vm_offset_t va)
 1328 {
 1329         u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
 1330 
 1331         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
 1332 
 1333         return (PDmap + ((va >> PDRSHIFT) & mask));
 1334 }
 1335 
 1336 static u_int64_t
 1337 allocpages(vm_paddr_t *firstaddr, int n)
 1338 {
 1339         u_int64_t ret;
 1340 
 1341         ret = *firstaddr;
 1342         bzero((void *)ret, n * PAGE_SIZE);
 1343         *firstaddr += n * PAGE_SIZE;
 1344         return (ret);
 1345 }
 1346 
 1347 CTASSERT(powerof2(NDMPML4E));
 1348 
 1349 /* number of kernel PDP slots */
 1350 #define NKPDPE(ptpgs)           howmany(ptpgs, NPDEPG)
 1351 
 1352 static void
 1353 nkpt_init(vm_paddr_t addr)
 1354 {
 1355         int pt_pages;
 1356         
 1357 #ifdef NKPT
 1358         pt_pages = NKPT;
 1359 #else
 1360         pt_pages = howmany(addr, 1 << PDRSHIFT);
 1361         pt_pages += NKPDPE(pt_pages);
 1362 
 1363         /*
 1364          * Add some slop beyond the bare minimum required for bootstrapping
 1365          * the kernel.
 1366          *
 1367          * This is quite important when allocating KVA for kernel modules.
 1368          * The modules are required to be linked in the negative 2GB of
 1369          * the address space.  If we run out of KVA in this region then
 1370          * pmap_growkernel() will need to allocate page table pages to map
 1371          * the entire 512GB of KVA space which is an unnecessary tax on
 1372          * physical memory.
 1373          *
 1374          * Secondly, device memory mapped as part of setting up the low-
 1375          * level console(s) is taken from KVA, starting at virtual_avail.
 1376          * This is because cninit() is called after pmap_bootstrap() but
 1377          * before vm_init() and pmap_init(). 20MB for a frame buffer is
 1378          * not uncommon.
 1379          */
 1380         pt_pages += 32;         /* 64MB additional slop. */
 1381 #endif
 1382         nkpt = pt_pages;
 1383 }
 1384 
 1385 /*
 1386  * Returns the proper write/execute permission for a physical page that is
 1387  * part of the initial boot allocations.
 1388  *
 1389  * If the page has kernel text, it is marked as read-only. If the page has
 1390  * kernel read-only data, it is marked as read-only/not-executable. If the
 1391  * page has only read-write data, it is marked as read-write/not-executable.
 1392  * If the page is below/above the kernel range, it is marked as read-write.
 1393  *
 1394  * This function operates on 2M pages, since we map the kernel space that
 1395  * way.
 1396  *
 1397  * Note that this doesn't currently provide any protection for modules.
 1398  */
 1399 static inline pt_entry_t
 1400 bootaddr_rwx(vm_paddr_t pa)
 1401 {
 1402 
 1403         /*
 1404          * Everything in the same 2M page as the start of the kernel
 1405          * should be static. On the other hand, things in the same 2M
 1406          * page as the end of the kernel could be read-write/executable,
 1407          * as the kernel image is not guaranteed to end on a 2M boundary.
 1408          */
 1409         if (pa < trunc_2mpage(btext - KERNBASE) ||
 1410            pa >= trunc_2mpage(_end - KERNBASE))
 1411                 return (X86_PG_RW);
 1412         /*
 1413          * The linker should ensure that the read-only and read-write
 1414          * portions don't share the same 2M page, so this shouldn't
 1415          * impact read-only data. However, in any case, any page with
 1416          * read-write data needs to be read-write.
 1417          */
 1418         if (pa >= trunc_2mpage(brwsection - KERNBASE))
 1419                 return (X86_PG_RW | pg_nx);
 1420         /*
 1421          * Mark any 2M page containing kernel text as read-only. Mark
 1422          * other pages with read-only data as read-only and not executable.
 1423          * (It is likely a small portion of the read-only data section will
 1424          * be marked as read-only, but executable. This should be acceptable
 1425          * since the read-only protection will keep the data from changing.)
 1426          * Note that fixups to the .text section will still work until we
 1427          * set CR0.WP.
 1428          */
 1429         if (pa < round_2mpage(etext - KERNBASE))
 1430                 return (0);
 1431         return (pg_nx);
 1432 }
 1433 
 1434 static void
 1435 create_pagetables(vm_paddr_t *firstaddr)
 1436 {
 1437         int i, j, ndm1g, nkpdpe, nkdmpde;
 1438         pd_entry_t *pd_p;
 1439         pdp_entry_t *pdp_p;
 1440         pml4_entry_t *p4_p;
 1441         uint64_t DMPDkernphys;
 1442 
 1443         /* Allocate page table pages for the direct map */
 1444         ndmpdp = howmany(ptoa(Maxmem), NBPDP);
 1445         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
 1446                 ndmpdp = 4;
 1447         ndmpdpphys = howmany(ndmpdp, NPDPEPG);
 1448         if (ndmpdpphys > NDMPML4E) {
 1449                 /*
 1450                  * Each NDMPML4E allows 512 GB, so limit to that,
 1451                  * and then readjust ndmpdp and ndmpdpphys.
 1452                  */
 1453                 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
 1454                 Maxmem = atop(NDMPML4E * NBPML4);
 1455                 ndmpdpphys = NDMPML4E;
 1456                 ndmpdp = NDMPML4E * NPDEPG;
 1457         }
 1458         DMPDPphys = allocpages(firstaddr, ndmpdpphys);
 1459         ndm1g = 0;
 1460         if ((amd_feature & AMDID_PAGE1GB) != 0) {
 1461                 /*
 1462                  * Calculate the number of 1G pages that will fully fit in
 1463                  * Maxmem.
 1464                  */
 1465                 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
 1466 
 1467                 /*
 1468                  * Allocate 2M pages for the kernel. These will be used in
 1469                  * place of the first one or more 1G pages from ndm1g.
 1470                  */
 1471                 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
 1472                 DMPDkernphys = allocpages(firstaddr, nkdmpde);
 1473         }
 1474         if (ndm1g < ndmpdp)
 1475                 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
 1476         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
 1477 
 1478         /* Allocate pages */
 1479         KPML4phys = allocpages(firstaddr, 1);
 1480         KPDPphys = allocpages(firstaddr, NKPML4E);
 1481 
 1482         /*
 1483          * Allocate the initial number of kernel page table pages required to
 1484          * bootstrap.  We defer this until after all memory-size dependent
 1485          * allocations are done (e.g. direct map), so that we don't have to
 1486          * build in too much slop in our estimate.
 1487          *
 1488          * Note that when NKPML4E > 1, we have an empty page underneath
 1489          * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
 1490          * pages.  (pmap_enter requires a PD page to exist for each KPML4E.)
 1491          */
 1492         nkpt_init(*firstaddr);
 1493         nkpdpe = NKPDPE(nkpt);
 1494 
 1495         KPTphys = allocpages(firstaddr, nkpt);
 1496         KPDphys = allocpages(firstaddr, nkpdpe);
 1497 
 1498         /*
 1499          * Connect the zero-filled PT pages to their PD entries.  This
 1500          * implicitly maps the PT pages at their correct locations within
 1501          * the PTmap.
 1502          */
 1503         pd_p = (pd_entry_t *)KPDphys;
 1504         for (i = 0; i < nkpt; i++)
 1505                 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
 1506 
 1507         /*
 1508          * Map from physical address zero to the end of loader preallocated
 1509          * memory using 2MB pages.  This replaces some of the PD entries
 1510          * created above.
 1511          */
 1512         for (i = 0; (i << PDRSHIFT) < KERNend; i++)
 1513                 /* Preset PG_M and PG_A because demotion expects it. */
 1514                 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
 1515                     X86_PG_M | X86_PG_A | bootaddr_rwx(i << PDRSHIFT);
 1516 
 1517         /*
 1518          * Because we map the physical blocks in 2M pages, adjust firstaddr
 1519          * to record the physical blocks we've actually mapped into kernel
 1520          * virtual address space.
 1521          */
 1522         if (*firstaddr < round_2mpage(KERNend))
 1523                 *firstaddr = round_2mpage(KERNend);
 1524 
 1525         /* And connect up the PD to the PDP (leaving room for L4 pages) */
 1526         pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
 1527         for (i = 0; i < nkpdpe; i++)
 1528                 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
 1529 
 1530         /*
 1531          * Now, set up the direct map region using 2MB and/or 1GB pages.  If
 1532          * the end of physical memory is not aligned to a 1GB page boundary,
 1533          * then the residual physical memory is mapped with 2MB pages.  Later,
 1534          * if pmap_mapdev{_attr}() uses the direct map for non-write-back
 1535          * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
 1536          * that are partially used. 
 1537          */
 1538         pd_p = (pd_entry_t *)DMPDphys;
 1539         for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
 1540                 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
 1541                 /* Preset PG_M and PG_A because demotion expects it. */
 1542                 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
 1543                     X86_PG_M | X86_PG_A | pg_nx;
 1544         }
 1545         pdp_p = (pdp_entry_t *)DMPDPphys;
 1546         for (i = 0; i < ndm1g; i++) {
 1547                 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
 1548                 /* Preset PG_M and PG_A because demotion expects it. */
 1549                 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
 1550                     X86_PG_M | X86_PG_A | pg_nx;
 1551         }
 1552         for (j = 0; i < ndmpdp; i++, j++) {
 1553                 pdp_p[i] = DMPDphys + ptoa(j);
 1554                 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
 1555         }
 1556 
 1557         /*
 1558          * Instead of using a 1G page for the memory containing the kernel,
 1559          * use 2M pages with read-only and no-execute permissions.  (If using 1G
 1560          * pages, this will partially overwrite the PDPEs above.)
 1561          */
 1562         if (ndm1g) {
 1563                 pd_p = (pd_entry_t *)DMPDkernphys;
 1564                 for (i = 0; i < (NPDEPG * nkdmpde); i++)
 1565                         pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
 1566                             X86_PG_M | X86_PG_A | pg_nx |
 1567                             bootaddr_rwx(i << PDRSHIFT);
 1568                 for (i = 0; i < nkdmpde; i++)
 1569                         pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
 1570                             X86_PG_V | pg_nx;
 1571         }
 1572 
 1573         /* And recursively map PML4 to itself in order to get PTmap */
 1574         p4_p = (pml4_entry_t *)KPML4phys;
 1575         p4_p[PML4PML4I] = KPML4phys;
 1576         p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
 1577 
 1578         /* Connect the Direct Map slot(s) up to the PML4. */
 1579         for (i = 0; i < ndmpdpphys; i++) {
 1580                 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
 1581                 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
 1582         }
 1583 
 1584         /* Connect the KVA slots up to the PML4 */
 1585         for (i = 0; i < NKPML4E; i++) {
 1586                 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
 1587                 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
 1588         }
 1589 }
 1590 
 1591 /*
 1592  *      Bootstrap the system enough to run with virtual memory.
 1593  *
 1594  *      On amd64 this is called after mapping has already been enabled
 1595  *      and just syncs the pmap module with what has already been done.
 1596  *      [We can't call it easily with mapping off since the kernel is not
 1597  *      mapped with PA == VA, hence we would have to relocate every address
 1598  *      from the linked base (virtual) address "KERNBASE" to the actual
 1599  *      (physical) address starting relative to 0]
 1600  */
 1601 void
 1602 pmap_bootstrap(vm_paddr_t *firstaddr)
 1603 {
 1604         vm_offset_t va;
 1605         pt_entry_t *pte, *pcpu_pte;
 1606         uint64_t cr4, pcpu_phys;
 1607         u_long res;
 1608         int i;
 1609 
 1610         KERNend = *firstaddr;
 1611         res = atop(KERNend - (vm_paddr_t)kernphys);
 1612 
 1613         if (!pti)
 1614                 pg_g = X86_PG_G;
 1615 
 1616         /*
 1617          * Create an initial set of page tables to run the kernel in.
 1618          */
 1619         create_pagetables(firstaddr);
 1620 
 1621         pcpu_phys = allocpages(firstaddr, MAXCPU);
 1622 
 1623         /*
 1624          * Add a physical memory segment (vm_phys_seg) corresponding to the
 1625          * preallocated kernel page table pages so that vm_page structures
 1626          * representing these pages will be created.  The vm_page structures
 1627          * are required for promotion of the corresponding kernel virtual
 1628          * addresses to superpage mappings.
 1629          */
 1630         vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
 1631 
 1632         /*
 1633          * Account for the virtual addresses mapped by create_pagetables().
 1634          */
 1635         virtual_avail = (vm_offset_t)KERNBASE + round_2mpage(KERNend);
 1636         virtual_end = VM_MAX_KERNEL_ADDRESS;
 1637 
 1638         /*
 1639          * Enable PG_G global pages, then switch to the kernel page
 1640          * table from the bootstrap page table.  After the switch, it
 1641          * is possible to enable SMEP and SMAP since PG_U bits are
 1642          * correct now.
 1643          */
 1644         cr4 = rcr4();
 1645         cr4 |= CR4_PGE;
 1646         load_cr4(cr4);
 1647         load_cr3(KPML4phys);
 1648         if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
 1649                 cr4 |= CR4_SMEP;
 1650         if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
 1651                 cr4 |= CR4_SMAP;
 1652         load_cr4(cr4);
 1653 
 1654         /*
 1655          * Initialize the kernel pmap (which is statically allocated).
 1656          * Count bootstrap data as being resident in case any of this data is
 1657          * later unmapped (using pmap_remove()) and freed.
 1658          */
 1659         PMAP_LOCK_INIT(kernel_pmap);
 1660         kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
 1661         kernel_pmap->pm_cr3 = KPML4phys;
 1662         kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
 1663         CPU_FILL(&kernel_pmap->pm_active);      /* don't allow deactivation */
 1664         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
 1665         kernel_pmap->pm_stats.resident_count = res;
 1666         kernel_pmap->pm_flags = pmap_flags;
 1667 
 1668         /*
 1669          * Initialize the TLB invalidations generation number lock.
 1670          */
 1671         mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
 1672 
 1673         /*
 1674          * Reserve some special page table entries/VA space for temporary
 1675          * mapping of pages.
 1676          */
 1677 #define SYSMAP(c, p, v, n)      \
 1678         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
 1679 
 1680         va = virtual_avail;
 1681         pte = vtopte(va);
 1682 
 1683         /*
 1684          * Crashdump maps.  The first page is reused as CMAP1 for the
 1685          * memory test.
 1686          */
 1687         SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
 1688         CADDR1 = crashdumpmap;
 1689 
 1690         SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
 1691         virtual_avail = va;
 1692 
 1693         for (i = 0; i < MAXCPU; i++) {
 1694                 pcpu_pte[i] = (pcpu_phys + ptoa(i)) | X86_PG_V | X86_PG_RW |
 1695                     pg_g | pg_nx | X86_PG_M | X86_PG_A;
 1696         }
 1697         STAILQ_INIT(&cpuhead);
 1698         wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
 1699         pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
 1700         amd64_bsp_pcpu_init1(&__pcpu[0]);
 1701         amd64_bsp_ist_init(&__pcpu[0]);
 1702         __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
 1703         __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
 1704 
 1705         /*
 1706          * Initialize the PAT MSR.
 1707          * pmap_init_pat() clears and sets CR4_PGE, which, as a
 1708          * side-effect, invalidates stale PG_G TLB entries that might
 1709          * have been created in our pre-boot environment.
 1710          */
 1711         pmap_init_pat();
 1712 
 1713         /* Initialize TLB Context Id. */
 1714         if (pmap_pcid_enabled) {
 1715                 for (i = 0; i < MAXCPU; i++) {
 1716                         kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
 1717                         kernel_pmap->pm_pcids[i].pm_gen = 1;
 1718                 }
 1719 
 1720                 /*
 1721                  * PMAP_PCID_KERN + 1 is used for initialization of
 1722                  * proc0 pmap.  The pmap' pcid state might be used by
 1723                  * EFIRT entry before first context switch, so it
 1724                  * needs to be valid.
 1725                  */
 1726                 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
 1727                 PCPU_SET(pcid_gen, 1);
 1728 
 1729                 /*
 1730                  * pcpu area for APs is zeroed during AP startup.
 1731                  * pc_pcid_next and pc_pcid_gen are initialized by AP
 1732                  * during pcpu setup.
 1733                  */
 1734                 load_cr4(rcr4() | CR4_PCIDE);
 1735         }
 1736 }
 1737 
 1738 /*
 1739  * Setup the PAT MSR.
 1740  */
 1741 void
 1742 pmap_init_pat(void)
 1743 {
 1744         uint64_t pat_msr;
 1745         u_long cr0, cr4;
 1746         int i;
 1747 
 1748         /* Bail if this CPU doesn't implement PAT. */
 1749         if ((cpu_feature & CPUID_PAT) == 0)
 1750                 panic("no PAT??");
 1751 
 1752         /* Set default PAT index table. */
 1753         for (i = 0; i < PAT_INDEX_SIZE; i++)
 1754                 pat_index[i] = -1;
 1755         pat_index[PAT_WRITE_BACK] = 0;
 1756         pat_index[PAT_WRITE_THROUGH] = 1;
 1757         pat_index[PAT_UNCACHEABLE] = 3;
 1758         pat_index[PAT_WRITE_COMBINING] = 6;
 1759         pat_index[PAT_WRITE_PROTECTED] = 5;
 1760         pat_index[PAT_UNCACHED] = 2;
 1761 
 1762         /*
 1763          * Initialize default PAT entries.
 1764          * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
 1765          * Program 5 and 6 as WP and WC.
 1766          *
 1767          * Leave 4 and 7 as WB and UC.  Note that a recursive page table
 1768          * mapping for a 2M page uses a PAT value with the bit 3 set due
 1769          * to its overload with PG_PS.
 1770          */
 1771         pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
 1772             PAT_VALUE(1, PAT_WRITE_THROUGH) |
 1773             PAT_VALUE(2, PAT_UNCACHED) |
 1774             PAT_VALUE(3, PAT_UNCACHEABLE) |
 1775             PAT_VALUE(4, PAT_WRITE_BACK) |
 1776             PAT_VALUE(5, PAT_WRITE_PROTECTED) |
 1777             PAT_VALUE(6, PAT_WRITE_COMBINING) |
 1778             PAT_VALUE(7, PAT_UNCACHEABLE);
 1779 
 1780         /* Disable PGE. */
 1781         cr4 = rcr4();
 1782         load_cr4(cr4 & ~CR4_PGE);
 1783 
 1784         /* Disable caches (CD = 1, NW = 0). */
 1785         cr0 = rcr0();
 1786         load_cr0((cr0 & ~CR0_NW) | CR0_CD);
 1787 
 1788         /* Flushes caches and TLBs. */
 1789         wbinvd();
 1790         invltlb();
 1791 
 1792         /* Update PAT and index table. */
 1793         wrmsr(MSR_PAT, pat_msr);
 1794 
 1795         /* Flush caches and TLBs again. */
 1796         wbinvd();
 1797         invltlb();
 1798 
 1799         /* Restore caches and PGE. */
 1800         load_cr0(cr0);
 1801         load_cr4(cr4);
 1802 }
 1803 
 1804 /*
 1805  *      Initialize a vm_page's machine-dependent fields.
 1806  */
 1807 void
 1808 pmap_page_init(vm_page_t m)
 1809 {
 1810 
 1811         TAILQ_INIT(&m->md.pv_list);
 1812         m->md.pat_mode = PAT_WRITE_BACK;
 1813 }
 1814 
 1815 static int pmap_allow_2m_x_ept;
 1816 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
 1817     &pmap_allow_2m_x_ept, 0,
 1818     "Allow executable superpage mappings in EPT");
 1819 
 1820 void
 1821 pmap_allow_2m_x_ept_recalculate(void)
 1822 {
 1823         /*
 1824          * SKL002, SKL012S.  Since the EPT format is only used by
 1825          * Intel CPUs, the vendor check is merely a formality.
 1826          */
 1827         if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
 1828             (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
 1829             (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
 1830             (CPUID_TO_MODEL(cpu_id) == 0x26 ||  /* Atoms */
 1831             CPUID_TO_MODEL(cpu_id) == 0x27 ||
 1832             CPUID_TO_MODEL(cpu_id) == 0x35 ||
 1833             CPUID_TO_MODEL(cpu_id) == 0x36 ||
 1834             CPUID_TO_MODEL(cpu_id) == 0x37 ||
 1835             CPUID_TO_MODEL(cpu_id) == 0x86 ||
 1836             CPUID_TO_MODEL(cpu_id) == 0x1c ||
 1837             CPUID_TO_MODEL(cpu_id) == 0x4a ||
 1838             CPUID_TO_MODEL(cpu_id) == 0x4c ||
 1839             CPUID_TO_MODEL(cpu_id) == 0x4d ||
 1840             CPUID_TO_MODEL(cpu_id) == 0x5a ||
 1841             CPUID_TO_MODEL(cpu_id) == 0x5c ||
 1842             CPUID_TO_MODEL(cpu_id) == 0x5d ||
 1843             CPUID_TO_MODEL(cpu_id) == 0x5f ||
 1844             CPUID_TO_MODEL(cpu_id) == 0x6e ||
 1845             CPUID_TO_MODEL(cpu_id) == 0x7a ||
 1846             CPUID_TO_MODEL(cpu_id) == 0x57 ||   /* Knights */
 1847             CPUID_TO_MODEL(cpu_id) == 0x85))))
 1848                 pmap_allow_2m_x_ept = 1;
 1849         TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
 1850 }
 1851 
 1852 static bool
 1853 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
 1854 {
 1855 
 1856         return (pmap->pm_type != PT_EPT || !executable ||
 1857             !pmap_allow_2m_x_ept);
 1858 }
 1859 
 1860 /*
 1861  *      Initialize the pmap module.
 1862  *      Called by vm_init, to initialize any structures that the pmap
 1863  *      system needs to map virtual memory.
 1864  */
 1865 void
 1866 pmap_init(void)
 1867 {
 1868         struct pmap_preinit_mapping *ppim;
 1869         vm_page_t m, mpte;
 1870         vm_size_t s;
 1871         int error, i, pv_npg, ret, skz63;
 1872 
 1873         /* L1TF, reserve page @0 unconditionally */
 1874         vm_page_blacklist_add(0, bootverbose);
 1875 
 1876         /* Detect bare-metal Skylake Server and Skylake-X. */
 1877         if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
 1878             CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
 1879                 /*
 1880                  * Skylake-X errata SKZ63. Processor May Hang When
 1881                  * Executing Code In an HLE Transaction Region between
 1882                  * 40000000H and 403FFFFFH.
 1883                  *
 1884                  * Mark the pages in the range as preallocated.  It
 1885                  * seems to be impossible to distinguish between
 1886                  * Skylake Server and Skylake X.
 1887                  */
 1888                 skz63 = 1;
 1889                 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
 1890                 if (skz63 != 0) {
 1891                         if (bootverbose)
 1892                                 printf("SKZ63: skipping 4M RAM starting "
 1893                                     "at physical 1G\n");
 1894                         for (i = 0; i < atop(0x400000); i++) {
 1895                                 ret = vm_page_blacklist_add(0x40000000 +
 1896                                     ptoa(i), FALSE);
 1897                                 if (!ret && bootverbose)
 1898                                         printf("page at %#lx already used\n",
 1899                                             0x40000000 + ptoa(i));
 1900                         }
 1901                 }
 1902         }
 1903 
 1904         /* IFU */
 1905         pmap_allow_2m_x_ept_recalculate();
 1906 
 1907         /*
 1908          * Initialize the vm page array entries for the kernel pmap's
 1909          * page table pages.
 1910          */ 
 1911         PMAP_LOCK(kernel_pmap);
 1912         for (i = 0; i < nkpt; i++) {
 1913                 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
 1914                 KASSERT(mpte >= vm_page_array &&
 1915                     mpte < &vm_page_array[vm_page_array_size],
 1916                     ("pmap_init: page table page is out of range"));
 1917                 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
 1918                 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
 1919                 mpte->wire_count = 1;
 1920 
 1921                 /*
 1922                  * Collect the page table pages that were replaced by a 2MB
 1923                  * page in create_pagetables().  They are zero filled.
 1924                  */
 1925                 if (i << PDRSHIFT < KERNend &&
 1926                     pmap_insert_pt_page(kernel_pmap, mpte, false))
 1927                         panic("pmap_init: pmap_insert_pt_page failed");
 1928         }
 1929         PMAP_UNLOCK(kernel_pmap);
 1930         vm_wire_add(nkpt);
 1931 
 1932         /*
 1933          * If the kernel is running on a virtual machine, then it must assume
 1934          * that MCA is enabled by the hypervisor.  Moreover, the kernel must
 1935          * be prepared for the hypervisor changing the vendor and family that
 1936          * are reported by CPUID.  Consequently, the workaround for AMD Family
 1937          * 10h Erratum 383 is enabled if the processor's feature set does not
 1938          * include at least one feature that is only supported by older Intel
 1939          * or newer AMD processors.
 1940          */
 1941         if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
 1942             (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
 1943             CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
 1944             AMDID2_FMA4)) == 0)
 1945                 workaround_erratum383 = 1;
 1946 
 1947         /*
 1948          * Are large page mappings enabled?
 1949          */
 1950         TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
 1951         if (pg_ps_enabled) {
 1952                 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
 1953                     ("pmap_init: can't assign to pagesizes[1]"));
 1954                 pagesizes[1] = NBPDR;
 1955         }
 1956 
 1957         /*
 1958          * Initialize the pv chunk list mutex.
 1959          */
 1960         mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
 1961 
 1962         /*
 1963          * Initialize the pool of pv list locks.
 1964          */
 1965         for (i = 0; i < NPV_LIST_LOCKS; i++)
 1966                 rw_init(&pv_list_locks[i], "pmap pv list");
 1967 
 1968         /*
 1969          * Calculate the size of the pv head table for superpages.
 1970          */
 1971         pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
 1972 
 1973         /*
 1974          * Allocate memory for the pv head table for superpages.
 1975          */
 1976         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
 1977         s = round_page(s);
 1978         pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
 1979         for (i = 0; i < pv_npg; i++)
 1980                 TAILQ_INIT(&pv_table[i].pv_list);
 1981         TAILQ_INIT(&pv_dummy.pv_list);
 1982 
 1983         pmap_initialized = 1;
 1984         for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
 1985                 ppim = pmap_preinit_mapping + i;
 1986                 if (ppim->va == 0)
 1987                         continue;
 1988                 /* Make the direct map consistent */
 1989                 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
 1990                         (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
 1991                             ppim->sz, ppim->mode);
 1992                 }
 1993                 if (!bootverbose)
 1994                         continue;
 1995                 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
 1996                     ppim->pa, ppim->va, ppim->sz, ppim->mode);
 1997         }
 1998 
 1999         mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
 2000         error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
 2001             (vmem_addr_t *)&qframe);
 2002         if (error != 0)
 2003                 panic("qframe allocation failed");
 2004 
 2005         lm_ents = 8;
 2006         TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
 2007         if (lm_ents > LMEPML4I - LMSPML4I + 1)
 2008                 lm_ents = LMEPML4I - LMSPML4I + 1;
 2009         if (bootverbose)
 2010                 printf("pmap: large map %u PML4 slots (%lu Gb)\n",
 2011                     lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
 2012         if (lm_ents != 0) {
 2013                 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
 2014                     (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
 2015                 if (large_vmem == NULL) {
 2016                         printf("pmap: cannot create large map\n");
 2017                         lm_ents = 0;
 2018                 }
 2019                 for (i = 0; i < lm_ents; i++) {
 2020                         m = pmap_large_map_getptp_unlocked();
 2021                         kernel_pmap->pm_pml4[LMSPML4I + i] = X86_PG_V |
 2022                             X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
 2023                             VM_PAGE_TO_PHYS(m);
 2024                 }
 2025         }
 2026 }
 2027 
 2028 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
 2029     "2MB page mapping counters");
 2030 
 2031 static u_long pmap_pde_demotions;
 2032 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
 2033     &pmap_pde_demotions, 0, "2MB page demotions");
 2034 
 2035 static u_long pmap_pde_mappings;
 2036 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
 2037     &pmap_pde_mappings, 0, "2MB page mappings");
 2038 
 2039 static u_long pmap_pde_p_failures;
 2040 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
 2041     &pmap_pde_p_failures, 0, "2MB page promotion failures");
 2042 
 2043 static u_long pmap_pde_promotions;
 2044 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
 2045     &pmap_pde_promotions, 0, "2MB page promotions");
 2046 
 2047 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
 2048     "1GB page mapping counters");
 2049 
 2050 static u_long pmap_pdpe_demotions;
 2051 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
 2052     &pmap_pdpe_demotions, 0, "1GB page demotions");
 2053 
 2054 /***************************************************
 2055  * Low level helper routines.....
 2056  ***************************************************/
 2057 
 2058 static pt_entry_t
 2059 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
 2060 {
 2061         int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
 2062 
 2063         switch (pmap->pm_type) {
 2064         case PT_X86:
 2065         case PT_RVI:
 2066                 /* Verify that both PAT bits are not set at the same time */
 2067                 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
 2068                     ("Invalid PAT bits in entry %#lx", entry));
 2069 
 2070                 /* Swap the PAT bits if one of them is set */
 2071                 if ((entry & x86_pat_bits) != 0)
 2072                         entry ^= x86_pat_bits;
 2073                 break;
 2074         case PT_EPT:
 2075                 /*
 2076                  * Nothing to do - the memory attributes are represented
 2077                  * the same way for regular pages and superpages.
 2078                  */
 2079                 break;
 2080         default:
 2081                 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
 2082         }
 2083 
 2084         return (entry);
 2085 }
 2086 
 2087 boolean_t
 2088 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
 2089 {
 2090 
 2091         return (mode >= 0 && mode < PAT_INDEX_SIZE &&
 2092             pat_index[(int)mode] >= 0);
 2093 }
 2094 
 2095 /*
 2096  * Determine the appropriate bits to set in a PTE or PDE for a specified
 2097  * caching mode.
 2098  */
 2099 int
 2100 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
 2101 {
 2102         int cache_bits, pat_flag, pat_idx;
 2103 
 2104         if (!pmap_is_valid_memattr(pmap, mode))
 2105                 panic("Unknown caching mode %d\n", mode);
 2106 
 2107         switch (pmap->pm_type) {
 2108         case PT_X86:
 2109         case PT_RVI:
 2110                 /* The PAT bit is different for PTE's and PDE's. */
 2111                 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
 2112 
 2113                 /* Map the caching mode to a PAT index. */
 2114                 pat_idx = pat_index[mode];
 2115 
 2116                 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
 2117                 cache_bits = 0;
 2118                 if (pat_idx & 0x4)
 2119                         cache_bits |= pat_flag;
 2120                 if (pat_idx & 0x2)
 2121                         cache_bits |= PG_NC_PCD;
 2122                 if (pat_idx & 0x1)
 2123                         cache_bits |= PG_NC_PWT;
 2124                 break;
 2125 
 2126         case PT_EPT:
 2127                 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
 2128                 break;
 2129 
 2130         default:
 2131                 panic("unsupported pmap type %d", pmap->pm_type);
 2132         }
 2133 
 2134         return (cache_bits);
 2135 }
 2136 
 2137 static int
 2138 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
 2139 {
 2140         int mask;
 2141 
 2142         switch (pmap->pm_type) {
 2143         case PT_X86:
 2144         case PT_RVI:
 2145                 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
 2146                 break;
 2147         case PT_EPT:
 2148                 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
 2149                 break;
 2150         default:
 2151                 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
 2152         }
 2153 
 2154         return (mask);
 2155 }
 2156 
 2157 static int
 2158 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
 2159 {
 2160         int pat_flag, pat_idx;
 2161 
 2162         pat_idx = 0;
 2163         switch (pmap->pm_type) {
 2164         case PT_X86:
 2165         case PT_RVI:
 2166                 /* The PAT bit is different for PTE's and PDE's. */
 2167                 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
 2168 
 2169                 if ((pte & pat_flag) != 0)
 2170                         pat_idx |= 0x4;
 2171                 if ((pte & PG_NC_PCD) != 0)
 2172                         pat_idx |= 0x2;
 2173                 if ((pte & PG_NC_PWT) != 0)
 2174                         pat_idx |= 0x1;
 2175                 break;
 2176         case PT_EPT:
 2177                 if ((pte & EPT_PG_IGNORE_PAT) != 0)
 2178                         panic("EPT PTE %#lx has no PAT memory type", pte);
 2179                 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
 2180                 break;
 2181         }
 2182 
 2183         /* See pmap_init_pat(). */
 2184         if (pat_idx == 4)
 2185                 pat_idx = 0;
 2186         if (pat_idx == 7)
 2187                 pat_idx = 3;
 2188 
 2189         return (pat_idx);
 2190 }
 2191 
 2192 bool
 2193 pmap_ps_enabled(pmap_t pmap)
 2194 {
 2195 
 2196         return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
 2197 }
 2198 
 2199 static void
 2200 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
 2201 {
 2202 
 2203         switch (pmap->pm_type) {
 2204         case PT_X86:
 2205                 break;
 2206         case PT_RVI:
 2207         case PT_EPT:
 2208                 /*
 2209                  * XXX
 2210                  * This is a little bogus since the generation number is
 2211                  * supposed to be bumped up when a region of the address
 2212                  * space is invalidated in the page tables.
 2213                  *
 2214                  * In this case the old PDE entry is valid but yet we want
 2215                  * to make sure that any mappings using the old entry are
 2216                  * invalidated in the TLB.
 2217                  *
 2218                  * The reason this works as expected is because we rendezvous
 2219                  * "all" host cpus and force any vcpu context to exit as a
 2220                  * side-effect.
 2221                  */
 2222                 atomic_add_acq_long(&pmap->pm_eptgen, 1);
 2223                 break;
 2224         default:
 2225                 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
 2226         }
 2227         pde_store(pde, newpde);
 2228 }
 2229 
 2230 /*
 2231  * After changing the page size for the specified virtual address in the page
 2232  * table, flush the corresponding entries from the processor's TLB.  Only the
 2233  * calling processor's TLB is affected.
 2234  *
 2235  * The calling thread must be pinned to a processor.
 2236  */
 2237 static void
 2238 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
 2239 {
 2240         pt_entry_t PG_G;
 2241 
 2242         if (pmap_type_guest(pmap))
 2243                 return;
 2244 
 2245         KASSERT(pmap->pm_type == PT_X86,
 2246             ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
 2247 
 2248         PG_G = pmap_global_bit(pmap);
 2249 
 2250         if ((newpde & PG_PS) == 0)
 2251                 /* Demotion: flush a specific 2MB page mapping. */
 2252                 invlpg(va);
 2253         else if ((newpde & PG_G) == 0)
 2254                 /*
 2255                  * Promotion: flush every 4KB page mapping from the TLB
 2256                  * because there are too many to flush individually.
 2257                  */
 2258                 invltlb();
 2259         else {
 2260                 /*
 2261                  * Promotion: flush every 4KB page mapping from the TLB,
 2262                  * including any global (PG_G) mappings.
 2263                  */
 2264                 invltlb_glob();
 2265         }
 2266 }
 2267 #ifdef SMP
 2268 
 2269 /*
 2270  * For SMP, these functions have to use the IPI mechanism for coherence.
 2271  *
 2272  * N.B.: Before calling any of the following TLB invalidation functions,
 2273  * the calling processor must ensure that all stores updating a non-
 2274  * kernel page table are globally performed.  Otherwise, another
 2275  * processor could cache an old, pre-update entry without being
 2276  * invalidated.  This can happen one of two ways: (1) The pmap becomes
 2277  * active on another processor after its pm_active field is checked by
 2278  * one of the following functions but before a store updating the page
 2279  * table is globally performed. (2) The pmap becomes active on another
 2280  * processor before its pm_active field is checked but due to
 2281  * speculative loads one of the following functions stills reads the
 2282  * pmap as inactive on the other processor.
 2283  * 
 2284  * The kernel page table is exempt because its pm_active field is
 2285  * immutable.  The kernel page table is always active on every
 2286  * processor.
 2287  */
 2288 
 2289 /*
 2290  * Interrupt the cpus that are executing in the guest context.
 2291  * This will force the vcpu to exit and the cached EPT mappings
 2292  * will be invalidated by the host before the next vmresume.
 2293  */
 2294 static __inline void
 2295 pmap_invalidate_ept(pmap_t pmap)
 2296 {
 2297         int ipinum;
 2298 
 2299         sched_pin();
 2300         KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
 2301             ("pmap_invalidate_ept: absurd pm_active"));
 2302 
 2303         /*
 2304          * The TLB mappings associated with a vcpu context are not
 2305          * flushed each time a different vcpu is chosen to execute.
 2306          *
 2307          * This is in contrast with a process's vtop mappings that
 2308          * are flushed from the TLB on each context switch.
 2309          *
 2310          * Therefore we need to do more than just a TLB shootdown on
 2311          * the active cpus in 'pmap->pm_active'. To do this we keep
 2312          * track of the number of invalidations performed on this pmap.
 2313          *
 2314          * Each vcpu keeps a cache of this counter and compares it
 2315          * just before a vmresume. If the counter is out-of-date an
 2316          * invept will be done to flush stale mappings from the TLB.
 2317          */
 2318         atomic_add_acq_long(&pmap->pm_eptgen, 1);
 2319 
 2320         /*
 2321          * Force the vcpu to exit and trap back into the hypervisor.
 2322          */
 2323         ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
 2324         ipi_selected(pmap->pm_active, ipinum);
 2325         sched_unpin();
 2326 }
 2327 
 2328 static cpuset_t
 2329 pmap_invalidate_cpu_mask(pmap_t pmap)
 2330 {
 2331 
 2332         return (pmap == kernel_pmap ? all_cpus : pmap->pm_active);
 2333 }
 2334 
 2335 static inline void
 2336 pmap_invalidate_page_pcid(pmap_t pmap, vm_offset_t va,
 2337     const bool invpcid_works1)
 2338 {
 2339         struct invpcid_descr d;
 2340         uint64_t kcr3, ucr3;
 2341         uint32_t pcid;
 2342         u_int cpuid, i;
 2343 
 2344         cpuid = PCPU_GET(cpuid);
 2345         if (pmap == PCPU_GET(curpmap)) {
 2346                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2347                         /*
 2348                          * Because pm_pcid is recalculated on a
 2349                          * context switch, we must disable switching.
 2350                          * Otherwise, we might use a stale value
 2351                          * below.
 2352                          */
 2353                         critical_enter();
 2354                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 2355                         if (invpcid_works1) {
 2356                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 2357                                 d.pad = 0;
 2358                                 d.addr = va;
 2359                                 invpcid(&d, INVPCID_ADDR);
 2360                         } else {
 2361                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 2362                                 ucr3 = pmap->pm_ucr3 | pcid |
 2363                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2364                                 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
 2365                         }
 2366                         critical_exit();
 2367                 }
 2368         } else
 2369                 pmap->pm_pcids[cpuid].pm_gen = 0;
 2370 
 2371         CPU_FOREACH(i) {
 2372                 if (cpuid != i)
 2373                         pmap->pm_pcids[i].pm_gen = 0;
 2374         }
 2375 
 2376         /*
 2377          * The fence is between stores to pm_gen and the read of the
 2378          * pm_active mask.  We need to ensure that it is impossible
 2379          * for us to miss the bit update in pm_active and
 2380          * simultaneously observe a non-zero pm_gen in
 2381          * pmap_activate_sw(), otherwise TLB update is missed.
 2382          * Without the fence, IA32 allows such an outcome.  Note that
 2383          * pm_active is updated by a locked operation, which provides
 2384          * the reciprocal fence.
 2385          */
 2386         atomic_thread_fence_seq_cst();
 2387 }
 2388 
 2389 static void
 2390 pmap_invalidate_page_pcid_invpcid(pmap_t pmap, vm_offset_t va)
 2391 {
 2392 
 2393         pmap_invalidate_page_pcid(pmap, va, true);
 2394 }
 2395 
 2396 static void
 2397 pmap_invalidate_page_pcid_noinvpcid(pmap_t pmap, vm_offset_t va)
 2398 {
 2399 
 2400         pmap_invalidate_page_pcid(pmap, va, false);
 2401 }
 2402 
 2403 static void
 2404 pmap_invalidate_page_nopcid(pmap_t pmap, vm_offset_t va)
 2405 {
 2406 }
 2407 
 2408 DEFINE_IFUNC(static, void, pmap_invalidate_page_mode, (pmap_t, vm_offset_t),
 2409     static)
 2410 {
 2411 
 2412         if (pmap_pcid_enabled)
 2413                 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid :
 2414                     pmap_invalidate_page_pcid_noinvpcid);
 2415         return (pmap_invalidate_page_nopcid);
 2416 }
 2417 
 2418 static void
 2419 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
 2420     vm_offset_t addr2 __unused)
 2421 {
 2422 
 2423         if (pmap == kernel_pmap) {
 2424                 invlpg(va);
 2425         } else {
 2426                 if (pmap == PCPU_GET(curpmap))
 2427                         invlpg(va);
 2428                 pmap_invalidate_page_mode(pmap, va);
 2429         }
 2430 }
 2431 
 2432 void
 2433 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
 2434 {
 2435 
 2436         if (pmap_type_guest(pmap)) {
 2437                 pmap_invalidate_ept(pmap);
 2438                 return;
 2439         }
 2440 
 2441         KASSERT(pmap->pm_type == PT_X86,
 2442             ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
 2443 
 2444         smp_masked_invlpg(pmap_invalidate_cpu_mask(pmap), va, pmap,
 2445             pmap_invalidate_page_curcpu_cb);
 2446 }
 2447 
 2448 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
 2449 #define PMAP_INVLPG_THRESHOLD   (4 * 1024 * PAGE_SIZE)
 2450 
 2451 static void
 2452 pmap_invalidate_range_pcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
 2453     const bool invpcid_works1)
 2454 {
 2455         struct invpcid_descr d;
 2456         uint64_t kcr3, ucr3;
 2457         uint32_t pcid;
 2458         u_int cpuid, i;
 2459 
 2460         cpuid = PCPU_GET(cpuid);
 2461         if (pmap == PCPU_GET(curpmap)) {
 2462                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2463                         critical_enter();
 2464                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 2465                         if (invpcid_works1) {
 2466                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 2467                                 d.pad = 0;
 2468                                 d.addr = sva;
 2469                                 for (; d.addr < eva; d.addr += PAGE_SIZE)
 2470                                         invpcid(&d, INVPCID_ADDR);
 2471                         } else {
 2472                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 2473                                 ucr3 = pmap->pm_ucr3 | pcid |
 2474                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2475                                 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
 2476                         }
 2477                         critical_exit();
 2478                 }
 2479         } else
 2480                 pmap->pm_pcids[cpuid].pm_gen = 0;
 2481 
 2482         CPU_FOREACH(i) {
 2483                 if (cpuid != i)
 2484                         pmap->pm_pcids[i].pm_gen = 0;
 2485         }
 2486         /* See the comment in pmap_invalidate_page_pcid(). */
 2487         atomic_thread_fence_seq_cst();
 2488 }
 2489 
 2490 static void
 2491 pmap_invalidate_range_pcid_invpcid(pmap_t pmap, vm_offset_t sva,
 2492     vm_offset_t eva)
 2493 {
 2494 
 2495         pmap_invalidate_range_pcid(pmap, sva, eva, true);
 2496 }
 2497 
 2498 static void
 2499 pmap_invalidate_range_pcid_noinvpcid(pmap_t pmap, vm_offset_t sva,
 2500     vm_offset_t eva)
 2501 {
 2502 
 2503         pmap_invalidate_range_pcid(pmap, sva, eva, false);
 2504 }
 2505 
 2506 static void
 2507 pmap_invalidate_range_nopcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2508 {
 2509 }
 2510 
 2511 DEFINE_IFUNC(static, void, pmap_invalidate_range_mode, (pmap_t, vm_offset_t,
 2512     vm_offset_t), static)
 2513 {
 2514 
 2515         if (pmap_pcid_enabled)
 2516                 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid :
 2517                     pmap_invalidate_range_pcid_noinvpcid);
 2518         return (pmap_invalidate_range_nopcid);
 2519 }
 2520 
 2521 static void
 2522 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2523 {
 2524         vm_offset_t addr;
 2525 
 2526         if (pmap == kernel_pmap) {
 2527                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
 2528                         invlpg(addr);
 2529         } else {
 2530                 if (pmap == PCPU_GET(curpmap)) {
 2531                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
 2532                                 invlpg(addr);
 2533                 }
 2534                 pmap_invalidate_range_mode(pmap, sva, eva);
 2535         }
 2536 }
 2537 
 2538 void
 2539 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2540 {
 2541 
 2542         if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
 2543                 pmap_invalidate_all(pmap);
 2544                 return;
 2545         }
 2546 
 2547         if (pmap_type_guest(pmap)) {
 2548                 pmap_invalidate_ept(pmap);
 2549                 return;
 2550         }
 2551 
 2552         KASSERT(pmap->pm_type == PT_X86,
 2553             ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
 2554 
 2555         smp_masked_invlpg_range(pmap_invalidate_cpu_mask(pmap), sva, eva, pmap,
 2556             pmap_invalidate_range_curcpu_cb);
 2557 }
 2558 
 2559 static inline void
 2560 pmap_invalidate_all_pcid(pmap_t pmap, bool invpcid_works1)
 2561 {
 2562         struct invpcid_descr d;
 2563         uint64_t kcr3, ucr3;
 2564         uint32_t pcid;
 2565         u_int cpuid, i;
 2566 
 2567         if (pmap == kernel_pmap) {
 2568                 if (invpcid_works1) {
 2569                         bzero(&d, sizeof(d));
 2570                         invpcid(&d, INVPCID_CTXGLOB);
 2571                 } else {
 2572                         invltlb_glob();
 2573                 }
 2574         } else {
 2575                 cpuid = PCPU_GET(cpuid);
 2576                 if (pmap == PCPU_GET(curpmap)) {
 2577                         critical_enter();
 2578                         pcid = pmap->pm_pcids[cpuid].pm_pcid;
 2579                         if (invpcid_works1) {
 2580                                 d.pcid = pcid;
 2581                                 d.pad = 0;
 2582                                 d.addr = 0;
 2583                                 invpcid(&d, INVPCID_CTX);
 2584                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2585                                         d.pcid |= PMAP_PCID_USER_PT;
 2586                                         invpcid(&d, INVPCID_CTX);
 2587                                 }
 2588                         } else {
 2589                                 kcr3 = pmap->pm_cr3 | pcid;
 2590                                 ucr3 = pmap->pm_ucr3;
 2591                                 if (ucr3 != PMAP_NO_CR3) {
 2592                                         ucr3 |= pcid | PMAP_PCID_USER_PT;
 2593                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
 2594                                 } else {
 2595                                         load_cr3(kcr3);
 2596                                 }
 2597                         }
 2598                         critical_exit();
 2599                 } else
 2600                         pmap->pm_pcids[cpuid].pm_gen = 0;
 2601                 CPU_FOREACH(i) {
 2602                         if (cpuid != i)
 2603                                 pmap->pm_pcids[i].pm_gen = 0;
 2604                 }
 2605         }
 2606         /* See the comment in pmap_invalidate_page_pcid(). */
 2607         atomic_thread_fence_seq_cst();
 2608 }
 2609 
 2610 static void
 2611 pmap_invalidate_all_pcid_invpcid(pmap_t pmap)
 2612 {
 2613 
 2614         pmap_invalidate_all_pcid(pmap, true);
 2615 }
 2616 
 2617 static void
 2618 pmap_invalidate_all_pcid_noinvpcid(pmap_t pmap)
 2619 {
 2620 
 2621         pmap_invalidate_all_pcid(pmap, false);
 2622 }
 2623 
 2624 static void
 2625 pmap_invalidate_all_nopcid(pmap_t pmap)
 2626 {
 2627 
 2628         if (pmap == kernel_pmap)
 2629                 invltlb_glob();
 2630         else if (pmap == PCPU_GET(curpmap))
 2631                 invltlb();
 2632 }
 2633 
 2634 DEFINE_IFUNC(static, void, pmap_invalidate_all_mode, (pmap_t), static)
 2635 {
 2636 
 2637         if (pmap_pcid_enabled)
 2638                 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid :
 2639                     pmap_invalidate_all_pcid_noinvpcid);
 2640         return (pmap_invalidate_all_nopcid);
 2641 }
 2642 
 2643 static void
 2644 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
 2645     vm_offset_t addr2 __unused)
 2646 {
 2647 
 2648         pmap_invalidate_all_mode(pmap);
 2649 }
 2650 
 2651 void
 2652 pmap_invalidate_all(pmap_t pmap)
 2653 {
 2654 
 2655         if (pmap_type_guest(pmap)) {
 2656                 pmap_invalidate_ept(pmap);
 2657                 return;
 2658         }
 2659 
 2660         KASSERT(pmap->pm_type == PT_X86,
 2661             ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
 2662 
 2663         smp_masked_invltlb(pmap_invalidate_cpu_mask(pmap), pmap,
 2664             pmap_invalidate_all_curcpu_cb);
 2665 }
 2666 
 2667 static void
 2668 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
 2669     vm_offset_t addr2 __unused)
 2670 {
 2671 
 2672         wbinvd();
 2673 }
 2674 
 2675 void
 2676 pmap_invalidate_cache(void)
 2677 {
 2678 
 2679         smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
 2680 }
 2681 
 2682 struct pde_action {
 2683         cpuset_t invalidate;    /* processors that invalidate their TLB */
 2684         pmap_t pmap;
 2685         vm_offset_t va;
 2686         pd_entry_t *pde;
 2687         pd_entry_t newpde;
 2688         u_int store;            /* processor that updates the PDE */
 2689 };
 2690 
 2691 static void
 2692 pmap_update_pde_action(void *arg)
 2693 {
 2694         struct pde_action *act = arg;
 2695 
 2696         if (act->store == PCPU_GET(cpuid))
 2697                 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
 2698 }
 2699 
 2700 static void
 2701 pmap_update_pde_teardown(void *arg)
 2702 {
 2703         struct pde_action *act = arg;
 2704 
 2705         if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
 2706                 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
 2707 }
 2708 
 2709 /*
 2710  * Change the page size for the specified virtual address in a way that
 2711  * prevents any possibility of the TLB ever having two entries that map the
 2712  * same virtual address using different page sizes.  This is the recommended
 2713  * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
 2714  * machine check exception for a TLB state that is improperly diagnosed as a
 2715  * hardware error.
 2716  */
 2717 static void
 2718 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
 2719 {
 2720         struct pde_action act;
 2721         cpuset_t active, other_cpus;
 2722         u_int cpuid;
 2723 
 2724         sched_pin();
 2725         cpuid = PCPU_GET(cpuid);
 2726         other_cpus = all_cpus;
 2727         CPU_CLR(cpuid, &other_cpus);
 2728         if (pmap == kernel_pmap || pmap_type_guest(pmap)) 
 2729                 active = all_cpus;
 2730         else {
 2731                 active = pmap->pm_active;
 2732         }
 2733         if (CPU_OVERLAP(&active, &other_cpus)) { 
 2734                 act.store = cpuid;
 2735                 act.invalidate = active;
 2736                 act.va = va;
 2737                 act.pmap = pmap;
 2738                 act.pde = pde;
 2739                 act.newpde = newpde;
 2740                 CPU_SET(cpuid, &active);
 2741                 smp_rendezvous_cpus(active,
 2742                     smp_no_rendezvous_barrier, pmap_update_pde_action,
 2743                     pmap_update_pde_teardown, &act);
 2744         } else {
 2745                 pmap_update_pde_store(pmap, pde, newpde);
 2746                 if (CPU_ISSET(cpuid, &active))
 2747                         pmap_update_pde_invalidate(pmap, va, newpde);
 2748         }
 2749         sched_unpin();
 2750 }
 2751 #else /* !SMP */
 2752 /*
 2753  * Normal, non-SMP, invalidation functions.
 2754  */
 2755 void
 2756 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
 2757 {
 2758         struct invpcid_descr d;
 2759         uint64_t kcr3, ucr3;
 2760         uint32_t pcid;
 2761 
 2762         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2763                 pmap->pm_eptgen++;
 2764                 return;
 2765         }
 2766         KASSERT(pmap->pm_type == PT_X86,
 2767             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
 2768 
 2769         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
 2770                 invlpg(va);
 2771                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
 2772                     pmap->pm_ucr3 != PMAP_NO_CR3) {
 2773                         critical_enter();
 2774                         pcid = pmap->pm_pcids[0].pm_pcid;
 2775                         if (invpcid_works) {
 2776                                 d.pcid = pcid | PMAP_PCID_USER_PT;
 2777                                 d.pad = 0;
 2778                                 d.addr = va;
 2779                                 invpcid(&d, INVPCID_ADDR);
 2780                         } else {
 2781                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
 2782                                 ucr3 = pmap->pm_ucr3 | pcid |
 2783                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2784                                 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
 2785                         }
 2786                         critical_exit();
 2787                 }
 2788         } else if (pmap_pcid_enabled)
 2789                 pmap->pm_pcids[0].pm_gen = 0;
 2790 }
 2791 
 2792 void
 2793 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2794 {
 2795         struct invpcid_descr d;
 2796         vm_offset_t addr;
 2797         uint64_t kcr3, ucr3;
 2798 
 2799         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2800                 pmap->pm_eptgen++;
 2801                 return;
 2802         }
 2803         KASSERT(pmap->pm_type == PT_X86,
 2804             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
 2805 
 2806         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
 2807                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
 2808                         invlpg(addr);
 2809                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
 2810                     pmap->pm_ucr3 != PMAP_NO_CR3) {
 2811                         critical_enter();
 2812                         if (invpcid_works) {
 2813                                 d.pcid = pmap->pm_pcids[0].pm_pcid |
 2814                                     PMAP_PCID_USER_PT;
 2815                                 d.pad = 0;
 2816                                 d.addr = sva;
 2817                                 for (; d.addr < eva; d.addr += PAGE_SIZE)
 2818                                         invpcid(&d, INVPCID_ADDR);
 2819                         } else {
 2820                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
 2821                                     pm_pcid | CR3_PCID_SAVE;
 2822                                 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
 2823                                     pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
 2824                                 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
 2825                         }
 2826                         critical_exit();
 2827                 }
 2828         } else if (pmap_pcid_enabled) {
 2829                 pmap->pm_pcids[0].pm_gen = 0;
 2830         }
 2831 }
 2832 
 2833 void
 2834 pmap_invalidate_all(pmap_t pmap)
 2835 {
 2836         struct invpcid_descr d;
 2837         uint64_t kcr3, ucr3;
 2838 
 2839         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
 2840                 pmap->pm_eptgen++;
 2841                 return;
 2842         }
 2843         KASSERT(pmap->pm_type == PT_X86,
 2844             ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
 2845 
 2846         if (pmap == kernel_pmap) {
 2847                 if (pmap_pcid_enabled && invpcid_works) {
 2848                         bzero(&d, sizeof(d));
 2849                         invpcid(&d, INVPCID_CTXGLOB);
 2850                 } else {
 2851                         invltlb_glob();
 2852                 }
 2853         } else if (pmap == PCPU_GET(curpmap)) {
 2854                 if (pmap_pcid_enabled) {
 2855                         critical_enter();
 2856                         if (invpcid_works) {
 2857                                 d.pcid = pmap->pm_pcids[0].pm_pcid;
 2858                                 d.pad = 0;
 2859                                 d.addr = 0;
 2860                                 invpcid(&d, INVPCID_CTX);
 2861                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2862                                         d.pcid |= PMAP_PCID_USER_PT;
 2863                                         invpcid(&d, INVPCID_CTX);
 2864                                 }
 2865                         } else {
 2866                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
 2867                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
 2868                                         ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
 2869                                             0].pm_pcid | PMAP_PCID_USER_PT;
 2870                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
 2871                                 } else
 2872                                         load_cr3(kcr3);
 2873                         }
 2874                         critical_exit();
 2875                 } else {
 2876                         invltlb();
 2877                 }
 2878         } else if (pmap_pcid_enabled) {
 2879                 pmap->pm_pcids[0].pm_gen = 0;
 2880         }
 2881 }
 2882 
 2883 PMAP_INLINE void
 2884 pmap_invalidate_cache(void)
 2885 {
 2886 
 2887         wbinvd();
 2888 }
 2889 
 2890 static void
 2891 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
 2892 {
 2893 
 2894         pmap_update_pde_store(pmap, pde, newpde);
 2895         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
 2896                 pmap_update_pde_invalidate(pmap, va, newpde);
 2897         else
 2898                 pmap->pm_pcids[0].pm_gen = 0;
 2899 }
 2900 #endif /* !SMP */
 2901 
 2902 static void
 2903 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
 2904 {
 2905 
 2906         /*
 2907          * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
 2908          * by a promotion that did not invalidate the 512 4KB page mappings
 2909          * that might exist in the TLB.  Consequently, at this point, the TLB
 2910          * may hold both 4KB and 2MB page mappings for the address range [va,
 2911          * va + NBPDR).  Therefore, the entire range must be invalidated here.
 2912          * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
 2913          * 4KB page mappings for the address range [va, va + NBPDR), and so a
 2914          * single INVLPG suffices to invalidate the 2MB page mapping from the
 2915          * TLB.
 2916          */
 2917         if ((pde & PG_PROMOTED) != 0)
 2918                 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
 2919         else
 2920                 pmap_invalidate_page(pmap, va);
 2921 }
 2922 
 2923 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
 2924     (vm_offset_t sva, vm_offset_t eva), static)
 2925 {
 2926 
 2927         if ((cpu_feature & CPUID_SS) != 0)
 2928                 return (pmap_invalidate_cache_range_selfsnoop);
 2929         if ((cpu_feature & CPUID_CLFSH) != 0)
 2930                 return (pmap_force_invalidate_cache_range);
 2931         return (pmap_invalidate_cache_range_all);
 2932 }
 2933 
 2934 #define PMAP_CLFLUSH_THRESHOLD   (2 * 1024 * 1024)
 2935 
 2936 static void
 2937 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
 2938 {
 2939 
 2940         KASSERT((sva & PAGE_MASK) == 0,
 2941             ("pmap_invalidate_cache_range: sva not page-aligned"));
 2942         KASSERT((eva & PAGE_MASK) == 0,
 2943             ("pmap_invalidate_cache_range: eva not page-aligned"));
 2944 }
 2945 
 2946 static void
 2947 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
 2948 {
 2949 
 2950         pmap_invalidate_cache_range_check_align(sva, eva);
 2951 }
 2952 
 2953 void
 2954 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
 2955 {
 2956 
 2957         sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
 2958 
 2959         /*
 2960          * XXX: Some CPUs fault, hang, or trash the local APIC
 2961          * registers if we use CLFLUSH on the local APIC range.  The
 2962          * local APIC is always uncached, so we don't need to flush
 2963          * for that range anyway.
 2964          */
 2965         if (pmap_kextract(sva) == lapic_paddr)
 2966                 return;
 2967 
 2968         if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
 2969                 /*
 2970                  * Do per-cache line flush.  Use a locked
 2971                  * instruction to insure that previous stores are
 2972                  * included in the write-back.  The processor
 2973                  * propagates flush to other processors in the cache
 2974                  * coherence domain.
 2975                  */
 2976                 atomic_thread_fence_seq_cst();
 2977                 for (; sva < eva; sva += cpu_clflush_line_size)
 2978                         clflushopt(sva);
 2979                 atomic_thread_fence_seq_cst();
 2980         } else {
 2981                 /*
 2982                  * Writes are ordered by CLFLUSH on Intel CPUs.
 2983                  */
 2984                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2985                         mfence();
 2986                 for (; sva < eva; sva += cpu_clflush_line_size)
 2987                         clflush(sva);
 2988                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
 2989                         mfence();
 2990         }
 2991 }
 2992 
 2993 static void
 2994 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
 2995 {
 2996 
 2997         pmap_invalidate_cache_range_check_align(sva, eva);
 2998         pmap_invalidate_cache();
 2999 }
 3000 
 3001 /*
 3002  * Remove the specified set of pages from the data and instruction caches.
 3003  *
 3004  * In contrast to pmap_invalidate_cache_range(), this function does not
 3005  * rely on the CPU's self-snoop feature, because it is intended for use
 3006  * when moving pages into a different cache domain.
 3007  */
 3008 void
 3009 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
 3010 {
 3011         vm_offset_t daddr, eva;
 3012         int i;
 3013         bool useclflushopt;
 3014 
 3015         useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
 3016         if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
 3017             ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
 3018                 pmap_invalidate_cache();
 3019         else {
 3020                 if (useclflushopt)
 3021                         atomic_thread_fence_seq_cst();
 3022                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
 3023                         mfence();
 3024                 for (i = 0; i < count; i++) {
 3025                         daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
 3026                         eva = daddr + PAGE_SIZE;
 3027                         for (; daddr < eva; daddr += cpu_clflush_line_size) {
 3028                                 if (useclflushopt)
 3029                                         clflushopt(daddr);
 3030                                 else
 3031                                         clflush(daddr);
 3032                         }
 3033                 }
 3034                 if (useclflushopt)
 3035                         atomic_thread_fence_seq_cst();
 3036                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
 3037                         mfence();
 3038         }
 3039 }
 3040 
 3041 void
 3042 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
 3043 {
 3044 
 3045         pmap_invalidate_cache_range_check_align(sva, eva);
 3046 
 3047         if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
 3048                 pmap_force_invalidate_cache_range(sva, eva);
 3049                 return;
 3050         }
 3051 
 3052         /* See comment in pmap_force_invalidate_cache_range(). */
 3053         if (pmap_kextract(sva) == lapic_paddr)
 3054                 return;
 3055 
 3056         atomic_thread_fence_seq_cst();
 3057         for (; sva < eva; sva += cpu_clflush_line_size)
 3058                 clwb(sva);
 3059         atomic_thread_fence_seq_cst();
 3060 }
 3061 
 3062 void
 3063 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
 3064 {
 3065         pt_entry_t *pte;
 3066         vm_offset_t vaddr;
 3067         int error, pte_bits;
 3068 
 3069         KASSERT((spa & PAGE_MASK) == 0,
 3070             ("pmap_flush_cache_phys_range: spa not page-aligned"));
 3071         KASSERT((epa & PAGE_MASK) == 0,
 3072             ("pmap_flush_cache_phys_range: epa not page-aligned"));
 3073 
 3074         if (spa < dmaplimit) {
 3075                 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
 3076                     dmaplimit, epa)));
 3077                 if (dmaplimit >= epa)
 3078                         return;
 3079                 spa = dmaplimit;
 3080         }
 3081 
 3082         pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
 3083             X86_PG_V;
 3084         error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
 3085             &vaddr);
 3086         KASSERT(error == 0, ("vmem_alloc failed: %d", error));
 3087         pte = vtopte(vaddr);
 3088         for (; spa < epa; spa += PAGE_SIZE) {
 3089                 sched_pin();
 3090                 pte_store(pte, spa | pte_bits);
 3091                 invlpg(vaddr);
 3092                 /* XXXKIB atomic inside flush_cache_range are excessive */
 3093                 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
 3094                 sched_unpin();
 3095         }
 3096         vmem_free(kernel_arena, vaddr, PAGE_SIZE);
 3097 }
 3098 
 3099 /*
 3100  *      Routine:        pmap_extract
 3101  *      Function:
 3102  *              Extract the physical page address associated
 3103  *              with the given map/virtual_address pair.
 3104  */
 3105 vm_paddr_t 
 3106 pmap_extract(pmap_t pmap, vm_offset_t va)
 3107 {
 3108         pdp_entry_t *pdpe;
 3109         pd_entry_t *pde;
 3110         pt_entry_t *pte, PG_V;
 3111         vm_paddr_t pa;
 3112 
 3113         pa = 0;
 3114         PG_V = pmap_valid_bit(pmap);
 3115         PMAP_LOCK(pmap);
 3116         pdpe = pmap_pdpe(pmap, va);
 3117         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
 3118                 if ((*pdpe & PG_PS) != 0)
 3119                         pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
 3120                 else {
 3121                         pde = pmap_pdpe_to_pde(pdpe, va);
 3122                         if ((*pde & PG_V) != 0) {
 3123                                 if ((*pde & PG_PS) != 0) {
 3124                                         pa = (*pde & PG_PS_FRAME) |
 3125                                             (va & PDRMASK);
 3126                                 } else {
 3127                                         pte = pmap_pde_to_pte(pde, va);
 3128                                         pa = (*pte & PG_FRAME) |
 3129                                             (va & PAGE_MASK);
 3130                                 }
 3131                         }
 3132                 }
 3133         }
 3134         PMAP_UNLOCK(pmap);
 3135         return (pa);
 3136 }
 3137 
 3138 /*
 3139  *      Routine:        pmap_extract_and_hold
 3140  *      Function:
 3141  *              Atomically extract and hold the physical page
 3142  *              with the given pmap and virtual address pair
 3143  *              if that mapping permits the given protection.
 3144  */
 3145 vm_page_t
 3146 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
 3147 {
 3148         pd_entry_t pde, *pdep;
 3149         pt_entry_t pte, PG_RW, PG_V;
 3150         vm_paddr_t pa;
 3151         vm_page_t m;
 3152 
 3153         pa = 0;
 3154         m = NULL;
 3155         PG_RW = pmap_rw_bit(pmap);
 3156         PG_V = pmap_valid_bit(pmap);
 3157         PMAP_LOCK(pmap);
 3158 retry:
 3159         pdep = pmap_pde(pmap, va);
 3160         if (pdep != NULL && (pde = *pdep)) {
 3161                 if (pde & PG_PS) {
 3162                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
 3163                                 if (vm_page_pa_tryrelock(pmap, (pde &
 3164                                     PG_PS_FRAME) | (va & PDRMASK), &pa))
 3165                                         goto retry;
 3166                                 m = PHYS_TO_VM_PAGE(pa);
 3167                         }
 3168                 } else {
 3169                         pte = *pmap_pde_to_pte(pdep, va);
 3170                         if ((pte & PG_V) &&
 3171                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
 3172                                 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
 3173                                     &pa))
 3174                                         goto retry;
 3175                                 m = PHYS_TO_VM_PAGE(pa);
 3176                         }
 3177                 }
 3178                 if (m != NULL)
 3179                         vm_page_hold(m);
 3180         }
 3181         PA_UNLOCK_COND(pa);
 3182         PMAP_UNLOCK(pmap);
 3183         return (m);
 3184 }
 3185 
 3186 vm_paddr_t
 3187 pmap_kextract(vm_offset_t va)
 3188 {
 3189         pd_entry_t pde;
 3190         vm_paddr_t pa;
 3191 
 3192         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
 3193                 pa = DMAP_TO_PHYS(va);
 3194         } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
 3195                 pa = pmap_large_map_kextract(va);
 3196         } else {
 3197                 pde = *vtopde(va);
 3198                 if (pde & PG_PS) {
 3199                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
 3200                 } else {
 3201                         /*
 3202                          * Beware of a concurrent promotion that changes the
 3203                          * PDE at this point!  For example, vtopte() must not
 3204                          * be used to access the PTE because it would use the
 3205                          * new PDE.  It is, however, safe to use the old PDE
 3206                          * because the page table page is preserved by the
 3207                          * promotion.
 3208                          */
 3209                         pa = *pmap_pde_to_pte(&pde, va);
 3210                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
 3211                 }
 3212         }
 3213         return (pa);
 3214 }
 3215 
 3216 /***************************************************
 3217  * Low level mapping routines.....
 3218  ***************************************************/
 3219 
 3220 /*
 3221  * Add a wired page to the kva.
 3222  * Note: not SMP coherent.
 3223  */
 3224 PMAP_INLINE void 
 3225 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 3226 {
 3227         pt_entry_t *pte;
 3228 
 3229         pte = vtopte(va);
 3230         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | pg_nx);
 3231 }
 3232 
 3233 static __inline void
 3234 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
 3235 {
 3236         pt_entry_t *pte;
 3237         int cache_bits;
 3238 
 3239         pte = vtopte(va);
 3240         cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
 3241         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | pg_nx | cache_bits);
 3242 }
 3243 
 3244 /*
 3245  * Remove a page from the kernel pagetables.
 3246  * Note: not SMP coherent.
 3247  */
 3248 PMAP_INLINE void
 3249 pmap_kremove(vm_offset_t va)
 3250 {
 3251         pt_entry_t *pte;
 3252 
 3253         pte = vtopte(va);
 3254         pte_clear(pte);
 3255 }
 3256 
 3257 /*
 3258  *      Used to map a range of physical addresses into kernel
 3259  *      virtual address space.
 3260  *
 3261  *      The value passed in '*virt' is a suggested virtual address for
 3262  *      the mapping. Architectures which can support a direct-mapped
 3263  *      physical to virtual region can return the appropriate address
 3264  *      within that region, leaving '*virt' unchanged. Other
 3265  *      architectures should map the pages starting at '*virt' and
 3266  *      update '*virt' with the first usable address after the mapped
 3267  *      region.
 3268  */
 3269 vm_offset_t
 3270 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
 3271 {
 3272         return PHYS_TO_DMAP(start);
 3273 }
 3274 
 3275 
 3276 /*
 3277  * Add a list of wired pages to the kva
 3278  * this routine is only used for temporary
 3279  * kernel mappings that do not need to have
 3280  * page modification or references recorded.
 3281  * Note that old mappings are simply written
 3282  * over.  The page *must* be wired.
 3283  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 3284  */
 3285 void
 3286 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
 3287 {
 3288         pt_entry_t *endpte, oldpte, pa, *pte;
 3289         vm_page_t m;
 3290         int cache_bits;
 3291 
 3292         oldpte = 0;
 3293         pte = vtopte(sva);
 3294         endpte = pte + count;
 3295         while (pte < endpte) {
 3296                 m = *ma++;
 3297                 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
 3298                 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
 3299                 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
 3300                         oldpte |= *pte;
 3301                         pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
 3302                 }
 3303                 pte++;
 3304         }
 3305         if (__predict_false((oldpte & X86_PG_V) != 0))
 3306                 pmap_invalidate_range(kernel_pmap, sva, sva + count *
 3307                     PAGE_SIZE);
 3308 }
 3309 
 3310 /*
 3311  * This routine tears out page mappings from the
 3312  * kernel -- it is meant only for temporary mappings.
 3313  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 3314  */
 3315 void
 3316 pmap_qremove(vm_offset_t sva, int count)
 3317 {
 3318         vm_offset_t va;
 3319 
 3320         va = sva;
 3321         while (count-- > 0) {
 3322                 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
 3323                 pmap_kremove(va);
 3324                 va += PAGE_SIZE;
 3325         }
 3326         pmap_invalidate_range(kernel_pmap, sva, va);
 3327 }
 3328 
 3329 /***************************************************
 3330  * Page table page management routines.....
 3331  ***************************************************/
 3332 /*
 3333  * Schedule the specified unused page table page to be freed.  Specifically,
 3334  * add the page to the specified list of pages that will be released to the
 3335  * physical memory manager after the TLB has been updated.
 3336  */
 3337 static __inline void
 3338 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
 3339     boolean_t set_PG_ZERO)
 3340 {
 3341 
 3342         if (set_PG_ZERO)
 3343                 m->flags |= PG_ZERO;
 3344         else
 3345                 m->flags &= ~PG_ZERO;
 3346         SLIST_INSERT_HEAD(free, m, plinks.s.ss);
 3347 }
 3348         
 3349 /*
 3350  * Inserts the specified page table page into the specified pmap's collection
 3351  * of idle page table pages.  Each of a pmap's page table pages is responsible
 3352  * for mapping a distinct range of virtual addresses.  The pmap's collection is
 3353  * ordered by this virtual address range.
 3354  *
 3355  * If "promoted" is false, then the page table page "mpte" must be zero filled.
 3356  */
 3357 static __inline int
 3358 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
 3359 {
 3360 
 3361         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3362         mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
 3363         return (vm_radix_insert(&pmap->pm_root, mpte));
 3364 }
 3365 
 3366 /*
 3367  * Removes the page table page mapping the specified virtual address from the
 3368  * specified pmap's collection of idle page table pages, and returns it.
 3369  * Otherwise, returns NULL if there is no page table page corresponding to the
 3370  * specified virtual address.
 3371  */
 3372 static __inline vm_page_t
 3373 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
 3374 {
 3375 
 3376         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3377         return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
 3378 }
 3379 
 3380 /*
 3381  * Decrements a page table page's wire count, which is used to record the
 3382  * number of valid page table entries within the page.  If the wire count
 3383  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
 3384  * page table page was unmapped and FALSE otherwise.
 3385  */
 3386 static inline boolean_t
 3387 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
 3388 {
 3389 
 3390         --m->wire_count;
 3391         if (m->wire_count == 0) {
 3392                 _pmap_unwire_ptp(pmap, va, m, free);
 3393                 return (TRUE);
 3394         } else
 3395                 return (FALSE);
 3396 }
 3397 
 3398 static void
 3399 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
 3400 {
 3401 
 3402         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3403         /*
 3404          * unmap the page table page
 3405          */
 3406         if (m->pindex >= (NUPDE + NUPDPE)) {
 3407                 /* PDP page */
 3408                 pml4_entry_t *pml4;
 3409                 pml4 = pmap_pml4e(pmap, va);
 3410                 *pml4 = 0;
 3411                 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
 3412                         pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
 3413                         *pml4 = 0;
 3414                 }
 3415         } else if (m->pindex >= NUPDE) {
 3416                 /* PD page */
 3417                 pdp_entry_t *pdp;
 3418                 pdp = pmap_pdpe(pmap, va);
 3419                 *pdp = 0;
 3420         } else {
 3421                 /* PTE page */
 3422                 pd_entry_t *pd;
 3423                 pd = pmap_pde(pmap, va);
 3424                 *pd = 0;
 3425         }
 3426         pmap_resident_count_dec(pmap, 1);
 3427         if (m->pindex < NUPDE) {
 3428                 /* We just released a PT, unhold the matching PD */
 3429                 vm_page_t pdpg;
 3430 
 3431                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
 3432                 pmap_unwire_ptp(pmap, va, pdpg, free);
 3433         }
 3434         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
 3435                 /* We just released a PD, unhold the matching PDP */
 3436                 vm_page_t pdppg;
 3437 
 3438                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
 3439                 pmap_unwire_ptp(pmap, va, pdppg, free);
 3440         }
 3441 
 3442         /* 
 3443          * Put page on a list so that it is released after
 3444          * *ALL* TLB shootdown is done
 3445          */
 3446         pmap_add_delayed_free_list(m, free, TRUE);
 3447 }
 3448 
 3449 /*
 3450  * After removing a page table entry, this routine is used to
 3451  * conditionally free the page, and manage the hold/wire counts.
 3452  */
 3453 static int
 3454 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
 3455     struct spglist *free)
 3456 {
 3457         vm_page_t mpte;
 3458 
 3459         if (va >= VM_MAXUSER_ADDRESS)
 3460                 return (0);
 3461         KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
 3462         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
 3463         return (pmap_unwire_ptp(pmap, va, mpte, free));
 3464 }
 3465 
 3466 void
 3467 pmap_pinit0(pmap_t pmap)
 3468 {
 3469         struct proc *p;
 3470         struct thread *td;
 3471         int i;
 3472 
 3473         PMAP_LOCK_INIT(pmap);
 3474         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
 3475         pmap->pm_pml4u = NULL;
 3476         pmap->pm_cr3 = KPML4phys;
 3477         /* hack to keep pmap_pti_pcid_invalidate() alive */
 3478         pmap->pm_ucr3 = PMAP_NO_CR3;
 3479         pmap->pm_root.rt_root = 0;
 3480         CPU_ZERO(&pmap->pm_active);
 3481         TAILQ_INIT(&pmap->pm_pvchunk);
 3482         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 3483         pmap->pm_flags = pmap_flags;
 3484         CPU_FOREACH(i) {
 3485                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
 3486                 pmap->pm_pcids[i].pm_gen = 1;
 3487         }
 3488         pmap_activate_boot(pmap);
 3489         td = curthread;
 3490         if (pti) {
 3491                 p = td->td_proc;
 3492                 PROC_LOCK(p);
 3493                 p->p_amd64_md_flags |= P_MD_KPTI;
 3494                 PROC_UNLOCK(p);
 3495         }
 3496         pmap_thread_init_invl_gen(td);
 3497 
 3498         if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
 3499                 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
 3500                     sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
 3501                     UMA_ALIGN_PTR, 0);
 3502         }
 3503 }
 3504 
 3505 void
 3506 pmap_pinit_pml4(vm_page_t pml4pg)
 3507 {
 3508         pml4_entry_t *pm_pml4;
 3509         int i;
 3510 
 3511         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
 3512 
 3513         /* Wire in kernel global address entries. */
 3514         for (i = 0; i < NKPML4E; i++) {
 3515                 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
 3516                     X86_PG_V;
 3517         }
 3518         for (i = 0; i < ndmpdpphys; i++) {
 3519                 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
 3520                     X86_PG_V;
 3521         }
 3522 
 3523         /* install self-referential address mapping entry(s) */
 3524         pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
 3525             X86_PG_A | X86_PG_M;
 3526 
 3527         /* install large map entries if configured */
 3528         for (i = 0; i < lm_ents; i++)
 3529                 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pml4[LMSPML4I + i];
 3530 }
 3531 
 3532 static void
 3533 pmap_pinit_pml4_pti(vm_page_t pml4pg)
 3534 {
 3535         pml4_entry_t *pm_pml4;
 3536         int i;
 3537 
 3538         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
 3539         for (i = 0; i < NPML4EPG; i++)
 3540                 pm_pml4[i] = pti_pml4[i];
 3541 }
 3542 
 3543 /*
 3544  * Initialize a preallocated and zeroed pmap structure,
 3545  * such as one in a vmspace structure.
 3546  */
 3547 int
 3548 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
 3549 {
 3550         vm_page_t pml4pg, pml4pgu;
 3551         vm_paddr_t pml4phys;
 3552         int i;
 3553 
 3554         /*
 3555          * allocate the page directory page
 3556          */
 3557         pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 3558             VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
 3559 
 3560         pml4phys = VM_PAGE_TO_PHYS(pml4pg);
 3561         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
 3562         CPU_FOREACH(i) {
 3563                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
 3564                 pmap->pm_pcids[i].pm_gen = 0;
 3565         }
 3566         pmap->pm_cr3 = PMAP_NO_CR3;     /* initialize to an invalid value */
 3567         pmap->pm_ucr3 = PMAP_NO_CR3;
 3568         pmap->pm_pml4u = NULL;
 3569 
 3570         pmap->pm_type = pm_type;
 3571         if ((pml4pg->flags & PG_ZERO) == 0)
 3572                 pagezero(pmap->pm_pml4);
 3573 
 3574         /*
 3575          * Do not install the host kernel mappings in the nested page
 3576          * tables. These mappings are meaningless in the guest physical
 3577          * address space.
 3578          * Install minimal kernel mappings in PTI case.
 3579          */
 3580         if (pm_type == PT_X86) {
 3581                 pmap->pm_cr3 = pml4phys;
 3582                 pmap_pinit_pml4(pml4pg);
 3583                 if ((curproc->p_amd64_md_flags & P_MD_KPTI) != 0) {
 3584                         pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
 3585                             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
 3586                         pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
 3587                             VM_PAGE_TO_PHYS(pml4pgu));
 3588                         pmap_pinit_pml4_pti(pml4pgu);
 3589                         pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
 3590                 }
 3591                 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
 3592                         rangeset_init(&pmap->pm_pkru, pkru_dup_range,
 3593                             pkru_free_range, pmap, M_NOWAIT);
 3594                 }
 3595         }
 3596 
 3597         pmap->pm_root.rt_root = 0;
 3598         CPU_ZERO(&pmap->pm_active);
 3599         TAILQ_INIT(&pmap->pm_pvchunk);
 3600         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 3601         pmap->pm_flags = flags;
 3602         pmap->pm_eptgen = 0;
 3603 
 3604         return (1);
 3605 }
 3606 
 3607 int
 3608 pmap_pinit(pmap_t pmap)
 3609 {
 3610 
 3611         return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
 3612 }
 3613 
 3614 /*
 3615  * This routine is called if the desired page table page does not exist.
 3616  *
 3617  * If page table page allocation fails, this routine may sleep before
 3618  * returning NULL.  It sleeps only if a lock pointer was given.
 3619  *
 3620  * Note: If a page allocation fails at page table level two or three,
 3621  * one or two pages may be held during the wait, only to be released
 3622  * afterwards.  This conservative approach is easily argued to avoid
 3623  * race conditions.
 3624  *
 3625  * The ptepindexes, i.e. page indices, of the page table pages encountered
 3626  * while translating virtual address va are defined as follows:
 3627  * - for the page table page (last level),
 3628  *      ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
 3629  *   in other words, it is just the index of the PDE that maps the page
 3630  *   table page.
 3631  * - for the page directory page,
 3632  *      ptepindex = NUPDE (number of userland PD entries) +
 3633  *          (pmap_pde_index(va) >> NPDEPGSHIFT)
 3634  *   i.e. index of PDPE is put after the last index of PDE,
 3635  * - for the page directory pointer page,
 3636  *      ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
 3637  *          NPML4EPGSHIFT),
 3638  *   i.e. index of pml4e is put after the last index of PDPE.
 3639  *
 3640  * Define an order on the paging entries, where all entries of the
 3641  * same height are put together, then heights are put from deepest to
 3642  * root.  Then ptexpindex is the sequential number of the
 3643  * corresponding paging entry in this order.
 3644  *
 3645  * The root page at PML4 does not participate in this indexing scheme, since
 3646  * it is statically allocated by pmap_pinit() and not by _pmap_allocpte().
 3647  */
 3648 static vm_page_t
 3649 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
 3650 {
 3651         vm_page_t m, pdppg, pdpg;
 3652         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
 3653 
 3654         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 3655 
 3656         PG_A = pmap_accessed_bit(pmap);
 3657         PG_M = pmap_modified_bit(pmap);
 3658         PG_V = pmap_valid_bit(pmap);
 3659         PG_RW = pmap_rw_bit(pmap);
 3660 
 3661         /*
 3662          * Allocate a page table page.
 3663          */
 3664         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
 3665             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
 3666                 if (lockp != NULL) {
 3667                         RELEASE_PV_LIST_LOCK(lockp);
 3668                         PMAP_UNLOCK(pmap);
 3669                         PMAP_ASSERT_NOT_IN_DI();
 3670                         vm_wait(NULL);
 3671                         PMAP_LOCK(pmap);
 3672                 }
 3673 
 3674                 /*
 3675                  * Indicate the need to retry.  While waiting, the page table
 3676                  * page may have been allocated.
 3677                  */
 3678                 return (NULL);
 3679         }
 3680         if ((m->flags & PG_ZERO) == 0)
 3681                 pmap_zero_page(m);
 3682 
 3683         /*
 3684          * Map the pagetable page into the process address space, if
 3685          * it isn't already there.
 3686          */
 3687 
 3688         if (ptepindex >= (NUPDE + NUPDPE)) {
 3689                 pml4_entry_t *pml4, *pml4u;
 3690                 vm_pindex_t pml4index;
 3691 
 3692                 /* Wire up a new PDPE page */
 3693                 pml4index = ptepindex - (NUPDE + NUPDPE);
 3694                 pml4 = &pmap->pm_pml4[pml4index];
 3695                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3696                 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
 3697                         /*
 3698                          * PTI: Make all user-space mappings in the
 3699                          * kernel-mode page table no-execute so that
 3700                          * we detect any programming errors that leave
 3701                          * the kernel-mode page table active on return
 3702                          * to user space.
 3703                          */
 3704                         if (pmap->pm_ucr3 != PMAP_NO_CR3)
 3705                                 *pml4 |= pg_nx;
 3706 
 3707                         pml4u = &pmap->pm_pml4u[pml4index];
 3708                         *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
 3709                             PG_A | PG_M;
 3710                 }
 3711 
 3712         } else if (ptepindex >= NUPDE) {
 3713                 vm_pindex_t pml4index;
 3714                 vm_pindex_t pdpindex;
 3715                 pml4_entry_t *pml4;
 3716                 pdp_entry_t *pdp;
 3717 
 3718                 /* Wire up a new PDE page */
 3719                 pdpindex = ptepindex - NUPDE;
 3720                 pml4index = pdpindex >> NPML4EPGSHIFT;
 3721 
 3722                 pml4 = &pmap->pm_pml4[pml4index];
 3723                 if ((*pml4 & PG_V) == 0) {
 3724                         /* Have to allocate a new pdp, recurse */
 3725                         if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
 3726                             lockp) == NULL) {
 3727                                 vm_page_unwire_noq(m);
 3728                                 vm_page_free_zero(m);
 3729                                 return (NULL);
 3730                         }
 3731                 } else {
 3732                         /* Add reference to pdp page */
 3733                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
 3734                         pdppg->wire_count++;
 3735                 }
 3736                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3737 
 3738                 /* Now find the pdp page */
 3739                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3740                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3741 
 3742         } else {
 3743                 vm_pindex_t pml4index;
 3744                 vm_pindex_t pdpindex;
 3745                 pml4_entry_t *pml4;
 3746                 pdp_entry_t *pdp;
 3747                 pd_entry_t *pd;
 3748 
 3749                 /* Wire up a new PTE page */
 3750                 pdpindex = ptepindex >> NPDPEPGSHIFT;
 3751                 pml4index = pdpindex >> NPML4EPGSHIFT;
 3752 
 3753                 /* First, find the pdp and check that its valid. */
 3754                 pml4 = &pmap->pm_pml4[pml4index];
 3755                 if ((*pml4 & PG_V) == 0) {
 3756                         /* Have to allocate a new pd, recurse */
 3757                         if (_pmap_allocpte(pmap, NUPDE + pdpindex,
 3758                             lockp) == NULL) {
 3759                                 vm_page_unwire_noq(m);
 3760                                 vm_page_free_zero(m);
 3761                                 return (NULL);
 3762                         }
 3763                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3764                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3765                 } else {
 3766                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
 3767                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
 3768                         if ((*pdp & PG_V) == 0) {
 3769                                 /* Have to allocate a new pd, recurse */
 3770                                 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
 3771                                     lockp) == NULL) {
 3772                                         vm_page_unwire_noq(m);
 3773                                         vm_page_free_zero(m);
 3774                                         return (NULL);
 3775                                 }
 3776                         } else {
 3777                                 /* Add reference to the pd page */
 3778                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
 3779                                 pdpg->wire_count++;
 3780                         }
 3781                 }
 3782                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
 3783 
 3784                 /* Now we know where the page directory page is */
 3785                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
 3786                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
 3787         }
 3788 
 3789         pmap_resident_count_inc(pmap, 1);
 3790 
 3791         return (m);
 3792 }
 3793 
 3794 static vm_page_t
 3795 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
 3796 {
 3797         vm_pindex_t pdpindex, ptepindex;
 3798         pdp_entry_t *pdpe, PG_V;
 3799         vm_page_t pdpg;
 3800 
 3801         PG_V = pmap_valid_bit(pmap);
 3802 
 3803 retry:
 3804         pdpe = pmap_pdpe(pmap, va);
 3805         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
 3806                 /* Add a reference to the pd page. */
 3807                 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
 3808                 pdpg->wire_count++;
 3809         } else {
 3810                 /* Allocate a pd page. */
 3811                 ptepindex = pmap_pde_pindex(va);
 3812                 pdpindex = ptepindex >> NPDPEPGSHIFT;
 3813                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
 3814                 if (pdpg == NULL && lockp != NULL)
 3815                         goto retry;
 3816         }
 3817         return (pdpg);
 3818 }
 3819 
 3820 static vm_page_t
 3821 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
 3822 {
 3823         vm_pindex_t ptepindex;
 3824         pd_entry_t *pd, PG_V;
 3825         vm_page_t m;
 3826 
 3827         PG_V = pmap_valid_bit(pmap);
 3828 
 3829         /*
 3830          * Calculate pagetable page index
 3831          */
 3832         ptepindex = pmap_pde_pindex(va);
 3833 retry:
 3834         /*
 3835          * Get the page directory entry
 3836          */
 3837         pd = pmap_pde(pmap, va);
 3838 
 3839         /*
 3840          * This supports switching from a 2MB page to a
 3841          * normal 4K page.
 3842          */
 3843         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
 3844                 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
 3845                         /*
 3846                          * Invalidation of the 2MB page mapping may have caused
 3847                          * the deallocation of the underlying PD page.
 3848                          */
 3849                         pd = NULL;
 3850                 }
 3851         }
 3852 
 3853         /*
 3854          * If the page table page is mapped, we just increment the
 3855          * hold count, and activate it.
 3856          */
 3857         if (pd != NULL && (*pd & PG_V) != 0) {
 3858                 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
 3859                 m->wire_count++;
 3860         } else {
 3861                 /*
 3862                  * Here if the pte page isn't mapped, or if it has been
 3863                  * deallocated.
 3864                  */
 3865                 m = _pmap_allocpte(pmap, ptepindex, lockp);
 3866                 if (m == NULL && lockp != NULL)
 3867                         goto retry;
 3868         }
 3869         return (m);
 3870 }
 3871 
 3872 
 3873 /***************************************************
 3874  * Pmap allocation/deallocation routines.
 3875  ***************************************************/
 3876 
 3877 /*
 3878  * Release any resources held by the given physical map.
 3879  * Called when a pmap initialized by pmap_pinit is being released.
 3880  * Should only be called if the map contains no valid mappings.
 3881  */
 3882 void
 3883 pmap_release(pmap_t pmap)
 3884 {
 3885         vm_page_t m;
 3886         int i;
 3887 
 3888         KASSERT(pmap->pm_stats.resident_count == 0,
 3889             ("pmap_release: pmap resident count %ld != 0",
 3890             pmap->pm_stats.resident_count));
 3891         KASSERT(vm_radix_is_empty(&pmap->pm_root),
 3892             ("pmap_release: pmap has reserved page table page(s)"));
 3893         KASSERT(CPU_EMPTY(&pmap->pm_active),
 3894             ("releasing active pmap %p", pmap));
 3895 
 3896         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
 3897 
 3898         for (i = 0; i < NKPML4E; i++)   /* KVA */
 3899                 pmap->pm_pml4[KPML4BASE + i] = 0;
 3900         for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
 3901                 pmap->pm_pml4[DMPML4I + i] = 0;
 3902         pmap->pm_pml4[PML4PML4I] = 0;   /* Recursive Mapping */
 3903         for (i = 0; i < lm_ents; i++)   /* Large Map */
 3904                 pmap->pm_pml4[LMSPML4I + i] = 0;
 3905 
 3906         vm_page_unwire_noq(m);
 3907         vm_page_free_zero(m);
 3908 
 3909         if (pmap->pm_pml4u != NULL) {
 3910                 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
 3911                 vm_page_unwire_noq(m);
 3912                 vm_page_free(m);
 3913         }
 3914         if (pmap->pm_type == PT_X86 &&
 3915             (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
 3916                 rangeset_fini(&pmap->pm_pkru);
 3917 }
 3918 
 3919 static int
 3920 kvm_size(SYSCTL_HANDLER_ARGS)
 3921 {
 3922         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
 3923 
 3924         return sysctl_handle_long(oidp, &ksize, 0, req);
 3925 }
 3926 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
 3927     0, 0, kvm_size, "LU", "Size of KVM");
 3928 
 3929 static int
 3930 kvm_free(SYSCTL_HANDLER_ARGS)
 3931 {
 3932         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
 3933 
 3934         return sysctl_handle_long(oidp, &kfree, 0, req);
 3935 }
 3936 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
 3937     0, 0, kvm_free, "LU", "Amount of KVM free");
 3938 
 3939 /*
 3940  * grow the number of kernel page table entries, if needed
 3941  */
 3942 void
 3943 pmap_growkernel(vm_offset_t addr)
 3944 {
 3945         vm_paddr_t paddr;
 3946         vm_page_t nkpg;
 3947         pd_entry_t *pde, newpdir;
 3948         pdp_entry_t *pdpe;
 3949 
 3950         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
 3951 
 3952         /*
 3953          * Return if "addr" is within the range of kernel page table pages
 3954          * that were preallocated during pmap bootstrap.  Moreover, leave
 3955          * "kernel_vm_end" and the kernel page table as they were.
 3956          *
 3957          * The correctness of this action is based on the following
 3958          * argument: vm_map_insert() allocates contiguous ranges of the
 3959          * kernel virtual address space.  It calls this function if a range
 3960          * ends after "kernel_vm_end".  If the kernel is mapped between
 3961          * "kernel_vm_end" and "addr", then the range cannot begin at
 3962          * "kernel_vm_end".  In fact, its beginning address cannot be less
 3963          * than the kernel.  Thus, there is no immediate need to allocate
 3964          * any new kernel page table pages between "kernel_vm_end" and
 3965          * "KERNBASE".
 3966          */
 3967         if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
 3968                 return;
 3969 
 3970         addr = roundup2(addr, NBPDR);
 3971         if (addr - 1 >= vm_map_max(kernel_map))
 3972                 addr = vm_map_max(kernel_map);
 3973         while (kernel_vm_end < addr) {
 3974                 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
 3975                 if ((*pdpe & X86_PG_V) == 0) {
 3976                         /* We need a new PDP entry */
 3977                         nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
 3978                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
 3979                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
 3980                         if (nkpg == NULL)
 3981                                 panic("pmap_growkernel: no memory to grow kernel");
 3982                         if ((nkpg->flags & PG_ZERO) == 0)
 3983                                 pmap_zero_page(nkpg);
 3984                         paddr = VM_PAGE_TO_PHYS(nkpg);
 3985                         *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
 3986                             X86_PG_A | X86_PG_M);
 3987                         continue; /* try again */
 3988                 }
 3989                 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
 3990                 if ((*pde & X86_PG_V) != 0) {
 3991                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 3992                         if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
 3993                                 kernel_vm_end = vm_map_max(kernel_map);
 3994                                 break;                       
 3995                         }
 3996                         continue;
 3997                 }
 3998 
 3999                 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
 4000                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
 4001                     VM_ALLOC_ZERO);
 4002                 if (nkpg == NULL)
 4003                         panic("pmap_growkernel: no memory to grow kernel");
 4004                 if ((nkpg->flags & PG_ZERO) == 0)
 4005                         pmap_zero_page(nkpg);
 4006                 paddr = VM_PAGE_TO_PHYS(nkpg);
 4007                 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
 4008                 pde_store(pde, newpdir);
 4009 
 4010                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 4011                 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
 4012                         kernel_vm_end = vm_map_max(kernel_map);
 4013                         break;                       
 4014                 }
 4015         }
 4016 }
 4017 
 4018 
 4019 /***************************************************
 4020  * page management routines.
 4021  ***************************************************/
 4022 
 4023 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
 4024 CTASSERT(_NPCM == 3);
 4025 CTASSERT(_NPCPV == 168);
 4026 
 4027 static __inline struct pv_chunk *
 4028 pv_to_chunk(pv_entry_t pv)
 4029 {
 4030 
 4031         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
 4032 }
 4033 
 4034 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
 4035 
 4036 #define PC_FREE0        0xfffffffffffffffful
 4037 #define PC_FREE1        0xfffffffffffffffful
 4038 #define PC_FREE2        0x000000fffffffffful
 4039 
 4040 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
 4041 
 4042 #ifdef PV_STATS
 4043 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
 4044 
 4045 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
 4046         "Current number of pv entry chunks");
 4047 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
 4048         "Current number of pv entry chunks allocated");
 4049 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
 4050         "Current number of pv entry chunks frees");
 4051 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
 4052         "Number of times tried to get a chunk page but failed.");
 4053 
 4054 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
 4055 static int pv_entry_spare;
 4056 
 4057 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
 4058         "Current number of pv entry frees");
 4059 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
 4060         "Current number of pv entry allocs");
 4061 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
 4062         "Current number of pv entries");
 4063 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
 4064         "Current number of spare pv entries");
 4065 #endif
 4066 
 4067 static void
 4068 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
 4069 {
 4070 
 4071         if (pmap == NULL)
 4072                 return;
 4073         pmap_invalidate_all(pmap);
 4074         if (pmap != locked_pmap)
 4075                 PMAP_UNLOCK(pmap);
 4076         if (start_di)
 4077                 pmap_delayed_invl_finish();
 4078 }
 4079 
 4080 /*
 4081  * We are in a serious low memory condition.  Resort to
 4082  * drastic measures to free some pages so we can allocate
 4083  * another pv entry chunk.
 4084  *
 4085  * Returns NULL if PV entries were reclaimed from the specified pmap.
 4086  *
 4087  * We do not, however, unmap 2mpages because subsequent accesses will
 4088  * allocate per-page pv entries until repromotion occurs, thereby
 4089  * exacerbating the shortage of free pv entries.
 4090  */
 4091 static vm_page_t
 4092 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
 4093 {
 4094         struct pv_chunk *pc, *pc_marker, *pc_marker_end;
 4095         struct pv_chunk_header pc_marker_b, pc_marker_end_b;
 4096         struct md_page *pvh;
 4097         pd_entry_t *pde;
 4098         pmap_t next_pmap, pmap;
 4099         pt_entry_t *pte, tpte;
 4100         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
 4101         pv_entry_t pv;
 4102         vm_offset_t va;
 4103         vm_page_t m, m_pc;
 4104         struct spglist free;
 4105         uint64_t inuse;
 4106         int bit, field, freed;
 4107         bool start_di;
 4108         static int active_reclaims = 0;
 4109 
 4110         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
 4111         KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
 4112         pmap = NULL;
 4113         m_pc = NULL;
 4114         PG_G = PG_A = PG_M = PG_RW = 0;
 4115         SLIST_INIT(&free);
 4116         bzero(&pc_marker_b, sizeof(pc_marker_b));
 4117         bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
 4118         pc_marker = (struct pv_chunk *)&pc_marker_b;
 4119         pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
 4120 
 4121         /*
 4122          * A delayed invalidation block should already be active if
 4123          * pmap_advise() or pmap_remove() called this function by way
 4124          * of pmap_demote_pde_locked().
 4125          */
 4126         start_di = pmap_not_in_di();
 4127 
 4128         mtx_lock(&pv_chunks_mutex);
 4129         active_reclaims++;
 4130         TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
 4131         TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
 4132         while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
 4133             SLIST_EMPTY(&free)) {
 4134                 next_pmap = pc->pc_pmap;
 4135                 if (next_pmap == NULL) {
 4136                         /*
 4137                          * The next chunk is a marker.  However, it is
 4138                          * not our marker, so active_reclaims must be
 4139                          * > 1.  Consequently, the next_chunk code
 4140                          * will not rotate the pv_chunks list.
 4141                          */
 4142                         goto next_chunk;
 4143                 }
 4144                 mtx_unlock(&pv_chunks_mutex);
 4145 
 4146                 /*
 4147                  * A pv_chunk can only be removed from the pc_lru list
 4148                  * when both pc_chunks_mutex is owned and the
 4149                  * corresponding pmap is locked.
 4150                  */
 4151                 if (pmap != next_pmap) {
 4152                         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
 4153                             start_di);
 4154                         pmap = next_pmap;
 4155                         /* Avoid deadlock and lock recursion. */
 4156                         if (pmap > locked_pmap) {
 4157                                 RELEASE_PV_LIST_LOCK(lockp);
 4158                                 PMAP_LOCK(pmap);
 4159                                 if (start_di)
 4160                                         pmap_delayed_invl_start();
 4161                                 mtx_lock(&pv_chunks_mutex);
 4162                                 continue;
 4163                         } else if (pmap != locked_pmap) {
 4164                                 if (PMAP_TRYLOCK(pmap)) {
 4165                                         if (start_di)
 4166                                                 pmap_delayed_invl_start();
 4167                                         mtx_lock(&pv_chunks_mutex);
 4168                                         continue;
 4169                                 } else {
 4170                                         pmap = NULL; /* pmap is not locked */
 4171                                         mtx_lock(&pv_chunks_mutex);
 4172                                         pc = TAILQ_NEXT(pc_marker, pc_lru);
 4173                                         if (pc == NULL ||
 4174                                             pc->pc_pmap != next_pmap)
 4175                                                 continue;
 4176                                         goto next_chunk;
 4177                                 }
 4178                         } else if (start_di)
 4179                                 pmap_delayed_invl_start();
 4180                         PG_G = pmap_global_bit(pmap);
 4181                         PG_A = pmap_accessed_bit(pmap);
 4182                         PG_M = pmap_modified_bit(pmap);
 4183                         PG_RW = pmap_rw_bit(pmap);
 4184                 }
 4185 
 4186                 /*
 4187                  * Destroy every non-wired, 4 KB page mapping in the chunk.
 4188                  */
 4189                 freed = 0;
 4190                 for (field = 0; field < _NPCM; field++) {
 4191                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
 4192                             inuse != 0; inuse &= ~(1UL << bit)) {
 4193                                 bit = bsfq(inuse);
 4194                                 pv = &pc->pc_pventry[field * 64 + bit];
 4195                                 va = pv->pv_va;
 4196                                 pde = pmap_pde(pmap, va);
 4197                                 if ((*pde & PG_PS) != 0)
 4198                                         continue;
 4199                                 pte = pmap_pde_to_pte(pde, va);
 4200                                 if ((*pte & PG_W) != 0)
 4201                                         continue;
 4202                                 tpte = pte_load_clear(pte);
 4203                                 if ((tpte & PG_G) != 0)
 4204                                         pmap_invalidate_page(pmap, va);
 4205                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
 4206                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 4207                                         vm_page_dirty(m);
 4208                                 if ((tpte & PG_A) != 0)
 4209                                         vm_page_aflag_set(m, PGA_REFERENCED);
 4210                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 4211                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 4212                                 m->md.pv_gen++;
 4213                                 if (TAILQ_EMPTY(&m->md.pv_list) &&
 4214                                     (m->flags & PG_FICTITIOUS) == 0) {
 4215                                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 4216                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
 4217                                                 vm_page_aflag_clear(m,
 4218                                                     PGA_WRITEABLE);
 4219                                         }
 4220                                 }
 4221                                 pmap_delayed_invl_page(m);
 4222                                 pc->pc_map[field] |= 1UL << bit;
 4223                                 pmap_unuse_pt(pmap, va, *pde, &free);
 4224                                 freed++;
 4225                         }
 4226                 }
 4227                 if (freed == 0) {
 4228                         mtx_lock(&pv_chunks_mutex);
 4229                         goto next_chunk;
 4230                 }
 4231                 /* Every freed mapping is for a 4 KB page. */
 4232                 pmap_resident_count_dec(pmap, freed);
 4233                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
 4234                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
 4235                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
 4236                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4237                 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
 4238                     pc->pc_map[2] == PC_FREE2) {
 4239                         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
 4240                         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
 4241                         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
 4242                         /* Entire chunk is free; return it. */
 4243                         m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
 4244                         dump_drop_page(m_pc->phys_addr);
 4245                         mtx_lock(&pv_chunks_mutex);
 4246                         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 4247                         break;
 4248                 }
 4249                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 4250                 mtx_lock(&pv_chunks_mutex);
 4251                 /* One freed pv entry in locked_pmap is sufficient. */
 4252                 if (pmap == locked_pmap)
 4253                         break;
 4254 next_chunk:
 4255                 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
 4256                 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
 4257                 if (active_reclaims == 1 && pmap != NULL) {
 4258                         /*
 4259                          * Rotate the pv chunks list so that we do not
 4260                          * scan the same pv chunks that could not be
 4261                          * freed (because they contained a wired
 4262                          * and/or superpage mapping) on every
 4263                          * invocation of reclaim_pv_chunk().
 4264                          */
 4265                         while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
 4266                                 MPASS(pc->pc_pmap != NULL);
 4267                                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 4268                                 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
 4269                         }
 4270                 }
 4271         }
 4272         TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
 4273         TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
 4274         active_reclaims--;
 4275         mtx_unlock(&pv_chunks_mutex);
 4276         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
 4277         if (m_pc == NULL && !SLIST_EMPTY(&free)) {
 4278                 m_pc = SLIST_FIRST(&free);
 4279                 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
 4280                 /* Recycle a freed page table page. */
 4281                 m_pc->wire_count = 1;
 4282         }
 4283         vm_page_free_pages_toq(&free, true);
 4284         return (m_pc);
 4285 }
 4286 
 4287 /*
 4288  * free the pv_entry back to the free list
 4289  */
 4290 static void
 4291 free_pv_entry(pmap_t pmap, pv_entry_t pv)
 4292 {
 4293         struct pv_chunk *pc;
 4294         int idx, field, bit;
 4295 
 4296         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4297         PV_STAT(atomic_add_long(&pv_entry_frees, 1));
 4298         PV_STAT(atomic_add_int(&pv_entry_spare, 1));
 4299         PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
 4300         pc = pv_to_chunk(pv);
 4301         idx = pv - &pc->pc_pventry[0];
 4302         field = idx / 64;
 4303         bit = idx % 64;
 4304         pc->pc_map[field] |= 1ul << bit;
 4305         if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
 4306             pc->pc_map[2] != PC_FREE2) {
 4307                 /* 98% of the time, pc is already at the head of the list. */
 4308                 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
 4309                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4310                         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 4311                 }
 4312                 return;
 4313         }
 4314         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4315         free_pv_chunk(pc);
 4316 }
 4317 
 4318 static void
 4319 free_pv_chunk_dequeued(struct pv_chunk *pc)
 4320 {
 4321         vm_page_t m;
 4322 
 4323         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
 4324         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
 4325         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
 4326         /* entire chunk is free, return it */
 4327         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
 4328         dump_drop_page(m->phys_addr);
 4329         vm_page_unwire_noq(m);
 4330         vm_page_free(m);
 4331 }
 4332 
 4333 static void
 4334 free_pv_chunk(struct pv_chunk *pc)
 4335 {
 4336 
 4337         mtx_lock(&pv_chunks_mutex);
 4338         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 4339         mtx_unlock(&pv_chunks_mutex);
 4340         free_pv_chunk_dequeued(pc);
 4341 }
 4342 
 4343 static void
 4344 free_pv_chunk_batch(struct pv_chunklist *batch)
 4345 {
 4346         struct pv_chunk *pc, *npc;
 4347 
 4348         if (TAILQ_EMPTY(batch))
 4349                 return;
 4350 
 4351         mtx_lock(&pv_chunks_mutex);
 4352         TAILQ_FOREACH(pc, batch, pc_list) {
 4353                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 4354         }
 4355         mtx_unlock(&pv_chunks_mutex);
 4356 
 4357         TAILQ_FOREACH_SAFE(pc, batch, pc_list, npc) {
 4358                 free_pv_chunk_dequeued(pc);
 4359         }
 4360 }
 4361 
 4362 /*
 4363  * Returns a new PV entry, allocating a new PV chunk from the system when
 4364  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
 4365  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
 4366  * returned.
 4367  *
 4368  * The given PV list lock may be released.
 4369  */
 4370 static pv_entry_t
 4371 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
 4372 {
 4373         int bit, field;
 4374         pv_entry_t pv;
 4375         struct pv_chunk *pc;
 4376         vm_page_t m;
 4377 
 4378         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4379         PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
 4380 retry:
 4381         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 4382         if (pc != NULL) {
 4383                 for (field = 0; field < _NPCM; field++) {
 4384                         if (pc->pc_map[field]) {
 4385                                 bit = bsfq(pc->pc_map[field]);
 4386                                 break;
 4387                         }
 4388                 }
 4389                 if (field < _NPCM) {
 4390                         pv = &pc->pc_pventry[field * 64 + bit];
 4391                         pc->pc_map[field] &= ~(1ul << bit);
 4392                         /* If this was the last item, move it to tail */
 4393                         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
 4394                             pc->pc_map[2] == 0) {
 4395                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4396                                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
 4397                                     pc_list);
 4398                         }
 4399                         PV_STAT(atomic_add_long(&pv_entry_count, 1));
 4400                         PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
 4401                         return (pv);
 4402                 }
 4403         }
 4404         /* No free items, allocate another chunk */
 4405         m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 4406             VM_ALLOC_WIRED);
 4407         if (m == NULL) {
 4408                 if (lockp == NULL) {
 4409                         PV_STAT(pc_chunk_tryfail++);
 4410                         return (NULL);
 4411                 }
 4412                 m = reclaim_pv_chunk(pmap, lockp);
 4413                 if (m == NULL)
 4414                         goto retry;
 4415         }
 4416         PV_STAT(atomic_add_int(&pc_chunk_count, 1));
 4417         PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
 4418         dump_add_page(m->phys_addr);
 4419         pc = (void *)PHYS_TO_DMAP(m->phys_addr);
 4420         pc->pc_pmap = pmap;
 4421         pc->pc_map[0] = PC_FREE0 & ~1ul;        /* preallocated bit 0 */
 4422         pc->pc_map[1] = PC_FREE1;
 4423         pc->pc_map[2] = PC_FREE2;
 4424         mtx_lock(&pv_chunks_mutex);
 4425         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
 4426         mtx_unlock(&pv_chunks_mutex);
 4427         pv = &pc->pc_pventry[0];
 4428         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 4429         PV_STAT(atomic_add_long(&pv_entry_count, 1));
 4430         PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
 4431         return (pv);
 4432 }
 4433 
 4434 /*
 4435  * Returns the number of one bits within the given PV chunk map.
 4436  *
 4437  * The erratas for Intel processors state that "POPCNT Instruction May
 4438  * Take Longer to Execute Than Expected".  It is believed that the
 4439  * issue is the spurious dependency on the destination register.
 4440  * Provide a hint to the register rename logic that the destination
 4441  * value is overwritten, by clearing it, as suggested in the
 4442  * optimization manual.  It should be cheap for unaffected processors
 4443  * as well.
 4444  *
 4445  * Reference numbers for erratas are
 4446  * 4th Gen Core: HSD146
 4447  * 5th Gen Core: BDM85
 4448  * 6th Gen Core: SKL029
 4449  */
 4450 static int
 4451 popcnt_pc_map_pq(uint64_t *map)
 4452 {
 4453         u_long result, tmp;
 4454 
 4455         __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
 4456             "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
 4457             "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
 4458             : "=&r" (result), "=&r" (tmp)
 4459             : "m" (map[0]), "m" (map[1]), "m" (map[2]));
 4460         return (result);
 4461 }
 4462 
 4463 /*
 4464  * Ensure that the number of spare PV entries in the specified pmap meets or
 4465  * exceeds the given count, "needed".
 4466  *
 4467  * The given PV list lock may be released.
 4468  */
 4469 static void
 4470 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
 4471 {
 4472         struct pch new_tail;
 4473         struct pv_chunk *pc;
 4474         vm_page_t m;
 4475         int avail, free;
 4476         bool reclaimed;
 4477 
 4478         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4479         KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
 4480 
 4481         /*
 4482          * Newly allocated PV chunks must be stored in a private list until
 4483          * the required number of PV chunks have been allocated.  Otherwise,
 4484          * reclaim_pv_chunk() could recycle one of these chunks.  In
 4485          * contrast, these chunks must be added to the pmap upon allocation.
 4486          */
 4487         TAILQ_INIT(&new_tail);
 4488 retry:
 4489         avail = 0;
 4490         TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
 4491 #ifndef __POPCNT__
 4492                 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
 4493                         bit_count((bitstr_t *)pc->pc_map, 0,
 4494                             sizeof(pc->pc_map) * NBBY, &free);
 4495                 else
 4496 #endif
 4497                 free = popcnt_pc_map_pq(pc->pc_map);
 4498                 if (free == 0)
 4499                         break;
 4500                 avail += free;
 4501                 if (avail >= needed)
 4502                         break;
 4503         }
 4504         for (reclaimed = false; avail < needed; avail += _NPCPV) {
 4505                 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 4506                     VM_ALLOC_WIRED);
 4507                 if (m == NULL) {
 4508                         m = reclaim_pv_chunk(pmap, lockp);
 4509                         if (m == NULL)
 4510                                 goto retry;
 4511                         reclaimed = true;
 4512                 }
 4513                 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
 4514                 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
 4515                 dump_add_page(m->phys_addr);
 4516                 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
 4517                 pc->pc_pmap = pmap;
 4518                 pc->pc_map[0] = PC_FREE0;
 4519                 pc->pc_map[1] = PC_FREE1;
 4520                 pc->pc_map[2] = PC_FREE2;
 4521                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 4522                 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
 4523                 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
 4524 
 4525                 /*
 4526                  * The reclaim might have freed a chunk from the current pmap.
 4527                  * If that chunk contained available entries, we need to
 4528                  * re-count the number of available entries.
 4529                  */
 4530                 if (reclaimed)
 4531                         goto retry;
 4532         }
 4533         if (!TAILQ_EMPTY(&new_tail)) {
 4534                 mtx_lock(&pv_chunks_mutex);
 4535                 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
 4536                 mtx_unlock(&pv_chunks_mutex);
 4537         }
 4538 }
 4539 
 4540 /*
 4541  * First find and then remove the pv entry for the specified pmap and virtual
 4542  * address from the specified pv list.  Returns the pv entry if found and NULL
 4543  * otherwise.  This operation can be performed on pv lists for either 4KB or
 4544  * 2MB page mappings.
 4545  */
 4546 static __inline pv_entry_t
 4547 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 4548 {
 4549         pv_entry_t pv;
 4550 
 4551         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
 4552                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
 4553                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
 4554                         pvh->pv_gen++;
 4555                         break;
 4556                 }
 4557         }
 4558         return (pv);
 4559 }
 4560 
 4561 /*
 4562  * After demotion from a 2MB page mapping to 512 4KB page mappings,
 4563  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
 4564  * entries for each of the 4KB page mappings.
 4565  */
 4566 static void
 4567 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 4568     struct rwlock **lockp)
 4569 {
 4570         struct md_page *pvh;
 4571         struct pv_chunk *pc;
 4572         pv_entry_t pv;
 4573         vm_offset_t va_last;
 4574         vm_page_t m;
 4575         int bit, field;
 4576 
 4577         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4578         KASSERT((pa & PDRMASK) == 0,
 4579             ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
 4580         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 4581 
 4582         /*
 4583          * Transfer the 2mpage's pv entry for this mapping to the first
 4584          * page's pv list.  Once this transfer begins, the pv list lock
 4585          * must not be released until the last pv entry is reinstantiated.
 4586          */
 4587         pvh = pa_to_pvh(pa);
 4588         va = trunc_2mpage(va);
 4589         pv = pmap_pvh_remove(pvh, pmap, va);
 4590         KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
 4591         m = PHYS_TO_VM_PAGE(pa);
 4592         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 4593         m->md.pv_gen++;
 4594         /* Instantiate the remaining NPTEPG - 1 pv entries. */
 4595         PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
 4596         va_last = va + NBPDR - PAGE_SIZE;
 4597         for (;;) {
 4598                 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 4599                 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
 4600                     pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
 4601                 for (field = 0; field < _NPCM; field++) {
 4602                         while (pc->pc_map[field]) {
 4603                                 bit = bsfq(pc->pc_map[field]);
 4604                                 pc->pc_map[field] &= ~(1ul << bit);
 4605                                 pv = &pc->pc_pventry[field * 64 + bit];
 4606                                 va += PAGE_SIZE;
 4607                                 pv->pv_va = va;
 4608                                 m++;
 4609                                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 4610                             ("pmap_pv_demote_pde: page %p is not managed", m));
 4611                                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 4612                                 m->md.pv_gen++;
 4613                                 if (va == va_last)
 4614                                         goto out;
 4615                         }
 4616                 }
 4617                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4618                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 4619         }
 4620 out:
 4621         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
 4622                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 4623                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 4624         }
 4625         PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
 4626         PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
 4627 }
 4628 
 4629 #if VM_NRESERVLEVEL > 0
 4630 /*
 4631  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
 4632  * replace the many pv entries for the 4KB page mappings by a single pv entry
 4633  * for the 2MB page mapping.
 4634  */
 4635 static void
 4636 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
 4637     struct rwlock **lockp)
 4638 {
 4639         struct md_page *pvh;
 4640         pv_entry_t pv;
 4641         vm_offset_t va_last;
 4642         vm_page_t m;
 4643 
 4644         KASSERT((pa & PDRMASK) == 0,
 4645             ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
 4646         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 4647 
 4648         /*
 4649          * Transfer the first page's pv entry for this mapping to the 2mpage's
 4650          * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
 4651          * a transfer avoids the possibility that get_pv_entry() calls
 4652          * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
 4653          * mappings that is being promoted.
 4654          */
 4655         m = PHYS_TO_VM_PAGE(pa);
 4656         va = trunc_2mpage(va);
 4657         pv = pmap_pvh_remove(&m->md, pmap, va);
 4658         KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
 4659         pvh = pa_to_pvh(pa);
 4660         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
 4661         pvh->pv_gen++;
 4662         /* Free the remaining NPTEPG - 1 pv entries. */
 4663         va_last = va + NBPDR - PAGE_SIZE;
 4664         do {
 4665                 m++;
 4666                 va += PAGE_SIZE;
 4667                 pmap_pvh_free(&m->md, pmap, va);
 4668         } while (va < va_last);
 4669 }
 4670 #endif /* VM_NRESERVLEVEL > 0 */
 4671 
 4672 /*
 4673  * First find and then destroy the pv entry for the specified pmap and virtual
 4674  * address.  This operation can be performed on pv lists for either 4KB or 2MB
 4675  * page mappings.
 4676  */
 4677 static void
 4678 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 4679 {
 4680         pv_entry_t pv;
 4681 
 4682         pv = pmap_pvh_remove(pvh, pmap, va);
 4683         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
 4684         free_pv_entry(pmap, pv);
 4685 }
 4686 
 4687 /*
 4688  * Conditionally create the PV entry for a 4KB page mapping if the required
 4689  * memory can be allocated without resorting to reclamation.
 4690  */
 4691 static boolean_t
 4692 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
 4693     struct rwlock **lockp)
 4694 {
 4695         pv_entry_t pv;
 4696 
 4697         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4698         /* Pass NULL instead of the lock pointer to disable reclamation. */
 4699         if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
 4700                 pv->pv_va = va;
 4701                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 4702                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
 4703                 m->md.pv_gen++;
 4704                 return (TRUE);
 4705         } else
 4706                 return (FALSE);
 4707 }
 4708 
 4709 /*
 4710  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
 4711  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
 4712  * false if the PV entry cannot be allocated without resorting to reclamation.
 4713  */
 4714 static bool
 4715 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
 4716     struct rwlock **lockp)
 4717 {
 4718         struct md_page *pvh;
 4719         pv_entry_t pv;
 4720         vm_paddr_t pa;
 4721 
 4722         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4723         /* Pass NULL instead of the lock pointer to disable reclamation. */
 4724         if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
 4725             NULL : lockp)) == NULL)
 4726                 return (false);
 4727         pv->pv_va = va;
 4728         pa = pde & PG_PS_FRAME;
 4729         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
 4730         pvh = pa_to_pvh(pa);
 4731         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
 4732         pvh->pv_gen++;
 4733         return (true);
 4734 }
 4735 
 4736 /*
 4737  * Fills a page table page with mappings to consecutive physical pages.
 4738  */
 4739 static void
 4740 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
 4741 {
 4742         pt_entry_t *pte;
 4743 
 4744         for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
 4745                 *pte = newpte;
 4746                 newpte += PAGE_SIZE;
 4747         }
 4748 }
 4749 
 4750 /*
 4751  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
 4752  * mapping is invalidated.
 4753  */
 4754 static boolean_t
 4755 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
 4756 {
 4757         struct rwlock *lock;
 4758         boolean_t rv;
 4759 
 4760         lock = NULL;
 4761         rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
 4762         if (lock != NULL)
 4763                 rw_wunlock(lock);
 4764         return (rv);
 4765 }
 4766 
 4767 static void
 4768 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
 4769 {
 4770 #ifdef INVARIANTS
 4771 #ifdef DIAGNOSTIC
 4772         pt_entry_t *xpte, *ypte;
 4773 
 4774         for (xpte = firstpte; xpte < firstpte + NPTEPG;
 4775             xpte++, newpte += PAGE_SIZE) {
 4776                 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
 4777                         printf("pmap_demote_pde: xpte %zd and newpte map "
 4778                             "different pages: found %#lx, expected %#lx\n",
 4779                             xpte - firstpte, *xpte, newpte);
 4780                         printf("page table dump\n");
 4781                         for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
 4782                                 printf("%zd %#lx\n", ypte - firstpte, *ypte);
 4783                         panic("firstpte");
 4784                 }
 4785         }
 4786 #else
 4787         KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
 4788             ("pmap_demote_pde: firstpte and newpte map different physical"
 4789             " addresses"));
 4790 #endif
 4791 #endif
 4792 }
 4793 
 4794 static void
 4795 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
 4796     pd_entry_t oldpde, struct rwlock **lockp)
 4797 {
 4798         struct spglist free;
 4799         vm_offset_t sva;
 4800 
 4801         SLIST_INIT(&free);
 4802         sva = trunc_2mpage(va);
 4803         pmap_remove_pde(pmap, pde, sva, &free, lockp);
 4804         if ((oldpde & pmap_global_bit(pmap)) == 0)
 4805                 pmap_invalidate_pde_page(pmap, sva, oldpde);
 4806         vm_page_free_pages_toq(&free, true);
 4807         CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
 4808             va, pmap);
 4809 }
 4810 
 4811 static boolean_t
 4812 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
 4813     struct rwlock **lockp)
 4814 {
 4815         pd_entry_t newpde, oldpde;
 4816         pt_entry_t *firstpte, newpte;
 4817         pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
 4818         vm_paddr_t mptepa;
 4819         vm_page_t mpte;
 4820         int PG_PTE_CACHE;
 4821         bool in_kernel;
 4822 
 4823         PG_A = pmap_accessed_bit(pmap);
 4824         PG_G = pmap_global_bit(pmap);
 4825         PG_M = pmap_modified_bit(pmap);
 4826         PG_RW = pmap_rw_bit(pmap);
 4827         PG_V = pmap_valid_bit(pmap);
 4828         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
 4829         PG_PKU_MASK = pmap_pku_mask_bit(pmap);
 4830 
 4831         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4832         in_kernel = va >= VM_MAXUSER_ADDRESS;
 4833         oldpde = *pde;
 4834         KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
 4835             ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
 4836 
 4837         /*
 4838          * Invalidate the 2MB page mapping and return "failure" if the
 4839          * mapping was never accessed.
 4840          */
 4841         if ((oldpde & PG_A) == 0) {
 4842                 KASSERT((oldpde & PG_W) == 0,
 4843                     ("pmap_demote_pde: a wired mapping is missing PG_A"));
 4844                 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
 4845                 return (FALSE);
 4846         }
 4847 
 4848         mpte = pmap_remove_pt_page(pmap, va);
 4849         if (mpte == NULL) {
 4850                 KASSERT((oldpde & PG_W) == 0,
 4851                     ("pmap_demote_pde: page table page for a wired mapping"
 4852                     " is missing"));
 4853 
 4854                 /*
 4855                  * If the page table page is missing and the mapping
 4856                  * is for a kernel address, the mapping must belong to
 4857                  * the direct map.  Page table pages are preallocated
 4858                  * for every other part of the kernel address space,
 4859                  * so the direct map region is the only part of the
 4860                  * kernel address space that must be handled here.
 4861                  */
 4862                 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
 4863                     va < DMAP_MAX_ADDRESS),
 4864                     ("pmap_demote_pde: No saved mpte for va %#lx", va));
 4865 
 4866                 /*
 4867                  * If the 2MB page mapping belongs to the direct map
 4868                  * region of the kernel's address space, then the page
 4869                  * allocation request specifies the highest possible
 4870                  * priority (VM_ALLOC_INTERRUPT).  Otherwise, the
 4871                  * priority is normal.
 4872                  */
 4873                 mpte = vm_page_alloc(NULL, pmap_pde_pindex(va),
 4874                     (in_kernel ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
 4875                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
 4876 
 4877                 /*
 4878                  * If the allocation of the new page table page fails,
 4879                  * invalidate the 2MB page mapping and return "failure".
 4880                  */
 4881                 if (mpte == NULL) {
 4882                         pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
 4883                         return (FALSE);
 4884                 }
 4885 
 4886                 if (!in_kernel) {
 4887                         mpte->wire_count = NPTEPG;
 4888                         pmap_resident_count_inc(pmap, 1);
 4889                 }
 4890         }
 4891         mptepa = VM_PAGE_TO_PHYS(mpte);
 4892         firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
 4893         newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
 4894         KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
 4895             ("pmap_demote_pde: oldpde is missing PG_M"));
 4896         newpte = oldpde & ~PG_PS;
 4897         newpte = pmap_swap_pat(pmap, newpte);
 4898 
 4899         /*
 4900          * If the page table page is not leftover from an earlier promotion,
 4901          * initialize it.
 4902          */
 4903         if (mpte->valid == 0)
 4904                 pmap_fill_ptp(firstpte, newpte);
 4905 
 4906         pmap_demote_pde_check(firstpte, newpte);
 4907 
 4908         /*
 4909          * If the mapping has changed attributes, update the page table
 4910          * entries.
 4911          */
 4912         if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
 4913                 pmap_fill_ptp(firstpte, newpte);
 4914 
 4915         /*
 4916          * The spare PV entries must be reserved prior to demoting the
 4917          * mapping, that is, prior to changing the PDE.  Otherwise, the state
 4918          * of the PDE and the PV lists will be inconsistent, which can result
 4919          * in reclaim_pv_chunk() attempting to remove a PV entry from the
 4920          * wrong PV list and pmap_pv_demote_pde() failing to find the expected
 4921          * PV entry for the 2MB page mapping that is being demoted.
 4922          */
 4923         if ((oldpde & PG_MANAGED) != 0)
 4924                 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
 4925 
 4926         /*
 4927          * Demote the mapping.  This pmap is locked.  The old PDE has
 4928          * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
 4929          * set.  Thus, there is no danger of a race with another
 4930          * processor changing the setting of PG_A and/or PG_M between
 4931          * the read above and the store below. 
 4932          */
 4933         if (workaround_erratum383)
 4934                 pmap_update_pde(pmap, va, pde, newpde);
 4935         else
 4936                 pde_store(pde, newpde);
 4937 
 4938         /*
 4939          * Invalidate a stale recursive mapping of the page table page.
 4940          */
 4941         if (in_kernel)
 4942                 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
 4943 
 4944         /*
 4945          * Demote the PV entry.
 4946          */
 4947         if ((oldpde & PG_MANAGED) != 0)
 4948                 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
 4949 
 4950         atomic_add_long(&pmap_pde_demotions, 1);
 4951         CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
 4952             va, pmap);
 4953         return (TRUE);
 4954 }
 4955 
 4956 /*
 4957  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
 4958  */
 4959 static void
 4960 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
 4961 {
 4962         pd_entry_t newpde;
 4963         vm_paddr_t mptepa;
 4964         vm_page_t mpte;
 4965 
 4966         KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
 4967         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 4968         mpte = pmap_remove_pt_page(pmap, va);
 4969         if (mpte == NULL)
 4970                 panic("pmap_remove_kernel_pde: Missing pt page.");
 4971 
 4972         mptepa = VM_PAGE_TO_PHYS(mpte);
 4973         newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
 4974 
 4975         /*
 4976          * If this page table page was unmapped by a promotion, then it
 4977          * contains valid mappings.  Zero it to invalidate those mappings.
 4978          */
 4979         if (mpte->valid != 0)
 4980                 pagezero((void *)PHYS_TO_DMAP(mptepa));
 4981 
 4982         /*
 4983          * Demote the mapping.
 4984          */
 4985         if (workaround_erratum383)
 4986                 pmap_update_pde(pmap, va, pde, newpde);
 4987         else
 4988                 pde_store(pde, newpde);
 4989 
 4990         /*
 4991          * Invalidate a stale recursive mapping of the page table page.
 4992          */
 4993         pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
 4994 }
 4995 
 4996 /*
 4997  * pmap_remove_pde: do the things to unmap a superpage in a process
 4998  */
 4999 static int
 5000 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
 5001     struct spglist *free, struct rwlock **lockp)
 5002 {
 5003         struct md_page *pvh;
 5004         pd_entry_t oldpde;
 5005         vm_offset_t eva, va;
 5006         vm_page_t m, mpte;
 5007         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
 5008 
 5009         PG_G = pmap_global_bit(pmap);
 5010         PG_A = pmap_accessed_bit(pmap);
 5011         PG_M = pmap_modified_bit(pmap);
 5012         PG_RW = pmap_rw_bit(pmap);
 5013 
 5014         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5015         KASSERT((sva & PDRMASK) == 0,
 5016             ("pmap_remove_pde: sva is not 2mpage aligned"));
 5017         oldpde = pte_load_clear(pdq);
 5018         if (oldpde & PG_W)
 5019                 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
 5020         if ((oldpde & PG_G) != 0)
 5021                 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
 5022         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
 5023         if (oldpde & PG_MANAGED) {
 5024                 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
 5025                 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
 5026                 pmap_pvh_free(pvh, pmap, sva);
 5027                 eva = sva + NBPDR;
 5028                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
 5029                     va < eva; va += PAGE_SIZE, m++) {
 5030                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
 5031                                 vm_page_dirty(m);
 5032                         if (oldpde & PG_A)
 5033                                 vm_page_aflag_set(m, PGA_REFERENCED);
 5034                         if (TAILQ_EMPTY(&m->md.pv_list) &&
 5035                             TAILQ_EMPTY(&pvh->pv_list))
 5036                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
 5037                         pmap_delayed_invl_page(m);
 5038                 }
 5039         }
 5040         if (pmap == kernel_pmap) {
 5041                 pmap_remove_kernel_pde(pmap, pdq, sva);
 5042         } else {
 5043                 mpte = pmap_remove_pt_page(pmap, sva);
 5044                 if (mpte != NULL) {
 5045                         KASSERT(mpte->valid == VM_PAGE_BITS_ALL,
 5046                             ("pmap_remove_pde: pte page not promoted"));
 5047                         pmap_resident_count_dec(pmap, 1);
 5048                         KASSERT(mpte->wire_count == NPTEPG,
 5049                             ("pmap_remove_pde: pte page wire count error"));
 5050                         mpte->wire_count = 0;
 5051                         pmap_add_delayed_free_list(mpte, free, FALSE);
 5052                 }
 5053         }
 5054         return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
 5055 }
 5056 
 5057 /*
 5058  * pmap_remove_pte: do the things to unmap a page in a process
 5059  */
 5060 static int
 5061 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, 
 5062     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
 5063 {
 5064         struct md_page *pvh;
 5065         pt_entry_t oldpte, PG_A, PG_M, PG_RW;
 5066         vm_page_t m;
 5067 
 5068         PG_A = pmap_accessed_bit(pmap);
 5069         PG_M = pmap_modified_bit(pmap);
 5070         PG_RW = pmap_rw_bit(pmap);
 5071 
 5072         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5073         oldpte = pte_load_clear(ptq);
 5074         if (oldpte & PG_W)
 5075                 pmap->pm_stats.wired_count -= 1;
 5076         pmap_resident_count_dec(pmap, 1);
 5077         if (oldpte & PG_MANAGED) {
 5078                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
 5079                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 5080                         vm_page_dirty(m);
 5081                 if (oldpte & PG_A)
 5082                         vm_page_aflag_set(m, PGA_REFERENCED);
 5083                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
 5084                 pmap_pvh_free(&m->md, pmap, va);
 5085                 if (TAILQ_EMPTY(&m->md.pv_list) &&
 5086                     (m->flags & PG_FICTITIOUS) == 0) {
 5087                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 5088                         if (TAILQ_EMPTY(&pvh->pv_list))
 5089                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
 5090                 }
 5091                 pmap_delayed_invl_page(m);
 5092         }
 5093         return (pmap_unuse_pt(pmap, va, ptepde, free));
 5094 }
 5095 
 5096 /*
 5097  * Remove a single page from a process address space
 5098  */
 5099 static void
 5100 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
 5101     struct spglist *free)
 5102 {
 5103         struct rwlock *lock;
 5104         pt_entry_t *pte, PG_V;
 5105 
 5106         PG_V = pmap_valid_bit(pmap);
 5107         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5108         if ((*pde & PG_V) == 0)
 5109                 return;
 5110         pte = pmap_pde_to_pte(pde, va);
 5111         if ((*pte & PG_V) == 0)
 5112                 return;
 5113         lock = NULL;
 5114         pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
 5115         if (lock != NULL)
 5116                 rw_wunlock(lock);
 5117         pmap_invalidate_page(pmap, va);
 5118 }
 5119 
 5120 /*
 5121  * Removes the specified range of addresses from the page table page.
 5122  */
 5123 static bool
 5124 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
 5125     pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
 5126 {
 5127         pt_entry_t PG_G, *pte;
 5128         vm_offset_t va;
 5129         bool anyvalid;
 5130 
 5131         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5132         PG_G = pmap_global_bit(pmap);
 5133         anyvalid = false;
 5134         va = eva;
 5135         for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
 5136             sva += PAGE_SIZE) {
 5137                 if (*pte == 0) {
 5138                         if (va != eva) {
 5139                                 pmap_invalidate_range(pmap, va, sva);
 5140                                 va = eva;
 5141                         }
 5142                         continue;
 5143                 }
 5144                 if ((*pte & PG_G) == 0)
 5145                         anyvalid = true;
 5146                 else if (va == eva)
 5147                         va = sva;
 5148                 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
 5149                         sva += PAGE_SIZE;
 5150                         break;
 5151                 }
 5152         }
 5153         if (va != eva)
 5154                 pmap_invalidate_range(pmap, va, sva);
 5155         return (anyvalid);
 5156 }
 5157 
 5158 /*
 5159  *      Remove the given range of addresses from the specified map.
 5160  *
 5161  *      It is assumed that the start and end are properly
 5162  *      rounded to the page size.
 5163  */
 5164 void
 5165 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 5166 {
 5167         struct rwlock *lock;
 5168         vm_offset_t va_next;
 5169         pml4_entry_t *pml4e;
 5170         pdp_entry_t *pdpe;
 5171         pd_entry_t ptpaddr, *pde;
 5172         pt_entry_t PG_G, PG_V;
 5173         struct spglist free;
 5174         int anyvalid;
 5175 
 5176         PG_G = pmap_global_bit(pmap);
 5177         PG_V = pmap_valid_bit(pmap);
 5178 
 5179         /*
 5180          * Perform an unsynchronized read.  This is, however, safe.
 5181          */
 5182         if (pmap->pm_stats.resident_count == 0)
 5183                 return;
 5184 
 5185         anyvalid = 0;
 5186         SLIST_INIT(&free);
 5187 
 5188         pmap_delayed_invl_start();
 5189         PMAP_LOCK(pmap);
 5190         pmap_pkru_on_remove(pmap, sva, eva);
 5191 
 5192         /*
 5193          * special handling of removing one page.  a very
 5194          * common operation and easy to short circuit some
 5195          * code.
 5196          */
 5197         if (sva + PAGE_SIZE == eva) {
 5198                 pde = pmap_pde(pmap, sva);
 5199                 if (pde && (*pde & PG_PS) == 0) {
 5200                         pmap_remove_page(pmap, sva, pde, &free);
 5201                         goto out;
 5202                 }
 5203         }
 5204 
 5205         lock = NULL;
 5206         for (; sva < eva; sva = va_next) {
 5207 
 5208                 if (pmap->pm_stats.resident_count == 0)
 5209                         break;
 5210 
 5211                 pml4e = pmap_pml4e(pmap, sva);
 5212                 if ((*pml4e & PG_V) == 0) {
 5213                         va_next = (sva + NBPML4) & ~PML4MASK;
 5214                         if (va_next < sva)
 5215                                 va_next = eva;
 5216                         continue;
 5217                 }
 5218 
 5219                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
 5220                 if ((*pdpe & PG_V) == 0) {
 5221                         va_next = (sva + NBPDP) & ~PDPMASK;
 5222                         if (va_next < sva)
 5223                                 va_next = eva;
 5224                         continue;
 5225                 }
 5226 
 5227                 /*
 5228                  * Calculate index for next page table.
 5229                  */
 5230                 va_next = (sva + NBPDR) & ~PDRMASK;
 5231                 if (va_next < sva)
 5232                         va_next = eva;
 5233 
 5234                 pde = pmap_pdpe_to_pde(pdpe, sva);
 5235                 ptpaddr = *pde;
 5236 
 5237                 /*
 5238                  * Weed out invalid mappings.
 5239                  */
 5240                 if (ptpaddr == 0)
 5241                         continue;
 5242 
 5243                 /*
 5244                  * Check for large page.
 5245                  */
 5246                 if ((ptpaddr & PG_PS) != 0) {
 5247                         /*
 5248                          * Are we removing the entire large page?  If not,
 5249                          * demote the mapping and fall through.
 5250                          */
 5251                         if (sva + NBPDR == va_next && eva >= va_next) {
 5252                                 /*
 5253                                  * The TLB entry for a PG_G mapping is
 5254                                  * invalidated by pmap_remove_pde().
 5255                                  */
 5256                                 if ((ptpaddr & PG_G) == 0)
 5257                                         anyvalid = 1;
 5258                                 pmap_remove_pde(pmap, pde, sva, &free, &lock);
 5259                                 continue;
 5260                         } else if (!pmap_demote_pde_locked(pmap, pde, sva,
 5261                             &lock)) {
 5262                                 /* The large page mapping was destroyed. */
 5263                                 continue;
 5264                         } else
 5265                                 ptpaddr = *pde;
 5266                 }
 5267 
 5268                 /*
 5269                  * Limit our scan to either the end of the va represented
 5270                  * by the current page table page, or to the end of the
 5271                  * range being removed.
 5272                  */
 5273                 if (va_next > eva)
 5274                         va_next = eva;
 5275 
 5276                 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
 5277                         anyvalid = 1;
 5278         }
 5279         if (lock != NULL)
 5280                 rw_wunlock(lock);
 5281 out:
 5282         if (anyvalid)
 5283                 pmap_invalidate_all(pmap);
 5284         PMAP_UNLOCK(pmap);
 5285         pmap_delayed_invl_finish();
 5286         vm_page_free_pages_toq(&free, true);
 5287 }
 5288 
 5289 /*
 5290  *      Routine:        pmap_remove_all
 5291  *      Function:
 5292  *              Removes this physical page from
 5293  *              all physical maps in which it resides.
 5294  *              Reflects back modify bits to the pager.
 5295  *
 5296  *      Notes:
 5297  *              Original versions of this routine were very
 5298  *              inefficient because they iteratively called
 5299  *              pmap_remove (slow...)
 5300  */
 5301 
 5302 void
 5303 pmap_remove_all(vm_page_t m)
 5304 {
 5305         struct md_page *pvh;
 5306         pv_entry_t pv;
 5307         pmap_t pmap;
 5308         struct rwlock *lock;
 5309         pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
 5310         pd_entry_t *pde;
 5311         vm_offset_t va;
 5312         struct spglist free;
 5313         int pvh_gen, md_gen;
 5314 
 5315         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 5316             ("pmap_remove_all: page %p is not managed", m));
 5317         SLIST_INIT(&free);
 5318         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
 5319         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
 5320             pa_to_pvh(VM_PAGE_TO_PHYS(m));
 5321 retry:
 5322         rw_wlock(lock);
 5323         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
 5324                 pmap = PV_PMAP(pv);
 5325                 if (!PMAP_TRYLOCK(pmap)) {
 5326                         pvh_gen = pvh->pv_gen;
 5327                         rw_wunlock(lock);
 5328                         PMAP_LOCK(pmap);
 5329                         rw_wlock(lock);
 5330                         if (pvh_gen != pvh->pv_gen) {
 5331                                 rw_wunlock(lock);
 5332                                 PMAP_UNLOCK(pmap);
 5333                                 goto retry;
 5334                         }
 5335                 }
 5336                 va = pv->pv_va;
 5337                 pde = pmap_pde(pmap, va);
 5338                 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
 5339                 PMAP_UNLOCK(pmap);
 5340         }
 5341         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 5342                 pmap = PV_PMAP(pv);
 5343                 if (!PMAP_TRYLOCK(pmap)) {
 5344                         pvh_gen = pvh->pv_gen;
 5345                         md_gen = m->md.pv_gen;
 5346                         rw_wunlock(lock);
 5347                         PMAP_LOCK(pmap);
 5348                         rw_wlock(lock);
 5349                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
 5350                                 rw_wunlock(lock);
 5351                                 PMAP_UNLOCK(pmap);
 5352                                 goto retry;
 5353                         }
 5354                 }
 5355                 PG_A = pmap_accessed_bit(pmap);
 5356                 PG_M = pmap_modified_bit(pmap);
 5357                 PG_RW = pmap_rw_bit(pmap);
 5358                 pmap_resident_count_dec(pmap, 1);
 5359                 pde = pmap_pde(pmap, pv->pv_va);
 5360                 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
 5361                     " a 2mpage in page %p's pv list", m));
 5362                 pte = pmap_pde_to_pte(pde, pv->pv_va);
 5363                 tpte = pte_load_clear(pte);
 5364                 if (tpte & PG_W)
 5365                         pmap->pm_stats.wired_count--;
 5366                 if (tpte & PG_A)
 5367                         vm_page_aflag_set(m, PGA_REFERENCED);
 5368 
 5369                 /*
 5370                  * Update the vm_page_t clean and reference bits.
 5371                  */
 5372                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 5373                         vm_page_dirty(m);
 5374                 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
 5375                 pmap_invalidate_page(pmap, pv->pv_va);
 5376                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
 5377                 m->md.pv_gen++;
 5378                 free_pv_entry(pmap, pv);
 5379                 PMAP_UNLOCK(pmap);
 5380         }
 5381         vm_page_aflag_clear(m, PGA_WRITEABLE);
 5382         rw_wunlock(lock);
 5383         pmap_delayed_invl_wait(m);
 5384         vm_page_free_pages_toq(&free, true);
 5385 }
 5386 
 5387 /*
 5388  * pmap_protect_pde: do the things to protect a 2mpage in a process
 5389  */
 5390 static boolean_t
 5391 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
 5392 {
 5393         pd_entry_t newpde, oldpde;
 5394         vm_page_t m, mt;
 5395         boolean_t anychanged;
 5396         pt_entry_t PG_G, PG_M, PG_RW;
 5397 
 5398         PG_G = pmap_global_bit(pmap);
 5399         PG_M = pmap_modified_bit(pmap);
 5400         PG_RW = pmap_rw_bit(pmap);
 5401 
 5402         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 5403         KASSERT((sva & PDRMASK) == 0,
 5404             ("pmap_protect_pde: sva is not 2mpage aligned"));
 5405         anychanged = FALSE;
 5406 retry:
 5407         oldpde = newpde = *pde;
 5408         if ((prot & VM_PROT_WRITE) == 0) {
 5409                 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
 5410                     (PG_MANAGED | PG_M | PG_RW)) {
 5411                         m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
 5412                         for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
 5413                                 vm_page_dirty(mt);
 5414                 }
 5415                 newpde &= ~(PG_RW | PG_M);
 5416         }
 5417         if ((prot & VM_PROT_EXECUTE) == 0)
 5418                 newpde |= pg_nx;
 5419         if (newpde != oldpde) {
 5420                 /*
 5421                  * As an optimization to future operations on this PDE, clear
 5422                  * PG_PROMOTED.  The impending invalidation will remove any
 5423                  * lingering 4KB page mappings from the TLB.
 5424                  */
 5425                 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
 5426                         goto retry;
 5427                 if ((oldpde & PG_G) != 0)
 5428                         pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
 5429                 else
 5430                         anychanged = TRUE;
 5431         }
 5432         return (anychanged);
 5433 }
 5434 
 5435 /*
 5436  *      Set the physical protection on the
 5437  *      specified range of this map as requested.
 5438  */
 5439 void
 5440 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
 5441 {
 5442         vm_offset_t va_next;
 5443         pml4_entry_t *pml4e;
 5444         pdp_entry_t *pdpe;
 5445         pd_entry_t ptpaddr, *pde;
 5446         pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
 5447         boolean_t anychanged;
 5448 
 5449         KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
 5450         if (prot == VM_PROT_NONE) {
 5451                 pmap_remove(pmap, sva, eva);
 5452                 return;
 5453         }
 5454 
 5455         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
 5456             (VM_PROT_WRITE|VM_PROT_EXECUTE))
 5457                 return;
 5458 
 5459         PG_G = pmap_global_bit(pmap);
 5460         PG_M = pmap_modified_bit(pmap);
 5461         PG_V = pmap_valid_bit(pmap);
 5462         PG_RW = pmap_rw_bit(pmap);
 5463         anychanged = FALSE;
 5464 
 5465         /*
 5466          * Although this function delays and batches the invalidation
 5467          * of stale TLB entries, it does not need to call
 5468          * pmap_delayed_invl_start() and
 5469          * pmap_delayed_invl_finish(), because it does not
 5470          * ordinarily destroy mappings.  Stale TLB entries from
 5471          * protection-only changes need only be invalidated before the
 5472          * pmap lock is released, because protection-only changes do
 5473          * not destroy PV entries.  Even operations that iterate over
 5474          * a physical page's PV list of mappings, like
 5475          * pmap_remove_write(), acquire the pmap lock for each
 5476          * mapping.  Consequently, for protection-only changes, the
 5477          * pmap lock suffices to synchronize both page table and TLB
 5478          * updates.
 5479          *
 5480          * This function only destroys a mapping if pmap_demote_pde()
 5481          * fails.  In that case, stale TLB entries are immediately
 5482          * invalidated.
 5483          */
 5484         
 5485         PMAP_LOCK(pmap);
 5486         for (; sva < eva; sva = va_next) {
 5487 
 5488                 pml4e = pmap_pml4e(pmap, sva);
 5489                 if ((*pml4e & PG_V) == 0) {
 5490                         va_next = (sva + NBPML4) & ~PML4MASK;
 5491                         if (va_next < sva)
 5492                                 va_next = eva;
 5493                         continue;
 5494                 }
 5495 
 5496                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);