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