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

Cache object: 3e85dcb547f2614b933945ce99131389


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


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.