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