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