kernel - Tag vm_map_entry structure, slight optimization to zalloc, misc.
[dragonfly.git] / sys / platform / pc64 / x86_64 / pmap.c
1 /*
2  * Copyright (c) 1991 Regents of the University of California.
3  * Copyright (c) 1994 John S. Dyson
4  * Copyright (c) 1994 David Greenman
5  * Copyright (c) 2003 Peter Wemm
6  * Copyright (c) 2005-2008 Alan L. Cox <alc@cs.rice.edu>
7  * Copyright (c) 2008, 2009 The DragonFly Project.
8  * Copyright (c) 2008, 2009 Jordan Gordeev.
9  * Copyright (c) 2011-2012 Matthew Dillon
10  * All rights reserved.
11  *
12  * This code is derived from software contributed to Berkeley by
13  * the Systems Programming Group of the University of Utah Computer
14  * Science Department and William Jolitz of UUNET Technologies Inc.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. All advertising materials mentioning features or use of this software
25  *    must display the following acknowledgement:
26  *      This product includes software developed by the University of
27  *      California, Berkeley and its contributors.
28  * 4. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  */
44 /*
45  * Manage physical address maps for x86-64 systems.
46  */
47
48 #if 0 /* JG */
49 #include "opt_disable_pse.h"
50 #include "opt_pmap.h"
51 #endif
52 #include "opt_msgbuf.h"
53
54 #include <sys/param.h>
55 #include <sys/kernel.h>
56 #include <sys/proc.h>
57 #include <sys/msgbuf.h>
58 #include <sys/vmmeter.h>
59 #include <sys/mman.h>
60 #include <sys/systm.h>
61
62 #include <vm/vm.h>
63 #include <vm/vm_param.h>
64 #include <sys/sysctl.h>
65 #include <sys/lock.h>
66 #include <vm/vm_kern.h>
67 #include <vm/vm_page.h>
68 #include <vm/vm_map.h>
69 #include <vm/vm_object.h>
70 #include <vm/vm_extern.h>
71 #include <vm/vm_pageout.h>
72 #include <vm/vm_pager.h>
73 #include <vm/vm_zone.h>
74
75 #include <sys/user.h>
76 #include <sys/thread2.h>
77 #include <sys/sysref2.h>
78 #include <sys/spinlock2.h>
79 #include <vm/vm_page2.h>
80
81 #include <machine/cputypes.h>
82 #include <machine/md_var.h>
83 #include <machine/specialreg.h>
84 #include <machine/smp.h>
85 #include <machine_base/apic/apicreg.h>
86 #include <machine/globaldata.h>
87 #include <machine/pmap.h>
88 #include <machine/pmap_inval.h>
89 #include <machine/inttypes.h>
90
91 #include <ddb/ddb.h>
92
93 #define PMAP_KEEP_PDIRS
94 #ifndef PMAP_SHPGPERPROC
95 #define PMAP_SHPGPERPROC 2000
96 #endif
97
98 #if defined(DIAGNOSTIC)
99 #define PMAP_DIAGNOSTIC
100 #endif
101
102 #define MINPV 2048
103
104 /*
105  * pmap debugging will report who owns a pv lock when blocking.
106  */
107 #ifdef PMAP_DEBUG
108
109 #define PMAP_DEBUG_DECL         ,const char *func, int lineno
110 #define PMAP_DEBUG_ARGS         , __func__, __LINE__
111 #define PMAP_DEBUG_COPY         , func, lineno
112
113 #define pv_get(pmap, pindex)            _pv_get(pmap, pindex            \
114                                                         PMAP_DEBUG_ARGS)
115 #define pv_lock(pv)                     _pv_lock(pv                     \
116                                                         PMAP_DEBUG_ARGS)
117 #define pv_hold_try(pv)                 _pv_hold_try(pv                 \
118                                                         PMAP_DEBUG_ARGS)
119 #define pv_alloc(pmap, pindex, isnewp)  _pv_alloc(pmap, pindex, isnewp  \
120                                                         PMAP_DEBUG_ARGS)
121
122 #else
123
124 #define PMAP_DEBUG_DECL
125 #define PMAP_DEBUG_ARGS
126 #define PMAP_DEBUG_COPY
127
128 #define pv_get(pmap, pindex)            _pv_get(pmap, pindex)
129 #define pv_lock(pv)                     _pv_lock(pv)
130 #define pv_hold_try(pv)                 _pv_hold_try(pv)
131 #define pv_alloc(pmap, pindex, isnewp)  _pv_alloc(pmap, pindex, isnewp)
132
133 #endif
134
135 /*
136  * Get PDEs and PTEs for user/kernel address space
137  */
138 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
139
140 #define pmap_pde_v(pmap, pte)           ((*(pd_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
141 #define pmap_pte_w(pmap, pte)           ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_W_IDX]) != 0)
142 #define pmap_pte_m(pmap, pte)           ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_M_IDX]) != 0)
143 #define pmap_pte_u(pmap, pte)           ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_U_IDX]) != 0)
144 #define pmap_pte_v(pmap, pte)           ((*(pt_entry_t *)pte & pmap->pmap_bits[PG_V_IDX]) != 0)
145
146 /*
147  * Given a map and a machine independent protection code,
148  * convert to a vax protection code.
149  */
150 #define pte_prot(m, p)          \
151         (m->protection_codes[p & (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE)])
152 static int protection_codes[PROTECTION_CODES_SIZE];
153
154 struct pmap kernel_pmap;
155 static TAILQ_HEAD(,pmap)        pmap_list = TAILQ_HEAD_INITIALIZER(pmap_list);
156
157 MALLOC_DEFINE(M_OBJPMAP, "objpmap", "pmaps associated with VM objects");
158
159 vm_paddr_t avail_start;         /* PA of first available physical page */
160 vm_paddr_t avail_end;           /* PA of last available physical page */
161 vm_offset_t virtual2_start;     /* cutout free area prior to kernel start */
162 vm_offset_t virtual2_end;
163 vm_offset_t virtual_start;      /* VA of first avail page (after kernel bss) */
164 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
165 vm_offset_t KvaStart;           /* VA start of KVA space */
166 vm_offset_t KvaEnd;             /* VA end of KVA space (non-inclusive) */
167 vm_offset_t KvaSize;            /* max size of kernel virtual address space */
168 static boolean_t pmap_initialized = FALSE;      /* Has pmap_init completed? */
169 //static int pgeflag;           /* PG_G or-in */
170 //static int pseflag;           /* PG_PS or-in */
171 uint64_t PatMsr;
172
173 static int ndmpdp;
174 static vm_paddr_t dmaplimit;
175 static int nkpt;
176 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
177
178 static pt_entry_t pat_pte_index[PAT_INDEX_SIZE];        /* PAT -> PG_ bits */
179 /*static pt_entry_t pat_pde_index[PAT_INDEX_SIZE];*/    /* PAT -> PG_ bits */
180
181 static uint64_t KPTbase;
182 static uint64_t KPTphys;
183 static uint64_t KPDphys;        /* phys addr of kernel level 2 */
184 static uint64_t KPDbase;        /* phys addr of kernel level 2 @ KERNBASE */
185 uint64_t KPDPphys;      /* phys addr of kernel level 3 */
186 uint64_t KPML4phys;     /* phys addr of kernel level 4 */
187
188 static uint64_t DMPDphys;       /* phys addr of direct mapped level 2 */
189 static uint64_t DMPDPphys;      /* phys addr of direct mapped level 3 */
190
191 /*
192  * Data for the pv entry allocation mechanism
193  */
194 static vm_zone_t pvzone;
195 static struct vm_zone pvzone_store;
196 static struct vm_object pvzone_obj;
197 static int pv_entry_max=0, pv_entry_high_water=0;
198 static int pmap_pagedaemon_waken = 0;
199 static struct pv_entry *pvinit;
200
201 /*
202  * All those kernel PT submaps that BSD is so fond of
203  */
204 pt_entry_t *CMAP1 = NULL, *ptmmap;
205 caddr_t CADDR1 = NULL, ptvmmap = NULL;
206 static pt_entry_t *msgbufmap;
207 struct msgbuf *msgbufp=NULL;
208
209 /*
210  * PMAP default PG_* bits. Needed to be able to add
211  * EPT/NPT pagetable pmap_bits for the VMM module
212  */
213 uint64_t pmap_bits_default[] = {
214                 REGULAR_PMAP,                                   /* TYPE_IDX             0 */
215                 X86_PG_V,                                       /* PG_V_IDX             1 */
216                 X86_PG_RW,                                      /* PG_RW_IDX            2 */
217                 X86_PG_U,                                       /* PG_U_IDX             3 */
218                 X86_PG_A,                                       /* PG_A_IDX             4 */
219                 X86_PG_M,                                       /* PG_M_IDX             5 */
220                 X86_PG_PS,                                      /* PG_PS_IDX3           6 */
221                 X86_PG_G,                                       /* PG_G_IDX             7 */
222                 X86_PG_AVAIL1,                                  /* PG_AVAIL1_IDX        8 */
223                 X86_PG_AVAIL2,                                  /* PG_AVAIL2_IDX        9 */
224                 X86_PG_AVAIL3,                                  /* PG_AVAIL3_IDX        10 */
225                 X86_PG_NC_PWT | X86_PG_NC_PCD,                  /* PG_N_IDX     11 */
226 };
227 /*
228  * Crashdump maps.
229  */
230 static pt_entry_t *pt_crashdumpmap;
231 static caddr_t crashdumpmap;
232
233 #ifdef PMAP_DEBUG2
234 static int pmap_enter_debug = 0;
235 SYSCTL_INT(_machdep, OID_AUTO, pmap_enter_debug, CTLFLAG_RW,
236     &pmap_enter_debug, 0, "Debug pmap_enter's");
237 #endif
238 static int pmap_yield_count = 64;
239 SYSCTL_INT(_machdep, OID_AUTO, pmap_yield_count, CTLFLAG_RW,
240     &pmap_yield_count, 0, "Yield during init_pt/release");
241 static int pmap_mmu_optimize = 0;
242 SYSCTL_INT(_machdep, OID_AUTO, pmap_mmu_optimize, CTLFLAG_RW,
243     &pmap_mmu_optimize, 0, "Share page table pages when possible");
244 int pmap_fast_kernel_cpusync = 0;
245 SYSCTL_INT(_machdep, OID_AUTO, pmap_fast_kernel_cpusync, CTLFLAG_RW,
246     &pmap_fast_kernel_cpusync, 0, "Share page table pages when possible");
247
248 #define DISABLE_PSE
249
250 /* Standard user access funtions */
251 extern int std_copyinstr (const void *udaddr, void *kaddr, size_t len,
252     size_t *lencopied);
253 extern int std_copyin (const void *udaddr, void *kaddr, size_t len);
254 extern int std_copyout (const void *kaddr, void *udaddr, size_t len);
255 extern int std_fubyte (const void *base);
256 extern int std_subyte (void *base, int byte);
257 extern long std_fuword (const void *base);
258 extern int std_suword (void *base, long word);
259 extern int std_suword32 (void *base, int word);
260
261 static void pv_hold(pv_entry_t pv);
262 static int _pv_hold_try(pv_entry_t pv
263                                 PMAP_DEBUG_DECL);
264 static void pv_drop(pv_entry_t pv);
265 static void _pv_lock(pv_entry_t pv
266                                 PMAP_DEBUG_DECL);
267 static void pv_unlock(pv_entry_t pv);
268 static pv_entry_t _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew
269                                 PMAP_DEBUG_DECL);
270 static pv_entry_t _pv_get(pmap_t pmap, vm_pindex_t pindex
271                                 PMAP_DEBUG_DECL);
272 static pv_entry_t pv_get_try(pmap_t pmap, vm_pindex_t pindex, int *errorp);
273 static pv_entry_t pv_find(pmap_t pmap, vm_pindex_t pindex);
274 static void pv_put(pv_entry_t pv);
275 static void pv_free(pv_entry_t pv);
276 static void *pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex);
277 static pv_entry_t pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
278                       pv_entry_t *pvpp);
279 static pv_entry_t pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex,
280                       pv_entry_t *pvpp, vm_map_entry_t entry, vm_offset_t va);
281 static void pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp,
282                         pmap_inval_bulk_t *bulk);
283 static vm_page_t pmap_remove_pv_page(pv_entry_t pv);
284 static int pmap_release_pv(pv_entry_t pv, pv_entry_t pvp,
285                         pmap_inval_bulk_t *bulk);
286
287 struct pmap_scan_info;
288 static void pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
289                       pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
290                       vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
291 static void pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
292                       pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
293                       vm_offset_t va, pt_entry_t *ptep, void *arg __unused);
294
295 static void i386_protection_init (void);
296 static void create_pagetables(vm_paddr_t *firstaddr);
297 static void pmap_remove_all (vm_page_t m);
298 static boolean_t pmap_testbit (vm_page_t m, int bit);
299
300 static pt_entry_t * pmap_pte_quick (pmap_t pmap, vm_offset_t va);
301 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
302
303 static void pmap_pinit_defaults(struct pmap *pmap);
304
305 static unsigned pdir4mb;
306
307 static int
308 pv_entry_compare(pv_entry_t pv1, pv_entry_t pv2)
309 {
310         if (pv1->pv_pindex < pv2->pv_pindex)
311                 return(-1);
312         if (pv1->pv_pindex > pv2->pv_pindex)
313                 return(1);
314         return(0);
315 }
316
317 RB_GENERATE2(pv_entry_rb_tree, pv_entry, pv_entry,
318              pv_entry_compare, vm_pindex_t, pv_pindex);
319
320 static __inline
321 void
322 pmap_page_stats_adding(vm_page_t m)
323 {
324         globaldata_t gd = mycpu;
325
326         if (TAILQ_EMPTY(&m->md.pv_list)) {
327                 ++gd->gd_vmtotal.t_arm;
328         } else if (TAILQ_FIRST(&m->md.pv_list) ==
329                    TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
330                 ++gd->gd_vmtotal.t_armshr;
331                 ++gd->gd_vmtotal.t_avmshr;
332         } else {
333                 ++gd->gd_vmtotal.t_avmshr;
334         }
335 }
336
337 static __inline
338 void
339 pmap_page_stats_deleting(vm_page_t m)
340 {
341         globaldata_t gd = mycpu;
342
343         if (TAILQ_EMPTY(&m->md.pv_list)) {
344                 --gd->gd_vmtotal.t_arm;
345         } else if (TAILQ_FIRST(&m->md.pv_list) ==
346                    TAILQ_LAST(&m->md.pv_list, md_page_pv_list)) {
347                 --gd->gd_vmtotal.t_armshr;
348                 --gd->gd_vmtotal.t_avmshr;
349         } else {
350                 --gd->gd_vmtotal.t_avmshr;
351         }
352 }
353
354 /*
355  * Move the kernel virtual free pointer to the next
356  * 2MB.  This is used to help improve performance
357  * by using a large (2MB) page for much of the kernel
358  * (.text, .data, .bss)
359  */
360 static
361 vm_offset_t
362 pmap_kmem_choose(vm_offset_t addr)
363 {
364         vm_offset_t newaddr = addr;
365
366         newaddr = roundup2(addr, NBPDR);
367         return newaddr;
368 }
369
370 /*
371  * pmap_pte_quick:
372  *
373  *      Super fast pmap_pte routine best used when scanning the pv lists.
374  *      This eliminates many course-grained invltlb calls.  Note that many of
375  *      the pv list scans are across different pmaps and it is very wasteful
376  *      to do an entire invltlb when checking a single mapping.
377  */
378 static __inline pt_entry_t *pmap_pte(pmap_t pmap, vm_offset_t va);
379
380 static
381 pt_entry_t *
382 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
383 {
384         return pmap_pte(pmap, va);
385 }
386
387 /*
388  * Returns the pindex of a page table entry (representing a terminal page).
389  * There are NUPTE_TOTAL page table entries possible (a huge number)
390  *
391  * x86-64 has a 48-bit address space, where bit 47 is sign-extended out.
392  * We want to properly translate negative KVAs.
393  */
394 static __inline
395 vm_pindex_t
396 pmap_pte_pindex(vm_offset_t va)
397 {
398         return ((va >> PAGE_SHIFT) & (NUPTE_TOTAL - 1));
399 }
400
401 /*
402  * Returns the pindex of a page table.
403  */
404 static __inline
405 vm_pindex_t
406 pmap_pt_pindex(vm_offset_t va)
407 {
408         return (NUPTE_TOTAL + ((va >> PDRSHIFT) & (NUPT_TOTAL - 1)));
409 }
410
411 /*
412  * Returns the pindex of a page directory.
413  */
414 static __inline
415 vm_pindex_t
416 pmap_pd_pindex(vm_offset_t va)
417 {
418         return (NUPTE_TOTAL + NUPT_TOTAL +
419                 ((va >> PDPSHIFT) & (NUPD_TOTAL - 1)));
420 }
421
422 static __inline
423 vm_pindex_t
424 pmap_pdp_pindex(vm_offset_t va)
425 {
426         return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
427                 ((va >> PML4SHIFT) & (NUPDP_TOTAL - 1)));
428 }
429
430 static __inline
431 vm_pindex_t
432 pmap_pml4_pindex(void)
433 {
434         return (NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL + NUPDP_TOTAL);
435 }
436
437 /*
438  * Return various clipped indexes for a given VA
439  *
440  * Returns the index of a pt in a page directory, representing a page
441  * table.
442  */
443 static __inline
444 vm_pindex_t
445 pmap_pt_index(vm_offset_t va)
446 {
447         return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
448 }
449
450 /*
451  * Returns the index of a pd in a page directory page, representing a page
452  * directory.
453  */
454 static __inline
455 vm_pindex_t
456 pmap_pd_index(vm_offset_t va)
457 {
458         return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
459 }
460
461 /*
462  * Returns the index of a pdp in the pml4 table, representing a page
463  * directory page.
464  */
465 static __inline
466 vm_pindex_t
467 pmap_pdp_index(vm_offset_t va)
468 {
469         return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
470 }
471
472 /*
473  * Generic procedure to index a pte from a pt, pd, or pdp.
474  *
475  * NOTE: Normally passed pindex as pmap_xx_index().  pmap_xx_pindex() is NOT
476  *       a page table page index but is instead of PV lookup index.
477  */
478 static
479 void *
480 pv_pte_lookup(pv_entry_t pv, vm_pindex_t pindex)
481 {
482         pt_entry_t *pte;
483
484         pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pv->pv_m));
485         return(&pte[pindex]);
486 }
487
488 /*
489  * Return pointer to PDP slot in the PML4
490  */
491 static __inline
492 pml4_entry_t *
493 pmap_pdp(pmap_t pmap, vm_offset_t va)
494 {
495         return (&pmap->pm_pml4[pmap_pdp_index(va)]);
496 }
497
498 /*
499  * Return pointer to PD slot in the PDP given a pointer to the PDP
500  */
501 static __inline
502 pdp_entry_t *
503 pmap_pdp_to_pd(pml4_entry_t pdp_pte, vm_offset_t va)
504 {
505         pdp_entry_t *pd;
506
507         pd = (pdp_entry_t *)PHYS_TO_DMAP(pdp_pte & PG_FRAME);
508         return (&pd[pmap_pd_index(va)]);
509 }
510
511 /*
512  * Return pointer to PD slot in the PDP.
513  */
514 static __inline
515 pdp_entry_t *
516 pmap_pd(pmap_t pmap, vm_offset_t va)
517 {
518         pml4_entry_t *pdp;
519
520         pdp = pmap_pdp(pmap, va);
521         if ((*pdp & pmap->pmap_bits[PG_V_IDX]) == 0)
522                 return NULL;
523         return (pmap_pdp_to_pd(*pdp, va));
524 }
525
526 /*
527  * Return pointer to PT slot in the PD given a pointer to the PD
528  */
529 static __inline
530 pd_entry_t *
531 pmap_pd_to_pt(pdp_entry_t pd_pte, vm_offset_t va)
532 {
533         pd_entry_t *pt;
534
535         pt = (pd_entry_t *)PHYS_TO_DMAP(pd_pte & PG_FRAME);
536         return (&pt[pmap_pt_index(va)]);
537 }
538
539 /*
540  * Return pointer to PT slot in the PD
541  *
542  * SIMPLE PMAP NOTE: Simple pmaps (embedded in objects) do not have PDPs,
543  *                   so we cannot lookup the PD via the PDP.  Instead we
544  *                   must look it up via the pmap.
545  */
546 static __inline
547 pd_entry_t *
548 pmap_pt(pmap_t pmap, vm_offset_t va)
549 {
550         pdp_entry_t *pd;
551         pv_entry_t pv;
552         vm_pindex_t pd_pindex;
553
554         if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
555                 pd_pindex = pmap_pd_pindex(va);
556                 spin_lock(&pmap->pm_spin);
557                 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pd_pindex);
558                 spin_unlock(&pmap->pm_spin);
559                 if (pv == NULL || pv->pv_m == NULL)
560                         return NULL;
561                 return (pmap_pd_to_pt(VM_PAGE_TO_PHYS(pv->pv_m), va));
562         } else {
563                 pd = pmap_pd(pmap, va);
564                 if (pd == NULL || (*pd & pmap->pmap_bits[PG_V_IDX]) == 0)
565                          return NULL;
566                 return (pmap_pd_to_pt(*pd, va));
567         }
568 }
569
570 /*
571  * Return pointer to PTE slot in the PT given a pointer to the PT
572  */
573 static __inline
574 pt_entry_t *
575 pmap_pt_to_pte(pd_entry_t pt_pte, vm_offset_t va)
576 {
577         pt_entry_t *pte;
578
579         pte = (pt_entry_t *)PHYS_TO_DMAP(pt_pte & PG_FRAME);
580         return (&pte[pmap_pte_index(va)]);
581 }
582
583 /*
584  * Return pointer to PTE slot in the PT
585  */
586 static __inline
587 pt_entry_t *
588 pmap_pte(pmap_t pmap, vm_offset_t va)
589 {
590         pd_entry_t *pt;
591
592         pt = pmap_pt(pmap, va);
593         if (pt == NULL || (*pt & pmap->pmap_bits[PG_V_IDX]) == 0)
594                  return NULL;
595         if ((*pt & pmap->pmap_bits[PG_PS_IDX]) != 0)
596                 return ((pt_entry_t *)pt);
597         return (pmap_pt_to_pte(*pt, va));
598 }
599
600 /*
601  * Of all the layers (PTE, PT, PD, PDP, PML4) the best one to cache is
602  * the PT layer.  This will speed up core pmap operations considerably.
603  *
604  * NOTE: The pmap spinlock does not need to be held but the passed-in pv
605  *       must be in a known associated state (typically by being locked when
606  *       the pmap spinlock isn't held).  We allow the race for that case.
607  */
608 static __inline
609 void
610 pv_cache(pv_entry_t pv, vm_pindex_t pindex)
611 {
612         if (pindex >= pmap_pt_pindex(0) && pindex <= pmap_pd_pindex(0))
613                 pv->pv_pmap->pm_pvhint = pv;
614 }
615
616
617 /*
618  * Return address of PT slot in PD (KVM only)
619  *
620  * Cannot be used for user page tables because it might interfere with
621  * the shared page-table-page optimization (pmap_mmu_optimize).
622  */
623 static __inline
624 pd_entry_t *
625 vtopt(vm_offset_t va)
626 {
627         uint64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
628                                   NPML4EPGSHIFT)) - 1);
629
630         return (PDmap + ((va >> PDRSHIFT) & mask));
631 }
632
633 /*
634  * KVM - return address of PTE slot in PT
635  */
636 static __inline
637 pt_entry_t *
638 vtopte(vm_offset_t va)
639 {
640         uint64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
641                                   NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
642
643         return (PTmap + ((va >> PAGE_SHIFT) & mask));
644 }
645
646 static uint64_t
647 allocpages(vm_paddr_t *firstaddr, long n)
648 {
649         uint64_t ret;
650
651         ret = *firstaddr;
652         bzero((void *)ret, n * PAGE_SIZE);
653         *firstaddr += n * PAGE_SIZE;
654         return (ret);
655 }
656
657 static
658 void
659 create_pagetables(vm_paddr_t *firstaddr)
660 {
661         long i;         /* must be 64 bits */
662         long nkpt_base;
663         long nkpt_phys;
664         int j;
665
666         /*
667          * We are running (mostly) V=P at this point
668          *
669          * Calculate NKPT - number of kernel page tables.  We have to
670          * accomodoate prealloction of the vm_page_array, dump bitmap,
671          * MSGBUF_SIZE, and other stuff.  Be generous.
672          *
673          * Maxmem is in pages.
674          *
675          * ndmpdp is the number of 1GB pages we wish to map.
676          */
677         ndmpdp = (ptoa(Maxmem) + NBPDP - 1) >> PDPSHIFT;
678         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
679                 ndmpdp = 4;
680         KKASSERT(ndmpdp <= NKPDPE * NPDEPG);
681
682         /*
683          * Starting at the beginning of kvm (not KERNBASE).
684          */
685         nkpt_phys = (Maxmem * sizeof(struct vm_page) + NBPDR - 1) / NBPDR;
686         nkpt_phys += (Maxmem * sizeof(struct pv_entry) + NBPDR - 1) / NBPDR;
687         nkpt_phys += ((nkpt + nkpt + 1 + NKPML4E + NKPDPE + NDMPML4E +
688                        ndmpdp) + 511) / 512;
689         nkpt_phys += 128;
690
691         /*
692          * Starting at KERNBASE - map 2G worth of page table pages.
693          * KERNBASE is offset -2G from the end of kvm.
694          */
695         nkpt_base = (NPDPEPG - KPDPI) * NPTEPG; /* typically 2 x 512 */
696
697         /*
698          * Allocate pages
699          */
700         KPTbase = allocpages(firstaddr, nkpt_base);
701         KPTphys = allocpages(firstaddr, nkpt_phys);
702         KPML4phys = allocpages(firstaddr, 1);
703         KPDPphys = allocpages(firstaddr, NKPML4E);
704         KPDphys = allocpages(firstaddr, NKPDPE);
705
706         /*
707          * Calculate the page directory base for KERNBASE,
708          * that is where we start populating the page table pages.
709          * Basically this is the end - 2.
710          */
711         KPDbase = KPDphys + ((NKPDPE - (NPDPEPG - KPDPI)) << PAGE_SHIFT);
712
713         DMPDPphys = allocpages(firstaddr, NDMPML4E);
714         if ((amd_feature & AMDID_PAGE1GB) == 0)
715                 DMPDphys = allocpages(firstaddr, ndmpdp);
716         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
717
718         /*
719          * Fill in the underlying page table pages for the area around
720          * KERNBASE.  This remaps low physical memory to KERNBASE.
721          *
722          * Read-only from zero to physfree
723          * XXX not fully used, underneath 2M pages
724          */
725         for (i = 0; (i << PAGE_SHIFT) < *firstaddr; i++) {
726                 ((pt_entry_t *)KPTbase)[i] = i << PAGE_SHIFT;
727                 ((pt_entry_t *)KPTbase)[i] |=
728                     pmap_bits_default[PG_RW_IDX] |
729                     pmap_bits_default[PG_V_IDX] |
730                     pmap_bits_default[PG_G_IDX];
731         }
732
733         /*
734          * Now map the initial kernel page tables.  One block of page
735          * tables is placed at the beginning of kernel virtual memory,
736          * and another block is placed at KERNBASE to map the kernel binary,
737          * data, bss, and initial pre-allocations.
738          */
739         for (i = 0; i < nkpt_base; i++) {
740                 ((pd_entry_t *)KPDbase)[i] = KPTbase + (i << PAGE_SHIFT);
741                 ((pd_entry_t *)KPDbase)[i] |=
742                     pmap_bits_default[PG_RW_IDX] |
743                     pmap_bits_default[PG_V_IDX];
744         }
745         for (i = 0; i < nkpt_phys; i++) {
746                 ((pd_entry_t *)KPDphys)[i] = KPTphys + (i << PAGE_SHIFT);
747                 ((pd_entry_t *)KPDphys)[i] |=
748                     pmap_bits_default[PG_RW_IDX] |
749                     pmap_bits_default[PG_V_IDX];
750         }
751
752         /*
753          * Map from zero to end of allocations using 2M pages as an
754          * optimization.  This will bypass some of the KPTBase pages
755          * above in the KERNBASE area.
756          */
757         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++) {
758                 ((pd_entry_t *)KPDbase)[i] = i << PDRSHIFT;
759                 ((pd_entry_t *)KPDbase)[i] |=
760                     pmap_bits_default[PG_RW_IDX] |
761                     pmap_bits_default[PG_V_IDX] |
762                     pmap_bits_default[PG_PS_IDX] |
763                     pmap_bits_default[PG_G_IDX];
764         }
765
766         /*
767          * And connect up the PD to the PDP.  The kernel pmap is expected
768          * to pre-populate all of its PDs.  See NKPDPE in vmparam.h.
769          */
770         for (i = 0; i < NKPDPE; i++) {
771                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] =
772                                 KPDphys + (i << PAGE_SHIFT);
773                 ((pdp_entry_t *)KPDPphys)[NPDPEPG - NKPDPE + i] |=
774                     pmap_bits_default[PG_RW_IDX] |
775                     pmap_bits_default[PG_V_IDX] |
776                     pmap_bits_default[PG_U_IDX];
777         }
778
779         /*
780          * Now set up the direct map space using either 2MB or 1GB pages
781          * Preset PG_M and PG_A because demotion expects it.
782          *
783          * When filling in entries in the PD pages make sure any excess
784          * entries are set to zero as we allocated enough PD pages
785          */
786         if ((amd_feature & AMDID_PAGE1GB) == 0) {
787                 for (i = 0; i < NPDEPG * ndmpdp; i++) {
788                         ((pd_entry_t *)DMPDphys)[i] = i << PDRSHIFT;
789                         ((pd_entry_t *)DMPDphys)[i] |=
790                             pmap_bits_default[PG_RW_IDX] |
791                             pmap_bits_default[PG_V_IDX] |
792                             pmap_bits_default[PG_PS_IDX] |
793                             pmap_bits_default[PG_G_IDX] |
794                             pmap_bits_default[PG_M_IDX] |
795                             pmap_bits_default[PG_A_IDX];
796                 }
797
798                 /*
799                  * And the direct map space's PDP
800                  */
801                 for (i = 0; i < ndmpdp; i++) {
802                         ((pdp_entry_t *)DMPDPphys)[i] = DMPDphys +
803                                                         (i << PAGE_SHIFT);
804                         ((pdp_entry_t *)DMPDPphys)[i] |=
805                             pmap_bits_default[PG_RW_IDX] |
806                             pmap_bits_default[PG_V_IDX] |
807                             pmap_bits_default[PG_U_IDX];
808                 }
809         } else {
810                 for (i = 0; i < ndmpdp; i++) {
811                         ((pdp_entry_t *)DMPDPphys)[i] =
812                                                 (vm_paddr_t)i << PDPSHIFT;
813                         ((pdp_entry_t *)DMPDPphys)[i] |=
814                             pmap_bits_default[PG_RW_IDX] |
815                             pmap_bits_default[PG_V_IDX] |
816                             pmap_bits_default[PG_PS_IDX] |
817                             pmap_bits_default[PG_G_IDX] |
818                             pmap_bits_default[PG_M_IDX] |
819                             pmap_bits_default[PG_A_IDX];
820                 }
821         }
822
823         /* And recursively map PML4 to itself in order to get PTmap */
824         ((pdp_entry_t *)KPML4phys)[PML4PML4I] = KPML4phys;
825         ((pdp_entry_t *)KPML4phys)[PML4PML4I] |=
826             pmap_bits_default[PG_RW_IDX] |
827             pmap_bits_default[PG_V_IDX] |
828             pmap_bits_default[PG_U_IDX];
829
830         /*
831          * Connect the Direct Map slots up to the PML4
832          */
833         for (j = 0; j < NDMPML4E; ++j) {
834                 ((pdp_entry_t *)KPML4phys)[DMPML4I + j] =
835                     (DMPDPphys + ((vm_paddr_t)j << PML4SHIFT)) |
836                     pmap_bits_default[PG_RW_IDX] |
837                     pmap_bits_default[PG_V_IDX] |
838                     pmap_bits_default[PG_U_IDX];
839         }
840
841         /*
842          * Connect the KVA slot up to the PML4
843          */
844         ((pdp_entry_t *)KPML4phys)[KPML4I] = KPDPphys;
845         ((pdp_entry_t *)KPML4phys)[KPML4I] |=
846             pmap_bits_default[PG_RW_IDX] |
847             pmap_bits_default[PG_V_IDX] |
848             pmap_bits_default[PG_U_IDX];
849 }
850
851 /*
852  *      Bootstrap the system enough to run with virtual memory.
853  *
854  *      On the i386 this is called after mapping has already been enabled
855  *      and just syncs the pmap module with what has already been done.
856  *      [We can't call it easily with mapping off since the kernel is not
857  *      mapped with PA == VA, hence we would have to relocate every address
858  *      from the linked base (virtual) address "KERNBASE" to the actual
859  *      (physical) address starting relative to 0]
860  */
861 void
862 pmap_bootstrap(vm_paddr_t *firstaddr)
863 {
864         vm_offset_t va;
865         pt_entry_t *pte;
866
867         KvaStart = VM_MIN_KERNEL_ADDRESS;
868         KvaEnd = VM_MAX_KERNEL_ADDRESS;
869         KvaSize = KvaEnd - KvaStart;
870
871         avail_start = *firstaddr;
872
873         /*
874          * Create an initial set of page tables to run the kernel in.
875          */
876         create_pagetables(firstaddr);
877
878         virtual2_start = KvaStart;
879         virtual2_end = PTOV_OFFSET;
880
881         virtual_start = (vm_offset_t) PTOV_OFFSET + *firstaddr;
882         virtual_start = pmap_kmem_choose(virtual_start);
883
884         virtual_end = VM_MAX_KERNEL_ADDRESS;
885
886         /* XXX do %cr0 as well */
887         load_cr4(rcr4() | CR4_PGE | CR4_PSE);
888         load_cr3(KPML4phys);
889
890         /*
891          * Initialize protection array.
892          */
893         i386_protection_init();
894
895         /*
896          * The kernel's pmap is statically allocated so we don't have to use
897          * pmap_create, which is unlikely to work correctly at this part of
898          * the boot sequence (XXX and which no longer exists).
899          */
900         kernel_pmap.pm_pml4 = (pdp_entry_t *) (PTOV_OFFSET + KPML4phys);
901         kernel_pmap.pm_count = 1;
902         CPUMASK_ASSALLONES(kernel_pmap.pm_active);
903         RB_INIT(&kernel_pmap.pm_pvroot);
904         spin_init(&kernel_pmap.pm_spin, "pmapbootstrap");
905         lwkt_token_init(&kernel_pmap.pm_token, "kpmap_tok");
906
907         /*
908          * Reserve some special page table entries/VA space for temporary
909          * mapping of pages.
910          */
911 #define SYSMAP(c, p, v, n)      \
912         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
913
914         va = virtual_start;
915         pte = vtopte(va);
916
917         /*
918          * CMAP1/CMAP2 are used for zeroing and copying pages.
919          */
920         SYSMAP(caddr_t, CMAP1, CADDR1, 1)
921
922         /*
923          * Crashdump maps.
924          */
925         SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
926
927         /*
928          * ptvmmap is used for reading arbitrary physical pages via
929          * /dev/mem.
930          */
931         SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
932
933         /*
934          * msgbufp is used to map the system message buffer.
935          * XXX msgbufmap is not used.
936          */
937         SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
938                atop(round_page(MSGBUF_SIZE)))
939
940         virtual_start = va;
941         virtual_start = pmap_kmem_choose(virtual_start);
942
943         *CMAP1 = 0;
944
945         /*
946          * PG_G is terribly broken on SMP because we IPI invltlb's in some
947          * cases rather then invl1pg.  Actually, I don't even know why it
948          * works under UP because self-referential page table mappings
949          */
950 //      pgeflag = 0;
951
952 /*
953  * Initialize the 4MB page size flag
954  */
955 //      pseflag = 0;
956 /*
957  * The 4MB page version of the initial
958  * kernel page mapping.
959  */
960         pdir4mb = 0;
961
962 #if !defined(DISABLE_PSE)
963         if (cpu_feature & CPUID_PSE) {
964                 pt_entry_t ptditmp;
965                 /*
966                  * Note that we have enabled PSE mode
967                  */
968 //              pseflag = kernel_pmap.pmap_bits[PG_PS_IDX];
969                 ptditmp = *(PTmap + x86_64_btop(KERNBASE));
970                 ptditmp &= ~(NBPDR - 1);
971                 ptditmp |= pmap_bits_default[PG_V_IDX] |
972                     pmap_bits_default[PG_RW_IDX] |
973                     pmap_bits_default[PG_PS_IDX] |
974                     pmap_bits_default[PG_U_IDX];
975 //                  pgeflag;
976                 pdir4mb = ptditmp;
977         }
978 #endif
979         cpu_invltlb();
980
981         /* Initialize the PAT MSR */
982         pmap_init_pat();
983         pmap_pinit_defaults(&kernel_pmap);
984
985         TUNABLE_INT_FETCH("machdep.pmap_fast_kernel_cpusync",
986                           &pmap_fast_kernel_cpusync);
987
988 }
989
990 /*
991  * Setup the PAT MSR.
992  */
993 void
994 pmap_init_pat(void)
995 {
996         uint64_t pat_msr;
997         u_long cr0, cr4;
998
999         /*
1000          * Default values mapping PATi,PCD,PWT bits at system reset.
1001          * The default values effectively ignore the PATi bit by
1002          * repeating the encodings for 0-3 in 4-7, and map the PCD
1003          * and PWT bit combinations to the expected PAT types.
1004          */
1005         pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |        /* 000 */
1006                   PAT_VALUE(1, PAT_WRITE_THROUGH) |     /* 001 */
1007                   PAT_VALUE(2, PAT_UNCACHED) |          /* 010 */
1008                   PAT_VALUE(3, PAT_UNCACHEABLE) |       /* 011 */
1009                   PAT_VALUE(4, PAT_WRITE_BACK) |        /* 100 */
1010                   PAT_VALUE(5, PAT_WRITE_THROUGH) |     /* 101 */
1011                   PAT_VALUE(6, PAT_UNCACHED) |          /* 110 */
1012                   PAT_VALUE(7, PAT_UNCACHEABLE);        /* 111 */
1013         pat_pte_index[PAT_WRITE_BACK]   = 0;
1014         pat_pte_index[PAT_WRITE_THROUGH]= 0         | X86_PG_NC_PWT;
1015         pat_pte_index[PAT_UNCACHED]     = X86_PG_NC_PCD;
1016         pat_pte_index[PAT_UNCACHEABLE]  = X86_PG_NC_PCD | X86_PG_NC_PWT;
1017         pat_pte_index[PAT_WRITE_PROTECTED] = pat_pte_index[PAT_UNCACHEABLE];
1018         pat_pte_index[PAT_WRITE_COMBINING] = pat_pte_index[PAT_UNCACHEABLE];
1019
1020         if (cpu_feature & CPUID_PAT) {
1021                 /*
1022                  * If we support the PAT then set-up entries for
1023                  * WRITE_PROTECTED and WRITE_COMBINING using bit patterns
1024                  * 4 and 5.
1025                  */
1026                 pat_msr = (pat_msr & ~PAT_MASK(4)) |
1027                           PAT_VALUE(4, PAT_WRITE_PROTECTED);
1028                 pat_msr = (pat_msr & ~PAT_MASK(5)) |
1029                           PAT_VALUE(5, PAT_WRITE_COMBINING);
1030                 pat_pte_index[PAT_WRITE_PROTECTED] = X86_PG_PTE_PAT | 0;
1031                 pat_pte_index[PAT_WRITE_COMBINING] = X86_PG_PTE_PAT | X86_PG_NC_PWT;
1032
1033                 /*
1034                  * Then enable the PAT
1035                  */
1036
1037                 /* Disable PGE. */
1038                 cr4 = rcr4();
1039                 load_cr4(cr4 & ~CR4_PGE);
1040
1041                 /* Disable caches (CD = 1, NW = 0). */
1042                 cr0 = rcr0();
1043                 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1044
1045                 /* Flushes caches and TLBs. */
1046                 wbinvd();
1047                 cpu_invltlb();
1048
1049                 /* Update PAT and index table. */
1050                 wrmsr(MSR_PAT, pat_msr);
1051
1052                 /* Flush caches and TLBs again. */
1053                 wbinvd();
1054                 cpu_invltlb();
1055
1056                 /* Restore caches and PGE. */
1057                 load_cr0(cr0);
1058                 load_cr4(cr4);
1059                 PatMsr = pat_msr;
1060         }
1061 }
1062
1063 /*
1064  * Set 4mb pdir for mp startup
1065  */
1066 void
1067 pmap_set_opt(void)
1068 {
1069         if (cpu_feature & CPUID_PSE) {
1070                 load_cr4(rcr4() | CR4_PSE);
1071                 if (pdir4mb && mycpu->gd_cpuid == 0) {  /* only on BSP */
1072                         cpu_invltlb();
1073                 }
1074         }
1075 }
1076
1077 /*
1078  *      Initialize the pmap module.
1079  *      Called by vm_init, to initialize any structures that the pmap
1080  *      system needs to map virtual memory.
1081  *      pmap_init has been enhanced to support in a fairly consistant
1082  *      way, discontiguous physical memory.
1083  */
1084 void
1085 pmap_init(void)
1086 {
1087         int i;
1088         int initial_pvs;
1089
1090         /*
1091          * Allocate memory for random pmap data structures.  Includes the
1092          * pv_head_table.
1093          */
1094
1095         for (i = 0; i < vm_page_array_size; i++) {
1096                 vm_page_t m;
1097
1098                 m = &vm_page_array[i];
1099                 TAILQ_INIT(&m->md.pv_list);
1100         }
1101
1102         /*
1103          * init the pv free list
1104          */
1105         initial_pvs = vm_page_array_size;
1106         if (initial_pvs < MINPV)
1107                 initial_pvs = MINPV;
1108         pvzone = &pvzone_store;
1109         pvinit = (void *)kmem_alloc(&kernel_map,
1110                                     initial_pvs * sizeof (struct pv_entry),
1111                                     VM_SUBSYS_PVENTRY);
1112         zbootinit(pvzone, "PV ENTRY", sizeof (struct pv_entry),
1113                   pvinit, initial_pvs);
1114
1115         /*
1116          * Now it is safe to enable pv_table recording.
1117          */
1118         pmap_initialized = TRUE;
1119 }
1120
1121 /*
1122  * Initialize the address space (zone) for the pv_entries.  Set a
1123  * high water mark so that the system can recover from excessive
1124  * numbers of pv entries.
1125  */
1126 void
1127 pmap_init2(void)
1128 {
1129         int shpgperproc = PMAP_SHPGPERPROC;
1130         int entry_max;
1131
1132         TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
1133         pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
1134         TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
1135         pv_entry_high_water = 9 * (pv_entry_max / 10);
1136
1137         /*
1138          * Subtract out pages already installed in the zone (hack)
1139          */
1140         entry_max = pv_entry_max - vm_page_array_size;
1141         if (entry_max <= 0)
1142                 entry_max = 1;
1143
1144         zinitna(pvzone, &pvzone_obj, NULL, 0, entry_max, ZONE_INTERRUPT);
1145 }
1146
1147 /*
1148  * Typically used to initialize a fictitious page by vm/device_pager.c
1149  */
1150 void
1151 pmap_page_init(struct vm_page *m)
1152 {
1153         vm_page_init(m);
1154         TAILQ_INIT(&m->md.pv_list);
1155 }
1156
1157 /***************************************************
1158  * Low level helper routines.....
1159  ***************************************************/
1160
1161 /*
1162  * this routine defines the region(s) of memory that should
1163  * not be tested for the modified bit.
1164  */
1165 static __inline
1166 int
1167 pmap_track_modified(vm_pindex_t pindex)
1168 {
1169         vm_offset_t va = (vm_offset_t)pindex << PAGE_SHIFT;
1170         if ((va < clean_sva) || (va >= clean_eva)) 
1171                 return 1;
1172         else
1173                 return 0;
1174 }
1175
1176 /*
1177  * Extract the physical page address associated with the map/VA pair.
1178  * The page must be wired for this to work reliably.
1179  *
1180  * XXX for the moment we're using pv_find() instead of pv_get(), as
1181  *     callers might be expecting non-blocking operation.
1182  */
1183 vm_paddr_t 
1184 pmap_extract(pmap_t pmap, vm_offset_t va)
1185 {
1186         vm_paddr_t rtval;
1187         pv_entry_t pt_pv;
1188         pt_entry_t *ptep;
1189
1190         rtval = 0;
1191         if (va >= VM_MAX_USER_ADDRESS) {
1192                 /*
1193                  * Kernel page directories might be direct-mapped and
1194                  * there is typically no PV tracking of pte's
1195                  */
1196                 pd_entry_t *pt;
1197
1198                 pt = pmap_pt(pmap, va);
1199                 if (pt && (*pt & pmap->pmap_bits[PG_V_IDX])) {
1200                         if (*pt & pmap->pmap_bits[PG_PS_IDX]) {
1201                                 rtval = *pt & PG_PS_FRAME;
1202                                 rtval |= va & PDRMASK;
1203                         } else {
1204                                 ptep = pmap_pt_to_pte(*pt, va);
1205                                 if (*pt & pmap->pmap_bits[PG_V_IDX]) {
1206                                         rtval = *ptep & PG_FRAME;
1207                                         rtval |= va & PAGE_MASK;
1208                                 }
1209                         }
1210                 }
1211         } else {
1212                 /*
1213                  * User pages currently do not direct-map the page directory
1214                  * and some pages might not used managed PVs.  But all PT's
1215                  * will have a PV.
1216                  */
1217                 pt_pv = pv_find(pmap, pmap_pt_pindex(va));
1218                 if (pt_pv) {
1219                         ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1220                         if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
1221                                 rtval = *ptep & PG_FRAME;
1222                                 rtval |= va & PAGE_MASK;
1223                         }
1224                         pv_drop(pt_pv);
1225                 }
1226         }
1227         return rtval;
1228 }
1229
1230 /*
1231  * Similar to extract but checks protections, SMP-friendly short-cut for
1232  * vm_fault_page[_quick]().  Can return NULL to cause the caller to
1233  * fall-through to the real fault code.
1234  *
1235  * The returned page, if not NULL, is held (and not busied).
1236  */
1237 vm_page_t
1238 pmap_fault_page_quick(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1239 {
1240         if (pmap && va < VM_MAX_USER_ADDRESS) {
1241                 pv_entry_t pt_pv;
1242                 pv_entry_t pte_pv;
1243                 pt_entry_t *ptep;
1244                 pt_entry_t req;
1245                 vm_page_t m;
1246                 int error;
1247
1248                 req = pmap->pmap_bits[PG_V_IDX] |
1249                       pmap->pmap_bits[PG_U_IDX];
1250                 if (prot & VM_PROT_WRITE)
1251                         req |= pmap->pmap_bits[PG_RW_IDX];
1252
1253                 pt_pv = pv_find(pmap, pmap_pt_pindex(va));
1254                 if (pt_pv == NULL)
1255                         return (NULL);
1256                 ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
1257                 if ((*ptep & req) != req) {
1258                         pv_drop(pt_pv);
1259                         return (NULL);
1260                 }
1261                 pte_pv = pv_get_try(pmap, pmap_pte_pindex(va), &error);
1262                 if (pte_pv && error == 0) {
1263                         m = pte_pv->pv_m;
1264                         vm_page_hold(m);
1265                         if (prot & VM_PROT_WRITE)
1266                                 vm_page_dirty(m);
1267                         pv_put(pte_pv);
1268                 } else if (pte_pv) {
1269                         pv_drop(pte_pv);
1270                         m = NULL;
1271                 } else {
1272                         m = NULL;
1273                 }
1274                 pv_drop(pt_pv);
1275                 return(m);
1276         } else {
1277                 return(NULL);
1278         }
1279 }
1280
1281 /*
1282  * Extract the physical page address associated kernel virtual address.
1283  */
1284 vm_paddr_t
1285 pmap_kextract(vm_offset_t va)
1286 {
1287         pd_entry_t pt;          /* pt entry in pd */
1288         vm_paddr_t pa;
1289
1290         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
1291                 pa = DMAP_TO_PHYS(va);
1292         } else {
1293                 pt = *vtopt(va);
1294                 if (pt & kernel_pmap.pmap_bits[PG_PS_IDX]) {
1295                         pa = (pt & PG_PS_FRAME) | (va & PDRMASK);
1296                 } else {
1297                         /*
1298                          * Beware of a concurrent promotion that changes the
1299                          * PDE at this point!  For example, vtopte() must not
1300                          * be used to access the PTE because it would use the
1301                          * new PDE.  It is, however, safe to use the old PDE
1302                          * because the page table page is preserved by the
1303                          * promotion.
1304                          */
1305                         pa = *pmap_pt_to_pte(pt, va);
1306                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
1307                 }
1308         }
1309         return pa;
1310 }
1311
1312 /***************************************************
1313  * Low level mapping routines.....
1314  ***************************************************/
1315
1316 /*
1317  * Routine: pmap_kenter
1318  * Function:
1319  *      Add a wired page to the KVA
1320  *      NOTE! note that in order for the mapping to take effect -- you
1321  *      should do an invltlb after doing the pmap_kenter().
1322  */
1323 void 
1324 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1325 {
1326         pt_entry_t *ptep;
1327         pt_entry_t npte;
1328
1329         npte = pa |
1330             kernel_pmap.pmap_bits[PG_RW_IDX] |
1331             kernel_pmap.pmap_bits[PG_V_IDX];
1332 //          pgeflag;
1333         ptep = vtopte(va);
1334 #if 1
1335         pmap_inval_smp(&kernel_pmap, va, 1, ptep, npte);
1336 #else
1337         /* FUTURE */
1338         if (*ptep)
1339                 pmap_inval_smp(&kernel_pmap, va, ptep, npte);
1340         else
1341                 *ptep = npte;
1342 #endif
1343 }
1344
1345 /*
1346  * Similar to pmap_kenter(), except we only invalidate the mapping on the
1347  * current CPU.  Returns 0 if the previous pte was 0, 1 if it wasn't
1348  * (caller can conditionalize calling smp_invltlb()).
1349  */
1350 int
1351 pmap_kenter_quick(vm_offset_t va, vm_paddr_t pa)
1352 {
1353         pt_entry_t *ptep;
1354         pt_entry_t npte;
1355         int res;
1356
1357         npte = pa |
1358             kernel_pmap.pmap_bits[PG_RW_IDX] |
1359             kernel_pmap.pmap_bits[PG_V_IDX];
1360 //          pgeflag;
1361         ptep = vtopte(va);
1362 #if 1
1363         res = 1;
1364 #else
1365         /* FUTURE */
1366         res = (*ptep != 0);
1367 #endif
1368         *ptep = npte;
1369         cpu_invlpg((void *)va);
1370
1371         return res;
1372 }
1373
1374 /*
1375  * Enter addresses into the kernel pmap but don't bother
1376  * doing any tlb invalidations.  Caller will do a rollup
1377  * invalidation via pmap_rollup_inval().
1378  */
1379 int
1380 pmap_kenter_noinval(vm_offset_t va, vm_paddr_t pa)
1381 {
1382         pt_entry_t *ptep;
1383         pt_entry_t npte;
1384         int res;
1385
1386         npte = pa |
1387             kernel_pmap.pmap_bits[PG_RW_IDX] |
1388             kernel_pmap.pmap_bits[PG_V_IDX];
1389 //          pgeflag;
1390         ptep = vtopte(va);
1391 #if 1
1392         res = 1;
1393 #else
1394         /* FUTURE */
1395         res = (*ptep != 0);
1396 #endif
1397         *ptep = npte;
1398         cpu_invlpg((void *)va);
1399
1400         return res;
1401 }
1402
1403 /*
1404  * remove a page from the kernel pagetables
1405  */
1406 void
1407 pmap_kremove(vm_offset_t va)
1408 {
1409         pt_entry_t *ptep;
1410
1411         ptep = vtopte(va);
1412         pmap_inval_smp(&kernel_pmap, va, 1, ptep, 0);
1413 }
1414
1415 void
1416 pmap_kremove_quick(vm_offset_t va)
1417 {
1418         pt_entry_t *ptep;
1419
1420         ptep = vtopte(va);
1421         (void)pte_load_clear(ptep);
1422         cpu_invlpg((void *)va);
1423 }
1424
1425 /*
1426  * Remove addresses from the kernel pmap but don't bother
1427  * doing any tlb invalidations.  Caller will do a rollup
1428  * invalidation via pmap_rollup_inval().
1429  */
1430 void
1431 pmap_kremove_noinval(vm_offset_t va)
1432 {
1433         pt_entry_t *ptep;
1434
1435         ptep = vtopte(va);
1436         (void)pte_load_clear(ptep);
1437 }
1438
1439 /*
1440  * XXX these need to be recoded.  They are not used in any critical path.
1441  */
1442 void
1443 pmap_kmodify_rw(vm_offset_t va)
1444 {
1445         atomic_set_long(vtopte(va), kernel_pmap.pmap_bits[PG_RW_IDX]);
1446         cpu_invlpg((void *)va);
1447 }
1448
1449 /* NOT USED
1450 void
1451 pmap_kmodify_nc(vm_offset_t va)
1452 {
1453         atomic_set_long(vtopte(va), PG_N);
1454         cpu_invlpg((void *)va);
1455 }
1456 */
1457
1458 /*
1459  * Used to map a range of physical addresses into kernel virtual
1460  * address space during the low level boot, typically to map the
1461  * dump bitmap, message buffer, and vm_page_array.
1462  *
1463  * These mappings are typically made at some pointer after the end of the
1464  * kernel text+data.
1465  *
1466  * We could return PHYS_TO_DMAP(start) here and not allocate any
1467  * via (*virtp), but then kmem from userland and kernel dumps won't
1468  * have access to the related pointers.
1469  */
1470 vm_offset_t
1471 pmap_map(vm_offset_t *virtp, vm_paddr_t start, vm_paddr_t end, int prot)
1472 {
1473         vm_offset_t va;
1474         vm_offset_t va_start;
1475
1476         /*return PHYS_TO_DMAP(start);*/
1477
1478         va_start = *virtp;
1479         va = va_start;
1480
1481         while (start < end) {
1482                 pmap_kenter_quick(va, start);
1483                 va += PAGE_SIZE;
1484                 start += PAGE_SIZE;
1485         }
1486         *virtp = va;
1487         return va_start;
1488 }
1489
1490 #define PMAP_CLFLUSH_THRESHOLD  (2 * 1024 * 1024)
1491
1492 /*
1493  * Remove the specified set of pages from the data and instruction caches.
1494  *
1495  * In contrast to pmap_invalidate_cache_range(), this function does not
1496  * rely on the CPU's self-snoop feature, because it is intended for use
1497  * when moving pages into a different cache domain.
1498  */
1499 void
1500 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1501 {
1502         vm_offset_t daddr, eva;
1503         int i;
1504
1505         if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1506             (cpu_feature & CPUID_CLFSH) == 0)
1507                 wbinvd();
1508         else {
1509                 cpu_mfence();
1510                 for (i = 0; i < count; i++) {
1511                         daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1512                         eva = daddr + PAGE_SIZE;
1513                         for (; daddr < eva; daddr += cpu_clflush_line_size)
1514                                 clflush(daddr);
1515                 }
1516                 cpu_mfence();
1517         }
1518 }
1519
1520 void
1521 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1522 {
1523         KASSERT((sva & PAGE_MASK) == 0,
1524             ("pmap_invalidate_cache_range: sva not page-aligned"));
1525         KASSERT((eva & PAGE_MASK) == 0,
1526             ("pmap_invalidate_cache_range: eva not page-aligned"));
1527
1528         if (cpu_feature & CPUID_SS) {
1529                 ; /* If "Self Snoop" is supported, do nothing. */
1530         } else {
1531                 /* Globally invalidate caches */
1532                 cpu_wbinvd_on_all_cpus();
1533         }
1534 }
1535
1536 /*
1537  * Invalidate the specified range of virtual memory on all cpus associated
1538  * with the pmap.
1539  */
1540 void
1541 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1542 {
1543         pmap_inval_smp(pmap, sva, (eva - sva) >> PAGE_SHIFT, NULL, 0);
1544 }
1545
1546 /*
1547  * Add a list of wired pages to the kva.  This routine is used for temporary
1548  * kernel mappings such as those found in buffer cache buffer.  Page
1549  * modifications and accesses are not tracked or recorded.
1550  *
1551  * NOTE! Old mappings are simply overwritten, and we cannot assume relaxed
1552  *       semantics as previous mappings may have been zerod without any
1553  *       invalidation.
1554  *
1555  * The page *must* be wired.
1556  */
1557 void
1558 pmap_qenter(vm_offset_t beg_va, vm_page_t *m, int count)
1559 {
1560         vm_offset_t end_va;
1561         vm_offset_t va;
1562
1563         end_va = beg_va + count * PAGE_SIZE;
1564
1565         for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1566                 pt_entry_t *pte;
1567
1568                 pte = vtopte(va);
1569                 *pte = VM_PAGE_TO_PHYS(*m) |
1570                     kernel_pmap.pmap_bits[PG_RW_IDX] |
1571                     kernel_pmap.pmap_bits[PG_V_IDX] |
1572                     kernel_pmap.pmap_cache_bits[(*m)->pat_mode];
1573 //              pgeflag;
1574                 m++;
1575         }
1576         pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
1577 }
1578
1579 /*
1580  * This routine jerks page mappings from the kernel -- it is meant only
1581  * for temporary mappings such as those found in buffer cache buffers.
1582  * No recording modified or access status occurs.
1583  *
1584  * MPSAFE, INTERRUPT SAFE (cluster callback)
1585  */
1586 void
1587 pmap_qremove(vm_offset_t beg_va, int count)
1588 {
1589         vm_offset_t end_va;
1590         vm_offset_t va;
1591
1592         end_va = beg_va + count * PAGE_SIZE;
1593
1594         for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1595                 pt_entry_t *pte;
1596
1597                 pte = vtopte(va);
1598                 (void)pte_load_clear(pte);
1599                 cpu_invlpg((void *)va);
1600         }
1601         pmap_invalidate_range(&kernel_pmap, beg_va, end_va);
1602 }
1603
1604 /*
1605  * This routine removes temporary kernel mappings, only invalidating them
1606  * on the current cpu.  It should only be used under carefully controlled
1607  * conditions.
1608  */
1609 void
1610 pmap_qremove_quick(vm_offset_t beg_va, int count)
1611 {
1612         vm_offset_t end_va;
1613         vm_offset_t va;
1614
1615         end_va = beg_va + count * PAGE_SIZE;
1616
1617         for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1618                 pt_entry_t *pte;
1619
1620                 pte = vtopte(va);
1621                 (void)pte_load_clear(pte);
1622                 cpu_invlpg((void *)va);
1623         }
1624 }
1625
1626 /*
1627  * This routine removes temporary kernel mappings *without* invalidating
1628  * the TLB.  It can only be used on permanent kva reservations such as those
1629  * found in buffer cache buffers, under carefully controlled circumstances.
1630  *
1631  * NOTE: Repopulating these KVAs requires unconditional invalidation.
1632  *       (pmap_qenter() does unconditional invalidation).
1633  */
1634 void
1635 pmap_qremove_noinval(vm_offset_t beg_va, int count)
1636 {
1637         vm_offset_t end_va;
1638         vm_offset_t va;
1639
1640         end_va = beg_va + count * PAGE_SIZE;
1641
1642         for (va = beg_va; va < end_va; va += PAGE_SIZE) {
1643                 pt_entry_t *pte;
1644
1645                 pte = vtopte(va);
1646                 (void)pte_load_clear(pte);
1647         }
1648 }
1649
1650 /*
1651  * Create a new thread and optionally associate it with a (new) process.
1652  * NOTE! the new thread's cpu may not equal the current cpu.
1653  */
1654 void
1655 pmap_init_thread(thread_t td)
1656 {
1657         /* enforce pcb placement & alignment */
1658         td->td_pcb = (struct pcb *)(td->td_kstack + td->td_kstack_size) - 1;
1659         td->td_pcb = (struct pcb *)((intptr_t)td->td_pcb & ~(intptr_t)0xF);
1660         td->td_savefpu = &td->td_pcb->pcb_save;
1661         td->td_sp = (char *)td->td_pcb; /* no -16 */
1662 }
1663
1664 /*
1665  * This routine directly affects the fork perf for a process.
1666  */
1667 void
1668 pmap_init_proc(struct proc *p)
1669 {
1670 }
1671
1672 static void
1673 pmap_pinit_defaults(struct pmap *pmap)
1674 {
1675         bcopy(pmap_bits_default, pmap->pmap_bits,
1676               sizeof(pmap_bits_default));
1677         bcopy(protection_codes, pmap->protection_codes,
1678               sizeof(protection_codes));
1679         bcopy(pat_pte_index, pmap->pmap_cache_bits,
1680               sizeof(pat_pte_index));
1681         pmap->pmap_cache_mask = X86_PG_NC_PWT | X86_PG_NC_PCD | X86_PG_PTE_PAT;
1682         pmap->copyinstr = std_copyinstr;
1683         pmap->copyin = std_copyin;
1684         pmap->copyout = std_copyout;
1685         pmap->fubyte = std_fubyte;
1686         pmap->subyte = std_subyte;
1687         pmap->fuword = std_fuword;
1688         pmap->suword = std_suword;
1689         pmap->suword32 = std_suword32;
1690 }
1691 /*
1692  * Initialize pmap0/vmspace0.  This pmap is not added to pmap_list because
1693  * it, and IdlePTD, represents the template used to update all other pmaps.
1694  *
1695  * On architectures where the kernel pmap is not integrated into the user
1696  * process pmap, this pmap represents the process pmap, not the kernel pmap.
1697  * kernel_pmap should be used to directly access the kernel_pmap.
1698  */
1699 void
1700 pmap_pinit0(struct pmap *pmap)
1701 {
1702         pmap->pm_pml4 = (pml4_entry_t *)(PTOV_OFFSET + KPML4phys);
1703         pmap->pm_count = 1;
1704         CPUMASK_ASSZERO(pmap->pm_active);
1705         pmap->pm_pvhint = NULL;
1706         RB_INIT(&pmap->pm_pvroot);
1707         spin_init(&pmap->pm_spin, "pmapinit0");
1708         lwkt_token_init(&pmap->pm_token, "pmap_tok");
1709         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1710         pmap_pinit_defaults(pmap);
1711 }
1712
1713 /*
1714  * Initialize a preallocated and zeroed pmap structure,
1715  * such as one in a vmspace structure.
1716  */
1717 static void
1718 pmap_pinit_simple(struct pmap *pmap)
1719 {
1720         /*
1721          * Misc initialization
1722          */
1723         pmap->pm_count = 1;
1724         CPUMASK_ASSZERO(pmap->pm_active);
1725         pmap->pm_pvhint = NULL;
1726         pmap->pm_flags = PMAP_FLAG_SIMPLE;
1727
1728         pmap_pinit_defaults(pmap);
1729
1730         /*
1731          * Don't blow up locks/tokens on re-use (XXX fix/use drop code
1732          * for this).
1733          */
1734         if (pmap->pm_pmlpv == NULL) {
1735                 RB_INIT(&pmap->pm_pvroot);
1736                 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1737                 spin_init(&pmap->pm_spin, "pmapinitsimple");
1738                 lwkt_token_init(&pmap->pm_token, "pmap_tok");
1739         }
1740 }
1741
1742 void
1743 pmap_pinit(struct pmap *pmap)
1744 {
1745         pv_entry_t pv;
1746         int j;
1747
1748         if (pmap->pm_pmlpv) {
1749                 if (pmap->pmap_bits[TYPE_IDX] != REGULAR_PMAP) {
1750                         pmap_puninit(pmap);
1751                 }
1752         }
1753
1754         pmap_pinit_simple(pmap);
1755         pmap->pm_flags &= ~PMAP_FLAG_SIMPLE;
1756
1757         /*
1758          * No need to allocate page table space yet but we do need a valid
1759          * page directory table.
1760          */
1761         if (pmap->pm_pml4 == NULL) {
1762                 pmap->pm_pml4 =
1763                     (pml4_entry_t *)kmem_alloc_pageable(&kernel_map,
1764                                                         PAGE_SIZE,
1765                                                         VM_SUBSYS_PML4);
1766         }
1767
1768         /*
1769          * Allocate the page directory page, which wires it even though
1770          * it isn't being entered into some higher level page table (it
1771          * being the highest level).  If one is already cached we don't
1772          * have to do anything.
1773          */
1774         if ((pv = pmap->pm_pmlpv) == NULL) {
1775                 pv = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
1776                 pmap->pm_pmlpv = pv;
1777                 pmap_kenter((vm_offset_t)pmap->pm_pml4,
1778                             VM_PAGE_TO_PHYS(pv->pv_m));
1779                 pv_put(pv);
1780
1781                 /*
1782                  * Install DMAP and KMAP.
1783                  */
1784                 for (j = 0; j < NDMPML4E; ++j) {
1785                         pmap->pm_pml4[DMPML4I + j] =
1786                             (DMPDPphys + ((vm_paddr_t)j << PML4SHIFT)) |
1787                             pmap->pmap_bits[PG_RW_IDX] |
1788                             pmap->pmap_bits[PG_V_IDX] |
1789                             pmap->pmap_bits[PG_U_IDX];
1790                 }
1791                 pmap->pm_pml4[KPML4I] = KPDPphys |
1792                     pmap->pmap_bits[PG_RW_IDX] |
1793                     pmap->pmap_bits[PG_V_IDX] |
1794                     pmap->pmap_bits[PG_U_IDX];
1795
1796                 /*
1797                  * install self-referential address mapping entry
1798                  */
1799                 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pv->pv_m) |
1800                     pmap->pmap_bits[PG_V_IDX] |
1801                     pmap->pmap_bits[PG_RW_IDX] |
1802                     pmap->pmap_bits[PG_A_IDX] |
1803                     pmap->pmap_bits[PG_M_IDX];
1804         } else {
1805                 KKASSERT(pv->pv_m->flags & PG_MAPPED);
1806                 KKASSERT(pv->pv_m->flags & PG_WRITEABLE);
1807         }
1808         KKASSERT(pmap->pm_pml4[255] == 0);
1809         KKASSERT(RB_ROOT(&pmap->pm_pvroot) == pv);
1810         KKASSERT(pv->pv_entry.rbe_left == NULL);
1811         KKASSERT(pv->pv_entry.rbe_right == NULL);
1812 }
1813
1814 /*
1815  * Clean up a pmap structure so it can be physically freed.  This routine
1816  * is called by the vmspace dtor function.  A great deal of pmap data is
1817  * left passively mapped to improve vmspace management so we have a bit
1818  * of cleanup work to do here.
1819  */
1820 void
1821 pmap_puninit(pmap_t pmap)
1822 {
1823         pv_entry_t pv;
1824         vm_page_t p;
1825
1826         KKASSERT(CPUMASK_TESTZERO(pmap->pm_active));
1827         if ((pv = pmap->pm_pmlpv) != NULL) {
1828                 if (pv_hold_try(pv) == 0)
1829                         pv_lock(pv);
1830                 KKASSERT(pv == pmap->pm_pmlpv);
1831                 p = pmap_remove_pv_page(pv);
1832                 pv_free(pv);
1833                 pmap_kremove((vm_offset_t)pmap->pm_pml4);
1834                 vm_page_busy_wait(p, FALSE, "pgpun");
1835                 KKASSERT(p->flags & (PG_FICTITIOUS|PG_UNMANAGED));
1836                 vm_page_unwire(p, 0);
1837                 vm_page_flag_clear(p, PG_MAPPED | PG_WRITEABLE);
1838
1839                 /*
1840                  * XXX eventually clean out PML4 static entries and
1841                  * use vm_page_free_zero()
1842                  */
1843                 vm_page_free(p);
1844                 pmap->pm_pmlpv = NULL;
1845         }
1846         if (pmap->pm_pml4) {
1847                 KKASSERT(pmap->pm_pml4 != (void *)(PTOV_OFFSET + KPML4phys));
1848                 kmem_free(&kernel_map, (vm_offset_t)pmap->pm_pml4, PAGE_SIZE);
1849                 pmap->pm_pml4 = NULL;
1850         }
1851         KKASSERT(pmap->pm_stats.resident_count == 0);
1852         KKASSERT(pmap->pm_stats.wired_count == 0);
1853 }
1854
1855 /*
1856  * Wire in kernel global address entries.  To avoid a race condition
1857  * between pmap initialization and pmap_growkernel, this procedure
1858  * adds the pmap to the master list (which growkernel scans to update),
1859  * then copies the template.
1860  */
1861 void
1862 pmap_pinit2(struct pmap *pmap)
1863 {
1864         spin_lock(&pmap_spin);
1865         TAILQ_INSERT_TAIL(&pmap_list, pmap, pm_pmnode);
1866         spin_unlock(&pmap_spin);
1867 }
1868
1869 /*
1870  * This routine is called when various levels in the page table need to
1871  * be populated.  This routine cannot fail.
1872  *
1873  * This function returns two locked pv_entry's, one representing the
1874  * requested pv and one representing the requested pv's parent pv.  If
1875  * the pv did not previously exist it will be mapped into its parent
1876  * and wired, otherwise no additional wire count will be added.
1877  */
1878 static
1879 pv_entry_t
1880 pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp)
1881 {
1882         pt_entry_t *ptep;
1883         pv_entry_t pv;
1884         pv_entry_t pvp;
1885         vm_pindex_t pt_pindex;
1886         vm_page_t m;
1887         int isnew;
1888         int ispt;
1889
1890         /*
1891          * If the pv already exists and we aren't being asked for the
1892          * parent page table page we can just return it.  A locked+held pv
1893          * is returned.  The pv will also have a second hold related to the
1894          * pmap association that we don't have to worry about.
1895          */
1896         ispt = 0;
1897         pv = pv_alloc(pmap, ptepindex, &isnew);
1898         if (isnew == 0 && pvpp == NULL)
1899                 return(pv);
1900
1901         /*
1902          * Special case terminal PVs.  These are not page table pages so
1903          * no vm_page is allocated (the caller supplied the vm_page).  If
1904          * pvpp is non-NULL we are being asked to also removed the pt_pv
1905          * for this pv.
1906          *
1907          * Note that pt_pv's are only returned for user VAs. We assert that
1908          * a pt_pv is not being requested for kernel VAs.
1909          */
1910         if (ptepindex < pmap_pt_pindex(0)) {
1911                 if (ptepindex >= NUPTE_USER)
1912                         KKASSERT(pvpp == NULL);
1913                 else
1914                         KKASSERT(pvpp != NULL);
1915                 if (pvpp) {
1916                         pt_pindex = NUPTE_TOTAL + (ptepindex >> NPTEPGSHIFT);
1917                         pvp = pmap_allocpte(pmap, pt_pindex, NULL);
1918                         if (isnew)
1919                                 vm_page_wire_quick(pvp->pv_m);
1920                         *pvpp = pvp;
1921                 } else {
1922                         pvp = NULL;
1923                 }
1924                 return(pv);
1925         }
1926
1927         /*
1928          * Non-terminal PVs allocate a VM page to represent the page table,
1929          * so we have to resolve pvp and calculate ptepindex for the pvp
1930          * and then for the page table entry index in the pvp for
1931          * fall-through.
1932          */
1933         if (ptepindex < pmap_pd_pindex(0)) {
1934                 /*
1935                  * pv is PT, pvp is PD
1936                  */
1937                 ptepindex = (ptepindex - pmap_pt_pindex(0)) >> NPDEPGSHIFT;
1938                 ptepindex += NUPTE_TOTAL + NUPT_TOTAL;
1939                 pvp = pmap_allocpte(pmap, ptepindex, NULL);
1940                 if (!isnew)
1941                         goto notnew;
1942
1943                 /*
1944                  * PT index in PD
1945                  */
1946                 ptepindex = pv->pv_pindex - pmap_pt_pindex(0);
1947                 ptepindex &= ((1ul << NPDEPGSHIFT) - 1);
1948                 ispt = 1;
1949         } else if (ptepindex < pmap_pdp_pindex(0)) {
1950                 /*
1951                  * pv is PD, pvp is PDP
1952                  *
1953                  * SIMPLE PMAP NOTE: Simple pmaps do not allocate above
1954                  *                   the PD.
1955                  */
1956                 ptepindex = (ptepindex - pmap_pd_pindex(0)) >> NPDPEPGSHIFT;
1957                 ptepindex += NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL;
1958
1959                 if (pmap->pm_flags & PMAP_FLAG_SIMPLE) {
1960                         KKASSERT(pvpp == NULL);
1961                         pvp = NULL;
1962                 } else {
1963                         pvp = pmap_allocpte(pmap, ptepindex, NULL);
1964                 }
1965                 if (!isnew)
1966                         goto notnew;
1967
1968                 /*
1969                  * PD index in PDP
1970                  */
1971                 ptepindex = pv->pv_pindex - pmap_pd_pindex(0);
1972                 ptepindex &= ((1ul << NPDPEPGSHIFT) - 1);
1973         } else if (ptepindex < pmap_pml4_pindex()) {
1974                 /*
1975                  * pv is PDP, pvp is the root pml4 table
1976                  */
1977                 pvp = pmap_allocpte(pmap, pmap_pml4_pindex(), NULL);
1978                 if (!isnew)
1979                         goto notnew;
1980
1981                 /*
1982                  * PDP index in PML4
1983                  */
1984                 ptepindex = pv->pv_pindex - pmap_pdp_pindex(0);
1985                 ptepindex &= ((1ul << NPML4EPGSHIFT) - 1);
1986         } else {
1987                 /*
1988                  * pv represents the top-level PML4, there is no parent.
1989                  */
1990                 pvp = NULL;
1991                 if (!isnew)
1992                         goto notnew;
1993         }
1994
1995         /*
1996          * This code is only reached if isnew is TRUE and this is not a
1997          * terminal PV.  We need to allocate a vm_page for the page table
1998          * at this level and enter it into the parent page table.
1999          *
2000          * page table pages are marked PG_WRITEABLE and PG_MAPPED.
2001          */
2002         for (;;) {
2003                 m = vm_page_alloc(NULL, pv->pv_pindex,
2004                                   VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2005                                   VM_ALLOC_INTERRUPT);
2006                 if (m)
2007                         break;
2008                 vm_wait(0);
2009         }
2010         vm_page_spin_lock(m);
2011         pmap_page_stats_adding(m);
2012         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2013         pv->pv_m = m;
2014         vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
2015         vm_page_spin_unlock(m);
2016         vm_page_unmanage(m);    /* m must be spinunlocked */
2017
2018         pmap_zero_page(VM_PAGE_TO_PHYS(m));
2019         m->valid = VM_PAGE_BITS_ALL;
2020         vm_page_wire(m);        /* wire for mapping in parent */
2021
2022         /*
2023          * Wire the page into pvp, bump the wire-count for pvp's page table
2024          * page.  Bump the resident_count for the pmap.  There is no pvp
2025          * for the top level, address the pm_pml4[] array directly.
2026          *
2027          * If the caller wants the parent we return it, otherwise
2028          * we just put it away.
2029          *
2030          * No interlock is needed for pte 0 -> non-zero.
2031          *
2032          * In the situation where *ptep is valid we might have an unmanaged
2033          * page table page shared from another page table which we need to
2034          * unshare before installing our private page table page.
2035          */
2036         if (pvp) {
2037                 ptep = pv_pte_lookup(pvp, ptepindex);
2038                 if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
2039                         pt_entry_t pte;
2040
2041                         if (ispt == 0) {
2042                                 panic("pmap_allocpte: unexpected pte %p/%d",
2043                                       pvp, (int)ptepindex);
2044                         }
2045                         pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
2046                         if (vm_page_unwire_quick(
2047                                         PHYS_TO_VM_PAGE(pte & PG_FRAME))) {
2048                                 panic("pmap_allocpte: shared pgtable "
2049                                       "pg bad wirecount");
2050                         }
2051                         atomic_add_long(&pmap->pm_stats.resident_count, -1);
2052                 } else {
2053                         vm_page_wire_quick(pvp->pv_m);
2054                 }
2055                 *ptep = VM_PAGE_TO_PHYS(m) |
2056                     (pmap->pmap_bits[PG_U_IDX] |
2057                     pmap->pmap_bits[PG_RW_IDX] |
2058                     pmap->pmap_bits[PG_V_IDX] |
2059                     pmap->pmap_bits[PG_A_IDX] |
2060                     pmap->pmap_bits[PG_M_IDX]);
2061         }
2062         vm_page_wakeup(m);
2063 notnew:
2064         if (pvpp)
2065                 *pvpp = pvp;
2066         else if (pvp)
2067                 pv_put(pvp);
2068         return (pv);
2069 }
2070
2071 /*
2072  * This version of pmap_allocpte() checks for possible segment optimizations
2073  * that would allow page-table sharing.  It can be called for terminal
2074  * page or page table page ptepindex's.
2075  *
2076  * The function is called with page table page ptepindex's for fictitious
2077  * and unmanaged terminal pages.  That is, we don't want to allocate a
2078  * terminal pv, we just want the pt_pv.  pvpp is usually passed as NULL
2079  * for this case.
2080  *
2081  * This function can return a pv and *pvpp associated with the passed in pmap
2082  * OR a pv and *pvpp associated with the shared pmap.  In the latter case
2083  * an unmanaged page table page will be entered into the pass in pmap.
2084  */
2085 static
2086 pv_entry_t
2087 pmap_allocpte_seg(pmap_t pmap, vm_pindex_t ptepindex, pv_entry_t *pvpp,
2088                   vm_map_entry_t entry, vm_offset_t va)
2089 {
2090         vm_object_t object;
2091         pmap_t obpmap;
2092         pmap_t *obpmapp;
2093         vm_offset_t b;
2094         pv_entry_t pte_pv;      /* in original or shared pmap */
2095         pv_entry_t pt_pv;       /* in original or shared pmap */
2096         pv_entry_t proc_pd_pv;  /* in original pmap */
2097         pv_entry_t proc_pt_pv;  /* in original pmap */
2098         pv_entry_t xpv;         /* PT in shared pmap */
2099         pd_entry_t *pt;         /* PT entry in PD of original pmap */
2100         pd_entry_t opte;        /* contents of *pt */
2101         pd_entry_t npte;        /* contents of *pt */
2102         vm_page_t m;
2103
2104 retry:
2105         /*
2106          * Basic tests, require a non-NULL vm_map_entry, require proper
2107          * alignment and type for the vm_map_entry, require that the
2108          * underlying object already be allocated.
2109          *
2110          * We allow almost any type of object to use this optimization.
2111          * The object itself does NOT have to be sized to a multiple of the
2112          * segment size, but the memory mapping does.
2113          *
2114          * XXX don't handle devices currently, because VM_PAGE_TO_PHYS()
2115          *     won't work as expected.
2116          */
2117         if (entry == NULL ||
2118             pmap_mmu_optimize == 0 ||                   /* not enabled */
2119             (pmap->pm_flags & PMAP_HVM) ||              /* special pmap */
2120             ptepindex >= pmap_pd_pindex(0) ||           /* not terminal or pt */
2121             entry->inheritance != VM_INHERIT_SHARE ||   /* not shared */
2122             entry->maptype != VM_MAPTYPE_NORMAL ||      /* weird map type */
2123             entry->object.vm_object == NULL ||          /* needs VM object */
2124             entry->object.vm_object->type == OBJT_DEVICE ||     /* ick */
2125             entry->object.vm_object->type == OBJT_MGTDEVICE ||  /* ick */
2126             (entry->offset & SEG_MASK) ||               /* must be aligned */
2127             (entry->start & SEG_MASK)) {
2128                 return(pmap_allocpte(pmap, ptepindex, pvpp));
2129         }
2130
2131         /*
2132          * Make sure the full segment can be represented.
2133          */
2134         b = va & ~(vm_offset_t)SEG_MASK;
2135         if (b < entry->start || b + SEG_SIZE > entry->end)
2136                 return(pmap_allocpte(pmap, ptepindex, pvpp));
2137
2138         /*
2139          * If the full segment can be represented dive the VM object's
2140          * shared pmap, allocating as required.
2141          */
2142         object = entry->object.vm_object;
2143
2144         if (entry->protection & VM_PROT_WRITE)
2145                 obpmapp = &object->md.pmap_rw;
2146         else
2147                 obpmapp = &object->md.pmap_ro;
2148
2149 #ifdef PMAP_DEBUG2
2150         if (pmap_enter_debug > 0) {
2151                 --pmap_enter_debug;
2152                 kprintf("pmap_allocpte_seg: va=%jx prot %08x o=%p "
2153                         "obpmapp %p %p\n",
2154                         va, entry->protection, object,
2155                         obpmapp, *obpmapp);
2156                 kprintf("pmap_allocpte_seg: entry %p %jx-%jx\n",
2157                         entry, entry->start, entry->end);
2158         }
2159 #endif
2160
2161         /*
2162          * We allocate what appears to be a normal pmap but because portions
2163          * of this pmap are shared with other unrelated pmaps we have to
2164          * set pm_active to point to all cpus.
2165          *
2166          * XXX Currently using pmap_spin to interlock the update, can't use
2167          *     vm_object_hold/drop because the token might already be held
2168          *     shared OR exclusive and we don't know.
2169          */
2170         while ((obpmap = *obpmapp) == NULL) {
2171                 obpmap = kmalloc(sizeof(*obpmap), M_OBJPMAP, M_WAITOK|M_ZERO);
2172                 pmap_pinit_simple(obpmap);
2173                 pmap_pinit2(obpmap);
2174                 spin_lock(&pmap_spin);
2175                 if (*obpmapp != NULL) {
2176                         /*
2177                          * Handle race
2178                          */
2179                         spin_unlock(&pmap_spin);
2180                         pmap_release(obpmap);
2181                         pmap_puninit(obpmap);
2182                         kfree(obpmap, M_OBJPMAP);
2183                         obpmap = *obpmapp; /* safety */
2184                 } else {
2185                         obpmap->pm_active = smp_active_mask;
2186                         obpmap->pm_flags |= PMAP_SEGSHARED;
2187                         *obpmapp = obpmap;
2188                         spin_unlock(&pmap_spin);
2189                 }
2190         }
2191
2192         /*
2193          * Layering is: PTE, PT, PD, PDP, PML4.  We have to return the
2194          * pte/pt using the shared pmap from the object but also adjust
2195          * the process pmap's page table page as a side effect.
2196          */
2197
2198         /*
2199          * Resolve the terminal PTE and PT in the shared pmap.  This is what
2200          * we will return.  This is true if ptepindex represents a terminal
2201          * page, otherwise pte_pv is actually the PT and pt_pv is actually
2202          * the PD.
2203          */
2204         pt_pv = NULL;
2205         pte_pv = pmap_allocpte(obpmap, ptepindex, &pt_pv);
2206         if (ptepindex >= pmap_pt_pindex(0))
2207                 xpv = pte_pv;
2208         else
2209                 xpv = pt_pv;
2210
2211         /*
2212          * Resolve the PD in the process pmap so we can properly share the
2213          * page table page.  Lock order is bottom-up (leaf first)!
2214          *
2215          * NOTE: proc_pt_pv can be NULL.
2216          */
2217         proc_pt_pv = pv_get(pmap, pmap_pt_pindex(b));
2218         proc_pd_pv = pmap_allocpte(pmap, pmap_pd_pindex(b), NULL);
2219 #ifdef PMAP_DEBUG2
2220         if (pmap_enter_debug > 0) {
2221                 --pmap_enter_debug;
2222                 kprintf("proc_pt_pv %p (wc %d) pd_pv %p va=%jx\n",
2223                         proc_pt_pv,
2224                         (proc_pt_pv ? proc_pt_pv->pv_m->wire_count : -1),
2225                         proc_pd_pv,
2226                         va);
2227         }
2228 #endif
2229
2230         /*
2231          * xpv is the page table page pv from the shared object
2232          * (for convenience), from above.
2233          *
2234          * Calculate the pte value for the PT to load into the process PD.
2235          * If we have to change it we must properly dispose of the previous
2236          * entry.
2237          */
2238         pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2239         npte = VM_PAGE_TO_PHYS(xpv->pv_m) |
2240             (pmap->pmap_bits[PG_U_IDX] |
2241             pmap->pmap_bits[PG_RW_IDX] |
2242             pmap->pmap_bits[PG_V_IDX] |
2243             pmap->pmap_bits[PG_A_IDX] |
2244             pmap->pmap_bits[PG_M_IDX]);
2245
2246         /*
2247          * Dispose of previous page table page if it was local to the
2248          * process pmap.  If the old pt is not empty we cannot dispose of it
2249          * until we clean it out.  This case should not arise very often so
2250          * it is not optimized.
2251          */
2252         if (proc_pt_pv) {
2253                 pmap_inval_bulk_t bulk;
2254
2255                 if (proc_pt_pv->pv_m->wire_count != 1) {
2256                         pv_put(proc_pd_pv);
2257                         pv_put(proc_pt_pv);
2258                         pv_put(pt_pv);
2259                         pv_put(pte_pv);
2260                         pmap_remove(pmap,
2261                                     va & ~(vm_offset_t)SEG_MASK,
2262                                     (va + SEG_SIZE) & ~(vm_offset_t)SEG_MASK);
2263                         goto retry;
2264                 }
2265
2266                 /*
2267                  * The release call will indirectly clean out *pt
2268                  */
2269                 pmap_inval_bulk_init(&bulk, proc_pt_pv->pv_pmap);
2270                 pmap_release_pv(proc_pt_pv, proc_pd_pv, &bulk);
2271                 pmap_inval_bulk_flush(&bulk);
2272                 proc_pt_pv = NULL;
2273                 /* relookup */
2274                 pt = pv_pte_lookup(proc_pd_pv, pmap_pt_index(b));
2275         }
2276
2277         /*
2278          * Handle remaining cases.
2279          */
2280         if (*pt == 0) {
2281                 *pt = npte;
2282                 vm_page_wire_quick(xpv->pv_m);
2283                 vm_page_wire_quick(proc_pd_pv->pv_m);
2284                 atomic_add_long(&pmap->pm_stats.resident_count, 1);
2285         } else if (*pt != npte) {
2286                 opte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, pt, npte);
2287
2288 #if 0
2289                 opte = pte_load_clear(pt);
2290                 KKASSERT(opte && opte != npte);
2291
2292                 *pt = npte;
2293 #endif
2294                 vm_page_wire_quick(xpv->pv_m);  /* pgtable pg that is npte */
2295
2296                 /*
2297                  * Clean up opte, bump the wire_count for the process
2298                  * PD page representing the new entry if it was
2299                  * previously empty.
2300                  *
2301                  * If the entry was not previously empty and we have
2302                  * a PT in the proc pmap then opte must match that
2303                  * pt.  The proc pt must be retired (this is done
2304                  * later on in this procedure).
2305                  *
2306                  * NOTE: replacing valid pte, wire_count on proc_pd_pv
2307                  * stays the same.
2308                  */
2309                 KKASSERT(opte & pmap->pmap_bits[PG_V_IDX]);
2310                 m = PHYS_TO_VM_PAGE(opte & PG_FRAME);
2311                 if (vm_page_unwire_quick(m)) {
2312                         panic("pmap_allocpte_seg: "
2313                               "bad wire count %p",
2314                               m);
2315                 }
2316         }
2317
2318         /*
2319          * The existing process page table was replaced and must be destroyed
2320          * here.
2321          */
2322         if (proc_pd_pv)
2323                 pv_put(proc_pd_pv);
2324         if (pvpp)
2325                 *pvpp = pt_pv;
2326         else
2327                 pv_put(pt_pv);
2328
2329         return (pte_pv);
2330 }
2331
2332 /*
2333  * Release any resources held by the given physical map.
2334  *
2335  * Called when a pmap initialized by pmap_pinit is being released.  Should
2336  * only be called if the map contains no valid mappings.
2337  *
2338  * Caller must hold pmap->pm_token
2339  */
2340 struct pmap_release_info {
2341         pmap_t  pmap;
2342         int     retry;
2343 };
2344
2345 static int pmap_release_callback(pv_entry_t pv, void *data);
2346
2347 void
2348 pmap_release(struct pmap *pmap)
2349 {
2350         struct pmap_release_info info;
2351
2352         KASSERT(CPUMASK_TESTZERO(pmap->pm_active),
2353                 ("pmap still active! %016jx",
2354                 (uintmax_t)CPUMASK_LOWMASK(pmap->pm_active)));
2355
2356         spin_lock(&pmap_spin);
2357         TAILQ_REMOVE(&pmap_list, pmap, pm_pmnode);
2358         spin_unlock(&pmap_spin);
2359
2360         /*
2361          * Pull pv's off the RB tree in order from low to high and release
2362          * each page.
2363          */
2364         info.pmap = pmap;
2365         do {
2366                 info.retry = 0;
2367                 spin_lock(&pmap->pm_spin);
2368                 RB_SCAN(pv_entry_rb_tree, &pmap->pm_pvroot, NULL,
2369                         pmap_release_callback, &info);
2370                 spin_unlock(&pmap->pm_spin);
2371         } while (info.retry);
2372
2373
2374         /*
2375          * One resident page (the pml4 page) should remain.
2376          * No wired pages should remain.
2377          */
2378         KKASSERT(pmap->pm_stats.resident_count ==
2379                  ((pmap->pm_flags & PMAP_FLAG_SIMPLE) ? 0 : 1));
2380
2381         KKASSERT(pmap->pm_stats.wired_count == 0);
2382 }
2383
2384 static int
2385 pmap_release_callback(pv_entry_t pv, void *data)
2386 {
2387         struct pmap_release_info *info = data;
2388         pmap_t pmap = info->pmap;
2389         int r;
2390
2391         if (pv_hold_try(pv)) {
2392                 spin_unlock(&pmap->pm_spin);
2393         } else {
2394                 spin_unlock(&pmap->pm_spin);
2395                 pv_lock(pv);
2396         }
2397         if (pv->pv_pmap != pmap) {
2398                 pv_put(pv);
2399                 spin_lock(&pmap->pm_spin);
2400                 info->retry = 1;
2401                 return(-1);
2402         }
2403         r = pmap_release_pv(pv, NULL, NULL);
2404         spin_lock(&pmap->pm_spin);
2405         return(r);
2406 }
2407
2408 /*
2409  * Called with held (i.e. also locked) pv.  This function will dispose of
2410  * the lock along with the pv.
2411  *
2412  * If the caller already holds the locked parent page table for pv it
2413  * must pass it as pvp, allowing us to avoid a deadlock, else it can
2414  * pass NULL for pvp.
2415  */
2416 static int
2417 pmap_release_pv(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
2418 {
2419         vm_page_t p;
2420
2421         /*
2422          * The pmap is currently not spinlocked, pv is held+locked.
2423          * Remove the pv's page from its parent's page table.  The
2424          * parent's page table page's wire_count will be decremented.
2425          *
2426          * This will clean out the pte at any level of the page table.
2427          * If smp != 0 all cpus are affected.
2428          */
2429         pmap_remove_pv_pte(pv, pvp, bulk);
2430
2431         /*
2432          * Terminal pvs are unhooked from their vm_pages.  Because
2433          * terminal pages aren't page table pages they aren't wired
2434          * by us, so we have to be sure not to unwire them either.
2435          */
2436         if (pv->pv_pindex < pmap_pt_pindex(0)) {
2437                 pmap_remove_pv_page(pv);
2438                 goto skip;
2439         }
2440
2441         /*
2442          * We leave the top-level page table page cached, wired, and
2443          * mapped in the pmap until the dtor function (pmap_puninit())
2444          * gets called.
2445          *
2446          * Since we are leaving the top-level pv intact we need
2447          * to break out of what would otherwise be an infinite loop.
2448          */
2449         if (pv->pv_pindex == pmap_pml4_pindex()) {
2450                 pv_put(pv);
2451                 return(-1);
2452         }
2453
2454         /*
2455          * For page table pages (other than the top-level page),
2456          * remove and free the vm_page.  The representitive mapping
2457          * removed above by pmap_remove_pv_pte() did not undo the
2458          * last wire_count so we have to do that as well.
2459          */
2460         p = pmap_remove_pv_page(pv);
2461         vm_page_busy_wait(p, FALSE, "pmaprl");
2462         if (p->wire_count != 1) {
2463                 kprintf("p->wire_count was %016lx %d\n",
2464                         pv->pv_pindex, p->wire_count);
2465         }
2466         KKASSERT(p->wire_count == 1);
2467         KKASSERT(p->flags & PG_UNMANAGED);
2468
2469         vm_page_unwire(p, 0);
2470         KKASSERT(p->wire_count == 0);
2471
2472         vm_page_free(p);
2473 skip:
2474         pv_free(pv);
2475         return 0;
2476 }
2477
2478 /*
2479  * This function will remove the pte associated with a pv from its parent.
2480  * Terminal pv's are supported.  All cpus are affected if smp != 0.
2481  *
2482  * The wire count will be dropped on the parent page table.  The wire
2483  * count on the page being removed (pv->pv_m) from the parent page table
2484  * is NOT touched.  Note that terminal pages will not have any additional
2485  * wire counts while page table pages will have at least one representing
2486  * the mapping, plus others representing sub-mappings.
2487  *
2488  * NOTE: Cannot be called on kernel page table pages, only KVM terminal
2489  *       pages and user page table and terminal pages.
2490  *
2491  * The pv must be locked.
2492  *
2493  * XXX must lock parent pv's if they exist to remove pte XXX
2494  */
2495 static
2496 void
2497 pmap_remove_pv_pte(pv_entry_t pv, pv_entry_t pvp, pmap_inval_bulk_t *bulk)
2498 {
2499         vm_pindex_t ptepindex = pv->pv_pindex;
2500         pmap_t pmap = pv->pv_pmap;
2501         vm_page_t p;
2502         int gotpvp = 0;
2503
2504         KKASSERT(pmap);
2505
2506         if (ptepindex == pmap_pml4_pindex()) {
2507                 /*
2508                  * We are the top level pml4 table, there is no parent.
2509                  */
2510                 p = pmap->pm_pmlpv->pv_m;
2511         } else if (ptepindex >= pmap_pdp_pindex(0)) {
2512                 /*
2513                  * Remove a PDP page from the pml4e.  This can only occur
2514                  * with user page tables.  We do not have to lock the
2515                  * pml4 PV so just ignore pvp.
2516                  */
2517                 vm_pindex_t pml4_pindex;
2518                 vm_pindex_t pdp_index;
2519                 pml4_entry_t *pdp;
2520
2521                 pdp_index = ptepindex - pmap_pdp_pindex(0);
2522                 if (pvp == NULL) {
2523                         pml4_pindex = pmap_pml4_pindex();
2524                         pvp = pv_get(pv->pv_pmap, pml4_pindex);
2525                         KKASSERT(pvp);
2526                         gotpvp = 1;
2527                 }
2528                 pdp = &pmap->pm_pml4[pdp_index & ((1ul << NPML4EPGSHIFT) - 1)];
2529                 KKASSERT((*pdp & pmap->pmap_bits[PG_V_IDX]) != 0);
2530                 p = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2531                 pmap_inval_bulk(bulk, (vm_offset_t)-1, pdp, 0);
2532         } else if (ptepindex >= pmap_pd_pindex(0)) {
2533                 /*
2534                  * Remove a PD page from the pdp
2535                  *
2536                  * SIMPLE PMAP NOTE: Non-existant pvp's are ok in the case
2537                  *                   of a simple pmap because it stops at
2538                  *                   the PD page.
2539                  */
2540                 vm_pindex_t pdp_pindex;
2541                 vm_pindex_t pd_index;
2542                 pdp_entry_t *pd;
2543
2544                 pd_index = ptepindex - pmap_pd_pindex(0);
2545
2546                 if (pvp == NULL) {
2547                         pdp_pindex = NUPTE_TOTAL + NUPT_TOTAL + NUPD_TOTAL +
2548                                      (pd_index >> NPML4EPGSHIFT);
2549                         pvp = pv_get(pv->pv_pmap, pdp_pindex);
2550                         if (pvp)
2551                                 gotpvp = 1;
2552                 }
2553                 if (pvp) {
2554                         pd = pv_pte_lookup(pvp, pd_index &
2555                                                 ((1ul << NPDPEPGSHIFT) - 1));
2556                         KKASSERT((*pd & pmap->pmap_bits[PG_V_IDX]) != 0);
2557                         p = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2558                         pmap_inval_bulk(bulk, (vm_offset_t)-1, pd, 0);
2559                 } else {
2560                         KKASSERT(pmap->pm_flags & PMAP_FLAG_SIMPLE);
2561                         p = pv->pv_m;           /* degenerate test later */
2562                 }
2563         } else if (ptepindex >= pmap_pt_pindex(0)) {
2564                 /*
2565                  *  Remove a PT page from the pd
2566                  */
2567                 vm_pindex_t pd_pindex;
2568                 vm_pindex_t pt_index;
2569                 pd_entry_t *pt;
2570
2571                 pt_index = ptepindex - pmap_pt_pindex(0);
2572
2573                 if (pvp == NULL) {
2574                         pd_pindex = NUPTE_TOTAL + NUPT_TOTAL +
2575                                     (pt_index >> NPDPEPGSHIFT);
2576                         pvp = pv_get(pv->pv_pmap, pd_pindex);
2577                         KKASSERT(pvp);
2578                         gotpvp = 1;
2579                 }
2580                 pt = pv_pte_lookup(pvp, pt_index & ((1ul << NPDPEPGSHIFT) - 1));
2581                 KKASSERT((*pt & pmap->pmap_bits[PG_V_IDX]) != 0);
2582                 p = PHYS_TO_VM_PAGE(*pt & PG_FRAME);
2583                 pmap_inval_bulk(bulk, (vm_offset_t)-1, pt, 0);
2584         } else {
2585                 /*
2586                  * Remove a PTE from the PT page
2587                  *
2588                  * NOTE: pv's must be locked bottom-up to avoid deadlocking.
2589                  *       pv is a pte_pv so we can safely lock pt_pv.
2590                  *
2591                  * NOTE: FICTITIOUS pages may have multiple physical mappings
2592                  *       so PHYS_TO_VM_PAGE() will not necessarily work for
2593                  *       terminal ptes.
2594                  */
2595                 vm_pindex_t pt_pindex;
2596                 pt_entry_t *ptep;
2597                 pt_entry_t pte;
2598                 vm_offset_t va;
2599
2600                 pt_pindex = ptepindex >> NPTEPGSHIFT;
2601                 va = (vm_offset_t)ptepindex << PAGE_SHIFT;
2602
2603                 if (ptepindex >= NUPTE_USER) {
2604                         ptep = vtopte(ptepindex << PAGE_SHIFT);
2605                         KKASSERT(pvp == NULL);
2606                 } else {
2607                         if (pvp == NULL) {
2608                                 pt_pindex = NUPTE_TOTAL +
2609                                             (ptepindex >> NPDPEPGSHIFT);
2610                                 pvp = pv_get(pv->pv_pmap, pt_pindex);
2611                                 KKASSERT(pvp);
2612                                 gotpvp = 1;
2613                         }
2614                         ptep = pv_pte_lookup(pvp, ptepindex &
2615                                                   ((1ul << NPDPEPGSHIFT) - 1));
2616                 }
2617                 pte = pmap_inval_bulk(bulk, va, ptep, 0);
2618                 if (bulk == NULL)               /* XXX */
2619                         cpu_invlpg((void *)va); /* XXX */
2620
2621                 /*
2622                  * Now update the vm_page_t
2623                  */
2624                 if ((pte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) !=
2625                     (pmap->pmap_bits[PG_MANAGED_IDX]|pmap->pmap_bits[PG_V_IDX])) {
2626                         kprintf("remove_pte badpte %016lx %016lx %d\n",
2627                                 pte, pv->pv_pindex,
2628                                 pv->pv_pindex < pmap_pt_pindex(0));
2629                 }
2630                 /* PHYS_TO_VM_PAGE() will not work for FICTITIOUS pages */
2631                 /*KKASSERT((pte & (PG_MANAGED|PG_V)) == (PG_MANAGED|PG_V));*/
2632                 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
2633                         p = pv->pv_m;
2634                 else
2635                         p = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2636                 /* p = pv->pv_m; */
2637
2638                 if (pte & pmap->pmap_bits[PG_M_IDX]) {
2639                         if (pmap_track_modified(ptepindex))
2640                                 vm_page_dirty(p);
2641                 }
2642                 if (pte & pmap->pmap_bits[PG_A_IDX]) {
2643                         vm_page_flag_set(p, PG_REFERENCED);
2644                 }
2645                 if (pte & pmap->pmap_bits[PG_W_IDX])
2646                         atomic_add_long(&pmap->pm_stats.wired_count, -1);
2647                 if (pte & pmap->pmap_bits[PG_G_IDX])
2648                         cpu_invlpg((void *)va);
2649         }
2650
2651         /*
2652          * Unwire the parent page table page.  The wire_count cannot go below
2653          * 1 here because the parent page table page is itself still mapped.
2654          *
2655          * XXX remove the assertions later.
2656          */
2657         KKASSERT(pv->pv_m == p);
2658         if (pvp && vm_page_unwire_quick(pvp->pv_m))
2659                 panic("pmap_remove_pv_pte: Insufficient wire_count");
2660
2661         if (gotpvp)
2662                 pv_put(pvp);
2663 }
2664
2665 /*
2666  * Remove the vm_page association to a pv.  The pv must be locked.
2667  */
2668 static
2669 vm_page_t
2670 pmap_remove_pv_page(pv_entry_t pv)
2671 {
2672         vm_page_t m;
2673
2674         m = pv->pv_m;
2675         KKASSERT(m);
2676         vm_page_spin_lock(m);
2677         pv->pv_m = NULL;
2678         TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2679         pmap_page_stats_deleting(m);
2680         /*
2681         if (m->object)
2682                 atomic_add_int(&m->object->agg_pv_list_count, -1);
2683         */
2684         if (TAILQ_EMPTY(&m->md.pv_list))
2685                 vm_page_flag_clear(m, PG_MAPPED | PG_WRITEABLE);
2686         vm_page_spin_unlock(m);
2687         return(m);
2688 }
2689
2690 /*
2691  * Grow the number of kernel page table entries, if needed.
2692  *
2693  * This routine is always called to validate any address space
2694  * beyond KERNBASE (for kldloads).  kernel_vm_end only governs the address
2695  * space below KERNBASE.
2696  */
2697 void
2698 pmap_growkernel(vm_offset_t kstart, vm_offset_t kend)
2699 {
2700         vm_paddr_t paddr;
2701         vm_offset_t ptppaddr;
2702         vm_page_t nkpg;
2703         pd_entry_t *pt, newpt;
2704         pdp_entry_t newpd;
2705         int update_kernel_vm_end;
2706
2707         /*
2708          * bootstrap kernel_vm_end on first real VM use
2709          */
2710         if (kernel_vm_end == 0) {
2711                 kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
2712                 nkpt = 0;
2713                 while ((*pmap_pt(&kernel_pmap, kernel_vm_end) & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
2714                         kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) &
2715                                         ~(PAGE_SIZE * NPTEPG - 1);
2716                         nkpt++;
2717                         if (kernel_vm_end - 1 >= kernel_map.max_offset) {
2718                                 kernel_vm_end = kernel_map.max_offset;
2719                                 break;                       
2720                         }
2721                 }
2722         }
2723
2724         /*
2725          * Fill in the gaps.  kernel_vm_end is only adjusted for ranges
2726          * below KERNBASE.  Ranges above KERNBASE are kldloaded and we
2727          * do not want to force-fill 128G worth of page tables.
2728          */
2729         if (kstart < KERNBASE) {
2730                 if (kstart > kernel_vm_end)
2731                         kstart = kernel_vm_end;
2732                 KKASSERT(kend <= KERNBASE);
2733                 update_kernel_vm_end = 1;
2734         } else {
2735                 update_kernel_vm_end = 0;
2736         }
2737
2738         kstart = rounddown2(kstart, PAGE_SIZE * NPTEPG);
2739         kend = roundup2(kend, PAGE_SIZE * NPTEPG);
2740
2741         if (kend - 1 >= kernel_map.max_offset)
2742                 kend = kernel_map.max_offset;
2743
2744         while (kstart < kend) {
2745                 pt = pmap_pt(&kernel_pmap, kstart);
2746                 if (pt == NULL) {
2747                         /* We need a new PDP entry */
2748                         nkpg = vm_page_alloc(NULL, nkpt,
2749                                              VM_ALLOC_NORMAL |
2750                                              VM_ALLOC_SYSTEM |
2751                                              VM_ALLOC_INTERRUPT);
2752                         if (nkpg == NULL) {
2753                                 panic("pmap_growkernel: no memory to grow "
2754                                       "kernel");
2755                         }
2756                         paddr = VM_PAGE_TO_PHYS(nkpg);
2757                         pmap_zero_page(paddr);
2758                         newpd = (pdp_entry_t)
2759                             (paddr |
2760                             kernel_pmap.pmap_bits[PG_V_IDX] |
2761                             kernel_pmap.pmap_bits[PG_RW_IDX] |
2762                             kernel_pmap.pmap_bits[PG_A_IDX] |
2763                             kernel_pmap.pmap_bits[PG_M_IDX]);
2764                         *pmap_pd(&kernel_pmap, kstart) = newpd;
2765                         nkpt++;
2766                         continue; /* try again */
2767                 }
2768                 if ((*pt & kernel_pmap.pmap_bits[PG_V_IDX]) != 0) {
2769                         kstart = (kstart + PAGE_SIZE * NPTEPG) &
2770                                  ~(PAGE_SIZE * NPTEPG - 1);
2771                         if (kstart - 1 >= kernel_map.max_offset) {
2772                                 kstart = kernel_map.max_offset;
2773                                 break;                       
2774                         }
2775                         continue;
2776                 }
2777
2778                 /*
2779                  * This index is bogus, but out of the way
2780                  */
2781                 nkpg = vm_page_alloc(NULL, nkpt,
2782                                      VM_ALLOC_NORMAL |
2783                                      VM_ALLOC_SYSTEM |
2784                                      VM_ALLOC_INTERRUPT);
2785                 if (nkpg == NULL)
2786                         panic("pmap_growkernel: no memory to grow kernel");
2787
2788                 vm_page_wire(nkpg);
2789                 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
2790                 pmap_zero_page(ptppaddr);
2791                 newpt = (pd_entry_t) (ptppaddr |
2792                     kernel_pmap.pmap_bits[PG_V_IDX] |
2793                     kernel_pmap.pmap_bits[PG_RW_IDX] |
2794                     kernel_pmap.pmap_bits[PG_A_IDX] |
2795                     kernel_pmap.pmap_bits[PG_M_IDX]);
2796                 *pmap_pt(&kernel_pmap, kstart) = newpt;
2797                 nkpt++;
2798
2799                 kstart = (kstart + PAGE_SIZE * NPTEPG) &
2800                           ~(PAGE_SIZE * NPTEPG - 1);
2801
2802                 if (kstart - 1 >= kernel_map.max_offset) {
2803                         kstart = kernel_map.max_offset;
2804                         break;                       
2805                 }
2806         }
2807
2808         /*
2809          * Only update kernel_vm_end for areas below KERNBASE.
2810          */
2811         if (update_kernel_vm_end && kernel_vm_end < kstart)
2812                 kernel_vm_end = kstart;
2813 }
2814
2815 /*
2816  *      Add a reference to the specified pmap.
2817  */
2818 void
2819 pmap_reference(pmap_t pmap)
2820 {
2821         if (pmap != NULL) {
2822                 lwkt_gettoken(&pmap->pm_token);
2823                 ++pmap->pm_count;
2824                 lwkt_reltoken(&pmap->pm_token);
2825         }
2826 }
2827
2828 /***************************************************
2829  * page management routines.
2830  ***************************************************/
2831
2832 /*
2833  * Hold a pv without locking it
2834  */
2835 static void
2836 pv_hold(pv_entry_t pv)
2837 {
2838         atomic_add_int(&pv->pv_hold, 1);
2839 }
2840
2841 /*
2842  * Hold a pv_entry, preventing its destruction.  TRUE is returned if the pv
2843  * was successfully locked, FALSE if it wasn't.  The caller must dispose of
2844  * the pv properly.
2845  *
2846  * Either the pmap->pm_spin or the related vm_page_spin (if traversing a
2847  * pv list via its page) must be held by the caller.
2848  */
2849 static int
2850 _pv_hold_try(pv_entry_t pv PMAP_DEBUG_DECL)
2851 {
2852         u_int count;
2853
2854         /*
2855          * Critical path shortcut expects pv to already have one ref
2856          * (for the pv->pv_pmap).
2857          */
2858         if (atomic_cmpset_int(&pv->pv_hold, 1, PV_HOLD_LOCKED | 2)) {
2859 #ifdef PMAP_DEBUG
2860                 pv->pv_func = func;
2861                 pv->pv_line = lineno;
2862 #endif
2863                 return TRUE;
2864         }
2865
2866         for (;;) {
2867                 count = pv->pv_hold;
2868                 cpu_ccfence();
2869                 if ((count & PV_HOLD_LOCKED) == 0) {
2870                         if (atomic_cmpset_int(&pv->pv_hold, count,
2871                                               (count + 1) | PV_HOLD_LOCKED)) {
2872 #ifdef PMAP_DEBUG
2873                                 pv->pv_func = func;
2874                                 pv->pv_line = lineno;
2875 #endif
2876                                 return TRUE;
2877                         }
2878                 } else {
2879                         if (atomic_cmpset_int(&pv->pv_hold, count, count + 1))
2880                                 return FALSE;
2881                 }
2882                 /* retry */
2883         }
2884 }
2885
2886 /*
2887  * Drop a previously held pv_entry which could not be locked, allowing its
2888  * destruction.
2889  *
2890  * Must not be called with a spinlock held as we might zfree() the pv if it
2891  * is no longer associated with a pmap and this was the last hold count.
2892  */
2893 static void
2894 pv_drop(pv_entry_t pv)
2895 {
2896         u_int count;
2897
2898         for (;;) {
2899                 count = pv->pv_hold;
2900                 cpu_ccfence();
2901                 KKASSERT((count & PV_HOLD_MASK) > 0);
2902                 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) !=
2903                          (PV_HOLD_LOCKED | 1));
2904                 if (atomic_cmpset_int(&pv->pv_hold, count, count - 1)) {
2905                         if ((count & PV_HOLD_MASK) == 1) {
2906 #ifdef PMAP_DEBUG2
2907                                 if (pmap_enter_debug > 0) {
2908                                         --pmap_enter_debug;
2909                                         kprintf("pv_drop: free pv %p\n", pv);
2910                                 }
2911 #endif
2912                                 KKASSERT(count == 1);
2913                                 KKASSERT(pv->pv_pmap == NULL);
2914                                 zfree(pvzone, pv);
2915                         }
2916                         return;
2917                 }
2918                 /* retry */
2919         }
2920 }
2921
2922 /*
2923  * Find or allocate the requested PV entry, returning a locked, held pv.
2924  *
2925  * If (*isnew) is non-zero, the returned pv will have two hold counts, one
2926  * for the caller and one representing the pmap and vm_page association.
2927  *
2928  * If (*isnew) is zero, the returned pv will have only one hold count.
2929  *
2930  * Since both associations can only be adjusted while the pv is locked,
2931  * together they represent just one additional hold.
2932  */
2933 static
2934 pv_entry_t
2935 _pv_alloc(pmap_t pmap, vm_pindex_t pindex, int *isnew PMAP_DEBUG_DECL)
2936 {
2937         pv_entry_t pv;
2938         pv_entry_t pnew = NULL;
2939
2940         spin_lock(&pmap->pm_spin);
2941         for (;;) {
2942                 if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex) {
2943                         pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot,
2944                                                         pindex);
2945                 }
2946                 if (pv == NULL) {
2947                         if (pnew == NULL) {
2948                                 spin_unlock(&pmap->pm_spin);
2949                                 pnew = zalloc(pvzone);
2950                                 spin_lock(&pmap->pm_spin);
2951                                 continue;
2952                         }
2953                         pnew->pv_pmap = pmap;
2954                         pnew->pv_pindex = pindex;
2955                         pnew->pv_hold = PV_HOLD_LOCKED | 2;
2956 #ifdef PMAP_DEBUG
2957                         pnew->pv_func = func;
2958                         pnew->pv_line = lineno;
2959 #endif
2960                         pv_entry_rb_tree_RB_INSERT(&pmap->pm_pvroot, pnew);
2961                         ++pmap->pm_generation;
2962                         atomic_add_long(&pmap->pm_stats.resident_count, 1);
2963                         spin_unlock(&pmap->pm_spin);
2964                         *isnew = 1;
2965                         return(pnew);
2966                 }
2967                 if (pnew) {
2968                         spin_unlock(&pmap->pm_spin);
2969                         zfree(pvzone, pnew);
2970                         pnew = NULL;
2971                         spin_lock(&pmap->pm_spin);
2972                         continue;
2973                 }
2974                 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
2975                         spin_unlock(&pmap->pm_spin);
2976                 } else {
2977                         spin_unlock(&pmap->pm_spin);
2978                         _pv_lock(pv PMAP_DEBUG_COPY);
2979                 }
2980                 if (pv->pv_pmap == pmap && pv->pv_pindex == pindex) {
2981                         *isnew = 0;
2982                         return(pv);
2983                 }
2984                 pv_put(pv);
2985                 spin_lock(&pmap->pm_spin);
2986         }
2987 }
2988
2989 /*
2990  * Find the requested PV entry, returning a locked+held pv or NULL
2991  */
2992 static
2993 pv_entry_t
2994 _pv_get(pmap_t pmap, vm_pindex_t pindex PMAP_DEBUG_DECL)
2995 {
2996         pv_entry_t pv;
2997
2998         spin_lock(&pmap->pm_spin);
2999         for (;;) {
3000                 /*
3001                  * Shortcut cache
3002                  */
3003                 if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex) {
3004                         pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot,
3005                                                         pindex);
3006                 }
3007                 if (pv == NULL) {
3008                         spin_unlock(&pmap->pm_spin);
3009                         return NULL;
3010                 }
3011                 if (_pv_hold_try(pv PMAP_DEBUG_COPY)) {
3012                         spin_unlock(&pmap->pm_spin);
3013                 } else {
3014                         spin_unlock(&pmap->pm_spin);
3015                         _pv_lock(pv PMAP_DEBUG_COPY);
3016                 }
3017                 if (pv->pv_pmap == pmap && pv->pv_pindex == pindex) {
3018                         pv_cache(pv, pindex);
3019                         return(pv);
3020                 }
3021                 pv_put(pv);
3022                 spin_lock(&pmap->pm_spin);
3023         }
3024 }
3025
3026 /*
3027  * Lookup, hold, and attempt to lock (pmap,pindex).
3028  *
3029  * If the entry does not exist NULL is returned and *errorp is set to 0
3030  *
3031  * If the entry exists and could be successfully locked it is returned and
3032  * errorp is set to 0.
3033  *
3034  * If the entry exists but could NOT be successfully locked it is returned
3035  * held and *errorp is set to 1.
3036  */
3037 static
3038 pv_entry_t
3039 pv_get_try(pmap_t pmap, vm_pindex_t pindex, int *errorp)
3040 {
3041         pv_entry_t pv;
3042
3043         spin_lock_shared(&pmap->pm_spin);
3044         if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex)
3045                 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
3046         if (pv == NULL) {
3047                 spin_unlock_shared(&pmap->pm_spin);
3048                 *errorp = 0;
3049                 return NULL;
3050         }
3051         if (pv_hold_try(pv)) {
3052                 pv_cache(pv, pindex);
3053                 spin_unlock_shared(&pmap->pm_spin);
3054                 *errorp = 0;
3055                 KKASSERT(pv->pv_pmap == pmap && pv->pv_pindex == pindex);
3056                 return(pv);     /* lock succeeded */
3057         }
3058         spin_unlock_shared(&pmap->pm_spin);
3059         *errorp = 1;
3060         return (pv);            /* lock failed */
3061 }
3062
3063 /*
3064  * Find the requested PV entry, returning a held pv or NULL
3065  */
3066 static
3067 pv_entry_t
3068 pv_find(pmap_t pmap, vm_pindex_t pindex)
3069 {
3070         pv_entry_t pv;
3071
3072         spin_lock_shared(&pmap->pm_spin);
3073
3074         if ((pv = pmap->pm_pvhint) == NULL || pv->pv_pindex != pindex)
3075                 pv = pv_entry_rb_tree_RB_LOOKUP(&pmap->pm_pvroot, pindex);
3076         if (pv == NULL) {
3077                 spin_unlock_shared(&pmap->pm_spin);
3078                 return NULL;
3079         }
3080         pv_hold(pv);
3081         pv_cache(pv, pindex);
3082         spin_unlock_shared(&pmap->pm_spin);
3083         return(pv);
3084 }
3085
3086 /*
3087  * Lock a held pv, keeping the hold count
3088  */
3089 static
3090 void
3091 _pv_lock(pv_entry_t pv PMAP_DEBUG_DECL)
3092 {
3093         u_int count;
3094
3095         for (;;) {
3096                 count = pv->pv_hold;
3097                 cpu_ccfence();
3098                 if ((count & PV_HOLD_LOCKED) == 0) {
3099                         if (atomic_cmpset_int(&pv->pv_hold, count,
3100                                               count | PV_HOLD_LOCKED)) {
3101 #ifdef PMAP_DEBUG
3102                                 pv->pv_func = func;
3103                                 pv->pv_line = lineno;
3104 #endif
3105                                 return;
3106                         }
3107                         continue;
3108                 }
3109                 tsleep_interlock(pv, 0);
3110                 if (atomic_cmpset_int(&pv->pv_hold, count,
3111                                       count | PV_HOLD_WAITING)) {
3112 #ifdef PMAP_DEBUG
3113                         kprintf("pv waiting on %s:%d\n",
3114                                         pv->pv_func, pv->pv_line);
3115 #endif
3116                         tsleep(pv, PINTERLOCKED, "pvwait", hz);
3117                 }
3118                 /* retry */
3119         }
3120 }
3121
3122 /*
3123  * Unlock a held and locked pv, keeping the hold count.
3124  */
3125 static
3126 void
3127 pv_unlock(pv_entry_t pv)
3128 {
3129         u_int count;
3130
3131         for (;;) {
3132                 count = pv->pv_hold;
3133                 cpu_ccfence();
3134                 KKASSERT((count & (PV_HOLD_LOCKED | PV_HOLD_MASK)) >=
3135                          (PV_HOLD_LOCKED | 1));
3136                 if (atomic_cmpset_int(&pv->pv_hold, count,
3137                                       count &
3138                                       ~(PV_HOLD_LOCKED | PV_HOLD_WAITING))) {
3139                         if (count & PV_HOLD_WAITING)
3140                                 wakeup(pv);
3141                         break;
3142                 }
3143         }
3144 }
3145
3146 /*
3147  * Unlock and drop a pv.  If the pv is no longer associated with a pmap
3148  * and the hold count drops to zero we will free it.
3149  *
3150  * Caller should not hold any spin locks.  We are protected from hold races
3151  * by virtue of holds only occuring only with a pmap_spin or vm_page_spin
3152  * lock held.  A pv cannot be located otherwise.
3153  */
3154 static
3155 void
3156 pv_put(pv_entry_t pv)
3157 {
3158 #ifdef PMAP_DEBUG2
3159         if (pmap_enter_debug > 0) {
3160                 --pmap_enter_debug;
3161                 kprintf("pv_put pv=%p hold=%08x\n", pv, pv->pv_hold);
3162         }
3163 #endif
3164
3165         /*
3166          * Fast - shortcut most common condition
3167          */
3168         if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 1))
3169                 return;
3170
3171         /*
3172          * Slow
3173          */
3174         pv_unlock(pv);
3175         pv_drop(pv);
3176 }
3177
3178 /*
3179  * Remove the pmap association from a pv, require that pv_m already be removed,
3180  * then unlock and drop the pv.  Any pte operations must have already been
3181  * completed.  This call may result in a last-drop which will physically free
3182  * the pv.
3183  *
3184  * Removing the pmap association entails an additional drop.
3185  *
3186  * pv must be exclusively locked on call and will be disposed of on return.
3187  */
3188 static
3189 void
3190 pv_free(pv_entry_t pv)
3191 {
3192         pmap_t pmap;
3193
3194         KKASSERT(pv->pv_m == NULL);
3195         KKASSERT((pv->pv_hold & PV_HOLD_MASK) >= 2);
3196         if ((pmap = pv->pv_pmap) != NULL) {
3197                 spin_lock(&pmap->pm_spin);
3198                 pv_entry_rb_tree_RB_REMOVE(&pmap->pm_pvroot, pv);
3199                 ++pmap->pm_generation;
3200                 if (pmap->pm_pvhint == pv)
3201                         pmap->pm_pvhint = NULL;
3202                 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3203                 pv->pv_pmap = NULL;
3204                 pv->pv_pindex = 0;
3205                 spin_unlock(&pmap->pm_spin);
3206
3207                 /*
3208                  * Try to shortcut three atomic ops, otherwise fall through
3209                  * and do it normally.  Drop two refs and the lock all in
3210                  * one go.
3211                  */
3212                 if (atomic_cmpset_int(&pv->pv_hold, PV_HOLD_LOCKED | 2, 0)) {
3213 #ifdef PMAP_DEBUG2
3214                         if (pmap_enter_debug > 0) {
3215                                 --pmap_enter_debug;
3216                                 kprintf("pv_free: free pv %p\n", pv);
3217                         }
3218 #endif
3219                         zfree(pvzone, pv);
3220                         return;
3221                 }
3222                 pv_drop(pv);    /* ref for pv_pmap */
3223         }
3224         pv_put(pv);
3225 }
3226
3227 /*
3228  * This routine is very drastic, but can save the system
3229  * in a pinch.
3230  */
3231 void
3232 pmap_collect(void)
3233 {
3234         int i;
3235         vm_page_t m;
3236         static int warningdone=0;
3237
3238         if (pmap_pagedaemon_waken == 0)
3239                 return;
3240         pmap_pagedaemon_waken = 0;
3241         if (warningdone < 5) {
3242                 kprintf("pmap_collect: collecting pv entries -- "
3243                         "suggest increasing PMAP_SHPGPERPROC\n");
3244                 warningdone++;
3245         }
3246
3247         for (i = 0; i < vm_page_array_size; i++) {
3248                 m = &vm_page_array[i];
3249                 if (m->wire_count || m->hold_count)
3250                         continue;
3251                 if (vm_page_busy_try(m, TRUE) == 0) {
3252                         if (m->wire_count == 0 && m->hold_count == 0) {
3253                                 pmap_remove_all(m);
3254                         }
3255                         vm_page_wakeup(m);
3256                 }
3257         }
3258 }
3259
3260 /*
3261  * Scan the pmap for active page table entries and issue a callback.
3262  * The callback must dispose of pte_pv, whos PTE entry is at *ptep in
3263  * its parent page table.
3264  *
3265  * pte_pv will be NULL if the page or page table is unmanaged.
3266  * pt_pv will point to the page table page containing the pte for the page.
3267  *
3268  * NOTE! If we come across an unmanaged page TABLE (verses an unmanaged page),
3269  *       we pass a NULL pte_pv and we pass a pt_pv pointing to the passed
3270  *       process pmap's PD and page to the callback function.  This can be
3271  *       confusing because the pt_pv is really a pd_pv, and the target page
3272  *       table page is simply aliased by the pmap and not owned by it.
3273  *
3274  * It is assumed that the start and end are properly rounded to the page size.
3275  *
3276  * It is assumed that PD pages and above are managed and thus in the RB tree,
3277  * allowing us to use RB_SCAN from the PD pages down for ranged scans.
3278  */
3279 struct pmap_scan_info {
3280         struct pmap *pmap;
3281         vm_offset_t sva;
3282         vm_offset_t eva;
3283         vm_pindex_t sva_pd_pindex;
3284         vm_pindex_t eva_pd_pindex;
3285         void (*func)(pmap_t, struct pmap_scan_info *,
3286                      pv_entry_t, pv_entry_t, int, vm_offset_t,
3287                      pt_entry_t *, void *);
3288         void *arg;
3289         pmap_inval_bulk_t bulk_core;
3290         pmap_inval_bulk_t *bulk;
3291         int count;
3292 };
3293
3294 static int pmap_scan_cmp(pv_entry_t pv, void *data);
3295 static int pmap_scan_callback(pv_entry_t pv, void *data);
3296
3297 static void
3298 pmap_scan(struct pmap_scan_info *info, int smp_inval)
3299 {
3300         struct pmap *pmap = info->pmap;
3301         pv_entry_t pd_pv;       /* A page directory PV */
3302         pv_entry_t pt_pv;       /* A page table PV */
3303         pv_entry_t pte_pv;      /* A page table entry PV */
3304         pt_entry_t *ptep;
3305         pt_entry_t oldpte;
3306         struct pv_entry dummy_pv;
3307         int generation;
3308
3309         if (pmap == NULL)
3310                 return;
3311         if (smp_inval) {
3312                 info->bulk = &info->bulk_core;
3313                 pmap_inval_bulk_init(&info->bulk_core, pmap);
3314         } else {
3315                 info->bulk = NULL;
3316         }
3317
3318         /*
3319          * Hold the token for stability; if the pmap is empty we have nothing
3320          * to do.
3321          */
3322         lwkt_gettoken(&pmap->pm_token);
3323 #if 0
3324         if (pmap->pm_stats.resident_count == 0) {
3325                 lwkt_reltoken(&pmap->pm_token);
3326                 return;
3327         }
3328 #endif
3329
3330         info->count = 0;
3331
3332 again:
3333         /*
3334          * Special handling for scanning one page, which is a very common
3335          * operation (it is?).
3336          *
3337          * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4
3338          */
3339         if (info->sva + PAGE_SIZE == info->eva) {
3340                 generation = pmap->pm_generation;
3341                 if (info->sva >= VM_MAX_USER_ADDRESS) {
3342                         /*
3343                          * Kernel mappings do not track wire counts on
3344                          * page table pages and only maintain pd_pv and
3345                          * pte_pv levels so pmap_scan() works.
3346                          */
3347                         pt_pv = NULL;
3348                         pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva));
3349                         ptep = vtopte(info->sva);
3350                 } else {
3351                         /*
3352                          * User pages which are unmanaged will not have a
3353                          * pte_pv.  User page table pages which are unmanaged
3354                          * (shared from elsewhere) will also not have a pt_pv.
3355                          * The func() callback will pass both pte_pv and pt_pv
3356                          * as NULL in that case.
3357                          */
3358                         pte_pv = pv_get(pmap, pmap_pte_pindex(info->sva));
3359                         pt_pv = pv_get(pmap, pmap_pt_pindex(info->sva));
3360                         if (pt_pv == NULL) {
3361                                 KKASSERT(pte_pv == NULL);
3362                                 pd_pv = pv_get(pmap, pmap_pd_pindex(info->sva));
3363                                 if (pd_pv) {
3364                                         ptep = pv_pte_lookup(pd_pv,
3365                                                     pmap_pt_index(info->sva));
3366                                         if (*ptep) {
3367                                                 info->func(pmap, info,
3368                                                      NULL, pd_pv, 1,
3369                                                      info->sva, ptep,
3370                                                      info->arg);
3371                                         }
3372                                         pv_put(pd_pv);
3373                                 }
3374                                 goto fast_skip;
3375                         }
3376                         ptep = pv_pte_lookup(pt_pv, pmap_pte_index(info->sva));
3377                 }
3378
3379                 /*
3380                  * NOTE: *ptep can't be ripped out from under us if we hold
3381                  *       pte_pv locked, but bits can change.  However, there is
3382                  *       a race where another thread may be inserting pte_pv
3383                  *       and setting *ptep just after our pte_pv lookup fails.
3384                  *
3385                  *       In this situation we can end up with a NULL pte_pv
3386                  *       but find that we have a managed *ptep.  We explicitly
3387                  *       check for this race.
3388                  */
3389                 oldpte = *ptep;
3390                 cpu_ccfence();
3391                 if (oldpte == 0) {
3392                         /*
3393                          * Unlike the pv_find() case below we actually
3394                          * acquired a locked pv in this case so any
3395                          * race should have been resolved.  It is expected
3396                          * to not exist.
3397                          */
3398                         KKASSERT(pte_pv == NULL);
3399                 } else if (pte_pv) {
3400                         KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
3401                                            pmap->pmap_bits[PG_V_IDX])) ==
3402                                 (pmap->pmap_bits[PG_MANAGED_IDX] |
3403                                  pmap->pmap_bits[PG_V_IDX]),
3404                             ("badA *ptep %016lx/%016lx sva %016lx pte_pv %p"
3405                              "generation %d/%d",
3406                             *ptep, oldpte, info->sva, pte_pv,
3407                             generation, pmap->pm_generation));
3408                         info->func(pmap, info, pte_pv, pt_pv, 0,
3409                                    info->sva, ptep, info->arg);
3410                 } else {
3411                         /*
3412                          * Check for insertion race
3413                          */
3414                         if ((oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3415                             pt_pv) {
3416                                 pte_pv = pv_find(pmap,
3417                                                  pmap_pte_pindex(info->sva));
3418                                 if (pte_pv) {
3419                                         pv_drop(pte_pv);
3420                                         pv_put(pt_pv);
3421                                         kprintf("pmap_scan: RACE1 "
3422                                                 "%016jx, %016lx\n",
3423                                                 info->sva, oldpte);
3424                                         goto again;
3425                                 }
3426                         }
3427
3428                         /*
3429                          * Didn't race
3430                          */
3431                         KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] |
3432                                            pmap->pmap_bits[PG_V_IDX])) ==
3433                             pmap->pmap_bits[PG_V_IDX],
3434                             ("badB *ptep %016lx/%016lx sva %016lx pte_pv NULL"
3435                              "generation %d/%d",
3436                             *ptep, oldpte, info->sva,
3437                             generation, pmap->pm_generation));
3438                         info->func(pmap, info, NULL, pt_pv, 0,
3439                             info->sva, ptep, info->arg);
3440                 }
3441                 if (pt_pv)
3442                         pv_put(pt_pv);
3443 fast_skip:
3444                 pmap_inval_bulk_flush(info->bulk);
3445                 lwkt_reltoken(&pmap->pm_token);
3446                 return;
3447         }
3448
3449         /*
3450          * Nominal scan case, RB_SCAN() for PD pages and iterate from
3451          * there.
3452          */
3453         info->sva_pd_pindex = pmap_pd_pindex(info->sva);
3454         info->eva_pd_pindex = pmap_pd_pindex(info->eva + NBPDP - 1);
3455
3456         if (info->sva >= VM_MAX_USER_ADDRESS) {
3457                 /*
3458                  * The kernel does not currently maintain any pv_entry's for
3459                  * higher-level page tables.
3460                  */
3461                 bzero(&dummy_pv, sizeof(dummy_pv));
3462                 dummy_pv.pv_pindex = info->sva_pd_pindex;
3463                 spin_lock(&pmap->pm_spin);
3464                 while (dummy_pv.pv_pindex < info->eva_pd_pindex) {
3465                         pmap_scan_callback(&dummy_pv, info);
3466                         ++dummy_pv.pv_pindex;
3467                 }
3468                 spin_unlock(&pmap->pm_spin);
3469         } else {
3470                 /*
3471                  * User page tables maintain local PML4, PDP, and PD
3472                  * pv_entry's at the very least.  PT pv's might be
3473                  * unmanaged and thus not exist.  PTE pv's might be
3474                  * unmanaged and thus not exist.
3475                  */
3476                 spin_lock(&pmap->pm_spin);
3477                 pv_entry_rb_tree_RB_SCAN(&pmap->pm_pvroot,
3478                         pmap_scan_cmp, pmap_scan_callback, info);
3479                 spin_unlock(&pmap->pm_spin);
3480         }
3481         pmap_inval_bulk_flush(info->bulk);
3482         lwkt_reltoken(&pmap->pm_token);
3483 }
3484
3485 /*
3486  * WARNING! pmap->pm_spin held
3487  */
3488 static int
3489 pmap_scan_cmp(pv_entry_t pv, void *data)
3490 {
3491         struct pmap_scan_info *info = data;
3492         if (pv->pv_pindex < info->sva_pd_pindex)
3493                 return(-1);
3494         if (pv->pv_pindex >= info->eva_pd_pindex)
3495                 return(1);
3496         return(0);
3497 }
3498
3499 /*
3500  * WARNING! pmap->pm_spin held
3501  */
3502 static int
3503 pmap_scan_callback(pv_entry_t pv, void *data)
3504 {
3505         struct pmap_scan_info *info = data;
3506         struct pmap *pmap = info->pmap;
3507         pv_entry_t pd_pv;       /* A page directory PV */
3508         pv_entry_t pt_pv;       /* A page table PV */
3509         pv_entry_t pte_pv;      /* A page table entry PV */
3510         pt_entry_t *ptep;
3511         pt_entry_t oldpte;
3512         vm_offset_t sva;
3513         vm_offset_t eva;
3514         vm_offset_t va_next;
3515         vm_pindex_t pd_pindex;
3516         int error;
3517         int generation;
3518
3519         /*
3520          * Pull the PD pindex from the pv before releasing the spinlock.
3521          *
3522          * WARNING: pv is faked for kernel pmap scans.
3523          */
3524         pd_pindex = pv->pv_pindex;
3525         spin_unlock(&pmap->pm_spin);
3526         pv = NULL;      /* invalid after spinlock unlocked */
3527
3528         /*
3529          * Calculate the page range within the PD.  SIMPLE pmaps are
3530          * direct-mapped for the entire 2^64 address space.  Normal pmaps
3531          * reflect the user and kernel address space which requires
3532          * cannonicalization w/regards to converting pd_pindex's back
3533          * into addresses.
3534          */
3535         sva = (pd_pindex - NUPTE_TOTAL - NUPT_TOTAL) << PDPSHIFT;
3536         if ((pmap->pm_flags & PMAP_FLAG_SIMPLE) == 0 &&
3537             (sva & PML4_SIGNMASK)) {
3538                 sva |= PML4_SIGNMASK;
3539         }
3540         eva = sva + NBPDP;      /* can overflow */
3541         if (sva < info->sva)
3542                 sva = info->sva;
3543         if (eva < info->sva || eva > info->eva)
3544                 eva = info->eva;
3545
3546         /*
3547          * NOTE: kernel mappings do not track page table pages, only
3548          *       terminal pages.
3549          *
3550          * NOTE: Locks must be ordered bottom-up. pte,pt,pd,pdp,pml4.
3551          *       However, for the scan to be efficient we try to
3552          *       cache items top-down.
3553          */
3554         pd_pv = NULL;
3555         pt_pv = NULL;
3556
3557         for (; sva < eva; sva = va_next) {
3558                 if (sva >= VM_MAX_USER_ADDRESS) {
3559                         if (pt_pv) {
3560                                 pv_put(pt_pv);
3561                                 pt_pv = NULL;
3562                         }
3563                         goto kernel_skip;
3564                 }
3565
3566                 /*
3567                  * PD cache (degenerate case if we skip).  It is possible
3568                  * for the PD to not exist due to races.  This is ok.
3569                  */
3570                 if (pd_pv == NULL) {
3571                         pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
3572                 } else if (pd_pv->pv_pindex != pmap_pd_pindex(sva)) {
3573                         pv_put(pd_pv);
3574                         pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
3575                 }
3576                 if (pd_pv == NULL) {
3577                         va_next = (sva + NBPDP) & ~PDPMASK;
3578                         if (va_next < sva)
3579                                 va_next = eva;
3580                         continue;
3581                 }
3582
3583                 /*
3584                  * PT cache
3585                  */
3586                 if (pt_pv == NULL) {
3587                         if (pd_pv) {
3588                                 pv_put(pd_pv);
3589                                 pd_pv = NULL;
3590                         }
3591                         pt_pv = pv_get(pmap, pmap_pt_pindex(sva));
3592                 } else if (pt_pv->pv_pindex != pmap_pt_pindex(sva)) {
3593                         if (pd_pv) {
3594                                 pv_put(pd_pv);
3595                                 pd_pv = NULL;
3596                         }
3597                         pv_put(pt_pv);
3598                         pt_pv = pv_get(pmap, pmap_pt_pindex(sva));
3599                 }
3600
3601                 /*
3602                  * If pt_pv is NULL we either have an shared page table
3603                  * page and must issue a callback specific to that case,
3604                  * or there is no page table page.
3605                  *
3606                  * Either way we can skip the page table page.
3607                  */
3608                 if (pt_pv == NULL) {
3609                         /*
3610                          * Possible unmanaged (shared from another pmap)
3611                          * page table page.
3612                          */
3613                         if (pd_pv == NULL)
3614                                 pd_pv = pv_get(pmap, pmap_pd_pindex(sva));
3615                         KKASSERT(pd_pv != NULL);
3616                         ptep = pv_pte_lookup(pd_pv, pmap_pt_index(sva));
3617                         if (*ptep & pmap->pmap_bits[PG_V_IDX]) {
3618                                 info->func(pmap, info, NULL, pd_pv, 1,
3619                                            sva, ptep, info->arg);
3620                         }
3621
3622                         /*
3623                          * Done, move to next page table page.
3624                          */
3625                         va_next = (sva + NBPDR) & ~PDRMASK;
3626                         if (va_next < sva)
3627                                 va_next = eva;
3628                         continue;
3629                 }
3630
3631                 /*
3632                  * From this point in the loop testing pt_pv for non-NULL
3633                  * means we are in UVM, else if it is NULL we are in KVM.
3634                  *
3635                  * Limit our scan to either the end of the va represented
3636                  * by the current page table page, or to the end of the
3637                  * range being removed.
3638                  */
3639 kernel_skip:
3640                 va_next = (sva + NBPDR) & ~PDRMASK;
3641                 if (va_next < sva)
3642                         va_next = eva;
3643                 if (va_next > eva)
3644                         va_next = eva;
3645
3646                 /*
3647                  * Scan the page table for pages.  Some pages may not be
3648                  * managed (might not have a pv_entry).
3649                  *
3650                  * There is no page table management for kernel pages so
3651                  * pt_pv will be NULL in that case, but otherwise pt_pv
3652                  * is non-NULL, locked, and referenced.
3653                  */
3654
3655                 /*
3656                  * At this point a non-NULL pt_pv means a UVA, and a NULL
3657                  * pt_pv means a KVA.
3658                  */
3659                 if (pt_pv)
3660                         ptep = pv_pte_lookup(pt_pv, pmap_pte_index(sva));
3661                 else
3662                         ptep = vtopte(sva);
3663
3664                 while (sva < va_next) {
3665                         /*
3666                          * Yield every 64 pages.
3667                          */
3668                         if ((++info->count & 63) == 0)
3669                                 lwkt_user_yield();
3670
3671                         /*
3672                          * Acquire the related pte_pv, if any.  If *ptep == 0
3673                          * the related pte_pv should not exist, but if *ptep
3674                          * is not zero the pte_pv may or may not exist (e.g.
3675                          * will not exist for an unmanaged page).
3676                          *
3677                          * However a multitude of races are possible here.
3678                          *
3679                          * In addition, the (pt_pv, pte_pv) lock order is
3680                          * backwards, so we have to be careful in aquiring
3681                          * a properly locked pte_pv.
3682                          */
3683                         generation = pmap->pm_generation;
3684                         if (pt_pv) {
3685                                 pte_pv = pv_get_try(pmap, pmap_pte_pindex(sva),
3686                                                     &error);
3687                                 if (error) {
3688                                         if (pd_pv) {
3689                                                 pv_put(pd_pv);
3690                                                 pd_pv = NULL;
3691                                         }
3692                                         pv_put(pt_pv);   /* must be non-NULL */
3693                                         pt_pv = NULL;
3694                                         pv_lock(pte_pv); /* safe to block now */
3695                                         pv_put(pte_pv);
3696                                         pte_pv = NULL;
3697                                         pt_pv = pv_get(pmap,
3698                                                        pmap_pt_pindex(sva));
3699                                         /*
3700                                          * pt_pv reloaded, need new ptep
3701                                          */
3702                                         KKASSERT(pt_pv != NULL);
3703                                         ptep = pv_pte_lookup(pt_pv,
3704                                                         pmap_pte_index(sva));
3705                                         continue;
3706                                 }
3707                         } else {
3708                                 pte_pv = pv_get(pmap, pmap_pte_pindex(sva));
3709                         }
3710
3711                         /*
3712                          * Ok, if *ptep == 0 we had better NOT have a pte_pv.
3713                          */
3714                         oldpte = *ptep;
3715                         if (oldpte == 0) {
3716                                 if (pte_pv) {
3717                                         kprintf("Unexpected non-NULL pte_pv "
3718                                                 "%p pt_pv %p "
3719                                                 "*ptep = %016lx/%016lx\n",
3720                                                 pte_pv, pt_pv, *ptep, oldpte);
3721                                         panic("Unexpected non-NULL pte_pv");
3722                                 }
3723                                 sva += PAGE_SIZE;
3724                                 ++ptep;
3725                                 continue;
3726                         }
3727
3728                         /*
3729                          * Ready for the callback.  The locked pte_pv (if any)
3730                          * is consumed by the callback.  pte_pv will exist if
3731                          *  the page is managed, and will not exist if it
3732                          * isn't.
3733                          */
3734                         if (pte_pv) {
3735                                 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) ==
3736                                     (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX]),
3737                                     ("badC *ptep %016lx/%016lx sva %016lx "
3738                                     "pte_pv %p pm_generation %d/%d",
3739                                     *ptep, oldpte, sva, pte_pv,
3740                                     generation, pmap->pm_generation));
3741                                 info->func(pmap, info, pte_pv, pt_pv, 0,
3742                                     sva, ptep, info->arg);
3743                         } else {
3744                                 /*
3745                                  * Check for insertion race.  Since there is no
3746                                  * pte_pv to guard us it is possible for us
3747                                  * to race another thread doing an insertion.
3748                                  * Our lookup misses the pte_pv but our *ptep
3749                                  * check sees the inserted pte.
3750                                  *
3751                                  * XXX panic case seems to occur within a
3752                                  * vm_fork() of /bin/sh, which frankly
3753                                  * shouldn't happen since no other threads
3754                                  * should be inserting to our pmap in that
3755                                  * situation.  Removing, possibly.  Inserting,
3756                                  * shouldn't happen.
3757                                  */
3758                                 if ((oldpte & pmap->pmap_bits[PG_MANAGED_IDX]) &&
3759                                     pt_pv) {
3760                                         pte_pv = pv_find(pmap,
3761                                                          pmap_pte_pindex(sva));
3762                                         if (pte_pv) {
3763                                                 pv_drop(pte_pv);
3764                                                 kprintf("pmap_scan: RACE2 "
3765                                                         "%016jx, %016lx\n",
3766                                                         sva, oldpte);
3767                                                 continue;
3768                                         }
3769                                 }
3770
3771                                 /*
3772                                  * Didn't race
3773                                  */
3774                                 KASSERT((oldpte & (pmap->pmap_bits[PG_MANAGED_IDX] | pmap->pmap_bits[PG_V_IDX])) ==
3775                                     pmap->pmap_bits[PG_V_IDX],
3776                                     ("badD *ptep %016lx/%016lx sva %016lx "
3777                                     "pte_pv NULL pm_generation %d/%d",
3778                                      *ptep, oldpte, sva,
3779                                      generation, pmap->pm_generation));
3780                                 info->func(pmap, info, NULL, pt_pv, 0,
3781                                     sva, ptep, info->arg);
3782                         }
3783                         pte_pv = NULL;
3784                         sva += PAGE_SIZE;
3785                         ++ptep;
3786                 }
3787         }
3788         if (pd_pv) {
3789                 pv_put(pd_pv);
3790                 pd_pv = NULL;
3791         }
3792         if (pt_pv) {
3793                 pv_put(pt_pv);
3794                 pt_pv = NULL;
3795         }
3796         if ((++info->count & 7) == 0)
3797                 lwkt_user_yield();
3798
3799         /*
3800          * Relock before returning.
3801          */
3802         spin_lock(&pmap->pm_spin);
3803         return (0);
3804 }
3805
3806 void
3807 pmap_remove(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
3808 {
3809         struct pmap_scan_info info;
3810
3811         info.pmap = pmap;
3812         info.sva = sva;
3813         info.eva = eva;
3814         info.func = pmap_remove_callback;
3815         info.arg = NULL;
3816         pmap_scan(&info, 1);
3817 }
3818
3819 static void
3820 pmap_remove_noinval(struct pmap *pmap, vm_offset_t sva, vm_offset_t eva)
3821 {
3822         struct pmap_scan_info info;
3823
3824         info.pmap = pmap;
3825         info.sva = sva;
3826         info.eva = eva;
3827         info.func = pmap_remove_callback;
3828         info.arg = NULL;
3829         pmap_scan(&info, 0);
3830 }
3831
3832 static void
3833 pmap_remove_callback(pmap_t pmap, struct pmap_scan_info *info,
3834                      pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
3835                      vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
3836 {
3837         pt_entry_t pte;
3838
3839         if (pte_pv) {
3840                 /*
3841                  * This will also drop pt_pv's wire_count. Note that
3842                  * terminal pages are not wired based on mmu presence.
3843                  */
3844                 pmap_remove_pv_pte(pte_pv, pt_pv, info->bulk);
3845                 pmap_remove_pv_page(pte_pv);
3846                 pv_free(pte_pv);
3847         } else if (sharept == 0) {
3848                 /*
3849                  * Unmanaged page table (pt, pd, or pdp. Not pte).
3850                  *
3851                  * pt_pv's wire_count is still bumped by unmanaged pages
3852                  * so we must decrement it manually.
3853                  *
3854                  * We have to unwire the target page table page.
3855                  *
3856                  * It is unclear how we can invalidate a segment so we
3857                  * invalidate -1 which invlidates the tlb.
3858                  */
3859                 pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
3860                 if (pte & pmap->pmap_bits[PG_W_IDX])
3861                         atomic_add_long(&pmap->pm_stats.wired_count, -1);
3862                 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3863                 if (vm_page_unwire_quick(pt_pv->pv_m))
3864                         panic("pmap_remove: insufficient wirecount");
3865         } else {
3866                 /*
3867                  * Unmanaged page table (pt, pd, or pdp. Not pte) for
3868                  * a shared page table.
3869                  *
3870                  * pt_pv is actually the pd_pv for our pmap (not the shared
3871                  * object pmap).
3872                  *
3873                  * We have to unwire the target page table page and we
3874                  * have to unwire our page directory page.
3875                  *
3876                  * It is unclear how we can invalidate a segment so we
3877                  * invalidate -1 which invlidates the tlb.
3878                  */
3879                 pte = pmap_inval_bulk(info->bulk, (vm_offset_t)-1, ptep, 0);
3880                 atomic_add_long(&pmap->pm_stats.resident_count, -1);
3881                 KKASSERT((pte & pmap->pmap_bits[PG_DEVICE_IDX]) == 0);
3882                 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
3883                         panic("pmap_remove: shared pgtable1 bad wirecount");
3884                 if (vm_page_unwire_quick(pt_pv->pv_m))
3885                         panic("pmap_remove: shared pgtable2 bad wirecount");
3886         }
3887 }
3888
3889 /*
3890  * Removes this physical page from all physical maps in which it resides.
3891  * Reflects back modify bits to the pager.
3892  *
3893  * This routine may not be called from an interrupt.
3894  */
3895 static
3896 void
3897 pmap_remove_all(vm_page_t m)
3898 {
3899         pv_entry_t pv;
3900         pmap_inval_bulk_t bulk;
3901
3902         if (!pmap_initialized /* || (m->flags & PG_FICTITIOUS)*/)
3903                 return;
3904
3905         vm_page_spin_lock(m);
3906         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3907                 KKASSERT(pv->pv_m == m);
3908                 if (pv_hold_try(pv)) {
3909                         vm_page_spin_unlock(m);
3910                 } else {
3911                         vm_page_spin_unlock(m);
3912                         pv_lock(pv);
3913                 }
3914                 if (pv->pv_m != m) {
3915                         pv_put(pv);
3916                         vm_page_spin_lock(m);
3917                         continue;
3918                 }
3919
3920                 /*
3921                  * Holding no spinlocks, pv is locked.
3922                  */
3923                 pmap_inval_bulk_init(&bulk, pv->pv_pmap);
3924                 pmap_remove_pv_pte(pv, NULL, &bulk);
3925                 pmap_inval_bulk_flush(&bulk);
3926                 pmap_remove_pv_page(pv);
3927                 pv_free(pv);
3928                 vm_page_spin_lock(m);
3929         }
3930         KKASSERT((m->flags & (PG_MAPPED|PG_WRITEABLE)) == 0);
3931         vm_page_spin_unlock(m);
3932 }
3933
3934 /*
3935  * Set the physical protection on the specified range of this map
3936  * as requested.  This function is typically only used for debug watchpoints
3937  * and COW pages.
3938  *
3939  * This function may not be called from an interrupt if the map is
3940  * not the kernel_pmap.
3941  *
3942  * NOTE!  For shared page table pages we just unmap the page.
3943  */
3944 void
3945 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3946 {
3947         struct pmap_scan_info info;
3948         /* JG review for NX */
3949
3950         if (pmap == NULL)
3951                 return;
3952         if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
3953                 pmap_remove(pmap, sva, eva);
3954                 return;
3955         }
3956         if (prot & VM_PROT_WRITE)
3957                 return;
3958         info.pmap = pmap;
3959         info.sva = sva;
3960         info.eva = eva;
3961         info.func = pmap_protect_callback;
3962         info.arg = &prot;
3963         pmap_scan(&info, 1);
3964 }
3965
3966 static
3967 void
3968 pmap_protect_callback(pmap_t pmap, struct pmap_scan_info *info,
3969                       pv_entry_t pte_pv, pv_entry_t pt_pv, int sharept,
3970                       vm_offset_t va, pt_entry_t *ptep, void *arg __unused)
3971 {
3972         pt_entry_t pbits;
3973         pt_entry_t cbits;
3974         pt_entry_t pte;
3975         vm_page_t m;
3976
3977 again:
3978         pbits = *ptep;
3979         cbits = pbits;
3980         if (pte_pv) {
3981                 m = NULL;
3982                 if (pbits & pmap->pmap_bits[PG_A_IDX]) {
3983                         if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
3984                                 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
3985                                 KKASSERT(m == pte_pv->pv_m);
3986                                 vm_page_flag_set(m, PG_REFERENCED);
3987                         }
3988                         cbits &= ~pmap->pmap_bits[PG_A_IDX];
3989                 }
3990                 if (pbits & pmap->pmap_bits[PG_M_IDX]) {
3991                         if (pmap_track_modified(pte_pv->pv_pindex)) {
3992                                 if ((pbits & pmap->pmap_bits[PG_DEVICE_IDX]) == 0) {
3993                                         if (m == NULL) {
3994                                                 m = PHYS_TO_VM_PAGE(pbits &
3995                                                                     PG_FRAME);
3996                                         }
3997                                         vm_page_dirty(m);
3998                                 }
3999                                 cbits &= ~pmap->pmap_bits[PG_M_IDX];
4000                         }
4001                 }
4002         } else if (sharept) {
4003                 /*
4004                  * Unmanaged page table, pt_pv is actually the pd_pv
4005                  * for our pmap (not the object's shared pmap).
4006                  *
4007                  * When asked to protect something in a shared page table
4008                  * page we just unmap the page table page.  We have to
4009                  * invalidate the tlb in this situation.
4010                  *
4011                  * XXX Warning, shared page tables will not be used for
4012                  * OBJT_DEVICE or OBJT_MGTDEVICE (PG_FICTITIOUS) mappings
4013                  * so PHYS_TO_VM_PAGE() should be safe here.
4014                  */
4015                 pte = pmap_inval_smp(pmap, (vm_offset_t)-1, 1, ptep, 0);
4016                 if (vm_page_unwire_quick(PHYS_TO_VM_PAGE(pte & PG_FRAME)))
4017                         panic("pmap_protect: pgtable1 pg bad wirecount");
4018                 if (vm_page_unwire_quick(pt_pv->pv_m))
4019                         panic("pmap_protect: pgtable2 pg bad wirecount");
4020                 ptep = NULL;
4021         }
4022         /* else unmanaged page, adjust bits, no wire changes */
4023
4024         if (ptep) {
4025                 cbits &= ~pmap->pmap_bits[PG_RW_IDX];
4026 #ifdef PMAP_DEBUG2
4027                 if (pmap_enter_debug > 0) {
4028                         --pmap_enter_debug;
4029                         kprintf("pmap_protect va=%lx ptep=%p pte_pv=%p "
4030                                 "pt_pv=%p cbits=%08lx\n",
4031                                 va, ptep, pte_pv,
4032                                 pt_pv, cbits
4033                         );
4034                 }
4035 #endif
4036                 if (pbits != cbits) {
4037                         if (!pmap_inval_smp_cmpset(pmap, (vm_offset_t)-1,
4038                                                    ptep, pbits, cbits)) {
4039                                 goto again;
4040                         }
4041                 }
4042         }
4043         if (pte_pv)
4044                 pv_put(pte_pv);
4045 }
4046
4047 /*
4048  * Insert the vm_page (m) at the virtual address (va), replacing any prior
4049  * mapping at that address.  Set protection and wiring as requested.
4050  *
4051  * If entry is non-NULL we check to see if the SEG_SIZE optimization is
4052  * possible.  If it is we enter the page into the appropriate shared pmap
4053  * hanging off the related VM object instead of the passed pmap, then we
4054  * share the page table page from the VM object's pmap into the current pmap.
4055  *
4056  * NOTE: This routine MUST insert the page into the pmap now, it cannot
4057  *       lazy-evaluate.
4058  */
4059 void
4060 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4061            boolean_t wired, vm_map_entry_t entry)
4062 {
4063         pv_entry_t pt_pv;       /* page table */
4064         pv_entry_t pte_pv;      /* page table entry */
4065         pt_entry_t *ptep;
4066         vm_paddr_t opa;
4067         pt_entry_t origpte, newpte;
4068         vm_paddr_t pa;
4069
4070         if (pmap == NULL)
4071                 return;
4072         va = trunc_page(va);
4073 #ifdef PMAP_DIAGNOSTIC
4074         if (va >= KvaEnd)
4075                 panic("pmap_enter: toobig");
4076         if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
4077                 panic("pmap_enter: invalid to pmap_enter page table "
4078                       "pages (va: 0x%lx)", va);
4079 #endif
4080         if (va < UPT_MAX_ADDRESS && pmap == &kernel_pmap) {
4081                 kprintf("Warning: pmap_enter called on UVA with "
4082                         "kernel_pmap\n");
4083 #ifdef DDB
4084                 db_print_backtrace();
4085 #endif
4086         }
4087         if (va >= UPT_MAX_ADDRESS && pmap != &kernel_pmap) {
4088                 kprintf("Warning: pmap_enter called on KVA without"
4089                         "kernel_pmap\n");
4090 #ifdef DDB
4091                 db_print_backtrace();
4092 #endif
4093         }
4094
4095         /*
4096          * Get locked PV entries for our new page table entry (pte_pv)
4097          * and for its parent page table (pt_pv).  We need the parent
4098          * so we can resolve the location of the ptep.
4099          *
4100          * Only hardware MMU actions can modify the ptep out from
4101          * under us.
4102          *
4103          * if (m) is fictitious or unmanaged we do not create a managing
4104          * pte_pv for it.  Any pre-existing page's management state must
4105          * match (avoiding code complexity).
4106          *
4107          * If the pmap is still being initialized we assume existing
4108          * page tables.
4109          *
4110          * Kernel mapppings do not track page table pages (i.e. pt_pv).
4111          */
4112         if (pmap_initialized == FALSE) {
4113                 pte_pv = NULL;
4114                 pt_pv = NULL;
4115                 ptep = vtopte(va);
4116                 origpte = *ptep;
4117         } else if (m->flags & (/*PG_FICTITIOUS |*/ PG_UNMANAGED)) { /* XXX */
4118                 pte_pv = NULL;
4119                 if (va >= VM_MAX_USER_ADDRESS) {
4120                         pt_pv = NULL;
4121                         ptep = vtopte(va);
4122                 } else {
4123                         pt_pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va),
4124                                                   NULL, entry, va);
4125                         ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
4126                 }
4127                 origpte = *ptep;
4128                 cpu_ccfence();
4129                 KASSERT(origpte == 0 ||
4130                          (origpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0,
4131                          ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
4132         } else {
4133                 if (va >= VM_MAX_USER_ADDRESS) {
4134                         /*
4135                          * Kernel map, pv_entry-tracked.
4136                          */
4137                         pt_pv = NULL;
4138                         pte_pv = pmap_allocpte(pmap, pmap_pte_pindex(va), NULL);
4139                         ptep = vtopte(va);
4140                 } else {
4141                         /*
4142                          * User map
4143                          */
4144                         pte_pv = pmap_allocpte_seg(pmap, pmap_pte_pindex(va),
4145                                                    &pt_pv, entry, va);
4146                         ptep = pv_pte_lookup(pt_pv, pmap_pte_index(va));
4147                 }
4148                 origpte = *ptep;
4149                 cpu_ccfence();
4150                 KASSERT(origpte == 0 ||
4151                          (origpte & pmap->pmap_bits[PG_MANAGED_IDX]),
4152                          ("Invalid PTE 0x%016jx @ 0x%016jx\n", origpte, va));
4153         }
4154
4155         pa = VM_PAGE_TO_PHYS(m);
4156         opa = origpte & PG_FRAME;
4157
4158         newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) |
4159                  pmap->pmap_bits[PG_V_IDX] | pmap->pmap_bits[PG_A_IDX]);
4160         if (wired)
4161                 newpte |= pmap->pmap_bits[PG_W_IDX];
4162         if (va < VM_MAX_USER_ADDRESS)
4163                 newpte |= pmap->pmap_bits[PG_U_IDX];
4164         if (pte_pv)
4165                 newpte |= pmap->pmap_bits[PG_MANAGED_IDX];
4166 //      if (pmap == &kernel_pmap)
4167 //              newpte |= pgeflag;
4168         newpte |= pmap->pmap_cache_bits[m->pat_mode];
4169         if (m->flags & PG_FICTITIOUS)
4170                 newpte |= pmap->pmap_bits[PG_DEVICE_IDX];
4171
4172         /*
4173          * It is possible for multiple faults to occur in threaded
4174          * environments, the existing pte might be correct.
4175          */
4176         if (((origpte ^ newpte) & ~(pt_entry_t)(pmap->pmap_bits[PG_M_IDX] |
4177             pmap->pmap_bits[PG_A_IDX])) == 0)
4178                 goto done;
4179
4180         /*
4181          * Ok, either the address changed or the protection or wiring
4182          * changed.
4183          *
4184          * Clear the current entry, interlocking the removal.  For managed
4185          * pte's this will also flush the modified state to the vm_page.
4186          * Atomic ops are mandatory in order to ensure that PG_M events are
4187          * not lost during any transition.
4188          *
4189          * WARNING: The caller has busied the new page but not the original
4190          *          vm_page which we are trying to replace.  Because we hold
4191          *          the pte_pv lock, but have not busied the page, PG bits
4192          *          can be cleared out from under us.
4193          */
4194         if (opa) {
4195                 if (pte_pv) {
4196                         /*
4197                          * pmap_remove_pv_pte() unwires pt_pv and assumes
4198                          * we will free pte_pv, but since we are reusing
4199                          * pte_pv we want to retain the wire count.
4200                          *
4201                          * pt_pv won't exist for a kernel page (managed or
4202                          * otherwise).
4203                          */
4204                         if (pt_pv)
4205                                 vm_page_wire_quick(pt_pv->pv_m);
4206                         if (prot & VM_PROT_NOSYNC) {
4207                                 pmap_remove_pv_pte(pte_pv, pt_pv, NULL);
4208                         } else {
4209                                 pmap_inval_bulk_t bulk;
4210
4211                                 pmap_inval_bulk_init(&bulk, pmap);
4212                                 pmap_remove_pv_pte(pte_pv, pt_pv, &bulk);
4213                                 pmap_inval_bulk_flush(&bulk);
4214                         }
4215                         if (pte_pv->pv_m)
4216                                 pmap_remove_pv_page(pte_pv);
4217                 } else if (prot & VM_PROT_NOSYNC) {
4218                         /*
4219                          * Unmanaged page, NOSYNC (no mmu sync) requested.
4220                          *
4221                          * Leave wire count on PT page intact.
4222                          */
4223                         (void)pte_load_clear(ptep);
4224                         cpu_invlpg((void *)va);
4225                         atomic_add_long(&pmap->pm_stats.resident_count, -1);
4226                 } else {
4227                         /*
4228                          * Unmanaged page, normal enter.
4229                          *
4230                          * Leave wire count on PT page intact.
4231                          */
4232                         pmap_inval_smp(pmap, va, 1, ptep, 0);
4233                         atomic_add_long(&pmap->pm_stats.resident_count, -1);
4234                 }
4235                 KKASSERT(*ptep == 0);
4236         }
4237
4238 #ifdef PMAP_DEBUG2
4239         if (pmap_enter_debug > 0) {
4240                 --pmap_enter_debug;
4241                 kprintf("pmap_enter: va=%lx m=%p origpte=%lx newpte=%lx ptep=%p"
4242                         " pte_pv=%p pt_pv=%p opa=%lx prot=%02x\n",
4243                         va, m,
4244                         origpte, newpte, ptep,
4245                         pte_pv, pt_pv, opa, prot);
4246         }
4247 #endif
4248
4249         if (pte_pv) {
4250                 /*
4251                  * Enter on the PV list if part of our managed memory.
4252                  * Wiring of the PT page is already handled.
4253                  */
4254                 KKASSERT(pte_pv->pv_m == NULL);
4255                 vm_page_spin_lock(m);
4256                 pte_pv->pv_m = m;
4257                 pmap_page_stats_adding(m);
4258                 TAILQ_INSERT_TAIL(&m->md.pv_list, pte_pv, pv_list);
4259                 vm_page_flag_set(m, PG_MAPPED);
4260                 vm_page_spin_unlock(m);
4261         } else if (pt_pv && opa == 0) {
4262                 /*
4263                  * We have to adjust the wire count on the PT page ourselves
4264                  * for unmanaged entries.  If opa was non-zero we retained
4265                  * the existing wire count from the removal.
4266                  */
4267                 vm_page_wire_quick(pt_pv->pv_m);
4268         }
4269
4270         /*
4271          * Kernel VMAs (pt_pv == NULL) require pmap invalidation interlocks.
4272          *
4273          * User VMAs do not because those will be zero->non-zero, so no
4274          * stale entries to worry about at this point.
4275          *
4276          * For KVM there appear to still be issues.  Theoretically we
4277          * should be able to scrap the interlocks entirely but we
4278          * get crashes.
4279          */
4280         if ((prot & VM_PROT_NOSYNC) == 0 && pt_pv == NULL) {
4281                 pmap_inval_smp(pmap, va, 1, ptep, newpte);
4282         } else {
4283                 *(volatile pt_entry_t *)ptep = newpte;
4284                 if (pt_pv == NULL)
4285                         cpu_invlpg((void *)va);
4286         }
4287
4288         if (wired) {
4289                 if (pte_pv) {
4290                         atomic_add_long(&pte_pv->pv_pmap->pm_stats.wired_count,
4291                                         1);
4292                 } else {
4293                         atomic_add_long(&pmap->pm_stats.wired_count, 1);
4294                 }
4295         }
4296         if (newpte & pmap->pmap_bits[PG_RW_IDX])
4297                 vm_page_flag_set(m, PG_WRITEABLE);
4298
4299         /*
4300          * Unmanaged pages need manual resident_count tracking.
4301          */
4302         if (pte_pv == NULL && pt_pv)
4303                 atomic_add_long(&pt_pv->pv_pmap->pm_stats.resident_count, 1);
4304
4305         /*
4306          * Cleanup
4307          */
4308 done:
4309         KKASSERT((newpte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0 ||
4310                  (m->flags & PG_MAPPED));
4311
4312         /*
4313          * Cleanup the pv entry, allowing other accessors.
4314          */
4315         if (pte_pv)
4316                 pv_put(pte_pv);
4317         if (pt_pv)
4318                 pv_put(pt_pv);
4319 }
4320
4321 /*
4322  * This code works like pmap_enter() but assumes VM_PROT_READ and not-wired.
4323  * This code also assumes that the pmap has no pre-existing entry for this
4324  * VA.
4325  *
4326  * This code currently may only be used on user pmaps, not kernel_pmap.
4327  */
4328 void
4329 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m)
4330 {
4331         pmap_enter(pmap, va, m, VM_PROT_READ, FALSE, NULL);
4332 }
4333
4334 /*
4335  * Make a temporary mapping for a physical address.  This is only intended
4336  * to be used for panic dumps.
4337  *
4338  * The caller is responsible for calling smp_invltlb().
4339  */
4340 void *
4341 pmap_kenter_temporary(vm_paddr_t pa, long i)
4342 {
4343         pmap_kenter_quick((vm_offset_t)crashdumpmap + (i * PAGE_SIZE), pa);
4344         return ((void *)crashdumpmap);
4345 }
4346
4347 #define MAX_INIT_PT (96)
4348
4349 /*
4350  * This routine preloads the ptes for a given object into the specified pmap.
4351  * This eliminates the blast of soft faults on process startup and
4352  * immediately after an mmap.
4353  */
4354 static int pmap_object_init_pt_callback(vm_page_t p, void *data);
4355
4356 void
4357 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_prot_t prot,
4358                     vm_object_t object, vm_pindex_t pindex,
4359                     vm_size_t size, int limit)
4360 {
4361         struct rb_vm_page_scan_info info;
4362         struct lwp *lp;
4363         vm_size_t psize;
4364
4365         /*
4366          * We can't preinit if read access isn't set or there is no pmap
4367          * or object.
4368          */
4369         if ((prot & VM_PROT_READ) == 0 || pmap == NULL || object == NULL)
4370                 return;
4371
4372         /*
4373          * We can't preinit if the pmap is not the current pmap
4374          */
4375         lp = curthread->td_lwp;
4376         if (lp == NULL || pmap != vmspace_pmap(lp->lwp_vmspace))
4377                 return;
4378
4379         /*
4380          * Misc additional checks
4381          */
4382         psize = x86_64_btop(size);
4383
4384         if ((object->type != OBJT_VNODE) ||
4385                 ((limit & MAP_PREFAULT_PARTIAL) && (psize > MAX_INIT_PT) &&
4386                         (object->resident_page_count > MAX_INIT_PT))) {
4387                 return;
4388         }
4389
4390         if (pindex + psize > object->size) {
4391                 if (object->size < pindex)
4392                         return;           
4393                 psize = object->size - pindex;
4394         }
4395
4396         if (psize == 0)
4397                 return;
4398
4399         /*
4400          * If everything is segment-aligned do not pre-init here.  Instead
4401          * allow the normal vm_fault path to pass a segment hint to
4402          * pmap_enter() which will then use an object-referenced shared
4403          * page table page.
4404          */
4405         if ((addr & SEG_MASK) == 0 &&
4406             (ctob(psize) & SEG_MASK) == 0 &&
4407             (ctob(pindex) & SEG_MASK) == 0) {
4408                 return;
4409         }
4410
4411         /*
4412          * Use a red-black scan to traverse the requested range and load
4413          * any valid pages found into the pmap.
4414          *
4415          * We cannot safely scan the object's memq without holding the
4416          * object token.
4417          */
4418         info.start_pindex = pindex;
4419         info.end_pindex = pindex + psize - 1;
4420         info.limit = limit;
4421         info.mpte = NULL;
4422         info.addr = addr;
4423         info.pmap = pmap;
4424
4425         vm_object_hold_shared(object);
4426         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
4427                                 pmap_object_init_pt_callback, &info);
4428         vm_object_drop(object);
4429 }
4430
4431 static
4432 int
4433 pmap_object_init_pt_callback(vm_page_t p, void *data)
4434 {
4435         struct rb_vm_page_scan_info *info = data;
4436         vm_pindex_t rel_index;
4437
4438         /*
4439          * don't allow an madvise to blow away our really
4440          * free pages allocating pv entries.
4441          */
4442         if ((info->limit & MAP_PREFAULT_MADVISE) &&
4443                 vmstats.v_free_count < vmstats.v_free_reserved) {
4444                     return(-1);
4445         }
4446
4447         /*
4448          * Ignore list markers and ignore pages we cannot instantly
4449          * busy (while holding the object token).
4450          */
4451         if (p->flags & PG_MARKER)
4452                 return 0;
4453         if (vm_page_busy_try(p, TRUE))
4454                 return 0;
4455         if (((p->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) &&
4456             (p->flags & PG_FICTITIOUS) == 0) {
4457                 if ((p->queue - p->pc) == PQ_CACHE)
4458                         vm_page_deactivate(p);
4459                 rel_index = p->pindex - info->start_pindex;
4460                 pmap_enter_quick(info->pmap,
4461                                  info->addr + x86_64_ptob(rel_index), p);
4462         }
4463         vm_page_wakeup(p);
4464         lwkt_yield();
4465         return(0);
4466 }
4467
4468 /*
4469  * Return TRUE if the pmap is in shape to trivially pre-fault the specified
4470  * address.
4471  *
4472  * Returns FALSE if it would be non-trivial or if a pte is already loaded
4473  * into the slot.
4474  *
4475  * XXX This is safe only because page table pages are not freed.
4476  */
4477 int
4478 pmap_prefault_ok(pmap_t pmap, vm_offset_t addr)
4479 {
4480         pt_entry_t *pte;
4481
4482         /*spin_lock(&pmap->pm_spin);*/
4483         if ((pte = pmap_pte(pmap, addr)) != NULL) {
4484                 if (*pte & pmap->pmap_bits[PG_V_IDX]) {
4485                         /*spin_unlock(&pmap->pm_spin);*/
4486                         return FALSE;
4487                 }
4488         }
4489         /*spin_unlock(&pmap->pm_spin);*/
4490         return TRUE;
4491 }
4492
4493 /*
4494  * Change the wiring attribute for a pmap/va pair.  The mapping must already
4495  * exist in the pmap.  The mapping may or may not be managed.
4496  */
4497 void
4498 pmap_change_wiring(pmap_t pmap, vm_offset_t va, boolean_t wired,
4499                    vm_map_entry_t entry)
4500 {
4501         pt_entry_t *ptep;
4502         pv_entry_t pv;
4503
4504         if (pmap == NULL)
4505                 return;
4506         lwkt_gettoken(&pmap->pm_token);
4507         pv = pmap_allocpte_seg(pmap, pmap_pt_pindex(va), NULL, entry, va);
4508         ptep = pv_pte_lookup(pv, pmap_pte_index(va));
4509
4510         if (wired && !pmap_pte_w(pmap, ptep))
4511                 atomic_add_long(&pv->pv_pmap->pm_stats.wired_count, 1);
4512         else if (!wired && pmap_pte_w(pmap, ptep))
4513                 atomic_add_long(&pv->pv_pmap->pm_stats.wired_count, -1);
4514
4515         /*
4516          * Wiring is not a hardware characteristic so there is no need to
4517          * invalidate TLB.  However, in an SMP environment we must use
4518          * a locked bus cycle to update the pte (if we are not using 
4519          * the pmap_inval_*() API that is)... it's ok to do this for simple
4520          * wiring changes.
4521          */
4522         if (wired)
4523                 atomic_set_long(ptep, pmap->pmap_bits[PG_W_IDX]);
4524         else
4525                 atomic_clear_long(ptep, pmap->pmap_bits[PG_W_IDX]);
4526         pv_put(pv);
4527         lwkt_reltoken(&pmap->pm_token);
4528 }
4529
4530
4531
4532 /*
4533  * Copy the range specified by src_addr/len from the source map to
4534  * the range dst_addr/len in the destination map.
4535  *
4536  * This routine is only advisory and need not do anything.
4537  */
4538 void
4539 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, 
4540           vm_size_t len, vm_offset_t src_addr)
4541 {
4542 }       
4543
4544 /*
4545  * pmap_zero_page:
4546  *
4547  *      Zero the specified physical page.
4548  *
4549  *      This function may be called from an interrupt and no locking is
4550  *      required.
4551  */
4552 void
4553 pmap_zero_page(vm_paddr_t phys)
4554 {
4555         vm_offset_t va = PHYS_TO_DMAP(phys);
4556
4557         pagezero((void *)va);
4558 }
4559
4560 /*
4561  * pmap_zero_page:
4562  *
4563  *      Zero part of a physical page by mapping it into memory and clearing
4564  *      its contents with bzero.
4565  *
4566  *      off and size may not cover an area beyond a single hardware page.
4567  */
4568 void
4569 pmap_zero_page_area(vm_paddr_t phys, int off, int size)
4570 {
4571         vm_offset_t virt = PHYS_TO_DMAP(phys);
4572
4573         bzero((char *)virt + off, size);
4574 }
4575
4576 /*
4577  * pmap_copy_page:
4578  *
4579  *      Copy the physical page from the source PA to the target PA.
4580  *      This function may be called from an interrupt.  No locking
4581  *      is required.
4582  */
4583 void
4584 pmap_copy_page(vm_paddr_t src, vm_paddr_t dst)
4585 {
4586         vm_offset_t src_virt, dst_virt;
4587
4588         src_virt = PHYS_TO_DMAP(src);
4589         dst_virt = PHYS_TO_DMAP(dst);
4590         bcopy((void *)src_virt, (void *)dst_virt, PAGE_SIZE);
4591 }
4592
4593 /*
4594  * pmap_copy_page_frag:
4595  *
4596  *      Copy the physical page from the source PA to the target PA.
4597  *      This function may be called from an interrupt.  No locking
4598  *      is required.
4599  */
4600 void
4601 pmap_copy_page_frag(vm_paddr_t src, vm_paddr_t dst, size_t bytes)
4602 {
4603         vm_offset_t src_virt, dst_virt;
4604
4605         src_virt = PHYS_TO_DMAP(src);
4606         dst_virt = PHYS_TO_DMAP(dst);
4607
4608         bcopy((char *)src_virt + (src & PAGE_MASK),
4609               (char *)dst_virt + (dst & PAGE_MASK),
4610               bytes);
4611 }
4612
4613 /*
4614  * Returns true if the pmap's pv is one of the first 16 pvs linked to from
4615  * this page.  This count may be changed upwards or downwards in the future;
4616  * it is only necessary that true be returned for a small subset of pmaps
4617  * for proper page aging.
4618  */
4619 boolean_t
4620 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
4621 {
4622         pv_entry_t pv;
4623         int loops = 0;
4624
4625         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
4626                 return FALSE;
4627
4628         vm_page_spin_lock(m);
4629         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4630                 if (pv->pv_pmap == pmap) {
4631                         vm_page_spin_unlock(m);
4632                         return TRUE;
4633                 }
4634                 loops++;
4635                 if (loops >= 16)
4636                         break;
4637         }
4638         vm_page_spin_unlock(m);
4639         return (FALSE);
4640 }
4641
4642 /*
4643  * Remove all pages from specified address space this aids process exit
4644  * speeds.  Also, this code may be special cased for the current process
4645  * only.
4646  */
4647 void
4648 pmap_remove_pages(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4649 {
4650         pmap_remove_noinval(pmap, sva, eva);
4651         cpu_invltlb();
4652 }
4653
4654 /*
4655  * pmap_testbit tests bits in pte's note that the testbit/clearbit
4656  * routines are inline, and a lot of things compile-time evaluate.
4657  */
4658 static
4659 boolean_t
4660 pmap_testbit(vm_page_t m, int bit)
4661 {
4662         pv_entry_t pv;
4663         pt_entry_t *pte;
4664         pmap_t pmap;
4665
4666         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
4667                 return FALSE;
4668
4669         if (TAILQ_FIRST(&m->md.pv_list) == NULL)
4670                 return FALSE;
4671         vm_page_spin_lock(m);
4672         if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
4673                 vm_page_spin_unlock(m);
4674                 return FALSE;
4675         }
4676
4677         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4678
4679 #if defined(PMAP_DIAGNOSTIC)
4680                 if (pv->pv_pmap == NULL) {
4681                         kprintf("Null pmap (tb) at pindex: %"PRIu64"\n",
4682                             pv->pv_pindex);
4683                         continue;
4684                 }
4685 #endif
4686                 pmap = pv->pv_pmap;
4687
4688                 /*
4689                  * If the bit being tested is the modified bit, then
4690                  * mark clean_map and ptes as never
4691                  * modified.
4692                  *
4693                  * WARNING!  Because we do not lock the pv, *pte can be in a
4694                  *           state of flux.  Despite this the value of *pte
4695                  *           will still be related to the vm_page in some way
4696                  *           because the pv cannot be destroyed as long as we
4697                  *           hold the vm_page spin lock.
4698                  */
4699                 if (bit == PG_A_IDX || bit == PG_M_IDX) {
4700                                 //& (pmap->pmap_bits[PG_A_IDX] | pmap->pmap_bits[PG_M_IDX])) {
4701                         if (!pmap_track_modified(pv->pv_pindex))
4702                                 continue;
4703                 }
4704
4705                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
4706                 if (*pte & pmap->pmap_bits[bit]) {
4707                         vm_page_spin_unlock(m);
4708                         return TRUE;
4709                 }
4710         }
4711         vm_page_spin_unlock(m);
4712         return (FALSE);
4713 }
4714
4715 /*
4716  * This routine is used to modify bits in ptes.  Only one bit should be
4717  * specified.  PG_RW requires special handling.
4718  *
4719  * Caller must NOT hold any spin locks
4720  */
4721 static __inline
4722 void
4723 pmap_clearbit(vm_page_t m, int bit_index)
4724 {
4725         pv_entry_t pv;
4726         pt_entry_t *pte;
4727         pt_entry_t pbits;
4728         pmap_t pmap;
4729
4730         if (bit_index == PG_RW_IDX)
4731                 vm_page_flag_clear(m, PG_WRITEABLE);
4732         if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
4733                 return;
4734         }
4735
4736         /*
4737          * PG_M or PG_A case
4738          *
4739          * Loop over all current mappings setting/clearing as appropos If
4740          * setting RO do we need to clear the VAC?
4741          *
4742          * NOTE: When clearing PG_M we could also (not implemented) drop
4743          *       through to the PG_RW code and clear PG_RW too, forcing
4744          *       a fault on write to redetect PG_M for virtual kernels, but
4745          *       it isn't necessary since virtual kernels invalidate the
4746          *       pte when they clear the VPTE_M bit in their virtual page
4747          *       tables.
4748          *
4749          * NOTE: Does not re-dirty the page when clearing only PG_M.
4750          *
4751          * NOTE: Because we do not lock the pv, *pte can be in a state of
4752          *       flux.  Despite this the value of *pte is still somewhat
4753          *       related while we hold the vm_page spin lock.
4754          *
4755          *       *pte can be zero due to this race.  Since we are clearing
4756          *       bits we basically do no harm when this race  ccurs.
4757          */
4758         if (bit_index != PG_RW_IDX) {
4759                 vm_page_spin_lock(m);
4760                 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4761 #if defined(PMAP_DIAGNOSTIC)
4762                         if (pv->pv_pmap == NULL) {
4763                                 kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
4764                                     pv->pv_pindex);
4765                                 continue;
4766                         }
4767 #endif
4768                         pmap = pv->pv_pmap;
4769                         pte = pmap_pte_quick(pv->pv_pmap,
4770                                              pv->pv_pindex << PAGE_SHIFT);
4771                         pbits = *pte;
4772                         if (pbits & pmap->pmap_bits[bit_index])
4773                                 atomic_clear_long(pte, pmap->pmap_bits[bit_index]);
4774                 }
4775                 vm_page_spin_unlock(m);
4776                 return;
4777         }
4778
4779         /*
4780          * Clear PG_RW.  Also clears PG_M and marks the page dirty if PG_M
4781          * was set.
4782          */
4783 restart:
4784         vm_page_spin_lock(m);
4785         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4786                 /*
4787                  * don't write protect pager mappings
4788                  */
4789                 if (!pmap_track_modified(pv->pv_pindex))
4790                         continue;
4791
4792 #if defined(PMAP_DIAGNOSTIC)
4793                 if (pv->pv_pmap == NULL) {
4794                         kprintf("Null pmap (cb) at pindex: %"PRIu64"\n",
4795                             pv->pv_pindex);
4796                         continue;
4797                 }
4798 #endif
4799                 pmap = pv->pv_pmap;
4800                 /*
4801                  * Skip pages which do not have PG_RW set.
4802                  */
4803                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
4804                 if ((*pte & pmap->pmap_bits[PG_RW_IDX]) == 0)
4805                         continue;
4806
4807                 /*
4808                  * Lock the PV
4809                  */
4810                 if (pv_hold_try(pv)) {
4811                         vm_page_spin_unlock(m);
4812                 } else {
4813                         vm_page_spin_unlock(m);
4814                         pv_lock(pv);    /* held, now do a blocking lock */
4815                 }
4816                 if (pv->pv_pmap != pmap || pv->pv_m != m) {
4817                         pv_put(pv);     /* and release */
4818                         goto restart;   /* anything could have happened */
4819                 }
4820                 KKASSERT(pv->pv_pmap == pmap);
4821                 for (;;) {
4822                         pt_entry_t nbits;
4823
4824                         pbits = *pte;
4825                         cpu_ccfence();
4826                         nbits = pbits & ~(pmap->pmap_bits[PG_RW_IDX] |
4827                                           pmap->pmap_bits[PG_M_IDX]);
4828                         if (pmap_inval_smp_cmpset(pmap,
4829                                      ((vm_offset_t)pv->pv_pindex << PAGE_SHIFT),
4830                                      pte, pbits, nbits)) {
4831                                 break;
4832                         }
4833                         cpu_pause();
4834                 }
4835                 vm_page_spin_lock(m);
4836
4837                 /*
4838                  * If PG_M was found to be set while we were clearing PG_RW
4839                  * we also clear PG_M (done above) and mark the page dirty.
4840                  * Callers expect this behavior.
4841                  */
4842                 if (pbits & pmap->pmap_bits[PG_M_IDX])
4843                         vm_page_dirty(m);
4844                 pv_put(pv);
4845         }
4846         vm_page_spin_unlock(m);
4847 }
4848
4849 /*
4850  * Lower the permission for all mappings to a given page.
4851  *
4852  * Page must be busied by caller.  Because page is busied by caller this
4853  * should not be able to race a pmap_enter().
4854  */
4855 void
4856 pmap_page_protect(vm_page_t m, vm_prot_t prot)
4857 {
4858         /* JG NX support? */
4859         if ((prot & VM_PROT_WRITE) == 0) {
4860                 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
4861                         /*
4862                          * NOTE: pmap_clearbit(.. PG_RW) also clears
4863                          *       the PG_WRITEABLE flag in (m).
4864                          */
4865                         pmap_clearbit(m, PG_RW_IDX);
4866                 } else {
4867                         pmap_remove_all(m);
4868                 }
4869         }
4870 }
4871
4872 vm_paddr_t
4873 pmap_phys_address(vm_pindex_t ppn)
4874 {
4875         return (x86_64_ptob(ppn));
4876 }
4877
4878 /*
4879  * Return a count of reference bits for a page, clearing those bits.
4880  * It is not necessary for every reference bit to be cleared, but it
4881  * is necessary that 0 only be returned when there are truly no
4882  * reference bits set.
4883  *
4884  * XXX: The exact number of bits to check and clear is a matter that
4885  * should be tested and standardized at some point in the future for
4886  * optimal aging of shared pages.
4887  *
4888  * This routine may not block.
4889  */
4890 int
4891 pmap_ts_referenced(vm_page_t m)
4892 {
4893         pv_entry_t pv;
4894         pt_entry_t *pte;
4895         pmap_t pmap;
4896         int rtval = 0;
4897
4898         if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
4899                 return (rtval);
4900
4901         vm_page_spin_lock(m);
4902         TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
4903                 if (!pmap_track_modified(pv->pv_pindex))
4904                         continue;
4905                 pmap = pv->pv_pmap;
4906                 pte = pmap_pte_quick(pv->pv_pmap, pv->pv_pindex << PAGE_SHIFT);
4907                 if (pte && (*pte & pmap->pmap_bits[PG_A_IDX])) {
4908                         atomic_clear_long(pte, pmap->pmap_bits[PG_A_IDX]);
4909                         rtval++;
4910                         if (rtval > 4)
4911                                 break;
4912                 }
4913         }
4914         vm_page_spin_unlock(m);
4915         return (rtval);
4916 }
4917
4918 /*
4919  *      pmap_is_modified:
4920  *
4921  *      Return whether or not the specified physical page was modified
4922  *      in any physical maps.
4923  */
4924 boolean_t
4925 pmap_is_modified(vm_page_t m)
4926 {
4927         boolean_t res;
4928
4929         res = pmap_testbit(m, PG_M_IDX);
4930         return (res);
4931 }
4932
4933 /*
4934  *      Clear the modify bits on the specified physical page.
4935  */
4936 void
4937 pmap_clear_modify(vm_page_t m)
4938 {
4939         pmap_clearbit(m, PG_M_IDX);
4940 }
4941
4942 /*
4943  *      pmap_clear_reference:
4944  *
4945  *      Clear the reference bit on the specified physical page.
4946  */
4947 void
4948 pmap_clear_reference(vm_page_t m)
4949 {
4950         pmap_clearbit(m, PG_A_IDX);
4951 }
4952
4953 /*
4954  * Miscellaneous support routines follow
4955  */
4956
4957 static
4958 void
4959 i386_protection_init(void)
4960 {
4961         int *kp, prot;
4962
4963         /* JG NX support may go here; No VM_PROT_EXECUTE ==> set NX bit  */
4964         kp = protection_codes;
4965         for (prot = 0; prot < PROTECTION_CODES_SIZE; prot++) {
4966                 switch (prot) {
4967                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
4968                         /*
4969                          * Read access is also 0. There isn't any execute bit,
4970                          * so just make it readable.
4971                          */
4972                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
4973                 case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
4974                 case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
4975                         *kp++ = 0;
4976                         break;
4977                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
4978                 case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
4979                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
4980                 case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
4981                         *kp++ = pmap_bits_default[PG_RW_IDX];
4982                         break;
4983                 }
4984         }
4985 }
4986
4987 /*
4988  * Map a set of physical memory pages into the kernel virtual
4989  * address space. Return a pointer to where it is mapped. This
4990  * routine is intended to be used for mapping device memory,
4991  * NOT real memory.
4992  *
4993  * NOTE: We can't use pgeflag unless we invalidate the pages one at
4994  *       a time.
4995  *
4996  * NOTE: The PAT attributes {WRITE_BACK, WRITE_THROUGH, UNCACHED, UNCACHEABLE}
4997  *       work whether the cpu supports PAT or not.  The remaining PAT
4998  *       attributes {WRITE_PROTECTED, WRITE_COMBINING} only work if the cpu
4999  *       supports PAT.
5000  */
5001 void *
5002 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
5003 {
5004         return(pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5005 }
5006
5007 void *
5008 pmap_mapdev_uncacheable(vm_paddr_t pa, vm_size_t size)
5009 {
5010         return(pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
5011 }
5012
5013 void *
5014 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5015 {
5016         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5017 }
5018
5019 /*
5020  * Map a set of physical memory pages into the kernel virtual
5021  * address space. Return a pointer to where it is mapped. This
5022  * routine is intended to be used for mapping device memory,
5023  * NOT real memory.
5024  */
5025 void *
5026 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
5027 {
5028         vm_offset_t va, tmpva, offset;
5029         pt_entry_t *pte;
5030         vm_size_t tmpsize;
5031
5032         offset = pa & PAGE_MASK;
5033         size = roundup(offset + size, PAGE_SIZE);
5034
5035         va = kmem_alloc_nofault(&kernel_map, size, VM_SUBSYS_MAPDEV, PAGE_SIZE);
5036         if (va == 0)
5037                 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
5038
5039         pa = pa & ~PAGE_MASK;
5040         for (tmpva = va, tmpsize = size; tmpsize > 0;) {
5041                 pte = vtopte(tmpva);
5042                 *pte = pa |
5043                     kernel_pmap.pmap_bits[PG_RW_IDX] |
5044                     kernel_pmap.pmap_bits[PG_V_IDX] | /* pgeflag | */
5045                     kernel_pmap.pmap_cache_bits[mode];
5046                 tmpsize -= PAGE_SIZE;
5047                 tmpva += PAGE_SIZE;
5048                 pa += PAGE_SIZE;
5049         }
5050         pmap_invalidate_range(&kernel_pmap, va, va + size);
5051         pmap_invalidate_cache_range(va, va + size);
5052
5053         return ((void *)(va + offset));
5054 }
5055
5056 void
5057 pmap_unmapdev(vm_offset_t va, vm_size_t size)
5058 {
5059         vm_offset_t base, offset;
5060
5061         base = va & ~PAGE_MASK;
5062         offset = va & PAGE_MASK;
5063         size = roundup(offset + size, PAGE_SIZE);
5064         pmap_qremove(va, size >> PAGE_SHIFT);
5065         kmem_free(&kernel_map, base, size);
5066 }
5067
5068 /*
5069  * Sets the memory attribute for the specified page.
5070  */
5071 void
5072 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5073 {
5074
5075     m->pat_mode = ma;
5076
5077     /*
5078      * If "m" is a normal page, update its direct mapping.  This update
5079      * can be relied upon to perform any cache operations that are
5080      * required for data coherence.
5081      */
5082     if ((m->flags & PG_FICTITIOUS) == 0)
5083         pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), 1, m->pat_mode);
5084 }
5085
5086 /*
5087  * Change the PAT attribute on an existing kernel memory map.  Caller
5088  * must ensure that the virtual memory in question is not accessed
5089  * during the adjustment.
5090  */
5091 void
5092 pmap_change_attr(vm_offset_t va, vm_size_t count, int mode)
5093 {
5094         pt_entry_t *pte;
5095         vm_offset_t base;
5096         int changed = 0;
5097
5098         if (va == 0)
5099                 panic("pmap_change_attr: va is NULL");
5100         base = trunc_page(va);
5101
5102         while (count) {
5103                 pte = vtopte(va);
5104                 *pte = (*pte & ~(pt_entry_t)(kernel_pmap.pmap_cache_mask)) |
5105                        kernel_pmap.pmap_cache_bits[mode];
5106                 --count;
5107                 va += PAGE_SIZE;
5108         }
5109
5110         changed = 1;    /* XXX: not optimal */
5111
5112         /*
5113          * Flush CPU caches if required to make sure any data isn't cached that
5114          * shouldn't be, etc.
5115          */
5116         if (changed) {
5117                 pmap_invalidate_range(&kernel_pmap, base, va);
5118                 pmap_invalidate_cache_range(base, va);
5119         }
5120 }
5121
5122 /*
5123  * perform the pmap work for mincore
5124  */
5125 int
5126 pmap_mincore(pmap_t pmap, vm_offset_t addr)
5127 {
5128         pt_entry_t *ptep, pte;
5129         vm_page_t m;
5130         int val = 0;
5131         
5132         lwkt_gettoken(&pmap->pm_token);
5133         ptep = pmap_pte(pmap, addr);
5134
5135         if (ptep && (pte = *ptep) != 0) {
5136                 vm_offset_t pa;
5137
5138                 val = MINCORE_INCORE;
5139                 if ((pte & pmap->pmap_bits[PG_MANAGED_IDX]) == 0)
5140                         goto done;
5141
5142                 pa = pte & PG_FRAME;
5143
5144                 if (pte & pmap->pmap_bits[PG_DEVICE_IDX])
5145                         m = NULL;
5146                 else
5147                         m = PHYS_TO_VM_PAGE(pa);
5148
5149                 /*
5150                  * Modified by us
5151                  */
5152                 if (pte & pmap->pmap_bits[PG_M_IDX])
5153                         val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
5154                 /*
5155                  * Modified by someone
5156                  */
5157                 else if (m && (m->dirty || pmap_is_modified(m)))
5158                         val |= MINCORE_MODIFIED_OTHER;
5159                 /*
5160                  * Referenced by us
5161                  */
5162                 if (pte & pmap->pmap_bits[PG_A_IDX])
5163                         val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
5164
5165                 /*
5166                  * Referenced by someone
5167                  */
5168                 else if (m && ((m->flags & PG_REFERENCED) ||
5169                                 pmap_ts_referenced(m))) {
5170                         val |= MINCORE_REFERENCED_OTHER;
5171                         vm_page_flag_set(m, PG_REFERENCED);
5172                 }
5173         } 
5174 done:
5175         lwkt_reltoken(&pmap->pm_token);
5176
5177         return val;
5178 }
5179
5180 /*
5181  * Replace p->p_vmspace with a new one.  If adjrefs is non-zero the new
5182  * vmspace will be ref'd and the old one will be deref'd.
5183  *
5184  * The vmspace for all lwps associated with the process will be adjusted
5185  * and cr3 will be reloaded if any lwp is the current lwp.
5186  *
5187  * The process must hold the vmspace->vm_map.token for oldvm and newvm
5188  */
5189 void
5190 pmap_replacevm(struct proc *p, struct vmspace *newvm, int adjrefs)
5191 {
5192         struct vmspace *oldvm;
5193         struct lwp *lp;
5194
5195         oldvm = p->p_vmspace;
5196         if (oldvm != newvm) {
5197                 if (adjrefs)
5198                         vmspace_ref(newvm);
5199                 p->p_vmspace = newvm;
5200                 KKASSERT(p->p_nthreads == 1);
5201                 lp = RB_ROOT(&p->p_lwp_tree);
5202                 pmap_setlwpvm(lp, newvm);
5203                 if (adjrefs)
5204                         vmspace_rel(oldvm);
5205         }
5206 }
5207
5208 /*
5209  * Set the vmspace for a LWP.  The vmspace is almost universally set the
5210  * same as the process vmspace, but virtual kernels need to swap out contexts
5211  * on a per-lwp basis.
5212  *
5213  * Caller does not necessarily hold any vmspace tokens.  Caller must control
5214  * the lwp (typically be in the context of the lwp).  We use a critical
5215  * section to protect against statclock and hardclock (statistics collection).
5216  */
5217 void
5218 pmap_setlwpvm(struct lwp *lp, struct vmspace *newvm)
5219 {
5220         struct vmspace *oldvm;
5221         struct pmap *pmap;
5222
5223         oldvm = lp->lwp_vmspace;
5224
5225         if (oldvm != newvm) {
5226                 crit_enter();
5227                 lp->lwp_vmspace = newvm;
5228                 if (curthread->td_lwp == lp) {
5229                         pmap = vmspace_pmap(newvm);
5230                         ATOMIC_CPUMASK_ORBIT(pmap->pm_active, mycpu->gd_cpuid);
5231                         if (pmap->pm_active_lock & CPULOCK_EXCL)
5232                                 pmap_interlock_wait(newvm);
5233 #if defined(SWTCH_OPTIM_STATS)
5234                         tlb_flush_count++;
5235 #endif
5236                         if (pmap->pmap_bits[TYPE_IDX] == REGULAR_PMAP) {
5237                                 curthread->td_pcb->pcb_cr3 = vtophys(pmap->pm_pml4);
5238                         } else if (pmap->pmap_bits[TYPE_IDX] == EPT_PMAP) {
5239                                 curthread->td_pcb->pcb_cr3 = KPML4phys;
5240                         } else {
5241                                 panic("pmap_setlwpvm: unknown pmap type\n");
5242                         }
5243                         load_cr3(curthread->td_pcb->pcb_cr3);
5244                         pmap = vmspace_pmap(oldvm);
5245                         ATOMIC_CPUMASK_NANDBIT(pmap->pm_active,
5246                                                mycpu->gd_cpuid);
5247                 }
5248                 crit_exit();
5249         }
5250 }
5251
5252 /*
5253  * Called when switching to a locked pmap, used to interlock against pmaps
5254  * undergoing modifications to prevent us from activating the MMU for the
5255  * target pmap until all such modifications have completed.  We have to do
5256  * this because the thread making the modifications has already set up its
5257  * SMP synchronization mask.
5258  *
5259  * This function cannot sleep!
5260  *
5261  * No requirements.
5262  */
5263 void
5264 pmap_interlock_wait(struct vmspace *vm)
5265 {
5266         struct pmap *pmap = &vm->vm_pmap;
5267
5268         if (pmap->pm_active_lock & CPULOCK_EXCL) {
5269                 crit_enter();
5270                 KKASSERT(curthread->td_critcount >= 2);
5271                 DEBUG_PUSH_INFO("pmap_interlock_wait");
5272                 while (pmap->pm_active_lock & CPULOCK_EXCL) {
5273                         cpu_ccfence();
5274                         lwkt_process_ipiq();
5275                 }
5276                 DEBUG_POP_INFO();
5277                 crit_exit();
5278         }
5279 }
5280
5281 vm_offset_t
5282 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
5283 {
5284
5285         if ((obj == NULL) || (size < NBPDR) ||
5286             ((obj->type != OBJT_DEVICE) && (obj->type != OBJT_MGTDEVICE))) {
5287                 return addr;
5288         }
5289
5290         addr = roundup2(addr, NBPDR);
5291         return addr;
5292 }
5293
5294 /*
5295  * Used by kmalloc/kfree, page already exists at va
5296  */
5297 vm_page_t
5298 pmap_kvtom(vm_offset_t va)
5299 {
5300         pt_entry_t *ptep = vtopte(va);
5301
5302         KKASSERT((*ptep & kernel_pmap.pmap_bits[PG_DEVICE_IDX]) == 0);
5303         return(PHYS_TO_VM_PAGE(*ptep & PG_FRAME));
5304 }
5305
5306 /*
5307  * Initialize machine-specific shared page directory support.  This
5308  * is executed when a VM object is created.
5309  */
5310 void
5311 pmap_object_init(vm_object_t object)
5312 {
5313         object->md.pmap_rw = NULL;
5314         object->md.pmap_ro = NULL;
5315 }
5316
5317 /*
5318  * Clean up machine-specific shared page directory support.  This
5319  * is executed when a VM object is destroyed.
5320  */
5321 void
5322 pmap_object_free(vm_object_t object)
5323 {
5324         pmap_t pmap;
5325
5326         if ((pmap = object->md.pmap_rw) != NULL) {
5327                 object->md.pmap_rw = NULL;
5328                 pmap_remove_noinval(pmap,
5329                                   VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
5330                 CPUMASK_ASSZERO(pmap->pm_active);
5331                 pmap_release(pmap);
5332                 pmap_puninit(pmap);
5333                 kfree(pmap, M_OBJPMAP);
5334         }
5335         if ((pmap = object->md.pmap_ro) != NULL) {
5336                 object->md.pmap_ro = NULL;
5337                 pmap_remove_noinval(pmap,
5338                                   VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
5339                 CPUMASK_ASSZERO(pmap->pm_active);
5340                 pmap_release(pmap);
5341                 pmap_puninit(pmap);
5342                 kfree(pmap, M_OBJPMAP);
5343         }
5344 }