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 <machine/cpu.h>
150 #include <machine/cputypes.h>
151 #include <machine/md_var.h>
152 #include <machine/pcb.h>
153 #include <machine/specialreg.h>
155 #include <machine/smp.h>
157 #include <machine/tss.h>
159 static __inline boolean_t
160 pmap_type_guest(pmap_t pmap)
163 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
166 static __inline boolean_t
167 pmap_emulate_ad_bits(pmap_t pmap)
170 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
173 static __inline pt_entry_t
174 pmap_valid_bit(pmap_t pmap)
178 switch (pmap->pm_type) {
184 if (pmap_emulate_ad_bits(pmap))
185 mask = EPT_PG_EMUL_V;
190 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
196 static __inline pt_entry_t
197 pmap_rw_bit(pmap_t pmap)
201 switch (pmap->pm_type) {
207 if (pmap_emulate_ad_bits(pmap))
208 mask = EPT_PG_EMUL_RW;
213 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
219 static pt_entry_t pg_g;
221 static __inline pt_entry_t
222 pmap_global_bit(pmap_t pmap)
226 switch (pmap->pm_type) {
235 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
241 static __inline pt_entry_t
242 pmap_accessed_bit(pmap_t pmap)
246 switch (pmap->pm_type) {
252 if (pmap_emulate_ad_bits(pmap))
258 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
264 static __inline pt_entry_t
265 pmap_modified_bit(pmap_t pmap)
269 switch (pmap->pm_type) {
275 if (pmap_emulate_ad_bits(pmap))
281 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
287 #if !defined(DIAGNOSTIC)
288 #ifdef __GNUC_GNU_INLINE__
289 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
291 #define PMAP_INLINE extern inline
298 #define PV_STAT(x) do { x ; } while (0)
300 #define PV_STAT(x) do { } while (0)
303 #define pa_index(pa) ((pa) >> PDRSHIFT)
304 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
306 #define NPV_LIST_LOCKS MAXCPU
308 #define PHYS_TO_PV_LIST_LOCK(pa) \
309 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
311 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
312 struct rwlock **_lockp = (lockp); \
313 struct rwlock *_new_lock; \
315 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
316 if (_new_lock != *_lockp) { \
317 if (*_lockp != NULL) \
318 rw_wunlock(*_lockp); \
319 *_lockp = _new_lock; \
324 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
325 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
327 #define RELEASE_PV_LIST_LOCK(lockp) do { \
328 struct rwlock **_lockp = (lockp); \
330 if (*_lockp != NULL) { \
331 rw_wunlock(*_lockp); \
336 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
337 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
339 struct pmap kernel_pmap_store;
341 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
342 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
345 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
346 "Number of kernel page table pages allocated on bootup");
349 vm_paddr_t dmaplimit;
350 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
353 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
355 static int pat_works = 1;
356 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
357 "Is page attribute table fully functional?");
359 static int pg_ps_enabled = 1;
360 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
361 &pg_ps_enabled, 0, "Are large page mappings enabled?");
363 #define PAT_INDEX_SIZE 8
364 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
366 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
367 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
368 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
369 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
371 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
372 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
373 static int ndmpdpphys; /* number of DMPDPphys pages */
376 * pmap_mapdev support pre initialization (i.e. console)
378 #define PMAP_PREINIT_MAPPING_COUNT 8
379 static struct pmap_preinit_mapping {
384 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
385 static int pmap_initialized;
388 * Data for the pv entry allocation mechanism.
389 * Updates to pv_invl_gen are protected by the pv_list_locks[]
390 * elements, but reads are not.
392 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
393 static struct mtx __exclusive_cache_line pv_chunks_mutex;
394 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
395 static u_long pv_invl_gen[NPV_LIST_LOCKS];
396 static struct md_page *pv_table;
397 static struct md_page pv_dummy;
400 * All those kernel PT submaps that BSD is so fond of
402 pt_entry_t *CMAP1 = NULL;
404 static vm_offset_t qframe = 0;
405 static struct mtx qframe_mtx;
407 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
409 int pmap_pcid_enabled = 1;
410 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
411 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
412 int invpcid_works = 0;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
414 "Is the invpcid instruction available ?");
417 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
419 "Page Table Isolation enabled");
420 static vm_object_t pti_obj;
421 static pml4_entry_t *pti_pml4;
422 static vm_pindex_t pti_pg_idx;
423 static bool pti_finalized;
426 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
433 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
435 return (sysctl_handle_64(oidp, &res, 0, req));
437 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
438 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
439 "Count of saved TLB context on switch");
441 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
442 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
443 static struct mtx invl_gen_mtx;
444 static u_long pmap_invl_gen = 0;
445 /* Fake lock object to satisfy turnstiles interface. */
446 static struct lock_object invl_gen_ts = {
454 return (curthread->td_md.md_invl_gen.gen == 0);
457 #define PMAP_ASSERT_NOT_IN_DI() \
458 KASSERT(pmap_not_in_di(), ("DI already started"))
461 * Start a new Delayed Invalidation (DI) block of code, executed by
462 * the current thread. Within a DI block, the current thread may
463 * destroy both the page table and PV list entries for a mapping and
464 * then release the corresponding PV list lock before ensuring that
465 * the mapping is flushed from the TLBs of any processors with the
469 pmap_delayed_invl_started(void)
471 struct pmap_invl_gen *invl_gen;
474 invl_gen = &curthread->td_md.md_invl_gen;
475 PMAP_ASSERT_NOT_IN_DI();
476 mtx_lock(&invl_gen_mtx);
477 if (LIST_EMPTY(&pmap_invl_gen_tracker))
478 currgen = pmap_invl_gen;
480 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
481 invl_gen->gen = currgen + 1;
482 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
483 mtx_unlock(&invl_gen_mtx);
487 * Finish the DI block, previously started by the current thread. All
488 * required TLB flushes for the pages marked by
489 * pmap_delayed_invl_page() must be finished before this function is
492 * This function works by bumping the global DI generation number to
493 * the generation number of the current thread's DI, unless there is a
494 * pending DI that started earlier. In the latter case, bumping the
495 * global DI generation number would incorrectly signal that the
496 * earlier DI had finished. Instead, this function bumps the earlier
497 * DI's generation number to match the generation number of the
498 * current thread's DI.
501 pmap_delayed_invl_finished(void)
503 struct pmap_invl_gen *invl_gen, *next;
504 struct turnstile *ts;
506 invl_gen = &curthread->td_md.md_invl_gen;
507 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
508 mtx_lock(&invl_gen_mtx);
509 next = LIST_NEXT(invl_gen, link);
511 turnstile_chain_lock(&invl_gen_ts);
512 ts = turnstile_lookup(&invl_gen_ts);
513 pmap_invl_gen = invl_gen->gen;
515 turnstile_broadcast(ts, TS_SHARED_QUEUE);
516 turnstile_unpend(ts, TS_SHARED_LOCK);
518 turnstile_chain_unlock(&invl_gen_ts);
520 next->gen = invl_gen->gen;
522 LIST_REMOVE(invl_gen, link);
523 mtx_unlock(&invl_gen_mtx);
528 static long invl_wait;
529 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
530 "Number of times DI invalidation blocked pmap_remove_all/write");
534 pmap_delayed_invl_genp(vm_page_t m)
537 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
541 * Ensure that all currently executing DI blocks, that need to flush
542 * TLB for the given page m, actually flushed the TLB at the time the
543 * function returned. If the page m has an empty PV list and we call
544 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
545 * valid mapping for the page m in either its page table or TLB.
547 * This function works by blocking until the global DI generation
548 * number catches up with the generation number associated with the
549 * given page m and its PV list. Since this function's callers
550 * typically own an object lock and sometimes own a page lock, it
551 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
555 pmap_delayed_invl_wait(vm_page_t m)
557 struct turnstile *ts;
560 bool accounted = false;
563 m_gen = pmap_delayed_invl_genp(m);
564 while (*m_gen > pmap_invl_gen) {
567 atomic_add_long(&invl_wait, 1);
571 ts = turnstile_trywait(&invl_gen_ts);
572 if (*m_gen > pmap_invl_gen)
573 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
575 turnstile_cancel(ts);
580 * Mark the page m's PV list as participating in the current thread's
581 * DI block. Any threads concurrently using m's PV list to remove or
582 * restrict all mappings to m will wait for the current thread's DI
583 * block to complete before proceeding.
585 * The function works by setting the DI generation number for m's PV
586 * list to at least the DI generation number of the current thread.
587 * This forces a caller of pmap_delayed_invl_wait() to block until
588 * current thread calls pmap_delayed_invl_finished().
591 pmap_delayed_invl_page(vm_page_t m)
595 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
596 gen = curthread->td_md.md_invl_gen.gen;
599 m_gen = pmap_delayed_invl_genp(m);
607 static caddr_t crashdumpmap;
610 * Internal flags for pmap_enter()'s helper functions.
612 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
613 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
615 static void free_pv_chunk(struct pv_chunk *pc);
616 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
617 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
618 static int popcnt_pc_map_pq(uint64_t *map);
619 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
620 static void reserve_pv_entries(pmap_t pmap, int needed,
621 struct rwlock **lockp);
622 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
623 struct rwlock **lockp);
624 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
625 u_int flags, struct rwlock **lockp);
626 #if VM_NRESERVLEVEL > 0
627 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
628 struct rwlock **lockp);
630 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
631 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
634 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
635 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
636 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
637 vm_offset_t va, struct rwlock **lockp);
638 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
640 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
641 vm_prot_t prot, struct rwlock **lockp);
642 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
643 u_int flags, vm_page_t m, struct rwlock **lockp);
644 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
645 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
646 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
647 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
648 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
650 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
651 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
652 #if VM_NRESERVLEVEL > 0
653 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
654 struct rwlock **lockp);
656 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
658 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
659 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
661 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
662 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
663 static void pmap_pti_wire_pte(void *pte);
664 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
665 struct spglist *free, struct rwlock **lockp);
666 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
667 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
668 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
669 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
670 struct spglist *free);
671 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
672 pd_entry_t *pde, struct spglist *free,
673 struct rwlock **lockp);
674 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
675 vm_page_t m, struct rwlock **lockp);
676 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
678 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
680 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
681 struct rwlock **lockp);
682 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
683 struct rwlock **lockp);
684 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
685 struct rwlock **lockp);
687 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
688 struct spglist *free);
689 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
691 /********************/
692 /* Inline functions */
693 /********************/
695 /* Return a non-clipped PD index for a given VA */
696 static __inline vm_pindex_t
697 pmap_pde_pindex(vm_offset_t va)
699 return (va >> PDRSHIFT);
703 /* Return a pointer to the PML4 slot that corresponds to a VA */
704 static __inline pml4_entry_t *
705 pmap_pml4e(pmap_t pmap, vm_offset_t va)
708 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
711 /* Return a pointer to the PDP slot that corresponds to a VA */
712 static __inline pdp_entry_t *
713 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
717 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
718 return (&pdpe[pmap_pdpe_index(va)]);
721 /* Return a pointer to the PDP slot that corresponds to a VA */
722 static __inline pdp_entry_t *
723 pmap_pdpe(pmap_t pmap, vm_offset_t va)
728 PG_V = pmap_valid_bit(pmap);
729 pml4e = pmap_pml4e(pmap, va);
730 if ((*pml4e & PG_V) == 0)
732 return (pmap_pml4e_to_pdpe(pml4e, va));
735 /* Return a pointer to the PD slot that corresponds to a VA */
736 static __inline pd_entry_t *
737 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
741 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
742 return (&pde[pmap_pde_index(va)]);
745 /* Return a pointer to the PD slot that corresponds to a VA */
746 static __inline pd_entry_t *
747 pmap_pde(pmap_t pmap, vm_offset_t va)
752 PG_V = pmap_valid_bit(pmap);
753 pdpe = pmap_pdpe(pmap, va);
754 if (pdpe == NULL || (*pdpe & PG_V) == 0)
756 return (pmap_pdpe_to_pde(pdpe, va));
759 /* Return a pointer to the PT slot that corresponds to a VA */
760 static __inline pt_entry_t *
761 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
765 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
766 return (&pte[pmap_pte_index(va)]);
769 /* Return a pointer to the PT slot that corresponds to a VA */
770 static __inline pt_entry_t *
771 pmap_pte(pmap_t pmap, vm_offset_t va)
776 PG_V = pmap_valid_bit(pmap);
777 pde = pmap_pde(pmap, va);
778 if (pde == NULL || (*pde & PG_V) == 0)
780 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
781 return ((pt_entry_t *)pde);
782 return (pmap_pde_to_pte(pde, va));
786 pmap_resident_count_inc(pmap_t pmap, int count)
789 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
790 pmap->pm_stats.resident_count += count;
794 pmap_resident_count_dec(pmap_t pmap, int count)
797 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
798 KASSERT(pmap->pm_stats.resident_count >= count,
799 ("pmap %p resident count underflow %ld %d", pmap,
800 pmap->pm_stats.resident_count, count));
801 pmap->pm_stats.resident_count -= count;
804 PMAP_INLINE pt_entry_t *
805 vtopte(vm_offset_t va)
807 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
809 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
811 return (PTmap + ((va >> PAGE_SHIFT) & mask));
814 static __inline pd_entry_t *
815 vtopde(vm_offset_t va)
817 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
819 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
821 return (PDmap + ((va >> PDRSHIFT) & mask));
825 allocpages(vm_paddr_t *firstaddr, int n)
830 bzero((void *)ret, n * PAGE_SIZE);
831 *firstaddr += n * PAGE_SIZE;
835 CTASSERT(powerof2(NDMPML4E));
837 /* number of kernel PDP slots */
838 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
841 nkpt_init(vm_paddr_t addr)
848 pt_pages = howmany(addr, 1 << PDRSHIFT);
849 pt_pages += NKPDPE(pt_pages);
852 * Add some slop beyond the bare minimum required for bootstrapping
855 * This is quite important when allocating KVA for kernel modules.
856 * The modules are required to be linked in the negative 2GB of
857 * the address space. If we run out of KVA in this region then
858 * pmap_growkernel() will need to allocate page table pages to map
859 * the entire 512GB of KVA space which is an unnecessary tax on
862 * Secondly, device memory mapped as part of setting up the low-
863 * level console(s) is taken from KVA, starting at virtual_avail.
864 * This is because cninit() is called after pmap_bootstrap() but
865 * before vm_init() and pmap_init(). 20MB for a frame buffer is
868 pt_pages += 32; /* 64MB additional slop. */
874 create_pagetables(vm_paddr_t *firstaddr)
876 int i, j, ndm1g, nkpdpe;
882 /* Allocate page table pages for the direct map */
883 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
884 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
886 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
887 if (ndmpdpphys > NDMPML4E) {
889 * Each NDMPML4E allows 512 GB, so limit to that,
890 * and then readjust ndmpdp and ndmpdpphys.
892 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
893 Maxmem = atop(NDMPML4E * NBPML4);
894 ndmpdpphys = NDMPML4E;
895 ndmpdp = NDMPML4E * NPDEPG;
897 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
899 if ((amd_feature & AMDID_PAGE1GB) != 0)
900 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
902 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
903 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
906 KPML4phys = allocpages(firstaddr, 1);
907 KPDPphys = allocpages(firstaddr, NKPML4E);
910 * Allocate the initial number of kernel page table pages required to
911 * bootstrap. We defer this until after all memory-size dependent
912 * allocations are done (e.g. direct map), so that we don't have to
913 * build in too much slop in our estimate.
915 * Note that when NKPML4E > 1, we have an empty page underneath
916 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
917 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
919 nkpt_init(*firstaddr);
920 nkpdpe = NKPDPE(nkpt);
922 KPTphys = allocpages(firstaddr, nkpt);
923 KPDphys = allocpages(firstaddr, nkpdpe);
925 /* Fill in the underlying page table pages */
926 /* Nominally read-only (but really R/W) from zero to physfree */
927 /* XXX not fully used, underneath 2M pages */
928 pt_p = (pt_entry_t *)KPTphys;
929 for (i = 0; ptoa(i) < *firstaddr; i++)
930 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
932 /* Now map the page tables at their location within PTmap */
933 pd_p = (pd_entry_t *)KPDphys;
934 for (i = 0; i < nkpt; i++)
935 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
937 /* Map from zero to end of allocations under 2M pages */
938 /* This replaces some of the KPTphys entries above */
939 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
940 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
944 * Because we map the physical blocks in 2M pages, adjust firstaddr
945 * to record the physical blocks we've actually mapped into kernel
946 * virtual address space.
948 *firstaddr = round_2mpage(*firstaddr);
950 /* And connect up the PD to the PDP (leaving room for L4 pages) */
951 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
952 for (i = 0; i < nkpdpe; i++)
953 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
957 * Now, set up the direct map region using 2MB and/or 1GB pages. If
958 * the end of physical memory is not aligned to a 1GB page boundary,
959 * then the residual physical memory is mapped with 2MB pages. Later,
960 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
961 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
962 * that are partially used.
964 pd_p = (pd_entry_t *)DMPDphys;
965 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
966 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
967 /* Preset PG_M and PG_A because demotion expects it. */
968 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
969 X86_PG_M | X86_PG_A | pg_nx;
971 pdp_p = (pdp_entry_t *)DMPDPphys;
972 for (i = 0; i < ndm1g; i++) {
973 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
974 /* Preset PG_M and PG_A because demotion expects it. */
975 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
976 X86_PG_M | X86_PG_A | pg_nx;
978 for (j = 0; i < ndmpdp; i++, j++) {
979 pdp_p[i] = DMPDphys + ptoa(j);
980 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
983 /* And recursively map PML4 to itself in order to get PTmap */
984 p4_p = (pml4_entry_t *)KPML4phys;
985 p4_p[PML4PML4I] = KPML4phys;
986 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
988 /* Connect the Direct Map slot(s) up to the PML4. */
989 for (i = 0; i < ndmpdpphys; i++) {
990 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
991 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
994 /* Connect the KVA slots up to the PML4 */
995 for (i = 0; i < NKPML4E; i++) {
996 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
997 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1002 * Bootstrap the system enough to run with virtual memory.
1004 * On amd64 this is called after mapping has already been enabled
1005 * and just syncs the pmap module with what has already been done.
1006 * [We can't call it easily with mapping off since the kernel is not
1007 * mapped with PA == VA, hence we would have to relocate every address
1008 * from the linked base (virtual) address "KERNBASE" to the actual
1009 * (physical) address starting relative to 0]
1012 pmap_bootstrap(vm_paddr_t *firstaddr)
1022 * Create an initial set of page tables to run the kernel in.
1024 create_pagetables(firstaddr);
1027 * Add a physical memory segment (vm_phys_seg) corresponding to the
1028 * preallocated kernel page table pages so that vm_page structures
1029 * representing these pages will be created. The vm_page structures
1030 * are required for promotion of the corresponding kernel virtual
1031 * addresses to superpage mappings.
1033 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1035 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1037 virtual_end = VM_MAX_KERNEL_ADDRESS;
1040 /* XXX do %cr0 as well */
1041 load_cr4(rcr4() | CR4_PGE);
1042 load_cr3(KPML4phys);
1043 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1044 load_cr4(rcr4() | CR4_SMEP);
1047 * Initialize the kernel pmap (which is statically allocated).
1049 PMAP_LOCK_INIT(kernel_pmap);
1050 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1051 kernel_pmap->pm_cr3 = KPML4phys;
1052 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1053 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1054 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1055 kernel_pmap->pm_flags = pmap_flags;
1058 * Initialize the TLB invalidations generation number lock.
1060 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1063 * Reserve some special page table entries/VA space for temporary
1066 #define SYSMAP(c, p, v, n) \
1067 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1073 * Crashdump maps. The first page is reused as CMAP1 for the
1076 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1077 CADDR1 = crashdumpmap;
1082 * Initialize the PAT MSR.
1083 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1084 * side-effect, invalidates stale PG_G TLB entries that might
1085 * have been created in our pre-boot environment.
1089 /* Initialize TLB Context Id. */
1090 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1091 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1092 /* Check for INVPCID support */
1093 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1095 for (i = 0; i < MAXCPU; i++) {
1096 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1097 kernel_pmap->pm_pcids[i].pm_gen = 1;
1099 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1100 PCPU_SET(pcid_gen, 1);
1102 * pcpu area for APs is zeroed during AP startup.
1103 * pc_pcid_next and pc_pcid_gen are initialized by AP
1104 * during pcpu setup.
1106 load_cr4(rcr4() | CR4_PCIDE);
1108 pmap_pcid_enabled = 0;
1113 * Setup the PAT MSR.
1118 int pat_table[PAT_INDEX_SIZE];
1123 /* Bail if this CPU doesn't implement PAT. */
1124 if ((cpu_feature & CPUID_PAT) == 0)
1127 /* Set default PAT index table. */
1128 for (i = 0; i < PAT_INDEX_SIZE; i++)
1130 pat_table[PAT_WRITE_BACK] = 0;
1131 pat_table[PAT_WRITE_THROUGH] = 1;
1132 pat_table[PAT_UNCACHEABLE] = 3;
1133 pat_table[PAT_WRITE_COMBINING] = 3;
1134 pat_table[PAT_WRITE_PROTECTED] = 3;
1135 pat_table[PAT_UNCACHED] = 3;
1137 /* Initialize default PAT entries. */
1138 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1139 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1140 PAT_VALUE(2, PAT_UNCACHED) |
1141 PAT_VALUE(3, PAT_UNCACHEABLE) |
1142 PAT_VALUE(4, PAT_WRITE_BACK) |
1143 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1144 PAT_VALUE(6, PAT_UNCACHED) |
1145 PAT_VALUE(7, PAT_UNCACHEABLE);
1149 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1150 * Program 5 and 6 as WP and WC.
1151 * Leave 4 and 7 as WB and UC.
1153 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1154 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1155 PAT_VALUE(6, PAT_WRITE_COMBINING);
1156 pat_table[PAT_UNCACHED] = 2;
1157 pat_table[PAT_WRITE_PROTECTED] = 5;
1158 pat_table[PAT_WRITE_COMBINING] = 6;
1161 * Just replace PAT Index 2 with WC instead of UC-.
1163 pat_msr &= ~PAT_MASK(2);
1164 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1165 pat_table[PAT_WRITE_COMBINING] = 2;
1170 load_cr4(cr4 & ~CR4_PGE);
1172 /* Disable caches (CD = 1, NW = 0). */
1174 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1176 /* Flushes caches and TLBs. */
1180 /* Update PAT and index table. */
1181 wrmsr(MSR_PAT, pat_msr);
1182 for (i = 0; i < PAT_INDEX_SIZE; i++)
1183 pat_index[i] = pat_table[i];
1185 /* Flush caches and TLBs again. */
1189 /* Restore caches and PGE. */
1195 * Initialize a vm_page's machine-dependent fields.
1198 pmap_page_init(vm_page_t m)
1201 TAILQ_INIT(&m->md.pv_list);
1202 m->md.pat_mode = PAT_WRITE_BACK;
1206 * Initialize the pmap module.
1207 * Called by vm_init, to initialize any structures that the pmap
1208 * system needs to map virtual memory.
1213 struct pmap_preinit_mapping *ppim;
1216 int error, i, pv_npg;
1219 * Initialize the vm page array entries for the kernel pmap's
1222 for (i = 0; i < nkpt; i++) {
1223 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1224 KASSERT(mpte >= vm_page_array &&
1225 mpte < &vm_page_array[vm_page_array_size],
1226 ("pmap_init: page table page is out of range"));
1227 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1228 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1229 mpte->wire_count = 1;
1234 * If the kernel is running on a virtual machine, then it must assume
1235 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1236 * be prepared for the hypervisor changing the vendor and family that
1237 * are reported by CPUID. Consequently, the workaround for AMD Family
1238 * 10h Erratum 383 is enabled if the processor's feature set does not
1239 * include at least one feature that is only supported by older Intel
1240 * or newer AMD processors.
1242 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1243 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1244 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1246 workaround_erratum383 = 1;
1249 * Are large page mappings enabled?
1251 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1252 if (pg_ps_enabled) {
1253 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1254 ("pmap_init: can't assign to pagesizes[1]"));
1255 pagesizes[1] = NBPDR;
1259 * Initialize the pv chunk list mutex.
1261 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1264 * Initialize the pool of pv list locks.
1266 for (i = 0; i < NPV_LIST_LOCKS; i++)
1267 rw_init(&pv_list_locks[i], "pmap pv list");
1270 * Calculate the size of the pv head table for superpages.
1272 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1275 * Allocate memory for the pv head table for superpages.
1277 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1279 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1281 for (i = 0; i < pv_npg; i++)
1282 TAILQ_INIT(&pv_table[i].pv_list);
1283 TAILQ_INIT(&pv_dummy.pv_list);
1285 pmap_initialized = 1;
1286 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1287 ppim = pmap_preinit_mapping + i;
1290 /* Make the direct map consistent */
1291 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1292 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1293 ppim->sz, ppim->mode);
1297 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1298 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1301 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1302 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1303 (vmem_addr_t *)&qframe);
1305 panic("qframe allocation failed");
1308 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1309 "2MB page mapping counters");
1311 static u_long pmap_pde_demotions;
1312 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1313 &pmap_pde_demotions, 0, "2MB page demotions");
1315 static u_long pmap_pde_mappings;
1316 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1317 &pmap_pde_mappings, 0, "2MB page mappings");
1319 static u_long pmap_pde_p_failures;
1320 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1321 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1323 static u_long pmap_pde_promotions;
1324 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1325 &pmap_pde_promotions, 0, "2MB page promotions");
1327 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1328 "1GB page mapping counters");
1330 static u_long pmap_pdpe_demotions;
1331 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1332 &pmap_pdpe_demotions, 0, "1GB page demotions");
1334 /***************************************************
1335 * Low level helper routines.....
1336 ***************************************************/
1339 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1341 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1343 switch (pmap->pm_type) {
1346 /* Verify that both PAT bits are not set at the same time */
1347 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1348 ("Invalid PAT bits in entry %#lx", entry));
1350 /* Swap the PAT bits if one of them is set */
1351 if ((entry & x86_pat_bits) != 0)
1352 entry ^= x86_pat_bits;
1356 * Nothing to do - the memory attributes are represented
1357 * the same way for regular pages and superpages.
1361 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1368 * Determine the appropriate bits to set in a PTE or PDE for a specified
1372 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1374 int cache_bits, pat_flag, pat_idx;
1376 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1377 panic("Unknown caching mode %d\n", mode);
1379 switch (pmap->pm_type) {
1382 /* The PAT bit is different for PTE's and PDE's. */
1383 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1385 /* Map the caching mode to a PAT index. */
1386 pat_idx = pat_index[mode];
1388 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1391 cache_bits |= pat_flag;
1393 cache_bits |= PG_NC_PCD;
1395 cache_bits |= PG_NC_PWT;
1399 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1403 panic("unsupported pmap type %d", pmap->pm_type);
1406 return (cache_bits);
1410 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1414 switch (pmap->pm_type) {
1417 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1420 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1423 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1430 pmap_ps_enabled(pmap_t pmap)
1433 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1437 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1440 switch (pmap->pm_type) {
1447 * This is a little bogus since the generation number is
1448 * supposed to be bumped up when a region of the address
1449 * space is invalidated in the page tables.
1451 * In this case the old PDE entry is valid but yet we want
1452 * to make sure that any mappings using the old entry are
1453 * invalidated in the TLB.
1455 * The reason this works as expected is because we rendezvous
1456 * "all" host cpus and force any vcpu context to exit as a
1459 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1462 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1464 pde_store(pde, newpde);
1468 * After changing the page size for the specified virtual address in the page
1469 * table, flush the corresponding entries from the processor's TLB. Only the
1470 * calling processor's TLB is affected.
1472 * The calling thread must be pinned to a processor.
1475 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1479 if (pmap_type_guest(pmap))
1482 KASSERT(pmap->pm_type == PT_X86,
1483 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1485 PG_G = pmap_global_bit(pmap);
1487 if ((newpde & PG_PS) == 0)
1488 /* Demotion: flush a specific 2MB page mapping. */
1490 else if ((newpde & PG_G) == 0)
1492 * Promotion: flush every 4KB page mapping from the TLB
1493 * because there are too many to flush individually.
1498 * Promotion: flush every 4KB page mapping from the TLB,
1499 * including any global (PG_G) mappings.
1507 * For SMP, these functions have to use the IPI mechanism for coherence.
1509 * N.B.: Before calling any of the following TLB invalidation functions,
1510 * the calling processor must ensure that all stores updating a non-
1511 * kernel page table are globally performed. Otherwise, another
1512 * processor could cache an old, pre-update entry without being
1513 * invalidated. This can happen one of two ways: (1) The pmap becomes
1514 * active on another processor after its pm_active field is checked by
1515 * one of the following functions but before a store updating the page
1516 * table is globally performed. (2) The pmap becomes active on another
1517 * processor before its pm_active field is checked but due to
1518 * speculative loads one of the following functions stills reads the
1519 * pmap as inactive on the other processor.
1521 * The kernel page table is exempt because its pm_active field is
1522 * immutable. The kernel page table is always active on every
1527 * Interrupt the cpus that are executing in the guest context.
1528 * This will force the vcpu to exit and the cached EPT mappings
1529 * will be invalidated by the host before the next vmresume.
1531 static __inline void
1532 pmap_invalidate_ept(pmap_t pmap)
1537 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1538 ("pmap_invalidate_ept: absurd pm_active"));
1541 * The TLB mappings associated with a vcpu context are not
1542 * flushed each time a different vcpu is chosen to execute.
1544 * This is in contrast with a process's vtop mappings that
1545 * are flushed from the TLB on each context switch.
1547 * Therefore we need to do more than just a TLB shootdown on
1548 * the active cpus in 'pmap->pm_active'. To do this we keep
1549 * track of the number of invalidations performed on this pmap.
1551 * Each vcpu keeps a cache of this counter and compares it
1552 * just before a vmresume. If the counter is out-of-date an
1553 * invept will be done to flush stale mappings from the TLB.
1555 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1558 * Force the vcpu to exit and trap back into the hypervisor.
1560 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1561 ipi_selected(pmap->pm_active, ipinum);
1566 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1569 struct invpcid_descr d;
1570 uint64_t kcr3, ucr3;
1574 if (pmap_type_guest(pmap)) {
1575 pmap_invalidate_ept(pmap);
1579 KASSERT(pmap->pm_type == PT_X86,
1580 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1583 if (pmap == kernel_pmap) {
1587 cpuid = PCPU_GET(cpuid);
1588 if (pmap == PCPU_GET(curpmap)) {
1590 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1592 * Disable context switching. pm_pcid
1593 * is recalculated on switch, which
1594 * might make us use wrong pcid below.
1597 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1599 if (invpcid_works) {
1600 d.pcid = pcid | PMAP_PCID_USER_PT;
1603 invpcid(&d, INVPCID_ADDR);
1605 kcr3 = pmap->pm_cr3 | pcid |
1607 ucr3 = pmap->pm_ucr3 | pcid |
1608 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1609 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1613 } else if (pmap_pcid_enabled)
1614 pmap->pm_pcids[cpuid].pm_gen = 0;
1615 if (pmap_pcid_enabled) {
1618 pmap->pm_pcids[i].pm_gen = 0;
1621 mask = &pmap->pm_active;
1623 smp_masked_invlpg(*mask, va, pmap);
1627 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1628 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1631 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1634 struct invpcid_descr d;
1636 uint64_t kcr3, ucr3;
1640 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1641 pmap_invalidate_all(pmap);
1645 if (pmap_type_guest(pmap)) {
1646 pmap_invalidate_ept(pmap);
1650 KASSERT(pmap->pm_type == PT_X86,
1651 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1654 cpuid = PCPU_GET(cpuid);
1655 if (pmap == kernel_pmap) {
1656 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1660 if (pmap == PCPU_GET(curpmap)) {
1661 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1663 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1665 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1666 if (invpcid_works) {
1667 d.pcid = pcid | PMAP_PCID_USER_PT;
1670 for (; d.addr < eva; d.addr +=
1672 invpcid(&d, INVPCID_ADDR);
1674 kcr3 = pmap->pm_cr3 | pcid |
1676 ucr3 = pmap->pm_ucr3 | pcid |
1677 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1678 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1683 } else if (pmap_pcid_enabled) {
1684 pmap->pm_pcids[cpuid].pm_gen = 0;
1686 if (pmap_pcid_enabled) {
1689 pmap->pm_pcids[i].pm_gen = 0;
1692 mask = &pmap->pm_active;
1694 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1699 pmap_invalidate_all(pmap_t pmap)
1702 struct invpcid_descr d;
1703 uint64_t kcr3, ucr3;
1707 if (pmap_type_guest(pmap)) {
1708 pmap_invalidate_ept(pmap);
1712 KASSERT(pmap->pm_type == PT_X86,
1713 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1716 if (pmap == kernel_pmap) {
1717 if (pmap_pcid_enabled && invpcid_works) {
1718 bzero(&d, sizeof(d));
1719 invpcid(&d, INVPCID_CTXGLOB);
1725 cpuid = PCPU_GET(cpuid);
1726 if (pmap == PCPU_GET(curpmap)) {
1727 if (pmap_pcid_enabled) {
1729 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1730 if (invpcid_works) {
1734 invpcid(&d, INVPCID_CTX);
1735 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1736 d.pcid |= PMAP_PCID_USER_PT;
1737 invpcid(&d, INVPCID_CTX);
1740 kcr3 = pmap->pm_cr3 | pcid;
1741 ucr3 = pmap->pm_ucr3;
1742 if (ucr3 != PMAP_NO_CR3) {
1743 ucr3 |= pcid | PMAP_PCID_USER_PT;
1744 pmap_pti_pcid_invalidate(ucr3,
1754 } else if (pmap_pcid_enabled) {
1755 pmap->pm_pcids[cpuid].pm_gen = 0;
1757 if (pmap_pcid_enabled) {
1760 pmap->pm_pcids[i].pm_gen = 0;
1763 mask = &pmap->pm_active;
1765 smp_masked_invltlb(*mask, pmap);
1770 pmap_invalidate_cache(void)
1780 cpuset_t invalidate; /* processors that invalidate their TLB */
1785 u_int store; /* processor that updates the PDE */
1789 pmap_update_pde_action(void *arg)
1791 struct pde_action *act = arg;
1793 if (act->store == PCPU_GET(cpuid))
1794 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1798 pmap_update_pde_teardown(void *arg)
1800 struct pde_action *act = arg;
1802 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1803 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1807 * Change the page size for the specified virtual address in a way that
1808 * prevents any possibility of the TLB ever having two entries that map the
1809 * same virtual address using different page sizes. This is the recommended
1810 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1811 * machine check exception for a TLB state that is improperly diagnosed as a
1815 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1817 struct pde_action act;
1818 cpuset_t active, other_cpus;
1822 cpuid = PCPU_GET(cpuid);
1823 other_cpus = all_cpus;
1824 CPU_CLR(cpuid, &other_cpus);
1825 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1828 active = pmap->pm_active;
1830 if (CPU_OVERLAP(&active, &other_cpus)) {
1832 act.invalidate = active;
1836 act.newpde = newpde;
1837 CPU_SET(cpuid, &active);
1838 smp_rendezvous_cpus(active,
1839 smp_no_rendezvous_barrier, pmap_update_pde_action,
1840 pmap_update_pde_teardown, &act);
1842 pmap_update_pde_store(pmap, pde, newpde);
1843 if (CPU_ISSET(cpuid, &active))
1844 pmap_update_pde_invalidate(pmap, va, newpde);
1850 * Normal, non-SMP, invalidation functions.
1853 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1855 struct invpcid_descr d;
1856 uint64_t kcr3, ucr3;
1859 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1863 KASSERT(pmap->pm_type == PT_X86,
1864 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1866 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1868 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1869 pmap->pm_ucr3 != PMAP_NO_CR3) {
1871 pcid = pmap->pm_pcids[0].pm_pcid;
1872 if (invpcid_works) {
1873 d.pcid = pcid | PMAP_PCID_USER_PT;
1876 invpcid(&d, INVPCID_ADDR);
1878 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1879 ucr3 = pmap->pm_ucr3 | pcid |
1880 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1881 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1885 } else if (pmap_pcid_enabled)
1886 pmap->pm_pcids[0].pm_gen = 0;
1890 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1892 struct invpcid_descr d;
1894 uint64_t kcr3, ucr3;
1896 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1900 KASSERT(pmap->pm_type == PT_X86,
1901 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1903 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1904 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1906 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1907 pmap->pm_ucr3 != PMAP_NO_CR3) {
1909 if (invpcid_works) {
1910 d.pcid = pmap->pm_pcids[0].pm_pcid |
1914 for (; d.addr < eva; d.addr += PAGE_SIZE)
1915 invpcid(&d, INVPCID_ADDR);
1917 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1918 pm_pcid | CR3_PCID_SAVE;
1919 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1920 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1921 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1925 } else if (pmap_pcid_enabled) {
1926 pmap->pm_pcids[0].pm_gen = 0;
1931 pmap_invalidate_all(pmap_t pmap)
1933 struct invpcid_descr d;
1934 uint64_t kcr3, ucr3;
1936 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1940 KASSERT(pmap->pm_type == PT_X86,
1941 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1943 if (pmap == kernel_pmap) {
1944 if (pmap_pcid_enabled && invpcid_works) {
1945 bzero(&d, sizeof(d));
1946 invpcid(&d, INVPCID_CTXGLOB);
1950 } else if (pmap == PCPU_GET(curpmap)) {
1951 if (pmap_pcid_enabled) {
1953 if (invpcid_works) {
1954 d.pcid = pmap->pm_pcids[0].pm_pcid;
1957 invpcid(&d, INVPCID_CTX);
1958 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1959 d.pcid |= PMAP_PCID_USER_PT;
1960 invpcid(&d, INVPCID_CTX);
1963 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
1964 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1965 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
1966 0].pm_pcid | PMAP_PCID_USER_PT;
1967 pmap_pti_pcid_invalidate(ucr3, kcr3);
1975 } else if (pmap_pcid_enabled) {
1976 pmap->pm_pcids[0].pm_gen = 0;
1981 pmap_invalidate_cache(void)
1988 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1991 pmap_update_pde_store(pmap, pde, newpde);
1992 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1993 pmap_update_pde_invalidate(pmap, va, newpde);
1995 pmap->pm_pcids[0].pm_gen = 0;
2000 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2004 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2005 * by a promotion that did not invalidate the 512 4KB page mappings
2006 * that might exist in the TLB. Consequently, at this point, the TLB
2007 * may hold both 4KB and 2MB page mappings for the address range [va,
2008 * va + NBPDR). Therefore, the entire range must be invalidated here.
2009 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2010 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2011 * single INVLPG suffices to invalidate the 2MB page mapping from the
2014 if ((pde & PG_PROMOTED) != 0)
2015 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2017 pmap_invalidate_page(pmap, va);
2020 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2023 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2027 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2029 KASSERT((sva & PAGE_MASK) == 0,
2030 ("pmap_invalidate_cache_range: sva not page-aligned"));
2031 KASSERT((eva & PAGE_MASK) == 0,
2032 ("pmap_invalidate_cache_range: eva not page-aligned"));
2035 if ((cpu_feature & CPUID_SS) != 0 && !force)
2036 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2037 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2038 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2040 * XXX: Some CPUs fault, hang, or trash the local APIC
2041 * registers if we use CLFLUSH on the local APIC
2042 * range. The local APIC is always uncached, so we
2043 * don't need to flush for that range anyway.
2045 if (pmap_kextract(sva) == lapic_paddr)
2049 * Otherwise, do per-cache line flush. Use the sfence
2050 * instruction to insure that previous stores are
2051 * included in the write-back. The processor
2052 * propagates flush to other processors in the cache
2056 for (; sva < eva; sva += cpu_clflush_line_size)
2059 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2060 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2061 if (pmap_kextract(sva) == lapic_paddr)
2064 * Writes are ordered by CLFLUSH on Intel CPUs.
2066 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2068 for (; sva < eva; sva += cpu_clflush_line_size)
2070 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2075 * No targeted cache flush methods are supported by CPU,
2076 * or the supplied range is bigger than 2MB.
2077 * Globally invalidate cache.
2079 pmap_invalidate_cache();
2084 * Remove the specified set of pages from the data and instruction caches.
2086 * In contrast to pmap_invalidate_cache_range(), this function does not
2087 * rely on the CPU's self-snoop feature, because it is intended for use
2088 * when moving pages into a different cache domain.
2091 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2093 vm_offset_t daddr, eva;
2097 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2098 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2099 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2100 pmap_invalidate_cache();
2104 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2106 for (i = 0; i < count; i++) {
2107 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2108 eva = daddr + PAGE_SIZE;
2109 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2118 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2124 * Routine: pmap_extract
2126 * Extract the physical page address associated
2127 * with the given map/virtual_address pair.
2130 pmap_extract(pmap_t pmap, vm_offset_t va)
2134 pt_entry_t *pte, PG_V;
2138 PG_V = pmap_valid_bit(pmap);
2140 pdpe = pmap_pdpe(pmap, va);
2141 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2142 if ((*pdpe & PG_PS) != 0)
2143 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2145 pde = pmap_pdpe_to_pde(pdpe, va);
2146 if ((*pde & PG_V) != 0) {
2147 if ((*pde & PG_PS) != 0) {
2148 pa = (*pde & PG_PS_FRAME) |
2151 pte = pmap_pde_to_pte(pde, va);
2152 pa = (*pte & PG_FRAME) |
2163 * Routine: pmap_extract_and_hold
2165 * Atomically extract and hold the physical page
2166 * with the given pmap and virtual address pair
2167 * if that mapping permits the given protection.
2170 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2172 pd_entry_t pde, *pdep;
2173 pt_entry_t pte, PG_RW, PG_V;
2179 PG_RW = pmap_rw_bit(pmap);
2180 PG_V = pmap_valid_bit(pmap);
2183 pdep = pmap_pde(pmap, va);
2184 if (pdep != NULL && (pde = *pdep)) {
2186 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2187 if (vm_page_pa_tryrelock(pmap, (pde &
2188 PG_PS_FRAME) | (va & PDRMASK), &pa))
2190 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2195 pte = *pmap_pde_to_pte(pdep, va);
2197 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2198 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2201 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2212 pmap_kextract(vm_offset_t va)
2217 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2218 pa = DMAP_TO_PHYS(va);
2222 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2225 * Beware of a concurrent promotion that changes the
2226 * PDE at this point! For example, vtopte() must not
2227 * be used to access the PTE because it would use the
2228 * new PDE. It is, however, safe to use the old PDE
2229 * because the page table page is preserved by the
2232 pa = *pmap_pde_to_pte(&pde, va);
2233 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2239 /***************************************************
2240 * Low level mapping routines.....
2241 ***************************************************/
2244 * Add a wired page to the kva.
2245 * Note: not SMP coherent.
2248 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2253 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2256 static __inline void
2257 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2263 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2264 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2268 * Remove a page from the kernel pagetables.
2269 * Note: not SMP coherent.
2272 pmap_kremove(vm_offset_t va)
2281 * Used to map a range of physical addresses into kernel
2282 * virtual address space.
2284 * The value passed in '*virt' is a suggested virtual address for
2285 * the mapping. Architectures which can support a direct-mapped
2286 * physical to virtual region can return the appropriate address
2287 * within that region, leaving '*virt' unchanged. Other
2288 * architectures should map the pages starting at '*virt' and
2289 * update '*virt' with the first usable address after the mapped
2293 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2295 return PHYS_TO_DMAP(start);
2300 * Add a list of wired pages to the kva
2301 * this routine is only used for temporary
2302 * kernel mappings that do not need to have
2303 * page modification or references recorded.
2304 * Note that old mappings are simply written
2305 * over. The page *must* be wired.
2306 * Note: SMP coherent. Uses a ranged shootdown IPI.
2309 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2311 pt_entry_t *endpte, oldpte, pa, *pte;
2317 endpte = pte + count;
2318 while (pte < endpte) {
2320 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2321 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2322 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2324 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2328 if (__predict_false((oldpte & X86_PG_V) != 0))
2329 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2334 * This routine tears out page mappings from the
2335 * kernel -- it is meant only for temporary mappings.
2336 * Note: SMP coherent. Uses a ranged shootdown IPI.
2339 pmap_qremove(vm_offset_t sva, int count)
2344 while (count-- > 0) {
2345 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2349 pmap_invalidate_range(kernel_pmap, sva, va);
2352 /***************************************************
2353 * Page table page management routines.....
2354 ***************************************************/
2356 * Schedule the specified unused page table page to be freed. Specifically,
2357 * add the page to the specified list of pages that will be released to the
2358 * physical memory manager after the TLB has been updated.
2360 static __inline void
2361 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2362 boolean_t set_PG_ZERO)
2366 m->flags |= PG_ZERO;
2368 m->flags &= ~PG_ZERO;
2369 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2373 * Inserts the specified page table page into the specified pmap's collection
2374 * of idle page table pages. Each of a pmap's page table pages is responsible
2375 * for mapping a distinct range of virtual addresses. The pmap's collection is
2376 * ordered by this virtual address range.
2379 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2382 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2383 return (vm_radix_insert(&pmap->pm_root, mpte));
2387 * Removes the page table page mapping the specified virtual address from the
2388 * specified pmap's collection of idle page table pages, and returns it.
2389 * Otherwise, returns NULL if there is no page table page corresponding to the
2390 * specified virtual address.
2392 static __inline vm_page_t
2393 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2396 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2397 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2401 * Decrements a page table page's wire count, which is used to record the
2402 * number of valid page table entries within the page. If the wire count
2403 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2404 * page table page was unmapped and FALSE otherwise.
2406 static inline boolean_t
2407 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2411 if (m->wire_count == 0) {
2412 _pmap_unwire_ptp(pmap, va, m, free);
2419 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2422 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2424 * unmap the page table page
2426 if (m->pindex >= (NUPDE + NUPDPE)) {
2429 pml4 = pmap_pml4e(pmap, va);
2431 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2432 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2435 } else if (m->pindex >= NUPDE) {
2438 pdp = pmap_pdpe(pmap, va);
2443 pd = pmap_pde(pmap, va);
2446 pmap_resident_count_dec(pmap, 1);
2447 if (m->pindex < NUPDE) {
2448 /* We just released a PT, unhold the matching PD */
2451 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2452 pmap_unwire_ptp(pmap, va, pdpg, free);
2454 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2455 /* We just released a PD, unhold the matching PDP */
2458 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2459 pmap_unwire_ptp(pmap, va, pdppg, free);
2463 * Put page on a list so that it is released after
2464 * *ALL* TLB shootdown is done
2466 pmap_add_delayed_free_list(m, free, TRUE);
2470 * After removing a page table entry, this routine is used to
2471 * conditionally free the page, and manage the hold/wire counts.
2474 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2475 struct spglist *free)
2479 if (va >= VM_MAXUSER_ADDRESS)
2481 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2482 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2483 return (pmap_unwire_ptp(pmap, va, mpte, free));
2487 pmap_pinit0(pmap_t pmap)
2491 PMAP_LOCK_INIT(pmap);
2492 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2493 pmap->pm_pml4u = NULL;
2494 pmap->pm_cr3 = KPML4phys;
2495 /* hack to keep pmap_pti_pcid_invalidate() alive */
2496 pmap->pm_ucr3 = PMAP_NO_CR3;
2497 pmap->pm_root.rt_root = 0;
2498 CPU_ZERO(&pmap->pm_active);
2499 TAILQ_INIT(&pmap->pm_pvchunk);
2500 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2501 pmap->pm_flags = pmap_flags;
2503 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2504 pmap->pm_pcids[i].pm_gen = 0;
2506 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2508 PCPU_SET(curpmap, kernel_pmap);
2509 pmap_activate(curthread);
2510 CPU_FILL(&kernel_pmap->pm_active);
2514 pmap_pinit_pml4(vm_page_t pml4pg)
2516 pml4_entry_t *pm_pml4;
2519 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2521 /* Wire in kernel global address entries. */
2522 for (i = 0; i < NKPML4E; i++) {
2523 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2526 for (i = 0; i < ndmpdpphys; i++) {
2527 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2531 /* install self-referential address mapping entry(s) */
2532 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2533 X86_PG_A | X86_PG_M;
2537 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2539 pml4_entry_t *pm_pml4;
2542 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2543 for (i = 0; i < NPML4EPG; i++)
2544 pm_pml4[i] = pti_pml4[i];
2548 * Initialize a preallocated and zeroed pmap structure,
2549 * such as one in a vmspace structure.
2552 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2554 vm_page_t pml4pg, pml4pgu;
2555 vm_paddr_t pml4phys;
2559 * allocate the page directory page
2561 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2562 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2564 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2565 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2567 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2568 pmap->pm_pcids[i].pm_gen = 0;
2570 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2571 pmap->pm_ucr3 = PMAP_NO_CR3;
2572 pmap->pm_pml4u = NULL;
2574 pmap->pm_type = pm_type;
2575 if ((pml4pg->flags & PG_ZERO) == 0)
2576 pagezero(pmap->pm_pml4);
2579 * Do not install the host kernel mappings in the nested page
2580 * tables. These mappings are meaningless in the guest physical
2582 * Install minimal kernel mappings in PTI case.
2584 if (pm_type == PT_X86) {
2585 pmap->pm_cr3 = pml4phys;
2586 pmap_pinit_pml4(pml4pg);
2588 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2589 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2590 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2591 VM_PAGE_TO_PHYS(pml4pgu));
2592 pmap_pinit_pml4_pti(pml4pgu);
2593 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2597 pmap->pm_root.rt_root = 0;
2598 CPU_ZERO(&pmap->pm_active);
2599 TAILQ_INIT(&pmap->pm_pvchunk);
2600 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2601 pmap->pm_flags = flags;
2602 pmap->pm_eptgen = 0;
2608 pmap_pinit(pmap_t pmap)
2611 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2615 * This routine is called if the desired page table page does not exist.
2617 * If page table page allocation fails, this routine may sleep before
2618 * returning NULL. It sleeps only if a lock pointer was given.
2620 * Note: If a page allocation fails at page table level two or three,
2621 * one or two pages may be held during the wait, only to be released
2622 * afterwards. This conservative approach is easily argued to avoid
2626 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2628 vm_page_t m, pdppg, pdpg;
2629 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2631 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2633 PG_A = pmap_accessed_bit(pmap);
2634 PG_M = pmap_modified_bit(pmap);
2635 PG_V = pmap_valid_bit(pmap);
2636 PG_RW = pmap_rw_bit(pmap);
2639 * Allocate a page table page.
2641 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2642 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2643 if (lockp != NULL) {
2644 RELEASE_PV_LIST_LOCK(lockp);
2646 PMAP_ASSERT_NOT_IN_DI();
2652 * Indicate the need to retry. While waiting, the page table
2653 * page may have been allocated.
2657 if ((m->flags & PG_ZERO) == 0)
2661 * Map the pagetable page into the process address space, if
2662 * it isn't already there.
2665 if (ptepindex >= (NUPDE + NUPDPE)) {
2666 pml4_entry_t *pml4, *pml4u;
2667 vm_pindex_t pml4index;
2669 /* Wire up a new PDPE page */
2670 pml4index = ptepindex - (NUPDE + NUPDPE);
2671 pml4 = &pmap->pm_pml4[pml4index];
2672 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2673 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2675 * PTI: Make all user-space mappings in the
2676 * kernel-mode page table no-execute so that
2677 * we detect any programming errors that leave
2678 * the kernel-mode page table active on return
2683 pml4u = &pmap->pm_pml4u[pml4index];
2684 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2688 } else if (ptepindex >= NUPDE) {
2689 vm_pindex_t pml4index;
2690 vm_pindex_t pdpindex;
2694 /* Wire up a new PDE page */
2695 pdpindex = ptepindex - NUPDE;
2696 pml4index = pdpindex >> NPML4EPGSHIFT;
2698 pml4 = &pmap->pm_pml4[pml4index];
2699 if ((*pml4 & PG_V) == 0) {
2700 /* Have to allocate a new pdp, recurse */
2701 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2703 vm_page_unwire_noq(m);
2704 vm_page_free_zero(m);
2708 /* Add reference to pdp page */
2709 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2710 pdppg->wire_count++;
2712 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2714 /* Now find the pdp page */
2715 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2716 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2719 vm_pindex_t pml4index;
2720 vm_pindex_t pdpindex;
2725 /* Wire up a new PTE page */
2726 pdpindex = ptepindex >> NPDPEPGSHIFT;
2727 pml4index = pdpindex >> NPML4EPGSHIFT;
2729 /* First, find the pdp and check that its valid. */
2730 pml4 = &pmap->pm_pml4[pml4index];
2731 if ((*pml4 & PG_V) == 0) {
2732 /* Have to allocate a new pd, recurse */
2733 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2735 vm_page_unwire_noq(m);
2736 vm_page_free_zero(m);
2739 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2740 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2742 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2743 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2744 if ((*pdp & PG_V) == 0) {
2745 /* Have to allocate a new pd, recurse */
2746 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2748 vm_page_unwire_noq(m);
2749 vm_page_free_zero(m);
2753 /* Add reference to the pd page */
2754 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2758 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2760 /* Now we know where the page directory page is */
2761 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2762 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2765 pmap_resident_count_inc(pmap, 1);
2771 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2773 vm_pindex_t pdpindex, ptepindex;
2774 pdp_entry_t *pdpe, PG_V;
2777 PG_V = pmap_valid_bit(pmap);
2780 pdpe = pmap_pdpe(pmap, va);
2781 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2782 /* Add a reference to the pd page. */
2783 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2786 /* Allocate a pd page. */
2787 ptepindex = pmap_pde_pindex(va);
2788 pdpindex = ptepindex >> NPDPEPGSHIFT;
2789 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2790 if (pdpg == NULL && lockp != NULL)
2797 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2799 vm_pindex_t ptepindex;
2800 pd_entry_t *pd, PG_V;
2803 PG_V = pmap_valid_bit(pmap);
2806 * Calculate pagetable page index
2808 ptepindex = pmap_pde_pindex(va);
2811 * Get the page directory entry
2813 pd = pmap_pde(pmap, va);
2816 * This supports switching from a 2MB page to a
2819 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2820 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2822 * Invalidation of the 2MB page mapping may have caused
2823 * the deallocation of the underlying PD page.
2830 * If the page table page is mapped, we just increment the
2831 * hold count, and activate it.
2833 if (pd != NULL && (*pd & PG_V) != 0) {
2834 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2838 * Here if the pte page isn't mapped, or if it has been
2841 m = _pmap_allocpte(pmap, ptepindex, lockp);
2842 if (m == NULL && lockp != NULL)
2849 /***************************************************
2850 * Pmap allocation/deallocation routines.
2851 ***************************************************/
2854 * Release any resources held by the given physical map.
2855 * Called when a pmap initialized by pmap_pinit is being released.
2856 * Should only be called if the map contains no valid mappings.
2859 pmap_release(pmap_t pmap)
2864 KASSERT(pmap->pm_stats.resident_count == 0,
2865 ("pmap_release: pmap resident count %ld != 0",
2866 pmap->pm_stats.resident_count));
2867 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2868 ("pmap_release: pmap has reserved page table page(s)"));
2869 KASSERT(CPU_EMPTY(&pmap->pm_active),
2870 ("releasing active pmap %p", pmap));
2872 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2874 for (i = 0; i < NKPML4E; i++) /* KVA */
2875 pmap->pm_pml4[KPML4BASE + i] = 0;
2876 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2877 pmap->pm_pml4[DMPML4I + i] = 0;
2878 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2880 vm_page_unwire_noq(m);
2881 vm_page_free_zero(m);
2883 if (pmap->pm_pml4u != NULL) {
2884 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2885 vm_page_unwire_noq(m);
2891 kvm_size(SYSCTL_HANDLER_ARGS)
2893 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2895 return sysctl_handle_long(oidp, &ksize, 0, req);
2897 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2898 0, 0, kvm_size, "LU", "Size of KVM");
2901 kvm_free(SYSCTL_HANDLER_ARGS)
2903 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2905 return sysctl_handle_long(oidp, &kfree, 0, req);
2907 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2908 0, 0, kvm_free, "LU", "Amount of KVM free");
2911 * grow the number of kernel page table entries, if needed
2914 pmap_growkernel(vm_offset_t addr)
2918 pd_entry_t *pde, newpdir;
2921 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2924 * Return if "addr" is within the range of kernel page table pages
2925 * that were preallocated during pmap bootstrap. Moreover, leave
2926 * "kernel_vm_end" and the kernel page table as they were.
2928 * The correctness of this action is based on the following
2929 * argument: vm_map_insert() allocates contiguous ranges of the
2930 * kernel virtual address space. It calls this function if a range
2931 * ends after "kernel_vm_end". If the kernel is mapped between
2932 * "kernel_vm_end" and "addr", then the range cannot begin at
2933 * "kernel_vm_end". In fact, its beginning address cannot be less
2934 * than the kernel. Thus, there is no immediate need to allocate
2935 * any new kernel page table pages between "kernel_vm_end" and
2938 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2941 addr = roundup2(addr, NBPDR);
2942 if (addr - 1 >= kernel_map->max_offset)
2943 addr = kernel_map->max_offset;
2944 while (kernel_vm_end < addr) {
2945 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2946 if ((*pdpe & X86_PG_V) == 0) {
2947 /* We need a new PDP entry */
2948 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2949 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2950 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2952 panic("pmap_growkernel: no memory to grow kernel");
2953 if ((nkpg->flags & PG_ZERO) == 0)
2954 pmap_zero_page(nkpg);
2955 paddr = VM_PAGE_TO_PHYS(nkpg);
2956 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2957 X86_PG_A | X86_PG_M);
2958 continue; /* try again */
2960 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2961 if ((*pde & X86_PG_V) != 0) {
2962 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2963 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2964 kernel_vm_end = kernel_map->max_offset;
2970 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2971 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2974 panic("pmap_growkernel: no memory to grow kernel");
2975 if ((nkpg->flags & PG_ZERO) == 0)
2976 pmap_zero_page(nkpg);
2977 paddr = VM_PAGE_TO_PHYS(nkpg);
2978 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2979 pde_store(pde, newpdir);
2981 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2982 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2983 kernel_vm_end = kernel_map->max_offset;
2990 /***************************************************
2991 * page management routines.
2992 ***************************************************/
2994 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2995 CTASSERT(_NPCM == 3);
2996 CTASSERT(_NPCPV == 168);
2998 static __inline struct pv_chunk *
2999 pv_to_chunk(pv_entry_t pv)
3002 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3005 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3007 #define PC_FREE0 0xfffffffffffffffful
3008 #define PC_FREE1 0xfffffffffffffffful
3009 #define PC_FREE2 0x000000fffffffffful
3011 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3014 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3016 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3017 "Current number of pv entry chunks");
3018 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3019 "Current number of pv entry chunks allocated");
3020 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3021 "Current number of pv entry chunks frees");
3022 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3023 "Number of times tried to get a chunk page but failed.");
3025 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3026 static int pv_entry_spare;
3028 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3029 "Current number of pv entry frees");
3030 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3031 "Current number of pv entry allocs");
3032 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3033 "Current number of pv entries");
3034 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3035 "Current number of spare pv entries");
3039 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3044 pmap_invalidate_all(pmap);
3045 if (pmap != locked_pmap)
3048 pmap_delayed_invl_finished();
3052 * We are in a serious low memory condition. Resort to
3053 * drastic measures to free some pages so we can allocate
3054 * another pv entry chunk.
3056 * Returns NULL if PV entries were reclaimed from the specified pmap.
3058 * We do not, however, unmap 2mpages because subsequent accesses will
3059 * allocate per-page pv entries until repromotion occurs, thereby
3060 * exacerbating the shortage of free pv entries.
3063 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3065 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3066 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3067 struct md_page *pvh;
3069 pmap_t next_pmap, pmap;
3070 pt_entry_t *pte, tpte;
3071 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3075 struct spglist free;
3077 int bit, field, freed;
3079 static int active_reclaims = 0;
3081 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3082 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3085 PG_G = PG_A = PG_M = PG_RW = 0;
3087 bzero(&pc_marker_b, sizeof(pc_marker_b));
3088 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3089 pc_marker = (struct pv_chunk *)&pc_marker_b;
3090 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3093 * A delayed invalidation block should already be active if
3094 * pmap_advise() or pmap_remove() called this function by way
3095 * of pmap_demote_pde_locked().
3097 start_di = pmap_not_in_di();
3099 mtx_lock(&pv_chunks_mutex);
3101 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3102 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3103 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3104 SLIST_EMPTY(&free)) {
3105 next_pmap = pc->pc_pmap;
3106 if (next_pmap == NULL) {
3108 * The next chunk is a marker. However, it is
3109 * not our marker, so active_reclaims must be
3110 * > 1. Consequently, the next_chunk code
3111 * will not rotate the pv_chunks list.
3115 mtx_unlock(&pv_chunks_mutex);
3118 * A pv_chunk can only be removed from the pc_lru list
3119 * when both pc_chunks_mutex is owned and the
3120 * corresponding pmap is locked.
3122 if (pmap != next_pmap) {
3123 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3126 /* Avoid deadlock and lock recursion. */
3127 if (pmap > locked_pmap) {
3128 RELEASE_PV_LIST_LOCK(lockp);
3131 pmap_delayed_invl_started();
3132 mtx_lock(&pv_chunks_mutex);
3134 } else if (pmap != locked_pmap) {
3135 if (PMAP_TRYLOCK(pmap)) {
3137 pmap_delayed_invl_started();
3138 mtx_lock(&pv_chunks_mutex);
3141 pmap = NULL; /* pmap is not locked */
3142 mtx_lock(&pv_chunks_mutex);
3143 pc = TAILQ_NEXT(pc_marker, pc_lru);
3145 pc->pc_pmap != next_pmap)
3149 } else if (start_di)
3150 pmap_delayed_invl_started();
3151 PG_G = pmap_global_bit(pmap);
3152 PG_A = pmap_accessed_bit(pmap);
3153 PG_M = pmap_modified_bit(pmap);
3154 PG_RW = pmap_rw_bit(pmap);
3158 * Destroy every non-wired, 4 KB page mapping in the chunk.
3161 for (field = 0; field < _NPCM; field++) {
3162 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3163 inuse != 0; inuse &= ~(1UL << bit)) {
3165 pv = &pc->pc_pventry[field * 64 + bit];
3167 pde = pmap_pde(pmap, va);
3168 if ((*pde & PG_PS) != 0)
3170 pte = pmap_pde_to_pte(pde, va);
3171 if ((*pte & PG_W) != 0)
3173 tpte = pte_load_clear(pte);
3174 if ((tpte & PG_G) != 0)
3175 pmap_invalidate_page(pmap, va);
3176 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3177 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3179 if ((tpte & PG_A) != 0)
3180 vm_page_aflag_set(m, PGA_REFERENCED);
3181 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3182 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3184 if (TAILQ_EMPTY(&m->md.pv_list) &&
3185 (m->flags & PG_FICTITIOUS) == 0) {
3186 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3187 if (TAILQ_EMPTY(&pvh->pv_list)) {
3188 vm_page_aflag_clear(m,
3192 pmap_delayed_invl_page(m);
3193 pc->pc_map[field] |= 1UL << bit;
3194 pmap_unuse_pt(pmap, va, *pde, &free);
3199 mtx_lock(&pv_chunks_mutex);
3202 /* Every freed mapping is for a 4 KB page. */
3203 pmap_resident_count_dec(pmap, freed);
3204 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3205 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3206 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3207 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3208 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3209 pc->pc_map[2] == PC_FREE2) {
3210 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3211 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3212 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3213 /* Entire chunk is free; return it. */
3214 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3215 dump_drop_page(m_pc->phys_addr);
3216 mtx_lock(&pv_chunks_mutex);
3217 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3220 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3221 mtx_lock(&pv_chunks_mutex);
3222 /* One freed pv entry in locked_pmap is sufficient. */
3223 if (pmap == locked_pmap)
3226 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3227 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3228 if (active_reclaims == 1 && pmap != NULL) {
3230 * Rotate the pv chunks list so that we do not
3231 * scan the same pv chunks that could not be
3232 * freed (because they contained a wired
3233 * and/or superpage mapping) on every
3234 * invocation of reclaim_pv_chunk().
3236 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3237 MPASS(pc->pc_pmap != NULL);
3238 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3239 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3243 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3244 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3246 mtx_unlock(&pv_chunks_mutex);
3247 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3248 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3249 m_pc = SLIST_FIRST(&free);
3250 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3251 /* Recycle a freed page table page. */
3252 m_pc->wire_count = 1;
3254 vm_page_free_pages_toq(&free, true);
3259 * free the pv_entry back to the free list
3262 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3264 struct pv_chunk *pc;
3265 int idx, field, bit;
3267 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3268 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3269 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3270 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3271 pc = pv_to_chunk(pv);
3272 idx = pv - &pc->pc_pventry[0];
3275 pc->pc_map[field] |= 1ul << bit;
3276 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3277 pc->pc_map[2] != PC_FREE2) {
3278 /* 98% of the time, pc is already at the head of the list. */
3279 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3280 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3281 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3285 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3290 free_pv_chunk(struct pv_chunk *pc)
3294 mtx_lock(&pv_chunks_mutex);
3295 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3296 mtx_unlock(&pv_chunks_mutex);
3297 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3298 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3299 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3300 /* entire chunk is free, return it */
3301 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3302 dump_drop_page(m->phys_addr);
3303 vm_page_unwire(m, PQ_NONE);
3308 * Returns a new PV entry, allocating a new PV chunk from the system when
3309 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3310 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3313 * The given PV list lock may be released.
3316 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3320 struct pv_chunk *pc;
3323 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3324 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3326 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3328 for (field = 0; field < _NPCM; field++) {
3329 if (pc->pc_map[field]) {
3330 bit = bsfq(pc->pc_map[field]);
3334 if (field < _NPCM) {
3335 pv = &pc->pc_pventry[field * 64 + bit];
3336 pc->pc_map[field] &= ~(1ul << bit);
3337 /* If this was the last item, move it to tail */
3338 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3339 pc->pc_map[2] == 0) {
3340 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3341 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3344 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3345 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3349 /* No free items, allocate another chunk */
3350 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3353 if (lockp == NULL) {
3354 PV_STAT(pc_chunk_tryfail++);
3357 m = reclaim_pv_chunk(pmap, lockp);
3361 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3362 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3363 dump_add_page(m->phys_addr);
3364 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3366 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3367 pc->pc_map[1] = PC_FREE1;
3368 pc->pc_map[2] = PC_FREE2;
3369 mtx_lock(&pv_chunks_mutex);
3370 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3371 mtx_unlock(&pv_chunks_mutex);
3372 pv = &pc->pc_pventry[0];
3373 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3374 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3375 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3380 * Returns the number of one bits within the given PV chunk map.
3382 * The erratas for Intel processors state that "POPCNT Instruction May
3383 * Take Longer to Execute Than Expected". It is believed that the
3384 * issue is the spurious dependency on the destination register.
3385 * Provide a hint to the register rename logic that the destination
3386 * value is overwritten, by clearing it, as suggested in the
3387 * optimization manual. It should be cheap for unaffected processors
3390 * Reference numbers for erratas are
3391 * 4th Gen Core: HSD146
3392 * 5th Gen Core: BDM85
3393 * 6th Gen Core: SKL029
3396 popcnt_pc_map_pq(uint64_t *map)
3400 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3401 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3402 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3403 : "=&r" (result), "=&r" (tmp)
3404 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3409 * Ensure that the number of spare PV entries in the specified pmap meets or
3410 * exceeds the given count, "needed".
3412 * The given PV list lock may be released.
3415 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3417 struct pch new_tail;
3418 struct pv_chunk *pc;
3422 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3423 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3426 * Newly allocated PV chunks must be stored in a private list until
3427 * the required number of PV chunks have been allocated. Otherwise,
3428 * reclaim_pv_chunk() could recycle one of these chunks. In
3429 * contrast, these chunks must be added to the pmap upon allocation.
3431 TAILQ_INIT(&new_tail);
3434 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3436 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3437 bit_count((bitstr_t *)pc->pc_map, 0,
3438 sizeof(pc->pc_map) * NBBY, &free);
3441 free = popcnt_pc_map_pq(pc->pc_map);
3445 if (avail >= needed)
3448 for (; avail < needed; avail += _NPCPV) {
3449 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3452 m = reclaim_pv_chunk(pmap, lockp);
3456 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3457 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3458 dump_add_page(m->phys_addr);
3459 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3461 pc->pc_map[0] = PC_FREE0;
3462 pc->pc_map[1] = PC_FREE1;
3463 pc->pc_map[2] = PC_FREE2;
3464 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3465 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3466 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3468 if (!TAILQ_EMPTY(&new_tail)) {
3469 mtx_lock(&pv_chunks_mutex);
3470 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3471 mtx_unlock(&pv_chunks_mutex);
3476 * First find and then remove the pv entry for the specified pmap and virtual
3477 * address from the specified pv list. Returns the pv entry if found and NULL
3478 * otherwise. This operation can be performed on pv lists for either 4KB or
3479 * 2MB page mappings.
3481 static __inline pv_entry_t
3482 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3486 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3487 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3488 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3497 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3498 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3499 * entries for each of the 4KB page mappings.
3502 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3503 struct rwlock **lockp)
3505 struct md_page *pvh;
3506 struct pv_chunk *pc;
3508 vm_offset_t va_last;
3512 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3513 KASSERT((pa & PDRMASK) == 0,
3514 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3515 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3518 * Transfer the 2mpage's pv entry for this mapping to the first
3519 * page's pv list. Once this transfer begins, the pv list lock
3520 * must not be released until the last pv entry is reinstantiated.
3522 pvh = pa_to_pvh(pa);
3523 va = trunc_2mpage(va);
3524 pv = pmap_pvh_remove(pvh, pmap, va);
3525 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3526 m = PHYS_TO_VM_PAGE(pa);
3527 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3529 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3530 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3531 va_last = va + NBPDR - PAGE_SIZE;
3533 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3534 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3535 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3536 for (field = 0; field < _NPCM; field++) {
3537 while (pc->pc_map[field]) {
3538 bit = bsfq(pc->pc_map[field]);
3539 pc->pc_map[field] &= ~(1ul << bit);
3540 pv = &pc->pc_pventry[field * 64 + bit];
3544 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3545 ("pmap_pv_demote_pde: page %p is not managed", m));
3546 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3552 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3553 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3556 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3557 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3558 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3560 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3561 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3564 #if VM_NRESERVLEVEL > 0
3566 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3567 * replace the many pv entries for the 4KB page mappings by a single pv entry
3568 * for the 2MB page mapping.
3571 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3572 struct rwlock **lockp)
3574 struct md_page *pvh;
3576 vm_offset_t va_last;
3579 KASSERT((pa & PDRMASK) == 0,
3580 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3581 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3584 * Transfer the first page's pv entry for this mapping to the 2mpage's
3585 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3586 * a transfer avoids the possibility that get_pv_entry() calls
3587 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3588 * mappings that is being promoted.
3590 m = PHYS_TO_VM_PAGE(pa);
3591 va = trunc_2mpage(va);
3592 pv = pmap_pvh_remove(&m->md, pmap, va);
3593 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3594 pvh = pa_to_pvh(pa);
3595 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3597 /* Free the remaining NPTEPG - 1 pv entries. */
3598 va_last = va + NBPDR - PAGE_SIZE;
3602 pmap_pvh_free(&m->md, pmap, va);
3603 } while (va < va_last);
3605 #endif /* VM_NRESERVLEVEL > 0 */
3608 * First find and then destroy the pv entry for the specified pmap and virtual
3609 * address. This operation can be performed on pv lists for either 4KB or 2MB
3613 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3617 pv = pmap_pvh_remove(pvh, pmap, va);
3618 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3619 free_pv_entry(pmap, pv);
3623 * Conditionally create the PV entry for a 4KB page mapping if the required
3624 * memory can be allocated without resorting to reclamation.
3627 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3628 struct rwlock **lockp)
3632 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3633 /* Pass NULL instead of the lock pointer to disable reclamation. */
3634 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3636 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3637 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3645 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3646 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3647 * false if the PV entry cannot be allocated without resorting to reclamation.
3650 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3651 struct rwlock **lockp)
3653 struct md_page *pvh;
3657 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3658 /* Pass NULL instead of the lock pointer to disable reclamation. */
3659 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3660 NULL : lockp)) == NULL)
3663 pa = pde & PG_PS_FRAME;
3664 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3665 pvh = pa_to_pvh(pa);
3666 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3672 * Fills a page table page with mappings to consecutive physical pages.
3675 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3679 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3681 newpte += PAGE_SIZE;
3686 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3687 * mapping is invalidated.
3690 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3692 struct rwlock *lock;
3696 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3703 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3704 struct rwlock **lockp)
3706 pd_entry_t newpde, oldpde;
3707 pt_entry_t *firstpte, newpte;
3708 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3711 struct spglist free;
3715 PG_G = pmap_global_bit(pmap);
3716 PG_A = pmap_accessed_bit(pmap);
3717 PG_M = pmap_modified_bit(pmap);
3718 PG_RW = pmap_rw_bit(pmap);
3719 PG_V = pmap_valid_bit(pmap);
3720 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3722 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3724 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3725 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3726 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3728 KASSERT((oldpde & PG_W) == 0,
3729 ("pmap_demote_pde: page table page for a wired mapping"
3733 * Invalidate the 2MB page mapping and return "failure" if the
3734 * mapping was never accessed or the allocation of the new
3735 * page table page fails. If the 2MB page mapping belongs to
3736 * the direct map region of the kernel's address space, then
3737 * the page allocation request specifies the highest possible
3738 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3739 * normal. Page table pages are preallocated for every other
3740 * part of the kernel address space, so the direct map region
3741 * is the only part of the kernel address space that must be
3744 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3745 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3746 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3747 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3749 sva = trunc_2mpage(va);
3750 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3751 if ((oldpde & PG_G) == 0)
3752 pmap_invalidate_pde_page(pmap, sva, oldpde);
3753 vm_page_free_pages_toq(&free, true);
3754 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3755 " in pmap %p", va, pmap);
3758 if (va < VM_MAXUSER_ADDRESS)
3759 pmap_resident_count_inc(pmap, 1);
3761 mptepa = VM_PAGE_TO_PHYS(mpte);
3762 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3763 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3764 KASSERT((oldpde & PG_A) != 0,
3765 ("pmap_demote_pde: oldpde is missing PG_A"));
3766 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3767 ("pmap_demote_pde: oldpde is missing PG_M"));
3768 newpte = oldpde & ~PG_PS;
3769 newpte = pmap_swap_pat(pmap, newpte);
3772 * If the page table page is new, initialize it.
3774 if (mpte->wire_count == 1) {
3775 mpte->wire_count = NPTEPG;
3776 pmap_fill_ptp(firstpte, newpte);
3778 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3779 ("pmap_demote_pde: firstpte and newpte map different physical"
3783 * If the mapping has changed attributes, update the page table
3786 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3787 pmap_fill_ptp(firstpte, newpte);
3790 * The spare PV entries must be reserved prior to demoting the
3791 * mapping, that is, prior to changing the PDE. Otherwise, the state
3792 * of the PDE and the PV lists will be inconsistent, which can result
3793 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3794 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3795 * PV entry for the 2MB page mapping that is being demoted.
3797 if ((oldpde & PG_MANAGED) != 0)
3798 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3801 * Demote the mapping. This pmap is locked. The old PDE has
3802 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3803 * set. Thus, there is no danger of a race with another
3804 * processor changing the setting of PG_A and/or PG_M between
3805 * the read above and the store below.
3807 if (workaround_erratum383)
3808 pmap_update_pde(pmap, va, pde, newpde);
3810 pde_store(pde, newpde);
3813 * Invalidate a stale recursive mapping of the page table page.
3815 if (va >= VM_MAXUSER_ADDRESS)
3816 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3819 * Demote the PV entry.
3821 if ((oldpde & PG_MANAGED) != 0)
3822 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3824 atomic_add_long(&pmap_pde_demotions, 1);
3825 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3826 " in pmap %p", va, pmap);
3831 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3834 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3840 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3841 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3842 mpte = pmap_remove_pt_page(pmap, va);
3844 panic("pmap_remove_kernel_pde: Missing pt page.");
3846 mptepa = VM_PAGE_TO_PHYS(mpte);
3847 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3850 * Initialize the page table page.
3852 pagezero((void *)PHYS_TO_DMAP(mptepa));
3855 * Demote the mapping.
3857 if (workaround_erratum383)
3858 pmap_update_pde(pmap, va, pde, newpde);
3860 pde_store(pde, newpde);
3863 * Invalidate a stale recursive mapping of the page table page.
3865 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3869 * pmap_remove_pde: do the things to unmap a superpage in a process
3872 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3873 struct spglist *free, struct rwlock **lockp)
3875 struct md_page *pvh;
3877 vm_offset_t eva, va;
3879 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3881 PG_G = pmap_global_bit(pmap);
3882 PG_A = pmap_accessed_bit(pmap);
3883 PG_M = pmap_modified_bit(pmap);
3884 PG_RW = pmap_rw_bit(pmap);
3886 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3887 KASSERT((sva & PDRMASK) == 0,
3888 ("pmap_remove_pde: sva is not 2mpage aligned"));
3889 oldpde = pte_load_clear(pdq);
3891 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3892 if ((oldpde & PG_G) != 0)
3893 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3894 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3895 if (oldpde & PG_MANAGED) {
3896 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3897 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3898 pmap_pvh_free(pvh, pmap, sva);
3900 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3901 va < eva; va += PAGE_SIZE, m++) {
3902 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3905 vm_page_aflag_set(m, PGA_REFERENCED);
3906 if (TAILQ_EMPTY(&m->md.pv_list) &&
3907 TAILQ_EMPTY(&pvh->pv_list))
3908 vm_page_aflag_clear(m, PGA_WRITEABLE);
3909 pmap_delayed_invl_page(m);
3912 if (pmap == kernel_pmap) {
3913 pmap_remove_kernel_pde(pmap, pdq, sva);
3915 mpte = pmap_remove_pt_page(pmap, sva);
3917 pmap_resident_count_dec(pmap, 1);
3918 KASSERT(mpte->wire_count == NPTEPG,
3919 ("pmap_remove_pde: pte page wire count error"));
3920 mpte->wire_count = 0;
3921 pmap_add_delayed_free_list(mpte, free, FALSE);
3924 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3928 * pmap_remove_pte: do the things to unmap a page in a process
3931 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3932 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3934 struct md_page *pvh;
3935 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3938 PG_A = pmap_accessed_bit(pmap);
3939 PG_M = pmap_modified_bit(pmap);
3940 PG_RW = pmap_rw_bit(pmap);
3942 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3943 oldpte = pte_load_clear(ptq);
3945 pmap->pm_stats.wired_count -= 1;
3946 pmap_resident_count_dec(pmap, 1);
3947 if (oldpte & PG_MANAGED) {
3948 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3949 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3952 vm_page_aflag_set(m, PGA_REFERENCED);
3953 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3954 pmap_pvh_free(&m->md, pmap, va);
3955 if (TAILQ_EMPTY(&m->md.pv_list) &&
3956 (m->flags & PG_FICTITIOUS) == 0) {
3957 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3958 if (TAILQ_EMPTY(&pvh->pv_list))
3959 vm_page_aflag_clear(m, PGA_WRITEABLE);
3961 pmap_delayed_invl_page(m);
3963 return (pmap_unuse_pt(pmap, va, ptepde, free));
3967 * Remove a single page from a process address space
3970 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3971 struct spglist *free)
3973 struct rwlock *lock;
3974 pt_entry_t *pte, PG_V;
3976 PG_V = pmap_valid_bit(pmap);
3977 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3978 if ((*pde & PG_V) == 0)
3980 pte = pmap_pde_to_pte(pde, va);
3981 if ((*pte & PG_V) == 0)
3984 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3987 pmap_invalidate_page(pmap, va);
3991 * Removes the specified range of addresses from the page table page.
3994 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3995 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
3997 pt_entry_t PG_G, *pte;
4001 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4002 PG_G = pmap_global_bit(pmap);
4005 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4009 pmap_invalidate_range(pmap, va, sva);
4014 if ((*pte & PG_G) == 0)
4018 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4024 pmap_invalidate_range(pmap, va, sva);
4029 * Remove the given range of addresses from the specified map.
4031 * It is assumed that the start and end are properly
4032 * rounded to the page size.
4035 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4037 struct rwlock *lock;
4038 vm_offset_t va_next;
4039 pml4_entry_t *pml4e;
4041 pd_entry_t ptpaddr, *pde;
4042 pt_entry_t PG_G, PG_V;
4043 struct spglist free;
4046 PG_G = pmap_global_bit(pmap);
4047 PG_V = pmap_valid_bit(pmap);
4050 * Perform an unsynchronized read. This is, however, safe.
4052 if (pmap->pm_stats.resident_count == 0)
4058 pmap_delayed_invl_started();
4062 * special handling of removing one page. a very
4063 * common operation and easy to short circuit some
4066 if (sva + PAGE_SIZE == eva) {
4067 pde = pmap_pde(pmap, sva);
4068 if (pde && (*pde & PG_PS) == 0) {
4069 pmap_remove_page(pmap, sva, pde, &free);
4075 for (; sva < eva; sva = va_next) {
4077 if (pmap->pm_stats.resident_count == 0)
4080 pml4e = pmap_pml4e(pmap, sva);
4081 if ((*pml4e & PG_V) == 0) {
4082 va_next = (sva + NBPML4) & ~PML4MASK;
4088 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4089 if ((*pdpe & PG_V) == 0) {
4090 va_next = (sva + NBPDP) & ~PDPMASK;
4097 * Calculate index for next page table.
4099 va_next = (sva + NBPDR) & ~PDRMASK;
4103 pde = pmap_pdpe_to_pde(pdpe, sva);
4107 * Weed out invalid mappings.
4113 * Check for large page.
4115 if ((ptpaddr & PG_PS) != 0) {
4117 * Are we removing the entire large page? If not,
4118 * demote the mapping and fall through.
4120 if (sva + NBPDR == va_next && eva >= va_next) {
4122 * The TLB entry for a PG_G mapping is
4123 * invalidated by pmap_remove_pde().
4125 if ((ptpaddr & PG_G) == 0)
4127 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4129 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4131 /* The large page mapping was destroyed. */
4138 * Limit our scan to either the end of the va represented
4139 * by the current page table page, or to the end of the
4140 * range being removed.
4145 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4152 pmap_invalidate_all(pmap);
4154 pmap_delayed_invl_finished();
4155 vm_page_free_pages_toq(&free, true);
4159 * Routine: pmap_remove_all
4161 * Removes this physical page from
4162 * all physical maps in which it resides.
4163 * Reflects back modify bits to the pager.
4166 * Original versions of this routine were very
4167 * inefficient because they iteratively called
4168 * pmap_remove (slow...)
4172 pmap_remove_all(vm_page_t m)
4174 struct md_page *pvh;
4177 struct rwlock *lock;
4178 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4181 struct spglist free;
4182 int pvh_gen, md_gen;
4184 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4185 ("pmap_remove_all: page %p is not managed", m));
4187 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4188 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4189 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4192 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4194 if (!PMAP_TRYLOCK(pmap)) {
4195 pvh_gen = pvh->pv_gen;
4199 if (pvh_gen != pvh->pv_gen) {
4206 pde = pmap_pde(pmap, va);
4207 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4210 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4212 if (!PMAP_TRYLOCK(pmap)) {
4213 pvh_gen = pvh->pv_gen;
4214 md_gen = m->md.pv_gen;
4218 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4224 PG_A = pmap_accessed_bit(pmap);
4225 PG_M = pmap_modified_bit(pmap);
4226 PG_RW = pmap_rw_bit(pmap);
4227 pmap_resident_count_dec(pmap, 1);
4228 pde = pmap_pde(pmap, pv->pv_va);
4229 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4230 " a 2mpage in page %p's pv list", m));
4231 pte = pmap_pde_to_pte(pde, pv->pv_va);
4232 tpte = pte_load_clear(pte);
4234 pmap->pm_stats.wired_count--;
4236 vm_page_aflag_set(m, PGA_REFERENCED);
4239 * Update the vm_page_t clean and reference bits.
4241 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4243 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4244 pmap_invalidate_page(pmap, pv->pv_va);
4245 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4247 free_pv_entry(pmap, pv);
4250 vm_page_aflag_clear(m, PGA_WRITEABLE);
4252 pmap_delayed_invl_wait(m);
4253 vm_page_free_pages_toq(&free, true);
4257 * pmap_protect_pde: do the things to protect a 2mpage in a process
4260 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4262 pd_entry_t newpde, oldpde;
4263 vm_offset_t eva, va;
4265 boolean_t anychanged;
4266 pt_entry_t PG_G, PG_M, PG_RW;
4268 PG_G = pmap_global_bit(pmap);
4269 PG_M = pmap_modified_bit(pmap);
4270 PG_RW = pmap_rw_bit(pmap);
4272 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4273 KASSERT((sva & PDRMASK) == 0,
4274 ("pmap_protect_pde: sva is not 2mpage aligned"));
4277 oldpde = newpde = *pde;
4278 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4279 (PG_MANAGED | PG_M | PG_RW)) {
4281 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4282 va < eva; va += PAGE_SIZE, m++)
4285 if ((prot & VM_PROT_WRITE) == 0)
4286 newpde &= ~(PG_RW | PG_M);
4287 if ((prot & VM_PROT_EXECUTE) == 0)
4289 if (newpde != oldpde) {
4291 * As an optimization to future operations on this PDE, clear
4292 * PG_PROMOTED. The impending invalidation will remove any
4293 * lingering 4KB page mappings from the TLB.
4295 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4297 if ((oldpde & PG_G) != 0)
4298 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4302 return (anychanged);
4306 * Set the physical protection on the
4307 * specified range of this map as requested.
4310 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4312 vm_offset_t va_next;
4313 pml4_entry_t *pml4e;
4315 pd_entry_t ptpaddr, *pde;
4316 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4317 boolean_t anychanged;
4319 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4320 if (prot == VM_PROT_NONE) {
4321 pmap_remove(pmap, sva, eva);
4325 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4326 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4329 PG_G = pmap_global_bit(pmap);
4330 PG_M = pmap_modified_bit(pmap);
4331 PG_V = pmap_valid_bit(pmap);
4332 PG_RW = pmap_rw_bit(pmap);
4336 * Although this function delays and batches the invalidation
4337 * of stale TLB entries, it does not need to call
4338 * pmap_delayed_invl_started() and
4339 * pmap_delayed_invl_finished(), because it does not
4340 * ordinarily destroy mappings. Stale TLB entries from
4341 * protection-only changes need only be invalidated before the
4342 * pmap lock is released, because protection-only changes do
4343 * not destroy PV entries. Even operations that iterate over
4344 * a physical page's PV list of mappings, like
4345 * pmap_remove_write(), acquire the pmap lock for each
4346 * mapping. Consequently, for protection-only changes, the
4347 * pmap lock suffices to synchronize both page table and TLB
4350 * This function only destroys a mapping if pmap_demote_pde()
4351 * fails. In that case, stale TLB entries are immediately
4356 for (; sva < eva; sva = va_next) {
4358 pml4e = pmap_pml4e(pmap, sva);
4359 if ((*pml4e & PG_V) == 0) {
4360 va_next = (sva + NBPML4) & ~PML4MASK;
4366 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4367 if ((*pdpe & PG_V) == 0) {
4368 va_next = (sva + NBPDP) & ~PDPMASK;
4374 va_next = (sva + NBPDR) & ~PDRMASK;
4378 pde = pmap_pdpe_to_pde(pdpe, sva);
4382 * Weed out invalid mappings.
4388 * Check for large page.
4390 if ((ptpaddr & PG_PS) != 0) {
4392 * Are we protecting the entire large page? If not,
4393 * demote the mapping and fall through.
4395 if (sva + NBPDR == va_next && eva >= va_next) {
4397 * The TLB entry for a PG_G mapping is
4398 * invalidated by pmap_protect_pde().
4400 if (pmap_protect_pde(pmap, pde, sva, prot))
4403 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4405 * The large page mapping was destroyed.
4414 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4416 pt_entry_t obits, pbits;
4420 obits = pbits = *pte;
4421 if ((pbits & PG_V) == 0)
4424 if ((prot & VM_PROT_WRITE) == 0) {
4425 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4426 (PG_MANAGED | PG_M | PG_RW)) {
4427 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4430 pbits &= ~(PG_RW | PG_M);
4432 if ((prot & VM_PROT_EXECUTE) == 0)
4435 if (pbits != obits) {
4436 if (!atomic_cmpset_long(pte, obits, pbits))
4439 pmap_invalidate_page(pmap, sva);
4446 pmap_invalidate_all(pmap);
4450 #if VM_NRESERVLEVEL > 0
4452 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4453 * single page table page (PTP) to a single 2MB page mapping. For promotion
4454 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4455 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4456 * identical characteristics.
4459 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4460 struct rwlock **lockp)
4463 pt_entry_t *firstpte, oldpte, pa, *pte;
4464 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4468 PG_A = pmap_accessed_bit(pmap);
4469 PG_G = pmap_global_bit(pmap);
4470 PG_M = pmap_modified_bit(pmap);
4471 PG_V = pmap_valid_bit(pmap);
4472 PG_RW = pmap_rw_bit(pmap);
4473 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4475 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4478 * Examine the first PTE in the specified PTP. Abort if this PTE is
4479 * either invalid, unused, or does not map the first 4KB physical page
4480 * within a 2MB page.
4482 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4485 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4486 atomic_add_long(&pmap_pde_p_failures, 1);
4487 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4488 " in pmap %p", va, pmap);
4491 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4493 * When PG_M is already clear, PG_RW can be cleared without
4494 * a TLB invalidation.
4496 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4502 * Examine each of the other PTEs in the specified PTP. Abort if this
4503 * PTE maps an unexpected 4KB physical page or does not have identical
4504 * characteristics to the first PTE.
4506 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4507 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4510 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4511 atomic_add_long(&pmap_pde_p_failures, 1);
4512 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4513 " in pmap %p", va, pmap);
4516 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4518 * When PG_M is already clear, PG_RW can be cleared
4519 * without a TLB invalidation.
4521 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4524 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4525 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4526 (va & ~PDRMASK), pmap);
4528 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4529 atomic_add_long(&pmap_pde_p_failures, 1);
4530 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4531 " in pmap %p", va, pmap);
4538 * Save the page table page in its current state until the PDE
4539 * mapping the superpage is demoted by pmap_demote_pde() or
4540 * destroyed by pmap_remove_pde().
4542 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4543 KASSERT(mpte >= vm_page_array &&
4544 mpte < &vm_page_array[vm_page_array_size],
4545 ("pmap_promote_pde: page table page is out of range"));
4546 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4547 ("pmap_promote_pde: page table page's pindex is wrong"));
4548 if (pmap_insert_pt_page(pmap, mpte)) {
4549 atomic_add_long(&pmap_pde_p_failures, 1);
4551 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4557 * Promote the pv entries.
4559 if ((newpde & PG_MANAGED) != 0)
4560 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4563 * Propagate the PAT index to its proper position.
4565 newpde = pmap_swap_pat(pmap, newpde);
4568 * Map the superpage.
4570 if (workaround_erratum383)
4571 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4573 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4575 atomic_add_long(&pmap_pde_promotions, 1);
4576 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4577 " in pmap %p", va, pmap);
4579 #endif /* VM_NRESERVLEVEL > 0 */
4582 * Insert the given physical page (p) at
4583 * the specified virtual address (v) in the
4584 * target physical map with the protection requested.
4586 * If specified, the page will be wired down, meaning
4587 * that the related pte can not be reclaimed.
4589 * NB: This is the only routine which MAY NOT lazy-evaluate
4590 * or lose information. That is, this routine must actually
4591 * insert this page into the given map NOW.
4593 * When destroying both a page table and PV entry, this function
4594 * performs the TLB invalidation before releasing the PV list
4595 * lock, so we do not need pmap_delayed_invl_page() calls here.
4598 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4599 u_int flags, int8_t psind)
4601 struct rwlock *lock;
4603 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4604 pt_entry_t newpte, origpte;
4611 PG_A = pmap_accessed_bit(pmap);
4612 PG_G = pmap_global_bit(pmap);
4613 PG_M = pmap_modified_bit(pmap);
4614 PG_V = pmap_valid_bit(pmap);
4615 PG_RW = pmap_rw_bit(pmap);
4617 va = trunc_page(va);
4618 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4619 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4620 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4622 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4623 va >= kmi.clean_eva,
4624 ("pmap_enter: managed mapping within the clean submap"));
4625 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4626 VM_OBJECT_ASSERT_LOCKED(m->object);
4627 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4628 ("pmap_enter: flags %u has reserved bits set", flags));
4629 pa = VM_PAGE_TO_PHYS(m);
4630 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4631 if ((flags & VM_PROT_WRITE) != 0)
4633 if ((prot & VM_PROT_WRITE) != 0)
4635 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4636 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4637 if ((prot & VM_PROT_EXECUTE) == 0)
4639 if ((flags & PMAP_ENTER_WIRED) != 0)
4641 if (va < VM_MAXUSER_ADDRESS)
4643 if (pmap == kernel_pmap)
4645 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4648 * Set modified bit gratuitously for writeable mappings if
4649 * the page is unmanaged. We do not want to take a fault
4650 * to do the dirty bit accounting for these mappings.
4652 if ((m->oflags & VPO_UNMANAGED) != 0) {
4653 if ((newpte & PG_RW) != 0)
4656 newpte |= PG_MANAGED;
4661 /* Assert the required virtual and physical alignment. */
4662 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4663 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4664 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4670 * In the case that a page table page is not
4671 * resident, we are creating it here.
4674 pde = pmap_pde(pmap, va);
4675 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4676 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4677 pte = pmap_pde_to_pte(pde, va);
4678 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4679 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4682 } else if (va < VM_MAXUSER_ADDRESS) {
4684 * Here if the pte page isn't mapped, or if it has been
4687 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4688 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4689 nosleep ? NULL : &lock);
4690 if (mpte == NULL && nosleep) {
4691 rv = KERN_RESOURCE_SHORTAGE;
4696 panic("pmap_enter: invalid page directory va=%#lx", va);
4701 * Is the specified virtual address already mapped?
4703 if ((origpte & PG_V) != 0) {
4705 * Wiring change, just update stats. We don't worry about
4706 * wiring PT pages as they remain resident as long as there
4707 * are valid mappings in them. Hence, if a user page is wired,
4708 * the PT page will be also.
4710 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4711 pmap->pm_stats.wired_count++;
4712 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4713 pmap->pm_stats.wired_count--;
4716 * Remove the extra PT page reference.
4720 KASSERT(mpte->wire_count > 0,
4721 ("pmap_enter: missing reference to page table page,"
4726 * Has the physical page changed?
4728 opa = origpte & PG_FRAME;
4731 * No, might be a protection or wiring change.
4733 if ((origpte & PG_MANAGED) != 0 &&
4734 (newpte & PG_RW) != 0)
4735 vm_page_aflag_set(m, PGA_WRITEABLE);
4736 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4742 * Increment the counters.
4744 if ((newpte & PG_W) != 0)
4745 pmap->pm_stats.wired_count++;
4746 pmap_resident_count_inc(pmap, 1);
4750 * Enter on the PV list if part of our managed memory.
4752 if ((newpte & PG_MANAGED) != 0) {
4753 pv = get_pv_entry(pmap, &lock);
4755 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4756 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4758 if ((newpte & PG_RW) != 0)
4759 vm_page_aflag_set(m, PGA_WRITEABLE);
4765 if ((origpte & PG_V) != 0) {
4767 origpte = pte_load_store(pte, newpte);
4768 opa = origpte & PG_FRAME;
4770 if ((origpte & PG_MANAGED) != 0) {
4771 om = PHYS_TO_VM_PAGE(opa);
4772 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4775 if ((origpte & PG_A) != 0)
4776 vm_page_aflag_set(om, PGA_REFERENCED);
4777 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4778 pmap_pvh_free(&om->md, pmap, va);
4779 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4780 TAILQ_EMPTY(&om->md.pv_list) &&
4781 ((om->flags & PG_FICTITIOUS) != 0 ||
4782 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4783 vm_page_aflag_clear(om, PGA_WRITEABLE);
4785 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4786 PG_RW)) == (PG_M | PG_RW)) {
4787 if ((origpte & PG_MANAGED) != 0)
4791 * Although the PTE may still have PG_RW set, TLB
4792 * invalidation may nonetheless be required because
4793 * the PTE no longer has PG_M set.
4795 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4797 * This PTE change does not require TLB invalidation.
4801 if ((origpte & PG_A) != 0)
4802 pmap_invalidate_page(pmap, va);
4804 pte_store(pte, newpte);
4808 #if VM_NRESERVLEVEL > 0
4810 * If both the page table page and the reservation are fully
4811 * populated, then attempt promotion.
4813 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4814 pmap_ps_enabled(pmap) &&
4815 (m->flags & PG_FICTITIOUS) == 0 &&
4816 vm_reserv_level_iffullpop(m) == 0)
4817 pmap_promote_pde(pmap, pde, va, &lock);
4829 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4830 * if successful. Returns false if (1) a page table page cannot be allocated
4831 * without sleeping, (2) a mapping already exists at the specified virtual
4832 * address, or (3) a PV entry cannot be allocated without reclaiming another
4836 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4837 struct rwlock **lockp)
4842 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4843 PG_V = pmap_valid_bit(pmap);
4844 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4846 if ((m->oflags & VPO_UNMANAGED) == 0)
4847 newpde |= PG_MANAGED;
4848 if ((prot & VM_PROT_EXECUTE) == 0)
4850 if (va < VM_MAXUSER_ADDRESS)
4852 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4853 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4858 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4859 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4860 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4861 * a mapping already exists at the specified virtual address. Returns
4862 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4863 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4864 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4866 * The parameter "m" is only used when creating a managed, writeable mapping.
4869 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4870 vm_page_t m, struct rwlock **lockp)
4872 struct spglist free;
4873 pd_entry_t oldpde, *pde;
4874 pt_entry_t PG_G, PG_RW, PG_V;
4877 PG_G = pmap_global_bit(pmap);
4878 PG_RW = pmap_rw_bit(pmap);
4879 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4880 ("pmap_enter_pde: newpde is missing PG_M"));
4881 PG_V = pmap_valid_bit(pmap);
4882 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4884 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4885 NULL : lockp)) == NULL) {
4886 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4887 " in pmap %p", va, pmap);
4888 return (KERN_RESOURCE_SHORTAGE);
4890 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4891 pde = &pde[pmap_pde_index(va)];
4893 if ((oldpde & PG_V) != 0) {
4894 KASSERT(pdpg->wire_count > 1,
4895 ("pmap_enter_pde: pdpg's wire count is too low"));
4896 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4898 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4899 " in pmap %p", va, pmap);
4900 return (KERN_FAILURE);
4902 /* Break the existing mapping(s). */
4904 if ((oldpde & PG_PS) != 0) {
4906 * The reference to the PD page that was acquired by
4907 * pmap_allocpde() ensures that it won't be freed.
4908 * However, if the PDE resulted from a promotion, then
4909 * a reserved PT page could be freed.
4911 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4912 if ((oldpde & PG_G) == 0)
4913 pmap_invalidate_pde_page(pmap, va, oldpde);
4915 pmap_delayed_invl_started();
4916 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4918 pmap_invalidate_all(pmap);
4919 pmap_delayed_invl_finished();
4921 vm_page_free_pages_toq(&free, true);
4922 if (va >= VM_MAXUSER_ADDRESS) {
4923 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4924 if (pmap_insert_pt_page(pmap, mt)) {
4926 * XXX Currently, this can't happen because
4927 * we do not perform pmap_enter(psind == 1)
4928 * on the kernel pmap.
4930 panic("pmap_enter_pde: trie insert failed");
4933 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4936 if ((newpde & PG_MANAGED) != 0) {
4938 * Abort this mapping if its PV entry could not be created.
4940 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4942 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4944 * Although "va" is not mapped, paging-
4945 * structure caches could nonetheless have
4946 * entries that refer to the freed page table
4947 * pages. Invalidate those entries.
4949 pmap_invalidate_page(pmap, va);
4950 vm_page_free_pages_toq(&free, true);
4952 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4953 " in pmap %p", va, pmap);
4954 return (KERN_RESOURCE_SHORTAGE);
4956 if ((newpde & PG_RW) != 0) {
4957 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4958 vm_page_aflag_set(mt, PGA_WRITEABLE);
4963 * Increment counters.
4965 if ((newpde & PG_W) != 0)
4966 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4967 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4970 * Map the superpage. (This is not a promoted mapping; there will not
4971 * be any lingering 4KB page mappings in the TLB.)
4973 pde_store(pde, newpde);
4975 atomic_add_long(&pmap_pde_mappings, 1);
4976 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4977 " in pmap %p", va, pmap);
4978 return (KERN_SUCCESS);
4982 * Maps a sequence of resident pages belonging to the same object.
4983 * The sequence begins with the given page m_start. This page is
4984 * mapped at the given virtual address start. Each subsequent page is
4985 * mapped at a virtual address that is offset from start by the same
4986 * amount as the page is offset from m_start within the object. The
4987 * last page in the sequence is the page with the largest offset from
4988 * m_start that can be mapped at a virtual address less than the given
4989 * virtual address end. Not every virtual page between start and end
4990 * is mapped; only those for which a resident page exists with the
4991 * corresponding offset from m_start are mapped.
4994 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4995 vm_page_t m_start, vm_prot_t prot)
4997 struct rwlock *lock;
5000 vm_pindex_t diff, psize;
5002 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5004 psize = atop(end - start);
5009 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5010 va = start + ptoa(diff);
5011 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5012 m->psind == 1 && pmap_ps_enabled(pmap) &&
5013 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5014 m = &m[NBPDR / PAGE_SIZE - 1];
5016 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5018 m = TAILQ_NEXT(m, listq);
5026 * this code makes some *MAJOR* assumptions:
5027 * 1. Current pmap & pmap exists.
5030 * 4. No page table pages.
5031 * but is *MUCH* faster than pmap_enter...
5035 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5037 struct rwlock *lock;
5041 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5048 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5049 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5051 struct spglist free;
5052 pt_entry_t *pte, PG_V;
5055 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5056 (m->oflags & VPO_UNMANAGED) != 0,
5057 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5058 PG_V = pmap_valid_bit(pmap);
5059 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5062 * In the case that a page table page is not
5063 * resident, we are creating it here.
5065 if (va < VM_MAXUSER_ADDRESS) {
5066 vm_pindex_t ptepindex;
5070 * Calculate pagetable page index
5072 ptepindex = pmap_pde_pindex(va);
5073 if (mpte && (mpte->pindex == ptepindex)) {
5077 * Get the page directory entry
5079 ptepa = pmap_pde(pmap, va);
5082 * If the page table page is mapped, we just increment
5083 * the hold count, and activate it. Otherwise, we
5084 * attempt to allocate a page table page. If this
5085 * attempt fails, we don't retry. Instead, we give up.
5087 if (ptepa && (*ptepa & PG_V) != 0) {
5090 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5094 * Pass NULL instead of the PV list lock
5095 * pointer, because we don't intend to sleep.
5097 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5102 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5103 pte = &pte[pmap_pte_index(va)];
5117 * Enter on the PV list if part of our managed memory.
5119 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5120 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5123 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5125 * Although "va" is not mapped, paging-
5126 * structure caches could nonetheless have
5127 * entries that refer to the freed page table
5128 * pages. Invalidate those entries.
5130 pmap_invalidate_page(pmap, va);
5131 vm_page_free_pages_toq(&free, true);
5139 * Increment counters
5141 pmap_resident_count_inc(pmap, 1);
5143 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5144 if ((prot & VM_PROT_EXECUTE) == 0)
5148 * Now validate mapping with RO protection
5150 if ((m->oflags & VPO_UNMANAGED) != 0)
5151 pte_store(pte, pa | PG_V | PG_U);
5153 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5158 * Make a temporary mapping for a physical address. This is only intended
5159 * to be used for panic dumps.
5162 pmap_kenter_temporary(vm_paddr_t pa, int i)
5166 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5167 pmap_kenter(va, pa);
5169 return ((void *)crashdumpmap);
5173 * This code maps large physical mmap regions into the
5174 * processor address space. Note that some shortcuts
5175 * are taken, but the code works.
5178 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5179 vm_pindex_t pindex, vm_size_t size)
5182 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5183 vm_paddr_t pa, ptepa;
5187 PG_A = pmap_accessed_bit(pmap);
5188 PG_M = pmap_modified_bit(pmap);
5189 PG_V = pmap_valid_bit(pmap);
5190 PG_RW = pmap_rw_bit(pmap);
5192 VM_OBJECT_ASSERT_WLOCKED(object);
5193 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5194 ("pmap_object_init_pt: non-device object"));
5195 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5196 if (!pmap_ps_enabled(pmap))
5198 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5200 p = vm_page_lookup(object, pindex);
5201 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5202 ("pmap_object_init_pt: invalid page %p", p));
5203 pat_mode = p->md.pat_mode;
5206 * Abort the mapping if the first page is not physically
5207 * aligned to a 2MB page boundary.
5209 ptepa = VM_PAGE_TO_PHYS(p);
5210 if (ptepa & (NBPDR - 1))
5214 * Skip the first page. Abort the mapping if the rest of
5215 * the pages are not physically contiguous or have differing
5216 * memory attributes.
5218 p = TAILQ_NEXT(p, listq);
5219 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5221 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5222 ("pmap_object_init_pt: invalid page %p", p));
5223 if (pa != VM_PAGE_TO_PHYS(p) ||
5224 pat_mode != p->md.pat_mode)
5226 p = TAILQ_NEXT(p, listq);
5230 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5231 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5232 * will not affect the termination of this loop.
5235 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5236 pa < ptepa + size; pa += NBPDR) {
5237 pdpg = pmap_allocpde(pmap, addr, NULL);
5240 * The creation of mappings below is only an
5241 * optimization. If a page directory page
5242 * cannot be allocated without blocking,
5243 * continue on to the next mapping rather than
5249 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5250 pde = &pde[pmap_pde_index(addr)];
5251 if ((*pde & PG_V) == 0) {
5252 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5253 PG_U | PG_RW | PG_V);
5254 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5255 atomic_add_long(&pmap_pde_mappings, 1);
5257 /* Continue on if the PDE is already valid. */
5259 KASSERT(pdpg->wire_count > 0,
5260 ("pmap_object_init_pt: missing reference "
5261 "to page directory page, va: 0x%lx", addr));
5270 * Clear the wired attribute from the mappings for the specified range of
5271 * addresses in the given pmap. Every valid mapping within that range
5272 * must have the wired attribute set. In contrast, invalid mappings
5273 * cannot have the wired attribute set, so they are ignored.
5275 * The wired attribute of the page table entry is not a hardware
5276 * feature, so there is no need to invalidate any TLB entries.
5277 * Since pmap_demote_pde() for the wired entry must never fail,
5278 * pmap_delayed_invl_started()/finished() calls around the
5279 * function are not needed.
5282 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5284 vm_offset_t va_next;
5285 pml4_entry_t *pml4e;
5288 pt_entry_t *pte, PG_V;
5290 PG_V = pmap_valid_bit(pmap);
5292 for (; sva < eva; sva = va_next) {
5293 pml4e = pmap_pml4e(pmap, sva);
5294 if ((*pml4e & PG_V) == 0) {
5295 va_next = (sva + NBPML4) & ~PML4MASK;
5300 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5301 if ((*pdpe & PG_V) == 0) {
5302 va_next = (sva + NBPDP) & ~PDPMASK;
5307 va_next = (sva + NBPDR) & ~PDRMASK;
5310 pde = pmap_pdpe_to_pde(pdpe, sva);
5311 if ((*pde & PG_V) == 0)
5313 if ((*pde & PG_PS) != 0) {
5314 if ((*pde & PG_W) == 0)
5315 panic("pmap_unwire: pde %#jx is missing PG_W",
5319 * Are we unwiring the entire large page? If not,
5320 * demote the mapping and fall through.
5322 if (sva + NBPDR == va_next && eva >= va_next) {
5323 atomic_clear_long(pde, PG_W);
5324 pmap->pm_stats.wired_count -= NBPDR /
5327 } else if (!pmap_demote_pde(pmap, pde, sva))
5328 panic("pmap_unwire: demotion failed");
5332 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5334 if ((*pte & PG_V) == 0)
5336 if ((*pte & PG_W) == 0)
5337 panic("pmap_unwire: pte %#jx is missing PG_W",
5341 * PG_W must be cleared atomically. Although the pmap
5342 * lock synchronizes access to PG_W, another processor
5343 * could be setting PG_M and/or PG_A concurrently.
5345 atomic_clear_long(pte, PG_W);
5346 pmap->pm_stats.wired_count--;
5353 * Copy the range specified by src_addr/len
5354 * from the source map to the range dst_addr/len
5355 * in the destination map.
5357 * This routine is only advisory and need not do anything.
5361 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5362 vm_offset_t src_addr)
5364 struct rwlock *lock;
5365 struct spglist free;
5367 vm_offset_t end_addr = src_addr + len;
5368 vm_offset_t va_next;
5369 vm_page_t dst_pdpg, dstmpte, srcmpte;
5370 pt_entry_t PG_A, PG_M, PG_V;
5372 if (dst_addr != src_addr)
5375 if (dst_pmap->pm_type != src_pmap->pm_type)
5379 * EPT page table entries that require emulation of A/D bits are
5380 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5381 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5382 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5383 * implementations flag an EPT misconfiguration for exec-only
5384 * mappings we skip this function entirely for emulated pmaps.
5386 if (pmap_emulate_ad_bits(dst_pmap))
5390 if (dst_pmap < src_pmap) {
5391 PMAP_LOCK(dst_pmap);
5392 PMAP_LOCK(src_pmap);
5394 PMAP_LOCK(src_pmap);
5395 PMAP_LOCK(dst_pmap);
5398 PG_A = pmap_accessed_bit(dst_pmap);
5399 PG_M = pmap_modified_bit(dst_pmap);
5400 PG_V = pmap_valid_bit(dst_pmap);
5402 for (addr = src_addr; addr < end_addr; addr = va_next) {
5403 pt_entry_t *src_pte, *dst_pte;
5404 pml4_entry_t *pml4e;
5406 pd_entry_t srcptepaddr, *pde;
5408 KASSERT(addr < UPT_MIN_ADDRESS,
5409 ("pmap_copy: invalid to pmap_copy page tables"));
5411 pml4e = pmap_pml4e(src_pmap, addr);
5412 if ((*pml4e & PG_V) == 0) {
5413 va_next = (addr + NBPML4) & ~PML4MASK;
5419 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5420 if ((*pdpe & PG_V) == 0) {
5421 va_next = (addr + NBPDP) & ~PDPMASK;
5427 va_next = (addr + NBPDR) & ~PDRMASK;
5431 pde = pmap_pdpe_to_pde(pdpe, addr);
5433 if (srcptepaddr == 0)
5436 if (srcptepaddr & PG_PS) {
5437 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5439 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5440 if (dst_pdpg == NULL)
5442 pde = (pd_entry_t *)
5443 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5444 pde = &pde[pmap_pde_index(addr)];
5445 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5446 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5447 PMAP_ENTER_NORECLAIM, &lock))) {
5448 *pde = srcptepaddr & ~PG_W;
5449 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5450 atomic_add_long(&pmap_pde_mappings, 1);
5452 dst_pdpg->wire_count--;
5456 srcptepaddr &= PG_FRAME;
5457 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5458 KASSERT(srcmpte->wire_count > 0,
5459 ("pmap_copy: source page table page is unused"));
5461 if (va_next > end_addr)
5464 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5465 src_pte = &src_pte[pmap_pte_index(addr)];
5467 while (addr < va_next) {
5471 * we only virtual copy managed pages
5473 if ((ptetemp & PG_MANAGED) != 0) {
5474 if (dstmpte != NULL &&
5475 dstmpte->pindex == pmap_pde_pindex(addr))
5476 dstmpte->wire_count++;
5477 else if ((dstmpte = pmap_allocpte(dst_pmap,
5478 addr, NULL)) == NULL)
5480 dst_pte = (pt_entry_t *)
5481 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5482 dst_pte = &dst_pte[pmap_pte_index(addr)];
5483 if (*dst_pte == 0 &&
5484 pmap_try_insert_pv_entry(dst_pmap, addr,
5485 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5488 * Clear the wired, modified, and
5489 * accessed (referenced) bits
5492 *dst_pte = ptetemp & ~(PG_W | PG_M |
5494 pmap_resident_count_inc(dst_pmap, 1);
5497 if (pmap_unwire_ptp(dst_pmap, addr,
5500 * Although "addr" is not
5501 * mapped, paging-structure
5502 * caches could nonetheless
5503 * have entries that refer to
5504 * the freed page table pages.
5505 * Invalidate those entries.
5507 pmap_invalidate_page(dst_pmap,
5509 vm_page_free_pages_toq(&free,
5514 if (dstmpte->wire_count >= srcmpte->wire_count)
5524 PMAP_UNLOCK(src_pmap);
5525 PMAP_UNLOCK(dst_pmap);
5529 * Zero the specified hardware page.
5532 pmap_zero_page(vm_page_t m)
5534 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5536 pagezero((void *)va);
5540 * Zero an an area within a single hardware page. off and size must not
5541 * cover an area beyond a single hardware page.
5544 pmap_zero_page_area(vm_page_t m, int off, int size)
5546 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5548 if (off == 0 && size == PAGE_SIZE)
5549 pagezero((void *)va);
5551 bzero((char *)va + off, size);
5555 * Copy 1 specified hardware page to another.
5558 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5560 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5561 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5563 pagecopy((void *)src, (void *)dst);
5566 int unmapped_buf_allowed = 1;
5569 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5570 vm_offset_t b_offset, int xfersize)
5574 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5578 while (xfersize > 0) {
5579 a_pg_offset = a_offset & PAGE_MASK;
5580 pages[0] = ma[a_offset >> PAGE_SHIFT];
5581 b_pg_offset = b_offset & PAGE_MASK;
5582 pages[1] = mb[b_offset >> PAGE_SHIFT];
5583 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5584 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5585 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5586 a_cp = (char *)vaddr[0] + a_pg_offset;
5587 b_cp = (char *)vaddr[1] + b_pg_offset;
5588 bcopy(a_cp, b_cp, cnt);
5589 if (__predict_false(mapped))
5590 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5598 * Returns true if the pmap's pv is one of the first
5599 * 16 pvs linked to from this page. This count may
5600 * be changed upwards or downwards in the future; it
5601 * is only necessary that true be returned for a small
5602 * subset of pmaps for proper page aging.
5605 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5607 struct md_page *pvh;
5608 struct rwlock *lock;
5613 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5614 ("pmap_page_exists_quick: page %p is not managed", m));
5616 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5618 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5619 if (PV_PMAP(pv) == pmap) {
5627 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5628 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5629 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5630 if (PV_PMAP(pv) == pmap) {
5644 * pmap_page_wired_mappings:
5646 * Return the number of managed mappings to the given physical page
5650 pmap_page_wired_mappings(vm_page_t m)
5652 struct rwlock *lock;
5653 struct md_page *pvh;
5657 int count, md_gen, pvh_gen;
5659 if ((m->oflags & VPO_UNMANAGED) != 0)
5661 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5665 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5667 if (!PMAP_TRYLOCK(pmap)) {
5668 md_gen = m->md.pv_gen;
5672 if (md_gen != m->md.pv_gen) {
5677 pte = pmap_pte(pmap, pv->pv_va);
5678 if ((*pte & PG_W) != 0)
5682 if ((m->flags & PG_FICTITIOUS) == 0) {
5683 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5684 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5686 if (!PMAP_TRYLOCK(pmap)) {
5687 md_gen = m->md.pv_gen;
5688 pvh_gen = pvh->pv_gen;
5692 if (md_gen != m->md.pv_gen ||
5693 pvh_gen != pvh->pv_gen) {
5698 pte = pmap_pde(pmap, pv->pv_va);
5699 if ((*pte & PG_W) != 0)
5709 * Returns TRUE if the given page is mapped individually or as part of
5710 * a 2mpage. Otherwise, returns FALSE.
5713 pmap_page_is_mapped(vm_page_t m)
5715 struct rwlock *lock;
5718 if ((m->oflags & VPO_UNMANAGED) != 0)
5720 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5722 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5723 ((m->flags & PG_FICTITIOUS) == 0 &&
5724 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5730 * Destroy all managed, non-wired mappings in the given user-space
5731 * pmap. This pmap cannot be active on any processor besides the
5734 * This function cannot be applied to the kernel pmap. Moreover, it
5735 * is not intended for general use. It is only to be used during
5736 * process termination. Consequently, it can be implemented in ways
5737 * that make it faster than pmap_remove(). First, it can more quickly
5738 * destroy mappings by iterating over the pmap's collection of PV
5739 * entries, rather than searching the page table. Second, it doesn't
5740 * have to test and clear the page table entries atomically, because
5741 * no processor is currently accessing the user address space. In
5742 * particular, a page table entry's dirty bit won't change state once
5743 * this function starts.
5745 * Although this function destroys all of the pmap's managed,
5746 * non-wired mappings, it can delay and batch the invalidation of TLB
5747 * entries without calling pmap_delayed_invl_started() and
5748 * pmap_delayed_invl_finished(). Because the pmap is not active on
5749 * any other processor, none of these TLB entries will ever be used
5750 * before their eventual invalidation. Consequently, there is no need
5751 * for either pmap_remove_all() or pmap_remove_write() to wait for
5752 * that eventual TLB invalidation.
5755 pmap_remove_pages(pmap_t pmap)
5758 pt_entry_t *pte, tpte;
5759 pt_entry_t PG_M, PG_RW, PG_V;
5760 struct spglist free;
5761 vm_page_t m, mpte, mt;
5763 struct md_page *pvh;
5764 struct pv_chunk *pc, *npc;
5765 struct rwlock *lock;
5767 uint64_t inuse, bitmask;
5768 int allfree, field, freed, idx;
5769 boolean_t superpage;
5773 * Assert that the given pmap is only active on the current
5774 * CPU. Unfortunately, we cannot block another CPU from
5775 * activating the pmap while this function is executing.
5777 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5780 cpuset_t other_cpus;
5782 other_cpus = all_cpus;
5784 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5785 CPU_AND(&other_cpus, &pmap->pm_active);
5787 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5792 PG_M = pmap_modified_bit(pmap);
5793 PG_V = pmap_valid_bit(pmap);
5794 PG_RW = pmap_rw_bit(pmap);
5798 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5801 for (field = 0; field < _NPCM; field++) {
5802 inuse = ~pc->pc_map[field] & pc_freemask[field];
5803 while (inuse != 0) {
5805 bitmask = 1UL << bit;
5806 idx = field * 64 + bit;
5807 pv = &pc->pc_pventry[idx];
5810 pte = pmap_pdpe(pmap, pv->pv_va);
5812 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5814 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5817 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5819 pte = &pte[pmap_pte_index(pv->pv_va)];
5823 * Keep track whether 'tpte' is a
5824 * superpage explicitly instead of
5825 * relying on PG_PS being set.
5827 * This is because PG_PS is numerically
5828 * identical to PG_PTE_PAT and thus a
5829 * regular page could be mistaken for
5835 if ((tpte & PG_V) == 0) {
5836 panic("bad pte va %lx pte %lx",
5841 * We cannot remove wired pages from a process' mapping at this time
5849 pa = tpte & PG_PS_FRAME;
5851 pa = tpte & PG_FRAME;
5853 m = PHYS_TO_VM_PAGE(pa);
5854 KASSERT(m->phys_addr == pa,
5855 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5856 m, (uintmax_t)m->phys_addr,
5859 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5860 m < &vm_page_array[vm_page_array_size],
5861 ("pmap_remove_pages: bad tpte %#jx",
5867 * Update the vm_page_t clean/reference bits.
5869 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5871 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5877 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5880 pc->pc_map[field] |= bitmask;
5882 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5883 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5884 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5886 if (TAILQ_EMPTY(&pvh->pv_list)) {
5887 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5888 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5889 TAILQ_EMPTY(&mt->md.pv_list))
5890 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5892 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5894 pmap_resident_count_dec(pmap, 1);
5895 KASSERT(mpte->wire_count == NPTEPG,
5896 ("pmap_remove_pages: pte page wire count error"));
5897 mpte->wire_count = 0;
5898 pmap_add_delayed_free_list(mpte, &free, FALSE);
5901 pmap_resident_count_dec(pmap, 1);
5902 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5904 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5905 TAILQ_EMPTY(&m->md.pv_list) &&
5906 (m->flags & PG_FICTITIOUS) == 0) {
5907 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5908 if (TAILQ_EMPTY(&pvh->pv_list))
5909 vm_page_aflag_clear(m, PGA_WRITEABLE);
5912 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5916 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5917 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5918 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5920 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5926 pmap_invalidate_all(pmap);
5928 vm_page_free_pages_toq(&free, true);
5932 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5934 struct rwlock *lock;
5936 struct md_page *pvh;
5937 pt_entry_t *pte, mask;
5938 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5940 int md_gen, pvh_gen;
5944 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5947 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5949 if (!PMAP_TRYLOCK(pmap)) {
5950 md_gen = m->md.pv_gen;
5954 if (md_gen != m->md.pv_gen) {
5959 pte = pmap_pte(pmap, pv->pv_va);
5962 PG_M = pmap_modified_bit(pmap);
5963 PG_RW = pmap_rw_bit(pmap);
5964 mask |= PG_RW | PG_M;
5967 PG_A = pmap_accessed_bit(pmap);
5968 PG_V = pmap_valid_bit(pmap);
5969 mask |= PG_V | PG_A;
5971 rv = (*pte & mask) == mask;
5976 if ((m->flags & PG_FICTITIOUS) == 0) {
5977 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5978 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5980 if (!PMAP_TRYLOCK(pmap)) {
5981 md_gen = m->md.pv_gen;
5982 pvh_gen = pvh->pv_gen;
5986 if (md_gen != m->md.pv_gen ||
5987 pvh_gen != pvh->pv_gen) {
5992 pte = pmap_pde(pmap, pv->pv_va);
5995 PG_M = pmap_modified_bit(pmap);
5996 PG_RW = pmap_rw_bit(pmap);
5997 mask |= PG_RW | PG_M;
6000 PG_A = pmap_accessed_bit(pmap);
6001 PG_V = pmap_valid_bit(pmap);
6002 mask |= PG_V | PG_A;
6004 rv = (*pte & mask) == mask;
6018 * Return whether or not the specified physical page was modified
6019 * in any physical maps.
6022 pmap_is_modified(vm_page_t m)
6025 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6026 ("pmap_is_modified: page %p is not managed", m));
6029 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6030 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6031 * is clear, no PTEs can have PG_M set.
6033 VM_OBJECT_ASSERT_WLOCKED(m->object);
6034 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6036 return (pmap_page_test_mappings(m, FALSE, TRUE));
6040 * pmap_is_prefaultable:
6042 * Return whether or not the specified virtual address is eligible
6046 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6049 pt_entry_t *pte, PG_V;
6052 PG_V = pmap_valid_bit(pmap);
6055 pde = pmap_pde(pmap, addr);
6056 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6057 pte = pmap_pde_to_pte(pde, addr);
6058 rv = (*pte & PG_V) == 0;
6065 * pmap_is_referenced:
6067 * Return whether or not the specified physical page was referenced
6068 * in any physical maps.
6071 pmap_is_referenced(vm_page_t m)
6074 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6075 ("pmap_is_referenced: page %p is not managed", m));
6076 return (pmap_page_test_mappings(m, TRUE, FALSE));
6080 * Clear the write and modified bits in each of the given page's mappings.
6083 pmap_remove_write(vm_page_t m)
6085 struct md_page *pvh;
6087 struct rwlock *lock;
6088 pv_entry_t next_pv, pv;
6090 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6092 int pvh_gen, md_gen;
6094 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6095 ("pmap_remove_write: page %p is not managed", m));
6098 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6099 * set by another thread while the object is locked. Thus,
6100 * if PGA_WRITEABLE is clear, no page table entries need updating.
6102 VM_OBJECT_ASSERT_WLOCKED(m->object);
6103 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6105 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6106 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6107 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6110 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6112 if (!PMAP_TRYLOCK(pmap)) {
6113 pvh_gen = pvh->pv_gen;
6117 if (pvh_gen != pvh->pv_gen) {
6123 PG_RW = pmap_rw_bit(pmap);
6125 pde = pmap_pde(pmap, va);
6126 if ((*pde & PG_RW) != 0)
6127 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6128 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6129 ("inconsistent pv lock %p %p for page %p",
6130 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6133 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6135 if (!PMAP_TRYLOCK(pmap)) {
6136 pvh_gen = pvh->pv_gen;
6137 md_gen = m->md.pv_gen;
6141 if (pvh_gen != pvh->pv_gen ||
6142 md_gen != m->md.pv_gen) {
6148 PG_M = pmap_modified_bit(pmap);
6149 PG_RW = pmap_rw_bit(pmap);
6150 pde = pmap_pde(pmap, pv->pv_va);
6151 KASSERT((*pde & PG_PS) == 0,
6152 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6154 pte = pmap_pde_to_pte(pde, pv->pv_va);
6157 if (oldpte & PG_RW) {
6158 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6161 if ((oldpte & PG_M) != 0)
6163 pmap_invalidate_page(pmap, pv->pv_va);
6168 vm_page_aflag_clear(m, PGA_WRITEABLE);
6169 pmap_delayed_invl_wait(m);
6172 static __inline boolean_t
6173 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6176 if (!pmap_emulate_ad_bits(pmap))
6179 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6182 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6183 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6184 * if the EPT_PG_WRITE bit is set.
6186 if ((pte & EPT_PG_WRITE) != 0)
6190 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6192 if ((pte & EPT_PG_EXECUTE) == 0 ||
6193 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6200 * pmap_ts_referenced:
6202 * Return a count of reference bits for a page, clearing those bits.
6203 * It is not necessary for every reference bit to be cleared, but it
6204 * is necessary that 0 only be returned when there are truly no
6205 * reference bits set.
6207 * As an optimization, update the page's dirty field if a modified bit is
6208 * found while counting reference bits. This opportunistic update can be
6209 * performed at low cost and can eliminate the need for some future calls
6210 * to pmap_is_modified(). However, since this function stops after
6211 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6212 * dirty pages. Those dirty pages will only be detected by a future call
6213 * to pmap_is_modified().
6215 * A DI block is not needed within this function, because
6216 * invalidations are performed before the PV list lock is
6220 pmap_ts_referenced(vm_page_t m)
6222 struct md_page *pvh;
6225 struct rwlock *lock;
6226 pd_entry_t oldpde, *pde;
6227 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6230 int cleared, md_gen, not_cleared, pvh_gen;
6231 struct spglist free;
6234 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6235 ("pmap_ts_referenced: page %p is not managed", m));
6238 pa = VM_PAGE_TO_PHYS(m);
6239 lock = PHYS_TO_PV_LIST_LOCK(pa);
6240 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6244 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6245 goto small_mappings;
6251 if (!PMAP_TRYLOCK(pmap)) {
6252 pvh_gen = pvh->pv_gen;
6256 if (pvh_gen != pvh->pv_gen) {
6261 PG_A = pmap_accessed_bit(pmap);
6262 PG_M = pmap_modified_bit(pmap);
6263 PG_RW = pmap_rw_bit(pmap);
6265 pde = pmap_pde(pmap, pv->pv_va);
6267 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6269 * Although "oldpde" is mapping a 2MB page, because
6270 * this function is called at a 4KB page granularity,
6271 * we only update the 4KB page under test.
6275 if ((oldpde & PG_A) != 0) {
6277 * Since this reference bit is shared by 512 4KB
6278 * pages, it should not be cleared every time it is
6279 * tested. Apply a simple "hash" function on the
6280 * physical page number, the virtual superpage number,
6281 * and the pmap address to select one 4KB page out of
6282 * the 512 on which testing the reference bit will
6283 * result in clearing that reference bit. This
6284 * function is designed to avoid the selection of the
6285 * same 4KB page for every 2MB page mapping.
6287 * On demotion, a mapping that hasn't been referenced
6288 * is simply destroyed. To avoid the possibility of a
6289 * subsequent page fault on a demoted wired mapping,
6290 * always leave its reference bit set. Moreover,
6291 * since the superpage is wired, the current state of
6292 * its reference bit won't affect page replacement.
6294 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6295 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6296 (oldpde & PG_W) == 0) {
6297 if (safe_to_clear_referenced(pmap, oldpde)) {
6298 atomic_clear_long(pde, PG_A);
6299 pmap_invalidate_page(pmap, pv->pv_va);
6301 } else if (pmap_demote_pde_locked(pmap, pde,
6302 pv->pv_va, &lock)) {
6304 * Remove the mapping to a single page
6305 * so that a subsequent access may
6306 * repromote. Since the underlying
6307 * page table page is fully populated,
6308 * this removal never frees a page
6312 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6314 pte = pmap_pde_to_pte(pde, va);
6315 pmap_remove_pte(pmap, pte, va, *pde,
6317 pmap_invalidate_page(pmap, va);
6323 * The superpage mapping was removed
6324 * entirely and therefore 'pv' is no
6332 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6333 ("inconsistent pv lock %p %p for page %p",
6334 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6339 /* Rotate the PV list if it has more than one entry. */
6340 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6341 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6342 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6345 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6347 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6349 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6356 if (!PMAP_TRYLOCK(pmap)) {
6357 pvh_gen = pvh->pv_gen;
6358 md_gen = m->md.pv_gen;
6362 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6367 PG_A = pmap_accessed_bit(pmap);
6368 PG_M = pmap_modified_bit(pmap);
6369 PG_RW = pmap_rw_bit(pmap);
6370 pde = pmap_pde(pmap, pv->pv_va);
6371 KASSERT((*pde & PG_PS) == 0,
6372 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6374 pte = pmap_pde_to_pte(pde, pv->pv_va);
6375 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6377 if ((*pte & PG_A) != 0) {
6378 if (safe_to_clear_referenced(pmap, *pte)) {
6379 atomic_clear_long(pte, PG_A);
6380 pmap_invalidate_page(pmap, pv->pv_va);
6382 } else if ((*pte & PG_W) == 0) {
6384 * Wired pages cannot be paged out so
6385 * doing accessed bit emulation for
6386 * them is wasted effort. We do the
6387 * hard work for unwired pages only.
6389 pmap_remove_pte(pmap, pte, pv->pv_va,
6390 *pde, &free, &lock);
6391 pmap_invalidate_page(pmap, pv->pv_va);
6396 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6397 ("inconsistent pv lock %p %p for page %p",
6398 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6403 /* Rotate the PV list if it has more than one entry. */
6404 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6405 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6406 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6409 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6410 not_cleared < PMAP_TS_REFERENCED_MAX);
6413 vm_page_free_pages_toq(&free, true);
6414 return (cleared + not_cleared);
6418 * Apply the given advice to the specified range of addresses within the
6419 * given pmap. Depending on the advice, clear the referenced and/or
6420 * modified flags in each mapping and set the mapped page's dirty field.
6423 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6425 struct rwlock *lock;
6426 pml4_entry_t *pml4e;
6428 pd_entry_t oldpde, *pde;
6429 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6430 vm_offset_t va, va_next;
6432 boolean_t anychanged;
6434 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6438 * A/D bit emulation requires an alternate code path when clearing
6439 * the modified and accessed bits below. Since this function is
6440 * advisory in nature we skip it entirely for pmaps that require
6441 * A/D bit emulation.
6443 if (pmap_emulate_ad_bits(pmap))
6446 PG_A = pmap_accessed_bit(pmap);
6447 PG_G = pmap_global_bit(pmap);
6448 PG_M = pmap_modified_bit(pmap);
6449 PG_V = pmap_valid_bit(pmap);
6450 PG_RW = pmap_rw_bit(pmap);
6452 pmap_delayed_invl_started();
6454 for (; sva < eva; sva = va_next) {
6455 pml4e = pmap_pml4e(pmap, sva);
6456 if ((*pml4e & PG_V) == 0) {
6457 va_next = (sva + NBPML4) & ~PML4MASK;
6462 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6463 if ((*pdpe & PG_V) == 0) {
6464 va_next = (sva + NBPDP) & ~PDPMASK;
6469 va_next = (sva + NBPDR) & ~PDRMASK;
6472 pde = pmap_pdpe_to_pde(pdpe, sva);
6474 if ((oldpde & PG_V) == 0)
6476 else if ((oldpde & PG_PS) != 0) {
6477 if ((oldpde & PG_MANAGED) == 0)
6480 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6485 * The large page mapping was destroyed.
6491 * Unless the page mappings are wired, remove the
6492 * mapping to a single page so that a subsequent
6493 * access may repromote. Since the underlying page
6494 * table page is fully populated, this removal never
6495 * frees a page table page.
6497 if ((oldpde & PG_W) == 0) {
6498 pte = pmap_pde_to_pte(pde, sva);
6499 KASSERT((*pte & PG_V) != 0,
6500 ("pmap_advise: invalid PTE"));
6501 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6511 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6513 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6515 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6516 if (advice == MADV_DONTNEED) {
6518 * Future calls to pmap_is_modified()
6519 * can be avoided by making the page
6522 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6525 atomic_clear_long(pte, PG_M | PG_A);
6526 } else if ((*pte & PG_A) != 0)
6527 atomic_clear_long(pte, PG_A);
6531 if ((*pte & PG_G) != 0) {
6538 if (va != va_next) {
6539 pmap_invalidate_range(pmap, va, sva);
6544 pmap_invalidate_range(pmap, va, sva);
6547 pmap_invalidate_all(pmap);
6549 pmap_delayed_invl_finished();
6553 * Clear the modify bits on the specified physical page.
6556 pmap_clear_modify(vm_page_t m)
6558 struct md_page *pvh;
6560 pv_entry_t next_pv, pv;
6561 pd_entry_t oldpde, *pde;
6562 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6563 struct rwlock *lock;
6565 int md_gen, pvh_gen;
6567 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6568 ("pmap_clear_modify: page %p is not managed", m));
6569 VM_OBJECT_ASSERT_WLOCKED(m->object);
6570 KASSERT(!vm_page_xbusied(m),
6571 ("pmap_clear_modify: page %p is exclusive busied", m));
6574 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6575 * If the object containing the page is locked and the page is not
6576 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6578 if ((m->aflags & PGA_WRITEABLE) == 0)
6580 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6581 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6582 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6585 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6587 if (!PMAP_TRYLOCK(pmap)) {
6588 pvh_gen = pvh->pv_gen;
6592 if (pvh_gen != pvh->pv_gen) {
6597 PG_M = pmap_modified_bit(pmap);
6598 PG_V = pmap_valid_bit(pmap);
6599 PG_RW = pmap_rw_bit(pmap);
6601 pde = pmap_pde(pmap, va);
6603 if ((oldpde & PG_RW) != 0) {
6604 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6605 if ((oldpde & PG_W) == 0) {
6607 * Write protect the mapping to a
6608 * single page so that a subsequent
6609 * write access may repromote.
6611 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6613 pte = pmap_pde_to_pte(pde, va);
6615 if ((oldpte & PG_V) != 0) {
6616 while (!atomic_cmpset_long(pte,
6618 oldpte & ~(PG_M | PG_RW)))
6621 pmap_invalidate_page(pmap, va);
6628 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6630 if (!PMAP_TRYLOCK(pmap)) {
6631 md_gen = m->md.pv_gen;
6632 pvh_gen = pvh->pv_gen;
6636 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6641 PG_M = pmap_modified_bit(pmap);
6642 PG_RW = pmap_rw_bit(pmap);
6643 pde = pmap_pde(pmap, pv->pv_va);
6644 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6645 " a 2mpage in page %p's pv list", m));
6646 pte = pmap_pde_to_pte(pde, pv->pv_va);
6647 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6648 atomic_clear_long(pte, PG_M);
6649 pmap_invalidate_page(pmap, pv->pv_va);
6657 * Miscellaneous support routines follow
6660 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6661 static __inline void
6662 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6667 * The cache mode bits are all in the low 32-bits of the
6668 * PTE, so we can just spin on updating the low 32-bits.
6671 opte = *(u_int *)pte;
6672 npte = opte & ~mask;
6674 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6677 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6678 static __inline void
6679 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6684 * The cache mode bits are all in the low 32-bits of the
6685 * PDE, so we can just spin on updating the low 32-bits.
6688 opde = *(u_int *)pde;
6689 npde = opde & ~mask;
6691 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6695 * Map a set of physical memory pages into the kernel virtual
6696 * address space. Return a pointer to where it is mapped. This
6697 * routine is intended to be used for mapping device memory,
6701 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6703 struct pmap_preinit_mapping *ppim;
6704 vm_offset_t va, offset;
6708 offset = pa & PAGE_MASK;
6709 size = round_page(offset + size);
6710 pa = trunc_page(pa);
6712 if (!pmap_initialized) {
6714 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6715 ppim = pmap_preinit_mapping + i;
6716 if (ppim->va == 0) {
6720 ppim->va = virtual_avail;
6721 virtual_avail += size;
6727 panic("%s: too many preinit mappings", __func__);
6730 * If we have a preinit mapping, re-use it.
6732 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6733 ppim = pmap_preinit_mapping + i;
6734 if (ppim->pa == pa && ppim->sz == size &&
6736 return ((void *)(ppim->va + offset));
6739 * If the specified range of physical addresses fits within
6740 * the direct map window, use the direct map.
6742 if (pa < dmaplimit && pa + size < dmaplimit) {
6743 va = PHYS_TO_DMAP(pa);
6744 if (!pmap_change_attr(va, size, mode))
6745 return ((void *)(va + offset));
6747 va = kva_alloc(size);
6749 panic("%s: Couldn't allocate KVA", __func__);
6751 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6752 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6753 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6754 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6755 return ((void *)(va + offset));
6759 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6762 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6766 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6769 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6773 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6775 struct pmap_preinit_mapping *ppim;
6779 /* If we gave a direct map region in pmap_mapdev, do nothing */
6780 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6782 offset = va & PAGE_MASK;
6783 size = round_page(offset + size);
6784 va = trunc_page(va);
6785 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6786 ppim = pmap_preinit_mapping + i;
6787 if (ppim->va == va && ppim->sz == size) {
6788 if (pmap_initialized)
6794 if (va + size == virtual_avail)
6799 if (pmap_initialized)
6804 * Tries to demote a 1GB page mapping.
6807 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6809 pdp_entry_t newpdpe, oldpdpe;
6810 pd_entry_t *firstpde, newpde, *pde;
6811 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6815 PG_A = pmap_accessed_bit(pmap);
6816 PG_M = pmap_modified_bit(pmap);
6817 PG_V = pmap_valid_bit(pmap);
6818 PG_RW = pmap_rw_bit(pmap);
6820 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6822 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6823 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6824 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6825 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6826 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6827 " in pmap %p", va, pmap);
6830 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6831 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6832 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6833 KASSERT((oldpdpe & PG_A) != 0,
6834 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6835 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6836 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6840 * Initialize the page directory page.
6842 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6848 * Demote the mapping.
6853 * Invalidate a stale recursive mapping of the page directory page.
6855 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6857 pmap_pdpe_demotions++;
6858 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6859 " in pmap %p", va, pmap);
6864 * Sets the memory attribute for the specified page.
6867 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6870 m->md.pat_mode = ma;
6873 * If "m" is a normal page, update its direct mapping. This update
6874 * can be relied upon to perform any cache operations that are
6875 * required for data coherence.
6877 if ((m->flags & PG_FICTITIOUS) == 0 &&
6878 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6880 panic("memory attribute change on the direct map failed");
6884 * Changes the specified virtual address range's memory type to that given by
6885 * the parameter "mode". The specified virtual address range must be
6886 * completely contained within either the direct map or the kernel map. If
6887 * the virtual address range is contained within the kernel map, then the
6888 * memory type for each of the corresponding ranges of the direct map is also
6889 * changed. (The corresponding ranges of the direct map are those ranges that
6890 * map the same physical pages as the specified virtual address range.) These
6891 * changes to the direct map are necessary because Intel describes the
6892 * behavior of their processors as "undefined" if two or more mappings to the
6893 * same physical page have different memory types.
6895 * Returns zero if the change completed successfully, and either EINVAL or
6896 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6897 * of the virtual address range was not mapped, and ENOMEM is returned if
6898 * there was insufficient memory available to complete the change. In the
6899 * latter case, the memory type may have been changed on some part of the
6900 * virtual address range or the direct map.
6903 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6907 PMAP_LOCK(kernel_pmap);
6908 error = pmap_change_attr_locked(va, size, mode);
6909 PMAP_UNLOCK(kernel_pmap);
6914 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6916 vm_offset_t base, offset, tmpva;
6917 vm_paddr_t pa_start, pa_end, pa_end1;
6921 int cache_bits_pte, cache_bits_pde, error;
6924 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6925 base = trunc_page(va);
6926 offset = va & PAGE_MASK;
6927 size = round_page(offset + size);
6930 * Only supported on kernel virtual addresses, including the direct
6931 * map but excluding the recursive map.
6933 if (base < DMAP_MIN_ADDRESS)
6936 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6937 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6941 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6942 * into 4KB pages if required.
6944 for (tmpva = base; tmpva < base + size; ) {
6945 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6946 if (pdpe == NULL || *pdpe == 0)
6948 if (*pdpe & PG_PS) {
6950 * If the current 1GB page already has the required
6951 * memory type, then we need not demote this page. Just
6952 * increment tmpva to the next 1GB page frame.
6954 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6955 tmpva = trunc_1gpage(tmpva) + NBPDP;
6960 * If the current offset aligns with a 1GB page frame
6961 * and there is at least 1GB left within the range, then
6962 * we need not break down this page into 2MB pages.
6964 if ((tmpva & PDPMASK) == 0 &&
6965 tmpva + PDPMASK < base + size) {
6969 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6972 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6977 * If the current 2MB page already has the required
6978 * memory type, then we need not demote this page. Just
6979 * increment tmpva to the next 2MB page frame.
6981 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6982 tmpva = trunc_2mpage(tmpva) + NBPDR;
6987 * If the current offset aligns with a 2MB page frame
6988 * and there is at least 2MB left within the range, then
6989 * we need not break down this page into 4KB pages.
6991 if ((tmpva & PDRMASK) == 0 &&
6992 tmpva + PDRMASK < base + size) {
6996 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6999 pte = pmap_pde_to_pte(pde, tmpva);
7007 * Ok, all the pages exist, so run through them updating their
7008 * cache mode if required.
7010 pa_start = pa_end = 0;
7011 for (tmpva = base; tmpva < base + size; ) {
7012 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7013 if (*pdpe & PG_PS) {
7014 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7015 pmap_pde_attr(pdpe, cache_bits_pde,
7019 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7020 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7021 if (pa_start == pa_end) {
7022 /* Start physical address run. */
7023 pa_start = *pdpe & PG_PS_FRAME;
7024 pa_end = pa_start + NBPDP;
7025 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7028 /* Run ended, update direct map. */
7029 error = pmap_change_attr_locked(
7030 PHYS_TO_DMAP(pa_start),
7031 pa_end - pa_start, mode);
7034 /* Start physical address run. */
7035 pa_start = *pdpe & PG_PS_FRAME;
7036 pa_end = pa_start + NBPDP;
7039 tmpva = trunc_1gpage(tmpva) + NBPDP;
7042 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7044 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7045 pmap_pde_attr(pde, cache_bits_pde,
7049 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7050 (*pde & PG_PS_FRAME) < dmaplimit) {
7051 if (pa_start == pa_end) {
7052 /* Start physical address run. */
7053 pa_start = *pde & PG_PS_FRAME;
7054 pa_end = pa_start + NBPDR;
7055 } else if (pa_end == (*pde & PG_PS_FRAME))
7058 /* Run ended, update direct map. */
7059 error = pmap_change_attr_locked(
7060 PHYS_TO_DMAP(pa_start),
7061 pa_end - pa_start, mode);
7064 /* Start physical address run. */
7065 pa_start = *pde & PG_PS_FRAME;
7066 pa_end = pa_start + NBPDR;
7069 tmpva = trunc_2mpage(tmpva) + NBPDR;
7071 pte = pmap_pde_to_pte(pde, tmpva);
7072 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7073 pmap_pte_attr(pte, cache_bits_pte,
7077 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7078 (*pte & PG_FRAME) < dmaplimit) {
7079 if (pa_start == pa_end) {
7080 /* Start physical address run. */
7081 pa_start = *pte & PG_FRAME;
7082 pa_end = pa_start + PAGE_SIZE;
7083 } else if (pa_end == (*pte & PG_FRAME))
7084 pa_end += PAGE_SIZE;
7086 /* Run ended, update direct map. */
7087 error = pmap_change_attr_locked(
7088 PHYS_TO_DMAP(pa_start),
7089 pa_end - pa_start, mode);
7092 /* Start physical address run. */
7093 pa_start = *pte & PG_FRAME;
7094 pa_end = pa_start + PAGE_SIZE;
7100 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7101 pa_end1 = MIN(pa_end, dmaplimit);
7102 if (pa_start != pa_end1)
7103 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7104 pa_end1 - pa_start, mode);
7108 * Flush CPU caches if required to make sure any data isn't cached that
7109 * shouldn't be, etc.
7112 pmap_invalidate_range(kernel_pmap, base, tmpva);
7113 pmap_invalidate_cache_range(base, tmpva, FALSE);
7119 * Demotes any mapping within the direct map region that covers more than the
7120 * specified range of physical addresses. This range's size must be a power
7121 * of two and its starting address must be a multiple of its size. Since the
7122 * demotion does not change any attributes of the mapping, a TLB invalidation
7123 * is not mandatory. The caller may, however, request a TLB invalidation.
7126 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7135 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7136 KASSERT((base & (len - 1)) == 0,
7137 ("pmap_demote_DMAP: base is not a multiple of len"));
7138 if (len < NBPDP && base < dmaplimit) {
7139 va = PHYS_TO_DMAP(base);
7141 PMAP_LOCK(kernel_pmap);
7142 pdpe = pmap_pdpe(kernel_pmap, va);
7143 if ((*pdpe & X86_PG_V) == 0)
7144 panic("pmap_demote_DMAP: invalid PDPE");
7145 if ((*pdpe & PG_PS) != 0) {
7146 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7147 panic("pmap_demote_DMAP: PDPE failed");
7151 pde = pmap_pdpe_to_pde(pdpe, va);
7152 if ((*pde & X86_PG_V) == 0)
7153 panic("pmap_demote_DMAP: invalid PDE");
7154 if ((*pde & PG_PS) != 0) {
7155 if (!pmap_demote_pde(kernel_pmap, pde, va))
7156 panic("pmap_demote_DMAP: PDE failed");
7160 if (changed && invalidate)
7161 pmap_invalidate_page(kernel_pmap, va);
7162 PMAP_UNLOCK(kernel_pmap);
7167 * perform the pmap work for mincore
7170 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7173 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7177 PG_A = pmap_accessed_bit(pmap);
7178 PG_M = pmap_modified_bit(pmap);
7179 PG_V = pmap_valid_bit(pmap);
7180 PG_RW = pmap_rw_bit(pmap);
7184 pdep = pmap_pde(pmap, addr);
7185 if (pdep != NULL && (*pdep & PG_V)) {
7186 if (*pdep & PG_PS) {
7188 /* Compute the physical address of the 4KB page. */
7189 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7191 val = MINCORE_SUPER;
7193 pte = *pmap_pde_to_pte(pdep, addr);
7194 pa = pte & PG_FRAME;
7202 if ((pte & PG_V) != 0) {
7203 val |= MINCORE_INCORE;
7204 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7205 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7206 if ((pte & PG_A) != 0)
7207 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7209 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7210 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7211 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7212 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7213 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7216 PA_UNLOCK_COND(*locked_pa);
7222 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7224 uint32_t gen, new_gen, pcid_next;
7226 CRITICAL_ASSERT(curthread);
7227 gen = PCPU_GET(pcid_gen);
7228 if (!pti && (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7229 pmap->pm_pcids[cpuid].pm_gen == gen))
7230 return (CR3_PCID_SAVE);
7231 pcid_next = PCPU_GET(pcid_next);
7232 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7233 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7234 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7235 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7236 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7240 PCPU_SET(pcid_gen, new_gen);
7241 pcid_next = PMAP_PCID_KERN + 1;
7245 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7246 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7247 PCPU_SET(pcid_next, pcid_next + 1);
7252 pmap_activate_sw(struct thread *td)
7254 pmap_t oldpmap, pmap;
7255 struct invpcid_descr d;
7256 uint64_t cached, cr3, kcr3, ucr3;
7260 oldpmap = PCPU_GET(curpmap);
7261 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7262 if (oldpmap == pmap)
7264 cpuid = PCPU_GET(cpuid);
7266 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7268 CPU_SET(cpuid, &pmap->pm_active);
7271 if (pmap_pcid_enabled) {
7272 cached = pmap_pcid_alloc(pmap, cpuid);
7273 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7274 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7275 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7276 pmap->pm_pcids[cpuid].pm_pcid));
7277 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7278 pmap == kernel_pmap,
7279 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7280 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7283 * If the INVPCID instruction is not available,
7284 * invltlb_pcid_handler() is used for handle
7285 * invalidate_all IPI, which checks for curpmap ==
7286 * smp_tlb_pmap. Below operations sequence has a
7287 * window where %CR3 is loaded with the new pmap's
7288 * PML4 address, but curpmap value is not yet updated.
7289 * This causes invltlb IPI handler, called between the
7290 * updates, to execute as NOP, which leaves stale TLB
7293 * Note that the most typical use of
7294 * pmap_activate_sw(), from the context switch, is
7295 * immune to this race, because interrupts are
7296 * disabled (while the thread lock is owned), and IPI
7297 * happends after curpmap is updated. Protect other
7298 * callers in a similar way, by disabling interrupts
7299 * around the %cr3 register reload and curpmap
7303 rflags = intr_disable();
7305 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7306 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7309 PCPU_INC(pm_save_cnt);
7311 PCPU_SET(curpmap, pmap);
7313 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7314 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7318 * Manually invalidate translations cached
7319 * from the user page table, which are not
7320 * flushed by reload of cr3 with the kernel
7321 * page table pointer above.
7323 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7324 if (invpcid_works) {
7325 d.pcid = PMAP_PCID_USER_PT |
7326 pmap->pm_pcids[cpuid].pm_pcid;
7329 invpcid(&d, INVPCID_CTX);
7331 pmap_pti_pcid_invalidate(ucr3, kcr3);
7335 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7336 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7339 intr_restore(rflags);
7340 } else if (cr3 != pmap->pm_cr3) {
7341 load_cr3(pmap->pm_cr3);
7342 PCPU_SET(curpmap, pmap);
7344 PCPU_SET(kcr3, pmap->pm_cr3);
7345 PCPU_SET(ucr3, pmap->pm_ucr3);
7349 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7351 CPU_CLR(cpuid, &oldpmap->pm_active);
7356 pmap_activate(struct thread *td)
7360 pmap_activate_sw(td);
7365 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7370 * Increase the starting virtual address of the given mapping if a
7371 * different alignment might result in more superpage mappings.
7374 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7375 vm_offset_t *addr, vm_size_t size)
7377 vm_offset_t superpage_offset;
7381 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7382 offset += ptoa(object->pg_color);
7383 superpage_offset = offset & PDRMASK;
7384 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7385 (*addr & PDRMASK) == superpage_offset)
7387 if ((*addr & PDRMASK) < superpage_offset)
7388 *addr = (*addr & ~PDRMASK) + superpage_offset;
7390 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7394 static unsigned long num_dirty_emulations;
7395 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7396 &num_dirty_emulations, 0, NULL);
7398 static unsigned long num_accessed_emulations;
7399 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7400 &num_accessed_emulations, 0, NULL);
7402 static unsigned long num_superpage_accessed_emulations;
7403 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7404 &num_superpage_accessed_emulations, 0, NULL);
7406 static unsigned long ad_emulation_superpage_promotions;
7407 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7408 &ad_emulation_superpage_promotions, 0, NULL);
7409 #endif /* INVARIANTS */
7412 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7415 struct rwlock *lock;
7416 #if VM_NRESERVLEVEL > 0
7420 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7422 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7423 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7425 if (!pmap_emulate_ad_bits(pmap))
7428 PG_A = pmap_accessed_bit(pmap);
7429 PG_M = pmap_modified_bit(pmap);
7430 PG_V = pmap_valid_bit(pmap);
7431 PG_RW = pmap_rw_bit(pmap);
7437 pde = pmap_pde(pmap, va);
7438 if (pde == NULL || (*pde & PG_V) == 0)
7441 if ((*pde & PG_PS) != 0) {
7442 if (ftype == VM_PROT_READ) {
7444 atomic_add_long(&num_superpage_accessed_emulations, 1);
7452 pte = pmap_pde_to_pte(pde, va);
7453 if ((*pte & PG_V) == 0)
7456 if (ftype == VM_PROT_WRITE) {
7457 if ((*pte & PG_RW) == 0)
7460 * Set the modified and accessed bits simultaneously.
7462 * Intel EPT PTEs that do software emulation of A/D bits map
7463 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7464 * An EPT misconfiguration is triggered if the PTE is writable
7465 * but not readable (WR=10). This is avoided by setting PG_A
7466 * and PG_M simultaneously.
7468 *pte |= PG_M | PG_A;
7473 #if VM_NRESERVLEVEL > 0
7474 /* try to promote the mapping */
7475 if (va < VM_MAXUSER_ADDRESS)
7476 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7480 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7482 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7483 pmap_ps_enabled(pmap) &&
7484 (m->flags & PG_FICTITIOUS) == 0 &&
7485 vm_reserv_level_iffullpop(m) == 0) {
7486 pmap_promote_pde(pmap, pde, va, &lock);
7488 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7494 if (ftype == VM_PROT_WRITE)
7495 atomic_add_long(&num_dirty_emulations, 1);
7497 atomic_add_long(&num_accessed_emulations, 1);
7499 rv = 0; /* success */
7508 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7513 pt_entry_t *pte, PG_V;
7517 PG_V = pmap_valid_bit(pmap);
7520 pml4 = pmap_pml4e(pmap, va);
7522 if ((*pml4 & PG_V) == 0)
7525 pdp = pmap_pml4e_to_pdpe(pml4, va);
7527 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7530 pde = pmap_pdpe_to_pde(pdp, va);
7532 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7535 pte = pmap_pde_to_pte(pde, va);
7544 * Get the kernel virtual address of a set of physical pages. If there are
7545 * physical addresses not covered by the DMAP perform a transient mapping
7546 * that will be removed when calling pmap_unmap_io_transient.
7548 * \param page The pages the caller wishes to obtain the virtual
7549 * address on the kernel memory map.
7550 * \param vaddr On return contains the kernel virtual memory address
7551 * of the pages passed in the page parameter.
7552 * \param count Number of pages passed in.
7553 * \param can_fault TRUE if the thread using the mapped pages can take
7554 * page faults, FALSE otherwise.
7556 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7557 * finished or FALSE otherwise.
7561 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7562 boolean_t can_fault)
7565 boolean_t needs_mapping;
7567 int cache_bits, error, i;
7570 * Allocate any KVA space that we need, this is done in a separate
7571 * loop to prevent calling vmem_alloc while pinned.
7573 needs_mapping = FALSE;
7574 for (i = 0; i < count; i++) {
7575 paddr = VM_PAGE_TO_PHYS(page[i]);
7576 if (__predict_false(paddr >= dmaplimit)) {
7577 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7578 M_BESTFIT | M_WAITOK, &vaddr[i]);
7579 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7580 needs_mapping = TRUE;
7582 vaddr[i] = PHYS_TO_DMAP(paddr);
7586 /* Exit early if everything is covered by the DMAP */
7591 * NB: The sequence of updating a page table followed by accesses
7592 * to the corresponding pages used in the !DMAP case is subject to
7593 * the situation described in the "AMD64 Architecture Programmer's
7594 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7595 * Coherency Considerations". Therefore, issuing the INVLPG right
7596 * after modifying the PTE bits is crucial.
7600 for (i = 0; i < count; i++) {
7601 paddr = VM_PAGE_TO_PHYS(page[i]);
7602 if (paddr >= dmaplimit) {
7605 * Slow path, since we can get page faults
7606 * while mappings are active don't pin the
7607 * thread to the CPU and instead add a global
7608 * mapping visible to all CPUs.
7610 pmap_qenter(vaddr[i], &page[i], 1);
7612 pte = vtopte(vaddr[i]);
7613 cache_bits = pmap_cache_bits(kernel_pmap,
7614 page[i]->md.pat_mode, 0);
7615 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7622 return (needs_mapping);
7626 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7627 boolean_t can_fault)
7634 for (i = 0; i < count; i++) {
7635 paddr = VM_PAGE_TO_PHYS(page[i]);
7636 if (paddr >= dmaplimit) {
7638 pmap_qremove(vaddr[i], 1);
7639 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7645 pmap_quick_enter_page(vm_page_t m)
7649 paddr = VM_PAGE_TO_PHYS(m);
7650 if (paddr < dmaplimit)
7651 return (PHYS_TO_DMAP(paddr));
7652 mtx_lock_spin(&qframe_mtx);
7653 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7654 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7655 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7660 pmap_quick_remove_page(vm_offset_t addr)
7665 pte_store(vtopte(qframe), 0);
7667 mtx_unlock_spin(&qframe_mtx);
7671 pmap_pti_alloc_page(void)
7675 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7676 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7677 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7682 pmap_pti_free_page(vm_page_t m)
7685 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7686 if (!vm_page_unwire_noq(m))
7688 vm_page_free_zero(m);
7702 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7703 VM_OBJECT_WLOCK(pti_obj);
7704 pml4_pg = pmap_pti_alloc_page();
7705 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7706 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7707 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7708 pdpe = pmap_pti_pdpe(va);
7709 pmap_pti_wire_pte(pdpe);
7711 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7712 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7713 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7714 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7715 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7716 sizeof(struct gate_descriptor) * NIDT, false);
7717 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7718 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7720 /* Doublefault stack IST 1 */
7721 va = common_tss[i].tss_ist1;
7722 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7723 /* NMI stack IST 2 */
7724 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7725 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7726 /* MC# stack IST 3 */
7727 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7728 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7730 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7731 (vm_offset_t)etext, true);
7732 pti_finalized = true;
7733 VM_OBJECT_WUNLOCK(pti_obj);
7735 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7737 static pdp_entry_t *
7738 pmap_pti_pdpe(vm_offset_t va)
7740 pml4_entry_t *pml4e;
7743 vm_pindex_t pml4_idx;
7746 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7748 pml4_idx = pmap_pml4e_index(va);
7749 pml4e = &pti_pml4[pml4_idx];
7753 panic("pml4 alloc after finalization\n");
7754 m = pmap_pti_alloc_page();
7756 pmap_pti_free_page(m);
7757 mphys = *pml4e & ~PAGE_MASK;
7759 mphys = VM_PAGE_TO_PHYS(m);
7760 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7763 mphys = *pml4e & ~PAGE_MASK;
7765 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7770 pmap_pti_wire_pte(void *pte)
7774 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7775 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7780 pmap_pti_unwire_pde(void *pde, bool only_ref)
7784 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7785 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7786 MPASS(m->wire_count > 0);
7787 MPASS(only_ref || m->wire_count > 1);
7788 pmap_pti_free_page(m);
7792 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7797 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7798 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7799 MPASS(m->wire_count > 0);
7800 if (pmap_pti_free_page(m)) {
7801 pde = pmap_pti_pde(va);
7802 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7804 pmap_pti_unwire_pde(pde, false);
7809 pmap_pti_pde(vm_offset_t va)
7817 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7819 pdpe = pmap_pti_pdpe(va);
7821 m = pmap_pti_alloc_page();
7823 pmap_pti_free_page(m);
7824 MPASS((*pdpe & X86_PG_PS) == 0);
7825 mphys = *pdpe & ~PAGE_MASK;
7827 mphys = VM_PAGE_TO_PHYS(m);
7828 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7831 MPASS((*pdpe & X86_PG_PS) == 0);
7832 mphys = *pdpe & ~PAGE_MASK;
7835 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7836 pd_idx = pmap_pde_index(va);
7842 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7849 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7851 pde = pmap_pti_pde(va);
7852 if (unwire_pde != NULL) {
7854 pmap_pti_wire_pte(pde);
7857 m = pmap_pti_alloc_page();
7859 pmap_pti_free_page(m);
7860 MPASS((*pde & X86_PG_PS) == 0);
7861 mphys = *pde & ~(PAGE_MASK | pg_nx);
7863 mphys = VM_PAGE_TO_PHYS(m);
7864 *pde = mphys | X86_PG_RW | X86_PG_V;
7865 if (unwire_pde != NULL)
7866 *unwire_pde = false;
7869 MPASS((*pde & X86_PG_PS) == 0);
7870 mphys = *pde & ~(PAGE_MASK | pg_nx);
7873 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7874 pte += pmap_pte_index(va);
7880 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7884 pt_entry_t *pte, ptev;
7887 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7889 sva = trunc_page(sva);
7890 MPASS(sva > VM_MAXUSER_ADDRESS);
7891 eva = round_page(eva);
7893 for (; sva < eva; sva += PAGE_SIZE) {
7894 pte = pmap_pti_pte(sva, &unwire_pde);
7895 pa = pmap_kextract(sva);
7896 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
7897 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
7898 VM_MEMATTR_DEFAULT, FALSE);
7900 pte_store(pte, ptev);
7901 pmap_pti_wire_pte(pte);
7903 KASSERT(!pti_finalized,
7904 ("pti overlap after fin %#lx %#lx %#lx",
7906 KASSERT(*pte == ptev,
7907 ("pti non-identical pte after fin %#lx %#lx %#lx",
7911 pde = pmap_pti_pde(sva);
7912 pmap_pti_unwire_pde(pde, true);
7918 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
7923 VM_OBJECT_WLOCK(pti_obj);
7924 pmap_pti_add_kva_locked(sva, eva, exec);
7925 VM_OBJECT_WUNLOCK(pti_obj);
7929 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
7936 sva = rounddown2(sva, PAGE_SIZE);
7937 MPASS(sva > VM_MAXUSER_ADDRESS);
7938 eva = roundup2(eva, PAGE_SIZE);
7940 VM_OBJECT_WLOCK(pti_obj);
7941 for (va = sva; va < eva; va += PAGE_SIZE) {
7942 pte = pmap_pti_pte(va, NULL);
7943 KASSERT((*pte & X86_PG_V) != 0,
7944 ("invalid pte va %#lx pte %#lx pt %#lx", va,
7945 (u_long)pte, *pte));
7947 pmap_pti_unwire_pte(pte, va);
7949 pmap_invalidate_range(kernel_pmap, sva, eva);
7950 VM_OBJECT_WUNLOCK(pti_obj);
7953 #include "opt_ddb.h"
7955 #include <sys/kdb.h>
7956 #include <ddb/ddb.h>
7958 DB_SHOW_COMMAND(pte, pmap_print_pte)
7964 pt_entry_t *pte, PG_V;
7968 db_printf("show pte addr\n");
7971 va = (vm_offset_t)addr;
7973 if (kdb_thread != NULL)
7974 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
7976 pmap = PCPU_GET(curpmap);
7978 PG_V = pmap_valid_bit(pmap);
7979 pml4 = pmap_pml4e(pmap, va);
7980 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7981 if ((*pml4 & PG_V) == 0) {
7985 pdp = pmap_pml4e_to_pdpe(pml4, va);
7986 db_printf(" pdpe %#016lx", *pdp);
7987 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7991 pde = pmap_pdpe_to_pde(pdp, va);
7992 db_printf(" pde %#016lx", *pde);
7993 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7997 pte = pmap_pde_to_pte(pde, va);
7998 db_printf(" pte %#016lx\n", *pte);
8001 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8006 a = (vm_paddr_t)addr;
8007 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8009 db_printf("show phys2dmap addr\n");