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>
89 __FBSDID("$FreeBSD$");
92 * Manages physical address maps.
94 * Since the information managed by this module is
95 * also stored by the logical address mapping module,
96 * this module may throw away valid virtual-to-physical
97 * mappings at almost any time. However, invalidations
98 * of virtual-to-physical mappings must be done as
101 * In order to cope with hardware architectures which
102 * make virtual-to-physical map invalidates expensive,
103 * this module may delay invalidate or reduced protection
104 * operations until such time as they are actually
105 * necessary. This module is given full information as
106 * to which processors are currently using which maps,
107 * and to when physical maps must be made correct.
111 #include "opt_pmap.h"
114 #include <sys/param.h>
115 #include <sys/asan.h>
116 #include <sys/bitstring.h>
118 #include <sys/systm.h>
119 #include <sys/counter.h>
120 #include <sys/kernel.h>
122 #include <sys/lock.h>
123 #include <sys/malloc.h>
124 #include <sys/mman.h>
125 #include <sys/msan.h>
126 #include <sys/mutex.h>
127 #include <sys/proc.h>
128 #include <sys/rangeset.h>
129 #include <sys/rwlock.h>
130 #include <sys/sbuf.h>
133 #include <sys/turnstile.h>
134 #include <sys/vmem.h>
135 #include <sys/vmmeter.h>
136 #include <sys/sched.h>
137 #include <sys/sysctl.h>
145 #include <vm/vm_param.h>
146 #include <vm/vm_kern.h>
147 #include <vm/vm_page.h>
148 #include <vm/vm_map.h>
149 #include <vm/vm_object.h>
150 #include <vm/vm_extern.h>
151 #include <vm/vm_pageout.h>
152 #include <vm/vm_pager.h>
153 #include <vm/vm_phys.h>
154 #include <vm/vm_radix.h>
155 #include <vm/vm_reserv.h>
156 #include <vm/vm_dumpset.h>
159 #include <machine/asan.h>
160 #include <machine/intr_machdep.h>
161 #include <x86/apicvar.h>
162 #include <x86/ifunc.h>
163 #include <machine/cpu.h>
164 #include <machine/cputypes.h>
165 #include <machine/md_var.h>
166 #include <machine/msan.h>
167 #include <machine/pcb.h>
168 #include <machine/specialreg.h>
170 #include <machine/smp.h>
172 #include <machine/sysarch.h>
173 #include <machine/tss.h>
176 #define PMAP_MEMDOM MAXMEMDOM
178 #define PMAP_MEMDOM 1
181 static __inline boolean_t
182 pmap_type_guest(pmap_t pmap)
185 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
188 static __inline boolean_t
189 pmap_emulate_ad_bits(pmap_t pmap)
192 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
195 static __inline pt_entry_t
196 pmap_valid_bit(pmap_t pmap)
200 switch (pmap->pm_type) {
206 if (pmap_emulate_ad_bits(pmap))
207 mask = EPT_PG_EMUL_V;
212 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
218 static __inline pt_entry_t
219 pmap_rw_bit(pmap_t pmap)
223 switch (pmap->pm_type) {
229 if (pmap_emulate_ad_bits(pmap))
230 mask = EPT_PG_EMUL_RW;
235 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
241 static pt_entry_t pg_g;
243 static __inline pt_entry_t
244 pmap_global_bit(pmap_t pmap)
248 switch (pmap->pm_type) {
257 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
263 static __inline pt_entry_t
264 pmap_accessed_bit(pmap_t pmap)
268 switch (pmap->pm_type) {
274 if (pmap_emulate_ad_bits(pmap))
280 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
286 static __inline pt_entry_t
287 pmap_modified_bit(pmap_t pmap)
291 switch (pmap->pm_type) {
297 if (pmap_emulate_ad_bits(pmap))
303 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
309 static __inline pt_entry_t
310 pmap_pku_mask_bit(pmap_t pmap)
313 return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
316 static __inline boolean_t
317 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
320 if (!pmap_emulate_ad_bits(pmap))
323 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
326 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
327 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
328 * if the EPT_PG_WRITE bit is set.
330 if ((pte & EPT_PG_WRITE) != 0)
334 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
336 if ((pte & EPT_PG_EXECUTE) == 0 ||
337 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
343 #if !defined(DIAGNOSTIC)
344 #ifdef __GNUC_GNU_INLINE__
345 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
347 #define PMAP_INLINE extern inline
354 #define PV_STAT(x) do { x ; } while (0)
356 #define PV_STAT(x) do { } while (0)
361 #define pa_index(pa) ({ \
362 KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end, \
363 ("address %lx beyond the last segment", (pa))); \
366 #define pa_to_pmdp(pa) (&pv_table[pa_index(pa)])
367 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
368 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
369 struct rwlock *_lock; \
370 if (__predict_false((pa) > pmap_last_pa)) \
371 _lock = &pv_dummy_large.pv_lock; \
373 _lock = &(pa_to_pmdp(pa)->pv_lock); \
377 #define pa_index(pa) ((pa) >> PDRSHIFT)
378 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
380 #define NPV_LIST_LOCKS MAXCPU
382 #define PHYS_TO_PV_LIST_LOCK(pa) \
383 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
386 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
387 struct rwlock **_lockp = (lockp); \
388 struct rwlock *_new_lock; \
390 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
391 if (_new_lock != *_lockp) { \
392 if (*_lockp != NULL) \
393 rw_wunlock(*_lockp); \
394 *_lockp = _new_lock; \
399 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
400 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
402 #define RELEASE_PV_LIST_LOCK(lockp) do { \
403 struct rwlock **_lockp = (lockp); \
405 if (*_lockp != NULL) { \
406 rw_wunlock(*_lockp); \
411 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
412 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
415 * Statically allocate kernel pmap memory. However, memory for
416 * pm_pcids is obtained after the dynamic allocator is operational.
417 * Initialize it with a non-canonical pointer to catch early accesses
418 * regardless of the active mapping.
420 struct pmap kernel_pmap_store = {
421 .pm_pcidp = (void *)0xdeadbeefdeadbeef,
424 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
425 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
428 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
429 "Number of kernel page table pages allocated on bootup");
432 vm_paddr_t dmaplimit;
433 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
436 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
437 "VM/pmap parameters");
439 static int __read_frequently pg_ps_enabled = 1;
440 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
441 &pg_ps_enabled, 0, "Are large page mappings enabled?");
443 int __read_frequently la57 = 0;
444 SYSCTL_INT(_vm_pmap, OID_AUTO, la57, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
446 "5-level paging for host is enabled");
449 pmap_is_la57(pmap_t pmap)
451 if (pmap->pm_type == PT_X86)
453 return (false); /* XXXKIB handle EPT */
456 #define PAT_INDEX_SIZE 8
457 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
459 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
460 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
461 static u_int64_t KPDPphys; /* phys addr of kernel level 3 */
462 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
463 u_int64_t KPML5phys; /* phys addr of kernel level 5,
467 static uint64_t KASANPDPphys;
470 static uint64_t KMSANSHADPDPphys;
471 static uint64_t KMSANORIGPDPphys;
474 * To support systems with large amounts of memory, it is necessary to extend
475 * the maximum size of the direct map. This could eat into the space reserved
476 * for the shadow map.
478 _Static_assert(DMPML4I + NDMPML4E <= KMSANSHADPML4I, "direct map overflow");
481 static pml4_entry_t *kernel_pml4;
482 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
483 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
484 static int ndmpdpphys; /* number of DMPDPphys pages */
486 vm_paddr_t kernphys; /* phys addr of start of bootstrap data */
487 vm_paddr_t KERNend; /* and the end */
490 * pmap_mapdev support pre initialization (i.e. console)
492 #define PMAP_PREINIT_MAPPING_COUNT 8
493 static struct pmap_preinit_mapping {
498 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
499 static int pmap_initialized;
502 * Data for the pv entry allocation mechanism.
503 * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
507 pc_to_domain(struct pv_chunk *pc)
510 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
514 pc_to_domain(struct pv_chunk *pc __unused)
521 struct pv_chunks_list {
523 TAILQ_HEAD(pch, pv_chunk) pvc_list;
525 } __aligned(CACHE_LINE_SIZE);
527 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
530 struct pmap_large_md_page {
531 struct rwlock pv_lock;
532 struct md_page pv_page;
535 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
536 #define pv_dummy pv_dummy_large.pv_page
537 __read_mostly static struct pmap_large_md_page *pv_table;
538 __read_mostly vm_paddr_t pmap_last_pa;
540 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
541 static u_long pv_invl_gen[NPV_LIST_LOCKS];
542 static struct md_page *pv_table;
543 static struct md_page pv_dummy;
547 * All those kernel PT submaps that BSD is so fond of
549 pt_entry_t *CMAP1 = NULL;
551 static vm_offset_t qframe = 0;
552 static struct mtx qframe_mtx;
554 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
556 static vmem_t *large_vmem;
557 static u_int lm_ents;
558 #define PMAP_ADDRESS_IN_LARGEMAP(va) ((va) >= LARGEMAP_MIN_ADDRESS && \
559 (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
561 int pmap_pcid_enabled = 1;
562 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
563 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
564 int invpcid_works = 0;
565 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
566 "Is the invpcid instruction available ?");
567 int pmap_pcid_invlpg_workaround = 0;
568 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_invlpg_workaround,
569 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
570 &pmap_pcid_invlpg_workaround, 0,
571 "Enable small core PCID/INVLPG workaround");
572 int pmap_pcid_invlpg_workaround_uena = 1;
574 int __read_frequently pti = 0;
575 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
577 "Page Table Isolation enabled");
578 static vm_object_t pti_obj;
579 static pml4_entry_t *pti_pml4;
580 static vm_pindex_t pti_pg_idx;
581 static bool pti_finalized;
583 struct pmap_pkru_range {
584 struct rs_el pkru_rs_el;
589 static uma_zone_t pmap_pkru_ranges_zone;
590 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
591 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
592 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
593 static void *pkru_dup_range(void *ctx, void *data);
594 static void pkru_free_range(void *ctx, void *node);
595 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
596 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
597 static void pmap_pkru_deassign_all(pmap_t pmap);
599 static COUNTER_U64_DEFINE_EARLY(pcid_save_cnt);
600 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLFLAG_RD,
601 &pcid_save_cnt, "Count of saved TLB context on switch");
603 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
604 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
605 static struct mtx invl_gen_mtx;
606 /* Fake lock object to satisfy turnstiles interface. */
607 static struct lock_object invl_gen_ts = {
610 static struct pmap_invl_gen pmap_invl_gen_head = {
614 static u_long pmap_invl_gen = 1;
615 static int pmap_invl_waiters;
616 static struct callout pmap_invl_callout;
617 static bool pmap_invl_callout_inited;
619 #define PMAP_ASSERT_NOT_IN_DI() \
620 KASSERT(pmap_not_in_di(), ("DI already started"))
627 if ((cpu_feature2 & CPUID2_CX16) == 0)
630 TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
635 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
639 locked = pmap_di_locked();
640 return (sysctl_handle_int(oidp, &locked, 0, req));
642 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
643 CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
644 "Locked delayed invalidation");
646 static bool pmap_not_in_di_l(void);
647 static bool pmap_not_in_di_u(void);
648 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
651 return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
655 pmap_not_in_di_l(void)
657 struct pmap_invl_gen *invl_gen;
659 invl_gen = &curthread->td_md.md_invl_gen;
660 return (invl_gen->gen == 0);
664 pmap_thread_init_invl_gen_l(struct thread *td)
666 struct pmap_invl_gen *invl_gen;
668 invl_gen = &td->td_md.md_invl_gen;
673 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
675 struct turnstile *ts;
677 ts = turnstile_trywait(&invl_gen_ts);
678 if (*m_gen > atomic_load_long(invl_gen))
679 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
681 turnstile_cancel(ts);
685 pmap_delayed_invl_finish_unblock(u_long new_gen)
687 struct turnstile *ts;
689 turnstile_chain_lock(&invl_gen_ts);
690 ts = turnstile_lookup(&invl_gen_ts);
692 pmap_invl_gen = new_gen;
694 turnstile_broadcast(ts, TS_SHARED_QUEUE);
695 turnstile_unpend(ts);
697 turnstile_chain_unlock(&invl_gen_ts);
701 * Start a new Delayed Invalidation (DI) block of code, executed by
702 * the current thread. Within a DI block, the current thread may
703 * destroy both the page table and PV list entries for a mapping and
704 * then release the corresponding PV list lock before ensuring that
705 * the mapping is flushed from the TLBs of any processors with the
709 pmap_delayed_invl_start_l(void)
711 struct pmap_invl_gen *invl_gen;
714 invl_gen = &curthread->td_md.md_invl_gen;
715 PMAP_ASSERT_NOT_IN_DI();
716 mtx_lock(&invl_gen_mtx);
717 if (LIST_EMPTY(&pmap_invl_gen_tracker))
718 currgen = pmap_invl_gen;
720 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
721 invl_gen->gen = currgen + 1;
722 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
723 mtx_unlock(&invl_gen_mtx);
727 * Finish the DI block, previously started by the current thread. All
728 * required TLB flushes for the pages marked by
729 * pmap_delayed_invl_page() must be finished before this function is
732 * This function works by bumping the global DI generation number to
733 * the generation number of the current thread's DI, unless there is a
734 * pending DI that started earlier. In the latter case, bumping the
735 * global DI generation number would incorrectly signal that the
736 * earlier DI had finished. Instead, this function bumps the earlier
737 * DI's generation number to match the generation number of the
738 * current thread's DI.
741 pmap_delayed_invl_finish_l(void)
743 struct pmap_invl_gen *invl_gen, *next;
745 invl_gen = &curthread->td_md.md_invl_gen;
746 KASSERT(invl_gen->gen != 0, ("missed invl_start"));
747 mtx_lock(&invl_gen_mtx);
748 next = LIST_NEXT(invl_gen, link);
750 pmap_delayed_invl_finish_unblock(invl_gen->gen);
752 next->gen = invl_gen->gen;
753 LIST_REMOVE(invl_gen, link);
754 mtx_unlock(&invl_gen_mtx);
759 pmap_not_in_di_u(void)
761 struct pmap_invl_gen *invl_gen;
763 invl_gen = &curthread->td_md.md_invl_gen;
764 return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
768 pmap_thread_init_invl_gen_u(struct thread *td)
770 struct pmap_invl_gen *invl_gen;
772 invl_gen = &td->td_md.md_invl_gen;
774 invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
778 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
780 uint64_t new_high, new_low, old_high, old_low;
783 old_low = new_low = 0;
784 old_high = new_high = (uintptr_t)0;
786 __asm volatile("lock;cmpxchg16b\t%1"
787 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
788 : "b"(new_low), "c" (new_high)
791 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
794 out->next = (void *)old_high;
797 out->next = (void *)new_high;
803 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
804 struct pmap_invl_gen *new_val)
806 uint64_t new_high, new_low, old_high, old_low;
809 new_low = new_val->gen;
810 new_high = (uintptr_t)new_val->next;
811 old_low = old_val->gen;
812 old_high = (uintptr_t)old_val->next;
814 __asm volatile("lock;cmpxchg16b\t%1"
815 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
816 : "b"(new_low), "c" (new_high)
821 static COUNTER_U64_DEFINE_EARLY(pv_page_count);
822 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_page_count, CTLFLAG_RD,
823 &pv_page_count, "Current number of allocated pv pages");
825 static COUNTER_U64_DEFINE_EARLY(user_pt_page_count);
826 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, user_pt_page_count, CTLFLAG_RD,
828 "Current number of allocated page table pages for userspace");
830 static COUNTER_U64_DEFINE_EARLY(kernel_pt_page_count);
831 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, kernel_pt_page_count, CTLFLAG_RD,
832 &kernel_pt_page_count,
833 "Current number of allocated page table pages for the kernel");
837 static COUNTER_U64_DEFINE_EARLY(invl_start_restart);
838 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_start_restart,
839 CTLFLAG_RD, &invl_start_restart,
840 "Number of delayed TLB invalidation request restarts");
842 static COUNTER_U64_DEFINE_EARLY(invl_finish_restart);
843 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
844 &invl_finish_restart,
845 "Number of delayed TLB invalidation completion restarts");
847 static int invl_max_qlen;
848 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
850 "Maximum delayed TLB invalidation request queue length");
853 #define di_delay locks_delay
856 pmap_delayed_invl_start_u(void)
858 struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
860 struct lock_delay_arg lda;
868 invl_gen = &td->td_md.md_invl_gen;
869 PMAP_ASSERT_NOT_IN_DI();
870 lock_delay_arg_init(&lda, &di_delay);
871 invl_gen->saved_pri = 0;
872 pri = td->td_base_pri;
875 pri = td->td_base_pri;
877 invl_gen->saved_pri = pri;
884 for (p = &pmap_invl_gen_head;; p = prev.next) {
886 prevl = (uintptr_t)atomic_load_ptr(&p->next);
887 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
888 PV_STAT(counter_u64_add(invl_start_restart, 1));
894 prev.next = (void *)prevl;
897 if ((ii = invl_max_qlen) < i)
898 atomic_cmpset_int(&invl_max_qlen, ii, i);
901 if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
902 PV_STAT(counter_u64_add(invl_start_restart, 1));
907 new_prev.gen = prev.gen;
908 new_prev.next = invl_gen;
909 invl_gen->gen = prev.gen + 1;
911 /* Formal fence between store to invl->gen and updating *p. */
912 atomic_thread_fence_rel();
915 * After inserting an invl_gen element with invalid bit set,
916 * this thread blocks any other thread trying to enter the
917 * delayed invalidation block. Do not allow to remove us from
918 * the CPU, because it causes starvation for other threads.
923 * ABA for *p is not possible there, since p->gen can only
924 * increase. So if the *p thread finished its di, then
925 * started a new one and got inserted into the list at the
926 * same place, its gen will appear greater than the previously
929 if (!pmap_di_store_invl(p, &prev, &new_prev)) {
931 PV_STAT(counter_u64_add(invl_start_restart, 1));
937 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
938 * invl_gen->next, allowing other threads to iterate past us.
939 * pmap_di_store_invl() provides fence between the generation
940 * write and the update of next.
942 invl_gen->next = NULL;
947 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
948 struct pmap_invl_gen *p)
950 struct pmap_invl_gen prev, new_prev;
954 * Load invl_gen->gen after setting invl_gen->next
955 * PMAP_INVL_GEN_NEXT_INVALID. This prevents larger
956 * generations to propagate to our invl_gen->gen. Lock prefix
957 * in atomic_set_ptr() worked as seq_cst fence.
959 mygen = atomic_load_long(&invl_gen->gen);
961 if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
964 KASSERT(prev.gen < mygen,
965 ("invalid di gen sequence %lu %lu", prev.gen, mygen));
966 new_prev.gen = mygen;
967 new_prev.next = (void *)((uintptr_t)invl_gen->next &
968 ~PMAP_INVL_GEN_NEXT_INVALID);
970 /* Formal fence between load of prev and storing update to it. */
971 atomic_thread_fence_rel();
973 return (pmap_di_store_invl(p, &prev, &new_prev));
977 pmap_delayed_invl_finish_u(void)
979 struct pmap_invl_gen *invl_gen, *p;
981 struct lock_delay_arg lda;
985 invl_gen = &td->td_md.md_invl_gen;
986 KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
987 KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
988 ("missed invl_start: INVALID"));
989 lock_delay_arg_init(&lda, &di_delay);
992 for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
993 prevl = (uintptr_t)atomic_load_ptr(&p->next);
994 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
995 PV_STAT(counter_u64_add(invl_finish_restart, 1));
999 if ((void *)prevl == invl_gen)
1004 * It is legitimate to not find ourself on the list if a
1005 * thread before us finished its DI and started it again.
1007 if (__predict_false(p == NULL)) {
1008 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1014 atomic_set_ptr((uintptr_t *)&invl_gen->next,
1015 PMAP_INVL_GEN_NEXT_INVALID);
1016 if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
1017 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
1018 PMAP_INVL_GEN_NEXT_INVALID);
1020 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1025 if (atomic_load_int(&pmap_invl_waiters) > 0)
1026 pmap_delayed_invl_finish_unblock(0);
1027 if (invl_gen->saved_pri != 0) {
1029 sched_prio(td, invl_gen->saved_pri);
1035 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
1037 struct pmap_invl_gen *p, *pn;
1042 for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
1044 nextl = (uintptr_t)atomic_load_ptr(&p->next);
1045 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
1046 td = first ? NULL : __containerof(p, struct thread,
1048 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
1049 (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
1050 td != NULL ? td->td_tid : -1);
1056 static COUNTER_U64_DEFINE_EARLY(invl_wait);
1057 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait,
1058 CTLFLAG_RD, &invl_wait,
1059 "Number of times DI invalidation blocked pmap_remove_all/write");
1061 static COUNTER_U64_DEFINE_EARLY(invl_wait_slow);
1062 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD,
1063 &invl_wait_slow, "Number of slow invalidation waits for lockless DI");
1069 pmap_delayed_invl_genp(vm_page_t m)
1074 pa = VM_PAGE_TO_PHYS(m);
1075 if (__predict_false((pa) > pmap_last_pa))
1076 gen = &pv_dummy_large.pv_invl_gen;
1078 gen = &(pa_to_pmdp(pa)->pv_invl_gen);
1084 pmap_delayed_invl_genp(vm_page_t m)
1087 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
1092 pmap_delayed_invl_callout_func(void *arg __unused)
1095 if (atomic_load_int(&pmap_invl_waiters) == 0)
1097 pmap_delayed_invl_finish_unblock(0);
1101 pmap_delayed_invl_callout_init(void *arg __unused)
1104 if (pmap_di_locked())
1106 callout_init(&pmap_invl_callout, 1);
1107 pmap_invl_callout_inited = true;
1109 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
1110 pmap_delayed_invl_callout_init, NULL);
1113 * Ensure that all currently executing DI blocks, that need to flush
1114 * TLB for the given page m, actually flushed the TLB at the time the
1115 * function returned. If the page m has an empty PV list and we call
1116 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1117 * valid mapping for the page m in either its page table or TLB.
1119 * This function works by blocking until the global DI generation
1120 * number catches up with the generation number associated with the
1121 * given page m and its PV list. Since this function's callers
1122 * typically own an object lock and sometimes own a page lock, it
1123 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
1127 pmap_delayed_invl_wait_l(vm_page_t m)
1131 bool accounted = false;
1134 m_gen = pmap_delayed_invl_genp(m);
1135 while (*m_gen > pmap_invl_gen) {
1138 counter_u64_add(invl_wait, 1);
1142 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1147 pmap_delayed_invl_wait_u(vm_page_t m)
1150 struct lock_delay_arg lda;
1154 m_gen = pmap_delayed_invl_genp(m);
1155 lock_delay_arg_init(&lda, &di_delay);
1156 while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1157 if (fast || !pmap_invl_callout_inited) {
1158 PV_STAT(counter_u64_add(invl_wait, 1));
1163 * The page's invalidation generation number
1164 * is still below the current thread's number.
1165 * Prepare to block so that we do not waste
1166 * CPU cycles or worse, suffer livelock.
1168 * Since it is impossible to block without
1169 * racing with pmap_delayed_invl_finish_u(),
1170 * prepare for the race by incrementing
1171 * pmap_invl_waiters and arming a 1-tick
1172 * callout which will unblock us if we lose
1175 atomic_add_int(&pmap_invl_waiters, 1);
1178 * Re-check the current thread's invalidation
1179 * generation after incrementing
1180 * pmap_invl_waiters, so that there is no race
1181 * with pmap_delayed_invl_finish_u() setting
1182 * the page generation and checking
1183 * pmap_invl_waiters. The only race allowed
1184 * is for a missed unblock, which is handled
1188 atomic_load_long(&pmap_invl_gen_head.gen)) {
1189 callout_reset(&pmap_invl_callout, 1,
1190 pmap_delayed_invl_callout_func, NULL);
1191 PV_STAT(counter_u64_add(invl_wait_slow, 1));
1192 pmap_delayed_invl_wait_block(m_gen,
1193 &pmap_invl_gen_head.gen);
1195 atomic_add_int(&pmap_invl_waiters, -1);
1200 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1203 return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1204 pmap_thread_init_invl_gen_u);
1207 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1210 return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1211 pmap_delayed_invl_start_u);
1214 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1217 return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1218 pmap_delayed_invl_finish_u);
1221 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1224 return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1225 pmap_delayed_invl_wait_u);
1229 * Mark the page m's PV list as participating in the current thread's
1230 * DI block. Any threads concurrently using m's PV list to remove or
1231 * restrict all mappings to m will wait for the current thread's DI
1232 * block to complete before proceeding.
1234 * The function works by setting the DI generation number for m's PV
1235 * list to at least the DI generation number of the current thread.
1236 * This forces a caller of pmap_delayed_invl_wait() to block until
1237 * current thread calls pmap_delayed_invl_finish().
1240 pmap_delayed_invl_page(vm_page_t m)
1244 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1245 gen = curthread->td_md.md_invl_gen.gen;
1248 m_gen = pmap_delayed_invl_genp(m);
1256 static caddr_t crashdumpmap;
1259 * Internal flags for pmap_enter()'s helper functions.
1261 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
1262 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
1265 * Internal flags for pmap_mapdev_internal() and
1266 * pmap_change_props_locked().
1268 #define MAPDEV_FLUSHCACHE 0x00000001 /* Flush cache after mapping. */
1269 #define MAPDEV_SETATTR 0x00000002 /* Modify existing attrs. */
1270 #define MAPDEV_ASSERTVALID 0x00000004 /* Assert mapping validity. */
1272 TAILQ_HEAD(pv_chunklist, pv_chunk);
1274 static void free_pv_chunk(struct pv_chunk *pc);
1275 static void free_pv_chunk_batch(struct pv_chunklist *batch);
1276 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
1277 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1278 static int popcnt_pc_map_pq(uint64_t *map);
1279 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1280 static void reserve_pv_entries(pmap_t pmap, int needed,
1281 struct rwlock **lockp);
1282 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1283 struct rwlock **lockp);
1284 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1285 u_int flags, struct rwlock **lockp);
1286 #if VM_NRESERVLEVEL > 0
1287 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1288 struct rwlock **lockp);
1290 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1291 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1294 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
1295 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1296 vm_prot_t prot, int mode, int flags);
1297 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1298 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1299 vm_offset_t va, struct rwlock **lockp);
1300 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1302 static int pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1303 vm_prot_t prot, struct rwlock **lockp);
1304 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1305 u_int flags, vm_page_t m, struct rwlock **lockp);
1306 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1307 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1308 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1309 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
1310 bool allpte_PG_A_set);
1311 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1313 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1315 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1317 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1318 static vm_page_t pmap_large_map_getptp_unlocked(void);
1319 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1320 #if VM_NRESERVLEVEL > 0
1321 static bool pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1322 vm_page_t mpte, struct rwlock **lockp);
1324 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1326 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1327 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1329 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1330 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1331 static void pmap_pti_wire_pte(void *pte);
1332 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1333 struct spglist *free, struct rwlock **lockp);
1334 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1335 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1336 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1337 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1338 struct spglist *free);
1339 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1340 pd_entry_t *pde, struct spglist *free,
1341 struct rwlock **lockp);
1342 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1343 vm_page_t m, struct rwlock **lockp);
1344 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1346 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1348 static pd_entry_t *pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
1349 struct rwlock **lockp);
1350 static vm_page_t pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex,
1351 struct rwlock **lockp, vm_offset_t va);
1352 static vm_page_t pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex,
1353 struct rwlock **lockp, vm_offset_t va);
1354 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1355 struct rwlock **lockp);
1357 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1358 struct spglist *free);
1359 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1361 static vm_page_t pmap_alloc_pt_page(pmap_t, vm_pindex_t, int);
1362 static void pmap_free_pt_page(pmap_t, vm_page_t, bool);
1364 /********************/
1365 /* Inline functions */
1366 /********************/
1369 * Return a non-clipped indexes for a given VA, which are page table
1370 * pages indexes at the corresponding level.
1372 static __inline vm_pindex_t
1373 pmap_pde_pindex(vm_offset_t va)
1375 return (va >> PDRSHIFT);
1378 static __inline vm_pindex_t
1379 pmap_pdpe_pindex(vm_offset_t va)
1381 return (NUPDE + (va >> PDPSHIFT));
1384 static __inline vm_pindex_t
1385 pmap_pml4e_pindex(vm_offset_t va)
1387 return (NUPDE + NUPDPE + (va >> PML4SHIFT));
1390 static __inline vm_pindex_t
1391 pmap_pml5e_pindex(vm_offset_t va)
1393 return (NUPDE + NUPDPE + NUPML4E + (va >> PML5SHIFT));
1396 static __inline pml4_entry_t *
1397 pmap_pml5e(pmap_t pmap, vm_offset_t va)
1400 MPASS(pmap_is_la57(pmap));
1401 return (&pmap->pm_pmltop[pmap_pml5e_index(va)]);
1404 static __inline pml4_entry_t *
1405 pmap_pml5e_u(pmap_t pmap, vm_offset_t va)
1408 MPASS(pmap_is_la57(pmap));
1409 return (&pmap->pm_pmltopu[pmap_pml5e_index(va)]);
1412 static __inline pml4_entry_t *
1413 pmap_pml5e_to_pml4e(pml5_entry_t *pml5e, vm_offset_t va)
1415 pml4_entry_t *pml4e;
1417 /* XXX MPASS(pmap_is_la57(pmap); */
1418 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1419 return (&pml4e[pmap_pml4e_index(va)]);
1422 /* Return a pointer to the PML4 slot that corresponds to a VA */
1423 static __inline pml4_entry_t *
1424 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1426 pml5_entry_t *pml5e;
1427 pml4_entry_t *pml4e;
1430 if (pmap_is_la57(pmap)) {
1431 pml5e = pmap_pml5e(pmap, va);
1432 PG_V = pmap_valid_bit(pmap);
1433 if ((*pml5e & PG_V) == 0)
1435 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1437 pml4e = pmap->pm_pmltop;
1439 return (&pml4e[pmap_pml4e_index(va)]);
1442 static __inline pml4_entry_t *
1443 pmap_pml4e_u(pmap_t pmap, vm_offset_t va)
1445 MPASS(!pmap_is_la57(pmap));
1446 return (&pmap->pm_pmltopu[pmap_pml4e_index(va)]);
1449 /* Return a pointer to the PDP slot that corresponds to a VA */
1450 static __inline pdp_entry_t *
1451 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1455 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1456 return (&pdpe[pmap_pdpe_index(va)]);
1459 /* Return a pointer to the PDP slot that corresponds to a VA */
1460 static __inline pdp_entry_t *
1461 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1463 pml4_entry_t *pml4e;
1466 PG_V = pmap_valid_bit(pmap);
1467 pml4e = pmap_pml4e(pmap, va);
1468 if (pml4e == NULL || (*pml4e & PG_V) == 0)
1470 return (pmap_pml4e_to_pdpe(pml4e, va));
1473 /* Return a pointer to the PD slot that corresponds to a VA */
1474 static __inline pd_entry_t *
1475 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1479 KASSERT((*pdpe & PG_PS) == 0,
1480 ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
1481 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1482 return (&pde[pmap_pde_index(va)]);
1485 /* Return a pointer to the PD slot that corresponds to a VA */
1486 static __inline pd_entry_t *
1487 pmap_pde(pmap_t pmap, vm_offset_t va)
1492 PG_V = pmap_valid_bit(pmap);
1493 pdpe = pmap_pdpe(pmap, va);
1494 if (pdpe == NULL || (*pdpe & PG_V) == 0)
1496 KASSERT((*pdpe & PG_PS) == 0,
1497 ("pmap_pde for 1G page, pmap %p va %#lx", pmap, va));
1498 return (pmap_pdpe_to_pde(pdpe, va));
1501 /* Return a pointer to the PT slot that corresponds to a VA */
1502 static __inline pt_entry_t *
1503 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1507 KASSERT((*pde & PG_PS) == 0,
1508 ("%s: pde %#lx is a leaf", __func__, *pde));
1509 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1510 return (&pte[pmap_pte_index(va)]);
1513 /* Return a pointer to the PT slot that corresponds to a VA */
1514 static __inline pt_entry_t *
1515 pmap_pte(pmap_t pmap, vm_offset_t va)
1520 PG_V = pmap_valid_bit(pmap);
1521 pde = pmap_pde(pmap, va);
1522 if (pde == NULL || (*pde & PG_V) == 0)
1524 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
1525 return ((pt_entry_t *)pde);
1526 return (pmap_pde_to_pte(pde, va));
1529 static __inline void
1530 pmap_resident_count_adj(pmap_t pmap, int count)
1533 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1534 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1535 ("pmap %p resident count underflow %ld %d", pmap,
1536 pmap->pm_stats.resident_count, count));
1537 pmap->pm_stats.resident_count += count;
1540 static __inline void
1541 pmap_pt_page_count_pinit(pmap_t pmap, int count)
1543 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1544 ("pmap %p resident count underflow %ld %d", pmap,
1545 pmap->pm_stats.resident_count, count));
1546 pmap->pm_stats.resident_count += count;
1549 static __inline void
1550 pmap_pt_page_count_adj(pmap_t pmap, int count)
1552 if (pmap == kernel_pmap)
1553 counter_u64_add(kernel_pt_page_count, count);
1556 pmap_resident_count_adj(pmap, count);
1557 counter_u64_add(user_pt_page_count, count);
1561 pt_entry_t vtoptem __read_mostly = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
1562 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1) << 3;
1563 vm_offset_t PTmap __read_mostly = (vm_offset_t)P4Tmap;
1565 PMAP_INLINE pt_entry_t *
1566 vtopte(vm_offset_t va)
1568 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1570 return ((pt_entry_t *)(PTmap + ((va >> (PAGE_SHIFT - 3)) & vtoptem)));
1573 pd_entry_t vtopdem __read_mostly = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
1574 NPML4EPGSHIFT)) - 1) << 3;
1575 vm_offset_t PDmap __read_mostly = (vm_offset_t)P4Dmap;
1577 static __inline pd_entry_t *
1578 vtopde(vm_offset_t va)
1580 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1582 return ((pt_entry_t *)(PDmap + ((va >> (PDRSHIFT - 3)) & vtopdem)));
1586 allocpages(vm_paddr_t *firstaddr, int n)
1591 bzero((void *)ret, n * PAGE_SIZE);
1592 *firstaddr += n * PAGE_SIZE;
1596 CTASSERT(powerof2(NDMPML4E));
1598 /* number of kernel PDP slots */
1599 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
1602 nkpt_init(vm_paddr_t addr)
1609 pt_pages = howmany(addr - kernphys, NBPDR) + 1; /* +1 for 2M hole @0 */
1610 pt_pages += NKPDPE(pt_pages);
1613 * Add some slop beyond the bare minimum required for bootstrapping
1616 * This is quite important when allocating KVA for kernel modules.
1617 * The modules are required to be linked in the negative 2GB of
1618 * the address space. If we run out of KVA in this region then
1619 * pmap_growkernel() will need to allocate page table pages to map
1620 * the entire 512GB of KVA space which is an unnecessary tax on
1623 * Secondly, device memory mapped as part of setting up the low-
1624 * level console(s) is taken from KVA, starting at virtual_avail.
1625 * This is because cninit() is called after pmap_bootstrap() but
1626 * before vm_init() and pmap_init(). 20MB for a frame buffer is
1629 pt_pages += 32; /* 64MB additional slop. */
1635 * Returns the proper write/execute permission for a physical page that is
1636 * part of the initial boot allocations.
1638 * If the page has kernel text, it is marked as read-only. If the page has
1639 * kernel read-only data, it is marked as read-only/not-executable. If the
1640 * page has only read-write data, it is marked as read-write/not-executable.
1641 * If the page is below/above the kernel range, it is marked as read-write.
1643 * This function operates on 2M pages, since we map the kernel space that
1646 static inline pt_entry_t
1647 bootaddr_rwx(vm_paddr_t pa)
1650 * The kernel is loaded at a 2MB-aligned address, and memory below that
1651 * need not be executable. The .bss section is padded to a 2MB
1652 * boundary, so memory following the kernel need not be executable
1653 * either. Preloaded kernel modules have their mapping permissions
1654 * fixed up by the linker.
1656 if (pa < trunc_2mpage(kernphys + btext - KERNSTART) ||
1657 pa >= trunc_2mpage(kernphys + _end - KERNSTART))
1658 return (X86_PG_RW | pg_nx);
1661 * The linker should ensure that the read-only and read-write
1662 * portions don't share the same 2M page, so this shouldn't
1663 * impact read-only data. However, in any case, any page with
1664 * read-write data needs to be read-write.
1666 if (pa >= trunc_2mpage(kernphys + brwsection - KERNSTART))
1667 return (X86_PG_RW | pg_nx);
1670 * Mark any 2M page containing kernel text as read-only. Mark
1671 * other pages with read-only data as read-only and not executable.
1672 * (It is likely a small portion of the read-only data section will
1673 * be marked as read-only, but executable. This should be acceptable
1674 * since the read-only protection will keep the data from changing.)
1675 * Note that fixups to the .text section will still work until we
1678 if (pa < round_2mpage(kernphys + etext - KERNSTART))
1684 create_pagetables(vm_paddr_t *firstaddr)
1689 uint64_t DMPDkernphys;
1693 uint64_t KASANPDphys, KASANPTphys, KASANphys;
1694 vm_offset_t kasankernbase;
1695 int kasankpdpi, kasankpdi, nkasanpte;
1697 int i, j, ndm1g, nkpdpe, nkdmpde;
1700 /* Allocate page table pages for the direct map */
1701 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1702 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1704 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1705 if (ndmpdpphys > NDMPML4E) {
1707 * Each NDMPML4E allows 512 GB, so limit to that,
1708 * and then readjust ndmpdp and ndmpdpphys.
1710 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1711 Maxmem = atop(NDMPML4E * NBPML4);
1712 ndmpdpphys = NDMPML4E;
1713 ndmpdp = NDMPML4E * NPDEPG;
1715 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1717 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1719 * Calculate the number of 1G pages that will fully fit in
1722 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1725 * Allocate 2M pages for the kernel. These will be used in
1726 * place of the one or more 1G pages from ndm1g that maps
1727 * kernel memory into DMAP.
1729 nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1730 kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1731 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1734 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1735 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1737 /* Allocate pages. */
1738 KPML4phys = allocpages(firstaddr, 1);
1739 KPDPphys = allocpages(firstaddr, NKPML4E);
1741 KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1742 KASANPDphys = allocpages(firstaddr, 1);
1746 * The KMSAN shadow maps are initially left unpopulated, since there is
1747 * no need to shadow memory above KERNBASE.
1749 KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1750 KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1754 * Allocate the initial number of kernel page table pages required to
1755 * bootstrap. We defer this until after all memory-size dependent
1756 * allocations are done (e.g. direct map), so that we don't have to
1757 * build in too much slop in our estimate.
1759 * Note that when NKPML4E > 1, we have an empty page underneath
1760 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1761 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1763 nkpt_init(*firstaddr);
1764 nkpdpe = NKPDPE(nkpt);
1766 KPTphys = allocpages(firstaddr, nkpt);
1767 KPDphys = allocpages(firstaddr, nkpdpe);
1770 nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1771 KASANPTphys = allocpages(firstaddr, nkasanpte);
1772 KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1776 * Connect the zero-filled PT pages to their PD entries. This
1777 * implicitly maps the PT pages at their correct locations within
1780 pd_p = (pd_entry_t *)KPDphys;
1781 for (i = 0; i < nkpt; i++)
1782 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1785 * Map from start of the kernel in physical memory (staging
1786 * area) to the end of loader preallocated memory using 2MB
1787 * pages. This replaces some of the PD entries created above.
1788 * For compatibility, identity map 2M at the start.
1790 pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1792 for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1793 /* Preset PG_M and PG_A because demotion expects it. */
1794 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1795 X86_PG_A | bootaddr_rwx(pax);
1799 * Because we map the physical blocks in 2M pages, adjust firstaddr
1800 * to record the physical blocks we've actually mapped into kernel
1801 * virtual address space.
1803 if (*firstaddr < round_2mpage(KERNend))
1804 *firstaddr = round_2mpage(KERNend);
1806 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1807 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1808 for (i = 0; i < nkpdpe; i++)
1809 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1812 kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1813 kasankpdpi = pmap_pdpe_index(kasankernbase);
1814 kasankpdi = pmap_pde_index(kasankernbase);
1816 pdp_p = (pdp_entry_t *)KASANPDPphys;
1817 pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1819 pd_p = (pd_entry_t *)KASANPDphys;
1820 for (i = 0; i < nkasanpte; i++)
1821 pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1824 pt_p = (pt_entry_t *)KASANPTphys;
1825 for (i = 0; i < nkasanpte * NPTEPG; i++)
1826 pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1827 X86_PG_M | X86_PG_A | pg_nx;
1831 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1832 * the end of physical memory is not aligned to a 1GB page boundary,
1833 * then the residual physical memory is mapped with 2MB pages. Later,
1834 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1835 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1836 * that are partially used.
1838 pd_p = (pd_entry_t *)DMPDphys;
1839 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1840 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1841 /* Preset PG_M and PG_A because demotion expects it. */
1842 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1843 X86_PG_M | X86_PG_A | pg_nx;
1845 pdp_p = (pdp_entry_t *)DMPDPphys;
1846 for (i = 0; i < ndm1g; i++) {
1847 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1848 /* Preset PG_M and PG_A because demotion expects it. */
1849 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1850 X86_PG_M | X86_PG_A | pg_nx;
1852 for (j = 0; i < ndmpdp; i++, j++) {
1853 pdp_p[i] = DMPDphys + ptoa(j);
1854 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1858 * Instead of using a 1G page for the memory containing the kernel,
1859 * use 2M pages with read-only and no-execute permissions. (If using 1G
1860 * pages, this will partially overwrite the PDPEs above.)
1863 pd_p = (pd_entry_t *)DMPDkernphys;
1864 for (i = 0, pax = rounddown2(kernphys, NBPDP);
1865 i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1866 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1867 X86_PG_A | pg_nx | bootaddr_rwx(pax);
1869 j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1870 for (i = 0; i < nkdmpde; i++) {
1871 pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1872 X86_PG_RW | X86_PG_V | pg_nx;
1876 /* And recursively map PML4 to itself in order to get PTmap */
1877 p4_p = (pml4_entry_t *)KPML4phys;
1878 p4_p[PML4PML4I] = KPML4phys;
1879 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1882 /* Connect the KASAN shadow map slots up to the PML4. */
1883 for (i = 0; i < NKASANPML4E; i++) {
1884 p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1885 p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1890 /* Connect the KMSAN shadow map slots up to the PML4. */
1891 for (i = 0; i < NKMSANSHADPML4E; i++) {
1892 p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1893 p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1896 /* Connect the KMSAN origin map slots up to the PML4. */
1897 for (i = 0; i < NKMSANORIGPML4E; i++) {
1898 p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1899 p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1903 /* Connect the Direct Map slots up to the PML4. */
1904 for (i = 0; i < ndmpdpphys; i++) {
1905 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1906 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1909 /* Connect the KVA slots up to the PML4 */
1910 for (i = 0; i < NKPML4E; i++) {
1911 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1912 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1915 kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1920 * Bootstrap the system enough to run with virtual memory.
1922 * On amd64 this is called after mapping has already been enabled
1923 * and just syncs the pmap module with what has already been done.
1924 * [We can't call it easily with mapping off since the kernel is not
1925 * mapped with PA == VA, hence we would have to relocate every address
1926 * from the linked base (virtual) address "KERNBASE" to the actual
1927 * (physical) address starting relative to 0]
1930 pmap_bootstrap(vm_paddr_t *firstaddr)
1933 pt_entry_t *pte, *pcpu_pte;
1934 struct region_descriptor r_gdt;
1935 uint64_t cr4, pcpu0_phys;
1940 KERNend = *firstaddr;
1941 res = atop(KERNend - (vm_paddr_t)kernphys);
1947 * Create an initial set of page tables to run the kernel in.
1949 create_pagetables(firstaddr);
1951 pcpu0_phys = allocpages(firstaddr, 1);
1954 * Add a physical memory segment (vm_phys_seg) corresponding to the
1955 * preallocated kernel page table pages so that vm_page structures
1956 * representing these pages will be created. The vm_page structures
1957 * are required for promotion of the corresponding kernel virtual
1958 * addresses to superpage mappings.
1960 vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1963 * Account for the virtual addresses mapped by create_pagetables().
1965 virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1966 (vm_paddr_t)kernphys);
1967 virtual_end = VM_MAX_KERNEL_ADDRESS;
1970 * Enable PG_G global pages, then switch to the kernel page
1971 * table from the bootstrap page table. After the switch, it
1972 * is possible to enable SMEP and SMAP since PG_U bits are
1978 load_cr3(KPML4phys);
1979 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1981 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1986 * Initialize the kernel pmap (which is statically allocated).
1987 * Count bootstrap data as being resident in case any of this data is
1988 * later unmapped (using pmap_remove()) and freed.
1990 PMAP_LOCK_INIT(kernel_pmap);
1991 kernel_pmap->pm_pmltop = kernel_pml4;
1992 kernel_pmap->pm_cr3 = KPML4phys;
1993 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1994 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1995 kernel_pmap->pm_stats.resident_count = res;
1996 kernel_pmap->pm_flags = pmap_flags;
1999 * The kernel pmap is always active on all CPUs. Once CPUs are
2000 * enumerated, the mask will be set equal to all_cpus.
2002 CPU_FILL(&kernel_pmap->pm_active);
2005 * Initialize the TLB invalidations generation number lock.
2007 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
2010 * Reserve some special page table entries/VA space for temporary
2013 #define SYSMAP(c, p, v, n) \
2014 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
2020 * Crashdump maps. The first page is reused as CMAP1 for the
2023 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
2024 CADDR1 = crashdumpmap;
2026 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
2030 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2031 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2032 * number of CPUs and NUMA affinity.
2034 pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2035 X86_PG_M | X86_PG_A;
2036 for (i = 1; i < MAXCPU; i++)
2040 * Re-initialize PCPU area for BSP after switching.
2041 * Make hardware use gdt and common_tss from the new PCPU.
2043 STAILQ_INIT(&cpuhead);
2044 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2045 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2046 amd64_bsp_pcpu_init1(&__pcpu[0]);
2047 amd64_bsp_ist_init(&__pcpu[0]);
2048 __pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2050 memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2051 sizeof(struct user_segment_descriptor));
2052 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2053 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2054 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2055 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2056 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2058 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2059 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2060 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2061 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2064 * Initialize the PAT MSR.
2065 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2066 * side-effect, invalidates stale PG_G TLB entries that might
2067 * have been created in our pre-boot environment.
2071 /* Initialize TLB Context Id. */
2072 if (pmap_pcid_enabled) {
2073 kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2074 offsetof(struct pcpu, pc_kpmap_store);
2076 PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2077 PCPU_SET(kpmap_store.pm_gen, 1);
2080 * PMAP_PCID_KERN + 1 is used for initialization of
2081 * proc0 pmap. The pmap' pcid state might be used by
2082 * EFIRT entry before first context switch, so it
2083 * needs to be valid.
2085 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2086 PCPU_SET(pcid_gen, 1);
2089 * pcpu area for APs is zeroed during AP startup.
2090 * pc_pcid_next and pc_pcid_gen are initialized by AP
2091 * during pcpu setup.
2093 load_cr4(rcr4() | CR4_PCIDE);
2099 * Setup the PAT MSR.
2108 /* Bail if this CPU doesn't implement PAT. */
2109 if ((cpu_feature & CPUID_PAT) == 0)
2112 /* Set default PAT index table. */
2113 for (i = 0; i < PAT_INDEX_SIZE; i++)
2115 pat_index[PAT_WRITE_BACK] = 0;
2116 pat_index[PAT_WRITE_THROUGH] = 1;
2117 pat_index[PAT_UNCACHEABLE] = 3;
2118 pat_index[PAT_WRITE_COMBINING] = 6;
2119 pat_index[PAT_WRITE_PROTECTED] = 5;
2120 pat_index[PAT_UNCACHED] = 2;
2123 * Initialize default PAT entries.
2124 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2125 * Program 5 and 6 as WP and WC.
2127 * Leave 4 and 7 as WB and UC. Note that a recursive page table
2128 * mapping for a 2M page uses a PAT value with the bit 3 set due
2129 * to its overload with PG_PS.
2131 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2132 PAT_VALUE(1, PAT_WRITE_THROUGH) |
2133 PAT_VALUE(2, PAT_UNCACHED) |
2134 PAT_VALUE(3, PAT_UNCACHEABLE) |
2135 PAT_VALUE(4, PAT_WRITE_BACK) |
2136 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2137 PAT_VALUE(6, PAT_WRITE_COMBINING) |
2138 PAT_VALUE(7, PAT_UNCACHEABLE);
2142 load_cr4(cr4 & ~CR4_PGE);
2144 /* Disable caches (CD = 1, NW = 0). */
2146 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2148 /* Flushes caches and TLBs. */
2152 /* Update PAT and index table. */
2153 wrmsr(MSR_PAT, pat_msr);
2155 /* Flush caches and TLBs again. */
2159 /* Restore caches and PGE. */
2165 pmap_page_alloc_below_4g(bool zeroed)
2167 return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2168 1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2171 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2172 la57_trampoline_gdt[], la57_trampoline_end[];
2175 pmap_bootstrap_la57(void *arg __unused)
2178 pml5_entry_t *v_pml5;
2179 pml4_entry_t *v_pml4;
2183 vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2184 void (*la57_tramp)(uint64_t pml5);
2185 struct region_descriptor r_gdt;
2187 if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2189 TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2193 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2194 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2196 m_code = pmap_page_alloc_below_4g(true);
2197 v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2198 m_pml5 = pmap_page_alloc_below_4g(true);
2199 KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2200 v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2201 m_pml4 = pmap_page_alloc_below_4g(true);
2202 v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2203 m_pdp = pmap_page_alloc_below_4g(true);
2204 v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2205 m_pd = pmap_page_alloc_below_4g(true);
2206 v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2207 m_pt = pmap_page_alloc_below_4g(true);
2208 v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2211 * Map m_code 1:1, it appears below 4G in KVA due to physical
2212 * address being below 4G. Since kernel KVA is in upper half,
2213 * the pml4e should be zero and free for temporary use.
2215 kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2216 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2218 v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2219 VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2221 v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2222 VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2224 v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2225 VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2229 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2230 * entering all existing kernel mappings into level 5 table.
2232 v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2233 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g;
2236 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2238 v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2239 VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2241 v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2242 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2246 * Copy and call the 48->57 trampoline, hope we return there, alive.
2248 bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2249 *(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2250 la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2251 la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2252 invlpg((vm_offset_t)la57_tramp);
2253 la57_tramp(KPML5phys);
2256 * gdt was necessary reset, switch back to our gdt.
2259 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2263 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2264 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2265 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2268 * Now unmap the trampoline, and free the pages.
2269 * Clear pml5 entry used for 1:1 trampoline mapping.
2271 pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2272 invlpg((vm_offset_t)v_code);
2273 vm_page_free(m_code);
2274 vm_page_free(m_pdp);
2279 * Recursively map PML5 to itself in order to get PTmap and
2282 v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2284 vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2285 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2286 PTmap = (vm_offset_t)P5Tmap;
2287 vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2288 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2289 PDmap = (vm_offset_t)P5Dmap;
2291 kernel_pmap->pm_cr3 = KPML5phys;
2292 kernel_pmap->pm_pmltop = v_pml5;
2293 pmap_pt_page_count_adj(kernel_pmap, 1);
2295 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2298 * Initialize a vm_page's machine-dependent fields.
2301 pmap_page_init(vm_page_t m)
2304 TAILQ_INIT(&m->md.pv_list);
2305 m->md.pat_mode = PAT_WRITE_BACK;
2308 static int pmap_allow_2m_x_ept;
2309 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2310 &pmap_allow_2m_x_ept, 0,
2311 "Allow executable superpage mappings in EPT");
2314 pmap_allow_2m_x_ept_recalculate(void)
2317 * SKL002, SKL012S. Since the EPT format is only used by
2318 * Intel CPUs, the vendor check is merely a formality.
2320 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2321 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2322 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2323 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
2324 CPUID_TO_MODEL(cpu_id) == 0x27 ||
2325 CPUID_TO_MODEL(cpu_id) == 0x35 ||
2326 CPUID_TO_MODEL(cpu_id) == 0x36 ||
2327 CPUID_TO_MODEL(cpu_id) == 0x37 ||
2328 CPUID_TO_MODEL(cpu_id) == 0x86 ||
2329 CPUID_TO_MODEL(cpu_id) == 0x1c ||
2330 CPUID_TO_MODEL(cpu_id) == 0x4a ||
2331 CPUID_TO_MODEL(cpu_id) == 0x4c ||
2332 CPUID_TO_MODEL(cpu_id) == 0x4d ||
2333 CPUID_TO_MODEL(cpu_id) == 0x5a ||
2334 CPUID_TO_MODEL(cpu_id) == 0x5c ||
2335 CPUID_TO_MODEL(cpu_id) == 0x5d ||
2336 CPUID_TO_MODEL(cpu_id) == 0x5f ||
2337 CPUID_TO_MODEL(cpu_id) == 0x6e ||
2338 CPUID_TO_MODEL(cpu_id) == 0x7a ||
2339 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
2340 CPUID_TO_MODEL(cpu_id) == 0x85))))
2341 pmap_allow_2m_x_ept = 1;
2342 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2346 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2349 return (pmap->pm_type != PT_EPT || !executable ||
2350 !pmap_allow_2m_x_ept);
2355 pmap_init_pv_table(void)
2357 struct pmap_large_md_page *pvd;
2359 long start, end, highest, pv_npg;
2360 int domain, i, j, pages;
2363 * For correctness we depend on the size being evenly divisible into a
2364 * page. As a tradeoff between performance and total memory use, the
2365 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2366 * avoids false-sharing, but not being 128 bytes potentially allows for
2367 * avoidable traffic due to adjacent cacheline prefetcher.
2369 * Assert the size so that accidental changes fail to compile.
2371 CTASSERT((sizeof(*pvd) == 64));
2374 * Calculate the size of the array.
2376 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2377 pv_npg = howmany(pmap_last_pa, NBPDR);
2378 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2380 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2381 if (pv_table == NULL)
2382 panic("%s: kva_alloc failed\n", __func__);
2385 * Iterate physical segments to allocate space for respective pages.
2389 for (i = 0; i < vm_phys_nsegs; i++) {
2390 end = vm_phys_segs[i].end / NBPDR;
2391 domain = vm_phys_segs[i].domain;
2396 start = highest + 1;
2397 pvd = &pv_table[start];
2399 pages = end - start + 1;
2400 s = round_page(pages * sizeof(*pvd));
2401 highest = start + (s / sizeof(*pvd)) - 1;
2403 for (j = 0; j < s; j += PAGE_SIZE) {
2404 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2406 panic("failed to allocate PV table page");
2407 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2410 for (j = 0; j < s / sizeof(*pvd); j++) {
2411 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2412 TAILQ_INIT(&pvd->pv_page.pv_list);
2413 pvd->pv_page.pv_gen = 0;
2414 pvd->pv_page.pat_mode = 0;
2415 pvd->pv_invl_gen = 0;
2419 pvd = &pv_dummy_large;
2420 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2421 TAILQ_INIT(&pvd->pv_page.pv_list);
2422 pvd->pv_page.pv_gen = 0;
2423 pvd->pv_page.pat_mode = 0;
2424 pvd->pv_invl_gen = 0;
2428 pmap_init_pv_table(void)
2434 * Initialize the pool of pv list locks.
2436 for (i = 0; i < NPV_LIST_LOCKS; i++)
2437 rw_init(&pv_list_locks[i], "pmap pv list");
2440 * Calculate the size of the pv head table for superpages.
2442 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2445 * Allocate memory for the pv head table for superpages.
2447 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2449 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2450 for (i = 0; i < pv_npg; i++)
2451 TAILQ_INIT(&pv_table[i].pv_list);
2452 TAILQ_INIT(&pv_dummy.pv_list);
2457 * Initialize the pmap module.
2458 * Called by vm_init, to initialize any structures that the pmap
2459 * system needs to map virtual memory.
2464 struct pmap_preinit_mapping *ppim;
2466 int error, i, ret, skz63;
2468 /* L1TF, reserve page @0 unconditionally */
2469 vm_page_blacklist_add(0, bootverbose);
2471 /* Detect bare-metal Skylake Server and Skylake-X. */
2472 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2473 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2475 * Skylake-X errata SKZ63. Processor May Hang When
2476 * Executing Code In an HLE Transaction Region between
2477 * 40000000H and 403FFFFFH.
2479 * Mark the pages in the range as preallocated. It
2480 * seems to be impossible to distinguish between
2481 * Skylake Server and Skylake X.
2484 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2487 printf("SKZ63: skipping 4M RAM starting "
2488 "at physical 1G\n");
2489 for (i = 0; i < atop(0x400000); i++) {
2490 ret = vm_page_blacklist_add(0x40000000 +
2492 if (!ret && bootverbose)
2493 printf("page at %#lx already used\n",
2494 0x40000000 + ptoa(i));
2500 pmap_allow_2m_x_ept_recalculate();
2503 * Initialize the vm page array entries for the kernel pmap's
2506 PMAP_LOCK(kernel_pmap);
2507 for (i = 0; i < nkpt; i++) {
2508 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2509 KASSERT(mpte >= vm_page_array &&
2510 mpte < &vm_page_array[vm_page_array_size],
2511 ("pmap_init: page table page is out of range"));
2512 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2513 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2514 mpte->ref_count = 1;
2517 * Collect the page table pages that were replaced by a 2MB
2518 * page in create_pagetables(). They are zero filled.
2521 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2522 pmap_insert_pt_page(kernel_pmap, mpte, false, false))
2523 panic("pmap_init: pmap_insert_pt_page failed");
2525 PMAP_UNLOCK(kernel_pmap);
2529 * If the kernel is running on a virtual machine, then it must assume
2530 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2531 * be prepared for the hypervisor changing the vendor and family that
2532 * are reported by CPUID. Consequently, the workaround for AMD Family
2533 * 10h Erratum 383 is enabled if the processor's feature set does not
2534 * include at least one feature that is only supported by older Intel
2535 * or newer AMD processors.
2537 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2538 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2539 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2541 workaround_erratum383 = 1;
2544 * Are large page mappings enabled?
2546 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2547 if (pg_ps_enabled) {
2548 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2549 ("pmap_init: can't assign to pagesizes[1]"));
2550 pagesizes[1] = NBPDR;
2551 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2552 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2553 ("pmap_init: can't assign to pagesizes[2]"));
2554 pagesizes[2] = NBPDP;
2559 * Initialize pv chunk lists.
2561 for (i = 0; i < PMAP_MEMDOM; i++) {
2562 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2563 TAILQ_INIT(&pv_chunks[i].pvc_list);
2565 pmap_init_pv_table();
2567 pmap_initialized = 1;
2568 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2569 ppim = pmap_preinit_mapping + i;
2572 /* Make the direct map consistent */
2573 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2574 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2575 ppim->sz, ppim->mode);
2579 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2580 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2583 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2584 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2585 (vmem_addr_t *)&qframe);
2587 panic("qframe allocation failed");
2590 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2591 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2592 lm_ents = LMEPML4I - LMSPML4I + 1;
2594 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2596 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2597 lm_ents, KMSANORIGPML4I - LMSPML4I);
2598 lm_ents = KMSANORIGPML4I - LMSPML4I;
2602 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2603 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2605 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2606 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2607 if (large_vmem == NULL) {
2608 printf("pmap: cannot create large map\n");
2611 for (i = 0; i < lm_ents; i++) {
2612 m = pmap_large_map_getptp_unlocked();
2614 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2615 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2621 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2622 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2623 "Maximum number of PML4 entries for use by large map (tunable). "
2624 "Each entry corresponds to 512GB of address space.");
2626 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2627 "2MB page mapping counters");
2629 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2630 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2631 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2633 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2634 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2635 &pmap_pde_mappings, "2MB page mappings");
2637 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2638 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2639 &pmap_pde_p_failures, "2MB page promotion failures");
2641 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2642 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2643 &pmap_pde_promotions, "2MB page promotions");
2645 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2646 "1GB page mapping counters");
2648 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2649 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2650 &pmap_pdpe_demotions, "1GB page demotions");
2652 /***************************************************
2653 * Low level helper routines.....
2654 ***************************************************/
2657 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2659 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2661 switch (pmap->pm_type) {
2664 /* Verify that both PAT bits are not set at the same time */
2665 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2666 ("Invalid PAT bits in entry %#lx", entry));
2668 /* Swap the PAT bits if one of them is set */
2669 if ((entry & x86_pat_bits) != 0)
2670 entry ^= x86_pat_bits;
2674 * Nothing to do - the memory attributes are represented
2675 * the same way for regular pages and superpages.
2679 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2686 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2689 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2690 pat_index[(int)mode] >= 0);
2694 * Determine the appropriate bits to set in a PTE or PDE for a specified
2698 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2700 int cache_bits, pat_flag, pat_idx;
2702 if (!pmap_is_valid_memattr(pmap, mode))
2703 panic("Unknown caching mode %d\n", mode);
2705 switch (pmap->pm_type) {
2708 /* The PAT bit is different for PTE's and PDE's. */
2709 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2711 /* Map the caching mode to a PAT index. */
2712 pat_idx = pat_index[mode];
2714 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2717 cache_bits |= pat_flag;
2719 cache_bits |= PG_NC_PCD;
2721 cache_bits |= PG_NC_PWT;
2725 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2729 panic("unsupported pmap type %d", pmap->pm_type);
2732 return (cache_bits);
2736 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2740 switch (pmap->pm_type) {
2743 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2746 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2749 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2756 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2758 int pat_flag, pat_idx;
2761 switch (pmap->pm_type) {
2764 /* The PAT bit is different for PTE's and PDE's. */
2765 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2767 if ((pte & pat_flag) != 0)
2769 if ((pte & PG_NC_PCD) != 0)
2771 if ((pte & PG_NC_PWT) != 0)
2775 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2776 panic("EPT PTE %#lx has no PAT memory type", pte);
2777 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2781 /* See pmap_init_pat(). */
2791 pmap_ps_enabled(pmap_t pmap)
2794 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2798 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2801 switch (pmap->pm_type) {
2808 * This is a little bogus since the generation number is
2809 * supposed to be bumped up when a region of the address
2810 * space is invalidated in the page tables.
2812 * In this case the old PDE entry is valid but yet we want
2813 * to make sure that any mappings using the old entry are
2814 * invalidated in the TLB.
2816 * The reason this works as expected is because we rendezvous
2817 * "all" host cpus and force any vcpu context to exit as a
2820 atomic_add_long(&pmap->pm_eptgen, 1);
2823 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2825 pde_store(pde, newpde);
2829 * After changing the page size for the specified virtual address in the page
2830 * table, flush the corresponding entries from the processor's TLB. Only the
2831 * calling processor's TLB is affected.
2833 * The calling thread must be pinned to a processor.
2836 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2840 if (pmap_type_guest(pmap))
2843 KASSERT(pmap->pm_type == PT_X86,
2844 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2846 PG_G = pmap_global_bit(pmap);
2848 if ((newpde & PG_PS) == 0)
2849 /* Demotion: flush a specific 2MB page mapping. */
2850 pmap_invlpg(pmap, va);
2851 else if ((newpde & PG_G) == 0)
2853 * Promotion: flush every 4KB page mapping from the TLB
2854 * because there are too many to flush individually.
2859 * Promotion: flush every 4KB page mapping from the TLB,
2860 * including any global (PG_G) mappings.
2867 * The amd64 pmap uses different approaches to TLB invalidation
2868 * depending on the kernel configuration, available hardware features,
2869 * and known hardware errata. The kernel configuration option that
2870 * has the greatest operational impact on TLB invalidation is PTI,
2871 * which is enabled automatically on affected Intel CPUs. The most
2872 * impactful hardware features are first PCID, and then INVPCID
2873 * instruction presence. PCID usage is quite different for PTI
2876 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2877 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2878 * space is served by two page tables, user and kernel. The user
2879 * page table only maps user space and a kernel trampoline. The
2880 * kernel trampoline includes the entirety of the kernel text but
2881 * only the kernel data that is needed to switch from user to kernel
2882 * mode. The kernel page table maps the user and kernel address
2883 * spaces in their entirety. It is identical to the per-process
2884 * page table used in non-PTI mode.
2886 * User page tables are only used when the CPU is in user mode.
2887 * Consequently, some TLB invalidations can be postponed until the
2888 * switch from kernel to user mode. In contrast, the user
2889 * space part of the kernel page table is used for copyout(9), so
2890 * TLB invalidations on this page table cannot be similarly postponed.
2892 * The existence of a user mode page table for the given pmap is
2893 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2894 * which case pm_ucr3 contains the %cr3 register value for the user
2895 * mode page table's root.
2897 * * The pm_active bitmask indicates which CPUs currently have the
2898 * pmap active. A CPU's bit is set on context switch to the pmap, and
2899 * cleared on switching off this CPU. For the kernel page table,
2900 * the pm_active field is immutable and contains all CPUs. The
2901 * kernel page table is always logically active on every processor,
2902 * but not necessarily in use by the hardware, e.g., in PTI mode.
2904 * When requesting invalidation of virtual addresses with
2905 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2906 * all CPUs recorded as active in pm_active. Updates to and reads
2907 * from pm_active are not synchronized, and so they may race with
2908 * each other. Shootdown handlers are prepared to handle the race.
2910 * * PCID is an optional feature of the long mode x86 MMU where TLB
2911 * entries are tagged with the 'Process ID' of the address space
2912 * they belong to. This feature provides a limited namespace for
2913 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2916 * Allocation of a PCID to a pmap is done by an algorithm described
2917 * in section 15.12, "Other TLB Consistency Algorithms", of
2918 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2919 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2920 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2921 * the CPU is about to start caching TLB entries from a pmap,
2922 * i.e., on the context switch that activates the pmap on the CPU.
2924 * The PCID allocator maintains a per-CPU, per-pmap generation
2925 * count, pm_gen, which is incremented each time a new PCID is
2926 * allocated. On TLB invalidation, the generation counters for the
2927 * pmap are zeroed, which signals the context switch code that the
2928 * previously allocated PCID is no longer valid. Effectively,
2929 * zeroing any of these counters triggers a TLB shootdown for the
2930 * given CPU/address space, due to the allocation of a new PCID.
2932 * Zeroing can be performed remotely. Consequently, if a pmap is
2933 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2934 * be initiated by an ordinary memory access to reset the target
2935 * CPU's generation count within the pmap. The CPU initiating the
2936 * TLB shootdown does not need to send an IPI to the target CPU.
2938 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2939 * for complete (kernel) page tables, and PCIDs for user mode page
2940 * tables. A user PCID value is obtained from the kernel PCID value
2941 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2943 * User space page tables are activated on return to user mode, by
2944 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2945 * clearing bit 63 of the loaded ucr3, this effectively causes
2946 * complete invalidation of the user mode TLB entries for the
2947 * current pmap. In which case, local invalidations of individual
2948 * pages in the user page table are skipped.
2950 * * Local invalidation, all modes. If the requested invalidation is
2951 * for a specific address or the total invalidation of a currently
2952 * active pmap, then the TLB is flushed using INVLPG for a kernel
2953 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2954 * user space page table(s).
2956 * If the INVPCID instruction is available, it is used to flush user
2957 * entries from the kernel page table.
2959 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2960 * entries for the given page that either match the current PCID or
2961 * are global. Since TLB entries for the same page under different
2962 * PCIDs are unaffected, kernel pages which reside in all address
2963 * spaces could be problematic. We avoid the problem by creating
2964 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2967 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2968 * address space, all other 4095 PCIDs are used for user mode spaces
2969 * as described above. A context switch allocates a new PCID if
2970 * the recorded PCID is zero or the recorded generation does not match
2971 * the CPU's generation, effectively flushing the TLB for this address space.
2972 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2973 * local user page: INVLPG
2974 * local kernel page: INVLPG
2975 * local user total: INVPCID(CTX)
2976 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2977 * remote user page, inactive pmap: zero pm_gen
2978 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2979 * (Both actions are required to handle the aforementioned pm_active races.)
2980 * remote kernel page: IPI:INVLPG
2981 * remote user total, inactive pmap: zero pm_gen
2982 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2984 * (See note above about pm_active races.)
2985 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2987 * PTI enabled, PCID present.
2988 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2990 * local kernel page: INVLPG
2991 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
2992 * on loading UCR3 into %cr3 for upt
2993 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2994 * remote user page, inactive pmap: zero pm_gen
2995 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
2996 * INVPCID(ADDR) for upt)
2997 * remote kernel page: IPI:INVLPG
2998 * remote user total, inactive pmap: zero pm_gen
2999 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
3000 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
3001 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
3004 * local user page: INVLPG
3005 * local kernel page: INVLPG
3006 * local user total: reload %cr3
3007 * local kernel total: invltlb_glob()
3008 * remote user page, inactive pmap: -
3009 * remote user page, active pmap: IPI:INVLPG
3010 * remote kernel page: IPI:INVLPG
3011 * remote user total, inactive pmap: -
3012 * remote user total, active pmap: IPI:(reload %cr3)
3013 * remote kernel total: IPI:invltlb_glob()
3014 * Since on return to user mode, the reload of %cr3 with ucr3 causes
3015 * TLB invalidation, no specific action is required for user page table.
3017 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
3023 * Interrupt the cpus that are executing in the guest context.
3024 * This will force the vcpu to exit and the cached EPT mappings
3025 * will be invalidated by the host before the next vmresume.
3027 static __inline void
3028 pmap_invalidate_ept(pmap_t pmap)
3034 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3035 ("pmap_invalidate_ept: absurd pm_active"));
3038 * The TLB mappings associated with a vcpu context are not
3039 * flushed each time a different vcpu is chosen to execute.
3041 * This is in contrast with a process's vtop mappings that
3042 * are flushed from the TLB on each context switch.
3044 * Therefore we need to do more than just a TLB shootdown on
3045 * the active cpus in 'pmap->pm_active'. To do this we keep
3046 * track of the number of invalidations performed on this pmap.
3048 * Each vcpu keeps a cache of this counter and compares it
3049 * just before a vmresume. If the counter is out-of-date an
3050 * invept will be done to flush stale mappings from the TLB.
3052 * To ensure that all vCPU threads have observed the new counter
3053 * value before returning, we use SMR. Ordering is important here:
3054 * the VMM enters an SMR read section before loading the counter
3055 * and after updating the pm_active bit set. Thus, pm_active is
3056 * a superset of active readers, and any reader that has observed
3057 * the goal has observed the new counter value.
3059 atomic_add_long(&pmap->pm_eptgen, 1);
3061 goal = smr_advance(pmap->pm_eptsmr);
3064 * Force the vcpu to exit and trap back into the hypervisor.
3066 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3067 ipi_selected(pmap->pm_active, ipinum);
3071 * Ensure that all active vCPUs will observe the new generation counter
3072 * value before executing any more guest instructions.
3074 smr_wait(pmap->pm_eptsmr, goal);
3078 pmap_invalidate_preipi_pcid(pmap_t pmap)
3080 struct pmap_pcid *pcidp;
3085 cpuid = PCPU_GET(cpuid);
3086 if (pmap != PCPU_GET(curpmap))
3087 cpuid = 0xffffffff; /* An impossible value */
3091 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3097 * The fence is between stores to pm_gen and the read of the
3098 * pm_active mask. We need to ensure that it is impossible
3099 * for us to miss the bit update in pm_active and
3100 * simultaneously observe a non-zero pm_gen in
3101 * pmap_activate_sw(), otherwise TLB update is missed.
3102 * Without the fence, IA32 allows such an outcome. Note that
3103 * pm_active is updated by a locked operation, which provides
3104 * the reciprocal fence.
3106 atomic_thread_fence_seq_cst();
3110 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3115 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3117 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3118 pmap_invalidate_preipi_nopcid);
3122 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3123 const bool invpcid_works1)
3125 struct invpcid_descr d;
3126 uint64_t kcr3, ucr3;
3130 * Because pm_pcid is recalculated on a context switch, we
3131 * must ensure there is no preemption, not just pinning.
3132 * Otherwise, we might use a stale value below.
3134 CRITICAL_ASSERT(curthread);
3137 * No need to do anything with user page tables invalidation
3138 * if there is no user page table, or invalidation is deferred
3139 * until the return to userspace. ucr3_load_mask is stable
3140 * because we have preemption disabled.
3142 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3143 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3146 pcid = pmap_get_pcid(pmap);
3147 if (invpcid_works1) {
3148 d.pcid = pcid | PMAP_PCID_USER_PT;
3151 invpcid(&d, INVPCID_ADDR);
3153 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3154 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3155 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3160 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3162 pmap_invalidate_page_pcid_cb(pmap, va, true);
3166 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3168 pmap_invalidate_page_pcid_cb(pmap, va, false);
3172 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3176 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3178 if (pmap_pcid_enabled)
3179 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3180 pmap_invalidate_page_pcid_noinvpcid_cb);
3181 return (pmap_invalidate_page_nopcid_cb);
3185 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3186 vm_offset_t addr2 __unused)
3188 if (pmap == kernel_pmap) {
3189 pmap_invlpg(kernel_pmap, va);
3190 } else if (pmap == PCPU_GET(curpmap)) {
3192 pmap_invalidate_page_cb(pmap, va);
3197 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3199 if (pmap_type_guest(pmap)) {
3200 pmap_invalidate_ept(pmap);
3204 KASSERT(pmap->pm_type == PT_X86,
3205 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3207 pmap_invalidate_preipi(pmap);
3208 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3211 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3212 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3215 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3216 const bool invpcid_works1)
3218 struct invpcid_descr d;
3219 uint64_t kcr3, ucr3;
3222 CRITICAL_ASSERT(curthread);
3224 if (pmap != PCPU_GET(curpmap) ||
3225 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3226 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3229 pcid = pmap_get_pcid(pmap);
3230 if (invpcid_works1) {
3231 d.pcid = pcid | PMAP_PCID_USER_PT;
3233 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3234 invpcid(&d, INVPCID_ADDR);
3236 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3237 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3238 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3243 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3246 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3250 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3253 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3257 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3258 vm_offset_t eva __unused)
3262 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3265 if (pmap_pcid_enabled)
3266 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3267 pmap_invalidate_range_pcid_noinvpcid_cb);
3268 return (pmap_invalidate_range_nopcid_cb);
3272 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3276 if (pmap == kernel_pmap) {
3277 if (PCPU_GET(pcid_invlpg_workaround)) {
3278 struct invpcid_descr d = { 0 };
3280 invpcid(&d, INVPCID_CTXGLOB);
3282 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3285 } else if (pmap == PCPU_GET(curpmap)) {
3286 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3288 pmap_invalidate_range_cb(pmap, sva, eva);
3293 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3295 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3296 pmap_invalidate_all(pmap);
3300 if (pmap_type_guest(pmap)) {
3301 pmap_invalidate_ept(pmap);
3305 KASSERT(pmap->pm_type == PT_X86,
3306 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3308 pmap_invalidate_preipi(pmap);
3309 smp_masked_invlpg_range(sva, eva, pmap,
3310 pmap_invalidate_range_curcpu_cb);
3314 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3316 struct invpcid_descr d;
3320 if (pmap == kernel_pmap) {
3321 if (invpcid_works1) {
3322 bzero(&d, sizeof(d));
3323 invpcid(&d, INVPCID_CTXGLOB);
3327 } else if (pmap == PCPU_GET(curpmap)) {
3328 CRITICAL_ASSERT(curthread);
3330 pcid = pmap_get_pcid(pmap);
3331 if (invpcid_works1) {
3335 invpcid(&d, INVPCID_CTX);
3337 kcr3 = pmap->pm_cr3 | pcid;
3340 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3341 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3346 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3348 pmap_invalidate_all_pcid_cb(pmap, true);
3352 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3354 pmap_invalidate_all_pcid_cb(pmap, false);
3358 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3360 if (pmap == kernel_pmap)
3362 else if (pmap == PCPU_GET(curpmap))
3366 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3368 if (pmap_pcid_enabled)
3369 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3370 pmap_invalidate_all_pcid_noinvpcid_cb);
3371 return (pmap_invalidate_all_nopcid_cb);
3375 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3376 vm_offset_t addr2 __unused)
3378 pmap_invalidate_all_cb(pmap);
3382 pmap_invalidate_all(pmap_t pmap)
3384 if (pmap_type_guest(pmap)) {
3385 pmap_invalidate_ept(pmap);
3389 KASSERT(pmap->pm_type == PT_X86,
3390 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3392 pmap_invalidate_preipi(pmap);
3393 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3397 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3398 vm_offset_t addr2 __unused)
3404 pmap_invalidate_cache(void)
3407 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3411 cpuset_t invalidate; /* processors that invalidate their TLB */
3416 u_int store; /* processor that updates the PDE */
3420 pmap_update_pde_action(void *arg)
3422 struct pde_action *act = arg;
3424 if (act->store == PCPU_GET(cpuid))
3425 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3429 pmap_update_pde_teardown(void *arg)
3431 struct pde_action *act = arg;
3433 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3434 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3438 * Change the page size for the specified virtual address in a way that
3439 * prevents any possibility of the TLB ever having two entries that map the
3440 * same virtual address using different page sizes. This is the recommended
3441 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3442 * machine check exception for a TLB state that is improperly diagnosed as a
3446 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3448 struct pde_action act;
3449 cpuset_t active, other_cpus;
3453 cpuid = PCPU_GET(cpuid);
3454 other_cpus = all_cpus;
3455 CPU_CLR(cpuid, &other_cpus);
3456 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3459 active = pmap->pm_active;
3461 if (CPU_OVERLAP(&active, &other_cpus)) {
3463 act.invalidate = active;
3467 act.newpde = newpde;
3468 CPU_SET(cpuid, &active);
3469 smp_rendezvous_cpus(active,
3470 smp_no_rendezvous_barrier, pmap_update_pde_action,
3471 pmap_update_pde_teardown, &act);
3473 pmap_update_pde_store(pmap, pde, newpde);
3474 if (CPU_ISSET(cpuid, &active))
3475 pmap_update_pde_invalidate(pmap, va, newpde);
3481 * Normal, non-SMP, invalidation functions.
3484 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3486 struct invpcid_descr d;
3487 uint64_t kcr3, ucr3;
3490 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3494 KASSERT(pmap->pm_type == PT_X86,
3495 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3497 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3499 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3500 pmap->pm_ucr3 != PMAP_NO_CR3) {
3502 pcid = pmap->pm_pcidp->pm_pcid;
3503 if (invpcid_works) {
3504 d.pcid = pcid | PMAP_PCID_USER_PT;
3507 invpcid(&d, INVPCID_ADDR);
3509 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3510 ucr3 = pmap->pm_ucr3 | pcid |
3511 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3512 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3516 } else if (pmap_pcid_enabled)
3517 pmap->pm_pcidp->pm_gen = 0;
3521 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3523 struct invpcid_descr d;
3525 uint64_t kcr3, ucr3;
3527 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3531 KASSERT(pmap->pm_type == PT_X86,
3532 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3534 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3535 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3537 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3538 pmap->pm_ucr3 != PMAP_NO_CR3) {
3540 if (invpcid_works) {
3541 d.pcid = pmap->pm_pcidp->pm_pcid |
3545 for (; d.addr < eva; d.addr += PAGE_SIZE)
3546 invpcid(&d, INVPCID_ADDR);
3548 kcr3 = pmap->pm_cr3 | pmap->pm_pcidp->
3549 pm_pcid | CR3_PCID_SAVE;
3550 ucr3 = pmap->pm_ucr3 | pmap->pm_pcidp->
3551 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3552 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3556 } else if (pmap_pcid_enabled) {
3557 pmap->pm_pcidp->pm_gen = 0;
3562 pmap_invalidate_all(pmap_t pmap)
3564 struct invpcid_descr d;
3565 uint64_t kcr3, ucr3;
3567 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3571 KASSERT(pmap->pm_type == PT_X86,
3572 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3574 if (pmap == kernel_pmap) {
3575 if (pmap_pcid_enabled && invpcid_works) {
3576 bzero(&d, sizeof(d));
3577 invpcid(&d, INVPCID_CTXGLOB);
3581 } else if (pmap == PCPU_GET(curpmap)) {
3582 if (pmap_pcid_enabled) {
3584 if (invpcid_works) {
3585 d.pcid = pmap->pm_pcidp->pm_pcid;
3588 invpcid(&d, INVPCID_CTX);
3589 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3590 d.pcid |= PMAP_PCID_USER_PT;
3591 invpcid(&d, INVPCID_CTX);
3594 kcr3 = pmap->pm_cr3 | pmap->pm_pcidp->pm_pcid;
3595 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3596 ucr3 = pmap->pm_ucr3 | pmap->pm_pcidp->
3597 pm_pcid | PMAP_PCID_USER_PT;
3598 pmap_pti_pcid_invalidate(ucr3, kcr3);
3606 } else if (pmap_pcid_enabled) {
3607 pmap->pm_pcidp->pm_gen = 0;
3612 pmap_invalidate_cache(void)
3619 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3622 pmap_update_pde_store(pmap, pde, newpde);
3623 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3624 pmap_update_pde_invalidate(pmap, va, newpde);
3626 pmap->pm_pcidp->pm_gen = 0;
3631 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3635 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3636 * by a promotion that did not invalidate the 512 4KB page mappings
3637 * that might exist in the TLB. Consequently, at this point, the TLB
3638 * may hold both 4KB and 2MB page mappings for the address range [va,
3639 * va + NBPDR). Therefore, the entire range must be invalidated here.
3640 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3641 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3642 * single INVLPG suffices to invalidate the 2MB page mapping from the
3645 if ((pde & PG_PROMOTED) != 0)
3646 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3648 pmap_invalidate_page(pmap, va);
3651 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3652 (vm_offset_t sva, vm_offset_t eva))
3655 if ((cpu_feature & CPUID_SS) != 0)
3656 return (pmap_invalidate_cache_range_selfsnoop);
3657 if ((cpu_feature & CPUID_CLFSH) != 0)
3658 return (pmap_force_invalidate_cache_range);
3659 return (pmap_invalidate_cache_range_all);
3662 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3665 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3668 KASSERT((sva & PAGE_MASK) == 0,
3669 ("pmap_invalidate_cache_range: sva not page-aligned"));
3670 KASSERT((eva & PAGE_MASK) == 0,
3671 ("pmap_invalidate_cache_range: eva not page-aligned"));
3675 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3678 pmap_invalidate_cache_range_check_align(sva, eva);
3682 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3685 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3688 * XXX: Some CPUs fault, hang, or trash the local APIC
3689 * registers if we use CLFLUSH on the local APIC range. The
3690 * local APIC is always uncached, so we don't need to flush
3691 * for that range anyway.
3693 if (pmap_kextract(sva) == lapic_paddr)
3696 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3698 * Do per-cache line flush. Use a locked
3699 * instruction to insure that previous stores are
3700 * included in the write-back. The processor
3701 * propagates flush to other processors in the cache
3704 atomic_thread_fence_seq_cst();
3705 for (; sva < eva; sva += cpu_clflush_line_size)
3707 atomic_thread_fence_seq_cst();
3710 * Writes are ordered by CLFLUSH on Intel CPUs.
3712 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3714 for (; sva < eva; sva += cpu_clflush_line_size)
3716 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3722 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3725 pmap_invalidate_cache_range_check_align(sva, eva);
3726 pmap_invalidate_cache();
3730 * Remove the specified set of pages from the data and instruction caches.
3732 * In contrast to pmap_invalidate_cache_range(), this function does not
3733 * rely on the CPU's self-snoop feature, because it is intended for use
3734 * when moving pages into a different cache domain.
3737 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3739 vm_offset_t daddr, eva;
3743 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3744 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3745 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3746 pmap_invalidate_cache();
3749 atomic_thread_fence_seq_cst();
3750 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3752 for (i = 0; i < count; i++) {
3753 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3754 eva = daddr + PAGE_SIZE;
3755 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3763 atomic_thread_fence_seq_cst();
3764 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3770 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3773 pmap_invalidate_cache_range_check_align(sva, eva);
3775 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3776 pmap_force_invalidate_cache_range(sva, eva);
3780 /* See comment in pmap_force_invalidate_cache_range(). */
3781 if (pmap_kextract(sva) == lapic_paddr)
3784 atomic_thread_fence_seq_cst();
3785 for (; sva < eva; sva += cpu_clflush_line_size)
3787 atomic_thread_fence_seq_cst();
3791 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3795 int error __diagused;
3798 KASSERT((spa & PAGE_MASK) == 0,
3799 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3800 KASSERT((epa & PAGE_MASK) == 0,
3801 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3803 if (spa < dmaplimit) {
3804 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3806 if (dmaplimit >= epa)
3811 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3813 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3815 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3816 pte = vtopte(vaddr);
3817 for (; spa < epa; spa += PAGE_SIZE) {
3819 pte_store(pte, spa | pte_bits);
3820 pmap_invlpg(kernel_pmap, vaddr);
3821 /* XXXKIB atomic inside flush_cache_range are excessive */
3822 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3825 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3829 * Routine: pmap_extract
3831 * Extract the physical page address associated
3832 * with the given map/virtual_address pair.
3835 pmap_extract(pmap_t pmap, vm_offset_t va)
3839 pt_entry_t *pte, PG_V;
3843 PG_V = pmap_valid_bit(pmap);
3845 pdpe = pmap_pdpe(pmap, va);
3846 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3847 if ((*pdpe & PG_PS) != 0)
3848 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3850 pde = pmap_pdpe_to_pde(pdpe, va);
3851 if ((*pde & PG_V) != 0) {
3852 if ((*pde & PG_PS) != 0) {
3853 pa = (*pde & PG_PS_FRAME) |
3856 pte = pmap_pde_to_pte(pde, va);
3857 pa = (*pte & PG_FRAME) |
3868 * Routine: pmap_extract_and_hold
3870 * Atomically extract and hold the physical page
3871 * with the given pmap and virtual address pair
3872 * if that mapping permits the given protection.
3875 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3877 pdp_entry_t pdpe, *pdpep;
3878 pd_entry_t pde, *pdep;
3879 pt_entry_t pte, PG_RW, PG_V;
3883 PG_RW = pmap_rw_bit(pmap);
3884 PG_V = pmap_valid_bit(pmap);
3887 pdpep = pmap_pdpe(pmap, va);
3888 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3890 if ((pdpe & PG_PS) != 0) {
3891 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3893 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3897 pdep = pmap_pdpe_to_pde(pdpep, va);
3898 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3900 if ((pde & PG_PS) != 0) {
3901 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3903 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3907 pte = *pmap_pde_to_pte(pdep, va);
3908 if ((pte & PG_V) == 0 ||
3909 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3911 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3914 if (m != NULL && !vm_page_wire_mapped(m))
3922 pmap_kextract(vm_offset_t va)
3927 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3928 pa = DMAP_TO_PHYS(va);
3929 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3930 pa = pmap_large_map_kextract(va);
3934 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3937 * Beware of a concurrent promotion that changes the
3938 * PDE at this point! For example, vtopte() must not
3939 * be used to access the PTE because it would use the
3940 * new PDE. It is, however, safe to use the old PDE
3941 * because the page table page is preserved by the
3944 pa = *pmap_pde_to_pte(&pde, va);
3945 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3951 /***************************************************
3952 * Low level mapping routines.....
3953 ***************************************************/
3956 * Add a wired page to the kva.
3957 * Note: not SMP coherent.
3960 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3965 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3966 X86_PG_RW | X86_PG_V);
3969 static __inline void
3970 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3976 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
3977 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3978 X86_PG_RW | X86_PG_V | cache_bits);
3982 * Remove a page from the kernel pagetables.
3983 * Note: not SMP coherent.
3986 pmap_kremove(vm_offset_t va)
3995 * Used to map a range of physical addresses into kernel
3996 * virtual address space.
3998 * The value passed in '*virt' is a suggested virtual address for
3999 * the mapping. Architectures which can support a direct-mapped
4000 * physical to virtual region can return the appropriate address
4001 * within that region, leaving '*virt' unchanged. Other
4002 * architectures should map the pages starting at '*virt' and
4003 * update '*virt' with the first usable address after the mapped
4007 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
4009 return PHYS_TO_DMAP(start);
4013 * Add a list of wired pages to the kva
4014 * this routine is only used for temporary
4015 * kernel mappings that do not need to have
4016 * page modification or references recorded.
4017 * Note that old mappings are simply written
4018 * over. The page *must* be wired.
4019 * Note: SMP coherent. Uses a ranged shootdown IPI.
4022 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4024 pt_entry_t *endpte, oldpte, pa, *pte;
4030 endpte = pte + count;
4031 while (pte < endpte) {
4033 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4034 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4035 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4037 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4038 X86_PG_M | X86_PG_RW | X86_PG_V);
4042 if (__predict_false((oldpte & X86_PG_V) != 0))
4043 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4048 * This routine tears out page mappings from the
4049 * kernel -- it is meant only for temporary mappings.
4050 * Note: SMP coherent. Uses a ranged shootdown IPI.
4053 pmap_qremove(vm_offset_t sva, int count)
4058 while (count-- > 0) {
4059 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4063 pmap_invalidate_range(kernel_pmap, sva, va);
4066 /***************************************************
4067 * Page table page management routines.....
4068 ***************************************************/
4070 * Schedule the specified unused page table page to be freed. Specifically,
4071 * add the page to the specified list of pages that will be released to the
4072 * physical memory manager after the TLB has been updated.
4074 static __inline void
4075 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4076 boolean_t set_PG_ZERO)
4080 m->flags |= PG_ZERO;
4082 m->flags &= ~PG_ZERO;
4083 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4087 * Inserts the specified page table page into the specified pmap's collection
4088 * of idle page table pages. Each of a pmap's page table pages is responsible
4089 * for mapping a distinct range of virtual addresses. The pmap's collection is
4090 * ordered by this virtual address range.
4092 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4093 * "mpte"'s valid field will be set to 0.
4095 * If "promoted" is true and "allpte_PG_A_set" is false, then "mpte" must
4096 * contain valid mappings with identical attributes except for PG_A; "mpte"'s
4097 * valid field will be set to 1.
4099 * If "promoted" and "allpte_PG_A_set" are both true, then "mpte" must contain
4100 * valid mappings with identical attributes including PG_A; "mpte"'s valid
4101 * field will be set to VM_PAGE_BITS_ALL.
4104 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4105 bool allpte_PG_A_set)
4108 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4109 KASSERT(promoted || !allpte_PG_A_set,
4110 ("a zero-filled PTP can't have PG_A set in every PTE"));
4111 mpte->valid = promoted ? (allpte_PG_A_set ? VM_PAGE_BITS_ALL : 1) : 0;
4112 return (vm_radix_insert(&pmap->pm_root, mpte));
4116 * Removes the page table page mapping the specified virtual address from the
4117 * specified pmap's collection of idle page table pages, and returns it.
4118 * Otherwise, returns NULL if there is no page table page corresponding to the
4119 * specified virtual address.
4121 static __inline vm_page_t
4122 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4125 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4126 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4130 * Decrements a page table page's reference count, which is used to record the
4131 * number of valid page table entries within the page. If the reference count
4132 * drops to zero, then the page table page is unmapped. Returns TRUE if the
4133 * page table page was unmapped and FALSE otherwise.
4135 static inline boolean_t
4136 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4140 if (m->ref_count == 0) {
4141 _pmap_unwire_ptp(pmap, va, m, free);
4148 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4154 vm_page_t pdpg, pdppg, pml4pg;
4156 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4159 * unmap the page table page
4161 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4163 MPASS(pmap_is_la57(pmap));
4164 pml5 = pmap_pml5e(pmap, va);
4166 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4167 pml5 = pmap_pml5e_u(pmap, va);
4170 } else if (m->pindex >= NUPDE + NUPDPE) {
4172 pml4 = pmap_pml4e(pmap, va);
4174 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4175 va <= VM_MAXUSER_ADDRESS) {
4176 pml4 = pmap_pml4e_u(pmap, va);
4179 } else if (m->pindex >= NUPDE) {
4181 pdp = pmap_pdpe(pmap, va);
4185 pd = pmap_pde(pmap, va);
4188 if (m->pindex < NUPDE) {
4189 /* We just released a PT, unhold the matching PD */
4190 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4191 pmap_unwire_ptp(pmap, va, pdpg, free);
4192 } else if (m->pindex < NUPDE + NUPDPE) {
4193 /* We just released a PD, unhold the matching PDP */
4194 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4195 pmap_unwire_ptp(pmap, va, pdppg, free);
4196 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4197 /* We just released a PDP, unhold the matching PML4 */
4198 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4199 pmap_unwire_ptp(pmap, va, pml4pg, free);
4202 pmap_pt_page_count_adj(pmap, -1);
4205 * Put page on a list so that it is released after
4206 * *ALL* TLB shootdown is done
4208 pmap_add_delayed_free_list(m, free, TRUE);
4212 * After removing a page table entry, this routine is used to
4213 * conditionally free the page, and manage the reference count.
4216 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4217 struct spglist *free)
4221 if (va >= VM_MAXUSER_ADDRESS)
4223 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4224 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4225 return (pmap_unwire_ptp(pmap, va, mpte, free));
4229 * Release a page table page reference after a failed attempt to create a
4233 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4235 struct spglist free;
4238 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4240 * Although "va" was never mapped, paging-structure caches
4241 * could nonetheless have entries that refer to the freed
4242 * page table pages. Invalidate those entries.
4244 pmap_invalidate_page(pmap, va);
4245 vm_page_free_pages_toq(&free, true);
4250 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4252 struct pmap_pcid *pcidp;
4256 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4257 pcidp->pm_pcid = pcid;
4258 pcidp->pm_gen = gen;
4263 pmap_pinit0(pmap_t pmap)
4268 PMAP_LOCK_INIT(pmap);
4269 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4270 pmap->pm_pmltopu = NULL;
4271 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4272 /* hack to keep pmap_pti_pcid_invalidate() alive */
4273 pmap->pm_ucr3 = PMAP_NO_CR3;
4274 vm_radix_init(&pmap->pm_root);
4275 CPU_ZERO(&pmap->pm_active);
4276 TAILQ_INIT(&pmap->pm_pvchunk);
4277 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4278 pmap->pm_flags = pmap_flags;
4279 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4280 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4281 pmap_activate_boot(pmap);
4286 p->p_md.md_flags |= P_MD_KPTI;
4289 pmap_thread_init_invl_gen(td);
4291 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4292 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4293 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4299 pmap_pinit_pml4(vm_page_t pml4pg)
4301 pml4_entry_t *pm_pml4;
4304 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4306 /* Wire in kernel global address entries. */
4307 for (i = 0; i < NKPML4E; i++) {
4308 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4312 for (i = 0; i < NKASANPML4E; i++) {
4313 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4318 for (i = 0; i < NKMSANSHADPML4E; i++) {
4319 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4320 X86_PG_RW | X86_PG_V | pg_nx;
4322 for (i = 0; i < NKMSANORIGPML4E; i++) {
4323 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4324 X86_PG_RW | X86_PG_V | pg_nx;
4327 for (i = 0; i < ndmpdpphys; i++) {
4328 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4332 /* install self-referential address mapping entry(s) */
4333 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4334 X86_PG_A | X86_PG_M;
4336 /* install large map entries if configured */
4337 for (i = 0; i < lm_ents; i++)
4338 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4342 pmap_pinit_pml5(vm_page_t pml5pg)
4344 pml5_entry_t *pm_pml5;
4346 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4349 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4350 * entering all existing kernel mappings into level 5 table.
4352 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4353 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4354 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4357 * Install self-referential address mapping entry.
4359 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4360 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A |
4361 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4365 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4367 pml4_entry_t *pm_pml4u;
4370 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4371 for (i = 0; i < NPML4EPG; i++)
4372 pm_pml4u[i] = pti_pml4[i];
4376 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4378 pml5_entry_t *pm_pml5u;
4380 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4384 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4385 * table, entering all kernel mappings needed for usermode
4386 * into level 5 table.
4388 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4389 pmap_kextract((vm_offset_t)pti_pml4) |
4390 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4391 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4394 /* Allocate a page table page and do related bookkeeping */
4396 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4400 m = vm_page_alloc_noobj(flags);
4401 if (__predict_false(m == NULL))
4404 pmap_pt_page_count_adj(pmap, 1);
4409 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4412 * This function assumes the page will need to be unwired,
4413 * even though the counterpart allocation in pmap_alloc_pt_page()
4414 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4415 * of pmap_free_pt_page() require unwiring. The case in which
4416 * a PT page doesn't require unwiring because its ref_count has
4417 * naturally reached 0 is handled through _pmap_unwire_ptp().
4419 vm_page_unwire_noq(m);
4421 vm_page_free_zero(m);
4425 pmap_pt_page_count_adj(pmap, -1);
4428 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4431 * Initialize a preallocated and zeroed pmap structure,
4432 * such as one in a vmspace structure.
4435 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4437 vm_page_t pmltop_pg, pmltop_pgu;
4438 vm_paddr_t pmltop_phys;
4440 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4443 * Allocate the page directory page. Pass NULL instead of a
4444 * pointer to the pmap here to avoid calling
4445 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4446 * since that requires pmap lock. Instead do the accounting
4449 * Note that final call to pmap_remove() optimization that
4450 * checks for zero resident_count is basically disabled by
4451 * accounting for top-level page. But the optimization was
4452 * not effective since we started using non-managed mapping of
4455 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4457 pmap_pt_page_count_pinit(pmap, 1);
4459 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4460 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4462 if (pmap_pcid_enabled) {
4463 if (pmap->pm_pcidp == NULL)
4464 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4466 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4468 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4469 pmap->pm_ucr3 = PMAP_NO_CR3;
4470 pmap->pm_pmltopu = NULL;
4472 pmap->pm_type = pm_type;
4475 * Do not install the host kernel mappings in the nested page
4476 * tables. These mappings are meaningless in the guest physical
4478 * Install minimal kernel mappings in PTI case.
4482 pmap->pm_cr3 = pmltop_phys;
4483 if (pmap_is_la57(pmap))
4484 pmap_pinit_pml5(pmltop_pg);
4486 pmap_pinit_pml4(pmltop_pg);
4487 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4489 * As with pmltop_pg, pass NULL instead of a
4490 * pointer to the pmap to ensure that the PTI
4491 * page counted explicitly.
4493 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4494 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4495 pmap_pt_page_count_pinit(pmap, 1);
4496 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4497 VM_PAGE_TO_PHYS(pmltop_pgu));
4498 if (pmap_is_la57(pmap))
4499 pmap_pinit_pml5_pti(pmltop_pgu);
4501 pmap_pinit_pml4_pti(pmltop_pgu);
4502 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4504 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4505 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4506 pkru_free_range, pmap, M_NOWAIT);
4511 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4515 vm_radix_init(&pmap->pm_root);
4516 CPU_ZERO(&pmap->pm_active);
4517 TAILQ_INIT(&pmap->pm_pvchunk);
4518 pmap->pm_flags = flags;
4519 pmap->pm_eptgen = 0;
4525 pmap_pinit(pmap_t pmap)
4528 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4532 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4535 struct spglist free;
4537 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4538 if (mpg->ref_count != 0)
4541 _pmap_unwire_ptp(pmap, va, mpg, &free);
4542 pmap_invalidate_page(pmap, va);
4543 vm_page_free_pages_toq(&free, true);
4546 static pml4_entry_t *
4547 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4550 vm_pindex_t pml5index;
4557 if (!pmap_is_la57(pmap))
4558 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4560 PG_V = pmap_valid_bit(pmap);
4561 pml5index = pmap_pml5e_index(va);
4562 pml5 = &pmap->pm_pmltop[pml5index];
4563 if ((*pml5 & PG_V) == 0) {
4564 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4571 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4572 pml4 = &pml4[pmap_pml4e_index(va)];
4573 if ((*pml4 & PG_V) == 0) {
4574 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4575 if (allocated && !addref)
4576 pml4pg->ref_count--;
4577 else if (!allocated && addref)
4578 pml4pg->ref_count++;
4583 static pdp_entry_t *
4584 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4593 PG_V = pmap_valid_bit(pmap);
4595 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4599 if ((*pml4 & PG_V) == 0) {
4600 /* Have to allocate a new pdp, recurse */
4601 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4603 if (pmap_is_la57(pmap))
4604 pmap_allocpte_free_unref(pmap, va,
4605 pmap_pml5e(pmap, va));
4612 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4613 pdp = &pdp[pmap_pdpe_index(va)];
4614 if ((*pdp & PG_V) == 0) {
4615 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4616 if (allocated && !addref)
4618 else if (!allocated && addref)
4625 * The ptepindexes, i.e. page indices, of the page table pages encountered
4626 * while translating virtual address va are defined as follows:
4627 * - for the page table page (last level),
4628 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4629 * in other words, it is just the index of the PDE that maps the page
4631 * - for the page directory page,
4632 * ptepindex = NUPDE (number of userland PD entries) +
4633 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4634 * i.e. index of PDPE is put after the last index of PDE,
4635 * - for the page directory pointer page,
4636 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4638 * i.e. index of pml4e is put after the last index of PDPE,
4639 * - for the PML4 page (if LA57 mode is enabled),
4640 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4641 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4642 * i.e. index of pml5e is put after the last index of PML4E.
4644 * Define an order on the paging entries, where all entries of the
4645 * same height are put together, then heights are put from deepest to
4646 * root. Then ptexpindex is the sequential number of the
4647 * corresponding paging entry in this order.
4649 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4650 * LA57 paging structures even in LA48 paging mode. Moreover, the
4651 * ptepindexes are calculated as if the paging structures were 5-level
4652 * regardless of the actual mode of operation.
4654 * The root page at PML4/PML5 does not participate in this indexing scheme,
4655 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4658 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4661 vm_pindex_t pml5index, pml4index;
4662 pml5_entry_t *pml5, *pml5u;
4663 pml4_entry_t *pml4, *pml4u;
4667 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4669 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4671 PG_A = pmap_accessed_bit(pmap);
4672 PG_M = pmap_modified_bit(pmap);
4673 PG_V = pmap_valid_bit(pmap);
4674 PG_RW = pmap_rw_bit(pmap);
4677 * Allocate a page table page.
4679 m = pmap_alloc_pt_page(pmap, ptepindex,
4680 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4685 * Map the pagetable page into the process address space, if
4686 * it isn't already there.
4688 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4689 MPASS(pmap_is_la57(pmap));
4691 pml5index = pmap_pml5e_index(va);
4692 pml5 = &pmap->pm_pmltop[pml5index];
4693 KASSERT((*pml5 & PG_V) == 0,
4694 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4695 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4697 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4698 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4701 pml5u = &pmap->pm_pmltopu[pml5index];
4702 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4705 } else if (ptepindex >= NUPDE + NUPDPE) {
4706 pml4index = pmap_pml4e_index(va);
4707 /* Wire up a new PDPE page */
4708 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4710 pmap_free_pt_page(pmap, m, true);
4713 KASSERT((*pml4 & PG_V) == 0,
4714 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4715 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4717 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4718 pml4index < NUPML4E) {
4720 * PTI: Make all user-space mappings in the
4721 * kernel-mode page table no-execute so that
4722 * we detect any programming errors that leave
4723 * the kernel-mode page table active on return
4726 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4729 pml4u = &pmap->pm_pmltopu[pml4index];
4730 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4733 } else if (ptepindex >= NUPDE) {
4734 /* Wire up a new PDE page */
4735 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4737 pmap_free_pt_page(pmap, m, true);
4740 KASSERT((*pdp & PG_V) == 0,
4741 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4742 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4744 /* Wire up a new PTE page */
4745 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4747 pmap_free_pt_page(pmap, m, true);
4750 if ((*pdp & PG_V) == 0) {
4751 /* Have to allocate a new pd, recurse */
4752 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4753 lockp, va) == NULL) {
4754 pmap_allocpte_free_unref(pmap, va,
4755 pmap_pml4e(pmap, va));
4756 pmap_free_pt_page(pmap, m, true);
4760 /* Add reference to the pd page */
4761 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4764 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4766 /* Now we know where the page directory page is */
4767 pd = &pd[pmap_pde_index(va)];
4768 KASSERT((*pd & PG_V) == 0,
4769 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4770 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4777 * This routine is called if the desired page table page does not exist.
4779 * If page table page allocation fails, this routine may sleep before
4780 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4781 * occurs right before returning to the caller. This way, we never
4782 * drop pmap lock to sleep while a page table page has ref_count == 0,
4783 * which prevents the page from being freed under us.
4786 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4791 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4792 if (m == NULL && lockp != NULL) {
4793 RELEASE_PV_LIST_LOCK(lockp);
4795 PMAP_ASSERT_NOT_IN_DI();
4803 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4804 struct rwlock **lockp)
4806 pdp_entry_t *pdpe, PG_V;
4809 vm_pindex_t pdpindex;
4811 PG_V = pmap_valid_bit(pmap);
4814 pdpe = pmap_pdpe(pmap, va);
4815 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4816 pde = pmap_pdpe_to_pde(pdpe, va);
4817 if (va < VM_MAXUSER_ADDRESS) {
4818 /* Add a reference to the pd page. */
4819 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4823 } else if (va < VM_MAXUSER_ADDRESS) {
4824 /* Allocate a pd page. */
4825 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4826 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4833 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4834 pde = &pde[pmap_pde_index(va)];
4836 panic("pmap_alloc_pde: missing page table page for va %#lx",
4843 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4845 vm_pindex_t ptepindex;
4846 pd_entry_t *pd, PG_V;
4849 PG_V = pmap_valid_bit(pmap);
4852 * Calculate pagetable page index
4854 ptepindex = pmap_pde_pindex(va);
4857 * Get the page directory entry
4859 pd = pmap_pde(pmap, va);
4862 * This supports switching from a 2MB page to a
4865 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4866 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4868 * Invalidation of the 2MB page mapping may have caused
4869 * the deallocation of the underlying PD page.
4876 * If the page table page is mapped, we just increment the
4877 * hold count, and activate it.
4879 if (pd != NULL && (*pd & PG_V) != 0) {
4880 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4884 * Here if the pte page isn't mapped, or if it has been
4887 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4888 if (m == NULL && lockp != NULL)
4894 /***************************************************
4895 * Pmap allocation/deallocation routines.
4896 ***************************************************/
4899 * Release any resources held by the given physical map.
4900 * Called when a pmap initialized by pmap_pinit is being released.
4901 * Should only be called if the map contains no valid mappings.
4904 pmap_release(pmap_t pmap)
4909 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4910 ("pmap_release: pmap %p has reserved page table page(s)",
4912 KASSERT(CPU_EMPTY(&pmap->pm_active),
4913 ("releasing active pmap %p", pmap));
4915 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4917 if (pmap_is_la57(pmap)) {
4918 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4919 pmap->pm_pmltop[PML5PML5I] = 0;
4921 for (i = 0; i < NKPML4E; i++) /* KVA */
4922 pmap->pm_pmltop[KPML4BASE + i] = 0;
4924 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4925 pmap->pm_pmltop[KASANPML4I + i] = 0;
4928 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4929 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4930 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4931 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4933 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4934 pmap->pm_pmltop[DMPML4I + i] = 0;
4935 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4936 for (i = 0; i < lm_ents; i++) /* Large Map */
4937 pmap->pm_pmltop[LMSPML4I + i] = 0;
4940 pmap_free_pt_page(NULL, m, true);
4941 pmap_pt_page_count_pinit(pmap, -1);
4943 if (pmap->pm_pmltopu != NULL) {
4944 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4946 pmap_free_pt_page(NULL, m, false);
4947 pmap_pt_page_count_pinit(pmap, -1);
4949 if (pmap->pm_type == PT_X86 &&
4950 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4951 rangeset_fini(&pmap->pm_pkru);
4953 KASSERT(pmap->pm_stats.resident_count == 0,
4954 ("pmap_release: pmap %p resident count %ld != 0",
4955 pmap, pmap->pm_stats.resident_count));
4959 kvm_size(SYSCTL_HANDLER_ARGS)
4961 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4963 return sysctl_handle_long(oidp, &ksize, 0, req);
4965 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4966 0, 0, kvm_size, "LU",
4970 kvm_free(SYSCTL_HANDLER_ARGS)
4972 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4974 return sysctl_handle_long(oidp, &kfree, 0, req);
4976 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4977 0, 0, kvm_free, "LU",
4978 "Amount of KVM free");
4982 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
4987 vm_paddr_t dummypa, dummypd, dummypt;
4990 npdpg = howmany(size, NBPDP);
4991 npde = size / NBPDR;
4993 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
4994 pagezero((void *)PHYS_TO_DMAP(dummypa));
4996 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
4997 pagezero((void *)PHYS_TO_DMAP(dummypt));
4998 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
4999 for (i = 0; i < npdpg; i++)
5000 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
5002 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
5003 for (i = 0; i < NPTEPG; i++)
5004 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
5005 X86_PG_A | X86_PG_M | pg_nx);
5007 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
5008 for (i = 0; i < npde; i++)
5009 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
5011 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
5012 for (i = 0; i < npdpg; i++)
5013 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
5018 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
5022 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
5025 * The end of the page array's KVA region is 2MB aligned, see
5028 size = round_2mpage(end) - start;
5029 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
5030 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
5035 * Allocate physical memory for the vm_page array and map it into KVA,
5036 * attempting to back the vm_pages with domain-local memory.
5039 pmap_page_array_startup(long pages)
5042 pd_entry_t *pde, newpdir;
5043 vm_offset_t va, start, end;
5048 vm_page_array_size = pages;
5050 start = VM_MIN_KERNEL_ADDRESS;
5051 end = start + pages * sizeof(struct vm_page);
5052 for (va = start; va < end; va += NBPDR) {
5053 pfn = first_page + (va - start) / sizeof(struct vm_page);
5054 domain = vm_phys_domain(ptoa(pfn));
5055 pdpe = pmap_pdpe(kernel_pmap, va);
5056 if ((*pdpe & X86_PG_V) == 0) {
5057 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5059 pagezero((void *)PHYS_TO_DMAP(pa));
5060 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5061 X86_PG_A | X86_PG_M);
5063 pde = pmap_pdpe_to_pde(pdpe, va);
5064 if ((*pde & X86_PG_V) != 0)
5065 panic("Unexpected pde");
5066 pa = vm_phys_early_alloc(domain, NBPDR);
5067 for (i = 0; i < NPDEPG; i++)
5068 dump_add_page(pa + i * PAGE_SIZE);
5069 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5070 X86_PG_M | PG_PS | pg_g | pg_nx);
5071 pde_store(pde, newpdir);
5073 vm_page_array = (vm_page_t)start;
5076 pmap_kmsan_page_array_startup(start, end);
5081 * grow the number of kernel page table entries, if needed
5084 pmap_growkernel(vm_offset_t addr)
5088 pd_entry_t *pde, newpdir;
5093 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5096 * The kernel map covers two distinct regions of KVA: that used
5097 * for dynamic kernel memory allocations, and the uppermost 2GB
5098 * of the virtual address space. The latter is used to map the
5099 * kernel and loadable kernel modules. This scheme enables the
5100 * use of a special code generation model for kernel code which
5101 * takes advantage of compact addressing modes in machine code.
5103 * Both regions grow upwards; to avoid wasting memory, the gap
5104 * in between is unmapped. If "addr" is above "KERNBASE", the
5105 * kernel's region is grown, otherwise the kmem region is grown.
5107 * The correctness of this action is based on the following
5108 * argument: vm_map_insert() allocates contiguous ranges of the
5109 * kernel virtual address space. It calls this function if a range
5110 * ends after "kernel_vm_end". If the kernel is mapped between
5111 * "kernel_vm_end" and "addr", then the range cannot begin at
5112 * "kernel_vm_end". In fact, its beginning address cannot be less
5113 * than the kernel. Thus, there is no immediate need to allocate
5114 * any new kernel page table pages between "kernel_vm_end" and
5117 if (KERNBASE < addr) {
5118 end = KERNBASE + nkpt * NBPDR;
5124 end = kernel_vm_end;
5127 addr = roundup2(addr, NBPDR);
5128 if (addr - 1 >= vm_map_max(kernel_map))
5129 addr = vm_map_max(kernel_map);
5132 * The grown region is already mapped, so there is
5139 kasan_shadow_map(end, addr - end);
5140 kmsan_shadow_map(end, addr - end);
5141 while (end < addr) {
5142 pdpe = pmap_pdpe(kernel_pmap, end);
5143 if ((*pdpe & X86_PG_V) == 0) {
5144 nkpg = pmap_alloc_pt_page(kernel_pmap,
5145 pmap_pdpe_pindex(end), VM_ALLOC_WIRED |
5146 VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5148 panic("pmap_growkernel: no memory to grow kernel");
5149 paddr = VM_PAGE_TO_PHYS(nkpg);
5150 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5151 X86_PG_A | X86_PG_M);
5152 continue; /* try again */
5154 pde = pmap_pdpe_to_pde(pdpe, end);
5155 if ((*pde & X86_PG_V) != 0) {
5156 end = (end + NBPDR) & ~PDRMASK;
5157 if (end - 1 >= vm_map_max(kernel_map)) {
5158 end = vm_map_max(kernel_map);
5164 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5165 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5167 panic("pmap_growkernel: no memory to grow kernel");
5168 paddr = VM_PAGE_TO_PHYS(nkpg);
5169 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5170 pde_store(pde, newpdir);
5172 end = (end + NBPDR) & ~PDRMASK;
5173 if (end - 1 >= vm_map_max(kernel_map)) {
5174 end = vm_map_max(kernel_map);
5179 if (end <= KERNBASE)
5180 kernel_vm_end = end;
5182 nkpt = howmany(end - KERNBASE, NBPDR);
5186 /***************************************************
5187 * page management routines.
5188 ***************************************************/
5190 static const uint64_t pc_freemask[_NPCM] = {
5191 [0 ... _NPCM - 2] = PC_FREEN,
5192 [_NPCM - 1] = PC_FREEL
5197 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5198 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5199 &pc_chunk_count, "Current number of pv entry cnunks");
5201 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5202 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5203 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5205 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5206 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5207 &pc_chunk_frees, "Total number of pv entry chunks freed");
5209 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5210 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5212 "Number of failed attempts to get a pv entry chunk page");
5214 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5215 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5216 &pv_entry_frees, "Total number of pv entries freed");
5218 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5219 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5220 &pv_entry_allocs, "Total number of pv entries allocated");
5222 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5223 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5224 &pv_entry_count, "Current number of pv entries");
5226 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5227 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5228 &pv_entry_spare, "Current number of spare pv entries");
5232 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5237 pmap_invalidate_all(pmap);
5238 if (pmap != locked_pmap)
5241 pmap_delayed_invl_finish();
5245 * We are in a serious low memory condition. Resort to
5246 * drastic measures to free some pages so we can allocate
5247 * another pv entry chunk.
5249 * Returns NULL if PV entries were reclaimed from the specified pmap.
5251 * We do not, however, unmap 2mpages because subsequent accesses will
5252 * allocate per-page pv entries until repromotion occurs, thereby
5253 * exacerbating the shortage of free pv entries.
5256 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5258 struct pv_chunks_list *pvc;
5259 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5260 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5261 struct md_page *pvh;
5263 pmap_t next_pmap, pmap;
5264 pt_entry_t *pte, tpte;
5265 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5269 struct spglist free;
5271 int bit, field, freed;
5272 bool start_di, restart;
5274 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5275 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5278 PG_G = PG_A = PG_M = PG_RW = 0;
5280 bzero(&pc_marker_b, sizeof(pc_marker_b));
5281 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5282 pc_marker = (struct pv_chunk *)&pc_marker_b;
5283 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5286 * A delayed invalidation block should already be active if
5287 * pmap_advise() or pmap_remove() called this function by way
5288 * of pmap_demote_pde_locked().
5290 start_di = pmap_not_in_di();
5292 pvc = &pv_chunks[domain];
5293 mtx_lock(&pvc->pvc_lock);
5294 pvc->active_reclaims++;
5295 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5296 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5297 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5298 SLIST_EMPTY(&free)) {
5299 next_pmap = pc->pc_pmap;
5300 if (next_pmap == NULL) {
5302 * The next chunk is a marker. However, it is
5303 * not our marker, so active_reclaims must be
5304 * > 1. Consequently, the next_chunk code
5305 * will not rotate the pv_chunks list.
5309 mtx_unlock(&pvc->pvc_lock);
5312 * A pv_chunk can only be removed from the pc_lru list
5313 * when both pc_chunks_mutex is owned and the
5314 * corresponding pmap is locked.
5316 if (pmap != next_pmap) {
5318 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5321 /* Avoid deadlock and lock recursion. */
5322 if (pmap > locked_pmap) {
5323 RELEASE_PV_LIST_LOCK(lockp);
5326 pmap_delayed_invl_start();
5327 mtx_lock(&pvc->pvc_lock);
5329 } else if (pmap != locked_pmap) {
5330 if (PMAP_TRYLOCK(pmap)) {
5332 pmap_delayed_invl_start();
5333 mtx_lock(&pvc->pvc_lock);
5336 pmap = NULL; /* pmap is not locked */
5337 mtx_lock(&pvc->pvc_lock);
5338 pc = TAILQ_NEXT(pc_marker, pc_lru);
5340 pc->pc_pmap != next_pmap)
5344 } else if (start_di)
5345 pmap_delayed_invl_start();
5346 PG_G = pmap_global_bit(pmap);
5347 PG_A = pmap_accessed_bit(pmap);
5348 PG_M = pmap_modified_bit(pmap);
5349 PG_RW = pmap_rw_bit(pmap);
5355 * Destroy every non-wired, 4 KB page mapping in the chunk.
5358 for (field = 0; field < _NPCM; field++) {
5359 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5360 inuse != 0; inuse &= ~(1UL << bit)) {
5362 pv = &pc->pc_pventry[field * 64 + bit];
5364 pde = pmap_pde(pmap, va);
5365 if ((*pde & PG_PS) != 0)
5367 pte = pmap_pde_to_pte(pde, va);
5368 if ((*pte & PG_W) != 0)
5370 tpte = pte_load_clear(pte);
5371 if ((tpte & PG_G) != 0)
5372 pmap_invalidate_page(pmap, va);
5373 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5374 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5376 if ((tpte & PG_A) != 0)
5377 vm_page_aflag_set(m, PGA_REFERENCED);
5378 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5379 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5381 if (TAILQ_EMPTY(&m->md.pv_list) &&
5382 (m->flags & PG_FICTITIOUS) == 0) {
5383 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5384 if (TAILQ_EMPTY(&pvh->pv_list)) {
5385 vm_page_aflag_clear(m,
5389 pmap_delayed_invl_page(m);
5390 pc->pc_map[field] |= 1UL << bit;
5391 pmap_unuse_pt(pmap, va, *pde, &free);
5396 mtx_lock(&pvc->pvc_lock);
5399 /* Every freed mapping is for a 4 KB page. */
5400 pmap_resident_count_adj(pmap, -freed);
5401 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5402 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5403 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5404 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5405 if (pc_is_free(pc)) {
5406 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5407 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5408 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5409 /* Entire chunk is free; return it. */
5410 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5411 dump_drop_page(m_pc->phys_addr);
5412 mtx_lock(&pvc->pvc_lock);
5413 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5416 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5417 mtx_lock(&pvc->pvc_lock);
5418 /* One freed pv entry in locked_pmap is sufficient. */
5419 if (pmap == locked_pmap)
5422 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5423 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5424 if (pvc->active_reclaims == 1 && pmap != NULL) {
5426 * Rotate the pv chunks list so that we do not
5427 * scan the same pv chunks that could not be
5428 * freed (because they contained a wired
5429 * and/or superpage mapping) on every
5430 * invocation of reclaim_pv_chunk().
5432 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5433 MPASS(pc->pc_pmap != NULL);
5434 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5435 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5439 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5440 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5441 pvc->active_reclaims--;
5442 mtx_unlock(&pvc->pvc_lock);
5443 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5444 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5445 m_pc = SLIST_FIRST(&free);
5446 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5447 /* Recycle a freed page table page. */
5448 m_pc->ref_count = 1;
5450 vm_page_free_pages_toq(&free, true);
5455 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5460 domain = PCPU_GET(domain);
5461 for (i = 0; i < vm_ndomains; i++) {
5462 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5465 domain = (domain + 1) % vm_ndomains;
5472 * free the pv_entry back to the free list
5475 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5477 struct pv_chunk *pc;
5478 int idx, field, bit;
5480 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5481 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5482 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5483 PV_STAT(counter_u64_add(pv_entry_count, -1));
5484 pc = pv_to_chunk(pv);
5485 idx = pv - &pc->pc_pventry[0];
5488 pc->pc_map[field] |= 1ul << bit;
5489 if (!pc_is_free(pc)) {
5490 /* 98% of the time, pc is already at the head of the list. */
5491 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5492 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5493 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5497 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5502 free_pv_chunk_dequeued(struct pv_chunk *pc)
5506 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5507 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5508 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5509 counter_u64_add(pv_page_count, -1);
5510 /* entire chunk is free, return it */
5511 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5512 dump_drop_page(m->phys_addr);
5513 vm_page_unwire_noq(m);
5518 free_pv_chunk(struct pv_chunk *pc)
5520 struct pv_chunks_list *pvc;
5522 pvc = &pv_chunks[pc_to_domain(pc)];
5523 mtx_lock(&pvc->pvc_lock);
5524 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5525 mtx_unlock(&pvc->pvc_lock);
5526 free_pv_chunk_dequeued(pc);
5530 free_pv_chunk_batch(struct pv_chunklist *batch)
5532 struct pv_chunks_list *pvc;
5533 struct pv_chunk *pc, *npc;
5536 for (i = 0; i < vm_ndomains; i++) {
5537 if (TAILQ_EMPTY(&batch[i]))
5539 pvc = &pv_chunks[i];
5540 mtx_lock(&pvc->pvc_lock);
5541 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5542 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5544 mtx_unlock(&pvc->pvc_lock);
5547 for (i = 0; i < vm_ndomains; i++) {
5548 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5549 free_pv_chunk_dequeued(pc);
5555 * Returns a new PV entry, allocating a new PV chunk from the system when
5556 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5557 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5560 * The given PV list lock may be released.
5563 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5565 struct pv_chunks_list *pvc;
5568 struct pv_chunk *pc;
5571 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5572 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5574 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5576 for (field = 0; field < _NPCM; field++) {
5577 if (pc->pc_map[field]) {
5578 bit = bsfq(pc->pc_map[field]);
5582 if (field < _NPCM) {
5583 pv = &pc->pc_pventry[field * 64 + bit];
5584 pc->pc_map[field] &= ~(1ul << bit);
5585 /* If this was the last item, move it to tail */
5586 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
5587 pc->pc_map[2] == 0) {
5588 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5589 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5592 PV_STAT(counter_u64_add(pv_entry_count, 1));
5593 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5597 /* No free items, allocate another chunk */
5598 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5600 if (lockp == NULL) {
5601 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5604 m = reclaim_pv_chunk(pmap, lockp);
5608 counter_u64_add(pv_page_count, 1);
5609 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5610 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5611 dump_add_page(m->phys_addr);
5612 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5614 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5615 pc->pc_map[1] = PC_FREEN;
5616 pc->pc_map[2] = PC_FREEL;
5617 pvc = &pv_chunks[vm_page_domain(m)];
5618 mtx_lock(&pvc->pvc_lock);
5619 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5620 mtx_unlock(&pvc->pvc_lock);
5621 pv = &pc->pc_pventry[0];
5622 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5623 PV_STAT(counter_u64_add(pv_entry_count, 1));
5624 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5629 * Returns the number of one bits within the given PV chunk map.
5631 * The erratas for Intel processors state that "POPCNT Instruction May
5632 * Take Longer to Execute Than Expected". It is believed that the
5633 * issue is the spurious dependency on the destination register.
5634 * Provide a hint to the register rename logic that the destination
5635 * value is overwritten, by clearing it, as suggested in the
5636 * optimization manual. It should be cheap for unaffected processors
5639 * Reference numbers for erratas are
5640 * 4th Gen Core: HSD146
5641 * 5th Gen Core: BDM85
5642 * 6th Gen Core: SKL029
5645 popcnt_pc_map_pq(uint64_t *map)
5649 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5650 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5651 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5652 : "=&r" (result), "=&r" (tmp)
5653 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5658 * Ensure that the number of spare PV entries in the specified pmap meets or
5659 * exceeds the given count, "needed".
5661 * The given PV list lock may be released.
5664 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5666 struct pv_chunks_list *pvc;
5667 struct pch new_tail[PMAP_MEMDOM];
5668 struct pv_chunk *pc;
5673 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5674 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5677 * Newly allocated PV chunks must be stored in a private list until
5678 * the required number of PV chunks have been allocated. Otherwise,
5679 * reclaim_pv_chunk() could recycle one of these chunks. In
5680 * contrast, these chunks must be added to the pmap upon allocation.
5682 for (i = 0; i < PMAP_MEMDOM; i++)
5683 TAILQ_INIT(&new_tail[i]);
5686 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5688 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5689 bit_count((bitstr_t *)pc->pc_map, 0,
5690 sizeof(pc->pc_map) * NBBY, &free);
5693 free = popcnt_pc_map_pq(pc->pc_map);
5697 if (avail >= needed)
5700 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5701 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5703 m = reclaim_pv_chunk(pmap, lockp);
5708 counter_u64_add(pv_page_count, 1);
5709 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5710 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5711 dump_add_page(m->phys_addr);
5712 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5714 pc->pc_map[0] = PC_FREEN;
5715 pc->pc_map[1] = PC_FREEN;
5716 pc->pc_map[2] = PC_FREEL;
5717 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5718 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5719 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5722 * The reclaim might have freed a chunk from the current pmap.
5723 * If that chunk contained available entries, we need to
5724 * re-count the number of available entries.
5729 for (i = 0; i < vm_ndomains; i++) {
5730 if (TAILQ_EMPTY(&new_tail[i]))
5732 pvc = &pv_chunks[i];
5733 mtx_lock(&pvc->pvc_lock);
5734 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5735 mtx_unlock(&pvc->pvc_lock);
5740 * First find and then remove the pv entry for the specified pmap and virtual
5741 * address from the specified pv list. Returns the pv entry if found and NULL
5742 * otherwise. This operation can be performed on pv lists for either 4KB or
5743 * 2MB page mappings.
5745 static __inline pv_entry_t
5746 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5750 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5751 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5752 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5761 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5762 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5763 * entries for each of the 4KB page mappings.
5766 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5767 struct rwlock **lockp)
5769 struct md_page *pvh;
5770 struct pv_chunk *pc;
5772 vm_offset_t va_last;
5776 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5777 KASSERT((pa & PDRMASK) == 0,
5778 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5779 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5782 * Transfer the 2mpage's pv entry for this mapping to the first
5783 * page's pv list. Once this transfer begins, the pv list lock
5784 * must not be released until the last pv entry is reinstantiated.
5786 pvh = pa_to_pvh(pa);
5787 va = trunc_2mpage(va);
5788 pv = pmap_pvh_remove(pvh, pmap, va);
5789 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5790 m = PHYS_TO_VM_PAGE(pa);
5791 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5793 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5794 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5795 va_last = va + NBPDR - PAGE_SIZE;
5797 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5798 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
5799 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
5800 for (field = 0; field < _NPCM; field++) {
5801 while (pc->pc_map[field]) {
5802 bit = bsfq(pc->pc_map[field]);
5803 pc->pc_map[field] &= ~(1ul << bit);
5804 pv = &pc->pc_pventry[field * 64 + bit];
5808 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5809 ("pmap_pv_demote_pde: page %p is not managed", m));
5810 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5816 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5817 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5820 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
5821 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5822 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5824 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5825 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5828 #if VM_NRESERVLEVEL > 0
5830 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5831 * replace the many pv entries for the 4KB page mappings by a single pv entry
5832 * for the 2MB page mapping.
5835 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5836 struct rwlock **lockp)
5838 struct md_page *pvh;
5840 vm_offset_t va_last;
5843 KASSERT((pa & PDRMASK) == 0,
5844 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5845 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5848 * Transfer the first page's pv entry for this mapping to the 2mpage's
5849 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5850 * a transfer avoids the possibility that get_pv_entry() calls
5851 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5852 * mappings that is being promoted.
5854 m = PHYS_TO_VM_PAGE(pa);
5855 va = trunc_2mpage(va);
5856 pv = pmap_pvh_remove(&m->md, pmap, va);
5857 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5858 pvh = pa_to_pvh(pa);
5859 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5861 /* Free the remaining NPTEPG - 1 pv entries. */
5862 va_last = va + NBPDR - PAGE_SIZE;
5866 pmap_pvh_free(&m->md, pmap, va);
5867 } while (va < va_last);
5869 #endif /* VM_NRESERVLEVEL > 0 */
5872 * First find and then destroy the pv entry for the specified pmap and virtual
5873 * address. This operation can be performed on pv lists for either 4KB or 2MB
5877 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5881 pv = pmap_pvh_remove(pvh, pmap, va);
5882 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5883 free_pv_entry(pmap, pv);
5887 * Conditionally create the PV entry for a 4KB page mapping if the required
5888 * memory can be allocated without resorting to reclamation.
5891 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5892 struct rwlock **lockp)
5896 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5897 /* Pass NULL instead of the lock pointer to disable reclamation. */
5898 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5900 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5901 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5909 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5910 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5911 * false if the PV entry cannot be allocated without resorting to reclamation.
5914 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5915 struct rwlock **lockp)
5917 struct md_page *pvh;
5921 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5922 /* Pass NULL instead of the lock pointer to disable reclamation. */
5923 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5924 NULL : lockp)) == NULL)
5927 pa = pde & PG_PS_FRAME;
5928 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5929 pvh = pa_to_pvh(pa);
5930 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5936 * Fills a page table page with mappings to consecutive physical pages.
5939 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5943 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5945 newpte += PAGE_SIZE;
5950 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5951 * mapping is invalidated.
5954 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5956 struct rwlock *lock;
5960 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5967 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5971 pt_entry_t *xpte, *ypte;
5973 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5974 xpte++, newpte += PAGE_SIZE) {
5975 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
5976 printf("pmap_demote_pde: xpte %zd and newpte map "
5977 "different pages: found %#lx, expected %#lx\n",
5978 xpte - firstpte, *xpte, newpte);
5979 printf("page table dump\n");
5980 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
5981 printf("%zd %#lx\n", ypte - firstpte, *ypte);
5986 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
5987 ("pmap_demote_pde: firstpte and newpte map different physical"
5994 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
5995 pd_entry_t oldpde, struct rwlock **lockp)
5997 struct spglist free;
6001 sva = trunc_2mpage(va);
6002 pmap_remove_pde(pmap, pde, sva, &free, lockp);
6003 if ((oldpde & pmap_global_bit(pmap)) == 0)
6004 pmap_invalidate_pde_page(pmap, sva, oldpde);
6005 vm_page_free_pages_toq(&free, true);
6006 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
6011 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
6012 struct rwlock **lockp)
6014 pd_entry_t newpde, oldpde;
6015 pt_entry_t *firstpte, newpte;
6016 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6022 PG_A = pmap_accessed_bit(pmap);
6023 PG_G = pmap_global_bit(pmap);
6024 PG_M = pmap_modified_bit(pmap);
6025 PG_RW = pmap_rw_bit(pmap);
6026 PG_V = pmap_valid_bit(pmap);
6027 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6028 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6030 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6031 in_kernel = va >= VM_MAXUSER_ADDRESS;
6033 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
6034 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
6037 * Invalidate the 2MB page mapping and return "failure" if the
6038 * mapping was never accessed.
6040 if ((oldpde & PG_A) == 0) {
6041 KASSERT((oldpde & PG_W) == 0,
6042 ("pmap_demote_pde: a wired mapping is missing PG_A"));
6043 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6047 mpte = pmap_remove_pt_page(pmap, va);
6049 KASSERT((oldpde & PG_W) == 0,
6050 ("pmap_demote_pde: page table page for a wired mapping"
6054 * If the page table page is missing and the mapping
6055 * is for a kernel address, the mapping must belong to
6056 * the direct map. Page table pages are preallocated
6057 * for every other part of the kernel address space,
6058 * so the direct map region is the only part of the
6059 * kernel address space that must be handled here.
6061 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6062 va < DMAP_MAX_ADDRESS),
6063 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6066 * If the 2MB page mapping belongs to the direct map
6067 * region of the kernel's address space, then the page
6068 * allocation request specifies the highest possible
6069 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6070 * priority is normal.
6072 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6073 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6076 * If the allocation of the new page table page fails,
6077 * invalidate the 2MB page mapping and return "failure".
6080 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6085 mpte->ref_count = NPTEPG;
6087 mptepa = VM_PAGE_TO_PHYS(mpte);
6088 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6089 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6090 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6091 ("pmap_demote_pde: oldpde is missing PG_M"));
6092 newpte = oldpde & ~PG_PS;
6093 newpte = pmap_swap_pat(pmap, newpte);
6096 * If the PTP is not leftover from an earlier promotion or it does not
6097 * have PG_A set in every PTE, then fill it. The new PTEs will all
6100 if (!vm_page_all_valid(mpte))
6101 pmap_fill_ptp(firstpte, newpte);
6103 pmap_demote_pde_check(firstpte, newpte);
6106 * If the mapping has changed attributes, update the PTEs.
6108 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6109 pmap_fill_ptp(firstpte, newpte);
6112 * The spare PV entries must be reserved prior to demoting the
6113 * mapping, that is, prior to changing the PDE. Otherwise, the state
6114 * of the PDE and the PV lists will be inconsistent, which can result
6115 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6116 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6117 * PV entry for the 2MB page mapping that is being demoted.
6119 if ((oldpde & PG_MANAGED) != 0)
6120 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6123 * Demote the mapping. This pmap is locked. The old PDE has
6124 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6125 * set. Thus, there is no danger of a race with another
6126 * processor changing the setting of PG_A and/or PG_M between
6127 * the read above and the store below.
6129 if (workaround_erratum383)
6130 pmap_update_pde(pmap, va, pde, newpde);
6132 pde_store(pde, newpde);
6135 * Invalidate a stale recursive mapping of the page table page.
6138 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6141 * Demote the PV entry.
6143 if ((oldpde & PG_MANAGED) != 0)
6144 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6146 counter_u64_add(pmap_pde_demotions, 1);
6147 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6153 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6156 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6162 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6163 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6164 mpte = pmap_remove_pt_page(pmap, va);
6166 panic("pmap_remove_kernel_pde: Missing pt page.");
6168 mptepa = VM_PAGE_TO_PHYS(mpte);
6169 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6172 * If this page table page was unmapped by a promotion, then it
6173 * contains valid mappings. Zero it to invalidate those mappings.
6175 if (vm_page_any_valid(mpte))
6176 pagezero((void *)PHYS_TO_DMAP(mptepa));
6179 * Demote the mapping.
6181 if (workaround_erratum383)
6182 pmap_update_pde(pmap, va, pde, newpde);
6184 pde_store(pde, newpde);
6187 * Invalidate a stale recursive mapping of the page table page.
6189 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6193 * pmap_remove_pde: do the things to unmap a superpage in a process
6196 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6197 struct spglist *free, struct rwlock **lockp)
6199 struct md_page *pvh;
6201 vm_offset_t eva, va;
6203 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6205 PG_G = pmap_global_bit(pmap);
6206 PG_A = pmap_accessed_bit(pmap);
6207 PG_M = pmap_modified_bit(pmap);
6208 PG_RW = pmap_rw_bit(pmap);
6210 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6211 KASSERT((sva & PDRMASK) == 0,
6212 ("pmap_remove_pde: sva is not 2mpage aligned"));
6213 oldpde = pte_load_clear(pdq);
6215 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6216 if ((oldpde & PG_G) != 0)
6217 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6218 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6219 if (oldpde & PG_MANAGED) {
6220 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6221 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6222 pmap_pvh_free(pvh, pmap, sva);
6224 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6225 va < eva; va += PAGE_SIZE, m++) {
6226 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6229 vm_page_aflag_set(m, PGA_REFERENCED);
6230 if (TAILQ_EMPTY(&m->md.pv_list) &&
6231 TAILQ_EMPTY(&pvh->pv_list))
6232 vm_page_aflag_clear(m, PGA_WRITEABLE);
6233 pmap_delayed_invl_page(m);
6236 if (pmap == kernel_pmap) {
6237 pmap_remove_kernel_pde(pmap, pdq, sva);
6239 mpte = pmap_remove_pt_page(pmap, sva);
6241 KASSERT(vm_page_any_valid(mpte),
6242 ("pmap_remove_pde: pte page not promoted"));
6243 pmap_pt_page_count_adj(pmap, -1);
6244 KASSERT(mpte->ref_count == NPTEPG,
6245 ("pmap_remove_pde: pte page ref count error"));
6246 mpte->ref_count = 0;
6247 pmap_add_delayed_free_list(mpte, free, FALSE);
6250 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6254 * pmap_remove_pte: do the things to unmap a page in a process
6257 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6258 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6260 struct md_page *pvh;
6261 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6264 PG_A = pmap_accessed_bit(pmap);
6265 PG_M = pmap_modified_bit(pmap);
6266 PG_RW = pmap_rw_bit(pmap);
6268 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6269 oldpte = pte_load_clear(ptq);
6271 pmap->pm_stats.wired_count -= 1;
6272 pmap_resident_count_adj(pmap, -1);
6273 if (oldpte & PG_MANAGED) {
6274 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6275 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6278 vm_page_aflag_set(m, PGA_REFERENCED);
6279 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6280 pmap_pvh_free(&m->md, pmap, va);
6281 if (TAILQ_EMPTY(&m->md.pv_list) &&
6282 (m->flags & PG_FICTITIOUS) == 0) {
6283 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6284 if (TAILQ_EMPTY(&pvh->pv_list))
6285 vm_page_aflag_clear(m, PGA_WRITEABLE);
6287 pmap_delayed_invl_page(m);
6289 return (pmap_unuse_pt(pmap, va, ptepde, free));
6293 * Remove a single page from a process address space
6296 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6297 struct spglist *free)
6299 struct rwlock *lock;
6300 pt_entry_t *pte, PG_V;
6302 PG_V = pmap_valid_bit(pmap);
6303 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6304 if ((*pde & PG_V) == 0)
6306 pte = pmap_pde_to_pte(pde, va);
6307 if ((*pte & PG_V) == 0)
6310 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6313 pmap_invalidate_page(pmap, va);
6317 * Removes the specified range of addresses from the page table page.
6320 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6321 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6323 pt_entry_t PG_G, *pte;
6327 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6328 PG_G = pmap_global_bit(pmap);
6331 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6335 pmap_invalidate_range(pmap, va, sva);
6340 if ((*pte & PG_G) == 0)
6344 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6350 pmap_invalidate_range(pmap, va, sva);
6355 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6357 struct rwlock *lock;
6359 vm_offset_t va_next;
6360 pml5_entry_t *pml5e;
6361 pml4_entry_t *pml4e;
6363 pd_entry_t ptpaddr, *pde;
6364 pt_entry_t PG_G, PG_V;
6365 struct spglist free;
6368 PG_G = pmap_global_bit(pmap);
6369 PG_V = pmap_valid_bit(pmap);
6372 * If there are no resident pages besides the top level page
6373 * table page(s), there is nothing to do. Kernel pmap always
6374 * accounts whole preloaded area as resident, which makes its
6375 * resident count > 2.
6376 * Perform an unsynchronized read. This is, however, safe.
6378 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6385 pmap_delayed_invl_start();
6388 pmap_pkru_on_remove(pmap, sva, eva);
6391 * special handling of removing one page. a very
6392 * common operation and easy to short circuit some
6395 if (sva + PAGE_SIZE == eva) {
6396 pde = pmap_pde(pmap, sva);
6397 if (pde && (*pde & PG_PS) == 0) {
6398 pmap_remove_page(pmap, sva, pde, &free);
6404 for (; sva < eva; sva = va_next) {
6405 if (pmap->pm_stats.resident_count == 0)
6408 if (pmap_is_la57(pmap)) {
6409 pml5e = pmap_pml5e(pmap, sva);
6410 if ((*pml5e & PG_V) == 0) {
6411 va_next = (sva + NBPML5) & ~PML5MASK;
6416 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6418 pml4e = pmap_pml4e(pmap, sva);
6420 if ((*pml4e & PG_V) == 0) {
6421 va_next = (sva + NBPML4) & ~PML4MASK;
6427 va_next = (sva + NBPDP) & ~PDPMASK;
6430 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6431 if ((*pdpe & PG_V) == 0)
6433 if ((*pdpe & PG_PS) != 0) {
6434 KASSERT(va_next <= eva,
6435 ("partial update of non-transparent 1G mapping "
6436 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6437 *pdpe, sva, eva, va_next));
6438 MPASS(pmap != kernel_pmap); /* XXXKIB */
6439 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6442 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6443 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6444 pmap_unwire_ptp(pmap, sva, mt, &free);
6449 * Calculate index for next page table.
6451 va_next = (sva + NBPDR) & ~PDRMASK;
6455 pde = pmap_pdpe_to_pde(pdpe, sva);
6459 * Weed out invalid mappings.
6465 * Check for large page.
6467 if ((ptpaddr & PG_PS) != 0) {
6469 * Are we removing the entire large page? If not,
6470 * demote the mapping and fall through.
6472 if (sva + NBPDR == va_next && eva >= va_next) {
6474 * The TLB entry for a PG_G mapping is
6475 * invalidated by pmap_remove_pde().
6477 if ((ptpaddr & PG_G) == 0)
6479 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6481 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6483 /* The large page mapping was destroyed. */
6490 * Limit our scan to either the end of the va represented
6491 * by the current page table page, or to the end of the
6492 * range being removed.
6497 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6504 pmap_invalidate_all(pmap);
6506 pmap_delayed_invl_finish();
6507 vm_page_free_pages_toq(&free, true);
6511 * Remove the given range of addresses from the specified map.
6513 * It is assumed that the start and end are properly
6514 * rounded to the page size.
6517 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6519 pmap_remove1(pmap, sva, eva, false);
6523 * Remove the given range of addresses as part of a logical unmap
6524 * operation. This has the effect of calling pmap_remove(), but
6525 * also clears any metadata that should persist for the lifetime
6526 * of a logical mapping.
6529 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6531 pmap_remove1(pmap, sva, eva, true);
6535 * Routine: pmap_remove_all
6537 * Removes this physical page from
6538 * all physical maps in which it resides.
6539 * Reflects back modify bits to the pager.
6542 * Original versions of this routine were very
6543 * inefficient because they iteratively called
6544 * pmap_remove (slow...)
6548 pmap_remove_all(vm_page_t m)
6550 struct md_page *pvh;
6553 struct rwlock *lock;
6554 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6557 struct spglist free;
6558 int pvh_gen, md_gen;
6560 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6561 ("pmap_remove_all: page %p is not managed", m));
6563 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6564 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6565 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6568 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6570 if (!PMAP_TRYLOCK(pmap)) {
6571 pvh_gen = pvh->pv_gen;
6575 if (pvh_gen != pvh->pv_gen) {
6581 pde = pmap_pde(pmap, va);
6582 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6585 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6587 if (!PMAP_TRYLOCK(pmap)) {
6588 pvh_gen = pvh->pv_gen;
6589 md_gen = m->md.pv_gen;
6593 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6598 PG_A = pmap_accessed_bit(pmap);
6599 PG_M = pmap_modified_bit(pmap);
6600 PG_RW = pmap_rw_bit(pmap);
6601 pmap_resident_count_adj(pmap, -1);
6602 pde = pmap_pde(pmap, pv->pv_va);
6603 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6604 " a 2mpage in page %p's pv list", m));
6605 pte = pmap_pde_to_pte(pde, pv->pv_va);
6606 tpte = pte_load_clear(pte);
6608 pmap->pm_stats.wired_count--;
6610 vm_page_aflag_set(m, PGA_REFERENCED);
6613 * Update the vm_page_t clean and reference bits.
6615 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6617 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6618 pmap_invalidate_page(pmap, pv->pv_va);
6619 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6621 free_pv_entry(pmap, pv);
6624 vm_page_aflag_clear(m, PGA_WRITEABLE);
6626 pmap_delayed_invl_wait(m);
6627 vm_page_free_pages_toq(&free, true);
6631 * pmap_protect_pde: do the things to protect a 2mpage in a process
6634 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6636 pd_entry_t newpde, oldpde;
6638 boolean_t anychanged;
6639 pt_entry_t PG_G, PG_M, PG_RW;
6641 PG_G = pmap_global_bit(pmap);
6642 PG_M = pmap_modified_bit(pmap);
6643 PG_RW = pmap_rw_bit(pmap);
6645 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6646 KASSERT((sva & PDRMASK) == 0,
6647 ("pmap_protect_pde: sva is not 2mpage aligned"));
6650 oldpde = newpde = *pde;
6651 if ((prot & VM_PROT_WRITE) == 0) {
6652 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6653 (PG_MANAGED | PG_M | PG_RW)) {
6654 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6655 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6658 newpde &= ~(PG_RW | PG_M);
6660 if ((prot & VM_PROT_EXECUTE) == 0)
6662 if (newpde != oldpde) {
6664 * As an optimization to future operations on this PDE, clear
6665 * PG_PROMOTED. The impending invalidation will remove any
6666 * lingering 4KB page mappings from the TLB.
6668 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6670 if ((oldpde & PG_G) != 0)
6671 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6675 return (anychanged);
6679 * Set the physical protection on the
6680 * specified range of this map as requested.
6683 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6686 vm_offset_t va_next;
6687 pml4_entry_t *pml4e;
6689 pd_entry_t ptpaddr, *pde;
6690 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6691 pt_entry_t obits, pbits;
6692 boolean_t anychanged;
6694 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6695 if (prot == VM_PROT_NONE) {
6696 pmap_remove(pmap, sva, eva);
6700 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6701 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6704 PG_G = pmap_global_bit(pmap);
6705 PG_M = pmap_modified_bit(pmap);
6706 PG_V = pmap_valid_bit(pmap);
6707 PG_RW = pmap_rw_bit(pmap);
6711 * Although this function delays and batches the invalidation
6712 * of stale TLB entries, it does not need to call
6713 * pmap_delayed_invl_start() and
6714 * pmap_delayed_invl_finish(), because it does not
6715 * ordinarily destroy mappings. Stale TLB entries from
6716 * protection-only changes need only be invalidated before the
6717 * pmap lock is released, because protection-only changes do
6718 * not destroy PV entries. Even operations that iterate over
6719 * a physical page's PV list of mappings, like
6720 * pmap_remove_write(), acquire the pmap lock for each
6721 * mapping. Consequently, for protection-only changes, the
6722 * pmap lock suffices to synchronize both page table and TLB
6725 * This function only destroys a mapping if pmap_demote_pde()
6726 * fails. In that case, stale TLB entries are immediately
6731 for (; sva < eva; sva = va_next) {
6732 pml4e = pmap_pml4e(pmap, sva);
6733 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6734 va_next = (sva + NBPML4) & ~PML4MASK;
6740 va_next = (sva + NBPDP) & ~PDPMASK;
6743 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6744 if ((*pdpe & PG_V) == 0)
6746 if ((*pdpe & PG_PS) != 0) {
6747 KASSERT(va_next <= eva,
6748 ("partial update of non-transparent 1G mapping "
6749 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6750 *pdpe, sva, eva, va_next));
6752 obits = pbits = *pdpe;
6753 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6754 MPASS(pmap != kernel_pmap); /* XXXKIB */
6755 if ((prot & VM_PROT_WRITE) == 0)
6756 pbits &= ~(PG_RW | PG_M);
6757 if ((prot & VM_PROT_EXECUTE) == 0)
6760 if (pbits != obits) {
6761 if (!atomic_cmpset_long(pdpe, obits, pbits))
6762 /* PG_PS cannot be cleared under us, */
6769 va_next = (sva + NBPDR) & ~PDRMASK;
6773 pde = pmap_pdpe_to_pde(pdpe, sva);
6777 * Weed out invalid mappings.
6783 * Check for large page.
6785 if ((ptpaddr & PG_PS) != 0) {
6787 * Are we protecting the entire large page? If not,
6788 * demote the mapping and fall through.
6790 if (sva + NBPDR == va_next && eva >= va_next) {
6792 * The TLB entry for a PG_G mapping is
6793 * invalidated by pmap_protect_pde().
6795 if (pmap_protect_pde(pmap, pde, sva, prot))
6798 } else if (!pmap_demote_pde(pmap, pde, sva)) {
6800 * The large page mapping was destroyed.
6809 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6812 obits = pbits = *pte;
6813 if ((pbits & PG_V) == 0)
6816 if ((prot & VM_PROT_WRITE) == 0) {
6817 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6818 (PG_MANAGED | PG_M | PG_RW)) {
6819 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6822 pbits &= ~(PG_RW | PG_M);
6824 if ((prot & VM_PROT_EXECUTE) == 0)
6827 if (pbits != obits) {
6828 if (!atomic_cmpset_long(pte, obits, pbits))
6831 pmap_invalidate_page(pmap, sva);
6838 pmap_invalidate_all(pmap);
6842 #if VM_NRESERVLEVEL > 0
6844 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6847 if (pmap->pm_type != PT_EPT)
6849 return ((pde & EPT_PG_EXECUTE) != 0);
6853 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6854 * single page table page (PTP) to a single 2MB page mapping. For promotion
6855 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6856 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6857 * identical characteristics.
6860 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6861 struct rwlock **lockp)
6864 pt_entry_t *firstpte, oldpte, pa, *pte;
6865 pt_entry_t allpte_PG_A, PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6868 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6869 if (!pmap_ps_enabled(pmap))
6872 PG_A = pmap_accessed_bit(pmap);
6873 PG_G = pmap_global_bit(pmap);
6874 PG_M = pmap_modified_bit(pmap);
6875 PG_V = pmap_valid_bit(pmap);
6876 PG_RW = pmap_rw_bit(pmap);
6877 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6878 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6881 * Examine the first PTE in the specified PTP. Abort if this PTE is
6882 * ineligible for promotion due to hardware errata, invalid, or does
6883 * not map the first 4KB physical page within a 2MB page.
6885 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6887 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6889 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6890 counter_u64_add(pmap_pde_p_failures, 1);
6891 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6892 " in pmap %p", va, pmap);
6897 * Both here and in the below "for" loop, to allow for repromotion
6898 * after MADV_FREE, conditionally write protect a clean PTE before
6899 * possibly aborting the promotion due to other PTE attributes. Why?
6900 * Suppose that MADV_FREE is applied to a part of a superpage, the
6901 * address range [S, E). pmap_advise() will demote the superpage
6902 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6903 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6904 * imagine that the memory in [S, E) is recycled, but the last 4KB
6905 * page in [S, E) is not the last to be rewritten, or simply accessed.
6906 * In other words, there is still a 4KB page in [S, E), call it P,
6907 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6908 * we write protect P before aborting the promotion, if and when P is
6909 * finally rewritten, there won't be a page fault to trigger
6913 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6915 * When PG_M is already clear, PG_RW can be cleared without
6916 * a TLB invalidation.
6918 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6921 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6922 " in pmap %p", va & ~PDRMASK, pmap);
6926 * Examine each of the other PTEs in the specified PTP. Abort if this
6927 * PTE maps an unexpected 4KB physical page or does not have identical
6928 * characteristics to the first PTE.
6930 allpte_PG_A = newpde & PG_A;
6931 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6932 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6934 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6935 counter_u64_add(pmap_pde_p_failures, 1);
6936 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6937 " in pmap %p", va, pmap);
6941 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6943 * When PG_M is already clear, PG_RW can be cleared
6944 * without a TLB invalidation.
6946 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6949 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6950 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6951 (va & ~PDRMASK), pmap);
6953 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6954 counter_u64_add(pmap_pde_p_failures, 1);
6955 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6956 " in pmap %p", va, pmap);
6959 allpte_PG_A &= oldpte;
6964 * Unless all PTEs have PG_A set, clear it from the superpage mapping,
6965 * so that promotions triggered by speculative mappings, such as
6966 * pmap_enter_quick(), don't automatically mark the underlying pages
6969 newpde &= ~PG_A | allpte_PG_A;
6972 * EPT PTEs with PG_M set and PG_A clear are not supported by early
6973 * MMUs supporting EPT.
6975 KASSERT((newpde & PG_A) != 0 || safe_to_clear_referenced(pmap, newpde),
6976 ("unsupported EPT PTE"));
6979 * Save the PTP in its current state until the PDE mapping the
6980 * superpage is demoted by pmap_demote_pde() or destroyed by
6981 * pmap_remove_pde(). If PG_A is not set in every PTE, then request
6982 * that the PTP be refilled on demotion.
6985 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
6986 KASSERT(mpte >= vm_page_array &&
6987 mpte < &vm_page_array[vm_page_array_size],
6988 ("pmap_promote_pde: page table page is out of range"));
6989 KASSERT(mpte->pindex == pmap_pde_pindex(va),
6990 ("pmap_promote_pde: page table page's pindex is wrong "
6991 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
6992 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
6993 if (pmap_insert_pt_page(pmap, mpte, true, allpte_PG_A != 0)) {
6994 counter_u64_add(pmap_pde_p_failures, 1);
6996 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
7002 * Promote the pv entries.
7004 if ((newpde & PG_MANAGED) != 0)
7005 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
7008 * Propagate the PAT index to its proper position.
7010 newpde = pmap_swap_pat(pmap, newpde);
7013 * Map the superpage.
7015 if (workaround_erratum383)
7016 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
7018 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
7020 counter_u64_add(pmap_pde_promotions, 1);
7021 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
7022 " in pmap %p", va, pmap);
7025 #endif /* VM_NRESERVLEVEL > 0 */
7028 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
7032 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
7034 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7035 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
7036 ("psind %d unexpected", psind));
7037 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
7038 ("unaligned phys address %#lx newpte %#lx psind %d",
7039 newpte & PG_FRAME, newpte, psind));
7040 KASSERT((va & (pagesizes[psind] - 1)) == 0,
7041 ("unaligned va %#lx psind %d", va, psind));
7042 KASSERT(va < VM_MAXUSER_ADDRESS,
7043 ("kernel mode non-transparent superpage")); /* XXXKIB */
7044 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
7045 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
7047 PG_V = pmap_valid_bit(pmap);
7050 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind]))
7051 return (KERN_PROTECTION_FAILURE);
7053 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7054 pten |= pmap_pkru_get(pmap, va);
7056 if (psind == 2) { /* 1G */
7057 pml4e = pmap_pml4e(pmap, va);
7058 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7059 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7063 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7064 pdpe = &pdpe[pmap_pdpe_index(va)];
7066 MPASS(origpte == 0);
7068 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7069 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7071 if ((origpte & PG_V) == 0) {
7072 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7077 } else /* (psind == 1) */ { /* 2M */
7078 pde = pmap_pde(pmap, va);
7080 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7084 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7085 pde = &pde[pmap_pde_index(va)];
7087 MPASS(origpte == 0);
7090 if ((origpte & PG_V) == 0) {
7091 pdpe = pmap_pdpe(pmap, va);
7092 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7093 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7099 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7100 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7101 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7102 va, psind == 2 ? "1G" : "2M", origpte, pten));
7103 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7104 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7105 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7106 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7107 if ((origpte & PG_V) == 0)
7108 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7110 return (KERN_SUCCESS);
7113 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7114 return (KERN_RESOURCE_SHORTAGE);
7122 * Insert the given physical page (p) at
7123 * the specified virtual address (v) in the
7124 * target physical map with the protection requested.
7126 * If specified, the page will be wired down, meaning
7127 * that the related pte can not be reclaimed.
7129 * NB: This is the only routine which MAY NOT lazy-evaluate
7130 * or lose information. That is, this routine must actually
7131 * insert this page into the given map NOW.
7133 * When destroying both a page table and PV entry, this function
7134 * performs the TLB invalidation before releasing the PV list
7135 * lock, so we do not need pmap_delayed_invl_page() calls here.
7138 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7139 u_int flags, int8_t psind)
7141 struct rwlock *lock;
7143 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7144 pt_entry_t newpte, origpte;
7151 PG_A = pmap_accessed_bit(pmap);
7152 PG_G = pmap_global_bit(pmap);
7153 PG_M = pmap_modified_bit(pmap);
7154 PG_V = pmap_valid_bit(pmap);
7155 PG_RW = pmap_rw_bit(pmap);
7157 va = trunc_page(va);
7158 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7159 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7160 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7162 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7163 ("pmap_enter: managed mapping within the clean submap"));
7164 if ((m->oflags & VPO_UNMANAGED) == 0)
7165 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7166 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7167 ("pmap_enter: flags %u has reserved bits set", flags));
7168 pa = VM_PAGE_TO_PHYS(m);
7169 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7170 if ((flags & VM_PROT_WRITE) != 0)
7172 if ((prot & VM_PROT_WRITE) != 0)
7174 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7175 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7176 if ((prot & VM_PROT_EXECUTE) == 0)
7178 if ((flags & PMAP_ENTER_WIRED) != 0)
7180 if (va < VM_MAXUSER_ADDRESS)
7182 if (pmap == kernel_pmap)
7184 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7187 * Set modified bit gratuitously for writeable mappings if
7188 * the page is unmanaged. We do not want to take a fault
7189 * to do the dirty bit accounting for these mappings.
7191 if ((m->oflags & VPO_UNMANAGED) != 0) {
7192 if ((newpte & PG_RW) != 0)
7195 newpte |= PG_MANAGED;
7199 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7200 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7201 ("managed largepage va %#lx flags %#x", va, flags));
7202 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7207 /* Assert the required virtual and physical alignment. */
7208 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7209 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7210 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7216 * In the case that a page table page is not
7217 * resident, we are creating it here.
7220 pde = pmap_pde(pmap, va);
7221 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7222 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7223 pte = pmap_pde_to_pte(pde, va);
7224 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7225 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7228 } else if (va < VM_MAXUSER_ADDRESS) {
7230 * Here if the pte page isn't mapped, or if it has been
7233 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7234 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7235 nosleep ? NULL : &lock, va);
7236 if (mpte == NULL && nosleep) {
7237 rv = KERN_RESOURCE_SHORTAGE;
7242 panic("pmap_enter: invalid page directory va=%#lx", va);
7246 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7247 newpte |= pmap_pkru_get(pmap, va);
7250 * Is the specified virtual address already mapped?
7252 if ((origpte & PG_V) != 0) {
7254 * Wiring change, just update stats. We don't worry about
7255 * wiring PT pages as they remain resident as long as there
7256 * are valid mappings in them. Hence, if a user page is wired,
7257 * the PT page will be also.
7259 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7260 pmap->pm_stats.wired_count++;
7261 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7262 pmap->pm_stats.wired_count--;
7265 * Remove the extra PT page reference.
7269 KASSERT(mpte->ref_count > 0,
7270 ("pmap_enter: missing reference to page table page,"
7275 * Has the physical page changed?
7277 opa = origpte & PG_FRAME;
7280 * No, might be a protection or wiring change.
7282 if ((origpte & PG_MANAGED) != 0 &&
7283 (newpte & PG_RW) != 0)
7284 vm_page_aflag_set(m, PGA_WRITEABLE);
7285 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7291 * The physical page has changed. Temporarily invalidate
7292 * the mapping. This ensures that all threads sharing the
7293 * pmap keep a consistent view of the mapping, which is
7294 * necessary for the correct handling of COW faults. It
7295 * also permits reuse of the old mapping's PV entry,
7296 * avoiding an allocation.
7298 * For consistency, handle unmanaged mappings the same way.
7300 origpte = pte_load_clear(pte);
7301 KASSERT((origpte & PG_FRAME) == opa,
7302 ("pmap_enter: unexpected pa update for %#lx", va));
7303 if ((origpte & PG_MANAGED) != 0) {
7304 om = PHYS_TO_VM_PAGE(opa);
7307 * The pmap lock is sufficient to synchronize with
7308 * concurrent calls to pmap_page_test_mappings() and
7309 * pmap_ts_referenced().
7311 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7313 if ((origpte & PG_A) != 0) {
7314 pmap_invalidate_page(pmap, va);
7315 vm_page_aflag_set(om, PGA_REFERENCED);
7317 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7318 pv = pmap_pvh_remove(&om->md, pmap, va);
7320 ("pmap_enter: no PV entry for %#lx", va));
7321 if ((newpte & PG_MANAGED) == 0)
7322 free_pv_entry(pmap, pv);
7323 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7324 TAILQ_EMPTY(&om->md.pv_list) &&
7325 ((om->flags & PG_FICTITIOUS) != 0 ||
7326 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7327 vm_page_aflag_clear(om, PGA_WRITEABLE);
7330 * Since this mapping is unmanaged, assume that PG_A
7333 pmap_invalidate_page(pmap, va);
7338 * Increment the counters.
7340 if ((newpte & PG_W) != 0)
7341 pmap->pm_stats.wired_count++;
7342 pmap_resident_count_adj(pmap, 1);
7346 * Enter on the PV list if part of our managed memory.
7348 if ((newpte & PG_MANAGED) != 0) {
7350 pv = get_pv_entry(pmap, &lock);
7353 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7354 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7356 if ((newpte & PG_RW) != 0)
7357 vm_page_aflag_set(m, PGA_WRITEABLE);
7363 if ((origpte & PG_V) != 0) {
7365 origpte = pte_load_store(pte, newpte);
7366 KASSERT((origpte & PG_FRAME) == pa,
7367 ("pmap_enter: unexpected pa update for %#lx", va));
7368 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7370 if ((origpte & PG_MANAGED) != 0)
7374 * Although the PTE may still have PG_RW set, TLB
7375 * invalidation may nonetheless be required because
7376 * the PTE no longer has PG_M set.
7378 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7380 * This PTE change does not require TLB invalidation.
7384 if ((origpte & PG_A) != 0)
7385 pmap_invalidate_page(pmap, va);
7387 pte_store(pte, newpte);
7391 #if VM_NRESERVLEVEL > 0
7393 * If both the page table page and the reservation are fully
7394 * populated, then attempt promotion.
7396 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7397 (m->flags & PG_FICTITIOUS) == 0 &&
7398 vm_reserv_level_iffullpop(m) == 0)
7399 (void)pmap_promote_pde(pmap, pde, va, mpte, &lock);
7411 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7412 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7413 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7414 * "no replace", and "no reclaim" are specified.
7417 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7418 struct rwlock **lockp)
7423 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7424 PG_V = pmap_valid_bit(pmap);
7425 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
7427 if ((m->oflags & VPO_UNMANAGED) == 0)
7428 newpde |= PG_MANAGED;
7429 if ((prot & VM_PROT_EXECUTE) == 0)
7431 if (va < VM_MAXUSER_ADDRESS)
7433 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7434 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7438 * Returns true if every page table entry in the specified page table page is
7442 pmap_every_pte_zero(vm_paddr_t pa)
7444 pt_entry_t *pt_end, *pte;
7446 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7447 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7448 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7456 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7457 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7458 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7459 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7460 * page mapping already exists within the 2MB virtual address range starting
7461 * at the specified virtual address or (2) the requested 2MB page mapping is
7462 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7463 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7464 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7465 * settings are not the same across the 2MB virtual address range starting at
7466 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7467 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7468 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7471 * The parameter "m" is only used when creating a managed, writeable mapping.
7474 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7475 vm_page_t m, struct rwlock **lockp)
7477 struct spglist free;
7478 pd_entry_t oldpde, *pde;
7479 pt_entry_t PG_G, PG_RW, PG_V;
7482 KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
7483 ("pmap_enter_pde: cannot create wired user mapping"));
7484 PG_G = pmap_global_bit(pmap);
7485 PG_RW = pmap_rw_bit(pmap);
7486 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7487 ("pmap_enter_pde: newpde is missing PG_M"));
7488 PG_V = pmap_valid_bit(pmap);
7489 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7491 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7493 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7494 " in pmap %p", va, pmap);
7495 return (KERN_FAILURE);
7497 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7498 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7499 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7500 " in pmap %p", va, pmap);
7501 return (KERN_RESOURCE_SHORTAGE);
7505 * If pkru is not same for the whole pde range, return failure
7506 * and let vm_fault() cope. Check after pde allocation, since
7509 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
7510 pmap_abort_ptp(pmap, va, pdpg);
7511 return (KERN_PROTECTION_FAILURE);
7513 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
7514 newpde &= ~X86_PG_PKU_MASK;
7515 newpde |= pmap_pkru_get(pmap, va);
7519 * If there are existing mappings, either abort or remove them.
7522 if ((oldpde & PG_V) != 0) {
7523 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7524 ("pmap_enter_pde: pdpg's reference count is too low"));
7525 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7526 if ((oldpde & PG_PS) != 0) {
7530 "pmap_enter_pde: no space for va %#lx"
7531 " in pmap %p", va, pmap);
7532 return (KERN_NO_SPACE);
7533 } else if (va < VM_MAXUSER_ADDRESS ||
7534 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7538 "pmap_enter_pde: failure for va %#lx"
7539 " in pmap %p", va, pmap);
7540 return (KERN_FAILURE);
7543 /* Break the existing mapping(s). */
7545 if ((oldpde & PG_PS) != 0) {
7547 * The reference to the PD page that was acquired by
7548 * pmap_alloc_pde() ensures that it won't be freed.
7549 * However, if the PDE resulted from a promotion, then
7550 * a reserved PT page could be freed.
7552 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7553 if ((oldpde & PG_G) == 0)
7554 pmap_invalidate_pde_page(pmap, va, oldpde);
7556 pmap_delayed_invl_start();
7557 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7559 pmap_invalidate_all(pmap);
7560 pmap_delayed_invl_finish();
7562 if (va < VM_MAXUSER_ADDRESS) {
7563 vm_page_free_pages_toq(&free, true);
7564 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7567 KASSERT(SLIST_EMPTY(&free),
7568 ("pmap_enter_pde: freed kernel page table page"));
7571 * Both pmap_remove_pde() and pmap_remove_ptes() will
7572 * leave the kernel page table page zero filled.
7574 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7575 if (pmap_insert_pt_page(pmap, mt, false, false))
7576 panic("pmap_enter_pde: trie insert failed");
7580 if ((newpde & PG_MANAGED) != 0) {
7582 * Abort this mapping if its PV entry could not be created.
7584 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7586 pmap_abort_ptp(pmap, va, pdpg);
7587 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7588 " in pmap %p", va, pmap);
7589 return (KERN_RESOURCE_SHORTAGE);
7591 if ((newpde & PG_RW) != 0) {
7592 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7593 vm_page_aflag_set(mt, PGA_WRITEABLE);
7598 * Increment counters.
7600 if ((newpde & PG_W) != 0)
7601 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7602 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7605 * Map the superpage. (This is not a promoted mapping; there will not
7606 * be any lingering 4KB page mappings in the TLB.)
7608 pde_store(pde, newpde);
7610 counter_u64_add(pmap_pde_mappings, 1);
7611 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7613 return (KERN_SUCCESS);
7617 * Maps a sequence of resident pages belonging to the same object.
7618 * The sequence begins with the given page m_start. This page is
7619 * mapped at the given virtual address start. Each subsequent page is
7620 * mapped at a virtual address that is offset from start by the same
7621 * amount as the page is offset from m_start within the object. The
7622 * last page in the sequence is the page with the largest offset from
7623 * m_start that can be mapped at a virtual address less than the given
7624 * virtual address end. Not every virtual page between start and end
7625 * is mapped; only those for which a resident page exists with the
7626 * corresponding offset from m_start are mapped.
7629 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7630 vm_page_t m_start, vm_prot_t prot)
7632 struct rwlock *lock;
7635 vm_pindex_t diff, psize;
7638 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7640 psize = atop(end - start);
7645 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7646 va = start + ptoa(diff);
7647 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7648 m->psind == 1 && pmap_ps_enabled(pmap) &&
7649 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7650 KERN_SUCCESS || rv == KERN_NO_SPACE))
7651 m = &m[NBPDR / PAGE_SIZE - 1];
7653 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7655 m = TAILQ_NEXT(m, listq);
7663 * this code makes some *MAJOR* assumptions:
7664 * 1. Current pmap & pmap exists.
7667 * 4. No page table pages.
7668 * but is *MUCH* faster than pmap_enter...
7672 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7674 struct rwlock *lock;
7678 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7685 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7686 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7689 pt_entry_t newpte, *pte, PG_V;
7691 KASSERT(!VA_IS_CLEANMAP(va) ||
7692 (m->oflags & VPO_UNMANAGED) != 0,
7693 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7694 PG_V = pmap_valid_bit(pmap);
7695 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7699 * In the case that a page table page is not
7700 * resident, we are creating it here.
7702 if (va < VM_MAXUSER_ADDRESS) {
7704 vm_pindex_t ptepindex;
7707 * Calculate pagetable page index
7709 ptepindex = pmap_pde_pindex(va);
7710 if (mpte && (mpte->pindex == ptepindex)) {
7714 * If the page table page is mapped, we just increment
7715 * the hold count, and activate it. Otherwise, we
7716 * attempt to allocate a page table page, passing NULL
7717 * instead of the PV list lock pointer because we don't
7718 * intend to sleep. If this attempt fails, we don't
7719 * retry. Instead, we give up.
7721 pdpe = pmap_pdpe(pmap, va);
7722 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7723 if ((*pdpe & PG_PS) != 0)
7725 pde = pmap_pdpe_to_pde(pdpe, va);
7726 if ((*pde & PG_V) != 0) {
7727 if ((*pde & PG_PS) != 0)
7729 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7732 mpte = pmap_allocpte_alloc(pmap,
7733 ptepindex, NULL, va);
7738 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7744 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7745 pte = &pte[pmap_pte_index(va)];
7757 * Enter on the PV list if part of our managed memory.
7759 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7760 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7762 pmap_abort_ptp(pmap, va, mpte);
7767 * Increment counters
7769 pmap_resident_count_adj(pmap, 1);
7771 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7772 pmap_cache_bits(pmap, m->md.pat_mode, 0);
7773 if ((m->oflags & VPO_UNMANAGED) == 0)
7774 newpte |= PG_MANAGED;
7775 if ((prot & VM_PROT_EXECUTE) == 0)
7777 if (va < VM_MAXUSER_ADDRESS)
7778 newpte |= PG_U | pmap_pkru_get(pmap, va);
7779 pte_store(pte, newpte);
7781 #if VM_NRESERVLEVEL > 0
7783 * If both the PTP and the reservation are fully populated, then
7784 * attempt promotion.
7786 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7787 (m->flags & PG_FICTITIOUS) == 0 &&
7788 vm_reserv_level_iffullpop(m) == 0) {
7790 pde = pmap_pde(pmap, va);
7793 * If promotion succeeds, then the next call to this function
7794 * should not be given the unmapped PTP as a hint.
7796 if (pmap_promote_pde(pmap, pde, va, mpte, lockp))
7805 * Make a temporary mapping for a physical address. This is only intended
7806 * to be used for panic dumps.
7809 pmap_kenter_temporary(vm_paddr_t pa, int i)
7813 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7814 pmap_kenter(va, pa);
7815 pmap_invlpg(kernel_pmap, va);
7816 return ((void *)crashdumpmap);
7820 * This code maps large physical mmap regions into the
7821 * processor address space. Note that some shortcuts
7822 * are taken, but the code works.
7825 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7826 vm_pindex_t pindex, vm_size_t size)
7829 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7830 vm_paddr_t pa, ptepa;
7834 PG_A = pmap_accessed_bit(pmap);
7835 PG_M = pmap_modified_bit(pmap);
7836 PG_V = pmap_valid_bit(pmap);
7837 PG_RW = pmap_rw_bit(pmap);
7839 VM_OBJECT_ASSERT_WLOCKED(object);
7840 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7841 ("pmap_object_init_pt: non-device object"));
7842 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7843 if (!pmap_ps_enabled(pmap))
7845 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7847 p = vm_page_lookup(object, pindex);
7848 KASSERT(vm_page_all_valid(p),
7849 ("pmap_object_init_pt: invalid page %p", p));
7850 pat_mode = p->md.pat_mode;
7853 * Abort the mapping if the first page is not physically
7854 * aligned to a 2MB page boundary.
7856 ptepa = VM_PAGE_TO_PHYS(p);
7857 if (ptepa & (NBPDR - 1))
7861 * Skip the first page. Abort the mapping if the rest of
7862 * the pages are not physically contiguous or have differing
7863 * memory attributes.
7865 p = TAILQ_NEXT(p, listq);
7866 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7868 KASSERT(vm_page_all_valid(p),
7869 ("pmap_object_init_pt: invalid page %p", p));
7870 if (pa != VM_PAGE_TO_PHYS(p) ||
7871 pat_mode != p->md.pat_mode)
7873 p = TAILQ_NEXT(p, listq);
7877 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7878 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7879 * will not affect the termination of this loop.
7882 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
7883 pa < ptepa + size; pa += NBPDR) {
7884 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7887 * The creation of mappings below is only an
7888 * optimization. If a page directory page
7889 * cannot be allocated without blocking,
7890 * continue on to the next mapping rather than
7896 if ((*pde & PG_V) == 0) {
7897 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7898 PG_U | PG_RW | PG_V);
7899 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7900 counter_u64_add(pmap_pde_mappings, 1);
7902 /* Continue on if the PDE is already valid. */
7904 KASSERT(pdpg->ref_count > 0,
7905 ("pmap_object_init_pt: missing reference "
7906 "to page directory page, va: 0x%lx", addr));
7915 * Clear the wired attribute from the mappings for the specified range of
7916 * addresses in the given pmap. Every valid mapping within that range
7917 * must have the wired attribute set. In contrast, invalid mappings
7918 * cannot have the wired attribute set, so they are ignored.
7920 * The wired attribute of the page table entry is not a hardware
7921 * feature, so there is no need to invalidate any TLB entries.
7922 * Since pmap_demote_pde() for the wired entry must never fail,
7923 * pmap_delayed_invl_start()/finish() calls around the
7924 * function are not needed.
7927 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7929 vm_offset_t va_next;
7930 pml4_entry_t *pml4e;
7933 pt_entry_t *pte, PG_V, PG_G __diagused;
7935 PG_V = pmap_valid_bit(pmap);
7936 PG_G = pmap_global_bit(pmap);
7938 for (; sva < eva; sva = va_next) {
7939 pml4e = pmap_pml4e(pmap, sva);
7940 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7941 va_next = (sva + NBPML4) & ~PML4MASK;
7947 va_next = (sva + NBPDP) & ~PDPMASK;
7950 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7951 if ((*pdpe & PG_V) == 0)
7953 if ((*pdpe & PG_PS) != 0) {
7954 KASSERT(va_next <= eva,
7955 ("partial update of non-transparent 1G mapping "
7956 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
7957 *pdpe, sva, eva, va_next));
7958 MPASS(pmap != kernel_pmap); /* XXXKIB */
7959 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
7960 atomic_clear_long(pdpe, PG_W);
7961 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
7965 va_next = (sva + NBPDR) & ~PDRMASK;
7968 pde = pmap_pdpe_to_pde(pdpe, sva);
7969 if ((*pde & PG_V) == 0)
7971 if ((*pde & PG_PS) != 0) {
7972 if ((*pde & PG_W) == 0)
7973 panic("pmap_unwire: pde %#jx is missing PG_W",
7977 * Are we unwiring the entire large page? If not,
7978 * demote the mapping and fall through.
7980 if (sva + NBPDR == va_next && eva >= va_next) {
7981 atomic_clear_long(pde, PG_W);
7982 pmap->pm_stats.wired_count -= NBPDR /
7985 } else if (!pmap_demote_pde(pmap, pde, sva))
7986 panic("pmap_unwire: demotion failed");
7990 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
7992 if ((*pte & PG_V) == 0)
7994 if ((*pte & PG_W) == 0)
7995 panic("pmap_unwire: pte %#jx is missing PG_W",
7999 * PG_W must be cleared atomically. Although the pmap
8000 * lock synchronizes access to PG_W, another processor
8001 * could be setting PG_M and/or PG_A concurrently.
8003 atomic_clear_long(pte, PG_W);
8004 pmap->pm_stats.wired_count--;
8011 * Copy the range specified by src_addr/len
8012 * from the source map to the range dst_addr/len
8013 * in the destination map.
8015 * This routine is only advisory and need not do anything.
8018 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
8019 vm_offset_t src_addr)
8021 struct rwlock *lock;
8022 pml4_entry_t *pml4e;
8024 pd_entry_t *pde, srcptepaddr;
8025 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
8026 vm_offset_t addr, end_addr, va_next;
8027 vm_page_t dst_pdpg, dstmpte, srcmpte;
8029 if (dst_addr != src_addr)
8032 if (dst_pmap->pm_type != src_pmap->pm_type)
8036 * EPT page table entries that require emulation of A/D bits are
8037 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
8038 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
8039 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
8040 * implementations flag an EPT misconfiguration for exec-only
8041 * mappings we skip this function entirely for emulated pmaps.
8043 if (pmap_emulate_ad_bits(dst_pmap))
8046 end_addr = src_addr + len;
8048 if (dst_pmap < src_pmap) {
8049 PMAP_LOCK(dst_pmap);
8050 PMAP_LOCK(src_pmap);
8052 PMAP_LOCK(src_pmap);
8053 PMAP_LOCK(dst_pmap);
8056 PG_A = pmap_accessed_bit(dst_pmap);
8057 PG_M = pmap_modified_bit(dst_pmap);
8058 PG_V = pmap_valid_bit(dst_pmap);
8060 for (addr = src_addr; addr < end_addr; addr = va_next) {
8061 KASSERT(addr < UPT_MIN_ADDRESS,
8062 ("pmap_copy: invalid to pmap_copy page tables"));
8064 pml4e = pmap_pml4e(src_pmap, addr);
8065 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8066 va_next = (addr + NBPML4) & ~PML4MASK;
8072 va_next = (addr + NBPDP) & ~PDPMASK;
8075 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
8076 if ((*pdpe & PG_V) == 0)
8078 if ((*pdpe & PG_PS) != 0) {
8079 KASSERT(va_next <= end_addr,
8080 ("partial update of non-transparent 1G mapping "
8081 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8082 *pdpe, addr, end_addr, va_next));
8083 MPASS((addr & PDPMASK) == 0);
8084 MPASS((*pdpe & PG_MANAGED) == 0);
8085 srcptepaddr = *pdpe;
8086 pdpe = pmap_pdpe(dst_pmap, addr);
8088 if (pmap_allocpte_alloc(dst_pmap,
8089 pmap_pml4e_pindex(addr), NULL, addr) ==
8092 pdpe = pmap_pdpe(dst_pmap, addr);
8094 pml4e = pmap_pml4e(dst_pmap, addr);
8095 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8096 dst_pdpg->ref_count++;
8099 ("1G mapping present in dst pmap "
8100 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8101 *pdpe, addr, end_addr, va_next));
8102 *pdpe = srcptepaddr & ~PG_W;
8103 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8107 va_next = (addr + NBPDR) & ~PDRMASK;
8111 pde = pmap_pdpe_to_pde(pdpe, addr);
8113 if (srcptepaddr == 0)
8116 if (srcptepaddr & PG_PS) {
8118 * We can only virtual copy whole superpages.
8120 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8122 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8125 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8126 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8127 PMAP_ENTER_NORECLAIM, &lock))) {
8129 * We leave the dirty bit unchanged because
8130 * managed read/write superpage mappings are
8131 * required to be dirty. However, managed
8132 * superpage mappings are not required to
8133 * have their accessed bit set, so we clear
8134 * it because we don't know if this mapping
8137 srcptepaddr &= ~PG_W;
8138 if ((srcptepaddr & PG_MANAGED) != 0)
8139 srcptepaddr &= ~PG_A;
8141 pmap_resident_count_adj(dst_pmap, NBPDR /
8143 counter_u64_add(pmap_pde_mappings, 1);
8145 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8149 srcptepaddr &= PG_FRAME;
8150 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8151 KASSERT(srcmpte->ref_count > 0,
8152 ("pmap_copy: source page table page is unused"));
8154 if (va_next > end_addr)
8157 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8158 src_pte = &src_pte[pmap_pte_index(addr)];
8160 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8164 * We only virtual copy managed pages.
8166 if ((ptetemp & PG_MANAGED) == 0)
8169 if (dstmpte != NULL) {
8170 KASSERT(dstmpte->pindex ==
8171 pmap_pde_pindex(addr),
8172 ("dstmpte pindex/addr mismatch"));
8173 dstmpte->ref_count++;
8174 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8177 dst_pte = (pt_entry_t *)
8178 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8179 dst_pte = &dst_pte[pmap_pte_index(addr)];
8180 if (*dst_pte == 0 &&
8181 pmap_try_insert_pv_entry(dst_pmap, addr,
8182 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8184 * Clear the wired, modified, and accessed
8185 * (referenced) bits during the copy.
8187 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8188 pmap_resident_count_adj(dst_pmap, 1);
8190 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8193 /* Have we copied all of the valid mappings? */
8194 if (dstmpte->ref_count >= srcmpte->ref_count)
8201 PMAP_UNLOCK(src_pmap);
8202 PMAP_UNLOCK(dst_pmap);
8206 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8210 if (dst_pmap->pm_type != src_pmap->pm_type ||
8211 dst_pmap->pm_type != PT_X86 ||
8212 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8215 if (dst_pmap < src_pmap) {
8216 PMAP_LOCK(dst_pmap);
8217 PMAP_LOCK(src_pmap);
8219 PMAP_LOCK(src_pmap);
8220 PMAP_LOCK(dst_pmap);
8222 error = pmap_pkru_copy(dst_pmap, src_pmap);
8223 /* Clean up partial copy on failure due to no memory. */
8224 if (error == ENOMEM)
8225 pmap_pkru_deassign_all(dst_pmap);
8226 PMAP_UNLOCK(src_pmap);
8227 PMAP_UNLOCK(dst_pmap);
8228 if (error != ENOMEM)
8236 * Zero the specified hardware page.
8239 pmap_zero_page(vm_page_t m)
8243 #ifdef TSLOG_PAGEZERO
8246 va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8247 pagezero((void *)va);
8248 #ifdef TSLOG_PAGEZERO
8254 * Zero an area within a single hardware page. off and size must not
8255 * cover an area beyond a single hardware page.
8258 pmap_zero_page_area(vm_page_t m, int off, int size)
8260 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8262 if (off == 0 && size == PAGE_SIZE)
8263 pagezero((void *)va);
8265 bzero((char *)va + off, size);
8269 * Copy 1 specified hardware page to another.
8272 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8274 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8275 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8277 pagecopy((void *)src, (void *)dst);
8280 int unmapped_buf_allowed = 1;
8283 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8284 vm_offset_t b_offset, int xfersize)
8288 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8292 while (xfersize > 0) {
8293 a_pg_offset = a_offset & PAGE_MASK;
8294 pages[0] = ma[a_offset >> PAGE_SHIFT];
8295 b_pg_offset = b_offset & PAGE_MASK;
8296 pages[1] = mb[b_offset >> PAGE_SHIFT];
8297 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8298 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8299 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
8300 a_cp = (char *)vaddr[0] + a_pg_offset;
8301 b_cp = (char *)vaddr[1] + b_pg_offset;
8302 bcopy(a_cp, b_cp, cnt);
8303 if (__predict_false(mapped))
8304 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
8312 * Returns true if the pmap's pv is one of the first
8313 * 16 pvs linked to from this page. This count may
8314 * be changed upwards or downwards in the future; it
8315 * is only necessary that true be returned for a small
8316 * subset of pmaps for proper page aging.
8319 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8321 struct md_page *pvh;
8322 struct rwlock *lock;
8327 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8328 ("pmap_page_exists_quick: page %p is not managed", m));
8330 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8332 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8333 if (PV_PMAP(pv) == pmap) {
8341 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8342 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8343 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8344 if (PV_PMAP(pv) == pmap) {
8358 * pmap_page_wired_mappings:
8360 * Return the number of managed mappings to the given physical page
8364 pmap_page_wired_mappings(vm_page_t m)
8366 struct rwlock *lock;
8367 struct md_page *pvh;
8371 int count, md_gen, pvh_gen;
8373 if ((m->oflags & VPO_UNMANAGED) != 0)
8375 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8379 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8381 if (!PMAP_TRYLOCK(pmap)) {
8382 md_gen = m->md.pv_gen;
8386 if (md_gen != m->md.pv_gen) {
8391 pte = pmap_pte(pmap, pv->pv_va);
8392 if ((*pte & PG_W) != 0)
8396 if ((m->flags & PG_FICTITIOUS) == 0) {
8397 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8398 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8400 if (!PMAP_TRYLOCK(pmap)) {
8401 md_gen = m->md.pv_gen;
8402 pvh_gen = pvh->pv_gen;
8406 if (md_gen != m->md.pv_gen ||
8407 pvh_gen != pvh->pv_gen) {
8412 pte = pmap_pde(pmap, pv->pv_va);
8413 if ((*pte & PG_W) != 0)
8423 * Returns TRUE if the given page is mapped individually or as part of
8424 * a 2mpage. Otherwise, returns FALSE.
8427 pmap_page_is_mapped(vm_page_t m)
8429 struct rwlock *lock;
8432 if ((m->oflags & VPO_UNMANAGED) != 0)
8434 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8436 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8437 ((m->flags & PG_FICTITIOUS) == 0 &&
8438 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8444 * Destroy all managed, non-wired mappings in the given user-space
8445 * pmap. This pmap cannot be active on any processor besides the
8448 * This function cannot be applied to the kernel pmap. Moreover, it
8449 * is not intended for general use. It is only to be used during
8450 * process termination. Consequently, it can be implemented in ways
8451 * that make it faster than pmap_remove(). First, it can more quickly
8452 * destroy mappings by iterating over the pmap's collection of PV
8453 * entries, rather than searching the page table. Second, it doesn't
8454 * have to test and clear the page table entries atomically, because
8455 * no processor is currently accessing the user address space. In
8456 * particular, a page table entry's dirty bit won't change state once
8457 * this function starts.
8459 * Although this function destroys all of the pmap's managed,
8460 * non-wired mappings, it can delay and batch the invalidation of TLB
8461 * entries without calling pmap_delayed_invl_start() and
8462 * pmap_delayed_invl_finish(). Because the pmap is not active on
8463 * any other processor, none of these TLB entries will ever be used
8464 * before their eventual invalidation. Consequently, there is no need
8465 * for either pmap_remove_all() or pmap_remove_write() to wait for
8466 * that eventual TLB invalidation.
8469 pmap_remove_pages(pmap_t pmap)
8472 pt_entry_t *pte, tpte;
8473 pt_entry_t PG_M, PG_RW, PG_V;
8474 struct spglist free;
8475 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8476 vm_page_t m, mpte, mt;
8478 struct md_page *pvh;
8479 struct pv_chunk *pc, *npc;
8480 struct rwlock *lock;
8482 uint64_t inuse, bitmask;
8483 int allfree, field, i, idx;
8487 boolean_t superpage;
8491 * Assert that the given pmap is only active on the current
8492 * CPU. Unfortunately, we cannot block another CPU from
8493 * activating the pmap while this function is executing.
8495 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8498 cpuset_t other_cpus;
8500 other_cpus = all_cpus;
8502 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8503 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8505 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8510 PG_M = pmap_modified_bit(pmap);
8511 PG_V = pmap_valid_bit(pmap);
8512 PG_RW = pmap_rw_bit(pmap);
8514 for (i = 0; i < PMAP_MEMDOM; i++)
8515 TAILQ_INIT(&free_chunks[i]);
8518 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8523 for (field = 0; field < _NPCM; field++) {
8524 inuse = ~pc->pc_map[field] & pc_freemask[field];
8525 while (inuse != 0) {
8527 bitmask = 1UL << bit;
8528 idx = field * 64 + bit;
8529 pv = &pc->pc_pventry[idx];
8532 pte = pmap_pdpe(pmap, pv->pv_va);
8534 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8536 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8539 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8541 pte = &pte[pmap_pte_index(pv->pv_va)];
8545 * Keep track whether 'tpte' is a
8546 * superpage explicitly instead of
8547 * relying on PG_PS being set.
8549 * This is because PG_PS is numerically
8550 * identical to PG_PTE_PAT and thus a
8551 * regular page could be mistaken for
8557 if ((tpte & PG_V) == 0) {
8558 panic("bad pte va %lx pte %lx",
8563 * We cannot remove wired pages from a process' mapping at this time
8571 pc->pc_map[field] |= bitmask;
8574 * Because this pmap is not active on other
8575 * processors, the dirty bit cannot have
8576 * changed state since we last loaded pte.
8581 pa = tpte & PG_PS_FRAME;
8583 pa = tpte & PG_FRAME;
8585 m = PHYS_TO_VM_PAGE(pa);
8586 KASSERT(m->phys_addr == pa,
8587 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8588 m, (uintmax_t)m->phys_addr,
8591 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8592 m < &vm_page_array[vm_page_array_size],
8593 ("pmap_remove_pages: bad tpte %#jx",
8597 * Update the vm_page_t clean/reference bits.
8599 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8601 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8607 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8610 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8611 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8612 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8614 if (TAILQ_EMPTY(&pvh->pv_list)) {
8615 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8616 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8617 TAILQ_EMPTY(&mt->md.pv_list))
8618 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8620 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8622 KASSERT(vm_page_any_valid(mpte),
8623 ("pmap_remove_pages: pte page not promoted"));
8624 pmap_pt_page_count_adj(pmap, -1);
8625 KASSERT(mpte->ref_count == NPTEPG,
8626 ("pmap_remove_pages: pte page reference count error"));
8627 mpte->ref_count = 0;
8628 pmap_add_delayed_free_list(mpte, &free, FALSE);
8631 pmap_resident_count_adj(pmap, -1);
8632 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8634 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8635 TAILQ_EMPTY(&m->md.pv_list) &&
8636 (m->flags & PG_FICTITIOUS) == 0) {
8637 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8638 if (TAILQ_EMPTY(&pvh->pv_list))
8639 vm_page_aflag_clear(m, PGA_WRITEABLE);
8642 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8648 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8649 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8650 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8652 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8653 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8658 pmap_invalidate_all(pmap);
8659 pmap_pkru_deassign_all(pmap);
8660 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8662 vm_page_free_pages_toq(&free, true);
8666 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
8668 struct rwlock *lock;
8670 struct md_page *pvh;
8671 pt_entry_t *pte, mask;
8672 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8674 int md_gen, pvh_gen;
8678 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8681 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8683 if (!PMAP_TRYLOCK(pmap)) {
8684 md_gen = m->md.pv_gen;
8688 if (md_gen != m->md.pv_gen) {
8693 pte = pmap_pte(pmap, pv->pv_va);
8696 PG_M = pmap_modified_bit(pmap);
8697 PG_RW = pmap_rw_bit(pmap);
8698 mask |= PG_RW | PG_M;
8701 PG_A = pmap_accessed_bit(pmap);
8702 PG_V = pmap_valid_bit(pmap);
8703 mask |= PG_V | PG_A;
8705 rv = (*pte & mask) == mask;
8710 if ((m->flags & PG_FICTITIOUS) == 0) {
8711 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8712 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8714 if (!PMAP_TRYLOCK(pmap)) {
8715 md_gen = m->md.pv_gen;
8716 pvh_gen = pvh->pv_gen;
8720 if (md_gen != m->md.pv_gen ||
8721 pvh_gen != pvh->pv_gen) {
8726 pte = pmap_pde(pmap, pv->pv_va);
8729 PG_M = pmap_modified_bit(pmap);
8730 PG_RW = pmap_rw_bit(pmap);
8731 mask |= PG_RW | PG_M;
8734 PG_A = pmap_accessed_bit(pmap);
8735 PG_V = pmap_valid_bit(pmap);
8736 mask |= PG_V | PG_A;
8738 rv = (*pte & mask) == mask;
8752 * Return whether or not the specified physical page was modified
8753 * in any physical maps.
8756 pmap_is_modified(vm_page_t m)
8759 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8760 ("pmap_is_modified: page %p is not managed", m));
8763 * If the page is not busied then this check is racy.
8765 if (!pmap_page_is_write_mapped(m))
8767 return (pmap_page_test_mappings(m, FALSE, TRUE));
8771 * pmap_is_prefaultable:
8773 * Return whether or not the specified virtual address is eligible
8777 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8780 pt_entry_t *pte, PG_V;
8783 PG_V = pmap_valid_bit(pmap);
8786 * Return TRUE if and only if the PTE for the specified virtual
8787 * address is allocated but invalid.
8791 pde = pmap_pde(pmap, addr);
8792 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8793 pte = pmap_pde_to_pte(pde, addr);
8794 rv = (*pte & PG_V) == 0;
8801 * pmap_is_referenced:
8803 * Return whether or not the specified physical page was referenced
8804 * in any physical maps.
8807 pmap_is_referenced(vm_page_t m)
8810 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8811 ("pmap_is_referenced: page %p is not managed", m));
8812 return (pmap_page_test_mappings(m, TRUE, FALSE));
8816 * Clear the write and modified bits in each of the given page's mappings.
8819 pmap_remove_write(vm_page_t m)
8821 struct md_page *pvh;
8823 struct rwlock *lock;
8824 pv_entry_t next_pv, pv;
8826 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8828 int pvh_gen, md_gen;
8830 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8831 ("pmap_remove_write: page %p is not managed", m));
8833 vm_page_assert_busied(m);
8834 if (!pmap_page_is_write_mapped(m))
8837 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8838 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8839 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8842 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8844 if (!PMAP_TRYLOCK(pmap)) {
8845 pvh_gen = pvh->pv_gen;
8849 if (pvh_gen != pvh->pv_gen) {
8854 PG_RW = pmap_rw_bit(pmap);
8856 pde = pmap_pde(pmap, va);
8857 if ((*pde & PG_RW) != 0)
8858 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8859 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8860 ("inconsistent pv lock %p %p for page %p",
8861 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8864 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8866 if (!PMAP_TRYLOCK(pmap)) {
8867 pvh_gen = pvh->pv_gen;
8868 md_gen = m->md.pv_gen;
8872 if (pvh_gen != pvh->pv_gen ||
8873 md_gen != m->md.pv_gen) {
8878 PG_M = pmap_modified_bit(pmap);
8879 PG_RW = pmap_rw_bit(pmap);
8880 pde = pmap_pde(pmap, pv->pv_va);
8881 KASSERT((*pde & PG_PS) == 0,
8882 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8884 pte = pmap_pde_to_pte(pde, pv->pv_va);
8886 if (oldpte & PG_RW) {
8887 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8890 if ((oldpte & PG_M) != 0)
8892 pmap_invalidate_page(pmap, pv->pv_va);
8897 vm_page_aflag_clear(m, PGA_WRITEABLE);
8898 pmap_delayed_invl_wait(m);
8902 * pmap_ts_referenced:
8904 * Return a count of reference bits for a page, clearing those bits.
8905 * It is not necessary for every reference bit to be cleared, but it
8906 * is necessary that 0 only be returned when there are truly no
8907 * reference bits set.
8909 * As an optimization, update the page's dirty field if a modified bit is
8910 * found while counting reference bits. This opportunistic update can be
8911 * performed at low cost and can eliminate the need for some future calls
8912 * to pmap_is_modified(). However, since this function stops after
8913 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8914 * dirty pages. Those dirty pages will only be detected by a future call
8915 * to pmap_is_modified().
8917 * A DI block is not needed within this function, because
8918 * invalidations are performed before the PV list lock is
8922 pmap_ts_referenced(vm_page_t m)
8924 struct md_page *pvh;
8927 struct rwlock *lock;
8928 pd_entry_t oldpde, *pde;
8929 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8932 int cleared, md_gen, not_cleared, pvh_gen;
8933 struct spglist free;
8936 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8937 ("pmap_ts_referenced: page %p is not managed", m));
8940 pa = VM_PAGE_TO_PHYS(m);
8941 lock = PHYS_TO_PV_LIST_LOCK(pa);
8942 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8946 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
8947 goto small_mappings;
8953 if (!PMAP_TRYLOCK(pmap)) {
8954 pvh_gen = pvh->pv_gen;
8958 if (pvh_gen != pvh->pv_gen) {
8963 PG_A = pmap_accessed_bit(pmap);
8964 PG_M = pmap_modified_bit(pmap);
8965 PG_RW = pmap_rw_bit(pmap);
8967 pde = pmap_pde(pmap, pv->pv_va);
8969 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8971 * Although "oldpde" is mapping a 2MB page, because
8972 * this function is called at a 4KB page granularity,
8973 * we only update the 4KB page under test.
8977 if ((oldpde & PG_A) != 0) {
8979 * Since this reference bit is shared by 512 4KB
8980 * pages, it should not be cleared every time it is
8981 * tested. Apply a simple "hash" function on the
8982 * physical page number, the virtual superpage number,
8983 * and the pmap address to select one 4KB page out of
8984 * the 512 on which testing the reference bit will
8985 * result in clearing that reference bit. This
8986 * function is designed to avoid the selection of the
8987 * same 4KB page for every 2MB page mapping.
8989 * On demotion, a mapping that hasn't been referenced
8990 * is simply destroyed. To avoid the possibility of a
8991 * subsequent page fault on a demoted wired mapping,
8992 * always leave its reference bit set. Moreover,
8993 * since the superpage is wired, the current state of
8994 * its reference bit won't affect page replacement.
8996 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
8997 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
8998 (oldpde & PG_W) == 0) {
8999 if (safe_to_clear_referenced(pmap, oldpde)) {
9000 atomic_clear_long(pde, PG_A);
9001 pmap_invalidate_page(pmap, pv->pv_va);
9003 } else if (pmap_demote_pde_locked(pmap, pde,
9004 pv->pv_va, &lock)) {
9006 * Remove the mapping to a single page
9007 * so that a subsequent access may
9008 * repromote. Since the underlying
9009 * page table page is fully populated,
9010 * this removal never frees a page
9014 va += VM_PAGE_TO_PHYS(m) - (oldpde &
9016 pte = pmap_pde_to_pte(pde, va);
9017 pmap_remove_pte(pmap, pte, va, *pde,
9019 pmap_invalidate_page(pmap, va);
9025 * The superpage mapping was removed
9026 * entirely and therefore 'pv' is no
9034 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9035 ("inconsistent pv lock %p %p for page %p",
9036 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9041 /* Rotate the PV list if it has more than one entry. */
9042 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9043 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
9044 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
9047 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
9049 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9051 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9058 if (!PMAP_TRYLOCK(pmap)) {
9059 pvh_gen = pvh->pv_gen;
9060 md_gen = m->md.pv_gen;
9064 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9069 PG_A = pmap_accessed_bit(pmap);
9070 PG_M = pmap_modified_bit(pmap);
9071 PG_RW = pmap_rw_bit(pmap);
9072 pde = pmap_pde(pmap, pv->pv_va);
9073 KASSERT((*pde & PG_PS) == 0,
9074 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9076 pte = pmap_pde_to_pte(pde, pv->pv_va);
9077 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9079 if ((*pte & PG_A) != 0) {
9080 if (safe_to_clear_referenced(pmap, *pte)) {
9081 atomic_clear_long(pte, PG_A);
9082 pmap_invalidate_page(pmap, pv->pv_va);
9084 } else if ((*pte & PG_W) == 0) {
9086 * Wired pages cannot be paged out so
9087 * doing accessed bit emulation for
9088 * them is wasted effort. We do the
9089 * hard work for unwired pages only.
9091 pmap_remove_pte(pmap, pte, pv->pv_va,
9092 *pde, &free, &lock);
9093 pmap_invalidate_page(pmap, pv->pv_va);
9098 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9099 ("inconsistent pv lock %p %p for page %p",
9100 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9105 /* Rotate the PV list if it has more than one entry. */
9106 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9107 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9108 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9111 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9112 not_cleared < PMAP_TS_REFERENCED_MAX);
9115 vm_page_free_pages_toq(&free, true);
9116 return (cleared + not_cleared);
9120 * Apply the given advice to the specified range of addresses within the
9121 * given pmap. Depending on the advice, clear the referenced and/or
9122 * modified flags in each mapping and set the mapped page's dirty field.
9125 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9127 struct rwlock *lock;
9128 pml4_entry_t *pml4e;
9130 pd_entry_t oldpde, *pde;
9131 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9132 vm_offset_t va, va_next;
9136 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9140 * A/D bit emulation requires an alternate code path when clearing
9141 * the modified and accessed bits below. Since this function is
9142 * advisory in nature we skip it entirely for pmaps that require
9143 * A/D bit emulation.
9145 if (pmap_emulate_ad_bits(pmap))
9148 PG_A = pmap_accessed_bit(pmap);
9149 PG_G = pmap_global_bit(pmap);
9150 PG_M = pmap_modified_bit(pmap);
9151 PG_V = pmap_valid_bit(pmap);
9152 PG_RW = pmap_rw_bit(pmap);
9154 pmap_delayed_invl_start();
9156 for (; sva < eva; sva = va_next) {
9157 pml4e = pmap_pml4e(pmap, sva);
9158 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9159 va_next = (sva + NBPML4) & ~PML4MASK;
9165 va_next = (sva + NBPDP) & ~PDPMASK;
9168 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9169 if ((*pdpe & PG_V) == 0)
9171 if ((*pdpe & PG_PS) != 0)
9174 va_next = (sva + NBPDR) & ~PDRMASK;
9177 pde = pmap_pdpe_to_pde(pdpe, sva);
9179 if ((oldpde & PG_V) == 0)
9181 else if ((oldpde & PG_PS) != 0) {
9182 if ((oldpde & PG_MANAGED) == 0)
9185 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9190 * The large page mapping was destroyed.
9196 * Unless the page mappings are wired, remove the
9197 * mapping to a single page so that a subsequent
9198 * access may repromote. Choosing the last page
9199 * within the address range [sva, min(va_next, eva))
9200 * generally results in more repromotions. Since the
9201 * underlying page table page is fully populated, this
9202 * removal never frees a page table page.
9204 if ((oldpde & PG_W) == 0) {
9210 ("pmap_advise: no address gap"));
9211 pte = pmap_pde_to_pte(pde, va);
9212 KASSERT((*pte & PG_V) != 0,
9213 ("pmap_advise: invalid PTE"));
9214 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9224 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9226 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9228 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9229 if (advice == MADV_DONTNEED) {
9231 * Future calls to pmap_is_modified()
9232 * can be avoided by making the page
9235 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9238 atomic_clear_long(pte, PG_M | PG_A);
9239 } else if ((*pte & PG_A) != 0)
9240 atomic_clear_long(pte, PG_A);
9244 if ((*pte & PG_G) != 0) {
9251 if (va != va_next) {
9252 pmap_invalidate_range(pmap, va, sva);
9257 pmap_invalidate_range(pmap, va, sva);
9260 pmap_invalidate_all(pmap);
9262 pmap_delayed_invl_finish();
9266 * Clear the modify bits on the specified physical page.
9269 pmap_clear_modify(vm_page_t m)
9271 struct md_page *pvh;
9273 pv_entry_t next_pv, pv;
9274 pd_entry_t oldpde, *pde;
9275 pt_entry_t *pte, PG_M, PG_RW;
9276 struct rwlock *lock;
9278 int md_gen, pvh_gen;
9280 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9281 ("pmap_clear_modify: page %p is not managed", m));
9282 vm_page_assert_busied(m);
9284 if (!pmap_page_is_write_mapped(m))
9286 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9287 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9288 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9291 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9293 if (!PMAP_TRYLOCK(pmap)) {
9294 pvh_gen = pvh->pv_gen;
9298 if (pvh_gen != pvh->pv_gen) {
9303 PG_M = pmap_modified_bit(pmap);
9304 PG_RW = pmap_rw_bit(pmap);
9306 pde = pmap_pde(pmap, va);
9308 /* If oldpde has PG_RW set, then it also has PG_M set. */
9309 if ((oldpde & PG_RW) != 0 &&
9310 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9311 (oldpde & PG_W) == 0) {
9313 * Write protect the mapping to a single page so that
9314 * a subsequent write access may repromote.
9316 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9317 pte = pmap_pde_to_pte(pde, va);
9318 atomic_clear_long(pte, PG_M | PG_RW);
9320 pmap_invalidate_page(pmap, va);
9324 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9326 if (!PMAP_TRYLOCK(pmap)) {
9327 md_gen = m->md.pv_gen;
9328 pvh_gen = pvh->pv_gen;
9332 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9337 PG_M = pmap_modified_bit(pmap);
9338 PG_RW = pmap_rw_bit(pmap);
9339 pde = pmap_pde(pmap, pv->pv_va);
9340 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9341 " a 2mpage in page %p's pv list", m));
9342 pte = pmap_pde_to_pte(pde, pv->pv_va);
9343 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9344 atomic_clear_long(pte, PG_M);
9345 pmap_invalidate_page(pmap, pv->pv_va);
9353 * Miscellaneous support routines follow
9356 /* Adjust the properties for a leaf page table entry. */
9357 static __inline void
9358 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9362 opte = *(u_long *)pte;
9364 npte = opte & ~mask;
9366 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9371 * Map a set of physical memory pages into the kernel virtual
9372 * address space. Return a pointer to where it is mapped. This
9373 * routine is intended to be used for mapping device memory,
9377 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9379 struct pmap_preinit_mapping *ppim;
9380 vm_offset_t va, offset;
9384 offset = pa & PAGE_MASK;
9385 size = round_page(offset + size);
9386 pa = trunc_page(pa);
9388 if (!pmap_initialized) {
9390 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9391 ppim = pmap_preinit_mapping + i;
9392 if (ppim->va == 0) {
9396 ppim->va = virtual_avail;
9397 virtual_avail += size;
9403 panic("%s: too many preinit mappings", __func__);
9406 * If we have a preinit mapping, re-use it.
9408 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9409 ppim = pmap_preinit_mapping + i;
9410 if (ppim->pa == pa && ppim->sz == size &&
9411 (ppim->mode == mode ||
9412 (flags & MAPDEV_SETATTR) == 0))
9413 return ((void *)(ppim->va + offset));
9416 * If the specified range of physical addresses fits within
9417 * the direct map window, use the direct map.
9419 if (pa < dmaplimit && pa + size <= dmaplimit) {
9420 va = PHYS_TO_DMAP(pa);
9421 if ((flags & MAPDEV_SETATTR) != 0) {
9422 PMAP_LOCK(kernel_pmap);
9423 i = pmap_change_props_locked(va, size,
9424 PROT_NONE, mode, flags);
9425 PMAP_UNLOCK(kernel_pmap);
9429 return ((void *)(va + offset));
9431 va = kva_alloc(size);
9433 panic("%s: Couldn't allocate KVA", __func__);
9435 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9436 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9437 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9438 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9439 pmap_invalidate_cache_range(va, va + tmpsize);
9440 return ((void *)(va + offset));
9444 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9447 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9452 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9455 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9459 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9462 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9467 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9470 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9471 MAPDEV_FLUSHCACHE));
9475 pmap_unmapdev(void *p, vm_size_t size)
9477 struct pmap_preinit_mapping *ppim;
9478 vm_offset_t offset, va;
9481 va = (vm_offset_t)p;
9483 /* If we gave a direct map region in pmap_mapdev, do nothing */
9484 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9486 offset = va & PAGE_MASK;
9487 size = round_page(offset + size);
9488 va = trunc_page(va);
9489 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9490 ppim = pmap_preinit_mapping + i;
9491 if (ppim->va == va && ppim->sz == size) {
9492 if (pmap_initialized)
9498 if (va + size == virtual_avail)
9503 if (pmap_initialized) {
9504 pmap_qremove(va, atop(size));
9510 * Tries to demote a 1GB page mapping.
9513 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9515 pdp_entry_t newpdpe, oldpdpe;
9516 pd_entry_t *firstpde, newpde, *pde;
9517 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9521 PG_A = pmap_accessed_bit(pmap);
9522 PG_M = pmap_modified_bit(pmap);
9523 PG_V = pmap_valid_bit(pmap);
9524 PG_RW = pmap_rw_bit(pmap);
9526 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9528 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9529 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9530 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9531 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9533 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9534 " in pmap %p", va, pmap);
9537 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9538 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9539 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9540 KASSERT((oldpdpe & PG_A) != 0,
9541 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9542 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9543 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9547 * Initialize the page directory page.
9549 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9555 * Demote the mapping.
9560 * Invalidate a stale recursive mapping of the page directory page.
9562 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9564 counter_u64_add(pmap_pdpe_demotions, 1);
9565 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9566 " in pmap %p", va, pmap);
9571 * Sets the memory attribute for the specified page.
9574 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9577 m->md.pat_mode = ma;
9580 * If "m" is a normal page, update its direct mapping. This update
9581 * can be relied upon to perform any cache operations that are
9582 * required for data coherence.
9584 if ((m->flags & PG_FICTITIOUS) == 0 &&
9585 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9587 panic("memory attribute change on the direct map failed");
9591 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9595 m->md.pat_mode = ma;
9597 if ((m->flags & PG_FICTITIOUS) != 0)
9599 PMAP_LOCK(kernel_pmap);
9600 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9601 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9602 PMAP_UNLOCK(kernel_pmap);
9604 panic("memory attribute change on the direct map failed");
9608 * Changes the specified virtual address range's memory type to that given by
9609 * the parameter "mode". The specified virtual address range must be
9610 * completely contained within either the direct map or the kernel map. If
9611 * the virtual address range is contained within the kernel map, then the
9612 * memory type for each of the corresponding ranges of the direct map is also
9613 * changed. (The corresponding ranges of the direct map are those ranges that
9614 * map the same physical pages as the specified virtual address range.) These
9615 * changes to the direct map are necessary because Intel describes the
9616 * behavior of their processors as "undefined" if two or more mappings to the
9617 * same physical page have different memory types.
9619 * Returns zero if the change completed successfully, and either EINVAL or
9620 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9621 * of the virtual address range was not mapped, and ENOMEM is returned if
9622 * there was insufficient memory available to complete the change. In the
9623 * latter case, the memory type may have been changed on some part of the
9624 * virtual address range or the direct map.
9627 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9631 PMAP_LOCK(kernel_pmap);
9632 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9634 PMAP_UNLOCK(kernel_pmap);
9639 * Changes the specified virtual address range's protections to those
9640 * specified by "prot". Like pmap_change_attr(), protections for aliases
9641 * in the direct map are updated as well. Protections on aliasing mappings may
9642 * be a subset of the requested protections; for example, mappings in the direct
9643 * map are never executable.
9646 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9650 /* Only supported within the kernel map. */
9651 if (va < VM_MIN_KERNEL_ADDRESS)
9654 PMAP_LOCK(kernel_pmap);
9655 error = pmap_change_props_locked(va, size, prot, -1,
9656 MAPDEV_ASSERTVALID);
9657 PMAP_UNLOCK(kernel_pmap);
9662 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9663 int mode, int flags)
9665 vm_offset_t base, offset, tmpva;
9666 vm_paddr_t pa_start, pa_end, pa_end1;
9668 pd_entry_t *pde, pde_bits, pde_mask;
9669 pt_entry_t *pte, pte_bits, pte_mask;
9673 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9674 base = trunc_page(va);
9675 offset = va & PAGE_MASK;
9676 size = round_page(offset + size);
9679 * Only supported on kernel virtual addresses, including the direct
9680 * map but excluding the recursive map.
9682 if (base < DMAP_MIN_ADDRESS)
9686 * Construct our flag sets and masks. "bits" is the subset of
9687 * "mask" that will be set in each modified PTE.
9689 * Mappings in the direct map are never allowed to be executable.
9691 pde_bits = pte_bits = 0;
9692 pde_mask = pte_mask = 0;
9694 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9695 pde_mask |= X86_PG_PDE_CACHE;
9696 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9697 pte_mask |= X86_PG_PTE_CACHE;
9699 if (prot != VM_PROT_NONE) {
9700 if ((prot & VM_PROT_WRITE) != 0) {
9701 pde_bits |= X86_PG_RW;
9702 pte_bits |= X86_PG_RW;
9704 if ((prot & VM_PROT_EXECUTE) == 0 ||
9705 va < VM_MIN_KERNEL_ADDRESS) {
9709 pde_mask |= X86_PG_RW | pg_nx;
9710 pte_mask |= X86_PG_RW | pg_nx;
9714 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9715 * into 4KB pages if required.
9717 for (tmpva = base; tmpva < base + size; ) {
9718 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9719 if (pdpe == NULL || *pdpe == 0) {
9720 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9721 ("%s: addr %#lx is not mapped", __func__, tmpva));
9724 if (*pdpe & PG_PS) {
9726 * If the current 1GB page already has the required
9727 * properties, then we need not demote this page. Just
9728 * increment tmpva to the next 1GB page frame.
9730 if ((*pdpe & pde_mask) == pde_bits) {
9731 tmpva = trunc_1gpage(tmpva) + NBPDP;
9736 * If the current offset aligns with a 1GB page frame
9737 * and there is at least 1GB left within the range, then
9738 * we need not break down this page into 2MB pages.
9740 if ((tmpva & PDPMASK) == 0 &&
9741 tmpva + PDPMASK < base + size) {
9745 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9748 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9750 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9751 ("%s: addr %#lx is not mapped", __func__, tmpva));
9756 * If the current 2MB page already has the required
9757 * properties, then we need not demote this page. Just
9758 * increment tmpva to the next 2MB page frame.
9760 if ((*pde & pde_mask) == pde_bits) {
9761 tmpva = trunc_2mpage(tmpva) + NBPDR;
9766 * If the current offset aligns with a 2MB page frame
9767 * and there is at least 2MB left within the range, then
9768 * we need not break down this page into 4KB pages.
9770 if ((tmpva & PDRMASK) == 0 &&
9771 tmpva + PDRMASK < base + size) {
9775 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9778 pte = pmap_pde_to_pte(pde, tmpva);
9780 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9781 ("%s: addr %#lx is not mapped", __func__, tmpva));
9789 * Ok, all the pages exist, so run through them updating their
9790 * properties if required.
9793 pa_start = pa_end = 0;
9794 for (tmpva = base; tmpva < base + size; ) {
9795 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9796 if (*pdpe & PG_PS) {
9797 if ((*pdpe & pde_mask) != pde_bits) {
9798 pmap_pte_props(pdpe, pde_bits, pde_mask);
9801 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9802 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9803 if (pa_start == pa_end) {
9804 /* Start physical address run. */
9805 pa_start = *pdpe & PG_PS_FRAME;
9806 pa_end = pa_start + NBPDP;
9807 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9810 /* Run ended, update direct map. */
9811 error = pmap_change_props_locked(
9812 PHYS_TO_DMAP(pa_start),
9813 pa_end - pa_start, prot, mode,
9817 /* Start physical address run. */
9818 pa_start = *pdpe & PG_PS_FRAME;
9819 pa_end = pa_start + NBPDP;
9822 tmpva = trunc_1gpage(tmpva) + NBPDP;
9825 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9827 if ((*pde & pde_mask) != pde_bits) {
9828 pmap_pte_props(pde, pde_bits, pde_mask);
9831 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9832 (*pde & PG_PS_FRAME) < dmaplimit) {
9833 if (pa_start == pa_end) {
9834 /* Start physical address run. */
9835 pa_start = *pde & PG_PS_FRAME;
9836 pa_end = pa_start + NBPDR;
9837 } else if (pa_end == (*pde & PG_PS_FRAME))
9840 /* Run ended, update direct map. */
9841 error = pmap_change_props_locked(
9842 PHYS_TO_DMAP(pa_start),
9843 pa_end - pa_start, prot, mode,
9847 /* Start physical address run. */
9848 pa_start = *pde & PG_PS_FRAME;
9849 pa_end = pa_start + NBPDR;
9852 tmpva = trunc_2mpage(tmpva) + NBPDR;
9854 pte = pmap_pde_to_pte(pde, tmpva);
9855 if ((*pte & pte_mask) != pte_bits) {
9856 pmap_pte_props(pte, pte_bits, pte_mask);
9859 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9860 (*pte & PG_FRAME) < dmaplimit) {
9861 if (pa_start == pa_end) {
9862 /* Start physical address run. */
9863 pa_start = *pte & PG_FRAME;
9864 pa_end = pa_start + PAGE_SIZE;
9865 } else if (pa_end == (*pte & PG_FRAME))
9866 pa_end += PAGE_SIZE;
9868 /* Run ended, update direct map. */
9869 error = pmap_change_props_locked(
9870 PHYS_TO_DMAP(pa_start),
9871 pa_end - pa_start, prot, mode,
9875 /* Start physical address run. */
9876 pa_start = *pte & PG_FRAME;
9877 pa_end = pa_start + PAGE_SIZE;
9883 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9884 pa_end1 = MIN(pa_end, dmaplimit);
9885 if (pa_start != pa_end1)
9886 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9887 pa_end1 - pa_start, prot, mode, flags);
9891 * Flush CPU caches if required to make sure any data isn't cached that
9892 * shouldn't be, etc.
9895 pmap_invalidate_range(kernel_pmap, base, tmpva);
9896 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9897 pmap_invalidate_cache_range(base, tmpva);
9903 * Demotes any mapping within the direct map region that covers more than the
9904 * specified range of physical addresses. This range's size must be a power
9905 * of two and its starting address must be a multiple of its size. Since the
9906 * demotion does not change any attributes of the mapping, a TLB invalidation
9907 * is not mandatory. The caller may, however, request a TLB invalidation.
9910 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
9919 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9920 KASSERT((base & (len - 1)) == 0,
9921 ("pmap_demote_DMAP: base is not a multiple of len"));
9922 if (len < NBPDP && base < dmaplimit) {
9923 va = PHYS_TO_DMAP(base);
9925 PMAP_LOCK(kernel_pmap);
9926 pdpe = pmap_pdpe(kernel_pmap, va);
9927 if ((*pdpe & X86_PG_V) == 0)
9928 panic("pmap_demote_DMAP: invalid PDPE");
9929 if ((*pdpe & PG_PS) != 0) {
9930 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9931 panic("pmap_demote_DMAP: PDPE failed");
9935 pde = pmap_pdpe_to_pde(pdpe, va);
9936 if ((*pde & X86_PG_V) == 0)
9937 panic("pmap_demote_DMAP: invalid PDE");
9938 if ((*pde & PG_PS) != 0) {
9939 if (!pmap_demote_pde(kernel_pmap, pde, va))
9940 panic("pmap_demote_DMAP: PDE failed");
9944 if (changed && invalidate)
9945 pmap_invalidate_page(kernel_pmap, va);
9946 PMAP_UNLOCK(kernel_pmap);
9951 * Perform the pmap work for mincore(2). If the page is not both referenced and
9952 * modified by this pmap, returns its physical address so that the caller can
9953 * find other mappings.
9956 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
9960 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
9964 PG_A = pmap_accessed_bit(pmap);
9965 PG_M = pmap_modified_bit(pmap);
9966 PG_V = pmap_valid_bit(pmap);
9967 PG_RW = pmap_rw_bit(pmap);
9973 pdpe = pmap_pdpe(pmap, addr);
9976 if ((*pdpe & PG_V) != 0) {
9977 if ((*pdpe & PG_PS) != 0) {
9979 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
9981 val = MINCORE_PSIND(2);
9983 pdep = pmap_pde(pmap, addr);
9984 if (pdep != NULL && (*pdep & PG_V) != 0) {
9985 if ((*pdep & PG_PS) != 0) {
9987 /* Compute the physical address of the 4KB page. */
9988 pa = ((pte & PG_PS_FRAME) | (addr &
9989 PDRMASK)) & PG_FRAME;
9990 val = MINCORE_PSIND(1);
9992 pte = *pmap_pde_to_pte(pdep, addr);
9993 pa = pte & PG_FRAME;
9999 if ((pte & PG_V) != 0) {
10000 val |= MINCORE_INCORE;
10001 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
10002 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
10003 if ((pte & PG_A) != 0)
10004 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
10006 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
10007 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
10008 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
10017 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
10019 uint32_t gen, new_gen, pcid_next;
10021 CRITICAL_ASSERT(curthread);
10022 gen = PCPU_GET(pcid_gen);
10023 if (pcidp->pm_pcid == PMAP_PCID_KERN)
10024 return (pti ? 0 : CR3_PCID_SAVE);
10025 if (pcidp->pm_gen == gen)
10026 return (CR3_PCID_SAVE);
10027 pcid_next = PCPU_GET(pcid_next);
10028 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
10029 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
10030 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
10031 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
10032 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
10036 PCPU_SET(pcid_gen, new_gen);
10037 pcid_next = PMAP_PCID_KERN + 1;
10041 pcidp->pm_pcid = pcid_next;
10042 pcidp->pm_gen = new_gen;
10043 PCPU_SET(pcid_next, pcid_next + 1);
10048 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10052 cached = pmap_pcid_alloc(pmap, pcidp);
10053 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10054 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10055 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10056 ("non-kernel pmap pmap %p cpu %d pcid %#x",
10057 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10062 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10065 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10066 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10070 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10073 struct pmap_pcid *pcidp, *old_pcidp;
10074 uint64_t cached, cr3, kcr3, ucr3;
10076 KASSERT((read_rflags() & PSL_I) == 0,
10077 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10079 /* See the comment in pmap_invalidate_page_pcid(). */
10080 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10081 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10082 old_pmap = PCPU_GET(curpmap);
10083 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10084 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10085 old_pcidp->pm_gen = 0;
10088 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10089 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10091 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10092 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10093 PCPU_SET(curpmap, pmap);
10094 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10095 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10097 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10098 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10100 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10101 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10103 counter_u64_add(pcid_save_cnt, 1);
10105 pmap_activate_sw_pti_post(td, pmap);
10109 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10112 struct pmap_pcid *pcidp;
10113 uint64_t cached, cr3;
10115 KASSERT((read_rflags() & PSL_I) == 0,
10116 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10118 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10119 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10121 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10122 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10123 PCPU_SET(curpmap, pmap);
10125 counter_u64_add(pcid_save_cnt, 1);
10129 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10130 u_int cpuid __unused)
10133 load_cr3(pmap->pm_cr3);
10134 PCPU_SET(curpmap, pmap);
10138 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10139 u_int cpuid __unused)
10142 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10143 PCPU_SET(kcr3, pmap->pm_cr3);
10144 PCPU_SET(ucr3, pmap->pm_ucr3);
10145 pmap_activate_sw_pti_post(td, pmap);
10148 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10152 if (pmap_pcid_enabled && pti)
10153 return (pmap_activate_sw_pcid_pti);
10154 else if (pmap_pcid_enabled && !pti)
10155 return (pmap_activate_sw_pcid_nopti);
10156 else if (!pmap_pcid_enabled && pti)
10157 return (pmap_activate_sw_nopcid_pti);
10158 else /* if (!pmap_pcid_enabled && !pti) */
10159 return (pmap_activate_sw_nopcid_nopti);
10163 pmap_activate_sw(struct thread *td)
10165 pmap_t oldpmap, pmap;
10168 oldpmap = PCPU_GET(curpmap);
10169 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10170 if (oldpmap == pmap) {
10171 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10175 cpuid = PCPU_GET(cpuid);
10177 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10179 CPU_SET(cpuid, &pmap->pm_active);
10181 pmap_activate_sw_mode(td, pmap, cpuid);
10183 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10185 CPU_CLR(cpuid, &oldpmap->pm_active);
10190 pmap_activate(struct thread *td)
10193 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10194 * invalidate_all IPI, which checks for curpmap ==
10195 * smp_tlb_pmap. The below sequence of operations has a
10196 * window where %CR3 is loaded with the new pmap's PML4
10197 * address, but the curpmap value has not yet been updated.
10198 * This causes the invltlb IPI handler, which is called
10199 * between the updates, to execute as a NOP, which leaves
10200 * stale TLB entries.
10202 * Note that the most common use of pmap_activate_sw(), from
10203 * a context switch, is immune to this race, because
10204 * interrupts are disabled (while the thread lock is owned),
10205 * so the IPI is delayed until after curpmap is updated. Protect
10206 * other callers in a similar way, by disabling interrupts
10207 * around the %cr3 register reload and curpmap assignment.
10210 pmap_activate_sw(td);
10215 pmap_activate_boot(pmap_t pmap)
10221 * kernel_pmap must be never deactivated, and we ensure that
10222 * by never activating it at all.
10224 MPASS(pmap != kernel_pmap);
10226 cpuid = PCPU_GET(cpuid);
10228 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10230 CPU_SET(cpuid, &pmap->pm_active);
10232 PCPU_SET(curpmap, pmap);
10234 kcr3 = pmap->pm_cr3;
10235 if (pmap_pcid_enabled)
10236 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10238 kcr3 = PMAP_NO_CR3;
10240 PCPU_SET(kcr3, kcr3);
10241 PCPU_SET(ucr3, PMAP_NO_CR3);
10245 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10250 * Increase the starting virtual address of the given mapping if a
10251 * different alignment might result in more superpage mappings.
10254 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10255 vm_offset_t *addr, vm_size_t size)
10257 vm_offset_t superpage_offset;
10261 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10262 offset += ptoa(object->pg_color);
10263 superpage_offset = offset & PDRMASK;
10264 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10265 (*addr & PDRMASK) == superpage_offset)
10267 if ((*addr & PDRMASK) < superpage_offset)
10268 *addr = (*addr & ~PDRMASK) + superpage_offset;
10270 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10274 static unsigned long num_dirty_emulations;
10275 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10276 &num_dirty_emulations, 0, NULL);
10278 static unsigned long num_accessed_emulations;
10279 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10280 &num_accessed_emulations, 0, NULL);
10282 static unsigned long num_superpage_accessed_emulations;
10283 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10284 &num_superpage_accessed_emulations, 0, NULL);
10286 static unsigned long ad_emulation_superpage_promotions;
10287 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10288 &ad_emulation_superpage_promotions, 0, NULL);
10289 #endif /* INVARIANTS */
10292 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10295 struct rwlock *lock;
10296 #if VM_NRESERVLEVEL > 0
10300 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10302 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10303 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10305 if (!pmap_emulate_ad_bits(pmap))
10308 PG_A = pmap_accessed_bit(pmap);
10309 PG_M = pmap_modified_bit(pmap);
10310 PG_V = pmap_valid_bit(pmap);
10311 PG_RW = pmap_rw_bit(pmap);
10317 pde = pmap_pde(pmap, va);
10318 if (pde == NULL || (*pde & PG_V) == 0)
10321 if ((*pde & PG_PS) != 0) {
10322 if (ftype == VM_PROT_READ) {
10324 atomic_add_long(&num_superpage_accessed_emulations, 1);
10332 pte = pmap_pde_to_pte(pde, va);
10333 if ((*pte & PG_V) == 0)
10336 if (ftype == VM_PROT_WRITE) {
10337 if ((*pte & PG_RW) == 0)
10340 * Set the modified and accessed bits simultaneously.
10342 * Intel EPT PTEs that do software emulation of A/D bits map
10343 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10344 * An EPT misconfiguration is triggered if the PTE is writable
10345 * but not readable (WR=10). This is avoided by setting PG_A
10346 * and PG_M simultaneously.
10348 *pte |= PG_M | PG_A;
10353 #if VM_NRESERVLEVEL > 0
10354 /* try to promote the mapping */
10355 if (va < VM_MAXUSER_ADDRESS)
10356 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10360 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10362 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10363 (m->flags & PG_FICTITIOUS) == 0 &&
10364 vm_reserv_level_iffullpop(m) == 0 &&
10365 pmap_promote_pde(pmap, pde, va, mpte, &lock)) {
10367 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10373 if (ftype == VM_PROT_WRITE)
10374 atomic_add_long(&num_dirty_emulations, 1);
10376 atomic_add_long(&num_accessed_emulations, 1);
10378 rv = 0; /* success */
10387 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10389 pml4_entry_t *pml4;
10392 pt_entry_t *pte, PG_V;
10396 PG_V = pmap_valid_bit(pmap);
10399 pml4 = pmap_pml4e(pmap, va);
10402 ptr[idx++] = *pml4;
10403 if ((*pml4 & PG_V) == 0)
10406 pdp = pmap_pml4e_to_pdpe(pml4, va);
10408 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10411 pde = pmap_pdpe_to_pde(pdp, va);
10413 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10416 pte = pmap_pde_to_pte(pde, va);
10425 * Get the kernel virtual address of a set of physical pages. If there are
10426 * physical addresses not covered by the DMAP perform a transient mapping
10427 * that will be removed when calling pmap_unmap_io_transient.
10429 * \param page The pages the caller wishes to obtain the virtual
10430 * address on the kernel memory map.
10431 * \param vaddr On return contains the kernel virtual memory address
10432 * of the pages passed in the page parameter.
10433 * \param count Number of pages passed in.
10434 * \param can_fault true if the thread using the mapped pages can take
10435 * page faults, false otherwise.
10437 * \returns true if the caller must call pmap_unmap_io_transient when
10438 * finished or false otherwise.
10442 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10446 bool needs_mapping;
10448 int cache_bits, error __unused, i;
10451 * Allocate any KVA space that we need, this is done in a separate
10452 * loop to prevent calling vmem_alloc while pinned.
10454 needs_mapping = false;
10455 for (i = 0; i < count; i++) {
10456 paddr = VM_PAGE_TO_PHYS(page[i]);
10457 if (__predict_false(paddr >= dmaplimit)) {
10458 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10459 M_BESTFIT | M_WAITOK, &vaddr[i]);
10460 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10461 needs_mapping = true;
10463 vaddr[i] = PHYS_TO_DMAP(paddr);
10467 /* Exit early if everything is covered by the DMAP */
10468 if (!needs_mapping)
10472 * NB: The sequence of updating a page table followed by accesses
10473 * to the corresponding pages used in the !DMAP case is subject to
10474 * the situation described in the "AMD64 Architecture Programmer's
10475 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10476 * Coherency Considerations". Therefore, issuing the INVLPG right
10477 * after modifying the PTE bits is crucial.
10481 for (i = 0; i < count; i++) {
10482 paddr = VM_PAGE_TO_PHYS(page[i]);
10483 if (paddr >= dmaplimit) {
10486 * Slow path, since we can get page faults
10487 * while mappings are active don't pin the
10488 * thread to the CPU and instead add a global
10489 * mapping visible to all CPUs.
10491 pmap_qenter(vaddr[i], &page[i], 1);
10493 pte = vtopte(vaddr[i]);
10494 cache_bits = pmap_cache_bits(kernel_pmap,
10495 page[i]->md.pat_mode, false);
10496 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10498 pmap_invlpg(kernel_pmap, vaddr[i]);
10503 return (needs_mapping);
10507 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10515 for (i = 0; i < count; i++) {
10516 paddr = VM_PAGE_TO_PHYS(page[i]);
10517 if (paddr >= dmaplimit) {
10519 pmap_qremove(vaddr[i], 1);
10520 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10526 pmap_quick_enter_page(vm_page_t m)
10530 paddr = VM_PAGE_TO_PHYS(m);
10531 if (paddr < dmaplimit)
10532 return (PHYS_TO_DMAP(paddr));
10533 mtx_lock_spin(&qframe_mtx);
10534 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10537 * Since qframe is exclusively mapped by us, and we do not set
10538 * PG_G, we can use INVLPG here.
10542 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10543 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
10548 pmap_quick_remove_page(vm_offset_t addr)
10551 if (addr != qframe)
10553 pte_store(vtopte(qframe), 0);
10554 mtx_unlock_spin(&qframe_mtx);
10558 * Pdp pages from the large map are managed differently from either
10559 * kernel or user page table pages. They are permanently allocated at
10560 * initialization time, and their reference count is permanently set to
10561 * zero. The pml4 entries pointing to those pages are copied into
10562 * each allocated pmap.
10564 * In contrast, pd and pt pages are managed like user page table
10565 * pages. They are dynamically allocated, and their reference count
10566 * represents the number of valid entries within the page.
10569 pmap_large_map_getptp_unlocked(void)
10571 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10575 pmap_large_map_getptp(void)
10579 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10580 m = pmap_large_map_getptp_unlocked();
10582 PMAP_UNLOCK(kernel_pmap);
10584 PMAP_LOCK(kernel_pmap);
10585 /* Callers retry. */
10590 static pdp_entry_t *
10591 pmap_large_map_pdpe(vm_offset_t va)
10593 vm_pindex_t pml4_idx;
10596 pml4_idx = pmap_pml4e_index(va);
10597 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10598 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10600 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10601 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10602 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10603 "LMSPML4I %#jx lm_ents %d",
10604 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10605 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10606 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10609 static pd_entry_t *
10610 pmap_large_map_pde(vm_offset_t va)
10617 pdpe = pmap_large_map_pdpe(va);
10619 m = pmap_large_map_getptp();
10622 mphys = VM_PAGE_TO_PHYS(m);
10623 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10625 MPASS((*pdpe & X86_PG_PS) == 0);
10626 mphys = *pdpe & PG_FRAME;
10628 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10631 static pt_entry_t *
10632 pmap_large_map_pte(vm_offset_t va)
10639 pde = pmap_large_map_pde(va);
10641 m = pmap_large_map_getptp();
10644 mphys = VM_PAGE_TO_PHYS(m);
10645 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10646 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10648 MPASS((*pde & X86_PG_PS) == 0);
10649 mphys = *pde & PG_FRAME;
10651 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10655 pmap_large_map_kextract(vm_offset_t va)
10657 pdp_entry_t *pdpe, pdp;
10658 pd_entry_t *pde, pd;
10659 pt_entry_t *pte, pt;
10661 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10662 ("not largemap range %#lx", (u_long)va));
10663 pdpe = pmap_large_map_pdpe(va);
10665 KASSERT((pdp & X86_PG_V) != 0,
10666 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10667 (u_long)pdpe, pdp));
10668 if ((pdp & X86_PG_PS) != 0) {
10669 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10670 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10671 (u_long)pdpe, pdp));
10672 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10674 pde = pmap_pdpe_to_pde(pdpe, va);
10676 KASSERT((pd & X86_PG_V) != 0,
10677 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10678 if ((pd & X86_PG_PS) != 0)
10679 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10680 pte = pmap_pde_to_pte(pde, va);
10682 KASSERT((pt & X86_PG_V) != 0,
10683 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10684 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10688 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10689 vmem_addr_t *vmem_res)
10693 * Large mappings are all but static. Consequently, there
10694 * is no point in waiting for an earlier allocation to be
10697 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10698 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10702 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10703 vm_memattr_t mattr)
10708 vm_offset_t va, inc;
10709 vmem_addr_t vmem_res;
10713 if (len == 0 || spa + len < spa)
10716 /* See if DMAP can serve. */
10717 if (spa + len <= dmaplimit) {
10718 va = PHYS_TO_DMAP(spa);
10719 *addr = (void *)va;
10720 return (pmap_change_attr(va, len, mattr));
10724 * No, allocate KVA. Fit the address with best possible
10725 * alignment for superpages. Fall back to worse align if
10729 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10730 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10731 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10733 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10735 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10738 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10743 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10744 * in the pagetable to minimize flushing. No need to
10745 * invalidate TLB, since we only update invalid entries.
10747 PMAP_LOCK(kernel_pmap);
10748 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10750 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10751 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10752 pdpe = pmap_large_map_pdpe(va);
10754 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10755 X86_PG_V | X86_PG_A | pg_nx |
10756 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10758 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10759 (va & PDRMASK) == 0) {
10760 pde = pmap_large_map_pde(va);
10762 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10763 X86_PG_V | X86_PG_A | pg_nx |
10764 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10765 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10769 pte = pmap_large_map_pte(va);
10771 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10772 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10774 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10779 PMAP_UNLOCK(kernel_pmap);
10782 *addr = (void *)vmem_res;
10787 pmap_large_unmap(void *svaa, vm_size_t len)
10789 vm_offset_t sva, va;
10791 pdp_entry_t *pdpe, pdp;
10792 pd_entry_t *pde, pd;
10795 struct spglist spgf;
10797 sva = (vm_offset_t)svaa;
10798 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10799 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10803 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10804 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10805 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10806 PMAP_LOCK(kernel_pmap);
10807 for (va = sva; va < sva + len; va += inc) {
10808 pdpe = pmap_large_map_pdpe(va);
10810 KASSERT((pdp & X86_PG_V) != 0,
10811 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10812 (u_long)pdpe, pdp));
10813 if ((pdp & X86_PG_PS) != 0) {
10814 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10815 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10816 (u_long)pdpe, pdp));
10817 KASSERT((va & PDPMASK) == 0,
10818 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10819 (u_long)pdpe, pdp));
10820 KASSERT(va + NBPDP <= sva + len,
10821 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10822 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10823 (u_long)pdpe, pdp, len));
10828 pde = pmap_pdpe_to_pde(pdpe, va);
10830 KASSERT((pd & X86_PG_V) != 0,
10831 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10833 if ((pd & X86_PG_PS) != 0) {
10834 KASSERT((va & PDRMASK) == 0,
10835 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10837 KASSERT(va + NBPDR <= sva + len,
10838 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10839 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10843 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10845 if (m->ref_count == 0) {
10847 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10851 pte = pmap_pde_to_pte(pde, va);
10852 KASSERT((*pte & X86_PG_V) != 0,
10853 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10854 (u_long)pte, *pte));
10857 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10859 if (m->ref_count == 0) {
10861 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10862 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10864 if (m->ref_count == 0) {
10866 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10870 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10871 PMAP_UNLOCK(kernel_pmap);
10872 vm_page_free_pages_toq(&spgf, false);
10873 vmem_free(large_vmem, sva, len);
10877 pmap_large_map_wb_fence_mfence(void)
10884 pmap_large_map_wb_fence_atomic(void)
10887 atomic_thread_fence_seq_cst();
10891 pmap_large_map_wb_fence_nop(void)
10895 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10898 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10899 return (pmap_large_map_wb_fence_mfence);
10900 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10901 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10902 return (pmap_large_map_wb_fence_atomic);
10904 /* clflush is strongly enough ordered */
10905 return (pmap_large_map_wb_fence_nop);
10909 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10912 for (; len > 0; len -= cpu_clflush_line_size,
10913 va += cpu_clflush_line_size)
10918 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10921 for (; len > 0; len -= cpu_clflush_line_size,
10922 va += cpu_clflush_line_size)
10927 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10930 for (; len > 0; len -= cpu_clflush_line_size,
10931 va += cpu_clflush_line_size)
10936 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10940 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
10943 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
10944 return (pmap_large_map_flush_range_clwb);
10945 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
10946 return (pmap_large_map_flush_range_clflushopt);
10947 else if ((cpu_feature & CPUID_CLFSH) != 0)
10948 return (pmap_large_map_flush_range_clflush);
10950 return (pmap_large_map_flush_range_nop);
10954 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
10956 volatile u_long *pe;
10962 for (va = sva; va < eva; va += inc) {
10964 if ((amd_feature & AMDID_PAGE1GB) != 0) {
10965 pe = (volatile u_long *)pmap_large_map_pdpe(va);
10967 if ((p & X86_PG_PS) != 0)
10971 pe = (volatile u_long *)pmap_large_map_pde(va);
10973 if ((p & X86_PG_PS) != 0)
10977 pe = (volatile u_long *)pmap_large_map_pte(va);
10981 seen_other = false;
10983 if ((p & X86_PG_AVAIL1) != 0) {
10985 * Spin-wait for the end of a parallel
10992 * If we saw other write-back
10993 * occuring, we cannot rely on PG_M to
10994 * indicate state of the cache. The
10995 * PG_M bit is cleared before the
10996 * flush to avoid ignoring new writes,
10997 * and writes which are relevant for
10998 * us might happen after.
11004 if ((p & X86_PG_M) != 0 || seen_other) {
11005 if (!atomic_fcmpset_long(pe, &p,
11006 (p & ~X86_PG_M) | X86_PG_AVAIL1))
11008 * If we saw PG_M without
11009 * PG_AVAIL1, and then on the
11010 * next attempt we do not
11011 * observe either PG_M or
11012 * PG_AVAIL1, the other
11013 * write-back started after us
11014 * and finished before us. We
11015 * can rely on it doing our
11019 pmap_large_map_flush_range(va, inc);
11020 atomic_clear_long(pe, X86_PG_AVAIL1);
11029 * Write-back cache lines for the given address range.
11031 * Must be called only on the range or sub-range returned from
11032 * pmap_large_map(). Must not be called on the coalesced ranges.
11034 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
11035 * instructions support.
11038 pmap_large_map_wb(void *svap, vm_size_t len)
11040 vm_offset_t eva, sva;
11042 sva = (vm_offset_t)svap;
11044 pmap_large_map_wb_fence();
11045 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
11046 pmap_large_map_flush_range(sva, len);
11048 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
11049 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11050 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11051 pmap_large_map_wb_large(sva, eva);
11053 pmap_large_map_wb_fence();
11057 pmap_pti_alloc_page(void)
11061 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11062 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11067 pmap_pti_free_page(vm_page_t m)
11069 if (!vm_page_unwire_noq(m))
11071 vm_page_xbusy_claim(m);
11072 vm_page_free_zero(m);
11077 pmap_pti_init(void)
11086 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11087 VM_OBJECT_WLOCK(pti_obj);
11088 pml4_pg = pmap_pti_alloc_page();
11089 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11090 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11091 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11092 pdpe = pmap_pti_pdpe(va);
11093 pmap_pti_wire_pte(pdpe);
11095 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11096 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11097 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11098 sizeof(struct gate_descriptor) * NIDT, false);
11100 /* Doublefault stack IST 1 */
11101 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11102 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11103 /* NMI stack IST 2 */
11104 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11105 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11106 /* MC# stack IST 3 */
11107 va = __pcpu[i].pc_common_tss.tss_ist3 +
11108 sizeof(struct nmi_pcpu);
11109 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11110 /* DB# stack IST 4 */
11111 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11112 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11114 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11116 pti_finalized = true;
11117 VM_OBJECT_WUNLOCK(pti_obj);
11121 pmap_cpu_init(void *arg __unused)
11123 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11126 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11128 static pdp_entry_t *
11129 pmap_pti_pdpe(vm_offset_t va)
11131 pml4_entry_t *pml4e;
11134 vm_pindex_t pml4_idx;
11137 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11139 pml4_idx = pmap_pml4e_index(va);
11140 pml4e = &pti_pml4[pml4_idx];
11144 panic("pml4 alloc after finalization\n");
11145 m = pmap_pti_alloc_page();
11147 pmap_pti_free_page(m);
11148 mphys = *pml4e & ~PAGE_MASK;
11150 mphys = VM_PAGE_TO_PHYS(m);
11151 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11154 mphys = *pml4e & ~PAGE_MASK;
11156 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11161 pmap_pti_wire_pte(void *pte)
11165 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11166 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11171 pmap_pti_unwire_pde(void *pde, bool only_ref)
11175 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11176 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11177 MPASS(only_ref || m->ref_count > 1);
11178 pmap_pti_free_page(m);
11182 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11187 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11188 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11189 if (pmap_pti_free_page(m)) {
11190 pde = pmap_pti_pde(va);
11191 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11193 pmap_pti_unwire_pde(pde, false);
11197 static pd_entry_t *
11198 pmap_pti_pde(vm_offset_t va)
11203 vm_pindex_t pd_idx;
11206 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11208 pdpe = pmap_pti_pdpe(va);
11210 m = pmap_pti_alloc_page();
11212 pmap_pti_free_page(m);
11213 MPASS((*pdpe & X86_PG_PS) == 0);
11214 mphys = *pdpe & ~PAGE_MASK;
11216 mphys = VM_PAGE_TO_PHYS(m);
11217 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11220 MPASS((*pdpe & X86_PG_PS) == 0);
11221 mphys = *pdpe & ~PAGE_MASK;
11224 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11225 pd_idx = pmap_pde_index(va);
11230 static pt_entry_t *
11231 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11238 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11240 pde = pmap_pti_pde(va);
11241 if (unwire_pde != NULL) {
11242 *unwire_pde = true;
11243 pmap_pti_wire_pte(pde);
11246 m = pmap_pti_alloc_page();
11248 pmap_pti_free_page(m);
11249 MPASS((*pde & X86_PG_PS) == 0);
11250 mphys = *pde & ~(PAGE_MASK | pg_nx);
11252 mphys = VM_PAGE_TO_PHYS(m);
11253 *pde = mphys | X86_PG_RW | X86_PG_V;
11254 if (unwire_pde != NULL)
11255 *unwire_pde = false;
11258 MPASS((*pde & X86_PG_PS) == 0);
11259 mphys = *pde & ~(PAGE_MASK | pg_nx);
11262 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11263 pte += pmap_pte_index(va);
11269 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11273 pt_entry_t *pte, ptev;
11276 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11278 sva = trunc_page(sva);
11279 MPASS(sva > VM_MAXUSER_ADDRESS);
11280 eva = round_page(eva);
11282 for (; sva < eva; sva += PAGE_SIZE) {
11283 pte = pmap_pti_pte(sva, &unwire_pde);
11284 pa = pmap_kextract(sva);
11285 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11286 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11287 VM_MEMATTR_DEFAULT, FALSE);
11289 pte_store(pte, ptev);
11290 pmap_pti_wire_pte(pte);
11292 KASSERT(!pti_finalized,
11293 ("pti overlap after fin %#lx %#lx %#lx",
11295 KASSERT(*pte == ptev,
11296 ("pti non-identical pte after fin %#lx %#lx %#lx",
11300 pde = pmap_pti_pde(sva);
11301 pmap_pti_unwire_pde(pde, true);
11307 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11312 VM_OBJECT_WLOCK(pti_obj);
11313 pmap_pti_add_kva_locked(sva, eva, exec);
11314 VM_OBJECT_WUNLOCK(pti_obj);
11318 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11325 sva = rounddown2(sva, PAGE_SIZE);
11326 MPASS(sva > VM_MAXUSER_ADDRESS);
11327 eva = roundup2(eva, PAGE_SIZE);
11329 VM_OBJECT_WLOCK(pti_obj);
11330 for (va = sva; va < eva; va += PAGE_SIZE) {
11331 pte = pmap_pti_pte(va, NULL);
11332 KASSERT((*pte & X86_PG_V) != 0,
11333 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11334 (u_long)pte, *pte));
11336 pmap_pti_unwire_pte(pte, va);
11338 pmap_invalidate_range(kernel_pmap, sva, eva);
11339 VM_OBJECT_WUNLOCK(pti_obj);
11343 pkru_dup_range(void *ctx __unused, void *data)
11345 struct pmap_pkru_range *node, *new_node;
11347 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11348 if (new_node == NULL)
11351 memcpy(new_node, node, sizeof(*node));
11356 pkru_free_range(void *ctx __unused, void *node)
11359 uma_zfree(pmap_pkru_ranges_zone, node);
11363 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11366 struct pmap_pkru_range *ppr;
11369 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11370 MPASS(pmap->pm_type == PT_X86);
11371 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11372 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11373 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11375 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11378 ppr->pkru_keyidx = keyidx;
11379 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11380 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11382 uma_zfree(pmap_pkru_ranges_zone, ppr);
11387 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11390 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11391 MPASS(pmap->pm_type == PT_X86);
11392 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11393 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11397 pmap_pkru_deassign_all(pmap_t pmap)
11400 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11401 if (pmap->pm_type == PT_X86 &&
11402 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11403 rangeset_remove_all(&pmap->pm_pkru);
11407 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11409 struct pmap_pkru_range *ppr, *prev_ppr;
11412 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11413 if (pmap->pm_type != PT_X86 ||
11414 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11415 sva >= VM_MAXUSER_ADDRESS)
11417 MPASS(eva <= VM_MAXUSER_ADDRESS);
11418 for (va = sva; va < eva; prev_ppr = ppr) {
11419 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11422 else if ((ppr == NULL) ^ (prev_ppr == NULL))
11428 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
11430 va = ppr->pkru_rs_el.re_end;
11436 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11438 struct pmap_pkru_range *ppr;
11440 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11441 if (pmap->pm_type != PT_X86 ||
11442 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11443 va >= VM_MAXUSER_ADDRESS)
11445 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11447 return (X86_PG_PKU(ppr->pkru_keyidx));
11452 pred_pkru_on_remove(void *ctx __unused, void *r)
11454 struct pmap_pkru_range *ppr;
11457 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11461 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11464 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11465 if (pmap->pm_type == PT_X86 &&
11466 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11467 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11468 pred_pkru_on_remove);
11473 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11476 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11477 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11478 MPASS(dst_pmap->pm_type == PT_X86);
11479 MPASS(src_pmap->pm_type == PT_X86);
11480 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11481 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11483 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11487 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11490 pml4_entry_t *pml4e;
11492 pd_entry_t newpde, ptpaddr, *pde;
11493 pt_entry_t newpte, *ptep, pte;
11494 vm_offset_t va, va_next;
11497 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11498 MPASS(pmap->pm_type == PT_X86);
11499 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11501 for (changed = false, va = sva; va < eva; va = va_next) {
11502 pml4e = pmap_pml4e(pmap, va);
11503 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11504 va_next = (va + NBPML4) & ~PML4MASK;
11510 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11511 if ((*pdpe & X86_PG_V) == 0) {
11512 va_next = (va + NBPDP) & ~PDPMASK;
11518 va_next = (va + NBPDR) & ~PDRMASK;
11522 pde = pmap_pdpe_to_pde(pdpe, va);
11527 MPASS((ptpaddr & X86_PG_V) != 0);
11528 if ((ptpaddr & PG_PS) != 0) {
11529 if (va + NBPDR == va_next && eva >= va_next) {
11530 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11531 X86_PG_PKU(keyidx);
11532 if (newpde != ptpaddr) {
11537 } else if (!pmap_demote_pde(pmap, pde, va)) {
11545 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11546 ptep++, va += PAGE_SIZE) {
11548 if ((pte & X86_PG_V) == 0)
11550 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11551 if (newpte != pte) {
11558 pmap_invalidate_range(pmap, sva, eva);
11562 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11563 u_int keyidx, int flags)
11566 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11567 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11569 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11571 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11577 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11582 sva = trunc_page(sva);
11583 eva = round_page(eva);
11584 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11589 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11591 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11593 if (error != ENOMEM)
11601 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11605 sva = trunc_page(sva);
11606 eva = round_page(eva);
11607 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11612 error = pmap_pkru_deassign(pmap, sva, eva);
11614 pmap_pkru_update_range(pmap, sva, eva, 0);
11616 if (error != ENOMEM)
11623 #if defined(KASAN) || defined(KMSAN)
11626 * Reserve enough memory to:
11627 * 1) allocate PDP pages for the shadow map(s),
11628 * 2) shadow one page of memory, so one PD page, one PT page, and one shadow
11629 * page per shadow map.
11632 #define SAN_EARLY_PAGES (NKASANPML4E + 3)
11634 #define SAN_EARLY_PAGES (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * 3)
11637 static uint64_t __nosanitizeaddress __nosanitizememory
11638 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11640 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11641 static size_t offset = 0;
11644 if (offset == sizeof(data)) {
11645 panic("%s: ran out of memory for the bootstrap shadow map",
11649 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11650 offset += PAGE_SIZE;
11655 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11656 * is currently only used to shadow the temporary boot stack set up by locore.
11658 static void __nosanitizeaddress __nosanitizememory
11659 pmap_san_enter_early(vm_offset_t va)
11661 static bool first = true;
11662 pml4_entry_t *pml4e;
11666 uint64_t cr3, pa, base;
11669 base = amd64_loadaddr();
11674 * If this the first call, we need to allocate new PML4Es for
11675 * the bootstrap shadow map(s). We don't know how the PML4 page
11676 * was initialized by the boot loader, so we can't simply test
11677 * whether the shadow map's PML4Es are zero.
11681 for (i = 0; i < NKASANPML4E; i++) {
11682 pa = pmap_san_enter_early_alloc_4k(base);
11684 pml4e = (pml4_entry_t *)cr3 +
11685 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11686 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11689 for (i = 0; i < NKMSANORIGPML4E; i++) {
11690 pa = pmap_san_enter_early_alloc_4k(base);
11692 pml4e = (pml4_entry_t *)cr3 +
11693 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11695 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11697 for (i = 0; i < NKMSANSHADPML4E; i++) {
11698 pa = pmap_san_enter_early_alloc_4k(base);
11700 pml4e = (pml4_entry_t *)cr3 +
11701 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11703 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11707 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11708 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11710 pa = pmap_san_enter_early_alloc_4k(base);
11711 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11713 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11715 pa = pmap_san_enter_early_alloc_4k(base);
11716 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11718 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11720 panic("%s: PTE for %#lx is already initialized", __func__, va);
11721 pa = pmap_san_enter_early_alloc_4k(base);
11722 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11726 pmap_san_enter_alloc_4k(void)
11730 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11733 panic("%s: no memory to grow shadow map", __func__);
11738 pmap_san_enter_alloc_2m(void)
11740 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11741 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11745 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11746 * pages when possible.
11748 void __nosanitizeaddress __nosanitizememory
11749 pmap_san_enter(vm_offset_t va)
11756 if (kernphys == 0) {
11758 * We're creating a temporary shadow map for the boot stack.
11760 pmap_san_enter_early(va);
11764 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11766 pdpe = pmap_pdpe(kernel_pmap, va);
11767 if ((*pdpe & X86_PG_V) == 0) {
11768 m = pmap_san_enter_alloc_4k();
11769 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11772 pde = pmap_pdpe_to_pde(pdpe, va);
11773 if ((*pde & X86_PG_V) == 0) {
11774 m = pmap_san_enter_alloc_2m();
11776 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11777 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11779 m = pmap_san_enter_alloc_4k();
11780 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11784 if ((*pde & X86_PG_PS) != 0)
11786 pte = pmap_pde_to_pte(pde, va);
11787 if ((*pte & X86_PG_V) != 0)
11789 m = pmap_san_enter_alloc_4k();
11790 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11791 X86_PG_M | X86_PG_A | pg_nx);
11796 * Track a range of the kernel's virtual address space that is contiguous
11797 * in various mapping attributes.
11799 struct pmap_kernel_map_range {
11808 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11814 if (eva <= range->sva)
11817 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11818 for (i = 0; i < PAT_INDEX_SIZE; i++)
11819 if (pat_index[i] == pat_idx)
11823 case PAT_WRITE_BACK:
11826 case PAT_WRITE_THROUGH:
11829 case PAT_UNCACHEABLE:
11835 case PAT_WRITE_PROTECTED:
11838 case PAT_WRITE_COMBINING:
11842 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11843 __func__, pat_idx, range->sva, eva);
11848 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11850 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11851 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11852 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11853 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11854 mode, range->pdpes, range->pdes, range->ptes);
11856 /* Reset to sentinel value. */
11857 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11858 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11859 NPDEPG - 1, NPTEPG - 1);
11863 * Determine whether the attributes specified by a page table entry match those
11864 * being tracked by the current range. This is not quite as simple as a direct
11865 * flag comparison since some PAT modes have multiple representations.
11868 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11870 pt_entry_t diff, mask;
11872 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11873 diff = (range->attrs ^ attrs) & mask;
11876 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11877 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11878 pmap_pat_index(kernel_pmap, attrs, true))
11884 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11888 memset(range, 0, sizeof(*range));
11890 range->attrs = attrs;
11894 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11895 * those of the current run, dump the address range and its attributes, and
11899 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11900 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11905 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11907 attrs |= pdpe & pg_nx;
11908 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11909 if ((pdpe & PG_PS) != 0) {
11910 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11911 } else if (pde != 0) {
11912 attrs |= pde & pg_nx;
11913 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11915 if ((pde & PG_PS) != 0) {
11916 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11917 } else if (pte != 0) {
11918 attrs |= pte & pg_nx;
11919 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11920 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11922 /* Canonicalize by always using the PDE PAT bit. */
11923 if ((attrs & X86_PG_PTE_PAT) != 0)
11924 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11927 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11928 sysctl_kmaps_dump(sb, range, va);
11929 sysctl_kmaps_reinit(range, va, attrs);
11934 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
11936 struct pmap_kernel_map_range range;
11937 struct sbuf sbuf, *sb;
11938 pml4_entry_t pml4e;
11939 pdp_entry_t *pdp, pdpe;
11940 pd_entry_t *pd, pde;
11941 pt_entry_t *pt, pte;
11944 int error, i, j, k, l;
11946 error = sysctl_wire_old_buffer(req, 0);
11950 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
11952 /* Sentinel value. */
11953 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11954 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11955 NPDEPG - 1, NPTEPG - 1);
11958 * Iterate over the kernel page tables without holding the kernel pmap
11959 * lock. Outside of the large map, kernel page table pages are never
11960 * freed, so at worst we will observe inconsistencies in the output.
11961 * Within the large map, ensure that PDP and PD page addresses are
11962 * valid before descending.
11964 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
11967 sbuf_printf(sb, "\nRecursive map:\n");
11970 sbuf_printf(sb, "\nDirect map:\n");
11974 sbuf_printf(sb, "\nKASAN shadow map:\n");
11978 case KMSANSHADPML4I:
11979 sbuf_printf(sb, "\nKMSAN shadow map:\n");
11981 case KMSANORIGPML4I:
11982 sbuf_printf(sb, "\nKMSAN origin map:\n");
11986 sbuf_printf(sb, "\nKernel map:\n");
11989 sbuf_printf(sb, "\nLarge map:\n");
11993 /* Convert to canonical form. */
11994 if (sva == 1ul << 47)
11998 pml4e = kernel_pml4[i];
11999 if ((pml4e & X86_PG_V) == 0) {
12000 sva = rounddown2(sva, NBPML4);
12001 sysctl_kmaps_dump(sb, &range, sva);
12005 pa = pml4e & PG_FRAME;
12006 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
12008 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
12010 if ((pdpe & X86_PG_V) == 0) {
12011 sva = rounddown2(sva, NBPDP);
12012 sysctl_kmaps_dump(sb, &range, sva);
12016 pa = pdpe & PG_FRAME;
12017 if ((pdpe & PG_PS) != 0) {
12018 sva = rounddown2(sva, NBPDP);
12019 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
12025 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12026 vm_phys_paddr_to_vm_page(pa) == NULL) {
12028 * Page table pages for the large map may be
12029 * freed. Validate the next-level address
12030 * before descending.
12034 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
12036 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
12038 if ((pde & X86_PG_V) == 0) {
12039 sva = rounddown2(sva, NBPDR);
12040 sysctl_kmaps_dump(sb, &range, sva);
12044 pa = pde & PG_FRAME;
12045 if ((pde & PG_PS) != 0) {
12046 sva = rounddown2(sva, NBPDR);
12047 sysctl_kmaps_check(sb, &range, sva,
12048 pml4e, pdpe, pde, 0);
12053 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12054 vm_phys_paddr_to_vm_page(pa) == NULL) {
12056 * Page table pages for the large map
12057 * may be freed. Validate the
12058 * next-level address before descending.
12062 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12064 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12065 sva += PAGE_SIZE) {
12067 if ((pte & X86_PG_V) == 0) {
12068 sysctl_kmaps_dump(sb, &range,
12072 sysctl_kmaps_check(sb, &range, sva,
12073 pml4e, pdpe, pde, pte);
12080 error = sbuf_finish(sb);
12084 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12085 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12086 NULL, 0, sysctl_kmaps, "A",
12087 "Dump kernel address layout");
12090 DB_SHOW_COMMAND(pte, pmap_print_pte)
12093 pml5_entry_t *pml5;
12094 pml4_entry_t *pml4;
12097 pt_entry_t *pte, PG_V;
12101 db_printf("show pte addr\n");
12104 va = (vm_offset_t)addr;
12106 if (kdb_thread != NULL)
12107 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12109 pmap = PCPU_GET(curpmap);
12111 PG_V = pmap_valid_bit(pmap);
12112 db_printf("VA 0x%016lx", va);
12114 if (pmap_is_la57(pmap)) {
12115 pml5 = pmap_pml5e(pmap, va);
12116 db_printf(" pml5e 0x%016lx", *pml5);
12117 if ((*pml5 & PG_V) == 0) {
12121 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12123 pml4 = pmap_pml4e(pmap, va);
12125 db_printf(" pml4e 0x%016lx", *pml4);
12126 if ((*pml4 & PG_V) == 0) {
12130 pdp = pmap_pml4e_to_pdpe(pml4, va);
12131 db_printf(" pdpe 0x%016lx", *pdp);
12132 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12136 pde = pmap_pdpe_to_pde(pdp, va);
12137 db_printf(" pde 0x%016lx", *pde);
12138 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12142 pte = pmap_pde_to_pte(pde, va);
12143 db_printf(" pte 0x%016lx\n", *pte);
12146 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12151 a = (vm_paddr_t)addr;
12152 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12154 db_printf("show phys2dmap addr\n");
12159 ptpages_show_page(int level, int idx, vm_page_t pg)
12161 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12162 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12166 ptpages_show_complain(int level, int idx, uint64_t pte)
12168 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12172 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12174 vm_page_t pg3, pg2, pg1;
12175 pml4_entry_t *pml4;
12180 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12181 for (i4 = 0; i4 < num_entries; i4++) {
12182 if ((pml4[i4] & PG_V) == 0)
12184 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12186 ptpages_show_complain(3, i4, pml4[i4]);
12189 ptpages_show_page(3, i4, pg3);
12190 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12191 for (i3 = 0; i3 < NPDPEPG; i3++) {
12192 if ((pdp[i3] & PG_V) == 0)
12194 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12196 ptpages_show_complain(2, i3, pdp[i3]);
12199 ptpages_show_page(2, i3, pg2);
12200 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12201 for (i2 = 0; i2 < NPDEPG; i2++) {
12202 if ((pd[i2] & PG_V) == 0)
12204 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12206 ptpages_show_complain(1, i2, pd[i2]);
12209 ptpages_show_page(1, i2, pg1);
12215 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12219 pml5_entry_t *pml5;
12224 pmap = (pmap_t)addr;
12226 pmap = PCPU_GET(curpmap);
12228 PG_V = pmap_valid_bit(pmap);
12230 if (pmap_is_la57(pmap)) {
12231 pml5 = pmap->pm_pmltop;
12232 for (i5 = 0; i5 < NUPML5E; i5++) {
12233 if ((pml5[i5] & PG_V) == 0)
12235 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12237 ptpages_show_complain(4, i5, pml5[i5]);
12240 ptpages_show_page(4, i5, pg);
12241 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12244 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12245 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);