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