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