2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
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.
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.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
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.
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
47 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
50 * Copyright (c) 2003 Networks Associates Technology, Inc.
51 * Copyright (c) 2014-2020 The FreeBSD Foundation
52 * All rights reserved.
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.
60 * Portions of this software were developed by
61 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
62 * the FreeBSD Foundation.
64 * Redistribution and use in source and binary forms, with or without
65 * modification, are permitted provided that the following conditions
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.
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
86 #define AMD64_NPT_AWARE
88 #include <sys/cdefs.h>
90 * Manages physical address maps.
92 * Since the information managed by this module is
93 * also stored by the logical address mapping module,
94 * this module may throw away valid virtual-to-physical
95 * mappings at almost any time. However, invalidations
96 * of virtual-to-physical mappings must be done as
99 * In order to cope with hardware architectures which
100 * make virtual-to-physical map invalidates expensive,
101 * this module may delay invalidate or reduced protection
102 * operations until such time as they are actually
103 * necessary. This module is given full information as
104 * to which processors are currently using which maps,
105 * and to when physical maps must be made correct.
109 #include "opt_pmap.h"
112 #include <sys/param.h>
113 #include <sys/asan.h>
114 #include <sys/bitstring.h>
116 #include <sys/systm.h>
117 #include <sys/counter.h>
118 #include <sys/kernel.h>
120 #include <sys/lock.h>
121 #include <sys/malloc.h>
122 #include <sys/mman.h>
123 #include <sys/msan.h>
124 #include <sys/mutex.h>
125 #include <sys/proc.h>
126 #include <sys/rangeset.h>
127 #include <sys/rwlock.h>
128 #include <sys/sbuf.h>
131 #include <sys/turnstile.h>
132 #include <sys/vmem.h>
133 #include <sys/vmmeter.h>
134 #include <sys/sched.h>
135 #include <sys/sysctl.h>
143 #include <vm/vm_param.h>
144 #include <vm/vm_kern.h>
145 #include <vm/vm_page.h>
146 #include <vm/vm_map.h>
147 #include <vm/vm_object.h>
148 #include <vm/vm_extern.h>
149 #include <vm/vm_pageout.h>
150 #include <vm/vm_pager.h>
151 #include <vm/vm_phys.h>
152 #include <vm/vm_radix.h>
153 #include <vm/vm_reserv.h>
154 #include <vm/vm_dumpset.h>
157 #include <machine/asan.h>
158 #include <machine/intr_machdep.h>
159 #include <x86/apicvar.h>
160 #include <x86/ifunc.h>
161 #include <machine/cpu.h>
162 #include <machine/cputypes.h>
163 #include <machine/md_var.h>
164 #include <machine/msan.h>
165 #include <machine/pcb.h>
166 #include <machine/specialreg.h>
168 #include <machine/smp.h>
170 #include <machine/sysarch.h>
171 #include <machine/tss.h>
174 #define PMAP_MEMDOM MAXMEMDOM
176 #define PMAP_MEMDOM 1
179 static __inline boolean_t
180 pmap_type_guest(pmap_t pmap)
183 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
186 static __inline boolean_t
187 pmap_emulate_ad_bits(pmap_t pmap)
190 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
193 static __inline pt_entry_t
194 pmap_valid_bit(pmap_t pmap)
198 switch (pmap->pm_type) {
204 if (pmap_emulate_ad_bits(pmap))
205 mask = EPT_PG_EMUL_V;
210 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
216 static __inline pt_entry_t
217 pmap_rw_bit(pmap_t pmap)
221 switch (pmap->pm_type) {
227 if (pmap_emulate_ad_bits(pmap))
228 mask = EPT_PG_EMUL_RW;
233 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
239 static pt_entry_t pg_g;
241 static __inline pt_entry_t
242 pmap_global_bit(pmap_t pmap)
246 switch (pmap->pm_type) {
255 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
261 static __inline pt_entry_t
262 pmap_accessed_bit(pmap_t pmap)
266 switch (pmap->pm_type) {
272 if (pmap_emulate_ad_bits(pmap))
278 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
284 static __inline pt_entry_t
285 pmap_modified_bit(pmap_t pmap)
289 switch (pmap->pm_type) {
295 if (pmap_emulate_ad_bits(pmap))
301 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
307 static __inline pt_entry_t
308 pmap_pku_mask_bit(pmap_t pmap)
311 return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
314 static __inline boolean_t
315 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
318 if (!pmap_emulate_ad_bits(pmap))
321 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
324 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
325 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
326 * if the EPT_PG_WRITE bit is set.
328 if ((pte & EPT_PG_WRITE) != 0)
332 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
334 if ((pte & EPT_PG_EXECUTE) == 0 ||
335 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
341 #if !defined(DIAGNOSTIC)
342 #ifdef __GNUC_GNU_INLINE__
343 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
345 #define PMAP_INLINE extern inline
352 #define PV_STAT(x) do { x ; } while (0)
354 #define PV_STAT(x) do { } while (0)
359 #define pa_index(pa) ({ \
360 KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end, \
361 ("address %lx beyond the last segment", (pa))); \
364 #define pa_to_pmdp(pa) (&pv_table[pa_index(pa)])
365 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
366 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
367 struct rwlock *_lock; \
368 if (__predict_false((pa) > pmap_last_pa)) \
369 _lock = &pv_dummy_large.pv_lock; \
371 _lock = &(pa_to_pmdp(pa)->pv_lock); \
375 #define pa_index(pa) ((pa) >> PDRSHIFT)
376 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
378 #define NPV_LIST_LOCKS MAXCPU
380 #define PHYS_TO_PV_LIST_LOCK(pa) \
381 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
384 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
385 struct rwlock **_lockp = (lockp); \
386 struct rwlock *_new_lock; \
388 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
389 if (_new_lock != *_lockp) { \
390 if (*_lockp != NULL) \
391 rw_wunlock(*_lockp); \
392 *_lockp = _new_lock; \
397 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
398 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
400 #define RELEASE_PV_LIST_LOCK(lockp) do { \
401 struct rwlock **_lockp = (lockp); \
403 if (*_lockp != NULL) { \
404 rw_wunlock(*_lockp); \
409 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
410 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
413 * Statically allocate kernel pmap memory. However, memory for
414 * pm_pcids is obtained after the dynamic allocator is operational.
415 * Initialize it with a non-canonical pointer to catch early accesses
416 * regardless of the active mapping.
418 struct pmap kernel_pmap_store = {
419 .pm_pcidp = (void *)0xdeadbeefdeadbeef,
422 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
423 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
426 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
427 "Number of kernel page table pages allocated on bootup");
430 vm_paddr_t dmaplimit;
431 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
434 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
435 "VM/pmap parameters");
437 static int __read_frequently pg_ps_enabled = 1;
438 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
439 &pg_ps_enabled, 0, "Are large page mappings enabled?");
441 int __read_frequently la57 = 0;
442 SYSCTL_INT(_vm_pmap, OID_AUTO, la57, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
444 "5-level paging for host is enabled");
447 pmap_is_la57(pmap_t pmap)
449 if (pmap->pm_type == PT_X86)
451 return (false); /* XXXKIB handle EPT */
454 #define PAT_INDEX_SIZE 8
455 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
457 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
458 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
459 static u_int64_t KPDPphys; /* phys addr of kernel level 3 */
460 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
461 u_int64_t KPML5phys; /* phys addr of kernel level 5,
465 static uint64_t KASANPDPphys;
468 static uint64_t KMSANSHADPDPphys;
469 static uint64_t KMSANORIGPDPphys;
472 * To support systems with large amounts of memory, it is necessary to extend
473 * the maximum size of the direct map. This could eat into the space reserved
474 * for the shadow map.
476 _Static_assert(DMPML4I + NDMPML4E <= KMSANSHADPML4I, "direct map overflow");
479 static pml4_entry_t *kernel_pml4;
480 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
481 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
482 static int ndmpdpphys; /* number of DMPDPphys pages */
484 vm_paddr_t kernphys; /* phys addr of start of bootstrap data */
485 vm_paddr_t KERNend; /* and the end */
488 * pmap_mapdev support pre initialization (i.e. console)
490 #define PMAP_PREINIT_MAPPING_COUNT 8
491 static struct pmap_preinit_mapping {
496 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
497 static int pmap_initialized;
500 * Data for the pv entry allocation mechanism.
501 * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
505 pc_to_domain(struct pv_chunk *pc)
508 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
512 pc_to_domain(struct pv_chunk *pc __unused)
519 struct pv_chunks_list {
521 TAILQ_HEAD(pch, pv_chunk) pvc_list;
523 } __aligned(CACHE_LINE_SIZE);
525 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
528 struct pmap_large_md_page {
529 struct rwlock pv_lock;
530 struct md_page pv_page;
533 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
534 #define pv_dummy pv_dummy_large.pv_page
535 __read_mostly static struct pmap_large_md_page *pv_table;
536 __read_mostly vm_paddr_t pmap_last_pa;
538 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
539 static u_long pv_invl_gen[NPV_LIST_LOCKS];
540 static struct md_page *pv_table;
541 static struct md_page pv_dummy;
545 * All those kernel PT submaps that BSD is so fond of
547 pt_entry_t *CMAP1 = NULL;
549 static vm_offset_t qframe = 0;
550 static struct mtx qframe_mtx;
552 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
554 static vmem_t *large_vmem;
555 static u_int lm_ents;
556 #define PMAP_ADDRESS_IN_LARGEMAP(va) ((va) >= LARGEMAP_MIN_ADDRESS && \
557 (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
559 int pmap_pcid_enabled = 1;
560 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
561 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
562 int invpcid_works = 0;
563 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
564 "Is the invpcid instruction available ?");
565 int pmap_pcid_invlpg_workaround = 0;
566 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_invlpg_workaround,
567 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
568 &pmap_pcid_invlpg_workaround, 0,
569 "Enable small core PCID/INVLPG workaround");
570 int pmap_pcid_invlpg_workaround_uena = 1;
572 int __read_frequently pti = 0;
573 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
575 "Page Table Isolation enabled");
576 static vm_object_t pti_obj;
577 static pml4_entry_t *pti_pml4;
578 static vm_pindex_t pti_pg_idx;
579 static bool pti_finalized;
581 struct pmap_pkru_range {
582 struct rs_el pkru_rs_el;
587 static uma_zone_t pmap_pkru_ranges_zone;
588 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
589 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
590 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
591 static void *pkru_dup_range(void *ctx, void *data);
592 static void pkru_free_range(void *ctx, void *node);
593 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
594 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
595 static void pmap_pkru_deassign_all(pmap_t pmap);
597 static COUNTER_U64_DEFINE_EARLY(pcid_save_cnt);
598 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLFLAG_RD,
599 &pcid_save_cnt, "Count of saved TLB context on switch");
601 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
602 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
603 static struct mtx invl_gen_mtx;
604 /* Fake lock object to satisfy turnstiles interface. */
605 static struct lock_object invl_gen_ts = {
608 static struct pmap_invl_gen pmap_invl_gen_head = {
612 static u_long pmap_invl_gen = 1;
613 static int pmap_invl_waiters;
614 static struct callout pmap_invl_callout;
615 static bool pmap_invl_callout_inited;
617 #define PMAP_ASSERT_NOT_IN_DI() \
618 KASSERT(pmap_not_in_di(), ("DI already started"))
625 if ((cpu_feature2 & CPUID2_CX16) == 0)
628 TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
633 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
637 locked = pmap_di_locked();
638 return (sysctl_handle_int(oidp, &locked, 0, req));
640 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
641 CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
642 "Locked delayed invalidation");
644 static bool pmap_not_in_di_l(void);
645 static bool pmap_not_in_di_u(void);
646 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
649 return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
653 pmap_not_in_di_l(void)
655 struct pmap_invl_gen *invl_gen;
657 invl_gen = &curthread->td_md.md_invl_gen;
658 return (invl_gen->gen == 0);
662 pmap_thread_init_invl_gen_l(struct thread *td)
664 struct pmap_invl_gen *invl_gen;
666 invl_gen = &td->td_md.md_invl_gen;
671 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
673 struct turnstile *ts;
675 ts = turnstile_trywait(&invl_gen_ts);
676 if (*m_gen > atomic_load_long(invl_gen))
677 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
679 turnstile_cancel(ts);
683 pmap_delayed_invl_finish_unblock(u_long new_gen)
685 struct turnstile *ts;
687 turnstile_chain_lock(&invl_gen_ts);
688 ts = turnstile_lookup(&invl_gen_ts);
690 pmap_invl_gen = new_gen;
692 turnstile_broadcast(ts, TS_SHARED_QUEUE);
693 turnstile_unpend(ts);
695 turnstile_chain_unlock(&invl_gen_ts);
699 * Start a new Delayed Invalidation (DI) block of code, executed by
700 * the current thread. Within a DI block, the current thread may
701 * destroy both the page table and PV list entries for a mapping and
702 * then release the corresponding PV list lock before ensuring that
703 * the mapping is flushed from the TLBs of any processors with the
707 pmap_delayed_invl_start_l(void)
709 struct pmap_invl_gen *invl_gen;
712 invl_gen = &curthread->td_md.md_invl_gen;
713 PMAP_ASSERT_NOT_IN_DI();
714 mtx_lock(&invl_gen_mtx);
715 if (LIST_EMPTY(&pmap_invl_gen_tracker))
716 currgen = pmap_invl_gen;
718 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
719 invl_gen->gen = currgen + 1;
720 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
721 mtx_unlock(&invl_gen_mtx);
725 * Finish the DI block, previously started by the current thread. All
726 * required TLB flushes for the pages marked by
727 * pmap_delayed_invl_page() must be finished before this function is
730 * This function works by bumping the global DI generation number to
731 * the generation number of the current thread's DI, unless there is a
732 * pending DI that started earlier. In the latter case, bumping the
733 * global DI generation number would incorrectly signal that the
734 * earlier DI had finished. Instead, this function bumps the earlier
735 * DI's generation number to match the generation number of the
736 * current thread's DI.
739 pmap_delayed_invl_finish_l(void)
741 struct pmap_invl_gen *invl_gen, *next;
743 invl_gen = &curthread->td_md.md_invl_gen;
744 KASSERT(invl_gen->gen != 0, ("missed invl_start"));
745 mtx_lock(&invl_gen_mtx);
746 next = LIST_NEXT(invl_gen, link);
748 pmap_delayed_invl_finish_unblock(invl_gen->gen);
750 next->gen = invl_gen->gen;
751 LIST_REMOVE(invl_gen, link);
752 mtx_unlock(&invl_gen_mtx);
757 pmap_not_in_di_u(void)
759 struct pmap_invl_gen *invl_gen;
761 invl_gen = &curthread->td_md.md_invl_gen;
762 return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
766 pmap_thread_init_invl_gen_u(struct thread *td)
768 struct pmap_invl_gen *invl_gen;
770 invl_gen = &td->td_md.md_invl_gen;
772 invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
776 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
778 uint64_t new_high, new_low, old_high, old_low;
781 old_low = new_low = 0;
782 old_high = new_high = (uintptr_t)0;
784 __asm volatile("lock;cmpxchg16b\t%1"
785 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
786 : "b"(new_low), "c" (new_high)
789 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
792 out->next = (void *)old_high;
795 out->next = (void *)new_high;
801 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
802 struct pmap_invl_gen *new_val)
804 uint64_t new_high, new_low, old_high, old_low;
807 new_low = new_val->gen;
808 new_high = (uintptr_t)new_val->next;
809 old_low = old_val->gen;
810 old_high = (uintptr_t)old_val->next;
812 __asm volatile("lock;cmpxchg16b\t%1"
813 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
814 : "b"(new_low), "c" (new_high)
819 static COUNTER_U64_DEFINE_EARLY(pv_page_count);
820 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_page_count, CTLFLAG_RD,
821 &pv_page_count, "Current number of allocated pv pages");
823 static COUNTER_U64_DEFINE_EARLY(user_pt_page_count);
824 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, user_pt_page_count, CTLFLAG_RD,
826 "Current number of allocated page table pages for userspace");
828 static COUNTER_U64_DEFINE_EARLY(kernel_pt_page_count);
829 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, kernel_pt_page_count, CTLFLAG_RD,
830 &kernel_pt_page_count,
831 "Current number of allocated page table pages for the kernel");
835 static COUNTER_U64_DEFINE_EARLY(invl_start_restart);
836 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_start_restart,
837 CTLFLAG_RD, &invl_start_restart,
838 "Number of delayed TLB invalidation request restarts");
840 static COUNTER_U64_DEFINE_EARLY(invl_finish_restart);
841 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
842 &invl_finish_restart,
843 "Number of delayed TLB invalidation completion restarts");
845 static int invl_max_qlen;
846 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
848 "Maximum delayed TLB invalidation request queue length");
851 #define di_delay locks_delay
854 pmap_delayed_invl_start_u(void)
856 struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
858 struct lock_delay_arg lda;
866 invl_gen = &td->td_md.md_invl_gen;
867 PMAP_ASSERT_NOT_IN_DI();
868 lock_delay_arg_init(&lda, &di_delay);
869 invl_gen->saved_pri = 0;
870 pri = td->td_base_pri;
873 pri = td->td_base_pri;
875 invl_gen->saved_pri = pri;
882 for (p = &pmap_invl_gen_head;; p = prev.next) {
884 prevl = (uintptr_t)atomic_load_ptr(&p->next);
885 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
886 PV_STAT(counter_u64_add(invl_start_restart, 1));
892 prev.next = (void *)prevl;
895 if ((ii = invl_max_qlen) < i)
896 atomic_cmpset_int(&invl_max_qlen, ii, i);
899 if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
900 PV_STAT(counter_u64_add(invl_start_restart, 1));
905 new_prev.gen = prev.gen;
906 new_prev.next = invl_gen;
907 invl_gen->gen = prev.gen + 1;
909 /* Formal fence between store to invl->gen and updating *p. */
910 atomic_thread_fence_rel();
913 * After inserting an invl_gen element with invalid bit set,
914 * this thread blocks any other thread trying to enter the
915 * delayed invalidation block. Do not allow to remove us from
916 * the CPU, because it causes starvation for other threads.
921 * ABA for *p is not possible there, since p->gen can only
922 * increase. So if the *p thread finished its di, then
923 * started a new one and got inserted into the list at the
924 * same place, its gen will appear greater than the previously
927 if (!pmap_di_store_invl(p, &prev, &new_prev)) {
929 PV_STAT(counter_u64_add(invl_start_restart, 1));
935 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
936 * invl_gen->next, allowing other threads to iterate past us.
937 * pmap_di_store_invl() provides fence between the generation
938 * write and the update of next.
940 invl_gen->next = NULL;
945 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
946 struct pmap_invl_gen *p)
948 struct pmap_invl_gen prev, new_prev;
952 * Load invl_gen->gen after setting invl_gen->next
953 * PMAP_INVL_GEN_NEXT_INVALID. This prevents larger
954 * generations to propagate to our invl_gen->gen. Lock prefix
955 * in atomic_set_ptr() worked as seq_cst fence.
957 mygen = atomic_load_long(&invl_gen->gen);
959 if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
962 KASSERT(prev.gen < mygen,
963 ("invalid di gen sequence %lu %lu", prev.gen, mygen));
964 new_prev.gen = mygen;
965 new_prev.next = (void *)((uintptr_t)invl_gen->next &
966 ~PMAP_INVL_GEN_NEXT_INVALID);
968 /* Formal fence between load of prev and storing update to it. */
969 atomic_thread_fence_rel();
971 return (pmap_di_store_invl(p, &prev, &new_prev));
975 pmap_delayed_invl_finish_u(void)
977 struct pmap_invl_gen *invl_gen, *p;
979 struct lock_delay_arg lda;
983 invl_gen = &td->td_md.md_invl_gen;
984 KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
985 KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
986 ("missed invl_start: INVALID"));
987 lock_delay_arg_init(&lda, &di_delay);
990 for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
991 prevl = (uintptr_t)atomic_load_ptr(&p->next);
992 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
993 PV_STAT(counter_u64_add(invl_finish_restart, 1));
997 if ((void *)prevl == invl_gen)
1002 * It is legitimate to not find ourself on the list if a
1003 * thread before us finished its DI and started it again.
1005 if (__predict_false(p == NULL)) {
1006 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1012 atomic_set_ptr((uintptr_t *)&invl_gen->next,
1013 PMAP_INVL_GEN_NEXT_INVALID);
1014 if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
1015 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
1016 PMAP_INVL_GEN_NEXT_INVALID);
1018 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1023 if (atomic_load_int(&pmap_invl_waiters) > 0)
1024 pmap_delayed_invl_finish_unblock(0);
1025 if (invl_gen->saved_pri != 0) {
1027 sched_prio(td, invl_gen->saved_pri);
1033 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
1035 struct pmap_invl_gen *p, *pn;
1040 for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
1042 nextl = (uintptr_t)atomic_load_ptr(&p->next);
1043 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
1044 td = first ? NULL : __containerof(p, struct thread,
1046 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
1047 (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
1048 td != NULL ? td->td_tid : -1);
1054 static COUNTER_U64_DEFINE_EARLY(invl_wait);
1055 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait,
1056 CTLFLAG_RD, &invl_wait,
1057 "Number of times DI invalidation blocked pmap_remove_all/write");
1059 static COUNTER_U64_DEFINE_EARLY(invl_wait_slow);
1060 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD,
1061 &invl_wait_slow, "Number of slow invalidation waits for lockless DI");
1067 pmap_delayed_invl_genp(vm_page_t m)
1072 pa = VM_PAGE_TO_PHYS(m);
1073 if (__predict_false((pa) > pmap_last_pa))
1074 gen = &pv_dummy_large.pv_invl_gen;
1076 gen = &(pa_to_pmdp(pa)->pv_invl_gen);
1082 pmap_delayed_invl_genp(vm_page_t m)
1085 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
1090 pmap_delayed_invl_callout_func(void *arg __unused)
1093 if (atomic_load_int(&pmap_invl_waiters) == 0)
1095 pmap_delayed_invl_finish_unblock(0);
1099 pmap_delayed_invl_callout_init(void *arg __unused)
1102 if (pmap_di_locked())
1104 callout_init(&pmap_invl_callout, 1);
1105 pmap_invl_callout_inited = true;
1107 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
1108 pmap_delayed_invl_callout_init, NULL);
1111 * Ensure that all currently executing DI blocks, that need to flush
1112 * TLB for the given page m, actually flushed the TLB at the time the
1113 * function returned. If the page m has an empty PV list and we call
1114 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1115 * valid mapping for the page m in either its page table or TLB.
1117 * This function works by blocking until the global DI generation
1118 * number catches up with the generation number associated with the
1119 * given page m and its PV list. Since this function's callers
1120 * typically own an object lock and sometimes own a page lock, it
1121 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
1125 pmap_delayed_invl_wait_l(vm_page_t m)
1129 bool accounted = false;
1132 m_gen = pmap_delayed_invl_genp(m);
1133 while (*m_gen > pmap_invl_gen) {
1136 counter_u64_add(invl_wait, 1);
1140 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1145 pmap_delayed_invl_wait_u(vm_page_t m)
1148 struct lock_delay_arg lda;
1152 m_gen = pmap_delayed_invl_genp(m);
1153 lock_delay_arg_init(&lda, &di_delay);
1154 while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1155 if (fast || !pmap_invl_callout_inited) {
1156 PV_STAT(counter_u64_add(invl_wait, 1));
1161 * The page's invalidation generation number
1162 * is still below the current thread's number.
1163 * Prepare to block so that we do not waste
1164 * CPU cycles or worse, suffer livelock.
1166 * Since it is impossible to block without
1167 * racing with pmap_delayed_invl_finish_u(),
1168 * prepare for the race by incrementing
1169 * pmap_invl_waiters and arming a 1-tick
1170 * callout which will unblock us if we lose
1173 atomic_add_int(&pmap_invl_waiters, 1);
1176 * Re-check the current thread's invalidation
1177 * generation after incrementing
1178 * pmap_invl_waiters, so that there is no race
1179 * with pmap_delayed_invl_finish_u() setting
1180 * the page generation and checking
1181 * pmap_invl_waiters. The only race allowed
1182 * is for a missed unblock, which is handled
1186 atomic_load_long(&pmap_invl_gen_head.gen)) {
1187 callout_reset(&pmap_invl_callout, 1,
1188 pmap_delayed_invl_callout_func, NULL);
1189 PV_STAT(counter_u64_add(invl_wait_slow, 1));
1190 pmap_delayed_invl_wait_block(m_gen,
1191 &pmap_invl_gen_head.gen);
1193 atomic_add_int(&pmap_invl_waiters, -1);
1198 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1201 return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1202 pmap_thread_init_invl_gen_u);
1205 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1208 return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1209 pmap_delayed_invl_start_u);
1212 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1215 return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1216 pmap_delayed_invl_finish_u);
1219 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1222 return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1223 pmap_delayed_invl_wait_u);
1227 * Mark the page m's PV list as participating in the current thread's
1228 * DI block. Any threads concurrently using m's PV list to remove or
1229 * restrict all mappings to m will wait for the current thread's DI
1230 * block to complete before proceeding.
1232 * The function works by setting the DI generation number for m's PV
1233 * list to at least the DI generation number of the current thread.
1234 * This forces a caller of pmap_delayed_invl_wait() to block until
1235 * current thread calls pmap_delayed_invl_finish().
1238 pmap_delayed_invl_page(vm_page_t m)
1242 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1243 gen = curthread->td_md.md_invl_gen.gen;
1246 m_gen = pmap_delayed_invl_genp(m);
1254 static caddr_t crashdumpmap;
1257 * Internal flags for pmap_enter()'s helper functions.
1259 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
1260 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
1263 * Internal flags for pmap_mapdev_internal() and
1264 * pmap_change_props_locked().
1266 #define MAPDEV_FLUSHCACHE 0x00000001 /* Flush cache after mapping. */
1267 #define MAPDEV_SETATTR 0x00000002 /* Modify existing attrs. */
1268 #define MAPDEV_ASSERTVALID 0x00000004 /* Assert mapping validity. */
1270 TAILQ_HEAD(pv_chunklist, pv_chunk);
1272 static void free_pv_chunk(struct pv_chunk *pc);
1273 static void free_pv_chunk_batch(struct pv_chunklist *batch);
1274 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
1275 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1276 static int popcnt_pc_map_pq(uint64_t *map);
1277 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1278 static void reserve_pv_entries(pmap_t pmap, int needed,
1279 struct rwlock **lockp);
1280 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1281 struct rwlock **lockp);
1282 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1283 u_int flags, struct rwlock **lockp);
1284 #if VM_NRESERVLEVEL > 0
1285 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1286 struct rwlock **lockp);
1288 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1289 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1292 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
1293 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1294 vm_prot_t prot, int mode, int flags);
1295 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1296 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1297 vm_offset_t va, struct rwlock **lockp);
1298 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1300 static int pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1301 vm_prot_t prot, struct rwlock **lockp);
1302 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1303 u_int flags, vm_page_t m, struct rwlock **lockp);
1304 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1305 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1306 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1307 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
1308 bool allpte_PG_A_set);
1309 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1311 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1313 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1315 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1316 static vm_page_t pmap_large_map_getptp_unlocked(void);
1317 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1318 #if VM_NRESERVLEVEL > 0
1319 static bool pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1320 vm_page_t mpte, struct rwlock **lockp);
1322 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1324 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1325 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1327 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1328 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1329 static void pmap_pti_wire_pte(void *pte);
1330 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1331 struct spglist *free, struct rwlock **lockp);
1332 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1333 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1334 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1335 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1336 struct spglist *free);
1337 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1338 pd_entry_t *pde, struct spglist *free,
1339 struct rwlock **lockp);
1340 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1341 vm_page_t m, struct rwlock **lockp);
1342 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1344 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1346 static pd_entry_t *pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
1347 struct rwlock **lockp);
1348 static vm_page_t pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex,
1349 struct rwlock **lockp, vm_offset_t va);
1350 static vm_page_t pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex,
1351 struct rwlock **lockp, vm_offset_t va);
1352 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1353 struct rwlock **lockp);
1355 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1356 struct spglist *free);
1357 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1359 static vm_page_t pmap_alloc_pt_page(pmap_t, vm_pindex_t, int);
1360 static void pmap_free_pt_page(pmap_t, vm_page_t, bool);
1362 /********************/
1363 /* Inline functions */
1364 /********************/
1367 * Return a non-clipped indexes for a given VA, which are page table
1368 * pages indexes at the corresponding level.
1370 static __inline vm_pindex_t
1371 pmap_pde_pindex(vm_offset_t va)
1373 return (va >> PDRSHIFT);
1376 static __inline vm_pindex_t
1377 pmap_pdpe_pindex(vm_offset_t va)
1379 return (NUPDE + (va >> PDPSHIFT));
1382 static __inline vm_pindex_t
1383 pmap_pml4e_pindex(vm_offset_t va)
1385 return (NUPDE + NUPDPE + (va >> PML4SHIFT));
1388 static __inline vm_pindex_t
1389 pmap_pml5e_pindex(vm_offset_t va)
1391 return (NUPDE + NUPDPE + NUPML4E + (va >> PML5SHIFT));
1394 static __inline pml4_entry_t *
1395 pmap_pml5e(pmap_t pmap, vm_offset_t va)
1398 MPASS(pmap_is_la57(pmap));
1399 return (&pmap->pm_pmltop[pmap_pml5e_index(va)]);
1402 static __inline pml4_entry_t *
1403 pmap_pml5e_u(pmap_t pmap, vm_offset_t va)
1406 MPASS(pmap_is_la57(pmap));
1407 return (&pmap->pm_pmltopu[pmap_pml5e_index(va)]);
1410 static __inline pml4_entry_t *
1411 pmap_pml5e_to_pml4e(pml5_entry_t *pml5e, vm_offset_t va)
1413 pml4_entry_t *pml4e;
1415 /* XXX MPASS(pmap_is_la57(pmap); */
1416 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1417 return (&pml4e[pmap_pml4e_index(va)]);
1420 /* Return a pointer to the PML4 slot that corresponds to a VA */
1421 static __inline pml4_entry_t *
1422 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1424 pml5_entry_t *pml5e;
1425 pml4_entry_t *pml4e;
1428 if (pmap_is_la57(pmap)) {
1429 pml5e = pmap_pml5e(pmap, va);
1430 PG_V = pmap_valid_bit(pmap);
1431 if ((*pml5e & PG_V) == 0)
1433 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1435 pml4e = pmap->pm_pmltop;
1437 return (&pml4e[pmap_pml4e_index(va)]);
1440 static __inline pml4_entry_t *
1441 pmap_pml4e_u(pmap_t pmap, vm_offset_t va)
1443 MPASS(!pmap_is_la57(pmap));
1444 return (&pmap->pm_pmltopu[pmap_pml4e_index(va)]);
1447 /* Return a pointer to the PDP slot that corresponds to a VA */
1448 static __inline pdp_entry_t *
1449 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1453 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1454 return (&pdpe[pmap_pdpe_index(va)]);
1457 /* Return a pointer to the PDP slot that corresponds to a VA */
1458 static __inline pdp_entry_t *
1459 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1461 pml4_entry_t *pml4e;
1464 PG_V = pmap_valid_bit(pmap);
1465 pml4e = pmap_pml4e(pmap, va);
1466 if (pml4e == NULL || (*pml4e & PG_V) == 0)
1468 return (pmap_pml4e_to_pdpe(pml4e, va));
1471 /* Return a pointer to the PD slot that corresponds to a VA */
1472 static __inline pd_entry_t *
1473 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1477 KASSERT((*pdpe & PG_PS) == 0,
1478 ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
1479 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1480 return (&pde[pmap_pde_index(va)]);
1483 /* Return a pointer to the PD slot that corresponds to a VA */
1484 static __inline pd_entry_t *
1485 pmap_pde(pmap_t pmap, vm_offset_t va)
1490 PG_V = pmap_valid_bit(pmap);
1491 pdpe = pmap_pdpe(pmap, va);
1492 if (pdpe == NULL || (*pdpe & PG_V) == 0)
1494 KASSERT((*pdpe & PG_PS) == 0,
1495 ("pmap_pde for 1G page, pmap %p va %#lx", pmap, va));
1496 return (pmap_pdpe_to_pde(pdpe, va));
1499 /* Return a pointer to the PT slot that corresponds to a VA */
1500 static __inline pt_entry_t *
1501 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1505 KASSERT((*pde & PG_PS) == 0,
1506 ("%s: pde %#lx is a leaf", __func__, *pde));
1507 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1508 return (&pte[pmap_pte_index(va)]);
1511 /* Return a pointer to the PT slot that corresponds to a VA */
1512 static __inline pt_entry_t *
1513 pmap_pte(pmap_t pmap, vm_offset_t va)
1518 PG_V = pmap_valid_bit(pmap);
1519 pde = pmap_pde(pmap, va);
1520 if (pde == NULL || (*pde & PG_V) == 0)
1522 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
1523 return ((pt_entry_t *)pde);
1524 return (pmap_pde_to_pte(pde, va));
1527 static __inline void
1528 pmap_resident_count_adj(pmap_t pmap, int count)
1531 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1532 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1533 ("pmap %p resident count underflow %ld %d", pmap,
1534 pmap->pm_stats.resident_count, count));
1535 pmap->pm_stats.resident_count += count;
1538 static __inline void
1539 pmap_pt_page_count_pinit(pmap_t pmap, int count)
1541 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1542 ("pmap %p resident count underflow %ld %d", pmap,
1543 pmap->pm_stats.resident_count, count));
1544 pmap->pm_stats.resident_count += count;
1547 static __inline void
1548 pmap_pt_page_count_adj(pmap_t pmap, int count)
1550 if (pmap == kernel_pmap)
1551 counter_u64_add(kernel_pt_page_count, count);
1554 pmap_resident_count_adj(pmap, count);
1555 counter_u64_add(user_pt_page_count, count);
1559 pt_entry_t vtoptem __read_mostly = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
1560 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1) << 3;
1561 vm_offset_t PTmap __read_mostly = (vm_offset_t)P4Tmap;
1563 PMAP_INLINE pt_entry_t *
1564 vtopte(vm_offset_t va)
1566 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1568 return ((pt_entry_t *)(PTmap + ((va >> (PAGE_SHIFT - 3)) & vtoptem)));
1571 pd_entry_t vtopdem __read_mostly = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
1572 NPML4EPGSHIFT)) - 1) << 3;
1573 vm_offset_t PDmap __read_mostly = (vm_offset_t)P4Dmap;
1575 static __inline pd_entry_t *
1576 vtopde(vm_offset_t va)
1578 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1580 return ((pt_entry_t *)(PDmap + ((va >> (PDRSHIFT - 3)) & vtopdem)));
1584 allocpages(vm_paddr_t *firstaddr, int n)
1589 bzero((void *)ret, n * PAGE_SIZE);
1590 *firstaddr += n * PAGE_SIZE;
1594 CTASSERT(powerof2(NDMPML4E));
1596 /* number of kernel PDP slots */
1597 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
1600 nkpt_init(vm_paddr_t addr)
1607 pt_pages = howmany(addr - kernphys, NBPDR) + 1; /* +1 for 2M hole @0 */
1608 pt_pages += NKPDPE(pt_pages);
1611 * Add some slop beyond the bare minimum required for bootstrapping
1614 * This is quite important when allocating KVA for kernel modules.
1615 * The modules are required to be linked in the negative 2GB of
1616 * the address space. If we run out of KVA in this region then
1617 * pmap_growkernel() will need to allocate page table pages to map
1618 * the entire 512GB of KVA space which is an unnecessary tax on
1621 * Secondly, device memory mapped as part of setting up the low-
1622 * level console(s) is taken from KVA, starting at virtual_avail.
1623 * This is because cninit() is called after pmap_bootstrap() but
1624 * before vm_init() and pmap_init(). 20MB for a frame buffer is
1627 pt_pages += 32; /* 64MB additional slop. */
1633 * Returns the proper write/execute permission for a physical page that is
1634 * part of the initial boot allocations.
1636 * If the page has kernel text, it is marked as read-only. If the page has
1637 * kernel read-only data, it is marked as read-only/not-executable. If the
1638 * page has only read-write data, it is marked as read-write/not-executable.
1639 * If the page is below/above the kernel range, it is marked as read-write.
1641 * This function operates on 2M pages, since we map the kernel space that
1644 static inline pt_entry_t
1645 bootaddr_rwx(vm_paddr_t pa)
1648 * The kernel is loaded at a 2MB-aligned address, and memory below that
1649 * need not be executable. The .bss section is padded to a 2MB
1650 * boundary, so memory following the kernel need not be executable
1651 * either. Preloaded kernel modules have their mapping permissions
1652 * fixed up by the linker.
1654 if (pa < trunc_2mpage(kernphys + btext - KERNSTART) ||
1655 pa >= trunc_2mpage(kernphys + _end - KERNSTART))
1656 return (X86_PG_RW | pg_nx);
1659 * The linker should ensure that the read-only and read-write
1660 * portions don't share the same 2M page, so this shouldn't
1661 * impact read-only data. However, in any case, any page with
1662 * read-write data needs to be read-write.
1664 if (pa >= trunc_2mpage(kernphys + brwsection - KERNSTART))
1665 return (X86_PG_RW | pg_nx);
1668 * Mark any 2M page containing kernel text as read-only. Mark
1669 * other pages with read-only data as read-only and not executable.
1670 * (It is likely a small portion of the read-only data section will
1671 * be marked as read-only, but executable. This should be acceptable
1672 * since the read-only protection will keep the data from changing.)
1673 * Note that fixups to the .text section will still work until we
1676 if (pa < round_2mpage(kernphys + etext - KERNSTART))
1682 create_pagetables(vm_paddr_t *firstaddr)
1687 uint64_t DMPDkernphys;
1691 uint64_t KASANPDphys, KASANPTphys, KASANphys;
1692 vm_offset_t kasankernbase;
1693 int kasankpdpi, kasankpdi, nkasanpte;
1695 int i, j, ndm1g, nkpdpe, nkdmpde;
1698 /* Allocate page table pages for the direct map */
1699 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1700 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1702 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1703 if (ndmpdpphys > NDMPML4E) {
1705 * Each NDMPML4E allows 512 GB, so limit to that,
1706 * and then readjust ndmpdp and ndmpdpphys.
1708 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1709 Maxmem = atop(NDMPML4E * NBPML4);
1710 ndmpdpphys = NDMPML4E;
1711 ndmpdp = NDMPML4E * NPDEPG;
1713 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1715 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1717 * Calculate the number of 1G pages that will fully fit in
1720 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1723 * Allocate 2M pages for the kernel. These will be used in
1724 * place of the one or more 1G pages from ndm1g that maps
1725 * kernel memory into DMAP.
1727 nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1728 kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1729 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1732 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1733 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1735 /* Allocate pages. */
1736 KPML4phys = allocpages(firstaddr, 1);
1737 KPDPphys = allocpages(firstaddr, NKPML4E);
1739 KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1740 KASANPDphys = allocpages(firstaddr, 1);
1744 * The KMSAN shadow maps are initially left unpopulated, since there is
1745 * no need to shadow memory above KERNBASE.
1747 KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1748 KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1752 * Allocate the initial number of kernel page table pages required to
1753 * bootstrap. We defer this until after all memory-size dependent
1754 * allocations are done (e.g. direct map), so that we don't have to
1755 * build in too much slop in our estimate.
1757 * Note that when NKPML4E > 1, we have an empty page underneath
1758 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1759 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1761 nkpt_init(*firstaddr);
1762 nkpdpe = NKPDPE(nkpt);
1764 KPTphys = allocpages(firstaddr, nkpt);
1765 KPDphys = allocpages(firstaddr, nkpdpe);
1768 nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1769 KASANPTphys = allocpages(firstaddr, nkasanpte);
1770 KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1774 * Connect the zero-filled PT pages to their PD entries. This
1775 * implicitly maps the PT pages at their correct locations within
1778 pd_p = (pd_entry_t *)KPDphys;
1779 for (i = 0; i < nkpt; i++)
1780 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1783 * Map from start of the kernel in physical memory (staging
1784 * area) to the end of loader preallocated memory using 2MB
1785 * pages. This replaces some of the PD entries created above.
1786 * For compatibility, identity map 2M at the start.
1788 pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1790 for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1791 /* Preset PG_M and PG_A because demotion expects it. */
1792 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1793 X86_PG_A | bootaddr_rwx(pax);
1797 * Because we map the physical blocks in 2M pages, adjust firstaddr
1798 * to record the physical blocks we've actually mapped into kernel
1799 * virtual address space.
1801 if (*firstaddr < round_2mpage(KERNend))
1802 *firstaddr = round_2mpage(KERNend);
1804 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1805 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1806 for (i = 0; i < nkpdpe; i++)
1807 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1810 kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1811 kasankpdpi = pmap_pdpe_index(kasankernbase);
1812 kasankpdi = pmap_pde_index(kasankernbase);
1814 pdp_p = (pdp_entry_t *)KASANPDPphys;
1815 pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1817 pd_p = (pd_entry_t *)KASANPDphys;
1818 for (i = 0; i < nkasanpte; i++)
1819 pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1822 pt_p = (pt_entry_t *)KASANPTphys;
1823 for (i = 0; i < nkasanpte * NPTEPG; i++)
1824 pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1825 X86_PG_M | X86_PG_A | pg_nx;
1829 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1830 * the end of physical memory is not aligned to a 1GB page boundary,
1831 * then the residual physical memory is mapped with 2MB pages. Later,
1832 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1833 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1834 * that are partially used.
1836 pd_p = (pd_entry_t *)DMPDphys;
1837 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1838 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1839 /* Preset PG_M and PG_A because demotion expects it. */
1840 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1841 X86_PG_M | X86_PG_A | pg_nx;
1843 pdp_p = (pdp_entry_t *)DMPDPphys;
1844 for (i = 0; i < ndm1g; i++) {
1845 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1846 /* Preset PG_M and PG_A because demotion expects it. */
1847 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1848 X86_PG_M | X86_PG_A | pg_nx;
1850 for (j = 0; i < ndmpdp; i++, j++) {
1851 pdp_p[i] = DMPDphys + ptoa(j);
1852 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1856 * Instead of using a 1G page for the memory containing the kernel,
1857 * use 2M pages with read-only and no-execute permissions. (If using 1G
1858 * pages, this will partially overwrite the PDPEs above.)
1861 pd_p = (pd_entry_t *)DMPDkernphys;
1862 for (i = 0, pax = rounddown2(kernphys, NBPDP);
1863 i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1864 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1865 X86_PG_A | pg_nx | bootaddr_rwx(pax);
1867 j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1868 for (i = 0; i < nkdmpde; i++) {
1869 pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1870 X86_PG_RW | X86_PG_V | pg_nx;
1874 /* And recursively map PML4 to itself in order to get PTmap */
1875 p4_p = (pml4_entry_t *)KPML4phys;
1876 p4_p[PML4PML4I] = KPML4phys;
1877 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1880 /* Connect the KASAN shadow map slots up to the PML4. */
1881 for (i = 0; i < NKASANPML4E; i++) {
1882 p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1883 p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1888 /* Connect the KMSAN shadow map slots up to the PML4. */
1889 for (i = 0; i < NKMSANSHADPML4E; i++) {
1890 p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1891 p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1894 /* Connect the KMSAN origin map slots up to the PML4. */
1895 for (i = 0; i < NKMSANORIGPML4E; i++) {
1896 p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1897 p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1901 /* Connect the Direct Map slots up to the PML4. */
1902 for (i = 0; i < ndmpdpphys; i++) {
1903 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1904 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1907 /* Connect the KVA slots up to the PML4 */
1908 for (i = 0; i < NKPML4E; i++) {
1909 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1910 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1913 kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1918 * Bootstrap the system enough to run with virtual memory.
1920 * On amd64 this is called after mapping has already been enabled
1921 * and just syncs the pmap module with what has already been done.
1922 * [We can't call it easily with mapping off since the kernel is not
1923 * mapped with PA == VA, hence we would have to relocate every address
1924 * from the linked base (virtual) address "KERNBASE" to the actual
1925 * (physical) address starting relative to 0]
1928 pmap_bootstrap(vm_paddr_t *firstaddr)
1931 pt_entry_t *pte, *pcpu_pte;
1932 struct region_descriptor r_gdt;
1933 uint64_t cr4, pcpu0_phys;
1938 KERNend = *firstaddr;
1939 res = atop(KERNend - (vm_paddr_t)kernphys);
1945 * Create an initial set of page tables to run the kernel in.
1947 create_pagetables(firstaddr);
1949 pcpu0_phys = allocpages(firstaddr, 1);
1952 * Add a physical memory segment (vm_phys_seg) corresponding to the
1953 * preallocated kernel page table pages so that vm_page structures
1954 * representing these pages will be created. The vm_page structures
1955 * are required for promotion of the corresponding kernel virtual
1956 * addresses to superpage mappings.
1958 vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1961 * Account for the virtual addresses mapped by create_pagetables().
1963 virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1964 (vm_paddr_t)kernphys);
1965 virtual_end = VM_MAX_KERNEL_ADDRESS;
1968 * Enable PG_G global pages, then switch to the kernel page
1969 * table from the bootstrap page table. After the switch, it
1970 * is possible to enable SMEP and SMAP since PG_U bits are
1976 load_cr3(KPML4phys);
1977 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1979 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1984 * Initialize the kernel pmap (which is statically allocated).
1985 * Count bootstrap data as being resident in case any of this data is
1986 * later unmapped (using pmap_remove()) and freed.
1988 PMAP_LOCK_INIT(kernel_pmap);
1989 kernel_pmap->pm_pmltop = kernel_pml4;
1990 kernel_pmap->pm_cr3 = KPML4phys;
1991 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1992 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1993 kernel_pmap->pm_stats.resident_count = res;
1994 vm_radix_init(&kernel_pmap->pm_root);
1995 kernel_pmap->pm_flags = pmap_flags;
1996 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
1997 rangeset_init(&kernel_pmap->pm_pkru, pkru_dup_range,
1998 pkru_free_range, kernel_pmap, M_NOWAIT);
2002 * The kernel pmap is always active on all CPUs. Once CPUs are
2003 * enumerated, the mask will be set equal to all_cpus.
2005 CPU_FILL(&kernel_pmap->pm_active);
2008 * Initialize the TLB invalidations generation number lock.
2010 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
2013 * Reserve some special page table entries/VA space for temporary
2016 #define SYSMAP(c, p, v, n) \
2017 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
2023 * Crashdump maps. The first page is reused as CMAP1 for the
2026 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
2027 CADDR1 = crashdumpmap;
2029 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
2033 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2034 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2035 * number of CPUs and NUMA affinity.
2037 pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2038 X86_PG_M | X86_PG_A;
2039 for (i = 1; i < MAXCPU; i++)
2043 * Re-initialize PCPU area for BSP after switching.
2044 * Make hardware use gdt and common_tss from the new PCPU.
2046 STAILQ_INIT(&cpuhead);
2047 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2048 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2049 amd64_bsp_pcpu_init1(&__pcpu[0]);
2050 amd64_bsp_ist_init(&__pcpu[0]);
2051 __pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2053 memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2054 sizeof(struct user_segment_descriptor));
2055 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2056 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2057 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2058 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2059 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2061 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2062 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2063 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2064 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2067 * Initialize the PAT MSR.
2068 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2069 * side-effect, invalidates stale PG_G TLB entries that might
2070 * have been created in our pre-boot environment.
2074 /* Initialize TLB Context Id. */
2075 if (pmap_pcid_enabled) {
2076 kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2077 offsetof(struct pcpu, pc_kpmap_store);
2079 PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2080 PCPU_SET(kpmap_store.pm_gen, 1);
2083 * PMAP_PCID_KERN + 1 is used for initialization of
2084 * proc0 pmap. The pmap' pcid state might be used by
2085 * EFIRT entry before first context switch, so it
2086 * needs to be valid.
2088 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2089 PCPU_SET(pcid_gen, 1);
2092 * pcpu area for APs is zeroed during AP startup.
2093 * pc_pcid_next and pc_pcid_gen are initialized by AP
2094 * during pcpu setup.
2096 load_cr4(rcr4() | CR4_PCIDE);
2102 * Setup the PAT MSR.
2111 /* Bail if this CPU doesn't implement PAT. */
2112 if ((cpu_feature & CPUID_PAT) == 0)
2115 /* Set default PAT index table. */
2116 for (i = 0; i < PAT_INDEX_SIZE; i++)
2118 pat_index[PAT_WRITE_BACK] = 0;
2119 pat_index[PAT_WRITE_THROUGH] = 1;
2120 pat_index[PAT_UNCACHEABLE] = 3;
2121 pat_index[PAT_WRITE_COMBINING] = 6;
2122 pat_index[PAT_WRITE_PROTECTED] = 5;
2123 pat_index[PAT_UNCACHED] = 2;
2126 * Initialize default PAT entries.
2127 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2128 * Program 5 and 6 as WP and WC.
2130 * Leave 4 and 7 as WB and UC. Note that a recursive page table
2131 * mapping for a 2M page uses a PAT value with the bit 3 set due
2132 * to its overload with PG_PS.
2134 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2135 PAT_VALUE(1, PAT_WRITE_THROUGH) |
2136 PAT_VALUE(2, PAT_UNCACHED) |
2137 PAT_VALUE(3, PAT_UNCACHEABLE) |
2138 PAT_VALUE(4, PAT_WRITE_BACK) |
2139 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2140 PAT_VALUE(6, PAT_WRITE_COMBINING) |
2141 PAT_VALUE(7, PAT_UNCACHEABLE);
2145 load_cr4(cr4 & ~CR4_PGE);
2147 /* Disable caches (CD = 1, NW = 0). */
2149 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2151 /* Flushes caches and TLBs. */
2155 /* Update PAT and index table. */
2156 wrmsr(MSR_PAT, pat_msr);
2158 /* Flush caches and TLBs again. */
2162 /* Restore caches and PGE. */
2168 pmap_page_alloc_below_4g(bool zeroed)
2170 return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2171 1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2174 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2175 la57_trampoline_gdt[], la57_trampoline_end[];
2178 pmap_bootstrap_la57(void *arg __unused)
2181 pml5_entry_t *v_pml5;
2182 pml4_entry_t *v_pml4;
2186 vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2187 void (*la57_tramp)(uint64_t pml5);
2188 struct region_descriptor r_gdt;
2190 if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2192 TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2196 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2197 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2199 m_code = pmap_page_alloc_below_4g(true);
2200 v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2201 m_pml5 = pmap_page_alloc_below_4g(true);
2202 KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2203 v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2204 m_pml4 = pmap_page_alloc_below_4g(true);
2205 v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2206 m_pdp = pmap_page_alloc_below_4g(true);
2207 v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2208 m_pd = pmap_page_alloc_below_4g(true);
2209 v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2210 m_pt = pmap_page_alloc_below_4g(true);
2211 v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2214 * Map m_code 1:1, it appears below 4G in KVA due to physical
2215 * address being below 4G. Since kernel KVA is in upper half,
2216 * the pml4e should be zero and free for temporary use.
2218 kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2219 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2221 v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2222 VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2224 v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2225 VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2227 v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2228 VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2232 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2233 * entering all existing kernel mappings into level 5 table.
2235 v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2236 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g;
2239 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2241 v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2242 VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2244 v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2245 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2249 * Copy and call the 48->57 trampoline, hope we return there, alive.
2251 bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2252 *(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2253 la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2254 la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2255 invlpg((vm_offset_t)la57_tramp);
2256 la57_tramp(KPML5phys);
2259 * gdt was necessary reset, switch back to our gdt.
2262 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2266 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2267 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2268 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2271 * Now unmap the trampoline, and free the pages.
2272 * Clear pml5 entry used for 1:1 trampoline mapping.
2274 pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2275 invlpg((vm_offset_t)v_code);
2276 vm_page_free(m_code);
2277 vm_page_free(m_pdp);
2282 * Recursively map PML5 to itself in order to get PTmap and
2285 v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2287 vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2288 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2289 PTmap = (vm_offset_t)P5Tmap;
2290 vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2291 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2292 PDmap = (vm_offset_t)P5Dmap;
2294 kernel_pmap->pm_cr3 = KPML5phys;
2295 kernel_pmap->pm_pmltop = v_pml5;
2296 pmap_pt_page_count_adj(kernel_pmap, 1);
2298 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2301 * Initialize a vm_page's machine-dependent fields.
2304 pmap_page_init(vm_page_t m)
2307 TAILQ_INIT(&m->md.pv_list);
2308 m->md.pat_mode = PAT_WRITE_BACK;
2311 static int pmap_allow_2m_x_ept;
2312 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2313 &pmap_allow_2m_x_ept, 0,
2314 "Allow executable superpage mappings in EPT");
2317 pmap_allow_2m_x_ept_recalculate(void)
2320 * SKL002, SKL012S. Since the EPT format is only used by
2321 * Intel CPUs, the vendor check is merely a formality.
2323 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2324 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2325 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2326 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
2327 CPUID_TO_MODEL(cpu_id) == 0x27 ||
2328 CPUID_TO_MODEL(cpu_id) == 0x35 ||
2329 CPUID_TO_MODEL(cpu_id) == 0x36 ||
2330 CPUID_TO_MODEL(cpu_id) == 0x37 ||
2331 CPUID_TO_MODEL(cpu_id) == 0x86 ||
2332 CPUID_TO_MODEL(cpu_id) == 0x1c ||
2333 CPUID_TO_MODEL(cpu_id) == 0x4a ||
2334 CPUID_TO_MODEL(cpu_id) == 0x4c ||
2335 CPUID_TO_MODEL(cpu_id) == 0x4d ||
2336 CPUID_TO_MODEL(cpu_id) == 0x5a ||
2337 CPUID_TO_MODEL(cpu_id) == 0x5c ||
2338 CPUID_TO_MODEL(cpu_id) == 0x5d ||
2339 CPUID_TO_MODEL(cpu_id) == 0x5f ||
2340 CPUID_TO_MODEL(cpu_id) == 0x6e ||
2341 CPUID_TO_MODEL(cpu_id) == 0x7a ||
2342 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
2343 CPUID_TO_MODEL(cpu_id) == 0x85))))
2344 pmap_allow_2m_x_ept = 1;
2345 #ifndef BURN_BRIDGES
2346 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2348 TUNABLE_INT_FETCH("vm.pmap.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2352 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2355 return (pmap->pm_type != PT_EPT || !executable ||
2356 !pmap_allow_2m_x_ept);
2361 pmap_init_pv_table(void)
2363 struct pmap_large_md_page *pvd;
2365 long start, end, highest, pv_npg;
2366 int domain, i, j, pages;
2369 * For correctness we depend on the size being evenly divisible into a
2370 * page. As a tradeoff between performance and total memory use, the
2371 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2372 * avoids false-sharing, but not being 128 bytes potentially allows for
2373 * avoidable traffic due to adjacent cacheline prefetcher.
2375 * Assert the size so that accidental changes fail to compile.
2377 CTASSERT((sizeof(*pvd) == 64));
2380 * Calculate the size of the array.
2382 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2383 pv_npg = howmany(pmap_last_pa, NBPDR);
2384 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2386 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2387 if (pv_table == NULL)
2388 panic("%s: kva_alloc failed\n", __func__);
2391 * Iterate physical segments to allocate space for respective pages.
2395 for (i = 0; i < vm_phys_nsegs; i++) {
2396 end = vm_phys_segs[i].end / NBPDR;
2397 domain = vm_phys_segs[i].domain;
2402 start = highest + 1;
2403 pvd = &pv_table[start];
2405 pages = end - start + 1;
2406 s = round_page(pages * sizeof(*pvd));
2407 highest = start + (s / sizeof(*pvd)) - 1;
2409 for (j = 0; j < s; j += PAGE_SIZE) {
2410 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2412 panic("failed to allocate PV table page");
2413 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2416 for (j = 0; j < s / sizeof(*pvd); j++) {
2417 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2418 TAILQ_INIT(&pvd->pv_page.pv_list);
2419 pvd->pv_page.pv_gen = 0;
2420 pvd->pv_page.pat_mode = 0;
2421 pvd->pv_invl_gen = 0;
2425 pvd = &pv_dummy_large;
2426 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2427 TAILQ_INIT(&pvd->pv_page.pv_list);
2428 pvd->pv_page.pv_gen = 0;
2429 pvd->pv_page.pat_mode = 0;
2430 pvd->pv_invl_gen = 0;
2434 pmap_init_pv_table(void)
2440 * Initialize the pool of pv list locks.
2442 for (i = 0; i < NPV_LIST_LOCKS; i++)
2443 rw_init(&pv_list_locks[i], "pmap pv list");
2446 * Calculate the size of the pv head table for superpages.
2448 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2451 * Allocate memory for the pv head table for superpages.
2453 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2455 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2456 for (i = 0; i < pv_npg; i++)
2457 TAILQ_INIT(&pv_table[i].pv_list);
2458 TAILQ_INIT(&pv_dummy.pv_list);
2463 * Initialize the pmap module.
2464 * Called by vm_init, to initialize any structures that the pmap
2465 * system needs to map virtual memory.
2470 struct pmap_preinit_mapping *ppim;
2472 int error, i, ret, skz63;
2474 /* L1TF, reserve page @0 unconditionally */
2475 vm_page_blacklist_add(0, bootverbose);
2477 /* Detect bare-metal Skylake Server and Skylake-X. */
2478 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2479 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2481 * Skylake-X errata SKZ63. Processor May Hang When
2482 * Executing Code In an HLE Transaction Region between
2483 * 40000000H and 403FFFFFH.
2485 * Mark the pages in the range as preallocated. It
2486 * seems to be impossible to distinguish between
2487 * Skylake Server and Skylake X.
2490 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2493 printf("SKZ63: skipping 4M RAM starting "
2494 "at physical 1G\n");
2495 for (i = 0; i < atop(0x400000); i++) {
2496 ret = vm_page_blacklist_add(0x40000000 +
2498 if (!ret && bootverbose)
2499 printf("page at %#lx already used\n",
2500 0x40000000 + ptoa(i));
2506 pmap_allow_2m_x_ept_recalculate();
2509 * Initialize the vm page array entries for the kernel pmap's
2512 PMAP_LOCK(kernel_pmap);
2513 for (i = 0; i < nkpt; i++) {
2514 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2515 KASSERT(mpte >= vm_page_array &&
2516 mpte < &vm_page_array[vm_page_array_size],
2517 ("pmap_init: page table page is out of range"));
2518 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2519 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2520 mpte->ref_count = 1;
2523 * Collect the page table pages that were replaced by a 2MB
2524 * page in create_pagetables(). They are zero filled.
2527 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2528 pmap_insert_pt_page(kernel_pmap, mpte, false, false))
2529 panic("pmap_init: pmap_insert_pt_page failed");
2531 PMAP_UNLOCK(kernel_pmap);
2535 * If the kernel is running on a virtual machine, then it must assume
2536 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2537 * be prepared for the hypervisor changing the vendor and family that
2538 * are reported by CPUID. Consequently, the workaround for AMD Family
2539 * 10h Erratum 383 is enabled if the processor's feature set does not
2540 * include at least one feature that is only supported by older Intel
2541 * or newer AMD processors.
2543 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2544 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2545 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2547 workaround_erratum383 = 1;
2550 * Are large page mappings enabled?
2552 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2553 if (pg_ps_enabled) {
2554 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2555 ("pmap_init: can't assign to pagesizes[1]"));
2556 pagesizes[1] = NBPDR;
2557 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2558 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2559 ("pmap_init: can't assign to pagesizes[2]"));
2560 pagesizes[2] = NBPDP;
2565 * Initialize pv chunk lists.
2567 for (i = 0; i < PMAP_MEMDOM; i++) {
2568 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2569 TAILQ_INIT(&pv_chunks[i].pvc_list);
2571 pmap_init_pv_table();
2573 pmap_initialized = 1;
2574 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2575 ppim = pmap_preinit_mapping + i;
2578 /* Make the direct map consistent */
2579 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2580 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2581 ppim->sz, ppim->mode);
2585 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2586 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2589 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2590 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2591 (vmem_addr_t *)&qframe);
2593 panic("qframe allocation failed");
2596 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2597 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2598 lm_ents = LMEPML4I - LMSPML4I + 1;
2600 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2602 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2603 lm_ents, KMSANORIGPML4I - LMSPML4I);
2604 lm_ents = KMSANORIGPML4I - LMSPML4I;
2608 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2609 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2611 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2612 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2613 if (large_vmem == NULL) {
2614 printf("pmap: cannot create large map\n");
2617 for (i = 0; i < lm_ents; i++) {
2618 m = pmap_large_map_getptp_unlocked();
2620 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2621 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2627 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2628 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2629 "Maximum number of PML4 entries for use by large map (tunable). "
2630 "Each entry corresponds to 512GB of address space.");
2632 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2633 "2MB page mapping counters");
2635 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2636 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2637 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2639 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2640 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2641 &pmap_pde_mappings, "2MB page mappings");
2643 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2644 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2645 &pmap_pde_p_failures, "2MB page promotion failures");
2647 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2648 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2649 &pmap_pde_promotions, "2MB page promotions");
2651 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2652 "1GB page mapping counters");
2654 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2655 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2656 &pmap_pdpe_demotions, "1GB page demotions");
2658 /***************************************************
2659 * Low level helper routines.....
2660 ***************************************************/
2663 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2665 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2667 switch (pmap->pm_type) {
2670 /* Verify that both PAT bits are not set at the same time */
2671 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2672 ("Invalid PAT bits in entry %#lx", entry));
2674 /* Swap the PAT bits if one of them is set */
2675 if ((entry & x86_pat_bits) != 0)
2676 entry ^= x86_pat_bits;
2680 * Nothing to do - the memory attributes are represented
2681 * the same way for regular pages and superpages.
2685 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2692 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2695 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2696 pat_index[(int)mode] >= 0);
2700 * Determine the appropriate bits to set in a PTE or PDE for a specified
2704 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2706 int cache_bits, pat_flag, pat_idx;
2708 if (!pmap_is_valid_memattr(pmap, mode))
2709 panic("Unknown caching mode %d\n", mode);
2711 switch (pmap->pm_type) {
2714 /* The PAT bit is different for PTE's and PDE's. */
2715 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2717 /* Map the caching mode to a PAT index. */
2718 pat_idx = pat_index[mode];
2720 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2723 cache_bits |= pat_flag;
2725 cache_bits |= PG_NC_PCD;
2727 cache_bits |= PG_NC_PWT;
2731 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2735 panic("unsupported pmap type %d", pmap->pm_type);
2738 return (cache_bits);
2742 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2746 switch (pmap->pm_type) {
2749 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2752 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2755 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2762 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2764 int pat_flag, pat_idx;
2767 switch (pmap->pm_type) {
2770 /* The PAT bit is different for PTE's and PDE's. */
2771 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2773 if ((pte & pat_flag) != 0)
2775 if ((pte & PG_NC_PCD) != 0)
2777 if ((pte & PG_NC_PWT) != 0)
2781 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2782 panic("EPT PTE %#lx has no PAT memory type", pte);
2783 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2787 /* See pmap_init_pat(). */
2797 pmap_ps_enabled(pmap_t pmap)
2800 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2804 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2807 switch (pmap->pm_type) {
2814 * This is a little bogus since the generation number is
2815 * supposed to be bumped up when a region of the address
2816 * space is invalidated in the page tables.
2818 * In this case the old PDE entry is valid but yet we want
2819 * to make sure that any mappings using the old entry are
2820 * invalidated in the TLB.
2822 * The reason this works as expected is because we rendezvous
2823 * "all" host cpus and force any vcpu context to exit as a
2826 atomic_add_long(&pmap->pm_eptgen, 1);
2829 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2831 pde_store(pde, newpde);
2835 * After changing the page size for the specified virtual address in the page
2836 * table, flush the corresponding entries from the processor's TLB. Only the
2837 * calling processor's TLB is affected.
2839 * The calling thread must be pinned to a processor.
2842 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2846 if (pmap_type_guest(pmap))
2849 KASSERT(pmap->pm_type == PT_X86,
2850 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2852 PG_G = pmap_global_bit(pmap);
2854 if ((newpde & PG_PS) == 0)
2855 /* Demotion: flush a specific 2MB page mapping. */
2856 pmap_invlpg(pmap, va);
2857 else if ((newpde & PG_G) == 0)
2859 * Promotion: flush every 4KB page mapping from the TLB
2860 * because there are too many to flush individually.
2865 * Promotion: flush every 4KB page mapping from the TLB,
2866 * including any global (PG_G) mappings.
2873 * The amd64 pmap uses different approaches to TLB invalidation
2874 * depending on the kernel configuration, available hardware features,
2875 * and known hardware errata. The kernel configuration option that
2876 * has the greatest operational impact on TLB invalidation is PTI,
2877 * which is enabled automatically on affected Intel CPUs. The most
2878 * impactful hardware features are first PCID, and then INVPCID
2879 * instruction presence. PCID usage is quite different for PTI
2882 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2883 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2884 * space is served by two page tables, user and kernel. The user
2885 * page table only maps user space and a kernel trampoline. The
2886 * kernel trampoline includes the entirety of the kernel text but
2887 * only the kernel data that is needed to switch from user to kernel
2888 * mode. The kernel page table maps the user and kernel address
2889 * spaces in their entirety. It is identical to the per-process
2890 * page table used in non-PTI mode.
2892 * User page tables are only used when the CPU is in user mode.
2893 * Consequently, some TLB invalidations can be postponed until the
2894 * switch from kernel to user mode. In contrast, the user
2895 * space part of the kernel page table is used for copyout(9), so
2896 * TLB invalidations on this page table cannot be similarly postponed.
2898 * The existence of a user mode page table for the given pmap is
2899 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2900 * which case pm_ucr3 contains the %cr3 register value for the user
2901 * mode page table's root.
2903 * * The pm_active bitmask indicates which CPUs currently have the
2904 * pmap active. A CPU's bit is set on context switch to the pmap, and
2905 * cleared on switching off this CPU. For the kernel page table,
2906 * the pm_active field is immutable and contains all CPUs. The
2907 * kernel page table is always logically active on every processor,
2908 * but not necessarily in use by the hardware, e.g., in PTI mode.
2910 * When requesting invalidation of virtual addresses with
2911 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2912 * all CPUs recorded as active in pm_active. Updates to and reads
2913 * from pm_active are not synchronized, and so they may race with
2914 * each other. Shootdown handlers are prepared to handle the race.
2916 * * PCID is an optional feature of the long mode x86 MMU where TLB
2917 * entries are tagged with the 'Process ID' of the address space
2918 * they belong to. This feature provides a limited namespace for
2919 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2922 * Allocation of a PCID to a pmap is done by an algorithm described
2923 * in section 15.12, "Other TLB Consistency Algorithms", of
2924 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2925 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2926 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2927 * the CPU is about to start caching TLB entries from a pmap,
2928 * i.e., on the context switch that activates the pmap on the CPU.
2930 * The PCID allocator maintains a per-CPU, per-pmap generation
2931 * count, pm_gen, which is incremented each time a new PCID is
2932 * allocated. On TLB invalidation, the generation counters for the
2933 * pmap are zeroed, which signals the context switch code that the
2934 * previously allocated PCID is no longer valid. Effectively,
2935 * zeroing any of these counters triggers a TLB shootdown for the
2936 * given CPU/address space, due to the allocation of a new PCID.
2938 * Zeroing can be performed remotely. Consequently, if a pmap is
2939 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2940 * be initiated by an ordinary memory access to reset the target
2941 * CPU's generation count within the pmap. The CPU initiating the
2942 * TLB shootdown does not need to send an IPI to the target CPU.
2944 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2945 * for complete (kernel) page tables, and PCIDs for user mode page
2946 * tables. A user PCID value is obtained from the kernel PCID value
2947 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2949 * User space page tables are activated on return to user mode, by
2950 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2951 * clearing bit 63 of the loaded ucr3, this effectively causes
2952 * complete invalidation of the user mode TLB entries for the
2953 * current pmap. In which case, local invalidations of individual
2954 * pages in the user page table are skipped.
2956 * * Local invalidation, all modes. If the requested invalidation is
2957 * for a specific address or the total invalidation of a currently
2958 * active pmap, then the TLB is flushed using INVLPG for a kernel
2959 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2960 * user space page table(s).
2962 * If the INVPCID instruction is available, it is used to flush user
2963 * entries from the kernel page table.
2965 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2966 * entries for the given page that either match the current PCID or
2967 * are global. Since TLB entries for the same page under different
2968 * PCIDs are unaffected, kernel pages which reside in all address
2969 * spaces could be problematic. We avoid the problem by creating
2970 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2973 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2974 * address space, all other 4095 PCIDs are used for user mode spaces
2975 * as described above. A context switch allocates a new PCID if
2976 * the recorded PCID is zero or the recorded generation does not match
2977 * the CPU's generation, effectively flushing the TLB for this address space.
2978 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2979 * local user page: INVLPG
2980 * local kernel page: INVLPG
2981 * local user total: INVPCID(CTX)
2982 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2983 * remote user page, inactive pmap: zero pm_gen
2984 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2985 * (Both actions are required to handle the aforementioned pm_active races.)
2986 * remote kernel page: IPI:INVLPG
2987 * remote user total, inactive pmap: zero pm_gen
2988 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2990 * (See note above about pm_active races.)
2991 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2993 * PTI enabled, PCID present.
2994 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2996 * local kernel page: INVLPG
2997 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
2998 * on loading UCR3 into %cr3 for upt
2999 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
3000 * remote user page, inactive pmap: zero pm_gen
3001 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
3002 * INVPCID(ADDR) for upt)
3003 * remote kernel page: IPI:INVLPG
3004 * remote user total, inactive pmap: zero pm_gen
3005 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
3006 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
3007 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
3010 * local user page: INVLPG
3011 * local kernel page: INVLPG
3012 * local user total: reload %cr3
3013 * local kernel total: invltlb_glob()
3014 * remote user page, inactive pmap: -
3015 * remote user page, active pmap: IPI:INVLPG
3016 * remote kernel page: IPI:INVLPG
3017 * remote user total, inactive pmap: -
3018 * remote user total, active pmap: IPI:(reload %cr3)
3019 * remote kernel total: IPI:invltlb_glob()
3020 * Since on return to user mode, the reload of %cr3 with ucr3 causes
3021 * TLB invalidation, no specific action is required for user page table.
3023 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
3029 * Interrupt the cpus that are executing in the guest context.
3030 * This will force the vcpu to exit and the cached EPT mappings
3031 * will be invalidated by the host before the next vmresume.
3033 static __inline void
3034 pmap_invalidate_ept(pmap_t pmap)
3040 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3041 ("pmap_invalidate_ept: absurd pm_active"));
3044 * The TLB mappings associated with a vcpu context are not
3045 * flushed each time a different vcpu is chosen to execute.
3047 * This is in contrast with a process's vtop mappings that
3048 * are flushed from the TLB on each context switch.
3050 * Therefore we need to do more than just a TLB shootdown on
3051 * the active cpus in 'pmap->pm_active'. To do this we keep
3052 * track of the number of invalidations performed on this pmap.
3054 * Each vcpu keeps a cache of this counter and compares it
3055 * just before a vmresume. If the counter is out-of-date an
3056 * invept will be done to flush stale mappings from the TLB.
3058 * To ensure that all vCPU threads have observed the new counter
3059 * value before returning, we use SMR. Ordering is important here:
3060 * the VMM enters an SMR read section before loading the counter
3061 * and after updating the pm_active bit set. Thus, pm_active is
3062 * a superset of active readers, and any reader that has observed
3063 * the goal has observed the new counter value.
3065 atomic_add_long(&pmap->pm_eptgen, 1);
3067 goal = smr_advance(pmap->pm_eptsmr);
3070 * Force the vcpu to exit and trap back into the hypervisor.
3072 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3073 ipi_selected(pmap->pm_active, ipinum);
3077 * Ensure that all active vCPUs will observe the new generation counter
3078 * value before executing any more guest instructions.
3080 smr_wait(pmap->pm_eptsmr, goal);
3084 pmap_invalidate_preipi_pcid(pmap_t pmap)
3086 struct pmap_pcid *pcidp;
3091 cpuid = PCPU_GET(cpuid);
3092 if (pmap != PCPU_GET(curpmap))
3093 cpuid = 0xffffffff; /* An impossible value */
3097 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3103 * The fence is between stores to pm_gen and the read of the
3104 * pm_active mask. We need to ensure that it is impossible
3105 * for us to miss the bit update in pm_active and
3106 * simultaneously observe a non-zero pm_gen in
3107 * pmap_activate_sw(), otherwise TLB update is missed.
3108 * Without the fence, IA32 allows such an outcome. Note that
3109 * pm_active is updated by a locked operation, which provides
3110 * the reciprocal fence.
3112 atomic_thread_fence_seq_cst();
3116 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3121 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3123 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3124 pmap_invalidate_preipi_nopcid);
3128 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3129 const bool invpcid_works1)
3131 struct invpcid_descr d;
3132 uint64_t kcr3, ucr3;
3136 * Because pm_pcid is recalculated on a context switch, we
3137 * must ensure there is no preemption, not just pinning.
3138 * Otherwise, we might use a stale value below.
3140 CRITICAL_ASSERT(curthread);
3143 * No need to do anything with user page tables invalidation
3144 * if there is no user page table, or invalidation is deferred
3145 * until the return to userspace. ucr3_load_mask is stable
3146 * because we have preemption disabled.
3148 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3149 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3152 pcid = pmap_get_pcid(pmap);
3153 if (invpcid_works1) {
3154 d.pcid = pcid | PMAP_PCID_USER_PT;
3157 invpcid(&d, INVPCID_ADDR);
3159 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3160 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3161 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3166 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3168 pmap_invalidate_page_pcid_cb(pmap, va, true);
3172 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3174 pmap_invalidate_page_pcid_cb(pmap, va, false);
3178 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3182 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3184 if (pmap_pcid_enabled)
3185 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3186 pmap_invalidate_page_pcid_noinvpcid_cb);
3187 return (pmap_invalidate_page_nopcid_cb);
3191 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3192 vm_offset_t addr2 __unused)
3194 if (pmap == kernel_pmap) {
3195 pmap_invlpg(kernel_pmap, va);
3196 } else if (pmap == PCPU_GET(curpmap)) {
3198 pmap_invalidate_page_cb(pmap, va);
3203 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3205 if (pmap_type_guest(pmap)) {
3206 pmap_invalidate_ept(pmap);
3210 KASSERT(pmap->pm_type == PT_X86,
3211 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3213 pmap_invalidate_preipi(pmap);
3214 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3217 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3218 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3221 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3222 const bool invpcid_works1)
3224 struct invpcid_descr d;
3225 uint64_t kcr3, ucr3;
3228 CRITICAL_ASSERT(curthread);
3230 if (pmap != PCPU_GET(curpmap) ||
3231 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3232 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3235 pcid = pmap_get_pcid(pmap);
3236 if (invpcid_works1) {
3237 d.pcid = pcid | PMAP_PCID_USER_PT;
3239 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3240 invpcid(&d, INVPCID_ADDR);
3242 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3243 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3244 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3249 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3252 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3256 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3259 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3263 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3264 vm_offset_t eva __unused)
3268 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3271 if (pmap_pcid_enabled)
3272 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3273 pmap_invalidate_range_pcid_noinvpcid_cb);
3274 return (pmap_invalidate_range_nopcid_cb);
3278 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3282 if (pmap == kernel_pmap) {
3283 if (PCPU_GET(pcid_invlpg_workaround)) {
3284 struct invpcid_descr d = { 0 };
3286 invpcid(&d, INVPCID_CTXGLOB);
3288 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3291 } else if (pmap == PCPU_GET(curpmap)) {
3292 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3294 pmap_invalidate_range_cb(pmap, sva, eva);
3299 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3301 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3302 pmap_invalidate_all(pmap);
3306 if (pmap_type_guest(pmap)) {
3307 pmap_invalidate_ept(pmap);
3311 KASSERT(pmap->pm_type == PT_X86,
3312 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3314 pmap_invalidate_preipi(pmap);
3315 smp_masked_invlpg_range(sva, eva, pmap,
3316 pmap_invalidate_range_curcpu_cb);
3320 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3322 struct invpcid_descr d;
3326 if (pmap == kernel_pmap) {
3327 if (invpcid_works1) {
3328 bzero(&d, sizeof(d));
3329 invpcid(&d, INVPCID_CTXGLOB);
3333 } else if (pmap == PCPU_GET(curpmap)) {
3334 CRITICAL_ASSERT(curthread);
3336 pcid = pmap_get_pcid(pmap);
3337 if (invpcid_works1) {
3341 invpcid(&d, INVPCID_CTX);
3343 kcr3 = pmap->pm_cr3 | pcid;
3346 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3347 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3352 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3354 pmap_invalidate_all_pcid_cb(pmap, true);
3358 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3360 pmap_invalidate_all_pcid_cb(pmap, false);
3364 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3366 if (pmap == kernel_pmap)
3368 else if (pmap == PCPU_GET(curpmap))
3372 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3374 if (pmap_pcid_enabled)
3375 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3376 pmap_invalidate_all_pcid_noinvpcid_cb);
3377 return (pmap_invalidate_all_nopcid_cb);
3381 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3382 vm_offset_t addr2 __unused)
3384 pmap_invalidate_all_cb(pmap);
3388 pmap_invalidate_all(pmap_t pmap)
3390 if (pmap_type_guest(pmap)) {
3391 pmap_invalidate_ept(pmap);
3395 KASSERT(pmap->pm_type == PT_X86,
3396 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3398 pmap_invalidate_preipi(pmap);
3399 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3403 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3404 vm_offset_t addr2 __unused)
3410 pmap_invalidate_cache(void)
3413 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3417 cpuset_t invalidate; /* processors that invalidate their TLB */
3422 u_int store; /* processor that updates the PDE */
3426 pmap_update_pde_action(void *arg)
3428 struct pde_action *act = arg;
3430 if (act->store == PCPU_GET(cpuid))
3431 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3435 pmap_update_pde_teardown(void *arg)
3437 struct pde_action *act = arg;
3439 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3440 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3444 * Change the page size for the specified virtual address in a way that
3445 * prevents any possibility of the TLB ever having two entries that map the
3446 * same virtual address using different page sizes. This is the recommended
3447 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3448 * machine check exception for a TLB state that is improperly diagnosed as a
3452 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3454 struct pde_action act;
3455 cpuset_t active, other_cpus;
3459 cpuid = PCPU_GET(cpuid);
3460 other_cpus = all_cpus;
3461 CPU_CLR(cpuid, &other_cpus);
3462 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3465 active = pmap->pm_active;
3467 if (CPU_OVERLAP(&active, &other_cpus)) {
3469 act.invalidate = active;
3473 act.newpde = newpde;
3474 CPU_SET(cpuid, &active);
3475 smp_rendezvous_cpus(active,
3476 smp_no_rendezvous_barrier, pmap_update_pde_action,
3477 pmap_update_pde_teardown, &act);
3479 pmap_update_pde_store(pmap, pde, newpde);
3480 if (CPU_ISSET(cpuid, &active))
3481 pmap_update_pde_invalidate(pmap, va, newpde);
3487 * Normal, non-SMP, invalidation functions.
3490 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3492 struct invpcid_descr d;
3493 struct pmap_pcid *pcidp;
3494 uint64_t kcr3, ucr3;
3497 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3501 KASSERT(pmap->pm_type == PT_X86,
3502 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3504 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3506 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3507 pmap->pm_ucr3 != PMAP_NO_CR3) {
3509 pcid = pmap_get_pcid(pmap);
3510 if (invpcid_works) {
3511 d.pcid = pcid | PMAP_PCID_USER_PT;
3514 invpcid(&d, INVPCID_ADDR);
3516 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3517 ucr3 = pmap->pm_ucr3 | pcid |
3518 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3519 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3523 } else if (pmap_pcid_enabled) {
3524 pcidp = zpcpu_get(pmap->pm_pcidp);
3530 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3532 struct invpcid_descr d;
3533 struct pmap_pcid *pcidp;
3535 uint64_t kcr3, ucr3;
3538 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3542 KASSERT(pmap->pm_type == PT_X86,
3543 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3545 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3546 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3548 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3549 pmap->pm_ucr3 != PMAP_NO_CR3) {
3551 pcid = pmap_get_pcid(pmap);
3552 if (invpcid_works) {
3553 d.pcid = pcid | PMAP_PCID_USER_PT;
3556 for (; d.addr < eva; d.addr += PAGE_SIZE)
3557 invpcid(&d, INVPCID_ADDR);
3559 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3560 ucr3 = pmap->pm_ucr3 | pcid |
3561 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3562 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3566 } else if (pmap_pcid_enabled) {
3567 pcidp = zpcpu_get(pmap->pm_pcidp);
3573 pmap_invalidate_all(pmap_t pmap)
3575 struct invpcid_descr d;
3576 struct pmap_pcid *pcidp;
3577 uint64_t kcr3, ucr3;
3580 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3584 KASSERT(pmap->pm_type == PT_X86,
3585 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3587 if (pmap == kernel_pmap) {
3588 if (pmap_pcid_enabled && invpcid_works) {
3589 bzero(&d, sizeof(d));
3590 invpcid(&d, INVPCID_CTXGLOB);
3594 } else if (pmap == PCPU_GET(curpmap)) {
3595 if (pmap_pcid_enabled) {
3597 pcid = pmap_get_pcid(pmap);
3598 if (invpcid_works) {
3602 invpcid(&d, INVPCID_CTX);
3603 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3604 d.pcid |= PMAP_PCID_USER_PT;
3605 invpcid(&d, INVPCID_CTX);
3608 kcr3 = pmap->pm_cr3 | pcid;
3609 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3610 ucr3 = pmap->pm_ucr3 | pcid |
3612 pmap_pti_pcid_invalidate(ucr3, kcr3);
3620 } else if (pmap_pcid_enabled) {
3621 pcidp = zpcpu_get(pmap->pm_pcidp);
3627 pmap_invalidate_cache(void)
3634 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3636 struct pmap_pcid *pcidp;
3638 pmap_update_pde_store(pmap, pde, newpde);
3639 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3640 pmap_update_pde_invalidate(pmap, va, newpde);
3642 pcidp = zpcpu_get(pmap->pm_pcidp);
3649 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3653 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3654 * by a promotion that did not invalidate the 512 4KB page mappings
3655 * that might exist in the TLB. Consequently, at this point, the TLB
3656 * may hold both 4KB and 2MB page mappings for the address range [va,
3657 * va + NBPDR). Therefore, the entire range must be invalidated here.
3658 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3659 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3660 * single INVLPG suffices to invalidate the 2MB page mapping from the
3663 if ((pde & PG_PROMOTED) != 0)
3664 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3666 pmap_invalidate_page(pmap, va);
3669 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3670 (vm_offset_t sva, vm_offset_t eva))
3673 if ((cpu_feature & CPUID_SS) != 0)
3674 return (pmap_invalidate_cache_range_selfsnoop);
3675 if ((cpu_feature & CPUID_CLFSH) != 0)
3676 return (pmap_force_invalidate_cache_range);
3677 return (pmap_invalidate_cache_range_all);
3680 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3683 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3686 KASSERT((sva & PAGE_MASK) == 0,
3687 ("pmap_invalidate_cache_range: sva not page-aligned"));
3688 KASSERT((eva & PAGE_MASK) == 0,
3689 ("pmap_invalidate_cache_range: eva not page-aligned"));
3693 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3696 pmap_invalidate_cache_range_check_align(sva, eva);
3700 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3703 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3706 * XXX: Some CPUs fault, hang, or trash the local APIC
3707 * registers if we use CLFLUSH on the local APIC range. The
3708 * local APIC is always uncached, so we don't need to flush
3709 * for that range anyway.
3711 if (pmap_kextract(sva) == lapic_paddr)
3714 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3716 * Do per-cache line flush. Use a locked
3717 * instruction to insure that previous stores are
3718 * included in the write-back. The processor
3719 * propagates flush to other processors in the cache
3722 atomic_thread_fence_seq_cst();
3723 for (; sva < eva; sva += cpu_clflush_line_size)
3725 atomic_thread_fence_seq_cst();
3728 * Writes are ordered by CLFLUSH on Intel CPUs.
3730 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3732 for (; sva < eva; sva += cpu_clflush_line_size)
3734 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3740 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3743 pmap_invalidate_cache_range_check_align(sva, eva);
3744 pmap_invalidate_cache();
3748 * Remove the specified set of pages from the data and instruction caches.
3750 * In contrast to pmap_invalidate_cache_range(), this function does not
3751 * rely on the CPU's self-snoop feature, because it is intended for use
3752 * when moving pages into a different cache domain.
3755 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3757 vm_offset_t daddr, eva;
3761 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3762 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3763 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3764 pmap_invalidate_cache();
3767 atomic_thread_fence_seq_cst();
3768 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3770 for (i = 0; i < count; i++) {
3771 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3772 eva = daddr + PAGE_SIZE;
3773 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3781 atomic_thread_fence_seq_cst();
3782 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3788 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3791 pmap_invalidate_cache_range_check_align(sva, eva);
3793 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3794 pmap_force_invalidate_cache_range(sva, eva);
3798 /* See comment in pmap_force_invalidate_cache_range(). */
3799 if (pmap_kextract(sva) == lapic_paddr)
3802 atomic_thread_fence_seq_cst();
3803 for (; sva < eva; sva += cpu_clflush_line_size)
3805 atomic_thread_fence_seq_cst();
3809 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3813 int error __diagused;
3816 KASSERT((spa & PAGE_MASK) == 0,
3817 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3818 KASSERT((epa & PAGE_MASK) == 0,
3819 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3821 if (spa < dmaplimit) {
3822 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3824 if (dmaplimit >= epa)
3829 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3831 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3833 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3834 pte = vtopte(vaddr);
3835 for (; spa < epa; spa += PAGE_SIZE) {
3837 pte_store(pte, spa | pte_bits);
3838 pmap_invlpg(kernel_pmap, vaddr);
3839 /* XXXKIB atomic inside flush_cache_range are excessive */
3840 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3843 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3847 * Routine: pmap_extract
3849 * Extract the physical page address associated
3850 * with the given map/virtual_address pair.
3853 pmap_extract(pmap_t pmap, vm_offset_t va)
3857 pt_entry_t *pte, PG_V;
3861 PG_V = pmap_valid_bit(pmap);
3863 pdpe = pmap_pdpe(pmap, va);
3864 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3865 if ((*pdpe & PG_PS) != 0)
3866 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3868 pde = pmap_pdpe_to_pde(pdpe, va);
3869 if ((*pde & PG_V) != 0) {
3870 if ((*pde & PG_PS) != 0) {
3871 pa = (*pde & PG_PS_FRAME) |
3874 pte = pmap_pde_to_pte(pde, va);
3875 pa = (*pte & PG_FRAME) |
3886 * Routine: pmap_extract_and_hold
3888 * Atomically extract and hold the physical page
3889 * with the given pmap and virtual address pair
3890 * if that mapping permits the given protection.
3893 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3895 pdp_entry_t pdpe, *pdpep;
3896 pd_entry_t pde, *pdep;
3897 pt_entry_t pte, PG_RW, PG_V;
3901 PG_RW = pmap_rw_bit(pmap);
3902 PG_V = pmap_valid_bit(pmap);
3905 pdpep = pmap_pdpe(pmap, va);
3906 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3908 if ((pdpe & PG_PS) != 0) {
3909 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3911 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3915 pdep = pmap_pdpe_to_pde(pdpep, va);
3916 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3918 if ((pde & PG_PS) != 0) {
3919 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3921 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3925 pte = *pmap_pde_to_pte(pdep, va);
3926 if ((pte & PG_V) == 0 ||
3927 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3929 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3932 if (m != NULL && !vm_page_wire_mapped(m))
3940 * Routine: pmap_kextract
3942 * Extract the physical page address associated with the given kernel
3946 pmap_kextract(vm_offset_t va)
3951 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3952 pa = DMAP_TO_PHYS(va);
3953 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3954 pa = pmap_large_map_kextract(va);
3958 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3961 * Beware of a concurrent promotion that changes the
3962 * PDE at this point! For example, vtopte() must not
3963 * be used to access the PTE because it would use the
3964 * new PDE. It is, however, safe to use the old PDE
3965 * because the page table page is preserved by the
3968 pa = *pmap_pde_to_pte(&pde, va);
3969 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3975 /***************************************************
3976 * Low level mapping routines.....
3977 ***************************************************/
3980 * Add a wired page to the kva.
3981 * Note: not SMP coherent.
3984 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3989 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3990 X86_PG_RW | X86_PG_V);
3993 static __inline void
3994 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
4000 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
4001 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
4002 X86_PG_RW | X86_PG_V | cache_bits);
4006 * Remove a page from the kernel pagetables.
4007 * Note: not SMP coherent.
4010 pmap_kremove(vm_offset_t va)
4019 * Used to map a range of physical addresses into kernel
4020 * virtual address space.
4022 * The value passed in '*virt' is a suggested virtual address for
4023 * the mapping. Architectures which can support a direct-mapped
4024 * physical to virtual region can return the appropriate address
4025 * within that region, leaving '*virt' unchanged. Other
4026 * architectures should map the pages starting at '*virt' and
4027 * update '*virt' with the first usable address after the mapped
4031 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
4033 return PHYS_TO_DMAP(start);
4037 * Add a list of wired pages to the kva
4038 * this routine is only used for temporary
4039 * kernel mappings that do not need to have
4040 * page modification or references recorded.
4041 * Note that old mappings are simply written
4042 * over. The page *must* be wired.
4043 * Note: SMP coherent. Uses a ranged shootdown IPI.
4046 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4048 pt_entry_t *endpte, oldpte, pa, *pte;
4054 endpte = pte + count;
4055 while (pte < endpte) {
4057 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4058 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4059 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4061 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4062 X86_PG_M | X86_PG_RW | X86_PG_V);
4066 if (__predict_false((oldpte & X86_PG_V) != 0))
4067 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4072 * This routine tears out page mappings from the
4073 * kernel -- it is meant only for temporary mappings.
4074 * Note: SMP coherent. Uses a ranged shootdown IPI.
4077 pmap_qremove(vm_offset_t sva, int count)
4082 while (count-- > 0) {
4083 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4087 pmap_invalidate_range(kernel_pmap, sva, va);
4090 /***************************************************
4091 * Page table page management routines.....
4092 ***************************************************/
4094 * Schedule the specified unused page table page to be freed. Specifically,
4095 * add the page to the specified list of pages that will be released to the
4096 * physical memory manager after the TLB has been updated.
4098 static __inline void
4099 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4100 boolean_t set_PG_ZERO)
4104 m->flags |= PG_ZERO;
4106 m->flags &= ~PG_ZERO;
4107 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4111 * Inserts the specified page table page into the specified pmap's collection
4112 * of idle page table pages. Each of a pmap's page table pages is responsible
4113 * for mapping a distinct range of virtual addresses. The pmap's collection is
4114 * ordered by this virtual address range.
4116 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4117 * "mpte"'s valid field will be set to 0.
4119 * If "promoted" is true and "allpte_PG_A_set" is false, then "mpte" must
4120 * contain valid mappings with identical attributes except for PG_A; "mpte"'s
4121 * valid field will be set to 1.
4123 * If "promoted" and "allpte_PG_A_set" are both true, then "mpte" must contain
4124 * valid mappings with identical attributes including PG_A; "mpte"'s valid
4125 * field will be set to VM_PAGE_BITS_ALL.
4128 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4129 bool allpte_PG_A_set)
4132 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4133 KASSERT(promoted || !allpte_PG_A_set,
4134 ("a zero-filled PTP can't have PG_A set in every PTE"));
4135 mpte->valid = promoted ? (allpte_PG_A_set ? VM_PAGE_BITS_ALL : 1) : 0;
4136 return (vm_radix_insert(&pmap->pm_root, mpte));
4140 * Removes the page table page mapping the specified virtual address from the
4141 * specified pmap's collection of idle page table pages, and returns it.
4142 * Otherwise, returns NULL if there is no page table page corresponding to the
4143 * specified virtual address.
4145 static __inline vm_page_t
4146 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4149 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4150 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4154 * Decrements a page table page's reference count, which is used to record the
4155 * number of valid page table entries within the page. If the reference count
4156 * drops to zero, then the page table page is unmapped. Returns TRUE if the
4157 * page table page was unmapped and FALSE otherwise.
4159 static inline boolean_t
4160 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4164 if (m->ref_count == 0) {
4165 _pmap_unwire_ptp(pmap, va, m, free);
4172 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4178 vm_page_t pdpg, pdppg, pml4pg;
4180 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4183 * unmap the page table page
4185 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4187 MPASS(pmap_is_la57(pmap));
4188 pml5 = pmap_pml5e(pmap, va);
4190 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4191 pml5 = pmap_pml5e_u(pmap, va);
4194 } else if (m->pindex >= NUPDE + NUPDPE) {
4196 pml4 = pmap_pml4e(pmap, va);
4198 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4199 va <= VM_MAXUSER_ADDRESS) {
4200 pml4 = pmap_pml4e_u(pmap, va);
4203 } else if (m->pindex >= NUPDE) {
4205 pdp = pmap_pdpe(pmap, va);
4209 pd = pmap_pde(pmap, va);
4212 if (m->pindex < NUPDE) {
4213 /* We just released a PT, unhold the matching PD */
4214 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4215 pmap_unwire_ptp(pmap, va, pdpg, free);
4216 } else if (m->pindex < NUPDE + NUPDPE) {
4217 /* We just released a PD, unhold the matching PDP */
4218 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4219 pmap_unwire_ptp(pmap, va, pdppg, free);
4220 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4221 /* We just released a PDP, unhold the matching PML4 */
4222 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4223 pmap_unwire_ptp(pmap, va, pml4pg, free);
4226 pmap_pt_page_count_adj(pmap, -1);
4229 * Put page on a list so that it is released after
4230 * *ALL* TLB shootdown is done
4232 pmap_add_delayed_free_list(m, free, TRUE);
4236 * After removing a page table entry, this routine is used to
4237 * conditionally free the page, and manage the reference count.
4240 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4241 struct spglist *free)
4245 if (va >= VM_MAXUSER_ADDRESS)
4247 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4248 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4249 return (pmap_unwire_ptp(pmap, va, mpte, free));
4253 * Release a page table page reference after a failed attempt to create a
4257 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4259 struct spglist free;
4262 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4264 * Although "va" was never mapped, paging-structure caches
4265 * could nonetheless have entries that refer to the freed
4266 * page table pages. Invalidate those entries.
4268 pmap_invalidate_page(pmap, va);
4269 vm_page_free_pages_toq(&free, true);
4274 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4276 struct pmap_pcid *pcidp;
4280 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4281 pcidp->pm_pcid = pcid;
4282 pcidp->pm_gen = gen;
4287 pmap_pinit0(pmap_t pmap)
4292 PMAP_LOCK_INIT(pmap);
4293 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4294 pmap->pm_pmltopu = NULL;
4295 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4296 /* hack to keep pmap_pti_pcid_invalidate() alive */
4297 pmap->pm_ucr3 = PMAP_NO_CR3;
4298 vm_radix_init(&pmap->pm_root);
4299 CPU_ZERO(&pmap->pm_active);
4300 TAILQ_INIT(&pmap->pm_pvchunk);
4301 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4302 pmap->pm_flags = pmap_flags;
4303 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4304 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4305 pmap_activate_boot(pmap);
4310 p->p_md.md_flags |= P_MD_KPTI;
4313 pmap_thread_init_invl_gen(td);
4315 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4316 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4317 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4323 pmap_pinit_pml4(vm_page_t pml4pg)
4325 pml4_entry_t *pm_pml4;
4328 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4330 /* Wire in kernel global address entries. */
4331 for (i = 0; i < NKPML4E; i++) {
4332 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4336 for (i = 0; i < NKASANPML4E; i++) {
4337 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4342 for (i = 0; i < NKMSANSHADPML4E; i++) {
4343 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4344 X86_PG_RW | X86_PG_V | pg_nx;
4346 for (i = 0; i < NKMSANORIGPML4E; i++) {
4347 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4348 X86_PG_RW | X86_PG_V | pg_nx;
4351 for (i = 0; i < ndmpdpphys; i++) {
4352 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4356 /* install self-referential address mapping entry(s) */
4357 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4358 X86_PG_A | X86_PG_M;
4360 /* install large map entries if configured */
4361 for (i = 0; i < lm_ents; i++)
4362 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4366 pmap_pinit_pml5(vm_page_t pml5pg)
4368 pml5_entry_t *pm_pml5;
4370 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4373 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4374 * entering all existing kernel mappings into level 5 table.
4376 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4377 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4378 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4381 * Install self-referential address mapping entry.
4383 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4384 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A |
4385 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4389 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4391 pml4_entry_t *pm_pml4u;
4394 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4395 for (i = 0; i < NPML4EPG; i++)
4396 pm_pml4u[i] = pti_pml4[i];
4400 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4402 pml5_entry_t *pm_pml5u;
4404 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4408 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4409 * table, entering all kernel mappings needed for usermode
4410 * into level 5 table.
4412 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4413 pmap_kextract((vm_offset_t)pti_pml4) |
4414 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4415 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4418 /* Allocate a page table page and do related bookkeeping */
4420 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4424 m = vm_page_alloc_noobj(flags);
4425 if (__predict_false(m == NULL))
4428 pmap_pt_page_count_adj(pmap, 1);
4433 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4436 * This function assumes the page will need to be unwired,
4437 * even though the counterpart allocation in pmap_alloc_pt_page()
4438 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4439 * of pmap_free_pt_page() require unwiring. The case in which
4440 * a PT page doesn't require unwiring because its ref_count has
4441 * naturally reached 0 is handled through _pmap_unwire_ptp().
4443 vm_page_unwire_noq(m);
4445 vm_page_free_zero(m);
4449 pmap_pt_page_count_adj(pmap, -1);
4452 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4455 * Initialize a preallocated and zeroed pmap structure,
4456 * such as one in a vmspace structure.
4459 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4461 vm_page_t pmltop_pg, pmltop_pgu;
4462 vm_paddr_t pmltop_phys;
4464 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4467 * Allocate the page directory page. Pass NULL instead of a
4468 * pointer to the pmap here to avoid calling
4469 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4470 * since that requires pmap lock. Instead do the accounting
4473 * Note that final call to pmap_remove() optimization that
4474 * checks for zero resident_count is basically disabled by
4475 * accounting for top-level page. But the optimization was
4476 * not effective since we started using non-managed mapping of
4479 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4481 pmap_pt_page_count_pinit(pmap, 1);
4483 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4484 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4486 if (pmap_pcid_enabled) {
4487 if (pmap->pm_pcidp == NULL)
4488 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4490 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4492 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4493 pmap->pm_ucr3 = PMAP_NO_CR3;
4494 pmap->pm_pmltopu = NULL;
4496 pmap->pm_type = pm_type;
4499 * Do not install the host kernel mappings in the nested page
4500 * tables. These mappings are meaningless in the guest physical
4502 * Install minimal kernel mappings in PTI case.
4506 pmap->pm_cr3 = pmltop_phys;
4507 if (pmap_is_la57(pmap))
4508 pmap_pinit_pml5(pmltop_pg);
4510 pmap_pinit_pml4(pmltop_pg);
4511 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4513 * As with pmltop_pg, pass NULL instead of a
4514 * pointer to the pmap to ensure that the PTI
4515 * page counted explicitly.
4517 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4518 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4519 pmap_pt_page_count_pinit(pmap, 1);
4520 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4521 VM_PAGE_TO_PHYS(pmltop_pgu));
4522 if (pmap_is_la57(pmap))
4523 pmap_pinit_pml5_pti(pmltop_pgu);
4525 pmap_pinit_pml4_pti(pmltop_pgu);
4526 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4528 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4529 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4530 pkru_free_range, pmap, M_NOWAIT);
4535 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4539 vm_radix_init(&pmap->pm_root);
4540 CPU_ZERO(&pmap->pm_active);
4541 TAILQ_INIT(&pmap->pm_pvchunk);
4542 pmap->pm_flags = flags;
4543 pmap->pm_eptgen = 0;
4549 pmap_pinit(pmap_t pmap)
4552 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4556 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4559 struct spglist free;
4561 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4562 if (mpg->ref_count != 0)
4565 _pmap_unwire_ptp(pmap, va, mpg, &free);
4566 pmap_invalidate_page(pmap, va);
4567 vm_page_free_pages_toq(&free, true);
4570 static pml4_entry_t *
4571 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4574 vm_pindex_t pml5index;
4581 if (!pmap_is_la57(pmap))
4582 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4584 PG_V = pmap_valid_bit(pmap);
4585 pml5index = pmap_pml5e_index(va);
4586 pml5 = &pmap->pm_pmltop[pml5index];
4587 if ((*pml5 & PG_V) == 0) {
4588 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4595 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4596 pml4 = &pml4[pmap_pml4e_index(va)];
4597 if ((*pml4 & PG_V) == 0) {
4598 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4599 if (allocated && !addref)
4600 pml4pg->ref_count--;
4601 else if (!allocated && addref)
4602 pml4pg->ref_count++;
4607 static pdp_entry_t *
4608 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4617 PG_V = pmap_valid_bit(pmap);
4619 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4623 if ((*pml4 & PG_V) == 0) {
4624 /* Have to allocate a new pdp, recurse */
4625 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4627 if (pmap_is_la57(pmap))
4628 pmap_allocpte_free_unref(pmap, va,
4629 pmap_pml5e(pmap, va));
4636 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4637 pdp = &pdp[pmap_pdpe_index(va)];
4638 if ((*pdp & PG_V) == 0) {
4639 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4640 if (allocated && !addref)
4642 else if (!allocated && addref)
4649 * The ptepindexes, i.e. page indices, of the page table pages encountered
4650 * while translating virtual address va are defined as follows:
4651 * - for the page table page (last level),
4652 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4653 * in other words, it is just the index of the PDE that maps the page
4655 * - for the page directory page,
4656 * ptepindex = NUPDE (number of userland PD entries) +
4657 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4658 * i.e. index of PDPE is put after the last index of PDE,
4659 * - for the page directory pointer page,
4660 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4662 * i.e. index of pml4e is put after the last index of PDPE,
4663 * - for the PML4 page (if LA57 mode is enabled),
4664 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4665 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4666 * i.e. index of pml5e is put after the last index of PML4E.
4668 * Define an order on the paging entries, where all entries of the
4669 * same height are put together, then heights are put from deepest to
4670 * root. Then ptexpindex is the sequential number of the
4671 * corresponding paging entry in this order.
4673 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4674 * LA57 paging structures even in LA48 paging mode. Moreover, the
4675 * ptepindexes are calculated as if the paging structures were 5-level
4676 * regardless of the actual mode of operation.
4678 * The root page at PML4/PML5 does not participate in this indexing scheme,
4679 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4682 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4685 vm_pindex_t pml5index, pml4index;
4686 pml5_entry_t *pml5, *pml5u;
4687 pml4_entry_t *pml4, *pml4u;
4691 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4693 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4695 PG_A = pmap_accessed_bit(pmap);
4696 PG_M = pmap_modified_bit(pmap);
4697 PG_V = pmap_valid_bit(pmap);
4698 PG_RW = pmap_rw_bit(pmap);
4701 * Allocate a page table page.
4703 m = pmap_alloc_pt_page(pmap, ptepindex,
4704 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4709 * Map the pagetable page into the process address space, if
4710 * it isn't already there.
4712 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4713 MPASS(pmap_is_la57(pmap));
4715 pml5index = pmap_pml5e_index(va);
4716 pml5 = &pmap->pm_pmltop[pml5index];
4717 KASSERT((*pml5 & PG_V) == 0,
4718 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4719 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4721 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4722 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4725 pml5u = &pmap->pm_pmltopu[pml5index];
4726 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4729 } else if (ptepindex >= NUPDE + NUPDPE) {
4730 pml4index = pmap_pml4e_index(va);
4731 /* Wire up a new PDPE page */
4732 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4734 pmap_free_pt_page(pmap, m, true);
4737 KASSERT((*pml4 & PG_V) == 0,
4738 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4739 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4741 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4742 pml4index < NUPML4E) {
4744 * PTI: Make all user-space mappings in the
4745 * kernel-mode page table no-execute so that
4746 * we detect any programming errors that leave
4747 * the kernel-mode page table active on return
4750 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4753 pml4u = &pmap->pm_pmltopu[pml4index];
4754 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4757 } else if (ptepindex >= NUPDE) {
4758 /* Wire up a new PDE page */
4759 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4761 pmap_free_pt_page(pmap, m, true);
4764 KASSERT((*pdp & PG_V) == 0,
4765 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4766 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4768 /* Wire up a new PTE page */
4769 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4771 pmap_free_pt_page(pmap, m, true);
4774 if ((*pdp & PG_V) == 0) {
4775 /* Have to allocate a new pd, recurse */
4776 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4777 lockp, va) == NULL) {
4778 pmap_allocpte_free_unref(pmap, va,
4779 pmap_pml4e(pmap, va));
4780 pmap_free_pt_page(pmap, m, true);
4784 /* Add reference to the pd page */
4785 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4788 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4790 /* Now we know where the page directory page is */
4791 pd = &pd[pmap_pde_index(va)];
4792 KASSERT((*pd & PG_V) == 0,
4793 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4794 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4801 * This routine is called if the desired page table page does not exist.
4803 * If page table page allocation fails, this routine may sleep before
4804 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4805 * occurs right before returning to the caller. This way, we never
4806 * drop pmap lock to sleep while a page table page has ref_count == 0,
4807 * which prevents the page from being freed under us.
4810 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4815 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4816 if (m == NULL && lockp != NULL) {
4817 RELEASE_PV_LIST_LOCK(lockp);
4819 PMAP_ASSERT_NOT_IN_DI();
4827 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4828 struct rwlock **lockp)
4830 pdp_entry_t *pdpe, PG_V;
4833 vm_pindex_t pdpindex;
4835 PG_V = pmap_valid_bit(pmap);
4838 pdpe = pmap_pdpe(pmap, va);
4839 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4840 pde = pmap_pdpe_to_pde(pdpe, va);
4841 if (va < VM_MAXUSER_ADDRESS) {
4842 /* Add a reference to the pd page. */
4843 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4847 } else if (va < VM_MAXUSER_ADDRESS) {
4848 /* Allocate a pd page. */
4849 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4850 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4857 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4858 pde = &pde[pmap_pde_index(va)];
4860 panic("pmap_alloc_pde: missing page table page for va %#lx",
4867 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4869 vm_pindex_t ptepindex;
4870 pd_entry_t *pd, PG_V;
4873 PG_V = pmap_valid_bit(pmap);
4876 * Calculate pagetable page index
4878 ptepindex = pmap_pde_pindex(va);
4881 * Get the page directory entry
4883 pd = pmap_pde(pmap, va);
4886 * This supports switching from a 2MB page to a
4889 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4890 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4892 * Invalidation of the 2MB page mapping may have caused
4893 * the deallocation of the underlying PD page.
4900 * If the page table page is mapped, we just increment the
4901 * hold count, and activate it.
4903 if (pd != NULL && (*pd & PG_V) != 0) {
4904 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4908 * Here if the pte page isn't mapped, or if it has been
4911 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4912 if (m == NULL && lockp != NULL)
4918 /***************************************************
4919 * Pmap allocation/deallocation routines.
4920 ***************************************************/
4923 * Release any resources held by the given physical map.
4924 * Called when a pmap initialized by pmap_pinit is being released.
4925 * Should only be called if the map contains no valid mappings.
4928 pmap_release(pmap_t pmap)
4933 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4934 ("pmap_release: pmap %p has reserved page table page(s)",
4936 KASSERT(CPU_EMPTY(&pmap->pm_active),
4937 ("releasing active pmap %p", pmap));
4939 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4941 if (pmap_is_la57(pmap)) {
4942 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4943 pmap->pm_pmltop[PML5PML5I] = 0;
4945 for (i = 0; i < NKPML4E; i++) /* KVA */
4946 pmap->pm_pmltop[KPML4BASE + i] = 0;
4948 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4949 pmap->pm_pmltop[KASANPML4I + i] = 0;
4952 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4953 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4954 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4955 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4957 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4958 pmap->pm_pmltop[DMPML4I + i] = 0;
4959 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4960 for (i = 0; i < lm_ents; i++) /* Large Map */
4961 pmap->pm_pmltop[LMSPML4I + i] = 0;
4964 pmap_free_pt_page(NULL, m, true);
4965 pmap_pt_page_count_pinit(pmap, -1);
4967 if (pmap->pm_pmltopu != NULL) {
4968 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4970 pmap_free_pt_page(NULL, m, false);
4971 pmap_pt_page_count_pinit(pmap, -1);
4973 if (pmap->pm_type == PT_X86 &&
4974 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4975 rangeset_fini(&pmap->pm_pkru);
4977 KASSERT(pmap->pm_stats.resident_count == 0,
4978 ("pmap_release: pmap %p resident count %ld != 0",
4979 pmap, pmap->pm_stats.resident_count));
4983 kvm_size(SYSCTL_HANDLER_ARGS)
4985 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4987 return sysctl_handle_long(oidp, &ksize, 0, req);
4989 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4990 0, 0, kvm_size, "LU",
4994 kvm_free(SYSCTL_HANDLER_ARGS)
4996 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4998 return sysctl_handle_long(oidp, &kfree, 0, req);
5000 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
5001 0, 0, kvm_free, "LU",
5002 "Amount of KVM free");
5006 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
5011 vm_paddr_t dummypa, dummypd, dummypt;
5014 npdpg = howmany(size, NBPDP);
5015 npde = size / NBPDR;
5017 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
5018 pagezero((void *)PHYS_TO_DMAP(dummypa));
5020 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
5021 pagezero((void *)PHYS_TO_DMAP(dummypt));
5022 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
5023 for (i = 0; i < npdpg; i++)
5024 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
5026 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
5027 for (i = 0; i < NPTEPG; i++)
5028 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
5029 X86_PG_A | X86_PG_M | pg_nx);
5031 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
5032 for (i = 0; i < npde; i++)
5033 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
5035 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
5036 for (i = 0; i < npdpg; i++)
5037 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
5042 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
5046 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
5049 * The end of the page array's KVA region is 2MB aligned, see
5052 size = round_2mpage(end) - start;
5053 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
5054 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
5059 * Allocate physical memory for the vm_page array and map it into KVA,
5060 * attempting to back the vm_pages with domain-local memory.
5063 pmap_page_array_startup(long pages)
5066 pd_entry_t *pde, newpdir;
5067 vm_offset_t va, start, end;
5072 vm_page_array_size = pages;
5074 start = VM_MIN_KERNEL_ADDRESS;
5075 end = start + pages * sizeof(struct vm_page);
5076 for (va = start; va < end; va += NBPDR) {
5077 pfn = first_page + (va - start) / sizeof(struct vm_page);
5078 domain = vm_phys_domain(ptoa(pfn));
5079 pdpe = pmap_pdpe(kernel_pmap, va);
5080 if ((*pdpe & X86_PG_V) == 0) {
5081 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5083 pagezero((void *)PHYS_TO_DMAP(pa));
5084 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5085 X86_PG_A | X86_PG_M);
5087 pde = pmap_pdpe_to_pde(pdpe, va);
5088 if ((*pde & X86_PG_V) != 0)
5089 panic("Unexpected pde");
5090 pa = vm_phys_early_alloc(domain, NBPDR);
5091 for (i = 0; i < NPDEPG; i++)
5092 dump_add_page(pa + i * PAGE_SIZE);
5093 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5094 X86_PG_M | PG_PS | pg_g | pg_nx);
5095 pde_store(pde, newpdir);
5097 vm_page_array = (vm_page_t)start;
5100 pmap_kmsan_page_array_startup(start, end);
5105 * grow the number of kernel page table entries, if needed
5108 pmap_growkernel(vm_offset_t addr)
5112 pd_entry_t *pde, newpdir;
5117 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5120 * The kernel map covers two distinct regions of KVA: that used
5121 * for dynamic kernel memory allocations, and the uppermost 2GB
5122 * of the virtual address space. The latter is used to map the
5123 * kernel and loadable kernel modules. This scheme enables the
5124 * use of a special code generation model for kernel code which
5125 * takes advantage of compact addressing modes in machine code.
5127 * Both regions grow upwards; to avoid wasting memory, the gap
5128 * in between is unmapped. If "addr" is above "KERNBASE", the
5129 * kernel's region is grown, otherwise the kmem region is grown.
5131 * The correctness of this action is based on the following
5132 * argument: vm_map_insert() allocates contiguous ranges of the
5133 * kernel virtual address space. It calls this function if a range
5134 * ends after "kernel_vm_end". If the kernel is mapped between
5135 * "kernel_vm_end" and "addr", then the range cannot begin at
5136 * "kernel_vm_end". In fact, its beginning address cannot be less
5137 * than the kernel. Thus, there is no immediate need to allocate
5138 * any new kernel page table pages between "kernel_vm_end" and
5141 if (KERNBASE < addr) {
5142 end = KERNBASE + nkpt * NBPDR;
5148 end = kernel_vm_end;
5151 addr = roundup2(addr, NBPDR);
5152 if (addr - 1 >= vm_map_max(kernel_map))
5153 addr = vm_map_max(kernel_map);
5156 * The grown region is already mapped, so there is
5163 kasan_shadow_map(end, addr - end);
5164 kmsan_shadow_map(end, addr - end);
5165 while (end < addr) {
5166 pdpe = pmap_pdpe(kernel_pmap, end);
5167 if ((*pdpe & X86_PG_V) == 0) {
5168 nkpg = pmap_alloc_pt_page(kernel_pmap,
5169 pmap_pdpe_pindex(end), VM_ALLOC_WIRED |
5170 VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5172 panic("pmap_growkernel: no memory to grow kernel");
5173 paddr = VM_PAGE_TO_PHYS(nkpg);
5174 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5175 X86_PG_A | X86_PG_M);
5176 continue; /* try again */
5178 pde = pmap_pdpe_to_pde(pdpe, end);
5179 if ((*pde & X86_PG_V) != 0) {
5180 end = (end + NBPDR) & ~PDRMASK;
5181 if (end - 1 >= vm_map_max(kernel_map)) {
5182 end = vm_map_max(kernel_map);
5188 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5189 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5191 panic("pmap_growkernel: no memory to grow kernel");
5192 paddr = VM_PAGE_TO_PHYS(nkpg);
5193 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5194 pde_store(pde, newpdir);
5196 end = (end + NBPDR) & ~PDRMASK;
5197 if (end - 1 >= vm_map_max(kernel_map)) {
5198 end = vm_map_max(kernel_map);
5203 if (end <= KERNBASE)
5204 kernel_vm_end = end;
5206 nkpt = howmany(end - KERNBASE, NBPDR);
5210 /***************************************************
5211 * page management routines.
5212 ***************************************************/
5214 static const uint64_t pc_freemask[_NPCM] = {
5215 [0 ... _NPCM - 2] = PC_FREEN,
5216 [_NPCM - 1] = PC_FREEL
5221 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5222 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5223 &pc_chunk_count, "Current number of pv entry cnunks");
5225 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5226 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5227 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5229 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5230 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5231 &pc_chunk_frees, "Total number of pv entry chunks freed");
5233 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5234 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5236 "Number of failed attempts to get a pv entry chunk page");
5238 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5239 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5240 &pv_entry_frees, "Total number of pv entries freed");
5242 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5243 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5244 &pv_entry_allocs, "Total number of pv entries allocated");
5246 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5247 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5248 &pv_entry_count, "Current number of pv entries");
5250 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5251 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5252 &pv_entry_spare, "Current number of spare pv entries");
5256 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5261 pmap_invalidate_all(pmap);
5262 if (pmap != locked_pmap)
5265 pmap_delayed_invl_finish();
5269 * We are in a serious low memory condition. Resort to
5270 * drastic measures to free some pages so we can allocate
5271 * another pv entry chunk.
5273 * Returns NULL if PV entries were reclaimed from the specified pmap.
5275 * We do not, however, unmap 2mpages because subsequent accesses will
5276 * allocate per-page pv entries until repromotion occurs, thereby
5277 * exacerbating the shortage of free pv entries.
5280 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5282 struct pv_chunks_list *pvc;
5283 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5284 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5285 struct md_page *pvh;
5287 pmap_t next_pmap, pmap;
5288 pt_entry_t *pte, tpte;
5289 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5293 struct spglist free;
5295 int bit, field, freed;
5296 bool start_di, restart;
5298 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5299 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5302 PG_G = PG_A = PG_M = PG_RW = 0;
5304 bzero(&pc_marker_b, sizeof(pc_marker_b));
5305 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5306 pc_marker = (struct pv_chunk *)&pc_marker_b;
5307 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5310 * A delayed invalidation block should already be active if
5311 * pmap_advise() or pmap_remove() called this function by way
5312 * of pmap_demote_pde_locked().
5314 start_di = pmap_not_in_di();
5316 pvc = &pv_chunks[domain];
5317 mtx_lock(&pvc->pvc_lock);
5318 pvc->active_reclaims++;
5319 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5320 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5321 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5322 SLIST_EMPTY(&free)) {
5323 next_pmap = pc->pc_pmap;
5324 if (next_pmap == NULL) {
5326 * The next chunk is a marker. However, it is
5327 * not our marker, so active_reclaims must be
5328 * > 1. Consequently, the next_chunk code
5329 * will not rotate the pv_chunks list.
5333 mtx_unlock(&pvc->pvc_lock);
5336 * A pv_chunk can only be removed from the pc_lru list
5337 * when both pc_chunks_mutex is owned and the
5338 * corresponding pmap is locked.
5340 if (pmap != next_pmap) {
5342 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5345 /* Avoid deadlock and lock recursion. */
5346 if (pmap > locked_pmap) {
5347 RELEASE_PV_LIST_LOCK(lockp);
5350 pmap_delayed_invl_start();
5351 mtx_lock(&pvc->pvc_lock);
5353 } else if (pmap != locked_pmap) {
5354 if (PMAP_TRYLOCK(pmap)) {
5356 pmap_delayed_invl_start();
5357 mtx_lock(&pvc->pvc_lock);
5360 pmap = NULL; /* pmap is not locked */
5361 mtx_lock(&pvc->pvc_lock);
5362 pc = TAILQ_NEXT(pc_marker, pc_lru);
5364 pc->pc_pmap != next_pmap)
5368 } else if (start_di)
5369 pmap_delayed_invl_start();
5370 PG_G = pmap_global_bit(pmap);
5371 PG_A = pmap_accessed_bit(pmap);
5372 PG_M = pmap_modified_bit(pmap);
5373 PG_RW = pmap_rw_bit(pmap);
5379 * Destroy every non-wired, 4 KB page mapping in the chunk.
5382 for (field = 0; field < _NPCM; field++) {
5383 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5384 inuse != 0; inuse &= ~(1UL << bit)) {
5386 pv = &pc->pc_pventry[field * 64 + bit];
5388 pde = pmap_pde(pmap, va);
5389 if ((*pde & PG_PS) != 0)
5391 pte = pmap_pde_to_pte(pde, va);
5392 if ((*pte & PG_W) != 0)
5394 tpte = pte_load_clear(pte);
5395 if ((tpte & PG_G) != 0)
5396 pmap_invalidate_page(pmap, va);
5397 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5398 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5400 if ((tpte & PG_A) != 0)
5401 vm_page_aflag_set(m, PGA_REFERENCED);
5402 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5403 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5405 if (TAILQ_EMPTY(&m->md.pv_list) &&
5406 (m->flags & PG_FICTITIOUS) == 0) {
5407 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5408 if (TAILQ_EMPTY(&pvh->pv_list)) {
5409 vm_page_aflag_clear(m,
5413 pmap_delayed_invl_page(m);
5414 pc->pc_map[field] |= 1UL << bit;
5415 pmap_unuse_pt(pmap, va, *pde, &free);
5420 mtx_lock(&pvc->pvc_lock);
5423 /* Every freed mapping is for a 4 KB page. */
5424 pmap_resident_count_adj(pmap, -freed);
5425 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5426 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5427 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5428 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5429 if (pc_is_free(pc)) {
5430 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5431 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5432 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5433 /* Entire chunk is free; return it. */
5434 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5435 dump_drop_page(m_pc->phys_addr);
5436 mtx_lock(&pvc->pvc_lock);
5437 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5440 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5441 mtx_lock(&pvc->pvc_lock);
5442 /* One freed pv entry in locked_pmap is sufficient. */
5443 if (pmap == locked_pmap)
5446 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5447 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5448 if (pvc->active_reclaims == 1 && pmap != NULL) {
5450 * Rotate the pv chunks list so that we do not
5451 * scan the same pv chunks that could not be
5452 * freed (because they contained a wired
5453 * and/or superpage mapping) on every
5454 * invocation of reclaim_pv_chunk().
5456 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5457 MPASS(pc->pc_pmap != NULL);
5458 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5459 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5463 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5464 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5465 pvc->active_reclaims--;
5466 mtx_unlock(&pvc->pvc_lock);
5467 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5468 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5469 m_pc = SLIST_FIRST(&free);
5470 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5471 /* Recycle a freed page table page. */
5472 m_pc->ref_count = 1;
5474 vm_page_free_pages_toq(&free, true);
5479 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5484 domain = PCPU_GET(domain);
5485 for (i = 0; i < vm_ndomains; i++) {
5486 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5489 domain = (domain + 1) % vm_ndomains;
5496 * free the pv_entry back to the free list
5499 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5501 struct pv_chunk *pc;
5502 int idx, field, bit;
5504 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5505 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5506 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5507 PV_STAT(counter_u64_add(pv_entry_count, -1));
5508 pc = pv_to_chunk(pv);
5509 idx = pv - &pc->pc_pventry[0];
5512 pc->pc_map[field] |= 1ul << bit;
5513 if (!pc_is_free(pc)) {
5514 /* 98% of the time, pc is already at the head of the list. */
5515 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5516 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5517 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5521 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5526 free_pv_chunk_dequeued(struct pv_chunk *pc)
5530 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5531 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5532 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5533 counter_u64_add(pv_page_count, -1);
5534 /* entire chunk is free, return it */
5535 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5536 dump_drop_page(m->phys_addr);
5537 vm_page_unwire_noq(m);
5542 free_pv_chunk(struct pv_chunk *pc)
5544 struct pv_chunks_list *pvc;
5546 pvc = &pv_chunks[pc_to_domain(pc)];
5547 mtx_lock(&pvc->pvc_lock);
5548 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5549 mtx_unlock(&pvc->pvc_lock);
5550 free_pv_chunk_dequeued(pc);
5554 free_pv_chunk_batch(struct pv_chunklist *batch)
5556 struct pv_chunks_list *pvc;
5557 struct pv_chunk *pc, *npc;
5560 for (i = 0; i < vm_ndomains; i++) {
5561 if (TAILQ_EMPTY(&batch[i]))
5563 pvc = &pv_chunks[i];
5564 mtx_lock(&pvc->pvc_lock);
5565 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5566 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5568 mtx_unlock(&pvc->pvc_lock);
5571 for (i = 0; i < vm_ndomains; i++) {
5572 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5573 free_pv_chunk_dequeued(pc);
5579 * Returns a new PV entry, allocating a new PV chunk from the system when
5580 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5581 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5584 * The given PV list lock may be released.
5587 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5589 struct pv_chunks_list *pvc;
5592 struct pv_chunk *pc;
5595 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5596 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5598 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5600 for (field = 0; field < _NPCM; field++) {
5601 if (pc->pc_map[field]) {
5602 bit = bsfq(pc->pc_map[field]);
5606 if (field < _NPCM) {
5607 pv = &pc->pc_pventry[field * 64 + bit];
5608 pc->pc_map[field] &= ~(1ul << bit);
5609 /* If this was the last item, move it to tail */
5610 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
5611 pc->pc_map[2] == 0) {
5612 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5613 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5616 PV_STAT(counter_u64_add(pv_entry_count, 1));
5617 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5621 /* No free items, allocate another chunk */
5622 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5624 if (lockp == NULL) {
5625 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5628 m = reclaim_pv_chunk(pmap, lockp);
5632 counter_u64_add(pv_page_count, 1);
5633 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5634 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5635 dump_add_page(m->phys_addr);
5636 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5638 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5639 pc->pc_map[1] = PC_FREEN;
5640 pc->pc_map[2] = PC_FREEL;
5641 pvc = &pv_chunks[vm_page_domain(m)];
5642 mtx_lock(&pvc->pvc_lock);
5643 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5644 mtx_unlock(&pvc->pvc_lock);
5645 pv = &pc->pc_pventry[0];
5646 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5647 PV_STAT(counter_u64_add(pv_entry_count, 1));
5648 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5653 * Returns the number of one bits within the given PV chunk map.
5655 * The erratas for Intel processors state that "POPCNT Instruction May
5656 * Take Longer to Execute Than Expected". It is believed that the
5657 * issue is the spurious dependency on the destination register.
5658 * Provide a hint to the register rename logic that the destination
5659 * value is overwritten, by clearing it, as suggested in the
5660 * optimization manual. It should be cheap for unaffected processors
5663 * Reference numbers for erratas are
5664 * 4th Gen Core: HSD146
5665 * 5th Gen Core: BDM85
5666 * 6th Gen Core: SKL029
5669 popcnt_pc_map_pq(uint64_t *map)
5673 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5674 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5675 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5676 : "=&r" (result), "=&r" (tmp)
5677 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5682 * Ensure that the number of spare PV entries in the specified pmap meets or
5683 * exceeds the given count, "needed".
5685 * The given PV list lock may be released.
5688 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5690 struct pv_chunks_list *pvc;
5691 struct pch new_tail[PMAP_MEMDOM];
5692 struct pv_chunk *pc;
5697 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5698 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5701 * Newly allocated PV chunks must be stored in a private list until
5702 * the required number of PV chunks have been allocated. Otherwise,
5703 * reclaim_pv_chunk() could recycle one of these chunks. In
5704 * contrast, these chunks must be added to the pmap upon allocation.
5706 for (i = 0; i < PMAP_MEMDOM; i++)
5707 TAILQ_INIT(&new_tail[i]);
5710 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5712 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5713 bit_count((bitstr_t *)pc->pc_map, 0,
5714 sizeof(pc->pc_map) * NBBY, &free);
5717 free = popcnt_pc_map_pq(pc->pc_map);
5721 if (avail >= needed)
5724 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5725 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5727 m = reclaim_pv_chunk(pmap, lockp);
5732 counter_u64_add(pv_page_count, 1);
5733 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5734 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5735 dump_add_page(m->phys_addr);
5736 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5738 pc->pc_map[0] = PC_FREEN;
5739 pc->pc_map[1] = PC_FREEN;
5740 pc->pc_map[2] = PC_FREEL;
5741 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5742 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5743 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5746 * The reclaim might have freed a chunk from the current pmap.
5747 * If that chunk contained available entries, we need to
5748 * re-count the number of available entries.
5753 for (i = 0; i < vm_ndomains; i++) {
5754 if (TAILQ_EMPTY(&new_tail[i]))
5756 pvc = &pv_chunks[i];
5757 mtx_lock(&pvc->pvc_lock);
5758 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5759 mtx_unlock(&pvc->pvc_lock);
5764 * First find and then remove the pv entry for the specified pmap and virtual
5765 * address from the specified pv list. Returns the pv entry if found and NULL
5766 * otherwise. This operation can be performed on pv lists for either 4KB or
5767 * 2MB page mappings.
5769 static __inline pv_entry_t
5770 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5774 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5775 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5776 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5785 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5786 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5787 * entries for each of the 4KB page mappings.
5790 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5791 struct rwlock **lockp)
5793 struct md_page *pvh;
5794 struct pv_chunk *pc;
5796 vm_offset_t va_last;
5800 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5801 KASSERT((pa & PDRMASK) == 0,
5802 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5803 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5806 * Transfer the 2mpage's pv entry for this mapping to the first
5807 * page's pv list. Once this transfer begins, the pv list lock
5808 * must not be released until the last pv entry is reinstantiated.
5810 pvh = pa_to_pvh(pa);
5811 va = trunc_2mpage(va);
5812 pv = pmap_pvh_remove(pvh, pmap, va);
5813 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5814 m = PHYS_TO_VM_PAGE(pa);
5815 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5817 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5818 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5819 va_last = va + NBPDR - PAGE_SIZE;
5821 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5822 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
5823 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
5824 for (field = 0; field < _NPCM; field++) {
5825 while (pc->pc_map[field]) {
5826 bit = bsfq(pc->pc_map[field]);
5827 pc->pc_map[field] &= ~(1ul << bit);
5828 pv = &pc->pc_pventry[field * 64 + bit];
5832 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5833 ("pmap_pv_demote_pde: page %p is not managed", m));
5834 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5840 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5841 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5844 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
5845 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5846 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5848 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5849 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5852 #if VM_NRESERVLEVEL > 0
5854 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5855 * replace the many pv entries for the 4KB page mappings by a single pv entry
5856 * for the 2MB page mapping.
5859 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5860 struct rwlock **lockp)
5862 struct md_page *pvh;
5864 vm_offset_t va_last;
5867 KASSERT((pa & PDRMASK) == 0,
5868 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5869 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5872 * Transfer the first page's pv entry for this mapping to the 2mpage's
5873 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5874 * a transfer avoids the possibility that get_pv_entry() calls
5875 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5876 * mappings that is being promoted.
5878 m = PHYS_TO_VM_PAGE(pa);
5879 va = trunc_2mpage(va);
5880 pv = pmap_pvh_remove(&m->md, pmap, va);
5881 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5882 pvh = pa_to_pvh(pa);
5883 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5885 /* Free the remaining NPTEPG - 1 pv entries. */
5886 va_last = va + NBPDR - PAGE_SIZE;
5890 pmap_pvh_free(&m->md, pmap, va);
5891 } while (va < va_last);
5893 #endif /* VM_NRESERVLEVEL > 0 */
5896 * First find and then destroy the pv entry for the specified pmap and virtual
5897 * address. This operation can be performed on pv lists for either 4KB or 2MB
5901 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5905 pv = pmap_pvh_remove(pvh, pmap, va);
5906 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5907 free_pv_entry(pmap, pv);
5911 * Conditionally create the PV entry for a 4KB page mapping if the required
5912 * memory can be allocated without resorting to reclamation.
5915 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5916 struct rwlock **lockp)
5920 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5921 /* Pass NULL instead of the lock pointer to disable reclamation. */
5922 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5924 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5925 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5933 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5934 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5935 * false if the PV entry cannot be allocated without resorting to reclamation.
5938 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5939 struct rwlock **lockp)
5941 struct md_page *pvh;
5945 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5946 /* Pass NULL instead of the lock pointer to disable reclamation. */
5947 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5948 NULL : lockp)) == NULL)
5951 pa = pde & PG_PS_FRAME;
5952 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5953 pvh = pa_to_pvh(pa);
5954 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5960 * Fills a page table page with mappings to consecutive physical pages.
5963 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5967 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5969 newpte += PAGE_SIZE;
5974 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5975 * mapping is invalidated.
5978 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5980 struct rwlock *lock;
5984 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5991 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5995 pt_entry_t *xpte, *ypte;
5997 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5998 xpte++, newpte += PAGE_SIZE) {
5999 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
6000 printf("pmap_demote_pde: xpte %zd and newpte map "
6001 "different pages: found %#lx, expected %#lx\n",
6002 xpte - firstpte, *xpte, newpte);
6003 printf("page table dump\n");
6004 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
6005 printf("%zd %#lx\n", ypte - firstpte, *ypte);
6010 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
6011 ("pmap_demote_pde: firstpte and newpte map different physical"
6018 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6019 pd_entry_t oldpde, struct rwlock **lockp)
6021 struct spglist free;
6025 sva = trunc_2mpage(va);
6026 pmap_remove_pde(pmap, pde, sva, &free, lockp);
6027 if ((oldpde & pmap_global_bit(pmap)) == 0)
6028 pmap_invalidate_pde_page(pmap, sva, oldpde);
6029 vm_page_free_pages_toq(&free, true);
6030 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
6035 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
6036 struct rwlock **lockp)
6038 pd_entry_t newpde, oldpde;
6039 pt_entry_t *firstpte, newpte;
6040 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6046 PG_A = pmap_accessed_bit(pmap);
6047 PG_G = pmap_global_bit(pmap);
6048 PG_M = pmap_modified_bit(pmap);
6049 PG_RW = pmap_rw_bit(pmap);
6050 PG_V = pmap_valid_bit(pmap);
6051 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6052 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6054 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6055 in_kernel = va >= VM_MAXUSER_ADDRESS;
6057 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
6058 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
6061 * Invalidate the 2MB page mapping and return "failure" if the
6062 * mapping was never accessed.
6064 if ((oldpde & PG_A) == 0) {
6065 KASSERT((oldpde & PG_W) == 0,
6066 ("pmap_demote_pde: a wired mapping is missing PG_A"));
6067 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6071 mpte = pmap_remove_pt_page(pmap, va);
6073 KASSERT((oldpde & PG_W) == 0,
6074 ("pmap_demote_pde: page table page for a wired mapping"
6078 * If the page table page is missing and the mapping
6079 * is for a kernel address, the mapping must belong to
6080 * the direct map. Page table pages are preallocated
6081 * for every other part of the kernel address space,
6082 * so the direct map region is the only part of the
6083 * kernel address space that must be handled here.
6085 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6086 va < DMAP_MAX_ADDRESS),
6087 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6090 * If the 2MB page mapping belongs to the direct map
6091 * region of the kernel's address space, then the page
6092 * allocation request specifies the highest possible
6093 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6094 * priority is normal.
6096 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6097 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6100 * If the allocation of the new page table page fails,
6101 * invalidate the 2MB page mapping and return "failure".
6104 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6109 mpte->ref_count = NPTEPG;
6111 mptepa = VM_PAGE_TO_PHYS(mpte);
6112 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6113 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6114 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6115 ("pmap_demote_pde: oldpde is missing PG_M"));
6116 newpte = oldpde & ~PG_PS;
6117 newpte = pmap_swap_pat(pmap, newpte);
6120 * If the PTP is not leftover from an earlier promotion or it does not
6121 * have PG_A set in every PTE, then fill it. The new PTEs will all
6124 if (!vm_page_all_valid(mpte))
6125 pmap_fill_ptp(firstpte, newpte);
6127 pmap_demote_pde_check(firstpte, newpte);
6130 * If the mapping has changed attributes, update the PTEs.
6132 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6133 pmap_fill_ptp(firstpte, newpte);
6136 * The spare PV entries must be reserved prior to demoting the
6137 * mapping, that is, prior to changing the PDE. Otherwise, the state
6138 * of the PDE and the PV lists will be inconsistent, which can result
6139 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6140 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6141 * PV entry for the 2MB page mapping that is being demoted.
6143 if ((oldpde & PG_MANAGED) != 0)
6144 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6147 * Demote the mapping. This pmap is locked. The old PDE has
6148 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6149 * set. Thus, there is no danger of a race with another
6150 * processor changing the setting of PG_A and/or PG_M between
6151 * the read above and the store below.
6153 if (workaround_erratum383)
6154 pmap_update_pde(pmap, va, pde, newpde);
6156 pde_store(pde, newpde);
6159 * Invalidate a stale recursive mapping of the page table page.
6162 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6165 * Demote the PV entry.
6167 if ((oldpde & PG_MANAGED) != 0)
6168 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6170 counter_u64_add(pmap_pde_demotions, 1);
6171 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6177 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6180 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6186 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6187 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6188 mpte = pmap_remove_pt_page(pmap, va);
6190 panic("pmap_remove_kernel_pde: Missing pt page.");
6192 mptepa = VM_PAGE_TO_PHYS(mpte);
6193 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6196 * If this page table page was unmapped by a promotion, then it
6197 * contains valid mappings. Zero it to invalidate those mappings.
6199 if (vm_page_any_valid(mpte))
6200 pagezero((void *)PHYS_TO_DMAP(mptepa));
6203 * Demote the mapping.
6205 if (workaround_erratum383)
6206 pmap_update_pde(pmap, va, pde, newpde);
6208 pde_store(pde, newpde);
6211 * Invalidate a stale recursive mapping of the page table page.
6213 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6217 * pmap_remove_pde: do the things to unmap a superpage in a process
6220 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6221 struct spglist *free, struct rwlock **lockp)
6223 struct md_page *pvh;
6225 vm_offset_t eva, va;
6227 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6229 PG_G = pmap_global_bit(pmap);
6230 PG_A = pmap_accessed_bit(pmap);
6231 PG_M = pmap_modified_bit(pmap);
6232 PG_RW = pmap_rw_bit(pmap);
6234 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6235 KASSERT((sva & PDRMASK) == 0,
6236 ("pmap_remove_pde: sva is not 2mpage aligned"));
6237 oldpde = pte_load_clear(pdq);
6239 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6240 if ((oldpde & PG_G) != 0)
6241 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6242 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6243 if (oldpde & PG_MANAGED) {
6244 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6245 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6246 pmap_pvh_free(pvh, pmap, sva);
6248 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6249 va < eva; va += PAGE_SIZE, m++) {
6250 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6253 vm_page_aflag_set(m, PGA_REFERENCED);
6254 if (TAILQ_EMPTY(&m->md.pv_list) &&
6255 TAILQ_EMPTY(&pvh->pv_list))
6256 vm_page_aflag_clear(m, PGA_WRITEABLE);
6257 pmap_delayed_invl_page(m);
6260 if (pmap == kernel_pmap) {
6261 pmap_remove_kernel_pde(pmap, pdq, sva);
6263 mpte = pmap_remove_pt_page(pmap, sva);
6265 KASSERT(vm_page_any_valid(mpte),
6266 ("pmap_remove_pde: pte page not promoted"));
6267 pmap_pt_page_count_adj(pmap, -1);
6268 KASSERT(mpte->ref_count == NPTEPG,
6269 ("pmap_remove_pde: pte page ref count error"));
6270 mpte->ref_count = 0;
6271 pmap_add_delayed_free_list(mpte, free, FALSE);
6274 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6278 * pmap_remove_pte: do the things to unmap a page in a process
6281 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6282 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6284 struct md_page *pvh;
6285 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6288 PG_A = pmap_accessed_bit(pmap);
6289 PG_M = pmap_modified_bit(pmap);
6290 PG_RW = pmap_rw_bit(pmap);
6292 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6293 oldpte = pte_load_clear(ptq);
6295 pmap->pm_stats.wired_count -= 1;
6296 pmap_resident_count_adj(pmap, -1);
6297 if (oldpte & PG_MANAGED) {
6298 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6299 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6302 vm_page_aflag_set(m, PGA_REFERENCED);
6303 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6304 pmap_pvh_free(&m->md, pmap, va);
6305 if (TAILQ_EMPTY(&m->md.pv_list) &&
6306 (m->flags & PG_FICTITIOUS) == 0) {
6307 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6308 if (TAILQ_EMPTY(&pvh->pv_list))
6309 vm_page_aflag_clear(m, PGA_WRITEABLE);
6311 pmap_delayed_invl_page(m);
6313 return (pmap_unuse_pt(pmap, va, ptepde, free));
6317 * Remove a single page from a process address space
6320 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6321 struct spglist *free)
6323 struct rwlock *lock;
6324 pt_entry_t *pte, PG_V;
6326 PG_V = pmap_valid_bit(pmap);
6327 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6328 if ((*pde & PG_V) == 0)
6330 pte = pmap_pde_to_pte(pde, va);
6331 if ((*pte & PG_V) == 0)
6334 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6337 pmap_invalidate_page(pmap, va);
6341 * Removes the specified range of addresses from the page table page.
6344 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6345 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6347 pt_entry_t PG_G, *pte;
6351 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6352 PG_G = pmap_global_bit(pmap);
6355 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6359 pmap_invalidate_range(pmap, va, sva);
6364 if ((*pte & PG_G) == 0)
6368 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6374 pmap_invalidate_range(pmap, va, sva);
6379 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6381 struct rwlock *lock;
6383 vm_offset_t va_next;
6384 pml5_entry_t *pml5e;
6385 pml4_entry_t *pml4e;
6387 pd_entry_t ptpaddr, *pde;
6388 pt_entry_t PG_G, PG_V;
6389 struct spglist free;
6392 PG_G = pmap_global_bit(pmap);
6393 PG_V = pmap_valid_bit(pmap);
6396 * If there are no resident pages besides the top level page
6397 * table page(s), there is nothing to do. Kernel pmap always
6398 * accounts whole preloaded area as resident, which makes its
6399 * resident count > 2.
6400 * Perform an unsynchronized read. This is, however, safe.
6402 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6409 pmap_delayed_invl_start();
6412 pmap_pkru_on_remove(pmap, sva, eva);
6415 * special handling of removing one page. a very
6416 * common operation and easy to short circuit some
6419 if (sva + PAGE_SIZE == eva) {
6420 pde = pmap_pde(pmap, sva);
6421 if (pde && (*pde & PG_PS) == 0) {
6422 pmap_remove_page(pmap, sva, pde, &free);
6428 for (; sva < eva; sva = va_next) {
6429 if (pmap->pm_stats.resident_count == 0)
6432 if (pmap_is_la57(pmap)) {
6433 pml5e = pmap_pml5e(pmap, sva);
6434 if ((*pml5e & PG_V) == 0) {
6435 va_next = (sva + NBPML5) & ~PML5MASK;
6440 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6442 pml4e = pmap_pml4e(pmap, sva);
6444 if ((*pml4e & PG_V) == 0) {
6445 va_next = (sva + NBPML4) & ~PML4MASK;
6451 va_next = (sva + NBPDP) & ~PDPMASK;
6454 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6455 if ((*pdpe & PG_V) == 0)
6457 if ((*pdpe & PG_PS) != 0) {
6458 KASSERT(va_next <= eva,
6459 ("partial update of non-transparent 1G mapping "
6460 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6461 *pdpe, sva, eva, va_next));
6462 MPASS(pmap != kernel_pmap); /* XXXKIB */
6463 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6466 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6467 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6468 pmap_unwire_ptp(pmap, sva, mt, &free);
6473 * Calculate index for next page table.
6475 va_next = (sva + NBPDR) & ~PDRMASK;
6479 pde = pmap_pdpe_to_pde(pdpe, sva);
6483 * Weed out invalid mappings.
6489 * Check for large page.
6491 if ((ptpaddr & PG_PS) != 0) {
6493 * Are we removing the entire large page? If not,
6494 * demote the mapping and fall through.
6496 if (sva + NBPDR == va_next && eva >= va_next) {
6498 * The TLB entry for a PG_G mapping is
6499 * invalidated by pmap_remove_pde().
6501 if ((ptpaddr & PG_G) == 0)
6503 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6505 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6507 /* The large page mapping was destroyed. */
6514 * Limit our scan to either the end of the va represented
6515 * by the current page table page, or to the end of the
6516 * range being removed.
6521 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6528 pmap_invalidate_all(pmap);
6530 pmap_delayed_invl_finish();
6531 vm_page_free_pages_toq(&free, true);
6535 * Remove the given range of addresses from the specified map.
6537 * It is assumed that the start and end are properly
6538 * rounded to the page size.
6541 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6543 pmap_remove1(pmap, sva, eva, false);
6547 * Remove the given range of addresses as part of a logical unmap
6548 * operation. This has the effect of calling pmap_remove(), but
6549 * also clears any metadata that should persist for the lifetime
6550 * of a logical mapping.
6553 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6555 pmap_remove1(pmap, sva, eva, true);
6559 * Routine: pmap_remove_all
6561 * Removes this physical page from
6562 * all physical maps in which it resides.
6563 * Reflects back modify bits to the pager.
6566 * Original versions of this routine were very
6567 * inefficient because they iteratively called
6568 * pmap_remove (slow...)
6572 pmap_remove_all(vm_page_t m)
6574 struct md_page *pvh;
6577 struct rwlock *lock;
6578 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6581 struct spglist free;
6582 int pvh_gen, md_gen;
6584 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6585 ("pmap_remove_all: page %p is not managed", m));
6587 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6588 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6589 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6592 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6594 if (!PMAP_TRYLOCK(pmap)) {
6595 pvh_gen = pvh->pv_gen;
6599 if (pvh_gen != pvh->pv_gen) {
6605 pde = pmap_pde(pmap, va);
6606 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6609 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6611 if (!PMAP_TRYLOCK(pmap)) {
6612 pvh_gen = pvh->pv_gen;
6613 md_gen = m->md.pv_gen;
6617 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6622 PG_A = pmap_accessed_bit(pmap);
6623 PG_M = pmap_modified_bit(pmap);
6624 PG_RW = pmap_rw_bit(pmap);
6625 pmap_resident_count_adj(pmap, -1);
6626 pde = pmap_pde(pmap, pv->pv_va);
6627 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6628 " a 2mpage in page %p's pv list", m));
6629 pte = pmap_pde_to_pte(pde, pv->pv_va);
6630 tpte = pte_load_clear(pte);
6632 pmap->pm_stats.wired_count--;
6634 vm_page_aflag_set(m, PGA_REFERENCED);
6637 * Update the vm_page_t clean and reference bits.
6639 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6641 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6642 pmap_invalidate_page(pmap, pv->pv_va);
6643 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6645 free_pv_entry(pmap, pv);
6648 vm_page_aflag_clear(m, PGA_WRITEABLE);
6650 pmap_delayed_invl_wait(m);
6651 vm_page_free_pages_toq(&free, true);
6655 * pmap_protect_pde: do the things to protect a 2mpage in a process
6658 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6660 pd_entry_t newpde, oldpde;
6662 boolean_t anychanged;
6663 pt_entry_t PG_G, PG_M, PG_RW;
6665 PG_G = pmap_global_bit(pmap);
6666 PG_M = pmap_modified_bit(pmap);
6667 PG_RW = pmap_rw_bit(pmap);
6669 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6670 KASSERT((sva & PDRMASK) == 0,
6671 ("pmap_protect_pde: sva is not 2mpage aligned"));
6674 oldpde = newpde = *pde;
6675 if ((prot & VM_PROT_WRITE) == 0) {
6676 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6677 (PG_MANAGED | PG_M | PG_RW)) {
6678 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6679 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6682 newpde &= ~(PG_RW | PG_M);
6684 if ((prot & VM_PROT_EXECUTE) == 0)
6686 if (newpde != oldpde) {
6688 * As an optimization to future operations on this PDE, clear
6689 * PG_PROMOTED. The impending invalidation will remove any
6690 * lingering 4KB page mappings from the TLB.
6692 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6694 if ((oldpde & PG_G) != 0)
6695 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6699 return (anychanged);
6703 * Set the physical protection on the
6704 * specified range of this map as requested.
6707 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6710 vm_offset_t va_next;
6711 pml4_entry_t *pml4e;
6713 pd_entry_t ptpaddr, *pde;
6714 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6715 pt_entry_t obits, pbits;
6716 boolean_t anychanged;
6718 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6719 if (prot == VM_PROT_NONE) {
6720 pmap_remove(pmap, sva, eva);
6724 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6725 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6728 PG_G = pmap_global_bit(pmap);
6729 PG_M = pmap_modified_bit(pmap);
6730 PG_V = pmap_valid_bit(pmap);
6731 PG_RW = pmap_rw_bit(pmap);
6735 * Although this function delays and batches the invalidation
6736 * of stale TLB entries, it does not need to call
6737 * pmap_delayed_invl_start() and
6738 * pmap_delayed_invl_finish(), because it does not
6739 * ordinarily destroy mappings. Stale TLB entries from
6740 * protection-only changes need only be invalidated before the
6741 * pmap lock is released, because protection-only changes do
6742 * not destroy PV entries. Even operations that iterate over
6743 * a physical page's PV list of mappings, like
6744 * pmap_remove_write(), acquire the pmap lock for each
6745 * mapping. Consequently, for protection-only changes, the
6746 * pmap lock suffices to synchronize both page table and TLB
6749 * This function only destroys a mapping if pmap_demote_pde()
6750 * fails. In that case, stale TLB entries are immediately
6755 for (; sva < eva; sva = va_next) {
6756 pml4e = pmap_pml4e(pmap, sva);
6757 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6758 va_next = (sva + NBPML4) & ~PML4MASK;
6764 va_next = (sva + NBPDP) & ~PDPMASK;
6767 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6768 if ((*pdpe & PG_V) == 0)
6770 if ((*pdpe & PG_PS) != 0) {
6771 KASSERT(va_next <= eva,
6772 ("partial update of non-transparent 1G mapping "
6773 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6774 *pdpe, sva, eva, va_next));
6776 obits = pbits = *pdpe;
6777 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6778 MPASS(pmap != kernel_pmap); /* XXXKIB */
6779 if ((prot & VM_PROT_WRITE) == 0)
6780 pbits &= ~(PG_RW | PG_M);
6781 if ((prot & VM_PROT_EXECUTE) == 0)
6784 if (pbits != obits) {
6785 if (!atomic_cmpset_long(pdpe, obits, pbits))
6786 /* PG_PS cannot be cleared under us, */
6793 va_next = (sva + NBPDR) & ~PDRMASK;
6797 pde = pmap_pdpe_to_pde(pdpe, sva);
6801 * Weed out invalid mappings.
6807 * Check for large page.
6809 if ((ptpaddr & PG_PS) != 0) {
6811 * Are we protecting the entire large page? If not,
6812 * demote the mapping and fall through.
6814 if (sva + NBPDR == va_next && eva >= va_next) {
6816 * The TLB entry for a PG_G mapping is
6817 * invalidated by pmap_protect_pde().
6819 if (pmap_protect_pde(pmap, pde, sva, prot))
6822 } else if (!pmap_demote_pde(pmap, pde, sva)) {
6824 * The large page mapping was destroyed.
6833 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6836 obits = pbits = *pte;
6837 if ((pbits & PG_V) == 0)
6840 if ((prot & VM_PROT_WRITE) == 0) {
6841 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6842 (PG_MANAGED | PG_M | PG_RW)) {
6843 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6846 pbits &= ~(PG_RW | PG_M);
6848 if ((prot & VM_PROT_EXECUTE) == 0)
6851 if (pbits != obits) {
6852 if (!atomic_cmpset_long(pte, obits, pbits))
6855 pmap_invalidate_page(pmap, sva);
6862 pmap_invalidate_all(pmap);
6867 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6870 if (pmap->pm_type != PT_EPT)
6872 return ((pde & EPT_PG_EXECUTE) != 0);
6875 #if VM_NRESERVLEVEL > 0
6877 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6878 * single page table page (PTP) to a single 2MB page mapping. For promotion
6879 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6880 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6881 * identical characteristics.
6884 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6885 struct rwlock **lockp)
6888 pt_entry_t *firstpte, oldpte, pa, *pte;
6889 pt_entry_t allpte_PG_A, PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6892 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6893 if (!pmap_ps_enabled(pmap))
6896 PG_A = pmap_accessed_bit(pmap);
6897 PG_G = pmap_global_bit(pmap);
6898 PG_M = pmap_modified_bit(pmap);
6899 PG_V = pmap_valid_bit(pmap);
6900 PG_RW = pmap_rw_bit(pmap);
6901 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6902 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6905 * Examine the first PTE in the specified PTP. Abort if this PTE is
6906 * ineligible for promotion due to hardware errata, invalid, or does
6907 * not map the first 4KB physical page within a 2MB page.
6909 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6911 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6913 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6914 counter_u64_add(pmap_pde_p_failures, 1);
6915 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6916 " in pmap %p", va, pmap);
6921 * Both here and in the below "for" loop, to allow for repromotion
6922 * after MADV_FREE, conditionally write protect a clean PTE before
6923 * possibly aborting the promotion due to other PTE attributes. Why?
6924 * Suppose that MADV_FREE is applied to a part of a superpage, the
6925 * address range [S, E). pmap_advise() will demote the superpage
6926 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6927 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6928 * imagine that the memory in [S, E) is recycled, but the last 4KB
6929 * page in [S, E) is not the last to be rewritten, or simply accessed.
6930 * In other words, there is still a 4KB page in [S, E), call it P,
6931 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6932 * we write protect P before aborting the promotion, if and when P is
6933 * finally rewritten, there won't be a page fault to trigger
6937 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6939 * When PG_M is already clear, PG_RW can be cleared without
6940 * a TLB invalidation.
6942 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6945 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6946 " in pmap %p", va & ~PDRMASK, pmap);
6950 * Examine each of the other PTEs in the specified PTP. Abort if this
6951 * PTE maps an unexpected 4KB physical page or does not have identical
6952 * characteristics to the first PTE.
6954 allpte_PG_A = newpde & PG_A;
6955 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6956 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6958 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6959 counter_u64_add(pmap_pde_p_failures, 1);
6960 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6961 " in pmap %p", va, pmap);
6965 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6967 * When PG_M is already clear, PG_RW can be cleared
6968 * without a TLB invalidation.
6970 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6973 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6974 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6975 (va & ~PDRMASK), pmap);
6977 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6978 counter_u64_add(pmap_pde_p_failures, 1);
6979 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6980 " in pmap %p", va, pmap);
6983 allpte_PG_A &= oldpte;
6988 * Unless all PTEs have PG_A set, clear it from the superpage mapping,
6989 * so that promotions triggered by speculative mappings, such as
6990 * pmap_enter_quick(), don't automatically mark the underlying pages
6993 newpde &= ~PG_A | allpte_PG_A;
6996 * EPT PTEs with PG_M set and PG_A clear are not supported by early
6997 * MMUs supporting EPT.
6999 KASSERT((newpde & PG_A) != 0 || safe_to_clear_referenced(pmap, newpde),
7000 ("unsupported EPT PTE"));
7003 * Save the PTP in its current state until the PDE mapping the
7004 * superpage is demoted by pmap_demote_pde() or destroyed by
7005 * pmap_remove_pde(). If PG_A is not set in every PTE, then request
7006 * that the PTP be refilled on demotion.
7009 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7010 KASSERT(mpte >= vm_page_array &&
7011 mpte < &vm_page_array[vm_page_array_size],
7012 ("pmap_promote_pde: page table page is out of range"));
7013 KASSERT(mpte->pindex == pmap_pde_pindex(va),
7014 ("pmap_promote_pde: page table page's pindex is wrong "
7015 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
7016 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
7017 if (pmap_insert_pt_page(pmap, mpte, true, allpte_PG_A != 0)) {
7018 counter_u64_add(pmap_pde_p_failures, 1);
7020 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
7026 * Promote the pv entries.
7028 if ((newpde & PG_MANAGED) != 0)
7029 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
7032 * Propagate the PAT index to its proper position.
7034 newpde = pmap_swap_pat(pmap, newpde);
7037 * Map the superpage.
7039 if (workaround_erratum383)
7040 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
7042 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
7044 counter_u64_add(pmap_pde_promotions, 1);
7045 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
7046 " in pmap %p", va, pmap);
7049 #endif /* VM_NRESERVLEVEL > 0 */
7052 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
7056 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
7058 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7059 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
7060 ("psind %d unexpected", psind));
7061 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
7062 ("unaligned phys address %#lx newpte %#lx psind %d",
7063 newpte & PG_FRAME, newpte, psind));
7064 KASSERT((va & (pagesizes[psind] - 1)) == 0,
7065 ("unaligned va %#lx psind %d", va, psind));
7066 KASSERT(va < VM_MAXUSER_ADDRESS,
7067 ("kernel mode non-transparent superpage")); /* XXXKIB */
7068 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
7069 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
7071 PG_V = pmap_valid_bit(pmap);
7074 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind]))
7075 return (KERN_PROTECTION_FAILURE);
7077 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7078 pten |= pmap_pkru_get(pmap, va);
7080 if (psind == 2) { /* 1G */
7081 pml4e = pmap_pml4e(pmap, va);
7082 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7083 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7087 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7088 pdpe = &pdpe[pmap_pdpe_index(va)];
7090 MPASS(origpte == 0);
7092 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7093 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7095 if ((origpte & PG_V) == 0) {
7096 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7101 } else /* (psind == 1) */ { /* 2M */
7102 pde = pmap_pde(pmap, va);
7104 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7108 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7109 pde = &pde[pmap_pde_index(va)];
7111 MPASS(origpte == 0);
7114 if ((origpte & PG_V) == 0) {
7115 pdpe = pmap_pdpe(pmap, va);
7116 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7117 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7123 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7124 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7125 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7126 va, psind == 2 ? "1G" : "2M", origpte, pten));
7127 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7128 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7129 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7130 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7131 if ((origpte & PG_V) == 0)
7132 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7134 return (KERN_SUCCESS);
7137 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7138 return (KERN_RESOURCE_SHORTAGE);
7146 * Insert the given physical page (p) at
7147 * the specified virtual address (v) in the
7148 * target physical map with the protection requested.
7150 * If specified, the page will be wired down, meaning
7151 * that the related pte can not be reclaimed.
7153 * NB: This is the only routine which MAY NOT lazy-evaluate
7154 * or lose information. That is, this routine must actually
7155 * insert this page into the given map NOW.
7157 * When destroying both a page table and PV entry, this function
7158 * performs the TLB invalidation before releasing the PV list
7159 * lock, so we do not need pmap_delayed_invl_page() calls here.
7162 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7163 u_int flags, int8_t psind)
7165 struct rwlock *lock;
7167 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7168 pt_entry_t newpte, origpte;
7175 PG_A = pmap_accessed_bit(pmap);
7176 PG_G = pmap_global_bit(pmap);
7177 PG_M = pmap_modified_bit(pmap);
7178 PG_V = pmap_valid_bit(pmap);
7179 PG_RW = pmap_rw_bit(pmap);
7181 va = trunc_page(va);
7182 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7183 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7184 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7186 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7187 ("pmap_enter: managed mapping within the clean submap"));
7188 if ((m->oflags & VPO_UNMANAGED) == 0)
7189 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7190 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7191 ("pmap_enter: flags %u has reserved bits set", flags));
7192 pa = VM_PAGE_TO_PHYS(m);
7193 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7194 if ((flags & VM_PROT_WRITE) != 0)
7196 if ((prot & VM_PROT_WRITE) != 0)
7198 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7199 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7200 if ((prot & VM_PROT_EXECUTE) == 0)
7202 if ((flags & PMAP_ENTER_WIRED) != 0)
7204 if (va < VM_MAXUSER_ADDRESS)
7206 if (pmap == kernel_pmap)
7208 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7211 * Set modified bit gratuitously for writeable mappings if
7212 * the page is unmanaged. We do not want to take a fault
7213 * to do the dirty bit accounting for these mappings.
7215 if ((m->oflags & VPO_UNMANAGED) != 0) {
7216 if ((newpte & PG_RW) != 0)
7219 newpte |= PG_MANAGED;
7223 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7224 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7225 ("managed largepage va %#lx flags %#x", va, flags));
7226 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7231 /* Assert the required virtual and physical alignment. */
7232 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7233 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7234 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7240 * In the case that a page table page is not
7241 * resident, we are creating it here.
7244 pde = pmap_pde(pmap, va);
7245 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7246 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7247 pte = pmap_pde_to_pte(pde, va);
7248 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7249 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7252 } else if (va < VM_MAXUSER_ADDRESS) {
7254 * Here if the pte page isn't mapped, or if it has been
7257 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7258 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7259 nosleep ? NULL : &lock, va);
7260 if (mpte == NULL && nosleep) {
7261 rv = KERN_RESOURCE_SHORTAGE;
7266 panic("pmap_enter: invalid page directory va=%#lx", va);
7270 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7271 newpte |= pmap_pkru_get(pmap, va);
7274 * Is the specified virtual address already mapped?
7276 if ((origpte & PG_V) != 0) {
7278 * Wiring change, just update stats. We don't worry about
7279 * wiring PT pages as they remain resident as long as there
7280 * are valid mappings in them. Hence, if a user page is wired,
7281 * the PT page will be also.
7283 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7284 pmap->pm_stats.wired_count++;
7285 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7286 pmap->pm_stats.wired_count--;
7289 * Remove the extra PT page reference.
7293 KASSERT(mpte->ref_count > 0,
7294 ("pmap_enter: missing reference to page table page,"
7299 * Has the physical page changed?
7301 opa = origpte & PG_FRAME;
7304 * No, might be a protection or wiring change.
7306 if ((origpte & PG_MANAGED) != 0 &&
7307 (newpte & PG_RW) != 0)
7308 vm_page_aflag_set(m, PGA_WRITEABLE);
7309 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7315 * The physical page has changed. Temporarily invalidate
7316 * the mapping. This ensures that all threads sharing the
7317 * pmap keep a consistent view of the mapping, which is
7318 * necessary for the correct handling of COW faults. It
7319 * also permits reuse of the old mapping's PV entry,
7320 * avoiding an allocation.
7322 * For consistency, handle unmanaged mappings the same way.
7324 origpte = pte_load_clear(pte);
7325 KASSERT((origpte & PG_FRAME) == opa,
7326 ("pmap_enter: unexpected pa update for %#lx", va));
7327 if ((origpte & PG_MANAGED) != 0) {
7328 om = PHYS_TO_VM_PAGE(opa);
7331 * The pmap lock is sufficient to synchronize with
7332 * concurrent calls to pmap_page_test_mappings() and
7333 * pmap_ts_referenced().
7335 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7337 if ((origpte & PG_A) != 0) {
7338 pmap_invalidate_page(pmap, va);
7339 vm_page_aflag_set(om, PGA_REFERENCED);
7341 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7342 pv = pmap_pvh_remove(&om->md, pmap, va);
7344 ("pmap_enter: no PV entry for %#lx", va));
7345 if ((newpte & PG_MANAGED) == 0)
7346 free_pv_entry(pmap, pv);
7347 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7348 TAILQ_EMPTY(&om->md.pv_list) &&
7349 ((om->flags & PG_FICTITIOUS) != 0 ||
7350 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7351 vm_page_aflag_clear(om, PGA_WRITEABLE);
7354 * Since this mapping is unmanaged, assume that PG_A
7357 pmap_invalidate_page(pmap, va);
7362 * Increment the counters.
7364 if ((newpte & PG_W) != 0)
7365 pmap->pm_stats.wired_count++;
7366 pmap_resident_count_adj(pmap, 1);
7370 * Enter on the PV list if part of our managed memory.
7372 if ((newpte & PG_MANAGED) != 0) {
7374 pv = get_pv_entry(pmap, &lock);
7377 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7378 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7380 if ((newpte & PG_RW) != 0)
7381 vm_page_aflag_set(m, PGA_WRITEABLE);
7387 if ((origpte & PG_V) != 0) {
7389 origpte = pte_load_store(pte, newpte);
7390 KASSERT((origpte & PG_FRAME) == pa,
7391 ("pmap_enter: unexpected pa update for %#lx", va));
7392 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7394 if ((origpte & PG_MANAGED) != 0)
7398 * Although the PTE may still have PG_RW set, TLB
7399 * invalidation may nonetheless be required because
7400 * the PTE no longer has PG_M set.
7402 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7404 * This PTE change does not require TLB invalidation.
7408 if ((origpte & PG_A) != 0)
7409 pmap_invalidate_page(pmap, va);
7411 pte_store(pte, newpte);
7415 #if VM_NRESERVLEVEL > 0
7417 * If both the page table page and the reservation are fully
7418 * populated, then attempt promotion.
7420 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7421 (m->flags & PG_FICTITIOUS) == 0 &&
7422 vm_reserv_level_iffullpop(m) == 0)
7423 (void)pmap_promote_pde(pmap, pde, va, mpte, &lock);
7435 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7436 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7437 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7438 * "no replace", and "no reclaim" are specified.
7441 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7442 struct rwlock **lockp)
7447 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7448 PG_V = pmap_valid_bit(pmap);
7449 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
7451 if ((m->oflags & VPO_UNMANAGED) == 0)
7452 newpde |= PG_MANAGED;
7453 if ((prot & VM_PROT_EXECUTE) == 0)
7455 if (va < VM_MAXUSER_ADDRESS)
7457 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7458 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7462 * Returns true if every page table entry in the specified page table page is
7466 pmap_every_pte_zero(vm_paddr_t pa)
7468 pt_entry_t *pt_end, *pte;
7470 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7471 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7472 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7480 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7481 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7482 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7483 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7484 * page mapping already exists within the 2MB virtual address range starting
7485 * at the specified virtual address or (2) the requested 2MB page mapping is
7486 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7487 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7488 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7489 * settings are not the same across the 2MB virtual address range starting at
7490 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7491 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7492 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7495 * The parameter "m" is only used when creating a managed, writeable mapping.
7498 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7499 vm_page_t m, struct rwlock **lockp)
7501 struct spglist free;
7502 pd_entry_t oldpde, *pde;
7503 pt_entry_t PG_G, PG_RW, PG_V;
7507 PG_G = pmap_global_bit(pmap);
7508 PG_RW = pmap_rw_bit(pmap);
7509 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7510 ("pmap_enter_pde: newpde is missing PG_M"));
7511 PG_V = pmap_valid_bit(pmap);
7512 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7514 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7516 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7517 " in pmap %p", va, pmap);
7518 return (KERN_FAILURE);
7520 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7521 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7522 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7523 " in pmap %p", va, pmap);
7524 return (KERN_RESOURCE_SHORTAGE);
7528 * If pkru is not same for the whole pde range, return failure
7529 * and let vm_fault() cope. Check after pde allocation, since
7532 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
7533 pmap_abort_ptp(pmap, va, pdpg);
7534 return (KERN_PROTECTION_FAILURE);
7536 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
7537 newpde &= ~X86_PG_PKU_MASK;
7538 newpde |= pmap_pkru_get(pmap, va);
7542 * If there are existing mappings, either abort or remove them.
7545 if ((oldpde & PG_V) != 0) {
7546 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7547 ("pmap_enter_pde: pdpg's reference count is too low"));
7548 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7549 if ((oldpde & PG_PS) != 0) {
7553 "pmap_enter_pde: no space for va %#lx"
7554 " in pmap %p", va, pmap);
7555 return (KERN_NO_SPACE);
7556 } else if (va < VM_MAXUSER_ADDRESS ||
7557 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7561 "pmap_enter_pde: failure for va %#lx"
7562 " in pmap %p", va, pmap);
7563 return (KERN_FAILURE);
7566 /* Break the existing mapping(s). */
7568 if ((oldpde & PG_PS) != 0) {
7570 * The reference to the PD page that was acquired by
7571 * pmap_alloc_pde() ensures that it won't be freed.
7572 * However, if the PDE resulted from a promotion, then
7573 * a reserved PT page could be freed.
7575 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7576 if ((oldpde & PG_G) == 0)
7577 pmap_invalidate_pde_page(pmap, va, oldpde);
7579 pmap_delayed_invl_start();
7580 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7582 pmap_invalidate_all(pmap);
7583 pmap_delayed_invl_finish();
7585 if (va < VM_MAXUSER_ADDRESS) {
7586 vm_page_free_pages_toq(&free, true);
7587 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7590 KASSERT(SLIST_EMPTY(&free),
7591 ("pmap_enter_pde: freed kernel page table page"));
7594 * Both pmap_remove_pde() and pmap_remove_ptes() will
7595 * leave the kernel page table page zero filled.
7597 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7598 if (pmap_insert_pt_page(pmap, mt, false, false))
7599 panic("pmap_enter_pde: trie insert failed");
7604 * Allocate leaf ptpage for wired userspace pages.
7607 if ((newpde & PG_W) != 0 && pmap != kernel_pmap) {
7608 uwptpg = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
7611 return (KERN_RESOURCE_SHORTAGE);
7612 if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
7613 pmap_free_pt_page(pmap, uwptpg, false);
7614 return (KERN_RESOURCE_SHORTAGE);
7617 uwptpg->ref_count = NPTEPG;
7619 if ((newpde & PG_MANAGED) != 0) {
7621 * Abort this mapping if its PV entry could not be created.
7623 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7625 pmap_abort_ptp(pmap, va, pdpg);
7626 if (uwptpg != NULL) {
7627 mt = pmap_remove_pt_page(pmap, va);
7628 KASSERT(mt == uwptpg,
7629 ("removed pt page %p, expected %p", mt,
7631 uwptpg->ref_count = 1;
7632 pmap_free_pt_page(pmap, uwptpg, false);
7634 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7635 " in pmap %p", va, pmap);
7636 return (KERN_RESOURCE_SHORTAGE);
7638 if ((newpde & PG_RW) != 0) {
7639 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7640 vm_page_aflag_set(mt, PGA_WRITEABLE);
7645 * Increment counters.
7647 if ((newpde & PG_W) != 0)
7648 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7649 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7652 * Map the superpage. (This is not a promoted mapping; there will not
7653 * be any lingering 4KB page mappings in the TLB.)
7655 pde_store(pde, newpde);
7657 counter_u64_add(pmap_pde_mappings, 1);
7658 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7660 return (KERN_SUCCESS);
7664 * Maps a sequence of resident pages belonging to the same object.
7665 * The sequence begins with the given page m_start. This page is
7666 * mapped at the given virtual address start. Each subsequent page is
7667 * mapped at a virtual address that is offset from start by the same
7668 * amount as the page is offset from m_start within the object. The
7669 * last page in the sequence is the page with the largest offset from
7670 * m_start that can be mapped at a virtual address less than the given
7671 * virtual address end. Not every virtual page between start and end
7672 * is mapped; only those for which a resident page exists with the
7673 * corresponding offset from m_start are mapped.
7676 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7677 vm_page_t m_start, vm_prot_t prot)
7679 struct rwlock *lock;
7682 vm_pindex_t diff, psize;
7685 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7687 psize = atop(end - start);
7692 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7693 va = start + ptoa(diff);
7694 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7695 m->psind == 1 && pmap_ps_enabled(pmap) &&
7696 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7697 KERN_SUCCESS || rv == KERN_NO_SPACE))
7698 m = &m[NBPDR / PAGE_SIZE - 1];
7700 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7702 m = TAILQ_NEXT(m, listq);
7710 * this code makes some *MAJOR* assumptions:
7711 * 1. Current pmap & pmap exists.
7714 * 4. No page table pages.
7715 * but is *MUCH* faster than pmap_enter...
7719 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7721 struct rwlock *lock;
7725 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7732 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7733 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7736 pt_entry_t newpte, *pte, PG_V;
7738 KASSERT(!VA_IS_CLEANMAP(va) ||
7739 (m->oflags & VPO_UNMANAGED) != 0,
7740 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7741 PG_V = pmap_valid_bit(pmap);
7742 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7746 * In the case that a page table page is not
7747 * resident, we are creating it here.
7749 if (va < VM_MAXUSER_ADDRESS) {
7751 vm_pindex_t ptepindex;
7754 * Calculate pagetable page index
7756 ptepindex = pmap_pde_pindex(va);
7757 if (mpte && (mpte->pindex == ptepindex)) {
7761 * If the page table page is mapped, we just increment
7762 * the hold count, and activate it. Otherwise, we
7763 * attempt to allocate a page table page, passing NULL
7764 * instead of the PV list lock pointer because we don't
7765 * intend to sleep. If this attempt fails, we don't
7766 * retry. Instead, we give up.
7768 pdpe = pmap_pdpe(pmap, va);
7769 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7770 if ((*pdpe & PG_PS) != 0)
7772 pde = pmap_pdpe_to_pde(pdpe, va);
7773 if ((*pde & PG_V) != 0) {
7774 if ((*pde & PG_PS) != 0)
7776 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7779 mpte = pmap_allocpte_alloc(pmap,
7780 ptepindex, NULL, va);
7785 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7791 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7792 pte = &pte[pmap_pte_index(va)];
7804 * Enter on the PV list if part of our managed memory.
7806 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7807 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7809 pmap_abort_ptp(pmap, va, mpte);
7814 * Increment counters
7816 pmap_resident_count_adj(pmap, 1);
7818 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7819 pmap_cache_bits(pmap, m->md.pat_mode, 0);
7820 if ((m->oflags & VPO_UNMANAGED) == 0)
7821 newpte |= PG_MANAGED;
7822 if ((prot & VM_PROT_EXECUTE) == 0)
7824 if (va < VM_MAXUSER_ADDRESS)
7825 newpte |= PG_U | pmap_pkru_get(pmap, va);
7826 pte_store(pte, newpte);
7828 #if VM_NRESERVLEVEL > 0
7830 * If both the PTP and the reservation are fully populated, then
7831 * attempt promotion.
7833 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7834 (m->flags & PG_FICTITIOUS) == 0 &&
7835 vm_reserv_level_iffullpop(m) == 0) {
7837 pde = pmap_pde(pmap, va);
7840 * If promotion succeeds, then the next call to this function
7841 * should not be given the unmapped PTP as a hint.
7843 if (pmap_promote_pde(pmap, pde, va, mpte, lockp))
7852 * Make a temporary mapping for a physical address. This is only intended
7853 * to be used for panic dumps.
7856 pmap_kenter_temporary(vm_paddr_t pa, int i)
7860 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7861 pmap_kenter(va, pa);
7862 pmap_invlpg(kernel_pmap, va);
7863 return ((void *)crashdumpmap);
7867 * This code maps large physical mmap regions into the
7868 * processor address space. Note that some shortcuts
7869 * are taken, but the code works.
7872 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7873 vm_pindex_t pindex, vm_size_t size)
7876 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7877 vm_paddr_t pa, ptepa;
7881 PG_A = pmap_accessed_bit(pmap);
7882 PG_M = pmap_modified_bit(pmap);
7883 PG_V = pmap_valid_bit(pmap);
7884 PG_RW = pmap_rw_bit(pmap);
7886 VM_OBJECT_ASSERT_WLOCKED(object);
7887 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7888 ("pmap_object_init_pt: non-device object"));
7889 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7890 if (!pmap_ps_enabled(pmap))
7892 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7894 p = vm_page_lookup(object, pindex);
7895 KASSERT(vm_page_all_valid(p),
7896 ("pmap_object_init_pt: invalid page %p", p));
7897 pat_mode = p->md.pat_mode;
7900 * Abort the mapping if the first page is not physically
7901 * aligned to a 2MB page boundary.
7903 ptepa = VM_PAGE_TO_PHYS(p);
7904 if (ptepa & (NBPDR - 1))
7908 * Skip the first page. Abort the mapping if the rest of
7909 * the pages are not physically contiguous or have differing
7910 * memory attributes.
7912 p = TAILQ_NEXT(p, listq);
7913 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7915 KASSERT(vm_page_all_valid(p),
7916 ("pmap_object_init_pt: invalid page %p", p));
7917 if (pa != VM_PAGE_TO_PHYS(p) ||
7918 pat_mode != p->md.pat_mode)
7920 p = TAILQ_NEXT(p, listq);
7924 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7925 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7926 * will not affect the termination of this loop.
7929 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
7930 pa < ptepa + size; pa += NBPDR) {
7931 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7934 * The creation of mappings below is only an
7935 * optimization. If a page directory page
7936 * cannot be allocated without blocking,
7937 * continue on to the next mapping rather than
7943 if ((*pde & PG_V) == 0) {
7944 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7945 PG_U | PG_RW | PG_V);
7946 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7947 counter_u64_add(pmap_pde_mappings, 1);
7949 /* Continue on if the PDE is already valid. */
7951 KASSERT(pdpg->ref_count > 0,
7952 ("pmap_object_init_pt: missing reference "
7953 "to page directory page, va: 0x%lx", addr));
7962 * Clear the wired attribute from the mappings for the specified range of
7963 * addresses in the given pmap. Every valid mapping within that range
7964 * must have the wired attribute set. In contrast, invalid mappings
7965 * cannot have the wired attribute set, so they are ignored.
7967 * The wired attribute of the page table entry is not a hardware
7968 * feature, so there is no need to invalidate any TLB entries.
7969 * Since pmap_demote_pde() for the wired entry must never fail,
7970 * pmap_delayed_invl_start()/finish() calls around the
7971 * function are not needed.
7974 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7976 vm_offset_t va_next;
7977 pml4_entry_t *pml4e;
7980 pt_entry_t *pte, PG_V, PG_G __diagused;
7982 PG_V = pmap_valid_bit(pmap);
7983 PG_G = pmap_global_bit(pmap);
7985 for (; sva < eva; sva = va_next) {
7986 pml4e = pmap_pml4e(pmap, sva);
7987 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7988 va_next = (sva + NBPML4) & ~PML4MASK;
7994 va_next = (sva + NBPDP) & ~PDPMASK;
7997 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7998 if ((*pdpe & PG_V) == 0)
8000 if ((*pdpe & PG_PS) != 0) {
8001 KASSERT(va_next <= eva,
8002 ("partial update of non-transparent 1G mapping "
8003 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8004 *pdpe, sva, eva, va_next));
8005 MPASS(pmap != kernel_pmap); /* XXXKIB */
8006 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
8007 atomic_clear_long(pdpe, PG_W);
8008 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
8012 va_next = (sva + NBPDR) & ~PDRMASK;
8015 pde = pmap_pdpe_to_pde(pdpe, sva);
8016 if ((*pde & PG_V) == 0)
8018 if ((*pde & PG_PS) != 0) {
8019 if ((*pde & PG_W) == 0)
8020 panic("pmap_unwire: pde %#jx is missing PG_W",
8024 * Are we unwiring the entire large page? If not,
8025 * demote the mapping and fall through.
8027 if (sva + NBPDR == va_next && eva >= va_next) {
8028 atomic_clear_long(pde, PG_W);
8029 pmap->pm_stats.wired_count -= NBPDR /
8032 } else if (!pmap_demote_pde(pmap, pde, sva))
8033 panic("pmap_unwire: demotion failed");
8037 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
8039 if ((*pte & PG_V) == 0)
8041 if ((*pte & PG_W) == 0)
8042 panic("pmap_unwire: pte %#jx is missing PG_W",
8046 * PG_W must be cleared atomically. Although the pmap
8047 * lock synchronizes access to PG_W, another processor
8048 * could be setting PG_M and/or PG_A concurrently.
8050 atomic_clear_long(pte, PG_W);
8051 pmap->pm_stats.wired_count--;
8058 * Copy the range specified by src_addr/len
8059 * from the source map to the range dst_addr/len
8060 * in the destination map.
8062 * This routine is only advisory and need not do anything.
8065 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
8066 vm_offset_t src_addr)
8068 struct rwlock *lock;
8069 pml4_entry_t *pml4e;
8071 pd_entry_t *pde, srcptepaddr;
8072 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
8073 vm_offset_t addr, end_addr, va_next;
8074 vm_page_t dst_pdpg, dstmpte, srcmpte;
8076 if (dst_addr != src_addr)
8079 if (dst_pmap->pm_type != src_pmap->pm_type)
8083 * EPT page table entries that require emulation of A/D bits are
8084 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
8085 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
8086 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
8087 * implementations flag an EPT misconfiguration for exec-only
8088 * mappings we skip this function entirely for emulated pmaps.
8090 if (pmap_emulate_ad_bits(dst_pmap))
8093 end_addr = src_addr + len;
8095 if (dst_pmap < src_pmap) {
8096 PMAP_LOCK(dst_pmap);
8097 PMAP_LOCK(src_pmap);
8099 PMAP_LOCK(src_pmap);
8100 PMAP_LOCK(dst_pmap);
8103 PG_A = pmap_accessed_bit(dst_pmap);
8104 PG_M = pmap_modified_bit(dst_pmap);
8105 PG_V = pmap_valid_bit(dst_pmap);
8107 for (addr = src_addr; addr < end_addr; addr = va_next) {
8108 KASSERT(addr < UPT_MIN_ADDRESS,
8109 ("pmap_copy: invalid to pmap_copy page tables"));
8111 pml4e = pmap_pml4e(src_pmap, addr);
8112 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8113 va_next = (addr + NBPML4) & ~PML4MASK;
8119 va_next = (addr + NBPDP) & ~PDPMASK;
8122 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
8123 if ((*pdpe & PG_V) == 0)
8125 if ((*pdpe & PG_PS) != 0) {
8126 KASSERT(va_next <= end_addr,
8127 ("partial update of non-transparent 1G mapping "
8128 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8129 *pdpe, addr, end_addr, va_next));
8130 MPASS((addr & PDPMASK) == 0);
8131 MPASS((*pdpe & PG_MANAGED) == 0);
8132 srcptepaddr = *pdpe;
8133 pdpe = pmap_pdpe(dst_pmap, addr);
8135 if (pmap_allocpte_alloc(dst_pmap,
8136 pmap_pml4e_pindex(addr), NULL, addr) ==
8139 pdpe = pmap_pdpe(dst_pmap, addr);
8141 pml4e = pmap_pml4e(dst_pmap, addr);
8142 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8143 dst_pdpg->ref_count++;
8146 ("1G mapping present in dst pmap "
8147 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8148 *pdpe, addr, end_addr, va_next));
8149 *pdpe = srcptepaddr & ~PG_W;
8150 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8154 va_next = (addr + NBPDR) & ~PDRMASK;
8158 pde = pmap_pdpe_to_pde(pdpe, addr);
8160 if (srcptepaddr == 0)
8163 if (srcptepaddr & PG_PS) {
8165 * We can only virtual copy whole superpages.
8167 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8169 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8172 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8173 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8174 PMAP_ENTER_NORECLAIM, &lock))) {
8176 * We leave the dirty bit unchanged because
8177 * managed read/write superpage mappings are
8178 * required to be dirty. However, managed
8179 * superpage mappings are not required to
8180 * have their accessed bit set, so we clear
8181 * it because we don't know if this mapping
8184 srcptepaddr &= ~PG_W;
8185 if ((srcptepaddr & PG_MANAGED) != 0)
8186 srcptepaddr &= ~PG_A;
8188 pmap_resident_count_adj(dst_pmap, NBPDR /
8190 counter_u64_add(pmap_pde_mappings, 1);
8192 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8196 srcptepaddr &= PG_FRAME;
8197 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8198 KASSERT(srcmpte->ref_count > 0,
8199 ("pmap_copy: source page table page is unused"));
8201 if (va_next > end_addr)
8204 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8205 src_pte = &src_pte[pmap_pte_index(addr)];
8207 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8211 * We only virtual copy managed pages.
8213 if ((ptetemp & PG_MANAGED) == 0)
8216 if (dstmpte != NULL) {
8217 KASSERT(dstmpte->pindex ==
8218 pmap_pde_pindex(addr),
8219 ("dstmpte pindex/addr mismatch"));
8220 dstmpte->ref_count++;
8221 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8224 dst_pte = (pt_entry_t *)
8225 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8226 dst_pte = &dst_pte[pmap_pte_index(addr)];
8227 if (*dst_pte == 0 &&
8228 pmap_try_insert_pv_entry(dst_pmap, addr,
8229 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8231 * Clear the wired, modified, and accessed
8232 * (referenced) bits during the copy.
8234 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8235 pmap_resident_count_adj(dst_pmap, 1);
8237 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8240 /* Have we copied all of the valid mappings? */
8241 if (dstmpte->ref_count >= srcmpte->ref_count)
8248 PMAP_UNLOCK(src_pmap);
8249 PMAP_UNLOCK(dst_pmap);
8253 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8257 if (dst_pmap->pm_type != src_pmap->pm_type ||
8258 dst_pmap->pm_type != PT_X86 ||
8259 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8262 if (dst_pmap < src_pmap) {
8263 PMAP_LOCK(dst_pmap);
8264 PMAP_LOCK(src_pmap);
8266 PMAP_LOCK(src_pmap);
8267 PMAP_LOCK(dst_pmap);
8269 error = pmap_pkru_copy(dst_pmap, src_pmap);
8270 /* Clean up partial copy on failure due to no memory. */
8271 if (error == ENOMEM)
8272 pmap_pkru_deassign_all(dst_pmap);
8273 PMAP_UNLOCK(src_pmap);
8274 PMAP_UNLOCK(dst_pmap);
8275 if (error != ENOMEM)
8283 * Zero the specified hardware page.
8286 pmap_zero_page(vm_page_t m)
8290 #ifdef TSLOG_PAGEZERO
8293 va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8294 pagezero((void *)va);
8295 #ifdef TSLOG_PAGEZERO
8301 * Zero an area within a single hardware page. off and size must not
8302 * cover an area beyond a single hardware page.
8305 pmap_zero_page_area(vm_page_t m, int off, int size)
8307 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8309 if (off == 0 && size == PAGE_SIZE)
8310 pagezero((void *)va);
8312 bzero((char *)va + off, size);
8316 * Copy 1 specified hardware page to another.
8319 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8321 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8322 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8324 pagecopy((void *)src, (void *)dst);
8327 int unmapped_buf_allowed = 1;
8330 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8331 vm_offset_t b_offset, int xfersize)
8335 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8339 while (xfersize > 0) {
8340 a_pg_offset = a_offset & PAGE_MASK;
8341 pages[0] = ma[a_offset >> PAGE_SHIFT];
8342 b_pg_offset = b_offset & PAGE_MASK;
8343 pages[1] = mb[b_offset >> PAGE_SHIFT];
8344 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8345 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8346 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
8347 a_cp = (char *)vaddr[0] + a_pg_offset;
8348 b_cp = (char *)vaddr[1] + b_pg_offset;
8349 bcopy(a_cp, b_cp, cnt);
8350 if (__predict_false(mapped))
8351 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
8359 * Returns true if the pmap's pv is one of the first
8360 * 16 pvs linked to from this page. This count may
8361 * be changed upwards or downwards in the future; it
8362 * is only necessary that true be returned for a small
8363 * subset of pmaps for proper page aging.
8366 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8368 struct md_page *pvh;
8369 struct rwlock *lock;
8374 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8375 ("pmap_page_exists_quick: page %p is not managed", m));
8377 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8379 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8380 if (PV_PMAP(pv) == pmap) {
8388 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8389 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8390 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8391 if (PV_PMAP(pv) == pmap) {
8405 * pmap_page_wired_mappings:
8407 * Return the number of managed mappings to the given physical page
8411 pmap_page_wired_mappings(vm_page_t m)
8413 struct rwlock *lock;
8414 struct md_page *pvh;
8418 int count, md_gen, pvh_gen;
8420 if ((m->oflags & VPO_UNMANAGED) != 0)
8422 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8426 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8428 if (!PMAP_TRYLOCK(pmap)) {
8429 md_gen = m->md.pv_gen;
8433 if (md_gen != m->md.pv_gen) {
8438 pte = pmap_pte(pmap, pv->pv_va);
8439 if ((*pte & PG_W) != 0)
8443 if ((m->flags & PG_FICTITIOUS) == 0) {
8444 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8445 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8447 if (!PMAP_TRYLOCK(pmap)) {
8448 md_gen = m->md.pv_gen;
8449 pvh_gen = pvh->pv_gen;
8453 if (md_gen != m->md.pv_gen ||
8454 pvh_gen != pvh->pv_gen) {
8459 pte = pmap_pde(pmap, pv->pv_va);
8460 if ((*pte & PG_W) != 0)
8470 * Returns TRUE if the given page is mapped individually or as part of
8471 * a 2mpage. Otherwise, returns FALSE.
8474 pmap_page_is_mapped(vm_page_t m)
8476 struct rwlock *lock;
8479 if ((m->oflags & VPO_UNMANAGED) != 0)
8481 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8483 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8484 ((m->flags & PG_FICTITIOUS) == 0 &&
8485 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8491 * Destroy all managed, non-wired mappings in the given user-space
8492 * pmap. This pmap cannot be active on any processor besides the
8495 * This function cannot be applied to the kernel pmap. Moreover, it
8496 * is not intended for general use. It is only to be used during
8497 * process termination. Consequently, it can be implemented in ways
8498 * that make it faster than pmap_remove(). First, it can more quickly
8499 * destroy mappings by iterating over the pmap's collection of PV
8500 * entries, rather than searching the page table. Second, it doesn't
8501 * have to test and clear the page table entries atomically, because
8502 * no processor is currently accessing the user address space. In
8503 * particular, a page table entry's dirty bit won't change state once
8504 * this function starts.
8506 * Although this function destroys all of the pmap's managed,
8507 * non-wired mappings, it can delay and batch the invalidation of TLB
8508 * entries without calling pmap_delayed_invl_start() and
8509 * pmap_delayed_invl_finish(). Because the pmap is not active on
8510 * any other processor, none of these TLB entries will ever be used
8511 * before their eventual invalidation. Consequently, there is no need
8512 * for either pmap_remove_all() or pmap_remove_write() to wait for
8513 * that eventual TLB invalidation.
8516 pmap_remove_pages(pmap_t pmap)
8519 pt_entry_t *pte, tpte;
8520 pt_entry_t PG_M, PG_RW, PG_V;
8521 struct spglist free;
8522 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8523 vm_page_t m, mpte, mt;
8525 struct md_page *pvh;
8526 struct pv_chunk *pc, *npc;
8527 struct rwlock *lock;
8529 uint64_t inuse, bitmask;
8530 int allfree, field, i, idx;
8534 boolean_t superpage;
8538 * Assert that the given pmap is only active on the current
8539 * CPU. Unfortunately, we cannot block another CPU from
8540 * activating the pmap while this function is executing.
8542 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8545 cpuset_t other_cpus;
8547 other_cpus = all_cpus;
8549 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8550 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8552 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8557 PG_M = pmap_modified_bit(pmap);
8558 PG_V = pmap_valid_bit(pmap);
8559 PG_RW = pmap_rw_bit(pmap);
8561 for (i = 0; i < PMAP_MEMDOM; i++)
8562 TAILQ_INIT(&free_chunks[i]);
8565 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8570 for (field = 0; field < _NPCM; field++) {
8571 inuse = ~pc->pc_map[field] & pc_freemask[field];
8572 while (inuse != 0) {
8574 bitmask = 1UL << bit;
8575 idx = field * 64 + bit;
8576 pv = &pc->pc_pventry[idx];
8579 pte = pmap_pdpe(pmap, pv->pv_va);
8581 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8583 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8586 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8588 pte = &pte[pmap_pte_index(pv->pv_va)];
8592 * Keep track whether 'tpte' is a
8593 * superpage explicitly instead of
8594 * relying on PG_PS being set.
8596 * This is because PG_PS is numerically
8597 * identical to PG_PTE_PAT and thus a
8598 * regular page could be mistaken for
8604 if ((tpte & PG_V) == 0) {
8605 panic("bad pte va %lx pte %lx",
8610 * We cannot remove wired pages from a process' mapping at this time
8618 pc->pc_map[field] |= bitmask;
8621 * Because this pmap is not active on other
8622 * processors, the dirty bit cannot have
8623 * changed state since we last loaded pte.
8628 pa = tpte & PG_PS_FRAME;
8630 pa = tpte & PG_FRAME;
8632 m = PHYS_TO_VM_PAGE(pa);
8633 KASSERT(m->phys_addr == pa,
8634 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8635 m, (uintmax_t)m->phys_addr,
8638 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8639 m < &vm_page_array[vm_page_array_size],
8640 ("pmap_remove_pages: bad tpte %#jx",
8644 * Update the vm_page_t clean/reference bits.
8646 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8648 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8654 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8657 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8658 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8659 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8661 if (TAILQ_EMPTY(&pvh->pv_list)) {
8662 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8663 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8664 TAILQ_EMPTY(&mt->md.pv_list))
8665 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8667 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8669 KASSERT(vm_page_any_valid(mpte),
8670 ("pmap_remove_pages: pte page not promoted"));
8671 pmap_pt_page_count_adj(pmap, -1);
8672 KASSERT(mpte->ref_count == NPTEPG,
8673 ("pmap_remove_pages: pte page reference count error"));
8674 mpte->ref_count = 0;
8675 pmap_add_delayed_free_list(mpte, &free, FALSE);
8678 pmap_resident_count_adj(pmap, -1);
8679 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8681 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8682 TAILQ_EMPTY(&m->md.pv_list) &&
8683 (m->flags & PG_FICTITIOUS) == 0) {
8684 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8685 if (TAILQ_EMPTY(&pvh->pv_list))
8686 vm_page_aflag_clear(m, PGA_WRITEABLE);
8689 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8695 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8696 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8697 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8699 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8700 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8705 pmap_invalidate_all(pmap);
8706 pmap_pkru_deassign_all(pmap);
8707 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8709 vm_page_free_pages_toq(&free, true);
8713 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
8715 struct rwlock *lock;
8717 struct md_page *pvh;
8718 pt_entry_t *pte, mask;
8719 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8721 int md_gen, pvh_gen;
8725 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8728 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8730 if (!PMAP_TRYLOCK(pmap)) {
8731 md_gen = m->md.pv_gen;
8735 if (md_gen != m->md.pv_gen) {
8740 pte = pmap_pte(pmap, pv->pv_va);
8743 PG_M = pmap_modified_bit(pmap);
8744 PG_RW = pmap_rw_bit(pmap);
8745 mask |= PG_RW | PG_M;
8748 PG_A = pmap_accessed_bit(pmap);
8749 PG_V = pmap_valid_bit(pmap);
8750 mask |= PG_V | PG_A;
8752 rv = (*pte & mask) == mask;
8757 if ((m->flags & PG_FICTITIOUS) == 0) {
8758 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8759 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8761 if (!PMAP_TRYLOCK(pmap)) {
8762 md_gen = m->md.pv_gen;
8763 pvh_gen = pvh->pv_gen;
8767 if (md_gen != m->md.pv_gen ||
8768 pvh_gen != pvh->pv_gen) {
8773 pte = pmap_pde(pmap, pv->pv_va);
8776 PG_M = pmap_modified_bit(pmap);
8777 PG_RW = pmap_rw_bit(pmap);
8778 mask |= PG_RW | PG_M;
8781 PG_A = pmap_accessed_bit(pmap);
8782 PG_V = pmap_valid_bit(pmap);
8783 mask |= PG_V | PG_A;
8785 rv = (*pte & mask) == mask;
8799 * Return whether or not the specified physical page was modified
8800 * in any physical maps.
8803 pmap_is_modified(vm_page_t m)
8806 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8807 ("pmap_is_modified: page %p is not managed", m));
8810 * If the page is not busied then this check is racy.
8812 if (!pmap_page_is_write_mapped(m))
8814 return (pmap_page_test_mappings(m, FALSE, TRUE));
8818 * pmap_is_prefaultable:
8820 * Return whether or not the specified virtual address is eligible
8824 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8827 pt_entry_t *pte, PG_V;
8830 PG_V = pmap_valid_bit(pmap);
8833 * Return TRUE if and only if the PTE for the specified virtual
8834 * address is allocated but invalid.
8838 pde = pmap_pde(pmap, addr);
8839 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8840 pte = pmap_pde_to_pte(pde, addr);
8841 rv = (*pte & PG_V) == 0;
8848 * pmap_is_referenced:
8850 * Return whether or not the specified physical page was referenced
8851 * in any physical maps.
8854 pmap_is_referenced(vm_page_t m)
8857 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8858 ("pmap_is_referenced: page %p is not managed", m));
8859 return (pmap_page_test_mappings(m, TRUE, FALSE));
8863 * Clear the write and modified bits in each of the given page's mappings.
8866 pmap_remove_write(vm_page_t m)
8868 struct md_page *pvh;
8870 struct rwlock *lock;
8871 pv_entry_t next_pv, pv;
8873 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8875 int pvh_gen, md_gen;
8877 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8878 ("pmap_remove_write: page %p is not managed", m));
8880 vm_page_assert_busied(m);
8881 if (!pmap_page_is_write_mapped(m))
8884 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8885 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8886 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8889 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8891 if (!PMAP_TRYLOCK(pmap)) {
8892 pvh_gen = pvh->pv_gen;
8896 if (pvh_gen != pvh->pv_gen) {
8901 PG_RW = pmap_rw_bit(pmap);
8903 pde = pmap_pde(pmap, va);
8904 if ((*pde & PG_RW) != 0)
8905 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8906 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8907 ("inconsistent pv lock %p %p for page %p",
8908 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8911 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8913 if (!PMAP_TRYLOCK(pmap)) {
8914 pvh_gen = pvh->pv_gen;
8915 md_gen = m->md.pv_gen;
8919 if (pvh_gen != pvh->pv_gen ||
8920 md_gen != m->md.pv_gen) {
8925 PG_M = pmap_modified_bit(pmap);
8926 PG_RW = pmap_rw_bit(pmap);
8927 pde = pmap_pde(pmap, pv->pv_va);
8928 KASSERT((*pde & PG_PS) == 0,
8929 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8931 pte = pmap_pde_to_pte(pde, pv->pv_va);
8933 if (oldpte & PG_RW) {
8934 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8937 if ((oldpte & PG_M) != 0)
8939 pmap_invalidate_page(pmap, pv->pv_va);
8944 vm_page_aflag_clear(m, PGA_WRITEABLE);
8945 pmap_delayed_invl_wait(m);
8949 * pmap_ts_referenced:
8951 * Return a count of reference bits for a page, clearing those bits.
8952 * It is not necessary for every reference bit to be cleared, but it
8953 * is necessary that 0 only be returned when there are truly no
8954 * reference bits set.
8956 * As an optimization, update the page's dirty field if a modified bit is
8957 * found while counting reference bits. This opportunistic update can be
8958 * performed at low cost and can eliminate the need for some future calls
8959 * to pmap_is_modified(). However, since this function stops after
8960 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8961 * dirty pages. Those dirty pages will only be detected by a future call
8962 * to pmap_is_modified().
8964 * A DI block is not needed within this function, because
8965 * invalidations are performed before the PV list lock is
8969 pmap_ts_referenced(vm_page_t m)
8971 struct md_page *pvh;
8974 struct rwlock *lock;
8975 pd_entry_t oldpde, *pde;
8976 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8979 int cleared, md_gen, not_cleared, pvh_gen;
8980 struct spglist free;
8983 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8984 ("pmap_ts_referenced: page %p is not managed", m));
8987 pa = VM_PAGE_TO_PHYS(m);
8988 lock = PHYS_TO_PV_LIST_LOCK(pa);
8989 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8993 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
8994 goto small_mappings;
9000 if (!PMAP_TRYLOCK(pmap)) {
9001 pvh_gen = pvh->pv_gen;
9005 if (pvh_gen != pvh->pv_gen) {
9010 PG_A = pmap_accessed_bit(pmap);
9011 PG_M = pmap_modified_bit(pmap);
9012 PG_RW = pmap_rw_bit(pmap);
9014 pde = pmap_pde(pmap, pv->pv_va);
9016 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9018 * Although "oldpde" is mapping a 2MB page, because
9019 * this function is called at a 4KB page granularity,
9020 * we only update the 4KB page under test.
9024 if ((oldpde & PG_A) != 0) {
9026 * Since this reference bit is shared by 512 4KB
9027 * pages, it should not be cleared every time it is
9028 * tested. Apply a simple "hash" function on the
9029 * physical page number, the virtual superpage number,
9030 * and the pmap address to select one 4KB page out of
9031 * the 512 on which testing the reference bit will
9032 * result in clearing that reference bit. This
9033 * function is designed to avoid the selection of the
9034 * same 4KB page for every 2MB page mapping.
9036 * On demotion, a mapping that hasn't been referenced
9037 * is simply destroyed. To avoid the possibility of a
9038 * subsequent page fault on a demoted wired mapping,
9039 * always leave its reference bit set. Moreover,
9040 * since the superpage is wired, the current state of
9041 * its reference bit won't affect page replacement.
9043 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
9044 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
9045 (oldpde & PG_W) == 0) {
9046 if (safe_to_clear_referenced(pmap, oldpde)) {
9047 atomic_clear_long(pde, PG_A);
9048 pmap_invalidate_page(pmap, pv->pv_va);
9050 } else if (pmap_demote_pde_locked(pmap, pde,
9051 pv->pv_va, &lock)) {
9053 * Remove the mapping to a single page
9054 * so that a subsequent access may
9055 * repromote. Since the underlying
9056 * page table page is fully populated,
9057 * this removal never frees a page
9061 va += VM_PAGE_TO_PHYS(m) - (oldpde &
9063 pte = pmap_pde_to_pte(pde, va);
9064 pmap_remove_pte(pmap, pte, va, *pde,
9066 pmap_invalidate_page(pmap, va);
9072 * The superpage mapping was removed
9073 * entirely and therefore 'pv' is no
9081 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9082 ("inconsistent pv lock %p %p for page %p",
9083 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9088 /* Rotate the PV list if it has more than one entry. */
9089 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9090 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
9091 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
9094 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
9096 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9098 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9105 if (!PMAP_TRYLOCK(pmap)) {
9106 pvh_gen = pvh->pv_gen;
9107 md_gen = m->md.pv_gen;
9111 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9116 PG_A = pmap_accessed_bit(pmap);
9117 PG_M = pmap_modified_bit(pmap);
9118 PG_RW = pmap_rw_bit(pmap);
9119 pde = pmap_pde(pmap, pv->pv_va);
9120 KASSERT((*pde & PG_PS) == 0,
9121 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9123 pte = pmap_pde_to_pte(pde, pv->pv_va);
9124 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9126 if ((*pte & PG_A) != 0) {
9127 if (safe_to_clear_referenced(pmap, *pte)) {
9128 atomic_clear_long(pte, PG_A);
9129 pmap_invalidate_page(pmap, pv->pv_va);
9131 } else if ((*pte & PG_W) == 0) {
9133 * Wired pages cannot be paged out so
9134 * doing accessed bit emulation for
9135 * them is wasted effort. We do the
9136 * hard work for unwired pages only.
9138 pmap_remove_pte(pmap, pte, pv->pv_va,
9139 *pde, &free, &lock);
9140 pmap_invalidate_page(pmap, pv->pv_va);
9145 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9146 ("inconsistent pv lock %p %p for page %p",
9147 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9152 /* Rotate the PV list if it has more than one entry. */
9153 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9154 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9155 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9158 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9159 not_cleared < PMAP_TS_REFERENCED_MAX);
9162 vm_page_free_pages_toq(&free, true);
9163 return (cleared + not_cleared);
9167 * Apply the given advice to the specified range of addresses within the
9168 * given pmap. Depending on the advice, clear the referenced and/or
9169 * modified flags in each mapping and set the mapped page's dirty field.
9172 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9174 struct rwlock *lock;
9175 pml4_entry_t *pml4e;
9177 pd_entry_t oldpde, *pde;
9178 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9179 vm_offset_t va, va_next;
9183 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9187 * A/D bit emulation requires an alternate code path when clearing
9188 * the modified and accessed bits below. Since this function is
9189 * advisory in nature we skip it entirely for pmaps that require
9190 * A/D bit emulation.
9192 if (pmap_emulate_ad_bits(pmap))
9195 PG_A = pmap_accessed_bit(pmap);
9196 PG_G = pmap_global_bit(pmap);
9197 PG_M = pmap_modified_bit(pmap);
9198 PG_V = pmap_valid_bit(pmap);
9199 PG_RW = pmap_rw_bit(pmap);
9201 pmap_delayed_invl_start();
9203 for (; sva < eva; sva = va_next) {
9204 pml4e = pmap_pml4e(pmap, sva);
9205 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9206 va_next = (sva + NBPML4) & ~PML4MASK;
9212 va_next = (sva + NBPDP) & ~PDPMASK;
9215 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9216 if ((*pdpe & PG_V) == 0)
9218 if ((*pdpe & PG_PS) != 0)
9221 va_next = (sva + NBPDR) & ~PDRMASK;
9224 pde = pmap_pdpe_to_pde(pdpe, sva);
9226 if ((oldpde & PG_V) == 0)
9228 else if ((oldpde & PG_PS) != 0) {
9229 if ((oldpde & PG_MANAGED) == 0)
9232 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9237 * The large page mapping was destroyed.
9243 * Unless the page mappings are wired, remove the
9244 * mapping to a single page so that a subsequent
9245 * access may repromote. Choosing the last page
9246 * within the address range [sva, min(va_next, eva))
9247 * generally results in more repromotions. Since the
9248 * underlying page table page is fully populated, this
9249 * removal never frees a page table page.
9251 if ((oldpde & PG_W) == 0) {
9257 ("pmap_advise: no address gap"));
9258 pte = pmap_pde_to_pte(pde, va);
9259 KASSERT((*pte & PG_V) != 0,
9260 ("pmap_advise: invalid PTE"));
9261 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9271 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9273 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9275 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9276 if (advice == MADV_DONTNEED) {
9278 * Future calls to pmap_is_modified()
9279 * can be avoided by making the page
9282 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9285 atomic_clear_long(pte, PG_M | PG_A);
9286 } else if ((*pte & PG_A) != 0)
9287 atomic_clear_long(pte, PG_A);
9291 if ((*pte & PG_G) != 0) {
9298 if (va != va_next) {
9299 pmap_invalidate_range(pmap, va, sva);
9304 pmap_invalidate_range(pmap, va, sva);
9307 pmap_invalidate_all(pmap);
9309 pmap_delayed_invl_finish();
9313 * Clear the modify bits on the specified physical page.
9316 pmap_clear_modify(vm_page_t m)
9318 struct md_page *pvh;
9320 pv_entry_t next_pv, pv;
9321 pd_entry_t oldpde, *pde;
9322 pt_entry_t *pte, PG_M, PG_RW;
9323 struct rwlock *lock;
9325 int md_gen, pvh_gen;
9327 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9328 ("pmap_clear_modify: page %p is not managed", m));
9329 vm_page_assert_busied(m);
9331 if (!pmap_page_is_write_mapped(m))
9333 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9334 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9335 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9338 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9340 if (!PMAP_TRYLOCK(pmap)) {
9341 pvh_gen = pvh->pv_gen;
9345 if (pvh_gen != pvh->pv_gen) {
9350 PG_M = pmap_modified_bit(pmap);
9351 PG_RW = pmap_rw_bit(pmap);
9353 pde = pmap_pde(pmap, va);
9355 /* If oldpde has PG_RW set, then it also has PG_M set. */
9356 if ((oldpde & PG_RW) != 0 &&
9357 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9358 (oldpde & PG_W) == 0) {
9360 * Write protect the mapping to a single page so that
9361 * a subsequent write access may repromote.
9363 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9364 pte = pmap_pde_to_pte(pde, va);
9365 atomic_clear_long(pte, PG_M | PG_RW);
9367 pmap_invalidate_page(pmap, va);
9371 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9373 if (!PMAP_TRYLOCK(pmap)) {
9374 md_gen = m->md.pv_gen;
9375 pvh_gen = pvh->pv_gen;
9379 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9384 PG_M = pmap_modified_bit(pmap);
9385 PG_RW = pmap_rw_bit(pmap);
9386 pde = pmap_pde(pmap, pv->pv_va);
9387 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9388 " a 2mpage in page %p's pv list", m));
9389 pte = pmap_pde_to_pte(pde, pv->pv_va);
9390 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9391 atomic_clear_long(pte, PG_M);
9392 pmap_invalidate_page(pmap, pv->pv_va);
9400 * Miscellaneous support routines follow
9403 /* Adjust the properties for a leaf page table entry. */
9404 static __inline void
9405 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9409 opte = *(u_long *)pte;
9411 npte = opte & ~mask;
9413 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9418 * Map a set of physical memory pages into the kernel virtual
9419 * address space. Return a pointer to where it is mapped. This
9420 * routine is intended to be used for mapping device memory,
9424 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9426 struct pmap_preinit_mapping *ppim;
9427 vm_offset_t va, offset;
9431 offset = pa & PAGE_MASK;
9432 size = round_page(offset + size);
9433 pa = trunc_page(pa);
9435 if (!pmap_initialized) {
9437 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9438 ppim = pmap_preinit_mapping + i;
9439 if (ppim->va == 0) {
9443 ppim->va = virtual_avail;
9444 virtual_avail += size;
9450 panic("%s: too many preinit mappings", __func__);
9453 * If we have a preinit mapping, re-use it.
9455 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9456 ppim = pmap_preinit_mapping + i;
9457 if (ppim->pa == pa && ppim->sz == size &&
9458 (ppim->mode == mode ||
9459 (flags & MAPDEV_SETATTR) == 0))
9460 return ((void *)(ppim->va + offset));
9463 * If the specified range of physical addresses fits within
9464 * the direct map window, use the direct map.
9466 if (pa < dmaplimit && pa + size <= dmaplimit) {
9467 va = PHYS_TO_DMAP(pa);
9468 if ((flags & MAPDEV_SETATTR) != 0) {
9469 PMAP_LOCK(kernel_pmap);
9470 i = pmap_change_props_locked(va, size,
9471 PROT_NONE, mode, flags);
9472 PMAP_UNLOCK(kernel_pmap);
9476 return ((void *)(va + offset));
9478 va = kva_alloc(size);
9480 panic("%s: Couldn't allocate KVA", __func__);
9482 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9483 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9484 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9485 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9486 pmap_invalidate_cache_range(va, va + tmpsize);
9487 return ((void *)(va + offset));
9491 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9494 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9499 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9502 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9506 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9509 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9514 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9517 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9518 MAPDEV_FLUSHCACHE));
9522 pmap_unmapdev(void *p, vm_size_t size)
9524 struct pmap_preinit_mapping *ppim;
9525 vm_offset_t offset, va;
9528 va = (vm_offset_t)p;
9530 /* If we gave a direct map region in pmap_mapdev, do nothing */
9531 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9533 offset = va & PAGE_MASK;
9534 size = round_page(offset + size);
9535 va = trunc_page(va);
9536 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9537 ppim = pmap_preinit_mapping + i;
9538 if (ppim->va == va && ppim->sz == size) {
9539 if (pmap_initialized)
9545 if (va + size == virtual_avail)
9550 if (pmap_initialized) {
9551 pmap_qremove(va, atop(size));
9557 * Tries to demote a 1GB page mapping.
9560 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9562 pdp_entry_t newpdpe, oldpdpe;
9563 pd_entry_t *firstpde, newpde, *pde;
9564 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9568 PG_A = pmap_accessed_bit(pmap);
9569 PG_M = pmap_modified_bit(pmap);
9570 PG_V = pmap_valid_bit(pmap);
9571 PG_RW = pmap_rw_bit(pmap);
9573 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9575 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9576 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9577 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9578 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9580 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9581 " in pmap %p", va, pmap);
9584 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9585 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9586 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9587 KASSERT((oldpdpe & PG_A) != 0,
9588 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9589 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9590 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9594 * Initialize the page directory page.
9596 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9602 * Demote the mapping.
9607 * Invalidate a stale recursive mapping of the page directory page.
9609 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9611 counter_u64_add(pmap_pdpe_demotions, 1);
9612 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9613 " in pmap %p", va, pmap);
9618 * Sets the memory attribute for the specified page.
9621 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9624 m->md.pat_mode = ma;
9627 * If "m" is a normal page, update its direct mapping. This update
9628 * can be relied upon to perform any cache operations that are
9629 * required for data coherence.
9631 if ((m->flags & PG_FICTITIOUS) == 0 &&
9632 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9634 panic("memory attribute change on the direct map failed");
9638 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9642 m->md.pat_mode = ma;
9644 if ((m->flags & PG_FICTITIOUS) != 0)
9646 PMAP_LOCK(kernel_pmap);
9647 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9648 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9649 PMAP_UNLOCK(kernel_pmap);
9651 panic("memory attribute change on the direct map failed");
9655 * Changes the specified virtual address range's memory type to that given by
9656 * the parameter "mode". The specified virtual address range must be
9657 * completely contained within either the direct map or the kernel map. If
9658 * the virtual address range is contained within the kernel map, then the
9659 * memory type for each of the corresponding ranges of the direct map is also
9660 * changed. (The corresponding ranges of the direct map are those ranges that
9661 * map the same physical pages as the specified virtual address range.) These
9662 * changes to the direct map are necessary because Intel describes the
9663 * behavior of their processors as "undefined" if two or more mappings to the
9664 * same physical page have different memory types.
9666 * Returns zero if the change completed successfully, and either EINVAL or
9667 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9668 * of the virtual address range was not mapped, and ENOMEM is returned if
9669 * there was insufficient memory available to complete the change. In the
9670 * latter case, the memory type may have been changed on some part of the
9671 * virtual address range or the direct map.
9674 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9678 PMAP_LOCK(kernel_pmap);
9679 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9681 PMAP_UNLOCK(kernel_pmap);
9686 * Changes the specified virtual address range's protections to those
9687 * specified by "prot". Like pmap_change_attr(), protections for aliases
9688 * in the direct map are updated as well. Protections on aliasing mappings may
9689 * be a subset of the requested protections; for example, mappings in the direct
9690 * map are never executable.
9693 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9697 /* Only supported within the kernel map. */
9698 if (va < VM_MIN_KERNEL_ADDRESS)
9701 PMAP_LOCK(kernel_pmap);
9702 error = pmap_change_props_locked(va, size, prot, -1,
9703 MAPDEV_ASSERTVALID);
9704 PMAP_UNLOCK(kernel_pmap);
9709 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9710 int mode, int flags)
9712 vm_offset_t base, offset, tmpva;
9713 vm_paddr_t pa_start, pa_end, pa_end1;
9715 pd_entry_t *pde, pde_bits, pde_mask;
9716 pt_entry_t *pte, pte_bits, pte_mask;
9720 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9721 base = trunc_page(va);
9722 offset = va & PAGE_MASK;
9723 size = round_page(offset + size);
9726 * Only supported on kernel virtual addresses, including the direct
9727 * map but excluding the recursive map.
9729 if (base < DMAP_MIN_ADDRESS)
9733 * Construct our flag sets and masks. "bits" is the subset of
9734 * "mask" that will be set in each modified PTE.
9736 * Mappings in the direct map are never allowed to be executable.
9738 pde_bits = pte_bits = 0;
9739 pde_mask = pte_mask = 0;
9741 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9742 pde_mask |= X86_PG_PDE_CACHE;
9743 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9744 pte_mask |= X86_PG_PTE_CACHE;
9746 if (prot != VM_PROT_NONE) {
9747 if ((prot & VM_PROT_WRITE) != 0) {
9748 pde_bits |= X86_PG_RW;
9749 pte_bits |= X86_PG_RW;
9751 if ((prot & VM_PROT_EXECUTE) == 0 ||
9752 va < VM_MIN_KERNEL_ADDRESS) {
9756 pde_mask |= X86_PG_RW | pg_nx;
9757 pte_mask |= X86_PG_RW | pg_nx;
9761 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9762 * into 4KB pages if required.
9764 for (tmpva = base; tmpva < base + size; ) {
9765 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9766 if (pdpe == NULL || *pdpe == 0) {
9767 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9768 ("%s: addr %#lx is not mapped", __func__, tmpva));
9771 if (*pdpe & PG_PS) {
9773 * If the current 1GB page already has the required
9774 * properties, then we need not demote this page. Just
9775 * increment tmpva to the next 1GB page frame.
9777 if ((*pdpe & pde_mask) == pde_bits) {
9778 tmpva = trunc_1gpage(tmpva) + NBPDP;
9783 * If the current offset aligns with a 1GB page frame
9784 * and there is at least 1GB left within the range, then
9785 * we need not break down this page into 2MB pages.
9787 if ((tmpva & PDPMASK) == 0 &&
9788 tmpva + PDPMASK < base + size) {
9792 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9795 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9797 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9798 ("%s: addr %#lx is not mapped", __func__, tmpva));
9803 * If the current 2MB page already has the required
9804 * properties, then we need not demote this page. Just
9805 * increment tmpva to the next 2MB page frame.
9807 if ((*pde & pde_mask) == pde_bits) {
9808 tmpva = trunc_2mpage(tmpva) + NBPDR;
9813 * If the current offset aligns with a 2MB page frame
9814 * and there is at least 2MB left within the range, then
9815 * we need not break down this page into 4KB pages.
9817 if ((tmpva & PDRMASK) == 0 &&
9818 tmpva + PDRMASK < base + size) {
9822 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9825 pte = pmap_pde_to_pte(pde, tmpva);
9827 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9828 ("%s: addr %#lx is not mapped", __func__, tmpva));
9836 * Ok, all the pages exist, so run through them updating their
9837 * properties if required.
9840 pa_start = pa_end = 0;
9841 for (tmpva = base; tmpva < base + size; ) {
9842 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9843 if (*pdpe & PG_PS) {
9844 if ((*pdpe & pde_mask) != pde_bits) {
9845 pmap_pte_props(pdpe, pde_bits, pde_mask);
9848 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9849 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9850 if (pa_start == pa_end) {
9851 /* Start physical address run. */
9852 pa_start = *pdpe & PG_PS_FRAME;
9853 pa_end = pa_start + NBPDP;
9854 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9857 /* Run ended, update direct map. */
9858 error = pmap_change_props_locked(
9859 PHYS_TO_DMAP(pa_start),
9860 pa_end - pa_start, prot, mode,
9864 /* Start physical address run. */
9865 pa_start = *pdpe & PG_PS_FRAME;
9866 pa_end = pa_start + NBPDP;
9869 tmpva = trunc_1gpage(tmpva) + NBPDP;
9872 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9874 if ((*pde & pde_mask) != pde_bits) {
9875 pmap_pte_props(pde, pde_bits, pde_mask);
9878 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9879 (*pde & PG_PS_FRAME) < dmaplimit) {
9880 if (pa_start == pa_end) {
9881 /* Start physical address run. */
9882 pa_start = *pde & PG_PS_FRAME;
9883 pa_end = pa_start + NBPDR;
9884 } else if (pa_end == (*pde & PG_PS_FRAME))
9887 /* Run ended, update direct map. */
9888 error = pmap_change_props_locked(
9889 PHYS_TO_DMAP(pa_start),
9890 pa_end - pa_start, prot, mode,
9894 /* Start physical address run. */
9895 pa_start = *pde & PG_PS_FRAME;
9896 pa_end = pa_start + NBPDR;
9899 tmpva = trunc_2mpage(tmpva) + NBPDR;
9901 pte = pmap_pde_to_pte(pde, tmpva);
9902 if ((*pte & pte_mask) != pte_bits) {
9903 pmap_pte_props(pte, pte_bits, pte_mask);
9906 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9907 (*pte & PG_FRAME) < dmaplimit) {
9908 if (pa_start == pa_end) {
9909 /* Start physical address run. */
9910 pa_start = *pte & PG_FRAME;
9911 pa_end = pa_start + PAGE_SIZE;
9912 } else if (pa_end == (*pte & PG_FRAME))
9913 pa_end += PAGE_SIZE;
9915 /* Run ended, update direct map. */
9916 error = pmap_change_props_locked(
9917 PHYS_TO_DMAP(pa_start),
9918 pa_end - pa_start, prot, mode,
9922 /* Start physical address run. */
9923 pa_start = *pte & PG_FRAME;
9924 pa_end = pa_start + PAGE_SIZE;
9930 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9931 pa_end1 = MIN(pa_end, dmaplimit);
9932 if (pa_start != pa_end1)
9933 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9934 pa_end1 - pa_start, prot, mode, flags);
9938 * Flush CPU caches if required to make sure any data isn't cached that
9939 * shouldn't be, etc.
9942 pmap_invalidate_range(kernel_pmap, base, tmpva);
9943 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9944 pmap_invalidate_cache_range(base, tmpva);
9950 * Demotes any mapping within the direct map region that covers more than the
9951 * specified range of physical addresses. This range's size must be a power
9952 * of two and its starting address must be a multiple of its size. Since the
9953 * demotion does not change any attributes of the mapping, a TLB invalidation
9954 * is not mandatory. The caller may, however, request a TLB invalidation.
9957 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
9966 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9967 KASSERT((base & (len - 1)) == 0,
9968 ("pmap_demote_DMAP: base is not a multiple of len"));
9969 if (len < NBPDP && base < dmaplimit) {
9970 va = PHYS_TO_DMAP(base);
9972 PMAP_LOCK(kernel_pmap);
9973 pdpe = pmap_pdpe(kernel_pmap, va);
9974 if ((*pdpe & X86_PG_V) == 0)
9975 panic("pmap_demote_DMAP: invalid PDPE");
9976 if ((*pdpe & PG_PS) != 0) {
9977 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9978 panic("pmap_demote_DMAP: PDPE failed");
9982 pde = pmap_pdpe_to_pde(pdpe, va);
9983 if ((*pde & X86_PG_V) == 0)
9984 panic("pmap_demote_DMAP: invalid PDE");
9985 if ((*pde & PG_PS) != 0) {
9986 if (!pmap_demote_pde(kernel_pmap, pde, va))
9987 panic("pmap_demote_DMAP: PDE failed");
9991 if (changed && invalidate)
9992 pmap_invalidate_page(kernel_pmap, va);
9993 PMAP_UNLOCK(kernel_pmap);
9998 * Perform the pmap work for mincore(2). If the page is not both referenced and
9999 * modified by this pmap, returns its physical address so that the caller can
10000 * find other mappings.
10003 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
10007 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
10011 PG_A = pmap_accessed_bit(pmap);
10012 PG_M = pmap_modified_bit(pmap);
10013 PG_V = pmap_valid_bit(pmap);
10014 PG_RW = pmap_rw_bit(pmap);
10020 pdpe = pmap_pdpe(pmap, addr);
10023 if ((*pdpe & PG_V) != 0) {
10024 if ((*pdpe & PG_PS) != 0) {
10026 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
10028 val = MINCORE_PSIND(2);
10030 pdep = pmap_pde(pmap, addr);
10031 if (pdep != NULL && (*pdep & PG_V) != 0) {
10032 if ((*pdep & PG_PS) != 0) {
10034 /* Compute the physical address of the 4KB page. */
10035 pa = ((pte & PG_PS_FRAME) | (addr &
10036 PDRMASK)) & PG_FRAME;
10037 val = MINCORE_PSIND(1);
10039 pte = *pmap_pde_to_pte(pdep, addr);
10040 pa = pte & PG_FRAME;
10046 if ((pte & PG_V) != 0) {
10047 val |= MINCORE_INCORE;
10048 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
10049 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
10050 if ((pte & PG_A) != 0)
10051 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
10053 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
10054 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
10055 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
10064 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
10066 uint32_t gen, new_gen, pcid_next;
10068 CRITICAL_ASSERT(curthread);
10069 gen = PCPU_GET(pcid_gen);
10070 if (pcidp->pm_pcid == PMAP_PCID_KERN)
10071 return (pti ? 0 : CR3_PCID_SAVE);
10072 if (pcidp->pm_gen == gen)
10073 return (CR3_PCID_SAVE);
10074 pcid_next = PCPU_GET(pcid_next);
10075 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
10076 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
10077 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
10078 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
10079 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
10083 PCPU_SET(pcid_gen, new_gen);
10084 pcid_next = PMAP_PCID_KERN + 1;
10088 pcidp->pm_pcid = pcid_next;
10089 pcidp->pm_gen = new_gen;
10090 PCPU_SET(pcid_next, pcid_next + 1);
10095 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10099 cached = pmap_pcid_alloc(pmap, pcidp);
10100 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10101 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10102 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10103 ("non-kernel pmap pmap %p cpu %d pcid %#x",
10104 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10109 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10112 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10113 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10117 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10120 struct pmap_pcid *pcidp, *old_pcidp;
10121 uint64_t cached, cr3, kcr3, ucr3;
10123 KASSERT((read_rflags() & PSL_I) == 0,
10124 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10126 /* See the comment in pmap_invalidate_page_pcid(). */
10127 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10128 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10129 old_pmap = PCPU_GET(curpmap);
10130 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10131 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10132 old_pcidp->pm_gen = 0;
10135 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10136 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10138 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10139 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10140 PCPU_SET(curpmap, pmap);
10141 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10142 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10144 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10145 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10147 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10148 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10150 counter_u64_add(pcid_save_cnt, 1);
10152 pmap_activate_sw_pti_post(td, pmap);
10156 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10159 struct pmap_pcid *pcidp;
10160 uint64_t cached, cr3;
10162 KASSERT((read_rflags() & PSL_I) == 0,
10163 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10165 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10166 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10168 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10169 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10170 PCPU_SET(curpmap, pmap);
10172 counter_u64_add(pcid_save_cnt, 1);
10176 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10177 u_int cpuid __unused)
10180 load_cr3(pmap->pm_cr3);
10181 PCPU_SET(curpmap, pmap);
10185 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10186 u_int cpuid __unused)
10189 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10190 PCPU_SET(kcr3, pmap->pm_cr3);
10191 PCPU_SET(ucr3, pmap->pm_ucr3);
10192 pmap_activate_sw_pti_post(td, pmap);
10195 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10199 if (pmap_pcid_enabled && pti)
10200 return (pmap_activate_sw_pcid_pti);
10201 else if (pmap_pcid_enabled && !pti)
10202 return (pmap_activate_sw_pcid_nopti);
10203 else if (!pmap_pcid_enabled && pti)
10204 return (pmap_activate_sw_nopcid_pti);
10205 else /* if (!pmap_pcid_enabled && !pti) */
10206 return (pmap_activate_sw_nopcid_nopti);
10210 pmap_activate_sw(struct thread *td)
10212 pmap_t oldpmap, pmap;
10215 oldpmap = PCPU_GET(curpmap);
10216 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10217 if (oldpmap == pmap) {
10218 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10222 cpuid = PCPU_GET(cpuid);
10224 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10226 CPU_SET(cpuid, &pmap->pm_active);
10228 pmap_activate_sw_mode(td, pmap, cpuid);
10230 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10232 CPU_CLR(cpuid, &oldpmap->pm_active);
10237 pmap_activate(struct thread *td)
10240 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10241 * invalidate_all IPI, which checks for curpmap ==
10242 * smp_tlb_pmap. The below sequence of operations has a
10243 * window where %CR3 is loaded with the new pmap's PML4
10244 * address, but the curpmap value has not yet been updated.
10245 * This causes the invltlb IPI handler, which is called
10246 * between the updates, to execute as a NOP, which leaves
10247 * stale TLB entries.
10249 * Note that the most common use of pmap_activate_sw(), from
10250 * a context switch, is immune to this race, because
10251 * interrupts are disabled (while the thread lock is owned),
10252 * so the IPI is delayed until after curpmap is updated. Protect
10253 * other callers in a similar way, by disabling interrupts
10254 * around the %cr3 register reload and curpmap assignment.
10257 pmap_activate_sw(td);
10262 pmap_activate_boot(pmap_t pmap)
10268 * kernel_pmap must be never deactivated, and we ensure that
10269 * by never activating it at all.
10271 MPASS(pmap != kernel_pmap);
10273 cpuid = PCPU_GET(cpuid);
10275 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10277 CPU_SET(cpuid, &pmap->pm_active);
10279 PCPU_SET(curpmap, pmap);
10281 kcr3 = pmap->pm_cr3;
10282 if (pmap_pcid_enabled)
10283 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10285 kcr3 = PMAP_NO_CR3;
10287 PCPU_SET(kcr3, kcr3);
10288 PCPU_SET(ucr3, PMAP_NO_CR3);
10292 pmap_active_cpus(pmap_t pmap, cpuset_t *res)
10294 *res = pmap->pm_active;
10298 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10303 * Increase the starting virtual address of the given mapping if a
10304 * different alignment might result in more superpage mappings.
10307 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10308 vm_offset_t *addr, vm_size_t size)
10310 vm_offset_t superpage_offset;
10314 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10315 offset += ptoa(object->pg_color);
10316 superpage_offset = offset & PDRMASK;
10317 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10318 (*addr & PDRMASK) == superpage_offset)
10320 if ((*addr & PDRMASK) < superpage_offset)
10321 *addr = (*addr & ~PDRMASK) + superpage_offset;
10323 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10327 static unsigned long num_dirty_emulations;
10328 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10329 &num_dirty_emulations, 0, NULL);
10331 static unsigned long num_accessed_emulations;
10332 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10333 &num_accessed_emulations, 0, NULL);
10335 static unsigned long num_superpage_accessed_emulations;
10336 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10337 &num_superpage_accessed_emulations, 0, NULL);
10339 static unsigned long ad_emulation_superpage_promotions;
10340 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10341 &ad_emulation_superpage_promotions, 0, NULL);
10342 #endif /* INVARIANTS */
10345 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10348 struct rwlock *lock;
10349 #if VM_NRESERVLEVEL > 0
10353 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10355 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10356 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10358 if (!pmap_emulate_ad_bits(pmap))
10361 PG_A = pmap_accessed_bit(pmap);
10362 PG_M = pmap_modified_bit(pmap);
10363 PG_V = pmap_valid_bit(pmap);
10364 PG_RW = pmap_rw_bit(pmap);
10370 pde = pmap_pde(pmap, va);
10371 if (pde == NULL || (*pde & PG_V) == 0)
10374 if ((*pde & PG_PS) != 0) {
10375 if (ftype == VM_PROT_READ) {
10377 atomic_add_long(&num_superpage_accessed_emulations, 1);
10385 pte = pmap_pde_to_pte(pde, va);
10386 if ((*pte & PG_V) == 0)
10389 if (ftype == VM_PROT_WRITE) {
10390 if ((*pte & PG_RW) == 0)
10393 * Set the modified and accessed bits simultaneously.
10395 * Intel EPT PTEs that do software emulation of A/D bits map
10396 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10397 * An EPT misconfiguration is triggered if the PTE is writable
10398 * but not readable (WR=10). This is avoided by setting PG_A
10399 * and PG_M simultaneously.
10401 *pte |= PG_M | PG_A;
10406 #if VM_NRESERVLEVEL > 0
10407 /* try to promote the mapping */
10408 if (va < VM_MAXUSER_ADDRESS)
10409 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10413 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10415 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10416 (m->flags & PG_FICTITIOUS) == 0 &&
10417 vm_reserv_level_iffullpop(m) == 0 &&
10418 pmap_promote_pde(pmap, pde, va, mpte, &lock)) {
10420 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10426 if (ftype == VM_PROT_WRITE)
10427 atomic_add_long(&num_dirty_emulations, 1);
10429 atomic_add_long(&num_accessed_emulations, 1);
10431 rv = 0; /* success */
10440 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10442 pml4_entry_t *pml4;
10445 pt_entry_t *pte, PG_V;
10449 PG_V = pmap_valid_bit(pmap);
10452 pml4 = pmap_pml4e(pmap, va);
10455 ptr[idx++] = *pml4;
10456 if ((*pml4 & PG_V) == 0)
10459 pdp = pmap_pml4e_to_pdpe(pml4, va);
10461 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10464 pde = pmap_pdpe_to_pde(pdp, va);
10466 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10469 pte = pmap_pde_to_pte(pde, va);
10478 * Get the kernel virtual address of a set of physical pages. If there are
10479 * physical addresses not covered by the DMAP perform a transient mapping
10480 * that will be removed when calling pmap_unmap_io_transient.
10482 * \param page The pages the caller wishes to obtain the virtual
10483 * address on the kernel memory map.
10484 * \param vaddr On return contains the kernel virtual memory address
10485 * of the pages passed in the page parameter.
10486 * \param count Number of pages passed in.
10487 * \param can_fault true if the thread using the mapped pages can take
10488 * page faults, false otherwise.
10490 * \returns true if the caller must call pmap_unmap_io_transient when
10491 * finished or false otherwise.
10495 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10499 bool needs_mapping;
10501 int cache_bits, error __unused, i;
10504 * Allocate any KVA space that we need, this is done in a separate
10505 * loop to prevent calling vmem_alloc while pinned.
10507 needs_mapping = false;
10508 for (i = 0; i < count; i++) {
10509 paddr = VM_PAGE_TO_PHYS(page[i]);
10510 if (__predict_false(paddr >= dmaplimit)) {
10511 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10512 M_BESTFIT | M_WAITOK, &vaddr[i]);
10513 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10514 needs_mapping = true;
10516 vaddr[i] = PHYS_TO_DMAP(paddr);
10520 /* Exit early if everything is covered by the DMAP */
10521 if (!needs_mapping)
10525 * NB: The sequence of updating a page table followed by accesses
10526 * to the corresponding pages used in the !DMAP case is subject to
10527 * the situation described in the "AMD64 Architecture Programmer's
10528 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10529 * Coherency Considerations". Therefore, issuing the INVLPG right
10530 * after modifying the PTE bits is crucial.
10534 for (i = 0; i < count; i++) {
10535 paddr = VM_PAGE_TO_PHYS(page[i]);
10536 if (paddr >= dmaplimit) {
10539 * Slow path, since we can get page faults
10540 * while mappings are active don't pin the
10541 * thread to the CPU and instead add a global
10542 * mapping visible to all CPUs.
10544 pmap_qenter(vaddr[i], &page[i], 1);
10546 pte = vtopte(vaddr[i]);
10547 cache_bits = pmap_cache_bits(kernel_pmap,
10548 page[i]->md.pat_mode, false);
10549 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10551 pmap_invlpg(kernel_pmap, vaddr[i]);
10556 return (needs_mapping);
10560 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10568 for (i = 0; i < count; i++) {
10569 paddr = VM_PAGE_TO_PHYS(page[i]);
10570 if (paddr >= dmaplimit) {
10572 pmap_qremove(vaddr[i], 1);
10573 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10579 pmap_quick_enter_page(vm_page_t m)
10583 paddr = VM_PAGE_TO_PHYS(m);
10584 if (paddr < dmaplimit)
10585 return (PHYS_TO_DMAP(paddr));
10586 mtx_lock_spin(&qframe_mtx);
10587 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10590 * Since qframe is exclusively mapped by us, and we do not set
10591 * PG_G, we can use INVLPG here.
10595 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10596 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
10601 pmap_quick_remove_page(vm_offset_t addr)
10604 if (addr != qframe)
10606 pte_store(vtopte(qframe), 0);
10607 mtx_unlock_spin(&qframe_mtx);
10611 * Pdp pages from the large map are managed differently from either
10612 * kernel or user page table pages. They are permanently allocated at
10613 * initialization time, and their reference count is permanently set to
10614 * zero. The pml4 entries pointing to those pages are copied into
10615 * each allocated pmap.
10617 * In contrast, pd and pt pages are managed like user page table
10618 * pages. They are dynamically allocated, and their reference count
10619 * represents the number of valid entries within the page.
10622 pmap_large_map_getptp_unlocked(void)
10624 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10628 pmap_large_map_getptp(void)
10632 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10633 m = pmap_large_map_getptp_unlocked();
10635 PMAP_UNLOCK(kernel_pmap);
10637 PMAP_LOCK(kernel_pmap);
10638 /* Callers retry. */
10643 static pdp_entry_t *
10644 pmap_large_map_pdpe(vm_offset_t va)
10646 vm_pindex_t pml4_idx;
10649 pml4_idx = pmap_pml4e_index(va);
10650 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10651 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10653 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10654 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10655 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10656 "LMSPML4I %#jx lm_ents %d",
10657 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10658 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10659 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10662 static pd_entry_t *
10663 pmap_large_map_pde(vm_offset_t va)
10670 pdpe = pmap_large_map_pdpe(va);
10672 m = pmap_large_map_getptp();
10675 mphys = VM_PAGE_TO_PHYS(m);
10676 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10678 MPASS((*pdpe & X86_PG_PS) == 0);
10679 mphys = *pdpe & PG_FRAME;
10681 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10684 static pt_entry_t *
10685 pmap_large_map_pte(vm_offset_t va)
10692 pde = pmap_large_map_pde(va);
10694 m = pmap_large_map_getptp();
10697 mphys = VM_PAGE_TO_PHYS(m);
10698 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10699 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10701 MPASS((*pde & X86_PG_PS) == 0);
10702 mphys = *pde & PG_FRAME;
10704 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10708 pmap_large_map_kextract(vm_offset_t va)
10710 pdp_entry_t *pdpe, pdp;
10711 pd_entry_t *pde, pd;
10712 pt_entry_t *pte, pt;
10714 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10715 ("not largemap range %#lx", (u_long)va));
10716 pdpe = pmap_large_map_pdpe(va);
10718 KASSERT((pdp & X86_PG_V) != 0,
10719 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10720 (u_long)pdpe, pdp));
10721 if ((pdp & X86_PG_PS) != 0) {
10722 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10723 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10724 (u_long)pdpe, pdp));
10725 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10727 pde = pmap_pdpe_to_pde(pdpe, va);
10729 KASSERT((pd & X86_PG_V) != 0,
10730 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10731 if ((pd & X86_PG_PS) != 0)
10732 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10733 pte = pmap_pde_to_pte(pde, va);
10735 KASSERT((pt & X86_PG_V) != 0,
10736 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10737 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10741 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10742 vmem_addr_t *vmem_res)
10746 * Large mappings are all but static. Consequently, there
10747 * is no point in waiting for an earlier allocation to be
10750 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10751 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10755 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10756 vm_memattr_t mattr)
10761 vm_offset_t va, inc;
10762 vmem_addr_t vmem_res;
10766 if (len == 0 || spa + len < spa)
10769 /* See if DMAP can serve. */
10770 if (spa + len <= dmaplimit) {
10771 va = PHYS_TO_DMAP(spa);
10772 *addr = (void *)va;
10773 return (pmap_change_attr(va, len, mattr));
10777 * No, allocate KVA. Fit the address with best possible
10778 * alignment for superpages. Fall back to worse align if
10782 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10783 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10784 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10786 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10788 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10791 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10796 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10797 * in the pagetable to minimize flushing. No need to
10798 * invalidate TLB, since we only update invalid entries.
10800 PMAP_LOCK(kernel_pmap);
10801 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10803 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10804 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10805 pdpe = pmap_large_map_pdpe(va);
10807 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10808 X86_PG_V | X86_PG_A | pg_nx |
10809 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10811 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10812 (va & PDRMASK) == 0) {
10813 pde = pmap_large_map_pde(va);
10815 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10816 X86_PG_V | X86_PG_A | pg_nx |
10817 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10818 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10822 pte = pmap_large_map_pte(va);
10824 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10825 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10827 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10832 PMAP_UNLOCK(kernel_pmap);
10835 *addr = (void *)vmem_res;
10840 pmap_large_unmap(void *svaa, vm_size_t len)
10842 vm_offset_t sva, va;
10844 pdp_entry_t *pdpe, pdp;
10845 pd_entry_t *pde, pd;
10848 struct spglist spgf;
10850 sva = (vm_offset_t)svaa;
10851 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10852 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10856 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10857 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10858 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10859 PMAP_LOCK(kernel_pmap);
10860 for (va = sva; va < sva + len; va += inc) {
10861 pdpe = pmap_large_map_pdpe(va);
10863 KASSERT((pdp & X86_PG_V) != 0,
10864 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10865 (u_long)pdpe, pdp));
10866 if ((pdp & X86_PG_PS) != 0) {
10867 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10868 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10869 (u_long)pdpe, pdp));
10870 KASSERT((va & PDPMASK) == 0,
10871 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10872 (u_long)pdpe, pdp));
10873 KASSERT(va + NBPDP <= sva + len,
10874 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10875 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10876 (u_long)pdpe, pdp, len));
10881 pde = pmap_pdpe_to_pde(pdpe, va);
10883 KASSERT((pd & X86_PG_V) != 0,
10884 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10886 if ((pd & X86_PG_PS) != 0) {
10887 KASSERT((va & PDRMASK) == 0,
10888 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10890 KASSERT(va + NBPDR <= sva + len,
10891 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10892 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10896 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10898 if (m->ref_count == 0) {
10900 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10904 pte = pmap_pde_to_pte(pde, va);
10905 KASSERT((*pte & X86_PG_V) != 0,
10906 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10907 (u_long)pte, *pte));
10910 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10912 if (m->ref_count == 0) {
10914 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10915 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10917 if (m->ref_count == 0) {
10919 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10923 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10924 PMAP_UNLOCK(kernel_pmap);
10925 vm_page_free_pages_toq(&spgf, false);
10926 vmem_free(large_vmem, sva, len);
10930 pmap_large_map_wb_fence_mfence(void)
10937 pmap_large_map_wb_fence_atomic(void)
10940 atomic_thread_fence_seq_cst();
10944 pmap_large_map_wb_fence_nop(void)
10948 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10951 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10952 return (pmap_large_map_wb_fence_mfence);
10953 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10954 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10955 return (pmap_large_map_wb_fence_atomic);
10957 /* clflush is strongly enough ordered */
10958 return (pmap_large_map_wb_fence_nop);
10962 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10965 for (; len > 0; len -= cpu_clflush_line_size,
10966 va += cpu_clflush_line_size)
10971 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10974 for (; len > 0; len -= cpu_clflush_line_size,
10975 va += cpu_clflush_line_size)
10980 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10983 for (; len > 0; len -= cpu_clflush_line_size,
10984 va += cpu_clflush_line_size)
10989 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10993 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
10996 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
10997 return (pmap_large_map_flush_range_clwb);
10998 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
10999 return (pmap_large_map_flush_range_clflushopt);
11000 else if ((cpu_feature & CPUID_CLFSH) != 0)
11001 return (pmap_large_map_flush_range_clflush);
11003 return (pmap_large_map_flush_range_nop);
11007 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
11009 volatile u_long *pe;
11015 for (va = sva; va < eva; va += inc) {
11017 if ((amd_feature & AMDID_PAGE1GB) != 0) {
11018 pe = (volatile u_long *)pmap_large_map_pdpe(va);
11020 if ((p & X86_PG_PS) != 0)
11024 pe = (volatile u_long *)pmap_large_map_pde(va);
11026 if ((p & X86_PG_PS) != 0)
11030 pe = (volatile u_long *)pmap_large_map_pte(va);
11034 seen_other = false;
11036 if ((p & X86_PG_AVAIL1) != 0) {
11038 * Spin-wait for the end of a parallel
11045 * If we saw other write-back
11046 * occuring, we cannot rely on PG_M to
11047 * indicate state of the cache. The
11048 * PG_M bit is cleared before the
11049 * flush to avoid ignoring new writes,
11050 * and writes which are relevant for
11051 * us might happen after.
11057 if ((p & X86_PG_M) != 0 || seen_other) {
11058 if (!atomic_fcmpset_long(pe, &p,
11059 (p & ~X86_PG_M) | X86_PG_AVAIL1))
11061 * If we saw PG_M without
11062 * PG_AVAIL1, and then on the
11063 * next attempt we do not
11064 * observe either PG_M or
11065 * PG_AVAIL1, the other
11066 * write-back started after us
11067 * and finished before us. We
11068 * can rely on it doing our
11072 pmap_large_map_flush_range(va, inc);
11073 atomic_clear_long(pe, X86_PG_AVAIL1);
11082 * Write-back cache lines for the given address range.
11084 * Must be called only on the range or sub-range returned from
11085 * pmap_large_map(). Must not be called on the coalesced ranges.
11087 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
11088 * instructions support.
11091 pmap_large_map_wb(void *svap, vm_size_t len)
11093 vm_offset_t eva, sva;
11095 sva = (vm_offset_t)svap;
11097 pmap_large_map_wb_fence();
11098 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
11099 pmap_large_map_flush_range(sva, len);
11101 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
11102 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11103 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11104 pmap_large_map_wb_large(sva, eva);
11106 pmap_large_map_wb_fence();
11110 pmap_pti_alloc_page(void)
11114 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11115 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11120 pmap_pti_free_page(vm_page_t m)
11122 if (!vm_page_unwire_noq(m))
11124 vm_page_xbusy_claim(m);
11125 vm_page_free_zero(m);
11130 pmap_pti_init(void)
11139 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11140 VM_OBJECT_WLOCK(pti_obj);
11141 pml4_pg = pmap_pti_alloc_page();
11142 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11143 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11144 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11145 pdpe = pmap_pti_pdpe(va);
11146 pmap_pti_wire_pte(pdpe);
11148 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11149 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11150 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11151 sizeof(struct gate_descriptor) * NIDT, false);
11153 /* Doublefault stack IST 1 */
11154 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11155 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11156 /* NMI stack IST 2 */
11157 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11158 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11159 /* MC# stack IST 3 */
11160 va = __pcpu[i].pc_common_tss.tss_ist3 +
11161 sizeof(struct nmi_pcpu);
11162 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11163 /* DB# stack IST 4 */
11164 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11165 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11167 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11169 pti_finalized = true;
11170 VM_OBJECT_WUNLOCK(pti_obj);
11174 pmap_cpu_init(void *arg __unused)
11176 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11179 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11181 static pdp_entry_t *
11182 pmap_pti_pdpe(vm_offset_t va)
11184 pml4_entry_t *pml4e;
11187 vm_pindex_t pml4_idx;
11190 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11192 pml4_idx = pmap_pml4e_index(va);
11193 pml4e = &pti_pml4[pml4_idx];
11197 panic("pml4 alloc after finalization\n");
11198 m = pmap_pti_alloc_page();
11200 pmap_pti_free_page(m);
11201 mphys = *pml4e & ~PAGE_MASK;
11203 mphys = VM_PAGE_TO_PHYS(m);
11204 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11207 mphys = *pml4e & ~PAGE_MASK;
11209 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11214 pmap_pti_wire_pte(void *pte)
11218 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11219 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11224 pmap_pti_unwire_pde(void *pde, bool only_ref)
11228 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11229 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11230 MPASS(only_ref || m->ref_count > 1);
11231 pmap_pti_free_page(m);
11235 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11240 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11241 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11242 if (pmap_pti_free_page(m)) {
11243 pde = pmap_pti_pde(va);
11244 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11246 pmap_pti_unwire_pde(pde, false);
11250 static pd_entry_t *
11251 pmap_pti_pde(vm_offset_t va)
11256 vm_pindex_t pd_idx;
11259 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11261 pdpe = pmap_pti_pdpe(va);
11263 m = pmap_pti_alloc_page();
11265 pmap_pti_free_page(m);
11266 MPASS((*pdpe & X86_PG_PS) == 0);
11267 mphys = *pdpe & ~PAGE_MASK;
11269 mphys = VM_PAGE_TO_PHYS(m);
11270 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11273 MPASS((*pdpe & X86_PG_PS) == 0);
11274 mphys = *pdpe & ~PAGE_MASK;
11277 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11278 pd_idx = pmap_pde_index(va);
11283 static pt_entry_t *
11284 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11291 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11293 pde = pmap_pti_pde(va);
11294 if (unwire_pde != NULL) {
11295 *unwire_pde = true;
11296 pmap_pti_wire_pte(pde);
11299 m = pmap_pti_alloc_page();
11301 pmap_pti_free_page(m);
11302 MPASS((*pde & X86_PG_PS) == 0);
11303 mphys = *pde & ~(PAGE_MASK | pg_nx);
11305 mphys = VM_PAGE_TO_PHYS(m);
11306 *pde = mphys | X86_PG_RW | X86_PG_V;
11307 if (unwire_pde != NULL)
11308 *unwire_pde = false;
11311 MPASS((*pde & X86_PG_PS) == 0);
11312 mphys = *pde & ~(PAGE_MASK | pg_nx);
11315 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11316 pte += pmap_pte_index(va);
11322 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11326 pt_entry_t *pte, ptev;
11329 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11331 sva = trunc_page(sva);
11332 MPASS(sva > VM_MAXUSER_ADDRESS);
11333 eva = round_page(eva);
11335 for (; sva < eva; sva += PAGE_SIZE) {
11336 pte = pmap_pti_pte(sva, &unwire_pde);
11337 pa = pmap_kextract(sva);
11338 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11339 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11340 VM_MEMATTR_DEFAULT, FALSE);
11342 pte_store(pte, ptev);
11343 pmap_pti_wire_pte(pte);
11345 KASSERT(!pti_finalized,
11346 ("pti overlap after fin %#lx %#lx %#lx",
11348 KASSERT(*pte == ptev,
11349 ("pti non-identical pte after fin %#lx %#lx %#lx",
11353 pde = pmap_pti_pde(sva);
11354 pmap_pti_unwire_pde(pde, true);
11360 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11365 VM_OBJECT_WLOCK(pti_obj);
11366 pmap_pti_add_kva_locked(sva, eva, exec);
11367 VM_OBJECT_WUNLOCK(pti_obj);
11371 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11378 sva = rounddown2(sva, PAGE_SIZE);
11379 MPASS(sva > VM_MAXUSER_ADDRESS);
11380 eva = roundup2(eva, PAGE_SIZE);
11382 VM_OBJECT_WLOCK(pti_obj);
11383 for (va = sva; va < eva; va += PAGE_SIZE) {
11384 pte = pmap_pti_pte(va, NULL);
11385 KASSERT((*pte & X86_PG_V) != 0,
11386 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11387 (u_long)pte, *pte));
11389 pmap_pti_unwire_pte(pte, va);
11391 pmap_invalidate_range(kernel_pmap, sva, eva);
11392 VM_OBJECT_WUNLOCK(pti_obj);
11396 pkru_dup_range(void *ctx __unused, void *data)
11398 struct pmap_pkru_range *node, *new_node;
11400 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11401 if (new_node == NULL)
11404 memcpy(new_node, node, sizeof(*node));
11409 pkru_free_range(void *ctx __unused, void *node)
11412 uma_zfree(pmap_pkru_ranges_zone, node);
11416 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11419 struct pmap_pkru_range *ppr;
11422 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11423 MPASS(pmap->pm_type == PT_X86);
11424 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11425 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11426 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11428 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11431 ppr->pkru_keyidx = keyidx;
11432 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11433 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11435 uma_zfree(pmap_pkru_ranges_zone, ppr);
11440 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11443 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11444 MPASS(pmap->pm_type == PT_X86);
11445 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11446 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11450 pmap_pkru_deassign_all(pmap_t pmap)
11453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11454 if (pmap->pm_type == PT_X86 &&
11455 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11456 rangeset_remove_all(&pmap->pm_pkru);
11460 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11462 struct pmap_pkru_range *ppr, *prev_ppr;
11465 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11466 if (pmap->pm_type != PT_X86 ||
11467 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11468 sva >= VM_MAXUSER_ADDRESS)
11470 MPASS(eva <= VM_MAXUSER_ADDRESS);
11471 for (va = sva; va < eva; prev_ppr = ppr) {
11472 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11475 else if ((ppr == NULL) ^ (prev_ppr == NULL))
11481 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
11483 va = ppr->pkru_rs_el.re_end;
11489 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11491 struct pmap_pkru_range *ppr;
11493 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11494 if (pmap->pm_type != PT_X86 ||
11495 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11496 va >= VM_MAXUSER_ADDRESS)
11498 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11500 return (X86_PG_PKU(ppr->pkru_keyidx));
11505 pred_pkru_on_remove(void *ctx __unused, void *r)
11507 struct pmap_pkru_range *ppr;
11510 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11514 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11517 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11518 if (pmap->pm_type == PT_X86 &&
11519 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11520 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11521 pred_pkru_on_remove);
11526 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11529 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11530 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11531 MPASS(dst_pmap->pm_type == PT_X86);
11532 MPASS(src_pmap->pm_type == PT_X86);
11533 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11534 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11536 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11540 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11543 pml4_entry_t *pml4e;
11545 pd_entry_t newpde, ptpaddr, *pde;
11546 pt_entry_t newpte, *ptep, pte;
11547 vm_offset_t va, va_next;
11550 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11551 MPASS(pmap->pm_type == PT_X86);
11552 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11554 for (changed = false, va = sva; va < eva; va = va_next) {
11555 pml4e = pmap_pml4e(pmap, va);
11556 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11557 va_next = (va + NBPML4) & ~PML4MASK;
11563 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11564 if ((*pdpe & X86_PG_V) == 0) {
11565 va_next = (va + NBPDP) & ~PDPMASK;
11571 va_next = (va + NBPDR) & ~PDRMASK;
11575 pde = pmap_pdpe_to_pde(pdpe, va);
11580 MPASS((ptpaddr & X86_PG_V) != 0);
11581 if ((ptpaddr & PG_PS) != 0) {
11582 if (va + NBPDR == va_next && eva >= va_next) {
11583 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11584 X86_PG_PKU(keyidx);
11585 if (newpde != ptpaddr) {
11590 } else if (!pmap_demote_pde(pmap, pde, va)) {
11598 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11599 ptep++, va += PAGE_SIZE) {
11601 if ((pte & X86_PG_V) == 0)
11603 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11604 if (newpte != pte) {
11611 pmap_invalidate_range(pmap, sva, eva);
11615 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11616 u_int keyidx, int flags)
11619 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11620 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11622 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11624 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11630 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11635 sva = trunc_page(sva);
11636 eva = round_page(eva);
11637 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11642 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11644 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11646 if (error != ENOMEM)
11654 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11658 sva = trunc_page(sva);
11659 eva = round_page(eva);
11660 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11665 error = pmap_pkru_deassign(pmap, sva, eva);
11667 pmap_pkru_update_range(pmap, sva, eva, 0);
11669 if (error != ENOMEM)
11676 #if defined(KASAN) || defined(KMSAN)
11679 * Reserve enough memory to:
11680 * 1) allocate PDP pages for the shadow map(s),
11681 * 2) shadow the boot stack of KSTACK_PAGES pages,
11682 * so we need one PD page, one or two PT pages, and KSTACK_PAGES shadow pages
11686 #define SAN_EARLY_PAGES \
11687 (NKASANPML4E + 1 + 2 + howmany(KSTACK_PAGES, KASAN_SHADOW_SCALE))
11689 #define SAN_EARLY_PAGES \
11690 (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * (1 + 2 + KSTACK_PAGES))
11693 static uint64_t __nosanitizeaddress __nosanitizememory
11694 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11696 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11697 static size_t offset = 0;
11700 if (offset == sizeof(data)) {
11701 panic("%s: ran out of memory for the bootstrap shadow map",
11705 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11706 offset += PAGE_SIZE;
11711 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11712 * is currently only used to shadow the temporary boot stack set up by locore.
11714 static void __nosanitizeaddress __nosanitizememory
11715 pmap_san_enter_early(vm_offset_t va)
11717 static bool first = true;
11718 pml4_entry_t *pml4e;
11722 uint64_t cr3, pa, base;
11725 base = amd64_loadaddr();
11730 * If this the first call, we need to allocate new PML4Es for
11731 * the bootstrap shadow map(s). We don't know how the PML4 page
11732 * was initialized by the boot loader, so we can't simply test
11733 * whether the shadow map's PML4Es are zero.
11737 for (i = 0; i < NKASANPML4E; i++) {
11738 pa = pmap_san_enter_early_alloc_4k(base);
11740 pml4e = (pml4_entry_t *)cr3 +
11741 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11742 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11745 for (i = 0; i < NKMSANORIGPML4E; i++) {
11746 pa = pmap_san_enter_early_alloc_4k(base);
11748 pml4e = (pml4_entry_t *)cr3 +
11749 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11751 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11753 for (i = 0; i < NKMSANSHADPML4E; i++) {
11754 pa = pmap_san_enter_early_alloc_4k(base);
11756 pml4e = (pml4_entry_t *)cr3 +
11757 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11759 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11763 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11764 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11766 pa = pmap_san_enter_early_alloc_4k(base);
11767 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11769 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11771 pa = pmap_san_enter_early_alloc_4k(base);
11772 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11774 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11776 panic("%s: PTE for %#lx is already initialized", __func__, va);
11777 pa = pmap_san_enter_early_alloc_4k(base);
11778 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11782 pmap_san_enter_alloc_4k(void)
11786 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11789 panic("%s: no memory to grow shadow map", __func__);
11794 pmap_san_enter_alloc_2m(void)
11796 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11797 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11801 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11802 * pages when possible.
11804 void __nosanitizeaddress __nosanitizememory
11805 pmap_san_enter(vm_offset_t va)
11812 if (kernphys == 0) {
11814 * We're creating a temporary shadow map for the boot stack.
11816 pmap_san_enter_early(va);
11820 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11822 pdpe = pmap_pdpe(kernel_pmap, va);
11823 if ((*pdpe & X86_PG_V) == 0) {
11824 m = pmap_san_enter_alloc_4k();
11825 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11828 pde = pmap_pdpe_to_pde(pdpe, va);
11829 if ((*pde & X86_PG_V) == 0) {
11830 m = pmap_san_enter_alloc_2m();
11832 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11833 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11835 m = pmap_san_enter_alloc_4k();
11836 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11840 if ((*pde & X86_PG_PS) != 0)
11842 pte = pmap_pde_to_pte(pde, va);
11843 if ((*pte & X86_PG_V) != 0)
11845 m = pmap_san_enter_alloc_4k();
11846 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11847 X86_PG_M | X86_PG_A | pg_nx);
11852 * Track a range of the kernel's virtual address space that is contiguous
11853 * in various mapping attributes.
11855 struct pmap_kernel_map_range {
11864 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11870 if (eva <= range->sva)
11873 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11874 for (i = 0; i < PAT_INDEX_SIZE; i++)
11875 if (pat_index[i] == pat_idx)
11879 case PAT_WRITE_BACK:
11882 case PAT_WRITE_THROUGH:
11885 case PAT_UNCACHEABLE:
11891 case PAT_WRITE_PROTECTED:
11894 case PAT_WRITE_COMBINING:
11898 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11899 __func__, pat_idx, range->sva, eva);
11904 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11906 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11907 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11908 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11909 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11910 mode, range->pdpes, range->pdes, range->ptes);
11912 /* Reset to sentinel value. */
11913 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11914 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11915 NPDEPG - 1, NPTEPG - 1);
11919 * Determine whether the attributes specified by a page table entry match those
11920 * being tracked by the current range. This is not quite as simple as a direct
11921 * flag comparison since some PAT modes have multiple representations.
11924 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11926 pt_entry_t diff, mask;
11928 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11929 diff = (range->attrs ^ attrs) & mask;
11932 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11933 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11934 pmap_pat_index(kernel_pmap, attrs, true))
11940 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11944 memset(range, 0, sizeof(*range));
11946 range->attrs = attrs;
11950 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11951 * those of the current run, dump the address range and its attributes, and
11955 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11956 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11961 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11963 attrs |= pdpe & pg_nx;
11964 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11965 if ((pdpe & PG_PS) != 0) {
11966 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11967 } else if (pde != 0) {
11968 attrs |= pde & pg_nx;
11969 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11971 if ((pde & PG_PS) != 0) {
11972 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11973 } else if (pte != 0) {
11974 attrs |= pte & pg_nx;
11975 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11976 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11978 /* Canonicalize by always using the PDE PAT bit. */
11979 if ((attrs & X86_PG_PTE_PAT) != 0)
11980 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11983 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11984 sysctl_kmaps_dump(sb, range, va);
11985 sysctl_kmaps_reinit(range, va, attrs);
11990 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
11992 struct pmap_kernel_map_range range;
11993 struct sbuf sbuf, *sb;
11994 pml4_entry_t pml4e;
11995 pdp_entry_t *pdp, pdpe;
11996 pd_entry_t *pd, pde;
11997 pt_entry_t *pt, pte;
12000 int error, i, j, k, l;
12002 error = sysctl_wire_old_buffer(req, 0);
12006 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
12008 /* Sentinel value. */
12009 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
12010 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
12011 NPDEPG - 1, NPTEPG - 1);
12014 * Iterate over the kernel page tables without holding the kernel pmap
12015 * lock. Outside of the large map, kernel page table pages are never
12016 * freed, so at worst we will observe inconsistencies in the output.
12017 * Within the large map, ensure that PDP and PD page addresses are
12018 * valid before descending.
12020 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
12023 sbuf_printf(sb, "\nRecursive map:\n");
12026 sbuf_printf(sb, "\nDirect map:\n");
12030 sbuf_printf(sb, "\nKASAN shadow map:\n");
12034 case KMSANSHADPML4I:
12035 sbuf_printf(sb, "\nKMSAN shadow map:\n");
12037 case KMSANORIGPML4I:
12038 sbuf_printf(sb, "\nKMSAN origin map:\n");
12042 sbuf_printf(sb, "\nKernel map:\n");
12045 sbuf_printf(sb, "\nLarge map:\n");
12049 /* Convert to canonical form. */
12050 if (sva == 1ul << 47)
12054 pml4e = kernel_pml4[i];
12055 if ((pml4e & X86_PG_V) == 0) {
12056 sva = rounddown2(sva, NBPML4);
12057 sysctl_kmaps_dump(sb, &range, sva);
12061 pa = pml4e & PG_FRAME;
12062 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
12064 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
12066 if ((pdpe & X86_PG_V) == 0) {
12067 sva = rounddown2(sva, NBPDP);
12068 sysctl_kmaps_dump(sb, &range, sva);
12072 pa = pdpe & PG_FRAME;
12073 if ((pdpe & PG_PS) != 0) {
12074 sva = rounddown2(sva, NBPDP);
12075 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
12081 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12082 vm_phys_paddr_to_vm_page(pa) == NULL) {
12084 * Page table pages for the large map may be
12085 * freed. Validate the next-level address
12086 * before descending.
12090 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
12092 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
12094 if ((pde & X86_PG_V) == 0) {
12095 sva = rounddown2(sva, NBPDR);
12096 sysctl_kmaps_dump(sb, &range, sva);
12100 pa = pde & PG_FRAME;
12101 if ((pde & PG_PS) != 0) {
12102 sva = rounddown2(sva, NBPDR);
12103 sysctl_kmaps_check(sb, &range, sva,
12104 pml4e, pdpe, pde, 0);
12109 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12110 vm_phys_paddr_to_vm_page(pa) == NULL) {
12112 * Page table pages for the large map
12113 * may be freed. Validate the
12114 * next-level address before descending.
12118 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12120 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12121 sva += PAGE_SIZE) {
12123 if ((pte & X86_PG_V) == 0) {
12124 sysctl_kmaps_dump(sb, &range,
12128 sysctl_kmaps_check(sb, &range, sva,
12129 pml4e, pdpe, pde, pte);
12136 error = sbuf_finish(sb);
12140 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12141 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12142 NULL, 0, sysctl_kmaps, "A",
12143 "Dump kernel address layout");
12146 DB_SHOW_COMMAND(pte, pmap_print_pte)
12149 pml5_entry_t *pml5;
12150 pml4_entry_t *pml4;
12153 pt_entry_t *pte, PG_V;
12157 db_printf("show pte addr\n");
12160 va = (vm_offset_t)addr;
12162 if (kdb_thread != NULL)
12163 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12165 pmap = PCPU_GET(curpmap);
12167 PG_V = pmap_valid_bit(pmap);
12168 db_printf("VA 0x%016lx", va);
12170 if (pmap_is_la57(pmap)) {
12171 pml5 = pmap_pml5e(pmap, va);
12172 db_printf(" pml5e 0x%016lx", *pml5);
12173 if ((*pml5 & PG_V) == 0) {
12177 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12179 pml4 = pmap_pml4e(pmap, va);
12181 db_printf(" pml4e 0x%016lx", *pml4);
12182 if ((*pml4 & PG_V) == 0) {
12186 pdp = pmap_pml4e_to_pdpe(pml4, va);
12187 db_printf(" pdpe 0x%016lx", *pdp);
12188 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12192 pde = pmap_pdpe_to_pde(pdp, va);
12193 db_printf(" pde 0x%016lx", *pde);
12194 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12198 pte = pmap_pde_to_pte(pde, va);
12199 db_printf(" pte 0x%016lx\n", *pte);
12202 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12207 a = (vm_paddr_t)addr;
12208 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12210 db_printf("show phys2dmap addr\n");
12215 ptpages_show_page(int level, int idx, vm_page_t pg)
12217 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12218 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12222 ptpages_show_complain(int level, int idx, uint64_t pte)
12224 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12228 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12230 vm_page_t pg3, pg2, pg1;
12231 pml4_entry_t *pml4;
12236 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12237 for (i4 = 0; i4 < num_entries; i4++) {
12238 if ((pml4[i4] & PG_V) == 0)
12240 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12242 ptpages_show_complain(3, i4, pml4[i4]);
12245 ptpages_show_page(3, i4, pg3);
12246 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12247 for (i3 = 0; i3 < NPDPEPG; i3++) {
12248 if ((pdp[i3] & PG_V) == 0)
12250 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12252 ptpages_show_complain(2, i3, pdp[i3]);
12255 ptpages_show_page(2, i3, pg2);
12256 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12257 for (i2 = 0; i2 < NPDEPG; i2++) {
12258 if ((pd[i2] & PG_V) == 0)
12260 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12262 ptpages_show_complain(1, i2, pd[i2]);
12265 ptpages_show_page(1, i2, pg1);
12271 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12275 pml5_entry_t *pml5;
12280 pmap = (pmap_t)addr;
12282 pmap = PCPU_GET(curpmap);
12284 PG_V = pmap_valid_bit(pmap);
12286 if (pmap_is_la57(pmap)) {
12287 pml5 = pmap->pm_pmltop;
12288 for (i5 = 0; i5 < NUPML5E; i5++) {
12289 if ((pml5[i5] & PG_V) == 0)
12291 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12293 ptpages_show_complain(4, i5, pml5[i5]);
12296 ptpages_show_page(4, i5, pg);
12297 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12300 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12301 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);