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

Cache object: b6e03dc0447adda59a179c829abec4b2


[ 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.