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


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

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

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

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