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 #if !defined(DIAGNOSTIC)
317 #ifdef __GNUC_GNU_INLINE__
318 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
320 #define PMAP_INLINE extern inline
327 #define PV_STAT(x) do { x ; } while (0)
329 #define PV_STAT(x) do { } while (0)
334 #define pa_index(pa) ({ \
335 KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end, \
336 ("address %lx beyond the last segment", (pa))); \
339 #define pa_to_pmdp(pa) (&pv_table[pa_index(pa)])
340 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
341 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
342 struct rwlock *_lock; \
343 if (__predict_false((pa) > pmap_last_pa)) \
344 _lock = &pv_dummy_large.pv_lock; \
346 _lock = &(pa_to_pmdp(pa)->pv_lock); \
350 #define pa_index(pa) ((pa) >> PDRSHIFT)
351 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
353 #define NPV_LIST_LOCKS MAXCPU
355 #define PHYS_TO_PV_LIST_LOCK(pa) \
356 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
359 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
360 struct rwlock **_lockp = (lockp); \
361 struct rwlock *_new_lock; \
363 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
364 if (_new_lock != *_lockp) { \
365 if (*_lockp != NULL) \
366 rw_wunlock(*_lockp); \
367 *_lockp = _new_lock; \
372 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
373 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
375 #define RELEASE_PV_LIST_LOCK(lockp) do { \
376 struct rwlock **_lockp = (lockp); \
378 if (*_lockp != NULL) { \
379 rw_wunlock(*_lockp); \
384 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
385 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
388 * Statically allocate kernel pmap memory. However, memory for
389 * pm_pcids is obtained after the dynamic allocator is operational.
390 * Initialize it with a non-canonical pointer to catch early accesses
391 * regardless of the active mapping.
393 struct pmap kernel_pmap_store = {
394 .pm_pcidp = (void *)0xdeadbeefdeadbeef,
397 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
398 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
401 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
402 "Number of kernel page table pages allocated on bootup");
405 vm_paddr_t dmaplimit;
406 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
409 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
410 "VM/pmap parameters");
412 static int pg_ps_enabled = 1;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
414 &pg_ps_enabled, 0, "Are large page mappings enabled?");
416 int __read_frequently la57 = 0;
417 SYSCTL_INT(_vm_pmap, OID_AUTO, la57, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
419 "5-level paging for host is enabled");
422 pmap_is_la57(pmap_t pmap)
424 if (pmap->pm_type == PT_X86)
426 return (false); /* XXXKIB handle EPT */
429 #define PAT_INDEX_SIZE 8
430 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
432 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
433 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
434 static u_int64_t KPDPphys; /* phys addr of kernel level 3 */
435 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
436 u_int64_t KPML5phys; /* phys addr of kernel level 5,
440 static uint64_t KASANPDPphys;
443 static uint64_t KMSANSHADPDPphys;
444 static uint64_t KMSANORIGPDPphys;
447 * To support systems with large amounts of memory, it is necessary to extend
448 * the maximum size of the direct map. This could eat into the space reserved
449 * for the shadow map.
451 _Static_assert(DMPML4I + NDMPML4E <= KMSANSHADPML4I, "direct map overflow");
454 static pml4_entry_t *kernel_pml4;
455 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
456 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
457 static int ndmpdpphys; /* number of DMPDPphys pages */
459 vm_paddr_t kernphys; /* phys addr of start of bootstrap data */
460 vm_paddr_t KERNend; /* and the end */
463 * pmap_mapdev support pre initialization (i.e. console)
465 #define PMAP_PREINIT_MAPPING_COUNT 8
466 static struct pmap_preinit_mapping {
471 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
472 static int pmap_initialized;
475 * Data for the pv entry allocation mechanism.
476 * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
480 pc_to_domain(struct pv_chunk *pc)
483 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
487 pc_to_domain(struct pv_chunk *pc __unused)
494 struct pv_chunks_list {
496 TAILQ_HEAD(pch, pv_chunk) pvc_list;
498 } __aligned(CACHE_LINE_SIZE);
500 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
503 struct pmap_large_md_page {
504 struct rwlock pv_lock;
505 struct md_page pv_page;
508 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
509 #define pv_dummy pv_dummy_large.pv_page
510 __read_mostly static struct pmap_large_md_page *pv_table;
511 __read_mostly vm_paddr_t pmap_last_pa;
513 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
514 static u_long pv_invl_gen[NPV_LIST_LOCKS];
515 static struct md_page *pv_table;
516 static struct md_page pv_dummy;
520 * All those kernel PT submaps that BSD is so fond of
522 pt_entry_t *CMAP1 = NULL;
524 static vm_offset_t qframe = 0;
525 static struct mtx qframe_mtx;
527 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
529 static vmem_t *large_vmem;
530 static u_int lm_ents;
531 #define PMAP_ADDRESS_IN_LARGEMAP(va) ((va) >= LARGEMAP_MIN_ADDRESS && \
532 (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
534 int pmap_pcid_enabled = 1;
535 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
536 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
537 int invpcid_works = 0;
538 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
539 "Is the invpcid instruction available ?");
540 int pmap_pcid_invlpg_workaround = 0;
541 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_invlpg_workaround,
542 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
543 &pmap_pcid_invlpg_workaround, 0,
544 "Enable small core PCID/INVLPG workaround");
545 int pmap_pcid_invlpg_workaround_uena = 1;
547 int __read_frequently pti = 0;
548 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
550 "Page Table Isolation enabled");
551 static vm_object_t pti_obj;
552 static pml4_entry_t *pti_pml4;
553 static vm_pindex_t pti_pg_idx;
554 static bool pti_finalized;
556 struct pmap_pkru_range {
557 struct rs_el pkru_rs_el;
562 static uma_zone_t pmap_pkru_ranges_zone;
563 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
564 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
565 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
566 static void *pkru_dup_range(void *ctx, void *data);
567 static void pkru_free_range(void *ctx, void *node);
568 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
569 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
570 static void pmap_pkru_deassign_all(pmap_t pmap);
572 static COUNTER_U64_DEFINE_EARLY(pcid_save_cnt);
573 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLFLAG_RD,
574 &pcid_save_cnt, "Count of saved TLB context on switch");
576 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
577 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
578 static struct mtx invl_gen_mtx;
579 /* Fake lock object to satisfy turnstiles interface. */
580 static struct lock_object invl_gen_ts = {
583 static struct pmap_invl_gen pmap_invl_gen_head = {
587 static u_long pmap_invl_gen = 1;
588 static int pmap_invl_waiters;
589 static struct callout pmap_invl_callout;
590 static bool pmap_invl_callout_inited;
592 #define PMAP_ASSERT_NOT_IN_DI() \
593 KASSERT(pmap_not_in_di(), ("DI already started"))
600 if ((cpu_feature2 & CPUID2_CX16) == 0)
603 TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
608 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
612 locked = pmap_di_locked();
613 return (sysctl_handle_int(oidp, &locked, 0, req));
615 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
616 CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
617 "Locked delayed invalidation");
619 static bool pmap_not_in_di_l(void);
620 static bool pmap_not_in_di_u(void);
621 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
624 return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
628 pmap_not_in_di_l(void)
630 struct pmap_invl_gen *invl_gen;
632 invl_gen = &curthread->td_md.md_invl_gen;
633 return (invl_gen->gen == 0);
637 pmap_thread_init_invl_gen_l(struct thread *td)
639 struct pmap_invl_gen *invl_gen;
641 invl_gen = &td->td_md.md_invl_gen;
646 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
648 struct turnstile *ts;
650 ts = turnstile_trywait(&invl_gen_ts);
651 if (*m_gen > atomic_load_long(invl_gen))
652 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
654 turnstile_cancel(ts);
658 pmap_delayed_invl_finish_unblock(u_long new_gen)
660 struct turnstile *ts;
662 turnstile_chain_lock(&invl_gen_ts);
663 ts = turnstile_lookup(&invl_gen_ts);
665 pmap_invl_gen = new_gen;
667 turnstile_broadcast(ts, TS_SHARED_QUEUE);
668 turnstile_unpend(ts);
670 turnstile_chain_unlock(&invl_gen_ts);
674 * Start a new Delayed Invalidation (DI) block of code, executed by
675 * the current thread. Within a DI block, the current thread may
676 * destroy both the page table and PV list entries for a mapping and
677 * then release the corresponding PV list lock before ensuring that
678 * the mapping is flushed from the TLBs of any processors with the
682 pmap_delayed_invl_start_l(void)
684 struct pmap_invl_gen *invl_gen;
687 invl_gen = &curthread->td_md.md_invl_gen;
688 PMAP_ASSERT_NOT_IN_DI();
689 mtx_lock(&invl_gen_mtx);
690 if (LIST_EMPTY(&pmap_invl_gen_tracker))
691 currgen = pmap_invl_gen;
693 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
694 invl_gen->gen = currgen + 1;
695 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
696 mtx_unlock(&invl_gen_mtx);
700 * Finish the DI block, previously started by the current thread. All
701 * required TLB flushes for the pages marked by
702 * pmap_delayed_invl_page() must be finished before this function is
705 * This function works by bumping the global DI generation number to
706 * the generation number of the current thread's DI, unless there is a
707 * pending DI that started earlier. In the latter case, bumping the
708 * global DI generation number would incorrectly signal that the
709 * earlier DI had finished. Instead, this function bumps the earlier
710 * DI's generation number to match the generation number of the
711 * current thread's DI.
714 pmap_delayed_invl_finish_l(void)
716 struct pmap_invl_gen *invl_gen, *next;
718 invl_gen = &curthread->td_md.md_invl_gen;
719 KASSERT(invl_gen->gen != 0, ("missed invl_start"));
720 mtx_lock(&invl_gen_mtx);
721 next = LIST_NEXT(invl_gen, link);
723 pmap_delayed_invl_finish_unblock(invl_gen->gen);
725 next->gen = invl_gen->gen;
726 LIST_REMOVE(invl_gen, link);
727 mtx_unlock(&invl_gen_mtx);
732 pmap_not_in_di_u(void)
734 struct pmap_invl_gen *invl_gen;
736 invl_gen = &curthread->td_md.md_invl_gen;
737 return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
741 pmap_thread_init_invl_gen_u(struct thread *td)
743 struct pmap_invl_gen *invl_gen;
745 invl_gen = &td->td_md.md_invl_gen;
747 invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
751 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
753 uint64_t new_high, new_low, old_high, old_low;
756 old_low = new_low = 0;
757 old_high = new_high = (uintptr_t)0;
759 __asm volatile("lock;cmpxchg16b\t%1"
760 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
761 : "b"(new_low), "c" (new_high)
764 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
767 out->next = (void *)old_high;
770 out->next = (void *)new_high;
776 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
777 struct pmap_invl_gen *new_val)
779 uint64_t new_high, new_low, old_high, old_low;
782 new_low = new_val->gen;
783 new_high = (uintptr_t)new_val->next;
784 old_low = old_val->gen;
785 old_high = (uintptr_t)old_val->next;
787 __asm volatile("lock;cmpxchg16b\t%1"
788 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
789 : "b"(new_low), "c" (new_high)
794 static COUNTER_U64_DEFINE_EARLY(pv_page_count);
795 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_page_count, CTLFLAG_RD,
796 &pv_page_count, "Current number of allocated pv pages");
798 static COUNTER_U64_DEFINE_EARLY(user_pt_page_count);
799 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, user_pt_page_count, CTLFLAG_RD,
801 "Current number of allocated page table pages for userspace");
803 static COUNTER_U64_DEFINE_EARLY(kernel_pt_page_count);
804 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, kernel_pt_page_count, CTLFLAG_RD,
805 &kernel_pt_page_count,
806 "Current number of allocated page table pages for the kernel");
810 static COUNTER_U64_DEFINE_EARLY(invl_start_restart);
811 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_start_restart,
812 CTLFLAG_RD, &invl_start_restart,
813 "Number of delayed TLB invalidation request restarts");
815 static COUNTER_U64_DEFINE_EARLY(invl_finish_restart);
816 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
817 &invl_finish_restart,
818 "Number of delayed TLB invalidation completion restarts");
820 static int invl_max_qlen;
821 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
823 "Maximum delayed TLB invalidation request queue length");
826 #define di_delay locks_delay
829 pmap_delayed_invl_start_u(void)
831 struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
833 struct lock_delay_arg lda;
841 invl_gen = &td->td_md.md_invl_gen;
842 PMAP_ASSERT_NOT_IN_DI();
843 lock_delay_arg_init(&lda, &di_delay);
844 invl_gen->saved_pri = 0;
845 pri = td->td_base_pri;
848 pri = td->td_base_pri;
850 invl_gen->saved_pri = pri;
857 for (p = &pmap_invl_gen_head;; p = prev.next) {
859 prevl = (uintptr_t)atomic_load_ptr(&p->next);
860 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
861 PV_STAT(counter_u64_add(invl_start_restart, 1));
867 prev.next = (void *)prevl;
870 if ((ii = invl_max_qlen) < i)
871 atomic_cmpset_int(&invl_max_qlen, ii, i);
874 if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
875 PV_STAT(counter_u64_add(invl_start_restart, 1));
880 new_prev.gen = prev.gen;
881 new_prev.next = invl_gen;
882 invl_gen->gen = prev.gen + 1;
884 /* Formal fence between store to invl->gen and updating *p. */
885 atomic_thread_fence_rel();
888 * After inserting an invl_gen element with invalid bit set,
889 * this thread blocks any other thread trying to enter the
890 * delayed invalidation block. Do not allow to remove us from
891 * the CPU, because it causes starvation for other threads.
896 * ABA for *p is not possible there, since p->gen can only
897 * increase. So if the *p thread finished its di, then
898 * started a new one and got inserted into the list at the
899 * same place, its gen will appear greater than the previously
902 if (!pmap_di_store_invl(p, &prev, &new_prev)) {
904 PV_STAT(counter_u64_add(invl_start_restart, 1));
910 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
911 * invl_gen->next, allowing other threads to iterate past us.
912 * pmap_di_store_invl() provides fence between the generation
913 * write and the update of next.
915 invl_gen->next = NULL;
920 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
921 struct pmap_invl_gen *p)
923 struct pmap_invl_gen prev, new_prev;
927 * Load invl_gen->gen after setting invl_gen->next
928 * PMAP_INVL_GEN_NEXT_INVALID. This prevents larger
929 * generations to propagate to our invl_gen->gen. Lock prefix
930 * in atomic_set_ptr() worked as seq_cst fence.
932 mygen = atomic_load_long(&invl_gen->gen);
934 if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
937 KASSERT(prev.gen < mygen,
938 ("invalid di gen sequence %lu %lu", prev.gen, mygen));
939 new_prev.gen = mygen;
940 new_prev.next = (void *)((uintptr_t)invl_gen->next &
941 ~PMAP_INVL_GEN_NEXT_INVALID);
943 /* Formal fence between load of prev and storing update to it. */
944 atomic_thread_fence_rel();
946 return (pmap_di_store_invl(p, &prev, &new_prev));
950 pmap_delayed_invl_finish_u(void)
952 struct pmap_invl_gen *invl_gen, *p;
954 struct lock_delay_arg lda;
958 invl_gen = &td->td_md.md_invl_gen;
959 KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
960 KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
961 ("missed invl_start: INVALID"));
962 lock_delay_arg_init(&lda, &di_delay);
965 for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
966 prevl = (uintptr_t)atomic_load_ptr(&p->next);
967 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
968 PV_STAT(counter_u64_add(invl_finish_restart, 1));
972 if ((void *)prevl == invl_gen)
977 * It is legitimate to not find ourself on the list if a
978 * thread before us finished its DI and started it again.
980 if (__predict_false(p == NULL)) {
981 PV_STAT(counter_u64_add(invl_finish_restart, 1));
987 atomic_set_ptr((uintptr_t *)&invl_gen->next,
988 PMAP_INVL_GEN_NEXT_INVALID);
989 if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
990 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
991 PMAP_INVL_GEN_NEXT_INVALID);
993 PV_STAT(counter_u64_add(invl_finish_restart, 1));
998 if (atomic_load_int(&pmap_invl_waiters) > 0)
999 pmap_delayed_invl_finish_unblock(0);
1000 if (invl_gen->saved_pri != 0) {
1002 sched_prio(td, invl_gen->saved_pri);
1008 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
1010 struct pmap_invl_gen *p, *pn;
1015 for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
1017 nextl = (uintptr_t)atomic_load_ptr(&p->next);
1018 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
1019 td = first ? NULL : __containerof(p, struct thread,
1021 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
1022 (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
1023 td != NULL ? td->td_tid : -1);
1029 static COUNTER_U64_DEFINE_EARLY(invl_wait);
1030 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait,
1031 CTLFLAG_RD, &invl_wait,
1032 "Number of times DI invalidation blocked pmap_remove_all/write");
1034 static COUNTER_U64_DEFINE_EARLY(invl_wait_slow);
1035 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD,
1036 &invl_wait_slow, "Number of slow invalidation waits for lockless DI");
1042 pmap_delayed_invl_genp(vm_page_t m)
1047 pa = VM_PAGE_TO_PHYS(m);
1048 if (__predict_false((pa) > pmap_last_pa))
1049 gen = &pv_dummy_large.pv_invl_gen;
1051 gen = &(pa_to_pmdp(pa)->pv_invl_gen);
1057 pmap_delayed_invl_genp(vm_page_t m)
1060 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
1065 pmap_delayed_invl_callout_func(void *arg __unused)
1068 if (atomic_load_int(&pmap_invl_waiters) == 0)
1070 pmap_delayed_invl_finish_unblock(0);
1074 pmap_delayed_invl_callout_init(void *arg __unused)
1077 if (pmap_di_locked())
1079 callout_init(&pmap_invl_callout, 1);
1080 pmap_invl_callout_inited = true;
1082 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
1083 pmap_delayed_invl_callout_init, NULL);
1086 * Ensure that all currently executing DI blocks, that need to flush
1087 * TLB for the given page m, actually flushed the TLB at the time the
1088 * function returned. If the page m has an empty PV list and we call
1089 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1090 * valid mapping for the page m in either its page table or TLB.
1092 * This function works by blocking until the global DI generation
1093 * number catches up with the generation number associated with the
1094 * given page m and its PV list. Since this function's callers
1095 * typically own an object lock and sometimes own a page lock, it
1096 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
1100 pmap_delayed_invl_wait_l(vm_page_t m)
1104 bool accounted = false;
1107 m_gen = pmap_delayed_invl_genp(m);
1108 while (*m_gen > pmap_invl_gen) {
1111 counter_u64_add(invl_wait, 1);
1115 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1120 pmap_delayed_invl_wait_u(vm_page_t m)
1123 struct lock_delay_arg lda;
1127 m_gen = pmap_delayed_invl_genp(m);
1128 lock_delay_arg_init(&lda, &di_delay);
1129 while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1130 if (fast || !pmap_invl_callout_inited) {
1131 PV_STAT(counter_u64_add(invl_wait, 1));
1136 * The page's invalidation generation number
1137 * is still below the current thread's number.
1138 * Prepare to block so that we do not waste
1139 * CPU cycles or worse, suffer livelock.
1141 * Since it is impossible to block without
1142 * racing with pmap_delayed_invl_finish_u(),
1143 * prepare for the race by incrementing
1144 * pmap_invl_waiters and arming a 1-tick
1145 * callout which will unblock us if we lose
1148 atomic_add_int(&pmap_invl_waiters, 1);
1151 * Re-check the current thread's invalidation
1152 * generation after incrementing
1153 * pmap_invl_waiters, so that there is no race
1154 * with pmap_delayed_invl_finish_u() setting
1155 * the page generation and checking
1156 * pmap_invl_waiters. The only race allowed
1157 * is for a missed unblock, which is handled
1161 atomic_load_long(&pmap_invl_gen_head.gen)) {
1162 callout_reset(&pmap_invl_callout, 1,
1163 pmap_delayed_invl_callout_func, NULL);
1164 PV_STAT(counter_u64_add(invl_wait_slow, 1));
1165 pmap_delayed_invl_wait_block(m_gen,
1166 &pmap_invl_gen_head.gen);
1168 atomic_add_int(&pmap_invl_waiters, -1);
1173 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1176 return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1177 pmap_thread_init_invl_gen_u);
1180 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1183 return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1184 pmap_delayed_invl_start_u);
1187 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1190 return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1191 pmap_delayed_invl_finish_u);
1194 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1197 return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1198 pmap_delayed_invl_wait_u);
1202 * Mark the page m's PV list as participating in the current thread's
1203 * DI block. Any threads concurrently using m's PV list to remove or
1204 * restrict all mappings to m will wait for the current thread's DI
1205 * block to complete before proceeding.
1207 * The function works by setting the DI generation number for m's PV
1208 * list to at least the DI generation number of the current thread.
1209 * This forces a caller of pmap_delayed_invl_wait() to block until
1210 * current thread calls pmap_delayed_invl_finish().
1213 pmap_delayed_invl_page(vm_page_t m)
1217 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1218 gen = curthread->td_md.md_invl_gen.gen;
1221 m_gen = pmap_delayed_invl_genp(m);
1229 static caddr_t crashdumpmap;
1232 * Internal flags for pmap_enter()'s helper functions.
1234 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
1235 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
1238 * Internal flags for pmap_mapdev_internal() and
1239 * pmap_change_props_locked().
1241 #define MAPDEV_FLUSHCACHE 0x00000001 /* Flush cache after mapping. */
1242 #define MAPDEV_SETATTR 0x00000002 /* Modify existing attrs. */
1243 #define MAPDEV_ASSERTVALID 0x00000004 /* Assert mapping validity. */
1245 TAILQ_HEAD(pv_chunklist, pv_chunk);
1247 static void free_pv_chunk(struct pv_chunk *pc);
1248 static void free_pv_chunk_batch(struct pv_chunklist *batch);
1249 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
1250 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1251 static int popcnt_pc_map_pq(uint64_t *map);
1252 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1253 static void reserve_pv_entries(pmap_t pmap, int needed,
1254 struct rwlock **lockp);
1255 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1256 struct rwlock **lockp);
1257 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1258 u_int flags, struct rwlock **lockp);
1259 #if VM_NRESERVLEVEL > 0
1260 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1261 struct rwlock **lockp);
1263 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1264 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1267 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
1268 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1269 vm_prot_t prot, int mode, int flags);
1270 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1271 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1272 vm_offset_t va, struct rwlock **lockp);
1273 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1275 static int pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1276 vm_prot_t prot, struct rwlock **lockp);
1277 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1278 u_int flags, vm_page_t m, struct rwlock **lockp);
1279 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1280 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1281 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1282 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted);
1283 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1285 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1287 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1289 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1290 static vm_page_t pmap_large_map_getptp_unlocked(void);
1291 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1292 #if VM_NRESERVLEVEL > 0
1293 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1294 vm_page_t mpte, struct rwlock **lockp);
1296 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1298 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1299 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1301 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1302 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1303 static void pmap_pti_wire_pte(void *pte);
1304 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1305 struct spglist *free, struct rwlock **lockp);
1306 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1307 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1308 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1309 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1310 struct spglist *free);
1311 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1312 pd_entry_t *pde, struct spglist *free,
1313 struct rwlock **lockp);
1314 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1315 vm_page_t m, struct rwlock **lockp);
1316 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1318 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1320 static pd_entry_t *pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
1321 struct rwlock **lockp);
1322 static vm_page_t pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex,
1323 struct rwlock **lockp, vm_offset_t va);
1324 static vm_page_t pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex,
1325 struct rwlock **lockp, vm_offset_t va);
1326 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1327 struct rwlock **lockp);
1329 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1330 struct spglist *free);
1331 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1333 static vm_page_t pmap_alloc_pt_page(pmap_t, vm_pindex_t, int);
1334 static void pmap_free_pt_page(pmap_t, vm_page_t, bool);
1336 /********************/
1337 /* Inline functions */
1338 /********************/
1341 * Return a non-clipped indexes for a given VA, which are page table
1342 * pages indexes at the corresponding level.
1344 static __inline vm_pindex_t
1345 pmap_pde_pindex(vm_offset_t va)
1347 return (va >> PDRSHIFT);
1350 static __inline vm_pindex_t
1351 pmap_pdpe_pindex(vm_offset_t va)
1353 return (NUPDE + (va >> PDPSHIFT));
1356 static __inline vm_pindex_t
1357 pmap_pml4e_pindex(vm_offset_t va)
1359 return (NUPDE + NUPDPE + (va >> PML4SHIFT));
1362 static __inline vm_pindex_t
1363 pmap_pml5e_pindex(vm_offset_t va)
1365 return (NUPDE + NUPDPE + NUPML4E + (va >> PML5SHIFT));
1368 static __inline pml4_entry_t *
1369 pmap_pml5e(pmap_t pmap, vm_offset_t va)
1372 MPASS(pmap_is_la57(pmap));
1373 return (&pmap->pm_pmltop[pmap_pml5e_index(va)]);
1376 static __inline pml4_entry_t *
1377 pmap_pml5e_u(pmap_t pmap, vm_offset_t va)
1380 MPASS(pmap_is_la57(pmap));
1381 return (&pmap->pm_pmltopu[pmap_pml5e_index(va)]);
1384 static __inline pml4_entry_t *
1385 pmap_pml5e_to_pml4e(pml5_entry_t *pml5e, vm_offset_t va)
1387 pml4_entry_t *pml4e;
1389 /* XXX MPASS(pmap_is_la57(pmap); */
1390 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1391 return (&pml4e[pmap_pml4e_index(va)]);
1394 /* Return a pointer to the PML4 slot that corresponds to a VA */
1395 static __inline pml4_entry_t *
1396 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1398 pml5_entry_t *pml5e;
1399 pml4_entry_t *pml4e;
1402 if (pmap_is_la57(pmap)) {
1403 pml5e = pmap_pml5e(pmap, va);
1404 PG_V = pmap_valid_bit(pmap);
1405 if ((*pml5e & PG_V) == 0)
1407 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1409 pml4e = pmap->pm_pmltop;
1411 return (&pml4e[pmap_pml4e_index(va)]);
1414 static __inline pml4_entry_t *
1415 pmap_pml4e_u(pmap_t pmap, vm_offset_t va)
1417 MPASS(!pmap_is_la57(pmap));
1418 return (&pmap->pm_pmltopu[pmap_pml4e_index(va)]);
1421 /* Return a pointer to the PDP slot that corresponds to a VA */
1422 static __inline pdp_entry_t *
1423 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1427 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1428 return (&pdpe[pmap_pdpe_index(va)]);
1431 /* Return a pointer to the PDP slot that corresponds to a VA */
1432 static __inline pdp_entry_t *
1433 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1435 pml4_entry_t *pml4e;
1438 PG_V = pmap_valid_bit(pmap);
1439 pml4e = pmap_pml4e(pmap, va);
1440 if (pml4e == NULL || (*pml4e & PG_V) == 0)
1442 return (pmap_pml4e_to_pdpe(pml4e, va));
1445 /* Return a pointer to the PD slot that corresponds to a VA */
1446 static __inline pd_entry_t *
1447 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1451 KASSERT((*pdpe & PG_PS) == 0,
1452 ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
1453 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1454 return (&pde[pmap_pde_index(va)]);
1457 /* Return a pointer to the PD slot that corresponds to a VA */
1458 static __inline pd_entry_t *
1459 pmap_pde(pmap_t pmap, vm_offset_t va)
1464 PG_V = pmap_valid_bit(pmap);
1465 pdpe = pmap_pdpe(pmap, va);
1466 if (pdpe == NULL || (*pdpe & PG_V) == 0)
1468 KASSERT((*pdpe & PG_PS) == 0,
1469 ("pmap_pde for 1G page, pmap %p va %#lx", pmap, va));
1470 return (pmap_pdpe_to_pde(pdpe, va));
1473 /* Return a pointer to the PT slot that corresponds to a VA */
1474 static __inline pt_entry_t *
1475 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1479 KASSERT((*pde & PG_PS) == 0,
1480 ("%s: pde %#lx is a leaf", __func__, *pde));
1481 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1482 return (&pte[pmap_pte_index(va)]);
1485 /* Return a pointer to the PT slot that corresponds to a VA */
1486 static __inline pt_entry_t *
1487 pmap_pte(pmap_t pmap, vm_offset_t va)
1492 PG_V = pmap_valid_bit(pmap);
1493 pde = pmap_pde(pmap, va);
1494 if (pde == NULL || (*pde & PG_V) == 0)
1496 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
1497 return ((pt_entry_t *)pde);
1498 return (pmap_pde_to_pte(pde, va));
1501 static __inline void
1502 pmap_resident_count_adj(pmap_t pmap, int count)
1505 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1506 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1507 ("pmap %p resident count underflow %ld %d", pmap,
1508 pmap->pm_stats.resident_count, count));
1509 pmap->pm_stats.resident_count += count;
1512 static __inline void
1513 pmap_pt_page_count_pinit(pmap_t pmap, int count)
1515 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1516 ("pmap %p resident count underflow %ld %d", pmap,
1517 pmap->pm_stats.resident_count, count));
1518 pmap->pm_stats.resident_count += count;
1521 static __inline void
1522 pmap_pt_page_count_adj(pmap_t pmap, int count)
1524 if (pmap == kernel_pmap)
1525 counter_u64_add(kernel_pt_page_count, count);
1528 pmap_resident_count_adj(pmap, count);
1529 counter_u64_add(user_pt_page_count, count);
1533 pt_entry_t vtoptem __read_mostly = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
1534 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1) << 3;
1535 vm_offset_t PTmap __read_mostly = (vm_offset_t)P4Tmap;
1537 PMAP_INLINE pt_entry_t *
1538 vtopte(vm_offset_t va)
1540 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1542 return ((pt_entry_t *)(PTmap + ((va >> (PAGE_SHIFT - 3)) & vtoptem)));
1545 pd_entry_t vtopdem __read_mostly = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
1546 NPML4EPGSHIFT)) - 1) << 3;
1547 vm_offset_t PDmap __read_mostly = (vm_offset_t)P4Dmap;
1549 static __inline pd_entry_t *
1550 vtopde(vm_offset_t va)
1552 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1554 return ((pt_entry_t *)(PDmap + ((va >> (PDRSHIFT - 3)) & vtopdem)));
1558 allocpages(vm_paddr_t *firstaddr, int n)
1563 bzero((void *)ret, n * PAGE_SIZE);
1564 *firstaddr += n * PAGE_SIZE;
1568 CTASSERT(powerof2(NDMPML4E));
1570 /* number of kernel PDP slots */
1571 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
1574 nkpt_init(vm_paddr_t addr)
1581 pt_pages = howmany(addr - kernphys, NBPDR) + 1; /* +1 for 2M hole @0 */
1582 pt_pages += NKPDPE(pt_pages);
1585 * Add some slop beyond the bare minimum required for bootstrapping
1588 * This is quite important when allocating KVA for kernel modules.
1589 * The modules are required to be linked in the negative 2GB of
1590 * the address space. If we run out of KVA in this region then
1591 * pmap_growkernel() will need to allocate page table pages to map
1592 * the entire 512GB of KVA space which is an unnecessary tax on
1595 * Secondly, device memory mapped as part of setting up the low-
1596 * level console(s) is taken from KVA, starting at virtual_avail.
1597 * This is because cninit() is called after pmap_bootstrap() but
1598 * before vm_init() and pmap_init(). 20MB for a frame buffer is
1601 pt_pages += 32; /* 64MB additional slop. */
1607 * Returns the proper write/execute permission for a physical page that is
1608 * part of the initial boot allocations.
1610 * If the page has kernel text, it is marked as read-only. If the page has
1611 * kernel read-only data, it is marked as read-only/not-executable. If the
1612 * page has only read-write data, it is marked as read-write/not-executable.
1613 * If the page is below/above the kernel range, it is marked as read-write.
1615 * This function operates on 2M pages, since we map the kernel space that
1618 static inline pt_entry_t
1619 bootaddr_rwx(vm_paddr_t pa)
1622 * The kernel is loaded at a 2MB-aligned address, and memory below that
1623 * need not be executable. The .bss section is padded to a 2MB
1624 * boundary, so memory following the kernel need not be executable
1625 * either. Preloaded kernel modules have their mapping permissions
1626 * fixed up by the linker.
1628 if (pa < trunc_2mpage(kernphys + btext - KERNSTART) ||
1629 pa >= trunc_2mpage(kernphys + _end - KERNSTART))
1630 return (X86_PG_RW | pg_nx);
1633 * The linker should ensure that the read-only and read-write
1634 * portions don't share the same 2M page, so this shouldn't
1635 * impact read-only data. However, in any case, any page with
1636 * read-write data needs to be read-write.
1638 if (pa >= trunc_2mpage(kernphys + brwsection - KERNSTART))
1639 return (X86_PG_RW | pg_nx);
1642 * Mark any 2M page containing kernel text as read-only. Mark
1643 * other pages with read-only data as read-only and not executable.
1644 * (It is likely a small portion of the read-only data section will
1645 * be marked as read-only, but executable. This should be acceptable
1646 * since the read-only protection will keep the data from changing.)
1647 * Note that fixups to the .text section will still work until we
1650 if (pa < round_2mpage(kernphys + etext - KERNSTART))
1656 create_pagetables(vm_paddr_t *firstaddr)
1661 uint64_t DMPDkernphys;
1665 uint64_t KASANPDphys, KASANPTphys, KASANphys;
1666 vm_offset_t kasankernbase;
1667 int kasankpdpi, kasankpdi, nkasanpte;
1669 int i, j, ndm1g, nkpdpe, nkdmpde;
1671 /* Allocate page table pages for the direct map */
1672 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1673 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1675 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1676 if (ndmpdpphys > NDMPML4E) {
1678 * Each NDMPML4E allows 512 GB, so limit to that,
1679 * and then readjust ndmpdp and ndmpdpphys.
1681 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1682 Maxmem = atop(NDMPML4E * NBPML4);
1683 ndmpdpphys = NDMPML4E;
1684 ndmpdp = NDMPML4E * NPDEPG;
1686 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1688 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1690 * Calculate the number of 1G pages that will fully fit in
1693 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1696 * Allocate 2M pages for the kernel. These will be used in
1697 * place of the one or more 1G pages from ndm1g that maps
1698 * kernel memory into DMAP.
1700 nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1701 kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1702 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1705 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1706 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1708 /* Allocate pages. */
1709 KPML4phys = allocpages(firstaddr, 1);
1710 KPDPphys = allocpages(firstaddr, NKPML4E);
1712 KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1713 KASANPDphys = allocpages(firstaddr, 1);
1717 * The KMSAN shadow maps are initially left unpopulated, since there is
1718 * no need to shadow memory above KERNBASE.
1720 KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1721 KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1725 * Allocate the initial number of kernel page table pages required to
1726 * bootstrap. We defer this until after all memory-size dependent
1727 * allocations are done (e.g. direct map), so that we don't have to
1728 * build in too much slop in our estimate.
1730 * Note that when NKPML4E > 1, we have an empty page underneath
1731 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1732 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1734 nkpt_init(*firstaddr);
1735 nkpdpe = NKPDPE(nkpt);
1737 KPTphys = allocpages(firstaddr, nkpt);
1738 KPDphys = allocpages(firstaddr, nkpdpe);
1741 nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1742 KASANPTphys = allocpages(firstaddr, nkasanpte);
1743 KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1747 * Connect the zero-filled PT pages to their PD entries. This
1748 * implicitly maps the PT pages at their correct locations within
1751 pd_p = (pd_entry_t *)KPDphys;
1752 for (i = 0; i < nkpt; i++)
1753 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1756 * Map from start of the kernel in physical memory (staging
1757 * area) to the end of loader preallocated memory using 2MB
1758 * pages. This replaces some of the PD entries created above.
1759 * For compatibility, identity map 2M at the start.
1761 pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1763 for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1764 /* Preset PG_M and PG_A because demotion expects it. */
1765 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1766 X86_PG_A | bootaddr_rwx(pax);
1770 * Because we map the physical blocks in 2M pages, adjust firstaddr
1771 * to record the physical blocks we've actually mapped into kernel
1772 * virtual address space.
1774 if (*firstaddr < round_2mpage(KERNend))
1775 *firstaddr = round_2mpage(KERNend);
1777 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1778 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1779 for (i = 0; i < nkpdpe; i++)
1780 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1783 kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1784 kasankpdpi = pmap_pdpe_index(kasankernbase);
1785 kasankpdi = pmap_pde_index(kasankernbase);
1787 pdp_p = (pdp_entry_t *)KASANPDPphys;
1788 pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1790 pd_p = (pd_entry_t *)KASANPDphys;
1791 for (i = 0; i < nkasanpte; i++)
1792 pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1795 pt_p = (pt_entry_t *)KASANPTphys;
1796 for (i = 0; i < nkasanpte * NPTEPG; i++)
1797 pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1798 X86_PG_M | X86_PG_A | pg_nx;
1802 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1803 * the end of physical memory is not aligned to a 1GB page boundary,
1804 * then the residual physical memory is mapped with 2MB pages. Later,
1805 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1806 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1807 * that are partially used.
1809 pd_p = (pd_entry_t *)DMPDphys;
1810 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1811 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1812 /* Preset PG_M and PG_A because demotion expects it. */
1813 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1814 X86_PG_M | X86_PG_A | pg_nx;
1816 pdp_p = (pdp_entry_t *)DMPDPphys;
1817 for (i = 0; i < ndm1g; i++) {
1818 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1819 /* Preset PG_M and PG_A because demotion expects it. */
1820 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1821 X86_PG_M | X86_PG_A | pg_nx;
1823 for (j = 0; i < ndmpdp; i++, j++) {
1824 pdp_p[i] = DMPDphys + ptoa(j);
1825 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1829 * Instead of using a 1G page for the memory containing the kernel,
1830 * use 2M pages with read-only and no-execute permissions. (If using 1G
1831 * pages, this will partially overwrite the PDPEs above.)
1834 pd_p = (pd_entry_t *)DMPDkernphys;
1835 for (i = 0, pax = rounddown2(kernphys, NBPDP);
1836 i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1837 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1838 X86_PG_A | pg_nx | bootaddr_rwx(pax);
1840 j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1841 for (i = 0; i < nkdmpde; i++) {
1842 pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1843 X86_PG_RW | X86_PG_V | pg_nx;
1847 /* And recursively map PML4 to itself in order to get PTmap */
1848 p4_p = (pml4_entry_t *)KPML4phys;
1849 p4_p[PML4PML4I] = KPML4phys;
1850 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1853 /* Connect the KASAN shadow map slots up to the PML4. */
1854 for (i = 0; i < NKASANPML4E; i++) {
1855 p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1856 p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1861 /* Connect the KMSAN shadow map slots up to the PML4. */
1862 for (i = 0; i < NKMSANSHADPML4E; i++) {
1863 p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1864 p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1867 /* Connect the KMSAN origin map slots up to the PML4. */
1868 for (i = 0; i < NKMSANORIGPML4E; i++) {
1869 p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1870 p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1874 /* Connect the Direct Map slots up to the PML4. */
1875 for (i = 0; i < ndmpdpphys; i++) {
1876 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1877 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1880 /* Connect the KVA slots up to the PML4 */
1881 for (i = 0; i < NKPML4E; i++) {
1882 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1883 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1886 kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1890 * Bootstrap the system enough to run with virtual memory.
1892 * On amd64 this is called after mapping has already been enabled
1893 * and just syncs the pmap module with what has already been done.
1894 * [We can't call it easily with mapping off since the kernel is not
1895 * mapped with PA == VA, hence we would have to relocate every address
1896 * from the linked base (virtual) address "KERNBASE" to the actual
1897 * (physical) address starting relative to 0]
1900 pmap_bootstrap(vm_paddr_t *firstaddr)
1903 pt_entry_t *pte, *pcpu_pte;
1904 struct region_descriptor r_gdt;
1905 uint64_t cr4, pcpu0_phys;
1909 KERNend = *firstaddr;
1910 res = atop(KERNend - (vm_paddr_t)kernphys);
1916 * Create an initial set of page tables to run the kernel in.
1918 create_pagetables(firstaddr);
1920 pcpu0_phys = allocpages(firstaddr, 1);
1923 * Add a physical memory segment (vm_phys_seg) corresponding to the
1924 * preallocated kernel page table pages so that vm_page structures
1925 * representing these pages will be created. The vm_page structures
1926 * are required for promotion of the corresponding kernel virtual
1927 * addresses to superpage mappings.
1929 vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1932 * Account for the virtual addresses mapped by create_pagetables().
1934 virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1935 (vm_paddr_t)kernphys);
1936 virtual_end = VM_MAX_KERNEL_ADDRESS;
1939 * Enable PG_G global pages, then switch to the kernel page
1940 * table from the bootstrap page table. After the switch, it
1941 * is possible to enable SMEP and SMAP since PG_U bits are
1947 load_cr3(KPML4phys);
1948 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1950 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1955 * Initialize the kernel pmap (which is statically allocated).
1956 * Count bootstrap data as being resident in case any of this data is
1957 * later unmapped (using pmap_remove()) and freed.
1959 PMAP_LOCK_INIT(kernel_pmap);
1960 kernel_pmap->pm_pmltop = kernel_pml4;
1961 kernel_pmap->pm_cr3 = KPML4phys;
1962 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1963 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1964 kernel_pmap->pm_stats.resident_count = res;
1965 kernel_pmap->pm_flags = pmap_flags;
1968 * The kernel pmap is always active on all CPUs. Once CPUs are
1969 * enumerated, the mask will be set equal to all_cpus.
1971 CPU_FILL(&kernel_pmap->pm_active);
1974 * Initialize the TLB invalidations generation number lock.
1976 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1979 * Reserve some special page table entries/VA space for temporary
1982 #define SYSMAP(c, p, v, n) \
1983 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1989 * Crashdump maps. The first page is reused as CMAP1 for the
1992 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1993 CADDR1 = crashdumpmap;
1995 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
1999 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2000 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2001 * number of CPUs and NUMA affinity.
2003 pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2004 X86_PG_M | X86_PG_A;
2005 for (i = 1; i < MAXCPU; i++)
2009 * Re-initialize PCPU area for BSP after switching.
2010 * Make hardware use gdt and common_tss from the new PCPU.
2012 STAILQ_INIT(&cpuhead);
2013 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2014 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2015 amd64_bsp_pcpu_init1(&__pcpu[0]);
2016 amd64_bsp_ist_init(&__pcpu[0]);
2017 __pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2019 memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2020 sizeof(struct user_segment_descriptor));
2021 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2022 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2023 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2024 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2025 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2027 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2028 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2029 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2030 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2033 * Initialize the PAT MSR.
2034 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2035 * side-effect, invalidates stale PG_G TLB entries that might
2036 * have been created in our pre-boot environment.
2040 /* Initialize TLB Context Id. */
2041 if (pmap_pcid_enabled) {
2042 kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2043 offsetof(struct pcpu, pc_kpmap_store);
2045 PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2046 PCPU_SET(kpmap_store.pm_gen, 1);
2049 * PMAP_PCID_KERN + 1 is used for initialization of
2050 * proc0 pmap. The pmap' pcid state might be used by
2051 * EFIRT entry before first context switch, so it
2052 * needs to be valid.
2054 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2055 PCPU_SET(pcid_gen, 1);
2058 * pcpu area for APs is zeroed during AP startup.
2059 * pc_pcid_next and pc_pcid_gen are initialized by AP
2060 * during pcpu setup.
2062 load_cr4(rcr4() | CR4_PCIDE);
2067 * Setup the PAT MSR.
2076 /* Bail if this CPU doesn't implement PAT. */
2077 if ((cpu_feature & CPUID_PAT) == 0)
2080 /* Set default PAT index table. */
2081 for (i = 0; i < PAT_INDEX_SIZE; i++)
2083 pat_index[PAT_WRITE_BACK] = 0;
2084 pat_index[PAT_WRITE_THROUGH] = 1;
2085 pat_index[PAT_UNCACHEABLE] = 3;
2086 pat_index[PAT_WRITE_COMBINING] = 6;
2087 pat_index[PAT_WRITE_PROTECTED] = 5;
2088 pat_index[PAT_UNCACHED] = 2;
2091 * Initialize default PAT entries.
2092 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2093 * Program 5 and 6 as WP and WC.
2095 * Leave 4 and 7 as WB and UC. Note that a recursive page table
2096 * mapping for a 2M page uses a PAT value with the bit 3 set due
2097 * to its overload with PG_PS.
2099 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2100 PAT_VALUE(1, PAT_WRITE_THROUGH) |
2101 PAT_VALUE(2, PAT_UNCACHED) |
2102 PAT_VALUE(3, PAT_UNCACHEABLE) |
2103 PAT_VALUE(4, PAT_WRITE_BACK) |
2104 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2105 PAT_VALUE(6, PAT_WRITE_COMBINING) |
2106 PAT_VALUE(7, PAT_UNCACHEABLE);
2110 load_cr4(cr4 & ~CR4_PGE);
2112 /* Disable caches (CD = 1, NW = 0). */
2114 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2116 /* Flushes caches and TLBs. */
2120 /* Update PAT and index table. */
2121 wrmsr(MSR_PAT, pat_msr);
2123 /* Flush caches and TLBs again. */
2127 /* Restore caches and PGE. */
2133 pmap_page_alloc_below_4g(bool zeroed)
2135 return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2136 1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2139 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2140 la57_trampoline_gdt[], la57_trampoline_end[];
2143 pmap_bootstrap_la57(void *arg __unused)
2146 pml5_entry_t *v_pml5;
2147 pml4_entry_t *v_pml4;
2151 vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2152 void (*la57_tramp)(uint64_t pml5);
2153 struct region_descriptor r_gdt;
2155 if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2157 TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2161 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2162 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2164 m_code = pmap_page_alloc_below_4g(true);
2165 v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2166 m_pml5 = pmap_page_alloc_below_4g(true);
2167 KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2168 v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2169 m_pml4 = pmap_page_alloc_below_4g(true);
2170 v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2171 m_pdp = pmap_page_alloc_below_4g(true);
2172 v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2173 m_pd = pmap_page_alloc_below_4g(true);
2174 v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2175 m_pt = pmap_page_alloc_below_4g(true);
2176 v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2179 * Map m_code 1:1, it appears below 4G in KVA due to physical
2180 * address being below 4G. Since kernel KVA is in upper half,
2181 * the pml4e should be zero and free for temporary use.
2183 kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2184 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2186 v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2187 VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2189 v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2190 VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2192 v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2193 VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2197 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2198 * entering all existing kernel mappings into level 5 table.
2200 v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2201 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g;
2204 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2206 v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2207 VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2209 v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2210 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2214 * Copy and call the 48->57 trampoline, hope we return there, alive.
2216 bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2217 *(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2218 la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2219 la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2220 invlpg((vm_offset_t)la57_tramp);
2221 la57_tramp(KPML5phys);
2224 * gdt was necessary reset, switch back to our gdt.
2227 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2231 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2232 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2233 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2236 * Now unmap the trampoline, and free the pages.
2237 * Clear pml5 entry used for 1:1 trampoline mapping.
2239 pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2240 invlpg((vm_offset_t)v_code);
2241 vm_page_free(m_code);
2242 vm_page_free(m_pdp);
2247 * Recursively map PML5 to itself in order to get PTmap and
2250 v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2252 vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2253 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2254 PTmap = (vm_offset_t)P5Tmap;
2255 vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2256 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2257 PDmap = (vm_offset_t)P5Dmap;
2259 kernel_pmap->pm_cr3 = KPML5phys;
2260 kernel_pmap->pm_pmltop = v_pml5;
2261 pmap_pt_page_count_adj(kernel_pmap, 1);
2263 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2266 * Initialize a vm_page's machine-dependent fields.
2269 pmap_page_init(vm_page_t m)
2272 TAILQ_INIT(&m->md.pv_list);
2273 m->md.pat_mode = PAT_WRITE_BACK;
2276 static int pmap_allow_2m_x_ept;
2277 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2278 &pmap_allow_2m_x_ept, 0,
2279 "Allow executable superpage mappings in EPT");
2282 pmap_allow_2m_x_ept_recalculate(void)
2285 * SKL002, SKL012S. Since the EPT format is only used by
2286 * Intel CPUs, the vendor check is merely a formality.
2288 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2289 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2290 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2291 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
2292 CPUID_TO_MODEL(cpu_id) == 0x27 ||
2293 CPUID_TO_MODEL(cpu_id) == 0x35 ||
2294 CPUID_TO_MODEL(cpu_id) == 0x36 ||
2295 CPUID_TO_MODEL(cpu_id) == 0x37 ||
2296 CPUID_TO_MODEL(cpu_id) == 0x86 ||
2297 CPUID_TO_MODEL(cpu_id) == 0x1c ||
2298 CPUID_TO_MODEL(cpu_id) == 0x4a ||
2299 CPUID_TO_MODEL(cpu_id) == 0x4c ||
2300 CPUID_TO_MODEL(cpu_id) == 0x4d ||
2301 CPUID_TO_MODEL(cpu_id) == 0x5a ||
2302 CPUID_TO_MODEL(cpu_id) == 0x5c ||
2303 CPUID_TO_MODEL(cpu_id) == 0x5d ||
2304 CPUID_TO_MODEL(cpu_id) == 0x5f ||
2305 CPUID_TO_MODEL(cpu_id) == 0x6e ||
2306 CPUID_TO_MODEL(cpu_id) == 0x7a ||
2307 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
2308 CPUID_TO_MODEL(cpu_id) == 0x85))))
2309 pmap_allow_2m_x_ept = 1;
2310 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2314 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2317 return (pmap->pm_type != PT_EPT || !executable ||
2318 !pmap_allow_2m_x_ept);
2323 pmap_init_pv_table(void)
2325 struct pmap_large_md_page *pvd;
2327 long start, end, highest, pv_npg;
2328 int domain, i, j, pages;
2331 * For correctness we depend on the size being evenly divisible into a
2332 * page. As a tradeoff between performance and total memory use, the
2333 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2334 * avoids false-sharing, but not being 128 bytes potentially allows for
2335 * avoidable traffic due to adjacent cacheline prefetcher.
2337 * Assert the size so that accidental changes fail to compile.
2339 CTASSERT((sizeof(*pvd) == 64));
2342 * Calculate the size of the array.
2344 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2345 pv_npg = howmany(pmap_last_pa, NBPDR);
2346 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2348 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2349 if (pv_table == NULL)
2350 panic("%s: kva_alloc failed\n", __func__);
2353 * Iterate physical segments to allocate space for respective pages.
2357 for (i = 0; i < vm_phys_nsegs; i++) {
2358 end = vm_phys_segs[i].end / NBPDR;
2359 domain = vm_phys_segs[i].domain;
2364 start = highest + 1;
2365 pvd = &pv_table[start];
2367 pages = end - start + 1;
2368 s = round_page(pages * sizeof(*pvd));
2369 highest = start + (s / sizeof(*pvd)) - 1;
2371 for (j = 0; j < s; j += PAGE_SIZE) {
2372 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2374 panic("failed to allocate PV table page");
2375 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2378 for (j = 0; j < s / sizeof(*pvd); j++) {
2379 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2380 TAILQ_INIT(&pvd->pv_page.pv_list);
2381 pvd->pv_page.pv_gen = 0;
2382 pvd->pv_page.pat_mode = 0;
2383 pvd->pv_invl_gen = 0;
2387 pvd = &pv_dummy_large;
2388 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2389 TAILQ_INIT(&pvd->pv_page.pv_list);
2390 pvd->pv_page.pv_gen = 0;
2391 pvd->pv_page.pat_mode = 0;
2392 pvd->pv_invl_gen = 0;
2396 pmap_init_pv_table(void)
2402 * Initialize the pool of pv list locks.
2404 for (i = 0; i < NPV_LIST_LOCKS; i++)
2405 rw_init(&pv_list_locks[i], "pmap pv list");
2408 * Calculate the size of the pv head table for superpages.
2410 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2413 * Allocate memory for the pv head table for superpages.
2415 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2417 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2418 for (i = 0; i < pv_npg; i++)
2419 TAILQ_INIT(&pv_table[i].pv_list);
2420 TAILQ_INIT(&pv_dummy.pv_list);
2425 * Initialize the pmap module.
2426 * Called by vm_init, to initialize any structures that the pmap
2427 * system needs to map virtual memory.
2432 struct pmap_preinit_mapping *ppim;
2434 int error, i, ret, skz63;
2436 /* L1TF, reserve page @0 unconditionally */
2437 vm_page_blacklist_add(0, bootverbose);
2439 /* Detect bare-metal Skylake Server and Skylake-X. */
2440 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2441 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2443 * Skylake-X errata SKZ63. Processor May Hang When
2444 * Executing Code In an HLE Transaction Region between
2445 * 40000000H and 403FFFFFH.
2447 * Mark the pages in the range as preallocated. It
2448 * seems to be impossible to distinguish between
2449 * Skylake Server and Skylake X.
2452 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2455 printf("SKZ63: skipping 4M RAM starting "
2456 "at physical 1G\n");
2457 for (i = 0; i < atop(0x400000); i++) {
2458 ret = vm_page_blacklist_add(0x40000000 +
2460 if (!ret && bootverbose)
2461 printf("page at %#lx already used\n",
2462 0x40000000 + ptoa(i));
2468 pmap_allow_2m_x_ept_recalculate();
2471 * Initialize the vm page array entries for the kernel pmap's
2474 PMAP_LOCK(kernel_pmap);
2475 for (i = 0; i < nkpt; i++) {
2476 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2477 KASSERT(mpte >= vm_page_array &&
2478 mpte < &vm_page_array[vm_page_array_size],
2479 ("pmap_init: page table page is out of range"));
2480 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2481 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2482 mpte->ref_count = 1;
2485 * Collect the page table pages that were replaced by a 2MB
2486 * page in create_pagetables(). They are zero filled.
2489 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2490 pmap_insert_pt_page(kernel_pmap, mpte, false))
2491 panic("pmap_init: pmap_insert_pt_page failed");
2493 PMAP_UNLOCK(kernel_pmap);
2497 * If the kernel is running on a virtual machine, then it must assume
2498 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2499 * be prepared for the hypervisor changing the vendor and family that
2500 * are reported by CPUID. Consequently, the workaround for AMD Family
2501 * 10h Erratum 383 is enabled if the processor's feature set does not
2502 * include at least one feature that is only supported by older Intel
2503 * or newer AMD processors.
2505 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2506 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2507 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2509 workaround_erratum383 = 1;
2512 * Are large page mappings enabled?
2514 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2515 if (pg_ps_enabled) {
2516 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2517 ("pmap_init: can't assign to pagesizes[1]"));
2518 pagesizes[1] = NBPDR;
2519 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2520 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2521 ("pmap_init: can't assign to pagesizes[2]"));
2522 pagesizes[2] = NBPDP;
2527 * Initialize pv chunk lists.
2529 for (i = 0; i < PMAP_MEMDOM; i++) {
2530 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2531 TAILQ_INIT(&pv_chunks[i].pvc_list);
2533 pmap_init_pv_table();
2535 pmap_initialized = 1;
2536 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2537 ppim = pmap_preinit_mapping + i;
2540 /* Make the direct map consistent */
2541 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2542 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2543 ppim->sz, ppim->mode);
2547 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2548 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2551 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2552 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2553 (vmem_addr_t *)&qframe);
2555 panic("qframe allocation failed");
2558 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2559 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2560 lm_ents = LMEPML4I - LMSPML4I + 1;
2562 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2564 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2565 lm_ents, KMSANORIGPML4I - LMSPML4I);
2566 lm_ents = KMSANORIGPML4I - LMSPML4I;
2570 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2571 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2573 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2574 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2575 if (large_vmem == NULL) {
2576 printf("pmap: cannot create large map\n");
2579 for (i = 0; i < lm_ents; i++) {
2580 m = pmap_large_map_getptp_unlocked();
2582 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2583 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2589 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2590 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2591 "Maximum number of PML4 entries for use by large map (tunable). "
2592 "Each entry corresponds to 512GB of address space.");
2594 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2595 "2MB page mapping counters");
2597 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2598 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2599 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2601 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2602 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2603 &pmap_pde_mappings, "2MB page mappings");
2605 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2606 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2607 &pmap_pde_p_failures, "2MB page promotion failures");
2609 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2610 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2611 &pmap_pde_promotions, "2MB page promotions");
2613 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2614 "1GB page mapping counters");
2616 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2617 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2618 &pmap_pdpe_demotions, "1GB page demotions");
2620 /***************************************************
2621 * Low level helper routines.....
2622 ***************************************************/
2625 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2627 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2629 switch (pmap->pm_type) {
2632 /* Verify that both PAT bits are not set at the same time */
2633 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2634 ("Invalid PAT bits in entry %#lx", entry));
2636 /* Swap the PAT bits if one of them is set */
2637 if ((entry & x86_pat_bits) != 0)
2638 entry ^= x86_pat_bits;
2642 * Nothing to do - the memory attributes are represented
2643 * the same way for regular pages and superpages.
2647 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2654 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2657 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2658 pat_index[(int)mode] >= 0);
2662 * Determine the appropriate bits to set in a PTE or PDE for a specified
2666 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2668 int cache_bits, pat_flag, pat_idx;
2670 if (!pmap_is_valid_memattr(pmap, mode))
2671 panic("Unknown caching mode %d\n", mode);
2673 switch (pmap->pm_type) {
2676 /* The PAT bit is different for PTE's and PDE's. */
2677 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2679 /* Map the caching mode to a PAT index. */
2680 pat_idx = pat_index[mode];
2682 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2685 cache_bits |= pat_flag;
2687 cache_bits |= PG_NC_PCD;
2689 cache_bits |= PG_NC_PWT;
2693 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2697 panic("unsupported pmap type %d", pmap->pm_type);
2700 return (cache_bits);
2704 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2708 switch (pmap->pm_type) {
2711 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2714 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2717 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2724 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2726 int pat_flag, pat_idx;
2729 switch (pmap->pm_type) {
2732 /* The PAT bit is different for PTE's and PDE's. */
2733 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2735 if ((pte & pat_flag) != 0)
2737 if ((pte & PG_NC_PCD) != 0)
2739 if ((pte & PG_NC_PWT) != 0)
2743 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2744 panic("EPT PTE %#lx has no PAT memory type", pte);
2745 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2749 /* See pmap_init_pat(). */
2759 pmap_ps_enabled(pmap_t pmap)
2762 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2766 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2769 switch (pmap->pm_type) {
2776 * This is a little bogus since the generation number is
2777 * supposed to be bumped up when a region of the address
2778 * space is invalidated in the page tables.
2780 * In this case the old PDE entry is valid but yet we want
2781 * to make sure that any mappings using the old entry are
2782 * invalidated in the TLB.
2784 * The reason this works as expected is because we rendezvous
2785 * "all" host cpus and force any vcpu context to exit as a
2788 atomic_add_long(&pmap->pm_eptgen, 1);
2791 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2793 pde_store(pde, newpde);
2797 * After changing the page size for the specified virtual address in the page
2798 * table, flush the corresponding entries from the processor's TLB. Only the
2799 * calling processor's TLB is affected.
2801 * The calling thread must be pinned to a processor.
2804 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2808 if (pmap_type_guest(pmap))
2811 KASSERT(pmap->pm_type == PT_X86,
2812 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2814 PG_G = pmap_global_bit(pmap);
2816 if ((newpde & PG_PS) == 0)
2817 /* Demotion: flush a specific 2MB page mapping. */
2818 pmap_invlpg(pmap, va);
2819 else if ((newpde & PG_G) == 0)
2821 * Promotion: flush every 4KB page mapping from the TLB
2822 * because there are too many to flush individually.
2827 * Promotion: flush every 4KB page mapping from the TLB,
2828 * including any global (PG_G) mappings.
2835 * The amd64 pmap uses different approaches to TLB invalidation
2836 * depending on the kernel configuration, available hardware features,
2837 * and known hardware errata. The kernel configuration option that
2838 * has the greatest operational impact on TLB invalidation is PTI,
2839 * which is enabled automatically on affected Intel CPUs. The most
2840 * impactful hardware features are first PCID, and then INVPCID
2841 * instruction presence. PCID usage is quite different for PTI
2844 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2845 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2846 * space is served by two page tables, user and kernel. The user
2847 * page table only maps user space and a kernel trampoline. The
2848 * kernel trampoline includes the entirety of the kernel text but
2849 * only the kernel data that is needed to switch from user to kernel
2850 * mode. The kernel page table maps the user and kernel address
2851 * spaces in their entirety. It is identical to the per-process
2852 * page table used in non-PTI mode.
2854 * User page tables are only used when the CPU is in user mode.
2855 * Consequently, some TLB invalidations can be postponed until the
2856 * switch from kernel to user mode. In contrast, the user
2857 * space part of the kernel page table is used for copyout(9), so
2858 * TLB invalidations on this page table cannot be similarly postponed.
2860 * The existence of a user mode page table for the given pmap is
2861 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2862 * which case pm_ucr3 contains the %cr3 register value for the user
2863 * mode page table's root.
2865 * * The pm_active bitmask indicates which CPUs currently have the
2866 * pmap active. A CPU's bit is set on context switch to the pmap, and
2867 * cleared on switching off this CPU. For the kernel page table,
2868 * the pm_active field is immutable and contains all CPUs. The
2869 * kernel page table is always logically active on every processor,
2870 * but not necessarily in use by the hardware, e.g., in PTI mode.
2872 * When requesting invalidation of virtual addresses with
2873 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2874 * all CPUs recorded as active in pm_active. Updates to and reads
2875 * from pm_active are not synchronized, and so they may race with
2876 * each other. Shootdown handlers are prepared to handle the race.
2878 * * PCID is an optional feature of the long mode x86 MMU where TLB
2879 * entries are tagged with the 'Process ID' of the address space
2880 * they belong to. This feature provides a limited namespace for
2881 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2884 * Allocation of a PCID to a pmap is done by an algorithm described
2885 * in section 15.12, "Other TLB Consistency Algorithms", of
2886 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2887 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2888 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2889 * the CPU is about to start caching TLB entries from a pmap,
2890 * i.e., on the context switch that activates the pmap on the CPU.
2892 * The PCID allocator maintains a per-CPU, per-pmap generation
2893 * count, pm_gen, which is incremented each time a new PCID is
2894 * allocated. On TLB invalidation, the generation counters for the
2895 * pmap are zeroed, which signals the context switch code that the
2896 * previously allocated PCID is no longer valid. Effectively,
2897 * zeroing any of these counters triggers a TLB shootdown for the
2898 * given CPU/address space, due to the allocation of a new PCID.
2900 * Zeroing can be performed remotely. Consequently, if a pmap is
2901 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2902 * be initiated by an ordinary memory access to reset the target
2903 * CPU's generation count within the pmap. The CPU initiating the
2904 * TLB shootdown does not need to send an IPI to the target CPU.
2906 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2907 * for complete (kernel) page tables, and PCIDs for user mode page
2908 * tables. A user PCID value is obtained from the kernel PCID value
2909 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2911 * User space page tables are activated on return to user mode, by
2912 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2913 * clearing bit 63 of the loaded ucr3, this effectively causes
2914 * complete invalidation of the user mode TLB entries for the
2915 * current pmap. In which case, local invalidations of individual
2916 * pages in the user page table are skipped.
2918 * * Local invalidation, all modes. If the requested invalidation is
2919 * for a specific address or the total invalidation of a currently
2920 * active pmap, then the TLB is flushed using INVLPG for a kernel
2921 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2922 * user space page table(s).
2924 * If the INVPCID instruction is available, it is used to flush user
2925 * entries from the kernel page table.
2927 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2928 * entries for the given page that either match the current PCID or
2929 * are global. Since TLB entries for the same page under different
2930 * PCIDs are unaffected, kernel pages which reside in all address
2931 * spaces could be problematic. We avoid the problem by creating
2932 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2935 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2936 * address space, all other 4095 PCIDs are used for user mode spaces
2937 * as described above. A context switch allocates a new PCID if
2938 * the recorded PCID is zero or the recorded generation does not match
2939 * the CPU's generation, effectively flushing the TLB for this address space.
2940 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2941 * local user page: INVLPG
2942 * local kernel page: INVLPG
2943 * local user total: INVPCID(CTX)
2944 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2945 * remote user page, inactive pmap: zero pm_gen
2946 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2947 * (Both actions are required to handle the aforementioned pm_active races.)
2948 * remote kernel page: IPI:INVLPG
2949 * remote user total, inactive pmap: zero pm_gen
2950 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2952 * (See note above about pm_active races.)
2953 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2955 * PTI enabled, PCID present.
2956 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2958 * local kernel page: INVLPG
2959 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
2960 * on loading UCR3 into %cr3 for upt
2961 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2962 * remote user page, inactive pmap: zero pm_gen
2963 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
2964 * INVPCID(ADDR) for upt)
2965 * remote kernel page: IPI:INVLPG
2966 * remote user total, inactive pmap: zero pm_gen
2967 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
2968 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
2969 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2972 * local user page: INVLPG
2973 * local kernel page: INVLPG
2974 * local user total: reload %cr3
2975 * local kernel total: invltlb_glob()
2976 * remote user page, inactive pmap: -
2977 * remote user page, active pmap: IPI:INVLPG
2978 * remote kernel page: IPI:INVLPG
2979 * remote user total, inactive pmap: -
2980 * remote user total, active pmap: IPI:(reload %cr3)
2981 * remote kernel total: IPI:invltlb_glob()
2982 * Since on return to user mode, the reload of %cr3 with ucr3 causes
2983 * TLB invalidation, no specific action is required for user page table.
2985 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
2991 * Interrupt the cpus that are executing in the guest context.
2992 * This will force the vcpu to exit and the cached EPT mappings
2993 * will be invalidated by the host before the next vmresume.
2995 static __inline void
2996 pmap_invalidate_ept(pmap_t pmap)
3002 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3003 ("pmap_invalidate_ept: absurd pm_active"));
3006 * The TLB mappings associated with a vcpu context are not
3007 * flushed each time a different vcpu is chosen to execute.
3009 * This is in contrast with a process's vtop mappings that
3010 * are flushed from the TLB on each context switch.
3012 * Therefore we need to do more than just a TLB shootdown on
3013 * the active cpus in 'pmap->pm_active'. To do this we keep
3014 * track of the number of invalidations performed on this pmap.
3016 * Each vcpu keeps a cache of this counter and compares it
3017 * just before a vmresume. If the counter is out-of-date an
3018 * invept will be done to flush stale mappings from the TLB.
3020 * To ensure that all vCPU threads have observed the new counter
3021 * value before returning, we use SMR. Ordering is important here:
3022 * the VMM enters an SMR read section before loading the counter
3023 * and after updating the pm_active bit set. Thus, pm_active is
3024 * a superset of active readers, and any reader that has observed
3025 * the goal has observed the new counter value.
3027 atomic_add_long(&pmap->pm_eptgen, 1);
3029 goal = smr_advance(pmap->pm_eptsmr);
3032 * Force the vcpu to exit and trap back into the hypervisor.
3034 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3035 ipi_selected(pmap->pm_active, ipinum);
3039 * Ensure that all active vCPUs will observe the new generation counter
3040 * value before executing any more guest instructions.
3042 smr_wait(pmap->pm_eptsmr, goal);
3046 pmap_invalidate_preipi_pcid(pmap_t pmap)
3048 struct pmap_pcid *pcidp;
3053 cpuid = PCPU_GET(cpuid);
3054 if (pmap != PCPU_GET(curpmap))
3055 cpuid = 0xffffffff; /* An impossible value */
3059 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3065 * The fence is between stores to pm_gen and the read of the
3066 * pm_active mask. We need to ensure that it is impossible
3067 * for us to miss the bit update in pm_active and
3068 * simultaneously observe a non-zero pm_gen in
3069 * pmap_activate_sw(), otherwise TLB update is missed.
3070 * Without the fence, IA32 allows such an outcome. Note that
3071 * pm_active is updated by a locked operation, which provides
3072 * the reciprocal fence.
3074 atomic_thread_fence_seq_cst();
3078 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3083 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3085 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3086 pmap_invalidate_preipi_nopcid);
3090 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3091 const bool invpcid_works1)
3093 struct invpcid_descr d;
3094 uint64_t kcr3, ucr3;
3098 * Because pm_pcid is recalculated on a context switch, we
3099 * must ensure there is no preemption, not just pinning.
3100 * Otherwise, we might use a stale value below.
3102 CRITICAL_ASSERT(curthread);
3105 * No need to do anything with user page tables invalidation
3106 * if there is no user page table, or invalidation is deferred
3107 * until the return to userspace. ucr3_load_mask is stable
3108 * because we have preemption disabled.
3110 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3111 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3114 pcid = pmap_get_pcid(pmap);
3115 if (invpcid_works1) {
3116 d.pcid = pcid | PMAP_PCID_USER_PT;
3119 invpcid(&d, INVPCID_ADDR);
3121 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3122 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3123 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3128 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3130 pmap_invalidate_page_pcid_cb(pmap, va, true);
3134 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3136 pmap_invalidate_page_pcid_cb(pmap, va, false);
3140 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3144 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3146 if (pmap_pcid_enabled)
3147 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3148 pmap_invalidate_page_pcid_noinvpcid_cb);
3149 return (pmap_invalidate_page_nopcid_cb);
3153 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3154 vm_offset_t addr2 __unused)
3156 if (pmap == kernel_pmap) {
3157 pmap_invlpg(kernel_pmap, va);
3158 } else if (pmap == PCPU_GET(curpmap)) {
3160 pmap_invalidate_page_cb(pmap, va);
3165 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3167 if (pmap_type_guest(pmap)) {
3168 pmap_invalidate_ept(pmap);
3172 KASSERT(pmap->pm_type == PT_X86,
3173 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3175 pmap_invalidate_preipi(pmap);
3176 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3179 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3180 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3183 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3184 const bool invpcid_works1)
3186 struct invpcid_descr d;
3187 uint64_t kcr3, ucr3;
3190 CRITICAL_ASSERT(curthread);
3192 if (pmap != PCPU_GET(curpmap) ||
3193 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3194 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3197 pcid = pmap_get_pcid(pmap);
3198 if (invpcid_works1) {
3199 d.pcid = pcid | PMAP_PCID_USER_PT;
3201 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3202 invpcid(&d, INVPCID_ADDR);
3204 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3205 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3206 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3211 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3214 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3218 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3221 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3225 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3226 vm_offset_t eva __unused)
3230 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3233 if (pmap_pcid_enabled)
3234 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3235 pmap_invalidate_range_pcid_noinvpcid_cb);
3236 return (pmap_invalidate_range_nopcid_cb);
3240 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3244 if (pmap == kernel_pmap) {
3245 if (PCPU_GET(pcid_invlpg_workaround)) {
3246 struct invpcid_descr d = { 0 };
3248 invpcid(&d, INVPCID_CTXGLOB);
3250 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3253 } else if (pmap == PCPU_GET(curpmap)) {
3254 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3256 pmap_invalidate_range_cb(pmap, sva, eva);
3261 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3263 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3264 pmap_invalidate_all(pmap);
3268 if (pmap_type_guest(pmap)) {
3269 pmap_invalidate_ept(pmap);
3273 KASSERT(pmap->pm_type == PT_X86,
3274 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3276 pmap_invalidate_preipi(pmap);
3277 smp_masked_invlpg_range(sva, eva, pmap,
3278 pmap_invalidate_range_curcpu_cb);
3282 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3284 struct invpcid_descr d;
3288 if (pmap == kernel_pmap) {
3289 if (invpcid_works1) {
3290 bzero(&d, sizeof(d));
3291 invpcid(&d, INVPCID_CTXGLOB);
3295 } else if (pmap == PCPU_GET(curpmap)) {
3296 CRITICAL_ASSERT(curthread);
3298 pcid = pmap_get_pcid(pmap);
3299 if (invpcid_works1) {
3303 invpcid(&d, INVPCID_CTX);
3305 kcr3 = pmap->pm_cr3 | pcid;
3308 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3309 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3314 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3316 pmap_invalidate_all_pcid_cb(pmap, true);
3320 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3322 pmap_invalidate_all_pcid_cb(pmap, false);
3326 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3328 if (pmap == kernel_pmap)
3330 else if (pmap == PCPU_GET(curpmap))
3334 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3336 if (pmap_pcid_enabled)
3337 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3338 pmap_invalidate_all_pcid_noinvpcid_cb);
3339 return (pmap_invalidate_all_nopcid_cb);
3343 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3344 vm_offset_t addr2 __unused)
3346 pmap_invalidate_all_cb(pmap);
3350 pmap_invalidate_all(pmap_t pmap)
3352 if (pmap_type_guest(pmap)) {
3353 pmap_invalidate_ept(pmap);
3357 KASSERT(pmap->pm_type == PT_X86,
3358 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3360 pmap_invalidate_preipi(pmap);
3361 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3365 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3366 vm_offset_t addr2 __unused)
3372 pmap_invalidate_cache(void)
3375 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3379 cpuset_t invalidate; /* processors that invalidate their TLB */
3384 u_int store; /* processor that updates the PDE */
3388 pmap_update_pde_action(void *arg)
3390 struct pde_action *act = arg;
3392 if (act->store == PCPU_GET(cpuid))
3393 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3397 pmap_update_pde_teardown(void *arg)
3399 struct pde_action *act = arg;
3401 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3402 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3406 * Change the page size for the specified virtual address in a way that
3407 * prevents any possibility of the TLB ever having two entries that map the
3408 * same virtual address using different page sizes. This is the recommended
3409 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3410 * machine check exception for a TLB state that is improperly diagnosed as a
3414 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3416 struct pde_action act;
3417 cpuset_t active, other_cpus;
3421 cpuid = PCPU_GET(cpuid);
3422 other_cpus = all_cpus;
3423 CPU_CLR(cpuid, &other_cpus);
3424 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3427 active = pmap->pm_active;
3429 if (CPU_OVERLAP(&active, &other_cpus)) {
3431 act.invalidate = active;
3435 act.newpde = newpde;
3436 CPU_SET(cpuid, &active);
3437 smp_rendezvous_cpus(active,
3438 smp_no_rendezvous_barrier, pmap_update_pde_action,
3439 pmap_update_pde_teardown, &act);
3441 pmap_update_pde_store(pmap, pde, newpde);
3442 if (CPU_ISSET(cpuid, &active))
3443 pmap_update_pde_invalidate(pmap, va, newpde);
3449 * Normal, non-SMP, invalidation functions.
3452 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3454 struct invpcid_descr d;
3455 uint64_t kcr3, ucr3;
3458 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3462 KASSERT(pmap->pm_type == PT_X86,
3463 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3465 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3467 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3468 pmap->pm_ucr3 != PMAP_NO_CR3) {
3470 pcid = pmap->pm_pcids[0].pm_pcid;
3471 if (invpcid_works) {
3472 d.pcid = pcid | PMAP_PCID_USER_PT;
3475 invpcid(&d, INVPCID_ADDR);
3477 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3478 ucr3 = pmap->pm_ucr3 | pcid |
3479 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3480 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3484 } else if (pmap_pcid_enabled)
3485 pmap->pm_pcids[0].pm_gen = 0;
3489 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3491 struct invpcid_descr d;
3493 uint64_t kcr3, ucr3;
3495 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3499 KASSERT(pmap->pm_type == PT_X86,
3500 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3502 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3503 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3505 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3506 pmap->pm_ucr3 != PMAP_NO_CR3) {
3508 if (invpcid_works) {
3509 d.pcid = pmap->pm_pcids[0].pm_pcid |
3513 for (; d.addr < eva; d.addr += PAGE_SIZE)
3514 invpcid(&d, INVPCID_ADDR);
3516 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
3517 pm_pcid | CR3_PCID_SAVE;
3518 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
3519 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3520 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3524 } else if (pmap_pcid_enabled) {
3525 pmap->pm_pcids[0].pm_gen = 0;
3530 pmap_invalidate_all(pmap_t pmap)
3532 struct invpcid_descr d;
3533 uint64_t kcr3, ucr3;
3535 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3539 KASSERT(pmap->pm_type == PT_X86,
3540 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3542 if (pmap == kernel_pmap) {
3543 if (pmap_pcid_enabled && invpcid_works) {
3544 bzero(&d, sizeof(d));
3545 invpcid(&d, INVPCID_CTXGLOB);
3549 } else if (pmap == PCPU_GET(curpmap)) {
3550 if (pmap_pcid_enabled) {
3552 if (invpcid_works) {
3553 d.pcid = pmap->pm_pcids[0].pm_pcid;
3556 invpcid(&d, INVPCID_CTX);
3557 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3558 d.pcid |= PMAP_PCID_USER_PT;
3559 invpcid(&d, INVPCID_CTX);
3562 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
3563 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3564 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
3565 0].pm_pcid | PMAP_PCID_USER_PT;
3566 pmap_pti_pcid_invalidate(ucr3, kcr3);
3574 } else if (pmap_pcid_enabled) {
3575 pmap->pm_pcids[0].pm_gen = 0;
3580 pmap_invalidate_cache(void)
3587 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3590 pmap_update_pde_store(pmap, pde, newpde);
3591 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3592 pmap_update_pde_invalidate(pmap, va, newpde);
3594 pmap->pm_pcids[0].pm_gen = 0;
3599 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3603 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3604 * by a promotion that did not invalidate the 512 4KB page mappings
3605 * that might exist in the TLB. Consequently, at this point, the TLB
3606 * may hold both 4KB and 2MB page mappings for the address range [va,
3607 * va + NBPDR). Therefore, the entire range must be invalidated here.
3608 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3609 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3610 * single INVLPG suffices to invalidate the 2MB page mapping from the
3613 if ((pde & PG_PROMOTED) != 0)
3614 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3616 pmap_invalidate_page(pmap, va);
3619 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3620 (vm_offset_t sva, vm_offset_t eva))
3623 if ((cpu_feature & CPUID_SS) != 0)
3624 return (pmap_invalidate_cache_range_selfsnoop);
3625 if ((cpu_feature & CPUID_CLFSH) != 0)
3626 return (pmap_force_invalidate_cache_range);
3627 return (pmap_invalidate_cache_range_all);
3630 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3633 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3636 KASSERT((sva & PAGE_MASK) == 0,
3637 ("pmap_invalidate_cache_range: sva not page-aligned"));
3638 KASSERT((eva & PAGE_MASK) == 0,
3639 ("pmap_invalidate_cache_range: eva not page-aligned"));
3643 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3646 pmap_invalidate_cache_range_check_align(sva, eva);
3650 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3653 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3656 * XXX: Some CPUs fault, hang, or trash the local APIC
3657 * registers if we use CLFLUSH on the local APIC range. The
3658 * local APIC is always uncached, so we don't need to flush
3659 * for that range anyway.
3661 if (pmap_kextract(sva) == lapic_paddr)
3664 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3666 * Do per-cache line flush. Use a locked
3667 * instruction to insure that previous stores are
3668 * included in the write-back. The processor
3669 * propagates flush to other processors in the cache
3672 atomic_thread_fence_seq_cst();
3673 for (; sva < eva; sva += cpu_clflush_line_size)
3675 atomic_thread_fence_seq_cst();
3678 * Writes are ordered by CLFLUSH on Intel CPUs.
3680 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3682 for (; sva < eva; sva += cpu_clflush_line_size)
3684 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3690 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3693 pmap_invalidate_cache_range_check_align(sva, eva);
3694 pmap_invalidate_cache();
3698 * Remove the specified set of pages from the data and instruction caches.
3700 * In contrast to pmap_invalidate_cache_range(), this function does not
3701 * rely on the CPU's self-snoop feature, because it is intended for use
3702 * when moving pages into a different cache domain.
3705 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3707 vm_offset_t daddr, eva;
3711 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3712 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3713 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3714 pmap_invalidate_cache();
3717 atomic_thread_fence_seq_cst();
3718 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3720 for (i = 0; i < count; i++) {
3721 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3722 eva = daddr + PAGE_SIZE;
3723 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3731 atomic_thread_fence_seq_cst();
3732 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3738 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3741 pmap_invalidate_cache_range_check_align(sva, eva);
3743 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3744 pmap_force_invalidate_cache_range(sva, eva);
3748 /* See comment in pmap_force_invalidate_cache_range(). */
3749 if (pmap_kextract(sva) == lapic_paddr)
3752 atomic_thread_fence_seq_cst();
3753 for (; sva < eva; sva += cpu_clflush_line_size)
3755 atomic_thread_fence_seq_cst();
3759 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3763 int error __diagused;
3766 KASSERT((spa & PAGE_MASK) == 0,
3767 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3768 KASSERT((epa & PAGE_MASK) == 0,
3769 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3771 if (spa < dmaplimit) {
3772 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3774 if (dmaplimit >= epa)
3779 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3781 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3783 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3784 pte = vtopte(vaddr);
3785 for (; spa < epa; spa += PAGE_SIZE) {
3787 pte_store(pte, spa | pte_bits);
3788 pmap_invlpg(kernel_pmap, vaddr);
3789 /* XXXKIB atomic inside flush_cache_range are excessive */
3790 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3793 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3797 * Routine: pmap_extract
3799 * Extract the physical page address associated
3800 * with the given map/virtual_address pair.
3803 pmap_extract(pmap_t pmap, vm_offset_t va)
3807 pt_entry_t *pte, PG_V;
3811 PG_V = pmap_valid_bit(pmap);
3813 pdpe = pmap_pdpe(pmap, va);
3814 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3815 if ((*pdpe & PG_PS) != 0)
3816 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3818 pde = pmap_pdpe_to_pde(pdpe, va);
3819 if ((*pde & PG_V) != 0) {
3820 if ((*pde & PG_PS) != 0) {
3821 pa = (*pde & PG_PS_FRAME) |
3824 pte = pmap_pde_to_pte(pde, va);
3825 pa = (*pte & PG_FRAME) |
3836 * Routine: pmap_extract_and_hold
3838 * Atomically extract and hold the physical page
3839 * with the given pmap and virtual address pair
3840 * if that mapping permits the given protection.
3843 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3845 pdp_entry_t pdpe, *pdpep;
3846 pd_entry_t pde, *pdep;
3847 pt_entry_t pte, PG_RW, PG_V;
3851 PG_RW = pmap_rw_bit(pmap);
3852 PG_V = pmap_valid_bit(pmap);
3855 pdpep = pmap_pdpe(pmap, va);
3856 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3858 if ((pdpe & PG_PS) != 0) {
3859 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3861 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3865 pdep = pmap_pdpe_to_pde(pdpep, va);
3866 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3868 if ((pde & PG_PS) != 0) {
3869 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3871 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3875 pte = *pmap_pde_to_pte(pdep, va);
3876 if ((pte & PG_V) == 0 ||
3877 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3879 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3882 if (m != NULL && !vm_page_wire_mapped(m))
3890 pmap_kextract(vm_offset_t va)
3895 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3896 pa = DMAP_TO_PHYS(va);
3897 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3898 pa = pmap_large_map_kextract(va);
3902 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3905 * Beware of a concurrent promotion that changes the
3906 * PDE at this point! For example, vtopte() must not
3907 * be used to access the PTE because it would use the
3908 * new PDE. It is, however, safe to use the old PDE
3909 * because the page table page is preserved by the
3912 pa = *pmap_pde_to_pte(&pde, va);
3913 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3919 /***************************************************
3920 * Low level mapping routines.....
3921 ***************************************************/
3924 * Add a wired page to the kva.
3925 * Note: not SMP coherent.
3928 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3933 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3934 X86_PG_RW | X86_PG_V);
3937 static __inline void
3938 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3944 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
3945 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3946 X86_PG_RW | X86_PG_V | cache_bits);
3950 * Remove a page from the kernel pagetables.
3951 * Note: not SMP coherent.
3954 pmap_kremove(vm_offset_t va)
3963 * Used to map a range of physical addresses into kernel
3964 * virtual address space.
3966 * The value passed in '*virt' is a suggested virtual address for
3967 * the mapping. Architectures which can support a direct-mapped
3968 * physical to virtual region can return the appropriate address
3969 * within that region, leaving '*virt' unchanged. Other
3970 * architectures should map the pages starting at '*virt' and
3971 * update '*virt' with the first usable address after the mapped
3975 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
3977 return PHYS_TO_DMAP(start);
3981 * Add a list of wired pages to the kva
3982 * this routine is only used for temporary
3983 * kernel mappings that do not need to have
3984 * page modification or references recorded.
3985 * Note that old mappings are simply written
3986 * over. The page *must* be wired.
3987 * Note: SMP coherent. Uses a ranged shootdown IPI.
3990 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
3992 pt_entry_t *endpte, oldpte, pa, *pte;
3998 endpte = pte + count;
3999 while (pte < endpte) {
4001 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4002 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4003 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4005 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4006 X86_PG_M | X86_PG_RW | X86_PG_V);
4010 if (__predict_false((oldpte & X86_PG_V) != 0))
4011 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4016 * This routine tears out page mappings from the
4017 * kernel -- it is meant only for temporary mappings.
4018 * Note: SMP coherent. Uses a ranged shootdown IPI.
4021 pmap_qremove(vm_offset_t sva, int count)
4026 while (count-- > 0) {
4027 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4031 pmap_invalidate_range(kernel_pmap, sva, va);
4034 /***************************************************
4035 * Page table page management routines.....
4036 ***************************************************/
4038 * Schedule the specified unused page table page to be freed. Specifically,
4039 * add the page to the specified list of pages that will be released to the
4040 * physical memory manager after the TLB has been updated.
4042 static __inline void
4043 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4044 boolean_t set_PG_ZERO)
4048 m->flags |= PG_ZERO;
4050 m->flags &= ~PG_ZERO;
4051 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4055 * Inserts the specified page table page into the specified pmap's collection
4056 * of idle page table pages. Each of a pmap's page table pages is responsible
4057 * for mapping a distinct range of virtual addresses. The pmap's collection is
4058 * ordered by this virtual address range.
4060 * If "promoted" is false, then the page table page "mpte" must be zero filled.
4063 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
4066 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4067 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
4068 return (vm_radix_insert(&pmap->pm_root, mpte));
4072 * Removes the page table page mapping the specified virtual address from the
4073 * specified pmap's collection of idle page table pages, and returns it.
4074 * Otherwise, returns NULL if there is no page table page corresponding to the
4075 * specified virtual address.
4077 static __inline vm_page_t
4078 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4081 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4082 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4086 * Decrements a page table page's reference count, which is used to record the
4087 * number of valid page table entries within the page. If the reference count
4088 * drops to zero, then the page table page is unmapped. Returns TRUE if the
4089 * page table page was unmapped and FALSE otherwise.
4091 static inline boolean_t
4092 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4096 if (m->ref_count == 0) {
4097 _pmap_unwire_ptp(pmap, va, m, free);
4104 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4110 vm_page_t pdpg, pdppg, pml4pg;
4112 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4115 * unmap the page table page
4117 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4119 MPASS(pmap_is_la57(pmap));
4120 pml5 = pmap_pml5e(pmap, va);
4122 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4123 pml5 = pmap_pml5e_u(pmap, va);
4126 } else if (m->pindex >= NUPDE + NUPDPE) {
4128 pml4 = pmap_pml4e(pmap, va);
4130 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4131 va <= VM_MAXUSER_ADDRESS) {
4132 pml4 = pmap_pml4e_u(pmap, va);
4135 } else if (m->pindex >= NUPDE) {
4137 pdp = pmap_pdpe(pmap, va);
4141 pd = pmap_pde(pmap, va);
4144 if (m->pindex < NUPDE) {
4145 /* We just released a PT, unhold the matching PD */
4146 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4147 pmap_unwire_ptp(pmap, va, pdpg, free);
4148 } else if (m->pindex < NUPDE + NUPDPE) {
4149 /* We just released a PD, unhold the matching PDP */
4150 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4151 pmap_unwire_ptp(pmap, va, pdppg, free);
4152 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4153 /* We just released a PDP, unhold the matching PML4 */
4154 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4155 pmap_unwire_ptp(pmap, va, pml4pg, free);
4158 pmap_pt_page_count_adj(pmap, -1);
4161 * Put page on a list so that it is released after
4162 * *ALL* TLB shootdown is done
4164 pmap_add_delayed_free_list(m, free, TRUE);
4168 * After removing a page table entry, this routine is used to
4169 * conditionally free the page, and manage the reference count.
4172 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4173 struct spglist *free)
4177 if (va >= VM_MAXUSER_ADDRESS)
4179 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4180 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4181 return (pmap_unwire_ptp(pmap, va, mpte, free));
4185 * Release a page table page reference after a failed attempt to create a
4189 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4191 struct spglist free;
4194 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4196 * Although "va" was never mapped, paging-structure caches
4197 * could nonetheless have entries that refer to the freed
4198 * page table pages. Invalidate those entries.
4200 pmap_invalidate_page(pmap, va);
4201 vm_page_free_pages_toq(&free, true);
4206 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4208 struct pmap_pcid *pcidp;
4212 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4213 pcidp->pm_pcid = pcid;
4214 pcidp->pm_gen = gen;
4219 pmap_pinit0(pmap_t pmap)
4224 PMAP_LOCK_INIT(pmap);
4225 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4226 pmap->pm_pmltopu = NULL;
4227 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4228 /* hack to keep pmap_pti_pcid_invalidate() alive */
4229 pmap->pm_ucr3 = PMAP_NO_CR3;
4230 vm_radix_init(&pmap->pm_root);
4231 CPU_ZERO(&pmap->pm_active);
4232 TAILQ_INIT(&pmap->pm_pvchunk);
4233 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4234 pmap->pm_flags = pmap_flags;
4235 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4236 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4237 pmap_activate_boot(pmap);
4242 p->p_md.md_flags |= P_MD_KPTI;
4245 pmap_thread_init_invl_gen(td);
4247 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4248 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4249 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4255 pmap_pinit_pml4(vm_page_t pml4pg)
4257 pml4_entry_t *pm_pml4;
4260 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4262 /* Wire in kernel global address entries. */
4263 for (i = 0; i < NKPML4E; i++) {
4264 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4268 for (i = 0; i < NKASANPML4E; i++) {
4269 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4274 for (i = 0; i < NKMSANSHADPML4E; i++) {
4275 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4276 X86_PG_RW | X86_PG_V | pg_nx;
4278 for (i = 0; i < NKMSANORIGPML4E; i++) {
4279 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4280 X86_PG_RW | X86_PG_V | pg_nx;
4283 for (i = 0; i < ndmpdpphys; i++) {
4284 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4288 /* install self-referential address mapping entry(s) */
4289 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4290 X86_PG_A | X86_PG_M;
4292 /* install large map entries if configured */
4293 for (i = 0; i < lm_ents; i++)
4294 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4298 pmap_pinit_pml5(vm_page_t pml5pg)
4300 pml5_entry_t *pm_pml5;
4302 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4305 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4306 * entering all existing kernel mappings into level 5 table.
4308 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4309 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4310 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4313 * Install self-referential address mapping entry.
4315 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4316 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A |
4317 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4321 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4323 pml4_entry_t *pm_pml4u;
4326 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4327 for (i = 0; i < NPML4EPG; i++)
4328 pm_pml4u[i] = pti_pml4[i];
4332 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4334 pml5_entry_t *pm_pml5u;
4336 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4340 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4341 * table, entering all kernel mappings needed for usermode
4342 * into level 5 table.
4344 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4345 pmap_kextract((vm_offset_t)pti_pml4) |
4346 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4347 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4350 /* Allocate a page table page and do related bookkeeping */
4352 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4356 m = vm_page_alloc_noobj(flags);
4357 if (__predict_false(m == NULL))
4360 pmap_pt_page_count_adj(pmap, 1);
4365 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4368 * This function assumes the page will need to be unwired,
4369 * even though the counterpart allocation in pmap_alloc_pt_page()
4370 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4371 * of pmap_free_pt_page() require unwiring. The case in which
4372 * a PT page doesn't require unwiring because its ref_count has
4373 * naturally reached 0 is handled through _pmap_unwire_ptp().
4375 vm_page_unwire_noq(m);
4377 vm_page_free_zero(m);
4381 pmap_pt_page_count_adj(pmap, -1);
4384 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4387 * Initialize a preallocated and zeroed pmap structure,
4388 * such as one in a vmspace structure.
4391 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4393 vm_page_t pmltop_pg, pmltop_pgu;
4394 vm_paddr_t pmltop_phys;
4396 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4399 * Allocate the page directory page. Pass NULL instead of a
4400 * pointer to the pmap here to avoid calling
4401 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4402 * since that requires pmap lock. Instead do the accounting
4405 * Note that final call to pmap_remove() optimization that
4406 * checks for zero resident_count is basically disabled by
4407 * accounting for top-level page. But the optimization was
4408 * not effective since we started using non-managed mapping of
4411 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4413 pmap_pt_page_count_pinit(pmap, 1);
4415 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4416 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4418 if (pmap_pcid_enabled) {
4419 if (pmap->pm_pcidp == NULL)
4420 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4422 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4424 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4425 pmap->pm_ucr3 = PMAP_NO_CR3;
4426 pmap->pm_pmltopu = NULL;
4428 pmap->pm_type = pm_type;
4431 * Do not install the host kernel mappings in the nested page
4432 * tables. These mappings are meaningless in the guest physical
4434 * Install minimal kernel mappings in PTI case.
4438 pmap->pm_cr3 = pmltop_phys;
4439 if (pmap_is_la57(pmap))
4440 pmap_pinit_pml5(pmltop_pg);
4442 pmap_pinit_pml4(pmltop_pg);
4443 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4445 * As with pmltop_pg, pass NULL instead of a
4446 * pointer to the pmap to ensure that the PTI
4447 * page counted explicitly.
4449 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4450 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4451 pmap_pt_page_count_pinit(pmap, 1);
4452 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4453 VM_PAGE_TO_PHYS(pmltop_pgu));
4454 if (pmap_is_la57(pmap))
4455 pmap_pinit_pml5_pti(pmltop_pgu);
4457 pmap_pinit_pml4_pti(pmltop_pgu);
4458 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4460 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4461 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4462 pkru_free_range, pmap, M_NOWAIT);
4467 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4471 vm_radix_init(&pmap->pm_root);
4472 CPU_ZERO(&pmap->pm_active);
4473 TAILQ_INIT(&pmap->pm_pvchunk);
4474 pmap->pm_flags = flags;
4475 pmap->pm_eptgen = 0;
4481 pmap_pinit(pmap_t pmap)
4484 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4488 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4491 struct spglist free;
4493 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4494 if (mpg->ref_count != 0)
4497 _pmap_unwire_ptp(pmap, va, mpg, &free);
4498 pmap_invalidate_page(pmap, va);
4499 vm_page_free_pages_toq(&free, true);
4502 static pml4_entry_t *
4503 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4506 vm_pindex_t pml5index;
4513 if (!pmap_is_la57(pmap))
4514 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4516 PG_V = pmap_valid_bit(pmap);
4517 pml5index = pmap_pml5e_index(va);
4518 pml5 = &pmap->pm_pmltop[pml5index];
4519 if ((*pml5 & PG_V) == 0) {
4520 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4527 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4528 pml4 = &pml4[pmap_pml4e_index(va)];
4529 if ((*pml4 & PG_V) == 0) {
4530 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4531 if (allocated && !addref)
4532 pml4pg->ref_count--;
4533 else if (!allocated && addref)
4534 pml4pg->ref_count++;
4539 static pdp_entry_t *
4540 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4549 PG_V = pmap_valid_bit(pmap);
4551 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4555 if ((*pml4 & PG_V) == 0) {
4556 /* Have to allocate a new pdp, recurse */
4557 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4559 if (pmap_is_la57(pmap))
4560 pmap_allocpte_free_unref(pmap, va,
4561 pmap_pml5e(pmap, va));
4568 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4569 pdp = &pdp[pmap_pdpe_index(va)];
4570 if ((*pdp & PG_V) == 0) {
4571 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4572 if (allocated && !addref)
4574 else if (!allocated && addref)
4581 * The ptepindexes, i.e. page indices, of the page table pages encountered
4582 * while translating virtual address va are defined as follows:
4583 * - for the page table page (last level),
4584 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4585 * in other words, it is just the index of the PDE that maps the page
4587 * - for the page directory page,
4588 * ptepindex = NUPDE (number of userland PD entries) +
4589 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4590 * i.e. index of PDPE is put after the last index of PDE,
4591 * - for the page directory pointer page,
4592 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4594 * i.e. index of pml4e is put after the last index of PDPE,
4595 * - for the PML4 page (if LA57 mode is enabled),
4596 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4597 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4598 * i.e. index of pml5e is put after the last index of PML4E.
4600 * Define an order on the paging entries, where all entries of the
4601 * same height are put together, then heights are put from deepest to
4602 * root. Then ptexpindex is the sequential number of the
4603 * corresponding paging entry in this order.
4605 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4606 * LA57 paging structures even in LA48 paging mode. Moreover, the
4607 * ptepindexes are calculated as if the paging structures were 5-level
4608 * regardless of the actual mode of operation.
4610 * The root page at PML4/PML5 does not participate in this indexing scheme,
4611 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4614 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4617 vm_pindex_t pml5index, pml4index;
4618 pml5_entry_t *pml5, *pml5u;
4619 pml4_entry_t *pml4, *pml4u;
4623 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4625 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4627 PG_A = pmap_accessed_bit(pmap);
4628 PG_M = pmap_modified_bit(pmap);
4629 PG_V = pmap_valid_bit(pmap);
4630 PG_RW = pmap_rw_bit(pmap);
4633 * Allocate a page table page.
4635 m = pmap_alloc_pt_page(pmap, ptepindex,
4636 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4641 * Map the pagetable page into the process address space, if
4642 * it isn't already there.
4644 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4645 MPASS(pmap_is_la57(pmap));
4647 pml5index = pmap_pml5e_index(va);
4648 pml5 = &pmap->pm_pmltop[pml5index];
4649 KASSERT((*pml5 & PG_V) == 0,
4650 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4651 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4653 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4654 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4657 pml5u = &pmap->pm_pmltopu[pml5index];
4658 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4661 } else if (ptepindex >= NUPDE + NUPDPE) {
4662 pml4index = pmap_pml4e_index(va);
4663 /* Wire up a new PDPE page */
4664 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4666 pmap_free_pt_page(pmap, m, true);
4669 KASSERT((*pml4 & PG_V) == 0,
4670 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4671 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4673 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4674 pml4index < NUPML4E) {
4676 * PTI: Make all user-space mappings in the
4677 * kernel-mode page table no-execute so that
4678 * we detect any programming errors that leave
4679 * the kernel-mode page table active on return
4682 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4685 pml4u = &pmap->pm_pmltopu[pml4index];
4686 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4689 } else if (ptepindex >= NUPDE) {
4690 /* Wire up a new PDE page */
4691 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4693 pmap_free_pt_page(pmap, m, true);
4696 KASSERT((*pdp & PG_V) == 0,
4697 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4698 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4700 /* Wire up a new PTE page */
4701 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4703 pmap_free_pt_page(pmap, m, true);
4706 if ((*pdp & PG_V) == 0) {
4707 /* Have to allocate a new pd, recurse */
4708 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4709 lockp, va) == NULL) {
4710 pmap_allocpte_free_unref(pmap, va,
4711 pmap_pml4e(pmap, va));
4712 pmap_free_pt_page(pmap, m, true);
4716 /* Add reference to the pd page */
4717 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4720 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4722 /* Now we know where the page directory page is */
4723 pd = &pd[pmap_pde_index(va)];
4724 KASSERT((*pd & PG_V) == 0,
4725 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4726 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4733 * This routine is called if the desired page table page does not exist.
4735 * If page table page allocation fails, this routine may sleep before
4736 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4737 * occurs right before returning to the caller. This way, we never
4738 * drop pmap lock to sleep while a page table page has ref_count == 0,
4739 * which prevents the page from being freed under us.
4742 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4747 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4748 if (m == NULL && lockp != NULL) {
4749 RELEASE_PV_LIST_LOCK(lockp);
4751 PMAP_ASSERT_NOT_IN_DI();
4759 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4760 struct rwlock **lockp)
4762 pdp_entry_t *pdpe, PG_V;
4765 vm_pindex_t pdpindex;
4767 PG_V = pmap_valid_bit(pmap);
4770 pdpe = pmap_pdpe(pmap, va);
4771 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4772 pde = pmap_pdpe_to_pde(pdpe, va);
4773 if (va < VM_MAXUSER_ADDRESS) {
4774 /* Add a reference to the pd page. */
4775 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4779 } else if (va < VM_MAXUSER_ADDRESS) {
4780 /* Allocate a pd page. */
4781 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4782 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4789 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4790 pde = &pde[pmap_pde_index(va)];
4792 panic("pmap_alloc_pde: missing page table page for va %#lx",
4799 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4801 vm_pindex_t ptepindex;
4802 pd_entry_t *pd, PG_V;
4805 PG_V = pmap_valid_bit(pmap);
4808 * Calculate pagetable page index
4810 ptepindex = pmap_pde_pindex(va);
4813 * Get the page directory entry
4815 pd = pmap_pde(pmap, va);
4818 * This supports switching from a 2MB page to a
4821 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4822 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4824 * Invalidation of the 2MB page mapping may have caused
4825 * the deallocation of the underlying PD page.
4832 * If the page table page is mapped, we just increment the
4833 * hold count, and activate it.
4835 if (pd != NULL && (*pd & PG_V) != 0) {
4836 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4840 * Here if the pte page isn't mapped, or if it has been
4843 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4844 if (m == NULL && lockp != NULL)
4850 /***************************************************
4851 * Pmap allocation/deallocation routines.
4852 ***************************************************/
4855 * Release any resources held by the given physical map.
4856 * Called when a pmap initialized by pmap_pinit is being released.
4857 * Should only be called if the map contains no valid mappings.
4860 pmap_release(pmap_t pmap)
4865 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4866 ("pmap_release: pmap %p has reserved page table page(s)",
4868 KASSERT(CPU_EMPTY(&pmap->pm_active),
4869 ("releasing active pmap %p", pmap));
4871 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4873 if (pmap_is_la57(pmap)) {
4874 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4875 pmap->pm_pmltop[PML5PML5I] = 0;
4877 for (i = 0; i < NKPML4E; i++) /* KVA */
4878 pmap->pm_pmltop[KPML4BASE + i] = 0;
4880 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4881 pmap->pm_pmltop[KASANPML4I + i] = 0;
4884 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4885 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4886 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4887 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4889 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4890 pmap->pm_pmltop[DMPML4I + i] = 0;
4891 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4892 for (i = 0; i < lm_ents; i++) /* Large Map */
4893 pmap->pm_pmltop[LMSPML4I + i] = 0;
4896 pmap_free_pt_page(NULL, m, true);
4897 pmap_pt_page_count_pinit(pmap, -1);
4899 if (pmap->pm_pmltopu != NULL) {
4900 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4902 pmap_free_pt_page(NULL, m, false);
4903 pmap_pt_page_count_pinit(pmap, -1);
4905 if (pmap->pm_type == PT_X86 &&
4906 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4907 rangeset_fini(&pmap->pm_pkru);
4909 KASSERT(pmap->pm_stats.resident_count == 0,
4910 ("pmap_release: pmap %p resident count %ld != 0",
4911 pmap, pmap->pm_stats.resident_count));
4915 kvm_size(SYSCTL_HANDLER_ARGS)
4917 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4919 return sysctl_handle_long(oidp, &ksize, 0, req);
4921 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4922 0, 0, kvm_size, "LU",
4926 kvm_free(SYSCTL_HANDLER_ARGS)
4928 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4930 return sysctl_handle_long(oidp, &kfree, 0, req);
4932 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4933 0, 0, kvm_free, "LU",
4934 "Amount of KVM free");
4938 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
4943 vm_paddr_t dummypa, dummypd, dummypt;
4946 npdpg = howmany(size, NBPDP);
4947 npde = size / NBPDR;
4949 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
4950 pagezero((void *)PHYS_TO_DMAP(dummypa));
4952 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
4953 pagezero((void *)PHYS_TO_DMAP(dummypt));
4954 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
4955 for (i = 0; i < npdpg; i++)
4956 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
4958 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
4959 for (i = 0; i < NPTEPG; i++)
4960 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
4961 X86_PG_A | X86_PG_M | pg_nx);
4963 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
4964 for (i = 0; i < npde; i++)
4965 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
4967 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
4968 for (i = 0; i < npdpg; i++)
4969 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
4974 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
4978 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
4981 * The end of the page array's KVA region is 2MB aligned, see
4984 size = round_2mpage(end) - start;
4985 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
4986 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
4991 * Allocate physical memory for the vm_page array and map it into KVA,
4992 * attempting to back the vm_pages with domain-local memory.
4995 pmap_page_array_startup(long pages)
4998 pd_entry_t *pde, newpdir;
4999 vm_offset_t va, start, end;
5004 vm_page_array_size = pages;
5006 start = VM_MIN_KERNEL_ADDRESS;
5007 end = start + pages * sizeof(struct vm_page);
5008 for (va = start; va < end; va += NBPDR) {
5009 pfn = first_page + (va - start) / sizeof(struct vm_page);
5010 domain = vm_phys_domain(ptoa(pfn));
5011 pdpe = pmap_pdpe(kernel_pmap, va);
5012 if ((*pdpe & X86_PG_V) == 0) {
5013 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5015 pagezero((void *)PHYS_TO_DMAP(pa));
5016 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5017 X86_PG_A | X86_PG_M);
5019 pde = pmap_pdpe_to_pde(pdpe, va);
5020 if ((*pde & X86_PG_V) != 0)
5021 panic("Unexpected pde");
5022 pa = vm_phys_early_alloc(domain, NBPDR);
5023 for (i = 0; i < NPDEPG; i++)
5024 dump_add_page(pa + i * PAGE_SIZE);
5025 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5026 X86_PG_M | PG_PS | pg_g | pg_nx);
5027 pde_store(pde, newpdir);
5029 vm_page_array = (vm_page_t)start;
5032 pmap_kmsan_page_array_startup(start, end);
5037 * grow the number of kernel page table entries, if needed
5040 pmap_growkernel(vm_offset_t addr)
5044 pd_entry_t *pde, newpdir;
5048 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5051 * The kernel map covers two distinct regions of KVA: that used
5052 * for dynamic kernel memory allocations, and the uppermost 2GB
5053 * of the virtual address space. The latter is used to map the
5054 * kernel and loadable kernel modules. This scheme enables the
5055 * use of a special code generation model for kernel code which
5056 * takes advantage of compact addressing modes in machine code.
5058 * Both regions grow upwards; to avoid wasting memory, the gap
5059 * in between is unmapped. If "addr" is above "KERNBASE", the
5060 * kernel's region is grown, otherwise the kmem region is grown.
5062 * The correctness of this action is based on the following
5063 * argument: vm_map_insert() allocates contiguous ranges of the
5064 * kernel virtual address space. It calls this function if a range
5065 * ends after "kernel_vm_end". If the kernel is mapped between
5066 * "kernel_vm_end" and "addr", then the range cannot begin at
5067 * "kernel_vm_end". In fact, its beginning address cannot be less
5068 * than the kernel. Thus, there is no immediate need to allocate
5069 * any new kernel page table pages between "kernel_vm_end" and
5072 if (KERNBASE < addr) {
5073 end = KERNBASE + nkpt * NBPDR;
5077 end = kernel_vm_end;
5080 addr = roundup2(addr, NBPDR);
5081 if (addr - 1 >= vm_map_max(kernel_map))
5082 addr = vm_map_max(kernel_map);
5085 * The grown region is already mapped, so there is
5091 kasan_shadow_map(end, addr - end);
5092 kmsan_shadow_map(end, addr - end);
5093 while (end < addr) {
5094 pdpe = pmap_pdpe(kernel_pmap, end);
5095 if ((*pdpe & X86_PG_V) == 0) {
5096 nkpg = pmap_alloc_pt_page(kernel_pmap,
5097 pmap_pdpe_pindex(end), VM_ALLOC_WIRED |
5098 VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5100 panic("pmap_growkernel: no memory to grow kernel");
5101 paddr = VM_PAGE_TO_PHYS(nkpg);
5102 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5103 X86_PG_A | X86_PG_M);
5104 continue; /* try again */
5106 pde = pmap_pdpe_to_pde(pdpe, end);
5107 if ((*pde & X86_PG_V) != 0) {
5108 end = (end + NBPDR) & ~PDRMASK;
5109 if (end - 1 >= vm_map_max(kernel_map)) {
5110 end = vm_map_max(kernel_map);
5116 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5117 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5119 panic("pmap_growkernel: no memory to grow kernel");
5120 paddr = VM_PAGE_TO_PHYS(nkpg);
5121 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5122 pde_store(pde, newpdir);
5124 end = (end + NBPDR) & ~PDRMASK;
5125 if (end - 1 >= vm_map_max(kernel_map)) {
5126 end = vm_map_max(kernel_map);
5131 if (end <= KERNBASE)
5132 kernel_vm_end = end;
5134 nkpt = howmany(end - KERNBASE, NBPDR);
5137 /***************************************************
5138 * page management routines.
5139 ***************************************************/
5141 static const uint64_t pc_freemask[_NPCM] = {
5142 [0 ... _NPCM - 2] = PC_FREEN,
5143 [_NPCM - 1] = PC_FREEL
5148 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5149 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5150 &pc_chunk_count, "Current number of pv entry cnunks");
5152 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5153 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5154 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5156 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5157 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5158 &pc_chunk_frees, "Total number of pv entry chunks freed");
5160 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5161 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5163 "Number of failed attempts to get a pv entry chunk page");
5165 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5166 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5167 &pv_entry_frees, "Total number of pv entries freed");
5169 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5170 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5171 &pv_entry_allocs, "Total number of pv entries allocated");
5173 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5174 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5175 &pv_entry_count, "Current number of pv entries");
5177 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5178 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5179 &pv_entry_spare, "Current number of spare pv entries");
5183 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5188 pmap_invalidate_all(pmap);
5189 if (pmap != locked_pmap)
5192 pmap_delayed_invl_finish();
5196 * We are in a serious low memory condition. Resort to
5197 * drastic measures to free some pages so we can allocate
5198 * another pv entry chunk.
5200 * Returns NULL if PV entries were reclaimed from the specified pmap.
5202 * We do not, however, unmap 2mpages because subsequent accesses will
5203 * allocate per-page pv entries until repromotion occurs, thereby
5204 * exacerbating the shortage of free pv entries.
5207 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5209 struct pv_chunks_list *pvc;
5210 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5211 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5212 struct md_page *pvh;
5214 pmap_t next_pmap, pmap;
5215 pt_entry_t *pte, tpte;
5216 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5220 struct spglist free;
5222 int bit, field, freed;
5223 bool start_di, restart;
5225 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5226 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5229 PG_G = PG_A = PG_M = PG_RW = 0;
5231 bzero(&pc_marker_b, sizeof(pc_marker_b));
5232 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5233 pc_marker = (struct pv_chunk *)&pc_marker_b;
5234 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5237 * A delayed invalidation block should already be active if
5238 * pmap_advise() or pmap_remove() called this function by way
5239 * of pmap_demote_pde_locked().
5241 start_di = pmap_not_in_di();
5243 pvc = &pv_chunks[domain];
5244 mtx_lock(&pvc->pvc_lock);
5245 pvc->active_reclaims++;
5246 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5247 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5248 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5249 SLIST_EMPTY(&free)) {
5250 next_pmap = pc->pc_pmap;
5251 if (next_pmap == NULL) {
5253 * The next chunk is a marker. However, it is
5254 * not our marker, so active_reclaims must be
5255 * > 1. Consequently, the next_chunk code
5256 * will not rotate the pv_chunks list.
5260 mtx_unlock(&pvc->pvc_lock);
5263 * A pv_chunk can only be removed from the pc_lru list
5264 * when both pc_chunks_mutex is owned and the
5265 * corresponding pmap is locked.
5267 if (pmap != next_pmap) {
5269 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5272 /* Avoid deadlock and lock recursion. */
5273 if (pmap > locked_pmap) {
5274 RELEASE_PV_LIST_LOCK(lockp);
5277 pmap_delayed_invl_start();
5278 mtx_lock(&pvc->pvc_lock);
5280 } else if (pmap != locked_pmap) {
5281 if (PMAP_TRYLOCK(pmap)) {
5283 pmap_delayed_invl_start();
5284 mtx_lock(&pvc->pvc_lock);
5287 pmap = NULL; /* pmap is not locked */
5288 mtx_lock(&pvc->pvc_lock);
5289 pc = TAILQ_NEXT(pc_marker, pc_lru);
5291 pc->pc_pmap != next_pmap)
5295 } else if (start_di)
5296 pmap_delayed_invl_start();
5297 PG_G = pmap_global_bit(pmap);
5298 PG_A = pmap_accessed_bit(pmap);
5299 PG_M = pmap_modified_bit(pmap);
5300 PG_RW = pmap_rw_bit(pmap);
5306 * Destroy every non-wired, 4 KB page mapping in the chunk.
5309 for (field = 0; field < _NPCM; field++) {
5310 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5311 inuse != 0; inuse &= ~(1UL << bit)) {
5313 pv = &pc->pc_pventry[field * 64 + bit];
5315 pde = pmap_pde(pmap, va);
5316 if ((*pde & PG_PS) != 0)
5318 pte = pmap_pde_to_pte(pde, va);
5319 if ((*pte & PG_W) != 0)
5321 tpte = pte_load_clear(pte);
5322 if ((tpte & PG_G) != 0)
5323 pmap_invalidate_page(pmap, va);
5324 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5325 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5327 if ((tpte & PG_A) != 0)
5328 vm_page_aflag_set(m, PGA_REFERENCED);
5329 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5330 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5332 if (TAILQ_EMPTY(&m->md.pv_list) &&
5333 (m->flags & PG_FICTITIOUS) == 0) {
5334 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5335 if (TAILQ_EMPTY(&pvh->pv_list)) {
5336 vm_page_aflag_clear(m,
5340 pmap_delayed_invl_page(m);
5341 pc->pc_map[field] |= 1UL << bit;
5342 pmap_unuse_pt(pmap, va, *pde, &free);
5347 mtx_lock(&pvc->pvc_lock);
5350 /* Every freed mapping is for a 4 KB page. */
5351 pmap_resident_count_adj(pmap, -freed);
5352 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5353 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5354 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5355 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5356 if (pc_is_free(pc)) {
5357 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5358 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5359 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5360 /* Entire chunk is free; return it. */
5361 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5362 dump_drop_page(m_pc->phys_addr);
5363 mtx_lock(&pvc->pvc_lock);
5364 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5367 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5368 mtx_lock(&pvc->pvc_lock);
5369 /* One freed pv entry in locked_pmap is sufficient. */
5370 if (pmap == locked_pmap)
5373 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5374 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5375 if (pvc->active_reclaims == 1 && pmap != NULL) {
5377 * Rotate the pv chunks list so that we do not
5378 * scan the same pv chunks that could not be
5379 * freed (because they contained a wired
5380 * and/or superpage mapping) on every
5381 * invocation of reclaim_pv_chunk().
5383 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5384 MPASS(pc->pc_pmap != NULL);
5385 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5386 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5390 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5391 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5392 pvc->active_reclaims--;
5393 mtx_unlock(&pvc->pvc_lock);
5394 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5395 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5396 m_pc = SLIST_FIRST(&free);
5397 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5398 /* Recycle a freed page table page. */
5399 m_pc->ref_count = 1;
5401 vm_page_free_pages_toq(&free, true);
5406 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5411 domain = PCPU_GET(domain);
5412 for (i = 0; i < vm_ndomains; i++) {
5413 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5416 domain = (domain + 1) % vm_ndomains;
5423 * free the pv_entry back to the free list
5426 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5428 struct pv_chunk *pc;
5429 int idx, field, bit;
5431 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5432 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5433 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5434 PV_STAT(counter_u64_add(pv_entry_count, -1));
5435 pc = pv_to_chunk(pv);
5436 idx = pv - &pc->pc_pventry[0];
5439 pc->pc_map[field] |= 1ul << bit;
5440 if (!pc_is_free(pc)) {
5441 /* 98% of the time, pc is already at the head of the list. */
5442 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5443 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5444 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5448 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5453 free_pv_chunk_dequeued(struct pv_chunk *pc)
5457 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5458 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5459 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5460 counter_u64_add(pv_page_count, -1);
5461 /* entire chunk is free, return it */
5462 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5463 dump_drop_page(m->phys_addr);
5464 vm_page_unwire_noq(m);
5469 free_pv_chunk(struct pv_chunk *pc)
5471 struct pv_chunks_list *pvc;
5473 pvc = &pv_chunks[pc_to_domain(pc)];
5474 mtx_lock(&pvc->pvc_lock);
5475 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5476 mtx_unlock(&pvc->pvc_lock);
5477 free_pv_chunk_dequeued(pc);
5481 free_pv_chunk_batch(struct pv_chunklist *batch)
5483 struct pv_chunks_list *pvc;
5484 struct pv_chunk *pc, *npc;
5487 for (i = 0; i < vm_ndomains; i++) {
5488 if (TAILQ_EMPTY(&batch[i]))
5490 pvc = &pv_chunks[i];
5491 mtx_lock(&pvc->pvc_lock);
5492 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5493 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5495 mtx_unlock(&pvc->pvc_lock);
5498 for (i = 0; i < vm_ndomains; i++) {
5499 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5500 free_pv_chunk_dequeued(pc);
5506 * Returns a new PV entry, allocating a new PV chunk from the system when
5507 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5508 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5511 * The given PV list lock may be released.
5514 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5516 struct pv_chunks_list *pvc;
5519 struct pv_chunk *pc;
5522 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5523 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5525 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5527 for (field = 0; field < _NPCM; field++) {
5528 if (pc->pc_map[field]) {
5529 bit = bsfq(pc->pc_map[field]);
5533 if (field < _NPCM) {
5534 pv = &pc->pc_pventry[field * 64 + bit];
5535 pc->pc_map[field] &= ~(1ul << bit);
5536 /* If this was the last item, move it to tail */
5537 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
5538 pc->pc_map[2] == 0) {
5539 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5540 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5543 PV_STAT(counter_u64_add(pv_entry_count, 1));
5544 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5548 /* No free items, allocate another chunk */
5549 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5551 if (lockp == NULL) {
5552 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5555 m = reclaim_pv_chunk(pmap, lockp);
5559 counter_u64_add(pv_page_count, 1);
5560 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5561 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5562 dump_add_page(m->phys_addr);
5563 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5565 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5566 pc->pc_map[1] = PC_FREEN;
5567 pc->pc_map[2] = PC_FREEL;
5568 pvc = &pv_chunks[vm_page_domain(m)];
5569 mtx_lock(&pvc->pvc_lock);
5570 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5571 mtx_unlock(&pvc->pvc_lock);
5572 pv = &pc->pc_pventry[0];
5573 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5574 PV_STAT(counter_u64_add(pv_entry_count, 1));
5575 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5580 * Returns the number of one bits within the given PV chunk map.
5582 * The erratas for Intel processors state that "POPCNT Instruction May
5583 * Take Longer to Execute Than Expected". It is believed that the
5584 * issue is the spurious dependency on the destination register.
5585 * Provide a hint to the register rename logic that the destination
5586 * value is overwritten, by clearing it, as suggested in the
5587 * optimization manual. It should be cheap for unaffected processors
5590 * Reference numbers for erratas are
5591 * 4th Gen Core: HSD146
5592 * 5th Gen Core: BDM85
5593 * 6th Gen Core: SKL029
5596 popcnt_pc_map_pq(uint64_t *map)
5600 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5601 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5602 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5603 : "=&r" (result), "=&r" (tmp)
5604 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5609 * Ensure that the number of spare PV entries in the specified pmap meets or
5610 * exceeds the given count, "needed".
5612 * The given PV list lock may be released.
5615 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5617 struct pv_chunks_list *pvc;
5618 struct pch new_tail[PMAP_MEMDOM];
5619 struct pv_chunk *pc;
5624 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5625 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5628 * Newly allocated PV chunks must be stored in a private list until
5629 * the required number of PV chunks have been allocated. Otherwise,
5630 * reclaim_pv_chunk() could recycle one of these chunks. In
5631 * contrast, these chunks must be added to the pmap upon allocation.
5633 for (i = 0; i < PMAP_MEMDOM; i++)
5634 TAILQ_INIT(&new_tail[i]);
5637 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5639 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5640 bit_count((bitstr_t *)pc->pc_map, 0,
5641 sizeof(pc->pc_map) * NBBY, &free);
5644 free = popcnt_pc_map_pq(pc->pc_map);
5648 if (avail >= needed)
5651 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5652 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5654 m = reclaim_pv_chunk(pmap, lockp);
5659 counter_u64_add(pv_page_count, 1);
5660 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5661 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5662 dump_add_page(m->phys_addr);
5663 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5665 pc->pc_map[0] = PC_FREEN;
5666 pc->pc_map[1] = PC_FREEN;
5667 pc->pc_map[2] = PC_FREEL;
5668 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5669 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5670 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5673 * The reclaim might have freed a chunk from the current pmap.
5674 * If that chunk contained available entries, we need to
5675 * re-count the number of available entries.
5680 for (i = 0; i < vm_ndomains; i++) {
5681 if (TAILQ_EMPTY(&new_tail[i]))
5683 pvc = &pv_chunks[i];
5684 mtx_lock(&pvc->pvc_lock);
5685 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5686 mtx_unlock(&pvc->pvc_lock);
5691 * First find and then remove the pv entry for the specified pmap and virtual
5692 * address from the specified pv list. Returns the pv entry if found and NULL
5693 * otherwise. This operation can be performed on pv lists for either 4KB or
5694 * 2MB page mappings.
5696 static __inline pv_entry_t
5697 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5701 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5702 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5703 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5712 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5713 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5714 * entries for each of the 4KB page mappings.
5717 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5718 struct rwlock **lockp)
5720 struct md_page *pvh;
5721 struct pv_chunk *pc;
5723 vm_offset_t va_last;
5727 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5728 KASSERT((pa & PDRMASK) == 0,
5729 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5730 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5733 * Transfer the 2mpage's pv entry for this mapping to the first
5734 * page's pv list. Once this transfer begins, the pv list lock
5735 * must not be released until the last pv entry is reinstantiated.
5737 pvh = pa_to_pvh(pa);
5738 va = trunc_2mpage(va);
5739 pv = pmap_pvh_remove(pvh, pmap, va);
5740 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5741 m = PHYS_TO_VM_PAGE(pa);
5742 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5744 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5745 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5746 va_last = va + NBPDR - PAGE_SIZE;
5748 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5749 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
5750 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
5751 for (field = 0; field < _NPCM; field++) {
5752 while (pc->pc_map[field]) {
5753 bit = bsfq(pc->pc_map[field]);
5754 pc->pc_map[field] &= ~(1ul << bit);
5755 pv = &pc->pc_pventry[field * 64 + bit];
5759 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5760 ("pmap_pv_demote_pde: page %p is not managed", m));
5761 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5767 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5768 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5771 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
5772 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5773 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5775 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5776 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5779 #if VM_NRESERVLEVEL > 0
5781 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5782 * replace the many pv entries for the 4KB page mappings by a single pv entry
5783 * for the 2MB page mapping.
5786 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5787 struct rwlock **lockp)
5789 struct md_page *pvh;
5791 vm_offset_t va_last;
5794 KASSERT((pa & PDRMASK) == 0,
5795 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5796 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5799 * Transfer the first page's pv entry for this mapping to the 2mpage's
5800 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5801 * a transfer avoids the possibility that get_pv_entry() calls
5802 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5803 * mappings that is being promoted.
5805 m = PHYS_TO_VM_PAGE(pa);
5806 va = trunc_2mpage(va);
5807 pv = pmap_pvh_remove(&m->md, pmap, va);
5808 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5809 pvh = pa_to_pvh(pa);
5810 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5812 /* Free the remaining NPTEPG - 1 pv entries. */
5813 va_last = va + NBPDR - PAGE_SIZE;
5817 pmap_pvh_free(&m->md, pmap, va);
5818 } while (va < va_last);
5820 #endif /* VM_NRESERVLEVEL > 0 */
5823 * First find and then destroy the pv entry for the specified pmap and virtual
5824 * address. This operation can be performed on pv lists for either 4KB or 2MB
5828 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5832 pv = pmap_pvh_remove(pvh, pmap, va);
5833 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5834 free_pv_entry(pmap, pv);
5838 * Conditionally create the PV entry for a 4KB page mapping if the required
5839 * memory can be allocated without resorting to reclamation.
5842 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5843 struct rwlock **lockp)
5847 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5848 /* Pass NULL instead of the lock pointer to disable reclamation. */
5849 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5851 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5852 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5860 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5861 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5862 * false if the PV entry cannot be allocated without resorting to reclamation.
5865 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5866 struct rwlock **lockp)
5868 struct md_page *pvh;
5872 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5873 /* Pass NULL instead of the lock pointer to disable reclamation. */
5874 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5875 NULL : lockp)) == NULL)
5878 pa = pde & PG_PS_FRAME;
5879 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5880 pvh = pa_to_pvh(pa);
5881 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5887 * Fills a page table page with mappings to consecutive physical pages.
5890 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5894 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5896 newpte += PAGE_SIZE;
5901 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5902 * mapping is invalidated.
5905 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5907 struct rwlock *lock;
5911 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5918 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5922 pt_entry_t *xpte, *ypte;
5924 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5925 xpte++, newpte += PAGE_SIZE) {
5926 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
5927 printf("pmap_demote_pde: xpte %zd and newpte map "
5928 "different pages: found %#lx, expected %#lx\n",
5929 xpte - firstpte, *xpte, newpte);
5930 printf("page table dump\n");
5931 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
5932 printf("%zd %#lx\n", ypte - firstpte, *ypte);
5937 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
5938 ("pmap_demote_pde: firstpte and newpte map different physical"
5945 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
5946 pd_entry_t oldpde, struct rwlock **lockp)
5948 struct spglist free;
5952 sva = trunc_2mpage(va);
5953 pmap_remove_pde(pmap, pde, sva, &free, lockp);
5954 if ((oldpde & pmap_global_bit(pmap)) == 0)
5955 pmap_invalidate_pde_page(pmap, sva, oldpde);
5956 vm_page_free_pages_toq(&free, true);
5957 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
5962 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
5963 struct rwlock **lockp)
5965 pd_entry_t newpde, oldpde;
5966 pt_entry_t *firstpte, newpte;
5967 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
5973 PG_A = pmap_accessed_bit(pmap);
5974 PG_G = pmap_global_bit(pmap);
5975 PG_M = pmap_modified_bit(pmap);
5976 PG_RW = pmap_rw_bit(pmap);
5977 PG_V = pmap_valid_bit(pmap);
5978 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
5979 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
5981 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5982 in_kernel = va >= VM_MAXUSER_ADDRESS;
5984 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
5985 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
5988 * Invalidate the 2MB page mapping and return "failure" if the
5989 * mapping was never accessed.
5991 if ((oldpde & PG_A) == 0) {
5992 KASSERT((oldpde & PG_W) == 0,
5993 ("pmap_demote_pde: a wired mapping is missing PG_A"));
5994 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
5998 mpte = pmap_remove_pt_page(pmap, va);
6000 KASSERT((oldpde & PG_W) == 0,
6001 ("pmap_demote_pde: page table page for a wired mapping"
6005 * If the page table page is missing and the mapping
6006 * is for a kernel address, the mapping must belong to
6007 * the direct map. Page table pages are preallocated
6008 * for every other part of the kernel address space,
6009 * so the direct map region is the only part of the
6010 * kernel address space that must be handled here.
6012 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6013 va < DMAP_MAX_ADDRESS),
6014 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6017 * If the 2MB page mapping belongs to the direct map
6018 * region of the kernel's address space, then the page
6019 * allocation request specifies the highest possible
6020 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6021 * priority is normal.
6023 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6024 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6027 * If the allocation of the new page table page fails,
6028 * invalidate the 2MB page mapping and return "failure".
6031 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6036 mpte->ref_count = NPTEPG;
6038 mptepa = VM_PAGE_TO_PHYS(mpte);
6039 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6040 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6041 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6042 ("pmap_demote_pde: oldpde is missing PG_M"));
6043 newpte = oldpde & ~PG_PS;
6044 newpte = pmap_swap_pat(pmap, newpte);
6047 * If the page table page is not leftover from an earlier promotion,
6050 if (vm_page_none_valid(mpte))
6051 pmap_fill_ptp(firstpte, newpte);
6053 pmap_demote_pde_check(firstpte, newpte);
6056 * If the mapping has changed attributes, update the page table
6059 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6060 pmap_fill_ptp(firstpte, newpte);
6063 * The spare PV entries must be reserved prior to demoting the
6064 * mapping, that is, prior to changing the PDE. Otherwise, the state
6065 * of the PDE and the PV lists will be inconsistent, which can result
6066 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6067 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6068 * PV entry for the 2MB page mapping that is being demoted.
6070 if ((oldpde & PG_MANAGED) != 0)
6071 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6074 * Demote the mapping. This pmap is locked. The old PDE has
6075 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6076 * set. Thus, there is no danger of a race with another
6077 * processor changing the setting of PG_A and/or PG_M between
6078 * the read above and the store below.
6080 if (workaround_erratum383)
6081 pmap_update_pde(pmap, va, pde, newpde);
6083 pde_store(pde, newpde);
6086 * Invalidate a stale recursive mapping of the page table page.
6089 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6092 * Demote the PV entry.
6094 if ((oldpde & PG_MANAGED) != 0)
6095 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6097 counter_u64_add(pmap_pde_demotions, 1);
6098 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6104 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6107 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6113 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6114 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6115 mpte = pmap_remove_pt_page(pmap, va);
6117 panic("pmap_remove_kernel_pde: Missing pt page.");
6119 mptepa = VM_PAGE_TO_PHYS(mpte);
6120 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6123 * If this page table page was unmapped by a promotion, then it
6124 * contains valid mappings. Zero it to invalidate those mappings.
6126 if (vm_page_any_valid(mpte))
6127 pagezero((void *)PHYS_TO_DMAP(mptepa));
6130 * Demote the mapping.
6132 if (workaround_erratum383)
6133 pmap_update_pde(pmap, va, pde, newpde);
6135 pde_store(pde, newpde);
6138 * Invalidate a stale recursive mapping of the page table page.
6140 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6144 * pmap_remove_pde: do the things to unmap a superpage in a process
6147 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6148 struct spglist *free, struct rwlock **lockp)
6150 struct md_page *pvh;
6152 vm_offset_t eva, va;
6154 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6156 PG_G = pmap_global_bit(pmap);
6157 PG_A = pmap_accessed_bit(pmap);
6158 PG_M = pmap_modified_bit(pmap);
6159 PG_RW = pmap_rw_bit(pmap);
6161 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6162 KASSERT((sva & PDRMASK) == 0,
6163 ("pmap_remove_pde: sva is not 2mpage aligned"));
6164 oldpde = pte_load_clear(pdq);
6166 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6167 if ((oldpde & PG_G) != 0)
6168 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6169 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6170 if (oldpde & PG_MANAGED) {
6171 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6172 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6173 pmap_pvh_free(pvh, pmap, sva);
6175 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6176 va < eva; va += PAGE_SIZE, m++) {
6177 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6180 vm_page_aflag_set(m, PGA_REFERENCED);
6181 if (TAILQ_EMPTY(&m->md.pv_list) &&
6182 TAILQ_EMPTY(&pvh->pv_list))
6183 vm_page_aflag_clear(m, PGA_WRITEABLE);
6184 pmap_delayed_invl_page(m);
6187 if (pmap == kernel_pmap) {
6188 pmap_remove_kernel_pde(pmap, pdq, sva);
6190 mpte = pmap_remove_pt_page(pmap, sva);
6192 KASSERT(vm_page_all_valid(mpte),
6193 ("pmap_remove_pde: pte page not promoted"));
6194 pmap_pt_page_count_adj(pmap, -1);
6195 KASSERT(mpte->ref_count == NPTEPG,
6196 ("pmap_remove_pde: pte page ref count error"));
6197 mpte->ref_count = 0;
6198 pmap_add_delayed_free_list(mpte, free, FALSE);
6201 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6205 * pmap_remove_pte: do the things to unmap a page in a process
6208 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6209 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6211 struct md_page *pvh;
6212 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6215 PG_A = pmap_accessed_bit(pmap);
6216 PG_M = pmap_modified_bit(pmap);
6217 PG_RW = pmap_rw_bit(pmap);
6219 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6220 oldpte = pte_load_clear(ptq);
6222 pmap->pm_stats.wired_count -= 1;
6223 pmap_resident_count_adj(pmap, -1);
6224 if (oldpte & PG_MANAGED) {
6225 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6226 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6229 vm_page_aflag_set(m, PGA_REFERENCED);
6230 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6231 pmap_pvh_free(&m->md, pmap, va);
6232 if (TAILQ_EMPTY(&m->md.pv_list) &&
6233 (m->flags & PG_FICTITIOUS) == 0) {
6234 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6235 if (TAILQ_EMPTY(&pvh->pv_list))
6236 vm_page_aflag_clear(m, PGA_WRITEABLE);
6238 pmap_delayed_invl_page(m);
6240 return (pmap_unuse_pt(pmap, va, ptepde, free));
6244 * Remove a single page from a process address space
6247 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6248 struct spglist *free)
6250 struct rwlock *lock;
6251 pt_entry_t *pte, PG_V;
6253 PG_V = pmap_valid_bit(pmap);
6254 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6255 if ((*pde & PG_V) == 0)
6257 pte = pmap_pde_to_pte(pde, va);
6258 if ((*pte & PG_V) == 0)
6261 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6264 pmap_invalidate_page(pmap, va);
6268 * Removes the specified range of addresses from the page table page.
6271 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6272 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6274 pt_entry_t PG_G, *pte;
6278 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6279 PG_G = pmap_global_bit(pmap);
6282 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6286 pmap_invalidate_range(pmap, va, sva);
6291 if ((*pte & PG_G) == 0)
6295 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6301 pmap_invalidate_range(pmap, va, sva);
6306 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6308 struct rwlock *lock;
6310 vm_offset_t va_next;
6311 pml5_entry_t *pml5e;
6312 pml4_entry_t *pml4e;
6314 pd_entry_t ptpaddr, *pde;
6315 pt_entry_t PG_G, PG_V;
6316 struct spglist free;
6319 PG_G = pmap_global_bit(pmap);
6320 PG_V = pmap_valid_bit(pmap);
6323 * If there are no resident pages besides the top level page
6324 * table page(s), there is nothing to do. Kernel pmap always
6325 * accounts whole preloaded area as resident, which makes its
6326 * resident count > 2.
6327 * Perform an unsynchronized read. This is, however, safe.
6329 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6336 pmap_delayed_invl_start();
6339 pmap_pkru_on_remove(pmap, sva, eva);
6342 * special handling of removing one page. a very
6343 * common operation and easy to short circuit some
6346 if (sva + PAGE_SIZE == eva) {
6347 pde = pmap_pde(pmap, sva);
6348 if (pde && (*pde & PG_PS) == 0) {
6349 pmap_remove_page(pmap, sva, pde, &free);
6355 for (; sva < eva; sva = va_next) {
6356 if (pmap->pm_stats.resident_count == 0)
6359 if (pmap_is_la57(pmap)) {
6360 pml5e = pmap_pml5e(pmap, sva);
6361 if ((*pml5e & PG_V) == 0) {
6362 va_next = (sva + NBPML5) & ~PML5MASK;
6367 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6369 pml4e = pmap_pml4e(pmap, sva);
6371 if ((*pml4e & PG_V) == 0) {
6372 va_next = (sva + NBPML4) & ~PML4MASK;
6378 va_next = (sva + NBPDP) & ~PDPMASK;
6381 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6382 if ((*pdpe & PG_V) == 0)
6384 if ((*pdpe & PG_PS) != 0) {
6385 KASSERT(va_next <= eva,
6386 ("partial update of non-transparent 1G mapping "
6387 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6388 *pdpe, sva, eva, va_next));
6389 MPASS(pmap != kernel_pmap); /* XXXKIB */
6390 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6393 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6394 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6395 pmap_unwire_ptp(pmap, sva, mt, &free);
6400 * Calculate index for next page table.
6402 va_next = (sva + NBPDR) & ~PDRMASK;
6406 pde = pmap_pdpe_to_pde(pdpe, sva);
6410 * Weed out invalid mappings.
6416 * Check for large page.
6418 if ((ptpaddr & PG_PS) != 0) {
6420 * Are we removing the entire large page? If not,
6421 * demote the mapping and fall through.
6423 if (sva + NBPDR == va_next && eva >= va_next) {
6425 * The TLB entry for a PG_G mapping is
6426 * invalidated by pmap_remove_pde().
6428 if ((ptpaddr & PG_G) == 0)
6430 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6432 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6434 /* The large page mapping was destroyed. */
6441 * Limit our scan to either the end of the va represented
6442 * by the current page table page, or to the end of the
6443 * range being removed.
6448 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6455 pmap_invalidate_all(pmap);
6457 pmap_delayed_invl_finish();
6458 vm_page_free_pages_toq(&free, true);
6462 * Remove the given range of addresses from the specified map.
6464 * It is assumed that the start and end are properly
6465 * rounded to the page size.
6468 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6470 pmap_remove1(pmap, sva, eva, false);
6474 * Remove the given range of addresses as part of a logical unmap
6475 * operation. This has the effect of calling pmap_remove(), but
6476 * also clears any metadata that should persist for the lifetime
6477 * of a logical mapping.
6480 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6482 pmap_remove1(pmap, sva, eva, true);
6486 * Routine: pmap_remove_all
6488 * Removes this physical page from
6489 * all physical maps in which it resides.
6490 * Reflects back modify bits to the pager.
6493 * Original versions of this routine were very
6494 * inefficient because they iteratively called
6495 * pmap_remove (slow...)
6499 pmap_remove_all(vm_page_t m)
6501 struct md_page *pvh;
6504 struct rwlock *lock;
6505 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6508 struct spglist free;
6509 int pvh_gen, md_gen;
6511 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6512 ("pmap_remove_all: page %p is not managed", m));
6514 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6515 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6516 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6519 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6521 if (!PMAP_TRYLOCK(pmap)) {
6522 pvh_gen = pvh->pv_gen;
6526 if (pvh_gen != pvh->pv_gen) {
6532 pde = pmap_pde(pmap, va);
6533 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6536 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6538 if (!PMAP_TRYLOCK(pmap)) {
6539 pvh_gen = pvh->pv_gen;
6540 md_gen = m->md.pv_gen;
6544 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6549 PG_A = pmap_accessed_bit(pmap);
6550 PG_M = pmap_modified_bit(pmap);
6551 PG_RW = pmap_rw_bit(pmap);
6552 pmap_resident_count_adj(pmap, -1);
6553 pde = pmap_pde(pmap, pv->pv_va);
6554 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6555 " a 2mpage in page %p's pv list", m));
6556 pte = pmap_pde_to_pte(pde, pv->pv_va);
6557 tpte = pte_load_clear(pte);
6559 pmap->pm_stats.wired_count--;
6561 vm_page_aflag_set(m, PGA_REFERENCED);
6564 * Update the vm_page_t clean and reference bits.
6566 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6568 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6569 pmap_invalidate_page(pmap, pv->pv_va);
6570 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6572 free_pv_entry(pmap, pv);
6575 vm_page_aflag_clear(m, PGA_WRITEABLE);
6577 pmap_delayed_invl_wait(m);
6578 vm_page_free_pages_toq(&free, true);
6582 * pmap_protect_pde: do the things to protect a 2mpage in a process
6585 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6587 pd_entry_t newpde, oldpde;
6589 boolean_t anychanged;
6590 pt_entry_t PG_G, PG_M, PG_RW;
6592 PG_G = pmap_global_bit(pmap);
6593 PG_M = pmap_modified_bit(pmap);
6594 PG_RW = pmap_rw_bit(pmap);
6596 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6597 KASSERT((sva & PDRMASK) == 0,
6598 ("pmap_protect_pde: sva is not 2mpage aligned"));
6601 oldpde = newpde = *pde;
6602 if ((prot & VM_PROT_WRITE) == 0) {
6603 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6604 (PG_MANAGED | PG_M | PG_RW)) {
6605 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6606 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6609 newpde &= ~(PG_RW | PG_M);
6611 if ((prot & VM_PROT_EXECUTE) == 0)
6613 if (newpde != oldpde) {
6615 * As an optimization to future operations on this PDE, clear
6616 * PG_PROMOTED. The impending invalidation will remove any
6617 * lingering 4KB page mappings from the TLB.
6619 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6621 if ((oldpde & PG_G) != 0)
6622 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6626 return (anychanged);
6630 * Set the physical protection on the
6631 * specified range of this map as requested.
6634 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6637 vm_offset_t va_next;
6638 pml4_entry_t *pml4e;
6640 pd_entry_t ptpaddr, *pde;
6641 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6642 pt_entry_t obits, pbits;
6643 boolean_t anychanged;
6645 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6646 if (prot == VM_PROT_NONE) {
6647 pmap_remove(pmap, sva, eva);
6651 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6652 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6655 PG_G = pmap_global_bit(pmap);
6656 PG_M = pmap_modified_bit(pmap);
6657 PG_V = pmap_valid_bit(pmap);
6658 PG_RW = pmap_rw_bit(pmap);
6662 * Although this function delays and batches the invalidation
6663 * of stale TLB entries, it does not need to call
6664 * pmap_delayed_invl_start() and
6665 * pmap_delayed_invl_finish(), because it does not
6666 * ordinarily destroy mappings. Stale TLB entries from
6667 * protection-only changes need only be invalidated before the
6668 * pmap lock is released, because protection-only changes do
6669 * not destroy PV entries. Even operations that iterate over
6670 * a physical page's PV list of mappings, like
6671 * pmap_remove_write(), acquire the pmap lock for each
6672 * mapping. Consequently, for protection-only changes, the
6673 * pmap lock suffices to synchronize both page table and TLB
6676 * This function only destroys a mapping if pmap_demote_pde()
6677 * fails. In that case, stale TLB entries are immediately
6682 for (; sva < eva; sva = va_next) {
6683 pml4e = pmap_pml4e(pmap, sva);
6684 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6685 va_next = (sva + NBPML4) & ~PML4MASK;
6691 va_next = (sva + NBPDP) & ~PDPMASK;
6694 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6695 if ((*pdpe & PG_V) == 0)
6697 if ((*pdpe & PG_PS) != 0) {
6698 KASSERT(va_next <= eva,
6699 ("partial update of non-transparent 1G mapping "
6700 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6701 *pdpe, sva, eva, va_next));
6703 obits = pbits = *pdpe;
6704 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6705 MPASS(pmap != kernel_pmap); /* XXXKIB */
6706 if ((prot & VM_PROT_WRITE) == 0)
6707 pbits &= ~(PG_RW | PG_M);
6708 if ((prot & VM_PROT_EXECUTE) == 0)
6711 if (pbits != obits) {
6712 if (!atomic_cmpset_long(pdpe, obits, pbits))
6713 /* PG_PS cannot be cleared under us, */
6720 va_next = (sva + NBPDR) & ~PDRMASK;
6724 pde = pmap_pdpe_to_pde(pdpe, sva);
6728 * Weed out invalid mappings.
6734 * Check for large page.
6736 if ((ptpaddr & PG_PS) != 0) {
6738 * Are we protecting the entire large page? If not,
6739 * demote the mapping and fall through.
6741 if (sva + NBPDR == va_next && eva >= va_next) {
6743 * The TLB entry for a PG_G mapping is
6744 * invalidated by pmap_protect_pde().
6746 if (pmap_protect_pde(pmap, pde, sva, prot))
6749 } else if (!pmap_demote_pde(pmap, pde, sva)) {
6751 * The large page mapping was destroyed.
6760 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6763 obits = pbits = *pte;
6764 if ((pbits & PG_V) == 0)
6767 if ((prot & VM_PROT_WRITE) == 0) {
6768 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6769 (PG_MANAGED | PG_M | PG_RW)) {
6770 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6773 pbits &= ~(PG_RW | PG_M);
6775 if ((prot & VM_PROT_EXECUTE) == 0)
6778 if (pbits != obits) {
6779 if (!atomic_cmpset_long(pte, obits, pbits))
6782 pmap_invalidate_page(pmap, sva);
6789 pmap_invalidate_all(pmap);
6793 #if VM_NRESERVLEVEL > 0
6795 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6798 if (pmap->pm_type != PT_EPT)
6800 return ((pde & EPT_PG_EXECUTE) != 0);
6804 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6805 * single page table page (PTP) to a single 2MB page mapping. For promotion
6806 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6807 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6808 * identical characteristics.
6811 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6812 struct rwlock **lockp)
6815 pt_entry_t *firstpte, oldpte, pa, *pte;
6816 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V, PG_PKU_MASK;
6819 PG_A = pmap_accessed_bit(pmap);
6820 PG_G = pmap_global_bit(pmap);
6821 PG_M = pmap_modified_bit(pmap);
6822 PG_V = pmap_valid_bit(pmap);
6823 PG_RW = pmap_rw_bit(pmap);
6824 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6825 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6827 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6830 * Examine the first PTE in the specified PTP. Abort if this PTE is
6831 * ineligible for promotion due to hardware errata, invalid, or does
6832 * not map the first 4KB physical page within a 2MB page.
6834 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6836 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6838 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6839 counter_u64_add(pmap_pde_p_failures, 1);
6840 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6841 " in pmap %p", va, pmap);
6846 * Both here and in the below "for" loop, to allow for repromotion
6847 * after MADV_FREE, conditionally write protect a clean PTE before
6848 * possibly aborting the promotion due to other PTE attributes. Why?
6849 * Suppose that MADV_FREE is applied to a part of a superpage, the
6850 * address range [S, E). pmap_advise() will demote the superpage
6851 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6852 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6853 * imagine that the memory in [S, E) is recycled, but the last 4KB
6854 * page in [S, E) is not the last to be rewritten, or simply accessed.
6855 * In other words, there is still a 4KB page in [S, E), call it P,
6856 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6857 * we write protect P before aborting the promotion, if and when P is
6858 * finally rewritten, there won't be a page fault to trigger
6862 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6864 * When PG_M is already clear, PG_RW can be cleared without
6865 * a TLB invalidation.
6867 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6871 if ((newpde & PG_A) == 0) {
6872 counter_u64_add(pmap_pde_p_failures, 1);
6873 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6874 " in pmap %p", va, pmap);
6879 * Examine each of the other PTEs in the specified PTP. Abort if this
6880 * PTE maps an unexpected 4KB physical page or does not have identical
6881 * characteristics to the first PTE.
6883 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6884 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6886 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6887 counter_u64_add(pmap_pde_p_failures, 1);
6888 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6889 " in pmap %p", va, pmap);
6893 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6895 * When PG_M is already clear, PG_RW can be cleared
6896 * without a TLB invalidation.
6898 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6901 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6902 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6903 (va & ~PDRMASK), pmap);
6905 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6906 counter_u64_add(pmap_pde_p_failures, 1);
6907 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6908 " in pmap %p", va, pmap);
6915 * Save the page table page in its current state until the PDE
6916 * mapping the superpage is demoted by pmap_demote_pde() or
6917 * destroyed by pmap_remove_pde().
6920 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
6921 KASSERT(mpte >= vm_page_array &&
6922 mpte < &vm_page_array[vm_page_array_size],
6923 ("pmap_promote_pde: page table page is out of range"));
6924 KASSERT(mpte->pindex == pmap_pde_pindex(va),
6925 ("pmap_promote_pde: page table page's pindex is wrong "
6926 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
6927 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
6928 if (pmap_insert_pt_page(pmap, mpte, true)) {
6929 counter_u64_add(pmap_pde_p_failures, 1);
6931 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
6937 * Promote the pv entries.
6939 if ((newpde & PG_MANAGED) != 0)
6940 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
6943 * Propagate the PAT index to its proper position.
6945 newpde = pmap_swap_pat(pmap, newpde);
6948 * Map the superpage.
6950 if (workaround_erratum383)
6951 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
6953 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
6955 counter_u64_add(pmap_pde_promotions, 1);
6956 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
6957 " in pmap %p", va, pmap);
6959 #endif /* VM_NRESERVLEVEL > 0 */
6962 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
6966 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
6968 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6969 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
6970 ("psind %d unexpected", psind));
6971 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
6972 ("unaligned phys address %#lx newpte %#lx psind %d",
6973 newpte & PG_FRAME, newpte, psind));
6974 KASSERT((va & (pagesizes[psind] - 1)) == 0,
6975 ("unaligned va %#lx psind %d", va, psind));
6976 KASSERT(va < VM_MAXUSER_ADDRESS,
6977 ("kernel mode non-transparent superpage")); /* XXXKIB */
6978 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
6979 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
6981 PG_V = pmap_valid_bit(pmap);
6984 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind]))
6985 return (KERN_PROTECTION_FAILURE);
6987 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
6988 pten |= pmap_pkru_get(pmap, va);
6990 if (psind == 2) { /* 1G */
6991 pml4e = pmap_pml4e(pmap, va);
6992 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6993 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
6997 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
6998 pdpe = &pdpe[pmap_pdpe_index(va)];
7000 MPASS(origpte == 0);
7002 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7003 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7005 if ((origpte & PG_V) == 0) {
7006 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7011 } else /* (psind == 1) */ { /* 2M */
7012 pde = pmap_pde(pmap, va);
7014 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7018 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7019 pde = &pde[pmap_pde_index(va)];
7021 MPASS(origpte == 0);
7024 if ((origpte & PG_V) == 0) {
7025 pdpe = pmap_pdpe(pmap, va);
7026 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7027 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7033 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7034 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7035 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7036 va, psind == 2 ? "1G" : "2M", origpte, pten));
7037 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7038 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7039 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7040 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7041 if ((origpte & PG_V) == 0)
7042 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7044 return (KERN_SUCCESS);
7047 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7048 return (KERN_RESOURCE_SHORTAGE);
7056 * Insert the given physical page (p) at
7057 * the specified virtual address (v) in the
7058 * target physical map with the protection requested.
7060 * If specified, the page will be wired down, meaning
7061 * that the related pte can not be reclaimed.
7063 * NB: This is the only routine which MAY NOT lazy-evaluate
7064 * or lose information. That is, this routine must actually
7065 * insert this page into the given map NOW.
7067 * When destroying both a page table and PV entry, this function
7068 * performs the TLB invalidation before releasing the PV list
7069 * lock, so we do not need pmap_delayed_invl_page() calls here.
7072 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7073 u_int flags, int8_t psind)
7075 struct rwlock *lock;
7077 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7078 pt_entry_t newpte, origpte;
7085 PG_A = pmap_accessed_bit(pmap);
7086 PG_G = pmap_global_bit(pmap);
7087 PG_M = pmap_modified_bit(pmap);
7088 PG_V = pmap_valid_bit(pmap);
7089 PG_RW = pmap_rw_bit(pmap);
7091 va = trunc_page(va);
7092 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7093 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7094 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7096 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7097 ("pmap_enter: managed mapping within the clean submap"));
7098 if ((m->oflags & VPO_UNMANAGED) == 0)
7099 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7100 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7101 ("pmap_enter: flags %u has reserved bits set", flags));
7102 pa = VM_PAGE_TO_PHYS(m);
7103 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7104 if ((flags & VM_PROT_WRITE) != 0)
7106 if ((prot & VM_PROT_WRITE) != 0)
7108 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7109 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7110 if ((prot & VM_PROT_EXECUTE) == 0)
7112 if ((flags & PMAP_ENTER_WIRED) != 0)
7114 if (va < VM_MAXUSER_ADDRESS)
7116 if (pmap == kernel_pmap)
7118 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7121 * Set modified bit gratuitously for writeable mappings if
7122 * the page is unmanaged. We do not want to take a fault
7123 * to do the dirty bit accounting for these mappings.
7125 if ((m->oflags & VPO_UNMANAGED) != 0) {
7126 if ((newpte & PG_RW) != 0)
7129 newpte |= PG_MANAGED;
7133 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7134 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7135 ("managed largepage va %#lx flags %#x", va, flags));
7136 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7141 /* Assert the required virtual and physical alignment. */
7142 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7143 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7144 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7150 * In the case that a page table page is not
7151 * resident, we are creating it here.
7154 pde = pmap_pde(pmap, va);
7155 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7156 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7157 pte = pmap_pde_to_pte(pde, va);
7158 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7159 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7162 } else if (va < VM_MAXUSER_ADDRESS) {
7164 * Here if the pte page isn't mapped, or if it has been
7167 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7168 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7169 nosleep ? NULL : &lock, va);
7170 if (mpte == NULL && nosleep) {
7171 rv = KERN_RESOURCE_SHORTAGE;
7176 panic("pmap_enter: invalid page directory va=%#lx", va);
7180 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7181 newpte |= pmap_pkru_get(pmap, va);
7184 * Is the specified virtual address already mapped?
7186 if ((origpte & PG_V) != 0) {
7188 * Wiring change, just update stats. We don't worry about
7189 * wiring PT pages as they remain resident as long as there
7190 * are valid mappings in them. Hence, if a user page is wired,
7191 * the PT page will be also.
7193 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7194 pmap->pm_stats.wired_count++;
7195 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7196 pmap->pm_stats.wired_count--;
7199 * Remove the extra PT page reference.
7203 KASSERT(mpte->ref_count > 0,
7204 ("pmap_enter: missing reference to page table page,"
7209 * Has the physical page changed?
7211 opa = origpte & PG_FRAME;
7214 * No, might be a protection or wiring change.
7216 if ((origpte & PG_MANAGED) != 0 &&
7217 (newpte & PG_RW) != 0)
7218 vm_page_aflag_set(m, PGA_WRITEABLE);
7219 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7225 * The physical page has changed. Temporarily invalidate
7226 * the mapping. This ensures that all threads sharing the
7227 * pmap keep a consistent view of the mapping, which is
7228 * necessary for the correct handling of COW faults. It
7229 * also permits reuse of the old mapping's PV entry,
7230 * avoiding an allocation.
7232 * For consistency, handle unmanaged mappings the same way.
7234 origpte = pte_load_clear(pte);
7235 KASSERT((origpte & PG_FRAME) == opa,
7236 ("pmap_enter: unexpected pa update for %#lx", va));
7237 if ((origpte & PG_MANAGED) != 0) {
7238 om = PHYS_TO_VM_PAGE(opa);
7241 * The pmap lock is sufficient to synchronize with
7242 * concurrent calls to pmap_page_test_mappings() and
7243 * pmap_ts_referenced().
7245 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7247 if ((origpte & PG_A) != 0) {
7248 pmap_invalidate_page(pmap, va);
7249 vm_page_aflag_set(om, PGA_REFERENCED);
7251 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7252 pv = pmap_pvh_remove(&om->md, pmap, va);
7254 ("pmap_enter: no PV entry for %#lx", va));
7255 if ((newpte & PG_MANAGED) == 0)
7256 free_pv_entry(pmap, pv);
7257 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7258 TAILQ_EMPTY(&om->md.pv_list) &&
7259 ((om->flags & PG_FICTITIOUS) != 0 ||
7260 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7261 vm_page_aflag_clear(om, PGA_WRITEABLE);
7264 * Since this mapping is unmanaged, assume that PG_A
7267 pmap_invalidate_page(pmap, va);
7272 * Increment the counters.
7274 if ((newpte & PG_W) != 0)
7275 pmap->pm_stats.wired_count++;
7276 pmap_resident_count_adj(pmap, 1);
7280 * Enter on the PV list if part of our managed memory.
7282 if ((newpte & PG_MANAGED) != 0) {
7284 pv = get_pv_entry(pmap, &lock);
7287 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7288 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7290 if ((newpte & PG_RW) != 0)
7291 vm_page_aflag_set(m, PGA_WRITEABLE);
7297 if ((origpte & PG_V) != 0) {
7299 origpte = pte_load_store(pte, newpte);
7300 KASSERT((origpte & PG_FRAME) == pa,
7301 ("pmap_enter: unexpected pa update for %#lx", va));
7302 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7304 if ((origpte & PG_MANAGED) != 0)
7308 * Although the PTE may still have PG_RW set, TLB
7309 * invalidation may nonetheless be required because
7310 * the PTE no longer has PG_M set.
7312 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7314 * This PTE change does not require TLB invalidation.
7318 if ((origpte & PG_A) != 0)
7319 pmap_invalidate_page(pmap, va);
7321 pte_store(pte, newpte);
7325 #if VM_NRESERVLEVEL > 0
7327 * If both the page table page and the reservation are fully
7328 * populated, then attempt promotion.
7330 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7331 pmap_ps_enabled(pmap) &&
7332 (m->flags & PG_FICTITIOUS) == 0 &&
7333 vm_reserv_level_iffullpop(m) == 0)
7334 pmap_promote_pde(pmap, pde, va, mpte, &lock);
7346 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7347 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7348 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7349 * "no replace", and "no reclaim" are specified.
7352 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7353 struct rwlock **lockp)
7358 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7359 PG_V = pmap_valid_bit(pmap);
7360 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
7362 if ((m->oflags & VPO_UNMANAGED) == 0)
7363 newpde |= PG_MANAGED;
7364 if ((prot & VM_PROT_EXECUTE) == 0)
7366 if (va < VM_MAXUSER_ADDRESS)
7368 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7369 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7373 * Returns true if every page table entry in the specified page table page is
7377 pmap_every_pte_zero(vm_paddr_t pa)
7379 pt_entry_t *pt_end, *pte;
7381 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7382 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7383 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7391 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7392 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7393 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7394 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7395 * page mapping already exists within the 2MB virtual address range starting
7396 * at the specified virtual address or (2) the requested 2MB page mapping is
7397 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7398 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7399 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7400 * settings are not the same across the 2MB virtual address range starting at
7401 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7402 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7403 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7406 * The parameter "m" is only used when creating a managed, writeable mapping.
7409 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7410 vm_page_t m, struct rwlock **lockp)
7412 struct spglist free;
7413 pd_entry_t oldpde, *pde;
7414 pt_entry_t PG_G, PG_RW, PG_V;
7417 KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
7418 ("pmap_enter_pde: cannot create wired user mapping"));
7419 PG_G = pmap_global_bit(pmap);
7420 PG_RW = pmap_rw_bit(pmap);
7421 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7422 ("pmap_enter_pde: newpde is missing PG_M"));
7423 PG_V = pmap_valid_bit(pmap);
7424 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7426 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7428 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7429 " in pmap %p", va, pmap);
7430 return (KERN_FAILURE);
7432 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7433 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7434 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7435 " in pmap %p", va, pmap);
7436 return (KERN_RESOURCE_SHORTAGE);
7440 * If pkru is not same for the whole pde range, return failure
7441 * and let vm_fault() cope. Check after pde allocation, since
7444 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
7445 pmap_abort_ptp(pmap, va, pdpg);
7446 return (KERN_PROTECTION_FAILURE);
7448 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
7449 newpde &= ~X86_PG_PKU_MASK;
7450 newpde |= pmap_pkru_get(pmap, va);
7454 * If there are existing mappings, either abort or remove them.
7457 if ((oldpde & PG_V) != 0) {
7458 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7459 ("pmap_enter_pde: pdpg's reference count is too low"));
7460 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7461 if ((oldpde & PG_PS) != 0) {
7465 "pmap_enter_pde: no space for va %#lx"
7466 " in pmap %p", va, pmap);
7467 return (KERN_NO_SPACE);
7468 } else if (va < VM_MAXUSER_ADDRESS ||
7469 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7473 "pmap_enter_pde: failure for va %#lx"
7474 " in pmap %p", va, pmap);
7475 return (KERN_FAILURE);
7478 /* Break the existing mapping(s). */
7480 if ((oldpde & PG_PS) != 0) {
7482 * The reference to the PD page that was acquired by
7483 * pmap_alloc_pde() ensures that it won't be freed.
7484 * However, if the PDE resulted from a promotion, then
7485 * a reserved PT page could be freed.
7487 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7488 if ((oldpde & PG_G) == 0)
7489 pmap_invalidate_pde_page(pmap, va, oldpde);
7491 pmap_delayed_invl_start();
7492 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7494 pmap_invalidate_all(pmap);
7495 pmap_delayed_invl_finish();
7497 if (va < VM_MAXUSER_ADDRESS) {
7498 vm_page_free_pages_toq(&free, true);
7499 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7502 KASSERT(SLIST_EMPTY(&free),
7503 ("pmap_enter_pde: freed kernel page table page"));
7506 * Both pmap_remove_pde() and pmap_remove_ptes() will
7507 * leave the kernel page table page zero filled.
7509 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7510 if (pmap_insert_pt_page(pmap, mt, false))
7511 panic("pmap_enter_pde: trie insert failed");
7515 if ((newpde & PG_MANAGED) != 0) {
7517 * Abort this mapping if its PV entry could not be created.
7519 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7521 pmap_abort_ptp(pmap, va, pdpg);
7522 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7523 " in pmap %p", va, pmap);
7524 return (KERN_RESOURCE_SHORTAGE);
7526 if ((newpde & PG_RW) != 0) {
7527 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7528 vm_page_aflag_set(mt, PGA_WRITEABLE);
7533 * Increment counters.
7535 if ((newpde & PG_W) != 0)
7536 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7537 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7540 * Map the superpage. (This is not a promoted mapping; there will not
7541 * be any lingering 4KB page mappings in the TLB.)
7543 pde_store(pde, newpde);
7545 counter_u64_add(pmap_pde_mappings, 1);
7546 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7548 return (KERN_SUCCESS);
7552 * Maps a sequence of resident pages belonging to the same object.
7553 * The sequence begins with the given page m_start. This page is
7554 * mapped at the given virtual address start. Each subsequent page is
7555 * mapped at a virtual address that is offset from start by the same
7556 * amount as the page is offset from m_start within the object. The
7557 * last page in the sequence is the page with the largest offset from
7558 * m_start that can be mapped at a virtual address less than the given
7559 * virtual address end. Not every virtual page between start and end
7560 * is mapped; only those for which a resident page exists with the
7561 * corresponding offset from m_start are mapped.
7564 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7565 vm_page_t m_start, vm_prot_t prot)
7567 struct rwlock *lock;
7570 vm_pindex_t diff, psize;
7573 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7575 psize = atop(end - start);
7580 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7581 va = start + ptoa(diff);
7582 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7583 m->psind == 1 && pmap_ps_enabled(pmap) &&
7584 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7585 KERN_SUCCESS || rv == KERN_NO_SPACE))
7586 m = &m[NBPDR / PAGE_SIZE - 1];
7588 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7590 m = TAILQ_NEXT(m, listq);
7598 * this code makes some *MAJOR* assumptions:
7599 * 1. Current pmap & pmap exists.
7602 * 4. No page table pages.
7603 * but is *MUCH* faster than pmap_enter...
7607 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7609 struct rwlock *lock;
7613 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7620 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7621 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7623 pt_entry_t newpte, *pte, PG_V;
7625 KASSERT(!VA_IS_CLEANMAP(va) ||
7626 (m->oflags & VPO_UNMANAGED) != 0,
7627 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7628 PG_V = pmap_valid_bit(pmap);
7629 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7632 * In the case that a page table page is not
7633 * resident, we are creating it here.
7635 if (va < VM_MAXUSER_ADDRESS) {
7638 vm_pindex_t ptepindex;
7641 * Calculate pagetable page index
7643 ptepindex = pmap_pde_pindex(va);
7644 if (mpte && (mpte->pindex == ptepindex)) {
7648 * If the page table page is mapped, we just increment
7649 * the hold count, and activate it. Otherwise, we
7650 * attempt to allocate a page table page, passing NULL
7651 * instead of the PV list lock pointer because we don't
7652 * intend to sleep. If this attempt fails, we don't
7653 * retry. Instead, we give up.
7655 pdpe = pmap_pdpe(pmap, va);
7656 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7657 if ((*pdpe & PG_PS) != 0)
7659 pde = pmap_pdpe_to_pde(pdpe, va);
7660 if ((*pde & PG_V) != 0) {
7661 if ((*pde & PG_PS) != 0)
7663 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7666 mpte = pmap_allocpte_alloc(pmap,
7667 ptepindex, NULL, va);
7672 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7678 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7679 pte = &pte[pmap_pte_index(va)];
7691 * Enter on the PV list if part of our managed memory.
7693 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7694 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7696 pmap_abort_ptp(pmap, va, mpte);
7701 * Increment counters
7703 pmap_resident_count_adj(pmap, 1);
7705 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7706 pmap_cache_bits(pmap, m->md.pat_mode, 0);
7707 if ((m->oflags & VPO_UNMANAGED) == 0)
7708 newpte |= PG_MANAGED;
7709 if ((prot & VM_PROT_EXECUTE) == 0)
7711 if (va < VM_MAXUSER_ADDRESS)
7712 newpte |= PG_U | pmap_pkru_get(pmap, va);
7713 pte_store(pte, newpte);
7718 * Make a temporary mapping for a physical address. This is only intended
7719 * to be used for panic dumps.
7722 pmap_kenter_temporary(vm_paddr_t pa, int i)
7726 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7727 pmap_kenter(va, pa);
7728 pmap_invlpg(kernel_pmap, va);
7729 return ((void *)crashdumpmap);
7733 * This code maps large physical mmap regions into the
7734 * processor address space. Note that some shortcuts
7735 * are taken, but the code works.
7738 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7739 vm_pindex_t pindex, vm_size_t size)
7742 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7743 vm_paddr_t pa, ptepa;
7747 PG_A = pmap_accessed_bit(pmap);
7748 PG_M = pmap_modified_bit(pmap);
7749 PG_V = pmap_valid_bit(pmap);
7750 PG_RW = pmap_rw_bit(pmap);
7752 VM_OBJECT_ASSERT_WLOCKED(object);
7753 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7754 ("pmap_object_init_pt: non-device object"));
7755 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7756 if (!pmap_ps_enabled(pmap))
7758 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7760 p = vm_page_lookup(object, pindex);
7761 KASSERT(vm_page_all_valid(p),
7762 ("pmap_object_init_pt: invalid page %p", p));
7763 pat_mode = p->md.pat_mode;
7766 * Abort the mapping if the first page is not physically
7767 * aligned to a 2MB page boundary.
7769 ptepa = VM_PAGE_TO_PHYS(p);
7770 if (ptepa & (NBPDR - 1))
7774 * Skip the first page. Abort the mapping if the rest of
7775 * the pages are not physically contiguous or have differing
7776 * memory attributes.
7778 p = TAILQ_NEXT(p, listq);
7779 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7781 KASSERT(vm_page_all_valid(p),
7782 ("pmap_object_init_pt: invalid page %p", p));
7783 if (pa != VM_PAGE_TO_PHYS(p) ||
7784 pat_mode != p->md.pat_mode)
7786 p = TAILQ_NEXT(p, listq);
7790 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7791 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7792 * will not affect the termination of this loop.
7795 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
7796 pa < ptepa + size; pa += NBPDR) {
7797 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7800 * The creation of mappings below is only an
7801 * optimization. If a page directory page
7802 * cannot be allocated without blocking,
7803 * continue on to the next mapping rather than
7809 if ((*pde & PG_V) == 0) {
7810 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7811 PG_U | PG_RW | PG_V);
7812 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7813 counter_u64_add(pmap_pde_mappings, 1);
7815 /* Continue on if the PDE is already valid. */
7817 KASSERT(pdpg->ref_count > 0,
7818 ("pmap_object_init_pt: missing reference "
7819 "to page directory page, va: 0x%lx", addr));
7828 * Clear the wired attribute from the mappings for the specified range of
7829 * addresses in the given pmap. Every valid mapping within that range
7830 * must have the wired attribute set. In contrast, invalid mappings
7831 * cannot have the wired attribute set, so they are ignored.
7833 * The wired attribute of the page table entry is not a hardware
7834 * feature, so there is no need to invalidate any TLB entries.
7835 * Since pmap_demote_pde() for the wired entry must never fail,
7836 * pmap_delayed_invl_start()/finish() calls around the
7837 * function are not needed.
7840 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7842 vm_offset_t va_next;
7843 pml4_entry_t *pml4e;
7846 pt_entry_t *pte, PG_V, PG_G __diagused;
7848 PG_V = pmap_valid_bit(pmap);
7849 PG_G = pmap_global_bit(pmap);
7851 for (; sva < eva; sva = va_next) {
7852 pml4e = pmap_pml4e(pmap, sva);
7853 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7854 va_next = (sva + NBPML4) & ~PML4MASK;
7860 va_next = (sva + NBPDP) & ~PDPMASK;
7863 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7864 if ((*pdpe & PG_V) == 0)
7866 if ((*pdpe & PG_PS) != 0) {
7867 KASSERT(va_next <= eva,
7868 ("partial update of non-transparent 1G mapping "
7869 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
7870 *pdpe, sva, eva, va_next));
7871 MPASS(pmap != kernel_pmap); /* XXXKIB */
7872 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
7873 atomic_clear_long(pdpe, PG_W);
7874 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
7878 va_next = (sva + NBPDR) & ~PDRMASK;
7881 pde = pmap_pdpe_to_pde(pdpe, sva);
7882 if ((*pde & PG_V) == 0)
7884 if ((*pde & PG_PS) != 0) {
7885 if ((*pde & PG_W) == 0)
7886 panic("pmap_unwire: pde %#jx is missing PG_W",
7890 * Are we unwiring the entire large page? If not,
7891 * demote the mapping and fall through.
7893 if (sva + NBPDR == va_next && eva >= va_next) {
7894 atomic_clear_long(pde, PG_W);
7895 pmap->pm_stats.wired_count -= NBPDR /
7898 } else if (!pmap_demote_pde(pmap, pde, sva))
7899 panic("pmap_unwire: demotion failed");
7903 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
7905 if ((*pte & PG_V) == 0)
7907 if ((*pte & PG_W) == 0)
7908 panic("pmap_unwire: pte %#jx is missing PG_W",
7912 * PG_W must be cleared atomically. Although the pmap
7913 * lock synchronizes access to PG_W, another processor
7914 * could be setting PG_M and/or PG_A concurrently.
7916 atomic_clear_long(pte, PG_W);
7917 pmap->pm_stats.wired_count--;
7924 * Copy the range specified by src_addr/len
7925 * from the source map to the range dst_addr/len
7926 * in the destination map.
7928 * This routine is only advisory and need not do anything.
7931 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
7932 vm_offset_t src_addr)
7934 struct rwlock *lock;
7935 pml4_entry_t *pml4e;
7937 pd_entry_t *pde, srcptepaddr;
7938 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
7939 vm_offset_t addr, end_addr, va_next;
7940 vm_page_t dst_pdpg, dstmpte, srcmpte;
7942 if (dst_addr != src_addr)
7945 if (dst_pmap->pm_type != src_pmap->pm_type)
7949 * EPT page table entries that require emulation of A/D bits are
7950 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
7951 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
7952 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
7953 * implementations flag an EPT misconfiguration for exec-only
7954 * mappings we skip this function entirely for emulated pmaps.
7956 if (pmap_emulate_ad_bits(dst_pmap))
7959 end_addr = src_addr + len;
7961 if (dst_pmap < src_pmap) {
7962 PMAP_LOCK(dst_pmap);
7963 PMAP_LOCK(src_pmap);
7965 PMAP_LOCK(src_pmap);
7966 PMAP_LOCK(dst_pmap);
7969 PG_A = pmap_accessed_bit(dst_pmap);
7970 PG_M = pmap_modified_bit(dst_pmap);
7971 PG_V = pmap_valid_bit(dst_pmap);
7973 for (addr = src_addr; addr < end_addr; addr = va_next) {
7974 KASSERT(addr < UPT_MIN_ADDRESS,
7975 ("pmap_copy: invalid to pmap_copy page tables"));
7977 pml4e = pmap_pml4e(src_pmap, addr);
7978 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7979 va_next = (addr + NBPML4) & ~PML4MASK;
7985 va_next = (addr + NBPDP) & ~PDPMASK;
7988 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
7989 if ((*pdpe & PG_V) == 0)
7991 if ((*pdpe & PG_PS) != 0) {
7992 KASSERT(va_next <= end_addr,
7993 ("partial update of non-transparent 1G mapping "
7994 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
7995 *pdpe, addr, end_addr, va_next));
7996 MPASS((addr & PDPMASK) == 0);
7997 MPASS((*pdpe & PG_MANAGED) == 0);
7998 srcptepaddr = *pdpe;
7999 pdpe = pmap_pdpe(dst_pmap, addr);
8001 if (pmap_allocpte_alloc(dst_pmap,
8002 pmap_pml4e_pindex(addr), NULL, addr) ==
8005 pdpe = pmap_pdpe(dst_pmap, addr);
8007 pml4e = pmap_pml4e(dst_pmap, addr);
8008 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8009 dst_pdpg->ref_count++;
8012 ("1G mapping present in dst pmap "
8013 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8014 *pdpe, addr, end_addr, va_next));
8015 *pdpe = srcptepaddr & ~PG_W;
8016 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8020 va_next = (addr + NBPDR) & ~PDRMASK;
8024 pde = pmap_pdpe_to_pde(pdpe, addr);
8026 if (srcptepaddr == 0)
8029 if (srcptepaddr & PG_PS) {
8031 * We can only virtual copy whole superpages.
8033 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8035 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8038 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8039 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8040 PMAP_ENTER_NORECLAIM, &lock))) {
8042 * We leave the dirty bit unchanged because
8043 * managed read/write superpage mappings are
8044 * required to be dirty. However, managed
8045 * superpage mappings are not required to
8046 * have their accessed bit set, so we clear
8047 * it because we don't know if this mapping
8050 srcptepaddr &= ~PG_W;
8051 if ((srcptepaddr & PG_MANAGED) != 0)
8052 srcptepaddr &= ~PG_A;
8054 pmap_resident_count_adj(dst_pmap, NBPDR /
8056 counter_u64_add(pmap_pde_mappings, 1);
8058 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8062 srcptepaddr &= PG_FRAME;
8063 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8064 KASSERT(srcmpte->ref_count > 0,
8065 ("pmap_copy: source page table page is unused"));
8067 if (va_next > end_addr)
8070 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8071 src_pte = &src_pte[pmap_pte_index(addr)];
8073 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8077 * We only virtual copy managed pages.
8079 if ((ptetemp & PG_MANAGED) == 0)
8082 if (dstmpte != NULL) {
8083 KASSERT(dstmpte->pindex ==
8084 pmap_pde_pindex(addr),
8085 ("dstmpte pindex/addr mismatch"));
8086 dstmpte->ref_count++;
8087 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8090 dst_pte = (pt_entry_t *)
8091 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8092 dst_pte = &dst_pte[pmap_pte_index(addr)];
8093 if (*dst_pte == 0 &&
8094 pmap_try_insert_pv_entry(dst_pmap, addr,
8095 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8097 * Clear the wired, modified, and accessed
8098 * (referenced) bits during the copy.
8100 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8101 pmap_resident_count_adj(dst_pmap, 1);
8103 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8106 /* Have we copied all of the valid mappings? */
8107 if (dstmpte->ref_count >= srcmpte->ref_count)
8114 PMAP_UNLOCK(src_pmap);
8115 PMAP_UNLOCK(dst_pmap);
8119 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8123 if (dst_pmap->pm_type != src_pmap->pm_type ||
8124 dst_pmap->pm_type != PT_X86 ||
8125 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8128 if (dst_pmap < src_pmap) {
8129 PMAP_LOCK(dst_pmap);
8130 PMAP_LOCK(src_pmap);
8132 PMAP_LOCK(src_pmap);
8133 PMAP_LOCK(dst_pmap);
8135 error = pmap_pkru_copy(dst_pmap, src_pmap);
8136 /* Clean up partial copy on failure due to no memory. */
8137 if (error == ENOMEM)
8138 pmap_pkru_deassign_all(dst_pmap);
8139 PMAP_UNLOCK(src_pmap);
8140 PMAP_UNLOCK(dst_pmap);
8141 if (error != ENOMEM)
8149 * Zero the specified hardware page.
8152 pmap_zero_page(vm_page_t m)
8154 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8156 pagezero((void *)va);
8160 * Zero an area within a single hardware page. off and size must not
8161 * cover an area beyond a single hardware page.
8164 pmap_zero_page_area(vm_page_t m, int off, int size)
8166 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8168 if (off == 0 && size == PAGE_SIZE)
8169 pagezero((void *)va);
8171 bzero((char *)va + off, size);
8175 * Copy 1 specified hardware page to another.
8178 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8180 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8181 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8183 pagecopy((void *)src, (void *)dst);
8186 int unmapped_buf_allowed = 1;
8189 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8190 vm_offset_t b_offset, int xfersize)
8194 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8198 while (xfersize > 0) {
8199 a_pg_offset = a_offset & PAGE_MASK;
8200 pages[0] = ma[a_offset >> PAGE_SHIFT];
8201 b_pg_offset = b_offset & PAGE_MASK;
8202 pages[1] = mb[b_offset >> PAGE_SHIFT];
8203 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8204 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8205 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
8206 a_cp = (char *)vaddr[0] + a_pg_offset;
8207 b_cp = (char *)vaddr[1] + b_pg_offset;
8208 bcopy(a_cp, b_cp, cnt);
8209 if (__predict_false(mapped))
8210 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
8218 * Returns true if the pmap's pv is one of the first
8219 * 16 pvs linked to from this page. This count may
8220 * be changed upwards or downwards in the future; it
8221 * is only necessary that true be returned for a small
8222 * subset of pmaps for proper page aging.
8225 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8227 struct md_page *pvh;
8228 struct rwlock *lock;
8233 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8234 ("pmap_page_exists_quick: page %p is not managed", m));
8236 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8238 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8239 if (PV_PMAP(pv) == pmap) {
8247 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8248 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8249 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8250 if (PV_PMAP(pv) == pmap) {
8264 * pmap_page_wired_mappings:
8266 * Return the number of managed mappings to the given physical page
8270 pmap_page_wired_mappings(vm_page_t m)
8272 struct rwlock *lock;
8273 struct md_page *pvh;
8277 int count, md_gen, pvh_gen;
8279 if ((m->oflags & VPO_UNMANAGED) != 0)
8281 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8285 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8287 if (!PMAP_TRYLOCK(pmap)) {
8288 md_gen = m->md.pv_gen;
8292 if (md_gen != m->md.pv_gen) {
8297 pte = pmap_pte(pmap, pv->pv_va);
8298 if ((*pte & PG_W) != 0)
8302 if ((m->flags & PG_FICTITIOUS) == 0) {
8303 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8304 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8306 if (!PMAP_TRYLOCK(pmap)) {
8307 md_gen = m->md.pv_gen;
8308 pvh_gen = pvh->pv_gen;
8312 if (md_gen != m->md.pv_gen ||
8313 pvh_gen != pvh->pv_gen) {
8318 pte = pmap_pde(pmap, pv->pv_va);
8319 if ((*pte & PG_W) != 0)
8329 * Returns TRUE if the given page is mapped individually or as part of
8330 * a 2mpage. Otherwise, returns FALSE.
8333 pmap_page_is_mapped(vm_page_t m)
8335 struct rwlock *lock;
8338 if ((m->oflags & VPO_UNMANAGED) != 0)
8340 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8342 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8343 ((m->flags & PG_FICTITIOUS) == 0 &&
8344 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8350 * Destroy all managed, non-wired mappings in the given user-space
8351 * pmap. This pmap cannot be active on any processor besides the
8354 * This function cannot be applied to the kernel pmap. Moreover, it
8355 * is not intended for general use. It is only to be used during
8356 * process termination. Consequently, it can be implemented in ways
8357 * that make it faster than pmap_remove(). First, it can more quickly
8358 * destroy mappings by iterating over the pmap's collection of PV
8359 * entries, rather than searching the page table. Second, it doesn't
8360 * have to test and clear the page table entries atomically, because
8361 * no processor is currently accessing the user address space. In
8362 * particular, a page table entry's dirty bit won't change state once
8363 * this function starts.
8365 * Although this function destroys all of the pmap's managed,
8366 * non-wired mappings, it can delay and batch the invalidation of TLB
8367 * entries without calling pmap_delayed_invl_start() and
8368 * pmap_delayed_invl_finish(). Because the pmap is not active on
8369 * any other processor, none of these TLB entries will ever be used
8370 * before their eventual invalidation. Consequently, there is no need
8371 * for either pmap_remove_all() or pmap_remove_write() to wait for
8372 * that eventual TLB invalidation.
8375 pmap_remove_pages(pmap_t pmap)
8378 pt_entry_t *pte, tpte;
8379 pt_entry_t PG_M, PG_RW, PG_V;
8380 struct spglist free;
8381 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8382 vm_page_t m, mpte, mt;
8384 struct md_page *pvh;
8385 struct pv_chunk *pc, *npc;
8386 struct rwlock *lock;
8388 uint64_t inuse, bitmask;
8389 int allfree, field, i, idx;
8393 boolean_t superpage;
8397 * Assert that the given pmap is only active on the current
8398 * CPU. Unfortunately, we cannot block another CPU from
8399 * activating the pmap while this function is executing.
8401 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8404 cpuset_t other_cpus;
8406 other_cpus = all_cpus;
8408 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8409 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8411 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8416 PG_M = pmap_modified_bit(pmap);
8417 PG_V = pmap_valid_bit(pmap);
8418 PG_RW = pmap_rw_bit(pmap);
8420 for (i = 0; i < PMAP_MEMDOM; i++)
8421 TAILQ_INIT(&free_chunks[i]);
8424 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8429 for (field = 0; field < _NPCM; field++) {
8430 inuse = ~pc->pc_map[field] & pc_freemask[field];
8431 while (inuse != 0) {
8433 bitmask = 1UL << bit;
8434 idx = field * 64 + bit;
8435 pv = &pc->pc_pventry[idx];
8438 pte = pmap_pdpe(pmap, pv->pv_va);
8440 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8442 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8445 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8447 pte = &pte[pmap_pte_index(pv->pv_va)];
8451 * Keep track whether 'tpte' is a
8452 * superpage explicitly instead of
8453 * relying on PG_PS being set.
8455 * This is because PG_PS is numerically
8456 * identical to PG_PTE_PAT and thus a
8457 * regular page could be mistaken for
8463 if ((tpte & PG_V) == 0) {
8464 panic("bad pte va %lx pte %lx",
8469 * We cannot remove wired pages from a process' mapping at this time
8477 pc->pc_map[field] |= bitmask;
8480 * Because this pmap is not active on other
8481 * processors, the dirty bit cannot have
8482 * changed state since we last loaded pte.
8487 pa = tpte & PG_PS_FRAME;
8489 pa = tpte & PG_FRAME;
8491 m = PHYS_TO_VM_PAGE(pa);
8492 KASSERT(m->phys_addr == pa,
8493 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8494 m, (uintmax_t)m->phys_addr,
8497 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8498 m < &vm_page_array[vm_page_array_size],
8499 ("pmap_remove_pages: bad tpte %#jx",
8503 * Update the vm_page_t clean/reference bits.
8505 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8507 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8513 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8516 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8517 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8518 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8520 if (TAILQ_EMPTY(&pvh->pv_list)) {
8521 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8522 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8523 TAILQ_EMPTY(&mt->md.pv_list))
8524 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8526 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8528 KASSERT(vm_page_all_valid(mpte),
8529 ("pmap_remove_pages: pte page not promoted"));
8530 pmap_pt_page_count_adj(pmap, -1);
8531 KASSERT(mpte->ref_count == NPTEPG,
8532 ("pmap_remove_pages: pte page reference count error"));
8533 mpte->ref_count = 0;
8534 pmap_add_delayed_free_list(mpte, &free, FALSE);
8537 pmap_resident_count_adj(pmap, -1);
8538 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8540 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8541 TAILQ_EMPTY(&m->md.pv_list) &&
8542 (m->flags & PG_FICTITIOUS) == 0) {
8543 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8544 if (TAILQ_EMPTY(&pvh->pv_list))
8545 vm_page_aflag_clear(m, PGA_WRITEABLE);
8548 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8554 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8555 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8556 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8558 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8559 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8564 pmap_invalidate_all(pmap);
8565 pmap_pkru_deassign_all(pmap);
8566 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8568 vm_page_free_pages_toq(&free, true);
8572 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
8574 struct rwlock *lock;
8576 struct md_page *pvh;
8577 pt_entry_t *pte, mask;
8578 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8580 int md_gen, pvh_gen;
8584 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8587 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8589 if (!PMAP_TRYLOCK(pmap)) {
8590 md_gen = m->md.pv_gen;
8594 if (md_gen != m->md.pv_gen) {
8599 pte = pmap_pte(pmap, pv->pv_va);
8602 PG_M = pmap_modified_bit(pmap);
8603 PG_RW = pmap_rw_bit(pmap);
8604 mask |= PG_RW | PG_M;
8607 PG_A = pmap_accessed_bit(pmap);
8608 PG_V = pmap_valid_bit(pmap);
8609 mask |= PG_V | PG_A;
8611 rv = (*pte & mask) == mask;
8616 if ((m->flags & PG_FICTITIOUS) == 0) {
8617 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8618 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8620 if (!PMAP_TRYLOCK(pmap)) {
8621 md_gen = m->md.pv_gen;
8622 pvh_gen = pvh->pv_gen;
8626 if (md_gen != m->md.pv_gen ||
8627 pvh_gen != pvh->pv_gen) {
8632 pte = pmap_pde(pmap, pv->pv_va);
8635 PG_M = pmap_modified_bit(pmap);
8636 PG_RW = pmap_rw_bit(pmap);
8637 mask |= PG_RW | PG_M;
8640 PG_A = pmap_accessed_bit(pmap);
8641 PG_V = pmap_valid_bit(pmap);
8642 mask |= PG_V | PG_A;
8644 rv = (*pte & mask) == mask;
8658 * Return whether or not the specified physical page was modified
8659 * in any physical maps.
8662 pmap_is_modified(vm_page_t m)
8665 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8666 ("pmap_is_modified: page %p is not managed", m));
8669 * If the page is not busied then this check is racy.
8671 if (!pmap_page_is_write_mapped(m))
8673 return (pmap_page_test_mappings(m, FALSE, TRUE));
8677 * pmap_is_prefaultable:
8679 * Return whether or not the specified virtual address is eligible
8683 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8686 pt_entry_t *pte, PG_V;
8689 PG_V = pmap_valid_bit(pmap);
8692 * Return TRUE if and only if the PTE for the specified virtual
8693 * address is allocated but invalid.
8697 pde = pmap_pde(pmap, addr);
8698 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8699 pte = pmap_pde_to_pte(pde, addr);
8700 rv = (*pte & PG_V) == 0;
8707 * pmap_is_referenced:
8709 * Return whether or not the specified physical page was referenced
8710 * in any physical maps.
8713 pmap_is_referenced(vm_page_t m)
8716 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8717 ("pmap_is_referenced: page %p is not managed", m));
8718 return (pmap_page_test_mappings(m, TRUE, FALSE));
8722 * Clear the write and modified bits in each of the given page's mappings.
8725 pmap_remove_write(vm_page_t m)
8727 struct md_page *pvh;
8729 struct rwlock *lock;
8730 pv_entry_t next_pv, pv;
8732 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8734 int pvh_gen, md_gen;
8736 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8737 ("pmap_remove_write: page %p is not managed", m));
8739 vm_page_assert_busied(m);
8740 if (!pmap_page_is_write_mapped(m))
8743 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8744 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8745 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8748 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8750 if (!PMAP_TRYLOCK(pmap)) {
8751 pvh_gen = pvh->pv_gen;
8755 if (pvh_gen != pvh->pv_gen) {
8760 PG_RW = pmap_rw_bit(pmap);
8762 pde = pmap_pde(pmap, va);
8763 if ((*pde & PG_RW) != 0)
8764 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8765 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8766 ("inconsistent pv lock %p %p for page %p",
8767 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8770 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8772 if (!PMAP_TRYLOCK(pmap)) {
8773 pvh_gen = pvh->pv_gen;
8774 md_gen = m->md.pv_gen;
8778 if (pvh_gen != pvh->pv_gen ||
8779 md_gen != m->md.pv_gen) {
8784 PG_M = pmap_modified_bit(pmap);
8785 PG_RW = pmap_rw_bit(pmap);
8786 pde = pmap_pde(pmap, pv->pv_va);
8787 KASSERT((*pde & PG_PS) == 0,
8788 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8790 pte = pmap_pde_to_pte(pde, pv->pv_va);
8792 if (oldpte & PG_RW) {
8793 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8796 if ((oldpte & PG_M) != 0)
8798 pmap_invalidate_page(pmap, pv->pv_va);
8803 vm_page_aflag_clear(m, PGA_WRITEABLE);
8804 pmap_delayed_invl_wait(m);
8807 static __inline boolean_t
8808 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
8811 if (!pmap_emulate_ad_bits(pmap))
8814 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
8817 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
8818 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
8819 * if the EPT_PG_WRITE bit is set.
8821 if ((pte & EPT_PG_WRITE) != 0)
8825 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
8827 if ((pte & EPT_PG_EXECUTE) == 0 ||
8828 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
8835 * pmap_ts_referenced:
8837 * Return a count of reference bits for a page, clearing those bits.
8838 * It is not necessary for every reference bit to be cleared, but it
8839 * is necessary that 0 only be returned when there are truly no
8840 * reference bits set.
8842 * As an optimization, update the page's dirty field if a modified bit is
8843 * found while counting reference bits. This opportunistic update can be
8844 * performed at low cost and can eliminate the need for some future calls
8845 * to pmap_is_modified(). However, since this function stops after
8846 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8847 * dirty pages. Those dirty pages will only be detected by a future call
8848 * to pmap_is_modified().
8850 * A DI block is not needed within this function, because
8851 * invalidations are performed before the PV list lock is
8855 pmap_ts_referenced(vm_page_t m)
8857 struct md_page *pvh;
8860 struct rwlock *lock;
8861 pd_entry_t oldpde, *pde;
8862 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8865 int cleared, md_gen, not_cleared, pvh_gen;
8866 struct spglist free;
8869 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8870 ("pmap_ts_referenced: page %p is not managed", m));
8873 pa = VM_PAGE_TO_PHYS(m);
8874 lock = PHYS_TO_PV_LIST_LOCK(pa);
8875 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8879 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
8880 goto small_mappings;
8886 if (!PMAP_TRYLOCK(pmap)) {
8887 pvh_gen = pvh->pv_gen;
8891 if (pvh_gen != pvh->pv_gen) {
8896 PG_A = pmap_accessed_bit(pmap);
8897 PG_M = pmap_modified_bit(pmap);
8898 PG_RW = pmap_rw_bit(pmap);
8900 pde = pmap_pde(pmap, pv->pv_va);
8902 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8904 * Although "oldpde" is mapping a 2MB page, because
8905 * this function is called at a 4KB page granularity,
8906 * we only update the 4KB page under test.
8910 if ((oldpde & PG_A) != 0) {
8912 * Since this reference bit is shared by 512 4KB
8913 * pages, it should not be cleared every time it is
8914 * tested. Apply a simple "hash" function on the
8915 * physical page number, the virtual superpage number,
8916 * and the pmap address to select one 4KB page out of
8917 * the 512 on which testing the reference bit will
8918 * result in clearing that reference bit. This
8919 * function is designed to avoid the selection of the
8920 * same 4KB page for every 2MB page mapping.
8922 * On demotion, a mapping that hasn't been referenced
8923 * is simply destroyed. To avoid the possibility of a
8924 * subsequent page fault on a demoted wired mapping,
8925 * always leave its reference bit set. Moreover,
8926 * since the superpage is wired, the current state of
8927 * its reference bit won't affect page replacement.
8929 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
8930 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
8931 (oldpde & PG_W) == 0) {
8932 if (safe_to_clear_referenced(pmap, oldpde)) {
8933 atomic_clear_long(pde, PG_A);
8934 pmap_invalidate_page(pmap, pv->pv_va);
8936 } else if (pmap_demote_pde_locked(pmap, pde,
8937 pv->pv_va, &lock)) {
8939 * Remove the mapping to a single page
8940 * so that a subsequent access may
8941 * repromote. Since the underlying
8942 * page table page is fully populated,
8943 * this removal never frees a page
8947 va += VM_PAGE_TO_PHYS(m) - (oldpde &
8949 pte = pmap_pde_to_pte(pde, va);
8950 pmap_remove_pte(pmap, pte, va, *pde,
8952 pmap_invalidate_page(pmap, va);
8958 * The superpage mapping was removed
8959 * entirely and therefore 'pv' is no
8967 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8968 ("inconsistent pv lock %p %p for page %p",
8969 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8974 /* Rotate the PV list if it has more than one entry. */
8975 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
8976 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8977 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
8980 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
8982 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
8984 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
8991 if (!PMAP_TRYLOCK(pmap)) {
8992 pvh_gen = pvh->pv_gen;
8993 md_gen = m->md.pv_gen;
8997 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9002 PG_A = pmap_accessed_bit(pmap);
9003 PG_M = pmap_modified_bit(pmap);
9004 PG_RW = pmap_rw_bit(pmap);
9005 pde = pmap_pde(pmap, pv->pv_va);
9006 KASSERT((*pde & PG_PS) == 0,
9007 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9009 pte = pmap_pde_to_pte(pde, pv->pv_va);
9010 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9012 if ((*pte & PG_A) != 0) {
9013 if (safe_to_clear_referenced(pmap, *pte)) {
9014 atomic_clear_long(pte, PG_A);
9015 pmap_invalidate_page(pmap, pv->pv_va);
9017 } else if ((*pte & PG_W) == 0) {
9019 * Wired pages cannot be paged out so
9020 * doing accessed bit emulation for
9021 * them is wasted effort. We do the
9022 * hard work for unwired pages only.
9024 pmap_remove_pte(pmap, pte, pv->pv_va,
9025 *pde, &free, &lock);
9026 pmap_invalidate_page(pmap, pv->pv_va);
9031 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9032 ("inconsistent pv lock %p %p for page %p",
9033 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9038 /* Rotate the PV list if it has more than one entry. */
9039 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9040 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9041 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9044 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9045 not_cleared < PMAP_TS_REFERENCED_MAX);
9048 vm_page_free_pages_toq(&free, true);
9049 return (cleared + not_cleared);
9053 * Apply the given advice to the specified range of addresses within the
9054 * given pmap. Depending on the advice, clear the referenced and/or
9055 * modified flags in each mapping and set the mapped page's dirty field.
9058 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9060 struct rwlock *lock;
9061 pml4_entry_t *pml4e;
9063 pd_entry_t oldpde, *pde;
9064 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9065 vm_offset_t va, va_next;
9069 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9073 * A/D bit emulation requires an alternate code path when clearing
9074 * the modified and accessed bits below. Since this function is
9075 * advisory in nature we skip it entirely for pmaps that require
9076 * A/D bit emulation.
9078 if (pmap_emulate_ad_bits(pmap))
9081 PG_A = pmap_accessed_bit(pmap);
9082 PG_G = pmap_global_bit(pmap);
9083 PG_M = pmap_modified_bit(pmap);
9084 PG_V = pmap_valid_bit(pmap);
9085 PG_RW = pmap_rw_bit(pmap);
9087 pmap_delayed_invl_start();
9089 for (; sva < eva; sva = va_next) {
9090 pml4e = pmap_pml4e(pmap, sva);
9091 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9092 va_next = (sva + NBPML4) & ~PML4MASK;
9098 va_next = (sva + NBPDP) & ~PDPMASK;
9101 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9102 if ((*pdpe & PG_V) == 0)
9104 if ((*pdpe & PG_PS) != 0)
9107 va_next = (sva + NBPDR) & ~PDRMASK;
9110 pde = pmap_pdpe_to_pde(pdpe, sva);
9112 if ((oldpde & PG_V) == 0)
9114 else if ((oldpde & PG_PS) != 0) {
9115 if ((oldpde & PG_MANAGED) == 0)
9118 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9123 * The large page mapping was destroyed.
9129 * Unless the page mappings are wired, remove the
9130 * mapping to a single page so that a subsequent
9131 * access may repromote. Choosing the last page
9132 * within the address range [sva, min(va_next, eva))
9133 * generally results in more repromotions. Since the
9134 * underlying page table page is fully populated, this
9135 * removal never frees a page table page.
9137 if ((oldpde & PG_W) == 0) {
9143 ("pmap_advise: no address gap"));
9144 pte = pmap_pde_to_pte(pde, va);
9145 KASSERT((*pte & PG_V) != 0,
9146 ("pmap_advise: invalid PTE"));
9147 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9157 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9159 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9161 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9162 if (advice == MADV_DONTNEED) {
9164 * Future calls to pmap_is_modified()
9165 * can be avoided by making the page
9168 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9171 atomic_clear_long(pte, PG_M | PG_A);
9172 } else if ((*pte & PG_A) != 0)
9173 atomic_clear_long(pte, PG_A);
9177 if ((*pte & PG_G) != 0) {
9184 if (va != va_next) {
9185 pmap_invalidate_range(pmap, va, sva);
9190 pmap_invalidate_range(pmap, va, sva);
9193 pmap_invalidate_all(pmap);
9195 pmap_delayed_invl_finish();
9199 * Clear the modify bits on the specified physical page.
9202 pmap_clear_modify(vm_page_t m)
9204 struct md_page *pvh;
9206 pv_entry_t next_pv, pv;
9207 pd_entry_t oldpde, *pde;
9208 pt_entry_t *pte, PG_M, PG_RW;
9209 struct rwlock *lock;
9211 int md_gen, pvh_gen;
9213 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9214 ("pmap_clear_modify: page %p is not managed", m));
9215 vm_page_assert_busied(m);
9217 if (!pmap_page_is_write_mapped(m))
9219 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9220 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9221 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9224 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9226 if (!PMAP_TRYLOCK(pmap)) {
9227 pvh_gen = pvh->pv_gen;
9231 if (pvh_gen != pvh->pv_gen) {
9236 PG_M = pmap_modified_bit(pmap);
9237 PG_RW = pmap_rw_bit(pmap);
9239 pde = pmap_pde(pmap, va);
9241 /* If oldpde has PG_RW set, then it also has PG_M set. */
9242 if ((oldpde & PG_RW) != 0 &&
9243 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9244 (oldpde & PG_W) == 0) {
9246 * Write protect the mapping to a single page so that
9247 * a subsequent write access may repromote.
9249 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9250 pte = pmap_pde_to_pte(pde, va);
9251 atomic_clear_long(pte, PG_M | PG_RW);
9253 pmap_invalidate_page(pmap, va);
9257 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9259 if (!PMAP_TRYLOCK(pmap)) {
9260 md_gen = m->md.pv_gen;
9261 pvh_gen = pvh->pv_gen;
9265 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9270 PG_M = pmap_modified_bit(pmap);
9271 PG_RW = pmap_rw_bit(pmap);
9272 pde = pmap_pde(pmap, pv->pv_va);
9273 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9274 " a 2mpage in page %p's pv list", m));
9275 pte = pmap_pde_to_pte(pde, pv->pv_va);
9276 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9277 atomic_clear_long(pte, PG_M);
9278 pmap_invalidate_page(pmap, pv->pv_va);
9286 * Miscellaneous support routines follow
9289 /* Adjust the properties for a leaf page table entry. */
9290 static __inline void
9291 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9295 opte = *(u_long *)pte;
9297 npte = opte & ~mask;
9299 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9304 * Map a set of physical memory pages into the kernel virtual
9305 * address space. Return a pointer to where it is mapped. This
9306 * routine is intended to be used for mapping device memory,
9310 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9312 struct pmap_preinit_mapping *ppim;
9313 vm_offset_t va, offset;
9317 offset = pa & PAGE_MASK;
9318 size = round_page(offset + size);
9319 pa = trunc_page(pa);
9321 if (!pmap_initialized) {
9323 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9324 ppim = pmap_preinit_mapping + i;
9325 if (ppim->va == 0) {
9329 ppim->va = virtual_avail;
9330 virtual_avail += size;
9336 panic("%s: too many preinit mappings", __func__);
9339 * If we have a preinit mapping, re-use it.
9341 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9342 ppim = pmap_preinit_mapping + i;
9343 if (ppim->pa == pa && ppim->sz == size &&
9344 (ppim->mode == mode ||
9345 (flags & MAPDEV_SETATTR) == 0))
9346 return ((void *)(ppim->va + offset));
9349 * If the specified range of physical addresses fits within
9350 * the direct map window, use the direct map.
9352 if (pa < dmaplimit && pa + size <= dmaplimit) {
9353 va = PHYS_TO_DMAP(pa);
9354 if ((flags & MAPDEV_SETATTR) != 0) {
9355 PMAP_LOCK(kernel_pmap);
9356 i = pmap_change_props_locked(va, size,
9357 PROT_NONE, mode, flags);
9358 PMAP_UNLOCK(kernel_pmap);
9362 return ((void *)(va + offset));
9364 va = kva_alloc(size);
9366 panic("%s: Couldn't allocate KVA", __func__);
9368 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9369 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9370 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9371 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9372 pmap_invalidate_cache_range(va, va + tmpsize);
9373 return ((void *)(va + offset));
9377 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9380 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9385 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9388 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9392 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9395 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9400 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9403 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9404 MAPDEV_FLUSHCACHE));
9408 pmap_unmapdev(void *p, vm_size_t size)
9410 struct pmap_preinit_mapping *ppim;
9411 vm_offset_t offset, va;
9414 va = (vm_offset_t)p;
9416 /* If we gave a direct map region in pmap_mapdev, do nothing */
9417 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9419 offset = va & PAGE_MASK;
9420 size = round_page(offset + size);
9421 va = trunc_page(va);
9422 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9423 ppim = pmap_preinit_mapping + i;
9424 if (ppim->va == va && ppim->sz == size) {
9425 if (pmap_initialized)
9431 if (va + size == virtual_avail)
9436 if (pmap_initialized) {
9437 pmap_qremove(va, atop(size));
9443 * Tries to demote a 1GB page mapping.
9446 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9448 pdp_entry_t newpdpe, oldpdpe;
9449 pd_entry_t *firstpde, newpde, *pde;
9450 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9454 PG_A = pmap_accessed_bit(pmap);
9455 PG_M = pmap_modified_bit(pmap);
9456 PG_V = pmap_valid_bit(pmap);
9457 PG_RW = pmap_rw_bit(pmap);
9459 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9461 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9462 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9463 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9464 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9466 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9467 " in pmap %p", va, pmap);
9470 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9471 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9472 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9473 KASSERT((oldpdpe & PG_A) != 0,
9474 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9475 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9476 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9480 * Initialize the page directory page.
9482 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9488 * Demote the mapping.
9493 * Invalidate a stale recursive mapping of the page directory page.
9495 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9497 counter_u64_add(pmap_pdpe_demotions, 1);
9498 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9499 " in pmap %p", va, pmap);
9504 * Sets the memory attribute for the specified page.
9507 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9510 m->md.pat_mode = ma;
9513 * If "m" is a normal page, update its direct mapping. This update
9514 * can be relied upon to perform any cache operations that are
9515 * required for data coherence.
9517 if ((m->flags & PG_FICTITIOUS) == 0 &&
9518 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9520 panic("memory attribute change on the direct map failed");
9524 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9528 m->md.pat_mode = ma;
9530 if ((m->flags & PG_FICTITIOUS) != 0)
9532 PMAP_LOCK(kernel_pmap);
9533 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9534 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9535 PMAP_UNLOCK(kernel_pmap);
9537 panic("memory attribute change on the direct map failed");
9541 * Changes the specified virtual address range's memory type to that given by
9542 * the parameter "mode". The specified virtual address range must be
9543 * completely contained within either the direct map or the kernel map. If
9544 * the virtual address range is contained within the kernel map, then the
9545 * memory type for each of the corresponding ranges of the direct map is also
9546 * changed. (The corresponding ranges of the direct map are those ranges that
9547 * map the same physical pages as the specified virtual address range.) These
9548 * changes to the direct map are necessary because Intel describes the
9549 * behavior of their processors as "undefined" if two or more mappings to the
9550 * same physical page have different memory types.
9552 * Returns zero if the change completed successfully, and either EINVAL or
9553 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9554 * of the virtual address range was not mapped, and ENOMEM is returned if
9555 * there was insufficient memory available to complete the change. In the
9556 * latter case, the memory type may have been changed on some part of the
9557 * virtual address range or the direct map.
9560 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9564 PMAP_LOCK(kernel_pmap);
9565 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9567 PMAP_UNLOCK(kernel_pmap);
9572 * Changes the specified virtual address range's protections to those
9573 * specified by "prot". Like pmap_change_attr(), protections for aliases
9574 * in the direct map are updated as well. Protections on aliasing mappings may
9575 * be a subset of the requested protections; for example, mappings in the direct
9576 * map are never executable.
9579 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9583 /* Only supported within the kernel map. */
9584 if (va < VM_MIN_KERNEL_ADDRESS)
9587 PMAP_LOCK(kernel_pmap);
9588 error = pmap_change_props_locked(va, size, prot, -1,
9589 MAPDEV_ASSERTVALID);
9590 PMAP_UNLOCK(kernel_pmap);
9595 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9596 int mode, int flags)
9598 vm_offset_t base, offset, tmpva;
9599 vm_paddr_t pa_start, pa_end, pa_end1;
9601 pd_entry_t *pde, pde_bits, pde_mask;
9602 pt_entry_t *pte, pte_bits, pte_mask;
9606 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9607 base = trunc_page(va);
9608 offset = va & PAGE_MASK;
9609 size = round_page(offset + size);
9612 * Only supported on kernel virtual addresses, including the direct
9613 * map but excluding the recursive map.
9615 if (base < DMAP_MIN_ADDRESS)
9619 * Construct our flag sets and masks. "bits" is the subset of
9620 * "mask" that will be set in each modified PTE.
9622 * Mappings in the direct map are never allowed to be executable.
9624 pde_bits = pte_bits = 0;
9625 pde_mask = pte_mask = 0;
9627 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9628 pde_mask |= X86_PG_PDE_CACHE;
9629 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9630 pte_mask |= X86_PG_PTE_CACHE;
9632 if (prot != VM_PROT_NONE) {
9633 if ((prot & VM_PROT_WRITE) != 0) {
9634 pde_bits |= X86_PG_RW;
9635 pte_bits |= X86_PG_RW;
9637 if ((prot & VM_PROT_EXECUTE) == 0 ||
9638 va < VM_MIN_KERNEL_ADDRESS) {
9642 pde_mask |= X86_PG_RW | pg_nx;
9643 pte_mask |= X86_PG_RW | pg_nx;
9647 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9648 * into 4KB pages if required.
9650 for (tmpva = base; tmpva < base + size; ) {
9651 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9652 if (pdpe == NULL || *pdpe == 0) {
9653 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9654 ("%s: addr %#lx is not mapped", __func__, tmpva));
9657 if (*pdpe & PG_PS) {
9659 * If the current 1GB page already has the required
9660 * properties, then we need not demote this page. Just
9661 * increment tmpva to the next 1GB page frame.
9663 if ((*pdpe & pde_mask) == pde_bits) {
9664 tmpva = trunc_1gpage(tmpva) + NBPDP;
9669 * If the current offset aligns with a 1GB page frame
9670 * and there is at least 1GB left within the range, then
9671 * we need not break down this page into 2MB pages.
9673 if ((tmpva & PDPMASK) == 0 &&
9674 tmpva + PDPMASK < base + size) {
9678 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9681 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9683 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9684 ("%s: addr %#lx is not mapped", __func__, tmpva));
9689 * If the current 2MB page already has the required
9690 * properties, then we need not demote this page. Just
9691 * increment tmpva to the next 2MB page frame.
9693 if ((*pde & pde_mask) == pde_bits) {
9694 tmpva = trunc_2mpage(tmpva) + NBPDR;
9699 * If the current offset aligns with a 2MB page frame
9700 * and there is at least 2MB left within the range, then
9701 * we need not break down this page into 4KB pages.
9703 if ((tmpva & PDRMASK) == 0 &&
9704 tmpva + PDRMASK < base + size) {
9708 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9711 pte = pmap_pde_to_pte(pde, tmpva);
9713 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9714 ("%s: addr %#lx is not mapped", __func__, tmpva));
9722 * Ok, all the pages exist, so run through them updating their
9723 * properties if required.
9726 pa_start = pa_end = 0;
9727 for (tmpva = base; tmpva < base + size; ) {
9728 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9729 if (*pdpe & PG_PS) {
9730 if ((*pdpe & pde_mask) != pde_bits) {
9731 pmap_pte_props(pdpe, pde_bits, pde_mask);
9734 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9735 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9736 if (pa_start == pa_end) {
9737 /* Start physical address run. */
9738 pa_start = *pdpe & PG_PS_FRAME;
9739 pa_end = pa_start + NBPDP;
9740 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9743 /* Run ended, update direct map. */
9744 error = pmap_change_props_locked(
9745 PHYS_TO_DMAP(pa_start),
9746 pa_end - pa_start, prot, mode,
9750 /* Start physical address run. */
9751 pa_start = *pdpe & PG_PS_FRAME;
9752 pa_end = pa_start + NBPDP;
9755 tmpva = trunc_1gpage(tmpva) + NBPDP;
9758 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9760 if ((*pde & pde_mask) != pde_bits) {
9761 pmap_pte_props(pde, pde_bits, pde_mask);
9764 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9765 (*pde & PG_PS_FRAME) < dmaplimit) {
9766 if (pa_start == pa_end) {
9767 /* Start physical address run. */
9768 pa_start = *pde & PG_PS_FRAME;
9769 pa_end = pa_start + NBPDR;
9770 } else if (pa_end == (*pde & PG_PS_FRAME))
9773 /* Run ended, update direct map. */
9774 error = pmap_change_props_locked(
9775 PHYS_TO_DMAP(pa_start),
9776 pa_end - pa_start, prot, mode,
9780 /* Start physical address run. */
9781 pa_start = *pde & PG_PS_FRAME;
9782 pa_end = pa_start + NBPDR;
9785 tmpva = trunc_2mpage(tmpva) + NBPDR;
9787 pte = pmap_pde_to_pte(pde, tmpva);
9788 if ((*pte & pte_mask) != pte_bits) {
9789 pmap_pte_props(pte, pte_bits, pte_mask);
9792 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9793 (*pte & PG_FRAME) < dmaplimit) {
9794 if (pa_start == pa_end) {
9795 /* Start physical address run. */
9796 pa_start = *pte & PG_FRAME;
9797 pa_end = pa_start + PAGE_SIZE;
9798 } else if (pa_end == (*pte & PG_FRAME))
9799 pa_end += PAGE_SIZE;
9801 /* Run ended, update direct map. */
9802 error = pmap_change_props_locked(
9803 PHYS_TO_DMAP(pa_start),
9804 pa_end - pa_start, prot, mode,
9808 /* Start physical address run. */
9809 pa_start = *pte & PG_FRAME;
9810 pa_end = pa_start + PAGE_SIZE;
9816 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9817 pa_end1 = MIN(pa_end, dmaplimit);
9818 if (pa_start != pa_end1)
9819 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9820 pa_end1 - pa_start, prot, mode, flags);
9824 * Flush CPU caches if required to make sure any data isn't cached that
9825 * shouldn't be, etc.
9828 pmap_invalidate_range(kernel_pmap, base, tmpva);
9829 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9830 pmap_invalidate_cache_range(base, tmpva);
9836 * Demotes any mapping within the direct map region that covers more than the
9837 * specified range of physical addresses. This range's size must be a power
9838 * of two and its starting address must be a multiple of its size. Since the
9839 * demotion does not change any attributes of the mapping, a TLB invalidation
9840 * is not mandatory. The caller may, however, request a TLB invalidation.
9843 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
9852 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9853 KASSERT((base & (len - 1)) == 0,
9854 ("pmap_demote_DMAP: base is not a multiple of len"));
9855 if (len < NBPDP && base < dmaplimit) {
9856 va = PHYS_TO_DMAP(base);
9858 PMAP_LOCK(kernel_pmap);
9859 pdpe = pmap_pdpe(kernel_pmap, va);
9860 if ((*pdpe & X86_PG_V) == 0)
9861 panic("pmap_demote_DMAP: invalid PDPE");
9862 if ((*pdpe & PG_PS) != 0) {
9863 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9864 panic("pmap_demote_DMAP: PDPE failed");
9868 pde = pmap_pdpe_to_pde(pdpe, va);
9869 if ((*pde & X86_PG_V) == 0)
9870 panic("pmap_demote_DMAP: invalid PDE");
9871 if ((*pde & PG_PS) != 0) {
9872 if (!pmap_demote_pde(kernel_pmap, pde, va))
9873 panic("pmap_demote_DMAP: PDE failed");
9877 if (changed && invalidate)
9878 pmap_invalidate_page(kernel_pmap, va);
9879 PMAP_UNLOCK(kernel_pmap);
9884 * Perform the pmap work for mincore(2). If the page is not both referenced and
9885 * modified by this pmap, returns its physical address so that the caller can
9886 * find other mappings.
9889 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
9893 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
9897 PG_A = pmap_accessed_bit(pmap);
9898 PG_M = pmap_modified_bit(pmap);
9899 PG_V = pmap_valid_bit(pmap);
9900 PG_RW = pmap_rw_bit(pmap);
9906 pdpe = pmap_pdpe(pmap, addr);
9909 if ((*pdpe & PG_V) != 0) {
9910 if ((*pdpe & PG_PS) != 0) {
9912 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
9914 val = MINCORE_PSIND(2);
9916 pdep = pmap_pde(pmap, addr);
9917 if (pdep != NULL && (*pdep & PG_V) != 0) {
9918 if ((*pdep & PG_PS) != 0) {
9920 /* Compute the physical address of the 4KB page. */
9921 pa = ((pte & PG_PS_FRAME) | (addr &
9922 PDRMASK)) & PG_FRAME;
9923 val = MINCORE_PSIND(1);
9925 pte = *pmap_pde_to_pte(pdep, addr);
9926 pa = pte & PG_FRAME;
9932 if ((pte & PG_V) != 0) {
9933 val |= MINCORE_INCORE;
9934 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9935 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
9936 if ((pte & PG_A) != 0)
9937 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
9939 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
9940 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
9941 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
9950 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
9952 uint32_t gen, new_gen, pcid_next;
9954 CRITICAL_ASSERT(curthread);
9955 gen = PCPU_GET(pcid_gen);
9956 if (pcidp->pm_pcid == PMAP_PCID_KERN)
9957 return (pti ? 0 : CR3_PCID_SAVE);
9958 if (pcidp->pm_gen == gen)
9959 return (CR3_PCID_SAVE);
9960 pcid_next = PCPU_GET(pcid_next);
9961 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
9962 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
9963 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
9964 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
9965 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
9969 PCPU_SET(pcid_gen, new_gen);
9970 pcid_next = PMAP_PCID_KERN + 1;
9974 pcidp->pm_pcid = pcid_next;
9975 pcidp->pm_gen = new_gen;
9976 PCPU_SET(pcid_next, pcid_next + 1);
9981 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
9985 cached = pmap_pcid_alloc(pmap, pcidp);
9986 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
9987 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
9988 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
9989 ("non-kernel pmap pmap %p cpu %d pcid %#x",
9990 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
9995 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
9998 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
9999 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10003 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10006 struct pmap_pcid *pcidp, *old_pcidp;
10007 uint64_t cached, cr3, kcr3, ucr3;
10009 KASSERT((read_rflags() & PSL_I) == 0,
10010 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10012 /* See the comment in pmap_invalidate_page_pcid(). */
10013 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10014 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10015 old_pmap = PCPU_GET(curpmap);
10016 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10017 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10018 old_pcidp->pm_gen = 0;
10021 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10022 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10024 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10025 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10026 PCPU_SET(curpmap, pmap);
10027 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10028 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10030 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10031 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10033 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10034 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10036 counter_u64_add(pcid_save_cnt, 1);
10038 pmap_activate_sw_pti_post(td, pmap);
10042 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10045 struct pmap_pcid *pcidp;
10046 uint64_t cached, cr3;
10048 KASSERT((read_rflags() & PSL_I) == 0,
10049 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10051 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10052 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10054 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10055 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10056 PCPU_SET(curpmap, pmap);
10058 counter_u64_add(pcid_save_cnt, 1);
10062 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10063 u_int cpuid __unused)
10066 load_cr3(pmap->pm_cr3);
10067 PCPU_SET(curpmap, pmap);
10071 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10072 u_int cpuid __unused)
10075 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10076 PCPU_SET(kcr3, pmap->pm_cr3);
10077 PCPU_SET(ucr3, pmap->pm_ucr3);
10078 pmap_activate_sw_pti_post(td, pmap);
10081 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10085 if (pmap_pcid_enabled && pti)
10086 return (pmap_activate_sw_pcid_pti);
10087 else if (pmap_pcid_enabled && !pti)
10088 return (pmap_activate_sw_pcid_nopti);
10089 else if (!pmap_pcid_enabled && pti)
10090 return (pmap_activate_sw_nopcid_pti);
10091 else /* if (!pmap_pcid_enabled && !pti) */
10092 return (pmap_activate_sw_nopcid_nopti);
10096 pmap_activate_sw(struct thread *td)
10098 pmap_t oldpmap, pmap;
10101 oldpmap = PCPU_GET(curpmap);
10102 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10103 if (oldpmap == pmap) {
10104 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10108 cpuid = PCPU_GET(cpuid);
10110 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10112 CPU_SET(cpuid, &pmap->pm_active);
10114 pmap_activate_sw_mode(td, pmap, cpuid);
10116 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10118 CPU_CLR(cpuid, &oldpmap->pm_active);
10123 pmap_activate(struct thread *td)
10126 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10127 * invalidate_all IPI, which checks for curpmap ==
10128 * smp_tlb_pmap. The below sequence of operations has a
10129 * window where %CR3 is loaded with the new pmap's PML4
10130 * address, but the curpmap value has not yet been updated.
10131 * This causes the invltlb IPI handler, which is called
10132 * between the updates, to execute as a NOP, which leaves
10133 * stale TLB entries.
10135 * Note that the most common use of pmap_activate_sw(), from
10136 * a context switch, is immune to this race, because
10137 * interrupts are disabled (while the thread lock is owned),
10138 * so the IPI is delayed until after curpmap is updated. Protect
10139 * other callers in a similar way, by disabling interrupts
10140 * around the %cr3 register reload and curpmap assignment.
10143 pmap_activate_sw(td);
10148 pmap_activate_boot(pmap_t pmap)
10154 * kernel_pmap must be never deactivated, and we ensure that
10155 * by never activating it at all.
10157 MPASS(pmap != kernel_pmap);
10159 cpuid = PCPU_GET(cpuid);
10161 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10163 CPU_SET(cpuid, &pmap->pm_active);
10165 PCPU_SET(curpmap, pmap);
10167 kcr3 = pmap->pm_cr3;
10168 if (pmap_pcid_enabled)
10169 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10171 kcr3 = PMAP_NO_CR3;
10173 PCPU_SET(kcr3, kcr3);
10174 PCPU_SET(ucr3, PMAP_NO_CR3);
10178 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10183 * Increase the starting virtual address of the given mapping if a
10184 * different alignment might result in more superpage mappings.
10187 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10188 vm_offset_t *addr, vm_size_t size)
10190 vm_offset_t superpage_offset;
10194 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10195 offset += ptoa(object->pg_color);
10196 superpage_offset = offset & PDRMASK;
10197 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10198 (*addr & PDRMASK) == superpage_offset)
10200 if ((*addr & PDRMASK) < superpage_offset)
10201 *addr = (*addr & ~PDRMASK) + superpage_offset;
10203 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10207 static unsigned long num_dirty_emulations;
10208 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10209 &num_dirty_emulations, 0, NULL);
10211 static unsigned long num_accessed_emulations;
10212 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10213 &num_accessed_emulations, 0, NULL);
10215 static unsigned long num_superpage_accessed_emulations;
10216 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10217 &num_superpage_accessed_emulations, 0, NULL);
10219 static unsigned long ad_emulation_superpage_promotions;
10220 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10221 &ad_emulation_superpage_promotions, 0, NULL);
10222 #endif /* INVARIANTS */
10225 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10228 struct rwlock *lock;
10229 #if VM_NRESERVLEVEL > 0
10233 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10235 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10236 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10238 if (!pmap_emulate_ad_bits(pmap))
10241 PG_A = pmap_accessed_bit(pmap);
10242 PG_M = pmap_modified_bit(pmap);
10243 PG_V = pmap_valid_bit(pmap);
10244 PG_RW = pmap_rw_bit(pmap);
10250 pde = pmap_pde(pmap, va);
10251 if (pde == NULL || (*pde & PG_V) == 0)
10254 if ((*pde & PG_PS) != 0) {
10255 if (ftype == VM_PROT_READ) {
10257 atomic_add_long(&num_superpage_accessed_emulations, 1);
10265 pte = pmap_pde_to_pte(pde, va);
10266 if ((*pte & PG_V) == 0)
10269 if (ftype == VM_PROT_WRITE) {
10270 if ((*pte & PG_RW) == 0)
10273 * Set the modified and accessed bits simultaneously.
10275 * Intel EPT PTEs that do software emulation of A/D bits map
10276 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10277 * An EPT misconfiguration is triggered if the PTE is writable
10278 * but not readable (WR=10). This is avoided by setting PG_A
10279 * and PG_M simultaneously.
10281 *pte |= PG_M | PG_A;
10286 #if VM_NRESERVLEVEL > 0
10287 /* try to promote the mapping */
10288 if (va < VM_MAXUSER_ADDRESS)
10289 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10293 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10295 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10296 pmap_ps_enabled(pmap) &&
10297 (m->flags & PG_FICTITIOUS) == 0 &&
10298 vm_reserv_level_iffullpop(m) == 0) {
10299 pmap_promote_pde(pmap, pde, va, mpte, &lock);
10301 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10307 if (ftype == VM_PROT_WRITE)
10308 atomic_add_long(&num_dirty_emulations, 1);
10310 atomic_add_long(&num_accessed_emulations, 1);
10312 rv = 0; /* success */
10321 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10323 pml4_entry_t *pml4;
10326 pt_entry_t *pte, PG_V;
10330 PG_V = pmap_valid_bit(pmap);
10333 pml4 = pmap_pml4e(pmap, va);
10336 ptr[idx++] = *pml4;
10337 if ((*pml4 & PG_V) == 0)
10340 pdp = pmap_pml4e_to_pdpe(pml4, va);
10342 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10345 pde = pmap_pdpe_to_pde(pdp, va);
10347 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10350 pte = pmap_pde_to_pte(pde, va);
10359 * Get the kernel virtual address of a set of physical pages. If there are
10360 * physical addresses not covered by the DMAP perform a transient mapping
10361 * that will be removed when calling pmap_unmap_io_transient.
10363 * \param page The pages the caller wishes to obtain the virtual
10364 * address on the kernel memory map.
10365 * \param vaddr On return contains the kernel virtual memory address
10366 * of the pages passed in the page parameter.
10367 * \param count Number of pages passed in.
10368 * \param can_fault true if the thread using the mapped pages can take
10369 * page faults, false otherwise.
10371 * \returns true if the caller must call pmap_unmap_io_transient when
10372 * finished or false otherwise.
10376 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10380 bool needs_mapping;
10382 int cache_bits, error __unused, i;
10385 * Allocate any KVA space that we need, this is done in a separate
10386 * loop to prevent calling vmem_alloc while pinned.
10388 needs_mapping = false;
10389 for (i = 0; i < count; i++) {
10390 paddr = VM_PAGE_TO_PHYS(page[i]);
10391 if (__predict_false(paddr >= dmaplimit)) {
10392 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10393 M_BESTFIT | M_WAITOK, &vaddr[i]);
10394 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10395 needs_mapping = true;
10397 vaddr[i] = PHYS_TO_DMAP(paddr);
10401 /* Exit early if everything is covered by the DMAP */
10402 if (!needs_mapping)
10406 * NB: The sequence of updating a page table followed by accesses
10407 * to the corresponding pages used in the !DMAP case is subject to
10408 * the situation described in the "AMD64 Architecture Programmer's
10409 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10410 * Coherency Considerations". Therefore, issuing the INVLPG right
10411 * after modifying the PTE bits is crucial.
10415 for (i = 0; i < count; i++) {
10416 paddr = VM_PAGE_TO_PHYS(page[i]);
10417 if (paddr >= dmaplimit) {
10420 * Slow path, since we can get page faults
10421 * while mappings are active don't pin the
10422 * thread to the CPU and instead add a global
10423 * mapping visible to all CPUs.
10425 pmap_qenter(vaddr[i], &page[i], 1);
10427 pte = vtopte(vaddr[i]);
10428 cache_bits = pmap_cache_bits(kernel_pmap,
10429 page[i]->md.pat_mode, false);
10430 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10432 pmap_invlpg(kernel_pmap, vaddr[i]);
10437 return (needs_mapping);
10441 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10449 for (i = 0; i < count; i++) {
10450 paddr = VM_PAGE_TO_PHYS(page[i]);
10451 if (paddr >= dmaplimit) {
10453 pmap_qremove(vaddr[i], 1);
10454 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10460 pmap_quick_enter_page(vm_page_t m)
10464 paddr = VM_PAGE_TO_PHYS(m);
10465 if (paddr < dmaplimit)
10466 return (PHYS_TO_DMAP(paddr));
10467 mtx_lock_spin(&qframe_mtx);
10468 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10471 * Since qframe is exclusively mapped by us, and we do not set
10472 * PG_G, we can use INVLPG here.
10476 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10477 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
10482 pmap_quick_remove_page(vm_offset_t addr)
10485 if (addr != qframe)
10487 pte_store(vtopte(qframe), 0);
10488 mtx_unlock_spin(&qframe_mtx);
10492 * Pdp pages from the large map are managed differently from either
10493 * kernel or user page table pages. They are permanently allocated at
10494 * initialization time, and their reference count is permanently set to
10495 * zero. The pml4 entries pointing to those pages are copied into
10496 * each allocated pmap.
10498 * In contrast, pd and pt pages are managed like user page table
10499 * pages. They are dynamically allocated, and their reference count
10500 * represents the number of valid entries within the page.
10503 pmap_large_map_getptp_unlocked(void)
10505 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10509 pmap_large_map_getptp(void)
10513 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10514 m = pmap_large_map_getptp_unlocked();
10516 PMAP_UNLOCK(kernel_pmap);
10518 PMAP_LOCK(kernel_pmap);
10519 /* Callers retry. */
10524 static pdp_entry_t *
10525 pmap_large_map_pdpe(vm_offset_t va)
10527 vm_pindex_t pml4_idx;
10530 pml4_idx = pmap_pml4e_index(va);
10531 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10532 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10534 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10535 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10536 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10537 "LMSPML4I %#jx lm_ents %d",
10538 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10539 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10540 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10543 static pd_entry_t *
10544 pmap_large_map_pde(vm_offset_t va)
10551 pdpe = pmap_large_map_pdpe(va);
10553 m = pmap_large_map_getptp();
10556 mphys = VM_PAGE_TO_PHYS(m);
10557 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10559 MPASS((*pdpe & X86_PG_PS) == 0);
10560 mphys = *pdpe & PG_FRAME;
10562 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10565 static pt_entry_t *
10566 pmap_large_map_pte(vm_offset_t va)
10573 pde = pmap_large_map_pde(va);
10575 m = pmap_large_map_getptp();
10578 mphys = VM_PAGE_TO_PHYS(m);
10579 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10580 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10582 MPASS((*pde & X86_PG_PS) == 0);
10583 mphys = *pde & PG_FRAME;
10585 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10589 pmap_large_map_kextract(vm_offset_t va)
10591 pdp_entry_t *pdpe, pdp;
10592 pd_entry_t *pde, pd;
10593 pt_entry_t *pte, pt;
10595 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10596 ("not largemap range %#lx", (u_long)va));
10597 pdpe = pmap_large_map_pdpe(va);
10599 KASSERT((pdp & X86_PG_V) != 0,
10600 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10601 (u_long)pdpe, pdp));
10602 if ((pdp & X86_PG_PS) != 0) {
10603 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10604 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10605 (u_long)pdpe, pdp));
10606 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10608 pde = pmap_pdpe_to_pde(pdpe, va);
10610 KASSERT((pd & X86_PG_V) != 0,
10611 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10612 if ((pd & X86_PG_PS) != 0)
10613 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10614 pte = pmap_pde_to_pte(pde, va);
10616 KASSERT((pt & X86_PG_V) != 0,
10617 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10618 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10622 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10623 vmem_addr_t *vmem_res)
10627 * Large mappings are all but static. Consequently, there
10628 * is no point in waiting for an earlier allocation to be
10631 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10632 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10636 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10637 vm_memattr_t mattr)
10642 vm_offset_t va, inc;
10643 vmem_addr_t vmem_res;
10647 if (len == 0 || spa + len < spa)
10650 /* See if DMAP can serve. */
10651 if (spa + len <= dmaplimit) {
10652 va = PHYS_TO_DMAP(spa);
10653 *addr = (void *)va;
10654 return (pmap_change_attr(va, len, mattr));
10658 * No, allocate KVA. Fit the address with best possible
10659 * alignment for superpages. Fall back to worse align if
10663 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10664 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10665 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10667 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10669 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10672 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10677 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10678 * in the pagetable to minimize flushing. No need to
10679 * invalidate TLB, since we only update invalid entries.
10681 PMAP_LOCK(kernel_pmap);
10682 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10684 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10685 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10686 pdpe = pmap_large_map_pdpe(va);
10688 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10689 X86_PG_V | X86_PG_A | pg_nx |
10690 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10692 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10693 (va & PDRMASK) == 0) {
10694 pde = pmap_large_map_pde(va);
10696 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10697 X86_PG_V | X86_PG_A | pg_nx |
10698 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10699 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10703 pte = pmap_large_map_pte(va);
10705 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10706 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10708 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10713 PMAP_UNLOCK(kernel_pmap);
10716 *addr = (void *)vmem_res;
10721 pmap_large_unmap(void *svaa, vm_size_t len)
10723 vm_offset_t sva, va;
10725 pdp_entry_t *pdpe, pdp;
10726 pd_entry_t *pde, pd;
10729 struct spglist spgf;
10731 sva = (vm_offset_t)svaa;
10732 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10733 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10737 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10738 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10739 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10740 PMAP_LOCK(kernel_pmap);
10741 for (va = sva; va < sva + len; va += inc) {
10742 pdpe = pmap_large_map_pdpe(va);
10744 KASSERT((pdp & X86_PG_V) != 0,
10745 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10746 (u_long)pdpe, pdp));
10747 if ((pdp & X86_PG_PS) != 0) {
10748 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10749 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10750 (u_long)pdpe, pdp));
10751 KASSERT((va & PDPMASK) == 0,
10752 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10753 (u_long)pdpe, pdp));
10754 KASSERT(va + NBPDP <= sva + len,
10755 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10756 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10757 (u_long)pdpe, pdp, len));
10762 pde = pmap_pdpe_to_pde(pdpe, va);
10764 KASSERT((pd & X86_PG_V) != 0,
10765 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10767 if ((pd & X86_PG_PS) != 0) {
10768 KASSERT((va & PDRMASK) == 0,
10769 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10771 KASSERT(va + NBPDR <= sva + len,
10772 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10773 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10777 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10779 if (m->ref_count == 0) {
10781 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10785 pte = pmap_pde_to_pte(pde, va);
10786 KASSERT((*pte & X86_PG_V) != 0,
10787 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10788 (u_long)pte, *pte));
10791 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10793 if (m->ref_count == 0) {
10795 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10796 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10798 if (m->ref_count == 0) {
10800 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10804 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10805 PMAP_UNLOCK(kernel_pmap);
10806 vm_page_free_pages_toq(&spgf, false);
10807 vmem_free(large_vmem, sva, len);
10811 pmap_large_map_wb_fence_mfence(void)
10818 pmap_large_map_wb_fence_atomic(void)
10821 atomic_thread_fence_seq_cst();
10825 pmap_large_map_wb_fence_nop(void)
10829 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10832 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10833 return (pmap_large_map_wb_fence_mfence);
10834 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10835 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10836 return (pmap_large_map_wb_fence_atomic);
10838 /* clflush is strongly enough ordered */
10839 return (pmap_large_map_wb_fence_nop);
10843 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10846 for (; len > 0; len -= cpu_clflush_line_size,
10847 va += cpu_clflush_line_size)
10852 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10855 for (; len > 0; len -= cpu_clflush_line_size,
10856 va += cpu_clflush_line_size)
10861 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10864 for (; len > 0; len -= cpu_clflush_line_size,
10865 va += cpu_clflush_line_size)
10870 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10874 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
10877 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
10878 return (pmap_large_map_flush_range_clwb);
10879 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
10880 return (pmap_large_map_flush_range_clflushopt);
10881 else if ((cpu_feature & CPUID_CLFSH) != 0)
10882 return (pmap_large_map_flush_range_clflush);
10884 return (pmap_large_map_flush_range_nop);
10888 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
10890 volatile u_long *pe;
10896 for (va = sva; va < eva; va += inc) {
10898 if ((amd_feature & AMDID_PAGE1GB) != 0) {
10899 pe = (volatile u_long *)pmap_large_map_pdpe(va);
10901 if ((p & X86_PG_PS) != 0)
10905 pe = (volatile u_long *)pmap_large_map_pde(va);
10907 if ((p & X86_PG_PS) != 0)
10911 pe = (volatile u_long *)pmap_large_map_pte(va);
10915 seen_other = false;
10917 if ((p & X86_PG_AVAIL1) != 0) {
10919 * Spin-wait for the end of a parallel
10926 * If we saw other write-back
10927 * occuring, we cannot rely on PG_M to
10928 * indicate state of the cache. The
10929 * PG_M bit is cleared before the
10930 * flush to avoid ignoring new writes,
10931 * and writes which are relevant for
10932 * us might happen after.
10938 if ((p & X86_PG_M) != 0 || seen_other) {
10939 if (!atomic_fcmpset_long(pe, &p,
10940 (p & ~X86_PG_M) | X86_PG_AVAIL1))
10942 * If we saw PG_M without
10943 * PG_AVAIL1, and then on the
10944 * next attempt we do not
10945 * observe either PG_M or
10946 * PG_AVAIL1, the other
10947 * write-back started after us
10948 * and finished before us. We
10949 * can rely on it doing our
10953 pmap_large_map_flush_range(va, inc);
10954 atomic_clear_long(pe, X86_PG_AVAIL1);
10963 * Write-back cache lines for the given address range.
10965 * Must be called only on the range or sub-range returned from
10966 * pmap_large_map(). Must not be called on the coalesced ranges.
10968 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
10969 * instructions support.
10972 pmap_large_map_wb(void *svap, vm_size_t len)
10974 vm_offset_t eva, sva;
10976 sva = (vm_offset_t)svap;
10978 pmap_large_map_wb_fence();
10979 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
10980 pmap_large_map_flush_range(sva, len);
10982 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
10983 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
10984 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
10985 pmap_large_map_wb_large(sva, eva);
10987 pmap_large_map_wb_fence();
10991 pmap_pti_alloc_page(void)
10995 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
10996 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11001 pmap_pti_free_page(vm_page_t m)
11003 if (!vm_page_unwire_noq(m))
11005 vm_page_xbusy_claim(m);
11006 vm_page_free_zero(m);
11011 pmap_pti_init(void)
11020 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11021 VM_OBJECT_WLOCK(pti_obj);
11022 pml4_pg = pmap_pti_alloc_page();
11023 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11024 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11025 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11026 pdpe = pmap_pti_pdpe(va);
11027 pmap_pti_wire_pte(pdpe);
11029 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11030 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11031 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11032 sizeof(struct gate_descriptor) * NIDT, false);
11034 /* Doublefault stack IST 1 */
11035 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11036 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11037 /* NMI stack IST 2 */
11038 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11039 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11040 /* MC# stack IST 3 */
11041 va = __pcpu[i].pc_common_tss.tss_ist3 +
11042 sizeof(struct nmi_pcpu);
11043 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11044 /* DB# stack IST 4 */
11045 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11046 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11048 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11050 pti_finalized = true;
11051 VM_OBJECT_WUNLOCK(pti_obj);
11055 pmap_cpu_init(void *arg __unused)
11057 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11060 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11062 static pdp_entry_t *
11063 pmap_pti_pdpe(vm_offset_t va)
11065 pml4_entry_t *pml4e;
11068 vm_pindex_t pml4_idx;
11071 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11073 pml4_idx = pmap_pml4e_index(va);
11074 pml4e = &pti_pml4[pml4_idx];
11078 panic("pml4 alloc after finalization\n");
11079 m = pmap_pti_alloc_page();
11081 pmap_pti_free_page(m);
11082 mphys = *pml4e & ~PAGE_MASK;
11084 mphys = VM_PAGE_TO_PHYS(m);
11085 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11088 mphys = *pml4e & ~PAGE_MASK;
11090 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11095 pmap_pti_wire_pte(void *pte)
11099 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11100 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11105 pmap_pti_unwire_pde(void *pde, bool only_ref)
11109 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11110 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11111 MPASS(only_ref || m->ref_count > 1);
11112 pmap_pti_free_page(m);
11116 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11121 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11122 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11123 if (pmap_pti_free_page(m)) {
11124 pde = pmap_pti_pde(va);
11125 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11127 pmap_pti_unwire_pde(pde, false);
11131 static pd_entry_t *
11132 pmap_pti_pde(vm_offset_t va)
11137 vm_pindex_t pd_idx;
11140 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11142 pdpe = pmap_pti_pdpe(va);
11144 m = pmap_pti_alloc_page();
11146 pmap_pti_free_page(m);
11147 MPASS((*pdpe & X86_PG_PS) == 0);
11148 mphys = *pdpe & ~PAGE_MASK;
11150 mphys = VM_PAGE_TO_PHYS(m);
11151 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11154 MPASS((*pdpe & X86_PG_PS) == 0);
11155 mphys = *pdpe & ~PAGE_MASK;
11158 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11159 pd_idx = pmap_pde_index(va);
11164 static pt_entry_t *
11165 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11172 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11174 pde = pmap_pti_pde(va);
11175 if (unwire_pde != NULL) {
11176 *unwire_pde = true;
11177 pmap_pti_wire_pte(pde);
11180 m = pmap_pti_alloc_page();
11182 pmap_pti_free_page(m);
11183 MPASS((*pde & X86_PG_PS) == 0);
11184 mphys = *pde & ~(PAGE_MASK | pg_nx);
11186 mphys = VM_PAGE_TO_PHYS(m);
11187 *pde = mphys | X86_PG_RW | X86_PG_V;
11188 if (unwire_pde != NULL)
11189 *unwire_pde = false;
11192 MPASS((*pde & X86_PG_PS) == 0);
11193 mphys = *pde & ~(PAGE_MASK | pg_nx);
11196 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11197 pte += pmap_pte_index(va);
11203 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11207 pt_entry_t *pte, ptev;
11210 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11212 sva = trunc_page(sva);
11213 MPASS(sva > VM_MAXUSER_ADDRESS);
11214 eva = round_page(eva);
11216 for (; sva < eva; sva += PAGE_SIZE) {
11217 pte = pmap_pti_pte(sva, &unwire_pde);
11218 pa = pmap_kextract(sva);
11219 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11220 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11221 VM_MEMATTR_DEFAULT, FALSE);
11223 pte_store(pte, ptev);
11224 pmap_pti_wire_pte(pte);
11226 KASSERT(!pti_finalized,
11227 ("pti overlap after fin %#lx %#lx %#lx",
11229 KASSERT(*pte == ptev,
11230 ("pti non-identical pte after fin %#lx %#lx %#lx",
11234 pde = pmap_pti_pde(sva);
11235 pmap_pti_unwire_pde(pde, true);
11241 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11246 VM_OBJECT_WLOCK(pti_obj);
11247 pmap_pti_add_kva_locked(sva, eva, exec);
11248 VM_OBJECT_WUNLOCK(pti_obj);
11252 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11259 sva = rounddown2(sva, PAGE_SIZE);
11260 MPASS(sva > VM_MAXUSER_ADDRESS);
11261 eva = roundup2(eva, PAGE_SIZE);
11263 VM_OBJECT_WLOCK(pti_obj);
11264 for (va = sva; va < eva; va += PAGE_SIZE) {
11265 pte = pmap_pti_pte(va, NULL);
11266 KASSERT((*pte & X86_PG_V) != 0,
11267 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11268 (u_long)pte, *pte));
11270 pmap_pti_unwire_pte(pte, va);
11272 pmap_invalidate_range(kernel_pmap, sva, eva);
11273 VM_OBJECT_WUNLOCK(pti_obj);
11277 pkru_dup_range(void *ctx __unused, void *data)
11279 struct pmap_pkru_range *node, *new_node;
11281 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11282 if (new_node == NULL)
11285 memcpy(new_node, node, sizeof(*node));
11290 pkru_free_range(void *ctx __unused, void *node)
11293 uma_zfree(pmap_pkru_ranges_zone, node);
11297 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11300 struct pmap_pkru_range *ppr;
11303 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11304 MPASS(pmap->pm_type == PT_X86);
11305 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11306 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11307 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11309 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11312 ppr->pkru_keyidx = keyidx;
11313 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11314 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11316 uma_zfree(pmap_pkru_ranges_zone, ppr);
11321 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11324 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11325 MPASS(pmap->pm_type == PT_X86);
11326 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11327 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11331 pmap_pkru_deassign_all(pmap_t pmap)
11334 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11335 if (pmap->pm_type == PT_X86 &&
11336 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11337 rangeset_remove_all(&pmap->pm_pkru);
11341 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11343 struct pmap_pkru_range *ppr, *prev_ppr;
11346 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11347 if (pmap->pm_type != PT_X86 ||
11348 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11349 sva >= VM_MAXUSER_ADDRESS)
11351 MPASS(eva <= VM_MAXUSER_ADDRESS);
11352 for (va = sva; va < eva; prev_ppr = ppr) {
11353 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11356 else if ((ppr == NULL) ^ (prev_ppr == NULL))
11362 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
11364 va = ppr->pkru_rs_el.re_end;
11370 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11372 struct pmap_pkru_range *ppr;
11374 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11375 if (pmap->pm_type != PT_X86 ||
11376 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11377 va >= VM_MAXUSER_ADDRESS)
11379 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11381 return (X86_PG_PKU(ppr->pkru_keyidx));
11386 pred_pkru_on_remove(void *ctx __unused, void *r)
11388 struct pmap_pkru_range *ppr;
11391 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11395 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11398 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11399 if (pmap->pm_type == PT_X86 &&
11400 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11401 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11402 pred_pkru_on_remove);
11407 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11410 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11411 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11412 MPASS(dst_pmap->pm_type == PT_X86);
11413 MPASS(src_pmap->pm_type == PT_X86);
11414 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11415 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11417 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11421 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11424 pml4_entry_t *pml4e;
11426 pd_entry_t newpde, ptpaddr, *pde;
11427 pt_entry_t newpte, *ptep, pte;
11428 vm_offset_t va, va_next;
11431 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11432 MPASS(pmap->pm_type == PT_X86);
11433 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11435 for (changed = false, va = sva; va < eva; va = va_next) {
11436 pml4e = pmap_pml4e(pmap, va);
11437 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11438 va_next = (va + NBPML4) & ~PML4MASK;
11444 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11445 if ((*pdpe & X86_PG_V) == 0) {
11446 va_next = (va + NBPDP) & ~PDPMASK;
11452 va_next = (va + NBPDR) & ~PDRMASK;
11456 pde = pmap_pdpe_to_pde(pdpe, va);
11461 MPASS((ptpaddr & X86_PG_V) != 0);
11462 if ((ptpaddr & PG_PS) != 0) {
11463 if (va + NBPDR == va_next && eva >= va_next) {
11464 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11465 X86_PG_PKU(keyidx);
11466 if (newpde != ptpaddr) {
11471 } else if (!pmap_demote_pde(pmap, pde, va)) {
11479 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11480 ptep++, va += PAGE_SIZE) {
11482 if ((pte & X86_PG_V) == 0)
11484 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11485 if (newpte != pte) {
11492 pmap_invalidate_range(pmap, sva, eva);
11496 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11497 u_int keyidx, int flags)
11500 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11501 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11503 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11505 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11511 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11516 sva = trunc_page(sva);
11517 eva = round_page(eva);
11518 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11523 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11525 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11527 if (error != ENOMEM)
11535 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11539 sva = trunc_page(sva);
11540 eva = round_page(eva);
11541 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11546 error = pmap_pkru_deassign(pmap, sva, eva);
11548 pmap_pkru_update_range(pmap, sva, eva, 0);
11550 if (error != ENOMEM)
11557 #if defined(KASAN) || defined(KMSAN)
11560 * Reserve enough memory to:
11561 * 1) allocate PDP pages for the shadow map(s),
11562 * 2) shadow one page of memory, so one PD page, one PT page, and one shadow
11563 * page per shadow map.
11566 #define SAN_EARLY_PAGES (NKASANPML4E + 3)
11568 #define SAN_EARLY_PAGES (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * 3)
11571 static uint64_t __nosanitizeaddress __nosanitizememory
11572 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11574 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11575 static size_t offset = 0;
11578 if (offset == sizeof(data)) {
11579 panic("%s: ran out of memory for the bootstrap shadow map",
11583 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11584 offset += PAGE_SIZE;
11589 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11590 * is currently only used to shadow the temporary boot stack set up by locore.
11592 static void __nosanitizeaddress __nosanitizememory
11593 pmap_san_enter_early(vm_offset_t va)
11595 static bool first = true;
11596 pml4_entry_t *pml4e;
11600 uint64_t cr3, pa, base;
11603 base = amd64_loadaddr();
11608 * If this the first call, we need to allocate new PML4Es for
11609 * the bootstrap shadow map(s). We don't know how the PML4 page
11610 * was initialized by the boot loader, so we can't simply test
11611 * whether the shadow map's PML4Es are zero.
11615 for (i = 0; i < NKASANPML4E; i++) {
11616 pa = pmap_san_enter_early_alloc_4k(base);
11618 pml4e = (pml4_entry_t *)cr3 +
11619 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11620 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11623 for (i = 0; i < NKMSANORIGPML4E; i++) {
11624 pa = pmap_san_enter_early_alloc_4k(base);
11626 pml4e = (pml4_entry_t *)cr3 +
11627 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11629 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11631 for (i = 0; i < NKMSANSHADPML4E; i++) {
11632 pa = pmap_san_enter_early_alloc_4k(base);
11634 pml4e = (pml4_entry_t *)cr3 +
11635 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11637 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11641 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11642 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11644 pa = pmap_san_enter_early_alloc_4k(base);
11645 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11647 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11649 pa = pmap_san_enter_early_alloc_4k(base);
11650 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11652 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11654 panic("%s: PTE for %#lx is already initialized", __func__, va);
11655 pa = pmap_san_enter_early_alloc_4k(base);
11656 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11660 pmap_san_enter_alloc_4k(void)
11664 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11667 panic("%s: no memory to grow shadow map", __func__);
11672 pmap_san_enter_alloc_2m(void)
11674 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11675 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11679 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11680 * pages when possible.
11682 void __nosanitizeaddress __nosanitizememory
11683 pmap_san_enter(vm_offset_t va)
11690 if (kernphys == 0) {
11692 * We're creating a temporary shadow map for the boot stack.
11694 pmap_san_enter_early(va);
11698 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11700 pdpe = pmap_pdpe(kernel_pmap, va);
11701 if ((*pdpe & X86_PG_V) == 0) {
11702 m = pmap_san_enter_alloc_4k();
11703 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11706 pde = pmap_pdpe_to_pde(pdpe, va);
11707 if ((*pde & X86_PG_V) == 0) {
11708 m = pmap_san_enter_alloc_2m();
11710 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11711 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11713 m = pmap_san_enter_alloc_4k();
11714 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11718 if ((*pde & X86_PG_PS) != 0)
11720 pte = pmap_pde_to_pte(pde, va);
11721 if ((*pte & X86_PG_V) != 0)
11723 m = pmap_san_enter_alloc_4k();
11724 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11725 X86_PG_M | X86_PG_A | pg_nx);
11730 * Track a range of the kernel's virtual address space that is contiguous
11731 * in various mapping attributes.
11733 struct pmap_kernel_map_range {
11742 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11748 if (eva <= range->sva)
11751 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11752 for (i = 0; i < PAT_INDEX_SIZE; i++)
11753 if (pat_index[i] == pat_idx)
11757 case PAT_WRITE_BACK:
11760 case PAT_WRITE_THROUGH:
11763 case PAT_UNCACHEABLE:
11769 case PAT_WRITE_PROTECTED:
11772 case PAT_WRITE_COMBINING:
11776 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11777 __func__, pat_idx, range->sva, eva);
11782 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11784 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11785 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11786 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11787 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11788 mode, range->pdpes, range->pdes, range->ptes);
11790 /* Reset to sentinel value. */
11791 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11792 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11793 NPDEPG - 1, NPTEPG - 1);
11797 * Determine whether the attributes specified by a page table entry match those
11798 * being tracked by the current range. This is not quite as simple as a direct
11799 * flag comparison since some PAT modes have multiple representations.
11802 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11804 pt_entry_t diff, mask;
11806 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11807 diff = (range->attrs ^ attrs) & mask;
11810 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11811 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11812 pmap_pat_index(kernel_pmap, attrs, true))
11818 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11822 memset(range, 0, sizeof(*range));
11824 range->attrs = attrs;
11828 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11829 * those of the current run, dump the address range and its attributes, and
11833 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11834 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11839 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11841 attrs |= pdpe & pg_nx;
11842 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11843 if ((pdpe & PG_PS) != 0) {
11844 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11845 } else if (pde != 0) {
11846 attrs |= pde & pg_nx;
11847 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11849 if ((pde & PG_PS) != 0) {
11850 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11851 } else if (pte != 0) {
11852 attrs |= pte & pg_nx;
11853 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11854 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11856 /* Canonicalize by always using the PDE PAT bit. */
11857 if ((attrs & X86_PG_PTE_PAT) != 0)
11858 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11861 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11862 sysctl_kmaps_dump(sb, range, va);
11863 sysctl_kmaps_reinit(range, va, attrs);
11868 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
11870 struct pmap_kernel_map_range range;
11871 struct sbuf sbuf, *sb;
11872 pml4_entry_t pml4e;
11873 pdp_entry_t *pdp, pdpe;
11874 pd_entry_t *pd, pde;
11875 pt_entry_t *pt, pte;
11878 int error, i, j, k, l;
11880 error = sysctl_wire_old_buffer(req, 0);
11884 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
11886 /* Sentinel value. */
11887 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11888 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11889 NPDEPG - 1, NPTEPG - 1);
11892 * Iterate over the kernel page tables without holding the kernel pmap
11893 * lock. Outside of the large map, kernel page table pages are never
11894 * freed, so at worst we will observe inconsistencies in the output.
11895 * Within the large map, ensure that PDP and PD page addresses are
11896 * valid before descending.
11898 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
11901 sbuf_printf(sb, "\nRecursive map:\n");
11904 sbuf_printf(sb, "\nDirect map:\n");
11908 sbuf_printf(sb, "\nKASAN shadow map:\n");
11912 case KMSANSHADPML4I:
11913 sbuf_printf(sb, "\nKMSAN shadow map:\n");
11915 case KMSANORIGPML4I:
11916 sbuf_printf(sb, "\nKMSAN origin map:\n");
11920 sbuf_printf(sb, "\nKernel map:\n");
11923 sbuf_printf(sb, "\nLarge map:\n");
11927 /* Convert to canonical form. */
11928 if (sva == 1ul << 47)
11932 pml4e = kernel_pml4[i];
11933 if ((pml4e & X86_PG_V) == 0) {
11934 sva = rounddown2(sva, NBPML4);
11935 sysctl_kmaps_dump(sb, &range, sva);
11939 pa = pml4e & PG_FRAME;
11940 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
11942 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
11944 if ((pdpe & X86_PG_V) == 0) {
11945 sva = rounddown2(sva, NBPDP);
11946 sysctl_kmaps_dump(sb, &range, sva);
11950 pa = pdpe & PG_FRAME;
11951 if ((pdpe & PG_PS) != 0) {
11952 sva = rounddown2(sva, NBPDP);
11953 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
11959 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
11960 vm_phys_paddr_to_vm_page(pa) == NULL) {
11962 * Page table pages for the large map may be
11963 * freed. Validate the next-level address
11964 * before descending.
11968 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
11970 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
11972 if ((pde & X86_PG_V) == 0) {
11973 sva = rounddown2(sva, NBPDR);
11974 sysctl_kmaps_dump(sb, &range, sva);
11978 pa = pde & PG_FRAME;
11979 if ((pde & PG_PS) != 0) {
11980 sva = rounddown2(sva, NBPDR);
11981 sysctl_kmaps_check(sb, &range, sva,
11982 pml4e, pdpe, pde, 0);
11987 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
11988 vm_phys_paddr_to_vm_page(pa) == NULL) {
11990 * Page table pages for the large map
11991 * may be freed. Validate the
11992 * next-level address before descending.
11996 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
11998 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
11999 sva += PAGE_SIZE) {
12001 if ((pte & X86_PG_V) == 0) {
12002 sysctl_kmaps_dump(sb, &range,
12006 sysctl_kmaps_check(sb, &range, sva,
12007 pml4e, pdpe, pde, pte);
12014 error = sbuf_finish(sb);
12018 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12019 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12020 NULL, 0, sysctl_kmaps, "A",
12021 "Dump kernel address layout");
12024 DB_SHOW_COMMAND(pte, pmap_print_pte)
12027 pml5_entry_t *pml5;
12028 pml4_entry_t *pml4;
12031 pt_entry_t *pte, PG_V;
12035 db_printf("show pte addr\n");
12038 va = (vm_offset_t)addr;
12040 if (kdb_thread != NULL)
12041 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12043 pmap = PCPU_GET(curpmap);
12045 PG_V = pmap_valid_bit(pmap);
12046 db_printf("VA 0x%016lx", va);
12048 if (pmap_is_la57(pmap)) {
12049 pml5 = pmap_pml5e(pmap, va);
12050 db_printf(" pml5e 0x%016lx", *pml5);
12051 if ((*pml5 & PG_V) == 0) {
12055 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12057 pml4 = pmap_pml4e(pmap, va);
12059 db_printf(" pml4e 0x%016lx", *pml4);
12060 if ((*pml4 & PG_V) == 0) {
12064 pdp = pmap_pml4e_to_pdpe(pml4, va);
12065 db_printf(" pdpe 0x%016lx", *pdp);
12066 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12070 pde = pmap_pdpe_to_pde(pdp, va);
12071 db_printf(" pde 0x%016lx", *pde);
12072 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12076 pte = pmap_pde_to_pte(pde, va);
12077 db_printf(" pte 0x%016lx\n", *pte);
12080 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12085 a = (vm_paddr_t)addr;
12086 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12088 db_printf("show phys2dmap addr\n");
12093 ptpages_show_page(int level, int idx, vm_page_t pg)
12095 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12096 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12100 ptpages_show_complain(int level, int idx, uint64_t pte)
12102 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12106 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12108 vm_page_t pg3, pg2, pg1;
12109 pml4_entry_t *pml4;
12114 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12115 for (i4 = 0; i4 < num_entries; i4++) {
12116 if ((pml4[i4] & PG_V) == 0)
12118 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12120 ptpages_show_complain(3, i4, pml4[i4]);
12123 ptpages_show_page(3, i4, pg3);
12124 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12125 for (i3 = 0; i3 < NPDPEPG; i3++) {
12126 if ((pdp[i3] & PG_V) == 0)
12128 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12130 ptpages_show_complain(2, i3, pdp[i3]);
12133 ptpages_show_page(2, i3, pg2);
12134 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12135 for (i2 = 0; i2 < NPDEPG; i2++) {
12136 if ((pd[i2] & PG_V) == 0)
12138 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12140 ptpages_show_complain(1, i2, pd[i2]);
12143 ptpages_show_page(1, i2, pg1);
12149 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12153 pml5_entry_t *pml5;
12158 pmap = (pmap_t)addr;
12160 pmap = PCPU_GET(curpmap);
12162 PG_V = pmap_valid_bit(pmap);
12164 if (pmap_is_la57(pmap)) {
12165 pml5 = pmap->pm_pmltop;
12166 for (i5 = 0; i5 < NUPML5E; i5++) {
12167 if ((pml5[i5] & PG_V) == 0)
12169 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12171 ptpages_show_complain(4, i5, pml5[i5]);
12174 ptpages_show_page(4, i5, pg);
12175 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12178 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12179 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);