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