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