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