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  -  FREEBSD11  -  FREEBSD10  -  FREEBSD9  -  FREEBSD92  -  FREEBSD91  -  FREEBSD90  -  FREEBSD8  -  FREEBSD82  -  FREEBSD81  -  FREEBSD80  -  FREEBSD7  -  FREEBSD74  -  FREEBSD73  -  FREEBSD72  -  FREEBSD71  -  FREEBSD70  -  FREEBSD6  -  FREEBSD64  -  FREEBSD63  -  FREEBSD62  -  FREEBSD61  -  FREEBSD60  -  FREEBSD5  -  FREEBSD55  -  FREEBSD54  -  FREEBSD53  -  FREEBSD52  -  FREEBSD51  -  FREEBSD50  -  FREEBSD4  -  FREEBSD3  -  FREEBSD22  -  linux-2.6  -  linux-2.4.22  -  MK83  -  MK84  -  PLAN9  -  DFBSD  -  NETBSD  -  NETBSD5  -  NETBSD4  -  NETBSD3  -  NETBSD20  -  OPENBSD  -  xnu-517  -  xnu-792  -  xnu-792.6.70  -  xnu-1228  -  xnu-1456.1.26  -  xnu-1699.24.8  -  xnu-2050.18.24  -  OPENSOLARIS  -  minix-3-1-1 
SearchContext: -  none  -  3  -  10 

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