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