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