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-2018 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.
110 #include "opt_pmap.h"
113 #include <sys/param.h>
114 #include <sys/bitstring.h>
116 #include <sys/systm.h>
117 #include <sys/kernel.h>
119 #include <sys/lock.h>
120 #include <sys/malloc.h>
121 #include <sys/mman.h>
122 #include <sys/mutex.h>
123 #include <sys/proc.h>
124 #include <sys/rwlock.h>
126 #include <sys/turnstile.h>
127 #include <sys/vmem.h>
128 #include <sys/vmmeter.h>
129 #include <sys/sched.h>
130 #include <sys/sysctl.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
147 #include <machine/intr_machdep.h>
148 #include <x86/apicvar.h>
149 #include <x86/ifunc.h>
150 #include <machine/cpu.h>
151 #include <machine/cputypes.h>
152 #include <machine/md_var.h>
153 #include <machine/pcb.h>
154 #include <machine/specialreg.h>
156 #include <machine/smp.h>
158 #include <machine/tss.h>
160 static __inline boolean_t
161 pmap_type_guest(pmap_t pmap)
164 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
167 static __inline boolean_t
168 pmap_emulate_ad_bits(pmap_t pmap)
171 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
174 static __inline pt_entry_t
175 pmap_valid_bit(pmap_t pmap)
179 switch (pmap->pm_type) {
185 if (pmap_emulate_ad_bits(pmap))
186 mask = EPT_PG_EMUL_V;
191 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
197 static __inline pt_entry_t
198 pmap_rw_bit(pmap_t pmap)
202 switch (pmap->pm_type) {
208 if (pmap_emulate_ad_bits(pmap))
209 mask = EPT_PG_EMUL_RW;
214 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
220 static pt_entry_t pg_g;
222 static __inline pt_entry_t
223 pmap_global_bit(pmap_t pmap)
227 switch (pmap->pm_type) {
236 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
242 static __inline pt_entry_t
243 pmap_accessed_bit(pmap_t pmap)
247 switch (pmap->pm_type) {
253 if (pmap_emulate_ad_bits(pmap))
259 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
265 static __inline pt_entry_t
266 pmap_modified_bit(pmap_t pmap)
270 switch (pmap->pm_type) {
276 if (pmap_emulate_ad_bits(pmap))
282 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
292 #define PMAP_INLINE extern inline
299 #define PV_STAT(x) do { x ; } while (0)
301 #define PV_STAT(x) do { } while (0)
304 #define pa_index(pa) ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
307 #define NPV_LIST_LOCKS MAXCPU
309 #define PHYS_TO_PV_LIST_LOCK(pa) \
310 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
313 struct rwlock **_lockp = (lockp); \
314 struct rwlock *_new_lock; \
316 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
317 if (_new_lock != *_lockp) { \
318 if (*_lockp != NULL) \
319 rw_wunlock(*_lockp); \
320 *_lockp = _new_lock; \
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
326 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
328 #define RELEASE_PV_LIST_LOCK(lockp) do { \
329 struct rwlock **_lockp = (lockp); \
331 if (*_lockp != NULL) { \
332 rw_wunlock(*_lockp); \
337 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
338 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
340 struct pmap kernel_pmap_store;
342 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347 "Number of kernel page table pages allocated on bootup");
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358 "Is page attribute table fully functional?");
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362 &pg_ps_enabled, 0, "Are large page mappings enabled?");
364 #define PAT_INDEX_SIZE 8
365 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
367 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
368 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
369 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
370 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
372 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
373 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
374 static int ndmpdpphys; /* number of DMPDPphys pages */
376 static vm_paddr_t KERNend; /* phys addr of end of bootstrap data */
379 * pmap_mapdev support pre initialization (i.e. console)
381 #define PMAP_PREINIT_MAPPING_COUNT 8
382 static struct pmap_preinit_mapping {
387 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
388 static int pmap_initialized;
391 * Data for the pv entry allocation mechanism.
392 * Updates to pv_invl_gen are protected by the pv_list_locks[]
393 * elements, but reads are not.
395 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
396 static struct mtx __exclusive_cache_line pv_chunks_mutex;
397 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
398 static u_long pv_invl_gen[NPV_LIST_LOCKS];
399 static struct md_page *pv_table;
400 static struct md_page pv_dummy;
403 * All those kernel PT submaps that BSD is so fond of
405 pt_entry_t *CMAP1 = NULL;
407 static vm_offset_t qframe = 0;
408 static struct mtx qframe_mtx;
410 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
412 int pmap_pcid_enabled = 1;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
414 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
415 int invpcid_works = 0;
416 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
417 "Is the invpcid instruction available ?");
419 int __read_frequently pti = 0;
420 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
422 "Page Table Isolation enabled");
423 static vm_object_t pti_obj;
424 static pml4_entry_t *pti_pml4;
425 static vm_pindex_t pti_pg_idx;
426 static bool pti_finalized;
429 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
436 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
438 return (sysctl_handle_64(oidp, &res, 0, req));
440 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
441 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
442 "Count of saved TLB context on switch");
444 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
445 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
446 static struct mtx invl_gen_mtx;
447 static u_long pmap_invl_gen = 0;
448 /* Fake lock object to satisfy turnstiles interface. */
449 static struct lock_object invl_gen_ts = {
457 return (curthread->td_md.md_invl_gen.gen == 0);
460 #define PMAP_ASSERT_NOT_IN_DI() \
461 KASSERT(pmap_not_in_di(), ("DI already started"))
464 * Start a new Delayed Invalidation (DI) block of code, executed by
465 * the current thread. Within a DI block, the current thread may
466 * destroy both the page table and PV list entries for a mapping and
467 * then release the corresponding PV list lock before ensuring that
468 * the mapping is flushed from the TLBs of any processors with the
472 pmap_delayed_invl_started(void)
474 struct pmap_invl_gen *invl_gen;
477 invl_gen = &curthread->td_md.md_invl_gen;
478 PMAP_ASSERT_NOT_IN_DI();
479 mtx_lock(&invl_gen_mtx);
480 if (LIST_EMPTY(&pmap_invl_gen_tracker))
481 currgen = pmap_invl_gen;
483 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
484 invl_gen->gen = currgen + 1;
485 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
486 mtx_unlock(&invl_gen_mtx);
490 * Finish the DI block, previously started by the current thread. All
491 * required TLB flushes for the pages marked by
492 * pmap_delayed_invl_page() must be finished before this function is
495 * This function works by bumping the global DI generation number to
496 * the generation number of the current thread's DI, unless there is a
497 * pending DI that started earlier. In the latter case, bumping the
498 * global DI generation number would incorrectly signal that the
499 * earlier DI had finished. Instead, this function bumps the earlier
500 * DI's generation number to match the generation number of the
501 * current thread's DI.
504 pmap_delayed_invl_finished(void)
506 struct pmap_invl_gen *invl_gen, *next;
507 struct turnstile *ts;
509 invl_gen = &curthread->td_md.md_invl_gen;
510 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
511 mtx_lock(&invl_gen_mtx);
512 next = LIST_NEXT(invl_gen, link);
514 turnstile_chain_lock(&invl_gen_ts);
515 ts = turnstile_lookup(&invl_gen_ts);
516 pmap_invl_gen = invl_gen->gen;
518 turnstile_broadcast(ts, TS_SHARED_QUEUE);
519 turnstile_unpend(ts);
521 turnstile_chain_unlock(&invl_gen_ts);
523 next->gen = invl_gen->gen;
525 LIST_REMOVE(invl_gen, link);
526 mtx_unlock(&invl_gen_mtx);
531 static long invl_wait;
532 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
533 "Number of times DI invalidation blocked pmap_remove_all/write");
537 pmap_delayed_invl_genp(vm_page_t m)
540 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
544 * Ensure that all currently executing DI blocks, that need to flush
545 * TLB for the given page m, actually flushed the TLB at the time the
546 * function returned. If the page m has an empty PV list and we call
547 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
548 * valid mapping for the page m in either its page table or TLB.
550 * This function works by blocking until the global DI generation
551 * number catches up with the generation number associated with the
552 * given page m and its PV list. Since this function's callers
553 * typically own an object lock and sometimes own a page lock, it
554 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
558 pmap_delayed_invl_wait(vm_page_t m)
560 struct turnstile *ts;
563 bool accounted = false;
566 m_gen = pmap_delayed_invl_genp(m);
567 while (*m_gen > pmap_invl_gen) {
570 atomic_add_long(&invl_wait, 1);
574 ts = turnstile_trywait(&invl_gen_ts);
575 if (*m_gen > pmap_invl_gen)
576 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
578 turnstile_cancel(ts);
583 * Mark the page m's PV list as participating in the current thread's
584 * DI block. Any threads concurrently using m's PV list to remove or
585 * restrict all mappings to m will wait for the current thread's DI
586 * block to complete before proceeding.
588 * The function works by setting the DI generation number for m's PV
589 * list to at least the DI generation number of the current thread.
590 * This forces a caller of pmap_delayed_invl_wait() to block until
591 * current thread calls pmap_delayed_invl_finished().
594 pmap_delayed_invl_page(vm_page_t m)
598 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
599 gen = curthread->td_md.md_invl_gen.gen;
602 m_gen = pmap_delayed_invl_genp(m);
610 static caddr_t crashdumpmap;
613 * Internal flags for pmap_enter()'s helper functions.
615 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
616 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
618 static void free_pv_chunk(struct pv_chunk *pc);
619 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
620 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
621 static int popcnt_pc_map_pq(uint64_t *map);
622 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
623 static void reserve_pv_entries(pmap_t pmap, int needed,
624 struct rwlock **lockp);
625 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
626 struct rwlock **lockp);
627 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
628 u_int flags, struct rwlock **lockp);
629 #if VM_NRESERVLEVEL > 0
630 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
631 struct rwlock **lockp);
633 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
634 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
637 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
638 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
639 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
640 vm_offset_t va, struct rwlock **lockp);
641 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
643 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
644 vm_prot_t prot, struct rwlock **lockp);
645 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
646 u_int flags, vm_page_t m, struct rwlock **lockp);
647 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
648 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
649 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
650 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
651 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
653 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
655 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
657 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
658 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
659 #if VM_NRESERVLEVEL > 0
660 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
661 struct rwlock **lockp);
663 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
665 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
666 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
668 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
669 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
670 static void pmap_pti_wire_pte(void *pte);
671 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
672 struct spglist *free, struct rwlock **lockp);
673 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
674 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
675 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
676 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
677 struct spglist *free);
678 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
679 pd_entry_t *pde, struct spglist *free,
680 struct rwlock **lockp);
681 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
682 vm_page_t m, struct rwlock **lockp);
683 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
685 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
687 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
688 struct rwlock **lockp);
689 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
690 struct rwlock **lockp);
691 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
692 struct rwlock **lockp);
694 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
695 struct spglist *free);
696 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
698 /********************/
699 /* Inline functions */
700 /********************/
702 /* Return a non-clipped PD index for a given VA */
703 static __inline vm_pindex_t
704 pmap_pde_pindex(vm_offset_t va)
706 return (va >> PDRSHIFT);
710 /* Return a pointer to the PML4 slot that corresponds to a VA */
711 static __inline pml4_entry_t *
712 pmap_pml4e(pmap_t pmap, vm_offset_t va)
715 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
718 /* Return a pointer to the PDP slot that corresponds to a VA */
719 static __inline pdp_entry_t *
720 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
724 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
725 return (&pdpe[pmap_pdpe_index(va)]);
728 /* Return a pointer to the PDP slot that corresponds to a VA */
729 static __inline pdp_entry_t *
730 pmap_pdpe(pmap_t pmap, vm_offset_t va)
735 PG_V = pmap_valid_bit(pmap);
736 pml4e = pmap_pml4e(pmap, va);
737 if ((*pml4e & PG_V) == 0)
739 return (pmap_pml4e_to_pdpe(pml4e, va));
742 /* Return a pointer to the PD slot that corresponds to a VA */
743 static __inline pd_entry_t *
744 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
748 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
749 return (&pde[pmap_pde_index(va)]);
752 /* Return a pointer to the PD slot that corresponds to a VA */
753 static __inline pd_entry_t *
754 pmap_pde(pmap_t pmap, vm_offset_t va)
759 PG_V = pmap_valid_bit(pmap);
760 pdpe = pmap_pdpe(pmap, va);
761 if (pdpe == NULL || (*pdpe & PG_V) == 0)
763 return (pmap_pdpe_to_pde(pdpe, va));
766 /* Return a pointer to the PT slot that corresponds to a VA */
767 static __inline pt_entry_t *
768 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
772 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
773 return (&pte[pmap_pte_index(va)]);
776 /* Return a pointer to the PT slot that corresponds to a VA */
777 static __inline pt_entry_t *
778 pmap_pte(pmap_t pmap, vm_offset_t va)
783 PG_V = pmap_valid_bit(pmap);
784 pde = pmap_pde(pmap, va);
785 if (pde == NULL || (*pde & PG_V) == 0)
787 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
788 return ((pt_entry_t *)pde);
789 return (pmap_pde_to_pte(pde, va));
793 pmap_resident_count_inc(pmap_t pmap, int count)
796 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
797 pmap->pm_stats.resident_count += count;
801 pmap_resident_count_dec(pmap_t pmap, int count)
804 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
805 KASSERT(pmap->pm_stats.resident_count >= count,
806 ("pmap %p resident count underflow %ld %d", pmap,
807 pmap->pm_stats.resident_count, count));
808 pmap->pm_stats.resident_count -= count;
811 PMAP_INLINE pt_entry_t *
812 vtopte(vm_offset_t va)
814 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
816 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
818 return (PTmap + ((va >> PAGE_SHIFT) & mask));
821 static __inline pd_entry_t *
822 vtopde(vm_offset_t va)
824 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
826 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
828 return (PDmap + ((va >> PDRSHIFT) & mask));
832 allocpages(vm_paddr_t *firstaddr, int n)
837 bzero((void *)ret, n * PAGE_SIZE);
838 *firstaddr += n * PAGE_SIZE;
842 CTASSERT(powerof2(NDMPML4E));
844 /* number of kernel PDP slots */
845 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
848 nkpt_init(vm_paddr_t addr)
855 pt_pages = howmany(addr, 1 << PDRSHIFT);
856 pt_pages += NKPDPE(pt_pages);
859 * Add some slop beyond the bare minimum required for bootstrapping
862 * This is quite important when allocating KVA for kernel modules.
863 * The modules are required to be linked in the negative 2GB of
864 * the address space. If we run out of KVA in this region then
865 * pmap_growkernel() will need to allocate page table pages to map
866 * the entire 512GB of KVA space which is an unnecessary tax on
869 * Secondly, device memory mapped as part of setting up the low-
870 * level console(s) is taken from KVA, starting at virtual_avail.
871 * This is because cninit() is called after pmap_bootstrap() but
872 * before vm_init() and pmap_init(). 20MB for a frame buffer is
875 pt_pages += 32; /* 64MB additional slop. */
881 * Returns the proper write/execute permission for a physical page that is
882 * part of the initial boot allocations.
884 * If the page has kernel text, it is marked as read-only. If the page has
885 * kernel read-only data, it is marked as read-only/not-executable. If the
886 * page has only read-write data, it is marked as read-write/not-executable.
887 * If the page is below/above the kernel range, it is marked as read-write.
889 * This function operates on 2M pages, since we map the kernel space that
892 * Note that this doesn't currently provide any protection for modules.
894 static inline pt_entry_t
895 bootaddr_rwx(vm_paddr_t pa)
899 * Everything in the same 2M page as the start of the kernel
900 * should be static. On the other hand, things in the same 2M
901 * page as the end of the kernel could be read-write/executable,
902 * as the kernel image is not guaranteed to end on a 2M boundary.
904 if (pa < trunc_2mpage(btext - KERNBASE) ||
905 pa >= trunc_2mpage(_end - KERNBASE))
908 * The linker should ensure that the read-only and read-write
909 * portions don't share the same 2M page, so this shouldn't
910 * impact read-only data. However, in any case, any page with
911 * read-write data needs to be read-write.
913 if (pa >= trunc_2mpage(brwsection - KERNBASE))
914 return (X86_PG_RW | pg_nx);
916 * Mark any 2M page containing kernel text as read-only. Mark
917 * other pages with read-only data as read-only and not executable.
918 * (It is likely a small portion of the read-only data section will
919 * be marked as read-only, but executable. This should be acceptable
920 * since the read-only protection will keep the data from changing.)
921 * Note that fixups to the .text section will still work until we
924 if (pa < round_2mpage(etext - KERNBASE))
930 create_pagetables(vm_paddr_t *firstaddr)
932 int i, j, ndm1g, nkpdpe, nkdmpde;
937 uint64_t DMPDkernphys;
939 /* Allocate page table pages for the direct map */
940 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
941 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
943 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
944 if (ndmpdpphys > NDMPML4E) {
946 * Each NDMPML4E allows 512 GB, so limit to that,
947 * and then readjust ndmpdp and ndmpdpphys.
949 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
950 Maxmem = atop(NDMPML4E * NBPML4);
951 ndmpdpphys = NDMPML4E;
952 ndmpdp = NDMPML4E * NPDEPG;
954 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
956 if ((amd_feature & AMDID_PAGE1GB) != 0) {
958 * Calculate the number of 1G pages that will fully fit in
961 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
964 * Allocate 2M pages for the kernel. These will be used in
965 * place of the first one or more 1G pages from ndm1g.
967 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
968 DMPDkernphys = allocpages(firstaddr, nkdmpde);
971 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
972 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
975 KPML4phys = allocpages(firstaddr, 1);
976 KPDPphys = allocpages(firstaddr, NKPML4E);
979 * Allocate the initial number of kernel page table pages required to
980 * bootstrap. We defer this until after all memory-size dependent
981 * allocations are done (e.g. direct map), so that we don't have to
982 * build in too much slop in our estimate.
984 * Note that when NKPML4E > 1, we have an empty page underneath
985 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
986 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
988 nkpt_init(*firstaddr);
989 nkpdpe = NKPDPE(nkpt);
991 KPTphys = allocpages(firstaddr, nkpt);
992 KPDphys = allocpages(firstaddr, nkpdpe);
994 /* Fill in the underlying page table pages */
995 /* XXX not fully used, underneath 2M pages */
996 pt_p = (pt_entry_t *)KPTphys;
997 for (i = 0; ptoa(i) < *firstaddr; i++)
998 pt_p[i] = ptoa(i) | X86_PG_V | pg_g | bootaddr_rwx(ptoa(i));
1000 /* Now map the page tables at their location within PTmap */
1001 pd_p = (pd_entry_t *)KPDphys;
1002 for (i = 0; i < nkpt; i++)
1003 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1005 /* Map from zero to end of allocations under 2M pages */
1006 /* This replaces some of the KPTphys entries above */
1007 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
1008 /* Preset PG_M and PG_A because demotion expects it. */
1009 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1010 X86_PG_M | X86_PG_A | bootaddr_rwx(i << PDRSHIFT);
1013 * Because we map the physical blocks in 2M pages, adjust firstaddr
1014 * to record the physical blocks we've actually mapped into kernel
1015 * virtual address space.
1017 *firstaddr = round_2mpage(*firstaddr);
1019 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1020 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1021 for (i = 0; i < nkpdpe; i++)
1022 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1025 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1026 * the end of physical memory is not aligned to a 1GB page boundary,
1027 * then the residual physical memory is mapped with 2MB pages. Later,
1028 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1029 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1030 * that are partially used.
1032 pd_p = (pd_entry_t *)DMPDphys;
1033 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1034 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1035 /* Preset PG_M and PG_A because demotion expects it. */
1036 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1037 X86_PG_M | X86_PG_A | pg_nx;
1039 pdp_p = (pdp_entry_t *)DMPDPphys;
1040 for (i = 0; i < ndm1g; i++) {
1041 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1042 /* Preset PG_M and PG_A because demotion expects it. */
1043 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1044 X86_PG_M | X86_PG_A | pg_nx;
1046 for (j = 0; i < ndmpdp; i++, j++) {
1047 pdp_p[i] = DMPDphys + ptoa(j);
1048 pdp_p[i] |= X86_PG_RW | X86_PG_V;
1052 * Instead of using a 1G page for the memory containing the kernel,
1053 * use 2M pages with appropriate permissions. (If using 1G pages,
1054 * this will partially overwrite the PDPEs above.)
1057 pd_p = (pd_entry_t *)DMPDkernphys;
1058 for (i = 0; i < (NPDEPG * nkdmpde); i++)
1059 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1060 X86_PG_M | X86_PG_A | pg_nx |
1061 bootaddr_rwx(i << PDRSHIFT);
1062 for (i = 0; i < nkdmpde; i++)
1063 pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
1067 /* And recursively map PML4 to itself in order to get PTmap */
1068 p4_p = (pml4_entry_t *)KPML4phys;
1069 p4_p[PML4PML4I] = KPML4phys;
1070 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1072 /* Connect the Direct Map slot(s) up to the PML4. */
1073 for (i = 0; i < ndmpdpphys; i++) {
1074 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1075 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
1078 /* Connect the KVA slots up to the PML4 */
1079 for (i = 0; i < NKPML4E; i++) {
1080 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1081 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1086 * Bootstrap the system enough to run with virtual memory.
1088 * On amd64 this is called after mapping has already been enabled
1089 * and just syncs the pmap module with what has already been done.
1090 * [We can't call it easily with mapping off since the kernel is not
1091 * mapped with PA == VA, hence we would have to relocate every address
1092 * from the linked base (virtual) address "KERNBASE" to the actual
1093 * (physical) address starting relative to 0]
1096 pmap_bootstrap(vm_paddr_t *firstaddr)
1104 KERNend = *firstaddr;
1105 res = atop(KERNend - (vm_paddr_t)kernphys);
1111 * Create an initial set of page tables to run the kernel in.
1113 create_pagetables(firstaddr);
1116 * Add a physical memory segment (vm_phys_seg) corresponding to the
1117 * preallocated kernel page table pages so that vm_page structures
1118 * representing these pages will be created. The vm_page structures
1119 * are required for promotion of the corresponding kernel virtual
1120 * addresses to superpage mappings.
1122 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1124 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1125 virtual_end = VM_MAX_KERNEL_ADDRESS;
1128 * Enable PG_G global pages, then switch to the kernel page
1129 * table from the bootstrap page table. After the switch, it
1130 * is possible to enable SMEP and SMAP since PG_U bits are
1136 load_cr3(KPML4phys);
1137 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1139 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1144 * Initialize the kernel pmap (which is statically allocated).
1145 * Count bootstrap data as being resident in case any of this data is
1146 * later unmapped (using pmap_remove()) and freed.
1148 PMAP_LOCK_INIT(kernel_pmap);
1149 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1150 kernel_pmap->pm_cr3 = KPML4phys;
1151 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1152 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1153 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1154 kernel_pmap->pm_stats.resident_count = res;
1155 kernel_pmap->pm_flags = pmap_flags;
1158 * Initialize the TLB invalidations generation number lock.
1160 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1163 * Reserve some special page table entries/VA space for temporary
1166 #define SYSMAP(c, p, v, n) \
1167 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1173 * Crashdump maps. The first page is reused as CMAP1 for the
1176 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1177 CADDR1 = crashdumpmap;
1182 * Initialize the PAT MSR.
1183 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1184 * side-effect, invalidates stale PG_G TLB entries that might
1185 * have been created in our pre-boot environment.
1189 /* Initialize TLB Context Id. */
1190 if (pmap_pcid_enabled) {
1191 for (i = 0; i < MAXCPU; i++) {
1192 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1193 kernel_pmap->pm_pcids[i].pm_gen = 1;
1197 * PMAP_PCID_KERN + 1 is used for initialization of
1198 * proc0 pmap. The pmap' pcid state might be used by
1199 * EFIRT entry before first context switch, so it
1200 * needs to be valid.
1202 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
1203 PCPU_SET(pcid_gen, 1);
1206 * pcpu area for APs is zeroed during AP startup.
1207 * pc_pcid_next and pc_pcid_gen are initialized by AP
1208 * during pcpu setup.
1210 load_cr4(rcr4() | CR4_PCIDE);
1215 * Setup the PAT MSR.
1220 int pat_table[PAT_INDEX_SIZE];
1225 /* Bail if this CPU doesn't implement PAT. */
1226 if ((cpu_feature & CPUID_PAT) == 0)
1229 /* Set default PAT index table. */
1230 for (i = 0; i < PAT_INDEX_SIZE; i++)
1232 pat_table[PAT_WRITE_BACK] = 0;
1233 pat_table[PAT_WRITE_THROUGH] = 1;
1234 pat_table[PAT_UNCACHEABLE] = 3;
1235 pat_table[PAT_WRITE_COMBINING] = 3;
1236 pat_table[PAT_WRITE_PROTECTED] = 3;
1237 pat_table[PAT_UNCACHED] = 3;
1239 /* Initialize default PAT entries. */
1240 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1241 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1242 PAT_VALUE(2, PAT_UNCACHED) |
1243 PAT_VALUE(3, PAT_UNCACHEABLE) |
1244 PAT_VALUE(4, PAT_WRITE_BACK) |
1245 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1246 PAT_VALUE(6, PAT_UNCACHED) |
1247 PAT_VALUE(7, PAT_UNCACHEABLE);
1251 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1252 * Program 5 and 6 as WP and WC.
1253 * Leave 4 and 7 as WB and UC.
1255 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1256 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1257 PAT_VALUE(6, PAT_WRITE_COMBINING);
1258 pat_table[PAT_UNCACHED] = 2;
1259 pat_table[PAT_WRITE_PROTECTED] = 5;
1260 pat_table[PAT_WRITE_COMBINING] = 6;
1263 * Just replace PAT Index 2 with WC instead of UC-.
1265 pat_msr &= ~PAT_MASK(2);
1266 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1267 pat_table[PAT_WRITE_COMBINING] = 2;
1272 load_cr4(cr4 & ~CR4_PGE);
1274 /* Disable caches (CD = 1, NW = 0). */
1276 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1278 /* Flushes caches and TLBs. */
1282 /* Update PAT and index table. */
1283 wrmsr(MSR_PAT, pat_msr);
1284 for (i = 0; i < PAT_INDEX_SIZE; i++)
1285 pat_index[i] = pat_table[i];
1287 /* Flush caches and TLBs again. */
1291 /* Restore caches and PGE. */
1297 * Initialize a vm_page's machine-dependent fields.
1300 pmap_page_init(vm_page_t m)
1303 TAILQ_INIT(&m->md.pv_list);
1304 m->md.pat_mode = PAT_WRITE_BACK;
1308 * Initialize the pmap module.
1309 * Called by vm_init, to initialize any structures that the pmap
1310 * system needs to map virtual memory.
1315 struct pmap_preinit_mapping *ppim;
1318 int error, i, pv_npg, ret, skz63;
1320 /* L1TF, reserve page @0 unconditionally */
1321 vm_page_blacklist_add(0, bootverbose);
1323 /* Detect bare-metal Skylake Server and Skylake-X. */
1324 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1325 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1327 * Skylake-X errata SKZ63. Processor May Hang When
1328 * Executing Code In an HLE Transaction Region between
1329 * 40000000H and 403FFFFFH.
1331 * Mark the pages in the range as preallocated. It
1332 * seems to be impossible to distinguish between
1333 * Skylake Server and Skylake X.
1336 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1339 printf("SKZ63: skipping 4M RAM starting "
1340 "at physical 1G\n");
1341 for (i = 0; i < atop(0x400000); i++) {
1342 ret = vm_page_blacklist_add(0x40000000 +
1344 if (!ret && bootverbose)
1345 printf("page at %#lx already used\n",
1346 0x40000000 + ptoa(i));
1352 * Initialize the vm page array entries for the kernel pmap's
1355 PMAP_LOCK(kernel_pmap);
1356 for (i = 0; i < nkpt; i++) {
1357 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1358 KASSERT(mpte >= vm_page_array &&
1359 mpte < &vm_page_array[vm_page_array_size],
1360 ("pmap_init: page table page is out of range"));
1361 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1362 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1363 mpte->wire_count = 1;
1364 if (i << PDRSHIFT < KERNend &&
1365 pmap_insert_pt_page(kernel_pmap, mpte))
1366 panic("pmap_init: pmap_insert_pt_page failed");
1368 PMAP_UNLOCK(kernel_pmap);
1372 * If the kernel is running on a virtual machine, then it must assume
1373 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1374 * be prepared for the hypervisor changing the vendor and family that
1375 * are reported by CPUID. Consequently, the workaround for AMD Family
1376 * 10h Erratum 383 is enabled if the processor's feature set does not
1377 * include at least one feature that is only supported by older Intel
1378 * or newer AMD processors.
1380 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1381 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1382 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1384 workaround_erratum383 = 1;
1387 * Are large page mappings enabled?
1389 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1390 if (pg_ps_enabled) {
1391 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1392 ("pmap_init: can't assign to pagesizes[1]"));
1393 pagesizes[1] = NBPDR;
1397 * Initialize the pv chunk list mutex.
1399 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1402 * Initialize the pool of pv list locks.
1404 for (i = 0; i < NPV_LIST_LOCKS; i++)
1405 rw_init(&pv_list_locks[i], "pmap pv list");
1408 * Calculate the size of the pv head table for superpages.
1410 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1413 * Allocate memory for the pv head table for superpages.
1415 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1417 pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
1418 for (i = 0; i < pv_npg; i++)
1419 TAILQ_INIT(&pv_table[i].pv_list);
1420 TAILQ_INIT(&pv_dummy.pv_list);
1422 pmap_initialized = 1;
1423 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1424 ppim = pmap_preinit_mapping + i;
1427 /* Make the direct map consistent */
1428 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
1429 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1430 ppim->sz, ppim->mode);
1434 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1435 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1438 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1439 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1440 (vmem_addr_t *)&qframe);
1442 panic("qframe allocation failed");
1445 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1446 "2MB page mapping counters");
1448 static u_long pmap_pde_demotions;
1449 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1450 &pmap_pde_demotions, 0, "2MB page demotions");
1452 static u_long pmap_pde_mappings;
1453 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1454 &pmap_pde_mappings, 0, "2MB page mappings");
1456 static u_long pmap_pde_p_failures;
1457 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1458 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1460 static u_long pmap_pde_promotions;
1461 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1462 &pmap_pde_promotions, 0, "2MB page promotions");
1464 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1465 "1GB page mapping counters");
1467 static u_long pmap_pdpe_demotions;
1468 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1469 &pmap_pdpe_demotions, 0, "1GB page demotions");
1471 /***************************************************
1472 * Low level helper routines.....
1473 ***************************************************/
1476 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1478 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1480 switch (pmap->pm_type) {
1483 /* Verify that both PAT bits are not set at the same time */
1484 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1485 ("Invalid PAT bits in entry %#lx", entry));
1487 /* Swap the PAT bits if one of them is set */
1488 if ((entry & x86_pat_bits) != 0)
1489 entry ^= x86_pat_bits;
1493 * Nothing to do - the memory attributes are represented
1494 * the same way for regular pages and superpages.
1498 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1505 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
1508 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
1509 pat_index[(int)mode] >= 0);
1513 * Determine the appropriate bits to set in a PTE or PDE for a specified
1517 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1519 int cache_bits, pat_flag, pat_idx;
1521 if (!pmap_is_valid_memattr(pmap, mode))
1522 panic("Unknown caching mode %d\n", mode);
1524 switch (pmap->pm_type) {
1527 /* The PAT bit is different for PTE's and PDE's. */
1528 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1530 /* Map the caching mode to a PAT index. */
1531 pat_idx = pat_index[mode];
1533 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1536 cache_bits |= pat_flag;
1538 cache_bits |= PG_NC_PCD;
1540 cache_bits |= PG_NC_PWT;
1544 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1548 panic("unsupported pmap type %d", pmap->pm_type);
1551 return (cache_bits);
1555 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1559 switch (pmap->pm_type) {
1562 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1565 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1568 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1575 pmap_ps_enabled(pmap_t pmap)
1578 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1582 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1585 switch (pmap->pm_type) {
1592 * This is a little bogus since the generation number is
1593 * supposed to be bumped up when a region of the address
1594 * space is invalidated in the page tables.
1596 * In this case the old PDE entry is valid but yet we want
1597 * to make sure that any mappings using the old entry are
1598 * invalidated in the TLB.
1600 * The reason this works as expected is because we rendezvous
1601 * "all" host cpus and force any vcpu context to exit as a
1604 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1607 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1609 pde_store(pde, newpde);
1613 * After changing the page size for the specified virtual address in the page
1614 * table, flush the corresponding entries from the processor's TLB. Only the
1615 * calling processor's TLB is affected.
1617 * The calling thread must be pinned to a processor.
1620 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1624 if (pmap_type_guest(pmap))
1627 KASSERT(pmap->pm_type == PT_X86,
1628 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1630 PG_G = pmap_global_bit(pmap);
1632 if ((newpde & PG_PS) == 0)
1633 /* Demotion: flush a specific 2MB page mapping. */
1635 else if ((newpde & PG_G) == 0)
1637 * Promotion: flush every 4KB page mapping from the TLB
1638 * because there are too many to flush individually.
1643 * Promotion: flush every 4KB page mapping from the TLB,
1644 * including any global (PG_G) mappings.
1652 * For SMP, these functions have to use the IPI mechanism for coherence.
1654 * N.B.: Before calling any of the following TLB invalidation functions,
1655 * the calling processor must ensure that all stores updating a non-
1656 * kernel page table are globally performed. Otherwise, another
1657 * processor could cache an old, pre-update entry without being
1658 * invalidated. This can happen one of two ways: (1) The pmap becomes
1659 * active on another processor after its pm_active field is checked by
1660 * one of the following functions but before a store updating the page
1661 * table is globally performed. (2) The pmap becomes active on another
1662 * processor before its pm_active field is checked but due to
1663 * speculative loads one of the following functions stills reads the
1664 * pmap as inactive on the other processor.
1666 * The kernel page table is exempt because its pm_active field is
1667 * immutable. The kernel page table is always active on every
1672 * Interrupt the cpus that are executing in the guest context.
1673 * This will force the vcpu to exit and the cached EPT mappings
1674 * will be invalidated by the host before the next vmresume.
1676 static __inline void
1677 pmap_invalidate_ept(pmap_t pmap)
1682 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1683 ("pmap_invalidate_ept: absurd pm_active"));
1686 * The TLB mappings associated with a vcpu context are not
1687 * flushed each time a different vcpu is chosen to execute.
1689 * This is in contrast with a process's vtop mappings that
1690 * are flushed from the TLB on each context switch.
1692 * Therefore we need to do more than just a TLB shootdown on
1693 * the active cpus in 'pmap->pm_active'. To do this we keep
1694 * track of the number of invalidations performed on this pmap.
1696 * Each vcpu keeps a cache of this counter and compares it
1697 * just before a vmresume. If the counter is out-of-date an
1698 * invept will be done to flush stale mappings from the TLB.
1700 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1703 * Force the vcpu to exit and trap back into the hypervisor.
1705 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1706 ipi_selected(pmap->pm_active, ipinum);
1711 pmap_invalidate_cpu_mask(pmap_t pmap)
1714 return (pmap == kernel_pmap ? all_cpus : pmap->pm_active);
1718 pmap_invalidate_page_pcid(pmap_t pmap, vm_offset_t va,
1719 const bool invpcid_works1)
1721 struct invpcid_descr d;
1722 uint64_t kcr3, ucr3;
1726 cpuid = PCPU_GET(cpuid);
1727 if (pmap == PCPU_GET(curpmap)) {
1728 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1730 * Because pm_pcid is recalculated on a
1731 * context switch, we must disable switching.
1732 * Otherwise, we might use a stale value
1736 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1737 if (invpcid_works1) {
1738 d.pcid = pcid | PMAP_PCID_USER_PT;
1741 invpcid(&d, INVPCID_ADDR);
1743 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1744 ucr3 = pmap->pm_ucr3 | pcid |
1745 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1746 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1751 pmap->pm_pcids[cpuid].pm_gen = 0;
1755 pmap->pm_pcids[i].pm_gen = 0;
1759 * The fence is between stores to pm_gen and the read of the
1760 * pm_active mask. We need to ensure that it is impossible
1761 * for us to miss the bit update in pm_active and
1762 * simultaneously observe a non-zero pm_gen in
1763 * pmap_activate_sw(), otherwise TLB update is missed.
1764 * Without the fence, IA32 allows such an outcome. Note that
1765 * pm_active is updated by a locked operation, which provides
1766 * the reciprocal fence.
1768 atomic_thread_fence_seq_cst();
1772 pmap_invalidate_page_pcid_invpcid(pmap_t pmap, vm_offset_t va)
1775 pmap_invalidate_page_pcid(pmap, va, true);
1779 pmap_invalidate_page_pcid_noinvpcid(pmap_t pmap, vm_offset_t va)
1782 pmap_invalidate_page_pcid(pmap, va, false);
1786 pmap_invalidate_page_nopcid(pmap_t pmap, vm_offset_t va)
1790 DEFINE_IFUNC(static, void, pmap_invalidate_page_mode, (pmap_t, vm_offset_t),
1794 if (pmap_pcid_enabled)
1795 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid :
1796 pmap_invalidate_page_pcid_noinvpcid);
1797 return (pmap_invalidate_page_nopcid);
1801 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1804 if (pmap_type_guest(pmap)) {
1805 pmap_invalidate_ept(pmap);
1809 KASSERT(pmap->pm_type == PT_X86,
1810 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1813 if (pmap == kernel_pmap) {
1816 if (pmap == PCPU_GET(curpmap))
1818 pmap_invalidate_page_mode(pmap, va);
1820 smp_masked_invlpg(pmap_invalidate_cpu_mask(pmap), va, pmap);
1824 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1825 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1828 pmap_invalidate_range_pcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1829 const bool invpcid_works1)
1831 struct invpcid_descr d;
1832 uint64_t kcr3, ucr3;
1836 cpuid = PCPU_GET(cpuid);
1837 if (pmap == PCPU_GET(curpmap)) {
1838 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1840 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1841 if (invpcid_works1) {
1842 d.pcid = pcid | PMAP_PCID_USER_PT;
1845 for (; d.addr < eva; d.addr += PAGE_SIZE)
1846 invpcid(&d, INVPCID_ADDR);
1848 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1849 ucr3 = pmap->pm_ucr3 | pcid |
1850 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1851 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1856 pmap->pm_pcids[cpuid].pm_gen = 0;
1860 pmap->pm_pcids[i].pm_gen = 0;
1862 /* See the comment in pmap_invalidate_page_pcid(). */
1863 atomic_thread_fence_seq_cst();
1867 pmap_invalidate_range_pcid_invpcid(pmap_t pmap, vm_offset_t sva,
1871 pmap_invalidate_range_pcid(pmap, sva, eva, true);
1875 pmap_invalidate_range_pcid_noinvpcid(pmap_t pmap, vm_offset_t sva,
1879 pmap_invalidate_range_pcid(pmap, sva, eva, false);
1883 pmap_invalidate_range_nopcid(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1887 DEFINE_IFUNC(static, void, pmap_invalidate_range_mode, (pmap_t, vm_offset_t,
1888 vm_offset_t), static)
1891 if (pmap_pcid_enabled)
1892 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid :
1893 pmap_invalidate_range_pcid_noinvpcid);
1894 return (pmap_invalidate_range_nopcid);
1898 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1902 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1903 pmap_invalidate_all(pmap);
1907 if (pmap_type_guest(pmap)) {
1908 pmap_invalidate_ept(pmap);
1912 KASSERT(pmap->pm_type == PT_X86,
1913 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1916 if (pmap == kernel_pmap) {
1917 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1920 if (pmap == PCPU_GET(curpmap)) {
1921 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1924 pmap_invalidate_range_mode(pmap, sva, eva);
1926 smp_masked_invlpg_range(pmap_invalidate_cpu_mask(pmap), sva, eva, pmap);
1931 pmap_invalidate_all_pcid(pmap_t pmap, bool invpcid_works1)
1933 struct invpcid_descr d;
1934 uint64_t kcr3, ucr3;
1938 if (pmap == kernel_pmap) {
1939 if (invpcid_works1) {
1940 bzero(&d, sizeof(d));
1941 invpcid(&d, INVPCID_CTXGLOB);
1946 cpuid = PCPU_GET(cpuid);
1947 if (pmap == PCPU_GET(curpmap)) {
1949 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1950 if (invpcid_works1) {
1954 invpcid(&d, INVPCID_CTX);
1955 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1956 d.pcid |= PMAP_PCID_USER_PT;
1957 invpcid(&d, INVPCID_CTX);
1960 kcr3 = pmap->pm_cr3 | pcid;
1961 ucr3 = pmap->pm_ucr3;
1962 if (ucr3 != PMAP_NO_CR3) {
1963 ucr3 |= pcid | PMAP_PCID_USER_PT;
1964 pmap_pti_pcid_invalidate(ucr3, kcr3);
1971 pmap->pm_pcids[cpuid].pm_gen = 0;
1974 pmap->pm_pcids[i].pm_gen = 0;
1977 /* See the comment in pmap_invalidate_page_pcid(). */
1978 atomic_thread_fence_seq_cst();
1982 pmap_invalidate_all_pcid_invpcid(pmap_t pmap)
1985 pmap_invalidate_all_pcid(pmap, true);
1989 pmap_invalidate_all_pcid_noinvpcid(pmap_t pmap)
1992 pmap_invalidate_all_pcid(pmap, false);
1996 pmap_invalidate_all_nopcid(pmap_t pmap)
1999 if (pmap == kernel_pmap)
2001 else if (pmap == PCPU_GET(curpmap))
2005 DEFINE_IFUNC(static, void, pmap_invalidate_all_mode, (pmap_t), static)
2008 if (pmap_pcid_enabled)
2009 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid :
2010 pmap_invalidate_all_pcid_noinvpcid);
2011 return (pmap_invalidate_all_nopcid);
2015 pmap_invalidate_all(pmap_t pmap)
2018 if (pmap_type_guest(pmap)) {
2019 pmap_invalidate_ept(pmap);
2023 KASSERT(pmap->pm_type == PT_X86,
2024 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
2027 pmap_invalidate_all_mode(pmap);
2028 smp_masked_invltlb(pmap_invalidate_cpu_mask(pmap), pmap);
2033 pmap_invalidate_cache(void)
2043 cpuset_t invalidate; /* processors that invalidate their TLB */
2048 u_int store; /* processor that updates the PDE */
2052 pmap_update_pde_action(void *arg)
2054 struct pde_action *act = arg;
2056 if (act->store == PCPU_GET(cpuid))
2057 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
2061 pmap_update_pde_teardown(void *arg)
2063 struct pde_action *act = arg;
2065 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
2066 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
2070 * Change the page size for the specified virtual address in a way that
2071 * prevents any possibility of the TLB ever having two entries that map the
2072 * same virtual address using different page sizes. This is the recommended
2073 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
2074 * machine check exception for a TLB state that is improperly diagnosed as a
2078 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2080 struct pde_action act;
2081 cpuset_t active, other_cpus;
2085 cpuid = PCPU_GET(cpuid);
2086 other_cpus = all_cpus;
2087 CPU_CLR(cpuid, &other_cpus);
2088 if (pmap == kernel_pmap || pmap_type_guest(pmap))
2091 active = pmap->pm_active;
2093 if (CPU_OVERLAP(&active, &other_cpus)) {
2095 act.invalidate = active;
2099 act.newpde = newpde;
2100 CPU_SET(cpuid, &active);
2101 smp_rendezvous_cpus(active,
2102 smp_no_rendezvous_barrier, pmap_update_pde_action,
2103 pmap_update_pde_teardown, &act);
2105 pmap_update_pde_store(pmap, pde, newpde);
2106 if (CPU_ISSET(cpuid, &active))
2107 pmap_update_pde_invalidate(pmap, va, newpde);
2113 * Normal, non-SMP, invalidation functions.
2116 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
2118 struct invpcid_descr d;
2119 uint64_t kcr3, ucr3;
2122 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2126 KASSERT(pmap->pm_type == PT_X86,
2127 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2129 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2131 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2132 pmap->pm_ucr3 != PMAP_NO_CR3) {
2134 pcid = pmap->pm_pcids[0].pm_pcid;
2135 if (invpcid_works) {
2136 d.pcid = pcid | PMAP_PCID_USER_PT;
2139 invpcid(&d, INVPCID_ADDR);
2141 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
2142 ucr3 = pmap->pm_ucr3 | pcid |
2143 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2144 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
2148 } else if (pmap_pcid_enabled)
2149 pmap->pm_pcids[0].pm_gen = 0;
2153 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2155 struct invpcid_descr d;
2157 uint64_t kcr3, ucr3;
2159 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2163 KASSERT(pmap->pm_type == PT_X86,
2164 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2166 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2167 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2169 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2170 pmap->pm_ucr3 != PMAP_NO_CR3) {
2172 if (invpcid_works) {
2173 d.pcid = pmap->pm_pcids[0].pm_pcid |
2177 for (; d.addr < eva; d.addr += PAGE_SIZE)
2178 invpcid(&d, INVPCID_ADDR);
2180 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2181 pm_pcid | CR3_PCID_SAVE;
2182 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2183 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2184 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2188 } else if (pmap_pcid_enabled) {
2189 pmap->pm_pcids[0].pm_gen = 0;
2194 pmap_invalidate_all(pmap_t pmap)
2196 struct invpcid_descr d;
2197 uint64_t kcr3, ucr3;
2199 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2203 KASSERT(pmap->pm_type == PT_X86,
2204 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2206 if (pmap == kernel_pmap) {
2207 if (pmap_pcid_enabled && invpcid_works) {
2208 bzero(&d, sizeof(d));
2209 invpcid(&d, INVPCID_CTXGLOB);
2213 } else if (pmap == PCPU_GET(curpmap)) {
2214 if (pmap_pcid_enabled) {
2216 if (invpcid_works) {
2217 d.pcid = pmap->pm_pcids[0].pm_pcid;
2220 invpcid(&d, INVPCID_CTX);
2221 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2222 d.pcid |= PMAP_PCID_USER_PT;
2223 invpcid(&d, INVPCID_CTX);
2226 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2227 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2228 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2229 0].pm_pcid | PMAP_PCID_USER_PT;
2230 pmap_pti_pcid_invalidate(ucr3, kcr3);
2238 } else if (pmap_pcid_enabled) {
2239 pmap->pm_pcids[0].pm_gen = 0;
2244 pmap_invalidate_cache(void)
2251 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2254 pmap_update_pde_store(pmap, pde, newpde);
2255 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2256 pmap_update_pde_invalidate(pmap, va, newpde);
2258 pmap->pm_pcids[0].pm_gen = 0;
2263 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2267 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2268 * by a promotion that did not invalidate the 512 4KB page mappings
2269 * that might exist in the TLB. Consequently, at this point, the TLB
2270 * may hold both 4KB and 2MB page mappings for the address range [va,
2271 * va + NBPDR). Therefore, the entire range must be invalidated here.
2272 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2273 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2274 * single INVLPG suffices to invalidate the 2MB page mapping from the
2277 if ((pde & PG_PROMOTED) != 0)
2278 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2280 pmap_invalidate_page(pmap, va);
2283 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
2284 (vm_offset_t sva, vm_offset_t eva), static)
2287 if ((cpu_feature & CPUID_SS) != 0)
2288 return (pmap_invalidate_cache_range_selfsnoop);
2289 if ((cpu_feature & CPUID_CLFSH) != 0)
2290 return (pmap_force_invalidate_cache_range);
2291 return (pmap_invalidate_cache_range_all);
2294 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2297 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
2300 KASSERT((sva & PAGE_MASK) == 0,
2301 ("pmap_invalidate_cache_range: sva not page-aligned"));
2302 KASSERT((eva & PAGE_MASK) == 0,
2303 ("pmap_invalidate_cache_range: eva not page-aligned"));
2307 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
2310 pmap_invalidate_cache_range_check_align(sva, eva);
2314 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
2317 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2318 if (eva - sva >= PMAP_CLFLUSH_THRESHOLD) {
2320 * The supplied range is bigger than 2MB.
2321 * Globally invalidate cache.
2323 pmap_invalidate_cache();
2328 * XXX: Some CPUs fault, hang, or trash the local APIC
2329 * registers if we use CLFLUSH on the local APIC range. The
2330 * local APIC is always uncached, so we don't need to flush
2331 * for that range anyway.
2333 if (pmap_kextract(sva) == lapic_paddr)
2336 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
2338 * Do per-cache line flush. Use the sfence
2339 * instruction to insure that previous stores are
2340 * included in the write-back. The processor
2341 * propagates flush to other processors in the cache
2345 for (; sva < eva; sva += cpu_clflush_line_size)
2350 * Writes are ordered by CLFLUSH on Intel CPUs.
2352 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2354 for (; sva < eva; sva += cpu_clflush_line_size)
2356 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2362 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
2365 pmap_invalidate_cache_range_check_align(sva, eva);
2366 pmap_invalidate_cache();
2370 * Remove the specified set of pages from the data and instruction caches.
2372 * In contrast to pmap_invalidate_cache_range(), this function does not
2373 * rely on the CPU's self-snoop feature, because it is intended for use
2374 * when moving pages into a different cache domain.
2377 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2379 vm_offset_t daddr, eva;
2383 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2384 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2385 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2386 pmap_invalidate_cache();
2390 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2392 for (i = 0; i < count; i++) {
2393 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2394 eva = daddr + PAGE_SIZE;
2395 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2404 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2410 * Routine: pmap_extract
2412 * Extract the physical page address associated
2413 * with the given map/virtual_address pair.
2416 pmap_extract(pmap_t pmap, vm_offset_t va)
2420 pt_entry_t *pte, PG_V;
2424 PG_V = pmap_valid_bit(pmap);
2426 pdpe = pmap_pdpe(pmap, va);
2427 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2428 if ((*pdpe & PG_PS) != 0)
2429 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2431 pde = pmap_pdpe_to_pde(pdpe, va);
2432 if ((*pde & PG_V) != 0) {
2433 if ((*pde & PG_PS) != 0) {
2434 pa = (*pde & PG_PS_FRAME) |
2437 pte = pmap_pde_to_pte(pde, va);
2438 pa = (*pte & PG_FRAME) |
2449 * Routine: pmap_extract_and_hold
2451 * Atomically extract and hold the physical page
2452 * with the given pmap and virtual address pair
2453 * if that mapping permits the given protection.
2456 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2458 pd_entry_t pde, *pdep;
2459 pt_entry_t pte, PG_RW, PG_V;
2465 PG_RW = pmap_rw_bit(pmap);
2466 PG_V = pmap_valid_bit(pmap);
2469 pdep = pmap_pde(pmap, va);
2470 if (pdep != NULL && (pde = *pdep)) {
2472 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2473 if (vm_page_pa_tryrelock(pmap, (pde &
2474 PG_PS_FRAME) | (va & PDRMASK), &pa))
2476 m = PHYS_TO_VM_PAGE(pa);
2479 pte = *pmap_pde_to_pte(pdep, va);
2481 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2482 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2485 m = PHYS_TO_VM_PAGE(pa);
2497 pmap_kextract(vm_offset_t va)
2502 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2503 pa = DMAP_TO_PHYS(va);
2507 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2510 * Beware of a concurrent promotion that changes the
2511 * PDE at this point! For example, vtopte() must not
2512 * be used to access the PTE because it would use the
2513 * new PDE. It is, however, safe to use the old PDE
2514 * because the page table page is preserved by the
2517 pa = *pmap_pde_to_pte(&pde, va);
2518 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2524 /***************************************************
2525 * Low level mapping routines.....
2526 ***************************************************/
2529 * Add a wired page to the kva.
2530 * Note: not SMP coherent.
2533 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2538 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2541 static __inline void
2542 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2548 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2549 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2553 * Remove a page from the kernel pagetables.
2554 * Note: not SMP coherent.
2557 pmap_kremove(vm_offset_t va)
2566 * Used to map a range of physical addresses into kernel
2567 * virtual address space.
2569 * The value passed in '*virt' is a suggested virtual address for
2570 * the mapping. Architectures which can support a direct-mapped
2571 * physical to virtual region can return the appropriate address
2572 * within that region, leaving '*virt' unchanged. Other
2573 * architectures should map the pages starting at '*virt' and
2574 * update '*virt' with the first usable address after the mapped
2578 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2580 return PHYS_TO_DMAP(start);
2585 * Add a list of wired pages to the kva
2586 * this routine is only used for temporary
2587 * kernel mappings that do not need to have
2588 * page modification or references recorded.
2589 * Note that old mappings are simply written
2590 * over. The page *must* be wired.
2591 * Note: SMP coherent. Uses a ranged shootdown IPI.
2594 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2596 pt_entry_t *endpte, oldpte, pa, *pte;
2602 endpte = pte + count;
2603 while (pte < endpte) {
2605 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2606 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2607 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2609 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2613 if (__predict_false((oldpte & X86_PG_V) != 0))
2614 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2619 * This routine tears out page mappings from the
2620 * kernel -- it is meant only for temporary mappings.
2621 * Note: SMP coherent. Uses a ranged shootdown IPI.
2624 pmap_qremove(vm_offset_t sva, int count)
2629 while (count-- > 0) {
2630 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2634 pmap_invalidate_range(kernel_pmap, sva, va);
2637 /***************************************************
2638 * Page table page management routines.....
2639 ***************************************************/
2641 * Schedule the specified unused page table page to be freed. Specifically,
2642 * add the page to the specified list of pages that will be released to the
2643 * physical memory manager after the TLB has been updated.
2645 static __inline void
2646 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2647 boolean_t set_PG_ZERO)
2651 m->flags |= PG_ZERO;
2653 m->flags &= ~PG_ZERO;
2654 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2658 * Inserts the specified page table page into the specified pmap's collection
2659 * of idle page table pages. Each of a pmap's page table pages is responsible
2660 * for mapping a distinct range of virtual addresses. The pmap's collection is
2661 * ordered by this virtual address range.
2664 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2667 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2668 return (vm_radix_insert(&pmap->pm_root, mpte));
2672 * Removes the page table page mapping the specified virtual address from the
2673 * specified pmap's collection of idle page table pages, and returns it.
2674 * Otherwise, returns NULL if there is no page table page corresponding to the
2675 * specified virtual address.
2677 static __inline vm_page_t
2678 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2681 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2682 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2686 * Decrements a page table page's wire count, which is used to record the
2687 * number of valid page table entries within the page. If the wire count
2688 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2689 * page table page was unmapped and FALSE otherwise.
2691 static inline boolean_t
2692 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2696 if (m->wire_count == 0) {
2697 _pmap_unwire_ptp(pmap, va, m, free);
2704 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2707 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2709 * unmap the page table page
2711 if (m->pindex >= (NUPDE + NUPDPE)) {
2714 pml4 = pmap_pml4e(pmap, va);
2716 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2717 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2720 } else if (m->pindex >= NUPDE) {
2723 pdp = pmap_pdpe(pmap, va);
2728 pd = pmap_pde(pmap, va);
2731 pmap_resident_count_dec(pmap, 1);
2732 if (m->pindex < NUPDE) {
2733 /* We just released a PT, unhold the matching PD */
2736 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2737 pmap_unwire_ptp(pmap, va, pdpg, free);
2739 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2740 /* We just released a PD, unhold the matching PDP */
2743 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2744 pmap_unwire_ptp(pmap, va, pdppg, free);
2748 * Put page on a list so that it is released after
2749 * *ALL* TLB shootdown is done
2751 pmap_add_delayed_free_list(m, free, TRUE);
2755 * After removing a page table entry, this routine is used to
2756 * conditionally free the page, and manage the hold/wire counts.
2759 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2760 struct spglist *free)
2764 if (va >= VM_MAXUSER_ADDRESS)
2766 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2767 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2768 return (pmap_unwire_ptp(pmap, va, mpte, free));
2772 pmap_pinit0(pmap_t pmap)
2776 PMAP_LOCK_INIT(pmap);
2777 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2778 pmap->pm_pml4u = NULL;
2779 pmap->pm_cr3 = KPML4phys;
2780 /* hack to keep pmap_pti_pcid_invalidate() alive */
2781 pmap->pm_ucr3 = PMAP_NO_CR3;
2782 pmap->pm_root.rt_root = 0;
2783 CPU_ZERO(&pmap->pm_active);
2784 TAILQ_INIT(&pmap->pm_pvchunk);
2785 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2786 pmap->pm_flags = pmap_flags;
2788 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
2789 pmap->pm_pcids[i].pm_gen = 1;
2791 pmap_activate_boot(pmap);
2795 pmap_pinit_pml4(vm_page_t pml4pg)
2797 pml4_entry_t *pm_pml4;
2800 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2802 /* Wire in kernel global address entries. */
2803 for (i = 0; i < NKPML4E; i++) {
2804 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2807 for (i = 0; i < ndmpdpphys; i++) {
2808 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2812 /* install self-referential address mapping entry(s) */
2813 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2814 X86_PG_A | X86_PG_M;
2818 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2820 pml4_entry_t *pm_pml4;
2823 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2824 for (i = 0; i < NPML4EPG; i++)
2825 pm_pml4[i] = pti_pml4[i];
2829 * Initialize a preallocated and zeroed pmap structure,
2830 * such as one in a vmspace structure.
2833 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2835 vm_page_t pml4pg, pml4pgu;
2836 vm_paddr_t pml4phys;
2840 * allocate the page directory page
2842 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2843 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2845 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2846 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2848 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2849 pmap->pm_pcids[i].pm_gen = 0;
2851 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2852 pmap->pm_ucr3 = PMAP_NO_CR3;
2853 pmap->pm_pml4u = NULL;
2855 pmap->pm_type = pm_type;
2856 if ((pml4pg->flags & PG_ZERO) == 0)
2857 pagezero(pmap->pm_pml4);
2860 * Do not install the host kernel mappings in the nested page
2861 * tables. These mappings are meaningless in the guest physical
2863 * Install minimal kernel mappings in PTI case.
2865 if (pm_type == PT_X86) {
2866 pmap->pm_cr3 = pml4phys;
2867 pmap_pinit_pml4(pml4pg);
2869 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2870 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2871 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2872 VM_PAGE_TO_PHYS(pml4pgu));
2873 pmap_pinit_pml4_pti(pml4pgu);
2874 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2878 pmap->pm_root.rt_root = 0;
2879 CPU_ZERO(&pmap->pm_active);
2880 TAILQ_INIT(&pmap->pm_pvchunk);
2881 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2882 pmap->pm_flags = flags;
2883 pmap->pm_eptgen = 0;
2889 pmap_pinit(pmap_t pmap)
2892 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2896 * This routine is called if the desired page table page does not exist.
2898 * If page table page allocation fails, this routine may sleep before
2899 * returning NULL. It sleeps only if a lock pointer was given.
2901 * Note: If a page allocation fails at page table level two or three,
2902 * one or two pages may be held during the wait, only to be released
2903 * afterwards. This conservative approach is easily argued to avoid
2907 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2909 vm_page_t m, pdppg, pdpg;
2910 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2912 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2914 PG_A = pmap_accessed_bit(pmap);
2915 PG_M = pmap_modified_bit(pmap);
2916 PG_V = pmap_valid_bit(pmap);
2917 PG_RW = pmap_rw_bit(pmap);
2920 * Allocate a page table page.
2922 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2923 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2924 if (lockp != NULL) {
2925 RELEASE_PV_LIST_LOCK(lockp);
2927 PMAP_ASSERT_NOT_IN_DI();
2933 * Indicate the need to retry. While waiting, the page table
2934 * page may have been allocated.
2938 if ((m->flags & PG_ZERO) == 0)
2942 * Map the pagetable page into the process address space, if
2943 * it isn't already there.
2946 if (ptepindex >= (NUPDE + NUPDPE)) {
2947 pml4_entry_t *pml4, *pml4u;
2948 vm_pindex_t pml4index;
2950 /* Wire up a new PDPE page */
2951 pml4index = ptepindex - (NUPDE + NUPDPE);
2952 pml4 = &pmap->pm_pml4[pml4index];
2953 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2954 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2956 * PTI: Make all user-space mappings in the
2957 * kernel-mode page table no-execute so that
2958 * we detect any programming errors that leave
2959 * the kernel-mode page table active on return
2962 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2965 pml4u = &pmap->pm_pml4u[pml4index];
2966 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2970 } else if (ptepindex >= NUPDE) {
2971 vm_pindex_t pml4index;
2972 vm_pindex_t pdpindex;
2976 /* Wire up a new PDE page */
2977 pdpindex = ptepindex - NUPDE;
2978 pml4index = pdpindex >> NPML4EPGSHIFT;
2980 pml4 = &pmap->pm_pml4[pml4index];
2981 if ((*pml4 & PG_V) == 0) {
2982 /* Have to allocate a new pdp, recurse */
2983 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2985 vm_page_unwire_noq(m);
2986 vm_page_free_zero(m);
2990 /* Add reference to pdp page */
2991 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2992 pdppg->wire_count++;
2994 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2996 /* Now find the pdp page */
2997 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2998 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
3001 vm_pindex_t pml4index;
3002 vm_pindex_t pdpindex;
3007 /* Wire up a new PTE page */
3008 pdpindex = ptepindex >> NPDPEPGSHIFT;
3009 pml4index = pdpindex >> NPML4EPGSHIFT;
3011 /* First, find the pdp and check that its valid. */
3012 pml4 = &pmap->pm_pml4[pml4index];
3013 if ((*pml4 & PG_V) == 0) {
3014 /* Have to allocate a new pd, recurse */
3015 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
3017 vm_page_unwire_noq(m);
3018 vm_page_free_zero(m);
3021 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
3022 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
3024 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
3025 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
3026 if ((*pdp & PG_V) == 0) {
3027 /* Have to allocate a new pd, recurse */
3028 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
3030 vm_page_unwire_noq(m);
3031 vm_page_free_zero(m);
3035 /* Add reference to the pd page */
3036 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
3040 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
3042 /* Now we know where the page directory page is */
3043 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
3044 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
3047 pmap_resident_count_inc(pmap, 1);
3053 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
3055 vm_pindex_t pdpindex, ptepindex;
3056 pdp_entry_t *pdpe, PG_V;
3059 PG_V = pmap_valid_bit(pmap);
3062 pdpe = pmap_pdpe(pmap, va);
3063 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3064 /* Add a reference to the pd page. */
3065 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
3068 /* Allocate a pd page. */
3069 ptepindex = pmap_pde_pindex(va);
3070 pdpindex = ptepindex >> NPDPEPGSHIFT;
3071 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
3072 if (pdpg == NULL && lockp != NULL)
3079 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
3081 vm_pindex_t ptepindex;
3082 pd_entry_t *pd, PG_V;
3085 PG_V = pmap_valid_bit(pmap);
3088 * Calculate pagetable page index
3090 ptepindex = pmap_pde_pindex(va);
3093 * Get the page directory entry
3095 pd = pmap_pde(pmap, va);
3098 * This supports switching from a 2MB page to a
3101 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
3102 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
3104 * Invalidation of the 2MB page mapping may have caused
3105 * the deallocation of the underlying PD page.
3112 * If the page table page is mapped, we just increment the
3113 * hold count, and activate it.
3115 if (pd != NULL && (*pd & PG_V) != 0) {
3116 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
3120 * Here if the pte page isn't mapped, or if it has been
3123 m = _pmap_allocpte(pmap, ptepindex, lockp);
3124 if (m == NULL && lockp != NULL)
3131 /***************************************************
3132 * Pmap allocation/deallocation routines.
3133 ***************************************************/
3136 * Release any resources held by the given physical map.
3137 * Called when a pmap initialized by pmap_pinit is being released.
3138 * Should only be called if the map contains no valid mappings.
3141 pmap_release(pmap_t pmap)
3146 KASSERT(pmap->pm_stats.resident_count == 0,
3147 ("pmap_release: pmap resident count %ld != 0",
3148 pmap->pm_stats.resident_count));
3149 KASSERT(vm_radix_is_empty(&pmap->pm_root),
3150 ("pmap_release: pmap has reserved page table page(s)"));
3151 KASSERT(CPU_EMPTY(&pmap->pm_active),
3152 ("releasing active pmap %p", pmap));
3154 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
3156 for (i = 0; i < NKPML4E; i++) /* KVA */
3157 pmap->pm_pml4[KPML4BASE + i] = 0;
3158 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3159 pmap->pm_pml4[DMPML4I + i] = 0;
3160 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
3162 vm_page_unwire_noq(m);
3163 vm_page_free_zero(m);
3165 if (pmap->pm_pml4u != NULL) {
3166 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3167 vm_page_unwire_noq(m);
3173 kvm_size(SYSCTL_HANDLER_ARGS)
3175 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3177 return sysctl_handle_long(oidp, &ksize, 0, req);
3179 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
3180 0, 0, kvm_size, "LU", "Size of KVM");
3183 kvm_free(SYSCTL_HANDLER_ARGS)
3185 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3187 return sysctl_handle_long(oidp, &kfree, 0, req);
3189 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
3190 0, 0, kvm_free, "LU", "Amount of KVM free");
3193 * grow the number of kernel page table entries, if needed
3196 pmap_growkernel(vm_offset_t addr)
3200 pd_entry_t *pde, newpdir;
3203 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3206 * Return if "addr" is within the range of kernel page table pages
3207 * that were preallocated during pmap bootstrap. Moreover, leave
3208 * "kernel_vm_end" and the kernel page table as they were.
3210 * The correctness of this action is based on the following
3211 * argument: vm_map_insert() allocates contiguous ranges of the
3212 * kernel virtual address space. It calls this function if a range
3213 * ends after "kernel_vm_end". If the kernel is mapped between
3214 * "kernel_vm_end" and "addr", then the range cannot begin at
3215 * "kernel_vm_end". In fact, its beginning address cannot be less
3216 * than the kernel. Thus, there is no immediate need to allocate
3217 * any new kernel page table pages between "kernel_vm_end" and
3220 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3223 addr = roundup2(addr, NBPDR);
3224 if (addr - 1 >= vm_map_max(kernel_map))
3225 addr = vm_map_max(kernel_map);
3226 while (kernel_vm_end < addr) {
3227 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3228 if ((*pdpe & X86_PG_V) == 0) {
3229 /* We need a new PDP entry */
3230 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3231 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3232 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3234 panic("pmap_growkernel: no memory to grow kernel");
3235 if ((nkpg->flags & PG_ZERO) == 0)
3236 pmap_zero_page(nkpg);
3237 paddr = VM_PAGE_TO_PHYS(nkpg);
3238 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3239 X86_PG_A | X86_PG_M);
3240 continue; /* try again */
3242 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3243 if ((*pde & X86_PG_V) != 0) {
3244 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3245 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3246 kernel_vm_end = vm_map_max(kernel_map);
3252 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3253 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3256 panic("pmap_growkernel: no memory to grow kernel");
3257 if ((nkpg->flags & PG_ZERO) == 0)
3258 pmap_zero_page(nkpg);
3259 paddr = VM_PAGE_TO_PHYS(nkpg);
3260 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3261 pde_store(pde, newpdir);
3263 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3264 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3265 kernel_vm_end = vm_map_max(kernel_map);
3272 /***************************************************
3273 * page management routines.
3274 ***************************************************/
3276 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3277 CTASSERT(_NPCM == 3);
3278 CTASSERT(_NPCPV == 168);
3280 static __inline struct pv_chunk *
3281 pv_to_chunk(pv_entry_t pv)
3284 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3287 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3289 #define PC_FREE0 0xfffffffffffffffful
3290 #define PC_FREE1 0xfffffffffffffffful
3291 #define PC_FREE2 0x000000fffffffffful
3293 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3296 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3298 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3299 "Current number of pv entry chunks");
3300 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3301 "Current number of pv entry chunks allocated");
3302 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3303 "Current number of pv entry chunks frees");
3304 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3305 "Number of times tried to get a chunk page but failed.");
3307 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3308 static int pv_entry_spare;
3310 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3311 "Current number of pv entry frees");
3312 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3313 "Current number of pv entry allocs");
3314 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3315 "Current number of pv entries");
3316 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3317 "Current number of spare pv entries");
3321 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3326 pmap_invalidate_all(pmap);
3327 if (pmap != locked_pmap)
3330 pmap_delayed_invl_finished();
3334 * We are in a serious low memory condition. Resort to
3335 * drastic measures to free some pages so we can allocate
3336 * another pv entry chunk.
3338 * Returns NULL if PV entries were reclaimed from the specified pmap.
3340 * We do not, however, unmap 2mpages because subsequent accesses will
3341 * allocate per-page pv entries until repromotion occurs, thereby
3342 * exacerbating the shortage of free pv entries.
3345 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3347 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3348 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3349 struct md_page *pvh;
3351 pmap_t next_pmap, pmap;
3352 pt_entry_t *pte, tpte;
3353 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3357 struct spglist free;
3359 int bit, field, freed;
3361 static int active_reclaims = 0;
3363 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3364 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3367 PG_G = PG_A = PG_M = PG_RW = 0;
3369 bzero(&pc_marker_b, sizeof(pc_marker_b));
3370 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3371 pc_marker = (struct pv_chunk *)&pc_marker_b;
3372 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3375 * A delayed invalidation block should already be active if
3376 * pmap_advise() or pmap_remove() called this function by way
3377 * of pmap_demote_pde_locked().
3379 start_di = pmap_not_in_di();
3381 mtx_lock(&pv_chunks_mutex);
3383 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3384 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3385 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3386 SLIST_EMPTY(&free)) {
3387 next_pmap = pc->pc_pmap;
3388 if (next_pmap == NULL) {
3390 * The next chunk is a marker. However, it is
3391 * not our marker, so active_reclaims must be
3392 * > 1. Consequently, the next_chunk code
3393 * will not rotate the pv_chunks list.
3397 mtx_unlock(&pv_chunks_mutex);
3400 * A pv_chunk can only be removed from the pc_lru list
3401 * when both pc_chunks_mutex is owned and the
3402 * corresponding pmap is locked.
3404 if (pmap != next_pmap) {
3405 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3408 /* Avoid deadlock and lock recursion. */
3409 if (pmap > locked_pmap) {
3410 RELEASE_PV_LIST_LOCK(lockp);
3413 pmap_delayed_invl_started();
3414 mtx_lock(&pv_chunks_mutex);
3416 } else if (pmap != locked_pmap) {
3417 if (PMAP_TRYLOCK(pmap)) {
3419 pmap_delayed_invl_started();
3420 mtx_lock(&pv_chunks_mutex);
3423 pmap = NULL; /* pmap is not locked */
3424 mtx_lock(&pv_chunks_mutex);
3425 pc = TAILQ_NEXT(pc_marker, pc_lru);
3427 pc->pc_pmap != next_pmap)
3431 } else if (start_di)
3432 pmap_delayed_invl_started();
3433 PG_G = pmap_global_bit(pmap);
3434 PG_A = pmap_accessed_bit(pmap);
3435 PG_M = pmap_modified_bit(pmap);
3436 PG_RW = pmap_rw_bit(pmap);
3440 * Destroy every non-wired, 4 KB page mapping in the chunk.
3443 for (field = 0; field < _NPCM; field++) {
3444 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3445 inuse != 0; inuse &= ~(1UL << bit)) {
3447 pv = &pc->pc_pventry[field * 64 + bit];
3449 pde = pmap_pde(pmap, va);
3450 if ((*pde & PG_PS) != 0)
3452 pte = pmap_pde_to_pte(pde, va);
3453 if ((*pte & PG_W) != 0)
3455 tpte = pte_load_clear(pte);
3456 if ((tpte & PG_G) != 0)
3457 pmap_invalidate_page(pmap, va);
3458 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3459 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3461 if ((tpte & PG_A) != 0)
3462 vm_page_aflag_set(m, PGA_REFERENCED);
3463 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3464 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3466 if (TAILQ_EMPTY(&m->md.pv_list) &&
3467 (m->flags & PG_FICTITIOUS) == 0) {
3468 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3469 if (TAILQ_EMPTY(&pvh->pv_list)) {
3470 vm_page_aflag_clear(m,
3474 pmap_delayed_invl_page(m);
3475 pc->pc_map[field] |= 1UL << bit;
3476 pmap_unuse_pt(pmap, va, *pde, &free);
3481 mtx_lock(&pv_chunks_mutex);
3484 /* Every freed mapping is for a 4 KB page. */
3485 pmap_resident_count_dec(pmap, freed);
3486 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3487 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3488 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3489 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3490 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3491 pc->pc_map[2] == PC_FREE2) {
3492 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3493 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3494 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3495 /* Entire chunk is free; return it. */
3496 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3497 dump_drop_page(m_pc->phys_addr);
3498 mtx_lock(&pv_chunks_mutex);
3499 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3502 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3503 mtx_lock(&pv_chunks_mutex);
3504 /* One freed pv entry in locked_pmap is sufficient. */
3505 if (pmap == locked_pmap)
3508 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3509 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3510 if (active_reclaims == 1 && pmap != NULL) {
3512 * Rotate the pv chunks list so that we do not
3513 * scan the same pv chunks that could not be
3514 * freed (because they contained a wired
3515 * and/or superpage mapping) on every
3516 * invocation of reclaim_pv_chunk().
3518 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3519 MPASS(pc->pc_pmap != NULL);
3520 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3521 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3525 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3526 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3528 mtx_unlock(&pv_chunks_mutex);
3529 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3530 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3531 m_pc = SLIST_FIRST(&free);
3532 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3533 /* Recycle a freed page table page. */
3534 m_pc->wire_count = 1;
3536 vm_page_free_pages_toq(&free, true);
3541 * free the pv_entry back to the free list
3544 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3546 struct pv_chunk *pc;
3547 int idx, field, bit;
3549 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3550 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3551 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3552 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3553 pc = pv_to_chunk(pv);
3554 idx = pv - &pc->pc_pventry[0];
3557 pc->pc_map[field] |= 1ul << bit;
3558 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3559 pc->pc_map[2] != PC_FREE2) {
3560 /* 98% of the time, pc is already at the head of the list. */
3561 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3562 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3563 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3567 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3572 free_pv_chunk(struct pv_chunk *pc)
3576 mtx_lock(&pv_chunks_mutex);
3577 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3578 mtx_unlock(&pv_chunks_mutex);
3579 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3580 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3581 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3582 /* entire chunk is free, return it */
3583 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3584 dump_drop_page(m->phys_addr);
3585 vm_page_unwire(m, PQ_NONE);
3590 * Returns a new PV entry, allocating a new PV chunk from the system when
3591 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3592 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3595 * The given PV list lock may be released.
3598 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3602 struct pv_chunk *pc;
3605 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3606 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3608 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3610 for (field = 0; field < _NPCM; field++) {
3611 if (pc->pc_map[field]) {
3612 bit = bsfq(pc->pc_map[field]);
3616 if (field < _NPCM) {
3617 pv = &pc->pc_pventry[field * 64 + bit];
3618 pc->pc_map[field] &= ~(1ul << bit);
3619 /* If this was the last item, move it to tail */
3620 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3621 pc->pc_map[2] == 0) {
3622 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3623 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3626 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3627 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3631 /* No free items, allocate another chunk */
3632 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3635 if (lockp == NULL) {
3636 PV_STAT(pc_chunk_tryfail++);
3639 m = reclaim_pv_chunk(pmap, lockp);
3643 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3644 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3645 dump_add_page(m->phys_addr);
3646 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3648 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3649 pc->pc_map[1] = PC_FREE1;
3650 pc->pc_map[2] = PC_FREE2;
3651 mtx_lock(&pv_chunks_mutex);
3652 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3653 mtx_unlock(&pv_chunks_mutex);
3654 pv = &pc->pc_pventry[0];
3655 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3656 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3657 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3662 * Returns the number of one bits within the given PV chunk map.
3664 * The erratas for Intel processors state that "POPCNT Instruction May
3665 * Take Longer to Execute Than Expected". It is believed that the
3666 * issue is the spurious dependency on the destination register.
3667 * Provide a hint to the register rename logic that the destination
3668 * value is overwritten, by clearing it, as suggested in the
3669 * optimization manual. It should be cheap for unaffected processors
3672 * Reference numbers for erratas are
3673 * 4th Gen Core: HSD146
3674 * 5th Gen Core: BDM85
3675 * 6th Gen Core: SKL029
3678 popcnt_pc_map_pq(uint64_t *map)
3682 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3683 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3684 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3685 : "=&r" (result), "=&r" (tmp)
3686 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3691 * Ensure that the number of spare PV entries in the specified pmap meets or
3692 * exceeds the given count, "needed".
3694 * The given PV list lock may be released.
3697 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3699 struct pch new_tail;
3700 struct pv_chunk *pc;
3705 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3706 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3709 * Newly allocated PV chunks must be stored in a private list until
3710 * the required number of PV chunks have been allocated. Otherwise,
3711 * reclaim_pv_chunk() could recycle one of these chunks. In
3712 * contrast, these chunks must be added to the pmap upon allocation.
3714 TAILQ_INIT(&new_tail);
3717 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3719 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3720 bit_count((bitstr_t *)pc->pc_map, 0,
3721 sizeof(pc->pc_map) * NBBY, &free);
3724 free = popcnt_pc_map_pq(pc->pc_map);
3728 if (avail >= needed)
3731 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3732 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3735 m = reclaim_pv_chunk(pmap, lockp);
3740 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3741 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3742 dump_add_page(m->phys_addr);
3743 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3745 pc->pc_map[0] = PC_FREE0;
3746 pc->pc_map[1] = PC_FREE1;
3747 pc->pc_map[2] = PC_FREE2;
3748 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3749 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3750 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3753 * The reclaim might have freed a chunk from the current pmap.
3754 * If that chunk contained available entries, we need to
3755 * re-count the number of available entries.
3760 if (!TAILQ_EMPTY(&new_tail)) {
3761 mtx_lock(&pv_chunks_mutex);
3762 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3763 mtx_unlock(&pv_chunks_mutex);
3768 * First find and then remove the pv entry for the specified pmap and virtual
3769 * address from the specified pv list. Returns the pv entry if found and NULL
3770 * otherwise. This operation can be performed on pv lists for either 4KB or
3771 * 2MB page mappings.
3773 static __inline pv_entry_t
3774 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3778 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3779 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3780 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3789 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3790 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3791 * entries for each of the 4KB page mappings.
3794 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3795 struct rwlock **lockp)
3797 struct md_page *pvh;
3798 struct pv_chunk *pc;
3800 vm_offset_t va_last;
3804 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3805 KASSERT((pa & PDRMASK) == 0,
3806 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3807 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3810 * Transfer the 2mpage's pv entry for this mapping to the first
3811 * page's pv list. Once this transfer begins, the pv list lock
3812 * must not be released until the last pv entry is reinstantiated.
3814 pvh = pa_to_pvh(pa);
3815 va = trunc_2mpage(va);
3816 pv = pmap_pvh_remove(pvh, pmap, va);
3817 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3818 m = PHYS_TO_VM_PAGE(pa);
3819 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3821 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3822 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3823 va_last = va + NBPDR - PAGE_SIZE;
3825 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3826 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3827 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3828 for (field = 0; field < _NPCM; field++) {
3829 while (pc->pc_map[field]) {
3830 bit = bsfq(pc->pc_map[field]);
3831 pc->pc_map[field] &= ~(1ul << bit);
3832 pv = &pc->pc_pventry[field * 64 + bit];
3836 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3837 ("pmap_pv_demote_pde: page %p is not managed", m));
3838 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3844 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3845 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3848 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3849 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3850 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3852 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3853 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3856 #if VM_NRESERVLEVEL > 0
3858 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3859 * replace the many pv entries for the 4KB page mappings by a single pv entry
3860 * for the 2MB page mapping.
3863 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3864 struct rwlock **lockp)
3866 struct md_page *pvh;
3868 vm_offset_t va_last;
3871 KASSERT((pa & PDRMASK) == 0,
3872 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3873 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3876 * Transfer the first page's pv entry for this mapping to the 2mpage's
3877 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3878 * a transfer avoids the possibility that get_pv_entry() calls
3879 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3880 * mappings that is being promoted.
3882 m = PHYS_TO_VM_PAGE(pa);
3883 va = trunc_2mpage(va);
3884 pv = pmap_pvh_remove(&m->md, pmap, va);
3885 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3886 pvh = pa_to_pvh(pa);
3887 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3889 /* Free the remaining NPTEPG - 1 pv entries. */
3890 va_last = va + NBPDR - PAGE_SIZE;
3894 pmap_pvh_free(&m->md, pmap, va);
3895 } while (va < va_last);
3897 #endif /* VM_NRESERVLEVEL > 0 */
3900 * First find and then destroy the pv entry for the specified pmap and virtual
3901 * address. This operation can be performed on pv lists for either 4KB or 2MB
3905 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3909 pv = pmap_pvh_remove(pvh, pmap, va);
3910 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3911 free_pv_entry(pmap, pv);
3915 * Conditionally create the PV entry for a 4KB page mapping if the required
3916 * memory can be allocated without resorting to reclamation.
3919 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3920 struct rwlock **lockp)
3924 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3925 /* Pass NULL instead of the lock pointer to disable reclamation. */
3926 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3928 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3929 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3937 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3938 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3939 * false if the PV entry cannot be allocated without resorting to reclamation.
3942 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3943 struct rwlock **lockp)
3945 struct md_page *pvh;
3949 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3950 /* Pass NULL instead of the lock pointer to disable reclamation. */
3951 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3952 NULL : lockp)) == NULL)
3955 pa = pde & PG_PS_FRAME;
3956 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3957 pvh = pa_to_pvh(pa);
3958 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3964 * Fills a page table page with mappings to consecutive physical pages.
3967 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3971 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3973 newpte += PAGE_SIZE;
3978 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3979 * mapping is invalidated.
3982 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3984 struct rwlock *lock;
3988 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3995 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3996 struct rwlock **lockp)
3998 pd_entry_t newpde, oldpde;
3999 pt_entry_t *firstpte, newpte;
4000 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
4003 struct spglist free;
4007 PG_G = pmap_global_bit(pmap);
4008 PG_A = pmap_accessed_bit(pmap);
4009 PG_M = pmap_modified_bit(pmap);
4010 PG_RW = pmap_rw_bit(pmap);
4011 PG_V = pmap_valid_bit(pmap);
4012 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4014 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4016 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
4017 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
4018 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
4020 KASSERT((oldpde & PG_W) == 0,
4021 ("pmap_demote_pde: page table page for a wired mapping"
4025 * Invalidate the 2MB page mapping and return "failure" if the
4026 * mapping was never accessed or the allocation of the new
4027 * page table page fails. If the 2MB page mapping belongs to
4028 * the direct map region of the kernel's address space, then
4029 * the page allocation request specifies the highest possible
4030 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
4031 * normal. Page table pages are preallocated for every other
4032 * part of the kernel address space, so the direct map region
4033 * is the only part of the kernel address space that must be
4036 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
4037 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
4038 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
4039 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
4041 sva = trunc_2mpage(va);
4042 pmap_remove_pde(pmap, pde, sva, &free, lockp);
4043 if ((oldpde & PG_G) == 0)
4044 pmap_invalidate_pde_page(pmap, sva, oldpde);
4045 vm_page_free_pages_toq(&free, true);
4046 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
4047 " in pmap %p", va, pmap);
4050 if (va < VM_MAXUSER_ADDRESS)
4051 pmap_resident_count_inc(pmap, 1);
4053 mptepa = VM_PAGE_TO_PHYS(mpte);
4054 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
4055 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
4056 KASSERT((oldpde & PG_A) != 0,
4057 ("pmap_demote_pde: oldpde is missing PG_A"));
4058 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
4059 ("pmap_demote_pde: oldpde is missing PG_M"));
4060 newpte = oldpde & ~PG_PS;
4061 newpte = pmap_swap_pat(pmap, newpte);
4064 * If the page table page is new, initialize it.
4066 if (mpte->wire_count == 1) {
4067 mpte->wire_count = NPTEPG;
4068 pmap_fill_ptp(firstpte, newpte);
4070 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
4071 ("pmap_demote_pde: firstpte and newpte map different physical"
4075 * If the mapping has changed attributes, update the page table
4078 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
4079 pmap_fill_ptp(firstpte, newpte);
4082 * The spare PV entries must be reserved prior to demoting the
4083 * mapping, that is, prior to changing the PDE. Otherwise, the state
4084 * of the PDE and the PV lists will be inconsistent, which can result
4085 * in reclaim_pv_chunk() attempting to remove a PV entry from the
4086 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
4087 * PV entry for the 2MB page mapping that is being demoted.
4089 if ((oldpde & PG_MANAGED) != 0)
4090 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
4093 * Demote the mapping. This pmap is locked. The old PDE has
4094 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
4095 * set. Thus, there is no danger of a race with another
4096 * processor changing the setting of PG_A and/or PG_M between
4097 * the read above and the store below.
4099 if (workaround_erratum383)
4100 pmap_update_pde(pmap, va, pde, newpde);
4102 pde_store(pde, newpde);
4105 * Invalidate a stale recursive mapping of the page table page.
4107 if (va >= VM_MAXUSER_ADDRESS)
4108 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
4111 * Demote the PV entry.
4113 if ((oldpde & PG_MANAGED) != 0)
4114 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
4116 atomic_add_long(&pmap_pde_demotions, 1);
4117 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
4118 " in pmap %p", va, pmap);
4123 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
4126 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
4132 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
4133 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4134 mpte = pmap_remove_pt_page(pmap, va);
4136 panic("pmap_remove_kernel_pde: Missing pt page.");
4138 mptepa = VM_PAGE_TO_PHYS(mpte);
4139 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
4142 * Initialize the page table page.
4144 pagezero((void *)PHYS_TO_DMAP(mptepa));
4147 * Demote the mapping.
4149 if (workaround_erratum383)
4150 pmap_update_pde(pmap, va, pde, newpde);
4152 pde_store(pde, newpde);
4155 * Invalidate a stale recursive mapping of the page table page.
4157 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
4161 * pmap_remove_pde: do the things to unmap a superpage in a process
4164 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
4165 struct spglist *free, struct rwlock **lockp)
4167 struct md_page *pvh;
4169 vm_offset_t eva, va;
4171 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4173 PG_G = pmap_global_bit(pmap);
4174 PG_A = pmap_accessed_bit(pmap);
4175 PG_M = pmap_modified_bit(pmap);
4176 PG_RW = pmap_rw_bit(pmap);
4178 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4179 KASSERT((sva & PDRMASK) == 0,
4180 ("pmap_remove_pde: sva is not 2mpage aligned"));
4181 oldpde = pte_load_clear(pdq);
4183 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
4184 if ((oldpde & PG_G) != 0)
4185 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4186 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4187 if (oldpde & PG_MANAGED) {
4188 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4189 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4190 pmap_pvh_free(pvh, pmap, sva);
4192 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4193 va < eva; va += PAGE_SIZE, m++) {
4194 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4197 vm_page_aflag_set(m, PGA_REFERENCED);
4198 if (TAILQ_EMPTY(&m->md.pv_list) &&
4199 TAILQ_EMPTY(&pvh->pv_list))
4200 vm_page_aflag_clear(m, PGA_WRITEABLE);
4201 pmap_delayed_invl_page(m);
4204 if (pmap == kernel_pmap) {
4205 pmap_remove_kernel_pde(pmap, pdq, sva);
4207 mpte = pmap_remove_pt_page(pmap, sva);
4209 pmap_resident_count_dec(pmap, 1);
4210 KASSERT(mpte->wire_count == NPTEPG,
4211 ("pmap_remove_pde: pte page wire count error"));
4212 mpte->wire_count = 0;
4213 pmap_add_delayed_free_list(mpte, free, FALSE);
4216 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4220 * pmap_remove_pte: do the things to unmap a page in a process
4223 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4224 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4226 struct md_page *pvh;
4227 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4230 PG_A = pmap_accessed_bit(pmap);
4231 PG_M = pmap_modified_bit(pmap);
4232 PG_RW = pmap_rw_bit(pmap);
4234 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4235 oldpte = pte_load_clear(ptq);
4237 pmap->pm_stats.wired_count -= 1;
4238 pmap_resident_count_dec(pmap, 1);
4239 if (oldpte & PG_MANAGED) {
4240 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4241 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4244 vm_page_aflag_set(m, PGA_REFERENCED);
4245 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4246 pmap_pvh_free(&m->md, pmap, va);
4247 if (TAILQ_EMPTY(&m->md.pv_list) &&
4248 (m->flags & PG_FICTITIOUS) == 0) {
4249 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4250 if (TAILQ_EMPTY(&pvh->pv_list))
4251 vm_page_aflag_clear(m, PGA_WRITEABLE);
4253 pmap_delayed_invl_page(m);
4255 return (pmap_unuse_pt(pmap, va, ptepde, free));
4259 * Remove a single page from a process address space
4262 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4263 struct spglist *free)
4265 struct rwlock *lock;
4266 pt_entry_t *pte, PG_V;
4268 PG_V = pmap_valid_bit(pmap);
4269 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4270 if ((*pde & PG_V) == 0)
4272 pte = pmap_pde_to_pte(pde, va);
4273 if ((*pte & PG_V) == 0)
4276 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4279 pmap_invalidate_page(pmap, va);
4283 * Removes the specified range of addresses from the page table page.
4286 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4287 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4289 pt_entry_t PG_G, *pte;
4293 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4294 PG_G = pmap_global_bit(pmap);
4297 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4301 pmap_invalidate_range(pmap, va, sva);
4306 if ((*pte & PG_G) == 0)
4310 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4316 pmap_invalidate_range(pmap, va, sva);
4321 * Remove the given range of addresses from the specified map.
4323 * It is assumed that the start and end are properly
4324 * rounded to the page size.
4327 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4329 struct rwlock *lock;
4330 vm_offset_t va_next;
4331 pml4_entry_t *pml4e;
4333 pd_entry_t ptpaddr, *pde;
4334 pt_entry_t PG_G, PG_V;
4335 struct spglist free;
4338 PG_G = pmap_global_bit(pmap);
4339 PG_V = pmap_valid_bit(pmap);
4342 * Perform an unsynchronized read. This is, however, safe.
4344 if (pmap->pm_stats.resident_count == 0)
4350 pmap_delayed_invl_started();
4354 * special handling of removing one page. a very
4355 * common operation and easy to short circuit some
4358 if (sva + PAGE_SIZE == eva) {
4359 pde = pmap_pde(pmap, sva);
4360 if (pde && (*pde & PG_PS) == 0) {
4361 pmap_remove_page(pmap, sva, pde, &free);
4367 for (; sva < eva; sva = va_next) {
4369 if (pmap->pm_stats.resident_count == 0)
4372 pml4e = pmap_pml4e(pmap, sva);
4373 if ((*pml4e & PG_V) == 0) {
4374 va_next = (sva + NBPML4) & ~PML4MASK;
4380 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4381 if ((*pdpe & PG_V) == 0) {
4382 va_next = (sva + NBPDP) & ~PDPMASK;
4389 * Calculate index for next page table.
4391 va_next = (sva + NBPDR) & ~PDRMASK;
4395 pde = pmap_pdpe_to_pde(pdpe, sva);
4399 * Weed out invalid mappings.
4405 * Check for large page.
4407 if ((ptpaddr & PG_PS) != 0) {
4409 * Are we removing the entire large page? If not,
4410 * demote the mapping and fall through.
4412 if (sva + NBPDR == va_next && eva >= va_next) {
4414 * The TLB entry for a PG_G mapping is
4415 * invalidated by pmap_remove_pde().
4417 if ((ptpaddr & PG_G) == 0)
4419 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4421 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4423 /* The large page mapping was destroyed. */
4430 * Limit our scan to either the end of the va represented
4431 * by the current page table page, or to the end of the
4432 * range being removed.
4437 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4444 pmap_invalidate_all(pmap);
4446 pmap_delayed_invl_finished();
4447 vm_page_free_pages_toq(&free, true);
4451 * Routine: pmap_remove_all
4453 * Removes this physical page from
4454 * all physical maps in which it resides.
4455 * Reflects back modify bits to the pager.
4458 * Original versions of this routine were very
4459 * inefficient because they iteratively called
4460 * pmap_remove (slow...)
4464 pmap_remove_all(vm_page_t m)
4466 struct md_page *pvh;
4469 struct rwlock *lock;
4470 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4473 struct spglist free;
4474 int pvh_gen, md_gen;
4476 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4477 ("pmap_remove_all: page %p is not managed", m));
4479 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4480 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4481 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4484 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4486 if (!PMAP_TRYLOCK(pmap)) {
4487 pvh_gen = pvh->pv_gen;
4491 if (pvh_gen != pvh->pv_gen) {
4498 pde = pmap_pde(pmap, va);
4499 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4502 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4504 if (!PMAP_TRYLOCK(pmap)) {
4505 pvh_gen = pvh->pv_gen;
4506 md_gen = m->md.pv_gen;
4510 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4516 PG_A = pmap_accessed_bit(pmap);
4517 PG_M = pmap_modified_bit(pmap);
4518 PG_RW = pmap_rw_bit(pmap);
4519 pmap_resident_count_dec(pmap, 1);
4520 pde = pmap_pde(pmap, pv->pv_va);
4521 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4522 " a 2mpage in page %p's pv list", m));
4523 pte = pmap_pde_to_pte(pde, pv->pv_va);
4524 tpte = pte_load_clear(pte);
4526 pmap->pm_stats.wired_count--;
4528 vm_page_aflag_set(m, PGA_REFERENCED);
4531 * Update the vm_page_t clean and reference bits.
4533 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4535 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4536 pmap_invalidate_page(pmap, pv->pv_va);
4537 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4539 free_pv_entry(pmap, pv);
4542 vm_page_aflag_clear(m, PGA_WRITEABLE);
4544 pmap_delayed_invl_wait(m);
4545 vm_page_free_pages_toq(&free, true);
4549 * pmap_protect_pde: do the things to protect a 2mpage in a process
4552 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4554 pd_entry_t newpde, oldpde;
4555 vm_offset_t eva, va;
4557 boolean_t anychanged;
4558 pt_entry_t PG_G, PG_M, PG_RW;
4560 PG_G = pmap_global_bit(pmap);
4561 PG_M = pmap_modified_bit(pmap);
4562 PG_RW = pmap_rw_bit(pmap);
4564 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4565 KASSERT((sva & PDRMASK) == 0,
4566 ("pmap_protect_pde: sva is not 2mpage aligned"));
4569 oldpde = newpde = *pde;
4570 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4571 (PG_MANAGED | PG_M | PG_RW)) {
4573 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4574 va < eva; va += PAGE_SIZE, m++)
4577 if ((prot & VM_PROT_WRITE) == 0)
4578 newpde &= ~(PG_RW | PG_M);
4579 if ((prot & VM_PROT_EXECUTE) == 0)
4581 if (newpde != oldpde) {
4583 * As an optimization to future operations on this PDE, clear
4584 * PG_PROMOTED. The impending invalidation will remove any
4585 * lingering 4KB page mappings from the TLB.
4587 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4589 if ((oldpde & PG_G) != 0)
4590 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4594 return (anychanged);
4598 * Set the physical protection on the
4599 * specified range of this map as requested.
4602 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4604 vm_offset_t va_next;
4605 pml4_entry_t *pml4e;
4607 pd_entry_t ptpaddr, *pde;
4608 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4609 boolean_t anychanged;
4611 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4612 if (prot == VM_PROT_NONE) {
4613 pmap_remove(pmap, sva, eva);
4617 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4618 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4621 PG_G = pmap_global_bit(pmap);
4622 PG_M = pmap_modified_bit(pmap);
4623 PG_V = pmap_valid_bit(pmap);
4624 PG_RW = pmap_rw_bit(pmap);
4628 * Although this function delays and batches the invalidation
4629 * of stale TLB entries, it does not need to call
4630 * pmap_delayed_invl_started() and
4631 * pmap_delayed_invl_finished(), because it does not
4632 * ordinarily destroy mappings. Stale TLB entries from
4633 * protection-only changes need only be invalidated before the
4634 * pmap lock is released, because protection-only changes do
4635 * not destroy PV entries. Even operations that iterate over
4636 * a physical page's PV list of mappings, like
4637 * pmap_remove_write(), acquire the pmap lock for each
4638 * mapping. Consequently, for protection-only changes, the
4639 * pmap lock suffices to synchronize both page table and TLB
4642 * This function only destroys a mapping if pmap_demote_pde()
4643 * fails. In that case, stale TLB entries are immediately
4648 for (; sva < eva; sva = va_next) {
4650 pml4e = pmap_pml4e(pmap, sva);
4651 if ((*pml4e & PG_V) == 0) {
4652 va_next = (sva + NBPML4) & ~PML4MASK;
4658 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4659 if ((*pdpe & PG_V) == 0) {
4660 va_next = (sva + NBPDP) & ~PDPMASK;
4666 va_next = (sva + NBPDR) & ~PDRMASK;
4670 pde = pmap_pdpe_to_pde(pdpe, sva);
4674 * Weed out invalid mappings.
4680 * Check for large page.
4682 if ((ptpaddr & PG_PS) != 0) {
4684 * Are we protecting the entire large page? If not,
4685 * demote the mapping and fall through.
4687 if (sva + NBPDR == va_next && eva >= va_next) {
4689 * The TLB entry for a PG_G mapping is
4690 * invalidated by pmap_protect_pde().
4692 if (pmap_protect_pde(pmap, pde, sva, prot))
4695 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4697 * The large page mapping was destroyed.
4706 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4708 pt_entry_t obits, pbits;
4712 obits = pbits = *pte;
4713 if ((pbits & PG_V) == 0)
4716 if ((prot & VM_PROT_WRITE) == 0) {
4717 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4718 (PG_MANAGED | PG_M | PG_RW)) {
4719 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4722 pbits &= ~(PG_RW | PG_M);
4724 if ((prot & VM_PROT_EXECUTE) == 0)
4727 if (pbits != obits) {
4728 if (!atomic_cmpset_long(pte, obits, pbits))
4731 pmap_invalidate_page(pmap, sva);
4738 pmap_invalidate_all(pmap);
4742 #if VM_NRESERVLEVEL > 0
4744 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4745 * single page table page (PTP) to a single 2MB page mapping. For promotion
4746 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4747 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4748 * identical characteristics.
4751 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4752 struct rwlock **lockp)
4755 pt_entry_t *firstpte, oldpte, pa, *pte;
4756 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4760 PG_A = pmap_accessed_bit(pmap);
4761 PG_G = pmap_global_bit(pmap);
4762 PG_M = pmap_modified_bit(pmap);
4763 PG_V = pmap_valid_bit(pmap);
4764 PG_RW = pmap_rw_bit(pmap);
4765 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4767 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4770 * Examine the first PTE in the specified PTP. Abort if this PTE is
4771 * either invalid, unused, or does not map the first 4KB physical page
4772 * within a 2MB page.
4774 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4777 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4778 atomic_add_long(&pmap_pde_p_failures, 1);
4779 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4780 " in pmap %p", va, pmap);
4783 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4785 * When PG_M is already clear, PG_RW can be cleared without
4786 * a TLB invalidation.
4788 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4794 * Examine each of the other PTEs in the specified PTP. Abort if this
4795 * PTE maps an unexpected 4KB physical page or does not have identical
4796 * characteristics to the first PTE.
4798 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4799 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4802 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4803 atomic_add_long(&pmap_pde_p_failures, 1);
4804 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4805 " in pmap %p", va, pmap);
4808 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4810 * When PG_M is already clear, PG_RW can be cleared
4811 * without a TLB invalidation.
4813 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4816 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4817 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4818 (va & ~PDRMASK), pmap);
4820 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4821 atomic_add_long(&pmap_pde_p_failures, 1);
4822 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4823 " in pmap %p", va, pmap);
4830 * Save the page table page in its current state until the PDE
4831 * mapping the superpage is demoted by pmap_demote_pde() or
4832 * destroyed by pmap_remove_pde().
4834 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4835 KASSERT(mpte >= vm_page_array &&
4836 mpte < &vm_page_array[vm_page_array_size],
4837 ("pmap_promote_pde: page table page is out of range"));
4838 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4839 ("pmap_promote_pde: page table page's pindex is wrong"));
4840 if (pmap_insert_pt_page(pmap, mpte)) {
4841 atomic_add_long(&pmap_pde_p_failures, 1);
4843 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4849 * Promote the pv entries.
4851 if ((newpde & PG_MANAGED) != 0)
4852 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4855 * Propagate the PAT index to its proper position.
4857 newpde = pmap_swap_pat(pmap, newpde);
4860 * Map the superpage.
4862 if (workaround_erratum383)
4863 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4865 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4867 atomic_add_long(&pmap_pde_promotions, 1);
4868 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4869 " in pmap %p", va, pmap);
4871 #endif /* VM_NRESERVLEVEL > 0 */
4874 * Insert the given physical page (p) at
4875 * the specified virtual address (v) in the
4876 * target physical map with the protection requested.
4878 * If specified, the page will be wired down, meaning
4879 * that the related pte can not be reclaimed.
4881 * NB: This is the only routine which MAY NOT lazy-evaluate
4882 * or lose information. That is, this routine must actually
4883 * insert this page into the given map NOW.
4885 * When destroying both a page table and PV entry, this function
4886 * performs the TLB invalidation before releasing the PV list
4887 * lock, so we do not need pmap_delayed_invl_page() calls here.
4890 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4891 u_int flags, int8_t psind)
4893 struct rwlock *lock;
4895 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4896 pt_entry_t newpte, origpte;
4903 PG_A = pmap_accessed_bit(pmap);
4904 PG_G = pmap_global_bit(pmap);
4905 PG_M = pmap_modified_bit(pmap);
4906 PG_V = pmap_valid_bit(pmap);
4907 PG_RW = pmap_rw_bit(pmap);
4909 va = trunc_page(va);
4910 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4911 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4912 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4914 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4915 va >= kmi.clean_eva,
4916 ("pmap_enter: managed mapping within the clean submap"));
4917 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4918 VM_OBJECT_ASSERT_LOCKED(m->object);
4919 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4920 ("pmap_enter: flags %u has reserved bits set", flags));
4921 pa = VM_PAGE_TO_PHYS(m);
4922 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4923 if ((flags & VM_PROT_WRITE) != 0)
4925 if ((prot & VM_PROT_WRITE) != 0)
4927 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4928 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4929 if ((prot & VM_PROT_EXECUTE) == 0)
4931 if ((flags & PMAP_ENTER_WIRED) != 0)
4933 if (va < VM_MAXUSER_ADDRESS)
4935 if (pmap == kernel_pmap)
4937 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4940 * Set modified bit gratuitously for writeable mappings if
4941 * the page is unmanaged. We do not want to take a fault
4942 * to do the dirty bit accounting for these mappings.
4944 if ((m->oflags & VPO_UNMANAGED) != 0) {
4945 if ((newpte & PG_RW) != 0)
4948 newpte |= PG_MANAGED;
4953 /* Assert the required virtual and physical alignment. */
4954 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4955 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4956 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4962 * In the case that a page table page is not
4963 * resident, we are creating it here.
4966 pde = pmap_pde(pmap, va);
4967 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4968 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4969 pte = pmap_pde_to_pte(pde, va);
4970 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4971 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4974 } else if (va < VM_MAXUSER_ADDRESS) {
4976 * Here if the pte page isn't mapped, or if it has been
4979 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4980 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4981 nosleep ? NULL : &lock);
4982 if (mpte == NULL && nosleep) {
4983 rv = KERN_RESOURCE_SHORTAGE;
4988 panic("pmap_enter: invalid page directory va=%#lx", va);
4994 * Is the specified virtual address already mapped?
4996 if ((origpte & PG_V) != 0) {
4998 * Wiring change, just update stats. We don't worry about
4999 * wiring PT pages as they remain resident as long as there
5000 * are valid mappings in them. Hence, if a user page is wired,
5001 * the PT page will be also.
5003 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
5004 pmap->pm_stats.wired_count++;
5005 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
5006 pmap->pm_stats.wired_count--;
5009 * Remove the extra PT page reference.
5013 KASSERT(mpte->wire_count > 0,
5014 ("pmap_enter: missing reference to page table page,"
5019 * Has the physical page changed?
5021 opa = origpte & PG_FRAME;
5024 * No, might be a protection or wiring change.
5026 if ((origpte & PG_MANAGED) != 0 &&
5027 (newpte & PG_RW) != 0)
5028 vm_page_aflag_set(m, PGA_WRITEABLE);
5029 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
5035 * The physical page has changed. Temporarily invalidate
5036 * the mapping. This ensures that all threads sharing the
5037 * pmap keep a consistent view of the mapping, which is
5038 * necessary for the correct handling of COW faults. It
5039 * also permits reuse of the old mapping's PV entry,
5040 * avoiding an allocation.
5042 * For consistency, handle unmanaged mappings the same way.
5044 origpte = pte_load_clear(pte);
5045 KASSERT((origpte & PG_FRAME) == opa,
5046 ("pmap_enter: unexpected pa update for %#lx", va));
5047 if ((origpte & PG_MANAGED) != 0) {
5048 om = PHYS_TO_VM_PAGE(opa);
5051 * The pmap lock is sufficient to synchronize with
5052 * concurrent calls to pmap_page_test_mappings() and
5053 * pmap_ts_referenced().
5055 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5057 if ((origpte & PG_A) != 0)
5058 vm_page_aflag_set(om, PGA_REFERENCED);
5059 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
5060 pv = pmap_pvh_remove(&om->md, pmap, va);
5061 if ((newpte & PG_MANAGED) == 0)
5062 free_pv_entry(pmap, pv);
5063 if ((om->aflags & PGA_WRITEABLE) != 0 &&
5064 TAILQ_EMPTY(&om->md.pv_list) &&
5065 ((om->flags & PG_FICTITIOUS) != 0 ||
5066 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
5067 vm_page_aflag_clear(om, PGA_WRITEABLE);
5069 if ((origpte & PG_A) != 0)
5070 pmap_invalidate_page(pmap, va);
5074 * Increment the counters.
5076 if ((newpte & PG_W) != 0)
5077 pmap->pm_stats.wired_count++;
5078 pmap_resident_count_inc(pmap, 1);
5082 * Enter on the PV list if part of our managed memory.
5084 if ((newpte & PG_MANAGED) != 0) {
5086 pv = get_pv_entry(pmap, &lock);
5089 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
5090 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5092 if ((newpte & PG_RW) != 0)
5093 vm_page_aflag_set(m, PGA_WRITEABLE);
5099 if ((origpte & PG_V) != 0) {
5101 origpte = pte_load_store(pte, newpte);
5102 KASSERT((origpte & PG_FRAME) == pa,
5103 ("pmap_enter: unexpected pa update for %#lx", va));
5104 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
5106 if ((origpte & PG_MANAGED) != 0)
5110 * Although the PTE may still have PG_RW set, TLB
5111 * invalidation may nonetheless be required because
5112 * the PTE no longer has PG_M set.
5114 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
5116 * This PTE change does not require TLB invalidation.
5120 if ((origpte & PG_A) != 0)
5121 pmap_invalidate_page(pmap, va);
5123 pte_store(pte, newpte);
5127 #if VM_NRESERVLEVEL > 0
5129 * If both the page table page and the reservation are fully
5130 * populated, then attempt promotion.
5132 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
5133 pmap_ps_enabled(pmap) &&
5134 (m->flags & PG_FICTITIOUS) == 0 &&
5135 vm_reserv_level_iffullpop(m) == 0)
5136 pmap_promote_pde(pmap, pde, va, &lock);
5148 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
5149 * if successful. Returns false if (1) a page table page cannot be allocated
5150 * without sleeping, (2) a mapping already exists at the specified virtual
5151 * address, or (3) a PV entry cannot be allocated without reclaiming another
5155 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5156 struct rwlock **lockp)
5161 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5162 PG_V = pmap_valid_bit(pmap);
5163 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
5165 if ((m->oflags & VPO_UNMANAGED) == 0)
5166 newpde |= PG_MANAGED;
5167 if ((prot & VM_PROT_EXECUTE) == 0)
5169 if (va < VM_MAXUSER_ADDRESS)
5171 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
5172 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
5177 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
5178 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
5179 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
5180 * a mapping already exists at the specified virtual address. Returns
5181 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
5182 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
5183 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
5185 * The parameter "m" is only used when creating a managed, writeable mapping.
5188 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
5189 vm_page_t m, struct rwlock **lockp)
5191 struct spglist free;
5192 pd_entry_t oldpde, *pde;
5193 pt_entry_t PG_G, PG_RW, PG_V;
5196 PG_G = pmap_global_bit(pmap);
5197 PG_RW = pmap_rw_bit(pmap);
5198 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
5199 ("pmap_enter_pde: newpde is missing PG_M"));
5200 PG_V = pmap_valid_bit(pmap);
5201 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5203 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5204 NULL : lockp)) == NULL) {
5205 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5206 " in pmap %p", va, pmap);
5207 return (KERN_RESOURCE_SHORTAGE);
5209 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5210 pde = &pde[pmap_pde_index(va)];
5212 if ((oldpde & PG_V) != 0) {
5213 KASSERT(pdpg->wire_count > 1,
5214 ("pmap_enter_pde: pdpg's wire count is too low"));
5215 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5217 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5218 " in pmap %p", va, pmap);
5219 return (KERN_FAILURE);
5221 /* Break the existing mapping(s). */
5223 if ((oldpde & PG_PS) != 0) {
5225 * The reference to the PD page that was acquired by
5226 * pmap_allocpde() ensures that it won't be freed.
5227 * However, if the PDE resulted from a promotion, then
5228 * a reserved PT page could be freed.
5230 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5231 if ((oldpde & PG_G) == 0)
5232 pmap_invalidate_pde_page(pmap, va, oldpde);
5234 pmap_delayed_invl_started();
5235 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5237 pmap_invalidate_all(pmap);
5238 pmap_delayed_invl_finished();
5240 vm_page_free_pages_toq(&free, true);
5241 if (va >= VM_MAXUSER_ADDRESS) {
5242 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5243 if (pmap_insert_pt_page(pmap, mt)) {
5245 * XXX Currently, this can't happen because
5246 * we do not perform pmap_enter(psind == 1)
5247 * on the kernel pmap.
5249 panic("pmap_enter_pde: trie insert failed");
5252 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5255 if ((newpde & PG_MANAGED) != 0) {
5257 * Abort this mapping if its PV entry could not be created.
5259 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5261 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5263 * Although "va" is not mapped, paging-
5264 * structure caches could nonetheless have
5265 * entries that refer to the freed page table
5266 * pages. Invalidate those entries.
5268 pmap_invalidate_page(pmap, va);
5269 vm_page_free_pages_toq(&free, true);
5271 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5272 " in pmap %p", va, pmap);
5273 return (KERN_RESOURCE_SHORTAGE);
5275 if ((newpde & PG_RW) != 0) {
5276 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5277 vm_page_aflag_set(mt, PGA_WRITEABLE);
5282 * Increment counters.
5284 if ((newpde & PG_W) != 0)
5285 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5286 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5289 * Map the superpage. (This is not a promoted mapping; there will not
5290 * be any lingering 4KB page mappings in the TLB.)
5292 pde_store(pde, newpde);
5294 atomic_add_long(&pmap_pde_mappings, 1);
5295 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5296 " in pmap %p", va, pmap);
5297 return (KERN_SUCCESS);
5301 * Maps a sequence of resident pages belonging to the same object.
5302 * The sequence begins with the given page m_start. This page is
5303 * mapped at the given virtual address start. Each subsequent page is
5304 * mapped at a virtual address that is offset from start by the same
5305 * amount as the page is offset from m_start within the object. The
5306 * last page in the sequence is the page with the largest offset from
5307 * m_start that can be mapped at a virtual address less than the given
5308 * virtual address end. Not every virtual page between start and end
5309 * is mapped; only those for which a resident page exists with the
5310 * corresponding offset from m_start are mapped.
5313 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5314 vm_page_t m_start, vm_prot_t prot)
5316 struct rwlock *lock;
5319 vm_pindex_t diff, psize;
5321 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5323 psize = atop(end - start);
5328 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5329 va = start + ptoa(diff);
5330 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5331 m->psind == 1 && pmap_ps_enabled(pmap) &&
5332 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5333 m = &m[NBPDR / PAGE_SIZE - 1];
5335 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5337 m = TAILQ_NEXT(m, listq);
5345 * this code makes some *MAJOR* assumptions:
5346 * 1. Current pmap & pmap exists.
5349 * 4. No page table pages.
5350 * but is *MUCH* faster than pmap_enter...
5354 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5356 struct rwlock *lock;
5360 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5367 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5368 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5370 struct spglist free;
5371 pt_entry_t *pte, PG_V;
5374 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5375 (m->oflags & VPO_UNMANAGED) != 0,
5376 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5377 PG_V = pmap_valid_bit(pmap);
5378 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5381 * In the case that a page table page is not
5382 * resident, we are creating it here.
5384 if (va < VM_MAXUSER_ADDRESS) {
5385 vm_pindex_t ptepindex;
5389 * Calculate pagetable page index
5391 ptepindex = pmap_pde_pindex(va);
5392 if (mpte && (mpte->pindex == ptepindex)) {
5396 * Get the page directory entry
5398 ptepa = pmap_pde(pmap, va);
5401 * If the page table page is mapped, we just increment
5402 * the hold count, and activate it. Otherwise, we
5403 * attempt to allocate a page table page. If this
5404 * attempt fails, we don't retry. Instead, we give up.
5406 if (ptepa && (*ptepa & PG_V) != 0) {
5409 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5413 * Pass NULL instead of the PV list lock
5414 * pointer, because we don't intend to sleep.
5416 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5421 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5422 pte = &pte[pmap_pte_index(va)];
5436 * Enter on the PV list if part of our managed memory.
5438 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5439 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5442 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5444 * Although "va" is not mapped, paging-
5445 * structure caches could nonetheless have
5446 * entries that refer to the freed page table
5447 * pages. Invalidate those entries.
5449 pmap_invalidate_page(pmap, va);
5450 vm_page_free_pages_toq(&free, true);
5458 * Increment counters
5460 pmap_resident_count_inc(pmap, 1);
5462 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5463 if ((prot & VM_PROT_EXECUTE) == 0)
5467 * Now validate mapping with RO protection
5469 if ((m->oflags & VPO_UNMANAGED) != 0)
5470 pte_store(pte, pa | PG_V | PG_U);
5472 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5477 * Make a temporary mapping for a physical address. This is only intended
5478 * to be used for panic dumps.
5481 pmap_kenter_temporary(vm_paddr_t pa, int i)
5485 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5486 pmap_kenter(va, pa);
5488 return ((void *)crashdumpmap);
5492 * This code maps large physical mmap regions into the
5493 * processor address space. Note that some shortcuts
5494 * are taken, but the code works.
5497 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5498 vm_pindex_t pindex, vm_size_t size)
5501 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5502 vm_paddr_t pa, ptepa;
5506 PG_A = pmap_accessed_bit(pmap);
5507 PG_M = pmap_modified_bit(pmap);
5508 PG_V = pmap_valid_bit(pmap);
5509 PG_RW = pmap_rw_bit(pmap);
5511 VM_OBJECT_ASSERT_WLOCKED(object);
5512 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5513 ("pmap_object_init_pt: non-device object"));
5514 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5515 if (!pmap_ps_enabled(pmap))
5517 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5519 p = vm_page_lookup(object, pindex);
5520 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5521 ("pmap_object_init_pt: invalid page %p", p));
5522 pat_mode = p->md.pat_mode;
5525 * Abort the mapping if the first page is not physically
5526 * aligned to a 2MB page boundary.
5528 ptepa = VM_PAGE_TO_PHYS(p);
5529 if (ptepa & (NBPDR - 1))
5533 * Skip the first page. Abort the mapping if the rest of
5534 * the pages are not physically contiguous or have differing
5535 * memory attributes.
5537 p = TAILQ_NEXT(p, listq);
5538 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5540 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5541 ("pmap_object_init_pt: invalid page %p", p));
5542 if (pa != VM_PAGE_TO_PHYS(p) ||
5543 pat_mode != p->md.pat_mode)
5545 p = TAILQ_NEXT(p, listq);
5549 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5550 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5551 * will not affect the termination of this loop.
5554 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5555 pa < ptepa + size; pa += NBPDR) {
5556 pdpg = pmap_allocpde(pmap, addr, NULL);
5559 * The creation of mappings below is only an
5560 * optimization. If a page directory page
5561 * cannot be allocated without blocking,
5562 * continue on to the next mapping rather than
5568 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5569 pde = &pde[pmap_pde_index(addr)];
5570 if ((*pde & PG_V) == 0) {
5571 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5572 PG_U | PG_RW | PG_V);
5573 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5574 atomic_add_long(&pmap_pde_mappings, 1);
5576 /* Continue on if the PDE is already valid. */
5578 KASSERT(pdpg->wire_count > 0,
5579 ("pmap_object_init_pt: missing reference "
5580 "to page directory page, va: 0x%lx", addr));
5589 * Clear the wired attribute from the mappings for the specified range of
5590 * addresses in the given pmap. Every valid mapping within that range
5591 * must have the wired attribute set. In contrast, invalid mappings
5592 * cannot have the wired attribute set, so they are ignored.
5594 * The wired attribute of the page table entry is not a hardware
5595 * feature, so there is no need to invalidate any TLB entries.
5596 * Since pmap_demote_pde() for the wired entry must never fail,
5597 * pmap_delayed_invl_started()/finished() calls around the
5598 * function are not needed.
5601 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5603 vm_offset_t va_next;
5604 pml4_entry_t *pml4e;
5607 pt_entry_t *pte, PG_V;
5609 PG_V = pmap_valid_bit(pmap);
5611 for (; sva < eva; sva = va_next) {
5612 pml4e = pmap_pml4e(pmap, sva);
5613 if ((*pml4e & PG_V) == 0) {
5614 va_next = (sva + NBPML4) & ~PML4MASK;
5619 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5620 if ((*pdpe & PG_V) == 0) {
5621 va_next = (sva + NBPDP) & ~PDPMASK;
5626 va_next = (sva + NBPDR) & ~PDRMASK;
5629 pde = pmap_pdpe_to_pde(pdpe, sva);
5630 if ((*pde & PG_V) == 0)
5632 if ((*pde & PG_PS) != 0) {
5633 if ((*pde & PG_W) == 0)
5634 panic("pmap_unwire: pde %#jx is missing PG_W",
5638 * Are we unwiring the entire large page? If not,
5639 * demote the mapping and fall through.
5641 if (sva + NBPDR == va_next && eva >= va_next) {
5642 atomic_clear_long(pde, PG_W);
5643 pmap->pm_stats.wired_count -= NBPDR /
5646 } else if (!pmap_demote_pde(pmap, pde, sva))
5647 panic("pmap_unwire: demotion failed");
5651 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5653 if ((*pte & PG_V) == 0)
5655 if ((*pte & PG_W) == 0)
5656 panic("pmap_unwire: pte %#jx is missing PG_W",
5660 * PG_W must be cleared atomically. Although the pmap
5661 * lock synchronizes access to PG_W, another processor
5662 * could be setting PG_M and/or PG_A concurrently.
5664 atomic_clear_long(pte, PG_W);
5665 pmap->pm_stats.wired_count--;
5672 * Copy the range specified by src_addr/len
5673 * from the source map to the range dst_addr/len
5674 * in the destination map.
5676 * This routine is only advisory and need not do anything.
5680 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5681 vm_offset_t src_addr)
5683 struct rwlock *lock;
5684 struct spglist free;
5686 vm_offset_t end_addr = src_addr + len;
5687 vm_offset_t va_next;
5688 vm_page_t dst_pdpg, dstmpte, srcmpte;
5689 pt_entry_t PG_A, PG_M, PG_V;
5691 if (dst_addr != src_addr)
5694 if (dst_pmap->pm_type != src_pmap->pm_type)
5698 * EPT page table entries that require emulation of A/D bits are
5699 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5700 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5701 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5702 * implementations flag an EPT misconfiguration for exec-only
5703 * mappings we skip this function entirely for emulated pmaps.
5705 if (pmap_emulate_ad_bits(dst_pmap))
5709 if (dst_pmap < src_pmap) {
5710 PMAP_LOCK(dst_pmap);
5711 PMAP_LOCK(src_pmap);
5713 PMAP_LOCK(src_pmap);
5714 PMAP_LOCK(dst_pmap);
5717 PG_A = pmap_accessed_bit(dst_pmap);
5718 PG_M = pmap_modified_bit(dst_pmap);
5719 PG_V = pmap_valid_bit(dst_pmap);
5721 for (addr = src_addr; addr < end_addr; addr = va_next) {
5722 pt_entry_t *src_pte, *dst_pte;
5723 pml4_entry_t *pml4e;
5725 pd_entry_t srcptepaddr, *pde;
5727 KASSERT(addr < UPT_MIN_ADDRESS,
5728 ("pmap_copy: invalid to pmap_copy page tables"));
5730 pml4e = pmap_pml4e(src_pmap, addr);
5731 if ((*pml4e & PG_V) == 0) {
5732 va_next = (addr + NBPML4) & ~PML4MASK;
5738 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5739 if ((*pdpe & PG_V) == 0) {
5740 va_next = (addr + NBPDP) & ~PDPMASK;
5746 va_next = (addr + NBPDR) & ~PDRMASK;
5750 pde = pmap_pdpe_to_pde(pdpe, addr);
5752 if (srcptepaddr == 0)
5755 if (srcptepaddr & PG_PS) {
5756 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5758 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5759 if (dst_pdpg == NULL)
5761 pde = (pd_entry_t *)
5762 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5763 pde = &pde[pmap_pde_index(addr)];
5764 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5765 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5766 PMAP_ENTER_NORECLAIM, &lock))) {
5767 *pde = srcptepaddr & ~PG_W;
5768 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5769 atomic_add_long(&pmap_pde_mappings, 1);
5771 dst_pdpg->wire_count--;
5775 srcptepaddr &= PG_FRAME;
5776 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5777 KASSERT(srcmpte->wire_count > 0,
5778 ("pmap_copy: source page table page is unused"));
5780 if (va_next > end_addr)
5783 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5784 src_pte = &src_pte[pmap_pte_index(addr)];
5786 while (addr < va_next) {
5790 * we only virtual copy managed pages
5792 if ((ptetemp & PG_MANAGED) != 0) {
5793 if (dstmpte != NULL &&
5794 dstmpte->pindex == pmap_pde_pindex(addr))
5795 dstmpte->wire_count++;
5796 else if ((dstmpte = pmap_allocpte(dst_pmap,
5797 addr, NULL)) == NULL)
5799 dst_pte = (pt_entry_t *)
5800 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5801 dst_pte = &dst_pte[pmap_pte_index(addr)];
5802 if (*dst_pte == 0 &&
5803 pmap_try_insert_pv_entry(dst_pmap, addr,
5804 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5807 * Clear the wired, modified, and
5808 * accessed (referenced) bits
5811 *dst_pte = ptetemp & ~(PG_W | PG_M |
5813 pmap_resident_count_inc(dst_pmap, 1);
5816 if (pmap_unwire_ptp(dst_pmap, addr,
5819 * Although "addr" is not
5820 * mapped, paging-structure
5821 * caches could nonetheless
5822 * have entries that refer to
5823 * the freed page table pages.
5824 * Invalidate those entries.
5826 pmap_invalidate_page(dst_pmap,
5828 vm_page_free_pages_toq(&free,
5833 if (dstmpte->wire_count >= srcmpte->wire_count)
5843 PMAP_UNLOCK(src_pmap);
5844 PMAP_UNLOCK(dst_pmap);
5848 * Zero the specified hardware page.
5851 pmap_zero_page(vm_page_t m)
5853 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5855 pagezero((void *)va);
5859 * Zero an an area within a single hardware page. off and size must not
5860 * cover an area beyond a single hardware page.
5863 pmap_zero_page_area(vm_page_t m, int off, int size)
5865 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5867 if (off == 0 && size == PAGE_SIZE)
5868 pagezero((void *)va);
5870 bzero((char *)va + off, size);
5874 * Copy 1 specified hardware page to another.
5877 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5879 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5880 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5882 pagecopy((void *)src, (void *)dst);
5885 int unmapped_buf_allowed = 1;
5888 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5889 vm_offset_t b_offset, int xfersize)
5893 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5897 while (xfersize > 0) {
5898 a_pg_offset = a_offset & PAGE_MASK;
5899 pages[0] = ma[a_offset >> PAGE_SHIFT];
5900 b_pg_offset = b_offset & PAGE_MASK;
5901 pages[1] = mb[b_offset >> PAGE_SHIFT];
5902 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5903 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5904 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5905 a_cp = (char *)vaddr[0] + a_pg_offset;
5906 b_cp = (char *)vaddr[1] + b_pg_offset;
5907 bcopy(a_cp, b_cp, cnt);
5908 if (__predict_false(mapped))
5909 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5917 * Returns true if the pmap's pv is one of the first
5918 * 16 pvs linked to from this page. This count may
5919 * be changed upwards or downwards in the future; it
5920 * is only necessary that true be returned for a small
5921 * subset of pmaps for proper page aging.
5924 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5926 struct md_page *pvh;
5927 struct rwlock *lock;
5932 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5933 ("pmap_page_exists_quick: page %p is not managed", m));
5935 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5937 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5938 if (PV_PMAP(pv) == pmap) {
5946 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5947 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5948 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5949 if (PV_PMAP(pv) == pmap) {
5963 * pmap_page_wired_mappings:
5965 * Return the number of managed mappings to the given physical page
5969 pmap_page_wired_mappings(vm_page_t m)
5971 struct rwlock *lock;
5972 struct md_page *pvh;
5976 int count, md_gen, pvh_gen;
5978 if ((m->oflags & VPO_UNMANAGED) != 0)
5980 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5984 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5986 if (!PMAP_TRYLOCK(pmap)) {
5987 md_gen = m->md.pv_gen;
5991 if (md_gen != m->md.pv_gen) {
5996 pte = pmap_pte(pmap, pv->pv_va);
5997 if ((*pte & PG_W) != 0)
6001 if ((m->flags & PG_FICTITIOUS) == 0) {
6002 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6003 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6005 if (!PMAP_TRYLOCK(pmap)) {
6006 md_gen = m->md.pv_gen;
6007 pvh_gen = pvh->pv_gen;
6011 if (md_gen != m->md.pv_gen ||
6012 pvh_gen != pvh->pv_gen) {
6017 pte = pmap_pde(pmap, pv->pv_va);
6018 if ((*pte & PG_W) != 0)
6028 * Returns TRUE if the given page is mapped individually or as part of
6029 * a 2mpage. Otherwise, returns FALSE.
6032 pmap_page_is_mapped(vm_page_t m)
6034 struct rwlock *lock;
6037 if ((m->oflags & VPO_UNMANAGED) != 0)
6039 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6041 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
6042 ((m->flags & PG_FICTITIOUS) == 0 &&
6043 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
6049 * Destroy all managed, non-wired mappings in the given user-space
6050 * pmap. This pmap cannot be active on any processor besides the
6053 * This function cannot be applied to the kernel pmap. Moreover, it
6054 * is not intended for general use. It is only to be used during
6055 * process termination. Consequently, it can be implemented in ways
6056 * that make it faster than pmap_remove(). First, it can more quickly
6057 * destroy mappings by iterating over the pmap's collection of PV
6058 * entries, rather than searching the page table. Second, it doesn't
6059 * have to test and clear the page table entries atomically, because
6060 * no processor is currently accessing the user address space. In
6061 * particular, a page table entry's dirty bit won't change state once
6062 * this function starts.
6064 * Although this function destroys all of the pmap's managed,
6065 * non-wired mappings, it can delay and batch the invalidation of TLB
6066 * entries without calling pmap_delayed_invl_started() and
6067 * pmap_delayed_invl_finished(). Because the pmap is not active on
6068 * any other processor, none of these TLB entries will ever be used
6069 * before their eventual invalidation. Consequently, there is no need
6070 * for either pmap_remove_all() or pmap_remove_write() to wait for
6071 * that eventual TLB invalidation.
6074 pmap_remove_pages(pmap_t pmap)
6077 pt_entry_t *pte, tpte;
6078 pt_entry_t PG_M, PG_RW, PG_V;
6079 struct spglist free;
6080 vm_page_t m, mpte, mt;
6082 struct md_page *pvh;
6083 struct pv_chunk *pc, *npc;
6084 struct rwlock *lock;
6086 uint64_t inuse, bitmask;
6087 int allfree, field, freed, idx;
6088 boolean_t superpage;
6092 * Assert that the given pmap is only active on the current
6093 * CPU. Unfortunately, we cannot block another CPU from
6094 * activating the pmap while this function is executing.
6096 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
6099 cpuset_t other_cpus;
6101 other_cpus = all_cpus;
6103 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
6104 CPU_AND(&other_cpus, &pmap->pm_active);
6106 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
6111 PG_M = pmap_modified_bit(pmap);
6112 PG_V = pmap_valid_bit(pmap);
6113 PG_RW = pmap_rw_bit(pmap);
6117 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
6120 for (field = 0; field < _NPCM; field++) {
6121 inuse = ~pc->pc_map[field] & pc_freemask[field];
6122 while (inuse != 0) {
6124 bitmask = 1UL << bit;
6125 idx = field * 64 + bit;
6126 pv = &pc->pc_pventry[idx];
6129 pte = pmap_pdpe(pmap, pv->pv_va);
6131 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
6133 if ((tpte & (PG_PS | PG_V)) == PG_V) {
6136 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
6138 pte = &pte[pmap_pte_index(pv->pv_va)];
6142 * Keep track whether 'tpte' is a
6143 * superpage explicitly instead of
6144 * relying on PG_PS being set.
6146 * This is because PG_PS is numerically
6147 * identical to PG_PTE_PAT and thus a
6148 * regular page could be mistaken for
6154 if ((tpte & PG_V) == 0) {
6155 panic("bad pte va %lx pte %lx",
6160 * We cannot remove wired pages from a process' mapping at this time
6168 pa = tpte & PG_PS_FRAME;
6170 pa = tpte & PG_FRAME;
6172 m = PHYS_TO_VM_PAGE(pa);
6173 KASSERT(m->phys_addr == pa,
6174 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6175 m, (uintmax_t)m->phys_addr,
6178 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6179 m < &vm_page_array[vm_page_array_size],
6180 ("pmap_remove_pages: bad tpte %#jx",
6186 * Update the vm_page_t clean/reference bits.
6188 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6190 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6196 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6199 pc->pc_map[field] |= bitmask;
6201 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6202 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6203 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6205 if (TAILQ_EMPTY(&pvh->pv_list)) {
6206 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6207 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6208 TAILQ_EMPTY(&mt->md.pv_list))
6209 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6211 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6213 pmap_resident_count_dec(pmap, 1);
6214 KASSERT(mpte->wire_count == NPTEPG,
6215 ("pmap_remove_pages: pte page wire count error"));
6216 mpte->wire_count = 0;
6217 pmap_add_delayed_free_list(mpte, &free, FALSE);
6220 pmap_resident_count_dec(pmap, 1);
6221 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6223 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6224 TAILQ_EMPTY(&m->md.pv_list) &&
6225 (m->flags & PG_FICTITIOUS) == 0) {
6226 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6227 if (TAILQ_EMPTY(&pvh->pv_list))
6228 vm_page_aflag_clear(m, PGA_WRITEABLE);
6231 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6235 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6236 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6237 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6239 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6245 pmap_invalidate_all(pmap);
6247 vm_page_free_pages_toq(&free, true);
6251 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6253 struct rwlock *lock;
6255 struct md_page *pvh;
6256 pt_entry_t *pte, mask;
6257 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6259 int md_gen, pvh_gen;
6263 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6266 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6268 if (!PMAP_TRYLOCK(pmap)) {
6269 md_gen = m->md.pv_gen;
6273 if (md_gen != m->md.pv_gen) {
6278 pte = pmap_pte(pmap, pv->pv_va);
6281 PG_M = pmap_modified_bit(pmap);
6282 PG_RW = pmap_rw_bit(pmap);
6283 mask |= PG_RW | PG_M;
6286 PG_A = pmap_accessed_bit(pmap);
6287 PG_V = pmap_valid_bit(pmap);
6288 mask |= PG_V | PG_A;
6290 rv = (*pte & mask) == mask;
6295 if ((m->flags & PG_FICTITIOUS) == 0) {
6296 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6297 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6299 if (!PMAP_TRYLOCK(pmap)) {
6300 md_gen = m->md.pv_gen;
6301 pvh_gen = pvh->pv_gen;
6305 if (md_gen != m->md.pv_gen ||
6306 pvh_gen != pvh->pv_gen) {
6311 pte = pmap_pde(pmap, pv->pv_va);
6314 PG_M = pmap_modified_bit(pmap);
6315 PG_RW = pmap_rw_bit(pmap);
6316 mask |= PG_RW | PG_M;
6319 PG_A = pmap_accessed_bit(pmap);
6320 PG_V = pmap_valid_bit(pmap);
6321 mask |= PG_V | PG_A;
6323 rv = (*pte & mask) == mask;
6337 * Return whether or not the specified physical page was modified
6338 * in any physical maps.
6341 pmap_is_modified(vm_page_t m)
6344 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6345 ("pmap_is_modified: page %p is not managed", m));
6348 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6349 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6350 * is clear, no PTEs can have PG_M set.
6352 VM_OBJECT_ASSERT_WLOCKED(m->object);
6353 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6355 return (pmap_page_test_mappings(m, FALSE, TRUE));
6359 * pmap_is_prefaultable:
6361 * Return whether or not the specified virtual address is eligible
6365 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6368 pt_entry_t *pte, PG_V;
6371 PG_V = pmap_valid_bit(pmap);
6374 pde = pmap_pde(pmap, addr);
6375 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6376 pte = pmap_pde_to_pte(pde, addr);
6377 rv = (*pte & PG_V) == 0;
6384 * pmap_is_referenced:
6386 * Return whether or not the specified physical page was referenced
6387 * in any physical maps.
6390 pmap_is_referenced(vm_page_t m)
6393 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6394 ("pmap_is_referenced: page %p is not managed", m));
6395 return (pmap_page_test_mappings(m, TRUE, FALSE));
6399 * Clear the write and modified bits in each of the given page's mappings.
6402 pmap_remove_write(vm_page_t m)
6404 struct md_page *pvh;
6406 struct rwlock *lock;
6407 pv_entry_t next_pv, pv;
6409 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6411 int pvh_gen, md_gen;
6413 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6414 ("pmap_remove_write: page %p is not managed", m));
6417 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6418 * set by another thread while the object is locked. Thus,
6419 * if PGA_WRITEABLE is clear, no page table entries need updating.
6421 VM_OBJECT_ASSERT_WLOCKED(m->object);
6422 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6424 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6425 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6426 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6429 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6431 if (!PMAP_TRYLOCK(pmap)) {
6432 pvh_gen = pvh->pv_gen;
6436 if (pvh_gen != pvh->pv_gen) {
6442 PG_RW = pmap_rw_bit(pmap);
6444 pde = pmap_pde(pmap, va);
6445 if ((*pde & PG_RW) != 0)
6446 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6447 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6448 ("inconsistent pv lock %p %p for page %p",
6449 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6452 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6454 if (!PMAP_TRYLOCK(pmap)) {
6455 pvh_gen = pvh->pv_gen;
6456 md_gen = m->md.pv_gen;
6460 if (pvh_gen != pvh->pv_gen ||
6461 md_gen != m->md.pv_gen) {
6467 PG_M = pmap_modified_bit(pmap);
6468 PG_RW = pmap_rw_bit(pmap);
6469 pde = pmap_pde(pmap, pv->pv_va);
6470 KASSERT((*pde & PG_PS) == 0,
6471 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6473 pte = pmap_pde_to_pte(pde, pv->pv_va);
6476 if (oldpte & PG_RW) {
6477 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6480 if ((oldpte & PG_M) != 0)
6482 pmap_invalidate_page(pmap, pv->pv_va);
6487 vm_page_aflag_clear(m, PGA_WRITEABLE);
6488 pmap_delayed_invl_wait(m);
6491 static __inline boolean_t
6492 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6495 if (!pmap_emulate_ad_bits(pmap))
6498 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6501 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6502 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6503 * if the EPT_PG_WRITE bit is set.
6505 if ((pte & EPT_PG_WRITE) != 0)
6509 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6511 if ((pte & EPT_PG_EXECUTE) == 0 ||
6512 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6519 * pmap_ts_referenced:
6521 * Return a count of reference bits for a page, clearing those bits.
6522 * It is not necessary for every reference bit to be cleared, but it
6523 * is necessary that 0 only be returned when there are truly no
6524 * reference bits set.
6526 * As an optimization, update the page's dirty field if a modified bit is
6527 * found while counting reference bits. This opportunistic update can be
6528 * performed at low cost and can eliminate the need for some future calls
6529 * to pmap_is_modified(). However, since this function stops after
6530 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6531 * dirty pages. Those dirty pages will only be detected by a future call
6532 * to pmap_is_modified().
6534 * A DI block is not needed within this function, because
6535 * invalidations are performed before the PV list lock is
6539 pmap_ts_referenced(vm_page_t m)
6541 struct md_page *pvh;
6544 struct rwlock *lock;
6545 pd_entry_t oldpde, *pde;
6546 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6549 int cleared, md_gen, not_cleared, pvh_gen;
6550 struct spglist free;
6553 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6554 ("pmap_ts_referenced: page %p is not managed", m));
6557 pa = VM_PAGE_TO_PHYS(m);
6558 lock = PHYS_TO_PV_LIST_LOCK(pa);
6559 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6563 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6564 goto small_mappings;
6570 if (!PMAP_TRYLOCK(pmap)) {
6571 pvh_gen = pvh->pv_gen;
6575 if (pvh_gen != pvh->pv_gen) {
6580 PG_A = pmap_accessed_bit(pmap);
6581 PG_M = pmap_modified_bit(pmap);
6582 PG_RW = pmap_rw_bit(pmap);
6584 pde = pmap_pde(pmap, pv->pv_va);
6586 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6588 * Although "oldpde" is mapping a 2MB page, because
6589 * this function is called at a 4KB page granularity,
6590 * we only update the 4KB page under test.
6594 if ((oldpde & PG_A) != 0) {
6596 * Since this reference bit is shared by 512 4KB
6597 * pages, it should not be cleared every time it is
6598 * tested. Apply a simple "hash" function on the
6599 * physical page number, the virtual superpage number,
6600 * and the pmap address to select one 4KB page out of
6601 * the 512 on which testing the reference bit will
6602 * result in clearing that reference bit. This
6603 * function is designed to avoid the selection of the
6604 * same 4KB page for every 2MB page mapping.
6606 * On demotion, a mapping that hasn't been referenced
6607 * is simply destroyed. To avoid the possibility of a
6608 * subsequent page fault on a demoted wired mapping,
6609 * always leave its reference bit set. Moreover,
6610 * since the superpage is wired, the current state of
6611 * its reference bit won't affect page replacement.
6613 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6614 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6615 (oldpde & PG_W) == 0) {
6616 if (safe_to_clear_referenced(pmap, oldpde)) {
6617 atomic_clear_long(pde, PG_A);
6618 pmap_invalidate_page(pmap, pv->pv_va);
6620 } else if (pmap_demote_pde_locked(pmap, pde,
6621 pv->pv_va, &lock)) {
6623 * Remove the mapping to a single page
6624 * so that a subsequent access may
6625 * repromote. Since the underlying
6626 * page table page is fully populated,
6627 * this removal never frees a page
6631 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6633 pte = pmap_pde_to_pte(pde, va);
6634 pmap_remove_pte(pmap, pte, va, *pde,
6636 pmap_invalidate_page(pmap, va);
6642 * The superpage mapping was removed
6643 * entirely and therefore 'pv' is no
6651 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6652 ("inconsistent pv lock %p %p for page %p",
6653 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6658 /* Rotate the PV list if it has more than one entry. */
6659 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6660 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6661 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6664 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6666 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6668 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6675 if (!PMAP_TRYLOCK(pmap)) {
6676 pvh_gen = pvh->pv_gen;
6677 md_gen = m->md.pv_gen;
6681 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6686 PG_A = pmap_accessed_bit(pmap);
6687 PG_M = pmap_modified_bit(pmap);
6688 PG_RW = pmap_rw_bit(pmap);
6689 pde = pmap_pde(pmap, pv->pv_va);
6690 KASSERT((*pde & PG_PS) == 0,
6691 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6693 pte = pmap_pde_to_pte(pde, pv->pv_va);
6694 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6696 if ((*pte & PG_A) != 0) {
6697 if (safe_to_clear_referenced(pmap, *pte)) {
6698 atomic_clear_long(pte, PG_A);
6699 pmap_invalidate_page(pmap, pv->pv_va);
6701 } else if ((*pte & PG_W) == 0) {
6703 * Wired pages cannot be paged out so
6704 * doing accessed bit emulation for
6705 * them is wasted effort. We do the
6706 * hard work for unwired pages only.
6708 pmap_remove_pte(pmap, pte, pv->pv_va,
6709 *pde, &free, &lock);
6710 pmap_invalidate_page(pmap, pv->pv_va);
6715 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6716 ("inconsistent pv lock %p %p for page %p",
6717 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6722 /* Rotate the PV list if it has more than one entry. */
6723 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6724 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6725 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6728 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6729 not_cleared < PMAP_TS_REFERENCED_MAX);
6732 vm_page_free_pages_toq(&free, true);
6733 return (cleared + not_cleared);
6737 * Apply the given advice to the specified range of addresses within the
6738 * given pmap. Depending on the advice, clear the referenced and/or
6739 * modified flags in each mapping and set the mapped page's dirty field.
6742 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6744 struct rwlock *lock;
6745 pml4_entry_t *pml4e;
6747 pd_entry_t oldpde, *pde;
6748 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6749 vm_offset_t va, va_next;
6751 boolean_t anychanged;
6753 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6757 * A/D bit emulation requires an alternate code path when clearing
6758 * the modified and accessed bits below. Since this function is
6759 * advisory in nature we skip it entirely for pmaps that require
6760 * A/D bit emulation.
6762 if (pmap_emulate_ad_bits(pmap))
6765 PG_A = pmap_accessed_bit(pmap);
6766 PG_G = pmap_global_bit(pmap);
6767 PG_M = pmap_modified_bit(pmap);
6768 PG_V = pmap_valid_bit(pmap);
6769 PG_RW = pmap_rw_bit(pmap);
6771 pmap_delayed_invl_started();
6773 for (; sva < eva; sva = va_next) {
6774 pml4e = pmap_pml4e(pmap, sva);
6775 if ((*pml4e & PG_V) == 0) {
6776 va_next = (sva + NBPML4) & ~PML4MASK;
6781 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6782 if ((*pdpe & PG_V) == 0) {
6783 va_next = (sva + NBPDP) & ~PDPMASK;
6788 va_next = (sva + NBPDR) & ~PDRMASK;
6791 pde = pmap_pdpe_to_pde(pdpe, sva);
6793 if ((oldpde & PG_V) == 0)
6795 else if ((oldpde & PG_PS) != 0) {
6796 if ((oldpde & PG_MANAGED) == 0)
6799 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6804 * The large page mapping was destroyed.
6810 * Unless the page mappings are wired, remove the
6811 * mapping to a single page so that a subsequent
6812 * access may repromote. Since the underlying page
6813 * table page is fully populated, this removal never
6814 * frees a page table page.
6816 if ((oldpde & PG_W) == 0) {
6817 pte = pmap_pde_to_pte(pde, sva);
6818 KASSERT((*pte & PG_V) != 0,
6819 ("pmap_advise: invalid PTE"));
6820 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6830 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6832 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6834 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6835 if (advice == MADV_DONTNEED) {
6837 * Future calls to pmap_is_modified()
6838 * can be avoided by making the page
6841 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6844 atomic_clear_long(pte, PG_M | PG_A);
6845 } else if ((*pte & PG_A) != 0)
6846 atomic_clear_long(pte, PG_A);
6850 if ((*pte & PG_G) != 0) {
6857 if (va != va_next) {
6858 pmap_invalidate_range(pmap, va, sva);
6863 pmap_invalidate_range(pmap, va, sva);
6866 pmap_invalidate_all(pmap);
6868 pmap_delayed_invl_finished();
6872 * Clear the modify bits on the specified physical page.
6875 pmap_clear_modify(vm_page_t m)
6877 struct md_page *pvh;
6879 pv_entry_t next_pv, pv;
6880 pd_entry_t oldpde, *pde;
6881 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6882 struct rwlock *lock;
6884 int md_gen, pvh_gen;
6886 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6887 ("pmap_clear_modify: page %p is not managed", m));
6888 VM_OBJECT_ASSERT_WLOCKED(m->object);
6889 KASSERT(!vm_page_xbusied(m),
6890 ("pmap_clear_modify: page %p is exclusive busied", m));
6893 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6894 * If the object containing the page is locked and the page is not
6895 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6897 if ((m->aflags & PGA_WRITEABLE) == 0)
6899 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6900 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6901 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6904 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6906 if (!PMAP_TRYLOCK(pmap)) {
6907 pvh_gen = pvh->pv_gen;
6911 if (pvh_gen != pvh->pv_gen) {
6916 PG_M = pmap_modified_bit(pmap);
6917 PG_V = pmap_valid_bit(pmap);
6918 PG_RW = pmap_rw_bit(pmap);
6920 pde = pmap_pde(pmap, va);
6922 if ((oldpde & PG_RW) != 0) {
6923 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6924 if ((oldpde & PG_W) == 0) {
6926 * Write protect the mapping to a
6927 * single page so that a subsequent
6928 * write access may repromote.
6930 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6932 pte = pmap_pde_to_pte(pde, va);
6934 if ((oldpte & PG_V) != 0) {
6935 while (!atomic_cmpset_long(pte,
6937 oldpte & ~(PG_M | PG_RW)))
6940 pmap_invalidate_page(pmap, va);
6947 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6949 if (!PMAP_TRYLOCK(pmap)) {
6950 md_gen = m->md.pv_gen;
6951 pvh_gen = pvh->pv_gen;
6955 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6960 PG_M = pmap_modified_bit(pmap);
6961 PG_RW = pmap_rw_bit(pmap);
6962 pde = pmap_pde(pmap, pv->pv_va);
6963 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6964 " a 2mpage in page %p's pv list", m));
6965 pte = pmap_pde_to_pte(pde, pv->pv_va);
6966 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6967 atomic_clear_long(pte, PG_M);
6968 pmap_invalidate_page(pmap, pv->pv_va);
6976 * Miscellaneous support routines follow
6979 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6980 static __inline void
6981 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6986 * The cache mode bits are all in the low 32-bits of the
6987 * PTE, so we can just spin on updating the low 32-bits.
6990 opte = *(u_int *)pte;
6991 npte = opte & ~mask;
6993 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6996 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6997 static __inline void
6998 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
7003 * The cache mode bits are all in the low 32-bits of the
7004 * PDE, so we can just spin on updating the low 32-bits.
7007 opde = *(u_int *)pde;
7008 npde = opde & ~mask;
7010 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
7014 * Map a set of physical memory pages into the kernel virtual
7015 * address space. Return a pointer to where it is mapped. This
7016 * routine is intended to be used for mapping device memory,
7020 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
7022 struct pmap_preinit_mapping *ppim;
7023 vm_offset_t va, offset;
7027 offset = pa & PAGE_MASK;
7028 size = round_page(offset + size);
7029 pa = trunc_page(pa);
7031 if (!pmap_initialized) {
7033 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7034 ppim = pmap_preinit_mapping + i;
7035 if (ppim->va == 0) {
7039 ppim->va = virtual_avail;
7040 virtual_avail += size;
7046 panic("%s: too many preinit mappings", __func__);
7049 * If we have a preinit mapping, re-use it.
7051 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7052 ppim = pmap_preinit_mapping + i;
7053 if (ppim->pa == pa && ppim->sz == size &&
7055 return ((void *)(ppim->va + offset));
7058 * If the specified range of physical addresses fits within
7059 * the direct map window, use the direct map.
7061 if (pa < dmaplimit && pa + size <= dmaplimit) {
7062 va = PHYS_TO_DMAP(pa);
7063 if (!pmap_change_attr(va, size, mode))
7064 return ((void *)(va + offset));
7066 va = kva_alloc(size);
7068 panic("%s: Couldn't allocate KVA", __func__);
7070 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
7071 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
7072 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
7073 pmap_invalidate_cache_range(va, va + tmpsize);
7074 return ((void *)(va + offset));
7078 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
7081 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
7085 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
7088 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
7092 pmap_unmapdev(vm_offset_t va, vm_size_t size)
7094 struct pmap_preinit_mapping *ppim;
7098 /* If we gave a direct map region in pmap_mapdev, do nothing */
7099 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
7101 offset = va & PAGE_MASK;
7102 size = round_page(offset + size);
7103 va = trunc_page(va);
7104 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7105 ppim = pmap_preinit_mapping + i;
7106 if (ppim->va == va && ppim->sz == size) {
7107 if (pmap_initialized)
7113 if (va + size == virtual_avail)
7118 if (pmap_initialized)
7123 * Tries to demote a 1GB page mapping.
7126 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
7128 pdp_entry_t newpdpe, oldpdpe;
7129 pd_entry_t *firstpde, newpde, *pde;
7130 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7134 PG_A = pmap_accessed_bit(pmap);
7135 PG_M = pmap_modified_bit(pmap);
7136 PG_V = pmap_valid_bit(pmap);
7137 PG_RW = pmap_rw_bit(pmap);
7139 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7141 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
7142 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
7143 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
7144 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
7145 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
7146 " in pmap %p", va, pmap);
7149 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
7150 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
7151 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
7152 KASSERT((oldpdpe & PG_A) != 0,
7153 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
7154 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
7155 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
7159 * Initialize the page directory page.
7161 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
7167 * Demote the mapping.
7172 * Invalidate a stale recursive mapping of the page directory page.
7174 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
7176 pmap_pdpe_demotions++;
7177 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
7178 " in pmap %p", va, pmap);
7183 * Sets the memory attribute for the specified page.
7186 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7189 m->md.pat_mode = ma;
7192 * If "m" is a normal page, update its direct mapping. This update
7193 * can be relied upon to perform any cache operations that are
7194 * required for data coherence.
7196 if ((m->flags & PG_FICTITIOUS) == 0 &&
7197 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7199 panic("memory attribute change on the direct map failed");
7203 * Changes the specified virtual address range's memory type to that given by
7204 * the parameter "mode". The specified virtual address range must be
7205 * completely contained within either the direct map or the kernel map. If
7206 * the virtual address range is contained within the kernel map, then the
7207 * memory type for each of the corresponding ranges of the direct map is also
7208 * changed. (The corresponding ranges of the direct map are those ranges that
7209 * map the same physical pages as the specified virtual address range.) These
7210 * changes to the direct map are necessary because Intel describes the
7211 * behavior of their processors as "undefined" if two or more mappings to the
7212 * same physical page have different memory types.
7214 * Returns zero if the change completed successfully, and either EINVAL or
7215 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7216 * of the virtual address range was not mapped, and ENOMEM is returned if
7217 * there was insufficient memory available to complete the change. In the
7218 * latter case, the memory type may have been changed on some part of the
7219 * virtual address range or the direct map.
7222 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7226 PMAP_LOCK(kernel_pmap);
7227 error = pmap_change_attr_locked(va, size, mode);
7228 PMAP_UNLOCK(kernel_pmap);
7233 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7235 vm_offset_t base, offset, tmpva;
7236 vm_paddr_t pa_start, pa_end, pa_end1;
7240 int cache_bits_pte, cache_bits_pde, error;
7243 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7244 base = trunc_page(va);
7245 offset = va & PAGE_MASK;
7246 size = round_page(offset + size);
7249 * Only supported on kernel virtual addresses, including the direct
7250 * map but excluding the recursive map.
7252 if (base < DMAP_MIN_ADDRESS)
7255 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7256 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7260 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7261 * into 4KB pages if required.
7263 for (tmpva = base; tmpva < base + size; ) {
7264 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7265 if (pdpe == NULL || *pdpe == 0)
7267 if (*pdpe & PG_PS) {
7269 * If the current 1GB page already has the required
7270 * memory type, then we need not demote this page. Just
7271 * increment tmpva to the next 1GB page frame.
7273 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7274 tmpva = trunc_1gpage(tmpva) + NBPDP;
7279 * If the current offset aligns with a 1GB page frame
7280 * and there is at least 1GB left within the range, then
7281 * we need not break down this page into 2MB pages.
7283 if ((tmpva & PDPMASK) == 0 &&
7284 tmpva + PDPMASK < base + size) {
7288 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7291 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7296 * If the current 2MB page already has the required
7297 * memory type, then we need not demote this page. Just
7298 * increment tmpva to the next 2MB page frame.
7300 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7301 tmpva = trunc_2mpage(tmpva) + NBPDR;
7306 * If the current offset aligns with a 2MB page frame
7307 * and there is at least 2MB left within the range, then
7308 * we need not break down this page into 4KB pages.
7310 if ((tmpva & PDRMASK) == 0 &&
7311 tmpva + PDRMASK < base + size) {
7315 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7318 pte = pmap_pde_to_pte(pde, tmpva);
7326 * Ok, all the pages exist, so run through them updating their
7327 * cache mode if required.
7329 pa_start = pa_end = 0;
7330 for (tmpva = base; tmpva < base + size; ) {
7331 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7332 if (*pdpe & PG_PS) {
7333 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7334 pmap_pde_attr(pdpe, cache_bits_pde,
7338 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7339 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7340 if (pa_start == pa_end) {
7341 /* Start physical address run. */
7342 pa_start = *pdpe & PG_PS_FRAME;
7343 pa_end = pa_start + NBPDP;
7344 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7347 /* Run ended, update direct map. */
7348 error = pmap_change_attr_locked(
7349 PHYS_TO_DMAP(pa_start),
7350 pa_end - pa_start, mode);
7353 /* Start physical address run. */
7354 pa_start = *pdpe & PG_PS_FRAME;
7355 pa_end = pa_start + NBPDP;
7358 tmpva = trunc_1gpage(tmpva) + NBPDP;
7361 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7363 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7364 pmap_pde_attr(pde, cache_bits_pde,
7368 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7369 (*pde & PG_PS_FRAME) < dmaplimit) {
7370 if (pa_start == pa_end) {
7371 /* Start physical address run. */
7372 pa_start = *pde & PG_PS_FRAME;
7373 pa_end = pa_start + NBPDR;
7374 } else if (pa_end == (*pde & PG_PS_FRAME))
7377 /* Run ended, update direct map. */
7378 error = pmap_change_attr_locked(
7379 PHYS_TO_DMAP(pa_start),
7380 pa_end - pa_start, mode);
7383 /* Start physical address run. */
7384 pa_start = *pde & PG_PS_FRAME;
7385 pa_end = pa_start + NBPDR;
7388 tmpva = trunc_2mpage(tmpva) + NBPDR;
7390 pte = pmap_pde_to_pte(pde, tmpva);
7391 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7392 pmap_pte_attr(pte, cache_bits_pte,
7396 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7397 (*pte & PG_FRAME) < dmaplimit) {
7398 if (pa_start == pa_end) {
7399 /* Start physical address run. */
7400 pa_start = *pte & PG_FRAME;
7401 pa_end = pa_start + PAGE_SIZE;
7402 } else if (pa_end == (*pte & PG_FRAME))
7403 pa_end += PAGE_SIZE;
7405 /* Run ended, update direct map. */
7406 error = pmap_change_attr_locked(
7407 PHYS_TO_DMAP(pa_start),
7408 pa_end - pa_start, mode);
7411 /* Start physical address run. */
7412 pa_start = *pte & PG_FRAME;
7413 pa_end = pa_start + PAGE_SIZE;
7419 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7420 pa_end1 = MIN(pa_end, dmaplimit);
7421 if (pa_start != pa_end1)
7422 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7423 pa_end1 - pa_start, mode);
7427 * Flush CPU caches if required to make sure any data isn't cached that
7428 * shouldn't be, etc.
7431 pmap_invalidate_range(kernel_pmap, base, tmpva);
7432 pmap_invalidate_cache_range(base, tmpva);
7438 * Demotes any mapping within the direct map region that covers more than the
7439 * specified range of physical addresses. This range's size must be a power
7440 * of two and its starting address must be a multiple of its size. Since the
7441 * demotion does not change any attributes of the mapping, a TLB invalidation
7442 * is not mandatory. The caller may, however, request a TLB invalidation.
7445 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7454 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7455 KASSERT((base & (len - 1)) == 0,
7456 ("pmap_demote_DMAP: base is not a multiple of len"));
7457 if (len < NBPDP && base < dmaplimit) {
7458 va = PHYS_TO_DMAP(base);
7460 PMAP_LOCK(kernel_pmap);
7461 pdpe = pmap_pdpe(kernel_pmap, va);
7462 if ((*pdpe & X86_PG_V) == 0)
7463 panic("pmap_demote_DMAP: invalid PDPE");
7464 if ((*pdpe & PG_PS) != 0) {
7465 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7466 panic("pmap_demote_DMAP: PDPE failed");
7470 pde = pmap_pdpe_to_pde(pdpe, va);
7471 if ((*pde & X86_PG_V) == 0)
7472 panic("pmap_demote_DMAP: invalid PDE");
7473 if ((*pde & PG_PS) != 0) {
7474 if (!pmap_demote_pde(kernel_pmap, pde, va))
7475 panic("pmap_demote_DMAP: PDE failed");
7479 if (changed && invalidate)
7480 pmap_invalidate_page(kernel_pmap, va);
7481 PMAP_UNLOCK(kernel_pmap);
7486 * perform the pmap work for mincore
7489 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7492 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7496 PG_A = pmap_accessed_bit(pmap);
7497 PG_M = pmap_modified_bit(pmap);
7498 PG_V = pmap_valid_bit(pmap);
7499 PG_RW = pmap_rw_bit(pmap);
7503 pdep = pmap_pde(pmap, addr);
7504 if (pdep != NULL && (*pdep & PG_V)) {
7505 if (*pdep & PG_PS) {
7507 /* Compute the physical address of the 4KB page. */
7508 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7510 val = MINCORE_SUPER;
7512 pte = *pmap_pde_to_pte(pdep, addr);
7513 pa = pte & PG_FRAME;
7521 if ((pte & PG_V) != 0) {
7522 val |= MINCORE_INCORE;
7523 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7524 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7525 if ((pte & PG_A) != 0)
7526 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7528 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7529 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7530 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7531 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7532 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7535 PA_UNLOCK_COND(*locked_pa);
7541 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7543 uint32_t gen, new_gen, pcid_next;
7545 CRITICAL_ASSERT(curthread);
7546 gen = PCPU_GET(pcid_gen);
7547 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7548 return (pti ? 0 : CR3_PCID_SAVE);
7549 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7550 return (CR3_PCID_SAVE);
7551 pcid_next = PCPU_GET(pcid_next);
7552 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7553 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7554 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7555 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7556 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7560 PCPU_SET(pcid_gen, new_gen);
7561 pcid_next = PMAP_PCID_KERN + 1;
7565 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7566 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7567 PCPU_SET(pcid_next, pcid_next + 1);
7572 pmap_pcid_alloc_checked(pmap_t pmap, u_int cpuid)
7576 cached = pmap_pcid_alloc(pmap, cpuid);
7577 KASSERT(pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7578 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7579 pmap->pm_pcids[cpuid].pm_pcid));
7580 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7581 pmap == kernel_pmap,
7582 ("non-kernel pmap pmap %p cpu %d pcid %#x",
7583 pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7588 pmap_activate_sw_pti_post(pmap_t pmap)
7591 if (pmap->pm_ucr3 != PMAP_NO_CR3)
7592 PCPU_GET(tssp)->tss_rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7593 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7597 pmap_activate_sw_pcid_pti(pmap_t pmap, u_int cpuid, const bool invpcid_works1)
7599 struct invpcid_descr d;
7600 uint64_t cached, cr3, kcr3, ucr3;
7602 cached = pmap_pcid_alloc_checked(pmap, cpuid);
7604 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
7605 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid);
7606 PCPU_SET(curpmap, pmap);
7607 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7608 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7611 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7613 * Explicitly invalidate translations cached from the
7614 * user page table. They are not automatically
7615 * flushed by reload of cr3 with the kernel page table
7618 * Note that the if() condition is resolved statically
7619 * by using the function argument instead of
7620 * runtime-evaluated invpcid_works value.
7622 if (invpcid_works1) {
7623 d.pcid = PMAP_PCID_USER_PT |
7624 pmap->pm_pcids[cpuid].pm_pcid;
7627 invpcid(&d, INVPCID_CTX);
7629 pmap_pti_pcid_invalidate(ucr3, kcr3);
7633 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7634 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7636 PCPU_INC(pm_save_cnt);
7640 pmap_activate_sw_pcid_invpcid_pti(pmap_t pmap, u_int cpuid)
7643 pmap_activate_sw_pcid_pti(pmap, cpuid, true);
7644 pmap_activate_sw_pti_post(pmap);
7648 pmap_activate_sw_pcid_noinvpcid_pti(pmap_t pmap, u_int cpuid)
7653 * If the INVPCID instruction is not available,
7654 * invltlb_pcid_handler() is used to handle an invalidate_all
7655 * IPI, which checks for curpmap == smp_tlb_pmap. The below
7656 * sequence of operations has a window where %CR3 is loaded
7657 * with the new pmap's PML4 address, but the curpmap value has
7658 * not yet been updated. This causes the invltlb IPI handler,
7659 * which is called between the updates, to execute as a NOP,
7660 * which leaves stale TLB entries.
7662 * Note that the most typical use of pmap_activate_sw(), from
7663 * the context switch, is immune to this race, because
7664 * interrupts are disabled (while the thread lock is owned),
7665 * and the IPI happens after curpmap is updated. Protect
7666 * other callers in a similar way, by disabling interrupts
7667 * around the %cr3 register reload and curpmap assignment.
7669 rflags = intr_disable();
7670 pmap_activate_sw_pcid_pti(pmap, cpuid, false);
7671 intr_restore(rflags);
7672 pmap_activate_sw_pti_post(pmap);
7676 pmap_activate_sw_pcid_nopti(pmap_t pmap, u_int cpuid)
7678 uint64_t cached, cr3;
7680 cached = pmap_pcid_alloc_checked(pmap, cpuid);
7682 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
7683 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7685 PCPU_SET(curpmap, pmap);
7687 PCPU_INC(pm_save_cnt);
7691 pmap_activate_sw_pcid_noinvpcid_nopti(pmap_t pmap, u_int cpuid)
7695 rflags = intr_disable();
7696 pmap_activate_sw_pcid_nopti(pmap, cpuid);
7697 intr_restore(rflags);
7701 pmap_activate_sw_nopcid_nopti(pmap_t pmap, u_int cpuid __unused)
7704 load_cr3(pmap->pm_cr3);
7705 PCPU_SET(curpmap, pmap);
7709 pmap_activate_sw_nopcid_pti(pmap_t pmap, u_int cpuid __unused)
7712 pmap_activate_sw_nopcid_nopti(pmap, cpuid);
7713 PCPU_SET(kcr3, pmap->pm_cr3);
7714 PCPU_SET(ucr3, pmap->pm_ucr3);
7715 pmap_activate_sw_pti_post(pmap);
7718 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (pmap_t, u_int), static)
7721 if (pmap_pcid_enabled && pti && invpcid_works)
7722 return (pmap_activate_sw_pcid_invpcid_pti);
7723 else if (pmap_pcid_enabled && pti && !invpcid_works)
7724 return (pmap_activate_sw_pcid_noinvpcid_pti);
7725 else if (pmap_pcid_enabled && !pti && invpcid_works)
7726 return (pmap_activate_sw_pcid_nopti);
7727 else if (pmap_pcid_enabled && !pti && !invpcid_works)
7728 return (pmap_activate_sw_pcid_noinvpcid_nopti);
7729 else if (!pmap_pcid_enabled && pti)
7730 return (pmap_activate_sw_nopcid_pti);
7731 else /* if (!pmap_pcid_enabled && !pti) */
7732 return (pmap_activate_sw_nopcid_nopti);
7736 pmap_activate_sw(struct thread *td)
7738 pmap_t oldpmap, pmap;
7741 oldpmap = PCPU_GET(curpmap);
7742 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7743 if (oldpmap == pmap)
7745 cpuid = PCPU_GET(cpuid);
7747 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7749 CPU_SET(cpuid, &pmap->pm_active);
7751 pmap_activate_sw_mode(pmap, cpuid);
7753 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7755 CPU_CLR(cpuid, &oldpmap->pm_active);
7760 pmap_activate(struct thread *td)
7764 pmap_activate_sw(td);
7769 pmap_activate_boot(pmap_t pmap)
7775 * kernel_pmap must be never deactivated, and we ensure that
7776 * by never activating it at all.
7778 MPASS(pmap != kernel_pmap);
7780 cpuid = PCPU_GET(cpuid);
7782 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7784 CPU_SET(cpuid, &pmap->pm_active);
7786 PCPU_SET(curpmap, pmap);
7788 kcr3 = pmap->pm_cr3;
7789 if (pmap_pcid_enabled)
7790 kcr3 |= pmap->pm_pcids[cpuid].pm_pcid | CR3_PCID_SAVE;
7794 PCPU_SET(kcr3, kcr3);
7795 PCPU_SET(ucr3, PMAP_NO_CR3);
7799 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7804 * Increase the starting virtual address of the given mapping if a
7805 * different alignment might result in more superpage mappings.
7808 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7809 vm_offset_t *addr, vm_size_t size)
7811 vm_offset_t superpage_offset;
7815 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7816 offset += ptoa(object->pg_color);
7817 superpage_offset = offset & PDRMASK;
7818 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7819 (*addr & PDRMASK) == superpage_offset)
7821 if ((*addr & PDRMASK) < superpage_offset)
7822 *addr = (*addr & ~PDRMASK) + superpage_offset;
7824 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7828 static unsigned long num_dirty_emulations;
7829 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7830 &num_dirty_emulations, 0, NULL);
7832 static unsigned long num_accessed_emulations;
7833 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7834 &num_accessed_emulations, 0, NULL);
7836 static unsigned long num_superpage_accessed_emulations;
7837 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7838 &num_superpage_accessed_emulations, 0, NULL);
7840 static unsigned long ad_emulation_superpage_promotions;
7841 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7842 &ad_emulation_superpage_promotions, 0, NULL);
7843 #endif /* INVARIANTS */
7846 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7849 struct rwlock *lock;
7850 #if VM_NRESERVLEVEL > 0
7854 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7856 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7857 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7859 if (!pmap_emulate_ad_bits(pmap))
7862 PG_A = pmap_accessed_bit(pmap);
7863 PG_M = pmap_modified_bit(pmap);
7864 PG_V = pmap_valid_bit(pmap);
7865 PG_RW = pmap_rw_bit(pmap);
7871 pde = pmap_pde(pmap, va);
7872 if (pde == NULL || (*pde & PG_V) == 0)
7875 if ((*pde & PG_PS) != 0) {
7876 if (ftype == VM_PROT_READ) {
7878 atomic_add_long(&num_superpage_accessed_emulations, 1);
7886 pte = pmap_pde_to_pte(pde, va);
7887 if ((*pte & PG_V) == 0)
7890 if (ftype == VM_PROT_WRITE) {
7891 if ((*pte & PG_RW) == 0)
7894 * Set the modified and accessed bits simultaneously.
7896 * Intel EPT PTEs that do software emulation of A/D bits map
7897 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7898 * An EPT misconfiguration is triggered if the PTE is writable
7899 * but not readable (WR=10). This is avoided by setting PG_A
7900 * and PG_M simultaneously.
7902 *pte |= PG_M | PG_A;
7907 #if VM_NRESERVLEVEL > 0
7908 /* try to promote the mapping */
7909 if (va < VM_MAXUSER_ADDRESS)
7910 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7914 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7916 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7917 pmap_ps_enabled(pmap) &&
7918 (m->flags & PG_FICTITIOUS) == 0 &&
7919 vm_reserv_level_iffullpop(m) == 0) {
7920 pmap_promote_pde(pmap, pde, va, &lock);
7922 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7928 if (ftype == VM_PROT_WRITE)
7929 atomic_add_long(&num_dirty_emulations, 1);
7931 atomic_add_long(&num_accessed_emulations, 1);
7933 rv = 0; /* success */
7942 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7947 pt_entry_t *pte, PG_V;
7951 PG_V = pmap_valid_bit(pmap);
7954 pml4 = pmap_pml4e(pmap, va);
7956 if ((*pml4 & PG_V) == 0)
7959 pdp = pmap_pml4e_to_pdpe(pml4, va);
7961 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7964 pde = pmap_pdpe_to_pde(pdp, va);
7966 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7969 pte = pmap_pde_to_pte(pde, va);
7978 * Get the kernel virtual address of a set of physical pages. If there are
7979 * physical addresses not covered by the DMAP perform a transient mapping
7980 * that will be removed when calling pmap_unmap_io_transient.
7982 * \param page The pages the caller wishes to obtain the virtual
7983 * address on the kernel memory map.
7984 * \param vaddr On return contains the kernel virtual memory address
7985 * of the pages passed in the page parameter.
7986 * \param count Number of pages passed in.
7987 * \param can_fault TRUE if the thread using the mapped pages can take
7988 * page faults, FALSE otherwise.
7990 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7991 * finished or FALSE otherwise.
7995 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7996 boolean_t can_fault)
7999 boolean_t needs_mapping;
8001 int cache_bits, error __unused, i;
8004 * Allocate any KVA space that we need, this is done in a separate
8005 * loop to prevent calling vmem_alloc while pinned.
8007 needs_mapping = FALSE;
8008 for (i = 0; i < count; i++) {
8009 paddr = VM_PAGE_TO_PHYS(page[i]);
8010 if (__predict_false(paddr >= dmaplimit)) {
8011 error = vmem_alloc(kernel_arena, PAGE_SIZE,
8012 M_BESTFIT | M_WAITOK, &vaddr[i]);
8013 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
8014 needs_mapping = TRUE;
8016 vaddr[i] = PHYS_TO_DMAP(paddr);
8020 /* Exit early if everything is covered by the DMAP */
8025 * NB: The sequence of updating a page table followed by accesses
8026 * to the corresponding pages used in the !DMAP case is subject to
8027 * the situation described in the "AMD64 Architecture Programmer's
8028 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
8029 * Coherency Considerations". Therefore, issuing the INVLPG right
8030 * after modifying the PTE bits is crucial.
8034 for (i = 0; i < count; i++) {
8035 paddr = VM_PAGE_TO_PHYS(page[i]);
8036 if (paddr >= dmaplimit) {
8039 * Slow path, since we can get page faults
8040 * while mappings are active don't pin the
8041 * thread to the CPU and instead add a global
8042 * mapping visible to all CPUs.
8044 pmap_qenter(vaddr[i], &page[i], 1);
8046 pte = vtopte(vaddr[i]);
8047 cache_bits = pmap_cache_bits(kernel_pmap,
8048 page[i]->md.pat_mode, 0);
8049 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
8056 return (needs_mapping);
8060 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
8061 boolean_t can_fault)
8068 for (i = 0; i < count; i++) {
8069 paddr = VM_PAGE_TO_PHYS(page[i]);
8070 if (paddr >= dmaplimit) {
8072 pmap_qremove(vaddr[i], 1);
8073 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
8079 pmap_quick_enter_page(vm_page_t m)
8083 paddr = VM_PAGE_TO_PHYS(m);
8084 if (paddr < dmaplimit)
8085 return (PHYS_TO_DMAP(paddr));
8086 mtx_lock_spin(&qframe_mtx);
8087 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
8088 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
8089 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
8094 pmap_quick_remove_page(vm_offset_t addr)
8099 pte_store(vtopte(qframe), 0);
8101 mtx_unlock_spin(&qframe_mtx);
8105 pmap_pti_alloc_page(void)
8109 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8110 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
8111 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
8116 pmap_pti_free_page(vm_page_t m)
8119 KASSERT(m->wire_count > 0, ("page %p not wired", m));
8120 if (!vm_page_unwire_noq(m))
8122 vm_page_free_zero(m);
8136 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
8137 VM_OBJECT_WLOCK(pti_obj);
8138 pml4_pg = pmap_pti_alloc_page();
8139 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
8140 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
8141 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
8142 pdpe = pmap_pti_pdpe(va);
8143 pmap_pti_wire_pte(pdpe);
8145 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
8146 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
8147 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
8148 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
8149 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
8150 sizeof(struct gate_descriptor) * NIDT, false);
8151 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
8152 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
8154 /* Doublefault stack IST 1 */
8155 va = common_tss[i].tss_ist1;
8156 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8157 /* NMI stack IST 2 */
8158 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
8159 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8160 /* MC# stack IST 3 */
8161 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
8162 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8163 /* DB# stack IST 4 */
8164 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
8165 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8167 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
8168 (vm_offset_t)etext, true);
8169 pti_finalized = true;
8170 VM_OBJECT_WUNLOCK(pti_obj);
8172 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
8174 static pdp_entry_t *
8175 pmap_pti_pdpe(vm_offset_t va)
8177 pml4_entry_t *pml4e;
8180 vm_pindex_t pml4_idx;
8183 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8185 pml4_idx = pmap_pml4e_index(va);
8186 pml4e = &pti_pml4[pml4_idx];
8190 panic("pml4 alloc after finalization\n");
8191 m = pmap_pti_alloc_page();
8193 pmap_pti_free_page(m);
8194 mphys = *pml4e & ~PAGE_MASK;
8196 mphys = VM_PAGE_TO_PHYS(m);
8197 *pml4e = mphys | X86_PG_RW | X86_PG_V;
8200 mphys = *pml4e & ~PAGE_MASK;
8202 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
8207 pmap_pti_wire_pte(void *pte)
8211 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8212 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8217 pmap_pti_unwire_pde(void *pde, bool only_ref)
8221 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8222 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
8223 MPASS(m->wire_count > 0);
8224 MPASS(only_ref || m->wire_count > 1);
8225 pmap_pti_free_page(m);
8229 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
8234 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8235 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8236 MPASS(m->wire_count > 0);
8237 if (pmap_pti_free_page(m)) {
8238 pde = pmap_pti_pde(va);
8239 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
8241 pmap_pti_unwire_pde(pde, false);
8246 pmap_pti_pde(vm_offset_t va)
8254 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8256 pdpe = pmap_pti_pdpe(va);
8258 m = pmap_pti_alloc_page();
8260 pmap_pti_free_page(m);
8261 MPASS((*pdpe & X86_PG_PS) == 0);
8262 mphys = *pdpe & ~PAGE_MASK;
8264 mphys = VM_PAGE_TO_PHYS(m);
8265 *pdpe = mphys | X86_PG_RW | X86_PG_V;
8268 MPASS((*pdpe & X86_PG_PS) == 0);
8269 mphys = *pdpe & ~PAGE_MASK;
8272 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8273 pd_idx = pmap_pde_index(va);
8279 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8286 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8288 pde = pmap_pti_pde(va);
8289 if (unwire_pde != NULL) {
8291 pmap_pti_wire_pte(pde);
8294 m = pmap_pti_alloc_page();
8296 pmap_pti_free_page(m);
8297 MPASS((*pde & X86_PG_PS) == 0);
8298 mphys = *pde & ~(PAGE_MASK | pg_nx);
8300 mphys = VM_PAGE_TO_PHYS(m);
8301 *pde = mphys | X86_PG_RW | X86_PG_V;
8302 if (unwire_pde != NULL)
8303 *unwire_pde = false;
8306 MPASS((*pde & X86_PG_PS) == 0);
8307 mphys = *pde & ~(PAGE_MASK | pg_nx);
8310 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8311 pte += pmap_pte_index(va);
8317 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8321 pt_entry_t *pte, ptev;
8324 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8326 sva = trunc_page(sva);
8327 MPASS(sva > VM_MAXUSER_ADDRESS);
8328 eva = round_page(eva);
8330 for (; sva < eva; sva += PAGE_SIZE) {
8331 pte = pmap_pti_pte(sva, &unwire_pde);
8332 pa = pmap_kextract(sva);
8333 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8334 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8335 VM_MEMATTR_DEFAULT, FALSE);
8337 pte_store(pte, ptev);
8338 pmap_pti_wire_pte(pte);
8340 KASSERT(!pti_finalized,
8341 ("pti overlap after fin %#lx %#lx %#lx",
8343 KASSERT(*pte == ptev,
8344 ("pti non-identical pte after fin %#lx %#lx %#lx",
8348 pde = pmap_pti_pde(sva);
8349 pmap_pti_unwire_pde(pde, true);
8355 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8360 VM_OBJECT_WLOCK(pti_obj);
8361 pmap_pti_add_kva_locked(sva, eva, exec);
8362 VM_OBJECT_WUNLOCK(pti_obj);
8366 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8373 sva = rounddown2(sva, PAGE_SIZE);
8374 MPASS(sva > VM_MAXUSER_ADDRESS);
8375 eva = roundup2(eva, PAGE_SIZE);
8377 VM_OBJECT_WLOCK(pti_obj);
8378 for (va = sva; va < eva; va += PAGE_SIZE) {
8379 pte = pmap_pti_pte(va, NULL);
8380 KASSERT((*pte & X86_PG_V) != 0,
8381 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8382 (u_long)pte, *pte));
8384 pmap_pti_unwire_pte(pte, va);
8386 pmap_invalidate_range(kernel_pmap, sva, eva);
8387 VM_OBJECT_WUNLOCK(pti_obj);
8390 #include "opt_ddb.h"
8392 #include <sys/kdb.h>
8393 #include <ddb/ddb.h>
8395 DB_SHOW_COMMAND(pte, pmap_print_pte)
8401 pt_entry_t *pte, PG_V;
8405 db_printf("show pte addr\n");
8408 va = (vm_offset_t)addr;
8410 if (kdb_thread != NULL)
8411 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
8413 pmap = PCPU_GET(curpmap);
8415 PG_V = pmap_valid_bit(pmap);
8416 pml4 = pmap_pml4e(pmap, va);
8417 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8418 if ((*pml4 & PG_V) == 0) {
8422 pdp = pmap_pml4e_to_pdpe(pml4, va);
8423 db_printf(" pdpe %#016lx", *pdp);
8424 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8428 pde = pmap_pdpe_to_pde(pdp, va);
8429 db_printf(" pde %#016lx", *pde);
8430 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8434 pte = pmap_pde_to_pte(pde, va);
8435 db_printf(" pte %#016lx\n", *pte);
8438 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8443 a = (vm_paddr_t)addr;
8444 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8446 db_printf("show phys2dmap addr\n");