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;
1672 /* Allocate page table pages for the direct map */
1673 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1674 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1676 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1677 if (ndmpdpphys > NDMPML4E) {
1679 * Each NDMPML4E allows 512 GB, so limit to that,
1680 * and then readjust ndmpdp and ndmpdpphys.
1682 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1683 Maxmem = atop(NDMPML4E * NBPML4);
1684 ndmpdpphys = NDMPML4E;
1685 ndmpdp = NDMPML4E * NPDEPG;
1687 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1689 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1691 * Calculate the number of 1G pages that will fully fit in
1694 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1697 * Allocate 2M pages for the kernel. These will be used in
1698 * place of the one or more 1G pages from ndm1g that maps
1699 * kernel memory into DMAP.
1701 nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1702 kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1703 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1706 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1707 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1709 /* Allocate pages. */
1710 KPML4phys = allocpages(firstaddr, 1);
1711 KPDPphys = allocpages(firstaddr, NKPML4E);
1713 KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1714 KASANPDphys = allocpages(firstaddr, 1);
1718 * The KMSAN shadow maps are initially left unpopulated, since there is
1719 * no need to shadow memory above KERNBASE.
1721 KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1722 KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1726 * Allocate the initial number of kernel page table pages required to
1727 * bootstrap. We defer this until after all memory-size dependent
1728 * allocations are done (e.g. direct map), so that we don't have to
1729 * build in too much slop in our estimate.
1731 * Note that when NKPML4E > 1, we have an empty page underneath
1732 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1733 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1735 nkpt_init(*firstaddr);
1736 nkpdpe = NKPDPE(nkpt);
1738 KPTphys = allocpages(firstaddr, nkpt);
1739 KPDphys = allocpages(firstaddr, nkpdpe);
1742 nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1743 KASANPTphys = allocpages(firstaddr, nkasanpte);
1744 KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1748 * Connect the zero-filled PT pages to their PD entries. This
1749 * implicitly maps the PT pages at their correct locations within
1752 pd_p = (pd_entry_t *)KPDphys;
1753 for (i = 0; i < nkpt; i++)
1754 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1757 * Map from start of the kernel in physical memory (staging
1758 * area) to the end of loader preallocated memory using 2MB
1759 * pages. This replaces some of the PD entries created above.
1760 * For compatibility, identity map 2M at the start.
1762 pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1764 for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1765 /* Preset PG_M and PG_A because demotion expects it. */
1766 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1767 X86_PG_A | bootaddr_rwx(pax);
1771 * Because we map the physical blocks in 2M pages, adjust firstaddr
1772 * to record the physical blocks we've actually mapped into kernel
1773 * virtual address space.
1775 if (*firstaddr < round_2mpage(KERNend))
1776 *firstaddr = round_2mpage(KERNend);
1778 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1779 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1780 for (i = 0; i < nkpdpe; i++)
1781 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1784 kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1785 kasankpdpi = pmap_pdpe_index(kasankernbase);
1786 kasankpdi = pmap_pde_index(kasankernbase);
1788 pdp_p = (pdp_entry_t *)KASANPDPphys;
1789 pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1791 pd_p = (pd_entry_t *)KASANPDphys;
1792 for (i = 0; i < nkasanpte; i++)
1793 pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1796 pt_p = (pt_entry_t *)KASANPTphys;
1797 for (i = 0; i < nkasanpte * NPTEPG; i++)
1798 pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1799 X86_PG_M | X86_PG_A | pg_nx;
1803 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1804 * the end of physical memory is not aligned to a 1GB page boundary,
1805 * then the residual physical memory is mapped with 2MB pages. Later,
1806 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1807 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1808 * that are partially used.
1810 pd_p = (pd_entry_t *)DMPDphys;
1811 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1812 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1813 /* Preset PG_M and PG_A because demotion expects it. */
1814 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1815 X86_PG_M | X86_PG_A | pg_nx;
1817 pdp_p = (pdp_entry_t *)DMPDPphys;
1818 for (i = 0; i < ndm1g; i++) {
1819 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1820 /* Preset PG_M and PG_A because demotion expects it. */
1821 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1822 X86_PG_M | X86_PG_A | pg_nx;
1824 for (j = 0; i < ndmpdp; i++, j++) {
1825 pdp_p[i] = DMPDphys + ptoa(j);
1826 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1830 * Instead of using a 1G page for the memory containing the kernel,
1831 * use 2M pages with read-only and no-execute permissions. (If using 1G
1832 * pages, this will partially overwrite the PDPEs above.)
1835 pd_p = (pd_entry_t *)DMPDkernphys;
1836 for (i = 0, pax = rounddown2(kernphys, NBPDP);
1837 i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1838 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1839 X86_PG_A | pg_nx | bootaddr_rwx(pax);
1841 j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1842 for (i = 0; i < nkdmpde; i++) {
1843 pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1844 X86_PG_RW | X86_PG_V | pg_nx;
1848 /* And recursively map PML4 to itself in order to get PTmap */
1849 p4_p = (pml4_entry_t *)KPML4phys;
1850 p4_p[PML4PML4I] = KPML4phys;
1851 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1854 /* Connect the KASAN shadow map slots up to the PML4. */
1855 for (i = 0; i < NKASANPML4E; i++) {
1856 p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1857 p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1862 /* Connect the KMSAN shadow map slots up to the PML4. */
1863 for (i = 0; i < NKMSANSHADPML4E; i++) {
1864 p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1865 p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1868 /* Connect the KMSAN origin map slots up to the PML4. */
1869 for (i = 0; i < NKMSANORIGPML4E; i++) {
1870 p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1871 p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1875 /* Connect the Direct Map slots up to the PML4. */
1876 for (i = 0; i < ndmpdpphys; i++) {
1877 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1878 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1881 /* Connect the KVA slots up to the PML4 */
1882 for (i = 0; i < NKPML4E; i++) {
1883 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1884 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1887 kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1892 * Bootstrap the system enough to run with virtual memory.
1894 * On amd64 this is called after mapping has already been enabled
1895 * and just syncs the pmap module with what has already been done.
1896 * [We can't call it easily with mapping off since the kernel is not
1897 * mapped with PA == VA, hence we would have to relocate every address
1898 * from the linked base (virtual) address "KERNBASE" to the actual
1899 * (physical) address starting relative to 0]
1902 pmap_bootstrap(vm_paddr_t *firstaddr)
1905 pt_entry_t *pte, *pcpu_pte;
1906 struct region_descriptor r_gdt;
1907 uint64_t cr4, pcpu0_phys;
1912 KERNend = *firstaddr;
1913 res = atop(KERNend - (vm_paddr_t)kernphys);
1919 * Create an initial set of page tables to run the kernel in.
1921 create_pagetables(firstaddr);
1923 pcpu0_phys = allocpages(firstaddr, 1);
1926 * Add a physical memory segment (vm_phys_seg) corresponding to the
1927 * preallocated kernel page table pages so that vm_page structures
1928 * representing these pages will be created. The vm_page structures
1929 * are required for promotion of the corresponding kernel virtual
1930 * addresses to superpage mappings.
1932 vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1935 * Account for the virtual addresses mapped by create_pagetables().
1937 virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1938 (vm_paddr_t)kernphys);
1939 virtual_end = VM_MAX_KERNEL_ADDRESS;
1942 * Enable PG_G global pages, then switch to the kernel page
1943 * table from the bootstrap page table. After the switch, it
1944 * is possible to enable SMEP and SMAP since PG_U bits are
1950 load_cr3(KPML4phys);
1951 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1953 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1958 * Initialize the kernel pmap (which is statically allocated).
1959 * Count bootstrap data as being resident in case any of this data is
1960 * later unmapped (using pmap_remove()) and freed.
1962 PMAP_LOCK_INIT(kernel_pmap);
1963 kernel_pmap->pm_pmltop = kernel_pml4;
1964 kernel_pmap->pm_cr3 = KPML4phys;
1965 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1966 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1967 kernel_pmap->pm_stats.resident_count = res;
1968 kernel_pmap->pm_flags = pmap_flags;
1971 * The kernel pmap is always active on all CPUs. Once CPUs are
1972 * enumerated, the mask will be set equal to all_cpus.
1974 CPU_FILL(&kernel_pmap->pm_active);
1977 * Initialize the TLB invalidations generation number lock.
1979 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1982 * Reserve some special page table entries/VA space for temporary
1985 #define SYSMAP(c, p, v, n) \
1986 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1992 * Crashdump maps. The first page is reused as CMAP1 for the
1995 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1996 CADDR1 = crashdumpmap;
1998 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
2002 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2003 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2004 * number of CPUs and NUMA affinity.
2006 pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2007 X86_PG_M | X86_PG_A;
2008 for (i = 1; i < MAXCPU; i++)
2012 * Re-initialize PCPU area for BSP after switching.
2013 * Make hardware use gdt and common_tss from the new PCPU.
2015 STAILQ_INIT(&cpuhead);
2016 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2017 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2018 amd64_bsp_pcpu_init1(&__pcpu[0]);
2019 amd64_bsp_ist_init(&__pcpu[0]);
2020 __pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2022 memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2023 sizeof(struct user_segment_descriptor));
2024 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2025 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2026 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2027 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2028 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2030 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2031 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2032 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2033 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2036 * Initialize the PAT MSR.
2037 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2038 * side-effect, invalidates stale PG_G TLB entries that might
2039 * have been created in our pre-boot environment.
2043 /* Initialize TLB Context Id. */
2044 if (pmap_pcid_enabled) {
2045 kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2046 offsetof(struct pcpu, pc_kpmap_store);
2048 PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2049 PCPU_SET(kpmap_store.pm_gen, 1);
2052 * PMAP_PCID_KERN + 1 is used for initialization of
2053 * proc0 pmap. The pmap' pcid state might be used by
2054 * EFIRT entry before first context switch, so it
2055 * needs to be valid.
2057 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2058 PCPU_SET(pcid_gen, 1);
2061 * pcpu area for APs is zeroed during AP startup.
2062 * pc_pcid_next and pc_pcid_gen are initialized by AP
2063 * during pcpu setup.
2065 load_cr4(rcr4() | CR4_PCIDE);
2071 * Setup the PAT MSR.
2080 /* Bail if this CPU doesn't implement PAT. */
2081 if ((cpu_feature & CPUID_PAT) == 0)
2084 /* Set default PAT index table. */
2085 for (i = 0; i < PAT_INDEX_SIZE; i++)
2087 pat_index[PAT_WRITE_BACK] = 0;
2088 pat_index[PAT_WRITE_THROUGH] = 1;
2089 pat_index[PAT_UNCACHEABLE] = 3;
2090 pat_index[PAT_WRITE_COMBINING] = 6;
2091 pat_index[PAT_WRITE_PROTECTED] = 5;
2092 pat_index[PAT_UNCACHED] = 2;
2095 * Initialize default PAT entries.
2096 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2097 * Program 5 and 6 as WP and WC.
2099 * Leave 4 and 7 as WB and UC. Note that a recursive page table
2100 * mapping for a 2M page uses a PAT value with the bit 3 set due
2101 * to its overload with PG_PS.
2103 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2104 PAT_VALUE(1, PAT_WRITE_THROUGH) |
2105 PAT_VALUE(2, PAT_UNCACHED) |
2106 PAT_VALUE(3, PAT_UNCACHEABLE) |
2107 PAT_VALUE(4, PAT_WRITE_BACK) |
2108 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2109 PAT_VALUE(6, PAT_WRITE_COMBINING) |
2110 PAT_VALUE(7, PAT_UNCACHEABLE);
2114 load_cr4(cr4 & ~CR4_PGE);
2116 /* Disable caches (CD = 1, NW = 0). */
2118 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2120 /* Flushes caches and TLBs. */
2124 /* Update PAT and index table. */
2125 wrmsr(MSR_PAT, pat_msr);
2127 /* Flush caches and TLBs again. */
2131 /* Restore caches and PGE. */
2137 pmap_page_alloc_below_4g(bool zeroed)
2139 return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2140 1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2143 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2144 la57_trampoline_gdt[], la57_trampoline_end[];
2147 pmap_bootstrap_la57(void *arg __unused)
2150 pml5_entry_t *v_pml5;
2151 pml4_entry_t *v_pml4;
2155 vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2156 void (*la57_tramp)(uint64_t pml5);
2157 struct region_descriptor r_gdt;
2159 if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2161 TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2165 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2166 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2168 m_code = pmap_page_alloc_below_4g(true);
2169 v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2170 m_pml5 = pmap_page_alloc_below_4g(true);
2171 KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2172 v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2173 m_pml4 = pmap_page_alloc_below_4g(true);
2174 v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2175 m_pdp = pmap_page_alloc_below_4g(true);
2176 v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2177 m_pd = pmap_page_alloc_below_4g(true);
2178 v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2179 m_pt = pmap_page_alloc_below_4g(true);
2180 v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2183 * Map m_code 1:1, it appears below 4G in KVA due to physical
2184 * address being below 4G. Since kernel KVA is in upper half,
2185 * the pml4e should be zero and free for temporary use.
2187 kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2188 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2190 v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2191 VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2193 v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2194 VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2196 v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2197 VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2201 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2202 * entering all existing kernel mappings into level 5 table.
2204 v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2205 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g;
2208 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2210 v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2211 VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2213 v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2214 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2218 * Copy and call the 48->57 trampoline, hope we return there, alive.
2220 bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2221 *(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2222 la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2223 la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2224 invlpg((vm_offset_t)la57_tramp);
2225 la57_tramp(KPML5phys);
2228 * gdt was necessary reset, switch back to our gdt.
2231 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2235 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2236 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2237 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2240 * Now unmap the trampoline, and free the pages.
2241 * Clear pml5 entry used for 1:1 trampoline mapping.
2243 pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2244 invlpg((vm_offset_t)v_code);
2245 vm_page_free(m_code);
2246 vm_page_free(m_pdp);
2251 * Recursively map PML5 to itself in order to get PTmap and
2254 v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2256 vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2257 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2258 PTmap = (vm_offset_t)P5Tmap;
2259 vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2260 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2261 PDmap = (vm_offset_t)P5Dmap;
2263 kernel_pmap->pm_cr3 = KPML5phys;
2264 kernel_pmap->pm_pmltop = v_pml5;
2265 pmap_pt_page_count_adj(kernel_pmap, 1);
2267 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2270 * Initialize a vm_page's machine-dependent fields.
2273 pmap_page_init(vm_page_t m)
2276 TAILQ_INIT(&m->md.pv_list);
2277 m->md.pat_mode = PAT_WRITE_BACK;
2280 static int pmap_allow_2m_x_ept;
2281 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2282 &pmap_allow_2m_x_ept, 0,
2283 "Allow executable superpage mappings in EPT");
2286 pmap_allow_2m_x_ept_recalculate(void)
2289 * SKL002, SKL012S. Since the EPT format is only used by
2290 * Intel CPUs, the vendor check is merely a formality.
2292 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2293 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2294 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2295 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
2296 CPUID_TO_MODEL(cpu_id) == 0x27 ||
2297 CPUID_TO_MODEL(cpu_id) == 0x35 ||
2298 CPUID_TO_MODEL(cpu_id) == 0x36 ||
2299 CPUID_TO_MODEL(cpu_id) == 0x37 ||
2300 CPUID_TO_MODEL(cpu_id) == 0x86 ||
2301 CPUID_TO_MODEL(cpu_id) == 0x1c ||
2302 CPUID_TO_MODEL(cpu_id) == 0x4a ||
2303 CPUID_TO_MODEL(cpu_id) == 0x4c ||
2304 CPUID_TO_MODEL(cpu_id) == 0x4d ||
2305 CPUID_TO_MODEL(cpu_id) == 0x5a ||
2306 CPUID_TO_MODEL(cpu_id) == 0x5c ||
2307 CPUID_TO_MODEL(cpu_id) == 0x5d ||
2308 CPUID_TO_MODEL(cpu_id) == 0x5f ||
2309 CPUID_TO_MODEL(cpu_id) == 0x6e ||
2310 CPUID_TO_MODEL(cpu_id) == 0x7a ||
2311 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
2312 CPUID_TO_MODEL(cpu_id) == 0x85))))
2313 pmap_allow_2m_x_ept = 1;
2314 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2318 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2321 return (pmap->pm_type != PT_EPT || !executable ||
2322 !pmap_allow_2m_x_ept);
2327 pmap_init_pv_table(void)
2329 struct pmap_large_md_page *pvd;
2331 long start, end, highest, pv_npg;
2332 int domain, i, j, pages;
2335 * For correctness we depend on the size being evenly divisible into a
2336 * page. As a tradeoff between performance and total memory use, the
2337 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2338 * avoids false-sharing, but not being 128 bytes potentially allows for
2339 * avoidable traffic due to adjacent cacheline prefetcher.
2341 * Assert the size so that accidental changes fail to compile.
2343 CTASSERT((sizeof(*pvd) == 64));
2346 * Calculate the size of the array.
2348 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2349 pv_npg = howmany(pmap_last_pa, NBPDR);
2350 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2352 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2353 if (pv_table == NULL)
2354 panic("%s: kva_alloc failed\n", __func__);
2357 * Iterate physical segments to allocate space for respective pages.
2361 for (i = 0; i < vm_phys_nsegs; i++) {
2362 end = vm_phys_segs[i].end / NBPDR;
2363 domain = vm_phys_segs[i].domain;
2368 start = highest + 1;
2369 pvd = &pv_table[start];
2371 pages = end - start + 1;
2372 s = round_page(pages * sizeof(*pvd));
2373 highest = start + (s / sizeof(*pvd)) - 1;
2375 for (j = 0; j < s; j += PAGE_SIZE) {
2376 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2378 panic("failed to allocate PV table page");
2379 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2382 for (j = 0; j < s / sizeof(*pvd); j++) {
2383 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2384 TAILQ_INIT(&pvd->pv_page.pv_list);
2385 pvd->pv_page.pv_gen = 0;
2386 pvd->pv_page.pat_mode = 0;
2387 pvd->pv_invl_gen = 0;
2391 pvd = &pv_dummy_large;
2392 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2393 TAILQ_INIT(&pvd->pv_page.pv_list);
2394 pvd->pv_page.pv_gen = 0;
2395 pvd->pv_page.pat_mode = 0;
2396 pvd->pv_invl_gen = 0;
2400 pmap_init_pv_table(void)
2406 * Initialize the pool of pv list locks.
2408 for (i = 0; i < NPV_LIST_LOCKS; i++)
2409 rw_init(&pv_list_locks[i], "pmap pv list");
2412 * Calculate the size of the pv head table for superpages.
2414 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2417 * Allocate memory for the pv head table for superpages.
2419 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2421 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2422 for (i = 0; i < pv_npg; i++)
2423 TAILQ_INIT(&pv_table[i].pv_list);
2424 TAILQ_INIT(&pv_dummy.pv_list);
2429 * Initialize the pmap module.
2430 * Called by vm_init, to initialize any structures that the pmap
2431 * system needs to map virtual memory.
2436 struct pmap_preinit_mapping *ppim;
2438 int error, i, ret, skz63;
2440 /* L1TF, reserve page @0 unconditionally */
2441 vm_page_blacklist_add(0, bootverbose);
2443 /* Detect bare-metal Skylake Server and Skylake-X. */
2444 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2445 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2447 * Skylake-X errata SKZ63. Processor May Hang When
2448 * Executing Code In an HLE Transaction Region between
2449 * 40000000H and 403FFFFFH.
2451 * Mark the pages in the range as preallocated. It
2452 * seems to be impossible to distinguish between
2453 * Skylake Server and Skylake X.
2456 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2459 printf("SKZ63: skipping 4M RAM starting "
2460 "at physical 1G\n");
2461 for (i = 0; i < atop(0x400000); i++) {
2462 ret = vm_page_blacklist_add(0x40000000 +
2464 if (!ret && bootverbose)
2465 printf("page at %#lx already used\n",
2466 0x40000000 + ptoa(i));
2472 pmap_allow_2m_x_ept_recalculate();
2475 * Initialize the vm page array entries for the kernel pmap's
2478 PMAP_LOCK(kernel_pmap);
2479 for (i = 0; i < nkpt; i++) {
2480 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2481 KASSERT(mpte >= vm_page_array &&
2482 mpte < &vm_page_array[vm_page_array_size],
2483 ("pmap_init: page table page is out of range"));
2484 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2485 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2486 mpte->ref_count = 1;
2489 * Collect the page table pages that were replaced by a 2MB
2490 * page in create_pagetables(). They are zero filled.
2493 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2494 pmap_insert_pt_page(kernel_pmap, mpte, false))
2495 panic("pmap_init: pmap_insert_pt_page failed");
2497 PMAP_UNLOCK(kernel_pmap);
2501 * If the kernel is running on a virtual machine, then it must assume
2502 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2503 * be prepared for the hypervisor changing the vendor and family that
2504 * are reported by CPUID. Consequently, the workaround for AMD Family
2505 * 10h Erratum 383 is enabled if the processor's feature set does not
2506 * include at least one feature that is only supported by older Intel
2507 * or newer AMD processors.
2509 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2510 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2511 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2513 workaround_erratum383 = 1;
2516 * Are large page mappings enabled?
2518 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2519 if (pg_ps_enabled) {
2520 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2521 ("pmap_init: can't assign to pagesizes[1]"));
2522 pagesizes[1] = NBPDR;
2523 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2524 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2525 ("pmap_init: can't assign to pagesizes[2]"));
2526 pagesizes[2] = NBPDP;
2531 * Initialize pv chunk lists.
2533 for (i = 0; i < PMAP_MEMDOM; i++) {
2534 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2535 TAILQ_INIT(&pv_chunks[i].pvc_list);
2537 pmap_init_pv_table();
2539 pmap_initialized = 1;
2540 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2541 ppim = pmap_preinit_mapping + i;
2544 /* Make the direct map consistent */
2545 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2546 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2547 ppim->sz, ppim->mode);
2551 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2552 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2555 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2556 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2557 (vmem_addr_t *)&qframe);
2559 panic("qframe allocation failed");
2562 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2563 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2564 lm_ents = LMEPML4I - LMSPML4I + 1;
2566 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2568 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2569 lm_ents, KMSANORIGPML4I - LMSPML4I);
2570 lm_ents = KMSANORIGPML4I - LMSPML4I;
2574 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2575 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2577 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2578 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2579 if (large_vmem == NULL) {
2580 printf("pmap: cannot create large map\n");
2583 for (i = 0; i < lm_ents; i++) {
2584 m = pmap_large_map_getptp_unlocked();
2586 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2587 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2593 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2594 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2595 "Maximum number of PML4 entries for use by large map (tunable). "
2596 "Each entry corresponds to 512GB of address space.");
2598 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2599 "2MB page mapping counters");
2601 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2602 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2603 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2605 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2606 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2607 &pmap_pde_mappings, "2MB page mappings");
2609 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2610 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2611 &pmap_pde_p_failures, "2MB page promotion failures");
2613 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2614 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2615 &pmap_pde_promotions, "2MB page promotions");
2617 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2618 "1GB page mapping counters");
2620 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2621 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2622 &pmap_pdpe_demotions, "1GB page demotions");
2624 /***************************************************
2625 * Low level helper routines.....
2626 ***************************************************/
2629 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2631 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2633 switch (pmap->pm_type) {
2636 /* Verify that both PAT bits are not set at the same time */
2637 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2638 ("Invalid PAT bits in entry %#lx", entry));
2640 /* Swap the PAT bits if one of them is set */
2641 if ((entry & x86_pat_bits) != 0)
2642 entry ^= x86_pat_bits;
2646 * Nothing to do - the memory attributes are represented
2647 * the same way for regular pages and superpages.
2651 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2658 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2661 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2662 pat_index[(int)mode] >= 0);
2666 * Determine the appropriate bits to set in a PTE or PDE for a specified
2670 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2672 int cache_bits, pat_flag, pat_idx;
2674 if (!pmap_is_valid_memattr(pmap, mode))
2675 panic("Unknown caching mode %d\n", mode);
2677 switch (pmap->pm_type) {
2680 /* The PAT bit is different for PTE's and PDE's. */
2681 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2683 /* Map the caching mode to a PAT index. */
2684 pat_idx = pat_index[mode];
2686 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2689 cache_bits |= pat_flag;
2691 cache_bits |= PG_NC_PCD;
2693 cache_bits |= PG_NC_PWT;
2697 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2701 panic("unsupported pmap type %d", pmap->pm_type);
2704 return (cache_bits);
2708 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2712 switch (pmap->pm_type) {
2715 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2718 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2721 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2728 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2730 int pat_flag, pat_idx;
2733 switch (pmap->pm_type) {
2736 /* The PAT bit is different for PTE's and PDE's. */
2737 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2739 if ((pte & pat_flag) != 0)
2741 if ((pte & PG_NC_PCD) != 0)
2743 if ((pte & PG_NC_PWT) != 0)
2747 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2748 panic("EPT PTE %#lx has no PAT memory type", pte);
2749 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2753 /* See pmap_init_pat(). */
2763 pmap_ps_enabled(pmap_t pmap)
2766 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2770 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2773 switch (pmap->pm_type) {
2780 * This is a little bogus since the generation number is
2781 * supposed to be bumped up when a region of the address
2782 * space is invalidated in the page tables.
2784 * In this case the old PDE entry is valid but yet we want
2785 * to make sure that any mappings using the old entry are
2786 * invalidated in the TLB.
2788 * The reason this works as expected is because we rendezvous
2789 * "all" host cpus and force any vcpu context to exit as a
2792 atomic_add_long(&pmap->pm_eptgen, 1);
2795 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2797 pde_store(pde, newpde);
2801 * After changing the page size for the specified virtual address in the page
2802 * table, flush the corresponding entries from the processor's TLB. Only the
2803 * calling processor's TLB is affected.
2805 * The calling thread must be pinned to a processor.
2808 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2812 if (pmap_type_guest(pmap))
2815 KASSERT(pmap->pm_type == PT_X86,
2816 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2818 PG_G = pmap_global_bit(pmap);
2820 if ((newpde & PG_PS) == 0)
2821 /* Demotion: flush a specific 2MB page mapping. */
2822 pmap_invlpg(pmap, va);
2823 else if ((newpde & PG_G) == 0)
2825 * Promotion: flush every 4KB page mapping from the TLB
2826 * because there are too many to flush individually.
2831 * Promotion: flush every 4KB page mapping from the TLB,
2832 * including any global (PG_G) mappings.
2839 * The amd64 pmap uses different approaches to TLB invalidation
2840 * depending on the kernel configuration, available hardware features,
2841 * and known hardware errata. The kernel configuration option that
2842 * has the greatest operational impact on TLB invalidation is PTI,
2843 * which is enabled automatically on affected Intel CPUs. The most
2844 * impactful hardware features are first PCID, and then INVPCID
2845 * instruction presence. PCID usage is quite different for PTI
2848 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2849 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2850 * space is served by two page tables, user and kernel. The user
2851 * page table only maps user space and a kernel trampoline. The
2852 * kernel trampoline includes the entirety of the kernel text but
2853 * only the kernel data that is needed to switch from user to kernel
2854 * mode. The kernel page table maps the user and kernel address
2855 * spaces in their entirety. It is identical to the per-process
2856 * page table used in non-PTI mode.
2858 * User page tables are only used when the CPU is in user mode.
2859 * Consequently, some TLB invalidations can be postponed until the
2860 * switch from kernel to user mode. In contrast, the user
2861 * space part of the kernel page table is used for copyout(9), so
2862 * TLB invalidations on this page table cannot be similarly postponed.
2864 * The existence of a user mode page table for the given pmap is
2865 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2866 * which case pm_ucr3 contains the %cr3 register value for the user
2867 * mode page table's root.
2869 * * The pm_active bitmask indicates which CPUs currently have the
2870 * pmap active. A CPU's bit is set on context switch to the pmap, and
2871 * cleared on switching off this CPU. For the kernel page table,
2872 * the pm_active field is immutable and contains all CPUs. The
2873 * kernel page table is always logically active on every processor,
2874 * but not necessarily in use by the hardware, e.g., in PTI mode.
2876 * When requesting invalidation of virtual addresses with
2877 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2878 * all CPUs recorded as active in pm_active. Updates to and reads
2879 * from pm_active are not synchronized, and so they may race with
2880 * each other. Shootdown handlers are prepared to handle the race.
2882 * * PCID is an optional feature of the long mode x86 MMU where TLB
2883 * entries are tagged with the 'Process ID' of the address space
2884 * they belong to. This feature provides a limited namespace for
2885 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2888 * Allocation of a PCID to a pmap is done by an algorithm described
2889 * in section 15.12, "Other TLB Consistency Algorithms", of
2890 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2891 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2892 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2893 * the CPU is about to start caching TLB entries from a pmap,
2894 * i.e., on the context switch that activates the pmap on the CPU.
2896 * The PCID allocator maintains a per-CPU, per-pmap generation
2897 * count, pm_gen, which is incremented each time a new PCID is
2898 * allocated. On TLB invalidation, the generation counters for the
2899 * pmap are zeroed, which signals the context switch code that the
2900 * previously allocated PCID is no longer valid. Effectively,
2901 * zeroing any of these counters triggers a TLB shootdown for the
2902 * given CPU/address space, due to the allocation of a new PCID.
2904 * Zeroing can be performed remotely. Consequently, if a pmap is
2905 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2906 * be initiated by an ordinary memory access to reset the target
2907 * CPU's generation count within the pmap. The CPU initiating the
2908 * TLB shootdown does not need to send an IPI to the target CPU.
2910 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2911 * for complete (kernel) page tables, and PCIDs for user mode page
2912 * tables. A user PCID value is obtained from the kernel PCID value
2913 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2915 * User space page tables are activated on return to user mode, by
2916 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2917 * clearing bit 63 of the loaded ucr3, this effectively causes
2918 * complete invalidation of the user mode TLB entries for the
2919 * current pmap. In which case, local invalidations of individual
2920 * pages in the user page table are skipped.
2922 * * Local invalidation, all modes. If the requested invalidation is
2923 * for a specific address or the total invalidation of a currently
2924 * active pmap, then the TLB is flushed using INVLPG for a kernel
2925 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2926 * user space page table(s).
2928 * If the INVPCID instruction is available, it is used to flush user
2929 * entries from the kernel page table.
2931 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2932 * entries for the given page that either match the current PCID or
2933 * are global. Since TLB entries for the same page under different
2934 * PCIDs are unaffected, kernel pages which reside in all address
2935 * spaces could be problematic. We avoid the problem by creating
2936 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2939 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2940 * address space, all other 4095 PCIDs are used for user mode spaces
2941 * as described above. A context switch allocates a new PCID if
2942 * the recorded PCID is zero or the recorded generation does not match
2943 * the CPU's generation, effectively flushing the TLB for this address space.
2944 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2945 * local user page: INVLPG
2946 * local kernel page: INVLPG
2947 * local user total: INVPCID(CTX)
2948 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2949 * remote user page, inactive pmap: zero pm_gen
2950 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2951 * (Both actions are required to handle the aforementioned pm_active races.)
2952 * remote kernel page: IPI:INVLPG
2953 * remote user total, inactive pmap: zero pm_gen
2954 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2956 * (See note above about pm_active races.)
2957 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2959 * PTI enabled, PCID present.
2960 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2962 * local kernel page: INVLPG
2963 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
2964 * on loading UCR3 into %cr3 for upt
2965 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2966 * remote user page, inactive pmap: zero pm_gen
2967 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
2968 * INVPCID(ADDR) for upt)
2969 * remote kernel page: IPI:INVLPG
2970 * remote user total, inactive pmap: zero pm_gen
2971 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
2972 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
2973 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2976 * local user page: INVLPG
2977 * local kernel page: INVLPG
2978 * local user total: reload %cr3
2979 * local kernel total: invltlb_glob()
2980 * remote user page, inactive pmap: -
2981 * remote user page, active pmap: IPI:INVLPG
2982 * remote kernel page: IPI:INVLPG
2983 * remote user total, inactive pmap: -
2984 * remote user total, active pmap: IPI:(reload %cr3)
2985 * remote kernel total: IPI:invltlb_glob()
2986 * Since on return to user mode, the reload of %cr3 with ucr3 causes
2987 * TLB invalidation, no specific action is required for user page table.
2989 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
2995 * Interrupt the cpus that are executing in the guest context.
2996 * This will force the vcpu to exit and the cached EPT mappings
2997 * will be invalidated by the host before the next vmresume.
2999 static __inline void
3000 pmap_invalidate_ept(pmap_t pmap)
3006 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3007 ("pmap_invalidate_ept: absurd pm_active"));
3010 * The TLB mappings associated with a vcpu context are not
3011 * flushed each time a different vcpu is chosen to execute.
3013 * This is in contrast with a process's vtop mappings that
3014 * are flushed from the TLB on each context switch.
3016 * Therefore we need to do more than just a TLB shootdown on
3017 * the active cpus in 'pmap->pm_active'. To do this we keep
3018 * track of the number of invalidations performed on this pmap.
3020 * Each vcpu keeps a cache of this counter and compares it
3021 * just before a vmresume. If the counter is out-of-date an
3022 * invept will be done to flush stale mappings from the TLB.
3024 * To ensure that all vCPU threads have observed the new counter
3025 * value before returning, we use SMR. Ordering is important here:
3026 * the VMM enters an SMR read section before loading the counter
3027 * and after updating the pm_active bit set. Thus, pm_active is
3028 * a superset of active readers, and any reader that has observed
3029 * the goal has observed the new counter value.
3031 atomic_add_long(&pmap->pm_eptgen, 1);
3033 goal = smr_advance(pmap->pm_eptsmr);
3036 * Force the vcpu to exit and trap back into the hypervisor.
3038 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3039 ipi_selected(pmap->pm_active, ipinum);
3043 * Ensure that all active vCPUs will observe the new generation counter
3044 * value before executing any more guest instructions.
3046 smr_wait(pmap->pm_eptsmr, goal);
3050 pmap_invalidate_preipi_pcid(pmap_t pmap)
3052 struct pmap_pcid *pcidp;
3057 cpuid = PCPU_GET(cpuid);
3058 if (pmap != PCPU_GET(curpmap))
3059 cpuid = 0xffffffff; /* An impossible value */
3063 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3069 * The fence is between stores to pm_gen and the read of the
3070 * pm_active mask. We need to ensure that it is impossible
3071 * for us to miss the bit update in pm_active and
3072 * simultaneously observe a non-zero pm_gen in
3073 * pmap_activate_sw(), otherwise TLB update is missed.
3074 * Without the fence, IA32 allows such an outcome. Note that
3075 * pm_active is updated by a locked operation, which provides
3076 * the reciprocal fence.
3078 atomic_thread_fence_seq_cst();
3082 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3087 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3089 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3090 pmap_invalidate_preipi_nopcid);
3094 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3095 const bool invpcid_works1)
3097 struct invpcid_descr d;
3098 uint64_t kcr3, ucr3;
3102 * Because pm_pcid is recalculated on a context switch, we
3103 * must ensure there is no preemption, not just pinning.
3104 * Otherwise, we might use a stale value below.
3106 CRITICAL_ASSERT(curthread);
3109 * No need to do anything with user page tables invalidation
3110 * if there is no user page table, or invalidation is deferred
3111 * until the return to userspace. ucr3_load_mask is stable
3112 * because we have preemption disabled.
3114 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3115 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3118 pcid = pmap_get_pcid(pmap);
3119 if (invpcid_works1) {
3120 d.pcid = pcid | PMAP_PCID_USER_PT;
3123 invpcid(&d, INVPCID_ADDR);
3125 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3126 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3127 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3132 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3134 pmap_invalidate_page_pcid_cb(pmap, va, true);
3138 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3140 pmap_invalidate_page_pcid_cb(pmap, va, false);
3144 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3148 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3150 if (pmap_pcid_enabled)
3151 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3152 pmap_invalidate_page_pcid_noinvpcid_cb);
3153 return (pmap_invalidate_page_nopcid_cb);
3157 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3158 vm_offset_t addr2 __unused)
3160 if (pmap == kernel_pmap) {
3161 pmap_invlpg(kernel_pmap, va);
3162 } else if (pmap == PCPU_GET(curpmap)) {
3164 pmap_invalidate_page_cb(pmap, va);
3169 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3171 if (pmap_type_guest(pmap)) {
3172 pmap_invalidate_ept(pmap);
3176 KASSERT(pmap->pm_type == PT_X86,
3177 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3179 pmap_invalidate_preipi(pmap);
3180 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3183 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3184 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3187 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3188 const bool invpcid_works1)
3190 struct invpcid_descr d;
3191 uint64_t kcr3, ucr3;
3194 CRITICAL_ASSERT(curthread);
3196 if (pmap != PCPU_GET(curpmap) ||
3197 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3198 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3201 pcid = pmap_get_pcid(pmap);
3202 if (invpcid_works1) {
3203 d.pcid = pcid | PMAP_PCID_USER_PT;
3205 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3206 invpcid(&d, INVPCID_ADDR);
3208 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3209 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3210 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3215 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3218 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3222 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3225 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3229 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3230 vm_offset_t eva __unused)
3234 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3237 if (pmap_pcid_enabled)
3238 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3239 pmap_invalidate_range_pcid_noinvpcid_cb);
3240 return (pmap_invalidate_range_nopcid_cb);
3244 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3248 if (pmap == kernel_pmap) {
3249 if (PCPU_GET(pcid_invlpg_workaround)) {
3250 struct invpcid_descr d = { 0 };
3252 invpcid(&d, INVPCID_CTXGLOB);
3254 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3257 } else if (pmap == PCPU_GET(curpmap)) {
3258 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3260 pmap_invalidate_range_cb(pmap, sva, eva);
3265 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3267 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3268 pmap_invalidate_all(pmap);
3272 if (pmap_type_guest(pmap)) {
3273 pmap_invalidate_ept(pmap);
3277 KASSERT(pmap->pm_type == PT_X86,
3278 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3280 pmap_invalidate_preipi(pmap);
3281 smp_masked_invlpg_range(sva, eva, pmap,
3282 pmap_invalidate_range_curcpu_cb);
3286 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3288 struct invpcid_descr d;
3292 if (pmap == kernel_pmap) {
3293 if (invpcid_works1) {
3294 bzero(&d, sizeof(d));
3295 invpcid(&d, INVPCID_CTXGLOB);
3299 } else if (pmap == PCPU_GET(curpmap)) {
3300 CRITICAL_ASSERT(curthread);
3302 pcid = pmap_get_pcid(pmap);
3303 if (invpcid_works1) {
3307 invpcid(&d, INVPCID_CTX);
3309 kcr3 = pmap->pm_cr3 | pcid;
3312 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3313 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3318 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3320 pmap_invalidate_all_pcid_cb(pmap, true);
3324 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3326 pmap_invalidate_all_pcid_cb(pmap, false);
3330 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3332 if (pmap == kernel_pmap)
3334 else if (pmap == PCPU_GET(curpmap))
3338 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3340 if (pmap_pcid_enabled)
3341 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3342 pmap_invalidate_all_pcid_noinvpcid_cb);
3343 return (pmap_invalidate_all_nopcid_cb);
3347 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3348 vm_offset_t addr2 __unused)
3350 pmap_invalidate_all_cb(pmap);
3354 pmap_invalidate_all(pmap_t pmap)
3356 if (pmap_type_guest(pmap)) {
3357 pmap_invalidate_ept(pmap);
3361 KASSERT(pmap->pm_type == PT_X86,
3362 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3364 pmap_invalidate_preipi(pmap);
3365 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3369 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3370 vm_offset_t addr2 __unused)
3376 pmap_invalidate_cache(void)
3379 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3383 cpuset_t invalidate; /* processors that invalidate their TLB */
3388 u_int store; /* processor that updates the PDE */
3392 pmap_update_pde_action(void *arg)
3394 struct pde_action *act = arg;
3396 if (act->store == PCPU_GET(cpuid))
3397 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3401 pmap_update_pde_teardown(void *arg)
3403 struct pde_action *act = arg;
3405 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3406 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3410 * Change the page size for the specified virtual address in a way that
3411 * prevents any possibility of the TLB ever having two entries that map the
3412 * same virtual address using different page sizes. This is the recommended
3413 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3414 * machine check exception for a TLB state that is improperly diagnosed as a
3418 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3420 struct pde_action act;
3421 cpuset_t active, other_cpus;
3425 cpuid = PCPU_GET(cpuid);
3426 other_cpus = all_cpus;
3427 CPU_CLR(cpuid, &other_cpus);
3428 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3431 active = pmap->pm_active;
3433 if (CPU_OVERLAP(&active, &other_cpus)) {
3435 act.invalidate = active;
3439 act.newpde = newpde;
3440 CPU_SET(cpuid, &active);
3441 smp_rendezvous_cpus(active,
3442 smp_no_rendezvous_barrier, pmap_update_pde_action,
3443 pmap_update_pde_teardown, &act);
3445 pmap_update_pde_store(pmap, pde, newpde);
3446 if (CPU_ISSET(cpuid, &active))
3447 pmap_update_pde_invalidate(pmap, va, newpde);
3453 * Normal, non-SMP, invalidation functions.
3456 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3458 struct invpcid_descr d;
3459 uint64_t kcr3, ucr3;
3462 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3466 KASSERT(pmap->pm_type == PT_X86,
3467 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3469 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3471 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3472 pmap->pm_ucr3 != PMAP_NO_CR3) {
3474 pcid = pmap->pm_pcidp->pm_pcid;
3475 if (invpcid_works) {
3476 d.pcid = pcid | PMAP_PCID_USER_PT;
3479 invpcid(&d, INVPCID_ADDR);
3481 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3482 ucr3 = pmap->pm_ucr3 | pcid |
3483 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3484 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3488 } else if (pmap_pcid_enabled)
3489 pmap->pm_pcidp->pm_gen = 0;
3493 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3495 struct invpcid_descr d;
3497 uint64_t kcr3, ucr3;
3499 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3503 KASSERT(pmap->pm_type == PT_X86,
3504 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3506 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3507 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3509 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3510 pmap->pm_ucr3 != PMAP_NO_CR3) {
3512 if (invpcid_works) {
3513 d.pcid = pmap->pm_pcidp->pm_pcid |
3517 for (; d.addr < eva; d.addr += PAGE_SIZE)
3518 invpcid(&d, INVPCID_ADDR);
3520 kcr3 = pmap->pm_cr3 | pmap->pm_pcidp->
3521 pm_pcid | CR3_PCID_SAVE;
3522 ucr3 = pmap->pm_ucr3 | pmap->pm_pcidp->
3523 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3524 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3528 } else if (pmap_pcid_enabled) {
3529 pmap->pm_pcidp->pm_gen = 0;
3534 pmap_invalidate_all(pmap_t pmap)
3536 struct invpcid_descr d;
3537 uint64_t kcr3, ucr3;
3539 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3543 KASSERT(pmap->pm_type == PT_X86,
3544 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3546 if (pmap == kernel_pmap) {
3547 if (pmap_pcid_enabled && invpcid_works) {
3548 bzero(&d, sizeof(d));
3549 invpcid(&d, INVPCID_CTXGLOB);
3553 } else if (pmap == PCPU_GET(curpmap)) {
3554 if (pmap_pcid_enabled) {
3556 if (invpcid_works) {
3557 d.pcid = pmap->pm_pcidp->pm_pcid;
3560 invpcid(&d, INVPCID_CTX);
3561 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3562 d.pcid |= PMAP_PCID_USER_PT;
3563 invpcid(&d, INVPCID_CTX);
3566 kcr3 = pmap->pm_cr3 | pmap->pm_pcidp->pm_pcid;
3567 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3568 ucr3 = pmap->pm_ucr3 | pmap->pm_pcidp->
3569 pm_pcid | PMAP_PCID_USER_PT;
3570 pmap_pti_pcid_invalidate(ucr3, kcr3);
3578 } else if (pmap_pcid_enabled) {
3579 pmap->pm_pcidp->pm_gen = 0;
3584 pmap_invalidate_cache(void)
3591 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3594 pmap_update_pde_store(pmap, pde, newpde);
3595 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3596 pmap_update_pde_invalidate(pmap, va, newpde);
3598 pmap->pm_pcidp->pm_gen = 0;
3603 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3607 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3608 * by a promotion that did not invalidate the 512 4KB page mappings
3609 * that might exist in the TLB. Consequently, at this point, the TLB
3610 * may hold both 4KB and 2MB page mappings for the address range [va,
3611 * va + NBPDR). Therefore, the entire range must be invalidated here.
3612 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3613 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3614 * single INVLPG suffices to invalidate the 2MB page mapping from the
3617 if ((pde & PG_PROMOTED) != 0)
3618 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3620 pmap_invalidate_page(pmap, va);
3623 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3624 (vm_offset_t sva, vm_offset_t eva))
3627 if ((cpu_feature & CPUID_SS) != 0)
3628 return (pmap_invalidate_cache_range_selfsnoop);
3629 if ((cpu_feature & CPUID_CLFSH) != 0)
3630 return (pmap_force_invalidate_cache_range);
3631 return (pmap_invalidate_cache_range_all);
3634 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3637 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3640 KASSERT((sva & PAGE_MASK) == 0,
3641 ("pmap_invalidate_cache_range: sva not page-aligned"));
3642 KASSERT((eva & PAGE_MASK) == 0,
3643 ("pmap_invalidate_cache_range: eva not page-aligned"));
3647 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3650 pmap_invalidate_cache_range_check_align(sva, eva);
3654 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3657 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3660 * XXX: Some CPUs fault, hang, or trash the local APIC
3661 * registers if we use CLFLUSH on the local APIC range. The
3662 * local APIC is always uncached, so we don't need to flush
3663 * for that range anyway.
3665 if (pmap_kextract(sva) == lapic_paddr)
3668 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3670 * Do per-cache line flush. Use a locked
3671 * instruction to insure that previous stores are
3672 * included in the write-back. The processor
3673 * propagates flush to other processors in the cache
3676 atomic_thread_fence_seq_cst();
3677 for (; sva < eva; sva += cpu_clflush_line_size)
3679 atomic_thread_fence_seq_cst();
3682 * Writes are ordered by CLFLUSH on Intel CPUs.
3684 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3686 for (; sva < eva; sva += cpu_clflush_line_size)
3688 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3694 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3697 pmap_invalidate_cache_range_check_align(sva, eva);
3698 pmap_invalidate_cache();
3702 * Remove the specified set of pages from the data and instruction caches.
3704 * In contrast to pmap_invalidate_cache_range(), this function does not
3705 * rely on the CPU's self-snoop feature, because it is intended for use
3706 * when moving pages into a different cache domain.
3709 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3711 vm_offset_t daddr, eva;
3715 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3716 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3717 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3718 pmap_invalidate_cache();
3721 atomic_thread_fence_seq_cst();
3722 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3724 for (i = 0; i < count; i++) {
3725 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3726 eva = daddr + PAGE_SIZE;
3727 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3735 atomic_thread_fence_seq_cst();
3736 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3742 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3745 pmap_invalidate_cache_range_check_align(sva, eva);
3747 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3748 pmap_force_invalidate_cache_range(sva, eva);
3752 /* See comment in pmap_force_invalidate_cache_range(). */
3753 if (pmap_kextract(sva) == lapic_paddr)
3756 atomic_thread_fence_seq_cst();
3757 for (; sva < eva; sva += cpu_clflush_line_size)
3759 atomic_thread_fence_seq_cst();
3763 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3767 int error __diagused;
3770 KASSERT((spa & PAGE_MASK) == 0,
3771 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3772 KASSERT((epa & PAGE_MASK) == 0,
3773 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3775 if (spa < dmaplimit) {
3776 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3778 if (dmaplimit >= epa)
3783 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3785 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3787 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3788 pte = vtopte(vaddr);
3789 for (; spa < epa; spa += PAGE_SIZE) {
3791 pte_store(pte, spa | pte_bits);
3792 pmap_invlpg(kernel_pmap, vaddr);
3793 /* XXXKIB atomic inside flush_cache_range are excessive */
3794 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3797 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3801 * Routine: pmap_extract
3803 * Extract the physical page address associated
3804 * with the given map/virtual_address pair.
3807 pmap_extract(pmap_t pmap, vm_offset_t va)
3811 pt_entry_t *pte, PG_V;
3815 PG_V = pmap_valid_bit(pmap);
3817 pdpe = pmap_pdpe(pmap, va);
3818 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3819 if ((*pdpe & PG_PS) != 0)
3820 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3822 pde = pmap_pdpe_to_pde(pdpe, va);
3823 if ((*pde & PG_V) != 0) {
3824 if ((*pde & PG_PS) != 0) {
3825 pa = (*pde & PG_PS_FRAME) |
3828 pte = pmap_pde_to_pte(pde, va);
3829 pa = (*pte & PG_FRAME) |
3840 * Routine: pmap_extract_and_hold
3842 * Atomically extract and hold the physical page
3843 * with the given pmap and virtual address pair
3844 * if that mapping permits the given protection.
3847 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3849 pdp_entry_t pdpe, *pdpep;
3850 pd_entry_t pde, *pdep;
3851 pt_entry_t pte, PG_RW, PG_V;
3855 PG_RW = pmap_rw_bit(pmap);
3856 PG_V = pmap_valid_bit(pmap);
3859 pdpep = pmap_pdpe(pmap, va);
3860 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3862 if ((pdpe & PG_PS) != 0) {
3863 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3865 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3869 pdep = pmap_pdpe_to_pde(pdpep, va);
3870 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3872 if ((pde & PG_PS) != 0) {
3873 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3875 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3879 pte = *pmap_pde_to_pte(pdep, va);
3880 if ((pte & PG_V) == 0 ||
3881 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3883 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3886 if (m != NULL && !vm_page_wire_mapped(m))
3894 pmap_kextract(vm_offset_t va)
3899 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3900 pa = DMAP_TO_PHYS(va);
3901 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3902 pa = pmap_large_map_kextract(va);
3906 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3909 * Beware of a concurrent promotion that changes the
3910 * PDE at this point! For example, vtopte() must not
3911 * be used to access the PTE because it would use the
3912 * new PDE. It is, however, safe to use the old PDE
3913 * because the page table page is preserved by the
3916 pa = *pmap_pde_to_pte(&pde, va);
3917 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3923 /***************************************************
3924 * Low level mapping routines.....
3925 ***************************************************/
3928 * Add a wired page to the kva.
3929 * Note: not SMP coherent.
3932 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3937 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3938 X86_PG_RW | X86_PG_V);
3941 static __inline void
3942 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3948 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
3949 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3950 X86_PG_RW | X86_PG_V | cache_bits);
3954 * Remove a page from the kernel pagetables.
3955 * Note: not SMP coherent.
3958 pmap_kremove(vm_offset_t va)
3967 * Used to map a range of physical addresses into kernel
3968 * virtual address space.
3970 * The value passed in '*virt' is a suggested virtual address for
3971 * the mapping. Architectures which can support a direct-mapped
3972 * physical to virtual region can return the appropriate address
3973 * within that region, leaving '*virt' unchanged. Other
3974 * architectures should map the pages starting at '*virt' and
3975 * update '*virt' with the first usable address after the mapped
3979 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
3981 return PHYS_TO_DMAP(start);
3985 * Add a list of wired pages to the kva
3986 * this routine is only used for temporary
3987 * kernel mappings that do not need to have
3988 * page modification or references recorded.
3989 * Note that old mappings are simply written
3990 * over. The page *must* be wired.
3991 * Note: SMP coherent. Uses a ranged shootdown IPI.
3994 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
3996 pt_entry_t *endpte, oldpte, pa, *pte;
4002 endpte = pte + count;
4003 while (pte < endpte) {
4005 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
4006 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4007 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4009 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4010 X86_PG_M | X86_PG_RW | X86_PG_V);
4014 if (__predict_false((oldpte & X86_PG_V) != 0))
4015 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4020 * This routine tears out page mappings from the
4021 * kernel -- it is meant only for temporary mappings.
4022 * Note: SMP coherent. Uses a ranged shootdown IPI.
4025 pmap_qremove(vm_offset_t sva, int count)
4030 while (count-- > 0) {
4031 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4035 pmap_invalidate_range(kernel_pmap, sva, va);
4038 /***************************************************
4039 * Page table page management routines.....
4040 ***************************************************/
4042 * Schedule the specified unused page table page to be freed. Specifically,
4043 * add the page to the specified list of pages that will be released to the
4044 * physical memory manager after the TLB has been updated.
4046 static __inline void
4047 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
4048 boolean_t set_PG_ZERO)
4052 m->flags |= PG_ZERO;
4054 m->flags &= ~PG_ZERO;
4055 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4059 * Inserts the specified page table page into the specified pmap's collection
4060 * of idle page table pages. Each of a pmap's page table pages is responsible
4061 * for mapping a distinct range of virtual addresses. The pmap's collection is
4062 * ordered by this virtual address range.
4064 * If "promoted" is false, then the page table page "mpte" must be zero filled.
4067 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
4070 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4071 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
4072 return (vm_radix_insert(&pmap->pm_root, mpte));
4076 * Removes the page table page mapping the specified virtual address from the
4077 * specified pmap's collection of idle page table pages, and returns it.
4078 * Otherwise, returns NULL if there is no page table page corresponding to the
4079 * specified virtual address.
4081 static __inline vm_page_t
4082 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4085 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4086 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4090 * Decrements a page table page's reference count, which is used to record the
4091 * number of valid page table entries within the page. If the reference count
4092 * drops to zero, then the page table page is unmapped. Returns TRUE if the
4093 * page table page was unmapped and FALSE otherwise.
4095 static inline boolean_t
4096 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4100 if (m->ref_count == 0) {
4101 _pmap_unwire_ptp(pmap, va, m, free);
4108 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4114 vm_page_t pdpg, pdppg, pml4pg;
4116 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4119 * unmap the page table page
4121 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4123 MPASS(pmap_is_la57(pmap));
4124 pml5 = pmap_pml5e(pmap, va);
4126 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4127 pml5 = pmap_pml5e_u(pmap, va);
4130 } else if (m->pindex >= NUPDE + NUPDPE) {
4132 pml4 = pmap_pml4e(pmap, va);
4134 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4135 va <= VM_MAXUSER_ADDRESS) {
4136 pml4 = pmap_pml4e_u(pmap, va);
4139 } else if (m->pindex >= NUPDE) {
4141 pdp = pmap_pdpe(pmap, va);
4145 pd = pmap_pde(pmap, va);
4148 if (m->pindex < NUPDE) {
4149 /* We just released a PT, unhold the matching PD */
4150 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4151 pmap_unwire_ptp(pmap, va, pdpg, free);
4152 } else if (m->pindex < NUPDE + NUPDPE) {
4153 /* We just released a PD, unhold the matching PDP */
4154 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4155 pmap_unwire_ptp(pmap, va, pdppg, free);
4156 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4157 /* We just released a PDP, unhold the matching PML4 */
4158 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4159 pmap_unwire_ptp(pmap, va, pml4pg, free);
4162 pmap_pt_page_count_adj(pmap, -1);
4165 * Put page on a list so that it is released after
4166 * *ALL* TLB shootdown is done
4168 pmap_add_delayed_free_list(m, free, TRUE);
4172 * After removing a page table entry, this routine is used to
4173 * conditionally free the page, and manage the reference count.
4176 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4177 struct spglist *free)
4181 if (va >= VM_MAXUSER_ADDRESS)
4183 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4184 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4185 return (pmap_unwire_ptp(pmap, va, mpte, free));
4189 * Release a page table page reference after a failed attempt to create a
4193 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4195 struct spglist free;
4198 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4200 * Although "va" was never mapped, paging-structure caches
4201 * could nonetheless have entries that refer to the freed
4202 * page table pages. Invalidate those entries.
4204 pmap_invalidate_page(pmap, va);
4205 vm_page_free_pages_toq(&free, true);
4210 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4212 struct pmap_pcid *pcidp;
4216 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4217 pcidp->pm_pcid = pcid;
4218 pcidp->pm_gen = gen;
4223 pmap_pinit0(pmap_t pmap)
4228 PMAP_LOCK_INIT(pmap);
4229 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4230 pmap->pm_pmltopu = NULL;
4231 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4232 /* hack to keep pmap_pti_pcid_invalidate() alive */
4233 pmap->pm_ucr3 = PMAP_NO_CR3;
4234 vm_radix_init(&pmap->pm_root);
4235 CPU_ZERO(&pmap->pm_active);
4236 TAILQ_INIT(&pmap->pm_pvchunk);
4237 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4238 pmap->pm_flags = pmap_flags;
4239 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4240 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4241 pmap_activate_boot(pmap);
4246 p->p_md.md_flags |= P_MD_KPTI;
4249 pmap_thread_init_invl_gen(td);
4251 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4252 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4253 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4259 pmap_pinit_pml4(vm_page_t pml4pg)
4261 pml4_entry_t *pm_pml4;
4264 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4266 /* Wire in kernel global address entries. */
4267 for (i = 0; i < NKPML4E; i++) {
4268 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4272 for (i = 0; i < NKASANPML4E; i++) {
4273 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4278 for (i = 0; i < NKMSANSHADPML4E; i++) {
4279 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4280 X86_PG_RW | X86_PG_V | pg_nx;
4282 for (i = 0; i < NKMSANORIGPML4E; i++) {
4283 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4284 X86_PG_RW | X86_PG_V | pg_nx;
4287 for (i = 0; i < ndmpdpphys; i++) {
4288 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4292 /* install self-referential address mapping entry(s) */
4293 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4294 X86_PG_A | X86_PG_M;
4296 /* install large map entries if configured */
4297 for (i = 0; i < lm_ents; i++)
4298 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4302 pmap_pinit_pml5(vm_page_t pml5pg)
4304 pml5_entry_t *pm_pml5;
4306 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4309 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4310 * entering all existing kernel mappings into level 5 table.
4312 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4313 X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4314 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4317 * Install self-referential address mapping entry.
4319 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4320 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A |
4321 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4325 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4327 pml4_entry_t *pm_pml4u;
4330 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4331 for (i = 0; i < NPML4EPG; i++)
4332 pm_pml4u[i] = pti_pml4[i];
4336 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4338 pml5_entry_t *pm_pml5u;
4340 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4344 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4345 * table, entering all kernel mappings needed for usermode
4346 * into level 5 table.
4348 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4349 pmap_kextract((vm_offset_t)pti_pml4) |
4350 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M | pg_g |
4351 pmap_cache_bits(kernel_pmap, VM_MEMATTR_DEFAULT, FALSE);
4354 /* Allocate a page table page and do related bookkeeping */
4356 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4360 m = vm_page_alloc_noobj(flags);
4361 if (__predict_false(m == NULL))
4364 pmap_pt_page_count_adj(pmap, 1);
4369 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4372 * This function assumes the page will need to be unwired,
4373 * even though the counterpart allocation in pmap_alloc_pt_page()
4374 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4375 * of pmap_free_pt_page() require unwiring. The case in which
4376 * a PT page doesn't require unwiring because its ref_count has
4377 * naturally reached 0 is handled through _pmap_unwire_ptp().
4379 vm_page_unwire_noq(m);
4381 vm_page_free_zero(m);
4385 pmap_pt_page_count_adj(pmap, -1);
4388 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4391 * Initialize a preallocated and zeroed pmap structure,
4392 * such as one in a vmspace structure.
4395 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4397 vm_page_t pmltop_pg, pmltop_pgu;
4398 vm_paddr_t pmltop_phys;
4400 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4403 * Allocate the page directory page. Pass NULL instead of a
4404 * pointer to the pmap here to avoid calling
4405 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4406 * since that requires pmap lock. Instead do the accounting
4409 * Note that final call to pmap_remove() optimization that
4410 * checks for zero resident_count is basically disabled by
4411 * accounting for top-level page. But the optimization was
4412 * not effective since we started using non-managed mapping of
4415 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4417 pmap_pt_page_count_pinit(pmap, 1);
4419 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4420 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4422 if (pmap_pcid_enabled) {
4423 if (pmap->pm_pcidp == NULL)
4424 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4426 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4428 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4429 pmap->pm_ucr3 = PMAP_NO_CR3;
4430 pmap->pm_pmltopu = NULL;
4432 pmap->pm_type = pm_type;
4435 * Do not install the host kernel mappings in the nested page
4436 * tables. These mappings are meaningless in the guest physical
4438 * Install minimal kernel mappings in PTI case.
4442 pmap->pm_cr3 = pmltop_phys;
4443 if (pmap_is_la57(pmap))
4444 pmap_pinit_pml5(pmltop_pg);
4446 pmap_pinit_pml4(pmltop_pg);
4447 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4449 * As with pmltop_pg, pass NULL instead of a
4450 * pointer to the pmap to ensure that the PTI
4451 * page counted explicitly.
4453 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4454 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4455 pmap_pt_page_count_pinit(pmap, 1);
4456 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4457 VM_PAGE_TO_PHYS(pmltop_pgu));
4458 if (pmap_is_la57(pmap))
4459 pmap_pinit_pml5_pti(pmltop_pgu);
4461 pmap_pinit_pml4_pti(pmltop_pgu);
4462 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4464 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4465 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4466 pkru_free_range, pmap, M_NOWAIT);
4471 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4475 vm_radix_init(&pmap->pm_root);
4476 CPU_ZERO(&pmap->pm_active);
4477 TAILQ_INIT(&pmap->pm_pvchunk);
4478 pmap->pm_flags = flags;
4479 pmap->pm_eptgen = 0;
4485 pmap_pinit(pmap_t pmap)
4488 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4492 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4495 struct spglist free;
4497 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4498 if (mpg->ref_count != 0)
4501 _pmap_unwire_ptp(pmap, va, mpg, &free);
4502 pmap_invalidate_page(pmap, va);
4503 vm_page_free_pages_toq(&free, true);
4506 static pml4_entry_t *
4507 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4510 vm_pindex_t pml5index;
4517 if (!pmap_is_la57(pmap))
4518 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4520 PG_V = pmap_valid_bit(pmap);
4521 pml5index = pmap_pml5e_index(va);
4522 pml5 = &pmap->pm_pmltop[pml5index];
4523 if ((*pml5 & PG_V) == 0) {
4524 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4531 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4532 pml4 = &pml4[pmap_pml4e_index(va)];
4533 if ((*pml4 & PG_V) == 0) {
4534 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4535 if (allocated && !addref)
4536 pml4pg->ref_count--;
4537 else if (!allocated && addref)
4538 pml4pg->ref_count++;
4543 static pdp_entry_t *
4544 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4553 PG_V = pmap_valid_bit(pmap);
4555 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4559 if ((*pml4 & PG_V) == 0) {
4560 /* Have to allocate a new pdp, recurse */
4561 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4563 if (pmap_is_la57(pmap))
4564 pmap_allocpte_free_unref(pmap, va,
4565 pmap_pml5e(pmap, va));
4572 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4573 pdp = &pdp[pmap_pdpe_index(va)];
4574 if ((*pdp & PG_V) == 0) {
4575 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4576 if (allocated && !addref)
4578 else if (!allocated && addref)
4585 * The ptepindexes, i.e. page indices, of the page table pages encountered
4586 * while translating virtual address va are defined as follows:
4587 * - for the page table page (last level),
4588 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4589 * in other words, it is just the index of the PDE that maps the page
4591 * - for the page directory page,
4592 * ptepindex = NUPDE (number of userland PD entries) +
4593 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4594 * i.e. index of PDPE is put after the last index of PDE,
4595 * - for the page directory pointer page,
4596 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4598 * i.e. index of pml4e is put after the last index of PDPE,
4599 * - for the PML4 page (if LA57 mode is enabled),
4600 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4601 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4602 * i.e. index of pml5e is put after the last index of PML4E.
4604 * Define an order on the paging entries, where all entries of the
4605 * same height are put together, then heights are put from deepest to
4606 * root. Then ptexpindex is the sequential number of the
4607 * corresponding paging entry in this order.
4609 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4610 * LA57 paging structures even in LA48 paging mode. Moreover, the
4611 * ptepindexes are calculated as if the paging structures were 5-level
4612 * regardless of the actual mode of operation.
4614 * The root page at PML4/PML5 does not participate in this indexing scheme,
4615 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4618 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4621 vm_pindex_t pml5index, pml4index;
4622 pml5_entry_t *pml5, *pml5u;
4623 pml4_entry_t *pml4, *pml4u;
4627 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4629 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4631 PG_A = pmap_accessed_bit(pmap);
4632 PG_M = pmap_modified_bit(pmap);
4633 PG_V = pmap_valid_bit(pmap);
4634 PG_RW = pmap_rw_bit(pmap);
4637 * Allocate a page table page.
4639 m = pmap_alloc_pt_page(pmap, ptepindex,
4640 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4645 * Map the pagetable page into the process address space, if
4646 * it isn't already there.
4648 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4649 MPASS(pmap_is_la57(pmap));
4651 pml5index = pmap_pml5e_index(va);
4652 pml5 = &pmap->pm_pmltop[pml5index];
4653 KASSERT((*pml5 & PG_V) == 0,
4654 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4655 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4657 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4658 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4661 pml5u = &pmap->pm_pmltopu[pml5index];
4662 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4665 } else if (ptepindex >= NUPDE + NUPDPE) {
4666 pml4index = pmap_pml4e_index(va);
4667 /* Wire up a new PDPE page */
4668 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4670 pmap_free_pt_page(pmap, m, true);
4673 KASSERT((*pml4 & PG_V) == 0,
4674 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4675 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4677 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4678 pml4index < NUPML4E) {
4680 * PTI: Make all user-space mappings in the
4681 * kernel-mode page table no-execute so that
4682 * we detect any programming errors that leave
4683 * the kernel-mode page table active on return
4686 if (pmap->pm_ucr3 != PMAP_NO_CR3)
4689 pml4u = &pmap->pm_pmltopu[pml4index];
4690 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4693 } else if (ptepindex >= NUPDE) {
4694 /* Wire up a new PDE page */
4695 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4697 pmap_free_pt_page(pmap, m, true);
4700 KASSERT((*pdp & PG_V) == 0,
4701 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4702 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4704 /* Wire up a new PTE page */
4705 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4707 pmap_free_pt_page(pmap, m, true);
4710 if ((*pdp & PG_V) == 0) {
4711 /* Have to allocate a new pd, recurse */
4712 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4713 lockp, va) == NULL) {
4714 pmap_allocpte_free_unref(pmap, va,
4715 pmap_pml4e(pmap, va));
4716 pmap_free_pt_page(pmap, m, true);
4720 /* Add reference to the pd page */
4721 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4724 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4726 /* Now we know where the page directory page is */
4727 pd = &pd[pmap_pde_index(va)];
4728 KASSERT((*pd & PG_V) == 0,
4729 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4730 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4737 * This routine is called if the desired page table page does not exist.
4739 * If page table page allocation fails, this routine may sleep before
4740 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4741 * occurs right before returning to the caller. This way, we never
4742 * drop pmap lock to sleep while a page table page has ref_count == 0,
4743 * which prevents the page from being freed under us.
4746 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4751 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4752 if (m == NULL && lockp != NULL) {
4753 RELEASE_PV_LIST_LOCK(lockp);
4755 PMAP_ASSERT_NOT_IN_DI();
4763 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4764 struct rwlock **lockp)
4766 pdp_entry_t *pdpe, PG_V;
4769 vm_pindex_t pdpindex;
4771 PG_V = pmap_valid_bit(pmap);
4774 pdpe = pmap_pdpe(pmap, va);
4775 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4776 pde = pmap_pdpe_to_pde(pdpe, va);
4777 if (va < VM_MAXUSER_ADDRESS) {
4778 /* Add a reference to the pd page. */
4779 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4783 } else if (va < VM_MAXUSER_ADDRESS) {
4784 /* Allocate a pd page. */
4785 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4786 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4793 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4794 pde = &pde[pmap_pde_index(va)];
4796 panic("pmap_alloc_pde: missing page table page for va %#lx",
4803 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4805 vm_pindex_t ptepindex;
4806 pd_entry_t *pd, PG_V;
4809 PG_V = pmap_valid_bit(pmap);
4812 * Calculate pagetable page index
4814 ptepindex = pmap_pde_pindex(va);
4817 * Get the page directory entry
4819 pd = pmap_pde(pmap, va);
4822 * This supports switching from a 2MB page to a
4825 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4826 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4828 * Invalidation of the 2MB page mapping may have caused
4829 * the deallocation of the underlying PD page.
4836 * If the page table page is mapped, we just increment the
4837 * hold count, and activate it.
4839 if (pd != NULL && (*pd & PG_V) != 0) {
4840 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4844 * Here if the pte page isn't mapped, or if it has been
4847 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4848 if (m == NULL && lockp != NULL)
4854 /***************************************************
4855 * Pmap allocation/deallocation routines.
4856 ***************************************************/
4859 * Release any resources held by the given physical map.
4860 * Called when a pmap initialized by pmap_pinit is being released.
4861 * Should only be called if the map contains no valid mappings.
4864 pmap_release(pmap_t pmap)
4869 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4870 ("pmap_release: pmap %p has reserved page table page(s)",
4872 KASSERT(CPU_EMPTY(&pmap->pm_active),
4873 ("releasing active pmap %p", pmap));
4875 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4877 if (pmap_is_la57(pmap)) {
4878 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4879 pmap->pm_pmltop[PML5PML5I] = 0;
4881 for (i = 0; i < NKPML4E; i++) /* KVA */
4882 pmap->pm_pmltop[KPML4BASE + i] = 0;
4884 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4885 pmap->pm_pmltop[KASANPML4I + i] = 0;
4888 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4889 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4890 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4891 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4893 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4894 pmap->pm_pmltop[DMPML4I + i] = 0;
4895 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4896 for (i = 0; i < lm_ents; i++) /* Large Map */
4897 pmap->pm_pmltop[LMSPML4I + i] = 0;
4900 pmap_free_pt_page(NULL, m, true);
4901 pmap_pt_page_count_pinit(pmap, -1);
4903 if (pmap->pm_pmltopu != NULL) {
4904 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4906 pmap_free_pt_page(NULL, m, false);
4907 pmap_pt_page_count_pinit(pmap, -1);
4909 if (pmap->pm_type == PT_X86 &&
4910 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4911 rangeset_fini(&pmap->pm_pkru);
4913 KASSERT(pmap->pm_stats.resident_count == 0,
4914 ("pmap_release: pmap %p resident count %ld != 0",
4915 pmap, pmap->pm_stats.resident_count));
4919 kvm_size(SYSCTL_HANDLER_ARGS)
4921 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4923 return sysctl_handle_long(oidp, &ksize, 0, req);
4925 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4926 0, 0, kvm_size, "LU",
4930 kvm_free(SYSCTL_HANDLER_ARGS)
4932 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4934 return sysctl_handle_long(oidp, &kfree, 0, req);
4936 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4937 0, 0, kvm_free, "LU",
4938 "Amount of KVM free");
4942 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
4947 vm_paddr_t dummypa, dummypd, dummypt;
4950 npdpg = howmany(size, NBPDP);
4951 npde = size / NBPDR;
4953 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
4954 pagezero((void *)PHYS_TO_DMAP(dummypa));
4956 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
4957 pagezero((void *)PHYS_TO_DMAP(dummypt));
4958 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
4959 for (i = 0; i < npdpg; i++)
4960 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
4962 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
4963 for (i = 0; i < NPTEPG; i++)
4964 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
4965 X86_PG_A | X86_PG_M | pg_nx);
4967 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
4968 for (i = 0; i < npde; i++)
4969 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
4971 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
4972 for (i = 0; i < npdpg; i++)
4973 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
4978 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
4982 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
4985 * The end of the page array's KVA region is 2MB aligned, see
4988 size = round_2mpage(end) - start;
4989 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
4990 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
4995 * Allocate physical memory for the vm_page array and map it into KVA,
4996 * attempting to back the vm_pages with domain-local memory.
4999 pmap_page_array_startup(long pages)
5002 pd_entry_t *pde, newpdir;
5003 vm_offset_t va, start, end;
5008 vm_page_array_size = pages;
5010 start = VM_MIN_KERNEL_ADDRESS;
5011 end = start + pages * sizeof(struct vm_page);
5012 for (va = start; va < end; va += NBPDR) {
5013 pfn = first_page + (va - start) / sizeof(struct vm_page);
5014 domain = vm_phys_domain(ptoa(pfn));
5015 pdpe = pmap_pdpe(kernel_pmap, va);
5016 if ((*pdpe & X86_PG_V) == 0) {
5017 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5019 pagezero((void *)PHYS_TO_DMAP(pa));
5020 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5021 X86_PG_A | X86_PG_M);
5023 pde = pmap_pdpe_to_pde(pdpe, va);
5024 if ((*pde & X86_PG_V) != 0)
5025 panic("Unexpected pde");
5026 pa = vm_phys_early_alloc(domain, NBPDR);
5027 for (i = 0; i < NPDEPG; i++)
5028 dump_add_page(pa + i * PAGE_SIZE);
5029 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5030 X86_PG_M | PG_PS | pg_g | pg_nx);
5031 pde_store(pde, newpdir);
5033 vm_page_array = (vm_page_t)start;
5036 pmap_kmsan_page_array_startup(start, end);
5041 * grow the number of kernel page table entries, if needed
5044 pmap_growkernel(vm_offset_t addr)
5048 pd_entry_t *pde, newpdir;
5053 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5056 * The kernel map covers two distinct regions of KVA: that used
5057 * for dynamic kernel memory allocations, and the uppermost 2GB
5058 * of the virtual address space. The latter is used to map the
5059 * kernel and loadable kernel modules. This scheme enables the
5060 * use of a special code generation model for kernel code which
5061 * takes advantage of compact addressing modes in machine code.
5063 * Both regions grow upwards; to avoid wasting memory, the gap
5064 * in between is unmapped. If "addr" is above "KERNBASE", the
5065 * kernel's region is grown, otherwise the kmem region is grown.
5067 * The correctness of this action is based on the following
5068 * argument: vm_map_insert() allocates contiguous ranges of the
5069 * kernel virtual address space. It calls this function if a range
5070 * ends after "kernel_vm_end". If the kernel is mapped between
5071 * "kernel_vm_end" and "addr", then the range cannot begin at
5072 * "kernel_vm_end". In fact, its beginning address cannot be less
5073 * than the kernel. Thus, there is no immediate need to allocate
5074 * any new kernel page table pages between "kernel_vm_end" and
5077 if (KERNBASE < addr) {
5078 end = KERNBASE + nkpt * NBPDR;
5084 end = kernel_vm_end;
5087 addr = roundup2(addr, NBPDR);
5088 if (addr - 1 >= vm_map_max(kernel_map))
5089 addr = vm_map_max(kernel_map);
5092 * The grown region is already mapped, so there is
5099 kasan_shadow_map(end, addr - end);
5100 kmsan_shadow_map(end, addr - end);
5101 while (end < addr) {
5102 pdpe = pmap_pdpe(kernel_pmap, end);
5103 if ((*pdpe & X86_PG_V) == 0) {
5104 nkpg = pmap_alloc_pt_page(kernel_pmap,
5105 pmap_pdpe_pindex(end), VM_ALLOC_WIRED |
5106 VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5108 panic("pmap_growkernel: no memory to grow kernel");
5109 paddr = VM_PAGE_TO_PHYS(nkpg);
5110 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5111 X86_PG_A | X86_PG_M);
5112 continue; /* try again */
5114 pde = pmap_pdpe_to_pde(pdpe, end);
5115 if ((*pde & X86_PG_V) != 0) {
5116 end = (end + NBPDR) & ~PDRMASK;
5117 if (end - 1 >= vm_map_max(kernel_map)) {
5118 end = vm_map_max(kernel_map);
5124 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5125 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT | VM_ALLOC_ZERO);
5127 panic("pmap_growkernel: no memory to grow kernel");
5128 paddr = VM_PAGE_TO_PHYS(nkpg);
5129 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5130 pde_store(pde, newpdir);
5132 end = (end + NBPDR) & ~PDRMASK;
5133 if (end - 1 >= vm_map_max(kernel_map)) {
5134 end = vm_map_max(kernel_map);
5139 if (end <= KERNBASE)
5140 kernel_vm_end = end;
5142 nkpt = howmany(end - KERNBASE, NBPDR);
5146 /***************************************************
5147 * page management routines.
5148 ***************************************************/
5150 static const uint64_t pc_freemask[_NPCM] = {
5151 [0 ... _NPCM - 2] = PC_FREEN,
5152 [_NPCM - 1] = PC_FREEL
5157 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5158 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5159 &pc_chunk_count, "Current number of pv entry cnunks");
5161 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5162 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5163 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5165 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5166 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5167 &pc_chunk_frees, "Total number of pv entry chunks freed");
5169 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5170 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5172 "Number of failed attempts to get a pv entry chunk page");
5174 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5175 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5176 &pv_entry_frees, "Total number of pv entries freed");
5178 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5179 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5180 &pv_entry_allocs, "Total number of pv entries allocated");
5182 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5183 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5184 &pv_entry_count, "Current number of pv entries");
5186 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5187 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5188 &pv_entry_spare, "Current number of spare pv entries");
5192 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5197 pmap_invalidate_all(pmap);
5198 if (pmap != locked_pmap)
5201 pmap_delayed_invl_finish();
5205 * We are in a serious low memory condition. Resort to
5206 * drastic measures to free some pages so we can allocate
5207 * another pv entry chunk.
5209 * Returns NULL if PV entries were reclaimed from the specified pmap.
5211 * We do not, however, unmap 2mpages because subsequent accesses will
5212 * allocate per-page pv entries until repromotion occurs, thereby
5213 * exacerbating the shortage of free pv entries.
5216 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5218 struct pv_chunks_list *pvc;
5219 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5220 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5221 struct md_page *pvh;
5223 pmap_t next_pmap, pmap;
5224 pt_entry_t *pte, tpte;
5225 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5229 struct spglist free;
5231 int bit, field, freed;
5232 bool start_di, restart;
5234 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5235 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5238 PG_G = PG_A = PG_M = PG_RW = 0;
5240 bzero(&pc_marker_b, sizeof(pc_marker_b));
5241 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5242 pc_marker = (struct pv_chunk *)&pc_marker_b;
5243 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5246 * A delayed invalidation block should already be active if
5247 * pmap_advise() or pmap_remove() called this function by way
5248 * of pmap_demote_pde_locked().
5250 start_di = pmap_not_in_di();
5252 pvc = &pv_chunks[domain];
5253 mtx_lock(&pvc->pvc_lock);
5254 pvc->active_reclaims++;
5255 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5256 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5257 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5258 SLIST_EMPTY(&free)) {
5259 next_pmap = pc->pc_pmap;
5260 if (next_pmap == NULL) {
5262 * The next chunk is a marker. However, it is
5263 * not our marker, so active_reclaims must be
5264 * > 1. Consequently, the next_chunk code
5265 * will not rotate the pv_chunks list.
5269 mtx_unlock(&pvc->pvc_lock);
5272 * A pv_chunk can only be removed from the pc_lru list
5273 * when both pc_chunks_mutex is owned and the
5274 * corresponding pmap is locked.
5276 if (pmap != next_pmap) {
5278 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5281 /* Avoid deadlock and lock recursion. */
5282 if (pmap > locked_pmap) {
5283 RELEASE_PV_LIST_LOCK(lockp);
5286 pmap_delayed_invl_start();
5287 mtx_lock(&pvc->pvc_lock);
5289 } else if (pmap != locked_pmap) {
5290 if (PMAP_TRYLOCK(pmap)) {
5292 pmap_delayed_invl_start();
5293 mtx_lock(&pvc->pvc_lock);
5296 pmap = NULL; /* pmap is not locked */
5297 mtx_lock(&pvc->pvc_lock);
5298 pc = TAILQ_NEXT(pc_marker, pc_lru);
5300 pc->pc_pmap != next_pmap)
5304 } else if (start_di)
5305 pmap_delayed_invl_start();
5306 PG_G = pmap_global_bit(pmap);
5307 PG_A = pmap_accessed_bit(pmap);
5308 PG_M = pmap_modified_bit(pmap);
5309 PG_RW = pmap_rw_bit(pmap);
5315 * Destroy every non-wired, 4 KB page mapping in the chunk.
5318 for (field = 0; field < _NPCM; field++) {
5319 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5320 inuse != 0; inuse &= ~(1UL << bit)) {
5322 pv = &pc->pc_pventry[field * 64 + bit];
5324 pde = pmap_pde(pmap, va);
5325 if ((*pde & PG_PS) != 0)
5327 pte = pmap_pde_to_pte(pde, va);
5328 if ((*pte & PG_W) != 0)
5330 tpte = pte_load_clear(pte);
5331 if ((tpte & PG_G) != 0)
5332 pmap_invalidate_page(pmap, va);
5333 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5334 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5336 if ((tpte & PG_A) != 0)
5337 vm_page_aflag_set(m, PGA_REFERENCED);
5338 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5339 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5341 if (TAILQ_EMPTY(&m->md.pv_list) &&
5342 (m->flags & PG_FICTITIOUS) == 0) {
5343 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5344 if (TAILQ_EMPTY(&pvh->pv_list)) {
5345 vm_page_aflag_clear(m,
5349 pmap_delayed_invl_page(m);
5350 pc->pc_map[field] |= 1UL << bit;
5351 pmap_unuse_pt(pmap, va, *pde, &free);
5356 mtx_lock(&pvc->pvc_lock);
5359 /* Every freed mapping is for a 4 KB page. */
5360 pmap_resident_count_adj(pmap, -freed);
5361 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5362 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5363 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5364 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5365 if (pc_is_free(pc)) {
5366 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5367 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5368 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5369 /* Entire chunk is free; return it. */
5370 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5371 dump_drop_page(m_pc->phys_addr);
5372 mtx_lock(&pvc->pvc_lock);
5373 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5376 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5377 mtx_lock(&pvc->pvc_lock);
5378 /* One freed pv entry in locked_pmap is sufficient. */
5379 if (pmap == locked_pmap)
5382 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5383 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5384 if (pvc->active_reclaims == 1 && pmap != NULL) {
5386 * Rotate the pv chunks list so that we do not
5387 * scan the same pv chunks that could not be
5388 * freed (because they contained a wired
5389 * and/or superpage mapping) on every
5390 * invocation of reclaim_pv_chunk().
5392 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5393 MPASS(pc->pc_pmap != NULL);
5394 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5395 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5399 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5400 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5401 pvc->active_reclaims--;
5402 mtx_unlock(&pvc->pvc_lock);
5403 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5404 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5405 m_pc = SLIST_FIRST(&free);
5406 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5407 /* Recycle a freed page table page. */
5408 m_pc->ref_count = 1;
5410 vm_page_free_pages_toq(&free, true);
5415 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5420 domain = PCPU_GET(domain);
5421 for (i = 0; i < vm_ndomains; i++) {
5422 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5425 domain = (domain + 1) % vm_ndomains;
5432 * free the pv_entry back to the free list
5435 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5437 struct pv_chunk *pc;
5438 int idx, field, bit;
5440 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5441 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5442 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5443 PV_STAT(counter_u64_add(pv_entry_count, -1));
5444 pc = pv_to_chunk(pv);
5445 idx = pv - &pc->pc_pventry[0];
5448 pc->pc_map[field] |= 1ul << bit;
5449 if (!pc_is_free(pc)) {
5450 /* 98% of the time, pc is already at the head of the list. */
5451 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5452 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5453 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5457 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5462 free_pv_chunk_dequeued(struct pv_chunk *pc)
5466 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5467 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5468 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5469 counter_u64_add(pv_page_count, -1);
5470 /* entire chunk is free, return it */
5471 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5472 dump_drop_page(m->phys_addr);
5473 vm_page_unwire_noq(m);
5478 free_pv_chunk(struct pv_chunk *pc)
5480 struct pv_chunks_list *pvc;
5482 pvc = &pv_chunks[pc_to_domain(pc)];
5483 mtx_lock(&pvc->pvc_lock);
5484 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5485 mtx_unlock(&pvc->pvc_lock);
5486 free_pv_chunk_dequeued(pc);
5490 free_pv_chunk_batch(struct pv_chunklist *batch)
5492 struct pv_chunks_list *pvc;
5493 struct pv_chunk *pc, *npc;
5496 for (i = 0; i < vm_ndomains; i++) {
5497 if (TAILQ_EMPTY(&batch[i]))
5499 pvc = &pv_chunks[i];
5500 mtx_lock(&pvc->pvc_lock);
5501 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5502 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5504 mtx_unlock(&pvc->pvc_lock);
5507 for (i = 0; i < vm_ndomains; i++) {
5508 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5509 free_pv_chunk_dequeued(pc);
5515 * Returns a new PV entry, allocating a new PV chunk from the system when
5516 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5517 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5520 * The given PV list lock may be released.
5523 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5525 struct pv_chunks_list *pvc;
5528 struct pv_chunk *pc;
5531 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5532 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5534 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5536 for (field = 0; field < _NPCM; field++) {
5537 if (pc->pc_map[field]) {
5538 bit = bsfq(pc->pc_map[field]);
5542 if (field < _NPCM) {
5543 pv = &pc->pc_pventry[field * 64 + bit];
5544 pc->pc_map[field] &= ~(1ul << bit);
5545 /* If this was the last item, move it to tail */
5546 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
5547 pc->pc_map[2] == 0) {
5548 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5549 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5552 PV_STAT(counter_u64_add(pv_entry_count, 1));
5553 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5557 /* No free items, allocate another chunk */
5558 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5560 if (lockp == NULL) {
5561 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5564 m = reclaim_pv_chunk(pmap, lockp);
5568 counter_u64_add(pv_page_count, 1);
5569 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5570 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5571 dump_add_page(m->phys_addr);
5572 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5574 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5575 pc->pc_map[1] = PC_FREEN;
5576 pc->pc_map[2] = PC_FREEL;
5577 pvc = &pv_chunks[vm_page_domain(m)];
5578 mtx_lock(&pvc->pvc_lock);
5579 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5580 mtx_unlock(&pvc->pvc_lock);
5581 pv = &pc->pc_pventry[0];
5582 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5583 PV_STAT(counter_u64_add(pv_entry_count, 1));
5584 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5589 * Returns the number of one bits within the given PV chunk map.
5591 * The erratas for Intel processors state that "POPCNT Instruction May
5592 * Take Longer to Execute Than Expected". It is believed that the
5593 * issue is the spurious dependency on the destination register.
5594 * Provide a hint to the register rename logic that the destination
5595 * value is overwritten, by clearing it, as suggested in the
5596 * optimization manual. It should be cheap for unaffected processors
5599 * Reference numbers for erratas are
5600 * 4th Gen Core: HSD146
5601 * 5th Gen Core: BDM85
5602 * 6th Gen Core: SKL029
5605 popcnt_pc_map_pq(uint64_t *map)
5609 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5610 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5611 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5612 : "=&r" (result), "=&r" (tmp)
5613 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5618 * Ensure that the number of spare PV entries in the specified pmap meets or
5619 * exceeds the given count, "needed".
5621 * The given PV list lock may be released.
5624 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5626 struct pv_chunks_list *pvc;
5627 struct pch new_tail[PMAP_MEMDOM];
5628 struct pv_chunk *pc;
5633 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5634 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5637 * Newly allocated PV chunks must be stored in a private list until
5638 * the required number of PV chunks have been allocated. Otherwise,
5639 * reclaim_pv_chunk() could recycle one of these chunks. In
5640 * contrast, these chunks must be added to the pmap upon allocation.
5642 for (i = 0; i < PMAP_MEMDOM; i++)
5643 TAILQ_INIT(&new_tail[i]);
5646 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5648 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5649 bit_count((bitstr_t *)pc->pc_map, 0,
5650 sizeof(pc->pc_map) * NBBY, &free);
5653 free = popcnt_pc_map_pq(pc->pc_map);
5657 if (avail >= needed)
5660 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5661 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5663 m = reclaim_pv_chunk(pmap, lockp);
5668 counter_u64_add(pv_page_count, 1);
5669 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5670 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5671 dump_add_page(m->phys_addr);
5672 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5674 pc->pc_map[0] = PC_FREEN;
5675 pc->pc_map[1] = PC_FREEN;
5676 pc->pc_map[2] = PC_FREEL;
5677 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5678 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5679 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5682 * The reclaim might have freed a chunk from the current pmap.
5683 * If that chunk contained available entries, we need to
5684 * re-count the number of available entries.
5689 for (i = 0; i < vm_ndomains; i++) {
5690 if (TAILQ_EMPTY(&new_tail[i]))
5692 pvc = &pv_chunks[i];
5693 mtx_lock(&pvc->pvc_lock);
5694 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5695 mtx_unlock(&pvc->pvc_lock);
5700 * First find and then remove the pv entry for the specified pmap and virtual
5701 * address from the specified pv list. Returns the pv entry if found and NULL
5702 * otherwise. This operation can be performed on pv lists for either 4KB or
5703 * 2MB page mappings.
5705 static __inline pv_entry_t
5706 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5710 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5711 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5712 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5721 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5722 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5723 * entries for each of the 4KB page mappings.
5726 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5727 struct rwlock **lockp)
5729 struct md_page *pvh;
5730 struct pv_chunk *pc;
5732 vm_offset_t va_last;
5736 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5737 KASSERT((pa & PDRMASK) == 0,
5738 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5739 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5742 * Transfer the 2mpage's pv entry for this mapping to the first
5743 * page's pv list. Once this transfer begins, the pv list lock
5744 * must not be released until the last pv entry is reinstantiated.
5746 pvh = pa_to_pvh(pa);
5747 va = trunc_2mpage(va);
5748 pv = pmap_pvh_remove(pvh, pmap, va);
5749 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5750 m = PHYS_TO_VM_PAGE(pa);
5751 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5753 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5754 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5755 va_last = va + NBPDR - PAGE_SIZE;
5757 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5758 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
5759 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
5760 for (field = 0; field < _NPCM; field++) {
5761 while (pc->pc_map[field]) {
5762 bit = bsfq(pc->pc_map[field]);
5763 pc->pc_map[field] &= ~(1ul << bit);
5764 pv = &pc->pc_pventry[field * 64 + bit];
5768 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5769 ("pmap_pv_demote_pde: page %p is not managed", m));
5770 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5776 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5777 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5780 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
5781 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5782 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5784 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5785 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5788 #if VM_NRESERVLEVEL > 0
5790 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5791 * replace the many pv entries for the 4KB page mappings by a single pv entry
5792 * for the 2MB page mapping.
5795 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5796 struct rwlock **lockp)
5798 struct md_page *pvh;
5800 vm_offset_t va_last;
5803 KASSERT((pa & PDRMASK) == 0,
5804 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5805 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5808 * Transfer the first page's pv entry for this mapping to the 2mpage's
5809 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5810 * a transfer avoids the possibility that get_pv_entry() calls
5811 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5812 * mappings that is being promoted.
5814 m = PHYS_TO_VM_PAGE(pa);
5815 va = trunc_2mpage(va);
5816 pv = pmap_pvh_remove(&m->md, pmap, va);
5817 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5818 pvh = pa_to_pvh(pa);
5819 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5821 /* Free the remaining NPTEPG - 1 pv entries. */
5822 va_last = va + NBPDR - PAGE_SIZE;
5826 pmap_pvh_free(&m->md, pmap, va);
5827 } while (va < va_last);
5829 #endif /* VM_NRESERVLEVEL > 0 */
5832 * First find and then destroy the pv entry for the specified pmap and virtual
5833 * address. This operation can be performed on pv lists for either 4KB or 2MB
5837 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5841 pv = pmap_pvh_remove(pvh, pmap, va);
5842 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5843 free_pv_entry(pmap, pv);
5847 * Conditionally create the PV entry for a 4KB page mapping if the required
5848 * memory can be allocated without resorting to reclamation.
5851 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5852 struct rwlock **lockp)
5856 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5857 /* Pass NULL instead of the lock pointer to disable reclamation. */
5858 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5860 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5861 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5869 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5870 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5871 * false if the PV entry cannot be allocated without resorting to reclamation.
5874 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5875 struct rwlock **lockp)
5877 struct md_page *pvh;
5881 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5882 /* Pass NULL instead of the lock pointer to disable reclamation. */
5883 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5884 NULL : lockp)) == NULL)
5887 pa = pde & PG_PS_FRAME;
5888 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5889 pvh = pa_to_pvh(pa);
5890 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5896 * Fills a page table page with mappings to consecutive physical pages.
5899 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5903 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5905 newpte += PAGE_SIZE;
5910 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5911 * mapping is invalidated.
5914 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5916 struct rwlock *lock;
5920 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5927 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5931 pt_entry_t *xpte, *ypte;
5933 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5934 xpte++, newpte += PAGE_SIZE) {
5935 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
5936 printf("pmap_demote_pde: xpte %zd and newpte map "
5937 "different pages: found %#lx, expected %#lx\n",
5938 xpte - firstpte, *xpte, newpte);
5939 printf("page table dump\n");
5940 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
5941 printf("%zd %#lx\n", ypte - firstpte, *ypte);
5946 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
5947 ("pmap_demote_pde: firstpte and newpte map different physical"
5954 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
5955 pd_entry_t oldpde, struct rwlock **lockp)
5957 struct spglist free;
5961 sva = trunc_2mpage(va);
5962 pmap_remove_pde(pmap, pde, sva, &free, lockp);
5963 if ((oldpde & pmap_global_bit(pmap)) == 0)
5964 pmap_invalidate_pde_page(pmap, sva, oldpde);
5965 vm_page_free_pages_toq(&free, true);
5966 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
5971 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
5972 struct rwlock **lockp)
5974 pd_entry_t newpde, oldpde;
5975 pt_entry_t *firstpte, newpte;
5976 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
5982 PG_A = pmap_accessed_bit(pmap);
5983 PG_G = pmap_global_bit(pmap);
5984 PG_M = pmap_modified_bit(pmap);
5985 PG_RW = pmap_rw_bit(pmap);
5986 PG_V = pmap_valid_bit(pmap);
5987 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
5988 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
5990 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5991 in_kernel = va >= VM_MAXUSER_ADDRESS;
5993 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
5994 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
5997 * Invalidate the 2MB page mapping and return "failure" if the
5998 * mapping was never accessed.
6000 if ((oldpde & PG_A) == 0) {
6001 KASSERT((oldpde & PG_W) == 0,
6002 ("pmap_demote_pde: a wired mapping is missing PG_A"));
6003 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6007 mpte = pmap_remove_pt_page(pmap, va);
6009 KASSERT((oldpde & PG_W) == 0,
6010 ("pmap_demote_pde: page table page for a wired mapping"
6014 * If the page table page is missing and the mapping
6015 * is for a kernel address, the mapping must belong to
6016 * the direct map. Page table pages are preallocated
6017 * for every other part of the kernel address space,
6018 * so the direct map region is the only part of the
6019 * kernel address space that must be handled here.
6021 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6022 va < DMAP_MAX_ADDRESS),
6023 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6026 * If the 2MB page mapping belongs to the direct map
6027 * region of the kernel's address space, then the page
6028 * allocation request specifies the highest possible
6029 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6030 * priority is normal.
6032 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6033 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6036 * If the allocation of the new page table page fails,
6037 * invalidate the 2MB page mapping and return "failure".
6040 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6045 mpte->ref_count = NPTEPG;
6047 mptepa = VM_PAGE_TO_PHYS(mpte);
6048 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6049 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6050 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6051 ("pmap_demote_pde: oldpde is missing PG_M"));
6052 newpte = oldpde & ~PG_PS;
6053 newpte = pmap_swap_pat(pmap, newpte);
6056 * If the page table page is not leftover from an earlier promotion,
6059 if (vm_page_none_valid(mpte))
6060 pmap_fill_ptp(firstpte, newpte);
6062 pmap_demote_pde_check(firstpte, newpte);
6065 * If the mapping has changed attributes, update the page table
6068 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6069 pmap_fill_ptp(firstpte, newpte);
6072 * The spare PV entries must be reserved prior to demoting the
6073 * mapping, that is, prior to changing the PDE. Otherwise, the state
6074 * of the PDE and the PV lists will be inconsistent, which can result
6075 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6076 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6077 * PV entry for the 2MB page mapping that is being demoted.
6079 if ((oldpde & PG_MANAGED) != 0)
6080 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6083 * Demote the mapping. This pmap is locked. The old PDE has
6084 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6085 * set. Thus, there is no danger of a race with another
6086 * processor changing the setting of PG_A and/or PG_M between
6087 * the read above and the store below.
6089 if (workaround_erratum383)
6090 pmap_update_pde(pmap, va, pde, newpde);
6092 pde_store(pde, newpde);
6095 * Invalidate a stale recursive mapping of the page table page.
6098 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6101 * Demote the PV entry.
6103 if ((oldpde & PG_MANAGED) != 0)
6104 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6106 counter_u64_add(pmap_pde_demotions, 1);
6107 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6113 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6116 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6122 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6123 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6124 mpte = pmap_remove_pt_page(pmap, va);
6126 panic("pmap_remove_kernel_pde: Missing pt page.");
6128 mptepa = VM_PAGE_TO_PHYS(mpte);
6129 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6132 * If this page table page was unmapped by a promotion, then it
6133 * contains valid mappings. Zero it to invalidate those mappings.
6135 if (vm_page_any_valid(mpte))
6136 pagezero((void *)PHYS_TO_DMAP(mptepa));
6139 * Demote the mapping.
6141 if (workaround_erratum383)
6142 pmap_update_pde(pmap, va, pde, newpde);
6144 pde_store(pde, newpde);
6147 * Invalidate a stale recursive mapping of the page table page.
6149 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6153 * pmap_remove_pde: do the things to unmap a superpage in a process
6156 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6157 struct spglist *free, struct rwlock **lockp)
6159 struct md_page *pvh;
6161 vm_offset_t eva, va;
6163 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6165 PG_G = pmap_global_bit(pmap);
6166 PG_A = pmap_accessed_bit(pmap);
6167 PG_M = pmap_modified_bit(pmap);
6168 PG_RW = pmap_rw_bit(pmap);
6170 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6171 KASSERT((sva & PDRMASK) == 0,
6172 ("pmap_remove_pde: sva is not 2mpage aligned"));
6173 oldpde = pte_load_clear(pdq);
6175 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6176 if ((oldpde & PG_G) != 0)
6177 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6178 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6179 if (oldpde & PG_MANAGED) {
6180 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6181 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6182 pmap_pvh_free(pvh, pmap, sva);
6184 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6185 va < eva; va += PAGE_SIZE, m++) {
6186 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6189 vm_page_aflag_set(m, PGA_REFERENCED);
6190 if (TAILQ_EMPTY(&m->md.pv_list) &&
6191 TAILQ_EMPTY(&pvh->pv_list))
6192 vm_page_aflag_clear(m, PGA_WRITEABLE);
6193 pmap_delayed_invl_page(m);
6196 if (pmap == kernel_pmap) {
6197 pmap_remove_kernel_pde(pmap, pdq, sva);
6199 mpte = pmap_remove_pt_page(pmap, sva);
6201 KASSERT(vm_page_all_valid(mpte),
6202 ("pmap_remove_pde: pte page not promoted"));
6203 pmap_pt_page_count_adj(pmap, -1);
6204 KASSERT(mpte->ref_count == NPTEPG,
6205 ("pmap_remove_pde: pte page ref count error"));
6206 mpte->ref_count = 0;
6207 pmap_add_delayed_free_list(mpte, free, FALSE);
6210 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6214 * pmap_remove_pte: do the things to unmap a page in a process
6217 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6218 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6220 struct md_page *pvh;
6221 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6224 PG_A = pmap_accessed_bit(pmap);
6225 PG_M = pmap_modified_bit(pmap);
6226 PG_RW = pmap_rw_bit(pmap);
6228 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6229 oldpte = pte_load_clear(ptq);
6231 pmap->pm_stats.wired_count -= 1;
6232 pmap_resident_count_adj(pmap, -1);
6233 if (oldpte & PG_MANAGED) {
6234 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6235 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6238 vm_page_aflag_set(m, PGA_REFERENCED);
6239 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6240 pmap_pvh_free(&m->md, pmap, va);
6241 if (TAILQ_EMPTY(&m->md.pv_list) &&
6242 (m->flags & PG_FICTITIOUS) == 0) {
6243 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6244 if (TAILQ_EMPTY(&pvh->pv_list))
6245 vm_page_aflag_clear(m, PGA_WRITEABLE);
6247 pmap_delayed_invl_page(m);
6249 return (pmap_unuse_pt(pmap, va, ptepde, free));
6253 * Remove a single page from a process address space
6256 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6257 struct spglist *free)
6259 struct rwlock *lock;
6260 pt_entry_t *pte, PG_V;
6262 PG_V = pmap_valid_bit(pmap);
6263 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6264 if ((*pde & PG_V) == 0)
6266 pte = pmap_pde_to_pte(pde, va);
6267 if ((*pte & PG_V) == 0)
6270 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6273 pmap_invalidate_page(pmap, va);
6277 * Removes the specified range of addresses from the page table page.
6280 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6281 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6283 pt_entry_t PG_G, *pte;
6287 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6288 PG_G = pmap_global_bit(pmap);
6291 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6295 pmap_invalidate_range(pmap, va, sva);
6300 if ((*pte & PG_G) == 0)
6304 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6310 pmap_invalidate_range(pmap, va, sva);
6315 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6317 struct rwlock *lock;
6319 vm_offset_t va_next;
6320 pml5_entry_t *pml5e;
6321 pml4_entry_t *pml4e;
6323 pd_entry_t ptpaddr, *pde;
6324 pt_entry_t PG_G, PG_V;
6325 struct spglist free;
6328 PG_G = pmap_global_bit(pmap);
6329 PG_V = pmap_valid_bit(pmap);
6332 * If there are no resident pages besides the top level page
6333 * table page(s), there is nothing to do. Kernel pmap always
6334 * accounts whole preloaded area as resident, which makes its
6335 * resident count > 2.
6336 * Perform an unsynchronized read. This is, however, safe.
6338 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6345 pmap_delayed_invl_start();
6348 pmap_pkru_on_remove(pmap, sva, eva);
6351 * special handling of removing one page. a very
6352 * common operation and easy to short circuit some
6355 if (sva + PAGE_SIZE == eva) {
6356 pde = pmap_pde(pmap, sva);
6357 if (pde && (*pde & PG_PS) == 0) {
6358 pmap_remove_page(pmap, sva, pde, &free);
6364 for (; sva < eva; sva = va_next) {
6365 if (pmap->pm_stats.resident_count == 0)
6368 if (pmap_is_la57(pmap)) {
6369 pml5e = pmap_pml5e(pmap, sva);
6370 if ((*pml5e & PG_V) == 0) {
6371 va_next = (sva + NBPML5) & ~PML5MASK;
6376 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6378 pml4e = pmap_pml4e(pmap, sva);
6380 if ((*pml4e & PG_V) == 0) {
6381 va_next = (sva + NBPML4) & ~PML4MASK;
6387 va_next = (sva + NBPDP) & ~PDPMASK;
6390 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6391 if ((*pdpe & PG_V) == 0)
6393 if ((*pdpe & PG_PS) != 0) {
6394 KASSERT(va_next <= eva,
6395 ("partial update of non-transparent 1G mapping "
6396 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6397 *pdpe, sva, eva, va_next));
6398 MPASS(pmap != kernel_pmap); /* XXXKIB */
6399 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6402 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6403 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6404 pmap_unwire_ptp(pmap, sva, mt, &free);
6409 * Calculate index for next page table.
6411 va_next = (sva + NBPDR) & ~PDRMASK;
6415 pde = pmap_pdpe_to_pde(pdpe, sva);
6419 * Weed out invalid mappings.
6425 * Check for large page.
6427 if ((ptpaddr & PG_PS) != 0) {
6429 * Are we removing the entire large page? If not,
6430 * demote the mapping and fall through.
6432 if (sva + NBPDR == va_next && eva >= va_next) {
6434 * The TLB entry for a PG_G mapping is
6435 * invalidated by pmap_remove_pde().
6437 if ((ptpaddr & PG_G) == 0)
6439 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6441 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6443 /* The large page mapping was destroyed. */
6450 * Limit our scan to either the end of the va represented
6451 * by the current page table page, or to the end of the
6452 * range being removed.
6457 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6464 pmap_invalidate_all(pmap);
6466 pmap_delayed_invl_finish();
6467 vm_page_free_pages_toq(&free, true);
6471 * Remove the given range of addresses from the specified map.
6473 * It is assumed that the start and end are properly
6474 * rounded to the page size.
6477 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6479 pmap_remove1(pmap, sva, eva, false);
6483 * Remove the given range of addresses as part of a logical unmap
6484 * operation. This has the effect of calling pmap_remove(), but
6485 * also clears any metadata that should persist for the lifetime
6486 * of a logical mapping.
6489 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6491 pmap_remove1(pmap, sva, eva, true);
6495 * Routine: pmap_remove_all
6497 * Removes this physical page from
6498 * all physical maps in which it resides.
6499 * Reflects back modify bits to the pager.
6502 * Original versions of this routine were very
6503 * inefficient because they iteratively called
6504 * pmap_remove (slow...)
6508 pmap_remove_all(vm_page_t m)
6510 struct md_page *pvh;
6513 struct rwlock *lock;
6514 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6517 struct spglist free;
6518 int pvh_gen, md_gen;
6520 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6521 ("pmap_remove_all: page %p is not managed", m));
6523 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6524 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6525 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6528 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6530 if (!PMAP_TRYLOCK(pmap)) {
6531 pvh_gen = pvh->pv_gen;
6535 if (pvh_gen != pvh->pv_gen) {
6541 pde = pmap_pde(pmap, va);
6542 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6545 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6547 if (!PMAP_TRYLOCK(pmap)) {
6548 pvh_gen = pvh->pv_gen;
6549 md_gen = m->md.pv_gen;
6553 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6558 PG_A = pmap_accessed_bit(pmap);
6559 PG_M = pmap_modified_bit(pmap);
6560 PG_RW = pmap_rw_bit(pmap);
6561 pmap_resident_count_adj(pmap, -1);
6562 pde = pmap_pde(pmap, pv->pv_va);
6563 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6564 " a 2mpage in page %p's pv list", m));
6565 pte = pmap_pde_to_pte(pde, pv->pv_va);
6566 tpte = pte_load_clear(pte);
6568 pmap->pm_stats.wired_count--;
6570 vm_page_aflag_set(m, PGA_REFERENCED);
6573 * Update the vm_page_t clean and reference bits.
6575 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6577 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6578 pmap_invalidate_page(pmap, pv->pv_va);
6579 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6581 free_pv_entry(pmap, pv);
6584 vm_page_aflag_clear(m, PGA_WRITEABLE);
6586 pmap_delayed_invl_wait(m);
6587 vm_page_free_pages_toq(&free, true);
6591 * pmap_protect_pde: do the things to protect a 2mpage in a process
6594 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6596 pd_entry_t newpde, oldpde;
6598 boolean_t anychanged;
6599 pt_entry_t PG_G, PG_M, PG_RW;
6601 PG_G = pmap_global_bit(pmap);
6602 PG_M = pmap_modified_bit(pmap);
6603 PG_RW = pmap_rw_bit(pmap);
6605 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6606 KASSERT((sva & PDRMASK) == 0,
6607 ("pmap_protect_pde: sva is not 2mpage aligned"));
6610 oldpde = newpde = *pde;
6611 if ((prot & VM_PROT_WRITE) == 0) {
6612 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6613 (PG_MANAGED | PG_M | PG_RW)) {
6614 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6615 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6618 newpde &= ~(PG_RW | PG_M);
6620 if ((prot & VM_PROT_EXECUTE) == 0)
6622 if (newpde != oldpde) {
6624 * As an optimization to future operations on this PDE, clear
6625 * PG_PROMOTED. The impending invalidation will remove any
6626 * lingering 4KB page mappings from the TLB.
6628 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6630 if ((oldpde & PG_G) != 0)
6631 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6635 return (anychanged);
6639 * Set the physical protection on the
6640 * specified range of this map as requested.
6643 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6646 vm_offset_t va_next;
6647 pml4_entry_t *pml4e;
6649 pd_entry_t ptpaddr, *pde;
6650 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6651 pt_entry_t obits, pbits;
6652 boolean_t anychanged;
6654 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6655 if (prot == VM_PROT_NONE) {
6656 pmap_remove(pmap, sva, eva);
6660 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6661 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6664 PG_G = pmap_global_bit(pmap);
6665 PG_M = pmap_modified_bit(pmap);
6666 PG_V = pmap_valid_bit(pmap);
6667 PG_RW = pmap_rw_bit(pmap);
6671 * Although this function delays and batches the invalidation
6672 * of stale TLB entries, it does not need to call
6673 * pmap_delayed_invl_start() and
6674 * pmap_delayed_invl_finish(), because it does not
6675 * ordinarily destroy mappings. Stale TLB entries from
6676 * protection-only changes need only be invalidated before the
6677 * pmap lock is released, because protection-only changes do
6678 * not destroy PV entries. Even operations that iterate over
6679 * a physical page's PV list of mappings, like
6680 * pmap_remove_write(), acquire the pmap lock for each
6681 * mapping. Consequently, for protection-only changes, the
6682 * pmap lock suffices to synchronize both page table and TLB
6685 * This function only destroys a mapping if pmap_demote_pde()
6686 * fails. In that case, stale TLB entries are immediately
6691 for (; sva < eva; sva = va_next) {
6692 pml4e = pmap_pml4e(pmap, sva);
6693 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6694 va_next = (sva + NBPML4) & ~PML4MASK;
6700 va_next = (sva + NBPDP) & ~PDPMASK;
6703 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6704 if ((*pdpe & PG_V) == 0)
6706 if ((*pdpe & PG_PS) != 0) {
6707 KASSERT(va_next <= eva,
6708 ("partial update of non-transparent 1G mapping "
6709 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6710 *pdpe, sva, eva, va_next));
6712 obits = pbits = *pdpe;
6713 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6714 MPASS(pmap != kernel_pmap); /* XXXKIB */
6715 if ((prot & VM_PROT_WRITE) == 0)
6716 pbits &= ~(PG_RW | PG_M);
6717 if ((prot & VM_PROT_EXECUTE) == 0)
6720 if (pbits != obits) {
6721 if (!atomic_cmpset_long(pdpe, obits, pbits))
6722 /* PG_PS cannot be cleared under us, */
6729 va_next = (sva + NBPDR) & ~PDRMASK;
6733 pde = pmap_pdpe_to_pde(pdpe, sva);
6737 * Weed out invalid mappings.
6743 * Check for large page.
6745 if ((ptpaddr & PG_PS) != 0) {
6747 * Are we protecting the entire large page? If not,
6748 * demote the mapping and fall through.
6750 if (sva + NBPDR == va_next && eva >= va_next) {
6752 * The TLB entry for a PG_G mapping is
6753 * invalidated by pmap_protect_pde().
6755 if (pmap_protect_pde(pmap, pde, sva, prot))
6758 } else if (!pmap_demote_pde(pmap, pde, sva)) {
6760 * The large page mapping was destroyed.
6769 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6772 obits = pbits = *pte;
6773 if ((pbits & PG_V) == 0)
6776 if ((prot & VM_PROT_WRITE) == 0) {
6777 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6778 (PG_MANAGED | PG_M | PG_RW)) {
6779 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6782 pbits &= ~(PG_RW | PG_M);
6784 if ((prot & VM_PROT_EXECUTE) == 0)
6787 if (pbits != obits) {
6788 if (!atomic_cmpset_long(pte, obits, pbits))
6791 pmap_invalidate_page(pmap, sva);
6798 pmap_invalidate_all(pmap);
6802 #if VM_NRESERVLEVEL > 0
6804 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6807 if (pmap->pm_type != PT_EPT)
6809 return ((pde & EPT_PG_EXECUTE) != 0);
6813 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6814 * single page table page (PTP) to a single 2MB page mapping. For promotion
6815 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6816 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6817 * identical characteristics.
6820 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6821 struct rwlock **lockp)
6824 pt_entry_t *firstpte, oldpte, pa, *pte;
6825 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V, PG_PKU_MASK;
6828 PG_A = pmap_accessed_bit(pmap);
6829 PG_G = pmap_global_bit(pmap);
6830 PG_M = pmap_modified_bit(pmap);
6831 PG_V = pmap_valid_bit(pmap);
6832 PG_RW = pmap_rw_bit(pmap);
6833 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6834 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
6836 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6839 * Examine the first PTE in the specified PTP. Abort if this PTE is
6840 * ineligible for promotion due to hardware errata, invalid, or does
6841 * not map the first 4KB physical page within a 2MB page.
6843 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6845 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6847 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6848 counter_u64_add(pmap_pde_p_failures, 1);
6849 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6850 " in pmap %p", va, pmap);
6855 * Both here and in the below "for" loop, to allow for repromotion
6856 * after MADV_FREE, conditionally write protect a clean PTE before
6857 * possibly aborting the promotion due to other PTE attributes. Why?
6858 * Suppose that MADV_FREE is applied to a part of a superpage, the
6859 * address range [S, E). pmap_advise() will demote the superpage
6860 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6861 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6862 * imagine that the memory in [S, E) is recycled, but the last 4KB
6863 * page in [S, E) is not the last to be rewritten, or simply accessed.
6864 * In other words, there is still a 4KB page in [S, E), call it P,
6865 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6866 * we write protect P before aborting the promotion, if and when P is
6867 * finally rewritten, there won't be a page fault to trigger
6871 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6873 * When PG_M is already clear, PG_RW can be cleared without
6874 * a TLB invalidation.
6876 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6880 if ((newpde & PG_A) == 0) {
6881 counter_u64_add(pmap_pde_p_failures, 1);
6882 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6883 " in pmap %p", va, pmap);
6888 * Examine each of the other PTEs in the specified PTP. Abort if this
6889 * PTE maps an unexpected 4KB physical page or does not have identical
6890 * characteristics to the first PTE.
6892 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6893 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6895 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6896 counter_u64_add(pmap_pde_p_failures, 1);
6897 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6898 " in pmap %p", va, pmap);
6902 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6904 * When PG_M is already clear, PG_RW can be cleared
6905 * without a TLB invalidation.
6907 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6910 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6911 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6912 (va & ~PDRMASK), pmap);
6914 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6915 counter_u64_add(pmap_pde_p_failures, 1);
6916 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6917 " in pmap %p", va, pmap);
6924 * Save the page table page in its current state until the PDE
6925 * mapping the superpage is demoted by pmap_demote_pde() or
6926 * destroyed by pmap_remove_pde().
6929 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
6930 KASSERT(mpte >= vm_page_array &&
6931 mpte < &vm_page_array[vm_page_array_size],
6932 ("pmap_promote_pde: page table page is out of range"));
6933 KASSERT(mpte->pindex == pmap_pde_pindex(va),
6934 ("pmap_promote_pde: page table page's pindex is wrong "
6935 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
6936 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
6937 if (pmap_insert_pt_page(pmap, mpte, true)) {
6938 counter_u64_add(pmap_pde_p_failures, 1);
6940 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
6946 * Promote the pv entries.
6948 if ((newpde & PG_MANAGED) != 0)
6949 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
6952 * Propagate the PAT index to its proper position.
6954 newpde = pmap_swap_pat(pmap, newpde);
6957 * Map the superpage.
6959 if (workaround_erratum383)
6960 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
6962 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
6964 counter_u64_add(pmap_pde_promotions, 1);
6965 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
6966 " in pmap %p", va, pmap);
6968 #endif /* VM_NRESERVLEVEL > 0 */
6971 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
6975 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
6977 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6978 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
6979 ("psind %d unexpected", psind));
6980 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
6981 ("unaligned phys address %#lx newpte %#lx psind %d",
6982 newpte & PG_FRAME, newpte, psind));
6983 KASSERT((va & (pagesizes[psind] - 1)) == 0,
6984 ("unaligned va %#lx psind %d", va, psind));
6985 KASSERT(va < VM_MAXUSER_ADDRESS,
6986 ("kernel mode non-transparent superpage")); /* XXXKIB */
6987 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
6988 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
6990 PG_V = pmap_valid_bit(pmap);
6993 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind]))
6994 return (KERN_PROTECTION_FAILURE);
6996 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
6997 pten |= pmap_pkru_get(pmap, va);
6999 if (psind == 2) { /* 1G */
7000 pml4e = pmap_pml4e(pmap, va);
7001 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7002 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7006 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7007 pdpe = &pdpe[pmap_pdpe_index(va)];
7009 MPASS(origpte == 0);
7011 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7012 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7014 if ((origpte & PG_V) == 0) {
7015 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7020 } else /* (psind == 1) */ { /* 2M */
7021 pde = pmap_pde(pmap, va);
7023 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7027 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7028 pde = &pde[pmap_pde_index(va)];
7030 MPASS(origpte == 0);
7033 if ((origpte & PG_V) == 0) {
7034 pdpe = pmap_pdpe(pmap, va);
7035 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7036 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7042 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7043 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7044 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7045 va, psind == 2 ? "1G" : "2M", origpte, pten));
7046 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7047 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7048 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7049 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7050 if ((origpte & PG_V) == 0)
7051 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7053 return (KERN_SUCCESS);
7056 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7057 return (KERN_RESOURCE_SHORTAGE);
7065 * Insert the given physical page (p) at
7066 * the specified virtual address (v) in the
7067 * target physical map with the protection requested.
7069 * If specified, the page will be wired down, meaning
7070 * that the related pte can not be reclaimed.
7072 * NB: This is the only routine which MAY NOT lazy-evaluate
7073 * or lose information. That is, this routine must actually
7074 * insert this page into the given map NOW.
7076 * When destroying both a page table and PV entry, this function
7077 * performs the TLB invalidation before releasing the PV list
7078 * lock, so we do not need pmap_delayed_invl_page() calls here.
7081 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7082 u_int flags, int8_t psind)
7084 struct rwlock *lock;
7086 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7087 pt_entry_t newpte, origpte;
7094 PG_A = pmap_accessed_bit(pmap);
7095 PG_G = pmap_global_bit(pmap);
7096 PG_M = pmap_modified_bit(pmap);
7097 PG_V = pmap_valid_bit(pmap);
7098 PG_RW = pmap_rw_bit(pmap);
7100 va = trunc_page(va);
7101 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7102 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7103 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7105 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7106 ("pmap_enter: managed mapping within the clean submap"));
7107 if ((m->oflags & VPO_UNMANAGED) == 0)
7108 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7109 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7110 ("pmap_enter: flags %u has reserved bits set", flags));
7111 pa = VM_PAGE_TO_PHYS(m);
7112 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7113 if ((flags & VM_PROT_WRITE) != 0)
7115 if ((prot & VM_PROT_WRITE) != 0)
7117 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7118 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7119 if ((prot & VM_PROT_EXECUTE) == 0)
7121 if ((flags & PMAP_ENTER_WIRED) != 0)
7123 if (va < VM_MAXUSER_ADDRESS)
7125 if (pmap == kernel_pmap)
7127 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7130 * Set modified bit gratuitously for writeable mappings if
7131 * the page is unmanaged. We do not want to take a fault
7132 * to do the dirty bit accounting for these mappings.
7134 if ((m->oflags & VPO_UNMANAGED) != 0) {
7135 if ((newpte & PG_RW) != 0)
7138 newpte |= PG_MANAGED;
7142 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7143 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7144 ("managed largepage va %#lx flags %#x", va, flags));
7145 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7150 /* Assert the required virtual and physical alignment. */
7151 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7152 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7153 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7159 * In the case that a page table page is not
7160 * resident, we are creating it here.
7163 pde = pmap_pde(pmap, va);
7164 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7165 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7166 pte = pmap_pde_to_pte(pde, va);
7167 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7168 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7171 } else if (va < VM_MAXUSER_ADDRESS) {
7173 * Here if the pte page isn't mapped, or if it has been
7176 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7177 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7178 nosleep ? NULL : &lock, va);
7179 if (mpte == NULL && nosleep) {
7180 rv = KERN_RESOURCE_SHORTAGE;
7185 panic("pmap_enter: invalid page directory va=%#lx", va);
7189 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7190 newpte |= pmap_pkru_get(pmap, va);
7193 * Is the specified virtual address already mapped?
7195 if ((origpte & PG_V) != 0) {
7197 * Wiring change, just update stats. We don't worry about
7198 * wiring PT pages as they remain resident as long as there
7199 * are valid mappings in them. Hence, if a user page is wired,
7200 * the PT page will be also.
7202 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7203 pmap->pm_stats.wired_count++;
7204 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7205 pmap->pm_stats.wired_count--;
7208 * Remove the extra PT page reference.
7212 KASSERT(mpte->ref_count > 0,
7213 ("pmap_enter: missing reference to page table page,"
7218 * Has the physical page changed?
7220 opa = origpte & PG_FRAME;
7223 * No, might be a protection or wiring change.
7225 if ((origpte & PG_MANAGED) != 0 &&
7226 (newpte & PG_RW) != 0)
7227 vm_page_aflag_set(m, PGA_WRITEABLE);
7228 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7234 * The physical page has changed. Temporarily invalidate
7235 * the mapping. This ensures that all threads sharing the
7236 * pmap keep a consistent view of the mapping, which is
7237 * necessary for the correct handling of COW faults. It
7238 * also permits reuse of the old mapping's PV entry,
7239 * avoiding an allocation.
7241 * For consistency, handle unmanaged mappings the same way.
7243 origpte = pte_load_clear(pte);
7244 KASSERT((origpte & PG_FRAME) == opa,
7245 ("pmap_enter: unexpected pa update for %#lx", va));
7246 if ((origpte & PG_MANAGED) != 0) {
7247 om = PHYS_TO_VM_PAGE(opa);
7250 * The pmap lock is sufficient to synchronize with
7251 * concurrent calls to pmap_page_test_mappings() and
7252 * pmap_ts_referenced().
7254 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7256 if ((origpte & PG_A) != 0) {
7257 pmap_invalidate_page(pmap, va);
7258 vm_page_aflag_set(om, PGA_REFERENCED);
7260 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7261 pv = pmap_pvh_remove(&om->md, pmap, va);
7263 ("pmap_enter: no PV entry for %#lx", va));
7264 if ((newpte & PG_MANAGED) == 0)
7265 free_pv_entry(pmap, pv);
7266 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7267 TAILQ_EMPTY(&om->md.pv_list) &&
7268 ((om->flags & PG_FICTITIOUS) != 0 ||
7269 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7270 vm_page_aflag_clear(om, PGA_WRITEABLE);
7273 * Since this mapping is unmanaged, assume that PG_A
7276 pmap_invalidate_page(pmap, va);
7281 * Increment the counters.
7283 if ((newpte & PG_W) != 0)
7284 pmap->pm_stats.wired_count++;
7285 pmap_resident_count_adj(pmap, 1);
7289 * Enter on the PV list if part of our managed memory.
7291 if ((newpte & PG_MANAGED) != 0) {
7293 pv = get_pv_entry(pmap, &lock);
7296 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7297 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7299 if ((newpte & PG_RW) != 0)
7300 vm_page_aflag_set(m, PGA_WRITEABLE);
7306 if ((origpte & PG_V) != 0) {
7308 origpte = pte_load_store(pte, newpte);
7309 KASSERT((origpte & PG_FRAME) == pa,
7310 ("pmap_enter: unexpected pa update for %#lx", va));
7311 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7313 if ((origpte & PG_MANAGED) != 0)
7317 * Although the PTE may still have PG_RW set, TLB
7318 * invalidation may nonetheless be required because
7319 * the PTE no longer has PG_M set.
7321 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7323 * This PTE change does not require TLB invalidation.
7327 if ((origpte & PG_A) != 0)
7328 pmap_invalidate_page(pmap, va);
7330 pte_store(pte, newpte);
7334 #if VM_NRESERVLEVEL > 0
7336 * If both the page table page and the reservation are fully
7337 * populated, then attempt promotion.
7339 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7340 pmap_ps_enabled(pmap) &&
7341 (m->flags & PG_FICTITIOUS) == 0 &&
7342 vm_reserv_level_iffullpop(m) == 0)
7343 pmap_promote_pde(pmap, pde, va, mpte, &lock);
7355 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7356 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7357 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7358 * "no replace", and "no reclaim" are specified.
7361 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7362 struct rwlock **lockp)
7367 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7368 PG_V = pmap_valid_bit(pmap);
7369 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
7371 if ((m->oflags & VPO_UNMANAGED) == 0)
7372 newpde |= PG_MANAGED;
7373 if ((prot & VM_PROT_EXECUTE) == 0)
7375 if (va < VM_MAXUSER_ADDRESS)
7377 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7378 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7382 * Returns true if every page table entry in the specified page table page is
7386 pmap_every_pte_zero(vm_paddr_t pa)
7388 pt_entry_t *pt_end, *pte;
7390 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7391 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7392 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7400 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7401 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7402 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7403 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7404 * page mapping already exists within the 2MB virtual address range starting
7405 * at the specified virtual address or (2) the requested 2MB page mapping is
7406 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7407 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7408 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7409 * settings are not the same across the 2MB virtual address range starting at
7410 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7411 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7412 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7415 * The parameter "m" is only used when creating a managed, writeable mapping.
7418 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7419 vm_page_t m, struct rwlock **lockp)
7421 struct spglist free;
7422 pd_entry_t oldpde, *pde;
7423 pt_entry_t PG_G, PG_RW, PG_V;
7426 KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
7427 ("pmap_enter_pde: cannot create wired user mapping"));
7428 PG_G = pmap_global_bit(pmap);
7429 PG_RW = pmap_rw_bit(pmap);
7430 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7431 ("pmap_enter_pde: newpde is missing PG_M"));
7432 PG_V = pmap_valid_bit(pmap);
7433 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7435 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7437 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7438 " in pmap %p", va, pmap);
7439 return (KERN_FAILURE);
7441 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7442 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7443 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7444 " in pmap %p", va, pmap);
7445 return (KERN_RESOURCE_SHORTAGE);
7449 * If pkru is not same for the whole pde range, return failure
7450 * and let vm_fault() cope. Check after pde allocation, since
7453 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
7454 pmap_abort_ptp(pmap, va, pdpg);
7455 return (KERN_PROTECTION_FAILURE);
7457 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
7458 newpde &= ~X86_PG_PKU_MASK;
7459 newpde |= pmap_pkru_get(pmap, va);
7463 * If there are existing mappings, either abort or remove them.
7466 if ((oldpde & PG_V) != 0) {
7467 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7468 ("pmap_enter_pde: pdpg's reference count is too low"));
7469 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7470 if ((oldpde & PG_PS) != 0) {
7474 "pmap_enter_pde: no space for va %#lx"
7475 " in pmap %p", va, pmap);
7476 return (KERN_NO_SPACE);
7477 } else if (va < VM_MAXUSER_ADDRESS ||
7478 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7482 "pmap_enter_pde: failure for va %#lx"
7483 " in pmap %p", va, pmap);
7484 return (KERN_FAILURE);
7487 /* Break the existing mapping(s). */
7489 if ((oldpde & PG_PS) != 0) {
7491 * The reference to the PD page that was acquired by
7492 * pmap_alloc_pde() ensures that it won't be freed.
7493 * However, if the PDE resulted from a promotion, then
7494 * a reserved PT page could be freed.
7496 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7497 if ((oldpde & PG_G) == 0)
7498 pmap_invalidate_pde_page(pmap, va, oldpde);
7500 pmap_delayed_invl_start();
7501 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7503 pmap_invalidate_all(pmap);
7504 pmap_delayed_invl_finish();
7506 if (va < VM_MAXUSER_ADDRESS) {
7507 vm_page_free_pages_toq(&free, true);
7508 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7511 KASSERT(SLIST_EMPTY(&free),
7512 ("pmap_enter_pde: freed kernel page table page"));
7515 * Both pmap_remove_pde() and pmap_remove_ptes() will
7516 * leave the kernel page table page zero filled.
7518 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7519 if (pmap_insert_pt_page(pmap, mt, false))
7520 panic("pmap_enter_pde: trie insert failed");
7524 if ((newpde & PG_MANAGED) != 0) {
7526 * Abort this mapping if its PV entry could not be created.
7528 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7530 pmap_abort_ptp(pmap, va, pdpg);
7531 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7532 " in pmap %p", va, pmap);
7533 return (KERN_RESOURCE_SHORTAGE);
7535 if ((newpde & PG_RW) != 0) {
7536 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7537 vm_page_aflag_set(mt, PGA_WRITEABLE);
7542 * Increment counters.
7544 if ((newpde & PG_W) != 0)
7545 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7546 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7549 * Map the superpage. (This is not a promoted mapping; there will not
7550 * be any lingering 4KB page mappings in the TLB.)
7552 pde_store(pde, newpde);
7554 counter_u64_add(pmap_pde_mappings, 1);
7555 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7557 return (KERN_SUCCESS);
7561 * Maps a sequence of resident pages belonging to the same object.
7562 * The sequence begins with the given page m_start. This page is
7563 * mapped at the given virtual address start. Each subsequent page is
7564 * mapped at a virtual address that is offset from start by the same
7565 * amount as the page is offset from m_start within the object. The
7566 * last page in the sequence is the page with the largest offset from
7567 * m_start that can be mapped at a virtual address less than the given
7568 * virtual address end. Not every virtual page between start and end
7569 * is mapped; only those for which a resident page exists with the
7570 * corresponding offset from m_start are mapped.
7573 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7574 vm_page_t m_start, vm_prot_t prot)
7576 struct rwlock *lock;
7579 vm_pindex_t diff, psize;
7582 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7584 psize = atop(end - start);
7589 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7590 va = start + ptoa(diff);
7591 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7592 m->psind == 1 && pmap_ps_enabled(pmap) &&
7593 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7594 KERN_SUCCESS || rv == KERN_NO_SPACE))
7595 m = &m[NBPDR / PAGE_SIZE - 1];
7597 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7599 m = TAILQ_NEXT(m, listq);
7607 * this code makes some *MAJOR* assumptions:
7608 * 1. Current pmap & pmap exists.
7611 * 4. No page table pages.
7612 * but is *MUCH* faster than pmap_enter...
7616 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7618 struct rwlock *lock;
7622 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7629 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7630 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7632 pt_entry_t newpte, *pte, PG_V;
7634 KASSERT(!VA_IS_CLEANMAP(va) ||
7635 (m->oflags & VPO_UNMANAGED) != 0,
7636 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7637 PG_V = pmap_valid_bit(pmap);
7638 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7641 * In the case that a page table page is not
7642 * resident, we are creating it here.
7644 if (va < VM_MAXUSER_ADDRESS) {
7647 vm_pindex_t ptepindex;
7650 * Calculate pagetable page index
7652 ptepindex = pmap_pde_pindex(va);
7653 if (mpte && (mpte->pindex == ptepindex)) {
7657 * If the page table page is mapped, we just increment
7658 * the hold count, and activate it. Otherwise, we
7659 * attempt to allocate a page table page, passing NULL
7660 * instead of the PV list lock pointer because we don't
7661 * intend to sleep. If this attempt fails, we don't
7662 * retry. Instead, we give up.
7664 pdpe = pmap_pdpe(pmap, va);
7665 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7666 if ((*pdpe & PG_PS) != 0)
7668 pde = pmap_pdpe_to_pde(pdpe, va);
7669 if ((*pde & PG_V) != 0) {
7670 if ((*pde & PG_PS) != 0)
7672 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7675 mpte = pmap_allocpte_alloc(pmap,
7676 ptepindex, NULL, va);
7681 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7687 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7688 pte = &pte[pmap_pte_index(va)];
7700 * Enter on the PV list if part of our managed memory.
7702 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7703 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7705 pmap_abort_ptp(pmap, va, mpte);
7710 * Increment counters
7712 pmap_resident_count_adj(pmap, 1);
7714 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7715 pmap_cache_bits(pmap, m->md.pat_mode, 0);
7716 if ((m->oflags & VPO_UNMANAGED) == 0)
7717 newpte |= PG_MANAGED;
7718 if ((prot & VM_PROT_EXECUTE) == 0)
7720 if (va < VM_MAXUSER_ADDRESS)
7721 newpte |= PG_U | pmap_pkru_get(pmap, va);
7722 pte_store(pte, newpte);
7727 * Make a temporary mapping for a physical address. This is only intended
7728 * to be used for panic dumps.
7731 pmap_kenter_temporary(vm_paddr_t pa, int i)
7735 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7736 pmap_kenter(va, pa);
7737 pmap_invlpg(kernel_pmap, va);
7738 return ((void *)crashdumpmap);
7742 * This code maps large physical mmap regions into the
7743 * processor address space. Note that some shortcuts
7744 * are taken, but the code works.
7747 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7748 vm_pindex_t pindex, vm_size_t size)
7751 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7752 vm_paddr_t pa, ptepa;
7756 PG_A = pmap_accessed_bit(pmap);
7757 PG_M = pmap_modified_bit(pmap);
7758 PG_V = pmap_valid_bit(pmap);
7759 PG_RW = pmap_rw_bit(pmap);
7761 VM_OBJECT_ASSERT_WLOCKED(object);
7762 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7763 ("pmap_object_init_pt: non-device object"));
7764 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7765 if (!pmap_ps_enabled(pmap))
7767 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7769 p = vm_page_lookup(object, pindex);
7770 KASSERT(vm_page_all_valid(p),
7771 ("pmap_object_init_pt: invalid page %p", p));
7772 pat_mode = p->md.pat_mode;
7775 * Abort the mapping if the first page is not physically
7776 * aligned to a 2MB page boundary.
7778 ptepa = VM_PAGE_TO_PHYS(p);
7779 if (ptepa & (NBPDR - 1))
7783 * Skip the first page. Abort the mapping if the rest of
7784 * the pages are not physically contiguous or have differing
7785 * memory attributes.
7787 p = TAILQ_NEXT(p, listq);
7788 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7790 KASSERT(vm_page_all_valid(p),
7791 ("pmap_object_init_pt: invalid page %p", p));
7792 if (pa != VM_PAGE_TO_PHYS(p) ||
7793 pat_mode != p->md.pat_mode)
7795 p = TAILQ_NEXT(p, listq);
7799 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7800 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7801 * will not affect the termination of this loop.
7804 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
7805 pa < ptepa + size; pa += NBPDR) {
7806 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7809 * The creation of mappings below is only an
7810 * optimization. If a page directory page
7811 * cannot be allocated without blocking,
7812 * continue on to the next mapping rather than
7818 if ((*pde & PG_V) == 0) {
7819 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7820 PG_U | PG_RW | PG_V);
7821 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7822 counter_u64_add(pmap_pde_mappings, 1);
7824 /* Continue on if the PDE is already valid. */
7826 KASSERT(pdpg->ref_count > 0,
7827 ("pmap_object_init_pt: missing reference "
7828 "to page directory page, va: 0x%lx", addr));
7837 * Clear the wired attribute from the mappings for the specified range of
7838 * addresses in the given pmap. Every valid mapping within that range
7839 * must have the wired attribute set. In contrast, invalid mappings
7840 * cannot have the wired attribute set, so they are ignored.
7842 * The wired attribute of the page table entry is not a hardware
7843 * feature, so there is no need to invalidate any TLB entries.
7844 * Since pmap_demote_pde() for the wired entry must never fail,
7845 * pmap_delayed_invl_start()/finish() calls around the
7846 * function are not needed.
7849 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7851 vm_offset_t va_next;
7852 pml4_entry_t *pml4e;
7855 pt_entry_t *pte, PG_V, PG_G __diagused;
7857 PG_V = pmap_valid_bit(pmap);
7858 PG_G = pmap_global_bit(pmap);
7860 for (; sva < eva; sva = va_next) {
7861 pml4e = pmap_pml4e(pmap, sva);
7862 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7863 va_next = (sva + NBPML4) & ~PML4MASK;
7869 va_next = (sva + NBPDP) & ~PDPMASK;
7872 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7873 if ((*pdpe & PG_V) == 0)
7875 if ((*pdpe & PG_PS) != 0) {
7876 KASSERT(va_next <= eva,
7877 ("partial update of non-transparent 1G mapping "
7878 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
7879 *pdpe, sva, eva, va_next));
7880 MPASS(pmap != kernel_pmap); /* XXXKIB */
7881 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
7882 atomic_clear_long(pdpe, PG_W);
7883 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
7887 va_next = (sva + NBPDR) & ~PDRMASK;
7890 pde = pmap_pdpe_to_pde(pdpe, sva);
7891 if ((*pde & PG_V) == 0)
7893 if ((*pde & PG_PS) != 0) {
7894 if ((*pde & PG_W) == 0)
7895 panic("pmap_unwire: pde %#jx is missing PG_W",
7899 * Are we unwiring the entire large page? If not,
7900 * demote the mapping and fall through.
7902 if (sva + NBPDR == va_next && eva >= va_next) {
7903 atomic_clear_long(pde, PG_W);
7904 pmap->pm_stats.wired_count -= NBPDR /
7907 } else if (!pmap_demote_pde(pmap, pde, sva))
7908 panic("pmap_unwire: demotion failed");
7912 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
7914 if ((*pte & PG_V) == 0)
7916 if ((*pte & PG_W) == 0)
7917 panic("pmap_unwire: pte %#jx is missing PG_W",
7921 * PG_W must be cleared atomically. Although the pmap
7922 * lock synchronizes access to PG_W, another processor
7923 * could be setting PG_M and/or PG_A concurrently.
7925 atomic_clear_long(pte, PG_W);
7926 pmap->pm_stats.wired_count--;
7933 * Copy the range specified by src_addr/len
7934 * from the source map to the range dst_addr/len
7935 * in the destination map.
7937 * This routine is only advisory and need not do anything.
7940 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
7941 vm_offset_t src_addr)
7943 struct rwlock *lock;
7944 pml4_entry_t *pml4e;
7946 pd_entry_t *pde, srcptepaddr;
7947 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
7948 vm_offset_t addr, end_addr, va_next;
7949 vm_page_t dst_pdpg, dstmpte, srcmpte;
7951 if (dst_addr != src_addr)
7954 if (dst_pmap->pm_type != src_pmap->pm_type)
7958 * EPT page table entries that require emulation of A/D bits are
7959 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
7960 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
7961 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
7962 * implementations flag an EPT misconfiguration for exec-only
7963 * mappings we skip this function entirely for emulated pmaps.
7965 if (pmap_emulate_ad_bits(dst_pmap))
7968 end_addr = src_addr + len;
7970 if (dst_pmap < src_pmap) {
7971 PMAP_LOCK(dst_pmap);
7972 PMAP_LOCK(src_pmap);
7974 PMAP_LOCK(src_pmap);
7975 PMAP_LOCK(dst_pmap);
7978 PG_A = pmap_accessed_bit(dst_pmap);
7979 PG_M = pmap_modified_bit(dst_pmap);
7980 PG_V = pmap_valid_bit(dst_pmap);
7982 for (addr = src_addr; addr < end_addr; addr = va_next) {
7983 KASSERT(addr < UPT_MIN_ADDRESS,
7984 ("pmap_copy: invalid to pmap_copy page tables"));
7986 pml4e = pmap_pml4e(src_pmap, addr);
7987 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7988 va_next = (addr + NBPML4) & ~PML4MASK;
7994 va_next = (addr + NBPDP) & ~PDPMASK;
7997 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
7998 if ((*pdpe & PG_V) == 0)
8000 if ((*pdpe & PG_PS) != 0) {
8001 KASSERT(va_next <= end_addr,
8002 ("partial update of non-transparent 1G mapping "
8003 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8004 *pdpe, addr, end_addr, va_next));
8005 MPASS((addr & PDPMASK) == 0);
8006 MPASS((*pdpe & PG_MANAGED) == 0);
8007 srcptepaddr = *pdpe;
8008 pdpe = pmap_pdpe(dst_pmap, addr);
8010 if (pmap_allocpte_alloc(dst_pmap,
8011 pmap_pml4e_pindex(addr), NULL, addr) ==
8014 pdpe = pmap_pdpe(dst_pmap, addr);
8016 pml4e = pmap_pml4e(dst_pmap, addr);
8017 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8018 dst_pdpg->ref_count++;
8021 ("1G mapping present in dst pmap "
8022 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8023 *pdpe, addr, end_addr, va_next));
8024 *pdpe = srcptepaddr & ~PG_W;
8025 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8029 va_next = (addr + NBPDR) & ~PDRMASK;
8033 pde = pmap_pdpe_to_pde(pdpe, addr);
8035 if (srcptepaddr == 0)
8038 if (srcptepaddr & PG_PS) {
8040 * We can only virtual copy whole superpages.
8042 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8044 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8047 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8048 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8049 PMAP_ENTER_NORECLAIM, &lock))) {
8051 * We leave the dirty bit unchanged because
8052 * managed read/write superpage mappings are
8053 * required to be dirty. However, managed
8054 * superpage mappings are not required to
8055 * have their accessed bit set, so we clear
8056 * it because we don't know if this mapping
8059 srcptepaddr &= ~PG_W;
8060 if ((srcptepaddr & PG_MANAGED) != 0)
8061 srcptepaddr &= ~PG_A;
8063 pmap_resident_count_adj(dst_pmap, NBPDR /
8065 counter_u64_add(pmap_pde_mappings, 1);
8067 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8071 srcptepaddr &= PG_FRAME;
8072 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8073 KASSERT(srcmpte->ref_count > 0,
8074 ("pmap_copy: source page table page is unused"));
8076 if (va_next > end_addr)
8079 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8080 src_pte = &src_pte[pmap_pte_index(addr)];
8082 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8086 * We only virtual copy managed pages.
8088 if ((ptetemp & PG_MANAGED) == 0)
8091 if (dstmpte != NULL) {
8092 KASSERT(dstmpte->pindex ==
8093 pmap_pde_pindex(addr),
8094 ("dstmpte pindex/addr mismatch"));
8095 dstmpte->ref_count++;
8096 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8099 dst_pte = (pt_entry_t *)
8100 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8101 dst_pte = &dst_pte[pmap_pte_index(addr)];
8102 if (*dst_pte == 0 &&
8103 pmap_try_insert_pv_entry(dst_pmap, addr,
8104 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8106 * Clear the wired, modified, and accessed
8107 * (referenced) bits during the copy.
8109 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8110 pmap_resident_count_adj(dst_pmap, 1);
8112 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8115 /* Have we copied all of the valid mappings? */
8116 if (dstmpte->ref_count >= srcmpte->ref_count)
8123 PMAP_UNLOCK(src_pmap);
8124 PMAP_UNLOCK(dst_pmap);
8128 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8132 if (dst_pmap->pm_type != src_pmap->pm_type ||
8133 dst_pmap->pm_type != PT_X86 ||
8134 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8137 if (dst_pmap < src_pmap) {
8138 PMAP_LOCK(dst_pmap);
8139 PMAP_LOCK(src_pmap);
8141 PMAP_LOCK(src_pmap);
8142 PMAP_LOCK(dst_pmap);
8144 error = pmap_pkru_copy(dst_pmap, src_pmap);
8145 /* Clean up partial copy on failure due to no memory. */
8146 if (error == ENOMEM)
8147 pmap_pkru_deassign_all(dst_pmap);
8148 PMAP_UNLOCK(src_pmap);
8149 PMAP_UNLOCK(dst_pmap);
8150 if (error != ENOMEM)
8158 * Zero the specified hardware page.
8161 pmap_zero_page(vm_page_t m)
8165 #ifdef TSLOG_PAGEZERO
8168 va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8169 pagezero((void *)va);
8170 #ifdef TSLOG_PAGEZERO
8176 * Zero an area within a single hardware page. off and size must not
8177 * cover an area beyond a single hardware page.
8180 pmap_zero_page_area(vm_page_t m, int off, int size)
8182 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8184 if (off == 0 && size == PAGE_SIZE)
8185 pagezero((void *)va);
8187 bzero((char *)va + off, size);
8191 * Copy 1 specified hardware page to another.
8194 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8196 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8197 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8199 pagecopy((void *)src, (void *)dst);
8202 int unmapped_buf_allowed = 1;
8205 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8206 vm_offset_t b_offset, int xfersize)
8210 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8214 while (xfersize > 0) {
8215 a_pg_offset = a_offset & PAGE_MASK;
8216 pages[0] = ma[a_offset >> PAGE_SHIFT];
8217 b_pg_offset = b_offset & PAGE_MASK;
8218 pages[1] = mb[b_offset >> PAGE_SHIFT];
8219 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8220 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8221 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
8222 a_cp = (char *)vaddr[0] + a_pg_offset;
8223 b_cp = (char *)vaddr[1] + b_pg_offset;
8224 bcopy(a_cp, b_cp, cnt);
8225 if (__predict_false(mapped))
8226 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
8234 * Returns true if the pmap's pv is one of the first
8235 * 16 pvs linked to from this page. This count may
8236 * be changed upwards or downwards in the future; it
8237 * is only necessary that true be returned for a small
8238 * subset of pmaps for proper page aging.
8241 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8243 struct md_page *pvh;
8244 struct rwlock *lock;
8249 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8250 ("pmap_page_exists_quick: page %p is not managed", m));
8252 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8254 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8255 if (PV_PMAP(pv) == pmap) {
8263 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8264 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8265 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8266 if (PV_PMAP(pv) == pmap) {
8280 * pmap_page_wired_mappings:
8282 * Return the number of managed mappings to the given physical page
8286 pmap_page_wired_mappings(vm_page_t m)
8288 struct rwlock *lock;
8289 struct md_page *pvh;
8293 int count, md_gen, pvh_gen;
8295 if ((m->oflags & VPO_UNMANAGED) != 0)
8297 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8301 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8303 if (!PMAP_TRYLOCK(pmap)) {
8304 md_gen = m->md.pv_gen;
8308 if (md_gen != m->md.pv_gen) {
8313 pte = pmap_pte(pmap, pv->pv_va);
8314 if ((*pte & PG_W) != 0)
8318 if ((m->flags & PG_FICTITIOUS) == 0) {
8319 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8320 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8322 if (!PMAP_TRYLOCK(pmap)) {
8323 md_gen = m->md.pv_gen;
8324 pvh_gen = pvh->pv_gen;
8328 if (md_gen != m->md.pv_gen ||
8329 pvh_gen != pvh->pv_gen) {
8334 pte = pmap_pde(pmap, pv->pv_va);
8335 if ((*pte & PG_W) != 0)
8345 * Returns TRUE if the given page is mapped individually or as part of
8346 * a 2mpage. Otherwise, returns FALSE.
8349 pmap_page_is_mapped(vm_page_t m)
8351 struct rwlock *lock;
8354 if ((m->oflags & VPO_UNMANAGED) != 0)
8356 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8358 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8359 ((m->flags & PG_FICTITIOUS) == 0 &&
8360 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8366 * Destroy all managed, non-wired mappings in the given user-space
8367 * pmap. This pmap cannot be active on any processor besides the
8370 * This function cannot be applied to the kernel pmap. Moreover, it
8371 * is not intended for general use. It is only to be used during
8372 * process termination. Consequently, it can be implemented in ways
8373 * that make it faster than pmap_remove(). First, it can more quickly
8374 * destroy mappings by iterating over the pmap's collection of PV
8375 * entries, rather than searching the page table. Second, it doesn't
8376 * have to test and clear the page table entries atomically, because
8377 * no processor is currently accessing the user address space. In
8378 * particular, a page table entry's dirty bit won't change state once
8379 * this function starts.
8381 * Although this function destroys all of the pmap's managed,
8382 * non-wired mappings, it can delay and batch the invalidation of TLB
8383 * entries without calling pmap_delayed_invl_start() and
8384 * pmap_delayed_invl_finish(). Because the pmap is not active on
8385 * any other processor, none of these TLB entries will ever be used
8386 * before their eventual invalidation. Consequently, there is no need
8387 * for either pmap_remove_all() or pmap_remove_write() to wait for
8388 * that eventual TLB invalidation.
8391 pmap_remove_pages(pmap_t pmap)
8394 pt_entry_t *pte, tpte;
8395 pt_entry_t PG_M, PG_RW, PG_V;
8396 struct spglist free;
8397 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8398 vm_page_t m, mpte, mt;
8400 struct md_page *pvh;
8401 struct pv_chunk *pc, *npc;
8402 struct rwlock *lock;
8404 uint64_t inuse, bitmask;
8405 int allfree, field, i, idx;
8409 boolean_t superpage;
8413 * Assert that the given pmap is only active on the current
8414 * CPU. Unfortunately, we cannot block another CPU from
8415 * activating the pmap while this function is executing.
8417 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8420 cpuset_t other_cpus;
8422 other_cpus = all_cpus;
8424 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8425 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8427 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8432 PG_M = pmap_modified_bit(pmap);
8433 PG_V = pmap_valid_bit(pmap);
8434 PG_RW = pmap_rw_bit(pmap);
8436 for (i = 0; i < PMAP_MEMDOM; i++)
8437 TAILQ_INIT(&free_chunks[i]);
8440 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8445 for (field = 0; field < _NPCM; field++) {
8446 inuse = ~pc->pc_map[field] & pc_freemask[field];
8447 while (inuse != 0) {
8449 bitmask = 1UL << bit;
8450 idx = field * 64 + bit;
8451 pv = &pc->pc_pventry[idx];
8454 pte = pmap_pdpe(pmap, pv->pv_va);
8456 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8458 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8461 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8463 pte = &pte[pmap_pte_index(pv->pv_va)];
8467 * Keep track whether 'tpte' is a
8468 * superpage explicitly instead of
8469 * relying on PG_PS being set.
8471 * This is because PG_PS is numerically
8472 * identical to PG_PTE_PAT and thus a
8473 * regular page could be mistaken for
8479 if ((tpte & PG_V) == 0) {
8480 panic("bad pte va %lx pte %lx",
8485 * We cannot remove wired pages from a process' mapping at this time
8493 pc->pc_map[field] |= bitmask;
8496 * Because this pmap is not active on other
8497 * processors, the dirty bit cannot have
8498 * changed state since we last loaded pte.
8503 pa = tpte & PG_PS_FRAME;
8505 pa = tpte & PG_FRAME;
8507 m = PHYS_TO_VM_PAGE(pa);
8508 KASSERT(m->phys_addr == pa,
8509 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8510 m, (uintmax_t)m->phys_addr,
8513 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8514 m < &vm_page_array[vm_page_array_size],
8515 ("pmap_remove_pages: bad tpte %#jx",
8519 * Update the vm_page_t clean/reference bits.
8521 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8523 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8529 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8532 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8533 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8534 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8536 if (TAILQ_EMPTY(&pvh->pv_list)) {
8537 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8538 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8539 TAILQ_EMPTY(&mt->md.pv_list))
8540 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8542 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8544 KASSERT(vm_page_all_valid(mpte),
8545 ("pmap_remove_pages: pte page not promoted"));
8546 pmap_pt_page_count_adj(pmap, -1);
8547 KASSERT(mpte->ref_count == NPTEPG,
8548 ("pmap_remove_pages: pte page reference count error"));
8549 mpte->ref_count = 0;
8550 pmap_add_delayed_free_list(mpte, &free, FALSE);
8553 pmap_resident_count_adj(pmap, -1);
8554 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8556 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8557 TAILQ_EMPTY(&m->md.pv_list) &&
8558 (m->flags & PG_FICTITIOUS) == 0) {
8559 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8560 if (TAILQ_EMPTY(&pvh->pv_list))
8561 vm_page_aflag_clear(m, PGA_WRITEABLE);
8564 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8570 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8571 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8572 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8574 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8575 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8580 pmap_invalidate_all(pmap);
8581 pmap_pkru_deassign_all(pmap);
8582 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8584 vm_page_free_pages_toq(&free, true);
8588 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
8590 struct rwlock *lock;
8592 struct md_page *pvh;
8593 pt_entry_t *pte, mask;
8594 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8596 int md_gen, pvh_gen;
8600 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8603 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8605 if (!PMAP_TRYLOCK(pmap)) {
8606 md_gen = m->md.pv_gen;
8610 if (md_gen != m->md.pv_gen) {
8615 pte = pmap_pte(pmap, pv->pv_va);
8618 PG_M = pmap_modified_bit(pmap);
8619 PG_RW = pmap_rw_bit(pmap);
8620 mask |= PG_RW | PG_M;
8623 PG_A = pmap_accessed_bit(pmap);
8624 PG_V = pmap_valid_bit(pmap);
8625 mask |= PG_V | PG_A;
8627 rv = (*pte & mask) == mask;
8632 if ((m->flags & PG_FICTITIOUS) == 0) {
8633 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8634 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8636 if (!PMAP_TRYLOCK(pmap)) {
8637 md_gen = m->md.pv_gen;
8638 pvh_gen = pvh->pv_gen;
8642 if (md_gen != m->md.pv_gen ||
8643 pvh_gen != pvh->pv_gen) {
8648 pte = pmap_pde(pmap, pv->pv_va);
8651 PG_M = pmap_modified_bit(pmap);
8652 PG_RW = pmap_rw_bit(pmap);
8653 mask |= PG_RW | PG_M;
8656 PG_A = pmap_accessed_bit(pmap);
8657 PG_V = pmap_valid_bit(pmap);
8658 mask |= PG_V | PG_A;
8660 rv = (*pte & mask) == mask;
8674 * Return whether or not the specified physical page was modified
8675 * in any physical maps.
8678 pmap_is_modified(vm_page_t m)
8681 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8682 ("pmap_is_modified: page %p is not managed", m));
8685 * If the page is not busied then this check is racy.
8687 if (!pmap_page_is_write_mapped(m))
8689 return (pmap_page_test_mappings(m, FALSE, TRUE));
8693 * pmap_is_prefaultable:
8695 * Return whether or not the specified virtual address is eligible
8699 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8702 pt_entry_t *pte, PG_V;
8705 PG_V = pmap_valid_bit(pmap);
8708 * Return TRUE if and only if the PTE for the specified virtual
8709 * address is allocated but invalid.
8713 pde = pmap_pde(pmap, addr);
8714 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8715 pte = pmap_pde_to_pte(pde, addr);
8716 rv = (*pte & PG_V) == 0;
8723 * pmap_is_referenced:
8725 * Return whether or not the specified physical page was referenced
8726 * in any physical maps.
8729 pmap_is_referenced(vm_page_t m)
8732 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8733 ("pmap_is_referenced: page %p is not managed", m));
8734 return (pmap_page_test_mappings(m, TRUE, FALSE));
8738 * Clear the write and modified bits in each of the given page's mappings.
8741 pmap_remove_write(vm_page_t m)
8743 struct md_page *pvh;
8745 struct rwlock *lock;
8746 pv_entry_t next_pv, pv;
8748 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8750 int pvh_gen, md_gen;
8752 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8753 ("pmap_remove_write: page %p is not managed", m));
8755 vm_page_assert_busied(m);
8756 if (!pmap_page_is_write_mapped(m))
8759 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8760 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8761 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8764 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8766 if (!PMAP_TRYLOCK(pmap)) {
8767 pvh_gen = pvh->pv_gen;
8771 if (pvh_gen != pvh->pv_gen) {
8776 PG_RW = pmap_rw_bit(pmap);
8778 pde = pmap_pde(pmap, va);
8779 if ((*pde & PG_RW) != 0)
8780 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8781 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8782 ("inconsistent pv lock %p %p for page %p",
8783 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8786 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8788 if (!PMAP_TRYLOCK(pmap)) {
8789 pvh_gen = pvh->pv_gen;
8790 md_gen = m->md.pv_gen;
8794 if (pvh_gen != pvh->pv_gen ||
8795 md_gen != m->md.pv_gen) {
8800 PG_M = pmap_modified_bit(pmap);
8801 PG_RW = pmap_rw_bit(pmap);
8802 pde = pmap_pde(pmap, pv->pv_va);
8803 KASSERT((*pde & PG_PS) == 0,
8804 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8806 pte = pmap_pde_to_pte(pde, pv->pv_va);
8808 if (oldpte & PG_RW) {
8809 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8812 if ((oldpte & PG_M) != 0)
8814 pmap_invalidate_page(pmap, pv->pv_va);
8819 vm_page_aflag_clear(m, PGA_WRITEABLE);
8820 pmap_delayed_invl_wait(m);
8823 static __inline boolean_t
8824 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
8827 if (!pmap_emulate_ad_bits(pmap))
8830 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
8833 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
8834 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
8835 * if the EPT_PG_WRITE bit is set.
8837 if ((pte & EPT_PG_WRITE) != 0)
8841 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
8843 if ((pte & EPT_PG_EXECUTE) == 0 ||
8844 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
8851 * pmap_ts_referenced:
8853 * Return a count of reference bits for a page, clearing those bits.
8854 * It is not necessary for every reference bit to be cleared, but it
8855 * is necessary that 0 only be returned when there are truly no
8856 * reference bits set.
8858 * As an optimization, update the page's dirty field if a modified bit is
8859 * found while counting reference bits. This opportunistic update can be
8860 * performed at low cost and can eliminate the need for some future calls
8861 * to pmap_is_modified(). However, since this function stops after
8862 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8863 * dirty pages. Those dirty pages will only be detected by a future call
8864 * to pmap_is_modified().
8866 * A DI block is not needed within this function, because
8867 * invalidations are performed before the PV list lock is
8871 pmap_ts_referenced(vm_page_t m)
8873 struct md_page *pvh;
8876 struct rwlock *lock;
8877 pd_entry_t oldpde, *pde;
8878 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8881 int cleared, md_gen, not_cleared, pvh_gen;
8882 struct spglist free;
8885 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8886 ("pmap_ts_referenced: page %p is not managed", m));
8889 pa = VM_PAGE_TO_PHYS(m);
8890 lock = PHYS_TO_PV_LIST_LOCK(pa);
8891 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8895 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
8896 goto small_mappings;
8902 if (!PMAP_TRYLOCK(pmap)) {
8903 pvh_gen = pvh->pv_gen;
8907 if (pvh_gen != pvh->pv_gen) {
8912 PG_A = pmap_accessed_bit(pmap);
8913 PG_M = pmap_modified_bit(pmap);
8914 PG_RW = pmap_rw_bit(pmap);
8916 pde = pmap_pde(pmap, pv->pv_va);
8918 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8920 * Although "oldpde" is mapping a 2MB page, because
8921 * this function is called at a 4KB page granularity,
8922 * we only update the 4KB page under test.
8926 if ((oldpde & PG_A) != 0) {
8928 * Since this reference bit is shared by 512 4KB
8929 * pages, it should not be cleared every time it is
8930 * tested. Apply a simple "hash" function on the
8931 * physical page number, the virtual superpage number,
8932 * and the pmap address to select one 4KB page out of
8933 * the 512 on which testing the reference bit will
8934 * result in clearing that reference bit. This
8935 * function is designed to avoid the selection of the
8936 * same 4KB page for every 2MB page mapping.
8938 * On demotion, a mapping that hasn't been referenced
8939 * is simply destroyed. To avoid the possibility of a
8940 * subsequent page fault on a demoted wired mapping,
8941 * always leave its reference bit set. Moreover,
8942 * since the superpage is wired, the current state of
8943 * its reference bit won't affect page replacement.
8945 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
8946 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
8947 (oldpde & PG_W) == 0) {
8948 if (safe_to_clear_referenced(pmap, oldpde)) {
8949 atomic_clear_long(pde, PG_A);
8950 pmap_invalidate_page(pmap, pv->pv_va);
8952 } else if (pmap_demote_pde_locked(pmap, pde,
8953 pv->pv_va, &lock)) {
8955 * Remove the mapping to a single page
8956 * so that a subsequent access may
8957 * repromote. Since the underlying
8958 * page table page is fully populated,
8959 * this removal never frees a page
8963 va += VM_PAGE_TO_PHYS(m) - (oldpde &
8965 pte = pmap_pde_to_pte(pde, va);
8966 pmap_remove_pte(pmap, pte, va, *pde,
8968 pmap_invalidate_page(pmap, va);
8974 * The superpage mapping was removed
8975 * entirely and therefore 'pv' is no
8983 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8984 ("inconsistent pv lock %p %p for page %p",
8985 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8990 /* Rotate the PV list if it has more than one entry. */
8991 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
8992 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8993 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
8996 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
8998 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9000 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9007 if (!PMAP_TRYLOCK(pmap)) {
9008 pvh_gen = pvh->pv_gen;
9009 md_gen = m->md.pv_gen;
9013 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9018 PG_A = pmap_accessed_bit(pmap);
9019 PG_M = pmap_modified_bit(pmap);
9020 PG_RW = pmap_rw_bit(pmap);
9021 pde = pmap_pde(pmap, pv->pv_va);
9022 KASSERT((*pde & PG_PS) == 0,
9023 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9025 pte = pmap_pde_to_pte(pde, pv->pv_va);
9026 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9028 if ((*pte & PG_A) != 0) {
9029 if (safe_to_clear_referenced(pmap, *pte)) {
9030 atomic_clear_long(pte, PG_A);
9031 pmap_invalidate_page(pmap, pv->pv_va);
9033 } else if ((*pte & PG_W) == 0) {
9035 * Wired pages cannot be paged out so
9036 * doing accessed bit emulation for
9037 * them is wasted effort. We do the
9038 * hard work for unwired pages only.
9040 pmap_remove_pte(pmap, pte, pv->pv_va,
9041 *pde, &free, &lock);
9042 pmap_invalidate_page(pmap, pv->pv_va);
9047 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9048 ("inconsistent pv lock %p %p for page %p",
9049 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9054 /* Rotate the PV list if it has more than one entry. */
9055 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9056 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9057 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9060 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9061 not_cleared < PMAP_TS_REFERENCED_MAX);
9064 vm_page_free_pages_toq(&free, true);
9065 return (cleared + not_cleared);
9069 * Apply the given advice to the specified range of addresses within the
9070 * given pmap. Depending on the advice, clear the referenced and/or
9071 * modified flags in each mapping and set the mapped page's dirty field.
9074 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9076 struct rwlock *lock;
9077 pml4_entry_t *pml4e;
9079 pd_entry_t oldpde, *pde;
9080 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9081 vm_offset_t va, va_next;
9085 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9089 * A/D bit emulation requires an alternate code path when clearing
9090 * the modified and accessed bits below. Since this function is
9091 * advisory in nature we skip it entirely for pmaps that require
9092 * A/D bit emulation.
9094 if (pmap_emulate_ad_bits(pmap))
9097 PG_A = pmap_accessed_bit(pmap);
9098 PG_G = pmap_global_bit(pmap);
9099 PG_M = pmap_modified_bit(pmap);
9100 PG_V = pmap_valid_bit(pmap);
9101 PG_RW = pmap_rw_bit(pmap);
9103 pmap_delayed_invl_start();
9105 for (; sva < eva; sva = va_next) {
9106 pml4e = pmap_pml4e(pmap, sva);
9107 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9108 va_next = (sva + NBPML4) & ~PML4MASK;
9114 va_next = (sva + NBPDP) & ~PDPMASK;
9117 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9118 if ((*pdpe & PG_V) == 0)
9120 if ((*pdpe & PG_PS) != 0)
9123 va_next = (sva + NBPDR) & ~PDRMASK;
9126 pde = pmap_pdpe_to_pde(pdpe, sva);
9128 if ((oldpde & PG_V) == 0)
9130 else if ((oldpde & PG_PS) != 0) {
9131 if ((oldpde & PG_MANAGED) == 0)
9134 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9139 * The large page mapping was destroyed.
9145 * Unless the page mappings are wired, remove the
9146 * mapping to a single page so that a subsequent
9147 * access may repromote. Choosing the last page
9148 * within the address range [sva, min(va_next, eva))
9149 * generally results in more repromotions. Since the
9150 * underlying page table page is fully populated, this
9151 * removal never frees a page table page.
9153 if ((oldpde & PG_W) == 0) {
9159 ("pmap_advise: no address gap"));
9160 pte = pmap_pde_to_pte(pde, va);
9161 KASSERT((*pte & PG_V) != 0,
9162 ("pmap_advise: invalid PTE"));
9163 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9173 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9175 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9177 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9178 if (advice == MADV_DONTNEED) {
9180 * Future calls to pmap_is_modified()
9181 * can be avoided by making the page
9184 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9187 atomic_clear_long(pte, PG_M | PG_A);
9188 } else if ((*pte & PG_A) != 0)
9189 atomic_clear_long(pte, PG_A);
9193 if ((*pte & PG_G) != 0) {
9200 if (va != va_next) {
9201 pmap_invalidate_range(pmap, va, sva);
9206 pmap_invalidate_range(pmap, va, sva);
9209 pmap_invalidate_all(pmap);
9211 pmap_delayed_invl_finish();
9215 * Clear the modify bits on the specified physical page.
9218 pmap_clear_modify(vm_page_t m)
9220 struct md_page *pvh;
9222 pv_entry_t next_pv, pv;
9223 pd_entry_t oldpde, *pde;
9224 pt_entry_t *pte, PG_M, PG_RW;
9225 struct rwlock *lock;
9227 int md_gen, pvh_gen;
9229 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9230 ("pmap_clear_modify: page %p is not managed", m));
9231 vm_page_assert_busied(m);
9233 if (!pmap_page_is_write_mapped(m))
9235 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9236 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9237 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9240 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9242 if (!PMAP_TRYLOCK(pmap)) {
9243 pvh_gen = pvh->pv_gen;
9247 if (pvh_gen != pvh->pv_gen) {
9252 PG_M = pmap_modified_bit(pmap);
9253 PG_RW = pmap_rw_bit(pmap);
9255 pde = pmap_pde(pmap, va);
9257 /* If oldpde has PG_RW set, then it also has PG_M set. */
9258 if ((oldpde & PG_RW) != 0 &&
9259 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9260 (oldpde & PG_W) == 0) {
9262 * Write protect the mapping to a single page so that
9263 * a subsequent write access may repromote.
9265 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9266 pte = pmap_pde_to_pte(pde, va);
9267 atomic_clear_long(pte, PG_M | PG_RW);
9269 pmap_invalidate_page(pmap, va);
9273 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9275 if (!PMAP_TRYLOCK(pmap)) {
9276 md_gen = m->md.pv_gen;
9277 pvh_gen = pvh->pv_gen;
9281 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9286 PG_M = pmap_modified_bit(pmap);
9287 PG_RW = pmap_rw_bit(pmap);
9288 pde = pmap_pde(pmap, pv->pv_va);
9289 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9290 " a 2mpage in page %p's pv list", m));
9291 pte = pmap_pde_to_pte(pde, pv->pv_va);
9292 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9293 atomic_clear_long(pte, PG_M);
9294 pmap_invalidate_page(pmap, pv->pv_va);
9302 * Miscellaneous support routines follow
9305 /* Adjust the properties for a leaf page table entry. */
9306 static __inline void
9307 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9311 opte = *(u_long *)pte;
9313 npte = opte & ~mask;
9315 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9320 * Map a set of physical memory pages into the kernel virtual
9321 * address space. Return a pointer to where it is mapped. This
9322 * routine is intended to be used for mapping device memory,
9326 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9328 struct pmap_preinit_mapping *ppim;
9329 vm_offset_t va, offset;
9333 offset = pa & PAGE_MASK;
9334 size = round_page(offset + size);
9335 pa = trunc_page(pa);
9337 if (!pmap_initialized) {
9339 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9340 ppim = pmap_preinit_mapping + i;
9341 if (ppim->va == 0) {
9345 ppim->va = virtual_avail;
9346 virtual_avail += size;
9352 panic("%s: too many preinit mappings", __func__);
9355 * If we have a preinit mapping, re-use it.
9357 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9358 ppim = pmap_preinit_mapping + i;
9359 if (ppim->pa == pa && ppim->sz == size &&
9360 (ppim->mode == mode ||
9361 (flags & MAPDEV_SETATTR) == 0))
9362 return ((void *)(ppim->va + offset));
9365 * If the specified range of physical addresses fits within
9366 * the direct map window, use the direct map.
9368 if (pa < dmaplimit && pa + size <= dmaplimit) {
9369 va = PHYS_TO_DMAP(pa);
9370 if ((flags & MAPDEV_SETATTR) != 0) {
9371 PMAP_LOCK(kernel_pmap);
9372 i = pmap_change_props_locked(va, size,
9373 PROT_NONE, mode, flags);
9374 PMAP_UNLOCK(kernel_pmap);
9378 return ((void *)(va + offset));
9380 va = kva_alloc(size);
9382 panic("%s: Couldn't allocate KVA", __func__);
9384 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9385 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9386 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9387 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9388 pmap_invalidate_cache_range(va, va + tmpsize);
9389 return ((void *)(va + offset));
9393 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9396 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9401 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9404 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9408 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9411 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9416 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9419 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9420 MAPDEV_FLUSHCACHE));
9424 pmap_unmapdev(void *p, vm_size_t size)
9426 struct pmap_preinit_mapping *ppim;
9427 vm_offset_t offset, va;
9430 va = (vm_offset_t)p;
9432 /* If we gave a direct map region in pmap_mapdev, do nothing */
9433 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9435 offset = va & PAGE_MASK;
9436 size = round_page(offset + size);
9437 va = trunc_page(va);
9438 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9439 ppim = pmap_preinit_mapping + i;
9440 if (ppim->va == va && ppim->sz == size) {
9441 if (pmap_initialized)
9447 if (va + size == virtual_avail)
9452 if (pmap_initialized) {
9453 pmap_qremove(va, atop(size));
9459 * Tries to demote a 1GB page mapping.
9462 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9464 pdp_entry_t newpdpe, oldpdpe;
9465 pd_entry_t *firstpde, newpde, *pde;
9466 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9470 PG_A = pmap_accessed_bit(pmap);
9471 PG_M = pmap_modified_bit(pmap);
9472 PG_V = pmap_valid_bit(pmap);
9473 PG_RW = pmap_rw_bit(pmap);
9475 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9477 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9478 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9479 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9480 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9482 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9483 " in pmap %p", va, pmap);
9486 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9487 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9488 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9489 KASSERT((oldpdpe & PG_A) != 0,
9490 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9491 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9492 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9496 * Initialize the page directory page.
9498 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9504 * Demote the mapping.
9509 * Invalidate a stale recursive mapping of the page directory page.
9511 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9513 counter_u64_add(pmap_pdpe_demotions, 1);
9514 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9515 " in pmap %p", va, pmap);
9520 * Sets the memory attribute for the specified page.
9523 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9526 m->md.pat_mode = ma;
9529 * If "m" is a normal page, update its direct mapping. This update
9530 * can be relied upon to perform any cache operations that are
9531 * required for data coherence.
9533 if ((m->flags & PG_FICTITIOUS) == 0 &&
9534 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9536 panic("memory attribute change on the direct map failed");
9540 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9544 m->md.pat_mode = ma;
9546 if ((m->flags & PG_FICTITIOUS) != 0)
9548 PMAP_LOCK(kernel_pmap);
9549 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9550 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9551 PMAP_UNLOCK(kernel_pmap);
9553 panic("memory attribute change on the direct map failed");
9557 * Changes the specified virtual address range's memory type to that given by
9558 * the parameter "mode". The specified virtual address range must be
9559 * completely contained within either the direct map or the kernel map. If
9560 * the virtual address range is contained within the kernel map, then the
9561 * memory type for each of the corresponding ranges of the direct map is also
9562 * changed. (The corresponding ranges of the direct map are those ranges that
9563 * map the same physical pages as the specified virtual address range.) These
9564 * changes to the direct map are necessary because Intel describes the
9565 * behavior of their processors as "undefined" if two or more mappings to the
9566 * same physical page have different memory types.
9568 * Returns zero if the change completed successfully, and either EINVAL or
9569 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9570 * of the virtual address range was not mapped, and ENOMEM is returned if
9571 * there was insufficient memory available to complete the change. In the
9572 * latter case, the memory type may have been changed on some part of the
9573 * virtual address range or the direct map.
9576 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9580 PMAP_LOCK(kernel_pmap);
9581 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9583 PMAP_UNLOCK(kernel_pmap);
9588 * Changes the specified virtual address range's protections to those
9589 * specified by "prot". Like pmap_change_attr(), protections for aliases
9590 * in the direct map are updated as well. Protections on aliasing mappings may
9591 * be a subset of the requested protections; for example, mappings in the direct
9592 * map are never executable.
9595 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9599 /* Only supported within the kernel map. */
9600 if (va < VM_MIN_KERNEL_ADDRESS)
9603 PMAP_LOCK(kernel_pmap);
9604 error = pmap_change_props_locked(va, size, prot, -1,
9605 MAPDEV_ASSERTVALID);
9606 PMAP_UNLOCK(kernel_pmap);
9611 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9612 int mode, int flags)
9614 vm_offset_t base, offset, tmpva;
9615 vm_paddr_t pa_start, pa_end, pa_end1;
9617 pd_entry_t *pde, pde_bits, pde_mask;
9618 pt_entry_t *pte, pte_bits, pte_mask;
9622 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9623 base = trunc_page(va);
9624 offset = va & PAGE_MASK;
9625 size = round_page(offset + size);
9628 * Only supported on kernel virtual addresses, including the direct
9629 * map but excluding the recursive map.
9631 if (base < DMAP_MIN_ADDRESS)
9635 * Construct our flag sets and masks. "bits" is the subset of
9636 * "mask" that will be set in each modified PTE.
9638 * Mappings in the direct map are never allowed to be executable.
9640 pde_bits = pte_bits = 0;
9641 pde_mask = pte_mask = 0;
9643 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9644 pde_mask |= X86_PG_PDE_CACHE;
9645 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9646 pte_mask |= X86_PG_PTE_CACHE;
9648 if (prot != VM_PROT_NONE) {
9649 if ((prot & VM_PROT_WRITE) != 0) {
9650 pde_bits |= X86_PG_RW;
9651 pte_bits |= X86_PG_RW;
9653 if ((prot & VM_PROT_EXECUTE) == 0 ||
9654 va < VM_MIN_KERNEL_ADDRESS) {
9658 pde_mask |= X86_PG_RW | pg_nx;
9659 pte_mask |= X86_PG_RW | pg_nx;
9663 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9664 * into 4KB pages if required.
9666 for (tmpva = base; tmpva < base + size; ) {
9667 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9668 if (pdpe == NULL || *pdpe == 0) {
9669 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9670 ("%s: addr %#lx is not mapped", __func__, tmpva));
9673 if (*pdpe & PG_PS) {
9675 * If the current 1GB page already has the required
9676 * properties, then we need not demote this page. Just
9677 * increment tmpva to the next 1GB page frame.
9679 if ((*pdpe & pde_mask) == pde_bits) {
9680 tmpva = trunc_1gpage(tmpva) + NBPDP;
9685 * If the current offset aligns with a 1GB page frame
9686 * and there is at least 1GB left within the range, then
9687 * we need not break down this page into 2MB pages.
9689 if ((tmpva & PDPMASK) == 0 &&
9690 tmpva + PDPMASK < base + size) {
9694 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9697 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9699 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9700 ("%s: addr %#lx is not mapped", __func__, tmpva));
9705 * If the current 2MB page already has the required
9706 * properties, then we need not demote this page. Just
9707 * increment tmpva to the next 2MB page frame.
9709 if ((*pde & pde_mask) == pde_bits) {
9710 tmpva = trunc_2mpage(tmpva) + NBPDR;
9715 * If the current offset aligns with a 2MB page frame
9716 * and there is at least 2MB left within the range, then
9717 * we need not break down this page into 4KB pages.
9719 if ((tmpva & PDRMASK) == 0 &&
9720 tmpva + PDRMASK < base + size) {
9724 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9727 pte = pmap_pde_to_pte(pde, tmpva);
9729 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9730 ("%s: addr %#lx is not mapped", __func__, tmpva));
9738 * Ok, all the pages exist, so run through them updating their
9739 * properties if required.
9742 pa_start = pa_end = 0;
9743 for (tmpva = base; tmpva < base + size; ) {
9744 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9745 if (*pdpe & PG_PS) {
9746 if ((*pdpe & pde_mask) != pde_bits) {
9747 pmap_pte_props(pdpe, pde_bits, pde_mask);
9750 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9751 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9752 if (pa_start == pa_end) {
9753 /* Start physical address run. */
9754 pa_start = *pdpe & PG_PS_FRAME;
9755 pa_end = pa_start + NBPDP;
9756 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9759 /* Run ended, update direct map. */
9760 error = pmap_change_props_locked(
9761 PHYS_TO_DMAP(pa_start),
9762 pa_end - pa_start, prot, mode,
9766 /* Start physical address run. */
9767 pa_start = *pdpe & PG_PS_FRAME;
9768 pa_end = pa_start + NBPDP;
9771 tmpva = trunc_1gpage(tmpva) + NBPDP;
9774 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9776 if ((*pde & pde_mask) != pde_bits) {
9777 pmap_pte_props(pde, pde_bits, pde_mask);
9780 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9781 (*pde & PG_PS_FRAME) < dmaplimit) {
9782 if (pa_start == pa_end) {
9783 /* Start physical address run. */
9784 pa_start = *pde & PG_PS_FRAME;
9785 pa_end = pa_start + NBPDR;
9786 } else if (pa_end == (*pde & PG_PS_FRAME))
9789 /* Run ended, update direct map. */
9790 error = pmap_change_props_locked(
9791 PHYS_TO_DMAP(pa_start),
9792 pa_end - pa_start, prot, mode,
9796 /* Start physical address run. */
9797 pa_start = *pde & PG_PS_FRAME;
9798 pa_end = pa_start + NBPDR;
9801 tmpva = trunc_2mpage(tmpva) + NBPDR;
9803 pte = pmap_pde_to_pte(pde, tmpva);
9804 if ((*pte & pte_mask) != pte_bits) {
9805 pmap_pte_props(pte, pte_bits, pte_mask);
9808 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9809 (*pte & PG_FRAME) < dmaplimit) {
9810 if (pa_start == pa_end) {
9811 /* Start physical address run. */
9812 pa_start = *pte & PG_FRAME;
9813 pa_end = pa_start + PAGE_SIZE;
9814 } else if (pa_end == (*pte & PG_FRAME))
9815 pa_end += PAGE_SIZE;
9817 /* Run ended, update direct map. */
9818 error = pmap_change_props_locked(
9819 PHYS_TO_DMAP(pa_start),
9820 pa_end - pa_start, prot, mode,
9824 /* Start physical address run. */
9825 pa_start = *pte & PG_FRAME;
9826 pa_end = pa_start + PAGE_SIZE;
9832 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9833 pa_end1 = MIN(pa_end, dmaplimit);
9834 if (pa_start != pa_end1)
9835 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9836 pa_end1 - pa_start, prot, mode, flags);
9840 * Flush CPU caches if required to make sure any data isn't cached that
9841 * shouldn't be, etc.
9844 pmap_invalidate_range(kernel_pmap, base, tmpva);
9845 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9846 pmap_invalidate_cache_range(base, tmpva);
9852 * Demotes any mapping within the direct map region that covers more than the
9853 * specified range of physical addresses. This range's size must be a power
9854 * of two and its starting address must be a multiple of its size. Since the
9855 * demotion does not change any attributes of the mapping, a TLB invalidation
9856 * is not mandatory. The caller may, however, request a TLB invalidation.
9859 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
9868 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9869 KASSERT((base & (len - 1)) == 0,
9870 ("pmap_demote_DMAP: base is not a multiple of len"));
9871 if (len < NBPDP && base < dmaplimit) {
9872 va = PHYS_TO_DMAP(base);
9874 PMAP_LOCK(kernel_pmap);
9875 pdpe = pmap_pdpe(kernel_pmap, va);
9876 if ((*pdpe & X86_PG_V) == 0)
9877 panic("pmap_demote_DMAP: invalid PDPE");
9878 if ((*pdpe & PG_PS) != 0) {
9879 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9880 panic("pmap_demote_DMAP: PDPE failed");
9884 pde = pmap_pdpe_to_pde(pdpe, va);
9885 if ((*pde & X86_PG_V) == 0)
9886 panic("pmap_demote_DMAP: invalid PDE");
9887 if ((*pde & PG_PS) != 0) {
9888 if (!pmap_demote_pde(kernel_pmap, pde, va))
9889 panic("pmap_demote_DMAP: PDE failed");
9893 if (changed && invalidate)
9894 pmap_invalidate_page(kernel_pmap, va);
9895 PMAP_UNLOCK(kernel_pmap);
9900 * Perform the pmap work for mincore(2). If the page is not both referenced and
9901 * modified by this pmap, returns its physical address so that the caller can
9902 * find other mappings.
9905 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
9909 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
9913 PG_A = pmap_accessed_bit(pmap);
9914 PG_M = pmap_modified_bit(pmap);
9915 PG_V = pmap_valid_bit(pmap);
9916 PG_RW = pmap_rw_bit(pmap);
9922 pdpe = pmap_pdpe(pmap, addr);
9925 if ((*pdpe & PG_V) != 0) {
9926 if ((*pdpe & PG_PS) != 0) {
9928 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
9930 val = MINCORE_PSIND(2);
9932 pdep = pmap_pde(pmap, addr);
9933 if (pdep != NULL && (*pdep & PG_V) != 0) {
9934 if ((*pdep & PG_PS) != 0) {
9936 /* Compute the physical address of the 4KB page. */
9937 pa = ((pte & PG_PS_FRAME) | (addr &
9938 PDRMASK)) & PG_FRAME;
9939 val = MINCORE_PSIND(1);
9941 pte = *pmap_pde_to_pte(pdep, addr);
9942 pa = pte & PG_FRAME;
9948 if ((pte & PG_V) != 0) {
9949 val |= MINCORE_INCORE;
9950 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9951 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
9952 if ((pte & PG_A) != 0)
9953 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
9955 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
9956 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
9957 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
9966 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
9968 uint32_t gen, new_gen, pcid_next;
9970 CRITICAL_ASSERT(curthread);
9971 gen = PCPU_GET(pcid_gen);
9972 if (pcidp->pm_pcid == PMAP_PCID_KERN)
9973 return (pti ? 0 : CR3_PCID_SAVE);
9974 if (pcidp->pm_gen == gen)
9975 return (CR3_PCID_SAVE);
9976 pcid_next = PCPU_GET(pcid_next);
9977 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
9978 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
9979 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
9980 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
9981 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
9985 PCPU_SET(pcid_gen, new_gen);
9986 pcid_next = PMAP_PCID_KERN + 1;
9990 pcidp->pm_pcid = pcid_next;
9991 pcidp->pm_gen = new_gen;
9992 PCPU_SET(pcid_next, pcid_next + 1);
9997 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10001 cached = pmap_pcid_alloc(pmap, pcidp);
10002 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10003 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10004 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10005 ("non-kernel pmap pmap %p cpu %d pcid %#x",
10006 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10011 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10014 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10015 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10019 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10022 struct pmap_pcid *pcidp, *old_pcidp;
10023 uint64_t cached, cr3, kcr3, ucr3;
10025 KASSERT((read_rflags() & PSL_I) == 0,
10026 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10028 /* See the comment in pmap_invalidate_page_pcid(). */
10029 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10030 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10031 old_pmap = PCPU_GET(curpmap);
10032 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10033 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10034 old_pcidp->pm_gen = 0;
10037 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10038 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10040 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10041 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10042 PCPU_SET(curpmap, pmap);
10043 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10044 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10046 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10047 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10049 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10050 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10052 counter_u64_add(pcid_save_cnt, 1);
10054 pmap_activate_sw_pti_post(td, pmap);
10058 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10061 struct pmap_pcid *pcidp;
10062 uint64_t cached, cr3;
10064 KASSERT((read_rflags() & PSL_I) == 0,
10065 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10067 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10068 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10070 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10071 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10072 PCPU_SET(curpmap, pmap);
10074 counter_u64_add(pcid_save_cnt, 1);
10078 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10079 u_int cpuid __unused)
10082 load_cr3(pmap->pm_cr3);
10083 PCPU_SET(curpmap, pmap);
10087 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10088 u_int cpuid __unused)
10091 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10092 PCPU_SET(kcr3, pmap->pm_cr3);
10093 PCPU_SET(ucr3, pmap->pm_ucr3);
10094 pmap_activate_sw_pti_post(td, pmap);
10097 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10101 if (pmap_pcid_enabled && pti)
10102 return (pmap_activate_sw_pcid_pti);
10103 else if (pmap_pcid_enabled && !pti)
10104 return (pmap_activate_sw_pcid_nopti);
10105 else if (!pmap_pcid_enabled && pti)
10106 return (pmap_activate_sw_nopcid_pti);
10107 else /* if (!pmap_pcid_enabled && !pti) */
10108 return (pmap_activate_sw_nopcid_nopti);
10112 pmap_activate_sw(struct thread *td)
10114 pmap_t oldpmap, pmap;
10117 oldpmap = PCPU_GET(curpmap);
10118 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10119 if (oldpmap == pmap) {
10120 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10124 cpuid = PCPU_GET(cpuid);
10126 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10128 CPU_SET(cpuid, &pmap->pm_active);
10130 pmap_activate_sw_mode(td, pmap, cpuid);
10132 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10134 CPU_CLR(cpuid, &oldpmap->pm_active);
10139 pmap_activate(struct thread *td)
10142 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10143 * invalidate_all IPI, which checks for curpmap ==
10144 * smp_tlb_pmap. The below sequence of operations has a
10145 * window where %CR3 is loaded with the new pmap's PML4
10146 * address, but the curpmap value has not yet been updated.
10147 * This causes the invltlb IPI handler, which is called
10148 * between the updates, to execute as a NOP, which leaves
10149 * stale TLB entries.
10151 * Note that the most common use of pmap_activate_sw(), from
10152 * a context switch, is immune to this race, because
10153 * interrupts are disabled (while the thread lock is owned),
10154 * so the IPI is delayed until after curpmap is updated. Protect
10155 * other callers in a similar way, by disabling interrupts
10156 * around the %cr3 register reload and curpmap assignment.
10159 pmap_activate_sw(td);
10164 pmap_activate_boot(pmap_t pmap)
10170 * kernel_pmap must be never deactivated, and we ensure that
10171 * by never activating it at all.
10173 MPASS(pmap != kernel_pmap);
10175 cpuid = PCPU_GET(cpuid);
10177 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10179 CPU_SET(cpuid, &pmap->pm_active);
10181 PCPU_SET(curpmap, pmap);
10183 kcr3 = pmap->pm_cr3;
10184 if (pmap_pcid_enabled)
10185 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10187 kcr3 = PMAP_NO_CR3;
10189 PCPU_SET(kcr3, kcr3);
10190 PCPU_SET(ucr3, PMAP_NO_CR3);
10194 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10199 * Increase the starting virtual address of the given mapping if a
10200 * different alignment might result in more superpage mappings.
10203 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10204 vm_offset_t *addr, vm_size_t size)
10206 vm_offset_t superpage_offset;
10210 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10211 offset += ptoa(object->pg_color);
10212 superpage_offset = offset & PDRMASK;
10213 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10214 (*addr & PDRMASK) == superpage_offset)
10216 if ((*addr & PDRMASK) < superpage_offset)
10217 *addr = (*addr & ~PDRMASK) + superpage_offset;
10219 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10223 static unsigned long num_dirty_emulations;
10224 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10225 &num_dirty_emulations, 0, NULL);
10227 static unsigned long num_accessed_emulations;
10228 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10229 &num_accessed_emulations, 0, NULL);
10231 static unsigned long num_superpage_accessed_emulations;
10232 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10233 &num_superpage_accessed_emulations, 0, NULL);
10235 static unsigned long ad_emulation_superpage_promotions;
10236 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10237 &ad_emulation_superpage_promotions, 0, NULL);
10238 #endif /* INVARIANTS */
10241 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10244 struct rwlock *lock;
10245 #if VM_NRESERVLEVEL > 0
10249 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10251 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10252 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10254 if (!pmap_emulate_ad_bits(pmap))
10257 PG_A = pmap_accessed_bit(pmap);
10258 PG_M = pmap_modified_bit(pmap);
10259 PG_V = pmap_valid_bit(pmap);
10260 PG_RW = pmap_rw_bit(pmap);
10266 pde = pmap_pde(pmap, va);
10267 if (pde == NULL || (*pde & PG_V) == 0)
10270 if ((*pde & PG_PS) != 0) {
10271 if (ftype == VM_PROT_READ) {
10273 atomic_add_long(&num_superpage_accessed_emulations, 1);
10281 pte = pmap_pde_to_pte(pde, va);
10282 if ((*pte & PG_V) == 0)
10285 if (ftype == VM_PROT_WRITE) {
10286 if ((*pte & PG_RW) == 0)
10289 * Set the modified and accessed bits simultaneously.
10291 * Intel EPT PTEs that do software emulation of A/D bits map
10292 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10293 * An EPT misconfiguration is triggered if the PTE is writable
10294 * but not readable (WR=10). This is avoided by setting PG_A
10295 * and PG_M simultaneously.
10297 *pte |= PG_M | PG_A;
10302 #if VM_NRESERVLEVEL > 0
10303 /* try to promote the mapping */
10304 if (va < VM_MAXUSER_ADDRESS)
10305 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10309 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10311 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10312 pmap_ps_enabled(pmap) &&
10313 (m->flags & PG_FICTITIOUS) == 0 &&
10314 vm_reserv_level_iffullpop(m) == 0) {
10315 pmap_promote_pde(pmap, pde, va, mpte, &lock);
10317 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10323 if (ftype == VM_PROT_WRITE)
10324 atomic_add_long(&num_dirty_emulations, 1);
10326 atomic_add_long(&num_accessed_emulations, 1);
10328 rv = 0; /* success */
10337 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10339 pml4_entry_t *pml4;
10342 pt_entry_t *pte, PG_V;
10346 PG_V = pmap_valid_bit(pmap);
10349 pml4 = pmap_pml4e(pmap, va);
10352 ptr[idx++] = *pml4;
10353 if ((*pml4 & PG_V) == 0)
10356 pdp = pmap_pml4e_to_pdpe(pml4, va);
10358 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10361 pde = pmap_pdpe_to_pde(pdp, va);
10363 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10366 pte = pmap_pde_to_pte(pde, va);
10375 * Get the kernel virtual address of a set of physical pages. If there are
10376 * physical addresses not covered by the DMAP perform a transient mapping
10377 * that will be removed when calling pmap_unmap_io_transient.
10379 * \param page The pages the caller wishes to obtain the virtual
10380 * address on the kernel memory map.
10381 * \param vaddr On return contains the kernel virtual memory address
10382 * of the pages passed in the page parameter.
10383 * \param count Number of pages passed in.
10384 * \param can_fault true if the thread using the mapped pages can take
10385 * page faults, false otherwise.
10387 * \returns true if the caller must call pmap_unmap_io_transient when
10388 * finished or false otherwise.
10392 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10396 bool needs_mapping;
10398 int cache_bits, error __unused, i;
10401 * Allocate any KVA space that we need, this is done in a separate
10402 * loop to prevent calling vmem_alloc while pinned.
10404 needs_mapping = false;
10405 for (i = 0; i < count; i++) {
10406 paddr = VM_PAGE_TO_PHYS(page[i]);
10407 if (__predict_false(paddr >= dmaplimit)) {
10408 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10409 M_BESTFIT | M_WAITOK, &vaddr[i]);
10410 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10411 needs_mapping = true;
10413 vaddr[i] = PHYS_TO_DMAP(paddr);
10417 /* Exit early if everything is covered by the DMAP */
10418 if (!needs_mapping)
10422 * NB: The sequence of updating a page table followed by accesses
10423 * to the corresponding pages used in the !DMAP case is subject to
10424 * the situation described in the "AMD64 Architecture Programmer's
10425 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10426 * Coherency Considerations". Therefore, issuing the INVLPG right
10427 * after modifying the PTE bits is crucial.
10431 for (i = 0; i < count; i++) {
10432 paddr = VM_PAGE_TO_PHYS(page[i]);
10433 if (paddr >= dmaplimit) {
10436 * Slow path, since we can get page faults
10437 * while mappings are active don't pin the
10438 * thread to the CPU and instead add a global
10439 * mapping visible to all CPUs.
10441 pmap_qenter(vaddr[i], &page[i], 1);
10443 pte = vtopte(vaddr[i]);
10444 cache_bits = pmap_cache_bits(kernel_pmap,
10445 page[i]->md.pat_mode, false);
10446 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10448 pmap_invlpg(kernel_pmap, vaddr[i]);
10453 return (needs_mapping);
10457 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10465 for (i = 0; i < count; i++) {
10466 paddr = VM_PAGE_TO_PHYS(page[i]);
10467 if (paddr >= dmaplimit) {
10469 pmap_qremove(vaddr[i], 1);
10470 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10476 pmap_quick_enter_page(vm_page_t m)
10480 paddr = VM_PAGE_TO_PHYS(m);
10481 if (paddr < dmaplimit)
10482 return (PHYS_TO_DMAP(paddr));
10483 mtx_lock_spin(&qframe_mtx);
10484 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10487 * Since qframe is exclusively mapped by us, and we do not set
10488 * PG_G, we can use INVLPG here.
10492 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10493 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
10498 pmap_quick_remove_page(vm_offset_t addr)
10501 if (addr != qframe)
10503 pte_store(vtopte(qframe), 0);
10504 mtx_unlock_spin(&qframe_mtx);
10508 * Pdp pages from the large map are managed differently from either
10509 * kernel or user page table pages. They are permanently allocated at
10510 * initialization time, and their reference count is permanently set to
10511 * zero. The pml4 entries pointing to those pages are copied into
10512 * each allocated pmap.
10514 * In contrast, pd and pt pages are managed like user page table
10515 * pages. They are dynamically allocated, and their reference count
10516 * represents the number of valid entries within the page.
10519 pmap_large_map_getptp_unlocked(void)
10521 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10525 pmap_large_map_getptp(void)
10529 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10530 m = pmap_large_map_getptp_unlocked();
10532 PMAP_UNLOCK(kernel_pmap);
10534 PMAP_LOCK(kernel_pmap);
10535 /* Callers retry. */
10540 static pdp_entry_t *
10541 pmap_large_map_pdpe(vm_offset_t va)
10543 vm_pindex_t pml4_idx;
10546 pml4_idx = pmap_pml4e_index(va);
10547 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10548 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10550 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10551 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10552 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10553 "LMSPML4I %#jx lm_ents %d",
10554 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10555 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10556 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10559 static pd_entry_t *
10560 pmap_large_map_pde(vm_offset_t va)
10567 pdpe = pmap_large_map_pdpe(va);
10569 m = pmap_large_map_getptp();
10572 mphys = VM_PAGE_TO_PHYS(m);
10573 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10575 MPASS((*pdpe & X86_PG_PS) == 0);
10576 mphys = *pdpe & PG_FRAME;
10578 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10581 static pt_entry_t *
10582 pmap_large_map_pte(vm_offset_t va)
10589 pde = pmap_large_map_pde(va);
10591 m = pmap_large_map_getptp();
10594 mphys = VM_PAGE_TO_PHYS(m);
10595 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10596 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10598 MPASS((*pde & X86_PG_PS) == 0);
10599 mphys = *pde & PG_FRAME;
10601 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10605 pmap_large_map_kextract(vm_offset_t va)
10607 pdp_entry_t *pdpe, pdp;
10608 pd_entry_t *pde, pd;
10609 pt_entry_t *pte, pt;
10611 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10612 ("not largemap range %#lx", (u_long)va));
10613 pdpe = pmap_large_map_pdpe(va);
10615 KASSERT((pdp & X86_PG_V) != 0,
10616 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10617 (u_long)pdpe, pdp));
10618 if ((pdp & X86_PG_PS) != 0) {
10619 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10620 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10621 (u_long)pdpe, pdp));
10622 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10624 pde = pmap_pdpe_to_pde(pdpe, va);
10626 KASSERT((pd & X86_PG_V) != 0,
10627 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10628 if ((pd & X86_PG_PS) != 0)
10629 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10630 pte = pmap_pde_to_pte(pde, va);
10632 KASSERT((pt & X86_PG_V) != 0,
10633 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10634 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10638 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10639 vmem_addr_t *vmem_res)
10643 * Large mappings are all but static. Consequently, there
10644 * is no point in waiting for an earlier allocation to be
10647 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10648 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10652 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10653 vm_memattr_t mattr)
10658 vm_offset_t va, inc;
10659 vmem_addr_t vmem_res;
10663 if (len == 0 || spa + len < spa)
10666 /* See if DMAP can serve. */
10667 if (spa + len <= dmaplimit) {
10668 va = PHYS_TO_DMAP(spa);
10669 *addr = (void *)va;
10670 return (pmap_change_attr(va, len, mattr));
10674 * No, allocate KVA. Fit the address with best possible
10675 * alignment for superpages. Fall back to worse align if
10679 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10680 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10681 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10683 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10685 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10688 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10693 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10694 * in the pagetable to minimize flushing. No need to
10695 * invalidate TLB, since we only update invalid entries.
10697 PMAP_LOCK(kernel_pmap);
10698 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10700 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10701 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10702 pdpe = pmap_large_map_pdpe(va);
10704 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10705 X86_PG_V | X86_PG_A | pg_nx |
10706 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10708 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10709 (va & PDRMASK) == 0) {
10710 pde = pmap_large_map_pde(va);
10712 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10713 X86_PG_V | X86_PG_A | pg_nx |
10714 pmap_cache_bits(kernel_pmap, mattr, TRUE);
10715 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10719 pte = pmap_large_map_pte(va);
10721 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10722 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10724 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10729 PMAP_UNLOCK(kernel_pmap);
10732 *addr = (void *)vmem_res;
10737 pmap_large_unmap(void *svaa, vm_size_t len)
10739 vm_offset_t sva, va;
10741 pdp_entry_t *pdpe, pdp;
10742 pd_entry_t *pde, pd;
10745 struct spglist spgf;
10747 sva = (vm_offset_t)svaa;
10748 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10749 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10753 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10754 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10755 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10756 PMAP_LOCK(kernel_pmap);
10757 for (va = sva; va < sva + len; va += inc) {
10758 pdpe = pmap_large_map_pdpe(va);
10760 KASSERT((pdp & X86_PG_V) != 0,
10761 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10762 (u_long)pdpe, pdp));
10763 if ((pdp & X86_PG_PS) != 0) {
10764 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10765 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10766 (u_long)pdpe, pdp));
10767 KASSERT((va & PDPMASK) == 0,
10768 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10769 (u_long)pdpe, pdp));
10770 KASSERT(va + NBPDP <= sva + len,
10771 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10772 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10773 (u_long)pdpe, pdp, len));
10778 pde = pmap_pdpe_to_pde(pdpe, va);
10780 KASSERT((pd & X86_PG_V) != 0,
10781 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10783 if ((pd & X86_PG_PS) != 0) {
10784 KASSERT((va & PDRMASK) == 0,
10785 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10787 KASSERT(va + NBPDR <= sva + len,
10788 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10789 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10793 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10795 if (m->ref_count == 0) {
10797 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10801 pte = pmap_pde_to_pte(pde, va);
10802 KASSERT((*pte & X86_PG_V) != 0,
10803 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10804 (u_long)pte, *pte));
10807 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10809 if (m->ref_count == 0) {
10811 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10812 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10814 if (m->ref_count == 0) {
10816 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10820 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10821 PMAP_UNLOCK(kernel_pmap);
10822 vm_page_free_pages_toq(&spgf, false);
10823 vmem_free(large_vmem, sva, len);
10827 pmap_large_map_wb_fence_mfence(void)
10834 pmap_large_map_wb_fence_atomic(void)
10837 atomic_thread_fence_seq_cst();
10841 pmap_large_map_wb_fence_nop(void)
10845 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10848 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10849 return (pmap_large_map_wb_fence_mfence);
10850 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10851 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10852 return (pmap_large_map_wb_fence_atomic);
10854 /* clflush is strongly enough ordered */
10855 return (pmap_large_map_wb_fence_nop);
10859 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10862 for (; len > 0; len -= cpu_clflush_line_size,
10863 va += cpu_clflush_line_size)
10868 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10871 for (; len > 0; len -= cpu_clflush_line_size,
10872 va += cpu_clflush_line_size)
10877 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10880 for (; len > 0; len -= cpu_clflush_line_size,
10881 va += cpu_clflush_line_size)
10886 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10890 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
10893 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
10894 return (pmap_large_map_flush_range_clwb);
10895 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
10896 return (pmap_large_map_flush_range_clflushopt);
10897 else if ((cpu_feature & CPUID_CLFSH) != 0)
10898 return (pmap_large_map_flush_range_clflush);
10900 return (pmap_large_map_flush_range_nop);
10904 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
10906 volatile u_long *pe;
10912 for (va = sva; va < eva; va += inc) {
10914 if ((amd_feature & AMDID_PAGE1GB) != 0) {
10915 pe = (volatile u_long *)pmap_large_map_pdpe(va);
10917 if ((p & X86_PG_PS) != 0)
10921 pe = (volatile u_long *)pmap_large_map_pde(va);
10923 if ((p & X86_PG_PS) != 0)
10927 pe = (volatile u_long *)pmap_large_map_pte(va);
10931 seen_other = false;
10933 if ((p & X86_PG_AVAIL1) != 0) {
10935 * Spin-wait for the end of a parallel
10942 * If we saw other write-back
10943 * occuring, we cannot rely on PG_M to
10944 * indicate state of the cache. The
10945 * PG_M bit is cleared before the
10946 * flush to avoid ignoring new writes,
10947 * and writes which are relevant for
10948 * us might happen after.
10954 if ((p & X86_PG_M) != 0 || seen_other) {
10955 if (!atomic_fcmpset_long(pe, &p,
10956 (p & ~X86_PG_M) | X86_PG_AVAIL1))
10958 * If we saw PG_M without
10959 * PG_AVAIL1, and then on the
10960 * next attempt we do not
10961 * observe either PG_M or
10962 * PG_AVAIL1, the other
10963 * write-back started after us
10964 * and finished before us. We
10965 * can rely on it doing our
10969 pmap_large_map_flush_range(va, inc);
10970 atomic_clear_long(pe, X86_PG_AVAIL1);
10979 * Write-back cache lines for the given address range.
10981 * Must be called only on the range or sub-range returned from
10982 * pmap_large_map(). Must not be called on the coalesced ranges.
10984 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
10985 * instructions support.
10988 pmap_large_map_wb(void *svap, vm_size_t len)
10990 vm_offset_t eva, sva;
10992 sva = (vm_offset_t)svap;
10994 pmap_large_map_wb_fence();
10995 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
10996 pmap_large_map_flush_range(sva, len);
10998 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
10999 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11000 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11001 pmap_large_map_wb_large(sva, eva);
11003 pmap_large_map_wb_fence();
11007 pmap_pti_alloc_page(void)
11011 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11012 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11017 pmap_pti_free_page(vm_page_t m)
11019 if (!vm_page_unwire_noq(m))
11021 vm_page_xbusy_claim(m);
11022 vm_page_free_zero(m);
11027 pmap_pti_init(void)
11036 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11037 VM_OBJECT_WLOCK(pti_obj);
11038 pml4_pg = pmap_pti_alloc_page();
11039 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11040 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11041 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11042 pdpe = pmap_pti_pdpe(va);
11043 pmap_pti_wire_pte(pdpe);
11045 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11046 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11047 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11048 sizeof(struct gate_descriptor) * NIDT, false);
11050 /* Doublefault stack IST 1 */
11051 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11052 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11053 /* NMI stack IST 2 */
11054 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11055 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11056 /* MC# stack IST 3 */
11057 va = __pcpu[i].pc_common_tss.tss_ist3 +
11058 sizeof(struct nmi_pcpu);
11059 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11060 /* DB# stack IST 4 */
11061 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11062 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11064 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11066 pti_finalized = true;
11067 VM_OBJECT_WUNLOCK(pti_obj);
11071 pmap_cpu_init(void *arg __unused)
11073 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11076 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11078 static pdp_entry_t *
11079 pmap_pti_pdpe(vm_offset_t va)
11081 pml4_entry_t *pml4e;
11084 vm_pindex_t pml4_idx;
11087 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11089 pml4_idx = pmap_pml4e_index(va);
11090 pml4e = &pti_pml4[pml4_idx];
11094 panic("pml4 alloc after finalization\n");
11095 m = pmap_pti_alloc_page();
11097 pmap_pti_free_page(m);
11098 mphys = *pml4e & ~PAGE_MASK;
11100 mphys = VM_PAGE_TO_PHYS(m);
11101 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11104 mphys = *pml4e & ~PAGE_MASK;
11106 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11111 pmap_pti_wire_pte(void *pte)
11115 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11116 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11121 pmap_pti_unwire_pde(void *pde, bool only_ref)
11125 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11126 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11127 MPASS(only_ref || m->ref_count > 1);
11128 pmap_pti_free_page(m);
11132 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11137 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11138 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11139 if (pmap_pti_free_page(m)) {
11140 pde = pmap_pti_pde(va);
11141 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11143 pmap_pti_unwire_pde(pde, false);
11147 static pd_entry_t *
11148 pmap_pti_pde(vm_offset_t va)
11153 vm_pindex_t pd_idx;
11156 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11158 pdpe = pmap_pti_pdpe(va);
11160 m = pmap_pti_alloc_page();
11162 pmap_pti_free_page(m);
11163 MPASS((*pdpe & X86_PG_PS) == 0);
11164 mphys = *pdpe & ~PAGE_MASK;
11166 mphys = VM_PAGE_TO_PHYS(m);
11167 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11170 MPASS((*pdpe & X86_PG_PS) == 0);
11171 mphys = *pdpe & ~PAGE_MASK;
11174 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11175 pd_idx = pmap_pde_index(va);
11180 static pt_entry_t *
11181 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11188 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11190 pde = pmap_pti_pde(va);
11191 if (unwire_pde != NULL) {
11192 *unwire_pde = true;
11193 pmap_pti_wire_pte(pde);
11196 m = pmap_pti_alloc_page();
11198 pmap_pti_free_page(m);
11199 MPASS((*pde & X86_PG_PS) == 0);
11200 mphys = *pde & ~(PAGE_MASK | pg_nx);
11202 mphys = VM_PAGE_TO_PHYS(m);
11203 *pde = mphys | X86_PG_RW | X86_PG_V;
11204 if (unwire_pde != NULL)
11205 *unwire_pde = false;
11208 MPASS((*pde & X86_PG_PS) == 0);
11209 mphys = *pde & ~(PAGE_MASK | pg_nx);
11212 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11213 pte += pmap_pte_index(va);
11219 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11223 pt_entry_t *pte, ptev;
11226 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11228 sva = trunc_page(sva);
11229 MPASS(sva > VM_MAXUSER_ADDRESS);
11230 eva = round_page(eva);
11232 for (; sva < eva; sva += PAGE_SIZE) {
11233 pte = pmap_pti_pte(sva, &unwire_pde);
11234 pa = pmap_kextract(sva);
11235 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11236 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11237 VM_MEMATTR_DEFAULT, FALSE);
11239 pte_store(pte, ptev);
11240 pmap_pti_wire_pte(pte);
11242 KASSERT(!pti_finalized,
11243 ("pti overlap after fin %#lx %#lx %#lx",
11245 KASSERT(*pte == ptev,
11246 ("pti non-identical pte after fin %#lx %#lx %#lx",
11250 pde = pmap_pti_pde(sva);
11251 pmap_pti_unwire_pde(pde, true);
11257 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11262 VM_OBJECT_WLOCK(pti_obj);
11263 pmap_pti_add_kva_locked(sva, eva, exec);
11264 VM_OBJECT_WUNLOCK(pti_obj);
11268 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11275 sva = rounddown2(sva, PAGE_SIZE);
11276 MPASS(sva > VM_MAXUSER_ADDRESS);
11277 eva = roundup2(eva, PAGE_SIZE);
11279 VM_OBJECT_WLOCK(pti_obj);
11280 for (va = sva; va < eva; va += PAGE_SIZE) {
11281 pte = pmap_pti_pte(va, NULL);
11282 KASSERT((*pte & X86_PG_V) != 0,
11283 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11284 (u_long)pte, *pte));
11286 pmap_pti_unwire_pte(pte, va);
11288 pmap_invalidate_range(kernel_pmap, sva, eva);
11289 VM_OBJECT_WUNLOCK(pti_obj);
11293 pkru_dup_range(void *ctx __unused, void *data)
11295 struct pmap_pkru_range *node, *new_node;
11297 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11298 if (new_node == NULL)
11301 memcpy(new_node, node, sizeof(*node));
11306 pkru_free_range(void *ctx __unused, void *node)
11309 uma_zfree(pmap_pkru_ranges_zone, node);
11313 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11316 struct pmap_pkru_range *ppr;
11319 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11320 MPASS(pmap->pm_type == PT_X86);
11321 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11322 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11323 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11325 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11328 ppr->pkru_keyidx = keyidx;
11329 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11330 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11332 uma_zfree(pmap_pkru_ranges_zone, ppr);
11337 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11340 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11341 MPASS(pmap->pm_type == PT_X86);
11342 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11343 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11347 pmap_pkru_deassign_all(pmap_t pmap)
11350 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11351 if (pmap->pm_type == PT_X86 &&
11352 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11353 rangeset_remove_all(&pmap->pm_pkru);
11357 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11359 struct pmap_pkru_range *ppr, *prev_ppr;
11362 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11363 if (pmap->pm_type != PT_X86 ||
11364 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11365 sva >= VM_MAXUSER_ADDRESS)
11367 MPASS(eva <= VM_MAXUSER_ADDRESS);
11368 for (va = sva; va < eva; prev_ppr = ppr) {
11369 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11372 else if ((ppr == NULL) ^ (prev_ppr == NULL))
11378 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
11380 va = ppr->pkru_rs_el.re_end;
11386 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11388 struct pmap_pkru_range *ppr;
11390 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11391 if (pmap->pm_type != PT_X86 ||
11392 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11393 va >= VM_MAXUSER_ADDRESS)
11395 ppr = rangeset_lookup(&pmap->pm_pkru, va);
11397 return (X86_PG_PKU(ppr->pkru_keyidx));
11402 pred_pkru_on_remove(void *ctx __unused, void *r)
11404 struct pmap_pkru_range *ppr;
11407 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11411 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11414 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11415 if (pmap->pm_type == PT_X86 &&
11416 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11417 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11418 pred_pkru_on_remove);
11423 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11426 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11427 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11428 MPASS(dst_pmap->pm_type == PT_X86);
11429 MPASS(src_pmap->pm_type == PT_X86);
11430 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11431 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11433 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11437 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11440 pml4_entry_t *pml4e;
11442 pd_entry_t newpde, ptpaddr, *pde;
11443 pt_entry_t newpte, *ptep, pte;
11444 vm_offset_t va, va_next;
11447 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11448 MPASS(pmap->pm_type == PT_X86);
11449 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11451 for (changed = false, va = sva; va < eva; va = va_next) {
11452 pml4e = pmap_pml4e(pmap, va);
11453 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11454 va_next = (va + NBPML4) & ~PML4MASK;
11460 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11461 if ((*pdpe & X86_PG_V) == 0) {
11462 va_next = (va + NBPDP) & ~PDPMASK;
11468 va_next = (va + NBPDR) & ~PDRMASK;
11472 pde = pmap_pdpe_to_pde(pdpe, va);
11477 MPASS((ptpaddr & X86_PG_V) != 0);
11478 if ((ptpaddr & PG_PS) != 0) {
11479 if (va + NBPDR == va_next && eva >= va_next) {
11480 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11481 X86_PG_PKU(keyidx);
11482 if (newpde != ptpaddr) {
11487 } else if (!pmap_demote_pde(pmap, pde, va)) {
11495 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11496 ptep++, va += PAGE_SIZE) {
11498 if ((pte & X86_PG_V) == 0)
11500 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11501 if (newpte != pte) {
11508 pmap_invalidate_range(pmap, sva, eva);
11512 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11513 u_int keyidx, int flags)
11516 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11517 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11519 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11521 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11527 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11532 sva = trunc_page(sva);
11533 eva = round_page(eva);
11534 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11539 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11541 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11543 if (error != ENOMEM)
11551 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11555 sva = trunc_page(sva);
11556 eva = round_page(eva);
11557 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11562 error = pmap_pkru_deassign(pmap, sva, eva);
11564 pmap_pkru_update_range(pmap, sva, eva, 0);
11566 if (error != ENOMEM)
11573 #if defined(KASAN) || defined(KMSAN)
11576 * Reserve enough memory to:
11577 * 1) allocate PDP pages for the shadow map(s),
11578 * 2) shadow one page of memory, so one PD page, one PT page, and one shadow
11579 * page per shadow map.
11582 #define SAN_EARLY_PAGES (NKASANPML4E + 3)
11584 #define SAN_EARLY_PAGES (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * 3)
11587 static uint64_t __nosanitizeaddress __nosanitizememory
11588 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11590 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11591 static size_t offset = 0;
11594 if (offset == sizeof(data)) {
11595 panic("%s: ran out of memory for the bootstrap shadow map",
11599 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11600 offset += PAGE_SIZE;
11605 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11606 * is currently only used to shadow the temporary boot stack set up by locore.
11608 static void __nosanitizeaddress __nosanitizememory
11609 pmap_san_enter_early(vm_offset_t va)
11611 static bool first = true;
11612 pml4_entry_t *pml4e;
11616 uint64_t cr3, pa, base;
11619 base = amd64_loadaddr();
11624 * If this the first call, we need to allocate new PML4Es for
11625 * the bootstrap shadow map(s). We don't know how the PML4 page
11626 * was initialized by the boot loader, so we can't simply test
11627 * whether the shadow map's PML4Es are zero.
11631 for (i = 0; i < NKASANPML4E; i++) {
11632 pa = pmap_san_enter_early_alloc_4k(base);
11634 pml4e = (pml4_entry_t *)cr3 +
11635 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11636 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11639 for (i = 0; i < NKMSANORIGPML4E; i++) {
11640 pa = pmap_san_enter_early_alloc_4k(base);
11642 pml4e = (pml4_entry_t *)cr3 +
11643 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11645 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11647 for (i = 0; i < NKMSANSHADPML4E; i++) {
11648 pa = pmap_san_enter_early_alloc_4k(base);
11650 pml4e = (pml4_entry_t *)cr3 +
11651 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11653 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11657 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11658 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11660 pa = pmap_san_enter_early_alloc_4k(base);
11661 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11663 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11665 pa = pmap_san_enter_early_alloc_4k(base);
11666 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11668 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11670 panic("%s: PTE for %#lx is already initialized", __func__, va);
11671 pa = pmap_san_enter_early_alloc_4k(base);
11672 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11676 pmap_san_enter_alloc_4k(void)
11680 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11683 panic("%s: no memory to grow shadow map", __func__);
11688 pmap_san_enter_alloc_2m(void)
11690 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11691 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11695 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11696 * pages when possible.
11698 void __nosanitizeaddress __nosanitizememory
11699 pmap_san_enter(vm_offset_t va)
11706 if (kernphys == 0) {
11708 * We're creating a temporary shadow map for the boot stack.
11710 pmap_san_enter_early(va);
11714 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11716 pdpe = pmap_pdpe(kernel_pmap, va);
11717 if ((*pdpe & X86_PG_V) == 0) {
11718 m = pmap_san_enter_alloc_4k();
11719 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11722 pde = pmap_pdpe_to_pde(pdpe, va);
11723 if ((*pde & X86_PG_V) == 0) {
11724 m = pmap_san_enter_alloc_2m();
11726 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11727 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11729 m = pmap_san_enter_alloc_4k();
11730 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11734 if ((*pde & X86_PG_PS) != 0)
11736 pte = pmap_pde_to_pte(pde, va);
11737 if ((*pte & X86_PG_V) != 0)
11739 m = pmap_san_enter_alloc_4k();
11740 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11741 X86_PG_M | X86_PG_A | pg_nx);
11746 * Track a range of the kernel's virtual address space that is contiguous
11747 * in various mapping attributes.
11749 struct pmap_kernel_map_range {
11758 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11764 if (eva <= range->sva)
11767 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11768 for (i = 0; i < PAT_INDEX_SIZE; i++)
11769 if (pat_index[i] == pat_idx)
11773 case PAT_WRITE_BACK:
11776 case PAT_WRITE_THROUGH:
11779 case PAT_UNCACHEABLE:
11785 case PAT_WRITE_PROTECTED:
11788 case PAT_WRITE_COMBINING:
11792 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11793 __func__, pat_idx, range->sva, eva);
11798 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11800 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11801 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11802 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11803 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11804 mode, range->pdpes, range->pdes, range->ptes);
11806 /* Reset to sentinel value. */
11807 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11808 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11809 NPDEPG - 1, NPTEPG - 1);
11813 * Determine whether the attributes specified by a page table entry match those
11814 * being tracked by the current range. This is not quite as simple as a direct
11815 * flag comparison since some PAT modes have multiple representations.
11818 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11820 pt_entry_t diff, mask;
11822 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11823 diff = (range->attrs ^ attrs) & mask;
11826 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11827 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11828 pmap_pat_index(kernel_pmap, attrs, true))
11834 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11838 memset(range, 0, sizeof(*range));
11840 range->attrs = attrs;
11844 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11845 * those of the current run, dump the address range and its attributes, and
11849 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11850 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11855 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11857 attrs |= pdpe & pg_nx;
11858 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11859 if ((pdpe & PG_PS) != 0) {
11860 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11861 } else if (pde != 0) {
11862 attrs |= pde & pg_nx;
11863 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11865 if ((pde & PG_PS) != 0) {
11866 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11867 } else if (pte != 0) {
11868 attrs |= pte & pg_nx;
11869 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11870 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11872 /* Canonicalize by always using the PDE PAT bit. */
11873 if ((attrs & X86_PG_PTE_PAT) != 0)
11874 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11877 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11878 sysctl_kmaps_dump(sb, range, va);
11879 sysctl_kmaps_reinit(range, va, attrs);
11884 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
11886 struct pmap_kernel_map_range range;
11887 struct sbuf sbuf, *sb;
11888 pml4_entry_t pml4e;
11889 pdp_entry_t *pdp, pdpe;
11890 pd_entry_t *pd, pde;
11891 pt_entry_t *pt, pte;
11894 int error, i, j, k, l;
11896 error = sysctl_wire_old_buffer(req, 0);
11900 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
11902 /* Sentinel value. */
11903 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11904 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11905 NPDEPG - 1, NPTEPG - 1);
11908 * Iterate over the kernel page tables without holding the kernel pmap
11909 * lock. Outside of the large map, kernel page table pages are never
11910 * freed, so at worst we will observe inconsistencies in the output.
11911 * Within the large map, ensure that PDP and PD page addresses are
11912 * valid before descending.
11914 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
11917 sbuf_printf(sb, "\nRecursive map:\n");
11920 sbuf_printf(sb, "\nDirect map:\n");
11924 sbuf_printf(sb, "\nKASAN shadow map:\n");
11928 case KMSANSHADPML4I:
11929 sbuf_printf(sb, "\nKMSAN shadow map:\n");
11931 case KMSANORIGPML4I:
11932 sbuf_printf(sb, "\nKMSAN origin map:\n");
11936 sbuf_printf(sb, "\nKernel map:\n");
11939 sbuf_printf(sb, "\nLarge map:\n");
11943 /* Convert to canonical form. */
11944 if (sva == 1ul << 47)
11948 pml4e = kernel_pml4[i];
11949 if ((pml4e & X86_PG_V) == 0) {
11950 sva = rounddown2(sva, NBPML4);
11951 sysctl_kmaps_dump(sb, &range, sva);
11955 pa = pml4e & PG_FRAME;
11956 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
11958 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
11960 if ((pdpe & X86_PG_V) == 0) {
11961 sva = rounddown2(sva, NBPDP);
11962 sysctl_kmaps_dump(sb, &range, sva);
11966 pa = pdpe & PG_FRAME;
11967 if ((pdpe & PG_PS) != 0) {
11968 sva = rounddown2(sva, NBPDP);
11969 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
11975 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
11976 vm_phys_paddr_to_vm_page(pa) == NULL) {
11978 * Page table pages for the large map may be
11979 * freed. Validate the next-level address
11980 * before descending.
11984 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
11986 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
11988 if ((pde & X86_PG_V) == 0) {
11989 sva = rounddown2(sva, NBPDR);
11990 sysctl_kmaps_dump(sb, &range, sva);
11994 pa = pde & PG_FRAME;
11995 if ((pde & PG_PS) != 0) {
11996 sva = rounddown2(sva, NBPDR);
11997 sysctl_kmaps_check(sb, &range, sva,
11998 pml4e, pdpe, pde, 0);
12003 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12004 vm_phys_paddr_to_vm_page(pa) == NULL) {
12006 * Page table pages for the large map
12007 * may be freed. Validate the
12008 * next-level address before descending.
12012 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12014 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12015 sva += PAGE_SIZE) {
12017 if ((pte & X86_PG_V) == 0) {
12018 sysctl_kmaps_dump(sb, &range,
12022 sysctl_kmaps_check(sb, &range, sva,
12023 pml4e, pdpe, pde, pte);
12030 error = sbuf_finish(sb);
12034 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12035 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12036 NULL, 0, sysctl_kmaps, "A",
12037 "Dump kernel address layout");
12040 DB_SHOW_COMMAND(pte, pmap_print_pte)
12043 pml5_entry_t *pml5;
12044 pml4_entry_t *pml4;
12047 pt_entry_t *pte, PG_V;
12051 db_printf("show pte addr\n");
12054 va = (vm_offset_t)addr;
12056 if (kdb_thread != NULL)
12057 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12059 pmap = PCPU_GET(curpmap);
12061 PG_V = pmap_valid_bit(pmap);
12062 db_printf("VA 0x%016lx", va);
12064 if (pmap_is_la57(pmap)) {
12065 pml5 = pmap_pml5e(pmap, va);
12066 db_printf(" pml5e 0x%016lx", *pml5);
12067 if ((*pml5 & PG_V) == 0) {
12071 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12073 pml4 = pmap_pml4e(pmap, va);
12075 db_printf(" pml4e 0x%016lx", *pml4);
12076 if ((*pml4 & PG_V) == 0) {
12080 pdp = pmap_pml4e_to_pdpe(pml4, va);
12081 db_printf(" pdpe 0x%016lx", *pdp);
12082 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12086 pde = pmap_pdpe_to_pde(pdp, va);
12087 db_printf(" pde 0x%016lx", *pde);
12088 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12092 pte = pmap_pde_to_pte(pde, va);
12093 db_printf(" pte 0x%016lx\n", *pte);
12096 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12101 a = (vm_paddr_t)addr;
12102 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12104 db_printf("show phys2dmap addr\n");
12109 ptpages_show_page(int level, int idx, vm_page_t pg)
12111 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12112 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12116 ptpages_show_complain(int level, int idx, uint64_t pte)
12118 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12122 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12124 vm_page_t pg3, pg2, pg1;
12125 pml4_entry_t *pml4;
12130 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12131 for (i4 = 0; i4 < num_entries; i4++) {
12132 if ((pml4[i4] & PG_V) == 0)
12134 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12136 ptpages_show_complain(3, i4, pml4[i4]);
12139 ptpages_show_page(3, i4, pg3);
12140 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12141 for (i3 = 0; i3 < NPDPEPG; i3++) {
12142 if ((pdp[i3] & PG_V) == 0)
12144 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12146 ptpages_show_complain(2, i3, pdp[i3]);
12149 ptpages_show_page(2, i3, pg2);
12150 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12151 for (i2 = 0; i2 < NPDEPG; i2++) {
12152 if ((pd[i2] & PG_V) == 0)
12154 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12156 ptpages_show_complain(1, i2, pd[i2]);
12159 ptpages_show_page(1, i2, pg1);
12165 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12169 pml5_entry_t *pml5;
12174 pmap = (pmap_t)addr;
12176 pmap = PCPU_GET(curpmap);
12178 PG_V = pmap_valid_bit(pmap);
12180 if (pmap_is_la57(pmap)) {
12181 pml5 = pmap->pm_pmltop;
12182 for (i5 = 0; i5 < NUPML5E; i5++) {
12183 if ((pml5[i5] & PG_V) == 0)
12185 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12187 ptpages_show_complain(4, i5, pml5[i5]);
12190 ptpages_show_page(4, i5, pg);
12191 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12194 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12195 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);