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