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