7396c056e2438cdbb1e8837224272ec96021c449
[dragonfly.git] / sys / platform / pc64 / x86_64 / pmap.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * Copyright (c) 1994 John S. Dyson
6  * Copyright (c) 1994 David Greenman
7  * Copyright (c) 2003 Peter Wemm
8  * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
9  * Copyright (c) 2008, 2009 The DragonFly Project.
10  * Copyright (c) 2008, 2009 Jordan Gordeev.
11  * All rights reserved.
12  *
13  * This code is derived from software contributed to Berkeley by
14  * the Systems Programming Group of the University of Utah Computer
15  * Science Department and William Jolitz of UUNET Technologies Inc.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. All advertising materials mentioning features or use of this software
26  *    must display the following acknowledgement:
27  *      This product includes software developed by the University of
28  *      California, Berkeley and its contributors.
29  * 4. Neither the name of the University nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43  * SUCH DAMAGE.
44  *
45  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
46  * $FreeBSD: src/sys/i386/i386/pmap.c,v 1.250.2.18 2002/03/06 22:48:53 silby Exp $
47  */
48
49 /*
50  *      Manages physical address maps.
51  *
52  *      In addition to hardware address maps, this
53  *      module is called upon to provide software-use-only
54  *      maps which may or may not be stored in the same
55  *      form as hardware maps.  These pseudo-maps are
56  *      used to store intermediate results from copy
57  *      operations to and from address spaces.
58  *
59  *      Since the information managed by this module is
60  *      also stored by the logical address mapping module,
61  *      this module may throw away valid virtual-to-physical
62  *      mappings at almost any time.  However, invalidations
63  *      of virtual-to-physical mappings must be done as
64  *      requested.
65  *
66  *      In order to cope with hardware architectures which
67  *      make virtual-to-physical map invalidates expensive,
68  *      this module may delay invalidate or reduced protection
69  *      operations until such time as they are actually
70  *      necessary.  This module is given full information as
71  *      to which processors are currently using which maps,
72  *      and to when physical maps must be made correct.
73  */
74
75 #if JG
76 #include "opt_disable_pse.h"
77 #include "opt_pmap.h"
78 #endif
79 #include "opt_msgbuf.h"
80
81 #include <sys/param.h>
82 #include <sys/systm.h>
83 #include <sys/kernel.h>
84 #include <sys/proc.h>
85 #include <sys/msgbuf.h>
86 #include <sys/vmmeter.h>
87 #include <sys/mman.h>
88
89 #include <vm/vm.h>
90 #include <vm/vm_param.h>
91 #include <sys/sysctl.h>
92 #include <sys/lock.h>
93 #include <vm/vm_kern.h>
94 #include <vm/vm_page.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_object.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vm_pageout.h>
99 #include <vm/vm_pager.h>
100 #include <vm/vm_zone.h>
101
102 #include <sys/user.h>
103 #include <sys/thread2.h>
104 #include <sys/sysref2.h>
105 #include <sys/spinlock2.h>
106 #include <vm/vm_page2.h>
107
108 #include <machine/cputypes.h>
109 #include <machine/md_var.h>
110 #include <machine/specialreg.h>
111 #include <machine/smp.h>
112 #include <machine_base/apic/apicreg.h>
113 #include <machine/globaldata.h>
114 #include <machine/pmap.h>
115 #include <machine/pmap_inval.h>
116
117 #include <ddb/ddb.h>
118
119 #define PMAP_KEEP_PDIRS
120 #ifndef PMAP_SHPGPERPROC
121 #define PMAP_SHPGPERPROC 200
122 #endif
123
124 #if defined(DIAGNOSTIC)
125 #define PMAP_DIAGNOSTIC
126 #endif
127
128 #define MINPV 2048
129
130 /*
131  * Get PDEs and PTEs for user/kernel address space
132  */
133 static pd_entry_t *pmap_pde(pmap_t pmap, vm_offset_t va);
134 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
135
136 #define pmap_pde_v(pte)         ((*(pd_entry_t *)pte & PG_V) != 0)
137 #define pmap_pte_w(pte)         ((*(pt_entry_t *)pte & PG_W) != 0)
138 #define pmap_pte_m(pte)         ((*(pt_entry_t *)pte & PG_M) != 0)
139 #define pmap_pte_u(pte)         ((*(pt_entry_t *)pte & PG_A) != 0)
140 #define pmap_pte_v(pte)         ((*(pt_entry_t *)pte & PG_V) != 0)
141
142
143 /*
144  * Given a map and a machine independent protection code,
145  * convert to a vax protection code.
146  */
147 #define pte_prot(m, p)          \
148         (protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
149 static int protection_codes[8];
150
151 struct pmap kernel_pmap;
152 static TAILQ_HEAD(,pmap)        pmap_list = TAILQ_HEAD_INITIALIZER(pmap_list);
153
154 vm_paddr_t avail_start;         /* PA of first available physical page */
155 vm_paddr_t avail_end;           /* PA of last available physical page */
156 vm_offset_t virtual2_start;     /* cutout free area prior to kernel start */
157 vm_offset_t virtual2_end;
158 vm_offset_t virtual_start;      /* VA of first avail page (after kernel bss) */
159 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
160 vm_offset_t KvaStart;           /* VA start of KVA space */
161 vm_offset_t KvaEnd;             /* VA end of KVA space (non-inclusive) */
162 vm_offset_t KvaSize;            /* max size of kernel virtual address space */
163 static boolean_t pmap_initialized = FALSE;      /* Has pmap_init completed? */
164 static int pgeflag;             /* PG_G or-in */
165 static int pseflag;             /* PG_PS or-in */
166
167 static vm_object_t kptobj;
168
169 static int ndmpdp;
170 static vm_paddr_t dmaplimit;
171 static int nkpt;
172 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
173
174 static uint64_t KPTbase;
175 static uint64_t KPTphys;
176 static uint64_t KPDphys;        /* phys addr of kernel level 2 */
177 static uint64_t KPDbase;        /* phys addr of kernel level 2 @ KERNBASE */
178 uint64_t KPDPphys;      /* phys addr of kernel level 3 */
179 uint64_t KPML4phys;     /* phys addr of kernel level 4 */
180
181 static uint64_t DMPDphys;       /* phys addr of direct mapped level 2 */
182 static uint64_t DMPDPphys;      /* phys addr of direct mapped level 3 */
183
184 /*
185  * Data for the pv entry allocation mechanism
186  */
187 static vm_zone_t pvzone;
188 static struct vm_zone pvzone_store;
189 static struct vm_object pvzone_obj;
190 static int pv_entry_count=0, pv_entry_max=0, pv_entry_high_water=0;
191 static int pmap_pagedaemon_waken = 0;
192 static struct pv_entry *pvinit;
193
194 /*
195  * All those kernel PT submaps that BSD is so fond of
196  */
197 pt_entry_t *CMAP1 = 0, *ptmmap;
198 caddr_t CADDR1 = 0, ptvmmap = 0;
199 static pt_entry_t *msgbufmap;
200 struct msgbuf *msgbufp=0;
201
202 /*
203  * Crashdump maps.
204  */
205 static pt_entry_t *pt_crashdumpmap;
206 static caddr_t crashdumpmap;
207
208 static int pmap_yield_count = 64;
209 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
210     &pmap_yield_count, 0, "Yield during init_pt/release");
211
212 #define DISABLE_PSE
213
214 static pv_entry_t get_pv_entry (void);
215 static void i386_protection_init (void);
216 static void create_pagetables(vm_paddr_t *firstaddr);
217 static void pmap_remove_all (vm_page_t m);
218 static int  pmap_remove_pte (struct pmap *pmap, pt_entry_t *ptq,
219                                 vm_offset_t sva, pmap_inval_info_t info);
220 static void pmap_remove_page (struct pmap *pmap, 
221                                 vm_offset_t va, pmap_inval_info_t info);
222 static int  pmap_remove_entry (struct pmap *pmap, vm_page_t m,
223                                 vm_offset_t va, pmap_inval_info_t info);
224 static boolean_t pmap_testbit (vm_page_t m, int bit);
225 static void pmap_insert_entry (pmap_t pmap, vm_offset_t va,
226                                 vm_page_t mpte, vm_page_t m);
227
228 static vm_page_t pmap_allocpte (pmap_t pmap, vm_offset_t va);
229
230 static int pmap_release_free_page (pmap_t pmap, vm_page_t p);
231 static vm_page_t _pmap_allocpte (pmap_t pmap, vm_pindex_t ptepindex);
232 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
233 static vm_page_t pmap_page_lookup (vm_object_t object, vm_pindex_t pindex);
234 static int pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
235                                 pmap_inval_info_t info);
236 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
237
238 static unsigned pdir4mb;
239
240 /*
241  * Move the kernel virtual free pointer to the next
242  * 2MB.  This is used to help improve performance
243  * by using a large (2MB) page for much of the kernel
244  * (.text, .data, .bss)
245  */
246 static
247 vm_offset_t
248 pmap_kmem_choose(vm_offset_t addr)
249 {
250         vm_offset_t newaddr = addr;
251
252         newaddr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
253         return newaddr;
254 }
255
256 /*
257  * pmap_pte_quick:
258  *
259  *      Super fast pmap_pte routine best used when scanning the pv lists.
260  *      This eliminates many course-grained invltlb calls.  Note that many of
261  *      the pv list scans are across different pmaps and it is very wasteful
262  *      to do an entire invltlb when checking a single mapping.
263  */
264 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
265
266 static
267 pt_entry_t *
268 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
269 {
270         return pmap_pte(pmap, va);
271 }
272
273 /* Return a non-clipped PD index for a given VA */
274 static __inline
275 vm_pindex_t
276 pmap_pde_pindex(vm_offset_t va)
277 {
278         return va >> PDRSHIFT;
279 }
280
281 /* Return various clipped indexes for a given VA */
282 static __inline
283 vm_pindex_t
284 pmap_pte_index(vm_offset_t va)
285 {
286
287         return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
288 }
289
290 static __inline
291 vm_pindex_t
292 pmap_pde_index(vm_offset_t va)
293 {
294
295         return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
296 }
297
298 static __inline
299 vm_pindex_t
300 pmap_pdpe_index(vm_offset_t va)
301 {
302
303         return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
304 }
305
306 static __inline
307 vm_pindex_t
308 pmap_pml4e_index(vm_offset_t va)
309 {
310
311         return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
312 }
313
314 /* Return a pointer to the PML4 slot that corresponds to a VA */
315 static __inline
316 pml4_entry_t *
317 pmap_pml4e(pmap_t pmap, vm_offset_t va)
318 {
319
320         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
321 }
322
323 /* Return a pointer to the PDP slot that corresponds to a VA */
324 static __inline
325 pdp_entry_t *
326 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
327 {
328         pdp_entry_t *pdpe;
329
330         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
331         return (&pdpe[pmap_pdpe_index(va)]);
332 }
333
334 /* Return a pointer to the PDP slot that corresponds to a VA */
335 static __inline
336 pdp_entry_t *
337 pmap_pdpe(pmap_t pmap, vm_offset_t va)
338 {
339         pml4_entry_t *pml4e;
340
341         pml4e = pmap_pml4e(pmap, va);
342         if ((*pml4e & PG_V) == 0)
343                 return NULL;
344         return (pmap_pml4e_to_pdpe(pml4e, va));
345 }
346
347 /* Return a pointer to the PD slot that corresponds to a VA */
348 static __inline
349 pd_entry_t *
350 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
351 {
352         pd_entry_t *pde;
353
354         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
355         return (&pde[pmap_pde_index(va)]);
356 }
357
358 /* Return a pointer to the PD slot that corresponds to a VA */
359 static __inline
360 pd_entry_t *
361 pmap_pde(pmap_t pmap, vm_offset_t va)
362 {
363         pdp_entry_t *pdpe;
364
365         pdpe = pmap_pdpe(pmap, va);
366         if (pdpe == NULL || (*pdpe & PG_V) == 0)
367                  return NULL;
368         return (pmap_pdpe_to_pde(pdpe, va));
369 }
370
371 /* Return a pointer to the PT slot that corresponds to a VA */
372 static __inline
373 pt_entry_t *
374 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
375 {
376         pt_entry_t *pte;
377
378         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
379         return (&pte[pmap_pte_index(va)]);
380 }
381
382 /* Return a pointer to the PT slot that corresponds to a VA */
383 static __inline
384 pt_entry_t *
385 pmap_pte(pmap_t pmap, vm_offset_t va)
386 {
387         pd_entry_t *pde;
388
389         pde = pmap_pde(pmap, va);
390         if (pde == NULL || (*pde & PG_V) == 0)
391                 return NULL;
392         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
393                 return ((pt_entry_t *)pde);
394         return (pmap_pde_to_pte(pde, va));
395 }
396
397 static __inline
398 pt_entry_t *
399 vtopte(vm_offset_t va)
400 {
401         uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
402                                   NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
403
404         return (PTmap + ((va >> PAGE_SHIFT) & mask));
405 }
406
407 static __inline
408 pd_entry_t *
409 vtopde(vm_offset_t va)
410 {
411         uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
412                                   NPML4EPGSHIFT)) - 1);
413
414         return (PDmap + ((va >> PDRSHIFT) & mask));
415 }
416
417 static uint64_t
418 allocpages(vm_paddr_t *firstaddr, long n)
419 {
420         uint64_t ret;
421
422         ret = *firstaddr;
423         bzero((void *)ret, n * PAGE_SIZE);
424         *firstaddr += n * PAGE_SIZE;
425         return (ret);
426 }
427
428 static
429 void
430 create_pagetables(vm_paddr_t *firstaddr)
431 {
432         long i;         /* must be 64 bits */
433         long nkpt_base;
434         long nkpt_phys;
435
436         /*
437          * We are running (mostly) V=P at this point
438          *
439          * Calculate NKPT - number of kernel page tables.  We have to
440          * accomodoate prealloction of the vm_page_array, dump bitmap,
441          * MSGBUF_SIZE, and other stuff.  Be generous.
442          *
443          * Maxmem is in pages.
444          */
445         ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
446         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
447                 ndmpdp = 4;
448
449         /*
450          * Starting at the beginning of kvm (not KERNBASE).
451          */
452         nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
453         nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
454         nkpt_phys += ((nkpt + nkpt + 1 + NKPML4E + NKPDPE + NDMPML4E + ndmpdp) +
455                      511) / 512;
456         nkpt_phys += 128;
457
458         /*
459          * Starting at KERNBASE - map 2G worth of page table pages.
460          * KERNBASE is offset -2G from the end of kvm.
461          */
462         nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
463
464         /*
465          * Allocate pages
466          */
467         KPTbase = allocpages(firstaddr, nkpt_base);
468         KPTphys = allocpages(firstaddr, nkpt_phys);
469         KPML4phys = allocpages(firstaddr, 1);
470         KPDPphys = allocpages(firstaddr, NKPML4E);
471         KPDphys = allocpages(firstaddr, NKPDPE);
472
473         /*
474          * Calculate the page directory base for KERNBASE,
475          * that is where we start populating the page table pages.
476          * Basically this is the end - 2.
477          */
478         KPDbase = KPDphys + ((NKPDPE - (NPDPEPG - KPDPI)) << PAGE_SHIFT);
479
480         DMPDPphys = allocpages(firstaddr, NDMPML4E);
481         if ((amd_feature & AMDID_PAGE1GB) == 0)
482                 DMPDphys = allocpages(firstaddr, ndmpdp);
483         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
484
485         /*
486          * Fill in the underlying page table pages for the area around
487          * KERNBASE.  This remaps low physical memory to KERNBASE.
488          *
489          * Read-only from zero to physfree
490          * XXX not fully used, underneath 2M pages
491          */
492         for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
493                 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
494                 ((pt_entry_t *)KPTbase)[i] |= PG_RW | PG_V | PG_G;
495         }
496
497         /*
498          * Now map the initial kernel page tables.  One block of page
499          * tables is placed at the beginning of kernel virtual memory,
500          * and another block is placed at KERNBASE to map the kernel binary,
501          * data, bss, and initial pre-allocations.
502          */
503         for (i = 0; i < nkpt_base; i++) {
504                 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
505                 ((pd_entry_t *)KPDbase)[i] |= PG_RW | PG_V;
506         }
507         for (i = 0; i < nkpt_phys; i++) {
508                 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
509                 ((pd_entry_t *)KPDphys)[i] |= PG_RW | PG_V;
510         }
511
512         /*
513          * Map from zero to end of allocations using 2M pages as an
514          * optimization.  This will bypass some of the KPTBase pages
515          * above in the KERNBASE area.
516          */
517         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
518                 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
519                 ((pd_entry_t *)KPDbase)[i] |= PG_RW | PG_V | PG_PS | PG_G;
520         }
521
522         /*
523          * And connect up the PD to the PDP.  The kernel pmap is expected
524          * to pre-populate all of its PDs.  See NKPDPE in vmparam.h.
525          */
526         for (i = 0; i < NKPDPE; i++) {
527                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] =
528                                 KPDphys + (i << PAGE_SHIFT);
529                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] |=
530                                 PG_RW | PG_V | PG_U;
531         }
532
533         /* Now set up the direct map space using either 2MB or 1GB pages */
534         /* Preset PG_M and PG_A because demotion expects it */
535         if ((amd_feature & AMDID_PAGE1GB) == 0) {
536                 for (i = 0; i < NPDEPG * ndmpdp; i++) {
537                         ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
538                         ((pd_entry_t *)DMPDphys)[i] |= PG_RW | PG_V | PG_PS |
539                             PG_G | PG_M | PG_A;
540                 }
541                 /* And the direct map space's PDP */
542                 for (i = 0; i < ndmpdp; i++) {
543                         ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
544                             (i << PAGE_SHIFT);
545                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_U;
546                 }
547         } else {
548                 for (i = 0; i < ndmpdp; i++) {
549                         ((pdp_entry_t *)DMPDPphys)[i] =
550                             (vm_paddr_t)i << PDPSHIFT;
551                         ((pdp_entry_t *)DMPDPphys)[i] |= PG_RW | PG_V | PG_PS |
552                             PG_G | PG_M | PG_A;
553                 }
554         }
555
556         /* And recursively map PML4 to itself in order to get PTmap */
557         ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
558         ((pdp_entry_t *)KPML4phys)[PML4PML4I] |= PG_RW | PG_V | PG_U;
559
560         /* Connect the Direct Map slot up to the PML4 */
561         ((pdp_entry_t *)KPML4phys)[DMPML4I] = DMPDPphys;
562         ((pdp_entry_t *)KPML4phys)[DMPML4I] |= PG_RW | PG_V | PG_U;
563
564         /* Connect the KVA slot up to the PML4 */
565         ((pdp_entry_t *)KPML4phys)[KPML4I] = KPDPphys;
566         ((pdp_entry_t *)KPML4phys)[KPML4I] |= PG_RW | PG_V | PG_U;
567 }
568
569 /*
570  *      Bootstrap the system enough to run with virtual memory.
571  *
572  *      On the i386 this is called after mapping has already been enabled
573  *      and just syncs the pmap module with what has already been done.
574  *      [We can't call it easily with mapping off since the kernel is not
575  *      mapped with PA == VA, hence we would have to relocate every address
576  *      from the linked base (virtual) address "KERNBASE" to the actual
577  *      (physical) address starting relative to 0]
578  */
579 void
580 pmap_bootstrap(vm_paddr_t *firstaddr)
581 {
582         vm_offset_t va;
583         pt_entry_t *pte;
584         struct mdglobaldata *gd;
585         int pg;
586
587         KvaStart = VM_MIN_KERNEL_ADDRESS;
588         KvaEnd = VM_MAX_KERNEL_ADDRESS;
589         KvaSize = KvaEnd - KvaStart;
590
591         avail_start = *firstaddr;
592
593         /*
594          * Create an initial set of page tables to run the kernel in.
595          */
596         create_pagetables(firstaddr);
597
598         virtual2_start = KvaStart;
599         virtual2_end = PTOV_OFFSET;
600
601         virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
602         virtual_start = pmap_kmem_choose(virtual_start);
603
604         virtual_end = VM_MAX_KERNEL_ADDRESS;
605
606         /* XXX do %cr0 as well */
607         load_cr4(rcr4() | CR4_PGE | CR4_PSE);
608         load_cr3(KPML4phys);
609
610         /*
611          * Initialize protection array.
612          */
613         i386_protection_init();
614
615         /*
616          * The kernel's pmap is statically allocated so we don't have to use
617          * pmap_create, which is unlikely to work correctly at this part of
618          * the boot sequence (XXX and which no longer exists).
619          *
620          * The kernel_pmap's pm_pteobj is used only for locking and not
621          * for mmu pages.
622          */
623         kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
624         kernel_pmap.pm_count = 1;
625         kernel_pmap.pm_active = (cpumask_t)-1 & ~CPUMASK_LOCK;
626         kernel_pmap.pm_pteobj = &kernel_object;
627         TAILQ_INIT(&kernel_pmap.pm_pvlist);
628         TAILQ_INIT(&kernel_pmap.pm_pvlist_free);
629         kernel_pmap.pm_hold = 0;
630         spin_init(&kernel_pmap.pm_spin);
631         lwkt_token_init(&kernel_pmap.pm_token, "kpmap_tok");
632
633         /*
634          * Reserve some special page table entries/VA space for temporary
635          * mapping of pages.
636          */
637 #define SYSMAP(c, p, v, n)      \
638         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
639
640         va = virtual_start;
641         pte = vtopte(va);
642
643         /*
644          * CMAP1/CMAP2 are used for zeroing and copying pages.
645          */
646         SYSMAP(caddr_t, CMAP1, CADDR1, 1)
647
648         /*
649          * Crashdump maps.
650          */
651         SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
652
653         /*
654          * ptvmmap is used for reading arbitrary physical pages via
655          * /dev/mem.
656          */
657         SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
658
659         /*
660          * msgbufp is used to map the system message buffer.
661          * XXX msgbufmap is not used.
662          */
663         SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
664                atop(round_page(MSGBUF_SIZE)))
665
666         virtual_start = va;
667
668         *CMAP1 = 0;
669
670         /*
671          * PG_G is terribly broken on SMP because we IPI invltlb's in some
672          * cases rather then invl1pg.  Actually, I don't even know why it
673          * works under UP because self-referential page table mappings
674          */
675 #ifdef SMP
676         pgeflag = 0;
677 #else
678         if (cpu_feature & CPUID_PGE)
679                 pgeflag = PG_G;
680 #endif
681         
682 /*
683  * Initialize the 4MB page size flag
684  */
685         pseflag = 0;
686 /*
687  * The 4MB page version of the initial
688  * kernel page mapping.
689  */
690         pdir4mb = 0;
691
692 #if !defined(DISABLE_PSE)
693         if (cpu_feature & CPUID_PSE) {
694                 pt_entry_t ptditmp;
695                 /*
696                  * Note that we have enabled PSE mode
697                  */
698                 pseflag = PG_PS;
699                 ptditmp = *(PTmap + x86_64_btop(KERNBASE));
700                 ptditmp &= ~(NBPDR - 1);
701                 ptditmp |= PG_V | PG_RW | PG_PS | PG_U | pgeflag;
702                 pdir4mb = ptditmp;
703
704 #ifndef SMP
705                 /*
706                  * Enable the PSE mode.  If we are SMP we can't do this
707                  * now because the APs will not be able to use it when
708                  * they boot up.
709                  */
710                 load_cr4(rcr4() | CR4_PSE);
711
712                 /*
713                  * We can do the mapping here for the single processor
714                  * case.  We simply ignore the old page table page from
715                  * now on.
716                  */
717                 /*
718                  * For SMP, we still need 4K pages to bootstrap APs,
719                  * PSE will be enabled as soon as all APs are up.
720                  */
721                 PTD[KPTDI] = (pd_entry_t)ptditmp;
722                 cpu_invltlb();
723 #endif
724         }
725 #endif
726
727         /*
728          * We need to finish setting up the globaldata page for the BSP.
729          * locore has already populated the page table for the mdglobaldata
730          * portion.
731          */
732         pg = MDGLOBALDATA_BASEALLOC_PAGES;
733         gd = &CPU_prvspace[0].mdglobaldata;
734
735         cpu_invltlb();
736 }
737
738 #ifdef SMP
739 /*
740  * Set 4mb pdir for mp startup
741  */
742 void
743 pmap_set_opt(void)
744 {
745         if (pseflag && (cpu_feature & CPUID_PSE)) {
746                 load_cr4(rcr4() | CR4_PSE);
747                 if (pdir4mb && mycpu->gd_cpuid == 0) {  /* only on BSP */
748                         cpu_invltlb();
749                 }
750         }
751 }
752 #endif
753
754 /*
755  *      Initialize the pmap module.
756  *      Called by vm_init, to initialize any structures that the pmap
757  *      system needs to map virtual memory.
758  *      pmap_init has been enhanced to support in a fairly consistant
759  *      way, discontiguous physical memory.
760  */
761 void
762 pmap_init(void)
763 {
764         int i;
765         int initial_pvs;
766
767         /*
768          * object for kernel page table pages
769          */
770         /* JG I think the number can be arbitrary */
771         kptobj = vm_object_allocate(OBJT_DEFAULT, 5);
772
773         /*
774          * Allocate memory for random pmap data structures.  Includes the
775          * pv_head_table.
776          */
777
778         for(i = 0; i < vm_page_array_size; i++) {
779                 vm_page_t m;
780
781                 m = &vm_page_array[i];
782                 TAILQ_INIT(&m->md.pv_list);
783                 m->md.pv_list_count = 0;
784         }
785
786         /*
787          * init the pv free list
788          */
789         initial_pvs = vm_page_array_size;
790         if (initial_pvs < MINPV)
791                 initial_pvs = MINPV;
792         pvzone = &pvzone_store;
793         pvinit = (void *)kmem_alloc(&kernel_map,
794                                     initial_pvs * sizeof (struct pv_entry));
795         zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
796                   pvinit, initial_pvs);
797
798         /*
799          * Now it is safe to enable pv_table recording.
800          */
801         pmap_initialized = TRUE;
802 }
803
804 /*
805  * Initialize the address space (zone) for the pv_entries.  Set a
806  * high water mark so that the system can recover from excessive
807  * numbers of pv entries.
808  */
809 void
810 pmap_init2(void)
811 {
812         int shpgperproc = PMAP_SHPGPERPROC;
813         int entry_max;
814
815         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
816         pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
817         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
818         pv_entry_high_water = 9 * (pv_entry_max / 10);
819
820         /*
821          * Subtract out pages already installed in the zone (hack)
822          */
823         entry_max = pv_entry_max - vm_page_array_size;
824         if (entry_max <= 0)
825                 entry_max = 1;
826
827         zinitna(pvzone, &pvzone_obj, NULL, 0, entry_max, ZONE_INTERRUPT, 1);
828 }
829
830
831 /***************************************************
832  * Low level helper routines.....
833  ***************************************************/
834
835 #if defined(PMAP_DIAGNOSTIC)
836
837 /*
838  * This code checks for non-writeable/modified pages.
839  * This should be an invalid condition.
840  */
841 static
842 int
843 pmap_nw_modified(pt_entry_t pte)
844 {
845         if ((pte & (PG_M|PG_RW)) == PG_M)
846                 return 1;
847         else
848                 return 0;
849 }
850 #endif
851
852
853 /*
854  * this routine defines the region(s) of memory that should
855  * not be tested for the modified bit.
856  */
857 static __inline
858 int
859 pmap_track_modified(vm_offset_t va)
860 {
861         if ((va < clean_sva) || (va >= clean_eva)) 
862                 return 1;
863         else
864                 return 0;
865 }
866
867 /*
868  * Extract the physical page address associated with the map/VA pair.
869  *
870  * The caller must hold pmap->pm_token if non-blocking operation is desired.
871  */
872 vm_paddr_t 
873 pmap_extract(pmap_t pmap, vm_offset_t va)
874 {
875         vm_paddr_t rtval;
876         pt_entry_t *pte;
877         pd_entry_t pde, *pdep;
878
879         lwkt_gettoken(&pmap->pm_token);
880         rtval = 0;
881         pdep = pmap_pde(pmap, va);
882         if (pdep != NULL) {
883                 pde = *pdep;
884                 if (pde) {
885                         if ((pde & PG_PS) != 0) {
886                                 rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
887                         } else {
888                                 pte = pmap_pde_to_pte(pdep, va);
889                                 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
890                         }
891                 }
892         }
893         lwkt_reltoken(&pmap->pm_token);
894         return rtval;
895 }
896
897 /*
898  * Extract the physical page address associated kernel virtual address.
899  */
900 vm_paddr_t
901 pmap_kextract(vm_offset_t va)
902 {
903         pd_entry_t pde;
904         vm_paddr_t pa;
905
906         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
907                 pa = DMAP_TO_PHYS(va);
908         } else {
909                 pde = *vtopde(va);
910                 if (pde & PG_PS) {
911                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
912                 } else {
913                         /*
914                          * Beware of a concurrent promotion that changes the
915                          * PDE at this point!  For example, vtopte() must not
916                          * be used to access the PTE because it would use the
917                          * new PDE.  It is, however, safe to use the old PDE
918                          * because the page table page is preserved by the
919                          * promotion.
920                          */
921                         pa = *pmap_pde_to_pte(&pde, va);
922                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
923                 }
924         }
925         return pa;
926 }
927
928 /***************************************************
929  * Low level mapping routines.....
930  ***************************************************/
931
932 /*
933  * Routine: pmap_kenter
934  * Function:
935  *      Add a wired page to the KVA
936  *      NOTE! note that in order for the mapping to take effect -- you
937  *      should do an invltlb after doing the pmap_kenter().
938  */
939 void 
940 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
941 {
942         pt_entry_t *pte;
943         pt_entry_t npte;
944         pmap_inval_info info;
945
946         pmap_inval_init(&info);
947         npte = pa | PG_RW | PG_V | pgeflag;
948         pte = vtopte(va);
949         pmap_inval_interlock(&info, &kernel_pmap, va);
950         *pte = npte;
951         pmap_inval_deinterlock(&info, &kernel_pmap);
952         pmap_inval_done(&info);
953 }
954
955 /*
956  * Routine: pmap_kenter_quick
957  * Function:
958  *      Similar to pmap_kenter(), except we only invalidate the
959  *      mapping on the current CPU.
960  */
961 void
962 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
963 {
964         pt_entry_t *pte;
965         pt_entry_t npte;
966
967         npte = pa | PG_RW | PG_V | pgeflag;
968         pte = vtopte(va);
969         *pte = npte;
970         cpu_invlpg((void *)va);
971 }
972
973 void
974 pmap_kenter_sync(vm_offset_t va)
975 {
976         pmap_inval_info info;
977
978         pmap_inval_init(&info);
979         pmap_inval_interlock(&info, &kernel_pmap, va);
980         pmap_inval_deinterlock(&info, &kernel_pmap);
981         pmap_inval_done(&info);
982 }
983
984 void
985 pmap_kenter_sync_quick(vm_offset_t va)
986 {
987         cpu_invlpg((void *)va);
988 }
989
990 /*
991  * remove a page from the kernel pagetables
992  */
993 void
994 pmap_kremove(vm_offset_t va)
995 {
996         pt_entry_t *pte;
997         pmap_inval_info info;
998
999         pmap_inval_init(&info);
1000         pte = vtopte(va);
1001         pmap_inval_interlock(&info, &kernel_pmap, va);
1002         *pte = 0;
1003         pmap_inval_deinterlock(&info, &kernel_pmap);
1004         pmap_inval_done(&info);
1005 }
1006
1007 void
1008 pmap_kremove_quick(vm_offset_t va)
1009 {
1010         pt_entry_t *pte;
1011         pte = vtopte(va);
1012         *pte = 0;
1013         cpu_invlpg((void *)va);
1014 }
1015
1016 /*
1017  * XXX these need to be recoded.  They are not used in any critical path.
1018  */
1019 void
1020 pmap_kmodify_rw(vm_offset_t va)
1021 {
1022         *vtopte(va) |= PG_RW;
1023         cpu_invlpg((void *)va);
1024 }
1025
1026 void
1027 pmap_kmodify_nc(vm_offset_t va)
1028 {
1029         *vtopte(va) |= PG_N;
1030         cpu_invlpg((void *)va);
1031 }
1032
1033 /*
1034  * Used to map a range of physical addresses into kernel virtual
1035  * address space during the low level boot, typically to map the
1036  * dump bitmap, message buffer, and vm_page_array.
1037  *
1038  * These mappings are typically made at some pointer after the end of the
1039  * kernel text+data.
1040  *
1041  * We could return PHYS_TO_DMAP(start) here and not allocate any
1042  * via (*virtp), but then kmem from userland and kernel dumps won't
1043  * have access to the related pointers.
1044  */
1045 vm_offset_t
1046 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1047 {
1048         vm_offset_t va;
1049         vm_offset_t va_start;
1050
1051         /*return PHYS_TO_DMAP(start);*/
1052
1053         va_start = *virtp;
1054         va = va_start;
1055
1056         while (start < end) {
1057                 pmap_kenter_quick(va, start);
1058                 va += PAGE_SIZE;
1059                 start += PAGE_SIZE;
1060         }
1061         *virtp = va;
1062         return va_start;
1063 }
1064
1065
1066 /*
1067  * Add a list of wired pages to the kva
1068  * this routine is only used for temporary
1069  * kernel mappings that do not need to have
1070  * page modification or references recorded.
1071  * Note that old mappings are simply written
1072  * over.  The page *must* be wired.
1073  */
1074 void
1075 pmap_qenter(vm_offset_t va, vm_page_t *m, int count)
1076 {
1077         vm_offset_t end_va;
1078
1079         end_va = va + count * PAGE_SIZE;
1080                 
1081         while (va < end_va) {
1082                 pt_entry_t *pte;
1083
1084                 pte = vtopte(va);
1085                 *pte = VM_PAGE_TO_PHYS(*m) | PG_RW | PG_V | pgeflag;
1086                 cpu_invlpg((void *)va);
1087                 va += PAGE_SIZE;
1088                 m++;
1089         }
1090         smp_invltlb();
1091 }
1092
1093 /*
1094  * This routine jerks page mappings from the
1095  * kernel -- it is meant only for temporary mappings.
1096  *
1097  * MPSAFE, INTERRUPT SAFE (cluster callback)
1098  */
1099 void
1100 pmap_qremove(vm_offset_t va, int count)
1101 {
1102         vm_offset_t end_va;
1103
1104         end_va = va + count * PAGE_SIZE;
1105
1106         while (va < end_va) {
1107                 pt_entry_t *pte;
1108
1109                 pte = vtopte(va);
1110                 *pte = 0;
1111                 cpu_invlpg((void *)va);
1112                 va += PAGE_SIZE;
1113         }
1114         smp_invltlb();
1115 }
1116
1117 /*
1118  * This routine works like vm_page_lookup() but also blocks as long as the
1119  * page is busy.  This routine does not busy the page it returns.
1120  *
1121  * The call should be made with the governing object held so the page's
1122  * object association remains valid on return.
1123  *
1124  * This function can block!
1125  */
1126 static
1127 vm_page_t
1128 pmap_page_lookup(vm_object_t object, vm_pindex_t pindex)
1129 {
1130         vm_page_t m;
1131
1132         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1133         m = vm_page_lookup_busy_wait(object, pindex, FALSE, "pplookp");
1134
1135         return(m);
1136 }
1137
1138 /*
1139  * Create a new thread and optionally associate it with a (new) process.
1140  * NOTE! the new thread's cpu may not equal the current cpu.
1141  */
1142 void
1143 pmap_init_thread(thread_t td)
1144 {
1145         /* enforce pcb placement & alignment */
1146         td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
1147         td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
1148         td->td_savefpu = &td->td_pcb->pcb_save;
1149         td->td_sp = (char *)td->td_pcb; /* no -16 */
1150 }
1151
1152 /*
1153  * This routine directly affects the fork perf for a process.
1154  */
1155 void
1156 pmap_init_proc(struct proc *p)
1157 {
1158 }
1159
1160 /*
1161  * Dispose the UPAGES for a process that has exited.
1162  * This routine directly impacts the exit perf of a process.
1163  */
1164 void
1165 pmap_dispose_proc(struct proc *p)
1166 {
1167         KASSERT(p->p_lock == 0, ("attempt to dispose referenced proc! %p", p));
1168 }
1169
1170 /***************************************************
1171  * Page table page management routines.....
1172  ***************************************************/
1173
1174 /*
1175  * After removing a page table entry, this routine is used to
1176  * conditionally free the page, and manage the hold/wire counts.
1177  */
1178 static __inline
1179 int
1180 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte,
1181               pmap_inval_info_t info)
1182 {
1183         if (mpte)
1184                 return (pmap_unwire_pte_hold(pmap, va, mpte, info));
1185         return 0;
1186 }
1187
1188 /*
1189  * This routine reduces the wire_count on a page.  If the wire_count
1190  * would drop to zero we remove the PT, PD, or PDP from its parent page
1191  * table.  Under normal operation this only occurs with PT pages.
1192  */
1193 static __inline
1194 int
1195 pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t m,
1196                      pmap_inval_info_t info)
1197 {
1198         if (!vm_page_unwire_quick(m))
1199                 return 0;
1200
1201         /* 
1202          * Wait until we can busy the page ourselves.  We cannot have
1203          * any active flushes if we block.  We own one hold count on the
1204          * page so it cannot be freed out from under us.
1205          */
1206         vm_page_busy_wait(m, FALSE, "pmuwpt");
1207         KASSERT(m->queue == PQ_NONE,
1208                 ("_pmap_unwire_pte_hold: %p->queue != PQ_NONE", m));
1209
1210         /*
1211          * New references can bump the wire_count while we were blocked,
1212          * try to unwire quickly again (e.g. 2->1).
1213          */
1214         if (vm_page_unwire_quick(m) == 0) {
1215                 vm_page_wakeup(m);
1216                 return 0;
1217         }
1218
1219         /*
1220          * Unmap the page table page
1221          */
1222         KKASSERT(m->wire_count == 1);
1223         pmap_inval_interlock(info, pmap, -1);
1224
1225         if (m->pindex >= (NUPDE + NUPDPE)) {
1226                 /* PDP page */
1227                 pml4_entry_t *pml4;
1228                 pml4 = pmap_pml4e(pmap, va);
1229                 KKASSERT(*pml4);
1230                 *pml4 = 0;
1231         } else if (m->pindex >= NUPDE) {
1232                 /* PD page */
1233                 pdp_entry_t *pdp;
1234                 pdp = pmap_pdpe(pmap, va);
1235                 KKASSERT(*pdp);
1236                 *pdp = 0;
1237         } else {
1238                 /* PT page */
1239                 pd_entry_t *pd;
1240                 pd = pmap_pde(pmap, va);
1241                 KKASSERT(*pd);
1242                 *pd = 0;
1243         }
1244
1245         KKASSERT(pmap->pm_stats.resident_count > 0);
1246         --pmap->pm_stats.resident_count;
1247
1248         if (pmap->pm_ptphint == m)
1249                 pmap->pm_ptphint = NULL;
1250         pmap_inval_deinterlock(info, pmap);
1251
1252         if (m->pindex < NUPDE) {
1253                 /* We just released a PT, unhold the matching PD */
1254                 vm_page_t pdpg;
1255
1256                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
1257                 pmap_unwire_pte_hold(pmap, va, pdpg, info);
1258         }
1259         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
1260                 /* We just released a PD, unhold the matching PDP */
1261                 vm_page_t pdppg;
1262
1263                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
1264                 pmap_unwire_pte_hold(pmap, va, pdppg, info);
1265         }
1266
1267         /*
1268          * This was our wiring.
1269          */
1270         KKASSERT(m->flags & PG_UNMANAGED);
1271         vm_page_unwire(m, 0);
1272         KKASSERT(m->wire_count == 0);
1273         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
1274         vm_page_flash(m);
1275         vm_page_free_zero(m);
1276
1277         return 1;
1278 }
1279
1280 /*
1281  * Initialize pmap0/vmspace0.  This pmap is not added to pmap_list because
1282  * it, and IdlePTD, represents the template used to update all other pmaps.
1283  *
1284  * On architectures where the kernel pmap is not integrated into the user
1285  * process pmap, this pmap represents the process pmap, not the kernel pmap.
1286  * kernel_pmap should be used to directly access the kernel_pmap.
1287  */
1288 void
1289 pmap_pinit0(struct pmap *pmap)
1290 {
1291         pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
1292         pmap->pm_count = 1;
1293         pmap->pm_active = 0;
1294         pmap->pm_ptphint = NULL;
1295         TAILQ_INIT(&pmap->pm_pvlist);
1296         TAILQ_INIT(&pmap->pm_pvlist_free);
1297         pmap->pm_hold = 0;
1298         spin_init(&pmap->pm_spin);
1299         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1300         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1301 }
1302
1303 /*
1304  * Initialize a preallocated and zeroed pmap structure,
1305  * such as one in a vmspace structure.
1306  */
1307 void
1308 pmap_pinit(struct pmap *pmap)
1309 {
1310         vm_page_t pml4pg;
1311
1312         /*
1313          * No need to allocate page table space yet but we do need a valid
1314          * page directory table.
1315          */
1316         if (pmap->pm_pml4 == NULL) {
1317                 pmap->pm_pml4 =
1318                     (pml4_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
1319         }
1320
1321         /*
1322          * Allocate an object for the ptes
1323          */
1324         if (pmap->pm_pteobj == NULL) {
1325                 pmap->pm_pteobj = vm_object_allocate(OBJT_DEFAULT,
1326                                                 NUPDE + NUPDPE + PML4PML4I + 1);
1327         }
1328
1329         /*
1330          * Allocate the page directory page, unless we already have
1331          * one cached.  If we used the cached page the wire_count will
1332          * already be set appropriately.
1333          */
1334         if ((pml4pg = pmap->pm_pdirm) == NULL) {
1335                 pml4pg = vm_page_grab(pmap->pm_pteobj,
1336                                       NUPDE + NUPDPE + PML4PML4I,
1337                                       VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
1338                 pmap->pm_pdirm = pml4pg;
1339                 vm_page_unmanage(pml4pg);
1340                 vm_page_flag_clear(pml4pg, PG_MAPPED);
1341                 pml4pg->valid = VM_PAGE_BITS_ALL;
1342                 vm_page_wire(pml4pg);
1343                 vm_page_wakeup(pml4pg);
1344                 pmap_kenter((vm_offset_t)pmap->pm_pml4,
1345                             VM_PAGE_TO_PHYS(pml4pg));
1346         }
1347         if ((pml4pg->flags & PG_ZERO) == 0)
1348                 bzero(pmap->pm_pml4, PAGE_SIZE);
1349 #ifdef PMAP_DEBUG
1350         else
1351                 pmap_page_assertzero(VM_PAGE_TO_PHYS(pml4pg));
1352 #endif
1353         vm_page_flag_clear(pml4pg, PG_ZERO);
1354
1355         pmap->pm_pml4[KPML4I] = KPDPphys | PG_RW | PG_V | PG_U;
1356         pmap->pm_pml4[DMPML4I] = DMPDPphys | PG_RW | PG_V | PG_U;
1357
1358         /* install self-referential address mapping entry */
1359         pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) |
1360                                    PG_V | PG_RW | PG_A | PG_M;
1361
1362         pmap->pm_count = 1;
1363         pmap->pm_active = 0;
1364         pmap->pm_ptphint = NULL;
1365         TAILQ_INIT(&pmap->pm_pvlist);
1366         TAILQ_INIT(&pmap->pm_pvlist_free);
1367         pmap->pm_hold = 0;
1368         spin_init(&pmap->pm_spin);
1369         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1370         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1371         pmap->pm_stats.resident_count = 1;
1372 }
1373
1374 /*
1375  * Clean up a pmap structure so it can be physically freed.  This routine
1376  * is called by the vmspace dtor function.  A great deal of pmap data is
1377  * left passively mapped to improve vmspace management so we have a bit
1378  * of cleanup work to do here.
1379  */
1380 void
1381 pmap_puninit(pmap_t pmap)
1382 {
1383         vm_page_t p;
1384
1385         KKASSERT(pmap->pm_active == 0);
1386         if ((p = pmap->pm_pdirm) != NULL) {
1387                 KKASSERT(pmap->pm_pml4 != NULL);
1388                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1389                 pmap_kremove((vm_offset_t)pmap->pm_pml4);
1390                 vm_page_busy_wait(p, FALSE, "pgpun");
1391                 KKASSERT(p->flags & PG_UNMANAGED);
1392                 vm_page_unwire(p, 0);
1393                 vm_page_free_zero(p);
1394                 pmap->pm_pdirm = NULL;
1395         }
1396         if (pmap->pm_pml4) {
1397                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1398                 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
1399                 pmap->pm_pml4 = NULL;
1400         }
1401         if (pmap->pm_pteobj) {
1402                 vm_object_deallocate(pmap->pm_pteobj);
1403                 pmap->pm_pteobj = NULL;
1404         }
1405 }
1406
1407 /*
1408  * Wire in kernel global address entries.  To avoid a race condition
1409  * between pmap initialization and pmap_growkernel, this procedure
1410  * adds the pmap to the master list (which growkernel scans to update),
1411  * then copies the template.
1412  */
1413 void
1414 pmap_pinit2(struct pmap *pmap)
1415 {
1416         /*
1417          * XXX copies current process, does not fill in MPPTDI
1418          */
1419         spin_lock(&pmap_spin);
1420         TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
1421         spin_unlock(&pmap_spin);
1422 }
1423
1424 /*
1425  * Attempt to release and free a vm_page in a pmap.  Returns 1 on success,
1426  * 0 on failure (if the procedure had to sleep).
1427  *
1428  * When asked to remove the page directory page itself, we actually just
1429  * leave it cached so we do not have to incur the SMP inval overhead of
1430  * removing the kernel mapping.  pmap_puninit() will take care of it.
1431  */
1432 static
1433 int
1434 pmap_release_free_page(struct pmap *pmap, vm_page_t p)
1435 {
1436         /*
1437          * This code optimizes the case of freeing non-busy
1438          * page-table pages.  Those pages are zero now, and
1439          * might as well be placed directly into the zero queue.
1440          */
1441         if (vm_page_busy_try(p, FALSE)) {
1442                 vm_page_sleep_busy(p, FALSE, "pmaprl");
1443                 return 0;
1444         }
1445
1446         /*
1447          * Remove the page table page from the processes address space.
1448          */
1449         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1450                 /*
1451                  * We are the pml4 table itself.
1452                  */
1453                 /* XXX anything to do here? */
1454         } else if (p->pindex >= (NUPDE + NUPDPE)) {
1455                 /*
1456                  * Remove a PDP page from the PML4.  We do not maintain
1457                  * wire counts on the PML4 page.
1458                  */
1459                 pml4_entry_t *pml4;
1460                 vm_page_t m4;
1461                 int idx;
1462
1463                 m4 = vm_page_lookup(pmap->pm_pteobj,
1464                                     NUPDE + NUPDPE + PML4PML4I);
1465                 KKASSERT(m4 != NULL);
1466                 pml4 = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m4));
1467                 idx = (p->pindex - (NUPDE + NUPDPE)) % NPML4EPG;
1468                 KKASSERT(pml4[idx] != 0);
1469                 pml4[idx] = 0;
1470         } else if (p->pindex >= NUPDE) {
1471                 /*
1472                  * Remove a PD page from the PDP and drop the wire count
1473                  * on the PDP.  The PDP has a wire_count just from being
1474                  * mapped so the wire_count should never drop to 0 here.
1475                  */
1476                 vm_page_t m3;
1477                 pdp_entry_t *pdp;
1478                 int idx;
1479
1480                 m3 = vm_page_lookup(pmap->pm_pteobj,
1481                                 NUPDE + NUPDPE + (p->pindex - NUPDE) / NPDPEPG);
1482                 KKASSERT(m3 != NULL);
1483                 pdp = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m3));
1484                 idx = (p->pindex - NUPDE) % NPDPEPG;
1485                 KKASSERT(pdp[idx] != 0);
1486                 pdp[idx] = 0;
1487                 if (vm_page_unwire_quick(m3))
1488                         panic("pmap_release_free_page: m3 wire_count 1->0");
1489         } else {
1490                 /*
1491                  * Remove a PT page from the PD and drop the wire count
1492                  * on the PD.  The PD has a wire_count just from being
1493                  * mapped so the wire_count should never drop to 0 here.
1494                  */
1495                 vm_page_t m2;
1496                 pd_entry_t *pd;
1497                 int idx;
1498
1499                 m2 = vm_page_lookup(pmap->pm_pteobj,
1500                                     NUPDE + p->pindex / NPDEPG);
1501                 KKASSERT(m2 != NULL);
1502                 pd = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m2));
1503                 idx = p->pindex % NPDEPG;
1504                 pd[idx] = 0;
1505                 if (vm_page_unwire_quick(m2))
1506                         panic("pmap_release_free_page: m2 wire_count 1->0");
1507         }
1508
1509         /*
1510          * p's wire_count should be transitioning from 1 to 0 here.
1511          */
1512         KKASSERT(p->wire_count == 1);
1513         KKASSERT(p->flags & PG_UNMANAGED);
1514         KKASSERT(pmap->pm_stats.resident_count > 0);
1515         vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
1516         --pmap->pm_stats.resident_count;
1517         if (pmap->pm_ptphint && (pmap->pm_ptphint->pindex == p->pindex))
1518                 pmap->pm_ptphint = NULL;
1519
1520         /*
1521          * We leave the top-level page table page cached, wired, and mapped in
1522          * the pmap until the dtor function (pmap_puninit()) gets called.
1523          * However, still clean it up so we can set PG_ZERO.
1524          */
1525         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1526                 bzero(pmap->pm_pml4, PAGE_SIZE);
1527                 vm_page_flag_set(p, PG_ZERO);
1528                 vm_page_wakeup(p);
1529         } else {
1530                 vm_page_unwire(p, 0);
1531                 KKASSERT(p->wire_count == 0);
1532                 /* JG eventually revert to using vm_page_free_zero() */
1533                 vm_page_free(p);
1534         }
1535         return 1;
1536 }
1537
1538 /*
1539  * This routine is called when various levels in the page table need to
1540  * be populated.  This routine cannot fail.
1541  *
1542  * We returned a page wired for the caller.  If we had to map the page into
1543  * a parent page table it will receive an additional wire_count.  For example,
1544  * an empty page table directory which is still mapped into its pdp will
1545  * retain a wire_count of 1.
1546  */
1547 static
1548 vm_page_t
1549 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex)
1550 {
1551         vm_page_t m;
1552
1553         /*
1554          * Find or fabricate a new pagetable page.  This will busy the page.
1555          */
1556         m = vm_page_grab(pmap->pm_pteobj, ptepindex,
1557                          VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
1558
1559         /*
1560          * The grab may have blocked and raced another thread populating
1561          * the same page table.  m->valid will be 0 on a newly allocated page
1562          * so use this to determine if we have to zero it out or not.  We
1563          * don't want to zero-out a raced page as this would desynchronize
1564          * the pv_entry's for the related pte's and cause pmap_remove_all()
1565          * to panic.
1566          *
1567          * Page table pages are unmanaged (do not use the normal PQ_s)
1568          */
1569         if (m->valid == 0) {
1570                 vm_page_unmanage(m);
1571                 if ((m->flags & PG_ZERO) == 0) {
1572                         pmap_zero_page(VM_PAGE_TO_PHYS(m));
1573                 }
1574 #ifdef PMAP_DEBUG
1575                 else {
1576                         pmap_page_assertzero(VM_PAGE_TO_PHYS(m));
1577                 }
1578 #endif
1579                 m->valid = VM_PAGE_BITS_ALL;
1580                 vm_page_flag_clear(m, PG_ZERO);
1581         }
1582 #ifdef PMAP_DEBUG
1583         else {
1584                 KKASSERT((m->flags & PG_ZERO) == 0);
1585         }
1586 #endif
1587
1588         KASSERT(m->queue == PQ_NONE,
1589                 ("_pmap_allocpte: %p->queue != PQ_NONE", m));
1590
1591         /*
1592          * Increment the wire_count for the page we will be returning to
1593          * the caller.
1594          */
1595         vm_page_wire(m);
1596
1597         /*
1598          * Map the pagetable page into the process address space, if
1599          * it isn't already there.
1600          *
1601          * It is possible that someone else got in and mapped the page
1602          * directory page while we were blocked, if so just unbusy and
1603          * return the held page.
1604          */
1605         if (ptepindex >= (NUPDE + NUPDPE)) {
1606                 /*
1607                  * Wire up a new PDP page in the PML4.
1608                  *
1609                  * (m) is busied so we cannot race another thread trying
1610                  * to map the PDP entry in the PML4.
1611                  */
1612                 vm_pindex_t pml4index;
1613                 pml4_entry_t *pml4;
1614
1615                 pml4index = ptepindex - (NUPDE + NUPDPE);
1616                 pml4 = &pmap->pm_pml4[pml4index];
1617                 if ((*pml4 & PG_V) == 0) {
1618                         *pml4 = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1619                                                       PG_A | PG_M);
1620                         ++pmap->pm_stats.resident_count;
1621                         vm_page_wire_quick(m);  /* wire for mapping */
1622                 }
1623                 /* return (m) wired for the caller */
1624         } else if (ptepindex >= NUPDE) {
1625                 /*
1626                  * Wire up a new PD page in the PDP
1627                  */
1628                 vm_pindex_t pml4index;
1629                 vm_pindex_t pdpindex;
1630                 vm_page_t pdppg;
1631                 pml4_entry_t *pml4;
1632                 pdp_entry_t *pdp;
1633
1634                 pdpindex = ptepindex - NUPDE;
1635                 pml4index = pdpindex >> NPML4EPGSHIFT;
1636
1637                 /*
1638                  * Once mapped the PDP is not unmapped during normal operation
1639                  * so we only need to handle races in the unmapped case.
1640                  *
1641                  * Mapping a PD into the PDP requires an additional wiring
1642                  * of the PDP.
1643                  */
1644                 pml4 = &pmap->pm_pml4[pml4index];
1645                 if ((*pml4 & PG_V) == 0) {
1646                         pdppg = _pmap_allocpte(pmap,
1647                                                NUPDE + NUPDPE + pml4index);
1648                         /* pdppg wired for the map and also wired for return */
1649                 } else {
1650                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1651                         vm_page_wire_quick(pdppg);
1652                 }
1653                 /* we have an extra ref on pdppg now for our use */
1654
1655                 /*
1656                  * Now find the PD entry in the PDP and map it.
1657                  *
1658                  * (m) is busied so we cannot race another thread trying
1659                  * to map the PD entry in the PDP.
1660                  *
1661                  * If the PD entry is already mapped we have to drop one
1662                  * wire count on the pdppg that we had bumped above.
1663                  */
1664                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1665                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1666
1667                 if ((*pdp & PG_V) == 0) {
1668                         *pdp = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1669                                                      PG_A | PG_M);
1670                         vm_page_wire_quick(m);  /* wire for mapping */
1671                         ++pmap->pm_stats.resident_count;
1672                         /* eat extra pdppg wiring for mapping */
1673                 } else {
1674                         if (vm_page_unwire_quick(pdppg))
1675                                 panic("pmap_allocpte: unwire case 1");
1676                 }
1677                 /* return (m) wired for the caller */
1678         } else {
1679                 /*
1680                  * Wire up the new PT page in the PD
1681                  */
1682                 vm_pindex_t pml4index;
1683                 vm_pindex_t pdpindex;
1684                 pml4_entry_t *pml4;
1685                 pdp_entry_t *pdp;
1686                 pd_entry_t *pd;
1687                 vm_page_t pdppg;
1688                 vm_page_t pdpg;
1689
1690                 pdpindex = ptepindex >> NPDPEPGSHIFT;
1691                 pml4index = pdpindex >> NPML4EPGSHIFT;
1692
1693                 /*
1694                  * Locate the PDP page in the PML4
1695                  *
1696                  * Once mapped the PDP is not unmapped during normal operation
1697                  * so we only need to handle races in the unmapped case.
1698                  */
1699                 pml4 = &pmap->pm_pml4[pml4index];
1700                 if ((*pml4 & PG_V) == 0) {
1701                         pdppg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1702                 } else {
1703                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1704                         vm_page_wire_quick(pdppg);
1705                 }
1706                 /* we have an extra ref on pdppg now for our use */
1707
1708                 /*
1709                  * Locate the PD page in the PDP
1710                  *
1711                  * Once mapped the PDP is not unmapped during normal operation
1712                  * so we only need to handle races in the unmapped case.
1713                  *
1714                  * We can scrap the extra reference on pdppg not needed if
1715                  * *pdp is already mapped and also not needed if it wasn't
1716                  * because the _pmap_allocpte() picked up the case for us.
1717                  */
1718                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1719                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1720
1721                 if ((*pdp & PG_V) == 0) {
1722                         pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1723                 } else {
1724                         pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
1725                         vm_page_wire_quick(pdpg);
1726                 }
1727                 vm_page_unwire_quick(pdppg);
1728                 /* we have an extra ref on pdpg now for our use */
1729
1730                 /*
1731                  * Locate the PT page in the PD.
1732                  *
1733                  * (m) is busied so we cannot race another thread trying
1734                  * to map the PT page in the PD.
1735                  */
1736                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
1737                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
1738                 if ((*pd & PG_V) == 0) {
1739                         *pd = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1740                                                     PG_A | PG_M);
1741                         ++pmap->pm_stats.resident_count;
1742                         vm_page_wire_quick(m);  /* wire for mapping */
1743                         /* eat extra pdpg wiring for mapping */
1744                 } else {
1745                         if (vm_page_unwire_quick(pdpg))
1746                                 panic("pmap_allocpte: unwire case 2");
1747                 }
1748                 /* return (m) wired for the caller */
1749         }
1750
1751         /*
1752          * We successfully loaded a PDP, PD, or PTE.  Set the page table hint,
1753          * valid bits, mapped flag, unbusy, and we're done.
1754          */
1755         pmap->pm_ptphint = m;
1756
1757 #if 0
1758         m->valid = VM_PAGE_BITS_ALL;
1759         vm_page_flag_clear(m, PG_ZERO);
1760 #endif
1761         vm_page_flag_set(m, PG_MAPPED);
1762         vm_page_wakeup(m);
1763
1764         return (m);
1765 }
1766
1767 static
1768 vm_page_t
1769 pmap_allocpte(pmap_t pmap, vm_offset_t va)
1770 {
1771         vm_pindex_t ptepindex;
1772         pd_entry_t *pd;
1773         vm_page_t m;
1774
1775         ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1776
1777         /*
1778          * Calculate pagetable page index
1779          */
1780         ptepindex = pmap_pde_pindex(va);
1781
1782         /*
1783          * Get the page directory entry
1784          */
1785         pd = pmap_pde(pmap, va);
1786
1787         /*
1788          * This supports switching from a 2MB page to a
1789          * normal 4K page.
1790          */
1791         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
1792                 panic("no promotion/demotion yet");
1793                 *pd = 0;
1794                 pd = NULL;
1795                 cpu_invltlb();
1796                 smp_invltlb();
1797         }
1798
1799         /*
1800          * If the page table page is mapped, we just increment the
1801          * wire count, and activate it.
1802          */
1803         if (pd != NULL && (*pd & PG_V) != 0) {
1804                 m = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1805                 pmap->pm_ptphint = m;
1806                 vm_page_wire_quick(m);
1807                 vm_page_wakeup(m);
1808                 return m;
1809         }
1810         /*
1811          * Here if the pte page isn't mapped, or if it has been deallocated.
1812          */
1813         return _pmap_allocpte(pmap, ptepindex);
1814 }
1815
1816
1817 /***************************************************
1818  * Pmap allocation/deallocation routines.
1819  ***************************************************/
1820
1821 /*
1822  * Release any resources held by the given physical map.
1823  * Called when a pmap initialized by pmap_pinit is being released.
1824  * Should only be called if the map contains no valid mappings.
1825  *
1826  * Caller must hold pmap->pm_token
1827  */
1828 static int pmap_release_callback(struct vm_page *p, void *data);
1829
1830 static __inline
1831 void
1832 pmap_auto_yield(struct rb_vm_page_scan_info *info)
1833 {
1834         if (++info->desired >= pmap_yield_count) {
1835                 info->desired = 0;
1836                 lwkt_yield();
1837         }
1838 }
1839
1840 void
1841 pmap_release(struct pmap *pmap)
1842 {
1843         vm_object_t object = pmap->pm_pteobj;
1844         struct rb_vm_page_scan_info info;
1845
1846         KASSERT(pmap->pm_active == 0,
1847                 ("pmap still active! %016jx", (uintmax_t)pmap->pm_active));
1848 #if defined(DIAGNOSTIC)
1849         if (object->ref_count != 1)
1850                 panic("pmap_release: pteobj reference count != 1");
1851 #endif
1852         
1853         info.pmap = pmap;
1854         info.object = object;
1855
1856         spin_lock(&pmap_spin);
1857         TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
1858         spin_unlock(&pmap_spin);
1859
1860         info.desired = 0;
1861         vm_object_hold(object);
1862         do {
1863                 info.error = 0;
1864                 info.mpte = NULL;
1865                 info.limit = object->generation;
1866
1867                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL, 
1868                                         pmap_release_callback, &info);
1869                 if (info.error == 0 && info.mpte) {
1870                         if (!pmap_release_free_page(pmap, info.mpte))
1871                                 info.error = 1;
1872                 }
1873         } while (info.error);
1874         vm_object_drop(object);
1875
1876         while (pmap->pm_hold)
1877                 tsleep(pmap, 0, "pmapx", 1);
1878 }
1879
1880 static
1881 int
1882 pmap_release_callback(struct vm_page *p, void *data)
1883 {
1884         struct rb_vm_page_scan_info *info = data;
1885
1886         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1887                 info->mpte = p;
1888                 return(0);
1889         }
1890         if (!pmap_release_free_page(info->pmap, p)) {
1891                 info->error = 1;
1892                 pmap_auto_yield(info);
1893                 return(-1);
1894         }
1895         if (info->object->generation != info->limit) {
1896                 info->error = 1;
1897                 pmap_auto_yield(info);
1898                 return(-1);
1899         }
1900         return(0);
1901 }
1902
1903 /*
1904  * Grow the number of kernel page table entries, if needed.
1905  *
1906  * This routine is always called to validate any address space
1907  * beyond KERNBASE (for kldloads).  kernel_vm_end only governs the address
1908  * space below KERNBASE.
1909  */
1910 void
1911 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
1912 {
1913         vm_paddr_t paddr;
1914         vm_offset_t ptppaddr;
1915         vm_page_t nkpg;
1916         pd_entry_t *pde, newpdir;
1917         pdp_entry_t newpdp;
1918         int update_kernel_vm_end;
1919
1920         vm_object_hold(kptobj);
1921
1922         /*
1923          * bootstrap kernel_vm_end on first real VM use
1924          */
1925         if (kernel_vm_end == 0) {
1926                 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
1927                 nkpt = 0;
1928                 while ((*pmap_pde(&kernel_pmap, kernel_vm_end) & PG_V) != 0) {
1929                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
1930                                         ~(PAGE_SIZE * NPTEPG - 1);
1931                         nkpt++;
1932                         if (kernel_vm_end - 1 >= kernel_map.max_offset) {
1933                                 kernel_vm_end = kernel_map.max_offset;
1934                                 break;                       
1935                         }
1936                 }
1937         }
1938
1939         /*
1940          * Fill in the gaps.  kernel_vm_end is only adjusted for ranges
1941          * below KERNBASE.  Ranges above KERNBASE are kldloaded and we
1942          * do not want to force-fill 128G worth of page tables.
1943          */
1944         if (kstart < KERNBASE) {
1945                 if (kstart > kernel_vm_end)
1946                         kstart = kernel_vm_end;
1947                 KKASSERT(kend <= KERNBASE);
1948                 update_kernel_vm_end = 1;
1949         } else {
1950                 update_kernel_vm_end = 0;
1951         }
1952
1953         kstart = rounddown2(kstart, PAGE_SIZE * NPTEPG);
1954         kend = roundup2(kend, PAGE_SIZE * NPTEPG);
1955
1956         if (kend - 1 >= kernel_map.max_offset)
1957                 kend = kernel_map.max_offset;
1958
1959         while (kstart < kend) {
1960                 pde = pmap_pde(&kernel_pmap, kstart);
1961                 if (pde == NULL) {
1962                         /* We need a new PDP entry */
1963                         nkpg = vm_page_alloc(kptobj, nkpt,
1964                                              VM_ALLOC_NORMAL |
1965                                              VM_ALLOC_SYSTEM |
1966                                              VM_ALLOC_INTERRUPT);
1967                         if (nkpg == NULL) {
1968                                 panic("pmap_growkernel: no memory to grow "
1969                                       "kernel");
1970                         }
1971                         paddr = VM_PAGE_TO_PHYS(nkpg);
1972                         if ((nkpg->flags & PG_ZERO) == 0)
1973                                 pmap_zero_page(paddr);
1974                         vm_page_flag_clear(nkpg, PG_ZERO);
1975                         newpdp = (pdp_entry_t)
1976                                 (paddr | PG_V | PG_RW | PG_A | PG_M);
1977                         *pmap_pdpe(&kernel_pmap, kstart) = newpdp;
1978                         nkpt++;
1979                         continue; /* try again */
1980                 }
1981                 if ((*pde & PG_V) != 0) {
1982                         kstart = (kstart + PAGE_SIZE * NPTEPG) &
1983                                  ~(PAGE_SIZE * NPTEPG - 1);
1984                         if (kstart - 1 >= kernel_map.max_offset) {
1985                                 kstart = kernel_map.max_offset;
1986                                 break;                       
1987                         }
1988                         continue;
1989                 }
1990
1991                 /*
1992                  * This index is bogus, but out of the way
1993                  */
1994                 nkpg = vm_page_alloc(kptobj, nkpt,
1995                                      VM_ALLOC_NORMAL |
1996                                      VM_ALLOC_SYSTEM |
1997                                      VM_ALLOC_INTERRUPT);
1998                 if (nkpg == NULL)
1999                         panic("pmap_growkernel: no memory to grow kernel");
2000
2001                 vm_page_wire(nkpg);
2002                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
2003                 pmap_zero_page(ptppaddr);
2004                 vm_page_flag_clear(nkpg, PG_ZERO);
2005                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
2006                 *pmap_pde(&kernel_pmap, kstart) = newpdir;
2007                 nkpt++;
2008
2009                 kstart = (kstart + PAGE_SIZE * NPTEPG) &
2010                           ~(PAGE_SIZE * NPTEPG - 1);
2011
2012                 if (kstart - 1 >= kernel_map.max_offset) {
2013                         kstart = kernel_map.max_offset;
2014                         break;                       
2015                 }
2016         }
2017
2018         /*
2019          * Only update kernel_vm_end for areas below KERNBASE.
2020          */
2021         if (update_kernel_vm_end && kernel_vm_end < kstart)
2022                 kernel_vm_end = kstart;
2023
2024         vm_object_drop(kptobj);
2025 }
2026
2027 /*
2028  *      Retire the given physical map from service.
2029  *      Should only be called if the map contains
2030  *      no valid mappings.
2031  */
2032 void
2033 pmap_destroy(pmap_t pmap)
2034 {
2035         int count;
2036
2037         if (pmap == NULL)
2038                 return;
2039
2040         lwkt_gettoken(&pmap->pm_token);
2041         count = --pmap->pm_count;
2042         if (count == 0) {
2043                 pmap_release(pmap);     /* eats pm_token */
2044                 panic("destroying a pmap is not yet implemented");
2045         }
2046         lwkt_reltoken(&pmap->pm_token);
2047 }
2048
2049 /*
2050  *      Add a reference to the specified pmap.
2051  */
2052 void
2053 pmap_reference(pmap_t pmap)
2054 {
2055         if (pmap != NULL) {
2056                 lwkt_gettoken(&pmap->pm_token);
2057                 pmap->pm_count++;
2058                 lwkt_reltoken(&pmap->pm_token);
2059         }
2060 }
2061
2062 /***************************************************
2063 * page management routines.
2064  ***************************************************/
2065
2066 /*
2067  * free the pv_entry back to the free list.  This function may be
2068  * called from an interrupt.
2069  */
2070 static __inline
2071 void
2072 free_pv_entry(pv_entry_t pv)
2073 {
2074         atomic_add_int(&pv_entry_count, -1);
2075         KKASSERT(pv_entry_count >= 0);
2076         zfree(pvzone, pv);
2077 }
2078
2079 /*
2080  * get a new pv_entry, allocating a block from the system
2081  * when needed.  This function may be called from an interrupt.
2082  */
2083 static
2084 pv_entry_t
2085 get_pv_entry(void)
2086 {
2087         atomic_add_int(&pv_entry_count, 1);
2088         if (pv_entry_high_water &&
2089                 (pv_entry_count > pv_entry_high_water) &&
2090                 (pmap_pagedaemon_waken == 0)) {
2091                 pmap_pagedaemon_waken = 1;
2092                 wakeup(&vm_pages_needed);
2093         }
2094         return zalloc(pvzone);
2095 }
2096
2097 /*
2098  * This routine is very drastic, but can save the system
2099  * in a pinch.
2100  */
2101 void
2102 pmap_collect(void)
2103 {
2104         int i;
2105         vm_page_t m;
2106         static int warningdone=0;
2107
2108         if (pmap_pagedaemon_waken == 0)
2109                 return;
2110         pmap_pagedaemon_waken = 0;
2111         if (warningdone < 5) {
2112                 kprintf("pmap_collect: collecting pv entries -- suggest increasing PMAP_SHPGPERPROC\n");
2113                 warningdone++;
2114         }
2115
2116         for (i = 0; i < vm_page_array_size; i++) {
2117                 m = &vm_page_array[i];
2118                 if (m->wire_count || m->hold_count)
2119                         continue;
2120                 if (vm_page_busy_try(m, TRUE) == 0) {
2121                         if (m->wire_count == 0 && m->hold_count == 0) {
2122                                 pmap_remove_all(m);
2123                         }
2124                         vm_page_wakeup(m);
2125                 }
2126         }
2127 }
2128         
2129
2130 /*
2131  * If it is the first entry on the list, it is actually in the header and
2132  * we must copy the following entry up to the header.
2133  *
2134  * Otherwise we must search the list for the entry.  In either case we
2135  * free the now unused entry.
2136  *
2137  * Caller must hold pmap->pm_token
2138  */
2139 static
2140 int
2141 pmap_remove_entry(struct pmap *pmap, vm_page_t m, 
2142                   vm_offset_t va, pmap_inval_info_t info)
2143 {
2144         pv_entry_t pv;
2145         int rtval;
2146
2147         spin_lock(&pmap_spin);
2148         if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
2149                 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2150                         if (pmap == pv->pv_pmap && va == pv->pv_va) 
2151                                 break;
2152                 }
2153         } else {
2154                 TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
2155                         if (va == pv->pv_va) 
2156                                 break;
2157                 }
2158         }
2159
2160         rtval = 0;
2161         KKASSERT(pv);
2162
2163         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2164         m->md.pv_generation++;
2165         m->md.pv_list_count--;
2166         vm_page_spin_lock(m);
2167         if (m->object)
2168                 atomic_add_int(&m->object->agg_pv_list_count, -1);
2169         vm_page_spin_unlock(m);
2170         KKASSERT(m->md.pv_list_count >= 0);
2171         if (TAILQ_EMPTY(&m->md.pv_list))
2172                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2173         TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2174         ++pmap->pm_generation;
2175         spin_unlock(&pmap_spin);
2176
2177         rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem, info);
2178         free_pv_entry(pv);
2179
2180         return rtval;
2181 }
2182
2183 /*
2184  * Create a pv entry for page at pa for (pmap, va).
2185  *
2186  * Caller must hold pmap token
2187  */
2188 static
2189 void
2190 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
2191 {
2192         pv_entry_t pv;
2193
2194         pv = get_pv_entry();
2195         pv->pv_va = va;
2196         pv->pv_pmap = pmap;
2197         pv->pv_ptem = mpte;
2198
2199         spin_lock(&pmap_spin);
2200         TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
2201         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2202         m->md.pv_generation++;
2203         m->md.pv_list_count++;
2204         vm_page_spin_lock(m);
2205         if (m->object)
2206                 atomic_add_int(&m->object->agg_pv_list_count, 1);
2207         vm_page_spin_unlock(m);
2208         pmap->pm_generation++;
2209         spin_unlock(&pmap_spin);
2210 }
2211
2212 /*
2213  * pmap_remove_pte: do the things to unmap a page in a process
2214  *
2215  * Caller must hold pmap token
2216  */
2217 static
2218 int
2219 pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va,
2220                 pmap_inval_info_t info)
2221 {
2222         pt_entry_t oldpte;
2223         vm_page_t m;
2224
2225         ASSERT_LWKT_TOKEN_HELD(&pmap->pm_token);
2226
2227         pmap_inval_interlock(info, pmap, va);
2228         oldpte = pte_load_clear(ptq);
2229         pmap_inval_deinterlock(info, pmap);
2230         if (oldpte & PG_W)
2231                 pmap->pm_stats.wired_count -= 1;
2232         /*
2233          * Machines that don't support invlpg, also don't support
2234          * PG_G.  XXX PG_G is disabled for SMP so don't worry about
2235          * the SMP case.
2236          */
2237         if (oldpte & PG_G)
2238                 cpu_invlpg((void *)va);
2239         KKASSERT(pmap->pm_stats.resident_count > 0);
2240         --pmap->pm_stats.resident_count;
2241         if (oldpte & PG_MANAGED) {
2242                 m = PHYS_TO_VM_PAGE(oldpte);
2243                 if (oldpte & PG_M) {
2244 #if defined(PMAP_DIAGNOSTIC)
2245                         if (pmap_nw_modified((pt_entry_t) oldpte)) {
2246                                 kprintf(
2247         "pmap_remove: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2248                                     va, oldpte);
2249                         }
2250 #endif
2251                         if (pmap_track_modified(va))
2252                                 vm_page_dirty(m);
2253                 }
2254                 if (oldpte & PG_A)
2255                         vm_page_flag_set(m, PG_REFERENCED);
2256                 return pmap_remove_entry(pmap, m, va, info);
2257         }
2258 /*
2259         else {
2260                 return pmap_unuse_pt(pmap, va, NULL, info);
2261         }
2262 */
2263
2264         return 0;
2265 }
2266
2267 /*
2268  * Remove a single page from a process address space.
2269  *
2270  * This function may not be called from an interrupt if the pmap is
2271  * not kernel_pmap.
2272  *
2273  * Caller must hold pmap->pm_token
2274  */
2275 static
2276 void
2277 pmap_remove_page(struct pmap *pmap, vm_offset_t va, pmap_inval_info_t info)
2278 {
2279         pt_entry_t *pte;
2280
2281         ASSERT_LWKT_TOKEN_HELD(&pmap->pm_token);
2282
2283         pte = pmap_pte(pmap, va);
2284         if (pte == NULL)
2285                 return;
2286         if ((*pte & PG_V) == 0)
2287                 return;
2288         pmap_remove_pte(pmap, pte, va, info);
2289 }
2290
2291 /*
2292  * Remove the given range of addresses from the specified map.
2293  *
2294  * It is assumed that the start and end are properly rounded to the page size.
2295  *
2296  * This function may not be called from an interrupt if the pmap is not
2297  * kernel_pmap.
2298  */
2299 void
2300 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
2301 {
2302         vm_offset_t va_next;
2303         pml4_entry_t *pml4e;
2304         pdp_entry_t *pdpe;
2305         pd_entry_t ptpaddr, *pde;
2306         pt_entry_t *pte;
2307         struct pmap_inval_info info;
2308
2309         if (pmap == NULL)
2310                 return;
2311
2312         vm_object_hold(pmap->pm_pteobj);
2313         lwkt_gettoken(&pmap->pm_token);
2314         if (pmap->pm_stats.resident_count == 0) {
2315                 lwkt_reltoken(&pmap->pm_token);
2316                 vm_object_drop(pmap->pm_pteobj);
2317                 return;
2318         }
2319
2320         pmap_inval_init(&info);
2321
2322         /*
2323          * special handling of removing one page.  a very
2324          * common operation and easy to short circuit some
2325          * code.
2326          */
2327         if (sva + PAGE_SIZE == eva) {
2328                 pde = pmap_pde(pmap, sva);
2329                 if (pde && (*pde & PG_PS) == 0) {
2330                         pmap_remove_page(pmap, sva, &info);
2331                         pmap_inval_done(&info);
2332                         lwkt_reltoken(&pmap->pm_token);
2333                         vm_object_drop(pmap->pm_pteobj);
2334                         return;
2335                 }
2336         }
2337
2338         for (; sva < eva; sva = va_next) {
2339                 pml4e = pmap_pml4e(pmap, sva);
2340                 if ((*pml4e & PG_V) == 0) {
2341                         va_next = (sva + NBPML4) & ~PML4MASK;
2342                         if (va_next < sva)
2343                                 va_next = eva;
2344                         continue;
2345                 }
2346
2347                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2348                 if ((*pdpe & PG_V) == 0) {
2349                         va_next = (sva + NBPDP) & ~PDPMASK;
2350                         if (va_next < sva)
2351                                 va_next = eva;
2352                         continue;
2353                 }
2354
2355                 /*
2356                  * Calculate index for next page table.
2357                  */
2358                 va_next = (sva + NBPDR) & ~PDRMASK;
2359                 if (va_next < sva)
2360                         va_next = eva;
2361
2362                 pde = pmap_pdpe_to_pde(pdpe, sva);
2363                 ptpaddr = *pde;
2364
2365                 /*
2366                  * Weed out invalid mappings.
2367                  */
2368                 if (ptpaddr == 0)
2369                         continue;
2370
2371                 /*
2372                  * Check for large page.
2373                  */
2374                 if ((ptpaddr & PG_PS) != 0) {
2375                         /* JG FreeBSD has more complex treatment here */
2376                         pmap_inval_interlock(&info, pmap, -1);
2377                         *pde = 0;
2378                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2379                         pmap_inval_deinterlock(&info, pmap);
2380                         continue;
2381                 }
2382
2383                 /*
2384                  * Limit our scan to either the end of the va represented
2385                  * by the current page table page, or to the end of the
2386                  * range being removed.
2387                  */
2388                 if (va_next > eva)
2389                         va_next = eva;
2390
2391                 /*
2392                  * NOTE: pmap_remove_pte() can block.
2393                  */
2394                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2395                     sva += PAGE_SIZE) {
2396                         if (*pte == 0)
2397                                 continue;
2398                         if (pmap_remove_pte(pmap, pte, sva, &info))
2399                                 break;
2400                 }
2401         }
2402         pmap_inval_done(&info);
2403         lwkt_reltoken(&pmap->pm_token);
2404         vm_object_drop(pmap->pm_pteobj);
2405 }
2406
2407 /*
2408  * Removes this physical page from all physical maps in which it resides.
2409  * Reflects back modify bits to the pager.
2410  *
2411  * This routine may not be called from an interrupt.
2412  */
2413 static
2414 void
2415 pmap_remove_all(vm_page_t m)
2416 {
2417         struct pmap_inval_info info;
2418         pt_entry_t *pte, tpte;
2419         pv_entry_t pv;
2420         struct pmap *pmap;
2421
2422         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2423                 return;
2424
2425         pmap_inval_init(&info);
2426         spin_lock(&pmap_spin);
2427         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2428                 /*
2429                  * We have to be holding the pmap token to interlock
2430                  * the pte destruction and pv removal.  XXX need hold on
2431                  * pmap.
2432                  */
2433                 pmap = pv->pv_pmap;
2434                 spin_unlock(&pmap_spin);
2435                 lwkt_gettoken(&pmap->pm_token); /* XXX hold race */
2436                 spin_lock(&pmap_spin);
2437                 if (pv != TAILQ_FIRST(&m->md.pv_list)) {
2438                         spin_unlock(&pmap_spin);
2439                         lwkt_reltoken(&pmap->pm_token);
2440                         spin_lock(&pmap_spin);
2441                         continue;
2442                 }
2443
2444                 /*
2445                  * Remove the pv
2446                  */
2447                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2448                 TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2449                 m->md.pv_generation++;
2450                 m->md.pv_list_count--;
2451                 vm_page_spin_lock(m);
2452                 if (m->object)
2453                         atomic_add_int(&m->object->agg_pv_list_count, -1);
2454                 vm_page_spin_unlock(m);
2455                 KKASSERT(m->md.pv_list_count >= 0);
2456                 ++pv->pv_pmap->pm_generation;
2457                 spin_unlock(&pmap_spin);
2458
2459                 /*
2460                  * pv is now isolated
2461                  */
2462                 KKASSERT(pv->pv_pmap->pm_stats.resident_count > 0);
2463                 --pv->pv_pmap->pm_stats.resident_count;
2464
2465                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2466                 pmap_inval_interlock(&info, pv->pv_pmap, pv->pv_va);
2467                 tpte = pte_load_clear(pte);
2468                 KKASSERT(tpte & PG_MANAGED);
2469                 if (tpte & PG_W)
2470                         pv->pv_pmap->pm_stats.wired_count--;
2471                 pmap_inval_deinterlock(&info, pv->pv_pmap);
2472                 if (tpte & PG_A)
2473                         vm_page_flag_set(m, PG_REFERENCED);
2474
2475                 /*
2476                  * Update the vm_page_t clean and reference bits.
2477                  */
2478                 if (tpte & PG_M) {
2479 #if defined(PMAP_DIAGNOSTIC)
2480                         if (pmap_nw_modified(tpte)) {
2481                                 kprintf("pmap_remove_all: modified page not "
2482                                         "writable: va: 0x%lx, pte: 0x%lx\n",
2483                                         pv->pv_va, tpte);
2484                         }
2485 #endif
2486                         if (pmap_track_modified(pv->pv_va))
2487                                 vm_page_dirty(m); /* XXX races(m) */
2488                 }
2489
2490                 spin_lock(&pmap_spin);
2491                 if (TAILQ_EMPTY(&m->md.pv_list))
2492                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2493                 spin_unlock(&pmap_spin);
2494
2495                 pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem, &info);
2496                 lwkt_reltoken(&pv->pv_pmap->pm_token);
2497
2498                 free_pv_entry(pv);
2499                 spin_lock(&pmap_spin);
2500         }
2501         spin_unlock(&pmap_spin);
2502         KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
2503         pmap_inval_done(&info);
2504 }
2505
2506 /*
2507  * pmap_protect:
2508  *
2509  *      Set the physical protection on the specified range of this map
2510  *      as requested.
2511  *
2512  *      This function may not be called from an interrupt if the map is
2513  *      not the kernel_pmap.
2514  */
2515 void
2516 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2517 {
2518         vm_offset_t va_next;
2519         pml4_entry_t *pml4e;
2520         pdp_entry_t *pdpe;
2521         pd_entry_t ptpaddr, *pde;
2522         pt_entry_t *pte;
2523         pmap_inval_info info;
2524
2525         /* JG review for NX */
2526
2527         if (pmap == NULL)
2528                 return;
2529
2530         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2531                 pmap_remove(pmap, sva, eva);
2532                 return;
2533         }
2534
2535         if (prot & VM_PROT_WRITE)
2536                 return;
2537
2538         lwkt_gettoken(&pmap->pm_token);
2539         pmap_inval_init(&info);
2540
2541         for (; sva < eva; sva = va_next) {
2542                 pml4e = pmap_pml4e(pmap, sva);
2543                 if ((*pml4e & PG_V) == 0) {
2544                         va_next = (sva + NBPML4) & ~PML4MASK;
2545                         if (va_next < sva)
2546                                 va_next = eva;
2547                         continue;
2548                 }
2549
2550                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2551                 if ((*pdpe & PG_V) == 0) {
2552                         va_next = (sva + NBPDP) & ~PDPMASK;
2553                         if (va_next < sva)
2554                                 va_next = eva;
2555                         continue;
2556                 }
2557
2558                 va_next = (sva + NBPDR) & ~PDRMASK;
2559                 if (va_next < sva)
2560                         va_next = eva;
2561
2562                 pde = pmap_pdpe_to_pde(pdpe, sva);
2563                 ptpaddr = *pde;
2564
2565                 /*
2566                  * Check for large page.
2567                  */
2568                 if ((ptpaddr & PG_PS) != 0) {
2569                         pmap_inval_interlock(&info, pmap, -1);
2570                         *pde &= ~(PG_M|PG_RW);
2571                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2572                         pmap_inval_deinterlock(&info, pmap);
2573                         continue;
2574                 }
2575
2576                 /*
2577                  * Weed out invalid mappings. Note: we assume that the page
2578                  * directory table is always allocated, and in kernel virtual.
2579                  */
2580                 if (ptpaddr == 0)
2581                         continue;
2582
2583                 if (va_next > eva)
2584                         va_next = eva;
2585
2586                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2587                      sva += PAGE_SIZE) {
2588                         pt_entry_t pbits;
2589                         pt_entry_t cbits;
2590                         vm_page_t m;
2591
2592                         /*
2593                          * XXX non-optimal.
2594                          */
2595                         pmap_inval_interlock(&info, pmap, sva);
2596 again:
2597                         pbits = *pte;
2598                         cbits = pbits;
2599                         if ((pbits & PG_V) == 0) {
2600                                 pmap_inval_deinterlock(&info, pmap);
2601                                 continue;
2602                         }
2603                         if (pbits & PG_MANAGED) {
2604                                 m = NULL;
2605                                 if (pbits & PG_A) {
2606                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2607                                         vm_page_flag_set(m, PG_REFERENCED);
2608                                         cbits &= ~PG_A;
2609                                 }
2610                                 if (pbits & PG_M) {
2611                                         if (pmap_track_modified(sva)) {
2612                                                 if (m == NULL)
2613                                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2614                                                 vm_page_dirty(m);
2615                                                 cbits &= ~PG_M;
2616                                         }
2617                                 }
2618                         }
2619                         cbits &= ~PG_RW;
2620                         if (pbits != cbits &&
2621                             !atomic_cmpset_long(pte, pbits, cbits)) {
2622                                 goto again;
2623                         }
2624                         pmap_inval_deinterlock(&info, pmap);
2625                 }
2626         }
2627         pmap_inval_done(&info);
2628         lwkt_reltoken(&pmap->pm_token);
2629 }
2630
2631 /*
2632  *      Insert the given physical page (p) at
2633  *      the specified virtual address (v) in the
2634  *      target physical map with the protection requested.
2635  *
2636  *      If specified, the page will be wired down, meaning
2637  *      that the related pte can not be reclaimed.
2638  *
2639  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2640  *      or lose information.  That is, this routine must actually
2641  *      insert this page into the given map NOW.
2642  */
2643 void
2644 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2645            boolean_t wired)
2646 {
2647         vm_paddr_t pa;
2648         pd_entry_t *pde;
2649         pt_entry_t *pte;
2650         vm_paddr_t opa;
2651         pt_entry_t origpte, newpte;
2652         vm_page_t mpte;
2653         pmap_inval_info info;
2654
2655         if (pmap == NULL)
2656                 return;
2657
2658         va = trunc_page(va);
2659 #ifdef PMAP_DIAGNOSTIC
2660         if (va >= KvaEnd)
2661                 panic("pmap_enter: toobig");
2662         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
2663                 panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)", va);
2664 #endif
2665         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2666                 kprintf("Warning: pmap_enter called on UVA with kernel_pmap\n");
2667 #ifdef DDB
2668                 db_print_backtrace();
2669 #endif
2670         }
2671         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2672                 kprintf("Warning: pmap_enter called on KVA without kernel_pmap\n");
2673 #ifdef DDB
2674                 db_print_backtrace();
2675 #endif
2676         }
2677
2678         vm_object_hold(pmap->pm_pteobj);
2679         lwkt_gettoken(&pmap->pm_token);
2680
2681         /*
2682          * In the case that a page table page is not
2683          * resident, we are creating it here.
2684          */
2685         if (va < VM_MAX_USER_ADDRESS)
2686                 mpte = pmap_allocpte(pmap, va);
2687         else
2688                 mpte = NULL;
2689
2690         if ((prot & VM_PROT_NOSYNC) == 0)
2691                 pmap_inval_init(&info);
2692         pde = pmap_pde(pmap, va);
2693         if (pde != NULL && (*pde & PG_V) != 0) {
2694                 if ((*pde & PG_PS) != 0)
2695                         panic("pmap_enter: attempted pmap_enter on 2MB page");
2696                 pte = pmap_pde_to_pte(pde, va);
2697         } else {
2698                 panic("pmap_enter: invalid page directory va=%#lx", va);
2699         }
2700
2701         KKASSERT(pte != NULL);
2702         pa = VM_PAGE_TO_PHYS(m);
2703         origpte = *pte;
2704         opa = origpte & PG_FRAME;
2705
2706         /*
2707          * Mapping has not changed, must be protection or wiring change.
2708          */
2709         if (origpte && (opa == pa)) {
2710                 /*
2711                  * Wiring change, just update stats. We don't worry about
2712                  * wiring PT pages as they remain resident as long as there
2713                  * are valid mappings in them. Hence, if a user page is wired,
2714                  * the PT page will be also.
2715                  */
2716                 if (wired && ((origpte & PG_W) == 0))
2717                         pmap->pm_stats.wired_count++;
2718                 else if (!wired && (origpte & PG_W))
2719                         pmap->pm_stats.wired_count--;
2720
2721 #if defined(PMAP_DIAGNOSTIC)
2722                 if (pmap_nw_modified(origpte)) {
2723                         kprintf(
2724         "pmap_enter: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2725                             va, origpte);
2726                 }
2727 #endif
2728
2729                 /*
2730                  * Remove the extra pte reference.  Note that we cannot
2731                  * optimize the RO->RW case because we have adjusted the
2732                  * wiring count above and may need to adjust the wiring
2733                  * bits below.
2734                  */
2735                 if (mpte)
2736                         vm_page_unwire_quick(mpte);
2737
2738                 /*
2739                  * We might be turning off write access to the page,
2740                  * so we go ahead and sense modify status.
2741                  */
2742                 if (origpte & PG_MANAGED) {
2743                         if ((origpte & PG_M) && pmap_track_modified(va)) {
2744                                 vm_page_t om;
2745                                 om = PHYS_TO_VM_PAGE(opa);
2746                                 vm_page_dirty(om);
2747                         }
2748                         pa |= PG_MANAGED;
2749                         KKASSERT(m->flags & PG_MAPPED);
2750                 }
2751                 goto validate;
2752         } 
2753         /*
2754          * Mapping has changed, invalidate old range and fall through to
2755          * handle validating new mapping.
2756          */
2757         while (opa) {
2758                 int err;
2759                 err = pmap_remove_pte(pmap, pte, va, &info);
2760                 if (err)
2761                         panic("pmap_enter: pte vanished, va: 0x%lx", va);
2762                 origpte = *pte;
2763                 opa = origpte & PG_FRAME;
2764                 if (opa) {
2765                         kprintf("pmap_enter: Warning, raced pmap %p va %p\n",
2766                                 pmap, (void *)va);
2767                 }
2768         }
2769
2770         /*
2771          * Enter on the PV list if part of our managed memory. Note that we
2772          * raise IPL while manipulating pv_table since pmap_enter can be
2773          * called at interrupt time.
2774          *
2775          * The new mapping covers mpte's new wiring count so we don't
2776          * unwire it.
2777          */
2778         if (pmap_initialized && 
2779             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2780                 pmap_insert_entry(pmap, va, mpte, m);
2781                 pa |= PG_MANAGED;
2782                 vm_page_flag_set(m, PG_MAPPED);
2783         }
2784
2785         /*
2786          * Increment counters
2787          */
2788         ++pmap->pm_stats.resident_count;
2789         if (wired)
2790                 pmap->pm_stats.wired_count++;
2791
2792 validate:
2793         /*
2794          * Now validate mapping with desired protection/wiring.
2795          */
2796         newpte = (pt_entry_t) (pa | pte_prot(pmap, prot) | PG_V);
2797
2798         if (wired)
2799                 newpte |= PG_W;
2800         if (va < VM_MAX_USER_ADDRESS)
2801                 newpte |= PG_U;
2802         if (pmap == &kernel_pmap)
2803                 newpte |= pgeflag;
2804
2805         /*
2806          * if the mapping or permission bits are different, we need
2807          * to update the pte.
2808          */
2809         if ((origpte & ~(PG_M|PG_A)) != newpte) {
2810                 if ((prot & VM_PROT_NOSYNC) == 0)
2811                         pmap_inval_interlock(&info, pmap, va);
2812                 *pte = newpte | PG_A;
2813                 if (prot & VM_PROT_NOSYNC)
2814                         cpu_invlpg((void *)va);
2815                 else
2816                         pmap_inval_deinterlock(&info, pmap);
2817                 if (newpte & PG_RW)
2818                         vm_page_flag_set(m, PG_WRITEABLE);
2819         }
2820         KKASSERT((newpte & PG_MANAGED) == 0 || (m->flags & PG_MAPPED));
2821         if ((prot & VM_PROT_NOSYNC) == 0)
2822                 pmap_inval_done(&info);
2823         lwkt_reltoken(&pmap->pm_token);
2824         vm_object_drop(pmap->pm_pteobj);
2825 }
2826
2827 /*
2828  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
2829  * This code also assumes that the pmap has no pre-existing entry for this
2830  * VA.
2831  *
2832  * This code currently may only be used on user pmaps, not kernel_pmap.
2833  */
2834 void
2835 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
2836 {
2837         pt_entry_t *pte;
2838         vm_paddr_t pa;
2839         vm_page_t mpte;
2840         pmap_inval_info info;
2841
2842         lwkt_gettoken(&pmap->pm_token);
2843         vm_object_hold(pmap->pm_pteobj);
2844         pmap_inval_init(&info);
2845
2846         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2847                 kprintf("Warning: pmap_enter_quick called on UVA with"
2848                         "kernel_pmap\n");
2849 #ifdef DDB
2850                 db_print_backtrace();
2851 #endif
2852         }
2853         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2854                 kprintf("Warning: pmap_enter_quick called on KVA without"
2855                         "kernel_pmap\n");
2856 #ifdef DDB
2857                 db_print_backtrace();
2858 #endif
2859         }
2860
2861         KKASSERT(va < UPT_MIN_ADDRESS); /* assert used on user pmaps only */
2862
2863         /*
2864          * Calculate the page table page (mpte), allocating it if necessary.
2865          *
2866          * A wired page table page (mpte), or NULL, is passed onto the
2867          * section following.
2868          */
2869         if (va < VM_MAX_USER_ADDRESS) {
2870                 mpte = pmap_allocpte(pmap, va);
2871         } else {
2872                 mpte = NULL;
2873                 /* this code path is not yet used */
2874         }
2875
2876         /*
2877          * With a valid (and held) page directory page, we can just use
2878          * vtopte() to get to the pte.  If the pte is already present
2879          * we do not disturb it.
2880          */
2881         pte = vtopte(va);
2882         if (*pte & PG_V) {
2883                 pa = VM_PAGE_TO_PHYS(m);
2884                 KKASSERT(((*pte ^ pa) & PG_FRAME) == 0);
2885                 pmap_inval_done(&info);
2886                 if (mpte)
2887                         pmap_unwire_pte_hold(pmap, va, mpte, &info);
2888                 vm_object_drop(pmap->pm_pteobj);
2889                 lwkt_reltoken(&pmap->pm_token);
2890                 return;
2891         }
2892
2893         /*
2894          * Enter on the PV list if part of our managed memory.
2895          *
2896          * The new mapping covers mpte's new wiring count so we don't
2897          * unwire it.
2898          */
2899         if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2900                 pmap_insert_entry(pmap, va, mpte, m);
2901                 vm_page_flag_set(m, PG_MAPPED);
2902         }
2903
2904         /*
2905          * Increment counters
2906          */
2907         ++pmap->pm_stats.resident_count;
2908
2909         pa = VM_PAGE_TO_PHYS(m);
2910
2911         /*
2912          * Now validate mapping with RO protection
2913          */
2914         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2915                 *pte = pa | PG_V | PG_U;
2916         else
2917                 *pte = pa | PG_V | PG_U | PG_MANAGED;
2918 /*      pmap_inval_add(&info, pmap, va); shouldn't be needed inval->valid */
2919         pmap_inval_done(&info);
2920         vm_object_drop(pmap->pm_pteobj);
2921         lwkt_reltoken(&pmap->pm_token);
2922 }
2923
2924 /*
2925  * Make a temporary mapping for a physical address.  This is only intended
2926  * to be used for panic dumps.
2927  *
2928  * The caller is responsible for calling smp_invltlb().
2929  */
2930 void *
2931 pmap_kenter_temporary(vm_paddr_t pa, long i)
2932 {
2933         pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
2934         return ((void *)crashdumpmap);
2935 }
2936
2937 #define MAX_INIT_PT (96)
2938
2939 /*
2940  * This routine preloads the ptes for a given object into the specified pmap.
2941  * This eliminates the blast of soft faults on process startup and
2942  * immediately after an mmap.
2943  */
2944 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
2945
2946 void
2947 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
2948                     vm_object_t object, vm_pindex_t pindex, 
2949                     vm_size_t size, int limit)
2950 {
2951         struct rb_vm_page_scan_info info;
2952         struct lwp *lp;
2953         vm_size_t psize;
2954
2955         /*
2956          * We can't preinit if read access isn't set or there is no pmap
2957          * or object.
2958          */
2959         if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
2960                 return;
2961
2962         /*
2963          * We can't preinit if the pmap is not the current pmap
2964          */
2965         lp = curthread->td_lwp;
2966         if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
2967                 return;
2968
2969         psize = x86_64_btop(size);
2970
2971         if ((object->type != OBJT_VNODE) ||
2972                 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
2973                         (object->resident_page_count > MAX_INIT_PT))) {
2974                 return;
2975         }
2976
2977         if (psize + pindex > object->size) {
2978                 if (object->size < pindex)
2979                         return;           
2980                 psize = object->size - pindex;
2981         }
2982
2983         if (psize == 0)
2984                 return;
2985
2986         /*
2987          * Use a red-black scan to traverse the requested range and load
2988          * any valid pages found into the pmap.
2989          *
2990          * We cannot safely scan the object's memq without holding the
2991          * object token.
2992          */
2993         info.start_pindex = pindex;
2994         info.end_pindex = pindex + psize - 1;
2995         info.limit = limit;
2996         info.mpte = NULL;
2997         info.addr = addr;
2998         info.pmap = pmap;
2999         info.desired = 0;
3000
3001         vm_object_hold(object);
3002         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
3003                                 pmap_object_init_pt_callback, &info);
3004         vm_object_drop(object);
3005 }
3006
3007 static
3008 int
3009 pmap_object_init_pt_callback(vm_page_t p, void *data)
3010 {
3011         struct rb_vm_page_scan_info *info = data;
3012         vm_pindex_t rel_index;
3013
3014         /*
3015          * don't allow an madvise to blow away our really
3016          * free pages allocating pv entries.
3017          */
3018         if ((info->limit & MAP_PREFAULT_MADVISE) &&
3019                 vmstats.v_free_count < vmstats.v_free_reserved) {
3020                     return(-1);
3021         }
3022         if (vm_page_busy_try(p, TRUE))
3023                 return 0;
3024         if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3025             (p->flags & PG_FICTITIOUS) == 0) {
3026                 if ((p->queue - p->pc) == PQ_CACHE)
3027                         vm_page_deactivate(p);
3028                 rel_index = p->pindex - info->start_pindex;
3029                 pmap_enter_quick(info->pmap,
3030                                  info->addr + x86_64_ptob(rel_index), p);
3031         }
3032         vm_page_wakeup(p);
3033         pmap_auto_yield(info);
3034         return(0);
3035 }
3036
3037 /*
3038  * Return TRUE if the pmap is in shape to trivially
3039  * pre-fault the specified address.
3040  *
3041  * Returns FALSE if it would be non-trivial or if a
3042  * pte is already loaded into the slot.
3043  */
3044 int
3045 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
3046 {
3047         pt_entry_t *pte;
3048         pd_entry_t *pde;
3049         int ret;
3050
3051         lwkt_gettoken(&pmap->pm_token);
3052         pde = pmap_pde(pmap, addr);
3053         if (pde == NULL || *pde == 0) {
3054                 ret = 0;
3055         } else {
3056                 pte = vtopte(addr);
3057                 ret = (*pte) ? 0 : 1;
3058         }
3059         lwkt_reltoken(&pmap->pm_token);
3060         return(ret);
3061 }
3062
3063 /*
3064  *      Routine:        pmap_change_wiring
3065  *      Function:       Change the wiring attribute for a map/virtual-address
3066  *                      pair.
3067  *      In/out conditions:
3068  *                      The mapping must already exist in the pmap.
3069  */
3070 void
3071 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
3072 {
3073         pt_entry_t *pte;
3074
3075         if (pmap == NULL)
3076                 return;
3077
3078         lwkt_gettoken(&pmap->pm_token);
3079         pte = pmap_pte(pmap, va);
3080
3081         if (wired && !pmap_pte_w(pte))
3082                 pmap->pm_stats.wired_count++;
3083         else if (!wired && pmap_pte_w(pte))
3084                 pmap->pm_stats.wired_count--;
3085
3086         /*
3087          * Wiring is not a hardware characteristic so there is no need to
3088          * invalidate TLB.  However, in an SMP environment we must use
3089          * a locked bus cycle to update the pte (if we are not using 
3090          * the pmap_inval_*() API that is)... it's ok to do this for simple
3091          * wiring changes.
3092          */
3093 #ifdef SMP
3094         if (wired)
3095                 atomic_set_long(pte, PG_W);
3096         else
3097                 atomic_clear_long(pte, PG_W);
3098 #else
3099         if (wired)
3100                 atomic_set_long_nonlocked(pte, PG_W);
3101         else
3102                 atomic_clear_long_nonlocked(pte, PG_W);
3103 #endif
3104         lwkt_reltoken(&pmap->pm_token);
3105 }
3106
3107
3108
3109 /*
3110  * Copy the range specified by src_addr/len from the source map to
3111  * the range dst_addr/len in the destination map.
3112  *
3113  * This routine is only advisory and need not do anything.
3114  */
3115 void
3116 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, 
3117           vm_size_t len, vm_offset_t src_addr)
3118 {
3119         return;
3120 #if 0
3121         pmap_inval_info info;
3122         vm_offset_t addr;
3123         vm_offset_t end_addr = src_addr + len;
3124         vm_offset_t pdnxt;
3125         pd_entry_t src_frame, dst_frame;
3126         vm_page_t m;
3127
3128         if (dst_addr != src_addr)
3129                 return;
3130 #if JGPMAP32
3131         src_frame = src_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
3132         if (src_frame != (PTDpde & PG_FRAME)) {
3133                 return;
3134         }
3135
3136         dst_frame = dst_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
3137         if (dst_frame != (APTDpde & PG_FRAME)) {
3138                 APTDpde = (pd_entry_t) (dst_frame | PG_RW | PG_V);
3139                 /* The page directory is not shared between CPUs */
3140                 cpu_invltlb();
3141         }
3142 #endif
3143         pmap_inval_init(&info);
3144         pmap_inval_add(&info, dst_pmap, -1);
3145         pmap_inval_add(&info, src_pmap, -1);
3146
3147         lwkt_gettoken(&src_pmap->pm_token);
3148         lwkt_gettoken(&dst_pmap->pm_token);
3149         for (addr = src_addr; addr < end_addr; addr = pdnxt) {
3150                 pt_entry_t *src_pte, *dst_pte;
3151                 vm_page_t dstmpte, srcmpte;
3152                 vm_offset_t srcptepaddr;
3153                 vm_pindex_t ptepindex;
3154
3155                 if (addr >= UPT_MIN_ADDRESS)
3156                         panic("pmap_copy: invalid to pmap_copy page tables\n");
3157
3158                 /*
3159                  * Don't let optional prefaulting of pages make us go
3160                  * way below the low water mark of free pages or way
3161                  * above high water mark of used pv entries.
3162                  */
3163                 if (vmstats.v_free_count < vmstats.v_free_reserved ||
3164                     pv_entry_count > pv_entry_high_water)
3165                         break;
3166                 
3167                 pdnxt = ((addr + PAGE_SIZE*NPTEPG) & ~(PAGE_SIZE*NPTEPG - 1));
3168                 ptepindex = addr >> PDRSHIFT;
3169
3170 #if JGPMAP32
3171                 srcptepaddr = (vm_offset_t) src_pmap->pm_pdir[ptepindex];
3172 #endif
3173                 if (srcptepaddr == 0)
3174                         continue;
3175                         
3176                 if (srcptepaddr & PG_PS) {
3177 #if JGPMAP32
3178                         if (dst_pmap->pm_pdir[ptepindex] == 0) {
3179                                 dst_pmap->pm_pdir[ptepindex] = (pd_entry_t) srcptepaddr;
3180                                 dst_pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
3181                         }
3182 #endif
3183                         continue;
3184                 }
3185
3186                 /*
3187                  *
3188                  */
3189                 srcmpte = vm_page_lookup(src_pmap->pm_pteobj, ptepindex);
3190                 if (srcmpte == NULL || srcmpte->wire_count == 1 ||
3191                     (srcmpte->flags & PG_BUSY)) {
3192                         continue;
3193                 }
3194
3195                 if (pdnxt > end_addr)
3196                         pdnxt = end_addr;
3197
3198                 src_pte = vtopte(addr);
3199 #if JGPMAP32
3200                 dst_pte = avtopte(addr);
3201 #endif
3202                 while (addr < pdnxt) {
3203                         pt_entry_t ptetemp;
3204
3205                         ptetemp = *src_pte;
3206                         /*
3207                          * we only virtual copy managed pages
3208                          */
3209                         if ((ptetemp & PG_MANAGED) != 0) {
3210                                 /*
3211                                  * We have to check after allocpte for the
3212                                  * pte still being around...  allocpte can
3213                                  * block.
3214                                  *
3215                                  * pmap_allocpte() can block.  If we lose
3216                                  * our page directory mappings we stop.
3217                                  */
3218                                 dstmpte = pmap_allocpte(dst_pmap, addr);
3219
3220 #if JGPMAP32
3221                                 if (src_frame != (PTDpde & PG_FRAME) ||
3222                                     dst_frame != (APTDpde & PG_FRAME)
3223                                 ) {
3224                                         kprintf("WARNING: pmap_copy: detected and corrected race\n");
3225                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3226                                         goto failed;
3227                                 } else if ((*dst_pte == 0) &&
3228                                            (ptetemp = *src_pte) != 0 &&
3229                                            (ptetemp & PG_MANAGED)) {
3230                                         /*
3231                                          * Clear the modified and
3232                                          * accessed (referenced) bits
3233                                          * during the copy.
3234                                          */
3235                                         m = PHYS_TO_VM_PAGE(ptetemp);
3236                                         *dst_pte = ptetemp & ~(PG_M | PG_A);
3237                                         ++dst_pmap->pm_stats.resident_count;
3238                                         pmap_insert_entry(dst_pmap, addr,
3239                                                           dstmpte, m);
3240                                         KKASSERT(m->flags & PG_MAPPED);
3241                                 } else {
3242                                         kprintf("WARNING: pmap_copy: dst_pte race detected and corrected\n");
3243                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3244                                         goto failed;
3245                                 }
3246 #endif
3247                                 if (dstmpte->hold_count >= srcmpte->hold_count)
3248                                         break;
3249                         }
3250                         addr += PAGE_SIZE;
3251                         src_pte++;
3252                         dst_pte++;
3253                 }
3254         }
3255 failed:
3256         lwkt_reltoken(&dst_pmap->pm_token);
3257         lwkt_reltoken(&src_pmap->pm_token);
3258         pmap_inval_done(&info);
3259 #endif
3260 }       
3261
3262 /*
3263  * pmap_zero_page:
3264  *
3265  *      Zero the specified physical page.
3266  *
3267  *      This function may be called from an interrupt and no locking is
3268  *      required.
3269  */
3270 void
3271 pmap_zero_page(vm_paddr_t phys)
3272 {
3273         vm_offset_t va = PHYS_TO_DMAP(phys);
3274
3275         pagezero((void *)va);
3276 }
3277
3278 /*
3279  * pmap_page_assertzero:
3280  *
3281  *      Assert that a page is empty, panic if it isn't.
3282  */
3283 void
3284 pmap_page_assertzero(vm_paddr_t phys)
3285 {
3286         vm_offset_t va = PHYS_TO_DMAP(phys);
3287         size_t i;
3288
3289         for (i = 0; i < PAGE_SIZE; i += sizeof(long)) {
3290                 if (*(long *)((char *)va + i) != 0) {
3291                         panic("pmap_page_assertzero() @ %p not zero!\n",
3292                               (void *)(intptr_t)va);
3293                 }
3294         }
3295 }
3296
3297 /*
3298  * pmap_zero_page:
3299  *
3300  *      Zero part of a physical page by mapping it into memory and clearing
3301  *      its contents with bzero.
3302  *
3303  *      off and size may not cover an area beyond a single hardware page.
3304  */
3305 void
3306 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
3307 {
3308         vm_offset_t virt = PHYS_TO_DMAP(phys);
3309
3310         bzero((char *)virt + off, size);
3311 }
3312
3313 /*
3314  * pmap_copy_page:
3315  *
3316  *      Copy the physical page from the source PA to the target PA.
3317  *      This function may be called from an interrupt.  No locking
3318  *      is required.
3319  */
3320 void
3321 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
3322 {
3323         vm_offset_t src_virt, dst_virt;
3324
3325         src_virt = PHYS_TO_DMAP(src);
3326         dst_virt = PHYS_TO_DMAP(dst);
3327         bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
3328 }
3329
3330 /*
3331  * pmap_copy_page_frag:
3332  *
3333  *      Copy the physical page from the source PA to the target PA.
3334  *      This function may be called from an interrupt.  No locking
3335  *      is required.
3336  */
3337 void
3338 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
3339 {
3340         vm_offset_t src_virt, dst_virt;
3341
3342         src_virt = PHYS_TO_DMAP(src);
3343         dst_virt = PHYS_TO_DMAP(dst);
3344
3345         bcopy((char *)src_virt + (src & PAGE_MASK),
3346               (char *)dst_virt + (dst & PAGE_MASK),
3347               bytes);
3348 }
3349
3350 /*
3351  * Returns true if the pmap's pv is one of the first
3352  * 16 pvs linked to from this page.  This count may
3353  * be changed upwards or downwards in the future; it
3354  * is only necessary that true be returned for a small
3355  * subset of pmaps for proper page aging.
3356  */
3357 boolean_t
3358 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3359 {
3360         pv_entry_t pv;
3361         int loops = 0;
3362
3363         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3364                 return FALSE;
3365
3366         spin_lock(&pmap_spin);
3367         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3368                 if (pv->pv_pmap == pmap) {
3369                         spin_unlock(&pmap_spin);
3370                         return TRUE;
3371                 }
3372                 loops++;
3373                 if (loops >= 16)
3374                         break;
3375         }
3376         spin_unlock(&pmap_spin);
3377         return (FALSE);
3378 }
3379
3380 /*
3381  * Remove all pages from specified address space this aids process exit
3382  * speeds.  Also, this code is special cased for current process only, but
3383  * can have the more generic (and slightly slower) mode enabled.  This
3384  * is much faster than pmap_remove in the case of running down an entire
3385  * address space.
3386  */
3387 void
3388 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3389 {
3390         struct lwp *lp;
3391         pt_entry_t *pte, tpte;
3392         pv_entry_t pv, npv;
3393         vm_page_t m;
3394         vm_offset_t va;
3395         pmap_inval_info info;
3396         int iscurrentpmap;
3397         int save_generation;
3398
3399         lp = curthread->td_lwp;
3400         if (lp && pmap == vmspace_pmap(lp->lwp_vmspace))
3401                 iscurrentpmap = 1;
3402         else
3403                 iscurrentpmap = 0;
3404
3405         if (pmap->pm_pteobj)
3406                 vm_object_hold(pmap->pm_pteobj);
3407         lwkt_gettoken(&pmap->pm_token);
3408         pmap_inval_init(&info);
3409
3410         spin_lock(&pmap_spin);
3411         for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
3412                 /*
3413                  * Validate the pv.  We have to interlock the address with
3414                  * pmap_spin unlocked.
3415                  */
3416                 if (pv->pv_va >= eva || pv->pv_va < sva) {
3417                         npv = TAILQ_NEXT(pv, pv_plist);
3418                         continue;
3419                 }
3420
3421                 KKASSERT(pmap == pv->pv_pmap);
3422                 if (iscurrentpmap)
3423                         pte = vtopte(pv->pv_va);
3424                 else
3425                         pte = pmap_pte_quick(pmap, pv->pv_va);
3426
3427                 /*
3428                  * We cannot remove wired pages from a process' mapping
3429                  * at this time.  This does not require an invaldiation
3430                  * interlock as PG_W cannot be set by the MMU.
3431                  */
3432                 if (*pte & PG_W) {
3433                         npv = TAILQ_NEXT(pv, pv_plist);
3434                         continue;
3435                 }
3436
3437                 /*
3438                  * Interlock the pte so we can safely remove it
3439                  */
3440                 save_generation = pmap->pm_generation;
3441                 va = pv->pv_va;
3442                 spin_unlock(&pmap_spin);
3443
3444                 pmap_inval_interlock(&info, pmap, va);
3445
3446                 /*
3447                  * Restart the scan if the pv list changed out from under us.
3448                  */
3449                 spin_lock(&pmap_spin);
3450                 if (save_generation != pmap->pm_generation) {
3451                         spin_unlock(&pmap_spin);
3452                         pmap_inval_deinterlock(&info, pmap);
3453                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3454                         spin_lock(&pmap_spin);
3455                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3456                         continue;
3457                 }
3458                 KKASSERT(pmap == pv->pv_pmap && va == pv->pv_va);
3459
3460                 /*
3461                  * Extract the pte and clear its memory
3462                  */
3463                 tpte = pte_load_clear(pte);
3464                 KKASSERT(tpte & PG_MANAGED);
3465
3466                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3467                 KASSERT(m < &vm_page_array[vm_page_array_size],
3468                         ("pmap_remove_pages: bad tpte %lx", tpte));
3469
3470                 /*
3471                  * Remove the entry, set npv
3472                  */
3473                 npv = TAILQ_NEXT(pv, pv_plist);
3474                 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
3475                 m->md.pv_generation++;
3476                 m->md.pv_list_count--;
3477                 vm_page_spin_lock(m);
3478                 if (m->object)
3479                         atomic_add_int(&m->object->agg_pv_list_count, -1);
3480                 vm_page_spin_unlock(m);
3481                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3482                 if (TAILQ_EMPTY(&m->md.pv_list))
3483                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3484                 save_generation = ++pmap->pm_generation;
3485
3486                 spin_unlock(&pmap_spin);
3487
3488                 /*
3489                  * Adjust the pmap and cleanup the tpte and related vm_page
3490                  */
3491                 KKASSERT(pmap->pm_stats.resident_count > 0);
3492                 --pmap->pm_stats.resident_count;
3493                 pmap_inval_deinterlock(&info, pmap);
3494
3495                 /*
3496                  * Update the vm_page_t clean and reference bits.
3497                  */
3498                 if (tpte & PG_M) {
3499                         vm_page_dirty(m);
3500                 }
3501
3502                 pmap_unuse_pt(pmap, pv->pv_va, pv->pv_ptem, &info);
3503                 free_pv_entry(pv);
3504
3505                 /*
3506                  * Restart the scan if we blocked during the unuse or free
3507                  * calls and other removals were made.
3508                  */
3509                 spin_lock(&pmap_spin);
3510                 if (save_generation != pmap->pm_generation) {
3511                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3512                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3513                 }
3514         }
3515         spin_unlock(&pmap_spin);
3516         pmap_inval_done(&info);
3517         lwkt_reltoken(&pmap->pm_token);
3518         if (pmap->pm_pteobj)
3519                 vm_object_drop(pmap->pm_pteobj);
3520 }
3521
3522 /*
3523  * pmap_testbit tests bits in pte's note that the testbit/clearbit
3524  * routines are inline, and a lot of things compile-time evaluate.
3525  *
3526  * Caller must hold pmap_spin
3527  */
3528 static
3529 boolean_t
3530 pmap_testbit(vm_page_t m, int bit)
3531 {
3532         pv_entry_t pv;
3533         pt_entry_t *pte;
3534
3535         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3536                 return FALSE;
3537
3538         if (TAILQ_FIRST(&m->md.pv_list) == NULL)
3539                 return FALSE;
3540
3541         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3542                 /*
3543                  * if the bit being tested is the modified bit, then
3544                  * mark clean_map and ptes as never
3545                  * modified.
3546                  */
3547                 if (bit & (PG_A|PG_M)) {
3548                         if (!pmap_track_modified(pv->pv_va))
3549                                 continue;
3550                 }
3551
3552 #if defined(PMAP_DIAGNOSTIC)
3553                 if (pv->pv_pmap == NULL) {
3554                         kprintf("Null pmap (tb) at va: 0x%lx\n", pv->pv_va);
3555                         continue;
3556                 }
3557 #endif
3558                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3559                 if (*pte & bit)
3560                         return TRUE;
3561         }
3562         return (FALSE);
3563 }
3564
3565 /*
3566  * This routine is used to modify bits in ptes
3567  *
3568  * Caller must NOT hold pmap_spin
3569  */
3570 static __inline
3571 void
3572 pmap_clearbit(vm_page_t m, int bit)
3573 {
3574         struct pmap_inval_info info;
3575         int save_generation;
3576         vm_offset_t save_va;
3577         struct pmap *save_pmap;
3578         pv_entry_t pv;
3579         pt_entry_t *pte;
3580         pt_entry_t pbits;
3581
3582         if (bit == PG_RW)
3583                 vm_page_flag_clear(m, PG_WRITEABLE);
3584         if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
3585                 return;
3586         }
3587
3588         pmap_inval_init(&info);
3589
3590         /*
3591          * Loop over all current mappings setting/clearing as appropos If
3592          * setting RO do we need to clear the VAC?
3593          */
3594         spin_lock(&pmap_spin);
3595 restart:
3596         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3597                 /*
3598                  * don't write protect pager mappings
3599                  */
3600                 if (bit == PG_RW) {
3601                         if (!pmap_track_modified(pv->pv_va))
3602                                 continue;
3603                 }
3604
3605 #if defined(PMAP_DIAGNOSTIC)
3606                 if (pv->pv_pmap == NULL) {
3607                         kprintf("Null pmap (cb) at va: 0x%lx\n", pv->pv_va);
3608                         continue;
3609                 }
3610 #endif
3611
3612                 /*
3613                  * Careful here.  We can use a locked bus instruction to
3614                  * clear PG_A or PG_M safely but we need to synchronize
3615                  * with the target cpus when we mess with PG_RW.
3616                  *
3617                  * We do not have to force synchronization when clearing
3618                  * PG_M even for PTEs generated via virtual memory maps,
3619                  * because the virtual kernel will invalidate the pmap
3620                  * entry when/if it needs to resynchronize the Modify bit.
3621                  *
3622                  * We have to restart our scan if m->md.pv_generation changes
3623                  * on us.
3624                  */
3625                 if (bit & PG_RW) {
3626                         save_generation = m->md.pv_generation;
3627                         save_pmap = pv->pv_pmap;
3628                         save_va = pv->pv_va;
3629                         spin_unlock(&pmap_spin);
3630                         pmap_inval_interlock(&info, save_pmap, save_va);
3631                         spin_lock(&pmap_spin);
3632                         if (save_generation != m->md.pv_generation)
3633                                 goto restart;
3634                 }
3635                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3636 again:
3637                 pbits = *pte;
3638                 if (pbits & bit) {
3639                         if (bit == PG_RW) {
3640                                 if (pbits & PG_M) {
3641                                         vm_page_dirty(m);
3642                                         atomic_clear_long(pte, PG_M|PG_RW);
3643                                 } else {
3644                                         /*
3645                                          * The cpu may be trying to set PG_M
3646                                          * simultaniously with our clearing
3647                                          * of PG_RW.
3648                                          */
3649                                         if (!atomic_cmpset_long(pte, pbits,
3650                                                                pbits & ~PG_RW))
3651                                                 goto again;
3652                                 }
3653                         } else if (bit == PG_M) {
3654                                 /*
3655                                  * We could also clear PG_RW here to force
3656                                  * a fault on write to redetect PG_M for
3657                                  * virtual kernels, but it isn't necessary
3658                                  * since virtual kernels invalidate the pte 
3659                                  * when they clear the VPTE_M bit in their
3660                                  * virtual page tables.
3661                                  */
3662                                 atomic_clear_long(pte, PG_M);
3663                         } else {
3664                                 atomic_clear_long(pte, bit);
3665                         }
3666                 }
3667                 if (bit & PG_RW) {
3668                         save_generation = m->md.pv_generation;
3669                         save_pmap = pv->pv_pmap;
3670                         spin_unlock(&pmap_spin);
3671                         pmap_inval_deinterlock(&info, save_pmap);
3672                         spin_lock(&pmap_spin);
3673                         if (save_generation != m->md.pv_generation)
3674                                 goto restart;
3675                 }
3676         }
3677         spin_unlock(&pmap_spin);
3678         pmap_inval_done(&info);
3679 }
3680
3681 /*
3682  * Lower the permission for all mappings to a given page.
3683  *
3684  * Page must be busied by caller.
3685  */
3686 void
3687 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3688 {
3689         /* JG NX support? */
3690         if ((prot & VM_PROT_WRITE) == 0) {
3691                 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3692                         /*
3693                          * NOTE: pmap_clearbit(.. PG_RW) also clears
3694                          *       the PG_WRITEABLE flag in (m).
3695                          */
3696                         pmap_clearbit(m, PG_RW);
3697                 } else {
3698                         pmap_remove_all(m);
3699                 }
3700         }
3701 }
3702
3703 vm_paddr_t
3704 pmap_phys_address(vm_pindex_t ppn)
3705 {
3706         return (x86_64_ptob(ppn));
3707 }
3708
3709 /*
3710  * Return a count of reference bits for a page, clearing those bits.
3711  * It is not necessary for every reference bit to be cleared, but it
3712  * is necessary that 0 only be returned when there are truly no
3713  * reference bits set.
3714  *
3715  * XXX: The exact number of bits to check and clear is a matter that
3716  * should be tested and standardized at some point in the future for
3717  * optimal aging of shared pages.
3718  *
3719  * This routine may not block.
3720  */
3721 int
3722 pmap_ts_referenced(vm_page_t m)
3723 {
3724         pv_entry_t pv, pvf, pvn;
3725         pt_entry_t *pte;
3726         int rtval = 0;
3727
3728         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3729                 return (rtval);
3730
3731         spin_lock(&pmap_spin);
3732         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3733                 pvf = pv;
3734                 do {
3735                         pvn = TAILQ_NEXT(pv, pv_list);
3736
3737                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3738                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3739                         /*++pv->pv_pmap->pm_generation; not needed */
3740
3741                         if (!pmap_track_modified(pv->pv_va))
3742                                 continue;
3743
3744                         pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3745
3746                         if (pte && (*pte & PG_A)) {
3747 #ifdef SMP
3748                                 atomic_clear_long(pte, PG_A);
3749 #else
3750                                 atomic_clear_long_nonlocked(pte, PG_A);
3751 #endif
3752                                 rtval++;
3753                                 if (rtval > 4) {
3754                                         break;
3755                                 }
3756                         }
3757                 } while ((pv = pvn) != NULL && pv != pvf);
3758         }
3759         spin_unlock(&pmap_spin);
3760
3761         return (rtval);
3762 }
3763
3764 /*
3765  *      pmap_is_modified:
3766  *
3767  *      Return whether or not the specified physical page was modified
3768  *      in any physical maps.
3769  */
3770 boolean_t
3771 pmap_is_modified(vm_page_t m)
3772 {
3773         boolean_t res;
3774
3775         spin_lock(&pmap_spin);
3776         res = pmap_testbit(m, PG_M);
3777         spin_unlock(&pmap_spin);
3778         return (res);
3779 }
3780
3781 /*
3782  *      Clear the modify bits on the specified physical page.
3783  */
3784 void
3785 pmap_clear_modify(vm_page_t m)
3786 {
3787         pmap_clearbit(m, PG_M);
3788 }
3789
3790 /*
3791  *      pmap_clear_reference:
3792  *
3793  *      Clear the reference bit on the specified physical page.
3794  */
3795 void
3796 pmap_clear_reference(vm_page_t m)
3797 {
3798         pmap_clearbit(m, PG_A);
3799 }
3800
3801 /*
3802  * Miscellaneous support routines follow
3803  */
3804
3805 static
3806 void
3807 i386_protection_init(void)
3808 {
3809         int *kp, prot;
3810
3811         /* JG NX support may go here; No VM_PROT_EXECUTE ==> set NX bit  */
3812         kp = protection_codes;
3813         for (prot = 0; prot < 8; prot++) {
3814                 switch (prot) {
3815                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
3816                         /*
3817                          * Read access is also 0. There isn't any execute bit,
3818                          * so just make it readable.
3819                          */
3820                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
3821                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
3822                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
3823                         *kp++ = 0;
3824                         break;
3825                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
3826                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
3827                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
3828                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
3829                         *kp++ = PG_RW;
3830                         break;
3831                 }
3832         }
3833 }
3834
3835 /*
3836  * Map a set of physical memory pages into the kernel virtual
3837  * address space. Return a pointer to where it is mapped. This
3838  * routine is intended to be used for mapping device memory,
3839  * NOT real memory.
3840  *
3841  * NOTE: we can't use pgeflag unless we invalidate the pages one at
3842  * a time.
3843  */
3844 void *
3845 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
3846 {
3847         vm_offset_t va, tmpva, offset;
3848         pt_entry_t *pte;
3849
3850         offset = pa & PAGE_MASK;
3851         size = roundup(offset + size, PAGE_SIZE);
3852
3853         va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
3854         if (va == 0)
3855                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3856
3857         pa = pa & ~PAGE_MASK;
3858         for (tmpva = va; size > 0;) {
3859                 pte = vtopte(tmpva);
3860                 *pte = pa | PG_RW | PG_V; /* | pgeflag; */
3861                 size -= PAGE_SIZE;
3862                 tmpva += PAGE_SIZE;
3863                 pa += PAGE_SIZE;
3864         }
3865         cpu_invltlb();
3866         smp_invltlb();
3867
3868         return ((void *)(va + offset));
3869 }
3870
3871 void *
3872 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
3873 {
3874         vm_offset_t va, tmpva, offset;
3875         pt_entry_t *pte;
3876
3877         offset = pa & PAGE_MASK;
3878         size = roundup(offset + size, PAGE_SIZE);
3879
3880         va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
3881         if (va == 0)
3882                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3883
3884         pa = pa & ~PAGE_MASK;
3885         for (tmpva = va; size > 0;) {
3886                 pte = vtopte(tmpva);
3887                 *pte = pa | PG_RW | PG_V | PG_N; /* | pgeflag; */
3888                 size -= PAGE_SIZE;
3889                 tmpva += PAGE_SIZE;
3890                 pa += PAGE_SIZE;
3891         }
3892         cpu_invltlb();
3893         smp_invltlb();
3894
3895         return ((void *)(va + offset));
3896 }
3897
3898 void
3899 pmap_unmapdev(vm_offset_t va, vm_size_t size)
3900 {
3901         vm_offset_t base, offset;
3902
3903         base = va & ~PAGE_MASK;
3904         offset = va & PAGE_MASK;
3905         size = roundup(offset + size, PAGE_SIZE);
3906         pmap_qremove(va, size >> PAGE_SHIFT);
3907         kmem_free(&kernel_map, base, size);
3908 }
3909
3910 /*
3911  * perform the pmap work for mincore
3912  */
3913 int
3914 pmap_mincore(pmap_t pmap, vm_offset_t addr)
3915 {
3916         pt_entry_t *ptep, pte;
3917         vm_page_t m;
3918         int val = 0;
3919         
3920         lwkt_gettoken(&pmap->pm_token);
3921         ptep = pmap_pte(pmap, addr);
3922
3923         if (ptep && (pte = *ptep) != 0) {
3924                 vm_offset_t pa;
3925
3926                 val = MINCORE_INCORE;
3927                 if ((pte & PG_MANAGED) == 0)
3928                         goto done;
3929
3930                 pa = pte & PG_FRAME;
3931
3932                 m = PHYS_TO_VM_PAGE(pa);
3933
3934                 /*
3935                  * Modified by us
3936                  */
3937                 if (pte & PG_M)
3938                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3939                 /*
3940                  * Modified by someone
3941                  */
3942                 else if (m->dirty || pmap_is_modified(m))
3943                         val |= MINCORE_MODIFIED_OTHER;
3944                 /*
3945                  * Referenced by us
3946                  */
3947                 if (pte & PG_A)
3948                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3949
3950                 /*
3951                  * Referenced by someone
3952                  */
3953                 else if ((m->flags & PG_REFERENCED) || pmap_ts_referenced(m)) {
3954                         val |= MINCORE_REFERENCED_OTHER;
3955                         vm_page_flag_set(m, PG_REFERENCED);
3956                 }
3957         } 
3958 done:
3959         lwkt_reltoken(&pmap->pm_token);
3960
3961         return val;
3962 }
3963
3964 /*
3965  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
3966  * vmspace will be ref'd and the old one will be deref'd.
3967  *
3968  * The vmspace for all lwps associated with the process will be adjusted
3969  * and cr3 will be reloaded if any lwp is the current lwp.
3970  *
3971  * The process must hold the vmspace->vm_map.token for oldvm and newvm
3972  */
3973 void
3974 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
3975 {
3976         struct vmspace *oldvm;
3977         struct lwp *lp;
3978
3979         oldvm = p->p_vmspace;
3980         if (oldvm != newvm) {
3981                 if (adjrefs)
3982                         sysref_get(&newvm->vm_sysref);
3983                 p->p_vmspace = newvm;
3984                 KKASSERT(p->p_nthreads == 1);
3985                 lp = RB_ROOT(&p->p_lwp_tree);
3986                 pmap_setlwpvm(lp, newvm);
3987                 if (adjrefs)
3988                         sysref_put(&oldvm->vm_sysref);
3989         }
3990 }
3991
3992 /*
3993  * Set the vmspace for a LWP.  The vmspace is almost universally set the
3994  * same as the process vmspace, but virtual kernels need to swap out contexts
3995  * on a per-lwp basis.
3996  *
3997  * Caller does not necessarily hold any vmspace tokens.  Caller must control
3998  * the lwp (typically be in the context of the lwp).  We use a critical
3999  * section to protect against statclock and hardclock (statistics collection).
4000  */
4001 void
4002 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
4003 {
4004         struct vmspace *oldvm;
4005         struct pmap *pmap;
4006
4007         oldvm = lp->lwp_vmspace;
4008
4009         if (oldvm != newvm) {
4010                 crit_enter();
4011                 lp->lwp_vmspace = newvm;
4012                 if (curthread->td_lwp == lp) {
4013                         pmap = vmspace_pmap(newvm);
4014 #if defined(SMP)
4015                         atomic_set_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
4016                         if (pmap->pm_active & CPUMASK_LOCK)
4017                                 pmap_interlock_wait(newvm);
4018 #else
4019                         pmap->pm_active |= 1;
4020 #endif
4021 #if defined(SWTCH_OPTIM_STATS)
4022                         tlb_flush_count++;
4023 #endif
4024                         curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
4025                         curthread->td_pcb->pcb_cr3 |= PG_RW | PG_U | PG_V;
4026                         load_cr3(curthread->td_pcb->pcb_cr3);
4027                         pmap = vmspace_pmap(oldvm);
4028 #if defined(SMP)
4029                         atomic_clear_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
4030 #else
4031                         pmap->pm_active &= ~(cpumask_t)1;
4032 #endif
4033                 }
4034                 crit_exit();
4035         }
4036 }
4037
4038 #ifdef SMP
4039
4040 /*
4041  * Called when switching to a locked pmap, used to interlock against pmaps
4042  * undergoing modifications to prevent us from activating the MMU for the
4043  * target pmap until all such modifications have completed.  We have to do
4044  * this because the thread making the modifications has already set up its
4045  * SMP synchronization mask.
4046  *
4047  * No requirements.
4048  */
4049 void
4050 pmap_interlock_wait(struct vmspace *vm)
4051 {
4052         struct pmap *pmap = &vm->vm_pmap;
4053
4054         if (pmap->pm_active & CPUMASK_LOCK) {
4055                 crit_enter();
4056                 DEBUG_PUSH_INFO("pmap_interlock_wait");
4057                 while (pmap->pm_active & CPUMASK_LOCK) {
4058                         cpu_ccfence();
4059                         lwkt_process_ipiq();
4060                 }
4061                 DEBUG_POP_INFO();
4062                 crit_exit();
4063         }
4064 }
4065
4066 #endif
4067
4068 vm_offset_t
4069 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
4070 {
4071
4072         if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
4073                 return addr;
4074         }
4075
4076         addr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
4077         return addr;
4078 }
4079
4080 /*
4081  * Used by kmalloc/kfree, page already exists at va
4082  */
4083 vm_page_t
4084 pmap_kvtom(vm_offset_t va)
4085 {
4086         return(PHYS_TO_VM_PAGE(*vtopte(va) & PG_FRAME));
4087 }