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