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