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