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

Cache object: 9f8e6a8766e0a55a3c373295edf85240


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