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


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

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

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

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