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