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

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*-
    2  * Copyright (c) 1991 Regents of the University of California.
    3  * All rights reserved.
    4  * Copyright (c) 1994 John S. Dyson
    5  * All rights reserved.
    6  * Copyright (c) 1994 David Greenman
    7  * All rights reserved.
    8  * Copyright (c) 2005 Alan L. Cox <alc@cs.rice.edu>
    9  * All rights reserved.
   10  *
   11  * This code is derived from software contributed to Berkeley by
   12  * the Systems Programming Group of the University of Utah Computer
   13  * Science Department and William Jolitz of UUNET Technologies Inc.
   14  *
   15  * Redistribution and use in source and binary forms, with or without
   16  * modification, are permitted provided that the following conditions
   17  * are met:
   18  * 1. Redistributions of source code must retain the above copyright
   19  *    notice, this list of conditions and the following disclaimer.
   20  * 2. Redistributions in binary form must reproduce the above copyright
   21  *    notice, this list of conditions and the following disclaimer in the
   22  *    documentation and/or other materials provided with the distribution.
   23  * 3. All advertising materials mentioning features or use of this software
   24  *    must display the following acknowledgement:
   25  *      This product includes software developed by the University of
   26  *      California, Berkeley and its contributors.
   27  * 4. Neither the name of the University nor the names of its contributors
   28  *    may be used to endorse or promote products derived from this software
   29  *    without specific prior written permission.
   30  *
   31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   41  * SUCH DAMAGE.
   42  *
   43  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
   44  */
   45 /*-
   46  * Copyright (c) 2003 Networks Associates Technology, Inc.
   47  * All rights reserved.
   48  *
   49  * This software was developed for the FreeBSD Project by Jake Burkholder,
   50  * Safeport Network Services, and Network Associates Laboratories, the
   51  * Security Research Division of Network Associates, Inc. under
   52  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
   53  * CHATS research program.
   54  *
   55  * Redistribution and use in source and binary forms, with or without
   56  * modification, are permitted provided that the following conditions
   57  * are met:
   58  * 1. Redistributions of source code must retain the above copyright
   59  *    notice, this list of conditions and the following disclaimer.
   60  * 2. Redistributions in binary form must reproduce the above copyright
   61  *    notice, this list of conditions and the following disclaimer in the
   62  *    documentation and/or other materials provided with the distribution.
   63  *
   64  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
   65  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   66  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   67  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   68  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   69  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   70  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   71  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   72  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   73  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   74  * SUCH DAMAGE.
   75  */
   76 
   77 #include <sys/cdefs.h>
   78 __FBSDID("$FreeBSD: releng/9.1/sys/i386/xen/pmap.c 238005 2012-07-02 17:22:38Z alc $");
   79 
   80 /*
   81  *      Manages physical address maps.
   82  *
   83  *      In addition to hardware address maps, this
   84  *      module is called upon to provide software-use-only
   85  *      maps which may or may not be stored in the same
   86  *      form as hardware maps.  These pseudo-maps are
   87  *      used to store intermediate results from copy
   88  *      operations to and from address spaces.
   89  *
   90  *      Since the information managed by this module is
   91  *      also stored by the logical address mapping module,
   92  *      this module may throw away valid virtual-to-physical
   93  *      mappings at almost any time.  However, invalidations
   94  *      of virtual-to-physical mappings must be done as
   95  *      requested.
   96  *
   97  *      In order to cope with hardware architectures which
   98  *      make virtual-to-physical map invalidates expensive,
   99  *      this module may delay invalidate or reduced protection
  100  *      operations until such time as they are actually
  101  *      necessary.  This module is given full information as
  102  *      to which processors are currently using which maps,
  103  *      and to when physical maps must be made correct.
  104  */
  105 
  106 #include "opt_cpu.h"
  107 #include "opt_pmap.h"
  108 #include "opt_smp.h"
  109 #include "opt_xbox.h"
  110 
  111 #include <sys/param.h>
  112 #include <sys/systm.h>
  113 #include <sys/kernel.h>
  114 #include <sys/ktr.h>
  115 #include <sys/lock.h>
  116 #include <sys/malloc.h>
  117 #include <sys/mman.h>
  118 #include <sys/msgbuf.h>
  119 #include <sys/mutex.h>
  120 #include <sys/proc.h>
  121 #include <sys/sf_buf.h>
  122 #include <sys/sx.h>
  123 #include <sys/vmmeter.h>
  124 #include <sys/sched.h>
  125 #include <sys/sysctl.h>
  126 #ifdef SMP
  127 #include <sys/smp.h>
  128 #else
  129 #include <sys/cpuset.h>
  130 #endif
  131 
  132 #include <vm/vm.h>
  133 #include <vm/vm_param.h>
  134 #include <vm/vm_kern.h>
  135 #include <vm/vm_page.h>
  136 #include <vm/vm_map.h>
  137 #include <vm/vm_object.h>
  138 #include <vm/vm_extern.h>
  139 #include <vm/vm_pageout.h>
  140 #include <vm/vm_pager.h>
  141 #include <vm/uma.h>
  142 
  143 #include <machine/cpu.h>
  144 #include <machine/cputypes.h>
  145 #include <machine/md_var.h>
  146 #include <machine/pcb.h>
  147 #include <machine/specialreg.h>
  148 #ifdef SMP
  149 #include <machine/smp.h>
  150 #endif
  151 
  152 #ifdef XBOX
  153 #include <machine/xbox.h>
  154 #endif
  155 
  156 #include <xen/interface/xen.h>
  157 #include <xen/hypervisor.h>
  158 #include <machine/xen/hypercall.h>
  159 #include <machine/xen/xenvar.h>
  160 #include <machine/xen/xenfunc.h>
  161 
  162 #if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
  163 #define CPU_ENABLE_SSE
  164 #endif
  165 
  166 #ifndef PMAP_SHPGPERPROC
  167 #define PMAP_SHPGPERPROC 200
  168 #endif
  169 
  170 #define DIAGNOSTIC
  171 
  172 #if !defined(DIAGNOSTIC)
  173 #ifdef __GNUC_GNU_INLINE__
  174 #define PMAP_INLINE     __attribute__((__gnu_inline__)) inline
  175 #else
  176 #define PMAP_INLINE     extern inline
  177 #endif
  178 #else
  179 #define PMAP_INLINE
  180 #endif
  181 
  182 #define PV_STATS
  183 #ifdef PV_STATS
  184 #define PV_STAT(x)      do { x ; } while (0)
  185 #else
  186 #define PV_STAT(x)      do { } while (0)
  187 #endif
  188 
  189 /*
  190  * Get PDEs and PTEs for user/kernel address space
  191  */
  192 #define pmap_pde(m, v)  (&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
  193 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
  194 
  195 #define pmap_pde_v(pte)         ((*(int *)pte & PG_V) != 0)
  196 #define pmap_pte_w(pte)         ((*(int *)pte & PG_W) != 0)
  197 #define pmap_pte_m(pte)         ((*(int *)pte & PG_M) != 0)
  198 #define pmap_pte_u(pte)         ((*(int *)pte & PG_A) != 0)
  199 #define pmap_pte_v(pte)         ((*(int *)pte & PG_V) != 0)
  200 
  201 #define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
  202 
  203 #define HAMFISTED_LOCKING
  204 #ifdef HAMFISTED_LOCKING
  205 static struct mtx createdelete_lock;
  206 #endif
  207 
  208 struct pmap kernel_pmap_store;
  209 LIST_HEAD(pmaplist, pmap);
  210 static struct pmaplist allpmaps;
  211 static struct mtx allpmaps_lock;
  212 
  213 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
  214 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
  215 int pgeflag = 0;                /* PG_G or-in */
  216 int pseflag = 0;                /* PG_PS or-in */
  217 
  218 int nkpt;
  219 vm_offset_t kernel_vm_end;
  220 extern u_int32_t KERNend;
  221 
  222 #ifdef PAE
  223 pt_entry_t pg_nx;
  224 #endif
  225 
  226 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
  227 
  228 static int pat_works;                   /* Is page attribute table sane? */
  229 
  230 /*
  231  * Data for the pv entry allocation mechanism
  232  */
  233 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
  234 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
  235 static int shpgperproc = PMAP_SHPGPERPROC;
  236 
  237 struct pv_chunk *pv_chunkbase;          /* KVA block for pv_chunks */
  238 int pv_maxchunks;                       /* How many chunks we have KVA for */
  239 vm_offset_t pv_vafree;                  /* freelist stored in the PTE */
  240 
  241 /*
  242  * All those kernel PT submaps that BSD is so fond of
  243  */
  244 struct sysmaps {
  245         struct  mtx lock;
  246         pt_entry_t *CMAP1;
  247         pt_entry_t *CMAP2;
  248         caddr_t CADDR1;
  249         caddr_t CADDR2;
  250 };
  251 static struct sysmaps sysmaps_pcpu[MAXCPU];
  252 static pt_entry_t *CMAP3;
  253 caddr_t ptvmmap = 0;
  254 static caddr_t CADDR3;
  255 struct msgbuf *msgbufp = 0;
  256 
  257 /*
  258  * Crashdump maps.
  259  */
  260 static caddr_t crashdumpmap;
  261 
  262 static pt_entry_t *PMAP1 = 0, *PMAP2;
  263 static pt_entry_t *PADDR1 = 0, *PADDR2;
  264 #ifdef SMP
  265 static int PMAP1cpu;
  266 static int PMAP1changedcpu;
  267 SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD, 
  268            &PMAP1changedcpu, 0,
  269            "Number of times pmap_pte_quick changed CPU with same PMAP1");
  270 #endif
  271 static int PMAP1changed;
  272 SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD, 
  273            &PMAP1changed, 0,
  274            "Number of times pmap_pte_quick changed PMAP1");
  275 static int PMAP1unchanged;
  276 SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD, 
  277            &PMAP1unchanged, 0,
  278            "Number of times pmap_pte_quick didn't change PMAP1");
  279 static struct mtx PMAP2mutex;
  280 
  281 static void     free_pv_chunk(struct pv_chunk *pc);
  282 static void     free_pv_entry(pmap_t pmap, pv_entry_t pv);
  283 static pv_entry_t get_pv_entry(pmap_t pmap, boolean_t try);
  284 static void     pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
  285 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
  286                     vm_offset_t va);
  287 
  288 static vm_page_t pmap_enter_quick_locked(multicall_entry_t **mcl, int *count, pmap_t pmap, vm_offset_t va,
  289     vm_page_t m, vm_prot_t prot, vm_page_t mpte);
  290 static void pmap_flush_page(vm_page_t m);
  291 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
  292 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
  293     vm_page_t *free);
  294 static void pmap_remove_page(struct pmap *pmap, vm_offset_t va,
  295     vm_page_t *free);
  296 static void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
  297                                         vm_offset_t va);
  298 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
  299     vm_page_t m);
  300 
  301 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags);
  302 
  303 static vm_page_t _pmap_allocpte(pmap_t pmap, u_int ptepindex, int flags);
  304 static int _pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m, vm_page_t *free);
  305 static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
  306 static void pmap_pte_release(pt_entry_t *pte);
  307 static int pmap_unuse_pt(pmap_t, vm_offset_t, vm_page_t *);
  308 static boolean_t pmap_is_prefaultable_locked(pmap_t pmap, vm_offset_t addr);
  309 
  310 static __inline void pagezero(void *page);
  311 
  312 CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
  313 CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
  314 
  315 /*
  316  * If you get an error here, then you set KVA_PAGES wrong! See the
  317  * description of KVA_PAGES in sys/i386/include/pmap.h. It must be
  318  * multiple of 4 for a normal kernel, or a multiple of 8 for a PAE.
  319  */
  320 CTASSERT(KERNBASE % (1 << 24) == 0);
  321 
  322 void 
  323 pd_set(struct pmap *pmap, int ptepindex, vm_paddr_t val, int type)
  324 {
  325         vm_paddr_t pdir_ma = vtomach(&pmap->pm_pdir[ptepindex]);
  326         
  327         switch (type) {
  328         case SH_PD_SET_VA:
  329 #if 0           
  330                 xen_queue_pt_update(shadow_pdir_ma,
  331                                     xpmap_ptom(val & ~(PG_RW)));
  332 #endif          
  333                 xen_queue_pt_update(pdir_ma,
  334                                     xpmap_ptom(val));   
  335                 break;
  336         case SH_PD_SET_VA_MA:
  337 #if 0           
  338                 xen_queue_pt_update(shadow_pdir_ma,
  339                                     val & ~(PG_RW));
  340 #endif          
  341                 xen_queue_pt_update(pdir_ma, val);      
  342                 break;
  343         case SH_PD_SET_VA_CLEAR:
  344 #if 0
  345                 xen_queue_pt_update(shadow_pdir_ma, 0);
  346 #endif          
  347                 xen_queue_pt_update(pdir_ma, 0);        
  348                 break;
  349         }
  350 }
  351 
  352 /*
  353  *      Bootstrap the system enough to run with virtual memory.
  354  *
  355  *      On the i386 this is called after mapping has already been enabled
  356  *      and just syncs the pmap module with what has already been done.
  357  *      [We can't call it easily with mapping off since the kernel is not
  358  *      mapped with PA == VA, hence we would have to relocate every address
  359  *      from the linked base (virtual) address "KERNBASE" to the actual
  360  *      (physical) address starting relative to 0]
  361  */
  362 void
  363 pmap_bootstrap(vm_paddr_t firstaddr)
  364 {
  365         vm_offset_t va;
  366         pt_entry_t *pte, *unused;
  367         struct sysmaps *sysmaps;
  368         int i;
  369 
  370         /*
  371          * Initialize the first available kernel virtual address.  However,
  372          * using "firstaddr" may waste a few pages of the kernel virtual
  373          * address space, because locore may not have mapped every physical
  374          * page that it allocated.  Preferably, locore would provide a first
  375          * unused virtual address in addition to "firstaddr".
  376          */
  377         virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
  378 
  379         virtual_end = VM_MAX_KERNEL_ADDRESS;
  380 
  381         /*
  382          * Initialize the kernel pmap (which is statically allocated).
  383          */
  384         PMAP_LOCK_INIT(kernel_pmap);
  385         kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
  386 #ifdef PAE
  387         kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
  388 #endif
  389         CPU_FILL(&kernel_pmap->pm_active);      /* don't allow deactivation */
  390         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
  391         LIST_INIT(&allpmaps);
  392         mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
  393         mtx_lock_spin(&allpmaps_lock);
  394         LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
  395         mtx_unlock_spin(&allpmaps_lock);
  396         if (nkpt == 0)
  397                 nkpt = NKPT;
  398 
  399         /*
  400          * Reserve some special page table entries/VA space for temporary
  401          * mapping of pages.
  402          */
  403 #define SYSMAP(c, p, v, n)      \
  404         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
  405 
  406         va = virtual_avail;
  407         pte = vtopte(va);
  408 
  409         /*
  410          * CMAP1/CMAP2 are used for zeroing and copying pages.
  411          * CMAP3 is used for the idle process page zeroing.
  412          */
  413         for (i = 0; i < MAXCPU; i++) {
  414                 sysmaps = &sysmaps_pcpu[i];
  415                 mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
  416                 SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1)
  417                 SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1)
  418                 PT_SET_MA(sysmaps->CADDR1, 0);
  419                 PT_SET_MA(sysmaps->CADDR2, 0);
  420         }
  421         SYSMAP(caddr_t, CMAP3, CADDR3, 1)
  422         PT_SET_MA(CADDR3, 0);
  423 
  424         /*
  425          * Crashdump maps.
  426          */
  427         SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
  428 
  429         /*
  430          * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
  431          */
  432         SYSMAP(caddr_t, unused, ptvmmap, 1)
  433 
  434         /*
  435          * msgbufp is used to map the system message buffer.
  436          */
  437         SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(msgbufsize)))
  438 
  439         /*
  440          * ptemap is used for pmap_pte_quick
  441          */
  442         SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1)
  443         SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1)
  444 
  445         mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
  446 
  447         virtual_avail = va;
  448 
  449         /*
  450          * Leave in place an identity mapping (virt == phys) for the low 1 MB
  451          * physical memory region that is used by the ACPI wakeup code.  This
  452          * mapping must not have PG_G set. 
  453          */
  454 #ifndef XEN
  455         /*
  456          * leave here deliberately to show that this is not supported
  457          */
  458 #ifdef XBOX
  459         /* FIXME: This is gross, but needed for the XBOX. Since we are in such
  460          * an early stadium, we cannot yet neatly map video memory ... :-(
  461          * Better fixes are very welcome! */
  462         if (!arch_i386_is_xbox)
  463 #endif
  464         for (i = 1; i < NKPT; i++)
  465                 PTD[i] = 0;
  466 
  467         /* Initialize the PAT MSR if present. */
  468         pmap_init_pat();
  469 
  470         /* Turn on PG_G on kernel page(s) */
  471         pmap_set_pg();
  472 #endif
  473 
  474 #ifdef HAMFISTED_LOCKING
  475         mtx_init(&createdelete_lock, "pmap create/delete", NULL, MTX_DEF);
  476 #endif
  477 }
  478 
  479 /*
  480  * Setup the PAT MSR.
  481  */
  482 void
  483 pmap_init_pat(void)
  484 {
  485         uint64_t pat_msr;
  486 
  487         /* Bail if this CPU doesn't implement PAT. */
  488         if (!(cpu_feature & CPUID_PAT))
  489                 return;
  490 
  491         if (cpu_vendor_id != CPU_VENDOR_INTEL ||
  492             (CPUID_TO_FAMILY(cpu_id) == 6 && CPUID_TO_MODEL(cpu_id) >= 0xe)) {
  493                 /*
  494                  * Leave the indices 0-3 at the default of WB, WT, UC, and UC-.
  495                  * Program 4 and 5 as WP and WC.
  496                  * Leave 6 and 7 as UC and UC-.
  497                  */
  498                 pat_msr = rdmsr(MSR_PAT);
  499                 pat_msr &= ~(PAT_MASK(4) | PAT_MASK(5));
  500                 pat_msr |= PAT_VALUE(4, PAT_WRITE_PROTECTED) |
  501                     PAT_VALUE(5, PAT_WRITE_COMBINING);
  502                 pat_works = 1;
  503         } else {
  504                 /*
  505                  * Due to some Intel errata, we can only safely use the lower 4
  506                  * PAT entries.  Thus, just replace PAT Index 2 with WC instead
  507                  * of UC-.
  508                  *
  509                  *   Intel Pentium III Processor Specification Update
  510                  * Errata E.27 (Upper Four PAT Entries Not Usable With Mode B
  511                  * or Mode C Paging)
  512                  *
  513                  *   Intel Pentium IV  Processor Specification Update
  514                  * Errata N46 (PAT Index MSB May Be Calculated Incorrectly)
  515                  */
  516                 pat_msr = rdmsr(MSR_PAT);
  517                 pat_msr &= ~PAT_MASK(2);
  518                 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
  519                 pat_works = 0;
  520         }
  521         wrmsr(MSR_PAT, pat_msr);
  522 }
  523 
  524 /*
  525  * Initialize a vm_page's machine-dependent fields.
  526  */
  527 void
  528 pmap_page_init(vm_page_t m)
  529 {
  530 
  531         TAILQ_INIT(&m->md.pv_list);
  532         m->md.pat_mode = PAT_WRITE_BACK;
  533 }
  534 
  535 /*
  536  * ABuse the pte nodes for unmapped kva to thread a kva freelist through.
  537  * Requirements:
  538  *  - Must deal with pages in order to ensure that none of the PG_* bits
  539  *    are ever set, PG_V in particular.
  540  *  - Assumes we can write to ptes without pte_store() atomic ops, even
  541  *    on PAE systems.  This should be ok.
  542  *  - Assumes nothing will ever test these addresses for 0 to indicate
  543  *    no mapping instead of correctly checking PG_V.
  544  *  - Assumes a vm_offset_t will fit in a pte (true for i386).
  545  * Because PG_V is never set, there can be no mappings to invalidate.
  546  */
  547 static int ptelist_count = 0;
  548 static vm_offset_t
  549 pmap_ptelist_alloc(vm_offset_t *head)
  550 {
  551         vm_offset_t va;
  552         vm_offset_t *phead = (vm_offset_t *)*head;
  553         
  554         if (ptelist_count == 0) {
  555                 printf("out of memory!!!!!!\n");
  556                 return (0);     /* Out of memory */
  557         }
  558         ptelist_count--;
  559         va = phead[ptelist_count];
  560         return (va);
  561 }
  562 
  563 static void
  564 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
  565 {
  566         vm_offset_t *phead = (vm_offset_t *)*head;
  567 
  568         phead[ptelist_count++] = va;
  569 }
  570 
  571 static void
  572 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
  573 {
  574         int i, nstackpages;
  575         vm_offset_t va;
  576         vm_page_t m;
  577         
  578         nstackpages = (npages + PAGE_SIZE/sizeof(vm_offset_t) - 1)/ (PAGE_SIZE/sizeof(vm_offset_t));
  579         for (i = 0; i < nstackpages; i++) {
  580                 va = (vm_offset_t)base + i * PAGE_SIZE;
  581                 m = vm_page_alloc(NULL, i,
  582                     VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
  583                     VM_ALLOC_ZERO);
  584                 pmap_qenter(va, &m, 1);
  585         }
  586 
  587         *head = (vm_offset_t)base;
  588         for (i = npages - 1; i >= nstackpages; i--) {
  589                 va = (vm_offset_t)base + i * PAGE_SIZE;
  590                 pmap_ptelist_free(head, va);
  591         }
  592 }
  593 
  594 
  595 /*
  596  *      Initialize the pmap module.
  597  *      Called by vm_init, to initialize any structures that the pmap
  598  *      system needs to map virtual memory.
  599  */
  600 void
  601 pmap_init(void)
  602 {
  603 
  604         /*
  605          * Initialize the address space (zone) for the pv entries.  Set a
  606          * high water mark so that the system can recover from excessive
  607          * numbers of pv entries.
  608          */
  609         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
  610         pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
  611         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
  612         pv_entry_max = roundup(pv_entry_max, _NPCPV);
  613         pv_entry_high_water = 9 * (pv_entry_max / 10);
  614 
  615         pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
  616         pv_chunkbase = (struct pv_chunk *)kmem_alloc_nofault(kernel_map,
  617             PAGE_SIZE * pv_maxchunks);
  618         if (pv_chunkbase == NULL)
  619                 panic("pmap_init: not enough kvm for pv chunks");
  620         pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
  621 }
  622 
  623 
  624 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
  625         "Max number of PV entries");
  626 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
  627         "Page share factor per proc");
  628 
  629 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
  630     "2/4MB page mapping counters");
  631 
  632 static u_long pmap_pde_mappings;
  633 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
  634     &pmap_pde_mappings, 0, "2/4MB page mappings");
  635 
  636 /***************************************************
  637  * Low level helper routines.....
  638  ***************************************************/
  639 
  640 /*
  641  * Determine the appropriate bits to set in a PTE or PDE for a specified
  642  * caching mode.
  643  */
  644 int
  645 pmap_cache_bits(int mode, boolean_t is_pde)
  646 {
  647         int pat_flag, pat_index, cache_bits;
  648 
  649         /* The PAT bit is different for PTE's and PDE's. */
  650         pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
  651 
  652         /* If we don't support PAT, map extended modes to older ones. */
  653         if (!(cpu_feature & CPUID_PAT)) {
  654                 switch (mode) {
  655                 case PAT_UNCACHEABLE:
  656                 case PAT_WRITE_THROUGH:
  657                 case PAT_WRITE_BACK:
  658                         break;
  659                 case PAT_UNCACHED:
  660                 case PAT_WRITE_COMBINING:
  661                 case PAT_WRITE_PROTECTED:
  662                         mode = PAT_UNCACHEABLE;
  663                         break;
  664                 }
  665         }
  666         
  667         /* Map the caching mode to a PAT index. */
  668         if (pat_works) {
  669                 switch (mode) {
  670                         case PAT_UNCACHEABLE:
  671                                 pat_index = 3;
  672                                 break;
  673                         case PAT_WRITE_THROUGH:
  674                                 pat_index = 1;
  675                                 break;
  676                         case PAT_WRITE_BACK:
  677                                 pat_index = 0;
  678                                 break;
  679                         case PAT_UNCACHED:
  680                                 pat_index = 2;
  681                                 break;
  682                         case PAT_WRITE_COMBINING:
  683                                 pat_index = 5;
  684                                 break;
  685                         case PAT_WRITE_PROTECTED:
  686                                 pat_index = 4;
  687                                 break;
  688                         default:
  689                                 panic("Unknown caching mode %d\n", mode);
  690                 }
  691         } else {
  692                 switch (mode) {
  693                         case PAT_UNCACHED:
  694                         case PAT_UNCACHEABLE:
  695                         case PAT_WRITE_PROTECTED:
  696                                 pat_index = 3;
  697                                 break;
  698                         case PAT_WRITE_THROUGH:
  699                                 pat_index = 1;
  700                                 break;
  701                         case PAT_WRITE_BACK:
  702                                 pat_index = 0;
  703                                 break;
  704                         case PAT_WRITE_COMBINING:
  705                                 pat_index = 2;
  706                                 break;
  707                         default:
  708                                 panic("Unknown caching mode %d\n", mode);
  709                 }
  710         }       
  711 
  712         /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
  713         cache_bits = 0;
  714         if (pat_index & 0x4)
  715                 cache_bits |= pat_flag;
  716         if (pat_index & 0x2)
  717                 cache_bits |= PG_NC_PCD;
  718         if (pat_index & 0x1)
  719                 cache_bits |= PG_NC_PWT;
  720         return (cache_bits);
  721 }
  722 #ifdef SMP
  723 /*
  724  * For SMP, these functions have to use the IPI mechanism for coherence.
  725  *
  726  * N.B.: Before calling any of the following TLB invalidation functions,
  727  * the calling processor must ensure that all stores updating a non-
  728  * kernel page table are globally performed.  Otherwise, another
  729  * processor could cache an old, pre-update entry without being
  730  * invalidated.  This can happen one of two ways: (1) The pmap becomes
  731  * active on another processor after its pm_active field is checked by
  732  * one of the following functions but before a store updating the page
  733  * table is globally performed. (2) The pmap becomes active on another
  734  * processor before its pm_active field is checked but due to
  735  * speculative loads one of the following functions stills reads the
  736  * pmap as inactive on the other processor.
  737  * 
  738  * The kernel page table is exempt because its pm_active field is
  739  * immutable.  The kernel page table is always active on every
  740  * processor.
  741  */
  742 void
  743 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
  744 {
  745         cpuset_t other_cpus;
  746         u_int cpuid;
  747 
  748         CTR2(KTR_PMAP, "pmap_invalidate_page: pmap=%p va=0x%x",
  749             pmap, va);
  750         
  751         sched_pin();
  752         if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
  753                 invlpg(va);
  754                 smp_invlpg(va);
  755         } else {
  756                 cpuid = PCPU_GET(cpuid);
  757                 other_cpus = all_cpus;
  758                 CPU_CLR(cpuid, &other_cpus);
  759                 if (CPU_ISSET(cpuid, &pmap->pm_active))
  760                         invlpg(va);
  761                 CPU_AND(&other_cpus, &pmap->pm_active);
  762                 if (!CPU_EMPTY(&other_cpus))
  763                         smp_masked_invlpg(other_cpus, va);
  764         }
  765         sched_unpin();
  766         PT_UPDATES_FLUSH();
  767 }
  768 
  769 void
  770 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
  771 {
  772         cpuset_t other_cpus;
  773         vm_offset_t addr;
  774         u_int cpuid;
  775 
  776         CTR3(KTR_PMAP, "pmap_invalidate_page: pmap=%p eva=0x%x sva=0x%x",
  777             pmap, sva, eva);
  778 
  779         sched_pin();
  780         if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
  781                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
  782                         invlpg(addr);
  783                 smp_invlpg_range(sva, eva);
  784         } else {
  785                 cpuid = PCPU_GET(cpuid);
  786                 other_cpus = all_cpus;
  787                 CPU_CLR(cpuid, &other_cpus);
  788                 if (CPU_ISSET(cpuid, &pmap->pm_active))
  789                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
  790                                 invlpg(addr);
  791                 CPU_AND(&other_cpus, &pmap->pm_active);
  792                 if (!CPU_EMPTY(&other_cpus))
  793                         smp_masked_invlpg_range(other_cpus, sva, eva);
  794         }
  795         sched_unpin();
  796         PT_UPDATES_FLUSH();
  797 }
  798 
  799 void
  800 pmap_invalidate_all(pmap_t pmap)
  801 {
  802         cpuset_t other_cpus;
  803         u_int cpuid;
  804 
  805         CTR1(KTR_PMAP, "pmap_invalidate_page: pmap=%p", pmap);
  806 
  807         sched_pin();
  808         if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
  809                 invltlb();
  810                 smp_invltlb();
  811         } else {
  812                 cpuid = PCPU_GET(cpuid);
  813                 other_cpus = all_cpus;
  814                 CPU_CLR(cpuid, &other_cpus);
  815                 if (CPU_ISSET(cpuid, &pmap->pm_active))
  816                         invltlb();
  817                 CPU_AND(&other_cpus, &pmap->pm_active);
  818                 if (!CPU_EMPTY(&other_cpus))
  819                         smp_masked_invltlb(other_cpus);
  820         }
  821         sched_unpin();
  822 }
  823 
  824 void
  825 pmap_invalidate_cache(void)
  826 {
  827 
  828         sched_pin();
  829         wbinvd();
  830         smp_cache_flush();
  831         sched_unpin();
  832 }
  833 #else /* !SMP */
  834 /*
  835  * Normal, non-SMP, 486+ invalidation functions.
  836  * We inline these within pmap.c for speed.
  837  */
  838 PMAP_INLINE void
  839 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
  840 {
  841         CTR2(KTR_PMAP, "pmap_invalidate_page: pmap=%p va=0x%x",
  842             pmap, va);
  843 
  844         if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
  845                 invlpg(va);
  846         PT_UPDATES_FLUSH();
  847 }
  848 
  849 PMAP_INLINE void
  850 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
  851 {
  852         vm_offset_t addr;
  853 
  854         if (eva - sva > PAGE_SIZE)
  855                 CTR3(KTR_PMAP, "pmap_invalidate_range: pmap=%p sva=0x%x eva=0x%x",
  856                     pmap, sva, eva);
  857 
  858         if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
  859                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
  860                         invlpg(addr);
  861         PT_UPDATES_FLUSH();
  862 }
  863 
  864 PMAP_INLINE void
  865 pmap_invalidate_all(pmap_t pmap)
  866 {
  867 
  868         CTR1(KTR_PMAP, "pmap_invalidate_all: pmap=%p", pmap);
  869         
  870         if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
  871                 invltlb();
  872 }
  873 
  874 PMAP_INLINE void
  875 pmap_invalidate_cache(void)
  876 {
  877 
  878         wbinvd();
  879 }
  880 #endif /* !SMP */
  881 
  882 #define PMAP_CLFLUSH_THRESHOLD  (2 * 1024 * 1024)
  883 
  884 void
  885 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
  886 {
  887 
  888         KASSERT((sva & PAGE_MASK) == 0,
  889             ("pmap_invalidate_cache_range: sva not page-aligned"));
  890         KASSERT((eva & PAGE_MASK) == 0,
  891             ("pmap_invalidate_cache_range: eva not page-aligned"));
  892 
  893         if (cpu_feature & CPUID_SS)
  894                 ; /* If "Self Snoop" is supported, do nothing. */
  895         else if ((cpu_feature & CPUID_CLFSH) != 0 &&
  896             eva - sva < PMAP_CLFLUSH_THRESHOLD) {
  897 
  898                 /*
  899                  * Otherwise, do per-cache line flush.  Use the mfence
  900                  * instruction to insure that previous stores are
  901                  * included in the write-back.  The processor
  902                  * propagates flush to other processors in the cache
  903                  * coherence domain.
  904                  */
  905                 mfence();
  906                 for (; sva < eva; sva += cpu_clflush_line_size)
  907                         clflush(sva);
  908                 mfence();
  909         } else {
  910 
  911                 /*
  912                  * No targeted cache flush methods are supported by CPU,
  913                  * or the supplied range is bigger than 2MB.
  914                  * Globally invalidate cache.
  915                  */
  916                 pmap_invalidate_cache();
  917         }
  918 }
  919 
  920 void
  921 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
  922 {
  923         int i;
  924 
  925         if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
  926             (cpu_feature & CPUID_CLFSH) == 0) {
  927                 pmap_invalidate_cache();
  928         } else {
  929                 for (i = 0; i < count; i++)
  930                         pmap_flush_page(pages[i]);
  931         }
  932 }
  933 
  934 /*
  935  * Are we current address space or kernel?  N.B. We return FALSE when
  936  * a pmap's page table is in use because a kernel thread is borrowing
  937  * it.  The borrowed page table can change spontaneously, making any
  938  * dependence on its continued use subject to a race condition.
  939  */
  940 static __inline int
  941 pmap_is_current(pmap_t pmap)
  942 {
  943 
  944         return (pmap == kernel_pmap ||
  945             (pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
  946             (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
  947 }
  948 
  949 /*
  950  * If the given pmap is not the current or kernel pmap, the returned pte must
  951  * be released by passing it to pmap_pte_release().
  952  */
  953 pt_entry_t *
  954 pmap_pte(pmap_t pmap, vm_offset_t va)
  955 {
  956         pd_entry_t newpf;
  957         pd_entry_t *pde;
  958 
  959         pde = pmap_pde(pmap, va);
  960         if (*pde & PG_PS)
  961                 return (pde);
  962         if (*pde != 0) {
  963                 /* are we current address space or kernel? */
  964                 if (pmap_is_current(pmap))
  965                         return (vtopte(va));
  966                 mtx_lock(&PMAP2mutex);
  967                 newpf = *pde & PG_FRAME;
  968                 if ((*PMAP2 & PG_FRAME) != newpf) {
  969                         vm_page_lock_queues();
  970                         PT_SET_MA(PADDR2, newpf | PG_V | PG_A | PG_M);
  971                         vm_page_unlock_queues();
  972                         CTR3(KTR_PMAP, "pmap_pte: pmap=%p va=0x%x newpte=0x%08x",
  973                             pmap, va, (*PMAP2 & 0xffffffff));
  974                 }
  975                 return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
  976         }
  977         return (NULL);
  978 }
  979 
  980 /*
  981  * Releases a pte that was obtained from pmap_pte().  Be prepared for the pte
  982  * being NULL.
  983  */
  984 static __inline void
  985 pmap_pte_release(pt_entry_t *pte)
  986 {
  987 
  988         if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2) {
  989                 CTR1(KTR_PMAP, "pmap_pte_release: pte=0x%jx",
  990                     *PMAP2);
  991                 vm_page_lock_queues();
  992                 PT_SET_VA(PMAP2, 0, TRUE);
  993                 vm_page_unlock_queues();
  994                 mtx_unlock(&PMAP2mutex);
  995         }
  996 }
  997 
  998 static __inline void
  999 invlcaddr(void *caddr)
 1000 {
 1001 
 1002         invlpg((u_int)caddr);
 1003         PT_UPDATES_FLUSH();
 1004 }
 1005 
 1006 /*
 1007  * Super fast pmap_pte routine best used when scanning
 1008  * the pv lists.  This eliminates many coarse-grained
 1009  * invltlb calls.  Note that many of the pv list
 1010  * scans are across different pmaps.  It is very wasteful
 1011  * to do an entire invltlb for checking a single mapping.
 1012  *
 1013  * If the given pmap is not the current pmap, vm_page_queue_mtx
 1014  * must be held and curthread pinned to a CPU.
 1015  */
 1016 static pt_entry_t *
 1017 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
 1018 {
 1019         pd_entry_t newpf;
 1020         pd_entry_t *pde;
 1021 
 1022         pde = pmap_pde(pmap, va);
 1023         if (*pde & PG_PS)
 1024                 return (pde);
 1025         if (*pde != 0) {
 1026                 /* are we current address space or kernel? */
 1027                 if (pmap_is_current(pmap))
 1028                         return (vtopte(va));
 1029                 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1030                 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
 1031                 newpf = *pde & PG_FRAME;
 1032                 if ((*PMAP1 & PG_FRAME) != newpf) {
 1033                         PT_SET_MA(PADDR1, newpf | PG_V | PG_A | PG_M);
 1034                         CTR3(KTR_PMAP, "pmap_pte_quick: pmap=%p va=0x%x newpte=0x%08x",
 1035                             pmap, va, (u_long)*PMAP1);
 1036                         
 1037 #ifdef SMP
 1038                         PMAP1cpu = PCPU_GET(cpuid);
 1039 #endif
 1040                         PMAP1changed++;
 1041                 } else
 1042 #ifdef SMP
 1043                 if (PMAP1cpu != PCPU_GET(cpuid)) {
 1044                         PMAP1cpu = PCPU_GET(cpuid);
 1045                         invlcaddr(PADDR1);
 1046                         PMAP1changedcpu++;
 1047                 } else
 1048 #endif
 1049                         PMAP1unchanged++;
 1050                 return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
 1051         }
 1052         return (0);
 1053 }
 1054 
 1055 /*
 1056  *      Routine:        pmap_extract
 1057  *      Function:
 1058  *              Extract the physical page address associated
 1059  *              with the given map/virtual_address pair.
 1060  */
 1061 vm_paddr_t 
 1062 pmap_extract(pmap_t pmap, vm_offset_t va)
 1063 {
 1064         vm_paddr_t rtval;
 1065         pt_entry_t *pte;
 1066         pd_entry_t pde;
 1067         pt_entry_t pteval;
 1068 
 1069         rtval = 0;
 1070         PMAP_LOCK(pmap);
 1071         pde = pmap->pm_pdir[va >> PDRSHIFT];
 1072         if (pde != 0) {
 1073                 if ((pde & PG_PS) != 0) {
 1074                         rtval = xpmap_mtop(pde & PG_PS_FRAME) | (va & PDRMASK);
 1075                         PMAP_UNLOCK(pmap);
 1076                         return rtval;
 1077                 }
 1078                 pte = pmap_pte(pmap, va);
 1079                 pteval = *pte ? xpmap_mtop(*pte) : 0;
 1080                 rtval = (pteval & PG_FRAME) | (va & PAGE_MASK);
 1081                 pmap_pte_release(pte);
 1082         }
 1083         PMAP_UNLOCK(pmap);
 1084         return (rtval);
 1085 }
 1086 
 1087 /*
 1088  *      Routine:        pmap_extract_ma
 1089  *      Function:
 1090  *              Like pmap_extract, but returns machine address
 1091  */
 1092 vm_paddr_t 
 1093 pmap_extract_ma(pmap_t pmap, vm_offset_t va)
 1094 {
 1095         vm_paddr_t rtval;
 1096         pt_entry_t *pte;
 1097         pd_entry_t pde;
 1098 
 1099         rtval = 0;
 1100         PMAP_LOCK(pmap);
 1101         pde = pmap->pm_pdir[va >> PDRSHIFT];
 1102         if (pde != 0) {
 1103                 if ((pde & PG_PS) != 0) {
 1104                         rtval = (pde & ~PDRMASK) | (va & PDRMASK);
 1105                         PMAP_UNLOCK(pmap);
 1106                         return rtval;
 1107                 }
 1108                 pte = pmap_pte(pmap, va);
 1109                 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
 1110                 pmap_pte_release(pte);
 1111         }
 1112         PMAP_UNLOCK(pmap);
 1113         return (rtval);
 1114 }
 1115 
 1116 /*
 1117  *      Routine:        pmap_extract_and_hold
 1118  *      Function:
 1119  *              Atomically extract and hold the physical page
 1120  *              with the given pmap and virtual address pair
 1121  *              if that mapping permits the given protection.
 1122  */
 1123 vm_page_t
 1124 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
 1125 {
 1126         pd_entry_t pde;
 1127         pt_entry_t pte, *ptep;
 1128         vm_page_t m;
 1129         vm_paddr_t pa;
 1130 
 1131         pa = 0;
 1132         m = NULL;
 1133         PMAP_LOCK(pmap);
 1134 retry:
 1135         pde = PT_GET(pmap_pde(pmap, va));
 1136         if (pde != 0) {
 1137                 if (pde & PG_PS) {
 1138                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
 1139                                 if (vm_page_pa_tryrelock(pmap, (pde &
 1140                                     PG_PS_FRAME) | (va & PDRMASK), &pa))
 1141                                         goto retry;
 1142                                 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
 1143                                     (va & PDRMASK));
 1144                                 vm_page_hold(m);
 1145                         }
 1146                 } else {
 1147                         ptep = pmap_pte(pmap, va);
 1148                         pte = PT_GET(ptep);
 1149                         pmap_pte_release(ptep);
 1150                         if (pte != 0 &&
 1151                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
 1152                                 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
 1153                                     &pa))
 1154                                         goto retry;
 1155                                 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
 1156                                 vm_page_hold(m);
 1157                         }
 1158                 }
 1159         }
 1160         PA_UNLOCK_COND(pa);
 1161         PMAP_UNLOCK(pmap);
 1162         return (m);
 1163 }
 1164 
 1165 /***************************************************
 1166  * Low level mapping routines.....
 1167  ***************************************************/
 1168 
 1169 /*
 1170  * Add a wired page to the kva.
 1171  * Note: not SMP coherent.
 1172  *
 1173  * This function may be used before pmap_bootstrap() is called.
 1174  */
 1175 void 
 1176 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 1177 {
 1178 
 1179         PT_SET_MA(va, xpmap_ptom(pa)| PG_RW | PG_V | pgeflag);
 1180 }
 1181 
 1182 void 
 1183 pmap_kenter_ma(vm_offset_t va, vm_paddr_t ma)
 1184 {
 1185         pt_entry_t *pte;
 1186 
 1187         pte = vtopte(va);
 1188         pte_store_ma(pte, ma | PG_RW | PG_V | pgeflag);
 1189 }
 1190 
 1191 static __inline void
 1192 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
 1193 {
 1194 
 1195         PT_SET_MA(va, pa | PG_RW | PG_V | pgeflag | pmap_cache_bits(mode, 0));
 1196 }
 1197 
 1198 /*
 1199  * Remove a page from the kernel pagetables.
 1200  * Note: not SMP coherent.
 1201  *
 1202  * This function may be used before pmap_bootstrap() is called.
 1203  */
 1204 PMAP_INLINE void
 1205 pmap_kremove(vm_offset_t va)
 1206 {
 1207         pt_entry_t *pte;
 1208 
 1209         pte = vtopte(va);
 1210         PT_CLEAR_VA(pte, FALSE);
 1211 }
 1212 
 1213 /*
 1214  *      Used to map a range of physical addresses into kernel
 1215  *      virtual address space.
 1216  *
 1217  *      The value passed in '*virt' is a suggested virtual address for
 1218  *      the mapping. Architectures which can support a direct-mapped
 1219  *      physical to virtual region can return the appropriate address
 1220  *      within that region, leaving '*virt' unchanged. Other
 1221  *      architectures should map the pages starting at '*virt' and
 1222  *      update '*virt' with the first usable address after the mapped
 1223  *      region.
 1224  */
 1225 vm_offset_t
 1226 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
 1227 {
 1228         vm_offset_t va, sva;
 1229 
 1230         va = sva = *virt;
 1231         CTR4(KTR_PMAP, "pmap_map: va=0x%x start=0x%jx end=0x%jx prot=0x%x",
 1232             va, start, end, prot);
 1233         while (start < end) {
 1234                 pmap_kenter(va, start);
 1235                 va += PAGE_SIZE;
 1236                 start += PAGE_SIZE;
 1237         }
 1238         pmap_invalidate_range(kernel_pmap, sva, va);
 1239         *virt = va;
 1240         return (sva);
 1241 }
 1242 
 1243 
 1244 /*
 1245  * Add a list of wired pages to the kva
 1246  * this routine is only used for temporary
 1247  * kernel mappings that do not need to have
 1248  * page modification or references recorded.
 1249  * Note that old mappings are simply written
 1250  * over.  The page *must* be wired.
 1251  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 1252  */
 1253 void
 1254 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
 1255 {
 1256         pt_entry_t *endpte, *pte;
 1257         vm_paddr_t pa;
 1258         vm_offset_t va = sva;
 1259         int mclcount = 0;
 1260         multicall_entry_t mcl[16];
 1261         multicall_entry_t *mclp = mcl;
 1262         int error;
 1263 
 1264         CTR2(KTR_PMAP, "pmap_qenter:sva=0x%x count=%d", va, count);
 1265         pte = vtopte(sva);
 1266         endpte = pte + count;
 1267         while (pte < endpte) {
 1268                 pa = VM_PAGE_TO_MACH(*ma) | pgeflag | PG_RW | PG_V | PG_M | PG_A;
 1269 
 1270                 mclp->op = __HYPERVISOR_update_va_mapping;
 1271                 mclp->args[0] = va;
 1272                 mclp->args[1] = (uint32_t)(pa & 0xffffffff);
 1273                 mclp->args[2] = (uint32_t)(pa >> 32);
 1274                 mclp->args[3] = (*pte & PG_V) ? UVMF_INVLPG|UVMF_ALL : 0;
 1275         
 1276                 va += PAGE_SIZE;
 1277                 pte++;
 1278                 ma++;
 1279                 mclp++;
 1280                 mclcount++;
 1281                 if (mclcount == 16) {
 1282                         error = HYPERVISOR_multicall(mcl, mclcount);
 1283                         mclp = mcl;
 1284                         mclcount = 0;
 1285                         KASSERT(error == 0, ("bad multicall %d", error));
 1286                 }               
 1287         }
 1288         if (mclcount) {
 1289                 error = HYPERVISOR_multicall(mcl, mclcount);
 1290                 KASSERT(error == 0, ("bad multicall %d", error));
 1291         }
 1292         
 1293 #ifdef INVARIANTS
 1294         for (pte = vtopte(sva), mclcount = 0; mclcount < count; mclcount++, pte++)
 1295                 KASSERT(*pte, ("pte not set for va=0x%x", sva + mclcount*PAGE_SIZE));
 1296 #endif  
 1297 }
 1298 
 1299 /*
 1300  * This routine tears out page mappings from the
 1301  * kernel -- it is meant only for temporary mappings.
 1302  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 1303  */
 1304 void
 1305 pmap_qremove(vm_offset_t sva, int count)
 1306 {
 1307         vm_offset_t va;
 1308 
 1309         CTR2(KTR_PMAP, "pmap_qremove: sva=0x%x count=%d", sva, count);
 1310         va = sva;
 1311         vm_page_lock_queues();
 1312         critical_enter();
 1313         while (count-- > 0) {
 1314                 pmap_kremove(va);
 1315                 va += PAGE_SIZE;
 1316         }
 1317         PT_UPDATES_FLUSH();
 1318         pmap_invalidate_range(kernel_pmap, sva, va);
 1319         critical_exit();
 1320         vm_page_unlock_queues();
 1321 }
 1322 
 1323 /***************************************************
 1324  * Page table page management routines.....
 1325  ***************************************************/
 1326 static __inline void
 1327 pmap_free_zero_pages(vm_page_t free)
 1328 {
 1329         vm_page_t m;
 1330 
 1331         while (free != NULL) {
 1332                 m = free;
 1333                 free = m->right;
 1334                 vm_page_free_zero(m);
 1335         }
 1336 }
 1337 
 1338 /*
 1339  * This routine unholds page table pages, and if the hold count
 1340  * drops to zero, then it decrements the wire count.
 1341  */
 1342 static __inline int
 1343 pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m, vm_page_t *free)
 1344 {
 1345 
 1346         --m->wire_count;
 1347         if (m->wire_count == 0)
 1348                 return (_pmap_unwire_pte_hold(pmap, m, free));
 1349         else
 1350                 return (0);
 1351 }
 1352 
 1353 static int 
 1354 _pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m, vm_page_t *free)
 1355 {
 1356         vm_offset_t pteva;
 1357 
 1358         PT_UPDATES_FLUSH();
 1359         /*
 1360          * unmap the page table page
 1361          */
 1362         xen_pt_unpin(pmap->pm_pdir[m->pindex]);
 1363         /*
 1364          * page *might* contain residual mapping :-/  
 1365          */
 1366         PD_CLEAR_VA(pmap, m->pindex, TRUE);
 1367         pmap_zero_page(m);
 1368         --pmap->pm_stats.resident_count;
 1369 
 1370         /*
 1371          * This is a release store so that the ordinary store unmapping
 1372          * the page table page is globally performed before TLB shoot-
 1373          * down is begun.
 1374          */
 1375         atomic_subtract_rel_int(&cnt.v_wire_count, 1);
 1376 
 1377         /*
 1378          * Do an invltlb to make the invalidated mapping
 1379          * take effect immediately.
 1380          */
 1381         pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
 1382         pmap_invalidate_page(pmap, pteva);
 1383 
 1384         /* 
 1385          * Put page on a list so that it is released after
 1386          * *ALL* TLB shootdown is done
 1387          */
 1388         m->right = *free;
 1389         *free = m;
 1390 
 1391         return (1);
 1392 }
 1393 
 1394 /*
 1395  * After removing a page table entry, this routine is used to
 1396  * conditionally free the page, and manage the hold/wire counts.
 1397  */
 1398 static int
 1399 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t *free)
 1400 {
 1401         pd_entry_t ptepde;
 1402         vm_page_t mpte;
 1403 
 1404         if (va >= VM_MAXUSER_ADDRESS)
 1405                 return (0);
 1406         ptepde = PT_GET(pmap_pde(pmap, va));
 1407         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
 1408         return (pmap_unwire_pte_hold(pmap, mpte, free));
 1409 }
 1410 
 1411 /*
 1412  * Initialize the pmap for the swapper process.
 1413  */
 1414 void
 1415 pmap_pinit0(pmap_t pmap)
 1416 {
 1417 
 1418         PMAP_LOCK_INIT(pmap);
 1419         /*
 1420          * Since the page table directory is shared with the kernel pmap,
 1421          * which is already included in the list "allpmaps", this pmap does
 1422          * not need to be inserted into that list.
 1423          */
 1424         pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
 1425 #ifdef PAE
 1426         pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
 1427 #endif
 1428         CPU_ZERO(&pmap->pm_active);
 1429         PCPU_SET(curpmap, pmap);
 1430         TAILQ_INIT(&pmap->pm_pvchunk);
 1431         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 1432 }
 1433 
 1434 /*
 1435  * Initialize a preallocated and zeroed pmap structure,
 1436  * such as one in a vmspace structure.
 1437  */
 1438 int
 1439 pmap_pinit(pmap_t pmap)
 1440 {
 1441         vm_page_t m, ptdpg[NPGPTD + 1];
 1442         int npgptd = NPGPTD + 1;
 1443         int i;
 1444 
 1445 #ifdef HAMFISTED_LOCKING
 1446         mtx_lock(&createdelete_lock);
 1447 #endif
 1448 
 1449         PMAP_LOCK_INIT(pmap);
 1450 
 1451         /*
 1452          * No need to allocate page table space yet but we do need a valid
 1453          * page directory table.
 1454          */
 1455         if (pmap->pm_pdir == NULL) {
 1456                 pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
 1457                     NBPTD);
 1458                 if (pmap->pm_pdir == NULL) {
 1459                         PMAP_LOCK_DESTROY(pmap);
 1460 #ifdef HAMFISTED_LOCKING
 1461                         mtx_unlock(&createdelete_lock);
 1462 #endif
 1463                         return (0);
 1464                 }
 1465 #ifdef PAE
 1466                 pmap->pm_pdpt = (pd_entry_t *)kmem_alloc_nofault(kernel_map, 1);
 1467 #endif
 1468         }
 1469 
 1470         /*
 1471          * allocate the page directory page(s)
 1472          */
 1473         for (i = 0; i < npgptd;) {
 1474                 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
 1475                     VM_ALLOC_WIRED | VM_ALLOC_ZERO);
 1476                 if (m == NULL)
 1477                         VM_WAIT;
 1478                 else {
 1479                         ptdpg[i++] = m;
 1480                 }
 1481         }
 1482 
 1483         pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
 1484 
 1485         for (i = 0; i < NPGPTD; i++)
 1486                 if ((ptdpg[i]->flags & PG_ZERO) == 0)
 1487                         pagezero(pmap->pm_pdir + (i * NPDEPG));
 1488 
 1489         mtx_lock_spin(&allpmaps_lock);
 1490         LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
 1491         /* Copy the kernel page table directory entries. */
 1492         bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
 1493         mtx_unlock_spin(&allpmaps_lock);
 1494 
 1495 #ifdef PAE
 1496         pmap_qenter((vm_offset_t)pmap->pm_pdpt, &ptdpg[NPGPTD], 1);
 1497         if ((ptdpg[NPGPTD]->flags & PG_ZERO) == 0)
 1498                 bzero(pmap->pm_pdpt, PAGE_SIZE);
 1499         for (i = 0; i < NPGPTD; i++) {
 1500                 vm_paddr_t ma;
 1501                 
 1502                 ma = VM_PAGE_TO_MACH(ptdpg[i]);
 1503                 pmap->pm_pdpt[i] = ma | PG_V;
 1504 
 1505         }
 1506 #endif  
 1507         for (i = 0; i < NPGPTD; i++) {
 1508                 pt_entry_t *pd;
 1509                 vm_paddr_t ma;
 1510                 
 1511                 ma = VM_PAGE_TO_MACH(ptdpg[i]);
 1512                 pd = pmap->pm_pdir + (i * NPDEPG);
 1513                 PT_SET_MA(pd, *vtopte((vm_offset_t)pd) & ~(PG_M|PG_A|PG_U|PG_RW));
 1514 #if 0           
 1515                 xen_pgd_pin(ma);
 1516 #endif          
 1517         }
 1518         
 1519 #ifdef PAE      
 1520         PT_SET_MA(pmap->pm_pdpt, *vtopte((vm_offset_t)pmap->pm_pdpt) & ~PG_RW);
 1521 #endif
 1522         vm_page_lock_queues();
 1523         xen_flush_queue();
 1524         xen_pgdpt_pin(VM_PAGE_TO_MACH(ptdpg[NPGPTD]));
 1525         for (i = 0; i < NPGPTD; i++) {
 1526                 vm_paddr_t ma = VM_PAGE_TO_MACH(ptdpg[i]);
 1527                 PT_SET_VA_MA(&pmap->pm_pdir[PTDPTDI + i], ma | PG_V | PG_A, FALSE);
 1528         }
 1529         xen_flush_queue();
 1530         vm_page_unlock_queues();
 1531         CPU_ZERO(&pmap->pm_active);
 1532         TAILQ_INIT(&pmap->pm_pvchunk);
 1533         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
 1534 
 1535 #ifdef HAMFISTED_LOCKING
 1536         mtx_unlock(&createdelete_lock);
 1537 #endif
 1538         return (1);
 1539 }
 1540 
 1541 /*
 1542  * this routine is called if the page table page is not
 1543  * mapped correctly.
 1544  */
 1545 static vm_page_t
 1546 _pmap_allocpte(pmap_t pmap, u_int ptepindex, int flags)
 1547 {
 1548         vm_paddr_t ptema;
 1549         vm_page_t m;
 1550 
 1551         KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
 1552             (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
 1553             ("_pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
 1554 
 1555         /*
 1556          * Allocate a page table page.
 1557          */
 1558         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
 1559             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
 1560                 if (flags & M_WAITOK) {
 1561                         PMAP_UNLOCK(pmap);
 1562                         vm_page_unlock_queues();
 1563                         VM_WAIT;
 1564                         vm_page_lock_queues();
 1565                         PMAP_LOCK(pmap);
 1566                 }
 1567 
 1568                 /*
 1569                  * Indicate the need to retry.  While waiting, the page table
 1570                  * page may have been allocated.
 1571                  */
 1572                 return (NULL);
 1573         }
 1574         if ((m->flags & PG_ZERO) == 0)
 1575                 pmap_zero_page(m);
 1576 
 1577         /*
 1578          * Map the pagetable page into the process address space, if
 1579          * it isn't already there.
 1580          */
 1581 
 1582         pmap->pm_stats.resident_count++;
 1583 
 1584         ptema = VM_PAGE_TO_MACH(m);
 1585         xen_pt_pin(ptema);
 1586         PT_SET_VA_MA(&pmap->pm_pdir[ptepindex],
 1587                 (ptema | PG_U | PG_RW | PG_V | PG_A | PG_M), TRUE);
 1588         
 1589         KASSERT(pmap->pm_pdir[ptepindex],
 1590             ("_pmap_allocpte: ptepindex=%d did not get mapped", ptepindex));
 1591         return (m);
 1592 }
 1593 
 1594 static vm_page_t
 1595 pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags)
 1596 {
 1597         u_int ptepindex;
 1598         pd_entry_t ptema;
 1599         vm_page_t m;
 1600 
 1601         KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
 1602             (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
 1603             ("pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
 1604 
 1605         /*
 1606          * Calculate pagetable page index
 1607          */
 1608         ptepindex = va >> PDRSHIFT;
 1609 retry:
 1610         /*
 1611          * Get the page directory entry
 1612          */
 1613         ptema = pmap->pm_pdir[ptepindex];
 1614 
 1615         /*
 1616          * This supports switching from a 4MB page to a
 1617          * normal 4K page.
 1618          */
 1619         if (ptema & PG_PS) {
 1620                 /*
 1621                  * XXX 
 1622                  */
 1623                 pmap->pm_pdir[ptepindex] = 0;
 1624                 ptema = 0;
 1625                 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
 1626                 pmap_invalidate_all(kernel_pmap);
 1627         }
 1628 
 1629         /*
 1630          * If the page table page is mapped, we just increment the
 1631          * hold count, and activate it.
 1632          */
 1633         if (ptema & PG_V) {
 1634                 m = PHYS_TO_VM_PAGE(xpmap_mtop(ptema) & PG_FRAME);
 1635                 m->wire_count++;
 1636         } else {
 1637                 /*
 1638                  * Here if the pte page isn't mapped, or if it has
 1639                  * been deallocated. 
 1640                  */
 1641                 CTR3(KTR_PMAP, "pmap_allocpte: pmap=%p va=0x%08x flags=0x%x",
 1642                     pmap, va, flags);
 1643                 m = _pmap_allocpte(pmap, ptepindex, flags);
 1644                 if (m == NULL && (flags & M_WAITOK))
 1645                         goto retry;
 1646 
 1647                 KASSERT(pmap->pm_pdir[ptepindex], ("ptepindex=%d did not get mapped", ptepindex));
 1648         }
 1649         return (m);
 1650 }
 1651 
 1652 
 1653 /***************************************************
 1654 * Pmap allocation/deallocation routines.
 1655  ***************************************************/
 1656 
 1657 #ifdef SMP
 1658 /*
 1659  * Deal with a SMP shootdown of other users of the pmap that we are
 1660  * trying to dispose of.  This can be a bit hairy.
 1661  */
 1662 static cpuset_t *lazymask;
 1663 static u_int lazyptd;
 1664 static volatile u_int lazywait;
 1665 
 1666 void pmap_lazyfix_action(void);
 1667 
 1668 void
 1669 pmap_lazyfix_action(void)
 1670 {
 1671 
 1672 #ifdef COUNT_IPIS
 1673         (*ipi_lazypmap_counts[PCPU_GET(cpuid)])++;
 1674 #endif
 1675         if (rcr3() == lazyptd)
 1676                 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
 1677         CPU_CLR_ATOMIC(PCPU_GET(cpuid), lazymask);
 1678         atomic_store_rel_int(&lazywait, 1);
 1679 }
 1680 
 1681 static void
 1682 pmap_lazyfix_self(u_int cpuid)
 1683 {
 1684 
 1685         if (rcr3() == lazyptd)
 1686                 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
 1687         CPU_CLR_ATOMIC(cpuid, lazymask);
 1688 }
 1689 
 1690 
 1691 static void
 1692 pmap_lazyfix(pmap_t pmap)
 1693 {
 1694         cpuset_t mymask, mask;
 1695         u_int cpuid, spins;
 1696         int lsb;
 1697 
 1698         mask = pmap->pm_active;
 1699         while (!CPU_EMPTY(&mask)) {
 1700                 spins = 50000000;
 1701 
 1702                 /* Find least significant set bit. */
 1703                 lsb = cpusetobj_ffs(&mask);
 1704                 MPASS(lsb != 0);
 1705                 lsb--;
 1706                 CPU_SETOF(lsb, &mask);
 1707                 mtx_lock_spin(&smp_ipi_mtx);
 1708 #ifdef PAE
 1709                 lazyptd = vtophys(pmap->pm_pdpt);
 1710 #else
 1711                 lazyptd = vtophys(pmap->pm_pdir);
 1712 #endif
 1713                 cpuid = PCPU_GET(cpuid);
 1714 
 1715                 /* Use a cpuset just for having an easy check. */
 1716                 CPU_SETOF(cpuid, &mymask);
 1717                 if (!CPU_CMP(&mask, &mymask)) {
 1718                         lazymask = &pmap->pm_active;
 1719                         pmap_lazyfix_self(cpuid);
 1720                 } else {
 1721                         atomic_store_rel_int((u_int *)&lazymask,
 1722                             (u_int)&pmap->pm_active);
 1723                         atomic_store_rel_int(&lazywait, 0);
 1724                         ipi_selected(mask, IPI_LAZYPMAP);
 1725                         while (lazywait == 0) {
 1726                                 ia32_pause();
 1727                                 if (--spins == 0)
 1728                                         break;
 1729                         }
 1730                 }
 1731                 mtx_unlock_spin(&smp_ipi_mtx);
 1732                 if (spins == 0)
 1733                         printf("pmap_lazyfix: spun for 50000000\n");
 1734                 mask = pmap->pm_active;
 1735         }
 1736 }
 1737 
 1738 #else   /* SMP */
 1739 
 1740 /*
 1741  * Cleaning up on uniprocessor is easy.  For various reasons, we're
 1742  * unlikely to have to even execute this code, including the fact
 1743  * that the cleanup is deferred until the parent does a wait(2), which
 1744  * means that another userland process has run.
 1745  */
 1746 static void
 1747 pmap_lazyfix(pmap_t pmap)
 1748 {
 1749         u_int cr3;
 1750 
 1751         cr3 = vtophys(pmap->pm_pdir);
 1752         if (cr3 == rcr3()) {
 1753                 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
 1754                 CPU_CLR(PCPU_GET(cpuid), &pmap->pm_active);
 1755         }
 1756 }
 1757 #endif  /* SMP */
 1758 
 1759 /*
 1760  * Release any resources held by the given physical map.
 1761  * Called when a pmap initialized by pmap_pinit is being released.
 1762  * Should only be called if the map contains no valid mappings.
 1763  */
 1764 void
 1765 pmap_release(pmap_t pmap)
 1766 {
 1767         vm_page_t m, ptdpg[2*NPGPTD+1];
 1768         vm_paddr_t ma;
 1769         int i;
 1770 #ifdef PAE      
 1771         int npgptd = NPGPTD + 1;
 1772 #else
 1773         int npgptd = NPGPTD;
 1774 #endif
 1775 
 1776         KASSERT(pmap->pm_stats.resident_count == 0,
 1777             ("pmap_release: pmap resident count %ld != 0",
 1778             pmap->pm_stats.resident_count));
 1779         PT_UPDATES_FLUSH();
 1780 
 1781 #ifdef HAMFISTED_LOCKING
 1782         mtx_lock(&createdelete_lock);
 1783 #endif
 1784 
 1785         pmap_lazyfix(pmap);
 1786         mtx_lock_spin(&allpmaps_lock);
 1787         LIST_REMOVE(pmap, pm_list);
 1788         mtx_unlock_spin(&allpmaps_lock);
 1789 
 1790         for (i = 0; i < NPGPTD; i++)
 1791                 ptdpg[i] = PHYS_TO_VM_PAGE(vtophys(pmap->pm_pdir + (i*NPDEPG)) & PG_FRAME);
 1792         pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
 1793 #ifdef PAE
 1794         ptdpg[NPGPTD] = PHYS_TO_VM_PAGE(vtophys(pmap->pm_pdpt));
 1795 #endif  
 1796 
 1797         for (i = 0; i < npgptd; i++) {
 1798                 m = ptdpg[i];
 1799                 ma = VM_PAGE_TO_MACH(m);
 1800                 /* unpinning L1 and L2 treated the same */
 1801 #if 0
 1802                 xen_pgd_unpin(ma);
 1803 #else
 1804                 if (i == NPGPTD)
 1805                         xen_pgd_unpin(ma);
 1806 #endif
 1807 #ifdef PAE
 1808                 if (i < NPGPTD)
 1809                         KASSERT(VM_PAGE_TO_MACH(m) == (pmap->pm_pdpt[i] & PG_FRAME),
 1810                             ("pmap_release: got wrong ptd page"));
 1811 #endif
 1812                 m->wire_count--;
 1813                 atomic_subtract_int(&cnt.v_wire_count, 1);
 1814                 vm_page_free(m);
 1815         }
 1816 #ifdef PAE
 1817         pmap_qremove((vm_offset_t)pmap->pm_pdpt, 1);
 1818 #endif
 1819         PMAP_LOCK_DESTROY(pmap);
 1820 
 1821 #ifdef HAMFISTED_LOCKING
 1822         mtx_unlock(&createdelete_lock);
 1823 #endif
 1824 }
 1825 
 1826 static int
 1827 kvm_size(SYSCTL_HANDLER_ARGS)
 1828 {
 1829         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
 1830 
 1831         return (sysctl_handle_long(oidp, &ksize, 0, req));
 1832 }
 1833 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
 1834     0, 0, kvm_size, "IU", "Size of KVM");
 1835 
 1836 static int
 1837 kvm_free(SYSCTL_HANDLER_ARGS)
 1838 {
 1839         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
 1840 
 1841         return (sysctl_handle_long(oidp, &kfree, 0, req));
 1842 }
 1843 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
 1844     0, 0, kvm_free, "IU", "Amount of KVM free");
 1845 
 1846 /*
 1847  * grow the number of kernel page table entries, if needed
 1848  */
 1849 void
 1850 pmap_growkernel(vm_offset_t addr)
 1851 {
 1852         struct pmap *pmap;
 1853         vm_paddr_t ptppaddr;
 1854         vm_page_t nkpg;
 1855         pd_entry_t newpdir;
 1856 
 1857         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
 1858         if (kernel_vm_end == 0) {
 1859                 kernel_vm_end = KERNBASE;
 1860                 nkpt = 0;
 1861                 while (pdir_pde(PTD, kernel_vm_end)) {
 1862                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
 1863                         nkpt++;
 1864                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1865                                 kernel_vm_end = kernel_map->max_offset;
 1866                                 break;
 1867                         }
 1868                 }
 1869         }
 1870         addr = roundup2(addr, NBPDR);
 1871         if (addr - 1 >= kernel_map->max_offset)
 1872                 addr = kernel_map->max_offset;
 1873         while (kernel_vm_end < addr) {
 1874                 if (pdir_pde(PTD, kernel_vm_end)) {
 1875                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 1876                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1877                                 kernel_vm_end = kernel_map->max_offset;
 1878                                 break;
 1879                         }
 1880                         continue;
 1881                 }
 1882 
 1883                 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDRSHIFT,
 1884                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
 1885                     VM_ALLOC_ZERO);
 1886                 if (nkpg == NULL)
 1887                         panic("pmap_growkernel: no memory to grow kernel");
 1888 
 1889                 nkpt++;
 1890 
 1891                 if ((nkpg->flags & PG_ZERO) == 0)
 1892                         pmap_zero_page(nkpg);
 1893                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
 1894                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
 1895                 vm_page_lock_queues();
 1896                 PD_SET_VA(kernel_pmap, (kernel_vm_end >> PDRSHIFT), newpdir, TRUE);
 1897                 mtx_lock_spin(&allpmaps_lock);
 1898                 LIST_FOREACH(pmap, &allpmaps, pm_list)
 1899                         PD_SET_VA(pmap, (kernel_vm_end >> PDRSHIFT), newpdir, TRUE);
 1900 
 1901                 mtx_unlock_spin(&allpmaps_lock);
 1902                 vm_page_unlock_queues();
 1903 
 1904                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
 1905                 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1906                         kernel_vm_end = kernel_map->max_offset;
 1907                         break;
 1908                 }
 1909         }
 1910 }
 1911 
 1912 
 1913 /***************************************************
 1914  * page management routines.
 1915  ***************************************************/
 1916 
 1917 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
 1918 CTASSERT(_NPCM == 11);
 1919 CTASSERT(_NPCPV == 336);
 1920 
 1921 static __inline struct pv_chunk *
 1922 pv_to_chunk(pv_entry_t pv)
 1923 {
 1924 
 1925         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
 1926 }
 1927 
 1928 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
 1929 
 1930 #define PC_FREE0_9      0xfffffffful    /* Free values for index 0 through 9 */
 1931 #define PC_FREE10       0x0000fffful    /* Free values for index 10 */
 1932 
 1933 static const uint32_t pc_freemask[_NPCM] = {
 1934         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1935         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1936         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1937         PC_FREE0_9, PC_FREE10
 1938 };
 1939 
 1940 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
 1941         "Current number of pv entries");
 1942 
 1943 #ifdef PV_STATS
 1944 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
 1945 
 1946 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
 1947         "Current number of pv entry chunks");
 1948 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
 1949         "Current number of pv entry chunks allocated");
 1950 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
 1951         "Current number of pv entry chunks frees");
 1952 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
 1953         "Number of times tried to get a chunk page but failed.");
 1954 
 1955 static long pv_entry_frees, pv_entry_allocs;
 1956 static int pv_entry_spare;
 1957 
 1958 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
 1959         "Current number of pv entry frees");
 1960 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
 1961         "Current number of pv entry allocs");
 1962 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
 1963         "Current number of spare pv entries");
 1964 #endif
 1965 
 1966 /*
 1967  * We are in a serious low memory condition.  Resort to
 1968  * drastic measures to free some pages so we can allocate
 1969  * another pv entry chunk.
 1970  */
 1971 static vm_page_t
 1972 pmap_pv_reclaim(pmap_t locked_pmap)
 1973 {
 1974         struct pch newtail;
 1975         struct pv_chunk *pc;
 1976         pmap_t pmap;
 1977         pt_entry_t *pte, tpte;
 1978         pv_entry_t pv;
 1979         vm_offset_t va;
 1980         vm_page_t free, m, m_pc;
 1981         uint32_t inuse;
 1982         int bit, field, freed;
 1983 
 1984         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
 1985         pmap = NULL;
 1986         free = m_pc = NULL;
 1987         TAILQ_INIT(&newtail);
 1988         sched_pin();
 1989         while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
 1990             free == NULL)) {
 1991                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 1992                 if (pmap != pc->pc_pmap) {
 1993                         if (pmap != NULL) {
 1994                                 pmap_invalidate_all(pmap);
 1995                                 if (pmap != locked_pmap)
 1996                                         PMAP_UNLOCK(pmap);
 1997                         }
 1998                         pmap = pc->pc_pmap;
 1999                         /* Avoid deadlock and lock recursion. */
 2000                         if (pmap > locked_pmap)
 2001                                 PMAP_LOCK(pmap);
 2002                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
 2003                                 pmap = NULL;
 2004                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
 2005                                 continue;
 2006                         }
 2007                 }
 2008 
 2009                 /*
 2010                  * Destroy every non-wired, 4 KB page mapping in the chunk.
 2011                  */
 2012                 freed = 0;
 2013                 for (field = 0; field < _NPCM; field++) {
 2014                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
 2015                             inuse != 0; inuse &= ~(1UL << bit)) {
 2016                                 bit = bsfl(inuse);
 2017                                 pv = &pc->pc_pventry[field * 32 + bit];
 2018                                 va = pv->pv_va;
 2019                                 pte = pmap_pte_quick(pmap, va);
 2020                                 if ((*pte & PG_W) != 0)
 2021                                         continue;
 2022                                 tpte = pte_load_clear(pte);
 2023                                 if ((tpte & PG_G) != 0)
 2024                                         pmap_invalidate_page(pmap, va);
 2025                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
 2026                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 2027                                         vm_page_dirty(m);
 2028                                 if ((tpte & PG_A) != 0)
 2029                                         vm_page_aflag_set(m, PGA_REFERENCED);
 2030                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 2031                                 if (TAILQ_EMPTY(&m->md.pv_list))
 2032                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
 2033                                 pc->pc_map[field] |= 1UL << bit;
 2034                                 pmap_unuse_pt(pmap, va, &free);
 2035                                 freed++;
 2036                         }
 2037                 }
 2038                 if (freed == 0) {
 2039                         TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
 2040                         continue;
 2041                 }
 2042                 /* Every freed mapping is for a 4 KB page. */
 2043                 pmap->pm_stats.resident_count -= freed;
 2044                 PV_STAT(pv_entry_frees += freed);
 2045                 PV_STAT(pv_entry_spare += freed);
 2046                 pv_entry_count -= freed;
 2047                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2048                 for (field = 0; field < _NPCM; field++)
 2049                         if (pc->pc_map[field] != pc_freemask[field]) {
 2050                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
 2051                                     pc_list);
 2052                                 TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
 2053 
 2054                                 /*
 2055                                  * One freed pv entry in locked_pmap is
 2056                                  * sufficient.
 2057                                  */
 2058                                 if (pmap == locked_pmap)
 2059                                         goto out;
 2060                                 break;
 2061                         }
 2062                 if (field == _NPCM) {
 2063                         PV_STAT(pv_entry_spare -= _NPCPV);
 2064                         PV_STAT(pc_chunk_count--);
 2065                         PV_STAT(pc_chunk_frees++);
 2066                         /* Entire chunk is free; return it. */
 2067                         m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
 2068                         pmap_qremove((vm_offset_t)pc, 1);
 2069                         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
 2070                         break;
 2071                 }
 2072         }
 2073 out:
 2074         sched_unpin();
 2075         TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
 2076         if (pmap != NULL) {
 2077                 pmap_invalidate_all(pmap);
 2078                 if (pmap != locked_pmap)
 2079                         PMAP_UNLOCK(pmap);
 2080         }
 2081         if (m_pc == NULL && pv_vafree != 0 && free != NULL) {
 2082                 m_pc = free;
 2083                 free = m_pc->right;
 2084                 /* Recycle a freed page table page. */
 2085                 m_pc->wire_count = 1;
 2086                 atomic_add_int(&cnt.v_wire_count, 1);
 2087         }
 2088         pmap_free_zero_pages(free);
 2089         return (m_pc);
 2090 }
 2091 
 2092 /*
 2093  * free the pv_entry back to the free list
 2094  */
 2095 static void
 2096 free_pv_entry(pmap_t pmap, pv_entry_t pv)
 2097 {
 2098         struct pv_chunk *pc;
 2099         int idx, field, bit;
 2100 
 2101         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2102         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2103         PV_STAT(pv_entry_frees++);
 2104         PV_STAT(pv_entry_spare++);
 2105         pv_entry_count--;
 2106         pc = pv_to_chunk(pv);
 2107         idx = pv - &pc->pc_pventry[0];
 2108         field = idx / 32;
 2109         bit = idx % 32;
 2110         pc->pc_map[field] |= 1ul << bit;
 2111         for (idx = 0; idx < _NPCM; idx++)
 2112                 if (pc->pc_map[idx] != pc_freemask[idx]) {
 2113                         /*
 2114                          * 98% of the time, pc is already at the head of the
 2115                          * list.  If it isn't already, move it to the head.
 2116                          */
 2117                         if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
 2118                             pc)) {
 2119                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2120                                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
 2121                                     pc_list);
 2122                         }
 2123                         return;
 2124                 }
 2125         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2126         free_pv_chunk(pc);
 2127 }
 2128 
 2129 static void
 2130 free_pv_chunk(struct pv_chunk *pc)
 2131 {
 2132         vm_page_t m;
 2133 
 2134         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
 2135         PV_STAT(pv_entry_spare -= _NPCPV);
 2136         PV_STAT(pc_chunk_count--);
 2137         PV_STAT(pc_chunk_frees++);
 2138         /* entire chunk is free, return it */
 2139         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
 2140         pmap_qremove((vm_offset_t)pc, 1);
 2141         vm_page_unwire(m, 0);
 2142         vm_page_free(m);
 2143         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
 2144 }
 2145 
 2146 /*
 2147  * get a new pv_entry, allocating a block from the system
 2148  * when needed.
 2149  */
 2150 static pv_entry_t
 2151 get_pv_entry(pmap_t pmap, boolean_t try)
 2152 {
 2153         static const struct timeval printinterval = { 60, 0 };
 2154         static struct timeval lastprint;
 2155         int bit, field;
 2156         pv_entry_t pv;
 2157         struct pv_chunk *pc;
 2158         vm_page_t m;
 2159 
 2160         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2161         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2162         PV_STAT(pv_entry_allocs++);
 2163         pv_entry_count++;
 2164         if (pv_entry_count > pv_entry_high_water)
 2165                 if (ratecheck(&lastprint, &printinterval))
 2166                         printf("Approaching the limit on PV entries, consider "
 2167                             "increasing either the vm.pmap.shpgperproc or the "
 2168                             "vm.pmap.pv_entry_max tunable.\n");
 2169 retry:
 2170         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 2171         if (pc != NULL) {
 2172                 for (field = 0; field < _NPCM; field++) {
 2173                         if (pc->pc_map[field]) {
 2174                                 bit = bsfl(pc->pc_map[field]);
 2175                                 break;
 2176                         }
 2177                 }
 2178                 if (field < _NPCM) {
 2179                         pv = &pc->pc_pventry[field * 32 + bit];
 2180                         pc->pc_map[field] &= ~(1ul << bit);
 2181                         /* If this was the last item, move it to tail */
 2182                         for (field = 0; field < _NPCM; field++)
 2183                                 if (pc->pc_map[field] != 0) {
 2184                                         PV_STAT(pv_entry_spare--);
 2185                                         return (pv);    /* not full, return */
 2186                                 }
 2187                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2188                         TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 2189                         PV_STAT(pv_entry_spare--);
 2190                         return (pv);
 2191                 }
 2192         }
 2193         /*
 2194          * Access to the ptelist "pv_vafree" is synchronized by the page
 2195          * queues lock.  If "pv_vafree" is currently non-empty, it will
 2196          * remain non-empty until pmap_ptelist_alloc() completes.
 2197          */
 2198         if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
 2199             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
 2200                 if (try) {
 2201                         pv_entry_count--;
 2202                         PV_STAT(pc_chunk_tryfail++);
 2203                         return (NULL);
 2204                 }
 2205                 m = pmap_pv_reclaim(pmap);
 2206                 if (m == NULL)
 2207                         goto retry;
 2208         }
 2209         PV_STAT(pc_chunk_count++);
 2210         PV_STAT(pc_chunk_allocs++);
 2211         pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
 2212         pmap_qenter((vm_offset_t)pc, &m, 1);
 2213         if ((m->flags & PG_ZERO) == 0)
 2214                 pagezero(pc);
 2215         pc->pc_pmap = pmap;
 2216         pc->pc_map[0] = pc_freemask[0] & ~1ul;  /* preallocated bit 0 */
 2217         for (field = 1; field < _NPCM; field++)
 2218                 pc->pc_map[field] = pc_freemask[field];
 2219         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
 2220         pv = &pc->pc_pventry[0];
 2221         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 2222         PV_STAT(pv_entry_spare += _NPCPV - 1);
 2223         return (pv);
 2224 }
 2225 
 2226 static __inline pv_entry_t
 2227 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 2228 {
 2229         pv_entry_t pv;
 2230 
 2231         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2232         TAILQ_FOREACH(pv, &pvh->pv_list, pv_list) {
 2233                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
 2234                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_list);
 2235                         break;
 2236                 }
 2237         }
 2238         return (pv);
 2239 }
 2240 
 2241 static void
 2242 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
 2243 {
 2244         pv_entry_t pv;
 2245 
 2246         pv = pmap_pvh_remove(pvh, pmap, va);
 2247         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
 2248         free_pv_entry(pmap, pv);
 2249 }
 2250 
 2251 static void
 2252 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
 2253 {
 2254 
 2255         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2256         pmap_pvh_free(&m->md, pmap, va);
 2257         if (TAILQ_EMPTY(&m->md.pv_list))
 2258                 vm_page_aflag_clear(m, PGA_WRITEABLE);
 2259 }
 2260 
 2261 /*
 2262  * Conditionally create a pv entry.
 2263  */
 2264 static boolean_t
 2265 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
 2266 {
 2267         pv_entry_t pv;
 2268 
 2269         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2270         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2271         if (pv_entry_count < pv_entry_high_water && 
 2272             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
 2273                 pv->pv_va = va;
 2274                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 2275                 return (TRUE);
 2276         } else
 2277                 return (FALSE);
 2278 }
 2279 
 2280 /*
 2281  * pmap_remove_pte: do the things to unmap a page in a process
 2282  */
 2283 static int
 2284 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, vm_page_t *free)
 2285 {
 2286         pt_entry_t oldpte;
 2287         vm_page_t m;
 2288 
 2289         CTR3(KTR_PMAP, "pmap_remove_pte: pmap=%p *ptq=0x%x va=0x%x",
 2290             pmap, (u_long)*ptq, va);
 2291         
 2292         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2293         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2294         oldpte = *ptq;
 2295         PT_SET_VA_MA(ptq, 0, TRUE);
 2296         if (oldpte & PG_W)
 2297                 pmap->pm_stats.wired_count -= 1;
 2298         /*
 2299          * Machines that don't support invlpg, also don't support
 2300          * PG_G.
 2301          */
 2302         if (oldpte & PG_G)
 2303                 pmap_invalidate_page(kernel_pmap, va);
 2304         pmap->pm_stats.resident_count -= 1;
 2305         if (oldpte & PG_MANAGED) {
 2306                 m = PHYS_TO_VM_PAGE(xpmap_mtop(oldpte) & PG_FRAME);
 2307                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 2308                         vm_page_dirty(m);
 2309                 if (oldpte & PG_A)
 2310                         vm_page_aflag_set(m, PGA_REFERENCED);
 2311                 pmap_remove_entry(pmap, m, va);
 2312         }
 2313         return (pmap_unuse_pt(pmap, va, free));
 2314 }
 2315 
 2316 /*
 2317  * Remove a single page from a process address space
 2318  */
 2319 static void
 2320 pmap_remove_page(pmap_t pmap, vm_offset_t va, vm_page_t *free)
 2321 {
 2322         pt_entry_t *pte;
 2323 
 2324         CTR2(KTR_PMAP, "pmap_remove_page: pmap=%p va=0x%x",
 2325             pmap, va);
 2326         
 2327         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2328         KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
 2329         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2330         if ((pte = pmap_pte_quick(pmap, va)) == NULL || (*pte & PG_V) == 0)
 2331                 return;
 2332         pmap_remove_pte(pmap, pte, va, free);
 2333         pmap_invalidate_page(pmap, va);
 2334         if (*PMAP1)
 2335                 PT_SET_MA(PADDR1, 0);
 2336 
 2337 }
 2338 
 2339 /*
 2340  *      Remove the given range of addresses from the specified map.
 2341  *
 2342  *      It is assumed that the start and end are properly
 2343  *      rounded to the page size.
 2344  */
 2345 void
 2346 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2347 {
 2348         vm_offset_t pdnxt;
 2349         pd_entry_t ptpaddr;
 2350         pt_entry_t *pte;
 2351         vm_page_t free = NULL;
 2352         int anyvalid;
 2353 
 2354         CTR3(KTR_PMAP, "pmap_remove: pmap=%p sva=0x%x eva=0x%x",
 2355             pmap, sva, eva);
 2356 
 2357         /*
 2358          * Perform an unsynchronized read.  This is, however, safe.
 2359          */
 2360         if (pmap->pm_stats.resident_count == 0)
 2361                 return;
 2362 
 2363         anyvalid = 0;
 2364 
 2365         vm_page_lock_queues();
 2366         sched_pin();
 2367         PMAP_LOCK(pmap);
 2368 
 2369         /*
 2370          * special handling of removing one page.  a very
 2371          * common operation and easy to short circuit some
 2372          * code.
 2373          */
 2374         if ((sva + PAGE_SIZE == eva) && 
 2375             ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
 2376                 pmap_remove_page(pmap, sva, &free);
 2377                 goto out;
 2378         }
 2379 
 2380         for (; sva < eva; sva = pdnxt) {
 2381                 u_int pdirindex;
 2382 
 2383                 /*
 2384                  * Calculate index for next page table.
 2385                  */
 2386                 pdnxt = (sva + NBPDR) & ~PDRMASK;
 2387                 if (pdnxt < sva)
 2388                         pdnxt = eva;
 2389                 if (pmap->pm_stats.resident_count == 0)
 2390                         break;
 2391 
 2392                 pdirindex = sva >> PDRSHIFT;
 2393                 ptpaddr = pmap->pm_pdir[pdirindex];
 2394 
 2395                 /*
 2396                  * Weed out invalid mappings. Note: we assume that the page
 2397                  * directory table is always allocated, and in kernel virtual.
 2398                  */
 2399                 if (ptpaddr == 0)
 2400                         continue;
 2401 
 2402                 /*
 2403                  * Check for large page.
 2404                  */
 2405                 if ((ptpaddr & PG_PS) != 0) {
 2406                         PD_CLEAR_VA(pmap, pdirindex, TRUE);
 2407                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
 2408                         anyvalid = 1;
 2409                         continue;
 2410                 }
 2411 
 2412                 /*
 2413                  * Limit our scan to either the end of the va represented
 2414                  * by the current page table page, or to the end of the
 2415                  * range being removed.
 2416                  */
 2417                 if (pdnxt > eva)
 2418                         pdnxt = eva;
 2419 
 2420                 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
 2421                     sva += PAGE_SIZE) {
 2422                         if ((*pte & PG_V) == 0)
 2423                                 continue;
 2424 
 2425                         /*
 2426                          * The TLB entry for a PG_G mapping is invalidated
 2427                          * by pmap_remove_pte().
 2428                          */
 2429                         if ((*pte & PG_G) == 0)
 2430                                 anyvalid = 1;
 2431                         if (pmap_remove_pte(pmap, pte, sva, &free))
 2432                                 break;
 2433                 }
 2434         }
 2435         PT_UPDATES_FLUSH();
 2436         if (*PMAP1)
 2437                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2438 out:
 2439         if (anyvalid)
 2440                 pmap_invalidate_all(pmap);
 2441         sched_unpin();
 2442         vm_page_unlock_queues();
 2443         PMAP_UNLOCK(pmap);
 2444         pmap_free_zero_pages(free);
 2445 }
 2446 
 2447 /*
 2448  *      Routine:        pmap_remove_all
 2449  *      Function:
 2450  *              Removes this physical page from
 2451  *              all physical maps in which it resides.
 2452  *              Reflects back modify bits to the pager.
 2453  *
 2454  *      Notes:
 2455  *              Original versions of this routine were very
 2456  *              inefficient because they iteratively called
 2457  *              pmap_remove (slow...)
 2458  */
 2459 
 2460 void
 2461 pmap_remove_all(vm_page_t m)
 2462 {
 2463         pv_entry_t pv;
 2464         pmap_t pmap;
 2465         pt_entry_t *pte, tpte;
 2466         vm_page_t free;
 2467 
 2468         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 2469             ("pmap_remove_all: page %p is not managed", m));
 2470         free = NULL;
 2471         vm_page_lock_queues();
 2472         sched_pin();
 2473         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 2474                 pmap = PV_PMAP(pv);
 2475                 PMAP_LOCK(pmap);
 2476                 pmap->pm_stats.resident_count--;
 2477                 pte = pmap_pte_quick(pmap, pv->pv_va);
 2478                 tpte = *pte;
 2479                 PT_SET_VA_MA(pte, 0, TRUE);
 2480                 if (tpte & PG_W)
 2481                         pmap->pm_stats.wired_count--;
 2482                 if (tpte & PG_A)
 2483                         vm_page_aflag_set(m, PGA_REFERENCED);
 2484 
 2485                 /*
 2486                  * Update the vm_page_t clean and reference bits.
 2487                  */
 2488                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 2489                         vm_page_dirty(m);
 2490                 pmap_unuse_pt(pmap, pv->pv_va, &free);
 2491                 pmap_invalidate_page(pmap, pv->pv_va);
 2492                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 2493                 free_pv_entry(pmap, pv);
 2494                 PMAP_UNLOCK(pmap);
 2495         }
 2496         vm_page_aflag_clear(m, PGA_WRITEABLE);
 2497         PT_UPDATES_FLUSH();
 2498         if (*PMAP1)
 2499                 PT_SET_MA(PADDR1, 0);
 2500         sched_unpin();
 2501         vm_page_unlock_queues();
 2502         pmap_free_zero_pages(free);
 2503 }
 2504 
 2505 /*
 2506  *      Set the physical protection on the
 2507  *      specified range of this map as requested.
 2508  */
 2509 void
 2510 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
 2511 {
 2512         vm_offset_t pdnxt;
 2513         pd_entry_t ptpaddr;
 2514         pt_entry_t *pte;
 2515         int anychanged;
 2516 
 2517         CTR4(KTR_PMAP, "pmap_protect: pmap=%p sva=0x%x eva=0x%x prot=0x%x",
 2518             pmap, sva, eva, prot);
 2519         
 2520         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
 2521                 pmap_remove(pmap, sva, eva);
 2522                 return;
 2523         }
 2524 
 2525 #ifdef PAE
 2526         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
 2527             (VM_PROT_WRITE|VM_PROT_EXECUTE))
 2528                 return;
 2529 #else
 2530         if (prot & VM_PROT_WRITE)
 2531                 return;
 2532 #endif
 2533 
 2534         anychanged = 0;
 2535 
 2536         vm_page_lock_queues();
 2537         sched_pin();
 2538         PMAP_LOCK(pmap);
 2539         for (; sva < eva; sva = pdnxt) {
 2540                 pt_entry_t obits, pbits;
 2541                 u_int pdirindex;
 2542 
 2543                 pdnxt = (sva + NBPDR) & ~PDRMASK;
 2544                 if (pdnxt < sva)
 2545                         pdnxt = eva;
 2546 
 2547                 pdirindex = sva >> PDRSHIFT;
 2548                 ptpaddr = pmap->pm_pdir[pdirindex];
 2549 
 2550                 /*
 2551                  * Weed out invalid mappings. Note: we assume that the page
 2552                  * directory table is always allocated, and in kernel virtual.
 2553                  */
 2554                 if (ptpaddr == 0)
 2555                         continue;
 2556 
 2557                 /*
 2558                  * Check for large page.
 2559                  */
 2560                 if ((ptpaddr & PG_PS) != 0) {
 2561                         if ((prot & VM_PROT_WRITE) == 0)
 2562                                 pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
 2563 #ifdef PAE
 2564                         if ((prot & VM_PROT_EXECUTE) == 0)
 2565                                 pmap->pm_pdir[pdirindex] |= pg_nx;
 2566 #endif
 2567                         anychanged = 1;
 2568                         continue;
 2569                 }
 2570 
 2571                 if (pdnxt > eva)
 2572                         pdnxt = eva;
 2573 
 2574                 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
 2575                     sva += PAGE_SIZE) {
 2576                         vm_page_t m;
 2577 
 2578 retry:
 2579                         /*
 2580                          * Regardless of whether a pte is 32 or 64 bits in
 2581                          * size, PG_RW, PG_A, and PG_M are among the least
 2582                          * significant 32 bits.
 2583                          */
 2584                         obits = pbits = *pte;
 2585                         if ((pbits & PG_V) == 0)
 2586                                 continue;
 2587 
 2588                         if ((prot & VM_PROT_WRITE) == 0) {
 2589                                 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
 2590                                     (PG_MANAGED | PG_M | PG_RW)) {
 2591                                         m = PHYS_TO_VM_PAGE(xpmap_mtop(pbits) &
 2592                                             PG_FRAME);
 2593                                         vm_page_dirty(m);
 2594                                 }
 2595                                 pbits &= ~(PG_RW | PG_M);
 2596                         }
 2597 #ifdef PAE
 2598                         if ((prot & VM_PROT_EXECUTE) == 0)
 2599                                 pbits |= pg_nx;
 2600 #endif
 2601 
 2602                         if (pbits != obits) {
 2603                                 obits = *pte;
 2604                                 PT_SET_VA_MA(pte, pbits, TRUE);
 2605                                 if (*pte != pbits)
 2606                                         goto retry;
 2607                                 if (obits & PG_G)
 2608                                         pmap_invalidate_page(pmap, sva);
 2609                                 else
 2610                                         anychanged = 1;
 2611                         }
 2612                 }
 2613         }
 2614         PT_UPDATES_FLUSH();
 2615         if (*PMAP1)
 2616                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2617         if (anychanged)
 2618                 pmap_invalidate_all(pmap);
 2619         sched_unpin();
 2620         vm_page_unlock_queues();
 2621         PMAP_UNLOCK(pmap);
 2622 }
 2623 
 2624 /*
 2625  *      Insert the given physical page (p) at
 2626  *      the specified virtual address (v) in the
 2627  *      target physical map with the protection requested.
 2628  *
 2629  *      If specified, the page will be wired down, meaning
 2630  *      that the related pte can not be reclaimed.
 2631  *
 2632  *      NB:  This is the only routine which MAY NOT lazy-evaluate
 2633  *      or lose information.  That is, this routine must actually
 2634  *      insert this page into the given map NOW.
 2635  */
 2636 void
 2637 pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
 2638     vm_prot_t prot, boolean_t wired)
 2639 {
 2640         pd_entry_t *pde;
 2641         pt_entry_t *pte;
 2642         pt_entry_t newpte, origpte;
 2643         pv_entry_t pv;
 2644         vm_paddr_t opa, pa;
 2645         vm_page_t mpte, om;
 2646         boolean_t invlva;
 2647 
 2648         CTR6(KTR_PMAP, "pmap_enter: pmap=%08p va=0x%08x access=0x%x ma=0x%08x prot=0x%x wired=%d",
 2649             pmap, va, access, VM_PAGE_TO_MACH(m), prot, wired);
 2650         va = trunc_page(va);
 2651         KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
 2652         KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
 2653             ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)",
 2654             va));
 2655         KASSERT((m->oflags & (VPO_UNMANAGED | VPO_BUSY)) != 0 ||
 2656             VM_OBJECT_LOCKED(m->object),
 2657             ("pmap_enter: page %p is not busy", m));
 2658 
 2659         mpte = NULL;
 2660 
 2661         vm_page_lock_queues();
 2662         PMAP_LOCK(pmap);
 2663         sched_pin();
 2664 
 2665         /*
 2666          * In the case that a page table page is not
 2667          * resident, we are creating it here.
 2668          */
 2669         if (va < VM_MAXUSER_ADDRESS) {
 2670                 mpte = pmap_allocpte(pmap, va, M_WAITOK);
 2671         }
 2672 
 2673         pde = pmap_pde(pmap, va);
 2674         if ((*pde & PG_PS) != 0)
 2675                 panic("pmap_enter: attempted pmap_enter on 4MB page");
 2676         pte = pmap_pte_quick(pmap, va);
 2677 
 2678         /*
 2679          * Page Directory table entry not valid, we need a new PT page
 2680          */
 2681         if (pte == NULL) {
 2682                 panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x",
 2683                         (uintmax_t)pmap->pm_pdir[va >> PDRSHIFT], va);
 2684         }
 2685 
 2686         pa = VM_PAGE_TO_PHYS(m);
 2687         om = NULL;
 2688         opa = origpte = 0;
 2689 
 2690 #if 0
 2691         KASSERT((*pte & PG_V) || (*pte == 0), ("address set but not valid pte=%p *pte=0x%016jx",
 2692                 pte, *pte));
 2693 #endif
 2694         origpte = *pte;
 2695         if (origpte)
 2696                 origpte = xpmap_mtop(origpte);
 2697         opa = origpte & PG_FRAME;
 2698 
 2699         /*
 2700          * Mapping has not changed, must be protection or wiring change.
 2701          */
 2702         if (origpte && (opa == pa)) {
 2703                 /*
 2704                  * Wiring change, just update stats. We don't worry about
 2705                  * wiring PT pages as they remain resident as long as there
 2706                  * are valid mappings in them. Hence, if a user page is wired,
 2707                  * the PT page will be also.
 2708                  */
 2709                 if (wired && ((origpte & PG_W) == 0))
 2710                         pmap->pm_stats.wired_count++;
 2711                 else if (!wired && (origpte & PG_W))
 2712                         pmap->pm_stats.wired_count--;
 2713 
 2714                 /*
 2715                  * Remove extra pte reference
 2716                  */
 2717                 if (mpte)
 2718                         mpte->wire_count--;
 2719 
 2720                 if (origpte & PG_MANAGED) {
 2721                         om = m;
 2722                         pa |= PG_MANAGED;
 2723                 }
 2724                 goto validate;
 2725         } 
 2726 
 2727         pv = NULL;
 2728 
 2729         /*
 2730          * Mapping has changed, invalidate old range and fall through to
 2731          * handle validating new mapping.
 2732          */
 2733         if (opa) {
 2734                 if (origpte & PG_W)
 2735                         pmap->pm_stats.wired_count--;
 2736                 if (origpte & PG_MANAGED) {
 2737                         om = PHYS_TO_VM_PAGE(opa);
 2738                         pv = pmap_pvh_remove(&om->md, pmap, va);
 2739                 } else if (va < VM_MAXUSER_ADDRESS) 
 2740                         printf("va=0x%x is unmanaged :-( \n", va);
 2741                         
 2742                 if (mpte != NULL) {
 2743                         mpte->wire_count--;
 2744                         KASSERT(mpte->wire_count > 0,
 2745                             ("pmap_enter: missing reference to page table page,"
 2746                              " va: 0x%x", va));
 2747                 }
 2748         } else
 2749                 pmap->pm_stats.resident_count++;
 2750 
 2751         /*
 2752          * Enter on the PV list if part of our managed memory.
 2753          */
 2754         if ((m->oflags & VPO_UNMANAGED) == 0) {
 2755                 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
 2756                     ("pmap_enter: managed mapping within the clean submap"));
 2757                 if (pv == NULL)
 2758                         pv = get_pv_entry(pmap, FALSE);
 2759                 pv->pv_va = va;
 2760                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 2761                 pa |= PG_MANAGED;
 2762         } else if (pv != NULL)
 2763                 free_pv_entry(pmap, pv);
 2764 
 2765         /*
 2766          * Increment counters
 2767          */
 2768         if (wired)
 2769                 pmap->pm_stats.wired_count++;
 2770 
 2771 validate:
 2772         /*
 2773          * Now validate mapping with desired protection/wiring.
 2774          */
 2775         newpte = (pt_entry_t)(pa | PG_V);
 2776         if ((prot & VM_PROT_WRITE) != 0) {
 2777                 newpte |= PG_RW;
 2778                 if ((newpte & PG_MANAGED) != 0)
 2779                         vm_page_aflag_set(m, PGA_WRITEABLE);
 2780         }
 2781 #ifdef PAE
 2782         if ((prot & VM_PROT_EXECUTE) == 0)
 2783                 newpte |= pg_nx;
 2784 #endif
 2785         if (wired)
 2786                 newpte |= PG_W;
 2787         if (va < VM_MAXUSER_ADDRESS)
 2788                 newpte |= PG_U;
 2789         if (pmap == kernel_pmap)
 2790                 newpte |= pgeflag;
 2791 
 2792         critical_enter();
 2793         /*
 2794          * if the mapping or permission bits are different, we need
 2795          * to update the pte.
 2796          */
 2797         if ((origpte & ~(PG_M|PG_A)) != newpte) {
 2798                 if (origpte) {
 2799                         invlva = FALSE;
 2800                         origpte = *pte;
 2801                         PT_SET_VA(pte, newpte | PG_A, FALSE);
 2802                         if (origpte & PG_A) {
 2803                                 if (origpte & PG_MANAGED)
 2804                                         vm_page_aflag_set(om, PGA_REFERENCED);
 2805                                 if (opa != VM_PAGE_TO_PHYS(m))
 2806                                         invlva = TRUE;
 2807 #ifdef PAE
 2808                                 if ((origpte & PG_NX) == 0 &&
 2809                                     (newpte & PG_NX) != 0)
 2810                                         invlva = TRUE;
 2811 #endif
 2812                         }
 2813                         if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
 2814                                 if ((origpte & PG_MANAGED) != 0)
 2815                                         vm_page_dirty(om);
 2816                                 if ((prot & VM_PROT_WRITE) == 0)
 2817                                         invlva = TRUE;
 2818                         }
 2819                         if ((origpte & PG_MANAGED) != 0 &&
 2820                             TAILQ_EMPTY(&om->md.pv_list))
 2821                                 vm_page_aflag_clear(om, PGA_WRITEABLE);
 2822                         if (invlva)
 2823                                 pmap_invalidate_page(pmap, va);
 2824                 } else{
 2825                         PT_SET_VA(pte, newpte | PG_A, FALSE);
 2826                 }
 2827                 
 2828         }
 2829         PT_UPDATES_FLUSH();
 2830         critical_exit();
 2831         if (*PMAP1)
 2832                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2833         sched_unpin();
 2834         vm_page_unlock_queues();
 2835         PMAP_UNLOCK(pmap);
 2836 }
 2837 
 2838 /*
 2839  * Maps a sequence of resident pages belonging to the same object.
 2840  * The sequence begins with the given page m_start.  This page is
 2841  * mapped at the given virtual address start.  Each subsequent page is
 2842  * mapped at a virtual address that is offset from start by the same
 2843  * amount as the page is offset from m_start within the object.  The
 2844  * last page in the sequence is the page with the largest offset from
 2845  * m_start that can be mapped at a virtual address less than the given
 2846  * virtual address end.  Not every virtual page between start and end
 2847  * is mapped; only those for which a resident page exists with the
 2848  * corresponding offset from m_start are mapped.
 2849  */
 2850 void
 2851 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
 2852     vm_page_t m_start, vm_prot_t prot)
 2853 {
 2854         vm_page_t m, mpte;
 2855         vm_pindex_t diff, psize;
 2856         multicall_entry_t mcl[16];
 2857         multicall_entry_t *mclp = mcl;
 2858         int error, count = 0;
 2859 
 2860         VM_OBJECT_LOCK_ASSERT(m_start->object, MA_OWNED);
 2861         psize = atop(end - start);
 2862         mpte = NULL;
 2863         m = m_start;
 2864         vm_page_lock_queues();
 2865         PMAP_LOCK(pmap);
 2866         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
 2867                 mpte = pmap_enter_quick_locked(&mclp, &count, pmap, start + ptoa(diff), m,
 2868                     prot, mpte);
 2869                 m = TAILQ_NEXT(m, listq);
 2870                 if (count == 16) {
 2871                         error = HYPERVISOR_multicall(mcl, count);
 2872                         KASSERT(error == 0, ("bad multicall %d", error));
 2873                         mclp = mcl;
 2874                         count = 0;
 2875                 }
 2876         }
 2877         if (count) {
 2878                 error = HYPERVISOR_multicall(mcl, count);
 2879                 KASSERT(error == 0, ("bad multicall %d", error));
 2880         }
 2881         vm_page_unlock_queues();
 2882         PMAP_UNLOCK(pmap);
 2883 }
 2884 
 2885 /*
 2886  * this code makes some *MAJOR* assumptions:
 2887  * 1. Current pmap & pmap exists.
 2888  * 2. Not wired.
 2889  * 3. Read access.
 2890  * 4. No page table pages.
 2891  * but is *MUCH* faster than pmap_enter...
 2892  */
 2893 
 2894 void
 2895 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
 2896 {
 2897         multicall_entry_t mcl, *mclp;
 2898         int count = 0;
 2899         mclp = &mcl;
 2900 
 2901         CTR4(KTR_PMAP, "pmap_enter_quick: pmap=%p va=0x%x m=%p prot=0x%x",
 2902             pmap, va, m, prot);
 2903         
 2904         vm_page_lock_queues();
 2905         PMAP_LOCK(pmap);
 2906         (void)pmap_enter_quick_locked(&mclp, &count, pmap, va, m, prot, NULL);
 2907         if (count)
 2908                 HYPERVISOR_multicall(&mcl, count);
 2909         vm_page_unlock_queues();
 2910         PMAP_UNLOCK(pmap);
 2911 }
 2912 
 2913 #ifdef notyet
 2914 void
 2915 pmap_enter_quick_range(pmap_t pmap, vm_offset_t *addrs, vm_page_t *pages, vm_prot_t *prots, int count)
 2916 {
 2917         int i, error, index = 0;
 2918         multicall_entry_t mcl[16];
 2919         multicall_entry_t *mclp = mcl;
 2920                 
 2921         PMAP_LOCK(pmap);
 2922         for (i = 0; i < count; i++, addrs++, pages++, prots++) {
 2923                 if (!pmap_is_prefaultable_locked(pmap, *addrs))
 2924                         continue;
 2925 
 2926                 (void) pmap_enter_quick_locked(&mclp, &index, pmap, *addrs, *pages, *prots, NULL);
 2927                 if (index == 16) {
 2928                         error = HYPERVISOR_multicall(mcl, index);
 2929                         mclp = mcl;
 2930                         index = 0;
 2931                         KASSERT(error == 0, ("bad multicall %d", error));
 2932                 }
 2933         }
 2934         if (index) {
 2935                 error = HYPERVISOR_multicall(mcl, index);
 2936                 KASSERT(error == 0, ("bad multicall %d", error));
 2937         }
 2938         
 2939         PMAP_UNLOCK(pmap);
 2940 }
 2941 #endif
 2942 
 2943 static vm_page_t
 2944 pmap_enter_quick_locked(multicall_entry_t **mclpp, int *count, pmap_t pmap, vm_offset_t va, vm_page_t m,
 2945     vm_prot_t prot, vm_page_t mpte)
 2946 {
 2947         pt_entry_t *pte;
 2948         vm_paddr_t pa;
 2949         vm_page_t free;
 2950         multicall_entry_t *mcl = *mclpp;
 2951 
 2952         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
 2953             (m->oflags & VPO_UNMANAGED) != 0,
 2954             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
 2955         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2956         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2957 
 2958         /*
 2959          * In the case that a page table page is not
 2960          * resident, we are creating it here.
 2961          */
 2962         if (va < VM_MAXUSER_ADDRESS) {
 2963                 u_int ptepindex;
 2964                 pd_entry_t ptema;
 2965 
 2966                 /*
 2967                  * Calculate pagetable page index
 2968                  */
 2969                 ptepindex = va >> PDRSHIFT;
 2970                 if (mpte && (mpte->pindex == ptepindex)) {
 2971                         mpte->wire_count++;
 2972                 } else {
 2973                         /*
 2974                          * Get the page directory entry
 2975                          */
 2976                         ptema = pmap->pm_pdir[ptepindex];
 2977 
 2978                         /*
 2979                          * If the page table page is mapped, we just increment
 2980                          * the hold count, and activate it.
 2981                          */
 2982                         if (ptema & PG_V) {
 2983                                 if (ptema & PG_PS)
 2984                                         panic("pmap_enter_quick: unexpected mapping into 4MB page");
 2985                                 mpte = PHYS_TO_VM_PAGE(xpmap_mtop(ptema) & PG_FRAME);
 2986                                 mpte->wire_count++;
 2987                         } else {
 2988                                 mpte = _pmap_allocpte(pmap, ptepindex,
 2989                                     M_NOWAIT);
 2990                                 if (mpte == NULL)
 2991                                         return (mpte);
 2992                         }
 2993                 }
 2994         } else {
 2995                 mpte = NULL;
 2996         }
 2997 
 2998         /*
 2999          * This call to vtopte makes the assumption that we are
 3000          * entering the page into the current pmap.  In order to support
 3001          * quick entry into any pmap, one would likely use pmap_pte_quick.
 3002          * But that isn't as quick as vtopte.
 3003          */
 3004         KASSERT(pmap_is_current(pmap), ("entering pages in non-current pmap"));
 3005         pte = vtopte(va);
 3006         if (*pte & PG_V) {
 3007                 if (mpte != NULL) {
 3008                         mpte->wire_count--;
 3009                         mpte = NULL;
 3010                 }
 3011                 return (mpte);
 3012         }
 3013 
 3014         /*
 3015          * Enter on the PV list if part of our managed memory.
 3016          */
 3017         if ((m->oflags & VPO_UNMANAGED) == 0 &&
 3018             !pmap_try_insert_pv_entry(pmap, va, m)) {
 3019                 if (mpte != NULL) {
 3020                         free = NULL;
 3021                         if (pmap_unwire_pte_hold(pmap, mpte, &free)) {
 3022                                 pmap_invalidate_page(pmap, va);
 3023                                 pmap_free_zero_pages(free);
 3024                         }
 3025                         
 3026                         mpte = NULL;
 3027                 }
 3028                 return (mpte);
 3029         }
 3030 
 3031         /*
 3032          * Increment counters
 3033          */
 3034         pmap->pm_stats.resident_count++;
 3035 
 3036         pa = VM_PAGE_TO_PHYS(m);
 3037 #ifdef PAE
 3038         if ((prot & VM_PROT_EXECUTE) == 0)
 3039                 pa |= pg_nx;
 3040 #endif
 3041 
 3042 #if 0
 3043         /*
 3044          * Now validate mapping with RO protection
 3045          */
 3046         if ((m->oflags & VPO_UNMANAGED) != 0)
 3047                 pte_store(pte, pa | PG_V | PG_U);
 3048         else
 3049                 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
 3050 #else
 3051         /*
 3052          * Now validate mapping with RO protection
 3053          */
 3054         if ((m->oflags & VPO_UNMANAGED) != 0)
 3055                 pa =    xpmap_ptom(pa | PG_V | PG_U);
 3056         else
 3057                 pa = xpmap_ptom(pa | PG_V | PG_U | PG_MANAGED);
 3058 
 3059         mcl->op = __HYPERVISOR_update_va_mapping;
 3060         mcl->args[0] = va;
 3061         mcl->args[1] = (uint32_t)(pa & 0xffffffff);
 3062         mcl->args[2] = (uint32_t)(pa >> 32);
 3063         mcl->args[3] = 0;
 3064         *mclpp = mcl + 1;
 3065         *count = *count + 1;
 3066 #endif  
 3067         return (mpte);
 3068 }
 3069 
 3070 /*
 3071  * Make a temporary mapping for a physical address.  This is only intended
 3072  * to be used for panic dumps.
 3073  */
 3074 void *
 3075 pmap_kenter_temporary(vm_paddr_t pa, int i)
 3076 {
 3077         vm_offset_t va;
 3078         vm_paddr_t ma = xpmap_ptom(pa);
 3079 
 3080         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
 3081         PT_SET_MA(va, (ma & ~PAGE_MASK) | PG_V | pgeflag);
 3082         invlpg(va);
 3083         return ((void *)crashdumpmap);
 3084 }
 3085 
 3086 /*
 3087  * This code maps large physical mmap regions into the
 3088  * processor address space.  Note that some shortcuts
 3089  * are taken, but the code works.
 3090  */
 3091 void
 3092 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
 3093     vm_pindex_t pindex, vm_size_t size)
 3094 {
 3095         pd_entry_t *pde;
 3096         vm_paddr_t pa, ptepa;
 3097         vm_page_t p;
 3098         int pat_mode;
 3099 
 3100         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 3101         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
 3102             ("pmap_object_init_pt: non-device object"));
 3103         if (pseflag && 
 3104             (addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
 3105                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
 3106                         return;
 3107                 p = vm_page_lookup(object, pindex);
 3108                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
 3109                     ("pmap_object_init_pt: invalid page %p", p));
 3110                 pat_mode = p->md.pat_mode;
 3111 
 3112                 /*
 3113                  * Abort the mapping if the first page is not physically
 3114                  * aligned to a 2/4MB page boundary.
 3115                  */
 3116                 ptepa = VM_PAGE_TO_PHYS(p);
 3117                 if (ptepa & (NBPDR - 1))
 3118                         return;
 3119 
 3120                 /*
 3121                  * Skip the first page.  Abort the mapping if the rest of
 3122                  * the pages are not physically contiguous or have differing
 3123                  * memory attributes.
 3124                  */
 3125                 p = TAILQ_NEXT(p, listq);
 3126                 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
 3127                     pa += PAGE_SIZE) {
 3128                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
 3129                             ("pmap_object_init_pt: invalid page %p", p));
 3130                         if (pa != VM_PAGE_TO_PHYS(p) ||
 3131                             pat_mode != p->md.pat_mode)
 3132                                 return;
 3133                         p = TAILQ_NEXT(p, listq);
 3134                 }
 3135 
 3136                 /*
 3137                  * Map using 2/4MB pages.  Since "ptepa" is 2/4M aligned and
 3138                  * "size" is a multiple of 2/4M, adding the PAT setting to
 3139                  * "pa" will not affect the termination of this loop.
 3140                  */
 3141                 PMAP_LOCK(pmap);
 3142                 for (pa = ptepa | pmap_cache_bits(pat_mode, 1); pa < ptepa +
 3143                     size; pa += NBPDR) {
 3144                         pde = pmap_pde(pmap, addr);
 3145                         if (*pde == 0) {
 3146                                 pde_store(pde, pa | PG_PS | PG_M | PG_A |
 3147                                     PG_U | PG_RW | PG_V);
 3148                                 pmap->pm_stats.resident_count += NBPDR /
 3149                                     PAGE_SIZE;
 3150                                 pmap_pde_mappings++;
 3151                         }
 3152                         /* Else continue on if the PDE is already valid. */
 3153                         addr += NBPDR;
 3154                 }
 3155                 PMAP_UNLOCK(pmap);
 3156         }
 3157 }
 3158 
 3159 /*
 3160  *      Routine:        pmap_change_wiring
 3161  *      Function:       Change the wiring attribute for a map/virtual-address
 3162  *                      pair.
 3163  *      In/out conditions:
 3164  *                      The mapping must already exist in the pmap.
 3165  */
 3166 void
 3167 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
 3168 {
 3169         pt_entry_t *pte;
 3170 
 3171         vm_page_lock_queues();
 3172         PMAP_LOCK(pmap);
 3173         pte = pmap_pte(pmap, va);
 3174 
 3175         if (wired && !pmap_pte_w(pte)) {
 3176                 PT_SET_VA_MA((pte), *(pte) | PG_W, TRUE);
 3177                 pmap->pm_stats.wired_count++;
 3178         } else if (!wired && pmap_pte_w(pte)) {
 3179                 PT_SET_VA_MA((pte), *(pte) & ~PG_W, TRUE);
 3180                 pmap->pm_stats.wired_count--;
 3181         }
 3182         
 3183         /*
 3184          * Wiring is not a hardware characteristic so there is no need to
 3185          * invalidate TLB.
 3186          */
 3187         pmap_pte_release(pte);
 3188         PMAP_UNLOCK(pmap);
 3189         vm_page_unlock_queues();
 3190 }
 3191 
 3192 
 3193 
 3194 /*
 3195  *      Copy the range specified by src_addr/len
 3196  *      from the source map to the range dst_addr/len
 3197  *      in the destination map.
 3198  *
 3199  *      This routine is only advisory and need not do anything.
 3200  */
 3201 
 3202 void
 3203 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
 3204     vm_offset_t src_addr)
 3205 {
 3206         vm_page_t   free;
 3207         vm_offset_t addr;
 3208         vm_offset_t end_addr = src_addr + len;
 3209         vm_offset_t pdnxt;
 3210 
 3211         if (dst_addr != src_addr)
 3212                 return;
 3213 
 3214         if (!pmap_is_current(src_pmap)) {
 3215                 CTR2(KTR_PMAP,
 3216                     "pmap_copy, skipping: pdir[PTDPTDI]=0x%jx PTDpde[0]=0x%jx",
 3217                     (src_pmap->pm_pdir[PTDPTDI] & PG_FRAME), (PTDpde[0] & PG_FRAME));
 3218                 
 3219                 return;
 3220         }
 3221         CTR5(KTR_PMAP, "pmap_copy:  dst_pmap=%p src_pmap=%p dst_addr=0x%x len=%d src_addr=0x%x",
 3222             dst_pmap, src_pmap, dst_addr, len, src_addr);
 3223         
 3224 #ifdef HAMFISTED_LOCKING
 3225         mtx_lock(&createdelete_lock);
 3226 #endif
 3227 
 3228         vm_page_lock_queues();
 3229         if (dst_pmap < src_pmap) {
 3230                 PMAP_LOCK(dst_pmap);
 3231                 PMAP_LOCK(src_pmap);
 3232         } else {
 3233                 PMAP_LOCK(src_pmap);
 3234                 PMAP_LOCK(dst_pmap);
 3235         }
 3236         sched_pin();
 3237         for (addr = src_addr; addr < end_addr; addr = pdnxt) {
 3238                 pt_entry_t *src_pte, *dst_pte;
 3239                 vm_page_t dstmpte, srcmpte;
 3240                 pd_entry_t srcptepaddr;
 3241                 u_int ptepindex;
 3242 
 3243                 KASSERT(addr < UPT_MIN_ADDRESS,
 3244                     ("pmap_copy: invalid to pmap_copy page tables"));
 3245 
 3246                 pdnxt = (addr + NBPDR) & ~PDRMASK;
 3247                 if (pdnxt < addr)
 3248                         pdnxt = end_addr;
 3249                 ptepindex = addr >> PDRSHIFT;
 3250 
 3251                 srcptepaddr = PT_GET(&src_pmap->pm_pdir[ptepindex]);
 3252                 if (srcptepaddr == 0)
 3253                         continue;
 3254                         
 3255                 if (srcptepaddr & PG_PS) {
 3256                         if (dst_pmap->pm_pdir[ptepindex] == 0) {
 3257                                 PD_SET_VA(dst_pmap, ptepindex, srcptepaddr & ~PG_W, TRUE);
 3258                                 dst_pmap->pm_stats.resident_count +=
 3259                                     NBPDR / PAGE_SIZE;
 3260                         }
 3261                         continue;
 3262                 }
 3263 
 3264                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr & PG_FRAME);
 3265                 KASSERT(srcmpte->wire_count > 0,
 3266                     ("pmap_copy: source page table page is unused"));
 3267 
 3268                 if (pdnxt > end_addr)
 3269                         pdnxt = end_addr;
 3270 
 3271                 src_pte = vtopte(addr);
 3272                 while (addr < pdnxt) {
 3273                         pt_entry_t ptetemp;
 3274                         ptetemp = *src_pte;
 3275                         /*
 3276                          * we only virtual copy managed pages
 3277                          */
 3278                         if ((ptetemp & PG_MANAGED) != 0) {
 3279                                 dstmpte = pmap_allocpte(dst_pmap, addr,
 3280                                     M_NOWAIT);
 3281                                 if (dstmpte == NULL)
 3282                                         goto out;
 3283                                 dst_pte = pmap_pte_quick(dst_pmap, addr);
 3284                                 if (*dst_pte == 0 &&
 3285                                     pmap_try_insert_pv_entry(dst_pmap, addr,
 3286                                     PHYS_TO_VM_PAGE(xpmap_mtop(ptetemp) & PG_FRAME))) {
 3287                                         /*
 3288                                          * Clear the wired, modified, and
 3289                                          * accessed (referenced) bits
 3290                                          * during the copy.
 3291                                          */
 3292                                         KASSERT(ptetemp != 0, ("src_pte not set"));
 3293                                         PT_SET_VA_MA(dst_pte, ptetemp & ~(PG_W | PG_M | PG_A), TRUE /* XXX debug */);
 3294                                         KASSERT(*dst_pte == (ptetemp & ~(PG_W | PG_M | PG_A)),
 3295                                             ("no pmap copy expected: 0x%jx saw: 0x%jx",
 3296                                                 ptetemp &  ~(PG_W | PG_M | PG_A), *dst_pte));
 3297                                         dst_pmap->pm_stats.resident_count++;
 3298                                 } else {
 3299                                         free = NULL;
 3300                                         if (pmap_unwire_pte_hold(dst_pmap,
 3301                                             dstmpte, &free)) {
 3302                                                 pmap_invalidate_page(dst_pmap,
 3303                                                     addr);
 3304                                                 pmap_free_zero_pages(free);
 3305                                         }
 3306                                         goto out;
 3307                                 }
 3308                                 if (dstmpte->wire_count >= srcmpte->wire_count)
 3309                                         break;
 3310                         }
 3311                         addr += PAGE_SIZE;
 3312                         src_pte++;
 3313                 }
 3314         }
 3315 out:
 3316         PT_UPDATES_FLUSH();
 3317         sched_unpin();
 3318         vm_page_unlock_queues();
 3319         PMAP_UNLOCK(src_pmap);
 3320         PMAP_UNLOCK(dst_pmap);
 3321 
 3322 #ifdef HAMFISTED_LOCKING
 3323         mtx_unlock(&createdelete_lock);
 3324 #endif
 3325 }       
 3326 
 3327 static __inline void
 3328 pagezero(void *page)
 3329 {
 3330 #if defined(I686_CPU)
 3331         if (cpu_class == CPUCLASS_686) {
 3332 #if defined(CPU_ENABLE_SSE)
 3333                 if (cpu_feature & CPUID_SSE2)
 3334                         sse2_pagezero(page);
 3335                 else
 3336 #endif
 3337                         i686_pagezero(page);
 3338         } else
 3339 #endif
 3340                 bzero(page, PAGE_SIZE);
 3341 }
 3342 
 3343 /*
 3344  *      pmap_zero_page zeros the specified hardware page by mapping 
 3345  *      the page into KVM and using bzero to clear its contents.
 3346  */
 3347 void
 3348 pmap_zero_page(vm_page_t m)
 3349 {
 3350         struct sysmaps *sysmaps;
 3351 
 3352         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3353         mtx_lock(&sysmaps->lock);
 3354         if (*sysmaps->CMAP2)
 3355                 panic("pmap_zero_page: CMAP2 busy");
 3356         sched_pin();
 3357         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | VM_PAGE_TO_MACH(m) | PG_A | PG_M);
 3358         pagezero(sysmaps->CADDR2);
 3359         PT_SET_MA(sysmaps->CADDR2, 0);
 3360         sched_unpin();
 3361         mtx_unlock(&sysmaps->lock);
 3362 }
 3363 
 3364 /*
 3365  *      pmap_zero_page_area zeros the specified hardware page by mapping 
 3366  *      the page into KVM and using bzero to clear its contents.
 3367  *
 3368  *      off and size may not cover an area beyond a single hardware page.
 3369  */
 3370 void
 3371 pmap_zero_page_area(vm_page_t m, int off, int size)
 3372 {
 3373         struct sysmaps *sysmaps;
 3374 
 3375         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3376         mtx_lock(&sysmaps->lock);
 3377         if (*sysmaps->CMAP2)
 3378                 panic("pmap_zero_page_area: CMAP2 busy");
 3379         sched_pin();
 3380         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | VM_PAGE_TO_MACH(m) | PG_A | PG_M);
 3381 
 3382         if (off == 0 && size == PAGE_SIZE) 
 3383                 pagezero(sysmaps->CADDR2);
 3384         else
 3385                 bzero((char *)sysmaps->CADDR2 + off, size);
 3386         PT_SET_MA(sysmaps->CADDR2, 0);
 3387         sched_unpin();
 3388         mtx_unlock(&sysmaps->lock);
 3389 }
 3390 
 3391 /*
 3392  *      pmap_zero_page_idle zeros the specified hardware page by mapping 
 3393  *      the page into KVM and using bzero to clear its contents.  This
 3394  *      is intended to be called from the vm_pagezero process only and
 3395  *      outside of Giant.
 3396  */
 3397 void
 3398 pmap_zero_page_idle(vm_page_t m)
 3399 {
 3400 
 3401         if (*CMAP3)
 3402                 panic("pmap_zero_page_idle: CMAP3 busy");
 3403         sched_pin();
 3404         PT_SET_MA(CADDR3, PG_V | PG_RW | VM_PAGE_TO_MACH(m) | PG_A | PG_M);
 3405         pagezero(CADDR3);
 3406         PT_SET_MA(CADDR3, 0);
 3407         sched_unpin();
 3408 }
 3409 
 3410 /*
 3411  *      pmap_copy_page copies the specified (machine independent)
 3412  *      page by mapping the page into virtual memory and using
 3413  *      bcopy to copy the page, one machine dependent page at a
 3414  *      time.
 3415  */
 3416 void
 3417 pmap_copy_page(vm_page_t src, vm_page_t dst)
 3418 {
 3419         struct sysmaps *sysmaps;
 3420 
 3421         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3422         mtx_lock(&sysmaps->lock);
 3423         if (*sysmaps->CMAP1)
 3424                 panic("pmap_copy_page: CMAP1 busy");
 3425         if (*sysmaps->CMAP2)
 3426                 panic("pmap_copy_page: CMAP2 busy");
 3427         sched_pin();
 3428         PT_SET_MA(sysmaps->CADDR1, PG_V | VM_PAGE_TO_MACH(src) | PG_A);
 3429         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | VM_PAGE_TO_MACH(dst) | PG_A | PG_M);
 3430         bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
 3431         PT_SET_MA(sysmaps->CADDR1, 0);
 3432         PT_SET_MA(sysmaps->CADDR2, 0);
 3433         sched_unpin();
 3434         mtx_unlock(&sysmaps->lock);
 3435 }
 3436 
 3437 /*
 3438  * Returns true if the pmap's pv is one of the first
 3439  * 16 pvs linked to from this page.  This count may
 3440  * be changed upwards or downwards in the future; it
 3441  * is only necessary that true be returned for a small
 3442  * subset of pmaps for proper page aging.
 3443  */
 3444 boolean_t
 3445 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
 3446 {
 3447         pv_entry_t pv;
 3448         int loops = 0;
 3449         boolean_t rv;
 3450 
 3451         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3452             ("pmap_page_exists_quick: page %p is not managed", m));
 3453         rv = FALSE;
 3454         vm_page_lock_queues();
 3455         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3456                 if (PV_PMAP(pv) == pmap) {
 3457                         rv = TRUE;
 3458                         break;
 3459                 }
 3460                 loops++;
 3461                 if (loops >= 16)
 3462                         break;
 3463         }
 3464         vm_page_unlock_queues();
 3465         return (rv);
 3466 }
 3467 
 3468 /*
 3469  *      pmap_page_wired_mappings:
 3470  *
 3471  *      Return the number of managed mappings to the given physical page
 3472  *      that are wired.
 3473  */
 3474 int
 3475 pmap_page_wired_mappings(vm_page_t m)
 3476 {
 3477         pv_entry_t pv;
 3478         pt_entry_t *pte;
 3479         pmap_t pmap;
 3480         int count;
 3481 
 3482         count = 0;
 3483         if ((m->oflags & VPO_UNMANAGED) != 0)
 3484                 return (count);
 3485         vm_page_lock_queues();
 3486         sched_pin();
 3487         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3488                 pmap = PV_PMAP(pv);
 3489                 PMAP_LOCK(pmap);
 3490                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3491                 if ((*pte & PG_W) != 0)
 3492                         count++;
 3493                 PMAP_UNLOCK(pmap);
 3494         }
 3495         sched_unpin();
 3496         vm_page_unlock_queues();
 3497         return (count);
 3498 }
 3499 
 3500 /*
 3501  * Returns TRUE if the given page is mapped.  Otherwise, returns FALSE.
 3502  */
 3503 boolean_t
 3504 pmap_page_is_mapped(vm_page_t m)
 3505 {
 3506 
 3507         if ((m->oflags & VPO_UNMANAGED) != 0)
 3508                 return (FALSE);
 3509         return (!TAILQ_EMPTY(&m->md.pv_list));
 3510 }
 3511 
 3512 /*
 3513  * Remove all pages from specified address space
 3514  * this aids process exit speeds.  Also, this code
 3515  * is special cased for current process only, but
 3516  * can have the more generic (and slightly slower)
 3517  * mode enabled.  This is much faster than pmap_remove
 3518  * in the case of running down an entire address space.
 3519  */
 3520 void
 3521 pmap_remove_pages(pmap_t pmap)
 3522 {
 3523         pt_entry_t *pte, tpte;
 3524         vm_page_t m, free = NULL;
 3525         pv_entry_t pv;
 3526         struct pv_chunk *pc, *npc;
 3527         int field, idx;
 3528         int32_t bit;
 3529         uint32_t inuse, bitmask;
 3530         int allfree;
 3531 
 3532         CTR1(KTR_PMAP, "pmap_remove_pages: pmap=%p", pmap);
 3533         
 3534         if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace)) {
 3535                 printf("warning: pmap_remove_pages called with non-current pmap\n");
 3536                 return;
 3537         }
 3538         vm_page_lock_queues();
 3539         KASSERT(pmap_is_current(pmap), ("removing pages from non-current pmap"));
 3540         PMAP_LOCK(pmap);
 3541         sched_pin();
 3542         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
 3543                 allfree = 1;
 3544                 for (field = 0; field < _NPCM; field++) {
 3545                         inuse = ~pc->pc_map[field] & pc_freemask[field];
 3546                         while (inuse != 0) {
 3547                                 bit = bsfl(inuse);
 3548                                 bitmask = 1UL << bit;
 3549                                 idx = field * 32 + bit;
 3550                                 pv = &pc->pc_pventry[idx];
 3551                                 inuse &= ~bitmask;
 3552 
 3553                                 pte = vtopte(pv->pv_va);
 3554                                 tpte = *pte ? xpmap_mtop(*pte) : 0;
 3555 
 3556                                 if (tpte == 0) {
 3557                                         printf(
 3558                                             "TPTE at %p  IS ZERO @ VA %08x\n",
 3559                                             pte, pv->pv_va);
 3560                                         panic("bad pte");
 3561                                 }
 3562 
 3563 /*
 3564  * We cannot remove wired pages from a process' mapping at this time
 3565  */
 3566                                 if (tpte & PG_W) {
 3567                                         allfree = 0;
 3568                                         continue;
 3569                                 }
 3570 
 3571                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
 3572                                 KASSERT(m->phys_addr == (tpte & PG_FRAME),
 3573                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
 3574                                     m, (uintmax_t)m->phys_addr,
 3575                                     (uintmax_t)tpte));
 3576 
 3577                                 KASSERT(m < &vm_page_array[vm_page_array_size],
 3578                                         ("pmap_remove_pages: bad tpte %#jx",
 3579                                         (uintmax_t)tpte));
 3580 
 3581 
 3582                                 PT_CLEAR_VA(pte, FALSE);
 3583                                 
 3584                                 /*
 3585                                  * Update the vm_page_t clean/reference bits.
 3586                                  */
 3587                                 if (tpte & PG_M)
 3588                                         vm_page_dirty(m);
 3589 
 3590                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 3591                                 if (TAILQ_EMPTY(&m->md.pv_list))
 3592                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
 3593 
 3594                                 pmap_unuse_pt(pmap, pv->pv_va, &free);
 3595 
 3596                                 /* Mark free */
 3597                                 PV_STAT(pv_entry_frees++);
 3598                                 PV_STAT(pv_entry_spare++);
 3599                                 pv_entry_count--;
 3600                                 pc->pc_map[field] |= bitmask;
 3601                                 pmap->pm_stats.resident_count--;                        
 3602                         }
 3603                 }
 3604                 PT_UPDATES_FLUSH();
 3605                 if (allfree) {
 3606                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3607                         free_pv_chunk(pc);
 3608                 }
 3609         }
 3610         PT_UPDATES_FLUSH();
 3611         if (*PMAP1)
 3612                 PT_SET_MA(PADDR1, 0);
 3613 
 3614         sched_unpin();
 3615         pmap_invalidate_all(pmap);
 3616         vm_page_unlock_queues();
 3617         PMAP_UNLOCK(pmap);
 3618         pmap_free_zero_pages(free);
 3619 }
 3620 
 3621 /*
 3622  *      pmap_is_modified:
 3623  *
 3624  *      Return whether or not the specified physical page was modified
 3625  *      in any physical maps.
 3626  */
 3627 boolean_t
 3628 pmap_is_modified(vm_page_t m)
 3629 {
 3630         pv_entry_t pv;
 3631         pt_entry_t *pte;
 3632         pmap_t pmap;
 3633         boolean_t rv;
 3634 
 3635         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3636             ("pmap_is_modified: page %p is not managed", m));
 3637         rv = FALSE;
 3638 
 3639         /*
 3640          * If the page is not VPO_BUSY, then PGA_WRITEABLE cannot be
 3641          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
 3642          * is clear, no PTEs can have PG_M set.
 3643          */
 3644         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 3645         if ((m->oflags & VPO_BUSY) == 0 &&
 3646             (m->aflags & PGA_WRITEABLE) == 0)
 3647                 return (rv);
 3648         vm_page_lock_queues();
 3649         sched_pin();
 3650         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3651                 pmap = PV_PMAP(pv);
 3652                 PMAP_LOCK(pmap);
 3653                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3654                 rv = (*pte & PG_M) != 0;
 3655                 PMAP_UNLOCK(pmap);
 3656                 if (rv)
 3657                         break;
 3658         }
 3659         if (*PMAP1)
 3660                 PT_SET_MA(PADDR1, 0);
 3661         sched_unpin();
 3662         vm_page_unlock_queues();
 3663         return (rv);
 3664 }
 3665 
 3666 /*
 3667  *      pmap_is_prefaultable:
 3668  *
 3669  *      Return whether or not the specified virtual address is elgible
 3670  *      for prefault.
 3671  */
 3672 static boolean_t
 3673 pmap_is_prefaultable_locked(pmap_t pmap, vm_offset_t addr)
 3674 {
 3675         pt_entry_t *pte;
 3676         boolean_t rv = FALSE;
 3677 
 3678         return (rv);
 3679         
 3680         if (pmap_is_current(pmap) && *pmap_pde(pmap, addr)) {
 3681                 pte = vtopte(addr);
 3682                 rv = (*pte == 0);
 3683         }
 3684         return (rv);
 3685 }
 3686 
 3687 boolean_t
 3688 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
 3689 {
 3690         boolean_t rv;
 3691         
 3692         PMAP_LOCK(pmap);
 3693         rv = pmap_is_prefaultable_locked(pmap, addr);
 3694         PMAP_UNLOCK(pmap);
 3695         return (rv);
 3696 }
 3697 
 3698 boolean_t
 3699 pmap_is_referenced(vm_page_t m)
 3700 {
 3701         pv_entry_t pv;
 3702         pt_entry_t *pte;
 3703         pmap_t pmap;
 3704         boolean_t rv;
 3705 
 3706         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3707             ("pmap_is_referenced: page %p is not managed", m));
 3708         rv = FALSE;
 3709         vm_page_lock_queues();
 3710         sched_pin();
 3711         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3712                 pmap = PV_PMAP(pv);
 3713                 PMAP_LOCK(pmap);
 3714                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3715                 rv = (*pte & (PG_A | PG_V)) == (PG_A | PG_V);
 3716                 PMAP_UNLOCK(pmap);
 3717                 if (rv)
 3718                         break;
 3719         }
 3720         if (*PMAP1)
 3721                 PT_SET_MA(PADDR1, 0);
 3722         sched_unpin();
 3723         vm_page_unlock_queues();
 3724         return (rv);
 3725 }
 3726 
 3727 void
 3728 pmap_map_readonly(pmap_t pmap, vm_offset_t va, int len)
 3729 {
 3730         int i, npages = round_page(len) >> PAGE_SHIFT;
 3731         for (i = 0; i < npages; i++) {
 3732                 pt_entry_t *pte;
 3733                 pte = pmap_pte(pmap, (vm_offset_t)(va + i*PAGE_SIZE));
 3734                 vm_page_lock_queues();
 3735                 pte_store(pte, xpmap_mtop(*pte & ~(PG_RW|PG_M)));
 3736                 vm_page_unlock_queues();
 3737                 PMAP_MARK_PRIV(xpmap_mtop(*pte));
 3738                 pmap_pte_release(pte);
 3739         }
 3740 }
 3741 
 3742 void
 3743 pmap_map_readwrite(pmap_t pmap, vm_offset_t va, int len)
 3744 {
 3745         int i, npages = round_page(len) >> PAGE_SHIFT;
 3746         for (i = 0; i < npages; i++) {
 3747                 pt_entry_t *pte;
 3748                 pte = pmap_pte(pmap, (vm_offset_t)(va + i*PAGE_SIZE));
 3749                 PMAP_MARK_UNPRIV(xpmap_mtop(*pte));
 3750                 vm_page_lock_queues();
 3751                 pte_store(pte, xpmap_mtop(*pte) | (PG_RW|PG_M));
 3752                 vm_page_unlock_queues();
 3753                 pmap_pte_release(pte);
 3754         }
 3755 }
 3756 
 3757 /*
 3758  * Clear the write and modified bits in each of the given page's mappings.
 3759  */
 3760 void
 3761 pmap_remove_write(vm_page_t m)
 3762 {
 3763         pv_entry_t pv;
 3764         pmap_t pmap;
 3765         pt_entry_t oldpte, *pte;
 3766 
 3767         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3768             ("pmap_remove_write: page %p is not managed", m));
 3769 
 3770         /*
 3771          * If the page is not VPO_BUSY, then PGA_WRITEABLE cannot be set by
 3772          * another thread while the object is locked.  Thus, if PGA_WRITEABLE
 3773          * is clear, no page table entries need updating.
 3774          */
 3775         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 3776         if ((m->oflags & VPO_BUSY) == 0 &&
 3777             (m->aflags & PGA_WRITEABLE) == 0)
 3778                 return;
 3779         vm_page_lock_queues();
 3780         sched_pin();
 3781         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3782                 pmap = PV_PMAP(pv);
 3783                 PMAP_LOCK(pmap);
 3784                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3785 retry:
 3786                 oldpte = *pte;
 3787                 if ((oldpte & PG_RW) != 0) {
 3788                         vm_paddr_t newpte = oldpte & ~(PG_RW | PG_M);
 3789                         
 3790                         /*
 3791                          * Regardless of whether a pte is 32 or 64 bits
 3792                          * in size, PG_RW and PG_M are among the least
 3793                          * significant 32 bits.
 3794                          */
 3795                         PT_SET_VA_MA(pte, newpte, TRUE);
 3796                         if (*pte != newpte)
 3797                                 goto retry;
 3798                         
 3799                         if ((oldpte & PG_M) != 0)
 3800                                 vm_page_dirty(m);
 3801                         pmap_invalidate_page(pmap, pv->pv_va);
 3802                 }
 3803                 PMAP_UNLOCK(pmap);
 3804         }
 3805         vm_page_aflag_clear(m, PGA_WRITEABLE);
 3806         PT_UPDATES_FLUSH();
 3807         if (*PMAP1)
 3808                 PT_SET_MA(PADDR1, 0);
 3809         sched_unpin();
 3810         vm_page_unlock_queues();
 3811 }
 3812 
 3813 /*
 3814  *      pmap_ts_referenced:
 3815  *
 3816  *      Return a count of reference bits for a page, clearing those bits.
 3817  *      It is not necessary for every reference bit to be cleared, but it
 3818  *      is necessary that 0 only be returned when there are truly no
 3819  *      reference bits set.
 3820  *
 3821  *      XXX: The exact number of bits to check and clear is a matter that
 3822  *      should be tested and standardized at some point in the future for
 3823  *      optimal aging of shared pages.
 3824  */
 3825 int
 3826 pmap_ts_referenced(vm_page_t m)
 3827 {
 3828         pv_entry_t pv, pvf, pvn;
 3829         pmap_t pmap;
 3830         pt_entry_t *pte;
 3831         int rtval = 0;
 3832 
 3833         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3834             ("pmap_ts_referenced: page %p is not managed", m));
 3835         vm_page_lock_queues();
 3836         sched_pin();
 3837         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 3838                 pvf = pv;
 3839                 do {
 3840                         pvn = TAILQ_NEXT(pv, pv_list);
 3841                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 3842                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 3843                         pmap = PV_PMAP(pv);
 3844                         PMAP_LOCK(pmap);
 3845                         pte = pmap_pte_quick(pmap, pv->pv_va);
 3846                         if ((*pte & PG_A) != 0) {
 3847                                 PT_SET_VA_MA(pte, *pte & ~PG_A, FALSE);
 3848                                 pmap_invalidate_page(pmap, pv->pv_va);
 3849                                 rtval++;
 3850                                 if (rtval > 4)
 3851                                         pvn = NULL;
 3852                         }
 3853                         PMAP_UNLOCK(pmap);
 3854                 } while ((pv = pvn) != NULL && pv != pvf);
 3855         }
 3856         PT_UPDATES_FLUSH();
 3857         if (*PMAP1)
 3858                 PT_SET_MA(PADDR1, 0);
 3859         sched_unpin();
 3860         vm_page_unlock_queues();
 3861         return (rtval);
 3862 }
 3863 
 3864 /*
 3865  *      Clear the modify bits on the specified physical page.
 3866  */
 3867 void
 3868 pmap_clear_modify(vm_page_t m)
 3869 {
 3870         pv_entry_t pv;
 3871         pmap_t pmap;
 3872         pt_entry_t *pte;
 3873 
 3874         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3875             ("pmap_clear_modify: page %p is not managed", m));
 3876         VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
 3877         KASSERT((m->oflags & VPO_BUSY) == 0,
 3878             ("pmap_clear_modify: page %p is busy", m));
 3879 
 3880         /*
 3881          * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
 3882          * If the object containing the page is locked and the page is not
 3883          * VPO_BUSY, then PGA_WRITEABLE cannot be concurrently set.
 3884          */
 3885         if ((m->aflags & PGA_WRITEABLE) == 0)
 3886                 return;
 3887         vm_page_lock_queues();
 3888         sched_pin();
 3889         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3890                 pmap = PV_PMAP(pv);
 3891                 PMAP_LOCK(pmap);
 3892                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3893                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
 3894                         /*
 3895                          * Regardless of whether a pte is 32 or 64 bits
 3896                          * in size, PG_M is among the least significant
 3897                          * 32 bits. 
 3898                          */
 3899                         PT_SET_VA_MA(pte, *pte & ~PG_M, FALSE);
 3900                         pmap_invalidate_page(pmap, pv->pv_va);
 3901                 }
 3902                 PMAP_UNLOCK(pmap);
 3903         }
 3904         sched_unpin();
 3905         vm_page_unlock_queues();
 3906 }
 3907 
 3908 /*
 3909  *      pmap_clear_reference:
 3910  *
 3911  *      Clear the reference bit on the specified physical page.
 3912  */
 3913 void
 3914 pmap_clear_reference(vm_page_t m)
 3915 {
 3916         pv_entry_t pv;
 3917         pmap_t pmap;
 3918         pt_entry_t *pte;
 3919 
 3920         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
 3921             ("pmap_clear_reference: page %p is not managed", m));
 3922         vm_page_lock_queues();
 3923         sched_pin();
 3924         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3925                 pmap = PV_PMAP(pv);
 3926                 PMAP_LOCK(pmap);
 3927                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3928                 if ((*pte & PG_A) != 0) {
 3929                         /*
 3930                          * Regardless of whether a pte is 32 or 64 bits
 3931                          * in size, PG_A is among the least significant
 3932                          * 32 bits. 
 3933                          */
 3934                         PT_SET_VA_MA(pte, *pte & ~PG_A, FALSE);
 3935                         pmap_invalidate_page(pmap, pv->pv_va);
 3936                 }
 3937                 PMAP_UNLOCK(pmap);
 3938         }
 3939         sched_unpin();
 3940         vm_page_unlock_queues();
 3941 }
 3942 
 3943 /*
 3944  * Miscellaneous support routines follow
 3945  */
 3946 
 3947 /*
 3948  * Map a set of physical memory pages into the kernel virtual
 3949  * address space. Return a pointer to where it is mapped. This
 3950  * routine is intended to be used for mapping device memory,
 3951  * NOT real memory.
 3952  */
 3953 void *
 3954 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
 3955 {
 3956         vm_offset_t va, offset;
 3957         vm_size_t tmpsize;
 3958 
 3959         offset = pa & PAGE_MASK;
 3960         size = roundup(offset + size, PAGE_SIZE);
 3961         pa = pa & PG_FRAME;
 3962 
 3963         if (pa < KERNLOAD && pa + size <= KERNLOAD)
 3964                 va = KERNBASE + pa;
 3965         else
 3966                 va = kmem_alloc_nofault(kernel_map, size);
 3967         if (!va)
 3968                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
 3969 
 3970         for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
 3971                 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
 3972         pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
 3973         pmap_invalidate_cache_range(va, va + size);
 3974         return ((void *)(va + offset));
 3975 }
 3976 
 3977 void *
 3978 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
 3979 {
 3980 
 3981         return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
 3982 }
 3983 
 3984 void *
 3985 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
 3986 {
 3987 
 3988         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
 3989 }
 3990 
 3991 void
 3992 pmap_unmapdev(vm_offset_t va, vm_size_t size)
 3993 {
 3994         vm_offset_t base, offset, tmpva;
 3995 
 3996         if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
 3997                 return;
 3998         base = trunc_page(va);
 3999         offset = va & PAGE_MASK;
 4000         size = roundup(offset + size, PAGE_SIZE);
 4001         critical_enter();
 4002         for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
 4003                 pmap_kremove(tmpva);
 4004         pmap_invalidate_range(kernel_pmap, va, tmpva);
 4005         critical_exit();
 4006         kmem_free(kernel_map, base, size);
 4007 }
 4008 
 4009 /*
 4010  * Sets the memory attribute for the specified page.
 4011  */
 4012 void
 4013 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
 4014 {
 4015 
 4016         m->md.pat_mode = ma;
 4017         if ((m->flags & PG_FICTITIOUS) != 0)
 4018                 return;
 4019 
 4020         /*
 4021          * If "m" is a normal page, flush it from the cache.
 4022          * See pmap_invalidate_cache_range().
 4023          *
 4024          * First, try to find an existing mapping of the page by sf
 4025          * buffer. sf_buf_invalidate_cache() modifies mapping and
 4026          * flushes the cache.
 4027          */    
 4028         if (sf_buf_invalidate_cache(m))
 4029                 return;
 4030 
 4031         /*
 4032          * If page is not mapped by sf buffer, but CPU does not
 4033          * support self snoop, map the page transient and do
 4034          * invalidation. In the worst case, whole cache is flushed by
 4035          * pmap_invalidate_cache_range().
 4036          */
 4037         if ((cpu_feature & CPUID_SS) == 0)
 4038                 pmap_flush_page(m);
 4039 }
 4040 
 4041 static void
 4042 pmap_flush_page(vm_page_t m)
 4043 {
 4044         struct sysmaps *sysmaps;
 4045         vm_offset_t sva, eva;
 4046 
 4047         if ((cpu_feature & CPUID_CLFSH) != 0) {
 4048                 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 4049                 mtx_lock(&sysmaps->lock);
 4050                 if (*sysmaps->CMAP2)
 4051                         panic("pmap_flush_page: CMAP2 busy");
 4052                 sched_pin();
 4053                 PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW |
 4054                     VM_PAGE_TO_MACH(m) | PG_A | PG_M |
 4055                     pmap_cache_bits(m->md.pat_mode, 0));
 4056                 invlcaddr(sysmaps->CADDR2);
 4057                 sva = (vm_offset_t)sysmaps->CADDR2;
 4058                 eva = sva + PAGE_SIZE;
 4059 
 4060                 /*
 4061                  * Use mfence despite the ordering implied by
 4062                  * mtx_{un,}lock() because clflush is not guaranteed
 4063                  * to be ordered by any other instruction.
 4064                  */
 4065                 mfence();
 4066                 for (; sva < eva; sva += cpu_clflush_line_size)
 4067                         clflush(sva);
 4068                 mfence();
 4069                 PT_SET_MA(sysmaps->CADDR2, 0);
 4070                 sched_unpin();
 4071                 mtx_unlock(&sysmaps->lock);
 4072         } else
 4073                 pmap_invalidate_cache();
 4074 }
 4075 
 4076 /*
 4077  * Changes the specified virtual address range's memory type to that given by
 4078  * the parameter "mode".  The specified virtual address range must be
 4079  * completely contained within either the kernel map.
 4080  *
 4081  * Returns zero if the change completed successfully, and either EINVAL or
 4082  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
 4083  * of the virtual address range was not mapped, and ENOMEM is returned if
 4084  * there was insufficient memory available to complete the change.
 4085  */
 4086 int
 4087 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
 4088 {
 4089         vm_offset_t base, offset, tmpva;
 4090         pt_entry_t *pte;
 4091         u_int opte, npte;
 4092         pd_entry_t *pde;
 4093         boolean_t changed;
 4094 
 4095         base = trunc_page(va);
 4096         offset = va & PAGE_MASK;
 4097         size = roundup(offset + size, PAGE_SIZE);
 4098 
 4099         /* Only supported on kernel virtual addresses. */
 4100         if (base <= VM_MAXUSER_ADDRESS)
 4101                 return (EINVAL);
 4102 
 4103         /* 4MB pages and pages that aren't mapped aren't supported. */
 4104         for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE) {
 4105                 pde = pmap_pde(kernel_pmap, tmpva);
 4106                 if (*pde & PG_PS)
 4107                         return (EINVAL);
 4108                 if ((*pde & PG_V) == 0)
 4109                         return (EINVAL);
 4110                 pte = vtopte(va);
 4111                 if ((*pte & PG_V) == 0)
 4112                         return (EINVAL);
 4113         }
 4114 
 4115         changed = FALSE;
 4116 
 4117         /*
 4118          * Ok, all the pages exist and are 4k, so run through them updating
 4119          * their cache mode.
 4120          */
 4121         for (tmpva = base; size > 0; ) {
 4122                 pte = vtopte(tmpva);
 4123 
 4124                 /*
 4125                  * The cache mode bits are all in the low 32-bits of the
 4126                  * PTE, so we can just spin on updating the low 32-bits.
 4127                  */
 4128                 do {
 4129                         opte = *(u_int *)pte;
 4130                         npte = opte & ~(PG_PTE_PAT | PG_NC_PCD | PG_NC_PWT);
 4131                         npte |= pmap_cache_bits(mode, 0);
 4132                         PT_SET_VA_MA(pte, npte, TRUE);
 4133                 } while (npte != opte && (*pte != npte));
 4134                 if (npte != opte)
 4135                         changed = TRUE;
 4136                 tmpva += PAGE_SIZE;
 4137                 size -= PAGE_SIZE;
 4138         }
 4139 
 4140         /*
 4141          * Flush CPU caches to make sure any data isn't cached that
 4142          * shouldn't be, etc.
 4143          */
 4144         if (changed) {
 4145                 pmap_invalidate_range(kernel_pmap, base, tmpva);
 4146                 pmap_invalidate_cache_range(base, tmpva);
 4147         }
 4148         return (0);
 4149 }
 4150 
 4151 /*
 4152  * perform the pmap work for mincore
 4153  */
 4154 int
 4155 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
 4156 {
 4157         pt_entry_t *ptep, pte;
 4158         vm_paddr_t pa;
 4159         int val;
 4160 
 4161         PMAP_LOCK(pmap);
 4162 retry:
 4163         ptep = pmap_pte(pmap, addr);
 4164         pte = (ptep != NULL) ? PT_GET(ptep) : 0;
 4165         pmap_pte_release(ptep);
 4166         val = 0;
 4167         if ((pte & PG_V) != 0) {
 4168                 val |= MINCORE_INCORE;
 4169                 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
 4170                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
 4171                 if ((pte & PG_A) != 0)
 4172                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
 4173         }
 4174         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
 4175             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
 4176             (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
 4177                 pa = pte & PG_FRAME;
 4178                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
 4179                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
 4180                         goto retry;
 4181         } else
 4182                 PA_UNLOCK_COND(*locked_pa);
 4183         PMAP_UNLOCK(pmap);
 4184         return (val);
 4185 }
 4186 
 4187 void
 4188 pmap_activate(struct thread *td)
 4189 {
 4190         pmap_t  pmap, oldpmap;
 4191         u_int   cpuid;
 4192         u_int32_t  cr3;
 4193 
 4194         critical_enter();
 4195         pmap = vmspace_pmap(td->td_proc->p_vmspace);
 4196         oldpmap = PCPU_GET(curpmap);
 4197         cpuid = PCPU_GET(cpuid);
 4198 #if defined(SMP)
 4199         CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
 4200         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
 4201 #else
 4202         CPU_CLR(cpuid, &oldpmap->pm_active);
 4203         CPU_SET(cpuid, &pmap->pm_active);
 4204 #endif
 4205 #ifdef PAE
 4206         cr3 = vtophys(pmap->pm_pdpt);
 4207 #else
 4208         cr3 = vtophys(pmap->pm_pdir);
 4209 #endif
 4210         /*
 4211          * pmap_activate is for the current thread on the current cpu
 4212          */
 4213         td->td_pcb->pcb_cr3 = cr3;
 4214         PT_UPDATES_FLUSH();
 4215         load_cr3(cr3);
 4216         PCPU_SET(curpmap, pmap);
 4217         critical_exit();
 4218 }
 4219 
 4220 void
 4221 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
 4222 {
 4223 }
 4224 
 4225 /*
 4226  *      Increase the starting virtual address of the given mapping if a
 4227  *      different alignment might result in more superpage mappings.
 4228  */
 4229 void
 4230 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
 4231     vm_offset_t *addr, vm_size_t size)
 4232 {
 4233         vm_offset_t superpage_offset;
 4234 
 4235         if (size < NBPDR)
 4236                 return;
 4237         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
 4238                 offset += ptoa(object->pg_color);
 4239         superpage_offset = offset & PDRMASK;
 4240         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
 4241             (*addr & PDRMASK) == superpage_offset)
 4242                 return;
 4243         if ((*addr & PDRMASK) < superpage_offset)
 4244                 *addr = (*addr & ~PDRMASK) + superpage_offset;
 4245         else
 4246                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
 4247 }
 4248 
 4249 void
 4250 pmap_suspend()
 4251 {
 4252         pmap_t pmap;
 4253         int i, pdir, offset;
 4254         vm_paddr_t pdirma;
 4255         mmu_update_t mu[4];
 4256 
 4257         /*
 4258          * We need to remove the recursive mapping structure from all
 4259          * our pmaps so that Xen doesn't get confused when it restores
 4260          * the page tables. The recursive map lives at page directory
 4261          * index PTDPTDI. We assume that the suspend code has stopped
 4262          * the other vcpus (if any).
 4263          */
 4264         LIST_FOREACH(pmap, &allpmaps, pm_list) {
 4265                 for (i = 0; i < 4; i++) {
 4266                         /*
 4267                          * Figure out which page directory (L2) page
 4268                          * contains this bit of the recursive map and
 4269                          * the offset within that page of the map
 4270                          * entry
 4271                          */
 4272                         pdir = (PTDPTDI + i) / NPDEPG;
 4273                         offset = (PTDPTDI + i) % NPDEPG;
 4274                         pdirma = pmap->pm_pdpt[pdir] & PG_FRAME;
 4275                         mu[i].ptr = pdirma + offset * sizeof(pd_entry_t);
 4276                         mu[i].val = 0;
 4277                 }
 4278                 HYPERVISOR_mmu_update(mu, 4, NULL, DOMID_SELF);
 4279         }
 4280 }
 4281 
 4282 void
 4283 pmap_resume()
 4284 {
 4285         pmap_t pmap;
 4286         int i, pdir, offset;
 4287         vm_paddr_t pdirma;
 4288         mmu_update_t mu[4];
 4289 
 4290         /*
 4291          * Restore the recursive map that we removed on suspend.
 4292          */
 4293         LIST_FOREACH(pmap, &allpmaps, pm_list) {
 4294                 for (i = 0; i < 4; i++) {
 4295                         /*
 4296                          * Figure out which page directory (L2) page
 4297                          * contains this bit of the recursive map and
 4298                          * the offset within that page of the map
 4299                          * entry
 4300                          */
 4301                         pdir = (PTDPTDI + i) / NPDEPG;
 4302                         offset = (PTDPTDI + i) % NPDEPG;
 4303                         pdirma = pmap->pm_pdpt[pdir] & PG_FRAME;
 4304                         mu[i].ptr = pdirma + offset * sizeof(pd_entry_t);
 4305                         mu[i].val = (pmap->pm_pdpt[i] & PG_FRAME) | PG_V;
 4306                 }
 4307                 HYPERVISOR_mmu_update(mu, 4, NULL, DOMID_SELF);
 4308         }
 4309 }
 4310 
 4311 #if defined(PMAP_DEBUG)
 4312 pmap_pid_dump(int pid)
 4313 {
 4314         pmap_t pmap;
 4315         struct proc *p;
 4316         int npte = 0;
 4317         int index;
 4318 
 4319         sx_slock(&allproc_lock);
 4320         FOREACH_PROC_IN_SYSTEM(p) {
 4321                 if (p->p_pid != pid)
 4322                         continue;
 4323 
 4324                 if (p->p_vmspace) {
 4325                         int i,j;
 4326                         index = 0;
 4327                         pmap = vmspace_pmap(p->p_vmspace);
 4328                         for (i = 0; i < NPDEPTD; i++) {
 4329                                 pd_entry_t *pde;
 4330                                 pt_entry_t *pte;
 4331                                 vm_offset_t base = i << PDRSHIFT;
 4332                                 
 4333                                 pde = &pmap->pm_pdir[i];
 4334                                 if (pde && pmap_pde_v(pde)) {
 4335                                         for (j = 0; j < NPTEPG; j++) {
 4336                                                 vm_offset_t va = base + (j << PAGE_SHIFT);
 4337                                                 if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
 4338                                                         if (index) {
 4339                                                                 index = 0;
 4340                                                                 printf("\n");
 4341                                                         }
 4342                                                         sx_sunlock(&allproc_lock);
 4343                                                         return (npte);
 4344                                                 }
 4345                                                 pte = pmap_pte(pmap, va);
 4346                                                 if (pte && pmap_pte_v(pte)) {
 4347                                                         pt_entry_t pa;
 4348                                                         vm_page_t m;
 4349                                                         pa = PT_GET(pte);
 4350                                                         m = PHYS_TO_VM_PAGE(pa & PG_FRAME);
 4351                                                         printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
 4352                                                                 va, pa, m->hold_count, m->wire_count, m->flags);
 4353                                                         npte++;
 4354                                                         index++;
 4355                                                         if (index >= 2) {
 4356                                                                 index = 0;
 4357                                                                 printf("\n");
 4358                                                         } else {
 4359                                                                 printf(" ");
 4360                                                         }
 4361                                                 }
 4362                                         }
 4363                                 }
 4364                         }
 4365                 }
 4366         }
 4367         sx_sunlock(&allproc_lock);
 4368         return (npte);
 4369 }
 4370 #endif
 4371 
 4372 #if defined(DEBUG)
 4373 
 4374 static void     pads(pmap_t pm);
 4375 void            pmap_pvdump(vm_paddr_t pa);
 4376 
 4377 /* print address space of pmap*/
 4378 static void
 4379 pads(pmap_t pm)
 4380 {
 4381         int i, j;
 4382         vm_paddr_t va;
 4383         pt_entry_t *ptep;
 4384 
 4385         if (pm == kernel_pmap)
 4386                 return;
 4387         for (i = 0; i < NPDEPTD; i++)
 4388                 if (pm->pm_pdir[i])
 4389                         for (j = 0; j < NPTEPG; j++) {
 4390                                 va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
 4391                                 if (pm == kernel_pmap && va < KERNBASE)
 4392                                         continue;
 4393                                 if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
 4394                                         continue;
 4395                                 ptep = pmap_pte(pm, va);
 4396                                 if (pmap_pte_v(ptep))
 4397                                         printf("%x:%x ", va, *ptep);
 4398                         };
 4399 
 4400 }
 4401 
 4402 void
 4403 pmap_pvdump(vm_paddr_t pa)
 4404 {
 4405         pv_entry_t pv;
 4406         pmap_t pmap;
 4407         vm_page_t m;
 4408 
 4409         printf("pa %x", pa);
 4410         m = PHYS_TO_VM_PAGE(pa);
 4411         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 4412                 pmap = PV_PMAP(pv);
 4413                 printf(" -> pmap %p, va %x", (void *)pmap, pv->pv_va);
 4414                 pads(pmap);
 4415         }
 4416         printf(" ");
 4417 }
 4418 #endif

Cache object: 9b046dd1b0c862e0add4dc7f4b112fe9


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


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.