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