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