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

Cache object: 57a3d19a3440f68e536b05513240f69f


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