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