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-2019 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/bitstring.h>
117 #include <sys/systm.h>
118 #include <sys/kernel.h>
120 #include <sys/lock.h>
121 #include <sys/malloc.h>
122 #include <sys/mman.h>
123 #include <sys/mutex.h>
124 #include <sys/proc.h>
125 #include <sys/rangeset.h>
126 #include <sys/rwlock.h>
127 #include <sys/sbuf.h>
129 #include <sys/turnstile.h>
130 #include <sys/vmem.h>
131 #include <sys/vmmeter.h>
132 #include <sys/sched.h>
133 #include <sys/sysctl.h>
141 #include <vm/vm_param.h>
142 #include <vm/vm_kern.h>
143 #include <vm/vm_page.h>
144 #include <vm/vm_map.h>
145 #include <vm/vm_object.h>
146 #include <vm/vm_extern.h>
147 #include <vm/vm_pageout.h>
148 #include <vm/vm_pager.h>
149 #include <vm/vm_phys.h>
150 #include <vm/vm_radix.h>
151 #include <vm/vm_reserv.h>
154 #include <machine/intr_machdep.h>
155 #include <x86/apicvar.h>
156 #include <x86/ifunc.h>
157 #include <machine/cpu.h>
158 #include <machine/cputypes.h>
159 #include <machine/md_var.h>
160 #include <machine/pcb.h>
161 #include <machine/specialreg.h>
163 #include <machine/smp.h>
165 #include <machine/sysarch.h>
166 #include <machine/tss.h>
168 static __inline boolean_t
169 pmap_type_guest(pmap_t pmap)
172 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
175 static __inline boolean_t
176 pmap_emulate_ad_bits(pmap_t pmap)
179 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
182 static __inline pt_entry_t
183 pmap_valid_bit(pmap_t pmap)
187 switch (pmap->pm_type) {
193 if (pmap_emulate_ad_bits(pmap))
194 mask = EPT_PG_EMUL_V;
199 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
205 static __inline pt_entry_t
206 pmap_rw_bit(pmap_t pmap)
210 switch (pmap->pm_type) {
216 if (pmap_emulate_ad_bits(pmap))
217 mask = EPT_PG_EMUL_RW;
222 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
228 static pt_entry_t pg_g;
230 static __inline pt_entry_t
231 pmap_global_bit(pmap_t pmap)
235 switch (pmap->pm_type) {
244 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
250 static __inline pt_entry_t
251 pmap_accessed_bit(pmap_t pmap)
255 switch (pmap->pm_type) {
261 if (pmap_emulate_ad_bits(pmap))
267 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
273 static __inline pt_entry_t
274 pmap_modified_bit(pmap_t pmap)
278 switch (pmap->pm_type) {
284 if (pmap_emulate_ad_bits(pmap))
290 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
296 static __inline pt_entry_t
297 pmap_pku_mask_bit(pmap_t pmap)
300 return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
303 #if !defined(DIAGNOSTIC)
304 #ifdef __GNUC_GNU_INLINE__
305 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
307 #define PMAP_INLINE extern inline
314 #define PV_STAT(x) do { x ; } while (0)
316 #define PV_STAT(x) do { } while (0)
320 #define pa_index(pa) ({ \
321 KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end, \
322 ("address %lx beyond the last segment", (pa))); \
325 #if VM_NRESERVLEVEL > 0
326 #define pa_to_pmdp(pa) (&pv_table[pa_index(pa)])
327 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
328 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
329 struct rwlock *_lock; \
330 if (__predict_false((pa) > pmap_last_pa)) \
331 _lock = &pv_dummy_large.pv_lock; \
333 _lock = &(pa_to_pmdp(pa)->pv_lock); \
337 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
339 #define NPV_LIST_LOCKS MAXCPU
341 #define PHYS_TO_PV_LIST_LOCK(pa) \
342 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
345 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
346 struct rwlock **_lockp = (lockp); \
347 struct rwlock *_new_lock; \
349 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
350 if (_new_lock != *_lockp) { \
351 if (*_lockp != NULL) \
352 rw_wunlock(*_lockp); \
353 *_lockp = _new_lock; \
358 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
359 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
361 #define RELEASE_PV_LIST_LOCK(lockp) do { \
362 struct rwlock **_lockp = (lockp); \
364 if (*_lockp != NULL) { \
365 rw_wunlock(*_lockp); \
370 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
371 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
373 struct pmap kernel_pmap_store;
375 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
376 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
379 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
380 "Number of kernel page table pages allocated on bootup");
383 vm_paddr_t dmaplimit;
384 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
387 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
389 static int pg_ps_enabled = 1;
390 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
391 &pg_ps_enabled, 0, "Are large page mappings enabled?");
393 #define PAT_INDEX_SIZE 8
394 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
396 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
397 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
398 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
399 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
401 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
402 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
403 static int ndmpdpphys; /* number of DMPDPphys pages */
405 static vm_paddr_t KERNend; /* phys addr of end of bootstrap data */
408 * pmap_mapdev support pre initialization (i.e. console)
410 #define PMAP_PREINIT_MAPPING_COUNT 8
411 static struct pmap_preinit_mapping {
416 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
417 static int pmap_initialized;
420 * Data for the pv entry allocation mechanism.
421 * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
423 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
424 static struct mtx __exclusive_cache_line pv_chunks_mutex;
425 #if VM_NRESERVLEVEL > 0
426 struct pmap_large_md_page {
427 struct rwlock pv_lock;
428 struct md_page pv_page;
431 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
432 #define pv_dummy pv_dummy_large.pv_page
433 __read_mostly static struct pmap_large_md_page *pv_table;
434 __read_mostly vm_paddr_t pmap_last_pa;
436 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
437 static u_long pv_invl_gen[NPV_LIST_LOCKS];
438 static struct md_page *pv_table;
439 static struct md_page pv_dummy;
443 * All those kernel PT submaps that BSD is so fond of
445 pt_entry_t *CMAP1 = NULL;
447 static vm_offset_t qframe = 0;
448 static struct mtx qframe_mtx;
450 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
452 static vmem_t *large_vmem;
453 static u_int lm_ents;
454 #define PMAP_ADDRESS_IN_LARGEMAP(va) ((va) >= LARGEMAP_MIN_ADDRESS && \
455 (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
457 int pmap_pcid_enabled = 1;
458 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
459 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
460 int invpcid_works = 0;
461 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
462 "Is the invpcid instruction available ?");
464 int __read_frequently pti = 0;
465 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
467 "Page Table Isolation enabled");
468 static vm_object_t pti_obj;
469 static pml4_entry_t *pti_pml4;
470 static vm_pindex_t pti_pg_idx;
471 static bool pti_finalized;
473 struct pmap_pkru_range {
474 struct rs_el pkru_rs_el;
479 static uma_zone_t pmap_pkru_ranges_zone;
480 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
481 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
482 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
483 static void *pkru_dup_range(void *ctx, void *data);
484 static void pkru_free_range(void *ctx, void *node);
485 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
486 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
487 static void pmap_pkru_deassign_all(pmap_t pmap);
490 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
497 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
499 return (sysctl_handle_64(oidp, &res, 0, req));
501 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RD |
502 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
503 "Count of saved TLB context on switch");
505 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
506 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
507 static struct mtx invl_gen_mtx;
508 /* Fake lock object to satisfy turnstiles interface. */
509 static struct lock_object invl_gen_ts = {
512 static struct pmap_invl_gen pmap_invl_gen_head = {
516 static u_long pmap_invl_gen = 1;
517 static int pmap_invl_waiters;
518 static struct callout pmap_invl_callout;
519 static bool pmap_invl_callout_inited;
521 #define PMAP_ASSERT_NOT_IN_DI() \
522 KASSERT(pmap_not_in_di(), ("DI already started"))
529 if ((cpu_feature2 & CPUID2_CX16) == 0)
532 TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
537 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
541 locked = pmap_di_locked();
542 return (sysctl_handle_int(oidp, &locked, 0, req));
544 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
545 CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
546 "Locked delayed invalidation");
548 static bool pmap_not_in_di_l(void);
549 static bool pmap_not_in_di_u(void);
550 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
553 return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
557 pmap_not_in_di_l(void)
559 struct pmap_invl_gen *invl_gen;
561 invl_gen = &curthread->td_md.md_invl_gen;
562 return (invl_gen->gen == 0);
566 pmap_thread_init_invl_gen_l(struct thread *td)
568 struct pmap_invl_gen *invl_gen;
570 invl_gen = &td->td_md.md_invl_gen;
575 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
577 struct turnstile *ts;
579 ts = turnstile_trywait(&invl_gen_ts);
580 if (*m_gen > atomic_load_long(invl_gen))
581 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
583 turnstile_cancel(ts);
587 pmap_delayed_invl_finish_unblock(u_long new_gen)
589 struct turnstile *ts;
591 turnstile_chain_lock(&invl_gen_ts);
592 ts = turnstile_lookup(&invl_gen_ts);
594 pmap_invl_gen = new_gen;
596 turnstile_broadcast(ts, TS_SHARED_QUEUE);
597 turnstile_unpend(ts);
599 turnstile_chain_unlock(&invl_gen_ts);
603 * Start a new Delayed Invalidation (DI) block of code, executed by
604 * the current thread. Within a DI block, the current thread may
605 * destroy both the page table and PV list entries for a mapping and
606 * then release the corresponding PV list lock before ensuring that
607 * the mapping is flushed from the TLBs of any processors with the
611 pmap_delayed_invl_start_l(void)
613 struct pmap_invl_gen *invl_gen;
616 invl_gen = &curthread->td_md.md_invl_gen;
617 PMAP_ASSERT_NOT_IN_DI();
618 mtx_lock(&invl_gen_mtx);
619 if (LIST_EMPTY(&pmap_invl_gen_tracker))
620 currgen = pmap_invl_gen;
622 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
623 invl_gen->gen = currgen + 1;
624 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
625 mtx_unlock(&invl_gen_mtx);
629 * Finish the DI block, previously started by the current thread. All
630 * required TLB flushes for the pages marked by
631 * pmap_delayed_invl_page() must be finished before this function is
634 * This function works by bumping the global DI generation number to
635 * the generation number of the current thread's DI, unless there is a
636 * pending DI that started earlier. In the latter case, bumping the
637 * global DI generation number would incorrectly signal that the
638 * earlier DI had finished. Instead, this function bumps the earlier
639 * DI's generation number to match the generation number of the
640 * current thread's DI.
643 pmap_delayed_invl_finish_l(void)
645 struct pmap_invl_gen *invl_gen, *next;
647 invl_gen = &curthread->td_md.md_invl_gen;
648 KASSERT(invl_gen->gen != 0, ("missed invl_start"));
649 mtx_lock(&invl_gen_mtx);
650 next = LIST_NEXT(invl_gen, link);
652 pmap_delayed_invl_finish_unblock(invl_gen->gen);
654 next->gen = invl_gen->gen;
655 LIST_REMOVE(invl_gen, link);
656 mtx_unlock(&invl_gen_mtx);
661 pmap_not_in_di_u(void)
663 struct pmap_invl_gen *invl_gen;
665 invl_gen = &curthread->td_md.md_invl_gen;
666 return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
670 pmap_thread_init_invl_gen_u(struct thread *td)
672 struct pmap_invl_gen *invl_gen;
674 invl_gen = &td->td_md.md_invl_gen;
676 invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
680 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
682 uint64_t new_high, new_low, old_high, old_low;
685 old_low = new_low = 0;
686 old_high = new_high = (uintptr_t)0;
688 __asm volatile("lock;cmpxchg16b\t%1;sete\t%0"
689 : "=r" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
690 : "b"(new_low), "c" (new_high)
693 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
696 out->next = (void *)old_high;
699 out->next = (void *)new_high;
705 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
706 struct pmap_invl_gen *new_val)
708 uint64_t new_high, new_low, old_high, old_low;
711 new_low = new_val->gen;
712 new_high = (uintptr_t)new_val->next;
713 old_low = old_val->gen;
714 old_high = (uintptr_t)old_val->next;
716 __asm volatile("lock;cmpxchg16b\t%1;sete\t%0"
717 : "=r" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
718 : "b"(new_low), "c" (new_high)
724 static long invl_start_restart;
725 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_start_restart, CTLFLAG_RD,
726 &invl_start_restart, 0,
728 static long invl_finish_restart;
729 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
730 &invl_finish_restart, 0,
732 static int invl_max_qlen;
733 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
738 static struct lock_delay_config __read_frequently di_delay;
739 LOCK_DELAY_SYSINIT_DEFAULT(di_delay);
742 pmap_delayed_invl_start_u(void)
744 struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
746 struct lock_delay_arg lda;
754 invl_gen = &td->td_md.md_invl_gen;
755 PMAP_ASSERT_NOT_IN_DI();
756 lock_delay_arg_init(&lda, &di_delay);
757 invl_gen->saved_pri = 0;
758 pri = td->td_base_pri;
761 pri = td->td_base_pri;
763 invl_gen->saved_pri = pri;
770 for (p = &pmap_invl_gen_head;; p = prev.next) {
772 prevl = atomic_load_ptr(&p->next);
773 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
774 PV_STAT(atomic_add_long(&invl_start_restart, 1));
780 prev.next = (void *)prevl;
783 if ((ii = invl_max_qlen) < i)
784 atomic_cmpset_int(&invl_max_qlen, ii, i);
787 if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
788 PV_STAT(atomic_add_long(&invl_start_restart, 1));
793 new_prev.gen = prev.gen;
794 new_prev.next = invl_gen;
795 invl_gen->gen = prev.gen + 1;
797 /* Formal fence between store to invl->gen and updating *p. */
798 atomic_thread_fence_rel();
801 * After inserting an invl_gen element with invalid bit set,
802 * this thread blocks any other thread trying to enter the
803 * delayed invalidation block. Do not allow to remove us from
804 * the CPU, because it causes starvation for other threads.
809 * ABA for *p is not possible there, since p->gen can only
810 * increase. So if the *p thread finished its di, then
811 * started a new one and got inserted into the list at the
812 * same place, its gen will appear greater than the previously
815 if (!pmap_di_store_invl(p, &prev, &new_prev)) {
817 PV_STAT(atomic_add_long(&invl_start_restart, 1));
823 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
824 * invl_gen->next, allowing other threads to iterate past us.
825 * pmap_di_store_invl() provides fence between the generation
826 * write and the update of next.
828 invl_gen->next = NULL;
833 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
834 struct pmap_invl_gen *p)
836 struct pmap_invl_gen prev, new_prev;
840 * Load invl_gen->gen after setting invl_gen->next
841 * PMAP_INVL_GEN_NEXT_INVALID. This prevents larger
842 * generations to propagate to our invl_gen->gen. Lock prefix
843 * in atomic_set_ptr() worked as seq_cst fence.
845 mygen = atomic_load_long(&invl_gen->gen);
847 if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
850 KASSERT(prev.gen < mygen,
851 ("invalid di gen sequence %lu %lu", prev.gen, mygen));
852 new_prev.gen = mygen;
853 new_prev.next = (void *)((uintptr_t)invl_gen->next &
854 ~PMAP_INVL_GEN_NEXT_INVALID);
856 /* Formal fence between load of prev and storing update to it. */
857 atomic_thread_fence_rel();
859 return (pmap_di_store_invl(p, &prev, &new_prev));
863 pmap_delayed_invl_finish_u(void)
865 struct pmap_invl_gen *invl_gen, *p;
867 struct lock_delay_arg lda;
871 invl_gen = &td->td_md.md_invl_gen;
872 KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
873 KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
874 ("missed invl_start: INVALID"));
875 lock_delay_arg_init(&lda, &di_delay);
878 for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
879 prevl = atomic_load_ptr(&p->next);
880 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
881 PV_STAT(atomic_add_long(&invl_finish_restart, 1));
885 if ((void *)prevl == invl_gen)
890 * It is legitimate to not find ourself on the list if a
891 * thread before us finished its DI and started it again.
893 if (__predict_false(p == NULL)) {
894 PV_STAT(atomic_add_long(&invl_finish_restart, 1));
900 atomic_set_ptr((uintptr_t *)&invl_gen->next,
901 PMAP_INVL_GEN_NEXT_INVALID);
902 if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
903 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
904 PMAP_INVL_GEN_NEXT_INVALID);
906 PV_STAT(atomic_add_long(&invl_finish_restart, 1));
911 if (atomic_load_int(&pmap_invl_waiters) > 0)
912 pmap_delayed_invl_finish_unblock(0);
913 if (invl_gen->saved_pri != 0) {
915 sched_prio(td, invl_gen->saved_pri);
921 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
923 struct pmap_invl_gen *p, *pn;
928 for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
930 nextl = atomic_load_ptr(&p->next);
931 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
932 td = first ? NULL : __containerof(p, struct thread,
934 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
935 (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
936 td != NULL ? td->td_tid : -1);
942 static long invl_wait;
943 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
944 "Number of times DI invalidation blocked pmap_remove_all/write");
945 static long invl_wait_slow;
946 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD, &invl_wait_slow, 0,
947 "Number of slow invalidation waits for lockless DI");
950 #if VM_NRESERVLEVEL > 0
952 pmap_delayed_invl_genp(vm_page_t m)
957 pa = VM_PAGE_TO_PHYS(m);
958 if (__predict_false((pa) > pmap_last_pa))
959 gen = &pv_dummy_large.pv_invl_gen;
961 gen = &(pa_to_pmdp(pa)->pv_invl_gen);
967 pmap_delayed_invl_genp(vm_page_t m)
970 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
975 pmap_delayed_invl_callout_func(void *arg __unused)
978 if (atomic_load_int(&pmap_invl_waiters) == 0)
980 pmap_delayed_invl_finish_unblock(0);
984 pmap_delayed_invl_callout_init(void *arg __unused)
987 if (pmap_di_locked())
989 callout_init(&pmap_invl_callout, 1);
990 pmap_invl_callout_inited = true;
992 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
993 pmap_delayed_invl_callout_init, NULL);
996 * Ensure that all currently executing DI blocks, that need to flush
997 * TLB for the given page m, actually flushed the TLB at the time the
998 * function returned. If the page m has an empty PV list and we call
999 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1000 * valid mapping for the page m in either its page table or TLB.
1002 * This function works by blocking until the global DI generation
1003 * number catches up with the generation number associated with the
1004 * given page m and its PV list. Since this function's callers
1005 * typically own an object lock and sometimes own a page lock, it
1006 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
1010 pmap_delayed_invl_wait_l(vm_page_t m)
1014 bool accounted = false;
1017 m_gen = pmap_delayed_invl_genp(m);
1018 while (*m_gen > pmap_invl_gen) {
1021 atomic_add_long(&invl_wait, 1);
1025 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1030 pmap_delayed_invl_wait_u(vm_page_t m)
1033 struct lock_delay_arg lda;
1037 m_gen = pmap_delayed_invl_genp(m);
1038 lock_delay_arg_init(&lda, &di_delay);
1039 while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1040 if (fast || !pmap_invl_callout_inited) {
1041 PV_STAT(atomic_add_long(&invl_wait, 1));
1046 * The page's invalidation generation number
1047 * is still below the current thread's number.
1048 * Prepare to block so that we do not waste
1049 * CPU cycles or worse, suffer livelock.
1051 * Since it is impossible to block without
1052 * racing with pmap_delayed_invl_finish_u(),
1053 * prepare for the race by incrementing
1054 * pmap_invl_waiters and arming a 1-tick
1055 * callout which will unblock us if we lose
1058 atomic_add_int(&pmap_invl_waiters, 1);
1061 * Re-check the current thread's invalidation
1062 * generation after incrementing
1063 * pmap_invl_waiters, so that there is no race
1064 * with pmap_delayed_invl_finish_u() setting
1065 * the page generation and checking
1066 * pmap_invl_waiters. The only race allowed
1067 * is for a missed unblock, which is handled
1071 atomic_load_long(&pmap_invl_gen_head.gen)) {
1072 callout_reset(&pmap_invl_callout, 1,
1073 pmap_delayed_invl_callout_func, NULL);
1074 PV_STAT(atomic_add_long(&invl_wait_slow, 1));
1075 pmap_delayed_invl_wait_block(m_gen,
1076 &pmap_invl_gen_head.gen);
1078 atomic_add_int(&pmap_invl_waiters, -1);
1083 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1086 return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1087 pmap_thread_init_invl_gen_u);
1090 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1093 return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1094 pmap_delayed_invl_start_u);
1097 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1100 return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1101 pmap_delayed_invl_finish_u);
1104 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1107 return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1108 pmap_delayed_invl_wait_u);
1112 * Mark the page m's PV list as participating in the current thread's
1113 * DI block. Any threads concurrently using m's PV list to remove or
1114 * restrict all mappings to m will wait for the current thread's DI
1115 * block to complete before proceeding.
1117 * The function works by setting the DI generation number for m's PV
1118 * list to at least the DI generation number of the current thread.
1119 * This forces a caller of pmap_delayed_invl_wait() to block until
1120 * current thread calls pmap_delayed_invl_finish().
1123 pmap_delayed_invl_page(vm_page_t m)
1127 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1128 gen = curthread->td_md.md_invl_gen.gen;
1131 m_gen = pmap_delayed_invl_genp(m);
1139 static caddr_t crashdumpmap;
1142 * Internal flags for pmap_enter()'s helper functions.
1144 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
1145 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
1148 * Internal flags for pmap_mapdev_internal() and
1149 * pmap_change_props_locked().
1151 #define MAPDEV_FLUSHCACHE 0x00000001 /* Flush cache after mapping. */
1152 #define MAPDEV_SETATTR 0x00000002 /* Modify existing attrs. */
1153 #define MAPDEV_ASSERTVALID 0x00000004 /* Assert mapping validity. */
1155 TAILQ_HEAD(pv_chunklist, pv_chunk);
1157 static void free_pv_chunk(struct pv_chunk *pc);
1158 static void free_pv_chunk_batch(struct pv_chunklist *batch);
1159 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
1160 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1161 static int popcnt_pc_map_pq(uint64_t *map);
1162 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1163 static void reserve_pv_entries(pmap_t pmap, int needed,
1164 struct rwlock **lockp);
1165 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1166 struct rwlock **lockp);
1167 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1168 u_int flags, struct rwlock **lockp);
1169 #if VM_NRESERVLEVEL > 0
1170 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1171 struct rwlock **lockp);
1173 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1174 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1177 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1178 vm_prot_t prot, int mode, int flags);
1179 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1180 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1181 vm_offset_t va, struct rwlock **lockp);
1182 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1184 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1185 vm_prot_t prot, struct rwlock **lockp);
1186 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1187 u_int flags, vm_page_t m, struct rwlock **lockp);
1188 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1189 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1190 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1191 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted);
1192 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1194 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1196 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1198 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1199 static vm_page_t pmap_large_map_getptp_unlocked(void);
1200 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1201 #if VM_NRESERVLEVEL > 0
1202 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1203 struct rwlock **lockp);
1205 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1207 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1208 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1210 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1211 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1212 static void pmap_pti_wire_pte(void *pte);
1213 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1214 struct spglist *free, struct rwlock **lockp);
1215 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1216 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1217 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1218 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1219 struct spglist *free);
1220 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1221 pd_entry_t *pde, struct spglist *free,
1222 struct rwlock **lockp);
1223 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1224 vm_page_t m, struct rwlock **lockp);
1225 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1227 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1229 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
1230 struct rwlock **lockp);
1231 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
1232 struct rwlock **lockp);
1233 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1234 struct rwlock **lockp);
1236 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1237 struct spglist *free);
1238 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1240 /********************/
1241 /* Inline functions */
1242 /********************/
1244 /* Return a non-clipped PD index for a given VA */
1245 static __inline vm_pindex_t
1246 pmap_pde_pindex(vm_offset_t va)
1248 return (va >> PDRSHIFT);
1252 /* Return a pointer to the PML4 slot that corresponds to a VA */
1253 static __inline pml4_entry_t *
1254 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1257 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
1260 /* Return a pointer to the PDP slot that corresponds to a VA */
1261 static __inline pdp_entry_t *
1262 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1266 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1267 return (&pdpe[pmap_pdpe_index(va)]);
1270 /* Return a pointer to the PDP slot that corresponds to a VA */
1271 static __inline pdp_entry_t *
1272 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1274 pml4_entry_t *pml4e;
1277 PG_V = pmap_valid_bit(pmap);
1278 pml4e = pmap_pml4e(pmap, va);
1279 if ((*pml4e & PG_V) == 0)
1281 return (pmap_pml4e_to_pdpe(pml4e, va));
1284 /* Return a pointer to the PD slot that corresponds to a VA */
1285 static __inline pd_entry_t *
1286 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1290 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1291 return (&pde[pmap_pde_index(va)]);
1294 /* Return a pointer to the PD slot that corresponds to a VA */
1295 static __inline pd_entry_t *
1296 pmap_pde(pmap_t pmap, vm_offset_t va)
1301 PG_V = pmap_valid_bit(pmap);
1302 pdpe = pmap_pdpe(pmap, va);
1303 if (pdpe == NULL || (*pdpe & PG_V) == 0)
1305 return (pmap_pdpe_to_pde(pdpe, va));
1308 /* Return a pointer to the PT slot that corresponds to a VA */
1309 static __inline pt_entry_t *
1310 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1314 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1315 return (&pte[pmap_pte_index(va)]);
1318 /* Return a pointer to the PT slot that corresponds to a VA */
1319 static __inline pt_entry_t *
1320 pmap_pte(pmap_t pmap, vm_offset_t va)
1325 PG_V = pmap_valid_bit(pmap);
1326 pde = pmap_pde(pmap, va);
1327 if (pde == NULL || (*pde & PG_V) == 0)
1329 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
1330 return ((pt_entry_t *)pde);
1331 return (pmap_pde_to_pte(pde, va));
1334 static __inline void
1335 pmap_resident_count_inc(pmap_t pmap, int count)
1338 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1339 pmap->pm_stats.resident_count += count;
1342 static __inline void
1343 pmap_resident_count_dec(pmap_t pmap, int count)
1346 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1347 KASSERT(pmap->pm_stats.resident_count >= count,
1348 ("pmap %p resident count underflow %ld %d", pmap,
1349 pmap->pm_stats.resident_count, count));
1350 pmap->pm_stats.resident_count -= count;
1353 PMAP_INLINE pt_entry_t *
1354 vtopte(vm_offset_t va)
1356 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
1358 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1360 return (PTmap + ((va >> PAGE_SHIFT) & mask));
1363 static __inline pd_entry_t *
1364 vtopde(vm_offset_t va)
1366 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
1368 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1370 return (PDmap + ((va >> PDRSHIFT) & mask));
1374 allocpages(vm_paddr_t *firstaddr, int n)
1379 bzero((void *)ret, n * PAGE_SIZE);
1380 *firstaddr += n * PAGE_SIZE;
1384 CTASSERT(powerof2(NDMPML4E));
1386 /* number of kernel PDP slots */
1387 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
1390 nkpt_init(vm_paddr_t addr)
1397 pt_pages = howmany(addr, 1 << PDRSHIFT);
1398 pt_pages += NKPDPE(pt_pages);
1401 * Add some slop beyond the bare minimum required for bootstrapping
1404 * This is quite important when allocating KVA for kernel modules.
1405 * The modules are required to be linked in the negative 2GB of
1406 * the address space. If we run out of KVA in this region then
1407 * pmap_growkernel() will need to allocate page table pages to map
1408 * the entire 512GB of KVA space which is an unnecessary tax on
1411 * Secondly, device memory mapped as part of setting up the low-
1412 * level console(s) is taken from KVA, starting at virtual_avail.
1413 * This is because cninit() is called after pmap_bootstrap() but
1414 * before vm_init() and pmap_init(). 20MB for a frame buffer is
1417 pt_pages += 32; /* 64MB additional slop. */
1423 * Returns the proper write/execute permission for a physical page that is
1424 * part of the initial boot allocations.
1426 * If the page has kernel text, it is marked as read-only. If the page has
1427 * kernel read-only data, it is marked as read-only/not-executable. If the
1428 * page has only read-write data, it is marked as read-write/not-executable.
1429 * If the page is below/above the kernel range, it is marked as read-write.
1431 * This function operates on 2M pages, since we map the kernel space that
1434 static inline pt_entry_t
1435 bootaddr_rwx(vm_paddr_t pa)
1439 * The kernel is loaded at a 2MB-aligned address, and memory below that
1440 * need not be executable. The .bss section is padded to a 2MB
1441 * boundary, so memory following the kernel need not be executable
1442 * either. Preloaded kernel modules have their mapping permissions
1443 * fixed up by the linker.
1445 if (pa < trunc_2mpage(btext - KERNBASE) ||
1446 pa >= trunc_2mpage(_end - KERNBASE))
1447 return (X86_PG_RW | pg_nx);
1450 * The linker should ensure that the read-only and read-write
1451 * portions don't share the same 2M page, so this shouldn't
1452 * impact read-only data. However, in any case, any page with
1453 * read-write data needs to be read-write.
1455 if (pa >= trunc_2mpage(brwsection - KERNBASE))
1456 return (X86_PG_RW | pg_nx);
1459 * Mark any 2M page containing kernel text as read-only. Mark
1460 * other pages with read-only data as read-only and not executable.
1461 * (It is likely a small portion of the read-only data section will
1462 * be marked as read-only, but executable. This should be acceptable
1463 * since the read-only protection will keep the data from changing.)
1464 * Note that fixups to the .text section will still work until we
1467 if (pa < round_2mpage(etext - KERNBASE))
1473 create_pagetables(vm_paddr_t *firstaddr)
1475 int i, j, ndm1g, nkpdpe, nkdmpde;
1479 uint64_t DMPDkernphys;
1481 /* Allocate page table pages for the direct map */
1482 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1483 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1485 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1486 if (ndmpdpphys > NDMPML4E) {
1488 * Each NDMPML4E allows 512 GB, so limit to that,
1489 * and then readjust ndmpdp and ndmpdpphys.
1491 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1492 Maxmem = atop(NDMPML4E * NBPML4);
1493 ndmpdpphys = NDMPML4E;
1494 ndmpdp = NDMPML4E * NPDEPG;
1496 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1498 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1500 * Calculate the number of 1G pages that will fully fit in
1503 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1506 * Allocate 2M pages for the kernel. These will be used in
1507 * place of the first one or more 1G pages from ndm1g.
1509 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
1510 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1513 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1514 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1516 /* Allocate pages */
1517 KPML4phys = allocpages(firstaddr, 1);
1518 KPDPphys = allocpages(firstaddr, NKPML4E);
1521 * Allocate the initial number of kernel page table pages required to
1522 * bootstrap. We defer this until after all memory-size dependent
1523 * allocations are done (e.g. direct map), so that we don't have to
1524 * build in too much slop in our estimate.
1526 * Note that when NKPML4E > 1, we have an empty page underneath
1527 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1528 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1530 nkpt_init(*firstaddr);
1531 nkpdpe = NKPDPE(nkpt);
1533 KPTphys = allocpages(firstaddr, nkpt);
1534 KPDphys = allocpages(firstaddr, nkpdpe);
1537 * Connect the zero-filled PT pages to their PD entries. This
1538 * implicitly maps the PT pages at their correct locations within
1541 pd_p = (pd_entry_t *)KPDphys;
1542 for (i = 0; i < nkpt; i++)
1543 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1546 * Map from physical address zero to the end of loader preallocated
1547 * memory using 2MB pages. This replaces some of the PD entries
1550 for (i = 0; (i << PDRSHIFT) < KERNend; i++)
1551 /* Preset PG_M and PG_A because demotion expects it. */
1552 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1553 X86_PG_M | X86_PG_A | bootaddr_rwx(i << PDRSHIFT);
1556 * Because we map the physical blocks in 2M pages, adjust firstaddr
1557 * to record the physical blocks we've actually mapped into kernel
1558 * virtual address space.
1560 if (*firstaddr < round_2mpage(KERNend))
1561 *firstaddr = round_2mpage(KERNend);
1563 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1564 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1565 for (i = 0; i < nkpdpe; i++)
1566 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1569 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1570 * the end of physical memory is not aligned to a 1GB page boundary,
1571 * then the residual physical memory is mapped with 2MB pages. Later,
1572 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1573 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1574 * that are partially used.
1576 pd_p = (pd_entry_t *)DMPDphys;
1577 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1578 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1579 /* Preset PG_M and PG_A because demotion expects it. */
1580 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1581 X86_PG_M | X86_PG_A | pg_nx;
1583 pdp_p = (pdp_entry_t *)DMPDPphys;
1584 for (i = 0; i < ndm1g; i++) {
1585 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1586 /* Preset PG_M and PG_A because demotion expects it. */
1587 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1588 X86_PG_M | X86_PG_A | pg_nx;
1590 for (j = 0; i < ndmpdp; i++, j++) {
1591 pdp_p[i] = DMPDphys + ptoa(j);
1592 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1596 * Instead of using a 1G page for the memory containing the kernel,
1597 * use 2M pages with read-only and no-execute permissions. (If using 1G
1598 * pages, this will partially overwrite the PDPEs above.)
1601 pd_p = (pd_entry_t *)DMPDkernphys;
1602 for (i = 0; i < (NPDEPG * nkdmpde); i++)
1603 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1604 X86_PG_M | X86_PG_A | pg_nx |
1605 bootaddr_rwx(i << PDRSHIFT);
1606 for (i = 0; i < nkdmpde; i++)
1607 pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
1611 /* And recursively map PML4 to itself in order to get PTmap */
1612 p4_p = (pml4_entry_t *)KPML4phys;
1613 p4_p[PML4PML4I] = KPML4phys;
1614 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1616 /* Connect the Direct Map slot(s) up to the PML4. */
1617 for (i = 0; i < ndmpdpphys; i++) {
1618 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1619 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1622 /* Connect the KVA slots up to the PML4 */
1623 for (i = 0; i < NKPML4E; i++) {
1624 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1625 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1630 * Bootstrap the system enough to run with virtual memory.
1632 * On amd64 this is called after mapping has already been enabled
1633 * and just syncs the pmap module with what has already been done.
1634 * [We can't call it easily with mapping off since the kernel is not
1635 * mapped with PA == VA, hence we would have to relocate every address
1636 * from the linked base (virtual) address "KERNBASE" to the actual
1637 * (physical) address starting relative to 0]
1640 pmap_bootstrap(vm_paddr_t *firstaddr)
1643 pt_entry_t *pte, *pcpu_pte;
1644 uint64_t cr4, pcpu_phys;
1648 KERNend = *firstaddr;
1649 res = atop(KERNend - (vm_paddr_t)kernphys);
1655 * Create an initial set of page tables to run the kernel in.
1657 create_pagetables(firstaddr);
1659 pcpu_phys = allocpages(firstaddr, MAXCPU);
1662 * Add a physical memory segment (vm_phys_seg) corresponding to the
1663 * preallocated kernel page table pages so that vm_page structures
1664 * representing these pages will be created. The vm_page structures
1665 * are required for promotion of the corresponding kernel virtual
1666 * addresses to superpage mappings.
1668 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1671 * Account for the virtual addresses mapped by create_pagetables().
1673 virtual_avail = (vm_offset_t)KERNBASE + round_2mpage(KERNend);
1674 virtual_end = VM_MAX_KERNEL_ADDRESS;
1677 * Enable PG_G global pages, then switch to the kernel page
1678 * table from the bootstrap page table. After the switch, it
1679 * is possible to enable SMEP and SMAP since PG_U bits are
1685 load_cr3(KPML4phys);
1686 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1688 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1693 * Initialize the kernel pmap (which is statically allocated).
1694 * Count bootstrap data as being resident in case any of this data is
1695 * later unmapped (using pmap_remove()) and freed.
1697 PMAP_LOCK_INIT(kernel_pmap);
1698 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1699 kernel_pmap->pm_cr3 = KPML4phys;
1700 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1701 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1702 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1703 kernel_pmap->pm_stats.resident_count = res;
1704 kernel_pmap->pm_flags = pmap_flags;
1707 * Initialize the TLB invalidations generation number lock.
1709 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1712 * Reserve some special page table entries/VA space for temporary
1715 #define SYSMAP(c, p, v, n) \
1716 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1722 * Crashdump maps. The first page is reused as CMAP1 for the
1725 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1726 CADDR1 = crashdumpmap;
1728 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
1731 for (i = 0; i < MAXCPU; i++) {
1732 pcpu_pte[i] = (pcpu_phys + ptoa(i)) | X86_PG_V | X86_PG_RW |
1733 pg_g | pg_nx | X86_PG_M | X86_PG_A;
1735 STAILQ_INIT(&cpuhead);
1736 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
1737 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
1738 amd64_bsp_pcpu_init1(&__pcpu[0]);
1739 amd64_bsp_ist_init(&__pcpu[0]);
1740 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
1741 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
1744 * Initialize the PAT MSR.
1745 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1746 * side-effect, invalidates stale PG_G TLB entries that might
1747 * have been created in our pre-boot environment.
1751 /* Initialize TLB Context Id. */
1752 if (pmap_pcid_enabled) {
1753 for (i = 0; i < MAXCPU; i++) {
1754 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1755 kernel_pmap->pm_pcids[i].pm_gen = 1;
1759 * PMAP_PCID_KERN + 1 is used for initialization of
1760 * proc0 pmap. The pmap' pcid state might be used by
1761 * EFIRT entry before first context switch, so it
1762 * needs to be valid.
1764 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
1765 PCPU_SET(pcid_gen, 1);
1768 * pcpu area for APs is zeroed during AP startup.
1769 * pc_pcid_next and pc_pcid_gen are initialized by AP
1770 * during pcpu setup.
1772 load_cr4(rcr4() | CR4_PCIDE);
1777 * Setup the PAT MSR.
1786 /* Bail if this CPU doesn't implement PAT. */
1787 if ((cpu_feature & CPUID_PAT) == 0)
1790 /* Set default PAT index table. */
1791 for (i = 0; i < PAT_INDEX_SIZE; i++)
1793 pat_index[PAT_WRITE_BACK] = 0;
1794 pat_index[PAT_WRITE_THROUGH] = 1;
1795 pat_index[PAT_UNCACHEABLE] = 3;
1796 pat_index[PAT_WRITE_COMBINING] = 6;
1797 pat_index[PAT_WRITE_PROTECTED] = 5;
1798 pat_index[PAT_UNCACHED] = 2;
1801 * Initialize default PAT entries.
1802 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1803 * Program 5 and 6 as WP and WC.
1805 * Leave 4 and 7 as WB and UC. Note that a recursive page table
1806 * mapping for a 2M page uses a PAT value with the bit 3 set due
1807 * to its overload with PG_PS.
1809 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1810 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1811 PAT_VALUE(2, PAT_UNCACHED) |
1812 PAT_VALUE(3, PAT_UNCACHEABLE) |
1813 PAT_VALUE(4, PAT_WRITE_BACK) |
1814 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1815 PAT_VALUE(6, PAT_WRITE_COMBINING) |
1816 PAT_VALUE(7, PAT_UNCACHEABLE);
1820 load_cr4(cr4 & ~CR4_PGE);
1822 /* Disable caches (CD = 1, NW = 0). */
1824 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1826 /* Flushes caches and TLBs. */
1830 /* Update PAT and index table. */
1831 wrmsr(MSR_PAT, pat_msr);
1833 /* Flush caches and TLBs again. */
1837 /* Restore caches and PGE. */
1843 * Initialize a vm_page's machine-dependent fields.
1846 pmap_page_init(vm_page_t m)
1849 TAILQ_INIT(&m->md.pv_list);
1850 m->md.pat_mode = PAT_WRITE_BACK;
1853 #if VM_NRESERVLEVEL > 0
1855 pmap_init_pv_table(void)
1857 struct pmap_large_md_page *pvd;
1859 long start, end, highest, pv_npg;
1860 int domain, i, j, pages;
1863 * We strongly depend on the size being a power of two, so the assert
1864 * is overzealous. However, should the struct be resized to a
1865 * different power of two, the code below needs to be revisited.
1867 CTASSERT((sizeof(*pvd) == 64));
1870 * Calculate the size of the array.
1872 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
1873 pv_npg = howmany(pmap_last_pa, NBPDR);
1874 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
1876 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1877 if (pv_table == NULL)
1878 panic("%s: kva_alloc failed\n", __func__);
1881 * Iterate physical segments to allocate space for respective pages.
1885 for (i = 0; i < vm_phys_nsegs; i++) {
1886 end = vm_phys_segs[i].end / NBPDR;
1887 domain = vm_phys_segs[i].domain;
1892 start = highest + 1;
1893 pvd = &pv_table[start];
1895 pages = end - start + 1;
1896 s = round_page(pages * sizeof(*pvd));
1897 highest = start + (s / sizeof(*pvd)) - 1;
1899 for (j = 0; j < s; j += PAGE_SIZE) {
1900 vm_page_t m = vm_page_alloc_domain(NULL, 0,
1901 domain, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ);
1903 panic("vm_page_alloc_domain failed for %lx\n", (vm_offset_t)pvd + j);
1904 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1907 for (j = 0; j < s / sizeof(*pvd); j++) {
1908 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1909 TAILQ_INIT(&pvd->pv_page.pv_list);
1910 pvd->pv_page.pv_gen = 0;
1911 pvd->pv_page.pat_mode = 0;
1912 pvd->pv_invl_gen = 0;
1916 pvd = &pv_dummy_large;
1917 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1918 TAILQ_INIT(&pvd->pv_page.pv_list);
1919 pvd->pv_page.pv_gen = 0;
1920 pvd->pv_page.pat_mode = 0;
1921 pvd->pv_invl_gen = 0;
1925 pmap_init_pv_table(void)
1931 * Initialize the pool of pv list locks.
1933 for (i = 0; i < NPV_LIST_LOCKS; i++)
1934 rw_init(&pv_list_locks[i], "pmap pv list");
1937 * Calculate the size of the pv head table for superpages.
1939 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1942 * Allocate memory for the pv head table for superpages.
1944 s = (vm_size_t)pv_npg * sizeof(struct md_page);
1946 pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
1947 for (i = 0; i < pv_npg; i++)
1948 TAILQ_INIT(&pv_table[i].pv_list);
1949 TAILQ_INIT(&pv_dummy.pv_list);
1954 * Initialize the pmap module.
1955 * Called by vm_init, to initialize any structures that the pmap
1956 * system needs to map virtual memory.
1961 struct pmap_preinit_mapping *ppim;
1963 int error, i, ret, skz63;
1965 /* L1TF, reserve page @0 unconditionally */
1966 vm_page_blacklist_add(0, bootverbose);
1968 /* Detect bare-metal Skylake Server and Skylake-X. */
1969 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1970 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1972 * Skylake-X errata SKZ63. Processor May Hang When
1973 * Executing Code In an HLE Transaction Region between
1974 * 40000000H and 403FFFFFH.
1976 * Mark the pages in the range as preallocated. It
1977 * seems to be impossible to distinguish between
1978 * Skylake Server and Skylake X.
1981 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1984 printf("SKZ63: skipping 4M RAM starting "
1985 "at physical 1G\n");
1986 for (i = 0; i < atop(0x400000); i++) {
1987 ret = vm_page_blacklist_add(0x40000000 +
1989 if (!ret && bootverbose)
1990 printf("page at %#lx already used\n",
1991 0x40000000 + ptoa(i));
1997 * Initialize the vm page array entries for the kernel pmap's
2000 PMAP_LOCK(kernel_pmap);
2001 for (i = 0; i < nkpt; i++) {
2002 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2003 KASSERT(mpte >= vm_page_array &&
2004 mpte < &vm_page_array[vm_page_array_size],
2005 ("pmap_init: page table page is out of range"));
2006 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2007 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2008 mpte->ref_count = 1;
2011 * Collect the page table pages that were replaced by a 2MB
2012 * page in create_pagetables(). They are zero filled.
2014 if (i << PDRSHIFT < KERNend &&
2015 pmap_insert_pt_page(kernel_pmap, mpte, false))
2016 panic("pmap_init: pmap_insert_pt_page failed");
2018 PMAP_UNLOCK(kernel_pmap);
2022 * If the kernel is running on a virtual machine, then it must assume
2023 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2024 * be prepared for the hypervisor changing the vendor and family that
2025 * are reported by CPUID. Consequently, the workaround for AMD Family
2026 * 10h Erratum 383 is enabled if the processor's feature set does not
2027 * include at least one feature that is only supported by older Intel
2028 * or newer AMD processors.
2030 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2031 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2032 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2034 workaround_erratum383 = 1;
2037 * Are large page mappings enabled?
2039 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2040 if (pg_ps_enabled) {
2041 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2042 ("pmap_init: can't assign to pagesizes[1]"));
2043 pagesizes[1] = NBPDR;
2047 * Initialize the pv chunk list mutex.
2049 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
2051 pmap_init_pv_table();
2053 pmap_initialized = 1;
2054 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2055 ppim = pmap_preinit_mapping + i;
2058 /* Make the direct map consistent */
2059 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2060 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2061 ppim->sz, ppim->mode);
2065 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2066 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2069 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2070 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2071 (vmem_addr_t *)&qframe);
2073 panic("qframe allocation failed");
2076 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2077 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2078 lm_ents = LMEPML4I - LMSPML4I + 1;
2080 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2081 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2083 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2084 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2085 if (large_vmem == NULL) {
2086 printf("pmap: cannot create large map\n");
2089 for (i = 0; i < lm_ents; i++) {
2090 m = pmap_large_map_getptp_unlocked();
2091 kernel_pmap->pm_pml4[LMSPML4I + i] = X86_PG_V |
2092 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2098 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2099 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2100 "Maximum number of PML4 entries for use by large map (tunable). "
2101 "Each entry corresponds to 512GB of address space.");
2103 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
2104 "2MB page mapping counters");
2106 static u_long pmap_pde_demotions;
2107 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
2108 &pmap_pde_demotions, 0, "2MB page demotions");
2110 static u_long pmap_pde_mappings;
2111 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2112 &pmap_pde_mappings, 0, "2MB page mappings");
2114 static u_long pmap_pde_p_failures;
2115 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2116 &pmap_pde_p_failures, 0, "2MB page promotion failures");
2118 static u_long pmap_pde_promotions;
2119 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2120 &pmap_pde_promotions, 0, "2MB page promotions");
2122 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
2123 "1GB page mapping counters");
2125 static u_long pmap_pdpe_demotions;
2126 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2127 &pmap_pdpe_demotions, 0, "1GB page demotions");
2129 /***************************************************
2130 * Low level helper routines.....
2131 ***************************************************/
2134 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2136 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2138 switch (pmap->pm_type) {
2141 /* Verify that both PAT bits are not set at the same time */
2142 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2143 ("Invalid PAT bits in entry %#lx", entry));
2145 /* Swap the PAT bits if one of them is set */
2146 if ((entry & x86_pat_bits) != 0)
2147 entry ^= x86_pat_bits;
2151 * Nothing to do - the memory attributes are represented
2152 * the same way for regular pages and superpages.
2156 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2163 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2166 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2167 pat_index[(int)mode] >= 0);
2171 * Determine the appropriate bits to set in a PTE or PDE for a specified
2175 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
2177 int cache_bits, pat_flag, pat_idx;
2179 if (!pmap_is_valid_memattr(pmap, mode))
2180 panic("Unknown caching mode %d\n", mode);
2182 switch (pmap->pm_type) {
2185 /* The PAT bit is different for PTE's and PDE's. */
2186 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2188 /* Map the caching mode to a PAT index. */
2189 pat_idx = pat_index[mode];
2191 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2194 cache_bits |= pat_flag;
2196 cache_bits |= PG_NC_PCD;
2198 cache_bits |= PG_NC_PWT;
2202 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2206 panic("unsupported pmap type %d", pmap->pm_type);
2209 return (cache_bits);
2213 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
2217 switch (pmap->pm_type) {
2220 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2223 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2226 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2233 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2235 int pat_flag, pat_idx;
2238 switch (pmap->pm_type) {
2241 /* The PAT bit is different for PTE's and PDE's. */
2242 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2244 if ((pte & pat_flag) != 0)
2246 if ((pte & PG_NC_PCD) != 0)
2248 if ((pte & PG_NC_PWT) != 0)
2252 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2253 panic("EPT PTE %#lx has no PAT memory type", pte);
2254 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2258 /* See pmap_init_pat(). */
2268 pmap_ps_enabled(pmap_t pmap)
2271 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2275 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2278 switch (pmap->pm_type) {
2285 * This is a little bogus since the generation number is
2286 * supposed to be bumped up when a region of the address
2287 * space is invalidated in the page tables.
2289 * In this case the old PDE entry is valid but yet we want
2290 * to make sure that any mappings using the old entry are
2291 * invalidated in the TLB.
2293 * The reason this works as expected is because we rendezvous
2294 * "all" host cpus and force any vcpu context to exit as a
2297 atomic_add_acq_long(&pmap->pm_eptgen, 1);
2300 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2302 pde_store(pde, newpde);
2306 * After changing the page size for the specified virtual address in the page
2307 * table, flush the corresponding entries from the processor's TLB. Only the
2308 * calling processor's TLB is affected.
2310 * The calling thread must be pinned to a processor.
2313 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2317 if (pmap_type_guest(pmap))
2320 KASSERT(pmap->pm_type == PT_X86,
2321 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2323 PG_G = pmap_global_bit(pmap);
2325 if ((newpde & PG_PS) == 0)
2326 /* Demotion: flush a specific 2MB page mapping. */
2328 else if ((newpde & PG_G) == 0)
2330 * Promotion: flush every 4KB page mapping from the TLB
2331 * because there are too many to flush individually.
2336 * Promotion: flush every 4KB page mapping from the TLB,
2337 * including any global (PG_G) mappings.
2345 * For SMP, these functions have to use the IPI mechanism for coherence.
2347 * N.B.: Before calling any of the following TLB invalidation functions,
2348 * the calling processor must ensure that all stores updating a non-
2349 * kernel page table are globally performed. Otherwise, another
2350 * processor could cache an old, pre-update entry without being
2351 * invalidated. This can happen one of two ways: (1) The pmap becomes
2352 * active on another processor after its pm_active field is checked by
2353 * one of the following functions but before a store updating the page
2354 * table is globally performed. (2) The pmap becomes active on another
2355 * processor before its pm_active field is checked but due to
2356 * speculative loads one of the following functions stills reads the
2357 * pmap as inactive on the other processor.
2359 * The kernel page table is exempt because its pm_active field is
2360 * immutable. The kernel page table is always active on every
2365 * Interrupt the cpus that are executing in the guest context.
2366 * This will force the vcpu to exit and the cached EPT mappings
2367 * will be invalidated by the host before the next vmresume.
2369 static __inline void
2370 pmap_invalidate_ept(pmap_t pmap)
2375 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
2376 ("pmap_invalidate_ept: absurd pm_active"));
2379 * The TLB mappings associated with a vcpu context are not
2380 * flushed each time a different vcpu is chosen to execute.
2382 * This is in contrast with a process's vtop mappings that
2383 * are flushed from the TLB on each context switch.
2385 * Therefore we need to do more than just a TLB shootdown on
2386 * the active cpus in 'pmap->pm_active'. To do this we keep
2387 * track of the number of invalidations performed on this pmap.
2389 * Each vcpu keeps a cache of this counter and compares it
2390 * just before a vmresume. If the counter is out-of-date an
2391 * invept will be done to flush stale mappings from the TLB.
2393 atomic_add_acq_long(&pmap->pm_eptgen, 1);
2396 * Force the vcpu to exit and trap back into the hypervisor.
2398 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
2399 ipi_selected(pmap->pm_active, ipinum);
2404 pmap_invalidate_cpu_mask(pmap_t pmap)
2407 return (pmap == kernel_pmap ? all_cpus : pmap->pm_active);
2411 pmap_invalidate_page_pcid(pmap_t pmap, vm_offset_t va,
2412 const bool invpcid_works1)
2414 struct invpcid_descr d;
2415 uint64_t kcr3, ucr3;
2419 cpuid = PCPU_GET(cpuid);
2420 if (pmap == PCPU_GET(curpmap)) {
2421 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2423 * Because pm_pcid is recalculated on a
2424 * context switch, we must disable switching.
2425 * Otherwise, we might use a stale value
2429 pcid = pmap->pm_pcids[cpuid].pm_pcid;
2430 if (invpcid_works1) {
2431 d.pcid = pcid | PMAP_PCID_USER_PT;
2434 invpcid(&d, INVPCID_ADDR);
2436 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
2437 ucr3 = pmap->pm_ucr3 | pcid |
2438 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2439 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
2444 pmap->pm_pcids[cpuid].pm_gen = 0;
2448 pmap->pm_pcids[i].pm_gen = 0;
2452 * The fence is between stores to pm_gen and the read of the
2453 * pm_active mask. We need to ensure that it is impossible
2454 * for us to miss the bit update in pm_active and
2455 * simultaneously observe a non-zero pm_gen in
2456 * pmap_activate_sw(), otherwise TLB update is missed.
2457 * Without the fence, IA32 allows such an outcome. Note that
2458 * pm_active is updated by a locked operation, which provides
2459 * the reciprocal fence.
2461 atomic_thread_fence_seq_cst();
2465 pmap_invalidate_page_pcid_invpcid(pmap_t pmap, vm_offset_t va)
2468 pmap_invalidate_page_pcid(pmap, va, true);
2472 pmap_invalidate_page_pcid_noinvpcid(pmap_t pmap, vm_offset_t va)
2475 pmap_invalidate_page_pcid(pmap, va, false);
2479 pmap_invalidate_page_nopcid(pmap_t pmap, vm_offset_t va)
2483 DEFINE_IFUNC(static, void, pmap_invalidate_page_mode, (pmap_t, vm_offset_t))
2486 if (pmap_pcid_enabled)
2487 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid :
2488 pmap_invalidate_page_pcid_noinvpcid);
2489 return (pmap_invalidate_page_nopcid);
2493 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
2496 if (pmap_type_guest(pmap)) {
2497 pmap_invalidate_ept(pmap);
2501 KASSERT(pmap->pm_type == PT_X86,
2502 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
2505 if (pmap == kernel_pmap) {
2508 if (pmap == PCPU_GET(curpmap))
2510 pmap_invalidate_page_mode(pmap, va);
2512 smp_masked_invlpg(pmap_invalidate_cpu_mask(pmap), va, pmap);
2516 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
2517 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
2520 pmap_invalidate_range_pcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
2521 const bool invpcid_works1)
2523 struct invpcid_descr d;
2524 uint64_t kcr3, ucr3;
2528 cpuid = PCPU_GET(cpuid);
2529 if (pmap == PCPU_GET(curpmap)) {
2530 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2532 pcid = pmap->pm_pcids[cpuid].pm_pcid;
2533 if (invpcid_works1) {
2534 d.pcid = pcid | PMAP_PCID_USER_PT;
2537 for (; d.addr < eva; d.addr += PAGE_SIZE)
2538 invpcid(&d, INVPCID_ADDR);
2540 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
2541 ucr3 = pmap->pm_ucr3 | pcid |
2542 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2543 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2548 pmap->pm_pcids[cpuid].pm_gen = 0;
2552 pmap->pm_pcids[i].pm_gen = 0;
2554 /* See the comment in pmap_invalidate_page_pcid(). */
2555 atomic_thread_fence_seq_cst();
2559 pmap_invalidate_range_pcid_invpcid(pmap_t pmap, vm_offset_t sva,
2563 pmap_invalidate_range_pcid(pmap, sva, eva, true);
2567 pmap_invalidate_range_pcid_noinvpcid(pmap_t pmap, vm_offset_t sva,
2571 pmap_invalidate_range_pcid(pmap, sva, eva, false);
2575 pmap_invalidate_range_nopcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2579 DEFINE_IFUNC(static, void, pmap_invalidate_range_mode, (pmap_t, vm_offset_t,
2583 if (pmap_pcid_enabled)
2584 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid :
2585 pmap_invalidate_range_pcid_noinvpcid);
2586 return (pmap_invalidate_range_nopcid);
2590 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2594 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
2595 pmap_invalidate_all(pmap);
2599 if (pmap_type_guest(pmap)) {
2600 pmap_invalidate_ept(pmap);
2604 KASSERT(pmap->pm_type == PT_X86,
2605 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
2608 if (pmap == kernel_pmap) {
2609 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2612 if (pmap == PCPU_GET(curpmap)) {
2613 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2616 pmap_invalidate_range_mode(pmap, sva, eva);
2618 smp_masked_invlpg_range(pmap_invalidate_cpu_mask(pmap), sva, eva, pmap);
2623 pmap_invalidate_all_pcid(pmap_t pmap, bool invpcid_works1)
2625 struct invpcid_descr d;
2626 uint64_t kcr3, ucr3;
2630 if (pmap == kernel_pmap) {
2631 if (invpcid_works1) {
2632 bzero(&d, sizeof(d));
2633 invpcid(&d, INVPCID_CTXGLOB);
2638 cpuid = PCPU_GET(cpuid);
2639 if (pmap == PCPU_GET(curpmap)) {
2641 pcid = pmap->pm_pcids[cpuid].pm_pcid;
2642 if (invpcid_works1) {
2646 invpcid(&d, INVPCID_CTX);
2647 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2648 d.pcid |= PMAP_PCID_USER_PT;
2649 invpcid(&d, INVPCID_CTX);
2652 kcr3 = pmap->pm_cr3 | pcid;
2653 ucr3 = pmap->pm_ucr3;
2654 if (ucr3 != PMAP_NO_CR3) {
2655 ucr3 |= pcid | PMAP_PCID_USER_PT;
2656 pmap_pti_pcid_invalidate(ucr3, kcr3);
2663 pmap->pm_pcids[cpuid].pm_gen = 0;
2666 pmap->pm_pcids[i].pm_gen = 0;
2669 /* See the comment in pmap_invalidate_page_pcid(). */
2670 atomic_thread_fence_seq_cst();
2674 pmap_invalidate_all_pcid_invpcid(pmap_t pmap)
2677 pmap_invalidate_all_pcid(pmap, true);
2681 pmap_invalidate_all_pcid_noinvpcid(pmap_t pmap)
2684 pmap_invalidate_all_pcid(pmap, false);
2688 pmap_invalidate_all_nopcid(pmap_t pmap)
2691 if (pmap == kernel_pmap)
2693 else if (pmap == PCPU_GET(curpmap))
2697 DEFINE_IFUNC(static, void, pmap_invalidate_all_mode, (pmap_t))
2700 if (pmap_pcid_enabled)
2701 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid :
2702 pmap_invalidate_all_pcid_noinvpcid);
2703 return (pmap_invalidate_all_nopcid);
2707 pmap_invalidate_all(pmap_t pmap)
2710 if (pmap_type_guest(pmap)) {
2711 pmap_invalidate_ept(pmap);
2715 KASSERT(pmap->pm_type == PT_X86,
2716 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
2719 pmap_invalidate_all_mode(pmap);
2720 smp_masked_invltlb(pmap_invalidate_cpu_mask(pmap), pmap);
2725 pmap_invalidate_cache(void)
2735 cpuset_t invalidate; /* processors that invalidate their TLB */
2740 u_int store; /* processor that updates the PDE */
2744 pmap_update_pde_action(void *arg)
2746 struct pde_action *act = arg;
2748 if (act->store == PCPU_GET(cpuid))
2749 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
2753 pmap_update_pde_teardown(void *arg)
2755 struct pde_action *act = arg;
2757 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
2758 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
2762 * Change the page size for the specified virtual address in a way that
2763 * prevents any possibility of the TLB ever having two entries that map the
2764 * same virtual address using different page sizes. This is the recommended
2765 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
2766 * machine check exception for a TLB state that is improperly diagnosed as a
2770 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2772 struct pde_action act;
2773 cpuset_t active, other_cpus;
2777 cpuid = PCPU_GET(cpuid);
2778 other_cpus = all_cpus;
2779 CPU_CLR(cpuid, &other_cpus);
2780 if (pmap == kernel_pmap || pmap_type_guest(pmap))
2783 active = pmap->pm_active;
2785 if (CPU_OVERLAP(&active, &other_cpus)) {
2787 act.invalidate = active;
2791 act.newpde = newpde;
2792 CPU_SET(cpuid, &active);
2793 smp_rendezvous_cpus(active,
2794 smp_no_rendezvous_barrier, pmap_update_pde_action,
2795 pmap_update_pde_teardown, &act);
2797 pmap_update_pde_store(pmap, pde, newpde);
2798 if (CPU_ISSET(cpuid, &active))
2799 pmap_update_pde_invalidate(pmap, va, newpde);
2805 * Normal, non-SMP, invalidation functions.
2808 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
2810 struct invpcid_descr d;
2811 uint64_t kcr3, ucr3;
2814 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2818 KASSERT(pmap->pm_type == PT_X86,
2819 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2821 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2823 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2824 pmap->pm_ucr3 != PMAP_NO_CR3) {
2826 pcid = pmap->pm_pcids[0].pm_pcid;
2827 if (invpcid_works) {
2828 d.pcid = pcid | PMAP_PCID_USER_PT;
2831 invpcid(&d, INVPCID_ADDR);
2833 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
2834 ucr3 = pmap->pm_ucr3 | pcid |
2835 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2836 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
2840 } else if (pmap_pcid_enabled)
2841 pmap->pm_pcids[0].pm_gen = 0;
2845 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2847 struct invpcid_descr d;
2849 uint64_t kcr3, ucr3;
2851 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2855 KASSERT(pmap->pm_type == PT_X86,
2856 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2858 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2859 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2861 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2862 pmap->pm_ucr3 != PMAP_NO_CR3) {
2864 if (invpcid_works) {
2865 d.pcid = pmap->pm_pcids[0].pm_pcid |
2869 for (; d.addr < eva; d.addr += PAGE_SIZE)
2870 invpcid(&d, INVPCID_ADDR);
2872 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2873 pm_pcid | CR3_PCID_SAVE;
2874 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2875 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2876 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2880 } else if (pmap_pcid_enabled) {
2881 pmap->pm_pcids[0].pm_gen = 0;
2886 pmap_invalidate_all(pmap_t pmap)
2888 struct invpcid_descr d;
2889 uint64_t kcr3, ucr3;
2891 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2895 KASSERT(pmap->pm_type == PT_X86,
2896 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2898 if (pmap == kernel_pmap) {
2899 if (pmap_pcid_enabled && invpcid_works) {
2900 bzero(&d, sizeof(d));
2901 invpcid(&d, INVPCID_CTXGLOB);
2905 } else if (pmap == PCPU_GET(curpmap)) {
2906 if (pmap_pcid_enabled) {
2908 if (invpcid_works) {
2909 d.pcid = pmap->pm_pcids[0].pm_pcid;
2912 invpcid(&d, INVPCID_CTX);
2913 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2914 d.pcid |= PMAP_PCID_USER_PT;
2915 invpcid(&d, INVPCID_CTX);
2918 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2919 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2920 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2921 0].pm_pcid | PMAP_PCID_USER_PT;
2922 pmap_pti_pcid_invalidate(ucr3, kcr3);
2930 } else if (pmap_pcid_enabled) {
2931 pmap->pm_pcids[0].pm_gen = 0;
2936 pmap_invalidate_cache(void)
2943 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2946 pmap_update_pde_store(pmap, pde, newpde);
2947 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2948 pmap_update_pde_invalidate(pmap, va, newpde);
2950 pmap->pm_pcids[0].pm_gen = 0;
2955 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2959 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2960 * by a promotion that did not invalidate the 512 4KB page mappings
2961 * that might exist in the TLB. Consequently, at this point, the TLB
2962 * may hold both 4KB and 2MB page mappings for the address range [va,
2963 * va + NBPDR). Therefore, the entire range must be invalidated here.
2964 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2965 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2966 * single INVLPG suffices to invalidate the 2MB page mapping from the
2969 if ((pde & PG_PROMOTED) != 0)
2970 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2972 pmap_invalidate_page(pmap, va);
2975 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
2976 (vm_offset_t sva, vm_offset_t eva))
2979 if ((cpu_feature & CPUID_SS) != 0)
2980 return (pmap_invalidate_cache_range_selfsnoop);
2981 if ((cpu_feature & CPUID_CLFSH) != 0)
2982 return (pmap_force_invalidate_cache_range);
2983 return (pmap_invalidate_cache_range_all);
2986 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2989 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
2992 KASSERT((sva & PAGE_MASK) == 0,
2993 ("pmap_invalidate_cache_range: sva not page-aligned"));
2994 KASSERT((eva & PAGE_MASK) == 0,
2995 ("pmap_invalidate_cache_range: eva not page-aligned"));
2999 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3002 pmap_invalidate_cache_range_check_align(sva, eva);
3006 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3009 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3012 * XXX: Some CPUs fault, hang, or trash the local APIC
3013 * registers if we use CLFLUSH on the local APIC range. The
3014 * local APIC is always uncached, so we don't need to flush
3015 * for that range anyway.
3017 if (pmap_kextract(sva) == lapic_paddr)
3020 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3022 * Do per-cache line flush. Use the sfence
3023 * instruction to insure that previous stores are
3024 * included in the write-back. The processor
3025 * propagates flush to other processors in the cache
3029 for (; sva < eva; sva += cpu_clflush_line_size)
3034 * Writes are ordered by CLFLUSH on Intel CPUs.
3036 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3038 for (; sva < eva; sva += cpu_clflush_line_size)
3040 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3046 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3049 pmap_invalidate_cache_range_check_align(sva, eva);
3050 pmap_invalidate_cache();
3054 * Remove the specified set of pages from the data and instruction caches.
3056 * In contrast to pmap_invalidate_cache_range(), this function does not
3057 * rely on the CPU's self-snoop feature, because it is intended for use
3058 * when moving pages into a different cache domain.
3061 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3063 vm_offset_t daddr, eva;
3067 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3068 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3069 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3070 pmap_invalidate_cache();
3074 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3076 for (i = 0; i < count; i++) {
3077 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3078 eva = daddr + PAGE_SIZE;
3079 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3088 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3094 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3097 pmap_invalidate_cache_range_check_align(sva, eva);
3099 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3100 pmap_force_invalidate_cache_range(sva, eva);
3104 /* See comment in pmap_force_invalidate_cache_range(). */
3105 if (pmap_kextract(sva) == lapic_paddr)
3109 for (; sva < eva; sva += cpu_clflush_line_size)
3115 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3119 int error, pte_bits;
3121 KASSERT((spa & PAGE_MASK) == 0,
3122 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3123 KASSERT((epa & PAGE_MASK) == 0,
3124 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3126 if (spa < dmaplimit) {
3127 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3129 if (dmaplimit >= epa)
3134 pte_bits = pmap_cache_bits(kernel_pmap, mattr, 0) | X86_PG_RW |
3136 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3138 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3139 pte = vtopte(vaddr);
3140 for (; spa < epa; spa += PAGE_SIZE) {
3142 pte_store(pte, spa | pte_bits);
3144 /* XXXKIB sfences inside flush_cache_range are excessive */
3145 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3148 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3152 * Routine: pmap_extract
3154 * Extract the physical page address associated
3155 * with the given map/virtual_address pair.
3158 pmap_extract(pmap_t pmap, vm_offset_t va)
3162 pt_entry_t *pte, PG_V;
3166 PG_V = pmap_valid_bit(pmap);
3168 pdpe = pmap_pdpe(pmap, va);
3169 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3170 if ((*pdpe & PG_PS) != 0)
3171 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3173 pde = pmap_pdpe_to_pde(pdpe, va);
3174 if ((*pde & PG_V) != 0) {
3175 if ((*pde & PG_PS) != 0) {
3176 pa = (*pde & PG_PS_FRAME) |
3179 pte = pmap_pde_to_pte(pde, va);
3180 pa = (*pte & PG_FRAME) |
3191 * Routine: pmap_extract_and_hold
3193 * Atomically extract and hold the physical page
3194 * with the given pmap and virtual address pair
3195 * if that mapping permits the given protection.
3198 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3200 pd_entry_t pde, *pdep;
3201 pt_entry_t pte, PG_RW, PG_V;
3205 PG_RW = pmap_rw_bit(pmap);
3206 PG_V = pmap_valid_bit(pmap);
3209 pdep = pmap_pde(pmap, va);
3210 if (pdep != NULL && (pde = *pdep)) {
3212 if ((pde & PG_RW) != 0 || (prot & VM_PROT_WRITE) == 0)
3213 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
3216 pte = *pmap_pde_to_pte(pdep, va);
3217 if ((pte & PG_V) != 0 &&
3218 ((pte & PG_RW) != 0 || (prot & VM_PROT_WRITE) == 0))
3219 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3221 if (m != NULL && !vm_page_wire_mapped(m))
3229 pmap_kextract(vm_offset_t va)
3234 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3235 pa = DMAP_TO_PHYS(va);
3236 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3237 pa = pmap_large_map_kextract(va);
3241 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3244 * Beware of a concurrent promotion that changes the
3245 * PDE at this point! For example, vtopte() must not
3246 * be used to access the PTE because it would use the
3247 * new PDE. It is, however, safe to use the old PDE
3248 * because the page table page is preserved by the
3251 pa = *pmap_pde_to_pte(&pde, va);
3252 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3258 /***************************************************
3259 * Low level mapping routines.....
3260 ***************************************************/
3263 * Add a wired page to the kva.
3264 * Note: not SMP coherent.
3267 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3272 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | pg_nx);
3275 static __inline void
3276 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3282 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
3283 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | pg_nx | cache_bits);
3287 * Remove a page from the kernel pagetables.
3288 * Note: not SMP coherent.
3291 pmap_kremove(vm_offset_t va)
3300 * Used to map a range of physical addresses into kernel
3301 * virtual address space.
3303 * The value passed in '*virt' is a suggested virtual address for
3304 * the mapping. Architectures which can support a direct-mapped
3305 * physical to virtual region can return the appropriate address
3306 * within that region, leaving '*virt' unchanged. Other
3307 * architectures should map the pages starting at '*virt' and
3308 * update '*virt' with the first usable address after the mapped
3312 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
3314 return PHYS_TO_DMAP(start);
3319 * Add a list of wired pages to the kva
3320 * this routine is only used for temporary
3321 * kernel mappings that do not need to have
3322 * page modification or references recorded.
3323 * Note that old mappings are simply written
3324 * over. The page *must* be wired.
3325 * Note: SMP coherent. Uses a ranged shootdown IPI.
3328 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
3330 pt_entry_t *endpte, oldpte, pa, *pte;
3336 endpte = pte + count;
3337 while (pte < endpte) {
3339 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
3340 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
3341 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
3343 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
3347 if (__predict_false((oldpte & X86_PG_V) != 0))
3348 pmap_invalidate_range(kernel_pmap, sva, sva + count *
3353 * This routine tears out page mappings from the
3354 * kernel -- it is meant only for temporary mappings.
3355 * Note: SMP coherent. Uses a ranged shootdown IPI.
3358 pmap_qremove(vm_offset_t sva, int count)
3363 while (count-- > 0) {
3364 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
3368 pmap_invalidate_range(kernel_pmap, sva, va);
3371 /***************************************************
3372 * Page table page management routines.....
3373 ***************************************************/
3375 * Schedule the specified unused page table page to be freed. Specifically,
3376 * add the page to the specified list of pages that will be released to the
3377 * physical memory manager after the TLB has been updated.
3379 static __inline void
3380 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
3381 boolean_t set_PG_ZERO)
3385 m->flags |= PG_ZERO;
3387 m->flags &= ~PG_ZERO;
3388 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
3392 * Inserts the specified page table page into the specified pmap's collection
3393 * of idle page table pages. Each of a pmap's page table pages is responsible
3394 * for mapping a distinct range of virtual addresses. The pmap's collection is
3395 * ordered by this virtual address range.
3397 * If "promoted" is false, then the page table page "mpte" must be zero filled.
3400 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
3403 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3404 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
3405 return (vm_radix_insert(&pmap->pm_root, mpte));
3409 * Removes the page table page mapping the specified virtual address from the
3410 * specified pmap's collection of idle page table pages, and returns it.
3411 * Otherwise, returns NULL if there is no page table page corresponding to the
3412 * specified virtual address.
3414 static __inline vm_page_t
3415 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
3418 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3419 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
3423 * Decrements a page table page's reference count, which is used to record the
3424 * number of valid page table entries within the page. If the reference count
3425 * drops to zero, then the page table page is unmapped. Returns TRUE if the
3426 * page table page was unmapped and FALSE otherwise.
3428 static inline boolean_t
3429 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
3433 if (m->ref_count == 0) {
3434 _pmap_unwire_ptp(pmap, va, m, free);
3441 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
3444 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3446 * unmap the page table page
3448 if (m->pindex >= (NUPDE + NUPDPE)) {
3451 pml4 = pmap_pml4e(pmap, va);
3453 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
3454 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
3457 } else if (m->pindex >= NUPDE) {
3460 pdp = pmap_pdpe(pmap, va);
3465 pd = pmap_pde(pmap, va);
3468 pmap_resident_count_dec(pmap, 1);
3469 if (m->pindex < NUPDE) {
3470 /* We just released a PT, unhold the matching PD */
3473 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
3474 pmap_unwire_ptp(pmap, va, pdpg, free);
3476 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
3477 /* We just released a PD, unhold the matching PDP */
3480 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
3481 pmap_unwire_ptp(pmap, va, pdppg, free);
3485 * Put page on a list so that it is released after
3486 * *ALL* TLB shootdown is done
3488 pmap_add_delayed_free_list(m, free, TRUE);
3492 * After removing a page table entry, this routine is used to
3493 * conditionally free the page, and manage the reference count.
3496 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
3497 struct spglist *free)
3501 if (va >= VM_MAXUSER_ADDRESS)
3503 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
3504 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
3505 return (pmap_unwire_ptp(pmap, va, mpte, free));
3509 pmap_pinit0(pmap_t pmap)
3515 PMAP_LOCK_INIT(pmap);
3516 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
3517 pmap->pm_pml4u = NULL;
3518 pmap->pm_cr3 = KPML4phys;
3519 /* hack to keep pmap_pti_pcid_invalidate() alive */
3520 pmap->pm_ucr3 = PMAP_NO_CR3;
3521 pmap->pm_root.rt_root = 0;
3522 CPU_ZERO(&pmap->pm_active);
3523 TAILQ_INIT(&pmap->pm_pvchunk);
3524 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
3525 pmap->pm_flags = pmap_flags;
3527 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
3528 pmap->pm_pcids[i].pm_gen = 1;
3530 pmap_activate_boot(pmap);
3535 p->p_md.md_flags |= P_MD_KPTI;
3538 pmap_thread_init_invl_gen(td);
3540 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
3541 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
3542 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
3548 pmap_pinit_pml4(vm_page_t pml4pg)
3550 pml4_entry_t *pm_pml4;
3553 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
3555 /* Wire in kernel global address entries. */
3556 for (i = 0; i < NKPML4E; i++) {
3557 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
3560 for (i = 0; i < ndmpdpphys; i++) {
3561 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
3565 /* install self-referential address mapping entry(s) */
3566 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
3567 X86_PG_A | X86_PG_M;
3569 /* install large map entries if configured */
3570 for (i = 0; i < lm_ents; i++)
3571 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pml4[LMSPML4I + i];
3575 pmap_pinit_pml4_pti(vm_page_t pml4pg)
3577 pml4_entry_t *pm_pml4;
3580 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
3581 for (i = 0; i < NPML4EPG; i++)
3582 pm_pml4[i] = pti_pml4[i];
3586 * Initialize a preallocated and zeroed pmap structure,
3587 * such as one in a vmspace structure.
3590 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
3592 vm_page_t pml4pg, pml4pgu;
3593 vm_paddr_t pml4phys;
3597 * allocate the page directory page
3599 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3600 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
3602 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
3603 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
3605 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
3606 pmap->pm_pcids[i].pm_gen = 0;
3608 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
3609 pmap->pm_ucr3 = PMAP_NO_CR3;
3610 pmap->pm_pml4u = NULL;
3612 pmap->pm_type = pm_type;
3613 if ((pml4pg->flags & PG_ZERO) == 0)
3614 pagezero(pmap->pm_pml4);
3617 * Do not install the host kernel mappings in the nested page
3618 * tables. These mappings are meaningless in the guest physical
3620 * Install minimal kernel mappings in PTI case.
3622 if (pm_type == PT_X86) {
3623 pmap->pm_cr3 = pml4phys;
3624 pmap_pinit_pml4(pml4pg);
3625 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
3626 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
3627 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
3628 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
3629 VM_PAGE_TO_PHYS(pml4pgu));
3630 pmap_pinit_pml4_pti(pml4pgu);
3631 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
3633 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
3634 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
3635 pkru_free_range, pmap, M_NOWAIT);
3639 pmap->pm_root.rt_root = 0;
3640 CPU_ZERO(&pmap->pm_active);
3641 TAILQ_INIT(&pmap->pm_pvchunk);
3642 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
3643 pmap->pm_flags = flags;
3644 pmap->pm_eptgen = 0;
3650 pmap_pinit(pmap_t pmap)
3653 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
3657 * This routine is called if the desired page table page does not exist.
3659 * If page table page allocation fails, this routine may sleep before
3660 * returning NULL. It sleeps only if a lock pointer was given.
3662 * Note: If a page allocation fails at page table level two or three,
3663 * one or two pages may be held during the wait, only to be released
3664 * afterwards. This conservative approach is easily argued to avoid
3668 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
3670 vm_page_t m, pdppg, pdpg;
3671 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
3673 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3675 PG_A = pmap_accessed_bit(pmap);
3676 PG_M = pmap_modified_bit(pmap);
3677 PG_V = pmap_valid_bit(pmap);
3678 PG_RW = pmap_rw_bit(pmap);
3681 * Allocate a page table page.
3683 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
3684 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
3685 if (lockp != NULL) {
3686 RELEASE_PV_LIST_LOCK(lockp);
3688 PMAP_ASSERT_NOT_IN_DI();
3694 * Indicate the need to retry. While waiting, the page table
3695 * page may have been allocated.
3699 if ((m->flags & PG_ZERO) == 0)
3703 * Map the pagetable page into the process address space, if
3704 * it isn't already there.
3707 if (ptepindex >= (NUPDE + NUPDPE)) {
3708 pml4_entry_t *pml4, *pml4u;
3709 vm_pindex_t pml4index;
3711 /* Wire up a new PDPE page */
3712 pml4index = ptepindex - (NUPDE + NUPDPE);
3713 pml4 = &pmap->pm_pml4[pml4index];
3714 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
3715 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
3717 * PTI: Make all user-space mappings in the
3718 * kernel-mode page table no-execute so that
3719 * we detect any programming errors that leave
3720 * the kernel-mode page table active on return
3723 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3726 pml4u = &pmap->pm_pml4u[pml4index];
3727 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
3731 } else if (ptepindex >= NUPDE) {
3732 vm_pindex_t pml4index;
3733 vm_pindex_t pdpindex;
3737 /* Wire up a new PDE page */
3738 pdpindex = ptepindex - NUPDE;
3739 pml4index = pdpindex >> NPML4EPGSHIFT;
3741 pml4 = &pmap->pm_pml4[pml4index];
3742 if ((*pml4 & PG_V) == 0) {
3743 /* Have to allocate a new pdp, recurse */
3744 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
3746 vm_page_unwire_noq(m);
3747 vm_page_free_zero(m);
3751 /* Add reference to pdp page */
3752 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
3755 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
3757 /* Now find the pdp page */
3758 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
3759 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
3762 vm_pindex_t pml4index;
3763 vm_pindex_t pdpindex;
3768 /* Wire up a new PTE page */
3769 pdpindex = ptepindex >> NPDPEPGSHIFT;
3770 pml4index = pdpindex >> NPML4EPGSHIFT;
3772 /* First, find the pdp and check that its valid. */
3773 pml4 = &pmap->pm_pml4[pml4index];
3774 if ((*pml4 & PG_V) == 0) {
3775 /* Have to allocate a new pd, recurse */
3776 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
3778 vm_page_unwire_noq(m);
3779 vm_page_free_zero(m);
3782 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
3783 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
3785 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
3786 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
3787 if ((*pdp & PG_V) == 0) {
3788 /* Have to allocate a new pd, recurse */
3789 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
3791 vm_page_unwire_noq(m);
3792 vm_page_free_zero(m);
3796 /* Add reference to the pd page */
3797 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3801 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
3803 /* Now we know where the page directory page is */
3804 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
3805 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
3808 pmap_resident_count_inc(pmap, 1);
3814 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
3816 vm_pindex_t pdpindex, ptepindex;
3817 pdp_entry_t *pdpe, PG_V;
3820 PG_V = pmap_valid_bit(pmap);
3823 pdpe = pmap_pdpe(pmap, va);
3824 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3825 /* Add a reference to the pd page. */
3826 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
3829 /* Allocate a pd page. */
3830 ptepindex = pmap_pde_pindex(va);
3831 pdpindex = ptepindex >> NPDPEPGSHIFT;
3832 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
3833 if (pdpg == NULL && lockp != NULL)
3840 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
3842 vm_pindex_t ptepindex;
3843 pd_entry_t *pd, PG_V;
3846 PG_V = pmap_valid_bit(pmap);
3849 * Calculate pagetable page index
3851 ptepindex = pmap_pde_pindex(va);
3854 * Get the page directory entry
3856 pd = pmap_pde(pmap, va);
3859 * This supports switching from a 2MB page to a
3862 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
3863 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
3865 * Invalidation of the 2MB page mapping may have caused
3866 * the deallocation of the underlying PD page.
3873 * If the page table page is mapped, we just increment the
3874 * hold count, and activate it.
3876 if (pd != NULL && (*pd & PG_V) != 0) {
3877 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3881 * Here if the pte page isn't mapped, or if it has been
3884 m = _pmap_allocpte(pmap, ptepindex, lockp);
3885 if (m == NULL && lockp != NULL)
3892 /***************************************************
3893 * Pmap allocation/deallocation routines.
3894 ***************************************************/
3897 * Release any resources held by the given physical map.
3898 * Called when a pmap initialized by pmap_pinit is being released.
3899 * Should only be called if the map contains no valid mappings.
3902 pmap_release(pmap_t pmap)
3907 KASSERT(pmap->pm_stats.resident_count == 0,
3908 ("pmap_release: pmap resident count %ld != 0",
3909 pmap->pm_stats.resident_count));
3910 KASSERT(vm_radix_is_empty(&pmap->pm_root),
3911 ("pmap_release: pmap has reserved page table page(s)"));
3912 KASSERT(CPU_EMPTY(&pmap->pm_active),
3913 ("releasing active pmap %p", pmap));
3915 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
3917 for (i = 0; i < NKPML4E; i++) /* KVA */
3918 pmap->pm_pml4[KPML4BASE + i] = 0;
3919 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3920 pmap->pm_pml4[DMPML4I + i] = 0;
3921 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
3922 for (i = 0; i < lm_ents; i++) /* Large Map */
3923 pmap->pm_pml4[LMSPML4I + i] = 0;
3925 vm_page_unwire_noq(m);
3926 vm_page_free_zero(m);
3928 if (pmap->pm_pml4u != NULL) {
3929 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3930 vm_page_unwire_noq(m);
3933 if (pmap->pm_type == PT_X86 &&
3934 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
3935 rangeset_fini(&pmap->pm_pkru);
3939 kvm_size(SYSCTL_HANDLER_ARGS)
3941 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3943 return sysctl_handle_long(oidp, &ksize, 0, req);
3945 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
3946 0, 0, kvm_size, "LU", "Size of KVM");
3949 kvm_free(SYSCTL_HANDLER_ARGS)
3951 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3953 return sysctl_handle_long(oidp, &kfree, 0, req);
3955 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
3956 0, 0, kvm_free, "LU", "Amount of KVM free");
3959 * Allocate physical memory for the vm_page array and map it into KVA,
3960 * attempting to back the vm_pages with domain-local memory.
3963 pmap_page_array_startup(long pages)
3966 pd_entry_t *pde, newpdir;
3967 vm_offset_t va, start, end;
3972 vm_page_array_size = pages;
3974 start = VM_MIN_KERNEL_ADDRESS;
3975 end = start + pages * sizeof(struct vm_page);
3976 for (va = start; va < end; va += NBPDR) {
3977 pfn = first_page + (va - start) / sizeof(struct vm_page);
3978 domain = _vm_phys_domain(ptoa(pfn));
3979 pdpe = pmap_pdpe(kernel_pmap, va);
3980 if ((*pdpe & X86_PG_V) == 0) {
3981 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
3983 pagezero((void *)PHYS_TO_DMAP(pa));
3984 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
3985 X86_PG_A | X86_PG_M);
3987 pde = pmap_pdpe_to_pde(pdpe, va);
3988 if ((*pde & X86_PG_V) != 0)
3989 panic("Unexpected pde");
3990 pa = vm_phys_early_alloc(domain, NBPDR);
3991 for (i = 0; i < NPDEPG; i++)
3992 dump_add_page(pa + i * PAGE_SIZE);
3993 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
3994 X86_PG_M | PG_PS | pg_g | pg_nx);
3995 pde_store(pde, newpdir);
3997 vm_page_array = (vm_page_t)start;
4001 * grow the number of kernel page table entries, if needed
4004 pmap_growkernel(vm_offset_t addr)
4008 pd_entry_t *pde, newpdir;
4011 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
4014 * Return if "addr" is within the range of kernel page table pages
4015 * that were preallocated during pmap bootstrap. Moreover, leave
4016 * "kernel_vm_end" and the kernel page table as they were.
4018 * The correctness of this action is based on the following
4019 * argument: vm_map_insert() allocates contiguous ranges of the
4020 * kernel virtual address space. It calls this function if a range
4021 * ends after "kernel_vm_end". If the kernel is mapped between
4022 * "kernel_vm_end" and "addr", then the range cannot begin at
4023 * "kernel_vm_end". In fact, its beginning address cannot be less
4024 * than the kernel. Thus, there is no immediate need to allocate
4025 * any new kernel page table pages between "kernel_vm_end" and
4028 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
4031 addr = roundup2(addr, NBPDR);
4032 if (addr - 1 >= vm_map_max(kernel_map))
4033 addr = vm_map_max(kernel_map);
4034 while (kernel_vm_end < addr) {
4035 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
4036 if ((*pdpe & X86_PG_V) == 0) {
4037 /* We need a new PDP entry */
4038 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
4039 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
4040 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4042 panic("pmap_growkernel: no memory to grow kernel");
4043 if ((nkpg->flags & PG_ZERO) == 0)
4044 pmap_zero_page(nkpg);
4045 paddr = VM_PAGE_TO_PHYS(nkpg);
4046 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
4047 X86_PG_A | X86_PG_M);
4048 continue; /* try again */
4050 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
4051 if ((*pde & X86_PG_V) != 0) {
4052 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
4053 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
4054 kernel_vm_end = vm_map_max(kernel_map);
4060 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
4061 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
4064 panic("pmap_growkernel: no memory to grow kernel");
4065 if ((nkpg->flags & PG_ZERO) == 0)
4066 pmap_zero_page(nkpg);
4067 paddr = VM_PAGE_TO_PHYS(nkpg);
4068 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
4069 pde_store(pde, newpdir);
4071 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
4072 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
4073 kernel_vm_end = vm_map_max(kernel_map);
4080 /***************************************************
4081 * page management routines.
4082 ***************************************************/
4084 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
4085 CTASSERT(_NPCM == 3);
4086 CTASSERT(_NPCPV == 168);
4088 static __inline struct pv_chunk *
4089 pv_to_chunk(pv_entry_t pv)
4092 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
4095 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
4097 #define PC_FREE0 0xfffffffffffffffful
4098 #define PC_FREE1 0xfffffffffffffffful
4099 #define PC_FREE2 0x000000fffffffffful
4101 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
4104 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
4106 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
4107 "Current number of pv entry chunks");
4108 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
4109 "Current number of pv entry chunks allocated");
4110 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
4111 "Current number of pv entry chunks frees");
4112 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
4113 "Number of times tried to get a chunk page but failed.");
4115 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
4116 static int pv_entry_spare;
4118 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
4119 "Current number of pv entry frees");
4120 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
4121 "Current number of pv entry allocs");
4122 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
4123 "Current number of pv entries");
4124 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
4125 "Current number of spare pv entries");
4129 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
4134 pmap_invalidate_all(pmap);
4135 if (pmap != locked_pmap)
4138 pmap_delayed_invl_finish();
4142 * We are in a serious low memory condition. Resort to
4143 * drastic measures to free some pages so we can allocate
4144 * another pv entry chunk.
4146 * Returns NULL if PV entries were reclaimed from the specified pmap.
4148 * We do not, however, unmap 2mpages because subsequent accesses will
4149 * allocate per-page pv entries until repromotion occurs, thereby
4150 * exacerbating the shortage of free pv entries.
4153 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
4155 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
4156 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
4157 struct md_page *pvh;
4159 pmap_t next_pmap, pmap;
4160 pt_entry_t *pte, tpte;
4161 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4165 struct spglist free;
4167 int bit, field, freed;
4169 static int active_reclaims = 0;
4171 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
4172 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
4175 PG_G = PG_A = PG_M = PG_RW = 0;
4177 bzero(&pc_marker_b, sizeof(pc_marker_b));
4178 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
4179 pc_marker = (struct pv_chunk *)&pc_marker_b;
4180 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
4183 * A delayed invalidation block should already be active if
4184 * pmap_advise() or pmap_remove() called this function by way
4185 * of pmap_demote_pde_locked().
4187 start_di = pmap_not_in_di();
4189 mtx_lock(&pv_chunks_mutex);
4191 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
4192 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
4193 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
4194 SLIST_EMPTY(&free)) {
4195 next_pmap = pc->pc_pmap;
4196 if (next_pmap == NULL) {
4198 * The next chunk is a marker. However, it is
4199 * not our marker, so active_reclaims must be
4200 * > 1. Consequently, the next_chunk code
4201 * will not rotate the pv_chunks list.
4205 mtx_unlock(&pv_chunks_mutex);
4208 * A pv_chunk can only be removed from the pc_lru list
4209 * when both pc_chunks_mutex is owned and the
4210 * corresponding pmap is locked.
4212 if (pmap != next_pmap) {
4213 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
4216 /* Avoid deadlock and lock recursion. */
4217 if (pmap > locked_pmap) {
4218 RELEASE_PV_LIST_LOCK(lockp);
4221 pmap_delayed_invl_start();
4222 mtx_lock(&pv_chunks_mutex);
4224 } else if (pmap != locked_pmap) {
4225 if (PMAP_TRYLOCK(pmap)) {
4227 pmap_delayed_invl_start();
4228 mtx_lock(&pv_chunks_mutex);
4231 pmap = NULL; /* pmap is not locked */
4232 mtx_lock(&pv_chunks_mutex);
4233 pc = TAILQ_NEXT(pc_marker, pc_lru);
4235 pc->pc_pmap != next_pmap)
4239 } else if (start_di)
4240 pmap_delayed_invl_start();
4241 PG_G = pmap_global_bit(pmap);
4242 PG_A = pmap_accessed_bit(pmap);
4243 PG_M = pmap_modified_bit(pmap);
4244 PG_RW = pmap_rw_bit(pmap);
4248 * Destroy every non-wired, 4 KB page mapping in the chunk.
4251 for (field = 0; field < _NPCM; field++) {
4252 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
4253 inuse != 0; inuse &= ~(1UL << bit)) {
4255 pv = &pc->pc_pventry[field * 64 + bit];
4257 pde = pmap_pde(pmap, va);
4258 if ((*pde & PG_PS) != 0)
4260 pte = pmap_pde_to_pte(pde, va);
4261 if ((*pte & PG_W) != 0)
4263 tpte = pte_load_clear(pte);
4264 if ((tpte & PG_G) != 0)
4265 pmap_invalidate_page(pmap, va);
4266 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
4267 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4269 if ((tpte & PG_A) != 0)
4270 vm_page_aflag_set(m, PGA_REFERENCED);
4271 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4272 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4274 if (TAILQ_EMPTY(&m->md.pv_list) &&
4275 (m->flags & PG_FICTITIOUS) == 0) {
4276 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4277 if (TAILQ_EMPTY(&pvh->pv_list)) {
4278 vm_page_aflag_clear(m,
4282 pmap_delayed_invl_page(m);
4283 pc->pc_map[field] |= 1UL << bit;
4284 pmap_unuse_pt(pmap, va, *pde, &free);
4289 mtx_lock(&pv_chunks_mutex);
4292 /* Every freed mapping is for a 4 KB page. */
4293 pmap_resident_count_dec(pmap, freed);
4294 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
4295 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
4296 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
4297 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4298 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
4299 pc->pc_map[2] == PC_FREE2) {
4300 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
4301 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
4302 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
4303 /* Entire chunk is free; return it. */
4304 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
4305 dump_drop_page(m_pc->phys_addr);
4306 mtx_lock(&pv_chunks_mutex);
4307 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4310 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
4311 mtx_lock(&pv_chunks_mutex);
4312 /* One freed pv entry in locked_pmap is sufficient. */
4313 if (pmap == locked_pmap)
4316 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
4317 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
4318 if (active_reclaims == 1 && pmap != NULL) {
4320 * Rotate the pv chunks list so that we do not
4321 * scan the same pv chunks that could not be
4322 * freed (because they contained a wired
4323 * and/or superpage mapping) on every
4324 * invocation of reclaim_pv_chunk().
4326 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
4327 MPASS(pc->pc_pmap != NULL);
4328 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4329 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
4333 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
4334 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
4336 mtx_unlock(&pv_chunks_mutex);
4337 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
4338 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
4339 m_pc = SLIST_FIRST(&free);
4340 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
4341 /* Recycle a freed page table page. */
4342 m_pc->ref_count = 1;
4344 vm_page_free_pages_toq(&free, true);
4349 * free the pv_entry back to the free list
4352 free_pv_entry(pmap_t pmap, pv_entry_t pv)
4354 struct pv_chunk *pc;
4355 int idx, field, bit;
4357 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4358 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
4359 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
4360 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
4361 pc = pv_to_chunk(pv);
4362 idx = pv - &pc->pc_pventry[0];
4365 pc->pc_map[field] |= 1ul << bit;
4366 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
4367 pc->pc_map[2] != PC_FREE2) {
4368 /* 98% of the time, pc is already at the head of the list. */
4369 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
4370 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4371 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
4375 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4380 free_pv_chunk_dequeued(struct pv_chunk *pc)
4384 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
4385 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
4386 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
4387 /* entire chunk is free, return it */
4388 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
4389 dump_drop_page(m->phys_addr);
4390 vm_page_unwire_noq(m);
4395 free_pv_chunk(struct pv_chunk *pc)
4398 mtx_lock(&pv_chunks_mutex);
4399 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4400 mtx_unlock(&pv_chunks_mutex);
4401 free_pv_chunk_dequeued(pc);
4405 free_pv_chunk_batch(struct pv_chunklist *batch)
4407 struct pv_chunk *pc, *npc;
4409 if (TAILQ_EMPTY(batch))
4412 mtx_lock(&pv_chunks_mutex);
4413 TAILQ_FOREACH(pc, batch, pc_list) {
4414 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
4416 mtx_unlock(&pv_chunks_mutex);
4418 TAILQ_FOREACH_SAFE(pc, batch, pc_list, npc) {
4419 free_pv_chunk_dequeued(pc);
4424 * Returns a new PV entry, allocating a new PV chunk from the system when
4425 * needed. If this PV chunk allocation fails and a PV list lock pointer was
4426 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
4429 * The given PV list lock may be released.
4432 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
4436 struct pv_chunk *pc;
4439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4440 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
4442 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
4444 for (field = 0; field < _NPCM; field++) {
4445 if (pc->pc_map[field]) {
4446 bit = bsfq(pc->pc_map[field]);
4450 if (field < _NPCM) {
4451 pv = &pc->pc_pventry[field * 64 + bit];
4452 pc->pc_map[field] &= ~(1ul << bit);
4453 /* If this was the last item, move it to tail */
4454 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
4455 pc->pc_map[2] == 0) {
4456 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4457 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
4460 PV_STAT(atomic_add_long(&pv_entry_count, 1));
4461 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
4465 /* No free items, allocate another chunk */
4466 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
4469 if (lockp == NULL) {
4470 PV_STAT(pc_chunk_tryfail++);
4473 m = reclaim_pv_chunk(pmap, lockp);
4477 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
4478 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
4479 dump_add_page(m->phys_addr);
4480 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
4482 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
4483 pc->pc_map[1] = PC_FREE1;
4484 pc->pc_map[2] = PC_FREE2;
4485 mtx_lock(&pv_chunks_mutex);
4486 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
4487 mtx_unlock(&pv_chunks_mutex);
4488 pv = &pc->pc_pventry[0];
4489 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
4490 PV_STAT(atomic_add_long(&pv_entry_count, 1));
4491 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
4496 * Returns the number of one bits within the given PV chunk map.
4498 * The erratas for Intel processors state that "POPCNT Instruction May
4499 * Take Longer to Execute Than Expected". It is believed that the
4500 * issue is the spurious dependency on the destination register.
4501 * Provide a hint to the register rename logic that the destination
4502 * value is overwritten, by clearing it, as suggested in the
4503 * optimization manual. It should be cheap for unaffected processors
4506 * Reference numbers for erratas are
4507 * 4th Gen Core: HSD146
4508 * 5th Gen Core: BDM85
4509 * 6th Gen Core: SKL029
4512 popcnt_pc_map_pq(uint64_t *map)
4516 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
4517 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
4518 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
4519 : "=&r" (result), "=&r" (tmp)
4520 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
4525 * Ensure that the number of spare PV entries in the specified pmap meets or
4526 * exceeds the given count, "needed".
4528 * The given PV list lock may be released.
4531 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
4533 struct pch new_tail;
4534 struct pv_chunk *pc;
4539 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4540 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
4543 * Newly allocated PV chunks must be stored in a private list until
4544 * the required number of PV chunks have been allocated. Otherwise,
4545 * reclaim_pv_chunk() could recycle one of these chunks. In
4546 * contrast, these chunks must be added to the pmap upon allocation.
4548 TAILQ_INIT(&new_tail);
4551 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
4553 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
4554 bit_count((bitstr_t *)pc->pc_map, 0,
4555 sizeof(pc->pc_map) * NBBY, &free);
4558 free = popcnt_pc_map_pq(pc->pc_map);
4562 if (avail >= needed)
4565 for (reclaimed = false; avail < needed; avail += _NPCPV) {
4566 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
4569 m = reclaim_pv_chunk(pmap, lockp);
4574 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
4575 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
4576 dump_add_page(m->phys_addr);
4577 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
4579 pc->pc_map[0] = PC_FREE0;
4580 pc->pc_map[1] = PC_FREE1;
4581 pc->pc_map[2] = PC_FREE2;
4582 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
4583 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
4584 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
4587 * The reclaim might have freed a chunk from the current pmap.
4588 * If that chunk contained available entries, we need to
4589 * re-count the number of available entries.
4594 if (!TAILQ_EMPTY(&new_tail)) {
4595 mtx_lock(&pv_chunks_mutex);
4596 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
4597 mtx_unlock(&pv_chunks_mutex);
4602 * First find and then remove the pv entry for the specified pmap and virtual
4603 * address from the specified pv list. Returns the pv entry if found and NULL
4604 * otherwise. This operation can be performed on pv lists for either 4KB or
4605 * 2MB page mappings.
4607 static __inline pv_entry_t
4608 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
4612 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4613 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
4614 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4623 * After demotion from a 2MB page mapping to 512 4KB page mappings,
4624 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
4625 * entries for each of the 4KB page mappings.
4628 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4629 struct rwlock **lockp)
4631 struct md_page *pvh;
4632 struct pv_chunk *pc;
4634 vm_offset_t va_last;
4638 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4639 KASSERT((pa & PDRMASK) == 0,
4640 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
4641 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4644 * Transfer the 2mpage's pv entry for this mapping to the first
4645 * page's pv list. Once this transfer begins, the pv list lock
4646 * must not be released until the last pv entry is reinstantiated.
4648 pvh = pa_to_pvh(pa);
4649 va = trunc_2mpage(va);
4650 pv = pmap_pvh_remove(pvh, pmap, va);
4651 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
4652 m = PHYS_TO_VM_PAGE(pa);
4653 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4655 /* Instantiate the remaining NPTEPG - 1 pv entries. */
4656 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
4657 va_last = va + NBPDR - PAGE_SIZE;
4659 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
4660 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
4661 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
4662 for (field = 0; field < _NPCM; field++) {
4663 while (pc->pc_map[field]) {
4664 bit = bsfq(pc->pc_map[field]);
4665 pc->pc_map[field] &= ~(1ul << bit);
4666 pv = &pc->pc_pventry[field * 64 + bit];
4670 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4671 ("pmap_pv_demote_pde: page %p is not managed", m));
4672 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4678 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4679 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
4682 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
4683 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4684 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
4686 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
4687 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
4690 #if VM_NRESERVLEVEL > 0
4692 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
4693 * replace the many pv entries for the 4KB page mappings by a single pv entry
4694 * for the 2MB page mapping.
4697 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4698 struct rwlock **lockp)
4700 struct md_page *pvh;
4702 vm_offset_t va_last;
4705 KASSERT((pa & PDRMASK) == 0,
4706 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
4707 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4710 * Transfer the first page's pv entry for this mapping to the 2mpage's
4711 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
4712 * a transfer avoids the possibility that get_pv_entry() calls
4713 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
4714 * mappings that is being promoted.
4716 m = PHYS_TO_VM_PAGE(pa);
4717 va = trunc_2mpage(va);
4718 pv = pmap_pvh_remove(&m->md, pmap, va);
4719 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
4720 pvh = pa_to_pvh(pa);
4721 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4723 /* Free the remaining NPTEPG - 1 pv entries. */
4724 va_last = va + NBPDR - PAGE_SIZE;
4728 pmap_pvh_free(&m->md, pmap, va);
4729 } while (va < va_last);
4731 #endif /* VM_NRESERVLEVEL > 0 */
4734 * First find and then destroy the pv entry for the specified pmap and virtual
4735 * address. This operation can be performed on pv lists for either 4KB or 2MB
4739 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
4743 pv = pmap_pvh_remove(pvh, pmap, va);
4744 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
4745 free_pv_entry(pmap, pv);
4749 * Conditionally create the PV entry for a 4KB page mapping if the required
4750 * memory can be allocated without resorting to reclamation.
4753 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
4754 struct rwlock **lockp)
4758 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4759 /* Pass NULL instead of the lock pointer to disable reclamation. */
4760 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
4762 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4763 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4771 * Create the PV entry for a 2MB page mapping. Always returns true unless the
4772 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
4773 * false if the PV entry cannot be allocated without resorting to reclamation.
4776 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
4777 struct rwlock **lockp)
4779 struct md_page *pvh;
4783 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4784 /* Pass NULL instead of the lock pointer to disable reclamation. */
4785 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
4786 NULL : lockp)) == NULL)
4789 pa = pde & PG_PS_FRAME;
4790 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4791 pvh = pa_to_pvh(pa);
4792 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4798 * Fills a page table page with mappings to consecutive physical pages.
4801 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
4805 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
4807 newpte += PAGE_SIZE;
4812 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
4813 * mapping is invalidated.
4816 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
4818 struct rwlock *lock;
4822 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
4829 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
4833 pt_entry_t *xpte, *ypte;
4835 for (xpte = firstpte; xpte < firstpte + NPTEPG;
4836 xpte++, newpte += PAGE_SIZE) {
4837 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
4838 printf("pmap_demote_pde: xpte %zd and newpte map "
4839 "different pages: found %#lx, expected %#lx\n",
4840 xpte - firstpte, *xpte, newpte);
4841 printf("page table dump\n");
4842 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
4843 printf("%zd %#lx\n", ypte - firstpte, *ypte);
4848 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
4849 ("pmap_demote_pde: firstpte and newpte map different physical"
4856 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4857 pd_entry_t oldpde, struct rwlock **lockp)
4859 struct spglist free;
4863 sva = trunc_2mpage(va);
4864 pmap_remove_pde(pmap, pde, sva, &free, lockp);
4865 if ((oldpde & pmap_global_bit(pmap)) == 0)
4866 pmap_invalidate_pde_page(pmap, sva, oldpde);
4867 vm_page_free_pages_toq(&free, true);
4868 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
4873 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4874 struct rwlock **lockp)
4876 pd_entry_t newpde, oldpde;
4877 pt_entry_t *firstpte, newpte;
4878 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
4884 PG_A = pmap_accessed_bit(pmap);
4885 PG_G = pmap_global_bit(pmap);
4886 PG_M = pmap_modified_bit(pmap);
4887 PG_RW = pmap_rw_bit(pmap);
4888 PG_V = pmap_valid_bit(pmap);
4889 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4890 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
4892 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4893 in_kernel = va >= VM_MAXUSER_ADDRESS;
4895 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
4896 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
4899 * Invalidate the 2MB page mapping and return "failure" if the
4900 * mapping was never accessed.
4902 if ((oldpde & PG_A) == 0) {
4903 KASSERT((oldpde & PG_W) == 0,
4904 ("pmap_demote_pde: a wired mapping is missing PG_A"));
4905 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
4909 mpte = pmap_remove_pt_page(pmap, va);
4911 KASSERT((oldpde & PG_W) == 0,
4912 ("pmap_demote_pde: page table page for a wired mapping"
4916 * If the page table page is missing and the mapping
4917 * is for a kernel address, the mapping must belong to
4918 * the direct map. Page table pages are preallocated
4919 * for every other part of the kernel address space,
4920 * so the direct map region is the only part of the
4921 * kernel address space that must be handled here.
4923 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
4924 va < DMAP_MAX_ADDRESS),
4925 ("pmap_demote_pde: No saved mpte for va %#lx", va));
4928 * If the 2MB page mapping belongs to the direct map
4929 * region of the kernel's address space, then the page
4930 * allocation request specifies the highest possible
4931 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
4932 * priority is normal.
4934 mpte = vm_page_alloc(NULL, pmap_pde_pindex(va),
4935 (in_kernel ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
4936 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
4939 * If the allocation of the new page table page fails,
4940 * invalidate the 2MB page mapping and return "failure".
4943 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
4948 mpte->ref_count = NPTEPG;
4949 pmap_resident_count_inc(pmap, 1);
4952 mptepa = VM_PAGE_TO_PHYS(mpte);
4953 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
4954 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
4955 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
4956 ("pmap_demote_pde: oldpde is missing PG_M"));
4957 newpte = oldpde & ~PG_PS;
4958 newpte = pmap_swap_pat(pmap, newpte);
4961 * If the page table page is not leftover from an earlier promotion,
4964 if (mpte->valid == 0)
4965 pmap_fill_ptp(firstpte, newpte);
4967 pmap_demote_pde_check(firstpte, newpte);
4970 * If the mapping has changed attributes, update the page table
4973 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
4974 pmap_fill_ptp(firstpte, newpte);
4977 * The spare PV entries must be reserved prior to demoting the
4978 * mapping, that is, prior to changing the PDE. Otherwise, the state
4979 * of the PDE and the PV lists will be inconsistent, which can result
4980 * in reclaim_pv_chunk() attempting to remove a PV entry from the
4981 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
4982 * PV entry for the 2MB page mapping that is being demoted.
4984 if ((oldpde & PG_MANAGED) != 0)
4985 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
4988 * Demote the mapping. This pmap is locked. The old PDE has
4989 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
4990 * set. Thus, there is no danger of a race with another
4991 * processor changing the setting of PG_A and/or PG_M between
4992 * the read above and the store below.
4994 if (workaround_erratum383)
4995 pmap_update_pde(pmap, va, pde, newpde);
4997 pde_store(pde, newpde);
5000 * Invalidate a stale recursive mapping of the page table page.
5003 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
5006 * Demote the PV entry.
5008 if ((oldpde & PG_MANAGED) != 0)
5009 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
5011 atomic_add_long(&pmap_pde_demotions, 1);
5012 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
5018 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
5021 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5027 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
5028 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5029 mpte = pmap_remove_pt_page(pmap, va);
5031 panic("pmap_remove_kernel_pde: Missing pt page.");
5033 mptepa = VM_PAGE_TO_PHYS(mpte);
5034 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
5037 * If this page table page was unmapped by a promotion, then it
5038 * contains valid mappings. Zero it to invalidate those mappings.
5040 if (mpte->valid != 0)
5041 pagezero((void *)PHYS_TO_DMAP(mptepa));
5044 * Demote the mapping.
5046 if (workaround_erratum383)
5047 pmap_update_pde(pmap, va, pde, newpde);
5049 pde_store(pde, newpde);
5052 * Invalidate a stale recursive mapping of the page table page.
5054 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
5058 * pmap_remove_pde: do the things to unmap a superpage in a process
5061 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
5062 struct spglist *free, struct rwlock **lockp)
5064 struct md_page *pvh;
5066 vm_offset_t eva, va;
5068 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5070 PG_G = pmap_global_bit(pmap);
5071 PG_A = pmap_accessed_bit(pmap);
5072 PG_M = pmap_modified_bit(pmap);
5073 PG_RW = pmap_rw_bit(pmap);
5075 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5076 KASSERT((sva & PDRMASK) == 0,
5077 ("pmap_remove_pde: sva is not 2mpage aligned"));
5078 oldpde = pte_load_clear(pdq);
5080 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
5081 if ((oldpde & PG_G) != 0)
5082 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
5083 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5084 if (oldpde & PG_MANAGED) {
5085 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
5086 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
5087 pmap_pvh_free(pvh, pmap, sva);
5089 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
5090 va < eva; va += PAGE_SIZE, m++) {
5091 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
5094 vm_page_aflag_set(m, PGA_REFERENCED);
5095 if (TAILQ_EMPTY(&m->md.pv_list) &&
5096 TAILQ_EMPTY(&pvh->pv_list))
5097 vm_page_aflag_clear(m, PGA_WRITEABLE);
5098 pmap_delayed_invl_page(m);
5101 if (pmap == kernel_pmap) {
5102 pmap_remove_kernel_pde(pmap, pdq, sva);
5104 mpte = pmap_remove_pt_page(pmap, sva);
5106 KASSERT(mpte->valid == VM_PAGE_BITS_ALL,
5107 ("pmap_remove_pde: pte page not promoted"));
5108 pmap_resident_count_dec(pmap, 1);
5109 KASSERT(mpte->ref_count == NPTEPG,
5110 ("pmap_remove_pde: pte page ref count error"));
5111 mpte->ref_count = 0;
5112 pmap_add_delayed_free_list(mpte, free, FALSE);
5115 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
5119 * pmap_remove_pte: do the things to unmap a page in a process
5122 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
5123 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
5125 struct md_page *pvh;
5126 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
5129 PG_A = pmap_accessed_bit(pmap);
5130 PG_M = pmap_modified_bit(pmap);
5131 PG_RW = pmap_rw_bit(pmap);
5133 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5134 oldpte = pte_load_clear(ptq);
5136 pmap->pm_stats.wired_count -= 1;
5137 pmap_resident_count_dec(pmap, 1);
5138 if (oldpte & PG_MANAGED) {
5139 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
5140 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5143 vm_page_aflag_set(m, PGA_REFERENCED);
5144 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5145 pmap_pvh_free(&m->md, pmap, va);
5146 if (TAILQ_EMPTY(&m->md.pv_list) &&
5147 (m->flags & PG_FICTITIOUS) == 0) {
5148 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5149 if (TAILQ_EMPTY(&pvh->pv_list))
5150 vm_page_aflag_clear(m, PGA_WRITEABLE);
5152 pmap_delayed_invl_page(m);
5154 return (pmap_unuse_pt(pmap, va, ptepde, free));
5158 * Remove a single page from a process address space
5161 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
5162 struct spglist *free)
5164 struct rwlock *lock;
5165 pt_entry_t *pte, PG_V;
5167 PG_V = pmap_valid_bit(pmap);
5168 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5169 if ((*pde & PG_V) == 0)
5171 pte = pmap_pde_to_pte(pde, va);
5172 if ((*pte & PG_V) == 0)
5175 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
5178 pmap_invalidate_page(pmap, va);
5182 * Removes the specified range of addresses from the page table page.
5185 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
5186 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
5188 pt_entry_t PG_G, *pte;
5192 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5193 PG_G = pmap_global_bit(pmap);
5196 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
5200 pmap_invalidate_range(pmap, va, sva);
5205 if ((*pte & PG_G) == 0)
5209 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
5215 pmap_invalidate_range(pmap, va, sva);
5220 * Remove the given range of addresses from the specified map.
5222 * It is assumed that the start and end are properly
5223 * rounded to the page size.
5226 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5228 struct rwlock *lock;
5229 vm_offset_t va_next;
5230 pml4_entry_t *pml4e;
5232 pd_entry_t ptpaddr, *pde;
5233 pt_entry_t PG_G, PG_V;
5234 struct spglist free;
5237 PG_G = pmap_global_bit(pmap);
5238 PG_V = pmap_valid_bit(pmap);
5241 * Perform an unsynchronized read. This is, however, safe.
5243 if (pmap->pm_stats.resident_count == 0)
5249 pmap_delayed_invl_start();
5251 pmap_pkru_on_remove(pmap, sva, eva);
5254 * special handling of removing one page. a very
5255 * common operation and easy to short circuit some
5258 if (sva + PAGE_SIZE == eva) {
5259 pde = pmap_pde(pmap, sva);
5260 if (pde && (*pde & PG_PS) == 0) {
5261 pmap_remove_page(pmap, sva, pde, &free);
5267 for (; sva < eva; sva = va_next) {
5269 if (pmap->pm_stats.resident_count == 0)
5272 pml4e = pmap_pml4e(pmap, sva);
5273 if ((*pml4e & PG_V) == 0) {
5274 va_next = (sva + NBPML4) & ~PML4MASK;
5280 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5281 if ((*pdpe & PG_V) == 0) {
5282 va_next = (sva + NBPDP) & ~PDPMASK;
5289 * Calculate index for next page table.
5291 va_next = (sva + NBPDR) & ~PDRMASK;
5295 pde = pmap_pdpe_to_pde(pdpe, sva);
5299 * Weed out invalid mappings.
5305 * Check for large page.
5307 if ((ptpaddr & PG_PS) != 0) {
5309 * Are we removing the entire large page? If not,
5310 * demote the mapping and fall through.
5312 if (sva + NBPDR == va_next && eva >= va_next) {
5314 * The TLB entry for a PG_G mapping is
5315 * invalidated by pmap_remove_pde().
5317 if ((ptpaddr & PG_G) == 0)
5319 pmap_remove_pde(pmap, pde, sva, &free, &lock);
5321 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
5323 /* The large page mapping was destroyed. */
5330 * Limit our scan to either the end of the va represented
5331 * by the current page table page, or to the end of the
5332 * range being removed.
5337 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
5344 pmap_invalidate_all(pmap);
5346 pmap_delayed_invl_finish();
5347 vm_page_free_pages_toq(&free, true);
5351 * Routine: pmap_remove_all
5353 * Removes this physical page from
5354 * all physical maps in which it resides.
5355 * Reflects back modify bits to the pager.
5358 * Original versions of this routine were very
5359 * inefficient because they iteratively called
5360 * pmap_remove (slow...)
5364 pmap_remove_all(vm_page_t m)
5366 struct md_page *pvh;
5369 struct rwlock *lock;
5370 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
5373 struct spglist free;
5374 int pvh_gen, md_gen;
5376 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5377 ("pmap_remove_all: page %p is not managed", m));
5379 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5380 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5381 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5384 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
5386 if (!PMAP_TRYLOCK(pmap)) {
5387 pvh_gen = pvh->pv_gen;
5391 if (pvh_gen != pvh->pv_gen) {
5398 pde = pmap_pde(pmap, va);
5399 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5402 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
5404 if (!PMAP_TRYLOCK(pmap)) {
5405 pvh_gen = pvh->pv_gen;
5406 md_gen = m->md.pv_gen;
5410 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5416 PG_A = pmap_accessed_bit(pmap);
5417 PG_M = pmap_modified_bit(pmap);
5418 PG_RW = pmap_rw_bit(pmap);
5419 pmap_resident_count_dec(pmap, 1);
5420 pde = pmap_pde(pmap, pv->pv_va);
5421 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
5422 " a 2mpage in page %p's pv list", m));
5423 pte = pmap_pde_to_pte(pde, pv->pv_va);
5424 tpte = pte_load_clear(pte);
5426 pmap->pm_stats.wired_count--;
5428 vm_page_aflag_set(m, PGA_REFERENCED);
5431 * Update the vm_page_t clean and reference bits.
5433 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5435 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
5436 pmap_invalidate_page(pmap, pv->pv_va);
5437 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5439 free_pv_entry(pmap, pv);
5442 vm_page_aflag_clear(m, PGA_WRITEABLE);
5444 pmap_delayed_invl_wait(m);
5445 vm_page_free_pages_toq(&free, true);
5449 * pmap_protect_pde: do the things to protect a 2mpage in a process
5452 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
5454 pd_entry_t newpde, oldpde;
5456 boolean_t anychanged;
5457 pt_entry_t PG_G, PG_M, PG_RW;
5459 PG_G = pmap_global_bit(pmap);
5460 PG_M = pmap_modified_bit(pmap);
5461 PG_RW = pmap_rw_bit(pmap);
5463 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5464 KASSERT((sva & PDRMASK) == 0,
5465 ("pmap_protect_pde: sva is not 2mpage aligned"));
5468 oldpde = newpde = *pde;
5469 if ((prot & VM_PROT_WRITE) == 0) {
5470 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
5471 (PG_MANAGED | PG_M | PG_RW)) {
5472 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
5473 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5476 newpde &= ~(PG_RW | PG_M);
5478 if ((prot & VM_PROT_EXECUTE) == 0)
5480 if (newpde != oldpde) {
5482 * As an optimization to future operations on this PDE, clear
5483 * PG_PROMOTED. The impending invalidation will remove any
5484 * lingering 4KB page mappings from the TLB.
5486 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
5488 if ((oldpde & PG_G) != 0)
5489 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
5493 return (anychanged);
5497 * Set the physical protection on the
5498 * specified range of this map as requested.
5501 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
5503 vm_offset_t va_next;
5504 pml4_entry_t *pml4e;
5506 pd_entry_t ptpaddr, *pde;
5507 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
5508 boolean_t anychanged;
5510 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
5511 if (prot == VM_PROT_NONE) {
5512 pmap_remove(pmap, sva, eva);
5516 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
5517 (VM_PROT_WRITE|VM_PROT_EXECUTE))
5520 PG_G = pmap_global_bit(pmap);
5521 PG_M = pmap_modified_bit(pmap);
5522 PG_V = pmap_valid_bit(pmap);
5523 PG_RW = pmap_rw_bit(pmap);
5527 * Although this function delays and batches the invalidation
5528 * of stale TLB entries, it does not need to call
5529 * pmap_delayed_invl_start() and
5530 * pmap_delayed_invl_finish(), because it does not
5531 * ordinarily destroy mappings. Stale TLB entries from
5532 * protection-only changes need only be invalidated before the
5533 * pmap lock is released, because protection-only changes do
5534 * not destroy PV entries. Even operations that iterate over
5535 * a physical page's PV list of mappings, like
5536 * pmap_remove_write(), acquire the pmap lock for each
5537 * mapping. Consequently, for protection-only changes, the
5538 * pmap lock suffices to synchronize both page table and TLB
5541 * This function only destroys a mapping if pmap_demote_pde()
5542 * fails. In that case, stale TLB entries are immediately
5547 for (; sva < eva; sva = va_next) {
5549 pml4e = pmap_pml4e(pmap, sva);
5550 if ((*pml4e & PG_V) == 0) {
5551 va_next = (sva + NBPML4) & ~PML4MASK;
5557 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5558 if ((*pdpe & PG_V) == 0) {
5559 va_next = (sva + NBPDP) & ~PDPMASK;
5565 va_next = (sva + NBPDR) & ~PDRMASK;
5569 pde = pmap_pdpe_to_pde(pdpe, sva);
5573 * Weed out invalid mappings.
5579 * Check for large page.
5581 if ((ptpaddr & PG_PS) != 0) {
5583 * Are we protecting the entire large page? If not,
5584 * demote the mapping and fall through.
5586 if (sva + NBPDR == va_next && eva >= va_next) {
5588 * The TLB entry for a PG_G mapping is
5589 * invalidated by pmap_protect_pde().
5591 if (pmap_protect_pde(pmap, pde, sva, prot))
5594 } else if (!pmap_demote_pde(pmap, pde, sva)) {
5596 * The large page mapping was destroyed.
5605 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5607 pt_entry_t obits, pbits;
5611 obits = pbits = *pte;
5612 if ((pbits & PG_V) == 0)
5615 if ((prot & VM_PROT_WRITE) == 0) {
5616 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
5617 (PG_MANAGED | PG_M | PG_RW)) {
5618 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
5621 pbits &= ~(PG_RW | PG_M);
5623 if ((prot & VM_PROT_EXECUTE) == 0)
5626 if (pbits != obits) {
5627 if (!atomic_cmpset_long(pte, obits, pbits))
5630 pmap_invalidate_page(pmap, sva);
5637 pmap_invalidate_all(pmap);
5641 #if VM_NRESERVLEVEL > 0
5643 * Tries to promote the 512, contiguous 4KB page mappings that are within a
5644 * single page table page (PTP) to a single 2MB page mapping. For promotion
5645 * to occur, two conditions must be met: (1) the 4KB page mappings must map
5646 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
5647 * identical characteristics.
5650 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
5651 struct rwlock **lockp)
5654 pt_entry_t *firstpte, oldpte, pa, *pte;
5655 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V, PG_PKU_MASK;
5659 PG_A = pmap_accessed_bit(pmap);
5660 PG_G = pmap_global_bit(pmap);
5661 PG_M = pmap_modified_bit(pmap);
5662 PG_V = pmap_valid_bit(pmap);
5663 PG_RW = pmap_rw_bit(pmap);
5664 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
5665 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
5667 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5670 * Examine the first PTE in the specified PTP. Abort if this PTE is
5671 * either invalid, unused, or does not map the first 4KB physical page
5672 * within a 2MB page.
5674 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
5677 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
5678 atomic_add_long(&pmap_pde_p_failures, 1);
5679 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
5680 " in pmap %p", va, pmap);
5683 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
5685 * When PG_M is already clear, PG_RW can be cleared without
5686 * a TLB invalidation.
5688 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
5694 * Examine each of the other PTEs in the specified PTP. Abort if this
5695 * PTE maps an unexpected 4KB physical page or does not have identical
5696 * characteristics to the first PTE.
5698 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
5699 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
5702 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
5703 atomic_add_long(&pmap_pde_p_failures, 1);
5704 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
5705 " in pmap %p", va, pmap);
5708 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
5710 * When PG_M is already clear, PG_RW can be cleared
5711 * without a TLB invalidation.
5713 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
5716 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
5717 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
5718 (va & ~PDRMASK), pmap);
5720 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
5721 atomic_add_long(&pmap_pde_p_failures, 1);
5722 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
5723 " in pmap %p", va, pmap);
5730 * Save the page table page in its current state until the PDE
5731 * mapping the superpage is demoted by pmap_demote_pde() or
5732 * destroyed by pmap_remove_pde().
5734 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5735 KASSERT(mpte >= vm_page_array &&
5736 mpte < &vm_page_array[vm_page_array_size],
5737 ("pmap_promote_pde: page table page is out of range"));
5738 KASSERT(mpte->pindex == pmap_pde_pindex(va),
5739 ("pmap_promote_pde: page table page's pindex is wrong"));
5740 if (pmap_insert_pt_page(pmap, mpte, true)) {
5741 atomic_add_long(&pmap_pde_p_failures, 1);
5743 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
5749 * Promote the pv entries.
5751 if ((newpde & PG_MANAGED) != 0)
5752 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
5755 * Propagate the PAT index to its proper position.
5757 newpde = pmap_swap_pat(pmap, newpde);
5760 * Map the superpage.
5762 if (workaround_erratum383)
5763 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
5765 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
5767 atomic_add_long(&pmap_pde_promotions, 1);
5768 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
5769 " in pmap %p", va, pmap);
5771 #endif /* VM_NRESERVLEVEL > 0 */
5774 * Insert the given physical page (p) at
5775 * the specified virtual address (v) in the
5776 * target physical map with the protection requested.
5778 * If specified, the page will be wired down, meaning
5779 * that the related pte can not be reclaimed.
5781 * NB: This is the only routine which MAY NOT lazy-evaluate
5782 * or lose information. That is, this routine must actually
5783 * insert this page into the given map NOW.
5785 * When destroying both a page table and PV entry, this function
5786 * performs the TLB invalidation before releasing the PV list
5787 * lock, so we do not need pmap_delayed_invl_page() calls here.
5790 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5791 u_int flags, int8_t psind)
5793 struct rwlock *lock;
5795 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
5796 pt_entry_t newpte, origpte;
5803 PG_A = pmap_accessed_bit(pmap);
5804 PG_G = pmap_global_bit(pmap);
5805 PG_M = pmap_modified_bit(pmap);
5806 PG_V = pmap_valid_bit(pmap);
5807 PG_RW = pmap_rw_bit(pmap);
5809 va = trunc_page(va);
5810 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
5811 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
5812 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
5814 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
5815 va >= kmi.clean_eva,
5816 ("pmap_enter: managed mapping within the clean submap"));
5817 if ((m->oflags & VPO_UNMANAGED) == 0)
5818 VM_PAGE_OBJECT_BUSY_ASSERT(m);
5819 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
5820 ("pmap_enter: flags %u has reserved bits set", flags));
5821 pa = VM_PAGE_TO_PHYS(m);
5822 newpte = (pt_entry_t)(pa | PG_A | PG_V);
5823 if ((flags & VM_PROT_WRITE) != 0)
5825 if ((prot & VM_PROT_WRITE) != 0)
5827 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
5828 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
5829 if ((prot & VM_PROT_EXECUTE) == 0)
5831 if ((flags & PMAP_ENTER_WIRED) != 0)
5833 if (va < VM_MAXUSER_ADDRESS)
5835 if (pmap == kernel_pmap)
5837 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
5840 * Set modified bit gratuitously for writeable mappings if
5841 * the page is unmanaged. We do not want to take a fault
5842 * to do the dirty bit accounting for these mappings.
5844 if ((m->oflags & VPO_UNMANAGED) != 0) {
5845 if ((newpte & PG_RW) != 0)
5848 newpte |= PG_MANAGED;
5853 /* Assert the required virtual and physical alignment. */
5854 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
5855 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
5856 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
5862 * In the case that a page table page is not
5863 * resident, we are creating it here.
5866 pde = pmap_pde(pmap, va);
5867 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
5868 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
5869 pte = pmap_pde_to_pte(pde, va);
5870 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
5871 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5874 } else if (va < VM_MAXUSER_ADDRESS) {
5876 * Here if the pte page isn't mapped, or if it has been
5879 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
5880 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
5881 nosleep ? NULL : &lock);
5882 if (mpte == NULL && nosleep) {
5883 rv = KERN_RESOURCE_SHORTAGE;
5888 panic("pmap_enter: invalid page directory va=%#lx", va);
5892 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
5893 newpte |= pmap_pkru_get(pmap, va);
5896 * Is the specified virtual address already mapped?
5898 if ((origpte & PG_V) != 0) {
5900 * Wiring change, just update stats. We don't worry about
5901 * wiring PT pages as they remain resident as long as there
5902 * are valid mappings in them. Hence, if a user page is wired,
5903 * the PT page will be also.
5905 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
5906 pmap->pm_stats.wired_count++;
5907 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
5908 pmap->pm_stats.wired_count--;
5911 * Remove the extra PT page reference.
5915 KASSERT(mpte->ref_count > 0,
5916 ("pmap_enter: missing reference to page table page,"
5921 * Has the physical page changed?
5923 opa = origpte & PG_FRAME;
5926 * No, might be a protection or wiring change.
5928 if ((origpte & PG_MANAGED) != 0 &&
5929 (newpte & PG_RW) != 0)
5930 vm_page_aflag_set(m, PGA_WRITEABLE);
5931 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
5937 * The physical page has changed. Temporarily invalidate
5938 * the mapping. This ensures that all threads sharing the
5939 * pmap keep a consistent view of the mapping, which is
5940 * necessary for the correct handling of COW faults. It
5941 * also permits reuse of the old mapping's PV entry,
5942 * avoiding an allocation.
5944 * For consistency, handle unmanaged mappings the same way.
5946 origpte = pte_load_clear(pte);
5947 KASSERT((origpte & PG_FRAME) == opa,
5948 ("pmap_enter: unexpected pa update for %#lx", va));
5949 if ((origpte & PG_MANAGED) != 0) {
5950 om = PHYS_TO_VM_PAGE(opa);
5953 * The pmap lock is sufficient to synchronize with
5954 * concurrent calls to pmap_page_test_mappings() and
5955 * pmap_ts_referenced().
5957 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5959 if ((origpte & PG_A) != 0)
5960 vm_page_aflag_set(om, PGA_REFERENCED);
5961 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
5962 pv = pmap_pvh_remove(&om->md, pmap, va);
5964 ("pmap_enter: no PV entry for %#lx", va));
5965 if ((newpte & PG_MANAGED) == 0)
5966 free_pv_entry(pmap, pv);
5967 if ((om->aflags & PGA_WRITEABLE) != 0 &&
5968 TAILQ_EMPTY(&om->md.pv_list) &&
5969 ((om->flags & PG_FICTITIOUS) != 0 ||
5970 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
5971 vm_page_aflag_clear(om, PGA_WRITEABLE);
5973 if ((origpte & PG_A) != 0)
5974 pmap_invalidate_page(pmap, va);
5978 * Increment the counters.
5980 if ((newpte & PG_W) != 0)
5981 pmap->pm_stats.wired_count++;
5982 pmap_resident_count_inc(pmap, 1);
5986 * Enter on the PV list if part of our managed memory.
5988 if ((newpte & PG_MANAGED) != 0) {
5990 pv = get_pv_entry(pmap, &lock);
5993 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
5994 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5996 if ((newpte & PG_RW) != 0)
5997 vm_page_aflag_set(m, PGA_WRITEABLE);
6003 if ((origpte & PG_V) != 0) {
6005 origpte = pte_load_store(pte, newpte);
6006 KASSERT((origpte & PG_FRAME) == pa,
6007 ("pmap_enter: unexpected pa update for %#lx", va));
6008 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
6010 if ((origpte & PG_MANAGED) != 0)
6014 * Although the PTE may still have PG_RW set, TLB
6015 * invalidation may nonetheless be required because
6016 * the PTE no longer has PG_M set.
6018 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
6020 * This PTE change does not require TLB invalidation.
6024 if ((origpte & PG_A) != 0)
6025 pmap_invalidate_page(pmap, va);
6027 pte_store(pte, newpte);
6031 #if VM_NRESERVLEVEL > 0
6033 * If both the page table page and the reservation are fully
6034 * populated, then attempt promotion.
6036 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
6037 pmap_ps_enabled(pmap) &&
6038 (m->flags & PG_FICTITIOUS) == 0 &&
6039 vm_reserv_level_iffullpop(m) == 0)
6040 pmap_promote_pde(pmap, pde, va, &lock);
6052 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
6053 * if successful. Returns false if (1) a page table page cannot be allocated
6054 * without sleeping, (2) a mapping already exists at the specified virtual
6055 * address, or (3) a PV entry cannot be allocated without reclaiming another
6059 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
6060 struct rwlock **lockp)
6065 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6066 PG_V = pmap_valid_bit(pmap);
6067 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
6069 if ((m->oflags & VPO_UNMANAGED) == 0)
6070 newpde |= PG_MANAGED;
6071 if ((prot & VM_PROT_EXECUTE) == 0)
6073 if (va < VM_MAXUSER_ADDRESS)
6075 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
6076 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
6081 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
6082 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
6083 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
6084 * a mapping already exists at the specified virtual address. Returns
6085 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
6086 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
6087 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
6089 * The parameter "m" is only used when creating a managed, writeable mapping.
6092 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
6093 vm_page_t m, struct rwlock **lockp)
6095 struct spglist free;
6096 pd_entry_t oldpde, *pde;
6097 pt_entry_t PG_G, PG_RW, PG_V;
6100 KASSERT(pmap == kernel_pmap || (newpde & PG_W) == 0,
6101 ("pmap_enter_pde: cannot create wired user mapping"));
6102 PG_G = pmap_global_bit(pmap);
6103 PG_RW = pmap_rw_bit(pmap);
6104 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
6105 ("pmap_enter_pde: newpde is missing PG_M"));
6106 PG_V = pmap_valid_bit(pmap);
6107 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6109 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
6110 NULL : lockp)) == NULL) {
6111 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
6112 " in pmap %p", va, pmap);
6113 return (KERN_RESOURCE_SHORTAGE);
6117 * If pkru is not same for the whole pde range, return failure
6118 * and let vm_fault() cope. Check after pde allocation, since
6121 if (!pmap_pkru_same(pmap, va, va + NBPDR)) {
6123 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
6124 pmap_invalidate_page(pmap, va);
6125 vm_page_free_pages_toq(&free, true);
6127 return (KERN_FAILURE);
6129 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86) {
6130 newpde &= ~X86_PG_PKU_MASK;
6131 newpde |= pmap_pkru_get(pmap, va);
6134 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
6135 pde = &pde[pmap_pde_index(va)];
6137 if ((oldpde & PG_V) != 0) {
6138 KASSERT(pdpg->ref_count > 1,
6139 ("pmap_enter_pde: pdpg's reference count is too low"));
6140 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
6142 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
6143 " in pmap %p", va, pmap);
6144 return (KERN_FAILURE);
6146 /* Break the existing mapping(s). */
6148 if ((oldpde & PG_PS) != 0) {
6150 * The reference to the PD page that was acquired by
6151 * pmap_allocpde() ensures that it won't be freed.
6152 * However, if the PDE resulted from a promotion, then
6153 * a reserved PT page could be freed.
6155 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
6156 if ((oldpde & PG_G) == 0)
6157 pmap_invalidate_pde_page(pmap, va, oldpde);
6159 pmap_delayed_invl_start();
6160 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
6162 pmap_invalidate_all(pmap);
6163 pmap_delayed_invl_finish();
6165 vm_page_free_pages_toq(&free, true);
6166 if (va >= VM_MAXUSER_ADDRESS) {
6168 * Both pmap_remove_pde() and pmap_remove_ptes() will
6169 * leave the kernel page table page zero filled.
6171 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
6172 if (pmap_insert_pt_page(pmap, mt, false))
6173 panic("pmap_enter_pde: trie insert failed");
6175 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
6178 if ((newpde & PG_MANAGED) != 0) {
6180 * Abort this mapping if its PV entry could not be created.
6182 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
6184 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
6186 * Although "va" is not mapped, paging-
6187 * structure caches could nonetheless have
6188 * entries that refer to the freed page table
6189 * pages. Invalidate those entries.
6191 pmap_invalidate_page(pmap, va);
6192 vm_page_free_pages_toq(&free, true);
6194 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
6195 " in pmap %p", va, pmap);
6196 return (KERN_RESOURCE_SHORTAGE);
6198 if ((newpde & PG_RW) != 0) {
6199 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6200 vm_page_aflag_set(mt, PGA_WRITEABLE);
6205 * Increment counters.
6207 if ((newpde & PG_W) != 0)
6208 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
6209 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
6212 * Map the superpage. (This is not a promoted mapping; there will not
6213 * be any lingering 4KB page mappings in the TLB.)
6215 pde_store(pde, newpde);
6217 atomic_add_long(&pmap_pde_mappings, 1);
6218 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
6219 " in pmap %p", va, pmap);
6220 return (KERN_SUCCESS);
6224 * Maps a sequence of resident pages belonging to the same object.
6225 * The sequence begins with the given page m_start. This page is
6226 * mapped at the given virtual address start. Each subsequent page is
6227 * mapped at a virtual address that is offset from start by the same
6228 * amount as the page is offset from m_start within the object. The
6229 * last page in the sequence is the page with the largest offset from
6230 * m_start that can be mapped at a virtual address less than the given
6231 * virtual address end. Not every virtual page between start and end
6232 * is mapped; only those for which a resident page exists with the
6233 * corresponding offset from m_start are mapped.
6236 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
6237 vm_page_t m_start, vm_prot_t prot)
6239 struct rwlock *lock;
6242 vm_pindex_t diff, psize;
6244 VM_OBJECT_ASSERT_LOCKED(m_start->object);
6246 psize = atop(end - start);
6251 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
6252 va = start + ptoa(diff);
6253 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
6254 m->psind == 1 && pmap_ps_enabled(pmap) &&
6255 pmap_enter_2mpage(pmap, va, m, prot, &lock))
6256 m = &m[NBPDR / PAGE_SIZE - 1];
6258 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
6260 m = TAILQ_NEXT(m, listq);
6268 * this code makes some *MAJOR* assumptions:
6269 * 1. Current pmap & pmap exists.
6272 * 4. No page table pages.
6273 * but is *MUCH* faster than pmap_enter...
6277 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
6279 struct rwlock *lock;
6283 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
6290 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
6291 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
6293 struct spglist free;
6294 pt_entry_t newpte, *pte, PG_V;
6296 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
6297 (m->oflags & VPO_UNMANAGED) != 0,
6298 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
6299 PG_V = pmap_valid_bit(pmap);
6300 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6303 * In the case that a page table page is not
6304 * resident, we are creating it here.
6306 if (va < VM_MAXUSER_ADDRESS) {
6307 vm_pindex_t ptepindex;
6311 * Calculate pagetable page index
6313 ptepindex = pmap_pde_pindex(va);
6314 if (mpte && (mpte->pindex == ptepindex)) {
6318 * Get the page directory entry
6320 ptepa = pmap_pde(pmap, va);
6323 * If the page table page is mapped, we just increment
6324 * the hold count, and activate it. Otherwise, we
6325 * attempt to allocate a page table page. If this
6326 * attempt fails, we don't retry. Instead, we give up.
6328 if (ptepa && (*ptepa & PG_V) != 0) {
6331 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
6335 * Pass NULL instead of the PV list lock
6336 * pointer, because we don't intend to sleep.
6338 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
6343 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
6344 pte = &pte[pmap_pte_index(va)];
6358 * Enter on the PV list if part of our managed memory.
6360 if ((m->oflags & VPO_UNMANAGED) == 0 &&
6361 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
6364 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
6366 * Although "va" is not mapped, paging-
6367 * structure caches could nonetheless have
6368 * entries that refer to the freed page table
6369 * pages. Invalidate those entries.
6371 pmap_invalidate_page(pmap, va);
6372 vm_page_free_pages_toq(&free, true);
6380 * Increment counters
6382 pmap_resident_count_inc(pmap, 1);
6384 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
6385 pmap_cache_bits(pmap, m->md.pat_mode, 0);
6386 if ((m->oflags & VPO_UNMANAGED) == 0)
6387 newpte |= PG_MANAGED;
6388 if ((prot & VM_PROT_EXECUTE) == 0)
6390 if (va < VM_MAXUSER_ADDRESS)
6391 newpte |= PG_U | pmap_pkru_get(pmap, va);
6392 pte_store(pte, newpte);
6397 * Make a temporary mapping for a physical address. This is only intended
6398 * to be used for panic dumps.
6401 pmap_kenter_temporary(vm_paddr_t pa, int i)
6405 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
6406 pmap_kenter(va, pa);
6408 return ((void *)crashdumpmap);
6412 * This code maps large physical mmap regions into the
6413 * processor address space. Note that some shortcuts
6414 * are taken, but the code works.
6417 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
6418 vm_pindex_t pindex, vm_size_t size)
6421 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6422 vm_paddr_t pa, ptepa;
6426 PG_A = pmap_accessed_bit(pmap);
6427 PG_M = pmap_modified_bit(pmap);
6428 PG_V = pmap_valid_bit(pmap);
6429 PG_RW = pmap_rw_bit(pmap);
6431 VM_OBJECT_ASSERT_WLOCKED(object);
6432 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
6433 ("pmap_object_init_pt: non-device object"));
6434 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
6435 if (!pmap_ps_enabled(pmap))
6437 if (!vm_object_populate(object, pindex, pindex + atop(size)))
6439 p = vm_page_lookup(object, pindex);
6440 KASSERT(p->valid == VM_PAGE_BITS_ALL,
6441 ("pmap_object_init_pt: invalid page %p", p));
6442 pat_mode = p->md.pat_mode;
6445 * Abort the mapping if the first page is not physically
6446 * aligned to a 2MB page boundary.
6448 ptepa = VM_PAGE_TO_PHYS(p);
6449 if (ptepa & (NBPDR - 1))
6453 * Skip the first page. Abort the mapping if the rest of
6454 * the pages are not physically contiguous or have differing
6455 * memory attributes.
6457 p = TAILQ_NEXT(p, listq);
6458 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
6460 KASSERT(p->valid == VM_PAGE_BITS_ALL,
6461 ("pmap_object_init_pt: invalid page %p", p));
6462 if (pa != VM_PAGE_TO_PHYS(p) ||
6463 pat_mode != p->md.pat_mode)
6465 p = TAILQ_NEXT(p, listq);
6469 * Map using 2MB pages. Since "ptepa" is 2M aligned and
6470 * "size" is a multiple of 2M, adding the PAT setting to "pa"
6471 * will not affect the termination of this loop.
6474 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
6475 pa < ptepa + size; pa += NBPDR) {
6476 pdpg = pmap_allocpde(pmap, addr, NULL);
6479 * The creation of mappings below is only an
6480 * optimization. If a page directory page
6481 * cannot be allocated without blocking,
6482 * continue on to the next mapping rather than
6488 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
6489 pde = &pde[pmap_pde_index(addr)];
6490 if ((*pde & PG_V) == 0) {
6491 pde_store(pde, pa | PG_PS | PG_M | PG_A |
6492 PG_U | PG_RW | PG_V);
6493 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
6494 atomic_add_long(&pmap_pde_mappings, 1);
6496 /* Continue on if the PDE is already valid. */
6498 KASSERT(pdpg->ref_count > 0,
6499 ("pmap_object_init_pt: missing reference "
6500 "to page directory page, va: 0x%lx", addr));
6509 * Clear the wired attribute from the mappings for the specified range of
6510 * addresses in the given pmap. Every valid mapping within that range
6511 * must have the wired attribute set. In contrast, invalid mappings
6512 * cannot have the wired attribute set, so they are ignored.
6514 * The wired attribute of the page table entry is not a hardware
6515 * feature, so there is no need to invalidate any TLB entries.
6516 * Since pmap_demote_pde() for the wired entry must never fail,
6517 * pmap_delayed_invl_start()/finish() calls around the
6518 * function are not needed.
6521 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6523 vm_offset_t va_next;
6524 pml4_entry_t *pml4e;
6527 pt_entry_t *pte, PG_V;
6529 PG_V = pmap_valid_bit(pmap);
6531 for (; sva < eva; sva = va_next) {
6532 pml4e = pmap_pml4e(pmap, sva);
6533 if ((*pml4e & PG_V) == 0) {
6534 va_next = (sva + NBPML4) & ~PML4MASK;
6539 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6540 if ((*pdpe & PG_V) == 0) {
6541 va_next = (sva + NBPDP) & ~PDPMASK;
6546 va_next = (sva + NBPDR) & ~PDRMASK;
6549 pde = pmap_pdpe_to_pde(pdpe, sva);
6550 if ((*pde & PG_V) == 0)
6552 if ((*pde & PG_PS) != 0) {
6553 if ((*pde & PG_W) == 0)
6554 panic("pmap_unwire: pde %#jx is missing PG_W",
6558 * Are we unwiring the entire large page? If not,
6559 * demote the mapping and fall through.
6561 if (sva + NBPDR == va_next && eva >= va_next) {
6562 atomic_clear_long(pde, PG_W);
6563 pmap->pm_stats.wired_count -= NBPDR /
6566 } else if (!pmap_demote_pde(pmap, pde, sva))
6567 panic("pmap_unwire: demotion failed");
6571 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6573 if ((*pte & PG_V) == 0)
6575 if ((*pte & PG_W) == 0)
6576 panic("pmap_unwire: pte %#jx is missing PG_W",
6580 * PG_W must be cleared atomically. Although the pmap
6581 * lock synchronizes access to PG_W, another processor
6582 * could be setting PG_M and/or PG_A concurrently.
6584 atomic_clear_long(pte, PG_W);
6585 pmap->pm_stats.wired_count--;
6592 * Copy the range specified by src_addr/len
6593 * from the source map to the range dst_addr/len
6594 * in the destination map.
6596 * This routine is only advisory and need not do anything.
6599 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
6600 vm_offset_t src_addr)
6602 struct rwlock *lock;
6603 struct spglist free;
6604 pml4_entry_t *pml4e;
6606 pd_entry_t *pde, srcptepaddr;
6607 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
6608 vm_offset_t addr, end_addr, va_next;
6609 vm_page_t dst_pdpg, dstmpte, srcmpte;
6611 if (dst_addr != src_addr)
6614 if (dst_pmap->pm_type != src_pmap->pm_type)
6618 * EPT page table entries that require emulation of A/D bits are
6619 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
6620 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
6621 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
6622 * implementations flag an EPT misconfiguration for exec-only
6623 * mappings we skip this function entirely for emulated pmaps.
6625 if (pmap_emulate_ad_bits(dst_pmap))
6628 end_addr = src_addr + len;
6630 if (dst_pmap < src_pmap) {
6631 PMAP_LOCK(dst_pmap);
6632 PMAP_LOCK(src_pmap);
6634 PMAP_LOCK(src_pmap);
6635 PMAP_LOCK(dst_pmap);
6638 PG_A = pmap_accessed_bit(dst_pmap);
6639 PG_M = pmap_modified_bit(dst_pmap);
6640 PG_V = pmap_valid_bit(dst_pmap);
6642 for (addr = src_addr; addr < end_addr; addr = va_next) {
6643 KASSERT(addr < UPT_MIN_ADDRESS,
6644 ("pmap_copy: invalid to pmap_copy page tables"));
6646 pml4e = pmap_pml4e(src_pmap, addr);
6647 if ((*pml4e & PG_V) == 0) {
6648 va_next = (addr + NBPML4) & ~PML4MASK;
6654 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
6655 if ((*pdpe & PG_V) == 0) {
6656 va_next = (addr + NBPDP) & ~PDPMASK;
6662 va_next = (addr + NBPDR) & ~PDRMASK;
6666 pde = pmap_pdpe_to_pde(pdpe, addr);
6668 if (srcptepaddr == 0)
6671 if (srcptepaddr & PG_PS) {
6672 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
6674 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
6675 if (dst_pdpg == NULL)
6677 pde = (pd_entry_t *)
6678 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
6679 pde = &pde[pmap_pde_index(addr)];
6680 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
6681 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
6682 PMAP_ENTER_NORECLAIM, &lock))) {
6683 *pde = srcptepaddr & ~PG_W;
6684 pmap_resident_count_inc(dst_pmap, NBPDR /
6686 atomic_add_long(&pmap_pde_mappings, 1);
6688 dst_pdpg->ref_count--;
6692 srcptepaddr &= PG_FRAME;
6693 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
6694 KASSERT(srcmpte->ref_count > 0,
6695 ("pmap_copy: source page table page is unused"));
6697 if (va_next > end_addr)
6700 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
6701 src_pte = &src_pte[pmap_pte_index(addr)];
6703 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
6707 * We only virtual copy managed pages.
6709 if ((ptetemp & PG_MANAGED) == 0)
6712 if (dstmpte != NULL) {
6713 KASSERT(dstmpte->pindex ==
6714 pmap_pde_pindex(addr),
6715 ("dstmpte pindex/addr mismatch"));
6716 dstmpte->ref_count++;
6717 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
6720 dst_pte = (pt_entry_t *)
6721 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
6722 dst_pte = &dst_pte[pmap_pte_index(addr)];
6723 if (*dst_pte == 0 &&
6724 pmap_try_insert_pv_entry(dst_pmap, addr,
6725 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
6727 * Clear the wired, modified, and accessed
6728 * (referenced) bits during the copy.
6730 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
6731 pmap_resident_count_inc(dst_pmap, 1);
6734 if (pmap_unwire_ptp(dst_pmap, addr, dstmpte,
6737 * Although "addr" is not mapped,
6738 * paging-structure caches could
6739 * nonetheless have entries that refer
6740 * to the freed page table pages.
6741 * Invalidate those entries.
6743 pmap_invalidate_page(dst_pmap, addr);
6744 vm_page_free_pages_toq(&free, true);
6748 /* Have we copied all of the valid mappings? */
6749 if (dstmpte->ref_count >= srcmpte->ref_count)
6756 PMAP_UNLOCK(src_pmap);
6757 PMAP_UNLOCK(dst_pmap);
6761 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
6765 if (dst_pmap->pm_type != src_pmap->pm_type ||
6766 dst_pmap->pm_type != PT_X86 ||
6767 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
6770 if (dst_pmap < src_pmap) {
6771 PMAP_LOCK(dst_pmap);
6772 PMAP_LOCK(src_pmap);
6774 PMAP_LOCK(src_pmap);
6775 PMAP_LOCK(dst_pmap);
6777 error = pmap_pkru_copy(dst_pmap, src_pmap);
6778 /* Clean up partial copy on failure due to no memory. */
6779 if (error == ENOMEM)
6780 pmap_pkru_deassign_all(dst_pmap);
6781 PMAP_UNLOCK(src_pmap);
6782 PMAP_UNLOCK(dst_pmap);
6783 if (error != ENOMEM)
6791 * Zero the specified hardware page.
6794 pmap_zero_page(vm_page_t m)
6796 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
6798 pagezero((void *)va);
6802 * Zero an an area within a single hardware page. off and size must not
6803 * cover an area beyond a single hardware page.
6806 pmap_zero_page_area(vm_page_t m, int off, int size)
6808 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
6810 if (off == 0 && size == PAGE_SIZE)
6811 pagezero((void *)va);
6813 bzero((char *)va + off, size);
6817 * Copy 1 specified hardware page to another.
6820 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
6822 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
6823 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
6825 pagecopy((void *)src, (void *)dst);
6828 int unmapped_buf_allowed = 1;
6831 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
6832 vm_offset_t b_offset, int xfersize)
6836 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
6840 while (xfersize > 0) {
6841 a_pg_offset = a_offset & PAGE_MASK;
6842 pages[0] = ma[a_offset >> PAGE_SHIFT];
6843 b_pg_offset = b_offset & PAGE_MASK;
6844 pages[1] = mb[b_offset >> PAGE_SHIFT];
6845 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
6846 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
6847 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
6848 a_cp = (char *)vaddr[0] + a_pg_offset;
6849 b_cp = (char *)vaddr[1] + b_pg_offset;
6850 bcopy(a_cp, b_cp, cnt);
6851 if (__predict_false(mapped))
6852 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
6860 * Returns true if the pmap's pv is one of the first
6861 * 16 pvs linked to from this page. This count may
6862 * be changed upwards or downwards in the future; it
6863 * is only necessary that true be returned for a small
6864 * subset of pmaps for proper page aging.
6867 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
6869 struct md_page *pvh;
6870 struct rwlock *lock;
6875 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6876 ("pmap_page_exists_quick: page %p is not managed", m));
6878 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6880 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6881 if (PV_PMAP(pv) == pmap) {
6889 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
6890 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6891 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6892 if (PV_PMAP(pv) == pmap) {
6906 * pmap_page_wired_mappings:
6908 * Return the number of managed mappings to the given physical page
6912 pmap_page_wired_mappings(vm_page_t m)
6914 struct rwlock *lock;
6915 struct md_page *pvh;
6919 int count, md_gen, pvh_gen;
6921 if ((m->oflags & VPO_UNMANAGED) != 0)
6923 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6927 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6929 if (!PMAP_TRYLOCK(pmap)) {
6930 md_gen = m->md.pv_gen;
6934 if (md_gen != m->md.pv_gen) {
6939 pte = pmap_pte(pmap, pv->pv_va);
6940 if ((*pte & PG_W) != 0)
6944 if ((m->flags & PG_FICTITIOUS) == 0) {
6945 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6946 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6948 if (!PMAP_TRYLOCK(pmap)) {
6949 md_gen = m->md.pv_gen;
6950 pvh_gen = pvh->pv_gen;
6954 if (md_gen != m->md.pv_gen ||
6955 pvh_gen != pvh->pv_gen) {
6960 pte = pmap_pde(pmap, pv->pv_va);
6961 if ((*pte & PG_W) != 0)
6971 * Returns TRUE if the given page is mapped individually or as part of
6972 * a 2mpage. Otherwise, returns FALSE.
6975 pmap_page_is_mapped(vm_page_t m)
6977 struct rwlock *lock;
6980 if ((m->oflags & VPO_UNMANAGED) != 0)
6982 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6984 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
6985 ((m->flags & PG_FICTITIOUS) == 0 &&
6986 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
6992 * Destroy all managed, non-wired mappings in the given user-space
6993 * pmap. This pmap cannot be active on any processor besides the
6996 * This function cannot be applied to the kernel pmap. Moreover, it
6997 * is not intended for general use. It is only to be used during
6998 * process termination. Consequently, it can be implemented in ways
6999 * that make it faster than pmap_remove(). First, it can more quickly
7000 * destroy mappings by iterating over the pmap's collection of PV
7001 * entries, rather than searching the page table. Second, it doesn't
7002 * have to test and clear the page table entries atomically, because
7003 * no processor is currently accessing the user address space. In
7004 * particular, a page table entry's dirty bit won't change state once
7005 * this function starts.
7007 * Although this function destroys all of the pmap's managed,
7008 * non-wired mappings, it can delay and batch the invalidation of TLB
7009 * entries without calling pmap_delayed_invl_start() and
7010 * pmap_delayed_invl_finish(). Because the pmap is not active on
7011 * any other processor, none of these TLB entries will ever be used
7012 * before their eventual invalidation. Consequently, there is no need
7013 * for either pmap_remove_all() or pmap_remove_write() to wait for
7014 * that eventual TLB invalidation.
7017 pmap_remove_pages(pmap_t pmap)
7020 pt_entry_t *pte, tpte;
7021 pt_entry_t PG_M, PG_RW, PG_V;
7022 struct spglist free;
7023 struct pv_chunklist free_chunks;
7024 vm_page_t m, mpte, mt;
7026 struct md_page *pvh;
7027 struct pv_chunk *pc, *npc;
7028 struct rwlock *lock;
7030 uint64_t inuse, bitmask;
7031 int allfree, field, freed, idx;
7032 boolean_t superpage;
7036 * Assert that the given pmap is only active on the current
7037 * CPU. Unfortunately, we cannot block another CPU from
7038 * activating the pmap while this function is executing.
7040 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
7043 cpuset_t other_cpus;
7045 other_cpus = all_cpus;
7047 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
7048 CPU_AND(&other_cpus, &pmap->pm_active);
7050 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
7055 PG_M = pmap_modified_bit(pmap);
7056 PG_V = pmap_valid_bit(pmap);
7057 PG_RW = pmap_rw_bit(pmap);
7059 TAILQ_INIT(&free_chunks);
7062 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
7065 for (field = 0; field < _NPCM; field++) {
7066 inuse = ~pc->pc_map[field] & pc_freemask[field];
7067 while (inuse != 0) {
7069 bitmask = 1UL << bit;
7070 idx = field * 64 + bit;
7071 pv = &pc->pc_pventry[idx];
7074 pte = pmap_pdpe(pmap, pv->pv_va);
7076 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
7078 if ((tpte & (PG_PS | PG_V)) == PG_V) {
7081 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
7083 pte = &pte[pmap_pte_index(pv->pv_va)];
7087 * Keep track whether 'tpte' is a
7088 * superpage explicitly instead of
7089 * relying on PG_PS being set.
7091 * This is because PG_PS is numerically
7092 * identical to PG_PTE_PAT and thus a
7093 * regular page could be mistaken for
7099 if ((tpte & PG_V) == 0) {
7100 panic("bad pte va %lx pte %lx",
7105 * We cannot remove wired pages from a process' mapping at this time
7113 pa = tpte & PG_PS_FRAME;
7115 pa = tpte & PG_FRAME;
7117 m = PHYS_TO_VM_PAGE(pa);
7118 KASSERT(m->phys_addr == pa,
7119 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
7120 m, (uintmax_t)m->phys_addr,
7123 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
7124 m < &vm_page_array[vm_page_array_size],
7125 ("pmap_remove_pages: bad tpte %#jx",
7131 * Update the vm_page_t clean/reference bits.
7133 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
7135 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7141 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
7144 pc->pc_map[field] |= bitmask;
7146 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
7147 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
7148 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
7150 if (TAILQ_EMPTY(&pvh->pv_list)) {
7151 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7152 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
7153 TAILQ_EMPTY(&mt->md.pv_list))
7154 vm_page_aflag_clear(mt, PGA_WRITEABLE);
7156 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
7158 KASSERT(mpte->valid == VM_PAGE_BITS_ALL,
7159 ("pmap_remove_pages: pte page not promoted"));
7160 pmap_resident_count_dec(pmap, 1);
7161 KASSERT(mpte->ref_count == NPTEPG,
7162 ("pmap_remove_pages: pte page reference count error"));
7163 mpte->ref_count = 0;
7164 pmap_add_delayed_free_list(mpte, &free, FALSE);
7167 pmap_resident_count_dec(pmap, 1);
7168 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
7170 if ((m->aflags & PGA_WRITEABLE) != 0 &&
7171 TAILQ_EMPTY(&m->md.pv_list) &&
7172 (m->flags & PG_FICTITIOUS) == 0) {
7173 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
7174 if (TAILQ_EMPTY(&pvh->pv_list))
7175 vm_page_aflag_clear(m, PGA_WRITEABLE);
7178 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
7182 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
7183 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
7184 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
7186 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
7187 TAILQ_INSERT_TAIL(&free_chunks, pc, pc_list);
7192 pmap_invalidate_all(pmap);
7193 pmap_pkru_deassign_all(pmap);
7194 free_pv_chunk_batch(&free_chunks);
7196 vm_page_free_pages_toq(&free, true);
7200 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
7202 struct rwlock *lock;
7204 struct md_page *pvh;
7205 pt_entry_t *pte, mask;
7206 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7208 int md_gen, pvh_gen;
7212 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7215 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7217 if (!PMAP_TRYLOCK(pmap)) {
7218 md_gen = m->md.pv_gen;
7222 if (md_gen != m->md.pv_gen) {
7227 pte = pmap_pte(pmap, pv->pv_va);
7230 PG_M = pmap_modified_bit(pmap);
7231 PG_RW = pmap_rw_bit(pmap);
7232 mask |= PG_RW | PG_M;
7235 PG_A = pmap_accessed_bit(pmap);
7236 PG_V = pmap_valid_bit(pmap);
7237 mask |= PG_V | PG_A;
7239 rv = (*pte & mask) == mask;
7244 if ((m->flags & PG_FICTITIOUS) == 0) {
7245 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
7246 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
7248 if (!PMAP_TRYLOCK(pmap)) {
7249 md_gen = m->md.pv_gen;
7250 pvh_gen = pvh->pv_gen;
7254 if (md_gen != m->md.pv_gen ||
7255 pvh_gen != pvh->pv_gen) {
7260 pte = pmap_pde(pmap, pv->pv_va);
7263 PG_M = pmap_modified_bit(pmap);
7264 PG_RW = pmap_rw_bit(pmap);
7265 mask |= PG_RW | PG_M;
7268 PG_A = pmap_accessed_bit(pmap);
7269 PG_V = pmap_valid_bit(pmap);
7270 mask |= PG_V | PG_A;
7272 rv = (*pte & mask) == mask;
7286 * Return whether or not the specified physical page was modified
7287 * in any physical maps.
7290 pmap_is_modified(vm_page_t m)
7293 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7294 ("pmap_is_modified: page %p is not managed", m));
7297 * If the page is not busied then this check is racy.
7299 if (!pmap_page_is_write_mapped(m))
7301 return (pmap_page_test_mappings(m, FALSE, TRUE));
7305 * pmap_is_prefaultable:
7307 * Return whether or not the specified virtual address is eligible
7311 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
7314 pt_entry_t *pte, PG_V;
7317 PG_V = pmap_valid_bit(pmap);
7320 pde = pmap_pde(pmap, addr);
7321 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
7322 pte = pmap_pde_to_pte(pde, addr);
7323 rv = (*pte & PG_V) == 0;
7330 * pmap_is_referenced:
7332 * Return whether or not the specified physical page was referenced
7333 * in any physical maps.
7336 pmap_is_referenced(vm_page_t m)
7339 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7340 ("pmap_is_referenced: page %p is not managed", m));
7341 return (pmap_page_test_mappings(m, TRUE, FALSE));
7345 * Clear the write and modified bits in each of the given page's mappings.
7348 pmap_remove_write(vm_page_t m)
7350 struct md_page *pvh;
7352 struct rwlock *lock;
7353 pv_entry_t next_pv, pv;
7355 pt_entry_t oldpte, *pte, PG_M, PG_RW;
7357 int pvh_gen, md_gen;
7359 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7360 ("pmap_remove_write: page %p is not managed", m));
7362 vm_page_assert_busied(m);
7363 if (!pmap_page_is_write_mapped(m))
7366 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7367 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
7368 pa_to_pvh(VM_PAGE_TO_PHYS(m));
7371 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
7373 if (!PMAP_TRYLOCK(pmap)) {
7374 pvh_gen = pvh->pv_gen;
7378 if (pvh_gen != pvh->pv_gen) {
7384 PG_RW = pmap_rw_bit(pmap);
7386 pde = pmap_pde(pmap, va);
7387 if ((*pde & PG_RW) != 0)
7388 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
7389 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
7390 ("inconsistent pv lock %p %p for page %p",
7391 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
7394 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7396 if (!PMAP_TRYLOCK(pmap)) {
7397 pvh_gen = pvh->pv_gen;
7398 md_gen = m->md.pv_gen;
7402 if (pvh_gen != pvh->pv_gen ||
7403 md_gen != m->md.pv_gen) {
7409 PG_M = pmap_modified_bit(pmap);
7410 PG_RW = pmap_rw_bit(pmap);
7411 pde = pmap_pde(pmap, pv->pv_va);
7412 KASSERT((*pde & PG_PS) == 0,
7413 ("pmap_remove_write: found a 2mpage in page %p's pv list",
7415 pte = pmap_pde_to_pte(pde, pv->pv_va);
7418 if (oldpte & PG_RW) {
7419 if (!atomic_cmpset_long(pte, oldpte, oldpte &
7422 if ((oldpte & PG_M) != 0)
7424 pmap_invalidate_page(pmap, pv->pv_va);
7429 vm_page_aflag_clear(m, PGA_WRITEABLE);
7430 pmap_delayed_invl_wait(m);
7433 static __inline boolean_t
7434 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
7437 if (!pmap_emulate_ad_bits(pmap))
7440 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
7443 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
7444 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
7445 * if the EPT_PG_WRITE bit is set.
7447 if ((pte & EPT_PG_WRITE) != 0)
7451 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
7453 if ((pte & EPT_PG_EXECUTE) == 0 ||
7454 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
7461 * pmap_ts_referenced:
7463 * Return a count of reference bits for a page, clearing those bits.
7464 * It is not necessary for every reference bit to be cleared, but it
7465 * is necessary that 0 only be returned when there are truly no
7466 * reference bits set.
7468 * As an optimization, update the page's dirty field if a modified bit is
7469 * found while counting reference bits. This opportunistic update can be
7470 * performed at low cost and can eliminate the need for some future calls
7471 * to pmap_is_modified(). However, since this function stops after
7472 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
7473 * dirty pages. Those dirty pages will only be detected by a future call
7474 * to pmap_is_modified().
7476 * A DI block is not needed within this function, because
7477 * invalidations are performed before the PV list lock is
7481 pmap_ts_referenced(vm_page_t m)
7483 struct md_page *pvh;
7486 struct rwlock *lock;
7487 pd_entry_t oldpde, *pde;
7488 pt_entry_t *pte, PG_A, PG_M, PG_RW;
7491 int cleared, md_gen, not_cleared, pvh_gen;
7492 struct spglist free;
7495 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7496 ("pmap_ts_referenced: page %p is not managed", m));
7499 pa = VM_PAGE_TO_PHYS(m);
7500 lock = PHYS_TO_PV_LIST_LOCK(pa);
7501 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
7505 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
7506 goto small_mappings;
7512 if (!PMAP_TRYLOCK(pmap)) {
7513 pvh_gen = pvh->pv_gen;
7517 if (pvh_gen != pvh->pv_gen) {
7522 PG_A = pmap_accessed_bit(pmap);
7523 PG_M = pmap_modified_bit(pmap);
7524 PG_RW = pmap_rw_bit(pmap);
7526 pde = pmap_pde(pmap, pv->pv_va);
7528 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
7530 * Although "oldpde" is mapping a 2MB page, because
7531 * this function is called at a 4KB page granularity,
7532 * we only update the 4KB page under test.
7536 if ((oldpde & PG_A) != 0) {
7538 * Since this reference bit is shared by 512 4KB
7539 * pages, it should not be cleared every time it is
7540 * tested. Apply a simple "hash" function on the
7541 * physical page number, the virtual superpage number,
7542 * and the pmap address to select one 4KB page out of
7543 * the 512 on which testing the reference bit will
7544 * result in clearing that reference bit. This
7545 * function is designed to avoid the selection of the
7546 * same 4KB page for every 2MB page mapping.
7548 * On demotion, a mapping that hasn't been referenced
7549 * is simply destroyed. To avoid the possibility of a
7550 * subsequent page fault on a demoted wired mapping,
7551 * always leave its reference bit set. Moreover,
7552 * since the superpage is wired, the current state of
7553 * its reference bit won't affect page replacement.
7555 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
7556 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
7557 (oldpde & PG_W) == 0) {
7558 if (safe_to_clear_referenced(pmap, oldpde)) {
7559 atomic_clear_long(pde, PG_A);
7560 pmap_invalidate_page(pmap, pv->pv_va);
7562 } else if (pmap_demote_pde_locked(pmap, pde,
7563 pv->pv_va, &lock)) {
7565 * Remove the mapping to a single page
7566 * so that a subsequent access may
7567 * repromote. Since the underlying
7568 * page table page is fully populated,
7569 * this removal never frees a page
7573 va += VM_PAGE_TO_PHYS(m) - (oldpde &
7575 pte = pmap_pde_to_pte(pde, va);
7576 pmap_remove_pte(pmap, pte, va, *pde,
7578 pmap_invalidate_page(pmap, va);
7584 * The superpage mapping was removed
7585 * entirely and therefore 'pv' is no
7593 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
7594 ("inconsistent pv lock %p %p for page %p",
7595 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
7600 /* Rotate the PV list if it has more than one entry. */
7601 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
7602 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
7603 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
7606 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
7608 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
7610 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
7617 if (!PMAP_TRYLOCK(pmap)) {
7618 pvh_gen = pvh->pv_gen;
7619 md_gen = m->md.pv_gen;
7623 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
7628 PG_A = pmap_accessed_bit(pmap);
7629 PG_M = pmap_modified_bit(pmap);
7630 PG_RW = pmap_rw_bit(pmap);
7631 pde = pmap_pde(pmap, pv->pv_va);
7632 KASSERT((*pde & PG_PS) == 0,
7633 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
7635 pte = pmap_pde_to_pte(pde, pv->pv_va);
7636 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7638 if ((*pte & PG_A) != 0) {
7639 if (safe_to_clear_referenced(pmap, *pte)) {
7640 atomic_clear_long(pte, PG_A);
7641 pmap_invalidate_page(pmap, pv->pv_va);
7643 } else if ((*pte & PG_W) == 0) {
7645 * Wired pages cannot be paged out so
7646 * doing accessed bit emulation for
7647 * them is wasted effort. We do the
7648 * hard work for unwired pages only.
7650 pmap_remove_pte(pmap, pte, pv->pv_va,
7651 *pde, &free, &lock);
7652 pmap_invalidate_page(pmap, pv->pv_va);
7657 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
7658 ("inconsistent pv lock %p %p for page %p",
7659 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
7664 /* Rotate the PV list if it has more than one entry. */
7665 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
7666 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
7667 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7670 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
7671 not_cleared < PMAP_TS_REFERENCED_MAX);
7674 vm_page_free_pages_toq(&free, true);
7675 return (cleared + not_cleared);
7679 * Apply the given advice to the specified range of addresses within the
7680 * given pmap. Depending on the advice, clear the referenced and/or
7681 * modified flags in each mapping and set the mapped page's dirty field.
7684 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
7686 struct rwlock *lock;
7687 pml4_entry_t *pml4e;
7689 pd_entry_t oldpde, *pde;
7690 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
7691 vm_offset_t va, va_next;
7695 if (advice != MADV_DONTNEED && advice != MADV_FREE)
7699 * A/D bit emulation requires an alternate code path when clearing
7700 * the modified and accessed bits below. Since this function is
7701 * advisory in nature we skip it entirely for pmaps that require
7702 * A/D bit emulation.
7704 if (pmap_emulate_ad_bits(pmap))
7707 PG_A = pmap_accessed_bit(pmap);
7708 PG_G = pmap_global_bit(pmap);
7709 PG_M = pmap_modified_bit(pmap);
7710 PG_V = pmap_valid_bit(pmap);
7711 PG_RW = pmap_rw_bit(pmap);
7713 pmap_delayed_invl_start();
7715 for (; sva < eva; sva = va_next) {
7716 pml4e = pmap_pml4e(pmap, sva);
7717 if ((*pml4e & PG_V) == 0) {
7718 va_next = (sva + NBPML4) & ~PML4MASK;
7723 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
7724 if ((*pdpe & PG_V) == 0) {
7725 va_next = (sva + NBPDP) & ~PDPMASK;
7730 va_next = (sva + NBPDR) & ~PDRMASK;
7733 pde = pmap_pdpe_to_pde(pdpe, sva);
7735 if ((oldpde & PG_V) == 0)
7737 else if ((oldpde & PG_PS) != 0) {
7738 if ((oldpde & PG_MANAGED) == 0)
7741 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
7746 * The large page mapping was destroyed.
7752 * Unless the page mappings are wired, remove the
7753 * mapping to a single page so that a subsequent
7754 * access may repromote. Choosing the last page
7755 * within the address range [sva, min(va_next, eva))
7756 * generally results in more repromotions. Since the
7757 * underlying page table page is fully populated, this
7758 * removal never frees a page table page.
7760 if ((oldpde & PG_W) == 0) {
7766 ("pmap_advise: no address gap"));
7767 pte = pmap_pde_to_pte(pde, va);
7768 KASSERT((*pte & PG_V) != 0,
7769 ("pmap_advise: invalid PTE"));
7770 pmap_remove_pte(pmap, pte, va, *pde, NULL,
7780 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
7782 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
7784 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
7785 if (advice == MADV_DONTNEED) {
7787 * Future calls to pmap_is_modified()
7788 * can be avoided by making the page
7791 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7794 atomic_clear_long(pte, PG_M | PG_A);
7795 } else if ((*pte & PG_A) != 0)
7796 atomic_clear_long(pte, PG_A);
7800 if ((*pte & PG_G) != 0) {
7807 if (va != va_next) {
7808 pmap_invalidate_range(pmap, va, sva);
7813 pmap_invalidate_range(pmap, va, sva);
7816 pmap_invalidate_all(pmap);
7818 pmap_delayed_invl_finish();
7822 * Clear the modify bits on the specified physical page.
7825 pmap_clear_modify(vm_page_t m)
7827 struct md_page *pvh;
7829 pv_entry_t next_pv, pv;
7830 pd_entry_t oldpde, *pde;
7831 pt_entry_t *pte, PG_M, PG_RW;
7832 struct rwlock *lock;
7834 int md_gen, pvh_gen;
7836 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
7837 ("pmap_clear_modify: page %p is not managed", m));
7838 vm_page_assert_busied(m);
7840 if (!pmap_page_is_write_mapped(m))
7842 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
7843 pa_to_pvh(VM_PAGE_TO_PHYS(m));
7844 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
7847 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
7849 if (!PMAP_TRYLOCK(pmap)) {
7850 pvh_gen = pvh->pv_gen;
7854 if (pvh_gen != pvh->pv_gen) {
7859 PG_M = pmap_modified_bit(pmap);
7860 PG_RW = pmap_rw_bit(pmap);
7862 pde = pmap_pde(pmap, va);
7864 /* If oldpde has PG_RW set, then it also has PG_M set. */
7865 if ((oldpde & PG_RW) != 0 &&
7866 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
7867 (oldpde & PG_W) == 0) {
7869 * Write protect the mapping to a single page so that
7870 * a subsequent write access may repromote.
7872 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
7873 pte = pmap_pde_to_pte(pde, va);
7874 atomic_clear_long(pte, PG_M | PG_RW);
7876 pmap_invalidate_page(pmap, va);
7880 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
7882 if (!PMAP_TRYLOCK(pmap)) {
7883 md_gen = m->md.pv_gen;
7884 pvh_gen = pvh->pv_gen;
7888 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
7893 PG_M = pmap_modified_bit(pmap);
7894 PG_RW = pmap_rw_bit(pmap);
7895 pde = pmap_pde(pmap, pv->pv_va);
7896 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
7897 " a 2mpage in page %p's pv list", m));
7898 pte = pmap_pde_to_pte(pde, pv->pv_va);
7899 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
7900 atomic_clear_long(pte, PG_M);
7901 pmap_invalidate_page(pmap, pv->pv_va);
7909 * Miscellaneous support routines follow
7912 /* Adjust the properties for a leaf page table entry. */
7913 static __inline void
7914 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
7918 opte = *(u_long *)pte;
7920 npte = opte & ~mask;
7922 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
7927 * Map a set of physical memory pages into the kernel virtual
7928 * address space. Return a pointer to where it is mapped. This
7929 * routine is intended to be used for mapping device memory,
7933 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
7935 struct pmap_preinit_mapping *ppim;
7936 vm_offset_t va, offset;
7940 offset = pa & PAGE_MASK;
7941 size = round_page(offset + size);
7942 pa = trunc_page(pa);
7944 if (!pmap_initialized) {
7946 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7947 ppim = pmap_preinit_mapping + i;
7948 if (ppim->va == 0) {
7952 ppim->va = virtual_avail;
7953 virtual_avail += size;
7959 panic("%s: too many preinit mappings", __func__);
7962 * If we have a preinit mapping, re-use it.
7964 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7965 ppim = pmap_preinit_mapping + i;
7966 if (ppim->pa == pa && ppim->sz == size &&
7967 (ppim->mode == mode ||
7968 (flags & MAPDEV_SETATTR) == 0))
7969 return ((void *)(ppim->va + offset));
7972 * If the specified range of physical addresses fits within
7973 * the direct map window, use the direct map.
7975 if (pa < dmaplimit && pa + size <= dmaplimit) {
7976 va = PHYS_TO_DMAP(pa);
7977 if ((flags & MAPDEV_SETATTR) != 0) {
7978 PMAP_LOCK(kernel_pmap);
7979 i = pmap_change_props_locked(va, size,
7980 PROT_NONE, mode, flags);
7981 PMAP_UNLOCK(kernel_pmap);
7985 return ((void *)(va + offset));
7987 va = kva_alloc(size);
7989 panic("%s: Couldn't allocate KVA", __func__);
7991 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
7992 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
7993 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
7994 if ((flags & MAPDEV_FLUSHCACHE) != 0)
7995 pmap_invalidate_cache_range(va, va + tmpsize);
7996 return ((void *)(va + offset));
8000 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
8003 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
8008 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
8011 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
8015 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
8018 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
8023 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
8026 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
8027 MAPDEV_FLUSHCACHE));
8031 pmap_unmapdev(vm_offset_t va, vm_size_t size)
8033 struct pmap_preinit_mapping *ppim;
8037 /* If we gave a direct map region in pmap_mapdev, do nothing */
8038 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
8040 offset = va & PAGE_MASK;
8041 size = round_page(offset + size);
8042 va = trunc_page(va);
8043 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
8044 ppim = pmap_preinit_mapping + i;
8045 if (ppim->va == va && ppim->sz == size) {
8046 if (pmap_initialized)
8052 if (va + size == virtual_avail)
8057 if (pmap_initialized)
8062 * Tries to demote a 1GB page mapping.
8065 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
8067 pdp_entry_t newpdpe, oldpdpe;
8068 pd_entry_t *firstpde, newpde, *pde;
8069 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8073 PG_A = pmap_accessed_bit(pmap);
8074 PG_M = pmap_modified_bit(pmap);
8075 PG_V = pmap_valid_bit(pmap);
8076 PG_RW = pmap_rw_bit(pmap);
8078 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
8080 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
8081 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
8082 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
8083 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
8084 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
8085 " in pmap %p", va, pmap);
8088 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
8089 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
8090 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
8091 KASSERT((oldpdpe & PG_A) != 0,
8092 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
8093 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
8094 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
8098 * Initialize the page directory page.
8100 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
8106 * Demote the mapping.
8111 * Invalidate a stale recursive mapping of the page directory page.
8113 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
8115 pmap_pdpe_demotions++;
8116 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
8117 " in pmap %p", va, pmap);
8122 * Sets the memory attribute for the specified page.
8125 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
8128 m->md.pat_mode = ma;
8131 * If "m" is a normal page, update its direct mapping. This update
8132 * can be relied upon to perform any cache operations that are
8133 * required for data coherence.
8135 if ((m->flags & PG_FICTITIOUS) == 0 &&
8136 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
8138 panic("memory attribute change on the direct map failed");
8142 * Changes the specified virtual address range's memory type to that given by
8143 * the parameter "mode". The specified virtual address range must be
8144 * completely contained within either the direct map or the kernel map. If
8145 * the virtual address range is contained within the kernel map, then the
8146 * memory type for each of the corresponding ranges of the direct map is also
8147 * changed. (The corresponding ranges of the direct map are those ranges that
8148 * map the same physical pages as the specified virtual address range.) These
8149 * changes to the direct map are necessary because Intel describes the
8150 * behavior of their processors as "undefined" if two or more mappings to the
8151 * same physical page have different memory types.
8153 * Returns zero if the change completed successfully, and either EINVAL or
8154 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
8155 * of the virtual address range was not mapped, and ENOMEM is returned if
8156 * there was insufficient memory available to complete the change. In the
8157 * latter case, the memory type may have been changed on some part of the
8158 * virtual address range or the direct map.
8161 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
8165 PMAP_LOCK(kernel_pmap);
8166 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
8168 PMAP_UNLOCK(kernel_pmap);
8173 * Changes the specified virtual address range's protections to those
8174 * specified by "prot". Like pmap_change_attr(), protections for aliases
8175 * in the direct map are updated as well. Protections on aliasing mappings may
8176 * be a subset of the requested protections; for example, mappings in the direct
8177 * map are never executable.
8180 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
8184 /* Only supported within the kernel map. */
8185 if (va < VM_MIN_KERNEL_ADDRESS)
8188 PMAP_LOCK(kernel_pmap);
8189 error = pmap_change_props_locked(va, size, prot, -1,
8190 MAPDEV_ASSERTVALID);
8191 PMAP_UNLOCK(kernel_pmap);
8196 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
8197 int mode, int flags)
8199 vm_offset_t base, offset, tmpva;
8200 vm_paddr_t pa_start, pa_end, pa_end1;
8202 pd_entry_t *pde, pde_bits, pde_mask;
8203 pt_entry_t *pte, pte_bits, pte_mask;
8207 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
8208 base = trunc_page(va);
8209 offset = va & PAGE_MASK;
8210 size = round_page(offset + size);
8213 * Only supported on kernel virtual addresses, including the direct
8214 * map but excluding the recursive map.
8216 if (base < DMAP_MIN_ADDRESS)
8220 * Construct our flag sets and masks. "bits" is the subset of
8221 * "mask" that will be set in each modified PTE.
8223 * Mappings in the direct map are never allowed to be executable.
8225 pde_bits = pte_bits = 0;
8226 pde_mask = pte_mask = 0;
8228 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
8229 pde_mask |= X86_PG_PDE_CACHE;
8230 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
8231 pte_mask |= X86_PG_PTE_CACHE;
8233 if (prot != VM_PROT_NONE) {
8234 if ((prot & VM_PROT_WRITE) != 0) {
8235 pde_bits |= X86_PG_RW;
8236 pte_bits |= X86_PG_RW;
8238 if ((prot & VM_PROT_EXECUTE) == 0 ||
8239 va < VM_MIN_KERNEL_ADDRESS) {
8243 pde_mask |= X86_PG_RW | pg_nx;
8244 pte_mask |= X86_PG_RW | pg_nx;
8248 * Pages that aren't mapped aren't supported. Also break down 2MB pages
8249 * into 4KB pages if required.
8251 for (tmpva = base; tmpva < base + size; ) {
8252 pdpe = pmap_pdpe(kernel_pmap, tmpva);
8253 if (pdpe == NULL || *pdpe == 0) {
8254 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
8255 ("%s: addr %#lx is not mapped", __func__, tmpva));
8258 if (*pdpe & PG_PS) {
8260 * If the current 1GB page already has the required
8261 * properties, then we need not demote this page. Just
8262 * increment tmpva to the next 1GB page frame.
8264 if ((*pdpe & pde_mask) == pde_bits) {
8265 tmpva = trunc_1gpage(tmpva) + NBPDP;
8270 * If the current offset aligns with a 1GB page frame
8271 * and there is at least 1GB left within the range, then
8272 * we need not break down this page into 2MB pages.
8274 if ((tmpva & PDPMASK) == 0 &&
8275 tmpva + PDPMASK < base + size) {
8279 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
8282 pde = pmap_pdpe_to_pde(pdpe, tmpva);
8284 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
8285 ("%s: addr %#lx is not mapped", __func__, tmpva));
8290 * If the current 2MB page already has the required
8291 * properties, then we need not demote this page. Just
8292 * increment tmpva to the next 2MB page frame.
8294 if ((*pde & pde_mask) == pde_bits) {
8295 tmpva = trunc_2mpage(tmpva) + NBPDR;
8300 * If the current offset aligns with a 2MB page frame
8301 * and there is at least 2MB left within the range, then
8302 * we need not break down this page into 4KB pages.
8304 if ((tmpva & PDRMASK) == 0 &&
8305 tmpva + PDRMASK < base + size) {
8309 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
8312 pte = pmap_pde_to_pte(pde, tmpva);
8314 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
8315 ("%s: addr %#lx is not mapped", __func__, tmpva));
8323 * Ok, all the pages exist, so run through them updating their
8324 * properties if required.
8327 pa_start = pa_end = 0;
8328 for (tmpva = base; tmpva < base + size; ) {
8329 pdpe = pmap_pdpe(kernel_pmap, tmpva);
8330 if (*pdpe & PG_PS) {
8331 if ((*pdpe & pde_mask) != pde_bits) {
8332 pmap_pte_props(pdpe, pde_bits, pde_mask);
8335 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
8336 (*pdpe & PG_PS_FRAME) < dmaplimit) {
8337 if (pa_start == pa_end) {
8338 /* Start physical address run. */
8339 pa_start = *pdpe & PG_PS_FRAME;
8340 pa_end = pa_start + NBPDP;
8341 } else if (pa_end == (*pdpe & PG_PS_FRAME))
8344 /* Run ended, update direct map. */
8345 error = pmap_change_props_locked(
8346 PHYS_TO_DMAP(pa_start),
8347 pa_end - pa_start, prot, mode,
8351 /* Start physical address run. */
8352 pa_start = *pdpe & PG_PS_FRAME;
8353 pa_end = pa_start + NBPDP;
8356 tmpva = trunc_1gpage(tmpva) + NBPDP;
8359 pde = pmap_pdpe_to_pde(pdpe, tmpva);
8361 if ((*pde & pde_mask) != pde_bits) {
8362 pmap_pte_props(pde, pde_bits, pde_mask);
8365 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
8366 (*pde & PG_PS_FRAME) < dmaplimit) {
8367 if (pa_start == pa_end) {
8368 /* Start physical address run. */
8369 pa_start = *pde & PG_PS_FRAME;
8370 pa_end = pa_start + NBPDR;
8371 } else if (pa_end == (*pde & PG_PS_FRAME))
8374 /* Run ended, update direct map. */
8375 error = pmap_change_props_locked(
8376 PHYS_TO_DMAP(pa_start),
8377 pa_end - pa_start, prot, mode,
8381 /* Start physical address run. */
8382 pa_start = *pde & PG_PS_FRAME;
8383 pa_end = pa_start + NBPDR;
8386 tmpva = trunc_2mpage(tmpva) + NBPDR;
8388 pte = pmap_pde_to_pte(pde, tmpva);
8389 if ((*pte & pte_mask) != pte_bits) {
8390 pmap_pte_props(pte, pte_bits, pte_mask);
8393 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
8394 (*pte & PG_FRAME) < dmaplimit) {
8395 if (pa_start == pa_end) {
8396 /* Start physical address run. */
8397 pa_start = *pte & PG_FRAME;
8398 pa_end = pa_start + PAGE_SIZE;
8399 } else if (pa_end == (*pte & PG_FRAME))
8400 pa_end += PAGE_SIZE;
8402 /* Run ended, update direct map. */
8403 error = pmap_change_props_locked(
8404 PHYS_TO_DMAP(pa_start),
8405 pa_end - pa_start, prot, mode,
8409 /* Start physical address run. */
8410 pa_start = *pte & PG_FRAME;
8411 pa_end = pa_start + PAGE_SIZE;
8417 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
8418 pa_end1 = MIN(pa_end, dmaplimit);
8419 if (pa_start != pa_end1)
8420 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
8421 pa_end1 - pa_start, prot, mode, flags);
8425 * Flush CPU caches if required to make sure any data isn't cached that
8426 * shouldn't be, etc.
8429 pmap_invalidate_range(kernel_pmap, base, tmpva);
8430 if ((flags & MAPDEV_FLUSHCACHE) != 0)
8431 pmap_invalidate_cache_range(base, tmpva);
8437 * Demotes any mapping within the direct map region that covers more than the
8438 * specified range of physical addresses. This range's size must be a power
8439 * of two and its starting address must be a multiple of its size. Since the
8440 * demotion does not change any attributes of the mapping, a TLB invalidation
8441 * is not mandatory. The caller may, however, request a TLB invalidation.
8444 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
8453 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
8454 KASSERT((base & (len - 1)) == 0,
8455 ("pmap_demote_DMAP: base is not a multiple of len"));
8456 if (len < NBPDP && base < dmaplimit) {
8457 va = PHYS_TO_DMAP(base);
8459 PMAP_LOCK(kernel_pmap);
8460 pdpe = pmap_pdpe(kernel_pmap, va);
8461 if ((*pdpe & X86_PG_V) == 0)
8462 panic("pmap_demote_DMAP: invalid PDPE");
8463 if ((*pdpe & PG_PS) != 0) {
8464 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
8465 panic("pmap_demote_DMAP: PDPE failed");
8469 pde = pmap_pdpe_to_pde(pdpe, va);
8470 if ((*pde & X86_PG_V) == 0)
8471 panic("pmap_demote_DMAP: invalid PDE");
8472 if ((*pde & PG_PS) != 0) {
8473 if (!pmap_demote_pde(kernel_pmap, pde, va))
8474 panic("pmap_demote_DMAP: PDE failed");
8478 if (changed && invalidate)
8479 pmap_invalidate_page(kernel_pmap, va);
8480 PMAP_UNLOCK(kernel_pmap);
8485 * Perform the pmap work for mincore(2). If the page is not both referenced and
8486 * modified by this pmap, returns its physical address so that the caller can
8487 * find other mappings.
8490 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
8493 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
8497 PG_A = pmap_accessed_bit(pmap);
8498 PG_M = pmap_modified_bit(pmap);
8499 PG_V = pmap_valid_bit(pmap);
8500 PG_RW = pmap_rw_bit(pmap);
8503 pdep = pmap_pde(pmap, addr);
8504 if (pdep != NULL && (*pdep & PG_V)) {
8505 if (*pdep & PG_PS) {
8507 /* Compute the physical address of the 4KB page. */
8508 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
8510 val = MINCORE_SUPER;
8512 pte = *pmap_pde_to_pte(pdep, addr);
8513 pa = pte & PG_FRAME;
8521 if ((pte & PG_V) != 0) {
8522 val |= MINCORE_INCORE;
8523 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
8524 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
8525 if ((pte & PG_A) != 0)
8526 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
8528 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
8529 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
8530 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
8538 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
8540 uint32_t gen, new_gen, pcid_next;
8542 CRITICAL_ASSERT(curthread);
8543 gen = PCPU_GET(pcid_gen);
8544 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
8545 return (pti ? 0 : CR3_PCID_SAVE);
8546 if (pmap->pm_pcids[cpuid].pm_gen == gen)
8547 return (CR3_PCID_SAVE);
8548 pcid_next = PCPU_GET(pcid_next);
8549 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
8550 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
8551 ("cpu %d pcid_next %#x", cpuid, pcid_next));
8552 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
8553 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
8557 PCPU_SET(pcid_gen, new_gen);
8558 pcid_next = PMAP_PCID_KERN + 1;
8562 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
8563 pmap->pm_pcids[cpuid].pm_gen = new_gen;
8564 PCPU_SET(pcid_next, pcid_next + 1);
8569 pmap_pcid_alloc_checked(pmap_t pmap, u_int cpuid)
8573 cached = pmap_pcid_alloc(pmap, cpuid);
8574 KASSERT(pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
8575 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
8576 pmap->pm_pcids[cpuid].pm_pcid));
8577 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
8578 pmap == kernel_pmap,
8579 ("non-kernel pmap pmap %p cpu %d pcid %#x",
8580 pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
8585 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
8588 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
8589 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_pcb;
8593 pmap_activate_sw_pcid_pti(pmap_t pmap, u_int cpuid, const bool invpcid_works1)
8595 struct invpcid_descr d;
8596 uint64_t cached, cr3, kcr3, ucr3;
8598 cached = pmap_pcid_alloc_checked(pmap, cpuid);
8600 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
8601 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid);
8602 PCPU_SET(curpmap, pmap);
8603 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
8604 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
8607 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
8609 * Explicitly invalidate translations cached from the
8610 * user page table. They are not automatically
8611 * flushed by reload of cr3 with the kernel page table
8614 * Note that the if() condition is resolved statically
8615 * by using the function argument instead of
8616 * runtime-evaluated invpcid_works value.
8618 if (invpcid_works1) {
8619 d.pcid = PMAP_PCID_USER_PT |
8620 pmap->pm_pcids[cpuid].pm_pcid;
8623 invpcid(&d, INVPCID_CTX);
8625 pmap_pti_pcid_invalidate(ucr3, kcr3);
8629 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
8630 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
8632 PCPU_INC(pm_save_cnt);
8636 pmap_activate_sw_pcid_invpcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
8639 pmap_activate_sw_pcid_pti(pmap, cpuid, true);
8640 pmap_activate_sw_pti_post(td, pmap);
8644 pmap_activate_sw_pcid_noinvpcid_pti(struct thread *td, pmap_t pmap,
8650 * If the INVPCID instruction is not available,
8651 * invltlb_pcid_handler() is used to handle an invalidate_all
8652 * IPI, which checks for curpmap == smp_tlb_pmap. The below
8653 * sequence of operations has a window where %CR3 is loaded
8654 * with the new pmap's PML4 address, but the curpmap value has
8655 * not yet been updated. This causes the invltlb IPI handler,
8656 * which is called between the updates, to execute as a NOP,
8657 * which leaves stale TLB entries.
8659 * Note that the most typical use of pmap_activate_sw(), from
8660 * the context switch, is immune to this race, because
8661 * interrupts are disabled (while the thread lock is owned),
8662 * and the IPI happens after curpmap is updated. Protect
8663 * other callers in a similar way, by disabling interrupts
8664 * around the %cr3 register reload and curpmap assignment.
8666 rflags = intr_disable();
8667 pmap_activate_sw_pcid_pti(pmap, cpuid, false);
8668 intr_restore(rflags);
8669 pmap_activate_sw_pti_post(td, pmap);
8673 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
8676 uint64_t cached, cr3;
8678 cached = pmap_pcid_alloc_checked(pmap, cpuid);
8680 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
8681 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
8683 PCPU_SET(curpmap, pmap);
8685 PCPU_INC(pm_save_cnt);
8689 pmap_activate_sw_pcid_noinvpcid_nopti(struct thread *td __unused, pmap_t pmap,
8694 rflags = intr_disable();
8695 pmap_activate_sw_pcid_nopti(td, pmap, cpuid);
8696 intr_restore(rflags);
8700 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
8701 u_int cpuid __unused)
8704 load_cr3(pmap->pm_cr3);
8705 PCPU_SET(curpmap, pmap);
8709 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
8710 u_int cpuid __unused)
8713 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
8714 PCPU_SET(kcr3, pmap->pm_cr3);
8715 PCPU_SET(ucr3, pmap->pm_ucr3);
8716 pmap_activate_sw_pti_post(td, pmap);
8719 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
8723 if (pmap_pcid_enabled && pti && invpcid_works)
8724 return (pmap_activate_sw_pcid_invpcid_pti);
8725 else if (pmap_pcid_enabled && pti && !invpcid_works)
8726 return (pmap_activate_sw_pcid_noinvpcid_pti);
8727 else if (pmap_pcid_enabled && !pti && invpcid_works)
8728 return (pmap_activate_sw_pcid_nopti);
8729 else if (pmap_pcid_enabled && !pti && !invpcid_works)
8730 return (pmap_activate_sw_pcid_noinvpcid_nopti);
8731 else if (!pmap_pcid_enabled && pti)
8732 return (pmap_activate_sw_nopcid_pti);
8733 else /* if (!pmap_pcid_enabled && !pti) */
8734 return (pmap_activate_sw_nopcid_nopti);
8738 pmap_activate_sw(struct thread *td)
8740 pmap_t oldpmap, pmap;
8743 oldpmap = PCPU_GET(curpmap);
8744 pmap = vmspace_pmap(td->td_proc->p_vmspace);
8745 if (oldpmap == pmap)
8747 cpuid = PCPU_GET(cpuid);
8749 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
8751 CPU_SET(cpuid, &pmap->pm_active);
8753 pmap_activate_sw_mode(td, pmap, cpuid);
8755 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
8757 CPU_CLR(cpuid, &oldpmap->pm_active);
8762 pmap_activate(struct thread *td)
8766 pmap_activate_sw(td);
8771 pmap_activate_boot(pmap_t pmap)
8777 * kernel_pmap must be never deactivated, and we ensure that
8778 * by never activating it at all.
8780 MPASS(pmap != kernel_pmap);
8782 cpuid = PCPU_GET(cpuid);
8784 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
8786 CPU_SET(cpuid, &pmap->pm_active);
8788 PCPU_SET(curpmap, pmap);
8790 kcr3 = pmap->pm_cr3;
8791 if (pmap_pcid_enabled)
8792 kcr3 |= pmap->pm_pcids[cpuid].pm_pcid | CR3_PCID_SAVE;
8796 PCPU_SET(kcr3, kcr3);
8797 PCPU_SET(ucr3, PMAP_NO_CR3);
8801 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
8806 * Increase the starting virtual address of the given mapping if a
8807 * different alignment might result in more superpage mappings.
8810 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
8811 vm_offset_t *addr, vm_size_t size)
8813 vm_offset_t superpage_offset;
8817 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
8818 offset += ptoa(object->pg_color);
8819 superpage_offset = offset & PDRMASK;
8820 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
8821 (*addr & PDRMASK) == superpage_offset)
8823 if ((*addr & PDRMASK) < superpage_offset)
8824 *addr = (*addr & ~PDRMASK) + superpage_offset;
8826 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
8830 static unsigned long num_dirty_emulations;
8831 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
8832 &num_dirty_emulations, 0, NULL);
8834 static unsigned long num_accessed_emulations;
8835 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
8836 &num_accessed_emulations, 0, NULL);
8838 static unsigned long num_superpage_accessed_emulations;
8839 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
8840 &num_superpage_accessed_emulations, 0, NULL);
8842 static unsigned long ad_emulation_superpage_promotions;
8843 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
8844 &ad_emulation_superpage_promotions, 0, NULL);
8845 #endif /* INVARIANTS */
8848 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
8851 struct rwlock *lock;
8852 #if VM_NRESERVLEVEL > 0
8856 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
8858 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
8859 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
8861 if (!pmap_emulate_ad_bits(pmap))
8864 PG_A = pmap_accessed_bit(pmap);
8865 PG_M = pmap_modified_bit(pmap);
8866 PG_V = pmap_valid_bit(pmap);
8867 PG_RW = pmap_rw_bit(pmap);
8873 pde = pmap_pde(pmap, va);
8874 if (pde == NULL || (*pde & PG_V) == 0)
8877 if ((*pde & PG_PS) != 0) {
8878 if (ftype == VM_PROT_READ) {
8880 atomic_add_long(&num_superpage_accessed_emulations, 1);
8888 pte = pmap_pde_to_pte(pde, va);
8889 if ((*pte & PG_V) == 0)
8892 if (ftype == VM_PROT_WRITE) {
8893 if ((*pte & PG_RW) == 0)
8896 * Set the modified and accessed bits simultaneously.
8898 * Intel EPT PTEs that do software emulation of A/D bits map
8899 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
8900 * An EPT misconfiguration is triggered if the PTE is writable
8901 * but not readable (WR=10). This is avoided by setting PG_A
8902 * and PG_M simultaneously.
8904 *pte |= PG_M | PG_A;
8909 #if VM_NRESERVLEVEL > 0
8910 /* try to promote the mapping */
8911 if (va < VM_MAXUSER_ADDRESS)
8912 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
8916 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
8918 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
8919 pmap_ps_enabled(pmap) &&
8920 (m->flags & PG_FICTITIOUS) == 0 &&
8921 vm_reserv_level_iffullpop(m) == 0) {
8922 pmap_promote_pde(pmap, pde, va, &lock);
8924 atomic_add_long(&ad_emulation_superpage_promotions, 1);
8930 if (ftype == VM_PROT_WRITE)
8931 atomic_add_long(&num_dirty_emulations, 1);
8933 atomic_add_long(&num_accessed_emulations, 1);
8935 rv = 0; /* success */
8944 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
8949 pt_entry_t *pte, PG_V;
8953 PG_V = pmap_valid_bit(pmap);
8956 pml4 = pmap_pml4e(pmap, va);
8958 if ((*pml4 & PG_V) == 0)
8961 pdp = pmap_pml4e_to_pdpe(pml4, va);
8963 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
8966 pde = pmap_pdpe_to_pde(pdp, va);
8968 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
8971 pte = pmap_pde_to_pte(pde, va);
8980 * Get the kernel virtual address of a set of physical pages. If there are
8981 * physical addresses not covered by the DMAP perform a transient mapping
8982 * that will be removed when calling pmap_unmap_io_transient.
8984 * \param page The pages the caller wishes to obtain the virtual
8985 * address on the kernel memory map.
8986 * \param vaddr On return contains the kernel virtual memory address
8987 * of the pages passed in the page parameter.
8988 * \param count Number of pages passed in.
8989 * \param can_fault TRUE if the thread using the mapped pages can take
8990 * page faults, FALSE otherwise.
8992 * \returns TRUE if the caller must call pmap_unmap_io_transient when
8993 * finished or FALSE otherwise.
8997 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
8998 boolean_t can_fault)
9001 boolean_t needs_mapping;
9003 int cache_bits, error __unused, i;
9006 * Allocate any KVA space that we need, this is done in a separate
9007 * loop to prevent calling vmem_alloc while pinned.
9009 needs_mapping = FALSE;
9010 for (i = 0; i < count; i++) {
9011 paddr = VM_PAGE_TO_PHYS(page[i]);
9012 if (__predict_false(paddr >= dmaplimit)) {
9013 error = vmem_alloc(kernel_arena, PAGE_SIZE,
9014 M_BESTFIT | M_WAITOK, &vaddr[i]);
9015 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
9016 needs_mapping = TRUE;
9018 vaddr[i] = PHYS_TO_DMAP(paddr);
9022 /* Exit early if everything is covered by the DMAP */
9027 * NB: The sequence of updating a page table followed by accesses
9028 * to the corresponding pages used in the !DMAP case is subject to
9029 * the situation described in the "AMD64 Architecture Programmer's
9030 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
9031 * Coherency Considerations". Therefore, issuing the INVLPG right
9032 * after modifying the PTE bits is crucial.
9036 for (i = 0; i < count; i++) {
9037 paddr = VM_PAGE_TO_PHYS(page[i]);
9038 if (paddr >= dmaplimit) {
9041 * Slow path, since we can get page faults
9042 * while mappings are active don't pin the
9043 * thread to the CPU and instead add a global
9044 * mapping visible to all CPUs.
9046 pmap_qenter(vaddr[i], &page[i], 1);
9048 pte = vtopte(vaddr[i]);
9049 cache_bits = pmap_cache_bits(kernel_pmap,
9050 page[i]->md.pat_mode, 0);
9051 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
9058 return (needs_mapping);
9062 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
9063 boolean_t can_fault)
9070 for (i = 0; i < count; i++) {
9071 paddr = VM_PAGE_TO_PHYS(page[i]);
9072 if (paddr >= dmaplimit) {
9074 pmap_qremove(vaddr[i], 1);
9075 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
9081 pmap_quick_enter_page(vm_page_t m)
9085 paddr = VM_PAGE_TO_PHYS(m);
9086 if (paddr < dmaplimit)
9087 return (PHYS_TO_DMAP(paddr));
9088 mtx_lock_spin(&qframe_mtx);
9089 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
9090 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
9091 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
9096 pmap_quick_remove_page(vm_offset_t addr)
9101 pte_store(vtopte(qframe), 0);
9103 mtx_unlock_spin(&qframe_mtx);
9107 * Pdp pages from the large map are managed differently from either
9108 * kernel or user page table pages. They are permanently allocated at
9109 * initialization time, and their reference count is permanently set to
9110 * zero. The pml4 entries pointing to those pages are copied into
9111 * each allocated pmap.
9113 * In contrast, pd and pt pages are managed like user page table
9114 * pages. They are dynamically allocated, and their reference count
9115 * represents the number of valid entries within the page.
9118 pmap_large_map_getptp_unlocked(void)
9122 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
9124 if (m != NULL && (m->flags & PG_ZERO) == 0)
9130 pmap_large_map_getptp(void)
9134 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9135 m = pmap_large_map_getptp_unlocked();
9137 PMAP_UNLOCK(kernel_pmap);
9139 PMAP_LOCK(kernel_pmap);
9140 /* Callers retry. */
9145 static pdp_entry_t *
9146 pmap_large_map_pdpe(vm_offset_t va)
9148 vm_pindex_t pml4_idx;
9151 pml4_idx = pmap_pml4e_index(va);
9152 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
9153 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
9155 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
9156 KASSERT((kernel_pmap->pm_pml4[pml4_idx] & X86_PG_V) != 0,
9157 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
9158 "LMSPML4I %#jx lm_ents %d",
9159 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
9160 mphys = kernel_pmap->pm_pml4[pml4_idx] & PG_FRAME;
9161 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
9165 pmap_large_map_pde(vm_offset_t va)
9172 pdpe = pmap_large_map_pdpe(va);
9174 m = pmap_large_map_getptp();
9177 mphys = VM_PAGE_TO_PHYS(m);
9178 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
9180 MPASS((*pdpe & X86_PG_PS) == 0);
9181 mphys = *pdpe & PG_FRAME;
9183 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
9187 pmap_large_map_pte(vm_offset_t va)
9194 pde = pmap_large_map_pde(va);
9196 m = pmap_large_map_getptp();
9199 mphys = VM_PAGE_TO_PHYS(m);
9200 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
9201 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
9203 MPASS((*pde & X86_PG_PS) == 0);
9204 mphys = *pde & PG_FRAME;
9206 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
9210 pmap_large_map_kextract(vm_offset_t va)
9212 pdp_entry_t *pdpe, pdp;
9213 pd_entry_t *pde, pd;
9214 pt_entry_t *pte, pt;
9216 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
9217 ("not largemap range %#lx", (u_long)va));
9218 pdpe = pmap_large_map_pdpe(va);
9220 KASSERT((pdp & X86_PG_V) != 0,
9221 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
9222 (u_long)pdpe, pdp));
9223 if ((pdp & X86_PG_PS) != 0) {
9224 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
9225 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
9226 (u_long)pdpe, pdp));
9227 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
9229 pde = pmap_pdpe_to_pde(pdpe, va);
9231 KASSERT((pd & X86_PG_V) != 0,
9232 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
9233 if ((pd & X86_PG_PS) != 0)
9234 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
9235 pte = pmap_pde_to_pte(pde, va);
9237 KASSERT((pt & X86_PG_V) != 0,
9238 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
9239 return ((pt & PG_FRAME) | (va & PAGE_MASK));
9243 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
9244 vmem_addr_t *vmem_res)
9248 * Large mappings are all but static. Consequently, there
9249 * is no point in waiting for an earlier allocation to be
9252 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
9253 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
9257 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
9263 vm_offset_t va, inc;
9264 vmem_addr_t vmem_res;
9268 if (len == 0 || spa + len < spa)
9271 /* See if DMAP can serve. */
9272 if (spa + len <= dmaplimit) {
9273 va = PHYS_TO_DMAP(spa);
9275 return (pmap_change_attr(va, len, mattr));
9279 * No, allocate KVA. Fit the address with best possible
9280 * alignment for superpages. Fall back to worse align if
9284 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
9285 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
9286 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
9288 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
9290 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
9293 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
9298 * Fill pagetable. PG_M is not pre-set, we scan modified bits
9299 * in the pagetable to minimize flushing. No need to
9300 * invalidate TLB, since we only update invalid entries.
9302 PMAP_LOCK(kernel_pmap);
9303 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
9305 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
9306 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
9307 pdpe = pmap_large_map_pdpe(va);
9309 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
9310 X86_PG_V | X86_PG_A | pg_nx |
9311 pmap_cache_bits(kernel_pmap, mattr, TRUE);
9313 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
9314 (va & PDRMASK) == 0) {
9315 pde = pmap_large_map_pde(va);
9317 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
9318 X86_PG_V | X86_PG_A | pg_nx |
9319 pmap_cache_bits(kernel_pmap, mattr, TRUE);
9320 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
9324 pte = pmap_large_map_pte(va);
9326 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
9327 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
9329 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
9334 PMAP_UNLOCK(kernel_pmap);
9337 *addr = (void *)vmem_res;
9342 pmap_large_unmap(void *svaa, vm_size_t len)
9344 vm_offset_t sva, va;
9346 pdp_entry_t *pdpe, pdp;
9347 pd_entry_t *pde, pd;
9350 struct spglist spgf;
9352 sva = (vm_offset_t)svaa;
9353 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
9354 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
9358 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
9359 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
9360 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
9361 PMAP_LOCK(kernel_pmap);
9362 for (va = sva; va < sva + len; va += inc) {
9363 pdpe = pmap_large_map_pdpe(va);
9365 KASSERT((pdp & X86_PG_V) != 0,
9366 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
9367 (u_long)pdpe, pdp));
9368 if ((pdp & X86_PG_PS) != 0) {
9369 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
9370 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
9371 (u_long)pdpe, pdp));
9372 KASSERT((va & PDPMASK) == 0,
9373 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
9374 (u_long)pdpe, pdp));
9375 KASSERT(va + NBPDP <= sva + len,
9376 ("unmap covers partial 1GB page, sva %#lx va %#lx "
9377 "pdpe %#lx pdp %#lx len %#lx", sva, va,
9378 (u_long)pdpe, pdp, len));
9383 pde = pmap_pdpe_to_pde(pdpe, va);
9385 KASSERT((pd & X86_PG_V) != 0,
9386 ("invalid pd va %#lx pde %#lx pd %#lx", va,
9388 if ((pd & X86_PG_PS) != 0) {
9389 KASSERT((va & PDRMASK) == 0,
9390 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
9392 KASSERT(va + NBPDR <= sva + len,
9393 ("unmap covers partial 2MB page, sva %#lx va %#lx "
9394 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
9398 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
9400 if (m->ref_count == 0) {
9402 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
9406 pte = pmap_pde_to_pte(pde, va);
9407 KASSERT((*pte & X86_PG_V) != 0,
9408 ("invalid pte va %#lx pte %#lx pt %#lx", va,
9409 (u_long)pte, *pte));
9412 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
9414 if (m->ref_count == 0) {
9416 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
9417 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
9419 if (m->ref_count == 0) {
9421 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
9425 pmap_invalidate_range(kernel_pmap, sva, sva + len);
9426 PMAP_UNLOCK(kernel_pmap);
9427 vm_page_free_pages_toq(&spgf, false);
9428 vmem_free(large_vmem, sva, len);
9432 pmap_large_map_wb_fence_mfence(void)
9439 pmap_large_map_wb_fence_sfence(void)
9446 pmap_large_map_wb_fence_nop(void)
9450 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
9453 if (cpu_vendor_id != CPU_VENDOR_INTEL)
9454 return (pmap_large_map_wb_fence_mfence);
9455 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
9456 CPUID_STDEXT_CLFLUSHOPT)) == 0)
9457 return (pmap_large_map_wb_fence_sfence);
9459 /* clflush is strongly enough ordered */
9460 return (pmap_large_map_wb_fence_nop);
9464 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
9467 for (; len > 0; len -= cpu_clflush_line_size,
9468 va += cpu_clflush_line_size)
9473 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
9476 for (; len > 0; len -= cpu_clflush_line_size,
9477 va += cpu_clflush_line_size)
9482 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
9485 for (; len > 0; len -= cpu_clflush_line_size,
9486 va += cpu_clflush_line_size)
9491 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
9495 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
9498 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
9499 return (pmap_large_map_flush_range_clwb);
9500 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
9501 return (pmap_large_map_flush_range_clflushopt);
9502 else if ((cpu_feature & CPUID_CLFSH) != 0)
9503 return (pmap_large_map_flush_range_clflush);
9505 return (pmap_large_map_flush_range_nop);
9509 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
9511 volatile u_long *pe;
9517 for (va = sva; va < eva; va += inc) {
9519 if ((amd_feature & AMDID_PAGE1GB) != 0) {
9520 pe = (volatile u_long *)pmap_large_map_pdpe(va);
9522 if ((p & X86_PG_PS) != 0)
9526 pe = (volatile u_long *)pmap_large_map_pde(va);
9528 if ((p & X86_PG_PS) != 0)
9532 pe = (volatile u_long *)pmap_large_map_pte(va);
9538 if ((p & X86_PG_AVAIL1) != 0) {
9540 * Spin-wait for the end of a parallel
9547 * If we saw other write-back
9548 * occuring, we cannot rely on PG_M to
9549 * indicate state of the cache. The
9550 * PG_M bit is cleared before the
9551 * flush to avoid ignoring new writes,
9552 * and writes which are relevant for
9553 * us might happen after.
9559 if ((p & X86_PG_M) != 0 || seen_other) {
9560 if (!atomic_fcmpset_long(pe, &p,
9561 (p & ~X86_PG_M) | X86_PG_AVAIL1))
9563 * If we saw PG_M without
9564 * PG_AVAIL1, and then on the
9565 * next attempt we do not
9566 * observe either PG_M or
9567 * PG_AVAIL1, the other
9568 * write-back started after us
9569 * and finished before us. We
9570 * can rely on it doing our
9574 pmap_large_map_flush_range(va, inc);
9575 atomic_clear_long(pe, X86_PG_AVAIL1);
9584 * Write-back cache lines for the given address range.
9586 * Must be called only on the range or sub-range returned from
9587 * pmap_large_map(). Must not be called on the coalesced ranges.
9589 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
9590 * instructions support.
9593 pmap_large_map_wb(void *svap, vm_size_t len)
9595 vm_offset_t eva, sva;
9597 sva = (vm_offset_t)svap;
9599 pmap_large_map_wb_fence();
9600 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
9601 pmap_large_map_flush_range(sva, len);
9603 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
9604 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
9605 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
9606 pmap_large_map_wb_large(sva, eva);
9608 pmap_large_map_wb_fence();
9612 pmap_pti_alloc_page(void)
9616 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9617 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
9618 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
9623 pmap_pti_free_page(vm_page_t m)
9626 KASSERT(m->ref_count > 0, ("page %p not referenced", m));
9627 if (!vm_page_unwire_noq(m))
9629 vm_page_free_zero(m);
9643 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
9644 VM_OBJECT_WLOCK(pti_obj);
9645 pml4_pg = pmap_pti_alloc_page();
9646 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
9647 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
9648 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
9649 pdpe = pmap_pti_pdpe(va);
9650 pmap_pti_wire_pte(pdpe);
9652 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
9653 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
9654 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
9655 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
9656 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
9657 sizeof(struct gate_descriptor) * NIDT, false);
9658 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
9659 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
9661 /* Doublefault stack IST 1 */
9662 va = common_tss[i].tss_ist1;
9663 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
9664 /* NMI stack IST 2 */
9665 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
9666 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
9667 /* MC# stack IST 3 */
9668 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
9669 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
9670 /* DB# stack IST 4 */
9671 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
9672 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
9674 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
9675 (vm_offset_t)etext, true);
9676 pti_finalized = true;
9677 VM_OBJECT_WUNLOCK(pti_obj);
9679 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
9681 static pdp_entry_t *
9682 pmap_pti_pdpe(vm_offset_t va)
9684 pml4_entry_t *pml4e;
9687 vm_pindex_t pml4_idx;
9690 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9692 pml4_idx = pmap_pml4e_index(va);
9693 pml4e = &pti_pml4[pml4_idx];
9697 panic("pml4 alloc after finalization\n");
9698 m = pmap_pti_alloc_page();
9700 pmap_pti_free_page(m);
9701 mphys = *pml4e & ~PAGE_MASK;
9703 mphys = VM_PAGE_TO_PHYS(m);
9704 *pml4e = mphys | X86_PG_RW | X86_PG_V;
9707 mphys = *pml4e & ~PAGE_MASK;
9709 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
9714 pmap_pti_wire_pte(void *pte)
9718 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9719 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
9724 pmap_pti_unwire_pde(void *pde, bool only_ref)
9728 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9729 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
9730 MPASS(m->ref_count > 0);
9731 MPASS(only_ref || m->ref_count > 1);
9732 pmap_pti_free_page(m);
9736 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
9741 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9742 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
9743 MPASS(m->ref_count > 0);
9744 if (pmap_pti_free_page(m)) {
9745 pde = pmap_pti_pde(va);
9746 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
9748 pmap_pti_unwire_pde(pde, false);
9753 pmap_pti_pde(vm_offset_t va)
9761 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9763 pdpe = pmap_pti_pdpe(va);
9765 m = pmap_pti_alloc_page();
9767 pmap_pti_free_page(m);
9768 MPASS((*pdpe & X86_PG_PS) == 0);
9769 mphys = *pdpe & ~PAGE_MASK;
9771 mphys = VM_PAGE_TO_PHYS(m);
9772 *pdpe = mphys | X86_PG_RW | X86_PG_V;
9775 MPASS((*pdpe & X86_PG_PS) == 0);
9776 mphys = *pdpe & ~PAGE_MASK;
9779 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
9780 pd_idx = pmap_pde_index(va);
9786 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
9793 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9795 pde = pmap_pti_pde(va);
9796 if (unwire_pde != NULL) {
9798 pmap_pti_wire_pte(pde);
9801 m = pmap_pti_alloc_page();
9803 pmap_pti_free_page(m);
9804 MPASS((*pde & X86_PG_PS) == 0);
9805 mphys = *pde & ~(PAGE_MASK | pg_nx);
9807 mphys = VM_PAGE_TO_PHYS(m);
9808 *pde = mphys | X86_PG_RW | X86_PG_V;
9809 if (unwire_pde != NULL)
9810 *unwire_pde = false;
9813 MPASS((*pde & X86_PG_PS) == 0);
9814 mphys = *pde & ~(PAGE_MASK | pg_nx);
9817 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
9818 pte += pmap_pte_index(va);
9824 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
9828 pt_entry_t *pte, ptev;
9831 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
9833 sva = trunc_page(sva);
9834 MPASS(sva > VM_MAXUSER_ADDRESS);
9835 eva = round_page(eva);
9837 for (; sva < eva; sva += PAGE_SIZE) {
9838 pte = pmap_pti_pte(sva, &unwire_pde);
9839 pa = pmap_kextract(sva);
9840 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
9841 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
9842 VM_MEMATTR_DEFAULT, FALSE);
9844 pte_store(pte, ptev);
9845 pmap_pti_wire_pte(pte);
9847 KASSERT(!pti_finalized,
9848 ("pti overlap after fin %#lx %#lx %#lx",
9850 KASSERT(*pte == ptev,
9851 ("pti non-identical pte after fin %#lx %#lx %#lx",
9855 pde = pmap_pti_pde(sva);
9856 pmap_pti_unwire_pde(pde, true);
9862 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
9867 VM_OBJECT_WLOCK(pti_obj);
9868 pmap_pti_add_kva_locked(sva, eva, exec);
9869 VM_OBJECT_WUNLOCK(pti_obj);
9873 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
9880 sva = rounddown2(sva, PAGE_SIZE);
9881 MPASS(sva > VM_MAXUSER_ADDRESS);
9882 eva = roundup2(eva, PAGE_SIZE);
9884 VM_OBJECT_WLOCK(pti_obj);
9885 for (va = sva; va < eva; va += PAGE_SIZE) {
9886 pte = pmap_pti_pte(va, NULL);
9887 KASSERT((*pte & X86_PG_V) != 0,
9888 ("invalid pte va %#lx pte %#lx pt %#lx", va,
9889 (u_long)pte, *pte));
9891 pmap_pti_unwire_pte(pte, va);
9893 pmap_invalidate_range(kernel_pmap, sva, eva);
9894 VM_OBJECT_WUNLOCK(pti_obj);
9898 pkru_dup_range(void *ctx __unused, void *data)
9900 struct pmap_pkru_range *node, *new_node;
9902 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
9903 if (new_node == NULL)
9906 memcpy(new_node, node, sizeof(*node));
9911 pkru_free_range(void *ctx __unused, void *node)
9914 uma_zfree(pmap_pkru_ranges_zone, node);
9918 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
9921 struct pmap_pkru_range *ppr;
9924 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9925 MPASS(pmap->pm_type == PT_X86);
9926 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
9927 if ((flags & AMD64_PKRU_EXCL) != 0 &&
9928 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
9930 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
9933 ppr->pkru_keyidx = keyidx;
9934 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
9935 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
9937 uma_zfree(pmap_pkru_ranges_zone, ppr);
9942 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
9945 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9946 MPASS(pmap->pm_type == PT_X86);
9947 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
9948 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
9952 pmap_pkru_deassign_all(pmap_t pmap)
9955 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9956 if (pmap->pm_type == PT_X86 &&
9957 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
9958 rangeset_remove_all(&pmap->pm_pkru);
9962 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
9964 struct pmap_pkru_range *ppr, *prev_ppr;
9967 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9968 if (pmap->pm_type != PT_X86 ||
9969 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
9970 sva >= VM_MAXUSER_ADDRESS)
9972 MPASS(eva <= VM_MAXUSER_ADDRESS);
9973 for (va = sva, prev_ppr = NULL; va < eva;) {
9974 ppr = rangeset_lookup(&pmap->pm_pkru, va);
9975 if ((ppr == NULL) ^ (prev_ppr == NULL))
9981 if (prev_ppr->pkru_keyidx != ppr->pkru_keyidx)
9983 va = ppr->pkru_rs_el.re_end;
9989 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
9991 struct pmap_pkru_range *ppr;
9993 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9994 if (pmap->pm_type != PT_X86 ||
9995 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
9996 va >= VM_MAXUSER_ADDRESS)
9998 ppr = rangeset_lookup(&pmap->pm_pkru, va);
10000 return (X86_PG_PKU(ppr->pkru_keyidx));
10005 pred_pkru_on_remove(void *ctx __unused, void *r)
10007 struct pmap_pkru_range *ppr;
10010 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
10014 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
10017 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
10018 if (pmap->pm_type == PT_X86 &&
10019 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
10020 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
10021 pred_pkru_on_remove);
10026 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
10029 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
10030 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
10031 MPASS(dst_pmap->pm_type == PT_X86);
10032 MPASS(src_pmap->pm_type == PT_X86);
10033 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
10034 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
10036 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
10040 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
10043 pml4_entry_t *pml4e;
10045 pd_entry_t newpde, ptpaddr, *pde;
10046 pt_entry_t newpte, *ptep, pte;
10047 vm_offset_t va, va_next;
10050 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
10051 MPASS(pmap->pm_type == PT_X86);
10052 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
10054 for (changed = false, va = sva; va < eva; va = va_next) {
10055 pml4e = pmap_pml4e(pmap, va);
10056 if ((*pml4e & X86_PG_V) == 0) {
10057 va_next = (va + NBPML4) & ~PML4MASK;
10063 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
10064 if ((*pdpe & X86_PG_V) == 0) {
10065 va_next = (va + NBPDP) & ~PDPMASK;
10071 va_next = (va + NBPDR) & ~PDRMASK;
10075 pde = pmap_pdpe_to_pde(pdpe, va);
10080 MPASS((ptpaddr & X86_PG_V) != 0);
10081 if ((ptpaddr & PG_PS) != 0) {
10082 if (va + NBPDR == va_next && eva >= va_next) {
10083 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
10084 X86_PG_PKU(keyidx);
10085 if (newpde != ptpaddr) {
10090 } else if (!pmap_demote_pde(pmap, pde, va)) {
10098 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
10099 ptep++, va += PAGE_SIZE) {
10101 if ((pte & X86_PG_V) == 0)
10103 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
10104 if (newpte != pte) {
10111 pmap_invalidate_range(pmap, sva, eva);
10115 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
10116 u_int keyidx, int flags)
10119 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
10120 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
10122 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
10124 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
10130 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
10135 sva = trunc_page(sva);
10136 eva = round_page(eva);
10137 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
10142 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
10144 pmap_pkru_update_range(pmap, sva, eva, keyidx);
10146 if (error != ENOMEM)
10154 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
10158 sva = trunc_page(sva);
10159 eva = round_page(eva);
10160 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
10165 error = pmap_pkru_deassign(pmap, sva, eva);
10167 pmap_pkru_update_range(pmap, sva, eva, 0);
10169 if (error != ENOMEM)
10177 * Track a range of the kernel's virtual address space that is contiguous
10178 * in various mapping attributes.
10180 struct pmap_kernel_map_range {
10189 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
10195 if (eva <= range->sva)
10198 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
10199 for (i = 0; i < PAT_INDEX_SIZE; i++)
10200 if (pat_index[i] == pat_idx)
10204 case PAT_WRITE_BACK:
10207 case PAT_WRITE_THROUGH:
10210 case PAT_UNCACHEABLE:
10216 case PAT_WRITE_PROTECTED:
10219 case PAT_WRITE_COMBINING:
10223 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
10224 __func__, pat_idx, range->sva, eva);
10229 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
10231 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
10232 (range->attrs & pg_nx) != 0 ? '-' : 'x',
10233 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
10234 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
10235 mode, range->pdpes, range->pdes, range->ptes);
10237 /* Reset to sentinel value. */
10238 range->sva = KVADDR(NPML4EPG - 1, NPDPEPG - 1, NPDEPG - 1, NPTEPG - 1);
10242 * Determine whether the attributes specified by a page table entry match those
10243 * being tracked by the current range. This is not quite as simple as a direct
10244 * flag comparison since some PAT modes have multiple representations.
10247 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
10249 pt_entry_t diff, mask;
10251 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
10252 diff = (range->attrs ^ attrs) & mask;
10255 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
10256 pmap_pat_index(kernel_pmap, range->attrs, true) ==
10257 pmap_pat_index(kernel_pmap, attrs, true))
10263 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
10267 memset(range, 0, sizeof(*range));
10269 range->attrs = attrs;
10273 * Given a leaf PTE, derive the mapping's attributes. If they do not match
10274 * those of the current run, dump the address range and its attributes, and
10278 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
10279 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
10284 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
10286 attrs |= pdpe & pg_nx;
10287 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
10288 if ((pdpe & PG_PS) != 0) {
10289 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
10290 } else if (pde != 0) {
10291 attrs |= pde & pg_nx;
10292 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
10294 if ((pde & PG_PS) != 0) {
10295 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
10296 } else if (pte != 0) {
10297 attrs |= pte & pg_nx;
10298 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
10299 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
10301 /* Canonicalize by always using the PDE PAT bit. */
10302 if ((attrs & X86_PG_PTE_PAT) != 0)
10303 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
10306 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
10307 sysctl_kmaps_dump(sb, range, va);
10308 sysctl_kmaps_reinit(range, va, attrs);
10313 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
10315 struct pmap_kernel_map_range range;
10316 struct sbuf sbuf, *sb;
10317 pml4_entry_t pml4e;
10318 pdp_entry_t *pdp, pdpe;
10319 pd_entry_t *pd, pde;
10320 pt_entry_t *pt, pte;
10323 int error, i, j, k, l;
10325 error = sysctl_wire_old_buffer(req, 0);
10329 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
10331 /* Sentinel value. */
10332 range.sva = KVADDR(NPML4EPG - 1, NPDPEPG - 1, NPDEPG - 1, NPTEPG - 1);
10335 * Iterate over the kernel page tables without holding the kernel pmap
10336 * lock. Outside of the large map, kernel page table pages are never
10337 * freed, so at worst we will observe inconsistencies in the output.
10338 * Within the large map, ensure that PDP and PD page addresses are
10339 * valid before descending.
10341 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
10344 sbuf_printf(sb, "\nRecursive map:\n");
10347 sbuf_printf(sb, "\nDirect map:\n");
10350 sbuf_printf(sb, "\nKernel map:\n");
10353 sbuf_printf(sb, "\nLarge map:\n");
10357 /* Convert to canonical form. */
10358 if (sva == 1ul << 47)
10362 pml4e = kernel_pmap->pm_pml4[i];
10363 if ((pml4e & X86_PG_V) == 0) {
10364 sva = rounddown2(sva, NBPML4);
10365 sysctl_kmaps_dump(sb, &range, sva);
10369 pa = pml4e & PG_FRAME;
10370 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
10372 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
10374 if ((pdpe & X86_PG_V) == 0) {
10375 sva = rounddown2(sva, NBPDP);
10376 sysctl_kmaps_dump(sb, &range, sva);
10380 pa = pdpe & PG_FRAME;
10381 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10382 vm_phys_paddr_to_vm_page(pa) == NULL)
10384 if ((pdpe & PG_PS) != 0) {
10385 sva = rounddown2(sva, NBPDP);
10386 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
10392 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
10394 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
10396 if ((pde & X86_PG_V) == 0) {
10397 sva = rounddown2(sva, NBPDR);
10398 sysctl_kmaps_dump(sb, &range, sva);
10402 pa = pde & PG_FRAME;
10403 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10404 vm_phys_paddr_to_vm_page(pa) == NULL)
10406 if ((pde & PG_PS) != 0) {
10407 sva = rounddown2(sva, NBPDR);
10408 sysctl_kmaps_check(sb, &range, sva,
10409 pml4e, pdpe, pde, 0);
10414 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
10416 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
10417 sva += PAGE_SIZE) {
10419 if ((pte & X86_PG_V) == 0) {
10420 sysctl_kmaps_dump(sb, &range,
10424 sysctl_kmaps_check(sb, &range, sva,
10425 pml4e, pdpe, pde, pte);
10432 error = sbuf_finish(sb);
10436 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
10437 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
10438 NULL, 0, sysctl_kmaps, "A",
10439 "Dump kernel address layout");
10442 DB_SHOW_COMMAND(pte, pmap_print_pte)
10445 pml4_entry_t *pml4;
10448 pt_entry_t *pte, PG_V;
10452 db_printf("show pte addr\n");
10455 va = (vm_offset_t)addr;
10457 if (kdb_thread != NULL)
10458 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
10460 pmap = PCPU_GET(curpmap);
10462 PG_V = pmap_valid_bit(pmap);
10463 pml4 = pmap_pml4e(pmap, va);
10464 db_printf("VA 0x%016lx pml4e 0x%016lx", va, *pml4);
10465 if ((*pml4 & PG_V) == 0) {
10469 pdp = pmap_pml4e_to_pdpe(pml4, va);
10470 db_printf(" pdpe 0x%016lx", *pdp);
10471 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
10475 pde = pmap_pdpe_to_pde(pdp, va);
10476 db_printf(" pde 0x%016lx", *pde);
10477 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
10481 pte = pmap_pde_to_pte(pde, va);
10482 db_printf(" pte 0x%016lx\n", *pte);
10485 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
10490 a = (vm_paddr_t)addr;
10491 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
10493 db_printf("show phys2dmap addr\n");