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