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