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