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