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