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