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