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