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