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