]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/pmap.c
Fix Machine Check Exception on Page Size Change.
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / pmap.c
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  * Copyright (c) 2003 Peter Wemm
9  * All rights reserved.
10  * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11  * All rights reserved.
12  * Copyright (c) 2014-2018 The FreeBSD Foundation
13  * All rights reserved.
14  *
15  * This code is derived from software contributed to Berkeley by
16  * the Systems Programming Group of the University of Utah Computer
17  * Science Department and William Jolitz of UUNET Technologies Inc.
18  *
19  * Portions of this software were developed by
20  * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
21  * the FreeBSD Foundation.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *      This product includes software developed by the University of
34  *      California, Berkeley and its contributors.
35  * 4. Neither the name of the University nor the names of its contributors
36  *    may be used to endorse or promote products derived from this software
37  *    without specific prior written permission.
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49  * SUCH DAMAGE.
50  *
51  *      from:   @(#)pmap.c      7.7 (Berkeley)  5/12/91
52  */
53 /*-
54  * Copyright (c) 2003 Networks Associates Technology, Inc.
55  * All rights reserved.
56  *
57  * This software was developed for the FreeBSD Project by Jake Burkholder,
58  * Safeport Network Services, and Network Associates Laboratories, the
59  * Security Research Division of Network Associates, Inc. under
60  * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
61  * CHATS research program.
62  *
63  * Redistribution and use in source and binary forms, with or without
64  * modification, are permitted provided that the following conditions
65  * are met:
66  * 1. Redistributions of source code must retain the above copyright
67  *    notice, this list of conditions and the following disclaimer.
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in the
70  *    documentation and/or other materials provided with the distribution.
71  *
72  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
73  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
76  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
77  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
78  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
79  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
80  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
81  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
82  * SUCH DAMAGE.
83  */
84
85 #define AMD64_NPT_AWARE
86
87 #include <sys/cdefs.h>
88 __FBSDID("$FreeBSD$");
89
90 /*
91  *      Manages physical address maps.
92  *
93  *      Since the information managed by this module is
94  *      also stored by the logical address mapping module,
95  *      this module may throw away valid virtual-to-physical
96  *      mappings at almost any time.  However, invalidations
97  *      of virtual-to-physical mappings must be done as
98  *      requested.
99  *
100  *      In order to cope with hardware architectures which
101  *      make virtual-to-physical map invalidates expensive,
102  *      this module may delay invalidate or reduced protection
103  *      operations until such time as they are actually
104  *      necessary.  This module is given full information as
105  *      to which processors are currently using which maps,
106  *      and to when physical maps must be made correct.
107  */
108
109 #include "opt_pmap.h"
110 #include "opt_vm.h"
111
112 #include <sys/param.h>
113 #include <sys/bitstring.h>
114 #include <sys/bus.h>
115 #include <sys/systm.h>
116 #include <sys/kernel.h>
117 #include <sys/ktr.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/mutex.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
124 #include <sys/sx.h>
125 #include <sys/turnstile.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
130 #include <sys/smp.h>
131
132 #include <vm/vm.h>
133 #include <vm/vm_param.h>
134 #include <vm/vm_kern.h>
135 #include <vm/vm_page.h>
136 #include <vm/vm_map.h>
137 #include <vm/vm_object.h>
138 #include <vm/vm_extern.h>
139 #include <vm/vm_pageout.h>
140 #include <vm/vm_pager.h>
141 #include <vm/vm_phys.h>
142 #include <vm/vm_radix.h>
143 #include <vm/vm_reserv.h>
144 #include <vm/uma.h>
145
146 #include <machine/intr_machdep.h>
147 #include <x86/apicvar.h>
148 #include <machine/cpu.h>
149 #include <machine/cputypes.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
152 #include <machine/specialreg.h>
153 #ifdef SMP
154 #include <machine/smp.h>
155 #endif
156 #include <machine/tss.h>
157
158 static __inline boolean_t
159 pmap_type_guest(pmap_t pmap)
160 {
161
162         return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
163 }
164
165 static __inline boolean_t
166 pmap_emulate_ad_bits(pmap_t pmap)
167 {
168
169         return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
170 }
171
172 static __inline pt_entry_t
173 pmap_valid_bit(pmap_t pmap)
174 {
175         pt_entry_t mask;
176
177         switch (pmap->pm_type) {
178         case PT_X86:
179         case PT_RVI:
180                 mask = X86_PG_V;
181                 break;
182         case PT_EPT:
183                 if (pmap_emulate_ad_bits(pmap))
184                         mask = EPT_PG_EMUL_V;
185                 else
186                         mask = EPT_PG_READ;
187                 break;
188         default:
189                 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
190         }
191
192         return (mask);
193 }
194
195 static __inline pt_entry_t
196 pmap_rw_bit(pmap_t pmap)
197 {
198         pt_entry_t mask;
199
200         switch (pmap->pm_type) {
201         case PT_X86:
202         case PT_RVI:
203                 mask = X86_PG_RW;
204                 break;
205         case PT_EPT:
206                 if (pmap_emulate_ad_bits(pmap))
207                         mask = EPT_PG_EMUL_RW;
208                 else
209                         mask = EPT_PG_WRITE;
210                 break;
211         default:
212                 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
213         }
214
215         return (mask);
216 }
217
218 static pt_entry_t pg_g;
219
220 static __inline pt_entry_t
221 pmap_global_bit(pmap_t pmap)
222 {
223         pt_entry_t mask;
224
225         switch (pmap->pm_type) {
226         case PT_X86:
227                 mask = pg_g;
228                 break;
229         case PT_RVI:
230         case PT_EPT:
231                 mask = 0;
232                 break;
233         default:
234                 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
235         }
236
237         return (mask);
238 }
239
240 static __inline pt_entry_t
241 pmap_accessed_bit(pmap_t pmap)
242 {
243         pt_entry_t mask;
244
245         switch (pmap->pm_type) {
246         case PT_X86:
247         case PT_RVI:
248                 mask = X86_PG_A;
249                 break;
250         case PT_EPT:
251                 if (pmap_emulate_ad_bits(pmap))
252                         mask = EPT_PG_READ;
253                 else
254                         mask = EPT_PG_A;
255                 break;
256         default:
257                 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
258         }
259
260         return (mask);
261 }
262
263 static __inline pt_entry_t
264 pmap_modified_bit(pmap_t pmap)
265 {
266         pt_entry_t mask;
267
268         switch (pmap->pm_type) {
269         case PT_X86:
270         case PT_RVI:
271                 mask = X86_PG_M;
272                 break;
273         case PT_EPT:
274                 if (pmap_emulate_ad_bits(pmap))
275                         mask = EPT_PG_WRITE;
276                 else
277                         mask = EPT_PG_M;
278                 break;
279         default:
280                 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
281         }
282
283         return (mask);
284 }
285
286 extern  struct pcpu __pcpu[];
287
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE     __attribute__((__gnu_inline__)) inline
291 #else
292 #define PMAP_INLINE     extern inline
293 #endif
294 #else
295 #define PMAP_INLINE
296 #endif
297
298 #ifdef PV_STATS
299 #define PV_STAT(x)      do { x ; } while (0)
300 #else
301 #define PV_STAT(x)      do { } while (0)
302 #endif
303
304 #define pa_index(pa)    ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa)   (&pv_table[pa_index(pa)])
306
307 #define NPV_LIST_LOCKS  MAXCPU
308
309 #define PHYS_TO_PV_LIST_LOCK(pa)        \
310                         (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
311
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa)  do {    \
313         struct rwlock **_lockp = (lockp);               \
314         struct rwlock *_new_lock;                       \
315                                                         \
316         _new_lock = PHYS_TO_PV_LIST_LOCK(pa);           \
317         if (_new_lock != *_lockp) {                     \
318                 if (*_lockp != NULL)                    \
319                         rw_wunlock(*_lockp);            \
320                 *_lockp = _new_lock;                    \
321                 rw_wlock(*_lockp);                      \
322         }                                               \
323 } while (0)
324
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m)        \
326                         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
327
328 #define RELEASE_PV_LIST_LOCK(lockp)             do {    \
329         struct rwlock **_lockp = (lockp);               \
330                                                         \
331         if (*_lockp != NULL) {                          \
332                 rw_wunlock(*_lockp);                    \
333                 *_lockp = NULL;                         \
334         }                                               \
335 } while (0)
336
337 #define VM_PAGE_TO_PV_LIST_LOCK(m)      \
338                         PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
339
340 struct pmap kernel_pmap_store;
341
342 vm_offset_t virtual_avail;      /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end;        /* VA of last avail page (end of kernel AS) */
344
345 int nkpt;
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347     "Number of kernel page table pages allocated on bootup");
348
349 static int ndmpdp;
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
352 pt_entry_t pg_nx;
353
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
355
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358     "Is page attribute table fully functional?");
359
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362     &pg_ps_enabled, 0, "Are large page mappings enabled?");
363
364 #define PAT_INDEX_SIZE  8
365 static int pat_index[PAT_INDEX_SIZE];   /* cache mode to PAT index conversion */
366
367 static u_int64_t        KPTphys;        /* phys addr of kernel level 1 */
368 static u_int64_t        KPDphys;        /* phys addr of kernel level 2 */
369 u_int64_t               KPDPphys;       /* phys addr of kernel level 3 */
370 u_int64_t               KPML4phys;      /* phys addr of kernel level 4 */
371
372 static u_int64_t        DMPDphys;       /* phys addr of direct mapped level 2 */
373 static u_int64_t        DMPDPphys;      /* phys addr of direct mapped level 3 */
374 static int              ndmpdpphys;     /* number of DMPDPphys pages */
375
376 static vm_paddr_t       KERNend;        /* phys addr of end of bootstrap data */
377
378 /*
379  * pmap_mapdev support pre initialization (i.e. console)
380  */
381 #define PMAP_PREINIT_MAPPING_COUNT      8
382 static struct pmap_preinit_mapping {
383         vm_paddr_t      pa;
384         vm_offset_t     va;
385         vm_size_t       sz;
386         int             mode;
387 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
388 static int pmap_initialized;
389
390 /*
391  * Data for the pv entry allocation mechanism.
392  * Updates to pv_invl_gen are protected by the pv_list_locks[]
393  * elements, but reads are not.
394  */
395 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
396 static struct mtx pv_chunks_mutex;
397 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
398 static u_long pv_invl_gen[NPV_LIST_LOCKS];
399 static struct md_page *pv_table;
400 static struct md_page pv_dummy;
401
402 /*
403  * All those kernel PT submaps that BSD is so fond of
404  */
405 pt_entry_t *CMAP1 = NULL;
406 caddr_t CADDR1 = 0;
407 static vm_offset_t qframe = 0;
408 static struct mtx qframe_mtx;
409
410 static int pmap_flags = PMAP_PDE_SUPERPAGE;     /* flags for x86 pmaps */
411
412 int pmap_pcid_enabled = 1;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
414     &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
415 int invpcid_works = 0;
416 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
417     "Is the invpcid instruction available ?");
418
419 int pti = 0;
420 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
421     &pti, 0,
422     "Page Table Isolation enabled");
423 static vm_object_t pti_obj;
424 static pml4_entry_t *pti_pml4;
425 static vm_pindex_t pti_pg_idx;
426 static bool pti_finalized;
427
428 static int
429 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
430 {
431         int i;
432         uint64_t res;
433
434         res = 0;
435         CPU_FOREACH(i) {
436                 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
437         }
438         return (sysctl_handle_64(oidp, &res, 0, req));
439 }
440 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
441     CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
442     "Count of saved TLB context on switch");
443
444 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
445     LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
446 static struct mtx invl_gen_mtx;
447 static u_long pmap_invl_gen = 0;
448 /* Fake lock object to satisfy turnstiles interface. */
449 static struct lock_object invl_gen_ts = {
450         .lo_name = "invlts",
451 };
452
453 static bool
454 pmap_not_in_di(void)
455 {
456
457         return (curthread->td_md.md_invl_gen.gen == 0);
458 }
459
460 #define PMAP_ASSERT_NOT_IN_DI() \
461     KASSERT(pmap_not_in_di(), ("DI already started"))
462
463 /*
464  * Start a new Delayed Invalidation (DI) block of code, executed by
465  * the current thread.  Within a DI block, the current thread may
466  * destroy both the page table and PV list entries for a mapping and
467  * then release the corresponding PV list lock before ensuring that
468  * the mapping is flushed from the TLBs of any processors with the
469  * pmap active.
470  */
471 static void
472 pmap_delayed_invl_started(void)
473 {
474         struct pmap_invl_gen *invl_gen;
475         u_long currgen;
476
477         invl_gen = &curthread->td_md.md_invl_gen;
478         PMAP_ASSERT_NOT_IN_DI();
479         mtx_lock(&invl_gen_mtx);
480         if (LIST_EMPTY(&pmap_invl_gen_tracker))
481                 currgen = pmap_invl_gen;
482         else
483                 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
484         invl_gen->gen = currgen + 1;
485         LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
486         mtx_unlock(&invl_gen_mtx);
487 }
488
489 /*
490  * Finish the DI block, previously started by the current thread.  All
491  * required TLB flushes for the pages marked by
492  * pmap_delayed_invl_page() must be finished before this function is
493  * called.
494  *
495  * This function works by bumping the global DI generation number to
496  * the generation number of the current thread's DI, unless there is a
497  * pending DI that started earlier.  In the latter case, bumping the
498  * global DI generation number would incorrectly signal that the
499  * earlier DI had finished.  Instead, this function bumps the earlier
500  * DI's generation number to match the generation number of the
501  * current thread's DI.
502  */
503 static void
504 pmap_delayed_invl_finished(void)
505 {
506         struct pmap_invl_gen *invl_gen, *next;
507         struct turnstile *ts;
508
509         invl_gen = &curthread->td_md.md_invl_gen;
510         KASSERT(invl_gen->gen != 0, ("missed invl_started"));
511         mtx_lock(&invl_gen_mtx);
512         next = LIST_NEXT(invl_gen, link);
513         if (next == NULL) {
514                 turnstile_chain_lock(&invl_gen_ts);
515                 ts = turnstile_lookup(&invl_gen_ts);
516                 pmap_invl_gen = invl_gen->gen;
517                 if (ts != NULL) {
518                         turnstile_broadcast(ts, TS_SHARED_QUEUE);
519                         turnstile_unpend(ts, TS_SHARED_LOCK);
520                 }
521                 turnstile_chain_unlock(&invl_gen_ts);
522         } else {
523                 next->gen = invl_gen->gen;
524         }
525         LIST_REMOVE(invl_gen, link);
526         mtx_unlock(&invl_gen_mtx);
527         invl_gen->gen = 0;
528 }
529
530 #ifdef PV_STATS
531 static long invl_wait;
532 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
533     "Number of times DI invalidation blocked pmap_remove_all/write");
534 #endif
535
536 static u_long *
537 pmap_delayed_invl_genp(vm_page_t m)
538 {
539
540         return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
541 }
542
543 /*
544  * Ensure that all currently executing DI blocks, that need to flush
545  * TLB for the given page m, actually flushed the TLB at the time the
546  * function returned.  If the page m has an empty PV list and we call
547  * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
548  * valid mapping for the page m in either its page table or TLB.
549  *
550  * This function works by blocking until the global DI generation
551  * number catches up with the generation number associated with the
552  * given page m and its PV list.  Since this function's callers
553  * typically own an object lock and sometimes own a page lock, it
554  * cannot sleep.  Instead, it blocks on a turnstile to relinquish the
555  * processor.
556  */
557 static void
558 pmap_delayed_invl_wait(vm_page_t m)
559 {
560         struct turnstile *ts;
561         u_long *m_gen;
562 #ifdef PV_STATS
563         bool accounted = false;
564 #endif
565
566         m_gen = pmap_delayed_invl_genp(m);
567         while (*m_gen > pmap_invl_gen) {
568 #ifdef PV_STATS
569                 if (!accounted) {
570                         atomic_add_long(&invl_wait, 1);
571                         accounted = true;
572                 }
573 #endif
574                 ts = turnstile_trywait(&invl_gen_ts);
575                 if (*m_gen > pmap_invl_gen)
576                         turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
577                 else
578                         turnstile_cancel(ts);
579         }
580 }
581
582 /*
583  * Mark the page m's PV list as participating in the current thread's
584  * DI block.  Any threads concurrently using m's PV list to remove or
585  * restrict all mappings to m will wait for the current thread's DI
586  * block to complete before proceeding.
587  *
588  * The function works by setting the DI generation number for m's PV
589  * list to at least the DI generation number of the current thread.
590  * This forces a caller of pmap_delayed_invl_wait() to block until
591  * current thread calls pmap_delayed_invl_finished().
592  */
593 static void
594 pmap_delayed_invl_page(vm_page_t m)
595 {
596         u_long gen, *m_gen;
597
598         rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
599         gen = curthread->td_md.md_invl_gen.gen;
600         if (gen == 0)
601                 return;
602         m_gen = pmap_delayed_invl_genp(m);
603         if (*m_gen < gen)
604                 *m_gen = gen;
605 }
606
607 /*
608  * Crashdump maps.
609  */
610 static caddr_t crashdumpmap;
611
612 /*
613  * Internal flags for pmap_enter()'s helper functions.
614  */
615 #define PMAP_ENTER_NORECLAIM    0x1000000       /* Don't reclaim PV entries. */
616 #define PMAP_ENTER_NOREPLACE    0x2000000       /* Don't replace mappings. */
617
618 static void     free_pv_chunk(struct pv_chunk *pc);
619 static void     free_pv_entry(pmap_t pmap, pv_entry_t pv);
620 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
621 static int      popcnt_pc_map_pq(uint64_t *map);
622 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
623 static void     reserve_pv_entries(pmap_t pmap, int needed,
624                     struct rwlock **lockp);
625 static void     pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
626                     struct rwlock **lockp);
627 static bool     pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
628                     u_int flags, struct rwlock **lockp);
629 #if VM_NRESERVLEVEL > 0
630 static void     pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
631                     struct rwlock **lockp);
632 #endif
633 static void     pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
634 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
635                     vm_offset_t va);
636
637 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
638 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
639 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
640     vm_offset_t va, struct rwlock **lockp);
641 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
642     vm_offset_t va);
643 static bool     pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
644                     vm_prot_t prot, struct rwlock **lockp);
645 static int      pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
646                     u_int flags, vm_page_t m, struct rwlock **lockp);
647 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
648     vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
649 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
650 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
651 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
652                     pd_entry_t pde);
653 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
654 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
655 #if VM_NRESERVLEVEL > 0
656 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
657     struct rwlock **lockp);
658 #endif
659 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
660     vm_prot_t prot);
661 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
662 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
663     bool exec);
664 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
665 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
666 static void pmap_pti_wire_pte(void *pte);
667 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
668     struct spglist *free, struct rwlock **lockp);
669 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
670     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
671 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
672 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
673     struct spglist *free);
674 static bool     pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
675                     pd_entry_t *pde, struct spglist *free,
676                     struct rwlock **lockp);
677 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
678     vm_page_t m, struct rwlock **lockp);
679 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
680     pd_entry_t newpde);
681 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
682
683 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
684                 struct rwlock **lockp);
685 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
686                 struct rwlock **lockp);
687 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
688                 struct rwlock **lockp);
689
690 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
691     struct spglist *free);
692 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
693
694 /********************/
695 /* Inline functions */
696 /********************/
697
698 /* Return a non-clipped PD index for a given VA */
699 static __inline vm_pindex_t
700 pmap_pde_pindex(vm_offset_t va)
701 {
702         return (va >> PDRSHIFT);
703 }
704
705
706 /* Return a pointer to the PML4 slot that corresponds to a VA */
707 static __inline pml4_entry_t *
708 pmap_pml4e(pmap_t pmap, vm_offset_t va)
709 {
710
711         return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
712 }
713
714 /* Return a pointer to the PDP slot that corresponds to a VA */
715 static __inline pdp_entry_t *
716 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
717 {
718         pdp_entry_t *pdpe;
719
720         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
721         return (&pdpe[pmap_pdpe_index(va)]);
722 }
723
724 /* Return a pointer to the PDP slot that corresponds to a VA */
725 static __inline pdp_entry_t *
726 pmap_pdpe(pmap_t pmap, vm_offset_t va)
727 {
728         pml4_entry_t *pml4e;
729         pt_entry_t PG_V;
730
731         PG_V = pmap_valid_bit(pmap);
732         pml4e = pmap_pml4e(pmap, va);
733         if ((*pml4e & PG_V) == 0)
734                 return (NULL);
735         return (pmap_pml4e_to_pdpe(pml4e, va));
736 }
737
738 /* Return a pointer to the PD slot that corresponds to a VA */
739 static __inline pd_entry_t *
740 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
741 {
742         pd_entry_t *pde;
743
744         pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
745         return (&pde[pmap_pde_index(va)]);
746 }
747
748 /* Return a pointer to the PD slot that corresponds to a VA */
749 static __inline pd_entry_t *
750 pmap_pde(pmap_t pmap, vm_offset_t va)
751 {
752         pdp_entry_t *pdpe;
753         pt_entry_t PG_V;
754
755         PG_V = pmap_valid_bit(pmap);
756         pdpe = pmap_pdpe(pmap, va);
757         if (pdpe == NULL || (*pdpe & PG_V) == 0)
758                 return (NULL);
759         return (pmap_pdpe_to_pde(pdpe, va));
760 }
761
762 /* Return a pointer to the PT slot that corresponds to a VA */
763 static __inline pt_entry_t *
764 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
765 {
766         pt_entry_t *pte;
767
768         pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
769         return (&pte[pmap_pte_index(va)]);
770 }
771
772 /* Return a pointer to the PT slot that corresponds to a VA */
773 static __inline pt_entry_t *
774 pmap_pte(pmap_t pmap, vm_offset_t va)
775 {
776         pd_entry_t *pde;
777         pt_entry_t PG_V;
778
779         PG_V = pmap_valid_bit(pmap);
780         pde = pmap_pde(pmap, va);
781         if (pde == NULL || (*pde & PG_V) == 0)
782                 return (NULL);
783         if ((*pde & PG_PS) != 0)        /* compat with i386 pmap_pte() */
784                 return ((pt_entry_t *)pde);
785         return (pmap_pde_to_pte(pde, va));
786 }
787
788 static __inline void
789 pmap_resident_count_inc(pmap_t pmap, int count)
790 {
791
792         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
793         pmap->pm_stats.resident_count += count;
794 }
795
796 static __inline void
797 pmap_resident_count_dec(pmap_t pmap, int count)
798 {
799
800         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
801         KASSERT(pmap->pm_stats.resident_count >= count,
802             ("pmap %p resident count underflow %ld %d", pmap,
803             pmap->pm_stats.resident_count, count));
804         pmap->pm_stats.resident_count -= count;
805 }
806
807 PMAP_INLINE pt_entry_t *
808 vtopte(vm_offset_t va)
809 {
810         u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
811
812         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
813
814         return (PTmap + ((va >> PAGE_SHIFT) & mask));
815 }
816
817 static __inline pd_entry_t *
818 vtopde(vm_offset_t va)
819 {
820         u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
821
822         KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
823
824         return (PDmap + ((va >> PDRSHIFT) & mask));
825 }
826
827 static u_int64_t
828 allocpages(vm_paddr_t *firstaddr, int n)
829 {
830         u_int64_t ret;
831
832         ret = *firstaddr;
833         bzero((void *)ret, n * PAGE_SIZE);
834         *firstaddr += n * PAGE_SIZE;
835         return (ret);
836 }
837
838 CTASSERT(powerof2(NDMPML4E));
839
840 /* number of kernel PDP slots */
841 #define NKPDPE(ptpgs)           howmany(ptpgs, NPDEPG)
842
843 static void
844 nkpt_init(vm_paddr_t addr)
845 {
846         int pt_pages;
847         
848 #ifdef NKPT
849         pt_pages = NKPT;
850 #else
851         pt_pages = howmany(addr, 1 << PDRSHIFT);
852         pt_pages += NKPDPE(pt_pages);
853
854         /*
855          * Add some slop beyond the bare minimum required for bootstrapping
856          * the kernel.
857          *
858          * This is quite important when allocating KVA for kernel modules.
859          * The modules are required to be linked in the negative 2GB of
860          * the address space.  If we run out of KVA in this region then
861          * pmap_growkernel() will need to allocate page table pages to map
862          * the entire 512GB of KVA space which is an unnecessary tax on
863          * physical memory.
864          *
865          * Secondly, device memory mapped as part of setting up the low-
866          * level console(s) is taken from KVA, starting at virtual_avail.
867          * This is because cninit() is called after pmap_bootstrap() but
868          * before vm_init() and pmap_init(). 20MB for a frame buffer is
869          * not uncommon.
870          */
871         pt_pages += 32;         /* 64MB additional slop. */
872 #endif
873         nkpt = pt_pages;
874 }
875
876 static void
877 create_pagetables(vm_paddr_t *firstaddr)
878 {
879         int i, j, ndm1g, nkpdpe;
880         pt_entry_t *pt_p;
881         pd_entry_t *pd_p;
882         pdp_entry_t *pdp_p;
883         pml4_entry_t *p4_p;
884
885         /* Allocate page table pages for the direct map */
886         ndmpdp = howmany(ptoa(Maxmem), NBPDP);
887         if (ndmpdp < 4)         /* Minimum 4GB of dirmap */
888                 ndmpdp = 4;
889         ndmpdpphys = howmany(ndmpdp, NPDPEPG);
890         if (ndmpdpphys > NDMPML4E) {
891                 /*
892                  * Each NDMPML4E allows 512 GB, so limit to that,
893                  * and then readjust ndmpdp and ndmpdpphys.
894                  */
895                 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
896                 Maxmem = atop(NDMPML4E * NBPML4);
897                 ndmpdpphys = NDMPML4E;
898                 ndmpdp = NDMPML4E * NPDEPG;
899         }
900         DMPDPphys = allocpages(firstaddr, ndmpdpphys);
901         ndm1g = 0;
902         if ((amd_feature & AMDID_PAGE1GB) != 0)
903                 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
904         if (ndm1g < ndmpdp)
905                 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
906         dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
907
908         /* Allocate pages */
909         KPML4phys = allocpages(firstaddr, 1);
910         KPDPphys = allocpages(firstaddr, NKPML4E);
911
912         /*
913          * Allocate the initial number of kernel page table pages required to
914          * bootstrap.  We defer this until after all memory-size dependent
915          * allocations are done (e.g. direct map), so that we don't have to
916          * build in too much slop in our estimate.
917          *
918          * Note that when NKPML4E > 1, we have an empty page underneath
919          * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
920          * pages.  (pmap_enter requires a PD page to exist for each KPML4E.)
921          */
922         nkpt_init(*firstaddr);
923         nkpdpe = NKPDPE(nkpt);
924
925         KPTphys = allocpages(firstaddr, nkpt);
926         KPDphys = allocpages(firstaddr, nkpdpe);
927
928         /* Fill in the underlying page table pages */
929         /* Nominally read-only (but really R/W) from zero to physfree */
930         /* XXX not fully used, underneath 2M pages */
931         pt_p = (pt_entry_t *)KPTphys;
932         for (i = 0; ptoa(i) < *firstaddr; i++)
933                 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
934
935         /* Now map the page tables at their location within PTmap */
936         pd_p = (pd_entry_t *)KPDphys;
937         for (i = 0; i < nkpt; i++)
938                 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
939
940         /* Map from zero to end of allocations under 2M pages */
941         /* This replaces some of the KPTphys entries above */
942         for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
943                 /* Preset PG_M and PG_A because demotion expects it. */
944                 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
945                     X86_PG_M | X86_PG_A | pg_g;
946
947         /*
948          * Because we map the physical blocks in 2M pages, adjust firstaddr
949          * to record the physical blocks we've actually mapped into kernel
950          * virtual address space.
951          */
952         *firstaddr = round_2mpage(*firstaddr);
953
954         /* And connect up the PD to the PDP (leaving room for L4 pages) */
955         pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
956         for (i = 0; i < nkpdpe; i++)
957                 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
958
959         /*
960          * Now, set up the direct map region using 2MB and/or 1GB pages.  If
961          * the end of physical memory is not aligned to a 1GB page boundary,
962          * then the residual physical memory is mapped with 2MB pages.  Later,
963          * if pmap_mapdev{_attr}() uses the direct map for non-write-back
964          * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
965          * that are partially used. 
966          */
967         pd_p = (pd_entry_t *)DMPDphys;
968         for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
969                 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
970                 /* Preset PG_M and PG_A because demotion expects it. */
971                 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
972                     X86_PG_M | X86_PG_A;
973         }
974         pdp_p = (pdp_entry_t *)DMPDPphys;
975         for (i = 0; i < ndm1g; i++) {
976                 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
977                 /* Preset PG_M and PG_A because demotion expects it. */
978                 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
979                     X86_PG_M | X86_PG_A;
980         }
981         for (j = 0; i < ndmpdp; i++, j++) {
982                 pdp_p[i] = DMPDphys + ptoa(j);
983                 pdp_p[i] |= X86_PG_RW | X86_PG_V;
984         }
985
986         /* And recursively map PML4 to itself in order to get PTmap */
987         p4_p = (pml4_entry_t *)KPML4phys;
988         p4_p[PML4PML4I] = KPML4phys;
989         p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
990
991         /* Connect the Direct Map slot(s) up to the PML4. */
992         for (i = 0; i < ndmpdpphys; i++) {
993                 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
994                 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
995         }
996
997         /* Connect the KVA slots up to the PML4 */
998         for (i = 0; i < NKPML4E; i++) {
999                 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1000                 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1001         }
1002 }
1003
1004 /*
1005  *      Bootstrap the system enough to run with virtual memory.
1006  *
1007  *      On amd64 this is called after mapping has already been enabled
1008  *      and just syncs the pmap module with what has already been done.
1009  *      [We can't call it easily with mapping off since the kernel is not
1010  *      mapped with PA == VA, hence we would have to relocate every address
1011  *      from the linked base (virtual) address "KERNBASE" to the actual
1012  *      (physical) address starting relative to 0]
1013  */
1014 void
1015 pmap_bootstrap(vm_paddr_t *firstaddr)
1016 {
1017         vm_offset_t va;
1018         pt_entry_t *pte;
1019         u_long res;
1020         int i;
1021
1022         KERNend = *firstaddr;
1023         res = atop(KERNend - (vm_paddr_t)kernphys);
1024
1025         if (!pti)
1026                 pg_g = X86_PG_G;
1027
1028         /*
1029          * Create an initial set of page tables to run the kernel in.
1030          */
1031         create_pagetables(firstaddr);
1032
1033         /*
1034          * Add a physical memory segment (vm_phys_seg) corresponding to the
1035          * preallocated kernel page table pages so that vm_page structures
1036          * representing these pages will be created.  The vm_page structures
1037          * are required for promotion of the corresponding kernel virtual
1038          * addresses to superpage mappings.
1039          */
1040         vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1041
1042         virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1043         virtual_end = VM_MAX_KERNEL_ADDRESS;
1044
1045         /* XXX do %cr0 as well */
1046         load_cr4(rcr4() | CR4_PGE);
1047         load_cr3(KPML4phys);
1048         if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1049                 load_cr4(rcr4() | CR4_SMEP);
1050
1051         /*
1052          * Initialize the kernel pmap (which is statically allocated).
1053          * Count bootstrap data as being resident in case any of this data is
1054          * later unmapped (using pmap_remove()) and freed.
1055          */
1056         PMAP_LOCK_INIT(kernel_pmap);
1057         kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1058         kernel_pmap->pm_cr3 = KPML4phys;
1059         kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1060         CPU_FILL(&kernel_pmap->pm_active);      /* don't allow deactivation */
1061         TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1062         kernel_pmap->pm_stats.resident_count = res;
1063         kernel_pmap->pm_flags = pmap_flags;
1064
1065         /*
1066          * Initialize the TLB invalidations generation number lock.
1067          */
1068         mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1069
1070         /*
1071          * Reserve some special page table entries/VA space for temporary
1072          * mapping of pages.
1073          */
1074 #define SYSMAP(c, p, v, n)      \
1075         v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1076
1077         va = virtual_avail;
1078         pte = vtopte(va);
1079
1080         /*
1081          * Crashdump maps.  The first page is reused as CMAP1 for the
1082          * memory test.
1083          */
1084         SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1085         CADDR1 = crashdumpmap;
1086
1087         virtual_avail = va;
1088
1089         /*
1090          * Initialize the PAT MSR.
1091          * pmap_init_pat() clears and sets CR4_PGE, which, as a
1092          * side-effect, invalidates stale PG_G TLB entries that might
1093          * have been created in our pre-boot environment.
1094          */
1095         pmap_init_pat();
1096
1097         /* Initialize TLB Context Id. */
1098         TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1099         if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1100                 /* Check for INVPCID support */
1101                 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1102                     != 0;
1103                 for (i = 0; i < MAXCPU; i++) {
1104                         kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1105                         kernel_pmap->pm_pcids[i].pm_gen = 1;
1106                 }
1107
1108                 /*
1109                  * PMAP_PCID_KERN + 1 is used for initialization of
1110                  * proc0 pmap.  The pmap' pcid state might be used by
1111                  * EFIRT entry before first context switch, so it
1112                  * needs to be valid.
1113                  */
1114                 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
1115                 PCPU_SET(pcid_gen, 1);
1116
1117                 /*
1118                  * pcpu area for APs is zeroed during AP startup.
1119                  * pc_pcid_next and pc_pcid_gen are initialized by AP
1120                  * during pcpu setup.
1121                  */
1122                 load_cr4(rcr4() | CR4_PCIDE);
1123         } else {
1124                 pmap_pcid_enabled = 0;
1125         }
1126 }
1127
1128 /*
1129  * Setup the PAT MSR.
1130  */
1131 void
1132 pmap_init_pat(void)
1133 {
1134         int pat_table[PAT_INDEX_SIZE];
1135         uint64_t pat_msr;
1136         u_long cr0, cr4;
1137         int i;
1138
1139         /* Bail if this CPU doesn't implement PAT. */
1140         if ((cpu_feature & CPUID_PAT) == 0)
1141                 panic("no PAT??");
1142
1143         /* Set default PAT index table. */
1144         for (i = 0; i < PAT_INDEX_SIZE; i++)
1145                 pat_table[i] = -1;
1146         pat_table[PAT_WRITE_BACK] = 0;
1147         pat_table[PAT_WRITE_THROUGH] = 1;
1148         pat_table[PAT_UNCACHEABLE] = 3;
1149         pat_table[PAT_WRITE_COMBINING] = 3;
1150         pat_table[PAT_WRITE_PROTECTED] = 3;
1151         pat_table[PAT_UNCACHED] = 3;
1152
1153         /* Initialize default PAT entries. */
1154         pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1155             PAT_VALUE(1, PAT_WRITE_THROUGH) |
1156             PAT_VALUE(2, PAT_UNCACHED) |
1157             PAT_VALUE(3, PAT_UNCACHEABLE) |
1158             PAT_VALUE(4, PAT_WRITE_BACK) |
1159             PAT_VALUE(5, PAT_WRITE_THROUGH) |
1160             PAT_VALUE(6, PAT_UNCACHED) |
1161             PAT_VALUE(7, PAT_UNCACHEABLE);
1162
1163         if (pat_works) {
1164                 /*
1165                  * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1166                  * Program 5 and 6 as WP and WC.
1167                  * Leave 4 and 7 as WB and UC.
1168                  */
1169                 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1170                 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1171                     PAT_VALUE(6, PAT_WRITE_COMBINING);
1172                 pat_table[PAT_UNCACHED] = 2;
1173                 pat_table[PAT_WRITE_PROTECTED] = 5;
1174                 pat_table[PAT_WRITE_COMBINING] = 6;
1175         } else {
1176                 /*
1177                  * Just replace PAT Index 2 with WC instead of UC-.
1178                  */
1179                 pat_msr &= ~PAT_MASK(2);
1180                 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1181                 pat_table[PAT_WRITE_COMBINING] = 2;
1182         }
1183
1184         /* Disable PGE. */
1185         cr4 = rcr4();
1186         load_cr4(cr4 & ~CR4_PGE);
1187
1188         /* Disable caches (CD = 1, NW = 0). */
1189         cr0 = rcr0();
1190         load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1191
1192         /* Flushes caches and TLBs. */
1193         wbinvd();
1194         invltlb();
1195
1196         /* Update PAT and index table. */
1197         wrmsr(MSR_PAT, pat_msr);
1198         for (i = 0; i < PAT_INDEX_SIZE; i++)
1199                 pat_index[i] = pat_table[i];
1200
1201         /* Flush caches and TLBs again. */
1202         wbinvd();
1203         invltlb();
1204
1205         /* Restore caches and PGE. */
1206         load_cr0(cr0);
1207         load_cr4(cr4);
1208 }
1209
1210 /*
1211  *      Initialize a vm_page's machine-dependent fields.
1212  */
1213 void
1214 pmap_page_init(vm_page_t m)
1215 {
1216
1217         TAILQ_INIT(&m->md.pv_list);
1218         m->md.pat_mode = PAT_WRITE_BACK;
1219 }
1220
1221 static int pmap_allow_2m_x_ept;
1222 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
1223     &pmap_allow_2m_x_ept, 0,
1224     "Allow executable superpage mappings in EPT");
1225
1226 void
1227 pmap_allow_2m_x_ept_recalculate(void)
1228 {
1229         /*
1230          * SKL002, SKL012S.  Since the EPT format is only used by
1231          * Intel CPUs, the vendor check is merely a formality.
1232          */
1233         if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
1234             (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
1235             (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1236             (CPUID_TO_MODEL(cpu_id) == 0x26 ||  /* Atoms */
1237             CPUID_TO_MODEL(cpu_id) == 0x27 ||
1238             CPUID_TO_MODEL(cpu_id) == 0x35 ||
1239             CPUID_TO_MODEL(cpu_id) == 0x36 ||
1240             CPUID_TO_MODEL(cpu_id) == 0x37 ||
1241             CPUID_TO_MODEL(cpu_id) == 0x86 ||
1242             CPUID_TO_MODEL(cpu_id) == 0x1c ||
1243             CPUID_TO_MODEL(cpu_id) == 0x4a ||
1244             CPUID_TO_MODEL(cpu_id) == 0x4c ||
1245             CPUID_TO_MODEL(cpu_id) == 0x4d ||
1246             CPUID_TO_MODEL(cpu_id) == 0x5a ||
1247             CPUID_TO_MODEL(cpu_id) == 0x5c ||
1248             CPUID_TO_MODEL(cpu_id) == 0x5d ||
1249             CPUID_TO_MODEL(cpu_id) == 0x5f ||
1250             CPUID_TO_MODEL(cpu_id) == 0x6e ||
1251             CPUID_TO_MODEL(cpu_id) == 0x7a ||
1252             CPUID_TO_MODEL(cpu_id) == 0x57 ||   /* Knights */
1253             CPUID_TO_MODEL(cpu_id) == 0x85))))
1254                 pmap_allow_2m_x_ept = 1;
1255         TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
1256 }
1257
1258 static bool
1259 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
1260 {
1261
1262         return (pmap->pm_type != PT_EPT || !executable ||
1263             !pmap_allow_2m_x_ept);
1264 }
1265
1266 /*
1267  *      Initialize the pmap module.
1268  *      Called by vm_init, to initialize any structures that the pmap
1269  *      system needs to map virtual memory.
1270  */
1271 void
1272 pmap_init(void)
1273 {
1274         struct pmap_preinit_mapping *ppim;
1275         vm_page_t mpte;
1276         vm_size_t s;
1277         int error, i, pv_npg, ret, skz63;
1278
1279         /* L1TF, reserve page @0 unconditionally */
1280         vm_page_blacklist_add(0, bootverbose);
1281
1282         /* Detect bare-metal Skylake Server and Skylake-X. */
1283         if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1284             CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1285                 /*
1286                  * Skylake-X errata SKZ63. Processor May Hang When
1287                  * Executing Code In an HLE Transaction Region between
1288                  * 40000000H and 403FFFFFH.
1289                  *
1290                  * Mark the pages in the range as preallocated.  It
1291                  * seems to be impossible to distinguish between
1292                  * Skylake Server and Skylake X.
1293                  */
1294                 skz63 = 1;
1295                 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1296                 if (skz63 != 0) {
1297                         if (bootverbose)
1298                                 printf("SKZ63: skipping 4M RAM starting "
1299                                     "at physical 1G\n");
1300                         for (i = 0; i < atop(0x400000); i++) {
1301                                 ret = vm_page_blacklist_add(0x40000000 +
1302                                     ptoa(i), FALSE);
1303                                 if (!ret && bootverbose)
1304                                         printf("page at %#lx already used\n",
1305                                             0x40000000 + ptoa(i));
1306                         }
1307                 }
1308         }
1309
1310         /* IFU */
1311         pmap_allow_2m_x_ept_recalculate();
1312
1313         /*
1314          * Initialize the vm page array entries for the kernel pmap's
1315          * page table pages.
1316          */ 
1317         PMAP_LOCK(kernel_pmap);
1318         for (i = 0; i < nkpt; i++) {
1319                 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1320                 KASSERT(mpte >= vm_page_array &&
1321                     mpte < &vm_page_array[vm_page_array_size],
1322                     ("pmap_init: page table page is out of range"));
1323                 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1324                 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1325                 mpte->wire_count = 1;
1326                 if (i << PDRSHIFT < KERNend &&
1327                     pmap_insert_pt_page(kernel_pmap, mpte))
1328                         panic("pmap_init: pmap_insert_pt_page failed");
1329         }
1330         PMAP_UNLOCK(kernel_pmap);
1331         atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1332
1333         /*
1334          * If the kernel is running on a virtual machine, then it must assume
1335          * that MCA is enabled by the hypervisor.  Moreover, the kernel must
1336          * be prepared for the hypervisor changing the vendor and family that
1337          * are reported by CPUID.  Consequently, the workaround for AMD Family
1338          * 10h Erratum 383 is enabled if the processor's feature set does not
1339          * include at least one feature that is only supported by older Intel
1340          * or newer AMD processors.
1341          */
1342         if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1343             (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1344             CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1345             AMDID2_FMA4)) == 0)
1346                 workaround_erratum383 = 1;
1347
1348         /*
1349          * Are large page mappings enabled?
1350          */
1351         TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1352         if (pg_ps_enabled) {
1353                 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1354                     ("pmap_init: can't assign to pagesizes[1]"));
1355                 pagesizes[1] = NBPDR;
1356         }
1357
1358         /*
1359          * Initialize the pv chunk list mutex.
1360          */
1361         mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1362
1363         /*
1364          * Initialize the pool of pv list locks.
1365          */
1366         for (i = 0; i < NPV_LIST_LOCKS; i++)
1367                 rw_init(&pv_list_locks[i], "pmap pv list");
1368
1369         /*
1370          * Calculate the size of the pv head table for superpages.
1371          */
1372         pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1373
1374         /*
1375          * Allocate memory for the pv head table for superpages.
1376          */
1377         s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1378         s = round_page(s);
1379         pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1380             M_WAITOK | M_ZERO);
1381         for (i = 0; i < pv_npg; i++)
1382                 TAILQ_INIT(&pv_table[i].pv_list);
1383         TAILQ_INIT(&pv_dummy.pv_list);
1384
1385         pmap_initialized = 1;
1386         for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1387                 ppim = pmap_preinit_mapping + i;
1388                 if (ppim->va == 0)
1389                         continue;
1390                 /* Make the direct map consistent */
1391                 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
1392                         (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1393                             ppim->sz, ppim->mode);
1394                 }
1395                 if (!bootverbose)
1396                         continue;
1397                 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1398                     ppim->pa, ppim->va, ppim->sz, ppim->mode);
1399         }
1400
1401         mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1402         error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1403             (vmem_addr_t *)&qframe);
1404         if (error != 0)
1405                 panic("qframe allocation failed");
1406 }
1407
1408 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1409     "2MB page mapping counters");
1410
1411 static u_long pmap_pde_demotions;
1412 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1413     &pmap_pde_demotions, 0, "2MB page demotions");
1414
1415 static u_long pmap_pde_mappings;
1416 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1417     &pmap_pde_mappings, 0, "2MB page mappings");
1418
1419 static u_long pmap_pde_p_failures;
1420 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1421     &pmap_pde_p_failures, 0, "2MB page promotion failures");
1422
1423 static u_long pmap_pde_promotions;
1424 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1425     &pmap_pde_promotions, 0, "2MB page promotions");
1426
1427 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1428     "1GB page mapping counters");
1429
1430 static u_long pmap_pdpe_demotions;
1431 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1432     &pmap_pdpe_demotions, 0, "1GB page demotions");
1433
1434 /***************************************************
1435  * Low level helper routines.....
1436  ***************************************************/
1437
1438 static pt_entry_t
1439 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1440 {
1441         int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1442
1443         switch (pmap->pm_type) {
1444         case PT_X86:
1445         case PT_RVI:
1446                 /* Verify that both PAT bits are not set at the same time */
1447                 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1448                     ("Invalid PAT bits in entry %#lx", entry));
1449
1450                 /* Swap the PAT bits if one of them is set */
1451                 if ((entry & x86_pat_bits) != 0)
1452                         entry ^= x86_pat_bits;
1453                 break;
1454         case PT_EPT:
1455                 /*
1456                  * Nothing to do - the memory attributes are represented
1457                  * the same way for regular pages and superpages.
1458                  */
1459                 break;
1460         default:
1461                 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1462         }
1463
1464         return (entry);
1465 }
1466
1467 /*
1468  * Determine the appropriate bits to set in a PTE or PDE for a specified
1469  * caching mode.
1470  */
1471 int
1472 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1473 {
1474         int cache_bits, pat_flag, pat_idx;
1475
1476         if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1477                 panic("Unknown caching mode %d\n", mode);
1478
1479         switch (pmap->pm_type) {
1480         case PT_X86:
1481         case PT_RVI:
1482                 /* The PAT bit is different for PTE's and PDE's. */
1483                 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1484
1485                 /* Map the caching mode to a PAT index. */
1486                 pat_idx = pat_index[mode];
1487
1488                 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1489                 cache_bits = 0;
1490                 if (pat_idx & 0x4)
1491                         cache_bits |= pat_flag;
1492                 if (pat_idx & 0x2)
1493                         cache_bits |= PG_NC_PCD;
1494                 if (pat_idx & 0x1)
1495                         cache_bits |= PG_NC_PWT;
1496                 break;
1497
1498         case PT_EPT:
1499                 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1500                 break;
1501
1502         default:
1503                 panic("unsupported pmap type %d", pmap->pm_type);
1504         }
1505
1506         return (cache_bits);
1507 }
1508
1509 static int
1510 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1511 {
1512         int mask;
1513
1514         switch (pmap->pm_type) {
1515         case PT_X86:
1516         case PT_RVI:
1517                 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1518                 break;
1519         case PT_EPT:
1520                 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1521                 break;
1522         default:
1523                 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1524         }
1525
1526         return (mask);
1527 }
1528
1529 bool
1530 pmap_ps_enabled(pmap_t pmap)
1531 {
1532
1533         return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1534 }
1535
1536 static void
1537 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1538 {
1539
1540         switch (pmap->pm_type) {
1541         case PT_X86:
1542                 break;
1543         case PT_RVI:
1544         case PT_EPT:
1545                 /*
1546                  * XXX
1547                  * This is a little bogus since the generation number is
1548                  * supposed to be bumped up when a region of the address
1549                  * space is invalidated in the page tables.
1550                  *
1551                  * In this case the old PDE entry is valid but yet we want
1552                  * to make sure that any mappings using the old entry are
1553                  * invalidated in the TLB.
1554                  *
1555                  * The reason this works as expected is because we rendezvous
1556                  * "all" host cpus and force any vcpu context to exit as a
1557                  * side-effect.
1558                  */
1559                 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1560                 break;
1561         default:
1562                 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1563         }
1564         pde_store(pde, newpde);
1565 }
1566
1567 /*
1568  * After changing the page size for the specified virtual address in the page
1569  * table, flush the corresponding entries from the processor's TLB.  Only the
1570  * calling processor's TLB is affected.
1571  *
1572  * The calling thread must be pinned to a processor.
1573  */
1574 static void
1575 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1576 {
1577         pt_entry_t PG_G;
1578
1579         if (pmap_type_guest(pmap))
1580                 return;
1581
1582         KASSERT(pmap->pm_type == PT_X86,
1583             ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1584
1585         PG_G = pmap_global_bit(pmap);
1586
1587         if ((newpde & PG_PS) == 0)
1588                 /* Demotion: flush a specific 2MB page mapping. */
1589                 invlpg(va);
1590         else if ((newpde & PG_G) == 0)
1591                 /*
1592                  * Promotion: flush every 4KB page mapping from the TLB
1593                  * because there are too many to flush individually.
1594                  */
1595                 invltlb();
1596         else {
1597                 /*
1598                  * Promotion: flush every 4KB page mapping from the TLB,
1599                  * including any global (PG_G) mappings.
1600                  */
1601                 invltlb_glob();
1602         }
1603 }
1604 #ifdef SMP
1605
1606 /*
1607  * For SMP, these functions have to use the IPI mechanism for coherence.
1608  *
1609  * N.B.: Before calling any of the following TLB invalidation functions,
1610  * the calling processor must ensure that all stores updating a non-
1611  * kernel page table are globally performed.  Otherwise, another
1612  * processor could cache an old, pre-update entry without being
1613  * invalidated.  This can happen one of two ways: (1) The pmap becomes
1614  * active on another processor after its pm_active field is checked by
1615  * one of the following functions but before a store updating the page
1616  * table is globally performed. (2) The pmap becomes active on another
1617  * processor before its pm_active field is checked but due to
1618  * speculative loads one of the following functions stills reads the
1619  * pmap as inactive on the other processor.
1620  * 
1621  * The kernel page table is exempt because its pm_active field is
1622  * immutable.  The kernel page table is always active on every
1623  * processor.
1624  */
1625
1626 /*
1627  * Interrupt the cpus that are executing in the guest context.
1628  * This will force the vcpu to exit and the cached EPT mappings
1629  * will be invalidated by the host before the next vmresume.
1630  */
1631 static __inline void
1632 pmap_invalidate_ept(pmap_t pmap)
1633 {
1634         int ipinum;
1635
1636         sched_pin();
1637         KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1638             ("pmap_invalidate_ept: absurd pm_active"));
1639
1640         /*
1641          * The TLB mappings associated with a vcpu context are not
1642          * flushed each time a different vcpu is chosen to execute.
1643          *
1644          * This is in contrast with a process's vtop mappings that
1645          * are flushed from the TLB on each context switch.
1646          *
1647          * Therefore we need to do more than just a TLB shootdown on
1648          * the active cpus in 'pmap->pm_active'. To do this we keep
1649          * track of the number of invalidations performed on this pmap.
1650          *
1651          * Each vcpu keeps a cache of this counter and compares it
1652          * just before a vmresume. If the counter is out-of-date an
1653          * invept will be done to flush stale mappings from the TLB.
1654          */
1655         atomic_add_acq_long(&pmap->pm_eptgen, 1);
1656
1657         /*
1658          * Force the vcpu to exit and trap back into the hypervisor.
1659          */
1660         ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1661         ipi_selected(pmap->pm_active, ipinum);
1662         sched_unpin();
1663 }
1664
1665 void
1666 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1667 {
1668         cpuset_t *mask;
1669         struct invpcid_descr d;
1670         uint64_t kcr3, ucr3;
1671         uint32_t pcid;
1672         u_int cpuid, i;
1673
1674         if (pmap_type_guest(pmap)) {
1675                 pmap_invalidate_ept(pmap);
1676                 return;
1677         }
1678
1679         KASSERT(pmap->pm_type == PT_X86,
1680             ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1681
1682         sched_pin();
1683         if (pmap == kernel_pmap) {
1684                 invlpg(va);
1685                 mask = &all_cpus;
1686         } else {
1687                 cpuid = PCPU_GET(cpuid);
1688                 if (pmap == PCPU_GET(curpmap)) {
1689                         invlpg(va);
1690                         if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1691                                 /*
1692                                  * Disable context switching. pm_pcid
1693                                  * is recalculated on switch, which
1694                                  * might make us use wrong pcid below.
1695                                  */
1696                                 critical_enter();
1697                                 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1698
1699                                 if (invpcid_works) {
1700                                         d.pcid = pcid | PMAP_PCID_USER_PT;
1701                                         d.pad = 0;
1702                                         d.addr = va;
1703                                         invpcid(&d, INVPCID_ADDR);
1704                                 } else {
1705                                         kcr3 = pmap->pm_cr3 | pcid |
1706                                             CR3_PCID_SAVE;
1707                                         ucr3 = pmap->pm_ucr3 | pcid |
1708                                             PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1709                                         pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1710                                 }
1711                                 critical_exit();
1712                         }
1713                 } else if (pmap_pcid_enabled)
1714                         pmap->pm_pcids[cpuid].pm_gen = 0;
1715                 if (pmap_pcid_enabled) {
1716                         CPU_FOREACH(i) {
1717                                 if (cpuid != i)
1718                                         pmap->pm_pcids[i].pm_gen = 0;
1719                         }
1720
1721                         /*
1722                          * The fence is between stores to pm_gen and the read of
1723                          * the pm_active mask.  We need to ensure that it is
1724                          * impossible for us to miss the bit update in pm_active
1725                          * and simultaneously observe a non-zero pm_gen in
1726                          * pmap_activate_sw(), otherwise TLB update is missed.
1727                          * Without the fence, IA32 allows such an outcome.
1728                          * Note that pm_active is updated by a locked operation,
1729                          * which provides the reciprocal fence.
1730                          */
1731                         atomic_thread_fence_seq_cst();
1732                 }
1733                 mask = &pmap->pm_active;
1734         }
1735         smp_masked_invlpg(*mask, va, pmap);
1736         sched_unpin();
1737 }
1738
1739 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1740 #define PMAP_INVLPG_THRESHOLD   (4 * 1024 * PAGE_SIZE)
1741
1742 void
1743 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1744 {
1745         cpuset_t *mask;
1746         struct invpcid_descr d;
1747         vm_offset_t addr;
1748         uint64_t kcr3, ucr3;
1749         uint32_t pcid;
1750         u_int cpuid, i;
1751
1752         if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1753                 pmap_invalidate_all(pmap);
1754                 return;
1755         }
1756
1757         if (pmap_type_guest(pmap)) {
1758                 pmap_invalidate_ept(pmap);
1759                 return;
1760         }
1761
1762         KASSERT(pmap->pm_type == PT_X86,
1763             ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1764
1765         sched_pin();
1766         cpuid = PCPU_GET(cpuid);
1767         if (pmap == kernel_pmap) {
1768                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1769                         invlpg(addr);
1770                 mask = &all_cpus;
1771         } else {
1772                 if (pmap == PCPU_GET(curpmap)) {
1773                         for (addr = sva; addr < eva; addr += PAGE_SIZE)
1774                                 invlpg(addr);
1775                         if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1776                                 critical_enter();
1777                                 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1778                                 if (invpcid_works) {
1779                                         d.pcid = pcid | PMAP_PCID_USER_PT;
1780                                         d.pad = 0;
1781                                         d.addr = sva;
1782                                         for (; d.addr < eva; d.addr +=
1783                                             PAGE_SIZE)
1784                                                 invpcid(&d, INVPCID_ADDR);
1785                                 } else {
1786                                         kcr3 = pmap->pm_cr3 | pcid |
1787                                             CR3_PCID_SAVE;
1788                                         ucr3 = pmap->pm_ucr3 | pcid |
1789                                             PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1790                                         pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1791                                             eva);
1792                                 }
1793                                 critical_exit();
1794                         }
1795                 } else if (pmap_pcid_enabled) {
1796                         pmap->pm_pcids[cpuid].pm_gen = 0;
1797                 }
1798                 if (pmap_pcid_enabled) {
1799                         CPU_FOREACH(i) {
1800                                 if (cpuid != i)
1801                                         pmap->pm_pcids[i].pm_gen = 0;
1802                         }
1803                         /* See the comment in pmap_invalidate_page(). */
1804                         atomic_thread_fence_seq_cst();
1805                 }
1806                 mask = &pmap->pm_active;
1807         }
1808         smp_masked_invlpg_range(*mask, sva, eva, pmap);
1809         sched_unpin();
1810 }
1811
1812 void
1813 pmap_invalidate_all(pmap_t pmap)
1814 {
1815         cpuset_t *mask;
1816         struct invpcid_descr d;
1817         uint64_t kcr3, ucr3;
1818         uint32_t pcid;
1819         u_int cpuid, i;
1820
1821         if (pmap_type_guest(pmap)) {
1822                 pmap_invalidate_ept(pmap);
1823                 return;
1824         }
1825
1826         KASSERT(pmap->pm_type == PT_X86,
1827             ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1828
1829         sched_pin();
1830         if (pmap == kernel_pmap) {
1831                 if (pmap_pcid_enabled && invpcid_works) {
1832                         bzero(&d, sizeof(d));
1833                         invpcid(&d, INVPCID_CTXGLOB);
1834                 } else {
1835                         invltlb_glob();
1836                 }
1837                 mask = &all_cpus;
1838         } else {
1839                 cpuid = PCPU_GET(cpuid);
1840                 if (pmap == PCPU_GET(curpmap)) {
1841                         if (pmap_pcid_enabled) {
1842                                 critical_enter();
1843                                 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1844                                 if (invpcid_works) {
1845                                         d.pcid = pcid;
1846                                         d.pad = 0;
1847                                         d.addr = 0;
1848                                         invpcid(&d, INVPCID_CTX);
1849                                         if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1850                                                 d.pcid |= PMAP_PCID_USER_PT;
1851                                                 invpcid(&d, INVPCID_CTX);
1852                                         }
1853                                 } else {
1854                                         kcr3 = pmap->pm_cr3 | pcid;
1855                                         ucr3 = pmap->pm_ucr3;
1856                                         if (ucr3 != PMAP_NO_CR3) {
1857                                                 ucr3 |= pcid | PMAP_PCID_USER_PT;
1858                                                 pmap_pti_pcid_invalidate(ucr3,
1859                                                     kcr3);
1860                                         } else {
1861                                                 load_cr3(kcr3);
1862                                         }
1863                                 }
1864                                 critical_exit();
1865                         } else {
1866                                 invltlb();
1867                         }
1868                 } else if (pmap_pcid_enabled) {
1869                         pmap->pm_pcids[cpuid].pm_gen = 0;
1870                 }
1871                 if (pmap_pcid_enabled) {
1872                         CPU_FOREACH(i) {
1873                                 if (cpuid != i)
1874                                         pmap->pm_pcids[i].pm_gen = 0;
1875                         }
1876                         /* See the comment in pmap_invalidate_page(). */
1877                         atomic_thread_fence_seq_cst();
1878                 }
1879                 mask = &pmap->pm_active;
1880         }
1881         smp_masked_invltlb(*mask, pmap);
1882         sched_unpin();
1883 }
1884
1885 void
1886 pmap_invalidate_cache(void)
1887 {
1888
1889         sched_pin();
1890         wbinvd();
1891         smp_cache_flush();
1892         sched_unpin();
1893 }
1894
1895 struct pde_action {
1896         cpuset_t invalidate;    /* processors that invalidate their TLB */
1897         pmap_t pmap;
1898         vm_offset_t va;
1899         pd_entry_t *pde;
1900         pd_entry_t newpde;
1901         u_int store;            /* processor that updates the PDE */
1902 };
1903
1904 static void
1905 pmap_update_pde_action(void *arg)
1906 {
1907         struct pde_action *act = arg;
1908
1909         if (act->store == PCPU_GET(cpuid))
1910                 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1911 }
1912
1913 static void
1914 pmap_update_pde_teardown(void *arg)
1915 {
1916         struct pde_action *act = arg;
1917
1918         if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1919                 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1920 }
1921
1922 /*
1923  * Change the page size for the specified virtual address in a way that
1924  * prevents any possibility of the TLB ever having two entries that map the
1925  * same virtual address using different page sizes.  This is the recommended
1926  * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
1927  * machine check exception for a TLB state that is improperly diagnosed as a
1928  * hardware error.
1929  */
1930 static void
1931 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1932 {
1933         struct pde_action act;
1934         cpuset_t active, other_cpus;
1935         u_int cpuid;
1936
1937         sched_pin();
1938         cpuid = PCPU_GET(cpuid);
1939         other_cpus = all_cpus;
1940         CPU_CLR(cpuid, &other_cpus);
1941         if (pmap == kernel_pmap || pmap_type_guest(pmap)) 
1942                 active = all_cpus;
1943         else {
1944                 active = pmap->pm_active;
1945         }
1946         if (CPU_OVERLAP(&active, &other_cpus)) { 
1947                 act.store = cpuid;
1948                 act.invalidate = active;
1949                 act.va = va;
1950                 act.pmap = pmap;
1951                 act.pde = pde;
1952                 act.newpde = newpde;
1953                 CPU_SET(cpuid, &active);
1954                 smp_rendezvous_cpus(active,
1955                     smp_no_rendezvous_barrier, pmap_update_pde_action,
1956                     pmap_update_pde_teardown, &act);
1957         } else {
1958                 pmap_update_pde_store(pmap, pde, newpde);
1959                 if (CPU_ISSET(cpuid, &active))
1960                         pmap_update_pde_invalidate(pmap, va, newpde);
1961         }
1962         sched_unpin();
1963 }
1964 #else /* !SMP */
1965 /*
1966  * Normal, non-SMP, invalidation functions.
1967  */
1968 void
1969 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1970 {
1971         struct invpcid_descr d;
1972         uint64_t kcr3, ucr3;
1973         uint32_t pcid;
1974
1975         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1976                 pmap->pm_eptgen++;
1977                 return;
1978         }
1979         KASSERT(pmap->pm_type == PT_X86,
1980             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1981
1982         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1983                 invlpg(va);
1984                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1985                     pmap->pm_ucr3 != PMAP_NO_CR3) {
1986                         critical_enter();
1987                         pcid = pmap->pm_pcids[0].pm_pcid;
1988                         if (invpcid_works) {
1989                                 d.pcid = pcid | PMAP_PCID_USER_PT;
1990                                 d.pad = 0;
1991                                 d.addr = va;
1992                                 invpcid(&d, INVPCID_ADDR);
1993                         } else {
1994                                 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1995                                 ucr3 = pmap->pm_ucr3 | pcid |
1996                                     PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1997                                 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1998                         }
1999                         critical_exit();
2000                 }
2001         } else if (pmap_pcid_enabled)
2002                 pmap->pm_pcids[0].pm_gen = 0;
2003 }
2004
2005 void
2006 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2007 {
2008         struct invpcid_descr d;
2009         vm_offset_t addr;
2010         uint64_t kcr3, ucr3;
2011
2012         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2013                 pmap->pm_eptgen++;
2014                 return;
2015         }
2016         KASSERT(pmap->pm_type == PT_X86,
2017             ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2018
2019         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2020                 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2021                         invlpg(addr);
2022                 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2023                     pmap->pm_ucr3 != PMAP_NO_CR3) {
2024                         critical_enter();
2025                         if (invpcid_works) {
2026                                 d.pcid = pmap->pm_pcids[0].pm_pcid |
2027                                     PMAP_PCID_USER_PT;
2028                                 d.pad = 0;
2029                                 d.addr = sva;
2030                                 for (; d.addr < eva; d.addr += PAGE_SIZE)
2031                                         invpcid(&d, INVPCID_ADDR);
2032                         } else {
2033                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2034                                     pm_pcid | CR3_PCID_SAVE;
2035                                 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2036                                     pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2037                                 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2038                         }
2039                         critical_exit();
2040                 }
2041         } else if (pmap_pcid_enabled) {
2042                 pmap->pm_pcids[0].pm_gen = 0;
2043         }
2044 }
2045
2046 void
2047 pmap_invalidate_all(pmap_t pmap)
2048 {
2049         struct invpcid_descr d;
2050         uint64_t kcr3, ucr3;
2051
2052         if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2053                 pmap->pm_eptgen++;
2054                 return;
2055         }
2056         KASSERT(pmap->pm_type == PT_X86,
2057             ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2058
2059         if (pmap == kernel_pmap) {
2060                 if (pmap_pcid_enabled && invpcid_works) {
2061                         bzero(&d, sizeof(d));
2062                         invpcid(&d, INVPCID_CTXGLOB);
2063                 } else {
2064                         invltlb_glob();
2065                 }
2066         } else if (pmap == PCPU_GET(curpmap)) {
2067                 if (pmap_pcid_enabled) {
2068                         critical_enter();
2069                         if (invpcid_works) {
2070                                 d.pcid = pmap->pm_pcids[0].pm_pcid;
2071                                 d.pad = 0;
2072                                 d.addr = 0;
2073                                 invpcid(&d, INVPCID_CTX);
2074                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2075                                         d.pcid |= PMAP_PCID_USER_PT;
2076                                         invpcid(&d, INVPCID_CTX);
2077                                 }
2078                         } else {
2079                                 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2080                                 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2081                                         ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2082                                             0].pm_pcid | PMAP_PCID_USER_PT;
2083                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
2084                                 } else
2085                                         load_cr3(kcr3);
2086                         }
2087                         critical_exit();
2088                 } else {
2089                         invltlb();
2090                 }
2091         } else if (pmap_pcid_enabled) {
2092                 pmap->pm_pcids[0].pm_gen = 0;
2093         }
2094 }
2095
2096 PMAP_INLINE void
2097 pmap_invalidate_cache(void)
2098 {
2099
2100         wbinvd();
2101 }
2102
2103 static void
2104 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2105 {
2106
2107         pmap_update_pde_store(pmap, pde, newpde);
2108         if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2109                 pmap_update_pde_invalidate(pmap, va, newpde);
2110         else
2111                 pmap->pm_pcids[0].pm_gen = 0;
2112 }
2113 #endif /* !SMP */
2114
2115 static void
2116 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2117 {
2118
2119         /*
2120          * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2121          * by a promotion that did not invalidate the 512 4KB page mappings
2122          * that might exist in the TLB.  Consequently, at this point, the TLB
2123          * may hold both 4KB and 2MB page mappings for the address range [va,
2124          * va + NBPDR).  Therefore, the entire range must be invalidated here.
2125          * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2126          * 4KB page mappings for the address range [va, va + NBPDR), and so a
2127          * single INVLPG suffices to invalidate the 2MB page mapping from the
2128          * TLB.
2129          */
2130         if ((pde & PG_PROMOTED) != 0)
2131                 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2132         else
2133                 pmap_invalidate_page(pmap, va);
2134 }
2135
2136 #define PMAP_CLFLUSH_THRESHOLD   (2 * 1024 * 1024)
2137
2138 void
2139 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2140 {
2141
2142         if (force) {
2143                 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2144         } else {
2145                 KASSERT((sva & PAGE_MASK) == 0,
2146                     ("pmap_invalidate_cache_range: sva not page-aligned"));
2147                 KASSERT((eva & PAGE_MASK) == 0,
2148                     ("pmap_invalidate_cache_range: eva not page-aligned"));
2149         }
2150
2151         if ((cpu_feature & CPUID_SS) != 0 && !force)
2152                 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2153         else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2154             eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2155                 /*
2156                  * XXX: Some CPUs fault, hang, or trash the local APIC
2157                  * registers if we use CLFLUSH on the local APIC
2158                  * range.  The local APIC is always uncached, so we
2159                  * don't need to flush for that range anyway.
2160                  */
2161                 if (pmap_kextract(sva) == lapic_paddr)
2162                         return;
2163
2164                 /*
2165                  * Otherwise, do per-cache line flush.  Use the sfence
2166                  * instruction to insure that previous stores are
2167                  * included in the write-back.  The processor
2168                  * propagates flush to other processors in the cache
2169                  * coherence domain.
2170                  */
2171                 sfence();
2172                 for (; sva < eva; sva += cpu_clflush_line_size)
2173                         clflushopt(sva);
2174                 sfence();
2175         } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2176             eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2177                 if (pmap_kextract(sva) == lapic_paddr)
2178                         return;
2179                 /*
2180                  * Writes are ordered by CLFLUSH on Intel CPUs.
2181                  */
2182                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2183                         mfence();
2184                 for (; sva < eva; sva += cpu_clflush_line_size)
2185                         clflush(sva);
2186                 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2187                         mfence();
2188         } else {
2189
2190                 /*
2191                  * No targeted cache flush methods are supported by CPU,
2192                  * or the supplied range is bigger than 2MB.
2193                  * Globally invalidate cache.
2194                  */
2195                 pmap_invalidate_cache();
2196         }
2197 }
2198
2199 /*
2200  * Remove the specified set of pages from the data and instruction caches.
2201  *
2202  * In contrast to pmap_invalidate_cache_range(), this function does not
2203  * rely on the CPU's self-snoop feature, because it is intended for use
2204  * when moving pages into a different cache domain.
2205  */
2206 void
2207 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2208 {
2209         vm_offset_t daddr, eva;
2210         int i;
2211         bool useclflushopt;
2212
2213         useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2214         if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2215             ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2216                 pmap_invalidate_cache();
2217         else {
2218                 if (useclflushopt)
2219                         sfence();
2220                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2221                         mfence();
2222                 for (i = 0; i < count; i++) {
2223                         daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2224                         eva = daddr + PAGE_SIZE;
2225                         for (; daddr < eva; daddr += cpu_clflush_line_size) {
2226                                 if (useclflushopt)
2227                                         clflushopt(daddr);
2228                                 else
2229                                         clflush(daddr);
2230                         }
2231                 }
2232                 if (useclflushopt)
2233                         sfence();
2234                 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2235                         mfence();
2236         }
2237 }
2238
2239 /*
2240  *      Routine:        pmap_extract
2241  *      Function:
2242  *              Extract the physical page address associated
2243  *              with the given map/virtual_address pair.
2244  */
2245 vm_paddr_t 
2246 pmap_extract(pmap_t pmap, vm_offset_t va)
2247 {
2248         pdp_entry_t *pdpe;
2249         pd_entry_t *pde;
2250         pt_entry_t *pte, PG_V;
2251         vm_paddr_t pa;
2252
2253         pa = 0;
2254         PG_V = pmap_valid_bit(pmap);
2255         PMAP_LOCK(pmap);
2256         pdpe = pmap_pdpe(pmap, va);
2257         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2258                 if ((*pdpe & PG_PS) != 0)
2259                         pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2260                 else {
2261                         pde = pmap_pdpe_to_pde(pdpe, va);
2262                         if ((*pde & PG_V) != 0) {
2263                                 if ((*pde & PG_PS) != 0) {
2264                                         pa = (*pde & PG_PS_FRAME) |
2265                                             (va & PDRMASK);
2266                                 } else {
2267                                         pte = pmap_pde_to_pte(pde, va);
2268                                         pa = (*pte & PG_FRAME) |
2269                                             (va & PAGE_MASK);
2270                                 }
2271                         }
2272                 }
2273         }
2274         PMAP_UNLOCK(pmap);
2275         return (pa);
2276 }
2277
2278 /*
2279  *      Routine:        pmap_extract_and_hold
2280  *      Function:
2281  *              Atomically extract and hold the physical page
2282  *              with the given pmap and virtual address pair
2283  *              if that mapping permits the given protection.
2284  */
2285 vm_page_t
2286 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2287 {
2288         pd_entry_t pde, *pdep;
2289         pt_entry_t pte, PG_RW, PG_V;
2290         vm_paddr_t pa;
2291         vm_page_t m;
2292
2293         pa = 0;
2294         m = NULL;
2295         PG_RW = pmap_rw_bit(pmap);
2296         PG_V = pmap_valid_bit(pmap);
2297         PMAP_LOCK(pmap);
2298 retry:
2299         pdep = pmap_pde(pmap, va);
2300         if (pdep != NULL && (pde = *pdep)) {
2301                 if (pde & PG_PS) {
2302                         if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2303                                 if (vm_page_pa_tryrelock(pmap, (pde &
2304                                     PG_PS_FRAME) | (va & PDRMASK), &pa))
2305                                         goto retry;
2306                                 m = PHYS_TO_VM_PAGE(pa);
2307                         }
2308                 } else {
2309                         pte = *pmap_pde_to_pte(pdep, va);
2310                         if ((pte & PG_V) &&
2311                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2312                                 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2313                                     &pa))
2314                                         goto retry;
2315                                 m = PHYS_TO_VM_PAGE(pa);
2316                         }
2317                 }
2318                 if (m != NULL)
2319                         vm_page_hold(m);
2320         }
2321         PA_UNLOCK_COND(pa);
2322         PMAP_UNLOCK(pmap);
2323         return (m);
2324 }
2325
2326 vm_paddr_t
2327 pmap_kextract(vm_offset_t va)
2328 {
2329         pd_entry_t pde;
2330         vm_paddr_t pa;
2331
2332         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2333                 pa = DMAP_TO_PHYS(va);
2334         } else {
2335                 pde = *vtopde(va);
2336                 if (pde & PG_PS) {
2337                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2338                 } else {
2339                         /*
2340                          * Beware of a concurrent promotion that changes the
2341                          * PDE at this point!  For example, vtopte() must not
2342                          * be used to access the PTE because it would use the
2343                          * new PDE.  It is, however, safe to use the old PDE
2344                          * because the page table page is preserved by the
2345                          * promotion.
2346                          */
2347                         pa = *pmap_pde_to_pte(&pde, va);
2348                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2349                 }
2350         }
2351         return (pa);
2352 }
2353
2354 /***************************************************
2355  * Low level mapping routines.....
2356  ***************************************************/
2357
2358 /*
2359  * Add a wired page to the kva.
2360  * Note: not SMP coherent.
2361  */
2362 PMAP_INLINE void 
2363 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2364 {
2365         pt_entry_t *pte;
2366
2367         pte = vtopte(va);
2368         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2369 }
2370
2371 static __inline void
2372 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2373 {
2374         pt_entry_t *pte;
2375         int cache_bits;
2376
2377         pte = vtopte(va);
2378         cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2379         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2380 }
2381
2382 /*
2383  * Remove a page from the kernel pagetables.
2384  * Note: not SMP coherent.
2385  */
2386 PMAP_INLINE void
2387 pmap_kremove(vm_offset_t va)
2388 {
2389         pt_entry_t *pte;
2390
2391         pte = vtopte(va);
2392         pte_clear(pte);
2393 }
2394
2395 /*
2396  *      Used to map a range of physical addresses into kernel
2397  *      virtual address space.
2398  *
2399  *      The value passed in '*virt' is a suggested virtual address for
2400  *      the mapping. Architectures which can support a direct-mapped
2401  *      physical to virtual region can return the appropriate address
2402  *      within that region, leaving '*virt' unchanged. Other
2403  *      architectures should map the pages starting at '*virt' and
2404  *      update '*virt' with the first usable address after the mapped
2405  *      region.
2406  */
2407 vm_offset_t
2408 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2409 {
2410         return PHYS_TO_DMAP(start);
2411 }
2412
2413
2414 /*
2415  * Add a list of wired pages to the kva
2416  * this routine is only used for temporary
2417  * kernel mappings that do not need to have
2418  * page modification or references recorded.
2419  * Note that old mappings are simply written
2420  * over.  The page *must* be wired.
2421  * Note: SMP coherent.  Uses a ranged shootdown IPI.
2422  */
2423 void
2424 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2425 {
2426         pt_entry_t *endpte, oldpte, pa, *pte;
2427         vm_page_t m;
2428         int cache_bits;
2429
2430         oldpte = 0;
2431         pte = vtopte(sva);
2432         endpte = pte + count;
2433         while (pte < endpte) {
2434                 m = *ma++;
2435                 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2436                 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2437                 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2438                         oldpte |= *pte;
2439                         pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2440                 }
2441                 pte++;
2442         }
2443         if (__predict_false((oldpte & X86_PG_V) != 0))
2444                 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2445                     PAGE_SIZE);
2446 }
2447
2448 /*
2449  * This routine tears out page mappings from the
2450  * kernel -- it is meant only for temporary mappings.
2451  * Note: SMP coherent.  Uses a ranged shootdown IPI.
2452  */
2453 void
2454 pmap_qremove(vm_offset_t sva, int count)
2455 {
2456         vm_offset_t va;
2457
2458         va = sva;
2459         while (count-- > 0) {
2460                 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2461                 pmap_kremove(va);
2462                 va += PAGE_SIZE;
2463         }
2464         pmap_invalidate_range(kernel_pmap, sva, va);
2465 }
2466
2467 /***************************************************
2468  * Page table page management routines.....
2469  ***************************************************/
2470 static __inline void
2471 pmap_free_zero_pages(struct spglist *free)
2472 {
2473         vm_page_t m;
2474         int count;
2475
2476         for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2477                 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2478                 /* Preserve the page's PG_ZERO setting. */
2479                 vm_page_free_toq(m);
2480         }
2481         atomic_subtract_int(&vm_cnt.v_wire_count, count);
2482 }
2483
2484 /*
2485  * Schedule the specified unused page table page to be freed.  Specifically,
2486  * add the page to the specified list of pages that will be released to the
2487  * physical memory manager after the TLB has been updated.
2488  */
2489 static __inline void
2490 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2491     boolean_t set_PG_ZERO)
2492 {
2493
2494         if (set_PG_ZERO)
2495                 m->flags |= PG_ZERO;
2496         else
2497                 m->flags &= ~PG_ZERO;
2498         SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2499 }
2500         
2501 /*
2502  * Inserts the specified page table page into the specified pmap's collection
2503  * of idle page table pages.  Each of a pmap's page table pages is responsible
2504  * for mapping a distinct range of virtual addresses.  The pmap's collection is
2505  * ordered by this virtual address range.
2506  */
2507 static __inline int
2508 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2509 {
2510
2511         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2512         return (vm_radix_insert(&pmap->pm_root, mpte));
2513 }
2514
2515 /*
2516  * Removes the page table page mapping the specified virtual address from the
2517  * specified pmap's collection of idle page table pages, and returns it.
2518  * Otherwise, returns NULL if there is no page table page corresponding to the
2519  * specified virtual address.
2520  */
2521 static __inline vm_page_t
2522 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2523 {
2524
2525         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2526         return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2527 }
2528
2529 /*
2530  * Decrements a page table page's wire count, which is used to record the
2531  * number of valid page table entries within the page.  If the wire count
2532  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
2533  * page table page was unmapped and FALSE otherwise.
2534  */
2535 static inline boolean_t
2536 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2537 {
2538
2539         --m->wire_count;
2540         if (m->wire_count == 0) {
2541                 _pmap_unwire_ptp(pmap, va, m, free);
2542                 return (TRUE);
2543         } else
2544                 return (FALSE);
2545 }
2546
2547 static void
2548 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2549 {
2550
2551         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2552         /*
2553          * unmap the page table page
2554          */
2555         if (m->pindex >= (NUPDE + NUPDPE)) {
2556                 /* PDP page */
2557                 pml4_entry_t *pml4;
2558                 pml4 = pmap_pml4e(pmap, va);
2559                 *pml4 = 0;
2560                 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2561                         pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2562                         *pml4 = 0;
2563                 }
2564         } else if (m->pindex >= NUPDE) {
2565                 /* PD page */
2566                 pdp_entry_t *pdp;
2567                 pdp = pmap_pdpe(pmap, va);
2568                 *pdp = 0;
2569         } else {
2570                 /* PTE page */
2571                 pd_entry_t *pd;
2572                 pd = pmap_pde(pmap, va);
2573                 *pd = 0;
2574         }
2575         pmap_resident_count_dec(pmap, 1);
2576         if (m->pindex < NUPDE) {
2577                 /* We just released a PT, unhold the matching PD */
2578                 vm_page_t pdpg;
2579
2580                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2581                 pmap_unwire_ptp(pmap, va, pdpg, free);
2582         }
2583         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2584                 /* We just released a PD, unhold the matching PDP */
2585                 vm_page_t pdppg;
2586
2587                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2588                 pmap_unwire_ptp(pmap, va, pdppg, free);
2589         }
2590
2591         /* 
2592          * Put page on a list so that it is released after
2593          * *ALL* TLB shootdown is done
2594          */
2595         pmap_add_delayed_free_list(m, free, TRUE);
2596 }
2597
2598 /*
2599  * After removing a page table entry, this routine is used to
2600  * conditionally free the page, and manage the hold/wire counts.
2601  */
2602 static int
2603 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2604     struct spglist *free)
2605 {
2606         vm_page_t mpte;
2607
2608         if (va >= VM_MAXUSER_ADDRESS)
2609                 return (0);
2610         KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2611         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2612         return (pmap_unwire_ptp(pmap, va, mpte, free));
2613 }
2614
2615 void
2616 pmap_pinit0(pmap_t pmap)
2617 {
2618         int i;
2619
2620         PMAP_LOCK_INIT(pmap);
2621         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2622         pmap->pm_pml4u = NULL;
2623         pmap->pm_cr3 = KPML4phys;
2624         /* hack to keep pmap_pti_pcid_invalidate() alive */
2625         pmap->pm_ucr3 = PMAP_NO_CR3;
2626         pmap->pm_root.rt_root = 0;
2627         CPU_ZERO(&pmap->pm_active);
2628         TAILQ_INIT(&pmap->pm_pvchunk);
2629         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2630         pmap->pm_flags = pmap_flags;
2631         CPU_FOREACH(i) {
2632                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
2633                 pmap->pm_pcids[i].pm_gen = 1;
2634         }
2635         pmap_activate_boot(pmap);
2636 }
2637
2638 void
2639 pmap_pinit_pml4(vm_page_t pml4pg)
2640 {
2641         pml4_entry_t *pm_pml4;
2642         int i;
2643
2644         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2645
2646         /* Wire in kernel global address entries. */
2647         for (i = 0; i < NKPML4E; i++) {
2648                 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2649                     X86_PG_V;
2650         }
2651         for (i = 0; i < ndmpdpphys; i++) {
2652                 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2653                     X86_PG_V;
2654         }
2655
2656         /* install self-referential address mapping entry(s) */
2657         pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2658             X86_PG_A | X86_PG_M;
2659 }
2660
2661 static void
2662 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2663 {
2664         pml4_entry_t *pm_pml4;
2665         int i;
2666
2667         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2668         for (i = 0; i < NPML4EPG; i++)
2669                 pm_pml4[i] = pti_pml4[i];
2670 }
2671
2672 /*
2673  * Initialize a preallocated and zeroed pmap structure,
2674  * such as one in a vmspace structure.
2675  */
2676 int
2677 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2678 {
2679         vm_page_t pml4pg, pml4pgu;
2680         vm_paddr_t pml4phys;
2681         int i;
2682
2683         /*
2684          * allocate the page directory page
2685          */
2686         pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2687             VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2688
2689         pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2690         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2691         CPU_FOREACH(i) {
2692                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2693                 pmap->pm_pcids[i].pm_gen = 0;
2694         }
2695         pmap->pm_cr3 = PMAP_NO_CR3;     /* initialize to an invalid value */
2696         pmap->pm_ucr3 = PMAP_NO_CR3;
2697         pmap->pm_pml4u = NULL;
2698
2699         pmap->pm_type = pm_type;
2700         if ((pml4pg->flags & PG_ZERO) == 0)
2701                 pagezero(pmap->pm_pml4);
2702
2703         /*
2704          * Do not install the host kernel mappings in the nested page
2705          * tables. These mappings are meaningless in the guest physical
2706          * address space.
2707          * Install minimal kernel mappings in PTI case.
2708          */
2709         if (pm_type == PT_X86) {
2710                 pmap->pm_cr3 = pml4phys;
2711                 pmap_pinit_pml4(pml4pg);
2712                 if (pti) {
2713                         pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2714                             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2715                         pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2716                             VM_PAGE_TO_PHYS(pml4pgu));
2717                         pmap_pinit_pml4_pti(pml4pgu);
2718                         pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2719                 }
2720         }
2721
2722         pmap->pm_root.rt_root = 0;
2723         CPU_ZERO(&pmap->pm_active);
2724         TAILQ_INIT(&pmap->pm_pvchunk);
2725         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2726         pmap->pm_flags = flags;
2727         pmap->pm_eptgen = 0;
2728
2729         return (1);
2730 }
2731
2732 int
2733 pmap_pinit(pmap_t pmap)
2734 {
2735
2736         return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2737 }
2738
2739 /*
2740  * This routine is called if the desired page table page does not exist.
2741  *
2742  * If page table page allocation fails, this routine may sleep before
2743  * returning NULL.  It sleeps only if a lock pointer was given.
2744  *
2745  * Note: If a page allocation fails at page table level two or three,
2746  * one or two pages may be held during the wait, only to be released
2747  * afterwards.  This conservative approach is easily argued to avoid
2748  * race conditions.
2749  */
2750 static vm_page_t
2751 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2752 {
2753         vm_page_t m, pdppg, pdpg;
2754         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2755
2756         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2757
2758         PG_A = pmap_accessed_bit(pmap);
2759         PG_M = pmap_modified_bit(pmap);
2760         PG_V = pmap_valid_bit(pmap);
2761         PG_RW = pmap_rw_bit(pmap);
2762
2763         /*
2764          * Allocate a page table page.
2765          */
2766         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2767             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2768                 if (lockp != NULL) {
2769                         RELEASE_PV_LIST_LOCK(lockp);
2770                         PMAP_UNLOCK(pmap);
2771                         PMAP_ASSERT_NOT_IN_DI();
2772                         VM_WAIT;
2773                         PMAP_LOCK(pmap);
2774                 }
2775
2776                 /*
2777                  * Indicate the need to retry.  While waiting, the page table
2778                  * page may have been allocated.
2779                  */
2780                 return (NULL);
2781         }
2782         if ((m->flags & PG_ZERO) == 0)
2783                 pmap_zero_page(m);
2784
2785         /*
2786          * Map the pagetable page into the process address space, if
2787          * it isn't already there.
2788          */
2789
2790         if (ptepindex >= (NUPDE + NUPDPE)) {
2791                 pml4_entry_t *pml4, *pml4u;
2792                 vm_pindex_t pml4index;
2793
2794                 /* Wire up a new PDPE page */
2795                 pml4index = ptepindex - (NUPDE + NUPDPE);
2796                 pml4 = &pmap->pm_pml4[pml4index];
2797                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2798                 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2799                         /*
2800                          * PTI: Make all user-space mappings in the
2801                          * kernel-mode page table no-execute so that
2802                          * we detect any programming errors that leave
2803                          * the kernel-mode page table active on return
2804                          * to user space.
2805                          */
2806                         if (pmap->pm_ucr3 != PMAP_NO_CR3)
2807                                 *pml4 |= pg_nx;
2808
2809                         pml4u = &pmap->pm_pml4u[pml4index];
2810                         *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2811                             PG_A | PG_M;
2812                 }
2813
2814         } else if (ptepindex >= NUPDE) {
2815                 vm_pindex_t pml4index;
2816                 vm_pindex_t pdpindex;
2817                 pml4_entry_t *pml4;
2818                 pdp_entry_t *pdp;
2819
2820                 /* Wire up a new PDE page */
2821                 pdpindex = ptepindex - NUPDE;
2822                 pml4index = pdpindex >> NPML4EPGSHIFT;
2823
2824                 pml4 = &pmap->pm_pml4[pml4index];
2825                 if ((*pml4 & PG_V) == 0) {
2826                         /* Have to allocate a new pdp, recurse */
2827                         if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2828                             lockp) == NULL) {
2829                                 --m->wire_count;
2830                                 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2831                                 vm_page_free_zero(m);
2832                                 return (NULL);
2833                         }
2834                 } else {
2835                         /* Add reference to pdp page */
2836                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2837                         pdppg->wire_count++;
2838                 }
2839                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2840
2841                 /* Now find the pdp page */
2842                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2843                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2844
2845         } else {
2846                 vm_pindex_t pml4index;
2847                 vm_pindex_t pdpindex;
2848                 pml4_entry_t *pml4;
2849                 pdp_entry_t *pdp;
2850                 pd_entry_t *pd;
2851
2852                 /* Wire up a new PTE page */
2853                 pdpindex = ptepindex >> NPDPEPGSHIFT;
2854                 pml4index = pdpindex >> NPML4EPGSHIFT;
2855
2856                 /* First, find the pdp and check that its valid. */
2857                 pml4 = &pmap->pm_pml4[pml4index];
2858                 if ((*pml4 & PG_V) == 0) {
2859                         /* Have to allocate a new pd, recurse */
2860                         if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2861                             lockp) == NULL) {
2862                                 --m->wire_count;
2863                                 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2864                                 vm_page_free_zero(m);
2865                                 return (NULL);
2866                         }
2867                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2868                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2869                 } else {
2870                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2871                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2872                         if ((*pdp & PG_V) == 0) {
2873                                 /* Have to allocate a new pd, recurse */
2874                                 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2875                                     lockp) == NULL) {
2876                                         --m->wire_count;
2877                                         atomic_subtract_int(&vm_cnt.v_wire_count,
2878                                             1);
2879                                         vm_page_free_zero(m);
2880                                         return (NULL);
2881                                 }
2882                         } else {
2883                                 /* Add reference to the pd page */
2884                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2885                                 pdpg->wire_count++;
2886                         }
2887                 }
2888                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2889
2890                 /* Now we know where the page directory page is */
2891                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2892                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2893         }
2894
2895         pmap_resident_count_inc(pmap, 1);
2896
2897         return (m);
2898 }
2899
2900 static vm_page_t
2901 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2902 {
2903         vm_pindex_t pdpindex, ptepindex;
2904         pdp_entry_t *pdpe, PG_V;
2905         vm_page_t pdpg;
2906
2907         PG_V = pmap_valid_bit(pmap);
2908
2909 retry:
2910         pdpe = pmap_pdpe(pmap, va);
2911         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2912                 /* Add a reference to the pd page. */
2913                 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2914                 pdpg->wire_count++;
2915         } else {
2916                 /* Allocate a pd page. */
2917                 ptepindex = pmap_pde_pindex(va);
2918                 pdpindex = ptepindex >> NPDPEPGSHIFT;
2919                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2920                 if (pdpg == NULL && lockp != NULL)
2921                         goto retry;
2922         }
2923         return (pdpg);
2924 }
2925
2926 static vm_page_t
2927 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2928 {
2929         vm_pindex_t ptepindex;
2930         pd_entry_t *pd, PG_V;
2931         vm_page_t m;
2932
2933         PG_V = pmap_valid_bit(pmap);
2934
2935         /*
2936          * Calculate pagetable page index
2937          */
2938         ptepindex = pmap_pde_pindex(va);
2939 retry:
2940         /*
2941          * Get the page directory entry
2942          */
2943         pd = pmap_pde(pmap, va);
2944
2945         /*
2946          * This supports switching from a 2MB page to a
2947          * normal 4K page.
2948          */
2949         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2950                 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2951                         /*
2952                          * Invalidation of the 2MB page mapping may have caused
2953                          * the deallocation of the underlying PD page.
2954                          */
2955                         pd = NULL;
2956                 }
2957         }
2958
2959         /*
2960          * If the page table page is mapped, we just increment the
2961          * hold count, and activate it.
2962          */
2963         if (pd != NULL && (*pd & PG_V) != 0) {
2964                 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2965                 m->wire_count++;
2966         } else {
2967                 /*
2968                  * Here if the pte page isn't mapped, or if it has been
2969                  * deallocated.
2970                  */
2971                 m = _pmap_allocpte(pmap, ptepindex, lockp);
2972                 if (m == NULL && lockp != NULL)
2973                         goto retry;
2974         }
2975         return (m);
2976 }
2977
2978
2979 /***************************************************
2980  * Pmap allocation/deallocation routines.
2981  ***************************************************/
2982
2983 /*
2984  * Release any resources held by the given physical map.
2985  * Called when a pmap initialized by pmap_pinit is being released.
2986  * Should only be called if the map contains no valid mappings.
2987  */
2988 void
2989 pmap_release(pmap_t pmap)
2990 {
2991         vm_page_t m;
2992         int i;
2993
2994         KASSERT(pmap->pm_stats.resident_count == 0,
2995             ("pmap_release: pmap resident count %ld != 0",
2996             pmap->pm_stats.resident_count));
2997         KASSERT(vm_radix_is_empty(&pmap->pm_root),
2998             ("pmap_release: pmap has reserved page table page(s)"));
2999         KASSERT(CPU_EMPTY(&pmap->pm_active),
3000             ("releasing active pmap %p", pmap));
3001
3002         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
3003
3004         for (i = 0; i < NKPML4E; i++)   /* KVA */
3005                 pmap->pm_pml4[KPML4BASE + i] = 0;
3006         for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3007                 pmap->pm_pml4[DMPML4I + i] = 0;
3008         pmap->pm_pml4[PML4PML4I] = 0;   /* Recursive Mapping */
3009
3010         m->wire_count--;
3011         atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3012         vm_page_free_zero(m);
3013
3014         if (pmap->pm_pml4u != NULL) {
3015                 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3016                 m->wire_count--;
3017                 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3018                 vm_page_free(m);
3019         }
3020 }
3021 \f
3022 static int
3023 kvm_size(SYSCTL_HANDLER_ARGS)
3024 {
3025         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3026
3027         return sysctl_handle_long(oidp, &ksize, 0, req);
3028 }
3029 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
3030     0, 0, kvm_size, "LU", "Size of KVM");
3031
3032 static int
3033 kvm_free(SYSCTL_HANDLER_ARGS)
3034 {
3035         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3036
3037         return sysctl_handle_long(oidp, &kfree, 0, req);
3038 }
3039 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
3040     0, 0, kvm_free, "LU", "Amount of KVM free");
3041
3042 /*
3043  * grow the number of kernel page table entries, if needed
3044  */
3045 void
3046 pmap_growkernel(vm_offset_t addr)
3047 {
3048         vm_paddr_t paddr;
3049         vm_page_t nkpg;
3050         pd_entry_t *pde, newpdir;
3051         pdp_entry_t *pdpe;
3052
3053         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3054
3055         /*
3056          * Return if "addr" is within the range of kernel page table pages
3057          * that were preallocated during pmap bootstrap.  Moreover, leave
3058          * "kernel_vm_end" and the kernel page table as they were.
3059          *
3060          * The correctness of this action is based on the following
3061          * argument: vm_map_insert() allocates contiguous ranges of the
3062          * kernel virtual address space.  It calls this function if a range
3063          * ends after "kernel_vm_end".  If the kernel is mapped between
3064          * "kernel_vm_end" and "addr", then the range cannot begin at
3065          * "kernel_vm_end".  In fact, its beginning address cannot be less
3066          * than the kernel.  Thus, there is no immediate need to allocate
3067          * any new kernel page table pages between "kernel_vm_end" and
3068          * "KERNBASE".
3069          */
3070         if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3071                 return;
3072
3073         addr = roundup2(addr, NBPDR);
3074         if (addr - 1 >= vm_map_max(kernel_map))
3075                 addr = vm_map_max(kernel_map);
3076         while (kernel_vm_end < addr) {
3077                 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3078                 if ((*pdpe & X86_PG_V) == 0) {
3079                         /* We need a new PDP entry */
3080                         nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3081                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3082                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3083                         if (nkpg == NULL)
3084                                 panic("pmap_growkernel: no memory to grow kernel");
3085                         if ((nkpg->flags & PG_ZERO) == 0)
3086                                 pmap_zero_page(nkpg);
3087                         paddr = VM_PAGE_TO_PHYS(nkpg);
3088                         *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3089                             X86_PG_A | X86_PG_M);
3090                         continue; /* try again */
3091                 }
3092                 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3093                 if ((*pde & X86_PG_V) != 0) {
3094                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3095                         if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3096                                 kernel_vm_end = vm_map_max(kernel_map);
3097                                 break;                       
3098                         }
3099                         continue;
3100                 }
3101
3102                 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3103                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3104                     VM_ALLOC_ZERO);
3105                 if (nkpg == NULL)
3106                         panic("pmap_growkernel: no memory to grow kernel");
3107                 if ((nkpg->flags & PG_ZERO) == 0)
3108                         pmap_zero_page(nkpg);
3109                 paddr = VM_PAGE_TO_PHYS(nkpg);
3110                 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3111                 pde_store(pde, newpdir);
3112
3113                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3114                 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3115                         kernel_vm_end = vm_map_max(kernel_map);
3116                         break;                       
3117                 }
3118         }
3119 }
3120
3121
3122 /***************************************************
3123  * page management routines.
3124  ***************************************************/
3125
3126 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3127 CTASSERT(_NPCM == 3);
3128 CTASSERT(_NPCPV == 168);
3129
3130 static __inline struct pv_chunk *
3131 pv_to_chunk(pv_entry_t pv)
3132 {
3133
3134         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3135 }
3136
3137 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3138
3139 #define PC_FREE0        0xfffffffffffffffful
3140 #define PC_FREE1        0xfffffffffffffffful
3141 #define PC_FREE2        0x000000fffffffffful
3142
3143 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3144
3145 #ifdef PV_STATS
3146 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3147
3148 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3149         "Current number of pv entry chunks");
3150 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3151         "Current number of pv entry chunks allocated");
3152 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3153         "Current number of pv entry chunks frees");
3154 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3155         "Number of times tried to get a chunk page but failed.");
3156
3157 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3158 static int pv_entry_spare;
3159
3160 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3161         "Current number of pv entry frees");
3162 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3163         "Current number of pv entry allocs");
3164 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3165         "Current number of pv entries");
3166 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3167         "Current number of spare pv entries");
3168 #endif
3169
3170 static void
3171 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3172 {
3173
3174         if (pmap == NULL)
3175                 return;
3176         pmap_invalidate_all(pmap);
3177         if (pmap != locked_pmap)
3178                 PMAP_UNLOCK(pmap);
3179         if (start_di)
3180                 pmap_delayed_invl_finished();
3181 }
3182
3183 /*
3184  * We are in a serious low memory condition.  Resort to
3185  * drastic measures to free some pages so we can allocate
3186  * another pv entry chunk.
3187  *
3188  * Returns NULL if PV entries were reclaimed from the specified pmap.
3189  *
3190  * We do not, however, unmap 2mpages because subsequent accesses will
3191  * allocate per-page pv entries until repromotion occurs, thereby
3192  * exacerbating the shortage of free pv entries.
3193  */
3194 static vm_page_t
3195 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3196 {
3197         struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3198         struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3199         struct md_page *pvh;
3200         pd_entry_t *pde;
3201         pmap_t next_pmap, pmap;
3202         pt_entry_t *pte, tpte;
3203         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3204         pv_entry_t pv;
3205         vm_offset_t va;
3206         vm_page_t m, m_pc;
3207         struct spglist free;
3208         uint64_t inuse;
3209         int bit, field, freed;
3210         bool start_di;
3211         static int active_reclaims = 0;
3212
3213         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3214         KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3215         pmap = NULL;
3216         m_pc = NULL;
3217         PG_G = PG_A = PG_M = PG_RW = 0;
3218         SLIST_INIT(&free);
3219         bzero(&pc_marker_b, sizeof(pc_marker_b));
3220         bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3221         pc_marker = (struct pv_chunk *)&pc_marker_b;
3222         pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3223
3224         /*
3225          * A delayed invalidation block should already be active if
3226          * pmap_advise() or pmap_remove() called this function by way
3227          * of pmap_demote_pde_locked().
3228          */
3229         start_di = pmap_not_in_di();
3230
3231         mtx_lock(&pv_chunks_mutex);
3232         active_reclaims++;
3233         TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3234         TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3235         while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3236             SLIST_EMPTY(&free)) {
3237                 next_pmap = pc->pc_pmap;
3238                 if (next_pmap == NULL) {
3239                         /*
3240                          * The next chunk is a marker.  However, it is
3241                          * not our marker, so active_reclaims must be
3242                          * > 1.  Consequently, the next_chunk code
3243                          * will not rotate the pv_chunks list.
3244                          */
3245                         goto next_chunk;
3246                 }
3247                 mtx_unlock(&pv_chunks_mutex);
3248
3249                 /*
3250                  * A pv_chunk can only be removed from the pc_lru list
3251                  * when both pc_chunks_mutex is owned and the
3252                  * corresponding pmap is locked.
3253                  */
3254                 if (pmap != next_pmap) {
3255                         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3256                             start_di);
3257                         pmap = next_pmap;
3258                         /* Avoid deadlock and lock recursion. */
3259                         if (pmap > locked_pmap) {
3260                                 RELEASE_PV_LIST_LOCK(lockp);
3261                                 PMAP_LOCK(pmap);
3262                                 if (start_di)
3263                                         pmap_delayed_invl_started();
3264                                 mtx_lock(&pv_chunks_mutex);
3265                                 continue;
3266                         } else if (pmap != locked_pmap) {
3267                                 if (PMAP_TRYLOCK(pmap)) {
3268                                         if (start_di)
3269                                                 pmap_delayed_invl_started();
3270                                         mtx_lock(&pv_chunks_mutex);
3271                                         continue;
3272                                 } else {
3273                                         pmap = NULL; /* pmap is not locked */
3274                                         mtx_lock(&pv_chunks_mutex);
3275                                         pc = TAILQ_NEXT(pc_marker, pc_lru);
3276                                         if (pc == NULL ||
3277                                             pc->pc_pmap != next_pmap)
3278                                                 continue;
3279                                         goto next_chunk;
3280                                 }
3281                         } else if (start_di)
3282                                 pmap_delayed_invl_started();
3283                         PG_G = pmap_global_bit(pmap);
3284                         PG_A = pmap_accessed_bit(pmap);
3285                         PG_M = pmap_modified_bit(pmap);
3286                         PG_RW = pmap_rw_bit(pmap);
3287                 }
3288
3289                 /*
3290                  * Destroy every non-wired, 4 KB page mapping in the chunk.
3291                  */
3292                 freed = 0;
3293                 for (field = 0; field < _NPCM; field++) {
3294                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3295                             inuse != 0; inuse &= ~(1UL << bit)) {
3296                                 bit = bsfq(inuse);
3297                                 pv = &pc->pc_pventry[field * 64 + bit];
3298                                 va = pv->pv_va;
3299                                 pde = pmap_pde(pmap, va);
3300                                 if ((*pde & PG_PS) != 0)
3301                                         continue;
3302                                 pte = pmap_pde_to_pte(pde, va);
3303                                 if ((*pte & PG_W) != 0)
3304                                         continue;
3305                                 tpte = pte_load_clear(pte);
3306                                 if ((tpte & PG_G) != 0)
3307                                         pmap_invalidate_page(pmap, va);
3308                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3309                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3310                                         vm_page_dirty(m);
3311                                 if ((tpte & PG_A) != 0)
3312                                         vm_page_aflag_set(m, PGA_REFERENCED);
3313                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3314                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3315                                 m->md.pv_gen++;
3316                                 if (TAILQ_EMPTY(&m->md.pv_list) &&
3317                                     (m->flags & PG_FICTITIOUS) == 0) {
3318                                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3319                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
3320                                                 vm_page_aflag_clear(m,
3321                                                     PGA_WRITEABLE);
3322                                         }
3323                                 }
3324                                 pmap_delayed_invl_page(m);
3325                                 pc->pc_map[field] |= 1UL << bit;
3326                                 pmap_unuse_pt(pmap, va, *pde, &free);
3327                                 freed++;
3328                         }
3329                 }
3330                 if (freed == 0) {
3331                         mtx_lock(&pv_chunks_mutex);
3332                         goto next_chunk;
3333                 }
3334                 /* Every freed mapping is for a 4 KB page. */
3335                 pmap_resident_count_dec(pmap, freed);
3336                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3337                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3338                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3339                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3340                 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3341                     pc->pc_map[2] == PC_FREE2) {
3342                         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3343                         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3344                         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3345                         /* Entire chunk is free; return it. */
3346                         m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3347                         dump_drop_page(m_pc->phys_addr);
3348                         mtx_lock(&pv_chunks_mutex);
3349                         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3350                         break;
3351                 }
3352                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3353                 mtx_lock(&pv_chunks_mutex);
3354                 /* One freed pv entry in locked_pmap is sufficient. */
3355                 if (pmap == locked_pmap)
3356                         break;
3357 next_chunk:
3358                 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3359                 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3360                 if (active_reclaims == 1 && pmap != NULL) {
3361                         /*
3362                          * Rotate the pv chunks list so that we do not
3363                          * scan the same pv chunks that could not be
3364                          * freed (because they contained a wired
3365                          * and/or superpage mapping) on every
3366                          * invocation of reclaim_pv_chunk().
3367                          */
3368                         while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3369                                 MPASS(pc->pc_pmap != NULL);
3370                                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3371                                 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3372                         }
3373                 }
3374         }
3375         TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3376         TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3377         active_reclaims--;
3378         mtx_unlock(&pv_chunks_mutex);
3379         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3380         if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3381                 m_pc = SLIST_FIRST(&free);
3382                 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3383                 /* Recycle a freed page table page. */
3384                 m_pc->wire_count = 1;
3385         }
3386         pmap_free_zero_pages(&free);
3387         return (m_pc);
3388 }
3389
3390 /*
3391  * free the pv_entry back to the free list
3392  */
3393 static void
3394 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3395 {
3396         struct pv_chunk *pc;
3397         int idx, field, bit;
3398
3399         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3400         PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3401         PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3402         PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3403         pc = pv_to_chunk(pv);
3404         idx = pv - &pc->pc_pventry[0];
3405         field = idx / 64;
3406         bit = idx % 64;
3407         pc->pc_map[field] |= 1ul << bit;
3408         if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3409             pc->pc_map[2] != PC_FREE2) {
3410                 /* 98% of the time, pc is already at the head of the list. */
3411                 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3412                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3413                         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3414                 }
3415                 return;
3416         }
3417         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3418         free_pv_chunk(pc);
3419 }
3420
3421 static void
3422 free_pv_chunk(struct pv_chunk *pc)
3423 {
3424         vm_page_t m;
3425
3426         mtx_lock(&pv_chunks_mutex);
3427         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3428         mtx_unlock(&pv_chunks_mutex);
3429         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3430         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3431         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3432         /* entire chunk is free, return it */
3433         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3434         dump_drop_page(m->phys_addr);
3435         vm_page_unwire(m, PQ_NONE);
3436         vm_page_free(m);
3437 }
3438
3439 /*
3440  * Returns a new PV entry, allocating a new PV chunk from the system when
3441  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
3442  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
3443  * returned.
3444  *
3445  * The given PV list lock may be released.
3446  */
3447 static pv_entry_t
3448 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3449 {
3450         int bit, field;
3451         pv_entry_t pv;
3452         struct pv_chunk *pc;
3453         vm_page_t m;
3454
3455         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3456         PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3457 retry:
3458         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3459         if (pc != NULL) {
3460                 for (field = 0; field < _NPCM; field++) {
3461                         if (pc->pc_map[field]) {
3462                                 bit = bsfq(pc->pc_map[field]);
3463                                 break;
3464                         }
3465                 }
3466                 if (field < _NPCM) {
3467                         pv = &pc->pc_pventry[field * 64 + bit];
3468                         pc->pc_map[field] &= ~(1ul << bit);
3469                         /* If this was the last item, move it to tail */
3470                         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3471                             pc->pc_map[2] == 0) {
3472                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3473                                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3474                                     pc_list);
3475                         }
3476                         PV_STAT(atomic_add_long(&pv_entry_count, 1));
3477                         PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3478                         return (pv);
3479                 }
3480         }
3481         /* No free items, allocate another chunk */
3482         m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3483             VM_ALLOC_WIRED);
3484         if (m == NULL) {
3485                 if (lockp == NULL) {
3486                         PV_STAT(pc_chunk_tryfail++);
3487                         return (NULL);
3488                 }
3489                 m = reclaim_pv_chunk(pmap, lockp);
3490                 if (m == NULL)
3491                         goto retry;
3492         }
3493         PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3494         PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3495         dump_add_page(m->phys_addr);
3496         pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3497         pc->pc_pmap = pmap;
3498         pc->pc_map[0] = PC_FREE0 & ~1ul;        /* preallocated bit 0 */
3499         pc->pc_map[1] = PC_FREE1;
3500         pc->pc_map[2] = PC_FREE2;
3501         mtx_lock(&pv_chunks_mutex);
3502         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3503         mtx_unlock(&pv_chunks_mutex);
3504         pv = &pc->pc_pventry[0];
3505         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3506         PV_STAT(atomic_add_long(&pv_entry_count, 1));
3507         PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3508         return (pv);
3509 }
3510
3511 /*
3512  * Returns the number of one bits within the given PV chunk map.
3513  *
3514  * The erratas for Intel processors state that "POPCNT Instruction May
3515  * Take Longer to Execute Than Expected".  It is believed that the
3516  * issue is the spurious dependency on the destination register.
3517  * Provide a hint to the register rename logic that the destination
3518  * value is overwritten, by clearing it, as suggested in the
3519  * optimization manual.  It should be cheap for unaffected processors
3520  * as well.
3521  *
3522  * Reference numbers for erratas are
3523  * 4th Gen Core: HSD146
3524  * 5th Gen Core: BDM85
3525  * 6th Gen Core: SKL029
3526  */
3527 static int
3528 popcnt_pc_map_pq(uint64_t *map)
3529 {
3530         u_long result, tmp;
3531
3532         __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3533             "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3534             "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3535             : "=&r" (result), "=&r" (tmp)
3536             : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3537         return (result);
3538 }
3539
3540 /*
3541  * Ensure that the number of spare PV entries in the specified pmap meets or
3542  * exceeds the given count, "needed".
3543  *
3544  * The given PV list lock may be released.
3545  */
3546 static void
3547 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3548 {
3549         struct pch new_tail;
3550         struct pv_chunk *pc;
3551         vm_page_t m;
3552         int avail, free;
3553         bool reclaimed;
3554
3555         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3556         KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3557
3558         /*
3559          * Newly allocated PV chunks must be stored in a private list until
3560          * the required number of PV chunks have been allocated.  Otherwise,
3561          * reclaim_pv_chunk() could recycle one of these chunks.  In
3562          * contrast, these chunks must be added to the pmap upon allocation.
3563          */
3564         TAILQ_INIT(&new_tail);
3565 retry:
3566         avail = 0;
3567         TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3568 #ifndef __POPCNT__
3569                 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3570                         bit_count((bitstr_t *)pc->pc_map, 0,
3571                             sizeof(pc->pc_map) * NBBY, &free);
3572                 else
3573 #endif
3574                 free = popcnt_pc_map_pq(pc->pc_map);
3575                 if (free == 0)
3576                         break;
3577                 avail += free;
3578                 if (avail >= needed)
3579                         break;
3580         }
3581         for (reclaimed = false; avail < needed; avail += _NPCPV) {
3582                 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3583                     VM_ALLOC_WIRED);
3584                 if (m == NULL) {
3585                         m = reclaim_pv_chunk(pmap, lockp);
3586                         if (m == NULL)
3587                                 goto retry;
3588                         reclaimed = true;
3589                 }
3590                 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3591                 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3592                 dump_add_page(m->phys_addr);
3593                 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3594                 pc->pc_pmap = pmap;
3595                 pc->pc_map[0] = PC_FREE0;
3596                 pc->pc_map[1] = PC_FREE1;
3597                 pc->pc_map[2] = PC_FREE2;
3598                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3599                 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3600                 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3601
3602                 /*
3603                  * The reclaim might have freed a chunk from the current pmap.
3604                  * If that chunk contained available entries, we need to
3605                  * re-count the number of available entries.
3606                  */
3607                 if (reclaimed)
3608                         goto retry;
3609         }
3610         if (!TAILQ_EMPTY(&new_tail)) {
3611                 mtx_lock(&pv_chunks_mutex);
3612                 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3613                 mtx_unlock(&pv_chunks_mutex);
3614         }
3615 }
3616
3617 /*
3618  * First find and then remove the pv entry for the specified pmap and virtual
3619  * address from the specified pv list.  Returns the pv entry if found and NULL
3620  * otherwise.  This operation can be performed on pv lists for either 4KB or
3621  * 2MB page mappings.
3622  */
3623 static __inline pv_entry_t
3624 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3625 {
3626         pv_entry_t pv;
3627
3628         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3629                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3630                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3631                         pvh->pv_gen++;
3632                         break;
3633                 }
3634         }
3635         return (pv);
3636 }
3637
3638 /*
3639  * After demotion from a 2MB page mapping to 512 4KB page mappings,
3640  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3641  * entries for each of the 4KB page mappings.
3642  */
3643 static void
3644 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3645     struct rwlock **lockp)
3646 {
3647         struct md_page *pvh;
3648         struct pv_chunk *pc;
3649         pv_entry_t pv;
3650         vm_offset_t va_last;
3651         vm_page_t m;
3652         int bit, field;
3653
3654         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3655         KASSERT((pa & PDRMASK) == 0,
3656             ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3657         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3658
3659         /*
3660          * Transfer the 2mpage's pv entry for this mapping to the first
3661          * page's pv list.  Once this transfer begins, the pv list lock
3662          * must not be released until the last pv entry is reinstantiated.
3663          */
3664         pvh = pa_to_pvh(pa);
3665         va = trunc_2mpage(va);
3666         pv = pmap_pvh_remove(pvh, pmap, va);
3667         KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3668         m = PHYS_TO_VM_PAGE(pa);
3669         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3670         m->md.pv_gen++;
3671         /* Instantiate the remaining NPTEPG - 1 pv entries. */
3672         PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3673         va_last = va + NBPDR - PAGE_SIZE;
3674         for (;;) {
3675                 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3676                 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3677                     pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3678                 for (field = 0; field < _NPCM; field++) {
3679                         while (pc->pc_map[field]) {
3680                                 bit = bsfq(pc->pc_map[field]);
3681                                 pc->pc_map[field] &= ~(1ul << bit);
3682                                 pv = &pc->pc_pventry[field * 64 + bit];
3683                                 va += PAGE_SIZE;
3684                                 pv->pv_va = va;
3685                                 m++;
3686                                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3687                             ("pmap_pv_demote_pde: page %p is not managed", m));
3688                                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3689                                 m->md.pv_gen++;
3690                                 if (va == va_last)
3691                                         goto out;
3692                         }
3693                 }
3694                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3695                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3696         }
3697 out:
3698         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3699                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3700                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3701         }
3702         PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3703         PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3704 }
3705
3706 #if VM_NRESERVLEVEL > 0
3707 /*
3708  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3709  * replace the many pv entries for the 4KB page mappings by a single pv entry
3710  * for the 2MB page mapping.
3711  */
3712 static void
3713 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3714     struct rwlock **lockp)
3715 {
3716         struct md_page *pvh;
3717         pv_entry_t pv;
3718         vm_offset_t va_last;
3719         vm_page_t m;
3720
3721         KASSERT((pa & PDRMASK) == 0,
3722             ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3723         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3724
3725         /*
3726          * Transfer the first page's pv entry for this mapping to the 2mpage's
3727          * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
3728          * a transfer avoids the possibility that get_pv_entry() calls
3729          * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3730          * mappings that is being promoted.
3731          */
3732         m = PHYS_TO_VM_PAGE(pa);
3733         va = trunc_2mpage(va);
3734         pv = pmap_pvh_remove(&m->md, pmap, va);
3735         KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3736         pvh = pa_to_pvh(pa);
3737         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3738         pvh->pv_gen++;
3739         /* Free the remaining NPTEPG - 1 pv entries. */
3740         va_last = va + NBPDR - PAGE_SIZE;
3741         do {
3742                 m++;
3743                 va += PAGE_SIZE;
3744                 pmap_pvh_free(&m->md, pmap, va);
3745         } while (va < va_last);
3746 }
3747 #endif /* VM_NRESERVLEVEL > 0 */
3748
3749 /*
3750  * First find and then destroy the pv entry for the specified pmap and virtual
3751  * address.  This operation can be performed on pv lists for either 4KB or 2MB
3752  * page mappings.
3753  */
3754 static void
3755 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3756 {
3757         pv_entry_t pv;
3758
3759         pv = pmap_pvh_remove(pvh, pmap, va);
3760         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3761         free_pv_entry(pmap, pv);
3762 }
3763
3764 /*
3765  * Conditionally create the PV entry for a 4KB page mapping if the required
3766  * memory can be allocated without resorting to reclamation.
3767  */
3768 static boolean_t
3769 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3770     struct rwlock **lockp)
3771 {
3772         pv_entry_t pv;
3773
3774         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3775         /* Pass NULL instead of the lock pointer to disable reclamation. */
3776         if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3777                 pv->pv_va = va;
3778                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3779                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3780                 m->md.pv_gen++;
3781                 return (TRUE);
3782         } else
3783                 return (FALSE);
3784 }
3785
3786 /*
3787  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
3788  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
3789  * false if the PV entry cannot be allocated without resorting to reclamation.
3790  */
3791 static bool
3792 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3793     struct rwlock **lockp)
3794 {
3795         struct md_page *pvh;
3796         pv_entry_t pv;
3797         vm_paddr_t pa;
3798
3799         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3800         /* Pass NULL instead of the lock pointer to disable reclamation. */
3801         if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3802             NULL : lockp)) == NULL)
3803                 return (false);
3804         pv->pv_va = va;
3805         pa = pde & PG_PS_FRAME;
3806         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3807         pvh = pa_to_pvh(pa);
3808         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3809         pvh->pv_gen++;
3810         return (true);
3811 }
3812
3813 /*
3814  * Fills a page table page with mappings to consecutive physical pages.
3815  */
3816 static void
3817 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3818 {
3819         pt_entry_t *pte;
3820
3821         for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3822                 *pte = newpte;
3823                 newpte += PAGE_SIZE;
3824         }
3825 }
3826
3827 /*
3828  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
3829  * mapping is invalidated.
3830  */
3831 static boolean_t
3832 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3833 {
3834         struct rwlock *lock;
3835         boolean_t rv;
3836
3837         lock = NULL;
3838         rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3839         if (lock != NULL)
3840                 rw_wunlock(lock);
3841         return (rv);
3842 }
3843
3844 static boolean_t
3845 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3846     struct rwlock **lockp)
3847 {
3848         pd_entry_t newpde, oldpde;
3849         pt_entry_t *firstpte, newpte;
3850         pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3851         vm_paddr_t mptepa;
3852         vm_page_t mpte;
3853         struct spglist free;
3854         vm_offset_t sva;
3855         int PG_PTE_CACHE;
3856
3857         PG_G = pmap_global_bit(pmap);
3858         PG_A = pmap_accessed_bit(pmap);
3859         PG_M = pmap_modified_bit(pmap);
3860         PG_RW = pmap_rw_bit(pmap);
3861         PG_V = pmap_valid_bit(pmap);
3862         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3863
3864         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3865         oldpde = *pde;
3866         KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3867             ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3868         if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3869             NULL) {
3870                 KASSERT((oldpde & PG_W) == 0,
3871                     ("pmap_demote_pde: page table page for a wired mapping"
3872                     " is missing"));
3873
3874                 /*
3875                  * Invalidate the 2MB page mapping and return "failure" if the
3876                  * mapping was never accessed or the allocation of the new
3877                  * page table page fails.  If the 2MB page mapping belongs to
3878                  * the direct map region of the kernel's address space, then
3879                  * the page allocation request specifies the highest possible
3880                  * priority (VM_ALLOC_INTERRUPT).  Otherwise, the priority is
3881                  * normal.  Page table pages are preallocated for every other
3882                  * part of the kernel address space, so the direct map region
3883                  * is the only part of the kernel address space that must be
3884                  * handled here.
3885                  */
3886                 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3887                     pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3888                     DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3889                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3890                         SLIST_INIT(&free);
3891                         sva = trunc_2mpage(va);
3892                         pmap_remove_pde(pmap, pde, sva, &free, lockp);
3893                         if ((oldpde & PG_G) == 0)
3894                                 pmap_invalidate_pde_page(pmap, sva, oldpde);
3895                         pmap_free_zero_pages(&free);
3896                         CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3897                             " in pmap %p", va, pmap);
3898                         return (FALSE);
3899                 }
3900                 if (va < VM_MAXUSER_ADDRESS)
3901                         pmap_resident_count_inc(pmap, 1);
3902         }
3903         mptepa = VM_PAGE_TO_PHYS(mpte);
3904         firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3905         newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3906         KASSERT((oldpde & PG_A) != 0,
3907             ("pmap_demote_pde: oldpde is missing PG_A"));
3908         KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3909             ("pmap_demote_pde: oldpde is missing PG_M"));
3910         newpte = oldpde & ~PG_PS;
3911         newpte = pmap_swap_pat(pmap, newpte);
3912
3913         /*
3914          * If the page table page is new, initialize it.
3915          */
3916         if (mpte->wire_count == 1) {
3917                 mpte->wire_count = NPTEPG;
3918                 pmap_fill_ptp(firstpte, newpte);
3919         }
3920         KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3921             ("pmap_demote_pde: firstpte and newpte map different physical"
3922             " addresses"));
3923
3924         /*
3925          * If the mapping has changed attributes, update the page table
3926          * entries.
3927          */
3928         if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3929                 pmap_fill_ptp(firstpte, newpte);
3930
3931         /*
3932          * The spare PV entries must be reserved prior to demoting the
3933          * mapping, that is, prior to changing the PDE.  Otherwise, the state
3934          * of the PDE and the PV lists will be inconsistent, which can result
3935          * in reclaim_pv_chunk() attempting to remove a PV entry from the
3936          * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3937          * PV entry for the 2MB page mapping that is being demoted.
3938          */
3939         if ((oldpde & PG_MANAGED) != 0)
3940                 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3941
3942         /*
3943          * Demote the mapping.  This pmap is locked.  The old PDE has
3944          * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
3945          * set.  Thus, there is no danger of a race with another
3946          * processor changing the setting of PG_A and/or PG_M between
3947          * the read above and the store below. 
3948          */
3949         if (workaround_erratum383)
3950                 pmap_update_pde(pmap, va, pde, newpde);
3951         else
3952                 pde_store(pde, newpde);
3953
3954         /*
3955          * Invalidate a stale recursive mapping of the page table page.
3956          */
3957         if (va >= VM_MAXUSER_ADDRESS)
3958                 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3959
3960         /*
3961          * Demote the PV entry.
3962          */
3963         if ((oldpde & PG_MANAGED) != 0)
3964                 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3965
3966         atomic_add_long(&pmap_pde_demotions, 1);
3967         CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3968             " in pmap %p", va, pmap);
3969         return (TRUE);
3970 }
3971
3972 /*
3973  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3974  */
3975 static void
3976 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3977 {
3978         pd_entry_t newpde;
3979         vm_paddr_t mptepa;
3980         vm_page_t mpte;
3981
3982         KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3983         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3984         mpte = pmap_remove_pt_page(pmap, va);
3985         if (mpte == NULL)
3986                 panic("pmap_remove_kernel_pde: Missing pt page.");
3987
3988         mptepa = VM_PAGE_TO_PHYS(mpte);
3989         newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3990
3991         /*
3992          * Initialize the page table page.
3993          */
3994         pagezero((void *)PHYS_TO_DMAP(mptepa));
3995
3996         /*
3997          * Demote the mapping.
3998          */
3999         if (workaround_erratum383)
4000                 pmap_update_pde(pmap, va, pde, newpde);
4001         else
4002                 pde_store(pde, newpde);
4003
4004         /*
4005          * Invalidate a stale recursive mapping of the page table page.
4006          */
4007         pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
4008 }
4009
4010 /*
4011  * pmap_remove_pde: do the things to unmap a superpage in a process
4012  */
4013 static int
4014 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
4015     struct spglist *free, struct rwlock **lockp)
4016 {
4017         struct md_page *pvh;
4018         pd_entry_t oldpde;
4019         vm_offset_t eva, va;
4020         vm_page_t m, mpte;
4021         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4022
4023         PG_G = pmap_global_bit(pmap);
4024         PG_A = pmap_accessed_bit(pmap);
4025         PG_M = pmap_modified_bit(pmap);
4026         PG_RW = pmap_rw_bit(pmap);
4027
4028         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4029         KASSERT((sva & PDRMASK) == 0,
4030             ("pmap_remove_pde: sva is not 2mpage aligned"));
4031         oldpde = pte_load_clear(pdq);
4032         if (oldpde & PG_W)
4033                 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
4034         if ((oldpde & PG_G) != 0)
4035                 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4036         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4037         if (oldpde & PG_MANAGED) {
4038                 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4039                 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4040                 pmap_pvh_free(pvh, pmap, sva);
4041                 eva = sva + NBPDR;
4042                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4043                     va < eva; va += PAGE_SIZE, m++) {
4044                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4045                                 vm_page_dirty(m);
4046                         if (oldpde & PG_A)
4047                                 vm_page_aflag_set(m, PGA_REFERENCED);
4048                         if (TAILQ_EMPTY(&m->md.pv_list) &&
4049                             TAILQ_EMPTY(&pvh->pv_list))
4050                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
4051                         pmap_delayed_invl_page(m);
4052                 }
4053         }
4054         if (pmap == kernel_pmap) {
4055                 pmap_remove_kernel_pde(pmap, pdq, sva);
4056         } else {
4057                 mpte = pmap_remove_pt_page(pmap, sva);
4058                 if (mpte != NULL) {
4059                         pmap_resident_count_dec(pmap, 1);
4060                         KASSERT(mpte->wire_count == NPTEPG,
4061                             ("pmap_remove_pde: pte page wire count error"));
4062                         mpte->wire_count = 0;
4063                         pmap_add_delayed_free_list(mpte, free, FALSE);
4064                 }
4065         }
4066         return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4067 }
4068
4069 /*
4070  * pmap_remove_pte: do the things to unmap a page in a process
4071  */
4072 static int
4073 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, 
4074     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4075 {
4076         struct md_page *pvh;
4077         pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4078         vm_page_t m;
4079
4080         PG_A = pmap_accessed_bit(pmap);
4081         PG_M = pmap_modified_bit(pmap);
4082         PG_RW = pmap_rw_bit(pmap);
4083
4084         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4085         oldpte = pte_load_clear(ptq);
4086         if (oldpte & PG_W)
4087                 pmap->pm_stats.wired_count -= 1;
4088         pmap_resident_count_dec(pmap, 1);
4089         if (oldpte & PG_MANAGED) {
4090                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4091                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4092                         vm_page_dirty(m);
4093                 if (oldpte & PG_A)
4094                         vm_page_aflag_set(m, PGA_REFERENCED);
4095                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4096                 pmap_pvh_free(&m->md, pmap, va);
4097                 if (TAILQ_EMPTY(&m->md.pv_list) &&
4098                     (m->flags & PG_FICTITIOUS) == 0) {
4099                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4100                         if (TAILQ_EMPTY(&pvh->pv_list))
4101                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
4102                 }
4103                 pmap_delayed_invl_page(m);
4104         }
4105         return (pmap_unuse_pt(pmap, va, ptepde, free));
4106 }
4107
4108 /*
4109  * Remove a single page from a process address space
4110  */
4111 static void
4112 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4113     struct spglist *free)
4114 {
4115         struct rwlock *lock;
4116         pt_entry_t *pte, PG_V;
4117
4118         PG_V = pmap_valid_bit(pmap);
4119         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4120         if ((*pde & PG_V) == 0)
4121                 return;
4122         pte = pmap_pde_to_pte(pde, va);
4123         if ((*pte & PG_V) == 0)
4124                 return;
4125         lock = NULL;
4126         pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4127         if (lock != NULL)
4128                 rw_wunlock(lock);
4129         pmap_invalidate_page(pmap, va);
4130 }
4131
4132 /*
4133  * Removes the specified range of addresses from the page table page.
4134  */
4135 static bool
4136 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4137     pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4138 {
4139         pt_entry_t PG_G, *pte;
4140         vm_offset_t va;
4141         bool anyvalid;
4142
4143         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4144         PG_G = pmap_global_bit(pmap);
4145         anyvalid = false;
4146         va = eva;
4147         for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4148             sva += PAGE_SIZE) {
4149                 if (*pte == 0) {
4150                         if (va != eva) {
4151                                 pmap_invalidate_range(pmap, va, sva);
4152                                 va = eva;
4153                         }
4154                         continue;
4155                 }
4156                 if ((*pte & PG_G) == 0)
4157                         anyvalid = true;
4158                 else if (va == eva)
4159                         va = sva;
4160                 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4161                         sva += PAGE_SIZE;
4162                         break;
4163                 }
4164         }
4165         if (va != eva)
4166                 pmap_invalidate_range(pmap, va, sva);
4167         return (anyvalid);
4168 }
4169
4170 /*
4171  *      Remove the given range of addresses from the specified map.
4172  *
4173  *      It is assumed that the start and end are properly
4174  *      rounded to the page size.
4175  */
4176 void
4177 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4178 {
4179         struct rwlock *lock;
4180         vm_offset_t va_next;
4181         pml4_entry_t *pml4e;
4182         pdp_entry_t *pdpe;
4183         pd_entry_t ptpaddr, *pde;
4184         pt_entry_t PG_G, PG_V;
4185         struct spglist free;
4186         int anyvalid;
4187
4188         PG_G = pmap_global_bit(pmap);
4189         PG_V = pmap_valid_bit(pmap);
4190
4191         /*
4192          * Perform an unsynchronized read.  This is, however, safe.
4193          */
4194         if (pmap->pm_stats.resident_count == 0)
4195                 return;
4196
4197         anyvalid = 0;
4198         SLIST_INIT(&free);
4199
4200         pmap_delayed_invl_started();
4201         PMAP_LOCK(pmap);
4202
4203         /*
4204          * special handling of removing one page.  a very
4205          * common operation and easy to short circuit some
4206          * code.
4207          */
4208         if (sva + PAGE_SIZE == eva) {
4209                 pde = pmap_pde(pmap, sva);
4210                 if (pde && (*pde & PG_PS) == 0) {
4211                         pmap_remove_page(pmap, sva, pde, &free);
4212                         goto out;
4213                 }
4214         }
4215
4216         lock = NULL;
4217         for (; sva < eva; sva = va_next) {
4218
4219                 if (pmap->pm_stats.resident_count == 0)
4220                         break;
4221
4222                 pml4e = pmap_pml4e(pmap, sva);
4223                 if ((*pml4e & PG_V) == 0) {
4224                         va_next = (sva + NBPML4) & ~PML4MASK;
4225                         if (va_next < sva)
4226                                 va_next = eva;
4227                         continue;
4228                 }
4229
4230                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4231                 if ((*pdpe & PG_V) == 0) {
4232                         va_next = (sva + NBPDP) & ~PDPMASK;
4233                         if (va_next < sva)
4234                                 va_next = eva;
4235                         continue;
4236                 }
4237
4238                 /*
4239                  * Calculate index for next page table.
4240                  */
4241                 va_next = (sva + NBPDR) & ~PDRMASK;
4242                 if (va_next < sva)
4243                         va_next = eva;
4244
4245                 pde = pmap_pdpe_to_pde(pdpe, sva);
4246                 ptpaddr = *pde;
4247
4248                 /*
4249                  * Weed out invalid mappings.
4250                  */
4251                 if (ptpaddr == 0)
4252                         continue;
4253
4254                 /*
4255                  * Check for large page.
4256                  */
4257                 if ((ptpaddr & PG_PS) != 0) {
4258                         /*
4259                          * Are we removing the entire large page?  If not,
4260                          * demote the mapping and fall through.
4261                          */
4262                         if (sva + NBPDR == va_next && eva >= va_next) {
4263                                 /*
4264                                  * The TLB entry for a PG_G mapping is
4265                                  * invalidated by pmap_remove_pde().
4266                                  */
4267                                 if ((ptpaddr & PG_G) == 0)
4268                                         anyvalid = 1;
4269                                 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4270                                 continue;
4271                         } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4272                             &lock)) {
4273                                 /* The large page mapping was destroyed. */
4274                                 continue;
4275                         } else
4276                                 ptpaddr = *pde;
4277                 }
4278
4279                 /*
4280                  * Limit our scan to either the end of the va represented
4281                  * by the current page table page, or to the end of the
4282                  * range being removed.
4283                  */
4284                 if (va_next > eva)
4285                         va_next = eva;
4286
4287                 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4288                         anyvalid = 1;
4289         }
4290         if (lock != NULL)
4291                 rw_wunlock(lock);
4292 out:
4293         if (anyvalid)
4294                 pmap_invalidate_all(pmap);
4295         PMAP_UNLOCK(pmap);
4296         pmap_delayed_invl_finished();
4297         pmap_free_zero_pages(&free);
4298 }
4299
4300 /*
4301  *      Routine:        pmap_remove_all
4302  *      Function:
4303  *              Removes this physical page from
4304  *              all physical maps in which it resides.
4305  *              Reflects back modify bits to the pager.
4306  *
4307  *      Notes:
4308  *              Original versions of this routine were very
4309  *              inefficient because they iteratively called
4310  *              pmap_remove (slow...)
4311  */
4312
4313 void
4314 pmap_remove_all(vm_page_t m)
4315 {
4316         struct md_page *pvh;
4317         pv_entry_t pv;
4318         pmap_t pmap;
4319         struct rwlock *lock;
4320         pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4321         pd_entry_t *pde;
4322         vm_offset_t va;
4323         struct spglist free;
4324         int pvh_gen, md_gen;
4325
4326         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4327             ("pmap_remove_all: page %p is not managed", m));
4328         SLIST_INIT(&free);
4329         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4330         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4331             pa_to_pvh(VM_PAGE_TO_PHYS(m));
4332 retry:
4333         rw_wlock(lock);
4334         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4335                 pmap = PV_PMAP(pv);
4336                 if (!PMAP_TRYLOCK(pmap)) {
4337                         pvh_gen = pvh->pv_gen;
4338                         rw_wunlock(lock);
4339                         PMAP_LOCK(pmap);
4340                         rw_wlock(lock);
4341                         if (pvh_gen != pvh->pv_gen) {
4342                                 rw_wunlock(lock);
4343                                 PMAP_UNLOCK(pmap);
4344                                 goto retry;
4345                         }
4346                 }
4347                 va = pv->pv_va;
4348                 pde = pmap_pde(pmap, va);
4349                 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4350                 PMAP_UNLOCK(pmap);
4351         }
4352         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4353                 pmap = PV_PMAP(pv);
4354                 if (!PMAP_TRYLOCK(pmap)) {
4355                         pvh_gen = pvh->pv_gen;
4356                         md_gen = m->md.pv_gen;
4357                         rw_wunlock(lock);
4358                         PMAP_LOCK(pmap);
4359                         rw_wlock(lock);
4360                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4361                                 rw_wunlock(lock);
4362                                 PMAP_UNLOCK(pmap);
4363                                 goto retry;
4364                         }
4365                 }
4366                 PG_A = pmap_accessed_bit(pmap);
4367                 PG_M = pmap_modified_bit(pmap);
4368                 PG_RW = pmap_rw_bit(pmap);
4369                 pmap_resident_count_dec(pmap, 1);
4370                 pde = pmap_pde(pmap, pv->pv_va);
4371                 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4372                     " a 2mpage in page %p's pv list", m));
4373                 pte = pmap_pde_to_pte(pde, pv->pv_va);
4374                 tpte = pte_load_clear(pte);
4375                 if (tpte & PG_W)
4376                         pmap->pm_stats.wired_count--;
4377                 if (tpte & PG_A)
4378                         vm_page_aflag_set(m, PGA_REFERENCED);
4379
4380                 /*
4381                  * Update the vm_page_t clean and reference bits.
4382                  */
4383                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4384                         vm_page_dirty(m);
4385                 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4386                 pmap_invalidate_page(pmap, pv->pv_va);
4387                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4388                 m->md.pv_gen++;
4389                 free_pv_entry(pmap, pv);
4390                 PMAP_UNLOCK(pmap);
4391         }
4392         vm_page_aflag_clear(m, PGA_WRITEABLE);
4393         rw_wunlock(lock);
4394         pmap_delayed_invl_wait(m);
4395         pmap_free_zero_pages(&free);
4396 }
4397
4398 /*
4399  * pmap_protect_pde: do the things to protect a 2mpage in a process
4400  */
4401 static boolean_t
4402 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4403 {
4404         pd_entry_t newpde, oldpde;
4405         vm_offset_t eva, va;
4406         vm_page_t m;
4407         boolean_t anychanged;
4408         pt_entry_t PG_G, PG_M, PG_RW;
4409
4410         PG_G = pmap_global_bit(pmap);
4411         PG_M = pmap_modified_bit(pmap);
4412         PG_RW = pmap_rw_bit(pmap);
4413
4414         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4415         KASSERT((sva & PDRMASK) == 0,
4416             ("pmap_protect_pde: sva is not 2mpage aligned"));
4417         anychanged = FALSE;
4418 retry:
4419         oldpde = newpde = *pde;
4420         if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4421             (PG_MANAGED | PG_M | PG_RW)) {
4422                 eva = sva + NBPDR;
4423                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4424                     va < eva; va += PAGE_SIZE, m++)
4425                         vm_page_dirty(m);
4426         }
4427         if ((prot & VM_PROT_WRITE) == 0)
4428                 newpde &= ~(PG_RW | PG_M);
4429         if ((prot & VM_PROT_EXECUTE) == 0)
4430                 newpde |= pg_nx;
4431         if (newpde != oldpde) {
4432                 /*
4433                  * As an optimization to future operations on this PDE, clear
4434                  * PG_PROMOTED.  The impending invalidation will remove any
4435                  * lingering 4KB page mappings from the TLB.
4436                  */
4437                 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4438                         goto retry;
4439                 if ((oldpde & PG_G) != 0)
4440                         pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4441                 else
4442                         anychanged = TRUE;
4443         }
4444         return (anychanged);
4445 }
4446
4447 /*
4448  *      Set the physical protection on the
4449  *      specified range of this map as requested.
4450  */
4451 void
4452 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4453 {
4454         vm_offset_t va_next;
4455         pml4_entry_t *pml4e;
4456         pdp_entry_t *pdpe;
4457         pd_entry_t ptpaddr, *pde;
4458         pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4459         boolean_t anychanged;
4460
4461         KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4462         if (prot == VM_PROT_NONE) {
4463                 pmap_remove(pmap, sva, eva);
4464                 return;
4465         }
4466
4467         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4468             (VM_PROT_WRITE|VM_PROT_EXECUTE))
4469                 return;
4470
4471         PG_G = pmap_global_bit(pmap);
4472         PG_M = pmap_modified_bit(pmap);
4473         PG_V = pmap_valid_bit(pmap);
4474         PG_RW = pmap_rw_bit(pmap);
4475         anychanged = FALSE;
4476
4477         /*
4478          * Although this function delays and batches the invalidation
4479          * of stale TLB entries, it does not need to call
4480          * pmap_delayed_invl_started() and
4481          * pmap_delayed_invl_finished(), because it does not
4482          * ordinarily destroy mappings.  Stale TLB entries from
4483          * protection-only changes need only be invalidated before the
4484          * pmap lock is released, because protection-only changes do
4485          * not destroy PV entries.  Even operations that iterate over
4486          * a physical page's PV list of mappings, like
4487          * pmap_remove_write(), acquire the pmap lock for each
4488          * mapping.  Consequently, for protection-only changes, the
4489          * pmap lock suffices to synchronize both page table and TLB
4490          * updates.
4491          *
4492          * This function only destroys a mapping if pmap_demote_pde()
4493          * fails.  In that case, stale TLB entries are immediately
4494          * invalidated.
4495          */
4496         
4497         PMAP_LOCK(pmap);
4498         for (; sva < eva; sva = va_next) {
4499
4500                 pml4e = pmap_pml4e(pmap, sva);
4501                 if ((*pml4e & PG_V) == 0) {
4502                         va_next = (sva + NBPML4) & ~PML4MASK;
4503                         if (va_next < sva)
4504                                 va_next = eva;
4505                         continue;
4506                 }
4507
4508                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4509                 if ((*pdpe & PG_V) == 0) {
4510                         va_next = (sva + NBPDP) & ~PDPMASK;
4511                         if (va_next < sva)
4512                                 va_next = eva;
4513                         continue;
4514                 }
4515
4516                 va_next = (sva + NBPDR) & ~PDRMASK;
4517                 if (va_next < sva)
4518                         va_next = eva;
4519
4520                 pde = pmap_pdpe_to_pde(pdpe, sva);
4521                 ptpaddr = *pde;
4522
4523                 /*
4524                  * Weed out invalid mappings.
4525                  */
4526                 if (ptpaddr == 0)
4527                         continue;
4528
4529                 /*
4530                  * Check for large page.
4531                  */
4532                 if ((ptpaddr & PG_PS) != 0) {
4533                         /*
4534                          * Are we protecting the entire large page?  If not,
4535                          * demote the mapping and fall through.
4536                          */
4537                         if (sva + NBPDR == va_next && eva >= va_next) {
4538                                 /*
4539                                  * The TLB entry for a PG_G mapping is
4540                                  * invalidated by pmap_protect_pde().
4541                                  */
4542                                 if (pmap_protect_pde(pmap, pde, sva, prot))
4543                                         anychanged = TRUE;
4544                                 continue;
4545                         } else if (!pmap_demote_pde(pmap, pde, sva)) {
4546                                 /*
4547                                  * The large page mapping was destroyed.
4548                                  */
4549                                 continue;
4550                         }
4551                 }
4552
4553                 if (va_next > eva)
4554                         va_next = eva;
4555
4556                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4557                     sva += PAGE_SIZE) {
4558                         pt_entry_t obits, pbits;
4559                         vm_page_t m;
4560
4561 retry:
4562                         obits = pbits = *pte;
4563                         if ((pbits & PG_V) == 0)
4564                                 continue;
4565
4566                         if ((prot & VM_PROT_WRITE) == 0) {
4567                                 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4568                                     (PG_MANAGED | PG_M | PG_RW)) {
4569                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4570                                         vm_page_dirty(m);
4571                                 }
4572                                 pbits &= ~(PG_RW | PG_M);
4573                         }
4574                         if ((prot & VM_PROT_EXECUTE) == 0)
4575                                 pbits |= pg_nx;
4576
4577                         if (pbits != obits) {
4578                                 if (!atomic_cmpset_long(pte, obits, pbits))
4579                                         goto retry;
4580                                 if (obits & PG_G)
4581                                         pmap_invalidate_page(pmap, sva);
4582                                 else
4583                                         anychanged = TRUE;
4584                         }
4585                 }
4586         }
4587         if (anychanged)
4588                 pmap_invalidate_all(pmap);
4589         PMAP_UNLOCK(pmap);
4590 }
4591
4592 #if VM_NRESERVLEVEL > 0
4593 static bool
4594 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
4595 {
4596
4597         if (pmap->pm_type != PT_EPT)
4598                 return (false);
4599         return ((pde & EPT_PG_EXECUTE) != 0);
4600 }
4601
4602 /*
4603  * Tries to promote the 512, contiguous 4KB page mappings that are within a
4604  * single page table page (PTP) to a single 2MB page mapping.  For promotion
4605  * to occur, two conditions must be met: (1) the 4KB page mappings must map
4606  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4607  * identical characteristics. 
4608  */
4609 static void
4610 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4611     struct rwlock **lockp)
4612 {
4613         pd_entry_t newpde;
4614         pt_entry_t *firstpte, oldpte, pa, *pte;
4615         pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4616         vm_page_t mpte;
4617         int PG_PTE_CACHE;
4618
4619         PG_A = pmap_accessed_bit(pmap);
4620         PG_G = pmap_global_bit(pmap);
4621         PG_M = pmap_modified_bit(pmap);
4622         PG_V = pmap_valid_bit(pmap);
4623         PG_RW = pmap_rw_bit(pmap);
4624         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4625
4626         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4627
4628         /*
4629          * Examine the first PTE in the specified PTP.  Abort if this PTE is
4630          * either invalid, unused, or does not map the first 4KB physical page
4631          * within a 2MB page. 
4632          */
4633         firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4634 setpde:
4635         newpde = *firstpte;
4636         if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V) ||
4637             !pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
4638             newpde))) {
4639                 atomic_add_long(&pmap_pde_p_failures, 1);
4640                 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4641                     " in pmap %p", va, pmap);
4642                 return;
4643         }
4644         if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4645                 /*
4646                  * When PG_M is already clear, PG_RW can be cleared without
4647                  * a TLB invalidation.
4648                  */
4649                 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4650                         goto setpde;
4651                 newpde &= ~PG_RW;
4652         }
4653
4654         /*
4655          * Examine each of the other PTEs in the specified PTP.  Abort if this
4656          * PTE maps an unexpected 4KB physical page or does not have identical
4657          * characteristics to the first PTE.
4658          */
4659         pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4660         for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4661 setpte:
4662                 oldpte = *pte;
4663                 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4664                         atomic_add_long(&pmap_pde_p_failures, 1);
4665                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4666                             " in pmap %p", va, pmap);
4667                         return;
4668                 }
4669                 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4670                         /*
4671                          * When PG_M is already clear, PG_RW can be cleared
4672                          * without a TLB invalidation.
4673                          */
4674                         if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4675                                 goto setpte;
4676                         oldpte &= ~PG_RW;
4677                         CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4678                             " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4679                             (va & ~PDRMASK), pmap);
4680                 }
4681                 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4682                         atomic_add_long(&pmap_pde_p_failures, 1);
4683                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4684                             " in pmap %p", va, pmap);
4685                         return;
4686                 }
4687                 pa -= PAGE_SIZE;
4688         }
4689
4690         /*
4691          * Save the page table page in its current state until the PDE
4692          * mapping the superpage is demoted by pmap_demote_pde() or
4693          * destroyed by pmap_remove_pde(). 
4694          */
4695         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4696         KASSERT(mpte >= vm_page_array &&
4697             mpte < &vm_page_array[vm_page_array_size],
4698             ("pmap_promote_pde: page table page is out of range"));
4699         KASSERT(mpte->pindex == pmap_pde_pindex(va),
4700             ("pmap_promote_pde: page table page's pindex is wrong"));
4701         if (pmap_insert_pt_page(pmap, mpte)) {
4702                 atomic_add_long(&pmap_pde_p_failures, 1);
4703                 CTR2(KTR_PMAP,
4704                     "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4705                     pmap);
4706                 return;
4707         }
4708
4709         /*
4710          * Promote the pv entries.
4711          */
4712         if ((newpde & PG_MANAGED) != 0)
4713                 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4714
4715         /*
4716          * Propagate the PAT index to its proper position.
4717          */
4718         newpde = pmap_swap_pat(pmap, newpde);
4719
4720         /*
4721          * Map the superpage.
4722          */
4723         if (workaround_erratum383)
4724                 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4725         else
4726                 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4727
4728         atomic_add_long(&pmap_pde_promotions, 1);
4729         CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4730             " in pmap %p", va, pmap);
4731 }
4732 #endif /* VM_NRESERVLEVEL > 0 */
4733
4734 /*
4735  *      Insert the given physical page (p) at
4736  *      the specified virtual address (v) in the
4737  *      target physical map with the protection requested.
4738  *
4739  *      If specified, the page will be wired down, meaning
4740  *      that the related pte can not be reclaimed.
4741  *
4742  *      NB:  This is the only routine which MAY NOT lazy-evaluate
4743  *      or lose information.  That is, this routine must actually
4744  *      insert this page into the given map NOW.
4745  *
4746  *      When destroying both a page table and PV entry, this function
4747  *      performs the TLB invalidation before releasing the PV list
4748  *      lock, so we do not need pmap_delayed_invl_page() calls here.
4749  */
4750 int
4751 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4752     u_int flags, int8_t psind)
4753 {
4754         struct rwlock *lock;
4755         pd_entry_t *pde;
4756         pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4757         pt_entry_t newpte, origpte;
4758         pv_entry_t pv;
4759         vm_paddr_t opa, pa;
4760         vm_page_t mpte, om;
4761         int rv;
4762         boolean_t nosleep;
4763
4764         PG_A = pmap_accessed_bit(pmap);
4765         PG_G = pmap_global_bit(pmap);
4766         PG_M = pmap_modified_bit(pmap);
4767         PG_V = pmap_valid_bit(pmap);
4768         PG_RW = pmap_rw_bit(pmap);
4769
4770         va = trunc_page(va);
4771         KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4772         KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4773             ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4774             va));
4775         KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4776             va >= kmi.clean_eva,
4777             ("pmap_enter: managed mapping within the clean submap"));
4778         if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4779                 VM_OBJECT_ASSERT_LOCKED(m->object);
4780         KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4781             ("pmap_enter: flags %u has reserved bits set", flags));
4782         pa = VM_PAGE_TO_PHYS(m);
4783         newpte = (pt_entry_t)(pa | PG_A | PG_V);
4784         if ((flags & VM_PROT_WRITE) != 0)
4785                 newpte |= PG_M;
4786         if ((prot & VM_PROT_WRITE) != 0)
4787                 newpte |= PG_RW;
4788         KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4789             ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4790         if ((prot & VM_PROT_EXECUTE) == 0)
4791                 newpte |= pg_nx;
4792         if ((flags & PMAP_ENTER_WIRED) != 0)
4793                 newpte |= PG_W;
4794         if (va < VM_MAXUSER_ADDRESS)
4795                 newpte |= PG_U;
4796         if (pmap == kernel_pmap)
4797                 newpte |= PG_G;
4798         newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4799
4800         /*
4801          * Set modified bit gratuitously for writeable mappings if
4802          * the page is unmanaged. We do not want to take a fault
4803          * to do the dirty bit accounting for these mappings.
4804          */
4805         if ((m->oflags & VPO_UNMANAGED) != 0) {
4806                 if ((newpte & PG_RW) != 0)
4807                         newpte |= PG_M;
4808         } else
4809                 newpte |= PG_MANAGED;
4810
4811         lock = NULL;
4812         PMAP_LOCK(pmap);
4813         if (psind == 1) {
4814                 /* Assert the required virtual and physical alignment. */ 
4815                 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4816                 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4817                 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4818                 goto out;
4819         }
4820         mpte = NULL;
4821
4822         /*
4823          * In the case that a page table page is not
4824          * resident, we are creating it here.
4825          */
4826 retry:
4827         pde = pmap_pde(pmap, va);
4828         if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4829             pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4830                 pte = pmap_pde_to_pte(pde, va);
4831                 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4832                         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4833                         mpte->wire_count++;
4834                 }
4835         } else if (va < VM_MAXUSER_ADDRESS) {
4836                 /*
4837                  * Here if the pte page isn't mapped, or if it has been
4838                  * deallocated.
4839                  */
4840                 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4841                 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4842                     nosleep ? NULL : &lock);
4843                 if (mpte == NULL && nosleep) {
4844                         rv = KERN_RESOURCE_SHORTAGE;
4845                         goto out;
4846                 }
4847                 goto retry;
4848         } else
4849                 panic("pmap_enter: invalid page directory va=%#lx", va);
4850
4851         origpte = *pte;
4852         pv = NULL;
4853
4854         /*
4855          * Is the specified virtual address already mapped?
4856          */
4857         if ((origpte & PG_V) != 0) {
4858                 /*
4859                  * Wiring change, just update stats. We don't worry about
4860                  * wiring PT pages as they remain resident as long as there
4861                  * are valid mappings in them. Hence, if a user page is wired,
4862                  * the PT page will be also.
4863                  */
4864                 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4865                         pmap->pm_stats.wired_count++;
4866                 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4867                         pmap->pm_stats.wired_count--;
4868
4869                 /*
4870                  * Remove the extra PT page reference.
4871                  */
4872                 if (mpte != NULL) {
4873                         mpte->wire_count--;
4874                         KASSERT(mpte->wire_count > 0,
4875                             ("pmap_enter: missing reference to page table page,"
4876                              " va: 0x%lx", va));
4877                 }
4878
4879                 /*
4880                  * Has the physical page changed?
4881                  */
4882                 opa = origpte & PG_FRAME;
4883                 if (opa == pa) {
4884                         /*
4885                          * No, might be a protection or wiring change.
4886                          */
4887                         if ((origpte & PG_MANAGED) != 0 &&
4888                             (newpte & PG_RW) != 0)
4889                                 vm_page_aflag_set(m, PGA_WRITEABLE);
4890                         if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4891                                 goto unchanged;
4892                         goto validate;
4893                 }
4894
4895                 /*
4896                  * The physical page has changed.  Temporarily invalidate
4897                  * the mapping.  This ensures that all threads sharing the
4898                  * pmap keep a consistent view of the mapping, which is
4899                  * necessary for the correct handling of COW faults.  It
4900                  * also permits reuse of the old mapping's PV entry,
4901                  * avoiding an allocation.
4902                  *
4903                  * For consistency, handle unmanaged mappings the same way.
4904                  */
4905                 origpte = pte_load_clear(pte);
4906                 KASSERT((origpte & PG_FRAME) == opa,
4907                     ("pmap_enter: unexpected pa update for %#lx", va));
4908                 if ((origpte & PG_MANAGED) != 0) {
4909                         om = PHYS_TO_VM_PAGE(opa);
4910
4911                         /*
4912                          * The pmap lock is sufficient to synchronize with
4913                          * concurrent calls to pmap_page_test_mappings() and
4914                          * pmap_ts_referenced().
4915                          */
4916                         if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4917                                 vm_page_dirty(om);
4918                         if ((origpte & PG_A) != 0)
4919                                 vm_page_aflag_set(om, PGA_REFERENCED);
4920                         CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4921                         pv = pmap_pvh_remove(&om->md, pmap, va);
4922                         if ((newpte & PG_MANAGED) == 0)
4923                                 free_pv_entry(pmap, pv);
4924                         if ((om->aflags & PGA_WRITEABLE) != 0 &&
4925                             TAILQ_EMPTY(&om->md.pv_list) &&
4926                             ((om->flags & PG_FICTITIOUS) != 0 ||
4927                             TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4928                                 vm_page_aflag_clear(om, PGA_WRITEABLE);
4929                 }
4930                 if ((origpte & PG_A) != 0)
4931                         pmap_invalidate_page(pmap, va);
4932                 origpte = 0;
4933         } else {
4934                 /*
4935                  * Increment the counters.
4936                  */
4937                 if ((newpte & PG_W) != 0)
4938                         pmap->pm_stats.wired_count++;
4939                 pmap_resident_count_inc(pmap, 1);
4940         }
4941
4942         /*
4943          * Enter on the PV list if part of our managed memory.
4944          */
4945         if ((newpte & PG_MANAGED) != 0) {
4946                 if (pv == NULL) {
4947                         pv = get_pv_entry(pmap, &lock);
4948                         pv->pv_va = va;
4949                 }
4950                 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4951                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4952                 m->md.pv_gen++;
4953                 if ((newpte & PG_RW) != 0)
4954                         vm_page_aflag_set(m, PGA_WRITEABLE);
4955         }
4956
4957         /*
4958          * Update the PTE.
4959          */
4960         if ((origpte & PG_V) != 0) {
4961 validate:
4962                 origpte = pte_load_store(pte, newpte);
4963                 KASSERT((origpte & PG_FRAME) == pa,
4964                     ("pmap_enter: unexpected pa update for %#lx", va));
4965                 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4966                     (PG_M | PG_RW)) {
4967                         if ((origpte & PG_MANAGED) != 0)
4968                                 vm_page_dirty(m);
4969
4970                         /*
4971                          * Although the PTE may still have PG_RW set, TLB
4972                          * invalidation may nonetheless be required because
4973                          * the PTE no longer has PG_M set.
4974                          */
4975                 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4976                         /*
4977                          * This PTE change does not require TLB invalidation.
4978                          */
4979                         goto unchanged;
4980                 }
4981                 if ((origpte & PG_A) != 0)
4982                         pmap_invalidate_page(pmap, va);
4983         } else
4984                 pte_store(pte, newpte);
4985
4986 unchanged:
4987
4988 #if VM_NRESERVLEVEL > 0
4989         /*
4990          * If both the page table page and the reservation are fully
4991          * populated, then attempt promotion.
4992          */
4993         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4994             pmap_ps_enabled(pmap) &&
4995             (m->flags & PG_FICTITIOUS) == 0 &&
4996             vm_reserv_level_iffullpop(m) == 0)
4997                 pmap_promote_pde(pmap, pde, va, &lock);
4998 #endif
4999
5000         rv = KERN_SUCCESS;
5001 out:
5002         if (lock != NULL)
5003                 rw_wunlock(lock);
5004         PMAP_UNLOCK(pmap);
5005         return (rv);
5006 }
5007
5008 /*
5009  * Tries to create a read- and/or execute-only 2MB page mapping.  Returns true
5010  * if successful.  Returns false if (1) a page table page cannot be allocated
5011  * without sleeping, (2) a mapping already exists at the specified virtual
5012  * address, or (3) a PV entry cannot be allocated without reclaiming another
5013  * PV entry.
5014  */
5015 static bool
5016 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5017     struct rwlock **lockp)
5018 {
5019         pd_entry_t newpde;
5020         pt_entry_t PG_V;
5021
5022         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5023         PG_V = pmap_valid_bit(pmap);
5024         newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
5025             PG_PS | PG_V;
5026         if ((m->oflags & VPO_UNMANAGED) == 0)
5027                 newpde |= PG_MANAGED;
5028         if ((prot & VM_PROT_EXECUTE) == 0)
5029                 newpde |= pg_nx;
5030         if (va < VM_MAXUSER_ADDRESS)
5031                 newpde |= PG_U;
5032         return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
5033             PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
5034             KERN_SUCCESS);
5035 }
5036
5037 /*
5038  * Tries to create the specified 2MB page mapping.  Returns KERN_SUCCESS if
5039  * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
5040  * otherwise.  Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
5041  * a mapping already exists at the specified virtual address.  Returns
5042  * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
5043  * page allocation failed.  Returns KERN_RESOURCE_SHORTAGE if
5044  * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
5045  *
5046  * The parameter "m" is only used when creating a managed, writeable mapping.
5047  */
5048 static int
5049 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
5050     vm_page_t m, struct rwlock **lockp)
5051 {
5052         struct spglist free;
5053         pd_entry_t oldpde, *pde;
5054         pt_entry_t PG_G, PG_RW, PG_V;
5055         vm_page_t mt, pdpg;
5056
5057         PG_G = pmap_global_bit(pmap);
5058         PG_RW = pmap_rw_bit(pmap);
5059         KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
5060             ("pmap_enter_pde: newpde is missing PG_M"));
5061         PG_V = pmap_valid_bit(pmap);
5062         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5063
5064         if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
5065             newpde))) {
5066                 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
5067                     " in pmap %p", va, pmap);
5068                 return (KERN_FAILURE);
5069         }
5070         if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5071             NULL : lockp)) == NULL) {
5072                 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5073                     " in pmap %p", va, pmap);
5074                 return (KERN_RESOURCE_SHORTAGE);
5075         }
5076         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5077         pde = &pde[pmap_pde_index(va)];
5078         oldpde = *pde;
5079         if ((oldpde & PG_V) != 0) {
5080                 KASSERT(pdpg->wire_count > 1,
5081                     ("pmap_enter_pde: pdpg's wire count is too low"));
5082                 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5083                         pdpg->wire_count--;
5084                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5085                             " in pmap %p", va, pmap);
5086                         return (KERN_FAILURE);
5087                 }
5088                 /* Break the existing mapping(s). */
5089                 SLIST_INIT(&free);
5090                 if ((oldpde & PG_PS) != 0) {
5091                         /*
5092                          * The reference to the PD page that was acquired by
5093                          * pmap_allocpde() ensures that it won't be freed.
5094                          * However, if the PDE resulted from a promotion, then
5095                          * a reserved PT page could be freed.
5096                          */
5097                         (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5098                         if ((oldpde & PG_G) == 0)
5099                                 pmap_invalidate_pde_page(pmap, va, oldpde);
5100                 } else {
5101                         pmap_delayed_invl_started();
5102                         if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5103                             lockp))
5104                                pmap_invalidate_all(pmap);
5105                         pmap_delayed_invl_finished();
5106                 }
5107                 pmap_free_zero_pages(&free);
5108                 if (va >= VM_MAXUSER_ADDRESS) {
5109                         mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5110                         if (pmap_insert_pt_page(pmap, mt)) {
5111                                 /*
5112                                  * XXX Currently, this can't happen because
5113                                  * we do not perform pmap_enter(psind == 1)
5114                                  * on the kernel pmap.
5115                                  */
5116                                 panic("pmap_enter_pde: trie insert failed");
5117                         }
5118                 } else
5119                         KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5120                             pde));
5121         }
5122         if ((newpde & PG_MANAGED) != 0) {
5123                 /*
5124                  * Abort this mapping if its PV entry could not be created.
5125                  */
5126                 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5127                         SLIST_INIT(&free);
5128                         if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5129                                 /*
5130                                  * Although "va" is not mapped, paging-
5131                                  * structure caches could nonetheless have
5132                                  * entries that refer to the freed page table
5133                                  * pages.  Invalidate those entries.
5134                                  */
5135                                 pmap_invalidate_page(pmap, va);
5136                                 pmap_free_zero_pages(&free);
5137                         }
5138                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5139                             " in pmap %p", va, pmap);
5140                         return (KERN_RESOURCE_SHORTAGE);
5141                 }
5142                 if ((newpde & PG_RW) != 0) {
5143                         for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5144                                 vm_page_aflag_set(mt, PGA_WRITEABLE);
5145                 }
5146         }
5147
5148         /*
5149          * Increment counters.
5150          */
5151         if ((newpde & PG_W) != 0)
5152                 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5153         pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5154
5155         /*
5156          * Map the superpage.  (This is not a promoted mapping; there will not
5157          * be any lingering 4KB page mappings in the TLB.)
5158          */
5159         pde_store(pde, newpde);
5160
5161         atomic_add_long(&pmap_pde_mappings, 1);
5162         CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5163             " in pmap %p", va, pmap);
5164         return (KERN_SUCCESS);
5165 }
5166
5167 /*
5168  * Maps a sequence of resident pages belonging to the same object.
5169  * The sequence begins with the given page m_start.  This page is
5170  * mapped at the given virtual address start.  Each subsequent page is
5171  * mapped at a virtual address that is offset from start by the same
5172  * amount as the page is offset from m_start within the object.  The
5173  * last page in the sequence is the page with the largest offset from
5174  * m_start that can be mapped at a virtual address less than the given
5175  * virtual address end.  Not every virtual page between start and end
5176  * is mapped; only those for which a resident page exists with the
5177  * corresponding offset from m_start are mapped.
5178  */
5179 void
5180 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5181     vm_page_t m_start, vm_prot_t prot)
5182 {
5183         struct rwlock *lock;
5184         vm_offset_t va;
5185         vm_page_t m, mpte;
5186         vm_pindex_t diff, psize;
5187
5188         VM_OBJECT_ASSERT_LOCKED(m_start->object);
5189
5190         psize = atop(end - start);
5191         mpte = NULL;
5192         m = m_start;
5193         lock = NULL;
5194         PMAP_LOCK(pmap);
5195         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5196                 va = start + ptoa(diff);
5197                 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5198                     m->psind == 1 && pmap_ps_enabled(pmap) &&
5199                     pmap_allow_2m_x_page(pmap, (prot & VM_PROT_EXECUTE) != 0) &&
5200                     pmap_enter_2mpage(pmap, va, m, prot, &lock))
5201                         m = &m[NBPDR / PAGE_SIZE - 1];
5202                 else
5203                         mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5204                             mpte, &lock);
5205                 m = TAILQ_NEXT(m, listq);
5206         }
5207         if (lock != NULL)
5208                 rw_wunlock(lock);
5209         PMAP_UNLOCK(pmap);
5210 }
5211
5212 /*
5213  * this code makes some *MAJOR* assumptions:
5214  * 1. Current pmap & pmap exists.
5215  * 2. Not wired.
5216  * 3. Read access.
5217  * 4. No page table pages.
5218  * but is *MUCH* faster than pmap_enter...
5219  */
5220
5221 void
5222 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5223 {
5224         struct rwlock *lock;
5225
5226         lock = NULL;
5227         PMAP_LOCK(pmap);
5228         (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5229         if (lock != NULL)
5230                 rw_wunlock(lock);
5231         PMAP_UNLOCK(pmap);
5232 }
5233
5234 static vm_page_t
5235 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5236     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5237 {
5238         struct spglist free;
5239         pt_entry_t newpte, *pte, PG_V;
5240
5241         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5242             (m->oflags & VPO_UNMANAGED) != 0,
5243             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5244         PG_V = pmap_valid_bit(pmap);
5245         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5246
5247         /*
5248          * In the case that a page table page is not
5249          * resident, we are creating it here.
5250          */
5251         if (va < VM_MAXUSER_ADDRESS) {
5252                 vm_pindex_t ptepindex;
5253                 pd_entry_t *ptepa;
5254
5255                 /*
5256                  * Calculate pagetable page index
5257                  */
5258                 ptepindex = pmap_pde_pindex(va);
5259                 if (mpte && (mpte->pindex == ptepindex)) {
5260                         mpte->wire_count++;
5261                 } else {
5262                         /*
5263                          * Get the page directory entry
5264                          */
5265                         ptepa = pmap_pde(pmap, va);
5266
5267                         /*
5268                          * If the page table page is mapped, we just increment
5269                          * the hold count, and activate it.  Otherwise, we
5270                          * attempt to allocate a page table page.  If this
5271                          * attempt fails, we don't retry.  Instead, we give up.
5272                          */
5273                         if (ptepa && (*ptepa & PG_V) != 0) {
5274                                 if (*ptepa & PG_PS)
5275                                         return (NULL);
5276                                 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5277                                 mpte->wire_count++;
5278                         } else {
5279                                 /*
5280                                  * Pass NULL instead of the PV list lock
5281                                  * pointer, because we don't intend to sleep.
5282                                  */
5283                                 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5284                                 if (mpte == NULL)
5285                                         return (mpte);
5286                         }
5287                 }
5288                 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5289                 pte = &pte[pmap_pte_index(va)];
5290         } else {
5291                 mpte = NULL;
5292                 pte = vtopte(va);
5293         }
5294         if (*pte) {
5295                 if (mpte != NULL) {
5296                         mpte->wire_count--;
5297                         mpte = NULL;
5298                 }
5299                 return (mpte);
5300         }
5301
5302         /*
5303          * Enter on the PV list if part of our managed memory.
5304          */
5305         if ((m->oflags & VPO_UNMANAGED) == 0 &&
5306             !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5307                 if (mpte != NULL) {
5308                         SLIST_INIT(&free);
5309                         if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5310                                 /*
5311                                  * Although "va" is not mapped, paging-
5312                                  * structure caches could nonetheless have
5313                                  * entries that refer to the freed page table
5314                                  * pages.  Invalidate those entries.
5315                                  */
5316                                 pmap_invalidate_page(pmap, va);
5317                                 pmap_free_zero_pages(&free);
5318                         }
5319                         mpte = NULL;
5320                 }
5321                 return (mpte);
5322         }
5323
5324         /*
5325          * Increment counters
5326          */
5327         pmap_resident_count_inc(pmap, 1);
5328
5329         newpte = VM_PAGE_TO_PHYS(m) | PG_V |
5330             pmap_cache_bits(pmap, m->md.pat_mode, 0);
5331         if ((m->oflags & VPO_UNMANAGED) == 0)
5332                 newpte |= PG_MANAGED;
5333         if ((prot & VM_PROT_EXECUTE) == 0)
5334                 newpte |= pg_nx;
5335         if (va < VM_MAXUSER_ADDRESS)
5336                 newpte |= PG_U;
5337         pte_store(pte, newpte);
5338         return (mpte);
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 void *
5346 pmap_kenter_temporary(vm_paddr_t pa, int i)
5347 {
5348         vm_offset_t va;
5349
5350         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5351         pmap_kenter(va, pa);
5352         invlpg(va);
5353         return ((void *)crashdumpmap);
5354 }
5355
5356 /*
5357  * This code maps large physical mmap regions into the
5358  * processor address space.  Note that some shortcuts
5359  * are taken, but the code works.
5360  */
5361 void
5362 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5363     vm_pindex_t pindex, vm_size_t size)
5364 {
5365         pd_entry_t *pde;
5366         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5367         vm_paddr_t pa, ptepa;
5368         vm_page_t p, pdpg;
5369         int pat_mode;
5370
5371         PG_A = pmap_accessed_bit(pmap);
5372         PG_M = pmap_modified_bit(pmap);
5373         PG_V = pmap_valid_bit(pmap);
5374         PG_RW = pmap_rw_bit(pmap);
5375
5376         VM_OBJECT_ASSERT_WLOCKED(object);
5377         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5378             ("pmap_object_init_pt: non-device object"));
5379         if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5380                 if (!pmap_ps_enabled(pmap))
5381                         return;
5382                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5383                         return;
5384                 p = vm_page_lookup(object, pindex);
5385                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5386                     ("pmap_object_init_pt: invalid page %p", p));
5387                 pat_mode = p->md.pat_mode;
5388
5389                 /*
5390                  * Abort the mapping if the first page is not physically
5391                  * aligned to a 2MB page boundary.
5392                  */
5393                 ptepa = VM_PAGE_TO_PHYS(p);
5394                 if (ptepa & (NBPDR - 1))
5395                         return;
5396
5397                 /*
5398                  * Skip the first page.  Abort the mapping if the rest of
5399                  * the pages are not physically contiguous or have differing
5400                  * memory attributes.
5401                  */
5402                 p = TAILQ_NEXT(p, listq);
5403                 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5404                     pa += PAGE_SIZE) {
5405                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
5406                             ("pmap_object_init_pt: invalid page %p", p));
5407                         if (pa != VM_PAGE_TO_PHYS(p) ||
5408                             pat_mode != p->md.pat_mode)
5409                                 return;
5410                         p = TAILQ_NEXT(p, listq);
5411                 }
5412
5413                 /*
5414                  * Map using 2MB pages.  Since "ptepa" is 2M aligned and
5415                  * "size" is a multiple of 2M, adding the PAT setting to "pa"
5416                  * will not affect the termination of this loop.
5417                  */ 
5418                 PMAP_LOCK(pmap);
5419                 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5420                     pa < ptepa + size; pa += NBPDR) {
5421                         pdpg = pmap_allocpde(pmap, addr, NULL);
5422                         if (pdpg == NULL) {
5423                                 /*
5424                                  * The creation of mappings below is only an
5425                                  * optimization.  If a page directory page
5426                                  * cannot be allocated without blocking,
5427                                  * continue on to the next mapping rather than
5428                                  * blocking.
5429                                  */
5430                                 addr += NBPDR;
5431                                 continue;
5432                         }
5433                         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5434                         pde = &pde[pmap_pde_index(addr)];
5435                         if ((*pde & PG_V) == 0) {
5436                                 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5437                                     PG_U | PG_RW | PG_V);
5438                                 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5439                                 atomic_add_long(&pmap_pde_mappings, 1);
5440                         } else {
5441                                 /* Continue on if the PDE is already valid. */
5442                                 pdpg->wire_count--;
5443                                 KASSERT(pdpg->wire_count > 0,
5444                                     ("pmap_object_init_pt: missing reference "
5445                                     "to page directory page, va: 0x%lx", addr));
5446                         }
5447                         addr += NBPDR;
5448                 }
5449                 PMAP_UNLOCK(pmap);
5450         }
5451 }
5452
5453 /*
5454  *      Clear the wired attribute from the mappings for the specified range of
5455  *      addresses in the given pmap.  Every valid mapping within that range
5456  *      must have the wired attribute set.  In contrast, invalid mappings
5457  *      cannot have the wired attribute set, so they are ignored.
5458  *
5459  *      The wired attribute of the page table entry is not a hardware
5460  *      feature, so there is no need to invalidate any TLB entries.
5461  *      Since pmap_demote_pde() for the wired entry must never fail,
5462  *      pmap_delayed_invl_started()/finished() calls around the
5463  *      function are not needed.
5464  */
5465 void
5466 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5467 {
5468         vm_offset_t va_next;
5469         pml4_entry_t *pml4e;
5470         pdp_entry_t *pdpe;
5471         pd_entry_t *pde;
5472         pt_entry_t *pte, PG_V;
5473
5474         PG_V = pmap_valid_bit(pmap);
5475         PMAP_LOCK(pmap);
5476         for (; sva < eva; sva = va_next) {
5477                 pml4e = pmap_pml4e(pmap, sva);
5478                 if ((*pml4e & PG_V) == 0) {
5479                         va_next = (sva + NBPML4) & ~PML4MASK;
5480                         if (va_next < sva)
5481                                 va_next = eva;
5482                         continue;
5483                 }
5484                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5485                 if ((*pdpe & PG_V) == 0) {
5486                         va_next = (sva + NBPDP) & ~PDPMASK;
5487                         if (va_next < sva)
5488                                 va_next = eva;
5489                         continue;
5490                 }
5491                 va_next = (sva + NBPDR) & ~PDRMASK;
5492                 if (va_next < sva)
5493                         va_next = eva;
5494                 pde = pmap_pdpe_to_pde(pdpe, sva);
5495                 if ((*pde & PG_V) == 0)
5496                         continue;
5497                 if ((*pde & PG_PS) != 0) {
5498                         if ((*pde & PG_W) == 0)
5499                                 panic("pmap_unwire: pde %#jx is missing PG_W",
5500                                     (uintmax_t)*pde);
5501
5502                         /*
5503                          * Are we unwiring the entire large page?  If not,
5504                          * demote the mapping and fall through.
5505                          */
5506                         if (sva + NBPDR == va_next && eva >= va_next) {
5507                                 atomic_clear_long(pde, PG_W);
5508                                 pmap->pm_stats.wired_count -= NBPDR /
5509                                     PAGE_SIZE;
5510                                 continue;
5511                         } else if (!pmap_demote_pde(pmap, pde, sva))
5512                                 panic("pmap_unwire: demotion failed");
5513                 }
5514                 if (va_next > eva)
5515                         va_next = eva;
5516                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5517                     sva += PAGE_SIZE) {
5518                         if ((*pte & PG_V) == 0)
5519                                 continue;
5520                         if ((*pte & PG_W) == 0)
5521                                 panic("pmap_unwire: pte %#jx is missing PG_W",
5522                                     (uintmax_t)*pte);
5523
5524                         /*
5525                          * PG_W must be cleared atomically.  Although the pmap
5526                          * lock synchronizes access to PG_W, another processor
5527                          * could be setting PG_M and/or PG_A concurrently.
5528                          */
5529                         atomic_clear_long(pte, PG_W);
5530                         pmap->pm_stats.wired_count--;
5531                 }
5532         }
5533         PMAP_UNLOCK(pmap);
5534 }
5535
5536 /*
5537  *      Copy the range specified by src_addr/len
5538  *      from the source map to the range dst_addr/len
5539  *      in the destination map.
5540  *
5541  *      This routine is only advisory and need not do anything.
5542  */
5543
5544 void
5545 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5546     vm_offset_t src_addr)
5547 {
5548         struct rwlock *lock;
5549         struct spglist free;
5550         vm_offset_t addr;
5551         vm_offset_t end_addr = src_addr + len;
5552         vm_offset_t va_next;
5553         vm_page_t dst_pdpg, dstmpte, srcmpte;
5554         pt_entry_t PG_A, PG_M, PG_V;
5555
5556         if (dst_addr != src_addr)
5557                 return;
5558
5559         if (dst_pmap->pm_type != src_pmap->pm_type)
5560                 return;
5561
5562         /*
5563          * EPT page table entries that require emulation of A/D bits are
5564          * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5565          * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5566          * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5567          * implementations flag an EPT misconfiguration for exec-only
5568          * mappings we skip this function entirely for emulated pmaps.
5569          */
5570         if (pmap_emulate_ad_bits(dst_pmap))
5571                 return;
5572
5573         lock = NULL;
5574         if (dst_pmap < src_pmap) {
5575                 PMAP_LOCK(dst_pmap);
5576                 PMAP_LOCK(src_pmap);
5577         } else {
5578                 PMAP_LOCK(src_pmap);
5579                 PMAP_LOCK(dst_pmap);
5580         }
5581
5582         PG_A = pmap_accessed_bit(dst_pmap);
5583         PG_M = pmap_modified_bit(dst_pmap);
5584         PG_V = pmap_valid_bit(dst_pmap);
5585
5586         for (addr = src_addr; addr < end_addr; addr = va_next) {
5587                 pt_entry_t *src_pte, *dst_pte;
5588                 pml4_entry_t *pml4e;
5589                 pdp_entry_t *pdpe;
5590                 pd_entry_t srcptepaddr, *pde;
5591
5592                 KASSERT(addr < UPT_MIN_ADDRESS,
5593                     ("pmap_copy: invalid to pmap_copy page tables"));
5594
5595                 pml4e = pmap_pml4e(src_pmap, addr);
5596                 if ((*pml4e & PG_V) == 0) {
5597                         va_next = (addr + NBPML4) & ~PML4MASK;
5598                         if (va_next < addr)
5599                                 va_next = end_addr;
5600                         continue;
5601                 }
5602
5603                 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5604                 if ((*pdpe & PG_V) == 0) {
5605                         va_next = (addr + NBPDP) & ~PDPMASK;
5606                         if (va_next < addr)
5607                                 va_next = end_addr;
5608                         continue;
5609                 }
5610
5611                 va_next = (addr + NBPDR) & ~PDRMASK;
5612                 if (va_next < addr)
5613                         va_next = end_addr;
5614
5615                 pde = pmap_pdpe_to_pde(pdpe, addr);
5616                 srcptepaddr = *pde;
5617                 if (srcptepaddr == 0)
5618                         continue;
5619                         
5620                 if (srcptepaddr & PG_PS) {
5621                         if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5622                                 continue;
5623                         dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5624                         if (dst_pdpg == NULL)
5625                                 break;
5626                         pde = (pd_entry_t *)
5627                             PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5628                         pde = &pde[pmap_pde_index(addr)];
5629                         if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5630                             pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5631                             PMAP_ENTER_NORECLAIM, &lock))) {
5632                                 *pde = srcptepaddr & ~PG_W;
5633                                 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5634                                 atomic_add_long(&pmap_pde_mappings, 1);
5635                         } else
5636                                 dst_pdpg->wire_count--;
5637                         continue;
5638                 }
5639
5640                 srcptepaddr &= PG_FRAME;
5641                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5642                 KASSERT(srcmpte->wire_count > 0,
5643                     ("pmap_copy: source page table page is unused"));
5644
5645                 if (va_next > end_addr)
5646                         va_next = end_addr;
5647
5648                 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5649                 src_pte = &src_pte[pmap_pte_index(addr)];
5650                 dstmpte = NULL;
5651                 while (addr < va_next) {
5652                         pt_entry_t ptetemp;
5653                         ptetemp = *src_pte;
5654                         /*
5655                          * we only virtual copy managed pages
5656                          */
5657                         if ((ptetemp & PG_MANAGED) != 0) {
5658                                 if (dstmpte != NULL &&
5659                                     dstmpte->pindex == pmap_pde_pindex(addr))
5660                                         dstmpte->wire_count++;
5661                                 else if ((dstmpte = pmap_allocpte(dst_pmap,
5662                                     addr, NULL)) == NULL)
5663                                         goto out;
5664                                 dst_pte = (pt_entry_t *)
5665                                     PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5666                                 dst_pte = &dst_pte[pmap_pte_index(addr)];
5667                                 if (*dst_pte == 0 &&
5668                                     pmap_try_insert_pv_entry(dst_pmap, addr,
5669                                     PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5670                                     &lock)) {
5671                                         /*
5672                                          * Clear the wired, modified, and
5673                                          * accessed (referenced) bits
5674                                          * during the copy.
5675                                          */
5676                                         *dst_pte = ptetemp & ~(PG_W | PG_M |
5677                                             PG_A);
5678                                         pmap_resident_count_inc(dst_pmap, 1);
5679                                 } else {
5680                                         SLIST_INIT(&free);
5681                                         if (pmap_unwire_ptp(dst_pmap, addr,
5682                                             dstmpte, &free)) {
5683                                                 /*
5684                                                  * Although "addr" is not
5685                                                  * mapped, paging-structure
5686                                                  * caches could nonetheless
5687                                                  * have entries that refer to
5688                                                  * the freed page table pages.
5689                                                  * Invalidate those entries.
5690                                                  */
5691                                                 pmap_invalidate_page(dst_pmap,
5692                                                     addr);
5693                                                 pmap_free_zero_pages(&free);
5694                                         }
5695                                         goto out;
5696                                 }
5697                                 if (dstmpte->wire_count >= srcmpte->wire_count)
5698                                         break;
5699                         }
5700                         addr += PAGE_SIZE;
5701                         src_pte++;
5702                 }
5703         }
5704 out:
5705         if (lock != NULL)
5706                 rw_wunlock(lock);
5707         PMAP_UNLOCK(src_pmap);
5708         PMAP_UNLOCK(dst_pmap);
5709 }
5710
5711 /*
5712  *      pmap_zero_page zeros the specified hardware page by mapping
5713  *      the page into KVM and using bzero to clear its contents.
5714  */
5715 void
5716 pmap_zero_page(vm_page_t m)
5717 {
5718         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5719
5720         pagezero((void *)va);
5721 }
5722
5723 /*
5724  *      pmap_zero_page_area zeros the specified hardware page by mapping 
5725  *      the page into KVM and using bzero to clear its contents.
5726  *
5727  *      off and size may not cover an area beyond a single hardware page.
5728  */
5729 void
5730 pmap_zero_page_area(vm_page_t m, int off, int size)
5731 {
5732         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5733
5734         if (off == 0 && size == PAGE_SIZE)
5735                 pagezero((void *)va);
5736         else
5737                 bzero((char *)va + off, size);
5738 }
5739
5740 /*
5741  *      pmap_zero_page_idle zeros the specified hardware page by mapping 
5742  *      the page into KVM and using bzero to clear its contents.  This
5743  *      is intended to be called from the vm_pagezero process only and
5744  *      outside of Giant.
5745  */
5746 void
5747 pmap_zero_page_idle(vm_page_t m)
5748 {
5749         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5750
5751         pagezero((void *)va);
5752 }
5753
5754 /*
5755  *      pmap_copy_page copies the specified (machine independent)
5756  *      page by mapping the page into virtual memory and using
5757  *      bcopy to copy the page, one machine dependent page at a
5758  *      time.
5759  */
5760 void
5761 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5762 {
5763         vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5764         vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5765
5766         pagecopy((void *)src, (void *)dst);
5767 }
5768
5769 int unmapped_buf_allowed = 1;
5770
5771 void
5772 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5773     vm_offset_t b_offset, int xfersize)
5774 {
5775         void *a_cp, *b_cp;
5776         vm_page_t pages[2];
5777         vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5778         int cnt;
5779         boolean_t mapped;
5780
5781         while (xfersize > 0) {
5782                 a_pg_offset = a_offset & PAGE_MASK;
5783                 pages[0] = ma[a_offset >> PAGE_SHIFT];
5784                 b_pg_offset = b_offset & PAGE_MASK;
5785                 pages[1] = mb[b_offset >> PAGE_SHIFT];
5786                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5787                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5788                 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5789                 a_cp = (char *)vaddr[0] + a_pg_offset;
5790                 b_cp = (char *)vaddr[1] + b_pg_offset;
5791                 bcopy(a_cp, b_cp, cnt);
5792                 if (__predict_false(mapped))
5793                         pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5794                 a_offset += cnt;
5795                 b_offset += cnt;
5796                 xfersize -= cnt;
5797         }
5798 }
5799
5800 /*
5801  * Returns true if the pmap's pv is one of the first
5802  * 16 pvs linked to from this page.  This count may
5803  * be changed upwards or downwards in the future; it
5804  * is only necessary that true be returned for a small
5805  * subset of pmaps for proper page aging.
5806  */
5807 boolean_t
5808 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5809 {
5810         struct md_page *pvh;
5811         struct rwlock *lock;
5812         pv_entry_t pv;
5813         int loops = 0;
5814         boolean_t rv;
5815
5816         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5817             ("pmap_page_exists_quick: page %p is not managed", m));
5818         rv = FALSE;
5819         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5820         rw_rlock(lock);
5821         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5822                 if (PV_PMAP(pv) == pmap) {
5823                         rv = TRUE;
5824                         break;
5825                 }
5826                 loops++;
5827                 if (loops >= 16)
5828                         break;
5829         }
5830         if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5831                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5832                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5833                         if (PV_PMAP(pv) == pmap) {
5834                                 rv = TRUE;
5835                                 break;
5836                         }
5837                         loops++;
5838                         if (loops >= 16)
5839                                 break;
5840                 }
5841         }
5842         rw_runlock(lock);
5843         return (rv);
5844 }
5845
5846 /*
5847  *      pmap_page_wired_mappings:
5848  *
5849  *      Return the number of managed mappings to the given physical page
5850  *      that are wired.
5851  */
5852 int
5853 pmap_page_wired_mappings(vm_page_t m)
5854 {
5855         struct rwlock *lock;
5856         struct md_page *pvh;
5857         pmap_t pmap;
5858         pt_entry_t *pte;
5859         pv_entry_t pv;
5860         int count, md_gen, pvh_gen;
5861
5862         if ((m->oflags & VPO_UNMANAGED) != 0)
5863                 return (0);
5864         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5865         rw_rlock(lock);
5866 restart:
5867         count = 0;
5868         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5869                 pmap = PV_PMAP(pv);
5870                 if (!PMAP_TRYLOCK(pmap)) {
5871                         md_gen = m->md.pv_gen;
5872                         rw_runlock(lock);
5873                         PMAP_LOCK(pmap);
5874                         rw_rlock(lock);
5875                         if (md_gen != m->md.pv_gen) {
5876                                 PMAP_UNLOCK(pmap);
5877                                 goto restart;
5878                         }
5879                 }
5880                 pte = pmap_pte(pmap, pv->pv_va);
5881                 if ((*pte & PG_W) != 0)
5882                         count++;
5883                 PMAP_UNLOCK(pmap);
5884         }
5885         if ((m->flags & PG_FICTITIOUS) == 0) {
5886                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5887                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5888                         pmap = PV_PMAP(pv);
5889                         if (!PMAP_TRYLOCK(pmap)) {
5890                                 md_gen = m->md.pv_gen;
5891                                 pvh_gen = pvh->pv_gen;
5892                                 rw_runlock(lock);
5893                                 PMAP_LOCK(pmap);
5894                                 rw_rlock(lock);
5895                                 if (md_gen != m->md.pv_gen ||
5896                                     pvh_gen != pvh->pv_gen) {
5897                                         PMAP_UNLOCK(pmap);
5898                                         goto restart;
5899                                 }
5900                         }
5901                         pte = pmap_pde(pmap, pv->pv_va);
5902                         if ((*pte & PG_W) != 0)
5903                                 count++;
5904                         PMAP_UNLOCK(pmap);
5905                 }
5906         }
5907         rw_runlock(lock);
5908         return (count);
5909 }
5910
5911 /*
5912  * Returns TRUE if the given page is mapped individually or as part of
5913  * a 2mpage.  Otherwise, returns FALSE.
5914  */
5915 boolean_t
5916 pmap_page_is_mapped(vm_page_t m)
5917 {
5918         struct rwlock *lock;
5919         boolean_t rv;
5920
5921         if ((m->oflags & VPO_UNMANAGED) != 0)
5922                 return (FALSE);
5923         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5924         rw_rlock(lock);
5925         rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5926             ((m->flags & PG_FICTITIOUS) == 0 &&
5927             !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5928         rw_runlock(lock);
5929         return (rv);
5930 }
5931
5932 /*
5933  * Destroy all managed, non-wired mappings in the given user-space
5934  * pmap.  This pmap cannot be active on any processor besides the
5935  * caller.
5936  *
5937  * This function cannot be applied to the kernel pmap.  Moreover, it
5938  * is not intended for general use.  It is only to be used during
5939  * process termination.  Consequently, it can be implemented in ways
5940  * that make it faster than pmap_remove().  First, it can more quickly
5941  * destroy mappings by iterating over the pmap's collection of PV
5942  * entries, rather than searching the page table.  Second, it doesn't
5943  * have to test and clear the page table entries atomically, because
5944  * no processor is currently accessing the user address space.  In
5945  * particular, a page table entry's dirty bit won't change state once
5946  * this function starts.
5947  *
5948  * Although this function destroys all of the pmap's managed,
5949  * non-wired mappings, it can delay and batch the invalidation of TLB
5950  * entries without calling pmap_delayed_invl_started() and
5951  * pmap_delayed_invl_finished().  Because the pmap is not active on
5952  * any other processor, none of these TLB entries will ever be used
5953  * before their eventual invalidation.  Consequently, there is no need
5954  * for either pmap_remove_all() or pmap_remove_write() to wait for
5955  * that eventual TLB invalidation.
5956  */
5957 void
5958 pmap_remove_pages(pmap_t pmap)
5959 {
5960         pd_entry_t ptepde;
5961         pt_entry_t *pte, tpte;
5962         pt_entry_t PG_M, PG_RW, PG_V;
5963         struct spglist free;
5964         vm_page_t m, mpte, mt;
5965         pv_entry_t pv;
5966         struct md_page *pvh;
5967         struct pv_chunk *pc, *npc;
5968         struct rwlock *lock;
5969         int64_t bit;
5970         uint64_t inuse, bitmask;
5971         int allfree, field, freed, idx;
5972         boolean_t superpage;
5973         vm_paddr_t pa;
5974
5975         /*
5976          * Assert that the given pmap is only active on the current
5977          * CPU.  Unfortunately, we cannot block another CPU from
5978          * activating the pmap while this function is executing.
5979          */
5980         KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5981 #ifdef INVARIANTS
5982         {
5983                 cpuset_t other_cpus;
5984
5985                 other_cpus = all_cpus;
5986                 critical_enter();
5987                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5988                 CPU_AND(&other_cpus, &pmap->pm_active);
5989                 critical_exit();
5990                 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5991         }
5992 #endif
5993
5994         lock = NULL;
5995         PG_M = pmap_modified_bit(pmap);
5996         PG_V = pmap_valid_bit(pmap);
5997         PG_RW = pmap_rw_bit(pmap);
5998
5999         SLIST_INIT(&free);
6000         PMAP_LOCK(pmap);
6001         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
6002                 allfree = 1;
6003                 freed = 0;
6004                 for (field = 0; field < _NPCM; field++) {
6005                         inuse = ~pc->pc_map[field] & pc_freemask[field];
6006                         while (inuse != 0) {
6007                                 bit = bsfq(inuse);
6008                                 bitmask = 1UL << bit;
6009                                 idx = field * 64 + bit;
6010                                 pv = &pc->pc_pventry[idx];
6011                                 inuse &= ~bitmask;
6012
6013                                 pte = pmap_pdpe(pmap, pv->pv_va);
6014                                 ptepde = *pte;
6015                                 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
6016                                 tpte = *pte;
6017                                 if ((tpte & (PG_PS | PG_V)) == PG_V) {
6018                                         superpage = FALSE;
6019                                         ptepde = tpte;
6020                                         pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
6021                                             PG_FRAME);
6022                                         pte = &pte[pmap_pte_index(pv->pv_va)];
6023                                         tpte = *pte;
6024                                 } else {
6025                                         /*
6026                                          * Keep track whether 'tpte' is a
6027                                          * superpage explicitly instead of
6028                                          * relying on PG_PS being set.
6029                                          *
6030                                          * This is because PG_PS is numerically
6031                                          * identical to PG_PTE_PAT and thus a
6032                                          * regular page could be mistaken for
6033                                          * a superpage.
6034                                          */
6035                                         superpage = TRUE;
6036                                 }
6037
6038                                 if ((tpte & PG_V) == 0) {
6039                                         panic("bad pte va %lx pte %lx",
6040                                             pv->pv_va, tpte);
6041                                 }
6042
6043 /*
6044  * We cannot remove wired pages from a process' mapping at this time
6045  */
6046                                 if (tpte & PG_W) {
6047                                         allfree = 0;
6048                                         continue;
6049                                 }
6050
6051                                 if (superpage)
6052                                         pa = tpte & PG_PS_FRAME;
6053                                 else
6054                                         pa = tpte & PG_FRAME;
6055
6056                                 m = PHYS_TO_VM_PAGE(pa);
6057                                 KASSERT(m->phys_addr == pa,
6058                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6059                                     m, (uintmax_t)m->phys_addr,
6060                                     (uintmax_t)tpte));
6061
6062                                 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6063                                     m < &vm_page_array[vm_page_array_size],
6064                                     ("pmap_remove_pages: bad tpte %#jx",
6065                                     (uintmax_t)tpte));
6066
6067                                 pte_clear(pte);
6068
6069                                 /*
6070                                  * Update the vm_page_t clean/reference bits.
6071                                  */
6072                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6073                                         if (superpage) {
6074                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6075                                                         vm_page_dirty(mt);
6076                                         } else
6077                                                 vm_page_dirty(m);
6078                                 }
6079
6080                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6081
6082                                 /* Mark free */
6083                                 pc->pc_map[field] |= bitmask;
6084                                 if (superpage) {
6085                                         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6086                                         pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6087                                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6088                                         pvh->pv_gen++;
6089                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
6090                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6091                                                         if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6092                                                             TAILQ_EMPTY(&mt->md.pv_list))
6093                                                                 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6094                                         }
6095                                         mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6096                                         if (mpte != NULL) {
6097                                                 pmap_resident_count_dec(pmap, 1);
6098                                                 KASSERT(mpte->wire_count == NPTEPG,
6099                                                     ("pmap_remove_pages: pte page wire count error"));
6100                                                 mpte->wire_count = 0;
6101                                                 pmap_add_delayed_free_list(mpte, &free, FALSE);
6102                                         }
6103                                 } else {
6104                                         pmap_resident_count_dec(pmap, 1);
6105                                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6106                                         m->md.pv_gen++;
6107                                         if ((m->aflags & PGA_WRITEABLE) != 0 &&
6108                                             TAILQ_EMPTY(&m->md.pv_list) &&
6109                                             (m->flags & PG_FICTITIOUS) == 0) {
6110                                                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6111                                                 if (TAILQ_EMPTY(&pvh->pv_list))
6112                                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
6113                                         }
6114                                 }
6115                                 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6116                                 freed++;
6117                         }
6118                 }
6119                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6120                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6121                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6122                 if (allfree) {
6123                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6124                         free_pv_chunk(pc);
6125                 }
6126         }
6127         if (lock != NULL)
6128                 rw_wunlock(lock);
6129         pmap_invalidate_all(pmap);
6130         PMAP_UNLOCK(pmap);
6131         pmap_free_zero_pages(&free);
6132 }
6133
6134 static boolean_t
6135 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6136 {
6137         struct rwlock *lock;
6138         pv_entry_t pv;
6139         struct md_page *pvh;
6140         pt_entry_t *pte, mask;
6141         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6142         pmap_t pmap;
6143         int md_gen, pvh_gen;
6144         boolean_t rv;
6145
6146         rv = FALSE;
6147         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6148         rw_rlock(lock);
6149 restart:
6150         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6151                 pmap = PV_PMAP(pv);
6152                 if (!PMAP_TRYLOCK(pmap)) {
6153                         md_gen = m->md.pv_gen;
6154                         rw_runlock(lock);
6155                         PMAP_LOCK(pmap);
6156                         rw_rlock(lock);
6157                         if (md_gen != m->md.pv_gen) {
6158                                 PMAP_UNLOCK(pmap);
6159                                 goto restart;
6160                         }
6161                 }
6162                 pte = pmap_pte(pmap, pv->pv_va);
6163                 mask = 0;
6164                 if (modified) {
6165                         PG_M = pmap_modified_bit(pmap);
6166                         PG_RW = pmap_rw_bit(pmap);
6167                         mask |= PG_RW | PG_M;
6168                 }
6169                 if (accessed) {
6170                         PG_A = pmap_accessed_bit(pmap);
6171                         PG_V = pmap_valid_bit(pmap);
6172                         mask |= PG_V | PG_A;
6173                 }
6174                 rv = (*pte & mask) == mask;
6175                 PMAP_UNLOCK(pmap);
6176                 if (rv)
6177                         goto out;
6178         }
6179         if ((m->flags & PG_FICTITIOUS) == 0) {
6180                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6181                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6182                         pmap = PV_PMAP(pv);
6183                         if (!PMAP_TRYLOCK(pmap)) {
6184                                 md_gen = m->md.pv_gen;
6185                                 pvh_gen = pvh->pv_gen;
6186                                 rw_runlock(lock);
6187                                 PMAP_LOCK(pmap);
6188                                 rw_rlock(lock);
6189                                 if (md_gen != m->md.pv_gen ||
6190                                     pvh_gen != pvh->pv_gen) {
6191                                         PMAP_UNLOCK(pmap);
6192                                         goto restart;
6193                                 }
6194                         }
6195                         pte = pmap_pde(pmap, pv->pv_va);
6196                         mask = 0;
6197                         if (modified) {
6198                                 PG_M = pmap_modified_bit(pmap);
6199                                 PG_RW = pmap_rw_bit(pmap);
6200                                 mask |= PG_RW | PG_M;
6201                         }
6202                         if (accessed) {
6203                                 PG_A = pmap_accessed_bit(pmap);
6204                                 PG_V = pmap_valid_bit(pmap);
6205                                 mask |= PG_V | PG_A;
6206                         }
6207                         rv = (*pte & mask) == mask;
6208                         PMAP_UNLOCK(pmap);
6209                         if (rv)
6210                                 goto out;
6211                 }
6212         }
6213 out:
6214         rw_runlock(lock);
6215         return (rv);
6216 }
6217
6218 /*
6219  *      pmap_is_modified:
6220  *
6221  *      Return whether or not the specified physical page was modified
6222  *      in any physical maps.
6223  */
6224 boolean_t
6225 pmap_is_modified(vm_page_t m)
6226 {
6227
6228         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6229             ("pmap_is_modified: page %p is not managed", m));
6230
6231         /*
6232          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6233          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
6234          * is clear, no PTEs can have PG_M set.
6235          */
6236         VM_OBJECT_ASSERT_WLOCKED(m->object);
6237         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6238                 return (FALSE);
6239         return (pmap_page_test_mappings(m, FALSE, TRUE));
6240 }
6241
6242 /*
6243  *      pmap_is_prefaultable:
6244  *
6245  *      Return whether or not the specified virtual address is eligible
6246  *      for prefault.
6247  */
6248 boolean_t
6249 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6250 {
6251         pd_entry_t *pde;
6252         pt_entry_t *pte, PG_V;
6253         boolean_t rv;
6254
6255         PG_V = pmap_valid_bit(pmap);
6256         rv = FALSE;
6257         PMAP_LOCK(pmap);
6258         pde = pmap_pde(pmap, addr);
6259         if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6260                 pte = pmap_pde_to_pte(pde, addr);
6261                 rv = (*pte & PG_V) == 0;
6262         }
6263         PMAP_UNLOCK(pmap);
6264         return (rv);
6265 }
6266
6267 /*
6268  *      pmap_is_referenced:
6269  *
6270  *      Return whether or not the specified physical page was referenced
6271  *      in any physical maps.
6272  */
6273 boolean_t
6274 pmap_is_referenced(vm_page_t m)
6275 {
6276
6277         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6278             ("pmap_is_referenced: page %p is not managed", m));
6279         return (pmap_page_test_mappings(m, TRUE, FALSE));
6280 }
6281
6282 /*
6283  * Clear the write and modified bits in each of the given page's mappings.
6284  */
6285 void
6286 pmap_remove_write(vm_page_t m)
6287 {
6288         struct md_page *pvh;
6289         pmap_t pmap;
6290         struct rwlock *lock;
6291         pv_entry_t next_pv, pv;
6292         pd_entry_t *pde;
6293         pt_entry_t oldpte, *pte, PG_M, PG_RW;
6294         vm_offset_t va;
6295         int pvh_gen, md_gen;
6296
6297         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6298             ("pmap_remove_write: page %p is not managed", m));
6299
6300         /*
6301          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6302          * set by another thread while the object is locked.  Thus,
6303          * if PGA_WRITEABLE is clear, no page table entries need updating.
6304          */
6305         VM_OBJECT_ASSERT_WLOCKED(m->object);
6306         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6307                 return;
6308         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6309         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6310             pa_to_pvh(VM_PAGE_TO_PHYS(m));
6311 retry_pv_loop:
6312         rw_wlock(lock);
6313         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6314                 pmap = PV_PMAP(pv);
6315                 if (!PMAP_TRYLOCK(pmap)) {
6316                         pvh_gen = pvh->pv_gen;
6317                         rw_wunlock(lock);
6318                         PMAP_LOCK(pmap);
6319                         rw_wlock(lock);
6320                         if (pvh_gen != pvh->pv_gen) {
6321                                 PMAP_UNLOCK(pmap);
6322                                 rw_wunlock(lock);
6323                                 goto retry_pv_loop;
6324                         }
6325                 }
6326                 PG_RW = pmap_rw_bit(pmap);
6327                 va = pv->pv_va;
6328                 pde = pmap_pde(pmap, va);
6329                 if ((*pde & PG_RW) != 0)
6330                         (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6331                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6332                     ("inconsistent pv lock %p %p for page %p",
6333                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6334                 PMAP_UNLOCK(pmap);
6335         }
6336         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6337                 pmap = PV_PMAP(pv);
6338                 if (!PMAP_TRYLOCK(pmap)) {
6339                         pvh_gen = pvh->pv_gen;
6340                         md_gen = m->md.pv_gen;
6341                         rw_wunlock(lock);
6342                         PMAP_LOCK(pmap);
6343                         rw_wlock(lock);
6344                         if (pvh_gen != pvh->pv_gen ||
6345                             md_gen != m->md.pv_gen) {
6346                                 PMAP_UNLOCK(pmap);
6347                                 rw_wunlock(lock);
6348                                 goto retry_pv_loop;
6349                         }
6350                 }
6351                 PG_M = pmap_modified_bit(pmap);
6352                 PG_RW = pmap_rw_bit(pmap);
6353                 pde = pmap_pde(pmap, pv->pv_va);
6354                 KASSERT((*pde & PG_PS) == 0,
6355                     ("pmap_remove_write: found a 2mpage in page %p's pv list",
6356                     m));
6357                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6358 retry:
6359                 oldpte = *pte;
6360                 if (oldpte & PG_RW) {
6361                         if (!atomic_cmpset_long(pte, oldpte, oldpte &
6362                             ~(PG_RW | PG_M)))
6363                                 goto retry;
6364                         if ((oldpte & PG_M) != 0)
6365                                 vm_page_dirty(m);
6366                         pmap_invalidate_page(pmap, pv->pv_va);
6367                 }
6368                 PMAP_UNLOCK(pmap);
6369         }
6370         rw_wunlock(lock);
6371         vm_page_aflag_clear(m, PGA_WRITEABLE);
6372         pmap_delayed_invl_wait(m);
6373 }
6374
6375 static __inline boolean_t
6376 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6377 {
6378
6379         if (!pmap_emulate_ad_bits(pmap))
6380                 return (TRUE);
6381
6382         KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6383
6384         /*
6385          * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6386          * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6387          * if the EPT_PG_WRITE bit is set.
6388          */
6389         if ((pte & EPT_PG_WRITE) != 0)
6390                 return (FALSE);
6391
6392         /*
6393          * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6394          */
6395         if ((pte & EPT_PG_EXECUTE) == 0 ||
6396             ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6397                 return (TRUE);
6398         else
6399                 return (FALSE);
6400 }
6401
6402 /*
6403  *      pmap_ts_referenced:
6404  *
6405  *      Return a count of reference bits for a page, clearing those bits.
6406  *      It is not necessary for every reference bit to be cleared, but it
6407  *      is necessary that 0 only be returned when there are truly no
6408  *      reference bits set.
6409  *
6410  *      As an optimization, update the page's dirty field if a modified bit is
6411  *      found while counting reference bits.  This opportunistic update can be
6412  *      performed at low cost and can eliminate the need for some future calls
6413  *      to pmap_is_modified().  However, since this function stops after
6414  *      finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6415  *      dirty pages.  Those dirty pages will only be detected by a future call
6416  *      to pmap_is_modified().
6417  *
6418  *      A DI block is not needed within this function, because
6419  *      invalidations are performed before the PV list lock is
6420  *      released.
6421  */
6422 int
6423 pmap_ts_referenced(vm_page_t m)
6424 {
6425         struct md_page *pvh;
6426         pv_entry_t pv, pvf;
6427         pmap_t pmap;
6428         struct rwlock *lock;
6429         pd_entry_t oldpde, *pde;
6430         pt_entry_t *pte, PG_A, PG_M, PG_RW;
6431         vm_offset_t va;
6432         vm_paddr_t pa;
6433         int cleared, md_gen, not_cleared, pvh_gen;
6434         struct spglist free;
6435         boolean_t demoted;
6436
6437         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6438             ("pmap_ts_referenced: page %p is not managed", m));
6439         SLIST_INIT(&free);
6440         cleared = 0;
6441         pa = VM_PAGE_TO_PHYS(m);
6442         lock = PHYS_TO_PV_LIST_LOCK(pa);
6443         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6444         rw_wlock(lock);
6445 retry:
6446         not_cleared = 0;
6447         if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6448                 goto small_mappings;
6449         pv = pvf;
6450         do {
6451                 if (pvf == NULL)
6452                         pvf = pv;
6453                 pmap = PV_PMAP(pv);
6454                 if (!PMAP_TRYLOCK(pmap)) {
6455                         pvh_gen = pvh->pv_gen;
6456                         rw_wunlock(lock);
6457                         PMAP_LOCK(pmap);
6458                         rw_wlock(lock);
6459                         if (pvh_gen != pvh->pv_gen) {
6460                                 PMAP_UNLOCK(pmap);
6461                                 goto retry;
6462                         }
6463                 }
6464                 PG_A = pmap_accessed_bit(pmap);
6465                 PG_M = pmap_modified_bit(pmap);
6466                 PG_RW = pmap_rw_bit(pmap);
6467                 va = pv->pv_va;
6468                 pde = pmap_pde(pmap, pv->pv_va);
6469                 oldpde = *pde;
6470                 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6471                         /*
6472                          * Although "oldpde" is mapping a 2MB page, because
6473                          * this function is called at a 4KB page granularity,
6474                          * we only update the 4KB page under test.
6475                          */
6476                         vm_page_dirty(m);
6477                 }
6478                 if ((oldpde & PG_A) != 0) {
6479                         /*
6480                          * Since this reference bit is shared by 512 4KB
6481                          * pages, it should not be cleared every time it is
6482                          * tested.  Apply a simple "hash" function on the
6483                          * physical page number, the virtual superpage number,
6484                          * and the pmap address to select one 4KB page out of
6485                          * the 512 on which testing the reference bit will
6486                          * result in clearing that reference bit.  This
6487                          * function is designed to avoid the selection of the
6488                          * same 4KB page for every 2MB page mapping.
6489                          *
6490                          * On demotion, a mapping that hasn't been referenced
6491                          * is simply destroyed.  To avoid the possibility of a
6492                          * subsequent page fault on a demoted wired mapping,
6493                          * always leave its reference bit set.  Moreover,
6494                          * since the superpage is wired, the current state of
6495                          * its reference bit won't affect page replacement.
6496                          */
6497                         if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6498                             (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6499                             (oldpde & PG_W) == 0) {
6500                                 if (safe_to_clear_referenced(pmap, oldpde)) {
6501                                         atomic_clear_long(pde, PG_A);
6502                                         pmap_invalidate_page(pmap, pv->pv_va);
6503                                         demoted = FALSE;
6504                                 } else if (pmap_demote_pde_locked(pmap, pde,
6505                                     pv->pv_va, &lock)) {
6506                                         /*
6507                                          * Remove the mapping to a single page
6508                                          * so that a subsequent access may
6509                                          * repromote.  Since the underlying
6510                                          * page table page is fully populated,
6511                                          * this removal never frees a page
6512                                          * table page.
6513                                          */
6514                                         demoted = TRUE;
6515                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
6516                                             PG_PS_FRAME);
6517                                         pte = pmap_pde_to_pte(pde, va);
6518                                         pmap_remove_pte(pmap, pte, va, *pde,
6519                                             NULL, &lock);
6520                                         pmap_invalidate_page(pmap, va);
6521                                 } else
6522                                         demoted = TRUE;
6523
6524                                 if (demoted) {
6525                                         /*
6526                                          * The superpage mapping was removed
6527                                          * entirely and therefore 'pv' is no
6528                                          * longer valid.
6529                                          */
6530                                         if (pvf == pv)
6531                                                 pvf = NULL;
6532                                         pv = NULL;
6533                                 }
6534                                 cleared++;
6535                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6536                                     ("inconsistent pv lock %p %p for page %p",
6537                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6538                         } else
6539                                 not_cleared++;
6540                 }
6541                 PMAP_UNLOCK(pmap);
6542                 /* Rotate the PV list if it has more than one entry. */
6543                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6544                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6545                         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6546                         pvh->pv_gen++;
6547                 }
6548                 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6549                         goto out;
6550         } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6551 small_mappings:
6552         if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6553                 goto out;
6554         pv = pvf;
6555         do {
6556                 if (pvf == NULL)
6557                         pvf = pv;
6558                 pmap = PV_PMAP(pv);
6559                 if (!PMAP_TRYLOCK(pmap)) {
6560                         pvh_gen = pvh->pv_gen;
6561                         md_gen = m->md.pv_gen;
6562                         rw_wunlock(lock);
6563                         PMAP_LOCK(pmap);
6564                         rw_wlock(lock);
6565                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6566                                 PMAP_UNLOCK(pmap);
6567                                 goto retry;
6568                         }
6569                 }
6570                 PG_A = pmap_accessed_bit(pmap);
6571                 PG_M = pmap_modified_bit(pmap);
6572                 PG_RW = pmap_rw_bit(pmap);
6573                 pde = pmap_pde(pmap, pv->pv_va);
6574                 KASSERT((*pde & PG_PS) == 0,
6575                     ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6576                     m));
6577                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6578                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6579                         vm_page_dirty(m);
6580                 if ((*pte & PG_A) != 0) {
6581                         if (safe_to_clear_referenced(pmap, *pte)) {
6582                                 atomic_clear_long(pte, PG_A);
6583                                 pmap_invalidate_page(pmap, pv->pv_va);
6584                                 cleared++;
6585                         } else if ((*pte & PG_W) == 0) {
6586                                 /*
6587                                  * Wired pages cannot be paged out so
6588                                  * doing accessed bit emulation for
6589                                  * them is wasted effort. We do the
6590                                  * hard work for unwired pages only.
6591                                  */
6592                                 pmap_remove_pte(pmap, pte, pv->pv_va,
6593                                     *pde, &free, &lock);
6594                                 pmap_invalidate_page(pmap, pv->pv_va);
6595                                 cleared++;
6596                                 if (pvf == pv)
6597                                         pvf = NULL;
6598                                 pv = NULL;
6599                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6600                                     ("inconsistent pv lock %p %p for page %p",
6601                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6602                         } else
6603                                 not_cleared++;
6604                 }
6605                 PMAP_UNLOCK(pmap);
6606                 /* Rotate the PV list if it has more than one entry. */
6607                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6608                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6609                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6610                         m->md.pv_gen++;
6611                 }
6612         } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6613             not_cleared < PMAP_TS_REFERENCED_MAX);
6614 out:
6615         rw_wunlock(lock);
6616         pmap_free_zero_pages(&free);
6617         return (cleared + not_cleared);
6618 }
6619
6620 /*
6621  *      Apply the given advice to the specified range of addresses within the
6622  *      given pmap.  Depending on the advice, clear the referenced and/or
6623  *      modified flags in each mapping and set the mapped page's dirty field.
6624  */
6625 void
6626 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6627 {
6628         struct rwlock *lock;
6629         pml4_entry_t *pml4e;
6630         pdp_entry_t *pdpe;
6631         pd_entry_t oldpde, *pde;
6632         pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6633         vm_offset_t va, va_next;
6634         vm_page_t m;
6635         boolean_t anychanged;
6636
6637         if (advice != MADV_DONTNEED && advice != MADV_FREE)
6638                 return;
6639
6640         /*
6641          * A/D bit emulation requires an alternate code path when clearing
6642          * the modified and accessed bits below. Since this function is
6643          * advisory in nature we skip it entirely for pmaps that require
6644          * A/D bit emulation.
6645          */
6646         if (pmap_emulate_ad_bits(pmap))
6647                 return;
6648
6649         PG_A = pmap_accessed_bit(pmap);
6650         PG_G = pmap_global_bit(pmap);
6651         PG_M = pmap_modified_bit(pmap);
6652         PG_V = pmap_valid_bit(pmap);
6653         PG_RW = pmap_rw_bit(pmap);
6654         anychanged = FALSE;
6655         pmap_delayed_invl_started();
6656         PMAP_LOCK(pmap);
6657         for (; sva < eva; sva = va_next) {
6658                 pml4e = pmap_pml4e(pmap, sva);
6659                 if ((*pml4e & PG_V) == 0) {
6660                         va_next = (sva + NBPML4) & ~PML4MASK;
6661                         if (va_next < sva)
6662                                 va_next = eva;
6663                         continue;
6664                 }
6665                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6666                 if ((*pdpe & PG_V) == 0) {
6667                         va_next = (sva + NBPDP) & ~PDPMASK;
6668                         if (va_next < sva)
6669                                 va_next = eva;
6670                         continue;
6671                 }
6672                 va_next = (sva + NBPDR) & ~PDRMASK;
6673                 if (va_next < sva)
6674                         va_next = eva;
6675                 pde = pmap_pdpe_to_pde(pdpe, sva);
6676                 oldpde = *pde;
6677                 if ((oldpde & PG_V) == 0)
6678                         continue;
6679                 else if ((oldpde & PG_PS) != 0) {
6680                         if ((oldpde & PG_MANAGED) == 0)
6681                                 continue;
6682                         lock = NULL;
6683                         if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6684                                 if (lock != NULL)
6685                                         rw_wunlock(lock);
6686
6687                                 /*
6688                                  * The large page mapping was destroyed.
6689                                  */
6690                                 continue;
6691                         }
6692
6693                         /*
6694                          * Unless the page mappings are wired, remove the
6695                          * mapping to a single page so that a subsequent
6696                          * access may repromote.  Since the underlying page
6697                          * table page is fully populated, this removal never
6698                          * frees a page table page.
6699                          */
6700                         if ((oldpde & PG_W) == 0) {
6701                                 pte = pmap_pde_to_pte(pde, sva);
6702                                 KASSERT((*pte & PG_V) != 0,
6703                                     ("pmap_advise: invalid PTE"));
6704                                 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6705                                     &lock);
6706                                 anychanged = TRUE;
6707                         }
6708                         if (lock != NULL)
6709                                 rw_wunlock(lock);
6710                 }
6711                 if (va_next > eva)
6712                         va_next = eva;
6713                 va = va_next;
6714                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6715                     sva += PAGE_SIZE) {
6716                         if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6717                                 goto maybe_invlrng;
6718                         else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6719                                 if (advice == MADV_DONTNEED) {
6720                                         /*
6721                                          * Future calls to pmap_is_modified()
6722                                          * can be avoided by making the page
6723                                          * dirty now.
6724                                          */
6725                                         m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6726                                         vm_page_dirty(m);
6727                                 }
6728                                 atomic_clear_long(pte, PG_M | PG_A);
6729                         } else if ((*pte & PG_A) != 0)
6730                                 atomic_clear_long(pte, PG_A);
6731                         else
6732                                 goto maybe_invlrng;
6733
6734                         if ((*pte & PG_G) != 0) {
6735                                 if (va == va_next)
6736                                         va = sva;
6737                         } else
6738                                 anychanged = TRUE;
6739                         continue;
6740 maybe_invlrng:
6741                         if (va != va_next) {
6742                                 pmap_invalidate_range(pmap, va, sva);
6743                                 va = va_next;
6744                         }
6745                 }
6746                 if (va != va_next)
6747                         pmap_invalidate_range(pmap, va, sva);
6748         }
6749         if (anychanged)
6750                 pmap_invalidate_all(pmap);
6751         PMAP_UNLOCK(pmap);
6752         pmap_delayed_invl_finished();
6753 }
6754
6755 /*
6756  *      Clear the modify bits on the specified physical page.
6757  */
6758 void
6759 pmap_clear_modify(vm_page_t m)
6760 {
6761         struct md_page *pvh;
6762         pmap_t pmap;
6763         pv_entry_t next_pv, pv;
6764         pd_entry_t oldpde, *pde;
6765         pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6766         struct rwlock *lock;
6767         vm_offset_t va;
6768         int md_gen, pvh_gen;
6769
6770         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6771             ("pmap_clear_modify: page %p is not managed", m));
6772         VM_OBJECT_ASSERT_WLOCKED(m->object);
6773         KASSERT(!vm_page_xbusied(m),
6774             ("pmap_clear_modify: page %p is exclusive busied", m));
6775
6776         /*
6777          * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6778          * If the object containing the page is locked and the page is not
6779          * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6780          */
6781         if ((m->aflags & PGA_WRITEABLE) == 0)
6782                 return;
6783         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6784             pa_to_pvh(VM_PAGE_TO_PHYS(m));
6785         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6786         rw_wlock(lock);
6787 restart:
6788         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6789                 pmap = PV_PMAP(pv);
6790                 if (!PMAP_TRYLOCK(pmap)) {
6791                         pvh_gen = pvh->pv_gen;
6792                         rw_wunlock(lock);
6793                         PMAP_LOCK(pmap);
6794                         rw_wlock(lock);
6795                         if (pvh_gen != pvh->pv_gen) {
6796                                 PMAP_UNLOCK(pmap);
6797                                 goto restart;
6798                         }
6799                 }
6800                 PG_M = pmap_modified_bit(pmap);
6801                 PG_V = pmap_valid_bit(pmap);
6802                 PG_RW = pmap_rw_bit(pmap);
6803                 va = pv->pv_va;
6804                 pde = pmap_pde(pmap, va);
6805                 oldpde = *pde;
6806                 if ((oldpde & PG_RW) != 0) {
6807                         if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6808                                 if ((oldpde & PG_W) == 0) {
6809                                         /*
6810                                          * Write protect the mapping to a
6811                                          * single page so that a subsequent
6812                                          * write access may repromote.
6813                                          */
6814                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
6815                                             PG_PS_FRAME);
6816                                         pte = pmap_pde_to_pte(pde, va);
6817                                         oldpte = *pte;
6818                                         if ((oldpte & PG_V) != 0) {
6819                                                 while (!atomic_cmpset_long(pte,
6820                                                     oldpte,
6821                                                     oldpte & ~(PG_M | PG_RW)))
6822                                                         oldpte = *pte;
6823                                                 vm_page_dirty(m);
6824                                                 pmap_invalidate_page(pmap, va);
6825                                         }
6826                                 }
6827                         }
6828                 }
6829                 PMAP_UNLOCK(pmap);
6830         }
6831         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6832                 pmap = PV_PMAP(pv);
6833                 if (!PMAP_TRYLOCK(pmap)) {
6834                         md_gen = m->md.pv_gen;
6835                         pvh_gen = pvh->pv_gen;
6836                         rw_wunlock(lock);
6837                         PMAP_LOCK(pmap);
6838                         rw_wlock(lock);
6839                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6840                                 PMAP_UNLOCK(pmap);
6841                                 goto restart;
6842                         }
6843                 }
6844                 PG_M = pmap_modified_bit(pmap);
6845                 PG_RW = pmap_rw_bit(pmap);
6846                 pde = pmap_pde(pmap, pv->pv_va);
6847                 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6848                     " a 2mpage in page %p's pv list", m));
6849                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6850                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6851                         atomic_clear_long(pte, PG_M);
6852                         pmap_invalidate_page(pmap, pv->pv_va);
6853                 }
6854                 PMAP_UNLOCK(pmap);
6855         }
6856         rw_wunlock(lock);
6857 }
6858
6859 /*
6860  * Miscellaneous support routines follow
6861  */
6862
6863 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6864 static __inline void
6865 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6866 {
6867         u_int opte, npte;
6868
6869         /*
6870          * The cache mode bits are all in the low 32-bits of the
6871          * PTE, so we can just spin on updating the low 32-bits.
6872          */
6873         do {
6874                 opte = *(u_int *)pte;
6875                 npte = opte & ~mask;
6876                 npte |= cache_bits;
6877         } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6878 }
6879
6880 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6881 static __inline void
6882 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6883 {
6884         u_int opde, npde;
6885
6886         /*
6887          * The cache mode bits are all in the low 32-bits of the
6888          * PDE, so we can just spin on updating the low 32-bits.
6889          */
6890         do {
6891                 opde = *(u_int *)pde;
6892                 npde = opde & ~mask;
6893                 npde |= cache_bits;
6894         } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6895 }
6896
6897 /*
6898  * Map a set of physical memory pages into the kernel virtual
6899  * address space. Return a pointer to where it is mapped. This
6900  * routine is intended to be used for mapping device memory,
6901  * NOT real memory.
6902  */
6903 void *
6904 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6905 {
6906         struct pmap_preinit_mapping *ppim;
6907         vm_offset_t va, offset;
6908         vm_size_t tmpsize;
6909         int i;
6910
6911         offset = pa & PAGE_MASK;
6912         size = round_page(offset + size);
6913         pa = trunc_page(pa);
6914
6915         if (!pmap_initialized) {
6916                 va = 0;
6917                 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6918                         ppim = pmap_preinit_mapping + i;
6919                         if (ppim->va == 0) {
6920                                 ppim->pa = pa;
6921                                 ppim->sz = size;
6922                                 ppim->mode = mode;
6923                                 ppim->va = virtual_avail;
6924                                 virtual_avail += size;
6925                                 va = ppim->va;
6926                                 break;
6927                         }
6928                 }
6929                 if (va == 0)
6930                         panic("%s: too many preinit mappings", __func__);
6931         } else {
6932                 /*
6933                  * If we have a preinit mapping, re-use it.
6934                  */
6935                 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6936                         ppim = pmap_preinit_mapping + i;
6937                         if (ppim->pa == pa && ppim->sz == size &&
6938                             ppim->mode == mode)
6939                                 return ((void *)(ppim->va + offset));
6940                 }
6941                 /*
6942                  * If the specified range of physical addresses fits within
6943                  * the direct map window, use the direct map.
6944                  */
6945                 if (pa < dmaplimit && pa + size <= dmaplimit) {
6946                         va = PHYS_TO_DMAP(pa);
6947                         if (!pmap_change_attr(va, size, mode))
6948                                 return ((void *)(va + offset));
6949                 }
6950                 va = kva_alloc(size);
6951                 if (va == 0)
6952                         panic("%s: Couldn't allocate KVA", __func__);
6953         }
6954         for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6955                 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6956         pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6957         pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6958         return ((void *)(va + offset));
6959 }
6960
6961 void *
6962 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6963 {
6964
6965         return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6966 }
6967
6968 void *
6969 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6970 {
6971
6972         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6973 }
6974
6975 void
6976 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6977 {
6978         struct pmap_preinit_mapping *ppim;
6979         vm_offset_t offset;
6980         int i;
6981
6982         /* If we gave a direct map region in pmap_mapdev, do nothing */
6983         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6984                 return;
6985         offset = va & PAGE_MASK;
6986         size = round_page(offset + size);
6987         va = trunc_page(va);
6988         for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6989                 ppim = pmap_preinit_mapping + i;
6990                 if (ppim->va == va && ppim->sz == size) {
6991                         if (pmap_initialized)
6992                                 return;
6993                         ppim->pa = 0;
6994                         ppim->va = 0;
6995                         ppim->sz = 0;
6996                         ppim->mode = 0;
6997                         if (va + size == virtual_avail)
6998                                 virtual_avail = va;
6999                         return;
7000                 }
7001         }
7002         if (pmap_initialized)
7003                 kva_free(va, size);
7004 }
7005
7006 /*
7007  * Tries to demote a 1GB page mapping.
7008  */
7009 static boolean_t
7010 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
7011 {
7012         pdp_entry_t newpdpe, oldpdpe;
7013         pd_entry_t *firstpde, newpde, *pde;
7014         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7015         vm_paddr_t pdpgpa;
7016         vm_page_t pdpg;
7017
7018         PG_A = pmap_accessed_bit(pmap);
7019         PG_M = pmap_modified_bit(pmap);
7020         PG_V = pmap_valid_bit(pmap);
7021         PG_RW = pmap_rw_bit(pmap);
7022
7023         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7024         oldpdpe = *pdpe;
7025         KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
7026             ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
7027         if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
7028             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
7029                 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
7030                     " in pmap %p", va, pmap);
7031                 return (FALSE);
7032         }
7033         pdpgpa = VM_PAGE_TO_PHYS(pdpg);
7034         firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
7035         newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
7036         KASSERT((oldpdpe & PG_A) != 0,
7037             ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
7038         KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
7039             ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
7040         newpde = oldpdpe;
7041
7042         /*
7043          * Initialize the page directory page.
7044          */
7045         for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
7046                 *pde = newpde;
7047                 newpde += NBPDR;
7048         }
7049
7050         /*
7051          * Demote the mapping.
7052          */
7053         *pdpe = newpdpe;
7054
7055         /*
7056          * Invalidate a stale recursive mapping of the page directory page.
7057          */
7058         pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
7059
7060         pmap_pdpe_demotions++;
7061         CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
7062             " in pmap %p", va, pmap);
7063         return (TRUE);
7064 }
7065
7066 /*
7067  * Sets the memory attribute for the specified page.
7068  */
7069 void
7070 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7071 {
7072
7073         m->md.pat_mode = ma;
7074
7075         /*
7076          * If "m" is a normal page, update its direct mapping.  This update
7077          * can be relied upon to perform any cache operations that are
7078          * required for data coherence.
7079          */
7080         if ((m->flags & PG_FICTITIOUS) == 0 &&
7081             pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7082             m->md.pat_mode))
7083                 panic("memory attribute change on the direct map failed");
7084 }
7085
7086 /*
7087  * Changes the specified virtual address range's memory type to that given by
7088  * the parameter "mode".  The specified virtual address range must be
7089  * completely contained within either the direct map or the kernel map.  If
7090  * the virtual address range is contained within the kernel map, then the
7091  * memory type for each of the corresponding ranges of the direct map is also
7092  * changed.  (The corresponding ranges of the direct map are those ranges that
7093  * map the same physical pages as the specified virtual address range.)  These
7094  * changes to the direct map are necessary because Intel describes the
7095  * behavior of their processors as "undefined" if two or more mappings to the
7096  * same physical page have different memory types.
7097  *
7098  * Returns zero if the change completed successfully, and either EINVAL or
7099  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
7100  * of the virtual address range was not mapped, and ENOMEM is returned if
7101  * there was insufficient memory available to complete the change.  In the
7102  * latter case, the memory type may have been changed on some part of the
7103  * virtual address range or the direct map.
7104  */
7105 int
7106 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7107 {
7108         int error;
7109
7110         PMAP_LOCK(kernel_pmap);
7111         error = pmap_change_attr_locked(va, size, mode);
7112         PMAP_UNLOCK(kernel_pmap);
7113         return (error);
7114 }
7115
7116 static int
7117 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7118 {
7119         vm_offset_t base, offset, tmpva;
7120         vm_paddr_t pa_start, pa_end, pa_end1;
7121         pdp_entry_t *pdpe;
7122         pd_entry_t *pde;
7123         pt_entry_t *pte;
7124         int cache_bits_pte, cache_bits_pde, error;
7125         boolean_t changed;
7126
7127         PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7128         base = trunc_page(va);
7129         offset = va & PAGE_MASK;
7130         size = round_page(offset + size);
7131
7132         /*
7133          * Only supported on kernel virtual addresses, including the direct
7134          * map but excluding the recursive map.
7135          */
7136         if (base < DMAP_MIN_ADDRESS)
7137                 return (EINVAL);
7138
7139         cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7140         cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7141         changed = FALSE;
7142
7143         /*
7144          * Pages that aren't mapped aren't supported.  Also break down 2MB pages
7145          * into 4KB pages if required.
7146          */
7147         for (tmpva = base; tmpva < base + size; ) {
7148                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7149                 if (pdpe == NULL || *pdpe == 0)
7150                         return (EINVAL);
7151                 if (*pdpe & PG_PS) {
7152                         /*
7153                          * If the current 1GB page already has the required
7154                          * memory type, then we need not demote this page. Just
7155                          * increment tmpva to the next 1GB page frame.
7156                          */
7157                         if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7158                                 tmpva = trunc_1gpage(tmpva) + NBPDP;
7159                                 continue;
7160                         }
7161
7162                         /*
7163                          * If the current offset aligns with a 1GB page frame
7164                          * and there is at least 1GB left within the range, then
7165                          * we need not break down this page into 2MB pages.
7166                          */
7167                         if ((tmpva & PDPMASK) == 0 &&
7168                             tmpva + PDPMASK < base + size) {
7169                                 tmpva += NBPDP;
7170                                 continue;
7171                         }
7172                         if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7173                                 return (ENOMEM);
7174                 }
7175                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7176                 if (*pde == 0)
7177                         return (EINVAL);
7178                 if (*pde & PG_PS) {
7179                         /*
7180                          * If the current 2MB page already has the required
7181                          * memory type, then we need not demote this page. Just
7182                          * increment tmpva to the next 2MB page frame.
7183                          */
7184                         if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7185                                 tmpva = trunc_2mpage(tmpva) + NBPDR;
7186                                 continue;
7187                         }
7188
7189                         /*
7190                          * If the current offset aligns with a 2MB page frame
7191                          * and there is at least 2MB left within the range, then
7192                          * we need not break down this page into 4KB pages.
7193                          */
7194                         if ((tmpva & PDRMASK) == 0 &&
7195                             tmpva + PDRMASK < base + size) {
7196                                 tmpva += NBPDR;
7197                                 continue;
7198                         }
7199                         if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7200                                 return (ENOMEM);
7201                 }
7202                 pte = pmap_pde_to_pte(pde, tmpva);
7203                 if (*pte == 0)
7204                         return (EINVAL);
7205                 tmpva += PAGE_SIZE;
7206         }
7207         error = 0;
7208
7209         /*
7210          * Ok, all the pages exist, so run through them updating their
7211          * cache mode if required.
7212          */
7213         pa_start = pa_end = 0;
7214         for (tmpva = base; tmpva < base + size; ) {
7215                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7216                 if (*pdpe & PG_PS) {
7217                         if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7218                                 pmap_pde_attr(pdpe, cache_bits_pde,
7219                                     X86_PG_PDE_CACHE);
7220                                 changed = TRUE;
7221                         }
7222                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7223                             (*pdpe & PG_PS_FRAME) < dmaplimit) {
7224                                 if (pa_start == pa_end) {
7225                                         /* Start physical address run. */
7226                                         pa_start = *pdpe & PG_PS_FRAME;
7227                                         pa_end = pa_start + NBPDP;
7228                                 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7229                                         pa_end += NBPDP;
7230                                 else {
7231                                         /* Run ended, update direct map. */
7232                                         error = pmap_change_attr_locked(
7233                                             PHYS_TO_DMAP(pa_start),
7234                                             pa_end - pa_start, mode);
7235                                         if (error != 0)
7236                                                 break;
7237                                         /* Start physical address run. */
7238                                         pa_start = *pdpe & PG_PS_FRAME;
7239                                         pa_end = pa_start + NBPDP;
7240                                 }
7241                         }
7242                         tmpva = trunc_1gpage(tmpva) + NBPDP;
7243                         continue;
7244                 }
7245                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7246                 if (*pde & PG_PS) {
7247                         if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7248                                 pmap_pde_attr(pde, cache_bits_pde,
7249                                     X86_PG_PDE_CACHE);
7250                                 changed = TRUE;
7251                         }
7252                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7253                             (*pde & PG_PS_FRAME) < dmaplimit) {
7254                                 if (pa_start == pa_end) {
7255                                         /* Start physical address run. */
7256                                         pa_start = *pde & PG_PS_FRAME;
7257                                         pa_end = pa_start + NBPDR;
7258                                 } else if (pa_end == (*pde & PG_PS_FRAME))
7259                                         pa_end += NBPDR;
7260                                 else {
7261                                         /* Run ended, update direct map. */
7262                                         error = pmap_change_attr_locked(
7263                                             PHYS_TO_DMAP(pa_start),
7264                                             pa_end - pa_start, mode);
7265                                         if (error != 0)
7266                                                 break;
7267                                         /* Start physical address run. */
7268                                         pa_start = *pde & PG_PS_FRAME;
7269                                         pa_end = pa_start + NBPDR;
7270                                 }
7271                         }
7272                         tmpva = trunc_2mpage(tmpva) + NBPDR;
7273                 } else {
7274                         pte = pmap_pde_to_pte(pde, tmpva);
7275                         if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7276                                 pmap_pte_attr(pte, cache_bits_pte,
7277                                     X86_PG_PTE_CACHE);
7278                                 changed = TRUE;
7279                         }
7280                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7281                             (*pte & PG_FRAME) < dmaplimit) {
7282                                 if (pa_start == pa_end) {
7283                                         /* Start physical address run. */
7284                                         pa_start = *pte & PG_FRAME;
7285                                         pa_end = pa_start + PAGE_SIZE;
7286                                 } else if (pa_end == (*pte & PG_FRAME))
7287                                         pa_end += PAGE_SIZE;
7288                                 else {
7289                                         /* Run ended, update direct map. */
7290                                         error = pmap_change_attr_locked(
7291                                             PHYS_TO_DMAP(pa_start),
7292                                             pa_end - pa_start, mode);
7293                                         if (error != 0)
7294                                                 break;
7295                                         /* Start physical address run. */
7296                                         pa_start = *pte & PG_FRAME;
7297                                         pa_end = pa_start + PAGE_SIZE;
7298                                 }
7299                         }
7300                         tmpva += PAGE_SIZE;
7301                 }
7302         }
7303         if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7304                 pa_end1 = MIN(pa_end, dmaplimit);
7305                 if (pa_start != pa_end1)
7306                         error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7307                             pa_end1 - pa_start, mode);
7308         }
7309
7310         /*
7311          * Flush CPU caches if required to make sure any data isn't cached that
7312          * shouldn't be, etc.
7313          */
7314         if (changed) {
7315                 pmap_invalidate_range(kernel_pmap, base, tmpva);
7316                 pmap_invalidate_cache_range(base, tmpva, FALSE);
7317         }
7318         return (error);
7319 }
7320
7321 /*
7322  * Demotes any mapping within the direct map region that covers more than the
7323  * specified range of physical addresses.  This range's size must be a power
7324  * of two and its starting address must be a multiple of its size.  Since the
7325  * demotion does not change any attributes of the mapping, a TLB invalidation
7326  * is not mandatory.  The caller may, however, request a TLB invalidation.
7327  */
7328 void
7329 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7330 {
7331         pdp_entry_t *pdpe;
7332         pd_entry_t *pde;
7333         vm_offset_t va;
7334         boolean_t changed;
7335
7336         if (len == 0)
7337                 return;
7338         KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7339         KASSERT((base & (len - 1)) == 0,
7340             ("pmap_demote_DMAP: base is not a multiple of len"));
7341         if (len < NBPDP && base < dmaplimit) {
7342                 va = PHYS_TO_DMAP(base);
7343                 changed = FALSE;
7344                 PMAP_LOCK(kernel_pmap);
7345                 pdpe = pmap_pdpe(kernel_pmap, va);
7346                 if ((*pdpe & X86_PG_V) == 0)
7347                         panic("pmap_demote_DMAP: invalid PDPE");
7348                 if ((*pdpe & PG_PS) != 0) {
7349                         if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7350                                 panic("pmap_demote_DMAP: PDPE failed");
7351                         changed = TRUE;
7352                 }
7353                 if (len < NBPDR) {
7354                         pde = pmap_pdpe_to_pde(pdpe, va);
7355                         if ((*pde & X86_PG_V) == 0)
7356                                 panic("pmap_demote_DMAP: invalid PDE");
7357                         if ((*pde & PG_PS) != 0) {
7358                                 if (!pmap_demote_pde(kernel_pmap, pde, va))
7359                                         panic("pmap_demote_DMAP: PDE failed");
7360                                 changed = TRUE;
7361                         }
7362                 }
7363                 if (changed && invalidate)
7364                         pmap_invalidate_page(kernel_pmap, va);
7365                 PMAP_UNLOCK(kernel_pmap);
7366         }
7367 }
7368
7369 /*
7370  * perform the pmap work for mincore
7371  */
7372 int
7373 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7374 {
7375         pd_entry_t *pdep;
7376         pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7377         vm_paddr_t pa;
7378         int val;
7379
7380         PG_A = pmap_accessed_bit(pmap);
7381         PG_M = pmap_modified_bit(pmap);
7382         PG_V = pmap_valid_bit(pmap);
7383         PG_RW = pmap_rw_bit(pmap);
7384
7385         PMAP_LOCK(pmap);
7386 retry:
7387         pdep = pmap_pde(pmap, addr);
7388         if (pdep != NULL && (*pdep & PG_V)) {
7389                 if (*pdep & PG_PS) {
7390                         pte = *pdep;
7391                         /* Compute the physical address of the 4KB page. */
7392                         pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7393                             PG_FRAME;
7394                         val = MINCORE_SUPER;
7395                 } else {
7396                         pte = *pmap_pde_to_pte(pdep, addr);
7397                         pa = pte & PG_FRAME;
7398                         val = 0;
7399                 }
7400         } else {
7401                 pte = 0;
7402                 pa = 0;
7403                 val = 0;
7404         }
7405         if ((pte & PG_V) != 0) {
7406                 val |= MINCORE_INCORE;
7407                 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7408                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7409                 if ((pte & PG_A) != 0)
7410                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7411         }
7412         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7413             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7414             (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7415                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7416                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7417                         goto retry;
7418         } else
7419                 PA_UNLOCK_COND(*locked_pa);
7420         PMAP_UNLOCK(pmap);
7421         return (val);
7422 }
7423
7424 static uint64_t
7425 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7426 {
7427         uint32_t gen, new_gen, pcid_next;
7428
7429         CRITICAL_ASSERT(curthread);
7430         gen = PCPU_GET(pcid_gen);
7431         if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7432                 return (pti ? 0 : CR3_PCID_SAVE);
7433         if (pmap->pm_pcids[cpuid].pm_gen == gen)
7434                 return (CR3_PCID_SAVE);
7435         pcid_next = PCPU_GET(pcid_next);
7436         KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7437             (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7438             ("cpu %d pcid_next %#x", cpuid, pcid_next));
7439         if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7440             (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7441                 new_gen = gen + 1;
7442                 if (new_gen == 0)
7443                         new_gen = 1;
7444                 PCPU_SET(pcid_gen, new_gen);
7445                 pcid_next = PMAP_PCID_KERN + 1;
7446         } else {
7447                 new_gen = gen;
7448         }
7449         pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7450         pmap->pm_pcids[cpuid].pm_gen = new_gen;
7451         PCPU_SET(pcid_next, pcid_next + 1);
7452         return (0);
7453 }
7454
7455 void
7456 pmap_activate_sw(struct thread *td)
7457 {
7458         pmap_t oldpmap, pmap;
7459         struct invpcid_descr d;
7460         uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7461         register_t rflags;
7462         u_int cpuid;
7463         struct amd64tss *tssp;
7464
7465         oldpmap = PCPU_GET(curpmap);
7466         pmap = vmspace_pmap(td->td_proc->p_vmspace);
7467         if (oldpmap == pmap)
7468                 return;
7469         cpuid = PCPU_GET(cpuid);
7470 #ifdef SMP
7471         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7472 #else
7473         CPU_SET(cpuid, &pmap->pm_active);
7474 #endif
7475         cr3 = rcr3();
7476         if (pmap_pcid_enabled) {
7477                 cached = pmap_pcid_alloc(pmap, cpuid);
7478                 KASSERT(pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7479                     ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7480                     pmap->pm_pcids[cpuid].pm_pcid));
7481                 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7482                     pmap == kernel_pmap,
7483                     ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7484                     td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7485
7486                 /*
7487                  * If the INVPCID instruction is not available,
7488                  * invltlb_pcid_handler() is used for handle
7489                  * invalidate_all IPI, which checks for curpmap ==
7490                  * smp_tlb_pmap.  Below operations sequence has a
7491                  * window where %CR3 is loaded with the new pmap's
7492                  * PML4 address, but curpmap value is not yet updated.
7493                  * This causes invltlb IPI handler, called between the
7494                  * updates, to execute as NOP, which leaves stale TLB
7495                  * entries.
7496                  *
7497                  * Note that the most typical use of
7498                  * pmap_activate_sw(), from the context switch, is
7499                  * immune to this race, because interrupts are
7500                  * disabled (while the thread lock is owned), and IPI
7501                  * happens after curpmap is updated.  Protect other
7502                  * callers in a similar way, by disabling interrupts
7503                  * around the %cr3 register reload and curpmap
7504                  * assignment.
7505                  */
7506                 if (!invpcid_works)
7507                         rflags = intr_disable();
7508
7509                 kern_pti_cached = pti ? 0 : cached;
7510                 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7511                         load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7512                             kern_pti_cached);
7513                 }
7514                 PCPU_SET(curpmap, pmap);
7515                 if (pti) {
7516                         kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7517                         ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7518                             PMAP_PCID_USER_PT;
7519
7520                         if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7521                                 /*
7522                                  * Manually invalidate translations cached
7523                                  * from the user page table.  They are not
7524                                  * flushed by reload of cr3 with the kernel
7525                                  * page table pointer above.
7526                                  */
7527                                 if (invpcid_works) {
7528                                         d.pcid = PMAP_PCID_USER_PT |
7529                                             pmap->pm_pcids[cpuid].pm_pcid;
7530                                         d.pad = 0;
7531                                         d.addr = 0;
7532                                         invpcid(&d, INVPCID_CTX);
7533                                 } else {
7534                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
7535                                 }
7536                         }
7537
7538                         PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7539                         PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7540                 }
7541                 if (!invpcid_works)
7542                         intr_restore(rflags);
7543                 if (cached)
7544                         PCPU_INC(pm_save_cnt);
7545         } else {
7546                 load_cr3(pmap->pm_cr3);
7547                 PCPU_SET(curpmap, pmap);
7548                 if (pti) {
7549                         PCPU_SET(kcr3, pmap->pm_cr3);
7550                         PCPU_SET(ucr3, pmap->pm_ucr3);
7551                 }
7552         }
7553         if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7554                 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7555                     PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7556                 tssp = PCPU_GET(tssp);
7557                 tssp->tss_rsp0 = rsp0;
7558         }
7559 #ifdef SMP
7560         CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7561 #else
7562         CPU_CLR(cpuid, &oldpmap->pm_active);
7563 #endif
7564 }
7565
7566 void
7567 pmap_activate(struct thread *td)
7568 {
7569
7570         critical_enter();
7571         pmap_activate_sw(td);
7572         critical_exit();
7573 }
7574
7575 void
7576 pmap_activate_boot(pmap_t pmap)
7577 {
7578         uint64_t kcr3;
7579         u_int cpuid;
7580
7581         /*
7582          * kernel_pmap must be never deactivated, and we ensure that
7583          * by never activating it at all.
7584          */
7585         MPASS(pmap != kernel_pmap);
7586
7587         cpuid = PCPU_GET(cpuid);
7588 #ifdef SMP
7589         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7590 #else
7591         CPU_SET(cpuid, &pmap->pm_active);
7592 #endif
7593         PCPU_SET(curpmap, pmap);
7594         if (pti) {
7595                 kcr3 = pmap->pm_cr3;
7596                 if (pmap_pcid_enabled)
7597                         kcr3 |= pmap->pm_pcids[cpuid].pm_pcid | CR3_PCID_SAVE;
7598         } else {
7599                 kcr3 = PMAP_NO_CR3;
7600         }
7601         PCPU_SET(kcr3, kcr3);
7602         PCPU_SET(ucr3, PMAP_NO_CR3);
7603 }
7604
7605 void
7606 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7607 {
7608 }
7609
7610 /*
7611  *      Increase the starting virtual address of the given mapping if a
7612  *      different alignment might result in more superpage mappings.
7613  */
7614 void
7615 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7616     vm_offset_t *addr, vm_size_t size)
7617 {
7618         vm_offset_t superpage_offset;
7619
7620         if (size < NBPDR)
7621                 return;
7622         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7623                 offset += ptoa(object->pg_color);
7624         superpage_offset = offset & PDRMASK;
7625         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7626             (*addr & PDRMASK) == superpage_offset)
7627                 return;
7628         if ((*addr & PDRMASK) < superpage_offset)
7629                 *addr = (*addr & ~PDRMASK) + superpage_offset;
7630         else
7631                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7632 }
7633
7634 #ifdef INVARIANTS
7635 static unsigned long num_dirty_emulations;
7636 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7637              &num_dirty_emulations, 0, NULL);
7638
7639 static unsigned long num_accessed_emulations;
7640 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7641              &num_accessed_emulations, 0, NULL);
7642
7643 static unsigned long num_superpage_accessed_emulations;
7644 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7645              &num_superpage_accessed_emulations, 0, NULL);
7646
7647 static unsigned long ad_emulation_superpage_promotions;
7648 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7649              &ad_emulation_superpage_promotions, 0, NULL);
7650 #endif  /* INVARIANTS */
7651
7652 int
7653 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7654 {
7655         int rv;
7656         struct rwlock *lock;
7657 #if VM_NRESERVLEVEL > 0
7658         vm_page_t m, mpte;
7659 #endif
7660         pd_entry_t *pde;
7661         pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7662
7663         KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7664             ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7665
7666         if (!pmap_emulate_ad_bits(pmap))
7667                 return (-1);
7668
7669         PG_A = pmap_accessed_bit(pmap);
7670         PG_M = pmap_modified_bit(pmap);
7671         PG_V = pmap_valid_bit(pmap);
7672         PG_RW = pmap_rw_bit(pmap);
7673
7674         rv = -1;
7675         lock = NULL;
7676         PMAP_LOCK(pmap);
7677
7678         pde = pmap_pde(pmap, va);
7679         if (pde == NULL || (*pde & PG_V) == 0)
7680                 goto done;
7681
7682         if ((*pde & PG_PS) != 0) {
7683                 if (ftype == VM_PROT_READ) {
7684 #ifdef INVARIANTS
7685                         atomic_add_long(&num_superpage_accessed_emulations, 1);
7686 #endif
7687                         *pde |= PG_A;
7688                         rv = 0;
7689                 }
7690                 goto done;
7691         }
7692
7693         pte = pmap_pde_to_pte(pde, va);
7694         if ((*pte & PG_V) == 0)
7695                 goto done;
7696
7697         if (ftype == VM_PROT_WRITE) {
7698                 if ((*pte & PG_RW) == 0)
7699                         goto done;
7700                 /*
7701                  * Set the modified and accessed bits simultaneously.
7702                  *
7703                  * Intel EPT PTEs that do software emulation of A/D bits map
7704                  * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7705                  * An EPT misconfiguration is triggered if the PTE is writable
7706                  * but not readable (WR=10). This is avoided by setting PG_A
7707                  * and PG_M simultaneously.
7708                  */
7709                 *pte |= PG_M | PG_A;
7710         } else {
7711                 *pte |= PG_A;
7712         }
7713
7714 #if VM_NRESERVLEVEL > 0
7715         /* try to promote the mapping */
7716         if (va < VM_MAXUSER_ADDRESS)
7717                 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7718         else
7719                 mpte = NULL;
7720
7721         m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7722
7723         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7724             pmap_ps_enabled(pmap) &&
7725             (m->flags & PG_FICTITIOUS) == 0 &&
7726             vm_reserv_level_iffullpop(m) == 0) {
7727                 pmap_promote_pde(pmap, pde, va, &lock);
7728 #ifdef INVARIANTS
7729                 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7730 #endif
7731         }
7732 #endif
7733
7734 #ifdef INVARIANTS
7735         if (ftype == VM_PROT_WRITE)
7736                 atomic_add_long(&num_dirty_emulations, 1);
7737         else
7738                 atomic_add_long(&num_accessed_emulations, 1);
7739 #endif
7740         rv = 0;         /* success */
7741 done:
7742         if (lock != NULL)
7743                 rw_wunlock(lock);
7744         PMAP_UNLOCK(pmap);
7745         return (rv);
7746 }
7747
7748 void
7749 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7750 {
7751         pml4_entry_t *pml4;
7752         pdp_entry_t *pdp;
7753         pd_entry_t *pde;
7754         pt_entry_t *pte, PG_V;
7755         int idx;
7756
7757         idx = 0;
7758         PG_V = pmap_valid_bit(pmap);
7759         PMAP_LOCK(pmap);
7760
7761         pml4 = pmap_pml4e(pmap, va);
7762         ptr[idx++] = *pml4;
7763         if ((*pml4 & PG_V) == 0)
7764                 goto done;
7765
7766         pdp = pmap_pml4e_to_pdpe(pml4, va);
7767         ptr[idx++] = *pdp;
7768         if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7769                 goto done;
7770
7771         pde = pmap_pdpe_to_pde(pdp, va);
7772         ptr[idx++] = *pde;
7773         if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7774                 goto done;
7775
7776         pte = pmap_pde_to_pte(pde, va);
7777         ptr[idx++] = *pte;
7778
7779 done:
7780         PMAP_UNLOCK(pmap);
7781         *num = idx;
7782 }
7783
7784 /**
7785  * Get the kernel virtual address of a set of physical pages. If there are
7786  * physical addresses not covered by the DMAP perform a transient mapping
7787  * that will be removed when calling pmap_unmap_io_transient.
7788  *
7789  * \param page        The pages the caller wishes to obtain the virtual
7790  *                    address on the kernel memory map.
7791  * \param vaddr       On return contains the kernel virtual memory address
7792  *                    of the pages passed in the page parameter.
7793  * \param count       Number of pages passed in.
7794  * \param can_fault   TRUE if the thread using the mapped pages can take
7795  *                    page faults, FALSE otherwise.
7796  *
7797  * \returns TRUE if the caller must call pmap_unmap_io_transient when
7798  *          finished or FALSE otherwise.
7799  *
7800  */
7801 boolean_t
7802 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7803     boolean_t can_fault)
7804 {
7805         vm_paddr_t paddr;
7806         boolean_t needs_mapping;
7807         pt_entry_t *pte;
7808         int cache_bits, error, i;
7809
7810         /*
7811          * Allocate any KVA space that we need, this is done in a separate
7812          * loop to prevent calling vmem_alloc while pinned.
7813          */
7814         needs_mapping = FALSE;
7815         for (i = 0; i < count; i++) {
7816                 paddr = VM_PAGE_TO_PHYS(page[i]);
7817                 if (__predict_false(paddr >= dmaplimit)) {
7818                         error = vmem_alloc(kernel_arena, PAGE_SIZE,
7819                             M_BESTFIT | M_WAITOK, &vaddr[i]);
7820                         KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7821                         needs_mapping = TRUE;
7822                 } else {
7823                         vaddr[i] = PHYS_TO_DMAP(paddr);
7824                 }
7825         }
7826
7827         /* Exit early if everything is covered by the DMAP */
7828         if (!needs_mapping)
7829                 return (FALSE);
7830
7831         /*
7832          * NB:  The sequence of updating a page table followed by accesses
7833          * to the corresponding pages used in the !DMAP case is subject to
7834          * the situation described in the "AMD64 Architecture Programmer's
7835          * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7836          * Coherency Considerations".  Therefore, issuing the INVLPG right
7837          * after modifying the PTE bits is crucial.
7838          */
7839         if (!can_fault)
7840                 sched_pin();
7841         for (i = 0; i < count; i++) {
7842                 paddr = VM_PAGE_TO_PHYS(page[i]);
7843                 if (paddr >= dmaplimit) {
7844                         if (can_fault) {
7845                                 /*
7846                                  * Slow path, since we can get page faults
7847                                  * while mappings are active don't pin the
7848                                  * thread to the CPU and instead add a global
7849                                  * mapping visible to all CPUs.
7850                                  */
7851                                 pmap_qenter(vaddr[i], &page[i], 1);
7852                         } else {
7853                                 pte = vtopte(vaddr[i]);
7854                                 cache_bits = pmap_cache_bits(kernel_pmap,
7855                                     page[i]->md.pat_mode, 0);
7856                                 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7857                                     cache_bits);
7858                                 invlpg(vaddr[i]);
7859                         }
7860                 }
7861         }
7862
7863         return (needs_mapping);
7864 }
7865
7866 void
7867 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7868     boolean_t can_fault)
7869 {
7870         vm_paddr_t paddr;
7871         int i;
7872
7873         if (!can_fault)
7874                 sched_unpin();
7875         for (i = 0; i < count; i++) {
7876                 paddr = VM_PAGE_TO_PHYS(page[i]);
7877                 if (paddr >= dmaplimit) {
7878                         if (can_fault)
7879                                 pmap_qremove(vaddr[i], 1);
7880                         vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7881                 }
7882         }
7883 }
7884
7885 vm_offset_t
7886 pmap_quick_enter_page(vm_page_t m)
7887 {
7888         vm_paddr_t paddr;
7889
7890         paddr = VM_PAGE_TO_PHYS(m);
7891         if (paddr < dmaplimit)
7892                 return (PHYS_TO_DMAP(paddr));
7893         mtx_lock_spin(&qframe_mtx);
7894         KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7895         pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7896             X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7897         return (qframe);
7898 }
7899
7900 void
7901 pmap_quick_remove_page(vm_offset_t addr)
7902 {
7903
7904         if (addr != qframe)
7905                 return;
7906         pte_store(vtopte(qframe), 0);
7907         invlpg(qframe);
7908         mtx_unlock_spin(&qframe_mtx);
7909 }
7910
7911 static vm_page_t
7912 pmap_pti_alloc_page(void)
7913 {
7914         vm_page_t m;
7915
7916         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7917         m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7918             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7919         return (m);
7920 }
7921
7922 static bool
7923 pmap_pti_free_page(vm_page_t m)
7924 {
7925
7926         KASSERT(m->wire_count > 0, ("page %p not wired", m));
7927         m->wire_count--;
7928         if (m->wire_count != 0)
7929                 return (false);
7930         atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7931         vm_page_free_zero(m);
7932         return (true);
7933 }
7934
7935 static void
7936 pmap_pti_init(void)
7937 {
7938         vm_page_t pml4_pg;
7939         pdp_entry_t *pdpe;
7940         vm_offset_t va;
7941         int i;
7942
7943         if (!pti)
7944                 return;
7945         pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7946         VM_OBJECT_WLOCK(pti_obj);
7947         pml4_pg = pmap_pti_alloc_page();
7948         pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7949         for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7950             va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7951                 pdpe = pmap_pti_pdpe(va);
7952                 pmap_pti_wire_pte(pdpe);
7953         }
7954         pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7955             (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7956         pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7957             sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7958         pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7959             sizeof(struct gate_descriptor) * NIDT, false);
7960         pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7961             (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7962         CPU_FOREACH(i) {
7963                 /* Doublefault stack IST 1 */
7964                 va = common_tss[i].tss_ist1;
7965                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7966                 /* NMI stack IST 2 */
7967                 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7968                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7969                 /* MC# stack IST 3 */
7970                 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7971                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7972                 /* DB# stack IST 4 */
7973                 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7974                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7975         }
7976         pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7977             (vm_offset_t)etext, true);
7978         pti_finalized = true;
7979         VM_OBJECT_WUNLOCK(pti_obj);
7980 }
7981 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7982
7983 static pdp_entry_t *
7984 pmap_pti_pdpe(vm_offset_t va)
7985 {
7986         pml4_entry_t *pml4e;
7987         pdp_entry_t *pdpe;
7988         vm_page_t m;
7989         vm_pindex_t pml4_idx;
7990         vm_paddr_t mphys;
7991
7992         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7993
7994         pml4_idx = pmap_pml4e_index(va);
7995         pml4e = &pti_pml4[pml4_idx];
7996         m = NULL;
7997         if (*pml4e == 0) {
7998                 if (pti_finalized)
7999                         panic("pml4 alloc after finalization\n");
8000                 m = pmap_pti_alloc_page();
8001                 if (*pml4e != 0) {
8002                         pmap_pti_free_page(m);
8003                         mphys = *pml4e & ~PAGE_MASK;
8004                 } else {
8005                         mphys = VM_PAGE_TO_PHYS(m);
8006                         *pml4e = mphys | X86_PG_RW | X86_PG_V;
8007                 }
8008         } else {
8009                 mphys = *pml4e & ~PAGE_MASK;
8010         }
8011         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
8012         return (pdpe);
8013 }
8014
8015 static void
8016 pmap_pti_wire_pte(void *pte)
8017 {
8018         vm_page_t m;
8019
8020         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8021         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8022         m->wire_count++;
8023 }
8024
8025 static void
8026 pmap_pti_unwire_pde(void *pde, bool only_ref)
8027 {
8028         vm_page_t m;
8029
8030         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8031         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
8032         MPASS(m->wire_count > 0);
8033         MPASS(only_ref || m->wire_count > 1);
8034         pmap_pti_free_page(m);
8035 }
8036
8037 static void
8038 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
8039 {
8040         vm_page_t m;
8041         pd_entry_t *pde;
8042
8043         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8044         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8045         MPASS(m->wire_count > 0);
8046         if (pmap_pti_free_page(m)) {
8047                 pde = pmap_pti_pde(va);
8048                 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
8049                 *pde = 0;
8050                 pmap_pti_unwire_pde(pde, false);
8051         }
8052 }
8053
8054 static pd_entry_t *
8055 pmap_pti_pde(vm_offset_t va)
8056 {
8057         pdp_entry_t *pdpe;
8058         pd_entry_t *pde;
8059         vm_page_t m;
8060         vm_pindex_t pd_idx;
8061         vm_paddr_t mphys;
8062
8063         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8064
8065         pdpe = pmap_pti_pdpe(va);
8066         if (*pdpe == 0) {
8067                 m = pmap_pti_alloc_page();
8068                 if (*pdpe != 0) {
8069                         pmap_pti_free_page(m);
8070                         MPASS((*pdpe & X86_PG_PS) == 0);
8071                         mphys = *pdpe & ~PAGE_MASK;
8072                 } else {
8073                         mphys =  VM_PAGE_TO_PHYS(m);
8074                         *pdpe = mphys | X86_PG_RW | X86_PG_V;
8075                 }
8076         } else {
8077                 MPASS((*pdpe & X86_PG_PS) == 0);
8078                 mphys = *pdpe & ~PAGE_MASK;
8079         }
8080
8081         pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8082         pd_idx = pmap_pde_index(va);
8083         pde += pd_idx;
8084         return (pde);
8085 }
8086
8087 static pt_entry_t *
8088 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8089 {
8090         pd_entry_t *pde;
8091         pt_entry_t *pte;
8092         vm_page_t m;
8093         vm_paddr_t mphys;
8094
8095         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8096
8097         pde = pmap_pti_pde(va);
8098         if (unwire_pde != NULL) {
8099                 *unwire_pde = true;
8100                 pmap_pti_wire_pte(pde);
8101         }
8102         if (*pde == 0) {
8103                 m = pmap_pti_alloc_page();
8104                 if (*pde != 0) {
8105                         pmap_pti_free_page(m);
8106                         MPASS((*pde & X86_PG_PS) == 0);
8107                         mphys = *pde & ~(PAGE_MASK | pg_nx);
8108                 } else {
8109                         mphys = VM_PAGE_TO_PHYS(m);
8110                         *pde = mphys | X86_PG_RW | X86_PG_V;
8111                         if (unwire_pde != NULL)
8112                                 *unwire_pde = false;
8113                 }
8114         } else {
8115                 MPASS((*pde & X86_PG_PS) == 0);
8116                 mphys = *pde & ~(PAGE_MASK | pg_nx);
8117         }
8118
8119         pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8120         pte += pmap_pte_index(va);
8121
8122         return (pte);
8123 }
8124
8125 static void
8126 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8127 {
8128         vm_paddr_t pa;
8129         pd_entry_t *pde;
8130         pt_entry_t *pte, ptev;
8131         bool unwire_pde;
8132
8133         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8134
8135         sva = trunc_page(sva);
8136         MPASS(sva > VM_MAXUSER_ADDRESS);
8137         eva = round_page(eva);
8138         MPASS(sva < eva);
8139         for (; sva < eva; sva += PAGE_SIZE) {
8140                 pte = pmap_pti_pte(sva, &unwire_pde);
8141                 pa = pmap_kextract(sva);
8142                 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8143                     (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8144                     VM_MEMATTR_DEFAULT, FALSE);
8145                 if (*pte == 0) {
8146                         pte_store(pte, ptev);
8147                         pmap_pti_wire_pte(pte);
8148                 } else {
8149                         KASSERT(!pti_finalized,
8150                             ("pti overlap after fin %#lx %#lx %#lx",
8151                             sva, *pte, ptev));
8152                         KASSERT(*pte == ptev,
8153                             ("pti non-identical pte after fin %#lx %#lx %#lx",
8154                             sva, *pte, ptev));
8155                 }
8156                 if (unwire_pde) {
8157                         pde = pmap_pti_pde(sva);
8158                         pmap_pti_unwire_pde(pde, true);
8159                 }
8160         }
8161 }
8162
8163 void
8164 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8165 {
8166
8167         if (!pti)
8168                 return;
8169         VM_OBJECT_WLOCK(pti_obj);
8170         pmap_pti_add_kva_locked(sva, eva, exec);
8171         VM_OBJECT_WUNLOCK(pti_obj);
8172 }
8173
8174 void
8175 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8176 {
8177         pt_entry_t *pte;
8178         vm_offset_t va;
8179
8180         if (!pti)
8181                 return;
8182         sva = rounddown2(sva, PAGE_SIZE);
8183         MPASS(sva > VM_MAXUSER_ADDRESS);
8184         eva = roundup2(eva, PAGE_SIZE);
8185         MPASS(sva < eva);
8186         VM_OBJECT_WLOCK(pti_obj);
8187         for (va = sva; va < eva; va += PAGE_SIZE) {
8188                 pte = pmap_pti_pte(va, NULL);
8189                 KASSERT((*pte & X86_PG_V) != 0,
8190                     ("invalid pte va %#lx pte %#lx pt %#lx", va,
8191                     (u_long)pte, *pte));
8192                 pte_clear(pte);
8193                 pmap_pti_unwire_pte(pte, va);
8194         }
8195         pmap_invalidate_range(kernel_pmap, sva, eva);
8196         VM_OBJECT_WUNLOCK(pti_obj);
8197 }
8198
8199 #include "opt_ddb.h"
8200 #ifdef DDB
8201 #include <ddb/ddb.h>
8202
8203 DB_SHOW_COMMAND(pte, pmap_print_pte)
8204 {
8205         pmap_t pmap;
8206         pml4_entry_t *pml4;
8207         pdp_entry_t *pdp;
8208         pd_entry_t *pde;
8209         pt_entry_t *pte, PG_V;
8210         vm_offset_t va;
8211
8212         if (have_addr) {
8213                 va = (vm_offset_t)addr;
8214                 pmap = PCPU_GET(curpmap); /* XXX */
8215         } else {
8216                 db_printf("show pte addr\n");
8217                 return;
8218         }
8219         PG_V = pmap_valid_bit(pmap);
8220         pml4 = pmap_pml4e(pmap, va);
8221         db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8222         if ((*pml4 & PG_V) == 0) {
8223                 db_printf("\n");
8224                 return;
8225         }
8226         pdp = pmap_pml4e_to_pdpe(pml4, va);
8227         db_printf(" pdpe %#016lx", *pdp);
8228         if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8229                 db_printf("\n");
8230                 return;
8231         }
8232         pde = pmap_pdpe_to_pde(pdp, va);
8233         db_printf(" pde %#016lx", *pde);
8234         if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8235                 db_printf("\n");
8236                 return;
8237         }
8238         pte = pmap_pde_to_pte(pde, va);
8239         db_printf(" pte %#016lx\n", *pte);
8240 }
8241
8242 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8243 {
8244         vm_paddr_t a;
8245
8246         if (have_addr) {
8247                 a = (vm_paddr_t)addr;
8248                 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8249         } else {
8250                 db_printf("show phys2dmap addr\n");
8251         }
8252 }
8253 #endif