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