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