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