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/i386/i386/pmap.c

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

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

Cache object: 8fd840b99ce4ade21f98472914864173


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