kernel - Add shared active virtual memory, i386
[dragonfly.git] / sys / platform / pc32 / i386 / pmap.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
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  * $FreeBSD: src/sys/i386/i386/pmap.c,v 1.250.2.18 2002/03/06 22:48:53 silby Exp $
45  */
46
47 /*
48  * Manages physical address maps.
49  *
50  * In most cases we hold page table pages busy in order to manipulate them.
51  */
52 /*
53  * PMAP_DEBUG - see platform/pc32/include/pmap.h
54  */
55
56 #include "opt_disable_pse.h"
57 #include "opt_pmap.h"
58 #include "opt_msgbuf.h"
59
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/kernel.h>
63 #include <sys/proc.h>
64 #include <sys/msgbuf.h>
65 #include <sys/vmmeter.h>
66 #include <sys/mman.h>
67 #include <sys/thread.h>
68
69 #include <vm/vm.h>
70 #include <vm/vm_param.h>
71 #include <sys/sysctl.h>
72 #include <sys/lock.h>
73 #include <vm/vm_kern.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_map.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_pageout.h>
79 #include <vm/vm_pager.h>
80 #include <vm/vm_zone.h>
81
82 #include <sys/user.h>
83 #include <sys/thread2.h>
84 #include <sys/sysref2.h>
85 #include <sys/spinlock2.h>
86 #include <vm/vm_page2.h>
87
88 #include <machine/cputypes.h>
89 #include <machine/md_var.h>
90 #include <machine/specialreg.h>
91 #include <machine/smp.h>
92 #include <machine_base/apic/apicreg.h>
93 #include <machine/globaldata.h>
94 #include <machine/pmap.h>
95 #include <machine/pmap_inval.h>
96
97 #define PMAP_KEEP_PDIRS
98 #ifndef PMAP_SHPGPERPROC
99 #define PMAP_SHPGPERPROC 200
100 #define PMAP_PVLIMIT     1400000        /* i386 kvm problems */
101 #endif
102
103 #if defined(DIAGNOSTIC)
104 #define PMAP_DIAGNOSTIC
105 #endif
106
107 #define MINPV 2048
108
109 #if !defined(PMAP_DIAGNOSTIC)
110 #define PMAP_INLINE __inline
111 #else
112 #define PMAP_INLINE
113 #endif
114
115 /*
116  * Get PDEs and PTEs for user/kernel address space
117  */
118 #define pmap_pde(m, v)  (&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
119 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
120
121 #define pmap_pde_v(pte)         ((*(int *)pte & PG_V) != 0)
122 #define pmap_pte_w(pte)         ((*(int *)pte & PG_W) != 0)
123 #define pmap_pte_m(pte)         ((*(int *)pte & PG_M) != 0)
124 #define pmap_pte_u(pte)         ((*(int *)pte & PG_A) != 0)
125 #define pmap_pte_v(pte)         ((*(int *)pte & PG_V) != 0)
126
127 /*
128  * Given a map and a machine independent protection code,
129  * convert to a vax protection code.
130  */
131 #define pte_prot(m, p)          \
132         (protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
133 static int protection_codes[8];
134
135 struct pmap kernel_pmap;
136 static TAILQ_HEAD(,pmap)        pmap_list = TAILQ_HEAD_INITIALIZER(pmap_list);
137
138 vm_paddr_t avail_start;         /* PA of first available physical page */
139 vm_paddr_t avail_end;           /* PA of last available physical page */
140 vm_offset_t virtual_start;      /* VA of first avail page (after kernel bss) */
141 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
142 vm_offset_t virtual2_start;
143 vm_offset_t virtual2_end;
144 vm_offset_t KvaStart;           /* VA start of KVA space */
145 vm_offset_t KvaEnd;             /* VA end of KVA space (non-inclusive) */
146 vm_offset_t KvaSize;            /* max size of kernel virtual address space */
147 static boolean_t pmap_initialized = FALSE;      /* Has pmap_init completed? */
148 static int pgeflag;             /* PG_G or-in */
149 static int pseflag;             /* PG_PS or-in */
150 uint64_t PatMsr;
151
152 static vm_object_t kptobj;
153
154 static int nkpt;
155 vm_offset_t kernel_vm_end;
156
157 #define PAT_INDEX_SIZE  8
158 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE];        /* PAT -> PG_ bits */
159 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/    /* PAT -> PG_ bits */
160
161 /*
162  * Data for the pv entry allocation mechanism
163  */
164 static vm_zone_t pvzone;
165 static struct vm_zone pvzone_store;
166 static struct vm_object pvzone_obj;
167 static int pv_entry_count=0, pv_entry_max=0, pv_entry_high_water=0;
168 static int pmap_pagedaemon_waken = 0;
169 static struct pv_entry *pvinit;
170
171 /*
172  * Considering all the issues I'm having with pmap caching, if breakage
173  * continues to occur, and for debugging, I've added a sysctl that will
174  * just do an unconditional invltlb.
175  */
176 static int dreadful_invltlb;
177
178 SYSCTL_INT(_vm, OID_AUTO, dreadful_invltlb,
179            CTLFLAG_RW, &dreadful_invltlb, 0, "Debugging sysctl to force invltlb on pmap operations");
180
181 /*
182  * All those kernel PT submaps that BSD is so fond of
183  */
184 pt_entry_t *CMAP1 = NULL, *ptmmap;
185 caddr_t CADDR1 = NULL, ptvmmap = NULL;
186 static pt_entry_t *msgbufmap;
187 struct msgbuf *msgbufp=NULL;
188
189 /*
190  * Crashdump maps.
191  */
192 static pt_entry_t *pt_crashdumpmap;
193 static caddr_t crashdumpmap;
194
195 extern pt_entry_t *SMPpt;
196
197 static PMAP_INLINE void free_pv_entry (pv_entry_t pv);
198 static unsigned * get_ptbase (pmap_t pmap);
199 static pv_entry_t get_pv_entry (void);
200 static void     i386_protection_init (void);
201 static __inline void    pmap_clearbit (vm_page_t m, int bit);
202
203 static void pmap_remove_all (vm_page_t m);
204 static void pmap_remove_pte (struct pmap *pmap, unsigned *ptq,
205                                 vm_offset_t sva, pmap_inval_info_t info);
206 static void pmap_remove_page (struct pmap *pmap, 
207                                 vm_offset_t va, pmap_inval_info_t info);
208 static void pmap_remove_entry (struct pmap *pmap, vm_page_t m,
209                                 vm_offset_t va, pmap_inval_info_t info);
210 static boolean_t pmap_testbit (vm_page_t m, int bit);
211 static void pmap_insert_entry (pmap_t pmap, pv_entry_t pv,
212                                 vm_offset_t va, vm_page_t mpte, vm_page_t m);
213
214 static vm_page_t pmap_allocpte (pmap_t pmap, vm_offset_t va);
215
216 static int pmap_release_free_page (pmap_t pmap, vm_page_t p);
217 static vm_page_t _pmap_allocpte (pmap_t pmap, unsigned ptepindex);
218 static unsigned * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
219 static vm_page_t pmap_page_lookup (vm_object_t object, vm_pindex_t pindex);
220 static void pmap_unuse_pt (pmap_t, vm_offset_t, vm_page_t, pmap_inval_info_t);
221 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
222
223 static void pmap_hold(pmap_t pmap);
224 static void pmap_drop(pmap_t pmap);
225 static void pmap_wait(pmap_t pmap, int count);
226
227 static unsigned pdir4mb;
228
229 static __inline
230 void
231 pmap_page_stats_adding(vm_page_t m)
232 {
233         globaldata_t gd = mycpu;
234
235         if (TAILQ_EMPTY(&m->md.pv_list)) {
236                 ++gd->gd_vmtotal.t_arm;
237         } else if (TAILQ_FIRST(&m->md.pv_list) ==
238                    TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
239                 ++gd->gd_vmtotal.t_armshr;
240                 ++gd->gd_vmtotal.t_avmshr;
241         } else {
242                 ++gd->gd_vmtotal.t_avmshr;
243         }
244 }
245
246 static __inline
247 void
248 pmap_page_stats_deleting(vm_page_t m)
249 {
250         globaldata_t gd = mycpu;
251
252         if (TAILQ_EMPTY(&m->md.pv_list)) {
253                 --gd->gd_vmtotal.t_arm;
254         } else if (TAILQ_FIRST(&m->md.pv_list) ==
255                    TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
256                 --gd->gd_vmtotal.t_armshr;
257                 --gd->gd_vmtotal.t_avmshr;
258         } else {
259                 --gd->gd_vmtotal.t_avmshr;
260         }
261 }
262
263 /*
264  * Move the kernel virtual free pointer to the next
265  * 4MB.  This is used to help improve performance
266  * by using a large (4MB) page for much of the kernel
267  * (.text, .data, .bss)
268  */
269 static
270 vm_offset_t
271 pmap_kmem_choose(vm_offset_t addr)
272 {
273         vm_offset_t newaddr = addr;
274 #ifndef DISABLE_PSE
275         if (cpu_feature & CPUID_PSE) {
276                 newaddr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
277         }
278 #endif
279         return newaddr;
280 }
281
282 /*
283  * This function returns a pointer to the pte entry in the pmap and has
284  * the side effect of potentially retaining a cached mapping of the pmap.
285  *
286  * The caller must hold vm_token and the returned value is only valid
287  * until the caller blocks or releases the token.
288  */
289 static
290 unsigned *
291 pmap_pte(pmap_t pmap, vm_offset_t va)
292 {
293         unsigned *pdeaddr;
294
295         ASSERT_LWKT_TOKEN_HELD(&vm_token);
296         if (pmap) {
297                 pdeaddr = (unsigned *) pmap_pde(pmap, va);
298                 if (*pdeaddr & PG_PS)
299                         return pdeaddr;
300                 if (*pdeaddr)
301                         return get_ptbase(pmap) + i386_btop(va);
302         }
303         return (0);
304 }
305
306 /*
307  * pmap_pte using the kernel_pmap
308  *
309  * Used for debugging, no requirements.
310  */
311 unsigned *
312 pmap_kernel_pte(vm_offset_t va)
313 {
314         unsigned *pdeaddr;
315
316         pdeaddr = (unsigned *) pmap_pde(&kernel_pmap, va);
317         if (*pdeaddr & PG_PS)
318                 return pdeaddr;
319         if (*pdeaddr)
320                 return (unsigned *)vtopte(va);
321         return(0);
322 }
323
324 /*
325  * pmap_pte_quick:
326  *
327  * Super fast pmap_pte routine best used when scanning the pv lists.
328  * This eliminates many course-grained invltlb calls.  Note that many of
329  * the pv list scans are across different pmaps and it is very wasteful
330  * to do an entire invltlb when checking a single mapping.
331  *
332  * Should only be called while in a critical section.
333  *
334  * The caller must hold vm_token and the returned value is only valid
335  * until the caller blocks or releases the token.
336  */
337 static
338 unsigned *
339 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
340 {
341         struct mdglobaldata *gd = mdcpu;
342         unsigned pde, newpf;
343
344         ASSERT_LWKT_TOKEN_HELD(&vm_token);
345         if ((pde = (unsigned) pmap->pm_pdir[va >> PDRSHIFT]) != 0) {
346                 unsigned frame = (unsigned) pmap->pm_pdir[PTDPTDI] & PG_FRAME;
347                 unsigned index = i386_btop(va);
348                 /* are we current address space or kernel? */
349                 if ((pmap == &kernel_pmap) ||
350                         (frame == (((unsigned) PTDpde) & PG_FRAME))) {
351                         return (unsigned *) PTmap + index;
352                 }
353                 newpf = pde & PG_FRAME;
354                 if (((*(unsigned *)gd->gd_PMAP1) & PG_FRAME) != newpf) {
355                         *(unsigned *)gd->gd_PMAP1 = newpf | PG_RW | PG_V;
356                         cpu_invlpg(gd->gd_PADDR1);
357                 }
358                 return gd->gd_PADDR1 + (index & (NPTEPG - 1));
359         }
360         return (0);
361 }
362
363
364 /*
365  * Bootstrap the system enough to run with virtual memory.
366  *
367  * On the i386 this is called after mapping has already been enabled
368  * and just syncs the pmap module with what has already been done.
369  * [We can't call it easily with mapping off since the kernel is not
370  * mapped with PA == VA, hence we would have to relocate every address
371  * from the linked base (virtual) address "KERNBASE" to the actual
372  * (physical) address starting relative to 0]
373  */
374 void
375 pmap_bootstrap(vm_paddr_t firstaddr, vm_paddr_t loadaddr)
376 {
377         vm_offset_t va;
378         pt_entry_t *pte;
379         struct mdglobaldata *gd;
380         int i;
381         int pg;
382
383         KvaStart = (vm_offset_t)VADDR(PTDPTDI, 0);
384         KvaSize = (vm_offset_t)VADDR(APTDPTDI, 0) - KvaStart;
385         KvaEnd  = KvaStart + KvaSize;
386
387         avail_start = firstaddr;
388
389         /*
390          * XXX The calculation of virtual_start is wrong. It's NKPT*PAGE_SIZE
391          * too large. It should instead be correctly calculated in locore.s and
392          * not based on 'first' (which is a physical address, not a virtual
393          * address, for the start of unused physical memory). The kernel
394          * page tables are NOT double mapped and thus should not be included
395          * in this calculation.
396          */
397         virtual_start = (vm_offset_t) KERNBASE + firstaddr;
398         virtual_start = pmap_kmem_choose(virtual_start);
399         virtual_end = VADDR(KPTDI+NKPDE-1, NPTEPG-1);
400
401         /*
402          * Initialize protection array.
403          */
404         i386_protection_init();
405
406         /*
407          * The kernel's pmap is statically allocated so we don't have to use
408          * pmap_create, which is unlikely to work correctly at this part of
409          * the boot sequence (XXX and which no longer exists).
410          *
411          * The kernel_pmap's pm_pteobj is used only for locking and not
412          * for mmu pages.
413          */
414         kernel_pmap.pm_pdir = (pd_entry_t *)(KERNBASE + (u_int)IdlePTD);
415         kernel_pmap.pm_count = 1;
416         kernel_pmap.pm_active = (cpumask_t)-1 & ~CPUMASK_LOCK;
417         kernel_pmap.pm_pteobj = &kernel_object;
418         TAILQ_INIT(&kernel_pmap.pm_pvlist);
419         TAILQ_INIT(&kernel_pmap.pm_pvlist_free);
420         spin_init(&kernel_pmap.pm_spin);
421         lwkt_token_init(&kernel_pmap.pm_token, "kpmap_tok");
422         nkpt = NKPT;
423
424         /*
425          * Reserve some special page table entries/VA space for temporary
426          * mapping of pages.
427          */
428 #define SYSMAP(c, p, v, n)      \
429         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
430
431         va = virtual_start;
432         pte = (pt_entry_t *) pmap_kernel_pte(va);
433
434         /*
435          * CMAP1/CMAP2 are used for zeroing and copying pages.
436          */
437         SYSMAP(caddr_t, CMAP1, CADDR1, 1)
438
439         /*
440          * Crashdump maps.
441          */
442         SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
443
444         /*
445          * ptvmmap is used for reading arbitrary physical pages via
446          * /dev/mem.
447          */
448         SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
449
450         /*
451          * msgbufp is used to map the system message buffer.
452          * XXX msgbufmap is not used.
453          */
454         SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
455                atop(round_page(MSGBUF_SIZE)))
456
457         virtual_start = va;
458
459         *(int *) CMAP1 = 0;
460         for (i = 0; i < NKPT; i++)
461                 PTD[i] = 0;
462
463         /*
464          * PG_G is terribly broken on SMP because we IPI invltlb's in some
465          * cases rather then invl1pg.  Actually, I don't even know why it
466          * works under UP because self-referential page table mappings
467          */
468         pgeflag = 0;
469         
470 /*
471  * Initialize the 4MB page size flag
472  */
473         pseflag = 0;
474 /*
475  * The 4MB page version of the initial
476  * kernel page mapping.
477  */
478         pdir4mb = 0;
479
480 #if !defined(DISABLE_PSE)
481         if (cpu_feature & CPUID_PSE) {
482                 unsigned ptditmp;
483                 /*
484                  * Note that we have enabled PSE mode
485                  */
486                 pseflag = PG_PS;
487                 ptditmp = *((unsigned *)PTmap + i386_btop(KERNBASE));
488                 ptditmp &= ~(NBPDR - 1);
489                 ptditmp |= PG_V | PG_RW | PG_PS | PG_U | pgeflag;
490                 pdir4mb = ptditmp;
491         }
492 #endif
493
494         /*
495          * We need to finish setting up the globaldata page for the BSP.
496          * locore has already populated the page table for the mdglobaldata
497          * portion.
498          */
499         pg = MDGLOBALDATA_BASEALLOC_PAGES;
500         gd = &CPU_prvspace[0].mdglobaldata;
501         gd->gd_CMAP1 = &SMPpt[pg + 0];
502         gd->gd_CMAP2 = &SMPpt[pg + 1];
503         gd->gd_CMAP3 = &SMPpt[pg + 2];
504         gd->gd_PMAP1 = &SMPpt[pg + 3];
505         gd->gd_GDMAP1 = &PTD[APTDPTDI];
506         gd->gd_CADDR1 = CPU_prvspace[0].CPAGE1;
507         gd->gd_CADDR2 = CPU_prvspace[0].CPAGE2;
508         gd->gd_CADDR3 = CPU_prvspace[0].CPAGE3;
509         gd->gd_PADDR1 = (unsigned *)CPU_prvspace[0].PPAGE1;
510         gd->gd_GDADDR1= (unsigned *)VADDR(APTDPTDI, 0);
511
512         cpu_invltlb();
513
514         /* Initialize the PAT MSR */
515         pmap_init_pat();
516 }
517
518 /*
519  * Setup the PAT MSR.
520  */
521 void
522 pmap_init_pat(void)
523 {
524         uint64_t pat_msr;
525         u_long cr0, cr4;
526
527         /*
528          * Default values mapping PATi,PCD,PWT bits at system reset.
529          * The default values effectively ignore the PATi bit by
530          * repeating the encodings for 0-3 in 4-7, and map the PCD
531          * and PWT bit combinations to the expected PAT types.
532          */
533         pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |        /* 000 */
534                   PAT_VALUE(1, PAT_WRITE_THROUGH) |     /* 001 */
535                   PAT_VALUE(2, PAT_UNCACHED) |          /* 010 */
536                   PAT_VALUE(3, PAT_UNCACHEABLE) |       /* 011 */
537                   PAT_VALUE(4, PAT_WRITE_BACK) |        /* 100 */
538                   PAT_VALUE(5, PAT_WRITE_THROUGH) |     /* 101 */
539                   PAT_VALUE(6, PAT_UNCACHED) |          /* 110 */
540                   PAT_VALUE(7, PAT_UNCACHEABLE);        /* 111 */
541         pat_pte_index[PAT_WRITE_BACK]   = 0;
542         pat_pte_index[PAT_WRITE_THROUGH]= 0         | PG_NC_PWT;
543         pat_pte_index[PAT_UNCACHED]     = PG_NC_PCD;
544         pat_pte_index[PAT_UNCACHEABLE]  = PG_NC_PCD | PG_NC_PWT;
545         pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
546         pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
547
548         if (cpu_feature & CPUID_PAT) {
549                 /*
550                  * If we support the PAT then set-up entries for
551                  * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
552                  * 4 and 5.
553                  */
554                 pat_msr = (pat_msr & ~PAT_MASK(4)) |
555                           PAT_VALUE(4, PAT_WRITE_PROTECTED);
556                 pat_msr = (pat_msr & ~PAT_MASK(5)) |
557                           PAT_VALUE(5, PAT_WRITE_COMBINING);
558                 pat_pte_index[PAT_WRITE_PROTECTED] = PG_PTE_PAT | 0;
559                 pat_pte_index[PAT_WRITE_COMBINING] = PG_PTE_PAT | PG_NC_PWT;
560
561                 /*
562                  * Then enable the PAT
563                  */
564
565                 /* Disable PGE. */
566                 cr4 = rcr4();
567                 load_cr4(cr4 & ~CR4_PGE);
568
569                 /* Disable caches (CD = 1, NW = 0). */
570                 cr0 = rcr0();
571                 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
572
573                 /* Flushes caches and TLBs. */
574                 wbinvd();
575                 cpu_invltlb();
576
577                 /* Update PAT and index table. */
578                 wrmsr(MSR_PAT, pat_msr);
579
580                 /* Flush caches and TLBs again. */
581                 wbinvd();
582                 cpu_invltlb();
583
584                 /* Restore caches and PGE. */
585                 load_cr0(cr0);
586                 load_cr4(cr4);
587                 PatMsr = pat_msr;
588         }
589 }
590
591 /*
592  * Set 4mb pdir for mp startup
593  */
594 void
595 pmap_set_opt(void)
596 {
597         if (pseflag && (cpu_feature & CPUID_PSE)) {
598                 load_cr4(rcr4() | CR4_PSE);
599                 if (pdir4mb && mycpu->gd_cpuid == 0) {  /* only on BSP */
600                         kernel_pmap.pm_pdir[KPTDI] =
601                             PTD[KPTDI] = (pd_entry_t)pdir4mb;
602                         cpu_invltlb();
603                 }
604         }
605 }
606
607 /*
608  * Initialize the pmap module, called by vm_init()
609  *
610  * Called from the low level boot code only.
611  */
612 void
613 pmap_init(void)
614 {
615         int i;
616         int initial_pvs;
617
618         /*
619          * object for kernel page table pages
620          */
621         kptobj = vm_object_allocate(OBJT_DEFAULT, NKPDE);
622
623         /*
624          * Allocate memory for random pmap data structures.  Includes the
625          * pv_head_table.
626          */
627
628         for(i = 0; i < vm_page_array_size; i++) {
629                 vm_page_t m;
630
631                 m = &vm_page_array[i];
632                 TAILQ_INIT(&m->md.pv_list);
633                 m->md.pv_list_count = 0;
634         }
635
636         /*
637          * init the pv free list
638          */
639         initial_pvs = vm_page_array_size;
640         if (initial_pvs < MINPV)
641                 initial_pvs = MINPV;
642         pvzone = &pvzone_store;
643         pvinit = (void *)kmem_alloc(&kernel_map,
644                                     initial_pvs * sizeof (struct pv_entry));
645         zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
646                   pvinit, initial_pvs);
647
648         /*
649          * Now it is safe to enable pv_table recording.
650          */
651         pmap_initialized = TRUE;
652 }
653
654 /*
655  * Initialize the address space (zone) for the pv_entries.  Set a
656  * high water mark so that the system can recover from excessive
657  * numbers of pv entries.
658  *
659  * Called from the low level boot code only.
660  */
661 void
662 pmap_init2(void)
663 {
664         int shpgperproc = PMAP_SHPGPERPROC;
665         int entry_max;
666
667         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
668         pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
669
670 #ifdef PMAP_PVLIMIT
671         /*
672          * Horrible hack for systems with a lot of memory running i386.
673          * the calculated pv_entry_max can wind up eating a ton of KVM
674          * so put a cap on the number of entries if the user did not
675          * change any of the values.   This saves about 44MB of KVM on
676          * boxes with 3+GB of ram.
677          *
678          * On the flip side, this makes it more likely that some setups
679          * will run out of pv entries.  Those sysads will have to bump
680          * the limit up with vm.pamp.pv_entries or vm.pmap.shpgperproc.
681          */
682         if (shpgperproc == PMAP_SHPGPERPROC) {
683                 if (pv_entry_max > PMAP_PVLIMIT)
684                         pv_entry_max = PMAP_PVLIMIT;
685         }
686 #endif
687         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
688         pv_entry_high_water = 9 * (pv_entry_max / 10);
689
690         /*
691          * Subtract out pages already installed in the zone (hack)
692          */
693         entry_max = pv_entry_max - vm_page_array_size;
694         if (entry_max <= 0)
695                 entry_max = 1;
696
697         zinitna(pvzone, &pvzone_obj, NULL, 0, entry_max, ZONE_INTERRUPT, 1);
698 }
699
700 /*
701  * Typically used to initialize a fictitious page by vm/device_pager.c
702  */
703 void
704 pmap_page_init(struct vm_page *m)
705 {
706         vm_page_init(m);
707         TAILQ_INIT(&m->md.pv_list);
708 }
709
710 /***************************************************
711  * Low level helper routines.....
712  ***************************************************/
713
714 #ifdef PMAP_DEBUG
715
716 static void
717 test_m_maps_pv(vm_page_t m, pv_entry_t pv)
718 {
719         pv_entry_t spv;
720
721         crit_enter();
722 #ifdef PMAP_DEBUG
723         KKASSERT(pv->pv_m == m);
724 #endif
725         TAILQ_FOREACH(spv, &m->md.pv_list, pv_list) {
726                 if (pv == spv) {
727                         crit_exit();
728                         return;
729                 }
730         }
731         crit_exit();
732         panic("test_m_maps_pv: failed m %p pv %p", m, pv);
733 }
734
735 static void
736 ptbase_assert(struct pmap *pmap)
737 {
738         unsigned frame = (unsigned) pmap->pm_pdir[PTDPTDI] & PG_FRAME;
739
740         /* are we current address space or kernel? */
741         if (pmap == &kernel_pmap || frame == (((unsigned)PTDpde) & PG_FRAME))
742                 return;
743         KKASSERT(frame == (*mdcpu->gd_GDMAP1 & PG_FRAME));
744 }
745
746 #else
747
748 #define test_m_maps_pv(m, pv)
749 #define ptbase_assert(pmap)
750
751 #endif
752
753 #if defined(PMAP_DIAGNOSTIC)
754
755 /*
756  * This code checks for non-writeable/modified pages.
757  * This should be an invalid condition.
758  */
759 static int
760 pmap_nw_modified(pt_entry_t ptea)
761 {
762         int pte;
763
764         pte = (int) ptea;
765
766         if ((pte & (PG_M|PG_RW)) == PG_M)
767                 return 1;
768         else
769                 return 0;
770 }
771 #endif
772
773
774 /*
775  * This routine defines the region(s) of memory that should not be tested
776  * for the modified bit.
777  *
778  * No requirements.
779  */
780 static PMAP_INLINE int
781 pmap_track_modified(vm_offset_t va)
782 {
783         if ((va < clean_sva) || (va >= clean_eva)) 
784                 return 1;
785         else
786                 return 0;
787 }
788
789 /*
790  * Retrieve the mapped page table base for a particular pmap.  Use our self
791  * mapping for the kernel_pmap or our current pmap.
792  *
793  * For foreign pmaps we use the per-cpu page table map.  Since this involves
794  * installing a ptd it's actually (per-process x per-cpu).  However, we
795  * still cannot depend on our mapping to survive thread switches because
796  * the process might be threaded and switching to another thread for the
797  * same process on the same cpu will allow that other thread to make its
798  * own mapping.
799  *
800  * This could be a bit confusing but the jist is for something like the
801  * vkernel which uses foreign pmaps all the time this represents a pretty
802  * good cache that avoids unnecessary invltlb()s.
803  *
804  * The caller must hold vm_token and the returned value is only valid
805  * until the caller blocks or releases the token.
806  */
807 static unsigned *
808 get_ptbase(pmap_t pmap)
809 {
810         unsigned frame = (unsigned) pmap->pm_pdir[PTDPTDI] & PG_FRAME;
811         struct mdglobaldata *gd = mdcpu;
812
813         ASSERT_LWKT_TOKEN_HELD(&vm_token);
814
815         /*
816          * We can use PTmap if the pmap is our current address space or
817          * the kernel address space.
818          */
819         if (pmap == &kernel_pmap || frame == (((unsigned) PTDpde) & PG_FRAME)) {
820                 return (unsigned *) PTmap;
821         }
822
823         /*
824          * Otherwise we use the per-cpu alternative page table map.  Each
825          * cpu gets its own map.  Because of this we cannot use this map
826          * from interrupts or threads which can preempt.
827          *
828          * Even if we already have the map cached we may still have to
829          * invalidate the TLB if another cpu modified a PDE in the map.
830          */
831         KKASSERT(gd->mi.gd_intr_nesting_level == 0 &&
832                  (gd->mi.gd_curthread->td_flags & TDF_INTTHREAD) == 0);
833
834         if ((*gd->gd_GDMAP1 & PG_FRAME) != frame) {
835                 *gd->gd_GDMAP1 = frame | PG_RW | PG_V;
836                 pmap->pm_cached |= gd->mi.gd_cpumask;
837                 cpu_invltlb();
838         } else if ((pmap->pm_cached & gd->mi.gd_cpumask) == 0) {
839                 pmap->pm_cached |= gd->mi.gd_cpumask;
840                 cpu_invltlb();
841         } else if (dreadful_invltlb) {
842                 cpu_invltlb();
843         }
844         return ((unsigned *)gd->gd_GDADDR1);
845 }
846
847 /*
848  * pmap_extract:
849  *
850  * Extract the physical page address associated with the map/VA pair.
851  *
852  * The caller may hold vm_token if it desires non-blocking operation.
853  */
854 vm_paddr_t 
855 pmap_extract(pmap_t pmap, vm_offset_t va)
856 {
857         vm_offset_t rtval;
858         vm_offset_t pdirindex;
859
860         lwkt_gettoken(&vm_token);
861         pdirindex = va >> PDRSHIFT;
862         if (pmap && (rtval = (unsigned) pmap->pm_pdir[pdirindex])) {
863                 unsigned *pte;
864                 if ((rtval & PG_PS) != 0) {
865                         rtval &= ~(NBPDR - 1);
866                         rtval |= va & (NBPDR - 1);
867                 } else {
868                         pte = get_ptbase(pmap) + i386_btop(va);
869                         rtval = ((*pte & PG_FRAME) | (va & PAGE_MASK));
870                 }
871         } else {
872                 rtval = 0;
873         }
874         lwkt_reltoken(&vm_token);
875         return rtval;
876 }
877
878 /*
879  * Similar to extract but checks protections, SMP-friendly short-cut for
880  * vm_fault_page[_quick]().
881  */
882 vm_page_t
883 pmap_fault_page_quick(pmap_t pmap __unused, vm_offset_t vaddr __unused,
884                       vm_prot_t prot __unused)
885 {
886         return(NULL);
887 }
888
889 /***************************************************
890  * Low level mapping routines.....
891  ***************************************************/
892
893 /*
894  * Map a wired VM page to a KVA, fully SMP synchronized.
895  *
896  * No requirements, non blocking.
897  */
898 void 
899 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
900 {
901         unsigned *pte;
902         unsigned npte;
903         pmap_inval_info info;
904
905         pmap_inval_init(&info);
906         npte = pa | PG_RW | PG_V | pgeflag;
907         pte = (unsigned *)vtopte(va);
908         pmap_inval_interlock(&info, &kernel_pmap, va);
909         *pte = npte;
910         pmap_inval_deinterlock(&info, &kernel_pmap);
911         pmap_inval_done(&info);
912 }
913
914 /*
915  * Map a wired VM page to a KVA, synchronized on current cpu only.
916  *
917  * No requirements, non blocking.
918  */
919 void
920 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
921 {
922         unsigned *pte;
923         unsigned npte;
924
925         npte = pa | PG_RW | PG_V | pgeflag;
926         pte = (unsigned *)vtopte(va);
927         *pte = npte;
928         cpu_invlpg((void *)va);
929 }
930
931 /*
932  * Synchronize a previously entered VA on all cpus.
933  *
934  * No requirements, non blocking.
935  */
936 void
937 pmap_kenter_sync(vm_offset_t va)
938 {
939         pmap_inval_info info;
940
941         pmap_inval_init(&info);
942         pmap_inval_interlock(&info, &kernel_pmap, va);
943         pmap_inval_deinterlock(&info, &kernel_pmap);
944         pmap_inval_done(&info);
945 }
946
947 /*
948  * Synchronize a previously entered VA on the current cpu only.
949  *
950  * No requirements, non blocking.
951  */
952 void
953 pmap_kenter_sync_quick(vm_offset_t va)
954 {
955         cpu_invlpg((void *)va);
956 }
957
958 /*
959  * Remove a page from the kernel pagetables, fully SMP synchronized.
960  *
961  * No requirements, non blocking.
962  */
963 void
964 pmap_kremove(vm_offset_t va)
965 {
966         unsigned *pte;
967         pmap_inval_info info;
968
969         pmap_inval_init(&info);
970         pte = (unsigned *)vtopte(va);
971         pmap_inval_interlock(&info, &kernel_pmap, va);
972         *pte = 0;
973         pmap_inval_deinterlock(&info, &kernel_pmap);
974         pmap_inval_done(&info);
975 }
976
977 /*
978  * Remove a page from the kernel pagetables, synchronized on current cpu only.
979  *
980  * No requirements, non blocking.
981  */
982 void
983 pmap_kremove_quick(vm_offset_t va)
984 {
985         unsigned *pte;
986         pte = (unsigned *)vtopte(va);
987         *pte = 0;
988         cpu_invlpg((void *)va);
989 }
990
991 /*
992  * Adjust the permissions of a page in the kernel page table,
993  * synchronized on the current cpu only.
994  *
995  * No requirements, non blocking.
996  */
997 void
998 pmap_kmodify_rw(vm_offset_t va)
999 {
1000         atomic_set_int(vtopte(va), PG_RW);
1001         cpu_invlpg((void *)va);
1002 }
1003
1004 /*
1005  * Adjust the permissions of a page in the kernel page table,
1006  * synchronized on the current cpu only.
1007  *
1008  * No requirements, non blocking.
1009  */
1010 void
1011 pmap_kmodify_nc(vm_offset_t va)
1012 {
1013         atomic_set_int(vtopte(va), PG_N);
1014         cpu_invlpg((void *)va);
1015 }
1016
1017 /*
1018  * Map a range of physical addresses into kernel virtual address space.
1019  *
1020  * No requirements, non blocking.
1021  */
1022 vm_offset_t
1023 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1024 {
1025         vm_offset_t     sva, virt;
1026
1027         sva = virt = *virtp;
1028         while (start < end) {
1029                 pmap_kenter(virt, start);
1030                 virt += PAGE_SIZE;
1031                 start += PAGE_SIZE;
1032         }
1033         *virtp = virt;
1034         return (sva);
1035 }
1036
1037 #define PMAP_CLFLUSH_THRESHOLD  (2 * 1024 * 1024)
1038
1039 /*
1040  * Remove the specified set of pages from the data and instruction caches.
1041  *
1042  * In contrast to pmap_invalidate_cache_range(), this function does not
1043  * rely on the CPU's self-snoop feature, because it is intended for use
1044  * when moving pages into a different cache domain.
1045  */
1046 void
1047 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1048 {
1049         wbinvd();       /* XXX: not optimal */
1050 }
1051
1052 void
1053 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1054 {
1055         KASSERT((sva & PAGE_MASK) == 0,
1056             ("pmap_invalidate_cache_range: sva not page-aligned"));
1057         KASSERT((eva & PAGE_MASK) == 0,
1058             ("pmap_invalidate_cache_range: eva not page-aligned"));
1059
1060         if (cpu_feature & CPUID_SS) {
1061                 ; /* If "Self Snoop" is supported, do nothing. */
1062         } else {
1063                 /* Globally invalidate caches */
1064                 cpu_wbinvd_on_all_cpus();
1065         }
1066 }
1067
1068 void
1069 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1070 {
1071         cpu_wbinvd_on_all_cpus();       /* XXX not optimal */
1072 }
1073
1074 /*
1075  * Add a list of wired pages to the kva
1076  * this routine is only used for temporary
1077  * kernel mappings that do not need to have
1078  * page modification or references recorded.
1079  * Note that old mappings are simply written
1080  * over.  The page *must* be wired.
1081  */
1082 void
1083 pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
1084 {
1085         vm_offset_t end_va;
1086
1087         end_va = va + count * PAGE_SIZE;
1088                 
1089         while (va < end_va) {
1090                 pt_entry_t *pte;
1091
1092                 pte = vtopte(va);
1093                 *pte = VM_PAGE_TO_PHYS(*m) | PG_RW | PG_V |
1094                         pat_pte_index[(*m)->pat_mode] | pgeflag;
1095                 cpu_invlpg((void *)va);
1096                 va += PAGE_SIZE;
1097                 m++;
1098         }
1099         smp_invltlb();  /* XXX */
1100 }
1101
1102 /*
1103  * Remove pages from KVA, fully SMP synchronized.
1104  *
1105  * No requirements, non blocking.
1106  */
1107 void
1108 pmap_qremove(vm_offset_t va, int count)
1109 {
1110         vm_offset_t end_va;
1111
1112         end_va = va + count*PAGE_SIZE;
1113
1114         while (va < end_va) {
1115                 unsigned *pte;
1116
1117                 pte = (unsigned *)vtopte(va);
1118                 *pte = 0;
1119                 cpu_invlpg((void *)va);
1120                 va += PAGE_SIZE;
1121         }
1122         smp_invltlb();
1123 }
1124
1125 /*
1126  * This routine works like vm_page_lookup() but also blocks as long as the
1127  * page is busy.  This routine does not busy the page it returns.
1128  *
1129  * The caller must hold the object.
1130  */
1131 static vm_page_t
1132 pmap_page_lookup(vm_object_t object, vm_pindex_t pindex)
1133 {
1134         vm_page_t m;
1135
1136         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1137         m = vm_page_lookup_busy_wait(object, pindex, FALSE, "pplookp");
1138
1139         return(m);
1140 }
1141
1142 /*
1143  * Create a new thread and optionally associate it with a (new) process.
1144  * NOTE! the new thread's cpu may not equal the current cpu.
1145  */
1146 void
1147 pmap_init_thread(thread_t td)
1148 {
1149         /* enforce pcb placement */
1150         td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
1151         td->td_savefpu = &td->td_pcb->pcb_save;
1152         td->td_sp = (char *)td->td_pcb - 16;
1153 }
1154
1155 /*
1156  * This routine directly affects the fork perf for a process.
1157  */
1158 void
1159 pmap_init_proc(struct proc *p)
1160 {
1161 }
1162
1163 /***************************************************
1164  * Page table page management routines.....
1165  ***************************************************/
1166
1167 /*
1168  * This routine unwires page table pages, removing and freeing the page
1169  * tale page when the wire count drops to 0.
1170  *
1171  * The caller must hold vm_token.
1172  * This function can block.
1173  */
1174 static int 
1175 _pmap_unwire_pte(pmap_t pmap, vm_page_t m, pmap_inval_info_t info)
1176 {
1177         /* 
1178          * Wait until we can busy the page ourselves.  We cannot have
1179          * any active flushes if we block.
1180          */
1181         vm_page_busy_wait(m, FALSE, "pmuwpt");
1182         KASSERT(m->queue == PQ_NONE,
1183                 ("_pmap_unwire_pte: %p->queue != PQ_NONE", m));
1184
1185         if (m->wire_count == 1) {
1186                 /*
1187                  * Unmap the page table page.
1188                  *
1189                  * NOTE: We must clear pm_cached for all cpus, including
1190                  *       the current one, when clearing a page directory
1191                  *       entry.
1192                  */
1193                 pmap_inval_interlock(info, pmap, -1);
1194                 KKASSERT(pmap->pm_pdir[m->pindex]);
1195                 pmap->pm_pdir[m->pindex] = 0;
1196                 pmap->pm_cached = 0;
1197                 pmap_inval_deinterlock(info, pmap);
1198
1199                 KKASSERT(pmap->pm_stats.resident_count > 0);
1200                 --pmap->pm_stats.resident_count;
1201
1202                 if (pmap->pm_ptphint == m)
1203                         pmap->pm_ptphint = NULL;
1204
1205                 /*
1206                  * This was our last hold, the page had better be unwired
1207                  * after we decrement wire_count.
1208                  * 
1209                  * FUTURE NOTE: shared page directory page could result in
1210                  * multiple wire counts.
1211                  */
1212                 vm_page_unwire(m, 0);
1213                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1214                 vm_page_flash(m);
1215                 vm_page_free_zero(m);
1216                 return 1;
1217         } else {
1218                 KKASSERT(m->wire_count > 1);
1219                 if (vm_page_unwire_quick(m))
1220                         panic("pmap_unwire_pte: Insufficient wire_count");
1221                 vm_page_wakeup(m);
1222                 return 0;
1223         }
1224 }
1225
1226 /*
1227  * The caller must hold vm_token.
1228  *
1229  * This function can block.
1230  *
1231  * This function can race the wire_count 2->1 case because the page
1232  * is not busied during the unwire_quick operation.  An eventual
1233  * pmap_release() will catch the case.
1234  */
1235 static PMAP_INLINE int
1236 pmap_unwire_pte(pmap_t pmap, vm_page_t m, pmap_inval_info_t info)
1237 {
1238         KKASSERT(m->wire_count > 0);
1239         if (m->wire_count > 1) {
1240                 if (vm_page_unwire_quick(m))
1241                         panic("pmap_unwire_pte: Insufficient wire_count");
1242                 return 0;
1243         } else {
1244                 return _pmap_unwire_pte(pmap, m, info);
1245         }
1246 }
1247
1248 /*
1249  * After removing a (user) page table entry, this routine is used to
1250  * conditionally free the page, and manage the hold/wire counts.
1251  *
1252  * The caller must hold vm_token.
1253  * This function can block regardless.
1254  */
1255 static void
1256 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte,
1257               pmap_inval_info_t info)
1258 {
1259         unsigned ptepindex;
1260
1261         ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1262
1263         if (va >= UPT_MIN_ADDRESS)
1264                 return;
1265
1266         if (mpte == NULL) {
1267                 ptepindex = (va >> PDRSHIFT);
1268                 if ((mpte = pmap->pm_ptphint) != NULL &&
1269                     mpte->pindex == ptepindex &&
1270                     (mpte->flags & PG_BUSY) == 0) {
1271                         ; /* use mpte */
1272                 } else {
1273                         mpte = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1274                         pmap->pm_ptphint = mpte;
1275                         vm_page_wakeup(mpte);
1276                 }
1277         }
1278         pmap_unwire_pte(pmap, mpte, info);
1279 }
1280
1281 /*
1282  * Initialize pmap0/vmspace0.  This pmap is not added to pmap_list because
1283  * it, and IdlePTD, represents the template used to update all other pmaps.
1284  *
1285  * On architectures where the kernel pmap is not integrated into the user
1286  * process pmap, this pmap represents the process pmap, not the kernel pmap.
1287  * kernel_pmap should be used to directly access the kernel_pmap.
1288  *
1289  * No requirements.
1290  */
1291 void
1292 pmap_pinit0(struct pmap *pmap)
1293 {
1294         pmap->pm_pdir =
1295                 (pd_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
1296         pmap_kenter((vm_offset_t)pmap->pm_pdir, (vm_offset_t) IdlePTD);
1297         pmap->pm_count = 1;
1298         pmap->pm_active = 0;
1299         pmap->pm_cached = 0;
1300         pmap->pm_ptphint = NULL;
1301         TAILQ_INIT(&pmap->pm_pvlist);
1302         TAILQ_INIT(&pmap->pm_pvlist_free);
1303         spin_init(&pmap->pm_spin);
1304         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1305         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1306 }
1307
1308 /*
1309  * Initialize a preallocated and zeroed pmap structure,
1310  * such as one in a vmspace structure.
1311  *
1312  * No requirements.
1313  */
1314 void
1315 pmap_pinit(struct pmap *pmap)
1316 {
1317         vm_page_t ptdpg;
1318
1319         /*
1320          * No need to allocate page table space yet but we do need a valid
1321          * page directory table.
1322          */
1323         if (pmap->pm_pdir == NULL) {
1324                 pmap->pm_pdir =
1325                     (pd_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
1326         }
1327
1328         /*
1329          * Allocate an object for the ptes
1330          */
1331         if (pmap->pm_pteobj == NULL)
1332                 pmap->pm_pteobj = vm_object_allocate(OBJT_DEFAULT, PTDPTDI + 1);
1333
1334         /*
1335          * Allocate the page directory page, unless we already have
1336          * one cached.  If we used the cached page the wire_count will
1337          * already be set appropriately.
1338          */
1339         if ((ptdpg = pmap->pm_pdirm) == NULL) {
1340                 ptdpg = vm_page_grab(pmap->pm_pteobj, PTDPTDI,
1341                                      VM_ALLOC_NORMAL | VM_ALLOC_RETRY |
1342                                      VM_ALLOC_ZERO);
1343                 pmap->pm_pdirm = ptdpg;
1344                 vm_page_flag_clear(ptdpg, PG_MAPPED);
1345                 vm_page_wire(ptdpg);
1346                 KKASSERT(ptdpg->valid == VM_PAGE_BITS_ALL);
1347                 pmap_kenter((vm_offset_t)pmap->pm_pdir, VM_PAGE_TO_PHYS(ptdpg));
1348                 vm_page_wakeup(ptdpg);
1349         }
1350         pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1351
1352         /* install self-referential address mapping entry */
1353         *(unsigned *) (pmap->pm_pdir + PTDPTDI) =
1354                 VM_PAGE_TO_PHYS(ptdpg) | PG_V | PG_RW | PG_A | PG_M;
1355
1356         pmap->pm_count = 1;
1357         pmap->pm_active = 0;
1358         pmap->pm_cached = 0;
1359         pmap->pm_ptphint = NULL;
1360         TAILQ_INIT(&pmap->pm_pvlist);
1361         TAILQ_INIT(&pmap->pm_pvlist_free);
1362         spin_init(&pmap->pm_spin);
1363         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1364         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1365         pmap->pm_stats.resident_count = 1;
1366 }
1367
1368 /*
1369  * Clean up a pmap structure so it can be physically freed.  This routine
1370  * is called by the vmspace dtor function.  A great deal of pmap data is
1371  * left passively mapped to improve vmspace management so we have a bit
1372  * of cleanup work to do here.
1373  *
1374  * No requirements.
1375  */
1376 void
1377 pmap_puninit(pmap_t pmap)
1378 {
1379         vm_page_t p;
1380
1381         pmap_wait(pmap, -1);
1382         KKASSERT(pmap->pm_active == 0);
1383         if ((p = pmap->pm_pdirm) != NULL) {
1384                 KKASSERT(pmap->pm_pdir != NULL);
1385                 pmap_kremove((vm_offset_t)pmap->pm_pdir);
1386                 vm_page_busy_wait(p, FALSE, "pgpun");
1387                 vm_page_unwire(p, 0);
1388                 vm_page_free_zero(p);
1389                 pmap->pm_pdirm = NULL;
1390         }
1391         if (pmap->pm_pdir) {
1392                 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pdir, PAGE_SIZE);
1393                 pmap->pm_pdir = NULL;
1394         }
1395         if (pmap->pm_pteobj) {
1396                 vm_object_deallocate(pmap->pm_pteobj);
1397                 pmap->pm_pteobj = NULL;
1398         }
1399 }
1400
1401 /*
1402  * Wire in kernel global address entries.  To avoid a race condition
1403  * between pmap initialization and pmap_growkernel, this procedure
1404  * adds the pmap to the master list (which growkernel scans to update),
1405  * then copies the template.
1406  *
1407  * No requirements.
1408  */
1409 void
1410 pmap_pinit2(struct pmap *pmap)
1411 {
1412         /*
1413          * XXX copies current process, does not fill in MPPTDI
1414          */
1415         spin_lock(&pmap_spin);
1416         TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
1417         bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * PTESIZE);
1418         spin_unlock(&pmap_spin);
1419 }
1420
1421 /*
1422  * Attempt to release and free a vm_page in a pmap.  Returns 1 on success,
1423  * 0 on failure (if the procedure had to sleep).
1424  *
1425  * When asked to remove the page directory page itself, we actually just
1426  * leave it cached so we do not have to incur the SMP inval overhead of
1427  * removing the kernel mapping.  pmap_puninit() will take care of it.
1428  *
1429  * The caller must hold vm_token.
1430  * This function can block regardless.
1431  */
1432 static int
1433 pmap_release_free_page(struct pmap *pmap, vm_page_t p)
1434 {
1435         unsigned *pde = (unsigned *) pmap->pm_pdir;
1436
1437         /*
1438          * This code optimizes the case of freeing non-busy
1439          * page-table pages.  Those pages are zero now, and
1440          * might as well be placed directly into the zero queue.
1441          */
1442         if (vm_page_busy_try(p, FALSE)) {
1443                 vm_page_sleep_busy(p, FALSE, "pmaprl");
1444                 return 0;
1445         }
1446
1447         KKASSERT(pmap->pm_stats.resident_count > 0);
1448         KKASSERT(pde[p->pindex]);
1449
1450         /*
1451          * page table page's wire_count must be 1.  Caller is the pmap
1452          * termination code which holds the pm_pteobj, there is a race
1453          * if someone else is trying to hold the VM object in order to
1454          * clean up a wire_count.
1455          */
1456         if (p->wire_count != 1)  {
1457                 if (pmap->pm_pteobj->hold_count <= 1)
1458                         panic("pmap_release: freeing wired page table page");
1459                 kprintf("pmap_release_free_page: unwire race detected\n");
1460                 vm_page_wakeup(p);
1461                 tsleep(p, 0, "pmapx", 1);
1462                 return 0;
1463         }
1464
1465         /*
1466          * Remove the page table page from the processes address space.
1467          */
1468         pmap->pm_cached = 0;
1469         pde[p->pindex] = 0;
1470         --pmap->pm_stats.resident_count;
1471         if (pmap->pm_ptphint && (pmap->pm_ptphint->pindex == p->pindex))
1472                 pmap->pm_ptphint = NULL;
1473
1474         /*
1475          * We leave the page directory page cached, wired, and mapped in
1476          * the pmap until the dtor function (pmap_puninit()) gets called.
1477          * However, still clean it up so we can set PG_ZERO.
1478          *
1479          * The pmap has already been removed from the pmap_list in the
1480          * PTDPTDI case.
1481          */
1482         if (p->pindex == PTDPTDI) {
1483                 bzero(pde + KPTDI, nkpt * PTESIZE);
1484                 bzero(pde + MPPTDI, (NPDEPG - MPPTDI) * PTESIZE);
1485                 vm_page_flag_set(p, PG_ZERO);
1486                 vm_page_wakeup(p);
1487         } else {
1488                 /*
1489                  * This case can occur if a pmap_unwire_pte() loses a race
1490                  * while the page is unbusied.
1491                  */
1492                 /*panic("pmap_release: page should already be gone %p", p);*/
1493                 vm_page_flag_clear(p, PG_MAPPED);
1494                 vm_page_unwire(p, 0);
1495                 vm_page_free_zero(p);
1496         }
1497         return 1;
1498 }
1499
1500 /*
1501  * This routine is called if the page table page is not mapped correctly.
1502  *
1503  * The caller must hold vm_token.
1504  */
1505 static vm_page_t
1506 _pmap_allocpte(pmap_t pmap, unsigned ptepindex)
1507 {
1508         vm_offset_t ptepa;
1509         vm_page_t m;
1510
1511         /*
1512          * Find or fabricate a new pagetable page.  Setting VM_ALLOC_ZERO
1513          * will zero any new page and mark it valid.
1514          */
1515         m = vm_page_grab(pmap->pm_pteobj, ptepindex,
1516                          VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
1517
1518         KASSERT(m->queue == PQ_NONE,
1519                 ("_pmap_allocpte: %p->queue != PQ_NONE", m));
1520
1521         /*
1522          * Increment the wire count for the page we will be returning to
1523          * the caller.
1524          */
1525         vm_page_wire(m);
1526
1527         /*
1528          * It is possible that someone else got in and mapped by the page
1529          * directory page while we were blocked, if so just unbusy and
1530          * return the wired page.
1531          */
1532         if ((ptepa = pmap->pm_pdir[ptepindex]) != 0) {
1533                 KKASSERT((ptepa & PG_FRAME) == VM_PAGE_TO_PHYS(m));
1534                 vm_page_wakeup(m);
1535                 return(m);
1536         }
1537
1538         /*
1539          * Map the pagetable page into the process address space, if
1540          * it isn't already there.
1541          *
1542          * NOTE: For safety clear pm_cached for all cpus including the
1543          *       current one when adding a PDE to the map.
1544          */
1545         ++pmap->pm_stats.resident_count;
1546
1547         ptepa = VM_PAGE_TO_PHYS(m);
1548         pmap->pm_pdir[ptepindex] =
1549                 (pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1550         pmap->pm_cached = 0;
1551
1552         /*
1553          * Set the page table hint
1554          */
1555         pmap->pm_ptphint = m;
1556         vm_page_flag_set(m, PG_MAPPED);
1557         vm_page_wakeup(m);
1558
1559         return m;
1560 }
1561
1562 /*
1563  * Allocate a page table entry for a va.
1564  *
1565  * The caller must hold vm_token.
1566  */
1567 static vm_page_t
1568 pmap_allocpte(pmap_t pmap, vm_offset_t va)
1569 {
1570         unsigned ptepindex;
1571         vm_offset_t ptepa;
1572         vm_page_t mpte;
1573
1574         ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1575
1576         /*
1577          * Calculate pagetable page index
1578          */
1579         ptepindex = va >> PDRSHIFT;
1580
1581         /*
1582          * Get the page directory entry
1583          */
1584         ptepa = (vm_offset_t) pmap->pm_pdir[ptepindex];
1585
1586         /*
1587          * This supports switching from a 4MB page to a
1588          * normal 4K page.
1589          */
1590         if (ptepa & PG_PS) {
1591                 pmap->pm_pdir[ptepindex] = 0;
1592                 ptepa = 0;
1593                 smp_invltlb();
1594                 cpu_invltlb();
1595         }
1596
1597         /*
1598          * If the page table page is mapped, we just increment the
1599          * wire count, and activate it.
1600          */
1601         if (ptepa) {
1602                 /*
1603                  * In order to get the page table page, try the
1604                  * hint first.
1605                  */
1606                 if ((mpte = pmap->pm_ptphint) != NULL &&
1607                     (mpte->pindex == ptepindex) &&
1608                     (mpte->flags & PG_BUSY) == 0) {
1609                         vm_page_wire_quick(mpte);
1610                 } else {
1611                         mpte = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1612                         pmap->pm_ptphint = mpte;
1613                         vm_page_wire_quick(mpte);
1614                         vm_page_wakeup(mpte);
1615                 }
1616                 return mpte;
1617         }
1618         /*
1619          * Here if the pte page isn't mapped, or if it has been deallocated.
1620          */
1621         return _pmap_allocpte(pmap, ptepindex);
1622 }
1623
1624
1625 /***************************************************
1626  * Pmap allocation/deallocation routines.
1627  ***************************************************/
1628
1629 /*
1630  * Release any resources held by the given physical map.
1631  * Called when a pmap initialized by pmap_pinit is being released.
1632  * Should only be called if the map contains no valid mappings.
1633  *
1634  * Caller must hold pmap->pm_token
1635  */
1636 static int pmap_release_callback(struct vm_page *p, void *data);
1637
1638 void
1639 pmap_release(struct pmap *pmap)
1640 {
1641         vm_object_t object = pmap->pm_pteobj;
1642         struct rb_vm_page_scan_info info;
1643
1644         KASSERT(pmap->pm_active == 0,
1645                 ("pmap still active! %08x", pmap->pm_active));
1646 #if defined(DIAGNOSTIC)
1647         if (object->ref_count != 1)
1648                 panic("pmap_release: pteobj reference count != 1");
1649 #endif
1650         
1651         info.pmap = pmap;
1652         info.object = object;
1653
1654         spin_lock(&pmap_spin);
1655         TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
1656         spin_unlock(&pmap_spin);
1657
1658         vm_object_hold(object);
1659         /*lwkt_gettoken(&vm_token);*/
1660         do {
1661                 info.error = 0;
1662                 info.mpte = NULL;
1663                 info.limit = object->generation;
1664
1665                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL, 
1666                                         pmap_release_callback, &info);
1667                 if (info.error == 0 && info.mpte) {
1668                         if (!pmap_release_free_page(pmap, info.mpte))
1669                                 info.error = 1;
1670                 }
1671         } while (info.error);
1672         /*lwkt_reltoken(&vm_token);*/
1673         vm_object_drop(object);
1674
1675         pmap->pm_cached = 0;
1676 }
1677
1678 /*
1679  * The caller must hold vm_token.
1680  */
1681 static int
1682 pmap_release_callback(struct vm_page *p, void *data)
1683 {
1684         struct rb_vm_page_scan_info *info = data;
1685
1686         if (p->pindex == PTDPTDI) {
1687                 info->mpte = p;
1688                 return(0);
1689         }
1690         if (!pmap_release_free_page(info->pmap, p)) {
1691                 info->error = 1;
1692                 return(-1);
1693         }
1694         if (info->object->generation != info->limit) {
1695                 info->error = 1;
1696                 return(-1);
1697         }
1698         return(0);
1699 }
1700
1701 /*
1702  * Grow the number of kernel page table entries, if needed.
1703  *
1704  * No requirements.
1705  */
1706 void
1707 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
1708 {
1709         vm_offset_t addr = kend;
1710         struct pmap *pmap;
1711         vm_offset_t ptppaddr;
1712         vm_page_t nkpg;
1713         pd_entry_t newpdir;
1714
1715         vm_object_hold(kptobj);
1716         if (kernel_vm_end == 0) {
1717                 kernel_vm_end = KERNBASE;
1718                 nkpt = 0;
1719                 while (pdir_pde(PTD, kernel_vm_end)) {
1720                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
1721                                         ~(PAGE_SIZE * NPTEPG - 1);
1722                         nkpt++;
1723                 }
1724         }
1725         addr = (addr + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1726         while (kernel_vm_end < addr) {
1727                 if (pdir_pde(PTD, kernel_vm_end)) {
1728                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
1729                                         ~(PAGE_SIZE * NPTEPG - 1);
1730                         continue;
1731                 }
1732
1733                 /*
1734                  * This index is bogus, but out of the way
1735                  */
1736                 nkpg = vm_page_alloc(kptobj, nkpt, VM_ALLOC_NORMAL |
1737                                                    VM_ALLOC_SYSTEM |
1738                                                    VM_ALLOC_INTERRUPT);
1739                 if (nkpg == NULL)
1740                         panic("pmap_growkernel: no memory to grow kernel");
1741
1742                 vm_page_wire(nkpg);
1743                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1744                 pmap_zero_page(ptppaddr);
1745                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1746                 pdir_pde(PTD, kernel_vm_end) = newpdir;
1747                 *pmap_pde(&kernel_pmap, kernel_vm_end) = newpdir;
1748                 nkpt++;
1749
1750                 /*
1751                  * This update must be interlocked with pmap_pinit2.
1752                  */
1753                 spin_lock(&pmap_spin);
1754                 TAILQ_FOREACH(pmap, &pmap_list, pm_pmnode) {
1755                         *pmap_pde(pmap, kernel_vm_end) = newpdir;
1756                 }
1757                 spin_unlock(&pmap_spin);
1758                 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
1759                                 ~(PAGE_SIZE * NPTEPG - 1);
1760         }
1761         vm_object_drop(kptobj);
1762 }
1763
1764 /*
1765  * Add a reference to the specified pmap.
1766  *
1767  * No requirements.
1768  */
1769 void
1770 pmap_reference(pmap_t pmap)
1771 {
1772         if (pmap) {
1773                 lwkt_gettoken(&vm_token);
1774                 ++pmap->pm_count;
1775                 lwkt_reltoken(&vm_token);
1776         }
1777 }
1778
1779 /*
1780  * vm_token must be held
1781  */
1782 static
1783 void
1784 pmap_hold(pmap_t pmap)
1785 {
1786         ++pmap->pm_count;
1787 }
1788
1789 /*
1790  * vm_token must be held
1791  */
1792 static
1793 void
1794 pmap_drop(pmap_t pmap)
1795 {
1796         --pmap->pm_count;
1797         if (pmap->pm_count == (int)0x80000000)
1798                 wakeup(pmap);
1799 }
1800
1801 static
1802 void
1803 pmap_wait(pmap_t pmap, int count)
1804 {
1805         lwkt_gettoken(&vm_token);
1806         pmap->pm_count += count;
1807         if (pmap->pm_count & 0x7FFFFFFF) {
1808                 while (pmap->pm_count & 0x7FFFFFFF) {
1809                         pmap->pm_count |= 0x80000000;
1810                         tsleep(pmap, 0, "pmapd", 0);
1811                         pmap->pm_count &= ~0x80000000;
1812                         kprintf("pmap_wait: race averted\n");
1813                 }
1814         }
1815         lwkt_reltoken(&vm_token);
1816 }
1817
1818 /***************************************************
1819  * page management routines.
1820  ***************************************************/
1821
1822 /*
1823  * free the pv_entry back to the free list.  This function may be
1824  * called from an interrupt.
1825  *
1826  * The caller must hold vm_token.
1827  */
1828 static PMAP_INLINE void
1829 free_pv_entry(pv_entry_t pv)
1830 {
1831         struct mdglobaldata *gd;
1832
1833 #ifdef PMAP_DEBUG
1834         KKASSERT(pv->pv_m != NULL);
1835         pv->pv_m = NULL;
1836 #endif
1837         gd = mdcpu;
1838         pv_entry_count--;
1839         if (gd->gd_freepv == NULL)
1840                 gd->gd_freepv = pv;
1841         else
1842                 zfree(pvzone, pv);
1843 }
1844
1845 /*
1846  * get a new pv_entry, allocating a block from the system
1847  * when needed.  This function may be called from an interrupt thread.
1848  *
1849  * THIS FUNCTION CAN BLOCK ON THE ZALLOC TOKEN, serialization of other
1850  * tokens (aka vm_token) to be temporarily lost.
1851  *
1852  * The caller must hold vm_token.
1853  */
1854 static pv_entry_t
1855 get_pv_entry(void)
1856 {
1857         struct mdglobaldata *gd;
1858         pv_entry_t pv;
1859
1860         pv_entry_count++;
1861         if (pv_entry_high_water &&
1862             (pv_entry_count > pv_entry_high_water) &&
1863             (pmap_pagedaemon_waken == 0)) {
1864                 pmap_pagedaemon_waken = 1;
1865                 wakeup (&vm_pages_needed);
1866         }
1867         gd = mdcpu;
1868         if ((pv = gd->gd_freepv) != NULL)
1869                 gd->gd_freepv = NULL;
1870         else
1871                 pv = zalloc(pvzone);
1872         return pv;
1873 }
1874
1875 /*
1876  * This routine is very drastic, but can save the system
1877  * in a pinch.
1878  *
1879  * No requirements.
1880  */
1881 void
1882 pmap_collect(void)
1883 {
1884         int i;
1885         vm_page_t m;
1886         static int warningdone=0;
1887
1888         if (pmap_pagedaemon_waken == 0)
1889                 return;
1890         lwkt_gettoken(&vm_token);
1891         pmap_pagedaemon_waken = 0;
1892
1893         if (warningdone < 5) {
1894                 kprintf("pmap_collect: collecting pv entries -- "
1895                         "suggest increasing PMAP_SHPGPERPROC\n");
1896                 warningdone++;
1897         }
1898
1899         for (i = 0; i < vm_page_array_size; i++) {
1900                 m = &vm_page_array[i];
1901                 if (m->wire_count || m->hold_count)
1902                         continue;
1903                 if (vm_page_busy_try(m, TRUE) == 0) {
1904                         if (m->wire_count == 0 && m->hold_count == 0) {
1905                                 pmap_remove_all(m);
1906                         }
1907                         vm_page_wakeup(m);
1908                 }
1909         }
1910         lwkt_reltoken(&vm_token);
1911 }
1912         
1913
1914 /*
1915  * Remove the pv entry and unwire the page table page related to the
1916  * pte the caller has cleared from the page table.
1917  *
1918  * The caller must hold vm_token.
1919  */
1920 static void
1921 pmap_remove_entry(struct pmap *pmap, vm_page_t m, 
1922                   vm_offset_t va, pmap_inval_info_t info)
1923 {
1924         pv_entry_t pv;
1925
1926         /*
1927          * Cannot block
1928          */
1929         ASSERT_LWKT_TOKEN_HELD(&vm_token);
1930         if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
1931                 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1932                         if (pmap == pv->pv_pmap && va == pv->pv_va) 
1933                                 break;
1934                 }
1935         } else {
1936                 TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
1937 #ifdef PMAP_DEBUG
1938                         KKASSERT(pv->pv_pmap == pmap);
1939 #endif
1940                         if (va == pv->pv_va)
1941                                 break;
1942                 }
1943         }
1944         KKASSERT(pv);
1945
1946         /*
1947          * Cannot block
1948          */
1949         test_m_maps_pv(m, pv);
1950         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1951         pmap_page_stats_deleting(m);
1952         m->md.pv_list_count--;
1953         if (m->object)
1954                 atomic_add_int(&m->object->agg_pv_list_count, -1);
1955         if (TAILQ_EMPTY(&m->md.pv_list))
1956                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1957         TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1958         ++pmap->pm_generation;
1959
1960         /*
1961          * This can block.
1962          */
1963         vm_object_hold(pmap->pm_pteobj);
1964         pmap_unuse_pt(pmap, va, pv->pv_ptem, info);
1965         vm_object_drop(pmap->pm_pteobj);
1966         free_pv_entry(pv);
1967 }
1968
1969 /*
1970  * Create a pv entry for page at pa for (pmap, va).
1971  *
1972  * The caller must hold vm_token.
1973  */
1974 static void
1975 pmap_insert_entry(pmap_t pmap, pv_entry_t pv, vm_offset_t va,
1976                   vm_page_t mpte, vm_page_t m)
1977 {
1978 #ifdef PMAP_DEBUG
1979         KKASSERT(pv->pv_m == NULL);
1980         pv->pv_m = m;
1981 #endif
1982         pv->pv_va = va;
1983         pv->pv_pmap = pmap;
1984         pv->pv_ptem = mpte;
1985
1986         pmap_page_stats_adding(m);
1987         TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
1988         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1989         ++pmap->pm_generation;
1990         m->md.pv_list_count++;
1991         if (m->object)
1992                 atomic_add_int(&m->object->agg_pv_list_count, 1);
1993 }
1994
1995 /*
1996  * pmap_remove_pte: do the things to unmap a page in a process.
1997  *
1998  * The caller must hold vm_token.
1999  *
2000  * WARNING! As with most other pmap functions this one can block, so
2001  *          callers using temporary page table mappings must reload
2002  *          them.
2003  */
2004 static void
2005 pmap_remove_pte(struct pmap *pmap, unsigned *ptq, vm_offset_t va,
2006                 pmap_inval_info_t info)
2007 {
2008         unsigned oldpte;
2009         vm_page_t m;
2010
2011         ptbase_assert(pmap);
2012         pmap_inval_interlock(info, pmap, va);
2013         ptbase_assert(pmap);
2014         oldpte = loadandclear(ptq);
2015         if (oldpte & PG_W)
2016                 pmap->pm_stats.wired_count -= 1;
2017         pmap_inval_deinterlock(info, pmap);
2018         KKASSERT(oldpte & PG_V);
2019         /*
2020          * Machines that don't support invlpg, also don't support
2021          * PG_G.  XXX PG_G is disabled for SMP so don't worry about
2022          * the SMP case.
2023          */
2024         if (oldpte & PG_G)
2025                 cpu_invlpg((void *)va);
2026         KKASSERT(pmap->pm_stats.resident_count > 0);
2027         --pmap->pm_stats.resident_count;
2028         if (oldpte & PG_MANAGED) {
2029                 m = PHYS_TO_VM_PAGE(oldpte);
2030                 if (oldpte & PG_M) {
2031 #if defined(PMAP_DIAGNOSTIC)
2032                         if (pmap_nw_modified((pt_entry_t) oldpte)) {
2033                                 kprintf("pmap_remove: modified page not "
2034                                         "writable: va: %p, pte: 0x%lx\n",
2035                                         (void *)va, (long)oldpte);
2036                         }
2037 #endif
2038                         if (pmap_track_modified(va))
2039                                 vm_page_dirty(m);
2040                 }
2041                 if (oldpte & PG_A)
2042                         vm_page_flag_set(m, PG_REFERENCED);
2043                 pmap_remove_entry(pmap, m, va, info);
2044         } else {
2045                 pmap_unuse_pt(pmap, va, NULL, info);
2046         }
2047 }
2048
2049 /*
2050  * Remove a single page from a process address space.
2051  *
2052  * The caller must hold vm_token.
2053  */
2054 static void
2055 pmap_remove_page(struct pmap *pmap, vm_offset_t va, pmap_inval_info_t info)
2056 {
2057         unsigned *ptq;
2058
2059         /*
2060          * If there is no pte for this address, just skip it!!!  Otherwise
2061          * get a local va for mappings for this pmap and remove the entry.
2062          */
2063         if (*pmap_pde(pmap, va) != 0) {
2064                 ptq = get_ptbase(pmap) + i386_btop(va);
2065                 if (*ptq) {
2066                         pmap_remove_pte(pmap, ptq, va, info);
2067                         /* ptq invalid */
2068                 }
2069         }
2070 }
2071
2072 /*
2073  * Remove the given range of addresses from the specified map.
2074  *
2075  * It is assumed that the start and end are properly rounded to the page
2076  * size.
2077  *
2078  * No requirements.
2079  */
2080 void
2081 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
2082 {
2083         unsigned *ptbase;
2084         vm_offset_t pdnxt;
2085         vm_offset_t ptpaddr;
2086         vm_offset_t sindex, eindex;
2087         struct pmap_inval_info info;
2088
2089         if (pmap == NULL)
2090                 return;
2091
2092         vm_object_hold(pmap->pm_pteobj);
2093         lwkt_gettoken(&vm_token);
2094         if (pmap->pm_stats.resident_count == 0) {
2095                 lwkt_reltoken(&vm_token);
2096                 vm_object_drop(pmap->pm_pteobj);
2097                 return;
2098         }
2099
2100         pmap_inval_init(&info);
2101
2102         /*
2103          * special handling of removing one page.  a very
2104          * common operation and easy to short circuit some
2105          * code.
2106          */
2107         if (((sva + PAGE_SIZE) == eva) && 
2108                 (((unsigned) pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
2109                 pmap_remove_page(pmap, sva, &info);
2110                 pmap_inval_done(&info);
2111                 lwkt_reltoken(&vm_token);
2112                 vm_object_drop(pmap->pm_pteobj);
2113                 return;
2114         }
2115
2116         /*
2117          * Get a local virtual address for the mappings that are being
2118          * worked with.
2119          */
2120         sindex = i386_btop(sva);
2121         eindex = i386_btop(eva);
2122
2123         while (sindex < eindex) {
2124                 unsigned pdirindex;
2125
2126                 /*
2127                  * Stop scanning if no pages are left
2128                  */
2129                 if (pmap->pm_stats.resident_count == 0)
2130                         break;
2131
2132                 /*
2133                  * Calculate index for next page table, limited by eindex.
2134                  */
2135                 pdnxt = ((sindex + NPTEPG) & ~(NPTEPG - 1));
2136                 if (pdnxt > eindex)
2137                         pdnxt = eindex;
2138
2139                 pdirindex = sindex / NPDEPG;
2140                 ptpaddr = (unsigned)pmap->pm_pdir[pdirindex];
2141                 if (ptpaddr & PG_PS) {
2142                         pmap_inval_interlock(&info, pmap, -1);
2143                         pmap->pm_pdir[pdirindex] = 0;
2144                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2145                         pmap->pm_cached = 0;
2146                         pmap_inval_deinterlock(&info, pmap);
2147                         sindex = pdnxt;
2148                         continue;
2149                 }
2150
2151                 /*
2152                  * Weed out invalid mappings. Note: we assume that the page
2153                  * directory table is always allocated, and in kernel virtual.
2154                  */
2155                 if (ptpaddr == 0) {
2156                         sindex = pdnxt;
2157                         continue;
2158                 }
2159
2160                 /*
2161                  * Sub-scan the page table page.  pmap_remove_pte() can
2162                  * block on us, invalidating ptbase, so we must reload
2163                  * ptbase and we must also check whether the page directory
2164                  * page is still present.
2165                  */
2166                 while (sindex < pdnxt) {
2167                         vm_offset_t va;
2168
2169                         ptbase = get_ptbase(pmap);
2170                         if (ptbase[sindex]) {
2171                                 va = i386_ptob(sindex);
2172                                 pmap_remove_pte(pmap, ptbase + sindex,
2173                                                 va, &info);
2174                         }
2175                         if (pmap->pm_pdir[pdirindex] == 0 ||
2176                             (pmap->pm_pdir[pdirindex] & PG_PS)) {
2177                                 break;
2178                         }
2179                         ++sindex;
2180                 }
2181         }
2182         pmap_inval_done(&info);
2183         lwkt_reltoken(&vm_token);
2184         vm_object_drop(pmap->pm_pteobj);
2185 }
2186
2187 /*
2188  * Removes this physical page from all physical maps in which it resides.
2189  * Reflects back modify bits to the pager.
2190  *
2191  * vm_token must be held by caller.
2192  */
2193 static void
2194 pmap_remove_all(vm_page_t m)
2195 {
2196         struct pmap_inval_info info;
2197         unsigned *pte, tpte;
2198         pv_entry_t pv;
2199         pmap_t pmap;
2200
2201         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2202                 return;
2203         if (TAILQ_EMPTY(&m->md.pv_list))
2204                 return;
2205
2206         pmap_inval_init(&info);
2207         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2208                 pmap = pv->pv_pmap;
2209                 KKASSERT(pmap->pm_stats.resident_count > 0);
2210                 pmap_hold(pmap);
2211                 vm_object_hold(pmap->pm_pteobj);
2212
2213                 if (pv != TAILQ_FIRST(&m->md.pv_list)) {
2214                         vm_object_drop(pmap->pm_pteobj);
2215                         pmap_drop(pmap);
2216                         continue;
2217                 }
2218
2219                 --pmap->pm_stats.resident_count;
2220                 pte = pmap_pte_quick(pmap, pv->pv_va);
2221                 pmap_inval_interlock(&info, pmap, pv->pv_va);
2222                 tpte = loadandclear(pte);
2223                 if (tpte & PG_W)
2224                         pmap->pm_stats.wired_count--;
2225                 pmap_inval_deinterlock(&info, pmap);
2226                 if (tpte & PG_A)
2227                         vm_page_flag_set(m, PG_REFERENCED);
2228                 KKASSERT(PHYS_TO_VM_PAGE(tpte) == m);
2229
2230                 /*
2231                  * Update the vm_page_t clean and reference bits.
2232                  */
2233                 if (tpte & PG_M) {
2234 #if defined(PMAP_DIAGNOSTIC)
2235                         if (pmap_nw_modified((pt_entry_t) tpte)) {
2236                                 kprintf("pmap_remove_all: modified page "
2237                                         "not writable: va: %p, pte: 0x%lx\n",
2238                                         (void *)pv->pv_va, (long)tpte);
2239                         }
2240 #endif
2241                         if (pmap_track_modified(pv->pv_va))
2242                                 vm_page_dirty(m);
2243                 }
2244 #ifdef PMAP_DEBUG
2245                 KKASSERT(pv->pv_m == m);
2246 #endif
2247                 KKASSERT(pv == TAILQ_FIRST(&m->md.pv_list));
2248                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2249                 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2250                 pmap_page_stats_deleting(m);
2251                 ++pmap->pm_generation;
2252                 m->md.pv_list_count--;
2253                 if (m->object)
2254                         atomic_add_int(&m->object->agg_pv_list_count, -1);
2255                 if (TAILQ_EMPTY(&m->md.pv_list))
2256                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2257                 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem, &info);
2258                 vm_object_drop(pmap->pm_pteobj);
2259                 free_pv_entry(pv);
2260                 pmap_drop(pmap);
2261         }
2262         KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
2263         pmap_inval_done(&info);
2264 }
2265
2266 /*
2267  * Set the physical protection on the specified range of this map
2268  * as requested.
2269  *
2270  * No requirements.
2271  */
2272 void
2273 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2274 {
2275         unsigned *ptbase;
2276         vm_offset_t pdnxt, ptpaddr;
2277         vm_pindex_t sindex, eindex;
2278         pmap_inval_info info;
2279
2280         if (pmap == NULL)
2281                 return;
2282
2283         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2284                 pmap_remove(pmap, sva, eva);
2285                 return;
2286         }
2287
2288         if (prot & VM_PROT_WRITE)
2289                 return;
2290
2291         lwkt_gettoken(&vm_token);
2292         pmap_inval_init(&info);
2293
2294         ptbase = get_ptbase(pmap);
2295
2296         sindex = i386_btop(sva);
2297         eindex = i386_btop(eva);
2298
2299         for (; sindex < eindex; sindex = pdnxt) {
2300                 unsigned pdirindex;
2301
2302                 pdnxt = ((sindex + NPTEPG) & ~(NPTEPG - 1));
2303
2304                 pdirindex = sindex / NPDEPG;
2305                 if (((ptpaddr = (unsigned) pmap->pm_pdir[pdirindex]) & PG_PS) != 0) {
2306                         pmap_inval_interlock(&info, pmap, -1);
2307                         pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
2308                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2309                         pmap_inval_deinterlock(&info, pmap);
2310                         continue;
2311                 }
2312
2313                 /*
2314                  * Weed out invalid mappings. Note: we assume that the page
2315                  * directory table is always allocated, and in kernel virtual.
2316                  */
2317                 if (ptpaddr == 0)
2318                         continue;
2319
2320                 if (pdnxt > eindex) {
2321                         pdnxt = eindex;
2322                 }
2323
2324                 for (; sindex != pdnxt; sindex++) {
2325                         unsigned pbits;
2326                         unsigned cbits;
2327                         vm_page_t m;
2328
2329                         /*
2330                          * XXX non-optimal.
2331                          */
2332                         pmap_inval_interlock(&info, pmap, i386_ptob(sindex));
2333 again:
2334                         pbits = ptbase[sindex];
2335                         cbits = pbits;
2336
2337                         if (pbits & PG_MANAGED) {
2338                                 m = NULL;
2339                                 if (pbits & PG_A) {
2340                                         m = PHYS_TO_VM_PAGE(pbits);
2341                                         vm_page_flag_set(m, PG_REFERENCED);
2342                                         cbits &= ~PG_A;
2343                                 }
2344                                 if (pbits & PG_M) {
2345                                         if (pmap_track_modified(i386_ptob(sindex))) {
2346                                                 if (m == NULL)
2347                                                         m = PHYS_TO_VM_PAGE(pbits);
2348                                                 vm_page_dirty(m);
2349                                                 cbits &= ~PG_M;
2350                                         }
2351                                 }
2352                         }
2353                         cbits &= ~PG_RW;
2354                         if (pbits != cbits &&
2355                             !atomic_cmpset_int(ptbase + sindex, pbits, cbits)) {
2356                                 goto again;
2357                         }
2358                         pmap_inval_deinterlock(&info, pmap);
2359                 }
2360         }
2361         pmap_inval_done(&info);
2362         lwkt_reltoken(&vm_token);
2363 }
2364
2365 /*
2366  * Insert the given physical page (p) at the specified virtual address (v)
2367  * in the target physical map with the protection requested.
2368  *
2369  * If specified, the page will be wired down, meaning that the related pte
2370  * cannot be reclaimed.
2371  *
2372  * No requirements.
2373  */
2374 void
2375 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2376            boolean_t wired, vm_map_entry_t entry __unused)
2377 {
2378         vm_paddr_t pa;
2379         unsigned *pte;
2380         vm_paddr_t opa;
2381         vm_offset_t origpte, newpte;
2382         vm_page_t mpte;
2383         pmap_inval_info info;
2384         pv_entry_t pv;
2385
2386         if (pmap == NULL)
2387                 return;
2388
2389         va &= PG_FRAME;
2390 #ifdef PMAP_DIAGNOSTIC
2391         if (va >= KvaEnd)
2392                 panic("pmap_enter: toobig");
2393         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS)) {
2394                 panic("pmap_enter: invalid to pmap_enter page "
2395                       "table pages (va: %p)", (void *)va);
2396         }
2397 #endif
2398         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2399                 kprintf("Warning: pmap_enter called on UVA with kernel_pmap\n");
2400                 print_backtrace(-1);
2401         }
2402         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2403                 kprintf("Warning: pmap_enter called on KVA without kernel_pmap\n");
2404                 print_backtrace(-1);
2405         }
2406
2407         vm_object_hold(pmap->pm_pteobj);
2408         lwkt_gettoken(&vm_token);
2409
2410         /*
2411          * This can block, get it before we do anything important.
2412          */
2413         if (pmap_initialized &&
2414             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2415                 pv = get_pv_entry();
2416         } else {
2417                 pv = NULL;
2418         }
2419
2420         /*
2421          * In the case that a page table page is not
2422          * resident, we are creating it here.
2423          */
2424         if (va < UPT_MIN_ADDRESS)
2425                 mpte = pmap_allocpte(pmap, va);
2426         else
2427                 mpte = NULL;
2428
2429         if ((prot & VM_PROT_NOSYNC) == 0)
2430                 pmap_inval_init(&info);
2431         pte = pmap_pte(pmap, va);
2432
2433         /*
2434          * Page Directory table entry not valid, we need a new PT page
2435          */
2436         if (pte == NULL) {
2437                 panic("pmap_enter: invalid page directory pdir=0x%lx, va=%p",
2438                      (long)pmap->pm_pdir[PTDPTDI], (void *)va);
2439         }
2440
2441         pa = VM_PAGE_TO_PHYS(m) & PG_FRAME;
2442         origpte = *(vm_offset_t *)pte;
2443         opa = origpte & PG_FRAME;
2444
2445         if (origpte & PG_PS)
2446                 panic("pmap_enter: attempted pmap_enter on 4MB page");
2447
2448         /*
2449          * Mapping has not changed, must be protection or wiring change.
2450          */
2451         if (origpte && (opa == pa)) {
2452                 /*
2453                  * Wiring change, just update stats. We don't worry about
2454                  * wiring PT pages as they remain resident as long as there
2455                  * are valid mappings in them. Hence, if a user page is wired,
2456                  * the PT page will be also.
2457                  */
2458                 if (wired && ((origpte & PG_W) == 0))
2459                         pmap->pm_stats.wired_count++;
2460                 else if (!wired && (origpte & PG_W))
2461                         pmap->pm_stats.wired_count--;
2462
2463 #if defined(PMAP_DIAGNOSTIC)
2464                 if (pmap_nw_modified((pt_entry_t) origpte)) {
2465                         kprintf("pmap_enter: modified page not "
2466                                 "writable: va: %p, pte: 0x%lx\n",
2467                                 (void *)va, (long )origpte);
2468                 }
2469 #endif
2470
2471                 /*
2472                  * We might be turning off write access to the page,
2473                  * so we go ahead and sense modify status.
2474                  */
2475                 if (origpte & PG_MANAGED) {
2476                         if ((origpte & PG_M) && pmap_track_modified(va)) {
2477                                 vm_page_t om;
2478                                 om = PHYS_TO_VM_PAGE(opa);
2479                                 vm_page_dirty(om);
2480                         }
2481                         pa |= PG_MANAGED;
2482                         KKASSERT(m->flags & PG_MAPPED);
2483                 }
2484                 goto validate;
2485         } 
2486         /*
2487          * Mapping has changed, invalidate old range and fall through to
2488          * handle validating new mapping.
2489          *
2490          * Since we have a ref on the page directory page pmap_pte()
2491          * will always return non-NULL.
2492          *
2493          * NOTE: pmap_remove_pte() can block and cause the temporary ptbase
2494          *       to get wiped.  reload the ptbase.  I'm not sure if it is
2495          *       also possible to race another pmap_enter() but check for
2496          *       that case too.
2497          */
2498         while (opa) {
2499                 KKASSERT((origpte & PG_FRAME) ==
2500                          (*(vm_offset_t *)pte & PG_FRAME));
2501                 if (prot & VM_PROT_NOSYNC) {
2502                         prot &= ~VM_PROT_NOSYNC;
2503                         pmap_inval_init(&info);
2504                 }
2505                 pmap_remove_pte(pmap, pte, va, &info);
2506                 pte = pmap_pte(pmap, va);
2507                 origpte = *(vm_offset_t *)pte;
2508                 opa = origpte & PG_FRAME;
2509                 if (opa) {
2510                         kprintf("pmap_enter: Warning, raced pmap %p va %p\n",
2511                                 pmap, (void *)va);
2512                 }
2513         }
2514
2515         /*
2516          * Enter on the PV list if part of our managed memory. Note that we
2517          * raise IPL while manipulating pv_table since pmap_enter can be
2518          * called at interrupt time.
2519          */
2520         if (pmap_initialized && 
2521             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2522                 pmap_insert_entry(pmap, pv, va, mpte, m);
2523                 pv = NULL;
2524                 ptbase_assert(pmap);
2525                 pa |= PG_MANAGED;
2526                 vm_page_flag_set(m, PG_MAPPED);
2527         }
2528
2529         /*
2530          * Increment counters
2531          */
2532         ++pmap->pm_stats.resident_count;
2533         if (wired)
2534                 pmap->pm_stats.wired_count++;
2535         KKASSERT(*pte == 0);
2536
2537 validate:
2538         /*
2539          * Now validate mapping with desired protection/wiring.
2540          */
2541         ptbase_assert(pmap);
2542         newpte = (vm_offset_t) (pa | pte_prot(pmap, prot) | PG_V);
2543
2544         if (wired)
2545                 newpte |= PG_W;
2546         if (va < UPT_MIN_ADDRESS)
2547                 newpte |= PG_U;
2548         if (pmap == &kernel_pmap)
2549                 newpte |= pgeflag;
2550         newpte |= pat_pte_index[m->pat_mode];
2551
2552         /*
2553          * If the mapping or permission bits are different, we need
2554          * to update the pte.  If the pte is already present we have
2555          * to get rid of the extra wire-count on mpte we had obtained
2556          * above.
2557          *
2558          * mpte has a new wire_count, which also serves to prevent the
2559          * page table page from getting ripped out while we work.  If we
2560          * are modifying an existing pte instead of installing a new one
2561          * we have to drop it.
2562          */
2563         if ((origpte & ~(PG_M|PG_A)) != newpte) {
2564                 if (prot & VM_PROT_NOSYNC)
2565                         cpu_invlpg((void *)va);
2566                 else
2567                         pmap_inval_interlock(&info, pmap, va);
2568                 ptbase_assert(pmap);
2569
2570                 if (*pte) {
2571                         KKASSERT((*pte & PG_FRAME) == (newpte & PG_FRAME));
2572                         if (mpte && vm_page_unwire_quick(mpte))
2573                                 panic("pmap_enter: Insufficient wire_count");
2574                 }
2575
2576                 *pte = newpte | PG_A;
2577                 if ((prot & VM_PROT_NOSYNC) == 0)
2578                         pmap_inval_deinterlock(&info, pmap);
2579                 if (newpte & PG_RW)
2580                         vm_page_flag_set(m, PG_WRITEABLE);
2581         } else {
2582                 if (*pte) {
2583                         KKASSERT((*pte & PG_FRAME) == (newpte & PG_FRAME));
2584                         if (mpte && vm_page_unwire_quick(mpte))
2585                                 panic("pmap_enter: Insufficient wire_count");
2586                 }
2587         }
2588
2589         /*
2590          * NOTE: mpte invalid after this point if we block.
2591          */
2592         KKASSERT((newpte & PG_MANAGED) == 0 || (m->flags & PG_MAPPED));
2593         if ((prot & VM_PROT_NOSYNC) == 0)
2594                 pmap_inval_done(&info);
2595         if (pv)
2596                 free_pv_entry(pv);
2597         lwkt_reltoken(&vm_token);
2598         vm_object_drop(pmap->pm_pteobj);
2599 }
2600
2601 /*
2602  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
2603  * This code also assumes that the pmap has no pre-existing entry for this
2604  * VA.
2605  *
2606  * This code currently may only be used on user pmaps, not kernel_pmap.
2607  *
2608  * No requirements.
2609  */
2610 void
2611 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
2612 {
2613         unsigned *pte;
2614         vm_paddr_t pa;
2615         vm_page_t mpte;
2616         unsigned ptepindex;
2617         vm_offset_t ptepa;
2618         pmap_inval_info info;
2619         pv_entry_t pv;
2620
2621         vm_object_hold(pmap->pm_pteobj);
2622         lwkt_gettoken(&vm_token);
2623
2624         /*
2625          * This can block, get it before we do anything important.
2626          */
2627         if (pmap_initialized &&
2628             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2629                 pv = get_pv_entry();
2630         } else {
2631                 pv = NULL;
2632         }
2633
2634         pmap_inval_init(&info);
2635
2636         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2637                 kprintf("Warning: pmap_enter_quick called on UVA with kernel_pmap\n");
2638                 print_backtrace(-1);
2639         }
2640         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2641                 kprintf("Warning: pmap_enter_quick called on KVA without kernel_pmap\n");
2642                 print_backtrace(-1);
2643         }
2644
2645         KKASSERT(va < UPT_MIN_ADDRESS); /* assert used on user pmaps only */
2646
2647         /*
2648          * Calculate the page table page (mpte), allocating it if necessary.
2649          *
2650          * A held page table page (mpte), or NULL, is passed onto the
2651          * section following.
2652          */
2653         if (va < UPT_MIN_ADDRESS) {
2654                 /*
2655                  * Calculate pagetable page index
2656                  */
2657                 ptepindex = va >> PDRSHIFT;
2658
2659                 do {
2660                         /*
2661                          * Get the page directory entry
2662                          */
2663                         ptepa = (vm_offset_t) pmap->pm_pdir[ptepindex];
2664
2665                         /*
2666                          * If the page table page is mapped, we just increment
2667                          * the wire count, and activate it.
2668                          */
2669                         if (ptepa) {
2670                                 if (ptepa & PG_PS)
2671                                         panic("pmap_enter_quick: unexpected mapping into 4MB page");
2672                                 if ((mpte = pmap->pm_ptphint) != NULL &&
2673                                     (mpte->pindex == ptepindex) &&
2674                                     (mpte->flags & PG_BUSY) == 0) {
2675                                         vm_page_wire_quick(mpte);
2676                                 } else {
2677                                         mpte = pmap_page_lookup(pmap->pm_pteobj,
2678                                                                 ptepindex);
2679                                         pmap->pm_ptphint = mpte;
2680                                         vm_page_wire_quick(mpte);
2681                                         vm_page_wakeup(mpte);
2682                                 }
2683                         } else {
2684                                 mpte = _pmap_allocpte(pmap, ptepindex);
2685                         }
2686                 } while (mpte == NULL);
2687         } else {
2688                 mpte = NULL;
2689                 /* this code path is not yet used */
2690         }
2691
2692         /*
2693          * With a valid (and held) page directory page, we can just use
2694          * vtopte() to get to the pte.  If the pte is already present
2695          * we do not disturb it.
2696          */
2697         pte = (unsigned *)vtopte(va);
2698         if (*pte) {
2699                 KKASSERT(*pte & PG_V);
2700                 pa = VM_PAGE_TO_PHYS(m);
2701                 KKASSERT(((*pte ^ pa) & PG_FRAME) == 0);
2702                 pmap_inval_done(&info);
2703                 if (mpte)
2704                         pmap_unwire_pte(pmap, mpte, &info);
2705                 if (pv) {
2706                         free_pv_entry(pv);
2707                         /* pv = NULL; */
2708                 }
2709                 lwkt_reltoken(&vm_token);
2710                 vm_object_drop(pmap->pm_pteobj);
2711                 return;
2712         }
2713
2714         /*
2715          * Enter on the PV list if part of our managed memory
2716          */
2717         if (pmap_initialized &&
2718             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2719                 pmap_insert_entry(pmap, pv, va, mpte, m);
2720                 pv = NULL;
2721                 vm_page_flag_set(m, PG_MAPPED);
2722         }
2723
2724         /*
2725          * Increment counters
2726          */
2727         ++pmap->pm_stats.resident_count;
2728
2729         pa = VM_PAGE_TO_PHYS(m);
2730
2731         /*
2732          * Now validate mapping with RO protection
2733          */
2734         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2735                 *pte = pa | PG_V | PG_U;
2736         else
2737                 *pte = pa | PG_V | PG_U | PG_MANAGED;
2738 /*      pmap_inval_add(&info, pmap, va); shouldn't be needed inval->valid */
2739         pmap_inval_done(&info);
2740         if (pv) {
2741                 free_pv_entry(pv);
2742                 /* pv = NULL; */
2743         }
2744         lwkt_reltoken(&vm_token);
2745         vm_object_drop(pmap->pm_pteobj);
2746 }
2747
2748 /*
2749  * Make a temporary mapping for a physical address.  This is only intended
2750  * to be used for panic dumps.
2751  *
2752  * The caller is responsible for calling smp_invltlb().
2753  *
2754  * No requirements.
2755  */
2756 void *
2757 pmap_kenter_temporary(vm_paddr_t pa, long i)
2758 {
2759         pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
2760         return ((void *)crashdumpmap);
2761 }
2762
2763 #define MAX_INIT_PT (96)
2764
2765 /*
2766  * This routine preloads the ptes for a given object into the specified pmap.
2767  * This eliminates the blast of soft faults on process startup and
2768  * immediately after an mmap.
2769  *
2770  * No requirements.
2771  */
2772 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
2773
2774 void
2775 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
2776                     vm_object_t object, vm_pindex_t pindex, 
2777                     vm_size_t size, int limit)
2778 {
2779         struct rb_vm_page_scan_info info;
2780         struct lwp *lp;
2781         int psize;
2782
2783         /*
2784          * We can't preinit if read access isn't set or there is no pmap
2785          * or object.
2786          */
2787         if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
2788                 return;
2789
2790         /*
2791          * We can't preinit if the pmap is not the current pmap
2792          */
2793         lp = curthread->td_lwp;
2794         if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
2795                 return;
2796
2797         psize = i386_btop(size);
2798
2799         if ((object->type != OBJT_VNODE) ||
2800                 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
2801                         (object->resident_page_count > MAX_INIT_PT))) {
2802                 return;
2803         }
2804
2805         if (psize + pindex > object->size) {
2806                 if (object->size < pindex)
2807                         return;           
2808                 psize = object->size - pindex;
2809         }
2810
2811         if (psize == 0)
2812                 return;
2813
2814         /*
2815          * Use a red-black scan to traverse the requested range and load
2816          * any valid pages found into the pmap.
2817          *
2818          * We cannot safely scan the object's memq unless we are in a
2819          * critical section since interrupts can remove pages from objects.
2820          */
2821         info.start_pindex = pindex;
2822         info.end_pindex = pindex + psize - 1;
2823         info.limit = limit;
2824         info.mpte = NULL;
2825         info.addr = addr;
2826         info.pmap = pmap;
2827
2828         vm_object_hold_shared(object);
2829         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2830                                 pmap_object_init_pt_callback, &info);
2831         vm_object_drop(object);
2832 }
2833
2834 /*
2835  * The caller must hold vm_token.
2836  */
2837 static
2838 int
2839 pmap_object_init_pt_callback(vm_page_t p, void *data)
2840 {
2841         struct rb_vm_page_scan_info *info = data;
2842         vm_pindex_t rel_index;
2843         /*
2844          * don't allow an madvise to blow away our really
2845          * free pages allocating pv entries.
2846          */
2847         if ((info->limit & MAP_PREFAULT_MADVISE) &&
2848                 vmstats.v_free_count < vmstats.v_free_reserved) {
2849                     return(-1);
2850         }
2851
2852         /*
2853          * Ignore list markers and ignore pages we cannot instantly
2854          * busy (while holding the object token).
2855          */
2856         if (p->flags & PG_MARKER)
2857                 return 0;
2858         if (vm_page_busy_try(p, TRUE))
2859                 return 0;
2860         if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
2861             (p->flags & PG_FICTITIOUS) == 0) {
2862                 if ((p->queue - p->pc) == PQ_CACHE)
2863                         vm_page_deactivate(p);
2864                 rel_index = p->pindex - info->start_pindex;
2865                 pmap_enter_quick(info->pmap,
2866                                  info->addr + i386_ptob(rel_index), p);
2867         }
2868         vm_page_wakeup(p);
2869         return(0);
2870 }
2871
2872 /*
2873  * Return TRUE if the pmap is in shape to trivially
2874  * pre-fault the specified address.
2875  *
2876  * Returns FALSE if it would be non-trivial or if a
2877  * pte is already loaded into the slot.
2878  *
2879  * No requirements.
2880  */
2881 int
2882 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
2883 {
2884         unsigned *pte;
2885         int ret;
2886
2887         lwkt_gettoken(&vm_token);
2888         if ((*pmap_pde(pmap, addr)) == 0) {
2889                 ret = 0;
2890         } else {
2891                 pte = (unsigned *) vtopte(addr);
2892                 ret = (*pte) ? 0 : 1;
2893         }
2894         lwkt_reltoken(&vm_token);
2895         return(ret);
2896 }
2897
2898 /*
2899  * Change the wiring attribute for a map/virtual-adderss pair.  The mapping
2900  * must already exist.
2901  *
2902  * No requirements.
2903  */
2904 void
2905 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired,
2906                    vm_map_entry_t entry __unused)
2907 {
2908         unsigned *pte;
2909
2910         if (pmap == NULL)
2911                 return;
2912
2913         lwkt_gettoken(&vm_token);
2914         pte = pmap_pte(pmap, va);
2915
2916         if (wired && !pmap_pte_w(pte))
2917                 pmap->pm_stats.wired_count++;
2918         else if (!wired && pmap_pte_w(pte))
2919                 pmap->pm_stats.wired_count--;
2920
2921         /*
2922          * Wiring is not a hardware characteristic so there is no need to
2923          * invalidate TLB.  However, in an SMP environment we must use
2924          * a locked bus cycle to update the pte (if we are not using 
2925          * the pmap_inval_*() API that is)... it's ok to do this for simple
2926          * wiring changes.
2927          */
2928         if (wired)
2929                 atomic_set_int(pte, PG_W);
2930         else
2931                 atomic_clear_int(pte, PG_W);
2932         lwkt_reltoken(&vm_token);
2933 }
2934
2935 /*
2936  * Copy the range specified by src_addr/len from the source map to the
2937  * range dst_addr/len in the destination map.
2938  *
2939  * This routine is only advisory and need not do anything.
2940  *
2941  * No requirements.
2942  */
2943 void
2944 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, 
2945           vm_size_t len, vm_offset_t src_addr)
2946 {
2947         /* does nothing */
2948 }       
2949
2950 /*
2951  * Zero the specified PA by mapping the page into KVM and clearing its
2952  * contents.
2953  *
2954  * No requirements.
2955  */
2956 void
2957 pmap_zero_page(vm_paddr_t phys)
2958 {
2959         struct mdglobaldata *gd = mdcpu;
2960
2961         crit_enter();
2962         if (*(int *)gd->gd_CMAP3)
2963                 panic("pmap_zero_page: CMAP3 busy");
2964         *(int *)gd->gd_CMAP3 =
2965                     PG_V | PG_RW | (phys & PG_FRAME) | PG_A | PG_M;
2966         cpu_invlpg(gd->gd_CADDR3);
2967         bzero(gd->gd_CADDR3, PAGE_SIZE);
2968         *(int *) gd->gd_CMAP3 = 0;
2969         crit_exit();
2970 }
2971
2972 /*
2973  * Assert that a page is empty, panic if it isn't.
2974  *
2975  * No requirements.
2976  */
2977 void
2978 pmap_page_assertzero(vm_paddr_t phys)
2979 {
2980         struct mdglobaldata *gd = mdcpu;
2981         int i;
2982
2983         crit_enter();
2984         if (*(int *)gd->gd_CMAP3)
2985                 panic("pmap_zero_page: CMAP3 busy");
2986         *(int *)gd->gd_CMAP3 =
2987                     PG_V | PG_RW | (phys & PG_FRAME) | PG_A | PG_M;
2988         cpu_invlpg(gd->gd_CADDR3);
2989         for (i = 0; i < PAGE_SIZE; i += 4) {
2990             if (*(int *)((char *)gd->gd_CADDR3 + i) != 0) {
2991                 panic("pmap_page_assertzero() @ %p not zero!",
2992                     (void *)gd->gd_CADDR3);
2993             }
2994         }
2995         *(int *) gd->gd_CMAP3 = 0;
2996         crit_exit();
2997 }
2998
2999 /*
3000  * Zero part of a physical page by mapping it into memory and clearing
3001  * its contents with bzero.
3002  *
3003  * off and size may not cover an area beyond a single hardware page.
3004  *
3005  * No requirements.
3006  */
3007 void
3008 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
3009 {
3010         struct mdglobaldata *gd = mdcpu;
3011
3012         crit_enter();
3013         if (*(int *) gd->gd_CMAP3)
3014                 panic("pmap_zero_page: CMAP3 busy");
3015         *(int *) gd->gd_CMAP3 = PG_V | PG_RW | (phys & PG_FRAME) | PG_A | PG_M;
3016         cpu_invlpg(gd->gd_CADDR3);
3017         bzero((char *)gd->gd_CADDR3 + off, size);
3018         *(int *) gd->gd_CMAP3 = 0;
3019         crit_exit();
3020 }
3021
3022 /*
3023  * Copy the physical page from the source PA to the target PA.
3024  * This function may be called from an interrupt.  No locking
3025  * is required.
3026  *
3027  * No requirements.
3028  */
3029 void
3030 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
3031 {
3032         struct mdglobaldata *gd = mdcpu;
3033
3034         crit_enter();
3035         if (*(int *) gd->gd_CMAP1)
3036                 panic("pmap_copy_page: CMAP1 busy");
3037         if (*(int *) gd->gd_CMAP2)
3038                 panic("pmap_copy_page: CMAP2 busy");
3039
3040         *(int *) gd->gd_CMAP1 = PG_V | (src & PG_FRAME) | PG_A;
3041         *(int *) gd->gd_CMAP2 = PG_V | PG_RW | (dst & PG_FRAME) | PG_A | PG_M;
3042
3043         cpu_invlpg(gd->gd_CADDR1);
3044         cpu_invlpg(gd->gd_CADDR2);
3045
3046         bcopy(gd->gd_CADDR1, gd->gd_CADDR2, PAGE_SIZE);
3047
3048         *(int *) gd->gd_CMAP1 = 0;
3049         *(int *) gd->gd_CMAP2 = 0;
3050         crit_exit();
3051 }
3052
3053 /*
3054  * Copy the physical page from the source PA to the target PA.
3055  * This function may be called from an interrupt.  No locking
3056  * is required.
3057  *
3058  * No requirements.
3059  */
3060 void
3061 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
3062 {
3063         struct mdglobaldata *gd = mdcpu;
3064
3065         crit_enter();
3066         if (*(int *) gd->gd_CMAP1)
3067                 panic("pmap_copy_page: CMAP1 busy");
3068         if (*(int *) gd->gd_CMAP2)
3069                 panic("pmap_copy_page: CMAP2 busy");
3070
3071         *(int *) gd->gd_CMAP1 = PG_V | (src & PG_FRAME) | PG_A;
3072         *(int *) gd->gd_CMAP2 = PG_V | PG_RW | (dst & PG_FRAME) | PG_A | PG_M;
3073
3074         cpu_invlpg(gd->gd_CADDR1);
3075         cpu_invlpg(gd->gd_CADDR2);
3076
3077         bcopy((char *)gd->gd_CADDR1 + (src & PAGE_MASK),
3078               (char *)gd->gd_CADDR2 + (dst & PAGE_MASK),
3079               bytes);
3080
3081         *(int *) gd->gd_CMAP1 = 0;
3082         *(int *) gd->gd_CMAP2 = 0;
3083         crit_exit();
3084 }
3085
3086 /*
3087  * Returns true if the pmap's pv is one of the first
3088  * 16 pvs linked to from this page.  This count may
3089  * be changed upwards or downwards in the future; it
3090  * is only necessary that true be returned for a small
3091  * subset of pmaps for proper page aging.
3092  *
3093  * No requirements.
3094  */
3095 boolean_t
3096 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3097 {
3098         pv_entry_t pv;
3099         int loops = 0;
3100
3101         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3102                 return FALSE;
3103
3104         lwkt_gettoken(&vm_token);
3105         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3106                 if (pv->pv_pmap == pmap) {
3107                         lwkt_reltoken(&vm_token);
3108                         return TRUE;
3109                 }
3110                 loops++;
3111                 if (loops >= 16)
3112                         break;
3113         }
3114         lwkt_reltoken(&vm_token);
3115         return (FALSE);
3116 }
3117
3118 /*
3119  * Remove all pages from specified address space
3120  * this aids process exit speeds.  Also, this code
3121  * is special cased for current process only, but
3122  * can have the more generic (and slightly slower)
3123  * mode enabled.  This is much faster than pmap_remove
3124  * in the case of running down an entire address space.
3125  *
3126  * No requirements.
3127  */
3128 void
3129 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3130 {
3131         struct lwp *lp;
3132         unsigned *pte, tpte;
3133         pv_entry_t pv, npv;
3134         vm_page_t m;
3135         pmap_inval_info info;
3136         int iscurrentpmap;
3137         int32_t save_generation;
3138
3139         lp = curthread->td_lwp;
3140         if (lp && pmap == vmspace_pmap(lp->lwp_vmspace))
3141                 iscurrentpmap = 1;
3142         else
3143                 iscurrentpmap = 0;
3144
3145         if (pmap->pm_pteobj)
3146                 vm_object_hold(pmap->pm_pteobj);
3147         lwkt_gettoken(&vm_token);
3148         pmap_inval_init(&info);
3149
3150         for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
3151                 if (pv->pv_va >= eva || pv->pv_va < sva) {
3152                         npv = TAILQ_NEXT(pv, pv_plist);
3153                         continue;
3154                 }
3155
3156                 KKASSERT(pmap == pv->pv_pmap);
3157
3158                 if (iscurrentpmap)
3159                         pte = (unsigned *)vtopte(pv->pv_va);
3160                 else
3161                         pte = pmap_pte_quick(pmap, pv->pv_va);
3162                 KKASSERT(*pte);
3163                 pmap_inval_interlock(&info, pmap, pv->pv_va);
3164
3165                 /*
3166                  * We cannot remove wired pages from a process' mapping
3167                  * at this time
3168                  */
3169                 if (*pte & PG_W) {
3170                         pmap_inval_deinterlock(&info, pmap);
3171                         npv = TAILQ_NEXT(pv, pv_plist);
3172                         continue;
3173                 }
3174                 KKASSERT(*pte);
3175                 tpte = loadandclear(pte);
3176                 pmap_inval_deinterlock(&info, pmap);
3177
3178                 m = PHYS_TO_VM_PAGE(tpte);
3179                 test_m_maps_pv(m, pv);
3180
3181                 KASSERT(m < &vm_page_array[vm_page_array_size],
3182                         ("pmap_remove_pages: bad tpte %x", tpte));
3183
3184                 KKASSERT(pmap->pm_stats.resident_count > 0);
3185                 --pmap->pm_stats.resident_count;
3186
3187                 /*
3188                  * Update the vm_page_t clean and reference bits.
3189                  */
3190                 if (tpte & PG_M) {
3191                         vm_page_dirty(m);
3192                 }
3193
3194                 npv = TAILQ_NEXT(pv, pv_plist);
3195 #ifdef PMAP_DEBUG
3196                 KKASSERT(pv->pv_m == m);
3197                 KKASSERT(pv->pv_pmap == pmap);
3198 #endif
3199                 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
3200                 save_generation = ++pmap->pm_generation;
3201
3202                 m->md.pv_list_count--;
3203                 if (m->object)
3204                         atomic_add_int(&m->object->agg_pv_list_count, -1);
3205                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3206                 pmap_page_stats_deleting(m);
3207                 if (TAILQ_EMPTY(&m->md.pv_list))
3208                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3209
3210                 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem, &info);
3211                 free_pv_entry(pv);
3212
3213                 /*
3214                  * Restart the scan if we blocked during the unuse or free
3215                  * calls and other removals were made.
3216                  */
3217                 if (save_generation != pmap->pm_generation) {
3218                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3219                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3220                 }
3221         }
3222         pmap_inval_done(&info);
3223         lwkt_reltoken(&vm_token);
3224         if (pmap->pm_pteobj)
3225                 vm_object_drop(pmap->pm_pteobj);
3226 }
3227
3228 /*
3229  * pmap_testbit tests bits in pte's
3230  * note that the testbit/clearbit routines are inline,
3231  * and a lot of things compile-time evaluate.
3232  *
3233  * The caller must hold vm_token.
3234  */
3235 static boolean_t
3236 pmap_testbit(vm_page_t m, int bit)
3237 {
3238         pv_entry_t pv;
3239         unsigned *pte;
3240
3241         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3242                 return FALSE;
3243
3244         if (TAILQ_FIRST(&m->md.pv_list) == NULL)
3245                 return FALSE;
3246
3247         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3248                 /*
3249                  * if the bit being tested is the modified bit, then
3250                  * mark clean_map and ptes as never
3251                  * modified.
3252                  */
3253                 if (bit & (PG_A|PG_M)) {
3254                         if (!pmap_track_modified(pv->pv_va))
3255                                 continue;
3256                 }
3257
3258 #if defined(PMAP_DIAGNOSTIC)
3259                 if (!pv->pv_pmap) {
3260                         kprintf("Null pmap (tb) at va: %p\n",
3261                                 (void *)pv->pv_va);
3262                         continue;
3263                 }
3264 #endif
3265                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3266                 if (*pte & bit) {
3267                         return TRUE;
3268                 }
3269         }
3270         return (FALSE);
3271 }
3272
3273 /*
3274  * This routine is used to modify bits in ptes
3275  *
3276  * The caller must hold vm_token.
3277  */
3278 static __inline void
3279 pmap_clearbit(vm_page_t m, int bit)
3280 {
3281         struct pmap_inval_info info;
3282         pv_entry_t pv;
3283         unsigned *pte;
3284         unsigned pbits;
3285
3286         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3287                 return;
3288
3289         pmap_inval_init(&info);
3290
3291         /*
3292          * Loop over all current mappings setting/clearing as appropos If
3293          * setting RO do we need to clear the VAC?
3294          */
3295         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3296                 /*
3297                  * don't write protect pager mappings
3298                  */
3299                 if (bit == PG_RW) {
3300                         if (!pmap_track_modified(pv->pv_va))
3301                                 continue;
3302                 }
3303
3304 #if defined(PMAP_DIAGNOSTIC)
3305                 if (!pv->pv_pmap) {
3306                         kprintf("Null pmap (cb) at va: %p\n",
3307                                 (void *)pv->pv_va);
3308                         continue;
3309                 }
3310 #endif
3311
3312                 /*
3313                  * Careful here.  We can use a locked bus instruction to
3314                  * clear PG_A or PG_M safely but we need to synchronize
3315                  * with the target cpus when we mess with PG_RW.
3316                  *
3317                  * We do not have to force synchronization when clearing
3318                  * PG_M even for PTEs generated via virtual memory maps,
3319                  * because the virtual kernel will invalidate the pmap
3320                  * entry when/if it needs to resynchronize the Modify bit.
3321                  */
3322                 if (bit & PG_RW)
3323                         pmap_inval_interlock(&info, pv->pv_pmap, pv->pv_va);
3324                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3325 again:
3326                 pbits = *pte;
3327                 if (pbits & bit) {
3328                         if (bit == PG_RW) {
3329                                 if (pbits & PG_M) {
3330                                         vm_page_dirty(m);
3331                                         atomic_clear_int(pte, PG_M|PG_RW);
3332                                 } else {
3333                                         /*
3334                                          * The cpu may be trying to set PG_M
3335                                          * simultaniously with our clearing
3336                                          * of PG_RW.
3337                                          */
3338                                         if (!atomic_cmpset_int(pte, pbits,
3339                                                                pbits & ~PG_RW))
3340                                                 goto again;
3341                                 }
3342                         } else if (bit == PG_M) {
3343                                 /*
3344                                  * We could also clear PG_RW here to force
3345                                  * a fault on write to redetect PG_M for
3346                                  * virtual kernels, but it isn't necessary
3347                                  * since virtual kernels invalidate the pte 
3348                                  * when they clear the VPTE_M bit in their
3349                                  * virtual page tables.
3350                                  */
3351                                 atomic_clear_int(pte, PG_M);
3352                         } else {
3353                                 atomic_clear_int(pte, bit);
3354                         }
3355                 }
3356                 if (bit & PG_RW)
3357                         pmap_inval_deinterlock(&info, pv->pv_pmap);
3358         }
3359         pmap_inval_done(&info);
3360 }
3361
3362 /*
3363  * Lower the permission for all mappings to a given page.
3364  *
3365  * No requirements.
3366  */
3367 void
3368 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3369 {
3370         if ((prot & VM_PROT_WRITE) == 0) {
3371                 lwkt_gettoken(&vm_token);
3372                 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3373                         pmap_clearbit(m, PG_RW);
3374                         vm_page_flag_clear(m, PG_WRITEABLE);
3375                 } else {
3376                         pmap_remove_all(m);
3377                 }
3378                 lwkt_reltoken(&vm_token);
3379         }
3380 }
3381
3382 /*
3383  * Return the physical address given a physical page index.
3384  *
3385  * No requirements.
3386  */
3387 vm_paddr_t
3388 pmap_phys_address(vm_pindex_t ppn)
3389 {
3390         return (i386_ptob(ppn));
3391 }
3392
3393 /*
3394  * Return a count of reference bits for a page, clearing those bits.
3395  * It is not necessary for every reference bit to be cleared, but it
3396  * is necessary that 0 only be returned when there are truly no
3397  * reference bits set.
3398  *
3399  * No requirements.
3400  */
3401 int
3402 pmap_ts_referenced(vm_page_t m)
3403 {
3404         pv_entry_t pv, pvf, pvn;
3405         unsigned *pte;
3406         int rtval = 0;
3407
3408         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3409                 return (rtval);
3410
3411         lwkt_gettoken(&vm_token);
3412
3413         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3414
3415                 pvf = pv;
3416
3417                 do {
3418                         pvn = TAILQ_NEXT(pv, pv_list);
3419
3420                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3421                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3422
3423                         if (!pmap_track_modified(pv->pv_va))
3424                                 continue;
3425
3426                         pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3427
3428                         if (pte && (*pte & PG_A)) {
3429                                 atomic_clear_int(pte, PG_A);
3430                                 rtval++;
3431                                 if (rtval > 4) {
3432                                         break;
3433                                 }
3434                         }
3435                 } while ((pv = pvn) != NULL && pv != pvf);
3436         }
3437
3438         lwkt_reltoken(&vm_token);
3439
3440         return (rtval);
3441 }
3442
3443 /*
3444  * Return whether or not the specified physical page was modified
3445  * in any physical maps.
3446  *
3447  * No requirements.
3448  */
3449 boolean_t
3450 pmap_is_modified(vm_page_t m)
3451 {
3452         boolean_t res;
3453
3454         lwkt_gettoken(&vm_token);
3455         res = pmap_testbit(m, PG_M);
3456         lwkt_reltoken(&vm_token);
3457         return (res);
3458 }
3459
3460 /*
3461  * Clear the modify bits on the specified physical page.
3462  *
3463  * No requirements.
3464  */
3465 void
3466 pmap_clear_modify(vm_page_t m)
3467 {
3468         lwkt_gettoken(&vm_token);
3469         pmap_clearbit(m, PG_M);
3470         lwkt_reltoken(&vm_token);
3471 }
3472
3473 /*
3474  * Clear the reference bit on the specified physical page.
3475  *
3476  * No requirements.
3477  */
3478 void
3479 pmap_clear_reference(vm_page_t m)
3480 {
3481         lwkt_gettoken(&vm_token);
3482         pmap_clearbit(m, PG_A);
3483         lwkt_reltoken(&vm_token);
3484 }
3485
3486 /*
3487  * Miscellaneous support routines follow
3488  *
3489  * Called from the low level boot code only.
3490  */
3491 static void
3492 i386_protection_init(void)
3493 {
3494         int *kp, prot;
3495
3496         kp = protection_codes;
3497         for (prot = 0; prot < 8; prot++) {
3498                 switch (prot) {
3499                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
3500                         /*
3501                          * Read access is also 0. There isn't any execute bit,
3502                          * so just make it readable.
3503                          */
3504                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
3505                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
3506                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
3507                         *kp++ = 0;
3508                         break;
3509                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
3510                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
3511                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
3512                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
3513                         *kp++ = PG_RW;
3514                         break;
3515                 }
3516         }
3517 }
3518
3519 /*
3520  * Map a set of physical memory pages into the kernel virtual
3521  * address space. Return a pointer to where it is mapped. This
3522  * routine is intended to be used for mapping device memory,
3523  * NOT real memory.
3524  *
3525  * NOTE: We can't use pgeflag unless we invalidate the pages one at
3526  *       a time.
3527  *
3528  * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
3529  *       work whether the cpu supports PAT or not.  The remaining PAT
3530  *       attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
3531  *       supports PAT.
3532  */
3533 void *
3534 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
3535 {
3536         return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
3537 }
3538
3539 void *
3540 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
3541 {
3542         return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
3543 }
3544
3545 void *
3546 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
3547 {
3548         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
3549 }
3550
3551 /*
3552  * Map a set of physical memory pages into the kernel virtual
3553  * address space. Return a pointer to where it is mapped. This
3554  * routine is intended to be used for mapping device memory,
3555  * NOT real memory.
3556  */
3557 void *
3558 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
3559 {
3560         vm_offset_t va, tmpva, offset;
3561         pt_entry_t *pte;
3562         vm_size_t tmpsize;
3563
3564         offset = pa & PAGE_MASK;
3565         size = roundup(offset + size, PAGE_SIZE);
3566
3567         va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
3568         if (va == 0)
3569                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3570
3571         pa = pa & ~PAGE_MASK;
3572         for (tmpva = va, tmpsize = size; tmpsize > 0;) {
3573                 pte = vtopte(tmpva);
3574                 *pte = pa | PG_RW | PG_V | /* pgeflag | */
3575                        pat_pte_index[mode];
3576                 tmpsize -= PAGE_SIZE;
3577                 tmpva += PAGE_SIZE;
3578                 pa += PAGE_SIZE;
3579         }
3580         pmap_invalidate_range(&kernel_pmap, va, va + size);
3581         pmap_invalidate_cache_range(va, va + size);
3582
3583         return ((void *)(va + offset));
3584 }
3585
3586 /*
3587  * No requirements.
3588  */
3589 void
3590 pmap_unmapdev(vm_offset_t va, vm_size_t size)
3591 {
3592         vm_offset_t base, offset;
3593
3594         base = va & PG_FRAME;
3595         offset = va & PAGE_MASK;
3596         size = roundup(offset + size, PAGE_SIZE);
3597         pmap_qremove(va, size >> PAGE_SHIFT);
3598         kmem_free(&kernel_map, base, size);
3599 }
3600
3601 /*
3602  * Sets the memory attribute for the specified page.
3603  */
3604 void
3605 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
3606 {
3607         m->pat_mode = ma;
3608
3609 #ifdef notyet
3610         /*
3611          * XXX
3612          * The following code is NOP, until we get pmap_change_attr()
3613          * implemented.
3614          */
3615
3616         /*
3617          * If "m" is a normal page, update its direct mapping.  This update
3618          * can be relied upon to perform any cache operations that are
3619          * required for data coherence.
3620          */
3621         if ((m->flags & PG_FICTITIOUS) == 0)
3622             pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
3623             m->pat_mode);
3624 #endif
3625 }
3626
3627 /*
3628  * Change the PAT attribute on an existing kernel memory map.  Caller
3629  * must ensure that the virtual memory in question is not accessed
3630  * during the adjustment.
3631  */
3632 void
3633 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
3634 {
3635         pt_entry_t *pte;
3636         vm_offset_t base;
3637         int changed = 0;
3638
3639         if (va == 0)
3640                 panic("pmap_change_attr: va is NULL");
3641         base = trunc_page(va);
3642
3643         while (count) {
3644                 pte = vtopte(va);
3645                 *pte = (*pte & ~(pt_entry_t)(PG_PTE_PAT | PG_NC_PCD |
3646                                              PG_NC_PWT)) |
3647                        pat_pte_index[mode];
3648                 --count;
3649                 va += PAGE_SIZE;
3650         }
3651
3652         changed = 1;    /* XXX: not optimal */
3653
3654         /*
3655          * Flush CPU caches if required to make sure any data isn't cached that
3656          * shouldn't be, etc.
3657          */
3658         if (changed) {
3659                 pmap_invalidate_range(&kernel_pmap, base, va);
3660                 pmap_invalidate_cache_range(base, va);
3661         }
3662 }
3663
3664 /*
3665  * Perform the pmap work for mincore
3666  *
3667  * The caller must hold vm_token if the caller wishes a stable result,
3668  * and even in that case some bits can change due to third party accesses
3669  * to the pmap.
3670  *
3671  * No requirements.
3672  */
3673 int
3674 pmap_mincore(pmap_t pmap, vm_offset_t addr)
3675 {
3676         unsigned *ptep, pte;
3677         vm_page_t m;
3678         int val = 0;
3679
3680         lwkt_gettoken(&vm_token);
3681         ptep = pmap_pte(pmap, addr);
3682
3683         if (ptep && (pte = *ptep) != 0) {
3684                 vm_offset_t pa;
3685
3686                 val = MINCORE_INCORE;
3687                 if ((pte & PG_MANAGED) == 0)
3688                         goto done;
3689
3690                 pa = pte & PG_FRAME;
3691
3692                 m = PHYS_TO_VM_PAGE(pa);
3693
3694                 if (pte & PG_M) {
3695                         /*
3696                          * Modified by us
3697                          */
3698                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3699                 } else if (m->dirty || pmap_is_modified(m)) {
3700                         /*
3701                          * Modified by someone else
3702                          */
3703                         val |= MINCORE_MODIFIED_OTHER;
3704                 }
3705
3706                 if (pte & PG_A) {
3707                         /*
3708                          * Referenced by us
3709                          */
3710                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3711                 } else if ((m->flags & PG_REFERENCED) ||
3712                            pmap_ts_referenced(m)) {
3713                         /*
3714                          * Referenced by someone else
3715                          */
3716                         val |= MINCORE_REFERENCED_OTHER;
3717                         vm_page_flag_set(m, PG_REFERENCED);
3718                 }
3719         } 
3720 done:
3721         lwkt_reltoken(&vm_token);
3722         return val;
3723 }
3724
3725 /*
3726  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
3727  * vmspace will be ref'd and the old one will be deref'd.
3728  *
3729  * cr3 will be reloaded if any lwp is the current lwp.
3730  *
3731  * Only called with new VM spaces.
3732  * The process must have only a single thread.
3733  * The process must hold the vmspace->vm_map.token for oldvm and newvm
3734  * No other requirements.
3735  */
3736 void
3737 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
3738 {
3739         struct vmspace *oldvm;
3740         struct lwp *lp;
3741
3742         oldvm = p->p_vmspace;
3743         if (oldvm != newvm) {
3744                 if (adjrefs)
3745                         sysref_get(&newvm->vm_sysref);
3746                 p->p_vmspace = newvm;
3747                 KKASSERT(p->p_nthreads == 1);
3748                 lp = RB_ROOT(&p->p_lwp_tree);
3749                 pmap_setlwpvm(lp, newvm);
3750                 if (adjrefs) 
3751                         sysref_put(&oldvm->vm_sysref);
3752         }
3753 }
3754
3755 /*
3756  * Set the vmspace for a LWP.  The vmspace is almost universally set the
3757  * same as the process vmspace, but virtual kernels need to swap out contexts
3758  * on a per-lwp basis.
3759  *
3760  * Always called with a lp under the caller's direct control, either
3761  * unscheduled or the current lwp.
3762  *
3763  * No requirements.
3764  */
3765 void
3766 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
3767 {
3768         struct vmspace *oldvm;
3769         struct pmap *pmap;
3770
3771         oldvm = lp->lwp_vmspace;
3772
3773         if (oldvm != newvm) {
3774                 lp->lwp_vmspace = newvm;
3775                 if (curthread->td_lwp == lp) {
3776                         pmap = vmspace_pmap(newvm);
3777                         atomic_set_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
3778                         if (pmap->pm_active & CPUMASK_LOCK)
3779                                 pmap_interlock_wait(newvm);
3780 #if defined(SWTCH_OPTIM_STATS)
3781                         tlb_flush_count++;
3782 #endif
3783                         curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pdir);
3784                         load_cr3(curthread->td_pcb->pcb_cr3);
3785                         pmap = vmspace_pmap(oldvm);
3786                         atomic_clear_cpumask(&pmap->pm_active,
3787                                              mycpu->gd_cpumask);
3788                 }
3789         }
3790 }
3791
3792 /*
3793  * Called when switching to a locked pmap, used to interlock against pmaps
3794  * undergoing modifications to prevent us from activating the MMU for the
3795  * target pmap until all such modifications have completed.  We have to do
3796  * this because the thread making the modifications has already set up its
3797  * SMP synchronization mask.
3798  *
3799  * No requirements.
3800  */
3801 void
3802 pmap_interlock_wait(struct vmspace *vm)
3803 {
3804         struct pmap *pmap = &vm->vm_pmap;
3805
3806         if (pmap->pm_active & CPUMASK_LOCK) {
3807                 crit_enter();
3808                 DEBUG_PUSH_INFO("pmap_interlock_wait");
3809                 while (pmap->pm_active & CPUMASK_LOCK) {
3810                         cpu_ccfence();
3811                         lwkt_process_ipiq();
3812                 }
3813                 DEBUG_POP_INFO();
3814                 crit_exit();
3815         }
3816 }
3817
3818 /*
3819  * Return a page-directory alignment hint for device mappings which will
3820  * allow the use of super-pages for the mapping.
3821  *
3822  * No requirements.
3823  */
3824 vm_offset_t
3825 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3826 {
3827
3828         if ((obj == NULL) || (size < NBPDR) ||
3829             ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
3830                 return addr;
3831         }
3832
3833         addr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
3834         return addr;
3835 }
3836
3837 /*
3838  * Return whether the PGE flag is supported globally.
3839  *
3840  * No requirements.
3841  */
3842 int
3843 pmap_get_pgeflag(void)
3844 {
3845         return pgeflag;
3846 }
3847
3848 /*
3849  * Used by kmalloc/kfree, page already exists at va
3850  */
3851 vm_page_t
3852 pmap_kvtom(vm_offset_t va)
3853 {
3854         return(PHYS_TO_VM_PAGE(*vtopte(va) & PG_FRAME));
3855 }
3856
3857 void
3858 pmap_object_init(vm_object_t object)
3859 {
3860         /* empty */
3861 }
3862
3863 void
3864 pmap_object_free(vm_object_t object)
3865 {
3866         /* empty */
3867 }