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