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 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2349 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2352 return (pmap->pm_type != PT_EPT || !executable ||
2353 !pmap_allow_2m_x_ept);
2358 pmap_init_pv_table(void)
2360 struct pmap_large_md_page *pvd;
2362 long start, end, highest, pv_npg;
2363 int domain, i, j, pages;
2366 * For correctness we depend on the size being evenly divisible into a
2367 * page. As a tradeoff between performance and total memory use, the
2368 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2369 * avoids false-sharing, but not being 128 bytes potentially allows for
2370 * avoidable traffic due to adjacent cacheline prefetcher.
2372 * Assert the size so that accidental changes fail to compile.
2374 CTASSERT((sizeof(*pvd) == 64));
2377 * Calculate the size of the array.
2379 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2380 pv_npg = howmany(pmap_last_pa, NBPDR);
2381 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2383 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2384 if (pv_table == NULL)
2385 panic("%s: kva_alloc failed\n", __func__);
2388 * Iterate physical segments to allocate space for respective pages.
2392 for (i = 0; i < vm_phys_nsegs; i++) {
2393 end = vm_phys_segs[i].end / NBPDR;
2394 domain = vm_phys_segs[i].domain;
2399 start = highest + 1;
2400 pvd = &pv_table[start];
2402 pages = end - start + 1;
2403 s = round_page(pages * sizeof(*pvd));
2404 highest = start + (s / sizeof(*pvd)) - 1;
2406 for (j = 0; j < s; j += PAGE_SIZE) {
2407 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2409 panic("failed to allocate PV table page");
2410 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2413 for (j = 0; j < s / sizeof(*pvd); j++) {
2414 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2415 TAILQ_INIT(&pvd->pv_page.pv_list);
2416 pvd->pv_page.pv_gen = 0;
2417 pvd->pv_page.pat_mode = 0;
2418 pvd->pv_invl_gen = 0;
2422 pvd = &pv_dummy_large;
2423 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2424 TAILQ_INIT(&pvd->pv_page.pv_list);
2425 pvd->pv_page.pv_gen = 0;
2426 pvd->pv_page.pat_mode = 0;
2427 pvd->pv_invl_gen = 0;
2431 pmap_init_pv_table(void)
2437 * Initialize the pool of pv list locks.
2439 for (i = 0; i < NPV_LIST_LOCKS; i++)
2440 rw_init(&pv_list_locks[i], "pmap pv list");
2443 * Calculate the size of the pv head table for superpages.
2445 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2448 * Allocate memory for the pv head table for superpages.
2450 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2452 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2453 for (i = 0; i < pv_npg; i++)
2454 TAILQ_INIT(&pv_table[i].pv_list);
2455 TAILQ_INIT(&pv_dummy.pv_list);
2460 * Initialize the pmap module.
2461 * Called by vm_init, to initialize any structures that the pmap
2462 * system needs to map virtual memory.
2467 struct pmap_preinit_mapping *ppim;
2469 int error, i, ret, skz63;
2471 /* L1TF, reserve page @0 unconditionally */
2472 vm_page_blacklist_add(0, bootverbose);
2474 /* Detect bare-metal Skylake Server and Skylake-X. */
2475 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2476 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2478 * Skylake-X errata SKZ63. Processor May Hang When
2479 * Executing Code In an HLE Transaction Region between
2480 * 40000000H and 403FFFFFH.
2482 * Mark the pages in the range as preallocated. It
2483 * seems to be impossible to distinguish between
2484 * Skylake Server and Skylake X.
2487 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2490 printf("SKZ63: skipping 4M RAM starting "
2491 "at physical 1G\n");
2492 for (i = 0; i < atop(0x400000); i++) {
2493 ret = vm_page_blacklist_add(0x40000000 +
2495 if (!ret && bootverbose)
2496 printf("page at %#lx already used\n",
2497 0x40000000 + ptoa(i));
2503 pmap_allow_2m_x_ept_recalculate();
2506 * Initialize the vm page array entries for the kernel pmap's
2509 PMAP_LOCK(kernel_pmap);
2510 for (i = 0; i < nkpt; i++) {
2511 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2512 KASSERT(mpte >= vm_page_array &&
2513 mpte < &vm_page_array[vm_page_array_size],
2514 ("pmap_init: page table page is out of range"));
2515 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2516 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2517 mpte->ref_count = 1;
2520 * Collect the page table pages that were replaced by a 2MB
2521 * page in create_pagetables(). They are zero filled.
2524 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2525 pmap_insert_pt_page(kernel_pmap, mpte, false, false))
2526 panic("pmap_init: pmap_insert_pt_page failed");
2528 PMAP_UNLOCK(kernel_pmap);
2532 * If the kernel is running on a virtual machine, then it must assume
2533 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2534 * be prepared for the hypervisor changing the vendor and family that
2535 * are reported by CPUID. Consequently, the workaround for AMD Family
2536 * 10h Erratum 383 is enabled if the processor's feature set does not
2537 * include at least one feature that is only supported by older Intel
2538 * or newer AMD processors.
2540 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2541 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2542 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2544 workaround_erratum383 = 1;
2547 * Are large page mappings enabled?
2549 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2550 if (pg_ps_enabled) {
2551 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2552 ("pmap_init: can't assign to pagesizes[1]"));
2553 pagesizes[1] = NBPDR;
2554 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2555 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2556 ("pmap_init: can't assign to pagesizes[2]"));
2557 pagesizes[2] = NBPDP;
2562 * Initialize pv chunk lists.
2564 for (i = 0; i < PMAP_MEMDOM; i++) {
2565 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2566 TAILQ_INIT(&pv_chunks[i].pvc_list);
2568 pmap_init_pv_table();
2570 pmap_initialized = 1;
2571 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2572 ppim = pmap_preinit_mapping + i;
2575 /* Make the direct map consistent */
2576 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2577 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2578 ppim->sz, ppim->mode);
2582 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2583 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2586 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2587 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2588 (vmem_addr_t *)&qframe);
2590 panic("qframe allocation failed");
2593 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2594 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2595 lm_ents = LMEPML4I - LMSPML4I + 1;
2597 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2599 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2600 lm_ents, KMSANORIGPML4I - LMSPML4I);
2601 lm_ents = KMSANORIGPML4I - LMSPML4I;
2605 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2606 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2608 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2609 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2610 if (large_vmem == NULL) {
2611 printf("pmap: cannot create large map\n");
2614 for (i = 0; i < lm_ents; i++) {
2615 m = pmap_large_map_getptp_unlocked();
2617 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2618 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2624 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2625 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2626 "Maximum number of PML4 entries for use by large map (tunable). "
2627 "Each entry corresponds to 512GB of address space.");
2629 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2630 "2MB page mapping counters");
2632 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2633 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2634 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2636 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2637 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2638 &pmap_pde_mappings, "2MB page mappings");
2640 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2641 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2642 &pmap_pde_p_failures, "2MB page promotion failures");
2644 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2645 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2646 &pmap_pde_promotions, "2MB page promotions");
2648 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2649 "1GB page mapping counters");
2651 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2652 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2653 &pmap_pdpe_demotions, "1GB page demotions");
2655 /***************************************************
2656 * Low level helper routines.....
2657 ***************************************************/
2660 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2662 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2664 switch (pmap->pm_type) {
2667 /* Verify that both PAT bits are not set at the same time */
2668 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2669 ("Invalid PAT bits in entry %#lx", entry));
2671 /* Swap the PAT bits if one of them is set */
2672 if ((entry & x86_pat_bits) != 0)
2673 entry ^= x86_pat_bits;
2677 * Nothing to do - the memory attributes are represented
2678 * the same way for regular pages and superpages.
2682 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2689 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2692 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2693 pat_index[(int)mode] >= 0);
2697 * Determine the appropriate bits to set in a PTE or PDE for a specified
2701 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2703 int cache_bits, pat_flag, pat_idx;
2705 if (!pmap_is_valid_memattr(pmap, mode))
2706 panic("Unknown caching mode %d\n", mode);
2708 switch (pmap->pm_type) {
2711 /* The PAT bit is different for PTE's and PDE's. */
2712 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2714 /* Map the caching mode to a PAT index. */
2715 pat_idx = pat_index[mode];
2717 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2720 cache_bits |= pat_flag;
2722 cache_bits |= PG_NC_PCD;
2724 cache_bits |= PG_NC_PWT;
2728 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2732 panic("unsupported pmap type %d", pmap->pm_type);
2735 return (cache_bits);
2739 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2743 switch (pmap->pm_type) {
2746 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2749 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2752 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2759 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2761 int pat_flag, pat_idx;
2764 switch (pmap->pm_type) {
2767 /* The PAT bit is different for PTE's and PDE's. */
2768 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2770 if ((pte & pat_flag) != 0)
2772 if ((pte & PG_NC_PCD) != 0)
2774 if ((pte & PG_NC_PWT) != 0)
2778 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2779 panic("EPT PTE %#lx has no PAT memory type", pte);
2780 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2784 /* See pmap_init_pat(). */
2794 pmap_ps_enabled(pmap_t pmap)
2797 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2801 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2804 switch (pmap->pm_type) {
2811 * This is a little bogus since the generation number is
2812 * supposed to be bumped up when a region of the address
2813 * space is invalidated in the page tables.
2815 * In this case the old PDE entry is valid but yet we want
2816 * to make sure that any mappings using the old entry are
2817 * invalidated in the TLB.
2819 * The reason this works as expected is because we rendezvous
2820 * "all" host cpus and force any vcpu context to exit as a
2823 atomic_add_long(&pmap->pm_eptgen, 1);
2826 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2828 pde_store(pde, newpde);
2832 * After changing the page size for the specified virtual address in the page
2833 * table, flush the corresponding entries from the processor's TLB. Only the
2834 * calling processor's TLB is affected.
2836 * The calling thread must be pinned to a processor.
2839 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2843 if (pmap_type_guest(pmap))
2846 KASSERT(pmap->pm_type == PT_X86,
2847 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2849 PG_G = pmap_global_bit(pmap);
2851 if ((newpde & PG_PS) == 0)
2852 /* Demotion: flush a specific 2MB page mapping. */
2853 pmap_invlpg(pmap, va);
2854 else if ((newpde & PG_G) == 0)
2856 * Promotion: flush every 4KB page mapping from the TLB
2857 * because there are too many to flush individually.
2862 * Promotion: flush every 4KB page mapping from the TLB,
2863 * including any global (PG_G) mappings.
2870 * The amd64 pmap uses different approaches to TLB invalidation
2871 * depending on the kernel configuration, available hardware features,
2872 * and known hardware errata. The kernel configuration option that
2873 * has the greatest operational impact on TLB invalidation is PTI,
2874 * which is enabled automatically on affected Intel CPUs. The most
2875 * impactful hardware features are first PCID, and then INVPCID
2876 * instruction presence. PCID usage is quite different for PTI
2879 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2880 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2881 * space is served by two page tables, user and kernel. The user
2882 * page table only maps user space and a kernel trampoline. The
2883 * kernel trampoline includes the entirety of the kernel text but
2884 * only the kernel data that is needed to switch from user to kernel
2885 * mode. The kernel page table maps the user and kernel address
2886 * spaces in their entirety. It is identical to the per-process
2887 * page table used in non-PTI mode.
2889 * User page tables are only used when the CPU is in user mode.
2890 * Consequently, some TLB invalidations can be postponed until the
2891 * switch from kernel to user mode. In contrast, the user
2892 * space part of the kernel page table is used for copyout(9), so
2893 * TLB invalidations on this page table cannot be similarly postponed.
2895 * The existence of a user mode page table for the given pmap is
2896 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2897 * which case pm_ucr3 contains the %cr3 register value for the user
2898 * mode page table's root.
2900 * * The pm_active bitmask indicates which CPUs currently have the
2901 * pmap active. A CPU's bit is set on context switch to the pmap, and
2902 * cleared on switching off this CPU. For the kernel page table,
2903 * the pm_active field is immutable and contains all CPUs. The
2904 * kernel page table is always logically active on every processor,
2905 * but not necessarily in use by the hardware, e.g., in PTI mode.
2907 * When requesting invalidation of virtual addresses with
2908 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2909 * all CPUs recorded as active in pm_active. Updates to and reads
2910 * from pm_active are not synchronized, and so they may race with
2911 * each other. Shootdown handlers are prepared to handle the race.
2913 * * PCID is an optional feature of the long mode x86 MMU where TLB
2914 * entries are tagged with the 'Process ID' of the address space
2915 * they belong to. This feature provides a limited namespace for
2916 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2919 * Allocation of a PCID to a pmap is done by an algorithm described
2920 * in section 15.12, "Other TLB Consistency Algorithms", of
2921 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2922 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2923 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2924 * the CPU is about to start caching TLB entries from a pmap,
2925 * i.e., on the context switch that activates the pmap on the CPU.
2927 * The PCID allocator maintains a per-CPU, per-pmap generation
2928 * count, pm_gen, which is incremented each time a new PCID is
2929 * allocated. On TLB invalidation, the generation counters for the
2930 * pmap are zeroed, which signals the context switch code that the
2931 * previously allocated PCID is no longer valid. Effectively,
2932 * zeroing any of these counters triggers a TLB shootdown for the
2933 * given CPU/address space, due to the allocation of a new PCID.
2935 * Zeroing can be performed remotely. Consequently, if a pmap is
2936 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2937 * be initiated by an ordinary memory access to reset the target
2938 * CPU's generation count within the pmap. The CPU initiating the
2939 * TLB shootdown does not need to send an IPI to the target CPU.
2941 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2942 * for complete (kernel) page tables, and PCIDs for user mode page
2943 * tables. A user PCID value is obtained from the kernel PCID value
2944 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2946 * User space page tables are activated on return to user mode, by
2947 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2948 * clearing bit 63 of the loaded ucr3, this effectively causes
2949 * complete invalidation of the user mode TLB entries for the
2950 * current pmap. In which case, local invalidations of individual
2951 * pages in the user page table are skipped.
2953 * * Local invalidation, all modes. If the requested invalidation is
2954 * for a specific address or the total invalidation of a currently
2955 * active pmap, then the TLB is flushed using INVLPG for a kernel
2956 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2957 * user space page table(s).
2959 * If the INVPCID instruction is available, it is used to flush user
2960 * entries from the kernel page table.
2962 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2963 * entries for the given page that either match the current PCID or
2964 * are global. Since TLB entries for the same page under different
2965 * PCIDs are unaffected, kernel pages which reside in all address
2966 * spaces could be problematic. We avoid the problem by creating
2967 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2970 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2971 * address space, all other 4095 PCIDs are used for user mode spaces
2972 * as described above. A context switch allocates a new PCID if
2973 * the recorded PCID is zero or the recorded generation does not match
2974 * the CPU's generation, effectively flushing the TLB for this address space.
2975 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2976 * local user page: INVLPG
2977 * local kernel page: INVLPG
2978 * local user total: INVPCID(CTX)
2979 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2980 * remote user page, inactive pmap: zero pm_gen
2981 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2982 * (Both actions are required to handle the aforementioned pm_active races.)
2983 * remote kernel page: IPI:INVLPG
2984 * remote user total, inactive pmap: zero pm_gen
2985 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2987 * (See note above about pm_active races.)
2988 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2990 * PTI enabled, PCID present.
2991 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2993 * local kernel page: INVLPG
2994 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
2995 * on loading UCR3 into %cr3 for upt
2996 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2997 * remote user page, inactive pmap: zero pm_gen
2998 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
2999 * INVPCID(ADDR) for upt)
3000 * remote kernel page: IPI:INVLPG
3001 * remote user total, inactive pmap: zero pm_gen
3002 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
3003 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
3004 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
3007 * local user page: INVLPG
3008 * local kernel page: INVLPG
3009 * local user total: reload %cr3
3010 * local kernel total: invltlb_glob()
3011 * remote user page, inactive pmap: -
3012 * remote user page, active pmap: IPI:INVLPG
3013 * remote kernel page: IPI:INVLPG
3014 * remote user total, inactive pmap: -
3015 * remote user total, active pmap: IPI:(reload %cr3)
3016 * remote kernel total: IPI:invltlb_glob()
3017 * Since on return to user mode, the reload of %cr3 with ucr3 causes
3018 * TLB invalidation, no specific action is required for user page table.
3020 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
3026 * Interrupt the cpus that are executing in the guest context.
3027 * This will force the vcpu to exit and the cached EPT mappings
3028 * will be invalidated by the host before the next vmresume.
3030 static __inline void
3031 pmap_invalidate_ept(pmap_t pmap)
3037 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3038 ("pmap_invalidate_ept: absurd pm_active"));
3041 * The TLB mappings associated with a vcpu context are not
3042 * flushed each time a different vcpu is chosen to execute.
3044 * This is in contrast with a process's vtop mappings that
3045 * are flushed from the TLB on each context switch.
3047 * Therefore we need to do more than just a TLB shootdown on
3048 * the active cpus in 'pmap->pm_active'. To do this we keep
3049 * track of the number of invalidations performed on this pmap.
3051 * Each vcpu keeps a cache of this counter and compares it
3052 * just before a vmresume. If the counter is out-of-date an
3053 * invept will be done to flush stale mappings from the TLB.
3055 * To ensure that all vCPU threads have observed the new counter
3056 * value before returning, we use SMR. Ordering is important here:
3057 * the VMM enters an SMR read section before loading the counter
3058 * and after updating the pm_active bit set. Thus, pm_active is
3059 * a superset of active readers, and any reader that has observed
3060 * the goal has observed the new counter value.
3062 atomic_add_long(&pmap->pm_eptgen, 1);
3064 goal = smr_advance(pmap->pm_eptsmr);
3067 * Force the vcpu to exit and trap back into the hypervisor.
3069 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3070 ipi_selected(pmap->pm_active, ipinum);
3074 * Ensure that all active vCPUs will observe the new generation counter
3075 * value before executing any more guest instructions.
3077 smr_wait(pmap->pm_eptsmr, goal);
3081 pmap_invalidate_preipi_pcid(pmap_t pmap)
3083 struct pmap_pcid *pcidp;
3088 cpuid = PCPU_GET(cpuid);
3089 if (pmap != PCPU_GET(curpmap))
3090 cpuid = 0xffffffff; /* An impossible value */
3094 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3100 * The fence is between stores to pm_gen and the read of the
3101 * pm_active mask. We need to ensure that it is impossible
3102 * for us to miss the bit update in pm_active and
3103 * simultaneously observe a non-zero pm_gen in
3104 * pmap_activate_sw(), otherwise TLB update is missed.
3105 * Without the fence, IA32 allows such an outcome. Note that
3106 * pm_active is updated by a locked operation, which provides
3107 * the reciprocal fence.
3109 atomic_thread_fence_seq_cst();
3113 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3118 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3120 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3121 pmap_invalidate_preipi_nopcid);
3125 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3126 const bool invpcid_works1)
3128 struct invpcid_descr d;
3129 uint64_t kcr3, ucr3;
3133 * Because pm_pcid is recalculated on a context switch, we
3134 * must ensure there is no preemption, not just pinning.
3135 * Otherwise, we might use a stale value below.
3137 CRITICAL_ASSERT(curthread);
3140 * No need to do anything with user page tables invalidation
3141 * if there is no user page table, or invalidation is deferred
3142 * until the return to userspace. ucr3_load_mask is stable
3143 * because we have preemption disabled.
3145 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3146 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3149 pcid = pmap_get_pcid(pmap);
3150 if (invpcid_works1) {
3151 d.pcid = pcid | PMAP_PCID_USER_PT;
3154 invpcid(&d, INVPCID_ADDR);
3156 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3157 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3158 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3163 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3165 pmap_invalidate_page_pcid_cb(pmap, va, true);
3169 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3171 pmap_invalidate_page_pcid_cb(pmap, va, false);
3175 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3179 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3181 if (pmap_pcid_enabled)
3182 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3183 pmap_invalidate_page_pcid_noinvpcid_cb);
3184 return (pmap_invalidate_page_nopcid_cb);
3188 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3189 vm_offset_t addr2 __unused)
3191 if (pmap == kernel_pmap) {
3192 pmap_invlpg(kernel_pmap, va);
3193 } else if (pmap == PCPU_GET(curpmap)) {
3195 pmap_invalidate_page_cb(pmap, va);
3200 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3202 if (pmap_type_guest(pmap)) {
3203 pmap_invalidate_ept(pmap);
3207 KASSERT(pmap->pm_type == PT_X86,
3208 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3210 pmap_invalidate_preipi(pmap);
3211 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3214 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3215 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3218 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3219 const bool invpcid_works1)
3221 struct invpcid_descr d;
3222 uint64_t kcr3, ucr3;
3225 CRITICAL_ASSERT(curthread);
3227 if (pmap != PCPU_GET(curpmap) ||
3228 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3229 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3232 pcid = pmap_get_pcid(pmap);
3233 if (invpcid_works1) {
3234 d.pcid = pcid | PMAP_PCID_USER_PT;
3236 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3237 invpcid(&d, INVPCID_ADDR);
3239 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3240 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3241 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3246 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3249 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3253 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3256 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3260 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3261 vm_offset_t eva __unused)
3265 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3268 if (pmap_pcid_enabled)
3269 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3270 pmap_invalidate_range_pcid_noinvpcid_cb);
3271 return (pmap_invalidate_range_nopcid_cb);
3275 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3279 if (pmap == kernel_pmap) {
3280 if (PCPU_GET(pcid_invlpg_workaround)) {
3281 struct invpcid_descr d = { 0 };
3283 invpcid(&d, INVPCID_CTXGLOB);
3285 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3288 } else if (pmap == PCPU_GET(curpmap)) {
3289 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3291 pmap_invalidate_range_cb(pmap, sva, eva);
3296 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3298 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3299 pmap_invalidate_all(pmap);
3303 if (pmap_type_guest(pmap)) {
3304 pmap_invalidate_ept(pmap);
3308 KASSERT(pmap->pm_type == PT_X86,
3309 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3311 pmap_invalidate_preipi(pmap);
3312 smp_masked_invlpg_range(sva, eva, pmap,
3313 pmap_invalidate_range_curcpu_cb);
3317 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3319 struct invpcid_descr d;
3323 if (pmap == kernel_pmap) {
3324 if (invpcid_works1) {
3325 bzero(&d, sizeof(d));
3326 invpcid(&d, INVPCID_CTXGLOB);
3330 } else if (pmap == PCPU_GET(curpmap)) {
3331 CRITICAL_ASSERT(curthread);
3333 pcid = pmap_get_pcid(pmap);
3334 if (invpcid_works1) {
3338 invpcid(&d, INVPCID_CTX);
3340 kcr3 = pmap->pm_cr3 | pcid;
3343 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3344 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3349 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3351 pmap_invalidate_all_pcid_cb(pmap, true);
3355 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3357 pmap_invalidate_all_pcid_cb(pmap, false);
3361 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3363 if (pmap == kernel_pmap)
3365 else if (pmap == PCPU_GET(curpmap))
3369 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3371 if (pmap_pcid_enabled)
3372 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3373 pmap_invalidate_all_pcid_noinvpcid_cb);
3374 return (pmap_invalidate_all_nopcid_cb);
3378 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3379 vm_offset_t addr2 __unused)
3381 pmap_invalidate_all_cb(pmap);
3385 pmap_invalidate_all(pmap_t pmap)
3387 if (pmap_type_guest(pmap)) {
3388 pmap_invalidate_ept(pmap);
3392 KASSERT(pmap->pm_type == PT_X86,
3393 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3395 pmap_invalidate_preipi(pmap);
3396 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3400 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3401 vm_offset_t addr2 __unused)
3407 pmap_invalidate_cache(void)
3410 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3414 cpuset_t invalidate; /* processors that invalidate their TLB */
3419 u_int store; /* processor that updates the PDE */
3423 pmap_update_pde_action(void *arg)
3425 struct pde_action *act = arg;
3427 if (act->store == PCPU_GET(cpuid))
3428 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3432 pmap_update_pde_teardown(void *arg)
3434 struct pde_action *act = arg;
3436 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3437 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3441 * Change the page size for the specified virtual address in a way that
3442 * prevents any possibility of the TLB ever having two entries that map the
3443 * same virtual address using different page sizes. This is the recommended
3444 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3445 * machine check exception for a TLB state that is improperly diagnosed as a
3449 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3451 struct pde_action act;
3452 cpuset_t active, other_cpus;
3456 cpuid = PCPU_GET(cpuid);
3457 other_cpus = all_cpus;
3458 CPU_CLR(cpuid, &other_cpus);
3459 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3462 active = pmap->pm_active;
3464 if (CPU_OVERLAP(&active, &other_cpus)) {
3466 act.invalidate = active;
3470 act.newpde = newpde;
3471 CPU_SET(cpuid, &active);
3472 smp_rendezvous_cpus(active,
3473 smp_no_rendezvous_barrier, pmap_update_pde_action,
3474 pmap_update_pde_teardown, &act);
3476 pmap_update_pde_store(pmap, pde, newpde);
3477 if (CPU_ISSET(cpuid, &active))
3478 pmap_update_pde_invalidate(pmap, va, newpde);
3484 * Normal, non-SMP, invalidation functions.
3487 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3489 struct invpcid_descr d;
3490 struct pmap_pcid *pcidp;
3491 uint64_t kcr3, ucr3;
3494 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3498 KASSERT(pmap->pm_type == PT_X86,
3499 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3501 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3503 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3504 pmap->pm_ucr3 != PMAP_NO_CR3) {
3506 pcid = pmap_get_pcid(pmap);
3507 if (invpcid_works) {
3508 d.pcid = pcid | PMAP_PCID_USER_PT;
3511 invpcid(&d, INVPCID_ADDR);
3513 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3514 ucr3 = pmap->pm_ucr3 | pcid |
3515 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3516 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3520 } else if (pmap_pcid_enabled) {
3521 pcidp = zpcpu_get(pmap->pm_pcidp);
3527 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3529 struct invpcid_descr d;
3530 struct pmap_pcid *pcidp;
3532 uint64_t kcr3, ucr3;
3535 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3539 KASSERT(pmap->pm_type == PT_X86,
3540 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3542 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3543 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3545 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3546 pmap->pm_ucr3 != PMAP_NO_CR3) {
3548 pcid = pmap_get_pcid(pmap);
3549 if (invpcid_works) {
3550 d.pcid = pcid | PMAP_PCID_USER_PT;
3553 for (; d.addr < eva; d.addr += PAGE_SIZE)
3554 invpcid(&d, INVPCID_ADDR);
3556 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3557 ucr3 = pmap->pm_ucr3 | pcid |
3558 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3559 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3563 } else if (pmap_pcid_enabled) {
3564 pcidp = zpcpu_get(pmap->pm_pcidp);
3570 pmap_invalidate_all(pmap_t pmap)
3572 struct invpcid_descr d;
3573 struct pmap_pcid *pcidp;
3574 uint64_t kcr3, ucr3;
3577 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3581 KASSERT(pmap->pm_type == PT_X86,
3582 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3584 if (pmap == kernel_pmap) {
3585 if (pmap_pcid_enabled && invpcid_works) {
3586 bzero(&d, sizeof(d));
3587 invpcid(&d, INVPCID_CTXGLOB);
3591 } else if (pmap == PCPU_GET(curpmap)) {
3592 if (pmap_pcid_enabled) {
3594 pcid = pmap_get_pcid(pmap);
3595 if (invpcid_works) {
3599 invpcid(&d, INVPCID_CTX);
3600 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3601 d.pcid |= PMAP_PCID_USER_PT;
3602 invpcid(&d, INVPCID_CTX);
3605 kcr3 = pmap->pm_cr3 | pcid;
3606 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3607 ucr3 = pmap->pm_ucr3 | pcid |
3609 pmap_pti_pcid_invalidate(ucr3, kcr3);
3617 } else if (pmap_pcid_enabled) {
3618 pcidp = zpcpu_get(pmap->pm_pcidp);
3624 pmap_invalidate_cache(void)
3631 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3633 struct pmap_pcid *pcidp;
3635 pmap_update_pde_store(pmap, pde, newpde);
3636 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3637 pmap_update_pde_invalidate(pmap, va, newpde);
3639 pcidp = zpcpu_get(pmap->pm_pcidp);
3646 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3650 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3651 * by a promotion that did not invalidate the 512 4KB page mappings
3652 * that might exist in the TLB. Consequently, at this point, the TLB
3653 * may hold both 4KB and 2MB page mappings for the address range [va,
3654 * va + NBPDR). Therefore, the entire range must be invalidated here.
3655 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3656 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3657 * single INVLPG suffices to invalidate the 2MB page mapping from the
3660 if ((pde & PG_PROMOTED) != 0)
3661 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3663 pmap_invalidate_page(pmap, va);
3666 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3667 (vm_offset_t sva, vm_offset_t eva))
3670 if ((cpu_feature & CPUID_SS) != 0)
3671 return (pmap_invalidate_cache_range_selfsnoop);
3672 if ((cpu_feature & CPUID_CLFSH) != 0)
3673 return (pmap_force_invalidate_cache_range);
3674 return (pmap_invalidate_cache_range_all);
3677 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3680 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3683 KASSERT((sva & PAGE_MASK) == 0,
3684 ("pmap_invalidate_cache_range: sva not page-aligned"));
3685 KASSERT((eva & PAGE_MASK) == 0,
3686 ("pmap_invalidate_cache_range: eva not page-aligned"));
3690 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3693 pmap_invalidate_cache_range_check_align(sva, eva);
3697 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3700 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3703 * XXX: Some CPUs fault, hang, or trash the local APIC
3704 * registers if we use CLFLUSH on the local APIC range. The
3705 * local APIC is always uncached, so we don't need to flush
3706 * for that range anyway.
3708 if (pmap_kextract(sva) == lapic_paddr)
3711 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3713 * Do per-cache line flush. Use a locked
3714 * instruction to insure that previous stores are
3715 * included in the write-back. The processor
3716 * propagates flush to other processors in the cache
3719 atomic_thread_fence_seq_cst();
3720 for (; sva < eva; sva += cpu_clflush_line_size)
3722 atomic_thread_fence_seq_cst();
3725 * Writes are ordered by CLFLUSH on Intel CPUs.
3727 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3729 for (; sva < eva; sva += cpu_clflush_line_size)
3731 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3737 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3740 pmap_invalidate_cache_range_check_align(sva, eva);
3741 pmap_invalidate_cache();
3745 * Remove the specified set of pages from the data and instruction caches.
3747 * In contrast to pmap_invalidate_cache_range(), this function does not
3748 * rely on the CPU's self-snoop feature, because it is intended for use
3749 * when moving pages into a different cache domain.
3752 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3754 vm_offset_t daddr, eva;
3758 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3759 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3760 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3761 pmap_invalidate_cache();
3764 atomic_thread_fence_seq_cst();
3765 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3767 for (i = 0; i < count; i++) {
3768 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3769 eva = daddr + PAGE_SIZE;
3770 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3778 atomic_thread_fence_seq_cst();
3779 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3785 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3788 pmap_invalidate_cache_range_check_align(sva, eva);
3790 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3791 pmap_force_invalidate_cache_range(sva, eva);
3795 /* See comment in pmap_force_invalidate_cache_range(). */
3796 if (pmap_kextract(sva) == lapic_paddr)
3799 atomic_thread_fence_seq_cst();
3800 for (; sva < eva; sva += cpu_clflush_line_size)
3802 atomic_thread_fence_seq_cst();
3806 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3810 int error __diagused;
3813 KASSERT((spa & PAGE_MASK) == 0,
3814 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3815 KASSERT((epa & PAGE_MASK) == 0,
3816 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3818 if (spa < dmaplimit) {
3819 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3821 if (dmaplimit >= epa)
3826 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3828 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3830 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3831 pte = vtopte(vaddr);
3832 for (; spa < epa; spa += PAGE_SIZE) {
3834 pte_store(pte, spa | pte_bits);
3835 pmap_invlpg(kernel_pmap, vaddr);
3836 /* XXXKIB atomic inside flush_cache_range are excessive */
3837 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3840 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3844 * Routine: pmap_extract
3846 * Extract the physical page address associated
3847 * with the given map/virtual_address pair.
3850 pmap_extract(pmap_t pmap, vm_offset_t va)
3854 pt_entry_t *pte, PG_V;
3858 PG_V = pmap_valid_bit(pmap);
3860 pdpe = pmap_pdpe(pmap, va);
3861 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3862 if ((*pdpe & PG_PS) != 0)
3863 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3865 pde = pmap_pdpe_to_pde(pdpe, va);
3866 if ((*pde & PG_V) != 0) {
3867 if ((*pde & PG_PS) != 0) {
3868 pa = (*pde & PG_PS_FRAME) |
3871 pte = pmap_pde_to_pte(pde, va);
3872 pa = (*pte & PG_FRAME) |
3883 * Routine: pmap_extract_and_hold
3885 * Atomically extract and hold the physical page
3886 * with the given pmap and virtual address pair
3887 * if that mapping permits the given protection.
3890 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3892 pdp_entry_t pdpe, *pdpep;
3893 pd_entry_t pde, *pdep;
3894 pt_entry_t pte, PG_RW, PG_V;
3898 PG_RW = pmap_rw_bit(pmap);
3899 PG_V = pmap_valid_bit(pmap);
3902 pdpep = pmap_pdpe(pmap, va);
3903 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3905 if ((pdpe & PG_PS) != 0) {
3906 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3908 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3912 pdep = pmap_pdpe_to_pde(pdpep, va);
3913 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3915 if ((pde & PG_PS) != 0) {
3916 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3918 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3922 pte = *pmap_pde_to_pte(pdep, va);
3923 if ((pte & PG_V) == 0 ||
3924 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3926 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3929 if (m != NULL && !vm_page_wire_mapped(m))
3937 pmap_kextract(vm_offset_t va)
3942 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3943 pa = DMAP_TO_PHYS(va);
3944 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3945 pa = pmap_large_map_kextract(va);
3949 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3952 * Beware of a concurrent promotion that changes the
3953 * PDE at this point! For example, vtopte() must not
3954 * be used to access the PTE because it would use the
3955 * new PDE. It is, however, safe to use the old PDE
3956 * because the page table page is preserved by the
3959 pa = *pmap_pde_to_pte(&pde, va);
3960 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3966 /***************************************************
3967 * Low level mapping routines.....
3968 ***************************************************/
3971 * Add a wired page to the kva.
3972 * Note: not SMP coherent.
3975 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3980 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3981 X86_PG_RW | X86_PG_V);
3984 static __inline void
3985 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3991 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
3992 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3993 X86_PG_RW | X86_PG_V | cache_bits);
3997 * Remove a page from the kernel pagetables.
3998 * Note: not SMP coherent.
4001 pmap_kremove(vm_offset_t va)
4010 * Used to map a range of physical addresses into kernel
4011 * virtual address space.
4013 * The value passed in '*virt' is a suggested virtual address for
4014 * the mapping. Architectures which can support a direct-mapped
4015 * physical to virtual region can return the appropriate address
4016 * within that region, leaving '*virt' unchanged. Other
4017 * architectures should map the pages starting at '*virt' and
4018 * update '*virt' with the first usable address after the mapped
4022 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
4024 return PHYS_TO_DMAP(start);
4028 * Add a list of wired pages to the kva
4029 * this routine is only used for temporary
4030 * kernel mappings that do not need to have
4031 * page modification or references recorded.
4032 * Note that old mappings are simply written
4033 * over. The page *must* be wired.
4034 * Note: SMP coherent. Uses a ranged shootdown IPI.
4037 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4039 pt_entry_t *endpte, oldpte, pa, *pte;
4045 endpte = pte + count;
4046 while (pte < endpte) {
4048 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4049 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4050 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4052 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4053 X86_PG_M | X86_PG_RW | X86_PG_V);
4057 if (__predict_false((oldpte & X86_PG_V) != 0))
4058 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4063 * This routine tears out page mappings from the
4064 * kernel -- it is meant only for temporary mappings.
4065 * Note: SMP coherent. Uses a ranged shootdown IPI.
4068 pmap_qremove(vm_offset_t sva, int count)
4073 while (count-- > 0) {
4074 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4078 pmap_invalidate_range(kernel_pmap, sva, va);
4081 /***************************************************
4082 * Page table page management routines.....
4083 ***************************************************/
4085 * Schedule the specified unused page table page to be freed. Specifically,
4086 * add the page to the specified list of pages that will be released to the
4087 * physical memory manager after the TLB has been updated.
4089 static __inline void
4090 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4091 boolean_t set_PG_ZERO)
4095 m->flags |= PG_ZERO;
4097 m->flags &= ~PG_ZERO;
4098 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4102 * Inserts the specified page table page into the specified pmap's collection
4103 * of idle page table pages. Each of a pmap's page table pages is responsible
4104 * for mapping a distinct range of virtual addresses. The pmap's collection is
4105 * ordered by this virtual address range.
4107 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4108 * "mpte"'s valid field will be set to 0.
4110 * If "promoted" is true and "allpte_PG_A_set" is false, then "mpte" must
4111 * contain valid mappings with identical attributes except for PG_A; "mpte"'s
4112 * valid field will be set to 1.
4114 * If "promoted" and "allpte_PG_A_set" are both true, then "mpte" must contain
4115 * valid mappings with identical attributes including PG_A; "mpte"'s valid
4116 * field will be set to VM_PAGE_BITS_ALL.
4119 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4120 bool allpte_PG_A_set)
4123 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4124 KASSERT(promoted || !allpte_PG_A_set,
4125 ("a zero-filled PTP can't have PG_A set in every PTE"));
4126 mpte->valid = promoted ? (allpte_PG_A_set ? VM_PAGE_BITS_ALL : 1) : 0;
4127 return (vm_radix_insert(&pmap->pm_root, mpte));
4131 * Removes the page table page mapping the specified virtual address from the
4132 * specified pmap's collection of idle page table pages, and returns it.
4133 * Otherwise, returns NULL if there is no page table page corresponding to the
4134 * specified virtual address.
4136 static __inline vm_page_t
4137 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4140 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4141 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4145 * Decrements a page table page's reference count, which is used to record the
4146 * number of valid page table entries within the page. If the reference count
4147 * drops to zero, then the page table page is unmapped. Returns TRUE if the
4148 * page table page was unmapped and FALSE otherwise.
4150 static inline boolean_t
4151 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4155 if (m->ref_count == 0) {
4156 _pmap_unwire_ptp(pmap, va, m, free);
4163 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4169 vm_page_t pdpg, pdppg, pml4pg;
4171 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4174 * unmap the page table page
4176 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4178 MPASS(pmap_is_la57(pmap));
4179 pml5 = pmap_pml5e(pmap, va);
4181 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4182 pml5 = pmap_pml5e_u(pmap, va);
4185 } else if (m->pindex >= NUPDE + NUPDPE) {
4187 pml4 = pmap_pml4e(pmap, va);
4189 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4190 va <= VM_MAXUSER_ADDRESS) {
4191 pml4 = pmap_pml4e_u(pmap, va);
4194 } else if (m->pindex >= NUPDE) {
4196 pdp = pmap_pdpe(pmap, va);
4200 pd = pmap_pde(pmap, va);
4203 if (m->pindex < NUPDE) {
4204 /* We just released a PT, unhold the matching PD */
4205 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4206 pmap_unwire_ptp(pmap, va, pdpg, free);
4207 } else if (m->pindex < NUPDE + NUPDPE) {
4208 /* We just released a PD, unhold the matching PDP */
4209 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4210 pmap_unwire_ptp(pmap, va, pdppg, free);
4211 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4212 /* We just released a PDP, unhold the matching PML4 */
4213 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4214 pmap_unwire_ptp(pmap, va, pml4pg, free);
4217 pmap_pt_page_count_adj(pmap, -1);
4220 * Put page on a list so that it is released after
4221 * *ALL* TLB shootdown is done
4223 pmap_add_delayed_free_list(m, free, TRUE);
4227 * After removing a page table entry, this routine is used to
4228 * conditionally free the page, and manage the reference count.
4231 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4232 struct spglist *free)
4236 if (va >= VM_MAXUSER_ADDRESS)
4238 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4239 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4240 return (pmap_unwire_ptp(pmap, va, mpte, free));
4244 * Release a page table page reference after a failed attempt to create a
4248 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4250 struct spglist free;
4253 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4255 * Although "va" was never mapped, paging-structure caches
4256 * could nonetheless have entries that refer to the freed
4257 * page table pages. Invalidate those entries.
4259 pmap_invalidate_page(pmap, va);
4260 vm_page_free_pages_toq(&free, true);
4265 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4267 struct pmap_pcid *pcidp;
4271 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4272 pcidp->pm_pcid = pcid;
4273 pcidp->pm_gen = gen;
4278 pmap_pinit0(pmap_t pmap)
4283 PMAP_LOCK_INIT(pmap);
4284 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4285 pmap->pm_pmltopu = NULL;
4286 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4287 /* hack to keep pmap_pti_pcid_invalidate() alive */
4288 pmap->pm_ucr3 = PMAP_NO_CR3;
4289 vm_radix_init(&pmap->pm_root);
4290 CPU_ZERO(&pmap->pm_active);
4291 TAILQ_INIT(&pmap->pm_pvchunk);
4292 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4293 pmap->pm_flags = pmap_flags;
4294 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4295 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4296 pmap_activate_boot(pmap);
4301 p->p_md.md_flags |= P_MD_KPTI;
4304 pmap_thread_init_invl_gen(td);
4306 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4307 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4308 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4314 pmap_pinit_pml4(vm_page_t pml4pg)
4316 pml4_entry_t *pm_pml4;
4319 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4321 /* Wire in kernel global address entries. */
4322 for (i = 0; i < NKPML4E; i++) {
4323 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4327 for (i = 0; i < NKASANPML4E; i++) {
4328 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4333 for (i = 0; i < NKMSANSHADPML4E; i++) {
4334 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4335 X86_PG_RW | X86_PG_V | pg_nx;
4337 for (i = 0; i < NKMSANORIGPML4E; i++) {
4338 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4339 X86_PG_RW | X86_PG_V | pg_nx;
4342 for (i = 0; i < ndmpdpphys; i++) {
4343 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4347 /* install self-referential address mapping entry(s) */
4348 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4349 X86_PG_A | X86_PG_M;
4351 /* install large map entries if configured */
4352 for (i = 0; i < lm_ents; i++)
4353 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4357 pmap_pinit_pml5(vm_page_t pml5pg)
4359 pml5_entry_t *pm_pml5;
4361 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4364 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4365 * entering all existing kernel mappings into level 5 table.
4367 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4368 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4369 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4372 * Install self-referential address mapping entry.
4374 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4375 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A |
4376 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4380 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4382 pml4_entry_t *pm_pml4u;
4385 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4386 for (i = 0; i < NPML4EPG; i++)
4387 pm_pml4u[i] = pti_pml4[i];
4391 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4393 pml5_entry_t *pm_pml5u;
4395 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4399 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4400 * table, entering all kernel mappings needed for usermode
4401 * into level 5 table.
4403 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4404 pmap_kextract((vm_offset_t)pti_pml4) |
4405 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4406 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4409 /* Allocate a page table page and do related bookkeeping */
4411 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4415 m = vm_page_alloc_noobj(flags);
4416 if (__predict_false(m == NULL))
4419 pmap_pt_page_count_adj(pmap, 1);
4424 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4427 * This function assumes the page will need to be unwired,
4428 * even though the counterpart allocation in pmap_alloc_pt_page()
4429 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4430 * of pmap_free_pt_page() require unwiring. The case in which
4431 * a PT page doesn't require unwiring because its ref_count has
4432 * naturally reached 0 is handled through _pmap_unwire_ptp().
4434 vm_page_unwire_noq(m);
4436 vm_page_free_zero(m);
4440 pmap_pt_page_count_adj(pmap, -1);
4443 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4446 * Initialize a preallocated and zeroed pmap structure,
4447 * such as one in a vmspace structure.
4450 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4452 vm_page_t pmltop_pg, pmltop_pgu;
4453 vm_paddr_t pmltop_phys;
4455 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4458 * Allocate the page directory page. Pass NULL instead of a
4459 * pointer to the pmap here to avoid calling
4460 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4461 * since that requires pmap lock. Instead do the accounting
4464 * Note that final call to pmap_remove() optimization that
4465 * checks for zero resident_count is basically disabled by
4466 * accounting for top-level page. But the optimization was
4467 * not effective since we started using non-managed mapping of
4470 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4472 pmap_pt_page_count_pinit(pmap, 1);
4474 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4475 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4477 if (pmap_pcid_enabled) {
4478 if (pmap->pm_pcidp == NULL)
4479 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4481 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4483 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4484 pmap->pm_ucr3 = PMAP_NO_CR3;
4485 pmap->pm_pmltopu = NULL;
4487 pmap->pm_type = pm_type;
4490 * Do not install the host kernel mappings in the nested page
4491 * tables. These mappings are meaningless in the guest physical
4493 * Install minimal kernel mappings in PTI case.
4497 pmap->pm_cr3 = pmltop_phys;
4498 if (pmap_is_la57(pmap))
4499 pmap_pinit_pml5(pmltop_pg);
4501 pmap_pinit_pml4(pmltop_pg);
4502 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4504 * As with pmltop_pg, pass NULL instead of a
4505 * pointer to the pmap to ensure that the PTI
4506 * page counted explicitly.
4508 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4509 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4510 pmap_pt_page_count_pinit(pmap, 1);
4511 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4512 VM_PAGE_TO_PHYS(pmltop_pgu));
4513 if (pmap_is_la57(pmap))
4514 pmap_pinit_pml5_pti(pmltop_pgu);
4516 pmap_pinit_pml4_pti(pmltop_pgu);
4517 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4519 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4520 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4521 pkru_free_range, pmap, M_NOWAIT);
4526 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4530 vm_radix_init(&pmap->pm_root);
4531 CPU_ZERO(&pmap->pm_active);
4532 TAILQ_INIT(&pmap->pm_pvchunk);
4533 pmap->pm_flags = flags;
4534 pmap->pm_eptgen = 0;
4540 pmap_pinit(pmap_t pmap)
4543 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4547 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4550 struct spglist free;
4552 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4553 if (mpg->ref_count != 0)
4556 _pmap_unwire_ptp(pmap, va, mpg, &free);
4557 pmap_invalidate_page(pmap, va);
4558 vm_page_free_pages_toq(&free, true);
4561 static pml4_entry_t *
4562 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4565 vm_pindex_t pml5index;
4572 if (!pmap_is_la57(pmap))
4573 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4575 PG_V = pmap_valid_bit(pmap);
4576 pml5index = pmap_pml5e_index(va);
4577 pml5 = &pmap->pm_pmltop[pml5index];
4578 if ((*pml5 & PG_V) == 0) {
4579 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4586 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4587 pml4 = &pml4[pmap_pml4e_index(va)];
4588 if ((*pml4 & PG_V) == 0) {
4589 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4590 if (allocated && !addref)
4591 pml4pg->ref_count--;
4592 else if (!allocated && addref)
4593 pml4pg->ref_count++;
4598 static pdp_entry_t *
4599 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4608 PG_V = pmap_valid_bit(pmap);
4610 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4614 if ((*pml4 & PG_V) == 0) {
4615 /* Have to allocate a new pdp, recurse */
4616 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4618 if (pmap_is_la57(pmap))
4619 pmap_allocpte_free_unref(pmap, va,
4620 pmap_pml5e(pmap, va));
4627 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4628 pdp = &pdp[pmap_pdpe_index(va)];
4629 if ((*pdp & PG_V) == 0) {
4630 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4631 if (allocated && !addref)
4633 else if (!allocated && addref)
4640 * The ptepindexes, i.e. page indices, of the page table pages encountered
4641 * while translating virtual address va are defined as follows:
4642 * - for the page table page (last level),
4643 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4644 * in other words, it is just the index of the PDE that maps the page
4646 * - for the page directory page,
4647 * ptepindex = NUPDE (number of userland PD entries) +
4648 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4649 * i.e. index of PDPE is put after the last index of PDE,
4650 * - for the page directory pointer page,
4651 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4653 * i.e. index of pml4e is put after the last index of PDPE,
4654 * - for the PML4 page (if LA57 mode is enabled),
4655 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4656 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4657 * i.e. index of pml5e is put after the last index of PML4E.
4659 * Define an order on the paging entries, where all entries of the
4660 * same height are put together, then heights are put from deepest to
4661 * root. Then ptexpindex is the sequential number of the
4662 * corresponding paging entry in this order.
4664 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4665 * LA57 paging structures even in LA48 paging mode. Moreover, the
4666 * ptepindexes are calculated as if the paging structures were 5-level
4667 * regardless of the actual mode of operation.
4669 * The root page at PML4/PML5 does not participate in this indexing scheme,
4670 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4673 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4676 vm_pindex_t pml5index, pml4index;
4677 pml5_entry_t *pml5, *pml5u;
4678 pml4_entry_t *pml4, *pml4u;
4682 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4684 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4686 PG_A = pmap_accessed_bit(pmap);
4687 PG_M = pmap_modified_bit(pmap);
4688 PG_V = pmap_valid_bit(pmap);
4689 PG_RW = pmap_rw_bit(pmap);
4692 * Allocate a page table page.
4694 m = pmap_alloc_pt_page(pmap, ptepindex,
4695 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4700 * Map the pagetable page into the process address space, if
4701 * it isn't already there.
4703 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4704 MPASS(pmap_is_la57(pmap));
4706 pml5index = pmap_pml5e_index(va);
4707 pml5 = &pmap->pm_pmltop[pml5index];
4708 KASSERT((*pml5 & PG_V) == 0,
4709 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4710 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4712 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4713 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4716 pml5u = &pmap->pm_pmltopu[pml5index];
4717 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4720 } else if (ptepindex >= NUPDE + NUPDPE) {
4721 pml4index = pmap_pml4e_index(va);
4722 /* Wire up a new PDPE page */
4723 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4725 pmap_free_pt_page(pmap, m, true);
4728 KASSERT((*pml4 & PG_V) == 0,
4729 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4730 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4732 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4733 pml4index < NUPML4E) {
4735 * PTI: Make all user-space mappings in the
4736 * kernel-mode page table no-execute so that
4737 * we detect any programming errors that leave
4738 * the kernel-mode page table active on return
4741 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4744 pml4u = &pmap->pm_pmltopu[pml4index];
4745 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4748 } else if (ptepindex >= NUPDE) {
4749 /* Wire up a new PDE page */
4750 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4752 pmap_free_pt_page(pmap, m, true);
4755 KASSERT((*pdp & PG_V) == 0,
4756 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4757 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4759 /* Wire up a new PTE page */
4760 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4762 pmap_free_pt_page(pmap, m, true);
4765 if ((*pdp & PG_V) == 0) {
4766 /* Have to allocate a new pd, recurse */
4767 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4768 lockp, va) == NULL) {
4769 pmap_allocpte_free_unref(pmap, va,
4770 pmap_pml4e(pmap, va));
4771 pmap_free_pt_page(pmap, m, true);
4775 /* Add reference to the pd page */
4776 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4779 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4781 /* Now we know where the page directory page is */
4782 pd = &pd[pmap_pde_index(va)];
4783 KASSERT((*pd & PG_V) == 0,
4784 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4785 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4792 * This routine is called if the desired page table page does not exist.
4794 * If page table page allocation fails, this routine may sleep before
4795 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4796 * occurs right before returning to the caller. This way, we never
4797 * drop pmap lock to sleep while a page table page has ref_count == 0,
4798 * which prevents the page from being freed under us.
4801 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4806 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4807 if (m == NULL && lockp != NULL) {
4808 RELEASE_PV_LIST_LOCK(lockp);
4810 PMAP_ASSERT_NOT_IN_DI();
4818 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4819 struct rwlock **lockp)
4821 pdp_entry_t *pdpe, PG_V;
4824 vm_pindex_t pdpindex;
4826 PG_V = pmap_valid_bit(pmap);
4829 pdpe = pmap_pdpe(pmap, va);
4830 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4831 pde = pmap_pdpe_to_pde(pdpe, va);
4832 if (va < VM_MAXUSER_ADDRESS) {
4833 /* Add a reference to the pd page. */
4834 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4838 } else if (va < VM_MAXUSER_ADDRESS) {
4839 /* Allocate a pd page. */
4840 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4841 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4848 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4849 pde = &pde[pmap_pde_index(va)];
4851 panic("pmap_alloc_pde: missing page table page for va %#lx",
4858 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4860 vm_pindex_t ptepindex;
4861 pd_entry_t *pd, PG_V;
4864 PG_V = pmap_valid_bit(pmap);
4867 * Calculate pagetable page index
4869 ptepindex = pmap_pde_pindex(va);
4872 * Get the page directory entry
4874 pd = pmap_pde(pmap, va);
4877 * This supports switching from a 2MB page to a
4880 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4881 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4883 * Invalidation of the 2MB page mapping may have caused
4884 * the deallocation of the underlying PD page.
4891 * If the page table page is mapped, we just increment the
4892 * hold count, and activate it.
4894 if (pd != NULL && (*pd & PG_V) != 0) {
4895 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4899 * Here if the pte page isn't mapped, or if it has been
4902 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4903 if (m == NULL && lockp != NULL)
4909 /***************************************************
4910 * Pmap allocation/deallocation routines.
4911 ***************************************************/
4914 * Release any resources held by the given physical map.
4915 * Called when a pmap initialized by pmap_pinit is being released.
4916 * Should only be called if the map contains no valid mappings.
4919 pmap_release(pmap_t pmap)
4924 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4925 ("pmap_release: pmap %p has reserved page table page(s)",
4927 KASSERT(CPU_EMPTY(&pmap->pm_active),
4928 ("releasing active pmap %p", pmap));
4930 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4932 if (pmap_is_la57(pmap)) {
4933 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4934 pmap->pm_pmltop[PML5PML5I] = 0;
4936 for (i = 0; i < NKPML4E; i++) /* KVA */
4937 pmap->pm_pmltop[KPML4BASE + i] = 0;
4939 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4940 pmap->pm_pmltop[KASANPML4I + i] = 0;
4943 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4944 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4945 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4946 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4948 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4949 pmap->pm_pmltop[DMPML4I + i] = 0;
4950 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4951 for (i = 0; i < lm_ents; i++) /* Large Map */
4952 pmap->pm_pmltop[LMSPML4I + i] = 0;
4955 pmap_free_pt_page(NULL, m, true);
4956 pmap_pt_page_count_pinit(pmap, -1);
4958 if (pmap->pm_pmltopu != NULL) {
4959 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4961 pmap_free_pt_page(NULL, m, false);
4962 pmap_pt_page_count_pinit(pmap, -1);
4964 if (pmap->pm_type == PT_X86 &&
4965 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4966 rangeset_fini(&pmap->pm_pkru);
4968 KASSERT(pmap->pm_stats.resident_count == 0,
4969 ("pmap_release: pmap %p resident count %ld != 0",
4970 pmap, pmap->pm_stats.resident_count));
4974 kvm_size(SYSCTL_HANDLER_ARGS)
4976 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4978 return sysctl_handle_long(oidp, &ksize, 0, req);
4980 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4981 0, 0, kvm_size, "LU",
4985 kvm_free(SYSCTL_HANDLER_ARGS)
4987 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4989 return sysctl_handle_long(oidp, &kfree, 0, req);
4991 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4992 0, 0, kvm_free, "LU",
4993 "Amount of KVM free");
4997 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
5002 vm_paddr_t dummypa, dummypd, dummypt;
5005 npdpg = howmany(size, NBPDP);
5006 npde = size / NBPDR;
5008 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
5009 pagezero((void *)PHYS_TO_DMAP(dummypa));
5011 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
5012 pagezero((void *)PHYS_TO_DMAP(dummypt));
5013 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
5014 for (i = 0; i < npdpg; i++)
5015 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
5017 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
5018 for (i = 0; i < NPTEPG; i++)
5019 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
5020 X86_PG_A | X86_PG_M | pg_nx);
5022 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
5023 for (i = 0; i < npde; i++)
5024 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
5026 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
5027 for (i = 0; i < npdpg; i++)
5028 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
5033 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
5037 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
5040 * The end of the page array's KVA region is 2MB aligned, see
5043 size = round_2mpage(end) - start;
5044 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
5045 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
5050 * Allocate physical memory for the vm_page array and map it into KVA,
5051 * attempting to back the vm_pages with domain-local memory.
5054 pmap_page_array_startup(long pages)
5057 pd_entry_t *pde, newpdir;
5058 vm_offset_t va, start, end;
5063 vm_page_array_size = pages;
5065 start = VM_MIN_KERNEL_ADDRESS;
5066 end = start + pages * sizeof(struct vm_page);
5067 for (va = start; va < end; va += NBPDR) {
5068 pfn = first_page + (va - start) / sizeof(struct vm_page);
5069 domain = vm_phys_domain(ptoa(pfn));
5070 pdpe = pmap_pdpe(kernel_pmap, va);
5071 if ((*pdpe & X86_PG_V) == 0) {
5072 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5074 pagezero((void *)PHYS_TO_DMAP(pa));
5075 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5076 X86_PG_A | X86_PG_M);
5078 pde = pmap_pdpe_to_pde(pdpe, va);
5079 if ((*pde & X86_PG_V) != 0)
5080 panic("Unexpected pde");
5081 pa = vm_phys_early_alloc(domain, NBPDR);
5082 for (i = 0; i < NPDEPG; i++)
5083 dump_add_page(pa + i * PAGE_SIZE);
5084 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5085 X86_PG_M | PG_PS | pg_g | pg_nx);
5086 pde_store(pde, newpdir);
5088 vm_page_array = (vm_page_t)start;
5091 pmap_kmsan_page_array_startup(start, end);
5096 * grow the number of kernel page table entries, if needed
5099 pmap_growkernel(vm_offset_t addr)
5103 pd_entry_t *pde, newpdir;
5108 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5111 * The kernel map covers two distinct regions of KVA: that used
5112 * for dynamic kernel memory allocations, and the uppermost 2GB
5113 * of the virtual address space. The latter is used to map the
5114 * kernel and loadable kernel modules. This scheme enables the
5115 * use of a special code generation model for kernel code which
5116 * takes advantage of compact addressing modes in machine code.
5118 * Both regions grow upwards; to avoid wasting memory, the gap
5119 * in between is unmapped. If "addr" is above "KERNBASE", the
5120 * kernel's region is grown, otherwise the kmem region is grown.
5122 * The correctness of this action is based on the following
5123 * argument: vm_map_insert() allocates contiguous ranges of the
5124 * kernel virtual address space. It calls this function if a range
5125 * ends after "kernel_vm_end". If the kernel is mapped between
5126 * "kernel_vm_end" and "addr", then the range cannot begin at
5127 * "kernel_vm_end". In fact, its beginning address cannot be less
5128 * than the kernel. Thus, there is no immediate need to allocate
5129 * any new kernel page table pages between "kernel_vm_end" and
5132 if (KERNBASE < addr) {
5133 end = KERNBASE + nkpt * NBPDR;
5139 end = kernel_vm_end;
5142 addr = roundup2(addr, NBPDR);
5143 if (addr - 1 >= vm_map_max(kernel_map))
5144 addr = vm_map_max(kernel_map);
5147 * The grown region is already mapped, so there is
5154 kasan_shadow_map(end, addr - end);
5155 kmsan_shadow_map(end, addr - end);
5156 while (end < addr) {
5157 pdpe = pmap_pdpe(kernel_pmap, end);
5158 if ((*pdpe & X86_PG_V) == 0) {
5159 nkpg = pmap_alloc_pt_page(kernel_pmap,
5160 pmap_pdpe_pindex(end), VM_ALLOC_WIRED |
5161 VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5163 panic("pmap_growkernel: no memory to grow kernel");
5164 paddr = VM_PAGE_TO_PHYS(nkpg);
5165 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5166 X86_PG_A | X86_PG_M);
5167 continue; /* try again */
5169 pde = pmap_pdpe_to_pde(pdpe, end);
5170 if ((*pde & X86_PG_V) != 0) {
5171 end = (end + NBPDR) & ~PDRMASK;
5172 if (end - 1 >= vm_map_max(kernel_map)) {
5173 end = vm_map_max(kernel_map);
5179 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5180 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5182 panic("pmap_growkernel: no memory to grow kernel");
5183 paddr = VM_PAGE_TO_PHYS(nkpg);
5184 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5185 pde_store(pde, newpdir);
5187 end = (end + NBPDR) & ~PDRMASK;
5188 if (end - 1 >= vm_map_max(kernel_map)) {
5189 end = vm_map_max(kernel_map);
5194 if (end <= KERNBASE)
5195 kernel_vm_end = end;
5197 nkpt = howmany(end - KERNBASE, NBPDR);
5201 /***************************************************
5202 * page management routines.
5203 ***************************************************/
5205 static const uint64_t pc_freemask[_NPCM] = {
5206 [0 ... _NPCM - 2] = PC_FREEN,
5207 [_NPCM - 1] = PC_FREEL
5212 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5213 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5214 &pc_chunk_count, "Current number of pv entry cnunks");
5216 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5217 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5218 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5220 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5221 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5222 &pc_chunk_frees, "Total number of pv entry chunks freed");
5224 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5225 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5227 "Number of failed attempts to get a pv entry chunk page");
5229 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5230 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5231 &pv_entry_frees, "Total number of pv entries freed");
5233 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5234 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5235 &pv_entry_allocs, "Total number of pv entries allocated");
5237 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5238 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5239 &pv_entry_count, "Current number of pv entries");
5241 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5242 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5243 &pv_entry_spare, "Current number of spare pv entries");
5247 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5252 pmap_invalidate_all(pmap);
5253 if (pmap != locked_pmap)
5256 pmap_delayed_invl_finish();
5260 * We are in a serious low memory condition. Resort to
5261 * drastic measures to free some pages so we can allocate
5262 * another pv entry chunk.
5264 * Returns NULL if PV entries were reclaimed from the specified pmap.
5266 * We do not, however, unmap 2mpages because subsequent accesses will
5267 * allocate per-page pv entries until repromotion occurs, thereby
5268 * exacerbating the shortage of free pv entries.
5271 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5273 struct pv_chunks_list *pvc;
5274 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5275 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5276 struct md_page *pvh;
5278 pmap_t next_pmap, pmap;
5279 pt_entry_t *pte, tpte;
5280 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5284 struct spglist free;
5286 int bit, field, freed;
5287 bool start_di, restart;
5289 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5290 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5293 PG_G = PG_A = PG_M = PG_RW = 0;
5295 bzero(&pc_marker_b, sizeof(pc_marker_b));
5296 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5297 pc_marker = (struct pv_chunk *)&pc_marker_b;
5298 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5301 * A delayed invalidation block should already be active if
5302 * pmap_advise() or pmap_remove() called this function by way
5303 * of pmap_demote_pde_locked().
5305 start_di = pmap_not_in_di();
5307 pvc = &pv_chunks[domain];
5308 mtx_lock(&pvc->pvc_lock);
5309 pvc->active_reclaims++;
5310 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5311 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5312 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5313 SLIST_EMPTY(&free)) {
5314 next_pmap = pc->pc_pmap;
5315 if (next_pmap == NULL) {
5317 * The next chunk is a marker. However, it is
5318 * not our marker, so active_reclaims must be
5319 * > 1. Consequently, the next_chunk code
5320 * will not rotate the pv_chunks list.
5324 mtx_unlock(&pvc->pvc_lock);
5327 * A pv_chunk can only be removed from the pc_lru list
5328 * when both pc_chunks_mutex is owned and the
5329 * corresponding pmap is locked.
5331 if (pmap != next_pmap) {
5333 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5336 /* Avoid deadlock and lock recursion. */
5337 if (pmap > locked_pmap) {
5338 RELEASE_PV_LIST_LOCK(lockp);
5341 pmap_delayed_invl_start();
5342 mtx_lock(&pvc->pvc_lock);
5344 } else if (pmap != locked_pmap) {
5345 if (PMAP_TRYLOCK(pmap)) {
5347 pmap_delayed_invl_start();
5348 mtx_lock(&pvc->pvc_lock);
5351 pmap = NULL; /* pmap is not locked */
5352 mtx_lock(&pvc->pvc_lock);
5353 pc = TAILQ_NEXT(pc_marker, pc_lru);
5355 pc->pc_pmap != next_pmap)
5359 } else if (start_di)
5360 pmap_delayed_invl_start();
5361 PG_G = pmap_global_bit(pmap);
5362 PG_A = pmap_accessed_bit(pmap);
5363 PG_M = pmap_modified_bit(pmap);
5364 PG_RW = pmap_rw_bit(pmap);
5370 * Destroy every non-wired, 4 KB page mapping in the chunk.
5373 for (field = 0; field < _NPCM; field++) {
5374 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5375 inuse != 0; inuse &= ~(1UL << bit)) {
5377 pv = &pc->pc_pventry[field * 64 + bit];
5379 pde = pmap_pde(pmap, va);
5380 if ((*pde & PG_PS) != 0)
5382 pte = pmap_pde_to_pte(pde, va);
5383 if ((*pte & PG_W) != 0)
5385 tpte = pte_load_clear(pte);
5386 if ((tpte & PG_G) != 0)
5387 pmap_invalidate_page(pmap, va);
5388 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5389 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5391 if ((tpte & PG_A) != 0)
5392 vm_page_aflag_set(m, PGA_REFERENCED);
5393 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5394 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5396 if (TAILQ_EMPTY(&m->md.pv_list) &&
5397 (m->flags & PG_FICTITIOUS) == 0) {
5398 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5399 if (TAILQ_EMPTY(&pvh->pv_list)) {
5400 vm_page_aflag_clear(m,
5404 pmap_delayed_invl_page(m);
5405 pc->pc_map[field] |= 1UL << bit;
5406 pmap_unuse_pt(pmap, va, *pde, &free);
5411 mtx_lock(&pvc->pvc_lock);
5414 /* Every freed mapping is for a 4 KB page. */
5415 pmap_resident_count_adj(pmap, -freed);
5416 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5417 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5418 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5419 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5420 if (pc_is_free(pc)) {
5421 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5422 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5423 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5424 /* Entire chunk is free; return it. */
5425 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5426 dump_drop_page(m_pc->phys_addr);
5427 mtx_lock(&pvc->pvc_lock);
5428 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5431 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5432 mtx_lock(&pvc->pvc_lock);
5433 /* One freed pv entry in locked_pmap is sufficient. */
5434 if (pmap == locked_pmap)
5437 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5438 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5439 if (pvc->active_reclaims == 1 && pmap != NULL) {
5441 * Rotate the pv chunks list so that we do not
5442 * scan the same pv chunks that could not be
5443 * freed (because they contained a wired
5444 * and/or superpage mapping) on every
5445 * invocation of reclaim_pv_chunk().
5447 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5448 MPASS(pc->pc_pmap != NULL);
5449 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5450 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5454 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5455 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5456 pvc->active_reclaims--;
5457 mtx_unlock(&pvc->pvc_lock);
5458 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5459 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5460 m_pc = SLIST_FIRST(&free);
5461 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5462 /* Recycle a freed page table page. */
5463 m_pc->ref_count = 1;
5465 vm_page_free_pages_toq(&free, true);
5470 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5475 domain = PCPU_GET(domain);
5476 for (i = 0; i < vm_ndomains; i++) {
5477 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5480 domain = (domain + 1) % vm_ndomains;
5487 * free the pv_entry back to the free list
5490 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5492 struct pv_chunk *pc;
5493 int idx, field, bit;
5495 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5496 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5497 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5498 PV_STAT(counter_u64_add(pv_entry_count, -1));
5499 pc = pv_to_chunk(pv);
5500 idx = pv - &pc->pc_pventry[0];
5503 pc->pc_map[field] |= 1ul << bit;
5504 if (!pc_is_free(pc)) {
5505 /* 98% of the time, pc is already at the head of the list. */
5506 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5507 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5508 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5512 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5517 free_pv_chunk_dequeued(struct pv_chunk *pc)
5521 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5522 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5523 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5524 counter_u64_add(pv_page_count, -1);
5525 /* entire chunk is free, return it */
5526 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5527 dump_drop_page(m->phys_addr);
5528 vm_page_unwire_noq(m);
5533 free_pv_chunk(struct pv_chunk *pc)
5535 struct pv_chunks_list *pvc;
5537 pvc = &pv_chunks[pc_to_domain(pc)];
5538 mtx_lock(&pvc->pvc_lock);
5539 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5540 mtx_unlock(&pvc->pvc_lock);
5541 free_pv_chunk_dequeued(pc);
5545 free_pv_chunk_batch(struct pv_chunklist *batch)
5547 struct pv_chunks_list *pvc;
5548 struct pv_chunk *pc, *npc;
5551 for (i = 0; i < vm_ndomains; i++) {
5552 if (TAILQ_EMPTY(&batch[i]))
5554 pvc = &pv_chunks[i];
5555 mtx_lock(&pvc->pvc_lock);
5556 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5557 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5559 mtx_unlock(&pvc->pvc_lock);
5562 for (i = 0; i < vm_ndomains; i++) {
5563 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5564 free_pv_chunk_dequeued(pc);
5570 * Returns a new PV entry, allocating a new PV chunk from the system when
5571 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5572 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5575 * The given PV list lock may be released.
5578 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5580 struct pv_chunks_list *pvc;
5583 struct pv_chunk *pc;
5586 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5587 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5589 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5591 for (field = 0; field < _NPCM; field++) {
5592 if (pc->pc_map[field]) {
5593 bit = bsfq(pc->pc_map[field]);
5597 if (field < _NPCM) {
5598 pv = &pc->pc_pventry[field * 64 + bit];
5599 pc->pc_map[field] &= ~(1ul << bit);
5600 /* If this was the last item, move it to tail */
5601 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
5602 pc->pc_map[2] == 0) {
5603 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5604 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5607 PV_STAT(counter_u64_add(pv_entry_count, 1));
5608 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5612 /* No free items, allocate another chunk */
5613 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5615 if (lockp == NULL) {
5616 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5619 m = reclaim_pv_chunk(pmap, lockp);
5623 counter_u64_add(pv_page_count, 1);
5624 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5625 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5626 dump_add_page(m->phys_addr);
5627 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5629 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5630 pc->pc_map[1] = PC_FREEN;
5631 pc->pc_map[2] = PC_FREEL;
5632 pvc = &pv_chunks[vm_page_domain(m)];
5633 mtx_lock(&pvc->pvc_lock);
5634 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5635 mtx_unlock(&pvc->pvc_lock);
5636 pv = &pc->pc_pventry[0];
5637 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5638 PV_STAT(counter_u64_add(pv_entry_count, 1));
5639 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5644 * Returns the number of one bits within the given PV chunk map.
5646 * The erratas for Intel processors state that "POPCNT Instruction May
5647 * Take Longer to Execute Than Expected". It is believed that the
5648 * issue is the spurious dependency on the destination register.
5649 * Provide a hint to the register rename logic that the destination
5650 * value is overwritten, by clearing it, as suggested in the
5651 * optimization manual. It should be cheap for unaffected processors
5654 * Reference numbers for erratas are
5655 * 4th Gen Core: HSD146
5656 * 5th Gen Core: BDM85
5657 * 6th Gen Core: SKL029
5660 popcnt_pc_map_pq(uint64_t *map)
5664 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5665 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5666 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5667 : "=&r" (result), "=&r" (tmp)
5668 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5673 * Ensure that the number of spare PV entries in the specified pmap meets or
5674 * exceeds the given count, "needed".
5676 * The given PV list lock may be released.
5679 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5681 struct pv_chunks_list *pvc;
5682 struct pch new_tail[PMAP_MEMDOM];
5683 struct pv_chunk *pc;
5688 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5689 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5692 * Newly allocated PV chunks must be stored in a private list until
5693 * the required number of PV chunks have been allocated. Otherwise,
5694 * reclaim_pv_chunk() could recycle one of these chunks. In
5695 * contrast, these chunks must be added to the pmap upon allocation.
5697 for (i = 0; i < PMAP_MEMDOM; i++)
5698 TAILQ_INIT(&new_tail[i]);
5701 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5703 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5704 bit_count((bitstr_t *)pc->pc_map, 0,
5705 sizeof(pc->pc_map) * NBBY, &free);
5708 free = popcnt_pc_map_pq(pc->pc_map);
5712 if (avail >= needed)
5715 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5716 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5718 m = reclaim_pv_chunk(pmap, lockp);
5723 counter_u64_add(pv_page_count, 1);
5724 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5725 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5726 dump_add_page(m->phys_addr);
5727 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5729 pc->pc_map[0] = PC_FREEN;
5730 pc->pc_map[1] = PC_FREEN;
5731 pc->pc_map[2] = PC_FREEL;
5732 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5733 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5734 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5737 * The reclaim might have freed a chunk from the current pmap.
5738 * If that chunk contained available entries, we need to
5739 * re-count the number of available entries.
5744 for (i = 0; i < vm_ndomains; i++) {
5745 if (TAILQ_EMPTY(&new_tail[i]))
5747 pvc = &pv_chunks[i];
5748 mtx_lock(&pvc->pvc_lock);
5749 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5750 mtx_unlock(&pvc->pvc_lock);
5755 * First find and then remove the pv entry for the specified pmap and virtual
5756 * address from the specified pv list. Returns the pv entry if found and NULL
5757 * otherwise. This operation can be performed on pv lists for either 4KB or
5758 * 2MB page mappings.
5760 static __inline pv_entry_t
5761 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5765 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5766 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5767 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5776 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5777 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5778 * entries for each of the 4KB page mappings.
5781 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5782 struct rwlock **lockp)
5784 struct md_page *pvh;
5785 struct pv_chunk *pc;
5787 vm_offset_t va_last;
5791 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5792 KASSERT((pa & PDRMASK) == 0,
5793 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5794 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5797 * Transfer the 2mpage's pv entry for this mapping to the first
5798 * page's pv list. Once this transfer begins, the pv list lock
5799 * must not be released until the last pv entry is reinstantiated.
5801 pvh = pa_to_pvh(pa);
5802 va = trunc_2mpage(va);
5803 pv = pmap_pvh_remove(pvh, pmap, va);
5804 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5805 m = PHYS_TO_VM_PAGE(pa);
5806 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5808 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5809 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5810 va_last = va + NBPDR - PAGE_SIZE;
5812 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5813 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
5814 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
5815 for (field = 0; field < _NPCM; field++) {
5816 while (pc->pc_map[field]) {
5817 bit = bsfq(pc->pc_map[field]);
5818 pc->pc_map[field] &= ~(1ul << bit);
5819 pv = &pc->pc_pventry[field * 64 + bit];
5823 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5824 ("pmap_pv_demote_pde: page %p is not managed", m));
5825 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5831 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5832 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5835 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
5836 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5837 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5839 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5840 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5843 #if VM_NRESERVLEVEL > 0
5845 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5846 * replace the many pv entries for the 4KB page mappings by a single pv entry
5847 * for the 2MB page mapping.
5850 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5851 struct rwlock **lockp)
5853 struct md_page *pvh;
5855 vm_offset_t va_last;
5858 KASSERT((pa & PDRMASK) == 0,
5859 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5860 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5863 * Transfer the first page's pv entry for this mapping to the 2mpage's
5864 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5865 * a transfer avoids the possibility that get_pv_entry() calls
5866 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5867 * mappings that is being promoted.
5869 m = PHYS_TO_VM_PAGE(pa);
5870 va = trunc_2mpage(va);
5871 pv = pmap_pvh_remove(&m->md, pmap, va);
5872 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5873 pvh = pa_to_pvh(pa);
5874 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5876 /* Free the remaining NPTEPG - 1 pv entries. */
5877 va_last = va + NBPDR - PAGE_SIZE;
5881 pmap_pvh_free(&m->md, pmap, va);
5882 } while (va < va_last);
5884 #endif /* VM_NRESERVLEVEL > 0 */
5887 * First find and then destroy the pv entry for the specified pmap and virtual
5888 * address. This operation can be performed on pv lists for either 4KB or 2MB
5892 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5896 pv = pmap_pvh_remove(pvh, pmap, va);
5897 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5898 free_pv_entry(pmap, pv);
5902 * Conditionally create the PV entry for a 4KB page mapping if the required
5903 * memory can be allocated without resorting to reclamation.
5906 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5907 struct rwlock **lockp)
5911 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5912 /* Pass NULL instead of the lock pointer to disable reclamation. */
5913 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5915 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5916 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5924 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5925 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5926 * false if the PV entry cannot be allocated without resorting to reclamation.
5929 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5930 struct rwlock **lockp)
5932 struct md_page *pvh;
5936 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5937 /* Pass NULL instead of the lock pointer to disable reclamation. */
5938 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5939 NULL : lockp)) == NULL)
5942 pa = pde & PG_PS_FRAME;
5943 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5944 pvh = pa_to_pvh(pa);
5945 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5951 * Fills a page table page with mappings to consecutive physical pages.
5954 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5958 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5960 newpte += PAGE_SIZE;
5965 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5966 * mapping is invalidated.
5969 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5971 struct rwlock *lock;
5975 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5982 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5986 pt_entry_t *xpte, *ypte;
5988 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5989 xpte++, newpte += PAGE_SIZE) {
5990 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
5991 printf("pmap_demote_pde: xpte %zd and newpte map "
5992 "different pages: found %#lx, expected %#lx\n",
5993 xpte - firstpte, *xpte, newpte);
5994 printf("page table dump\n");
5995 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
5996 printf("%zd %#lx\n", ypte - firstpte, *ypte);
6001 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
6002 ("pmap_demote_pde: firstpte and newpte map different physical"
6009 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6010 pd_entry_t oldpde, struct rwlock **lockp)
6012 struct spglist free;
6016 sva = trunc_2mpage(va);
6017 pmap_remove_pde(pmap, pde, sva, &free, lockp);
6018 if ((oldpde & pmap_global_bit(pmap)) == 0)
6019 pmap_invalidate_pde_page(pmap, sva, oldpde);
6020 vm_page_free_pages_toq(&free, true);
6021 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
6026 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
6027 struct rwlock **lockp)
6029 pd_entry_t newpde, oldpde;
6030 pt_entry_t *firstpte, newpte;
6031 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6037 PG_A = pmap_accessed_bit(pmap);
6038 PG_G = pmap_global_bit(pmap);
6039 PG_M = pmap_modified_bit(pmap);
6040 PG_RW = pmap_rw_bit(pmap);
6041 PG_V = pmap_valid_bit(pmap);
6042 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6043 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6045 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6046 in_kernel = va >= VM_MAXUSER_ADDRESS;
6048 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
6049 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
6052 * Invalidate the 2MB page mapping and return "failure" if the
6053 * mapping was never accessed.
6055 if ((oldpde & PG_A) == 0) {
6056 KASSERT((oldpde & PG_W) == 0,
6057 ("pmap_demote_pde: a wired mapping is missing PG_A"));
6058 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6062 mpte = pmap_remove_pt_page(pmap, va);
6064 KASSERT((oldpde & PG_W) == 0,
6065 ("pmap_demote_pde: page table page for a wired mapping"
6069 * If the page table page is missing and the mapping
6070 * is for a kernel address, the mapping must belong to
6071 * the direct map. Page table pages are preallocated
6072 * for every other part of the kernel address space,
6073 * so the direct map region is the only part of the
6074 * kernel address space that must be handled here.
6076 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6077 va < DMAP_MAX_ADDRESS),
6078 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6081 * If the 2MB page mapping belongs to the direct map
6082 * region of the kernel's address space, then the page
6083 * allocation request specifies the highest possible
6084 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6085 * priority is normal.
6087 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6088 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6091 * If the allocation of the new page table page fails,
6092 * invalidate the 2MB page mapping and return "failure".
6095 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6100 mpte->ref_count = NPTEPG;
6102 mptepa = VM_PAGE_TO_PHYS(mpte);
6103 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6104 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6105 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6106 ("pmap_demote_pde: oldpde is missing PG_M"));
6107 newpte = oldpde & ~PG_PS;
6108 newpte = pmap_swap_pat(pmap, newpte);
6111 * If the PTP is not leftover from an earlier promotion or it does not
6112 * have PG_A set in every PTE, then fill it. The new PTEs will all
6115 if (!vm_page_all_valid(mpte))
6116 pmap_fill_ptp(firstpte, newpte);
6118 pmap_demote_pde_check(firstpte, newpte);
6121 * If the mapping has changed attributes, update the PTEs.
6123 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6124 pmap_fill_ptp(firstpte, newpte);
6127 * The spare PV entries must be reserved prior to demoting the
6128 * mapping, that is, prior to changing the PDE. Otherwise, the state
6129 * of the PDE and the PV lists will be inconsistent, which can result
6130 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6131 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6132 * PV entry for the 2MB page mapping that is being demoted.
6134 if ((oldpde & PG_MANAGED) != 0)
6135 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6138 * Demote the mapping. This pmap is locked. The old PDE has
6139 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6140 * set. Thus, there is no danger of a race with another
6141 * processor changing the setting of PG_A and/or PG_M between
6142 * the read above and the store below.
6144 if (workaround_erratum383)
6145 pmap_update_pde(pmap, va, pde, newpde);
6147 pde_store(pde, newpde);
6150 * Invalidate a stale recursive mapping of the page table page.
6153 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6156 * Demote the PV entry.
6158 if ((oldpde & PG_MANAGED) != 0)
6159 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6161 counter_u64_add(pmap_pde_demotions, 1);
6162 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6168 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6171 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6177 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6178 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6179 mpte = pmap_remove_pt_page(pmap, va);
6181 panic("pmap_remove_kernel_pde: Missing pt page.");
6183 mptepa = VM_PAGE_TO_PHYS(mpte);
6184 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6187 * If this page table page was unmapped by a promotion, then it
6188 * contains valid mappings. Zero it to invalidate those mappings.
6190 if (vm_page_any_valid(mpte))
6191 pagezero((void *)PHYS_TO_DMAP(mptepa));
6194 * Demote the mapping.
6196 if (workaround_erratum383)
6197 pmap_update_pde(pmap, va, pde, newpde);
6199 pde_store(pde, newpde);
6202 * Invalidate a stale recursive mapping of the page table page.
6204 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6208 * pmap_remove_pde: do the things to unmap a superpage in a process
6211 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6212 struct spglist *free, struct rwlock **lockp)
6214 struct md_page *pvh;
6216 vm_offset_t eva, va;
6218 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6220 PG_G = pmap_global_bit(pmap);
6221 PG_A = pmap_accessed_bit(pmap);
6222 PG_M = pmap_modified_bit(pmap);
6223 PG_RW = pmap_rw_bit(pmap);
6225 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6226 KASSERT((sva & PDRMASK) == 0,
6227 ("pmap_remove_pde: sva is not 2mpage aligned"));
6228 oldpde = pte_load_clear(pdq);
6230 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6231 if ((oldpde & PG_G) != 0)
6232 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6233 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6234 if (oldpde & PG_MANAGED) {
6235 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6236 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6237 pmap_pvh_free(pvh, pmap, sva);
6239 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6240 va < eva; va += PAGE_SIZE, m++) {
6241 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6244 vm_page_aflag_set(m, PGA_REFERENCED);
6245 if (TAILQ_EMPTY(&m->md.pv_list) &&
6246 TAILQ_EMPTY(&pvh->pv_list))
6247 vm_page_aflag_clear(m, PGA_WRITEABLE);
6248 pmap_delayed_invl_page(m);
6251 if (pmap == kernel_pmap) {
6252 pmap_remove_kernel_pde(pmap, pdq, sva);
6254 mpte = pmap_remove_pt_page(pmap, sva);
6256 KASSERT(vm_page_any_valid(mpte),
6257 ("pmap_remove_pde: pte page not promoted"));
6258 pmap_pt_page_count_adj(pmap, -1);
6259 KASSERT(mpte->ref_count == NPTEPG,
6260 ("pmap_remove_pde: pte page ref count error"));
6261 mpte->ref_count = 0;
6262 pmap_add_delayed_free_list(mpte, free, FALSE);
6265 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6269 * pmap_remove_pte: do the things to unmap a page in a process
6272 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6273 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6275 struct md_page *pvh;
6276 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6279 PG_A = pmap_accessed_bit(pmap);
6280 PG_M = pmap_modified_bit(pmap);
6281 PG_RW = pmap_rw_bit(pmap);
6283 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6284 oldpte = pte_load_clear(ptq);
6286 pmap->pm_stats.wired_count -= 1;
6287 pmap_resident_count_adj(pmap, -1);
6288 if (oldpte & PG_MANAGED) {
6289 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6290 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6293 vm_page_aflag_set(m, PGA_REFERENCED);
6294 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6295 pmap_pvh_free(&m->md, pmap, va);
6296 if (TAILQ_EMPTY(&m->md.pv_list) &&
6297 (m->flags & PG_FICTITIOUS) == 0) {
6298 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6299 if (TAILQ_EMPTY(&pvh->pv_list))
6300 vm_page_aflag_clear(m, PGA_WRITEABLE);
6302 pmap_delayed_invl_page(m);
6304 return (pmap_unuse_pt(pmap, va, ptepde, free));
6308 * Remove a single page from a process address space
6311 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6312 struct spglist *free)
6314 struct rwlock *lock;
6315 pt_entry_t *pte, PG_V;
6317 PG_V = pmap_valid_bit(pmap);
6318 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6319 if ((*pde & PG_V) == 0)
6321 pte = pmap_pde_to_pte(pde, va);
6322 if ((*pte & PG_V) == 0)
6325 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6328 pmap_invalidate_page(pmap, va);
6332 * Removes the specified range of addresses from the page table page.
6335 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6336 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6338 pt_entry_t PG_G, *pte;
6342 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6343 PG_G = pmap_global_bit(pmap);
6346 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6350 pmap_invalidate_range(pmap, va, sva);
6355 if ((*pte & PG_G) == 0)
6359 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6365 pmap_invalidate_range(pmap, va, sva);
6370 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6372 struct rwlock *lock;
6374 vm_offset_t va_next;
6375 pml5_entry_t *pml5e;
6376 pml4_entry_t *pml4e;
6378 pd_entry_t ptpaddr, *pde;
6379 pt_entry_t PG_G, PG_V;
6380 struct spglist free;
6383 PG_G = pmap_global_bit(pmap);
6384 PG_V = pmap_valid_bit(pmap);
6387 * If there are no resident pages besides the top level page
6388 * table page(s), there is nothing to do. Kernel pmap always
6389 * accounts whole preloaded area as resident, which makes its
6390 * resident count > 2.
6391 * Perform an unsynchronized read. This is, however, safe.
6393 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6400 pmap_delayed_invl_start();
6403 pmap_pkru_on_remove(pmap, sva, eva);
6406 * special handling of removing one page. a very
6407 * common operation and easy to short circuit some
6410 if (sva + PAGE_SIZE == eva) {
6411 pde = pmap_pde(pmap, sva);
6412 if (pde && (*pde & PG_PS) == 0) {
6413 pmap_remove_page(pmap, sva, pde, &free);
6419 for (; sva < eva; sva = va_next) {
6420 if (pmap->pm_stats.resident_count == 0)
6423 if (pmap_is_la57(pmap)) {
6424 pml5e = pmap_pml5e(pmap, sva);
6425 if ((*pml5e & PG_V) == 0) {
6426 va_next = (sva + NBPML5) & ~PML5MASK;
6431 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6433 pml4e = pmap_pml4e(pmap, sva);
6435 if ((*pml4e & PG_V) == 0) {
6436 va_next = (sva + NBPML4) & ~PML4MASK;
6442 va_next = (sva + NBPDP) & ~PDPMASK;
6445 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6446 if ((*pdpe & PG_V) == 0)
6448 if ((*pdpe & PG_PS) != 0) {
6449 KASSERT(va_next <= eva,
6450 ("partial update of non-transparent 1G mapping "
6451 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6452 *pdpe, sva, eva, va_next));
6453 MPASS(pmap != kernel_pmap); /* XXXKIB */
6454 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6457 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6458 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6459 pmap_unwire_ptp(pmap, sva, mt, &free);
6464 * Calculate index for next page table.
6466 va_next = (sva + NBPDR) & ~PDRMASK;
6470 pde = pmap_pdpe_to_pde(pdpe, sva);
6474 * Weed out invalid mappings.
6480 * Check for large page.
6482 if ((ptpaddr & PG_PS) != 0) {
6484 * Are we removing the entire large page? If not,
6485 * demote the mapping and fall through.
6487 if (sva + NBPDR == va_next && eva >= va_next) {
6489 * The TLB entry for a PG_G mapping is
6490 * invalidated by pmap_remove_pde().
6492 if ((ptpaddr & PG_G) == 0)
6494 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6496 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6498 /* The large page mapping was destroyed. */
6505 * Limit our scan to either the end of the va represented
6506 * by the current page table page, or to the end of the
6507 * range being removed.
6512 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6519 pmap_invalidate_all(pmap);
6521 pmap_delayed_invl_finish();
6522 vm_page_free_pages_toq(&free, true);
6526 * Remove the given range of addresses from the specified map.
6528 * It is assumed that the start and end are properly
6529 * rounded to the page size.
6532 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6534 pmap_remove1(pmap, sva, eva, false);
6538 * Remove the given range of addresses as part of a logical unmap
6539 * operation. This has the effect of calling pmap_remove(), but
6540 * also clears any metadata that should persist for the lifetime
6541 * of a logical mapping.
6544 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6546 pmap_remove1(pmap, sva, eva, true);
6550 * Routine: pmap_remove_all
6552 * Removes this physical page from
6553 * all physical maps in which it resides.
6554 * Reflects back modify bits to the pager.
6557 * Original versions of this routine were very
6558 * inefficient because they iteratively called
6559 * pmap_remove (slow...)
6563 pmap_remove_all(vm_page_t m)
6565 struct md_page *pvh;
6568 struct rwlock *lock;
6569 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6572 struct spglist free;
6573 int pvh_gen, md_gen;
6575 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6576 ("pmap_remove_all: page %p is not managed", m));
6578 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6579 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6580 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6583 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6585 if (!PMAP_TRYLOCK(pmap)) {
6586 pvh_gen = pvh->pv_gen;
6590 if (pvh_gen != pvh->pv_gen) {
6596 pde = pmap_pde(pmap, va);
6597 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6600 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6602 if (!PMAP_TRYLOCK(pmap)) {
6603 pvh_gen = pvh->pv_gen;
6604 md_gen = m->md.pv_gen;
6608 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6613 PG_A = pmap_accessed_bit(pmap);
6614 PG_M = pmap_modified_bit(pmap);
6615 PG_RW = pmap_rw_bit(pmap);
6616 pmap_resident_count_adj(pmap, -1);
6617 pde = pmap_pde(pmap, pv->pv_va);
6618 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6619 " a 2mpage in page %p's pv list", m));
6620 pte = pmap_pde_to_pte(pde, pv->pv_va);
6621 tpte = pte_load_clear(pte);
6623 pmap->pm_stats.wired_count--;
6625 vm_page_aflag_set(m, PGA_REFERENCED);
6628 * Update the vm_page_t clean and reference bits.
6630 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6632 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6633 pmap_invalidate_page(pmap, pv->pv_va);
6634 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6636 free_pv_entry(pmap, pv);
6639 vm_page_aflag_clear(m, PGA_WRITEABLE);
6641 pmap_delayed_invl_wait(m);
6642 vm_page_free_pages_toq(&free, true);
6646 * pmap_protect_pde: do the things to protect a 2mpage in a process
6649 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6651 pd_entry_t newpde, oldpde;
6653 boolean_t anychanged;
6654 pt_entry_t PG_G, PG_M, PG_RW;
6656 PG_G = pmap_global_bit(pmap);
6657 PG_M = pmap_modified_bit(pmap);
6658 PG_RW = pmap_rw_bit(pmap);
6660 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6661 KASSERT((sva & PDRMASK) == 0,
6662 ("pmap_protect_pde: sva is not 2mpage aligned"));
6665 oldpde = newpde = *pde;
6666 if ((prot & VM_PROT_WRITE) == 0) {
6667 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6668 (PG_MANAGED | PG_M | PG_RW)) {
6669 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6670 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6673 newpde &= ~(PG_RW | PG_M);
6675 if ((prot & VM_PROT_EXECUTE) == 0)
6677 if (newpde != oldpde) {
6679 * As an optimization to future operations on this PDE, clear
6680 * PG_PROMOTED. The impending invalidation will remove any
6681 * lingering 4KB page mappings from the TLB.
6683 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6685 if ((oldpde & PG_G) != 0)
6686 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6690 return (anychanged);
6694 * Set the physical protection on the
6695 * specified range of this map as requested.
6698 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6701 vm_offset_t va_next;
6702 pml4_entry_t *pml4e;
6704 pd_entry_t ptpaddr, *pde;
6705 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6706 pt_entry_t obits, pbits;
6707 boolean_t anychanged;
6709 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6710 if (prot == VM_PROT_NONE) {
6711 pmap_remove(pmap, sva, eva);
6715 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6716 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6719 PG_G = pmap_global_bit(pmap);
6720 PG_M = pmap_modified_bit(pmap);
6721 PG_V = pmap_valid_bit(pmap);
6722 PG_RW = pmap_rw_bit(pmap);
6726 * Although this function delays and batches the invalidation
6727 * of stale TLB entries, it does not need to call
6728 * pmap_delayed_invl_start() and
6729 * pmap_delayed_invl_finish(), because it does not
6730 * ordinarily destroy mappings. Stale TLB entries from
6731 * protection-only changes need only be invalidated before the
6732 * pmap lock is released, because protection-only changes do
6733 * not destroy PV entries. Even operations that iterate over
6734 * a physical page's PV list of mappings, like
6735 * pmap_remove_write(), acquire the pmap lock for each
6736 * mapping. Consequently, for protection-only changes, the
6737 * pmap lock suffices to synchronize both page table and TLB
6740 * This function only destroys a mapping if pmap_demote_pde()
6741 * fails. In that case, stale TLB entries are immediately
6746 for (; sva < eva; sva = va_next) {
6747 pml4e = pmap_pml4e(pmap, sva);
6748 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6749 va_next = (sva + NBPML4) & ~PML4MASK;
6755 va_next = (sva + NBPDP) & ~PDPMASK;
6758 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6759 if ((*pdpe & PG_V) == 0)
6761 if ((*pdpe & PG_PS) != 0) {
6762 KASSERT(va_next <= eva,
6763 ("partial update of non-transparent 1G mapping "
6764 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6765 *pdpe, sva, eva, va_next));
6767 obits = pbits = *pdpe;
6768 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6769 MPASS(pmap != kernel_pmap); /* XXXKIB */
6770 if ((prot & VM_PROT_WRITE) == 0)
6771 pbits &= ~(PG_RW | PG_M);
6772 if ((prot & VM_PROT_EXECUTE) == 0)
6775 if (pbits != obits) {
6776 if (!atomic_cmpset_long(pdpe, obits, pbits))
6777 /* PG_PS cannot be cleared under us, */
6784 va_next = (sva + NBPDR) & ~PDRMASK;
6788 pde = pmap_pdpe_to_pde(pdpe, sva);
6792 * Weed out invalid mappings.
6798 * Check for large page.
6800 if ((ptpaddr & PG_PS) != 0) {
6802 * Are we protecting the entire large page? If not,
6803 * demote the mapping and fall through.
6805 if (sva + NBPDR == va_next && eva >= va_next) {
6807 * The TLB entry for a PG_G mapping is
6808 * invalidated by pmap_protect_pde().
6810 if (pmap_protect_pde(pmap, pde, sva, prot))
6813 } else if (!pmap_demote_pde(pmap, pde, sva)) {
6815 * The large page mapping was destroyed.
6824 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6827 obits = pbits = *pte;
6828 if ((pbits & PG_V) == 0)
6831 if ((prot & VM_PROT_WRITE) == 0) {
6832 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6833 (PG_MANAGED | PG_M | PG_RW)) {
6834 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6837 pbits &= ~(PG_RW | PG_M);
6839 if ((prot & VM_PROT_EXECUTE) == 0)
6842 if (pbits != obits) {
6843 if (!atomic_cmpset_long(pte, obits, pbits))
6846 pmap_invalidate_page(pmap, sva);
6853 pmap_invalidate_all(pmap);
6858 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6861 if (pmap->pm_type != PT_EPT)
6863 return ((pde & EPT_PG_EXECUTE) != 0);
6866 #if VM_NRESERVLEVEL > 0
6868 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6869 * single page table page (PTP) to a single 2MB page mapping. For promotion
6870 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6871 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6872 * identical characteristics.
6875 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6876 struct rwlock **lockp)
6879 pt_entry_t *firstpte, oldpte, pa, *pte;
6880 pt_entry_t allpte_PG_A, PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6883 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6884 if (!pmap_ps_enabled(pmap))
6887 PG_A = pmap_accessed_bit(pmap);
6888 PG_G = pmap_global_bit(pmap);
6889 PG_M = pmap_modified_bit(pmap);
6890 PG_V = pmap_valid_bit(pmap);
6891 PG_RW = pmap_rw_bit(pmap);
6892 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6893 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6896 * Examine the first PTE in the specified PTP. Abort if this PTE is
6897 * ineligible for promotion due to hardware errata, invalid, or does
6898 * not map the first 4KB physical page within a 2MB page.
6900 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6902 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6904 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6905 counter_u64_add(pmap_pde_p_failures, 1);
6906 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6907 " in pmap %p", va, pmap);
6912 * Both here and in the below "for" loop, to allow for repromotion
6913 * after MADV_FREE, conditionally write protect a clean PTE before
6914 * possibly aborting the promotion due to other PTE attributes. Why?
6915 * Suppose that MADV_FREE is applied to a part of a superpage, the
6916 * address range [S, E). pmap_advise() will demote the superpage
6917 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6918 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6919 * imagine that the memory in [S, E) is recycled, but the last 4KB
6920 * page in [S, E) is not the last to be rewritten, or simply accessed.
6921 * In other words, there is still a 4KB page in [S, E), call it P,
6922 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6923 * we write protect P before aborting the promotion, if and when P is
6924 * finally rewritten, there won't be a page fault to trigger
6928 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6930 * When PG_M is already clear, PG_RW can be cleared without
6931 * a TLB invalidation.
6933 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6936 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6937 " in pmap %p", va & ~PDRMASK, pmap);
6941 * Examine each of the other PTEs in the specified PTP. Abort if this
6942 * PTE maps an unexpected 4KB physical page or does not have identical
6943 * characteristics to the first PTE.
6945 allpte_PG_A = newpde & PG_A;
6946 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6947 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6949 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6950 counter_u64_add(pmap_pde_p_failures, 1);
6951 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6952 " in pmap %p", va, pmap);
6956 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6958 * When PG_M is already clear, PG_RW can be cleared
6959 * without a TLB invalidation.
6961 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6964 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6965 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6966 (va & ~PDRMASK), pmap);
6968 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6969 counter_u64_add(pmap_pde_p_failures, 1);
6970 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6971 " in pmap %p", va, pmap);
6974 allpte_PG_A &= oldpte;
6979 * Unless all PTEs have PG_A set, clear it from the superpage mapping,
6980 * so that promotions triggered by speculative mappings, such as
6981 * pmap_enter_quick(), don't automatically mark the underlying pages
6984 newpde &= ~PG_A | allpte_PG_A;
6987 * EPT PTEs with PG_M set and PG_A clear are not supported by early
6988 * MMUs supporting EPT.
6990 KASSERT((newpde & PG_A) != 0 || safe_to_clear_referenced(pmap, newpde),
6991 ("unsupported EPT PTE"));
6994 * Save the PTP in its current state until the PDE mapping the
6995 * superpage is demoted by pmap_demote_pde() or destroyed by
6996 * pmap_remove_pde(). If PG_A is not set in every PTE, then request
6997 * that the PTP be refilled on demotion.
7000 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7001 KASSERT(mpte >= vm_page_array &&
7002 mpte < &vm_page_array[vm_page_array_size],
7003 ("pmap_promote_pde: page table page is out of range"));
7004 KASSERT(mpte->pindex == pmap_pde_pindex(va),
7005 ("pmap_promote_pde: page table page's pindex is wrong "
7006 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
7007 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
7008 if (pmap_insert_pt_page(pmap, mpte, true, allpte_PG_A != 0)) {
7009 counter_u64_add(pmap_pde_p_failures, 1);
7011 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
7017 * Promote the pv entries.
7019 if ((newpde & PG_MANAGED) != 0)
7020 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
7023 * Propagate the PAT index to its proper position.
7025 newpde = pmap_swap_pat(pmap, newpde);
7028 * Map the superpage.
7030 if (workaround_erratum383)
7031 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
7033 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
7035 counter_u64_add(pmap_pde_promotions, 1);
7036 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
7037 " in pmap %p", va, pmap);
7040 #endif /* VM_NRESERVLEVEL > 0 */
7043 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
7047 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
7049 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7050 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
7051 ("psind %d unexpected", psind));
7052 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
7053 ("unaligned phys address %#lx newpte %#lx psind %d",
7054 newpte & PG_FRAME, newpte, psind));
7055 KASSERT((va & (pagesizes[psind] - 1)) == 0,
7056 ("unaligned va %#lx psind %d", va, psind));
7057 KASSERT(va < VM_MAXUSER_ADDRESS,
7058 ("kernel mode non-transparent superpage")); /* XXXKIB */
7059 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
7060 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
7062 PG_V = pmap_valid_bit(pmap);
7065 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind]))
7066 return (KERN_PROTECTION_FAILURE);
7068 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7069 pten |= pmap_pkru_get(pmap, va);
7071 if (psind == 2) { /* 1G */
7072 pml4e = pmap_pml4e(pmap, va);
7073 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7074 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7078 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7079 pdpe = &pdpe[pmap_pdpe_index(va)];
7081 MPASS(origpte == 0);
7083 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7084 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7086 if ((origpte & PG_V) == 0) {
7087 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7092 } else /* (psind == 1) */ { /* 2M */
7093 pde = pmap_pde(pmap, va);
7095 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7099 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7100 pde = &pde[pmap_pde_index(va)];
7102 MPASS(origpte == 0);
7105 if ((origpte & PG_V) == 0) {
7106 pdpe = pmap_pdpe(pmap, va);
7107 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7108 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7114 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7115 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7116 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7117 va, psind == 2 ? "1G" : "2M", origpte, pten));
7118 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7119 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7120 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7121 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7122 if ((origpte & PG_V) == 0)
7123 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7125 return (KERN_SUCCESS);
7128 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7129 return (KERN_RESOURCE_SHORTAGE);
7137 * Insert the given physical page (p) at
7138 * the specified virtual address (v) in the
7139 * target physical map with the protection requested.
7141 * If specified, the page will be wired down, meaning
7142 * that the related pte can not be reclaimed.
7144 * NB: This is the only routine which MAY NOT lazy-evaluate
7145 * or lose information. That is, this routine must actually
7146 * insert this page into the given map NOW.
7148 * When destroying both a page table and PV entry, this function
7149 * performs the TLB invalidation before releasing the PV list
7150 * lock, so we do not need pmap_delayed_invl_page() calls here.
7153 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7154 u_int flags, int8_t psind)
7156 struct rwlock *lock;
7158 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7159 pt_entry_t newpte, origpte;
7166 PG_A = pmap_accessed_bit(pmap);
7167 PG_G = pmap_global_bit(pmap);
7168 PG_M = pmap_modified_bit(pmap);
7169 PG_V = pmap_valid_bit(pmap);
7170 PG_RW = pmap_rw_bit(pmap);
7172 va = trunc_page(va);
7173 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7174 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7175 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7177 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7178 ("pmap_enter: managed mapping within the clean submap"));
7179 if ((m->oflags & VPO_UNMANAGED) == 0)
7180 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7181 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7182 ("pmap_enter: flags %u has reserved bits set", flags));
7183 pa = VM_PAGE_TO_PHYS(m);
7184 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7185 if ((flags & VM_PROT_WRITE) != 0)
7187 if ((prot & VM_PROT_WRITE) != 0)
7189 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7190 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7191 if ((prot & VM_PROT_EXECUTE) == 0)
7193 if ((flags & PMAP_ENTER_WIRED) != 0)
7195 if (va < VM_MAXUSER_ADDRESS)
7197 if (pmap == kernel_pmap)
7199 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7202 * Set modified bit gratuitously for writeable mappings if
7203 * the page is unmanaged. We do not want to take a fault
7204 * to do the dirty bit accounting for these mappings.
7206 if ((m->oflags & VPO_UNMANAGED) != 0) {
7207 if ((newpte & PG_RW) != 0)
7210 newpte |= PG_MANAGED;
7214 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7215 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7216 ("managed largepage va %#lx flags %#x", va, flags));
7217 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7222 /* Assert the required virtual and physical alignment. */
7223 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7224 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7225 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7231 * In the case that a page table page is not
7232 * resident, we are creating it here.
7235 pde = pmap_pde(pmap, va);
7236 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7237 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7238 pte = pmap_pde_to_pte(pde, va);
7239 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7240 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7243 } else if (va < VM_MAXUSER_ADDRESS) {
7245 * Here if the pte page isn't mapped, or if it has been
7248 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7249 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7250 nosleep ? NULL : &lock, va);
7251 if (mpte == NULL && nosleep) {
7252 rv = KERN_RESOURCE_SHORTAGE;
7257 panic("pmap_enter: invalid page directory va=%#lx", va);
7261 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7262 newpte |= pmap_pkru_get(pmap, va);
7265 * Is the specified virtual address already mapped?
7267 if ((origpte & PG_V) != 0) {
7269 * Wiring change, just update stats. We don't worry about
7270 * wiring PT pages as they remain resident as long as there
7271 * are valid mappings in them. Hence, if a user page is wired,
7272 * the PT page will be also.
7274 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7275 pmap->pm_stats.wired_count++;
7276 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7277 pmap->pm_stats.wired_count--;
7280 * Remove the extra PT page reference.
7284 KASSERT(mpte->ref_count > 0,
7285 ("pmap_enter: missing reference to page table page,"
7290 * Has the physical page changed?
7292 opa = origpte & PG_FRAME;
7295 * No, might be a protection or wiring change.
7297 if ((origpte & PG_MANAGED) != 0 &&
7298 (newpte & PG_RW) != 0)
7299 vm_page_aflag_set(m, PGA_WRITEABLE);
7300 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7306 * The physical page has changed. Temporarily invalidate
7307 * the mapping. This ensures that all threads sharing the
7308 * pmap keep a consistent view of the mapping, which is
7309 * necessary for the correct handling of COW faults. It
7310 * also permits reuse of the old mapping's PV entry,
7311 * avoiding an allocation.
7313 * For consistency, handle unmanaged mappings the same way.
7315 origpte = pte_load_clear(pte);
7316 KASSERT((origpte & PG_FRAME) == opa,
7317 ("pmap_enter: unexpected pa update for %#lx", va));
7318 if ((origpte & PG_MANAGED) != 0) {
7319 om = PHYS_TO_VM_PAGE(opa);
7322 * The pmap lock is sufficient to synchronize with
7323 * concurrent calls to pmap_page_test_mappings() and
7324 * pmap_ts_referenced().
7326 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7328 if ((origpte & PG_A) != 0) {
7329 pmap_invalidate_page(pmap, va);
7330 vm_page_aflag_set(om, PGA_REFERENCED);
7332 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7333 pv = pmap_pvh_remove(&om->md, pmap, va);
7335 ("pmap_enter: no PV entry for %#lx", va));
7336 if ((newpte & PG_MANAGED) == 0)
7337 free_pv_entry(pmap, pv);
7338 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7339 TAILQ_EMPTY(&om->md.pv_list) &&
7340 ((om->flags & PG_FICTITIOUS) != 0 ||
7341 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7342 vm_page_aflag_clear(om, PGA_WRITEABLE);
7345 * Since this mapping is unmanaged, assume that PG_A
7348 pmap_invalidate_page(pmap, va);
7353 * Increment the counters.
7355 if ((newpte & PG_W) != 0)
7356 pmap->pm_stats.wired_count++;
7357 pmap_resident_count_adj(pmap, 1);
7361 * Enter on the PV list if part of our managed memory.
7363 if ((newpte & PG_MANAGED) != 0) {
7365 pv = get_pv_entry(pmap, &lock);
7368 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7369 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7371 if ((newpte & PG_RW) != 0)
7372 vm_page_aflag_set(m, PGA_WRITEABLE);
7378 if ((origpte & PG_V) != 0) {
7380 origpte = pte_load_store(pte, newpte);
7381 KASSERT((origpte & PG_FRAME) == pa,
7382 ("pmap_enter: unexpected pa update for %#lx", va));
7383 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7385 if ((origpte & PG_MANAGED) != 0)
7389 * Although the PTE may still have PG_RW set, TLB
7390 * invalidation may nonetheless be required because
7391 * the PTE no longer has PG_M set.
7393 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7395 * This PTE change does not require TLB invalidation.
7399 if ((origpte & PG_A) != 0)
7400 pmap_invalidate_page(pmap, va);
7402 pte_store(pte, newpte);
7406 #if VM_NRESERVLEVEL > 0
7408 * If both the page table page and the reservation are fully
7409 * populated, then attempt promotion.
7411 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7412 (m->flags & PG_FICTITIOUS) == 0 &&
7413 vm_reserv_level_iffullpop(m) == 0)
7414 (void)pmap_promote_pde(pmap, pde, va, mpte, &lock);
7426 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7427 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7428 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7429 * "no replace", and "no reclaim" are specified.
7432 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7433 struct rwlock **lockp)
7438 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7439 PG_V = pmap_valid_bit(pmap);
7440 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
7442 if ((m->oflags & VPO_UNMANAGED) == 0)
7443 newpde |= PG_MANAGED;
7444 if ((prot & VM_PROT_EXECUTE) == 0)
7446 if (va < VM_MAXUSER_ADDRESS)
7448 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7449 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7453 * Returns true if every page table entry in the specified page table page is
7457 pmap_every_pte_zero(vm_paddr_t pa)
7459 pt_entry_t *pt_end, *pte;
7461 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7462 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7463 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7471 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7472 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7473 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7474 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7475 * page mapping already exists within the 2MB virtual address range starting
7476 * at the specified virtual address or (2) the requested 2MB page mapping is
7477 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7478 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7479 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7480 * settings are not the same across the 2MB virtual address range starting at
7481 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7482 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7483 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7486 * The parameter "m" is only used when creating a managed, writeable mapping.
7489 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7490 vm_page_t m, struct rwlock **lockp)
7492 struct spglist free;
7493 pd_entry_t oldpde, *pde;
7494 pt_entry_t PG_G, PG_RW, PG_V;
7498 PG_G = pmap_global_bit(pmap);
7499 PG_RW = pmap_rw_bit(pmap);
7500 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7501 ("pmap_enter_pde: newpde is missing PG_M"));
7502 PG_V = pmap_valid_bit(pmap);
7503 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7505 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7507 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7508 " in pmap %p", va, pmap);
7509 return (KERN_FAILURE);
7511 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7512 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7513 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7514 " in pmap %p", va, pmap);
7515 return (KERN_RESOURCE_SHORTAGE);
7519 * If pkru is not same for the whole pde range, return failure
7520 * and let vm_fault() cope. Check after pde allocation, since
7523 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
7524 pmap_abort_ptp(pmap, va, pdpg);
7525 return (KERN_PROTECTION_FAILURE);
7527 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
7528 newpde &= ~X86_PG_PKU_MASK;
7529 newpde |= pmap_pkru_get(pmap, va);
7533 * If there are existing mappings, either abort or remove them.
7536 if ((oldpde & PG_V) != 0) {
7537 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7538 ("pmap_enter_pde: pdpg's reference count is too low"));
7539 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7540 if ((oldpde & PG_PS) != 0) {
7544 "pmap_enter_pde: no space for va %#lx"
7545 " in pmap %p", va, pmap);
7546 return (KERN_NO_SPACE);
7547 } else if (va < VM_MAXUSER_ADDRESS ||
7548 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7552 "pmap_enter_pde: failure for va %#lx"
7553 " in pmap %p", va, pmap);
7554 return (KERN_FAILURE);
7557 /* Break the existing mapping(s). */
7559 if ((oldpde & PG_PS) != 0) {
7561 * The reference to the PD page that was acquired by
7562 * pmap_alloc_pde() ensures that it won't be freed.
7563 * However, if the PDE resulted from a promotion, then
7564 * a reserved PT page could be freed.
7566 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7567 if ((oldpde & PG_G) == 0)
7568 pmap_invalidate_pde_page(pmap, va, oldpde);
7570 pmap_delayed_invl_start();
7571 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7573 pmap_invalidate_all(pmap);
7574 pmap_delayed_invl_finish();
7576 if (va < VM_MAXUSER_ADDRESS) {
7577 vm_page_free_pages_toq(&free, true);
7578 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7581 KASSERT(SLIST_EMPTY(&free),
7582 ("pmap_enter_pde: freed kernel page table page"));
7585 * Both pmap_remove_pde() and pmap_remove_ptes() will
7586 * leave the kernel page table page zero filled.
7588 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7589 if (pmap_insert_pt_page(pmap, mt, false, false))
7590 panic("pmap_enter_pde: trie insert failed");
7595 * Allocate leaf ptpage for wired userspace pages.
7598 if ((newpde & PG_W) != 0 && pmap != kernel_pmap) {
7599 uwptpg = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
7602 return (KERN_RESOURCE_SHORTAGE);
7603 if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
7604 pmap_free_pt_page(pmap, uwptpg, false);
7605 return (KERN_RESOURCE_SHORTAGE);
7608 uwptpg->ref_count = NPTEPG;
7610 if ((newpde & PG_MANAGED) != 0) {
7612 * Abort this mapping if its PV entry could not be created.
7614 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7616 pmap_abort_ptp(pmap, va, pdpg);
7617 if (uwptpg != NULL) {
7618 mt = pmap_remove_pt_page(pmap, va);
7619 KASSERT(mt == uwptpg,
7620 ("removed pt page %p, expected %p", mt,
7622 uwptpg->ref_count = 1;
7623 pmap_free_pt_page(pmap, uwptpg, false);
7625 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7626 " in pmap %p", va, pmap);
7627 return (KERN_RESOURCE_SHORTAGE);
7629 if ((newpde & PG_RW) != 0) {
7630 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7631 vm_page_aflag_set(mt, PGA_WRITEABLE);
7636 * Increment counters.
7638 if ((newpde & PG_W) != 0)
7639 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7640 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7643 * Map the superpage. (This is not a promoted mapping; there will not
7644 * be any lingering 4KB page mappings in the TLB.)
7646 pde_store(pde, newpde);
7648 counter_u64_add(pmap_pde_mappings, 1);
7649 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7651 return (KERN_SUCCESS);
7655 * Maps a sequence of resident pages belonging to the same object.
7656 * The sequence begins with the given page m_start. This page is
7657 * mapped at the given virtual address start. Each subsequent page is
7658 * mapped at a virtual address that is offset from start by the same
7659 * amount as the page is offset from m_start within the object. The
7660 * last page in the sequence is the page with the largest offset from
7661 * m_start that can be mapped at a virtual address less than the given
7662 * virtual address end. Not every virtual page between start and end
7663 * is mapped; only those for which a resident page exists with the
7664 * corresponding offset from m_start are mapped.
7667 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7668 vm_page_t m_start, vm_prot_t prot)
7670 struct rwlock *lock;
7673 vm_pindex_t diff, psize;
7676 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7678 psize = atop(end - start);
7683 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7684 va = start + ptoa(diff);
7685 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7686 m->psind == 1 && pmap_ps_enabled(pmap) &&
7687 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7688 KERN_SUCCESS || rv == KERN_NO_SPACE))
7689 m = &m[NBPDR / PAGE_SIZE - 1];
7691 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7693 m = TAILQ_NEXT(m, listq);
7701 * this code makes some *MAJOR* assumptions:
7702 * 1. Current pmap & pmap exists.
7705 * 4. No page table pages.
7706 * but is *MUCH* faster than pmap_enter...
7710 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7712 struct rwlock *lock;
7716 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7723 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7724 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7727 pt_entry_t newpte, *pte, PG_V;
7729 KASSERT(!VA_IS_CLEANMAP(va) ||
7730 (m->oflags & VPO_UNMANAGED) != 0,
7731 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7732 PG_V = pmap_valid_bit(pmap);
7733 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7737 * In the case that a page table page is not
7738 * resident, we are creating it here.
7740 if (va < VM_MAXUSER_ADDRESS) {
7742 vm_pindex_t ptepindex;
7745 * Calculate pagetable page index
7747 ptepindex = pmap_pde_pindex(va);
7748 if (mpte && (mpte->pindex == ptepindex)) {
7752 * If the page table page is mapped, we just increment
7753 * the hold count, and activate it. Otherwise, we
7754 * attempt to allocate a page table page, passing NULL
7755 * instead of the PV list lock pointer because we don't
7756 * intend to sleep. If this attempt fails, we don't
7757 * retry. Instead, we give up.
7759 pdpe = pmap_pdpe(pmap, va);
7760 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7761 if ((*pdpe & PG_PS) != 0)
7763 pde = pmap_pdpe_to_pde(pdpe, va);
7764 if ((*pde & PG_V) != 0) {
7765 if ((*pde & PG_PS) != 0)
7767 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7770 mpte = pmap_allocpte_alloc(pmap,
7771 ptepindex, NULL, va);
7776 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7782 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7783 pte = &pte[pmap_pte_index(va)];
7795 * Enter on the PV list if part of our managed memory.
7797 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7798 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7800 pmap_abort_ptp(pmap, va, mpte);
7805 * Increment counters
7807 pmap_resident_count_adj(pmap, 1);
7809 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7810 pmap_cache_bits(pmap, m->md.pat_mode, 0);
7811 if ((m->oflags & VPO_UNMANAGED) == 0)
7812 newpte |= PG_MANAGED;
7813 if ((prot & VM_PROT_EXECUTE) == 0)
7815 if (va < VM_MAXUSER_ADDRESS)
7816 newpte |= PG_U | pmap_pkru_get(pmap, va);
7817 pte_store(pte, newpte);
7819 #if VM_NRESERVLEVEL > 0
7821 * If both the PTP and the reservation are fully populated, then
7822 * attempt promotion.
7824 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7825 (m->flags & PG_FICTITIOUS) == 0 &&
7826 vm_reserv_level_iffullpop(m) == 0) {
7828 pde = pmap_pde(pmap, va);
7831 * If promotion succeeds, then the next call to this function
7832 * should not be given the unmapped PTP as a hint.
7834 if (pmap_promote_pde(pmap, pde, va, mpte, lockp))
7843 * Make a temporary mapping for a physical address. This is only intended
7844 * to be used for panic dumps.
7847 pmap_kenter_temporary(vm_paddr_t pa, int i)
7851 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7852 pmap_kenter(va, pa);
7853 pmap_invlpg(kernel_pmap, va);
7854 return ((void *)crashdumpmap);
7858 * This code maps large physical mmap regions into the
7859 * processor address space. Note that some shortcuts
7860 * are taken, but the code works.
7863 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7864 vm_pindex_t pindex, vm_size_t size)
7867 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7868 vm_paddr_t pa, ptepa;
7872 PG_A = pmap_accessed_bit(pmap);
7873 PG_M = pmap_modified_bit(pmap);
7874 PG_V = pmap_valid_bit(pmap);
7875 PG_RW = pmap_rw_bit(pmap);
7877 VM_OBJECT_ASSERT_WLOCKED(object);
7878 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7879 ("pmap_object_init_pt: non-device object"));
7880 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7881 if (!pmap_ps_enabled(pmap))
7883 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7885 p = vm_page_lookup(object, pindex);
7886 KASSERT(vm_page_all_valid(p),
7887 ("pmap_object_init_pt: invalid page %p", p));
7888 pat_mode = p->md.pat_mode;
7891 * Abort the mapping if the first page is not physically
7892 * aligned to a 2MB page boundary.
7894 ptepa = VM_PAGE_TO_PHYS(p);
7895 if (ptepa & (NBPDR - 1))
7899 * Skip the first page. Abort the mapping if the rest of
7900 * the pages are not physically contiguous or have differing
7901 * memory attributes.
7903 p = TAILQ_NEXT(p, listq);
7904 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7906 KASSERT(vm_page_all_valid(p),
7907 ("pmap_object_init_pt: invalid page %p", p));
7908 if (pa != VM_PAGE_TO_PHYS(p) ||
7909 pat_mode != p->md.pat_mode)
7911 p = TAILQ_NEXT(p, listq);
7915 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7916 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7917 * will not affect the termination of this loop.
7920 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
7921 pa < ptepa + size; pa += NBPDR) {
7922 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7925 * The creation of mappings below is only an
7926 * optimization. If a page directory page
7927 * cannot be allocated without blocking,
7928 * continue on to the next mapping rather than
7934 if ((*pde & PG_V) == 0) {
7935 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7936 PG_U | PG_RW | PG_V);
7937 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7938 counter_u64_add(pmap_pde_mappings, 1);
7940 /* Continue on if the PDE is already valid. */
7942 KASSERT(pdpg->ref_count > 0,
7943 ("pmap_object_init_pt: missing reference "
7944 "to page directory page, va: 0x%lx", addr));
7953 * Clear the wired attribute from the mappings for the specified range of
7954 * addresses in the given pmap. Every valid mapping within that range
7955 * must have the wired attribute set. In contrast, invalid mappings
7956 * cannot have the wired attribute set, so they are ignored.
7958 * The wired attribute of the page table entry is not a hardware
7959 * feature, so there is no need to invalidate any TLB entries.
7960 * Since pmap_demote_pde() for the wired entry must never fail,
7961 * pmap_delayed_invl_start()/finish() calls around the
7962 * function are not needed.
7965 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7967 vm_offset_t va_next;
7968 pml4_entry_t *pml4e;
7971 pt_entry_t *pte, PG_V, PG_G __diagused;
7973 PG_V = pmap_valid_bit(pmap);
7974 PG_G = pmap_global_bit(pmap);
7976 for (; sva < eva; sva = va_next) {
7977 pml4e = pmap_pml4e(pmap, sva);
7978 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7979 va_next = (sva + NBPML4) & ~PML4MASK;
7985 va_next = (sva + NBPDP) & ~PDPMASK;
7988 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7989 if ((*pdpe & PG_V) == 0)
7991 if ((*pdpe & PG_PS) != 0) {
7992 KASSERT(va_next <= eva,
7993 ("partial update of non-transparent 1G mapping "
7994 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
7995 *pdpe, sva, eva, va_next));
7996 MPASS(pmap != kernel_pmap); /* XXXKIB */
7997 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
7998 atomic_clear_long(pdpe, PG_W);
7999 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
8003 va_next = (sva + NBPDR) & ~PDRMASK;
8006 pde = pmap_pdpe_to_pde(pdpe, sva);
8007 if ((*pde & PG_V) == 0)
8009 if ((*pde & PG_PS) != 0) {
8010 if ((*pde & PG_W) == 0)
8011 panic("pmap_unwire: pde %#jx is missing PG_W",
8015 * Are we unwiring the entire large page? If not,
8016 * demote the mapping and fall through.
8018 if (sva + NBPDR == va_next && eva >= va_next) {
8019 atomic_clear_long(pde, PG_W);
8020 pmap->pm_stats.wired_count -= NBPDR /
8023 } else if (!pmap_demote_pde(pmap, pde, sva))
8024 panic("pmap_unwire: demotion failed");
8028 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
8030 if ((*pte & PG_V) == 0)
8032 if ((*pte & PG_W) == 0)
8033 panic("pmap_unwire: pte %#jx is missing PG_W",
8037 * PG_W must be cleared atomically. Although the pmap
8038 * lock synchronizes access to PG_W, another processor
8039 * could be setting PG_M and/or PG_A concurrently.
8041 atomic_clear_long(pte, PG_W);
8042 pmap->pm_stats.wired_count--;
8049 * Copy the range specified by src_addr/len
8050 * from the source map to the range dst_addr/len
8051 * in the destination map.
8053 * This routine is only advisory and need not do anything.
8056 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
8057 vm_offset_t src_addr)
8059 struct rwlock *lock;
8060 pml4_entry_t *pml4e;
8062 pd_entry_t *pde, srcptepaddr;
8063 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
8064 vm_offset_t addr, end_addr, va_next;
8065 vm_page_t dst_pdpg, dstmpte, srcmpte;
8067 if (dst_addr != src_addr)
8070 if (dst_pmap->pm_type != src_pmap->pm_type)
8074 * EPT page table entries that require emulation of A/D bits are
8075 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
8076 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
8077 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
8078 * implementations flag an EPT misconfiguration for exec-only
8079 * mappings we skip this function entirely for emulated pmaps.
8081 if (pmap_emulate_ad_bits(dst_pmap))
8084 end_addr = src_addr + len;
8086 if (dst_pmap < src_pmap) {
8087 PMAP_LOCK(dst_pmap);
8088 PMAP_LOCK(src_pmap);
8090 PMAP_LOCK(src_pmap);
8091 PMAP_LOCK(dst_pmap);
8094 PG_A = pmap_accessed_bit(dst_pmap);
8095 PG_M = pmap_modified_bit(dst_pmap);
8096 PG_V = pmap_valid_bit(dst_pmap);
8098 for (addr = src_addr; addr < end_addr; addr = va_next) {
8099 KASSERT(addr < UPT_MIN_ADDRESS,
8100 ("pmap_copy: invalid to pmap_copy page tables"));
8102 pml4e = pmap_pml4e(src_pmap, addr);
8103 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8104 va_next = (addr + NBPML4) & ~PML4MASK;
8110 va_next = (addr + NBPDP) & ~PDPMASK;
8113 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
8114 if ((*pdpe & PG_V) == 0)
8116 if ((*pdpe & PG_PS) != 0) {
8117 KASSERT(va_next <= end_addr,
8118 ("partial update of non-transparent 1G mapping "
8119 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8120 *pdpe, addr, end_addr, va_next));
8121 MPASS((addr & PDPMASK) == 0);
8122 MPASS((*pdpe & PG_MANAGED) == 0);
8123 srcptepaddr = *pdpe;
8124 pdpe = pmap_pdpe(dst_pmap, addr);
8126 if (pmap_allocpte_alloc(dst_pmap,
8127 pmap_pml4e_pindex(addr), NULL, addr) ==
8130 pdpe = pmap_pdpe(dst_pmap, addr);
8132 pml4e = pmap_pml4e(dst_pmap, addr);
8133 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8134 dst_pdpg->ref_count++;
8137 ("1G mapping present in dst pmap "
8138 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8139 *pdpe, addr, end_addr, va_next));
8140 *pdpe = srcptepaddr & ~PG_W;
8141 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8145 va_next = (addr + NBPDR) & ~PDRMASK;
8149 pde = pmap_pdpe_to_pde(pdpe, addr);
8151 if (srcptepaddr == 0)
8154 if (srcptepaddr & PG_PS) {
8156 * We can only virtual copy whole superpages.
8158 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8160 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8163 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8164 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8165 PMAP_ENTER_NORECLAIM, &lock))) {
8167 * We leave the dirty bit unchanged because
8168 * managed read/write superpage mappings are
8169 * required to be dirty. However, managed
8170 * superpage mappings are not required to
8171 * have their accessed bit set, so we clear
8172 * it because we don't know if this mapping
8175 srcptepaddr &= ~PG_W;
8176 if ((srcptepaddr & PG_MANAGED) != 0)
8177 srcptepaddr &= ~PG_A;
8179 pmap_resident_count_adj(dst_pmap, NBPDR /
8181 counter_u64_add(pmap_pde_mappings, 1);
8183 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8187 srcptepaddr &= PG_FRAME;
8188 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8189 KASSERT(srcmpte->ref_count > 0,
8190 ("pmap_copy: source page table page is unused"));
8192 if (va_next > end_addr)
8195 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8196 src_pte = &src_pte[pmap_pte_index(addr)];
8198 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8202 * We only virtual copy managed pages.
8204 if ((ptetemp & PG_MANAGED) == 0)
8207 if (dstmpte != NULL) {
8208 KASSERT(dstmpte->pindex ==
8209 pmap_pde_pindex(addr),
8210 ("dstmpte pindex/addr mismatch"));
8211 dstmpte->ref_count++;
8212 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8215 dst_pte = (pt_entry_t *)
8216 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8217 dst_pte = &dst_pte[pmap_pte_index(addr)];
8218 if (*dst_pte == 0 &&
8219 pmap_try_insert_pv_entry(dst_pmap, addr,
8220 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8222 * Clear the wired, modified, and accessed
8223 * (referenced) bits during the copy.
8225 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8226 pmap_resident_count_adj(dst_pmap, 1);
8228 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8231 /* Have we copied all of the valid mappings? */
8232 if (dstmpte->ref_count >= srcmpte->ref_count)
8239 PMAP_UNLOCK(src_pmap);
8240 PMAP_UNLOCK(dst_pmap);
8244 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8248 if (dst_pmap->pm_type != src_pmap->pm_type ||
8249 dst_pmap->pm_type != PT_X86 ||
8250 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8253 if (dst_pmap < src_pmap) {
8254 PMAP_LOCK(dst_pmap);
8255 PMAP_LOCK(src_pmap);
8257 PMAP_LOCK(src_pmap);
8258 PMAP_LOCK(dst_pmap);
8260 error = pmap_pkru_copy(dst_pmap, src_pmap);
8261 /* Clean up partial copy on failure due to no memory. */
8262 if (error == ENOMEM)
8263 pmap_pkru_deassign_all(dst_pmap);
8264 PMAP_UNLOCK(src_pmap);
8265 PMAP_UNLOCK(dst_pmap);
8266 if (error != ENOMEM)
8274 * Zero the specified hardware page.
8277 pmap_zero_page(vm_page_t m)
8281 #ifdef TSLOG_PAGEZERO
8284 va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8285 pagezero((void *)va);
8286 #ifdef TSLOG_PAGEZERO
8292 * Zero an area within a single hardware page. off and size must not
8293 * cover an area beyond a single hardware page.
8296 pmap_zero_page_area(vm_page_t m, int off, int size)
8298 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8300 if (off == 0 && size == PAGE_SIZE)
8301 pagezero((void *)va);
8303 bzero((char *)va + off, size);
8307 * Copy 1 specified hardware page to another.
8310 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8312 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8313 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8315 pagecopy((void *)src, (void *)dst);
8318 int unmapped_buf_allowed = 1;
8321 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8322 vm_offset_t b_offset, int xfersize)
8326 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8330 while (xfersize > 0) {
8331 a_pg_offset = a_offset & PAGE_MASK;
8332 pages[0] = ma[a_offset >> PAGE_SHIFT];
8333 b_pg_offset = b_offset & PAGE_MASK;
8334 pages[1] = mb[b_offset >> PAGE_SHIFT];
8335 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8336 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8337 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
8338 a_cp = (char *)vaddr[0] + a_pg_offset;
8339 b_cp = (char *)vaddr[1] + b_pg_offset;
8340 bcopy(a_cp, b_cp, cnt);
8341 if (__predict_false(mapped))
8342 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
8350 * Returns true if the pmap's pv is one of the first
8351 * 16 pvs linked to from this page. This count may
8352 * be changed upwards or downwards in the future; it
8353 * is only necessary that true be returned for a small
8354 * subset of pmaps for proper page aging.
8357 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8359 struct md_page *pvh;
8360 struct rwlock *lock;
8365 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8366 ("pmap_page_exists_quick: page %p is not managed", m));
8368 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8370 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8371 if (PV_PMAP(pv) == pmap) {
8379 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8380 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8381 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8382 if (PV_PMAP(pv) == pmap) {
8396 * pmap_page_wired_mappings:
8398 * Return the number of managed mappings to the given physical page
8402 pmap_page_wired_mappings(vm_page_t m)
8404 struct rwlock *lock;
8405 struct md_page *pvh;
8409 int count, md_gen, pvh_gen;
8411 if ((m->oflags & VPO_UNMANAGED) != 0)
8413 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8417 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8419 if (!PMAP_TRYLOCK(pmap)) {
8420 md_gen = m->md.pv_gen;
8424 if (md_gen != m->md.pv_gen) {
8429 pte = pmap_pte(pmap, pv->pv_va);
8430 if ((*pte & PG_W) != 0)
8434 if ((m->flags & PG_FICTITIOUS) == 0) {
8435 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8436 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8438 if (!PMAP_TRYLOCK(pmap)) {
8439 md_gen = m->md.pv_gen;
8440 pvh_gen = pvh->pv_gen;
8444 if (md_gen != m->md.pv_gen ||
8445 pvh_gen != pvh->pv_gen) {
8450 pte = pmap_pde(pmap, pv->pv_va);
8451 if ((*pte & PG_W) != 0)
8461 * Returns TRUE if the given page is mapped individually or as part of
8462 * a 2mpage. Otherwise, returns FALSE.
8465 pmap_page_is_mapped(vm_page_t m)
8467 struct rwlock *lock;
8470 if ((m->oflags & VPO_UNMANAGED) != 0)
8472 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8474 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8475 ((m->flags & PG_FICTITIOUS) == 0 &&
8476 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8482 * Destroy all managed, non-wired mappings in the given user-space
8483 * pmap. This pmap cannot be active on any processor besides the
8486 * This function cannot be applied to the kernel pmap. Moreover, it
8487 * is not intended for general use. It is only to be used during
8488 * process termination. Consequently, it can be implemented in ways
8489 * that make it faster than pmap_remove(). First, it can more quickly
8490 * destroy mappings by iterating over the pmap's collection of PV
8491 * entries, rather than searching the page table. Second, it doesn't
8492 * have to test and clear the page table entries atomically, because
8493 * no processor is currently accessing the user address space. In
8494 * particular, a page table entry's dirty bit won't change state once
8495 * this function starts.
8497 * Although this function destroys all of the pmap's managed,
8498 * non-wired mappings, it can delay and batch the invalidation of TLB
8499 * entries without calling pmap_delayed_invl_start() and
8500 * pmap_delayed_invl_finish(). Because the pmap is not active on
8501 * any other processor, none of these TLB entries will ever be used
8502 * before their eventual invalidation. Consequently, there is no need
8503 * for either pmap_remove_all() or pmap_remove_write() to wait for
8504 * that eventual TLB invalidation.
8507 pmap_remove_pages(pmap_t pmap)
8510 pt_entry_t *pte, tpte;
8511 pt_entry_t PG_M, PG_RW, PG_V;
8512 struct spglist free;
8513 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8514 vm_page_t m, mpte, mt;
8516 struct md_page *pvh;
8517 struct pv_chunk *pc, *npc;
8518 struct rwlock *lock;
8520 uint64_t inuse, bitmask;
8521 int allfree, field, i, idx;
8525 boolean_t superpage;
8529 * Assert that the given pmap is only active on the current
8530 * CPU. Unfortunately, we cannot block another CPU from
8531 * activating the pmap while this function is executing.
8533 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8536 cpuset_t other_cpus;
8538 other_cpus = all_cpus;
8540 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8541 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8543 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8548 PG_M = pmap_modified_bit(pmap);
8549 PG_V = pmap_valid_bit(pmap);
8550 PG_RW = pmap_rw_bit(pmap);
8552 for (i = 0; i < PMAP_MEMDOM; i++)
8553 TAILQ_INIT(&free_chunks[i]);
8556 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8561 for (field = 0; field < _NPCM; field++) {
8562 inuse = ~pc->pc_map[field] & pc_freemask[field];
8563 while (inuse != 0) {
8565 bitmask = 1UL << bit;
8566 idx = field * 64 + bit;
8567 pv = &pc->pc_pventry[idx];
8570 pte = pmap_pdpe(pmap, pv->pv_va);
8572 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8574 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8577 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8579 pte = &pte[pmap_pte_index(pv->pv_va)];
8583 * Keep track whether 'tpte' is a
8584 * superpage explicitly instead of
8585 * relying on PG_PS being set.
8587 * This is because PG_PS is numerically
8588 * identical to PG_PTE_PAT and thus a
8589 * regular page could be mistaken for
8595 if ((tpte & PG_V) == 0) {
8596 panic("bad pte va %lx pte %lx",
8601 * We cannot remove wired pages from a process' mapping at this time
8609 pc->pc_map[field] |= bitmask;
8612 * Because this pmap is not active on other
8613 * processors, the dirty bit cannot have
8614 * changed state since we last loaded pte.
8619 pa = tpte & PG_PS_FRAME;
8621 pa = tpte & PG_FRAME;
8623 m = PHYS_TO_VM_PAGE(pa);
8624 KASSERT(m->phys_addr == pa,
8625 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8626 m, (uintmax_t)m->phys_addr,
8629 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8630 m < &vm_page_array[vm_page_array_size],
8631 ("pmap_remove_pages: bad tpte %#jx",
8635 * Update the vm_page_t clean/reference bits.
8637 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8639 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8645 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8648 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8649 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8650 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8652 if (TAILQ_EMPTY(&pvh->pv_list)) {
8653 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8654 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8655 TAILQ_EMPTY(&mt->md.pv_list))
8656 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8658 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8660 KASSERT(vm_page_any_valid(mpte),
8661 ("pmap_remove_pages: pte page not promoted"));
8662 pmap_pt_page_count_adj(pmap, -1);
8663 KASSERT(mpte->ref_count == NPTEPG,
8664 ("pmap_remove_pages: pte page reference count error"));
8665 mpte->ref_count = 0;
8666 pmap_add_delayed_free_list(mpte, &free, FALSE);
8669 pmap_resident_count_adj(pmap, -1);
8670 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8672 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8673 TAILQ_EMPTY(&m->md.pv_list) &&
8674 (m->flags & PG_FICTITIOUS) == 0) {
8675 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8676 if (TAILQ_EMPTY(&pvh->pv_list))
8677 vm_page_aflag_clear(m, PGA_WRITEABLE);
8680 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8686 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8687 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8688 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8690 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8691 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8696 pmap_invalidate_all(pmap);
8697 pmap_pkru_deassign_all(pmap);
8698 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8700 vm_page_free_pages_toq(&free, true);
8704 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
8706 struct rwlock *lock;
8708 struct md_page *pvh;
8709 pt_entry_t *pte, mask;
8710 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8712 int md_gen, pvh_gen;
8716 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8719 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8721 if (!PMAP_TRYLOCK(pmap)) {
8722 md_gen = m->md.pv_gen;
8726 if (md_gen != m->md.pv_gen) {
8731 pte = pmap_pte(pmap, pv->pv_va);
8734 PG_M = pmap_modified_bit(pmap);
8735 PG_RW = pmap_rw_bit(pmap);
8736 mask |= PG_RW | PG_M;
8739 PG_A = pmap_accessed_bit(pmap);
8740 PG_V = pmap_valid_bit(pmap);
8741 mask |= PG_V | PG_A;
8743 rv = (*pte & mask) == mask;
8748 if ((m->flags & PG_FICTITIOUS) == 0) {
8749 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8750 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8752 if (!PMAP_TRYLOCK(pmap)) {
8753 md_gen = m->md.pv_gen;
8754 pvh_gen = pvh->pv_gen;
8758 if (md_gen != m->md.pv_gen ||
8759 pvh_gen != pvh->pv_gen) {
8764 pte = pmap_pde(pmap, pv->pv_va);
8767 PG_M = pmap_modified_bit(pmap);
8768 PG_RW = pmap_rw_bit(pmap);
8769 mask |= PG_RW | PG_M;
8772 PG_A = pmap_accessed_bit(pmap);
8773 PG_V = pmap_valid_bit(pmap);
8774 mask |= PG_V | PG_A;
8776 rv = (*pte & mask) == mask;
8790 * Return whether or not the specified physical page was modified
8791 * in any physical maps.
8794 pmap_is_modified(vm_page_t m)
8797 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8798 ("pmap_is_modified: page %p is not managed", m));
8801 * If the page is not busied then this check is racy.
8803 if (!pmap_page_is_write_mapped(m))
8805 return (pmap_page_test_mappings(m, FALSE, TRUE));
8809 * pmap_is_prefaultable:
8811 * Return whether or not the specified virtual address is eligible
8815 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8818 pt_entry_t *pte, PG_V;
8821 PG_V = pmap_valid_bit(pmap);
8824 * Return TRUE if and only if the PTE for the specified virtual
8825 * address is allocated but invalid.
8829 pde = pmap_pde(pmap, addr);
8830 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8831 pte = pmap_pde_to_pte(pde, addr);
8832 rv = (*pte & PG_V) == 0;
8839 * pmap_is_referenced:
8841 * Return whether or not the specified physical page was referenced
8842 * in any physical maps.
8845 pmap_is_referenced(vm_page_t m)
8848 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8849 ("pmap_is_referenced: page %p is not managed", m));
8850 return (pmap_page_test_mappings(m, TRUE, FALSE));
8854 * Clear the write and modified bits in each of the given page's mappings.
8857 pmap_remove_write(vm_page_t m)
8859 struct md_page *pvh;
8861 struct rwlock *lock;
8862 pv_entry_t next_pv, pv;
8864 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8866 int pvh_gen, md_gen;
8868 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8869 ("pmap_remove_write: page %p is not managed", m));
8871 vm_page_assert_busied(m);
8872 if (!pmap_page_is_write_mapped(m))
8875 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8876 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8877 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8880 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8882 if (!PMAP_TRYLOCK(pmap)) {
8883 pvh_gen = pvh->pv_gen;
8887 if (pvh_gen != pvh->pv_gen) {
8892 PG_RW = pmap_rw_bit(pmap);
8894 pde = pmap_pde(pmap, va);
8895 if ((*pde & PG_RW) != 0)
8896 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8897 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8898 ("inconsistent pv lock %p %p for page %p",
8899 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8902 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8904 if (!PMAP_TRYLOCK(pmap)) {
8905 pvh_gen = pvh->pv_gen;
8906 md_gen = m->md.pv_gen;
8910 if (pvh_gen != pvh->pv_gen ||
8911 md_gen != m->md.pv_gen) {
8916 PG_M = pmap_modified_bit(pmap);
8917 PG_RW = pmap_rw_bit(pmap);
8918 pde = pmap_pde(pmap, pv->pv_va);
8919 KASSERT((*pde & PG_PS) == 0,
8920 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8922 pte = pmap_pde_to_pte(pde, pv->pv_va);
8924 if (oldpte & PG_RW) {
8925 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8928 if ((oldpte & PG_M) != 0)
8930 pmap_invalidate_page(pmap, pv->pv_va);
8935 vm_page_aflag_clear(m, PGA_WRITEABLE);
8936 pmap_delayed_invl_wait(m);
8940 * pmap_ts_referenced:
8942 * Return a count of reference bits for a page, clearing those bits.
8943 * It is not necessary for every reference bit to be cleared, but it
8944 * is necessary that 0 only be returned when there are truly no
8945 * reference bits set.
8947 * As an optimization, update the page's dirty field if a modified bit is
8948 * found while counting reference bits. This opportunistic update can be
8949 * performed at low cost and can eliminate the need for some future calls
8950 * to pmap_is_modified(). However, since this function stops after
8951 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8952 * dirty pages. Those dirty pages will only be detected by a future call
8953 * to pmap_is_modified().
8955 * A DI block is not needed within this function, because
8956 * invalidations are performed before the PV list lock is
8960 pmap_ts_referenced(vm_page_t m)
8962 struct md_page *pvh;
8965 struct rwlock *lock;
8966 pd_entry_t oldpde, *pde;
8967 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8970 int cleared, md_gen, not_cleared, pvh_gen;
8971 struct spglist free;
8974 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8975 ("pmap_ts_referenced: page %p is not managed", m));
8978 pa = VM_PAGE_TO_PHYS(m);
8979 lock = PHYS_TO_PV_LIST_LOCK(pa);
8980 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8984 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
8985 goto small_mappings;
8991 if (!PMAP_TRYLOCK(pmap)) {
8992 pvh_gen = pvh->pv_gen;
8996 if (pvh_gen != pvh->pv_gen) {
9001 PG_A = pmap_accessed_bit(pmap);
9002 PG_M = pmap_modified_bit(pmap);
9003 PG_RW = pmap_rw_bit(pmap);
9005 pde = pmap_pde(pmap, pv->pv_va);
9007 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9009 * Although "oldpde" is mapping a 2MB page, because
9010 * this function is called at a 4KB page granularity,
9011 * we only update the 4KB page under test.
9015 if ((oldpde & PG_A) != 0) {
9017 * Since this reference bit is shared by 512 4KB
9018 * pages, it should not be cleared every time it is
9019 * tested. Apply a simple "hash" function on the
9020 * physical page number, the virtual superpage number,
9021 * and the pmap address to select one 4KB page out of
9022 * the 512 on which testing the reference bit will
9023 * result in clearing that reference bit. This
9024 * function is designed to avoid the selection of the
9025 * same 4KB page for every 2MB page mapping.
9027 * On demotion, a mapping that hasn't been referenced
9028 * is simply destroyed. To avoid the possibility of a
9029 * subsequent page fault on a demoted wired mapping,
9030 * always leave its reference bit set. Moreover,
9031 * since the superpage is wired, the current state of
9032 * its reference bit won't affect page replacement.
9034 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
9035 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
9036 (oldpde & PG_W) == 0) {
9037 if (safe_to_clear_referenced(pmap, oldpde)) {
9038 atomic_clear_long(pde, PG_A);
9039 pmap_invalidate_page(pmap, pv->pv_va);
9041 } else if (pmap_demote_pde_locked(pmap, pde,
9042 pv->pv_va, &lock)) {
9044 * Remove the mapping to a single page
9045 * so that a subsequent access may
9046 * repromote. Since the underlying
9047 * page table page is fully populated,
9048 * this removal never frees a page
9052 va += VM_PAGE_TO_PHYS(m) - (oldpde &
9054 pte = pmap_pde_to_pte(pde, va);
9055 pmap_remove_pte(pmap, pte, va, *pde,
9057 pmap_invalidate_page(pmap, va);
9063 * The superpage mapping was removed
9064 * entirely and therefore 'pv' is no
9072 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9073 ("inconsistent pv lock %p %p for page %p",
9074 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9079 /* Rotate the PV list if it has more than one entry. */
9080 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9081 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
9082 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
9085 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
9087 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9089 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9096 if (!PMAP_TRYLOCK(pmap)) {
9097 pvh_gen = pvh->pv_gen;
9098 md_gen = m->md.pv_gen;
9102 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9107 PG_A = pmap_accessed_bit(pmap);
9108 PG_M = pmap_modified_bit(pmap);
9109 PG_RW = pmap_rw_bit(pmap);
9110 pde = pmap_pde(pmap, pv->pv_va);
9111 KASSERT((*pde & PG_PS) == 0,
9112 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9114 pte = pmap_pde_to_pte(pde, pv->pv_va);
9115 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9117 if ((*pte & PG_A) != 0) {
9118 if (safe_to_clear_referenced(pmap, *pte)) {
9119 atomic_clear_long(pte, PG_A);
9120 pmap_invalidate_page(pmap, pv->pv_va);
9122 } else if ((*pte & PG_W) == 0) {
9124 * Wired pages cannot be paged out so
9125 * doing accessed bit emulation for
9126 * them is wasted effort. We do the
9127 * hard work for unwired pages only.
9129 pmap_remove_pte(pmap, pte, pv->pv_va,
9130 *pde, &free, &lock);
9131 pmap_invalidate_page(pmap, pv->pv_va);
9136 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9137 ("inconsistent pv lock %p %p for page %p",
9138 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9143 /* Rotate the PV list if it has more than one entry. */
9144 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9145 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9146 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9149 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9150 not_cleared < PMAP_TS_REFERENCED_MAX);
9153 vm_page_free_pages_toq(&free, true);
9154 return (cleared + not_cleared);
9158 * Apply the given advice to the specified range of addresses within the
9159 * given pmap. Depending on the advice, clear the referenced and/or
9160 * modified flags in each mapping and set the mapped page's dirty field.
9163 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9165 struct rwlock *lock;
9166 pml4_entry_t *pml4e;
9168 pd_entry_t oldpde, *pde;
9169 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9170 vm_offset_t va, va_next;
9174 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9178 * A/D bit emulation requires an alternate code path when clearing
9179 * the modified and accessed bits below. Since this function is
9180 * advisory in nature we skip it entirely for pmaps that require
9181 * A/D bit emulation.
9183 if (pmap_emulate_ad_bits(pmap))
9186 PG_A = pmap_accessed_bit(pmap);
9187 PG_G = pmap_global_bit(pmap);
9188 PG_M = pmap_modified_bit(pmap);
9189 PG_V = pmap_valid_bit(pmap);
9190 PG_RW = pmap_rw_bit(pmap);
9192 pmap_delayed_invl_start();
9194 for (; sva < eva; sva = va_next) {
9195 pml4e = pmap_pml4e(pmap, sva);
9196 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9197 va_next = (sva + NBPML4) & ~PML4MASK;
9203 va_next = (sva + NBPDP) & ~PDPMASK;
9206 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9207 if ((*pdpe & PG_V) == 0)
9209 if ((*pdpe & PG_PS) != 0)
9212 va_next = (sva + NBPDR) & ~PDRMASK;
9215 pde = pmap_pdpe_to_pde(pdpe, sva);
9217 if ((oldpde & PG_V) == 0)
9219 else if ((oldpde & PG_PS) != 0) {
9220 if ((oldpde & PG_MANAGED) == 0)
9223 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9228 * The large page mapping was destroyed.
9234 * Unless the page mappings are wired, remove the
9235 * mapping to a single page so that a subsequent
9236 * access may repromote. Choosing the last page
9237 * within the address range [sva, min(va_next, eva))
9238 * generally results in more repromotions. Since the
9239 * underlying page table page is fully populated, this
9240 * removal never frees a page table page.
9242 if ((oldpde & PG_W) == 0) {
9248 ("pmap_advise: no address gap"));
9249 pte = pmap_pde_to_pte(pde, va);
9250 KASSERT((*pte & PG_V) != 0,
9251 ("pmap_advise: invalid PTE"));
9252 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9262 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9264 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9266 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9267 if (advice == MADV_DONTNEED) {
9269 * Future calls to pmap_is_modified()
9270 * can be avoided by making the page
9273 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9276 atomic_clear_long(pte, PG_M | PG_A);
9277 } else if ((*pte & PG_A) != 0)
9278 atomic_clear_long(pte, PG_A);
9282 if ((*pte & PG_G) != 0) {
9289 if (va != va_next) {
9290 pmap_invalidate_range(pmap, va, sva);
9295 pmap_invalidate_range(pmap, va, sva);
9298 pmap_invalidate_all(pmap);
9300 pmap_delayed_invl_finish();
9304 * Clear the modify bits on the specified physical page.
9307 pmap_clear_modify(vm_page_t m)
9309 struct md_page *pvh;
9311 pv_entry_t next_pv, pv;
9312 pd_entry_t oldpde, *pde;
9313 pt_entry_t *pte, PG_M, PG_RW;
9314 struct rwlock *lock;
9316 int md_gen, pvh_gen;
9318 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9319 ("pmap_clear_modify: page %p is not managed", m));
9320 vm_page_assert_busied(m);
9322 if (!pmap_page_is_write_mapped(m))
9324 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9325 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9326 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9329 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9331 if (!PMAP_TRYLOCK(pmap)) {
9332 pvh_gen = pvh->pv_gen;
9336 if (pvh_gen != pvh->pv_gen) {
9341 PG_M = pmap_modified_bit(pmap);
9342 PG_RW = pmap_rw_bit(pmap);
9344 pde = pmap_pde(pmap, va);
9346 /* If oldpde has PG_RW set, then it also has PG_M set. */
9347 if ((oldpde & PG_RW) != 0 &&
9348 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9349 (oldpde & PG_W) == 0) {
9351 * Write protect the mapping to a single page so that
9352 * a subsequent write access may repromote.
9354 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9355 pte = pmap_pde_to_pte(pde, va);
9356 atomic_clear_long(pte, PG_M | PG_RW);
9358 pmap_invalidate_page(pmap, va);
9362 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9364 if (!PMAP_TRYLOCK(pmap)) {
9365 md_gen = m->md.pv_gen;
9366 pvh_gen = pvh->pv_gen;
9370 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9375 PG_M = pmap_modified_bit(pmap);
9376 PG_RW = pmap_rw_bit(pmap);
9377 pde = pmap_pde(pmap, pv->pv_va);
9378 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9379 " a 2mpage in page %p's pv list", m));
9380 pte = pmap_pde_to_pte(pde, pv->pv_va);
9381 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9382 atomic_clear_long(pte, PG_M);
9383 pmap_invalidate_page(pmap, pv->pv_va);
9391 * Miscellaneous support routines follow
9394 /* Adjust the properties for a leaf page table entry. */
9395 static __inline void
9396 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9400 opte = *(u_long *)pte;
9402 npte = opte & ~mask;
9404 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9409 * Map a set of physical memory pages into the kernel virtual
9410 * address space. Return a pointer to where it is mapped. This
9411 * routine is intended to be used for mapping device memory,
9415 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9417 struct pmap_preinit_mapping *ppim;
9418 vm_offset_t va, offset;
9422 offset = pa & PAGE_MASK;
9423 size = round_page(offset + size);
9424 pa = trunc_page(pa);
9426 if (!pmap_initialized) {
9428 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9429 ppim = pmap_preinit_mapping + i;
9430 if (ppim->va == 0) {
9434 ppim->va = virtual_avail;
9435 virtual_avail += size;
9441 panic("%s: too many preinit mappings", __func__);
9444 * If we have a preinit mapping, re-use it.
9446 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9447 ppim = pmap_preinit_mapping + i;
9448 if (ppim->pa == pa && ppim->sz == size &&
9449 (ppim->mode == mode ||
9450 (flags & MAPDEV_SETATTR) == 0))
9451 return ((void *)(ppim->va + offset));
9454 * If the specified range of physical addresses fits within
9455 * the direct map window, use the direct map.
9457 if (pa < dmaplimit && pa + size <= dmaplimit) {
9458 va = PHYS_TO_DMAP(pa);
9459 if ((flags & MAPDEV_SETATTR) != 0) {
9460 PMAP_LOCK(kernel_pmap);
9461 i = pmap_change_props_locked(va, size,
9462 PROT_NONE, mode, flags);
9463 PMAP_UNLOCK(kernel_pmap);
9467 return ((void *)(va + offset));
9469 va = kva_alloc(size);
9471 panic("%s: Couldn't allocate KVA", __func__);
9473 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9474 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9475 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9476 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9477 pmap_invalidate_cache_range(va, va + tmpsize);
9478 return ((void *)(va + offset));
9482 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9485 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9490 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9493 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9497 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9500 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9505 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9508 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9509 MAPDEV_FLUSHCACHE));
9513 pmap_unmapdev(void *p, vm_size_t size)
9515 struct pmap_preinit_mapping *ppim;
9516 vm_offset_t offset, va;
9519 va = (vm_offset_t)p;
9521 /* If we gave a direct map region in pmap_mapdev, do nothing */
9522 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9524 offset = va & PAGE_MASK;
9525 size = round_page(offset + size);
9526 va = trunc_page(va);
9527 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9528 ppim = pmap_preinit_mapping + i;
9529 if (ppim->va == va && ppim->sz == size) {
9530 if (pmap_initialized)
9536 if (va + size == virtual_avail)
9541 if (pmap_initialized) {
9542 pmap_qremove(va, atop(size));
9548 * Tries to demote a 1GB page mapping.
9551 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9553 pdp_entry_t newpdpe, oldpdpe;
9554 pd_entry_t *firstpde, newpde, *pde;
9555 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9559 PG_A = pmap_accessed_bit(pmap);
9560 PG_M = pmap_modified_bit(pmap);
9561 PG_V = pmap_valid_bit(pmap);
9562 PG_RW = pmap_rw_bit(pmap);
9564 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9566 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9567 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9568 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9569 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9571 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9572 " in pmap %p", va, pmap);
9575 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9576 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9577 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9578 KASSERT((oldpdpe & PG_A) != 0,
9579 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9580 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9581 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9585 * Initialize the page directory page.
9587 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9593 * Demote the mapping.
9598 * Invalidate a stale recursive mapping of the page directory page.
9600 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9602 counter_u64_add(pmap_pdpe_demotions, 1);
9603 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9604 " in pmap %p", va, pmap);
9609 * Sets the memory attribute for the specified page.
9612 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9615 m->md.pat_mode = ma;
9618 * If "m" is a normal page, update its direct mapping. This update
9619 * can be relied upon to perform any cache operations that are
9620 * required for data coherence.
9622 if ((m->flags & PG_FICTITIOUS) == 0 &&
9623 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9625 panic("memory attribute change on the direct map failed");
9629 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9633 m->md.pat_mode = ma;
9635 if ((m->flags & PG_FICTITIOUS) != 0)
9637 PMAP_LOCK(kernel_pmap);
9638 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9639 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9640 PMAP_UNLOCK(kernel_pmap);
9642 panic("memory attribute change on the direct map failed");
9646 * Changes the specified virtual address range's memory type to that given by
9647 * the parameter "mode". The specified virtual address range must be
9648 * completely contained within either the direct map or the kernel map. If
9649 * the virtual address range is contained within the kernel map, then the
9650 * memory type for each of the corresponding ranges of the direct map is also
9651 * changed. (The corresponding ranges of the direct map are those ranges that
9652 * map the same physical pages as the specified virtual address range.) These
9653 * changes to the direct map are necessary because Intel describes the
9654 * behavior of their processors as "undefined" if two or more mappings to the
9655 * same physical page have different memory types.
9657 * Returns zero if the change completed successfully, and either EINVAL or
9658 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9659 * of the virtual address range was not mapped, and ENOMEM is returned if
9660 * there was insufficient memory available to complete the change. In the
9661 * latter case, the memory type may have been changed on some part of the
9662 * virtual address range or the direct map.
9665 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9669 PMAP_LOCK(kernel_pmap);
9670 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9672 PMAP_UNLOCK(kernel_pmap);
9677 * Changes the specified virtual address range's protections to those
9678 * specified by "prot". Like pmap_change_attr(), protections for aliases
9679 * in the direct map are updated as well. Protections on aliasing mappings may
9680 * be a subset of the requested protections; for example, mappings in the direct
9681 * map are never executable.
9684 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9688 /* Only supported within the kernel map. */
9689 if (va < VM_MIN_KERNEL_ADDRESS)
9692 PMAP_LOCK(kernel_pmap);
9693 error = pmap_change_props_locked(va, size, prot, -1,
9694 MAPDEV_ASSERTVALID);
9695 PMAP_UNLOCK(kernel_pmap);
9700 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9701 int mode, int flags)
9703 vm_offset_t base, offset, tmpva;
9704 vm_paddr_t pa_start, pa_end, pa_end1;
9706 pd_entry_t *pde, pde_bits, pde_mask;
9707 pt_entry_t *pte, pte_bits, pte_mask;
9711 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9712 base = trunc_page(va);
9713 offset = va & PAGE_MASK;
9714 size = round_page(offset + size);
9717 * Only supported on kernel virtual addresses, including the direct
9718 * map but excluding the recursive map.
9720 if (base < DMAP_MIN_ADDRESS)
9724 * Construct our flag sets and masks. "bits" is the subset of
9725 * "mask" that will be set in each modified PTE.
9727 * Mappings in the direct map are never allowed to be executable.
9729 pde_bits = pte_bits = 0;
9730 pde_mask = pte_mask = 0;
9732 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9733 pde_mask |= X86_PG_PDE_CACHE;
9734 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9735 pte_mask |= X86_PG_PTE_CACHE;
9737 if (prot != VM_PROT_NONE) {
9738 if ((prot & VM_PROT_WRITE) != 0) {
9739 pde_bits |= X86_PG_RW;
9740 pte_bits |= X86_PG_RW;
9742 if ((prot & VM_PROT_EXECUTE) == 0 ||
9743 va < VM_MIN_KERNEL_ADDRESS) {
9747 pde_mask |= X86_PG_RW | pg_nx;
9748 pte_mask |= X86_PG_RW | pg_nx;
9752 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9753 * into 4KB pages if required.
9755 for (tmpva = base; tmpva < base + size; ) {
9756 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9757 if (pdpe == NULL || *pdpe == 0) {
9758 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9759 ("%s: addr %#lx is not mapped", __func__, tmpva));
9762 if (*pdpe & PG_PS) {
9764 * If the current 1GB page already has the required
9765 * properties, then we need not demote this page. Just
9766 * increment tmpva to the next 1GB page frame.
9768 if ((*pdpe & pde_mask) == pde_bits) {
9769 tmpva = trunc_1gpage(tmpva) + NBPDP;
9774 * If the current offset aligns with a 1GB page frame
9775 * and there is at least 1GB left within the range, then
9776 * we need not break down this page into 2MB pages.
9778 if ((tmpva & PDPMASK) == 0 &&
9779 tmpva + PDPMASK < base + size) {
9783 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9786 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9788 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9789 ("%s: addr %#lx is not mapped", __func__, tmpva));
9794 * If the current 2MB page already has the required
9795 * properties, then we need not demote this page. Just
9796 * increment tmpva to the next 2MB page frame.
9798 if ((*pde & pde_mask) == pde_bits) {
9799 tmpva = trunc_2mpage(tmpva) + NBPDR;
9804 * If the current offset aligns with a 2MB page frame
9805 * and there is at least 2MB left within the range, then
9806 * we need not break down this page into 4KB pages.
9808 if ((tmpva & PDRMASK) == 0 &&
9809 tmpva + PDRMASK < base + size) {
9813 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9816 pte = pmap_pde_to_pte(pde, tmpva);
9818 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9819 ("%s: addr %#lx is not mapped", __func__, tmpva));
9827 * Ok, all the pages exist, so run through them updating their
9828 * properties if required.
9831 pa_start = pa_end = 0;
9832 for (tmpva = base; tmpva < base + size; ) {
9833 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9834 if (*pdpe & PG_PS) {
9835 if ((*pdpe & pde_mask) != pde_bits) {
9836 pmap_pte_props(pdpe, pde_bits, pde_mask);
9839 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9840 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9841 if (pa_start == pa_end) {
9842 /* Start physical address run. */
9843 pa_start = *pdpe & PG_PS_FRAME;
9844 pa_end = pa_start + NBPDP;
9845 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9848 /* Run ended, update direct map. */
9849 error = pmap_change_props_locked(
9850 PHYS_TO_DMAP(pa_start),
9851 pa_end - pa_start, prot, mode,
9855 /* Start physical address run. */
9856 pa_start = *pdpe & PG_PS_FRAME;
9857 pa_end = pa_start + NBPDP;
9860 tmpva = trunc_1gpage(tmpva) + NBPDP;
9863 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9865 if ((*pde & pde_mask) != pde_bits) {
9866 pmap_pte_props(pde, pde_bits, pde_mask);
9869 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9870 (*pde & PG_PS_FRAME) < dmaplimit) {
9871 if (pa_start == pa_end) {
9872 /* Start physical address run. */
9873 pa_start = *pde & PG_PS_FRAME;
9874 pa_end = pa_start + NBPDR;
9875 } else if (pa_end == (*pde & PG_PS_FRAME))
9878 /* Run ended, update direct map. */
9879 error = pmap_change_props_locked(
9880 PHYS_TO_DMAP(pa_start),
9881 pa_end - pa_start, prot, mode,
9885 /* Start physical address run. */
9886 pa_start = *pde & PG_PS_FRAME;
9887 pa_end = pa_start + NBPDR;
9890 tmpva = trunc_2mpage(tmpva) + NBPDR;
9892 pte = pmap_pde_to_pte(pde, tmpva);
9893 if ((*pte & pte_mask) != pte_bits) {
9894 pmap_pte_props(pte, pte_bits, pte_mask);
9897 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9898 (*pte & PG_FRAME) < dmaplimit) {
9899 if (pa_start == pa_end) {
9900 /* Start physical address run. */
9901 pa_start = *pte & PG_FRAME;
9902 pa_end = pa_start + PAGE_SIZE;
9903 } else if (pa_end == (*pte & PG_FRAME))
9904 pa_end += PAGE_SIZE;
9906 /* Run ended, update direct map. */
9907 error = pmap_change_props_locked(
9908 PHYS_TO_DMAP(pa_start),
9909 pa_end - pa_start, prot, mode,
9913 /* Start physical address run. */
9914 pa_start = *pte & PG_FRAME;
9915 pa_end = pa_start + PAGE_SIZE;
9921 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9922 pa_end1 = MIN(pa_end, dmaplimit);
9923 if (pa_start != pa_end1)
9924 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9925 pa_end1 - pa_start, prot, mode, flags);
9929 * Flush CPU caches if required to make sure any data isn't cached that
9930 * shouldn't be, etc.
9933 pmap_invalidate_range(kernel_pmap, base, tmpva);
9934 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9935 pmap_invalidate_cache_range(base, tmpva);
9941 * Demotes any mapping within the direct map region that covers more than the
9942 * specified range of physical addresses. This range's size must be a power
9943 * of two and its starting address must be a multiple of its size. Since the
9944 * demotion does not change any attributes of the mapping, a TLB invalidation
9945 * is not mandatory. The caller may, however, request a TLB invalidation.
9948 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
9957 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9958 KASSERT((base & (len - 1)) == 0,
9959 ("pmap_demote_DMAP: base is not a multiple of len"));
9960 if (len < NBPDP && base < dmaplimit) {
9961 va = PHYS_TO_DMAP(base);
9963 PMAP_LOCK(kernel_pmap);
9964 pdpe = pmap_pdpe(kernel_pmap, va);
9965 if ((*pdpe & X86_PG_V) == 0)
9966 panic("pmap_demote_DMAP: invalid PDPE");
9967 if ((*pdpe & PG_PS) != 0) {
9968 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9969 panic("pmap_demote_DMAP: PDPE failed");
9973 pde = pmap_pdpe_to_pde(pdpe, va);
9974 if ((*pde & X86_PG_V) == 0)
9975 panic("pmap_demote_DMAP: invalid PDE");
9976 if ((*pde & PG_PS) != 0) {
9977 if (!pmap_demote_pde(kernel_pmap, pde, va))
9978 panic("pmap_demote_DMAP: PDE failed");
9982 if (changed && invalidate)
9983 pmap_invalidate_page(kernel_pmap, va);
9984 PMAP_UNLOCK(kernel_pmap);
9989 * Perform the pmap work for mincore(2). If the page is not both referenced and
9990 * modified by this pmap, returns its physical address so that the caller can
9991 * find other mappings.
9994 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
9998 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
10002 PG_A = pmap_accessed_bit(pmap);
10003 PG_M = pmap_modified_bit(pmap);
10004 PG_V = pmap_valid_bit(pmap);
10005 PG_RW = pmap_rw_bit(pmap);
10011 pdpe = pmap_pdpe(pmap, addr);
10014 if ((*pdpe & PG_V) != 0) {
10015 if ((*pdpe & PG_PS) != 0) {
10017 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
10019 val = MINCORE_PSIND(2);
10021 pdep = pmap_pde(pmap, addr);
10022 if (pdep != NULL && (*pdep & PG_V) != 0) {
10023 if ((*pdep & PG_PS) != 0) {
10025 /* Compute the physical address of the 4KB page. */
10026 pa = ((pte & PG_PS_FRAME) | (addr &
10027 PDRMASK)) & PG_FRAME;
10028 val = MINCORE_PSIND(1);
10030 pte = *pmap_pde_to_pte(pdep, addr);
10031 pa = pte & PG_FRAME;
10037 if ((pte & PG_V) != 0) {
10038 val |= MINCORE_INCORE;
10039 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
10040 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
10041 if ((pte & PG_A) != 0)
10042 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
10044 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
10045 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
10046 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
10055 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
10057 uint32_t gen, new_gen, pcid_next;
10059 CRITICAL_ASSERT(curthread);
10060 gen = PCPU_GET(pcid_gen);
10061 if (pcidp->pm_pcid == PMAP_PCID_KERN)
10062 return (pti ? 0 : CR3_PCID_SAVE);
10063 if (pcidp->pm_gen == gen)
10064 return (CR3_PCID_SAVE);
10065 pcid_next = PCPU_GET(pcid_next);
10066 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
10067 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
10068 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
10069 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
10070 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
10074 PCPU_SET(pcid_gen, new_gen);
10075 pcid_next = PMAP_PCID_KERN + 1;
10079 pcidp->pm_pcid = pcid_next;
10080 pcidp->pm_gen = new_gen;
10081 PCPU_SET(pcid_next, pcid_next + 1);
10086 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10090 cached = pmap_pcid_alloc(pmap, pcidp);
10091 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10092 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10093 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10094 ("non-kernel pmap pmap %p cpu %d pcid %#x",
10095 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10100 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10103 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10104 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10108 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10111 struct pmap_pcid *pcidp, *old_pcidp;
10112 uint64_t cached, cr3, kcr3, ucr3;
10114 KASSERT((read_rflags() & PSL_I) == 0,
10115 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10117 /* See the comment in pmap_invalidate_page_pcid(). */
10118 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10119 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10120 old_pmap = PCPU_GET(curpmap);
10121 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10122 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10123 old_pcidp->pm_gen = 0;
10126 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10127 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10129 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10130 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10131 PCPU_SET(curpmap, pmap);
10132 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10133 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10135 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10136 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10138 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10139 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10141 counter_u64_add(pcid_save_cnt, 1);
10143 pmap_activate_sw_pti_post(td, pmap);
10147 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10150 struct pmap_pcid *pcidp;
10151 uint64_t cached, cr3;
10153 KASSERT((read_rflags() & PSL_I) == 0,
10154 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10156 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10157 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10159 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10160 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10161 PCPU_SET(curpmap, pmap);
10163 counter_u64_add(pcid_save_cnt, 1);
10167 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10168 u_int cpuid __unused)
10171 load_cr3(pmap->pm_cr3);
10172 PCPU_SET(curpmap, pmap);
10176 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10177 u_int cpuid __unused)
10180 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10181 PCPU_SET(kcr3, pmap->pm_cr3);
10182 PCPU_SET(ucr3, pmap->pm_ucr3);
10183 pmap_activate_sw_pti_post(td, pmap);
10186 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10190 if (pmap_pcid_enabled && pti)
10191 return (pmap_activate_sw_pcid_pti);
10192 else if (pmap_pcid_enabled && !pti)
10193 return (pmap_activate_sw_pcid_nopti);
10194 else if (!pmap_pcid_enabled && pti)
10195 return (pmap_activate_sw_nopcid_pti);
10196 else /* if (!pmap_pcid_enabled && !pti) */
10197 return (pmap_activate_sw_nopcid_nopti);
10201 pmap_activate_sw(struct thread *td)
10203 pmap_t oldpmap, pmap;
10206 oldpmap = PCPU_GET(curpmap);
10207 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10208 if (oldpmap == pmap) {
10209 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10213 cpuid = PCPU_GET(cpuid);
10215 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10217 CPU_SET(cpuid, &pmap->pm_active);
10219 pmap_activate_sw_mode(td, pmap, cpuid);
10221 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10223 CPU_CLR(cpuid, &oldpmap->pm_active);
10228 pmap_activate(struct thread *td)
10231 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10232 * invalidate_all IPI, which checks for curpmap ==
10233 * smp_tlb_pmap. The below sequence of operations has a
10234 * window where %CR3 is loaded with the new pmap's PML4
10235 * address, but the curpmap value has not yet been updated.
10236 * This causes the invltlb IPI handler, which is called
10237 * between the updates, to execute as a NOP, which leaves
10238 * stale TLB entries.
10240 * Note that the most common use of pmap_activate_sw(), from
10241 * a context switch, is immune to this race, because
10242 * interrupts are disabled (while the thread lock is owned),
10243 * so the IPI is delayed until after curpmap is updated. Protect
10244 * other callers in a similar way, by disabling interrupts
10245 * around the %cr3 register reload and curpmap assignment.
10248 pmap_activate_sw(td);
10253 pmap_activate_boot(pmap_t pmap)
10259 * kernel_pmap must be never deactivated, and we ensure that
10260 * by never activating it at all.
10262 MPASS(pmap != kernel_pmap);
10264 cpuid = PCPU_GET(cpuid);
10266 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10268 CPU_SET(cpuid, &pmap->pm_active);
10270 PCPU_SET(curpmap, pmap);
10272 kcr3 = pmap->pm_cr3;
10273 if (pmap_pcid_enabled)
10274 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10276 kcr3 = PMAP_NO_CR3;
10278 PCPU_SET(kcr3, kcr3);
10279 PCPU_SET(ucr3, PMAP_NO_CR3);
10283 pmap_active_cpus(pmap_t pmap, cpuset_t *res)
10285 *res = pmap->pm_active;
10289 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10294 * Increase the starting virtual address of the given mapping if a
10295 * different alignment might result in more superpage mappings.
10298 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10299 vm_offset_t *addr, vm_size_t size)
10301 vm_offset_t superpage_offset;
10305 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10306 offset += ptoa(object->pg_color);
10307 superpage_offset = offset & PDRMASK;
10308 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10309 (*addr & PDRMASK) == superpage_offset)
10311 if ((*addr & PDRMASK) < superpage_offset)
10312 *addr = (*addr & ~PDRMASK) + superpage_offset;
10314 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10318 static unsigned long num_dirty_emulations;
10319 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10320 &num_dirty_emulations, 0, NULL);
10322 static unsigned long num_accessed_emulations;
10323 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10324 &num_accessed_emulations, 0, NULL);
10326 static unsigned long num_superpage_accessed_emulations;
10327 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10328 &num_superpage_accessed_emulations, 0, NULL);
10330 static unsigned long ad_emulation_superpage_promotions;
10331 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10332 &ad_emulation_superpage_promotions, 0, NULL);
10333 #endif /* INVARIANTS */
10336 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10339 struct rwlock *lock;
10340 #if VM_NRESERVLEVEL > 0
10344 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10346 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10347 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10349 if (!pmap_emulate_ad_bits(pmap))
10352 PG_A = pmap_accessed_bit(pmap);
10353 PG_M = pmap_modified_bit(pmap);
10354 PG_V = pmap_valid_bit(pmap);
10355 PG_RW = pmap_rw_bit(pmap);
10361 pde = pmap_pde(pmap, va);
10362 if (pde == NULL || (*pde & PG_V) == 0)
10365 if ((*pde & PG_PS) != 0) {
10366 if (ftype == VM_PROT_READ) {
10368 atomic_add_long(&num_superpage_accessed_emulations, 1);
10376 pte = pmap_pde_to_pte(pde, va);
10377 if ((*pte & PG_V) == 0)
10380 if (ftype == VM_PROT_WRITE) {
10381 if ((*pte & PG_RW) == 0)
10384 * Set the modified and accessed bits simultaneously.
10386 * Intel EPT PTEs that do software emulation of A/D bits map
10387 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10388 * An EPT misconfiguration is triggered if the PTE is writable
10389 * but not readable (WR=10). This is avoided by setting PG_A
10390 * and PG_M simultaneously.
10392 *pte |= PG_M | PG_A;
10397 #if VM_NRESERVLEVEL > 0
10398 /* try to promote the mapping */
10399 if (va < VM_MAXUSER_ADDRESS)
10400 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10404 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10406 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10407 (m->flags & PG_FICTITIOUS) == 0 &&
10408 vm_reserv_level_iffullpop(m) == 0 &&
10409 pmap_promote_pde(pmap, pde, va, mpte, &lock)) {
10411 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10417 if (ftype == VM_PROT_WRITE)
10418 atomic_add_long(&num_dirty_emulations, 1);
10420 atomic_add_long(&num_accessed_emulations, 1);
10422 rv = 0; /* success */
10431 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10433 pml4_entry_t *pml4;
10436 pt_entry_t *pte, PG_V;
10440 PG_V = pmap_valid_bit(pmap);
10443 pml4 = pmap_pml4e(pmap, va);
10446 ptr[idx++] = *pml4;
10447 if ((*pml4 & PG_V) == 0)
10450 pdp = pmap_pml4e_to_pdpe(pml4, va);
10452 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10455 pde = pmap_pdpe_to_pde(pdp, va);
10457 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10460 pte = pmap_pde_to_pte(pde, va);
10469 * Get the kernel virtual address of a set of physical pages. If there are
10470 * physical addresses not covered by the DMAP perform a transient mapping
10471 * that will be removed when calling pmap_unmap_io_transient.
10473 * \param page The pages the caller wishes to obtain the virtual
10474 * address on the kernel memory map.
10475 * \param vaddr On return contains the kernel virtual memory address
10476 * of the pages passed in the page parameter.
10477 * \param count Number of pages passed in.
10478 * \param can_fault true if the thread using the mapped pages can take
10479 * page faults, false otherwise.
10481 * \returns true if the caller must call pmap_unmap_io_transient when
10482 * finished or false otherwise.
10486 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10490 bool needs_mapping;
10492 int cache_bits, error __unused, i;
10495 * Allocate any KVA space that we need, this is done in a separate
10496 * loop to prevent calling vmem_alloc while pinned.
10498 needs_mapping = false;
10499 for (i = 0; i < count; i++) {
10500 paddr = VM_PAGE_TO_PHYS(page[i]);
10501 if (__predict_false(paddr >= dmaplimit)) {
10502 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10503 M_BESTFIT | M_WAITOK, &vaddr[i]);
10504 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10505 needs_mapping = true;
10507 vaddr[i] = PHYS_TO_DMAP(paddr);
10511 /* Exit early if everything is covered by the DMAP */
10512 if (!needs_mapping)
10516 * NB: The sequence of updating a page table followed by accesses
10517 * to the corresponding pages used in the !DMAP case is subject to
10518 * the situation described in the "AMD64 Architecture Programmer's
10519 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10520 * Coherency Considerations". Therefore, issuing the INVLPG right
10521 * after modifying the PTE bits is crucial.
10525 for (i = 0; i < count; i++) {
10526 paddr = VM_PAGE_TO_PHYS(page[i]);
10527 if (paddr >= dmaplimit) {
10530 * Slow path, since we can get page faults
10531 * while mappings are active don't pin the
10532 * thread to the CPU and instead add a global
10533 * mapping visible to all CPUs.
10535 pmap_qenter(vaddr[i], &page[i], 1);
10537 pte = vtopte(vaddr[i]);
10538 cache_bits = pmap_cache_bits(kernel_pmap,
10539 page[i]->md.pat_mode, false);
10540 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10542 pmap_invlpg(kernel_pmap, vaddr[i]);
10547 return (needs_mapping);
10551 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10559 for (i = 0; i < count; i++) {
10560 paddr = VM_PAGE_TO_PHYS(page[i]);
10561 if (paddr >= dmaplimit) {
10563 pmap_qremove(vaddr[i], 1);
10564 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10570 pmap_quick_enter_page(vm_page_t m)
10574 paddr = VM_PAGE_TO_PHYS(m);
10575 if (paddr < dmaplimit)
10576 return (PHYS_TO_DMAP(paddr));
10577 mtx_lock_spin(&qframe_mtx);
10578 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10581 * Since qframe is exclusively mapped by us, and we do not set
10582 * PG_G, we can use INVLPG here.
10586 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10587 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
10592 pmap_quick_remove_page(vm_offset_t addr)
10595 if (addr != qframe)
10597 pte_store(vtopte(qframe), 0);
10598 mtx_unlock_spin(&qframe_mtx);
10602 * Pdp pages from the large map are managed differently from either
10603 * kernel or user page table pages. They are permanently allocated at
10604 * initialization time, and their reference count is permanently set to
10605 * zero. The pml4 entries pointing to those pages are copied into
10606 * each allocated pmap.
10608 * In contrast, pd and pt pages are managed like user page table
10609 * pages. They are dynamically allocated, and their reference count
10610 * represents the number of valid entries within the page.
10613 pmap_large_map_getptp_unlocked(void)
10615 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10619 pmap_large_map_getptp(void)
10623 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10624 m = pmap_large_map_getptp_unlocked();
10626 PMAP_UNLOCK(kernel_pmap);
10628 PMAP_LOCK(kernel_pmap);
10629 /* Callers retry. */
10634 static pdp_entry_t *
10635 pmap_large_map_pdpe(vm_offset_t va)
10637 vm_pindex_t pml4_idx;
10640 pml4_idx = pmap_pml4e_index(va);
10641 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10642 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10644 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10645 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10646 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10647 "LMSPML4I %#jx lm_ents %d",
10648 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10649 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10650 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10653 static pd_entry_t *
10654 pmap_large_map_pde(vm_offset_t va)
10661 pdpe = pmap_large_map_pdpe(va);
10663 m = pmap_large_map_getptp();
10666 mphys = VM_PAGE_TO_PHYS(m);
10667 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10669 MPASS((*pdpe & X86_PG_PS) == 0);
10670 mphys = *pdpe & PG_FRAME;
10672 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10675 static pt_entry_t *
10676 pmap_large_map_pte(vm_offset_t va)
10683 pde = pmap_large_map_pde(va);
10685 m = pmap_large_map_getptp();
10688 mphys = VM_PAGE_TO_PHYS(m);
10689 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10690 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10692 MPASS((*pde & X86_PG_PS) == 0);
10693 mphys = *pde & PG_FRAME;
10695 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10699 pmap_large_map_kextract(vm_offset_t va)
10701 pdp_entry_t *pdpe, pdp;
10702 pd_entry_t *pde, pd;
10703 pt_entry_t *pte, pt;
10705 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10706 ("not largemap range %#lx", (u_long)va));
10707 pdpe = pmap_large_map_pdpe(va);
10709 KASSERT((pdp & X86_PG_V) != 0,
10710 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10711 (u_long)pdpe, pdp));
10712 if ((pdp & X86_PG_PS) != 0) {
10713 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10714 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10715 (u_long)pdpe, pdp));
10716 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10718 pde = pmap_pdpe_to_pde(pdpe, va);
10720 KASSERT((pd & X86_PG_V) != 0,
10721 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10722 if ((pd & X86_PG_PS) != 0)
10723 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10724 pte = pmap_pde_to_pte(pde, va);
10726 KASSERT((pt & X86_PG_V) != 0,
10727 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10728 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10732 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10733 vmem_addr_t *vmem_res)
10737 * Large mappings are all but static. Consequently, there
10738 * is no point in waiting for an earlier allocation to be
10741 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10742 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10746 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10747 vm_memattr_t mattr)
10752 vm_offset_t va, inc;
10753 vmem_addr_t vmem_res;
10757 if (len == 0 || spa + len < spa)
10760 /* See if DMAP can serve. */
10761 if (spa + len <= dmaplimit) {
10762 va = PHYS_TO_DMAP(spa);
10763 *addr = (void *)va;
10764 return (pmap_change_attr(va, len, mattr));
10768 * No, allocate KVA. Fit the address with best possible
10769 * alignment for superpages. Fall back to worse align if
10773 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10774 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10775 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10777 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10779 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10782 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10787 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10788 * in the pagetable to minimize flushing. No need to
10789 * invalidate TLB, since we only update invalid entries.
10791 PMAP_LOCK(kernel_pmap);
10792 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10794 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10795 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10796 pdpe = pmap_large_map_pdpe(va);
10798 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10799 X86_PG_V | X86_PG_A | pg_nx |
10800 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10802 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10803 (va & PDRMASK) == 0) {
10804 pde = pmap_large_map_pde(va);
10806 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10807 X86_PG_V | X86_PG_A | pg_nx |
10808 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10809 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10813 pte = pmap_large_map_pte(va);
10815 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10816 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10818 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10823 PMAP_UNLOCK(kernel_pmap);
10826 *addr = (void *)vmem_res;
10831 pmap_large_unmap(void *svaa, vm_size_t len)
10833 vm_offset_t sva, va;
10835 pdp_entry_t *pdpe, pdp;
10836 pd_entry_t *pde, pd;
10839 struct spglist spgf;
10841 sva = (vm_offset_t)svaa;
10842 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10843 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10847 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10848 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10849 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10850 PMAP_LOCK(kernel_pmap);
10851 for (va = sva; va < sva + len; va += inc) {
10852 pdpe = pmap_large_map_pdpe(va);
10854 KASSERT((pdp & X86_PG_V) != 0,
10855 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10856 (u_long)pdpe, pdp));
10857 if ((pdp & X86_PG_PS) != 0) {
10858 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10859 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10860 (u_long)pdpe, pdp));
10861 KASSERT((va & PDPMASK) == 0,
10862 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10863 (u_long)pdpe, pdp));
10864 KASSERT(va + NBPDP <= sva + len,
10865 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10866 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10867 (u_long)pdpe, pdp, len));
10872 pde = pmap_pdpe_to_pde(pdpe, va);
10874 KASSERT((pd & X86_PG_V) != 0,
10875 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10877 if ((pd & X86_PG_PS) != 0) {
10878 KASSERT((va & PDRMASK) == 0,
10879 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10881 KASSERT(va + NBPDR <= sva + len,
10882 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10883 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10887 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10889 if (m->ref_count == 0) {
10891 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10895 pte = pmap_pde_to_pte(pde, va);
10896 KASSERT((*pte & X86_PG_V) != 0,
10897 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10898 (u_long)pte, *pte));
10901 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10903 if (m->ref_count == 0) {
10905 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10906 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10908 if (m->ref_count == 0) {
10910 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10914 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10915 PMAP_UNLOCK(kernel_pmap);
10916 vm_page_free_pages_toq(&spgf, false);
10917 vmem_free(large_vmem, sva, len);
10921 pmap_large_map_wb_fence_mfence(void)
10928 pmap_large_map_wb_fence_atomic(void)
10931 atomic_thread_fence_seq_cst();
10935 pmap_large_map_wb_fence_nop(void)
10939 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10942 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10943 return (pmap_large_map_wb_fence_mfence);
10944 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10945 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10946 return (pmap_large_map_wb_fence_atomic);
10948 /* clflush is strongly enough ordered */
10949 return (pmap_large_map_wb_fence_nop);
10953 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10956 for (; len > 0; len -= cpu_clflush_line_size,
10957 va += cpu_clflush_line_size)
10962 pmap_large_map_flush_range_clflushopt(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_clflush(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_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10984 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
10987 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
10988 return (pmap_large_map_flush_range_clwb);
10989 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
10990 return (pmap_large_map_flush_range_clflushopt);
10991 else if ((cpu_feature & CPUID_CLFSH) != 0)
10992 return (pmap_large_map_flush_range_clflush);
10994 return (pmap_large_map_flush_range_nop);
10998 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
11000 volatile u_long *pe;
11006 for (va = sva; va < eva; va += inc) {
11008 if ((amd_feature & AMDID_PAGE1GB) != 0) {
11009 pe = (volatile u_long *)pmap_large_map_pdpe(va);
11011 if ((p & X86_PG_PS) != 0)
11015 pe = (volatile u_long *)pmap_large_map_pde(va);
11017 if ((p & X86_PG_PS) != 0)
11021 pe = (volatile u_long *)pmap_large_map_pte(va);
11025 seen_other = false;
11027 if ((p & X86_PG_AVAIL1) != 0) {
11029 * Spin-wait for the end of a parallel
11036 * If we saw other write-back
11037 * occuring, we cannot rely on PG_M to
11038 * indicate state of the cache. The
11039 * PG_M bit is cleared before the
11040 * flush to avoid ignoring new writes,
11041 * and writes which are relevant for
11042 * us might happen after.
11048 if ((p & X86_PG_M) != 0 || seen_other) {
11049 if (!atomic_fcmpset_long(pe, &p,
11050 (p & ~X86_PG_M) | X86_PG_AVAIL1))
11052 * If we saw PG_M without
11053 * PG_AVAIL1, and then on the
11054 * next attempt we do not
11055 * observe either PG_M or
11056 * PG_AVAIL1, the other
11057 * write-back started after us
11058 * and finished before us. We
11059 * can rely on it doing our
11063 pmap_large_map_flush_range(va, inc);
11064 atomic_clear_long(pe, X86_PG_AVAIL1);
11073 * Write-back cache lines for the given address range.
11075 * Must be called only on the range or sub-range returned from
11076 * pmap_large_map(). Must not be called on the coalesced ranges.
11078 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
11079 * instructions support.
11082 pmap_large_map_wb(void *svap, vm_size_t len)
11084 vm_offset_t eva, sva;
11086 sva = (vm_offset_t)svap;
11088 pmap_large_map_wb_fence();
11089 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
11090 pmap_large_map_flush_range(sva, len);
11092 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
11093 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11094 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11095 pmap_large_map_wb_large(sva, eva);
11097 pmap_large_map_wb_fence();
11101 pmap_pti_alloc_page(void)
11105 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11106 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11111 pmap_pti_free_page(vm_page_t m)
11113 if (!vm_page_unwire_noq(m))
11115 vm_page_xbusy_claim(m);
11116 vm_page_free_zero(m);
11121 pmap_pti_init(void)
11130 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11131 VM_OBJECT_WLOCK(pti_obj);
11132 pml4_pg = pmap_pti_alloc_page();
11133 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11134 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11135 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11136 pdpe = pmap_pti_pdpe(va);
11137 pmap_pti_wire_pte(pdpe);
11139 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11140 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11141 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11142 sizeof(struct gate_descriptor) * NIDT, false);
11144 /* Doublefault stack IST 1 */
11145 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11146 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11147 /* NMI stack IST 2 */
11148 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11149 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11150 /* MC# stack IST 3 */
11151 va = __pcpu[i].pc_common_tss.tss_ist3 +
11152 sizeof(struct nmi_pcpu);
11153 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11154 /* DB# stack IST 4 */
11155 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11156 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11158 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11160 pti_finalized = true;
11161 VM_OBJECT_WUNLOCK(pti_obj);
11165 pmap_cpu_init(void *arg __unused)
11167 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11170 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11172 static pdp_entry_t *
11173 pmap_pti_pdpe(vm_offset_t va)
11175 pml4_entry_t *pml4e;
11178 vm_pindex_t pml4_idx;
11181 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11183 pml4_idx = pmap_pml4e_index(va);
11184 pml4e = &pti_pml4[pml4_idx];
11188 panic("pml4 alloc after finalization\n");
11189 m = pmap_pti_alloc_page();
11191 pmap_pti_free_page(m);
11192 mphys = *pml4e & ~PAGE_MASK;
11194 mphys = VM_PAGE_TO_PHYS(m);
11195 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11198 mphys = *pml4e & ~PAGE_MASK;
11200 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11205 pmap_pti_wire_pte(void *pte)
11209 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11210 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11215 pmap_pti_unwire_pde(void *pde, bool only_ref)
11219 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11220 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11221 MPASS(only_ref || m->ref_count > 1);
11222 pmap_pti_free_page(m);
11226 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11231 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11232 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11233 if (pmap_pti_free_page(m)) {
11234 pde = pmap_pti_pde(va);
11235 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11237 pmap_pti_unwire_pde(pde, false);
11241 static pd_entry_t *
11242 pmap_pti_pde(vm_offset_t va)
11247 vm_pindex_t pd_idx;
11250 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11252 pdpe = pmap_pti_pdpe(va);
11254 m = pmap_pti_alloc_page();
11256 pmap_pti_free_page(m);
11257 MPASS((*pdpe & X86_PG_PS) == 0);
11258 mphys = *pdpe & ~PAGE_MASK;
11260 mphys = VM_PAGE_TO_PHYS(m);
11261 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11264 MPASS((*pdpe & X86_PG_PS) == 0);
11265 mphys = *pdpe & ~PAGE_MASK;
11268 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11269 pd_idx = pmap_pde_index(va);
11274 static pt_entry_t *
11275 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11282 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11284 pde = pmap_pti_pde(va);
11285 if (unwire_pde != NULL) {
11286 *unwire_pde = true;
11287 pmap_pti_wire_pte(pde);
11290 m = pmap_pti_alloc_page();
11292 pmap_pti_free_page(m);
11293 MPASS((*pde & X86_PG_PS) == 0);
11294 mphys = *pde & ~(PAGE_MASK | pg_nx);
11296 mphys = VM_PAGE_TO_PHYS(m);
11297 *pde = mphys | X86_PG_RW | X86_PG_V;
11298 if (unwire_pde != NULL)
11299 *unwire_pde = false;
11302 MPASS((*pde & X86_PG_PS) == 0);
11303 mphys = *pde & ~(PAGE_MASK | pg_nx);
11306 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11307 pte += pmap_pte_index(va);
11313 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11317 pt_entry_t *pte, ptev;
11320 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11322 sva = trunc_page(sva);
11323 MPASS(sva > VM_MAXUSER_ADDRESS);
11324 eva = round_page(eva);
11326 for (; sva < eva; sva += PAGE_SIZE) {
11327 pte = pmap_pti_pte(sva, &unwire_pde);
11328 pa = pmap_kextract(sva);
11329 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11330 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11331 VM_MEMATTR_DEFAULT, FALSE);
11333 pte_store(pte, ptev);
11334 pmap_pti_wire_pte(pte);
11336 KASSERT(!pti_finalized,
11337 ("pti overlap after fin %#lx %#lx %#lx",
11339 KASSERT(*pte == ptev,
11340 ("pti non-identical pte after fin %#lx %#lx %#lx",
11344 pde = pmap_pti_pde(sva);
11345 pmap_pti_unwire_pde(pde, true);
11351 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11356 VM_OBJECT_WLOCK(pti_obj);
11357 pmap_pti_add_kva_locked(sva, eva, exec);
11358 VM_OBJECT_WUNLOCK(pti_obj);
11362 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11369 sva = rounddown2(sva, PAGE_SIZE);
11370 MPASS(sva > VM_MAXUSER_ADDRESS);
11371 eva = roundup2(eva, PAGE_SIZE);
11373 VM_OBJECT_WLOCK(pti_obj);
11374 for (va = sva; va < eva; va += PAGE_SIZE) {
11375 pte = pmap_pti_pte(va, NULL);
11376 KASSERT((*pte & X86_PG_V) != 0,
11377 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11378 (u_long)pte, *pte));
11380 pmap_pti_unwire_pte(pte, va);
11382 pmap_invalidate_range(kernel_pmap, sva, eva);
11383 VM_OBJECT_WUNLOCK(pti_obj);
11387 pkru_dup_range(void *ctx __unused, void *data)
11389 struct pmap_pkru_range *node, *new_node;
11391 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11392 if (new_node == NULL)
11395 memcpy(new_node, node, sizeof(*node));
11400 pkru_free_range(void *ctx __unused, void *node)
11403 uma_zfree(pmap_pkru_ranges_zone, node);
11407 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11410 struct pmap_pkru_range *ppr;
11413 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11414 MPASS(pmap->pm_type == PT_X86);
11415 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11416 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11417 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11419 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11422 ppr->pkru_keyidx = keyidx;
11423 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11424 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11426 uma_zfree(pmap_pkru_ranges_zone, ppr);
11431 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11434 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11435 MPASS(pmap->pm_type == PT_X86);
11436 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11437 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11441 pmap_pkru_deassign_all(pmap_t pmap)
11444 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11445 if (pmap->pm_type == PT_X86 &&
11446 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11447 rangeset_remove_all(&pmap->pm_pkru);
11451 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11453 struct pmap_pkru_range *ppr, *prev_ppr;
11456 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11457 if (pmap->pm_type != PT_X86 ||
11458 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11459 sva >= VM_MAXUSER_ADDRESS)
11461 MPASS(eva <= VM_MAXUSER_ADDRESS);
11462 for (va = sva; va < eva; prev_ppr = ppr) {
11463 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11466 else if ((ppr == NULL) ^ (prev_ppr == NULL))
11472 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
11474 va = ppr->pkru_rs_el.re_end;
11480 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11482 struct pmap_pkru_range *ppr;
11484 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11485 if (pmap->pm_type != PT_X86 ||
11486 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11487 va >= VM_MAXUSER_ADDRESS)
11489 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11491 return (X86_PG_PKU(ppr->pkru_keyidx));
11496 pred_pkru_on_remove(void *ctx __unused, void *r)
11498 struct pmap_pkru_range *ppr;
11501 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11505 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11508 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11509 if (pmap->pm_type == PT_X86 &&
11510 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11511 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11512 pred_pkru_on_remove);
11517 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11520 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11521 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11522 MPASS(dst_pmap->pm_type == PT_X86);
11523 MPASS(src_pmap->pm_type == PT_X86);
11524 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11525 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11527 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11531 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11534 pml4_entry_t *pml4e;
11536 pd_entry_t newpde, ptpaddr, *pde;
11537 pt_entry_t newpte, *ptep, pte;
11538 vm_offset_t va, va_next;
11541 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11542 MPASS(pmap->pm_type == PT_X86);
11543 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11545 for (changed = false, va = sva; va < eva; va = va_next) {
11546 pml4e = pmap_pml4e(pmap, va);
11547 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11548 va_next = (va + NBPML4) & ~PML4MASK;
11554 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11555 if ((*pdpe & X86_PG_V) == 0) {
11556 va_next = (va + NBPDP) & ~PDPMASK;
11562 va_next = (va + NBPDR) & ~PDRMASK;
11566 pde = pmap_pdpe_to_pde(pdpe, va);
11571 MPASS((ptpaddr & X86_PG_V) != 0);
11572 if ((ptpaddr & PG_PS) != 0) {
11573 if (va + NBPDR == va_next && eva >= va_next) {
11574 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11575 X86_PG_PKU(keyidx);
11576 if (newpde != ptpaddr) {
11581 } else if (!pmap_demote_pde(pmap, pde, va)) {
11589 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11590 ptep++, va += PAGE_SIZE) {
11592 if ((pte & X86_PG_V) == 0)
11594 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11595 if (newpte != pte) {
11602 pmap_invalidate_range(pmap, sva, eva);
11606 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11607 u_int keyidx, int flags)
11610 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11611 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11613 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11615 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11621 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11626 sva = trunc_page(sva);
11627 eva = round_page(eva);
11628 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11633 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11635 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11637 if (error != ENOMEM)
11645 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11649 sva = trunc_page(sva);
11650 eva = round_page(eva);
11651 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11656 error = pmap_pkru_deassign(pmap, sva, eva);
11658 pmap_pkru_update_range(pmap, sva, eva, 0);
11660 if (error != ENOMEM)
11667 #if defined(KASAN) || defined(KMSAN)
11670 * Reserve enough memory to:
11671 * 1) allocate PDP pages for the shadow map(s),
11672 * 2) shadow the boot stack of KSTACK_PAGES pages,
11673 * so we need one PD page, one or two PT pages, and KSTACK_PAGES shadow pages
11677 #define SAN_EARLY_PAGES \
11678 (NKASANPML4E + 1 + 2 + howmany(KSTACK_PAGES, KASAN_SHADOW_SCALE))
11680 #define SAN_EARLY_PAGES \
11681 (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * (1 + 2 + KSTACK_PAGES))
11684 static uint64_t __nosanitizeaddress __nosanitizememory
11685 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11687 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11688 static size_t offset = 0;
11691 if (offset == sizeof(data)) {
11692 panic("%s: ran out of memory for the bootstrap shadow map",
11696 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11697 offset += PAGE_SIZE;
11702 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11703 * is currently only used to shadow the temporary boot stack set up by locore.
11705 static void __nosanitizeaddress __nosanitizememory
11706 pmap_san_enter_early(vm_offset_t va)
11708 static bool first = true;
11709 pml4_entry_t *pml4e;
11713 uint64_t cr3, pa, base;
11716 base = amd64_loadaddr();
11721 * If this the first call, we need to allocate new PML4Es for
11722 * the bootstrap shadow map(s). We don't know how the PML4 page
11723 * was initialized by the boot loader, so we can't simply test
11724 * whether the shadow map's PML4Es are zero.
11728 for (i = 0; i < NKASANPML4E; i++) {
11729 pa = pmap_san_enter_early_alloc_4k(base);
11731 pml4e = (pml4_entry_t *)cr3 +
11732 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11733 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11736 for (i = 0; i < NKMSANORIGPML4E; i++) {
11737 pa = pmap_san_enter_early_alloc_4k(base);
11739 pml4e = (pml4_entry_t *)cr3 +
11740 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11742 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11744 for (i = 0; i < NKMSANSHADPML4E; i++) {
11745 pa = pmap_san_enter_early_alloc_4k(base);
11747 pml4e = (pml4_entry_t *)cr3 +
11748 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11750 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11754 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11755 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11757 pa = pmap_san_enter_early_alloc_4k(base);
11758 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11760 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11762 pa = pmap_san_enter_early_alloc_4k(base);
11763 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11765 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11767 panic("%s: PTE for %#lx is already initialized", __func__, va);
11768 pa = pmap_san_enter_early_alloc_4k(base);
11769 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11773 pmap_san_enter_alloc_4k(void)
11777 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11780 panic("%s: no memory to grow shadow map", __func__);
11785 pmap_san_enter_alloc_2m(void)
11787 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11788 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11792 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11793 * pages when possible.
11795 void __nosanitizeaddress __nosanitizememory
11796 pmap_san_enter(vm_offset_t va)
11803 if (kernphys == 0) {
11805 * We're creating a temporary shadow map for the boot stack.
11807 pmap_san_enter_early(va);
11811 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11813 pdpe = pmap_pdpe(kernel_pmap, va);
11814 if ((*pdpe & X86_PG_V) == 0) {
11815 m = pmap_san_enter_alloc_4k();
11816 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11819 pde = pmap_pdpe_to_pde(pdpe, va);
11820 if ((*pde & X86_PG_V) == 0) {
11821 m = pmap_san_enter_alloc_2m();
11823 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11824 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11826 m = pmap_san_enter_alloc_4k();
11827 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11831 if ((*pde & X86_PG_PS) != 0)
11833 pte = pmap_pde_to_pte(pde, va);
11834 if ((*pte & X86_PG_V) != 0)
11836 m = pmap_san_enter_alloc_4k();
11837 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11838 X86_PG_M | X86_PG_A | pg_nx);
11843 * Track a range of the kernel's virtual address space that is contiguous
11844 * in various mapping attributes.
11846 struct pmap_kernel_map_range {
11855 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11861 if (eva <= range->sva)
11864 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11865 for (i = 0; i < PAT_INDEX_SIZE; i++)
11866 if (pat_index[i] == pat_idx)
11870 case PAT_WRITE_BACK:
11873 case PAT_WRITE_THROUGH:
11876 case PAT_UNCACHEABLE:
11882 case PAT_WRITE_PROTECTED:
11885 case PAT_WRITE_COMBINING:
11889 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11890 __func__, pat_idx, range->sva, eva);
11895 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11897 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11898 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11899 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11900 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11901 mode, range->pdpes, range->pdes, range->ptes);
11903 /* Reset to sentinel value. */
11904 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11905 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11906 NPDEPG - 1, NPTEPG - 1);
11910 * Determine whether the attributes specified by a page table entry match those
11911 * being tracked by the current range. This is not quite as simple as a direct
11912 * flag comparison since some PAT modes have multiple representations.
11915 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11917 pt_entry_t diff, mask;
11919 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11920 diff = (range->attrs ^ attrs) & mask;
11923 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11924 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11925 pmap_pat_index(kernel_pmap, attrs, true))
11931 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11935 memset(range, 0, sizeof(*range));
11937 range->attrs = attrs;
11941 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11942 * those of the current run, dump the address range and its attributes, and
11946 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11947 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11952 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11954 attrs |= pdpe & pg_nx;
11955 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11956 if ((pdpe & PG_PS) != 0) {
11957 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11958 } else if (pde != 0) {
11959 attrs |= pde & pg_nx;
11960 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11962 if ((pde & PG_PS) != 0) {
11963 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11964 } else if (pte != 0) {
11965 attrs |= pte & pg_nx;
11966 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11967 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11969 /* Canonicalize by always using the PDE PAT bit. */
11970 if ((attrs & X86_PG_PTE_PAT) != 0)
11971 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11974 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11975 sysctl_kmaps_dump(sb, range, va);
11976 sysctl_kmaps_reinit(range, va, attrs);
11981 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
11983 struct pmap_kernel_map_range range;
11984 struct sbuf sbuf, *sb;
11985 pml4_entry_t pml4e;
11986 pdp_entry_t *pdp, pdpe;
11987 pd_entry_t *pd, pde;
11988 pt_entry_t *pt, pte;
11991 int error, i, j, k, l;
11993 error = sysctl_wire_old_buffer(req, 0);
11997 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
11999 /* Sentinel value. */
12000 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
12001 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
12002 NPDEPG - 1, NPTEPG - 1);
12005 * Iterate over the kernel page tables without holding the kernel pmap
12006 * lock. Outside of the large map, kernel page table pages are never
12007 * freed, so at worst we will observe inconsistencies in the output.
12008 * Within the large map, ensure that PDP and PD page addresses are
12009 * valid before descending.
12011 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
12014 sbuf_printf(sb, "\nRecursive map:\n");
12017 sbuf_printf(sb, "\nDirect map:\n");
12021 sbuf_printf(sb, "\nKASAN shadow map:\n");
12025 case KMSANSHADPML4I:
12026 sbuf_printf(sb, "\nKMSAN shadow map:\n");
12028 case KMSANORIGPML4I:
12029 sbuf_printf(sb, "\nKMSAN origin map:\n");
12033 sbuf_printf(sb, "\nKernel map:\n");
12036 sbuf_printf(sb, "\nLarge map:\n");
12040 /* Convert to canonical form. */
12041 if (sva == 1ul << 47)
12045 pml4e = kernel_pml4[i];
12046 if ((pml4e & X86_PG_V) == 0) {
12047 sva = rounddown2(sva, NBPML4);
12048 sysctl_kmaps_dump(sb, &range, sva);
12052 pa = pml4e & PG_FRAME;
12053 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
12055 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
12057 if ((pdpe & X86_PG_V) == 0) {
12058 sva = rounddown2(sva, NBPDP);
12059 sysctl_kmaps_dump(sb, &range, sva);
12063 pa = pdpe & PG_FRAME;
12064 if ((pdpe & PG_PS) != 0) {
12065 sva = rounddown2(sva, NBPDP);
12066 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
12072 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12073 vm_phys_paddr_to_vm_page(pa) == NULL) {
12075 * Page table pages for the large map may be
12076 * freed. Validate the next-level address
12077 * before descending.
12081 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
12083 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
12085 if ((pde & X86_PG_V) == 0) {
12086 sva = rounddown2(sva, NBPDR);
12087 sysctl_kmaps_dump(sb, &range, sva);
12091 pa = pde & PG_FRAME;
12092 if ((pde & PG_PS) != 0) {
12093 sva = rounddown2(sva, NBPDR);
12094 sysctl_kmaps_check(sb, &range, sva,
12095 pml4e, pdpe, pde, 0);
12100 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12101 vm_phys_paddr_to_vm_page(pa) == NULL) {
12103 * Page table pages for the large map
12104 * may be freed. Validate the
12105 * next-level address before descending.
12109 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12111 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12112 sva += PAGE_SIZE) {
12114 if ((pte & X86_PG_V) == 0) {
12115 sysctl_kmaps_dump(sb, &range,
12119 sysctl_kmaps_check(sb, &range, sva,
12120 pml4e, pdpe, pde, pte);
12127 error = sbuf_finish(sb);
12131 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12132 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12133 NULL, 0, sysctl_kmaps, "A",
12134 "Dump kernel address layout");
12137 DB_SHOW_COMMAND(pte, pmap_print_pte)
12140 pml5_entry_t *pml5;
12141 pml4_entry_t *pml4;
12144 pt_entry_t *pte, PG_V;
12148 db_printf("show pte addr\n");
12151 va = (vm_offset_t)addr;
12153 if (kdb_thread != NULL)
12154 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12156 pmap = PCPU_GET(curpmap);
12158 PG_V = pmap_valid_bit(pmap);
12159 db_printf("VA 0x%016lx", va);
12161 if (pmap_is_la57(pmap)) {
12162 pml5 = pmap_pml5e(pmap, va);
12163 db_printf(" pml5e 0x%016lx", *pml5);
12164 if ((*pml5 & PG_V) == 0) {
12168 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12170 pml4 = pmap_pml4e(pmap, va);
12172 db_printf(" pml4e 0x%016lx", *pml4);
12173 if ((*pml4 & PG_V) == 0) {
12177 pdp = pmap_pml4e_to_pdpe(pml4, va);
12178 db_printf(" pdpe 0x%016lx", *pdp);
12179 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12183 pde = pmap_pdpe_to_pde(pdp, va);
12184 db_printf(" pde 0x%016lx", *pde);
12185 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12189 pte = pmap_pde_to_pte(pde, va);
12190 db_printf(" pte 0x%016lx\n", *pte);
12193 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12198 a = (vm_paddr_t)addr;
12199 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12201 db_printf("show phys2dmap addr\n");
12206 ptpages_show_page(int level, int idx, vm_page_t pg)
12208 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12209 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12213 ptpages_show_complain(int level, int idx, uint64_t pte)
12215 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12219 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12221 vm_page_t pg3, pg2, pg1;
12222 pml4_entry_t *pml4;
12227 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12228 for (i4 = 0; i4 < num_entries; i4++) {
12229 if ((pml4[i4] & PG_V) == 0)
12231 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12233 ptpages_show_complain(3, i4, pml4[i4]);
12236 ptpages_show_page(3, i4, pg3);
12237 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12238 for (i3 = 0; i3 < NPDPEPG; i3++) {
12239 if ((pdp[i3] & PG_V) == 0)
12241 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12243 ptpages_show_complain(2, i3, pdp[i3]);
12246 ptpages_show_page(2, i3, pg2);
12247 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12248 for (i2 = 0; i2 < NPDEPG; i2++) {
12249 if ((pd[i2] & PG_V) == 0)
12251 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12253 ptpages_show_complain(1, i2, pd[i2]);
12256 ptpages_show_page(1, i2, pg1);
12262 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12266 pml5_entry_t *pml5;
12271 pmap = (pmap_t)addr;
12273 pmap = PCPU_GET(curpmap);
12275 PG_V = pmap_valid_bit(pmap);
12277 if (pmap_is_la57(pmap)) {
12278 pml5 = pmap->pm_pmltop;
12279 for (i5 = 0; i5 < NUPML5E; i5++) {
12280 if ((pml5[i5] & PG_V) == 0)
12282 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12284 ptpages_show_complain(4, i5, pml5[i5]);
12287 ptpages_show_page(4, i5, pg);
12288 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12291 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12292 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);