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.2/sys/i386/xen/pmap.c 217130 2011-01-07 23:11:19Z cperciva $");
   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         cpumask_t cpumask, other_cpus;
  855 
  856         CTR2(KTR_PMAP, "pmap_invalidate_page: pmap=%p va=0x%x",
  857             pmap, va);
  858         
  859         sched_pin();
  860         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
  861                 invlpg(va);
  862                 smp_invlpg(va);
  863         } else {
  864                 cpumask = PCPU_GET(cpumask);
  865                 other_cpus = PCPU_GET(other_cpus);
  866                 if (pmap->pm_active & cpumask)
  867                         invlpg(va);
  868                 if (pmap->pm_active & other_cpus)
  869                         smp_masked_invlpg(pmap->pm_active & other_cpus, va);
  870         }
  871         sched_unpin();
  872         PT_UPDATES_FLUSH();
  873 }
  874 
  875 void
  876 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
  877 {
  878         cpumask_t cpumask, other_cpus;
  879         vm_offset_t addr;
  880 
  881         CTR3(KTR_PMAP, "pmap_invalidate_page: pmap=%p eva=0x%x sva=0x%x",
  882             pmap, sva, eva);
  883 
  884         sched_pin();
  885         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
  886                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
  887                         invlpg(addr);
  888                 smp_invlpg_range(sva, eva);
  889         } else {
  890                 cpumask = PCPU_GET(cpumask);
  891                 other_cpus = PCPU_GET(other_cpus);
  892                 if (pmap->pm_active & cpumask)
  893                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
  894                                 invlpg(addr);
  895                 if (pmap->pm_active & other_cpus)
  896                         smp_masked_invlpg_range(pmap->pm_active & other_cpus,
  897                             sva, eva);
  898         }
  899         sched_unpin();
  900         PT_UPDATES_FLUSH();
  901 }
  902 
  903 void
  904 pmap_invalidate_all(pmap_t pmap)
  905 {
  906         cpumask_t cpumask, other_cpus;
  907 
  908         CTR1(KTR_PMAP, "pmap_invalidate_page: pmap=%p", pmap);
  909 
  910         sched_pin();
  911         if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
  912                 invltlb();
  913                 smp_invltlb();
  914         } else {
  915                 cpumask = PCPU_GET(cpumask);
  916                 other_cpus = PCPU_GET(other_cpus);
  917                 if (pmap->pm_active & cpumask)
  918                         invltlb();
  919                 if (pmap->pm_active & other_cpus)
  920                         smp_masked_invltlb(pmap->pm_active & other_cpus);
  921         }
  922         sched_unpin();
  923 }
  924 
  925 void
  926 pmap_invalidate_cache(void)
  927 {
  928 
  929         sched_pin();
  930         wbinvd();
  931         smp_cache_flush();
  932         sched_unpin();
  933 }
  934 #else /* !SMP */
  935 /*
  936  * Normal, non-SMP, 486+ invalidation functions.
  937  * We inline these within pmap.c for speed.
  938  */
  939 PMAP_INLINE void
  940 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
  941 {
  942         CTR2(KTR_PMAP, "pmap_invalidate_page: pmap=%p va=0x%x",
  943             pmap, va);
  944 
  945         if (pmap == kernel_pmap || pmap->pm_active)
  946                 invlpg(va);
  947         PT_UPDATES_FLUSH();
  948 }
  949 
  950 PMAP_INLINE void
  951 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
  952 {
  953         vm_offset_t addr;
  954 
  955         if (eva - sva > PAGE_SIZE)
  956                 CTR3(KTR_PMAP, "pmap_invalidate_range: pmap=%p sva=0x%x eva=0x%x",
  957                     pmap, sva, eva);
  958 
  959         if (pmap == kernel_pmap || pmap->pm_active)
  960                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
  961                         invlpg(addr);
  962         PT_UPDATES_FLUSH();
  963 }
  964 
  965 PMAP_INLINE void
  966 pmap_invalidate_all(pmap_t pmap)
  967 {
  968 
  969         CTR1(KTR_PMAP, "pmap_invalidate_all: pmap=%p", pmap);
  970         
  971         if (pmap == kernel_pmap || pmap->pm_active)
  972                 invltlb();
  973 }
  974 
  975 PMAP_INLINE void
  976 pmap_invalidate_cache(void)
  977 {
  978 
  979         wbinvd();
  980 }
  981 #endif /* !SMP */
  982 
  983 void
  984 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
  985 {
  986 
  987         KASSERT((sva & PAGE_MASK) == 0,
  988             ("pmap_invalidate_cache_range: sva not page-aligned"));
  989         KASSERT((eva & PAGE_MASK) == 0,
  990             ("pmap_invalidate_cache_range: eva not page-aligned"));
  991 
  992         if (cpu_feature & CPUID_SS)
  993                 ; /* If "Self Snoop" is supported, do nothing. */
  994         else if (cpu_feature & CPUID_CLFSH) {
  995 
  996                 /*
  997                  * Otherwise, do per-cache line flush.  Use the mfence
  998                  * instruction to insure that previous stores are
  999                  * included in the write-back.  The processor
 1000                  * propagates flush to other processors in the cache
 1001                  * coherence domain.
 1002                  */
 1003                 mfence();
 1004                 for (; sva < eva; sva += cpu_clflush_line_size)
 1005                         clflush(sva);
 1006                 mfence();
 1007         } else {
 1008 
 1009                 /*
 1010                  * No targeted cache flush methods are supported by CPU,
 1011                  * globally invalidate cache as a last resort.
 1012                  */
 1013                 pmap_invalidate_cache();
 1014         }
 1015 }
 1016 
 1017 /*
 1018  * Are we current address space or kernel?  N.B. We return FALSE when
 1019  * a pmap's page table is in use because a kernel thread is borrowing
 1020  * it.  The borrowed page table can change spontaneously, making any
 1021  * dependence on its continued use subject to a race condition.
 1022  */
 1023 static __inline int
 1024 pmap_is_current(pmap_t pmap)
 1025 {
 1026 
 1027         return (pmap == kernel_pmap ||
 1028             (pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
 1029                 (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
 1030 }
 1031 
 1032 /*
 1033  * If the given pmap is not the current or kernel pmap, the returned pte must
 1034  * be released by passing it to pmap_pte_release().
 1035  */
 1036 pt_entry_t *
 1037 pmap_pte(pmap_t pmap, vm_offset_t va)
 1038 {
 1039         pd_entry_t newpf;
 1040         pd_entry_t *pde;
 1041 
 1042         pde = pmap_pde(pmap, va);
 1043         if (*pde & PG_PS)
 1044                 return (pde);
 1045         if (*pde != 0) {
 1046                 /* are we current address space or kernel? */
 1047                 if (pmap_is_current(pmap))
 1048                         return (vtopte(va));
 1049                 mtx_lock(&PMAP2mutex);
 1050                 newpf = *pde & PG_FRAME;
 1051                 if ((*PMAP2 & PG_FRAME) != newpf) {
 1052                         PT_SET_MA(PADDR2, newpf | PG_V | PG_A | PG_M);
 1053                         CTR3(KTR_PMAP, "pmap_pte: pmap=%p va=0x%x newpte=0x%08x",
 1054                             pmap, va, (*PMAP2 & 0xffffffff));
 1055                 }
 1056                 
 1057                 return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
 1058         }
 1059         return (0);
 1060 }
 1061 
 1062 /*
 1063  * Releases a pte that was obtained from pmap_pte().  Be prepared for the pte
 1064  * being NULL.
 1065  */
 1066 static __inline void
 1067 pmap_pte_release(pt_entry_t *pte)
 1068 {
 1069 
 1070         if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2) {
 1071                 CTR1(KTR_PMAP, "pmap_pte_release: pte=0x%jx",
 1072                     *PMAP2);
 1073                 vm_page_lock_queues();
 1074                 PT_SET_VA(PMAP2, 0, TRUE);
 1075                 vm_page_unlock_queues();
 1076                 mtx_unlock(&PMAP2mutex);
 1077         }
 1078 }
 1079 
 1080 static __inline void
 1081 invlcaddr(void *caddr)
 1082 {
 1083 
 1084         invlpg((u_int)caddr);
 1085         PT_UPDATES_FLUSH();
 1086 }
 1087 
 1088 /*
 1089  * Super fast pmap_pte routine best used when scanning
 1090  * the pv lists.  This eliminates many coarse-grained
 1091  * invltlb calls.  Note that many of the pv list
 1092  * scans are across different pmaps.  It is very wasteful
 1093  * to do an entire invltlb for checking a single mapping.
 1094  *
 1095  * If the given pmap is not the current pmap, vm_page_queue_mtx
 1096  * must be held and curthread pinned to a CPU.
 1097  */
 1098 static pt_entry_t *
 1099 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
 1100 {
 1101         pd_entry_t newpf;
 1102         pd_entry_t *pde;
 1103 
 1104         pde = pmap_pde(pmap, va);
 1105         if (*pde & PG_PS)
 1106                 return (pde);
 1107         if (*pde != 0) {
 1108                 /* are we current address space or kernel? */
 1109                 if (pmap_is_current(pmap))
 1110                         return (vtopte(va));
 1111                 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 1112                 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
 1113                 newpf = *pde & PG_FRAME;
 1114                 if ((*PMAP1 & PG_FRAME) != newpf) {
 1115                         PT_SET_MA(PADDR1, newpf | PG_V | PG_A | PG_M);
 1116                         CTR3(KTR_PMAP, "pmap_pte_quick: pmap=%p va=0x%x newpte=0x%08x",
 1117                             pmap, va, (u_long)*PMAP1);
 1118                         
 1119 #ifdef SMP
 1120                         PMAP1cpu = PCPU_GET(cpuid);
 1121 #endif
 1122                         PMAP1changed++;
 1123                 } else
 1124 #ifdef SMP
 1125                 if (PMAP1cpu != PCPU_GET(cpuid)) {
 1126                         PMAP1cpu = PCPU_GET(cpuid);
 1127                         invlcaddr(PADDR1);
 1128                         PMAP1changedcpu++;
 1129                 } else
 1130 #endif
 1131                         PMAP1unchanged++;
 1132                 return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
 1133         }
 1134         return (0);
 1135 }
 1136 
 1137 /*
 1138  *      Routine:        pmap_extract
 1139  *      Function:
 1140  *              Extract the physical page address associated
 1141  *              with the given map/virtual_address pair.
 1142  */
 1143 vm_paddr_t 
 1144 pmap_extract(pmap_t pmap, vm_offset_t va)
 1145 {
 1146         vm_paddr_t rtval;
 1147         pt_entry_t *pte;
 1148         pd_entry_t pde;
 1149         pt_entry_t pteval;
 1150         
 1151         rtval = 0;
 1152         PMAP_LOCK(pmap);
 1153         pde = pmap->pm_pdir[va >> PDRSHIFT];
 1154         if (pde != 0) {
 1155                 if ((pde & PG_PS) != 0) {
 1156                         rtval = xpmap_mtop(pde & PG_PS_FRAME) | (va & PDRMASK);
 1157                         PMAP_UNLOCK(pmap);
 1158                         return rtval;
 1159                 }
 1160                 pte = pmap_pte(pmap, va);
 1161                 pteval = *pte ? xpmap_mtop(*pte) : 0;
 1162                 rtval = (pteval & PG_FRAME) | (va & PAGE_MASK);
 1163                 pmap_pte_release(pte);
 1164         }
 1165         PMAP_UNLOCK(pmap);
 1166         return (rtval);
 1167 }
 1168 
 1169 /*
 1170  *      Routine:        pmap_extract_ma
 1171  *      Function:
 1172  *              Like pmap_extract, but returns machine address
 1173  */
 1174 vm_paddr_t 
 1175 pmap_extract_ma(pmap_t pmap, vm_offset_t va)
 1176 {
 1177         vm_paddr_t rtval;
 1178         pt_entry_t *pte;
 1179         pd_entry_t pde;
 1180 
 1181         rtval = 0;
 1182         PMAP_LOCK(pmap);
 1183         pde = pmap->pm_pdir[va >> PDRSHIFT];
 1184         if (pde != 0) {
 1185                 if ((pde & PG_PS) != 0) {
 1186                         rtval = (pde & ~PDRMASK) | (va & PDRMASK);
 1187                         PMAP_UNLOCK(pmap);
 1188                         return rtval;
 1189                 }
 1190                 pte = pmap_pte(pmap, va);
 1191                 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
 1192                 pmap_pte_release(pte);
 1193         }
 1194         PMAP_UNLOCK(pmap);
 1195         return (rtval);
 1196 }
 1197 
 1198 /*
 1199  *      Routine:        pmap_extract_and_hold
 1200  *      Function:
 1201  *              Atomically extract and hold the physical page
 1202  *              with the given pmap and virtual address pair
 1203  *              if that mapping permits the given protection.
 1204  */
 1205 vm_page_t
 1206 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
 1207 {
 1208         pd_entry_t pde;
 1209         pt_entry_t pte;
 1210         vm_page_t m;
 1211 
 1212         m = NULL;
 1213         vm_page_lock_queues();
 1214         PMAP_LOCK(pmap);
 1215         pde = PT_GET(pmap_pde(pmap, va));
 1216         if (pde != 0) {
 1217                 if (pde & PG_PS) {
 1218                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
 1219                                 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
 1220                                     (va & PDRMASK));
 1221                                 vm_page_hold(m);
 1222                         }
 1223                 } else {
 1224                         sched_pin();
 1225                         pte = PT_GET(pmap_pte_quick(pmap, va));
 1226                         if (*PMAP1)
 1227                                 PT_SET_MA(PADDR1, 0);
 1228                         if ((pte & PG_V) &&
 1229                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
 1230                                 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
 1231                                 vm_page_hold(m);
 1232                         }
 1233                         sched_unpin();
 1234                 }
 1235         }
 1236         vm_page_unlock_queues();
 1237         PMAP_UNLOCK(pmap);
 1238         return (m);
 1239 }
 1240 
 1241 /***************************************************
 1242  * Low level mapping routines.....
 1243  ***************************************************/
 1244 
 1245 /*
 1246  * Add a wired page to the kva.
 1247  * Note: not SMP coherent.
 1248  */
 1249 void 
 1250 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
 1251 {
 1252         PT_SET_MA(va, xpmap_ptom(pa)| PG_RW | PG_V | pgeflag);
 1253 }
 1254 
 1255 void 
 1256 pmap_kenter_ma(vm_offset_t va, vm_paddr_t ma)
 1257 {
 1258         pt_entry_t *pte;
 1259 
 1260         pte = vtopte(va);
 1261         pte_store_ma(pte, ma | PG_RW | PG_V | pgeflag);
 1262 }
 1263 
 1264 
 1265 static __inline void 
 1266 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
 1267 {
 1268         PT_SET_MA(va, pa | PG_RW | PG_V | pgeflag | pmap_cache_bits(mode, 0));
 1269 }
 1270 
 1271 /*
 1272  * Remove a page from the kernel pagetables.
 1273  * Note: not SMP coherent.
 1274  */
 1275 PMAP_INLINE void
 1276 pmap_kremove(vm_offset_t va)
 1277 {
 1278         pt_entry_t *pte;
 1279 
 1280         pte = vtopte(va);
 1281         PT_CLEAR_VA(pte, FALSE);
 1282 }
 1283 
 1284 /*
 1285  *      Used to map a range of physical addresses into kernel
 1286  *      virtual address space.
 1287  *
 1288  *      The value passed in '*virt' is a suggested virtual address for
 1289  *      the mapping. Architectures which can support a direct-mapped
 1290  *      physical to virtual region can return the appropriate address
 1291  *      within that region, leaving '*virt' unchanged. Other
 1292  *      architectures should map the pages starting at '*virt' and
 1293  *      update '*virt' with the first usable address after the mapped
 1294  *      region.
 1295  */
 1296 vm_offset_t
 1297 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
 1298 {
 1299         vm_offset_t va, sva;
 1300 
 1301         va = sva = *virt;
 1302         CTR4(KTR_PMAP, "pmap_map: va=0x%x start=0x%jx end=0x%jx prot=0x%x",
 1303             va, start, end, prot);
 1304         while (start < end) {
 1305                 pmap_kenter(va, start);
 1306                 va += PAGE_SIZE;
 1307                 start += PAGE_SIZE;
 1308         }
 1309         pmap_invalidate_range(kernel_pmap, sva, va);
 1310         *virt = va;
 1311         return (sva);
 1312 }
 1313 
 1314 
 1315 /*
 1316  * Add a list of wired pages to the kva
 1317  * this routine is only used for temporary
 1318  * kernel mappings that do not need to have
 1319  * page modification or references recorded.
 1320  * Note that old mappings are simply written
 1321  * over.  The page *must* be wired.
 1322  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 1323  */
 1324 void
 1325 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
 1326 {
 1327         pt_entry_t *endpte, *pte;
 1328         vm_paddr_t pa;
 1329         vm_offset_t va = sva;
 1330         int mclcount = 0;
 1331         multicall_entry_t mcl[16];
 1332         multicall_entry_t *mclp = mcl;
 1333         int error;
 1334 
 1335         CTR2(KTR_PMAP, "pmap_qenter:sva=0x%x count=%d", va, count);
 1336         pte = vtopte(sva);
 1337         endpte = pte + count;
 1338         while (pte < endpte) {
 1339                 pa = xpmap_ptom(VM_PAGE_TO_PHYS(*ma)) | pgeflag | PG_RW | PG_V | PG_M | PG_A;
 1340 
 1341                 mclp->op = __HYPERVISOR_update_va_mapping;
 1342                 mclp->args[0] = va;
 1343                 mclp->args[1] = (uint32_t)(pa & 0xffffffff);
 1344                 mclp->args[2] = (uint32_t)(pa >> 32);
 1345                 mclp->args[3] = (*pte & PG_V) ? UVMF_INVLPG|UVMF_ALL : 0;
 1346         
 1347                 va += PAGE_SIZE;
 1348                 pte++;
 1349                 ma++;
 1350                 mclp++;
 1351                 mclcount++;
 1352                 if (mclcount == 16) {
 1353                         error = HYPERVISOR_multicall(mcl, mclcount);
 1354                         mclp = mcl;
 1355                         mclcount = 0;
 1356                         KASSERT(error == 0, ("bad multicall %d", error));
 1357                 }               
 1358         }
 1359         if (mclcount) {
 1360                 error = HYPERVISOR_multicall(mcl, mclcount);
 1361                 KASSERT(error == 0, ("bad multicall %d", error));
 1362         }
 1363         
 1364 #ifdef INVARIANTS
 1365         for (pte = vtopte(sva), mclcount = 0; mclcount < count; mclcount++, pte++)
 1366                 KASSERT(*pte, ("pte not set for va=0x%x", sva + mclcount*PAGE_SIZE));
 1367 #endif  
 1368 }
 1369 
 1370 
 1371 /*
 1372  * This routine tears out page mappings from the
 1373  * kernel -- it is meant only for temporary mappings.
 1374  * Note: SMP coherent.  Uses a ranged shootdown IPI.
 1375  */
 1376 void
 1377 pmap_qremove(vm_offset_t sva, int count)
 1378 {
 1379         vm_offset_t va;
 1380 
 1381         CTR2(KTR_PMAP, "pmap_qremove: sva=0x%x count=%d", sva, count);
 1382         va = sva;
 1383         vm_page_lock_queues();
 1384         critical_enter();
 1385         while (count-- > 0) {
 1386                 pmap_kremove(va);
 1387                 va += PAGE_SIZE;
 1388         }
 1389         PT_UPDATES_FLUSH();
 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 #if 0
 1861                 xen_pgd_unpin(ma);
 1862 #else
 1863                 if (i == NPGPTD)
 1864                         xen_pgd_unpin(ma);
 1865 #endif
 1866 #ifdef PAE
 1867                 if (i < NPGPTD)
 1868                         KASSERT(xpmap_ptom(VM_PAGE_TO_PHYS(m)) == (pmap->pm_pdpt[i] & PG_FRAME),
 1869                             ("pmap_release: got wrong ptd page"));
 1870 #endif
 1871                 m->wire_count--;
 1872                 atomic_subtract_int(&cnt.v_wire_count, 1);
 1873                 vm_page_free(m);
 1874         }
 1875 #ifdef PAE
 1876         pmap_qremove((vm_offset_t)pmap->pm_pdpt, 1);
 1877 #endif
 1878         PMAP_LOCK_DESTROY(pmap);
 1879 }
 1880 
 1881 static int
 1882 kvm_size(SYSCTL_HANDLER_ARGS)
 1883 {
 1884         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
 1885 
 1886         return sysctl_handle_long(oidp, &ksize, 0, req);
 1887 }
 1888 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
 1889     0, 0, kvm_size, "IU", "Size of KVM");
 1890 
 1891 static int
 1892 kvm_free(SYSCTL_HANDLER_ARGS)
 1893 {
 1894         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
 1895 
 1896         return sysctl_handle_long(oidp, &kfree, 0, req);
 1897 }
 1898 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
 1899     0, 0, kvm_free, "IU", "Amount of KVM free");
 1900 
 1901 /*
 1902  * grow the number of kernel page table entries, if needed
 1903  */
 1904 void
 1905 pmap_growkernel(vm_offset_t addr)
 1906 {
 1907         struct pmap *pmap;
 1908         vm_paddr_t ptppaddr;
 1909         vm_page_t nkpg;
 1910         pd_entry_t newpdir;
 1911 
 1912         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
 1913         if (kernel_vm_end == 0) {
 1914                 kernel_vm_end = KERNBASE;
 1915                 nkpt = 0;
 1916                 while (pdir_pde(PTD, kernel_vm_end)) {
 1917                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
 1918                         nkpt++;
 1919                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1920                                 kernel_vm_end = kernel_map->max_offset;
 1921                                 break;
 1922                         }
 1923                 }
 1924         }
 1925         addr = roundup2(addr, PAGE_SIZE * NPTEPG);
 1926         if (addr - 1 >= kernel_map->max_offset)
 1927                 addr = kernel_map->max_offset;
 1928         while (kernel_vm_end < addr) {
 1929                 if (pdir_pde(PTD, kernel_vm_end)) {
 1930                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
 1931                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1932                                 kernel_vm_end = kernel_map->max_offset;
 1933                                 break;
 1934                         }
 1935                         continue;
 1936                 }
 1937 
 1938                 /*
 1939                  * This index is bogus, but out of the way
 1940                  */
 1941                 nkpg = vm_page_alloc(NULL, nkpt,
 1942                     VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
 1943                 if (!nkpg)
 1944                         panic("pmap_growkernel: no memory to grow kernel");
 1945 
 1946                 nkpt++;
 1947 
 1948                 pmap_zero_page(nkpg);
 1949                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
 1950                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
 1951                 vm_page_lock_queues();
 1952                 PD_SET_VA(kernel_pmap, (kernel_vm_end >> PDRSHIFT), newpdir, TRUE);
 1953                 mtx_lock_spin(&allpmaps_lock);
 1954                 LIST_FOREACH(pmap, &allpmaps, pm_list)
 1955                         PD_SET_VA(pmap, (kernel_vm_end >> PDRSHIFT), newpdir, TRUE);
 1956 
 1957                 mtx_unlock_spin(&allpmaps_lock);
 1958                 vm_page_unlock_queues();
 1959 
 1960                 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
 1961                 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
 1962                         kernel_vm_end = kernel_map->max_offset;
 1963                         break;
 1964                 }
 1965         }
 1966 }
 1967 
 1968 
 1969 /***************************************************
 1970  * page management routines.
 1971  ***************************************************/
 1972 
 1973 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
 1974 CTASSERT(_NPCM == 11);
 1975 
 1976 static __inline struct pv_chunk *
 1977 pv_to_chunk(pv_entry_t pv)
 1978 {
 1979 
 1980         return (struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK);
 1981 }
 1982 
 1983 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
 1984 
 1985 #define PC_FREE0_9      0xfffffffful    /* Free values for index 0 through 9 */
 1986 #define PC_FREE10       0x0000fffful    /* Free values for index 10 */
 1987 
 1988 static uint32_t pc_freemask[11] = {
 1989         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1990         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1991         PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
 1992         PC_FREE0_9, PC_FREE10
 1993 };
 1994 
 1995 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
 1996         "Current number of pv entries");
 1997 
 1998 #ifdef PV_STATS
 1999 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
 2000 
 2001 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
 2002         "Current number of pv entry chunks");
 2003 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
 2004         "Current number of pv entry chunks allocated");
 2005 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
 2006         "Current number of pv entry chunks frees");
 2007 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
 2008         "Number of times tried to get a chunk page but failed.");
 2009 
 2010 static long pv_entry_frees, pv_entry_allocs;
 2011 static int pv_entry_spare;
 2012 
 2013 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
 2014         "Current number of pv entry frees");
 2015 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
 2016         "Current number of pv entry allocs");
 2017 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
 2018         "Current number of spare pv entries");
 2019 
 2020 static int pmap_collect_inactive, pmap_collect_active;
 2021 
 2022 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_inactive, CTLFLAG_RD, &pmap_collect_inactive, 0,
 2023         "Current number times pmap_collect called on inactive queue");
 2024 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_active, CTLFLAG_RD, &pmap_collect_active, 0,
 2025         "Current number times pmap_collect called on active queue");
 2026 #endif
 2027 
 2028 /*
 2029  * We are in a serious low memory condition.  Resort to
 2030  * drastic measures to free some pages so we can allocate
 2031  * another pv entry chunk.  This is normally called to
 2032  * unmap inactive pages, and if necessary, active pages.
 2033  */
 2034 static void
 2035 pmap_collect(pmap_t locked_pmap, struct vpgqueues *vpq)
 2036 {
 2037         pmap_t pmap;
 2038         pt_entry_t *pte, tpte;
 2039         pv_entry_t next_pv, pv;
 2040         vm_offset_t va;
 2041         vm_page_t m, free;
 2042 
 2043         sched_pin();
 2044         TAILQ_FOREACH(m, &vpq->pl, pageq) {
 2045                 if (m->hold_count || m->busy)
 2046                         continue;
 2047                 TAILQ_FOREACH_SAFE(pv, &m->md.pv_list, pv_list, next_pv) {
 2048                         va = pv->pv_va;
 2049                         pmap = PV_PMAP(pv);
 2050                         /* Avoid deadlock and lock recursion. */
 2051                         if (pmap > locked_pmap)
 2052                                 PMAP_LOCK(pmap);
 2053                         else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap))
 2054                                 continue;
 2055                         pmap->pm_stats.resident_count--;
 2056                         pte = pmap_pte_quick(pmap, va);
 2057                         tpte = pte_load_clear(pte);
 2058                         KASSERT((tpte & PG_W) == 0,
 2059                             ("pmap_collect: wired pte %#jx", (uintmax_t)tpte));
 2060                         if (tpte & PG_A)
 2061                                 vm_page_flag_set(m, PG_REFERENCED);
 2062                         if (tpte & PG_M) {
 2063                                 KASSERT((tpte & PG_RW),
 2064         ("pmap_collect: modified page not writable: va: %#x, pte: %#jx",
 2065                                     va, (uintmax_t)tpte));
 2066                                 vm_page_dirty(m);
 2067                         }
 2068                         free = NULL;
 2069                         pmap_unuse_pt(pmap, va, &free);
 2070                         pmap_invalidate_page(pmap, va);
 2071                         pmap_free_zero_pages(free);
 2072                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 2073                         if (TAILQ_EMPTY(&m->md.pv_list))
 2074                                 vm_page_flag_clear(m, PG_WRITEABLE);
 2075                         free_pv_entry(pmap, pv);
 2076                         if (pmap != locked_pmap)
 2077                                 PMAP_UNLOCK(pmap);
 2078                 }
 2079         }
 2080         sched_unpin();
 2081 }
 2082 
 2083 
 2084 /*
 2085  * free the pv_entry back to the free list
 2086  */
 2087 static void
 2088 free_pv_entry(pmap_t pmap, pv_entry_t pv)
 2089 {
 2090         vm_page_t m;
 2091         struct pv_chunk *pc;
 2092         int idx, field, bit;
 2093 
 2094         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2095         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2096         PV_STAT(pv_entry_frees++);
 2097         PV_STAT(pv_entry_spare++);
 2098         pv_entry_count--;
 2099         pc = pv_to_chunk(pv);
 2100         idx = pv - &pc->pc_pventry[0];
 2101         field = idx / 32;
 2102         bit = idx % 32;
 2103         pc->pc_map[field] |= 1ul << bit;
 2104         /* move to head of list */
 2105         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2106         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 2107         for (idx = 0; idx < _NPCM; idx++)
 2108                 if (pc->pc_map[idx] != pc_freemask[idx])
 2109                         return;
 2110         PV_STAT(pv_entry_spare -= _NPCPV);
 2111         PV_STAT(pc_chunk_count--);
 2112         PV_STAT(pc_chunk_frees++);
 2113         /* entire chunk is free, return it */
 2114         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2115         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
 2116         pmap_qremove((vm_offset_t)pc, 1);
 2117         vm_page_unwire(m, 0);
 2118         vm_page_free(m);
 2119         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
 2120 }
 2121 
 2122 /*
 2123  * get a new pv_entry, allocating a block from the system
 2124  * when needed.
 2125  */
 2126 static pv_entry_t
 2127 get_pv_entry(pmap_t pmap, int try)
 2128 {
 2129         static const struct timeval printinterval = { 60, 0 };
 2130         static struct timeval lastprint;
 2131         static vm_pindex_t colour;
 2132         struct vpgqueues *pq;
 2133         int bit, field;
 2134         pv_entry_t pv;
 2135         struct pv_chunk *pc;
 2136         vm_page_t m;
 2137 
 2138         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2139         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2140         PV_STAT(pv_entry_allocs++);
 2141         pv_entry_count++;
 2142         if (pv_entry_count > pv_entry_high_water)
 2143                 if (ratecheck(&lastprint, &printinterval))
 2144                         printf("Approaching the limit on PV entries, consider "
 2145                             "increasing either the vm.pmap.shpgperproc or the "
 2146                             "vm.pmap.pv_entry_max tunable.\n");
 2147         pq = NULL;
 2148 retry:
 2149         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
 2150         if (pc != NULL) {
 2151                 for (field = 0; field < _NPCM; field++) {
 2152                         if (pc->pc_map[field]) {
 2153                                 bit = bsfl(pc->pc_map[field]);
 2154                                 break;
 2155                         }
 2156                 }
 2157                 if (field < _NPCM) {
 2158                         pv = &pc->pc_pventry[field * 32 + bit];
 2159                         pc->pc_map[field] &= ~(1ul << bit);
 2160                         /* If this was the last item, move it to tail */
 2161                         for (field = 0; field < _NPCM; field++)
 2162                                 if (pc->pc_map[field] != 0) {
 2163                                         PV_STAT(pv_entry_spare--);
 2164                                         return (pv);    /* not full, return */
 2165                                 }
 2166                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 2167                         TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
 2168                         PV_STAT(pv_entry_spare--);
 2169                         return (pv);
 2170                 }
 2171         }
 2172         /*
 2173          * Access to the ptelist "pv_vafree" is synchronized by the page
 2174          * queues lock.  If "pv_vafree" is currently non-empty, it will
 2175          * remain non-empty until pmap_ptelist_alloc() completes.
 2176          */
 2177         if (pv_vafree == 0 || (m = vm_page_alloc(NULL, colour, (pq ==
 2178             &vm_page_queues[PQ_ACTIVE] ? VM_ALLOC_SYSTEM : VM_ALLOC_NORMAL) |
 2179             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
 2180                 if (try) {
 2181                         pv_entry_count--;
 2182                         PV_STAT(pc_chunk_tryfail++);
 2183                         return (NULL);
 2184                 }
 2185                 /*
 2186                  * Reclaim pv entries: At first, destroy mappings to
 2187                  * inactive pages.  After that, if a pv chunk entry
 2188                  * is still needed, destroy mappings to active pages.
 2189                  */
 2190                 if (pq == NULL) {
 2191                         PV_STAT(pmap_collect_inactive++);
 2192                         pq = &vm_page_queues[PQ_INACTIVE];
 2193                 } else if (pq == &vm_page_queues[PQ_INACTIVE]) {
 2194                         PV_STAT(pmap_collect_active++);
 2195                         pq = &vm_page_queues[PQ_ACTIVE];
 2196                 } else
 2197                         panic("get_pv_entry: increase vm.pmap.shpgperproc");
 2198                 pmap_collect(pmap, pq);
 2199                 goto retry;
 2200         }
 2201         PV_STAT(pc_chunk_count++);
 2202         PV_STAT(pc_chunk_allocs++);
 2203         colour++;
 2204         pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
 2205         pmap_qenter((vm_offset_t)pc, &m, 1);
 2206         if ((m->flags & PG_ZERO) == 0)
 2207                 pagezero(pc);
 2208         pc->pc_pmap = pmap;
 2209         pc->pc_map[0] = pc_freemask[0] & ~1ul;  /* preallocated bit 0 */
 2210         for (field = 1; field < _NPCM; field++)
 2211                 pc->pc_map[field] = pc_freemask[field];
 2212         pv = &pc->pc_pventry[0];
 2213         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
 2214         PV_STAT(pv_entry_spare += _NPCPV - 1);
 2215         return (pv);
 2216 }
 2217 
 2218 static void
 2219 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
 2220 {
 2221         pv_entry_t pv;
 2222 
 2223         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2224         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2225         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 2226                 if (pmap == PV_PMAP(pv) && va == pv->pv_va)
 2227                         break;
 2228         }
 2229         KASSERT(pv != NULL, ("pmap_remove_entry: pv not found"));
 2230         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 2231         if (TAILQ_EMPTY(&m->md.pv_list))
 2232                 vm_page_flag_clear(m, PG_WRITEABLE);
 2233         free_pv_entry(pmap, pv);
 2234 }
 2235 
 2236 /*
 2237  * Create a pv entry for page at pa for
 2238  * (pmap, va).
 2239  */
 2240 static void
 2241 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
 2242 {
 2243         pv_entry_t pv;
 2244 
 2245         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2246         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2247         pv = get_pv_entry(pmap, FALSE);
 2248         pv->pv_va = va;
 2249         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 2250 }
 2251 
 2252 /*
 2253  * Conditionally create a pv entry.
 2254  */
 2255 static boolean_t
 2256 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
 2257 {
 2258         pv_entry_t pv;
 2259 
 2260         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2261         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2262         if (pv_entry_count < pv_entry_high_water && 
 2263             (pv = get_pv_entry(pmap, TRUE)) != NULL) {
 2264                 pv->pv_va = va;
 2265                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 2266                 return (TRUE);
 2267         } else
 2268                 return (FALSE);
 2269 }
 2270 
 2271 /*
 2272  * pmap_remove_pte: do the things to unmap a page in a process
 2273  */
 2274 static int
 2275 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, vm_page_t *free)
 2276 {
 2277         pt_entry_t oldpte;
 2278         vm_page_t m;
 2279 
 2280         CTR3(KTR_PMAP, "pmap_remove_pte: pmap=%p *ptq=0x%x va=0x%x",
 2281             pmap, (u_long)*ptq, va);
 2282         
 2283         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2284         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2285         oldpte = *ptq;
 2286         PT_SET_VA_MA(ptq, 0, TRUE);
 2287         if (oldpte & PG_W)
 2288                 pmap->pm_stats.wired_count -= 1;
 2289         /*
 2290          * Machines that don't support invlpg, also don't support
 2291          * PG_G.
 2292          */
 2293         if (oldpte & PG_G)
 2294                 pmap_invalidate_page(kernel_pmap, va);
 2295         pmap->pm_stats.resident_count -= 1;
 2296         if (oldpte & PG_MANAGED) {
 2297                 m = PHYS_TO_VM_PAGE(xpmap_mtop(oldpte) & PG_FRAME);
 2298                 if (oldpte & PG_M) {
 2299                         KASSERT((oldpte & PG_RW),
 2300         ("pmap_remove_pte: modified page not writable: va: %#x, pte: %#jx",
 2301                             va, (uintmax_t)oldpte));
 2302                         vm_page_dirty(m);
 2303                 }
 2304                 if (oldpte & PG_A)
 2305                         vm_page_flag_set(m, PG_REFERENCED);
 2306                 pmap_remove_entry(pmap, m, va);
 2307         }
 2308         return (pmap_unuse_pt(pmap, va, free));
 2309 }
 2310 
 2311 /*
 2312  * Remove a single page from a process address space
 2313  */
 2314 static void
 2315 pmap_remove_page(pmap_t pmap, vm_offset_t va, vm_page_t *free)
 2316 {
 2317         pt_entry_t *pte;
 2318 
 2319         CTR2(KTR_PMAP, "pmap_remove_page: pmap=%p va=0x%x",
 2320             pmap, va);
 2321         
 2322         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2323         KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
 2324         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2325         if ((pte = pmap_pte_quick(pmap, va)) == NULL || (*pte & PG_V) == 0)
 2326                 return;
 2327         pmap_remove_pte(pmap, pte, va, free);
 2328         pmap_invalidate_page(pmap, va);
 2329         if (*PMAP1)
 2330                 PT_SET_MA(PADDR1, 0);
 2331 
 2332 }
 2333 
 2334 /*
 2335  *      Remove the given range of addresses from the specified map.
 2336  *
 2337  *      It is assumed that the start and end are properly
 2338  *      rounded to the page size.
 2339  */
 2340 void
 2341 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
 2342 {
 2343         vm_offset_t pdnxt;
 2344         pd_entry_t ptpaddr;
 2345         pt_entry_t *pte;
 2346         vm_page_t free = NULL;
 2347         int anyvalid;
 2348         
 2349         CTR3(KTR_PMAP, "pmap_remove: pmap=%p sva=0x%x eva=0x%x",
 2350             pmap, sva, eva);
 2351         
 2352         /*
 2353          * Perform an unsynchronized read.  This is, however, safe.
 2354          */
 2355         if (pmap->pm_stats.resident_count == 0)
 2356                 return;
 2357 
 2358         anyvalid = 0;
 2359 
 2360         vm_page_lock_queues();
 2361         sched_pin();
 2362         PMAP_LOCK(pmap);
 2363 
 2364         /*
 2365          * special handling of removing one page.  a very
 2366          * common operation and easy to short circuit some
 2367          * code.
 2368          */
 2369         if ((sva + PAGE_SIZE == eva) && 
 2370             ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
 2371                 pmap_remove_page(pmap, sva, &free);
 2372                 goto out;
 2373         }
 2374 
 2375         for (; sva < eva; sva = pdnxt) {
 2376                 unsigned pdirindex;
 2377 
 2378                 /*
 2379                  * Calculate index for next page table.
 2380                  */
 2381                 pdnxt = (sva + NBPDR) & ~PDRMASK;
 2382                 if (pmap->pm_stats.resident_count == 0)
 2383                         break;
 2384 
 2385                 pdirindex = sva >> PDRSHIFT;
 2386                 ptpaddr = pmap->pm_pdir[pdirindex];
 2387 
 2388                 /*
 2389                  * Weed out invalid mappings. Note: we assume that the page
 2390                  * directory table is always allocated, and in kernel virtual.
 2391                  */
 2392                 if (ptpaddr == 0)
 2393                         continue;
 2394 
 2395                 /*
 2396                  * Check for large page.
 2397                  */
 2398                 if ((ptpaddr & PG_PS) != 0) {
 2399                         PD_CLEAR_VA(pmap, pdirindex, TRUE);
 2400                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
 2401                         anyvalid = 1;
 2402                         continue;
 2403                 }
 2404 
 2405                 /*
 2406                  * Limit our scan to either the end of the va represented
 2407                  * by the current page table page, or to the end of the
 2408                  * range being removed.
 2409                  */
 2410                 if (pdnxt > eva)
 2411                         pdnxt = eva;
 2412 
 2413                 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
 2414                     sva += PAGE_SIZE) {
 2415                         if ((*pte & PG_V) == 0)
 2416                                 continue;
 2417 
 2418                         /*
 2419                          * The TLB entry for a PG_G mapping is invalidated
 2420                          * by pmap_remove_pte().
 2421                          */
 2422                         if ((*pte & PG_G) == 0)
 2423                                 anyvalid = 1;
 2424                         if (pmap_remove_pte(pmap, pte, sva, &free))
 2425                                 break;
 2426                 }
 2427         }
 2428         PT_UPDATES_FLUSH();
 2429         if (*PMAP1)
 2430                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2431 out:
 2432         if (anyvalid)
 2433                 pmap_invalidate_all(pmap);
 2434         sched_unpin();
 2435         vm_page_unlock_queues();
 2436         PMAP_UNLOCK(pmap);
 2437         pmap_free_zero_pages(free);
 2438 }
 2439 
 2440 /*
 2441  *      Routine:        pmap_remove_all
 2442  *      Function:
 2443  *              Removes this physical page from
 2444  *              all physical maps in which it resides.
 2445  *              Reflects back modify bits to the pager.
 2446  *
 2447  *      Notes:
 2448  *              Original versions of this routine were very
 2449  *              inefficient because they iteratively called
 2450  *              pmap_remove (slow...)
 2451  */
 2452 
 2453 void
 2454 pmap_remove_all(vm_page_t m)
 2455 {
 2456         pv_entry_t pv;
 2457         pmap_t pmap;
 2458         pt_entry_t *pte, tpte;
 2459         vm_page_t free;
 2460 
 2461 #if defined(PMAP_DIAGNOSTIC)
 2462         /*
 2463          * XXX This makes pmap_remove_all() illegal for non-managed pages!
 2464          */
 2465         if (m->flags & PG_FICTITIOUS) {
 2466                 panic("pmap_remove_all: illegal for unmanaged page, va: 0x%jx",
 2467                     VM_PAGE_TO_PHYS(m) & 0xffffffff);
 2468         }
 2469 #endif
 2470         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2471         sched_pin();
 2472         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 2473                 pmap = PV_PMAP(pv);
 2474                 PMAP_LOCK(pmap);
 2475                 pmap->pm_stats.resident_count--;
 2476                 pte = pmap_pte_quick(pmap, pv->pv_va);
 2477 
 2478                 tpte = *pte;
 2479                 PT_SET_VA_MA(pte, 0, TRUE);
 2480                 if (tpte & PG_W)
 2481                         pmap->pm_stats.wired_count--;
 2482                 if (tpte & PG_A)
 2483                         vm_page_flag_set(m, PG_REFERENCED);
 2484 
 2485                 /*
 2486                  * Update the vm_page_t clean and reference bits.
 2487                  */
 2488                 if (tpte & PG_M) {
 2489                         KASSERT((tpte & PG_RW),
 2490         ("pmap_remove_all: modified page not writable: va: %#x, pte: %#jx",
 2491                             pv->pv_va, (uintmax_t)tpte));
 2492                         vm_page_dirty(m);
 2493                 }
 2494                 free = NULL;
 2495                 pmap_unuse_pt(pmap, pv->pv_va, &free);
 2496                 pmap_invalidate_page(pmap, pv->pv_va);
 2497                 pmap_free_zero_pages(free);
 2498                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 2499                 free_pv_entry(pmap, pv);
 2500                 PMAP_UNLOCK(pmap);
 2501         }
 2502         vm_page_flag_clear(m, PG_WRITEABLE);
 2503         PT_UPDATES_FLUSH();
 2504         if (*PMAP1)
 2505                 PT_SET_MA(PADDR1, 0);
 2506         sched_unpin();
 2507 }
 2508 
 2509 /*
 2510  *      Set the physical protection on the
 2511  *      specified range of this map as requested.
 2512  */
 2513 void
 2514 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
 2515 {
 2516         vm_offset_t pdnxt;
 2517         pd_entry_t ptpaddr;
 2518         pt_entry_t *pte;
 2519         int anychanged;
 2520 
 2521         CTR4(KTR_PMAP, "pmap_protect: pmap=%p sva=0x%x eva=0x%x prot=0x%x",
 2522             pmap, sva, eva, prot);
 2523         
 2524         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
 2525                 pmap_remove(pmap, sva, eva);
 2526                 return;
 2527         }
 2528 
 2529 #ifdef PAE
 2530         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
 2531             (VM_PROT_WRITE|VM_PROT_EXECUTE))
 2532                 return;
 2533 #else
 2534         if (prot & VM_PROT_WRITE)
 2535                 return;
 2536 #endif
 2537 
 2538         anychanged = 0;
 2539 
 2540         vm_page_lock_queues();
 2541         sched_pin();
 2542         PMAP_LOCK(pmap);
 2543         for (; sva < eva; sva = pdnxt) {
 2544                 pt_entry_t obits, pbits;
 2545                 unsigned pdirindex;
 2546 
 2547                 pdnxt = (sva + NBPDR) & ~PDRMASK;
 2548 
 2549                 pdirindex = sva >> PDRSHIFT;
 2550                 ptpaddr = pmap->pm_pdir[pdirindex];
 2551 
 2552                 /*
 2553                  * Weed out invalid mappings. Note: we assume that the page
 2554                  * directory table is always allocated, and in kernel virtual.
 2555                  */
 2556                 if (ptpaddr == 0)
 2557                         continue;
 2558 
 2559                 /*
 2560                  * Check for large page.
 2561                  */
 2562                 if ((ptpaddr & PG_PS) != 0) {
 2563                         if ((prot & VM_PROT_WRITE) == 0)
 2564                                 pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
 2565 #ifdef PAE
 2566                         if ((prot & VM_PROT_EXECUTE) == 0)
 2567                                 pmap->pm_pdir[pdirindex] |= pg_nx;
 2568 #endif
 2569                         anychanged = 1;
 2570                         continue;
 2571                 }
 2572 
 2573                 if (pdnxt > eva)
 2574                         pdnxt = eva;
 2575 
 2576                 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
 2577                     sva += PAGE_SIZE) {
 2578                         vm_page_t m;
 2579 
 2580 retry:
 2581                         /*
 2582                          * Regardless of whether a pte is 32 or 64 bits in
 2583                          * size, PG_RW, PG_A, and PG_M are among the least
 2584                          * significant 32 bits.
 2585                          */
 2586                         obits = pbits = *pte;
 2587                         if ((pbits & PG_V) == 0)
 2588                                 continue;
 2589                         if (pbits & PG_MANAGED) {
 2590                                 m = NULL;
 2591                                 if (pbits & PG_A) {
 2592                                         m = PHYS_TO_VM_PAGE(xpmap_mtop(pbits) & PG_FRAME);
 2593                                         vm_page_flag_set(m, PG_REFERENCED);
 2594                                         pbits &= ~PG_A;
 2595                                 }
 2596                                 if ((pbits & PG_M) != 0) {
 2597                                         if (m == NULL)
 2598                                                 m = PHYS_TO_VM_PAGE(xpmap_mtop(pbits) & PG_FRAME);
 2599                                         vm_page_dirty(m);
 2600                                 }
 2601                         }
 2602 
 2603                         if ((prot & VM_PROT_WRITE) == 0)
 2604                                 pbits &= ~(PG_RW | PG_M);
 2605 #ifdef PAE
 2606                         if ((prot & VM_PROT_EXECUTE) == 0)
 2607                                 pbits |= pg_nx;
 2608 #endif
 2609 
 2610                         if (pbits != obits) {
 2611 #ifdef XEN
 2612                                 obits = *pte;
 2613                                 PT_SET_VA_MA(pte, pbits, TRUE);
 2614                                 if (*pte != pbits)
 2615                                         goto retry;
 2616 #else                           
 2617 #ifdef PAE
 2618                                 if (!atomic_cmpset_64(pte, obits, pbits))
 2619                                         goto retry;
 2620 #else
 2621                                 if (!atomic_cmpset_int((u_int *)pte, obits,
 2622                                     pbits))
 2623                                         goto retry;
 2624 #endif
 2625 #endif
 2626                                 if (obits & PG_G)
 2627                                         pmap_invalidate_page(pmap, sva);
 2628                                 else
 2629                                         anychanged = 1;
 2630                         }
 2631                 }
 2632         }
 2633         PT_UPDATES_FLUSH();
 2634         if (*PMAP1)
 2635                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2636         if (anychanged)
 2637                 pmap_invalidate_all(pmap);
 2638         sched_unpin();
 2639         vm_page_unlock_queues();
 2640         PMAP_UNLOCK(pmap);
 2641 }
 2642 
 2643 /*
 2644  *      Insert the given physical page (p) at
 2645  *      the specified virtual address (v) in the
 2646  *      target physical map with the protection requested.
 2647  *
 2648  *      If specified, the page will be wired down, meaning
 2649  *      that the related pte can not be reclaimed.
 2650  *
 2651  *      NB:  This is the only routine which MAY NOT lazy-evaluate
 2652  *      or lose information.  That is, this routine must actually
 2653  *      insert this page into the given map NOW.
 2654  */
 2655 void
 2656 pmap_enter(pmap_t pmap, vm_offset_t va, vm_prot_t access, vm_page_t m,
 2657     vm_prot_t prot, boolean_t wired)
 2658 {
 2659         vm_paddr_t pa;
 2660         pd_entry_t *pde;
 2661         pt_entry_t *pte;
 2662         vm_paddr_t opa;
 2663         pt_entry_t origpte, newpte;
 2664         vm_page_t mpte, om;
 2665         boolean_t invlva;
 2666 
 2667         CTR6(KTR_PMAP, "pmap_enter: pmap=%08p va=0x%08x access=0x%x ma=0x%08x prot=0x%x wired=%d",
 2668             pmap, va, access, xpmap_ptom(VM_PAGE_TO_PHYS(m)), prot, wired);
 2669         va = trunc_page(va);
 2670 #ifdef PMAP_DIAGNOSTIC
 2671         if (va > VM_MAX_KERNEL_ADDRESS)
 2672                 panic("pmap_enter: toobig");
 2673         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
 2674                 panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
 2675 #endif
 2676 
 2677         mpte = NULL;
 2678 
 2679         vm_page_lock_queues();
 2680         PMAP_LOCK(pmap);
 2681         sched_pin();
 2682 
 2683         /*
 2684          * In the case that a page table page is not
 2685          * resident, we are creating it here.
 2686          */
 2687         if (va < VM_MAXUSER_ADDRESS) {
 2688                 mpte = pmap_allocpte(pmap, va, M_WAITOK);
 2689         }
 2690 #if 0 && defined(PMAP_DIAGNOSTIC)
 2691         else {
 2692                 pd_entry_t *pdeaddr = pmap_pde(pmap, va);
 2693                 origpte = *pdeaddr;
 2694                 if ((origpte & PG_V) == 0) { 
 2695                         panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
 2696                                 pmap->pm_pdir[PTDPTDI], origpte, va);
 2697                 }
 2698         }
 2699 #endif
 2700 
 2701         pde = pmap_pde(pmap, va);
 2702         if ((*pde & PG_PS) != 0)
 2703                 panic("pmap_enter: attempted pmap_enter on 4MB page");
 2704         pte = pmap_pte_quick(pmap, va);
 2705 
 2706         /*
 2707          * Page Directory table entry not valid, we need a new PT page
 2708          */
 2709         if (pte == NULL) {
 2710                 panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
 2711                         (uintmax_t)pmap->pm_pdir[va >> PDRSHIFT], va);
 2712         }
 2713 
 2714         pa = VM_PAGE_TO_PHYS(m);
 2715         om = NULL;
 2716         opa = origpte = 0;
 2717 
 2718 #if 0
 2719         KASSERT((*pte & PG_V) || (*pte == 0), ("address set but not valid pte=%p *pte=0x%016jx",
 2720                 pte, *pte));
 2721 #endif
 2722         origpte = *pte;
 2723         if (origpte)
 2724                 origpte = xpmap_mtop(origpte);
 2725         opa = origpte & PG_FRAME;
 2726 
 2727         /*
 2728          * Mapping has not changed, must be protection or wiring change.
 2729          */
 2730         if (origpte && (opa == pa)) {
 2731                 /*
 2732                  * Wiring change, just update stats. We don't worry about
 2733                  * wiring PT pages as they remain resident as long as there
 2734                  * are valid mappings in them. Hence, if a user page is wired,
 2735                  * the PT page will be also.
 2736                  */
 2737                 if (wired && ((origpte & PG_W) == 0))
 2738                         pmap->pm_stats.wired_count++;
 2739                 else if (!wired && (origpte & PG_W))
 2740                         pmap->pm_stats.wired_count--;
 2741 
 2742                 /*
 2743                  * Remove extra pte reference
 2744                  */
 2745                 if (mpte)
 2746                         mpte->wire_count--;
 2747 
 2748                 /*
 2749                  * We might be turning off write access to the page,
 2750                  * so we go ahead and sense modify status.
 2751                  */
 2752                 if (origpte & PG_MANAGED) {
 2753                         om = m;
 2754                         pa |= PG_MANAGED;
 2755                 }
 2756                 goto validate;
 2757         } 
 2758         /*
 2759          * Mapping has changed, invalidate old range and fall through to
 2760          * handle validating new mapping.
 2761          */
 2762         if (opa) {
 2763                 if (origpte & PG_W)
 2764                         pmap->pm_stats.wired_count--;
 2765                 if (origpte & PG_MANAGED) {
 2766                         om = PHYS_TO_VM_PAGE(opa);
 2767                         pmap_remove_entry(pmap, om, va);
 2768                 } else if (va < VM_MAXUSER_ADDRESS) 
 2769                         printf("va=0x%x is unmanaged :-( \n", va);
 2770                         
 2771                 if (mpte != NULL) {
 2772                         mpte->wire_count--;
 2773                         KASSERT(mpte->wire_count > 0,
 2774                             ("pmap_enter: missing reference to page table page,"
 2775                              " va: 0x%x", va));
 2776                 }
 2777         } else
 2778                 pmap->pm_stats.resident_count++;
 2779 
 2780         /*
 2781          * Enter on the PV list if part of our managed memory.
 2782          */
 2783         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0) {
 2784                 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
 2785                     ("pmap_enter: managed mapping within the clean submap"));
 2786                 pmap_insert_entry(pmap, va, m);
 2787                 pa |= PG_MANAGED;
 2788         }
 2789 
 2790         /*
 2791          * Increment counters
 2792          */
 2793         if (wired)
 2794                 pmap->pm_stats.wired_count++;
 2795 
 2796 validate:
 2797         /*
 2798          * Now validate mapping with desired protection/wiring.
 2799          */
 2800         newpte = (pt_entry_t)(pa | PG_V);
 2801         if ((prot & VM_PROT_WRITE) != 0) {
 2802                 newpte |= PG_RW;
 2803                 vm_page_flag_set(m, PG_WRITEABLE);
 2804         }
 2805 #ifdef PAE
 2806         if ((prot & VM_PROT_EXECUTE) == 0)
 2807                 newpte |= pg_nx;
 2808 #endif
 2809         if (wired)
 2810                 newpte |= PG_W;
 2811         if (va < VM_MAXUSER_ADDRESS)
 2812                 newpte |= PG_U;
 2813         if (pmap == kernel_pmap)
 2814                 newpte |= pgeflag;
 2815 
 2816         critical_enter();
 2817         /*
 2818          * if the mapping or permission bits are different, we need
 2819          * to update the pte.
 2820          */
 2821         if ((origpte & ~(PG_M|PG_A)) != newpte) {
 2822                 if (origpte) {
 2823                         invlva = FALSE;
 2824                         origpte = *pte;
 2825                         PT_SET_VA(pte, newpte | PG_A, FALSE);
 2826                         if (origpte & PG_A) {
 2827                                 if (origpte & PG_MANAGED)
 2828                                         vm_page_flag_set(om, PG_REFERENCED);
 2829                                 if (opa != VM_PAGE_TO_PHYS(m))
 2830                                         invlva = TRUE;
 2831 #ifdef PAE
 2832                                 if ((origpte & PG_NX) == 0 &&
 2833                                     (newpte & PG_NX) != 0)
 2834                                         invlva = TRUE;
 2835 #endif
 2836                         }
 2837                         if (origpte & PG_M) {
 2838                                 KASSERT((origpte & PG_RW),
 2839         ("pmap_enter: modified page not writable: va: %#x, pte: %#jx",
 2840                                     va, (uintmax_t)origpte));
 2841                                 if ((origpte & PG_MANAGED) != 0)
 2842                                         vm_page_dirty(om);
 2843                                 if ((prot & VM_PROT_WRITE) == 0)
 2844                                         invlva = TRUE;
 2845                         }
 2846                         if (invlva)
 2847                                 pmap_invalidate_page(pmap, va);
 2848                 } else{
 2849                         PT_SET_VA(pte, newpte | PG_A, FALSE);
 2850                 }
 2851                 
 2852         }
 2853         PT_UPDATES_FLUSH();
 2854         critical_exit();
 2855         if (*PMAP1)
 2856                 PT_SET_VA_MA(PMAP1, 0, TRUE);
 2857         sched_unpin();
 2858         vm_page_unlock_queues();
 2859         PMAP_UNLOCK(pmap);
 2860 }
 2861 
 2862 /*
 2863  * Maps a sequence of resident pages belonging to the same object.
 2864  * The sequence begins with the given page m_start.  This page is
 2865  * mapped at the given virtual address start.  Each subsequent page is
 2866  * mapped at a virtual address that is offset from start by the same
 2867  * amount as the page is offset from m_start within the object.  The
 2868  * last page in the sequence is the page with the largest offset from
 2869  * m_start that can be mapped at a virtual address less than the given
 2870  * virtual address end.  Not every virtual page between start and end
 2871  * is mapped; only those for which a resident page exists with the
 2872  * corresponding offset from m_start are mapped.
 2873  */
 2874 void
 2875 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
 2876     vm_page_t m_start, vm_prot_t prot)
 2877 {
 2878         vm_page_t m, mpte;
 2879         vm_pindex_t diff, psize;
 2880         multicall_entry_t mcl[16];
 2881         multicall_entry_t *mclp = mcl;
 2882         int error, count = 0;
 2883         
 2884         VM_OBJECT_LOCK_ASSERT(m_start->object, MA_OWNED);
 2885         psize = atop(end - start);
 2886             
 2887         mpte = NULL;
 2888         m = m_start;
 2889         PMAP_LOCK(pmap);
 2890         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
 2891                 mpte = pmap_enter_quick_locked(&mclp, &count, pmap, start + ptoa(diff), m,
 2892                     prot, mpte);
 2893                 m = TAILQ_NEXT(m, listq);
 2894                 if (count == 16) {
 2895                         error = HYPERVISOR_multicall(mcl, count);
 2896                         KASSERT(error == 0, ("bad multicall %d", error));
 2897                         mclp = mcl;
 2898                         count = 0;
 2899                 }
 2900         }
 2901         if (count) {
 2902                 error = HYPERVISOR_multicall(mcl, count);
 2903                 KASSERT(error == 0, ("bad multicall %d", error));
 2904         }
 2905         
 2906         PMAP_UNLOCK(pmap);
 2907 }
 2908 
 2909 /*
 2910  * this code makes some *MAJOR* assumptions:
 2911  * 1. Current pmap & pmap exists.
 2912  * 2. Not wired.
 2913  * 3. Read access.
 2914  * 4. No page table pages.
 2915  * but is *MUCH* faster than pmap_enter...
 2916  */
 2917 
 2918 void
 2919 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
 2920 {
 2921         multicall_entry_t mcl, *mclp;
 2922         int count = 0;
 2923         mclp = &mcl;
 2924         
 2925         CTR4(KTR_PMAP, "pmap_enter_quick: pmap=%p va=0x%x m=%p prot=0x%x",
 2926             pmap, va, m, prot);
 2927         
 2928         PMAP_LOCK(pmap);
 2929         (void) pmap_enter_quick_locked(&mclp, &count, pmap, va, m, prot, NULL);
 2930         if (count)
 2931                 HYPERVISOR_multicall(&mcl, count);
 2932         PMAP_UNLOCK(pmap);
 2933 }
 2934 
 2935 #ifdef notyet
 2936 void
 2937 pmap_enter_quick_range(pmap_t pmap, vm_offset_t *addrs, vm_page_t *pages, vm_prot_t *prots, int count)
 2938 {
 2939         int i, error, index = 0;
 2940         multicall_entry_t mcl[16];
 2941         multicall_entry_t *mclp = mcl;
 2942                 
 2943         PMAP_LOCK(pmap);
 2944         for (i = 0; i < count; i++, addrs++, pages++, prots++) {
 2945                 if (!pmap_is_prefaultable_locked(pmap, *addrs))
 2946                         continue;
 2947 
 2948                 (void) pmap_enter_quick_locked(&mclp, &index, pmap, *addrs, *pages, *prots, NULL);
 2949                 if (index == 16) {
 2950                         error = HYPERVISOR_multicall(mcl, index);
 2951                         mclp = mcl;
 2952                         index = 0;
 2953                         KASSERT(error == 0, ("bad multicall %d", error));
 2954                 }
 2955         }
 2956         if (index) {
 2957                 error = HYPERVISOR_multicall(mcl, index);
 2958                 KASSERT(error == 0, ("bad multicall %d", error));
 2959         }
 2960         
 2961         PMAP_UNLOCK(pmap);
 2962 }
 2963 #endif
 2964 
 2965 static vm_page_t
 2966 pmap_enter_quick_locked(multicall_entry_t **mclpp, int *count, pmap_t pmap, vm_offset_t va, vm_page_t m,
 2967     vm_prot_t prot, vm_page_t mpte)
 2968 {
 2969         pt_entry_t *pte;
 2970         vm_paddr_t pa;
 2971         vm_page_t free;
 2972         multicall_entry_t *mcl = *mclpp;
 2973         
 2974         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
 2975             (m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0,
 2976             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
 2977         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 2978         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
 2979 
 2980         /*
 2981          * In the case that a page table page is not
 2982          * resident, we are creating it here.
 2983          */
 2984         if (va < VM_MAXUSER_ADDRESS) {
 2985                 unsigned ptepindex;
 2986                 pd_entry_t ptema;
 2987 
 2988                 /*
 2989                  * Calculate pagetable page index
 2990                  */
 2991                 ptepindex = va >> PDRSHIFT;
 2992                 if (mpte && (mpte->pindex == ptepindex)) {
 2993                         mpte->wire_count++;
 2994                 } else {
 2995                         /*
 2996                          * Get the page directory entry
 2997                          */
 2998                         ptema = pmap->pm_pdir[ptepindex];
 2999 
 3000                         /*
 3001                          * If the page table page is mapped, we just increment
 3002                          * the hold count, and activate it.
 3003                          */
 3004                         if (ptema & PG_V) {
 3005                                 if (ptema & PG_PS)
 3006                                         panic("pmap_enter_quick: unexpected mapping into 4MB page");
 3007                                 mpte = PHYS_TO_VM_PAGE(xpmap_mtop(ptema) & PG_FRAME);
 3008                                 mpte->wire_count++;
 3009                         } else {
 3010                                 mpte = _pmap_allocpte(pmap, ptepindex,
 3011                                     M_NOWAIT);
 3012                                 if (mpte == NULL)
 3013                                         return (mpte);
 3014                         }
 3015                 }
 3016         } else {
 3017                 mpte = NULL;
 3018         }
 3019 
 3020         /*
 3021          * This call to vtopte makes the assumption that we are
 3022          * entering the page into the current pmap.  In order to support
 3023          * quick entry into any pmap, one would likely use pmap_pte_quick.
 3024          * But that isn't as quick as vtopte.
 3025          */
 3026         KASSERT(pmap_is_current(pmap), ("entering pages in non-current pmap"));
 3027         pte = vtopte(va);
 3028         if (*pte & PG_V) {
 3029                 if (mpte != NULL) {
 3030                         mpte->wire_count--;
 3031                         mpte = NULL;
 3032                 }
 3033                 return (mpte);
 3034         }
 3035 
 3036         /*
 3037          * Enter on the PV list if part of our managed memory.
 3038          */
 3039         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0 &&
 3040             !pmap_try_insert_pv_entry(pmap, va, m)) {
 3041                 if (mpte != NULL) {
 3042                         free = NULL;
 3043                         if (pmap_unwire_pte_hold(pmap, mpte, &free)) {
 3044                                 pmap_invalidate_page(pmap, va);
 3045                                 pmap_free_zero_pages(free);
 3046                         }
 3047                         
 3048                         mpte = NULL;
 3049                 }
 3050                 return (mpte);
 3051         }
 3052 
 3053         /*
 3054          * Increment counters
 3055          */
 3056         pmap->pm_stats.resident_count++;
 3057 
 3058         pa = VM_PAGE_TO_PHYS(m);
 3059 #ifdef PAE
 3060         if ((prot & VM_PROT_EXECUTE) == 0)
 3061                 pa |= pg_nx;
 3062 #endif
 3063 
 3064 #if 0
 3065         /*
 3066          * Now validate mapping with RO protection
 3067          */
 3068         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
 3069                 pte_store(pte, pa | PG_V | PG_U);
 3070         else
 3071                 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
 3072 #else
 3073         /*
 3074          * Now validate mapping with RO protection
 3075          */
 3076         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
 3077                 pa =    xpmap_ptom(pa | PG_V | PG_U);
 3078         else
 3079                 pa = xpmap_ptom(pa | PG_V | PG_U | PG_MANAGED);
 3080 
 3081         mcl->op = __HYPERVISOR_update_va_mapping;
 3082         mcl->args[0] = va;
 3083         mcl->args[1] = (uint32_t)(pa & 0xffffffff);
 3084         mcl->args[2] = (uint32_t)(pa >> 32);
 3085         mcl->args[3] = 0;
 3086         *mclpp = mcl + 1;
 3087         *count = *count + 1;
 3088 #endif  
 3089         return mpte;
 3090 }
 3091 
 3092 /*
 3093  * Make a temporary mapping for a physical address.  This is only intended
 3094  * to be used for panic dumps.
 3095  */
 3096 void *
 3097 pmap_kenter_temporary(vm_paddr_t pa, int i)
 3098 {
 3099         vm_offset_t va;
 3100         vm_paddr_t ma = xpmap_ptom(pa);
 3101 
 3102         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
 3103         PT_SET_MA(va, (ma & ~PAGE_MASK) | PG_V | pgeflag);
 3104         invlpg(va);
 3105         return ((void *)crashdumpmap);
 3106 }
 3107 
 3108 /*
 3109  * This code maps large physical mmap regions into the
 3110  * processor address space.  Note that some shortcuts
 3111  * are taken, but the code works.
 3112  */
 3113 void
 3114 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr,
 3115                     vm_object_t object, vm_pindex_t pindex,
 3116                     vm_size_t size)
 3117 {
 3118         vm_page_t p;
 3119 
 3120         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 3121         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
 3122             ("pmap_object_init_pt: non-device object"));
 3123         if (pseflag && 
 3124             ((addr & (NBPDR - 1)) == 0) && ((size & (NBPDR - 1)) == 0)) {
 3125                 int i;
 3126                 vm_page_t m[1];
 3127                 unsigned int ptepindex;
 3128                 int npdes;
 3129                 pd_entry_t ptepa;
 3130 
 3131                 PMAP_LOCK(pmap);
 3132                 if (pmap->pm_pdir[ptepindex = (addr >> PDRSHIFT)])
 3133                         goto out;
 3134                 PMAP_UNLOCK(pmap);
 3135 retry:
 3136                 p = vm_page_lookup(object, pindex);
 3137                 if (p != NULL) {
 3138                         if (vm_page_sleep_if_busy(p, FALSE, "init4p"))
 3139                                 goto retry;
 3140                 } else {
 3141                         p = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
 3142                         if (p == NULL)
 3143                                 return;
 3144                         m[0] = p;
 3145 
 3146                         if (vm_pager_get_pages(object, m, 1, 0) != VM_PAGER_OK) {
 3147                                 vm_page_lock_queues();
 3148                                 vm_page_free(p);
 3149                                 vm_page_unlock_queues();
 3150                                 return;
 3151                         }
 3152 
 3153                         p = vm_page_lookup(object, pindex);
 3154                         vm_page_wakeup(p);
 3155                 }
 3156 
 3157                 ptepa = VM_PAGE_TO_PHYS(p);
 3158                 if (ptepa & (NBPDR - 1))
 3159                         return;
 3160 
 3161                 p->valid = VM_PAGE_BITS_ALL;
 3162 
 3163                 PMAP_LOCK(pmap);
 3164                 pmap->pm_stats.resident_count += size >> PAGE_SHIFT;
 3165                 npdes = size >> PDRSHIFT;
 3166                 critical_enter();
 3167                 for(i = 0; i < npdes; i++) {
 3168                         PD_SET_VA(pmap, ptepindex,
 3169                             ptepa | PG_U | PG_M | PG_RW | PG_V | PG_PS, FALSE);
 3170                         ptepa += NBPDR;
 3171                         ptepindex += 1;
 3172                 }
 3173                 pmap_invalidate_all(pmap);
 3174                 critical_exit();
 3175 out:
 3176                 PMAP_UNLOCK(pmap);
 3177         }
 3178 }
 3179 
 3180 /*
 3181  *      Routine:        pmap_change_wiring
 3182  *      Function:       Change the wiring attribute for a map/virtual-address
 3183  *                      pair.
 3184  *      In/out conditions:
 3185  *                      The mapping must already exist in the pmap.
 3186  */
 3187 void
 3188 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
 3189 {
 3190         pt_entry_t *pte;
 3191 
 3192         vm_page_lock_queues();
 3193         PMAP_LOCK(pmap);
 3194         pte = pmap_pte(pmap, va);
 3195 
 3196         if (wired && !pmap_pte_w(pte)) {
 3197                 PT_SET_VA_MA((pte), *(pte) | PG_W, TRUE);
 3198                 pmap->pm_stats.wired_count++;
 3199         } else if (!wired && pmap_pte_w(pte)) {
 3200                 PT_SET_VA_MA((pte), *(pte) & ~PG_W, TRUE);
 3201                 pmap->pm_stats.wired_count--;
 3202         }
 3203         
 3204         /*
 3205          * Wiring is not a hardware characteristic so there is no need to
 3206          * invalidate TLB.
 3207          */
 3208         pmap_pte_release(pte);
 3209         PMAP_UNLOCK(pmap);
 3210         vm_page_unlock_queues();
 3211 }
 3212 
 3213 
 3214 
 3215 /*
 3216  *      Copy the range specified by src_addr/len
 3217  *      from the source map to the range dst_addr/len
 3218  *      in the destination map.
 3219  *
 3220  *      This routine is only advisory and need not do anything.
 3221  */
 3222 
 3223 void
 3224 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
 3225           vm_offset_t src_addr)
 3226 {
 3227         vm_page_t   free;
 3228         vm_offset_t addr;
 3229         vm_offset_t end_addr = src_addr + len;
 3230         vm_offset_t pdnxt;
 3231 
 3232         if (dst_addr != src_addr)
 3233                 return;
 3234 
 3235         if (!pmap_is_current(src_pmap)) {
 3236                 CTR2(KTR_PMAP,
 3237                     "pmap_copy, skipping: pdir[PTDPTDI]=0x%jx PTDpde[0]=0x%jx",
 3238                     (src_pmap->pm_pdir[PTDPTDI] & PG_FRAME), (PTDpde[0] & PG_FRAME));
 3239                 
 3240                 return;
 3241         }
 3242         CTR5(KTR_PMAP, "pmap_copy:  dst_pmap=%p src_pmap=%p dst_addr=0x%x len=%d src_addr=0x%x",
 3243             dst_pmap, src_pmap, dst_addr, len, src_addr);
 3244         
 3245         vm_page_lock_queues();
 3246         if (dst_pmap < src_pmap) {
 3247                 PMAP_LOCK(dst_pmap);
 3248                 PMAP_LOCK(src_pmap);
 3249         } else {
 3250                 PMAP_LOCK(src_pmap);
 3251                 PMAP_LOCK(dst_pmap);
 3252         }
 3253         sched_pin();
 3254         for (addr = src_addr; addr < end_addr; addr = pdnxt) {
 3255                 pt_entry_t *src_pte, *dst_pte;
 3256                 vm_page_t dstmpte, srcmpte;
 3257                 pd_entry_t srcptepaddr;
 3258                 unsigned ptepindex;
 3259 
 3260                 if (addr >= UPT_MIN_ADDRESS)
 3261                         panic("pmap_copy: invalid to pmap_copy page tables");
 3262 
 3263                 pdnxt = (addr + NBPDR) & ~PDRMASK;
 3264                 ptepindex = addr >> PDRSHIFT;
 3265 
 3266                 srcptepaddr = PT_GET(&src_pmap->pm_pdir[ptepindex]);
 3267                 if (srcptepaddr == 0)
 3268                         continue;
 3269                         
 3270                 if (srcptepaddr & PG_PS) {
 3271                         if (dst_pmap->pm_pdir[ptepindex] == 0) {
 3272                                 PD_SET_VA(dst_pmap, ptepindex, srcptepaddr & ~PG_W, TRUE);
 3273                                 dst_pmap->pm_stats.resident_count +=
 3274                                     NBPDR / PAGE_SIZE;
 3275                         }
 3276                         continue;
 3277                 }
 3278 
 3279                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr & PG_FRAME);
 3280                 if (srcmpte->wire_count == 0)
 3281                         panic("pmap_copy: source page table page is unused");
 3282 
 3283                 if (pdnxt > end_addr)
 3284                         pdnxt = end_addr;
 3285 
 3286                 src_pte = vtopte(addr);
 3287                 while (addr < pdnxt) {
 3288                         pt_entry_t ptetemp;
 3289                         ptetemp = *src_pte;
 3290                         /*
 3291                          * we only virtual copy managed pages
 3292                          */
 3293                         if ((ptetemp & PG_MANAGED) != 0) {
 3294                                 dstmpte = pmap_allocpte(dst_pmap, addr,
 3295                                     M_NOWAIT);
 3296                                 if (dstmpte == NULL)
 3297                                         break;
 3298                                 dst_pte = pmap_pte_quick(dst_pmap, addr);
 3299                                 if (*dst_pte == 0 &&
 3300                                     pmap_try_insert_pv_entry(dst_pmap, addr,
 3301                                     PHYS_TO_VM_PAGE(xpmap_mtop(ptetemp) & PG_FRAME))) {
 3302                                         /*
 3303                                          * Clear the wired, modified, and
 3304                                          * accessed (referenced) bits
 3305                                          * during the copy.
 3306                                          */
 3307                                         KASSERT(ptetemp != 0, ("src_pte not set"));
 3308                                         PT_SET_VA_MA(dst_pte, ptetemp & ~(PG_W | PG_M | PG_A), TRUE /* XXX debug */);
 3309                                         KASSERT(*dst_pte == (ptetemp & ~(PG_W | PG_M | PG_A)),
 3310                                             ("no pmap copy expected: 0x%jx saw: 0x%jx",
 3311                                                 ptetemp &  ~(PG_W | PG_M | PG_A), *dst_pte));
 3312                                         dst_pmap->pm_stats.resident_count++;
 3313                                 } else {
 3314                                         free = NULL;
 3315                                         if (pmap_unwire_pte_hold(dst_pmap,
 3316                                             dstmpte, &free)) {
 3317                                                 pmap_invalidate_page(dst_pmap,
 3318                                                     addr);
 3319                                                 pmap_free_zero_pages(free);
 3320                                         }
 3321                                 }
 3322                                 if (dstmpte->wire_count >= srcmpte->wire_count)
 3323                                         break;
 3324                         }
 3325                         addr += PAGE_SIZE;
 3326                         src_pte++;
 3327                 }
 3328         }
 3329         PT_UPDATES_FLUSH();
 3330         sched_unpin();
 3331         vm_page_unlock_queues();
 3332         PMAP_UNLOCK(src_pmap);
 3333         PMAP_UNLOCK(dst_pmap);
 3334 }       
 3335 
 3336 static __inline void
 3337 pagezero(void *page)
 3338 {
 3339 #if defined(I686_CPU)
 3340         if (cpu_class == CPUCLASS_686) {
 3341 #if defined(CPU_ENABLE_SSE)
 3342                 if (cpu_feature & CPUID_SSE2)
 3343                         sse2_pagezero(page);
 3344                 else
 3345 #endif
 3346                         i686_pagezero(page);
 3347         } else
 3348 #endif
 3349                 bzero(page, PAGE_SIZE);
 3350 }
 3351 
 3352 /*
 3353  *      pmap_zero_page zeros the specified hardware page by mapping 
 3354  *      the page into KVM and using bzero to clear its contents.
 3355  */
 3356 void
 3357 pmap_zero_page(vm_page_t m)
 3358 {
 3359         struct sysmaps *sysmaps;
 3360 
 3361         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3362         mtx_lock(&sysmaps->lock);
 3363         if (*sysmaps->CMAP2)
 3364                 panic("pmap_zero_page: CMAP2 busy");
 3365         sched_pin();
 3366         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | xpmap_ptom(VM_PAGE_TO_PHYS(m)) | PG_A | PG_M);
 3367         pagezero(sysmaps->CADDR2);
 3368         PT_SET_MA(sysmaps->CADDR2, 0);
 3369         sched_unpin();
 3370         mtx_unlock(&sysmaps->lock);
 3371 }
 3372 
 3373 /*
 3374  *      pmap_zero_page_area zeros the specified hardware page by mapping 
 3375  *      the page into KVM and using bzero to clear its contents.
 3376  *
 3377  *      off and size may not cover an area beyond a single hardware page.
 3378  */
 3379 void
 3380 pmap_zero_page_area(vm_page_t m, int off, int size)
 3381 {
 3382         struct sysmaps *sysmaps;
 3383 
 3384         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3385         mtx_lock(&sysmaps->lock);
 3386         if (*sysmaps->CMAP2)
 3387                 panic("pmap_zero_page: CMAP2 busy");
 3388         sched_pin();
 3389         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | xpmap_ptom(VM_PAGE_TO_PHYS(m)) | PG_A | PG_M);
 3390 
 3391         if (off == 0 && size == PAGE_SIZE) 
 3392                 pagezero(sysmaps->CADDR2);
 3393         else
 3394                 bzero((char *)sysmaps->CADDR2 + off, size);
 3395         PT_SET_MA(sysmaps->CADDR2, 0);
 3396         sched_unpin();
 3397         mtx_unlock(&sysmaps->lock);
 3398 }
 3399 
 3400 /*
 3401  *      pmap_zero_page_idle zeros the specified hardware page by mapping 
 3402  *      the page into KVM and using bzero to clear its contents.  This
 3403  *      is intended to be called from the vm_pagezero process only and
 3404  *      outside of Giant.
 3405  */
 3406 void
 3407 pmap_zero_page_idle(vm_page_t m)
 3408 {
 3409 
 3410         if (*CMAP3)
 3411                 panic("pmap_zero_page: CMAP3 busy");
 3412         sched_pin();
 3413         PT_SET_MA(CADDR3, PG_V | PG_RW | xpmap_ptom(VM_PAGE_TO_PHYS(m)) | PG_A | PG_M);
 3414         pagezero(CADDR3);
 3415         PT_SET_MA(CADDR3, 0);
 3416         sched_unpin();
 3417 }
 3418 
 3419 /*
 3420  *      pmap_copy_page copies the specified (machine independent)
 3421  *      page by mapping the page into virtual memory and using
 3422  *      bcopy to copy the page, one machine dependent page at a
 3423  *      time.
 3424  */
 3425 void
 3426 pmap_copy_page(vm_page_t src, vm_page_t dst)
 3427 {
 3428         struct sysmaps *sysmaps;
 3429 
 3430         sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3431         mtx_lock(&sysmaps->lock);
 3432         if (*sysmaps->CMAP1)
 3433                 panic("pmap_copy_page: CMAP1 busy");
 3434         if (*sysmaps->CMAP2)
 3435                 panic("pmap_copy_page: CMAP2 busy");
 3436         sched_pin();
 3437         PT_SET_MA(sysmaps->CADDR1, PG_V | xpmap_ptom(VM_PAGE_TO_PHYS(src)) | PG_A);
 3438         PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW | xpmap_ptom(VM_PAGE_TO_PHYS(dst)) | PG_A | PG_M);
 3439         bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
 3440         PT_SET_MA(sysmaps->CADDR1, 0);
 3441         PT_SET_MA(sysmaps->CADDR2, 0);
 3442         sched_unpin();
 3443         mtx_unlock(&sysmaps->lock);
 3444 }
 3445 
 3446 /*
 3447  * Returns true if the pmap's pv is one of the first
 3448  * 16 pvs linked to from this page.  This count may
 3449  * be changed upwards or downwards in the future; it
 3450  * is only necessary that true be returned for a small
 3451  * subset of pmaps for proper page aging.
 3452  */
 3453 boolean_t
 3454 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
 3455 {
 3456         pv_entry_t pv;
 3457         int loops = 0;
 3458 
 3459         if (m->flags & PG_FICTITIOUS)
 3460                 return (FALSE);
 3461 
 3462         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3463         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3464                 if (PV_PMAP(pv) == pmap) {
 3465                         return TRUE;
 3466                 }
 3467                 loops++;
 3468                 if (loops >= 16)
 3469                         break;
 3470         }
 3471         return (FALSE);
 3472 }
 3473 
 3474 /*
 3475  *      pmap_page_wired_mappings:
 3476  *
 3477  *      Return the number of managed mappings to the given physical page
 3478  *      that are wired.
 3479  */
 3480 int
 3481 pmap_page_wired_mappings(vm_page_t m)
 3482 {
 3483         pv_entry_t pv;
 3484         pt_entry_t *pte;
 3485         pmap_t pmap;
 3486         int count;
 3487 
 3488         count = 0;
 3489         if ((m->flags & PG_FICTITIOUS) != 0)
 3490                 return (count);
 3491         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3492         sched_pin();
 3493         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3494                 pmap = PV_PMAP(pv);
 3495                 PMAP_LOCK(pmap);
 3496                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3497                 if ((*pte & PG_W) != 0)
 3498                         count++;
 3499                 PMAP_UNLOCK(pmap);
 3500         }
 3501         sched_unpin();
 3502         return (count);
 3503 }
 3504 
 3505 /*
 3506  * Returns TRUE if the given page is mapped individually or as part of
 3507  * a 4mpage.  Otherwise, returns FALSE.
 3508  */
 3509 boolean_t
 3510 pmap_page_is_mapped(vm_page_t m)
 3511 {
 3512         struct md_page *pvh;
 3513 
 3514         if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0)
 3515                 return (FALSE);
 3516         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3517         if (TAILQ_EMPTY(&m->md.pv_list)) {
 3518                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
 3519                 return (!TAILQ_EMPTY(&pvh->pv_list));
 3520         } else
 3521                 return (TRUE);
 3522 }
 3523 
 3524 /*
 3525  * Remove all pages from specified address space
 3526  * this aids process exit speeds.  Also, this code
 3527  * is special cased for current process only, but
 3528  * can have the more generic (and slightly slower)
 3529  * mode enabled.  This is much faster than pmap_remove
 3530  * in the case of running down an entire address space.
 3531  */
 3532 void
 3533 pmap_remove_pages(pmap_t pmap)
 3534 {
 3535         pt_entry_t *pte, tpte;
 3536         vm_page_t m, free = NULL;
 3537         pv_entry_t pv;
 3538         struct pv_chunk *pc, *npc;
 3539         int field, idx;
 3540         int32_t bit;
 3541         uint32_t inuse, bitmask;
 3542         int allfree;
 3543 
 3544         CTR1(KTR_PMAP, "pmap_remove_pages: pmap=%p", pmap);
 3545         
 3546         if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace)) {
 3547                 printf("warning: pmap_remove_pages called with non-current pmap\n");
 3548                 return;
 3549         }
 3550         vm_page_lock_queues();
 3551         KASSERT(pmap_is_current(pmap), ("removing pages from non-current pmap"));
 3552         PMAP_LOCK(pmap);
 3553         sched_pin();
 3554         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
 3555                 allfree = 1;
 3556                 for (field = 0; field < _NPCM; field++) {
 3557                         inuse = (~(pc->pc_map[field])) & pc_freemask[field];
 3558                         while (inuse != 0) {
 3559                                 bit = bsfl(inuse);
 3560                                 bitmask = 1UL << bit;
 3561                                 idx = field * 32 + bit;
 3562                                 pv = &pc->pc_pventry[idx];
 3563                                 inuse &= ~bitmask;
 3564 
 3565                                 pte = vtopte(pv->pv_va);
 3566                                 tpte = *pte ? xpmap_mtop(*pte) : 0;
 3567 
 3568                                 if (tpte == 0) {
 3569                                         printf(
 3570                                             "TPTE at %p  IS ZERO @ VA %08x\n",
 3571                                             pte, pv->pv_va);
 3572                                         panic("bad pte");
 3573                                 }
 3574 
 3575 /*
 3576  * We cannot remove wired pages from a process' mapping at this time
 3577  */
 3578                                 if (tpte & PG_W) {
 3579                                         allfree = 0;
 3580                                         continue;
 3581                                 }
 3582 
 3583                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
 3584                                 KASSERT(m->phys_addr == (tpte & PG_FRAME),
 3585                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
 3586                                     m, (uintmax_t)m->phys_addr,
 3587                                     (uintmax_t)tpte));
 3588 
 3589                                 KASSERT(m < &vm_page_array[vm_page_array_size],
 3590                                         ("pmap_remove_pages: bad tpte %#jx",
 3591                                         (uintmax_t)tpte));
 3592 
 3593 
 3594                                 PT_CLEAR_VA(pte, FALSE);
 3595                                 
 3596                                 /*
 3597                                  * Update the vm_page_t clean/reference bits.
 3598                                  */
 3599                                 if (tpte & PG_M)
 3600                                         vm_page_dirty(m);
 3601 
 3602                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 3603                                 if (TAILQ_EMPTY(&m->md.pv_list))
 3604                                         vm_page_flag_clear(m, PG_WRITEABLE);
 3605 
 3606                                 pmap_unuse_pt(pmap, pv->pv_va, &free);
 3607 
 3608                                 /* Mark free */
 3609                                 PV_STAT(pv_entry_frees++);
 3610                                 PV_STAT(pv_entry_spare++);
 3611                                 pv_entry_count--;
 3612                                 pc->pc_map[field] |= bitmask;
 3613                                 pmap->pm_stats.resident_count--;                        
 3614                         }
 3615                 }
 3616                 PT_UPDATES_FLUSH();
 3617                 if (allfree) {
 3618                         PV_STAT(pv_entry_spare -= _NPCPV);
 3619                         PV_STAT(pc_chunk_count--);
 3620                         PV_STAT(pc_chunk_frees++);
 3621                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
 3622                         m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
 3623                         pmap_qremove((vm_offset_t)pc, 1);
 3624                         vm_page_unwire(m, 0);
 3625                         vm_page_free(m);
 3626                         pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
 3627                 }
 3628         }
 3629         PT_UPDATES_FLUSH();
 3630         if (*PMAP1)
 3631                 PT_SET_MA(PADDR1, 0);
 3632 
 3633         sched_unpin();
 3634         pmap_invalidate_all(pmap);
 3635         vm_page_unlock_queues();
 3636         PMAP_UNLOCK(pmap);
 3637         pmap_free_zero_pages(free);
 3638 }
 3639 
 3640 /*
 3641  *      pmap_is_modified:
 3642  *
 3643  *      Return whether or not the specified physical page was modified
 3644  *      in any physical maps.
 3645  */
 3646 boolean_t
 3647 pmap_is_modified(vm_page_t m)
 3648 {
 3649         pv_entry_t pv;
 3650         pt_entry_t *pte;
 3651         pmap_t pmap;
 3652         boolean_t rv;
 3653 
 3654         rv = FALSE;
 3655         if (m->flags & PG_FICTITIOUS)
 3656                 return (rv);
 3657 
 3658         sched_pin();
 3659         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3660         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3661                 pmap = PV_PMAP(pv);
 3662                 PMAP_LOCK(pmap);
 3663                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3664                 rv = (*pte & PG_M) != 0;
 3665                 PMAP_UNLOCK(pmap);
 3666                 if (rv)
 3667                         break;
 3668         }
 3669         if (*PMAP1)
 3670                 PT_SET_MA(PADDR1, 0);
 3671         sched_unpin();
 3672         return (rv);
 3673 }
 3674 
 3675 /*
 3676  *      pmap_is_prefaultable:
 3677  *
 3678  *      Return whether or not the specified virtual address is elgible
 3679  *      for prefault.
 3680  */
 3681 static boolean_t
 3682 pmap_is_prefaultable_locked(pmap_t pmap, vm_offset_t addr)
 3683 {
 3684         pt_entry_t *pte;
 3685         boolean_t rv = FALSE;
 3686 
 3687         return (rv);
 3688         
 3689         if (pmap_is_current(pmap) && *pmap_pde(pmap, addr)) {
 3690                 pte = vtopte(addr);
 3691                 rv = (*pte == 0);
 3692         }
 3693         return (rv);
 3694 }
 3695 
 3696 boolean_t
 3697 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
 3698 {
 3699         boolean_t rv;
 3700         
 3701         PMAP_LOCK(pmap);
 3702         rv = pmap_is_prefaultable_locked(pmap, addr);
 3703         PMAP_UNLOCK(pmap);
 3704         return (rv);
 3705 }
 3706 
 3707 void
 3708 pmap_map_readonly(pmap_t pmap, vm_offset_t va, int len)
 3709 {
 3710         int i, npages = round_page(len) >> PAGE_SHIFT;
 3711         for (i = 0; i < npages; i++) {
 3712                 pt_entry_t *pte;
 3713                 pte = pmap_pte(pmap, (vm_offset_t)(va + i*PAGE_SIZE));
 3714                 vm_page_lock_queues();
 3715                 pte_store(pte, xpmap_mtop(*pte & ~(PG_RW|PG_M)));
 3716                 vm_page_unlock_queues();
 3717                 PMAP_MARK_PRIV(xpmap_mtop(*pte));
 3718                 pmap_pte_release(pte);
 3719         }
 3720 }
 3721 
 3722 void
 3723 pmap_map_readwrite(pmap_t pmap, vm_offset_t va, int len)
 3724 {
 3725         int i, npages = round_page(len) >> PAGE_SHIFT;
 3726         for (i = 0; i < npages; i++) {
 3727                 pt_entry_t *pte;
 3728                 pte = pmap_pte(pmap, (vm_offset_t)(va + i*PAGE_SIZE));
 3729                 PMAP_MARK_UNPRIV(xpmap_mtop(*pte));
 3730                 vm_page_lock_queues();
 3731                 pte_store(pte, xpmap_mtop(*pte) | (PG_RW|PG_M));
 3732                 vm_page_unlock_queues();
 3733                 pmap_pte_release(pte);
 3734         }
 3735 }
 3736 
 3737 /*
 3738  * Clear the write and modified bits in each of the given page's mappings.
 3739  */
 3740 void
 3741 pmap_remove_write(vm_page_t m)
 3742 {
 3743         pv_entry_t pv;
 3744         pmap_t pmap;
 3745         pt_entry_t oldpte, *pte;
 3746 
 3747         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3748         if ((m->flags & PG_FICTITIOUS) != 0 ||
 3749             (m->flags & PG_WRITEABLE) == 0)
 3750                 return;
 3751         sched_pin();
 3752         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3753                 pmap = PV_PMAP(pv);
 3754                 PMAP_LOCK(pmap);
 3755                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3756 retry:
 3757                 oldpte = *pte;
 3758                 if ((oldpte & PG_RW) != 0) {
 3759                         vm_paddr_t newpte = oldpte & ~(PG_RW | PG_M);
 3760                         
 3761                         /*
 3762                          * Regardless of whether a pte is 32 or 64 bits
 3763                          * in size, PG_RW and PG_M are among the least
 3764                          * significant 32 bits.
 3765                          */
 3766                         PT_SET_VA_MA(pte, newpte, TRUE);
 3767                         if (*pte != newpte)
 3768                                 goto retry;
 3769                         
 3770                         if ((oldpte & PG_M) != 0)
 3771                                 vm_page_dirty(m);
 3772                         pmap_invalidate_page(pmap, pv->pv_va);
 3773                 }
 3774                 PMAP_UNLOCK(pmap);
 3775         }
 3776         vm_page_flag_clear(m, PG_WRITEABLE);
 3777         PT_UPDATES_FLUSH();
 3778         if (*PMAP1)
 3779                 PT_SET_MA(PADDR1, 0);
 3780         sched_unpin();
 3781 }
 3782 
 3783 /*
 3784  *      pmap_ts_referenced:
 3785  *
 3786  *      Return a count of reference bits for a page, clearing those bits.
 3787  *      It is not necessary for every reference bit to be cleared, but it
 3788  *      is necessary that 0 only be returned when there are truly no
 3789  *      reference bits set.
 3790  *
 3791  *      XXX: The exact number of bits to check and clear is a matter that
 3792  *      should be tested and standardized at some point in the future for
 3793  *      optimal aging of shared pages.
 3794  */
 3795 int
 3796 pmap_ts_referenced(vm_page_t m)
 3797 {
 3798         pv_entry_t pv, pvf, pvn;
 3799         pmap_t pmap;
 3800         pt_entry_t *pte;
 3801         int rtval = 0;
 3802 
 3803         if (m->flags & PG_FICTITIOUS)
 3804                 return (rtval);
 3805         sched_pin();
 3806         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3807         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
 3808                 pvf = pv;
 3809                 do {
 3810                         pvn = TAILQ_NEXT(pv, pv_list);
 3811                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
 3812                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
 3813                         pmap = PV_PMAP(pv);
 3814                         PMAP_LOCK(pmap);
 3815                         pte = pmap_pte_quick(pmap, pv->pv_va);
 3816                         if ((*pte & PG_A) != 0) {
 3817                                 PT_SET_VA_MA(pte, *pte & ~PG_A, FALSE);
 3818                                 pmap_invalidate_page(pmap, pv->pv_va);
 3819                                 rtval++;
 3820                                 if (rtval > 4)
 3821                                         pvn = NULL;
 3822                         }
 3823                         PMAP_UNLOCK(pmap);
 3824                 } while ((pv = pvn) != NULL && pv != pvf);
 3825         }
 3826         PT_UPDATES_FLUSH();
 3827         if (*PMAP1)
 3828                 PT_SET_MA(PADDR1, 0);
 3829 
 3830         sched_unpin();
 3831         return (rtval);
 3832 }
 3833 
 3834 /*
 3835  *      Clear the modify bits on the specified physical page.
 3836  */
 3837 void
 3838 pmap_clear_modify(vm_page_t m)
 3839 {
 3840         pv_entry_t pv;
 3841         pmap_t pmap;
 3842         pt_entry_t *pte;
 3843 
 3844         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3845         if ((m->flags & PG_FICTITIOUS) != 0)
 3846                 return;
 3847         sched_pin();
 3848         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3849                 pmap = PV_PMAP(pv);
 3850                 PMAP_LOCK(pmap);
 3851                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3852                 if ((*pte & PG_M) != 0) {
 3853                         /*
 3854                          * Regardless of whether a pte is 32 or 64 bits
 3855                          * in size, PG_M is among the least significant
 3856                          * 32 bits. 
 3857                          */
 3858                         PT_SET_VA_MA(pte, *pte & ~PG_M, FALSE);
 3859                         pmap_invalidate_page(pmap, pv->pv_va);
 3860                 }
 3861                 PMAP_UNLOCK(pmap);
 3862         }
 3863         sched_unpin();
 3864 }
 3865 
 3866 /*
 3867  *      pmap_clear_reference:
 3868  *
 3869  *      Clear the reference bit on the specified physical page.
 3870  */
 3871 void
 3872 pmap_clear_reference(vm_page_t m)
 3873 {
 3874         pv_entry_t pv;
 3875         pmap_t pmap;
 3876         pt_entry_t *pte;
 3877 
 3878         mtx_assert(&vm_page_queue_mtx, MA_OWNED);
 3879         if ((m->flags & PG_FICTITIOUS) != 0)
 3880                 return;
 3881         sched_pin();
 3882         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 3883                 pmap = PV_PMAP(pv);
 3884                 PMAP_LOCK(pmap);
 3885                 pte = pmap_pte_quick(pmap, pv->pv_va);
 3886                 if ((*pte & PG_A) != 0) {
 3887                         /*
 3888                          * Regardless of whether a pte is 32 or 64 bits
 3889                          * in size, PG_A is among the least significant
 3890                          * 32 bits. 
 3891                          */
 3892                         PT_SET_VA_MA(pte, *pte & ~PG_A, FALSE);
 3893                         pmap_invalidate_page(pmap, pv->pv_va);
 3894                 }
 3895                 PMAP_UNLOCK(pmap);
 3896         }
 3897         sched_unpin();
 3898 }
 3899 
 3900 /*
 3901  * Miscellaneous support routines follow
 3902  */
 3903 
 3904 /*
 3905  * Map a set of physical memory pages into the kernel virtual
 3906  * address space. Return a pointer to where it is mapped. This
 3907  * routine is intended to be used for mapping device memory,
 3908  * NOT real memory.
 3909  */
 3910 void *
 3911 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
 3912 {
 3913         vm_offset_t va, offset;
 3914         vm_size_t tmpsize;
 3915 
 3916         offset = pa & PAGE_MASK;
 3917         size = roundup(offset + size, PAGE_SIZE);
 3918         pa = pa & PG_FRAME;
 3919 
 3920         if (pa < KERNLOAD && pa + size <= KERNLOAD)
 3921                 va = KERNBASE + pa;
 3922         else
 3923                 va = kmem_alloc_nofault(kernel_map, size);
 3924         if (!va)
 3925                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
 3926 
 3927         for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
 3928                 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
 3929         pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
 3930         pmap_invalidate_cache_range(va, va + size);
 3931         return ((void *)(va + offset));
 3932 }
 3933 
 3934 void *
 3935 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
 3936 {
 3937 
 3938         return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
 3939 }
 3940 
 3941 void *
 3942 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
 3943 {
 3944 
 3945         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
 3946 }
 3947 
 3948 void
 3949 pmap_unmapdev(vm_offset_t va, vm_size_t size)
 3950 {
 3951         vm_offset_t base, offset, tmpva;
 3952 
 3953         if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
 3954                 return;
 3955         base = trunc_page(va);
 3956         offset = va & PAGE_MASK;
 3957         size = roundup(offset + size, PAGE_SIZE);
 3958         critical_enter();
 3959         for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
 3960                 pmap_kremove(tmpva);
 3961         pmap_invalidate_range(kernel_pmap, va, tmpva);
 3962         critical_exit();
 3963         kmem_free(kernel_map, base, size);
 3964 }
 3965 
 3966 /*
 3967  * Sets the memory attribute for the specified page.
 3968  */
 3969 void
 3970 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
 3971 {
 3972         struct sysmaps *sysmaps;
 3973         vm_offset_t sva, eva;
 3974 
 3975         m->md.pat_mode = ma;
 3976         if ((m->flags & PG_FICTITIOUS) != 0)
 3977                 return;
 3978 
 3979         /*
 3980          * If "m" is a normal page, flush it from the cache.
 3981          * See pmap_invalidate_cache_range().
 3982          *
 3983          * First, try to find an existing mapping of the page by sf
 3984          * buffer. sf_buf_invalidate_cache() modifies mapping and
 3985          * flushes the cache.
 3986          */    
 3987         if (sf_buf_invalidate_cache(m))
 3988                 return;
 3989 
 3990         /*
 3991          * If page is not mapped by sf buffer, but CPU does not
 3992          * support self snoop, map the page transient and do
 3993          * invalidation. In the worst case, whole cache is flushed by
 3994          * pmap_invalidate_cache_range().
 3995          */
 3996         if ((cpu_feature & (CPUID_SS|CPUID_CLFSH)) == CPUID_CLFSH) {
 3997                 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
 3998                 mtx_lock(&sysmaps->lock);
 3999                 if (*sysmaps->CMAP2)
 4000                         panic("pmap_page_set_memattr: CMAP2 busy");
 4001                 sched_pin();
 4002                 PT_SET_MA(sysmaps->CADDR2, PG_V | PG_RW |
 4003                     xpmap_ptom(VM_PAGE_TO_PHYS(m)) | PG_A | PG_M |
 4004                     pmap_cache_bits(m->md.pat_mode, 0));
 4005                 invlcaddr(sysmaps->CADDR2);
 4006                 sva = (vm_offset_t)sysmaps->CADDR2;
 4007                 eva = sva + PAGE_SIZE;
 4008         } else
 4009                 sva = eva = 0; /* gcc */
 4010         pmap_invalidate_cache_range(sva, eva);
 4011         if (sva != 0) {
 4012                 PT_SET_MA(sysmaps->CADDR2, 0);
 4013                 sched_unpin();
 4014                 mtx_unlock(&sysmaps->lock);
 4015         }
 4016 }
 4017 
 4018 int
 4019 pmap_change_attr(va, size, mode)
 4020         vm_offset_t va;
 4021         vm_size_t size;
 4022         int mode;
 4023 {
 4024         vm_offset_t base, offset, tmpva;
 4025         pt_entry_t *pte;
 4026         u_int opte, npte;
 4027         pd_entry_t *pde;
 4028         boolean_t changed;
 4029 
 4030         base = trunc_page(va);
 4031         offset = va & PAGE_MASK;
 4032         size = roundup(offset + size, PAGE_SIZE);
 4033 
 4034         /* Only supported on kernel virtual addresses. */
 4035         if (base <= VM_MAXUSER_ADDRESS)
 4036                 return (EINVAL);
 4037 
 4038         /* 4MB pages and pages that aren't mapped aren't supported. */
 4039         for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE) {
 4040                 pde = pmap_pde(kernel_pmap, tmpva);
 4041                 if (*pde & PG_PS)
 4042                         return (EINVAL);
 4043                 if ((*pde & PG_V) == 0)
 4044                         return (EINVAL);
 4045                 pte = vtopte(va);
 4046                 if ((*pte & PG_V) == 0)
 4047                         return (EINVAL);
 4048         }
 4049 
 4050         changed = FALSE;
 4051 
 4052         /*
 4053          * Ok, all the pages exist and are 4k, so run through them updating
 4054          * their cache mode.
 4055          */
 4056         for (tmpva = base; size > 0; ) {
 4057                 pte = vtopte(tmpva);
 4058 
 4059                 /*
 4060                  * The cache mode bits are all in the low 32-bits of the
 4061                  * PTE, so we can just spin on updating the low 32-bits.
 4062                  */
 4063                 do {
 4064                         opte = *(u_int *)pte;
 4065                         npte = opte & ~(PG_PTE_PAT | PG_NC_PCD | PG_NC_PWT);
 4066                         npte |= pmap_cache_bits(mode, 0);
 4067                         PT_SET_VA_MA(pte, npte, TRUE);
 4068                 } while (npte != opte && (*pte != npte));
 4069                 if (npte != opte)
 4070                         changed = TRUE;
 4071                 tmpva += PAGE_SIZE;
 4072                 size -= PAGE_SIZE;
 4073         }
 4074 
 4075         /*
 4076          * Flush CPU caches to make sure any data isn't cached that shouldn't
 4077          * be, etc.
 4078          */
 4079         if (changed) {
 4080                 pmap_invalidate_range(kernel_pmap, base, tmpva);
 4081                 pmap_invalidate_cache_range(base, tmpva);
 4082         }
 4083         return (0);
 4084 }
 4085 
 4086 /*
 4087  * perform the pmap work for mincore
 4088  */
 4089 int
 4090 pmap_mincore(pmap_t pmap, vm_offset_t addr)
 4091 {
 4092         pt_entry_t *ptep, pte;
 4093         vm_page_t m;
 4094         int val = 0;
 4095         
 4096         PMAP_LOCK(pmap);
 4097         ptep = pmap_pte(pmap, addr);
 4098         pte = (ptep != NULL) ? PT_GET(ptep) : 0;
 4099         pmap_pte_release(ptep);
 4100         PMAP_UNLOCK(pmap);
 4101 
 4102         if (pte != 0) {
 4103                 vm_paddr_t pa;
 4104 
 4105                 val = MINCORE_INCORE;
 4106                 if ((pte & PG_MANAGED) == 0)
 4107                         return val;
 4108 
 4109                 pa = pte & PG_FRAME;
 4110 
 4111                 m = PHYS_TO_VM_PAGE(pa);
 4112 
 4113                 /*
 4114                  * Modified by us
 4115                  */
 4116                 if (pte & PG_M)
 4117                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
 4118                 else {
 4119                         /*
 4120                          * Modified by someone else
 4121                          */
 4122                         vm_page_lock_queues();
 4123                         if (m->dirty || pmap_is_modified(m))
 4124                                 val |= MINCORE_MODIFIED_OTHER;
 4125                         vm_page_unlock_queues();
 4126                 }
 4127                 /*
 4128                  * Referenced by us
 4129                  */
 4130                 if (pte & PG_A)
 4131                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
 4132                 else {
 4133                         /*
 4134                          * Referenced by someone else
 4135                          */
 4136                         vm_page_lock_queues();
 4137                         if ((m->flags & PG_REFERENCED) ||
 4138                             pmap_ts_referenced(m)) {
 4139                                 val |= MINCORE_REFERENCED_OTHER;
 4140                                 vm_page_flag_set(m, PG_REFERENCED);
 4141                         }
 4142                         vm_page_unlock_queues();
 4143                 }
 4144         } 
 4145         return val;
 4146 }
 4147 
 4148 void
 4149 pmap_activate(struct thread *td)
 4150 {
 4151         pmap_t  pmap, oldpmap;
 4152         u_int32_t  cr3;
 4153 
 4154         critical_enter();
 4155         pmap = vmspace_pmap(td->td_proc->p_vmspace);
 4156         oldpmap = PCPU_GET(curpmap);
 4157 #if defined(SMP)
 4158         atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
 4159         atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
 4160 #else
 4161         oldpmap->pm_active &= ~1;
 4162         pmap->pm_active |= 1;
 4163 #endif
 4164 #ifdef PAE
 4165         cr3 = vtophys(pmap->pm_pdpt);
 4166 #else
 4167         cr3 = vtophys(pmap->pm_pdir);
 4168 #endif
 4169         /*
 4170          * pmap_activate is for the current thread on the current cpu
 4171          */
 4172         td->td_pcb->pcb_cr3 = cr3;
 4173         PT_UPDATES_FLUSH();
 4174         load_cr3(cr3);
 4175         PCPU_SET(curpmap, pmap);
 4176         critical_exit();
 4177 }
 4178 
 4179 void
 4180 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
 4181 {
 4182 }
 4183 
 4184 /*
 4185  *      Increase the starting virtual address of the given mapping if a
 4186  *      different alignment might result in more superpage mappings.
 4187  */
 4188 void
 4189 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
 4190     vm_offset_t *addr, vm_size_t size)
 4191 {
 4192         vm_offset_t superpage_offset;
 4193 
 4194         if (size < NBPDR)
 4195                 return;
 4196         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
 4197                 offset += ptoa(object->pg_color);
 4198         superpage_offset = offset & PDRMASK;
 4199         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
 4200             (*addr & PDRMASK) == superpage_offset)
 4201                 return;
 4202         if ((*addr & PDRMASK) < superpage_offset)
 4203                 *addr = (*addr & ~PDRMASK) + superpage_offset;
 4204         else
 4205                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
 4206 }
 4207 
 4208 #ifdef XEN
 4209 
 4210 void
 4211 pmap_suspend()
 4212 {
 4213         pmap_t pmap;
 4214         int i, pdir, offset;
 4215         vm_paddr_t pdirma;
 4216         mmu_update_t mu[4];
 4217 
 4218         /*
 4219          * We need to remove the recursive mapping structure from all
 4220          * our pmaps so that Xen doesn't get confused when it restores
 4221          * the page tables. The recursive map lives at page directory
 4222          * index PTDPTDI. We assume that the suspend code has stopped
 4223          * the other vcpus (if any).
 4224          */
 4225         LIST_FOREACH(pmap, &allpmaps, pm_list) {
 4226                 for (i = 0; i < 4; i++) {
 4227                         /*
 4228                          * Figure out which page directory (L2) page
 4229                          * contains this bit of the recursive map and
 4230                          * the offset within that page of the map
 4231                          * entry
 4232                          */
 4233                         pdir = (PTDPTDI + i) / NPDEPG;
 4234                         offset = (PTDPTDI + i) % NPDEPG;
 4235                         pdirma = pmap->pm_pdpt[pdir] & PG_FRAME;
 4236                         mu[i].ptr = pdirma + offset * sizeof(pd_entry_t);
 4237                         mu[i].val = 0;
 4238                 }
 4239                 HYPERVISOR_mmu_update(mu, 4, NULL, DOMID_SELF);
 4240         }
 4241 }
 4242 
 4243 void
 4244 pmap_resume()
 4245 {
 4246         pmap_t pmap;
 4247         int i, pdir, offset;
 4248         vm_paddr_t pdirma;
 4249         mmu_update_t mu[4];
 4250 
 4251         /*
 4252          * Restore the recursive map that we removed on suspend.
 4253          */
 4254         LIST_FOREACH(pmap, &allpmaps, pm_list) {
 4255                 for (i = 0; i < 4; i++) {
 4256                         /*
 4257                          * Figure out which page directory (L2) page
 4258                          * contains this bit of the recursive map and
 4259                          * the offset within that page of the map
 4260                          * entry
 4261                          */
 4262                         pdir = (PTDPTDI + i) / NPDEPG;
 4263                         offset = (PTDPTDI + i) % NPDEPG;
 4264                         pdirma = pmap->pm_pdpt[pdir] & PG_FRAME;
 4265                         mu[i].ptr = pdirma + offset * sizeof(pd_entry_t);
 4266                         mu[i].val = (pmap->pm_pdpt[i] & PG_FRAME) | PG_V;
 4267                 }
 4268                 HYPERVISOR_mmu_update(mu, 4, NULL, DOMID_SELF);
 4269         }
 4270 }
 4271 
 4272 #endif
 4273 
 4274 #if defined(PMAP_DEBUG)
 4275 pmap_pid_dump(int pid)
 4276 {
 4277         pmap_t pmap;
 4278         struct proc *p;
 4279         int npte = 0;
 4280         int index;
 4281 
 4282         sx_slock(&allproc_lock);
 4283         FOREACH_PROC_IN_SYSTEM(p) {
 4284                 if (p->p_pid != pid)
 4285                         continue;
 4286 
 4287                 if (p->p_vmspace) {
 4288                         int i,j;
 4289                         index = 0;
 4290                         pmap = vmspace_pmap(p->p_vmspace);
 4291                         for (i = 0; i < NPDEPTD; i++) {
 4292                                 pd_entry_t *pde;
 4293                                 pt_entry_t *pte;
 4294                                 vm_offset_t base = i << PDRSHIFT;
 4295                                 
 4296                                 pde = &pmap->pm_pdir[i];
 4297                                 if (pde && pmap_pde_v(pde)) {
 4298                                         for (j = 0; j < NPTEPG; j++) {
 4299                                                 vm_offset_t va = base + (j << PAGE_SHIFT);
 4300                                                 if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
 4301                                                         if (index) {
 4302                                                                 index = 0;
 4303                                                                 printf("\n");
 4304                                                         }
 4305                                                         sx_sunlock(&allproc_lock);
 4306                                                         return npte;
 4307                                                 }
 4308                                                 pte = pmap_pte(pmap, va);
 4309                                                 if (pte && pmap_pte_v(pte)) {
 4310                                                         pt_entry_t pa;
 4311                                                         vm_page_t m;
 4312                                                         pa = PT_GET(pte);
 4313                                                         m = PHYS_TO_VM_PAGE(pa & PG_FRAME);
 4314                                                         printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
 4315                                                                 va, pa, m->hold_count, m->wire_count, m->flags);
 4316                                                         npte++;
 4317                                                         index++;
 4318                                                         if (index >= 2) {
 4319                                                                 index = 0;
 4320                                                                 printf("\n");
 4321                                                         } else {
 4322                                                                 printf(" ");
 4323                                                         }
 4324                                                 }
 4325                                         }
 4326                                 }
 4327                         }
 4328                 }
 4329         }
 4330         sx_sunlock(&allproc_lock);
 4331         return npte;
 4332 }
 4333 #endif
 4334 
 4335 #if defined(DEBUG)
 4336 
 4337 static void     pads(pmap_t pm);
 4338 void            pmap_pvdump(vm_paddr_t pa);
 4339 
 4340 /* print address space of pmap*/
 4341 static void
 4342 pads(pmap_t pm)
 4343 {
 4344         int i, j;
 4345         vm_paddr_t va;
 4346         pt_entry_t *ptep;
 4347 
 4348         if (pm == kernel_pmap)
 4349                 return;
 4350         for (i = 0; i < NPDEPTD; i++)
 4351                 if (pm->pm_pdir[i])
 4352                         for (j = 0; j < NPTEPG; j++) {
 4353                                 va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
 4354                                 if (pm == kernel_pmap && va < KERNBASE)
 4355                                         continue;
 4356                                 if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
 4357                                         continue;
 4358                                 ptep = pmap_pte(pm, va);
 4359                                 if (pmap_pte_v(ptep))
 4360                                         printf("%x:%x ", va, *ptep);
 4361                         };
 4362 
 4363 }
 4364 
 4365 void
 4366 pmap_pvdump(vm_paddr_t pa)
 4367 {
 4368         pv_entry_t pv;
 4369         pmap_t pmap;
 4370         vm_page_t m;
 4371 
 4372         printf("pa %x", pa);
 4373         m = PHYS_TO_VM_PAGE(pa);
 4374         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
 4375                 pmap = PV_PMAP(pv);
 4376                 printf(" -> pmap %p, va %x", (void *)pmap, pv->pv_va);
 4377                 pads(pmap);
 4378         }
 4379         printf(" ");
 4380 }
 4381 #endif

Cache object: c225bfda5088e99b662ea95c296f53ef


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