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