The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


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

FreeBSD/Linux Kernel Cross Reference
sys/i386/i386/pmap.c

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

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