Merge branch 'devel'
[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  * This routine reduces the wire_count on a page.  If the wire_count
1179  * would drop to zero we remove the PT, PD, or PDP from its parent page
1180  * table.  Under normal operation this only occurs with PT pages.
1181  *
1182  * mpte is never NULL for a user va, even for unmanaged pages.  mpte should
1183  * always be NULL for a kernel va.
1184  */
1185 static __inline
1186 int
1187 pmap_unwire_pte_hold(pmap_t pmap, vm_offset_t va, vm_page_t mpte,
1188                      pmap_inval_info_t info)
1189 {
1190         if (mpte == NULL)
1191                 return 0;
1192         if (!vm_page_unwire_quick(mpte))
1193                 return 0;
1194
1195         /* 
1196          * Wait until we can busy the page ourselves.  We cannot have
1197          * any active flushes if we block.  We own one hold count on the
1198          * page so it cannot be freed out from under us.
1199          */
1200         vm_page_busy_wait(mpte, FALSE, "pmuwpt");
1201         KASSERT(mpte->queue == PQ_NONE,
1202                 ("_pmap_unwire_pte_hold: %p->queue != PQ_NONE", mpte));
1203
1204         /*
1205          * New references can bump the wire_count while we were blocked,
1206          * try to unwire quickly again (e.g. 2->1).
1207          */
1208         if (vm_page_unwire_quick(mpte) == 0) {
1209                 vm_page_wakeup(mpte);
1210                 return 0;
1211         }
1212
1213         /*
1214          * Unmap the page table page
1215          */
1216         KKASSERT(mpte->wire_count == 1);
1217         pmap_inval_interlock(info, pmap, -1);
1218
1219         if (mpte->pindex >= (NUPDE + NUPDPE)) {
1220                 /* PDP page */
1221                 pml4_entry_t *pml4;
1222                 pml4 = pmap_pml4e(pmap, va);
1223                 KKASSERT(*pml4);
1224                 *pml4 = 0;
1225         } else if (mpte->pindex >= NUPDE) {
1226                 /* PD page */
1227                 pdp_entry_t *pdp;
1228                 pdp = pmap_pdpe(pmap, va);
1229                 KKASSERT(*pdp);
1230                 *pdp = 0;
1231         } else {
1232                 /* PT page */
1233                 pd_entry_t *pd;
1234                 pd = pmap_pde(pmap, va);
1235                 KKASSERT(*pd);
1236                 *pd = 0;
1237         }
1238
1239         KKASSERT(pmap->pm_stats.resident_count > 0);
1240         --pmap->pm_stats.resident_count;
1241
1242         if (pmap->pm_ptphint == mpte)
1243                 pmap->pm_ptphint = NULL;
1244         pmap_inval_deinterlock(info, pmap);
1245
1246         if (mpte->pindex < NUPDE) {
1247                 /* We just released a PT, unhold the matching PD */
1248                 vm_page_t pdpg;
1249
1250                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
1251                 pmap_unwire_pte_hold(pmap, va, pdpg, info);
1252         }
1253         if (mpte->pindex >= NUPDE && mpte->pindex < (NUPDE + NUPDPE)) {
1254                 /* We just released a PD, unhold the matching PDP */
1255                 vm_page_t pdppg;
1256
1257                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
1258                 pmap_unwire_pte_hold(pmap, va, pdppg, info);
1259         }
1260
1261         /*
1262          * This was our wiring.
1263          */
1264         KKASSERT(mpte->flags & PG_UNMANAGED);
1265         vm_page_unwire(mpte, 0);
1266         KKASSERT(mpte->wire_count == 0);
1267         vm_page_flag_clear(mpte, PG_MAPPED | PG_WRITEABLE);
1268         vm_page_flash(mpte);
1269         vm_page_free_zero(mpte);
1270
1271         return 1;
1272 }
1273
1274 /*
1275  * Initialize pmap0/vmspace0.  This pmap is not added to pmap_list because
1276  * it, and IdlePTD, represents the template used to update all other pmaps.
1277  *
1278  * On architectures where the kernel pmap is not integrated into the user
1279  * process pmap, this pmap represents the process pmap, not the kernel pmap.
1280  * kernel_pmap should be used to directly access the kernel_pmap.
1281  */
1282 void
1283 pmap_pinit0(struct pmap *pmap)
1284 {
1285         pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
1286         pmap->pm_count = 1;
1287         pmap->pm_active = 0;
1288         pmap->pm_ptphint = NULL;
1289         TAILQ_INIT(&pmap->pm_pvlist);
1290         TAILQ_INIT(&pmap->pm_pvlist_free);
1291         pmap->pm_hold = 0;
1292         spin_init(&pmap->pm_spin);
1293         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1294         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1295 }
1296
1297 /*
1298  * Initialize a preallocated and zeroed pmap structure,
1299  * such as one in a vmspace structure.
1300  */
1301 void
1302 pmap_pinit(struct pmap *pmap)
1303 {
1304         vm_page_t pml4pg;
1305
1306         /*
1307          * No need to allocate page table space yet but we do need a valid
1308          * page directory table.
1309          */
1310         if (pmap->pm_pml4 == NULL) {
1311                 pmap->pm_pml4 =
1312                     (pml4_entry_t *)kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
1313         }
1314
1315         /*
1316          * Allocate an object for the ptes
1317          */
1318         if (pmap->pm_pteobj == NULL) {
1319                 pmap->pm_pteobj = vm_object_allocate(OBJT_DEFAULT,
1320                                                 NUPDE + NUPDPE + PML4PML4I + 1);
1321         }
1322
1323         /*
1324          * Allocate the page directory page, unless we already have
1325          * one cached.  If we used the cached page the wire_count will
1326          * already be set appropriately.
1327          */
1328         if ((pml4pg = pmap->pm_pdirm) == NULL) {
1329                 pml4pg = vm_page_grab(pmap->pm_pteobj,
1330                                       NUPDE + NUPDPE + PML4PML4I,
1331                                       VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
1332                 pmap->pm_pdirm = pml4pg;
1333                 vm_page_unmanage(pml4pg);
1334                 vm_page_flag_clear(pml4pg, PG_MAPPED);
1335                 pml4pg->valid = VM_PAGE_BITS_ALL;
1336                 vm_page_wire(pml4pg);
1337                 vm_page_wakeup(pml4pg);
1338                 pmap_kenter((vm_offset_t)pmap->pm_pml4,
1339                             VM_PAGE_TO_PHYS(pml4pg));
1340         }
1341         if ((pml4pg->flags & PG_ZERO) == 0)
1342                 bzero(pmap->pm_pml4, PAGE_SIZE);
1343 #ifdef PMAP_DEBUG
1344         else
1345                 pmap_page_assertzero(VM_PAGE_TO_PHYS(pml4pg));
1346 #endif
1347         vm_page_flag_clear(pml4pg, PG_ZERO);
1348
1349         pmap->pm_pml4[KPML4I] = KPDPphys | PG_RW | PG_V | PG_U;
1350         pmap->pm_pml4[DMPML4I] = DMPDPphys | PG_RW | PG_V | PG_U;
1351
1352         /* install self-referential address mapping entry */
1353         pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) |
1354                                    PG_V | PG_RW | PG_A | PG_M;
1355
1356         pmap->pm_count = 1;
1357         pmap->pm_active = 0;
1358         pmap->pm_ptphint = NULL;
1359         TAILQ_INIT(&pmap->pm_pvlist);
1360         TAILQ_INIT(&pmap->pm_pvlist_free);
1361         pmap->pm_hold = 0;
1362         spin_init(&pmap->pm_spin);
1363         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1364         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1365         pmap->pm_stats.resident_count = 1;
1366 }
1367
1368 /*
1369  * Clean up a pmap structure so it can be physically freed.  This routine
1370  * is called by the vmspace dtor function.  A great deal of pmap data is
1371  * left passively mapped to improve vmspace management so we have a bit
1372  * of cleanup work to do here.
1373  */
1374 void
1375 pmap_puninit(pmap_t pmap)
1376 {
1377         vm_page_t p;
1378
1379         KKASSERT(pmap->pm_active == 0);
1380         if ((p = pmap->pm_pdirm) != NULL) {
1381                 KKASSERT(pmap->pm_pml4 != NULL);
1382                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1383                 pmap_kremove((vm_offset_t)pmap->pm_pml4);
1384                 vm_page_busy_wait(p, FALSE, "pgpun");
1385                 KKASSERT(p->flags & PG_UNMANAGED);
1386                 vm_page_unwire(p, 0);
1387                 vm_page_free_zero(p);
1388                 pmap->pm_pdirm = NULL;
1389         }
1390         if (pmap->pm_pml4) {
1391                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1392                 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
1393                 pmap->pm_pml4 = NULL;
1394         }
1395         if (pmap->pm_pteobj) {
1396                 vm_object_deallocate(pmap->pm_pteobj);
1397                 pmap->pm_pteobj = NULL;
1398         }
1399 }
1400
1401 /*
1402  * Wire in kernel global address entries.  To avoid a race condition
1403  * between pmap initialization and pmap_growkernel, this procedure
1404  * adds the pmap to the master list (which growkernel scans to update),
1405  * then copies the template.
1406  */
1407 void
1408 pmap_pinit2(struct pmap *pmap)
1409 {
1410         /*
1411          * XXX copies current process, does not fill in MPPTDI
1412          */
1413         spin_lock(&pmap_spin);
1414         TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
1415         spin_unlock(&pmap_spin);
1416 }
1417
1418 /*
1419  * Attempt to release and free a vm_page in a pmap.  Returns 1 on success,
1420  * 0 on failure (if the procedure had to sleep).
1421  *
1422  * When asked to remove the page directory page itself, we actually just
1423  * leave it cached so we do not have to incur the SMP inval overhead of
1424  * removing the kernel mapping.  pmap_puninit() will take care of it.
1425  */
1426 static
1427 int
1428 pmap_release_free_page(struct pmap *pmap, vm_page_t p)
1429 {
1430         /*
1431          * This code optimizes the case of freeing non-busy
1432          * page-table pages.  Those pages are zero now, and
1433          * might as well be placed directly into the zero queue.
1434          */
1435         if (vm_page_busy_try(p, FALSE)) {
1436                 vm_page_sleep_busy(p, FALSE, "pmaprl");
1437                 return 0;
1438         }
1439
1440         /*
1441          * Remove the page table page from the processes address space.
1442          */
1443         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1444                 /*
1445                  * We are the pml4 table itself.
1446                  */
1447                 /* XXX anything to do here? */
1448         } else if (p->pindex >= (NUPDE + NUPDPE)) {
1449                 /*
1450                  * Remove a PDP page from the PML4.  We do not maintain
1451                  * wire counts on the PML4 page.
1452                  */
1453                 pml4_entry_t *pml4;
1454                 vm_page_t m4;
1455                 int idx;
1456
1457                 m4 = vm_page_lookup(pmap->pm_pteobj,
1458                                     NUPDE + NUPDPE + PML4PML4I);
1459                 KKASSERT(m4 != NULL);
1460                 pml4 = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m4));
1461                 idx = (p->pindex - (NUPDE + NUPDPE)) % NPML4EPG;
1462                 KKASSERT(pml4[idx] != 0);
1463                 pml4[idx] = 0;
1464         } else if (p->pindex >= NUPDE) {
1465                 /*
1466                  * Remove a PD page from the PDP and drop the wire count
1467                  * on the PDP.  The PDP has a wire_count just from being
1468                  * mapped so the wire_count should never drop to 0 here.
1469                  */
1470                 vm_page_t m3;
1471                 pdp_entry_t *pdp;
1472                 int idx;
1473
1474                 m3 = vm_page_lookup(pmap->pm_pteobj,
1475                                 NUPDE + NUPDPE + (p->pindex - NUPDE) / NPDPEPG);
1476                 KKASSERT(m3 != NULL);
1477                 pdp = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m3));
1478                 idx = (p->pindex - NUPDE) % NPDPEPG;
1479                 KKASSERT(pdp[idx] != 0);
1480                 pdp[idx] = 0;
1481                 if (vm_page_unwire_quick(m3))
1482                         panic("pmap_release_free_page: m3 wire_count 1->0");
1483         } else {
1484                 /*
1485                  * Remove a PT page from the PD and drop the wire count
1486                  * on the PD.  The PD has a wire_count just from being
1487                  * mapped so the wire_count should never drop to 0 here.
1488                  */
1489                 vm_page_t m2;
1490                 pd_entry_t *pd;
1491                 int idx;
1492
1493                 m2 = vm_page_lookup(pmap->pm_pteobj,
1494                                     NUPDE + p->pindex / NPDEPG);
1495                 KKASSERT(m2 != NULL);
1496                 pd = (void *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m2));
1497                 idx = p->pindex % NPDEPG;
1498                 pd[idx] = 0;
1499                 if (vm_page_unwire_quick(m2))
1500                         panic("pmap_release_free_page: m2 wire_count 1->0");
1501         }
1502
1503         /*
1504          * p's wire_count should be transitioning from 1 to 0 here.
1505          */
1506         KKASSERT(p->wire_count == 1);
1507         KKASSERT(p->flags & PG_UNMANAGED);
1508         KKASSERT(pmap->pm_stats.resident_count > 0);
1509         vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
1510         --pmap->pm_stats.resident_count;
1511         if (pmap->pm_ptphint && (pmap->pm_ptphint->pindex == p->pindex))
1512                 pmap->pm_ptphint = NULL;
1513
1514         /*
1515          * We leave the top-level page table page cached, wired, and mapped in
1516          * the pmap until the dtor function (pmap_puninit()) gets called.
1517          * However, still clean it up so we can set PG_ZERO.
1518          */
1519         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1520                 bzero(pmap->pm_pml4, PAGE_SIZE);
1521                 vm_page_flag_set(p, PG_ZERO);
1522                 vm_page_wakeup(p);
1523         } else {
1524                 vm_page_unwire(p, 0);
1525                 KKASSERT(p->wire_count == 0);
1526                 /* JG eventually revert to using vm_page_free_zero() */
1527                 vm_page_free(p);
1528         }
1529         return 1;
1530 }
1531
1532 /*
1533  * This routine is called when various levels in the page table need to
1534  * be populated.  This routine cannot fail.
1535  *
1536  * We returned a page wired for the caller.  If we had to map the page into
1537  * a parent page table it will receive an additional wire_count.  For example,
1538  * an empty page table directory which is still mapped into its pdp will
1539  * retain a wire_count of 1.
1540  */
1541 static
1542 vm_page_t
1543 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex)
1544 {
1545         vm_page_t m;
1546
1547         /*
1548          * Find or fabricate a new pagetable page.  This will busy the page.
1549          */
1550         m = vm_page_grab(pmap->pm_pteobj, ptepindex,
1551                          VM_ALLOC_NORMAL | VM_ALLOC_ZERO | VM_ALLOC_RETRY);
1552
1553         /*
1554          * The grab may have blocked and raced another thread populating
1555          * the same page table.  m->valid will be 0 on a newly allocated page
1556          * so use this to determine if we have to zero it out or not.  We
1557          * don't want to zero-out a raced page as this would desynchronize
1558          * the pv_entry's for the related pte's and cause pmap_remove_all()
1559          * to panic.
1560          *
1561          * Page table pages are unmanaged (do not use the normal PQ_s)
1562          */
1563         if (m->valid == 0) {
1564                 vm_page_unmanage(m);
1565                 if ((m->flags & PG_ZERO) == 0) {
1566                         pmap_zero_page(VM_PAGE_TO_PHYS(m));
1567                 }
1568 #ifdef PMAP_DEBUG
1569                 else {
1570                         pmap_page_assertzero(VM_PAGE_TO_PHYS(m));
1571                 }
1572 #endif
1573                 m->valid = VM_PAGE_BITS_ALL;
1574                 vm_page_flag_clear(m, PG_ZERO);
1575         }
1576 #ifdef PMAP_DEBUG
1577         else {
1578                 KKASSERT((m->flags & PG_ZERO) == 0);
1579         }
1580 #endif
1581
1582         KASSERT(m->queue == PQ_NONE,
1583                 ("_pmap_allocpte: %p->queue != PQ_NONE", m));
1584
1585         /*
1586          * Increment the wire_count for the page we will be returning to
1587          * the caller.
1588          */
1589         vm_page_wire(m);
1590
1591         /*
1592          * Map the pagetable page into the process address space, if
1593          * it isn't already there.
1594          *
1595          * It is possible that someone else got in and mapped the page
1596          * directory page while we were blocked, if so just unbusy and
1597          * return the held page.
1598          */
1599         if (ptepindex >= (NUPDE + NUPDPE)) {
1600                 /*
1601                  * Wire up a new PDP page in the PML4.
1602                  *
1603                  * (m) is busied so we cannot race another thread trying
1604                  * to map the PDP entry in the PML4.
1605                  */
1606                 vm_pindex_t pml4index;
1607                 pml4_entry_t *pml4;
1608
1609                 pml4index = ptepindex - (NUPDE + NUPDPE);
1610                 pml4 = &pmap->pm_pml4[pml4index];
1611                 if ((*pml4 & PG_V) == 0) {
1612                         *pml4 = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1613                                                       PG_A | PG_M);
1614                         ++pmap->pm_stats.resident_count;
1615                         vm_page_wire_quick(m);  /* wire for mapping */
1616                 }
1617                 /* return (m) wired for the caller */
1618         } else if (ptepindex >= NUPDE) {
1619                 /*
1620                  * Wire up a new PD page in the PDP
1621                  */
1622                 vm_pindex_t pml4index;
1623                 vm_pindex_t pdpindex;
1624                 vm_page_t pdppg;
1625                 pml4_entry_t *pml4;
1626                 pdp_entry_t *pdp;
1627
1628                 pdpindex = ptepindex - NUPDE;
1629                 pml4index = pdpindex >> NPML4EPGSHIFT;
1630
1631                 /*
1632                  * Once mapped the PDP is not unmapped during normal operation
1633                  * so we only need to handle races in the unmapped case.
1634                  *
1635                  * Mapping a PD into the PDP requires an additional wiring
1636                  * of the PDP.
1637                  */
1638                 pml4 = &pmap->pm_pml4[pml4index];
1639                 if ((*pml4 & PG_V) == 0) {
1640                         pdppg = _pmap_allocpte(pmap,
1641                                                NUPDE + NUPDPE + pml4index);
1642                         /* pdppg wired for the map and also wired for return */
1643                 } else {
1644                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1645                         vm_page_wire_quick(pdppg);
1646                 }
1647                 /* we have an extra ref on pdppg now for our use */
1648
1649                 /*
1650                  * Now find the PD entry in the PDP and map it.
1651                  *
1652                  * (m) is busied so we cannot race another thread trying
1653                  * to map the PD entry in the PDP.
1654                  *
1655                  * If the PD entry is already mapped we have to drop one
1656                  * wire count on the pdppg that we had bumped above.
1657                  */
1658                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1659                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1660
1661                 if ((*pdp & PG_V) == 0) {
1662                         *pdp = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1663                                                      PG_A | PG_M);
1664                         vm_page_wire_quick(m);  /* wire for mapping */
1665                         ++pmap->pm_stats.resident_count;
1666                         /* eat extra pdppg wiring for mapping */
1667                 } else {
1668                         if (vm_page_unwire_quick(pdppg))
1669                                 panic("pmap_allocpte: unwire case 1");
1670                 }
1671                 /* return (m) wired for the caller */
1672         } else {
1673                 /*
1674                  * Wire up the new PT page in the PD
1675                  */
1676                 vm_pindex_t pml4index;
1677                 vm_pindex_t pdpindex;
1678                 pml4_entry_t *pml4;
1679                 pdp_entry_t *pdp;
1680                 pd_entry_t *pd;
1681                 vm_page_t pdppg;
1682                 vm_page_t pdpg;
1683
1684                 pdpindex = ptepindex >> NPDPEPGSHIFT;
1685                 pml4index = pdpindex >> NPML4EPGSHIFT;
1686
1687                 /*
1688                  * Locate the PDP page in the PML4
1689                  *
1690                  * Once mapped the PDP is not unmapped during normal operation
1691                  * so we only need to handle races in the unmapped case.
1692                  */
1693                 pml4 = &pmap->pm_pml4[pml4index];
1694                 if ((*pml4 & PG_V) == 0) {
1695                         pdppg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1696                 } else {
1697                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
1698                         vm_page_wire_quick(pdppg);
1699                 }
1700                 /* we have an extra ref on pdppg now for our use */
1701
1702                 /*
1703                  * Locate the PD page in the PDP
1704                  *
1705                  * Once mapped the PDP is not unmapped during normal operation
1706                  * so we only need to handle races in the unmapped case.
1707                  *
1708                  * We can scrap the extra reference on pdppg not needed if
1709                  * *pdp is already mapped and also not needed if it wasn't
1710                  * because the _pmap_allocpte() picked up the case for us.
1711                  */
1712                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
1713                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
1714
1715                 if ((*pdp & PG_V) == 0) {
1716                         pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex);
1717                 } else {
1718                         pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
1719                         vm_page_wire_quick(pdpg);
1720                 }
1721                 vm_page_unwire_quick(pdppg);
1722                 /* we have an extra ref on pdpg now for our use */
1723
1724                 /*
1725                  * Locate the PT page in the PD.
1726                  *
1727                  * (m) is busied so we cannot race another thread trying
1728                  * to map the PT page in the PD.
1729                  */
1730                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
1731                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
1732                 if ((*pd & PG_V) == 0) {
1733                         *pd = VM_PAGE_TO_PHYS(m) | (PG_U | PG_RW | PG_V |
1734                                                     PG_A | PG_M);
1735                         ++pmap->pm_stats.resident_count;
1736                         vm_page_wire_quick(m);  /* wire for mapping */
1737                         /* eat extra pdpg wiring for mapping */
1738                 } else {
1739                         if (vm_page_unwire_quick(pdpg))
1740                                 panic("pmap_allocpte: unwire case 2");
1741                 }
1742                 /* return (m) wired for the caller */
1743         }
1744
1745         /*
1746          * We successfully loaded a PDP, PD, or PTE.  Set the page table hint,
1747          * valid bits, mapped flag, unbusy, and we're done.
1748          */
1749         pmap->pm_ptphint = m;
1750
1751 #if 0
1752         m->valid = VM_PAGE_BITS_ALL;
1753         vm_page_flag_clear(m, PG_ZERO);
1754 #endif
1755         vm_page_flag_set(m, PG_MAPPED);
1756         vm_page_wakeup(m);
1757
1758         return (m);
1759 }
1760
1761 static
1762 vm_page_t
1763 pmap_allocpte(pmap_t pmap, vm_offset_t va)
1764 {
1765         vm_pindex_t ptepindex;
1766         pd_entry_t *pd;
1767         vm_page_t m;
1768
1769         ASSERT_LWKT_TOKEN_HELD(vm_object_token(pmap->pm_pteobj));
1770
1771         /*
1772          * Calculate pagetable page index
1773          */
1774         ptepindex = pmap_pde_pindex(va);
1775
1776         /*
1777          * Get the page directory entry
1778          */
1779         pd = pmap_pde(pmap, va);
1780
1781         /*
1782          * This supports switching from a 2MB page to a
1783          * normal 4K page.
1784          */
1785         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
1786                 panic("no promotion/demotion yet");
1787                 *pd = 0;
1788                 pd = NULL;
1789                 cpu_invltlb();
1790                 smp_invltlb();
1791         }
1792
1793         /*
1794          * If the page table page is mapped, we just increment the
1795          * wire count, and activate it.
1796          */
1797         if (pd != NULL && (*pd & PG_V) != 0) {
1798                 m = pmap_page_lookup(pmap->pm_pteobj, ptepindex);
1799                 pmap->pm_ptphint = m;
1800                 vm_page_wire_quick(m);
1801                 vm_page_wakeup(m);
1802                 return m;
1803         }
1804         /*
1805          * Here if the pte page isn't mapped, or if it has been deallocated.
1806          */
1807         return _pmap_allocpte(pmap, ptepindex);
1808 }
1809
1810
1811 /***************************************************
1812  * Pmap allocation/deallocation routines.
1813  ***************************************************/
1814
1815 /*
1816  * Release any resources held by the given physical map.
1817  * Called when a pmap initialized by pmap_pinit is being released.
1818  * Should only be called if the map contains no valid mappings.
1819  *
1820  * Caller must hold pmap->pm_token
1821  */
1822 static int pmap_release_callback(struct vm_page *p, void *data);
1823
1824 static __inline
1825 void
1826 pmap_auto_yield(struct rb_vm_page_scan_info *info)
1827 {
1828         if (++info->desired >= pmap_yield_count) {
1829                 info->desired = 0;
1830                 lwkt_yield();
1831         }
1832 }
1833
1834 void
1835 pmap_release(struct pmap *pmap)
1836 {
1837         vm_object_t object = pmap->pm_pteobj;
1838         struct rb_vm_page_scan_info info;
1839
1840         KASSERT(pmap->pm_active == 0,
1841                 ("pmap still active! %016jx", (uintmax_t)pmap->pm_active));
1842 #if defined(DIAGNOSTIC)
1843         if (object->ref_count != 1)
1844                 panic("pmap_release: pteobj reference count != 1");
1845 #endif
1846         
1847         info.pmap = pmap;
1848         info.object = object;
1849
1850         spin_lock(&pmap_spin);
1851         TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
1852         spin_unlock(&pmap_spin);
1853
1854         info.desired = 0;
1855         vm_object_hold(object);
1856         do {
1857                 info.error = 0;
1858                 info.mpte = NULL;
1859                 info.limit = object->generation;
1860
1861                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL, 
1862                                         pmap_release_callback, &info);
1863                 if (info.error == 0 && info.mpte) {
1864                         if (!pmap_release_free_page(pmap, info.mpte))
1865                                 info.error = 1;
1866                 }
1867         } while (info.error);
1868         vm_object_drop(object);
1869
1870         while (pmap->pm_hold)
1871                 tsleep(pmap, 0, "pmapx", 1);
1872 }
1873
1874 static
1875 int
1876 pmap_release_callback(struct vm_page *p, void *data)
1877 {
1878         struct rb_vm_page_scan_info *info = data;
1879
1880         if (p->pindex == NUPDE + NUPDPE + PML4PML4I) {
1881                 info->mpte = p;
1882                 return(0);
1883         }
1884         if (!pmap_release_free_page(info->pmap, p)) {
1885                 info->error = 1;
1886                 pmap_auto_yield(info);
1887                 return(-1);
1888         }
1889         if (info->object->generation != info->limit) {
1890                 info->error = 1;
1891                 pmap_auto_yield(info);
1892                 return(-1);
1893         }
1894         return(0);
1895 }
1896
1897 /*
1898  * Grow the number of kernel page table entries, if needed.
1899  *
1900  * This routine is always called to validate any address space
1901  * beyond KERNBASE (for kldloads).  kernel_vm_end only governs the address
1902  * space below KERNBASE.
1903  */
1904 void
1905 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
1906 {
1907         vm_paddr_t paddr;
1908         vm_offset_t ptppaddr;
1909         vm_page_t nkpg;
1910         pd_entry_t *pde, newpdir;
1911         pdp_entry_t newpdp;
1912         int update_kernel_vm_end;
1913
1914         vm_object_hold(kptobj);
1915
1916         /*
1917          * bootstrap kernel_vm_end on first real VM use
1918          */
1919         if (kernel_vm_end == 0) {
1920                 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
1921                 nkpt = 0;
1922                 while ((*pmap_pde(&kernel_pmap, kernel_vm_end) & PG_V) != 0) {
1923                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
1924                                         ~(PAGE_SIZE * NPTEPG - 1);
1925                         nkpt++;
1926                         if (kernel_vm_end - 1 >= kernel_map.max_offset) {
1927                                 kernel_vm_end = kernel_map.max_offset;
1928                                 break;                       
1929                         }
1930                 }
1931         }
1932
1933         /*
1934          * Fill in the gaps.  kernel_vm_end is only adjusted for ranges
1935          * below KERNBASE.  Ranges above KERNBASE are kldloaded and we
1936          * do not want to force-fill 128G worth of page tables.
1937          */
1938         if (kstart < KERNBASE) {
1939                 if (kstart > kernel_vm_end)
1940                         kstart = kernel_vm_end;
1941                 KKASSERT(kend <= KERNBASE);
1942                 update_kernel_vm_end = 1;
1943         } else {
1944                 update_kernel_vm_end = 0;
1945         }
1946
1947         kstart = rounddown2(kstart, PAGE_SIZE * NPTEPG);
1948         kend = roundup2(kend, PAGE_SIZE * NPTEPG);
1949
1950         if (kend - 1 >= kernel_map.max_offset)
1951                 kend = kernel_map.max_offset;
1952
1953         while (kstart < kend) {
1954                 pde = pmap_pde(&kernel_pmap, kstart);
1955                 if (pde == NULL) {
1956                         /* We need a new PDP entry */
1957                         nkpg = vm_page_alloc(kptobj, nkpt,
1958                                              VM_ALLOC_NORMAL |
1959                                              VM_ALLOC_SYSTEM |
1960                                              VM_ALLOC_INTERRUPT);
1961                         if (nkpg == NULL) {
1962                                 panic("pmap_growkernel: no memory to grow "
1963                                       "kernel");
1964                         }
1965                         paddr = VM_PAGE_TO_PHYS(nkpg);
1966                         if ((nkpg->flags & PG_ZERO) == 0)
1967                                 pmap_zero_page(paddr);
1968                         vm_page_flag_clear(nkpg, PG_ZERO);
1969                         newpdp = (pdp_entry_t)
1970                                 (paddr | PG_V | PG_RW | PG_A | PG_M);
1971                         *pmap_pdpe(&kernel_pmap, kstart) = newpdp;
1972                         nkpt++;
1973                         continue; /* try again */
1974                 }
1975                 if ((*pde & PG_V) != 0) {
1976                         kstart = (kstart + PAGE_SIZE * NPTEPG) &
1977                                  ~(PAGE_SIZE * NPTEPG - 1);
1978                         if (kstart - 1 >= kernel_map.max_offset) {
1979                                 kstart = kernel_map.max_offset;
1980                                 break;                       
1981                         }
1982                         continue;
1983                 }
1984
1985                 /*
1986                  * This index is bogus, but out of the way
1987                  */
1988                 nkpg = vm_page_alloc(kptobj, nkpt,
1989                                      VM_ALLOC_NORMAL |
1990                                      VM_ALLOC_SYSTEM |
1991                                      VM_ALLOC_INTERRUPT);
1992                 if (nkpg == NULL)
1993                         panic("pmap_growkernel: no memory to grow kernel");
1994
1995                 vm_page_wire(nkpg);
1996                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1997                 pmap_zero_page(ptppaddr);
1998                 vm_page_flag_clear(nkpg, PG_ZERO);
1999                 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
2000                 *pmap_pde(&kernel_pmap, kstart) = newpdir;
2001                 nkpt++;
2002
2003                 kstart = (kstart + PAGE_SIZE * NPTEPG) &
2004                           ~(PAGE_SIZE * NPTEPG - 1);
2005
2006                 if (kstart - 1 >= kernel_map.max_offset) {
2007                         kstart = kernel_map.max_offset;
2008                         break;                       
2009                 }
2010         }
2011
2012         /*
2013          * Only update kernel_vm_end for areas below KERNBASE.
2014          */
2015         if (update_kernel_vm_end && kernel_vm_end < kstart)
2016                 kernel_vm_end = kstart;
2017
2018         vm_object_drop(kptobj);
2019 }
2020
2021 /*
2022  *      Retire the given physical map from service.
2023  *      Should only be called if the map contains
2024  *      no valid mappings.
2025  */
2026 void
2027 pmap_destroy(pmap_t pmap)
2028 {
2029         int count;
2030
2031         if (pmap == NULL)
2032                 return;
2033
2034         lwkt_gettoken(&pmap->pm_token);
2035         count = --pmap->pm_count;
2036         if (count == 0) {
2037                 pmap_release(pmap);     /* eats pm_token */
2038                 panic("destroying a pmap is not yet implemented");
2039         }
2040         lwkt_reltoken(&pmap->pm_token);
2041 }
2042
2043 /*
2044  *      Add a reference to the specified pmap.
2045  */
2046 void
2047 pmap_reference(pmap_t pmap)
2048 {
2049         if (pmap != NULL) {
2050                 lwkt_gettoken(&pmap->pm_token);
2051                 pmap->pm_count++;
2052                 lwkt_reltoken(&pmap->pm_token);
2053         }
2054 }
2055
2056 /***************************************************
2057 * page management routines.
2058  ***************************************************/
2059
2060 /*
2061  * free the pv_entry back to the free list.  This function may be
2062  * called from an interrupt.
2063  */
2064 static __inline
2065 void
2066 free_pv_entry(pv_entry_t pv)
2067 {
2068         atomic_add_int(&pv_entry_count, -1);
2069         KKASSERT(pv_entry_count >= 0);
2070         zfree(pvzone, pv);
2071 }
2072
2073 /*
2074  * get a new pv_entry, allocating a block from the system
2075  * when needed.  This function may be called from an interrupt.
2076  */
2077 static
2078 pv_entry_t
2079 get_pv_entry(void)
2080 {
2081         atomic_add_int(&pv_entry_count, 1);
2082         if (pv_entry_high_water &&
2083                 (pv_entry_count > pv_entry_high_water) &&
2084                 (pmap_pagedaemon_waken == 0)) {
2085                 pmap_pagedaemon_waken = 1;
2086                 wakeup(&vm_pages_needed);
2087         }
2088         return zalloc(pvzone);
2089 }
2090
2091 /*
2092  * This routine is very drastic, but can save the system
2093  * in a pinch.
2094  */
2095 void
2096 pmap_collect(void)
2097 {
2098         int i;
2099         vm_page_t m;
2100         static int warningdone=0;
2101
2102         if (pmap_pagedaemon_waken == 0)
2103                 return;
2104         pmap_pagedaemon_waken = 0;
2105         if (warningdone < 5) {
2106                 kprintf("pmap_collect: collecting pv entries -- suggest increasing PMAP_SHPGPERPROC\n");
2107                 warningdone++;
2108         }
2109
2110         for (i = 0; i < vm_page_array_size; i++) {
2111                 m = &vm_page_array[i];
2112                 if (m->wire_count || m->hold_count)
2113                         continue;
2114                 if (vm_page_busy_try(m, TRUE) == 0) {
2115                         if (m->wire_count == 0 && m->hold_count == 0) {
2116                                 pmap_remove_all(m);
2117                         }
2118                         vm_page_wakeup(m);
2119                 }
2120         }
2121 }
2122         
2123
2124 /*
2125  * If it is the first entry on the list, it is actually in the header and
2126  * we must copy the following entry up to the header.
2127  *
2128  * Otherwise we must search the list for the entry.  In either case we
2129  * free the now unused entry.
2130  *
2131  * Caller must hold pmap->pm_token
2132  */
2133 static
2134 int
2135 pmap_remove_entry(struct pmap *pmap, vm_page_t m, 
2136                   vm_offset_t va, pmap_inval_info_t info)
2137 {
2138         pv_entry_t pv;
2139         int rtval;
2140
2141         spin_lock(&pmap_spin);
2142         if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
2143                 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2144                         if (pmap == pv->pv_pmap && va == pv->pv_va) 
2145                                 break;
2146                 }
2147         } else {
2148                 TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
2149                         if (va == pv->pv_va) 
2150                                 break;
2151                 }
2152         }
2153
2154         rtval = 0;
2155         KKASSERT(pv);
2156
2157         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2158         m->md.pv_generation++;
2159         m->md.pv_list_count--;
2160         vm_page_spin_lock(m);
2161         if (m->object)
2162                 atomic_add_int(&m->object->agg_pv_list_count, -1);
2163         vm_page_spin_unlock(m);
2164         KKASSERT(m->md.pv_list_count >= 0);
2165         if (TAILQ_EMPTY(&m->md.pv_list))
2166                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2167         TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2168         ++pmap->pm_generation;
2169         spin_unlock(&pmap_spin);
2170
2171         rtval = pmap_unwire_pte_hold(pmap, va, pv->pv_ptem, info);
2172         free_pv_entry(pv);
2173
2174         return rtval;
2175 }
2176
2177 /*
2178  * Create a pv entry for page at pa for (pmap, va).
2179  *
2180  * Caller must hold pmap token
2181  */
2182 static
2183 void
2184 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
2185 {
2186         pv_entry_t pv;
2187
2188         pv = get_pv_entry();
2189         pv->pv_va = va;
2190         pv->pv_pmap = pmap;
2191         pv->pv_ptem = mpte;
2192
2193         spin_lock(&pmap_spin);
2194         TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
2195         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2196         m->md.pv_generation++;
2197         m->md.pv_list_count++;
2198         vm_page_spin_lock(m);
2199         if (m->object)
2200                 atomic_add_int(&m->object->agg_pv_list_count, 1);
2201         vm_page_spin_unlock(m);
2202         pmap->pm_generation++;
2203         spin_unlock(&pmap_spin);
2204 }
2205
2206 /*
2207  * pmap_remove_pte: do the things to unmap a page in a process
2208  *
2209  * Caller must hold pmap token
2210  * Caller must hold pmap object
2211  */
2212 static
2213 int
2214 pmap_remove_pte(struct pmap *pmap, pt_entry_t *ptq, vm_offset_t va,
2215                 pmap_inval_info_t info)
2216 {
2217         pt_entry_t oldpte;
2218         vm_page_t m;
2219         vm_page_t mpte;
2220         vm_pindex_t ptepindex;
2221
2222         ASSERT_LWKT_TOKEN_HELD(&pmap->pm_token);
2223
2224         pmap_inval_interlock(info, pmap, va);
2225         oldpte = pte_load_clear(ptq);
2226         pmap_inval_deinterlock(info, pmap);
2227         if (oldpte & PG_W)
2228                 pmap->pm_stats.wired_count -= 1;
2229         /*
2230          * Machines that don't support invlpg, also don't support
2231          * PG_G.  XXX PG_G is disabled for SMP so don't worry about
2232          * the SMP case.
2233          */
2234         if (oldpte & PG_G)
2235                 cpu_invlpg((void *)va);
2236         KKASSERT(pmap->pm_stats.resident_count > 0);
2237         --pmap->pm_stats.resident_count;
2238         if (oldpte & PG_MANAGED) {
2239                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
2240                 if (oldpte & PG_M) {
2241 #if defined(PMAP_DIAGNOSTIC)
2242                         if (pmap_nw_modified((pt_entry_t) oldpte)) {
2243                                 kprintf(
2244         "pmap_remove: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2245                                     va, oldpte);
2246                         }
2247 #endif
2248                         if (pmap_track_modified(va))
2249                                 vm_page_dirty(m);
2250                 }
2251                 if (oldpte & PG_A)
2252                         vm_page_flag_set(m, PG_REFERENCED);
2253                 return pmap_remove_entry(pmap, m, va, info);
2254         }
2255
2256         /*
2257          * Unmanaged pages in userspace still wire the PT page, we have
2258          * to look up the mpte for the PDE page and pass it in.
2259          */
2260         if (va < VM_MAX_USER_ADDRESS) {
2261                 ptepindex = pmap_pde_pindex(va);
2262                 mpte = vm_page_lookup(pmap->pm_pteobj, ptepindex);
2263                 KKASSERT(mpte);
2264         } else {
2265                 mpte = NULL;
2266         }
2267         return pmap_unwire_pte_hold(pmap, va, mpte, info);
2268 }
2269
2270 /*
2271  * Remove a single page from a process address space.
2272  *
2273  * This function may not be called from an interrupt if the pmap is
2274  * not kernel_pmap.
2275  *
2276  * Caller must hold pmap->pm_token
2277  * Caller must hold pmap object
2278  */
2279 static
2280 void
2281 pmap_remove_page(struct pmap *pmap, vm_offset_t va, pmap_inval_info_t info)
2282 {
2283         pt_entry_t *pte;
2284
2285         ASSERT_LWKT_TOKEN_HELD(&pmap->pm_token);
2286
2287         pte = pmap_pte(pmap, va);
2288         if (pte == NULL)
2289                 return;
2290         if ((*pte & PG_V) == 0)
2291                 return;
2292         pmap_remove_pte(pmap, pte, va, info);
2293 }
2294
2295 /*
2296  * Remove the given range of addresses from the specified map.
2297  *
2298  * It is assumed that the start and end are properly rounded to the page size.
2299  *
2300  * This function may not be called from an interrupt if the pmap is not
2301  * kernel_pmap.
2302  */
2303 void
2304 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
2305 {
2306         vm_offset_t va_next;
2307         pml4_entry_t *pml4e;
2308         pdp_entry_t *pdpe;
2309         pd_entry_t ptpaddr, *pde;
2310         pt_entry_t *pte;
2311         struct pmap_inval_info info;
2312
2313         if (pmap == NULL)
2314                 return;
2315
2316         vm_object_hold(pmap->pm_pteobj);
2317         lwkt_gettoken(&pmap->pm_token);
2318         if (pmap->pm_stats.resident_count == 0) {
2319                 lwkt_reltoken(&pmap->pm_token);
2320                 vm_object_drop(pmap->pm_pteobj);
2321                 return;
2322         }
2323
2324         pmap_inval_init(&info);
2325
2326         /*
2327          * special handling of removing one page.  a very
2328          * common operation and easy to short circuit some
2329          * code.
2330          */
2331         if (sva + PAGE_SIZE == eva) {
2332                 pde = pmap_pde(pmap, sva);
2333                 if (pde && (*pde & PG_PS) == 0) {
2334                         pmap_remove_page(pmap, sva, &info);
2335                         pmap_inval_done(&info);
2336                         lwkt_reltoken(&pmap->pm_token);
2337                         vm_object_drop(pmap->pm_pteobj);
2338                         return;
2339                 }
2340         }
2341
2342         for (; sva < eva; sva = va_next) {
2343                 pml4e = pmap_pml4e(pmap, sva);
2344                 if ((*pml4e & PG_V) == 0) {
2345                         va_next = (sva + NBPML4) & ~PML4MASK;
2346                         if (va_next < sva)
2347                                 va_next = eva;
2348                         continue;
2349                 }
2350
2351                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2352                 if ((*pdpe & PG_V) == 0) {
2353                         va_next = (sva + NBPDP) & ~PDPMASK;
2354                         if (va_next < sva)
2355                                 va_next = eva;
2356                         continue;
2357                 }
2358
2359                 /*
2360                  * Calculate index for next page table.
2361                  */
2362                 va_next = (sva + NBPDR) & ~PDRMASK;
2363                 if (va_next < sva)
2364                         va_next = eva;
2365
2366                 pde = pmap_pdpe_to_pde(pdpe, sva);
2367                 ptpaddr = *pde;
2368
2369                 /*
2370                  * Weed out invalid mappings.
2371                  */
2372                 if (ptpaddr == 0)
2373                         continue;
2374
2375                 /*
2376                  * Check for large page.
2377                  */
2378                 if ((ptpaddr & PG_PS) != 0) {
2379                         /* JG FreeBSD has more complex treatment here */
2380                         pmap_inval_interlock(&info, pmap, -1);
2381                         *pde = 0;
2382                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2383                         pmap_inval_deinterlock(&info, pmap);
2384                         continue;
2385                 }
2386
2387                 /*
2388                  * Limit our scan to either the end of the va represented
2389                  * by the current page table page, or to the end of the
2390                  * range being removed.
2391                  */
2392                 if (va_next > eva)
2393                         va_next = eva;
2394
2395                 /*
2396                  * NOTE: pmap_remove_pte() can block.
2397                  */
2398                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2399                     sva += PAGE_SIZE) {
2400                         if (*pte == 0)
2401                                 continue;
2402                         if (pmap_remove_pte(pmap, pte, sva, &info))
2403                                 break;
2404                 }
2405         }
2406         pmap_inval_done(&info);
2407         lwkt_reltoken(&pmap->pm_token);
2408         vm_object_drop(pmap->pm_pteobj);
2409 }
2410
2411 /*
2412  * Removes this physical page from all physical maps in which it resides.
2413  * Reflects back modify bits to the pager.
2414  *
2415  * This routine may not be called from an interrupt.
2416  */
2417 static
2418 void
2419 pmap_remove_all(vm_page_t m)
2420 {
2421         struct pmap_inval_info info;
2422         pt_entry_t *pte, tpte;
2423         pv_entry_t pv;
2424         struct pmap *pmap;
2425
2426         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2427                 return;
2428
2429         pmap_inval_init(&info);
2430         spin_lock(&pmap_spin);
2431         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2432                 /*
2433                  * We have to be holding the pmap token to interlock
2434                  * the pte destruction and pv removal.  XXX need hold on
2435                  * pmap.
2436                  */
2437                 pmap = pv->pv_pmap;
2438                 spin_unlock(&pmap_spin);
2439                 lwkt_gettoken(&pmap->pm_token); /* XXX hold race */
2440                 spin_lock(&pmap_spin);
2441                 if (pv != TAILQ_FIRST(&m->md.pv_list)) {
2442                         spin_unlock(&pmap_spin);
2443                         lwkt_reltoken(&pmap->pm_token);
2444                         spin_lock(&pmap_spin);
2445                         continue;
2446                 }
2447
2448                 /*
2449                  * Remove the pv
2450                  */
2451                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2452                 TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2453                 m->md.pv_generation++;
2454                 m->md.pv_list_count--;
2455                 vm_page_spin_lock(m);
2456                 if (m->object)
2457                         atomic_add_int(&m->object->agg_pv_list_count, -1);
2458                 vm_page_spin_unlock(m);
2459                 KKASSERT(m->md.pv_list_count >= 0);
2460                 ++pv->pv_pmap->pm_generation;
2461                 spin_unlock(&pmap_spin);
2462
2463                 /*
2464                  * pv is now isolated
2465                  */
2466                 KKASSERT(pv->pv_pmap->pm_stats.resident_count > 0);
2467                 --pv->pv_pmap->pm_stats.resident_count;
2468
2469                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2470                 pmap_inval_interlock(&info, pv->pv_pmap, pv->pv_va);
2471                 tpte = pte_load_clear(pte);
2472                 KKASSERT(tpte & PG_MANAGED);
2473                 if (tpte & PG_W)
2474                         pv->pv_pmap->pm_stats.wired_count--;
2475                 pmap_inval_deinterlock(&info, pv->pv_pmap);
2476                 if (tpte & PG_A)
2477                         vm_page_flag_set(m, PG_REFERENCED);
2478
2479                 /*
2480                  * Update the vm_page_t clean and reference bits.
2481                  */
2482                 if (tpte & PG_M) {
2483 #if defined(PMAP_DIAGNOSTIC)
2484                         if (pmap_nw_modified(tpte)) {
2485                                 kprintf("pmap_remove_all: modified page not "
2486                                         "writable: va: 0x%lx, pte: 0x%lx\n",
2487                                         pv->pv_va, tpte);
2488                         }
2489 #endif
2490                         if (pmap_track_modified(pv->pv_va))
2491                                 vm_page_dirty(m); /* XXX races(m) */
2492                 }
2493
2494                 spin_lock(&pmap_spin);
2495                 if (TAILQ_EMPTY(&m->md.pv_list))
2496                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2497                 spin_unlock(&pmap_spin);
2498
2499                 pmap_unwire_pte_hold(pv->pv_pmap, pv->pv_va,
2500                                      pv->pv_ptem, &info);
2501                 lwkt_reltoken(&pv->pv_pmap->pm_token);
2502
2503                 free_pv_entry(pv);
2504                 spin_lock(&pmap_spin);
2505         }
2506         spin_unlock(&pmap_spin);
2507         KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
2508         pmap_inval_done(&info);
2509 }
2510
2511 /*
2512  * pmap_protect:
2513  *
2514  *      Set the physical protection on the specified range of this map
2515  *      as requested.
2516  *
2517  *      This function may not be called from an interrupt if the map is
2518  *      not the kernel_pmap.
2519  */
2520 void
2521 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2522 {
2523         vm_offset_t va_next;
2524         pml4_entry_t *pml4e;
2525         pdp_entry_t *pdpe;
2526         pd_entry_t ptpaddr, *pde;
2527         pt_entry_t *pte;
2528         pmap_inval_info info;
2529
2530         /* JG review for NX */
2531
2532         if (pmap == NULL)
2533                 return;
2534
2535         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2536                 pmap_remove(pmap, sva, eva);
2537                 return;
2538         }
2539
2540         if (prot & VM_PROT_WRITE)
2541                 return;
2542
2543         lwkt_gettoken(&pmap->pm_token);
2544         pmap_inval_init(&info);
2545
2546         for (; sva < eva; sva = va_next) {
2547                 pml4e = pmap_pml4e(pmap, sva);
2548                 if ((*pml4e & PG_V) == 0) {
2549                         va_next = (sva + NBPML4) & ~PML4MASK;
2550                         if (va_next < sva)
2551                                 va_next = eva;
2552                         continue;
2553                 }
2554
2555                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
2556                 if ((*pdpe & PG_V) == 0) {
2557                         va_next = (sva + NBPDP) & ~PDPMASK;
2558                         if (va_next < sva)
2559                                 va_next = eva;
2560                         continue;
2561                 }
2562
2563                 va_next = (sva + NBPDR) & ~PDRMASK;
2564                 if (va_next < sva)
2565                         va_next = eva;
2566
2567                 pde = pmap_pdpe_to_pde(pdpe, sva);
2568                 ptpaddr = *pde;
2569
2570                 /*
2571                  * Check for large page.
2572                  */
2573                 if ((ptpaddr & PG_PS) != 0) {
2574                         pmap_inval_interlock(&info, pmap, -1);
2575                         *pde &= ~(PG_M|PG_RW);
2576                         pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2577                         pmap_inval_deinterlock(&info, pmap);
2578                         continue;
2579                 }
2580
2581                 /*
2582                  * Weed out invalid mappings. Note: we assume that the page
2583                  * directory table is always allocated, and in kernel virtual.
2584                  */
2585                 if (ptpaddr == 0)
2586                         continue;
2587
2588                 if (va_next > eva)
2589                         va_next = eva;
2590
2591                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
2592                      sva += PAGE_SIZE) {
2593                         pt_entry_t pbits;
2594                         pt_entry_t cbits;
2595                         vm_page_t m;
2596
2597                         /*
2598                          * XXX non-optimal.
2599                          */
2600                         pmap_inval_interlock(&info, pmap, sva);
2601 again:
2602                         pbits = *pte;
2603                         cbits = pbits;
2604                         if ((pbits & PG_V) == 0) {
2605                                 pmap_inval_deinterlock(&info, pmap);
2606                                 continue;
2607                         }
2608                         if (pbits & PG_MANAGED) {
2609                                 m = NULL;
2610                                 if (pbits & PG_A) {
2611                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2612                                         vm_page_flag_set(m, PG_REFERENCED);
2613                                         cbits &= ~PG_A;
2614                                 }
2615                                 if (pbits & PG_M) {
2616                                         if (pmap_track_modified(sva)) {
2617                                                 if (m == NULL)
2618                                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
2619                                                 vm_page_dirty(m);
2620                                                 cbits &= ~PG_M;
2621                                         }
2622                                 }
2623                         }
2624                         cbits &= ~PG_RW;
2625                         if (pbits != cbits &&
2626                             !atomic_cmpset_long(pte, pbits, cbits)) {
2627                                 goto again;
2628                         }
2629                         pmap_inval_deinterlock(&info, pmap);
2630                 }
2631         }
2632         pmap_inval_done(&info);
2633         lwkt_reltoken(&pmap->pm_token);
2634 }
2635
2636 /*
2637  *      Insert the given physical page (p) at
2638  *      the specified virtual address (v) in the
2639  *      target physical map with the protection requested.
2640  *
2641  *      If specified, the page will be wired down, meaning
2642  *      that the related pte can not be reclaimed.
2643  *
2644  *      NB:  This is the only routine which MAY NOT lazy-evaluate
2645  *      or lose information.  That is, this routine must actually
2646  *      insert this page into the given map NOW.
2647  */
2648 void
2649 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2650            boolean_t wired)
2651 {
2652         vm_paddr_t pa;
2653         pd_entry_t *pde;
2654         pt_entry_t *pte;
2655         vm_paddr_t opa;
2656         pt_entry_t origpte, newpte;
2657         vm_page_t mpte;
2658         pmap_inval_info info;
2659
2660         if (pmap == NULL)
2661                 return;
2662
2663         va = trunc_page(va);
2664 #ifdef PMAP_DIAGNOSTIC
2665         if (va >= KvaEnd)
2666                 panic("pmap_enter: toobig");
2667         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
2668                 panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)", va);
2669 #endif
2670         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2671                 kprintf("Warning: pmap_enter called on UVA with kernel_pmap\n");
2672 #ifdef DDB
2673                 db_print_backtrace();
2674 #endif
2675         }
2676         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2677                 kprintf("Warning: pmap_enter called on KVA without kernel_pmap\n");
2678 #ifdef DDB
2679                 db_print_backtrace();
2680 #endif
2681         }
2682
2683         vm_object_hold(pmap->pm_pteobj);
2684         lwkt_gettoken(&pmap->pm_token);
2685
2686         /*
2687          * In the case that a page table page is not
2688          * resident, we are creating it here.
2689          */
2690         if (va < VM_MAX_USER_ADDRESS)
2691                 mpte = pmap_allocpte(pmap, va);
2692         else
2693                 mpte = NULL;
2694
2695         if ((prot & VM_PROT_NOSYNC) == 0)
2696                 pmap_inval_init(&info);
2697         pde = pmap_pde(pmap, va);
2698         if (pde != NULL && (*pde & PG_V) != 0) {
2699                 if ((*pde & PG_PS) != 0)
2700                         panic("pmap_enter: attempted pmap_enter on 2MB page");
2701                 pte = pmap_pde_to_pte(pde, va);
2702         } else {
2703                 panic("pmap_enter: invalid page directory va=%#lx", va);
2704         }
2705
2706         KKASSERT(pte != NULL);
2707         pa = VM_PAGE_TO_PHYS(m);
2708         origpte = *pte;
2709         opa = origpte & PG_FRAME;
2710
2711         /*
2712          * Mapping has not changed, must be protection or wiring change.
2713          */
2714         if (origpte && (opa == pa)) {
2715                 /*
2716                  * Wiring change, just update stats. We don't worry about
2717                  * wiring PT pages as they remain resident as long as there
2718                  * are valid mappings in them. Hence, if a user page is wired,
2719                  * the PT page will be also.
2720                  */
2721                 if (wired && ((origpte & PG_W) == 0))
2722                         pmap->pm_stats.wired_count++;
2723                 else if (!wired && (origpte & PG_W))
2724                         pmap->pm_stats.wired_count--;
2725
2726 #if defined(PMAP_DIAGNOSTIC)
2727                 if (pmap_nw_modified(origpte)) {
2728                         kprintf(
2729         "pmap_enter: modified page not writable: va: 0x%lx, pte: 0x%lx\n",
2730                             va, origpte);
2731                 }
2732 #endif
2733
2734                 /*
2735                  * Remove the extra pte reference.  Note that we cannot
2736                  * optimize the RO->RW case because we have adjusted the
2737                  * wiring count above and may need to adjust the wiring
2738                  * bits below.
2739                  */
2740                 if (mpte)
2741                         vm_page_unwire_quick(mpte);
2742
2743                 /*
2744                  * We might be turning off write access to the page,
2745                  * so we go ahead and sense modify status.
2746                  */
2747                 if (origpte & PG_MANAGED) {
2748                         if ((origpte & PG_M) && pmap_track_modified(va)) {
2749                                 vm_page_t om;
2750                                 om = PHYS_TO_VM_PAGE(opa);
2751                                 vm_page_dirty(om);
2752                         }
2753                         pa |= PG_MANAGED;
2754                         KKASSERT(m->flags & PG_MAPPED);
2755                 }
2756                 goto validate;
2757         } 
2758         /*
2759          * Mapping has changed, invalidate old range and fall through to
2760          * handle validating new mapping.
2761          */
2762         while (opa) {
2763                 int err;
2764                 err = pmap_remove_pte(pmap, pte, va, &info);
2765                 if (err)
2766                         panic("pmap_enter: pte vanished, va: 0x%lx", va);
2767                 origpte = *pte;
2768                 opa = origpte & PG_FRAME;
2769                 if (opa) {
2770                         kprintf("pmap_enter: Warning, raced pmap %p va %p\n",
2771                                 pmap, (void *)va);
2772                 }
2773         }
2774
2775         /*
2776          * Enter on the PV list if part of our managed memory. Note that we
2777          * raise IPL while manipulating pv_table since pmap_enter can be
2778          * called at interrupt time.
2779          *
2780          * The new mapping covers mpte's new wiring count so we don't
2781          * unwire it.
2782          */
2783         if (pmap_initialized && 
2784             (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2785                 pmap_insert_entry(pmap, va, mpte, m);
2786                 pa |= PG_MANAGED;
2787                 vm_page_flag_set(m, PG_MAPPED);
2788         }
2789
2790         /*
2791          * Increment counters
2792          */
2793         ++pmap->pm_stats.resident_count;
2794         if (wired)
2795                 pmap->pm_stats.wired_count++;
2796
2797 validate:
2798         /*
2799          * Now validate mapping with desired protection/wiring.
2800          */
2801         newpte = (pt_entry_t) (pa | pte_prot(pmap, prot) | PG_V);
2802
2803         if (wired)
2804                 newpte |= PG_W;
2805         if (va < VM_MAX_USER_ADDRESS)
2806                 newpte |= PG_U;
2807         if (pmap == &kernel_pmap)
2808                 newpte |= pgeflag;
2809
2810         /*
2811          * if the mapping or permission bits are different, we need
2812          * to update the pte.
2813          */
2814         if ((origpte & ~(PG_M|PG_A)) != newpte) {
2815                 if ((prot & VM_PROT_NOSYNC) == 0)
2816                         pmap_inval_interlock(&info, pmap, va);
2817                 *pte = newpte | PG_A;
2818                 if (prot & VM_PROT_NOSYNC)
2819                         cpu_invlpg((void *)va);
2820                 else
2821                         pmap_inval_deinterlock(&info, pmap);
2822                 if (newpte & PG_RW)
2823                         vm_page_flag_set(m, PG_WRITEABLE);
2824         }
2825         KKASSERT((newpte & PG_MANAGED) == 0 || (m->flags & PG_MAPPED));
2826         if ((prot & VM_PROT_NOSYNC) == 0)
2827                 pmap_inval_done(&info);
2828         lwkt_reltoken(&pmap->pm_token);
2829         vm_object_drop(pmap->pm_pteobj);
2830 }
2831
2832 /*
2833  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
2834  * This code also assumes that the pmap has no pre-existing entry for this
2835  * VA.
2836  *
2837  * This code currently may only be used on user pmaps, not kernel_pmap.
2838  */
2839 void
2840 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
2841 {
2842         pt_entry_t *pte;
2843         vm_paddr_t pa;
2844         vm_page_t mpte;
2845         pmap_inval_info info;
2846
2847         lwkt_gettoken(&pmap->pm_token);
2848         vm_object_hold(pmap->pm_pteobj);
2849         pmap_inval_init(&info);
2850
2851         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
2852                 kprintf("Warning: pmap_enter_quick called on UVA with"
2853                         "kernel_pmap\n");
2854 #ifdef DDB
2855                 db_print_backtrace();
2856 #endif
2857         }
2858         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
2859                 kprintf("Warning: pmap_enter_quick called on KVA without"
2860                         "kernel_pmap\n");
2861 #ifdef DDB
2862                 db_print_backtrace();
2863 #endif
2864         }
2865
2866         KKASSERT(va < UPT_MIN_ADDRESS); /* assert used on user pmaps only */
2867
2868         /*
2869          * Calculate the page table page (mpte), allocating it if necessary.
2870          *
2871          * A wired page table page (mpte), or NULL, is passed onto the
2872          * section following.
2873          */
2874         if (va < VM_MAX_USER_ADDRESS) {
2875                 mpte = pmap_allocpte(pmap, va);
2876         } else {
2877                 mpte = NULL;
2878                 /* this code path is not yet used */
2879         }
2880
2881         /*
2882          * With a valid (and held) page directory page, we can just use
2883          * vtopte() to get to the pte.  If the pte is already present
2884          * we do not disturb it.
2885          */
2886         pte = vtopte(va);
2887         if (*pte & PG_V) {
2888                 pa = VM_PAGE_TO_PHYS(m);
2889                 KKASSERT(((*pte ^ pa) & PG_FRAME) == 0);
2890                 pmap_inval_done(&info);
2891                 if (mpte)
2892                         pmap_unwire_pte_hold(pmap, va, mpte, &info);
2893                 vm_object_drop(pmap->pm_pteobj);
2894                 lwkt_reltoken(&pmap->pm_token);
2895                 return;
2896         }
2897
2898         /*
2899          * Enter on the PV list if part of our managed memory.
2900          *
2901          * The new mapping covers mpte's new wiring count so we don't
2902          * unwire it.
2903          */
2904         if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
2905                 pmap_insert_entry(pmap, va, mpte, m);
2906                 vm_page_flag_set(m, PG_MAPPED);
2907         }
2908
2909         /*
2910          * Increment counters
2911          */
2912         ++pmap->pm_stats.resident_count;
2913
2914         pa = VM_PAGE_TO_PHYS(m);
2915
2916         /*
2917          * Now validate mapping with RO protection
2918          */
2919         if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2920                 *pte = pa | PG_V | PG_U;
2921         else
2922                 *pte = pa | PG_V | PG_U | PG_MANAGED;
2923 /*      pmap_inval_add(&info, pmap, va); shouldn't be needed inval->valid */
2924         pmap_inval_done(&info);
2925         vm_object_drop(pmap->pm_pteobj);
2926         lwkt_reltoken(&pmap->pm_token);
2927 }
2928
2929 /*
2930  * Make a temporary mapping for a physical address.  This is only intended
2931  * to be used for panic dumps.
2932  *
2933  * The caller is responsible for calling smp_invltlb().
2934  */
2935 void *
2936 pmap_kenter_temporary(vm_paddr_t pa, long i)
2937 {
2938         pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
2939         return ((void *)crashdumpmap);
2940 }
2941
2942 #define MAX_INIT_PT (96)
2943
2944 /*
2945  * This routine preloads the ptes for a given object into the specified pmap.
2946  * This eliminates the blast of soft faults on process startup and
2947  * immediately after an mmap.
2948  */
2949 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
2950
2951 void
2952 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
2953                     vm_object_t object, vm_pindex_t pindex, 
2954                     vm_size_t size, int limit)
2955 {
2956         struct rb_vm_page_scan_info info;
2957         struct lwp *lp;
2958         vm_size_t psize;
2959
2960         /*
2961          * We can't preinit if read access isn't set or there is no pmap
2962          * or object.
2963          */
2964         if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
2965                 return;
2966
2967         /*
2968          * We can't preinit if the pmap is not the current pmap
2969          */
2970         lp = curthread->td_lwp;
2971         if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
2972                 return;
2973
2974         psize = x86_64_btop(size);
2975
2976         if ((object->type != OBJT_VNODE) ||
2977                 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
2978                         (object->resident_page_count > MAX_INIT_PT))) {
2979                 return;
2980         }
2981
2982         if (psize + pindex > object->size) {
2983                 if (object->size < pindex)
2984                         return;           
2985                 psize = object->size - pindex;
2986         }
2987
2988         if (psize == 0)
2989                 return;
2990
2991         /*
2992          * Use a red-black scan to traverse the requested range and load
2993          * any valid pages found into the pmap.
2994          *
2995          * We cannot safely scan the object's memq without holding the
2996          * object token.
2997          */
2998         info.start_pindex = pindex;
2999         info.end_pindex = pindex + psize - 1;
3000         info.limit = limit;
3001         info.mpte = NULL;
3002         info.addr = addr;
3003         info.pmap = pmap;
3004         info.desired = 0;
3005
3006         vm_object_hold(object);
3007         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
3008                                 pmap_object_init_pt_callback, &info);
3009         vm_object_drop(object);
3010 }
3011
3012 static
3013 int
3014 pmap_object_init_pt_callback(vm_page_t p, void *data)
3015 {
3016         struct rb_vm_page_scan_info *info = data;
3017         vm_pindex_t rel_index;
3018
3019         /*
3020          * don't allow an madvise to blow away our really
3021          * free pages allocating pv entries.
3022          */
3023         if ((info->limit & MAP_PREFAULT_MADVISE) &&
3024                 vmstats.v_free_count < vmstats.v_free_reserved) {
3025                     return(-1);
3026         }
3027         if (vm_page_busy_try(p, TRUE))
3028                 return 0;
3029         if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
3030             (p->flags & PG_FICTITIOUS) == 0) {
3031                 if ((p->queue - p->pc) == PQ_CACHE)
3032                         vm_page_deactivate(p);
3033                 rel_index = p->pindex - info->start_pindex;
3034                 pmap_enter_quick(info->pmap,
3035                                  info->addr + x86_64_ptob(rel_index), p);
3036         }
3037         vm_page_wakeup(p);
3038         pmap_auto_yield(info);
3039         return(0);
3040 }
3041
3042 /*
3043  * Return TRUE if the pmap is in shape to trivially
3044  * pre-fault the specified address.
3045  *
3046  * Returns FALSE if it would be non-trivial or if a
3047  * pte is already loaded into the slot.
3048  */
3049 int
3050 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
3051 {
3052         pt_entry_t *pte;
3053         pd_entry_t *pde;
3054         int ret;
3055
3056         lwkt_gettoken(&pmap->pm_token);
3057         pde = pmap_pde(pmap, addr);
3058         if (pde == NULL || *pde == 0) {
3059                 ret = 0;
3060         } else {
3061                 pte = vtopte(addr);
3062                 ret = (*pte) ? 0 : 1;
3063         }
3064         lwkt_reltoken(&pmap->pm_token);
3065         return(ret);
3066 }
3067
3068 /*
3069  *      Routine:        pmap_change_wiring
3070  *      Function:       Change the wiring attribute for a map/virtual-address
3071  *                      pair.
3072  *      In/out conditions:
3073  *                      The mapping must already exist in the pmap.
3074  */
3075 void
3076 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired)
3077 {
3078         pt_entry_t *pte;
3079
3080         if (pmap == NULL)
3081                 return;
3082
3083         lwkt_gettoken(&pmap->pm_token);
3084         pte = pmap_pte(pmap, va);
3085
3086         if (wired && !pmap_pte_w(pte))
3087                 pmap->pm_stats.wired_count++;
3088         else if (!wired && pmap_pte_w(pte))
3089                 pmap->pm_stats.wired_count--;
3090
3091         /*
3092          * Wiring is not a hardware characteristic so there is no need to
3093          * invalidate TLB.  However, in an SMP environment we must use
3094          * a locked bus cycle to update the pte (if we are not using 
3095          * the pmap_inval_*() API that is)... it's ok to do this for simple
3096          * wiring changes.
3097          */
3098 #ifdef SMP
3099         if (wired)
3100                 atomic_set_long(pte, PG_W);
3101         else
3102                 atomic_clear_long(pte, PG_W);
3103 #else
3104         if (wired)
3105                 atomic_set_long_nonlocked(pte, PG_W);
3106         else
3107                 atomic_clear_long_nonlocked(pte, PG_W);
3108 #endif
3109         lwkt_reltoken(&pmap->pm_token);
3110 }
3111
3112
3113
3114 /*
3115  * Copy the range specified by src_addr/len from the source map to
3116  * the range dst_addr/len in the destination map.
3117  *
3118  * This routine is only advisory and need not do anything.
3119  */
3120 void
3121 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, 
3122           vm_size_t len, vm_offset_t src_addr)
3123 {
3124         return;
3125 #if 0
3126         pmap_inval_info info;
3127         vm_offset_t addr;
3128         vm_offset_t end_addr = src_addr + len;
3129         vm_offset_t pdnxt;
3130         pd_entry_t src_frame, dst_frame;
3131         vm_page_t m;
3132
3133         if (dst_addr != src_addr)
3134                 return;
3135 #if JGPMAP32
3136         src_frame = src_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
3137         if (src_frame != (PTDpde & PG_FRAME)) {
3138                 return;
3139         }
3140
3141         dst_frame = dst_pmap->pm_pdir[PTDPTDI] & PG_FRAME;
3142         if (dst_frame != (APTDpde & PG_FRAME)) {
3143                 APTDpde = (pd_entry_t) (dst_frame | PG_RW | PG_V);
3144                 /* The page directory is not shared between CPUs */
3145                 cpu_invltlb();
3146         }
3147 #endif
3148         pmap_inval_init(&info);
3149         pmap_inval_add(&info, dst_pmap, -1);
3150         pmap_inval_add(&info, src_pmap, -1);
3151
3152         lwkt_gettoken(&src_pmap->pm_token);
3153         lwkt_gettoken(&dst_pmap->pm_token);
3154         for (addr = src_addr; addr < end_addr; addr = pdnxt) {
3155                 pt_entry_t *src_pte, *dst_pte;
3156                 vm_page_t dstmpte, srcmpte;
3157                 vm_offset_t srcptepaddr;
3158                 vm_pindex_t ptepindex;
3159
3160                 if (addr >= UPT_MIN_ADDRESS)
3161                         panic("pmap_copy: invalid to pmap_copy page tables\n");
3162
3163                 /*
3164                  * Don't let optional prefaulting of pages make us go
3165                  * way below the low water mark of free pages or way
3166                  * above high water mark of used pv entries.
3167                  */
3168                 if (vmstats.v_free_count < vmstats.v_free_reserved ||
3169                     pv_entry_count > pv_entry_high_water)
3170                         break;
3171                 
3172                 pdnxt = ((addr + PAGE_SIZE*NPTEPG) & ~(PAGE_SIZE*NPTEPG - 1));
3173                 ptepindex = addr >> PDRSHIFT;
3174
3175 #if JGPMAP32
3176                 srcptepaddr = (vm_offset_t) src_pmap->pm_pdir[ptepindex];
3177 #endif
3178                 if (srcptepaddr == 0)
3179                         continue;
3180                         
3181                 if (srcptepaddr & PG_PS) {
3182 #if JGPMAP32
3183                         if (dst_pmap->pm_pdir[ptepindex] == 0) {
3184                                 dst_pmap->pm_pdir[ptepindex] = (pd_entry_t) srcptepaddr;
3185                                 dst_pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
3186                         }
3187 #endif
3188                         continue;
3189                 }
3190
3191                 /*
3192                  *
3193                  */
3194                 srcmpte = vm_page_lookup(src_pmap->pm_pteobj, ptepindex);
3195                 if (srcmpte == NULL || srcmpte->wire_count == 1 ||
3196                     (srcmpte->flags & PG_BUSY)) {
3197                         continue;
3198                 }
3199
3200                 if (pdnxt > end_addr)
3201                         pdnxt = end_addr;
3202
3203                 src_pte = vtopte(addr);
3204 #if JGPMAP32
3205                 dst_pte = avtopte(addr);
3206 #endif
3207                 while (addr < pdnxt) {
3208                         pt_entry_t ptetemp;
3209
3210                         ptetemp = *src_pte;
3211                         /*
3212                          * we only virtual copy managed pages
3213                          */
3214                         if ((ptetemp & PG_MANAGED) != 0) {
3215                                 /*
3216                                  * We have to check after allocpte for the
3217                                  * pte still being around...  allocpte can
3218                                  * block.
3219                                  *
3220                                  * pmap_allocpte() can block.  If we lose
3221                                  * our page directory mappings we stop.
3222                                  */
3223                                 dstmpte = pmap_allocpte(dst_pmap, addr);
3224
3225 #if JGPMAP32
3226                                 if (src_frame != (PTDpde & PG_FRAME) ||
3227                                     dst_frame != (APTDpde & PG_FRAME)
3228                                 ) {
3229                                         kprintf("WARNING: pmap_copy: detected and corrected race\n");
3230                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3231                                         goto failed;
3232                                 } else if ((*dst_pte == 0) &&
3233                                            (ptetemp = *src_pte) != 0 &&
3234                                            (ptetemp & PG_MANAGED)) {
3235                                         /*
3236                                          * Clear the modified and
3237                                          * accessed (referenced) bits
3238                                          * during the copy.
3239                                          */
3240                                         m = PHYS_TO_VM_PAGE(ptetemp);
3241                                         *dst_pte = ptetemp & ~(PG_M | PG_A);
3242                                         ++dst_pmap->pm_stats.resident_count;
3243                                         pmap_insert_entry(dst_pmap, addr,
3244                                                           dstmpte, m);
3245                                         KKASSERT(m->flags & PG_MAPPED);
3246                                 } else {
3247                                         kprintf("WARNING: pmap_copy: dst_pte race detected and corrected\n");
3248                                         pmap_unwire_pte_hold(dst_pmap, dstmpte, &info);
3249                                         goto failed;
3250                                 }
3251 #endif
3252                                 if (dstmpte->hold_count >= srcmpte->hold_count)
3253                                         break;
3254                         }
3255                         addr += PAGE_SIZE;
3256                         src_pte++;
3257                         dst_pte++;
3258                 }
3259         }
3260 failed:
3261         lwkt_reltoken(&dst_pmap->pm_token);
3262         lwkt_reltoken(&src_pmap->pm_token);
3263         pmap_inval_done(&info);
3264 #endif
3265 }       
3266
3267 /*
3268  * pmap_zero_page:
3269  *
3270  *      Zero the specified physical page.
3271  *
3272  *      This function may be called from an interrupt and no locking is
3273  *      required.
3274  */
3275 void
3276 pmap_zero_page(vm_paddr_t phys)
3277 {
3278         vm_offset_t va = PHYS_TO_DMAP(phys);
3279
3280         pagezero((void *)va);
3281 }
3282
3283 /*
3284  * pmap_page_assertzero:
3285  *
3286  *      Assert that a page is empty, panic if it isn't.
3287  */
3288 void
3289 pmap_page_assertzero(vm_paddr_t phys)
3290 {
3291         vm_offset_t va = PHYS_TO_DMAP(phys);
3292         size_t i;
3293
3294         for (i = 0; i < PAGE_SIZE; i += sizeof(long)) {
3295                 if (*(long *)((char *)va + i) != 0) {
3296                         panic("pmap_page_assertzero() @ %p not zero!\n",
3297                               (void *)(intptr_t)va);
3298                 }
3299         }
3300 }
3301
3302 /*
3303  * pmap_zero_page:
3304  *
3305  *      Zero part of a physical page by mapping it into memory and clearing
3306  *      its contents with bzero.
3307  *
3308  *      off and size may not cover an area beyond a single hardware page.
3309  */
3310 void
3311 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
3312 {
3313         vm_offset_t virt = PHYS_TO_DMAP(phys);
3314
3315         bzero((char *)virt + off, size);
3316 }
3317
3318 /*
3319  * pmap_copy_page:
3320  *
3321  *      Copy the physical page from the source PA to the target PA.
3322  *      This function may be called from an interrupt.  No locking
3323  *      is required.
3324  */
3325 void
3326 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
3327 {
3328         vm_offset_t src_virt, dst_virt;
3329
3330         src_virt = PHYS_TO_DMAP(src);
3331         dst_virt = PHYS_TO_DMAP(dst);
3332         bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
3333 }
3334
3335 /*
3336  * pmap_copy_page_frag:
3337  *
3338  *      Copy the physical page from the source PA to the target PA.
3339  *      This function may be called from an interrupt.  No locking
3340  *      is required.
3341  */
3342 void
3343 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
3344 {
3345         vm_offset_t src_virt, dst_virt;
3346
3347         src_virt = PHYS_TO_DMAP(src);
3348         dst_virt = PHYS_TO_DMAP(dst);
3349
3350         bcopy((char *)src_virt + (src & PAGE_MASK),
3351               (char *)dst_virt + (dst & PAGE_MASK),
3352               bytes);
3353 }
3354
3355 /*
3356  * Returns true if the pmap's pv is one of the first
3357  * 16 pvs linked to from this page.  This count may
3358  * be changed upwards or downwards in the future; it
3359  * is only necessary that true be returned for a small
3360  * subset of pmaps for proper page aging.
3361  */
3362 boolean_t
3363 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
3364 {
3365         pv_entry_t pv;
3366         int loops = 0;
3367
3368         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3369                 return FALSE;
3370
3371         spin_lock(&pmap_spin);
3372         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3373                 if (pv->pv_pmap == pmap) {
3374                         spin_unlock(&pmap_spin);
3375                         return TRUE;
3376                 }
3377                 loops++;
3378                 if (loops >= 16)
3379                         break;
3380         }
3381         spin_unlock(&pmap_spin);
3382         return (FALSE);
3383 }
3384
3385 /*
3386  * Remove all pages from specified address space this aids process exit
3387  * speeds.  Also, this code is special cased for current process only, but
3388  * can have the more generic (and slightly slower) mode enabled.  This
3389  * is much faster than pmap_remove in the case of running down an entire
3390  * address space.
3391  */
3392 void
3393 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3394 {
3395         struct lwp *lp;
3396         pt_entry_t *pte, tpte;
3397         pv_entry_t pv, npv;
3398         vm_page_t m;
3399         vm_offset_t va;
3400         pmap_inval_info info;
3401         int iscurrentpmap;
3402         int save_generation;
3403
3404         lp = curthread->td_lwp;
3405         if (lp && pmap == vmspace_pmap(lp->lwp_vmspace))
3406                 iscurrentpmap = 1;
3407         else
3408                 iscurrentpmap = 0;
3409
3410         if (pmap->pm_pteobj)
3411                 vm_object_hold(pmap->pm_pteobj);
3412         lwkt_gettoken(&pmap->pm_token);
3413         pmap_inval_init(&info);
3414
3415         spin_lock(&pmap_spin);
3416         for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
3417                 /*
3418                  * Validate the pv.  We have to interlock the address with
3419                  * pmap_spin unlocked.
3420                  */
3421                 if (pv->pv_va >= eva || pv->pv_va < sva) {
3422                         npv = TAILQ_NEXT(pv, pv_plist);
3423                         continue;
3424                 }
3425
3426                 KKASSERT(pmap == pv->pv_pmap);
3427                 if (iscurrentpmap)
3428                         pte = vtopte(pv->pv_va);
3429                 else
3430                         pte = pmap_pte_quick(pmap, pv->pv_va);
3431
3432                 /*
3433                  * We cannot remove wired pages from a process' mapping
3434                  * at this time.  This does not require an invaldiation
3435                  * interlock as PG_W cannot be set by the MMU.
3436                  */
3437                 if (*pte & PG_W) {
3438                         npv = TAILQ_NEXT(pv, pv_plist);
3439                         continue;
3440                 }
3441
3442                 /*
3443                  * Interlock the pte so we can safely remove it
3444                  */
3445                 save_generation = pmap->pm_generation;
3446                 va = pv->pv_va;
3447                 spin_unlock(&pmap_spin);
3448
3449                 pmap_inval_interlock(&info, pmap, va);
3450
3451                 /*
3452                  * Restart the scan if the pv list changed out from under us.
3453                  */
3454                 spin_lock(&pmap_spin);
3455                 if (save_generation != pmap->pm_generation) {
3456                         spin_unlock(&pmap_spin);
3457                         pmap_inval_deinterlock(&info, pmap);
3458                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3459                         spin_lock(&pmap_spin);
3460                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3461                         continue;
3462                 }
3463                 KKASSERT(pmap == pv->pv_pmap && va == pv->pv_va);
3464
3465                 /*
3466                  * Extract the pte and clear its memory
3467                  */
3468                 tpte = pte_load_clear(pte);
3469                 KKASSERT(tpte & PG_MANAGED);
3470
3471                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3472                 KASSERT(m < &vm_page_array[vm_page_array_size],
3473                         ("pmap_remove_pages: bad tpte %lx", tpte));
3474
3475                 /*
3476                  * Remove the entry, set npv
3477                  */
3478                 npv = TAILQ_NEXT(pv, pv_plist);
3479                 TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
3480                 m->md.pv_generation++;
3481                 m->md.pv_list_count--;
3482                 vm_page_spin_lock(m);
3483                 if (m->object)
3484                         atomic_add_int(&m->object->agg_pv_list_count, -1);
3485                 vm_page_spin_unlock(m);
3486                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3487                 if (TAILQ_EMPTY(&m->md.pv_list))
3488                         vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
3489                 save_generation = ++pmap->pm_generation;
3490
3491                 spin_unlock(&pmap_spin);
3492
3493                 /*
3494                  * Adjust the pmap and cleanup the tpte and related vm_page
3495                  */
3496                 KKASSERT(pmap->pm_stats.resident_count > 0);
3497                 --pmap->pm_stats.resident_count;
3498                 pmap_inval_deinterlock(&info, pmap);
3499
3500                 /*
3501                  * Update the vm_page_t clean and reference bits.
3502                  */
3503                 if (tpte & PG_M) {
3504                         vm_page_dirty(m);
3505                 }
3506
3507                 pmap_unwire_pte_hold(pmap, pv->pv_va, pv->pv_ptem, &info);
3508                 free_pv_entry(pv);
3509
3510                 /*
3511                  * Restart the scan if we blocked during the unuse or free
3512                  * calls and other removals were made.
3513                  */
3514                 spin_lock(&pmap_spin);
3515                 if (save_generation != pmap->pm_generation) {
3516                         kprintf("Warning: pmap_remove_pages race-A avoided\n");
3517                         npv = TAILQ_FIRST(&pmap->pm_pvlist);
3518                 }
3519         }
3520         spin_unlock(&pmap_spin);
3521         pmap_inval_done(&info);
3522         lwkt_reltoken(&pmap->pm_token);
3523         if (pmap->pm_pteobj)
3524                 vm_object_drop(pmap->pm_pteobj);
3525 }
3526
3527 /*
3528  * pmap_testbit tests bits in pte's note that the testbit/clearbit
3529  * routines are inline, and a lot of things compile-time evaluate.
3530  *
3531  * Caller must hold pmap_spin
3532  */
3533 static
3534 boolean_t
3535 pmap_testbit(vm_page_t m, int bit)
3536 {
3537         pv_entry_t pv;
3538         pt_entry_t *pte;
3539
3540         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3541                 return FALSE;
3542
3543         if (TAILQ_FIRST(&m->md.pv_list) == NULL)
3544                 return FALSE;
3545
3546         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3547                 /*
3548                  * if the bit being tested is the modified bit, then
3549                  * mark clean_map and ptes as never
3550                  * modified.
3551                  */
3552                 if (bit & (PG_A|PG_M)) {
3553                         if (!pmap_track_modified(pv->pv_va))
3554                                 continue;
3555                 }
3556
3557 #if defined(PMAP_DIAGNOSTIC)
3558                 if (pv->pv_pmap == NULL) {
3559                         kprintf("Null pmap (tb) at va: 0x%lx\n", pv->pv_va);
3560                         continue;
3561                 }
3562 #endif
3563                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3564                 if (*pte & bit)
3565                         return TRUE;
3566         }
3567         return (FALSE);
3568 }
3569
3570 /*
3571  * This routine is used to modify bits in ptes
3572  *
3573  * Caller must NOT hold pmap_spin
3574  */
3575 static __inline
3576 void
3577 pmap_clearbit(vm_page_t m, int bit)
3578 {
3579         struct pmap_inval_info info;
3580         int save_generation;
3581         vm_offset_t save_va;
3582         struct pmap *save_pmap;
3583         pv_entry_t pv;
3584         pt_entry_t *pte;
3585         pt_entry_t pbits;
3586
3587         if (bit == PG_RW)
3588                 vm_page_flag_clear(m, PG_WRITEABLE);
3589         if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
3590                 return;
3591         }
3592
3593         pmap_inval_init(&info);
3594
3595         /*
3596          * Loop over all current mappings setting/clearing as appropos If
3597          * setting RO do we need to clear the VAC?
3598          */
3599         spin_lock(&pmap_spin);
3600 restart:
3601         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3602                 /*
3603                  * don't write protect pager mappings
3604                  */
3605                 if (bit == PG_RW) {
3606                         if (!pmap_track_modified(pv->pv_va))
3607                                 continue;
3608                 }
3609
3610 #if defined(PMAP_DIAGNOSTIC)
3611                 if (pv->pv_pmap == NULL) {
3612                         kprintf("Null pmap (cb) at va: 0x%lx\n", pv->pv_va);
3613                         continue;
3614                 }
3615 #endif
3616
3617                 /*
3618                  * Careful here.  We can use a locked bus instruction to
3619                  * clear PG_A or PG_M safely but we need to synchronize
3620                  * with the target cpus when we mess with PG_RW.
3621                  *
3622                  * We do not have to force synchronization when clearing
3623                  * PG_M even for PTEs generated via virtual memory maps,
3624                  * because the virtual kernel will invalidate the pmap
3625                  * entry when/if it needs to resynchronize the Modify bit.
3626                  *
3627                  * We have to restart our scan if m->md.pv_generation changes
3628                  * on us.
3629                  */
3630                 if (bit & PG_RW) {
3631                         save_generation = m->md.pv_generation;
3632                         save_pmap = pv->pv_pmap;
3633                         save_va = pv->pv_va;
3634                         spin_unlock(&pmap_spin);
3635                         pmap_inval_interlock(&info, save_pmap, save_va);
3636                         spin_lock(&pmap_spin);
3637                         if (save_generation != m->md.pv_generation)
3638                                 goto restart;
3639                 }
3640                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3641 again:
3642                 pbits = *pte;
3643                 if (pbits & bit) {
3644                         if (bit == PG_RW) {
3645                                 if (pbits & PG_M) {
3646                                         vm_page_dirty(m);
3647                                         atomic_clear_long(pte, PG_M|PG_RW);
3648                                 } else {
3649                                         /*
3650                                          * The cpu may be trying to set PG_M
3651                                          * simultaniously with our clearing
3652                                          * of PG_RW.
3653                                          */
3654                                         if (!atomic_cmpset_long(pte, pbits,
3655                                                                pbits & ~PG_RW))
3656                                                 goto again;
3657                                 }
3658                         } else if (bit == PG_M) {
3659                                 /*
3660                                  * We could also clear PG_RW here to force
3661                                  * a fault on write to redetect PG_M for
3662                                  * virtual kernels, but it isn't necessary
3663                                  * since virtual kernels invalidate the pte 
3664                                  * when they clear the VPTE_M bit in their
3665                                  * virtual page tables.
3666                                  */
3667                                 atomic_clear_long(pte, PG_M);
3668                         } else {
3669                                 atomic_clear_long(pte, bit);
3670                         }
3671                 }
3672                 if (bit & PG_RW) {
3673                         save_generation = m->md.pv_generation;
3674                         save_pmap = pv->pv_pmap;
3675                         spin_unlock(&pmap_spin);
3676                         pmap_inval_deinterlock(&info, save_pmap);
3677                         spin_lock(&pmap_spin);
3678                         if (save_generation != m->md.pv_generation)
3679                                 goto restart;
3680                 }
3681         }
3682         spin_unlock(&pmap_spin);
3683         pmap_inval_done(&info);
3684 }
3685
3686 /*
3687  * Lower the permission for all mappings to a given page.
3688  *
3689  * Page must be busied by caller.
3690  */
3691 void
3692 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3693 {
3694         /* JG NX support? */
3695         if ((prot & VM_PROT_WRITE) == 0) {
3696                 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3697                         /*
3698                          * NOTE: pmap_clearbit(.. PG_RW) also clears
3699                          *       the PG_WRITEABLE flag in (m).
3700                          */
3701                         pmap_clearbit(m, PG_RW);
3702                 } else {
3703                         pmap_remove_all(m);
3704                 }
3705         }
3706 }
3707
3708 vm_paddr_t
3709 pmap_phys_address(vm_pindex_t ppn)
3710 {
3711         return (x86_64_ptob(ppn));
3712 }
3713
3714 /*
3715  * Return a count of reference bits for a page, clearing those bits.
3716  * It is not necessary for every reference bit to be cleared, but it
3717  * is necessary that 0 only be returned when there are truly no
3718  * reference bits set.
3719  *
3720  * XXX: The exact number of bits to check and clear is a matter that
3721  * should be tested and standardized at some point in the future for
3722  * optimal aging of shared pages.
3723  *
3724  * This routine may not block.
3725  */
3726 int
3727 pmap_ts_referenced(vm_page_t m)
3728 {
3729         pv_entry_t pv, pvf, pvn;
3730         pt_entry_t *pte;
3731         int rtval = 0;
3732
3733         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
3734                 return (rtval);
3735
3736         spin_lock(&pmap_spin);
3737         if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3738                 pvf = pv;
3739                 do {
3740                         pvn = TAILQ_NEXT(pv, pv_list);
3741
3742                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3743                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3744                         /*++pv->pv_pmap->pm_generation; not needed */
3745
3746                         if (!pmap_track_modified(pv->pv_va))
3747                                 continue;
3748
3749                         pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
3750
3751                         if (pte && (*pte & PG_A)) {
3752 #ifdef SMP
3753                                 atomic_clear_long(pte, PG_A);
3754 #else
3755                                 atomic_clear_long_nonlocked(pte, PG_A);
3756 #endif
3757                                 rtval++;
3758                                 if (rtval > 4) {
3759                                         break;
3760                                 }
3761                         }
3762                 } while ((pv = pvn) != NULL && pv != pvf);
3763         }
3764         spin_unlock(&pmap_spin);
3765
3766         return (rtval);
3767 }
3768
3769 /*
3770  *      pmap_is_modified:
3771  *
3772  *      Return whether or not the specified physical page was modified
3773  *      in any physical maps.
3774  */
3775 boolean_t
3776 pmap_is_modified(vm_page_t m)
3777 {
3778         boolean_t res;
3779
3780         spin_lock(&pmap_spin);
3781         res = pmap_testbit(m, PG_M);
3782         spin_unlock(&pmap_spin);
3783         return (res);
3784 }
3785
3786 /*
3787  *      Clear the modify bits on the specified physical page.
3788  */
3789 void
3790 pmap_clear_modify(vm_page_t m)
3791 {
3792         pmap_clearbit(m, PG_M);
3793 }
3794
3795 /*
3796  *      pmap_clear_reference:
3797  *
3798  *      Clear the reference bit on the specified physical page.
3799  */
3800 void
3801 pmap_clear_reference(vm_page_t m)
3802 {
3803         pmap_clearbit(m, PG_A);
3804 }
3805
3806 /*
3807  * Miscellaneous support routines follow
3808  */
3809
3810 static
3811 void
3812 i386_protection_init(void)
3813 {
3814         int *kp, prot;
3815
3816         /* JG NX support may go here; No VM_PROT_EXECUTE ==> set NX bit  */
3817         kp = protection_codes;
3818         for (prot = 0; prot < 8; prot++) {
3819                 switch (prot) {
3820                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
3821                         /*
3822                          * Read access is also 0. There isn't any execute bit,
3823                          * so just make it readable.
3824                          */
3825                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
3826                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
3827                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
3828                         *kp++ = 0;
3829                         break;
3830                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
3831                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
3832                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
3833                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
3834                         *kp++ = PG_RW;
3835                         break;
3836                 }
3837         }
3838 }
3839
3840 /*
3841  * Map a set of physical memory pages into the kernel virtual
3842  * address space. Return a pointer to where it is mapped. This
3843  * routine is intended to be used for mapping device memory,
3844  * NOT real memory.
3845  *
3846  * NOTE: we can't use pgeflag unless we invalidate the pages one at
3847  * a time.
3848  */
3849 void *
3850 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
3851 {
3852         vm_offset_t va, tmpva, offset;
3853         pt_entry_t *pte;
3854
3855         offset = pa & PAGE_MASK;
3856         size = roundup(offset + size, PAGE_SIZE);
3857
3858         va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
3859         if (va == 0)
3860                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3861
3862         pa = pa & ~PAGE_MASK;
3863         for (tmpva = va; size > 0;) {
3864                 pte = vtopte(tmpva);
3865                 *pte = pa | PG_RW | PG_V; /* | pgeflag; */
3866                 size -= PAGE_SIZE;
3867                 tmpva += PAGE_SIZE;
3868                 pa += PAGE_SIZE;
3869         }
3870         cpu_invltlb();
3871         smp_invltlb();
3872
3873         return ((void *)(va + offset));
3874 }
3875
3876 void *
3877 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
3878 {
3879         vm_offset_t va, tmpva, offset;
3880         pt_entry_t *pte;
3881
3882         offset = pa & PAGE_MASK;
3883         size = roundup(offset + size, PAGE_SIZE);
3884
3885         va = kmem_alloc_nofault(&kernel_map, size, PAGE_SIZE);
3886         if (va == 0)
3887                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3888
3889         pa = pa & ~PAGE_MASK;
3890         for (tmpva = va; size > 0;) {
3891                 pte = vtopte(tmpva);
3892                 *pte = pa | PG_RW | PG_V | PG_N; /* | pgeflag; */
3893                 size -= PAGE_SIZE;
3894                 tmpva += PAGE_SIZE;
3895                 pa += PAGE_SIZE;
3896         }
3897         cpu_invltlb();
3898         smp_invltlb();
3899
3900         return ((void *)(va + offset));
3901 }
3902
3903 void
3904 pmap_unmapdev(vm_offset_t va, vm_size_t size)
3905 {
3906         vm_offset_t base, offset;
3907
3908         base = va & ~PAGE_MASK;
3909         offset = va & PAGE_MASK;
3910         size = roundup(offset + size, PAGE_SIZE);
3911         pmap_qremove(va, size >> PAGE_SHIFT);
3912         kmem_free(&kernel_map, base, size);
3913 }
3914
3915 /*
3916  * perform the pmap work for mincore
3917  */
3918 int
3919 pmap_mincore(pmap_t pmap, vm_offset_t addr)
3920 {
3921         pt_entry_t *ptep, pte;
3922         vm_page_t m;
3923         int val = 0;
3924         
3925         lwkt_gettoken(&pmap->pm_token);
3926         ptep = pmap_pte(pmap, addr);
3927
3928         if (ptep && (pte = *ptep) != 0) {
3929                 vm_offset_t pa;
3930
3931                 val = MINCORE_INCORE;
3932                 if ((pte & PG_MANAGED) == 0)
3933                         goto done;
3934
3935                 pa = pte & PG_FRAME;
3936
3937                 m = PHYS_TO_VM_PAGE(pa);
3938
3939                 /*
3940                  * Modified by us
3941                  */
3942                 if (pte & PG_M)
3943                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3944                 /*
3945                  * Modified by someone
3946                  */
3947                 else if (m->dirty || pmap_is_modified(m))
3948                         val |= MINCORE_MODIFIED_OTHER;
3949                 /*
3950                  * Referenced by us
3951                  */
3952                 if (pte & PG_A)
3953                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3954
3955                 /*
3956                  * Referenced by someone
3957                  */
3958                 else if ((m->flags & PG_REFERENCED) || pmap_ts_referenced(m)) {
3959                         val |= MINCORE_REFERENCED_OTHER;
3960                         vm_page_flag_set(m, PG_REFERENCED);
3961                 }
3962         } 
3963 done:
3964         lwkt_reltoken(&pmap->pm_token);
3965
3966         return val;
3967 }
3968
3969 /*
3970  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
3971  * vmspace will be ref'd and the old one will be deref'd.
3972  *
3973  * The vmspace for all lwps associated with the process will be adjusted
3974  * and cr3 will be reloaded if any lwp is the current lwp.
3975  *
3976  * The process must hold the vmspace->vm_map.token for oldvm and newvm
3977  */
3978 void
3979 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
3980 {
3981         struct vmspace *oldvm;
3982         struct lwp *lp;
3983
3984         oldvm = p->p_vmspace;
3985         if (oldvm != newvm) {
3986                 if (adjrefs)
3987                         sysref_get(&newvm->vm_sysref);
3988                 p->p_vmspace = newvm;
3989                 KKASSERT(p->p_nthreads == 1);
3990                 lp = RB_ROOT(&p->p_lwp_tree);
3991                 pmap_setlwpvm(lp, newvm);
3992                 if (adjrefs)
3993                         sysref_put(&oldvm->vm_sysref);
3994         }
3995 }
3996
3997 /*
3998  * Set the vmspace for a LWP.  The vmspace is almost universally set the
3999  * same as the process vmspace, but virtual kernels need to swap out contexts
4000  * on a per-lwp basis.
4001  *
4002  * Caller does not necessarily hold any vmspace tokens.  Caller must control
4003  * the lwp (typically be in the context of the lwp).  We use a critical
4004  * section to protect against statclock and hardclock (statistics collection).
4005  */
4006 void
4007 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
4008 {
4009         struct vmspace *oldvm;
4010         struct pmap *pmap;
4011
4012         oldvm = lp->lwp_vmspace;
4013
4014         if (oldvm != newvm) {
4015                 crit_enter();
4016                 lp->lwp_vmspace = newvm;
4017                 if (curthread->td_lwp == lp) {
4018                         pmap = vmspace_pmap(newvm);
4019 #if defined(SMP)
4020                         atomic_set_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
4021                         if (pmap->pm_active & CPUMASK_LOCK)
4022                                 pmap_interlock_wait(newvm);
4023 #else
4024                         pmap->pm_active |= 1;
4025 #endif
4026 #if defined(SWTCH_OPTIM_STATS)
4027                         tlb_flush_count++;
4028 #endif
4029                         curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
4030                         curthread->td_pcb->pcb_cr3 |= PG_RW | PG_U | PG_V;
4031                         load_cr3(curthread->td_pcb->pcb_cr3);
4032                         pmap = vmspace_pmap(oldvm);
4033 #if defined(SMP)
4034                         atomic_clear_cpumask(&pmap->pm_active, mycpu->gd_cpumask);
4035 #else
4036                         pmap->pm_active &= ~(cpumask_t)1;
4037 #endif
4038                 }
4039                 crit_exit();
4040         }
4041 }
4042
4043 #ifdef SMP
4044
4045 /*
4046  * Called when switching to a locked pmap, used to interlock against pmaps
4047  * undergoing modifications to prevent us from activating the MMU for the
4048  * target pmap until all such modifications have completed.  We have to do
4049  * this because the thread making the modifications has already set up its
4050  * SMP synchronization mask.
4051  *
4052  * No requirements.
4053  */
4054 void
4055 pmap_interlock_wait(struct vmspace *vm)
4056 {
4057         struct pmap *pmap = &vm->vm_pmap;
4058
4059         if (pmap->pm_active & CPUMASK_LOCK) {
4060                 crit_enter();
4061                 DEBUG_PUSH_INFO("pmap_interlock_wait");
4062                 while (pmap->pm_active & CPUMASK_LOCK) {
4063                         cpu_ccfence();
4064                         lwkt_process_ipiq();
4065                 }
4066                 DEBUG_POP_INFO();
4067                 crit_exit();
4068         }
4069 }
4070
4071 #endif
4072
4073 vm_offset_t
4074 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
4075 {
4076
4077         if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
4078                 return addr;
4079         }
4080
4081         addr = (addr + (NBPDR - 1)) & ~(NBPDR - 1);
4082         return addr;
4083 }
4084
4085 /*
4086  * Used by kmalloc/kfree, page already exists at va
4087  */
4088 vm_page_t
4089 pmap_kvtom(vm_offset_t va)
4090 {
4091         return(PHYS_TO_VM_PAGE(*vtopte(va) & PG_FRAME));
4092 }