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

Cache object: 4f81bb8d27d22a5dd4960f4b2cdf0170


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