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